feat: add service_accounts workspace sharing mode (#23093)

Introduce a three-way workspace sharing setting (none, everyone,
service_accounts) replacing the boolean workspace_sharing_disabled.
In service_accounts mode, only service account-owned workspaces can be
shared while regular members' share permissions are removed. Adds a
new organization-service-account system role with per-org permissions
reconciled alongside the existing organization-member system role.

Related to:
https://linear.app/codercom/issue/PLAT-28/feat-service-accounts-sharing-mode-and-rbac-role

---------

Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com>
Co-authored-by: Kayla はな <mckayla@hey.com>
This commit is contained in:
George K
2026-03-17 12:16:43 -07:00
committed by GitHub
co-authored by Steven Masley Kayla はな
parent 6b76e30321
commit 91ec0f1484
38 changed files with 1437 additions and 421 deletions
+3 -3
View File
@@ -737,19 +737,19 @@ func TestGroup(t *testing.T) {
},
})
ctx := testutil.Context(t, testutil.WaitLong)
_, err := sqlDB.ExecContext(ctx, "UPDATE organizations SET workspace_sharing_disabled = true WHERE id = $1", user.OrganizationID)
_, err := sqlDB.ExecContext(ctx, "UPDATE organizations SET shareable_workspace_owners = 'none' WHERE id = $1", user.OrganizationID)
require.NoError(t, err)
//nolint:gocritic // ReconcileOrgMemberRole needs the system:update
// permission that the test context doesn't have.
sysCtx := dbauthz.AsSystemRestricted(ctx)
_, _, err = rolestore.ReconcileOrgMemberRole(sysCtx, api.Database, database.CustomRole{
_, _, err = rolestore.ReconcileSystemRole(sysCtx, api.Database, database.CustomRole{
Name: rbac.RoleOrgMember(),
OrganizationID: uuid.NullUUID{
UUID: user.OrganizationID,
Valid: true,
},
}, true)
}, database.Organization{ShareableWorkspaceOwners: database.ShareableWorkspaceOwnersNone})
require.NoError(t, err)
client1, _ := coderdtest.CreateAnotherUser(t, client, user.OrganizationID)
+9 -11
View File
@@ -16,7 +16,6 @@ import (
"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/rolestore"
"github.com/coder/coder/v2/codersdk"
)
@@ -298,16 +297,15 @@ func (api *API) postOrganizations(rw http.ResponseWriter, r *http.Request) {
//nolint:gocritic // ReconcileOrgMemberRole needs the system:update
// permission that user doesn't have.
sysCtx := dbauthz.AsSystemRestricted(ctx)
_, _, err = rolestore.ReconcileOrgMemberRole(sysCtx, tx, database.CustomRole{
Name: rbac.RoleOrgMember(),
OrganizationID: uuid.NullUUID{
UUID: organizationID,
Valid: true,
},
}, organization.WorkspaceSharingDisabled)
if err != nil {
return xerrors.Errorf("reconcile organization-member role for organization %s: %w",
organizationID, err)
for roleName := range rolestore.SystemRoleNames {
_, _, err = rolestore.ReconcileSystemRole(sysCtx, tx, database.CustomRole{
Name: roleName,
OrganizationID: uuid.NullUUID{UUID: organizationID, Valid: true},
}, organization)
if err != nil {
return xerrors.Errorf("reconcile %s role for organization %s: %w",
roleName, organizationID, err)
}
}
_, err = tx.InsertOrganizationMember(ctx, database.InsertOrganizationMemberParams{
+3 -3
View File
@@ -288,7 +288,8 @@ func TestCustomOrganizationRole(t *testing.T) {
require.ErrorContains(t, err, "not allowed to assign organization member permissions for an organization role")
})
// Attempt to delete a system role, which is not allowed.
// 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()
@@ -306,8 +307,7 @@ func TestCustomOrganizationRole(t *testing.T) {
err := owner.DeleteOrganizationRole(ctx, first.OrganizationID, rbac.RoleOrgMember())
var apiErr *codersdk.Error
require.ErrorAs(t, err, &apiErr)
require.Equal(t, http.StatusBadRequest, apiErr.StatusCode())
require.ErrorContains(t, err, "Reserved role name")
require.Equal(t, http.StatusNotFound, apiErr.StatusCode())
})
t.Run("NotFound", func(t *testing.T) {
+73 -22
View File
@@ -1,7 +1,9 @@
package coderd
import (
"fmt"
"net/http"
"strings"
"golang.org/x/xerrors"
@@ -14,6 +16,7 @@ import (
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/rbac/policy"
"github.com/coder/coder/v2/coderd/rbac/rolestore"
"github.com/coder/coder/v2/coderd/util/slice"
"github.com/coder/coder/v2/codersdk"
)
@@ -34,10 +37,16 @@ func (api *API) workspaceSharingSettings(rw http.ResponseWriter, r *http.Request
return
}
disabled := org.ShareableWorkspaceOwners == database.ShareableWorkspaceOwnersNone
globallyDisabled := bool(api.DeploymentValues.DisableWorkspaceSharing)
owners := codersdk.ShareableWorkspaceOwners(org.ShareableWorkspaceOwners)
if globallyDisabled {
owners = codersdk.ShareableWorkspaceOwnersNone
}
httpapi.Write(ctx, rw, http.StatusOK, codersdk.WorkspaceSharingSettings{
SharingGloballyDisabled: globallyDisabled,
SharingDisabled: org.WorkspaceSharingDisabled || globallyDisabled,
SharingGloballyDisabled: globallyDisabled,
SharingDisabled: disabled || globallyDisabled,
ShareableWorkspaceOwners: owners,
})
}
@@ -48,8 +57,8 @@ func (api *API) workspaceSharingSettings(rw http.ResponseWriter, r *http.Request
// @Accept json
// @Tags Enterprise
// @Param organization path string true "Organization ID" format(uuid)
// @Param request body codersdk.WorkspaceSharingSettings true "Workspace sharing settings"
// @Success 200 {object} codersdk.UpdateWorkspaceSharingSettingsRequest
// @Param request body codersdk.UpdateWorkspaceSharingSettingsRequest true "Workspace sharing settings"
// @Success 200 {object} codersdk.WorkspaceSharingSettings
// @Router /organizations/{organization}/settings/workspace-sharing [patch]
func (api *API) patchWorkspaceSharingSettings(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
@@ -70,19 +79,44 @@ func (api *API) patchWorkspaceSharingSettings(rw http.ResponseWriter, r *http.Re
return
}
var req codersdk.WorkspaceSharingSettings
var req codersdk.UpdateWorkspaceSharingSettingsRequest
if !httpapi.Read(ctx, rw, r, &req) {
return
}
// Resolve the effective enum value. Prefer the new field; fall
// back to the deprecated boolean for older clients (e.g
// tf-provider-coderd v0.0.16)
allowedOwners := req.ShareableWorkspaceOwners
if allowedOwners == "" {
if req.SharingDisabled {
allowedOwners = codersdk.ShareableWorkspaceOwnersNone
} else {
allowedOwners = codersdk.ShareableWorkspaceOwnersEveryone
}
}
if !database.ShareableWorkspaceOwners(allowedOwners).Valid() {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: "Invalid shareable workspace owners value.",
Validations: []codersdk.ValidationError{{
Field: "shareable_workspace_owners",
Detail: fmt.Sprintf("invalid value %q, must be one of [%s]",
allowedOwners,
strings.Join(slice.ToStrings(database.AllShareableWorkspaceOwnersValues()), ", ")),
}},
})
return
}
err := api.Database.InTx(func(tx database.Store) error {
//nolint:gocritic // System context required to look up and reconcile the
// organization-member system role; callers only need `organization:update`
// system roles; callers only need `organization:update`
sysCtx := dbauthz.AsSystemRestricted(ctx)
// Serialize organization workspace-sharing updates with system role
// reconciliation across coderd instances (e.g. during rolling restarts).
// This prevents conflicting writes to the organization-member system role.
// This prevents conflicting writes to the system roles.
// TODO(geokat): Consider finer-grained locks as we add more system roles.
err := tx.AcquireLock(ctx, database.LockIDReconcileSystemRoles)
if err != nil {
@@ -91,38 +125,54 @@ func (api *API) patchWorkspaceSharingSettings(rw http.ResponseWriter, r *http.Re
org, err = tx.UpdateOrganizationWorkspaceSharingSettings(ctx, database.UpdateOrganizationWorkspaceSharingSettingsParams{
ID: org.ID,
WorkspaceSharingDisabled: req.SharingDisabled,
ShareableWorkspaceOwners: database.ShareableWorkspaceOwners(allowedOwners),
UpdatedAt: dbtime.Now(),
})
if err != nil {
return xerrors.Errorf("update organization workspace sharing settings: %w", err)
return xerrors.Errorf("update workspace sharing settings for organization %s: %w",
org.ID, err)
}
role, err := database.ExpectOne(tx.CustomRoles(sysCtx, database.CustomRolesParams{
roles, err := tx.CustomRoles(sysCtx, database.CustomRolesParams{
LookupRoles: []database.NameOrganizationPair{
{
Name: rbac.RoleOrgMember(),
OrganizationID: org.ID,
},
{
Name: rbac.RoleOrgServiceAccount(),
OrganizationID: org.ID,
},
},
// Satisfy linter that requires all fields to be set.
OrganizationID: org.ID,
ExcludeOrgRoles: false,
IncludeSystemRoles: true,
}))
if err != nil {
return xerrors.Errorf("get organization-member role: %w", err)
})
if err != nil || len(roles) != 2 {
return xerrors.Errorf("get member and service-account roles for organization %s: %w",
org.ID, err)
}
_, _, err = rolestore.ReconcileOrgMemberRole(sysCtx, tx, role, req.SharingDisabled)
if err != nil {
return xerrors.Errorf("reconcile organization-member role: %w", err)
}
if req.SharingDisabled {
err = tx.DeleteWorkspaceACLsByOrganization(sysCtx, org.ID)
for _, role := range roles {
_, _, err = rolestore.ReconcileSystemRole(sysCtx, tx, role, org)
if err != nil {
return xerrors.Errorf("delete workspace ACLs by organization: %w", err)
return xerrors.Errorf("reconcile %s role for organization %s: %w",
role.Name, org.ID, err)
}
}
// If sharing is not enabled, delete workspace ACLs to prevent
// ongoing shared use. In "service_accounts" mode, preserve
// ACLs on SA workspaces.
if org.ShareableWorkspaceOwners != database.ShareableWorkspaceOwnersEveryone {
err = tx.DeleteWorkspaceACLsByOrganization(sysCtx, database.DeleteWorkspaceACLsByOrganizationParams{
OrganizationID: org.ID,
ExcludeServiceAccounts: org.ShareableWorkspaceOwners == database.ShareableWorkspaceOwnersServiceAccounts,
})
if err != nil {
return xerrors.Errorf("delete workspace ACLs for organization %s: %w",
org.ID, err)
}
}
@@ -138,6 +188,7 @@ func (api *API) patchWorkspaceSharingSettings(rw http.ResponseWriter, r *http.Re
aReq.New = org
httpapi.Write(ctx, rw, http.StatusOK, codersdk.WorkspaceSharingSettings{
SharingDisabled: org.WorkspaceSharingDisabled,
SharingDisabled: org.ShareableWorkspaceOwners == database.ShareableWorkspaceOwnersNone,
ShareableWorkspaceOwners: codersdk.ShareableWorkspaceOwners(org.ShareableWorkspaceOwners),
})
}
+245 -4
View File
@@ -11,7 +11,9 @@ import (
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbfake"
"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/codersdk"
"github.com/coder/coder/v2/enterprise/coderd/coderdenttest"
"github.com/coder/coder/v2/enterprise/coderd/license"
@@ -34,10 +36,13 @@ func TestWorkspaceSharingSettings(t *testing.T) {
ctx := testutil.Context(t, testutil.WaitMedium)
// Use a regular user to make sure the setting is exposed to them.
memberClient, _ := coderdtest.CreateAnotherUser(t, client, first.OrganizationID)
settings, err := memberClient.WorkspaceSharingSettings(ctx, first.OrganizationID.String())
require.NoError(t, err)
// Check the deprecated boolean field.
require.False(t, settings.SharingDisabled)
require.Equal(t, codersdk.ShareableWorkspaceOwnersEveryone, settings.ShareableWorkspaceOwners)
})
t.Run("DisabledTogglePersists", func(t *testing.T) {
@@ -54,21 +59,59 @@ func TestWorkspaceSharingSettings(t *testing.T) {
ctx := testutil.Context(t, testutil.WaitMedium)
orgAdminClient, _ := coderdtest.CreateAnotherUser(t, client, first.OrganizationID, rbac.ScopedRoleOrgAdmin(first.OrganizationID))
// Disable sharing via the deprecated boolean field.
settings, err := orgAdminClient.PatchWorkspaceSharingSettings(ctx, first.OrganizationID.String(), codersdk.UpdateWorkspaceSharingSettingsRequest{
SharingDisabled: true,
})
require.NoError(t, err)
require.True(t, settings.SharingDisabled)
require.Equal(t, codersdk.ShareableWorkspaceOwnersNone, settings.ShareableWorkspaceOwners)
settings, err = orgAdminClient.WorkspaceSharingSettings(ctx, first.OrganizationID.String())
require.NoError(t, err)
require.True(t, settings.SharingDisabled)
require.Equal(t, codersdk.ShareableWorkspaceOwnersNone, settings.ShareableWorkspaceOwners)
// Switch to service_accounts mode via the new field.
settings, err = orgAdminClient.PatchWorkspaceSharingSettings(ctx, first.OrganizationID.String(), codersdk.UpdateWorkspaceSharingSettingsRequest{
SharingDisabled: false,
ShareableWorkspaceOwners: codersdk.ShareableWorkspaceOwnersServiceAccounts,
})
require.NoError(t, err)
require.False(t, settings.SharingDisabled)
require.Equal(t, codersdk.ShareableWorkspaceOwnersServiceAccounts, settings.ShareableWorkspaceOwners)
settings, err = orgAdminClient.WorkspaceSharingSettings(ctx, first.OrganizationID.String())
require.NoError(t, err)
require.Equal(t, codersdk.ShareableWorkspaceOwnersServiceAccounts, settings.ShareableWorkspaceOwners)
// Re-enable full sharing.
settings, err = orgAdminClient.PatchWorkspaceSharingSettings(ctx, first.OrganizationID.String(), codersdk.UpdateWorkspaceSharingSettingsRequest{
ShareableWorkspaceOwners: codersdk.ShareableWorkspaceOwnersEveryone,
})
require.NoError(t, err)
require.False(t, settings.SharingDisabled)
require.Equal(t, codersdk.ShareableWorkspaceOwnersEveryone, settings.ShareableWorkspaceOwners)
settings, err = orgAdminClient.WorkspaceSharingSettings(ctx, first.OrganizationID.String())
require.NoError(t, err)
require.Equal(t, codersdk.ShareableWorkspaceOwnersEveryone, settings.ShareableWorkspaceOwners)
})
t.Run("InvalidValueRejected", func(t *testing.T) {
t.Parallel()
client, first := coderdenttest.New(t, nil)
ctx := testutil.Context(t, testutil.WaitMedium)
orgAdminClient, _ := coderdtest.CreateAnotherUser(t, client, first.OrganizationID, rbac.ScopedRoleOrgAdmin(first.OrganizationID))
_, err := orgAdminClient.PatchWorkspaceSharingSettings(ctx, first.OrganizationID.String(), codersdk.UpdateWorkspaceSharingSettingsRequest{
ShareableWorkspaceOwners: "invalid",
})
var apiErr *codersdk.Error
require.ErrorAs(t, err, &apiErr)
require.Equal(t, http.StatusBadRequest, apiErr.StatusCode())
})
t.Run("UpdateAuthz", func(t *testing.T) {
@@ -153,7 +196,7 @@ func TestWorkspaceSharingDisabled(t *testing.T) {
orgAdminClient, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID, rbac.ScopedRoleOrgAdmin(owner.OrganizationID))
_, err := orgAdminClient.PatchWorkspaceSharingSettings(ctx, owner.OrganizationID.String(), codersdk.UpdateWorkspaceSharingSettingsRequest{
SharingDisabled: true,
ShareableWorkspaceOwners: codersdk.ShareableWorkspaceOwnersNone,
})
require.NoError(t, err)
@@ -185,6 +228,132 @@ func TestWorkspaceSharingDisabled(t *testing.T) {
assertSharingDisabled(t, err)
})
t.Run("ACLEndpointsForbiddenServiceAccountsMode", func(t *testing.T) {
t.Parallel()
client, db, owner := coderdenttest.NewWithDatabase(t, nil)
regularClient, regularUser := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID)
regularWS := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
OwnerID: regularUser.ID,
OrganizationID: owner.OrganizationID,
}).Do().Workspace
// Create an SA with a workspace.
saClient, saUser := coderdtest.CreateAnotherUserMutators(t, client, owner.OrganizationID, nil, func(r *codersdk.CreateUserRequestWithOrgs) {
r.ServiceAccount = true
})
saWS := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
OwnerID: saUser.ID,
OrganizationID: owner.OrganizationID,
}).Do().Workspace
ctx := testutil.Context(t, testutil.WaitMedium)
orgAdminClient, orgAdmin := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID, rbac.ScopedRoleOrgAdmin(owner.OrganizationID))
_, err := orgAdminClient.PatchWorkspaceSharingSettings(ctx, owner.OrganizationID.String(), codersdk.UpdateWorkspaceSharingSettingsRequest{
ShareableWorkspaceOwners: codersdk.ShareableWorkspaceOwnersServiceAccounts,
})
require.NoError(t, err)
// Regular member cannot share their own workspace.
err = regularClient.UpdateWorkspaceACL(ctx, regularWS.ID, codersdk.UpdateWorkspaceACL{
UserRoles: map[string]codersdk.WorkspaceRole{
orgAdmin.ID.String(): codersdk.WorkspaceRoleUse,
},
})
var apiErr *codersdk.Error
require.ErrorAs(t, err, &apiErr)
require.Equal(t, http.StatusForbidden, apiErr.StatusCode())
// SA can share their own workspace.
err = saClient.UpdateWorkspaceACL(ctx, saWS.ID, codersdk.UpdateWorkspaceACL{
UserRoles: map[string]codersdk.WorkspaceRole{
regularUser.ID.String(): codersdk.WorkspaceRoleUse,
},
})
require.NoError(t, err)
})
// Future-proofing: if custom roles with member-scoped
// workspace:share are ever allowed, the member-level negation
// from the organization-member system role must block sharing in
// service_accounts mode even with such custom role.
t.Run("MemberCannotBypassWithCustomRole", func(t *testing.T) {
t.Parallel()
rawDB, pubsub, sqlDB := dbtestutil.NewDBWithSQLDB(t)
client, _, _, owner := coderdenttest.NewWithAPI(t, &coderdenttest.Options{
Options: &coderdtest.Options{
Database: rawDB,
Pubsub: pubsub,
},
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureCustomRoles: 1,
codersdk.FeatureTemplateRBAC: 1,
},
},
})
ctx := testutil.Context(t, testutil.WaitMedium)
// Create an empty custom role via the API, then add
// member-scoped workspace:share via raw SQL (the API and
// dbauthz both reject member permissions on custom roles).
//nolint:gocritic // owner context required for role creation
customRole, err := client.CreateOrganizationRole(ctx, codersdk.Role{
Name: "workspace-share-granter",
OrganizationID: owner.OrganizationID.String(),
})
require.NoError(t, err)
_, err = sqlDB.ExecContext(ctx,
`UPDATE custom_roles SET member_permissions = $1 WHERE name = $2 AND organization_id = $3`,
database.CustomRolePermissions{{
ResourceType: rbac.ResourceWorkspace.Type,
Action: policy.ActionShare,
}},
customRole.Name,
owner.OrganizationID,
)
require.NoError(t, err)
// Create a member and assign the custom role.
memberClient, memberUser := coderdtest.CreateAnotherUserMutators(
t, client, owner.OrganizationID,
[]rbac.RoleIdentifier{{
Name: customRole.Name,
OrganizationID: owner.OrganizationID,
}},
)
memberWS := dbfake.WorkspaceBuild(t, rawDB, database.WorkspaceTable{
OwnerID: memberUser.ID,
OrganizationID: owner.OrganizationID,
}).Do().Workspace
_, sharedUser := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID)
// Switch to service_accounts mode.
orgAdminClient, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID, rbac.ScopedRoleOrgAdmin(owner.OrganizationID))
_, err = orgAdminClient.PatchWorkspaceSharingSettings(ctx, owner.OrganizationID.String(), codersdk.UpdateWorkspaceSharingSettingsRequest{
ShareableWorkspaceOwners: codersdk.ShareableWorkspaceOwnersServiceAccounts,
})
require.NoError(t, err)
// Despite the custom role granting workspace:share at the
// member level, the negation from organization-member should
// block it.
err = memberClient.UpdateWorkspaceACL(ctx, memberWS.ID, codersdk.UpdateWorkspaceACL{
UserRoles: map[string]codersdk.WorkspaceRole{
sharedUser.ID.String(): codersdk.WorkspaceRoleUse,
},
})
var apiErr *codersdk.Error
require.ErrorAs(t, err, &apiErr)
require.Equal(t, http.StatusForbidden, apiErr.StatusCode())
})
t.Run("ACLsPurged", func(t *testing.T) {
t.Parallel()
@@ -236,12 +405,12 @@ func TestWorkspaceSharingDisabled(t *testing.T) {
orgAdminClient, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID, rbac.ScopedRoleOrgAdmin(owner.OrganizationID))
_, err = orgAdminClient.PatchWorkspaceSharingSettings(ctx, owner.OrganizationID.String(), codersdk.UpdateWorkspaceSharingSettingsRequest{
SharingDisabled: true,
ShareableWorkspaceOwners: codersdk.ShareableWorkspaceOwnersNone,
})
require.NoError(t, err)
_, err = orgAdminClient.PatchWorkspaceSharingSettings(ctx, owner.OrganizationID.String(), codersdk.UpdateWorkspaceSharingSettingsRequest{
SharingDisabled: false,
ShareableWorkspaceOwners: codersdk.ShareableWorkspaceOwnersEveryone,
})
require.NoError(t, err)
@@ -263,4 +432,76 @@ func TestWorkspaceSharingDisabled(t *testing.T) {
require.Len(t, acl.Users, 1)
require.Equal(t, sharedUser.ID, acl.Users[0].ID)
})
t.Run("ACLsPurgedExceptServiceAccounts", func(t *testing.T) {
t.Parallel()
dv := coderdtest.DeploymentValues(t)
client, db, owner := coderdenttest.NewWithDatabase(t, &coderdenttest.Options{
Options: &coderdtest.Options{
DeploymentValues: dv,
},
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureTemplateRBAC: 1,
},
},
})
// Regular user with a workspace.
workspaceOwnerClient, workspaceOwner := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID)
_, sharedUser := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID)
regularWS := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
OwnerID: workspaceOwner.ID,
OrganizationID: owner.OrganizationID,
}).Do().Workspace
// Service account with a workspace.
_, saUser := coderdtest.CreateAnotherUserMutators(t, client, owner.OrganizationID, nil, func(r *codersdk.CreateUserRequestWithOrgs) {
r.ServiceAccount = true
})
saWS := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
OwnerID: saUser.ID,
OrganizationID: owner.OrganizationID,
}).Do().Workspace
ctx := testutil.Context(t, testutil.WaitMedium)
// Share regular user's workspace with sharedUser.
err := workspaceOwnerClient.UpdateWorkspaceACL(ctx, regularWS.ID, codersdk.UpdateWorkspaceACL{
UserRoles: map[string]codersdk.WorkspaceRole{
sharedUser.ID.String(): codersdk.WorkspaceRoleUse,
},
})
require.NoError(t, err)
// Use the owner client (site admin) to share the SA workspace,
// since the SA can't authenticate via the API.
err = client.UpdateWorkspaceACL(ctx, saWS.ID, codersdk.UpdateWorkspaceACL{
UserRoles: map[string]codersdk.WorkspaceRole{
sharedUser.ID.String(): codersdk.WorkspaceRoleUse,
},
})
require.NoError(t, err)
// Switch to service_accounts mode.
orgAdminClient, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID, rbac.ScopedRoleOrgAdmin(owner.OrganizationID))
_, err = orgAdminClient.PatchWorkspaceSharingSettings(ctx, owner.OrganizationID.String(), codersdk.UpdateWorkspaceSharingSettingsRequest{
ShareableWorkspaceOwners: codersdk.ShareableWorkspaceOwnersServiceAccounts,
})
require.NoError(t, err)
// Regular user workspace ACLs should be purged.
acl, err := workspaceOwnerClient.WorkspaceACL(ctx, regularWS.ID)
require.NoError(t, err)
require.Empty(t, acl.Users)
// Service account workspace ACLs should be preserved.
acl, err = client.WorkspaceACL(ctx, saWS.ID)
require.NoError(t, err)
require.Len(t, acl.Users, 1)
require.Equal(t, sharedUser.ID, acl.Users[0].ID)
})
}