Skip to content

DELETE license API endpoint #3697

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 48 additions & 38 deletions coderd/coderdtest/authtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package coderdtest

import (
"context"
"fmt"
"io"
"net/http"
"strconv"
Expand Down Expand Up @@ -43,6 +44,7 @@ type AuthTester struct {
File codersdk.UploadResponse
TemplateVersionDryRun codersdk.ProvisionerJob
TemplateParam codersdk.Parameter
URLParams map[string]string
}

func NewAuthTester(ctx context.Context, t *testing.T, options *Options) *AuthTester {
Expand Down Expand Up @@ -86,7 +88,7 @@ func NewAuthTester(ctx context.Context, t *testing.T, options *Options) *AuthTes
Id: "something",
Auth: &proto.Agent_Token{},
Apps: []*proto.App{{
Name: "app",
Name: "testapp",
Url: "http://localhost:3000",
}},
}},
Expand Down Expand Up @@ -116,6 +118,28 @@ func NewAuthTester(ctx context.Context, t *testing.T, options *Options) *AuthTes
})
require.NoError(t, err, "create template param")

urlParameters := map[string]string{
"{organization}": admin.OrganizationID.String(),
"{user}": admin.UserID.String(),
"{organizationname}": organization.Name,
"{workspace}": workspace.ID.String(),
"{workspacebuild}": workspace.LatestBuild.ID.String(),
"{workspacename}": workspace.Name,
"{workspacebuildname}": workspace.LatestBuild.Name,
"{workspaceagent}": workspaceResources[0].Agents[0].ID.String(),
"{buildnumber}": strconv.FormatInt(int64(workspace.LatestBuild.BuildNumber), 10),
"{template}": template.ID.String(),
"{hash}": file.Hash,
"{workspaceresource}": workspaceResources[0].ID.String(),
"{workspaceapp}": workspaceResources[0].Agents[0].Apps[0].Name,
"{templateversion}": version.ID.String(),
"{jobID}": templateVersionDryRun.ID.String(),
"{templatename}": template.Name,
// Only checking template scoped params here
"parameters/{scope}/{id}": fmt.Sprintf("parameters/%s/%s",
string(templateParam.Scope), templateParam.ScopeID.String()),
}
Comment on lines +121 to +141
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍


return &AuthTester{
t: t,
api: api,
Expand All @@ -130,6 +154,7 @@ func NewAuthTester(ctx context.Context, t *testing.T, options *Options) *AuthTes
File: file,
TemplateVersionDryRun: templateVersionDryRun,
TemplateParam: templateParam,
URLParams: urlParameters,
}
}

Expand All @@ -153,13 +178,13 @@ func AGPLRoutes(a *AuthTester) (map[string]string, map[string]RouteCheck) {
"POST:/api/v2/csp/reports": {NoAuthorize: true},
"GET:/api/v2/entitlements": {NoAuthorize: true},

"GET:/%40{user}/{workspacename}/apps/{application}/*": {
AssertAction: rbac.ActionRead,
AssertObject: workspaceRBACObj,
"GET:/%40{user}/{workspacename}/apps/{workspaceapp}/*": {
AssertAction: rbac.ActionCreate,
AssertObject: workspaceExecObj,
},
"GET:/@{user}/{workspacename}/apps/{application}/*": {
AssertAction: rbac.ActionRead,
AssertObject: workspaceRBACObj,
"GET:/@{user}/{workspacename}/apps/{workspaceapp}/*": {
AssertAction: rbac.ActionCreate,
AssertObject: workspaceExecObj,
},

// Has it's own auth
Expand Down Expand Up @@ -188,7 +213,7 @@ func AGPLRoutes(a *AuthTester) (map[string]string, map[string]RouteCheck) {
AssertObject: rbac.ResourceWorkspace,
AssertAction: rbac.ActionRead,
},
"GET:/api/v2/users/me/workspace/{workspacename}/builds/{buildnumber}": {
"GET:/api/v2/users/{user}/workspace/{workspacename}/builds/{buildnumber}": {
AssertObject: rbac.ResourceWorkspace,
AssertAction: rbac.ActionRead,
},
Expand Down Expand Up @@ -216,7 +241,7 @@ func AGPLRoutes(a *AuthTester) (map[string]string, map[string]RouteCheck) {
AssertAction: rbac.ActionUpdate,
AssertObject: workspaceRBACObj,
},
"PUT:/api/v2/workspaces/{workspace}/autostop": {
"PUT:/api/v2/workspaces/{workspace}/ttl": {
AssertAction: rbac.ActionUpdate,
AssertObject: workspaceRBACObj,
},
Expand Down Expand Up @@ -275,7 +300,7 @@ func AGPLRoutes(a *AuthTester) (map[string]string, map[string]RouteCheck) {
AssertObject: rbac.ResourceTemplate.InOrg(a.Template.OrganizationID),
},
"POST:/api/v2/files": {AssertAction: rbac.ActionCreate, AssertObject: rbac.ResourceFile},
"GET:/api/v2/files/{fileHash}": {
"GET:/api/v2/files/{hash}": {
AssertAction: rbac.ActionRead,
AssertObject: rbac.ResourceFile.WithOwner(a.Admin.UserID.String()),
},
Expand Down Expand Up @@ -320,19 +345,19 @@ func AGPLRoutes(a *AuthTester) (map[string]string, map[string]RouteCheck) {
AssertAction: rbac.ActionRead,
AssertObject: rbac.ResourceTemplate.InOrg(a.Version.OrganizationID),
},
"GET:/api/v2/templateversions/{templateversion}/dry-run/{templateversiondryrun}": {
"GET:/api/v2/templateversions/{templateversion}/dry-run/{jobID}": {
AssertAction: rbac.ActionRead,
AssertObject: rbac.ResourceTemplate.InOrg(a.Version.OrganizationID),
},
"GET:/api/v2/templateversions/{templateversion}/dry-run/{templateversiondryrun}/resources": {
"GET:/api/v2/templateversions/{templateversion}/dry-run/{jobID}/resources": {
AssertAction: rbac.ActionRead,
AssertObject: rbac.ResourceTemplate.InOrg(a.Version.OrganizationID),
},
"GET:/api/v2/templateversions/{templateversion}/dry-run/{templateversiondryrun}/logs": {
"GET:/api/v2/templateversions/{templateversion}/dry-run/{jobID}/logs": {
AssertAction: rbac.ActionRead,
AssertObject: rbac.ResourceTemplate.InOrg(a.Version.OrganizationID),
},
"PATCH:/api/v2/templateversions/{templateversion}/dry-run/{templateversiondryrun}/cancel": {
"PATCH:/api/v2/templateversions/{templateversion}/dry-run/{jobID}/cancel": {
AssertAction: rbac.ActionRead,
AssertObject: rbac.ResourceTemplate.InOrg(a.Version.OrganizationID),
},
Expand Down Expand Up @@ -366,10 +391,6 @@ func AGPLRoutes(a *AuthTester) (map[string]string, map[string]RouteCheck) {
AssertAction: rbac.ActionRead,
AssertObject: workspaceRBACObj,
},
"POST:/api/v2/users/{user}/organizations": {
AssertAction: rbac.ActionCreate,
AssertObject: rbac.ResourceOrganization,
},
"GET:/api/v2/users": {StatusCode: http.StatusOK, AssertObject: rbac.ResourceUser},

// These endpoints need payloads to get to the auth part. Payloads will be required
Expand All @@ -385,13 +406,15 @@ func (a *AuthTester) Test(ctx context.Context, assertRoute map[string]RouteCheck
// Always fail auth from this point forward
a.authorizer.AlwaysReturn = rbac.ForbiddenWithInternal(xerrors.New("fake implementation"), nil, nil)

routeMissing := make(map[string]bool)
for k, v := range assertRoute {
noTrailSlash := strings.TrimRight(k, "/")
if _, ok := assertRoute[noTrailSlash]; ok && noTrailSlash != k {
a.t.Errorf("route %q & %q is declared twice", noTrailSlash, k)
a.t.FailNow()
}
assertRoute[noTrailSlash] = v
routeMissing[noTrailSlash] = true
}

for k, v := range skipRoutes {
Expand Down Expand Up @@ -422,32 +445,18 @@ func (a *AuthTester) Test(ctx context.Context, assertRoute map[string]RouteCheck
}
a.t.Run(name, func(t *testing.T) {
a.authorizer.reset()
routeAssertions, ok := assertRoute[strings.TrimRight(name, "/")]
routeKey := strings.TrimRight(name, "/")
routeAssertions, ok := assertRoute[routeKey]
if !ok {
// By default, all omitted routes check for just "authorize" called
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need to drop this comment then? This was initially done because I was lazy, but I totally see how it allowed some routes to drift 🤦‍♂️

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still think it's fine for routes in the walk not to be in assertRoute and us just check that auth is called.

The issue is that there were entries in the assertRoute that were not present in the walk. Those entries asserted particular RBAC actions and objects, but because the routes were misspelled, the assertions were never checked.

routeAssertions = RouteCheck{}
}
delete(routeMissing, routeKey)

// Replace all url params with known values
route = strings.ReplaceAll(route, "{organization}", a.Admin.OrganizationID.String())
route = strings.ReplaceAll(route, "{user}", a.Admin.UserID.String())
route = strings.ReplaceAll(route, "{organizationname}", a.Organization.Name)
route = strings.ReplaceAll(route, "{workspace}", a.Workspace.ID.String())
route = strings.ReplaceAll(route, "{workspacebuild}", a.Workspace.LatestBuild.ID.String())
route = strings.ReplaceAll(route, "{workspacename}", a.Workspace.Name)
route = strings.ReplaceAll(route, "{workspacebuildname}", a.Workspace.LatestBuild.Name)
route = strings.ReplaceAll(route, "{workspaceagent}", a.WorkspaceResource.Agents[0].ID.String())
route = strings.ReplaceAll(route, "{buildnumber}", strconv.FormatInt(int64(a.Workspace.LatestBuild.BuildNumber), 10))
route = strings.ReplaceAll(route, "{template}", a.Template.ID.String())
route = strings.ReplaceAll(route, "{hash}", a.File.Hash)
route = strings.ReplaceAll(route, "{workspaceresource}", a.WorkspaceResource.ID.String())
route = strings.ReplaceAll(route, "{workspaceapp}", a.WorkspaceResource.Agents[0].Apps[0].Name)
route = strings.ReplaceAll(route, "{templateversion}", a.Version.ID.String())
route = strings.ReplaceAll(route, "{templateversiondryrun}", a.TemplateVersionDryRun.ID.String())
route = strings.ReplaceAll(route, "{templatename}", a.Template.Name)
// Only checking template scoped params here
route = strings.ReplaceAll(route, "{scope}", string(a.TemplateParam.Scope))
route = strings.ReplaceAll(route, "{id}", a.TemplateParam.ScopeID.String())
for k, v := range a.URLParams {
route = strings.ReplaceAll(route, k, v)
}

resp, err := a.Client.Request(ctx, method, route, nil)
require.NoError(t, err, "do req")
Expand Down Expand Up @@ -486,6 +495,7 @@ func (a *AuthTester) Test(ctx context.Context, assertRoute map[string]RouteCheck
return nil
})
require.NoError(a.t, err)
require.Len(a.t, routeMissing, 0, "didn't walk some asserted routes: %v", routeMissing)
}

type authCall struct {
Expand Down
14 changes: 14 additions & 0 deletions coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -2301,6 +2301,20 @@ func (q *fakeQuerier) GetLicenses(_ context.Context) ([]database.License, error)
return results, nil
}

func (q *fakeQuerier) DeleteLicense(_ context.Context, id int32) (int32, error) {
q.mutex.Lock()
defer q.mutex.Unlock()

for index, l := range q.licenses {
if l.ID == id {
q.licenses[index] = q.licenses[len(q.licenses)-1]
q.licenses = q.licenses[:len(q.licenses)-1]
return id, nil
}
}
return 0, sql.ErrNoRows
}

func (q *fakeQuerier) GetUserLinkByLinkedID(_ context.Context, id string) (database.UserLink, error) {
q.mutex.RLock()
defer q.mutex.RUnlock()
Expand Down
1 change: 1 addition & 0 deletions coderd/database/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion coderd/database/queries/licenses.sql
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@ INSERT INTO
VALUES
($1, $2, $3) RETURNING *;


-- name: GetLicenses :many
SELECT *
FROM licenses
ORDER BY (id);

-- name: DeleteLicense :one
DELETE
FROM licenses
WHERE id = $1
RETURNING id;
13 changes: 13 additions & 0 deletions codersdk/licenses.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package codersdk
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
Expand Down Expand Up @@ -50,3 +51,15 @@ func (c *Client) Licenses(ctx context.Context) ([]License, error) {
d.UseNumber()
return licenses, d.Decode(&licenses)
}

func (c *Client) DeleteLicense(ctx context.Context, id int32) error {
res, err := c.Request(ctx, http.MethodDelete, fmt.Sprintf("/api/v2/licenses/%d", id), nil)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return readBodyAsError(res)
}
return nil
}
8 changes: 7 additions & 1 deletion enterprise/coderd/auth_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"crypto/ed25519"
"crypto/rand"
"fmt"
"net/http"
"testing"
"time"
Expand Down Expand Up @@ -55,10 +56,11 @@ func TestAuthorizeAllEndpoints(t *testing.T) {
}
lic, err := makeLicense(claims, privKey, keyID)
require.NoError(t, err)
_, err = a.Client.AddLicense(ctx, codersdk.AddLicenseRequest{
license, err := a.Client.AddLicense(ctx, codersdk.AddLicenseRequest{
License: lic,
})
require.NoError(t, err)
a.URLParams["licenses/{id}"] = fmt.Sprintf("licenses/%d", license.ID)

skipRoutes, assertRoute := coderdtest.AGPLRoutes(a)
assertRoute["POST:/api/v2/licenses"] = coderdtest.RouteCheck{
Expand All @@ -70,5 +72,9 @@ func TestAuthorizeAllEndpoints(t *testing.T) {
AssertAction: rbac.ActionRead,
AssertObject: rbac.ResourceLicense,
}
assertRoute["DELETE:/api/v2/licenses/{id}"] = coderdtest.RouteCheck{
AssertAction: rbac.ActionDelete,
AssertObject: rbac.ResourceLicense,
}
a.Test(ctx, assertRoute, skipRoutes)
}
Loading