Skip to content

chore: implement audit log for custom role edits #13494

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 6 commits into from
Jun 7, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
chore: implement audit log for custom role edits
  • Loading branch information
Emyrk committed Jun 7, 2024
commit 05ce32c032eb9a8aee81ab4746b647e58e173d4d
3 changes: 2 additions & 1 deletion coderd/audit/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ type Auditable interface {
database.AuditOAuthConvertState |
database.HealthSettings |
database.OAuth2ProviderApp |
database.OAuth2ProviderAppSecret
database.OAuth2ProviderAppSecret |
database.CustomRole
}

// Map is a map of changed fields in an audited resource. It maps field names to
Expand Down
8 changes: 8 additions & 0 deletions coderd/audit/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ func ResourceTarget[T Auditable](tgt T) string {
return typed.Name
case database.OAuth2ProviderAppSecret:
return typed.DisplaySecret
case database.CustomRole:
return typed.Name
default:
panic(fmt.Sprintf("unknown resource %T for ResourceTarget", tgt))
}
Expand Down Expand Up @@ -140,6 +142,8 @@ func ResourceID[T Auditable](tgt T) uuid.UUID {
return typed.ID
case database.OAuth2ProviderAppSecret:
return typed.ID
case database.CustomRole:
return typed.ID
default:
panic(fmt.Sprintf("unknown resource %T for ResourceID", tgt))
}
Expand Down Expand Up @@ -175,6 +179,8 @@ func ResourceType[T Auditable](tgt T) database.ResourceType {
return database.ResourceTypeOauth2ProviderApp
case database.OAuth2ProviderAppSecret:
return database.ResourceTypeOauth2ProviderAppSecret
case database.CustomRole:
return database.ResourceTypeCustomRole
default:
panic(fmt.Sprintf("unknown resource %T for ResourceType", typed))
}
Expand Down Expand Up @@ -211,6 +217,8 @@ func ResourceRequiresOrgID[T Auditable]() bool {
return false
case database.OAuth2ProviderAppSecret:
return false
case database.CustomRole:
return true
default:
panic(fmt.Sprintf("unknown resource %T for ResourceRequiresOrgID", tgt))
}
Expand Down
2 changes: 2 additions & 0 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -758,6 +758,8 @@ func createAnotherUserRetry(t testing.TB, client *codersdk.Client, organizationI
roleName, _, err = rbac.RoleSplit(roleName)
require.NoError(t, err, "split org role name")
if ok {
roleName, _, err = rbac.RoleSplit(roleName)
require.NoError(t, err, "split rolename")
orgRoles[orgID] = append(orgRoles[orgID], roleName)
} else {
siteRoles = append(siteRoles, roleName)
Expand Down
1 change: 0 additions & 1 deletion coderd/database/dbauthz/customroles_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,6 @@ func TestUpsertCustomRoles(t *testing.T) {
} else {
require.NoError(t, err)

// Verify we can fetch the role
roles, err := az.CustomRoles(ctx, database.CustomRolesParams{
LookupRoles: []database.NameOrganizationPair{
{
Expand Down
1 change: 1 addition & 0 deletions coderd/database/dbmem/dbmem.go
Original file line number Diff line number Diff line change
Expand Up @@ -8415,6 +8415,7 @@ func (q *FakeQuerier) UpsertCustomRole(_ context.Context, arg database.UpsertCus
}

role := database.CustomRole{
ID: uuid.New(),
Name: arg.Name,
DisplayName: arg.DisplayName,
OrganizationID: arg.OrganizationID,
Expand Down
8 changes: 6 additions & 2 deletions coderd/database/dump.sql

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
DROP INDEX idx_custom_roles_id;
ALTER TABLE custom_roles DROP COLUMN id;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
-- A role does not need to belong to an organization
ALTER TABLE custom_roles ALTER COLUMN organization_id DROP NOT NULL;

-- (name) is the primary key, this column is almost exclusively for auditing.
ALTER TABLE custom_roles ADD COLUMN id uuid DEFAULT gen_random_uuid() NOT NULL;

-- Ensure unique uuids.
CREATE INDEX idx_custom_roles_id ON custom_roles (id);
ALTER TYPE resource_type ADD VALUE IF NOT EXISTS 'custom_role';
6 changes: 5 additions & 1 deletion coderd/database/models.go

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

6 changes: 4 additions & 2 deletions coderd/database/queries.sql.go

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

6 changes: 3 additions & 3 deletions coderd/roles.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ import (
// roles. Ideally only included in the enterprise package, but the routes are
// intermixed with AGPL endpoints.
type CustomRoleHandler interface {
PatchOrganizationRole(ctx context.Context, db database.Store, rw http.ResponseWriter, orgID uuid.UUID, role codersdk.Role) (codersdk.Role, bool)
PatchOrganizationRole(ctx context.Context, rw http.ResponseWriter, r *http.Request, orgID uuid.UUID, role codersdk.Role) (codersdk.Role, bool)
}

type agplCustomRoleHandler struct{}

func (agplCustomRoleHandler) PatchOrganizationRole(ctx context.Context, _ database.Store, rw http.ResponseWriter, _ uuid.UUID, _ codersdk.Role) (codersdk.Role, bool) {
func (agplCustomRoleHandler) PatchOrganizationRole(ctx context.Context, rw http.ResponseWriter, _ *http.Request, _ uuid.UUID, _ codersdk.Role) (codersdk.Role, bool) {
httpapi.Write(ctx, rw, http.StatusForbidden, codersdk.Response{
Message: "Creating and updating custom roles is an Enterprise feature. Contact sales!",
})
Expand Down Expand Up @@ -54,7 +54,7 @@ func (api *API) patchOrgRoles(rw http.ResponseWriter, r *http.Request) {
return
}

updated, ok := handler.PatchOrganizationRole(ctx, api.Database, rw, organization.ID, req)
updated, ok := handler.PatchOrganizationRole(ctx, rw, r, organization.ID, req)
if !ok {
return
}
Expand Down
3 changes: 3 additions & 0 deletions codersdk/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const (
ResourceTypeOAuth2ProviderApp ResourceType = "oauth2_provider_app"
// nolint:gosec // This is not a secret.
ResourceTypeOAuth2ProviderAppSecret ResourceType = "oauth2_provider_app_secret"
ResourceTypeCustomRole ResourceType = "custom_role"
)

func (r ResourceType) FriendlyString() string {
Expand Down Expand Up @@ -66,6 +67,8 @@ func (r ResourceType) FriendlyString() string {
return "oauth2 app"
case ResourceTypeOAuth2ProviderAppSecret:
return "oauth2 app secret"
case ResourceTypeCustomRole:
return "custom role"
default:
return "unknown"
}
Expand Down
13 changes: 13 additions & 0 deletions enterprise/audit/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,19 @@ func convertDiffType(left, right any) (newLeft, newRight any, changed bool) {
return leftInt64Ptr, rightInt64Ptr, true
case database.TemplateACL:
return fmt.Sprintf("%+v", left), fmt.Sprintf("%+v", right), true
case database.CustomRolePermissions:
leftArr := make([]string, 0)
rightArr := make([]string, 0)
for _, p := range typedLeft {
leftArr = append(leftArr, p.String())
}
for _, p := range right.(database.CustomRolePermissions) {
rightArr = append(rightArr, p.String())
}

// String representation is much easier to visually inspect
//typedRight := right.(database.CustomRolePermission)
return leftArr, rightArr, true
default:
return left, right, false
}
Expand Down
12 changes: 12 additions & 0 deletions enterprise/audit/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,18 @@ type Table map[string]map[string]Action
var AuditableResources = auditMap(auditableResourcesTypes)

var auditableResourcesTypes = map[any]map[string]Action{
&database.CustomRole{}: {
"name": ActionTrack,
"display_name": ActionTrack,
"site_permissions": ActionTrack,
"org_permissions": ActionTrack,
"user_permissions": ActionTrack,
"organization_id": ActionTrack,

"id": ActionIgnore,
"created_at": ActionIgnore,
"updated_at": ActionIgnore,
},
&database.GitSSHKey{}: {
"user_id": ActionTrack,
"created_at": ActionIgnore, // Never changes, but is implicit and not helpful in a diff.
Expand Down
2 changes: 1 addition & 1 deletion enterprise/coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -746,7 +746,7 @@ func (api *API) updateEntitlements(ctx context.Context) error {
}

if initial, changed, enabled := featureChanged(codersdk.FeatureCustomRoles); shouldUpdate(initial, changed, enabled) {
var handler coderd.CustomRoleHandler = &enterpriseCustomRoleHandler{Enabled: enabled}
var handler coderd.CustomRoleHandler = &enterpriseCustomRoleHandler{API: api, Enabled: enabled}
api.AGPL.CustomRoleHandler.Store(&handler)
}

Expand Down
38 changes: 37 additions & 1 deletion enterprise/coderd/roles.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/google/uuid"

"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/db2sdk"
"github.com/coder/coder/v2/coderd/httpapi"
Expand All @@ -15,17 +16,31 @@ import (
)

type enterpriseCustomRoleHandler struct {
API *API
Enabled bool
}

func (h enterpriseCustomRoleHandler) PatchOrganizationRole(ctx context.Context, db database.Store, rw http.ResponseWriter, orgID uuid.UUID, role codersdk.Role) (codersdk.Role, bool) {
func (h enterpriseCustomRoleHandler) PatchOrganizationRole(ctx context.Context, rw http.ResponseWriter, r *http.Request, orgID uuid.UUID, role codersdk.Role) (codersdk.Role, bool) {
if !h.Enabled {
httpapi.Write(ctx, rw, http.StatusForbidden, codersdk.Response{
Message: "Custom roles are not enabled",
})
return codersdk.Role{}, false
}

var (
db = h.API.Database
auditor = h.API.AGPL.Auditor.Load()
aReq, commitAudit = audit.InitRequest[database.CustomRole](rw, &audit.RequestParams{
Audit: *auditor,
Log: h.API.Logger,
Request: r,
Action: database.AuditActionWrite,
OrganizationID: orgID,
})
)
defer commitAudit()

if err := httpapi.NameValid(role.Name); err != nil {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: "Invalid role name",
Expand Down Expand Up @@ -59,6 +74,26 @@ func (h enterpriseCustomRoleHandler) PatchOrganizationRole(ctx context.Context,
return codersdk.Role{}, false
}

originalRoles, err := db.CustomRoles(ctx, database.CustomRolesParams{
LookupRoles: []database.NameOrganizationPair{
{
Name: role.Name,
OrganizationID: orgID,
},
},
ExcludeOrgRoles: false,
OrganizationID: orgID,
})
// If it is a 404 (not found) error, ignore it.
if err != nil && !httpapi.Is404Error(err) {
httpapi.InternalServerError(rw, err)
return codersdk.Role{}, false
}
if len(originalRoles) == 1 {
// For auditing changes to a role.
aReq.Old = originalRoles[0]
}

inserted, err := db.UpsertCustomRole(ctx, database.UpsertCustomRoleParams{
Name: role.Name,
DisplayName: role.DisplayName,
Expand All @@ -81,6 +116,7 @@ func (h enterpriseCustomRoleHandler) PatchOrganizationRole(ctx context.Context,
})
return codersdk.Role{}, false
}
aReq.New = inserted

return db2sdk.Role(inserted), true
}
Expand Down
2 changes: 2 additions & 0 deletions site/src/api/typesGenerated.ts

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