diff --git a/coderd/apidoc/docs.go b/coderd/apidoc/docs.go index d971f87b50a..e8ea098badb 100644 --- a/coderd/apidoc/docs.go +++ b/coderd/apidoc/docs.go @@ -1337,6 +1337,188 @@ const docTemplate = `{ } } }, + "/api/experimental/organizations/{organization}/members/{user}/skill-preferences": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "Organizations" + ], + "summary": "Get organization skill preferences for a member", + "operationId": "get-organization-skill-preferences-for-a-member", + "parameters": [ + { + "type": "string", + "description": "Organization ID or name", + "name": "organization", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "User ID, name, or me", + "name": "user", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/codersdk.OrganizationSkillPreferences" + } + } + }, + "security": [ + { + "CoderSessionToken": [] + } + ], + "x-apidocgen": { + "skip": true + } + }, + "patch": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Organizations" + ], + "summary": "Update organization skill preferences for a member", + "operationId": "update-organization-skill-preferences-for-a-member", + "parameters": [ + { + "type": "string", + "description": "Organization ID or name", + "name": "organization", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "User ID, name, or me", + "name": "user", + "in": "path", + "required": true + }, + { + "description": "Update organization skill preferences request", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/codersdk.UpdateOrganizationSkillPreferencesRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/codersdk.OrganizationSkillPreferences" + } + } + }, + "security": [ + { + "CoderSessionToken": [] + } + ], + "x-apidocgen": { + "skip": true + } + } + }, + "/api/experimental/organizations/{organization}/skill-settings": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "Organizations" + ], + "summary": "Get organization skill settings", + "operationId": "get-organization-skill-settings", + "parameters": [ + { + "type": "string", + "description": "Organization ID or name", + "name": "organization", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/codersdk.OrganizationSkillSettings" + } + } + }, + "security": [ + { + "CoderSessionToken": [] + } + ], + "x-apidocgen": { + "skip": true + } + }, + "put": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Organizations" + ], + "summary": "Update organization skill settings", + "operationId": "update-organization-skill-settings", + "parameters": [ + { + "type": "string", + "description": "Organization ID or name", + "name": "organization", + "in": "path", + "required": true + }, + { + "description": "Update organization skill settings request", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/codersdk.UpdateOrganizationSkillSettingsRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/codersdk.OrganizationSkillSettings" + } + } + }, + "security": [ + { + "CoderSessionToken": [] + } + ], + "x-apidocgen": { + "skip": true + } + } + }, "/api/experimental/organizations/{organization}/skills": { "get": { "produces": [ @@ -28947,6 +29129,27 @@ const docTemplate = `{ } } }, + "codersdk.OrganizationSkillPreferences": { + "type": "object", + "properties": { + "all_skills_disabled": { + "description": "AllSkillsDisabled turns off every organization skill, including\nskills added later. DisabledSkillIDs is kept and applies again when it\nis false.", + "type": "boolean" + }, + "disabled_skill_ids": { + "description": "DisabledSkillIDs lists the organization skills the member turned off.", + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + }, + "members_can_disable_skills": { + "description": "MembersCanDisableSkills is the organization's setting.", + "type": "boolean" + } + } + }, "codersdk.OrganizationSkillRole": { "type": "string", "enum": [ @@ -28958,6 +29161,15 @@ const docTemplate = `{ "OrganizationSkillRoleDeleted" ] }, + "codersdk.OrganizationSkillSettings": { + "type": "object", + "properties": { + "members_can_disable_skills": { + "description": "MembersCanDisableSkills lets each organization member turn off\norganization skills for their own chats.", + "type": "boolean" + } + } + }, "codersdk.OrganizationSkillUser": { "type": "object", "required": [ @@ -32914,6 +33126,29 @@ const docTemplate = `{ } } }, + "codersdk.UpdateOrganizationSkillPreferencesRequest": { + "type": "object", + "properties": { + "all_skills_disabled": { + "type": "boolean" + }, + "skills": { + "description": "Skills maps an organization skill ID to whether the skill is enabled\nfor the member's chats.", + "type": "object", + "additionalProperties": { + "type": "boolean" + } + } + } + }, + "codersdk.UpdateOrganizationSkillSettingsRequest": { + "type": "object", + "properties": { + "members_can_disable_skills": { + "type": "boolean" + } + } + }, "codersdk.UpdateRoles": { "type": "object", "properties": { diff --git a/coderd/apidoc/swagger.json b/coderd/apidoc/swagger.json index d9268b9c8f3..cec1536a2c9 100644 --- a/coderd/apidoc/swagger.json +++ b/coderd/apidoc/swagger.json @@ -1208,6 +1208,168 @@ } } }, + "/api/experimental/organizations/{organization}/members/{user}/skill-preferences": { + "get": { + "produces": ["application/json"], + "tags": ["Organizations"], + "summary": "Get organization skill preferences for a member", + "operationId": "get-organization-skill-preferences-for-a-member", + "parameters": [ + { + "type": "string", + "description": "Organization ID or name", + "name": "organization", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "User ID, name, or me", + "name": "user", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/codersdk.OrganizationSkillPreferences" + } + } + }, + "security": [ + { + "CoderSessionToken": [] + } + ], + "x-apidocgen": { + "skip": true + } + }, + "patch": { + "consumes": ["application/json"], + "produces": ["application/json"], + "tags": ["Organizations"], + "summary": "Update organization skill preferences for a member", + "operationId": "update-organization-skill-preferences-for-a-member", + "parameters": [ + { + "type": "string", + "description": "Organization ID or name", + "name": "organization", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "User ID, name, or me", + "name": "user", + "in": "path", + "required": true + }, + { + "description": "Update organization skill preferences request", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/codersdk.UpdateOrganizationSkillPreferencesRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/codersdk.OrganizationSkillPreferences" + } + } + }, + "security": [ + { + "CoderSessionToken": [] + } + ], + "x-apidocgen": { + "skip": true + } + } + }, + "/api/experimental/organizations/{organization}/skill-settings": { + "get": { + "produces": ["application/json"], + "tags": ["Organizations"], + "summary": "Get organization skill settings", + "operationId": "get-organization-skill-settings", + "parameters": [ + { + "type": "string", + "description": "Organization ID or name", + "name": "organization", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/codersdk.OrganizationSkillSettings" + } + } + }, + "security": [ + { + "CoderSessionToken": [] + } + ], + "x-apidocgen": { + "skip": true + } + }, + "put": { + "consumes": ["application/json"], + "produces": ["application/json"], + "tags": ["Organizations"], + "summary": "Update organization skill settings", + "operationId": "update-organization-skill-settings", + "parameters": [ + { + "type": "string", + "description": "Organization ID or name", + "name": "organization", + "in": "path", + "required": true + }, + { + "description": "Update organization skill settings request", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/codersdk.UpdateOrganizationSkillSettingsRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/codersdk.OrganizationSkillSettings" + } + } + }, + "security": [ + { + "CoderSessionToken": [] + } + ], + "x-apidocgen": { + "skip": true + } + } + }, "/api/experimental/organizations/{organization}/skills": { "get": { "produces": ["application/json"], @@ -26554,6 +26716,27 @@ } } }, + "codersdk.OrganizationSkillPreferences": { + "type": "object", + "properties": { + "all_skills_disabled": { + "description": "AllSkillsDisabled turns off every organization skill, including\nskills added later. DisabledSkillIDs is kept and applies again when it\nis false.", + "type": "boolean" + }, + "disabled_skill_ids": { + "description": "DisabledSkillIDs lists the organization skills the member turned off.", + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + }, + "members_can_disable_skills": { + "description": "MembersCanDisableSkills is the organization's setting.", + "type": "boolean" + } + } + }, "codersdk.OrganizationSkillRole": { "type": "string", "enum": ["read", ""], @@ -26562,6 +26745,15 @@ "OrganizationSkillRoleDeleted" ] }, + "codersdk.OrganizationSkillSettings": { + "type": "object", + "properties": { + "members_can_disable_skills": { + "description": "MembersCanDisableSkills lets each organization member turn off\norganization skills for their own chats.", + "type": "boolean" + } + } + }, "codersdk.OrganizationSkillUser": { "type": "object", "required": ["id", "username"], @@ -30349,6 +30541,29 @@ } } }, + "codersdk.UpdateOrganizationSkillPreferencesRequest": { + "type": "object", + "properties": { + "all_skills_disabled": { + "type": "boolean" + }, + "skills": { + "description": "Skills maps an organization skill ID to whether the skill is enabled\nfor the member's chats.", + "type": "object", + "additionalProperties": { + "type": "boolean" + } + } + } + }, + "codersdk.UpdateOrganizationSkillSettingsRequest": { + "type": "object", + "properties": { + "members_can_disable_skills": { + "type": "boolean" + } + } + }, "codersdk.UpdateRoles": { "type": "object", "properties": { diff --git a/coderd/coderd.go b/coderd/coderd.go index f08279cbc3a..9c460b31d40 100644 --- a/coderd/coderd.go +++ b/coderd/coderd.go @@ -1399,6 +1399,16 @@ func New(options *Options) *API { httpmw.ExtractOrganizationParam(options.Database), ) api.registerExperimentalOrganizationChatRoutes(r) + // These stay outside /skills, where {skillName} would capture them. + r.Route("/skill-settings", func(r chi.Router) { + r.Get("/", api.getOrganizationSkillSettings) + r.Put("/", api.putOrganizationSkillSettings) + }) + r.Route("/members/{user}/skill-preferences", func(r chi.Router) { + r.Use(httpmw.ExtractOrganizationMemberParam(options.Database)) + r.Get("/", api.getOrganizationSkillPreferences) + r.Patch("/", api.patchOrganizationSkillPreferences) + }) }) r.Route("/mcp", func(r chi.Router) { diff --git a/coderd/database/dbauthz/dbauthz.go b/coderd/database/dbauthz/dbauthz.go index 0a4cef25c36..1a654db266e 100644 --- a/coderd/database/dbauthz/dbauthz.go +++ b/coderd/database/dbauthz/dbauthz.go @@ -2680,6 +2680,13 @@ func (q *querier) DeleteOrganizationMember(ctx context.Context, arg database.Del }, q.db.DeleteOrganizationMember)(ctx, arg) } +func (q *querier) DeleteOrganizationMemberDisabledSkill(ctx context.Context, arg database.DeleteOrganizationMemberDisabledSkillParams) error { + if err := q.authorizeContext(ctx, policy.ActionUpdatePersonal, rbac.ResourceUserObject(arg.UserID)); err != nil { + return err + } + return q.db.DeleteOrganizationMemberDisabledSkill(ctx, arg) +} + func (q *querier) DeleteOrganizationSkillByOrganizationIDAndName(ctx context.Context, arg database.DeleteOrganizationSkillByOrganizationIDAndNameParams) (database.Skill, error) { fetch := func(ctx context.Context, arg database.DeleteOrganizationSkillByOrganizationIDAndNameParams) (database.Skill, error) { return q.db.GetOrganizationSkillByOrganizationIDAndName(ctx, database.GetOrganizationSkillByOrganizationIDAndNameParams(arg)) @@ -4742,6 +4749,13 @@ func (q *querier) GetOrganizationSkillByOrganizationIDAndName(ctx context.Contex return fetch(q.log, q.auth, q.db.GetOrganizationSkillByOrganizationIDAndName)(ctx, arg) } +func (q *querier) GetOrganizationSkillMemberPreferences(ctx context.Context, arg database.GetOrganizationSkillMemberPreferencesParams) (database.GetOrganizationSkillMemberPreferencesRow, error) { + if err := q.authorizeContext(ctx, policy.ActionReadPersonal, rbac.ResourceUserObject(arg.UserID)); err != nil { + return database.GetOrganizationSkillMemberPreferencesRow{}, err + } + return q.db.GetOrganizationSkillMemberPreferences(ctx, arg) +} + func (q *querier) GetOrganizations(ctx context.Context, args database.GetOrganizationsParams) ([]database.Organization, error) { fetch := func(ctx context.Context, _ interface{}) ([]database.Organization, error) { return q.db.GetOrganizations(ctx, args) @@ -6764,6 +6778,13 @@ func (q *querier) InsertOrganizationMember(ctx context.Context, arg database.Ins return insert(q.log, q.auth, obj, q.db.InsertOrganizationMember)(ctx, arg) } +func (q *querier) InsertOrganizationMemberDisabledSkill(ctx context.Context, arg database.InsertOrganizationMemberDisabledSkillParams) error { + if err := q.authorizeContext(ctx, policy.ActionUpdatePersonal, rbac.ResourceUserObject(arg.UserID)); err != nil { + return err + } + return q.db.InsertOrganizationMemberDisabledSkill(ctx, arg) +} + func (q *querier) InsertOrganizationSkill(ctx context.Context, arg database.InsertOrganizationSkillParams) (database.Skill, error) { if err := q.authorizeContext(ctx, policy.ActionCreate, rbac.ResourceOrganizationSkill.InOrg(arg.OrganizationID)); err != nil { return database.Skill{}, err @@ -8420,6 +8441,13 @@ func (q *querier) UpdateOrganizationDeletedByID(ctx context.Context, arg databas return deleteQ(q.log, q.auth, q.db.GetOrganizationByID, deleteF)(ctx, arg.ID) } +func (q *querier) UpdateOrganizationMembersCanDisableSkills(ctx context.Context, arg database.UpdateOrganizationMembersCanDisableSkillsParams) (database.Organization, error) { + if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceOrganizationSkill.InOrg(arg.ID)); err != nil { + return database.Organization{}, err + } + return q.db.UpdateOrganizationMembersCanDisableSkills(ctx, arg) +} + func (q *querier) UpdateOrganizationSkillACLByID(ctx context.Context, arg database.UpdateOrganizationSkillACLByIDParams) (database.Skill, error) { fetch := func(ctx context.Context, arg database.UpdateOrganizationSkillACLByIDParams) (database.Skill, error) { return q.db.GetOrganizationSkillByIDForUpdate(ctx, arg.ID) @@ -9734,6 +9762,13 @@ func (q *querier) UpsertOrganizationAIProviderModelConfig(ctx context.Context, a return q.db.UpsertOrganizationAIProviderModelConfig(ctx, arg) } +func (q *querier) UpsertOrganizationMemberSkillSettings(ctx context.Context, arg database.UpsertOrganizationMemberSkillSettingsParams) error { + if err := q.authorizeContext(ctx, policy.ActionUpdatePersonal, rbac.ResourceUserObject(arg.UserID)); err != nil { + return err + } + return q.db.UpsertOrganizationMemberSkillSettings(ctx, arg) +} + func (q *querier) UpsertPrebuildsSettings(ctx context.Context, value string) error { if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceDeploymentConfig); err != nil { return err diff --git a/coderd/database/dbauthz/dbauthz_test.go b/coderd/database/dbauthz/dbauthz_test.go index 97b3ac1995d..c6647315d3d 100644 --- a/coderd/database/dbauthz/dbauthz_test.go +++ b/coderd/database/dbauthz/dbauthz_test.go @@ -7141,6 +7141,38 @@ func (s *MethodTestSuite) TestOrganizationSkills() { dbm.EXPECT().UpdateOrganizationSkillACLByID(gomock.Any(), arg).Return(updated, nil).AnyTimes() check.Args(arg).Asserts(skill, policy.ActionShare).Returns(updated) })) + s.Run("UpdateOrganizationMembersCanDisableSkills", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) { + org := testutil.Fake(s.T(), faker, database.Organization{}) + arg := database.UpdateOrganizationMembersCanDisableSkillsParams{ID: org.ID, MembersCanDisableSkills: true, UpdatedAt: dbtime.Now()} + updated := org + updated.MembersCanDisableSkills = true + dbm.EXPECT().UpdateOrganizationMembersCanDisableSkills(gomock.Any(), arg).Return(updated, nil).AnyTimes() + check.Args(arg).Asserts(rbac.ResourceOrganizationSkill.InOrg(org.ID), policy.ActionUpdate).Returns(updated) + })) + s.Run("GetOrganizationSkillMemberPreferences", s.Mocked(func(dbm *dbmock.MockStore, _ *gofakeit.Faker, check *expects) { + arg := database.GetOrganizationSkillMemberPreferencesParams{OrganizationID: uuid.New(), UserID: uuid.New()} + row := database.GetOrganizationSkillMemberPreferencesRow{ + MembersCanDisableSkills: true, + DisabledSkillIDs: []uuid.UUID{uuid.New()}, + } + dbm.EXPECT().GetOrganizationSkillMemberPreferences(gomock.Any(), arg).Return(row, nil).AnyTimes() + check.Args(arg).Asserts(rbac.ResourceUserObject(arg.UserID), policy.ActionReadPersonal).Returns(row) + })) + s.Run("UpsertOrganizationMemberSkillSettings", s.Mocked(func(dbm *dbmock.MockStore, _ *gofakeit.Faker, check *expects) { + arg := database.UpsertOrganizationMemberSkillSettingsParams{OrganizationID: uuid.New(), UserID: uuid.New(), AllSkillsDisabled: true} + dbm.EXPECT().UpsertOrganizationMemberSkillSettings(gomock.Any(), arg).Return(nil).AnyTimes() + check.Args(arg).Asserts(rbac.ResourceUserObject(arg.UserID), policy.ActionUpdatePersonal).Returns() + })) + s.Run("InsertOrganizationMemberDisabledSkill", s.Mocked(func(dbm *dbmock.MockStore, _ *gofakeit.Faker, check *expects) { + arg := database.InsertOrganizationMemberDisabledSkillParams{OrganizationID: uuid.New(), UserID: uuid.New(), SkillID: uuid.New()} + dbm.EXPECT().InsertOrganizationMemberDisabledSkill(gomock.Any(), arg).Return(nil).AnyTimes() + check.Args(arg).Asserts(rbac.ResourceUserObject(arg.UserID), policy.ActionUpdatePersonal).Returns() + })) + s.Run("DeleteOrganizationMemberDisabledSkill", s.Mocked(func(dbm *dbmock.MockStore, _ *gofakeit.Faker, check *expects) { + arg := database.DeleteOrganizationMemberDisabledSkillParams{OrganizationID: uuid.New(), UserID: uuid.New(), SkillID: uuid.New()} + dbm.EXPECT().DeleteOrganizationMemberDisabledSkill(gomock.Any(), arg).Return(nil).AnyTimes() + check.Args(arg).Asserts(rbac.ResourceUserObject(arg.UserID), policy.ActionUpdatePersonal).Returns() + })) } func (s *MethodTestSuite) TestProjectSkills() { diff --git a/coderd/database/dbmetrics/querymetrics.go b/coderd/database/dbmetrics/querymetrics.go index 1fcc3273ec3..de68af7ace5 100644 --- a/coderd/database/dbmetrics/querymetrics.go +++ b/coderd/database/dbmetrics/querymetrics.go @@ -896,6 +896,14 @@ func (m queryMetricsStore) DeleteOrganizationMember(ctx context.Context, arg dat return r0 } +func (m queryMetricsStore) DeleteOrganizationMemberDisabledSkill(ctx context.Context, arg database.DeleteOrganizationMemberDisabledSkillParams) error { + start := time.Now() + r0 := m.s.DeleteOrganizationMemberDisabledSkill(ctx, arg) + m.queryLatencies.WithLabelValues("DeleteOrganizationMemberDisabledSkill").Observe(time.Since(start).Seconds()) + m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "DeleteOrganizationMemberDisabledSkill").Inc() + return r0 +} + func (m queryMetricsStore) DeleteOrganizationSkillByOrganizationIDAndName(ctx context.Context, arg database.DeleteOrganizationSkillByOrganizationIDAndNameParams) (database.Skill, error) { start := time.Now() r0, r1 := m.s.DeleteOrganizationSkillByOrganizationIDAndName(ctx, arg) @@ -2880,6 +2888,14 @@ func (m queryMetricsStore) GetOrganizationSkillByOrganizationIDAndName(ctx conte return r0, r1 } +func (m queryMetricsStore) GetOrganizationSkillMemberPreferences(ctx context.Context, arg database.GetOrganizationSkillMemberPreferencesParams) (database.GetOrganizationSkillMemberPreferencesRow, error) { + start := time.Now() + r0, r1 := m.s.GetOrganizationSkillMemberPreferences(ctx, arg) + m.queryLatencies.WithLabelValues("GetOrganizationSkillMemberPreferences").Observe(time.Since(start).Seconds()) + m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "GetOrganizationSkillMemberPreferences").Inc() + return r0, r1 +} + func (m queryMetricsStore) GetOrganizations(ctx context.Context, arg database.GetOrganizationsParams) ([]database.Organization, error) { start := time.Now() r0, r1 := m.s.GetOrganizations(ctx, arg) @@ -4688,6 +4704,14 @@ func (m queryMetricsStore) InsertOrganizationMember(ctx context.Context, arg dat return r0, r1 } +func (m queryMetricsStore) InsertOrganizationMemberDisabledSkill(ctx context.Context, arg database.InsertOrganizationMemberDisabledSkillParams) error { + start := time.Now() + r0 := m.s.InsertOrganizationMemberDisabledSkill(ctx, arg) + m.queryLatencies.WithLabelValues("InsertOrganizationMemberDisabledSkill").Observe(time.Since(start).Seconds()) + m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "InsertOrganizationMemberDisabledSkill").Inc() + return r0 +} + func (m queryMetricsStore) InsertOrganizationSkill(ctx context.Context, arg database.InsertOrganizationSkillParams) (database.Skill, error) { start := time.Now() r0, r1 := m.s.InsertOrganizationSkill(ctx, arg) @@ -5977,6 +6001,14 @@ func (m queryMetricsStore) UpdateOrganizationDeletedByID(ctx context.Context, ar return r0 } +func (m queryMetricsStore) UpdateOrganizationMembersCanDisableSkills(ctx context.Context, arg database.UpdateOrganizationMembersCanDisableSkillsParams) (database.Organization, error) { + start := time.Now() + r0, r1 := m.s.UpdateOrganizationMembersCanDisableSkills(ctx, arg) + m.queryLatencies.WithLabelValues("UpdateOrganizationMembersCanDisableSkills").Observe(time.Since(start).Seconds()) + m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "UpdateOrganizationMembersCanDisableSkills").Inc() + return r0, r1 +} + func (m queryMetricsStore) UpdateOrganizationSkillACLByID(ctx context.Context, arg database.UpdateOrganizationSkillACLByIDParams) (database.Skill, error) { start := time.Now() r0, r1 := m.s.UpdateOrganizationSkillACLByID(ctx, arg) @@ -6985,6 +7017,14 @@ func (m queryMetricsStore) UpsertOrganizationAIProviderModelConfig(ctx context.C return r0 } +func (m queryMetricsStore) UpsertOrganizationMemberSkillSettings(ctx context.Context, arg database.UpsertOrganizationMemberSkillSettingsParams) error { + start := time.Now() + r0 := m.s.UpsertOrganizationMemberSkillSettings(ctx, arg) + m.queryLatencies.WithLabelValues("UpsertOrganizationMemberSkillSettings").Observe(time.Since(start).Seconds()) + m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "UpsertOrganizationMemberSkillSettings").Inc() + return r0 +} + func (m queryMetricsStore) UpsertPrebuildsSettings(ctx context.Context, value string) error { start := time.Now() r0 := m.s.UpsertPrebuildsSettings(ctx, value) diff --git a/coderd/database/dbmock/dbmock.go b/coderd/database/dbmock/dbmock.go index 69cde6cf712..ba06b713fd6 100644 --- a/coderd/database/dbmock/dbmock.go +++ b/coderd/database/dbmock/dbmock.go @@ -1542,6 +1542,20 @@ func (mr *MockStoreMockRecorder) DeleteOrganizationMember(ctx, arg any) *gomock. return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteOrganizationMember", reflect.TypeOf((*MockStore)(nil).DeleteOrganizationMember), ctx, arg) } +// DeleteOrganizationMemberDisabledSkill mocks base method. +func (m *MockStore) DeleteOrganizationMemberDisabledSkill(ctx context.Context, arg database.DeleteOrganizationMemberDisabledSkillParams) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteOrganizationMemberDisabledSkill", ctx, arg) + ret0, _ := ret[0].(error) + return ret0 +} + +// DeleteOrganizationMemberDisabledSkill indicates an expected call of DeleteOrganizationMemberDisabledSkill. +func (mr *MockStoreMockRecorder) DeleteOrganizationMemberDisabledSkill(ctx, arg any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteOrganizationMemberDisabledSkill", reflect.TypeOf((*MockStore)(nil).DeleteOrganizationMemberDisabledSkill), ctx, arg) +} + // DeleteOrganizationSkillByOrganizationIDAndName mocks base method. func (m *MockStore) DeleteOrganizationSkillByOrganizationIDAndName(ctx context.Context, arg database.DeleteOrganizationSkillByOrganizationIDAndNameParams) (database.Skill, error) { m.ctrl.T.Helper() @@ -5409,6 +5423,21 @@ func (mr *MockStoreMockRecorder) GetOrganizationSkillByOrganizationIDAndName(ctx return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOrganizationSkillByOrganizationIDAndName", reflect.TypeOf((*MockStore)(nil).GetOrganizationSkillByOrganizationIDAndName), ctx, arg) } +// GetOrganizationSkillMemberPreferences mocks base method. +func (m *MockStore) GetOrganizationSkillMemberPreferences(ctx context.Context, arg database.GetOrganizationSkillMemberPreferencesParams) (database.GetOrganizationSkillMemberPreferencesRow, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetOrganizationSkillMemberPreferences", ctx, arg) + ret0, _ := ret[0].(database.GetOrganizationSkillMemberPreferencesRow) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetOrganizationSkillMemberPreferences indicates an expected call of GetOrganizationSkillMemberPreferences. +func (mr *MockStoreMockRecorder) GetOrganizationSkillMemberPreferences(ctx, arg any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOrganizationSkillMemberPreferences", reflect.TypeOf((*MockStore)(nil).GetOrganizationSkillMemberPreferences), ctx, arg) +} + // GetOrganizations mocks base method. func (m *MockStore) GetOrganizations(ctx context.Context, arg database.GetOrganizationsParams) ([]database.Organization, error) { m.ctrl.T.Helper() @@ -8838,6 +8867,20 @@ func (mr *MockStoreMockRecorder) InsertOrganizationMember(ctx, arg any) *gomock. return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InsertOrganizationMember", reflect.TypeOf((*MockStore)(nil).InsertOrganizationMember), ctx, arg) } +// InsertOrganizationMemberDisabledSkill mocks base method. +func (m *MockStore) InsertOrganizationMemberDisabledSkill(ctx context.Context, arg database.InsertOrganizationMemberDisabledSkillParams) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "InsertOrganizationMemberDisabledSkill", ctx, arg) + ret0, _ := ret[0].(error) + return ret0 +} + +// InsertOrganizationMemberDisabledSkill indicates an expected call of InsertOrganizationMemberDisabledSkill. +func (mr *MockStoreMockRecorder) InsertOrganizationMemberDisabledSkill(ctx, arg any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InsertOrganizationMemberDisabledSkill", reflect.TypeOf((*MockStore)(nil).InsertOrganizationMemberDisabledSkill), ctx, arg) +} + // InsertOrganizationSkill mocks base method. func (m *MockStore) InsertOrganizationSkill(ctx context.Context, arg database.InsertOrganizationSkillParams) (database.Skill, error) { m.ctrl.T.Helper() @@ -11319,6 +11362,21 @@ func (mr *MockStoreMockRecorder) UpdateOrganizationDeletedByID(ctx, arg any) *go return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateOrganizationDeletedByID", reflect.TypeOf((*MockStore)(nil).UpdateOrganizationDeletedByID), ctx, arg) } +// UpdateOrganizationMembersCanDisableSkills mocks base method. +func (m *MockStore) UpdateOrganizationMembersCanDisableSkills(ctx context.Context, arg database.UpdateOrganizationMembersCanDisableSkillsParams) (database.Organization, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateOrganizationMembersCanDisableSkills", ctx, arg) + ret0, _ := ret[0].(database.Organization) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// UpdateOrganizationMembersCanDisableSkills indicates an expected call of UpdateOrganizationMembersCanDisableSkills. +func (mr *MockStoreMockRecorder) UpdateOrganizationMembersCanDisableSkills(ctx, arg any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateOrganizationMembersCanDisableSkills", reflect.TypeOf((*MockStore)(nil).UpdateOrganizationMembersCanDisableSkills), ctx, arg) +} + // UpdateOrganizationSkillACLByID mocks base method. func (m *MockStore) UpdateOrganizationSkillACLByID(ctx context.Context, arg database.UpdateOrganizationSkillACLByIDParams) (database.Skill, error) { m.ctrl.T.Helper() @@ -13133,6 +13191,20 @@ func (mr *MockStoreMockRecorder) UpsertOrganizationAIProviderModelConfig(ctx, ar return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpsertOrganizationAIProviderModelConfig", reflect.TypeOf((*MockStore)(nil).UpsertOrganizationAIProviderModelConfig), ctx, arg) } +// UpsertOrganizationMemberSkillSettings mocks base method. +func (m *MockStore) UpsertOrganizationMemberSkillSettings(ctx context.Context, arg database.UpsertOrganizationMemberSkillSettingsParams) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpsertOrganizationMemberSkillSettings", ctx, arg) + ret0, _ := ret[0].(error) + return ret0 +} + +// UpsertOrganizationMemberSkillSettings indicates an expected call of UpsertOrganizationMemberSkillSettings. +func (mr *MockStoreMockRecorder) UpsertOrganizationMemberSkillSettings(ctx, arg any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpsertOrganizationMemberSkillSettings", reflect.TypeOf((*MockStore)(nil).UpsertOrganizationMemberSkillSettings), ctx, arg) +} + // UpsertPrebuildsSettings mocks base method. func (m *MockStore) UpsertPrebuildsSettings(ctx context.Context, value string) error { m.ctrl.T.Helper() diff --git a/coderd/database/dump.sql b/coderd/database/dump.sql index 96933d78ae4..d879d118e53 100644 --- a/coderd/database/dump.sql +++ b/coderd/database/dump.sql @@ -3114,6 +3114,24 @@ COMMENT ON COLUMN oauth2_provider_apps.registration_access_token IS 'RFC 7592: H COMMENT ON COLUMN oauth2_provider_apps.registration_client_uri IS 'RFC 7592: URI for client configuration endpoint'; +CREATE TABLE organization_member_disabled_skills ( + organization_id uuid NOT NULL, + user_id uuid NOT NULL, + skill_id uuid NOT NULL +); + +COMMENT ON TABLE organization_member_disabled_skills IS 'Organization skills that a member turned off for their own chats. Applied only while organizations.members_can_disable_skills is true.'; + +CREATE TABLE organization_member_skill_settings ( + organization_id uuid NOT NULL, + user_id uuid NOT NULL, + all_skills_disabled boolean DEFAULT false NOT NULL +); + +COMMENT ON TABLE organization_member_skill_settings IS 'Per-member organization skill settings. Applied only while organizations.members_can_disable_skills is true.'; + +COMMENT ON COLUMN organization_member_skill_settings.all_skills_disabled IS 'Whether the member turned off every organization skill, including skills added later. Per-skill choices in organization_member_disabled_skills are kept and apply again when this is false.'; + CREATE TABLE organizations ( id uuid NOT NULL, name text NOT NULL, @@ -3125,13 +3143,16 @@ CREATE TABLE organizations ( icon text DEFAULT ''::text NOT NULL, deleted boolean DEFAULT false NOT NULL, shareable_workspace_owners shareable_workspace_owners DEFAULT 'everyone'::shareable_workspace_owners NOT NULL, - default_org_member_roles text[] NOT NULL + default_org_member_roles text[] NOT NULL, + members_can_disable_skills boolean DEFAULT false NOT NULL ); COMMENT ON COLUMN organizations.shareable_workspace_owners IS 'Controls whose workspaces can be shared: none, everyone, or service_accounts.'; COMMENT ON COLUMN organizations.default_org_member_roles IS 'Roles granted to every member of this organization at request time. The set is unioned into each member''s effective roles when GetAuthorizationUserRoles runs, so changes propagate to all members on the next request. Deployments can use this column to revoke capabilities that would otherwise be considered normal organization member permissions.'; +COMMENT ON COLUMN organizations.members_can_disable_skills IS 'Whether organization members can turn off organization skills for their own chats. While false, member choices are kept but ignored.'; + CREATE TABLE parameter_schemas ( id uuid NOT NULL, created_at timestamp with time zone NOT NULL, @@ -4799,6 +4820,12 @@ ALTER TABLE ONLY oauth2_provider_app_tokens ALTER TABLE ONLY oauth2_provider_apps ADD CONSTRAINT oauth2_provider_apps_pkey PRIMARY KEY (id); +ALTER TABLE ONLY organization_member_disabled_skills + ADD CONSTRAINT organization_member_disabled_skills_pkey PRIMARY KEY (organization_id, user_id, skill_id); + +ALTER TABLE ONLY organization_member_skill_settings + ADD CONSTRAINT organization_member_skill_settings_pkey PRIMARY KEY (organization_id, user_id); + ALTER TABLE ONLY organization_members ADD CONSTRAINT organization_members_pkey PRIMARY KEY (organization_id, user_id); @@ -5239,6 +5266,8 @@ CREATE INDEX idx_mcp_server_user_tokens_user_id ON mcp_server_user_tokens USING CREATE INDEX idx_notification_messages_status ON notification_messages USING btree (status); +CREATE INDEX idx_organization_member_disabled_skills_skill_id ON organization_member_disabled_skills USING btree (skill_id); + CREATE INDEX idx_organization_member_organization_id_uuid ON organization_members USING btree (organization_id); CREATE INDEX idx_organization_member_user_id_uuid ON organization_members USING btree (user_id); @@ -5779,6 +5808,15 @@ ALTER TABLE ONLY oauth2_provider_app_tokens ALTER TABLE ONLY oauth2_provider_app_tokens ADD CONSTRAINT oauth2_provider_app_tokens_app_secret_id_fkey FOREIGN KEY (app_secret_id) REFERENCES oauth2_provider_app_secrets(id) ON DELETE CASCADE; +ALTER TABLE ONLY organization_member_disabled_skills + ADD CONSTRAINT organization_member_disabled_skill_organization_id_user_id_fkey FOREIGN KEY (organization_id, user_id) REFERENCES organization_members(organization_id, user_id) ON DELETE CASCADE; + +ALTER TABLE ONLY organization_member_disabled_skills + ADD CONSTRAINT organization_member_disabled_skills_skill_id_fkey FOREIGN KEY (skill_id) REFERENCES skills(id) ON DELETE CASCADE; + +ALTER TABLE ONLY organization_member_skill_settings + ADD CONSTRAINT organization_member_skill_settings_organization_id_user_id_fkey FOREIGN KEY (organization_id, user_id) REFERENCES organization_members(organization_id, user_id) ON DELETE CASCADE; + ALTER TABLE ONLY organization_members ADD CONSTRAINT organization_members_organization_id_uuid_fkey FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE CASCADE; diff --git a/coderd/database/foreign_key_constraint.go b/coderd/database/foreign_key_constraint.go index 16426c79ccb..a2bf141ed34 100644 --- a/coderd/database/foreign_key_constraint.go +++ b/coderd/database/foreign_key_constraint.go @@ -98,6 +98,9 @@ const ( ForeignKeyOauth2ProviderAppTokensAPIKeyID ForeignKeyConstraint = "oauth2_provider_app_tokens_api_key_id_fkey" // ALTER TABLE ONLY oauth2_provider_app_tokens ADD CONSTRAINT oauth2_provider_app_tokens_api_key_id_fkey FOREIGN KEY (api_key_id) REFERENCES api_keys(id) ON DELETE CASCADE; ForeignKeyOauth2ProviderAppTokensAppID ForeignKeyConstraint = "oauth2_provider_app_tokens_app_id_fkey" // ALTER TABLE ONLY oauth2_provider_app_tokens ADD CONSTRAINT oauth2_provider_app_tokens_app_id_fkey FOREIGN KEY (app_id) REFERENCES oauth2_provider_apps(id) ON DELETE CASCADE; ForeignKeyOauth2ProviderAppTokensAppSecretID ForeignKeyConstraint = "oauth2_provider_app_tokens_app_secret_id_fkey" // ALTER TABLE ONLY oauth2_provider_app_tokens ADD CONSTRAINT oauth2_provider_app_tokens_app_secret_id_fkey FOREIGN KEY (app_secret_id) REFERENCES oauth2_provider_app_secrets(id) ON DELETE CASCADE; + ForeignKeyOrganizationMemberDisabledSkillOrganizationIDUserID ForeignKeyConstraint = "organization_member_disabled_skill_organization_id_user_id_fkey" // ALTER TABLE ONLY organization_member_disabled_skills ADD CONSTRAINT organization_member_disabled_skill_organization_id_user_id_fkey FOREIGN KEY (organization_id, user_id) REFERENCES organization_members(organization_id, user_id) ON DELETE CASCADE; + ForeignKeyOrganizationMemberDisabledSkillsSkillID ForeignKeyConstraint = "organization_member_disabled_skills_skill_id_fkey" // ALTER TABLE ONLY organization_member_disabled_skills ADD CONSTRAINT organization_member_disabled_skills_skill_id_fkey FOREIGN KEY (skill_id) REFERENCES skills(id) ON DELETE CASCADE; + ForeignKeyOrganizationMemberSkillSettingsOrganizationIDUserID ForeignKeyConstraint = "organization_member_skill_settings_organization_id_user_id_fkey" // ALTER TABLE ONLY organization_member_skill_settings ADD CONSTRAINT organization_member_skill_settings_organization_id_user_id_fkey FOREIGN KEY (organization_id, user_id) REFERENCES organization_members(organization_id, user_id) ON DELETE CASCADE; ForeignKeyOrganizationMembersOrganizationIDUUID ForeignKeyConstraint = "organization_members_organization_id_uuid_fkey" // ALTER TABLE ONLY organization_members ADD CONSTRAINT organization_members_organization_id_uuid_fkey FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE CASCADE; ForeignKeyOrganizationMembersUserIDUUID ForeignKeyConstraint = "organization_members_user_id_uuid_fkey" // ALTER TABLE ONLY organization_members ADD CONSTRAINT organization_members_user_id_uuid_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE; ForeignKeyParameterSchemasJobID ForeignKeyConstraint = "parameter_schemas_job_id_fkey" // ALTER TABLE ONLY parameter_schemas ADD CONSTRAINT parameter_schemas_job_id_fkey FOREIGN KEY (job_id) REFERENCES provisioner_jobs(id) ON DELETE CASCADE; diff --git a/coderd/database/migrations/000636_organization_skill_member_preferences.down.sql b/coderd/database/migrations/000636_organization_skill_member_preferences.down.sql new file mode 100644 index 00000000000..48b14134420 --- /dev/null +++ b/coderd/database/migrations/000636_organization_skill_member_preferences.down.sql @@ -0,0 +1,3 @@ +DROP TABLE organization_member_disabled_skills; +DROP TABLE organization_member_skill_settings; +ALTER TABLE organizations DROP COLUMN members_can_disable_skills; diff --git a/coderd/database/migrations/000636_organization_skill_member_preferences.up.sql b/coderd/database/migrations/000636_organization_skill_member_preferences.up.sql new file mode 100644 index 00000000000..e8d4ea0d7c2 --- /dev/null +++ b/coderd/database/migrations/000636_organization_skill_member_preferences.up.sql @@ -0,0 +1,35 @@ +ALTER TABLE organizations + ADD COLUMN members_can_disable_skills boolean NOT NULL DEFAULT false; + +COMMENT ON COLUMN organizations.members_can_disable_skills IS 'Whether organization members can turn off organization skills for their own chats. While false, member choices are kept but ignored.'; + +-- One row per organization member who has saved an organization skill +-- choice. Removing the membership deletes the row. +CREATE TABLE organization_member_skill_settings ( + organization_id uuid NOT NULL, + user_id uuid NOT NULL, + all_skills_disabled boolean NOT NULL DEFAULT false, + PRIMARY KEY (organization_id, user_id), + FOREIGN KEY (organization_id, user_id) + REFERENCES organization_members (organization_id, user_id) ON DELETE CASCADE +); + +COMMENT ON TABLE organization_member_skill_settings IS 'Per-member organization skill settings. Applied only while organizations.members_can_disable_skills is true.'; + +COMMENT ON COLUMN organization_member_skill_settings.all_skills_disabled IS 'Whether the member turned off every organization skill, including skills added later. Per-skill choices in organization_member_disabled_skills are kept and apply again when this is false.'; + +-- Organization skills a member turned off for their own chats. +CREATE TABLE organization_member_disabled_skills ( + organization_id uuid NOT NULL, + user_id uuid NOT NULL, + skill_id uuid NOT NULL REFERENCES skills (id) ON DELETE CASCADE, + PRIMARY KEY (organization_id, user_id, skill_id), + FOREIGN KEY (organization_id, user_id) + REFERENCES organization_members (organization_id, user_id) ON DELETE CASCADE +); + +COMMENT ON TABLE organization_member_disabled_skills IS 'Organization skills that a member turned off for their own chats. Applied only while organizations.members_can_disable_skills is true.'; + +-- Supports the cascade from skills, which the primary key cannot serve. +CREATE INDEX idx_organization_member_disabled_skills_skill_id + ON organization_member_disabled_skills (skill_id); diff --git a/coderd/database/migrations/migrate_test.go b/coderd/database/migrations/migrate_test.go index f4e42ef92b6..eeab6faf91e 100644 --- a/coderd/database/migrations/migrate_test.go +++ b/coderd/database/migrations/migrate_test.go @@ -1637,15 +1637,14 @@ func testMigration000595RemoveTaskPermissions(t *testing.T, sqlDB *sql.DB, next func testMigration000587RemoveAgentsAccessRole(t *testing.T, sqlDB *sql.DB, next migrationStepper) { const migrationVersion = 587 + ctx := testutil.Context(t, testutil.WaitLong) db := database.New(sqlDB) user := dbgen.User(t, db, database.User{ RBACRoles: []string{"auditor", "agents-access"}, }) - org := dbgen.Organization(t, db, database.Organization{ - DefaultOrgMemberRoles: []string{"organization-workspace-access", "agents-access"}, - }) + orgID := insertMigrationTestOrganization(ctx, t, sqlDB, []string{"organization-workspace-access", "agents-access"}) dbgen.OrganizationMember(t, db, database.OrganizationMember{ - OrganizationID: org.ID, + OrganizationID: orgID, UserID: user.ID, Roles: []string{"organization-auditor", "agents-access"}, }) @@ -1654,13 +1653,12 @@ func testMigration000587RemoveAgentsAccessRole(t *testing.T, sqlDB *sql.DB, next require.NoError(t, err) require.EqualValues(t, migrationVersion, version) - ctx := testutil.Context(t, testutil.WaitLong) var siteRoles, orgRoles, defaultRoles pq.StringArray err = sqlDB.QueryRowContext(ctx, "SELECT rbac_roles FROM users WHERE id = $1", user.ID).Scan(&siteRoles) require.NoError(t, err) - err = sqlDB.QueryRowContext(ctx, "SELECT roles FROM organization_members WHERE organization_id = $1 AND user_id = $2", org.ID, user.ID).Scan(&orgRoles) + err = sqlDB.QueryRowContext(ctx, "SELECT roles FROM organization_members WHERE organization_id = $1 AND user_id = $2", orgID, user.ID).Scan(&orgRoles) require.NoError(t, err) - err = sqlDB.QueryRowContext(ctx, "SELECT default_org_member_roles FROM organizations WHERE id = $1", org.ID).Scan(&defaultRoles) + err = sqlDB.QueryRowContext(ctx, "SELECT default_org_member_roles FROM organizations WHERE id = $1", orgID).Scan(&defaultRoles) require.NoError(t, err) require.Equal(t, []string{"auditor"}, []string(siteRoles)) @@ -1684,11 +1682,7 @@ func testMigration000602RestoreAgentsAccessDefaultRole(t *testing.T, sqlDB *sql. } orgIDs := make([]uuid.UUID, len(orgs)) for i, o := range orgs { - org := dbgen.Organization(t, db, database.Organization{}) - // dbgen replaces an empty slice with the current defaults. - _, err := sqlDB.ExecContext(ctx, "UPDATE organizations SET default_org_member_roles = $1 WHERE id = $2", pq.StringArray(o.defaults), org.ID) - require.NoError(t, err) - orgIDs[i] = org.ID + orgIDs[i] = insertMigrationTestOrganization(ctx, t, sqlDB, o.defaults) } member := dbgen.User(t, db, database.User{}) @@ -4486,7 +4480,9 @@ func testMigration000625TemplateVersionScriptOrderUsage(t *testing.T, sqlDB *sql ctx := testutil.Context(t, testutil.WaitLong) db := database.New(sqlDB) - org, err := db.GetDefaultOrganization(ctx) + // Avoid GetDefaultOrganization: it reads columns added by later migrations. + var orgID uuid.UUID + err := sqlDB.QueryRowContext(ctx, `SELECT id FROM organizations WHERE is_default`).Scan(&orgID) require.NoError(t, err) user := dbgen.User(t, db, database.User{}) // GIVEN: An existing template version and a user-secrets telemetry lock. @@ -4494,7 +4490,7 @@ func testMigration000625TemplateVersionScriptOrderUsage(t *testing.T, sqlDB *sql legacyID := uuid.New() err = db.InsertTemplateVersion(ctx, database.InsertTemplateVersionParams{ ID: legacyID, - OrganizationID: org.ID, + OrganizationID: orgID, CreatedBy: user.ID, JobID: uuid.New(), Name: testutil.GetRandomName(t), @@ -4531,7 +4527,7 @@ func testMigration000625TemplateVersionScriptOrderUsage(t *testing.T, sqlDB *sql // An older provisioner omits the counts, so new rows also default to zero. newVersion := dbgen.TemplateVersion(t, db, database.TemplateVersion{ - OrganizationID: org.ID, + OrganizationID: orgID, CreatedBy: user.ID, }) require.Zero(t, newVersion.ScriptOrderDataSourceCount) @@ -4670,6 +4666,21 @@ func TestMigration000627WorkspaceAgentScriptTimingSkippedCanceled(t *testing.T) require.Equal(t, []string{"ok", "exit_failure", "timed_out", "pipes_left_open", "skipped", "canceled"}, enumValues()) } +// insertMigrationTestOrganization inserts an organization with raw SQL for +// tests that run at an older schema version. dbgen.Organization reads back +// every column of the current schema, so it fails before a later migration +// adds a column to organizations. +func insertMigrationTestOrganization(ctx context.Context, t *testing.T, sqlDB *sql.DB, defaultOrgMemberRoles []string) uuid.UUID { + t.Helper() + id := uuid.New() + _, err := sqlDB.ExecContext(ctx, + `INSERT INTO organizations (id, name, display_name, description, created_at, updated_at, default_org_member_roles) VALUES ($1, $2, $2, '', NOW(), NOW(), $3)`, + id, "org-"+id.String(), pq.StringArray(defaultOrgMemberRoles), + ) + require.NoError(t, err) + return id +} + func testMigration000635ChatModelOverrideComputerUse(t *testing.T, sqlDB *sql.DB, next migrationStepper) { const migrationVersion = 635 diff --git a/coderd/database/migrations/migration000617_test.go b/coderd/database/migrations/migration000617_test.go index c5f69a8b0f3..4a14a344437 100644 --- a/coderd/database/migrations/migration000617_test.go +++ b/coderd/database/migrations/migration000617_test.go @@ -80,10 +80,10 @@ func TestMigration000617ConnectionLogsMethod(t *testing.T) { ctx := testutil.Context(t, testutil.WaitLong) db := database.New(sqlDB) - org := dbgen.Organization(t, db, database.Organization{}) + orgID := insertMigrationTestOrganization(ctx, t, sqlDB, []string{}) owner := dbgen.User(t, db, database.User{}) - tpl := dbgen.Template(t, db, database.Template{OrganizationID: org.ID, CreatedBy: owner.ID}) - ws := dbgen.Workspace(t, db, database.WorkspaceTable{OrganizationID: org.ID, OwnerID: owner.ID, TemplateID: tpl.ID}) + tpl := dbgen.Template(t, db, database.Template{OrganizationID: orgID, CreatedBy: owner.ID}) + ws := dbgen.Workspace(t, db, database.WorkspaceTable{OrganizationID: orgID, OwnerID: owner.ID, TemplateID: tpl.ID}) // row is (type, slug_or_port) before 000617 and // (connection_method, app_name_or_port) after it. @@ -95,7 +95,7 @@ func TestMigration000617ConnectionLogsMethod(t *testing.T) { ids := map[row]uuid.UUID{} insert := func(query string, r row) { ids[r] = uuid.New() - _, err := sqlDB.ExecContext(ctx, query, ids[r], org.ID, owner.ID, ws.ID, ws.Name, r.kind, r.appNameOrPort) + _, err := sqlDB.ExecContext(ctx, query, ids[r], orgID, owner.ID, ws.ID, ws.Name, r.kind, r.appNameOrPort) require.NoError(t, err) } read := func(query string, r row) (got row) { diff --git a/coderd/database/migrations/migration000629_test.go b/coderd/database/migrations/migration000629_test.go index 52189153397..e6a6af6a027 100644 --- a/coderd/database/migrations/migration000629_test.go +++ b/coderd/database/migrations/migration000629_test.go @@ -24,21 +24,21 @@ func TestMigration000629DropsOutOfOrgChatProjectGrants(t *testing.T) { ctx := testutil.Context(t, testutil.WaitLong) db := database.New(sqlDB) - org := dbgen.Organization(t, db, database.Organization{}) - otherOrg := dbgen.Organization(t, db, database.Organization{}) + orgID := insertMigrationTestOrganization(ctx, t, sqlDB, []string{}) + otherOrgID := insertMigrationTestOrganization(ctx, t, sqlDB, []string{}) owner := dbgen.User(t, db, database.User{}) member := dbgen.User(t, db, database.User{}) departed := dbgen.User(t, db, database.User{}) for _, user := range []database.User{owner, member} { - dbgen.OrganizationMember(t, db, database.OrganizationMember{UserID: user.ID, OrganizationID: org.ID}) + dbgen.OrganizationMember(t, db, database.OrganizationMember{UserID: user.ID, OrganizationID: orgID}) } // Membership elsewhere must not keep a grant here. - dbgen.OrganizationMember(t, db, database.OrganizationMember{UserID: departed.ID, OrganizationID: otherOrg.ID}) + dbgen.OrganizationMember(t, db, database.OrganizationMember{UserID: departed.ID, OrganizationID: otherOrgID}) projectID := uuid.New() grant := `{"permissions":["read"]}` userACL := `{"` + member.ID.String() + `":` + grant + `,"` + departed.ID.String() + `":` + grant + `}` _, err := sqlDB.ExecContext(ctx, `INSERT INTO chat_projects (id, organization_id, owner_id, name, user_acl) VALUES ($1, $2, $3, 'project', $4::jsonb)`, - projectID, org.ID, owner.ID, userACL) + projectID, orgID, owner.ID, userACL) require.NoError(t, err) migration, err := os.ReadFile("000629_chat_project_acl_org_member_delete.up.sql") diff --git a/coderd/database/migrations/testdata/fixtures/000636_organization_skill_member_preferences.up.sql b/coderd/database/migrations/testdata/fixtures/000636_organization_skill_member_preferences.up.sql new file mode 100644 index 00000000000..4fcbb48958b --- /dev/null +++ b/coderd/database/migrations/testdata/fixtures/000636_organization_skill_member_preferences.up.sql @@ -0,0 +1,19 @@ +INSERT INTO organization_member_skill_settings ( + organization_id, + user_id, + all_skills_disabled +) VALUES ( + 'bb640d07-ca8a-4869-b6bc-ae61ebb2fda1', + '30095c71-380b-457a-8995-97b8ee6e5307', + false +); + +INSERT INTO organization_member_disabled_skills ( + organization_id, + user_id, + skill_id +) VALUES ( + 'bb640d07-ca8a-4869-b6bc-ae61ebb2fda1', + '30095c71-380b-457a-8995-97b8ee6e5307', + '7f070eb2-991e-4f7f-b780-40c4e0f49002' +); diff --git a/coderd/database/modelmethods.go b/coderd/database/modelmethods.go index 14af7e532b5..98cb94d490e 100644 --- a/coderd/database/modelmethods.go +++ b/coderd/database/modelmethods.go @@ -1023,6 +1023,14 @@ func (s Skill) RBACObject() rbac.Object { return rbac.Object{ID: s.ID.String()} } +// Excludes reports whether the member's choices remove the organization +// skill from their chats. Choices apply only while the organization lets +// members turn off organization skills, and the master switch also covers +// skills added after it was set. +func (p GetOrganizationSkillMemberPreferencesRow) Excludes(skillID uuid.UUID) bool { + return p.MembersCanDisableSkills && (p.AllSkillsDisabled || slices.Contains(p.DisabledSkillIDs, skillID)) +} + func (s UserSecret) RBACObject() rbac.Object { return rbac.ResourceUserSecret.WithID(s.ID).WithOwner(s.UserID.String()) } diff --git a/coderd/database/models.go b/coderd/database/models.go index 8b97fc6c657..7f11bf9fd71 100644 --- a/coderd/database/models.go +++ b/coderd/database/models.go @@ -6118,6 +6118,8 @@ type Organization struct { ShareableWorkspaceOwners ShareableWorkspaceOwners `db:"shareable_workspace_owners" json:"shareable_workspace_owners"` // Roles granted to every member of this organization at request time. The set is unioned into each member's effective roles when GetAuthorizationUserRoles runs, so changes propagate to all members on the next request. Deployments can use this column to revoke capabilities that would otherwise be considered normal organization member permissions. DefaultOrgMemberRoles []string `db:"default_org_member_roles" json:"default_org_member_roles"` + // Whether organization members can turn off organization skills for their own chats. While false, member choices are kept but ignored. + MembersCanDisableSkills bool `db:"members_can_disable_skills" json:"members_can_disable_skills"` } type OrganizationMember struct { @@ -6128,6 +6130,21 @@ type OrganizationMember struct { Roles []string `db:"roles" json:"roles"` } +// Organization skills that a member turned off for their own chats. Applied only while organizations.members_can_disable_skills is true. +type OrganizationMemberDisabledSkill struct { + OrganizationID uuid.UUID `db:"organization_id" json:"organization_id"` + UserID uuid.UUID `db:"user_id" json:"user_id"` + SkillID uuid.UUID `db:"skill_id" json:"skill_id"` +} + +// Per-member organization skill settings. Applied only while organizations.members_can_disable_skills is true. +type OrganizationMemberSkillSetting struct { + OrganizationID uuid.UUID `db:"organization_id" json:"organization_id"` + UserID uuid.UUID `db:"user_id" json:"user_id"` + // Whether the member turned off every organization skill, including skills added later. Per-skill choices in organization_member_disabled_skills are kept and apply again when this is false. + AllSkillsDisabled bool `db:"all_skills_disabled" json:"all_skills_disabled"` +} + type ParameterSchema struct { ID uuid.UUID `db:"id" json:"id"` CreatedAt time.Time `db:"created_at" json:"created_at"` diff --git a/coderd/database/querier.go b/coderd/database/querier.go index ff17625821c..08ee6ce3dbd 100644 --- a/coderd/database/querier.go +++ b/coderd/database/querier.go @@ -251,6 +251,7 @@ type sqlcQuerier interface { // provider. Returns zero rows when there is no live config. DeleteOrganizationAIProviderModelConfig(ctx context.Context, arg DeleteOrganizationAIProviderModelConfigParams) (int64, error) DeleteOrganizationMember(ctx context.Context, arg DeleteOrganizationMemberParams) error + DeleteOrganizationMemberDisabledSkill(ctx context.Context, arg DeleteOrganizationMemberDisabledSkillParams) error DeleteOrganizationSkillByOrganizationIDAndName(ctx context.Context, arg DeleteOrganizationSkillByOrganizationIDAndNameParams) (Skill, error) DeleteProjectSkillByProjectIDAndName(ctx context.Context, arg DeleteProjectSkillByProjectIDAndNameParams) (Skill, error) DeleteProvisionerKey(ctx context.Context, id uuid.UUID) error @@ -812,6 +813,9 @@ type sqlcQuerier interface { GetOrganizationResourceCountByID(ctx context.Context, organizationID uuid.UUID) (GetOrganizationResourceCountByIDRow, error) GetOrganizationSkillByIDForUpdate(ctx context.Context, id uuid.UUID) (Skill, error) GetOrganizationSkillByOrganizationIDAndName(ctx context.Context, arg GetOrganizationSkillByOrganizationIDAndNameParams) (Skill, error) + // Returns the organization's member opt-out setting and the member's stored + // choices. Members without stored choices get the defaults. + GetOrganizationSkillMemberPreferences(ctx context.Context, arg GetOrganizationSkillMemberPreferencesParams) (GetOrganizationSkillMemberPreferencesRow, error) GetOrganizations(ctx context.Context, arg GetOrganizationsParams) ([]Organization, error) GetOrganizationsByUserID(ctx context.Context, arg GetOrganizationsByUserIDParams) ([]Organization, error) // GetOrganizationsWithPrebuildStatus returns organizations with prebuilds configured and their @@ -1287,6 +1291,8 @@ type sqlcQuerier interface { InsertOAuth2ProviderAppToken(ctx context.Context, arg InsertOAuth2ProviderAppTokenParams) (OAuth2ProviderAppToken, error) InsertOrganization(ctx context.Context, arg InsertOrganizationParams) (Organization, error) InsertOrganizationMember(ctx context.Context, arg InsertOrganizationMemberParams) (OrganizationMember, error) + // Stores nothing unless the skill belongs to the organization. + InsertOrganizationMemberDisabledSkill(ctx context.Context, arg InsertOrganizationMemberDisabledSkillParams) error InsertOrganizationSkill(ctx context.Context, arg InsertOrganizationSkillParams) (Skill, error) InsertPreset(ctx context.Context, arg InsertPresetParams) (TemplateVersionPreset, error) InsertPresetParameters(ctx context.Context, arg InsertPresetParametersParams) ([]TemplateVersionPresetParameter, error) @@ -1684,6 +1690,7 @@ type sqlcQuerier interface { UpdateOAuth2ProviderAppByID(ctx context.Context, arg UpdateOAuth2ProviderAppByIDParams) (OAuth2ProviderApp, error) UpdateOrganization(ctx context.Context, arg UpdateOrganizationParams) (Organization, error) UpdateOrganizationDeletedByID(ctx context.Context, arg UpdateOrganizationDeletedByIDParams) error + UpdateOrganizationMembersCanDisableSkills(ctx context.Context, arg UpdateOrganizationMembersCanDisableSkillsParams) (Organization, error) UpdateOrganizationSkillACLByID(ctx context.Context, arg UpdateOrganizationSkillACLByIDParams) (Skill, error) UpdateOrganizationSkillByOrganizationIDAndName(ctx context.Context, arg UpdateOrganizationSkillByOrganizationIDAndNameParams) (Skill, error) UpdateOrganizationWorkspaceSharingSettings(ctx context.Context, arg UpdateOrganizationWorkspaceSharingSettingsParams) (Organization, error) @@ -1853,6 +1860,7 @@ type sqlcQuerier interface { // differs, so updated_at records when a price last changed. Soft-deleted rows // are left untouched, and a new live row is inserted beside them. UpsertOrganizationAIProviderModelConfig(ctx context.Context, arg UpsertOrganizationAIProviderModelConfigParams) error + UpsertOrganizationMemberSkillSettings(ctx context.Context, arg UpsertOrganizationMemberSkillSettingsParams) error UpsertPrebuildsSettings(ctx context.Context, value string) error UpsertProvisionerDaemon(ctx context.Context, arg UpsertProvisionerDaemonParams) (ProvisionerDaemon, error) UpsertRuntimeConfig(ctx context.Context, arg UpsertRuntimeConfigParams) error diff --git a/coderd/database/queries.sql.go b/coderd/database/queries.sql.go index 63ce247380f..018f38481fc 100644 --- a/coderd/database/queries.sql.go +++ b/coderd/database/queries.sql.go @@ -23616,7 +23616,7 @@ func (q *sqlQuerier) UpdateMemberRoles(ctx context.Context, arg UpdateMemberRole const getDefaultOrganization = `-- name: GetDefaultOrganization :one SELECT - id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles + id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles, members_can_disable_skills FROM organizations WHERE @@ -23640,13 +23640,14 @@ func (q *sqlQuerier) GetDefaultOrganization(ctx context.Context) (Organization, &i.Deleted, &i.ShareableWorkspaceOwners, pq.Array(&i.DefaultOrgMemberRoles), + &i.MembersCanDisableSkills, ) return i, err } const getOrganizationByID = `-- name: GetOrganizationByID :one SELECT - id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles + id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles, members_can_disable_skills FROM organizations WHERE @@ -23668,13 +23669,14 @@ func (q *sqlQuerier) GetOrganizationByID(ctx context.Context, id uuid.UUID) (Org &i.Deleted, &i.ShareableWorkspaceOwners, pq.Array(&i.DefaultOrgMemberRoles), + &i.MembersCanDisableSkills, ) return i, err } const getOrganizationByName = `-- name: GetOrganizationByName :one SELECT - id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles + id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles, members_can_disable_skills FROM organizations WHERE @@ -23705,6 +23707,7 @@ func (q *sqlQuerier) GetOrganizationByName(ctx context.Context, arg GetOrganizat &i.Deleted, &i.ShareableWorkspaceOwners, pq.Array(&i.DefaultOrgMemberRoles), + &i.MembersCanDisableSkills, ) return i, err } @@ -23775,7 +23778,7 @@ func (q *sqlQuerier) GetOrganizationResourceCountByID(ctx context.Context, organ const getOrganizations = `-- name: GetOrganizations :many SELECT - id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles + id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles, members_can_disable_skills FROM organizations WHERE @@ -23821,6 +23824,7 @@ func (q *sqlQuerier) GetOrganizations(ctx context.Context, arg GetOrganizationsP &i.Deleted, &i.ShareableWorkspaceOwners, pq.Array(&i.DefaultOrgMemberRoles), + &i.MembersCanDisableSkills, ); err != nil { return nil, err } @@ -23837,7 +23841,7 @@ func (q *sqlQuerier) GetOrganizations(ctx context.Context, arg GetOrganizationsP const getOrganizationsByUserID = `-- name: GetOrganizationsByUserID :many SELECT - id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles + id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles, members_can_disable_skills FROM organizations WHERE @@ -23884,6 +23888,7 @@ func (q *sqlQuerier) GetOrganizationsByUserID(ctx context.Context, arg GetOrgani &i.Deleted, &i.ShareableWorkspaceOwners, pq.Array(&i.DefaultOrgMemberRoles), + &i.MembersCanDisableSkills, ); err != nil { return nil, err } @@ -23903,7 +23908,7 @@ INSERT INTO organizations (id, "name", display_name, description, icon, created_at, updated_at, is_default, default_org_member_roles) VALUES -- If no organizations exist, and this is the first, make it the default. - ($1, $2, $3, $4, $5, $6, $7, (SELECT TRUE FROM organizations LIMIT 1) IS NULL, $8) RETURNING id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles + ($1, $2, $3, $4, $5, $6, $7, (SELECT TRUE FROM organizations LIMIT 1) IS NULL, $8) RETURNING id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles, members_can_disable_skills ` type InsertOrganizationParams struct { @@ -23941,6 +23946,7 @@ func (q *sqlQuerier) InsertOrganization(ctx context.Context, arg InsertOrganizat &i.Deleted, &i.ShareableWorkspaceOwners, pq.Array(&i.DefaultOrgMemberRoles), + &i.MembersCanDisableSkills, ) return i, err } @@ -23957,7 +23963,7 @@ SET default_org_member_roles = $6 WHERE id = $7 -RETURNING id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles +RETURNING id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles, members_can_disable_skills ` type UpdateOrganizationParams struct { @@ -23993,6 +23999,7 @@ func (q *sqlQuerier) UpdateOrganization(ctx context.Context, arg UpdateOrganizat &i.Deleted, &i.ShareableWorkspaceOwners, pq.Array(&i.DefaultOrgMemberRoles), + &i.MembersCanDisableSkills, ) return i, err } @@ -24017,6 +24024,43 @@ func (q *sqlQuerier) UpdateOrganizationDeletedByID(ctx context.Context, arg Upda return err } +const updateOrganizationMembersCanDisableSkills = `-- name: UpdateOrganizationMembersCanDisableSkills :one +UPDATE + organizations +SET + members_can_disable_skills = $1, + updated_at = $2 +WHERE + id = $3 +RETURNING id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles, members_can_disable_skills +` + +type UpdateOrganizationMembersCanDisableSkillsParams struct { + MembersCanDisableSkills bool `db:"members_can_disable_skills" json:"members_can_disable_skills"` + UpdatedAt time.Time `db:"updated_at" json:"updated_at"` + ID uuid.UUID `db:"id" json:"id"` +} + +func (q *sqlQuerier) UpdateOrganizationMembersCanDisableSkills(ctx context.Context, arg UpdateOrganizationMembersCanDisableSkillsParams) (Organization, error) { + row := q.db.QueryRowContext(ctx, updateOrganizationMembersCanDisableSkills, arg.MembersCanDisableSkills, arg.UpdatedAt, arg.ID) + var i Organization + err := row.Scan( + &i.ID, + &i.Name, + &i.Description, + &i.CreatedAt, + &i.UpdatedAt, + &i.IsDefault, + &i.DisplayName, + &i.Icon, + &i.Deleted, + &i.ShareableWorkspaceOwners, + pq.Array(&i.DefaultOrgMemberRoles), + &i.MembersCanDisableSkills, + ) + return i, err +} + const updateOrganizationWorkspaceSharingSettings = `-- name: UpdateOrganizationWorkspaceSharingSettings :one UPDATE organizations @@ -24025,7 +24069,7 @@ SET updated_at = $2 WHERE id = $3 -RETURNING id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles +RETURNING id, name, description, created_at, updated_at, is_default, display_name, icon, deleted, shareable_workspace_owners, default_org_member_roles, members_can_disable_skills ` type UpdateOrganizationWorkspaceSharingSettingsParams struct { @@ -24049,6 +24093,7 @@ func (q *sqlQuerier) UpdateOrganizationWorkspaceSharingSettings(ctx context.Cont &i.Deleted, &i.ShareableWorkspaceOwners, pq.Array(&i.DefaultOrgMemberRoles), + &i.MembersCanDisableSkills, ) return i, err } @@ -28971,6 +29016,24 @@ func (q *sqlQuerier) UpsertWebpushVAPIDKeys(ctx context.Context, arg UpsertWebpu return err } +const deleteOrganizationMemberDisabledSkill = `-- name: DeleteOrganizationMemberDisabledSkill :exec +DELETE FROM organization_member_disabled_skills +WHERE organization_id = $1::uuid + AND user_id = $2::uuid + AND skill_id = $3::uuid +` + +type DeleteOrganizationMemberDisabledSkillParams struct { + OrganizationID uuid.UUID `db:"organization_id" json:"organization_id"` + UserID uuid.UUID `db:"user_id" json:"user_id"` + SkillID uuid.UUID `db:"skill_id" json:"skill_id"` +} + +func (q *sqlQuerier) DeleteOrganizationMemberDisabledSkill(ctx context.Context, arg DeleteOrganizationMemberDisabledSkillParams) error { + _, err := q.db.ExecContext(ctx, deleteOrganizationMemberDisabledSkill, arg.OrganizationID, arg.UserID, arg.SkillID) + return err +} + const deleteOrganizationSkillByOrganizationIDAndName = `-- name: DeleteOrganizationSkillByOrganizationIDAndName :one DELETE FROM skills WHERE organization_id = $1::uuid AND name = $2 @@ -29132,6 +29195,42 @@ func (q *sqlQuerier) GetOrganizationSkillByOrganizationIDAndName(ctx context.Con return i, err } +const getOrganizationSkillMemberPreferences = `-- name: GetOrganizationSkillMemberPreferences :one +SELECT + organizations.members_can_disable_skills, + COALESCE(s.all_skills_disabled, false)::boolean AS all_skills_disabled, + ARRAY( + SELECT skill_id + FROM organization_member_disabled_skills + WHERE organization_id = $1::uuid AND user_id = $2::uuid + ORDER BY skill_id + )::uuid[] AS disabled_skill_ids +FROM organizations +LEFT JOIN organization_member_skill_settings s + ON s.organization_id = organizations.id AND s.user_id = $2::uuid +WHERE organizations.id = $1::uuid +` + +type GetOrganizationSkillMemberPreferencesParams struct { + OrganizationID uuid.UUID `db:"organization_id" json:"organization_id"` + UserID uuid.UUID `db:"user_id" json:"user_id"` +} + +type GetOrganizationSkillMemberPreferencesRow struct { + MembersCanDisableSkills bool `db:"members_can_disable_skills" json:"members_can_disable_skills"` + AllSkillsDisabled bool `db:"all_skills_disabled" json:"all_skills_disabled"` + DisabledSkillIDs []uuid.UUID `db:"disabled_skill_ids" json:"disabled_skill_ids"` +} + +// Returns the organization's member opt-out setting and the member's stored +// choices. Members without stored choices get the defaults. +func (q *sqlQuerier) GetOrganizationSkillMemberPreferences(ctx context.Context, arg GetOrganizationSkillMemberPreferencesParams) (GetOrganizationSkillMemberPreferencesRow, error) { + row := q.db.QueryRowContext(ctx, getOrganizationSkillMemberPreferences, arg.OrganizationID, arg.UserID) + var i GetOrganizationSkillMemberPreferencesRow + err := row.Scan(&i.MembersCanDisableSkills, &i.AllSkillsDisabled, pq.Array(&i.DisabledSkillIDs)) + return i, err +} + const getProjectSkillByIDForUpdate = `-- name: GetProjectSkillByIDForUpdate :one SELECT id, user_id, name, description, content, created_at, updated_at, organization_id, project_id, enabled, group_acl, user_acl, action, model_invocable FROM skills @@ -29227,6 +29326,26 @@ func (q *sqlQuerier) GetUserSkillByUserIDAndName(ctx context.Context, arg GetUse return i, err } +const insertOrganizationMemberDisabledSkill = `-- name: InsertOrganizationMemberDisabledSkill :exec +INSERT INTO organization_member_disabled_skills (organization_id, user_id, skill_id) +SELECT $1::uuid, $2::uuid, skills.id +FROM skills +WHERE skills.id = $3::uuid AND skills.organization_id = $1::uuid +ON CONFLICT DO NOTHING +` + +type InsertOrganizationMemberDisabledSkillParams struct { + OrganizationID uuid.UUID `db:"organization_id" json:"organization_id"` + UserID uuid.UUID `db:"user_id" json:"user_id"` + SkillID uuid.UUID `db:"skill_id" json:"skill_id"` +} + +// Stores nothing unless the skill belongs to the organization. +func (q *sqlQuerier) InsertOrganizationMemberDisabledSkill(ctx context.Context, arg InsertOrganizationMemberDisabledSkillParams) error { + _, err := q.db.ExecContext(ctx, insertOrganizationMemberDisabledSkill, arg.OrganizationID, arg.UserID, arg.SkillID) + return err +} + const insertOrganizationSkill = `-- name: InsertOrganizationSkill :one INSERT INTO skills (id, organization_id, name, description, content, model_invocable, group_acl, user_acl) VALUES ($1::uuid, $2::uuid, $3::text, $4::text, $5::text, COALESCE($6::boolean, true), $7, $8) @@ -29717,6 +29836,24 @@ func (q *sqlQuerier) UpdateUserSkillByUserIDAndName(ctx context.Context, arg Upd return i, err } +const upsertOrganizationMemberSkillSettings = `-- name: UpsertOrganizationMemberSkillSettings :exec +INSERT INTO organization_member_skill_settings (organization_id, user_id, all_skills_disabled) +VALUES ($1::uuid, $2::uuid, $3::boolean) +ON CONFLICT (organization_id, user_id) DO UPDATE +SET all_skills_disabled = EXCLUDED.all_skills_disabled +` + +type UpsertOrganizationMemberSkillSettingsParams struct { + OrganizationID uuid.UUID `db:"organization_id" json:"organization_id"` + UserID uuid.UUID `db:"user_id" json:"user_id"` + AllSkillsDisabled bool `db:"all_skills_disabled" json:"all_skills_disabled"` +} + +func (q *sqlQuerier) UpsertOrganizationMemberSkillSettings(ctx context.Context, arg UpsertOrganizationMemberSkillSettingsParams) error { + _, err := q.db.ExecContext(ctx, upsertOrganizationMemberSkillSettings, arg.OrganizationID, arg.UserID, arg.AllSkillsDisabled) + return err +} + const cleanTailnetCoordinators = `-- name: CleanTailnetCoordinators :exec DELETE FROM tailnet_coordinators diff --git a/coderd/database/queries/organizations.sql b/coderd/database/queries/organizations.sql index 7c71c6b2bfb..1684a7b791d 100644 --- a/coderd/database/queries/organizations.sql +++ b/coderd/database/queries/organizations.sql @@ -135,6 +135,16 @@ WHERE id = @id RETURNING *; +-- name: UpdateOrganizationMembersCanDisableSkills :one +UPDATE + organizations +SET + members_can_disable_skills = @members_can_disable_skills, + updated_at = @updated_at +WHERE + id = @id +RETURNING *; + -- name: UpdateOrganizationDeletedByID :exec UPDATE organizations SET diff --git a/coderd/database/queries/skills.sql b/coderd/database/queries/skills.sql index 8b31cdd6d38..5361f9e28d0 100644 --- a/coderd/database/queries/skills.sql +++ b/coderd/database/queries/skills.sql @@ -120,3 +120,40 @@ SELECT * FROM skills WHERE id = @id::uuid AND project_id IS NOT NULL FOR UPDATE; + +-- name: GetOrganizationSkillMemberPreferences :one +-- Returns the organization's member opt-out setting and the member's stored +-- choices. Members without stored choices get the defaults. +SELECT + organizations.members_can_disable_skills, + COALESCE(s.all_skills_disabled, false)::boolean AS all_skills_disabled, + ARRAY( + SELECT skill_id + FROM organization_member_disabled_skills + WHERE organization_id = @organization_id::uuid AND user_id = @user_id::uuid + ORDER BY skill_id + )::uuid[] AS disabled_skill_ids +FROM organizations +LEFT JOIN organization_member_skill_settings s + ON s.organization_id = organizations.id AND s.user_id = @user_id::uuid +WHERE organizations.id = @organization_id::uuid; + +-- name: UpsertOrganizationMemberSkillSettings :exec +INSERT INTO organization_member_skill_settings (organization_id, user_id, all_skills_disabled) +VALUES (@organization_id::uuid, @user_id::uuid, @all_skills_disabled::boolean) +ON CONFLICT (organization_id, user_id) DO UPDATE +SET all_skills_disabled = EXCLUDED.all_skills_disabled; + +-- name: InsertOrganizationMemberDisabledSkill :exec +-- Stores nothing unless the skill belongs to the organization. +INSERT INTO organization_member_disabled_skills (organization_id, user_id, skill_id) +SELECT @organization_id::uuid, @user_id::uuid, skills.id +FROM skills +WHERE skills.id = @skill_id::uuid AND skills.organization_id = @organization_id::uuid +ON CONFLICT DO NOTHING; + +-- name: DeleteOrganizationMemberDisabledSkill :exec +DELETE FROM organization_member_disabled_skills +WHERE organization_id = @organization_id::uuid + AND user_id = @user_id::uuid + AND skill_id = @skill_id::uuid; diff --git a/coderd/database/sqlc.yaml b/coderd/database/sqlc.yaml index eda792d10f0..f67a9c29f21 100644 --- a/coderd/database/sqlc.yaml +++ b/coderd/database/sqlc.yaml @@ -314,6 +314,7 @@ sql: mcp_server_tool_snapshots: MCPServerToolSnapshots mcp_server_config_id: MCPServerConfigID mcp_server_ids: MCPServerIDs + disabled_skill_ids: DisabledSkillIDs max_file_links: MaxFileLinks icon_url: IconURL oauth2_client_id: OAuth2ClientID diff --git a/coderd/database/unique_constraint.go b/coderd/database/unique_constraint.go index cfe3ddff18a..1bf1c9b0fd0 100644 --- a/coderd/database/unique_constraint.go +++ b/coderd/database/unique_constraint.go @@ -82,6 +82,8 @@ const ( UniqueOauth2ProviderAppTokensHashPrefixKey UniqueConstraint = "oauth2_provider_app_tokens_hash_prefix_key" // ALTER TABLE ONLY oauth2_provider_app_tokens ADD CONSTRAINT oauth2_provider_app_tokens_hash_prefix_key UNIQUE (hash_prefix); UniqueOauth2ProviderAppTokensPkey UniqueConstraint = "oauth2_provider_app_tokens_pkey" // ALTER TABLE ONLY oauth2_provider_app_tokens ADD CONSTRAINT oauth2_provider_app_tokens_pkey PRIMARY KEY (id); UniqueOauth2ProviderAppsPkey UniqueConstraint = "oauth2_provider_apps_pkey" // ALTER TABLE ONLY oauth2_provider_apps ADD CONSTRAINT oauth2_provider_apps_pkey PRIMARY KEY (id); + UniqueOrganizationMemberDisabledSkillsPkey UniqueConstraint = "organization_member_disabled_skills_pkey" // ALTER TABLE ONLY organization_member_disabled_skills ADD CONSTRAINT organization_member_disabled_skills_pkey PRIMARY KEY (organization_id, user_id, skill_id); + UniqueOrganizationMemberSkillSettingsPkey UniqueConstraint = "organization_member_skill_settings_pkey" // ALTER TABLE ONLY organization_member_skill_settings ADD CONSTRAINT organization_member_skill_settings_pkey PRIMARY KEY (organization_id, user_id); UniqueOrganizationMembersPkey UniqueConstraint = "organization_members_pkey" // ALTER TABLE ONLY organization_members ADD CONSTRAINT organization_members_pkey PRIMARY KEY (organization_id, user_id); UniqueOrganizationsPkey UniqueConstraint = "organizations_pkey" // ALTER TABLE ONLY organizations ADD CONSTRAINT organizations_pkey PRIMARY KEY (id); UniqueParameterSchemasJobIDNameKey UniqueConstraint = "parameter_schemas_job_id_name_key" // ALTER TABLE ONLY parameter_schemas ADD CONSTRAINT parameter_schemas_job_id_name_key UNIQUE (job_id, name); diff --git a/coderd/database/user_skills_test.go b/coderd/database/user_skills_test.go index e2aaa117774..a6a8bbb1acf 100644 --- a/coderd/database/user_skills_test.go +++ b/coderd/database/user_skills_test.go @@ -513,3 +513,110 @@ func TestProjectSkillQueries(t *testing.T) { require.NoError(t, err) require.Equal(t, skill.ID, deleted.ID) } + +func TestOrganizationSkillMemberPreferencesExcludes(t *testing.T) { + t.Parallel() + + skillID := uuid.New() + otherSkillID := uuid.New() + for _, tc := range []struct { + name string + prefs database.GetOrganizationSkillMemberPreferencesRow + wantSkill bool + wantOthers bool + }{ + { + name: "SettingOffIgnoresChoices", + prefs: database.GetOrganizationSkillMemberPreferencesRow{AllSkillsDisabled: true, DisabledSkillIDs: []uuid.UUID{skillID}}, + }, + { + name: "SettingOnNoChoices", + prefs: database.GetOrganizationSkillMemberPreferencesRow{MembersCanDisableSkills: true}, + }, + { + name: "SettingOnSkillOptedOut", + prefs: database.GetOrganizationSkillMemberPreferencesRow{MembersCanDisableSkills: true, DisabledSkillIDs: []uuid.UUID{skillID}}, + wantSkill: true, + }, + { + name: "SettingOnAllSkillsDisabled", + prefs: database.GetOrganizationSkillMemberPreferencesRow{MembersCanDisableSkills: true, AllSkillsDisabled: true}, + wantSkill: true, + wantOthers: true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + require.Equal(t, tc.wantSkill, tc.prefs.Excludes(skillID)) + require.Equal(t, tc.wantOthers, tc.prefs.Excludes(otherSkillID)) + }) + } +} + +func TestOrganizationSkillMemberPreferences(t *testing.T) { + t.Parallel() + if testing.Short() { + t.SkipNow() + } + + ctx := testutil.Context(t, testutil.WaitLong) + db, _ := dbtestutil.NewDB(t) + + org := dbgen.Organization(t, db, database.Organization{}) + otherOrg := dbgen.Organization(t, db, database.Organization{}) + user := dbgen.User(t, db, database.User{}) + dbgen.OrganizationMember(t, db, database.OrganizationMember{UserID: user.ID, OrganizationID: org.ID}) + dbgen.OrganizationMember(t, db, database.OrganizationMember{UserID: user.ID, OrganizationID: otherOrg.ID}) + skill := dbgen.OrganizationSkill(t, db, database.Skill{OrganizationID: uuid.NullUUID{UUID: org.ID, Valid: true}}) + deletedSkill := dbgen.OrganizationSkill(t, db, database.Skill{OrganizationID: uuid.NullUUID{UUID: org.ID, Valid: true}}) + foreignSkill := dbgen.OrganizationSkill(t, db, database.Skill{OrganizationID: uuid.NullUUID{UUID: otherOrg.ID, Valid: true}}) + + get := func(orgID uuid.UUID) database.GetOrganizationSkillMemberPreferencesRow { + t.Helper() + prefs, err := db.GetOrganizationSkillMemberPreferences(ctx, database.GetOrganizationSkillMemberPreferencesParams{ + OrganizationID: orgID, + UserID: user.ID, + }) + require.NoError(t, err) + return prefs + } + disable := func(orgID, skillID uuid.UUID) { + t.Helper() + require.NoError(t, db.InsertOrganizationMemberDisabledSkill(ctx, database.InsertOrganizationMemberDisabledSkillParams{ + OrganizationID: orgID, + UserID: user.ID, + SkillID: skillID, + })) + } + + require.Equal(t, database.GetOrganizationSkillMemberPreferencesRow{DisabledSkillIDs: []uuid.UUID{}}, get(org.ID)) + + require.NoError(t, db.UpsertOrganizationMemberSkillSettings(ctx, database.UpsertOrganizationMemberSkillSettingsParams{ + OrganizationID: org.ID, + UserID: user.ID, + AllSkillsDisabled: true, + })) + disable(org.ID, skill.ID) + disable(org.ID, deletedSkill.ID) + // A skill owned by another organization is never stored. + disable(org.ID, foreignSkill.ID) + require.ElementsMatch(t, []uuid.UUID{skill.ID, deletedSkill.ID}, get(org.ID).DisabledSkillIDs) + require.True(t, get(org.ID).AllSkillsDisabled) + + // Deleting a skill deletes every opt-out of it. + _, err := db.DeleteOrganizationSkillByOrganizationIDAndName(ctx, database.DeleteOrganizationSkillByOrganizationIDAndNameParams{ + OrganizationID: org.ID, + Name: deletedSkill.Name, + }) + require.NoError(t, err) + require.Equal(t, []uuid.UUID{skill.ID}, get(org.ID).DisabledSkillIDs) + + // Leaving the organization deletes the member's choices there only. + disable(otherOrg.ID, foreignSkill.ID) + require.NoError(t, db.DeleteOrganizationMember(ctx, database.DeleteOrganizationMemberParams{ + OrganizationID: org.ID, + UserID: user.ID, + })) + require.Equal(t, database.GetOrganizationSkillMemberPreferencesRow{DisabledSkillIDs: []uuid.UUID{}}, get(org.ID)) + require.Equal(t, []uuid.UUID{foreignSkill.ID}, get(otherOrg.ID).DisabledSkillIDs) +} diff --git a/coderd/organizationskillpreferences.go b/coderd/organizationskillpreferences.go new file mode 100644 index 00000000000..3056a7b99bf --- /dev/null +++ b/coderd/organizationskillpreferences.go @@ -0,0 +1,314 @@ +package coderd + +import ( + "bytes" + "context" + "fmt" + "net/http" + "slices" + "strings" + + "github.com/google/uuid" + "golang.org/x/xerrors" + + "github.com/coder/coder/v2/coderd/audit" + "github.com/coder/coder/v2/coderd/database" + "github.com/coder/coder/v2/coderd/database/dbauthz" + "github.com/coder/coder/v2/coderd/database/dbtime" + "github.com/coder/coder/v2/coderd/httpapi" + "github.com/coder/coder/v2/coderd/httpmw" + "github.com/coder/coder/v2/coderd/rbac" + "github.com/coder/coder/v2/coderd/rbac/policy" + "github.com/coder/coder/v2/codersdk" +) + +// @Summary Get organization skill settings +// @ID get-organization-skill-settings +// @Security CoderSessionToken +// @Produce json +// @Tags Organizations +// @Param organization path string true "Organization ID or name" +// @Success 200 {object} codersdk.OrganizationSkillSettings +// @Router /api/experimental/organizations/{organization}/skill-settings [get] +// @x-apidocgen {"skip": true} +func (api *API) getOrganizationSkillSettings(rw http.ResponseWriter, r *http.Request) { //nolint:revive // Method name matches route. + organization := httpmw.OrganizationParam(r) + httpapi.Write(r.Context(), rw, http.StatusOK, codersdk.OrganizationSkillSettings{ + MembersCanDisableSkills: organization.MembersCanDisableSkills, + }) +} + +// @Summary Update organization skill settings +// @ID update-organization-skill-settings +// @Security CoderSessionToken +// @Accept json +// @Produce json +// @Tags Organizations +// @Param organization path string true "Organization ID or name" +// @Param request body codersdk.UpdateOrganizationSkillSettingsRequest true "Update organization skill settings request" +// @Success 200 {object} codersdk.OrganizationSkillSettings +// @Router /api/experimental/organizations/{organization}/skill-settings [put] +// @x-apidocgen {"skip": true} +func (api *API) putOrganizationSkillSettings(rw http.ResponseWriter, r *http.Request) { + var ( + ctx = r.Context() + organization = httpmw.OrganizationParam(r) + auditor = api.Auditor.Load() + aReq, commitAudit = audit.InitRequest[database.Organization](rw, &audit.RequestParams{ + Audit: *auditor, + Log: api.Logger, + Request: r, + Action: database.AuditActionWrite, + OrganizationID: organization.ID, + }) + ) + defer commitAudit() + aReq.Old = organization + if !api.Authorize(r, policy.ActionUpdate, rbac.ResourceOrganizationSkill.InOrg(organization.ID)) { + httpapi.Write(ctx, rw, http.StatusForbidden, organizationSkillForbidden("update organization skill settings")) + return + } + + var req codersdk.UpdateOrganizationSkillSettingsRequest + if !httpapi.Read(ctx, rw, r, &req) { + return + } + updated, err := api.Database.UpdateOrganizationMembersCanDisableSkills(ctx, database.UpdateOrganizationMembersCanDisableSkillsParams{ + ID: organization.ID, + MembersCanDisableSkills: req.MembersCanDisableSkills, + UpdatedAt: dbtime.Now(), + }) + if err != nil { + httpapi.InternalServerError(rw, err) + return + } + aReq.New = updated + + httpapi.Write(ctx, rw, http.StatusOK, codersdk.OrganizationSkillSettings{ + MembersCanDisableSkills: updated.MembersCanDisableSkills, + }) +} + +// @Summary Get organization skill preferences for a member +// @ID get-organization-skill-preferences-for-a-member +// @Security CoderSessionToken +// @Produce json +// @Tags Organizations +// @Param organization path string true "Organization ID or name" +// @Param user path string true "User ID, name, or me" +// @Success 200 {object} codersdk.OrganizationSkillPreferences +// @Router /api/experimental/organizations/{organization}/members/{user}/skill-preferences [get] +// @x-apidocgen {"skip": true} +func (api *API) getOrganizationSkillPreferences(rw http.ResponseWriter, r *http.Request) { //nolint:revive // Method name matches route. + ctx := r.Context() + member := httpmw.OrganizationMemberParam(r) + + prefs, err := api.Database.GetOrganizationSkillMemberPreferences(ctx, database.GetOrganizationSkillMemberPreferencesParams{ + OrganizationID: member.OrganizationID, + UserID: member.UserID, + }) + if err != nil { + if httpapi.Is404Error(err) { + httpapi.ResourceNotFound(rw) + return + } + httpapi.InternalServerError(rw, err) + return + } + httpapi.Write(ctx, rw, http.StatusOK, organizationSkillPreferences(prefs)) +} + +// @Summary Update organization skill preferences for a member +// @ID update-organization-skill-preferences-for-a-member +// @Security CoderSessionToken +// @Accept json +// @Produce json +// @Tags Organizations +// @Param organization path string true "Organization ID or name" +// @Param user path string true "User ID, name, or me" +// @Param request body codersdk.UpdateOrganizationSkillPreferencesRequest true "Update organization skill preferences request" +// @Success 200 {object} codersdk.OrganizationSkillPreferences +// @Router /api/experimental/organizations/{organization}/members/{user}/skill-preferences [patch] +// @x-apidocgen {"skip": true} +func (api *API) patchOrganizationSkillPreferences(rw http.ResponseWriter, r *http.Request) { + var ( + ctx = r.Context() + organization = httpmw.OrganizationParam(r) + member = httpmw.OrganizationMemberParam(r) + ) + if !api.Authorize(r, policy.ActionUpdatePersonal, rbac.ResourceUserObject(member.UserID)) { + httpapi.ResourceNotFound(rw) + return + } + if !organization.MembersCanDisableSkills { + httpapi.Write(ctx, rw, http.StatusForbidden, codersdk.Response{ + Message: "Members cannot turn off organization skills in this organization.", + Detail: "An organization admin must let members turn off organization skills first.", + }) + return + } + + var req codersdk.UpdateOrganizationSkillPreferencesRequest + if !httpapi.Read(ctx, rw, r, &req) { + return + } + if req.AllSkillsDisabled == nil && len(req.Skills) == 0 { + httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ + Message: "Invalid request to update organization skill preferences.", + Detail: "Set all_skills_disabled or at least one entry in skills.", + }) + return + } + + skillIDs, validations, err := api.parseOrganizationSkillPreferenceIDs(ctx, organization.ID, member.UserID, req.Skills) + if err != nil { + httpapi.InternalServerError(rw, err) + return + } + if len(validations) > 0 { + httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ + Message: "Invalid request to update organization skill preferences.", + Validations: validations, + }) + return + } + + err = api.Database.InTx(func(tx database.Store) error { + if req.AllSkillsDisabled != nil { + err := tx.UpsertOrganizationMemberSkillSettings(ctx, database.UpsertOrganizationMemberSkillSettingsParams{ + OrganizationID: member.OrganizationID, + UserID: member.UserID, + AllSkillsDisabled: *req.AllSkillsDisabled, + }) + if err != nil { + return xerrors.Errorf("upsert organization member skill settings: %w", err) + } + } + for _, skill := range skillIDs { + if skill.enabled { + err := tx.DeleteOrganizationMemberDisabledSkill(ctx, database.DeleteOrganizationMemberDisabledSkillParams{ + OrganizationID: member.OrganizationID, + UserID: member.UserID, + SkillID: skill.id, + }) + if err != nil { + return xerrors.Errorf("delete organization member disabled skill: %w", err) + } + continue + } + err := tx.InsertOrganizationMemberDisabledSkill(ctx, database.InsertOrganizationMemberDisabledSkillParams{ + OrganizationID: member.OrganizationID, + UserID: member.UserID, + SkillID: skill.id, + }) + if err != nil { + return xerrors.Errorf("insert organization member disabled skill: %w", err) + } + } + return nil + }, nil) + if err != nil { + httpapi.InternalServerError(rw, err) + return + } + + prefs, err := api.Database.GetOrganizationSkillMemberPreferences(ctx, database.GetOrganizationSkillMemberPreferencesParams{ + OrganizationID: member.OrganizationID, + UserID: member.UserID, + }) + if err != nil { + httpapi.InternalServerError(rw, err) + return + } + httpapi.Write(ctx, rw, http.StatusOK, organizationSkillPreferences(prefs)) +} + +type organizationSkillPreferenceChange struct { + id uuid.UUID + enabled bool +} + +// parseOrganizationSkillPreferenceIDs validates that every key names an +// organization skill of the organization that the member can read, and +// returns the changes sorted by skill ID. +func (api *API) parseOrganizationSkillPreferenceIDs(ctx context.Context, organizationID, memberID uuid.UUID, choices map[string]bool) ([]organizationSkillPreferenceChange, []codersdk.ValidationError, error) { + if len(choices) == 0 { + return nil, nil, nil + } + + // Owners and user admins can edit another member's choices, so check + // the skills against what that member can read, as chatd does. + member, _, err := httpmw.UserRBACSubject(ctx, api.Database, memberID, rbac.ScopeAll) + if err != nil { + return nil, nil, xerrors.Errorf("load member authorization: %w", err) + } + + //nolint:gocritic // Org skill ACLs are evaluated against the member. + rows, err := api.Database.ListOrganizationSkillMetadataByOrganizationID(dbauthz.As(ctx, member), organizationID) + if err != nil { + return nil, nil, xerrors.Errorf("list organization skill metadata: %w", err) + } + readable := make(map[uuid.UUID]struct{}, len(rows)) + for _, row := range rows { + readable[row.ID] = struct{}{} + } + + var ( + keysByID = make(map[uuid.UUID][]string, len(choices)) + validations []codersdk.ValidationError + ) + for key := range choices { + field := "skills." + key + id, err := uuid.Parse(key) + if err != nil { + validations = append(validations, codersdk.ValidationError{ + Field: field, + Detail: fmt.Sprintf("%q is not a valid skill ID.", key), + }) + continue + } + if _, ok := readable[id]; !ok { + validations = append(validations, codersdk.ValidationError{ + Field: field, + Detail: "No organization skill with this ID exists in this organization.", + }) + continue + } + keysByID[id] = append(keysByID[id], key) + } + changes := make([]organizationSkillPreferenceChange, 0, len(keysByID)) + for id, keys := range keysByID { + // uuid.Parse accepts several spellings of one ID, so two keys can + // name the same skill. Reject them instead of letting map order + // pick the stored value. + if len(keys) > 1 { + for _, key := range keys { + validations = append(validations, codersdk.ValidationError{ + Field: "skills." + key, + Detail: "Another key in skills names the same skill.", + }) + } + continue + } + changes = append(changes, organizationSkillPreferenceChange{id: id, enabled: choices[keys[0]]}) + } + slices.SortFunc(validations, func(a, b codersdk.ValidationError) int { + return strings.Compare(a.Field, b.Field) + }) + slices.SortFunc(changes, func(a, b organizationSkillPreferenceChange) int { + return bytes.Compare(a.id[:], b.id[:]) + }) + return changes, validations, nil +} + +func organizationSkillPreferences(prefs database.GetOrganizationSkillMemberPreferencesRow) codersdk.OrganizationSkillPreferences { + disabled := prefs.DisabledSkillIDs + if disabled == nil { + disabled = []uuid.UUID{} + } + return codersdk.OrganizationSkillPreferences{ + MembersCanDisableSkills: prefs.MembersCanDisableSkills, + AllSkillsDisabled: prefs.AllSkillsDisabled, + DisabledSkillIDs: disabled, + } +} diff --git a/coderd/organizationskillpreferences_test.go b/coderd/organizationskillpreferences_test.go new file mode 100644 index 00000000000..e48426dbda4 --- /dev/null +++ b/coderd/organizationskillpreferences_test.go @@ -0,0 +1,207 @@ +package coderd_test + +import ( + "encoding/json" + "net/http" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/coder/coder/v2/coderd/audit" + "github.com/coder/coder/v2/coderd/coderdtest" + "github.com/coder/coder/v2/coderd/database" + "github.com/coder/coder/v2/coderd/database/dbgen" + "github.com/coder/coder/v2/coderd/database/dbtestutil" + "github.com/coder/coder/v2/coderd/rbac" + "github.com/coder/coder/v2/coderd/rbac/policy" + "github.com/coder/coder/v2/coderd/util/ptr" + "github.com/coder/coder/v2/codersdk" + "github.com/coder/coder/v2/testutil" +) + +func TestOrganizationSkillSettings(t *testing.T) { + t.Parallel() + + auditor := audit.NewMockWithDiffFn(func(old, newVal any) audit.Map { + oldOrg, oldOK := old.(database.Organization) + newOrg, newOK := newVal.(database.Organization) + if !oldOK || !newOK { + return audit.Map{} + } + return audit.Map{"members_can_disable_skills": {Old: oldOrg.MembersCanDisableSkills, New: newOrg.MembersCanDisableSkills}} + }) + ownerClient := coderdtest.New(t, &coderdtest.Options{Auditor: auditor}) + firstUser := coderdtest.CreateFirstUser(t, ownerClient) + orgID := firstUser.OrganizationID + memberRawClient, _ := coderdtest.CreateAnotherUser(t, ownerClient, orgID) + member := codersdk.NewExperimentalClient(memberRawClient) + adminRawClient, _ := coderdtest.CreateAnotherUser(t, ownerClient, orgID, rbac.ScopedRoleOrgAdmin(orgID)) + admin := codersdk.NewExperimentalClient(adminRawClient) + ctx := testutil.Context(t, testutil.WaitMedium) + + settings, err := member.OrganizationSkillSettings(ctx, orgID) + require.NoError(t, err) + require.False(t, settings.MembersCanDisableSkills) + + _, err = member.UpdateOrganizationSkillSettings(ctx, orgID, codersdk.UpdateOrganizationSkillSettingsRequest{MembersCanDisableSkills: true}) + sdkErr := requireSDKErrorStatus(t, err, http.StatusForbidden) + assert.Equal(t, "You don't have permission to update organization skill settings.", sdkErr.Message) + + auditor.ResetLogs() + settings, err = admin.UpdateOrganizationSkillSettings(ctx, orgID, codersdk.UpdateOrganizationSkillSettingsRequest{MembersCanDisableSkills: true}) + require.NoError(t, err) + require.True(t, settings.MembersCanDisableSkills) + settings, err = member.OrganizationSkillSettings(ctx, orgID) + require.NoError(t, err) + require.True(t, settings.MembersCanDisableSkills) + + logs := auditor.AuditLogs() + require.Len(t, logs, 1) + assert.Equal(t, database.AuditActionWrite, logs[0].Action) + assert.Equal(t, database.ResourceTypeOrganization, logs[0].ResourceType) + assert.Equal(t, orgID, logs[0].ResourceID) + assert.EqualValues(t, http.StatusOK, logs[0].StatusCode) + var diff map[string]codersdk.AuditDiffField + require.NoError(t, json.Unmarshal(logs[0].Diff, &diff)) + assert.Equal(t, false, diff["members_can_disable_skills"].Old) + assert.Equal(t, true, diff["members_can_disable_skills"].New) +} + +func TestOrganizationSkillPreferences(t *testing.T) { + t.Parallel() + + db, ps := dbtestutil.NewDB(t) + ownerRawClient := coderdtest.New(t, &coderdtest.Options{Database: db, Pubsub: ps}) + firstUser := coderdtest.CreateFirstUser(t, ownerRawClient) + orgID := firstUser.OrganizationID + owner := codersdk.NewExperimentalClient(ownerRawClient) + memberRawClient, memberUser := coderdtest.CreateAnotherUser(t, ownerRawClient, orgID) + member := codersdk.NewExperimentalClient(memberRawClient) + _, otherUser := coderdtest.CreateAnotherUser(t, ownerRawClient, orgID) + + everyone := database.ChatACL{orgID.String(): {Permissions: []policy.Action{policy.ActionRead}}} + orgSkill := func(orgID uuid.UUID, acl database.ChatACL) database.Skill { + return dbgen.OrganizationSkill(t, db, database.Skill{ + OrganizationID: uuid.NullUUID{UUID: orgID, Valid: true}, + GroupACL: acl, + UserACL: database.ChatACL{}, + }) + } + first := orgSkill(orgID, everyone) + second := orgSkill(orgID, everyone) + private := orgSkill(orgID, database.ChatACL{}) + otherOrg := dbgen.Organization(t, db, database.Organization{}) + foreign := orgSkill(otherOrg.ID, database.ChatACL{otherOrg.ID.String(): {Permissions: []policy.Action{policy.ActionRead}}}) + ctx := testutil.Context(t, testutil.WaitLong) + + prefs, err := member.OrganizationSkillPreferences(ctx, orgID, codersdk.Me) + require.NoError(t, err) + require.Equal(t, codersdk.OrganizationSkillPreferences{DisabledSkillIDs: []uuid.UUID{}}, prefs) + + // Members cannot see or change another member's choices. + _, err = member.OrganizationSkillPreferences(ctx, orgID, otherUser.ID.String()) + requireSDKErrorStatus(t, err, http.StatusNotFound) + _, err = member.UpdateOrganizationSkillPreferences(ctx, orgID, otherUser.ID.String(), codersdk.UpdateOrganizationSkillPreferencesRequest{ + AllSkillsDisabled: ptr.Ref(true), + }) + requireSDKErrorStatus(t, err, http.StatusNotFound) + + _, err = member.UpdateOrganizationSkillPreferences(ctx, orgID, codersdk.Me, codersdk.UpdateOrganizationSkillPreferencesRequest{ + AllSkillsDisabled: ptr.Ref(true), + }) + requireSDKErrorStatus(t, err, http.StatusForbidden) + + _, err = owner.UpdateOrganizationSkillSettings(ctx, orgID, codersdk.UpdateOrganizationSkillSettingsRequest{MembersCanDisableSkills: true}) + require.NoError(t, err) + + _, err = member.UpdateOrganizationSkillPreferences(ctx, orgID, codersdk.Me, codersdk.UpdateOrganizationSkillPreferencesRequest{}) + requireSDKErrorStatus(t, err, http.StatusBadRequest) + for name, key := range map[string]string{ + "NotUUID": "not-a-uuid", + "Unknown": uuid.NewString(), + "Unreadable": private.ID.String(), + "OtherOrg": foreign.ID.String(), + } { + _, err := member.UpdateOrganizationSkillPreferences(ctx, orgID, codersdk.Me, codersdk.UpdateOrganizationSkillPreferencesRequest{ + Skills: map[string]bool{key: false, first.ID.String(): false}, + }) + sdkErr := requireSDKErrorStatus(t, err, http.StatusBadRequest, name) + require.Len(t, sdkErr.Validations, 1, name) + require.Equal(t, "skills."+key, sdkErr.Validations[0].Field, name) + } + // Two spellings of one skill ID make the request ambiguous. + braced := "{" + first.ID.String() + "}" + _, err = member.UpdateOrganizationSkillPreferences(ctx, orgID, codersdk.Me, codersdk.UpdateOrganizationSkillPreferencesRequest{ + Skills: map[string]bool{first.ID.String(): false, braced: true}, + }) + sdkErr := requireSDKErrorStatus(t, err, http.StatusBadRequest) + require.Len(t, sdkErr.Validations, 2) + require.ElementsMatch(t, []string{"skills." + first.ID.String(), "skills." + braced}, []string{sdkErr.Validations[0].Field, sdkErr.Validations[1].Field}) + // A rejected request stores nothing. + prefs, err = member.OrganizationSkillPreferences(ctx, orgID, codersdk.Me) + require.NoError(t, err) + require.Empty(t, prefs.DisabledSkillIDs) + + update := func(req codersdk.UpdateOrganizationSkillPreferencesRequest) codersdk.OrganizationSkillPreferences { + t.Helper() + prefs, err := member.UpdateOrganizationSkillPreferences(ctx, orgID, codersdk.Me, req) + require.NoError(t, err) + require.True(t, prefs.MembersCanDisableSkills) + return prefs + } + prefs = update(codersdk.UpdateOrganizationSkillPreferencesRequest{ + Skills: map[string]bool{first.ID.String(): false, second.ID.String(): false}, + }) + require.ElementsMatch(t, []uuid.UUID{first.ID, second.ID}, prefs.DisabledSkillIDs) + require.False(t, prefs.AllSkillsDisabled) + + // Only the listed skills change. + prefs = update(codersdk.UpdateOrganizationSkillPreferencesRequest{ + Skills: map[string]bool{first.ID.String(): true}, + }) + require.Equal(t, []uuid.UUID{second.ID}, prefs.DisabledSkillIDs) + + // The master switch keeps the per-skill choices, and a later per-skill + // change keeps the master switch. + prefs = update(codersdk.UpdateOrganizationSkillPreferencesRequest{AllSkillsDisabled: ptr.Ref(true)}) + require.True(t, prefs.AllSkillsDisabled) + require.Equal(t, []uuid.UUID{second.ID}, prefs.DisabledSkillIDs) + prefs = update(codersdk.UpdateOrganizationSkillPreferencesRequest{ + Skills: map[string]bool{second.ID.String(): true}, + }) + require.True(t, prefs.AllSkillsDisabled) + require.Empty(t, prefs.DisabledSkillIDs) + + // Site owners can read another user's choices, like other personal + // settings. + prefs, err = owner.OrganizationSkillPreferences(ctx, orgID, memberUser.ID.String()) + require.NoError(t, err) + require.True(t, prefs.AllSkillsDisabled) + + // An owner editing a member's choices is limited to the skills that + // member can read, even though the owner can read every skill. + _, err = owner.UpdateOrganizationSkillPreferences(ctx, orgID, memberUser.ID.String(), codersdk.UpdateOrganizationSkillPreferencesRequest{ + Skills: map[string]bool{private.ID.String(): false}, + }) + sdkErr = requireSDKErrorStatus(t, err, http.StatusBadRequest) + require.Len(t, sdkErr.Validations, 1) + require.Equal(t, "skills."+private.ID.String(), sdkErr.Validations[0].Field) + + prefs, err = owner.UpdateOrganizationSkillPreferences(ctx, orgID, memberUser.ID.String(), codersdk.UpdateOrganizationSkillPreferencesRequest{ + Skills: map[string]bool{first.ID.String(): false}, + }) + require.NoError(t, err) + require.Equal(t, []uuid.UUID{first.ID}, prefs.DisabledSkillIDs) + + // A user admin outside the organization cannot read its skills, but + // can still change the skills the member can read. + userAdminRawClient, _ := coderdtest.CreateAnotherUser(t, ownerRawClient, otherOrg.ID, rbac.RoleUserAdmin()) + userAdmin := codersdk.NewExperimentalClient(userAdminRawClient) + prefs, err = userAdmin.UpdateOrganizationSkillPreferences(ctx, orgID, memberUser.ID.String(), codersdk.UpdateOrganizationSkillPreferencesRequest{ + Skills: map[string]bool{second.ID.String(): false}, + }) + require.NoError(t, err) + require.ElementsMatch(t, []uuid.UUID{first.ID, second.ID}, prefs.DisabledSkillIDs) +} diff --git a/coderd/x/chatd/chatd_internal_test.go b/coderd/x/chatd/chatd_internal_test.go index 6929f8e59f2..6013df2376d 100644 --- a/coderd/x/chatd/chatd_internal_test.go +++ b/coderd/x/chatd/chatd_internal_test.go @@ -2207,19 +2207,43 @@ func TestFetchPersonalSkillMetadata(t *testing.T) { }) } -func TestFetchOrganizationSkillMetadataListFailure(t *testing.T) { +func TestFetchOrganizationSkillMetadataFailure(t *testing.T) { t.Parallel() - ctrl := gomock.NewController(t) - db := dbmock.NewMockStore(ctrl) - server := &Server{db: db} - organizationID := uuid.New() - listErr := xerrors.New("boom") + t.Run("List", func(t *testing.T) { + t.Parallel() - db.EXPECT().ListOrganizationSkillMetadataByOrganizationID(gomock.Any(), organizationID).Return(nil, listErr) + ctrl := gomock.NewController(t) + db := dbmock.NewMockStore(ctrl) + server := &Server{db: db} + organizationID := uuid.New() + listErr := xerrors.New("boom") - _, err := server.fetchOrganizationSkillMetadata(context.Background(), rbac.Subject{ID: uuid.NewString()}, organizationID) - require.ErrorIs(t, err, listErr) + db.EXPECT().ListOrganizationSkillMetadataByOrganizationID(gomock.Any(), organizationID).Return(nil, listErr) + + _, err := server.fetchOrganizationSkillMetadata(context.Background(), rbac.Subject{ID: uuid.NewString()}, uuid.New(), organizationID) + require.ErrorIs(t, err, listErr) + }) + + t.Run("MemberPreferences", func(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + db := dbmock.NewMockStore(ctrl) + server := &Server{db: db} + organizationID := uuid.New() + ownerID := uuid.New() + prefsErr := xerrors.New("boom") + + db.EXPECT().ListOrganizationSkillMetadataByOrganizationID(gomock.Any(), organizationID).Return(nil, nil) + db.EXPECT().GetOrganizationSkillMemberPreferences(gomock.Any(), database.GetOrganizationSkillMemberPreferencesParams{ + OrganizationID: organizationID, + UserID: ownerID, + }).Return(database.GetOrganizationSkillMemberPreferencesRow{}, prefsErr) + + _, err := server.fetchOrganizationSkillMetadata(context.Background(), rbac.Subject{ID: ownerID.String()}, ownerID, organizationID) + require.ErrorIs(t, err, prefsErr) + }) } func TestLoadPersonalSkillBody(t *testing.T) { @@ -2416,6 +2440,25 @@ func TestLoadOrganizationSkillBody(t *testing.T) { Name: "disabled-review", }) require.NoError(t, err) + // The member turned off opted-out-review, and the organization lets + // members turn off organization skills. + optedOut := dbgen.OrganizationSkill(t, db, database.Skill{ + OrganizationID: uuid.NullUUID{UUID: org.ID, Valid: true}, + Name: "opted-out-review", + GroupACL: database.ChatACL{org.ID.String(): {Permissions: read}}, + UserACL: database.ChatACL{}, + }) + require.NoError(t, db.InsertOrganizationMemberDisabledSkill(ctx, database.InsertOrganizationMemberDisabledSkillParams{ + OrganizationID: org.ID, + UserID: member.ID, + SkillID: optedOut.ID, + })) + _, err = db.UpdateOrganizationMembersCanDisableSkills(ctx, database.UpdateOrganizationMembersCanDisableSkillsParams{ + ID: org.ID, + MembersCanDisableSkills: true, + UpdatedAt: dbtime.Now(), + }) + require.NoError(t, err) subject := func(userID uuid.UUID) rbac.Subject { t.Helper() @@ -2424,10 +2467,12 @@ func TestLoadOrganizationSkillBody(t *testing.T) { return got } - got, err := server.loadOrganizationSkillBody(ctx, subject(member.ID), org.ID, "team-review", skillLoaderModel) + got, err := server.loadOrganizationSkillBody(ctx, subject(member.ID), member.ID, org.ID, "team-review", skillLoaderModel) require.NoError(t, err) require.Equal(t, skillspkg.SourceOrganization, got.Source) require.Equal(t, "Team instructions.", got.Body) + _, err = server.loadOrganizationSkillBody(ctx, subject(outsider.ID), outsider.ID, org.ID, "opted-out-review", skillLoaderModel) + require.NoError(t, err) for _, tc := range []struct { name string @@ -2437,8 +2482,9 @@ func TestLoadOrganizationSkillBody(t *testing.T) { {name: "NotShared", reader: outsider.ID, skill: "team-review"}, {name: "Disabled", reader: member.ID, skill: "disabled-review"}, {name: "Missing", reader: member.ID, skill: "missing-review"}, + {name: "OptedOut", reader: member.ID, skill: "opted-out-review"}, } { - _, err := server.loadOrganizationSkillBody(ctx, subject(tc.reader), org.ID, tc.skill, skillLoaderModel) + _, err := server.loadOrganizationSkillBody(ctx, subject(tc.reader), tc.reader, org.ID, tc.skill, skillLoaderModel) require.ErrorIs(t, err, skillspkg.ErrSkillNotFound, tc.name) } } diff --git a/coderd/x/chatd/organization_skills_test.go b/coderd/x/chatd/organization_skills_test.go index e2a7cc1af2a..61c7b0efe9e 100644 --- a/coderd/x/chatd/organization_skills_test.go +++ b/coderd/x/chatd/organization_skills_test.go @@ -16,6 +16,7 @@ import ( "github.com/coder/coder/v2/coderd/database/dbauthz" "github.com/coder/coder/v2/coderd/database/dbgen" "github.com/coder/coder/v2/coderd/database/dbtestutil" + "github.com/coder/coder/v2/coderd/database/dbtime" "github.com/coder/coder/v2/coderd/httpmw" "github.com/coder/coder/v2/coderd/rbac" "github.com/coder/coder/v2/coderd/rbac/policy" @@ -245,3 +246,110 @@ func TestOrganizationSkillsFollowChatOwnerAccess(t *testing.T) { require.Contains(t, calls[0].system, "- org-wide: Org-wide process\n") require.Equal(t, `skill "team-review" not found`, calls[1].toolResults[len(calls[1].toolResults)-1]) } + +func TestOrganizationSkillsFollowMemberPreferences(t *testing.T) { + t.Parallel() + + db, ps := dbtestutil.NewDB(t) + ctx := testutil.Context(t, testutil.WaitLong) + recorder, openAIURL := newSkillRecordingOpenAI(t) + member, org, model := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL) + other := dbgen.User(t, db, database.User{}) + dbgen.OrganizationMember(t, db, database.OrganizationMember{UserID: other.ID, OrganizationID: org.ID}) + + everyone := database.ChatACL{org.ID.String(): {Permissions: []policy.Action{policy.ActionRead}}} + orgSkill := func(name string) database.Skill { + return dbgen.OrganizationSkill(t, db, database.Skill{ + OrganizationID: uuid.NullUUID{UUID: org.ID, Valid: true}, + Name: name, + Description: "Process " + name, + GroupACL: everyone, + UserACL: database.ChatACL{}, + }) + } + optedOut := orgSkill("opted-out") + orgSkill("kept") + require.NoError(t, db.InsertOrganizationMemberDisabledSkill(ctx, database.InsertOrganizationMemberDisabledSkillParams{ + OrganizationID: org.ID, + UserID: member.ID, + SkillID: optedOut.ID, + })) + setMembersCanDisable := func(enabled bool) { + t.Helper() + _, err := db.UpdateOrganizationMembersCanDisableSkills(ctx, database.UpdateOrganizationMembersCanDisableSkillsParams{ + ID: org.ID, + MembersCanDisableSkills: enabled, + UpdatedAt: dbtime.Now(), + }) + require.NoError(t, err) + } + + authzDB := dbauthz.New( + db, + rbac.NewStrictCachingAuthorizer(prometheus.NewRegistry()), + slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}), + coderdtest.AccessControlStorePointer(), + ) + server := newActiveTestServer(t, authzDB, ps, func(cfg *chatd.Config) { + cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL)) + }) + + runTurn := func(t *testing.T, userID uuid.UUID, text string) []skillRecordedCall { + t.Helper() + subject, _, err := httpmw.UserRBACSubject(dbauthz.AsSystemRestricted(ctx), db, userID, rbac.ScopeAll) + require.NoError(t, err) + before := len(recorder.recorded()) + chat, err := server.CreateChat(dbauthz.As(ctx, subject), chatd.CreateOptions{ + OrganizationID: org.ID, + OwnerID: userID, + Title: "org-skill-preferences", + ModelConfigID: model.ID, + InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText(text)}, + }) + require.NoError(t, err) + waitForChatProcessed(ctx, t, db, chat.ID, server) + chat, err = db.GetChatByID(ctx, chat.ID) + require.NoError(t, err) + require.NotEqual(t, database.ChatStatusError, chat.Status, "last_error=%q", chatLastErrorMessage(chat.LastError)) + return recorder.recorded()[before:] + } + + // While the setting is off, stored choices have no effect. + calls := runTurn(t, member.ID, "hello") + require.Len(t, calls, 1) + require.Contains(t, calls[0].system, "- opted-out: Process opted-out\n") + require.Contains(t, calls[0].system, "- kept: Process kept\n") + + // With the setting on, the opted-out skill leaves the member's index and + // read_skill, while another member still gets it. + setMembersCanDisable(true) + calls = runTurn(t, member.ID, readSkillsDirective+"opted-out,kept") + require.Len(t, calls, 2) + require.NotContains(t, calls[0].system, "opted-out") + require.Contains(t, calls[0].system, "- kept: Process kept\n") + require.Len(t, calls[1].toolResults, 2) + require.Equal(t, `skill "opted-out" not found`, calls[1].toolResults[0]) + require.Contains(t, calls[1].toolResults[1], "Fixture instructions.") + + calls = runTurn(t, other.ID, readSkillsDirective+"opted-out") + require.Len(t, calls, 2) + require.Contains(t, calls[0].system, "- opted-out: Process opted-out\n") + require.Contains(t, calls[1].toolResults[0], "Fixture instructions.") + + // The master switch excludes every organization skill, including one + // created after it was set. + require.NoError(t, db.UpsertOrganizationMemberSkillSettings(ctx, database.UpsertOrganizationMemberSkillSettingsParams{ + OrganizationID: org.ID, + UserID: member.ID, + AllSkillsDisabled: true, + })) + orgSkill("added-later") + calls = runTurn(t, member.ID, "hello") + require.Len(t, calls, 1) + for _, name := range []string{"opted-out", "kept", "added-later"} { + require.NotContains(t, calls[0].system, name) + } + calls = runTurn(t, other.ID, "hello") + require.Len(t, calls, 1) + require.Contains(t, calls[0].system, "- added-later: Process added-later\n") +} diff --git a/coderd/x/chatd/skill_invocation.go b/coderd/x/chatd/skill_invocation.go index 92e018cba9d..3951187bba6 100644 --- a/coderd/x/chatd/skill_invocation.go +++ b/coderd/x/chatd/skill_invocation.go @@ -100,7 +100,7 @@ func (p *Server) resolveSkillInvocations( if err != nil { return invokedSkill{}, err } - parsed, err := p.loadOrganizationSkillBody(ctx, owner, chat.OrganizationID, part.SkillName, skillLoaderUser) + parsed, err := p.loadOrganizationSkillBody(ctx, owner, chat.OwnerID, chat.OrganizationID, part.SkillName, skillLoaderUser) return invokedSkill{body: parsed.Body}, err case codersdk.ChatSkillSourceProject: // Read as chatd behind the chat owner's project usability check, diff --git a/coderd/x/chatd/skill_invocation_internal_test.go b/coderd/x/chatd/skill_invocation_internal_test.go index d7d3d10ca5f..40a86968923 100644 --- a/coderd/x/chatd/skill_invocation_internal_test.go +++ b/coderd/x/chatd/skill_invocation_internal_test.go @@ -19,6 +19,7 @@ import ( "github.com/coder/coder/v2/coderd/database/dbgen" "github.com/coder/coder/v2/coderd/database/dbmock" "github.com/coder/coder/v2/coderd/database/dbtestutil" + "github.com/coder/coder/v2/coderd/database/dbtime" "github.com/coder/coder/v2/coderd/rbac" "github.com/coder/coder/v2/coderd/rbac/policy" "github.com/coder/coder/v2/codersdk" @@ -70,7 +71,7 @@ func TestResolveSkillInvocations(t *testing.T) { }) require.NoError(t, err) } - dbgen.OrganizationSkill(t, db, database.Skill{ + teamReview := dbgen.OrganizationSkill(t, db, database.Skill{ OrganizationID: uuid.NullUUID{UUID: org.ID, Valid: true}, Name: "team-review", Content: skillMarkdown("team-review"), @@ -117,6 +118,21 @@ func TestResolveSkillInvocations(t *testing.T) { plainChat.ProjectID = uuid.NullUUID{} _, err = server.resolveSkillInvocations(ctx, plainChat, parts[3:]) requireUnavailable(t, err, "Skill project/triage is not available.") + + // An organization skill the owner turned off is not available. + require.NoError(t, db.InsertOrganizationMemberDisabledSkill(ctx, database.InsertOrganizationMemberDisabledSkillParams{ + OrganizationID: org.ID, + UserID: owner.ID, + SkillID: teamReview.ID, + })) + _, err = db.UpdateOrganizationMembersCanDisableSkills(ctx, database.UpdateOrganizationMembersCanDisableSkillsParams{ + ID: org.ID, + MembersCanDisableSkills: true, + UpdatedAt: dbtime.Now(), + }) + require.NoError(t, err) + _, err = server.resolveSkillInvocations(ctx, projectChat, parts[2:3]) + requireUnavailable(t, err, "Skill org/team-review is not available.") }) t.Run("WorkspaceFromPinnedContext", func(t *testing.T) { diff --git a/coderd/x/chatd/turn_environment.go b/coderd/x/chatd/turn_environment.go index bcc9c2ce10a..d7b625d7ae7 100644 --- a/coderd/x/chatd/turn_environment.go +++ b/coderd/x/chatd/turn_environment.go @@ -522,7 +522,7 @@ func (p *Server) buildTurnEnvironment( if err != nil { return err } - orgSkills, err = p.fetchOrganizationSkillMetadata(ctx, orgSkillReader, chat.OrganizationID) + orgSkills, err = p.fetchOrganizationSkillMetadata(ctx, orgSkillReader, chat.OwnerID, chat.OrganizationID) return err }) g2.Go(func() error { @@ -770,7 +770,7 @@ func (p *Server) buildTurnEnvironment( LoadStoredSkillBody: func(ctx context.Context, skill skillspkg.Skill) (skillspkg.ParsedSkill, error) { switch skill.Source { case skillspkg.SourceOrganization: - return p.loadOrganizationSkillBody(ctx, orgSkillReader, chat.OrganizationID, skill.Name, skillLoaderModel) + return p.loadOrganizationSkillBody(ctx, orgSkillReader, chat.OwnerID, chat.OrganizationID, skill.Name, skillLoaderModel) case skillspkg.SourceProject: return p.loadProjectSkillBody(ctx, usableProjectID.UUID, skill.Name, skillLoaderModel) default: @@ -2385,17 +2385,26 @@ func (p *Server) chatOwnerSubject(ctx context.Context, ownerID uuid.UUID) (rbac. func (p *Server) fetchOrganizationSkillMetadata( ctx context.Context, owner rbac.Subject, + ownerID uuid.UUID, organizationID uuid.UUID, ) ([]skillspkg.Skill, error) { //nolint:gocritic // Org skill ACLs are evaluated against the chat owner. - rows, err := p.db.ListOrganizationSkillMetadataByOrganizationID(dbauthz.As(ctx, owner), organizationID) + ownerCtx := dbauthz.As(ctx, owner) + rows, err := p.db.ListOrganizationSkillMetadataByOrganizationID(ownerCtx, organizationID) if err != nil { return nil, xerrors.Errorf("list organization skill metadata: %w", err) } + prefs, err := p.db.GetOrganizationSkillMemberPreferences(ownerCtx, database.GetOrganizationSkillMemberPreferencesParams{ + OrganizationID: organizationID, + UserID: ownerID, + }) + if err != nil { + return nil, xerrors.Errorf("get organization skill member preferences: %w", err) + } organizationSkills := make([]skillspkg.Skill, 0, len(rows)) for _, row := range rows { - if skillLoaderModel.hides(row.Enabled, row.ModelInvocable) { + if skillLoaderModel.hides(row.Enabled, row.ModelInvocable) || prefs.Excludes(row.ID) { continue } organizationSkills = append(organizationSkills, skillspkg.Skill{ @@ -2410,13 +2419,15 @@ func (p *Server) fetchOrganizationSkillMetadata( func (p *Server) loadOrganizationSkillBody( ctx context.Context, owner rbac.Subject, + ownerID uuid.UUID, organizationID uuid.UUID, name string, loader skillLoader, ) (skillspkg.ParsedSkill, error) { //nolint:gocritic // Org skill ACLs are evaluated against the chat owner. + ownerCtx := dbauthz.As(ctx, owner) row, err := p.db.GetOrganizationSkillByOrganizationIDAndName( - dbauthz.As(ctx, owner), + ownerCtx, database.GetOrganizationSkillByOrganizationIDAndNameParams{ OrganizationID: organizationID, Name: name, @@ -2437,6 +2448,18 @@ func (p *Server) loadOrganizationSkillBody( if loader.hides(row.Enabled, row.ModelInvocable) { return skillspkg.ParsedSkill{}, skillspkg.ErrSkillNotFound } + // Re-check at load time so an opt-out made mid-chat applies to the + // next load. + prefs, err := p.db.GetOrganizationSkillMemberPreferences(ownerCtx, database.GetOrganizationSkillMemberPreferencesParams{ + OrganizationID: organizationID, + UserID: ownerID, + }) + if err != nil { + return skillspkg.ParsedSkill{}, xerrors.Errorf("get organization skill member preferences: %w", err) + } + if prefs.Excludes(row.ID) { + return skillspkg.ParsedSkill{}, skillspkg.ErrSkillNotFound + } parsed, err := skillspkg.ParsePersonalSkillMarkdown([]byte(row.Content)) if err != nil { diff --git a/codersdk/skills.go b/codersdk/skills.go index af26ec06041..8df64d44189 100644 --- a/codersdk/skills.go +++ b/codersdk/skills.go @@ -100,6 +100,44 @@ type UpdateOrganizationSkillACLRequest struct { GroupRoles map[string]OrganizationSkillRole `json:"group_roles,omitempty"` } +// OrganizationSkillSettings is an organization's member opt-out setting for +// organization skills. +type OrganizationSkillSettings struct { + // MembersCanDisableSkills lets each organization member turn off + // organization skills for their own chats. + MembersCanDisableSkills bool `json:"members_can_disable_skills"` +} + +// UpdateOrganizationSkillSettingsRequest is the payload for updating an +// organization's member opt-out setting for organization skills. +type UpdateOrganizationSkillSettingsRequest struct { + MembersCanDisableSkills bool `json:"members_can_disable_skills"` +} + +// OrganizationSkillPreferences is an organization member's choices about the +// organization skills that load into their chats. The choices apply only +// while MembersCanDisableSkills is true. +type OrganizationSkillPreferences struct { + // MembersCanDisableSkills is the organization's setting. + MembersCanDisableSkills bool `json:"members_can_disable_skills"` + // AllSkillsDisabled turns off every organization skill, including + // skills added later. DisabledSkillIDs is kept and applies again when it + // is false. + AllSkillsDisabled bool `json:"all_skills_disabled"` + // DisabledSkillIDs lists the organization skills the member turned off. + DisabledSkillIDs []uuid.UUID `json:"disabled_skill_ids" format:"uuid"` +} + +// UpdateOrganizationSkillPreferencesRequest is a sparse update of an +// organization member's organization skill choices. At least one field must +// be set, and only the listed skills change. +type UpdateOrganizationSkillPreferencesRequest struct { + AllSkillsDisabled *bool `json:"all_skills_disabled,omitempty"` + // Skills maps an organization skill ID to whether the skill is enabled + // for the member's chats. + Skills map[string]bool `json:"skills,omitempty"` +} + func userSkillsPath(user string) string { return fmt.Sprintf("/api/experimental/users/%s/skills", url.PathEscape(user)) } @@ -257,6 +295,74 @@ func (c *ExperimentalClient) DeleteOrganizationSkill(ctx context.Context, organi return nil } +func organizationSkillSettingsPath(organizationID uuid.UUID) string { + return fmt.Sprintf("/api/experimental/organizations/%s/skill-settings", organizationID) +} + +func organizationSkillPreferencesPath(organizationID uuid.UUID, user string) string { + return fmt.Sprintf("/api/experimental/organizations/%s/members/%s/skill-preferences", organizationID, url.PathEscape(user)) +} + +// OrganizationSkillSettings returns an organization's member opt-out setting +// for organization skills. +func (c *ExperimentalClient) OrganizationSkillSettings(ctx context.Context, organizationID uuid.UUID) (OrganizationSkillSettings, error) { + res, err := c.Request(ctx, http.MethodGet, organizationSkillSettingsPath(organizationID), nil) + if err != nil { + return OrganizationSkillSettings{}, err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return OrganizationSkillSettings{}, ReadBodyAsError(res) + } + var settings OrganizationSkillSettings + return settings, ReadBodyAsJSON(res, &settings) +} + +// UpdateOrganizationSkillSettings updates an organization's member opt-out +// setting for organization skills. +func (c *ExperimentalClient) UpdateOrganizationSkillSettings(ctx context.Context, organizationID uuid.UUID, req UpdateOrganizationSkillSettingsRequest) (OrganizationSkillSettings, error) { + res, err := c.Request(ctx, http.MethodPut, organizationSkillSettingsPath(organizationID), req) + if err != nil { + return OrganizationSkillSettings{}, err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return OrganizationSkillSettings{}, ReadBodyAsError(res) + } + var settings OrganizationSkillSettings + return settings, ReadBodyAsJSON(res, &settings) +} + +// OrganizationSkillPreferences returns an organization member's organization +// skill choices. +func (c *ExperimentalClient) OrganizationSkillPreferences(ctx context.Context, organizationID uuid.UUID, user string) (OrganizationSkillPreferences, error) { + res, err := c.Request(ctx, http.MethodGet, organizationSkillPreferencesPath(organizationID, user), nil) + if err != nil { + return OrganizationSkillPreferences{}, err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return OrganizationSkillPreferences{}, ReadBodyAsError(res) + } + var prefs OrganizationSkillPreferences + return prefs, ReadBodyAsJSON(res, &prefs) +} + +// UpdateOrganizationSkillPreferences applies a sparse update to an +// organization member's organization skill choices. +func (c *ExperimentalClient) UpdateOrganizationSkillPreferences(ctx context.Context, organizationID uuid.UUID, user string, req UpdateOrganizationSkillPreferencesRequest) (OrganizationSkillPreferences, error) { + res, err := c.Request(ctx, http.MethodPatch, organizationSkillPreferencesPath(organizationID, user), req) + if err != nil { + return OrganizationSkillPreferences{}, err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return OrganizationSkillPreferences{}, ReadBodyAsError(res) + } + var prefs OrganizationSkillPreferences + return prefs, ReadBodyAsJSON(res, &prefs) +} + func chatProjectSkillPath(organizationID, projectID uuid.UUID, name string) string { return chatProjectPath(organizationID, projectID) + "/skills/" + url.PathEscape(name) } diff --git a/docs/admin/security/audit-logs.md b/docs/admin/security/audit-logs.md index 0f6f81bfcdd..22de9820358 100644 --- a/docs/admin/security/audit-logs.md +++ b/docs/admin/security/audit-logs.md @@ -662,6 +662,7 @@ Actions: `create`, `write`, `delete`
iconidis_defaultmembers_can_disable_skillsnameshareable_workspace_ownersupdated_at