Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions cli/organizationmanage.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,11 @@ func (r *RootCmd) editOrganization(orgContext *OrganizationContext) *serpent.Com
Long: FormatExamples(
Example{
Description: "Replace the roles every member of the organization holds",
Command: "coder organizations edit --default-org-member-roles organization-workspace-access,organization-template-admin",
Command: "coder organizations edit --default-org-member-roles organization-workspace-access,agents-access,organization-template-admin",
},
Example{
Description: "Restrict Coder Agents to members assigned agents-access directly",
Command: "coder organizations edit --default-org-member-roles organization-workspace-access",
},
Example{
Description: "Grant members no roles at all",
Expand All @@ -87,7 +91,8 @@ func (r *RootCmd) editOrganization(orgContext *OrganizationContext) *serpent.Com
Description: "Replaces the roles every member of the organization holds. " +
"Accepts a comma-separated list and may be repeated. " +
"An empty value removes every role. " +
"New organizations start with organization-workspace-access, which grants members access to their own workspaces.",
"New organizations start with organization-workspace-access, which grants members access to their own workspaces, " +
"and agents-access, which grants members access to Coder Agents.",
Value: serpent.StringArrayOf(&defaultOrgMemberRoles),
},
cliui.SkipPromptOption(),
Expand Down
10 changes: 8 additions & 2 deletions cli/testdata/coder_organizations_edit_--help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ USAGE:
- Replace the roles every member of the organization holds:

$ coder organizations edit --default-org-member-roles
organization-workspace-access,organization-template-admin
organization-workspace-access,agents-access,organization-template-admin

- Restrict Coder Agents to members assigned agents-access directly:

$ coder organizations edit --default-org-member-roles
organization-workspace-access

- Grant members no roles at all:

Expand All @@ -22,7 +27,8 @@ OPTIONS:
Replaces the roles every member of the organization holds. Accepts a
comma-separated list and may be repeated. An empty value removes every
role. New organizations start with organization-workspace-access,
which grants members access to their own workspaces.
which grants members access to their own workspaces, and
agents-access, which grants members access to Coder Agents.

-y, --yes bool
Bypass confirmation prompts.
Expand Down
38 changes: 0 additions & 38 deletions coderd/database/dbauthz/dbauthz.go
Original file line number Diff line number Diff line change
Expand Up @@ -1416,15 +1416,6 @@ func (q *querier) canAssignRoles(ctx context.Context, orgID uuid.UUID, added, re
grantedRoles := make([]rbac.RoleIdentifier, 0, len(added)+len(removed))
grantedRoles = append(grantedRoles, added...)
grantedRoles = append(grantedRoles, removed...)
// Retired role names may linger in stored role arrays and org default
// role lists until a data cleanup migration lands. They expand to no
// permissions and cannot be re-created as custom roles, so validating
// them is unnecessary: the added set only contains them via stored
// data (implied org defaults), never via explicit grants, which the
// role-update paths reject before reaching this filter.
grantedRoles = slices.DeleteFunc(grantedRoles, func(r rbac.RoleIdentifier) bool {
return rbac.IsRetiredRoleName(r.Name)
})
customRoles := make([]rbac.RoleIdentifier, 0)
// Validate that the roles being assigned are valid.
for _, r := range grantedRoles {
Expand Down Expand Up @@ -7912,17 +7903,6 @@ func (q *querier) UpdateMemberRoles(ctx context.Context, arg database.UpdateMemb
if err != nil {
return database.OrganizationMember{}, err
}
// Explicitly granting a retired role is rejected. Retired-name tolerance
// only covers stored grants and implied org defaults that linger until
// the cleanup migration lands; without this check the request would
// skip validation and persist a hidden grant that a binary rollback
// resolves again.
for _, role := range scopedGranted {
if rbac.IsRetiredRoleName(role.Name) {
return database.OrganizationMember{}, xerrors.Errorf("role %q is retired and cannot be assigned", role.Name)
}
}

// The org's default_org_member_roles are implied at request time by
// GetAuthorizationUserRoles. Include them in the implied set so
// canAssignRoles validates the caller can grant the full effective set
Expand Down Expand Up @@ -7998,15 +7978,6 @@ func (q *querier) UpdateOrganization(ctx context.Context, arg database.UpdateOrg
scopedOrgRoleIdentifiers(existing.DefaultOrgMemberRoles, arg.ID),
scopedOrgRoleIdentifiers(arg.DefaultOrgMemberRoles, arg.ID),
)
// Newly added defaults must not include retired names, which
// canAssignRoles tolerates only so stale stored defaults keep
// working until the cleanup migration lands. Removals stay
// tolerated so those stale defaults can be cleaned up.
for _, role := range added {
if rbac.IsRetiredRoleName(role.Name) {
return database.Organization{}, xerrors.Errorf("role %q is retired and cannot be a default role", role.Name)
}
}
if err := q.canAssignRoles(ctx, arg.ID, added, removed); err != nil {
return database.Organization{}, err
}
Expand Down Expand Up @@ -8534,15 +8505,6 @@ func (q *querier) UpdateUserRoles(ctx context.Context, arg database.UpdateUserRo
return database.User{}, err
}

// Explicitly granting a retired role is rejected. Retired-name tolerance
// only covers stored grants that linger until the cleanup migration
// lands.
for _, roleName := range arg.GrantedRoles {
if rbac.IsRetiredRoleName(roleName) {
return database.User{}, xerrors.Errorf("role %q is retired and cannot be assigned", roleName)
}
}

// The member role is always implied.
impliedTypes := append(q.convertToDeploymentRoles(arg.GrantedRoles), rbac.RoleMember())
// If the changeset is nothing, less rbac checks need to be done.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
-- Deleted legacy custom roles named agents-access are not restored.
UPDATE organizations
SET default_org_member_roles = array_remove(default_org_member_roles, 'agents-access')
WHERE 'agents-access' = ANY(default_org_member_roles);

UPDATE organization_members
SET roles = array_remove(roles, 'agents-access')
WHERE 'agents-access' = ANY(roles);
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
-- Custom roles named agents-access could predate the built-in role. The
-- built-in would shadow them and make them undeletable.
DELETE FROM custom_roles WHERE name = 'agents-access';

UPDATE organizations
SET default_org_member_roles = array_append(default_org_member_roles, 'agents-access')
WHERE NOT ('agents-access' = ANY(default_org_member_roles));
100 changes: 100 additions & 0 deletions coderd/database/migrations/migrate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,7 @@ func TestMigrationChain(t *testing.T) {
{"Migration000587RemoveAgentsAccessRole", 587, testMigration000587RemoveAgentsAccessRole},
{"Migration000590WorkspaceAgentSessionCounts", 590, testMigration000590WorkspaceAgentSessionCounts},
{"Migration000595RemoveTaskPermissions", 595, testMigration000595RemoveTaskPermissions},
{"Migration000602RestoreAgentsAccessDefaultRole", 602, testMigration000602RestoreAgentsAccessDefaultRole},
}
for _, step := range steps {
stepTo(step.version - 1)
Expand Down Expand Up @@ -1662,6 +1663,105 @@ func testMigration000587RemoveAgentsAccessRole(t *testing.T, sqlDB *sql.DB, next
require.Equal(t, []string{"organization-workspace-access"}, []string(defaultRoles))
}

func testMigration000602RestoreAgentsAccessDefaultRole(t *testing.T, sqlDB *sql.DB, next migrationStepper) {
const migrationVersion = 602

ctx := testutil.Context(t, testutil.WaitLong)
db := database.New(sqlDB)

orgs := []struct {
defaults []string
want []string
}{
{[]string{"organization-workspace-access"}, []string{"organization-workspace-access", "agents-access"}},
{[]string{}, []string{"agents-access"}},
{[]string{"organization-workspace-access", "organization-auditor"}, []string{"organization-workspace-access", "organization-auditor", "agents-access"}},
}
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
}

member := dbgen.User(t, db, database.User{})
dbgen.OrganizationMember(t, db, database.OrganizationMember{
OrganizationID: orgIDs[0],
UserID: member.ID,
Roles: []string{"organization-auditor"},
})
serviceAccount := dbgen.User(t, db, database.User{IsServiceAccount: true})
dbgen.OrganizationMember(t, db, database.OrganizationMember{
OrganizationID: orgIDs[0],
UserID: serviceAccount.ID,
Roles: []string{},
})
legacyRole := dbgen.CustomRole(t, db, database.CustomRole{
Name: "agents-access",
OrganizationID: uuid.NullUUID{UUID: orgIDs[1], Valid: true},
})
unrelatedRole := dbgen.CustomRole(t, db, database.CustomRole{
OrganizationID: uuid.NullUUID{UUID: orgIDs[1], Valid: true},
})

memberRoles := func(userID uuid.UUID) []string {
t.Helper()
var roles pq.StringArray
err := sqlDB.QueryRowContext(ctx, "SELECT roles FROM organization_members WHERE organization_id = $1 AND user_id = $2", orgIDs[0], userID).Scan(&roles)
require.NoError(t, err)
return roles
}
assertDefaults := func(withAgentsAccess bool) {
t.Helper()
for i, o := range orgs {
var roles pq.StringArray
err := sqlDB.QueryRowContext(ctx, "SELECT default_org_member_roles FROM organizations WHERE id = $1", orgIDs[i]).Scan(&roles)
require.NoError(t, err)
want := o.defaults
if withAgentsAccess {
want = o.want
}
require.Equal(t, want, []string(roles), "org %d", i)
}
}
customRoleExists := func(id uuid.UUID) bool {
t.Helper()
var exists bool
err := sqlDB.QueryRowContext(ctx, "SELECT EXISTS (SELECT 1 FROM custom_roles WHERE id = $1)", id).Scan(&exists)
require.NoError(t, err)
return exists
}

version, _, err := next()
require.NoError(t, err)
require.EqualValues(t, migrationVersion, version)
assertDefaults(true)
require.Equal(t, []string{"organization-auditor"}, memberRoles(member.ID))
require.Empty(t, memberRoles(serviceAccount.ID))
require.False(t, customRoleExists(legacyRole.ID))
require.True(t, customRoleExists(unrelatedRole.ID))

// An explicit grant made after the upgrade is removed on downgrade.
_, err = sqlDB.ExecContext(ctx, "UPDATE organization_members SET roles = array_append(roles, 'agents-access') WHERE user_id = $1", serviceAccount.ID)
require.NoError(t, err)

downSQL, err := os.ReadFile("000602_restore_agents_access_default_role.down.sql")
require.NoError(t, err)
_, err = sqlDB.ExecContext(ctx, string(downSQL))
require.NoError(t, err)
assertDefaults(false)
require.Equal(t, []string{"organization-auditor"}, memberRoles(member.ID))
require.Empty(t, memberRoles(serviceAccount.ID))

upSQL, err := os.ReadFile("000602_restore_agents_access_default_role.up.sql")
require.NoError(t, err)
_, err = sqlDB.ExecContext(ctx, string(upSQL))
require.NoError(t, err)
assertDefaults(true)
}

func TestMigration000504AIProvidersBackfill(t *testing.T) {
t.Parallel()

Expand Down
40 changes: 39 additions & 1 deletion coderd/database/querier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3758,7 +3758,7 @@ func TestGetAuthorizationUserRolesImpliedOrgRole(t *testing.T) {
// every member's effective roles include the org's defaults, and changes
// to the column propagate on the next request. The union applies to
// regular users and to service accounts; the SQL array_cats the column
// for both code paths.
// for both code paths (minus agents-access for service accounts).
func TestGetAuthorizationUserRolesUnionsDefaultOrgMemberRoles(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -3809,6 +3809,44 @@ func TestGetAuthorizationUserRolesUnionsDefaultOrgMemberRoles(t *testing.T) {
require.NotContains(t, shrunkSA.Roles, wantWorkspaceAccess)
}

// TestGetAuthorizationUserRolesServiceAccountAgentsAccess verifies service
// accounts do not inherit agents-access from the org defaults but keep an
// explicit grant.
func TestGetAuthorizationUserRolesServiceAccountAgentsAccess(t *testing.T) {
t.Parallel()

db, _ := dbtestutil.NewDB(t)
org := dbgen.Organization(t, db, database.Organization{})
require.Contains(t, org.DefaultOrgMemberRoles, rbac.RoleAgentsAccess())
user := dbgen.User(t, db, database.User{})
sa := dbgen.User(t, db, database.User{IsServiceAccount: true})
grantedSA := dbgen.User(t, db, database.User{IsServiceAccount: true})
dbgen.OrganizationMember(t, db, database.OrganizationMember{OrganizationID: org.ID, UserID: user.ID})
dbgen.OrganizationMember(t, db, database.OrganizationMember{OrganizationID: org.ID, UserID: sa.ID})
dbgen.OrganizationMember(t, db, database.OrganizationMember{
OrganizationID: org.ID,
UserID: grantedSA.ID,
Roles: []string{rbac.RoleAgentsAccess()},
})

ctx := testutil.Context(t, testutil.WaitShort)
wantAgentsAccess := rbac.ScopedRoleAgentsAccess(org.ID).String()
wantWorkspaceAccess := rbac.ScopedRoleOrgWorkspaceAccess(org.ID).String()

userRoles, err := db.GetAuthorizationUserRoles(ctx, user.ID)
require.NoError(t, err)
require.Contains(t, userRoles.Roles, wantAgentsAccess)

saRoles, err := db.GetAuthorizationUserRoles(ctx, sa.ID)
require.NoError(t, err)
require.NotContains(t, saRoles.Roles, wantAgentsAccess)
require.Contains(t, saRoles.Roles, wantWorkspaceAccess)

grantedRoles, err := db.GetAuthorizationUserRoles(ctx, grantedSA.ID)
require.NoError(t, err)
require.Contains(t, grantedRoles.Roles, wantAgentsAccess)
}

func TestUpdateOrganizationWorkspaceSharingSettings(t *testing.T) {
t.Parallel()

Expand Down
8 changes: 7 additions & 1 deletion coderd/database/queries.sql.go

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

8 changes: 7 additions & 1 deletion coderd/database/queries/users.sql
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,8 @@ SELECT
--
-- organizations.default_org_member_roles is unioned in so changes
-- to org defaults propagate to every member on the next request.
-- Service accounts do not inherit agents-access from the defaults
-- so they only get chat access through an explicit grant.
unnest(
array_cat(
array_append(
Expand All @@ -607,7 +609,11 @@ SELECT
'organization-member'
END
),
organizations.default_org_member_roles
CASE WHEN users.is_service_account THEN
array_remove(organizations.default_org_member_roles, 'agents-access')
ELSE
organizations.default_org_member_roles
END
)
) AS org_roles
WHERE
Expand Down
Loading
Loading