Files
coder/enterprise/coderd/roles_test.go
T
Michael Suchacz 6826da9397 feat: restore agents-access as a default organization role (#30004)
Restores `agents-access` (**Coder Agents User**) as a built-in
organization role and adds it to every organization's
`default_org_member_roles`. Members keep Coder Agents by default, and
admins can now restrict it per organization by removing the role from
the defaults and granting it through IdP role sync or direct assignment.

Since #28186, chat permissions lived in the organization-member floor,
so the only way to limit Coder Agents was narrowing per-model access
lists, which did not hide the feature.

- Migration 000602 appends `agents-access` to every organization's
defaults, so upgrading keeps every member's access. New organizations
get it from `rbac.DefaultOrgMemberRoles()`.
- Service accounts do not inherit the role from the defaults
(`GetAuthorizationUserRoles`), so they still need an explicit grant for
chat.
- Owners and Organization Admins keep chat access regardless of
defaults. Chats shared with a user stay readable without the role.
- Role sync is unchanged. It does not store default roles, so after the
default is removed a mapped user gets `agents-access` at their next
sign-in.
- The retired-role mechanism (`IsRetiredRoleName`) is removed.
- `PATCH /api/v2/organizations/{organization}` rejects duplicate
`default_org_member_roles` entries (the CLI already de-duplicated them).
- Custom organization role requests treat built-in role names
case-insensitively, since custom role names are stored lowercase and
`Agents-Access` would otherwise become an undeletable shadow of the
built-in role.
- The Agents permission alert tells restricted members their chats are
kept, and the model selector for users without chat permission no longer
claims that no models are configured.

Docs add "Control who can use Coder Agents" to the Agents
getting-started guide.

**NOTE**: Migration 000602 deletes custom roles named `agents-access`,
which the built-in role would shadow. The down migration does not
restore them. Stored member grants of `agents-access` from the earlier
built-in role or a deleted custom role stay and now grant chat access.

## Validation

- Remote dogfood
[UAT](https://dogfood.cdr.dev/agents/e1c18dc6-f6f0-49a1-b6cd-6ce014b51a86)
passed on fb441dfae5, covering case variants of built-in role names on
create, update, delete, default roles, and member grants. The previous
round, on a6fef66b3f, passed the upgrade from main 5dde49dffb on a
fresh database. 6b7f107e0b only changes wording (docs, comments, UI
copy, CLI help) and did not go through UAT.
- Local: rbac, dbauthz, idpsync, migrations (chain including 000602 down
and up), querier, httpmw, provisionerdserver, coderd and enterprise
chat, role, and organization tests, chatd, toolsdk, CLI; frontend
vitest, story tests, biome, oxlint, tsc.

## Known issues (not changed here)

- Sending from a chat page that was already open when access was removed
shows a generic 404 panel until reload.
- The members page role editor is not locked for OIDC users under org
role sync; the API rejects the change with 400.
- Creating a custom role named after a system role
(`organization-member`, `organization-service-account`) returns 400 with
a raw database unique-constraint error.

<details>
<summary>Review record</summary>

- Remote UAT (UAT Critic sub-agent `6636c855ec`): round 1 on 8bec029d35
passed with issues, fixed in d7ba937a10 and e0f16e1a45f; round 2 on
a6fef66b3f passed; round 3 on fb441dfae5 passed.
- Codex: round 1 on a6fef66b3f found one P2 (case variants of built-in
role names), fixed in fb441dfae5 with a red-green test. Rounds 2 and 3
on fb441dfae5 found no major issues.
- mafredri on fb441dfae5 (PR text only): nine wording suggestions
applied in 6b7f107e0b9; NOTE extended for stored grants; description
trimmed.
- Frontend: FE1 to FE10 and coder-frontend-review checkpoints
self-audited.

</details>

> 🤖 This PR was opened by [Xum](https://mux.coder.com) on behalf of
@ibetitsmike.
2026-09-27 23:34:26 +02:00

651 lines
24 KiB
Go

package coderd_test
import (
"bytes"
"context"
"net/http"
"slices"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/database/db2sdk"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/util/slice"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/enterprise/coderd/coderdenttest"
"github.com/coder/coder/v2/enterprise/coderd/license"
"github.com/coder/coder/v2/provisioner/echo"
"github.com/coder/coder/v2/testutil"
)
func TestCustomOrganizationRole(t *testing.T) {
t.Parallel()
templateAdminCustom := func(orgID uuid.UUID) codersdk.Role {
return codersdk.Role{
Name: "test-role",
DisplayName: "Testing Purposes",
OrganizationID: orgID.String(),
// Basically creating a template admin manually
SitePermissions: nil,
OrganizationPermissions: codersdk.CreatePermissions(map[codersdk.RBACResource][]codersdk.RBACAction{
codersdk.ResourceTemplate: {codersdk.ActionCreate, codersdk.ActionRead, codersdk.ActionUpdate, codersdk.ActionViewInsights},
codersdk.ResourceFile: {codersdk.ActionCreate, codersdk.ActionRead},
codersdk.ResourceWorkspace: {codersdk.ActionRead},
}),
UserPermissions: nil,
}
}
// Create, assign, and use a custom role
t.Run("Success", func(t *testing.T) {
t.Parallel()
owner, first := coderdenttest.New(t, &coderdenttest.Options{
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureCustomRoles: 1,
},
},
})
ctx := testutil.Context(t, testutil.WaitMedium)
//nolint:gocritic // owner is required for this
role, err := owner.CreateOrganizationRole(ctx, templateAdminCustom(first.OrganizationID))
require.NoError(t, err, "upsert role")
// Assign the custom template admin role
tmplAdmin, _ := coderdtest.CreateAnotherUser(t, owner, first.OrganizationID, rbac.RoleIdentifier{Name: role.Name, OrganizationID: first.OrganizationID})
// Assert the role exists
// TODO: At present user roles are not returned by the user endpoints.
// Changing this might mess up the UI in how it renders the roles on the
// users page. When the users endpoint is updated, this should be uncommented.
// roleNamesF := func(role codersdk.SlimRole) string { return role.Name }
// require.Contains(t, slice.List(user.Roles, roleNamesF), role.Name)
// Try to create a template version
coderdtest.CreateTemplateVersion(t, tmplAdmin, first.OrganizationID, nil)
// Verify the role exists in the list
allRoles, err := tmplAdmin.ListOrganizationRoles(ctx, first.OrganizationID)
require.NoError(t, err)
var foundRole codersdk.AssignableRoles
require.True(t, slices.ContainsFunc(allRoles, func(selected codersdk.AssignableRoles) bool {
if selected.Name == role.Name {
foundRole = selected
return true
}
return false
}), "role missing from org role list")
require.Len(t, foundRole.SitePermissions, 0)
require.Len(t, foundRole.OrganizationPermissions, 7)
require.Len(t, foundRole.UserPermissions, 0)
})
// Revoked licenses cannot modify/create custom roles, but they can
// use the existing roles.
t.Run("RevokedLicense", func(t *testing.T) {
t.Parallel()
owner, first := coderdenttest.New(t, &coderdenttest.Options{
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureCustomRoles: 1,
},
},
})
ctx := testutil.Context(t, testutil.WaitMedium)
//nolint:gocritic // owner is required for this
role, err := owner.CreateOrganizationRole(ctx, templateAdminCustom(first.OrganizationID))
require.NoError(t, err, "upsert role")
// Remove the license to block premium functionality
licenses, err := owner.Licenses(ctx)
require.NoError(t, err, "get licenses")
for _, license := range licenses {
// Should be only 1...
err := owner.DeleteLicense(ctx, license.ID)
require.NoError(t, err, "delete license")
}
// Verify functionality is lost
_, err = owner.UpdateOrganizationRole(ctx, templateAdminCustom(first.OrganizationID))
require.ErrorContains(t, err, "Custom Roles is a Premium feature")
// Assign the custom template admin role
tmplAdmin, _ := coderdtest.CreateAnotherUser(t, owner, first.OrganizationID, rbac.RoleIdentifier{Name: role.Name, OrganizationID: first.OrganizationID})
// Try to create a template version, eg using the custom role
coderdtest.CreateTemplateVersion(t, tmplAdmin, first.OrganizationID, nil)
})
// Role patches are complete, as in the request overrides the existing role.
t.Run("RoleOverrides", func(t *testing.T) {
t.Parallel()
owner, first := coderdenttest.New(t, &coderdenttest.Options{
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureCustomRoles: 1,
},
},
})
ctx := testutil.Context(t, testutil.WaitMedium)
//nolint:gocritic // owner is required for this
role, err := owner.CreateOrganizationRole(ctx, templateAdminCustom(first.OrganizationID))
require.NoError(t, err, "upsert role")
// Assign the custom template admin role
tmplAdmin, _ := coderdtest.CreateAnotherUser(t, owner, first.OrganizationID, rbac.RoleIdentifier{Name: role.Name, OrganizationID: first.OrganizationID})
// Try to create a template version, eg using the custom role
coderdtest.CreateTemplateVersion(t, tmplAdmin, first.OrganizationID, nil)
//nolint:gocritic // owner is required for this
newRole := templateAdminCustom(first.OrganizationID)
// These are all left nil, which sets the custom role to have 0
// permissions. Omitting this does not "inherit" what already
// exists.
newRole.SitePermissions = nil
newRole.OrganizationPermissions = nil
newRole.UserPermissions = nil
_, err = owner.UpdateOrganizationRole(ctx, newRole)
require.NoError(t, err, "upsert role with override")
// The role should no longer have template perms
data, err := echo.TarWithOptions(ctx, tmplAdmin.Logger(), nil)
require.NoError(t, err)
file, err := tmplAdmin.Upload(ctx, codersdk.ContentTypeTar, bytes.NewReader(data))
require.NoError(t, err)
_, err = tmplAdmin.CreateTemplateVersion(ctx, first.OrganizationID, codersdk.CreateTemplateVersionRequest{
FileID: file.ID,
StorageMethod: codersdk.ProvisionerStorageMethodFile,
Provisioner: codersdk.ProvisionerTypeEcho,
})
require.ErrorContains(t, err, "forbidden")
})
t.Run("InvalidName", func(t *testing.T) {
t.Parallel()
owner, first := coderdenttest.New(t, &coderdenttest.Options{
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureCustomRoles: 1,
},
},
})
ctx := testutil.Context(t, testutil.WaitMedium)
//nolint:gocritic // owner is required for this
_, err := owner.CreateOrganizationRole(ctx, codersdk.Role{
Name: "Bad_Name", // No underscores allowed
DisplayName: "Testing Purposes",
OrganizationID: first.OrganizationID.String(),
SitePermissions: nil,
OrganizationPermissions: nil,
UserPermissions: nil,
})
require.ErrorContains(t, err, "Validation")
})
t.Run("ReservedName", func(t *testing.T) {
t.Parallel()
owner, first := coderdenttest.New(t, &coderdenttest.Options{
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureCustomRoles: 1,
},
},
})
ctx := testutil.Context(t, testutil.WaitMedium)
//nolint:gocritic // owner is required for this
_, err := owner.CreateOrganizationRole(ctx, codersdk.Role{
Name: "owner", // Reserved
DisplayName: "Testing Purposes",
OrganizationID: first.OrganizationID.String(),
SitePermissions: nil,
OrganizationPermissions: nil,
UserPermissions: nil,
})
require.ErrorContains(t, err, "Reserved")
//nolint:gocritic // owner is required for this
_, err = owner.CreateOrganizationRole(ctx, codersdk.Role{
Name: codersdk.RoleAgentsAccess,
DisplayName: "Testing Purposes",
OrganizationID: first.OrganizationID.String(),
})
require.ErrorContains(t, err, "Reserved")
// Custom role names are stored lowercase, so a case variant would
// shadow the built-in role.
//nolint:gocritic // owner is required for this
_, err = owner.CreateOrganizationRole(ctx, codersdk.Role{
Name: "Agents-Access",
DisplayName: "Testing Purposes",
OrganizationID: first.OrganizationID.String(),
})
require.ErrorContains(t, err, "Reserved")
})
// Attempt to add site & user permissions, which is not allowed
t.Run("ExcessPermissions", func(t *testing.T) {
t.Parallel()
owner, first := coderdenttest.New(t, &coderdenttest.Options{
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureCustomRoles: 1,
},
},
})
ctx := testutil.Context(t, testutil.WaitMedium)
siteRole := templateAdminCustom(first.OrganizationID)
siteRole.SitePermissions = []codersdk.Permission{
{
ResourceType: codersdk.ResourceWorkspace,
Action: codersdk.ActionRead,
},
}
//nolint:gocritic // owner is required for this
_, err := owner.CreateOrganizationRole(ctx, siteRole)
require.ErrorContains(t, err, "site wide permissions")
userRole := templateAdminCustom(first.OrganizationID)
userRole.UserPermissions = []codersdk.Permission{
{
ResourceType: codersdk.ResourceWorkspace,
Action: codersdk.ActionRead,
},
}
//nolint:gocritic // owner is required for this
_, err = owner.UpdateOrganizationRole(ctx, userRole)
require.ErrorContains(t, err, "not allowed to assign user permissions")
})
// Attempt to add org member permissions, which is not allowed.
t.Run("MemberPermissions", func(t *testing.T) {
t.Parallel()
owner, first := coderdenttest.New(t, &coderdenttest.Options{
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureCustomRoles: 1,
},
},
})
ctx := testutil.Context(t, testutil.WaitMedium)
role := templateAdminCustom(first.OrganizationID)
role.Name = "test-role-member-perms"
role.OrganizationMemberPermissions = []codersdk.Permission{
{
ResourceType: codersdk.ResourceWorkspace,
Action: codersdk.ActionRead,
},
}
//nolint:gocritic // we want unrestricted permissions for the test
_, err := owner.CreateOrganizationRole(ctx, role)
var apiErr *codersdk.Error
require.ErrorAs(t, err, &apiErr)
require.Equal(t, http.StatusBadRequest, apiErr.StatusCode())
require.ErrorContains(t, err, "not allowed to assign organization member permissions for an organization role")
})
// System roles are stored in the DB but excluded from the custom
// roles API, so attempting to delete one returns 404.
t.Run("DeleteSystemRole", func(t *testing.T) {
t.Parallel()
owner, first := coderdenttest.New(t, &coderdenttest.Options{
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureCustomRoles: 1,
},
},
})
ctx := testutil.Context(t, testutil.WaitMedium)
//nolint:gocritic // we want unrestricted permissions for the test
err := owner.DeleteOrganizationRole(ctx, first.OrganizationID, rbac.RoleOrgMember())
var apiErr *codersdk.Error
require.ErrorAs(t, err, &apiErr)
require.Equal(t, http.StatusNotFound, apiErr.StatusCode())
})
t.Run("NotFound", func(t *testing.T) {
t.Parallel()
owner, first := coderdenttest.New(t, &coderdenttest.Options{
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureCustomRoles: 1,
},
},
})
ctx := testutil.Context(t, testutil.WaitMedium)
newRole := templateAdminCustom(first.OrganizationID)
newRole.OrganizationID = "0000" // This is not a valid uuid
//nolint:gocritic // owner is required for this
_, err := owner.CreateOrganizationRole(ctx, newRole)
require.ErrorContains(t, err, "Resource not found")
})
t.Run("Delete", func(t *testing.T) {
t.Parallel()
owner, first := coderdenttest.New(t, &coderdenttest.Options{
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureCustomRoles: 1,
},
},
})
orgAdmin, orgAdminUser := coderdtest.CreateAnotherUser(t, owner, first.OrganizationID, rbac.ScopedRoleOrgAdmin(first.OrganizationID))
ctx := testutil.Context(t, testutil.WaitMedium)
createdRole, err := orgAdmin.CreateOrganizationRole(ctx, templateAdminCustom(first.OrganizationID))
require.NoError(t, err, "upsert role")
//nolint:gocritic // org_admin cannot assign to themselves
_, err = owner.UpdateOrganizationMemberRoles(ctx, first.OrganizationID, orgAdminUser.ID.String(), codersdk.UpdateRoles{
// Give the user this custom role, to ensure when it is deleted, the user
// is ok to be used.
Roles: []string{createdRole.Name, rbac.ScopedRoleOrgAdmin(first.OrganizationID).Name},
})
require.NoError(t, err, "assign custom role to user")
existingRoles, err := orgAdmin.ListOrganizationRoles(ctx, first.OrganizationID)
require.NoError(t, err)
exists := slices.ContainsFunc(existingRoles, func(role codersdk.AssignableRoles) bool {
return role.Name == createdRole.Name
})
require.True(t, exists, "custom role should exist")
// Delete the role
err = orgAdmin.DeleteOrganizationRole(ctx, first.OrganizationID, createdRole.Name)
require.NoError(t, err)
existingRoles, err = orgAdmin.ListOrganizationRoles(ctx, first.OrganizationID)
require.NoError(t, err)
exists = slices.ContainsFunc(existingRoles, func(role codersdk.AssignableRoles) bool {
return role.Name == createdRole.Name
})
require.False(t, exists, "custom role should be deleted")
// Verify you can still assign roles.
// There used to be a bug that if a member had a delete role, they
// could not be assigned roles anymore.
//nolint:gocritic // org_admin cannot assign to themselves
_, err = owner.UpdateOrganizationMemberRoles(ctx, first.OrganizationID, orgAdminUser.ID.String(), codersdk.UpdateRoles{
Roles: []string{rbac.ScopedRoleOrgAdmin(first.OrganizationID).Name},
})
require.NoError(t, err)
})
// Verify deleting a custom role cascades to all members
t.Run("DeleteRoleCascadeMembers", func(t *testing.T) {
t.Parallel()
owner, first := coderdenttest.New(t, &coderdenttest.Options{
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureCustomRoles: 1,
},
},
})
orgAdmin, orgAdminUser := coderdtest.CreateAnotherUser(t, owner, first.OrganizationID, rbac.ScopedRoleOrgAdmin(first.OrganizationID))
ctx := testutil.Context(t, testutil.WaitMedium)
createdRole, err := orgAdmin.CreateOrganizationRole(ctx, templateAdminCustom(first.OrganizationID))
require.NoError(t, err, "upsert role")
customRoleIdentifier := rbac.RoleIdentifier{
Name: createdRole.Name,
OrganizationID: first.OrganizationID,
}
// Create a few members with the role
coderdtest.CreateAnotherUser(t, owner, first.OrganizationID, customRoleIdentifier)
coderdtest.CreateAnotherUser(t, owner, first.OrganizationID, rbac.ScopedRoleOrgAdmin(first.OrganizationID), customRoleIdentifier)
coderdtest.CreateAnotherUser(t, owner, first.OrganizationID, rbac.ScopedRoleOrgTemplateAdmin(first.OrganizationID), rbac.ScopedRoleOrgAuditor(first.OrganizationID), customRoleIdentifier)
// Verify members have the custom role
originalMembers, err := orgAdmin.OrganizationMembers(ctx, first.OrganizationID)
require.NoError(t, err)
require.Len(t, originalMembers, 5) // 3 members + org admin + owner
for _, member := range originalMembers {
if member.UserID == orgAdminUser.ID || member.UserID == first.UserID {
continue
}
require.True(t, slices.ContainsFunc(member.Roles, func(role codersdk.SlimRole) bool {
return role.Name == customRoleIdentifier.Name
}), "member should have custom role")
}
err = orgAdmin.DeleteOrganizationRole(ctx, first.OrganizationID, createdRole.Name)
require.NoError(t, err)
// Verify the role was removed from all members
members, err := orgAdmin.OrganizationMembers(ctx, first.OrganizationID)
require.NoError(t, err)
require.Len(t, members, 5) // 3 members + org admin + owner
for _, member := range members {
require.False(t, slices.ContainsFunc(member.Roles, func(role codersdk.SlimRole) bool {
return role.Name == customRoleIdentifier.Name
}), "role should be removed from all users")
// Verify the rest of the member's roles are unchanged
original := originalMembers[slices.IndexFunc(originalMembers, func(haystack codersdk.OrganizationMemberWithUserData) bool {
return haystack.UserID == member.UserID
})]
originalWithoutCustom := slices.DeleteFunc(original.Roles, func(role codersdk.SlimRole) bool {
return role.Name == customRoleIdentifier.Name
})
require.ElementsMatch(t, originalWithoutCustom, member.Roles, "original roles are unchanged")
}
})
}
func TestListRoles(t *testing.T) {
t.Parallel()
dv := coderdtest.DeploymentValues(t)
client, owner := coderdenttest.New(t, &coderdenttest.Options{
Options: &coderdtest.Options{
DeploymentValues: dv,
},
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureExternalProvisionerDaemons: 1,
codersdk.FeatureMultipleOrganizations: 1,
},
},
})
// Create owner, member, and org admin
member, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID)
orgAdmin, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID, rbac.ScopedRoleOrgAdmin(owner.OrganizationID))
otherOrg := coderdenttest.CreateOrganization(t, client, coderdenttest.CreateOrganizationOptions{})
const notFound = "Resource not found"
testCases := []struct {
Name string
Client *codersdk.Client
APICall func(context.Context) ([]codersdk.AssignableRoles, error)
ExpectedRoles []codersdk.AssignableRoles
AuthorizedError string
}{
{
// Members cannot assign any roles
Name: "MemberListSite",
APICall: func(ctx context.Context) ([]codersdk.AssignableRoles, error) {
x, err := member.ListSiteRoles(ctx)
return x, err
},
ExpectedRoles: convertRoles(map[rbac.RoleIdentifier]bool{
{Name: codersdk.RoleOwner}: false,
{Name: codersdk.RoleAuditor}: false,
{Name: codersdk.RoleTemplateAdmin}: false,
{Name: codersdk.RoleUserAdmin}: false,
}),
},
{
Name: "OrgMemberListOrg",
APICall: func(ctx context.Context) ([]codersdk.AssignableRoles, error) {
return member.ListOrganizationRoles(ctx, owner.OrganizationID)
},
ExpectedRoles: convertRoles(map[rbac.RoleIdentifier]bool{
{Name: codersdk.RoleOrganizationAdmin, OrganizationID: owner.OrganizationID}: false,
{Name: codersdk.RoleOrganizationAuditor, OrganizationID: owner.OrganizationID}: false,
{Name: codersdk.RoleOrganizationTemplateAdmin, OrganizationID: owner.OrganizationID}: false,
{Name: codersdk.RoleOrganizationUserAdmin, OrganizationID: owner.OrganizationID}: false,
{Name: codersdk.RoleOrganizationWorkspaceCreationBan, OrganizationID: owner.OrganizationID}: false,
{Name: codersdk.RoleOrganizationWorkspaceAccess, OrganizationID: owner.OrganizationID}: false,
{Name: codersdk.RoleAgentsAccess, OrganizationID: owner.OrganizationID}: false,
}),
},
{
Name: "NonOrgMemberListOrg",
APICall: func(ctx context.Context) ([]codersdk.AssignableRoles, error) {
return member.ListOrganizationRoles(ctx, otherOrg.ID)
},
AuthorizedError: notFound,
},
// Org admin
{
Name: "OrgAdminListSite",
APICall: func(ctx context.Context) ([]codersdk.AssignableRoles, error) {
return orgAdmin.ListSiteRoles(ctx)
},
ExpectedRoles: convertRoles(map[rbac.RoleIdentifier]bool{
{Name: codersdk.RoleOwner}: false,
{Name: codersdk.RoleAuditor}: false,
{Name: codersdk.RoleTemplateAdmin}: false,
{Name: codersdk.RoleUserAdmin}: false,
}),
},
{
Name: "OrgAdminListOrg",
APICall: func(ctx context.Context) ([]codersdk.AssignableRoles, error) {
return orgAdmin.ListOrganizationRoles(ctx, owner.OrganizationID)
},
ExpectedRoles: convertRoles(map[rbac.RoleIdentifier]bool{
{Name: codersdk.RoleOrganizationAdmin, OrganizationID: owner.OrganizationID}: true,
{Name: codersdk.RoleOrganizationAuditor, OrganizationID: owner.OrganizationID}: true,
{Name: codersdk.RoleOrganizationTemplateAdmin, OrganizationID: owner.OrganizationID}: true,
{Name: codersdk.RoleOrganizationUserAdmin, OrganizationID: owner.OrganizationID}: true,
{Name: codersdk.RoleOrganizationWorkspaceCreationBan, OrganizationID: owner.OrganizationID}: true,
{Name: codersdk.RoleOrganizationWorkspaceAccess, OrganizationID: owner.OrganizationID}: true,
{Name: codersdk.RoleAgentsAccess, OrganizationID: owner.OrganizationID}: true,
}),
},
{
Name: "OrgAdminListOtherOrg",
APICall: func(ctx context.Context) ([]codersdk.AssignableRoles, error) {
return orgAdmin.ListOrganizationRoles(ctx, otherOrg.ID)
},
AuthorizedError: notFound,
},
// Admin
{
Name: "AdminListSite",
APICall: func(ctx context.Context) ([]codersdk.AssignableRoles, error) {
return client.ListSiteRoles(ctx)
},
ExpectedRoles: convertRoles(map[rbac.RoleIdentifier]bool{
{Name: codersdk.RoleOwner}: true,
{Name: codersdk.RoleAuditor}: true,
{Name: codersdk.RoleTemplateAdmin}: true,
{Name: codersdk.RoleUserAdmin}: true,
}),
},
{
Name: "AdminListOrg",
APICall: func(ctx context.Context) ([]codersdk.AssignableRoles, error) {
return client.ListOrganizationRoles(ctx, owner.OrganizationID)
},
ExpectedRoles: convertRoles(map[rbac.RoleIdentifier]bool{
{Name: codersdk.RoleOrganizationAdmin, OrganizationID: owner.OrganizationID}: true,
{Name: codersdk.RoleOrganizationAuditor, OrganizationID: owner.OrganizationID}: true,
{Name: codersdk.RoleOrganizationTemplateAdmin, OrganizationID: owner.OrganizationID}: true,
{Name: codersdk.RoleOrganizationUserAdmin, OrganizationID: owner.OrganizationID}: true,
{Name: codersdk.RoleOrganizationWorkspaceCreationBan, OrganizationID: owner.OrganizationID}: true,
{Name: codersdk.RoleOrganizationWorkspaceAccess, OrganizationID: owner.OrganizationID}: true,
{Name: codersdk.RoleAgentsAccess, OrganizationID: owner.OrganizationID}: true,
}),
},
}
for _, c := range testCases {
t.Run(c.Name, func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
roles, err := c.APICall(ctx)
if c.AuthorizedError != "" {
var apiErr *codersdk.Error
require.ErrorAs(t, err, &apiErr)
require.Equal(t, http.StatusNotFound, apiErr.StatusCode())
require.Contains(t, apiErr.Message, c.AuthorizedError)
} else {
require.NoError(t, err)
ignorePerms := func(f codersdk.AssignableRoles) codersdk.AssignableRoles {
return codersdk.AssignableRoles{
Role: codersdk.Role{
Name: f.Name,
DisplayName: f.DisplayName,
},
Assignable: f.Assignable,
BuiltIn: true,
}
}
expected := slice.List(c.ExpectedRoles, ignorePerms)
found := slice.List(roles, ignorePerms)
require.ElementsMatch(t, expected, found)
}
})
}
}
func convertRole(roleName rbac.RoleIdentifier) codersdk.Role {
role, _ := rbac.RoleByName(roleName)
return db2sdk.RBACRole(role)
}
func convertRoles(assignableRoles map[rbac.RoleIdentifier]bool) []codersdk.AssignableRoles {
converted := make([]codersdk.AssignableRoles, 0, len(assignableRoles))
for roleName, assignable := range assignableRoles {
role := convertRole(roleName)
converted = append(converted, codersdk.AssignableRoles{
Role: role,
Assignable: assignable,
})
}
return converted
}