Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Merge the workspace owner role into admin (#1086)

Louis Amaudruz820a3458cc8b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ddfa548ee..ef02cac8d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -275,6 +275,18 @@ version of their own to them without also giving them a release of their own.
compares it only when someone signs in.
#### Changed
+- **One role runs a workspace: owner merges into admin.** Every workspace
+ `owner` becomes an `admin`, and every admin now manages every member, other
+ admins included, as well as everything an owner could. A workspace always
+ keeps at least one admin: demoting or removing the last one is refused
+ (409), and so is deleting the account of the last admin of a workspace
+ others are in. Two admins demoting each other at once can't both succeed. A
+ client that still asks for `owner`, in an invitation or a role change, gets
+ `admin`. The organization issue `workspace_without_owner` is now
+ `workspace_without_admin`. The migration is not expand-only: until every
+ replica runs this release, an older one creating a workspace writes `owner`,
+ which the new check refuses, and an older one sees former owners as plain
+ admins with no last-admin rule. Roll every replica together.
- **Only the owner or a workspace admin can change a reference's, reference
type's, package's or library document's visibility.** This tightens
permissions: before, anyone with write access could, so on a publicly
@@ -2548,6 +2560,10 @@ version of their own to them without also giving them a release of their own.
terminal can't be picked. No earlier prompt is sent again.
#### Changed
+- **No Owner role.** Inviting people and changing roles offer Admin and
+ Member, and the copy says "an admin of this workspace" where it said "an
+ owner or admin". A server from before the merge that still reports `owner`
+ shows as Admin, including for workspaces stored before the update.
- **Usage data follows an install to a working agent.** Three new
`activation_milestone` steps (`server_ready`, `agent_ready`,
`first_agent_session`) are each sent once per install, and only by installs
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts
index 402649fef..607903275 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts
@@ -500,10 +500,10 @@ describe('createWorkspace', () => {
});
it('returns the local row for the workspace the gateway minted', async () => {
- createOrganization.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });
+ createOrganization.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'admin' });
listWorkspacesForServer.mockResolvedValue([
workspaceRow({ id: 'ws-1', tenantId: 't1' }),
- workspaceRow({ id: 'ws-9', tenantId: 't9', name: 'Acme', role: 'owner' }),
+ workspaceRow({ id: 'ws-9', tenantId: 't9', name: 'Acme', role: 'admin' }),
]);
const created = await switchServersController.createWorkspace({
@@ -522,7 +522,7 @@ describe('createWorkspace', () => {
* success the install has no trace of.
*/
it('raises when the reconcile that records the workspace fails', async () => {
- createOrganization.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });
+ createOrganization.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'admin' });
reconcileServerWorkspaces.mockRejectedValue(new Error('the gateway stopped answering'));
await expect(
@@ -535,7 +535,7 @@ describe('createWorkspace', () => {
// nothing, would leave the app scoped to a workspace that is not the one just
// made — so it says so instead.
it('raises when the new workspace did not land locally', async () => {
- createOrganization.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'owner' });
+ createOrganization.mockResolvedValue({ id: 't9', slug: 'acme', name: 'Acme', role: 'admin' });
listWorkspacesForServer.mockResolvedValue([workspaceRow({ id: 'ws-1', tenantId: 't1' })]);
await expect(
@@ -566,13 +566,13 @@ describe('addOrganizationWorkspace', () => {
id: 't9',
slug: 'labs',
name: 'Labs',
- role: 'owner',
+ role: 'admin',
organizationId: 'o1',
organizationRole: 'org_admin',
});
listWorkspacesForServer.mockResolvedValue([
workspaceRow({ id: 'ws-1', tenantId: 't1' }),
- workspaceRow({ id: 'ws-9', tenantId: 't9', name: 'Labs', role: 'owner' }),
+ workspaceRow({ id: 'ws-9', tenantId: 't9', name: 'Labs', role: 'admin' }),
]);
const created = await switchServersController.addOrganizationWorkspace({
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
index f0dd79c1d..fab944a79 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
@@ -2618,7 +2618,7 @@ describe('organizations', () => {
id: 't1',
slug: 'acme',
name: 'Acme',
- role: 'owner',
+ role: 'admin',
organization_id: 'o1',
organization_role: 'org_admin',
};
@@ -2626,7 +2626,7 @@ describe('organizations', () => {
id: 't1',
slug: 'acme',
name: 'Acme',
- role: 'owner',
+ role: 'admin',
organizationId: 'o1',
organizationRole: 'org_admin',
};
@@ -2705,7 +2705,7 @@ describe('organizations', () => {
id: 't1',
slug: 'acme',
name: 'Acme',
- role: 'owner',
+ role: 'admin',
organizationId: null,
organizationRole: null,
});
@@ -4062,3 +4062,29 @@ describe('fetchAgentIconChoices', () => {
});
});
});
+
+describe('fetchTenants', () => {
+ beforeEach(() => {
+ getSessionCookie.mockResolvedValue('switch_session=fresh');
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('reads a workspace owner on a server from before the merge as an admin', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () =>
+ jsonResponse([
+ { id: 't1', slug: 'acme', name: 'Acme', role: 'owner' },
+ { id: 't2', slug: 'beta', name: 'Beta', role: 'member' },
+ ])
+ )
+ );
+
+ const tenants = await fetchTenants(SERVER);
+
+ expect(tenants.map((t) => t.role)).toEqual(['admin', 'member']);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
index b9de8d48f..122b29551 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -601,7 +601,7 @@ export async function fetchFeatureFlags(server: SwitchServer): Promise<RemoteFea
/**
* Delete the signed-in account on this server, confirmed by its email. A
- * refusal (the only owner of a shared workspace, the server's own admin, …) is
+ * refusal (the only admin of a shared workspace, the server's own admin, …) is
* raised with the server's own reason, which says what to do first.
*/
export async function deleteMyAccount(server: SwitchServer, email: string): Promise<void> {
@@ -684,7 +684,9 @@ type TenantJson = {
};
function mapRole(raw: unknown): WorkspaceRole {
- if (raw === 'owner' || raw === 'admin' || raw === 'member') return raw;
+ // A server from before `owner` merged into `admin` still reports it.
+ if (raw === 'owner') return 'admin';
+ if (raw === 'admin' || raw === 'member') return raw;
throw new GatewayError('http', `Switch server reported an unknown workspace role: ${raw}`);
}
@@ -989,7 +991,7 @@ function joinDomainsPath(tenantId: string): string {
return `/tenants/${encodeURIComponent(tenantId)}/join-domains`;
}
-/** The domains a workspace is open to. Admins and owners only. */
+/** The domains a workspace is open to. Admins only. */
export async function fetchJoinDomains(
server: SwitchServer,
tenantId: string
@@ -1041,7 +1043,7 @@ function invitationsPath(tenantId: string): string {
return `/tenants/${encodeURIComponent(tenantId)}/invitations`;
}
-/** Every invitation to a workspace, revoked and spent ones included. Admins and owners only. */
+/** Every invitation to a workspace, revoked and spent ones included. Admins only. */
export async function fetchInvitations(
server: SwitchServer,
tenantId: string
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts
index e11b8de19..707c4cf56 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts
@@ -496,7 +496,7 @@ describe('selecting a server', () => {
async function seedWorkspace(
id: string,
tenantId: string | null,
- role: 'owner' | 'member' | null = 'member'
+ role: 'admin' | 'member' | null = 'member'
): Promise<void> {
await fixture.db.insert(workspaces).values({ id, serverId: 'srv-1', name: id, tenantId, role });
}
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
index 2bfaa9907..9cf673287 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
@@ -503,7 +503,7 @@ export const workspacesController = createRPCController({
listRooms: (workspaceId: string): Promise<RemoteRoomSummary[]> =>
withWorkspaceSession(workspaceId, fetchRooms),
- /** Admins and owners only; the gateway refuses anyone else with a 403. */
+ /** Admins only; the gateway refuses anyone else with a 403. */
listInvitations: listWorkspaceInvitations,
createInvitation: createWorkspaceInvitation,
@@ -511,8 +511,8 @@ export const workspacesController = createRPCController({
revokeInvitation: revokeWorkspaceInvitation,
/**
- * The e-mail domains anyone may join the workspace from. Admins and owners
- * only, and an admin may add only the domain of their own address.
+ * The e-mail domains anyone may join the workspace from. Admins only, and an
+ * admin may add only the domain of their own address.
*/
listJoinDomains: listWorkspaceJoinDomains,
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts
index 1832f790d..f2c26324e 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/reconcile-workspaces.db.test.ts
@@ -115,7 +115,7 @@ describe('reconcile-workspaces', () => {
*/
it('claims the server’s existing workspace for its sole membership', async () => {
const before = await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
- fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'owner')]);
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'admin')]);
await reconcileServerWorkspaces('srv-1');
@@ -125,13 +125,13 @@ describe('reconcile-workspaces', () => {
// name this id, and a replacement would detach every one of them.
expect(found[0]!.id).toBe(before.id);
expect(found[0]!.tenantId).toBe('t-1');
- expect(found[0]!.role).toBe('owner');
+ expect(found[0]!.role).toBe('admin');
});
it('records each workspace’s organization, its name and the account’s role in it', async () => {
await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
fetchTenants.mockResolvedValue([
- tenant('t-1', 'Default', 'owner', { id: 'o-1', role: 'org_admin' }),
+ tenant('t-1', 'Default', 'admin', { id: 'o-1', role: 'org_admin' }),
tenant('t-2', 'Research', 'member', { id: 'o-2', role: 'member' }),
]);
fetchOrganizationNames.mockResolvedValue(
@@ -156,7 +156,7 @@ describe('reconcile-workspaces', () => {
it('does not ask a server from before organizations to name any', async () => {
await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
- fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'owner')]);
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'admin')]);
await reconcileServerWorkspaces('srv-1');
@@ -172,7 +172,7 @@ describe('reconcile-workspaces', () => {
it('records the workspace, and says so, where the server cannot name its organization', async () => {
await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
fetchTenants.mockResolvedValue([
- tenant('t-1', 'Default', 'owner', { id: 'o-1', role: 'org_admin' }),
+ tenant('t-1', 'Default', 'admin', { id: 'o-1', role: 'org_admin' }),
]);
fetchOrganizationNames.mockRejectedValue(new Error('Switch gateway returned 503'));
@@ -193,7 +193,7 @@ describe('reconcile-workspaces', () => {
it('keeps the names it has when a later reconcile cannot read them', async () => {
await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
fetchTenants.mockResolvedValue([
- tenant('t-1', 'Default', 'owner', { id: 'o-1', role: 'org_admin' }),
+ tenant('t-1', 'Default', 'admin', { id: 'o-1', role: 'org_admin' }),
]);
fetchOrganizationNames.mockResolvedValue(new Map([['o-1', 'Acme']]));
await reconcileServerWorkspaces('srv-1');
@@ -208,13 +208,13 @@ describe('reconcile-workspaces', () => {
it('drops a kept name once the workspace has moved to another organization', async () => {
await ensureServerWorkspace({ id: 'srv-1', name: 'Local dev' });
fetchTenants.mockResolvedValue([
- tenant('t-1', 'Default', 'owner', { id: 'o-1', role: 'org_admin' }),
+ tenant('t-1', 'Default', 'admin', { id: 'o-1', role: 'org_admin' }),
]);
fetchOrganizationNames.mockResolvedValue(new Map([['o-1', 'Acme']]));
await reconcileServerWorkspaces('srv-1');
fetchTenants.mockResolvedValue([
- tenant('t-1', 'Default', 'owner', { id: 'o-2', role: 'member' }),
+ tenant('t-1', 'Default', 'admin', { id: 'o-2', role: 'member' }),
]);
fetchOrganizationNames.mockRejectedValue(new Error('Switch gateway returned 503'));
await reconcileServerWorkspaces('srv-1');
@@ -228,7 +228,7 @@ describe('reconcile-workspaces', () => {
id: 't-1',
slug: 't-1',
name: 'Default',
- role: 'owner',
+ role: 'admin',
organizationId: 'o-1',
organizationName: 'Acme',
organizationRole: 'org_admin',
@@ -254,7 +254,7 @@ describe('reconcile-workspaces', () => {
// The placeholder is left alone, so the agents and selection naming it stay put.
expect((await listWorkspacesForServer('srv-1')).map((w) => w.id)).toEqual([placeholder.id]);
- fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'owner')]);
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'admin')]);
await reconcileServerWorkspaces('srv-1');
expect(listServersWithoutMembership()).toEqual([]);
@@ -395,7 +395,7 @@ describe('reconcile-workspaces', () => {
id: 't-1',
slug: 't-1',
name: 'Default',
- role: 'owner',
+ role: 'admin',
organizationId: null,
organizationName: null,
organizationRole: null,
@@ -541,13 +541,13 @@ describe('reconcile-workspaces', () => {
id: 't-previous',
slug: 't-previous',
name: 'Previous account’s',
- role: 'owner',
+ role: 'admin',
organizationId: null,
organizationName: null,
organizationRole: null,
});
await setActiveWorkspaceId(previous.id);
- fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'owner')]);
+ fetchTenants.mockResolvedValue([tenant('t-1', 'Default', 'admin')]);
await reconcileServerWorkspaces('srv-1');
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts
index 98fc6df27..4f9a24399 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/workspaces-store.ts
@@ -55,7 +55,9 @@ function mapRow(row: WorkspaceRow): Workspace {
name: row.name,
tenantId: row.tenantId ?? null,
slug: row.slug ?? null,
- role: row.role ?? null,
+ // A row written before `owner` merged into `admin` holds `owner` until the
+ // next reconcile rewrites it.
+ role: (row.role as string | null) === 'owner' ? 'admin' : (row.role ?? null),
organizationId: row.organizationId ?? null,
organizationName: row.organizationName ?? null,
organizationRole: row.organizationRole ?? null,
diff --git a/console/apps/switch-console-desktop/src/main/db/schema.ts b/console/apps/switch-console-desktop/src/main/db/schema.ts
index 853c01274..6afa5af88 100644
--- a/console/apps/switch-console-desktop/src/main/db/schema.ts
+++ b/console/apps/switch-console-desktop/src/main/db/schema.ts
@@ -167,7 +167,7 @@ export const workspaces = sqliteTable(
slug: text('slug'),
/**
* The caller's role in the workspace as the gateway last reported it
- * (`owner` / `admin` / `member`). Null for a tenant-less workspace, where
+ * (`admin` / `member`). Null for a tenant-less workspace, where
* the notion does not apply.
*/
role: text('role').$type<WorkspaceRole>(),
diff --git a/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.ts b/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.ts
index 328f9d63d..370e2de87 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/deeplinks/open-console-link.ts
@@ -173,7 +173,7 @@ function openAdmin(serverId: string, tab: string | null): void {
}
appState.navigation.navigate('server', { serverId });
toast.error('Admin is for workspace admins', {
- description: 'Ask an owner or admin of this workspace to change these.',
+ description: 'Ask an admin of this workspace to change these.',
});
return;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
index 82977887a..51e6afbc9 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
@@ -334,8 +334,8 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
{server && !isAdmin && (
<p className="text-xs text-destructive">
- Connecting a messaging app requires an owner or admin of this workspace. You are a
- member without admin rights, so the server would reject this.
+ Connecting a messaging app requires an admin of this workspace. You are a member
+ without admin rights, so the server would reject this.
</p>
)}
@@ -609,7 +609,7 @@ function messageFor(result: Exclude<CreateBridgeResult, { kind: 'created' }>): s
case 'unauthenticated':
return 'Your session for this server expired. Sign in again, then retry.';
case 'forbidden':
- return 'Connecting a messaging app requires an owner or admin of this workspace.';
+ return 'Connecting a messaging app requires an admin of this workspace.';
case 'invalid':
// The gateway validated the credentials against the platform's own config
// model, so its wording is more specific than anything we could invent.
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx
index 88c63afb5..aac4d6777 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx
@@ -156,7 +156,7 @@ function messageFor(result: Exclude<DeleteBridgeResult, { kind: 'deleted' }>): s
case 'unauthenticated':
return 'Your session for this server expired. Sign in again, then retry.';
case 'forbidden':
- return 'Disconnecting a messaging app requires an owner or admin of this workspace.';
+ return 'Disconnecting a messaging app requires an admin of this workspace.';
case 'not-found':
return 'That messaging app is no longer connected to this server.';
case 'error':
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
index a0114f1d7..41c1c93a4 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
@@ -71,7 +71,7 @@ import { administersWorkspaceInScope } from './workspace-admin';
/**
* The messaging apps bridged to a server, which account in each one is the
- * signed-in user, and — for a workspace owner or admin — the way to connect another
+ * signed-in user, and — for a workspace admin — the way to connect another
* (CHOO-1784, CHOO-2137).
*
* One row per app: its name with the account you have claimed on it underneath,
@@ -378,12 +378,12 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
) : bridges.length === 0 && !bridgesQuery.isLoading ? (
<p className="mt-3 text-xs text-foreground-muted">
{chatsWithoutApp
- ? `No messaging app is connected. They are optional: chats and rooms in Switch Console work without one. ${isAdmin ? 'Connect one to also reach your agents from Slack, Discord and others.' : administers ? 'Connect one from Admin to also reach your agents from Slack, Discord and others.' : 'An owner or admin of this workspace can connect one to reach your agents from Slack, Discord and others.'}`
+ ? `No messaging app is connected. They are optional: chats and rooms in Switch Console work without one. ${isAdmin ? 'Connect one to also reach your agents from Slack, Discord and others.' : administers ? 'Connect one from Admin to also reach your agents from Slack, Discord and others.' : 'An admin of this workspace can connect one to reach your agents from Slack, Discord and others.'}`
: isAdmin
? 'No messaging app is connected, so rooms created here would be unreachable. Connect one to get started.'
: administers
? 'No messaging app is connected. Connect one from Admin.'
- : 'No messaging app is connected. An owner or admin of this workspace can connect one.'}
+ : 'No messaging app is connected. An admin of this workspace can connect one.'}
</p>
) : (
<div className="mt-2 flex flex-col">
@@ -672,7 +672,7 @@ export function MessagingAppRow({
const channelsLockedReason = !bridge.channelCreationSupported
? `${platform} cannot create channels from Switch. Make the chat in the app and add the bot to it.`
: !isAdmin
- ? 'Only an owner or admin of this workspace can change this.'
+ ? 'Only an admin of this workspace can change this.'
: null;
return (
@@ -1008,7 +1008,7 @@ function messageForUpdate(result: { kind: string; message?: string }): string {
case 'unauthenticated':
return 'Your session for this server expired. Sign in again, then retry.';
case 'forbidden':
- return 'This requires an owner or admin of this workspace.';
+ return 'This requires an admin of this workspace.';
default:
return result.message ?? 'The server rejected the change.';
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ReplaceTokenModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ReplaceTokenModal.tsx
index 661a0ab1e..cda052dbd 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ReplaceTokenModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ReplaceTokenModal.tsx
@@ -172,7 +172,7 @@ function messageFor(result: Exclude<UpdateBridgeResult, { kind: 'updated' }>): s
case 'unauthenticated':
return 'Your session for this server expired. Sign in again, then retry.';
case 'forbidden':
- return 'Replacing a token requires an owner or admin of this workspace.';
+ return 'Replacing a token requires an admin of this workspace.';
case 'invalid':
case 'error':
return result.message;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/TeamsPlacementModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/TeamsPlacementModal.tsx
index 994233efa..db7c0e316 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/TeamsPlacementModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/TeamsPlacementModal.tsx
@@ -382,7 +382,7 @@ function teamsResultFailureText(result: Exclude<TeamsTeamsResult, { kind: 'liste
case 'unauthenticated':
return 'Your session for this server expired. Sign in again, then retry.';
case 'forbidden':
- return 'Managing teams requires an owner or admin of this workspace.';
+ return 'Managing teams requires an admin of this workspace.';
case 'error':
return result.message;
}
@@ -395,7 +395,7 @@ function addTeamFailureText(result: Exclude<AddTeamsTeamResult, { kind: 'added'
case 'unauthenticated':
return 'Your session for this server expired. Sign in again, then retry.';
case 'forbidden':
- return 'Managing teams requires an owner or admin of this workspace.';
+ return 'Managing teams requires an admin of this workspace.';
case 'error':
return result.message;
}
@@ -408,7 +408,7 @@ function removeTeamFailureText(
case 'unauthenticated':
return 'Your session for this server expired. Sign in again, then retry.';
case 'forbidden':
- return 'Managing teams requires an owner or admin of this workspace.';
+ return 'Managing teams requires an admin of this workspace.';
case 'error':
return result.message;
}
@@ -419,7 +419,7 @@ function setDefaultFailureText(result: Exclude<UpdateBridgeResult, { kind: 'upda
case 'unauthenticated':
return 'Your session for this server expired. Sign in again, then retry.';
case 'forbidden':
- return 'Managing teams requires an owner or admin of this workspace.';
+ return 'Managing teams requires an admin of this workspace.';
case 'invalid':
return result.message;
case 'error':
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-admin.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-admin.ts
index 8063a04ed..3abb01758 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-admin.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-admin.ts
@@ -12,7 +12,7 @@ export function operatesServer(serverId: string): boolean {
/**
* Whether the signed-in account may manage the workspace a view about
- * `serverId` acts in: an owner or admin of that workspace, or the operator
+ * `serverId` acts in: an admin of that workspace, or the operator
* running the server, whom the gateway lets administer every workspace.
*/
export function administersWorkspaceInScope(serverId: string): boolean {
@@ -23,7 +23,7 @@ export function administersWorkspaceInScope(serverId: string): boolean {
/**
* Whether the signed-in account may manage the workspace `workspaceId` names:
- * an owner or admin of it, or the operator running its server.
+ * an admin of it, or the operator running its server.
*/
export function administersWorkspaceById(workspaceId: string): boolean {
const serverId = workspacesStore.serverIdFor(workspaceId);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/invite-people-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/workspaces/invite-people-modal.tsx
index cd3d67b8d..00a7145f9 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/invite-people-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/invite-people-modal.tsx
@@ -41,7 +41,7 @@ import {
import type { WorkspaceRole } from '@shared/core/workspaces/workspaces';
type InvitePeopleModalArgs = {
- /** The workspace to invite to. Its admins and owners are the only ones offered this. */
+ /** The workspace to invite to. Its admins are the only ones offered this. */
workspaceId: string;
};
@@ -56,7 +56,6 @@ const EXPIRY_CHOICES = [
const ROLE_LABEL: Record<WorkspaceRole, string> = {
member: 'Member',
admin: 'Admin',
- owner: 'Owner',
};
const STATUS_LABEL: Record<InvitationStatus, string> = {
@@ -201,8 +200,7 @@ export const InvitePeopleModal = observer(function InvitePeopleModal({
);
}
- const roles: WorkspaceRole[] =
- workspace.role === 'owner' ? ['member', 'admin', 'owner'] : ['member', 'admin'];
+ const roles: WorkspaceRole[] = ['member', 'admin'];
const trimmedEmail = email.trim();
const usesNumber = Number(uses);
const usesValid = Number.isInteger(usesNumber) && usesNumber > 0;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/workspaces/organization-groups.test.ts b/console/apps/switch-console-desktop/src/renderer/features/workspaces/organization-groups.test.ts
index a3de446b5..d660165d8 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/workspaces/organization-groups.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/workspaces/organization-groups.test.ts
@@ -119,7 +119,7 @@ describe('addWorkspaceThrough', () => {
});
it('offers nothing on a server from before organizations', () => {
- const all = [workspace('a', null, { role: 'owner' })];
+ const all = [workspace('a', null, { role: 'admin' })];
const [group] = groupByOrganization(all);
expect(addWorkspaceThrough(group!, all, null)).toBeNull();
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/create-workspace-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/create-workspace-modal.test.tsx
index 3455d4d3a..f3d45725a 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/create-workspace-modal.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/create-workspace-modal.test.tsx
@@ -65,7 +65,7 @@ function workspace(id: string, serverId: string) {
name: 'Weekend Robotics',
tenantId: 't1',
slug: 'weekend-robotics',
- role: 'owner' as const,
+ role: 'admin' as const,
createdAt: '',
updatedAt: '',
};
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/delete-account-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/delete-account-modal.test.tsx
index c9c105801..9d4465e7f 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/delete-account-modal.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/delete-account-modal.test.tsx
@@ -96,13 +96,13 @@ describe('DeleteAccountModal', () => {
it("shows the server's reason when it refuses", async () => {
deleteAccount.mockRejectedValueOnce(
- new Error("You're the only owner of Acme, which has other members.")
+ new Error("You're the only admin of Acme, which has other members.")
);
await render();
await type('[email protected]');
await act(async () => button('Delete my account').click());
expect(document.querySelector('[role="alert"]')?.textContent).toBe(
- "You're the only owner of Acme, which has other members."
+ "You're the only admin of Acme, which has other members."
);
});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/disconnect-messaging-app-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/disconnect-messaging-app-modal.test.tsx
index 0ebca3679..43e4bd3eb 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/disconnect-messaging-app-modal.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/disconnect-messaging-app-modal.test.tsx
@@ -193,7 +193,7 @@ describe('confirming and disconnecting', () => {
await click(confirmButton(el));
await settle();
- expect(el.textContent).toContain('requires an owner or admin of this workspace');
+ expect(el.textContent).toContain('requires an admin of this workspace');
});
it('says the app is already gone rather than retrying a disconnect', async () => {
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/invite-people-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/invite-people-modal.test.tsx
index f6affff99..537670ca4 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/invite-people-modal.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/invite-people-modal.test.tsx
@@ -57,7 +57,7 @@ import { administersWorkspace } from '@shared/core/workspaces/workspaces';
const onClose = vi.fn();
-function workspace(role: 'owner' | 'admin' | 'member') {
+function workspace(role: 'admin' | 'member') {
return {
id: 'ws-1',
serverId: 'srv-1',
@@ -149,8 +149,7 @@ async function type(input: HTMLInputElement, value: string): Promise<void> {
}
describe('the invite-people modal', () => {
- it('is offered to admins and owners, not members', () => {
- expect(administersWorkspace(workspace('owner') as never)).toBe(true);
+ it('is offered to admins, not members', () => {
expect(administersWorkspace(workspace('admin') as never)).toBe(true);
expect(administersWorkspace(workspace('member') as never)).toBe(false);
});
@@ -300,7 +299,7 @@ describe('the invite-people modal', () => {
expect(listInvitations).toHaveBeenCalledTimes(2);
});
- it('does not let an admin hand out ownership', async () => {
+ it('offers the two roles there are', async () => {
listInvitations.mockResolvedValue({ invitations: [], emailEnabled: true });
byId.mockReturnValue(workspace('admin'));
const el = await render();
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/teams-placement-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/teams-placement-modal.test.tsx
index f891e7c56..809c48652 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/teams-placement-modal.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/teams-placement-modal.test.tsx
@@ -228,7 +228,7 @@ describe('non-listed results', () => {
it('names the admin requirement for a non-admin', async () => {
listBridgeTeams.mockResolvedValue({ kind: 'forbidden' });
const el = await render();
- expect(el.textContent).toContain('requires an owner or admin of this workspace');
+ expect(el.textContent).toContain('requires an admin of this workspace');
});
it('shows a generic error’s own message', async () => {
@@ -359,7 +359,7 @@ describe('adding Switch to a team', () => {
await act(async () => button(el, 'Add').click());
await settle();
- expect(el.textContent).toContain('requires an owner or admin of this workspace');
+ expect(el.textContent).toContain('requires an admin of this workspace');
});
it('shows a generic error’s own message', async () => {
@@ -447,7 +447,7 @@ describe('removing Switch from a team', () => {
await act(async () => button(el, 'Remove').click());
await settle();
- expect(el.textContent).toContain('requires an owner or admin of this workspace');
+ expect(el.textContent).toContain('requires an admin of this workspace');
});
it('shows a generic error’s own message', async () => {
@@ -562,7 +562,7 @@ describe('making a team the default', () => {
await act(async () => button(el, 'Make default').click());
await settle();
- expect(el.textContent).toContain('requires an owner or admin of this workspace');
+ expect(el.textContent).toContain('requires an admin of this workspace');
});
it('shows the server’s own sentence for a rejected choice (422 → invalid)', async () => {
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-admin.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-admin.test.ts
index a504c1d02..078abc2d5 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-admin.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-admin.test.ts
@@ -16,7 +16,7 @@ function signedInAs(role: 'admin' | 'user') {
statusFor.mockReturnValue({ user: { id: 'u-1', role } });
}
-function inWorkspaceAs(role: 'owner' | 'admin' | 'member' | null) {
+function inWorkspaceAs(role: 'admin' | 'member' | null) {
onServerInScope.mockReturnValue({ id: 'ws-1', tenantId: 't-1', role });
}
@@ -26,10 +26,8 @@ describe('administersWorkspaceInScope', () => {
statusFor.mockReset().mockReturnValue(undefined);
});
- it('lets an owner or admin of the workspace manage it', () => {
+ it('lets an admin of the workspace manage it', () => {
signedInAs('user');
- inWorkspaceAs('owner');
- expect(administersWorkspaceInScope('srv-1')).toBe(true);
inWorkspaceAs('admin');
expect(administersWorkspaceInScope('srv-1')).toBe(true);
});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx
index ff2eca324..ab234c9b1 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx
@@ -416,7 +416,7 @@ describe('inviting people from the switcher', () => {
[server('srv-1', 'Acme')],
[
workspace('ws-a', 'srv-1', { role: 'admin' }),
- workspace('ws-b', 'srv-1', { role: 'owner' }),
+ workspace('ws-b', 'srv-1', { role: 'admin' }),
],
'ws-a'
);
@@ -484,7 +484,7 @@ describe('organizations in the switcher', () => {
await openSwitcher(
[server('srv-1', 'Cloud')],
[
- workspace('ws-a', 'srv-1', { organization: ACME, role: 'owner' }),
+ workspace('ws-a', 'srv-1', { organization: ACME, role: 'admin' }),
workspace('ws-b', 'srv-1', { organization: GLOBEX }),
workspace('ws-c', 'srv-1', { organization: ACME }),
],
@@ -503,7 +503,7 @@ describe('organizations in the switcher', () => {
await openSwitcher(
[server('srv-1', 'Cloud')],
[
- workspace('ws-a', 'srv-1', { organization: ACME, role: 'owner' }),
+ workspace('ws-a', 'srv-1', { organization: ACME, role: 'admin' }),
workspace('ws-b', 'srv-1', { organization: { id: 'o-9', name: null, role: 'member' } }),
],
'ws-a'
@@ -519,7 +519,7 @@ describe('organizations in the switcher', () => {
await openSwitcher(
[server('srv-1', 'Cloud')],
[
- workspace('ws-a', 'srv-1', { organization: ACME, role: 'owner' }),
+ workspace('ws-a', 'srv-1', { organization: ACME, role: 'admin' }),
workspace('ws-b', 'srv-1', { organization: GLOBEX }),
],
'ws-a'
@@ -545,7 +545,7 @@ describe('organizations in the switcher', () => {
state.organizations.add('srv-1');
await openSwitcher(
[server('srv-1', 'Cloud')],
- [workspace('ws-a', 'srv-1', { organization: ACME, role: 'owner' })],
+ [workspace('ws-a', 'srv-1', { organization: ACME, role: 'admin' })],
'ws-a'
);
await settle();
@@ -558,7 +558,7 @@ describe('organizations in the switcher', () => {
state.noAdd.add('srv-1');
await openSwitcher(
[server('srv-1', 'Cloud')],
- [workspace('ws-a', 'srv-1', { organization: ACME, role: 'owner' })],
+ [workspace('ws-a', 'srv-1', { organization: ACME, role: 'admin' })],
'ws-a'
);
await settle();
@@ -788,7 +788,7 @@ describe('the server switcher on a build without Switch Cloud', () => {
it('lists servers, not workspaces, and offers no workspace actions', async () => {
await openSwitcher(
[server('srv-1', 'Acme'), server('srv-2', 'Local dev')],
- [workspace('ws-a', 'srv-1', { role: 'owner' }), workspace('ws-c', 'srv-2')],
+ [workspace('ws-a', 'srv-1', { role: 'admin' }), workspace('ws-c', 'srv-2')],
'ws-a',
'Switch server'
);
diff --git a/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts b/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts
index 692cb07bc..180b5b740 100644
--- a/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/workspaces/workspaces.ts
@@ -9,7 +9,7 @@
*/
/** The caller's standing in a workspace, as the gateway reports it. */
-export type WorkspaceRole = 'owner' | 'admin' | 'member';
+export type WorkspaceRole = 'admin' | 'member';
/**
* The caller's standing in the organization a workspace belongs to. An
@@ -60,7 +60,7 @@ export type Workspace = {
* messaging apps — which the gateway also enforces.
*/
export function administersWorkspace(workspace: Workspace): boolean {
- return workspace.role === 'owner' || workspace.role === 'admin';
+ return workspace.role === 'admin';
}
/**
diff --git a/console/packages/agent-providers/src/host/room-prompt.test.ts b/console/packages/agent-providers/src/host/room-prompt.test.ts
index f383b5db2..b1ea94053 100644
--- a/console/packages/agent-providers/src/host/room-prompt.test.ts
+++ b/console/packages/agent-providers/src/host/room-prompt.test.ts
@@ -66,4 +66,9 @@ describe('a room command', () => {
expect(text(fromMember)).toContain('[Switch] Owner (workspace member) addressed you');
expect(text(event)).toContain('[Switch] Owner addressed you');
});
+
+ it('reads a workspace owner from a server before the merge as an admin', () => {
+ const fromOwner = { ...event, payload: { ...event.payload, sender_role: 'owner' } };
+ expect(text(fromOwner)).toContain('[Switch] Owner (workspace admin) addressed you');
+ });
});
diff --git a/console/packages/agent-providers/src/host/room-prompt.ts b/console/packages/agent-providers/src/host/room-prompt.ts
index dbc3ea40d..7bac5e680 100644
--- a/console/packages/agent-providers/src/host/room-prompt.ts
+++ b/console/packages/agent-providers/src/host/room-prompt.ts
@@ -32,7 +32,11 @@ export const roomMessageSchema = z.object({
)
.default([]),
opening_message: z.string().nullish(),
- sender_role: z.enum(['owner', 'admin', 'member']).nullish(),
+ // A server from before `owner` merged into `admin` still sends it.
+ sender_role: z
+ .enum(['admin', 'member', 'owner'])
+ .nullish()
+ .transform((role) => (role === 'owner' ? 'admin' : role)),
/** What Switch tells the agent before this message, until it reads about it; absent for nothing. */
switch_notice: z.string().nullish(),
}),
diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.md
index a004aac06..651d9d5f5 100644
--- a/console/packages/plugins/src/switch-skill/SKILL.md
+++ b/console/packages/plugins/src/switch-skill/SKILL.md
@@ -105,7 +105,7 @@ does, and there is no polling tool to call.
- **Messages addressed to you** — `[Switch] <sender> addressed you in room
<room> (message_id …[, thread_id …]):`, the sender named with their role in
- the room's workspace when Switch knows it (`ada (workspace owner)`), read as
+ the room's workspace when Switch knows it (`ada (workspace admin)`), read as
the message arrived, then the sender's own text between a
matching `BEGIN SWITCH MESSAGE <nonce>` / `END SWITCH MESSAGE <nonce>` pair,
then a parenthetical naming any downloaded attachments. Everything between
diff --git a/console/packages/switch-agent-runtime/src/types.ts b/console/packages/switch-agent-runtime/src/types.ts
index 2c8c31607..2bd676713 100644
--- a/console/packages/switch-agent-runtime/src/types.ts
+++ b/console/packages/switch-agent-runtime/src/types.ts
@@ -37,8 +37,10 @@ export interface MessagePayload {
attachments?: AttachmentRef[];
/** The words the chat opened with, posted in the agent's name as it joined; absent elsewhere. */
opening_message?: string | null;
- /** The sending person's role in the workspace when the message arrived. */
- sender_role?: 'owner' | 'admin' | 'member' | null;
+ /** The sending person's role in the workspace when the message arrived. A
+ * server from before `owner` merged into `admin` may still send `owner`,
+ * which means `admin`. */
+ sender_role?: 'admin' | 'member' | 'owner' | null;
}
export interface CommandPayload {
diff --git a/console/tooling-e2e/src/clients/switch-client.ts b/console/tooling-e2e/src/clients/switch-client.ts
index 97d515e66..c6cc3635e 100644
--- a/console/tooling-e2e/src/clients/switch-client.ts
+++ b/console/tooling-e2e/src/clients/switch-client.ts
@@ -445,7 +445,7 @@ export class SwitchClient {
}
/**
- * `POST /gateway/tenants` — create a workspace. The caller becomes its owner
+ * `POST /gateway/tenants` — create a workspace. The caller becomes its admin
* and the server re-mints their session into it, so from here on this client
* acts in the new workspace.
*/
@@ -471,7 +471,7 @@ export class SwitchClient {
/**
* `POST /gateway/organizations` — create an organization with its first
* workspace. The caller becomes its organization admin and the workspace's
- * owner, and the server re-mints their session into the workspace, so from
+ * admin, and the server re-mints their session into the workspace, so from
* here on this client acts there.
*/
async createOrganization(name: string): Promise<{
diff --git a/console/tooling-e2e/src/fast/cross-tenant.ts b/console/tooling-e2e/src/fast/cross-tenant.ts
index 4e4a62c6e..0d0f83b69 100644
--- a/console/tooling-e2e/src/fast/cross-tenant.ts
+++ b/console/tooling-e2e/src/fast/cross-tenant.ts
@@ -63,7 +63,7 @@ export async function otherTenantAndProber(
const ownerEmail = `${names.name('owner')}@e2e.invalid`;
const proberEmail = `${names.name('prober')}@e2e.invalid`;
await admin.createUser({
- name: 'E2E workspace owner',
+ name: 'E2E workspace admin',
email: ownerEmail,
password,
role: 'admin',
diff --git a/console/tooling-e2e/src/fast/organizations.ts b/console/tooling-e2e/src/fast/organizations.ts
index 23821165d..5859c865f 100644
--- a/console/tooling-e2e/src/fast/organizations.ts
+++ b/console/tooling-e2e/src/fast/organizations.ts
@@ -64,7 +64,7 @@ export const organizations: FastScenario = {
const { organization, workspace } = await founder.createOrganization(names.name('org'));
expect(organization.role).toBe('org_admin');
expect(workspace).toMatchObject({
- role: 'owner',
+ role: 'admin',
organization_role: 'org_admin',
organization_id: organization.id,
});
diff --git a/core/switch_core/accounts/deletion.py b/core/switch_core/accounts/deletion.py
index 5a2b93b2b..8d9ba045c 100644
--- a/core/switch_core/accounts/deletion.py
+++ b/core/switch_core/accounts/deletion.py
@@ -4,7 +4,7 @@ Everything they own goes, and everything that only names them stops naming
them, so the `users` row can be deleted without any foreign key holding it
back. What other people depend on is handed over or kept: rooms they created
stay, with no owner, for the workspace's admins to manage, and the invitations,
-join domains and messaging installs they set up pass to another owner of the
+join domains and messaging installs they set up pass to another admin of the
workspace.
Nothing is deleted until every refusal has been checked, so a refused deletion
@@ -13,7 +13,7 @@ ahead would strand something nobody else could reach:
- the server's own administrator account, which the server recreates on every
start anyway;
-- a workspace with other people in it whose only owner is this person;
+- a workspace with other people in it whose only admin is this person;
- an organization with other people in it whose only `org_admin` is this
person;
- a cloud machine, whose teardown is driven from its row;
@@ -221,12 +221,12 @@ class AccountDeletion:
if (
not alone
and await self.users.tenant_role(session, workspace.id, user.id)
- == "owner"
- and await self.users.count_owners(session) <= 1
+ == "admin"
+ and await self.users.lock_admins(session) <= 1
):
return (
- f"You're the only owner of {workspace.name}, which has other "
- "members. Make one of them an owner first."
+ f"You're the only admin of {workspace.name}, which has other "
+ "members. Make one of them an admin first."
)
if alone:
platform = await session.scalar(
@@ -422,6 +422,7 @@ class AccountDeletion:
await self._revoke_controllers(tenant_id, user_id, controller_ids)
async with tenant_session(self.session_factory, tenant_id) as session:
+ await self._still_not_the_last_admin(session, user_id, workspace)
successor = await self._successor(session, user_id)
try:
removed_services = await self.broker.remove_connections(
@@ -481,18 +482,42 @@ class AccountDeletion:
warning,
)
+ async def _still_not_the_last_admin(
+ self, session: AsyncSession, user_id: str, workspace: Workspace
+ ) -> None:
+ """Check `refusal`'s last-admin rule again, in the transaction that
+ removes the membership and with the admin rows locked: another admin
+ may have been demoted or removed since `refusal` read them.
+
+ Their own membership row decides, not `workspace.role`: that is the
+ role they act with, which is `admin` for the organization's
+ `org_admin` whatever their row says, and only an `admin` row counts
+ towards keeping the workspace one."""
+ if await self.users.tenant_role(session, workspace.id, user_id) != "admin":
+ return
+ members = await self.users.list_tenant_members(session)
+ if all(member.id == user_id for member, _ in members):
+ return
+ if await self.users.lock_admins(session) <= 1:
+ raise RuntimeError(
+ f"Stopped deleting user {user_id} part-way: they became the only "
+ f"admin of workspace {workspace.id}, which has other members, after "
+ "the deletion was checked. Their agents there are already deleted; "
+ "make another member an admin and delete the account again."
+ )
+
async def _successor(self, session: AsyncSession, user_id: str) -> str | None:
"""Who takes over what the workspace still needs from this person: an
- owner, else an admin, else nobody when they are alone in it."""
+ admin, else nobody when no other admin is in it."""
ranked = sorted(
(
(membership.role, member.id)
for member, membership in await self.users.list_tenant_members(session)
if member.id != user_id
),
- key=lambda entry: {"owner": 0, "admin": 1}.get(entry[0], 2),
+ key=lambda entry: 0 if entry[0] == "admin" else 1,
)
- if not ranked or ranked[0][0] not in {"owner", "admin"}:
+ if not ranked or ranked[0][0] != "admin":
return None
return ranked[0][1]
diff --git a/core/switch_core/authz.py b/core/switch_core/authz.py
index 749de97de..9dd028884 100644
--- a/core/switch_core/authz.py
+++ b/core/switch_core/authz.py
@@ -12,10 +12,10 @@ Model:
owner holds there.
- `Principal.is_admin` means "may administer the tenant bound to this
request" — the deployment operator bypass (`User.role == "admin"`, global,
- never granted by anything self-service) OR an `owner`/`admin` membership
- row for this user in the bound tenant (`tenant_members.role`, granted per
- tenant, e.g. by creating it) OR `org_admin` of the organization the bound
- tenant belongs to (`organization_members.role`), which administers every
+ never granted by anything self-service) OR an `admin` membership row for
+ this user in the bound tenant (`tenant_members.role`, granted per tenant,
+ e.g. by creating it) OR `org_admin` of the organization the bound tenant
+ belongs to (`organization_members.role`), which administers every
workspace in it. `administers_tenant` below computes it; a
caller with a database session should use that rather than re-deriving it.
- Owned entities carry a nullable owner plus independent `read_visibility`
@@ -55,7 +55,7 @@ class Principal:
# `tenant_members.role` is a checked string, not an enum type (`db/models.py`).
-TENANT_ADMIN_ROLES = ("owner", "admin")
+TENANT_ADMIN_ROLES = ("admin",)
ORGANIZATION_ADMIN_ROLE = "org_admin"
@@ -74,10 +74,9 @@ def administers_tenant(
True for a deployment operator (the global bypass), regardless of
membership — an operator administers every tenant. True for the
organization's `org_admin`, with or without a membership row in the tenant.
- Otherwise true only if the membership role itself is `owner` or `admin`; a
- plain `member`, or no membership row at all, is false. This is the one
- function that should ever turn a role into an admin bit — see
- `Principal.is_admin`.
+ Otherwise true only if the membership role itself is `admin`; a plain
+ `member`, or no membership row at all, is false. This is the one function
+ that should ever turn a role into an admin bit — see `Principal.is_admin`.
"""
return (
is_operator
@@ -99,22 +98,6 @@ def effective_tenant_role(
return tenant_role
-def owns_tenant(*, is_operator: bool, tenant_role: str | None) -> bool:
- """Whether a caller may dispose of the tenant they hold `tenant_role` in.
-
- Narrower than `administers_tenant` on purpose. An `admin` runs a workspace;
- an `owner` decides who else gets to. The two collapse into one bit for
- everything inside a workspace — rooms, agents, references — but not for the
- ownership set itself: if an admin may grant `owner`, demote an owner, or
- remove one, then an admin may take the workspace, and each of those steps
- passes a last-owner guard on its own. Gate those three on this.
-
- An organization's `org_admin` administers its workspaces but does not own
- them: the organization's role is `admin`-level in each workspace.
- """
- return is_operator or tenant_role == "owner"
-
-
@runtime_checkable
class Authorizable(Protocol):
"""Structural interface for any entity `can` arbitrates over.
diff --git a/core/switch_core/bridges/agent/operations/my_context.py b/core/switch_core/bridges/agent/operations/my_context.py
index 574ea69f3..27fec4fc3 100644
--- a/core/switch_core/bridges/agent/operations/my_context.py
+++ b/core/switch_core/bridges/agent/operations/my_context.py
@@ -58,9 +58,9 @@ async def get_my_context() -> dict[str, Any]:
`you`: {name, can_manage_agents}, the agent making the call.
`person`: your owner, {name, email, workspace_role, workspace_admin,
- runs_server}. `workspace_role` is "owner", "admin" or "member".
+ runs_server}. `workspace_role` is "admin" or "member".
`workspace_admin` is whether they may set up messaging apps and invite
- people: an owner or admin of the workspace, or the server's own
+ people: an admin of the workspace, or the server's own
administrator, which `runs_server` marks.
`workspace`: {id, name, members}.
`server`: {kind, version, features}. `kind` is "switch_cloud",
@@ -180,7 +180,7 @@ async def get_my_context() -> dict[str, Any]:
bridges = await protocol.bridge_store.get_all(session)
services = await _services(session, protocol, connections, agents, grants)
- admin = role in {"owner", "admin"} or owner.role == "admin"
+ admin = role == "admin" or owner.role == "admin"
port = management_port()
managed = (
{
diff --git a/core/switch_core/bridges/agent/protocol/types.py b/core/switch_core/bridges/agent/protocol/types.py
index 277b5f654..afd78a8c8 100644
--- a/core/switch_core/bridges/agent/protocol/types.py
+++ b/core/switch_core/bridges/agent/protocol/types.py
@@ -236,7 +236,7 @@ class MessagePayload(BaseModel):
# it said; None everywhere else.
opening_message: str | None = None
# The sending person's role in the room's workspace when the message
- # arrived: "owner", "admin" or "member". None for an agent, the platform,
+ # arrived: "admin" or "member". None for an agent, the platform,
# or a person no Switch user has claimed.
sender_role: str | None = None
# What Switch has to tell the agent before this message, such as that
diff --git a/core/switch_core/config.py b/core/switch_core/config.py
index 7911fb2d5..a32b322c7 100644
--- a/core/switch_core/config.py
+++ b/core/switch_core/config.py
@@ -386,8 +386,9 @@ class SwitchConfig(BaseSettings):
# rooms. Unbounded self-service creation therefore buys steady-state work
# in the deployment, not storage.
#
- # Counts `owner` memberships only, so being invited into someone else's
- # workspace never spends an allowance the invitee cannot get back. Deployment
+ # Counts workspaces created (`users.workspaces_created`), so being invited
+ # into someone else's workspace never spends an allowance the invitee
+ # cannot get back. Deployment
# operators (`users.role == "admin"`) are exempt, on the same grounds as
# every other operator bypass in `authz.py`: this bounds self-service, and
# an operator provisioning workspaces for other people is not that.
@@ -428,7 +429,7 @@ class SwitchConfig(BaseSettings):
gateway_smtp_password: str | None = None
gateway_smtp_from: str | None = None
# How many e-mailed invitations one workspace may send in 24 hours. With
- # sign-up open anyone can own a workspace, so without this the server is
+ # sign-up open anyone can create a workspace, so without this the server is
# a relay for mail to arbitrary addresses. Operators are not limited.
gateway_invite_emails_per_day: int = 50
diff --git a/core/switch_core/db/audit.py b/core/switch_core/db/audit.py
index 355860043..a3d39c4ea 100644
--- a/core/switch_core/db/audit.py
+++ b/core/switch_core/db/audit.py
@@ -104,7 +104,7 @@ class OrganizationIssueKind(StrEnum):
hand as `OrganizationIssueKind` in the gateway's `data/api.ts`."""
NO_ORG_ADMIN = "no_org_admin"
- WORKSPACE_WITHOUT_OWNER = "workspace_without_owner"
+ WORKSPACE_WITHOUT_ADMIN = "workspace_without_admin"
AGENTS_WITHOUT_ACTING_OWNER = "agents_without_acting_owner"
DIRECTORY_ORGANIZATION_DELETED = "directory_organization_deleted"
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index a6c45cbda..f8e828a09 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -140,9 +140,9 @@ class OrganizationMember(Base):
changing or removing a workspace membership leaves this row as it is. Only
an organization's own `org_admin`s grant or revoke `org_admin`, through
the organization's API. The one exception is migration `238c68b7306e`:
- it made each existing workspace's owners `org_admin` of the organization
- it created for that workspace alone, which gave them nothing they did not
- already control.
+ it made each existing workspace's owners (a role since merged into
+ `admin`) `org_admin` of the organization it created for that workspace
+ alone, which gave them nothing they did not already control.
"""
__tablename__ = "organization_members"
@@ -216,9 +216,7 @@ class TenantMember(Base):
__tablename__ = "tenant_members"
__table_args__ = (
- CheckConstraint(
- "role IN ('owner', 'admin', 'member')", name="ck_tenant_members_role"
- ),
+ CheckConstraint("role IN ('admin', 'member')", name="ck_tenant_members_role"),
)
tenant_id: Mapped[str] = mapped_column(
@@ -370,8 +368,8 @@ class User(Base):
)
# Workspaces this person has created through self-service, which is what
# `GATEWAY_MAX_WORKSPACES_PER_USER` bounds. A count of creations rather
- # than of current ownership, so handing a workspace to someone else does
- # not free an allowance to create another.
+ # than of workspaces administered now, so handing a workspace to another
+ # admin does not free an allowance to create another.
workspaces_created: Mapped[int] = mapped_column(
Integer, server_default=text("0"), nullable=False
)
@@ -625,9 +623,7 @@ class Invitation(TenantScoped, Base):
__tablename__ = "invitations"
__table_args__ = (
Index("ix_invitations_tenant_id", "tenant_id"),
- CheckConstraint(
- "role IN ('owner', 'admin', 'member')", name="ck_invitations_role"
- ),
+ CheckConstraint("role IN ('admin', 'member')", name="ck_invitations_role"),
CheckConstraint(
"uses_remaining >= 0", name="ck_invitations_uses_remaining_not_negative"
),
diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.py
index b84940696..2aa6d466e 100644
--- a/core/switch_core/db/stores/user_store.py
+++ b/core/switch_core/db/stores/user_store.py
@@ -14,7 +14,6 @@ from switch_core.authz import (
TENANT_ADMIN_ROLES,
administers_tenant,
effective_tenant_role,
- owns_tenant,
)
from switch_core.db.models import (
OidcIdentity,
@@ -130,7 +129,7 @@ class UserStore:
`gateway/oidc_routes.py`).
The role mirrors the migration's own mapping for pre-existing users:
- `owner` for the global admin role, `member` otherwise.
+ `admin` for the global admin role, `member` otherwise.
"""
existing = await session.execute(
select(TenantMember.tenant_id).where(TenantMember.user_id == user.id)
@@ -142,7 +141,7 @@ class UserStore:
TenantMember(
tenant_id=tenant_id,
user_id=user.id,
- role="owner" if user.role == "admin" else "member",
+ role="admin" if user.role == "admin" else "member",
)
)
await session.flush()
@@ -489,7 +488,7 @@ class UserStore:
caller's global bit and is a no-op when a membership already exists:
this is the explicit write for the two places that grant a *specific*
role by a caller's own action — creating a workspace (the creator
- becomes its `owner`) and accepting an invitation (the invited role).
+ becomes its `admin`) and accepting an invitation (the invited role).
It does not check for an existing row first; a caller that needs that
checks before calling. Kept as the one place `TenantMember` is
constructed (`tests/switch_core/test_seed_admin_membership.py` pins
@@ -579,7 +578,7 @@ class UserStore:
self, session: AsyncSession, tenant_id: str, user_id: str
) -> bool:
"""Whether `user_id` administers `tenant_id` through a role they hold
- (a workspace admin or owner membership, or `org_admin` of its
+ (a workspace admin membership, or `org_admin` of its
organization), leaving the operator flag out. An operator who does
not is there on `platform_access`."""
return await self._administers(session, tenant_id, user_id, is_operator=False)
@@ -631,22 +630,40 @@ class UserStore:
)
return [(row[0], row[1]) for row in result.all()]
- async def count_owners(self, session: AsyncSession) -> int:
- """How many `owner` memberships exist in the session's bound tenant.
+ async def count_admins(self, session: AsyncSession) -> int:
+ """How many `admin` memberships the session's bound tenant has, locking
+ nothing. For reporting how things stand; a write that must keep an admin
+ counts with `lock_admins` instead."""
+ return (
+ await session.scalar(
+ select(func.count())
+ .select_from(TenantMember)
+ .where(TenantMember.role == "admin")
+ )
+ or 0
+ )
- Backs "a workspace must always have an owner": removing or demoting a
- member is refused when they are the one row this counts.
+ async def lock_admins(self, session: AsyncSession) -> int:
+ """How many `admin` memberships the session's bound tenant has, with
+ each of those rows locked until the transaction ends.
+
+ Backs "a workspace must always have an admin": removing or demoting a
+ member is refused when they are the one row this counts. The lock is
+ what makes that hold when two admins act at once: without it, each of
+ two concurrent demotions counts two admins and both commit. With it,
+ the second waits for the first, and its count leaves out the row the
+ first demoted or removed.
"""
- result = await session.execute(
- select(func.count())
- .select_from(TenantMember)
- .where(TenantMember.role == "owner")
+ result = await session.scalars(
+ select(TenantMember.user_id)
+ .where(TenantMember.role == "admin")
+ .with_for_update()
)
- return result.scalar_one()
+ return len(result.all())
async def administers(self, session: AsyncSession, user: User) -> bool:
"""Whether `user` may administer the tenant bound to `session`'s
- context — the operator bypass, an owner/admin membership in it, or
+ context — the operator bypass, an admin membership in it, or
`org_admin` of its organization.
See `authz.administers_tenant`, which this composes with a read of the
@@ -656,7 +673,7 @@ class UserStore:
RuntimeError: no tenant is bound. The question has no
tenant-independent answer: half of it is a membership row that
cannot be read without one. Answering on the operator bit
- alone would quietly demote a workspace owner to a plain
+ alone would quietly demote a workspace admin to a plain
member, and the symptom — a 403 on their own workspace — says
nothing about why.
"""
@@ -670,23 +687,3 @@ class UserStore:
return await self._administers(
session, tenant_id, user.id, is_operator=user.role == "admin"
)
-
- async def owns(self, session: AsyncSession, user: User) -> bool:
- """Whether `user` may decide who owns the tenant bound to `session`'s
- context — the operator bypass, or an `owner` membership in it.
-
- The same composition as `administers`, over `authz.owns_tenant`; see
- there for why the two are separate bits rather than one.
-
- Raises:
- RuntimeError: no tenant is bound, for the same reason
- `administers` raises.
- """
- tenant_id = current_tenant_id()
- if tenant_id is None:
- raise RuntimeError(
- "owns requires a bound tenant; whether someone owns a "
- "workspace is only answerable about a particular one"
- )
- role = await self.tenant_role(session, tenant_id, user.id)
- return owns_tenant(is_operator=user.role == "admin", tenant_role=role)
diff --git a/core/switch_core/delivery/recipient.py b/core/switch_core/delivery/recipient.py
index de59c7fa0..fb3d271e9 100644
--- a/core/switch_core/delivery/recipient.py
+++ b/core/switch_core/delivery/recipient.py
@@ -1815,7 +1815,7 @@ class AgentRecipient:
self, session: AsyncSession, sender: str, content: Mapping[str, object]
) -> str | None:
"""The sending person's role in this workspace, read as the message
- arrives: "owner", "admin" or "member". None for an agent, the
+ arrives: "admin" or "member". None for an agent, the
platform, or a person no Switch user has claimed.
Read fresh for every message, so an agent can rely on it over what it
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 7b0968a23..70d73ad4d 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -1156,23 +1156,6 @@ async def get_tenant_is_admin(
return is_admin
-async def get_tenant_is_owner(
- session: Annotated[AsyncSession, Depends(get_session)],
- user: Annotated[User, Depends(get_current_user)],
- user_store: Annotated[UserStore, Depends(get_user_store)],
-) -> bool:
- """Whether `user` may decide who owns the tenant this request is bound to.
-
- Strictly narrower than ``get_tenant_is_admin`` — see
- ``authz.owns_tenant``. A route that changes the ownership set needs both:
- ``require_tenant_admin`` to get in, this to make the call. Ends its read's
- transaction for the same reason ``get_tenant_is_admin`` does.
- """
- is_owner = await user_store.owns(session, user)
- await session.commit()
- return is_owner
-
-
async def require_tenant_admin(
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
@@ -1210,7 +1193,7 @@ async def require_room_access(
a different admin bit than the one its own dependencies resolved.
This is the widest of the tenant-admin gates: `authz.can` short-circuits
- on the admin bit, so a workspace owner or admin passes it for every room
+ on the admin bit, so a workspace admin passes it for every room
in their workspace, private ones included. See the phase 2 design note on
what that grant covers.
"""
diff --git a/core/switch_core/gateway/organizations.py b/core/switch_core/gateway/organizations.py
index 5597795dd..8d797f5ac 100644
--- a/core/switch_core/gateway/organizations.py
+++ b/core/switch_core/gateway/organizations.py
@@ -219,7 +219,7 @@ async def create_organization(
config: Annotated[SwitchConfig, Depends(get_config)],
) -> OrganizationCreateResponse:
"""Create an organization with its first workspace. The caller becomes the
- organization's `org_admin` and the workspace's `owner`, and their session
+ organization's `org_admin` and the workspace's `admin`, and their session
switches into the workspace.
Anyone signed in may, as `workspace_creation_refusal` decides: sign-up
@@ -308,7 +308,7 @@ async def create_organization_workspace(
user: Annotated[User, Depends(get_current_user)],
) -> TenantMembershipResponse:
"""Add a workspace to the organization. `org_admin` only; the creator
- becomes its `owner`. The session stays where it is: an `org_admin` adds
+ becomes its `admin`. The session stays where it is: an `org_admin` adds
workspaces for others as often as for themselves.
Counts against the creator's allowance as every workspace does, and is
@@ -345,7 +345,7 @@ async def create_organization_workspace(
id=tenant.id,
slug=tenant.slug,
name=tenant.name,
- role="owner",
+ role="admin",
organization_role=ORGANIZATION_ADMIN_ROLE,
organization_id=organization_id,
)
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 6be06c306..60f338e1d 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -1046,8 +1046,8 @@ class OperatorWorkspaceResponse(BaseModel):
class CurrentTenantResponse(TenantMembershipResponse):
"""The tenant this request is bound to. `administers` is whether the
- caller may manage it — an `owner` or `admin` membership, or the operator
- bit, which no membership role shows."""
+ caller may manage it — an `admin` membership, `org_admin` of its
+ organization, or the operator bit, which no membership role shows."""
administers: bool
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.py
index 6612b689a..e46529dee 100644
--- a/core/switch_core/gateway/tenants.py
+++ b/core/switch_core/gateway/tenants.py
@@ -62,7 +62,6 @@ from switch_core.gateway.auth import (
get_authenticated_caller,
get_authenticated_user_id,
get_current_user,
- get_tenant_is_owner,
list_tenant_memberships,
may_bind_tenant,
record_operator_entry,
@@ -140,7 +139,18 @@ logger = logging.getLogger(__name__)
router = APIRouter()
-TENANT_MEMBER_ROLES = ("owner", "admin", "member")
+TENANT_MEMBER_ROLES = ("admin", "member")
+
+
+def _member_role(role: str) -> str:
+ """`role` as this server stores it. `owner` was a role of its own until it
+ merged into `admin`; a client from before the merge may still ask for it,
+ and gets the role that now carries everything it did."""
+ if role == "owner":
+ return "admin"
+ if role not in TENANT_MEMBER_ROLES:
+ raise HTTPException(status_code=400, detail=f"Invalid role: {role}")
+ return role
def _require_bound_tenant(tenant_id: str) -> None:
@@ -213,23 +223,6 @@ async def _refuse_organization_admin(
)
-def _require_owner(is_owner: bool, action: str) -> None:
- """Raise 403 unless the caller owns the bound tenant.
-
- The three actions this guards — granting `owner`, changing an owner's
- role, removing an owner — are the ones that move a workspace's ownership
- set, and none of them is reachable by a last-owner guard: an admin who
- promotes themselves first leaves two owners standing at every subsequent
- step, so each individual request looks safe while the sequence takes the
- workspace. `require_tenant_admin` still gates getting this far; this is
- the narrower bit on top (`authz.owns_tenant`).
- """
- if not is_owner:
- raise HTTPException(
- status_code=403, detail=f"Only a workspace owner may {action}"
- )
-
-
def _require_invitation_usable(invitation: Invitation, caller_email: str) -> None:
"""Raise 403 unless `invitation` may still be accepted by `caller_email`.
@@ -442,15 +435,10 @@ async def create_invitation(
session: Annotated[AsyncSession, Depends(get_session)],
invitation_store: Annotated[InvitationStore, Depends(get_invitation_store)],
user: Annotated[User, Depends(require_tenant_admin)],
- is_owner: Annotated[bool, Depends(get_tenant_is_owner)],
config: Annotated[SwitchConfig, Depends(get_config)],
mailer: Annotated[InviteMailer | None, Depends(get_invite_mailer)],
) -> InvitationCreateResponse:
- """Mint an invitation to the bound tenant. `owner`/`admin` only.
-
- An `owner` invitation is owner-only: minting one is granting ownership
- with a step of indirection, so it answers to the same gate the direct
- grant does (`_require_owner`).
+ """Mint an invitation to the bound tenant. Admins only.
An invitation naming an e-mail is also sent there when a relay is
configured. The e-mail is a convenience on top of the link, not a
@@ -458,10 +446,7 @@ async def create_invitation(
stands, and `email_delivery` tells the admin to share the link instead.
"""
_require_bound_tenant(tenant_id)
- if req.role not in TENANT_MEMBER_ROLES:
- raise HTTPException(status_code=400, detail=f"Invalid role: {req.role}")
- if req.role == "owner":
- _require_owner(is_owner, "invite another owner")
+ role = _member_role(req.role)
if req.email is not None and mailer is not None and user.role != "admin":
sent_today = await invitation_store.count_addressed_since(
session, datetime.now(UTC) - timedelta(days=1)
@@ -481,7 +466,7 @@ async def create_invitation(
expires_at = datetime.now(UTC) + timedelta(hours=req.expires_in_hours)
invitation, token = await invitation_store.create(
session,
- role=req.role,
+ role=role,
email=req.email,
expires_at=expires_at,
uses_remaining=req.uses_remaining,
@@ -570,7 +555,7 @@ async def get_usage(
) -> list[UsageTotalResponse]:
"""The bound tenant's usage per metric, consumer and model over `[since, until)`.
- `owner`/`admin` only. Usage is counted in whole UTC hours, so `since` is
+ Admins only. Usage is counted in whole UTC hours, so `since` is
widened to the start of its hour. Both bounds must carry a timezone: a
naive time would be read in the server's zone and quietly shift the window.
"""
@@ -631,7 +616,7 @@ async def list_budgets(
_user: Annotated[User, Depends(require_tenant_admin)],
) -> list[BudgetResponse]:
"""Every budget of the bound tenant with its spend in the current period.
- `owner`/`admin` only."""
+ Admins only."""
_require_bound_tenant(tenant_id)
standings = await budget_store.standings(
session, tenant_id=tenant_id, agent_id=None
@@ -648,7 +633,7 @@ async def create_budget(
agent_store: Annotated[AgentStore, Depends(get_agent_store)],
_user: Annotated[User, Depends(require_tenant_admin)],
) -> BudgetResponse:
- """Add a budget to the bound tenant. `owner`/`admin` only.
+ """Add a budget to the bound tenant. Admins only.
404 when `agent_id` names no agent in this workspace; 409 when the same
agent (or the whole workspace), metric and model already has one — edit
@@ -687,7 +672,7 @@ async def update_budget(
budget_store: Annotated[BudgetStore, Depends(get_budget_store)],
_user: Annotated[User, Depends(require_tenant_admin)],
) -> BudgetResponse:
- """Change a budget's limit and period. `owner`/`admin` only. What it
+ """Change a budget's limit and period. Admins only. What it
covers is fixed; to cover something else, add another budget."""
_require_bound_tenant(tenant_id)
try:
@@ -712,7 +697,7 @@ async def delete_budget(
budget_store: Annotated[BudgetStore, Depends(get_budget_store)],
_user: Annotated[User, Depends(require_tenant_admin)],
) -> Response:
- """Remove a budget. `owner`/`admin` only."""
+ """Remove a budget. Admins only."""
_require_bound_tenant(tenant_id)
try:
await budget_store.delete(session, tenant_id=tenant_id, budget_id=budget_id)
@@ -729,7 +714,7 @@ async def list_invitations(
invitation_store: Annotated[InvitationStore, Depends(get_invitation_store)],
_user: Annotated[User, Depends(require_tenant_admin)],
) -> list[InvitationDetail]:
- """Every invitation of the bound tenant. `owner`/`admin` only."""
+ """Every invitation of the bound tenant. Admins only."""
_require_bound_tenant(tenant_id)
invitations = await invitation_store.list_for_tenant(session)
return [_invitation_detail(i) for i in invitations]
@@ -743,7 +728,7 @@ async def list_tenant_audit_events(
limit: Annotated[int, Query(ge=1, le=200)] = 50,
before: Annotated[datetime | None, Query()] = None,
) -> list[AuditEventDetail]:
- """The bound tenant's audit log, newest first. `owner`/`admin` only.
+ """The bound tenant's audit log, newest first. Admins only.
Page back by passing the oldest `occurred_at` returned as `before`.
"""
@@ -773,7 +758,7 @@ async def revoke_invitation(
invitation_store: Annotated[InvitationStore, Depends(get_invitation_store)],
user: Annotated[User, Depends(require_tenant_admin)],
) -> InvitationDetail:
- """Revoke an invitation of the bound tenant. `owner`/`admin` only."""
+ """Revoke an invitation of the bound tenant. Admins only."""
_require_bound_tenant(tenant_id)
try:
invitation = await invitation_store.revoke(session, invitation_id)
@@ -1105,7 +1090,7 @@ async def list_join_domains(
user: Annotated[User, Depends(require_tenant_admin)],
) -> JoinDomainsResponse:
"""The e-mail domains the bound tenant lets people join from, and whether
- the caller could add their own. `owner`/`admin` only."""
+ the caller could add their own. Admins only."""
_require_bound_tenant(tenant_id)
own_domain = email_domain(user.email)
rows = await join_domain_store.list_for_tenant(session, tenant_id)
@@ -1125,7 +1110,7 @@ async def add_join_domain(
user: Annotated[User, Depends(require_tenant_admin)],
) -> JoinDomainDetail:
"""Let anyone signed in with an address at a domain join the bound tenant
- as a member, without an invitation. `owner`/`admin` only.
+ as a member, without an invitation. Admins only.
Only the domain of the admin's own address. That is the proof the domain
is theirs to open: their account's address is either asserted verified by
@@ -1174,7 +1159,7 @@ async def remove_join_domain(
join_domain_store: Annotated[JoinDomainStore, Depends(get_join_domain_store)],
user: Annotated[User, Depends(require_tenant_admin)],
) -> None:
- """Stop letting people at a domain join the bound tenant. `owner`/`admin`
+ """Stop letting people at a domain join the bound tenant. Admins
only, and any domain: closing a workspace needs no proof of anything.
Members who already joined stay members."""
_require_bound_tenant(tenant_id)
@@ -1343,37 +1328,25 @@ async def update_member_role(
session: Annotated[AsyncSession, Depends(get_session)],
user_store: Annotated[UserStore, Depends(get_user_store)],
admin: Annotated[User, Depends(require_tenant_admin)],
- is_owner: Annotated[bool, Depends(get_tenant_is_owner)],
) -> MemberDetail:
- """Change a member's role. `owner`/`admin` only.
-
- Both ends of the ownership set are owner-only: an admin may promote a
- member to admin, but not to `owner`, and may not touch an existing
- owner's role at all. See `_require_owner` for what an admin who could do
- either would be able to do in three requests.
+ """Change a member's role. Admins only.
- Refuses to demote the last `owner` on top of that: with no workspace
- deletion in this phase, there is no legitimate route to a workspace with
- none.
+ Refuses to demote the last admin: a workspace with none has nobody who
+ can manage it, and getting one back takes the server's operator.
"""
_require_bound_tenant(tenant_id)
- if req.role not in TENANT_MEMBER_ROLES:
- raise HTTPException(status_code=400, detail=f"Invalid role: {req.role}")
+ role = _member_role(req.role)
membership = await session.get(TenantMember, (tenant_id, user_id))
if membership is None:
raise HTTPException(status_code=404, detail="Not a member of this tenant")
await _refuse_organization_admin(session, user_store, tenant_id, user_id)
- if req.role == "owner" and membership.role != "owner":
- _require_owner(is_owner, "grant ownership")
-
- if membership.role == "owner" and req.role != "owner":
- _require_owner(is_owner, "change an owner's role")
- if await user_store.count_owners(session) <= 1:
- raise HTTPException(status_code=409, detail="Cannot demote the last owner")
+ if membership.role == "admin" and role != "admin":
+ if await user_store.lock_admins(session) <= 1:
+ raise HTTPException(status_code=409, detail="Cannot demote the last admin")
- if membership.role != req.role:
+ if membership.role != role:
await record_audit_event(
session,
tenant_id=tenant_id,
@@ -1381,9 +1354,9 @@ async def update_member_role(
action=AuditAction.MEMBER_ROLE_CHANGED,
target_type="user",
target_id=user_id,
- details={"from": membership.role, "to": req.role},
+ details={"from": membership.role, "to": role},
)
- membership.role = req.role
+ membership.role = role
await session.commit()
user = await user_store.get(session, user_id)
@@ -1406,14 +1379,12 @@ async def remove_member(
api_key_store: Annotated[ApiKeyStore, Depends(get_api_key_store)],
protocol: Annotated[AgentCore, Depends(get_protocol)],
admin: Annotated[User, Depends(require_tenant_admin)],
- is_owner: Annotated[bool, Depends(get_tenant_is_owner)],
config: Annotated[SwitchConfig, Depends(get_config)],
broker: Annotated[ServiceBroker, Depends(get_service_broker)],
) -> dict | JSONResponse:
- """Remove a member from the bound tenant. `owner`/`admin` only.
+ """Remove a member from the bound tenant. Admins only.
- Removing an *owner* is owner-only, the same as demoting one and for the
- same reason (`_require_owner`), and refuses on the last owner besides.
+ Refuses to remove the last admin, as demoting one does.
Removal also revokes what the member's own credentials in this tenant let
them do here, in the same transaction as the membership row going away —
@@ -1444,10 +1415,9 @@ async def remove_member(
raise HTTPException(status_code=404, detail="Not a member of this tenant")
await _refuse_organization_admin(session, user_store, tenant_id, user_id)
- if membership.role == "owner":
- _require_owner(is_owner, "remove an owner")
- if await user_store.count_owners(session) <= 1:
- raise HTTPException(status_code=409, detail="Cannot remove the last owner")
+ if membership.role == "admin":
+ if await user_store.lock_admins(session) <= 1:
+ raise HTTPException(status_code=409, detail="Cannot remove the last admin")
owned_agents = await agent_store.get_by_owner(session, user_id)
if owned_agents:
diff --git a/core/switch_core/gateway/workspace_creation.py b/core/switch_core/gateway/workspace_creation.py
index ee689f728..a69443c28 100644
--- a/core/switch_core/gateway/workspace_creation.py
+++ b/core/switch_core/gateway/workspace_creation.py
@@ -143,16 +143,16 @@ async def lock_workspace_allowance(
`GET /auth/session` reports the same answer this enforces.
The bound is on workspaces created (`users.workspaces_created`), not on
- workspaces owned: ownership can be handed to another account, so a count of
- ownership could be reset by creating, handing over and stepping down, over
- and over. An invitation into someone else's workspace spends nothing.
+ workspaces administered: a workspace can be handed to another admin, so a
+ count of those could be reset by creating, handing over and stepping down,
+ over and over. An invitation into someone else's workspace spends nothing.
The row lock is what makes the check hold under concurrent requests. It
is taken `NOWAIT`, so a second request from the same person is refused
with 409 at once rather than holding a pool connection while it waits —
the request holding the lock needs more connections to provision, and a
burst of waiters could starve it of them. `FOR NO KEY UPDATE` rather than
- `FOR UPDATE`, because the new owner membership's foreign key takes a key
+ `FOR UPDATE`, because the new admin membership's foreign key takes a key
share on this same row from another session, and `FOR UPDATE` would make
the request wait on itself.
"""
@@ -254,7 +254,7 @@ async def create_organization_for(
id=tenant.id,
slug=tenant.slug,
name=tenant.name,
- role="owner",
+ role="admin",
organization_role=ORGANIZATION_ADMIN_ROLE,
organization_id=organization.id,
),
@@ -273,7 +273,7 @@ async def create_organization(
) -> tuple[Organization, Tenant]:
"""Create an organization named `name` and its first workspace, named
`workspace_name`. `creator` becomes the organization's `org_admin` and
- the workspace's `owner`, a member there in their own right.
+ the workspace's `admin`, a member there in their own right.
The directory records it first (`organization_directory.py`), since the
row keeps what the directory knows it by; a `DirectoryError` there leaves
@@ -386,7 +386,7 @@ async def create_workspace(
name: str,
) -> Tenant:
"""Create a workspace named `name` in `organization_id`, with `creator_id`,
- its `org_admin`, as its `owner`.
+ its `org_admin`, as its `admin`.
The creator administers it through the organization already; the
membership row makes them a member there in their own right, as creating
@@ -431,7 +431,7 @@ async def _add_creator(
organization_role: str,
new_organization: Organization | None,
) -> None:
- """Make `creator_id` the new workspace's `owner` and record its creation:
+ """Make `creator_id` the new workspace's `admin` and record its creation:
in the workspace's audit log, and in its organization's, with the
organization's own creation first when `new_organization` was made for it.
@@ -447,7 +447,7 @@ async def _add_creator(
session,
tenant_id=tenant.id,
user_id=creator_id,
- role="owner",
+ role="admin",
organization_role=organization_role,
)
await record_audit_event(
@@ -489,7 +489,7 @@ async def _add_creator(
await session.commit()
except Exception:
logger.error(
- "Workspace %s (slug %s) was created but its owner membership for "
+ "Workspace %s (slug %s) was created but its admin membership for "
"user %s was not written: it now has no members and its slug is "
"taken. Insert the membership to repair it.",
tenant.id,
diff --git a/core/switch_core/migrations/versions/a3c5e7f9b1d2_merge_owner_into_admin.py b/core/switch_core/migrations/versions/a3c5e7f9b1d2_merge_owner_into_admin.py
new file mode 100644
index 000000000..eb1609b41
--- /dev/null
+++ b/core/switch_core/migrations/versions/a3c5e7f9b1d2_merge_owner_into_admin.py
@@ -0,0 +1,46 @@
+"""merge the workspace owner role into admin
+
+A workspace had two roles that ran it, `owner` and `admin`, alike in
+everything but who could grant or remove ownership. They become one: every
+`owner` membership and invitation is now `admin`, and the role checks accept
+only `admin` and `member`. A workspace keeps at least one admin, as it kept
+at least one owner.
+
+Not expand only: a release from before this revision writes `owner` when a
+workspace is created, which the narrowed check refuses.
+
+Downgrading restores the checks that allow `owner`, but cannot tell which
+admins were owners, so every admin stays an admin.
+
+Revision ID: a3c5e7f9b1d2
+Revises: c3d9a1f7b246
+Create Date: 2026-10-27 09:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+from alembic import op
+
+revision: str = "a3c5e7f9b1d2"
+down_revision: str | None = "c3d9a1f7b246"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+_CHECKS = (
+ ("tenant_members", "ck_tenant_members_role"),
+ ("invitations", "ck_invitations_role"),
+)
+
+
+def upgrade() -> None:
+ for table, check in _CHECKS:
+ op.drop_constraint(check, table, type_="check")
+ op.execute(f"UPDATE {table} SET role = 'admin' WHERE role = 'owner'")
+ op.create_check_constraint(check, table, "role IN ('admin', 'member')")
+
+
+def downgrade() -> None:
+ for table, check in _CHECKS:
+ op.drop_constraint(check, table, type_="check")
+ op.create_check_constraint(check, table, "role IN ('owner', 'admin', 'member')")
diff --git a/core/switch_core/official_templates/switch-buddy/AGENT.md b/core/switch_core/official_templates/switch-buddy/AGENT.md
index 960a02691..1199210bf 100644
--- a/core/switch_core/official_templates/switch-buddy/AGENT.md
+++ b/core/switch_core/official_templates/switch-buddy/AGENT.md
@@ -62,7 +62,7 @@ take long enough that silence reads as a broken agent.
Before you help someone set something up, or explain why their setup behaves the
way it does, call `get_my_context`. It tells you:
-- who they are and whether they are an owner or admin of this workspace;
+- who they are and whether they are an admin of this workspace;
- whether this server is Switch Cloud, one Switch Console runs for them, or
self-hosted;
- which messaging apps are connected, how each platform would be added here,
@@ -76,11 +76,10 @@ offer. Never close a summary with "want me to…".
**Their role is in every message.** The line that hands you a message names it:
"olivia (workspace member) addressed you…". Switch reads it as the message
arrives, so trust it over anything earlier, your context included: roles change
-between messages, and walking a plain member through an owner's task wastes
+between messages, and walking a plain member through an admin's task wastes
their time. For what changes less often (connections, agents, the kind of
-server), call `get_my_context` again at the start of each setup request. Use their actual role:
-"owner" when `workspace_role` is owner, not "admin". Don't recite it back:
-use it to give the one next step that fits.
+server), call `get_my_context` again at the start of each setup request. Don't
+recite their role back: use it to give the one next step that fits.
## What you can do yourself
@@ -261,8 +260,8 @@ in Switch Console: link the page ("Link your account here: …"), never "want me
to link it?". End with the answer: no closing
offer, no menu of things you could do. They will ask.
-**Only owners and admins** connect messaging apps and invite people. If
-`person.workspace_admin` is false, say so and suggest they ask an owner of the
+**Only workspace admins** connect messaging apps and invite people. If
+`person.workspace_admin` is false, say so and suggest they ask an admin of the
workspace. Offer to draft the message.
**A messaging app (Slack, Discord, Teams, Telegram)** — look the platform up in
diff --git a/core/switch_core/organization_issues.py b/core/switch_core/organization_issues.py
index 6f62418f4..be0c120a0 100644
--- a/core/switch_core/organization_issues.py
+++ b/core/switch_core/organization_issues.py
@@ -8,7 +8,7 @@ once someone fixes it rather than once someone dismisses it:
- `no_org_admin`: nobody administers the organization (only the platform
operator, who may make someone its admin, can then read this).
-- `workspace_without_owner`: a workspace with no `owner`.
+- `workspace_without_admin`: a workspace with no `admin`.
- `agents_without_acting_owner`: agents whose owner is neither a member of
their workspace, nor the organization's `org_admin`, nor the platform
operator, so nobody can act for them as their owner.
@@ -95,12 +95,12 @@ async def workspace_issues(
workspace = await tenant_db.get(Tenant, tenant_id)
if workspace is None or workspace.organization_id != organization_id:
continue
- without_owner = await user_store.count_owners(tenant_db) == 0
+ without_admin = await user_store.count_admins(tenant_db) == 0
stranded = await _stranded_agents(tenant_db, tenant_id, admins)
- if without_owner:
+ if without_admin:
found.append(
OrganizationIssue(
- OrganizationIssueKind.WORKSPACE_WITHOUT_OWNER,
+ OrganizationIssueKind.WORKSPACE_WITHOUT_ADMIN,
tenant_id,
workspace.name,
[],
diff --git a/core/switch_core/organization_mirror.py b/core/switch_core/organization_mirror.py
index 4ded90840..2cee5878c 100644
--- a/core/switch_core/organization_mirror.py
+++ b/core/switch_core/organization_mirror.py
@@ -190,8 +190,8 @@ async def apply_from_directory(
session, dependencies, organization_id, user_id, tenant, details
)
if (
- membership.role == "owner"
- and await dependencies.user_store.count_owners(session) <= 1
+ membership.role == "admin"
+ and await dependencies.user_store.lock_admins(session) <= 1
):
await _conflict(
session,
@@ -199,7 +199,7 @@ async def apply_from_directory(
user_id,
{
**details,
- "kind": "workspace_left_without_owner",
+ "kind": "workspace_left_without_admin",
"workspace": tenant.name,
},
)
diff --git a/core/tests/switch_core/accounts/test_account_deletion.py b/core/tests/switch_core/accounts/test_account_deletion.py
index 8e693c761..0bf79ee7e 100644
--- a/core/tests/switch_core/accounts/test_account_deletion.py
+++ b/core/tests/switch_core/accounts/test_account_deletion.py
@@ -247,20 +247,55 @@ async def test_the_servers_admin_account_is_refused(
assert "administrator" in (await deletion.refusal(session, admin, []) or "")
-async def test_the_only_owner_of_a_shared_workspace_is_refused(
+async def test_the_only_admin_of_a_shared_workspace_is_refused(
session_factory: async_sessionmaker[AsyncSession],
) -> None:
deletion, _, _ = _deletion(session_factory)
async with session_factory() as session:
- owner = await _user(session, "owner")
+ admin = await _user(session, "admin")
other = await _user(session, "other")
- await _member(session, TENANT_ZERO_ID, owner, "owner")
+ await _member(session, TENANT_ZERO_ID, admin, "admin")
await _member(session, TENANT_ZERO_ID, other, "member")
await session.commit()
reason = await deletion.refusal(
- session, owner, [Workspace(TENANT_ZERO_ID, "Acme", "owner")]
+ session, admin, [Workspace(TENANT_ZERO_ID, "Acme", "admin")]
+ )
+ assert reason is not None and "only admin of Acme" in reason
+
+
+async def test_an_org_admin_with_a_member_row_takes_no_admin_away(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ """The workspace lists its organization's `org_admin` as an admin, but
+ their own row is a member's: deleting them leaves the workspace's one
+ admin row where it was, so the last-admin rule has nothing to stop."""
+ deletion, _, _ = _deletion(session_factory)
+ async with session_factory() as session:
+ org_admin = await _user(session, "org-admin")
+ second = await _user(session, "second-org-admin")
+ workspace_admin = await _user(session, "ws-admin")
+ await _member(session, TENANT_ZERO_ID, org_admin, "member")
+ await _member(session, TENANT_ZERO_ID, workspace_admin, "admin")
+ await _organization_role(session, org_admin, "org_admin")
+ await _organization_role(session, second, "org_admin")
+ await session.commit()
+ user_id = org_admin.id
+
+ workspaces = [Workspace(TENANT_ZERO_ID, "Acme", "admin")]
+ async with session_factory() as session:
+ user = await session.get(User, user_id)
+ assert user is not None
+ assert await deletion.refusal(session, user, workspaces) is None
+ await deletion.delete(session, user, workspaces)
+
+ async with session_factory() as session:
+ assert await session.get(User, user_id) is None
+ admins = await session.scalars(
+ select(TenantMember.user_id).where(
+ TenantMember.tenant_id == TENANT_ZERO_ID, TenantMember.role == "admin"
+ )
)
- assert reason is not None and "only owner of Acme" in reason
+ assert list(admins) == [workspace_admin.id]
async def _organization_role(session: AsyncSession, user: User, role: str) -> None:
@@ -279,12 +314,12 @@ async def test_the_only_org_admin_of_an_organization_with_others_is_refused(
admin = await _user(session, "org-admin")
other = await _user(session, "other")
await _member(session, TENANT_ZERO_ID, admin, "admin")
- await _member(session, TENANT_ZERO_ID, other, "owner")
+ await _member(session, TENANT_ZERO_ID, other, "admin")
await _organization_role(session, admin, "org_admin")
await _organization_role(session, other, "member")
await session.commit()
reason = await deletion.refusal(
- session, admin, [Workspace(TENANT_ZERO_ID, "Acme", "owner")]
+ session, admin, [Workspace(TENANT_ZERO_ID, "Acme", "admin")]
)
assert reason is not None and "only organization admin" in reason
@@ -298,7 +333,7 @@ async def test_an_org_admin_of_another_organization_does_not_count(
other = await _user(session, "other")
elsewhere = await _user(session, "elsewhere")
await _member(session, TENANT_ZERO_ID, admin, "admin")
- await _member(session, TENANT_ZERO_ID, other, "owner")
+ await _member(session, TENANT_ZERO_ID, other, "admin")
await _organization_role(session, admin, "org_admin")
await _organization_role(session, other, "member")
session.add(Organization(id="org-elsewhere", slug="org-elsewhere", name="Else"))
@@ -310,7 +345,7 @@ async def test_an_org_admin_of_another_organization_does_not_count(
)
await session.commit()
reason = await deletion.refusal(
- session, admin, [Workspace(TENANT_ZERO_ID, "Acme", "owner")]
+ session, admin, [Workspace(TENANT_ZERO_ID, "Acme", "admin")]
)
assert reason is not None and "only organization admin" in reason
@@ -323,12 +358,12 @@ async def test_an_org_admin_with_another_org_admin_beside_them_is_not_refused(
admin = await _user(session, "org-admin")
other = await _user(session, "other")
await _member(session, TENANT_ZERO_ID, admin, "admin")
- await _member(session, TENANT_ZERO_ID, other, "owner")
+ await _member(session, TENANT_ZERO_ID, other, "admin")
await _organization_role(session, admin, "org_admin")
await _organization_role(session, other, "org_admin")
await session.commit()
reason = await deletion.refusal(
- session, admin, [Workspace(TENANT_ZERO_ID, "Acme", "owner")]
+ session, admin, [Workspace(TENANT_ZERO_ID, "Acme", "admin")]
)
assert reason is None
@@ -339,7 +374,7 @@ async def test_a_connected_workspace_nobody_else_is_in_is_refused(
deletion, _, _ = _deletion(session_factory)
async with session_factory() as session:
alone = await _user(session, "alone")
- await _member(session, TENANT_ZERO_ID, alone, "owner")
+ await _member(session, TENANT_ZERO_ID, alone, "admin")
session.add(
MessagingInstall(
tenant_id=TENANT_ZERO_ID,
@@ -352,7 +387,7 @@ async def test_a_connected_workspace_nobody_else_is_in_is_refused(
)
await session.commit()
reason = await deletion.refusal(
- session, alone, [Workspace(TENANT_ZERO_ID, "Solo", "owner")]
+ session, alone, [Workspace(TENANT_ZERO_ID, "Solo", "admin")]
)
assert reason is not None and "Slack" in reason
@@ -362,9 +397,9 @@ async def test_deleting_a_member_hands_over_and_clears_what_others_need(
) -> None:
deletion, protocol, rooms = _deletion(session_factory)
async with session_factory() as session:
- owner = await _user(session, "owner")
+ admin = await _user(session, "admin")
leaving = await _user(session, "leaving")
- await _member(session, TENANT_ZERO_ID, owner, "owner")
+ await _member(session, TENANT_ZERO_ID, admin, "admin")
await _member(session, TENANT_ZERO_ID, leaving, "member")
agent = await _agent(session, TENANT_ZERO_ID, leaving, "helper")
invitation = await _invitation(session, TENANT_ZERO_ID, leaving)
@@ -424,7 +459,7 @@ async def test_deleting_a_member_hands_over_and_clears_what_others_need(
await session.commit()
ids = {
"user": leaving.id,
- "owner": owner.id,
+ "admin": admin.id,
"agent": agent.id,
"invitation": invitation.id,
"shared_room": shared_room.id,
@@ -448,14 +483,14 @@ async def test_deleting_a_member_hands_over_and_clears_what_others_need(
await session.scalar(
select(Invitation.created_by).where(Invitation.id == ids["invitation"])
)
- ) == ids["owner"]
+ ) == ids["admin"]
assert (
await session.scalar(
select(WorkspaceServiceSetting.updated_by).where(
WorkspaceServiceSetting.service == "github"
)
)
- ) == ids["owner"]
+ ) == ids["admin"]
room = await session.scalar(select(Room).where(Room.id == ids["shared_room"]))
assert room is not None and room.owner_id is None and room.created_by is None
assert (
@@ -499,11 +534,11 @@ async def test_a_workspace_left_empty_stays_with_nothing_pointing_at_the_person(
user_id = alone.id
await session.commit()
async with tenant_session(session_factory, solo) as session:
- await _member(session, solo, alone, "owner")
+ await _member(session, solo, alone, "admin")
await _invitation(session, solo, alone)
await session.commit()
- workspaces = [Workspace(solo, "Solo", "owner")]
+ workspaces = [Workspace(solo, "Solo", "admin")]
async with session_factory() as session:
user = await session.get(User, user_id)
assert user is not None
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py b/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py
index a370a5503..2784393e9 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py
@@ -3,19 +3,19 @@
``_resolve_acting_identity`` used to compute ``owner_is_admin`` from
``owner.role == "admin"`` alone — the same global bit every other admin check
-in the codebase used before this split. Once a person can hold ``owner`` in
+in the codebase used before this split. Once a person can hold ``admin`` in
one tenant and merely ``member`` (or nothing) in another, that global read is
wrong for an agent the same way it was wrong for a human acting directly: an
agent must not administer a tenant its owner does not administer, and must
administer one its owner does, purely because of the owner's role in *that*
tenant rather than any global bit.
-``test_agent_administers_the_tenant_its_owner_owns`` is the one that actually
+``test_agent_administers_the_tenant_its_owner_administers`` is the one that actually
distinguishes old from new: the owner here holds no global admin bit at all,
so the pre-split code (`owner.role == "admin"`) denies it regardless of the
`tenant_members` row, and only reading that row grants it. The other two
tests hold under both the old and new code — they pin down that the fix does
-not *overreach* (a workspace owner's agent must not gain cross-tenant power,
+not *overreach* (a workspace admin's agent must not gain cross-tenant power,
and a global operator's agent must not lose its bypass) rather than proving a
new grant.
"""
@@ -159,16 +159,16 @@ async def _private_room(
class TestAgentInheritsOwnerTenantScopedAdmin:
- async def test_agent_administers_the_tenant_its_owner_owns(
+ async def test_agent_administers_the_tenant_its_owner_administers(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- """The owner holds no global admin bit — only `owner` in the bound
+ """The owner holds no global admin bit — only `admin` in the bound
tenant. Only reading `tenant_members` (not `users.role`) can grant
this, so this is the one test that fails against the pre-split code.
"""
svc = _service(session_factory)
- owner = await _make_user(session_factory, "workspace-owner")
- await _membership(session_factory, TENANT_ZERO_ID, owner, "owner")
+ owner = await _make_user(session_factory, "workspace-admin")
+ await _membership(session_factory, TENANT_ZERO_ID, owner, "admin")
someone_else = await _make_user(session_factory, "tenant-zero-room-owner")
agent_id = await _register(svc, "owner-agent", owner)
room_id = await _private_room(session_factory, TENANT_ZERO_ID, someone_else)
@@ -180,12 +180,12 @@ class TestAgentInheritsOwnerTenantScopedAdmin:
async def test_agent_cannot_administer_a_tenant_where_owner_is_only_a_member(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- """Same owner, same agent: `owner` in tenant zero grants nothing in
+ """Same owner, same agent: `admin` in tenant zero grants nothing in
tenant B, where that owner only holds `member`."""
svc = _service(session_factory)
await _make_tenant(session_factory, TENANT_B)
owner = await _make_user(session_factory, "cross-tenant-owner")
- await _membership(session_factory, TENANT_ZERO_ID, owner, "owner")
+ await _membership(session_factory, TENANT_ZERO_ID, owner, "admin")
await _membership(session_factory, TENANT_B, owner, "member")
someone_else = await _make_user(session_factory, "tenant-b-room-owner")
agent_id = await _register(svc, "cross-tenant-agent", owner)
diff --git a/core/tests/switch_core/db/stores/test_service_connection_store.py b/core/tests/switch_core/db/stores/test_service_connection_store.py
index 3a899475e..7239ab6f8 100644
--- a/core/tests/switch_core/db/stores/test_service_connection_store.py
+++ b/core/tests/switch_core/db/stores/test_service_connection_store.py
@@ -335,7 +335,7 @@ class TestTenantIsolation:
await session.flush()
session.add(
TenantMember(
- tenant_id=f"tenant-{suffix}", user_id=user.id, role="owner"
+ tenant_id=f"tenant-{suffix}", user_id=user.id, role="admin"
)
)
await session.commit()
diff --git a/core/tests/switch_core/db/test_require_tenant_id.py b/core/tests/switch_core/db/test_require_tenant_id.py
index 66a592665..92de8bb48 100644
--- a/core/tests/switch_core/db/test_require_tenant_id.py
+++ b/core/tests/switch_core/db/test_require_tenant_id.py
@@ -154,7 +154,7 @@ class TestMembershipNeedsOneToo:
)
assert list(memberships.scalars()) == [TENANT_ZERO_ID]
- async def test_an_admin_joins_as_owner(
+ async def test_an_operator_joins_as_admin(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
async with session_factory() as session:
@@ -165,4 +165,4 @@ class TestMembershipNeedsOneToo:
roles = await session.execute(
select(TenantMember.role).where(TenantMember.user_id == user.id)
)
- assert list(roles.scalars()) == ["owner"]
+ assert list(roles.scalars()) == ["admin"]
diff --git a/core/tests/switch_core/db/test_tenant_admin_role_split.py b/core/tests/switch_core/db/test_tenant_admin_role_split.py
index 3af5082c9..28756657e 100644
--- a/core/tests/switch_core/db/test_tenant_admin_role_split.py
+++ b/core/tests/switch_core/db/test_tenant_admin_role_split.py
@@ -2,13 +2,13 @@
Before this change, `authz.Principal.is_admin` came from `users.role ==
"admin"` alone — a global bit that `tenant_members.role` never fed into. So a
-workspace's `owner` membership row granted nothing: every admin-gated route
+workspace's `admin` membership row granted nothing: every admin-gated route
checked the global bit, never the caller's role in the tenant the request is
bound to.
These tests pin the behavioural claims that split makes true:
-- a workspace `owner` can administer resources in *their own* tenant;
+- a workspace `admin` can administer resources in *their own* tenant;
- the same person has no such power in a tenant they only hold a `member`
row in — `UserStore.administers` must read the *bound* tenant's row, not
any row belonging to the caller;
@@ -29,11 +29,14 @@ an actual resource decision is exercised end to end, not just the boolean.
from __future__ import annotations
+import asyncio
+
import pytest
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.authz import Principal, can
from switch_core.db.models import TENANT_ZERO_ID, Room, Tenant, TenantMember, User
+from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.user_store import UserStore
from switch_core.tenant_context import no_tenant, tenant_scope
@@ -64,19 +67,19 @@ async def _membership(
class TestUserStoreAdministers:
- async def test_owner_administers_their_own_tenant(
+ async def test_admin_administers_their_own_tenant(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
store = UserStore()
async with session_factory() as session:
- owner = await _make_user(session, "owner-of-zero")
- await _membership(session, TENANT_ZERO_ID, owner.id, "owner")
+ admin = await _make_user(session, "admin-of-zero")
+ await _membership(session, TENANT_ZERO_ID, admin.id, "admin")
await session.commit()
# Ambient tenant is TENANT_ZERO_ID (see conftest.session_factory).
- assert await store.administers(session, owner) is True
+ assert await store.administers(session, admin) is True
- async def test_owner_has_no_power_in_a_tenant_they_only_belong_to_as_member(
+ async def test_admin_has_no_power_in_a_tenant_they_only_belong_to_as_member(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
# Two sessions, one per tenant: `TenantCheckedSession` stamps a
@@ -88,16 +91,16 @@ class TestUserStoreAdministers:
store = UserStore()
async with session_factory() as session:
tenant_b = await _make_tenant(session, TENANT_B)
- owner = await _make_user(session, "cross-tenant-owner")
- await _membership(session, TENANT_ZERO_ID, owner.id, "owner")
- await _membership(session, tenant_b.id, owner.id, "member")
+ admin = await _make_user(session, "cross-tenant-admin")
+ await _membership(session, TENANT_ZERO_ID, admin.id, "admin")
+ await _membership(session, tenant_b.id, admin.id, "member")
await session.commit()
- assert await store.administers(session, owner) is True
+ assert await store.administers(session, admin) is True
with tenant_scope(tenant_b.id):
async with session_factory() as session_b:
- assert await store.administers(session_b, owner) is False
+ assert await store.administers(session_b, admin) is False
async def test_admin_membership_role_also_administers(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -156,17 +159,17 @@ class TestUserStoreAdministers:
# Answering here would mean answering a question that was not asked:
# "may this person administer" has no deployment-wide form. The
# tempting fallback — the operator bit alone — silently strips a
- # workspace owner of their role, and the 403 that follows names no
+ # workspace admin of their role, and the 403 that follows names no
# cause. Same call as the one #442 made for the bridge identities.
store = UserStore()
async with session_factory() as session:
- owner = await _make_user(session, "unbound-owner")
- await _membership(session, TENANT_ZERO_ID, owner.id, "owner")
+ admin = await _make_user(session, "unbound-admin")
+ await _membership(session, TENANT_ZERO_ID, admin.id, "admin")
await session.commit()
with no_tenant():
with pytest.raises(RuntimeError, match="requires a bound tenant"):
- await store.administers(session, owner)
+ await store.administers(session, admin)
async def test_unbound_is_refused_for_an_operator_too(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -190,14 +193,14 @@ class TestRoomAuthzThroughTenantRole:
`Room` neither party personally owns, built from `UserStore.administers`
the way `gateway/rooms.py` and `gateway/auth.py` build it."""
- async def test_workspace_owner_can_delete_a_room_they_do_not_personally_own(
+ async def test_workspace_admin_can_delete_a_room_they_do_not_personally_own(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
store = UserStore()
async with session_factory() as session:
- owner = await _make_user(session, "room-admin-owner")
+ admin = await _make_user(session, "room-admin")
someone_else = await _make_user(session, "room-creator")
- await _membership(session, TENANT_ZERO_ID, owner.id, "owner")
+ await _membership(session, TENANT_ZERO_ID, admin.id, "admin")
room = Room(
tenant_id=TENANT_ZERO_ID,
transport_room_id="!private-room:test",
@@ -210,19 +213,19 @@ class TestRoomAuthzThroughTenantRole:
session.add(room)
await session.commit()
- principal = Principal(owner.id, await store.administers(session, owner))
+ principal = Principal(admin.id, await store.administers(session, admin))
assert can(principal, "delete", room)
- async def test_workspace_owner_cannot_delete_the_same_room_from_another_tenant(
+ async def test_workspace_admin_cannot_delete_the_same_room_from_another_tenant(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
store = UserStore()
async with session_factory() as session:
tenant_b = await _make_tenant(session, TENANT_B)
- owner = await _make_user(session, "room-admin-owner-2")
+ admin = await _make_user(session, "room-admin-2")
someone_else = await _make_user(session, "room-creator-2")
- await _membership(session, TENANT_ZERO_ID, owner.id, "owner")
- await _membership(session, tenant_b.id, owner.id, "member")
+ await _membership(session, TENANT_ZERO_ID, admin.id, "admin")
+ await _membership(session, tenant_b.id, admin.id, "member")
room = Room(
tenant_id=TENANT_ZERO_ID,
transport_room_id="!private-room-2:test",
@@ -238,7 +241,7 @@ class TestRoomAuthzThroughTenantRole:
with tenant_scope(tenant_b.id):
async with session_factory() as session_b:
principal = Principal(
- owner.id, await store.administers(session_b, owner)
+ admin.id, await store.administers(session_b, admin)
)
assert not can(principal, "delete", room)
@@ -264,3 +267,37 @@ class TestRoomAuthzThroughTenantRole:
principal = Principal(member.id, await store.administers(session, member))
assert not can(principal, "delete", room)
+
+
+class TestLockAdmins:
+ """`lock_admins` is what keeps the last-admin guard true when two admins
+ act at once."""
+
+ async def test_a_second_count_waits_for_the_first_demotion(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ ada = await _make_user(session, "lock-ada")
+ bob = await _make_user(session, "lock-bob")
+ await _membership(session, TENANT_ZERO_ID, ada.id, "admin")
+ await _membership(session, TENANT_ZERO_ID, bob.id, "admin")
+ await session.commit()
+
+ store = UserStore()
+ async with tenant_session(session_factory, TENANT_ZERO_ID) as first:
+ assert await store.lock_admins(first) == 2
+ membership = await first.get(TenantMember, (TENANT_ZERO_ID, bob.id))
+ assert membership is not None
+ membership.role = "member"
+ await first.flush()
+
+ async def second_count() -> int:
+ async with tenant_session(session_factory, TENANT_ZERO_ID) as second:
+ return await store.lock_admins(second)
+
+ waiting = asyncio.create_task(second_count())
+ await asyncio.sleep(0.3)
+ assert not waiting.done()
+ await first.commit()
+
+ assert await asyncio.wait_for(waiting, 5) == 1
diff --git a/core/tests/switch_core/delivery/test_sender_role.py b/core/tests/switch_core/delivery/test_sender_role.py
index 7aa346307..35eedc9c4 100644
--- a/core/tests/switch_core/delivery/test_sender_role.py
+++ b/core/tests/switch_core/delivery/test_sender_role.py
@@ -48,7 +48,7 @@ async def test_a_person_is_named_by_their_role_now(
session_factory: async_sessionmaker[AsyncSession],
) -> None:
async with session_factory() as session:
- olivia = await _member(session, "olivia", "owner")
+ olivia = await _member(session, "olivia", "admin")
person = SenderPrincipal("user", "client-1", [olivia.id], None)
assert (
@@ -58,7 +58,7 @@ async def test_a_person_is_named_by_their_role_now(
"@olivia:test",
{},
)
- == "owner"
+ == "admin"
)
membership = await session.get(TenantMember, (TENANT_ZERO_ID, olivia.id))
diff --git a/core/tests/switch_core/gateway/conftest.py b/core/tests/switch_core/gateway/conftest.py
index a55863042..5349bf3cb 100644
--- a/core/tests/switch_core/gateway/conftest.py
+++ b/core/tests/switch_core/gateway/conftest.py
@@ -256,7 +256,7 @@ async def _user(session: AsyncSession, name: str, role: str | None) -> User:
tenant_id="00000000-0000-0000-0000-000000000000",
user_id=user.id,
role=role,
- organization_role="org_admin" if role in ("owner", "admin") else "member",
+ organization_role="org_admin" if role == "admin" else "member",
)
return user
diff --git a/core/tests/switch_core/gateway/test_api_keys_belong_to_their_owner.py b/core/tests/switch_core/gateway/test_api_keys_belong_to_their_owner.py
index 5f1a8280e..cd7a0eb80 100644
--- a/core/tests/switch_core/gateway/test_api_keys_belong_to_their_owner.py
+++ b/core/tests/switch_core/gateway/test_api_keys_belong_to_their_owner.py
@@ -1,5 +1,5 @@
"""Nobody but a key's owner may list, reveal or delete it through the key
-routes: not a workspace owner or admin, and not the deployment operator.
+routes: not a workspace admin, and not the deployment operator.
An admin's power over the workspace stops at the keys, because a key is a
credential the owner can reveal and an admin who could reveal it could act as
@@ -19,7 +19,7 @@ from tests.switch_core.gateway.test_api_keys_hash_only import TEST_KEYRING, _app
from tests.switch_core.management.harness import add_member, cookies_for
[email protected]("who", ["owner", "admin", "operator"])
[email protected]("who", ["admin", "operator"])
async def test_an_admin_cannot_list_reveal_or_delete_a_members_key(
session_factory: async_sessionmaker[AsyncSession], who: str
) -> None:
diff --git a/core/tests/switch_core/gateway/test_audit_events.py b/core/tests/switch_core/gateway/test_audit_events.py
index 57e4ef2d5..1677f0d7a 100644
--- a/core/tests/switch_core/gateway/test_audit_events.py
+++ b/core/tests/switch_core/gateway/test_audit_events.py
@@ -37,21 +37,21 @@ async def _events(
return list(result.scalars().all())
-async def _owner(
+async def _admin(
session_factory: async_sessionmaker[AsyncSession], tenant_id: str, name: str
) -> tuple[str, str]:
await _make_tenant(session_factory, tenant_id)
- owner_id = await _make_member(
- session_factory, name=name, tenant_id=tenant_id, role="owner"
+ admin_id = await _make_member(
+ session_factory, name=name, tenant_id=tenant_id, role="admin"
)
- return owner_id, _token(owner_id, f"{name}@example.invalid", tenant_id)
+ return admin_id, _token(admin_id, f"{name}@example.invalid", tenant_id)
class TestMembershipEvents:
async def test_a_role_change_is_recorded_with_both_roles(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- owner_id, token = await _owner(session_factory, TENANT_A, "audit-owner")
+ admin_id, token = await _admin(session_factory, TENANT_A, "audit-admin")
member_id = await _make_member(
session_factory, name="audit-member", tenant_id=TENANT_A, role="member"
)
@@ -64,7 +64,7 @@ class TestMembershipEvents:
[event] = await _events(session_factory, TENANT_A)
assert event.action == AuditAction.MEMBER_ROLE_CHANGED
- assert event.actor_user_id == owner_id
+ assert event.actor_user_id == admin_id
assert event.target_type == "user"
assert event.target_id == member_id
assert event.details == {"from": "member", "to": "admin"}
@@ -72,7 +72,7 @@ class TestMembershipEvents:
async def test_setting_the_same_role_records_nothing(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- _, token = await _owner(session_factory, TENANT_A, "audit-owner")
+ _, token = await _admin(session_factory, TENANT_A, "audit-admin")
member_id = await _make_member(
session_factory, name="audit-member", tenant_id=TENANT_A, role="member"
)
@@ -88,7 +88,7 @@ class TestMembershipEvents:
async def test_removing_a_member_is_recorded(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- owner_id, token = await _owner(session_factory, TENANT_A, "audit-owner")
+ admin_id, token = await _admin(session_factory, TENANT_A, "audit-admin")
member_id = await _make_member(
session_factory, name="audit-member", tenant_id=TENANT_A, role="member"
)
@@ -99,7 +99,7 @@ class TestMembershipEvents:
[event] = await _events(session_factory, TENANT_A)
assert event.action == AuditAction.MEMBER_REMOVED
- assert event.actor_user_id == owner_id
+ assert event.actor_user_id == admin_id
assert event.target_id == member_id
assert event.details is not None
assert event.details["role"] == "member"
@@ -107,11 +107,11 @@ class TestMembershipEvents:
async def test_a_refused_change_records_nothing(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- owner_id, token = await _owner(session_factory, TENANT_A, "sole-owner")
+ admin_id, token = await _admin(session_factory, TENANT_A, "sole-admin")
async with _client(_app(session_factory), token) as client:
response = await client.patch(
- f"/tenants/{TENANT_A}/members/{owner_id}", json={"role": "member"}
+ f"/tenants/{TENANT_A}/members/{admin_id}", json={"role": "member"}
)
assert response.status_code == 409
@@ -122,7 +122,7 @@ class TestInvitationEvents:
async def test_creating_and_revoking_an_invitation_are_both_recorded(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- owner_id, token = await _owner(session_factory, TENANT_A, "audit-owner")
+ admin_id, token = await _admin(session_factory, TENANT_A, "audit-admin")
async with _client(_app(session_factory), token) as client:
created = await client.post(
@@ -141,7 +141,7 @@ class TestInvitationEvents:
AuditAction.INVITATION_REVOKED,
]
assert {e.target_id for e in events} == {invitation_id}
- assert {e.actor_user_id for e in events} == {owner_id}
+ assert {e.actor_user_id for e in events} == {admin_id}
assert events[0].details is not None
assert events[0].details["role"] == "member"
@@ -153,7 +153,7 @@ class TestApiKeyEvents:
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(api_keys, "get_protocol", _fake_protocol)
- user_id, token = await _owner(session_factory, TENANT_A, "key-owner")
+ user_id, token = await _admin(session_factory, TENANT_A, "key-owner")
app = _app(session_factory)
app.include_router(api_keys.router, prefix="/api-keys")
@@ -183,7 +183,7 @@ class TestReadingTheLog:
async def test_admins_read_their_own_tenant_newest_first(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- owner_id, token = await _owner(session_factory, TENANT_A, "audit-owner")
+ admin_id, token = await _admin(session_factory, TENANT_A, "audit-admin")
await _make_tenant(session_factory, TENANT_B)
for tenant_id, action in (
(TENANT_A, AuditAction.JOIN_DOMAIN_ADDED),
@@ -194,7 +194,7 @@ class TestReadingTheLog:
await record_audit_event(
session,
tenant_id=tenant_id,
- actor_user_id=owner_id,
+ actor_user_id=admin_id,
action=action,
target_type="join_domain",
target_id="example.invalid",
diff --git a/core/tests/switch_core/gateway/test_claim_identity_membership.py b/core/tests/switch_core/gateway/test_claim_identity_membership.py
index 5fc2095be..fa40acb52 100644
--- a/core/tests/switch_core/gateway/test_claim_identity_membership.py
+++ b/core/tests/switch_core/gateway/test_claim_identity_membership.py
@@ -96,7 +96,7 @@ async def _setup(
session.add(external_user)
admin = await _make_user(session, tenant_id=TENANT_ZERO_ID, role="admin")
member = await _make_user(session, tenant_id=TENANT_ZERO_ID, role="member")
- outsider = await _make_user(session, tenant_id=other_tenant, role="owner")
+ outsider = await _make_user(session, tenant_id=other_tenant, role="admin")
await session.commit()
return bridge.id, external_user, admin, member, outsider
diff --git a/core/tests/switch_core/gateway/test_connector_apps.py b/core/tests/switch_core/gateway/test_connector_apps.py
index f430f3d6e..2507d1270 100644
--- a/core/tests/switch_core/gateway/test_connector_apps.py
+++ b/core/tests/switch_core/gateway/test_connector_apps.py
@@ -334,7 +334,7 @@ async def operator(session_factory) -> User:
class TestOnlyTheOperator:
- @pytest.mark.parametrize("member_role", ["member", "admin", "owner"])
+ @pytest.mark.parametrize("member_role", ["member", "admin"])
async def test_everyone_else_is_refused_on_every_route(
self, world: World, session_factory, member_role: str
) -> None:
diff --git a/core/tests/switch_core/gateway/test_create_user.py b/core/tests/switch_core/gateway/test_create_user.py
index 9c54f3873..242977d53 100644
--- a/core/tests/switch_core/gateway/test_create_user.py
+++ b/core/tests/switch_core/gateway/test_create_user.py
@@ -208,7 +208,7 @@ class TestCreateUserOverHttp:
assert await _emails_like(session_factory, "[email protected]") == []
@pytest.mark.parametrize(
- ("role", "membership_role"), [("user", "member"), ("admin", "owner")]
+ ("role", "membership_role"), [("user", "member"), ("admin", "admin")]
)
async def test_a_known_role_is_stored_with_its_membership(
self,
diff --git a/core/tests/switch_core/gateway/test_held_connections.py b/core/tests/switch_core/gateway/test_held_connections.py
index e7e2fa805..20bdead17 100644
--- a/core/tests/switch_core/gateway/test_held_connections.py
+++ b/core/tests/switch_core/gateway/test_held_connections.py
@@ -309,19 +309,19 @@ def _client(app: Any, user: User) -> httpx.AsyncClient:
async def _admin(session_factory: async_sessionmaker[AsyncSession]) -> User:
- """A workspace owner: a plain user whose admin bit comes from membership,
+ """A workspace admin: a plain user whose admin bit comes from membership,
so `get_tenant_is_admin` has to read it."""
async with session_factory() as session:
user = User(
- name="owner",
+ name="ws-admin",
role="user",
password_hash=hash_password(_PASSWORD),
)
session.add(user)
await session.flush()
session.add(
- TenantMember(tenant_id=TENANT_ZERO_ID, user_id=user.id, role="owner")
+ TenantMember(tenant_id=TENANT_ZERO_ID, user_id=user.id, role="admin")
)
await session.commit()
return user
diff --git a/core/tests/switch_core/gateway/test_messaging_installs_authz.py b/core/tests/switch_core/gateway/test_messaging_installs_authz.py
index 9147e28f8..b36e8b820 100644
--- a/core/tests/switch_core/gateway/test_messaging_installs_authz.py
+++ b/core/tests/switch_core/gateway/test_messaging_installs_authz.py
@@ -1,7 +1,7 @@
"""Installing a messaging app is workspace administration.
An install lands a bridge in one tenant and nowhere else, so the person who
-may do it is that workspace's owner or admin — not only the deployment
+may do it is that workspace's admin — not only the deployment
operator. On a server where people sign themselves up, the operator bit is
held by nobody who runs a workspace, so gating these routes on it would leave
the Slack button unreachable to exactly the people it is for.
@@ -94,11 +94,11 @@ async def _list_installs(
class TestWhoMayManageInstalls:
- async def test_a_workspace_owner_who_is_not_an_operator_may(
+ async def test_a_workspace_admin_who_is_not_an_operator_may(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- user_id = await _member(session_factory, name="owner", role="owner")
- response = await _list_installs(session_factory, user_id, "owner")
+ user_id = await _member(session_factory, name="ws-admin", role="admin")
+ response = await _list_installs(session_factory, user_id, "ws-admin")
assert response.status_code == 200, response.text
assert response.json() == {"installs": []}
diff --git a/core/tests/switch_core/gateway/test_organization_connector_apps.py b/core/tests/switch_core/gateway/test_organization_connector_apps.py
index 1428bcdfa..193d36223 100644
--- a/core/tests/switch_core/gateway/test_organization_connector_apps.py
+++ b/core/tests/switch_core/gateway/test_organization_connector_apps.py
@@ -132,12 +132,12 @@ class TestOnlyOrgAdmins:
self, world: World, session_factory
) -> None:
await _install(world)
- owner = await _user(session_factory, "owner", member_role="owner")
+ ws_admin = await _user(session_factory, "ws-admin", member_role="admin")
operator = await _user(session_factory, "operator", role="admin")
async with world.harness.client() as client:
answers = [
await call(cookies_for(someone))
- for someone in (owner, operator)
+ for someone in (ws_admin, operator)
for call in (
lambda cookies: client.get(ORGANIZATION_APPS, cookies=cookies),
lambda cookies: client.put(
diff --git a/core/tests/switch_core/gateway/test_organization_directory_routes.py b/core/tests/switch_core/gateway/test_organization_directory_routes.py
index 00da2e3f8..ea8d1a8af 100644
--- a/core/tests/switch_core/gateway/test_organization_directory_routes.py
+++ b/core/tests/switch_core/gateway/test_organization_directory_routes.py
@@ -260,7 +260,7 @@ class TestJoining:
self, session_factory, directory: _Directory
) -> None:
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
token = await _invitation(session_factory, tenant_id, ada)
bob = await _outsider(session_factory)
@@ -276,7 +276,7 @@ class TestJoining:
self, session_factory, unavailable: _Directory, directory: _Directory
) -> None:
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
token = await _invitation(session_factory, tenant_id, ada)
bob = await _outsider(session_factory)
@@ -297,7 +297,7 @@ class TestJoining:
self, session_factory, directory: _Directory, unavailable: _Directory
) -> None:
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
async with tenant_session(session_factory, tenant_id) as session:
await JoinDomainStore().add(
session, domain="example.invalid", created_by=ada
@@ -322,7 +322,7 @@ class TestJoining:
nothing there: the directory is not asked, and can't demote them."""
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "org_admin")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "org_admin")}
)
async with tenant_session(session_factory, tenant_id) as session:
await JoinDomainStore().add(
@@ -345,7 +345,7 @@ class TestChangingRoles:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
async with _client(_with(session_factory, directory), ada, tenant_id) as client:
@@ -370,7 +370,7 @@ class TestChangingRoles:
is asked, and a directory that then fails doesn't give it back."""
ada, bob = _name("ada"), _name("bob")
first = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "org_admin")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "org_admin")}
)
second = await _second_workspace(session_factory, first)
key = await _personal_key(session_factory, second, bob)
@@ -396,7 +396,7 @@ class TestChangingRoles:
asked, so the directory is never asked to demote both."""
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("owner", "org_admin")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("admin", "org_admin")}
)
app = _with(session_factory, directory)
@@ -421,7 +421,7 @@ class TestChangingRoles:
self, session_factory, directory: _Directory
) -> None:
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
async with _client(_with(session_factory, directory), ada, tenant_id) as client:
response = await client.patch(
@@ -436,7 +436,7 @@ class TestRemoving:
async def _bob_in_no_workspace(self, session_factory) -> tuple[str, str, str]:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
async with tenant_session(session_factory, tenant_id) as session:
await session.delete(await session.get(TenantMember, (tenant_id, bob)))
@@ -474,7 +474,7 @@ class TestRemoving:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
async with _client(_with(session_factory, directory), ada, tenant_id) as client:
@@ -490,7 +490,7 @@ class TestTheCurrentOrganization:
) -> None:
"""So the dashboard can say where people are added and made Org Admin."""
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
async with _client(_with(session_factory, directory), ada, tenant_id) as client:
response = await client.get("/organizations/current")
diff --git a/core/tests/switch_core/gateway/test_organization_routes.py b/core/tests/switch_core/gateway/test_organization_routes.py
index 9ca1f8311..5f1ad34bd 100644
--- a/core/tests/switch_core/gateway/test_organization_routes.py
+++ b/core/tests/switch_core/gateway/test_organization_routes.py
@@ -194,7 +194,7 @@ class TestListing:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
async with _client(_app(session_factory), ada, tenant_id) as client:
@@ -211,7 +211,7 @@ class TestListing:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("admin", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("admin", "member")}
)
async with _client(_app(session_factory), bob, tenant_id) as client:
@@ -226,7 +226,7 @@ class TestChangingRoles:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
async with _client(_app(session_factory), ada, tenant_id) as client:
@@ -251,7 +251,7 @@ class TestChangingRoles:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("admin", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("admin", "member")}
)
async with _client(_app(session_factory), bob, tenant_id) as client:
@@ -265,7 +265,7 @@ class TestChangingRoles:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
async with _client(_app(session_factory), ada, tenant_id) as client:
response = await client.patch(
@@ -278,7 +278,7 @@ class TestChangingRoles:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
async with _client(_app(session_factory), ada, tenant_id) as client:
response = await client.patch(
@@ -294,7 +294,7 @@ class TestChangingRoles:
then in the workspace."""
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("admin", "org_admin")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("admin", "org_admin")}
)
async with _client(_app(session_factory), ada, tenant_id) as client:
@@ -365,7 +365,7 @@ class TestRemoving:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
async with _client(_app(session_factory), ada, tenant_id) as client:
@@ -379,7 +379,7 @@ class TestRemoving:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
async with tenant_session(session_factory, tenant_id) as session:
await session.delete(await session.get(TenantMember, (tenant_id, bob)))
@@ -403,7 +403,7 @@ class TestRemoving:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
async with _client(_app(session_factory), ada, tenant_id) as client:
response = await client.delete(f"/organizations/current/members/{ada}")
@@ -420,7 +420,7 @@ class TestTheWorkspaceRoster:
tenant_id = await _workspace(
session_factory,
{
- ada: ("owner", "org_admin"),
+ ada: ("admin", "org_admin"),
bob: ("member", "member"),
cy: ("member", "org_admin"),
},
@@ -442,7 +442,7 @@ class TestTheWorkspaceRoster:
for row in response.json()
}
assert rows == {
- ada: ("owner", "org_admin", False),
+ ada: ("admin", "org_admin", False),
bob: ("member", "member", False),
cy: ("admin", "org_admin", True),
}
@@ -453,7 +453,7 @@ class TestThePlatformOperator:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
operator_id = await _operator(session_factory)
async with _client(_app(session_factory), operator_id, None) as client:
@@ -469,7 +469,7 @@ class TestThePlatformOperator:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("admin", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("admin", "member")}
)
operator_id = await _operator(session_factory)
@@ -496,7 +496,7 @@ class TestThePlatformOperator:
`org_admin`, and is there as that."""
operator_id = await _operator(session_factory)
bob = _name("bob")
- tenant_id = await _workspace(session_factory, {bob: ("admin", "member")})
+ tenant_id = await _workspace(session_factory, {bob: ("member", "member")})
async with session_factory() as session:
tenant = await session.get(Tenant, tenant_id)
assert tenant is not None and tenant.organization_id is not None
@@ -513,7 +513,7 @@ class TestThePlatformOperator:
await client.post(f"/tenants/{tenant_id}/switch")
async with _client(_app(session_factory), operator_id, tenant_id) as client:
write = await client.patch(
- f"/tenants/{tenant_id}/members/{bob}", json={"role": "member"}
+ f"/tenants/{tenant_id}/members/{bob}", json={"role": "admin"}
)
assert write.status_code == 200, write.text
@@ -525,7 +525,7 @@ class TestThePlatformOperator:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
operator_id = await _operator(session_factory)
async with _client(_app(session_factory), operator_id, None) as client:
@@ -542,10 +542,10 @@ class TestThePlatformOperator:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
bob, cy = _name("bob"), _name("cy")
- orphaned = await _workspace(session_factory, {bob: ("owner", "member")})
+ orphaned = await _workspace(session_factory, {bob: ("admin", "member")})
governed = await _workspace(
session_factory,
- {cy: ("owner", "org_admin"), _name("dee"): ("member", "member")},
+ {cy: ("admin", "org_admin"), _name("dee"): ("member", "member")},
)
operator_id = await _operator(session_factory)
@@ -648,7 +648,7 @@ class TestCreatingAnOrganization:
"acme",
"org_admin",
)
- assert (workspace["name"], workspace["role"]) == ("Research", "owner")
+ assert (workspace["name"], workspace["role"]) == ("Research", "admin")
assert workspace["organization_id"] == organization["id"]
assert (
await _organization_id(session_factory, workspace["id"])
@@ -663,7 +663,7 @@ class TestCreatingAnOrganization:
organization_member = await session.get(
OrganizationMember, (organization["id"], ada)
)
- assert membership is not None and membership.role == "owner"
+ assert membership is not None and membership.role == "admin"
assert organization_member is not None
assert organization_member.role == "org_admin"
async with tenant_session(session_factory, workspace["id"]) as session:
@@ -745,7 +745,7 @@ class TestCreatingAWorkspace:
assert await _organization_id(session_factory, workspace["id"]) == (
organization_id
)
- assert workspace["role"] == "owner"
+ assert workspace["role"] == "admin"
# The session stays in the workspace it was in.
assert response.cookies.get("switch_auth") is None
assert await _workspaces_created(session_factory, ada) == 1
@@ -765,14 +765,14 @@ class TestCreatingAWorkspace:
)
async with tenant_session(session_factory, workspace["id"]) as session:
membership = await session.get(TenantMember, (workspace["id"], ada))
- assert membership is not None and membership.role == "owner"
+ assert membership is not None and membership.role == "admin"
async def test_a_workspace_admin_who_is_no_org_admin_is_refused(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("admin", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("admin", "member")}
)
async with _client(_app(session_factory), bob, tenant_id) as client:
@@ -787,7 +787,7 @@ class TestCreatingAWorkspace:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
app = _app(session_factory, signup_mode="invite_only")
async with _client(app, ada, tenant_id) as client:
@@ -801,7 +801,7 @@ class TestCreatingAWorkspace:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
app = _app(session_factory, max_workspaces_per_user=1)
async with _client(app, ada, tenant_id) as client:
@@ -822,7 +822,7 @@ class TestListingOrganizationsAndWorkspaces:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
app = _app(session_factory)
async with _client(app, ada, tenant_id) as client:
@@ -848,7 +848,7 @@ class TestListingOrganizationsAndWorkspaces:
"""There on the operator flag alone, the operator may enter every
workspace of the organization, and is shown each as its admin."""
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
app = _app(session_factory)
async with _client(app, ada, tenant_id) as client:
created = await client.post(
@@ -897,7 +897,7 @@ class TestTheOrganizationAuditLog:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
async with _client(_app(session_factory), ada, tenant_id) as client:
@@ -926,7 +926,7 @@ class TestTheOrganizationAuditLog:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("admin", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("admin", "member")}
)
async with _client(_app(session_factory), bob, tenant_id) as client:
@@ -966,7 +966,7 @@ class TestNamesInTheOrganizationAuditLog:
removed member no longer is; both are named all the same."""
bob, cy = _name("bob"), _name("cy")
tenant_id = await _workspace(
- session_factory, {bob: ("owner", "member"), cy: ("member", "member")}
+ session_factory, {bob: ("admin", "member"), cy: ("member", "member")}
)
operator_id = await _operator(session_factory)
app = _app(session_factory)
@@ -1024,13 +1024,13 @@ class TestMarkingTheOperatorsOrganizationChanges:
await session.commit()
return operator_id
- async def test_restoring_an_admin_is_marked_though_the_operator_owns_the_workspace(
+ async def test_restoring_an_admin_is_marked_though_the_operator_administers_the_workspace(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
bob = _name("bob")
tenant_id = await _workspace(session_factory, {bob: ("member", "member")})
operator_id = await self._operator_in(
- session_factory, tenant_id, workspace_role="owner", organization_role=None
+ session_factory, tenant_id, workspace_role="admin", organization_role=None
)
async with _client(_app(session_factory), operator_id, tenant_id) as client:
@@ -1168,7 +1168,7 @@ class TestLosingOrgAdmin:
) -> None:
ada, bob = _name("ada"), _name("bob")
first = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "org_admin")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "org_admin")}
)
second = await _second_workspace(session_factory, first)
kept = await _personal_key(session_factory, first, bob)
@@ -1196,7 +1196,7 @@ class TestLosingOrgAdmin:
) -> None:
ada, bob = _name("ada"), _name("bob")
first = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "org_admin")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "org_admin")}
)
second = await _second_workspace(session_factory, first)
await _agent(session_factory, second, bob)
@@ -1219,7 +1219,7 @@ class TestLosingOrgAdmin:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
ada, bob = _name("ada"), _name("bob")
- first = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ first = await _workspace(session_factory, {ada: ("admin", "org_admin")})
second = await _second_workspace(session_factory, first)
organization_id = await _organization_id(session_factory, first)
assert organization_id is not None
@@ -1247,7 +1247,7 @@ class TestLosingOrgAdmin:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("owner", "org_admin")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("admin", "org_admin")}
)
app = _app(session_factory)
@@ -1278,7 +1278,7 @@ class TestLosingOrgAdmin:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
ada, bob, cy = _name("ada"), _name("bob"), _name("cy")
- first = await _workspace(session_factory, {cy: ("owner", "member")})
+ first = await _workspace(session_factory, {cy: ("admin", "member")})
organization_id = await _organization_id(session_factory, first)
assert organization_id is not None
async with session_factory() as session:
@@ -1331,7 +1331,7 @@ class TestIssues:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
async with _client(_app(session_factory), ada, tenant_id) as client:
response = await client.get("/organizations/current/issues")
@@ -1339,12 +1339,14 @@ class TestIssues:
assert response.status_code == 200, response.text
assert response.json() == []
- async def test_a_workspace_without_an_owner_until_one_is_made(
+ async def test_a_workspace_without_an_admin_until_one_is_made(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
+ """The organization's admin administers the workspace, but a workspace
+ keeps an admin of its own, as the last-admin guard holds it to."""
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("member", "org_admin"), bob: ("member", "member")}
)
async with _client(_app(session_factory), ada, tenant_id) as client:
@@ -1352,13 +1354,13 @@ class TestIssues:
async with tenant_session(session_factory, tenant_id) as session:
member = await session.get(TenantMember, (tenant_id, bob))
assert member is not None
- member.role = "owner"
+ member.role = "admin"
await session.commit()
after = await client.get("/organizations/current/issues")
assert before.json() == [
{
- "kind": "workspace_without_owner",
+ "kind": "workspace_without_admin",
"workspace_id": tenant_id,
"workspace_name": "Acme",
"agents": [],
@@ -1375,7 +1377,7 @@ class TestIssues:
in any workspace."""
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
operator_id = await _operator(session_factory)
bobs_agent = await _agent(session_factory, tenant_id, bob)
@@ -1407,7 +1409,7 @@ class TestIssues:
"""Only a deletion of the WorkOS organization followed now counts,
whatever order the audit log has it in."""
ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
organization_id = await _organization_of(session_factory, tenant_id)
deleted_id, other_id = _name("org_workos"), _name("org_workos")
@@ -1450,7 +1452,7 @@ class TestIssues:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
bob = _name("bob")
- tenant_id = await _workspace(session_factory, {bob: ("owner", "member")})
+ tenant_id = await _workspace(session_factory, {bob: ("admin", "member")})
operator_id = await _operator(session_factory)
async with _client(_app(session_factory), operator_id, tenant_id) as client:
@@ -1464,7 +1466,7 @@ class TestIssues:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id = await _workspace(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
async with _client(_app(session_factory), bob, tenant_id) as client:
diff --git a/core/tests/switch_core/gateway/test_organization_services.py b/core/tests/switch_core/gateway/test_organization_services.py
index e8dd783f0..89d90f43f 100644
--- a/core/tests/switch_core/gateway/test_organization_services.py
+++ b/core/tests/switch_core/gateway/test_organization_services.py
@@ -133,18 +133,20 @@ async def _events(session_factory) -> list[OrganizationAuditEvent]:
class TestWhoMayCall:
- async def test_a_workspace_owner_is_refused(self, harness: Harness) -> None:
- owner = await _person(harness.session_factory, "owner", member_role="owner")
+ async def test_a_workspace_admin_is_refused(self, harness: Harness) -> None:
+ ws_admin = await _person(
+ harness.session_factory, "ws-admin", member_role="admin"
+ )
answers = [
- await _call(harness, owner, "GET", ORGANIZATION),
+ await _call(harness, ws_admin, "GET", ORGANIZATION),
await _call(
harness,
- owner,
+ ws_admin,
"PUT",
f"{ORGANIZATION}/github",
{"enabled": False, "locked": True},
),
- await _call(harness, owner, "DELETE", f"{ORGANIZATION}/github"),
+ await _call(harness, ws_admin, "DELETE", f"{ORGANIZATION}/github"),
]
assert [answer.status_code for answer in answers] == [403] * 3
diff --git a/core/tests/switch_core/gateway/test_query_counts.py b/core/tests/switch_core/gateway/test_query_counts.py
index 529009cc2..978dba0a7 100644
--- a/core/tests/switch_core/gateway/test_query_counts.py
+++ b/core/tests/switch_core/gateway/test_query_counts.py
@@ -158,7 +158,7 @@ class _Seed:
session.add(user)
await session.flush()
session.add(
- TenantMember(tenant_id=TENANT_ZERO_ID, user_id=user.id, role="owner")
+ TenantMember(tenant_id=TENANT_ZERO_ID, user_id=user.id, role="admin")
)
await session.commit()
return user
diff --git a/core/tests/switch_core/gateway/test_service_connections.py b/core/tests/switch_core/gateway/test_service_connections.py
index 690a8bbbe..53fd0b66c 100644
--- a/core/tests/switch_core/gateway/test_service_connections.py
+++ b/core/tests/switch_core/gateway/test_service_connections.py
@@ -437,7 +437,7 @@ class TestMemberRemoval:
) -> None:
await _make_tenant(session_factory, TENANT_A)
admin_id = await _make_member(
- session_factory, name="svc-admin", tenant_id=TENANT_A, role="owner"
+ session_factory, name="svc-admin", tenant_id=TENANT_A, role="admin"
)
member_id = await _make_member(
session_factory, name="svc-member", tenant_id=TENANT_A, role="member"
diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.py
index b69751ff4..8001af0be 100644
--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py
+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py
@@ -349,7 +349,7 @@ async def _make_agent_with_key(
class TestCreateTenant:
- async def test_creating_a_tenant_makes_the_caller_its_owner(
+ async def test_creating_a_tenant_makes_the_caller_its_admin(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
await _make_tenant(session_factory, TENANT_A)
@@ -364,12 +364,12 @@ class TestCreateTenant:
assert response.status_code == 201, response.text
body = response.json()
assert body["slug"] == "acme-corp"
- assert body["role"] == "owner"
+ assert body["role"] == "admin"
async with session_factory() as session:
membership = await session.get(TenantMember, (body["id"], user_id))
assert membership is not None
- assert membership.role == "owner"
+ assert membership.role == "admin"
async def test_creating_a_tenant_switches_the_caller_into_it(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -400,7 +400,7 @@ class TestCreateTenant:
response = await client.post("/tenants", json={"name": "First Light"})
assert response.status_code == 201, response.text
- assert response.json()["role"] == "owner"
+ assert response.json()["role"] == "admin"
assert _tenant_claim(response) == response.json()["id"]
async def test_a_taken_slug_gets_a_suffix_rather_than_a_409(
@@ -496,8 +496,8 @@ class TestCreateTenant:
async def test_a_failure_other_than_a_taken_slug_is_not_retried(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- """Retrying would leave the committed workspace behind, ownerless, and
- make another one."""
+ """Retrying would leave the committed workspace behind, with no admin,
+ and make another one."""
user_id = await _make_unaffiliated_user(
session_factory, name="unlucky", role="user"
)
@@ -609,8 +609,9 @@ class TestWorkspaceCreationLimit:
async def test_handing_a_workspace_over_does_not_free_the_allowance(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- # What is bounded is creation. Were it ownership, creating, promoting a
- # second account and stepping down would reset the count every time.
+ # What is bounded is creation. Were it the workspaces someone administers,
+ # creating, promoting a second account and stepping down would reset the
+ # count every time.
await _make_tenant(session_factory, TENANT_A)
user_id = await _make_member(
session_factory, name="hand-off", tenant_id=TENANT_A, role="member"
@@ -654,7 +655,7 @@ class TestWorkspaceCreationLimit:
async with session_factory() as session:
owned = await session.scalars(
select(TenantMember).where(
- TenantMember.user_id == user_id, TenantMember.role == "owner"
+ TenantMember.user_id == user_id, TenantMember.role == "admin"
)
)
assert len(owned.all()) == 1
@@ -730,7 +731,7 @@ class TestWorkspaceCreationLimit:
# `users.role == "admin"` is the deployment operator bit, and this
# bound is about self-service. An operator provisioning workspaces for
# other people is exactly who it must not stop — the same bypass
- # `authz.administers_tenant` and `authz.owns_tenant` already give them.
+ # `authz.administers_tenant` already gives them.
await _make_tenant(session_factory, TENANT_A)
user_id = await _make_member(
session_factory,
@@ -812,14 +813,14 @@ class TestInvitationAuthorisation:
async with tenant_session(session_factory, TENANT_B) as scoped:
assert await InvitationStore().list_for_tenant(scoped) == []
- async def test_an_owner_can_mint_an_invitation_to_their_own_tenant(
+ async def test_an_admin_can_mint_an_invitation_to_their_own_tenant(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
await _make_tenant(session_factory, TENANT_A)
user_id = await _make_member(
- session_factory, name="a-owner", tenant_id=TENANT_A, role="owner"
+ session_factory, name="a-admin", tenant_id=TENANT_A, role="admin"
)
- token = _token(user_id, "[email protected]", TENANT_A)
+ token = _token(user_id, "[email protected]", TENANT_A)
async with _client(_app(session_factory), token) as client:
response = await client.post(
@@ -841,7 +842,7 @@ class TestInvitationAuthorisation:
bound belongs on the schema, where it is a 422 with a field name."""
await _make_tenant(session_factory, TENANT_A)
user_id = await _make_member(
- session_factory, name="time-lord", tenant_id=TENANT_A, role="owner"
+ session_factory, name="time-lord", tenant_id=TENANT_A, role="admin"
)
token = _token(user_id, "[email protected]", TENANT_A)
@@ -862,9 +863,9 @@ class TestInvitationAuthorisation:
) -> None:
await _make_tenant(session_factory, TENANT_A)
user_id = await _make_member(
- session_factory, name="a-owner", tenant_id=TENANT_A, role="owner"
+ session_factory, name="a-admin", tenant_id=TENANT_A, role="admin"
)
- token = _token(user_id, "[email protected]", TENANT_A)
+ token = _token(user_id, "[email protected]", TENANT_A)
async with _client(_app(session_factory), token) as client:
response = await client.post(
@@ -875,109 +876,73 @@ class TestInvitationAuthorisation:
assert response.status_code == status, response.text
-class TestOwnershipIsOwnerOnly:
- """Who owns a workspace is decided by its owners, not by its admins.
-
- An `admin` runs the workspace; only an `owner` moves the ownership set.
- The distinction exists because a last-owner guard cannot see a sequence:
- each request below is individually safe — two owners stand at every
- step — and together they hand the workspace to someone the founder never
- promoted.
- """
+class TestOneAdminRole:
+ """`owner` merged into `admin`: every admin runs the workspace, other
+ admins included, and a workspace always keeps at least one."""
- async def test_an_admin_cannot_take_the_workspace_from_its_owner(
+ async def test_an_admin_can_demote_and_remove_another_admin(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
await _make_tenant(session_factory, TENANT_A)
- founder_id = await _make_member(
- session_factory, name="founder-owner", tenant_id=TENANT_A, role="owner"
- )
admin_id = await _make_member(
- session_factory, name="ambitious-admin", tenant_id=TENANT_A, role="admin"
- )
- token = _token(admin_id, "[email protected]", TENANT_A)
-
- async with _client(_app(session_factory), token) as client:
- promote_self = await client.patch(
- f"/tenants/{TENANT_A}/members/{admin_id}", json={"role": "owner"}
- )
- demote_founder = await client.patch(
- f"/tenants/{TENANT_A}/members/{founder_id}", json={"role": "member"}
- )
- remove_founder = await client.delete(
- f"/tenants/{TENANT_A}/members/{founder_id}"
- )
-
- assert promote_self.status_code == 403, promote_self.text
- assert demote_founder.status_code == 403, demote_founder.text
- assert remove_founder.status_code == 403, remove_founder.text
-
- async with session_factory() as session:
- founder = await session.get(TenantMember, (TENANT_A, founder_id))
- admin = await session.get(TenantMember, (TENANT_A, admin_id))
- assert founder is not None and founder.role == "owner"
- assert admin is not None and admin.role == "admin"
-
- async def test_an_admin_cannot_mint_an_owner_invitation(
- self, session_factory: async_sessionmaker[AsyncSession]
- ) -> None:
- """Otherwise the escalation above is the same three steps with a link
- in the middle: invite an accomplice as owner, then let them do it."""
- await _make_tenant(session_factory, TENANT_A)
- await _make_member(
- session_factory, name="quiet-owner", tenant_id=TENANT_A, role="owner"
+ session_factory, name="admin-one", tenant_id=TENANT_A, role="admin"
)
- admin_id = await _make_member(
- session_factory, name="inviting-admin", tenant_id=TENANT_A, role="admin"
+ other_id = await _make_member(
+ session_factory, name="admin-two", tenant_id=TENANT_A, role="admin"
)
- token = _token(admin_id, "[email protected]", TENANT_A)
+ token = _token(admin_id, "[email protected]", TENANT_A)
async with _client(_app(session_factory), token) as client:
- refused = await client.post(
- f"/tenants/{TENANT_A}/invitations", json={"role": "owner"}
- )
- allowed = await client.post(
- f"/tenants/{TENANT_A}/invitations", json={"role": "admin"}
+ demote = await client.patch(
+ f"/tenants/{TENANT_A}/members/{other_id}", json={"role": "member"}
)
+ remove = await client.delete(f"/tenants/{TENANT_A}/members/{other_id}")
- assert refused.status_code == 403, refused.text
- assert allowed.status_code == 201, allowed.text
-
- async with tenant_session(session_factory, TENANT_A) as scoped:
- roles = [i.role for i in await InvitationStore().list_for_tenant(scoped)]
- assert roles == ["admin"]
+ assert demote.status_code == 200, demote.text
+ assert demote.json()["role"] == "member"
+ assert remove.status_code == 200, remove.text
- async def test_an_owner_can_do_all_of_it(
+ async def test_a_client_asking_for_owner_gets_admin(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- """The guard is narrower authority, not a locked door: everything the
- admin was refused above succeeds for an owner."""
+ """A Console from before the merge still offers `owner`."""
await _make_tenant(session_factory, TENANT_A)
- owner_id = await _make_member(
- session_factory, name="real-owner", tenant_id=TENANT_A, role="owner"
+ admin_id = await _make_member(
+ session_factory, name="old-console", tenant_id=TENANT_A, role="admin"
)
member_id = await _make_member(
session_factory, name="promoted", tenant_id=TENANT_A, role="member"
)
- token = _token(owner_id, "[email protected]", TENANT_A)
+ token = _token(admin_id, "[email protected]", TENANT_A)
async with _client(_app(session_factory), token) as client:
promote = await client.patch(
f"/tenants/{TENANT_A}/members/{member_id}", json={"role": "owner"}
)
- demote = await client.patch(
- f"/tenants/{TENANT_A}/members/{member_id}", json={"role": "member"}
- )
invite = await client.post(
f"/tenants/{TENANT_A}/invitations", json={"role": "owner"}
)
- remove = await client.delete(f"/tenants/{TENANT_A}/members/{member_id}")
assert promote.status_code == 200, promote.text
- assert promote.json()["role"] == "owner"
- assert demote.status_code == 200, demote.text
+ assert promote.json()["role"] == "admin"
assert invite.status_code == 201, invite.text
- assert remove.status_code == 200, remove.text
+ assert invite.json()["role"] == "admin"
+
+ async def test_an_unknown_role_is_refused(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _make_tenant(session_factory, TENANT_A)
+ admin_id = await _make_member(
+ session_factory, name="typo", tenant_id=TENANT_A, role="admin"
+ )
+ token = _token(admin_id, "[email protected]", TENANT_A)
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.post(
+ f"/tenants/{TENANT_A}/invitations", json={"role": "superadmin"}
+ )
+
+ assert response.status_code == 400, response.text
class TestInvitationLifecycle:
@@ -1012,7 +977,7 @@ class TestInvitationLifecycle:
) -> None:
await _make_tenant(session_factory, TENANT_A)
admin_id = await _make_member(
- session_factory, name="inviter", tenant_id=TENANT_A, role="owner"
+ session_factory, name="inviter", tenant_id=TENANT_A, role="admin"
)
_id, token = await self._mint(
session_factory, tenant_id=TENANT_A, admin_id=admin_id, role="admin"
@@ -1049,7 +1014,7 @@ class TestInvitationLifecycle:
"""
await _make_tenant(session_factory, TENANT_A)
admin_id = await _make_member(
- session_factory, name="link-sharer", tenant_id=TENANT_A, role="owner"
+ session_factory, name="link-sharer", tenant_id=TENANT_A, role="admin"
)
invitation_id, token = await self._mint(
session_factory, tenant_id=TENANT_A, admin_id=admin_id, uses_remaining=2
@@ -1080,7 +1045,7 @@ class TestInvitationLifecycle:
) -> None:
await _make_tenant(session_factory, TENANT_A)
admin_id = await _make_member(
- session_factory, name="inviter2", tenant_id=TENANT_A, role="owner"
+ session_factory, name="inviter2", tenant_id=TENANT_A, role="admin"
)
_id, token = await self._mint(
session_factory, tenant_id=TENANT_A, admin_id=admin_id, uses_remaining=1
@@ -1116,7 +1081,7 @@ class TestInvitationLifecycle:
) -> None:
await _make_tenant(session_factory, TENANT_A)
admin_id = await _make_member(
- session_factory, name="revoker", tenant_id=TENANT_A, role="owner"
+ session_factory, name="revoker", tenant_id=TENANT_A, role="admin"
)
invitation_id, token = await self._mint(
session_factory, tenant_id=TENANT_A, admin_id=admin_id
@@ -1144,7 +1109,7 @@ class TestInvitationLifecycle:
) -> None:
await _make_tenant(session_factory, TENANT_A)
admin_id = await _make_member(
- session_factory, name="expiry-setter", tenant_id=TENANT_A, role="owner"
+ session_factory, name="expiry-setter", tenant_id=TENANT_A, role="admin"
)
_id, token = await self._mint(
session_factory,
@@ -1180,7 +1145,7 @@ class TestInvitationLifecycle:
) -> None:
await _make_tenant(session_factory, TENANT_A)
admin_id = await _make_member(
- session_factory, name="picky-inviter", tenant_id=TENANT_A, role="owner"
+ session_factory, name="picky-inviter", tenant_id=TENANT_A, role="admin"
)
_id, token = await self._mint(
session_factory,
@@ -1211,7 +1176,7 @@ class TestInvitationLifecycle:
) -> None:
await _make_tenant(session_factory, TENANT_A)
admin_id = await _make_member(
- session_factory, name="picky-inviter2", tenant_id=TENANT_A, role="owner"
+ session_factory, name="picky-inviter2", tenant_id=TENANT_A, role="admin"
)
_id, token = await self._mint(
session_factory,
@@ -1261,10 +1226,10 @@ class TestInvitationsAddressedToMe:
for tenant_id in (TENANT_A, TENANT_C):
await _make_tenant(session_factory, tenant_id)
inviter_a = await _make_member(
- session_factory, name="Ada", tenant_id=TENANT_A, role="owner"
+ session_factory, name="Ada", tenant_id=TENANT_A, role="admin"
)
inviter_c = await _make_member(
- session_factory, name="Cy", tenant_id=TENANT_C, role="owner"
+ session_factory, name="Cy", tenant_id=TENANT_C, role="admin"
)
wanted_a, _ = await self._mint(
session_factory,
@@ -1287,7 +1252,7 @@ class TestInvitationsAddressedToMe:
)
inviter_b = await _make_member(
- session_factory, name="Bo", tenant_id=TENANT_B, role="owner"
+ session_factory, name="Bo", tenant_id=TENANT_B, role="admin"
)
await self._mint(
session_factory,
@@ -1314,7 +1279,7 @@ class TestInvitationsAddressedToMe:
invitee_id, cookie = await self._invitee(session_factory, "joiner")
await _make_tenant(session_factory, TENANT_A)
inviter = await _make_member(
- session_factory, name="inviter", tenant_id=TENANT_A, role="owner"
+ session_factory, name="inviter", tenant_id=TENANT_A, role="admin"
)
invitation_id, _ = await self._mint(
session_factory,
@@ -1350,7 +1315,7 @@ class TestInvitationsAddressedToMe:
_invitee_id, cookie = await self._invitee(session_factory, "id-guesser")
await _make_tenant(session_factory, TENANT_A)
inviter = await _make_member(
- session_factory, name="inviter", tenant_id=TENANT_A, role="owner"
+ session_factory, name="inviter", tenant_id=TENANT_A, role="admin"
)
invitation_id, _ = await self._mint(
session_factory, tenant_id=TENANT_A, admin_id=inviter
@@ -1374,7 +1339,7 @@ class TestInvitationsAddressedToMe:
_invitee_id, cookie = await self._invitee(session_factory, "not-them")
await _make_tenant(session_factory, TENANT_A)
inviter = await _make_member(
- session_factory, name="inviter", tenant_id=TENANT_A, role="owner"
+ session_factory, name="inviter", tenant_id=TENANT_A, role="admin"
)
invitation_id, _ = await self._mint(
session_factory,
@@ -1398,7 +1363,7 @@ class TestInvitationsAddressedToMe:
for tenant_id in (TENANT_A, TENANT_C):
await _make_tenant(session_factory, tenant_id)
inviter = await _make_member(
- session_factory, name="inviter", tenant_id=TENANT_A, role="owner"
+ session_factory, name="inviter", tenant_id=TENANT_A, role="admin"
)
invitation_id, _ = await self._mint(
session_factory,
@@ -1423,7 +1388,7 @@ class TestInvitationsAddressedToMe:
_invitee_id, cookie = await self._invitee(session_factory, "too-late")
await _make_tenant(session_factory, TENANT_A)
inviter = await _make_member(
- session_factory, name="inviter", tenant_id=TENANT_A, role="owner"
+ session_factory, name="inviter", tenant_id=TENANT_A, role="admin"
)
invitation_id, _ = await self._mint(
session_factory,
@@ -1450,27 +1415,27 @@ class TestMemberRoutes:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
await _make_tenant(session_factory, TENANT_A)
- owner_id = await _make_member(
- session_factory, name="list-owner", tenant_id=TENANT_A, role="owner"
+ admin_id = await _make_member(
+ session_factory, name="list-admin", tenant_id=TENANT_A, role="admin"
)
await _make_member(
session_factory, name="list-member", tenant_id=TENANT_A, role="member"
)
- token = _token(owner_id, "[email protected]", TENANT_A)
+ token = _token(admin_id, "[email protected]", TENANT_A)
async with _client(_app(session_factory), token) as client:
response = await client.get(f"/tenants/{TENANT_A}/members")
assert response.status_code == 200, response.text
roles = {row["name"]: row["role"] for row in response.json()}
- assert roles == {"list-owner": "owner", "list-member": "member"}
+ assert roles == {"list-admin": "admin", "list-member": "member"}
async def test_listing_flags_the_bootstrap_owner_as_a_service_account(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
await _make_tenant(session_factory, TENANT_A)
- owner_id = await _make_member(
- session_factory, name="Agent Bootstrap", tenant_id=TENANT_A, role="owner"
+ admin_id = await _make_member(
+ session_factory, name="Agent Bootstrap", tenant_id=TENANT_A, role="admin"
)
bootstrap_id = await _make_member(
session_factory, name="robot", tenant_id=TENANT_A, role="member"
@@ -1480,7 +1445,7 @@ class TestMemberRoutes:
assert bootstrap is not None
bootstrap.metadata_ = {BOOTSTRAP_OWNER_MARKER_META_KEY: True}
await session.commit()
- token = _token(owner_id, "Agent [email protected]", TENANT_A)
+ token = _token(admin_id, "Agent [email protected]", TENANT_A)
async with _client(_app(session_factory), token) as client:
response = await client.get(f"/tenants/{TENANT_A}/members")
@@ -1489,76 +1454,76 @@ class TestMemberRoutes:
flags = {row["name"]: row["service_account"] for row in response.json()}
assert flags == {"Agent Bootstrap": False, "robot": True}
- async def test_the_last_owner_cannot_be_demoted(
+ async def test_the_last_admin_cannot_be_demoted(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
await _make_tenant(session_factory, TENANT_A)
- owner_id = await _make_member(
- session_factory, name="sole-owner", tenant_id=TENANT_A, role="owner"
+ admin_id = await _make_member(
+ session_factory, name="sole-admin", tenant_id=TENANT_A, role="admin"
)
- token = _token(owner_id, "[email protected]", TENANT_A)
+ token = _token(admin_id, "[email protected]", TENANT_A)
async with _client(_app(session_factory), token) as client:
response = await client.patch(
- f"/tenants/{TENANT_A}/members/{owner_id}", json={"role": "member"}
+ f"/tenants/{TENANT_A}/members/{admin_id}", json={"role": "member"}
)
assert response.status_code == 409
async with session_factory() as session:
- membership = await session.get(TenantMember, (TENANT_A, owner_id))
+ membership = await session.get(TenantMember, (TENANT_A, admin_id))
assert membership is not None
- assert membership.role == "owner"
+ assert membership.role == "admin"
- async def test_an_owner_can_be_demoted_when_another_owner_remains(
+ async def test_an_admin_can_be_demoted_when_another_admin_remains(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
await _make_tenant(session_factory, TENANT_A)
- owner_id = await _make_member(
- session_factory, name="owner-one", tenant_id=TENANT_A, role="owner"
+ admin_id = await _make_member(
+ session_factory, name="admin-one", tenant_id=TENANT_A, role="admin"
)
- other_owner_id = await _make_member(
- session_factory, name="owner-two", tenant_id=TENANT_A, role="owner"
+ other_admin_id = await _make_member(
+ session_factory, name="admin-two", tenant_id=TENANT_A, role="admin"
)
- token = _token(owner_id, "[email protected]", TENANT_A)
+ token = _token(admin_id, "[email protected]", TENANT_A)
async with _client(_app(session_factory), token) as client:
response = await client.patch(
- f"/tenants/{TENANT_A}/members/{other_owner_id}",
+ f"/tenants/{TENANT_A}/members/{other_admin_id}",
json={"role": "member"},
)
assert response.status_code == 200, response.text
assert response.json()["role"] == "member"
- async def test_the_last_owner_cannot_be_removed(
+ async def test_the_last_admin_cannot_be_removed(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
await _make_tenant(session_factory, TENANT_A)
- owner_id = await _make_member(
- session_factory, name="undeletable-owner", tenant_id=TENANT_A, role="owner"
+ admin_id = await _make_member(
+ session_factory, name="undeletable-admin", tenant_id=TENANT_A, role="admin"
)
- token = _token(owner_id, "[email protected]", TENANT_A)
+ token = _token(admin_id, "[email protected]", TENANT_A)
async with _client(_app(session_factory), token) as client:
- response = await client.delete(f"/tenants/{TENANT_A}/members/{owner_id}")
+ response = await client.delete(f"/tenants/{TENANT_A}/members/{admin_id}")
assert response.status_code == 409
async with session_factory() as session:
- assert await session.get(TenantMember, (TENANT_A, owner_id)) is not None
+ assert await session.get(TenantMember, (TENANT_A, admin_id)) is not None
async def test_removing_a_member_deletes_their_membership(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
await _make_tenant(session_factory, TENANT_A)
- owner_id = await _make_member(
- session_factory, name="remover", tenant_id=TENANT_A, role="owner"
+ admin_id = await _make_member(
+ session_factory, name="remover", tenant_id=TENANT_A, role="admin"
)
target_id = await _make_member(
session_factory, name="removed", tenant_id=TENANT_A, role="member"
)
- token = _token(owner_id, "[email protected]", TENANT_A)
+ token = _token(admin_id, "[email protected]", TENANT_A)
async with tenant_session(session_factory, TENANT_A) as session:
await ServiceConnectionStore().save_connection(
session,
@@ -1596,7 +1561,7 @@ class TestMemberRoutes:
for state, user_id, kind in (
("removed-github", target_id, "github"),
("removed-service", target_id, "service"),
- ("other", owner_id, "github"),
+ ("other", admin_id, "github"),
):
await app.state.sign_in_flows.start(
kind=kind,
@@ -1653,8 +1618,8 @@ class TestMemberRoutes:
first lookup `ApiKeyStore.get_by_hash` performs.
"""
await _make_tenant(session_factory, TENANT_A)
- owner_id = await _make_member(
- session_factory, name="key-remover", tenant_id=TENANT_A, role="owner"
+ admin_id = await _make_member(
+ session_factory, name="key-remover", tenant_id=TENANT_A, role="admin"
)
target_id = await _make_member(
session_factory, name="key-holder", tenant_id=TENANT_A, role="member"
@@ -1662,7 +1627,7 @@ class TestMemberRoutes:
key_hash = await _make_api_key(
session_factory, tenant_id=TENANT_A, user_id=target_id
)
- token = _token(owner_id, "[email protected]", TENANT_A)
+ token = _token(admin_id, "[email protected]", TENANT_A)
async with session_factory() as session:
assert await ApiKeyStore().get_by_hash(session, key_hash) is not None
@@ -1685,8 +1650,8 @@ class TestMemberRoutes:
own key may be touched when the route 409s.
"""
await _make_tenant(session_factory, TENANT_A)
- owner_id = await _make_member(
- session_factory, name="agent-remover", tenant_id=TENANT_A, role="owner"
+ admin_id = await _make_member(
+ session_factory, name="agent-remover", tenant_id=TENANT_A, role="admin"
)
target_id = await _make_member(
session_factory, name="agent-owner", tenant_id=TENANT_A, role="member"
@@ -1697,7 +1662,7 @@ class TestMemberRoutes:
personal_key_hash = await _make_api_key(
session_factory, tenant_id=TENANT_A, user_id=target_id
)
- token = _token(owner_id, "[email protected]", TENANT_A)
+ token = _token(admin_id, "[email protected]", TENANT_A)
async with _client(_app(session_factory), token) as client:
response = await client.delete(f"/tenants/{TENANT_A}/members/{target_id}")
@@ -1798,7 +1763,7 @@ class TestCurrentTenantRoute:
session_factory, name="current-member", tenant_id=TENANT_A, role="member"
)
async with session_factory() as session:
- session.add(TenantMember(tenant_id=TENANT_B, user_id=user_id, role="owner"))
+ session.add(TenantMember(tenant_id=TENANT_B, user_id=user_id, role="admin"))
await session.commit()
token = _token(user_id, "[email protected]", TENANT_A)
@@ -1818,9 +1783,9 @@ class TestCurrentTenantRoute:
@pytest.mark.parametrize(
("role", "user_role"),
- [("admin", "user"), ("owner", "user"), ("member", "admin")],
+ [("admin", "user"), ("member", "admin")],
)
- async def test_an_admin_owner_or_operator_is_told_they_administer_it(
+ async def test_an_admin_or_operator_is_told_they_administer_it(
self,
session_factory: async_sessionmaker[AsyncSession],
role: str,
@@ -1967,33 +1932,35 @@ class TestOrganizationAdmins:
async def test_an_org_admin_manages_members_as_a_workspace_admin_does(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- """Admin-level, not owner-level: the ownership set is still the
- workspace owners' own."""
+ """Including other admins, as any admin may; and like them, not the
+ workspace's last admin of its own, whom the organization's admin does
+ not stand in for."""
admin_id = await _make_unaffiliated_user(
session_factory, name="org-admin", role="user"
)
await self._organization_of(
session_factory, TENANT_A, members={admin_id: "org_admin"}
)
- member_id = await _make_member(
- session_factory, name="ws-admin", tenant_id=TENANT_A, role="admin"
+ first_id = await _make_member(
+ session_factory, name="ws-admin-1", tenant_id=TENANT_A, role="admin"
)
- owner_id = await _make_member(
- session_factory, name="ws-owner", tenant_id=TENANT_A, role="owner"
+ last_id = await _make_member(
+ session_factory, name="ws-admin-2", tenant_id=TENANT_A, role="admin"
)
token = _token(admin_id, "[email protected]", TENANT_A)
async with _client(_app(session_factory), token) as client:
demoted = await client.patch(
- f"/tenants/{TENANT_A}/members/{member_id}", json={"role": "member"}
+ f"/tenants/{TENANT_A}/members/{first_id}", json={"role": "member"}
)
- owner = await client.patch(
- f"/tenants/{TENANT_A}/members/{owner_id}", json={"role": "member"}
+ last = await client.patch(
+ f"/tenants/{TENANT_A}/members/{last_id}", json={"role": "member"}
)
assert demoted.status_code == 200, demoted.text
assert demoted.json()["role"] == "member"
- assert owner.status_code == 403
+ assert last.status_code == 409, last.text
+ assert last.json()["detail"] == "Cannot demote the last admin"
@pytest.mark.parametrize("method", ["patch", "delete"])
async def test_a_workspace_cannot_demote_or_remove_an_org_admin(
@@ -2004,11 +1971,11 @@ class TestOrganizationAdmins:
organization_id = await self._organization_of(
session_factory, TENANT_A, members={}
)
- owner_id = await _make_member(
- session_factory, name="ws-owner", tenant_id=TENANT_A, role="owner"
+ workspace_admin_id = await _make_member(
+ session_factory, name="ws-admin", tenant_id=TENANT_A, role="admin"
)
admin_id = await _make_member(
- session_factory, name="org-admin", tenant_id=TENANT_A, role="owner"
+ session_factory, name="org-admin", tenant_id=TENANT_A, role="admin"
)
async with session_factory() as session:
session.add(
@@ -2017,7 +1984,7 @@ class TestOrganizationAdmins:
)
)
await session.commit()
- token = _token(owner_id, "[email protected]", TENANT_A)
+ token = _token(workspace_admin_id, "[email protected]", TENANT_A)
async with _client(_app(session_factory), token) as client:
if method == "patch":
@@ -2033,7 +2000,7 @@ class TestOrganizationAdmins:
assert "organization" in response.json()["detail"]
async with session_factory() as session:
membership = await session.get(TenantMember, (TENANT_A, admin_id))
- assert membership is not None and membership.role == "owner"
+ assert membership is not None and membership.role == "admin"
class TestUsageRoute:
@@ -2115,7 +2082,7 @@ class TestUsageRoute:
) -> None:
await _make_tenant(session_factory, TENANT_A)
user_id = await _make_member(
- session_factory, name="usage-naive", tenant_id=TENANT_A, role="owner"
+ session_factory, name="usage-naive", tenant_id=TENANT_A, role="admin"
)
token = _token(user_id, "[email protected]", TENANT_A)
@@ -2133,7 +2100,7 @@ class TestUsageRoute:
) -> None:
await _make_tenant(session_factory, TENANT_A)
user_id = await _make_member(
- session_factory, name="usage-empty", tenant_id=TENANT_A, role="owner"
+ session_factory, name="usage-empty", tenant_id=TENANT_A, role="admin"
)
token = _token(user_id, "[email protected]", TENANT_A)
window = _window()
@@ -2278,7 +2245,7 @@ class TestBudgetRoutes:
_, token = await self._admin(session_factory, "budget-foreign")
await _make_tenant(session_factory, TENANT_B)
their_owner = await _make_member(
- session_factory, name="budget-theirs", tenant_id=TENANT_B, role="owner"
+ session_factory, name="budget-theirs", tenant_id=TENANT_B, role="admin"
)
their_agent, _, _ = await _make_agent_with_key(
session_factory, tenant_id=TENANT_B, owner_id=their_owner
@@ -2382,12 +2349,12 @@ class TestInvitationEmail:
configured, and stands whether or not the e-mail goes out — the response
says which, so the admin knows when to share the link themselves."""
- async def _owner(
+ async def _admin(
self, session_factory: async_sessionmaker[AsyncSession], name: str
) -> str:
await _make_tenant(session_factory, TENANT_A)
user_id = await _make_member(
- session_factory, name=name, tenant_id=TENANT_A, role="owner"
+ session_factory, name=name, tenant_id=TENANT_A, role="admin"
)
return _token(user_id, f"{name}@example.invalid", TENANT_A)
@@ -2398,7 +2365,7 @@ class TestInvitationEmail:
async def test_an_addressed_invitation_is_e_mailed_with_its_link(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- token = await self._owner(session_factory, "sender")
+ token = await self._admin(session_factory, "sender")
mailer = _RecordingMailer()
response = await self._invite(
@@ -2423,7 +2390,7 @@ class TestInvitationEmail:
session_factory: async_sessionmaker[AsyncSession],
caplog: pytest.LogCaptureFixture,
) -> None:
- token = await self._owner(session_factory, "no-relay")
+ token = await self._admin(session_factory, "no-relay")
with caplog.at_level("WARNING", logger="switch_core.gateway.tenants"):
response = await self._invite(
@@ -2440,7 +2407,7 @@ class TestInvitationEmail:
async def test_a_failed_send_still_leaves_a_usable_invitation(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- token = await self._owner(session_factory, "unlucky")
+ token = await self._admin(session_factory, "unlucky")
app = _app(session_factory, mailer=_FailingMailer())
response = await self._invite(app, token, {"email": "[email protected]"})
@@ -2463,7 +2430,7 @@ class TestInvitationEmail:
async def test_a_link_invitation_sends_nothing(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- token = await self._owner(session_factory, "linker")
+ token = await self._admin(session_factory, "linker")
mailer = _RecordingMailer()
response = await self._invite(
@@ -2480,7 +2447,7 @@ class TestInvitationEmail:
async def test_something_that_is_not_an_address_is_refused(
self, session_factory: async_sessionmaker[AsyncSession], email: str
) -> None:
- token = await self._owner(session_factory, "typist")
+ token = await self._admin(session_factory, "typist")
response = await self._invite(
_app(session_factory, mailer=_RecordingMailer()), token, {"email": email}
@@ -2491,7 +2458,7 @@ class TestInvitationEmail:
async def test_the_daily_cap_refuses_before_minting_anything(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- token = await self._owner(session_factory, "prolific")
+ token = await self._admin(session_factory, "prolific")
mailer = _RecordingMailer()
app = _app(session_factory, mailer=mailer, invite_emails_per_day=2)
@@ -2519,7 +2486,7 @@ class TestInvitationEmail:
session.add(operator)
await session.flush()
session.add(
- TenantMember(tenant_id=TENANT_A, user_id=operator.id, role="owner")
+ TenantMember(tenant_id=TENANT_A, user_id=operator.id, role="admin")
)
await session.commit()
operator_id = operator.id
diff --git a/core/tests/switch_core/gateway/test_workos_sign_in_routes.py b/core/tests/switch_core/gateway/test_workos_sign_in_routes.py
index 06883f17b..52e5069c4 100644
--- a/core/tests/switch_core/gateway/test_workos_sign_in_routes.py
+++ b/core/tests/switch_core/gateway/test_workos_sign_in_routes.py
@@ -187,7 +187,7 @@ class TestChangingMembers:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id, organization_id = await _linked(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
workos = _WorkOS({f"user_{bob}": ("om_bob", "viewer")})
workos.signs_in_as = f"user_{ada}"
@@ -216,7 +216,7 @@ class TestChangingMembers:
change that then waits on a sign-in."""
ada, cy = _name("ada"), _name("cy")
tenant_id, organization_id = await _linked(
- session_factory, {ada: ("owner", "org_admin"), cy: ("admin", "org_admin")}
+ session_factory, {ada: ("admin", "org_admin"), cy: ("admin", "org_admin")}
)
workos = _WorkOS({f"user_{cy}": ("om_cy", "org_admin")})
@@ -235,7 +235,7 @@ class TestChangingMembers:
) -> None:
ada, dee = _name("ada"), _name("dee")
tenant_id, organization_id = await _linked(
- session_factory, {ada: ("owner", "org_admin")}
+ session_factory, {ada: ("admin", "org_admin")}
)
async with session_factory() as session:
session.add(
@@ -269,7 +269,7 @@ class TestChangingMembers:
tenant_id, organization_id = await _linked(
session_factory,
{
- ada: ("owner", "org_admin"),
+ ada: ("admin", "org_admin"),
cy: ("admin", "org_admin"),
eli: ("admin", "org_admin"),
fay: ("admin", "org_admin"),
@@ -301,7 +301,7 @@ class TestChangingMembers:
) -> None:
ada = _name("ada")
tenant_id, organization_id = await _linked(
- session_factory, {ada: ("owner", "org_admin")}
+ session_factory, {ada: ("admin", "org_admin")}
)
workos = _WorkOS({f"user_{ada}": ("om_ada", "org_admin")})
@@ -319,7 +319,7 @@ class TestChangingMembers:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id, _ = await _linked(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
workos = _WorkOS({f"user_{bob}": ("om_bob", "viewer")})
@@ -334,7 +334,7 @@ class TestChangingMembers:
) -> None:
ada, cy = _name("ada"), _name("cy")
tenant_id, organization_id = await _linked(
- session_factory, {ada: ("owner", "org_admin"), cy: ("admin", "org_admin")}
+ session_factory, {ada: ("admin", "org_admin"), cy: ("admin", "org_admin")}
)
workos = _WorkOS({f"user_{cy}": ("om_cy", "org_admin")})
workos.signs_in_as = f"user_{ada}"
@@ -360,7 +360,7 @@ class TestOperatorRestoring:
) -> None:
bob = _name("bob")
tenant_id, organization_id = await _linked(
- session_factory, {bob: ("owner", "member")}
+ session_factory, {bob: ("admin", "member")}
)
operator_id = await _operator(session_factory)
workos = _WorkOS({f"user_{bob}": ("om_bob", "viewer")})
@@ -381,7 +381,7 @@ class TestOperatorRestoring:
) -> None:
bob = _name("bob")
tenant_id, organization_id = await _linked(
- session_factory, {bob: ("owner", "member")}
+ session_factory, {bob: ("admin", "member")}
)
operator_id = await _operator(session_factory)
workos = _WorkOS({f"user_{bob}": ("om_bob", "org_admin")})
@@ -404,7 +404,7 @@ class TestSigningIn:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id, _ = await _linked(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
workos = _WorkOS({f"user_{bob}": ("om_bob", "viewer")})
workos.signs_in_as = f"user_{bob}"
@@ -423,7 +423,7 @@ class TestSigningIn:
self, session_factory
) -> None:
ada = _name("ada")
- tenant_id, _ = await _linked(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id, _ = await _linked(session_factory, {ada: ("admin", "org_admin")})
workos = _WorkOS({})
workos.signs_in_as = f"user_{ada}"
workos.organization = "org_SOMEWHERE_ELSE"
@@ -437,7 +437,7 @@ class TestSigningIn:
self, session_factory
) -> None:
ada = _name("ada")
- tenant_id, _ = await _linked(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id, _ = await _linked(session_factory, {ada: ("admin", "org_admin")})
async with _client(
_with(session_factory, _WorkOS({})), ada, tenant_id
@@ -453,10 +453,10 @@ class TestSigningIn:
) -> None:
ada, bob = _name("ada"), _name("bob")
tenant_id, _ = await _linked(
- session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
)
eve = _name("eve")
- unlinked = await _workspace(session_factory, {eve: ("owner", "org_admin")})
+ unlinked = await _workspace(session_factory, {eve: ("admin", "org_admin")})
app = _with(session_factory, _WorkOS({}))
async with _client(app, bob, tenant_id) as client:
@@ -486,7 +486,7 @@ class TestSigningIn:
self, session_factory
) -> None:
ada = _name("ada")
- tenant_id, _ = await _linked(session_factory, {ada: ("owner", "org_admin")})
+ tenant_id, _ = await _linked(session_factory, {ada: ("admin", "org_admin")})
app = _with(session_factory, _WorkOS({}))
app.state.workos_sign_in = None
diff --git a/core/tests/switch_core/gateway/test_workspace_services.py b/core/tests/switch_core/gateway/test_workspace_services.py
index c9ebe02c2..049f31db8 100644
--- a/core/tests/switch_core/gateway/test_workspace_services.py
+++ b/core/tests/switch_core/gateway/test_workspace_services.py
@@ -179,15 +179,14 @@ class TestWhoMayCall:
[
("member", "user", 403),
("admin", "user", 200),
- ("owner", "user", 200),
("member", "admin", 200),
# The operator may enter any workspace, on `platform_access`,
# which the workspace's audit log records.
(None, "admin", 200),
],
- ids=["member", "admin", "owner", "operator-as-member", "operator-not-a-member"],
+ ids=["member", "admin", "operator-as-member", "operator-not-a-member"],
)
- async def test_only_admins_owners_and_the_operator(
+ async def test_only_admins_and_the_operator(
self, harness: Harness, member_role, user_role, expected
) -> None:
user = await _person(
diff --git a/core/tests/switch_core/management/test_my_context.py b/core/tests/switch_core/management/test_my_context.py
index 547ef7c69..dcf202f52 100644
--- a/core/tests/switch_core/management/test_my_context.py
+++ b/core/tests/switch_core/management/test_my_context.py
@@ -353,12 +353,12 @@ async def test_an_admin_is_told_so(harness: Harness, client: httpx.AsyncClient)
async with harness.session_factory() as session:
membership = await session.get(TenantMember, (TENANT_ZERO_ID, ada_id))
assert membership is not None
- membership.role = "owner"
+ membership.role = "admin"
await session.commit()
person = (await _context(client, buddy_id, key))["person"]
- assert person["workspace_role"] == "owner"
+ assert person["workspace_role"] == "admin"
assert person["workspace_admin"] is True
diff --git a/core/tests/switch_core/test_authz.py b/core/tests/switch_core/test_authz.py
index 092720a68..d0dfef579 100644
--- a/core/tests/switch_core/test_authz.py
+++ b/core/tests/switch_core/test_authz.py
@@ -11,7 +11,6 @@ from switch_core.authz import (
can_delete_room_document,
can_manage,
can_unlink_from_room,
- owns_tenant,
require,
require_manage,
require_visibility_change,
@@ -114,7 +113,7 @@ class TestCanManage:
class TestAdministersTenant:
"""`administers_tenant` is the one function allowed to turn a role into
the admin bit (`authz.py` module docstring) — the operator bypass and the
- per-tenant `owner`/`admin` membership role, combined."""
+ per-tenant `admin` membership role, combined."""
def test_operator_administers_regardless_of_tenant_role(self) -> None:
assert administers_tenant(
@@ -124,14 +123,18 @@ class TestAdministersTenant:
is_operator=True, tenant_role="member", organization_role=None
)
- def test_owner_or_admin_membership_administers(self) -> None:
- assert administers_tenant(
- is_operator=False, tenant_role="owner", organization_role=None
- )
+ def test_admin_membership_administers(self) -> None:
assert administers_tenant(
is_operator=False, tenant_role="admin", organization_role=None
)
+ def test_owner_is_no_longer_an_admin_role(self) -> None:
+ """`owner` merged into `admin`; a stray `owner` string must not
+ grant anything."""
+ assert not administers_tenant(
+ is_operator=False, tenant_role="owner", organization_role=None
+ )
+
def test_plain_member_does_not_administer(self) -> None:
assert not administers_tenant(
is_operator=False, tenant_role="member", organization_role=None
@@ -159,39 +162,6 @@ class TestAdministersTenant:
)
-class TestOwnsTenant:
- """`owns_tenant` is the narrower bit: who may move the ownership set,
- which is not everyone who may administer the workspace."""
-
- def test_operator_owns_regardless_of_tenant_role(self) -> None:
- assert owns_tenant(is_operator=True, tenant_role=None)
- assert owns_tenant(is_operator=True, tenant_role="member")
-
- def test_owner_membership_owns(self) -> None:
- assert owns_tenant(is_operator=False, tenant_role="owner")
-
- def test_admin_membership_administers_but_does_not_own(self) -> None:
- """The whole point of there being two functions: an admin who also
- owned could take the workspace from its owner one safe-looking
- request at a time."""
- assert administers_tenant(
- is_operator=False, tenant_role="admin", organization_role=None
- )
- assert not owns_tenant(is_operator=False, tenant_role="admin")
-
- def test_organization_admin_does_not_own(self) -> None:
- """`org_admin` is admin-level in each workspace of its organization:
- it administers them but does not move their ownership set."""
- assert administers_tenant(
- is_operator=False, tenant_role=None, organization_role="org_admin"
- )
- assert not owns_tenant(is_operator=False, tenant_role=None)
-
- def test_plain_member_and_no_membership_do_not_own(self) -> None:
- assert not owns_tenant(is_operator=False, tenant_role="member")
- assert not owns_tenant(is_operator=False, tenant_role=None)
-
-
class TestCanUnlinkFromRoom:
def test_those_taking_part_and_admins_may(self) -> None:
assert can_unlink_from_room(ALICE, takes_part=True)
diff --git a/core/tests/switch_core/test_migration_merge_owner_into_admin.py b/core/tests/switch_core/test_migration_merge_owner_into_admin.py
new file mode 100644
index 000000000..2762d4c35
--- /dev/null
+++ b/core/tests/switch_core/test_migration_merge_owner_into_admin.py
@@ -0,0 +1,88 @@
+"""`a3c5e7f9b1d2` turns every workspace owner into an admin.
+
+Seeds an `owner` membership and an `owner` invitation one revision short,
+runs the revision, and checks both became `admin` and that `owner` is no
+longer accepted.
+"""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy import text
+from sqlalchemy.exc import IntegrityError
+
+from tests.switch_core.test_migration_operator_owns_tenant_zero import (
+ _drop_fixture,
+ _fixture_engine,
+ _upgrade_to,
+)
+
+_PRE_MIGRATION_REVISION = "f68b679599ab"
+_MIGRATION_UNDER_TEST = "a3c5e7f9b1d2"
+_TENANT_ZERO_ID = "00000000-0000-0000-0000-000000000000"
+
+
+async def test_owners_become_admins_and_owner_is_refused(postgres_url: str) -> None:
+ engine = await _fixture_engine(postgres_url)
+ try:
+ async with engine.begin() as connection:
+ await connection.run_sync(_upgrade_to(_PRE_MIGRATION_REVISION))
+
+ async with engine.begin() as connection:
+ for user in ("ada", "bob"):
+ await connection.execute(
+ text(
+ f"""
+ INSERT INTO users (id, name, email, role, password_hash, metadata)
+ VALUES ('{user}', '{user}', '{user}@example.com', 'user',
+ 'bcrypt-hash', NULL)
+ """
+ )
+ )
+ await connection.execute(
+ text(
+ f"""
+ INSERT INTO tenant_members (tenant_id, user_id, role) VALUES
+ ('{_TENANT_ZERO_ID}', 'ada', 'owner'),
+ ('{_TENANT_ZERO_ID}', 'bob', 'member')
+ """
+ )
+ )
+ await connection.execute(
+ text(
+ f"""
+ INSERT INTO invitations (id, tenant_id, role, token_hash,
+ expires_at, uses_remaining, created_by)
+ VALUES ('inv', '{_TENANT_ZERO_ID}', 'owner', 'hash',
+ now() + interval '1 day', 1, 'ada')
+ """
+ )
+ )
+
+ async with engine.begin() as connection:
+ await connection.run_sync(_upgrade_to(_MIGRATION_UNDER_TEST))
+
+ async with engine.connect() as connection:
+ members = {
+ row.user_id: row.role
+ for row in await connection.execute(
+ text("SELECT user_id, role FROM tenant_members")
+ )
+ }
+ invitation = await connection.scalar(
+ text("SELECT role FROM invitations WHERE id = 'inv'")
+ )
+
+ with pytest.raises(IntegrityError):
+ async with engine.begin() as connection:
+ await connection.execute(
+ text(
+ "UPDATE tenant_members SET role = 'owner' WHERE user_id = 'bob'"
+ )
+ )
+ finally:
+ await engine.dispose()
+ await _drop_fixture(postgres_url)
+
+ assert members == {"ada": "admin", "bob": "member"}
+ assert invitation == "admin"
diff --git a/core/tests/switch_core/test_organization_mirror_apply.py b/core/tests/switch_core/test_organization_mirror_apply.py
index 3dd1e086f..ad08be93f 100644
--- a/core/tests/switch_core/test_organization_mirror_apply.py
+++ b/core/tests/switch_core/test_organization_mirror_apply.py
@@ -105,7 +105,7 @@ class _World:
owner: async_sessionmaker[AsyncSession],
*,
bea_role: str = "org_admin",
- ada_owns_joined: bool = False,
+ ada_administers_joined: bool = False,
) -> _World:
world = cls(_id("org"), _id("joined"), _id("reached"))
async with owner() as session:
@@ -155,13 +155,13 @@ class _World:
TenantMember(
tenant_id=world.joined,
user_id=world.ada,
- role="owner" if ada_owns_joined else "member",
+ role="admin" if ada_administers_joined else "member",
)
)
- if not ada_owns_joined:
+ if not ada_administers_joined:
session.add(
TenantMember(
- tenant_id=world.joined, user_id=world.bea, role="owner"
+ tenant_id=world.joined, user_id=world.bea, role="admin"
)
)
for tenant_id in (world.joined, world.reached):
@@ -373,11 +373,11 @@ class TestConflicts:
},
) in await _organization_events(owner, world.organization_id)
- async def test_a_workspace_left_with_no_owner_is_recorded(
+ async def test_a_workspace_left_with_no_admin_is_recorded(
self, rls_harness: RLSHarness
) -> None:
owner = rls_harness.owner
- world = await _World.make(owner, ada_owns_joined=True)
+ world = await _World.make(owner, ada_administers_joined=True)
await _apply(rls_harness, world, None)
@@ -387,7 +387,7 @@ class TestConflicts:
OrganizationAuditAction.DIRECTORY_CONFLICT,
{
"source": "directory_event",
- "kind": "workspace_left_without_owner",
+ "kind": "workspace_left_without_admin",
"workspace": world.joined,
},
) in await _organization_events(owner, world.organization_id)
@@ -426,10 +426,10 @@ class TestARetryAfterAFailure:
async def test_finds_the_workspaces_left_and_their_conflicts_recorded(
self, rls_harness: RLSHarness, monkeypatch: pytest.MonkeyPatch
) -> None:
- """Ada is the only owner of `joined` and owns an agent there; a second
+ """Ada is the only admin of `joined` and owns an agent there; a second
workspace she is in has a busy connection the first time."""
owner = rls_harness.owner
- world = await _World.make(owner, ada_owns_joined=True)
+ world = await _World.make(owner, ada_administers_joined=True)
await _agent(owner, world.joined, world.ada)
busy = _id("busy")
async with owner() as session:
@@ -468,6 +468,6 @@ class TestARetryAfterAFailure:
]
assert sorted(conflicts) == [
"agents_left_with_owner",
- "workspace_left_without_owner",
+ "workspace_left_without_admin",
]
assert await _role(owner, world.organization_id, world.ada) is None
diff --git a/core/tests/switch_core/test_seed_admin_membership.py b/core/tests/switch_core/test_seed_admin_membership.py
index 554d3d68c..fcf0ccf79 100644
--- a/core/tests/switch_core/test_seed_admin_membership.py
+++ b/core/tests/switch_core/test_seed_admin_membership.py
@@ -102,7 +102,7 @@ class TestSeedingRepairsTheAdmin:
user_id = await _admin_id(session_factory)
assert await _memberships(session_factory, user_id) == [
- (TENANT_ZERO_ID, "owner")
+ (TENANT_ZERO_ID, "admin")
]
async def test_a_stranded_admin_is_rejoined_on_the_next_boot(
@@ -118,7 +118,7 @@ class TestSeedingRepairsTheAdmin:
await _seed_admin_user(session_factory, UserStore(), _config())
assert await _memberships(session_factory, user_id) == [
- (TENANT_ZERO_ID, "owner")
+ (TENANT_ZERO_ID, "admin")
]
async def test_the_repair_is_reported_loudly(
@@ -155,7 +155,7 @@ class TestSeedingRepairsTheAdmin:
await _seed_admin_user(session_factory, UserStore(), _config())
assert await _memberships(session_factory, user_id) == [
- (TENANT_ZERO_ID, "owner")
+ (TENANT_ZERO_ID, "admin")
]
diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yaml
index 2b3f0edfd..171c6ab76 100644
--- a/deploy/remote/helm/switch/values.yaml
+++ b/deploy/remote/helm/switch/values.yaml
@@ -488,7 +488,7 @@ switchCore:
# The From address, e.g. "Switch <invites@your-domain>".
from: ""
# Addressed invitations one workspace may send per 24 hours. With sign-up
- # open anyone can own a workspace, so this keeps the relay from being used
+ # open anyone can create a workspace, so this keeps the relay from being used
# to mail arbitrary addresses. Operators are exempt.
emailsPerDayPerWorkspace: 50
# Public origin every distributed messaging app (Slack, Discord, Teams,
diff --git a/docs/design/service-connections-v2.md b/docs/design/service-connections-v2.md
index f240faf01..4c5864bd4 100644
--- a/docs/design/service-connections-v2.md
+++ b/docs/design/service-connections-v2.md
@@ -283,7 +283,7 @@ disconnecting still works. A slug outside the catalog stops the server.
## Switching a service on for a workspace
A workspace admin switches each catalog service on or off for the workspace
-(`GET` and `PUT /gateway/workspace/services[/{service}]`, admins and owners,
+(`GET` and `PUT /gateway/workspace/services[/{service}]`, admins only,
and the operator in a workspace they belong to). A service with no setting
takes the workspace's default, `tenants.services_on_by_default`: off for every
workspace made since services started off, so a new workspace has none until
diff --git a/docs/design/switch-trust-guardrails-v1.md b/docs/design/switch-trust-guardrails-v1.md
index 98c7f8f38..41a655d02 100644
--- a/docs/design/switch-trust-guardrails-v1.md
+++ b/docs/design/switch-trust-guardrails-v1.md
@@ -288,7 +288,7 @@ apps" and "Full admin interface" — not a separate view, since there's little
enough here to configure that a full page would be a detour rather than a
destination. Gated on the connected server's reported `user.role === "admin"`
directly — not the broader `administersWorkspaceInScope()` helper, which also
-admits a plain workspace owner and would be too wide for a deployment-level
+admits a plain workspace admin and would be too wide for a deployment-level
setting — and hidden entirely for anyone else, since there's nothing read-only
to show a non-operator. Labeled "Switch Trust Endpoint", "Guardrails Policy
ID" and "Switch Trust API key" rather than the gateway's own field names, to
diff --git a/docs/old/GATEWAY_OIDC_SETUP.md b/docs/old/GATEWAY_OIDC_SETUP.md
index 1eea74af8..b89b13871 100644
--- a/docs/old/GATEWAY_OIDC_SETUP.md
+++ b/docs/old/GATEWAY_OIDC_SETUP.md
@@ -211,7 +211,7 @@ An invitation addressed to an e-mail can be accepted only by someone signed in
with that address. Each workspace may send at most
`GATEWAY_INVITE_EMAILS_PER_DAY` addressed invitations in 24 hours; past that
the dashboard asks the admin to try tomorrow or share a link. This matters
-with `open` sign-up, where anyone can own a workspace and would otherwise be
+with `open` sign-up, where anyone can create a workspace and would otherwise be
able to use your relay to mail any address. Operators are exempt, and link
invitations are not counted.
diff --git a/docs/old/multi-tenancy-phase1-db.md b/docs/old/multi-tenancy-phase1-db.md
index 8c5ea27ea..3093bd906 100644
--- a/docs/old/multi-tenancy-phase1-db.md
+++ b/docs/old/multi-tenancy-phase1-db.md
@@ -82,7 +82,9 @@ than no column — it reads as a guarantee the code does not make.
`role` is a checked string rather than an enum type, matching how `users.role`
is already stored. Phase 2 owns making these roles mean something; Phase 1 only
-records them so the migration loses no information.
+records them so the migration loses no information. `owner` has since merged
+into `admin` (migration `a3c5e7f9b1d2`), and the check now allows only `admin`
+and `member`.
## Which tables are scoped
diff --git a/docs/old/multi-tenancy-phase2-tenants.md b/docs/old/multi-tenancy-phase2-tenants.md
index e9b53b783..d6fb55906 100644
--- a/docs/old/multi-tenancy-phase2-tenants.md
+++ b/docs/old/multi-tenancy-phase2-tenants.md
@@ -18,7 +18,11 @@ document assumes its vocabulary and does not repeat it.
- `tenants` — `id`, `slug`, `name`, `created_at`. Nothing else.
- `tenant_members` — `(tenant_id, user_id)` as the primary key, plus `role`
- (`owner` / `admin` / `member`) and `created_at`.
+ (`admin` / `member`) and `created_at`. This phase built it with a third
+ role, `owner`, which differed from `admin` only in who could grant or remove
+ ownership. It has since merged into `admin`: every `owner` row became an
+ `admin` one, and a client that still asks for `owner` gets `admin`. Where
+ this page describes owners below, it records how the phase was built.
- One tenant exists in every deployment: tenant zero, seeded by migration with
slug `default`. Sign-in binds it explicitly rather than by fallback.
- `sole_tenant_id()` raises unless the caller has exactly one membership, and
@@ -186,12 +190,12 @@ this phase must prove it has removed.
- `GET /tenants` — the caller's workspaces: id, slug, name, their role. §7 is
about how this reads across the boundary.
-- `POST /tenants` — create one; the creator becomes `owner` (meaningful only
+- `POST /tenants` — create one; the creator becomes `admin` (meaningful only
once §2 lands). Slug derived from the name; a taken slug is a 409. Bounded —
see below.
- `POST /tenants/{id}/switch` — verify membership, re-mint the cookie.
- `POST /tenants/{id}/invitations`, `GET`, `DELETE …/{token_id}` — mint, list,
- revoke. `owner` and `admin` only.
+ revoke. Admins only.
- `POST /invitations/accept` — accept. The token goes in the body, not the
path: a URL segment ends up in proxy logs, browser history and `Referer`,
and this one is a bearer credential.
@@ -206,9 +210,9 @@ unbounded self-service creation buys steady-state work in the deployment, not
storage. `GATEWAY_MAX_WORKSPACES_PER_USER` is both the
cap and the gate: at the limit `POST /tenants` is a 403, and `0` closes the
route outright. It counts workspaces a person has *created*
-(`users.workspaces_created`), not ones they own: ownership can be handed to a
-second account, so a count of ownership could be reset by creating, handing
-over and stepping down. Being invited into someone else's workspace spends
+(`users.workspaces_created`), not ones they administer: a workspace can be
+handed to another admin, so a count of those could be reset by creating,
+handing over and stepping down. Being invited into someone else's workspace spends
nothing. The check, the creation and the count run under a lock on the
person's `users` row, so concurrent requests cannot all pass a check that only
one of them should.
@@ -216,17 +220,17 @@ Deployment operators are exempt, on the same grounds as every other operator
bypass — this bounds self-service, and an operator provisioning workspaces for
other people is not that.
-**A workspace must always have an owner.** Removing or demoting the last one
-is refused; deletion of a workspace is not in this phase, so there is no
-legitimate path to an ownerless one.
+**A workspace must always have an admin.** Removing or demoting the last one
+is refused, and so is deleting the account of the last admin of a workspace
+other people are in. The check locks the workspace's admin rows before it
+counts them, so two admins demoting each other at once cannot both pass it.
-**Who owns a workspace is decided by its owners, not by its admins.** Granting
-`owner`, changing an owner's role, removing an owner, and minting an `owner`
-invitation are all owner-only, over and above the `owner`/`admin` gate on the
-route. The last-owner rule above cannot substitute for this, because it cannot
-see a sequence: an admin who promotes themselves first leaves two owners
-standing at every subsequent step, so each individual request passes while the
-three together take the workspace.
+This phase first built a separate `owner` role on top: granting `owner`,
+changing an owner's role and removing an owner were owner-only, because an
+admin who promoted themselves first could take the workspace one
+safe-looking request at a time. That distinction was dropped when `owner`
+merged into `admin`: every admin now manages every member, other admins
+included, and the last-admin rule is what keeps a workspace runnable.
**Invitations are a table, and a link that grants membership is a credential.**
`id`, `tenant_id`, `role`, `email` (null for a link), `expires_at`,
@@ -309,8 +313,8 @@ session is different in kind, not in degree.
## 8. Becoming an administrator
-**A workspace someone creates.** Solved by §5 plus §2: the creator is `owner`,
-and once §2 lands that means something.
+**A workspace someone creates.** Solved by §5 plus §2: the creator is its
+admin, and once §2 lands that means something.
**A deployment that already exists** — `CHOO-2726`. This is less broken than
previously reported, and the earlier account of it was wrong: identity linking
@@ -389,6 +393,6 @@ many a deployment ends up carrying.
- An invitation can be minted, accepted once, and revoked before use.
- A domain cannot be claimed by two tenants, nor by an account that cannot
prove it uses it.
-- The last owner of a workspace cannot be removed or demoted.
+- The last admin of a workspace cannot be removed or demoted.
- A person at the workspace limit is refused a new one and nothing is
provisioned for them, and a limit of zero closes the route.
diff --git a/docs/old/multi-tenancy.md b/docs/old/multi-tenancy.md
index d4ca19351..c33e22fc3 100644
--- a/docs/old/multi-tenancy.md
+++ b/docs/old/multi-tenancy.md
@@ -90,7 +90,7 @@ tenants
id, slug (unique), name, plan, status, created_at, deleted_at
tenant_members
- tenant_id, user_id, role (owner|admin|member), created_at
+ tenant_id, user_id, role (admin|member), created_at
primary key (tenant_id, user_id)
```
@@ -325,7 +325,7 @@ Not part of the tenant model, but on its critical path:
- **Tenant id on every log line and error report.** Retrofitting this is
miserable, and without it "is this one customer or everyone?" is
unanswerable.
-- **Per-tenant roles** (owner/admin/member) replacing reliance on the global
+- **Per-tenant roles** (admin/member) replacing reliance on the global
`admin` flag.
- **Audit log** — who invited whom, who connected Slack, who deleted an agent.
- **Support access** — an explicit impersonation path with an audit trail.
diff --git a/gateway/src/App.test.tsx b/gateway/src/App.test.tsx
index 52c1d023a..5d70b5af2 100644
--- a/gateway/src/App.test.tsx
+++ b/gateway/src/App.test.tsx
@@ -10,7 +10,7 @@ const acme: TenantMembership = {
id: "t1",
slug: "acme",
name: "Acme",
- role: "owner",
+ role: "admin",
organization_role: "org_admin",
organization_id: "o1",
};
diff --git a/gateway/src/data/api.test.ts b/gateway/src/data/api.test.ts
index 3c2a638c4..6278e8b48 100644
--- a/gateway/src/data/api.test.ts
+++ b/gateway/src/data/api.test.ts
@@ -13,9 +13,7 @@ import {
describe("errorText", () => {
it("returns a string detail as is", () => {
- expect(errorText("Only a workspace owner may grant ownership", "x")).toBe(
- "Only a workspace owner may grant ownership",
- );
+ expect(errorText("Cannot demote the last admin", "x")).toBe("Cannot demote the last admin");
});
it("joins validation messages", () => {
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index 7c9f29400..2e07be5c1 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -1139,7 +1139,7 @@ export interface AuthConfig {
// ── Session and workspaces ──────────────────────────────────────────────────
-export type TenantRole = "owner" | "admin" | "member";
+export type TenantRole = "admin" | "member";
export type OrganizationRole = "org_admin" | "member";
@@ -1374,7 +1374,7 @@ export async function removeOrganizationMember(
// Mirrors `OrganizationIssueKind` in core/switch_core/db/audit.py, by hand.
export type OrganizationIssueKind =
| "no_org_admin"
- | "workspace_without_owner"
+ | "workspace_without_admin"
| "agents_without_acting_owner"
| "directory_organization_deleted";
@@ -2292,8 +2292,8 @@ export interface CurrentTenant {
slug: string;
name: string;
role: string;
- // Whether the caller may manage the workspace: an owner or admin
- // membership, or the operator bit.
+ // Whether the caller may manage the workspace: an admin membership,
+ // `org_admin` of its organization, or the operator bit.
administers: boolean;
}
diff --git a/gateway/src/data/sessionState.test.ts b/gateway/src/data/sessionState.test.ts
index beb97c406..1a94a5dca 100644
--- a/gateway/src/data/sessionState.test.ts
+++ b/gateway/src/data/sessionState.test.ts
@@ -8,7 +8,6 @@ import {
deliveryNotice,
inviteTokenFrom,
inviteUrl,
- ownsTenant,
readPendingInvite,
storePendingInvite,
} from "./sessionState";
@@ -58,26 +57,21 @@ describe("appView", () => {
});
});
-describe("canAdminTenant and ownsTenant", () => {
+describe("canAdminTenant", () => {
it("follows the workspace role", () => {
expect(canAdminTenant(session())).toBe(false);
expect(canAdminTenant(session({ tenant: { ...acme, role: "admin" } }))).toBe(true);
- expect(canAdminTenant(session({ tenant: { ...acme, role: "owner" } }))).toBe(true);
- expect(ownsTenant(session({ tenant: { ...acme, role: "admin" } }))).toBe(false);
- expect(ownsTenant(session({ tenant: { ...acme, role: "owner" } }))).toBe(true);
});
- it("grants both to an operator whatever the role", () => {
+ it("is granted to an operator whatever the role", () => {
const operator = session({
user: { id: "u1", name: "Op", email: "[email protected]", is_operator: true },
});
expect(canAdminTenant(operator)).toBe(true);
- expect(ownsTenant(operator)).toBe(true);
});
- it("grants neither with no session or no workspace", () => {
+ it("is not granted with no session or no workspace", () => {
expect(canAdminTenant(null)).toBe(false);
- expect(ownsTenant(null)).toBe(false);
expect(canAdminTenant(session({ tenant: null, state: "needs_workspace" }))).toBe(false);
});
});
diff --git a/gateway/src/data/sessionState.ts b/gateway/src/data/sessionState.ts
index 2b5ffeb4b..35d90aa8d 100644
--- a/gateway/src/data/sessionState.ts
+++ b/gateway/src/data/sessionState.ts
@@ -19,13 +19,13 @@ export function appView(session: Session | null, pendingInvite: string | null):
}
/** May this session administer the workspace it is in? The operator bit, or
- * owner/admin of the current workspace — the same rule the server applies
+ * admin of the current workspace — the same rule the server applies
* (`require_tenant_admin`). */
export function canAdminTenant(session: Session | null): boolean {
if (session === null) return false;
if (session.user.is_operator) return true;
const role = session.tenant?.role;
- return role === "owner" || role === "admin";
+ return role === "admin";
}
/** Is this session an admin of the current workspace's organization? The
@@ -74,14 +74,6 @@ export function inviteUrl(origin: string, token: string): string {
return `${origin}/invite#token=${encodeURIComponent(token)}`;
}
-/** May this session change who owns the workspace — grant or revoke the
- * owner role? Narrower than `canAdminTenant`, matching the server's
- * `owns_tenant`. */
-export function ownsTenant(session: Session | null): boolean {
- if (session === null) return false;
- return session.user.is_operator || session.tenant?.role === "owner";
-}
-
export interface DeliveryNotice {
severity: "success" | "warning" | "error";
text: string;
diff --git a/gateway/src/pages/organization/OrganizationIssuesNotice.tsx b/gateway/src/pages/organization/OrganizationIssuesNotice.tsx
index 5c47c01c0..36c8458e1 100644
--- a/gateway/src/pages/organization/OrganizationIssuesNotice.tsx
+++ b/gateway/src/pages/organization/OrganizationIssuesNotice.tsx
@@ -8,8 +8,8 @@ function describe(issue: OrganizationIssue): string {
switch (issue.kind) {
case "no_org_admin":
return "Nobody is an admin of this organization. Make one of its members an organization admin below.";
- case "workspace_without_owner":
- return `${workspace} has no owner. Make one of its members owner in that workspace's members.`;
+ case "workspace_without_admin":
+ return `${workspace} has no admin. Make one of its members an admin in that workspace's members.`;
case "agents_without_acting_owner":
return (
`In ${workspace}, these agents are owned by someone who is no longer in the ` +
diff --git a/gateway/src/pages/organization/OrganizationPage.test.tsx b/gateway/src/pages/organization/OrganizationPage.test.tsx
index 1a9631b52..0caca9d27 100644
--- a/gateway/src/pages/organization/OrganizationPage.test.tsx
+++ b/gateway/src/pages/organization/OrganizationPage.test.tsx
@@ -600,7 +600,7 @@ describe("OrganizationPage", () => {
"GET /organizations/current/members": [],
"GET /organizations/current/audit-events": [],
"GET /organizations/current/issues": [
- { kind: "workspace_without_owner", workspace_id: "t1", workspace_name: "Acme", agents: [] },
+ { kind: "workspace_without_admin", workspace_id: "t1", workspace_name: "Acme", agents: [] },
{
kind: "agents_without_acting_owner",
workspace_id: "t1",
@@ -613,7 +613,7 @@ describe("OrganizationPage", () => {
render(<OrganizationPage />);
expect(await screen.findByText("2 things need your attention")).toBeTruthy();
- expect(screen.getByText(/Acme has no owner/)).toBeTruthy();
+ expect(screen.getByText(/Acme has no admin/)).toBeTruthy();
expect(screen.getByText(/reviewer, triage/)).toBeTruthy();
});
diff --git a/gateway/src/pages/organization/WorkspacesSection.tsx b/gateway/src/pages/organization/WorkspacesSection.tsx
index 09da1028a..8ab2fd9c7 100644
--- a/gateway/src/pages/organization/WorkspacesSection.tsx
+++ b/gateway/src/pages/organization/WorkspacesSection.tsx
@@ -160,7 +160,7 @@ function AddWorkspaceDialog({
label="Workspace name"
value={name}
onChange={(e) => setName(e.target.value)}
- helperText="You become its owner. Every organization admin administers it."
+ helperText="You become its admin. Every organization admin administers it."
required
autoFocus
/>
diff --git a/gateway/src/pages/usage/UsagePage.tsx b/gateway/src/pages/usage/UsagePage.tsx
index 9bfa66926..2749d92c5 100644
--- a/gateway/src/pages/usage/UsagePage.tsx
+++ b/gateway/src/pages/usage/UsagePage.tsx
@@ -47,7 +47,7 @@ export default function UsagePage() {
if (!tenant.administers) {
return (
<Alert severity="info">
- Only owners and admins of {tenant.name} can see its usage and budgets.
+ Only admins of {tenant.name} can see its usage and budgets.
</Alert>
);
}
diff --git a/gateway/src/pages/workspace/CreateInvitationDialog.test.tsx b/gateway/src/pages/workspace/CreateInvitationDialog.test.tsx
index 17d2883eb..20709d1f0 100644
--- a/gateway/src/pages/workspace/CreateInvitationDialog.test.tsx
+++ b/gateway/src/pages/workspace/CreateInvitationDialog.test.tsx
@@ -25,7 +25,6 @@ function renderDialog(emailEnabled: boolean) {
<CreateInvitationDialog
open
tenantId="t1"
- isOwner={false}
emailEnabled={emailEnabled}
onClose={() => {}}
onCreated={() => {}}
diff --git a/gateway/src/pages/workspace/CreateInvitationDialog.tsx b/gateway/src/pages/workspace/CreateInvitationDialog.tsx
index 31e1ac5c2..4c0b0fd88 100644
--- a/gateway/src/pages/workspace/CreateInvitationDialog.tsx
+++ b/gateway/src/pages/workspace/CreateInvitationDialog.tsx
@@ -24,7 +24,6 @@ const MAX_INVITATION_USES = 100;
interface Props {
open: boolean;
tenantId: string;
- isOwner: boolean;
emailEnabled: boolean;
onClose: () => void;
onCreated: () => void;
@@ -36,7 +35,6 @@ interface Props {
export default function CreateInvitationDialog({
open,
tenantId,
- isOwner,
emailEnabled,
onClose,
onCreated,
@@ -90,7 +88,7 @@ export default function CreateInvitationDialog({
}, [link]);
const addressed = email.trim() !== "";
- const roles: TenantRole[] = isOwner ? ["member", "admin", "owner"] : ["member", "admin"];
+ const roles: TenantRole[] = ["member", "admin"];
const valid =
Number.isInteger(Number(hours)) && Number(hours) > 0 && Number(hours) <= 8760 &&
Number.isInteger(Number(uses)) && Number(uses) > 0 && Number(uses) <= MAX_INVITATION_USES;
diff --git a/gateway/src/pages/workspace/InvitationsSection.test.tsx b/gateway/src/pages/workspace/InvitationsSection.test.tsx
index 40f78b84a..fe1df9d21 100644
--- a/gateway/src/pages/workspace/InvitationsSection.test.tsx
+++ b/gateway/src/pages/workspace/InvitationsSection.test.tsx
@@ -42,7 +42,7 @@ describe("InvitationsSection", () => {
"/organizations/current": [200, organization(true)],
});
- render(<InvitationsSection tenantId="t1" inOrganization isOwner emailEnabled={false} />);
+ render(<InvitationsSection tenantId="t1" inOrganization emailEnabled={false} />);
expect(await screen.findByText(/only people already in the organization can accept/)).toBeTruthy();
});
@@ -53,7 +53,7 @@ describe("InvitationsSection", () => {
"/organizations/current": [200, organization(false)],
});
- render(<InvitationsSection tenantId="t1" inOrganization isOwner emailEnabled={false} />);
+ render(<InvitationsSection tenantId="t1" inOrganization emailEnabled={false} />);
expect(await screen.findByRole("button", { name: "Invite" })).toBeTruthy();
expect(screen.queryByText(/already in the organization/)).toBeNull();
@@ -62,7 +62,7 @@ describe("InvitationsSection", () => {
it("asks nothing about an organization for a workspace in none", async () => {
const asked = answer({ "/tenants/t1/invitations": [200, []] });
- render(<InvitationsSection tenantId="t1" inOrganization={false} isOwner emailEnabled={false} />);
+ render(<InvitationsSection tenantId="t1" inOrganization={false} emailEnabled={false} />);
expect(await screen.findByRole("button", { name: "Invite" })).toBeTruthy();
expect(asked).not.toContain("/organizations/current");
@@ -75,7 +75,7 @@ describe("InvitationsSection", () => {
"/organizations/current": [500, { detail: "The database is unavailable" }],
});
- render(<InvitationsSection tenantId="t1" inOrganization isOwner emailEnabled={false} />);
+ render(<InvitationsSection tenantId="t1" inOrganization emailEnabled={false} />);
expect(await screen.findByText(/Could not check who can accept an invitation here/)).toBeTruthy();
});
diff --git a/gateway/src/pages/workspace/InvitationsSection.tsx b/gateway/src/pages/workspace/InvitationsSection.tsx
index 3e455ab35..135eb0523 100644
--- a/gateway/src/pages/workspace/InvitationsSection.tsx
+++ b/gateway/src/pages/workspace/InvitationsSection.tsx
@@ -30,12 +30,10 @@ function invitationStatus(inv: Invitation, now: number): string {
export default function InvitationsSection({
tenantId,
inOrganization,
- isOwner,
emailEnabled,
}: {
tenantId: string;
inOrganization: boolean;
- isOwner: boolean;
emailEnabled: boolean;
}) {
const load = useCallback(() => fetchInvitations(tenantId), [tenantId]);
@@ -159,7 +157,6 @@ export default function InvitationsSection({
<CreateInvitationDialog
open={createOpen}
tenantId={tenantId}
- isOwner={isOwner}
emailEnabled={emailEnabled}
onClose={() => setCreateOpen(false)}
onCreated={refetch}
diff --git a/gateway/src/pages/workspace/MembersSection.test.tsx b/gateway/src/pages/workspace/MembersSection.test.tsx
index 342123b52..08740200f 100644
--- a/gateway/src/pages/workspace/MembersSection.test.tsx
+++ b/gateway/src/pages/workspace/MembersSection.test.tsx
@@ -42,7 +42,7 @@ describe("MembersSection", () => {
user_id: "u4",
name: "Dee",
- role: "owner",
+ role: "admin",
organization_role: "org_admin",
}),
]),
@@ -50,10 +50,10 @@ describe("MembersSection", () => {
),
);
- render(<MembersSection tenantId="t1" selfId="u1" canAdmin isOwner />);
+ render(<MembersSection tenantId="t1" selfId="u1" canAdmin />);
expect(await screen.findByText("Org Admin, via organization")).toBeTruthy();
- expect(screen.getByText("Owner · Org Admin")).toBeTruthy();
+ expect(screen.getByText("Admin · Org Admin")).toBeTruthy();
expect(screen.queryByLabelText("Remove [email protected]")).toBeNull();
expect(screen.queryByLabelText("Role for [email protected]")).toBeNull();
expect(screen.queryByLabelText("Remove [email protected]")).toBeNull();
diff --git a/gateway/src/pages/workspace/MembersSection.tsx b/gateway/src/pages/workspace/MembersSection.tsx
index a0c934e20..d223a9af8 100644
--- a/gateway/src/pages/workspace/MembersSection.tsx
+++ b/gateway/src/pages/workspace/MembersSection.tsx
@@ -30,18 +30,17 @@ interface Props {
tenantId: string;
selfId: string;
canAdmin: boolean;
- isOwner: boolean;
}
-/** An admin may manage members and admins; only an owner may grant the owner
- * role or touch an existing owner. The server enforces the same, and refuses
- * the last owner — its message is shown as is.
+/** An admin may manage every member, other admins included. The server
+ * enforces the same, and refuses to demote or remove the last admin — its
+ * message is shown as is.
*
* An organization admin administers every workspace of the organization, so
* their row here is read-only: the role comes from the organization, and is
* changed on its page. One with no membership of their own here is listed
* "via the organization". */
-export default function MembersSection({ tenantId, selfId, canAdmin, isOwner }: Props) {
+export default function MembersSection({ tenantId, selfId, canAdmin }: Props) {
const load = useCallback(() => fetchMembers(tenantId), [tenantId]);
const { data: members, error, loading, refetch } = useLoad(load);
const [actionError, setActionError] = useState<string | null>(null);
@@ -67,9 +66,8 @@ export default function MembersSection({ tenantId, selfId, canAdmin, isOwner }:
);
const columns = useMemo<GridColDef<MemberRow>[]>(() => {
- const mayManage = (row: MemberRow) =>
- canAdmin && row.organization_role !== "org_admin" && (isOwner || row.role !== "owner");
- const roles: TenantRole[] = isOwner ? ["owner", "admin", "member"] : ["admin", "member"];
+ const mayManage = (row: MemberRow) => canAdmin && row.organization_role !== "org_admin";
+ const roles: TenantRole[] = ["admin", "member"];
return [
{
field: "name",
@@ -158,7 +156,7 @@ export default function MembersSection({ tenantId, selfId, canAdmin, isOwner }:
) : null,
},
];
- }, [act, busy, canAdmin, isOwner, selfId, tenantId]);
+ }, [act, busy, canAdmin, selfId, tenantId]);
return (
<Stack spacing={1.5}>
diff --git a/gateway/src/pages/workspace/WorkspacePage.tsx b/gateway/src/pages/workspace/WorkspacePage.tsx
index 088b423b0..3f8676839 100644
--- a/gateway/src/pages/workspace/WorkspacePage.tsx
+++ b/gateway/src/pages/workspace/WorkspacePage.tsx
@@ -1,6 +1,5 @@
import { Alert, Box, CircularProgress, Stack, Typography } from "@mui/material";
import { useAuth } from "../../data/AuthContext";
-import { ownsTenant } from "../../data/sessionState";
import InvitationsSection from "./InvitationsSection";
import MembersSection from "./MembersSection";
@@ -8,7 +7,6 @@ export default function WorkspacePage() {
const { session, canAdminTenant } = useAuth();
const tenant = session?.tenant;
if (!tenant) return <CircularProgress />;
- const isOwner = ownsTenant(session);
return (
<Box>
@@ -23,18 +21,16 @@ export default function WorkspacePage() {
tenantId={tenant.id}
selfId={session.user.id}
canAdmin={canAdminTenant}
- isOwner={isOwner}
/>
{canAdminTenant ? (
<InvitationsSection
tenantId={tenant.id}
inOrganization={tenant.organization_id !== null}
- isOwner={isOwner}
emailEnabled={session.invite_email_enabled}
/>
) : (
<Alert severity="info">
- Ask a workspace owner or admin to invite someone.
+ Ask a workspace admin to invite someone.
</Alert>
)}
</Stack>