Skip to content

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

Gateway: the server says what you may do, for every object (CHOO-4072) (#1570)

Christian McDermotta425936d615a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bea89e5fa..7e24241e1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -74,6 +74,26 @@ version of their own to them without also giving them a release of their own.
about an agent's message are still posted for the room.
#### Security
+- **Only the people in a direct or group conversation decide who is in it.**
+ The room routes and the agent tools added agents and people to one from
+ outside it, though its platform fixes its members; a DM the bridge adopted
+ is writable by every member, so anyone could put their own agent in someone
+ else's DM and have it receive their messages. The room routes now refuse
+ adding or removing with a 409, as do `invite_agent_to_room`,
+ `add_users_to_room` and `remove_agent_from_room`, and a template whose new
+ agent joins one is refused before anything is made. Rooms carry
+ `can_change_members`, false for one, and Switch Console no longer offers
+ it. The people in the conversation still invite and remove agents with
+ `!invite-agent` and `!remove-agent`, and a Switch Console chat still
+ changes its own through its chat routes.
+- **Adding to a package takes being able to read what is added.** Only the
+ package owner's reading was checked, and a package lists what it holds to
+ everyone who may read it, so someone who could edit a publicly writable
+ package could add a private reference or document by id and then read it.
+- **A refused agent transfer names the services it uses to its owner only.**
+ An admin who tried to transfer someone's agent was told which of the owner's
+ connections it was granted, which the owner's service access otherwise
+ shows nobody.
- **Sign out of all devices.** Signing out used to clear only that browser's
cookie, so a copied cookie or a browser left signed in elsewhere stayed
valid until it expired. The account menu now has **Sign out of all
@@ -199,6 +219,31 @@ version of their own to them without also giving them a release of their own.
still only needs write access to the room.
#### Added
+- **The gateway says what the caller may do with every object it shows**, so
+ no page works a permission out for itself. Alongside the room, template and
+ agent flags already there:
+ - references, reference types, documents and packages carry `can_edit` and
+ `can_manage`, documents and rooms `can_transfer`, and rooms
+ `can_change_members`;
+ - agents carry `can_edit_options`, `can_rename`, `can_transfer` with
+ `transfer_blocked_reason`, and, on their detail, `can_change_manage_agents`
+ and `can_grant_services`; an agent's sub-agents carry them too;
+ - workspace and organization members carry `can_change_role` and
+ `can_remove`, workspace members `can_receive_transfer`, and organization
+ members `can_grant_org_admin`;
+ - `GET /tenants/current` carries `can_delete` and
+ `can_manage_data_protection` (setting messages to be deleted, listing
+ and erasing people: its admins by their own membership), and
+ `GET /organizations/current` `administers` and `can_manage_members`;
+ - API keys carry `can_reveal` and `can_delete`, machines `can_edit` and
+ `can_remove`, managed agents `can_edit` and `can_delete`;
+ - messaging apps carry `can_manage` and `can_delete`, installs
+ `can_disconnect`, claims on a chat account `can_unlink`, connections
+ `can_revoke`, and the operator's list of accounts `can_delete`.
+ Each is decided by the same rule its route enforces, and a test holds every
+ flag to its route for each kind of caller. A flag says whether the caller
+ may, not whether there is anything left to do: an ended install or a revoked
+ machine says that by its own status.
- **The server's administrator can delete someone's account.** The Users page
has a Delete action (`DELETE /users/{id}`) that removes the account in every
workspace, with the same refusals as deleting your own. Administrator
@@ -400,6 +445,22 @@ version of their own to them without also giving them a release of their own.
compares it only when someone signs in.
#### Changed
+- **Admins step down and leave from their own row.** The workspace and
+ organization members pages offer changing your own role and leaving, while
+ another admin remains; the last one is refused, as before. Leaving the
+ workspace your session is on moves the session to your other workspace, or
+ to none, as deleting a workspace does, rather than leaving it on one you
+ left.
+- **A room's own document is changed in its room.** `PATCH` and
+ `DELETE /documents/{id}` refuse one with a 409, and its library flags say no.
+- **Revoking an invitation that has already ended is refused** with a 409,
+ rather than rewriting when, and by whom, it ended.
+- **An addressing rule that can never let anyone in is refused when it is
+ saved**, with a 422 naming the rule and why: one that names no rooms or no
+ room groups, or lets in no people, no agents, not the owner and not the
+ platform. Next to other rules it changed nothing while looking as if it did,
+ and a policy of only such rules shut the agent off, its owner included.
+ Policies already saved are left as they are.
- **Removing a member hands what they own to an admin.** Their rooms,
packages, references, reference types, library documents and templates in
that workspace stayed theirs, though they could no longer reach them, and
@@ -731,6 +792,20 @@ version of their own to them without also giving them a release of their own.
token again; revocation is still checked on every request.
#### Fixed
+- **Two organization admins demoting or removing each other at once** could
+ leave the refused one without their keys and connections in the workspaces
+ they reached as an organization admin: those were taken away before the
+ last-admin check that refused the change. The check is now made, under a
+ lock held until the change is saved, before anything is taken away.
+- **Deleting an API key an agent still signs in with** failed with a 500. It
+ is refused with a 409 that says to delete the agent; once the agent is gone,
+ its leftover key can be deleted.
+- **Attaching a document or package that is already attached**, to a room or
+ a package, failed with a 500. It now changes nothing, as for a reference,
+ and attaching anything a room already has is no longer reported as a new
+ attachment.
+- **A package in a room's list said the caller may open it** only on that
+ list; every route now works it out from the package's read rule.
- **Stable Switch Console can link chat accounts again.** Since links have to
be confirmed from the account with a one-time code, a claim from a Console
that cannot show the code was refused with "Update Switch Console", and no
@@ -2749,6 +2824,10 @@ version of their own to them without also giving them a release of their own.
agent"; it was the only place Console showed that name.
#### Fixed
+- **Direct and group conversations no longer offer adding or removing
+ agents**, in a room's side column, the sidebar or an agent's "Add to rooms",
+ where the server refuses it now that their platform decides who is in them.
+ People in the conversation still use `!invite-agent` and `!remove-agent`.
- **Antigravity runs Google's own `agy` CLI, on Windows too.** Switch Console
finds `agy` (including `%LOCALAPPDATA%\agy\bin` on Windows), installs it with
Google's installers, runs sessions with `agy acp`, and checks the sign-in you
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.rooms.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.rooms.test.ts
index 33b9e5332..e97f436e3 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.rooms.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.rooms.test.ts
@@ -159,8 +159,33 @@ describe('what the server says the caller may do', () => {
jsonResponse({ ...ROOM, can_write: true, can_manage: false })
);
const room = await fetchRoomDetail(SERVER, 'room-1');
- // A server from before detaching had its own rule: it took write access.
- expect(room.serverPermissions).toEqual({ canWrite: true, canManage: false, canUnlink: true });
+ // A server from before detaching, or before fixed membership, had its own
+ // rule for each: it took write access.
+ expect(room.serverPermissions).toEqual({
+ canWrite: true,
+ canChangeMembers: true,
+ canManage: false,
+ canUnlink: true,
+ });
+ });
+
+ it('carries that a direct conversation’s members are not the caller’s to change', async () => {
+ fetchMock.mockImplementation(async () =>
+ jsonResponse({
+ ...ROOM,
+ channel_type: 'direct',
+ can_write: true,
+ can_change_members: false,
+ can_manage: true,
+ can_unlink: true,
+ })
+ );
+ expect((await fetchRoomDetail(SERVER, 'room-1')).serverPermissions).toEqual({
+ canWrite: true,
+ canChangeMembers: false,
+ canManage: true,
+ canUnlink: true,
+ });
});
it('carries who may detach and delete when the server says', async () => {
@@ -169,6 +194,7 @@ describe('what the server says the caller may do', () => {
);
expect((await fetchRoomDetail(SERVER, 'room-1')).serverPermissions).toEqual({
canWrite: true,
+ canChangeMembers: true,
canManage: false,
canUnlink: false,
});
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 f8a359f92..5eef71ebe 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
@@ -3311,6 +3311,7 @@ type RoomSummaryJson = {
write_visibility?: string;
/** What the caller may do with the room, decided by the routes' own rules; absent from an older server. */
can_write?: boolean;
+ can_change_members?: boolean;
can_manage?: boolean;
can_unlink?: boolean;
group_id?: string | null;
@@ -3346,6 +3347,8 @@ function mapRoomSummary(r: RoomSummaryJson): RemoteRoomSummary {
? {
serverPermissions: {
canWrite: r.can_write,
+ // Who is in a room took write access until the server said otherwise.
+ canChangeMembers: r.can_change_members ?? r.can_write,
canManage: r.can_manage,
// Detaching took write access until the server said otherwise.
canUnlink: r.can_unlink ?? r.can_write,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
index e6b86d166..855e4b10c 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
@@ -28,6 +28,7 @@ import { AgentStatusSlot } from './agent-status-slot';
import { DiscoveryFailureIndicator } from './discovery-failure-indicator';
import { MigrationProblemIndicator } from './migration-problem-indicator';
import { SidebarItemMiniButton, SidebarMenuAction, SidebarMenuRow } from './sidebar-primitives';
+import { mayChangeRoomMembers } from './sidebar-room-grouping';
import { depthIndent, roomAgentGroupKey } from './sidebar-store';
/**
@@ -211,12 +212,14 @@ export const RoomAgentRow = observer(function RoomAgentRow({
)}
</SidebarMenuRow>
</ContextMenuTrigger>
- <ContextMenuContent>
- <ContextMenuItem variant="destructive" onClick={removeFromRoom}>
- <DoorOpen className="size-4" />
- Remove from this room
- </ContextMenuItem>
- </ContextMenuContent>
+ {mayChangeRoomMembers(roomId) && (
+ <ContextMenuContent>
+ <ContextMenuItem variant="destructive" onClick={removeFromRoom}>
+ <DoorOpen className="size-4" />
+ Remove from this room
+ </ContextMenuItem>
+ </ContextMenuContent>
+ )}
</ContextMenu>
);
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsx
index 2113146a0..e0c84cafa 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsx
@@ -16,6 +16,7 @@ import {
isRoomNameKnown,
isRoomViewActive,
deleteRoomAction,
+ mayChangeRoomMembers,
openRoomInMessagingApp,
openRoomView,
RoomRow,
@@ -166,7 +167,11 @@ export const RoomTree = observer(function RoomTree() {
? () => openRoomInMessagingApp(roomKey)
: null
}
- onAddAgent={() => showAddAgentsToRoomModal({ roomId: roomKey })}
+ onAddAgent={
+ mayChangeRoomMembers(roomKey)
+ ? () => showAddAgentsToRoomModal({ roomId: roomKey })
+ : null
+ }
onDelete={deleteRoomAction(roomKey, showDeleteRoomModal)}
/>
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx
index 55d596586..ae9046ed8 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx
@@ -70,6 +70,19 @@ export function deleteRoomAction(
return () => showDeleteRoomModal({ workspaceId, roomId: roomKey, roomName: room.name });
}
+/**
+ * Whether the user may add agents to a room and take them out: what the
+ * server says of a room it listed. A direct or group conversation's platform
+ * fixes who is in it. A Console chat follows its own rules, and a room not
+ * listed here is left to the server to answer.
+ */
+export function mayChangeRoomMembers(roomKey: string): boolean {
+ const workspaceId = switchRoomsStore.roomWorkspaceId(roomKey);
+ const room = switchRoomsStore.roomSummaryById(roomKey);
+ if (!workspaceId || !room || room.isConsoleChat) return true;
+ return switchRoomsStore.roomPermissions(workspaceId, room).canChangeMembers;
+}
+
/** Show a room's conversation in the main panel (no-op for Unassigned, which
* is a bucket rather than a real room). */
export function openRoomView(roomKey: string): void {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
index 455b27087..176b7890e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
@@ -62,11 +62,16 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({
// Every room the server let us see, not only the ones this user created: an
// agent's usefulness is mostly in rooms someone else set up, and a picker that
// omitted them made those rooms unreachable from here entirely.
- // Only rooms the user may add to: a chat they manage, a room they own or administer.
+ // Only rooms the user may add to: a chat they manage, a room they own or
+ // administer whose members are not fixed by its platform.
const candidates: Candidate[] = useReadableRoomsInWorkspace(workspaceId)
.filter((room) => !alreadyIn.has(room.id) && !selected.some((s) => s.id === room.id))
.filter((room) =>
- mayAddToRoom(chatsStore.chat(room.id), switchRoomsStore.canDeleteRoom(workspaceId, room))
+ mayAddToRoom(
+ chatsStore.chat(room.id),
+ switchRoomsStore.canDeleteRoom(workspaceId, room) &&
+ switchRoomsStore.roomPermissions(workspaceId, room).canChangeMembers
+ )
)
.map((room) => ({ id: room.id, name: room.name, bridgeType: room.bridgeType }));
const nothingToAdd = candidates.length === 0 && selected.length === 0;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
index 636bc7575..f55584b8e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
@@ -75,6 +75,7 @@ const ChatConfiguration = observer(function ChatConfiguration({
room={detail.data}
permissions={{
canWrite: chat.canManage,
+ canChangeMembers: chat.canManage,
canManage: chat.canManage,
canUnlink: chat.canManage,
}}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources-panel.tsx
index 30b2b1d74..bdedc6871 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources-panel.tsx
@@ -66,10 +66,15 @@ export const RoomResourcesPanel = observer(function RoomResourcesPanel({
// A Console chat's members may read it but only its managers change it.
const permissions =
opensAsConsoleChat(roomId) && chat
- ? { canWrite: chat.canManage, canManage: chat.canManage, canUnlink: chat.canManage }
+ ? {
+ canWrite: chat.canManage,
+ canChangeMembers: chat.canManage,
+ canManage: chat.canManage,
+ canUnlink: chat.canManage,
+ }
: room !== null
? switchRoomsStore.roomPermissions(workspaceId, room)
- : { canWrite: false, canManage: false, canUnlink: false };
+ : { canWrite: false, canChangeMembers: false, canManage: false, canUnlink: false };
const canWrite = permissions.canWrite;
const canUnlink = permissions.canUnlink;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-side-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-side-panel.tsx
index fb6f46da8..0a855dc89 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-side-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-side-panel.tsx
@@ -153,14 +153,18 @@ export const RoomSidePanel = observer(function RoomSidePanel({ roomId }: { roomI
const permissions = switchRoomsStore.roomPermissions(workspaceId, room);
const inviteability = roomInviteability(room, bridgePlatformLabel(room.bridgeType));
if (permissions.canWrite) {
+ // A direct or group conversation's platform fixes who is in it.
+ const members = permissions.canChangeMembers;
controls = {
- addAgents: () => setAdding('agents'),
- addPeople: inviteability.canInvite ? () => setAdding('people') : null,
+ addAgents: members ? () => setAdding('agents') : null,
+ addPeople: members && inviteability.canInvite ? () => setAdding('people') : null,
peopleNote: inviteability.canInvite ? null : inviteability.reason,
- removeAgent: async (agentId) => {
- await rpc.workspaces.removeRoomAgent({ workspaceId, roomId, agentId });
- await refreshRoom();
- },
+ removeAgent: members
+ ? async (agentId) => {
+ await rpc.workspaces.removeRoomAgent({ workspaceId, roomId, agentId });
+ await refreshRoom();
+ }
+ : null,
// Switch only knows the people it saw or added; it cannot take them out of a channel.
removePerson: () => null,
joinEvents: {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-permissions.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-permissions.test.ts
index ee80a90da..92c324d45 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-permissions.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-permissions.test.ts
@@ -7,6 +7,7 @@ describe('roomPermissionsFor', () => {
it('lets the owner manage, write and detach', () => {
expect(roomPermissionsFor({ ownerId: 'u-1', writeVisibility: 'private' }, ME)).toEqual({
canWrite: true,
+ canChangeMembers: true,
canManage: true,
canUnlink: true,
});
@@ -18,12 +19,13 @@ describe('roomPermissionsFor', () => {
{ ownerId: 'u-2', writeVisibility: 'private' },
{ userId: 'u-1', isAdmin: true }
)
- ).toEqual({ canWrite: true, canManage: true, canUnlink: true });
+ ).toEqual({ canWrite: true, canChangeMembers: true, canManage: true, canUnlink: true });
});
it('lets anyone write to a publicly writable room, but not manage it', () => {
expect(roomPermissionsFor({ ownerId: 'u-2', writeVisibility: 'public' }, ME)).toEqual({
canWrite: true,
+ canChangeMembers: true,
canManage: false,
canUnlink: true,
});
@@ -32,6 +34,7 @@ describe('roomPermissionsFor', () => {
it('gives a non-owner nothing on a privately writable room', () => {
expect(roomPermissionsFor({ ownerId: 'u-2', writeVisibility: 'private' }, ME)).toEqual({
canWrite: false,
+ canChangeMembers: false,
canManage: false,
canUnlink: false,
});
@@ -46,6 +49,7 @@ describe('roomPermissionsFor', () => {
it('offers no writing on a room whose write access is not known, so nothing it shows is refused', () => {
expect(roomPermissionsFor({ ownerId: 'u-2' }, ME)).toEqual({
canWrite: false,
+ canChangeMembers: false,
canManage: false,
canUnlink: false,
});
@@ -53,7 +57,8 @@ describe('roomPermissionsFor', () => {
});
it('takes the server’s answer over its own working when the server gives one', () => {
- const answer = { canWrite: true, canManage: false, canUnlink: false };
+ // A direct conversation: written to, but who is in it is its platform's.
+ const answer = { canWrite: true, canChangeMembers: false, canManage: false, canUnlink: false };
expect(
roomPermissionsFor(
{ ownerId: 'u-1', writeVisibility: 'public', serverPermissions: answer },
@@ -68,6 +73,6 @@ describe('roomPermissionsFor', () => {
{ ownerId: 'u-1', writeVisibility: 'public' },
{ userId: null, isAdmin: true }
)
- ).toEqual({ canWrite: false, canManage: false, canUnlink: false });
+ ).toEqual({ canWrite: false, canChangeMembers: false, canManage: false, canUnlink: false });
});
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-permissions.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-permissions.ts
index 0d1806bd3..82946a89f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-permissions.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-permissions.ts
@@ -4,12 +4,19 @@ import type { RoomVisibility } from '@shared/core/switch-servers/switch-servers'
* What someone may do with a room. `canManage` is the owner's and the
* workspace admins' alone: deleting the room, changing who may see it, naming
* it after its channel. `canWrite` also covers anyone at all when the room's
- * write access is public: its description and instructions, who is in it, its
- * roles, its group, archiving it. `canUnlink` is detaching what is attached
- * to it: the server now keeps that for those taking part in the room and
+ * write access is public: its description and instructions, its roles, its
+ * group, archiving it. `canChangeMembers` is adding and removing its agents
+ * and people: `canWrite`, except in a direct or group conversation, whose
+ * platform fixes who is in it. `canUnlink` is detaching what is attached to
+ * it: the server now keeps that for those taking part in the room and
* workspace admins, whatever its write access.
*/
-export type RoomPermissions = { canWrite: boolean; canManage: boolean; canUnlink: boolean };
+export type RoomPermissions = {
+ canWrite: boolean;
+ canChangeMembers: boolean;
+ canManage: boolean;
+ canUnlink: boolean;
+};
/**
* What one viewer may do with a room: the server's own answer when it gives
@@ -28,8 +35,10 @@ export function roomPermissionsFor(
viewer: { userId: string | null; isAdmin: boolean }
): RoomPermissions {
if (room.serverPermissions) return room.serverPermissions;
- if (viewer.userId === null) return { canWrite: false, canManage: false, canUnlink: false };
+ if (viewer.userId === null) {
+ return { canWrite: false, canChangeMembers: false, canManage: false, canUnlink: false };
+ }
const canManage = viewer.isAdmin || (room.ownerId !== null && room.ownerId === viewer.userId);
const canWrite = canManage || room.writeVisibility === 'public';
- return { canWrite, canManage, canUnlink: canWrite };
+ return { canWrite, canChangeMembers: canWrite, canManage, canUnlink: canWrite };
}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-settings-sections.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-settings-sections.test.tsx
index ebe5e90fd..184540c66 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-settings-sections.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-settings-sections.test.tsx
@@ -11,7 +11,9 @@ const getRoomDetail = vi.hoisted(() => vi.fn());
const setRoomAgentJoinEvents = vi.hoisted(() => vi.fn());
const createRoomRole = vi.hoisted(() => vi.fn());
const setRoomArchived = vi.hoisted(() => vi.fn());
-const permissions = vi.hoisted(() => ({ value: { canWrite: true, canManage: true } }));
+const permissions = vi.hoisted(() => ({
+ value: { canWrite: true, canChangeMembers: true, canManage: true },
+}));
const admin = vi.hoisted(() => ({ value: true }));
const setRoomGroup = vi.hoisted(() => vi.fn());
@@ -127,7 +129,7 @@ beforeEach(() => {
setRoomArchived.mockImplementation((params: { archived: boolean }) =>
Promise.resolve({ ...ROOM, archived: params.archived })
);
- permissions.value = { canWrite: true, canManage: true };
+ permissions.value = { canWrite: true, canChangeMembers: true, canManage: true };
admin.value = true;
setRoomGroup.mockReset();
setRoomGroup.mockImplementation(() =>
@@ -202,6 +204,18 @@ describe('room settings for someone who may write to the room', () => {
expect(el.querySelector('[aria-label="Add people"]')).not.toBeNull();
});
+ it('offers no adding or removing in a direct conversation, whose platform fixes who is in it', async () => {
+ permissions.value = { canWrite: true, canChangeMembers: false, canManage: true };
+ getRoomDetail.mockResolvedValue({ ...ROOM, channelType: 'direct' });
+ const el = await renderPanel('side');
+ expect(el.textContent).toContain('reviewer-bot');
+ expect(el.querySelector('[aria-label="Add agents"]')).toBeNull();
+ expect(el.querySelector('[aria-label="Add people"]')).toBeNull();
+ await click(el.querySelector<HTMLElement>('[aria-label="reviewer-bot in this room"]')!);
+ const items = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];
+ expect(items.some((item) => /Remove from room/.test(item.textContent ?? ''))).toBe(false);
+ });
+
it('shows every role an agent holds, matched on its name on the server', async () => {
getRoomDetail.mockResolvedValue({
...ROOM,
@@ -290,7 +304,7 @@ describe('putting a room in a group', () => {
it('shows anyone else who may change the room its group, and lets them take it out', async () => {
admin.value = false;
- permissions.value = { canWrite: true, canManage: false };
+ permissions.value = { canWrite: true, canChangeMembers: true, canManage: false };
getRoomDetail.mockResolvedValue({ ...ROOM, groupId: 'g-1', groupName: 'Design' });
const el = await renderPanel();
expect(el.querySelector('[aria-label="Group"]')).toBeNull();
@@ -314,7 +328,7 @@ describe('putting a room in a group', () => {
describe('room settings for someone who may only read the room', () => {
it('says who can change it, and offers no changes', async () => {
- permissions.value = { canWrite: false, canManage: false };
+ permissions.value = { canWrite: false, canChangeMembers: false, canManage: false };
const el = await renderPanel();
expect(el.textContent).toContain(
'Only Ada or a workspace admin can change this room’s settings.'
@@ -326,7 +340,7 @@ describe('room settings for someone who may only read the room', () => {
});
it('lists who is in the room without adding or menus', async () => {
- permissions.value = { canWrite: false, canManage: false };
+ permissions.value = { canWrite: false, canChangeMembers: false, canManage: false };
const el = await renderPanel('side');
expect(el.textContent).toContain('reviewer-bot');
expect(el.querySelector('[aria-label="Add agents"]')).toBeNull();
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
index 2a2860483..73d04da2d 100644
--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
@@ -367,7 +367,12 @@ export type RemoteRoomSummary = {
* by the rules its routes enforce. Absent from a server that does not say,
* where Console works it out the same way (`roomPermissionsFor`).
*/
- serverPermissions?: { canWrite: boolean; canManage: boolean; canUnlink: boolean };
+ serverPermissions?: {
+ canWrite: boolean;
+ canChangeMembers: boolean;
+ canManage: boolean;
+ canUnlink: boolean;
+ };
/** The messaging app connection it is on, when the server says (the list does). Unlike
* the display name, it tells two connections to the same platform apart. */
bridgeId?: string | null;
diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.md
index fe036e8a0..07315c498 100644
--- a/console/packages/plugins/src/switch-skill/SKILL.md
+++ b/console/packages/plugins/src/switch-skill/SKILL.md
@@ -568,7 +568,9 @@ carrying a display name addresses no one.
on bridged Slack, Discord and Telegram channels; Telegram registers it as
`/invite_agent`, since it will not accept a hyphen in a command). On Telegram
a command tapped from the `/` menu is sent immediately with no argument, so
- the bot asks for the one it needs and runs when you reply with it.
+ the bot asks for the one it needs and runs when you reply with it. The tool
+ is refused in a direct or group conversation, whose platform fixes who is in
+ it; the command still works there, and is how the people in it add an agent.
- **`remove_agent_from_room`** — take an agent out of a room by name, the
opposite of `invite_agent_to_room`; any session it had there is
disconnected. You need not be in the room. Allowed when you may address
@@ -577,7 +579,8 @@ carrying a display name addresses no one.
Confirm with the person asking before removing anything. People do the same
in a room with `!remove-agent @agent-name` (a slash command where
`/invite-agent` is one, `/remove_agent` on Telegram), which a workspace admin
- may use on any agent.
+ may use on any agent. As with inviting, the tool is refused in a direct or
+ group conversation, where the command still works.
- **`add_users_to_room`** — add human users to an existing room, the
counterpart to `invite_agent_to_room`. Name each person by their username on
the room's messaging app, or the e-mail address of their account there (not
@@ -585,7 +588,8 @@ carrying a display name addresses no one.
`get_my_context`; for anyone else, ask. Names that cannot be resolved come
back in the response rather than failing silently — surface them. The same
goes for `create_room`'s `user_names`, whose misses come back in
- `failed_attachments`.
+ `failed_attachments`. Refused in a direct or group conversation, as
+ inviting an agent is.
- **`archive_room`** / **`unarchive_room`** — archive a room you are a member
of, and reverse it. Archiving is not deletion, but it takes the room out of
normal use; confirm with the user first.
diff --git a/core/switch_core/accounts/deletion.py b/core/switch_core/accounts/deletion.py
index e58f3d4a8..c010259ce 100644
--- a/core/switch_core/accounts/deletion.py
+++ b/core/switch_core/accounts/deletion.py
@@ -264,6 +264,13 @@ class Workspace:
role: str
+def is_server_administrator(user: User, admin_email: str) -> bool:
+ """The server's administrator account: an operator, or the account at the
+ configured admin e-mail, which the server recreates every time it starts,
+ so it is never deleted."""
+ return user.role == "admin" or user.email.lower() == admin_email.lower()
+
+
@dataclass
class AccountDeletion:
session_factory: async_sessionmaker[AsyncSession]
@@ -308,7 +315,7 @@ class AccountDeletion:
self, session: AsyncSession, user: User, workspaces: list[Workspace]
) -> str | None:
"""Why the account cannot be deleted now, or None when it can."""
- if user.role == "admin" or user.email.lower() == self.admin_email.lower():
+ if is_server_administrator(user, self.admin_email):
return (
"This is the server's administrator account, which can't be "
"deleted. The server recreates it every time it starts."
diff --git a/core/switch_core/accounts/transfer.py b/core/switch_core/accounts/transfer.py
index 10f1ff779..b1dbfb251 100644
--- a/core/switch_core/accounts/transfer.py
+++ b/core/switch_core/accounts/transfer.py
@@ -38,13 +38,14 @@ from __future__ import annotations
import hashlib
import secrets
+from collections.abc import Collection
from dataclasses import dataclass
from typing import TYPE_CHECKING, Literal, cast, get_args
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
-from switch_core.authz import Principal, can_manage
+from switch_core.authz import Principal, can_manage, owns
from switch_core.db.audit import AuditAction, record_audit_event
from switch_core.db.models import (
Agent,
@@ -142,60 +143,138 @@ async def _load(
return row
-async def _refuse_agent(session: AsyncSession, tenant_id: str, agent: Agent) -> None:
- services = sorted(
+@dataclass(frozen=True)
+class AgentTransferFacts:
+ """What decides whether an agent can change owner, read for many agents
+ at once by `agent_transfer_facts`. Every one of these ties the agent to its
+ owner by more than its owner id; see this module's docstring."""
+
+ granted_services: tuple[str, ...]
+ managed: bool
+ may_manage_agents: bool
+ # It is a sub-agent, or has sub-agents.
+ in_family: bool
+ has_oauth_client: bool
+ run_by_server_connector: bool
+
+
+async def agent_transfer_facts(
+ session: AsyncSession, tenant_id: str, agent_ids: Collection[str]
+) -> dict[str, AgentTransferFacts]:
+ """`AgentTransferFacts` for each of `agent_ids` found in the tenant, in one
+ query per kind of fact rather than per agent."""
+ if not agent_ids:
+ return {}
+ ids = list(agent_ids)
+ rows = (
+ await session.execute(
+ select(
+ Agent.id,
+ Agent.can_manage_agents,
+ Agent.parent_agent_id,
+ Agent.oauth_client_id,
+ Agent.metadata_,
+ ).where(Agent.tenant_id == tenant_id, Agent.id.in_(ids))
+ )
+ ).all()
+ services: dict[str, list[str]] = {}
+ for agent_id, service in await session.execute(
+ select(ServiceGrant.agent_id, ServiceGrant.service).where(
+ ServiceGrant.tenant_id == tenant_id, ServiceGrant.agent_id.in_(ids)
+ )
+ ):
+ services.setdefault(agent_id, []).append(service)
+ managed = set(
await session.scalars(
- select(ServiceGrant.service).where(
- ServiceGrant.tenant_id == tenant_id, ServiceGrant.agent_id == agent.id
+ select(AgentDefinition.agent_id).where(
+ AgentDefinition.tenant_id == tenant_id,
+ AgentDefinition.agent_id.in_(ids),
)
)
)
- if services:
- raise TransferRefused(
- 409,
- "This agent uses its owner's own connections to "
- f"{', '.join(services)}. Remove its service access first; the new "
- "owner can then grant their own.",
- )
- managed = await session.scalar(
- select(AgentDefinition.id).where(
- AgentDefinition.tenant_id == tenant_id, AgentDefinition.agent_id == agent.id
+ parents = set(
+ await session.scalars(
+ select(Agent.parent_agent_id).where(
+ Agent.tenant_id == tenant_id, Agent.parent_agent_id.in_(ids)
+ )
)
)
- if managed is not None:
- raise TransferRefused(
- 409,
- "This agent is managed on its owner's machine, with their sign-ins, "
- "and can't be transferred.",
+ return {
+ agent_id: AgentTransferFacts(
+ granted_services=tuple(sorted(services.get(agent_id, ()))),
+ managed=agent_id in managed,
+ may_manage_agents=may_manage_agents,
+ in_family=parent_agent_id is not None or agent_id in parents,
+ has_oauth_client=oauth_client_id is not None,
+ run_by_server_connector=isinstance(metadata, dict)
+ and bool(metadata.get("server_connector_id")),
)
- if agent.can_manage_agents:
- raise TransferRefused(
- 409,
- "This agent can manage its owner's agents. Turn that off first.",
+ for agent_id, may_manage_agents, parent_agent_id, oauth_client_id, metadata in rows
+ }
+
+
+def agent_transfer_refusal(facts: AgentTransferFacts, *, to_owner: bool) -> str | None:
+ """Why the agent can't change owner, for the person asking; None when it
+ can. Only its owner is told which services it is granted: the grants are
+ made on the owner's own connections, which nobody else is shown."""
+ if facts.granted_services:
+ if to_owner:
+ return (
+ "This agent uses your own connections to "
+ f"{', '.join(facts.granted_services)}. Remove its service access "
+ "first; the new owner can then grant their own."
+ )
+ return (
+ "This agent uses its owner's own connections. Its owner has to "
+ "remove its service access first; the new owner can then grant "
+ "their own."
)
- child = await session.scalar(
- select(Agent.id).where(
- Agent.tenant_id == tenant_id, Agent.parent_agent_id == agent.id
+ if facts.managed:
+ return (
+ "This agent is managed on its owner's machine, with their sign-ins, "
+ "and can't be transferred."
)
- )
- if agent.parent_agent_id is not None or child is not None:
- raise TransferRefused(
- 409,
- "This agent is part of a family of sub-agents, which can't be transferred.",
+ if facts.may_manage_agents:
+ return "This agent can manage its owner's agents. Turn that off first."
+ if facts.in_family:
+ return (
+ "This agent is part of a family of sub-agents, which can't be transferred."
)
- if agent.oauth_client_id is not None:
- raise TransferRefused(
- 409,
+ if facts.has_oauth_client:
+ return (
"This agent signs in with an OAuth client of its own and can't be "
- "transferred.",
+ "transferred."
)
- if (agent.metadata_ or {}).get("server_connector_id"):
- raise TransferRefused(
- 409,
+ if facts.run_by_server_connector:
+ return (
"This agent is run by a server connector, which registers it again "
"under its own owner whenever the server starts, so it can't be "
- "transferred.",
+ "transferred."
+ )
+ return None
+
+
+async def _refuse_agent(
+ session: AsyncSession, tenant_id: str, agent: Agent, *, to_owner: bool
+) -> None:
+ facts = (await agent_transfer_facts(session, tenant_id, [agent.id]))[agent.id]
+ refusal = agent_transfer_refusal(facts, to_owner=to_owner)
+ if refusal is not None:
+ raise TransferRefused(409, refusal)
+
+
+def kind_refusal(resource: Room | Document) -> str | None:
+ """Why a room or a document can't change owner, whoever would receive it;
+ None when it can. A chat stays with the people in it, and a room's own
+ document with its room."""
+ if isinstance(resource, Room) and "chat_operation_id" in (resource.metadata_ or {}):
+ return "A chat can't be transferred."
+ if isinstance(resource, Document) and resource.room_id is not None:
+ return (
+ "This document belongs to a room. Only library documents can be "
+ "transferred."
)
+ return None
async def _refuse(
@@ -204,19 +283,16 @@ async def _refuse(
kind: str,
resource: Owned,
new_owner_id: str,
+ caller: Principal,
) -> None:
if isinstance(resource, Agent):
- await _refuse_agent(session, tenant_id, resource)
- elif isinstance(resource, Room):
- if resource.metadata_ is not None and "chat_operation_id" in resource.metadata_:
- raise TransferRefused(409, "A chat can't be transferred.")
- elif isinstance(resource, Document):
- if resource.room_id is not None:
- raise TransferRefused(
- 409,
- "This document belongs to a room. Only library documents can be "
- "transferred.",
- )
+ await _refuse_agent(
+ session, tenant_id, resource, to_owner=owns(caller, resource.owner_id)
+ )
+ elif isinstance(resource, Room | Document):
+ refusal = kind_refusal(resource)
+ if refusal is not None:
+ raise TransferRefused(409, refusal)
elif isinstance(resource, Template):
clash = await session.scalar(
select(Template.id).where(
@@ -295,7 +371,7 @@ async def transfer_ownership(
f"You can't transfer someone else's {label} to yourself. "
"Ask its owner to transfer it to you.",
)
- await _refuse(session, tenant_id, kind, resource, new_owner_id)
+ await _refuse(session, tenant_id, kind, resource, new_owner_id, caller)
retired: str | None = None
if isinstance(resource, Agent):
@@ -370,9 +446,7 @@ async def hand_over_everything(
)
)
for row in rows:
- if isinstance(row, Room) and "chat_operation_id" in (row.metadata_ or {}):
- continue
- if isinstance(row, Document) and row.room_id is not None:
+ if isinstance(row, (Room, Document)) and kind_refusal(row) is not None:
continue
if isinstance(row, Template):
if not await _template_passes(session, row, heir_id):
diff --git a/core/switch_core/addressing.py b/core/switch_core/addressing.py
index c4591d8dc..5b76b7eed 100644
--- a/core/switch_core/addressing.py
+++ b/core/switch_core/addressing.py
@@ -150,6 +150,28 @@ class AddressingRule(BaseModel):
return sender_owner_user_id == owner_user_id
+def never_allows(rule: AddressingRule) -> str | None:
+ """Why `rule` can never allow anyone, or None when it can.
+
+ With rules present a policy denies whatever no rule allows, so a rule like
+ this allows nothing while looking as if it did, and a policy of nothing
+ but such rules shuts the agent off, its owner included. Checked when a
+ policy is saved (`gateway/agents.py`), not when one is read: one stored
+ before still parses.
+ """
+ if rule.rooms == []:
+ return "it names no rooms"
+ if rule.room_groups == []:
+ return "it names no room groups"
+ if (
+ rule.users == []
+ and rule.agents == []
+ and not (rule.owner or rule.owner_agents or rule.platform)
+ ):
+ return "it lets in no people, no agents, not the owner and not the platform"
+ return None
+
+
class AddressingPolicy(BaseModel):
"""An agent's addressing allow-list. Empty ``rules`` → allow-all."""
diff --git a/core/switch_core/authz.py b/core/switch_core/authz.py
index 9dd028884..507853357 100644
--- a/core/switch_core/authz.py
+++ b/core/switch_core/authz.py
@@ -148,6 +148,16 @@ def require(principal: Principal, action: Action, resource: Authorizable) -> Non
raise PermissionError(f"Not authorized to {action} this resource")
+def owns(principal: Principal, owner_id: str | None) -> bool:
+ """Whether `principal` owns the entity, whatever their role.
+
+ For what only the owner may do, where administering the workspace is not
+ enough: an agent's own capabilities and the service access it holds on its
+ owner's connections, and a person's own API keys, devices and connections.
+ """
+ return owner_id is not None and owner_id == principal.id
+
+
def can_manage(principal: Principal, owner_id: str | None) -> bool:
"""Owner-or-admin check for entities that have no visibility model.
@@ -156,7 +166,7 @@ def can_manage(principal: Principal, owner_id: str | None) -> bool:
delete them. This is equivalent to write/delete on an always-private
resource.
"""
- return principal.is_admin or (owner_id is not None and owner_id == principal.id)
+ return principal.is_admin or owns(principal, owner_id)
def require_manage(principal: Principal, owner_id: str | None) -> None:
@@ -219,6 +229,46 @@ def can_delete_room_document(
)
+def can_change_workspace_member(
+ *, administers: bool, member_is_organization_admin: bool
+) -> bool:
+ """Whether the caller may change a workspace member's role or remove them.
+
+ A workspace admin may, their own row included, so an admin steps down or
+ leaves while another admin remains; the last one is refused when asked.
+ Never an organization admin's row, whose standing in the workspace comes
+ from the organization and is changed in its members.
+ """
+ return administers and not member_is_organization_admin
+
+
+def admin_by_own_membership(tenant_role: str | None) -> bool:
+ """Whether `tenant_role` is an admin's own membership of the workspace:
+ not the operator's bypass and not an organization admin acting as one.
+
+ What nobody can undo takes it: deleting the workspace, erasing a person,
+ and setting its messages to be deleted."""
+ return tenant_role in TENANT_ADMIN_ROLES
+
+
+def can_delete_workspace(*, tenant_role: str | None, is_default: bool) -> bool:
+ """Whether the caller may delete the workspace they hold `tenant_role` in:
+ `admin_by_own_membership`, and never the server's default workspace,
+ where new accounts start. That it must first be emptied is checked when
+ it is deleted.
+ """
+ return admin_by_own_membership(tenant_role) and not is_default
+
+
+def can_delete_api_key(
+ principal: Principal, owner_id: str | None, *, an_agent_signs_in_with_it: bool
+) -> bool:
+ """Whether `principal` may delete an API key: their own, unless an agent
+ still signs in with it. That key goes with its agent; once the agent is
+ deleted, what is left of it may go too."""
+ return owns(principal, owner_id) and not an_agent_signs_in_with_it
+
+
def require_group_filing(is_admin: bool) -> None:
"""Raise ``PermissionError`` unless a workspace admin is putting a room
into a room group.
diff --git a/core/switch_core/bridges/agent/api/operations.py b/core/switch_core/bridges/agent/api/operations.py
index 3e8265f37..914a930d9 100644
--- a/core/switch_core/bridges/agent/api/operations.py
+++ b/core/switch_core/bridges/agent/api/operations.py
@@ -46,6 +46,7 @@ from switch_core.observability.catalogue import (
BRIDGE_EVENTS_IN,
)
from switch_core.observability.metrics import metrics
+from switch_core.room_service import MembershipFixed
from switch_core.trust.client import GuardrailBlockedError
logger = logging.getLogger(__name__)
@@ -76,6 +77,10 @@ def refusal_status(exc: Exception) -> int | None:
return 422
if isinstance(exc, PermissionError):
return 403
+ if isinstance(exc, MembershipFixed):
+ # As the room routes answer it: nothing is wrong with the request, the
+ # room is a direct or group conversation.
+ return 409
if isinstance(exc, ValueError):
# Operations raise ValueError for "you asked for something that is not
# there or not allowed yet" - surfaced rather than swallowed.
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index ca123f93d..4a8f212ca 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -1438,6 +1438,9 @@ async def invite_agent_to_room(
) -> dict[str, bool]:
"""Invite an agent into an existing room by name.
+ A direct or group conversation is refused: its platform fixes who is in
+ it, and the people in it add agents with `!invite-agent` there.
+
Args:
room_id: The Switch room id (UUID string).
agent_name: Registry name of the agent to add.
@@ -1464,8 +1467,10 @@ async def remove_agent_from_room(room_id: str, agent_name: str) -> dict[str, boo
connected there is disconnected from it. You need not be in the room.
Allowed when you may address that agent (its addressing policy admits
- you), or when you can manage agents and it belongs to your owner. Anything
- else is refused with the reason — relay it rather than retrying.
+ you), or when you can manage agents and it belongs to your owner. A direct
+ or group conversation is refused: its platform fixes who is in it, and the
+ people in it use `!remove-agent` there. Anything else is refused with the
+ reason — relay it rather than retrying.
Args:
room_id: The Switch room id (UUID string).
@@ -1491,7 +1496,8 @@ async def add_users_to_room(room_id: str, user_names: list[str]) -> dict[str, An
be a user already known to that bridge — e.g. someone who has signed into
the workspace — otherwise the bridge cannot resolve them. Use this after a
bridge change to re-invite the humans who were dropped, since their
- identities are bridge-specific and are not carried across.
+ identities are bridge-specific and are not carried across. A direct or
+ group conversation is refused: its platform fixes who is in it.
Args:
room_id: The Switch room id (UUID string).
diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.py
index 094fa4c02..628da061c 100644
--- a/core/switch_core/bridges/agent/protocol/agent_core.py
+++ b/core/switch_core/bridges/agent/protocol/agent_core.py
@@ -135,6 +135,7 @@ from switch_core.events import (
)
from switch_core.messages.recorded_types import MEMBERSHIP_EVENT_TYPE
from switch_core.platform_access import administers_on_record
+from switch_core.room_service import require_membership_changeable_from_outside
from switch_core.room_wide_mention import (
ROOM_WIDE_TARGET,
is_reserved_mention_name,
@@ -3284,7 +3285,9 @@ class AgentCore:
"""
include_for: list[str] | None = None
async with self.session_factory() as session:
- await self._require_room_roster_change(session, agent_id, room_id)
+ require_membership_changeable_from_outside(
+ await self._require_room_roster_change(session, agent_id, room_id)
+ )
if include_subagents:
target = await self.agent_store.get_by_name(session, agent_name)
if target is None:
@@ -3316,7 +3319,9 @@ class AgentCore:
were skipped); an empty list means every requested user was added.
"""
async with self.session_factory() as session:
- await self._require_room_roster_change(session, agent_id, room_id)
+ require_membership_changeable_from_outside(
+ await self._require_room_roster_change(session, agent_id, room_id)
+ )
try:
return await self.room_service.add_users_to_room(room_id, user_names)
except ValueError as e:
@@ -3330,7 +3335,8 @@ class AgentCore:
Allowed when the caller may address the target in that room, or when
the caller can manage agents and the target belongs to the caller's
owner. Membership of the room is not required: an owner's assistant
- tidies rooms it was never in.
+ tidies rooms it was never in. Never in a direct or group conversation
+ (`require_membership_changeable_from_outside`).
"""
async with self.session_factory() as session:
caller = await self.agent_store.get(session, agent_id)
@@ -3339,6 +3345,7 @@ class AgentCore:
room = await self.room_store.get(session, room_id)
if room is None:
raise ValueError(f"Room not found: {room_id}")
+ require_membership_changeable_from_outside(room)
target = await self.agent_store.get_by_name(session, agent_name)
if target is None:
raise ValueError(f"Failed to remove agent: unknown agent {agent_name}")
diff --git a/core/switch_core/bridges/agent/protocol/agent_detail.py b/core/switch_core/bridges/agent/protocol/agent_detail.py
index c3e36bbcd..061489262 100644
--- a/core/switch_core/bridges/agent/protocol/agent_detail.py
+++ b/core/switch_core/bridges/agent/protocol/agent_detail.py
@@ -349,7 +349,7 @@ def agent_facing_summary(summary: AgentSummary) -> dict[str, Any]:
"""`summary` as an agent may read it: without the raw addressing policy,
whose rules name the users, agents and rooms the owner let in. An agent
learns who may address it from `describe_addressing` instead."""
- return summary.model_dump(exclude={"addressing_policy", "can_manage"})
+ return summary.model_dump(exclude={"addressing_policy"})
def agent_facing_detail(detail: AgentDetail) -> dict[str, Any]:
@@ -358,8 +358,7 @@ def agent_facing_detail(detail: AgentDetail) -> dict[str, Any]:
return detail.model_dump(
exclude={
"addressing_policy": True,
- "can_manage": True,
- "children": {"__all__": {"addressing_policy", "can_manage"}},
+ "children": {"__all__": {"addressing_policy"}},
}
)
diff --git a/core/switch_core/bridges/resource/service.py b/core/switch_core/bridges/resource/service.py
index aeb235ad0..91e7c01bb 100644
--- a/core/switch_core/bridges/resource/service.py
+++ b/core/switch_core/bridges/resource/service.py
@@ -690,12 +690,12 @@ class ResourceService:
if ref is None:
raise ValueError(f"Reference not found: {reference_id}")
require(Principal(user_id, is_admin), "read", ref)
- await self._references.attach_to_room(session, room_id, reference_id)
- emit_safely(
- self._telemetry,
- "reference_attached_to_room",
- {"reference_type": _reference_type(ref.type)},
- )
+ if await self._references.attach_to_room(session, room_id, reference_id):
+ emit_safely(
+ self._telemetry,
+ "reference_attached_to_room",
+ {"reference_type": _reference_type(ref.type)},
+ )
async def detach_reference_from_room(
self, session: AsyncSession, room_id: str, reference_id: str
@@ -990,14 +990,15 @@ class ResourceService:
doc = await self._documents.get(session, document_id)
if doc is None:
raise ValueError(f"Document not found: {document_id}")
+ # First, so whoever may not read it is not told what it is.
+ require(Principal(user_id, is_admin), "read", doc)
if doc.room_id is not None:
raise ValueError(
f"Document {document_id} is room-scoped and cannot be attached "
"to another room"
)
- require(Principal(user_id, is_admin), "read", doc)
- await self._documents.attach_to_room(session, room_id, document_id)
- emit_safely(self._telemetry, "document_attached_to_room", {})
+ if await self._documents.attach_to_room(session, room_id, document_id):
+ emit_safely(self._telemetry, "document_attached_to_room", {})
async def detach_document_from_room(
self, session: AsyncSession, room_id: str, document_id: str
@@ -1371,7 +1372,8 @@ class ResourceService:
if pkg is None:
raise ValueError(f"Package not found: {package_id}")
require(Principal(user_id, is_admin), "read", pkg)
- await self._packages.attach_to_room(session, room_id, package_id)
+ if not await self._packages.attach_to_room(session, room_id, package_id):
+ return
# What the package brought with it, which is the whole point of
# attaching one rather than its parts.
emit_safely(
@@ -1467,6 +1469,9 @@ class ResourceService:
ref = await self._references.get(session, reference_id)
if ref is None:
raise ValueError(f"Reference not found: {reference_id}")
+ # So did whoever adds it: a package lists its references to everyone
+ # who may read it, so adding one is showing it to them.
+ require(Principal(user_id, is_admin), "read", ref)
# The package owner must be able to read the reference being added.
if not can(Principal(pkg.owner_id, False), "read", ref):
raise PermissionError(
@@ -1510,6 +1515,9 @@ class ResourceService:
doc = await self._documents.get(session, document_id)
if doc is None:
raise ValueError(f"Document not found: {document_id}")
+ # As for a reference: adding it shows it to every reader of the package.
+ # First, so whoever may not read it is not told what it is.
+ require(Principal(user_id, is_admin), "read", doc)
if doc.room_id is not None:
raise ValueError(
f"Document {document_id} is room-scoped and cannot be added to a package"
diff --git a/core/switch_core/db/stores/document_store.py b/core/switch_core/db/stores/document_store.py
index 1358ae80e..907c7c608 100644
--- a/core/switch_core/db/stores/document_store.py
+++ b/core/switch_core/db/stores/document_store.py
@@ -1,4 +1,7 @@
-from sqlalchemy import and_, delete, func, insert, or_, select
+from typing import Any, cast
+
+from sqlalchemy import CursorResult, and_, delete, func, or_, select
+from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.db.models import Document, Room, package_documents, room_documents
@@ -109,11 +112,18 @@ class DocumentStore:
async def attach_to_room(
self, session: AsyncSession, room_id: str, document_id: str
- ) -> None:
- await session.execute(
- insert(room_documents).values(room_id=room_id, document_id=document_id)
+ ) -> bool:
+ """Attach a document to a room, saying whether it was attached now.
+ Idempotent, as attaching a reference is."""
+ result = await session.execute(
+ pg_insert(room_documents)
+ .values(room_id=room_id, document_id=document_id)
+ .on_conflict_do_nothing(
+ index_elements=[room_documents.c.room_id, room_documents.c.document_id]
+ )
)
await session.flush()
+ return cast("CursorResult[Any]", result).rowcount == 1
async def detach_from_room(
self, session: AsyncSession, room_id: str, document_id: str
diff --git a/core/switch_core/db/stores/invitation_store.py b/core/switch_core/db/stores/invitation_store.py
index 1dd8ba908..fafc4dad3 100644
--- a/core/switch_core/db/stores/invitation_store.py
+++ b/core/switch_core/db/stores/invitation_store.py
@@ -211,9 +211,23 @@ class InvitationStore:
return int(result.scalar_one())
async def revoke(self, session: AsyncSession, invitation_id: str) -> Invitation:
- invitation = await session.get(Invitation, invitation_id)
+ """Revoke an invitation that could still be accepted.
+
+ Raises `ValueError` when there is none, and `InvitationNotUsableError`
+ when it has already ended — revoked, expired or used up: revoking it
+ again would rewrite when, and by whom, it ended.
+ """
+ invitation = await session.get(
+ Invitation, invitation_id, with_for_update=True, populate_existing=True
+ )
if invitation is None:
raise ValueError(f"Invitation not found: {invitation_id}")
+ if not await session.scalar(
+ select(_usable()).where(Invitation.id == invitation_id)
+ ):
+ raise InvitationNotUsableError(
+ "This invitation has already ended: revoked, expired or used up."
+ )
invitation.revoked_at = datetime.now(UTC)
await session.flush()
return invitation
diff --git a/core/switch_core/db/stores/package_store.py b/core/switch_core/db/stores/package_store.py
index 67d8fb67a..f8140e3fa 100644
--- a/core/switch_core/db/stores/package_store.py
+++ b/core/switch_core/db/stores/package_store.py
@@ -1,4 +1,7 @@
-from sqlalchemy import delete, func, insert, or_, select
+from typing import Any, cast
+
+from sqlalchemy import CursorResult, delete, func, or_, select
+from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.db.models import (
@@ -101,11 +104,18 @@ class PackageStore:
async def attach_to_room(
self, session: AsyncSession, room_id: str, package_id: str
- ) -> None:
- await session.execute(
- insert(room_packages).values(room_id=room_id, package_id=package_id)
+ ) -> bool:
+ """Attach a package to a room, saying whether it was attached now.
+ Idempotent, as attaching a reference is."""
+ result = await session.execute(
+ pg_insert(room_packages)
+ .values(room_id=room_id, package_id=package_id)
+ .on_conflict_do_nothing(
+ index_elements=[room_packages.c.room_id, room_packages.c.package_id]
+ )
)
await session.flush()
+ return cast("CursorResult[Any]", result).rowcount == 1
async def detach_from_room(
self, session: AsyncSession, room_id: str, package_id: str
@@ -221,9 +231,15 @@ class PackageStore:
async def add_reference(
self, session: AsyncSession, package_id: str, reference_id: str
) -> None:
+ """Idempotent: adding a reference the package holds is a no-op."""
await session.execute(
- insert(package_references).values(
- package_id=package_id, reference_id=reference_id
+ pg_insert(package_references)
+ .values(package_id=package_id, reference_id=reference_id)
+ .on_conflict_do_nothing(
+ index_elements=[
+ package_references.c.package_id,
+ package_references.c.reference_id,
+ ]
)
)
await session.flush()
@@ -242,9 +258,15 @@ class PackageStore:
async def add_document(
self, session: AsyncSession, package_id: str, document_id: str
) -> None:
+ """Idempotent: adding a document the package holds is a no-op."""
await session.execute(
- insert(package_documents).values(
- package_id=package_id, document_id=document_id
+ pg_insert(package_documents)
+ .values(package_id=package_id, document_id=document_id)
+ .on_conflict_do_nothing(
+ index_elements=[
+ package_documents.c.package_id,
+ package_documents.c.document_id,
+ ]
)
)
await session.flush()
diff --git a/core/switch_core/db/stores/reference_store.py b/core/switch_core/db/stores/reference_store.py
index 4f458d33b..107cf4487 100644
--- a/core/switch_core/db/stores/reference_store.py
+++ b/core/switch_core/db/stores/reference_store.py
@@ -1,4 +1,6 @@
-from sqlalchemy import delete, func, or_, select
+from typing import Any, cast
+
+from sqlalchemy import CursorResult, delete, func, or_, select
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
@@ -157,10 +159,11 @@ class ReferenceStore:
async def attach_to_room(
self, session: AsyncSession, room_id: str, reference_id: str
- ) -> None:
- """Attach a reference to a room. Idempotent: attaching one that is
- already attached is a no-op, not a primary-key violation."""
- await session.execute(
+ ) -> bool:
+ """Attach a reference to a room, saying whether it was attached now.
+ Idempotent: attaching one that is already attached is a no-op, not a
+ primary-key violation."""
+ result = await session.execute(
pg_insert(room_references)
.values(room_id=room_id, reference_id=reference_id)
.on_conflict_do_nothing(
@@ -171,6 +174,7 @@ class ReferenceStore:
)
)
await session.flush()
+ return cast("CursorResult[Any]", result).rowcount == 1
async def detach_from_room(
self, session: AsyncSession, room_id: str, reference_id: str
diff --git a/core/switch_core/gateway/agents.py b/core/switch_core/gateway/agents.py
index 10a46f2bd..222c547e3 100644
--- a/core/switch_core/gateway/agents.py
+++ b/core/switch_core/gateway/agents.py
@@ -1,12 +1,18 @@
from __future__ import annotations
import logging
-from typing import Annotated
+from typing import Annotated, Any
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import ValidationError
from sqlalchemy.ext.asyncio import AsyncSession
+from switch_core.accounts.transfer import (
+ AgentTransferFacts,
+ agent_transfer_facts,
+ agent_transfer_refusal,
+)
+from switch_core.addressing import never_allows
from switch_core.agent_display_name import InvalidDisplayName, normalise_display_name
from switch_core.agent_icon import (
InvalidIconUrl,
@@ -14,7 +20,7 @@ from switch_core.agent_icon import (
normalise_icon_url,
refuse_third_party_avatar,
)
-from switch_core.authz import Principal, can_manage, require_manage
+from switch_core.authz import Principal, can_manage, owns, require_manage
from switch_core.bridges.agent.protocol.agent_core import (
AgentCore,
AgentExistsError,
@@ -52,11 +58,14 @@ from switch_core.gateway.dependencies import (
)
from switch_core.gateway.known_agents import known_agent, known_agents
from switch_core.gateway.schemas import (
+ AgentCapabilities,
AgentDetail,
AgentSummary,
AvatarSettingsResponse,
BulkRegisterResult,
DeleteAgentResponse,
+ GatewayAgentDetail,
+ GatewayAgentSummary,
IconChoicesResponse,
KnownAgentType,
RegisterAgentResponse,
@@ -81,13 +90,104 @@ logger = logging.getLogger(__name__)
router = APIRouter()
-def _for_caller[Summary: AgentSummary](
- summary: Summary, user: User, is_admin: bool
-) -> Summary:
- """`summary` with what `user` may do with the agent filled in."""
+def _has_known_spec(summary: AgentSummary) -> bool:
+ """Whether Switch Console runs the agent from a spec it knows, which is
+ what its options and its service tools come from."""
+ return (
+ summary.known_agent_type is not None
+ and known_agent(summary.known_agent_type) is not None
+ )
+
+
+def _capabilities(
+ summary: AgentSummary, principal: Principal, facts: AgentTransferFacts
+) -> dict[str, Any]:
+ """`AgentCapabilities` for one agent, from the rules its routes enforce."""
+ manage = can_manage(principal, summary.owner_id)
+ refusal = (
+ agent_transfer_refusal(facts, to_owner=owns(principal, summary.owner_id))
+ if manage
+ else None
+ )
+ return AgentCapabilities(
+ can_manage=manage,
+ can_edit_options=manage and _has_known_spec(summary),
+ can_rename=manage and not facts.in_family,
+ can_transfer=manage and refusal is None,
+ transfer_blocked_reason=refusal,
+ ).model_dump()
+
+
+def _with_capabilities(
+ summary: AgentSummary, principal: Principal, facts: dict[str, AgentTransferFacts]
+) -> GatewayAgentSummary:
+ return GatewayAgentSummary(
+ **summary.model_dump(), **_capabilities(summary, principal, facts[summary.id])
+ )
+
+
+def _agent_gone(agent_id: str) -> HTTPException:
+ return HTTPException(status_code=404, detail=f"Agent not found: {agent_id}")
+
+
+async def _summaries_for_caller(
+ session: AsyncSession, summaries: list[AgentSummary], user: User, is_admin: bool
+) -> list[GatewayAgentSummary]:
+ """`summaries` with what `user` may do with each agent filled in, reading
+ what that depends on for every agent at once. That is a read of its own,
+ so an agent deleted since `summaries` were read has no facts, and is left
+ out: it is gone."""
+ principal = Principal(user.id, is_admin)
+ facts = await agent_transfer_facts(
+ session, require_tenant_id(), [summary.id for summary in summaries]
+ )
+ return [
+ _with_capabilities(summary, principal, facts)
+ for summary in summaries
+ if summary.id in facts
+ ]
+
+
+async def _summary_for_caller(
+ session: AsyncSession, summary: AgentSummary, user: User, is_admin: bool
+) -> GatewayAgentSummary:
+ found = await _summaries_for_caller(session, [summary], user, is_admin)
+ if not found:
+ raise _agent_gone(summary.id)
+ return found[0]
+
+
+async def _detail_for_caller(
+ session: AsyncSession,
+ detail: AgentDetail,
+ user: User,
+ is_admin: bool,
+ config: SwitchConfig,
+) -> GatewayAgentDetail:
+ """`detail` with what `user` may do with the agent, and with each of its
+ children, filled in; as `_summaries_for_caller`, without whatever has been
+ deleted since `detail` was read."""
principal = Principal(user.id, is_admin)
- return summary.model_copy(
- update={"can_manage": can_manage(principal, summary.owner_id)}
+ facts = await agent_transfer_facts(
+ session,
+ require_tenant_id(),
+ [detail.id, *(child.id for child in detail.children)],
+ )
+ if detail.id not in facts:
+ raise _agent_gone(detail.id)
+ owner = owns(principal, detail.owner_id)
+ return GatewayAgentDetail(
+ **detail.model_dump(exclude={"children"}),
+ **_capabilities(detail, principal, facts[detail.id]),
+ can_change_manage_agents=owner,
+ can_grant_services=owner
+ and config.service_connections_enabled
+ and _has_known_spec(detail),
+ children=[
+ _with_capabilities(child, principal, facts)
+ for child in detail.children
+ if child.id in facts
+ ],
)
@@ -98,9 +198,9 @@ async def list_agents(
user_store: Annotated[UserStore, Depends(get_user_store)],
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
-) -> list[AgentSummary]:
+) -> list[GatewayAgentSummary]:
summaries = await list_agent_summaries(session, agent_store, user_store)
- return [_for_caller(summary, user, is_admin) for summary in summaries]
+ return await _summaries_for_caller(session, summaries, user, is_admin)
@router.delete("/by-name/{agent_name}")
@@ -389,7 +489,7 @@ async def update_agent_options(
agent_store: Annotated[AgentStore, Depends(get_agent_store)],
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
-) -> AgentSummary:
+) -> GatewayAgentSummary:
"""Replace a known-agent's options.
Body must contain the full options payload (no partial merge). The new
@@ -435,7 +535,7 @@ async def update_agent_options(
owner_name = user.name if agent.owner_id == user.id else None
summary = await build_agent_summary(session, agent_store, agent, owner_name)
- return _for_caller(summary, user, is_admin)
+ return await _summary_for_caller(session, summary, user, is_admin)
@router.put("/{agent_id}/icon")
@@ -448,7 +548,7 @@ async def update_agent_icon(
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
config: Annotated[SwitchConfig, Depends(get_config)],
chat_service: Annotated[ChatService, Depends(get_chat_service)],
-) -> AgentSummary:
+) -> GatewayAgentSummary:
"""Set, change, or clear an agent's icon (CHOO-2171).
``icon_url: null`` clears it, leaving the agent with no icon so the caller
@@ -501,7 +601,7 @@ async def update_agent_icon(
owner_name = user.name if agent.owner_id == user.id else None
summary = await build_agent_summary(session, agent_store, agent, owner_name)
- return _for_caller(summary, user, is_admin)
+ return await _summary_for_caller(session, summary, user, is_admin)
@router.put("/{agent_id}/name")
@@ -556,7 +656,8 @@ async def rename_agent(
await session.refresh(renamed)
owner_name = user.name if renamed.owner_id == user.id else None
return RenameAgentResponse(
- agent=_for_caller(
+ agent=await _summary_for_caller(
+ session,
await build_agent_summary(session, agent_store, renamed, owner_name),
user,
is_admin,
@@ -577,7 +678,7 @@ async def update_agent_display_name(
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
chat_service: Annotated[ChatService, Depends(get_chat_service)],
-) -> AgentSummary:
+) -> GatewayAgentSummary:
"""Set, change, or clear an agent's human display name.
``display_name: null`` (or a blank string) clears it, leaving the agent
@@ -623,7 +724,7 @@ async def update_agent_display_name(
owner_name = user.name if agent.owner_id == user.id else None
summary = await build_agent_summary(session, agent_store, agent, owner_name)
- return _for_caller(summary, user, is_admin)
+ return await _summary_for_caller(session, summary, user, is_admin)
@router.put("/{agent_id}/description")
@@ -635,7 +736,7 @@ async def update_agent_description(
protocol: Annotated[AgentCore, Depends(get_protocol)],
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
-) -> AgentSummary:
+) -> GatewayAgentSummary:
"""Change an agent's description. Only its owner (or an admin) may; a
blank description is refused with 400."""
agent = await agent_store.get(session, agent_id)
@@ -663,7 +764,7 @@ async def update_agent_description(
owner_name = user.name if agent.owner_id == user.id else None
summary = await build_agent_summary(session, agent_store, agent, owner_name)
- return _for_caller(summary, user, is_admin)
+ return await _summary_for_caller(session, summary, user, is_admin)
@router.post("/register-other")
@@ -718,7 +819,8 @@ async def update_addressing_policy(
protocol: Annotated[AgentCore, Depends(get_protocol)],
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
-) -> AgentDetail:
+ config: Annotated[SwitchConfig, Depends(get_config)],
+) -> GatewayAgentDetail:
"""Set or clear an agent's scoped addressing policy (CHOO-1585).
``policy: null`` clears it (the agent becomes open to anyone). Only the
@@ -739,6 +841,16 @@ async def update_addressing_policy(
detail="Only the agent's owner or an admin can change its addressing policy.",
)
+ dead = [
+ f"rule {number}: {why}"
+ for number, rule in enumerate(req.policy.rules if req.policy else [], 1)
+ if (why := never_allows(rule)) is not None
+ ]
+ if dead:
+ raise HTTPException(
+ status_code=422,
+ detail="These rules can never let anyone in: " + "; ".join(dead) + ".",
+ )
stored = req.policy.model_dump() if req.policy is not None else None
await agent_store.update(session, agent_id, addressing_policy=stored)
await session.commit()
@@ -761,7 +873,7 @@ async def update_addressing_policy(
room_role_store=protocol.room_role_store,
connections=protocol.connections,
)
- return _for_caller(detail, user, is_admin)
+ return await _detail_for_caller(session, detail, user, is_admin, config)
@router.put("/{agent_id}/can-manage-agents")
@@ -775,7 +887,8 @@ async def update_can_manage_agents(
protocol: Annotated[AgentCore, Depends(get_protocol)],
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
-) -> AgentDetail:
+ config: Annotated[SwitchConfig, Depends(get_config)],
+) -> GatewayAgentDetail:
"""Turn the agent's "can manage agents" capability on or off.
With it on, the agent may list its owner's machines and managed agents
@@ -787,7 +900,7 @@ async def update_can_manage_agents(
agent = await agent_store.get(session, agent_id)
if agent is None:
raise HTTPException(status_code=404, detail=f"Agent not found: {agent_id}")
- if agent.owner_id is None or agent.owner_id != user.id:
+ if not owns(Principal(user.id, is_admin), agent.owner_id):
raise HTTPException(
status_code=403,
detail="Only the agent's owner can change whether it can manage agents.",
@@ -815,7 +928,7 @@ async def update_can_manage_agents(
room_role_store=protocol.room_role_store,
connections=protocol.connections,
)
- return _for_caller(detail, user, is_admin)
+ return await _detail_for_caller(session, detail, user, is_admin, config)
# Declared after the literal GET routes (e.g. /known-types) so those are matched
@@ -830,7 +943,8 @@ async def get_agent_detail(
protocol: Annotated[AgentCore, Depends(get_protocol)],
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
-) -> AgentDetail:
+ config: Annotated[SwitchConfig, Depends(get_config)],
+) -> GatewayAgentDetail:
agent = await agent_store.get(session, agent_id)
if agent is None:
raise HTTPException(status_code=404, detail=f"Agent not found: {agent_id}")
@@ -846,4 +960,4 @@ async def get_agent_detail(
room_role_store=protocol.room_role_store,
connections=protocol.connections,
)
- return _for_caller(detail, user, is_admin)
+ return await _detail_for_caller(session, detail, user, is_admin, config)
diff --git a/core/switch_core/gateway/api_keys.py b/core/switch_core/gateway/api_keys.py
index e739f8211..39c078e0f 100644
--- a/core/switch_core/gateway/api_keys.py
+++ b/core/switch_core/gateway/api_keys.py
@@ -7,11 +7,13 @@ from datetime import UTC, datetime, timedelta
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException
+from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from switch_core.authz import Principal, can_delete_api_key, owns
from switch_core.config import SwitchConfig
from switch_core.db.audit import AuditAction, record_audit_event
-from switch_core.db.models import HASH_ONLY_KEY_TYPES, ApiKey, User
+from switch_core.db.models import HASH_ONLY_KEY_TYPES, Agent, ApiKey, User
from switch_core.db.stores.api_key_store import ApiKeyStore
from switch_core.gateway.auth import get_current_user
from switch_core.gateway.dependencies import (
@@ -45,6 +47,19 @@ def _key_type(value: str) -> str:
router = APIRouter()
+async def _signed_in_with(session: AsyncSession, keys: list[ApiKey]) -> set[str]:
+ """Which of `keys` an agent still signs in with: its own key, which goes
+ with it (`authz.can_delete_api_key`)."""
+ agent_keys = [k.id for k in keys if k.type == "agent"]
+ if not agent_keys:
+ return set()
+ return set(
+ await session.scalars(
+ select(Agent.api_key_id).where(Agent.api_key_id.in_(agent_keys))
+ )
+ )
+
+
@router.get("")
async def list_api_keys(
session: Annotated[AsyncSession, Depends(get_session)],
@@ -58,6 +73,10 @@ async def list_api_keys(
for k in await api_key_store.get_by_user(session, user.id)
if k.type not in HASH_ONLY_KEY_TYPES
]
+ signed_in_with = await _signed_in_with(session, keys)
+ # The caller's own keys, whatever their role: administering the workspace
+ # gives no reach over anyone's keys here.
+ principal = Principal(user.id, False)
return [
ApiKeyDetail(
id=k.id,
@@ -66,6 +85,10 @@ async def list_api_keys(
key_prefix=k.key_hash[:12],
created_at=str(k.created_at),
expires_at=k.expires_at,
+ can_reveal=owns(principal, k.user_id),
+ can_delete=can_delete_api_key(
+ principal, k.user_id, an_agent_signs_in_with_it=k.id in signed_in_with
+ ),
)
for k in keys
]
@@ -162,8 +185,22 @@ async def delete_api_key(
key = await api_key_store.get(session, key_id)
if key is None or key.type in HASH_ONLY_KEY_TYPES:
raise HTTPException(status_code=404, detail="API key not found")
- if key.user_id != user.id:
+ principal = Principal(user.id, False)
+ if not owns(principal, key.user_id):
raise HTTPException(status_code=403, detail="Not authorized to delete this key")
+ if not can_delete_api_key(
+ principal,
+ key.user_id,
+ an_agent_signs_in_with_it=key.id in await _signed_in_with(session, [key]),
+ ):
+ # The agent row refers to it, so deleting it would fail anyway.
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ "This is an agent's own key, which it still signs in with. "
+ "Delete the agent to retire it."
+ ),
+ )
key_hash = key.key_hash
await record_audit_event(
session,
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 95e9cc4c9..94be099cd 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -25,7 +25,7 @@ from switch_core.authz import (
)
from switch_core.config import SwitchConfig
from switch_core.db.audit import AuditAction, record_audit_event
-from switch_core.db.models import Organization, Room, Tenant, User
+from switch_core.db.models import Organization, Room, Tenant, User, require_tenant_id
from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.room_store import RoomStore
from switch_core.db.stores.user_store import UserStore
@@ -888,6 +888,31 @@ async def initial_tenant_claim(
return None
+async def rebind_if_left(
+ request: Request,
+ response: Response,
+ session_factory: async_sessionmaker[AsyncSession],
+ user_store: UserStore,
+ user: User,
+ config: SwitchConfig,
+) -> None:
+ """After the caller changed their own membership: when the workspace the
+ session is bound to is no longer one they may enter, re-mint the session
+ onto the one `initial_tenant_claim` picks, or none, as deleting a
+ workspace does, rather than leave it naming one they left. A re-mint, so
+ it keeps the session's sign-in time (`session_auth_time`)."""
+ if require_tenant_id() in await tenants_bindable_by(session_factory, user.id):
+ return
+ set_session_cookie(
+ response,
+ user,
+ config.keyring,
+ config.gateway_cookie_secure,
+ await initial_tenant_claim(session_factory, user_store, user),
+ session_auth_time(request),
+ )
+
+
def workspace_creation_refusal(
config: SwitchConfig,
*,
diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.py
index 8328e48c0..cf24c88c6 100644
--- a/core/switch_core/gateway/auth_routes.py
+++ b/core/switch_core/gateway/auth_routes.py
@@ -14,6 +14,7 @@ from switch_core.accounts.deletion import (
AccountDeletionIncomplete,
AccountDeletionRefused,
Workspace,
+ is_server_administrator,
)
from switch_core.bridges.agent.protocol.agent_core import AgentCore
from switch_core.bridges.resource.service import ResourceService
@@ -84,6 +85,7 @@ from switch_core.gateway.schemas import (
LinkedIdentity,
LoginRequest,
OidcLoginOptionView,
+ OperatorUserResponse,
PendingIdentity,
ServerDeclaration,
SessionStateResponse,
@@ -92,7 +94,6 @@ from switch_core.gateway.schemas import (
SignupRequest,
SignupResponse,
UpdateMeRequest,
- UserResponse,
)
from switch_core.providers.hosted import HostedControllerSettings
from switch_core.room_service import RoomService
@@ -689,16 +690,20 @@ async def change_password(
async def list_users(
session: Annotated[AsyncSession, Depends(get_session)],
user_store: Annotated[UserStore, Depends(get_user_store)],
- _admin: Annotated[User, Depends(require_admin)],
-) -> list[UserResponse]:
+ admin: Annotated[User, Depends(require_admin)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
+) -> list[OperatorUserResponse]:
+ admin_id = admin.id
users = await user_store.get_all(session)
return [
- UserResponse(
+ OperatorUserResponse(
id=u.id,
name=u.name,
email=u.email,
role=u.role,
created_at=str(u.created_at),
+ can_delete=u.id != admin_id
+ and not is_server_administrator(u, config.gateway_admin_email),
)
for u in users
]
@@ -710,7 +715,8 @@ async def create_user(
session: Annotated[AsyncSession, Depends(get_session)],
user_store: Annotated[UserStore, Depends(get_user_store)],
_admin: Annotated[User, Depends(require_admin)],
-) -> UserResponse:
+ config: Annotated[SwitchConfig, Depends(get_config)],
+) -> OperatorUserResponse:
existing = await user_store.get_by_email(session, req.email)
if existing is not None:
raise HTTPException(status_code=409, detail="Email already registered")
@@ -740,12 +746,13 @@ async def create_user(
logger.info("Created user: %s (%s)", user.email, user.id)
emit_safely(current_telemetry(), "account_created", {"method": "admin"})
- return UserResponse(
+ return OperatorUserResponse(
id=user.id,
name=user.name,
email=user.email,
role=user.role,
created_at=str(user.created_at),
+ can_delete=not is_server_administrator(user, config.gateway_admin_email),
)
diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.py
index b95bcb87b..8ed838e2c 100644
--- a/core/switch_core/gateway/collaborations.py
+++ b/core/switch_core/gateway/collaborations.py
@@ -12,6 +12,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from switch_core import messaging_platforms
from switch_core.account_links import LINK_CODE_TTL
+from switch_core.authz import Principal
from switch_core.bridges.collaboration.adapter import (
ConfigEditRefused,
DirectorySearchBusy,
@@ -238,6 +239,7 @@ async def _detail(
*,
room_count: int,
collab_lifecycle: CollaborationBridgeLifecycleService,
+ administers: bool,
is_default: bool | None = None,
) -> BridgeDetail:
"""One place every response shape is built, so a new field cannot reach
@@ -268,6 +270,8 @@ async def _detail(
team_placement_supported=_places_app_in_teams(bridge.id, collab_lifecycle),
receives_webhooks=collab_lifecycle.receives_webhooks(bridge.type),
webhook_url=collab_lifecycle.webhook_url(bridge.id, bridge.type),
+ can_manage=administers,
+ can_delete=administers,
)
@@ -392,7 +396,11 @@ async def create_bridge(
await session.commit()
return await _detail(
- bridge, room_count=0, collab_lifecycle=collab_lifecycle, is_default=is_default
+ bridge,
+ room_count=0,
+ collab_lifecycle=collab_lifecycle,
+ administers=True,
+ is_default=is_default,
)
@@ -425,7 +433,10 @@ async def set_default_bridge(
rooms = await room_store.get_by_bridge(session, bridge_id)
return await _detail(
- bridge, room_count=len(rooms), collab_lifecycle=collab_lifecycle
+ bridge,
+ room_count=len(rooms),
+ collab_lifecycle=collab_lifecycle,
+ administers=True,
)
@@ -438,6 +449,7 @@ async def list_bridges(
CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)
],
_user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> list[BridgeDetail]:
bridges = await bridge_store.get_all(session)
@@ -446,7 +458,10 @@ async def list_bridges(
rooms = await room_store.get_by_bridge(session, bridge.id)
details.append(
await _detail(
- bridge, room_count=len(rooms), collab_lifecycle=collab_lifecycle
+ bridge,
+ room_count=len(rooms),
+ collab_lifecycle=collab_lifecycle,
+ administers=is_admin,
)
)
@@ -592,7 +607,10 @@ async def update_bridge(
collab_lifecycle.note_preconfigured(bridge_id, payload.preconfigured)
rooms = await room_store.get_by_bridge(session, bridge_id)
return await _detail(
- bridge, room_count=len(rooms), collab_lifecycle=collab_lifecycle
+ bridge,
+ room_count=len(rooms),
+ collab_lifecycle=collab_lifecycle,
+ administers=True,
)
@@ -603,7 +621,8 @@ async def list_bridge_users(
bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],
user_store: Annotated[UserStore, Depends(get_user_store)],
- _user: Annotated[User, Depends(get_current_user)],
+ user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> list[ExternalUserSummary]:
bridge = await bridge_store.get(session, bridge_id)
if bridge is None:
@@ -618,7 +637,9 @@ async def list_bridge_users(
bridge_id=u.bridge_id,
external_user_id=u.external_user_id,
external_username=u.external_username,
- claimed_by=_claimants(claims.get(u.id, []), names),
+ claimed_by=_claimants(
+ claims.get(u.id, []), names, Principal(user.id, is_admin)
+ ),
)
for u in users
]
@@ -641,7 +662,7 @@ async def _user_names(
def _claimants(
- claims: list[ExternalUserClaim], names: dict[str, str]
+ claims: list[ExternalUserClaim], names: dict[str, str], viewer: Principal
) -> list[IdentityClaimant]:
def label(user_id: str) -> str:
return names.get(user_id) or user_id
@@ -651,6 +672,7 @@ def _claimants(
user_id=claim.user_id,
user_name=label(claim.user_id),
verified=claim.verified_at is not None,
+ can_unlink=_may_act_for(viewer, claim.user_id),
)
for claim in sorted(claims, key=lambda c: label(c.user_id).lower())
]
@@ -667,7 +689,8 @@ async def search_bridge_directory(
collab_lifecycle: Annotated[
CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)
],
- _user: Annotated[User, Depends(get_current_user)],
+ user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> DirectorySearchResponse:
"""Find someone on a messaging platform so they can be claimed.
@@ -684,6 +707,7 @@ async def search_bridge_directory(
outright would leave owner-only addressing unusable on those platforms even
for someone Switch knows perfectly well.
"""
+ viewer = Principal(user.id, is_admin)
bridge = await bridge_store.get(session, bridge_id)
if bridge is None:
raise HTTPException(status_code=404, detail="Bridge not found")
@@ -734,7 +758,11 @@ async def search_bridge_directory(
else None
),
claimed_by=(
- _claimants(claims.get(known[person.external_user_id].id, []), names)
+ _claimants(
+ claims.get(known[person.external_user_id].id, []),
+ names,
+ viewer,
+ )
if person.external_user_id in known
else []
),
@@ -948,7 +976,12 @@ async def claim_bridge_identity(
if claim is not None and claim.verified_at is not None:
# Already linked and confirmed: nothing to wait for.
return await _identity_summary(
- session, external_user_store, user_store, external_user, None
+ session,
+ external_user_store,
+ user_store,
+ external_user,
+ None,
+ Principal(caller_id, is_admin),
)
if older_client_for_someone_else:
@@ -968,7 +1001,12 @@ async def claim_bridge_identity(
)
await session.commit()
return await _identity_summary(
- session, external_user_store, user_store, external_user, None
+ session,
+ external_user_store,
+ user_store,
+ external_user,
+ None,
+ Principal(caller_id, is_admin),
)
code = (
await _issue_code(
@@ -1001,6 +1039,7 @@ async def claim_bridge_identity(
user_store,
external_user,
LinkRequestSummary(user_id=target_user_id, code=code),
+ Principal(caller_id, is_admin),
)
@@ -1060,6 +1099,7 @@ async def _identity_summary(
user_store: UserStore,
external_user: ExternalUser,
link_request: LinkRequestSummary | None,
+ viewer: Principal,
) -> ExternalUserSummary:
claims = await external_user_store.claims_for(session, [external_user.id])
names = await _user_names(session, user_store, claims)
@@ -1068,7 +1108,7 @@ async def _identity_summary(
bridge_id=external_user.bridge_id,
external_user_id=external_user.external_user_id,
external_username=external_user.external_username,
- claimed_by=_claimants(claims.get(external_user.id, []), names),
+ claimed_by=_claimants(claims.get(external_user.id, []), names, viewer),
link_request=link_request,
)
@@ -1119,13 +1159,19 @@ async def _refuse_unlinkable(
)
+def _may_act_for(viewer: Principal, user_id: str) -> bool:
+ """Whether `viewer` may act on `user_id`'s links: their own, or anyone's
+ for an admin."""
+ return viewer.is_admin or user_id == viewer.id
+
+
def _require_self_or_admin(
caller: User, is_admin: bool, user_id: str | None, doing: str
) -> str:
"""The Switch user a request acts for: the caller, or anyone for an
admin."""
target_user_id = user_id or caller.id
- if target_user_id != caller.id and not is_admin:
+ if not _may_act_for(Principal(caller.id, is_admin), target_user_id):
raise HTTPException(
status_code=403,
detail=f"Only an admin may {doing} for another user",
@@ -1261,6 +1307,7 @@ async def verify_identity_with_session(
CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)
],
user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> ExternalUserSummary:
"""Confirm the caller's pending link with the account's own session token.
@@ -1341,7 +1388,12 @@ async def verify_identity_with_session(
)
await session.commit()
return await _identity_summary(
- session, external_user_store, user_store, external_user, None
+ session,
+ external_user_store,
+ user_store,
+ external_user,
+ None,
+ Principal(caller_id, is_admin),
)
@@ -1439,6 +1491,7 @@ async def cancel_identity_link_request(
links needed confirming leaves that link working. Unlinking is
`release_bridge_identity`.
"""
+ viewer = Principal(user.id, is_admin)
external_user = await _identity_on_bridge(
session, external_user_store, bridge_id, external_user_row_id
)
@@ -1465,7 +1518,12 @@ async def cancel_identity_link_request(
)
await session.commit()
return await _identity_summary(
- session, external_user_store, user_store, external_user, None
+ session,
+ external_user_store,
+ user_store,
+ external_user,
+ None,
+ viewer,
)
@@ -1483,6 +1541,7 @@ async def release_bridge_identity(
"""Drop a claim on a platform account, and any link to it still waiting to
be confirmed — your own, or someone else's if you are an admin. Anyone
else's claim on the same account is left standing."""
+ viewer = Principal(user.id, is_admin)
external_user = await _identity_on_bridge(
session, external_user_store, bridge_id, external_user_row_id
)
@@ -1517,7 +1576,12 @@ async def release_bridge_identity(
)
await session.commit()
return await _identity_summary(
- session, external_user_store, user_store, external_user, None
+ session,
+ external_user_store,
+ user_store,
+ external_user,
+ None,
+ viewer,
)
diff --git a/core/switch_core/gateway/connection_catalog.py b/core/switch_core/gateway/connection_catalog.py
index 1a8bba725..bb37b3fc2 100644
--- a/core/switch_core/gateway/connection_catalog.py
+++ b/core/switch_core/gateway/connection_catalog.py
@@ -51,6 +51,9 @@ async def catalog(
if definition.slug in connected
else "not_connected"
),
+ # The caller's own connection, while they have one and the
+ # route that ends it is on.
+ "can_revoke": enabled and definition.slug in connected,
}
)
return {"connections": entries}
diff --git a/core/switch_core/gateway/documents.py b/core/switch_core/gateway/documents.py
index aee3764d2..80d5fb8f6 100644
--- a/core/switch_core/gateway/documents.py
+++ b/core/switch_core/gateway/documents.py
@@ -1,13 +1,15 @@
from __future__ import annotations
-from typing import Annotated
+from typing import Annotated, Any
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.authz import (
Principal,
+ can,
can_delete_room_document,
+ can_manage,
can_unlink_from_room,
)
from switch_core.bridges.resource.service import ResourceService
@@ -46,6 +48,7 @@ router = APIRouter()
def _to_detail(
doc: Document,
+ reader: Principal,
*,
owner_name: str | None = None,
attached_rooms_count: int = 0,
@@ -71,11 +74,13 @@ def _to_detail(
created_by_agent_id=doc.created_by_agent_id,
created_by_agent_name=created_by_agent_name,
created_at=str(doc.created_at),
+ **_capabilities(reader, doc),
)
def _to_summary(
doc: Document,
+ reader: Principal,
*,
owner_name: str | None = None,
attached_rooms_count: int = 0,
@@ -100,9 +105,23 @@ def _to_summary(
created_by_agent_id=doc.created_by_agent_id,
created_by_agent_name=created_by_agent_name,
created_at=str(doc.created_at),
+ **_capabilities(reader, doc),
)
+def _capabilities(reader: Principal, doc: Document) -> dict[str, Any]:
+ """What `reader` may do with `doc` through the library routes, for its
+ detail or summary: nothing with a room's own document, which is changed
+ and removed in its room (`RoomDocumentDetail.can_remove`)."""
+ library = doc.room_id is None
+ manage = library and can_manage(reader, doc.owner_id)
+ return {
+ "can_edit": library and can(reader, "write", doc),
+ "can_manage": manage,
+ "can_transfer": manage,
+ }
+
+
def _can_remove(
principal: Principal, room: Room, doc: Document, *, takes_part: bool
) -> bool:
@@ -146,6 +165,7 @@ async def _enrich_summaries(
return [
_to_summary(
d,
+ reader,
owner_name=owners.get(d.owner_id) if d.owner_id else None,
attached_rooms_count=counts[d.id].attached,
hidden_rooms_count=counts[d.id].hidden,
@@ -180,6 +200,7 @@ async def _enrich_detail(
)
return _to_detail(
doc,
+ reader,
owner_name=owner.name if owner else None,
attached_rooms_count=counts[doc.id].attached,
hidden_rooms_count=counts[doc.id].hidden,
@@ -270,6 +291,31 @@ async def get_document(
)
+async def _refuse_room_document(
+ session: AsyncSession,
+ resource_service: ResourceService,
+ document_id: str,
+ user_id: str,
+ is_admin: bool,
+) -> None:
+ """Raise 409 for a room's own document, which is changed and removed in
+ its room, not here; first refusing whoever may not read it, as the change
+ itself would, so the refusal names nothing they couldn't see."""
+ try:
+ doc = await resource_service.get_document_for_user(
+ session, document_id, user_id, is_admin=is_admin
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=404, detail=str(e)) from e
+ except PermissionError as e:
+ raise HTTPException(status_code=403, detail=str(e)) from e
+ if doc.room_id is not None:
+ raise HTTPException(
+ status_code=409,
+ detail="This document belongs to a room: change or remove it in the room.",
+ )
+
+
@router.patch("/documents/{document_id}")
async def patch_document(
document_id: str,
@@ -281,6 +327,9 @@ async def patch_document(
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> DocumentDetail:
+ await _refuse_room_document(
+ session, resource_service, document_id, user.id, is_admin
+ )
try:
doc = await resource_service.update_document(
session,
@@ -317,6 +366,9 @@ async def delete_document(
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> DocumentDeleteResponse:
+ await _refuse_room_document(
+ session, resource_service, document_id, user.id, is_admin
+ )
affected_packages = await resource_service.list_packages_for_document(
session, document_id
)
diff --git a/core/switch_core/gateway/github_connections.py b/core/switch_core/gateway/github_connections.py
index 4f9944ac5..b0abf2914 100644
--- a/core/switch_core/gateway/github_connections.py
+++ b/core/switch_core/gateway/github_connections.py
@@ -454,7 +454,11 @@ async def connection_status(
status = 422 if error.code == CONNECTOR_REVOKED else error.status_code
raise HTTPException(status, error.message) from None
if token is None:
- return {"status": "not_connected", "install_url": github.install_url}
+ return {
+ "status": "not_connected",
+ "install_url": github.install_url,
+ "can_revoke": False,
+ }
try:
reach = await github.repositories(token)
except GitHubAuthorizationError as error:
@@ -473,6 +477,8 @@ async def connection_status(
# this sign-in: connecting again and authorizing them shows those.
"sso_hidden_organizations": reach.sso_hidden,
"install_url": github.install_url,
+ # The caller's own connection, theirs to disconnect.
+ "can_revoke": True,
}
diff --git a/core/switch_core/gateway/messaging_installs.py b/core/switch_core/gateway/messaging_installs.py
index bce1f9e5c..0e0403d74 100644
--- a/core/switch_core/gateway/messaging_installs.py
+++ b/core/switch_core/gateway/messaging_installs.py
@@ -34,7 +34,9 @@ from switch_core.bridges.collaboration.install import MessagingInstallError
from switch_core.bridges.collaboration.install_service import MessagingInstallService
from switch_core.db.audit import AuditAction, record_audit_event
from switch_core.db.models import MessagingInstall, Room, User, require_tenant_id
-from switch_core.db.stores.messaging_install_store import MessagingInstallNotFound
+from switch_core.db.stores.messaging_install_store import (
+ MessagingInstallNotFound,
+)
from switch_core.gateway.auth import get_current_user, get_tenant_is_admin
from switch_core.gateway.dependencies import get_install_service, get_session
@@ -97,6 +99,10 @@ class InstalledApp(BaseModel):
bridge_id: str | None
installed_at: datetime
ended_at: datetime | None
+ # Whether the caller may disconnect it (`_disconnect_refusal`). An ended
+ # one may still be: disconnecting it again answers it as it is, and
+ # whether there is anything left to disconnect is `status`.
+ can_disconnect: bool
class InstalledApps(BaseModel):
@@ -266,7 +272,14 @@ async def list_installs(
principal = Principal(user.id, is_admin)
return InstalledApps(
installs=[
- _installed(install, names.get(install.id))
+ _installed(
+ install,
+ names.get(install.id),
+ can_disconnect=_disconnect_refusal(
+ service, install.platform, rooms.get(install.id), principal
+ )
+ is None,
+ )
for install in await service.list_installs(session)
if is_admin
or (
@@ -283,7 +296,9 @@ def _room_allows(principal: Principal, action: Action, room: Room | None) -> boo
return room is None or can(principal, action, room)
-def _installed(install: MessagingInstall, name: str | None) -> InstalledApp:
+def _installed(
+ install: MessagingInstall, name: str | None, *, can_disconnect: bool
+) -> InstalledApp:
return InstalledApp(
id=install.id,
platform=install.platform,
@@ -294,9 +309,39 @@ def _installed(install: MessagingInstall, name: str | None) -> InstalledApp:
bridge_id=install.bridge_id,
installed_at=install.installed_at,
ended_at=install.ended_at,
+ can_disconnect=can_disconnect,
)
+def _disconnect_refusal(
+ service: MessagingInstallService,
+ platform: str,
+ room: Room | None,
+ principal: Principal,
+) -> str | None:
+ """Why `principal` may not disconnect an install, or None when they may.
+
+ An OAuth install, or a chat whose platform's installer is gone, is the
+ tenant's: an admin's. One chat of a claim-based platform is a room, and
+ whoever may write to that room may disconnect it, the same as moving the
+ room onto another bridge; once the room is gone, it is the tenant's again.
+ """
+ if not _installs_by_claim_or_gone(service, platform):
+ return None if principal.is_admin else "Tenant admin access required"
+ if room is None:
+ return (
+ None
+ if principal.is_admin
+ else "Only an admin can disconnect a chat whose room is gone."
+ )
+ if not can(principal, "write", room):
+ return (
+ "Only someone who can change this chat's room in Switch, its owner or "
+ "an admin, can disconnect it."
+ )
+ return None
+
+
def _installs_by_claim_or_gone(service: MessagingInstallService, platform: str) -> bool:
"""Whether a platform is claim-based; False once its installer is gone."""
try:
@@ -332,25 +377,15 @@ async def disconnect_install(
platform = await installs.install_platform(session, install_id=install_id)
except MessagingInstallNotFound as missing:
raise HTTPException(status_code=404, detail=str(missing)) from missing
- if not _installs_by_claim_or_gone(installs, platform):
- _require_tenant_admin(is_admin)
- else:
- room = (await installs.chat_rooms(session)).get(install_id)
- if room is None:
- # Nobody's room covers it any more, so it is the tenant's to decide.
- if not is_admin:
- raise HTTPException(
- status_code=403,
- detail="Only an admin can disconnect a chat whose room is gone.",
- )
- elif not can(Principal(user.id, is_admin), "write", room):
- raise HTTPException(
- status_code=403,
- detail=(
- "Only someone who can change this chat's room in Switch, its "
- "owner or an admin, can disconnect it."
- ),
- )
+ principal = Principal(user.id, is_admin)
+ refusal = _disconnect_refusal(
+ installs,
+ platform,
+ (await installs.chat_rooms(session)).get(install_id),
+ principal,
+ )
+ if refusal is not None:
+ raise HTTPException(status_code=403, detail=refusal)
try:
ended = await installs.disconnect(
tenant_id=require_tenant_id(), install_id=install_id
@@ -377,5 +412,11 @@ async def disconnect_install(
)
await session.commit()
logger.info("User %s disconnected messaging install %s", user.id, install_id)
- # Ended, so it has let go of whatever it was called.
- return _installed(ended, None)
+ # Ended, so it has let go of whatever it was called, and a chat has let go
+ # of its room (`chat_rooms`), which may leave it an admin's.
+ return _installed(
+ ended,
+ None,
+ can_disconnect=_disconnect_refusal(installs, ended.platform, None, principal)
+ is None,
+ )
diff --git a/core/switch_core/gateway/organizations.py b/core/switch_core/gateway/organizations.py
index 910e49606..2835b6c93 100644
--- a/core/switch_core/gateway/organizations.py
+++ b/core/switch_core/gateway/organizations.py
@@ -59,6 +59,7 @@ from switch_core.gateway.auth import (
organization_candidates,
organization_workspaces_bindable_by,
organizations_bindable_by,
+ rebind_if_left,
session_auth_time,
workspaces_in_organization,
workspaces_reached_through_organization,
@@ -122,8 +123,17 @@ router = APIRouter()
def _member_detail(
- user: User, member: OrganizationMember, warning: str | None
+ user: User,
+ member: OrganizationMember,
+ warning: str | None,
+ *,
+ access: _OrganizationAccess | None,
+ accepts_promotion: bool,
) -> OrganizationMemberDetail:
+ """`member`, with what the caller, who passes the role-change gate as
+ `access` says (None: they don't), may do with them: their own row
+ included, so an `org_admin` steps down or leaves while another remains."""
+ change = access is not None
return OrganizationMemberDetail(
user_id=user.id,
name=user.name,
@@ -131,9 +141,26 @@ def _member_detail(
role=member.role,
created_at=str(member.created_at),
warning=warning,
+ can_change_role=change,
+ can_grant_org_admin=change and accepts_promotion,
+ # Removing takes the organization's own admin; the operator restoring
+ # one is let through to change roles only.
+ can_remove=access is not None and not access.platform_access,
)
+def _accepts_promotion(
+ organization_directory: OrganizationDirectory, organization: Organization
+) -> bool:
+ """Whether someone may be made `org_admin` from Switch at all: not in an
+ organization whose members come from a directory Switch cannot change,
+ where that is done in the directory (`OrganizationDirectory.prepare_change`).
+ Whether the directory takes a given person is asked when it is done."""
+ return not organization_directory.keeps_members_of(
+ organization
+ ) or organization_directory.sends_changes_for(organization)
+
+
async def _current_organization_id(session: AsyncSession) -> str:
"""The bound workspace's organization id; 404 when it belongs to none."""
tenant = await session.get(Tenant, require_tenant_id())
@@ -152,19 +179,19 @@ class _OrganizationAccess(NamedTuple):
platform_access: bool
-async def require_organization_admin(
+async def organization_access(
session: AsyncSession,
user_store: UserStore,
organization_store: OrganizationStore,
user: User,
*,
operator_restores: bool,
-) -> _OrganizationAccess:
- """The bound workspace's organization, and how `user` got in; 403 unless
- they are its `org_admin`, 404 when the workspace belongs to no
+) -> _OrganizationAccess | None:
+ """How `user` gets into the bound workspace's organization as its admin,
+ or None when they don't; 404 when the workspace belongs to no
organization.
- With `operator_restores`, the platform operator passes too while the
+ With `operator_restores`, the platform operator gets in too while the
organization has no `org_admin`, so that someone can be made one. That is
the organization's own decision, not the workspace's: an operator who
administers the bound workspace by role still has no role here.
@@ -181,9 +208,30 @@ async def require_organization_admin(
and await organization_store.count_admins(session, organization_id) == 0
):
return _OrganizationAccess(organization_id, platform_access=True)
- raise HTTPException(
- status_code=403, detail="Only an organization admin may do this"
+ return None
+
+
+async def require_organization_admin(
+ session: AsyncSession,
+ user_store: UserStore,
+ organization_store: OrganizationStore,
+ user: User,
+ *,
+ operator_restores: bool,
+) -> _OrganizationAccess:
+ """`organization_access`, refused with 403 when there is none."""
+ access = await organization_access(
+ session,
+ user_store,
+ organization_store,
+ user,
+ operator_restores=operator_restores,
)
+ if access is None:
+ raise HTTPException(
+ status_code=403, detail="Only an organization admin may do this"
+ )
+ return access
@router.get("/organizations")
@@ -250,6 +298,7 @@ async def create_organization(
async def current_organization(
session: Annotated[AsyncSession, Depends(get_session)],
user_store: Annotated[UserStore, Depends(get_user_store)],
+ organization_store: Annotated[OrganizationStore, Depends(get_organization_store)],
organization_directory: Annotated[
OrganizationDirectory, Depends(get_organization_directory)
],
@@ -262,13 +311,19 @@ async def current_organization(
organization = await session.get(Organization, organization_id)
if organization is None:
raise HTTPException(status_code=404, detail="Organization not found")
+ role = await user_store.organization_role(session, require_tenant_id(), user.id)
return CurrentOrganizationResponse(
id=organization.id,
slug=organization.slug,
name=organization.name,
- role=await user_store.organization_role(session, require_tenant_id(), user.id),
+ role=role,
members_from_directory=organization_directory.keeps_members_of(organization),
directory_takes_changes=organization_directory.sends_changes_for(organization),
+ administers=role == ORGANIZATION_ADMIN_ROLE,
+ can_manage_members=await organization_access(
+ session, user_store, organization_store, user, operator_restores=True
+ )
+ is not None,
)
@@ -464,6 +519,9 @@ async def list_organization_members(
session: Annotated[AsyncSession, Depends(get_session)],
user_store: Annotated[UserStore, Depends(get_user_store)],
organization_store: Annotated[OrganizationStore, Depends(get_organization_store)],
+ organization_directory: Annotated[
+ OrganizationDirectory, Depends(get_organization_directory)
+ ],
user: Annotated[User, Depends(get_current_user)],
) -> list[OrganizationMemberDetail]:
"""Every member of the organization and their role in it. `org_admin` only:
@@ -472,9 +530,19 @@ async def list_organization_members(
session, user_store, organization_store, user, operator_restores=True
)
organization_id = access.organization_id
+ accepts_promotion = _accepts_promotion(
+ organization_directory, await _organization(session, organization_id)
+ )
members = await organization_store.list_members(session, organization_id)
return [
- _member_detail(member_user, member, None) for member_user, member in members
+ _member_detail(
+ member_user,
+ member,
+ None,
+ access=access,
+ accepts_promotion=accepts_promotion,
+ )
+ for member_user, member in members
]
@@ -583,6 +651,36 @@ async def _organization(session: AsyncSession, organization_id: str) -> Organiza
return organization
+async def _lock_admins_keeping_one(
+ session: AsyncSession,
+ organization_store: OrganizationStore,
+ organization_id: str,
+ user_id: str,
+ *,
+ last_admin: str,
+) -> OrganizationMember:
+ """Lock the organization's `org_admin` rows on `session` until the change
+ commits (`OrganizationStore.lock_admins`), and refuse, 409 `last_admin`,
+ if taking `user_id` out of the role would leave none.
+
+ Taken once the directory has been asked what the change needs, which lets
+ go of the request's transaction (`_member_change`), and before anything is
+ changed or taken away; held to the commit. Of two admins demoting or
+ removing each other at once, the second then counts after the first has
+ committed, and is refused with nothing of the other's touched. Nothing
+ after it may commit before the change. Returns their membership as it
+ stands once locked: the other may have changed it meanwhile."""
+ admins = await organization_store.lock_admins(session, organization_id)
+ member = await session.get(
+ OrganizationMember, (organization_id, user_id), populate_existing=True
+ )
+ if member is None:
+ raise HTTPException(status_code=404, detail="Not a member of this organization")
+ if member.role == ORGANIZATION_ADMIN_ROLE and admins <= 1:
+ raise HTTPException(status_code=409, detail=last_admin)
+ return member
+
+
async def _end_access_through_organization(
session_factory: async_sessionmaker[AsyncSession],
*,
@@ -627,6 +725,7 @@ async def _end_access_through_organization(
@router.patch("/organizations/current/members/{user_id}", response_model=None)
async def update_organization_member_role(
request: Request,
+ response: Response,
user_id: str,
req: OrganizationMemberUpdateRequest,
session: Annotated[AsyncSession, Depends(get_session)],
@@ -646,9 +745,12 @@ async def update_organization_member_role(
OrganizationToken | None, Depends(directory_access_token)
],
user: Annotated[User, Depends(get_current_user)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
) -> OrganizationMemberDetail | JSONResponse:
"""Make a member `org_admin`, or an `org_admin` a `member`. `org_admin` only,
- the one role that grants `org_admin`.
+ the one role that grants `org_admin`; their own role included, so an
+ `org_admin` steps down while another remains, and the session moves off
+ a workspace they could enter only as one (`rebind_if_left`).
Refuses to demote the last `org_admin`: nobody else could grant the role
again. Demoting someone first takes away what they hold in the workspaces
@@ -663,17 +765,15 @@ async def update_organization_member_role(
member = await session.get(OrganizationMember, (organization_id, user_id))
if member is None:
raise HTTPException(status_code=404, detail="Not a member of this organization")
- demoting = (
- member.role == ORGANIZATION_ADMIN_ROLE and req.role != ORGANIZATION_ADMIN_ROLE
- )
- last_admin = HTTPException(
- status_code=409, detail="Cannot demote the last organization admin"
- )
+ last_admin = "Cannot demote the last organization admin"
+ # Before the directory is asked, so the plain case costs no sign-in; the
+ # count that decides is taken under the lock below.
if (
- demoting
+ member.role == ORGANIZATION_ADMIN_ROLE
+ and req.role != ORGANIZATION_ADMIN_ROLE
and await organization_store.count_admins(session, organization_id) <= 1
):
- raise last_admin
+ raise HTTPException(status_code=409, detail=last_admin)
organization = await _organization(session, organization_id)
member_change = (
await _member_change(
@@ -689,12 +789,21 @@ async def update_organization_member_role(
if member.role != req.role
else NO_DIRECTORY_CHANGE
)
+ if member.role == ORGANIZATION_ADMIN_ROLE and req.role != ORGANIZATION_ADMIN_ROLE:
+ member = await _lock_admins_keeping_one(
+ session,
+ organization_store,
+ organization_id,
+ user_id,
+ last_admin=last_admin,
+ )
+ demoting = (
+ member.role == ORGANIZATION_ADMIN_ROLE and req.role != ORGANIZATION_ADMIN_ROLE
+ )
warning = None
if demoting:
- # Let go of the request's connection while each workspace is worked on
- # on a session of its own.
- await session.commit()
+ # On sessions of its own, while this one holds the admins' lock.
try:
warning = await _end_access_through_organization(
session_factory,
@@ -712,15 +821,6 @@ async def update_organization_member_role(
)
except ServiceError as error:
return service_refusal(error)
- if await organization_store.lock_admins(session, organization_id) <= 1:
- raise last_admin
- member = await session.get(
- OrganizationMember, (organization_id, user_id), populate_existing=True
- )
- if member is None:
- raise HTTPException(
- status_code=404, detail="Not a member of this organization"
- )
if member.role != req.role:
await _ask_directory(
@@ -749,12 +849,27 @@ async def update_organization_member_role(
target = await user_store.get(session, user_id)
assert target is not None
- return _member_detail(target, member, warning)
+ if user_id == user.id:
+ await rebind_if_left(
+ request, response, session_factory, user_store, user, config
+ )
+ return _member_detail(
+ target,
+ member,
+ warning,
+ # Read again: the change may be what let the caller in, or the
+ # operator's way in may have closed with it.
+ access=await organization_access(
+ session, user_store, organization_store, user, operator_restores=True
+ ),
+ accepts_promotion=_accepts_promotion(organization_directory, organization),
+ )
@router.delete("/organizations/current/members/{user_id}", response_model=None)
async def remove_organization_member(
request: Request,
+ response: Response,
user_id: str,
session: Annotated[AsyncSession, Depends(get_session)],
session_factory: Annotated[
@@ -773,8 +888,11 @@ async def remove_organization_member(
OrganizationToken | None, Depends(directory_access_token)
],
user: Annotated[User, Depends(get_current_user)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
) -> dict | JSONResponse:
- """Remove someone from the organization. `org_admin` only.
+ """Remove someone from the organization. `org_admin` only, themselves
+ included, so an `org_admin` leaves while another remains; the session
+ then moves off a workspace they could enter only as one (`rebind_if_left`).
Refuses while they still belong to any of its workspaces, naming them:
leaving a workspace revokes their keys and connections there and refuses
@@ -792,19 +910,14 @@ async def remove_organization_member(
member = await session.get(OrganizationMember, (organization_id, user_id))
if member is None:
raise HTTPException(status_code=404, detail="Not a member of this organization")
- last_admin = HTTPException(
- status_code=409, detail="Cannot remove the last organization admin"
- )
- was_admin = member.role == ORGANIZATION_ADMIN_ROLE
+ last_admin = "Cannot remove the last organization admin"
+ # As for a demotion: early, then decided under the lock below.
if (
- was_admin
+ member.role == ORGANIZATION_ADMIN_ROLE
and await organization_store.count_admins(session, organization_id) <= 1
):
- raise last_admin
+ raise HTTPException(status_code=409, detail=last_admin)
organization = await _organization(session, organization_id)
- # Let go of the request's connection while each workspace is read on a
- # session of its own.
- await session.commit()
workspaces = await workspaces_in_organization(
session_factory, user_id, organization_id
@@ -825,6 +938,15 @@ async def remove_organization_member(
user_id,
None,
)
+ if member.role == ORGANIZATION_ADMIN_ROLE:
+ member = await _lock_admins_keeping_one(
+ session,
+ organization_store,
+ organization_id,
+ user_id,
+ last_admin=last_admin,
+ )
+ was_admin = member.role == ORGANIZATION_ADMIN_ROLE
warning = None
if was_admin:
try:
@@ -845,14 +967,6 @@ async def remove_organization_member(
except ServiceError as error:
return service_refusal(error)
- admins = await organization_store.lock_admins(session, organization_id)
- member = await session.get(
- OrganizationMember, (organization_id, user_id), populate_existing=True
- )
- if member is None:
- raise HTTPException(status_code=404, detail="Not a member of this organization")
- if member.role == ORGANIZATION_ADMIN_ROLE and admins <= 1:
- raise last_admin
await _ask_directory(
organization_directory.remove,
organization,
@@ -877,4 +991,8 @@ async def remove_organization_member(
details={"role": role, **_made_from(access)},
)
await session.commit()
+ if user_id == user.id:
+ await rebind_if_left(
+ request, response, session_factory, user_store, user, config
+ )
return {"ok": True, "warning": warning}
diff --git a/core/switch_core/gateway/packages.py b/core/switch_core/gateway/packages.py
index 31fe374c5..863d57480 100644
--- a/core/switch_core/gateway/packages.py
+++ b/core/switch_core/gateway/packages.py
@@ -5,7 +5,7 @@ from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
-from switch_core.authz import Principal, can
+from switch_core.authz import Principal, can, can_manage
from switch_core.bridges.resource.service import ResourceService
from switch_core.db.models import Package, User
from switch_core.db.stores.agent_store import AgentStore
@@ -43,6 +43,7 @@ router = APIRouter()
def _to_detail(
pkg: Package,
+ reader: Principal,
*,
owner_name: str | None = None,
references_count: int = 0,
@@ -64,6 +65,9 @@ def _to_detail(
attached_rooms_count=attached_rooms_count,
hidden_rooms_count=hidden_rooms_count,
created_at=str(pkg.created_at),
+ can_read=can(reader, "read", pkg),
+ can_edit=can(reader, "write", pkg),
+ can_manage=can_manage(reader, pkg.owner_id),
)
@@ -91,6 +95,7 @@ async def _enrich(
return [
_to_detail(
p,
+ reader,
owner_name=owners.get(p.owner_id),
references_count=ref_counts.get(p.id, 0),
documents_count=doc_counts.get(p.id, 0),
@@ -441,10 +446,9 @@ async def list_room_packages(
) -> list[PackageDetail]:
await require_room_access(session, room_store, room_id, user, "read", is_admin)
pkgs = await resource_service.list_room_packages(session, room_id)
- principal = Principal(user.id, is_admin)
- readable = {p.id for p in pkgs if can(principal, "read", p)}
- details = await _enrich(session, pkgs, resource_service, user_store, principal)
- return [d.model_copy(update={"can_read": d.id in readable}) for d in details]
+ return await _enrich(
+ session, pkgs, resource_service, user_store, Principal(user.id, is_admin)
+ )
@router.post("/rooms/{room_id}/packages/{package_id}", status_code=201)
diff --git a/core/switch_core/gateway/references.py b/core/switch_core/gateway/references.py
index 095e230c1..14adcdb0f 100644
--- a/core/switch_core/gateway/references.py
+++ b/core/switch_core/gateway/references.py
@@ -5,7 +5,7 @@ from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
-from switch_core.authz import Principal
+from switch_core.authz import Principal, can, can_manage
from switch_core.bridges.resource.registry import ReferenceValue, is_builtin_type
from switch_core.bridges.resource.service import (
ReferenceTypeInUseError,
@@ -47,6 +47,7 @@ router = APIRouter()
def _to_detail(
ref: Reference,
+ reader: Principal,
*,
owner_name: str | None = None,
type_display_name: str | None = None,
@@ -70,6 +71,8 @@ def _to_detail(
packages=packages or [],
created_at=str(ref.created_at),
type_display_name=type_display_name,
+ can_edit=can(reader, "write", ref),
+ can_manage=can_manage(reader, ref.owner_id),
)
@@ -100,6 +103,7 @@ async def _enrich(
return [
_to_detail(
r,
+ reader,
owner_name=owners.get(r.owner_id),
type_display_name=type_names.get(r.type),
attached_rooms_count=counts[r.id].attached,
@@ -146,7 +150,7 @@ def _type_to_info(view: ReferenceTypeView, owner_name: str | None) -> ReferenceT
def _type_to_detail(
- entry: ReferenceTypeRow, owner_name: str | None
+ entry: ReferenceTypeRow, owner_name: str | None, reader: Principal
) -> ReferenceTypeDetail:
row = entry.row
return ReferenceTypeDetail(
@@ -162,6 +166,8 @@ def _type_to_detail(
write_visibility=row.write_visibility,
shadowed_by_builtin=entry.shadowed_by_builtin,
created_at=str(row.created_at),
+ can_edit=can(reader, "write", row),
+ can_manage=can_manage(reader, row.owner_id),
)
@@ -203,7 +209,8 @@ async def list_owned_reference_types(
session, user_id=user.id, is_admin=is_admin
)
owners = await _owner_names(session, user_store, {e.row.owner_id for e in rows})
- return [_type_to_detail(e, owners.get(e.row.owner_id)) for e in rows]
+ reader = Principal(user.id, is_admin)
+ return [_type_to_detail(e, owners.get(e.row.owner_id), reader) for e in rows]
@router.post("/references/reference-types", status_code=201)
@@ -229,9 +236,11 @@ async def create_reference_type(
raise HTTPException(status_code=400, detail=str(e)) from e
await session.commit()
owners = await _owner_names(session, user_store, {row.owner_id})
+ # Its creator owns it, which is all either flag asks.
return _type_to_detail(
ReferenceTypeRow(row=row, shadowed_by_builtin=False),
owners.get(row.owner_id),
+ Principal(user.id, False),
)
@@ -266,6 +275,7 @@ async def patch_reference_type(
return _type_to_detail(
ReferenceTypeRow(row=row, shadowed_by_builtin=is_builtin_type(row.type)),
owners.get(row.owner_id),
+ Principal(user.id, is_admin),
)
diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.py
index d58096b47..9e05e0a77 100644
--- a/core/switch_core/gateway/rooms.py
+++ b/core/switch_core/gateway/rooms.py
@@ -9,11 +9,13 @@ from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy.ext.asyncio import AsyncSession
+from switch_core.accounts.transfer import kind_refusal
from switch_core.agent_templates import plan_template
from switch_core.authz import (
Action,
Principal,
can,
+ can_manage,
can_unlink_from_room,
)
from switch_core.bridges.agent.operations.agent_management import management_port
@@ -76,7 +78,14 @@ from switch_core.gateway.schemas import (
RoomUsersRequest,
)
from switch_core.gateway.templates import readable_template
-from switch_core.room_service import RoleSpec, RoomCreateConfig, RoomService
+from switch_core.room_service import (
+ FIXED_MEMBERSHIP,
+ MembershipFixed,
+ RoleSpec,
+ RoomCreateConfig,
+ RoomService,
+ require_membership_changeable_from_outside,
+)
from switch_core.rooms_yaml import (
GroupProvisionResult,
GroupSpec,
@@ -103,6 +112,15 @@ logger = logging.getLogger(__name__)
router = APIRouter()
+def _refuse_fixed_membership(room: Room) -> None:
+ """409 for a direct or group conversation, whose agents and people these
+ routes don't change (`require_membership_changeable_from_outside`)."""
+ try:
+ require_membership_changeable_from_outside(room)
+ except MembershipFixed as e:
+ raise HTTPException(status_code=409, detail=str(e)) from e
+
+
async def _require_room_released(
session: AsyncSession,
room_store: RoomStore,
@@ -246,9 +264,24 @@ async def _build_room_detail(
can_write=can(principal, "write", room),
can_manage=can(principal, "delete", room),
can_unlink=can_unlink_from_room(principal, takes_part=takes_part),
+ can_transfer=_can_transfer(principal, room),
+ can_change_members=_can_change_members(principal, room),
)
+def _can_change_members(principal: Principal, room: Room) -> bool:
+ """Whether `principal` may add and remove the room's agents and people
+ through these routes: write access, unless it is a direct or group
+ conversation (`_refuse_fixed_membership`)."""
+ return can(principal, "write", room) and room.channel_type not in FIXED_MEMBERSHIP
+
+
+def _can_transfer(principal: Principal, room: Room) -> bool:
+ """Whether `principal` may hand `room` to another member, as
+ `POST /ownership/transfer` decides it."""
+ return can_manage(principal, room.owner_id) and kind_refusal(room) is None
+
+
async def _list_room_role_details(
session: AsyncSession, room_id: str, protocol: AgentCore
) -> list[RoomRoleDetail]:
@@ -393,6 +426,8 @@ async def list_rooms(
can_unlink=can_unlink_from_room(
principal, takes_part=room.id in involved
),
+ can_transfer=_can_transfer(principal, room),
+ can_change_members=_can_change_members(principal, room),
)
)
@@ -1182,7 +1217,9 @@ async def post_room_agents(
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> RoomDetail:
principal = Principal(user.id, is_admin)
- await _require_room_released(session, room_store, room_id, principal, "write")
+ _refuse_fixed_membership(
+ await _require_room_released(session, room_store, room_id, principal, "write")
+ )
try:
await room_service.add_agents_to_room(
room_id,
@@ -1257,7 +1294,9 @@ async def delete_room_agent(
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> RoomDetail:
principal = Principal(user.id, is_admin)
- await _require_room_released(session, room_store, room_id, principal, "write")
+ _refuse_fixed_membership(
+ await _require_room_released(session, room_store, room_id, principal, "write")
+ )
try:
await room_service.remove_agents_from_room(room_id, [agent_id])
except ValueError as e:
@@ -1291,7 +1330,9 @@ async def post_room_users(
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> RoomDetail:
principal = Principal(user.id, is_admin)
- await _require_room_released(session, room_store, room_id, principal, "write")
+ _refuse_fixed_membership(
+ await _require_room_released(session, room_store, room_id, principal, "write")
+ )
try:
await room_service.add_users_to_room(room_id, req.user_names)
except ValueError as e:
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 4d30a2419..2b622df40 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -94,13 +94,19 @@ class RoomSummary(BaseModel):
is_console_chat: bool = False
# What the caller may do with it, so a client offers a change only where
# the server would allow it. `can_write` covers its settings, roles,
- # participants, links and attaching resources; `can_manage` (owner or
- # tenant admin) covers its access, deleting it and taking the platform
- # channel's name; `can_unlink` (taking part in it, or tenant admin) covers
- # unlinking a reference, document or package from it.
+ # links and attaching resources; `can_change_members` covers adding and
+ # removing its agents and people, which is `can_write` unless it is a
+ # direct or group conversation, whose platform fixes who is in it;
+ # `can_manage` (owner or tenant admin) covers its access, deleting it and
+ # taking the platform channel's name; `can_unlink` (taking part in it, or
+ # tenant admin) covers unlinking a reference, document or package from it;
+ # `can_transfer` is `can_manage` for anything but a chat, which stays with
+ # its people.
can_write: bool
+ can_change_members: bool
can_manage: bool
can_unlink: bool
+ can_transfer: bool
class RoomDetail(RoomSummary):
@@ -307,11 +313,6 @@ class AgentSummary(BaseModel):
# owner-restricted without fetching each one — the console warns about
# exactly that, and per-agent reads would make it a request storm.
addressing_policy: AddressingPolicy | None = None
- # Whether the caller may manage the agent (rename it, edit its options and
- # who may address it): its owner or a workspace admin. Decided here by
- # `switch_core.authz` so the Gateway does not repeat the rule; set by the
- # Gateway routes, and left out of what agents read.
- can_manage: bool = False
class AgentToolSummary(BaseModel):
@@ -380,6 +381,49 @@ class AgentDetail(AgentSummary):
children: list[AgentSummary]
+class AgentCapabilities(BaseModel):
+ """What the caller may do with an agent, as the Gateway reports it.
+
+ On Gateway-only models rather than on `AgentSummary`, which the agent
+ tools share, so an agent never reads them. Each is decided by the rule its
+ route enforces, so no client repeats it.
+ """
+
+ # Edit its icon, display name, description and who may address it, and
+ # delete it: its owner or a workspace admin.
+ can_manage: bool
+ # Edit its options: `can_manage`, for an agent Switch Console runs from a
+ # spec it knows. Any other agent has no options to edit.
+ can_edit_options: bool
+ # Change its name: `can_manage`, unless it is a sub-agent, whose name
+ # comes from its parent's, or has sub-agents named after it. A sub-agent's
+ # display name is still covered by `can_manage`.
+ can_rename: bool
+ # Hand it to another member: `can_manage`, unless it is tied to its owner
+ # by more than its owner id (`accounts/transfer.py`).
+ can_transfer: bool
+ # Why it can't be handed over, set only when `can_manage` is true and
+ # `can_transfer` false. Only its owner is told which services it uses.
+ transfer_blocked_reason: str | None
+
+
+class GatewayAgentSummary(AgentSummary, AgentCapabilities):
+ pass
+
+
+class GatewayAgentDetail(AgentDetail, AgentCapabilities):
+ # Its owner only, not an admin: turning on that it may manage its
+ # owner's agents.
+ can_change_manage_agents: bool
+ # Granting it service access: its owner only, since a grant is made on
+ # the owner's own connections, while service connections are switched on,
+ # and for an agent Switch Console runs from a spec it knows, since nothing
+ # else would start its service tools. Seeing and revoking the grants it
+ # already has needs only the first two.
+ can_grant_services: bool
+ children: list[GatewayAgentSummary] # type: ignore[assignment] # narrows the base type
+
+
class NamedEntry(BaseModel):
"""An id a policy names, with the name a person would know it by.
@@ -484,7 +528,7 @@ class RenameAgentResponse(BaseModel):
`templates_mentioning_old_name` lists saved templates whose text still
says the old name."""
- agent: AgentSummary
+ agent: GatewayAgentSummary
old_name: str
bridge_failures: list[str]
templates_mentioning_old_name: list[str]
@@ -626,6 +670,11 @@ class ApiKeyDetail(BaseModel):
key_prefix: str
created_at: str
expires_at: datetime | None
+ # What the caller may do with it: reveal and copy it, their own only; and
+ # delete it, their own unless an agent still signs in with it
+ # (`authz.can_delete_api_key`).
+ can_reveal: bool
+ can_delete: bool
class CreateApiKeyResponse(BaseModel):
@@ -699,6 +748,12 @@ class BridgeDetail(BaseModel):
# which is then what stands between this connection and its events.
receives_webhooks: bool = False
webhook_url: str | None = None
+ # What the caller may do with it: change its settings, Teams placement
+ # and confirmation rules, or delete it — a workspace admin. That chats
+ # still connected through it must be disconnected first is answered when
+ # it is deleted.
+ can_manage: bool
+ can_delete: bool
class BridgeUpdateRequest(BaseModel):
@@ -770,6 +825,9 @@ class IdentityClaimant(BaseModel):
# False for a claim made before accounts had to confirm their links
# (CHOO-3881). It still counts, and its owner is asked to confirm it.
verified: bool
+ # Whether the caller may drop this claim: their own, or anyone's for an
+ # admin.
+ can_unlink: bool
class LinkCode(BaseModel):
@@ -983,6 +1041,15 @@ Email = Annotated[
]
+class OperatorUserResponse(UserResponse):
+ """An account as the deployment operator manages it. `can_delete`: not
+ their own, which they delete from their account settings, and not the
+ server's administrator account (`accounts.deletion.is_server_administrator`).
+ What else stands in the way is answered when it is asked."""
+
+ can_delete: bool
+
+
class CreateUserRequest(BaseModel):
name: str
email: Email
@@ -1066,9 +1133,17 @@ class OperatorWorkspaceResponse(BaseModel):
class CurrentTenantResponse(TenantMembershipResponse):
"""The tenant this request is bound to. `administers` is whether the
caller may manage it — an `admin` membership, `org_admin` of its
- organization, or the operator bit, which no membership role shows."""
+ organization, or the operator bit, which no membership role shows.
+ `can_delete` is whether they may delete it (`authz.can_delete_workspace`):
+ by their own admin membership, never the server's default workspace.
+ `can_manage_data_protection` is whether they may set its messages to be
+ deleted, list the people seen in it and erase them: by their own admin
+ membership too (`authz.admin_by_own_membership`); reading and clearing
+ its retention window takes `administers` only."""
administers: bool
+ can_delete: bool
+ can_manage_data_protection: bool
class TenantCreateRequest(BaseModel):
@@ -1104,6 +1179,11 @@ class CurrentOrganizationResponse(BaseModel):
role: str | None
members_from_directory: bool
directory_takes_changes: bool
+ # Whether the caller is its `org_admin`, and whether they may manage its
+ # members and read its issues: its `org_admin`, or the platform operator
+ # while it has none, to make one.
+ administers: bool
+ can_manage_members: bool
class OrganizationIssueDetail(BaseModel):
@@ -1342,6 +1422,15 @@ class MemberDetail(BaseModel):
service_account: bool
organization_role: str | None
via_organization: bool
+ # What the caller may do with this member (`authz.can_change_workspace_member`):
+ # an admin of the workspace, their own row included, never on an
+ # organization admin's. That the last admin stays and that someone still
+ # owning agents can't be removed is checked when it is asked.
+ can_change_role: bool
+ can_remove: bool
+ # Whether the caller may hand them something they own: a member of the
+ # workspace by their own membership, and not the caller.
+ can_receive_transfer: bool
class UsageTotalResponse(BaseModel):
@@ -1372,6 +1461,16 @@ class OrganizationMemberDetail(BaseModel):
# What could not be revoked at a vendor when a demotion took away what
# they held in workspaces they were in only as `org_admin`.
warning: str | None
+ # What the caller may do with them, their own row included:
+ # `can_change_role` for whoever passes the role route's gate, the
+ # operator restoring an `org_admin` included;
+ # `can_grant_org_admin` too, unless the organization's members come from
+ # a directory Switch cannot change; `can_remove` for its `org_admin` only.
+ # The last `org_admin`, someone still in a workspace, and a directory that
+ # wants a sign-in first are answered when it is asked.
+ can_change_role: bool
+ can_grant_org_admin: bool
+ can_remove: bool
class OrganizationMemberUpdateRequest(BaseModel):
@@ -1469,6 +1568,12 @@ class ReferenceDetail(BaseModel):
# Resolved server-side, unfiltered by the type's visibility: the caller can
# already read the raw slug. Null when the slug resolves to no type at all.
type_display_name: str | None = None
+ # What the caller may do with it (`switch_core.authz`). `can_edit`: change
+ # it — its owner, an admin, or anyone when it is publicly writable.
+ # `can_manage`: delete it, change who may see or edit it, transfer it — its
+ # owner or an admin.
+ can_edit: bool
+ can_manage: bool
class ReferenceCreateRequest(BaseModel):
@@ -1530,6 +1635,10 @@ class ReferenceTypeDetail(BaseModel):
write_visibility: str
shadowed_by_builtin: bool
created_at: str
+ # As on `ReferenceDetail`. A built-in is never listed here, so never
+ # offered for editing.
+ can_edit: bool
+ can_manage: bool
class ReferenceTypeCreateRequest(BaseModel):
@@ -1672,6 +1781,12 @@ class DocumentDetail(BaseModel):
created_by_agent_id: str | None = None
created_by_agent_name: str | None = None
created_at: str
+ # As on `ReferenceDetail`, and `can_transfer`, which `can_manage` gives.
+ # All three are false for a room's own document, which is changed and
+ # removed in its room, not through the library.
+ can_edit: bool
+ can_manage: bool
+ can_transfer: bool
# Whether the caller may remove a document from a room it is in: delete it if
@@ -1705,6 +1820,10 @@ class DocumentSummary(BaseModel):
created_by_agent_id: str | None = None
created_by_agent_name: str | None = None
created_at: str
+ # As on `DocumentDetail`.
+ can_edit: bool
+ can_manage: bool
+ can_transfer: bool
class RoomDocumentSummary(DocumentSummary):
@@ -1761,7 +1880,10 @@ class PackageDetail(BaseModel):
# packages the caller may read, except a room's package list: a private
# package its owner attached is listed to every reader of the room, and the
# Gateway shows that one without a link.
- can_read: bool = True
+ can_read: bool
+ # As on `ReferenceDetail`.
+ can_edit: bool
+ can_manage: bool
class PackageCreateRequest(BaseModel):
diff --git a/core/switch_core/gateway/service_connections.py b/core/switch_core/gateway/service_connections.py
index 5e3cd24db..845e3a8ae 100644
--- a/core/switch_core/gateway/service_connections.py
+++ b/core/switch_core/gateway/service_connections.py
@@ -157,6 +157,9 @@ async def list_service_connections(
"external_identity": (
None if connection is None else connection.external_identity
),
+ # Whether the caller may disconnect it: their own connection,
+ # the only one listed here, while they have one.
+ "can_revoke": connection is not None,
}
)
return {"connections": entries}
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.py
index 89635c62b..ba63192f0 100644
--- a/core/switch_core/gateway/tenants.py
+++ b/core/switch_core/gateway/tenants.py
@@ -17,7 +17,10 @@ from switch_core.accounts.workspace_deletion import (
from switch_core.authz import (
ORGANIZATION_ADMIN_ROLE,
ORGANIZATION_ADMIN_TENANT_ROLE,
+ admin_by_own_membership,
administers_tenant,
+ can_change_workspace_member,
+ can_delete_workspace,
effective_tenant_role,
)
from switch_core.bridges.agent.protocol.agent_core import AgentCore
@@ -38,6 +41,7 @@ from switch_core.db.audit import (
)
from switch_core.db.models import (
MAX_MESSAGE_RETENTION_DAYS,
+ TENANT_ZERO_ID,
Invitation,
Organization,
OrganizationMember,
@@ -80,9 +84,11 @@ from switch_core.gateway.auth import (
get_authenticated_caller,
get_authenticated_user_id,
get_current_user,
+ get_tenant_is_admin,
initial_tenant_claim,
list_tenant_memberships,
may_bind_tenant,
+ rebind_if_left,
record_operator_entry,
require_tenant_admin,
session_auth_time,
@@ -216,8 +222,17 @@ def _invitation_detail(invitation: Invitation) -> InvitationDetail:
def _member_detail(
- user: User, membership: TenantMember, organization_role: str | None
+ user: User,
+ membership: TenantMember,
+ organization_role: str | None,
+ *,
+ caller_id: str,
+ administers: bool,
) -> MemberDetail:
+ may_change = can_change_workspace_member(
+ administers=administers,
+ member_is_organization_admin=organization_role == ORGANIZATION_ADMIN_ROLE,
+ )
return MemberDetail(
user_id=user.id,
name=user.name,
@@ -227,6 +242,9 @@ def _member_detail(
service_account=is_bootstrap_owner(user),
organization_role=organization_role,
via_organization=False,
+ can_change_role=may_change,
+ can_remove=may_change,
+ can_receive_transfer=user.id != caller_id,
)
@@ -345,6 +363,10 @@ async def current_tenant(
tenant_role=tenant_role,
organization_role=organization_role,
),
+ can_delete=can_delete_workspace(
+ tenant_role=tenant_role, is_default=tenant.id == TENANT_ZERO_ID
+ ),
+ can_manage_data_protection=admin_by_own_membership(tenant_role),
)
@@ -416,7 +438,9 @@ async def delete_tenant(
is exactly one.
"""
_require_bound_tenant(tenant_id)
- if await user_store.tenant_role(session, tenant_id, user.id) != "admin":
+ if not admin_by_own_membership(
+ await user_store.tenant_role(session, tenant_id, user.id)
+ ):
raise HTTPException(
status_code=403, detail="Only a workspace admin may delete the workspace"
)
@@ -961,7 +985,9 @@ async def _require_admin_membership(
deleted, takes, like deleting the workspace, the caller's own admin
membership: not the deployment operator's bypass, and not an organization
admin acting as one. `action` completes "Only a workspace admin may"."""
- if await user_store.tenant_role(session, tenant_id, user.id) != "admin":
+ if not admin_by_own_membership(
+ await user_store.tenant_role(session, tenant_id, user.id)
+ ):
raise HTTPException(
status_code=403, detail=f"Only a workspace admin may {action}"
)
@@ -1159,6 +1185,8 @@ async def revoke_invitation(
invitation = await invitation_store.revoke(session, invitation_id)
except ValueError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except InvitationNotUsableError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
await record_audit_event(
session,
tenant_id=tenant_id,
@@ -1689,42 +1717,55 @@ async def list_members(
session: Annotated[AsyncSession, Depends(get_session)],
user_store: Annotated[UserStore, Depends(get_user_store)],
organization_store: Annotated[OrganizationStore, Depends(get_organization_store)],
- _user: Annotated[User, Depends(get_current_user)],
+ user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> list[MemberDetail]:
"""Every member of the bound tenant, then every `org_admin` of its
organization who is not one, as `admin` via the organization. Any member
may list their own workspace's roster; changing or removing one is
admin-gated below."""
+ caller_id = user.id
_require_bound_tenant(tenant_id)
tenant = await session.get(Tenant, tenant_id)
organization_roles: dict[str, str] = {}
organization_admins: list[tuple[User, OrganizationMember]] = []
if tenant is not None and tenant.organization_id is not None:
- for user, member in await organization_store.list_members(
+ for person, member in await organization_store.list_members(
session, tenant.organization_id
):
- organization_roles[user.id] = member.role
+ organization_roles[person.id] = member.role
if member.role == ORGANIZATION_ADMIN_ROLE:
- organization_admins.append((user, member))
+ organization_admins.append((person, member))
members = await user_store.list_tenant_members(session)
roster = [
- _member_detail(user, membership, organization_roles.get(user.id))
- for user, membership in members
+ _member_detail(
+ person,
+ membership,
+ organization_roles.get(person.id),
+ caller_id=caller_id,
+ administers=is_admin,
+ )
+ for person, membership in members
]
- listed = {user.id for user, _ in members}
+ listed = {person.id for person, _ in members}
roster.extend(
MemberDetail(
- user_id=user.id,
- name=user.name,
- email=user.email,
+ user_id=person.id,
+ name=person.name,
+ email=person.email,
role=ORGANIZATION_ADMIN_TENANT_ROLE,
created_at=str(member.created_at),
- service_account=is_bootstrap_owner(user),
+ service_account=is_bootstrap_owner(person),
organization_role=member.role,
via_organization=True,
+ # Changed only through the organization's members; and a transfer
+ # needs a membership here, which they don't hold.
+ can_change_role=False,
+ can_remove=False,
+ can_receive_transfer=False,
)
- for user, member in organization_admins
- if user.id not in listed
+ for person, member in organization_admins
+ if person.id not in listed
)
return roster
@@ -1738,7 +1779,8 @@ async def update_member_role(
user_store: Annotated[UserStore, Depends(get_user_store)],
admin: Annotated[User, Depends(require_tenant_admin)],
) -> MemberDetail:
- """Change a member's role. Admins only.
+ """Change a member's role. Admins only, their own included, so an admin
+ steps down while another remains.
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.
@@ -1774,15 +1816,21 @@ async def update_member_role(
user,
membership,
await user_store.organization_role(session, tenant_id, user_id),
+ caller_id=admin.id,
+ administers=True,
)
@router.delete("/tenants/{tenant_id}/members/{user_id}", response_model=None)
async def remove_member(
request: Request,
+ response: Response,
tenant_id: str,
user_id: str,
session: Annotated[AsyncSession, Depends(get_session)],
+ session_factory: Annotated[
+ async_sessionmaker[AsyncSession], Depends(get_session_factory)
+ ],
user_store: Annotated[UserStore, Depends(get_user_store)],
agent_store: Annotated[AgentStore, Depends(get_agent_store)],
api_key_store: Annotated[ApiKeyStore, Depends(get_api_key_store)],
@@ -1791,7 +1839,9 @@ async def remove_member(
config: Annotated[SwitchConfig, Depends(get_config)],
broker: Annotated[ServiceBroker, Depends(get_service_broker)],
) -> dict | JSONResponse:
- """Remove a member from the bound tenant. Admins only.
+ """Remove a member from the bound tenant. Admins only, their own
+ membership included, so an admin leaves while another remains; the
+ session then moves off the workspace (`rebind_if_left`).
Refuses to remove the last admin, as demoting one does.
@@ -1874,4 +1924,8 @@ async def remove_member(
await session.commit()
warning = await revocation.finish(session, user_id, revoked)
+ if user_id == admin.id:
+ await rebind_if_left(
+ request, response, session_factory, user_store, admin, config
+ )
return {"ok": True, "warning": warning}
diff --git a/core/switch_core/management/gateway_routes.py b/core/switch_core/management/gateway_routes.py
index dbcaeefea..188392396 100644
--- a/core/switch_core/management/gateway_routes.py
+++ b/core/switch_core/management/gateway_routes.py
@@ -44,6 +44,19 @@ Protocol = Annotated[AgentCore, Depends(get_protocol)]
Broker = Annotated[ServiceBroker, Depends(get_service_broker)]
+def _controller(view: dict[str, Any]) -> dict[str, Any]:
+ """`view` with what the caller may do with the machine. Every machine
+ these routes return is the caller's own, to rename and remove; removing a
+ revoked one again changes nothing, which `revoked_at` says."""
+ return {**view, "can_edit": True, "can_remove": True}
+
+
+def _managed_agent(view: dict[str, Any]) -> dict[str, Any]:
+ """`view` with what the caller may do with the managed agent: every one
+ these routes return is the caller's own, to change or stop managing."""
+ return {**view, "can_edit": True, "can_delete": True}
+
+
async def _revoke_controller_tokens(
session: AsyncSession, broker: ServiceBroker, *conditions: Any
) -> None:
@@ -100,7 +113,12 @@ async def enroll_console(
async def list_controllers(
session: Session, user: CurrentUser, management: Management
) -> list[dict[str, Any]]:
- return await management.list_controllers(session, require_tenant_id(), user.id)
+ return [
+ _controller(view)
+ for view in await management.list_controllers(
+ session, require_tenant_id(), user.id
+ )
+ ]
@router.patch("/controllers/{controller_id}")
@@ -112,12 +130,14 @@ async def update_controller(
management: Management,
) -> dict[str, Any]:
"""Rename the machine and/or change its description."""
- return await management.update_controller(
- session,
- require_tenant_id(),
- user.id,
- controller_id,
- {key: getattr(body, key) for key in body.model_fields_set},
+ return _controller(
+ await management.update_controller(
+ session,
+ require_tenant_id(),
+ user.id,
+ controller_id,
+ {key: getattr(body, key) for key in body.model_fields_set},
+ )
)
@@ -184,15 +204,22 @@ async def withdraw_sealed_login(
async def list_managed_agents(
session: Session, user: CurrentUser, management: Management
) -> list[dict[str, Any]]:
- return await management.list_managed_agents(session, require_tenant_id(), user.id)
+ return [
+ _managed_agent(view)
+ for view in await management.list_managed_agents(
+ session, require_tenant_id(), user.id
+ )
+ ]
@router.get("/agents/{agent_id}")
async def get_managed_agent(
agent_id: str, session: Session, user: CurrentUser, management: Management
) -> dict[str, Any]:
- return await management.get_managed_agent(
- session, require_tenant_id(), user.id, agent_id
+ return _managed_agent(
+ await management.get_managed_agent(
+ session, require_tenant_id(), user.id, agent_id
+ )
)
@@ -204,8 +231,10 @@ async def create_managed_agent(
management: Management,
protocol: Protocol,
) -> dict[str, Any]:
- return await management.create_managed_agent(
- session, require_tenant_id(), user.id, body, protocol
+ return _managed_agent(
+ await management.create_managed_agent(
+ session, require_tenant_id(), user.id, body, protocol
+ )
)
@@ -230,7 +259,7 @@ async def put_managed_agent(
await _revoke_controller_tokens(
session, broker, ServiceTokenIssuance.agent_id == agent_id
)
- return view
+ return _managed_agent(view)
@router.patch("/agents/{agent_id}")
@@ -258,7 +287,7 @@ async def patch_managed_agent(
await _revoke_controller_tokens(
session, broker, ServiceTokenIssuance.agent_id == agent_id
)
- return view
+ return _managed_agent(view)
@router.delete("/agents/{agent_id}")
diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.py
index a8eae2507..07e314ee3 100644
--- a/core/switch_core/room_service.py
+++ b/core/switch_core/room_service.py
@@ -181,6 +181,31 @@ class RoomCreateResult(BaseModel):
ROOM_NAME_MAX = 200
+# The channel types whose members their platform fixes.
+FIXED_MEMBERSHIP = ("direct", "group")
+
+
+class MembershipFixed(ValueError):
+ """Who is in a direct or group conversation is not changed from outside it."""
+
+
+def require_membership_changeable_from_outside(room: Room) -> None:
+ """Raise `MembershipFixed` for a direct or group conversation.
+
+ Its platform fixes who is in it, and a direct one is one person and one
+ agent by rule, so its agents and people are changed only from inside it:
+ by its platform, by the commands its own participants post in it, and for
+ a Switch Console chat through the chat's own routes. The Gateway's room
+ routes, the agent tools and a template's `join:` act from outside, and
+ refuse it."""
+ if room.channel_type in FIXED_MEMBERSHIP:
+ raise MembershipFixed(
+ f"This is a {room.channel_type} conversation: who is in it is fixed "
+ "by its platform, so its agents and people can't be changed from "
+ "outside it."
+ )
+
+
class RoomService:
# Class-level defaults so a caller that builds this without `__init__` —
# several tests assemble a minimal instance directly — still has the
diff --git a/core/switch_core/template_runs.py b/core/switch_core/template_runs.py
index df6a9e159..191b87000 100644
--- a/core/switch_core/template_runs.py
+++ b/core/switch_core/template_runs.py
@@ -37,6 +37,7 @@ from switch_core.bridges.agent.protocol.agent_management import (
from switch_core.connections.broker import CheckedGrant, ServiceBroker, ServiceError
from switch_core.db.models import Agent
from switch_core.db.session_scope import tenant_session
+from switch_core.room_service import FIXED_MEMBERSHIP
if TYPE_CHECKING:
from switch_core.bridges.agent.protocol.agent_core import AgentCore
@@ -337,7 +338,8 @@ class TemplateAgents:
self, tenant_id: str, owner_id: str, plan: NewAgentPlan
) -> tuple[list[str], list[Problem]]:
"""The rooms the agent joins, by id: each must exist, be one the owner
- sees, and one the owner may add agents to."""
+ sees, and one the owner may add agents to, which a direct or group
+ conversation is not (`require_membership_changeable_from_outside`)."""
if not plan.joins:
return [], []
async with tenant_session(self._protocol.session_factory, tenant_id) as session:
@@ -372,6 +374,15 @@ class TemplateAgents:
f"it joins {name}, and you may not add agents to that room.",
)
)
+ elif matches[0].channel_type in FIXED_MEMBERSHIP:
+ problems.append(
+ Problem(
+ plan.slot,
+ "join_fixed_membership",
+ f"it joins {name}, a {matches[0].channel_type} conversation, "
+ "whose platform fixes who is in it.",
+ )
+ )
else:
ids.append(matches[0].id)
return ids, problems
diff --git a/core/tests/switch_core/accounts/test_ownership_transfer.py b/core/tests/switch_core/accounts/test_ownership_transfer.py
index d1d3ec511..6924218f9 100644
--- a/core/tests/switch_core/accounts/test_ownership_transfer.py
+++ b/core/tests/switch_core/accounts/test_ownership_transfer.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import asyncio
import uuid
+from dataclasses import replace
from types import SimpleNamespace
import httpx
@@ -16,7 +17,13 @@ from fastapi import FastAPI
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
-from switch_core.accounts.transfer import TransferRefused, transfer_ownership
+from switch_core.accounts.transfer import (
+ AgentTransferFacts,
+ TransferRefused,
+ agent_transfer_facts,
+ agent_transfer_refusal,
+ transfer_ownership,
+)
from switch_core.authz import Principal
from switch_core.bridges.agent.protocol.agent_connections import (
KEY_REISSUED,
@@ -29,6 +36,7 @@ from switch_core.db.models import (
TENANT_ZERO_ID,
Agent,
AgentConnectionRecord,
+ AgentDefinition,
ApiKey,
AuditEvent,
Document,
@@ -222,40 +230,45 @@ async def test_an_agent_moves_with_a_new_key_its_new_owner_holds(
assert key.key_hash != old_hash
+async def _grant_github(session: AsyncSession, owner: User, agent: Agent) -> None:
+ """Give `agent` service access on its owner's own GitHub connection."""
+ session.add(
+ ServiceConnection(
+ user_id=owner.id,
+ service="github",
+ status="active",
+ consent="read",
+ granted_scopes=[],
+ account_id="1001",
+ external_identity="owner",
+ encrypted_secret="x",
+ secret_revision=1,
+ )
+ )
+ await session.flush()
+ session.add(
+ ServiceGrant(
+ agent_id=agent.id,
+ owner_id=owner.id,
+ service="github",
+ access="read",
+ tool_mode="allow",
+ tools=[],
+ resources={},
+ account_id="1001",
+ created_by=owner.id,
+ )
+ )
+ await session.commit()
+
+
async def test_an_agent_using_its_owners_connections_is_refused(
session_factory: async_sessionmaker[AsyncSession],
) -> None:
async with session_factory() as session:
owner, member, _ = await _people(session)
agent = await _agent(session, TENANT_ZERO_ID, owner, "helper")
- session.add(
- ServiceConnection(
- user_id=owner.id,
- service="github",
- status="active",
- consent="read",
- granted_scopes=[],
- account_id="1001",
- external_identity="owner",
- encrypted_secret="x",
- secret_revision=1,
- )
- )
- await session.flush()
- session.add(
- ServiceGrant(
- agent_id=agent.id,
- owner_id=owner.id,
- service="github",
- access="read",
- tool_mode="allow",
- tools=[],
- resources={},
- account_id="1001",
- created_by=owner.id,
- )
- )
- await session.commit()
+ await _grant_github(session, owner, agent)
with pytest.raises(TransferRefused) as refused:
await _transfer(
@@ -270,6 +283,25 @@ async def test_an_agent_using_its_owners_connections_is_refused(
) == owner_id
+async def test_only_its_owner_is_told_which_services_an_agent_uses(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ """The grants are made on the owner's own connections, which an admin is
+ not shown either (`gateway/service_connections.py`)."""
+ async with session_factory() as session:
+ owner, member, admin = await _people(session)
+ agent = await _agent(session, TENANT_ZERO_ID, owner, "helper")
+ await _grant_github(session, owner, agent)
+
+ with pytest.raises(TransferRefused) as refused:
+ await _transfer(
+ session, "agent", agent.id, member, Principal(admin.id, True)
+ )
+ assert refused.value.status == 409
+ assert "service access" in str(refused.value)
+ assert "github" not in str(refused.value)
+
+
async def test_an_agent_that_may_manage_agents_is_refused(
session_factory: async_sessionmaker[AsyncSession],
) -> None:
@@ -601,3 +633,90 @@ async def test_a_removal_waits_for_a_transfer_to_the_member(
assert agent_name in response.json()["detail"]
async with session_factory() as session:
assert await session.get(TenantMember, (TENANT_A, member_id)) is not None
+
+
+_TIED_BY_NOTHING_ELSE = AgentTransferFacts(
+ granted_services=(),
+ managed=False,
+ may_manage_agents=False,
+ in_family=False,
+ has_oauth_client=False,
+ run_by_server_connector=False,
+)
+
+
+class TestAgentTransferRefusal:
+ def test_an_agent_tied_to_its_owner_by_nothing_else_may_change_owner(self) -> None:
+ assert agent_transfer_refusal(_TIED_BY_NOTHING_ELSE, to_owner=True) is None
+
+ @pytest.mark.parametrize(
+ ("fact", "value", "says"),
+ [
+ ("granted_services", ("github",), "service access"),
+ ("managed", True, "managed on its owner's machine"),
+ ("may_manage_agents", True, "manage its owner's agents"),
+ ("in_family", True, "family of sub-agents"),
+ ("has_oauth_client", True, "OAuth client of its own"),
+ ("run_by_server_connector", True, "server connector"),
+ ],
+ )
+ def test_each_tie_to_its_owner_refuses_on_its_own(
+ self, fact: str, value: object, says: str
+ ) -> None:
+ facts = replace(_TIED_BY_NOTHING_ELSE, **{fact: value})
+
+ for to_owner in (True, False):
+ refusal = agent_transfer_refusal(facts, to_owner=to_owner)
+ assert refusal is not None and says in refusal
+
+ def test_only_the_owner_is_told_which_services(self) -> None:
+ facts = replace(_TIED_BY_NOTHING_ELSE, granted_services=("github", "linear"))
+
+ assert "github, linear" in (agent_transfer_refusal(facts, to_owner=True) or "")
+ assert "github" not in (agent_transfer_refusal(facts, to_owner=False) or "")
+
+
+async def test_the_transfer_facts_of_many_agents_are_read_together(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ async with session_factory() as session:
+ owner, _member, _admin = await _people(session)
+ plain = await _agent(session, TENANT_ZERO_ID, owner, "plain")
+ granted = await _agent(session, TENANT_ZERO_ID, owner, "granted")
+ managed = await _agent(session, TENANT_ZERO_ID, owner, "managed")
+ manager = await _agent(session, TENANT_ZERO_ID, owner, "manager")
+ parent = await _agent(session, TENANT_ZERO_ID, owner, "parent")
+ child = await _agent(session, TENANT_ZERO_ID, owner, "parent-child")
+ connector = await _agent(session, TENANT_ZERO_ID, owner, "connector")
+ oauth = await _agent(session, TENANT_ZERO_ID, owner, "oauth")
+ manager.can_manage_agents = True
+ oauth.oauth_client_id = "client-1"
+ child.parent_agent_id = parent.id
+ connector.metadata_ = {"server_connector_id": "github"}
+ session.add(
+ AgentDefinition(
+ agent_id=managed.id,
+ owner_id=owner.id,
+ revision=1,
+ desired_state="running",
+ definition={},
+ )
+ )
+ await session.flush()
+ await _grant_github(session, owner, granted)
+ agents = [plain, granted, managed, manager, parent, child, connector, oauth]
+
+ facts = await agent_transfer_facts(
+ session, TENANT_ZERO_ID, [agent.id for agent in agents]
+ )
+
+ assert facts == {
+ plain.id: _TIED_BY_NOTHING_ELSE,
+ granted.id: replace(_TIED_BY_NOTHING_ELSE, granted_services=("github",)),
+ managed.id: replace(_TIED_BY_NOTHING_ELSE, managed=True),
+ manager.id: replace(_TIED_BY_NOTHING_ELSE, may_manage_agents=True),
+ parent.id: replace(_TIED_BY_NOTHING_ELSE, in_family=True),
+ child.id: replace(_TIED_BY_NOTHING_ELSE, in_family=True),
+ connector.id: replace(_TIED_BY_NOTHING_ELSE, run_by_server_connector=True),
+ oauth.id: replace(_TIED_BY_NOTHING_ELSE, has_oauth_client=True),
+ }
diff --git a/core/tests/switch_core/bridges/agent/api/test_operation_refusal_status.py b/core/tests/switch_core/bridges/agent/api/test_operation_refusal_status.py
new file mode 100644
index 000000000..1e7310c45
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/api/test_operation_refusal_status.py
@@ -0,0 +1,16 @@
+"""What an operation's refusal is answered with over the agent HTTP front door."""
+
+from __future__ import annotations
+
+from switch_core.bridges.agent.api.operations import refusal_status
+from switch_core.room_service import MembershipFixed
+
+
+def test_a_fixed_conversation_is_a_conflict_as_the_room_routes_say() -> None:
+ assert refusal_status(MembershipFixed("a direct conversation")) == 409
+
+
+def test_other_refusals_keep_their_status() -> None:
+ assert refusal_status(PermissionError("no")) == 403
+ assert refusal_status(ValueError("bad")) == 400
+ assert refusal_status(RuntimeError("broken")) is None
diff --git a/core/tests/switch_core/bridges/agent/operations/test_template_managed_agents.py b/core/tests/switch_core/bridges/agent/operations/test_template_managed_agents.py
index badd63776..3372d900d 100644
--- a/core/tests/switch_core/bridges/agent/operations/test_template_managed_agents.py
+++ b/core/tests/switch_core/bridges/agent/operations/test_template_managed_agents.py
@@ -663,6 +663,47 @@ agent:
assert added == [(lobby_id, [created["agent_id"]])]
[email protected]("channel_type", ["direct", "group"])
+async def test_a_new_agent_never_joins_a_direct_or_group_conversation(
+ managed, channel_type
+):
+ """Its platform fixes who is in it, however writable its room is: a DM the
+ bridge adopted is writable by every member of the workspace."""
+ added: list[tuple[str, list[str]]] = []
+
+ async def add_agents_to_room(room_id: str, agent_ids: list[str]) -> None:
+ added.append((room_id, agent_ids))
+
+ managed["protocol"].room_service.add_agents_to_room = add_agents_to_room
+ async with managed["session_factory"]() as session:
+ session.add(
+ Room(
+ transport_room_id="!someones-dm:test.local",
+ name="someones-dm",
+ description="d",
+ channel_type=channel_type,
+ write_visibility="public",
+ )
+ )
+ await session.commit()
+ template = """\
+agent:
+ name: joiner
+ instructions: Join.
+ provider: claude
+ machine: laptop
+ directory: /srv/joiner
+ join: [someones-dm]
+"""
+ stored = await _stored(managed, template, kind="agent")
+ with pytest.raises(AgentsNotCreated) as e:
+ await _as(managed["agent_id"], run_template, template_id=stored)
+ assert {p.code for p in e.value.problems} == {"join_fixed_membership"}
+ assert managed["management"].created == []
+ assert added == []
+
+
def test_a_provider_chain_takes_the_first_ready_on_the_machine():
template = """\
params:
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_remove_agent_from_room.py b/core/tests/switch_core/bridges/agent/protocol/test_remove_agent_from_room.py
index 5bc4ec52e..1656c2237 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_remove_agent_from_room.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_remove_agent_from_room.py
@@ -13,6 +13,7 @@ from switch_core.bridges.agent.protocol.agent_core import AgentCore
from switch_core.bridges.agent.protocol.agent_detail import addressing_policy_for
from switch_core.db.models import Agent, Room
from switch_core.db.stores.room_store import RoomStore
+from switch_core.room_service import MembershipFixed
from tests.switch_core.bridges.agent.protocol.test_room_roster_authz import (
_make_user,
_register,
@@ -100,6 +101,29 @@ class TestRemoveAgentFromRoom:
await svc.remove_agent_from_room(caller, room_id, "alice-agent")
assert rooms.removed == []
+ @pytest.mark.parametrize("channel_type", ["direct", "group"])
+ async def test_refuses_a_direct_or_group_conversation(
+ self, session_factory: async_sessionmaker[AsyncSession], channel_type: str
+ ) -> None:
+ """Its platform fixes who is in it, as the room routes say too; the
+ people in it use `!remove-agent`. Even its owner's own manager is
+ refused, which is let through anywhere else."""
+ svc, rooms = _core(session_factory)
+ alice = await _make_user(session_factory, "alice")
+ buddy = await _register(svc, "alice-buddy", alice)
+ target = await _register(svc, "alice-agent", alice)
+ await _set(session_factory, buddy, can_manage_agents=True)
+ room_id = await _room_with(session_factory, [target])
+ async with session_factory() as session:
+ room = await session.get(Room, room_id)
+ assert room is not None
+ room.channel_type = channel_type
+ await session.commit()
+
+ with pytest.raises(MembershipFixed, match=channel_type):
+ await svc.remove_agent_from_room(buddy, room_id, "alice-agent")
+ assert rooms.removed == []
+
async def test_manager_removes_its_owners_agent_it_may_not_address(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py b/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py
index 2ee603a33..b51c7c2e0 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py
@@ -25,6 +25,7 @@ from switch_core.db.stores.api_key_store import ApiKeyStore
from switch_core.db.stores.room_store import RoomStore
from switch_core.db.stores.user_store import UserStore
from switch_core.keys import Keyring
+from switch_core.room_service import MembershipFixed
_PROFILE = IntegrationProfile(
connection_model="session_passive",
@@ -189,3 +190,42 @@ class TestRoomRosterAuthz:
async with session_factory() as session:
room = await svc._require_room_roster_change(session, admin_agent, room_id)
assert room.id == room_id
+
+
+class _UntouchedRoomService:
+ """Fails the test if the tools get as far as changing anyone's rooms."""
+
+ async def add_agents_to_room(self, *args: object, **kwargs: object) -> None:
+ raise AssertionError("an agent was added")
+
+ async def add_users_to_room(self, *args: object, **kwargs: object) -> list[str]:
+ raise AssertionError("a person was added")
+
+
+class TestFixedMembership:
+ @pytest.mark.parametrize("channel_type", ["direct", "group"])
+ async def test_not_even_an_admin_adds_to_a_direct_or_group_conversation(
+ self, session_factory: async_sessionmaker[AsyncSession], channel_type: str
+ ) -> None:
+ """Its platform fixes who is in it; agents and people get in from
+ inside it, which the agent tools are not."""
+ svc = _service(session_factory)
+ svc.room_service = _UntouchedRoomService() # type: ignore[assignment]
+ person = await _make_user(session_factory, "person")
+ admin = await _make_user(session_factory, "root", role="admin")
+ dm_agent = await _register(svc, "dm-agent", person)
+ admin_agent = await _register(svc, "admin-agent", admin)
+ room_id = await _make_public_room(
+ session_factory, owner_id=person, member_agent_ids=[dm_agent]
+ )
+ async with session_factory() as session:
+ room = await session.get(Room, room_id)
+ assert room is not None
+ room.channel_type = channel_type
+ await session.commit()
+
+ for caller in (admin_agent, dm_agent):
+ with pytest.raises(MembershipFixed, match=channel_type):
+ await svc.invite_agent_to_room(caller, room_id, "admin-agent")
+ with pytest.raises(MembershipFixed, match=channel_type):
+ await svc.add_users_to_room(caller, room_id, ["root"])
diff --git a/core/tests/switch_core/bridges/resource/test_room_attachments.py b/core/tests/switch_core/bridges/resource/test_room_attachments.py
new file mode 100644
index 000000000..ccf405947
--- /dev/null
+++ b/core/tests/switch_core/bridges/resource/test_room_attachments.py
@@ -0,0 +1,71 @@
+"""Attaching to a room is idempotent, and is reported once.
+
+Attaching what a room already has is a no-op the routes answer as a success,
+so asking twice must neither fail nor count as a second attachment.
+"""
+
+from __future__ import annotations
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.resource.service import ResourceService
+from switch_core.db.models import Room
+from switch_core.db.stores.document_store import DocumentStore
+from switch_core.db.stores.package_store import PackageStore
+from switch_core.db.stores.reference_store import ReferenceStore
+from switch_core.db.stores.reference_type_store import ReferenceTypeStore
+from switch_core.db.stores.room_link_store import RoomLinkStore
+from tests.switch_core.bridges.resource.test_reference_types_service import (
+ _make_user,
+)
+from tests.switch_core.bridges.resource.test_visibility_changes import (
+ _open_resources,
+)
+from tests.telemetry_records import recording_telemetry
+
+
+async def test_attaching_twice_attaches_and_reports_once(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ telemetry, sink = recording_telemetry()
+ service = ResourceService(
+ reference_store=ReferenceStore(),
+ reference_type_store=ReferenceTypeStore(),
+ document_store=DocumentStore(),
+ package_store=PackageStore(),
+ room_link_store=RoomLinkStore(),
+ session_factory=session_factory,
+ telemetry=telemetry,
+ )
+ async with session_factory() as session:
+ owner = await _make_user(session, "owner")
+ reference_id, package_id, _slug, document_id = await _open_resources(
+ session, owner.id
+ )
+ room = Room(
+ transport_room_id="!attach-twice:test",
+ name="attach twice",
+ description="",
+ owner_id=owner.id,
+ )
+ session.add(room)
+ await session.commit()
+
+ for _ in range(2):
+ await service.attach_reference_to_room(
+ session, room.id, reference_id, user_id=owner.id
+ )
+ await service.attach_document_to_room(
+ session, room.id, document_id, user_id=owner.id
+ )
+ await service.attach_package_to_room(
+ session, room.id, package_id, user_id=owner.id
+ )
+ await session.commit()
+
+ assert [r.id for r in await service.list_room_references(session, room.id)] == [
+ reference_id
+ ]
+ assert len(sink.events("reference_attached_to_room")) == 1
+ assert len(sink.events("document_attached_to_room")) == 1
+ assert len(sink.events("package_attached_to_room")) == 1
diff --git a/core/tests/switch_core/db/stores/test_reference_store_listing.py b/core/tests/switch_core/db/stores/test_reference_store_listing.py
index 9ed6f1d32..1000e774c 100644
--- a/core/tests/switch_core/db/stores/test_reference_store_listing.py
+++ b/core/tests/switch_core/db/stores/test_reference_store_listing.py
@@ -400,8 +400,8 @@ class TestAttachToRoomIsIdempotent:
)
await session.commit()
- await store.attach_to_room(session, room.id, ref.id)
- await store.attach_to_room(session, room.id, ref.id)
+ assert await store.attach_to_room(session, room.id, ref.id) is True
+ assert await store.attach_to_room(session, room.id, ref.id) is False
await session.commit()
count = await session.scalar(
diff --git a/core/tests/switch_core/gateway/agent_route_harness.py b/core/tests/switch_core/gateway/agent_route_harness.py
index bde2343c8..f93a0f644 100644
--- a/core/tests/switch_core/gateway/agent_route_harness.py
+++ b/core/tests/switch_core/gateway/agent_route_harness.py
@@ -6,6 +6,8 @@ care about neither, so both are built here at their minimum shape.
from __future__ import annotations
+from types import SimpleNamespace
+
from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.db.models import Agent, ApiKey, Client, User
@@ -13,6 +15,9 @@ from switch_core.db.stores.user_store import UserStore
_USER_STORE = UserStore()
+# The settings an agent detail reads, with service connections switched on.
+SERVICES_ON = SimpleNamespace(service_connections_enabled=True)
+
async def is_admin(session: AsyncSession, user: User) -> bool:
"""The bit `get_tenant_is_admin` hands a route, resolved the same way.
diff --git a/core/tests/switch_core/gateway/role_matrix/__init__.py b/core/tests/switch_core/gateway/role_matrix/__init__.py
new file mode 100644
index 000000000..56aa7ed39
--- /dev/null
+++ b/core/tests/switch_core/gateway/role_matrix/__init__.py
@@ -0,0 +1,5 @@
+"""Every gateway route, asked by every kind of caller: the role × route matrix.
+
+`routes.py` says, for each route, who may use it; `test_role_matrix.py` asks
+the real gateway app on Postgres as each of them and holds the answer to it.
+"""
diff --git a/core/tests/switch_core/gateway/role_matrix/access.py b/core/tests/switch_core/gateway/role_matrix/access.py
new file mode 100644
index 000000000..7e6dea3ad
--- /dev/null
+++ b/core/tests/switch_core/gateway/role_matrix/access.py
@@ -0,0 +1,67 @@
+"""Who may use a route, as the status each `Persona` must be answered with.
+
+A rule names the people it lets through; everyone else is refused with the
+status the route refuses with. "Let through" is a set: the route's own success,
+or 418, which `harness.Reached` answers once a route passed its checks and
+asked something the matrix stands in for. A refusal is one exact status.
+"""
+
+from __future__ import annotations
+
+from tests.switch_core.gateway.role_matrix.harness import Persona
+
+Expected = int | frozenset[int]
+
+# Passed its checks: answered, or went on to something the matrix stands in for.
+REACHED = 418
+OK = frozenset({200, 201, 202, 204, REACHED})
+
+ADMINS = frozenset({Persona.ORG_ADMIN, Persona.WORKSPACE_ADMIN, Persona.OPERATOR})
+
+
+def _rule(
+ allowed: frozenset[Persona], ok: Expected, refused: int
+) -> dict[Persona, Expected]:
+ return {persona: ok if persona in allowed else refused for persona in Persona}
+
+
+def anyone(ok: Expected = OK) -> dict[Persona, Expected]:
+ """Anyone who may enter the workspace, the operator included."""
+ return {persona: ok for persona in Persona}
+
+
+def admins(ok: Expected = OK, refused: int = 403) -> dict[Persona, Expected]:
+ """Whoever administers the workspace: its admins by membership, its
+ organization's admin, and the operator."""
+ return _rule(ADMINS, ok, refused)
+
+
+def owner_or_admins(ok: Expected = OK, refused: int = 403) -> dict[Persona, Expected]:
+ return _rule(ADMINS | {Persona.OWNER}, ok, refused)
+
+
+def owner(ok: Expected = OK, refused: int = 404) -> dict[Persona, Expected]:
+ """Its owner alone, whatever anyone else administers."""
+ return _rule(frozenset({Persona.OWNER}), ok, refused)
+
+
+def org_admin(ok: Expected = OK, refused: int = 403) -> dict[Persona, Expected]:
+ """The organization's admin. The operator restores one only while the
+ organization has none, and this one has."""
+ return _rule(frozenset({Persona.ORG_ADMIN}), ok, refused)
+
+
+def operator(ok: Expected = OK, refused: int = 403) -> dict[Persona, Expected]:
+ return _rule(frozenset({Persona.OPERATOR}), ok, refused)
+
+
+def admin_by_membership(
+ ok: Expected = OK, refused: int = 403
+) -> dict[Persona, Expected]:
+ """An admin of the workspace by their own membership, not by the
+ organization or the operator bit."""
+ return _rule(frozenset({Persona.WORKSPACE_ADMIN}), ok, refused)
+
+
+def matches(expected: Expected, status: int) -> bool:
+ return status in expected if isinstance(expected, frozenset) else status == expected
diff --git a/core/tests/switch_core/gateway/role_matrix/harness.py b/core/tests/switch_core/gateway/role_matrix/harness.py
new file mode 100644
index 000000000..3c64dbecb
--- /dev/null
+++ b/core/tests/switch_core/gateway/role_matrix/harness.py
@@ -0,0 +1,613 @@
+"""The real gateway app on Postgres, the people who ask it, and what they ask
+about.
+
+Everything that decides who may do what is real: the routes, their
+dependencies, authentication by session cookie, the stores, the resource,
+room and chat services, agent management and the service broker. What the
+app would hand on to a messaging platform, a running client, a vendor or a
+machine is a stand-in that raises `Reached` when a route gets that far. A
+route can only get that far by passing its checks, so the matrix reads that
+answer, 418, as "let through", without these stand-ins having to do the work.
+A route that refuses after one of them was asked has acted before checking,
+and the matrix says so.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import importlib.util
+import json
+import tempfile
+import uuid
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from enum import StrEnum
+from pathlib import Path
+from types import ModuleType, SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock
+
+import httpx
+from fastapi import FastAPI, Request
+from fastapi.responses import JSONResponse
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.agent.api_key_cache import ApiKeyCache
+from switch_core.bridges.agent.controller_auth_cache import ControllerAuthCache
+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry
+from switch_core.bridges.agent.protocol.agent_core import AgentCore
+from switch_core.bridges.resource.service import ResourceService
+from switch_core.config import SwitchConfig
+from switch_core.connections.app_credentials import ConnectorApps
+from switch_core.connections.organization_apps import OrganizationApps
+from switch_core.db.models import (
+ Organization,
+ OrganizationMember,
+ Tenant,
+ TenantMember,
+ User,
+)
+from switch_core.db.stores.agent_session_store import AgentSessionStore
+from switch_core.db.stores.agent_store import AgentStore
+from switch_core.db.stores.api_key_store import ApiKeyStore
+from switch_core.db.stores.budget_store import BudgetStore
+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
+from switch_core.db.stores.document_store import DocumentStore
+from switch_core.db.stores.external_user_store import ExternalUserStore
+from switch_core.db.stores.invitation_store import InvitationStore
+from switch_core.db.stores.join_domain_store import JoinDomainStore
+from switch_core.db.stores.organization_app_credential_store import (
+ OrganizationAppCredentialStore,
+)
+from switch_core.db.stores.organization_store import OrganizationStore
+from switch_core.db.stores.package_store import PackageStore
+from switch_core.db.stores.reference_store import ReferenceStore
+from switch_core.db.stores.reference_type_store import ReferenceTypeStore
+from switch_core.db.stores.room_group_store import RoomGroupStore
+from switch_core.db.stores.room_link_store import RoomLinkStore
+from switch_core.db.stores.room_role_store import RoomRoleStore
+from switch_core.db.stores.room_store import RoomStore
+from switch_core.db.stores.switch_core_process_store import SwitchCoreProcessStore
+from switch_core.db.stores.template_store import TemplateStore
+from switch_core.db.stores.usage_store import UsageStore
+from switch_core.db.stores.user_store import UserStore
+from switch_core.feature_flags import KNOWN_FEATURE_FLAGS
+from switch_core.gateway.app import create_gateway_app
+from switch_core.gateway.auth import create_jwt
+from switch_core.management.dependencies import init_management_dependencies
+from switch_core.management.wiring import (
+ Management,
+ build_management,
+ mount_gateway_routes,
+)
+from switch_core.organization_directory import LocalDirectory
+from switch_core.process_lease import ProcessLease
+from switch_core.providers.github import GitHubConnections, GitHubReach
+from switch_core.signals import SignalBus
+from switch_core.tenant_context import tenant_scope
+from switch_core.user_changes import LocalUserChanges, SignalUserChanges
+from tests.switch_core.connections.fake_vendor import FakeVendor
+from tests.switch_core.connections.github_seed import github_broker
+from tests.switch_core.gateway.conftest import (
+ _chat_service,
+ _FakeActivityListener,
+ _FakeLifecycle,
+ _FakeListener,
+)
+from tests.switch_core.gateway.test_messaging_install_routes import _Service
+from tests.switch_core.management.harness import (
+ SERVER_URL,
+ STATUS_INTERVAL,
+ TOKEN_SECRET,
+ Clock,
+)
+
+REPO_ROOT = Path(__file__).resolve().parents[5]
+
+# The workspace every case is asked in, inside an organization of its own.
+TENANT = "role-matrix"
+ORGANIZATION = "role-matrix-org"
+
+
+def _surface() -> ModuleType:
+ """`scripts/e2e_surface.py`, which writes the committed route snapshot:
+ its configuration (every feature flag on) and its route walker, so the
+ matrix enumerates routes exactly as the snapshot does."""
+ path = REPO_ROOT / "scripts" / "e2e_surface.py"
+ spec = importlib.util.spec_from_file_location("e2e_surface", path)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+SURFACE = _surface()
+
+
+class Reached(Exception):
+ """A route passed its checks and asked a collaborator the matrix stands
+ in for."""
+
+
+def reached_response(request: Request, exc: Exception) -> JSONResponse:
+ return JSONResponse(status_code=418, content={"reached": str(exc)})
+
+
+class Fake:
+ """A collaborator the matrix does not run. `answers` are what it says to
+ the reads a route makes before deciding; anything else it is asked is a
+ route acting on what it allowed."""
+
+ def __init__(self, name: str, **answers: Any) -> None:
+ self._name = name
+ self._answers = answers
+
+ def __getattr__(self, attr: str) -> Any:
+ if attr.startswith("__"):
+ raise AttributeError(attr)
+ if attr in self._answers:
+ return self._answers[attr]
+
+ def reached(*args: Any, **kwargs: Any) -> Any:
+ raise Reached(f"{self._name}.{attr}")
+
+ return reached
+
+
+def stand_in(cls: type, name: str, **answers: Any) -> Any:
+ """A stand-in that passes for a `cls` where a route checks for one: it
+ holds `answers`, and anything else a route reaches for on it is `Reached`.
+ Its methods are `cls`'s own, so one that reaches for anything not given
+ is `Reached` too."""
+
+ def missing(self: Any, attr: str) -> Any:
+ if attr.startswith("__"):
+ raise AttributeError(attr)
+ raise Reached(f"{name}.{attr}")
+
+ standing_in = type(f"StandIn{cls.__name__}", (cls,), {"__getattr__": missing})
+ instance: Any = object.__new__(standing_in)
+ for attr, value in answers.items():
+ object.__setattr__(instance, attr, value)
+ return instance
+
+
+class _Partly:
+ """`real` for what it has, and `Reached` for what it hasn't."""
+
+ def __init__(self, real: Any, name: str) -> None:
+ self._real = real
+ self._fake = Fake(name)
+
+ def __getattr__(self, attr: str) -> Any:
+ try:
+ return getattr(self._real, attr)
+ except AttributeError:
+ return getattr(self._fake, attr)
+
+
+class _Core(AgentCore):
+ """The protocol service with the stores the gateway reads through it, and
+ nothing it would hand on to a running client or bridge: asking it for that
+ is `Reached`."""
+
+ def __getattr__(self, attr: str) -> Any:
+ if attr.startswith("__"):
+ raise AttributeError(attr)
+ raise Reached(f"protocol.{attr}")
+
+
+def _protocol(
+ session_factory: async_sessionmaker[AsyncSession],
+ config: SwitchConfig,
+ clients: _FakeLifecycle,
+) -> AgentCore:
+ core = object.__new__(_Core)
+ core.session_factory = session_factory # type: ignore[assignment]
+ core.agent_store = AgentStore()
+ core.api_key_store = ApiKeyStore()
+ core.api_key_cache = ApiKeyCache(ttl_seconds=5, max_entries=64)
+ core.config = config
+ core.telemetry = None
+ core.connections = AgentConnectionRegistry()
+ core.room_store = RoomStore()
+ core.agent_session_store = AgentSessionStore()
+ core.user_store = UserStore()
+ core.room_role_store = RoomRoleStore()
+ core.bridge_store = CollaborationBridgeStore()
+ core.external_user_store = ExternalUserStore()
+ core.room_group_store = RoomGroupStore()
+ core.client_lifecycle = _Partly(clients, "client_lifecycle") # type: ignore[assignment]
+ return core
+
+
+class _Bridges:
+ """The collaboration lifecycle with nothing running: what the gateway reads
+ of it to describe a bridge, and `Reached` for anything it would do."""
+
+ def __init__(self) -> None:
+ self._fake = Fake("collab_lifecycle")
+
+ def get_adapter(self, bridge_id: str) -> None:
+ return None
+
+ def supports_channel_creation(self, bridge_type: str) -> bool:
+ return True
+
+ def supports_directory_search(self, bridge_type: str) -> bool:
+ return True
+
+ def receives_webhooks(self, bridge_type: str) -> bool:
+ return False
+
+ def webhook_url(self, bridge_id: str, bridge_type: str) -> str | None:
+ return None
+
+ def __getattr__(self, attr: str) -> Any:
+ return getattr(self._fake, attr)
+
+
+def _install(install_id: str, platform: str) -> SimpleNamespace:
+ return SimpleNamespace(
+ id=install_id,
+ tenant_id=TENANT,
+ platform=platform,
+ external_workspace_id=f"ws-{install_id}",
+ status="active",
+ scopes="",
+ bridge_id=None,
+ installed_at="2026-09-28T00:00:00Z",
+ ended_at=None,
+ )
+
+
+def installs() -> Any:
+ """The messaging-app installer with a Slack install (`s1`, OAuth) and a
+ Telegram chat (`t1`, by claim), and Telegram not yet connected here: the
+ routes decide who may do what with them, and this only answers."""
+ return _Service(installs=[_install("s1", "slack"), _install("t1", "telegram")])
+
+
+def _never_listens() -> Any:
+ raise AssertionError("the matrix's signal bus is never started")
+
+
+def _management(
+ session_factory: async_sessionmaker[AsyncSession],
+ protocol: AgentCore,
+ settings: SwitchConfig,
+) -> Management:
+ """Agent management as `Management.install` sets it up for the gateway,
+ without what `install` does beyond that: switching the agent operations on
+ is process-wide, and no route here needs it."""
+ process_id = str(uuid.uuid4())
+ signal_bus = SignalBus(session_factory, _never_listens, process_id=process_id)
+ return build_management(
+ token_secret=TOKEN_SECRET,
+ status_interval_seconds=STATUS_INTERVAL,
+ server_url=SERVER_URL,
+ third_party_avatars=True,
+ controller_release=None,
+ session_factory=session_factory,
+ presence=protocol.connections.controllers,
+ auth_cache=ControllerAuthCache(ttl_seconds=5, max_entries=64),
+ clock=Clock(),
+ signal_bus=signal_bus,
+ lease=ProcessLease(
+ process_id=process_id,
+ session_factory=session_factory,
+ processes=SwitchCoreProcessStore(),
+ key_ids=[key.id for key in settings.keyring.keys],
+ ),
+ user_changes=SignalUserChanges(local=LocalUserChanges(), bus=signal_bus),
+ )
+
+
+def config() -> SwitchConfig:
+ return SURFACE._config(frozenset(KNOWN_FEATURE_FLAGS)) # type: ignore[no-any-return]
+
+
+def build_gateway(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
+ """The gateway as `main.py` builds it; `client` mounts it at `/gateway`,
+ as `main.py` does."""
+ settings = config()
+ lifecycle = _FakeLifecycle()
+ protocol = _protocol(session_factory, settings, lifecycle)
+ chat_service, room_service = _chat_service(
+ session_factory,
+ lifecycle=lifecycle,
+ listener=_FakeListener(),
+ activity=_FakeActivityListener(),
+ connections=protocol.connections,
+ )
+ resource_service = ResourceService(
+ reference_store=ReferenceStore(),
+ reference_type_store=ReferenceTypeStore(),
+ document_store=DocumentStore(),
+ package_store=PackageStore(),
+ room_link_store=RoomLinkStore(),
+ session_factory=session_factory,
+ )
+ protocol.room_service = room_service # type: ignore[assignment]
+ protocol.resource_service = resource_service # type: ignore[assignment]
+ gateway = create_gateway_app(
+ agent_store=AgentStore(),
+ room_store=RoomStore(),
+ room_group_store=RoomGroupStore(),
+ room_service=room_service,
+ bridge_store=CollaborationBridgeStore(),
+ client_lifecycle=Fake("client_lifecycle"), # type: ignore[arg-type]
+ collab_lifecycle=_Bridges(), # type: ignore[arg-type]
+ event_buffer=Fake("event_buffer"), # type: ignore[arg-type]
+ session_factory=session_factory,
+ user_store=UserStore(),
+ external_user_store=ExternalUserStore(),
+ api_key_store=ApiKeyStore(),
+ invitation_store=InvitationStore(),
+ join_domain_store=JoinDomainStore(),
+ organization_store=OrganizationStore(),
+ organization_directory=LocalDirectory(),
+ template_store=TemplateStore(),
+ usage_store=UsageStore(),
+ budget_store=BudgetStore(),
+ resource_service=resource_service,
+ protocol=protocol,
+ install_service=installs(),
+ invite_mailer=None,
+ user_changes=LocalUserChanges(),
+ chat_service=chat_service,
+ connector_apps=stand_in(
+ ConnectorApps, "connector_apps", github_app=lambda: None
+ ),
+ config=settings,
+ )
+ management = _management(session_factory, protocol, settings)
+ init_management_dependencies(
+ service=management.service,
+ authenticator=management.authenticator,
+ session_factory=session_factory,
+ )
+ mount_gateway_routes(gateway)
+ gateway.state.service_broker = github_broker(
+ session_factory, settings.keyring, FakeVendor()
+ )
+ gateway.state.organization_apps = stand_in(
+ OrganizationApps,
+ "organization_apps",
+ _store=OrganizationAppCredentialStore(settings.keyring),
+ )
+ gateway.state.controller_revoker = management.service
+ gateway.state.github_connections = _github()
+ # The clients the room and chat services think are running: `World` adds
+ # each agent it makes, as a running client would announce itself.
+ gateway.state.matrix_lifecycle = lifecycle
+ gateway.add_exception_handler(Reached, reached_response)
+ return gateway
+
+
+def _github() -> GitHubConnections:
+ """The server's GitHub App, answering for GitHub rather than asking it."""
+ with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as file:
+ json.dump(
+ {
+ "client_id": "example-client",
+ "client_secret": "SYNTHETIC-PLACEHOLDER",
+ "slug": "example-app",
+ "origin": "https://switch.example.com",
+ },
+ file,
+ )
+ github = GitHubConnections.from_file(file.name)
+ Path(file.name).unlink()
+ github.exchange = Fake("github").exchange # type: ignore[method-assign]
+ github.revoke = AsyncMock() # type: ignore[method-assign]
+ github.request = Fake("github").request # type: ignore[method-assign]
+ github.repositories = AsyncMock( # type: ignore[method-assign]
+ return_value=GitHubReach(installations=[], sso_hidden=[])
+ )
+ return github
+
+
+class Persona(StrEnum):
+ """Who asks. The ticket's three roles, the deployment operator, and the
+ member who owns the thing being asked about."""
+
+ ORG_ADMIN = "org-admin"
+ WORKSPACE_ADMIN = "workspace-admin"
+ MEMBER = "member"
+ OPERATOR = "operator"
+ OWNER = "owner"
+
+
+def domain_of(persona: Persona) -> str:
+ """Each persona's e-mail domain is their own, so a workspace can be opened
+ to it without the next one finding it already open."""
+ return f"{persona.value}.example.invalid"
+
+
+def email_of(persona: Persona) -> str:
+ return f"{persona.value}@{domain_of(persona)}"
+
+
+@dataclass(frozen=True)
+class People:
+ ids: dict[Persona, str]
+
+ def headers(self, persona: Persona) -> dict[str, str]:
+ """A signed-in session in the workspace, as the browser sends it."""
+ user_id = self.ids[persona]
+ token = create_jwt(
+ user_id,
+ email_of(persona),
+ "user",
+ config().keyring,
+ TENANT,
+ session_version=0,
+ auth_time=datetime.now(UTC),
+ )
+ return {"cookie": f"switch_auth={token}"}
+
+
+async def seed_people(session_factory: async_sessionmaker[AsyncSession]) -> People:
+ """The workspace, its organization, and one person for each `Persona`.
+
+ The organization admin holds no membership in the workspace: standing
+ there through the organization alone is the case that differs from a
+ workspace admin. The operator holds none either.
+ """
+ ids: dict[Persona, str] = {}
+ with tenant_scope(TENANT):
+ async with session_factory() as session:
+ session.add(Organization(id=ORGANIZATION, slug=ORGANIZATION, name="Acme"))
+ await session.flush()
+ session.add(
+ Tenant(
+ id=TENANT, slug=TENANT, name=TENANT, organization_id=ORGANIZATION
+ )
+ )
+ await session.flush()
+ for persona in Persona:
+ user = User(
+ id=f"{persona.value}-{uuid.uuid4().hex[:6]}",
+ name=persona.value,
+ email=email_of(persona),
+ role="admin" if persona is Persona.OPERATOR else "user",
+ )
+ session.add(user)
+ ids[persona] = user.id
+ await session.flush()
+ for persona, tenant_role in (
+ (Persona.WORKSPACE_ADMIN, "admin"),
+ (Persona.MEMBER, "member"),
+ (Persona.OWNER, "member"),
+ ):
+ session.add(
+ TenantMember(
+ tenant_id=TENANT, user_id=ids[persona], role=tenant_role
+ )
+ )
+ for persona, organization_role in (
+ (Persona.ORG_ADMIN, "org_admin"),
+ (Persona.WORKSPACE_ADMIN, "member"),
+ (Persona.MEMBER, "member"),
+ (Persona.OWNER, "member"),
+ ):
+ session.add(
+ OrganizationMember(
+ organization_id=ORGANIZATION,
+ user_id=ids[persona],
+ role=organization_role,
+ )
+ )
+ await session.commit()
+ return People(ids)
+
+
+def client(gateway: FastAPI) -> httpx.AsyncClient:
+ """A client of `gateway` at `/gateway`. A route that fails answers 500
+ rather than raising into the test, so the matrix can say which route."""
+ root = FastAPI()
+ root.mount("/gateway", gateway)
+ return httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=root, raise_app_exceptions=False),
+ base_url="http://switch.test",
+ )
+
+
+def _scope(
+ kind: str, method: str, path: str, headers: dict[str, str]
+) -> dict[str, Any]:
+ return {
+ "type": kind,
+ "asgi": {"version": "3.0"},
+ "http_version": "1.1",
+ "method": method,
+ "scheme": "http" if kind == "http" else "ws",
+ "path": path,
+ "raw_path": path.encode(),
+ "root_path": "",
+ "query_string": b"",
+ "headers": [
+ (name.lower().encode(), value.encode()) for name, value in headers.items()
+ ],
+ "server": ("switch.test", 80),
+ "client": ("127.0.0.1", 1),
+ "subprotocols": [],
+ }
+
+
+async def _first_answer(
+ gateway: FastAPI,
+ scope: dict[str, Any],
+ opening: dict[str, Any],
+ kinds: set[str],
+ hang_up_after: set[str],
+) -> dict[str, Any]:
+ """The first message of `kinds` the app sends for `scope`, hanging up once
+ it has sent one of `hang_up_after`: how a stream or a socket is asked who
+ may open it, without waiting for all it would go on to send."""
+ root = FastAPI()
+ root.mount("/gateway", gateway)
+ loop = asyncio.get_running_loop()
+ answered: asyncio.Future[dict[str, Any]] = loop.create_future()
+ done_opening: asyncio.Future[None] = loop.create_future()
+ opened = False
+
+ async def receive() -> dict[str, Any]:
+ nonlocal opened
+ if not opened:
+ opened = True
+ return opening
+ await done_opening
+ return {
+ "type": "http.disconnect"
+ if scope["type"] == "http"
+ else "websocket.disconnect"
+ }
+
+ async def send(message: Any) -> None:
+ if message["type"] in kinds and not answered.done():
+ answered.set_result(message)
+ if message["type"] in hang_up_after and not done_opening.done():
+ done_opening.set_result(None)
+
+ task = asyncio.create_task(root(scope, receive, send))
+ try:
+ return await asyncio.wait_for(asyncio.shield(answered), timeout=10)
+ finally:
+ # Hung up: let the app see it and finish, as it would a client leaving.
+ try:
+ await asyncio.wait_for(task, timeout=10)
+ except TimeoutError:
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
+
+
+async def stream_status(gateway: FastAPI, path: str, headers: dict[str, str]) -> int:
+ """The status an event stream opens with."""
+ answer = await _first_answer(
+ gateway,
+ _scope("http", "GET", path, headers),
+ {"type": "http.request", "body": b"", "more_body": False},
+ {"http.response.start"},
+ # Once it has sent something, it is waiting for what is next.
+ {"http.response.body"},
+ )
+ return int(answer["status"])
+
+
+async def socket_status(gateway: FastAPI, path: str, headers: dict[str, str]) -> int:
+ """101 when the socket is accepted, else the status its handshake is
+ refused with."""
+ answer = await _first_answer(
+ gateway,
+ _scope("websocket", "GET", path, headers),
+ {"type": "websocket.connect"},
+ {"websocket.accept", "websocket.http.response.start", "websocket.close"},
+ {"websocket.send", "websocket.http.response.body", "websocket.close"},
+ )
+ if answer["type"] == "websocket.accept":
+ return 101
+ return int(answer.get("status", 403))
diff --git a/core/tests/switch_core/gateway/role_matrix/routes.py b/core/tests/switch_core/gateway/role_matrix/routes.py
new file mode 100644
index 000000000..ff33ace30
--- /dev/null
+++ b/core/tests/switch_core/gateway/role_matrix/routes.py
@@ -0,0 +1,1175 @@
+"""Who may use each gateway route, and how the matrix asks it.
+
+Keyed as the committed route snapshot keys them, so `test_role_matrix.py` can
+hold this table to every route the server mounts: a route added without a
+line here fails, and so does a line for a route that is gone.
+
+`{name}` in a path or body is filled from the asking persona's `World`: the
+thing of that kind, owned by `Persona.OWNER`. A rule that is not the plain
+one for its kind says why.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+from tests.switch_core.gateway.role_matrix.access import (
+ Expected,
+ admin_by_membership,
+ admins,
+ anyone,
+ operator,
+ org_admin,
+ owner,
+ owner_or_admins,
+)
+from tests.switch_core.gateway.role_matrix.harness import Persona
+
+
+@dataclass(frozen=True)
+class Ask:
+ method: str
+ path: str
+ json: Any = None
+ params: dict[str, str] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class Case:
+ ask: Ask
+ expect: dict[Persona, Expected]
+ why: str = ""
+
+
+def get(
+ path: str, expect: dict[Persona, Expected], why: str = "", **params: str
+) -> Case:
+ return Case(Ask("GET", path, params=params), expect, why)
+
+
+def post(
+ path: str, expect: dict[Persona, Expected], json: Any = None, why: str = ""
+) -> Case:
+ return Case(Ask("POST", path, json=json), expect, why)
+
+
+def put(
+ path: str, expect: dict[Persona, Expected], json: Any = None, why: str = ""
+) -> Case:
+ return Case(Ask("PUT", path, json=json), expect, why)
+
+
+def patch(
+ path: str, expect: dict[Persona, Expected], json: Any = None, why: str = ""
+) -> Case:
+ return Case(Ask("PATCH", path, json=json), expect, why)
+
+
+def delete(
+ path: str, expect: dict[Persona, Expected], why: str = "", **params: str
+) -> Case:
+ return Case(Ask("DELETE", path, params=params), expect, why)
+
+
+G = "/gateway"
+FLOW = {"port": 39231, "state": "{flow_state}", "completion_secret": "{flow_secret}"}
+W = f"{G}/tenants/{{tenant}}"
+
+# Each persona acting on its own account or its own things.
+SELF = anyone()
+
+ROUTES: dict[str, Case] = {
+ # ── Agents ───────────────────────────────────────────────────────────
+ "GET /gateway/agents": get(f"{G}/agents", anyone()),
+ "GET /gateway/agents/avatar-settings": get(f"{G}/agents/avatar-settings", anyone()),
+ "GET /gateway/agents/icon-choices": get(
+ f"{G}/agents/icon-choices", anyone(), name="matrix"
+ ),
+ "GET /gateway/agents/{agent_id}": get(f"{G}/agents/{{agent}}", anyone()),
+ "DELETE /gateway/agents/{agent_id}": delete(
+ f"{G}/agents/{{agent}}", owner_or_admins()
+ ),
+ "DELETE /gateway/agents/by-name/{agent_name}": delete(
+ f"{G}/agents/by-name/{{agent_name}}", owner_or_admins()
+ ),
+ "PATCH /gateway/agents/{agent_id}/options": patch(
+ f"{G}/agents/{{console_agent}}/options", owner_or_admins(), json={"options": {}}
+ ),
+ "PUT /gateway/agents/{agent_id}/icon": put(
+ f"{G}/agents/{{agent}}/icon", owner_or_admins(), json={"icon_url": None}
+ ),
+ "PUT /gateway/agents/{agent_id}/name": put(
+ f"{G}/agents/{{agent}}/name",
+ owner_or_admins(),
+ json={"name": "{tag}-renamed", "display_name": None},
+ ),
+ "PUT /gateway/agents/{agent_id}/display-name": put(
+ f"{G}/agents/{{agent}}/display-name",
+ owner_or_admins(),
+ json={"display_name": "Renamed"},
+ ),
+ "PUT /gateway/agents/{agent_id}/description": put(
+ f"{G}/agents/{{agent}}/description",
+ owner_or_admins(),
+ json={"description": "changed"},
+ ),
+ "PUT /gateway/agents/{agent_id}/addressing-policy": put(
+ f"{G}/agents/{{agent}}/addressing-policy",
+ owner_or_admins(),
+ json={"policy": None},
+ ),
+ "PUT /gateway/agents/{agent_id}/can-manage-agents": put(
+ f"{G}/agents/{{agent}}/can-manage-agents",
+ owner(refused=403),
+ json={"enabled": False},
+ why="Its owner's alone: the agent would act on the owner's own machines.",
+ ),
+ "GET /gateway/agents/{agent_id}/service-grants": get(
+ f"{G}/agents/{{agent}}/service-grants",
+ owner(),
+ why="Made on the owner's own connections; anyone else is told it isn't there.",
+ ),
+ "PUT /gateway/agents/{agent_id}/service-grants/{service}": put(
+ f"{G}/agents/{{console_agent}}/service-grants/github",
+ owner(),
+ json={"access": "read", "resources": {}},
+ why="Made on the owner's own connections; anyone else is told it isn't there.",
+ ),
+ "DELETE /gateway/agents/{agent_id}/service-grants/{service}": delete(
+ f"{G}/agents/{{granted_agent}}/service-grants/github", owner()
+ ),
+ "POST /gateway/agents/register": post(
+ f"{G}/agents/register",
+ SELF,
+ json={"agent_type": "claude-code", "name": "{tag}-new", "description": ""},
+ ),
+ "POST /gateway/agents/register-other": post(
+ f"{G}/agents/register-other",
+ SELF,
+ json={"name": "{tag}-other", "description": ""},
+ ),
+ "POST /gateway/agents/register-known-bulk": post(
+ f"{G}/agents/register-known-bulk",
+ owner_or_admins(),
+ json={
+ "agent_type": "claude-code",
+ "parent_agent_id": "{agent}",
+ "subagents": [{"subagent_name": "reviewer", "description": ""}],
+ },
+ ),
+ "GET /gateway/agent-sessions/approvals": get(f"{G}/agent-sessions/approvals", SELF),
+ "POST /gateway/agent-sessions/{agent_id}/{session_id}/approvals/{request_id}/answer": post(
+ f"{G}/agent-sessions/{{agent}}/session-1/approvals/request-1/answer",
+ anyone(ok=404),
+ json={"answer": "allow"},
+ why="Whoever may address the agent, which is open; there is no such request.",
+ ),
+ # ── API keys ─────────────────────────────────────────────────────────
+ "GET /gateway/api-keys": get(f"{G}/api-keys", SELF),
+ "POST /gateway/api-keys": post(f"{G}/api-keys", SELF, json={"label": "mine"}),
+ "GET /gateway/api-keys/{key_id}/reveal": get(
+ f"{G}/api-keys/{{registration_key}}/reveal",
+ owner(refused=403),
+ why="A key is a credential: not even an admin may read another's.",
+ ),
+ "DELETE /gateway/api-keys/{key_id}": delete(
+ f"{G}/api-keys/{{registration_key}}", owner(refused=403)
+ ),
+ # ── Your account ─────────────────────────────────────────────────────
+ "GET /gateway/version": get(f"{G}/version", SELF),
+ "GET /gateway/feature-flags": get(f"{G}/feature-flags", SELF),
+ "GET /gateway/auth/me": get(f"{G}/auth/me", SELF),
+ "GET /gateway/auth/me/identities": get(f"{G}/auth/me/identities", SELF),
+ "GET /gateway/auth/me/identities/pending": get(
+ f"{G}/auth/me/identities/pending", SELF
+ ),
+ "GET /gateway/auth/session": get(f"{G}/auth/session", SELF),
+ "POST /gateway/auth/refresh": post(f"{G}/auth/refresh", SELF),
+ "PATCH /gateway/auth/me": patch(f"{G}/auth/me", SELF, json={"name": "Renamed"}),
+ "PUT /gateway/auth/me/password": put(
+ f"{G}/auth/me/password",
+ anyone(ok=403),
+ json={"current_password": "wrong-password", "new_password": "a-new-password-1"},
+ why="Your own: refused, the current password being wrong.",
+ ),
+ "DELETE /gateway/auth/me": Case(
+ Ask("DELETE", f"{G}/auth/me"),
+ anyone(ok=422),
+ why="Your own: refused without the account's e-mail typed to confirm it.",
+ ),
+ # ── Workspaces ───────────────────────────────────────────────────────
+ "GET /gateway/tenants": get(f"{G}/tenants", SELF),
+ "GET /gateway/tenants/current": get(f"{G}/tenants/current", SELF),
+ "POST /gateway/tenants": post(f"{G}/tenants", SELF, json={"name": "{tag}-ws"}),
+ "POST /gateway/tenants/{tenant_id}/switch": post(f"{W}/switch", SELF),
+ "DELETE /gateway/tenants/{tenant_id}": Case(
+ Ask("DELETE", W, json={"name": "{tenant}"}),
+ admin_by_membership(ok=409),
+ why=(
+ "Its admins by their own membership, not the organization's admin "
+ "or the operator; let through, then refused while it isn't empty."
+ ),
+ ),
+ "GET /gateway/tenants/{tenant_id}/retention": get(f"{W}/retention", admins()),
+ "GET /gateway/tenants/{tenant_id}/retention/preview": get(
+ f"{W}/retention/preview", admins(), days="30"
+ ),
+ "PUT /gateway/tenants/{tenant_id}/retention": put(
+ f"{W}/retention",
+ admin_by_membership(),
+ json={"message_retention_days": 30},
+ why="Deleting messages can't be undone: its admins by their own membership.",
+ ),
+ "DELETE /gateway/tenants/{tenant_id}/retention": delete(f"{W}/retention", admins()),
+ "GET /gateway/tenants/{tenant_id}/people": get(
+ f"{W}/people",
+ admin_by_membership(),
+ why="The list a person is erased from: its admins by their own membership.",
+ ),
+ "GET /gateway/tenants/{tenant_id}/erasures": get(
+ f"{W}/erasures", admin_by_membership()
+ ),
+ "POST /gateway/tenants/{tenant_id}/erasures": post(
+ f"{W}/erasures",
+ admin_by_membership(ok=404),
+ json={"external_user_ids": ["{tag}-nobody"]},
+ why=(
+ "Erasing a person can't be undone: its admins by their own "
+ "membership; let through, then told nobody has that id."
+ ),
+ ),
+ "GET /gateway/operator/workspaces": get(f"{G}/operator/workspaces", operator()),
+ "GET /gateway/tenants/{tenant_id}/members": get(f"{W}/members", anyone()),
+ "PATCH /gateway/tenants/{tenant_id}/members/{user_id}": patch(
+ f"{W}/members/{{member_target}}", admins(), json={"role": "member"}
+ ),
+ "DELETE /gateway/tenants/{tenant_id}/members/{user_id}": delete(
+ f"{W}/members/{{member_target}}", admins()
+ ),
+ "GET /gateway/tenants/{tenant_id}/invitations": get(f"{W}/invitations", admins()),
+ "POST /gateway/tenants/{tenant_id}/invitations": post(
+ f"{W}/invitations", admins(), json={"role": "member"}
+ ),
+ "DELETE /gateway/tenants/{tenant_id}/invitations/{invitation_id}": delete(
+ f"{W}/invitations/{{invitation}}", admins()
+ ),
+ "GET /gateway/tenants/{tenant_id}/audit-events": get(f"{W}/audit-events", admins()),
+ "GET /gateway/tenants/{tenant_id}/usage": get(
+ f"{W}/usage",
+ admins(),
+ since="2026-01-01T00:00:00Z",
+ until="2026-02-01T00:00:00Z",
+ ),
+ "GET /gateway/tenants/{tenant_id}/budgets": get(f"{W}/budgets", admins()),
+ "POST /gateway/tenants/{tenant_id}/budgets": post(
+ f"{W}/budgets",
+ admins(),
+ json={
+ "agent_id": None,
+ "metric": "input_tokens",
+ "model": "{tag}",
+ "amount_limit": 10,
+ "period_hours": 24,
+ },
+ ),
+ "PUT /gateway/tenants/{tenant_id}/budgets/{budget_id}": put(
+ f"{W}/budgets/{{budget}}",
+ admins(),
+ json={"amount_limit": 20, "period_hours": 24},
+ ),
+ "DELETE /gateway/tenants/{tenant_id}/budgets/{budget_id}": delete(
+ f"{W}/budgets/{{budget}}", admins()
+ ),
+ "GET /gateway/tenants/{tenant_id}/join-domains": get(f"{W}/join-domains", admins()),
+ "POST /gateway/tenants/{tenant_id}/join-domains": post(
+ f"{W}/join-domains",
+ admins(),
+ json={"domain": "{email_domain}"},
+ why="Each admin opens it to the domain of their own e-mail.",
+ ),
+ "DELETE /gateway/tenants/{tenant_id}/join-domains/{domain}": delete(
+ f"{W}/join-domains/{{join_domain}}", admins()
+ ),
+ "POST /gateway/invitations/accept": post(
+ f"{G}/invitations/accept",
+ anyone(ok=404),
+ json={"token": "no-such-invitation"},
+ why="Whoever holds the token; this one matches no invitation.",
+ ),
+ "GET /gateway/invitations/mine": get(f"{G}/invitations/mine", SELF),
+ "POST /gateway/invitations/mine/accept": post(
+ f"{G}/invitations/mine/accept",
+ anyone(ok=404),
+ json={"tenant_id": "{tenant}", "invitation_id": "no-such-invitation"},
+ why="Your own invitations; nobody here has one.",
+ ),
+ "GET /gateway/joinable-tenants": get(f"{G}/joinable-tenants", SELF),
+ "POST /gateway/joinable-tenants/{tenant_id}/join": post(
+ f"{G}/joinable-tenants/{{tenant}}/join",
+ anyone(ok=404),
+ why="Offered only to the domains it lists, and it lists none.",
+ ),
+ "GET /gateway/workspace/services": get(f"{G}/workspace/services", admins()),
+ "PUT /gateway/workspace/services/{service}": put(
+ f"{G}/workspace/services/github", admins(), json={"enabled": True}
+ ),
+ "DELETE /gateway/workspace/services/{service}": delete(
+ f"{G}/workspace/services/{{workspace_service}}", admins()
+ ),
+ "POST /gateway/ownership/transfer": post(
+ f"{G}/ownership/transfer",
+ owner_or_admins(),
+ json={"kind": "reference", "id": "{reference}", "new_owner_id": "{member}"},
+ why="Its owner or an admin; the member receiving it can't take it for themselves.",
+ ),
+ # ── Organizations ────────────────────────────────────────────────────
+ "GET /gateway/organizations": get(f"{G}/organizations", SELF),
+ "POST /gateway/organizations": post(
+ f"{G}/organizations", SELF, json={"name": "{tag}-org"}
+ ),
+ "GET /gateway/organizations/current": get(f"{G}/organizations/current", anyone()),
+ "GET /gateway/organizations/current/workspaces": get(
+ f"{G}/organizations/current/workspaces", anyone()
+ ),
+ "POST /gateway/organizations/current/workspaces": post(
+ f"{G}/organizations/current/workspaces", org_admin(), json={"name": "{tag}-ws"}
+ ),
+ "GET /gateway/organizations/current/audit-events": get(
+ f"{G}/organizations/current/audit-events", org_admin()
+ ),
+ "GET /gateway/organizations/current/issues": get(
+ f"{G}/organizations/current/issues", org_admin()
+ ),
+ "GET /gateway/organizations/current/members": get(
+ f"{G}/organizations/current/members", org_admin()
+ ),
+ "PATCH /gateway/organizations/current/members/{user_id}": patch(
+ f"{G}/organizations/current/members/{{org_target}}",
+ org_admin(),
+ json={"role": "member"},
+ ),
+ "DELETE /gateway/organizations/current/members/{user_id}": delete(
+ f"{G}/organizations/current/members/{{org_target}}", org_admin()
+ ),
+ "GET /gateway/organizations/current/services": get(
+ f"{G}/organizations/current/services", org_admin()
+ ),
+ "PUT /gateway/organizations/current/services/{service}": put(
+ f"{G}/organizations/current/services/github",
+ org_admin(),
+ json={"enabled": True, "locked": False},
+ ),
+ "DELETE /gateway/organizations/current/services/{service}": delete(
+ f"{G}/organizations/current/services/{{organization_service}}", org_admin()
+ ),
+ "GET /gateway/organizations/current/connector-apps": get(
+ f"{G}/organizations/current/connector-apps", org_admin()
+ ),
+ "PUT /gateway/organizations/current/connector-apps/{service}": put(
+ f"{G}/organizations/current/connector-apps/github",
+ org_admin(),
+ json={"client_id": "example", "replace": False},
+ ),
+ "POST /gateway/organizations/current/connector-apps/{service}/check": post(
+ f"{G}/organizations/current/connector-apps/github/check", org_admin()
+ ),
+ "GET /gateway/organizations/current/connector-apps/{service}/impact": get(
+ f"{G}/organizations/current/connector-apps/github/impact",
+ org_admin(),
+ client_id="example",
+ ),
+ "DELETE /gateway/organizations/current/connector-apps/{service}": delete(
+ f"{G}/organizations/current/connector-apps/github", org_admin()
+ ),
+ "GET /gateway/auth/workos/organization": get(
+ f"{G}/auth/workos/organization",
+ anyone(ok=404),
+ why="An organization admin's; this server sends nothing to WorkOS, and says so first.",
+ return_to="/organization",
+ ),
+ "GET /gateway/auth/workos/callback": get(
+ f"{G}/auth/workos/callback",
+ anyone(ok=404),
+ why="Your own sign-in coming back; this server sends nothing to WorkOS.",
+ code="matrix",
+ state="matrix",
+ ),
+ # ── Operator ─────────────────────────────────────────────────────────
+ "GET /gateway/users": get(f"{G}/users", operator()),
+ "POST /gateway/users": post(
+ f"{G}/users",
+ operator(),
+ json={
+ "name": "New",
+ "email": "{tag}[email protected]",
+ "password": "a-long-enough-password",
+ },
+ ),
+ "DELETE /gateway/users/{user_id}": delete(f"{G}/users/{{user_target}}", operator()),
+ "POST /gateway/users/{user_id}/sessions/revoke": post(
+ f"{G}/users/{{user_target}}/sessions/revoke", operator()
+ ),
+ "POST /gateway/auth/sessions/revoke": post(
+ f"{G}/auth/sessions/revoke",
+ SELF,
+ why="Signing yourself out of every device.",
+ ),
+ "GET /gateway/trust-settings": get(f"{G}/trust-settings", operator()),
+ "PUT /gateway/trust-settings": put(
+ f"{G}/trust-settings",
+ operator(),
+ json={"endpoint": "https://trust.example.invalid", "policy_id": None},
+ ),
+ "DELETE /gateway/trust-settings": delete(f"{G}/trust-settings", operator()),
+ "GET /gateway/connector-apps": get(f"{G}/connector-apps", operator()),
+ "PUT /gateway/connector-apps/{service}": put(
+ f"{G}/connector-apps/github",
+ operator(),
+ json={"client_id": "example", "replace": False},
+ ),
+ "POST /gateway/connector-apps/{service}/import": post(
+ f"{G}/connector-apps/github/import", operator()
+ ),
+ "POST /gateway/connector-apps/{service}/check": post(
+ f"{G}/connector-apps/github/check", operator()
+ ),
+ "GET /gateway/connector-apps/{service}/impact": get(
+ f"{G}/connector-apps/github/impact", operator(), client_id="example"
+ ),
+ "DELETE /gateway/connector-apps/{service}": delete(
+ f"{G}/connector-apps/github", operator()
+ ),
+ # ── Rooms ────────────────────────────────────────────────────────────
+ "GET /gateway/rooms": get(f"{G}/rooms", anyone()),
+ "GET /gateway/rooms/template-schema": get(f"{G}/rooms/template-schema", anyone()),
+ "POST /gateway/rooms": post(
+ f"{G}/rooms",
+ SELF,
+ json={"name": "{tag}-new-room", "description": "", "agent_ids": ["{agent}"]},
+ ),
+ "POST /gateway/rooms/from-yaml": post(
+ f"{G}/rooms/from-yaml",
+ SELF,
+ json={"yaml": "{room_yaml}", "template_name": "matrix"},
+ ),
+ "POST /gateway/rooms/from-template": post(
+ f"{G}/rooms/from-template",
+ SELF,
+ json={"agents": [], "yaml": "{room_yaml}", "template_name": "matrix"},
+ why="From a document the caller supplies.",
+ ),
+ "POST /gateway/rooms/from-template-document": post(
+ f"{G}/rooms/from-template-document",
+ owner_or_admins(refused=404),
+ json={
+ "template": "{room_yaml}",
+ "template_name": "matrix",
+ "template_id": "{template}",
+ "filled": {},
+ },
+ why="Run as a saved template the caller may read: a private one isn't there to anyone else.",
+ ),
+ "GET /gateway/rooms/{room_id}": get(f"{G}/rooms/{{room}}", owner_or_admins()),
+ "GET /gateway/rooms/{room_id}/yaml": get(
+ f"{G}/rooms/{{room}}/yaml", owner_or_admins()
+ ),
+ "PATCH /gateway/rooms/{room_id}": patch(
+ f"{G}/rooms/{{room}}", owner_or_admins(), json={"description": "changed"}
+ ),
+ "DELETE /gateway/rooms/{room_id}": delete(f"{G}/rooms/{{room}}", owner_or_admins()),
+ "POST /gateway/rooms/{room_id}/archive": post(
+ f"{G}/rooms/{{room}}/archive", owner_or_admins()
+ ),
+ "POST /gateway/rooms/{room_id}/unarchive": post(
+ f"{G}/rooms/{{room}}/unarchive", owner_or_admins()
+ ),
+ "POST /gateway/rooms/{room_id}/sync-name": post(
+ f"{G}/rooms/{{room}}/sync-name",
+ owner_or_admins(ok=409),
+ why="Let through, then refused: the room has no platform channel to name.",
+ ),
+ "GET /gateway/rooms/{room_id}/roles": get(
+ f"{G}/rooms/{{room}}/roles", owner_or_admins()
+ ),
+ "POST /gateway/rooms/{room_id}/roles": post(
+ f"{G}/rooms/{{room}}/roles",
+ owner_or_admins(),
+ json={"name": "reviewer", "instructions": "Review.", "exclusive": False},
+ ),
+ "PATCH /gateway/rooms/{room_id}/roles/{name}": patch(
+ f"{G}/rooms/{{room_role}}/roles/reviewer",
+ owner_or_admins(),
+ json={"instructions": "Review again."},
+ ),
+ "DELETE /gateway/rooms/{room_id}/roles/{name}": delete(
+ f"{G}/rooms/{{room_role}}/roles/reviewer", owner_or_admins()
+ ),
+ "PUT /gateway/rooms/{room_id}/protection": put(
+ f"{G}/rooms/{{room}}/protection",
+ owner_or_admins(),
+ json={"protection_config": {}},
+ ),
+ "PUT /gateway/rooms/{room_id}/observe": put(
+ f"{G}/rooms/{{room}}/observe", owner_or_admins(), json={"observe_config": {}}
+ ),
+ "POST /gateway/rooms/{room_id}/agents": post(
+ f"{G}/rooms/{{room}}/agents", owner_or_admins(), json={"agent_ids": ["{agent}"]}
+ ),
+ "PATCH /gateway/rooms/{room_id}/agents/{agent_id}": patch(
+ f"{G}/rooms/{{room_agent}}/agents/{{agent}}",
+ owner_or_admins(),
+ json={"receives_join_events": True},
+ ),
+ "DELETE /gateway/rooms/{room_id}/agents/{agent_id}": delete(
+ f"{G}/rooms/{{room_agent}}/agents/{{agent}}", owner_or_admins()
+ ),
+ "POST /gateway/rooms/{room_id}/users": post(
+ f"{G}/rooms/{{room}}/users",
+ owner_or_admins(ok=400),
+ json={"user_names": []},
+ why="Let through, then refused: people join through the room's platform channel, and it has none.",
+ ),
+ "PUT /gateway/rooms/{room_id}/group": put(
+ f"{G}/rooms/{{room}}/group",
+ admins(),
+ json={"group_id": "{room_group}"},
+ why="Filing a room in a group is an admin's: groups feed addressing policies.",
+ ),
+ "POST /gateway/rooms/bulk-delete": post(
+ f"{G}/rooms/bulk-delete",
+ anyone(ok=200),
+ json={"room_ids": ["{room}"]},
+ why="Skips each room the caller may not delete; see `test_bulk_room_actions`.",
+ ),
+ "POST /gateway/rooms/bulk-archive": post(
+ f"{G}/rooms/bulk-archive",
+ anyone(ok=200),
+ json={"room_ids": ["{room}"], "archived": True},
+ why="Skips each room the caller may not change; see `test_bulk_room_actions`.",
+ ),
+ "GET /gateway/linked-rooms/graph": get(f"{G}/linked-rooms/graph", anyone()),
+ "GET /gateway/rooms/{room_id}/linked-rooms": get(
+ f"{G}/rooms/{{room}}/linked-rooms", owner_or_admins()
+ ),
+ "GET /gateway/rooms/{room_id}/linked-rooms/inbound": get(
+ f"{G}/rooms/{{room}}/linked-rooms/inbound", owner_or_admins()
+ ),
+ "POST /gateway/rooms/{room_id}/linked-rooms": post(
+ f"{G}/rooms/{{room}}/linked-rooms",
+ owner_or_admins(),
+ json={"target_room_id": "{other_room}", "label": "related"},
+ ),
+ "DELETE /gateway/rooms/{room_id}/linked-rooms/{target_room_id}": delete(
+ f"{G}/rooms/{{linked_room}}/linked-rooms/{{other_room}}", owner_or_admins()
+ ),
+ "GET /gateway/rooms/{room_id}/references": get(
+ f"{G}/rooms/{{room}}/references", owner_or_admins()
+ ),
+ "POST /gateway/rooms/{room_id}/references/{reference_id}": post(
+ f"{G}/rooms/{{room}}/references/{{reference}}", owner_or_admins()
+ ),
+ "DELETE /gateway/rooms/{room_id}/references/{reference_id}": delete(
+ f"{G}/rooms/{{room_reference}}/references/{{reference}}", owner_or_admins()
+ ),
+ "GET /gateway/rooms/{room_id}/documents": get(
+ f"{G}/rooms/{{room}}/documents", owner_or_admins()
+ ),
+ "GET /gateway/rooms/{room_id}/documents/{document_id}": get(
+ f"{G}/rooms/{{room_document}}/documents/{{document}}", owner_or_admins()
+ ),
+ "POST /gateway/rooms/{room_id}/documents/{document_id}": post(
+ f"{G}/rooms/{{room}}/documents/{{document}}", owner_or_admins()
+ ),
+ "DELETE /gateway/rooms/{room_id}/documents/{document_id}": delete(
+ f"{G}/rooms/{{room_document}}/documents/{{document}}", owner_or_admins()
+ ),
+ "GET /gateway/rooms/{room_id}/packages": get(
+ f"{G}/rooms/{{room}}/packages", owner_or_admins()
+ ),
+ "POST /gateway/rooms/{room_id}/packages/{package_id}": post(
+ f"{G}/rooms/{{room}}/packages/{{package}}", owner_or_admins()
+ ),
+ "DELETE /gateway/rooms/{room_id}/packages/{package_id}": delete(
+ f"{G}/rooms/{{room_package}}/packages/{{package}}", owner_or_admins()
+ ),
+ # ── Room groups ──────────────────────────────────────────────────────
+ "GET /gateway/room-groups": get(f"{G}/room-groups", anyone()),
+ "POST /gateway/room-groups": post(
+ f"{G}/room-groups", admins(), json={"name": "{tag}-new-group"}
+ ),
+ "PATCH /gateway/room-groups/{group_id}": patch(
+ f"{G}/room-groups/{{room_group}}", admins(), json={"description": "changed"}
+ ),
+ "DELETE /gateway/room-groups/{group_id}": delete(
+ f"{G}/room-groups/{{room_group}}", admins()
+ ),
+ "PUT /gateway/room-groups/{group_id}/rooms": put(
+ f"{G}/room-groups/{{room_group}}/rooms",
+ admins(),
+ json={"room_ids": ["{room}"]},
+ ),
+ # ── References, documents, packages ──────────────────────────────────
+ "GET /gateway/references": get(f"{G}/references", anyone()),
+ "POST /gateway/references": post(
+ f"{G}/references",
+ SELF,
+ json={
+ "type": "github",
+ "name": "{tag}-new",
+ "description": "",
+ "instructions": "",
+ "value": {"urls": ["https://github.com/example/project"]},
+ },
+ ),
+ "GET /gateway/references/{reference_id}": get(
+ f"{G}/references/{{reference}}", owner_or_admins()
+ ),
+ "PATCH /gateway/references/{reference_id}": patch(
+ f"{G}/references/{{reference}}", owner_or_admins(), json={"description": "x"}
+ ),
+ "DELETE /gateway/references/{reference_id}": delete(
+ f"{G}/references/{{reference}}", owner_or_admins()
+ ),
+ "GET /gateway/references/{reference_id}/rooms": get(
+ f"{G}/references/{{reference}}/rooms", owner_or_admins()
+ ),
+ "GET /gateway/references/reference-types": get(
+ f"{G}/references/reference-types", anyone()
+ ),
+ "GET /gateway/references/reference-types/owned": get(
+ f"{G}/references/reference-types/owned", anyone()
+ ),
+ "POST /gateway/references/reference-types": post(
+ f"{G}/references/reference-types",
+ SELF,
+ json={
+ "type": "{slug}",
+ "display_name": "New",
+ "instructions": "",
+ "value_hint": "",
+ },
+ ),
+ "PATCH /gateway/references/reference-types/{type}": patch(
+ f"{G}/references/reference-types/{{reference_type}}",
+ owner_or_admins(),
+ json={"display_name": "Changed"},
+ ),
+ "DELETE /gateway/references/reference-types/{type}": delete(
+ f"{G}/references/reference-types/{{reference_type}}", owner_or_admins()
+ ),
+ "GET /gateway/documents": get(f"{G}/documents", anyone()),
+ "POST /gateway/documents": post(
+ f"{G}/documents",
+ SELF,
+ json={
+ "name": "{tag}-new",
+ "description": "",
+ "instructions": "",
+ "content": "",
+ },
+ ),
+ "GET /gateway/documents/{document_id}": get(
+ f"{G}/documents/{{document}}", owner_or_admins()
+ ),
+ "PATCH /gateway/documents/{document_id}": patch(
+ f"{G}/documents/{{document}}", owner_or_admins(), json={"description": "x"}
+ ),
+ "DELETE /gateway/documents/{document_id}": delete(
+ f"{G}/documents/{{document}}", owner_or_admins()
+ ),
+ "GET /gateway/documents/{document_id}/rooms": get(
+ f"{G}/documents/{{document}}/rooms", owner_or_admins()
+ ),
+ "GET /gateway/packages": get(f"{G}/packages", anyone()),
+ "POST /gateway/packages": post(
+ f"{G}/packages",
+ SELF,
+ json={"name": "{tag}-new", "description": "", "instructions": ""},
+ ),
+ "GET /gateway/packages/{package_id}": get(
+ f"{G}/packages/{{package}}", owner_or_admins()
+ ),
+ "PATCH /gateway/packages/{package_id}": patch(
+ f"{G}/packages/{{package}}", owner_or_admins(), json={"description": "x"}
+ ),
+ "DELETE /gateway/packages/{package_id}": delete(
+ f"{G}/packages/{{package}}", owner_or_admins()
+ ),
+ "GET /gateway/packages/{package_id}/rooms": get(
+ f"{G}/packages/{{package}}/rooms", owner_or_admins()
+ ),
+ "GET /gateway/packages/{package_id}/references": get(
+ f"{G}/packages/{{package}}/references", owner_or_admins()
+ ),
+ "POST /gateway/packages/{package_id}/references/{reference_id}": post(
+ f"{G}/packages/{{package}}/references/{{reference}}", owner_or_admins()
+ ),
+ "DELETE /gateway/packages/{package_id}/references/{reference_id}": delete(
+ f"{G}/packages/{{package_reference}}/references/{{reference}}",
+ owner_or_admins(),
+ ),
+ "GET /gateway/packages/{package_id}/documents": get(
+ f"{G}/packages/{{package}}/documents", owner_or_admins()
+ ),
+ "POST /gateway/packages/{package_id}/documents/{document_id}": post(
+ f"{G}/packages/{{package}}/documents/{{document}}", owner_or_admins()
+ ),
+ "DELETE /gateway/packages/{package_id}/documents/{document_id}": delete(
+ f"{G}/packages/{{package_document}}/documents/{{document}}",
+ owner_or_admins(),
+ ),
+ # ── Templates ────────────────────────────────────────────────────────
+ "GET /gateway/templates": get(f"{G}/templates", anyone()),
+ "POST /gateway/templates": post(
+ f"{G}/templates", SELF, json={"name": "{tag}-new", "content": "name: x\n"}
+ ),
+ "POST /gateway/templates/validate": post(
+ f"{G}/templates/validate", SELF, json={"content": "name: x\n"}
+ ),
+ "GET /gateway/templates/{template_id}": get(
+ f"{G}/templates/{{template}}",
+ owner_or_admins(refused=404),
+ why="A private template is not there for whoever may not read it.",
+ ),
+ "GET /gateway/templates/{template_id}/content": get(
+ f"{G}/templates/{{template}}/content", owner_or_admins(refused=404)
+ ),
+ "PATCH /gateway/templates/{template_id}": patch(
+ f"{G}/templates/{{template}}",
+ owner_or_admins(refused=404),
+ json={"description": "changed"},
+ ),
+ "DELETE /gateway/templates/{template_id}": delete(
+ f"{G}/templates/{{template}}", owner_or_admins(refused=404)
+ ),
+ "GET /gateway/template-runs": get(f"{G}/template-runs", anyone()),
+ "POST /gateway/template-runs/{root_room_id}/stop": post(
+ f"{G}/template-runs/{{room}}/stop",
+ admins(),
+ why=(
+ "An admin, an owner of an agent in the run, or whoever ran it: "
+ "owning its first room is none of those."
+ ),
+ ),
+ "POST /gateway/template-runs/{root_room_id}/continue": post(
+ f"{G}/template-runs/{{room}}/continue", admins()
+ ),
+ # ── Messaging apps ───────────────────────────────────────────────────
+ "GET /gateway/collaborations": get(f"{G}/collaborations", anyone()),
+ "GET /gateway/collaborations/types": get(f"{G}/collaborations/types", anyone()),
+ "GET /gateway/collaborations/setup/slack": get(
+ f"{G}/collaborations/setup/slack", admins()
+ ),
+ "POST /gateway/collaborations/setup/slack/check": post(
+ f"{G}/collaborations/setup/slack/check",
+ admins(ok=422),
+ json={"bot_token": "not-a-bot-token", "app_token": "not-an-app-token"},
+ why="Let through, then refused before Slack is asked: neither token is one.",
+ ),
+ "POST /gateway/collaborations": post(
+ f"{G}/collaborations",
+ admins(),
+ json={
+ "bridge_type": "mattermost",
+ "display_name": "{tag}-new-bridge",
+ "connection_config": {},
+ },
+ ),
+ "PATCH /gateway/collaborations/{bridge_id}": patch(
+ f"{G}/collaborations/{{bridge}}",
+ admins(),
+ json={"agent_greetings_enabled": True},
+ ),
+ "POST /gateway/collaborations/{bridge_id}/default": post(
+ f"{G}/collaborations/{{bridge}}/default", admins()
+ ),
+ "DELETE /gateway/collaborations/{bridge_id}": delete(
+ f"{G}/collaborations/{{bridge}}", admins()
+ ),
+ "GET /gateway/collaborations/{bridge_id}/users": get(
+ f"{G}/collaborations/{{bridge}}/users", anyone()
+ ),
+ "GET /gateway/collaborations/{bridge_id}/directory": get(
+ f"{G}/collaborations/{{bridge}}/directory",
+ anyone(ok=409),
+ why="Anyone in the workspace; the bridge isn't running to search.",
+ query="matrix",
+ ),
+ "POST /gateway/collaborations/{bridge_id}/identities": post(
+ f"{G}/collaborations/{{bridge}}/identities",
+ owner_or_admins(ok=409),
+ json={
+ "external_user_id": "U-{tag}-claimed",
+ "username": "claimed",
+ "user_id": "{owner}",
+ "expects_confirmation": True,
+ },
+ why=(
+ "Claiming an account for someone: themselves, or anyone for an "
+ "admin; then refused, the bridge not running to check the account."
+ ),
+ ),
+ "DELETE /gateway/collaborations/{bridge_id}/identities/{external_user_row_id}": Case(
+ Ask(
+ "DELETE",
+ f"{G}/collaborations/{{bridge}}/identities/{{identity}}",
+ params={"user_id": "{owner}"},
+ ),
+ owner_or_admins(),
+ why="Dropping someone's claim: their own, or anyone's for an admin.",
+ ),
+ "DELETE /gateway/collaborations/{bridge_id}/identities/{external_user_row_id}/request": Case(
+ Ask(
+ "DELETE",
+ f"{G}/collaborations/{{bridge}}/identities/{{identity}}/request",
+ params={"user_id": "{owner}"},
+ ),
+ owner_or_admins(ok=404),
+ why="Their own, or anyone's for an admin; there is no link waiting to drop.",
+ ),
+ "POST /gateway/collaborations/{bridge_id}/identities/{external_user_row_id}/code": post(
+ f"{G}/collaborations/{{bridge}}/identities/{{identity}}/code",
+ anyone(ok=409),
+ why="For the caller's own link; the bridge isn't running to check the account.",
+ ),
+ "POST /gateway/collaborations/{bridge_id}/identities/{external_user_row_id}/verify-session": post(
+ f"{G}/collaborations/{{bridge}}/identities/{{identity}}/verify-session",
+ anyone(ok=404),
+ json={"token": "session-token"},
+ why="For the caller's own link waiting to be confirmed; nobody has one.",
+ ),
+ "GET /gateway/collaborations/{bridge_id}/identities/unconfirmed": get(
+ f"{G}/collaborations/{{bridge}}/identities/unconfirmed", admins()
+ ),
+ "POST /gateway/collaborations/{bridge_id}/identities/require-confirmation": post(
+ f"{G}/collaborations/{{bridge}}/identities/require-confirmation",
+ admins(),
+ json={"links": []},
+ ),
+ "GET /gateway/collaborations/{bridge_id}/teams": get(
+ f"{G}/collaborations/{{bridge}}/teams", admins(ok=404)
+ ),
+ "POST /gateway/collaborations/{bridge_id}/teams/{team_id}": post(
+ f"{G}/collaborations/{{bridge}}/teams/team-1", admins(ok=404)
+ ),
+ "DELETE /gateway/collaborations/{bridge_id}/teams/{team_id}": delete(
+ f"{G}/collaborations/{{bridge}}/teams/team-1", admins(ok=404)
+ ),
+ "GET /gateway/collaborations/{bridge_id}/teams-package": get(
+ f"{G}/collaborations/{{bridge}}/teams-package", admins(ok=404)
+ ),
+ "GET /gateway/messaging-apps": get(f"{G}/messaging-apps", anyone()),
+ "POST /gateway/messaging-apps/{platform}/claim": post(
+ f"{G}/messaging-apps/telegram/claim",
+ admins(),
+ why="A member adds a chat only once an admin has connected the platform.",
+ ),
+ "POST /gateway/messaging-apps/{platform}/install": post(
+ f"{G}/messaging-apps/slack/install", admins()
+ ),
+ "GET /gateway/messaging-apps/installs": get(
+ f"{G}/messaging-apps/installs", anyone()
+ ),
+ "DELETE /gateway/messaging-apps/installs/{install_id}": delete(
+ f"{G}/messaging-apps/installs/{{oauth_install}}",
+ admins(),
+ why="An OAuth install is the workspace's admins'.",
+ ),
+ # ── Devices ──────────────────────────────────────────────────────────
+ "POST /gateway/management/enrollment-codes": post(
+ f"{G}/management/enrollment-codes", SELF
+ ),
+ "POST /gateway/management/controllers": post(
+ f"{G}/management/controllers",
+ SELF,
+ json={
+ "name": "{tag}-console",
+ "kind": "console",
+ "platform": {"os": "linux", "arch": "x64", "os_version": "6.1.0"},
+ "version": "0.1.0",
+ },
+ ),
+ "GET /gateway/management/controllers": get(f"{G}/management/controllers", SELF),
+ "PATCH /gateway/management/controllers/{controller_id}": patch(
+ f"{G}/management/controllers/{{controller}}",
+ owner(),
+ json={"description": "changed"},
+ why="Every machine is its owner's alone; anyone else is told it isn't there.",
+ ),
+ "DELETE /gateway/management/controllers/{controller_id}": delete(
+ f"{G}/management/controllers/{{controller}}", owner()
+ ),
+ "GET /gateway/management/controllers/{controller_id}/provider-logins": get(
+ f"{G}/management/controllers/{{controller}}/provider-logins", owner()
+ ),
+ "PUT /gateway/management/controllers/{controller_id}/provider-logins/{provider}": put(
+ f"{G}/management/controllers/{{controller}}/provider-logins/claude",
+ owner(ok=409),
+ json={"sealed": "{sealed_login}"},
+ why="Its owner's; refused then, the machine having no key to seal to.",
+ ),
+ "DELETE /gateway/management/controllers/{controller_id}/provider-logins/{provider}": delete(
+ f"{G}/management/controllers/{{controller}}/provider-logins/claude",
+ owner(ok=404),
+ why="Its owner's; it has no login for this provider to withdraw.",
+ ),
+ "GET /gateway/management/agents": get(f"{G}/management/agents", SELF),
+ "POST /gateway/management/agents": post(
+ f"{G}/management/agents",
+ SELF,
+ json={
+ "name": "{tag}-managed",
+ "description": "",
+ "controller_id": None,
+ "desired_state": "stopped",
+ "definition": "{definition}",
+ },
+ ),
+ "GET /gateway/management/agents/{agent_id}": get(
+ f"{G}/management/agents/{{managed_agent}}", owner()
+ ),
+ "PUT /gateway/management/agents/{agent_id}": put(
+ f"{G}/management/agents/{{managed_agent}}",
+ owner(),
+ json={
+ "controller_id": None,
+ "desired_state": "stopped",
+ "definition": "{definition}",
+ },
+ ),
+ "PATCH /gateway/management/agents/{agent_id}": patch(
+ f"{G}/management/agents/{{managed_agent}}",
+ owner(),
+ json={"desired_state": "stopped"},
+ ),
+ "DELETE /gateway/management/agents/{agent_id}": delete(
+ f"{G}/management/agents/{{managed_agent}}", owner()
+ ),
+ "POST /gateway/management/operations": post(
+ f"{G}/management/operations",
+ owner(),
+ json={
+ "controller_id": "{controller}",
+ "kind": "provider.recheck",
+ "params": {"provider": "claude"},
+ },
+ ),
+ "GET /gateway/management/operations": get(
+ f"{G}/management/operations", owner(), controller_id="{controller}"
+ ),
+ "GET /gateway/management/providers": get(f"{G}/management/providers", anyone()),
+ "GET /gateway/management/advanced-config": get(
+ f"{G}/management/advanced-config", anyone(), provider="claude"
+ ),
+ "GET /gateway/hosted-machines": get(f"{G}/hosted-machines", SELF),
+ "POST /gateway/hosted-machines/ensure": post(
+ f"{G}/hosted-machines/ensure",
+ anyone(ok=503),
+ why="Your own; this server offers no cloud machines.",
+ ),
+ "GET /gateway/hosted-machines/{machine_id}": get(
+ f"{G}/hosted-machines/no-such-machine",
+ anyone(ok=404),
+ why="Your own machine; nobody here has one.",
+ ),
+ "POST /gateway/hosted-machines/{machine_id}/lifecycle": post(
+ f"{G}/hosted-machines/no-such-machine/lifecycle",
+ anyone(ok=404),
+ json={"action": "stop", "revision": 1},
+ why="Your own machine; nobody here has one.",
+ ),
+ # ── Connections ──────────────────────────────────────────────────────
+ "GET /gateway/provider-connections/catalog": get(
+ f"{G}/provider-connections/catalog", SELF
+ ),
+ "GET /gateway/service-connections": get(f"{G}/service-connections", SELF),
+ "GET /gateway/service-connections/{service}/agents": get(
+ f"{G}/service-connections/github/agents", SELF
+ ),
+ "PUT /gateway/service-connections/{service}/key": put(
+ f"{G}/service-connections/datadog/key",
+ anyone(ok=403),
+ json={"fields": {"api_key": "matrix", "application_key": "matrix"}},
+ why="Your own connection; refused for anyone, Datadog keys never being handed to agents.",
+ ),
+ "DELETE /gateway/service-connections/{service}": delete(
+ f"{G}/service-connections/github",
+ anyone(ok=404),
+ why="Ends the caller's own connection, and none of them has one.",
+ ),
+ "POST /gateway/service-connections/{service}/flows": post(
+ f"{G}/service-connections/atlassian/flows",
+ anyone(ok=503),
+ json=FLOW,
+ why="Your own sign-in; this server has no Atlassian app to sign in through.",
+ ),
+ "GET /gateway/service-connections/{service}/flows/{flow_id}": get(
+ f"{G}/service-connections/atlassian/flows/{{service_flow}}",
+ owner(refused=410),
+ why="Its owner's; anyone else is told it was interrupted, as if it were gone.",
+ ),
+ "DELETE /gateway/service-connections/{service}/flows/{flow_id}": delete(
+ f"{G}/service-connections/atlassian/flows/{{service_flow}}",
+ owner(refused=410),
+ ),
+ "POST /gateway/service-connections/{service}/flows/{flow_id}/complete": post(
+ f"{G}/service-connections/atlassian/flows/{{service_flow}}/complete",
+ owner(ok=503, refused=410),
+ json={"completion_secret": "{flow_secret}", "code": "matrix"},
+ why="Its owner's; refused then, this server having no Atlassian app.",
+ ),
+ "GET /gateway/provider-connections/github": get(
+ f"{G}/provider-connections/github", SELF
+ ),
+ "DELETE /gateway/provider-connections/github": delete(
+ f"{G}/provider-connections/github", SELF
+ ),
+ "POST /gateway/provider-connections/github/flows": post(
+ f"{G}/provider-connections/github/flows", SELF, json=FLOW
+ ),
+ "GET /gateway/provider-connections/github/flows/{flow_id}": get(
+ f"{G}/provider-connections/github/flows/{{github_flow}}", owner()
+ ),
+ "DELETE /gateway/provider-connections/github/flows/{flow_id}": delete(
+ f"{G}/provider-connections/github/flows/{{github_flow}}", owner()
+ ),
+ "POST /gateway/provider-connections/github/flows/{flow_id}/complete": post(
+ f"{G}/provider-connections/github/flows/{{github_flow}}/complete",
+ owner(ok=400),
+ json={"completion_secret": "{flow_secret}", "code": "matrix"},
+ why="Its owner's; refused then, the secret not being the one it was started with.",
+ ),
+ # ── Overview ─────────────────────────────────────────────────────────
+ "GET /gateway/ecosystem/graph": get(f"{G}/ecosystem/graph", anyone()),
+}
+
+# Chats: a Switch Console chat is a room only the people in it may open, so
+# everyone else is refused whatever they administer; its owner manages it.
+CHAT = f"{G}/chats/{{chat}}"
+MEMBERS_OF_IT = owner(refused=403)
+
+ROUTES.update(
+ {
+ "GET /gateway/chats": get(f"{G}/chats", SELF),
+ "GET /gateway/chats/archived": get(f"{G}/chats/archived", SELF),
+ "GET /gateway/chats/agent-candidates": get(f"{G}/chats/agent-candidates", SELF),
+ "POST /gateway/chats": post(
+ f"{G}/chats",
+ SELF,
+ json={"agentId": "{agent}", "requestId": "{tag}-new-chat"},
+ why="Anyone may start a chat with an agent open to them.",
+ ),
+ "GET /gateway/chats/{room_id}/activity": get(f"{CHAT}/activity", MEMBERS_OF_IT),
+ "GET /gateway/chats/{room_id}/messages": get(f"{CHAT}/messages", MEMBERS_OF_IT),
+ "GET /gateway/chats/{room_id}/threads/{root_id}/messages": get(
+ f"{CHAT}/threads/no-such-root/messages",
+ owner(ok=404, refused=403),
+ why="The people in it; there is no such thread.",
+ ),
+ "GET /gateway/chats/{room_id}/media": get(
+ f"{CHAT}/media",
+ owner(ok=404, refused=403),
+ why="The people in it; there is no such file.",
+ uri="mxc://switch.test/no-such-file",
+ ),
+ "GET /gateway/chats/{room_id}/members": get(f"{CHAT}/members", MEMBERS_OF_IT),
+ "GET /gateway/chats/{room_id}/commands": get(f"{CHAT}/commands", MEMBERS_OF_IT),
+ "POST /gateway/chats/{room_id}/messages": post(
+ f"{CHAT}/messages",
+ MEMBERS_OF_IT,
+ json={"requestId": "{tag}-message", "body": "hello"},
+ ),
+ "POST /gateway/chats/{room_id}/controls": post(
+ f"{CHAT}/controls",
+ owner(ok=409, refused=403),
+ json={
+ "requestId": "{tag}-control",
+ "agentId": "{agent}",
+ "command": "interrupt",
+ },
+ why="The people in it; nothing is running to interrupt.",
+ ),
+ "POST /gateway/chats/{room_id}/warm": post(
+ f"{CHAT}/warm", MEMBERS_OF_IT, json={"agentId": "{agent}"}
+ ),
+ "PUT /gateway/chats/{room_id}/read": put(
+ f"{CHAT}/read", MEMBERS_OF_IT, json={"seq": 0}
+ ),
+ "PUT /gateway/chats/{room_id}/hidden": put(f"{CHAT}/hidden", MEMBERS_OF_IT),
+ "DELETE /gateway/chats/{room_id}/hidden": delete(
+ f"{CHAT}/hidden", MEMBERS_OF_IT
+ ),
+ "POST /gateway/chats/{room_id}/members": post(
+ f"{CHAT}/members",
+ owner_or_admins(),
+ json={"userId": "{member}"},
+ why="Its owner, or an admin, manages who is in it.",
+ ),
+ "DELETE /gateway/chats/{room_id}/members/{member_user_id}": delete(
+ f"{CHAT}/members/{{chat_guest}}", owner_or_admins()
+ ),
+ "POST /gateway/chats/{room_id}/agents": post(
+ f"{CHAT}/agents", owner_or_admins(), json={"agentId": "{other_agent}"}
+ ),
+ "DELETE /gateway/chats/{room_id}/agents/{agent_id}": delete(
+ f"{CHAT}/agents/{{agent}}", owner_or_admins()
+ ),
+ "POST /gateway/chats/{room_id}/archive": post(
+ f"{CHAT}/archive",
+ MEMBERS_OF_IT,
+ why="Archiving is for the people in it, whoever administers the workspace.",
+ ),
+ "POST /gateway/chats/{room_id}/unarchive": post(
+ f"{CHAT}/unarchive", MEMBERS_OF_IT
+ ),
+ }
+)
+
+# Routes whose answers stream, asked by `test_streams_answer_whom_they_should`.
+STREAMS: dict[str, Case] = {
+ "GET /gateway/chats/events": get(f"{G}/chats/events", SELF),
+ "GET /gateway/chats/activity/events": get(f"{G}/chats/activity/events", SELF),
+ "WS /gateway/changes/ws": get(f"{G}/changes/ws", SELF),
+ "POST /gateway/chats/{room_id}/attachments": post(
+ f"{CHAT}/attachments", MEMBERS_OF_IT
+ ),
+}
+
+# Routes that take no session, or the hosted controller's token: no persona
+# changes their answer, so each is asked once and must answer the same to all.
+UNAUTHENTICATED: dict[str, str] = {
+ "GET /gateway/agents/known-types": "The agent types any client may register.",
+ "GET /gateway/auth/config": "How to sign in, read before anyone has.",
+ "GET /gateway/auth/oidc/callback": "A sign-in coming back from the identity provider.",
+ "GET /gateway/auth/oidc/login": "Starting a sign-in.",
+ "POST /gateway/auth/oidc/exchange": "Finishing a sign-in with its one-time code.",
+ "POST /gateway/auth/login": "Signing in.",
+ "POST /gateway/auth/logout": "Signing out, which only clears the cookie.",
+ "POST /gateway/auth/signup": "Signing up.",
+ "GET /gateway/docs": "The API's own documentation.",
+ "GET /gateway/docs/oauth2-redirect": "The API's own documentation.",
+ "GET /gateway/openapi.json": "The API's own documentation.",
+ "GET /gateway/redoc": "The API's own documentation.",
+ "GET /gateway/provider-connections/github/authorize": (
+ "A browser handoff, tied to its flow by the state it carries."
+ ),
+ "GET /gateway/provider-connections/github/callback": (
+ "A browser handoff, tied to its flow by the state it carries."
+ ),
+ "GET /gateway/service-connections/{service}/flows/authorize": (
+ "A browser handoff, tied to its flow by the state it carries."
+ ),
+ "GET /gateway/service-connections/{service}/flows/callback": (
+ "A browser handoff, tied to its flow by the state it carries."
+ ),
+ "GET /gateway/hosted-controller/machines": (
+ "The hosted controller's, with its operator token; no session reaches it."
+ ),
+ "POST /gateway/hosted-controller/machines/{machine_id}/observation": (
+ "The hosted controller's, with its operator token; no session reaches it."
+ ),
+ "POST /gateway/hosted-controller/machines/{machine_id}/prepare": (
+ "The hosted controller's, with its operator token; no session reaches it."
+ ),
+}
diff --git a/core/tests/switch_core/gateway/role_matrix/test_flags_match_routes.py b/core/tests/switch_core/gateway/role_matrix/test_flags_match_routes.py
new file mode 100644
index 000000000..6e52c311a
--- /dev/null
+++ b/core/tests/switch_core/gateway/role_matrix/test_flags_match_routes.py
@@ -0,0 +1,584 @@
+"""Every capability flag says what its route does.
+
+Each persona reads a flag where the Gateway shows it, then asks the route it
+speaks for. A flag that says yes must be let through, and one that says no
+must be refused: so a wrong flag can't hide behind a correct route. A check
+names the refusals a flag leaves to the moment it is asked (the workspace
+isn't empty, say), which count as let through; any other answer, a server
+error above all, fails it either way.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from tests.switch_core.gateway.role_matrix.access import OK
+from tests.switch_core.gateway.role_matrix.harness import (
+ Persona,
+ build_gateway,
+ client,
+ seed_people,
+)
+from tests.switch_core.gateway.role_matrix.routes import Ask
+from tests.switch_core.gateway.role_matrix.world import World
+
+G = "/gateway"
+REFUSED = frozenset({403, 404, 410})
+
+
+@dataclass(frozen=True)
+class Check:
+ flag: str
+ read: Ask
+ act: Ask
+ # Where the thing is in what `read` answers: the key of the list holding
+ # it (None for a list answered bare), and the field and `World` name that
+ # pick it out of the list; no `match` for a detail answered alone.
+ match: tuple[str, str] | None = None
+ within: str | None = None
+ # What the route answers when it says no to what the flag covers.
+ refused: frozenset[int] = REFUSED
+ # What it answers, past what the flag covers, when the thing can't be
+ # done just then: let through as far as the flag is concerned.
+ later: frozenset[int] = frozenset()
+
+
+def _get(path: str, **params: str) -> Ask:
+ return Ask("GET", path, params=params)
+
+
+def _act(method: str, path: str, json: Any = None, **params: str) -> Ask:
+ return Ask(method, path, json=json, params=params)
+
+
+def _transfer(kind: str, thing: str) -> Ask:
+ return _act(
+ "POST",
+ f"{G}/ownership/transfer",
+ {"kind": kind, "id": thing, "new_owner_id": "{member_target}"},
+ )
+
+
+def _resource(kind: str, path: str, transfers: bool) -> list[Check]:
+ detail = _get(f"{G}/{path}/{{{kind}}}")
+ checks = [
+ Check(
+ "can_edit",
+ detail,
+ _act("PATCH", f"{G}/{path}/{{{kind}}}", {"description": "x"}),
+ ),
+ Check("can_manage", detail, _act("DELETE", f"{G}/{path}/{{{kind}}}")),
+ ]
+ if transfers:
+ checks.append(Check("can_transfer", detail, _transfer(kind, f"{{{kind}}}")))
+ return checks
+
+
+AGENT = _get(f"{G}/agents/{{agent}}")
+MEMBERS = _get(f"{G}/tenants/{{tenant}}/members")
+ORG_MEMBERS = _get(f"{G}/organizations/current/members")
+
+CHECKS: dict[str, Check] = {
+ f"{check.flag} on {name}, asking {check.act.method} {check.act.path}": check
+ for name, checks in {
+ "a reference": [
+ *_resource("reference", "references", transfers=False),
+ Check(
+ "can_manage",
+ _get(f"{G}/references/{{reference}}"),
+ _transfer("reference", "{reference}"),
+ ),
+ ],
+ "a document": _resource("document", "documents", transfers=True),
+ "a room's own document": [
+ Check(
+ flag,
+ _get(f"{G}/documents/{{room_document_itself}}"),
+ act,
+ refused=REFUSED | {409},
+ )
+ for flag, act in (
+ (
+ "can_edit",
+ _act(
+ "PATCH",
+ f"{G}/documents/{{room_document_itself}}",
+ {"description": "x"},
+ ),
+ ),
+ (
+ "can_manage",
+ _act("DELETE", f"{G}/documents/{{room_document_itself}}"),
+ ),
+ ("can_transfer", _transfer("document", "{room_document_itself}")),
+ )
+ ],
+ "a package": [
+ *_resource("package", "packages", transfers=False),
+ Check(
+ "can_manage",
+ _get(f"{G}/packages/{{package}}"),
+ _transfer("package", "{package}"),
+ ),
+ ],
+ "a template": [
+ Check(
+ "can_edit",
+ _get(f"{G}/templates/{{template}}"),
+ _act("PATCH", f"{G}/templates/{{template}}", {"description": "x"}),
+ ),
+ Check(
+ "can_manage",
+ _get(f"{G}/templates/{{template}}"),
+ _act("DELETE", f"{G}/templates/{{template}}"),
+ ),
+ ],
+ "a reference type": [
+ Check(
+ "can_edit",
+ _get(f"{G}/references/reference-types/owned"),
+ _act(
+ "PATCH",
+ f"{G}/references/reference-types/{{reference_type}}",
+ {"display_name": "x"},
+ ),
+ match=("type", "reference_type"),
+ ),
+ Check(
+ "can_manage",
+ _get(f"{G}/references/reference-types/owned"),
+ _act("DELETE", f"{G}/references/reference-types/{{reference_type}}"),
+ match=("type", "reference_type"),
+ ),
+ ],
+ "a room": [
+ Check(
+ "can_write",
+ _get(f"{G}/rooms/{{readable_room}}"),
+ _act("PATCH", f"{G}/rooms/{{readable_room}}", {"description": "x"}),
+ ),
+ Check(
+ "can_manage",
+ _get(f"{G}/rooms/{{readable_room}}"),
+ _act("DELETE", f"{G}/rooms/{{readable_room}}"),
+ ),
+ Check(
+ "can_transfer",
+ _get(f"{G}/rooms/{{readable_room}}"),
+ _transfer("room", "{readable_room}"),
+ ),
+ Check(
+ "can_change_members",
+ _get(f"{G}/rooms/{{readable_room}}"),
+ _act(
+ "POST",
+ f"{G}/rooms/{{readable_room}}/agents",
+ {"agent_ids": ["{agent}"]},
+ ),
+ ),
+ ],
+ "a direct conversation": [
+ Check(
+ "can_change_members",
+ _get(f"{G}/rooms/{{direct_room}}"),
+ act,
+ refused=REFUSED | {409},
+ )
+ for act in (
+ _act(
+ "POST",
+ f"{G}/rooms/{{direct_room}}/agents",
+ {"agent_ids": ["{agent}"]},
+ ),
+ _act(
+ "POST",
+ f"{G}/rooms/{{direct_room}}/users",
+ {"user_names": ["someone"]},
+ ),
+ )
+ ],
+ "a chat": [
+ Check(
+ "can_transfer",
+ _get(f"{G}/rooms/{{chat}}"),
+ _transfer("room", "{chat}"),
+ refused=REFUSED | {409},
+ ),
+ ],
+ "an agent": [
+ Check(
+ "can_manage",
+ AGENT,
+ _act("PUT", f"{G}/agents/{{agent}}/description", {"description": "x"}),
+ ),
+ Check(
+ "can_rename",
+ AGENT,
+ _act(
+ "PUT",
+ f"{G}/agents/{{agent}}/name",
+ {"name": "{tag}-renamed", "display_name": None},
+ ),
+ ),
+ Check("can_transfer", AGENT, _transfer("agent", "{agent}")),
+ Check(
+ "can_change_manage_agents",
+ AGENT,
+ _act(
+ "PUT", f"{G}/agents/{{agent}}/can-manage-agents", {"enabled": False}
+ ),
+ ),
+ Check(
+ "can_edit_options",
+ AGENT,
+ _act("PATCH", f"{G}/agents/{{agent}}/options", {"options": {}}),
+ refused=REFUSED | {400},
+ ),
+ Check(
+ "can_grant_services",
+ AGENT,
+ _act(
+ "PUT",
+ f"{G}/agents/{{agent}}/service-grants/github",
+ {"access": "read", "resources": {}},
+ ),
+ refused=REFUSED | {422},
+ ),
+ ],
+ "an agent Switch Console runs": [
+ Check(
+ "can_edit_options",
+ _get(f"{G}/agents/{{console_agent}}"),
+ _act("PATCH", f"{G}/agents/{{console_agent}}/options", {"options": {}}),
+ ),
+ Check(
+ "can_grant_services",
+ _get(f"{G}/agents/{{console_agent}}"),
+ _act(
+ "PUT",
+ f"{G}/agents/{{console_agent}}/service-grants/github",
+ {"access": "read", "resources": {}},
+ ),
+ ),
+ ],
+ "a sub-agent": [
+ Check(
+ "can_rename",
+ _get(f"{G}/agents/{{sub_agent}}"),
+ _act(
+ "PUT",
+ f"{G}/agents/{{sub_agent}}/name",
+ {"name": "{tag}-renamed", "display_name": None},
+ ),
+ refused=REFUSED | {400},
+ ),
+ Check(
+ "can_transfer",
+ _get(f"{G}/agents/{{sub_agent}}"),
+ _transfer("agent", "{sub_agent}"),
+ refused=REFUSED | {409},
+ ),
+ ],
+ "a workspace member": [
+ Check(
+ "can_change_role",
+ MEMBERS,
+ _act(
+ "PATCH",
+ f"{G}/tenants/{{tenant}}/members/{{member_target}}",
+ {"role": "member"},
+ ),
+ match=("user_id", "member_target"),
+ ),
+ Check(
+ "can_remove",
+ MEMBERS,
+ _act("DELETE", f"{G}/tenants/{{tenant}}/members/{{member_target}}"),
+ match=("user_id", "member_target"),
+ ),
+ ],
+ "your own membership": [
+ Check(
+ "can_change_role",
+ MEMBERS,
+ _act(
+ "PATCH",
+ f"{G}/tenants/{{tenant}}/members/{{self_id}}",
+ {"role": "member"},
+ ),
+ match=("user_id", "self_id"),
+ later=frozenset({409}), # The last admin stays.
+ ),
+ Check(
+ "can_remove",
+ MEMBERS,
+ _act("DELETE", f"{G}/tenants/{{tenant}}/members/{{self_id}}"),
+ match=("user_id", "self_id"),
+ later=frozenset({409}), # The last admin, or still owning agents.
+ ),
+ ],
+ "your own organization membership": [
+ Check(
+ "can_change_role",
+ ORG_MEMBERS,
+ _act(
+ "PATCH",
+ f"{G}/organizations/current/members/{{self_id}}",
+ {"role": "member"},
+ ),
+ match=("user_id", "self_id"),
+ later=frozenset({409}), # The last organization admin stays.
+ ),
+ Check(
+ "can_remove",
+ ORG_MEMBERS,
+ _act("DELETE", f"{G}/organizations/current/members/{{self_id}}"),
+ match=("user_id", "self_id"),
+ later=frozenset({409}), # The last one, or still in a workspace.
+ ),
+ ],
+ "the workspace": [
+ Check(
+ "can_delete",
+ _get(f"{G}/tenants/current"),
+ _act("DELETE", f"{G}/tenants/{{tenant}}", {"name": "{tenant}"}),
+ later=frozenset({409}), # Still has other members in it.
+ ),
+ Check(
+ "can_manage_data_protection",
+ _get(f"{G}/tenants/current"),
+ _act(
+ "PUT",
+ f"{G}/tenants/{{tenant}}/retention",
+ {"message_retention_days": 30},
+ ),
+ ),
+ Check(
+ "can_manage_data_protection",
+ _get(f"{G}/tenants/current"),
+ _get(f"{G}/tenants/{{tenant}}/people"),
+ ),
+ Check(
+ "can_manage_data_protection",
+ _get(f"{G}/tenants/current"),
+ _act(
+ "POST",
+ f"{G}/tenants/{{tenant}}/erasures",
+ {"external_user_ids": ["{tag}-nobody"]},
+ ),
+ later=frozenset({404}), # Nobody has that id.
+ ),
+ ],
+ "the organization": [
+ Check(
+ "can_manage_members", _get(f"{G}/organizations/current"), ORG_MEMBERS
+ ),
+ Check(
+ "administers",
+ _get(f"{G}/organizations/current"),
+ _get(f"{G}/organizations/current/audit-events"),
+ ),
+ ],
+ "an organization member": [
+ Check(
+ "can_change_role",
+ ORG_MEMBERS,
+ _act(
+ "PATCH",
+ f"{G}/organizations/current/members/{{org_target}}",
+ {"role": "member"},
+ ),
+ match=("user_id", "org_target"),
+ ),
+ Check(
+ "can_remove",
+ ORG_MEMBERS,
+ _act("DELETE", f"{G}/organizations/current/members/{{org_target}}"),
+ match=("user_id", "org_target"),
+ ),
+ ],
+ "an API key": [
+ Check(
+ "can_reveal",
+ _get(f"{G}/api-keys"),
+ _get(f"{G}/api-keys/{{registration_key}}/reveal"),
+ match=("id", "registration_key"),
+ ),
+ Check(
+ "can_delete",
+ _get(f"{G}/api-keys"),
+ _act("DELETE", f"{G}/api-keys/{{registration_key}}"),
+ match=("id", "registration_key"),
+ ),
+ ],
+ "an agent's key": [
+ Check(
+ "can_delete",
+ _get(f"{G}/api-keys"),
+ _act("DELETE", f"{G}/api-keys/{{agent_key}}"),
+ match=("id", "agent_key"),
+ refused=REFUSED | {409},
+ ),
+ ],
+ "a machine": [
+ Check(
+ "can_edit",
+ _get(f"{G}/management/controllers"),
+ _act(
+ "PATCH",
+ f"{G}/management/controllers/{{controller}}",
+ {"description": "x"},
+ ),
+ match=("id", "controller"),
+ ),
+ Check(
+ "can_remove",
+ _get(f"{G}/management/controllers"),
+ _act("DELETE", f"{G}/management/controllers/{{controller}}"),
+ match=("id", "controller"),
+ ),
+ ],
+ "a managed agent": [
+ Check(
+ "can_edit",
+ _get(f"{G}/management/agents"),
+ _act(
+ "PATCH",
+ f"{G}/management/agents/{{managed_agent}}",
+ {"desired_state": "stopped"},
+ ),
+ match=("agent_id", "managed_agent"),
+ ),
+ Check(
+ "can_delete",
+ _get(f"{G}/management/agents"),
+ _act("DELETE", f"{G}/management/agents/{{managed_agent}}"),
+ match=("agent_id", "managed_agent"),
+ ),
+ ],
+ "a messaging app": [
+ Check(
+ "can_manage",
+ _get(f"{G}/collaborations"),
+ _act(
+ "PATCH",
+ f"{G}/collaborations/{{bridge}}",
+ {"agent_greetings_enabled": True},
+ ),
+ match=("bridge_id", "bridge"),
+ ),
+ Check(
+ "can_delete",
+ _get(f"{G}/collaborations"),
+ _act("DELETE", f"{G}/collaborations/{{bridge}}"),
+ match=("bridge_id", "bridge"),
+ ),
+ ],
+ "an install": [
+ Check(
+ "can_disconnect",
+ _get(f"{G}/messaging-apps/installs"),
+ _act("DELETE", f"{G}/messaging-apps/installs/{{oauth_install}}"),
+ match=("id", "oauth_install"),
+ within="installs",
+ ),
+ ],
+ "a claim on a chat account": [
+ Check(
+ "can_unlink",
+ _get(f"{G}/collaborations/{{bridge}}/users"),
+ _act(
+ "DELETE",
+ f"{G}/collaborations/{{bridge}}/identities/{{identity}}",
+ user_id="{owner}",
+ ),
+ match=("id", "identity"),
+ ),
+ ],
+ "a connection": [
+ Check(
+ "can_revoke",
+ _get(f"{G}/service-connections"),
+ _act("DELETE", f"{G}/service-connections/{{connection}}"),
+ match=("slug", "connection"),
+ within="connections",
+ ),
+ ],
+ "an account": [
+ Check(
+ "can_delete",
+ _get(f"{G}/users"),
+ _act("DELETE", f"{G}/users/{{user_target}}"),
+ match=("id", "user_target"),
+ ),
+ ],
+ }.items()
+ for check in checks
+}
+
+
+def _claim(thing: dict[str, Any], owner_id: str) -> dict[str, Any]:
+ """A platform account's claim by the owner, which carries the flag."""
+ return next(claim for claim in thing["claimed_by"] if claim["user_id"] == owner_id)
+
+
[email protected]("name", sorted(CHECKS))
+async def test_a_flag_says_what_its_route_does(
+ session_factory: async_sessionmaker[AsyncSession], name: str
+) -> None:
+ check = CHECKS[name]
+ gateway = build_gateway(session_factory)
+ people = await seed_people(session_factory)
+ wrong: list[str] = []
+ told: dict[bool, int] = {True: 0, False: 0}
+ async with client(gateway) as http:
+ for persona in Persona:
+ world = World(session_factory, people, persona.value, http, gateway)
+ # Made before it is read about, so the list holds it.
+ wanted = (
+ None
+ if check.match is None
+ else (await world.fill(Ask("GET", f"{{{check.match[1]}}}"))).path
+ )
+ read = await world.fill(check.read)
+ shown = await http.request(
+ read.method,
+ read.path,
+ params=read.params,
+ headers=people.headers(persona),
+ )
+ if shown.status_code != 200:
+ continue # Not shown to them at all: nothing to say what it means.
+ found = shown.json()
+ if check.within is not None:
+ found = found[check.within]
+ if check.match is not None:
+ field = check.match[0]
+ found = next((row for row in found if row[field] == wanted), None)
+ if found is None:
+ continue
+ if "on a claim on a chat account" in name:
+ found = _claim(found, people.ids[Persona.OWNER])
+ flag = bool(found[check.flag])
+ told[flag] += 1
+ act = await world.fill(check.act)
+ answered = await http.request(
+ act.method,
+ act.path,
+ json=act.json,
+ params=act.params,
+ headers=people.headers(persona),
+ )
+ if answered.status_code not in (
+ OK | check.later if flag else check.refused
+ ):
+ wrong.append(
+ f"{persona.value}: {check.flag} is {flag}, but {act.method} "
+ f"{act.path} answered {answered.status_code} {answered.text[:200]}"
+ )
+ assert told[True] + told[False] > 0, "nobody was shown the flag"
+ assert not wrong, f"{name}:\n" + "\n".join(wrong)
diff --git a/core/tests/switch_core/gateway/role_matrix/test_role_matrix.py b/core/tests/switch_core/gateway/role_matrix/test_role_matrix.py
new file mode 100644
index 000000000..252aacd5a
--- /dev/null
+++ b/core/tests/switch_core/gateway/role_matrix/test_role_matrix.py
@@ -0,0 +1,208 @@
+"""Every gateway route, asked by every persona, answers as `routes.py` says.
+
+This is the server's half of "no route relies on the UI to hide an action":
+whatever a page offers or hides, the route itself refuses whoever may not use
+it. The table is held to the committed route snapshot, which CI keeps equal to
+the routes the server mounts (`scripts/e2e_surface.py --check`), so a route
+cannot be added without saying here who may use it.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from tests.switch_core.gateway.role_matrix.access import Expected, matches
+from tests.switch_core.gateway.role_matrix.harness import (
+ REPO_ROOT,
+ SURFACE,
+ Persona,
+ build_gateway,
+ client,
+ seed_people,
+ socket_status,
+ stream_status,
+)
+from tests.switch_core.gateway.role_matrix.routes import (
+ ROUTES,
+ STREAMS,
+ UNAUTHENTICATED,
+)
+from tests.switch_core.gateway.role_matrix.world import World
+
+SNAPSHOT = REPO_ROOT / "console" / "tooling-e2e" / "surface" / "server-surface.json"
+
+
+def _shown(expected: Expected) -> str:
+ return str(sorted(expected)) if isinstance(expected, frozenset) else str(expected)
+
+
+def _snapshot() -> dict[str, str]:
+ routes = json.loads(SNAPSHOT.read_text())["gatewayRoutes"]
+ return {route["route"]: route["auth"] for route in routes}
+
+
+def test_the_table_says_who_may_use_every_route_the_server_mounts() -> None:
+ snapshot = _snapshot()
+ tables = (ROUTES, STREAMS, UNAUTHENTICATED)
+ named = [key for table in tables for key in table]
+ assert len(named) == len(set(named)), "a route is in two tables"
+ assert set(named) - set(snapshot) == set(), "routes the server no longer mounts"
+ assert set(snapshot) - set(named) == set(), "routes nobody said who may use"
+ assert set(UNAUTHENTICATED) == {
+ key for key, auth in snapshot.items() if auth != "session"
+ }
+
+
+async def test_the_matrix_asks_the_app_the_server_mounts(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ """Every route in the snapshot is mounted on the app the matrix asks, so
+ an answer here is the answer a deployment gives."""
+ assert set(SURFACE._routes_by_key(build_gateway(session_factory))) == set(
+ _snapshot()
+ )
+
+
[email protected]("route", sorted(ROUTES))
+async def test_each_route_answers_each_persona_as_it_should(
+ session_factory: async_sessionmaker[AsyncSession], route: str
+) -> None:
+ case = ROUTES[route]
+ gateway = build_gateway(session_factory)
+ people = await seed_people(session_factory)
+ wrong: list[str] = []
+ async with client(gateway) as http:
+ for persona in Persona:
+ world = World(session_factory, people, persona.value, http, gateway)
+ ask = await world.fill(case.ask)
+ response = await http.request(
+ ask.method,
+ ask.path,
+ json=ask.json,
+ params=ask.params,
+ headers=people.headers(persona),
+ )
+ expected = case.expect[persona]
+ if not matches(expected, response.status_code):
+ wrong.append(
+ f"{persona.value}: expected {_shown(expected)}, got "
+ f"{response.status_code} {response.text[:300]}"
+ )
+ assert not wrong, f"{route} ({case.why or 'plain rule'}):\n" + "\n".join(wrong)
+
+
+async def test_streams_answer_whom_they_should(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ """The routes whose answer is a stream or a socket: each persona may open
+ their own, and nobody may without a session."""
+ gateway = build_gateway(session_factory)
+ people = await seed_people(session_factory)
+ opened: dict[str, dict[str, int]] = {}
+ for route, opens in (
+ ("GET /gateway/chats/events", stream_status),
+ ("GET /gateway/chats/activity/events", stream_status),
+ ("WS /gateway/changes/ws", socket_status),
+ ):
+ path = STREAMS[route].ask.path
+ opened[route] = {
+ persona.value: await opens(gateway, path, people.headers(persona))
+ for persona in Persona
+ }
+ opened[route]["nobody"] = await opens(gateway, path, {})
+ everyone = [persona.value for persona in Persona]
+ assert opened == {
+ "GET /gateway/chats/events": {**dict.fromkeys(everyone, 200), "nobody": 401},
+ "GET /gateway/chats/activity/events": {
+ **dict.fromkeys(everyone, 200),
+ "nobody": 401,
+ },
+ "WS /gateway/changes/ws": {**dict.fromkeys(everyone, 101), "nobody": 401},
+ }
+
+
+async def test_only_the_people_in_a_chat_may_upload_to_it(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ gateway = build_gateway(session_factory)
+ people = await seed_people(session_factory)
+ answers: dict[str, int] = {}
+ async with client(gateway) as http:
+ for persona in Persona:
+ world = World(session_factory, people, persona.value, http, gateway)
+ ask = await world.fill(
+ STREAMS["POST /gateway/chats/{room_id}/attachments"].ask
+ )
+ response = await http.post(
+ ask.path,
+ data={"uploadId": f"{persona.value}-upload"},
+ files={"file": ("note.txt", b"hello", "text/plain")},
+ headers=people.headers(persona),
+ )
+ answers[persona.value] = response.status_code
+ assert answers == {
+ **dict.fromkeys(
+ (
+ Persona.ORG_ADMIN,
+ Persona.WORKSPACE_ADMIN,
+ Persona.MEMBER,
+ Persona.OPERATOR,
+ ),
+ 403,
+ ),
+ Persona.OWNER: 200,
+ }
+
+
[email protected]("route", sorted(UNAUTHENTICATED))
+async def test_a_route_without_a_session_answers_everyone_alike(
+ session_factory: async_sessionmaker[AsyncSession], route: str
+) -> None:
+ """It reads no session, so being signed in, and as whom, changes nothing."""
+ method, path = route.split(" ", 1)
+ path = path.replace("{service}", "github").replace(
+ "{machine_id}", "no-such-machine"
+ )
+ gateway = build_gateway(session_factory)
+ people = await seed_people(session_factory)
+ async with client(gateway) as http:
+ answers = {
+ persona.value: (
+ await http.request(method, path, headers=people.headers(persona))
+ ).status_code
+ for persona in Persona
+ }
+ nobody = (await http.request(method, path)).status_code
+ assert set(answers.values()) == {nobody}, answers
+
+
[email protected]("action", ["bulk-delete", "bulk-archive"])
+async def test_bulk_room_actions_touch_only_rooms_the_caller_may(
+ session_factory: async_sessionmaker[AsyncSession], action: str
+) -> None:
+ """They answer everyone, skipping each room the caller may not delete or
+ change, so what each persona was let do is in the count."""
+ gateway = build_gateway(session_factory)
+ people = await seed_people(session_factory)
+ counts: dict[str, int] = {}
+ async with client(gateway) as http:
+ for persona in Persona:
+ world = World(session_factory, people, persona.value, http, gateway)
+ body: dict[str, object] = {"room_ids": [await world.room()]}
+ if action == "bulk-archive":
+ body["archived"] = True
+ response = await http.post(
+ f"/gateway/rooms/{action}", json=body, headers=people.headers(persona)
+ )
+ assert response.status_code == 200, response.text
+ counted = response.json()
+ counts[persona.value] = counted[
+ "deleted" if action == "bulk-delete" else "updated"
+ ]
+ assert counts == {
+ **dict.fromkeys(Persona, 1),
+ Persona.MEMBER: 0,
+ }
diff --git a/core/tests/switch_core/gateway/role_matrix/world.py b/core/tests/switch_core/gateway/role_matrix/world.py
new file mode 100644
index 000000000..d12e5e401
--- /dev/null
+++ b/core/tests/switch_core/gateway/role_matrix/world.py
@@ -0,0 +1,840 @@
+"""What the matrix asks about: one of each thing, owned by `Persona.OWNER`.
+
+Each is made the first time a case asks for it, so a case pays only for what
+its route reads. Everything is private where it has a visibility, so reading,
+changing and deleting it is its owner's and an admin's, and nobody else's.
+
+Each persona asks about a world of its own, `tag` keeping its names apart, so
+what one is let do never changes what the next is asked about.
+"""
+
+from __future__ import annotations
+
+import base64
+import re
+import uuid
+from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
+from typing import Any
+
+import httpx
+from fastapi import FastAPI
+from sqlalchemy import insert
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.connections.flows import KIND as SERVICE_FLOW
+from switch_core.db.models import (
+ Agent,
+ AgentDefinition,
+ ApiKey,
+ Client,
+ CollaborationBridge,
+ Document,
+ ExternalUser,
+ ExternalUserClaim,
+ OrganizationMember,
+ Package,
+ Reference,
+ ReferenceType,
+ Room,
+ RoomGroup,
+ RoomLink,
+ RoomRole,
+ Template,
+ TenantMember,
+ UsageMetric,
+ User,
+ package_documents,
+ package_references,
+ room_agents,
+ room_documents,
+ room_packages,
+ room_references,
+)
+from switch_core.db.stores.budget_store import BudgetStore
+from switch_core.db.stores.invitation_store import InvitationStore
+from switch_core.db.stores.join_domain_store import JoinDomainStore
+from switch_core.db.stores.service_connection_store import ServiceConnectionStore
+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStore
+from switch_core.tenant_context import tenant_scope
+from tests.switch_core.connections.github_seed import connect_github, grant_repository
+from tests.switch_core.gateway.agent_route_harness import add_agent
+from tests.switch_core.gateway.role_matrix.harness import (
+ ORGANIZATION,
+ TENANT,
+ People,
+ Persona,
+ config,
+ domain_of,
+)
+from tests.switch_core.gateway.role_matrix.routes import Ask
+from tests.switch_core.management.harness import definition, platform
+
+_PRIVATE = {"read_visibility": "private", "write_visibility": "private"}
+
+_PLACEHOLDER = re.compile(r"\{([a-z_]+)\}")
+
+
+class World:
+ def __init__(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ people: People,
+ tag: str,
+ http: httpx.AsyncClient,
+ gateway: FastAPI,
+ ) -> None:
+ self.session_factory = session_factory
+ self.people = people
+ self.tag = tag
+ # For what is made the way a person makes it, through the app.
+ self.http = http
+ self._clients = gateway.state.matrix_lifecycle
+ self._sign_in_flows = gateway.state.sign_in_flows
+ self._made: dict[str, Any] = {}
+
+ async def fill(self, ask: Ask) -> Ask:
+ """`ask` with each `{name}` it holds replaced by this world's thing of
+ that name; a body value that is nothing but one takes the thing
+ itself, so it can be an object."""
+ return Ask(
+ ask.method,
+ await self._text(ask.path),
+ await self._value(ask.json),
+ {key: await self._text(value) for key, value in ask.params.items()},
+ )
+
+ async def _value(self, value: Any) -> Any:
+ if isinstance(value, str):
+ whole = _PLACEHOLDER.fullmatch(value)
+ return (
+ await self._lookup(whole.group(1)) if whole else await self._text(value)
+ )
+ if isinstance(value, dict):
+ return {key: await self._value(item) for key, item in value.items()}
+ if isinstance(value, list):
+ return [await self._value(item) for item in value]
+ return value
+
+ async def _text(self, text: str) -> str:
+ names = _PLACEHOLDER.findall(text)
+ for name in names:
+ text = text.replace(f"{{{name}}}", str(await self._lookup(name)))
+ return text
+
+ async def _lookup(self, name: str) -> Any:
+ found = getattr(self, name)
+ return await found() if callable(found) else found
+
+ async def _as_owner(self, method: str, path: str, json: Any = None) -> Any:
+ return await self._as(Persona.OWNER, method, path, json)
+
+ async def _as(self, persona: Persona, method: str, path: str, json: Any) -> Any:
+ response = await self.http.request(
+ method, path, json=json, headers=self.people.headers(persona)
+ )
+ assert response.status_code < 300, f"{method} {path}: {response.text}"
+ return response.json()
+
+ async def tenant(self) -> str:
+ return TENANT
+
+ async def self_id(self) -> str:
+ """The asking persona's own id."""
+ return self.id_of(Persona(self.tag))
+
+ async def owner(self) -> str:
+ return self.owner_id
+
+ async def member(self) -> str:
+ return self.id_of(Persona.MEMBER)
+
+ async def definition(self) -> dict[str, Any]:
+ return definition()
+
+ async def slug(self) -> str:
+ """A name of this world's that may be a reference type's slug."""
+ return "matrix_" + self.tag.replace("-", "_")
+
+ async def email_domain(self) -> str:
+ """The domain of the asking persona's own e-mail (`harness.email_of`)."""
+ return domain_of(Persona(self.tag))
+
+ async def flow_state(self) -> str:
+ return base64.urlsafe_b64encode(uuid.uuid4().bytes * 2).decode()[:43]
+
+ async def flow_secret(self) -> str:
+ return base64.urlsafe_b64encode(uuid.uuid4().bytes * 2).decode()[:43]
+
+ async def room_yaml(self) -> str:
+ """A room template with nothing in it but its name."""
+ return f"room:\n name: {self.name('yaml-room')}\n description: matrix\n"
+
+ async def sealed_login(self) -> dict[str, str]:
+ """A provider login as a client seals it; only its shape matters here."""
+ return {
+ "alg": "X25519-HKDF-SHA256-A256GCM",
+ "key_id": "matrix-key",
+ "ephemeral_key": base64.urlsafe_b64encode(bytes(32)).decode(),
+ "nonce": base64.urlsafe_b64encode(bytes(12)).decode(),
+ "ciphertext": base64.urlsafe_b64encode(bytes(32)).decode(),
+ }
+
+ def name(self, kind: str) -> str:
+ return f"matrix-{kind}-{self.tag}"
+
+ def id_of(self, persona: Persona) -> str:
+ return self.people.ids[persona]
+
+ @property
+ def owner_id(self) -> str:
+ return self.people.ids[Persona.OWNER]
+
+ async def _once(self, kind: str, make: Any) -> Any:
+ if kind not in self._made:
+ with tenant_scope(TENANT):
+ async with self.session_factory() as session:
+ self._made[kind] = await make(session)
+ await session.commit()
+ return self._made[kind]
+
+ # ── Agents ───────────────────────────────────────────────────────────
+
+ async def agent(self) -> str:
+ return str(await self._once("agent", self._agent("agent")))
+
+ def _agent(self, kind: str) -> Any:
+ """An agent of the owner's, with a running client as far as the room
+ and chat services can tell."""
+
+ async def make(session: AsyncSession) -> str:
+ agent = await add_agent(
+ session, name=self.name(kind), owner_id=self.owner_id
+ )
+ client = await session.get(Client, agent.client_id)
+ assert client is not None
+ self._clients.agents[agent.id] = SimpleNamespace(
+ client_id=client.id, transport_user_id=client.transport_user_id
+ )
+ return agent.id
+
+ return make
+
+ async def console_agent(self) -> str:
+ """An agent of the owner's that Switch Console runs, registered from
+ the Claude Code spec, so it has options and may be granted services on
+ the owner's GitHub connection."""
+ agent_id = str(await self._once("console_agent", self._agent("console-agent")))
+ await self.connection()
+
+ async def make(session: AsyncSession) -> str:
+ agent = await session.get(Agent, agent_id)
+ assert agent is not None
+ agent.metadata_ = {
+ "known_agent_type": "claude-code",
+ "known_agent_options": {},
+ }
+ await session.flush()
+ return agent_id
+
+ return str(await self._once("console_agent_registered", make))
+
+ async def agent_name(self) -> str:
+ await self.agent()
+ return self.name("agent")
+
+ async def sub_agent(self) -> str:
+ """A sub-agent of the owner's agent."""
+ parent_id = await self.agent()
+ sub_id = str(await self._once("sub_agent", self._agent("sub-agent")))
+
+ async def make(session: AsyncSession) -> str:
+ sub = await session.get(Agent, sub_id)
+ assert sub is not None
+ sub.parent_agent_id = parent_id
+ await session.flush()
+ return sub_id
+
+ return str(await self._once("sub_agent_parented", make))
+
+ async def other_agent(self) -> str:
+ return str(await self._once("other_agent", self._agent("other-agent")))
+
+ async def granted_agent(self) -> str:
+ """The agent, with service access on its owner's GitHub connection."""
+ agent_id = await self.agent()
+ await self.connection()
+
+ async def make(session: AsyncSession) -> str:
+ await grant_repository(session, agent_id, self.owner_id)
+ return agent_id
+
+ return str(await self._once("granted_agent", make))
+
+ async def agent_key(self) -> str:
+ """The owner's agent's own API key."""
+ agent_id = await self.agent()
+
+ async def make(session: AsyncSession) -> str:
+ agent = await session.get(Agent, agent_id)
+ assert agent is not None
+ return agent.api_key_id
+
+ return str(await self._once("agent_key", make))
+
+ async def registration_key(self) -> str:
+ async def make(session: AsyncSession) -> str:
+ key = ApiKey(
+ user_id=self.owner_id,
+ key_hash=f"matrix-{uuid.uuid4().hex}",
+ encrypted_key=config().keyring.encrypt("matrix-secret"),
+ label="matrix",
+ type="registration",
+ )
+ session.add(key)
+ await session.flush()
+ return key.id
+
+ return str(await self._once("registration_key", make))
+
+ # ── People to act on ─────────────────────────────────────────────────
+
+ async def _person(self, kind: str, *, workspace: bool, organization: bool) -> str:
+ async def make(session: AsyncSession) -> str:
+ user = User(
+ name=self.name(kind),
+ email=f"{self.name(kind)}@example.invalid",
+ role="user",
+ )
+ session.add(user)
+ await session.flush()
+ if workspace:
+ session.add(
+ TenantMember(tenant_id=TENANT, user_id=user.id, role="member")
+ )
+ if organization:
+ session.add(
+ OrganizationMember(
+ organization_id=ORGANIZATION, user_id=user.id, role="member"
+ )
+ )
+ await session.flush()
+ return user.id
+
+ return str(await self._once(kind, make))
+
+ async def member_target(self) -> str:
+ """A member of the workspace, to change or remove."""
+ return await self._person("member-target", workspace=True, organization=True)
+
+ async def org_target(self) -> str:
+ """A member of the organization in none of its workspaces, to change or
+ remove from it."""
+ return await self._person("org-target", workspace=False, organization=True)
+
+ async def user_target(self) -> str:
+ """An account in no workspace, for the operator to delete."""
+ return await self._person("user-target", workspace=False, organization=False)
+
+ # ── Rooms and resources ──────────────────────────────────────────────
+
+ async def room(self) -> str:
+ return str(await self._once("room", self._room(self.name("room"))))
+
+ async def readable_room(self) -> str:
+ """A room of the owner's that everyone may read and only its owner
+ and admins may change."""
+
+ async def make(session: AsyncSession) -> str:
+ room = Room(
+ transport_room_id=f"!{self.name('readable-room')}:test",
+ name=self.name("readable-room"),
+ description="",
+ owner_id=self.owner_id,
+ read_visibility="public",
+ write_visibility="private",
+ )
+ session.add(room)
+ await session.flush()
+ return room.id
+
+ return str(await self._once("readable_room", make))
+
+ async def direct_room(self) -> str:
+ """A DM the bridge adopted: anyone may read it, and its owner and
+ admins write to it, but nobody changes who is in it from outside."""
+
+ async def make(session: AsyncSession) -> str:
+ room = Room(
+ transport_room_id=f"!{self.name('direct-room')}:test",
+ name=self.name("direct-room"),
+ description="",
+ owner_id=self.owner_id,
+ read_visibility="public",
+ write_visibility="private",
+ channel_type="direct",
+ )
+ session.add(room)
+ await session.flush()
+ return room.id
+
+ return str(await self._once("direct_room", make))
+
+ async def room_document_itself(self) -> str:
+ """A document of the room's own, as an agent writes one there."""
+ room_id = await self.room()
+
+ async def make(session: AsyncSession) -> str:
+ document = Document(
+ owner_id=self.owner_id,
+ room_id=room_id,
+ name=self.name("room-own-document"),
+ description="",
+ instructions="",
+ content="",
+ **_PRIVATE,
+ )
+ session.add(document)
+ await session.flush()
+ return document.id
+
+ return str(await self._once("room_document_itself", make))
+
+ async def other_room(self) -> str:
+ return str(await self._once("other_room", self._room(self.name("other-room"))))
+
+ def _room(self, name: str) -> Any:
+ async def make(session: AsyncSession) -> str:
+ room = Room(
+ transport_room_id=f"!{name}-{uuid.uuid4().hex[:6]}:test",
+ name=name,
+ description=name,
+ owner_id=self.owner_id,
+ **_PRIVATE,
+ )
+ session.add(room)
+ await session.flush()
+ return room.id
+
+ return make
+
+ async def room_role(self) -> str:
+ """The room, holding a role named `reviewer`."""
+ room_id = await self.room()
+
+ async def make(session: AsyncSession) -> str:
+ session.add(
+ RoomRole(room_id=room_id, name="reviewer", instructions="Review.")
+ )
+ await session.flush()
+ return room_id
+
+ return str(await self._once("room_role", make))
+
+ async def room_agent(self) -> str:
+ """The room, with the agent in it."""
+ return await self._linked(
+ "room_agent", self.room, self.agent, room_agents, "agent_id"
+ )
+
+ async def room_reference(self) -> str:
+ return await self._linked(
+ "room_reference", self.room, self.reference, room_references, "reference_id"
+ )
+
+ async def room_document(self) -> str:
+ return await self._linked(
+ "room_document", self.room, self.document, room_documents, "document_id"
+ )
+
+ async def room_package(self) -> str:
+ return await self._linked(
+ "room_package", self.room, self.package, room_packages, "package_id"
+ )
+
+ async def package_reference(self) -> str:
+ return await self._linked(
+ "package_reference",
+ self.package,
+ self.reference,
+ package_references,
+ "reference_id",
+ holder="package_id",
+ )
+
+ async def package_document(self) -> str:
+ return await self._linked(
+ "package_document",
+ self.package,
+ self.document,
+ package_documents,
+ "document_id",
+ holder="package_id",
+ )
+
+ async def _linked(
+ self,
+ kind: str,
+ holder_of: Any,
+ held_of: Any,
+ table: Any,
+ held: str,
+ *,
+ holder: str = "room_id",
+ ) -> str:
+ """The holder (a room, or a package), with the held thing in it."""
+ holder_id = await holder_of()
+ held_id = await held_of()
+
+ async def make(session: AsyncSession) -> str:
+ await session.execute(
+ insert(table).values({holder: holder_id, held: held_id})
+ )
+ return holder_id
+
+ return str(await self._once(kind, make))
+
+ async def linked_room(self) -> str:
+ """The room, linked to the other room."""
+ room_id = await self.room()
+ other_id = await self.other_room()
+
+ async def make(session: AsyncSession) -> str:
+ session.add(
+ RoomLink(
+ source_room_id=room_id, target_room_id=other_id, label="related"
+ )
+ )
+ await session.flush()
+ return room_id
+
+ return str(await self._once("linked_room", make))
+
+ async def room_group(self) -> str:
+ async def make(session: AsyncSession) -> str:
+ group = RoomGroup(name=self.name("group"))
+ session.add(group)
+ await session.flush()
+ return group.id
+
+ return str(await self._once("room_group", make))
+
+ async def reference(self) -> str:
+ async def make(session: AsyncSession) -> str:
+ reference = Reference(
+ owner_id=self.owner_id,
+ type="github",
+ name=self.name("reference"),
+ description="",
+ instructions="",
+ value={"urls": ["https://github.com/example/project"]},
+ **_PRIVATE,
+ )
+ session.add(reference)
+ await session.flush()
+ return reference.id
+
+ return str(await self._once("reference", make))
+
+ async def reference_type(self) -> str:
+ async def make(session: AsyncSession) -> str:
+ session.add(
+ ReferenceType(
+ type=self.name("type"),
+ owner_id=self.owner_id,
+ display_name="Matrix",
+ instructions="",
+ value_hint="",
+ **_PRIVATE,
+ )
+ )
+ await session.flush()
+ return self.name("type")
+
+ return str(await self._once("reference_type", make))
+
+ async def document(self) -> str:
+ async def make(session: AsyncSession) -> str:
+ document = Document(
+ owner_id=self.owner_id,
+ name=self.name("document"),
+ description="",
+ instructions="",
+ content="",
+ **_PRIVATE,
+ )
+ session.add(document)
+ await session.flush()
+ return document.id
+
+ return str(await self._once("document", make))
+
+ async def package(self) -> str:
+ async def make(session: AsyncSession) -> str:
+ package = Package(
+ owner_id=self.owner_id,
+ name=self.name("package"),
+ description="",
+ instructions="",
+ **_PRIVATE,
+ )
+ session.add(package)
+ await session.flush()
+ return package.id
+
+ return str(await self._once("package", make))
+
+ async def template(self) -> str:
+ async def make(session: AsyncSession) -> str:
+ template = Template(
+ owner_id=self.owner_id,
+ name=self.name("template"),
+ description="",
+ kind="room",
+ content="name: matrix\n",
+ **_PRIVATE,
+ )
+ session.add(template)
+ await session.flush()
+ return template.id
+
+ return str(await self._once("template", make))
+
+ # ── Workspace ────────────────────────────────────────────────────────
+
+ async def invitation(self) -> str:
+ async def make(session: AsyncSession) -> str:
+ invitation, _token = await InvitationStore().create(
+ session,
+ role="member",
+ email=None,
+ expires_at=datetime.now(UTC) + timedelta(days=7),
+ uses_remaining=1,
+ created_by=self.id_of(Persona.WORKSPACE_ADMIN),
+ )
+ return invitation.id
+
+ return str(await self._once("invitation", make))
+
+ async def budget(self) -> str:
+ async def make(session: AsyncSession) -> str:
+ budget = await BudgetStore().create(
+ session,
+ tenant_id=TENANT,
+ agent_id=None,
+ metric=UsageMetric.INPUT_TOKENS,
+ model=self.tag,
+ amount_limit=100,
+ period_hours=24,
+ )
+ return budget.id
+
+ return str(await self._once("budget", make))
+
+ async def join_domain(self) -> str:
+ async def make(session: AsyncSession) -> str:
+ domain = f"{self.tag}.matrix.example"
+ await JoinDomainStore().add(
+ session, domain=domain, created_by=self.id_of(Persona.WORKSPACE_ADMIN)
+ )
+ return domain
+
+ return str(await self._once("join_domain", make))
+
+ async def workspace_service(self) -> str:
+ """GitHub, switched on for the workspace by its admin."""
+
+ async def make(session: AsyncSession) -> str:
+ await WorkspaceServiceStore().set_enabled(
+ session, "github", True, self.id_of(Persona.WORKSPACE_ADMIN)
+ )
+ return "github"
+
+ return str(await self._once("workspace_service", make))
+
+ # ── Messaging apps ───────────────────────────────────────────────────
+
+ async def bridge(self) -> str:
+ async def make(session: AsyncSession) -> str:
+ client = Client(
+ transport_user_id=f"@matrix-bridge-{uuid.uuid4().hex[:8]}:test",
+ display_name="bridge",
+ type="bridge",
+ )
+ session.add(client)
+ await session.flush()
+ bridge = CollaborationBridge(
+ type="mattermost",
+ display_name=self.name("bridge"),
+ client_id=client.id,
+ status="active",
+ is_default=False,
+ )
+ session.add(bridge)
+ await session.flush()
+ return bridge.id
+
+ return str(await self._once("bridge", make))
+
+ async def identity(self) -> str:
+ """A platform account on the bridge, claimed by the owner."""
+ bridge_id = await self.bridge()
+
+ async def make(session: AsyncSession) -> str:
+ client = Client(
+ transport_user_id=f"@matrix-human-{uuid.uuid4().hex[:8]}:test",
+ display_name="human",
+ type="human",
+ )
+ session.add(client)
+ await session.flush()
+ account = ExternalUser(
+ bridge_id=bridge_id,
+ external_user_id=f"U-{self.tag}",
+ external_username=self.name("account"),
+ client_id=client.id,
+ )
+ session.add(account)
+ await session.flush()
+ session.add(
+ ExternalUserClaim(
+ external_user_id=account.id,
+ user_id=self.owner_id,
+ verified_at=datetime.now(UTC),
+ )
+ )
+ await session.flush()
+ return account.id
+
+ return str(await self._once("identity", make))
+
+ # ── Devices and connections ──────────────────────────────────────────
+
+ async def controller(self) -> str:
+ """A machine the owner enrolled from Switch Console."""
+ if "controller" not in self._made:
+ enrolled = await self._as_owner(
+ "POST",
+ "/gateway/management/controllers",
+ {
+ "name": self.name("machine"),
+ "kind": "console",
+ "platform": platform(),
+ "version": "0.1.0",
+ },
+ )
+ self._made["controller"] = enrolled["controller_id"]
+ return str(self._made["controller"])
+
+ async def managed_agent(self) -> str:
+ agent_id = await self.agent()
+ controller_id = await self.controller()
+
+ async def make(session: AsyncSession) -> str:
+ session.add(
+ AgentDefinition(
+ agent_id=agent_id,
+ owner_id=self.owner_id,
+ controller_id=controller_id,
+ revision=1,
+ desired_state="running",
+ definition=definition(),
+ )
+ )
+ await session.flush()
+ return agent_id
+
+ return str(await self._once("managed_agent", make))
+
+ async def connection(self) -> str:
+ """The owner's GitHub connection, the one every world shares: a person
+ holds one connection to each service."""
+
+ async def make(session: AsyncSession) -> str:
+ existing = await ServiceConnectionStore().get_connection(
+ session, self.owner_id, "github"
+ )
+ if existing is None:
+ await connect_github(session, self.owner_id, config().keyring)
+ return "github"
+
+ return str(await self._once("connection", make))
+
+ async def service_flow(self) -> str:
+ """A sign-in to Atlassian the owner started from Switch Console. Made
+ in the flow store: this server has no Atlassian app to start one."""
+ if "service_flow" not in self._made:
+ state = await self.flow_state()
+ await self._sign_in_flows.start(
+ kind=SERVICE_FLOW,
+ service="atlassian",
+ tenant_id=TENANT,
+ user_id=self.owner_id,
+ state=state,
+ mode="loopback",
+ port=39231,
+ redirect_uri="http://127.0.0.1:39231/callback",
+ owner_label="owner",
+ details={},
+ completion_secret=await self.flow_secret(),
+ )
+ self._made["service_flow"] = state
+ return str(self._made["service_flow"])
+
+ async def github_flow(self) -> str:
+ """A GitHub connection the owner started."""
+ if "github_flow" not in self._made:
+ started = await self._as_owner(
+ "POST", "/gateway/provider-connections/github/flows", await self._flow()
+ )
+ self._made["github_flow"] = started["id"]
+ return str(self._made["github_flow"])
+
+ async def _flow(self) -> dict[str, Any]:
+ """What Switch Console sends to start a sign-in it waits for."""
+ return {
+ "port": 39231,
+ "state": await self.flow_state(),
+ "completion_secret": await self.flow_secret(),
+ }
+
+ async def organization_service(self) -> str:
+ """GitHub, with a setting of the organization's own."""
+ if "organization_service" not in self._made:
+ await self._as(
+ Persona.ORG_ADMIN,
+ "PUT",
+ "/gateway/organizations/current/services/github",
+ {"enabled": True, "locked": False},
+ )
+ self._made["organization_service"] = "github"
+ return str(self._made["organization_service"])
+
+ # ── Chats ────────────────────────────────────────────────────────────
+
+ async def chat(self) -> str:
+ """A chat the owner started with their agent."""
+ if "chat" not in self._made:
+ agent_id = await self.agent()
+ started = await self._as_owner(
+ "POST",
+ "/gateway/chats",
+ {"agentId": agent_id, "requestId": f"{self.tag}-chat"},
+ )
+ self._made["chat"] = started["chat"]["roomId"]
+ return str(self._made["chat"])
+
+ async def chat_guest(self) -> str:
+ """Someone the owner brought into the chat."""
+ if "chat_guest" not in self._made:
+ chat_id = await self.chat()
+ guest = await self._person("chat-guest", workspace=True, organization=True)
+ await self._as_owner(
+ "POST", f"/gateway/chats/{chat_id}/members", {"userId": guest}
+ )
+ self._made["chat_guest"] = guest
+ return str(self._made["chat_guest"])
+
+ async def oauth_install(self) -> str:
+ """The workspace's Slack install (`harness.Installs`)."""
+ return "s1"
diff --git a/core/tests/switch_core/gateway/test_agent_can_manage_agents_route.py b/core/tests/switch_core/gateway/test_agent_can_manage_agents_route.py
index fac973f5b..2ba6f7207 100644
--- a/core/tests/switch_core/gateway/test_agent_can_manage_agents_route.py
+++ b/core/tests/switch_core/gateway/test_agent_can_manage_agents_route.py
@@ -23,7 +23,12 @@ from switch_core.db.stores.room_store import RoomStore
from switch_core.db.stores.user_store import UserStore
from switch_core.gateway.agents import update_can_manage_agents
from switch_core.gateway.schemas import AgentDetail, UpdateAgentCanManageAgentsRequest
-from tests.switch_core.gateway.agent_route_harness import add_agent, add_user, is_admin
+from tests.switch_core.gateway.agent_route_harness import (
+ SERVICES_ON,
+ add_agent,
+ add_user,
+ is_admin,
+)
async def _set(
@@ -43,6 +48,7 @@ async def _set(
),
user,
await is_admin(session, user),
+ SERVICES_ON, # type: ignore[arg-type]
)
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 cd7a0eb80..4c7d1d1a0 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
@@ -9,12 +9,17 @@ them. Removing the member, or deleting the account, still deletes the keys
from __future__ import annotations
+from types import SimpleNamespace
+
import httpx
import pytest
from sqlalchemy import select, update
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.db.models import TENANT_ZERO_ID, ApiKey, TenantMember, User
+from switch_core.db.stores.agent_store import AgentStore
+from switch_core.gateway import dependencies as gw_deps
+from tests.switch_core.gateway.agent_route_harness import add_agent
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
@@ -68,3 +73,55 @@ async def test_an_admin_cannot_list_reveal_or_delete_a_members_key(
assert deleted.status_code == 403, deleted.text
async with session_factory() as session:
assert await session.scalar(select(ApiKey.id).where(ApiKey.id == key.id))
+
+
+async def test_an_agents_key_says_it_cannot_go_while_the_agent_signs_in_with_it(
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Deleting it failed on the agent row's reference to it, as a server
+ error; it is refused for what it is now, and offered once the agent is
+ gone."""
+ # A deleted key is dropped from the protocol's cache.
+ monkeypatch.setitem(
+ gw_deps._state,
+ "protocol",
+ SimpleNamespace(
+ api_key_cache=SimpleNamespace(invalidate=lambda key_hash: None)
+ ),
+ )
+ owner = await add_member(session_factory, "agent-owner")
+ async with session_factory() as session:
+ agent = await add_agent(session, name="helper", owner_id=owner.id)
+ registration = ApiKey(
+ user_id=owner.id,
+ key_hash="registration-key",
+ encrypted_key=TEST_KEYRING.encrypt("secret"),
+ label="mine",
+ type="registration",
+ )
+ session.add(registration)
+ await session.commit()
+ agent_id, agent_key_id = agent.id, agent.api_key_id
+
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=_app(session_factory)),
+ base_url="http://test",
+ cookies=cookies_for(owner),
+ ) as client:
+ listed = await client.get("/api-keys")
+ refused = await client.delete(f"/api-keys/{agent_key_id}")
+ async with session_factory() as session:
+ await AgentStore().delete(session, agent_id)
+ await session.commit()
+ listed_after = await client.get("/api-keys")
+ deleted = await client.delete(f"/api-keys/{agent_key_id}")
+
+ def flags(response: httpx.Response) -> dict[str, tuple[bool, bool]]:
+ assert response.status_code == 200, response.text
+ return {k["label"]: (k["can_reveal"], k["can_delete"]) for k in response.json()}
+
+ assert flags(listed) == {"helper": (True, False), "mine": (True, True)}
+ assert refused.status_code == 409, refused.text
+ assert flags(listed_after) == {"helper": (True, True), "mine": (True, True)}
+ assert deleted.status_code == 200, deleted.text
diff --git a/core/tests/switch_core/gateway/test_audit_events.py b/core/tests/switch_core/gateway/test_audit_events.py
index 1677f0d7a..3dd91c6b2 100644
--- a/core/tests/switch_core/gateway/test_audit_events.py
+++ b/core/tests/switch_core/gateway/test_audit_events.py
@@ -113,6 +113,7 @@ class TestMembershipEvents:
response = await client.patch(
f"/tenants/{TENANT_A}/members/{admin_id}", json={"role": "member"}
)
+ # The last admin stays.
assert response.status_code == 409
assert await _events(session_factory, TENANT_A) == []
diff --git a/core/tests/switch_core/gateway/test_caller_permissions.py b/core/tests/switch_core/gateway/test_caller_permissions.py
index b862a319e..cd0794b67 100644
--- a/core/tests/switch_core/gateway/test_caller_permissions.py
+++ b/core/tests/switch_core/gateway/test_caller_permissions.py
@@ -1,6 +1,6 @@
"""What the server tells the Gateway the caller may do.
-The Gateway offers a room's, an agent's and a package's controls from flags the
+The Gateway offers a room's, an agent's and a resource's controls from flags the
server works out with `switch_core.authz`, so the rules live in one place. These
pin the flags against those rules: owner, workspace admin, and a member who
only has what the resource's visibility gives everyone.
@@ -8,17 +8,42 @@ only has what the resource's visibility gives everyone.
from __future__ import annotations
+import uuid
+from types import SimpleNamespace
+from typing import Any
+
import pytest
+from fastapi import HTTPException
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
-from switch_core.bridges.agent.protocol.agent_detail import agent_facing_summary
-from switch_core.db.models import Package, User
+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry
+from switch_core.bridges.agent.protocol.agent_detail import (
+ agent_facing_summary,
+ list_agent_summaries,
+)
+from switch_core.db.models import Document, Package, Reference, ReferenceType, User
+from switch_core.db.stores.agent_session_store import AgentSessionStore
from switch_core.db.stores.agent_store import AgentStore
+from switch_core.db.stores.room_role_store import RoomRoleStore
from switch_core.db.stores.user_store import UserStore
-from switch_core.gateway.agents import list_agents
-from switch_core.gateway.packages import list_room_packages
+from switch_core.gateway import agents as gateway_agents
+from switch_core.gateway.agents import get_agent_detail, list_agents
+from switch_core.gateway.documents import get_document
+from switch_core.gateway.packages import get_package, list_room_packages
+from switch_core.gateway.references import get_reference, list_owned_reference_types
from switch_core.gateway.rooms import get_room
-from tests.switch_core.gateway.agent_route_harness import add_agent, add_user
+from switch_core.gateway.schemas import (
+ AgentDetail,
+ AgentSummary,
+ GatewayAgentDetail,
+ GatewayAgentSummary,
+)
+from tests.switch_core.accounts.test_ownership_transfer import _grant_github
+from tests.switch_core.gateway.agent_route_harness import (
+ SERVICES_ON,
+ add_agent,
+ add_user,
+)
from tests.switch_core.gateway.test_room_detail_access import (
_ROOM_STORE,
_USER_STORE,
@@ -28,6 +53,15 @@ from tests.switch_core.gateway.test_room_detail_access import (
)
+def _detail_protocol() -> SimpleNamespace:
+ """What `get_agent_detail` reads off the protocol, with nothing connected."""
+ return SimpleNamespace(
+ agent_session_store=AgentSessionStore(),
+ room_role_store=RoomRoleStore(),
+ connections=AgentConnectionRegistry(),
+ )
+
+
class TestRoomPermissions:
@pytest.mark.parametrize(
("caller", "write_visibility", "can_write", "can_manage"),
@@ -91,18 +125,273 @@ class TestAgentPermissions:
assert await manageable(owner, False) == {"mine": True, "theirs": False}
assert await manageable(owner, True) == {"mine": True, "theirs": True}
- async def test_an_agent_reading_a_summary_is_not_told_the_flag(
+ async def test_each_child_in_an_agents_detail_says_whether_the_caller_may_manage_it(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- """The flag is about the Gateway's caller, not the agent reading it."""
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ member = await add_user(session, name="member")
+ parent = await add_agent(session, name="parent", owner_id=owner.id)
+ child = await add_agent(session, name="parent-child", owner_id=owner.id)
+ child.parent_agent_id = parent.id
+ await session.flush()
+
+ async def manageable(user: User, admin: bool) -> tuple[bool, list[bool]]:
+ detail = await get_agent_detail(
+ parent.id,
+ session,
+ AgentStore(),
+ _ROOM_STORE,
+ UserStore(),
+ _detail_protocol(), # type: ignore[arg-type]
+ user,
+ admin,
+ SERVICES_ON, # type: ignore[arg-type]
+ )
+ return detail.can_manage, [c.can_manage for c in detail.children]
+
+ assert await manageable(owner, False) == (True, [True])
+ assert await manageable(member, False) == (False, [False])
+ assert await manageable(member, True) == (True, [True])
+
+ @staticmethod
+ def _deleted_meanwhile(monkeypatch: pytest.MonkeyPatch, agent_id: str) -> None:
+ """`agent_id` is deleted between the agents being read and what the
+ caller may do with them being read: it has no facts."""
+ read_facts = gateway_agents.agent_transfer_facts
+
+ async def without_it(*args: Any, **kwargs: Any) -> dict[str, Any]:
+ facts = await read_facts(*args, **kwargs)
+ facts.pop(agent_id, None)
+ return facts
+
+ monkeypatch.setattr(gateway_agents, "agent_transfer_facts", without_it)
+
+ async def test_an_agent_deleted_while_listing_is_left_out(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ await add_agent(session, name="stays", owner_id=owner.id)
+ gone = await add_agent(session, name="gone", owner_id=owner.id)
+ self._deleted_meanwhile(monkeypatch, gone.id)
+
+ summaries = await list_agents(
+ session, AgentStore(), UserStore(), owner, False
+ )
+
+ assert [s.name for s in summaries] == ["stays"]
+
+ @pytest.mark.parametrize("deleted", ["child", "parent"])
+ async def test_an_agent_deleted_while_its_detail_is_built(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ deleted: str,
+ ) -> None:
+ """A child that has gone is left out; the agent itself gone is 404."""
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ parent = await add_agent(session, name="parent", owner_id=owner.id)
+ child = await add_agent(session, name="parent-child", owner_id=owner.id)
+ child.parent_agent_id = parent.id
+ await session.flush()
+ self._deleted_meanwhile(
+ monkeypatch, child.id if deleted == "child" else parent.id
+ )
+
+ async def detail() -> GatewayAgentDetail:
+ return await get_agent_detail(
+ parent.id,
+ session,
+ AgentStore(),
+ _ROOM_STORE,
+ UserStore(),
+ _detail_protocol(), # type: ignore[arg-type]
+ owner,
+ False,
+ SERVICES_ON, # type: ignore[arg-type]
+ )
+
+ if deleted == "child":
+ assert (await detail()).children == []
+ else:
+ with pytest.raises(HTTPException) as gone:
+ await detail()
+ assert gone.value.status_code == 404
+
+ async def test_an_agent_never_reads_what_the_gateways_caller_may_do(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """The flags are about the Gateway's caller, not the agent reading, so
+ they live only on the Gateway's own models."""
+ summary_flags = (
+ GatewayAgentSummary.model_fields.keys() - AgentSummary.model_fields.keys()
+ )
+ detail_flags = (
+ GatewayAgentDetail.model_fields.keys() - AgentDetail.model_fields.keys()
+ )
+ assert "can_manage" in summary_flags
+ assert summary_flags <= detail_flags
async with session_factory() as session:
owner = await add_user(session, name="owner")
await add_agent(session, name="mine", owner_id=owner.id)
- [summary] = await list_agents(
+ [summary] = await list_agent_summaries(session, AgentStore(), UserStore())
+
+ assert summary_flags.isdisjoint(agent_facing_summary(summary))
+
+ async def test_an_agent_in_a_family_of_sub_agents_cannot_be_renamed(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ await add_agent(session, name="solo", owner_id=owner.id)
+ parent = await add_agent(session, name="parent", owner_id=owner.id)
+ child = await add_agent(session, name="parent-child", owner_id=owner.id)
+ child.parent_agent_id = parent.id
+ await session.flush()
+
+ summaries = await list_agents(
session, AgentStore(), UserStore(), owner, False
)
- assert "can_manage" not in agent_facing_summary(summary)
+ assert {s.name: (s.can_manage, s.can_rename) for s in summaries} == {
+ "solo": (True, True),
+ "parent": (True, False),
+ "parent-child": (True, False),
+ }
+
+ async def test_only_an_agent_run_from_a_known_spec_has_options_to_edit(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ member = await add_user(session, name="member")
+ for name, known_type in (
+ ("console", "claude-code"),
+ ("retired", "retired-type"),
+ ("own-runtime", None),
+ ):
+ agent = await add_agent(session, name=name, owner_id=owner.id)
+ if known_type is not None:
+ agent.metadata_ = {"known_agent_type": known_type}
+ await session.flush()
+
+ async def editable(user: User, admin: bool) -> dict[str, bool]:
+ summaries = await list_agents(
+ session, AgentStore(), UserStore(), user, admin
+ )
+ return {s.name: s.can_edit_options for s in summaries}
+
+ assert await editable(owner, False) == {
+ "console": True,
+ "retired": False,
+ "own-runtime": False,
+ }
+ assert await editable(member, True) == await editable(owner, False)
+ assert set((await editable(member, False)).values()) == {False}
+
+ async def test_each_listed_agent_says_whether_it_can_be_transferred_and_why_not(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ member = await add_user(session, name="member")
+ await add_agent(session, name="plain", owner_id=owner.id)
+ manager = await add_agent(session, name="manager", owner_id=owner.id)
+ manager.can_manage_agents = True
+ await session.flush()
+
+ async def transfer(user: User) -> dict[str, tuple[bool, str | None]]:
+ summaries = await list_agents(
+ session, AgentStore(), UserStore(), user, False
+ )
+ return {
+ s.name: (s.can_transfer, s.transfer_blocked_reason)
+ for s in summaries
+ }
+
+ by_owner = await transfer(owner)
+ assert by_owner["plain"] == (True, None)
+ assert by_owner["manager"][0] is False
+ assert "manage its owner's agents" in (by_owner["manager"][1] or "")
+ # Someone who may not transfer it at all is not told why not.
+ assert await transfer(member) == {
+ "plain": (False, None),
+ "manager": (False, None),
+ }
+
+ async def test_only_its_owner_is_told_which_services_block_a_transfer(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ admin = await add_user(session, name="admin")
+ agent = await add_agent(session, name="helper", owner_id=owner.id)
+ await _grant_github(session, owner, agent)
+
+ async def reason(user: User, is_admin: bool) -> str:
+ [summary] = await list_agents(
+ session, AgentStore(), UserStore(), user, is_admin
+ )
+ assert summary.can_transfer is False
+ return summary.transfer_blocked_reason or ""
+
+ assert "github" in await reason(owner, False)
+ assert "github" not in await reason(admin, True)
+
+ @pytest.mark.parametrize(
+ (
+ "caller",
+ "services_on",
+ "known_type",
+ "change_manage_agents",
+ "grant_services",
+ ),
+ [
+ ("owner", True, "claude-code", True, True),
+ ("owner", False, "claude-code", True, False),
+ ("owner", True, None, True, False),
+ ("owner", True, "retired-type", True, False),
+ ("admin", True, "claude-code", False, False),
+ ("member", True, "claude-code", False, False),
+ ],
+ )
+ async def test_only_the_owner_may_change_what_the_agent_itself_may_do(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ caller: str,
+ services_on: bool,
+ known_type: str | None,
+ change_manage_agents: bool,
+ grant_services: bool,
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ member = await add_user(session, name="member")
+ agent = await add_agent(session, name="helper", owner_id=owner.id)
+ if known_type is not None:
+ agent.metadata_ = {"known_agent_type": known_type}
+ await session.flush()
+
+ detail = await get_agent_detail(
+ agent.id,
+ session,
+ AgentStore(),
+ _ROOM_STORE,
+ UserStore(),
+ _detail_protocol(), # type: ignore[arg-type]
+ owner if caller == "owner" else member,
+ caller == "admin",
+ SimpleNamespace(service_connections_enabled=services_on), # type: ignore[arg-type]
+ )
+
+ assert (detail.can_change_manage_agents, detail.can_grant_services) == (
+ change_manage_agents,
+ grant_services,
+ )
class TestRoomPackagePermissions:
@@ -157,3 +446,213 @@ class TestRoomPackagePermissions:
assert await readable(member) == {"shared": True, "private": False}
assert await readable(owner) == {"shared": True, "private": True}
+
+
+# Who reads a resource, whether its write visibility lets everyone change it,
+# and the (can_edit, can_manage) the server must report: what visibility gives
+# a member is editing, never deleting, transferring or changing who may see it.
+_RESOURCE_CASES = [
+ ("owner", "private", True, True),
+ ("admin", "private", True, True),
+ ("member", "public", True, False),
+ ("member", "private", False, False),
+]
+
+
+def _visible(owner: User, write_visibility: str) -> dict[str, object]:
+ return {
+ "owner_id": owner.id,
+ "read_visibility": "public",
+ "write_visibility": write_visibility,
+ "name": f"r-{uuid.uuid4().hex[:6]}",
+ "description": "",
+ "instructions": "",
+ }
+
+
+class TestResourcePermissions:
+ @pytest.mark.parametrize(
+ ("caller", "write_visibility", "can_edit", "can_manage"), _RESOURCE_CASES
+ )
+ async def test_a_reference_says_what_the_caller_may_do(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ caller: str,
+ write_visibility: str,
+ can_edit: bool,
+ can_manage: bool,
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ member = await add_user(session, name="member")
+ reference = Reference(
+ **_visible(owner, write_visibility),
+ type="url",
+ value={"urls": ["https://example.test"]},
+ )
+ session.add(reference)
+ await session.flush()
+
+ detail = await get_reference(
+ reference.id,
+ session,
+ _svc(session_factory),
+ _USER_STORE,
+ owner if caller == "owner" else member,
+ caller == "admin",
+ )
+
+ assert (detail.can_edit, detail.can_manage) == (can_edit, can_manage)
+
+ @pytest.mark.parametrize(
+ ("caller", "write_visibility", "can_edit", "can_manage"), _RESOURCE_CASES
+ )
+ async def test_a_document_says_what_the_caller_may_do(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ caller: str,
+ write_visibility: str,
+ can_edit: bool,
+ can_manage: bool,
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ member = await add_user(session, name="member")
+ document = Document(**_visible(owner, write_visibility), content="")
+ session.add(document)
+ await session.flush()
+
+ detail = await get_document(
+ document.id,
+ session,
+ _svc(session_factory),
+ _USER_STORE,
+ AgentStore(),
+ owner if caller == "owner" else member,
+ caller == "admin",
+ )
+
+ assert (detail.can_edit, detail.can_manage, detail.can_transfer) == (
+ can_edit,
+ can_manage,
+ can_manage,
+ )
+
+ @pytest.mark.parametrize(
+ ("caller", "write_visibility", "can_edit", "can_manage"), _RESOURCE_CASES
+ )
+ async def test_a_package_says_what_the_caller_may_do(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ caller: str,
+ write_visibility: str,
+ can_edit: bool,
+ can_manage: bool,
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ member = await add_user(session, name="member")
+ package = Package(**_visible(owner, write_visibility))
+ session.add(package)
+ await session.flush()
+
+ detail = await get_package(
+ package.id,
+ session,
+ _svc(session_factory),
+ _USER_STORE,
+ owner if caller == "owner" else member,
+ caller == "admin",
+ )
+
+ assert (detail.can_edit, detail.can_manage) == (can_edit, can_manage)
+
+ @pytest.mark.parametrize("caller", ["owner", "admin"])
+ async def test_a_managed_reference_type_says_it_may_be_changed(
+ self, session_factory: async_sessionmaker[AsyncSession], caller: str
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ member = await add_user(session, name="member")
+ session.add(
+ ReferenceType(
+ type="notion",
+ owner_id=owner.id,
+ read_visibility="public",
+ write_visibility="private",
+ display_name="Notion",
+ instructions="",
+ value_hint="",
+ )
+ )
+ await session.flush()
+
+ [listed] = await list_owned_reference_types(
+ session,
+ _svc(session_factory),
+ _USER_STORE,
+ owner if caller == "owner" else member,
+ caller == "admin",
+ )
+
+ assert (listed.can_edit, listed.can_manage) == (True, True)
+
+ async def test_a_rooms_own_document_is_not_the_librarys_to_change(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ room = await _add_room(session, name="r1", owner_id=owner.id)
+ document = Document(
+ **_visible(owner, "private"), content="", room_id=room.id
+ )
+ session.add(document)
+ await session.flush()
+
+ detail = await get_document(
+ document.id,
+ session,
+ _svc(session_factory),
+ _USER_STORE,
+ AgentStore(),
+ owner,
+ False,
+ )
+
+ # It is changed and removed in its room (`can_remove` there).
+ assert (detail.can_edit, detail.can_manage, detail.can_transfer) == (
+ False,
+ False,
+ False,
+ )
+
+
+class TestRoomTransfer:
+ @pytest.mark.parametrize(
+ ("metadata", "can_transfer"),
+ [(None, True), ({"chat_operation_id": "op-1"}, False)],
+ )
+ async def test_a_room_says_whether_it_can_be_transferred(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ metadata: dict[str, str] | None,
+ can_transfer: bool,
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ room = await _add_room(session, name="r1", owner_id=owner.id)
+ room.metadata_ = metadata
+ await session.flush()
+
+ detail = await get_room(
+ room.id,
+ session,
+ _ROOM_STORE,
+ None, # type: ignore[arg-type] # bridge_store: the room has no bridge
+ None, # type: ignore[arg-type] # external_user_store
+ _protocol(),
+ owner,
+ False,
+ )
+
+ assert (detail.can_manage, detail.can_transfer) == (True, can_transfer)
diff --git a/core/tests/switch_core/gateway/test_collaborations_authz.py b/core/tests/switch_core/gateway/test_collaborations_authz.py
index 89793e48f..937b8c77a 100644
--- a/core/tests/switch_core/gateway/test_collaborations_authz.py
+++ b/core/tests/switch_core/gateway/test_collaborations_authz.py
@@ -27,6 +27,7 @@ import pytest
from fastapi import HTTPException
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+from switch_core.authz import Principal
from switch_core.bridges.agent.auth import PUBLIC_PATH_PREFIXES
from switch_core.bridges.collaboration.models import DirectoryUser
from switch_core.db.models import Client, CollaborationBridge, User
@@ -34,6 +35,7 @@ from switch_core.db.stores.collaboration_bridge_store import CollaborationBridge
from switch_core.db.stores.room_store import RoomStore
from switch_core.gateway.auth import get_current_user, require_tenant_admin
from switch_core.gateway.collaborations import (
+ _claimants,
_require_directory_account,
claim_bridge_identity,
release_bridge_identity,
@@ -365,3 +367,21 @@ async def test_set_default_unknown_bridge_is_404(
_admin(),
)
assert exc.value.status_code == 404
+
+
+class TestWhoMayUnlinkAClaim:
+ def test_each_claimant_says_whether_the_caller_may_drop_their_claim(self) -> None:
+ claims = [
+ SimpleNamespace(user_id="me", verified_at=None),
+ SimpleNamespace(user_id="them", verified_at=None),
+ ]
+ names = {"me": "Me", "them": "Them"}
+
+ def unlinkable(viewer: Principal) -> dict[str, bool]:
+ return {
+ c.user_id: c.can_unlink
+ for c in _claimants(claims, names, viewer) # type: ignore[arg-type]
+ }
+
+ assert unlinkable(Principal("me", False)) == {"me": True, "them": False}
+ assert unlinkable(Principal("me", True)) == {"me": True, "them": True}
diff --git a/core/tests/switch_core/gateway/test_collaborations_preconfigured.py b/core/tests/switch_core/gateway/test_collaborations_preconfigured.py
index cebdbd068..9ef8a29b6 100644
--- a/core/tests/switch_core/gateway/test_collaborations_preconfigured.py
+++ b/core/tests/switch_core/gateway/test_collaborations_preconfigured.py
@@ -169,8 +169,33 @@ class TestReadingItBack:
_ROOM_STORE,
_NoRunningBridges(), # type: ignore[arg-type]
_admin(),
+ True,
)
flags = {d.bridge_id: d.preconfigured for d in listed}
assert flags[bundled] is True
assert flags[added] is False
+
+
+class TestWhatTheCallerMayDo:
+ async def test_each_bridge_says_whether_the_caller_may_change_or_delete_it(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ await _make_bridge(session)
+ await session.commit()
+
+ async def flags(is_admin: bool) -> tuple[bool, bool]:
+ async with session_factory() as session:
+ [listed] = await list_bridges(
+ session,
+ _BRIDGE_STORE,
+ _ROOM_STORE,
+ _NoRunningBridges(), # type: ignore[arg-type]
+ _admin(),
+ is_admin,
+ )
+ return listed.can_manage, listed.can_delete
+
+ assert await flags(True) == (True, True)
+ assert await flags(False) == (False, False)
diff --git a/core/tests/switch_core/gateway/test_connection_catalog.py b/core/tests/switch_core/gateway/test_connection_catalog.py
index fdaca9c19..fc0b2351a 100644
--- a/core/tests/switch_core/gateway/test_connection_catalog.py
+++ b/core/tests/switch_core/gateway/test_connection_catalog.py
@@ -102,6 +102,7 @@ async def test_catalog_lists_the_enabled_services_and_placeholders(catalog_app):
"enabled": True,
"auth_type": "oauth",
"status": "not_connected",
+ "can_revoke": False,
}
@@ -125,3 +126,22 @@ async def test_catalog_reports_only_the_callers_connection(catalog_app):
statuses(await client.get("/gateway/provider-connections/catalog"))["github"]
== "connected"
)
+
+
+async def test_only_the_callers_own_connection_may_be_revoked(catalog_app):
+ client, factory = catalog_app
+
+ def revocable(response):
+ assert response.status_code == 200, response.text
+ return {e["slug"]: e["can_revoke"] for e in response.json()["connections"]}
+
+ await link_github(factory, "other-user")
+ assert (
+ revocable(await client.get("/gateway/provider-connections/catalog"))["github"]
+ is False
+ )
+ await link_github(factory, "catalog-user")
+ assert (
+ revocable(await client.get("/gateway/provider-connections/catalog"))["github"]
+ is True
+ )
diff --git a/core/tests/switch_core/gateway/test_create_user.py b/core/tests/switch_core/gateway/test_create_user.py
index 765354eaa..56c872ef1 100644
--- a/core/tests/switch_core/gateway/test_create_user.py
+++ b/core/tests/switch_core/gateway/test_create_user.py
@@ -59,6 +59,7 @@ def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
gateway_cookie_secure=False,
gateway_password_login_enabled=True,
gateway_tenant_choice_enabled=False,
+ gateway_admin_email="[email protected]",
)
return app
@@ -372,3 +373,34 @@ class TestCreateUserSchemaValidation:
def test_bad_email_rejected(self) -> None:
with pytest.raises(ValidationError):
CreateUserRequest(name="Ada", email="not-an-email", password="good-pass-1")
+
+
+class TestWhichAccountsTheOperatorMayDelete:
+ async def test_each_user_says_whether_the_operator_may_delete_them(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """Not their own account, nor the server's administrator account,
+ which the server recreates; the same refusals `DELETE /users/{id}`
+ makes before anything else."""
+ async with session_factory() as session:
+ for name, email, role in (
+ ("Ada", "[email protected]", "user"),
+ ("Root", "[email protected]", "admin"),
+ ("Configured", "[email protected]", "user"),
+ ):
+ await _USER_STORE.create(
+ session,
+ User(name=name, email=email, role=role, password_hash=None),
+ )
+ await session.commit()
+ app = _app(session_factory)
+ async with await _admin_client(session_factory, app) as client:
+ response = await client.get("/users")
+
+ assert response.status_code == 200, response.text
+ assert {u["name"]: u["can_delete"] for u in response.json()} == {
+ "Operator": False,
+ "Ada": True,
+ "Root": False,
+ "Configured": False,
+ }
diff --git a/core/tests/switch_core/gateway/test_directory_fallback.py b/core/tests/switch_core/gateway/test_directory_fallback.py
index 2b5232b61..c549e07af 100644
--- a/core/tests/switch_core/gateway/test_directory_fallback.py
+++ b/core/tests/switch_core/gateway/test_directory_fallback.py
@@ -107,6 +107,7 @@ async def _search(
_StubUserStore(), # type: ignore[arg-type]
_StubLifecycle(adapter_result), # type: ignore[arg-type]
SimpleNamespace(id="u1", role="user", name="u1"), # type: ignore[arg-type]
+ False,
)
diff --git a/core/tests/switch_core/gateway/test_github_connections.py b/core/tests/switch_core/gateway/test_github_connections.py
index 0ea6211d6..8ce48c269 100644
--- a/core/tests/switch_core/gateway/test_github_connections.py
+++ b/core/tests/switch_core/gateway/test_github_connections.py
@@ -200,7 +200,8 @@ async def test_browser_handoff_completes_through_console_and_saves_encrypted(
await relay(client, flow_id)
github.exchange.assert_not_called()
assert (await client.get(BASE + f"/flows/{flow_id}")).json()["status"] == "pending"
- assert (await client.get(BASE)).json()["status"] == "not_connected"
+ before = (await client.get(BASE)).json()
+ assert (before["status"], before["can_revoke"]) == ("not_connected", False)
completed = await complete(client, flow_id)
assert completed.status_code == 200, completed.text
assert completed.json() == {"warning": None, "login": "example-user"}
@@ -217,6 +218,7 @@ async def test_browser_handoff_completes_through_console_and_saves_encrypted(
== "example/project"
)
assert status.json()["sso_hidden_organizations"] == []
+ assert status.json()["can_revoke"] is True
assert "SYNTHETIC-ACCESS" not in status.text
async with factory() as session:
row = await session.scalar(
diff --git a/core/tests/switch_core/gateway/test_held_connections.py b/core/tests/switch_core/gateway/test_held_connections.py
index f936657f7..0975451b0 100644
--- a/core/tests/switch_core/gateway/test_held_connections.py
+++ b/core/tests/switch_core/gateway/test_held_connections.py
@@ -257,6 +257,7 @@ def _config() -> SimpleNamespace:
gateway_password_login_enabled=True,
gateway_signup_open=True,
gateway_signup_max_per_hour=100,
+ gateway_admin_email="[email protected]",
)
diff --git a/core/tests/switch_core/gateway/test_identity_link_confirmation.py b/core/tests/switch_core/gateway/test_identity_link_confirmation.py
index 88509f845..4bd167f04 100644
--- a/core/tests/switch_core/gateway/test_identity_link_confirmation.py
+++ b/core/tests/switch_core/gateway/test_identity_link_confirmation.py
@@ -217,6 +217,7 @@ async def _verify(world: _World, caller: User, adapter: _Adapter | None) -> obje
UserStore(),
_Lifecycle(adapter), # type: ignore[arg-type]
caller,
+ False,
)
@@ -664,6 +665,7 @@ class TestVerifyingWithASession:
UserStore(),
_Lifecycle(_Adapter(_STAND_IN)), # type: ignore[arg-type]
world.ada,
+ False,
)
assert refused.value.status_code == 409
diff --git a/core/tests/switch_core/gateway/test_messaging_install_routes.py b/core/tests/switch_core/gateway/test_messaging_install_routes.py
index cfb8ba844..71183a990 100644
--- a/core/tests/switch_core/gateway/test_messaging_install_routes.py
+++ b/core/tests/switch_core/gateway/test_messaging_install_routes.py
@@ -106,7 +106,9 @@ class _Service:
return next(i.platform for i in self.installs if i.id == install_id)
async def disconnect(self, *, tenant_id: str, install_id: str) -> SimpleNamespace:
+ """Ended, a chat lets go of its room, as `chat_rooms` then says."""
self.disconnected.append(install_id)
+ self.rooms.pop(install_id, None)
return next(i for i in self.installs if i.id == install_id)
@@ -336,3 +338,65 @@ class TestPrivateRooms:
with tenant_scope(_TENANT):
await disconnect_install("t1", _Session(), service, _user(), True) # type: ignore[arg-type]
assert service.disconnected == ["t1"]
+
+
+class TestWhatTheCallerMayDisconnect:
+ """Each listed install says whether the caller may disconnect it, by the
+ rule `disconnect_install` enforces."""
+
+ @pytest.mark.parametrize(
+ ("rooms", "admin", "expected"),
+ [
+ # A chat whose room the caller may change; an OAuth install is an
+ # admin's alone.
+ ({"t1": _room()}, False, {"t1": True}),
+ ({"t1": _room()}, True, {"s1": True, "t1": True}),
+ # Readable, but not theirs to change.
+ ({"t1": _room(write="private")}, False, {"t1": False}),
+ # Its room is gone, so it is the tenant's admins' again.
+ ({}, False, {"t1": False}),
+ ({}, True, {"s1": True, "t1": True}),
+ ],
+ )
+ async def test_each_install_says_whether_the_caller_may_disconnect_it(
+ self,
+ rooms: dict[str, SimpleNamespace],
+ admin: bool,
+ expected: dict[str, bool],
+ ) -> None:
+ listed = await list_installs(
+ _Session(), # type: ignore[arg-type]
+ _Service(rooms=rooms), # type: ignore[arg-type]
+ _user(),
+ admin,
+ )
+ assert {i.id: i.can_disconnect for i in listed.installs} == expected
+
+ async def test_an_ended_install_says_so_by_its_status_not_its_flag(self) -> None:
+ """Disconnecting it again answers it as it is, so the flag stays the
+ rule the route enforces."""
+ ended = _install("s1", "slack")
+ ended.status = "disconnected"
+ listed = await list_installs(
+ _Session(), # type: ignore[arg-type]
+ _Service(installs=[ended]), # type: ignore[arg-type]
+ _user(),
+ True,
+ )
+ assert [(i.status, i.can_disconnect) for i in listed.installs] == [
+ ("disconnected", True)
+ ]
+
+ @pytest.mark.parametrize(("admin", "expected"), [(False, False), (True, True)])
+ async def test_a_disconnected_chat_is_an_admins_once_its_room_is_let_go(
+ self, admin: bool, expected: bool
+ ) -> None:
+ with tenant_scope(_TENANT):
+ ended = await disconnect_install(
+ "t1",
+ _Session(), # type: ignore[arg-type]
+ _Service(), # type: ignore[arg-type]
+ _user(),
+ admin,
+ )
+ assert ended.can_disconnect is expected
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 ea8d1a8af..898685758 100644
--- a/core/tests/switch_core/gateway/test_organization_directory_routes.py
+++ b/core/tests/switch_core/gateway/test_organization_directory_routes.py
@@ -497,3 +497,28 @@ class TestTheCurrentOrganization:
assert response.status_code == 200, response.text
assert response.json()["members_from_directory"] is True
+
+
+class _OneWayDirectory(_Directory):
+ """Keeps the organization's members, and takes no change made from Switch:
+ a linked organization with no WorkOS members service."""
+
+ def sends_changes_for(self, organization: Organization) -> bool:
+ return False
+
+
+async def test_nobody_is_offered_org_admin_where_the_directory_takes_no_changes(
+ session_factory,
+) -> None:
+ ada, bob = _name("ada"), _name("bob")
+ tenant_id = await _workspace(
+ session_factory, {ada: ("admin", "org_admin"), bob: ("member", "member")}
+ )
+ directory = _OneWayDirectory(None)
+
+ async with _client(_with(session_factory, directory), ada, tenant_id) as client:
+ response = await client.get("/organizations/current/members")
+
+ assert response.status_code == 200, response.text
+ [row] = [row for row in response.json() if row["user_id"] == bob]
+ assert (row["can_change_role"], row["can_grant_org_admin"]) == (True, False)
diff --git a/core/tests/switch_core/gateway/test_organization_routes.py b/core/tests/switch_core/gateway/test_organization_routes.py
index 6a2a1c3e4..225be82cf 100644
--- a/core/tests/switch_core/gateway/test_organization_routes.py
+++ b/core/tests/switch_core/gateway/test_organization_routes.py
@@ -7,8 +7,10 @@ from __future__ import annotations
import asyncio
import uuid
+from collections.abc import Awaitable, Callable
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
+from typing import Any
import httpx
import pytest
@@ -42,7 +44,7 @@ from switch_core.db.stores.tenant_store import TenantStore
from switch_core.db.stores.user_store import UserStore
from switch_core.db.stores.workspace_service_store import WorkspaceServiceStore
from switch_core.gateway import dependencies as gw_deps
-from switch_core.gateway import workspace_creation
+from switch_core.gateway import organizations, workspace_creation
from switch_core.gateway.auth import create_jwt, decode_jwt
from switch_core.gateway.organizations import router as organizations_router
from switch_core.gateway.tenants import router as tenants_router
@@ -267,18 +269,31 @@ class TestChangingRoles:
assert response.status_code == 403
- async def test_the_last_org_admin_cannot_be_demoted(
- self, session_factory: async_sessionmaker[AsyncSession]
+ @pytest.mark.parametrize("another_admin", [True, False])
+ async def test_an_org_admin_steps_down_while_another_remains(
+ self, session_factory: async_sessionmaker[AsyncSession], another_admin: bool
) -> None:
- ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
+ """Their own role is theirs to change; the last one of all stays, as
+ nobody else could grant the role again."""
+ ada, bob = _name("ada"), _name("bob")
+ tenant_id = await _workspace(
+ session_factory,
+ {
+ ada: ("admin", "org_admin"),
+ bob: ("member", "org_admin" if another_admin else "member"),
+ },
+ )
async with _client(_app(session_factory), ada, tenant_id) as client:
response = await client.patch(
f"/organizations/current/members/{ada}", json={"role": "member"}
)
- assert response.status_code == 409
+ assert response.status_code == (200 if another_admin else 409), response.text
+ if another_admin:
+ assert response.json()["role"] == "member"
+ # Still in the workspace by her own membership, so still bound to it.
+ assert "set-cookie" not in response.headers
async def test_an_unknown_role_is_refused(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -405,17 +420,42 @@ class TestRemoving:
await _events(session_factory, tenant_id, AuditAction.MEMBER_REMOVED) == []
)
- async def test_the_last_org_admin_cannot_be_removed(
- self, session_factory: async_sessionmaker[AsyncSession]
+ @pytest.mark.parametrize("another_admin", [True, False])
+ async def test_an_org_admin_leaves_while_another_remains(
+ self, session_factory: async_sessionmaker[AsyncSession], another_admin: bool
) -> None:
- ada = _name("ada")
- tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")})
+ """As with their own role. Having stood in the workspace only as an
+ organization admin, the session no longer names it once she leaves."""
+ ada, bob, cy = _name("ada"), _name("bob"), _name("cy")
+ tenant_id = await _workspace(session_factory, {cy: ("admin", "member")})
+ organization_id = await _organization_id(session_factory, tenant_id)
+ assert organization_id is not None
+ async with session_factory() as session:
+ for name, role in (
+ (ada, "org_admin"),
+ (bob, "org_admin" if another_admin else "member"),
+ ):
+ session.add(
+ User(
+ id=name, name=name, email=f"{name}@example.invalid", role="user"
+ )
+ )
+ await session.flush()
+ session.add(
+ OrganizationMember(
+ organization_id=organization_id, user_id=name, role=role
+ )
+ )
+ await session.commit()
async with _client(_app(session_factory), ada, tenant_id) as client:
response = await client.delete(f"/organizations/current/members/{ada}")
- assert response.status_code == 409
- assert "last organization admin" in response.json()["detail"]
+ assert response.status_code == (200 if another_admin else 409), response.text
+ async with session_factory() as session:
+ left = await session.get(OrganizationMember, (organization_id, ada)) is None
+ assert left is another_admin
+ assert ("set-cookie" in response.headers) is another_admin
class TestTheWorkspaceRoster:
@@ -574,6 +614,53 @@ class TestThePlatformOperator:
assert changed.details is not None
assert changed.details["platform_access"] is True
+ async def test_an_operator_in_the_organization_may_restore_themselves(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """They may make themselves its `org_admin`, as anyone else."""
+ op = _name("op")
+ tenant_id = await _workspace(session_factory, {op: ("member", "member")})
+ async with session_factory() as session:
+ operator = await session.get(User, op)
+ assert operator is not None
+ operator.role = "admin"
+ await session.commit()
+
+ async with _client(_app(session_factory), op, tenant_id) as client:
+ [row] = (await client.get("/organizations/current/members")).json()
+ restored = await client.patch(
+ f"/organizations/current/members/{op}", json={"role": "org_admin"}
+ )
+
+ assert (row["can_change_role"], row["can_remove"]) == (True, False)
+ assert restored.status_code == 200, restored.text
+ assert restored.json()["role"] == "org_admin"
+ # Now an `org_admin`, they may change and remove their own row.
+ assert (
+ restored.json()["can_change_role"],
+ restored.json()["can_remove"],
+ ) == (True, True)
+
+ async def test_once_the_operator_restores_someone_else_their_way_in_closes(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ bob = _name("bob")
+ tenant_id = await _workspace(session_factory, {bob: ("member", "member")})
+ operator_id = await _operator(session_factory)
+
+ async with _client(_app(session_factory), operator_id, tenant_id) as client:
+ restored = await client.patch(
+ f"/organizations/current/members/{bob}", json={"role": "org_admin"}
+ )
+
+ assert restored.status_code == 200, restored.text
+ flags = restored.json()
+ assert (
+ flags["can_change_role"],
+ flags["can_grant_org_admin"],
+ flags["can_remove"],
+ ) == (False, False, False)
+
async def _user(session_factory: async_sessionmaker[AsyncSession], role: str) -> str:
user_id = _name("newcomer")
@@ -1329,6 +1416,119 @@ async def _organization_of(
return tenant.organization_id
+class TestTheLastOrgAdminUnderARace:
+ """Two org admins demoting or removing each other at once. The first holds
+ the admins' lock from before it takes anything away until its change
+ commits, so the second waits, counts after it, and is refused with
+ nothing of the other's taken away. The first is held while it ends the
+ other's access, and the second sent then, so the wait is seen every time
+ rather than when the timing allows."""
+
+ @staticmethod
+ async def _race(
+ monkeypatch: pytest.MonkeyPatch,
+ first: Callable[[], Awaitable[httpx.Response]],
+ second: Callable[[], Awaitable[httpx.Response]],
+ ) -> tuple[httpx.Response, httpx.Response, list[str]]:
+ ended: list[str] = []
+ entered, release = asyncio.Event(), asyncio.Event()
+ end_access = organizations._end_access_through_organization
+
+ async def held_once(*args: Any, **kwargs: Any) -> str | None:
+ ended.append(kwargs["user_id"])
+ if len(ended) == 1:
+ entered.set()
+ await release.wait()
+ return await end_access(*args, **kwargs)
+
+ monkeypatch.setattr(
+ organizations, "_end_access_through_organization", held_once
+ )
+ first_task = asyncio.create_task(first())
+ await entered.wait()
+ second_task = asyncio.create_task(second())
+ await asyncio.sleep(0.5)
+ assert not second_task.done(), "the second did not wait for the first"
+ release.set()
+ return await first_task, await second_task, ended
+
+ async def test_of_two_admins_demoting_each_other_the_second_takes_nothing(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ ada, bob = _name("ada"), _name("bob")
+ tenant_id = await _workspace(
+ session_factory, {ada: ("admin", "org_admin"), bob: ("admin", "org_admin")}
+ )
+ organization_id = await _organization_id(session_factory, tenant_id)
+ assert organization_id is not None
+ app = _app(session_factory)
+
+ async with (
+ _client(app, ada, tenant_id) as as_ada,
+ _client(app, bob, tenant_id) as as_bob,
+ ):
+ first, second, ended = await self._race(
+ monkeypatch,
+ lambda: as_ada.patch(
+ f"/organizations/current/members/{bob}", json={"role": "member"}
+ ),
+ lambda: as_bob.patch(
+ f"/organizations/current/members/{ada}", json={"role": "member"}
+ ),
+ )
+
+ assert first.status_code == 200, first.text
+ assert second.status_code == 409, second.text
+ assert "last organization admin" in second.json()["detail"]
+ assert ended == [bob]
+ async with session_factory() as session:
+ assert await OrganizationStore().count_admins(session, organization_id) == 1
+
+ async def test_of_two_admins_removing_each_other_the_second_takes_nothing(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ ada, bob, cy = _name("ada"), _name("bob"), _name("cy")
+ tenant_id = await _workspace(session_factory, {cy: ("admin", "member")})
+ organization_id = await _organization_id(session_factory, tenant_id)
+ assert organization_id is not None
+ async with session_factory() as session:
+ for name in (ada, bob):
+ session.add(
+ User(
+ id=name, name=name, email=f"{name}@example.invalid", role="user"
+ )
+ )
+ await session.flush()
+ session.add(
+ OrganizationMember(
+ organization_id=organization_id, user_id=name, role="org_admin"
+ )
+ )
+ await session.commit()
+ app = _app(session_factory)
+
+ async with (
+ _client(app, ada, tenant_id) as as_ada,
+ _client(app, bob, tenant_id) as as_bob,
+ ):
+ first, second, ended = await self._race(
+ monkeypatch,
+ lambda: as_ada.delete(f"/organizations/current/members/{bob}"),
+ lambda: as_bob.delete(f"/organizations/current/members/{ada}"),
+ )
+
+ assert first.status_code == 200, first.text
+ assert second.status_code == 409, second.text
+ assert "last organization admin" in second.json()["detail"]
+ assert ended == [bob]
+ async with session_factory() as session:
+ assert await OrganizationStore().count_admins(session, organization_id) == 1
+
+
class TestIssues:
"""What needs an organization admin's attention, read from how things
stand: an issue is gone once fixed."""
@@ -1479,3 +1679,89 @@ class TestIssues:
response = await client.get("/organizations/current/issues")
assert response.status_code == 403
+
+
+class TestWhatTheCallerMayDo:
+ @pytest.mark.parametrize(
+ ("who", "administers", "can_manage_members"),
+ [
+ ("org-admin", True, True),
+ ("member", False, False),
+ # Only while the organization has no admin, to make one.
+ ("operator-restoring", False, True),
+ ("operator", False, False),
+ ],
+ )
+ async def test_the_organization_says_whether_the_caller_runs_it(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ who: str,
+ administers: bool,
+ can_manage_members: bool,
+ ) -> None:
+ ada, bob = _name("ada"), _name("bob")
+ restoring = who == "operator-restoring"
+ tenant_id = await _workspace(
+ session_factory,
+ {
+ ada: ("admin", "member" if restoring else "org_admin"),
+ bob: ("member", "member"),
+ },
+ )
+ caller = {"org-admin": ada, "member": bob}.get(who) or await _operator(
+ session_factory
+ )
+
+ async with _client(_app(session_factory), caller, tenant_id) as client:
+ response = await client.get("/organizations/current")
+
+ assert response.status_code == 200, response.text
+ assert (
+ response.json()["administers"],
+ response.json()["can_manage_members"],
+ ) == (administers, can_manage_members)
+
+ async def test_each_member_says_what_an_org_admin_may_do_with_them(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ ada, bob, cy = _name("ada"), _name("bob"), _name("cy")
+ tenant_id = await _workspace(
+ session_factory,
+ {
+ ada: ("admin", "org_admin"),
+ bob: ("member", "member"),
+ cy: ("member", "org_admin"),
+ },
+ )
+
+ async with _client(_app(session_factory), ada, tenant_id) as client:
+ response = await client.get("/organizations/current/members")
+
+ assert response.status_code == 200, response.text
+ assert {
+ row["user_id"]: (
+ row["can_change_role"],
+ row["can_grant_org_admin"],
+ row["can_remove"],
+ )
+ for row in response.json()
+ } == {
+ # Their own row too: they step down or leave while another remains.
+ ada: (True, True, True),
+ bob: (True, True, True),
+ cy: (True, True, True),
+ }
+
+ async def test_the_operator_restoring_an_admin_may_change_roles_and_nothing_more(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ bob = _name("bob")
+ tenant_id = await _workspace(session_factory, {bob: ("member", "member")})
+ operator_id = await _operator(session_factory)
+
+ async with _client(_app(session_factory), operator_id, tenant_id) as client:
+ response = await client.get("/organizations/current/members")
+
+ assert response.status_code == 200, response.text
+ [row] = response.json()
+ assert (row["can_change_role"], row["can_remove"]) == (True, False)
diff --git a/core/tests/switch_core/gateway/test_room_resource_permissions.py b/core/tests/switch_core/gateway/test_room_resource_permissions.py
index 1a070a7fb..992febf65 100644
--- a/core/tests/switch_core/gateway/test_room_resource_permissions.py
+++ b/core/tests/switch_core/gateway/test_room_resource_permissions.py
@@ -67,7 +67,7 @@ from switch_core.gateway.room_links import (
)
from switch_core.gateway.rooms import list_rooms
from switch_core.gateway.schemas import LinkedRoomCreateRequest
-from tests.switch_core.gateway.agent_route_harness import add_agent
+from tests.switch_core.gateway.agent_route_harness import SERVICES_ON, add_agent
_ROOM_STORE = RoomStore()
_USER_STORE = UserStore()
@@ -554,6 +554,7 @@ async def test_an_agents_detail_names_only_rooms_its_viewer_may_read(
protocol, # type: ignore[arg-type]
user,
admin,
+ SERVICES_ON, # type: ignore[arg-type]
)
return {room.room_name for room in detail.rooms}
diff --git a/core/tests/switch_core/gateway/test_server_side_gates.py b/core/tests/switch_core/gateway/test_server_side_gates.py
new file mode 100644
index 000000000..6b043eca8
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_server_side_gates.py
@@ -0,0 +1,285 @@
+"""Actions the Gateway hides that the server now refuses on its own, so no
+route relies on the page to keep them from happening."""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+
+from sqlalchemy import select, update
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import (
+ Document,
+ Invitation,
+ Package,
+ Room,
+ package_references,
+)
+from switch_core.tenant_context import tenant_scope
+from tests.switch_core.gateway.role_matrix.harness import (
+ TENANT,
+ Persona,
+ build_gateway,
+ client,
+ seed_people,
+)
+from tests.switch_core.gateway.role_matrix.world import World
+
+
+async def test_a_direct_or_group_conversations_members_are_not_changed_here(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ """Its platform fixes who is in it. A DM the bridge adopted is writable by
+ every member, so without this anyone could put their own agent in
+ someone else's DM."""
+ gateway = build_gateway(session_factory)
+ people = await seed_people(session_factory)
+ answers: dict[tuple[str, str], int] = {}
+ async with client(gateway) as http:
+ for channel_type in ("direct", "group"):
+ world = World(
+ session_factory, people, f"{channel_type}-room", http, gateway
+ )
+ room_id = await world.room_agent()
+ agent_id = await world.agent()
+ other = await world.other_agent()
+ with tenant_scope(TENANT):
+ async with session_factory() as session:
+ await session.execute(
+ update(Room)
+ .where(Room.id == room_id)
+ .values(
+ channel_type=channel_type,
+ read_visibility="public",
+ write_visibility="public",
+ )
+ )
+ await session.commit()
+ for persona in (Persona.MEMBER, Persona.WORKSPACE_ADMIN):
+ headers = people.headers(persona)
+ for what, response in (
+ (
+ "add agent",
+ await http.post(
+ f"/gateway/rooms/{room_id}/agents",
+ json={"agent_ids": [other]},
+ headers=headers,
+ ),
+ ),
+ (
+ "remove agent",
+ await http.delete(
+ f"/gateway/rooms/{room_id}/agents/{agent_id}",
+ headers=headers,
+ ),
+ ),
+ (
+ "add people",
+ await http.post(
+ f"/gateway/rooms/{room_id}/users",
+ json={"user_names": ["someone"]},
+ headers=headers,
+ ),
+ ),
+ ):
+ answers[(f"{channel_type} {what}", persona.value)] = (
+ response.status_code
+ )
+ assert set(answers.values()) == {409}, answers
+
+
+async def test_adding_to_a_package_takes_reading_what_is_added(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ """A package lists what it holds to everyone who may read it, so adding
+ an item someone can't read would show it to them."""
+ gateway = build_gateway(session_factory)
+ people = await seed_people(session_factory)
+ async with client(gateway) as http:
+ world = World(session_factory, people, "package-read", http, gateway)
+ package_id = await world.package()
+ reference_id = await world.reference()
+ document_id = await world.document()
+ with tenant_scope(TENANT):
+ async with session_factory() as session:
+ await session.execute(
+ update(Package)
+ .where(Package.id == package_id)
+ .values(read_visibility="public", write_visibility="public")
+ )
+ await session.commit()
+ headers = people.headers(Persona.MEMBER)
+ reference = await http.post(
+ f"/gateway/packages/{package_id}/references/{reference_id}", headers=headers
+ )
+ document = await http.post(
+ f"/gateway/packages/{package_id}/documents/{document_id}", headers=headers
+ )
+ listed = await http.get(
+ f"/gateway/packages/{package_id}/references", headers=headers
+ )
+ assert (reference.status_code, document.status_code) == (403, 403)
+ assert listed.status_code == 200 and listed.json() == []
+
+
+async def test_a_rooms_own_document_is_changed_in_its_room_not_the_library(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ gateway = build_gateway(session_factory)
+ people = await seed_people(session_factory)
+ async with client(gateway) as http:
+ world = World(session_factory, people, "room-document", http, gateway)
+ room_id = await world.room()
+ document_id = await world.document()
+ with tenant_scope(TENANT):
+ async with session_factory() as session:
+ await session.execute(
+ update(Document)
+ .where(Document.id == document_id)
+ .values(room_id=room_id)
+ )
+ await session.commit()
+ answers = {
+ persona.value: (
+ (
+ await http.patch(
+ f"/gateway/documents/{document_id}",
+ json={"read_visibility": "public"},
+ headers=people.headers(persona),
+ )
+ ).status_code,
+ (
+ await http.delete(
+ f"/gateway/documents/{document_id}",
+ headers=people.headers(persona),
+ )
+ ).status_code,
+ )
+ for persona in (Persona.OWNER, Persona.WORKSPACE_ADMIN, Persona.MEMBER)
+ }
+ assert answers == {
+ Persona.OWNER.value: (409, 409),
+ Persona.WORKSPACE_ADMIN.value: (409, 409),
+ # Not told what it is: it can't read it.
+ Persona.MEMBER.value: (403, 403),
+ }
+
+
+async def test_an_invitation_that_has_ended_is_not_revoked_again(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ """Revoking it again would rewrite when, and by whom, it ended."""
+ gateway = build_gateway(session_factory)
+ people = await seed_people(session_factory)
+ headers = people.headers(Persona.WORKSPACE_ADMIN)
+ async with client(gateway) as http:
+ revoked = await World(
+ session_factory, people, "revoked", http, gateway
+ ).invitation()
+ expired = await World(
+ session_factory, people, "expired", http, gateway
+ ).invitation()
+ with tenant_scope(TENANT):
+ async with session_factory() as session:
+ await session.execute(
+ update(Invitation)
+ .where(Invitation.id == expired)
+ .values(expires_at=datetime.now(UTC) - timedelta(days=1))
+ )
+ await session.commit()
+ path = f"/gateway/tenants/{TENANT}/invitations"
+ first = await http.delete(f"{path}/{revoked}", headers=headers)
+ with tenant_scope(TENANT):
+ async with session_factory() as session:
+ revoked_at = await session.scalar(
+ select(Invitation.revoked_at).where(Invitation.id == revoked)
+ )
+ again = await http.delete(f"{path}/{revoked}", headers=headers)
+ late = await http.delete(f"{path}/{expired}", headers=headers)
+ with tenant_scope(TENANT):
+ async with session_factory() as session:
+ assert (
+ await session.scalar(
+ select(Invitation.revoked_at).where(Invitation.id == revoked)
+ )
+ == revoked_at
+ )
+ assert (first.status_code, again.status_code, late.status_code) == (200, 409, 409)
+
+
+async def test_attaching_what_is_already_attached_changes_nothing(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ """As for references: the page leaves attached things out of its pickers,
+ and asking again is not a server error."""
+ gateway = build_gateway(session_factory)
+ people = await seed_people(session_factory)
+ headers = people.headers(Persona.OWNER)
+ async with client(gateway) as http:
+ world = World(session_factory, people, "attach-twice", http, gateway)
+ room_id = await world.room()
+ package_id = await world.package()
+ document_id = await world.document()
+ reference_id = await world.reference()
+ statuses = [
+ (await http.post(path, headers=headers)).status_code
+ for path in (
+ f"/gateway/rooms/{room_id}/documents/{document_id}",
+ f"/gateway/rooms/{room_id}/documents/{document_id}",
+ f"/gateway/rooms/{room_id}/packages/{package_id}",
+ f"/gateway/rooms/{room_id}/packages/{package_id}",
+ f"/gateway/packages/{package_id}/references/{reference_id}",
+ f"/gateway/packages/{package_id}/references/{reference_id}",
+ f"/gateway/packages/{package_id}/documents/{document_id}",
+ f"/gateway/packages/{package_id}/documents/{document_id}",
+ )
+ ]
+ with tenant_scope(TENANT):
+ async with session_factory() as session:
+ held = (
+ await session.execute(
+ select(package_references).where(
+ package_references.c.package_id == package_id
+ )
+ )
+ ).all()
+ assert all(status < 300 for status in statuses), statuses
+ assert len(held) == 1
+
+
+async def test_saving_an_addressing_rule_that_can_never_match_is_refused(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ """It would let nobody in while looking as if it did, and a policy of
+ nothing else would shut the agent off, its owner included."""
+ gateway = build_gateway(session_factory)
+ people = await seed_people(session_factory)
+ headers = people.headers(Persona.OWNER)
+ async with client(gateway) as http:
+ world = World(session_factory, people, "dead-rule", http, gateway)
+ path = f"/gateway/agents/{await world.agent()}/addressing-policy"
+ dead = await http.put(
+ path,
+ json={
+ "policy": {
+ "rules": [
+ {"users": [], "agents": [], "owner": True},
+ {"rooms": [], "owner": True},
+ ]
+ }
+ },
+ headers=headers,
+ )
+ kept = (
+ await http.get(path.removesuffix("/addressing-policy"), headers=headers)
+ ).json()
+ owner_only = await http.put(
+ path,
+ json={"policy": {"rules": [{"users": [], "agents": [], "owner": True}]}},
+ headers=headers,
+ )
+ assert dead.status_code == 422, dead.text
+ assert "rule 2: it names no rooms" in dead.json()["detail"]
+ assert "rule 1" not in dead.json()["detail"]
+ assert kept["addressing_policy"] is None
+ assert owner_only.status_code == 200, owner_only.text
diff --git a/core/tests/switch_core/gateway/test_service_connections.py b/core/tests/switch_core/gateway/test_service_connections.py
index 53fd0b66c..0a7a00765 100644
--- a/core/tests/switch_core/gateway/test_service_connections.py
+++ b/core/tests/switch_core/gateway/test_service_connections.py
@@ -148,6 +148,9 @@ class TestConnections:
28800,
)
assert atlassian["loopback_ports"] == [39231, 39232, 39233, 39234, 39235]
+ # Their own connection is theirs to disconnect; there is nothing to
+ # disconnect where they have none.
+ assert (github["can_revoke"], asana["can_revoke"]) == (True, False)
async def test_disconnecting_deletes_grants_and_revokes_the_sign_in(
self, harness: Harness, vendor: FakeVendor
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 a2766f7df..de5a7be86 100644
--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py
+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py
@@ -40,6 +40,7 @@ from switch_core.connections.broker import ServiceBroker
from switch_core.connections.loader import CATALOG
from switch_core.connections.sign_in_flows import SignInFlows
from switch_core.db.models import (
+ TENANT_ZERO_ID,
Agent,
ApiKey,
AuditEvent,
@@ -1500,26 +1501,33 @@ 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_admin_cannot_be_demoted(
- self, session_factory: async_sessionmaker[AsyncSession]
+ @pytest.mark.parametrize("another_admin", [True, False])
+ async def test_an_admin_steps_down_while_another_admin_remains(
+ self, session_factory: async_sessionmaker[AsyncSession], another_admin: bool
) -> None:
+ """Their own row is theirs to change; the last admin of all stays."""
await _make_tenant(session_factory, TENANT_A)
admin_id = await _make_member(
- session_factory, name="sole-admin", tenant_id=TENANT_A, role="admin"
+ session_factory, name="stepping-down", tenant_id=TENANT_A, role="admin"
+ )
+ await _make_member(
+ session_factory,
+ name="other",
+ tenant_id=TENANT_A,
+ role="admin" if another_admin else "member",
)
- 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:
response = await client.patch(
f"/tenants/{TENANT_A}/members/{admin_id}", json={"role": "member"}
)
- assert response.status_code == 409
-
+ assert response.status_code == (200 if another_admin else 409), response.text
async with session_factory() as session:
membership = await session.get(TenantMember, (TENANT_A, admin_id))
assert membership is not None
- assert membership.role == "admin"
+ assert membership.role == ("member" if another_admin else "admin")
async def test_an_admin_can_be_demoted_when_another_admin_remains(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -1542,22 +1550,32 @@ class TestMemberRoutes:
assert response.status_code == 200, response.text
assert response.json()["role"] == "member"
- async def test_the_last_admin_cannot_be_removed(
- self, session_factory: async_sessionmaker[AsyncSession]
+ @pytest.mark.parametrize("another_admin", [True, False])
+ async def test_an_admin_leaves_while_another_admin_remains(
+ self, session_factory: async_sessionmaker[AsyncSession], another_admin: bool
) -> None:
+ """As with their own role. Having left, the session no longer names
+ the workspace: it is re-minted onto none, their only one gone."""
await _make_tenant(session_factory, TENANT_A)
admin_id = await _make_member(
- session_factory, name="undeletable-admin", tenant_id=TENANT_A, role="admin"
+ session_factory, name="leaving", tenant_id=TENANT_A, role="admin"
)
- token = _token(admin_id, "[email protected]", TENANT_A)
+ await _make_member(
+ session_factory,
+ name="other",
+ tenant_id=TENANT_A,
+ role="admin" if another_admin else "member",
+ )
+ 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/{admin_id}")
- assert response.status_code == 409
-
+ assert response.status_code == (200 if another_admin else 409), response.text
async with session_factory() as session:
- assert await session.get(TenantMember, (TENANT_A, admin_id)) is not None
+ left = await session.get(TenantMember, (TENANT_A, admin_id)) is None
+ assert left is another_admin
+ assert ("set-cookie" in response.headers) is another_admin
async def test_removing_a_member_deletes_their_membership(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -1825,6 +1843,8 @@ class TestCurrentTenantRoute:
"organization_role": None,
"organization_id": None,
"administers": False,
+ "can_delete": False,
+ "can_manage_data_protection": False,
}
@pytest.mark.parametrize(
@@ -1913,6 +1933,11 @@ class TestOrganizationAdmins:
"organization_role": "org_admin",
"organization_id": organization_id,
"administers": True,
+ # An organization admin administers it, but deletes it, erases
+ # people and sets messages to be deleted only by an admin
+ # membership of their own.
+ "can_delete": False,
+ "can_manage_data_protection": False,
}
async def test_an_org_admin_is_offered_and_may_switch_to_every_workspace_of_it(
@@ -2050,6 +2075,28 @@ class TestOrganizationAdmins:
assert last.status_code == 409, last.text
assert last.json()["detail"] == "Cannot demote the last admin"
+ async def test_an_org_admin_cannot_remove_the_workspaces_last_admin(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ 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"}
+ )
+ last_id = await _make_member(
+ session_factory, name="ws-admin", 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.delete(f"/tenants/{TENANT_A}/members/{last_id}")
+
+ assert response.status_code == 409, response.text
+ assert response.json()["detail"] == "Cannot remove the last admin"
+ async with session_factory() as session:
+ assert await session.get(TenantMember, (TENANT_A, last_id)) is not None
+
@pytest.mark.parametrize("method", ["patch", "delete"])
async def test_a_workspace_cannot_demote_or_remove_an_org_admin(
self, session_factory: async_sessionmaker[AsyncSession], method: str
@@ -2090,6 +2137,101 @@ class TestOrganizationAdmins:
membership = await session.get(TenantMember, (TENANT_A, admin_id))
assert membership is not None and membership.role == "admin"
+ @pytest.mark.parametrize("caller", ["ws-admin", "member", "org-admin"])
+ async def test_each_member_row_says_what_the_caller_may_do_with_it(
+ self, session_factory: async_sessionmaker[AsyncSession], caller: str
+ ) -> None:
+ """An admin may change and remove anyone, themselves included, but an
+ organization admin, whose standing comes from the organization; a
+ transfer may go to anyone with a membership here but the caller."""
+ org_admin_id = await _make_unaffiliated_user(
+ session_factory, name="org-admin", role="user"
+ )
+ org_admin_member_id = await _make_unaffiliated_user(
+ session_factory, name="org-admin-member", role="user"
+ )
+ await self._organization_of(
+ session_factory,
+ TENANT_A,
+ members={org_admin_id: "org_admin", org_admin_member_id: "org_admin"},
+ )
+ async with session_factory() as session:
+ session.add(
+ TenantMember(
+ tenant_id=TENANT_A, user_id=org_admin_member_id, role="member"
+ )
+ )
+ await session.commit()
+ ids = {
+ "ws-admin": await _make_member(
+ session_factory, name="ws-admin", tenant_id=TENANT_A, role="admin"
+ ),
+ "member": await _make_member(
+ session_factory, name="member", tenant_id=TENANT_A, role="member"
+ ),
+ "org-admin": org_admin_id,
+ "org-admin-member": org_admin_member_id,
+ }
+ token = _token(ids[caller], f"{caller}@example.invalid", 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
+ rows = {
+ row["name"]: (
+ row["can_change_role"],
+ row["can_remove"],
+ row["can_receive_transfer"],
+ )
+ for row in response.json()
+ }
+ administers = caller != "member"
+ expected = {
+ "ws-admin": (administers, administers, True),
+ "member": (administers, administers, True),
+ # Listed through the organization, with no membership here.
+ "org-admin": (False, False, False),
+ "org-admin-member": (False, False, True),
+ }
+ # An admin's own row is theirs to change too; nobody hands themselves
+ # anything.
+ change, remove, _ = expected[caller]
+ expected[caller] = (change, remove, False)
+ assert rows == expected
+
+
+class TestWorkspaceDeletionFlag:
+ async def test_an_admin_member_is_told_they_may_delete_it(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _make_tenant(session_factory, TENANT_A)
+ admin_id = await _make_member(
+ session_factory, name="ws-admin", 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.get("/tenants/current")
+
+ assert response.status_code == 200, response.text
+ assert response.json()["can_delete"] is True
+
+ async def test_nobody_is_told_they_may_delete_the_default_workspace(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ admin_id = await _make_member(
+ session_factory, name="zero-admin", tenant_id=TENANT_ZERO_ID, role="admin"
+ )
+ token = _token(admin_id, "[email protected]", TENANT_ZERO_ID)
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.get("/tenants/current")
+
+ assert response.status_code == 200, response.text
+ assert response.json()["administers"] is True
+ assert response.json()["can_delete"] is False
+
class TestUsageRoute:
async def _spend(
diff --git a/core/tests/switch_core/management/test_gateway_routes.py b/core/tests/switch_core/management/test_gateway_routes.py
index 6daa787ab..15c76350f 100644
--- a/core/tests/switch_core/management/test_gateway_routes.py
+++ b/core/tests/switch_core/management/test_gateway_routes.py
@@ -1111,3 +1111,49 @@ class TestMachineNameAndDescription:
assert response.status_code == 422, response.text
assert response.json()["error"]["code"] == "validation_error"
assert listed.json()[0]["name"] == "laptop"
+
+
+class TestWhatTheOwnerMayDo:
+ async def test_each_machine_and_managed_agent_says_what_its_owner_may_do(
+ self, harness: Harness
+ ) -> None:
+ ada = await add_member(harness.session_factory, "ada")
+ cookies = cookies_for(ada)
+ async with harness.client() as client:
+ controller = await enroll_console(harness, client, ada)
+ await report_status(client, controller, 1, providers=[provider("claude")])
+ created = await create_managed_agent(
+ client, ada, name="reviewer", controller_id=controller.controller_id
+ )
+ agent_id = created.json()["agent_id"]
+
+ [machine] = (
+ await client.get("/gateway/management/controllers", cookies=cookies)
+ ).json()
+ [listed] = (
+ await client.get("/gateway/management/agents", cookies=cookies)
+ ).json()
+ single = (
+ await client.get(
+ f"/gateway/management/agents/{agent_id}", cookies=cookies
+ )
+ ).json()
+ await client.delete(
+ f"/gateway/management/controllers/{controller.controller_id}",
+ cookies=cookies,
+ )
+ [revoked] = (
+ await client.get("/gateway/management/controllers", cookies=cookies)
+ ).json()
+
+ assert (created.json()["can_edit"], created.json()["can_delete"]) == (
+ True,
+ True,
+ )
+ assert (machine["can_edit"], machine["can_remove"]) == (True, True)
+ assert (listed["can_edit"], listed["can_delete"]) == (True, True)
+ assert (single["can_edit"], single["can_delete"]) == (True, True)
+ # Still the caller's to rename and remove: removing it again does
+ # nothing, which its `revoked_at` says.
+ assert revoked["revoked_at"] is not None
+ assert (revoked["can_edit"], revoked["can_remove"]) == (True, True)
diff --git a/core/tests/switch_core/test_addressing.py b/core/tests/switch_core/test_addressing.py
index 991afabbd..824d8c843 100644
--- a/core/tests/switch_core/test_addressing.py
+++ b/core/tests/switch_core/test_addressing.py
@@ -8,6 +8,7 @@ from switch_core.addressing import (
AddressingRule,
can_address,
default_agent_policy,
+ never_allows,
owner_and_owner_agents_policy,
owner_only_policy,
parse_policy,
@@ -867,3 +868,45 @@ class TestPlatformSenderKind:
)
is False
)
+
+
+class TestNeverAllows:
+ @pytest.mark.parametrize(
+ "rule",
+ [
+ AddressingRule(rooms=[]),
+ AddressingRule(room_groups=[]),
+ AddressingRule(users=[], agents=[]),
+ ],
+ )
+ def test_a_rule_that_can_never_let_anyone_in_says_why(
+ self, rule: AddressingRule
+ ) -> None:
+ assert never_allows(rule) is not None
+
+ @pytest.mark.parametrize(
+ "rule",
+ [
+ AddressingRule(),
+ AddressingRule(users=[], agents=[], owner=True),
+ AddressingRule(users=[], agents=[], owner_agents=True),
+ AddressingRule(users=[], agents=[], platform=True),
+ AddressingRule(users=["u-1"], agents=[]),
+ AddressingRule(rooms=["r-1"], users=[], agents=["a-1"]),
+ ],
+ )
+ def test_a_rule_that_lets_someone_in_somewhere_is_fine(
+ self, rule: AddressingRule
+ ) -> None:
+ assert never_allows(rule) is None
+
+ def test_none_of_the_built_in_policies_has_one(self) -> None:
+ for policy in (
+ owner_only_policy([]),
+ owner_and_owner_agents_policy(),
+ default_agent_policy(),
+ platform_allowed_policy(),
+ ):
+ assert [never_allows(rule) for rule in policy.rules] == [None] * len(
+ policy.rules
+ )
diff --git a/core/tests/switch_core/test_authz.py b/core/tests/switch_core/test_authz.py
index d0dfef579..bef6b3a8b 100644
--- a/core/tests/switch_core/test_authz.py
+++ b/core/tests/switch_core/test_authz.py
@@ -6,11 +6,16 @@ import pytest
from switch_core.authz import (
Principal,
+ admin_by_own_membership,
administers_tenant,
can,
+ can_change_workspace_member,
+ can_delete_api_key,
can_delete_room_document,
+ can_delete_workspace,
can_manage,
can_unlink_from_room,
+ owns,
require,
require_manage,
require_visibility_change,
@@ -241,3 +246,62 @@ class TestRequireVisibilityChange:
owner = Principal("u-owner", False)
require_visibility_change(owner, self._open(), "private", "private", "package")
require_visibility_change(ADMIN, self._open(), "private", "private", "package")
+
+
+class TestOwns:
+ def test_only_the_owner_owns_it_whatever_their_role(self) -> None:
+ assert owns(ALICE, "u-alice")
+ assert not owns(ADMIN, "u-alice")
+
+ def test_a_missing_owner_matches_nobody(self) -> None:
+ assert not owns(ANON, None)
+
+
+class TestCanChangeWorkspaceMember:
+ def test_an_admin_may_change_a_member_themselves_included(self) -> None:
+ assert can_change_workspace_member(
+ administers=True, member_is_organization_admin=False
+ )
+
+ def test_a_member_may_not(self) -> None:
+ assert not can_change_workspace_member(
+ administers=False, member_is_organization_admin=False
+ )
+
+ def test_nobody_may_change_an_organization_admins_row_here(self) -> None:
+ assert not can_change_workspace_member(
+ administers=True, member_is_organization_admin=True
+ )
+
+
+class TestAdminByOwnMembership:
+ def test_only_an_admin_membership_is(self) -> None:
+ assert admin_by_own_membership("admin")
+ assert not admin_by_own_membership("member")
+ assert not admin_by_own_membership(None)
+
+
+class TestCanDeleteWorkspace:
+ def test_an_admin_member_may_delete_it(self) -> None:
+ assert can_delete_workspace(tenant_role="admin", is_default=False)
+
+ @pytest.mark.parametrize("tenant_role", ["member", None])
+ def test_no_one_else_may_whatever_else_they_administer(
+ self, tenant_role: str | None
+ ) -> None:
+ # An organization admin, or the operator, holds no admin row here.
+ assert not can_delete_workspace(tenant_role=tenant_role, is_default=False)
+
+ def test_nobody_may_delete_the_default_workspace(self) -> None:
+ assert not can_delete_workspace(tenant_role="admin", is_default=True)
+
+
+class TestCanDeleteApiKey:
+ def test_the_owner_may_delete_their_own_key(self) -> None:
+ assert can_delete_api_key(ALICE, "u-alice", an_agent_signs_in_with_it=False)
+
+ def test_not_one_an_agent_still_signs_in_with(self) -> None:
+ assert not can_delete_api_key(ALICE, "u-alice", an_agent_signs_in_with_it=True)
+
+ def test_not_someone_elses_even_as_an_admin(self) -> None:
+ assert not can_delete_api_key(ADMIN, "u-alice", an_agent_signs_in_with_it=False)
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index 26ab7cc8e..0cf8b4bc3 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -1225,6 +1225,12 @@ export interface Member {
// An organization admin with no membership of their own here, listed
// because the organization makes them an admin of every workspace.
via_organization: boolean;
+ // What you may do with this member, as the server decides it: change their
+ // role or remove them (an admin, never on your own row or an organization
+ // admin's), and hand them something you own.
+ can_change_role: boolean;
+ can_remove: boolean;
+ can_receive_transfer: boolean;
}
export async function fetchMembers(tenantId: string): Promise<Member[]> {
@@ -1296,6 +1302,12 @@ export interface OrganizationMember {
* taking away what they held in workspaces they were in only as an
* organization admin. */
warning: string | null;
+ /** What you may do with them, as the server decides it: never on your own
+ * row; making them Org Admin not where the members come from account
+ * settings Switch cannot change; removing them as an Org Admin only. */
+ can_change_role: boolean;
+ can_grant_org_admin: boolean;
+ can_remove: boolean;
}
export interface OrganizationAuditEvent {
diff --git a/gateway/src/pages/organization/OrganizationMembersSection.tsx b/gateway/src/pages/organization/OrganizationMembersSection.tsx
index 92b210baf..8b7f7e34b 100644
--- a/gateway/src/pages/organization/OrganizationMembersSection.tsx
+++ b/gateway/src/pages/organization/OrganizationMembersSection.tsx
@@ -2,6 +2,7 @@ import DeleteOutline from "@mui/icons-material/DeleteOutline";
import {
Alert,
Button,
+ Chip,
CircularProgress,
IconButton,
MenuItem,
@@ -75,9 +76,10 @@ function takePendingChange(organizationId: string): MemberChange | null {
}
/** Everyone in the organization, across its workspaces, and their role in it.
- * The server refuses demoting or removing the last organization admin, and
- * removing someone still in one of its workspaces, naming them; its message
- * is shown as is. Demoting or removing an admin also takes away their keys and
+ * Each row offers what the server says the caller may do with it: never their
+ * own row, which another organization admin changes. The server refuses
+ * demoting or removing the last organization admin, and removing someone
+ * still in one of its workspaces, naming them; its message is shown as is. Demoting or removing an admin also takes away their keys and
* connections in workspaces they were in only as an admin; what could not be
* revoked at a vendor comes back as a warning, shown too. */
export default function OrganizationMembersSection({
@@ -124,9 +126,14 @@ export default function OrganizationMembersSection({
const { warning } = await make(change);
setActionWarning(warning);
onChanged();
+ if (change.userId === selfId) {
+ // Your own role decides what this page offers you. Stepping down or
+ // leaving takes away reading these members at all, and may move the
+ // session to another workspace; the page follows it.
+ await refresh();
+ if ("remove" in change || change.role !== "org_admin") return;
+ }
await refetch();
- // Your own role decides what this page offers you.
- if (change.userId === selfId) await refresh();
} catch (err) {
// Once only: a change made again after the sign-in that still asks
// for one is shown as the failure it is, not sent round again. The
@@ -169,33 +176,37 @@ export default function OrganizationMembersSection({
field: "role",
headerName: "Organization role",
width: 170,
- renderCell: ({ row }) => (
- <Select
- size="small"
- value={row.role}
- disabled={busy !== null}
- onChange={(e) =>
- act({ userId: row.user_id, role: e.target.value as OrganizationRole })
- }
- aria-label={`Organization role for ${row.email}`}
- sx={{ fontSize: "0.875rem" }}
- >
- {(Object.keys(ROLE_LABELS) as OrganizationRole[]).map((role) => (
- <MenuItem
- key={role}
- value={role}
- disabled={
- fromDirectory &&
- !directoryTakesChanges &&
- role === "org_admin" &&
- row.role !== "org_admin"
- }
- >
- {ROLE_LABELS[role]}
- </MenuItem>
- ))}
- </Select>
- ),
+ renderCell: ({ row }) =>
+ row.can_change_role ? (
+ <Select
+ size="small"
+ value={row.role}
+ disabled={busy !== null}
+ onChange={(e) =>
+ act({ userId: row.user_id, role: e.target.value as OrganizationRole })
+ }
+ aria-label={`Organization role for ${row.email}`}
+ sx={{ fontSize: "0.875rem" }}
+ >
+ {(Object.keys(ROLE_LABELS) as OrganizationRole[]).map((role) => (
+ <MenuItem
+ key={role}
+ value={role}
+ disabled={
+ role === "org_admin" && row.role !== "org_admin" && !row.can_grant_org_admin
+ }
+ >
+ {ROLE_LABELS[role]}
+ </MenuItem>
+ ))}
+ </Select>
+ ) : (
+ <Chip
+ label={ROLE_LABELS[row.role]}
+ size="small"
+ color={row.role === "org_admin" ? "primary" : "default"}
+ />
+ ),
},
{
field: "created_at",
@@ -209,27 +220,35 @@ export default function OrganizationMembersSection({
width: 60,
sortable: false,
renderCell: ({ row }) =>
- row.user_id === selfId ? null : (
- <Tooltip title="Remove from organization">
+ row.can_remove ? (
+ <Tooltip
+ title={row.user_id === selfId ? "Leave organization" : "Remove from organization"}
+ >
<span>
<IconButton
size="small"
disabled={busy !== null}
onClick={() => act({ userId: row.user_id, remove: true })}
- aria-label={`Remove ${row.email} from the organization`}
+ aria-label={
+ row.user_id === selfId
+ ? "Leave this organization"
+ : `Remove ${row.email} from the organization`
+ }
>
<DeleteOutline fontSize="small" />
</IconButton>
</span>
</Tooltip>
- ),
+ ) : null,
},
],
- [act, busy, directoryTakesChanges, fromDirectory, selfId],
+ [act, busy, selfId],
);
- // The operator restores an admin and nothing more: removing a member is
- // refused to them, so there is nothing to offer.
- const shown = asOperator ? columns.filter((c) => c.field !== "actions") : columns;
+ // Nothing to offer when nobody may be removed, as for the operator, who
+ // restores an admin and nothing more.
+ const shown = (members ?? []).some((m) => m.can_remove)
+ ? columns
+ : columns.filter((c) => c.field !== "actions");
return (
<Stack spacing={1.5}>
diff --git a/gateway/src/pages/organization/OrganizationPage.test.tsx b/gateway/src/pages/organization/OrganizationPage.test.tsx
index 0caca9d27..85ccfa73f 100644
--- a/gateway/src/pages/organization/OrganizationPage.test.tsx
+++ b/gateway/src/pages/organization/OrganizationPage.test.tsx
@@ -92,7 +92,7 @@ describe("OrganizationPage", () => {
"GET /organizations/current": { id: "o1", slug: "acme", name: "Acme Inc", role: "org_admin", members_from_directory: false },
"GET /organizations/current/workspaces": [workspace("t1", "Acme")],
"GET /organizations/current/members": [
- { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01" },
+ { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01", can_change_role: true, can_grant_org_admin: true, can_remove: true },
],
"GET /organizations/current/audit-events": [
{
@@ -237,6 +237,9 @@ describe("OrganizationPage", () => {
role: "org_admin",
created_at: "2026-01-01",
warning: null,
+ can_change_role: true,
+ can_grant_org_admin: true,
+ can_remove: true,
};
answer({
"GET /organizations/current": { id: "o1", slug: "acme", name: "Acme Inc", role: "org_admin", members_from_directory: false },
@@ -304,8 +307,10 @@ describe("OrganizationPage", () => {
});
const members = [
- { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01" },
+ { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01", can_change_role: true, can_remove: false },
];
+ // The operator restoring an admin may change roles and remove nobody; who may
+ // be made Org Admin follows where the members come from.
const operatorRoutes = (membersAnswer: unknown, fromDirectory = false) => ({
"GET /organizations/current": {
id: "o1",
@@ -315,7 +320,9 @@ describe("OrganizationPage", () => {
members_from_directory: fromDirectory,
},
"GET /organizations/current/workspaces": [workspace("t1", "Acme")],
- "GET /organizations/current/members": membersAnswer,
+ "GET /organizations/current/members": Array.isArray(membersAnswer)
+ ? membersAnswer.map((m) => ({ ...m, can_grant_org_admin: !fromDirectory }))
+ : membersAnswer,
"GET /organizations/current/issues": new Refusal(403, "Only an organization admin may do this"),
});
@@ -376,8 +383,8 @@ describe("OrganizationPage", () => {
},
"GET /organizations/current/workspaces": [workspace("t1", "Acme")],
"GET /organizations/current/members": [
- { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01" },
- { user_id: "u3", name: "Cy", email: "[email protected]", role: "org_admin", created_at: "2026-01-01" },
+ { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01", can_change_role: true, can_grant_org_admin: false, can_remove: true },
+ { user_id: "u3", name: "Cy", email: "[email protected]", role: "org_admin", created_at: "2026-01-01", can_change_role: true, can_grant_org_admin: false, can_remove: true },
],
"GET /organizations/current/audit-events": [],
"GET /organizations/current/issues": [],
@@ -398,7 +405,7 @@ describe("OrganizationPage", () => {
describe("where changes go to the organization's account settings", () => {
const originalLocation = window.location;
- const bob = { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01" };
+ const bob = { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01", can_change_role: true, can_grant_org_admin: true, can_remove: true };
const routes = (patchAnswer: unknown) => ({
"GET /organizations/current": {
id: "o1",
@@ -578,7 +585,7 @@ describe("OrganizationPage", () => {
"GET /organizations/current": { id: "o1", slug: "acme", name: "Acme Inc", role: "org_admin", members_from_directory: false },
"GET /organizations/current/workspaces": [workspace("t1", "Acme")],
"GET /organizations/current/members": [
- { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01" },
+ { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01", can_change_role: true, can_grant_org_admin: true, can_remove: true },
],
"GET /organizations/current/audit-events": [],
"GET /organizations/current/issues": [],
@@ -623,7 +630,7 @@ describe("OrganizationPage", () => {
"GET /organizations/current": { id: "o1", slug: "acme", name: "Acme Inc", role: "org_admin", members_from_directory: false },
"GET /organizations/current/workspaces": [workspace("t1", "Acme")],
"GET /organizations/current/members": [
- { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01" },
+ { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01", can_change_role: true, can_grant_org_admin: true, can_remove: true },
],
"GET /organizations/current/audit-events": [],
"GET /organizations/current/issues": [],
diff --git a/gateway/src/pages/workspace/MembersSection.test.tsx b/gateway/src/pages/workspace/MembersSection.test.tsx
index 08740200f..7afa51f01 100644
--- a/gateway/src/pages/workspace/MembersSection.test.tsx
+++ b/gateway/src/pages/workspace/MembersSection.test.tsx
@@ -1,8 +1,9 @@
-import { cleanup, render, screen } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import MembersSection from "./MembersSection";
-vi.mock("../../data/AuthContext", () => ({ useAuth: () => ({ refresh: vi.fn() }) }));
+const refresh = vi.hoisted(() => vi.fn());
+vi.mock("../../data/AuthContext", () => ({ useAuth: () => ({ refresh }) }));
vi.mock("../../components/DataTable", () => import("../../test/FakeDataTable"));
@@ -13,6 +14,9 @@ const member = (overrides: Record<string, unknown>) => ({
created_at: "2026-01-01",
organization_role: "member",
via_organization: false,
+ can_change_role: false,
+ can_remove: false,
+ can_receive_transfer: true,
...overrides,
});
@@ -22,6 +26,65 @@ describe("MembersSection", () => {
vi.unstubAllGlobals();
});
+ it("offers each row only what the server says the caller may do", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(
+ JSON.stringify([
+ member({ user_id: "u1", name: "Me", email: "[email protected]", role: "admin" }),
+ member({
+ user_id: "u2",
+ name: "Bob",
+ email: "[email protected]",
+ can_change_role: true,
+ can_remove: true,
+ }),
+ ]),
+ ),
+ ),
+ );
+
+ render(<MembersSection tenantId="t1" selfId="u1" />);
+
+ expect(await screen.findByLabelText("Role for [email protected]")).toBeTruthy();
+ expect(screen.getByLabelText("Remove [email protected]")).toBeTruthy();
+ // Your own row, where the server says no: as the last admin, say.
+ expect(screen.queryByLabelText("Role for [email protected]")).toBeNull();
+ expect(screen.queryByLabelText("Leave this workspace")).toBeNull();
+ });
+
+ it("lets an admin leave from their own row, then follows the session", async () => {
+ refresh.mockReset();
+ const fetchMock = vi.fn(async (_url: string, init?: RequestInit) =>
+ init?.method === "DELETE"
+ ? new Response(JSON.stringify({ ok: true, warning: null }))
+ : new Response(
+ JSON.stringify([
+ member({
+ user_id: "u1",
+ name: "Me",
+ email: "[email protected]",
+ role: "admin",
+ can_change_role: true,
+ can_remove: true,
+ }),
+ ]),
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ render(<MembersSection tenantId="t1" selfId="u1" />);
+ expect(await screen.findByLabelText("Role for [email protected]")).toBeTruthy();
+ fireEvent.click(screen.getByLabelText("Leave this workspace"));
+
+ await waitFor(() => expect(refresh).toHaveBeenCalledTimes(1));
+ const reads = fetchMock.mock.calls.filter(([, init]) => init?.method !== "DELETE");
+ // Read once, and not again for a workspace the session has moved off.
+ expect(reads).toHaveLength(1);
+ });
+
it("shows organization admins read-only, and the rest manageable", async () => {
vi.stubGlobal(
"fetch",
@@ -29,7 +92,13 @@ describe("MembersSection", () => {
async () =>
new Response(
JSON.stringify([
- member({ user_id: "u2", name: "Bob", email: "[email protected]" }),
+ member({
+ user_id: "u2",
+ name: "Bob",
+ email: "[email protected]",
+ can_change_role: true,
+ can_remove: true,
+ }),
member({
user_id: "u3",
name: "Cy",
@@ -50,7 +119,7 @@ describe("MembersSection", () => {
),
);
- render(<MembersSection tenantId="t1" selfId="u1" canAdmin />);
+ render(<MembersSection tenantId="t1" selfId="u1" />);
expect(await screen.findByText("Org Admin, via organization")).toBeTruthy();
expect(screen.getByText("Admin · Org Admin")).toBeTruthy();
diff --git a/gateway/src/pages/workspace/MembersSection.tsx b/gateway/src/pages/workspace/MembersSection.tsx
index d223a9af8..99cfd3cd2 100644
--- a/gateway/src/pages/workspace/MembersSection.tsx
+++ b/gateway/src/pages/workspace/MembersSection.tsx
@@ -29,18 +29,16 @@ type MemberRow = Member & { id: string };
interface Props {
tenantId: string;
selfId: string;
- canAdmin: boolean;
}
-/** 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 }: Props) {
+/** Each row offers what the server says the caller may do with it: an admin
+ * may change and remove every member, other admins included, but not their
+ * own row (another admin steps them down) and not an organization admin's,
+ * whose role comes from the organization and is changed on its page. One
+ * with no membership of their own here is listed "via the organization". The
+ * server refuses to demote or remove the last admin when asked — its message
+ * is shown as is. */
+export default function MembersSection({ tenantId, selfId }: Props) {
const load = useCallback(() => fetchMembers(tenantId), [tenantId]);
const { data: members, error, loading, refetch } = useLoad(load);
const [actionError, setActionError] = useState<string | null>(null);
@@ -48,11 +46,17 @@ export default function MembersSection({ tenantId, selfId, canAdmin }: Props) {
const { refresh } = useAuth();
const act = useCallback(
- async (userId: string, action: () => Promise<unknown>) => {
+ async (userId: string, action: () => Promise<unknown>, leaving = false) => {
setBusy(userId);
setActionError(null);
try {
await action();
+ if (leaving) {
+ // The session is on another workspace now, or none, and the page
+ // follows it rather than reading this one's members again.
+ await refresh();
+ return;
+ }
await refetch();
// Your own role decides what this page offers you.
if (userId === selfId) await refresh();
@@ -66,7 +70,6 @@ export default function MembersSection({ tenantId, selfId, canAdmin }: Props) {
);
const columns = useMemo<GridColDef<MemberRow>[]>(() => {
- const mayManage = (row: MemberRow) => canAdmin && row.organization_role !== "org_admin";
const roles: TenantRole[] = ["admin", "member"];
return [
{
@@ -82,7 +85,7 @@ export default function MembersSection({ tenantId, selfId, canAdmin }: Props) {
headerName: "Role",
width: 210,
renderCell: ({ row }) =>
- mayManage(row) ? (
+ row.can_change_role ? (
<Select
size="small"
value={row.role}
@@ -140,14 +143,20 @@ export default function MembersSection({ tenantId, selfId, canAdmin }: Props) {
width: 60,
sortable: false,
renderCell: ({ row }) =>
- mayManage(row) && row.user_id !== selfId ? (
- <Tooltip title="Remove from workspace">
+ row.can_remove ? (
+ <Tooltip title={row.user_id === selfId ? "Leave workspace" : "Remove from workspace"}>
<span>
<IconButton
size="small"
disabled={busy !== null}
- onClick={() => act(row.user_id, () => removeMember(tenantId, row.user_id))}
- aria-label={`Remove ${row.email}`}
+ onClick={() =>
+ act(
+ row.user_id,
+ () => removeMember(tenantId, row.user_id),
+ row.user_id === selfId,
+ )
+ }
+ aria-label={row.user_id === selfId ? "Leave this workspace" : `Remove ${row.email}`}
>
<DeleteOutline fontSize="small" />
</IconButton>
@@ -156,7 +165,7 @@ export default function MembersSection({ tenantId, selfId, canAdmin }: Props) {
) : null,
},
];
- }, [act, busy, canAdmin, selfId, tenantId]);
+ }, [act, busy, selfId, tenantId]);
return (
<Stack spacing={1.5}>
diff --git a/gateway/src/pages/workspace/WorkspacePage.tsx b/gateway/src/pages/workspace/WorkspacePage.tsx
index f40b6762a..ac3e54118 100644
--- a/gateway/src/pages/workspace/WorkspacePage.tsx
+++ b/gateway/src/pages/workspace/WorkspacePage.tsx
@@ -20,11 +20,7 @@ export default function WorkspacePage() {
</Typography>
</Stack>
<Stack spacing={4}>
- <MembersSection
- tenantId={tenant.id}
- selfId={session.user.id}
- canAdmin={canAdminTenant}
- />
+ <MembersSection tenantId={tenant.id} selfId={session.user.id} />
{canAdminTenant ? (
<InvitationsSection
tenantId={tenant.id}