Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(security): multi-tenant security hardening
Petr Bauchea787c152f33
diff --git a/.env.example b/.env.exampleindex 0ac052716..765399948 100644--- a/.env.example+++ b/.env.example@@ -132,8 +132,19 @@ ID_SERVER_NAME=localhost# ── Agent registration ───────────────────────────────────────────────────────AGENT_REGISTRATION_TOKEN=-# ── Gateway auth ─────────────────────────────────────────────────────────────+# ── Server keys ──────────────────────────────────────────────────────────────+# Master keys every signing and encryption key is derived from:+# "<id>:<secret>" comma-separated, current first, secrets of 32+ characters.+# `just init-env` generates one. To rotate, put a new entry first and keep the+# old one until a boot has re-encrypted stored values; see+# docs/old/key-rotation.md.+SECRET_KEYS=+# Legacy: the single secret used before SECRET_KEYS. An existing .env keeps its+# value through the upgrade so sessions and stored credentials keep working;+# remove it once a boot has re-encrypted them. A new .env leaves it empty.JWT_SECRET_KEY=++# ── Gateway auth ─────────────────────────────────────────────────────────────GATEWAY_ADMIN_PASSWORD=@@ -221,10 +232,18 @@ MATTERMOST_USER_PASSWORD=# connection_config), never in global config.+# ── Outbound URLs ────────────────────────────────────────────────────────────+# Private hosts Switch may reach at a URL a tenant or agent supplied (a+# Mattermost server, an OpenCode server, an agent icon): hostnames and CIDRs,+# comma-separated. Every other non-public address is refused. `localhost`+# covers the local-dev Mattermost and an OpenCode server on this machine; the+# standalone compose always adds `mattermost` to whatever is listed here.+OUTBOUND_ALLOWED_PRIVATE_HOSTS=localhost+# ── OIDC (optional — MCP OAuth token validation; bring your own IdP) ─────────# Enable OAuth/OIDC token auth on the MCP server by pointing at any standards# compliant IdP. Leave unset to use API-token (bearer) auth only, which is the-# default for the local stack.+# default for the local stack. OAUTH_AUDIENCE is required with the issuer.# OAUTH_ISSUER_URL=https://your-idp.example.com/realms/switch# OAUTH_AUDIENCE=switch# OAUTH_VERIFY_ISSUER=truediff --git a/CLAUDE.md b/CLAUDE.mdindex 2d07f0f39..14a22e975 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -193,6 +193,9 @@ Tests live in `core/tests/switch_core/` mirroring the module structure. Uses pytroles, and how sign-up works (§9a)- `docs/old/multi-tenancy-phase1-db.md` — the Phase 1 database schema as built:tables, per-tenant uniqueness, and how a request's tenant is bound+- `docs/old/key-rotation.md` — the server's keys (`SECRET_KEYS`): what each+ derived key protects, moving a deployment off `JWT_SECRET_KEY`, and the+ rotation runbook- `docs/old/rds-migration.md` — moving a deployment's Postgres to RDS: theproposal and the cutover runbookdiff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.tsindex 943a96b73..d676d944d 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts@@ -10,6 +10,7 @@ const secrets: LocalServerSecrets = {dbRuntimePassword: 'db-runtime-pw',agentRegistrationToken: 'agent-token',jwtSecretKey: 'jwt-key',+ secretKeys: 'console:secret-keys-value',gatewayAdminPassword: 'gw-admin',mattermostAdminPassword: 'mm-admin',mattermostUserPassword: 'mm-user',@@ -55,6 +56,7 @@ describe('buildEnvFile', () => {it('binds the managed stack to loopback and seeds the admin account', () => {expect(vars.SWITCH_BIND_ADDR).toBe('127.0.0.1');+ expect(vars.GATEWAY_COOKIE_SECURE).toBe('false');expect(vars.GATEWAY_ADMIN_EMAIL).toBe('[email protected]');});@@ -63,6 +65,7 @@ describe('buildEnvFile', () => {expect(vars.DB_OWNER_PASSWORD).toBe('db-pw');expect(vars.AGENT_REGISTRATION_TOKEN).toBe('agent-token');expect(vars.JWT_SECRET_KEY).toBe('jwt-key');+ expect(vars.SECRET_KEYS).toBe('console:secret-keys-value');expect(vars.GATEWAY_ADMIN_PASSWORD).toBe('gw-admin');expect(vars.MATTERMOST_ADMIN_PASSWORD).toBe('mm-admin');expect(vars.MATTERMOST_USER_PASSWORD).toBe('mm-user');@@ -117,6 +120,10 @@ describe('buildEnvFile', () => {'DISCORD_APP_CLIENT_SECRET','DISCORD_APP_BOT_TOKEN','DISCORD_APP_APPLICATION_ID',+ // Private hosts Switch may reach at a tenant- or agent-supplied URL. The+ // compose file always allows the bundled Mattermost; a managed stack+ // allows nothing more until its operator says so.+ 'OUTBOUND_ALLOWED_PRIVATE_HOSTS',]);const missing = [...interpolated]@@ -199,6 +206,15 @@ describe('readStackEnv', () => {});});+ it('reads a file written before SECRET_KEYS, leaving the key ring to be filled in', () => {+ const legacy = written.replace(/^SECRET_KEYS=.*$/m, '');++ expect(readStackEnv(legacy)).toEqual({+ kind: 'complete',+ env: { ports, secrets: { ...secrets, secretKeys: null }, version: '1.2.3' },+ });+ });+it('names the owner password a file from before the role split is missing', () => {const legacy = written.replace('DB_USER=switch_app', 'DB_USER=postgres')@@ -305,6 +321,12 @@ describe('keysDisagreeing', () => {);});+ it('names a key ring the copy disagrees with', () => {+ expect(+ keysDisagreeing(written, { ports, secrets: { ...secrets, secretKeys: 'console:other' } })+ ).toEqual(['SECRET_KEYS']);+ });+it('reads DB_PASSWORD as the owner’s in a file written before the role split', () => {const legacy = written.replace('DB_USER=switch_app', 'DB_USER=postgres')diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.tsindex 330f11c69..1bd28cba1 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.ts@@ -67,9 +67,13 @@ export function buildEnvFile(params: LocalServerEnvParams): string {'',`AGENT_REGISTRATION_TOKEN=${secrets.agentRegistrationToken}`,`JWT_SECRET_KEY=${secrets.jwtSecretKey}`,+ `SECRET_KEYS=${secrets.secretKeys}`,`GATEWAY_ADMIN_EMAIL=${LOCAL_SERVER_ADMIN_EMAIL}`,`GATEWAY_ADMIN_PASSWORD=${secrets.gatewayAdminPassword}`,`FRONTEND_BASE_URL=${gatewayUrlFor(ports)}`,+ // The operator UI is served over plain http on localhost, where a browser+ // never sends a Secure cookie back.+ 'GATEWAY_COOKIE_SECURE=false',// Turns the "Open in Switch Console" link into an http(s) one. Discord (and any// other bridge that only linkifies http) renders a raw `switchdash://`// deeplink as dead text, so switch-core rewrites it to point at its own@@ -116,12 +120,16 @@ export function readEnvValue(env: string, key: string): string | null {/*** What another Console needs to run the same stack. `dbRuntimePassword` is- * null for a `.env` from before switch-core split its database roles; the- * caller fills it in (see `withRuntimePassword` in `secret-values.ts`).+ * null for a `.env` from before switch-core split its database roles, and+ * `secretKeys` for one from before `SECRET_KEYS`; the caller fills them in+ * (see `withNewerSecrets` in `secret-values.ts`).*/export type StackEnv = {ports: LocalServerPorts;- secrets: Omit<LocalServerSecrets, 'dbRuntimePassword'> & { dbRuntimePassword: string | null };+ secrets: Omit<LocalServerSecrets, 'dbRuntimePassword' | 'secretKeys'> & {+ dbRuntimePassword: string | null;+ secretKeys: string | null;+ };version: string | null;};@@ -198,6 +206,7 @@ export function keysDisagreeing(const expected = new Map<string, string>();for (const [field, key] of PORT_KEYS) expected.set(key, String(copy.ports[field]));for (const [field, key] of SECRET_KEYS) expected.set(key, copy.secrets[field]);+ expected.set('SECRET_KEYS', copy.secrets.secretKeys);// Which password `DB_PASSWORD` is depends on the layout that wrote the file.if (readEnvValue(env, 'DB_OWNER_PASSWORD') !== null) {expected.set('DB_OWNER_PASSWORD', copy.secrets.dbPassword);@@ -244,7 +253,11 @@ export function readStackEnv(env: string): StackEnvReading {kind: 'complete',env: {ports: ports as LocalServerPorts,- secrets: { ...(plain as Record<PlainSecret, string>), ...database },+ secrets: {+ ...(plain as Record<PlainSecret, string>),+ ...database,+ secretKeys: readEnvValue(env, 'SECRET_KEYS'),+ },version: readEnvValue(env, 'SWITCH_VERSION'),},};diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-shared-host.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-shared-host.test.tsindex 5f21634c1..748bcb941 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-shared-host.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-shared-host.test.ts@@ -111,6 +111,7 @@ const hostSecrets: LocalServerSecrets = {dbRuntimePassword: 'host-runtime-pw',agentRegistrationToken: 'host-agent-token',jwtSecretKey: 'host-jwt',+ secretKeys: 'console:host-secret-keys',gatewayAdminPassword: 'host-admin-pw',mattermostAdminPassword: 'host-mm-admin',mattermostUserPassword: 'host-mm-user',@@ -371,6 +372,31 @@ describe('starting a shared stack', () => {expect(secrets.dbRuntimePassword).toMatch(/.{16,}/);});+ it('keeps this desktop’s key ring for a stack whose .env predates SECRET_KEYS', async () => {+ inspectStackMock.mockResolvedValue(+ present({}, { secrets: { ...hostSecrets, secretKeys: null } })+ );+ readSecretsMock.mockResolvedValue({ ...hostSecrets, secretKeys: 'console:desktop-ring' });+ const { host } = sharedHost();++ await startStack(startOptions(host));++ const [{ secrets }] = buildEnvFileMock.mock.calls[0] as [{ secrets: LocalServerSecrets }];+ expect(secrets.secretKeys).toBe('console:desktop-ring');+ });++ it('makes a key ring for a pre-SECRET_KEYS stack this desktop has none for', async () => {+ inspectStackMock.mockResolvedValue(+ present({}, { secrets: { ...hostSecrets, secretKeys: null } })+ );+ const { host } = sharedHost();++ await startStack(startOptions(host));++ const [{ secrets }] = buildEnvFileMock.mock.calls[0] as [{ secrets: LocalServerSecrets }];+ expect(secrets.secretKeys).toMatch(/^console:[0-9a-f]{64}$/);+ });+it('makes new credentials only on a host with nothing of the stack', async () => {inspectStackMock.mockResolvedValue({ kind: 'absent' });const { host } = sharedHost();diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.tsindex f46886a1f..c9490ae1f 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts@@ -34,7 +34,7 @@ import type { ServerHost } from './host/types';import { finishUpgrade, type OwedUpgrade, prepareUpgrade } from './managed-upgrade';import { crossesMatrixBoundary, runBackfill } from './matrix-migration';import { clearPorts, readPersistedPorts, rememberPorts, resolvePorts } from './ports';-import { type LocalServerSecrets, withRuntimePassword } from './secret-values';+import { type LocalServerSecrets, withNewerSecrets } from './secret-values';import { clearSecrets, loadOrCreateSecrets, readSecrets, storeSecrets } from './secrets';import type { ServerLease } from './stack-lock';import {@@ -302,10 +302,13 @@ async function adoptSettings(stack: Extract<StackOnHost, { kind: 'present' }>): Promise<StackSettings> {// A `.env` from before the database role split has no runtime password; one- // is made here, and the next start gives the role it.- const { secrets } = withRuntimePassword({+ // is made here, and the next start gives the role it. One from before+ // SECRET_KEYS takes this desktop's, if it has one — a server may already+ // have stored credentials under it — and a fresh one otherwise.+ const { secrets } = withNewerSecrets({...stack.env.secrets,dbRuntimePassword: stack.env.secrets.dbRuntimePassword ?? '',+ secretKeys: stack.env.secrets.secretKeys ?? (await readSecrets(host))?.secretKeys ?? '',});await storeSecrets(host, secrets);await rememberPorts(host, stack.env.ports);diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.test.tsindex df14ddb6d..74b4fbc62 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.test.ts@@ -154,6 +154,7 @@ const secrets = {dbRuntimePassword: 'runtime-pw',agentRegistrationToken: 'agent-token',jwtSecretKey: 'jwt',+ secretKeys: 'console:secret-keys',gatewayAdminPassword: 'admin-pw',mattermostAdminPassword: 'mm-admin',mattermostUserPassword: 'mm-user',diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.ymlindex 0134d794f..5eff37fe4 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml@@ -219,7 +219,16 @@ services:# supported release reads ID_SERVER_NAME.MATRIX_SERVER_NAME: localhostAGENT_REGISTRATION_TOKEN: ${AGENT_REGISTRATION_TOKEN}- JWT_SECRET_KEY: ${JWT_SECRET_KEY}+ SECRET_KEYS: ${SECRET_KEYS:?required, set it in .env (just init-env generates one)}+ # Legacy, optional: keeps what it signed and encrypted working until the+ # first boot has re-encrypted stored credentials under SECRET_KEYS.+ JWT_SECRET_KEY: ${JWT_SECRET_KEY:-}+ # Served over plain http on this machine by default, where a Secure+ # cookie would never be sent back. Set it to true behind https.+ GATEWAY_COOKIE_SECURE: ${GATEWAY_COOKIE_SECURE:-false}+ # The bundled Mattermost is on the compose network, a private address,+ # so it is always allowed; .env adds to it rather than replacing it.+ OUTBOUND_ALLOWED_PRIVATE_HOSTS: mattermost,${OUTBOUND_ALLOWED_PRIVATE_HOSTS:-}GATEWAY_ADMIN_EMAIL: ${GATEWAY_ADMIN_EMAIL}GATEWAY_ADMIN_PASSWORD: ${GATEWAY_ADMIN_PASSWORD}FRONTEND_BASE_URL: ${FRONTEND_BASE_URL}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secret-values.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secret-values.tsindex 3398831f6..6b466112d 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secret-values.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secret-values.ts@@ -10,12 +10,17 @@ import { randomBytes } from 'node:crypto';* bootstrapped with it, and renaming the field here does not rename what is* already on disk. `dbRuntimePassword` is the separate, unprivileged runtime* role (`DB_PASSWORD`/`DB_USER=switch_app`) that switch-core actually serves- * requests as; see `init-db` in `deploy/local/standalone-docker-compose.yml`. */+ * requests as; see `init-db` in `deploy/local/standalone-docker-compose.yml`.+ *+ * `secretKeys` is switch-core's `SECRET_KEYS`: what it signs sessions and+ * encrypts stored credentials with. `jwtSecretKey` is the key that did both+ * before it, still passed so the server can read what it wrote back then. */export type LocalServerSecrets = {dbPassword: string;dbRuntimePassword: string;agentRegistrationToken: string;jwtSecretKey: string;+ secretKeys: string;gatewayAdminPassword: string;mattermostAdminPassword: string;mattermostUserPassword: string;@@ -33,6 +38,7 @@ export function generateSecrets(): LocalServerSecrets {dbRuntimePassword: token(),agentRegistrationToken: token(),jwtSecretKey: token(32),+ secretKeys: `console:${randomBytes(32).toString('hex')}`,gatewayAdminPassword: token(),mattermostAdminPassword: token(),mattermostUserPassword: token(),@@ -40,17 +46,24 @@ export function generateSecrets(): LocalServerSecrets {}/**- * Fill in `dbRuntimePassword` for secrets written before switch-core added its- * restricted runtime role. Safe where regenerating the bundle is not: nothing on- * the existing volume used it, and `init-db` sets the role's password on every start.+ * Fill in the secrets switch-core gained after a bundle was written, and only+ * those. Safe where regenerating the bundle is not:+ *+ * - `dbRuntimePassword`, from before the restricted runtime role: nothing on+ * the existing volume used it, and `init-db` sets the role's password on+ * every start.+ * - `secretKeys`, from before `SECRET_KEYS`: a server that never had one+ * still reads what it stored through `jwtSecretKey`, and moves it onto the+ * new key on its first start. Once a server has started with one it must+ * never be replaced, which is why only an empty value is filled.*/-export function withRuntimePassword(secrets: LocalServerSecrets): {+export function withNewerSecrets(secrets: LocalServerSecrets): {secrets: LocalServerSecrets;migrated: boolean;} {- if (secrets.dbRuntimePassword) return { secrets, migrated: false };- return {- secrets: { ...secrets, dbRuntimePassword: generateSecrets().dbRuntimePassword },- migrated: true,- };+ const missing: Partial<LocalServerSecrets> = {};+ if (!secrets.dbRuntimePassword) missing.dbRuntimePassword = generateSecrets().dbRuntimePassword;+ if (!secrets.secretKeys) missing.secretKeys = generateSecrets().secretKeys;+ if (Object.keys(missing).length === 0) return { secrets, migrated: false };+ return { secrets: { ...secrets, ...missing }, migrated: true };}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.test.tsindex 1d1629511..8a4f851ec 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.test.ts@@ -76,6 +76,28 @@ describe('loadOrCreateSecrets', () => {expect(setSecret).toHaveBeenCalledWith('host-a', JSON.stringify(secrets));});+ it('backfills a missing key ring on an install predating SECRET_KEYS', async () => {+ const legacy = generateSecrets() as Partial<ReturnType<typeof generateSecrets>>;+ delete legacy.secretKeys;+ getSecret.mockResolvedValue(JSON.stringify(legacy));++ const secrets = await loadOrCreateSecrets({ secretsKey: 'host-a' });++ expect(secrets).toMatchObject(legacy);+ expect(secrets.secretKeys).toMatch(/^console:[0-9a-f]{64}$/);+ expect(setSecret).toHaveBeenCalledWith('host-a', JSON.stringify(secrets));+ });++ it('never replaces a key ring the stored secrets were encrypted with', async () => {+ const current = generateSecrets();+ getSecret.mockResolvedValue(JSON.stringify(current));++ const secrets = await loadOrCreateSecrets({ secretsKey: 'host-a' });++ expect(secrets.secretKeys).toBe(current.secretKeys);+ expect(setSecret).not.toHaveBeenCalled();+ });+it('fails loud on an unreadable bundle instead of regenerating over a live volume', async () => {getSecret.mockResolvedValue('not json');diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.tsindex 6079094a2..818010884 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.ts@@ -3,7 +3,7 @@ import {UndecryptableSecretError,} from '@main/core/secrets/encrypted-app-secrets-store';import type { ServerHost } from './host/types';-import { generateSecrets, type LocalServerSecrets, withRuntimePassword } from './secret-values';+import { generateSecrets, type LocalServerSecrets, withNewerSecrets } from './secret-values';/*** A stored bundle that will not parse is not the same as no bundle at all, and@@ -43,7 +43,7 @@ export async function loadOrCreateSecrets(): Promise<LocalServerSecrets> {const stored = await readStoredSecrets(host);if (stored.kind === 'present') {- const { secrets, migrated } = withRuntimePassword(stored.secrets);+ const { secrets, migrated } = withNewerSecrets(stored.secrets);if (migrated)await encryptedAppSecretsStore.setSecret(host.secretsKey, JSON.stringify(secrets));return secrets;@@ -70,7 +70,7 @@ export async function loadOrCreateSecrets(* *display* or inspect the credentials rather than run the stack. Generating a* bundle as a side effect of reading would mint credentials that match no* running deployment, which is exactly the fiction a reader must not be shown.- * A missing `dbRuntimePassword` is backfilled in memory for callers that expect+ * Secrets newer than the bundle (see `withNewerSecrets`) are backfilled in memory for callers that expect* the full shape, but — unlike {@link loadOrCreateSecrets} — not persisted: a* reader must not mutate stored state, so the value shown here can differ from* the one the next real start assigns and persists.@@ -79,7 +79,7 @@ export async function readSecrets(host: Pick<ServerHost, 'secretsKey'>): Promise<LocalServerSecrets | null> {const stored = await readStoredSecrets(host);- return stored.kind === 'present' ? withRuntimePassword(stored.secrets).secrets : null;+ return stored.kind === 'present' ? withNewerSecrets(stored.secrets).secrets : null;}/** Cache `secrets` as this desktop's copy of the host's bundle, replacing anydiff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/stack-state.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/stack-state.test.tsindex c4bc8c265..281e991d9 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/stack-state.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/stack-state.test.ts@@ -36,6 +36,7 @@ const secrets: LocalServerSecrets = {dbRuntimePassword: 'db-runtime-pw',agentRegistrationToken: 'agent-token',jwtSecretKey: 'jwt-key',+ secretKeys: 'console:secret-keys-value',gatewayAdminPassword: 'gw-admin',mattermostAdminPassword: 'mm-admin',mattermostUserPassword: 'mm-user',diff --git a/core/pyproject.toml b/core/pyproject.tomlindex ae78ace78..49a0910a3 100644--- a/core/pyproject.toml+++ b/core/pyproject.toml@@ -40,6 +40,7 @@ dependencies = ["PyYAML>=6,<7","discord-py>=2.4,<3","python-telegram-bot>=21,<22",+ "httpcore>=1.0.9,<2",]# Repo coordinates point at the public switch repo — see RELEASING.md.diff --git a/core/switch_core/bridges/agent/auth.py b/core/switch_core/bridges/agent/auth.pyindex 5fa9a4f11..1392aeba3 100644--- a/core/switch_core/bridges/agent/auth.py+++ b/core/switch_core/bridges/agent/auth.py@@ -52,8 +52,8 @@ class OIDCTokenValidator:def __init__(self,issuer_url: str,- audience: str | None = None,- verify_issuer: bool = True,+ audience: str,+ verify_issuer: bool,) -> None:self._issuer = issuer_urlself._audience = audience@@ -64,8 +64,6 @@ class OIDCTokenValidator:def validate(self, token: str) -> dict:signing_key = self._jwk_client.get_signing_key_from_jwt(token)options: dict[str, bool] = {}- if self._audience is None:- options["verify_aud"] = Falseif not self._verify_issuer:options["verify_iss"] = Falsereturn jwt.decode(@@ -265,9 +263,8 @@ class BearerAuthMiddleware:# Same two steps as `_resolve_api_key`, for the same reason: `agents`# is scoped, and this is the read that decides which agent — and so- # which tenant — is asking. `oauth_client_id` carries no unique index,- # so the lookup refuses rather than picking when two tenants have- # registered an agent under the same one.+ # which tenant — is asking. `oauth_client_id` is unique across the+ # deployment, so at most one tenant answers.tenant_id = await tenant_of_agent_oauth_client(self._session_factory, client_id)if tenant_id is None:return Nonediff --git a/core/switch_core/bridges/agent/mcp/server.py b/core/switch_core/bridges/agent/mcp/server.pyindex 7a26f7d85..2afd5dd36 100644--- a/core/switch_core/bridges/agent/mcp/server.py+++ b/core/switch_core/bridges/agent/mcp/server.py@@ -100,6 +100,7 @@ def create_mcp_app(oidc_validator = Noneif config.oauth_issuer_url:+ assert config.oauth_audience is not None # enforced by SwitchConfigoidc_validator = OIDCTokenValidator(issuer_url=config.oauth_issuer_url,audience=config.oauth_audience,diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.pyindex e24355c00..be546eb48 100644--- a/core/switch_core/bridges/agent/protocol/agent_core.py+++ b/core/switch_core/bridges/agent/protocol/agent_core.py@@ -65,7 +65,6 @@ from switch_core.clients.admin_messages import (platform_on_behalf_of,platform_replies_in_channel,)-from switch_core.crypto import encrypt_tokenfrom switch_core.db.models import (Agent,AgentRuntimeState,@@ -415,7 +414,7 @@ class AgentCore:api_key = secrets.token_urlsafe(32)api_key_hash = hashlib.sha256(api_key.encode()).hexdigest()- encrypted_key = encrypt_token(api_key, self.config.jwt_secret_key)+ encrypted_key = self.config.keyring.encrypt(api_key)# Reported only for a genuinely new agent: a re-registration rotates a# key on an agent that already existed, and counting it would make adiff --git a/core/switch_core/bridges/agent/server_connectors/base.py b/core/switch_core/bridges/agent/server_connectors/base.pyindex 62508c7df..766e2d1e9 100644--- a/core/switch_core/bridges/agent/server_connectors/base.py+++ b/core/switch_core/bridges/agent/server_connectors/base.py@@ -66,6 +66,15 @@ class ServerSideConnector(ABC):The lifecycle service handles all Switch API communication."""+ @classmethod+ def outbound_urls(cls, connection_config: dict[str, object]) -> list[str]:+ """The URLs in this config that Switch connects to.++ Checked against the deployment's `OutboundPolicy` when the connector is+ registered and each time it starts.+ """+ return []+@abstractmethodasync def start(self) -> None:"""Initialize connection to the external platform."""diff --git a/core/switch_core/bridges/agent/server_connectors/lifecycle.py b/core/switch_core/bridges/agent/server_connectors/lifecycle.pyindex 9aa5ee635..feb5f6df9 100644--- a/core/switch_core/bridges/agent/server_connectors/lifecycle.py+++ b/core/switch_core/bridges/agent/server_connectors/lifecycle.py@@ -12,12 +12,13 @@ from switch_core.bridges.agent.server_connectors.base import (ServerSideConnectorConfig,)from switch_core.bridges.agent.server_connectors.core import ConnectorCore-from switch_core.crypto import decrypt_token, encrypt_tokenfrom switch_core.db.models import ApiKey, ServerConnectorfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.server_connector_store import ServerConnectorStorefrom switch_core.db.tenant_lookup import all_tenant_ids, tenant_of_server_connector+from switch_core.keys import Keyring+from switch_core.outbound import OutboundPolicyfrom switch_core.telemetry import TelemetryService, emit_safelylogger = logging.getLogger(__name__)@@ -45,14 +46,16 @@ class ServerSideConnectorLifecycleService:protocol: AgentCore,session_factory: async_sessionmaker[AsyncSession],telemetry: TelemetryService | None = None,- encryption_secret: str,+ keyring: Keyring,+ outbound_policy: OutboundPolicy,) -> None:self._connector_store = connector_storeself._api_key_store = api_key_storeself._protocol = protocolself._session_factory = session_factoryself._telemetry = telemetry- self._encryption_secret = encryption_secret+ self._keyring = keyring+ self._outbound_policy = outbound_policyself._connector_registry: dict[str, type[ServerSideConnector]] = {}self._config_registry: dict[str, type[ServerSideConnectorConfig]] = {}@@ -117,13 +120,15 @@ class ServerSideConnectorLifecycleService:raise ValueError(f"Unknown connector type: {connector_type}")config_cls.model_validate(connection_config)+ for url in connector_cls.outbound_urls(connection_config):+ await self._outbound_policy.check_url(url)plaintext = secrets.token_urlsafe(32)key_hash = hashlib.sha256(plaintext.encode()).hexdigest()reg_key = ApiKey(user_id=user_id,key_hash=key_hash,- encrypted_key=encrypt_token(plaintext, self._encryption_secret),+ encrypted_key=self._keyring.encrypt(plaintext),label=f"server-connector:{display_name}",type="registration",)@@ -195,12 +200,16 @@ class ServerSideConnectorLifecycleService:if connector_cls is None or config_cls is None:raise ValueError(f"Unknown connector type: {record.type}")- registration_token = decrypt_token(- reg_key.encrypted_key, self._encryption_secret- )+ registration_token = self._keyring.decrypt(reg_key.encrypted_key)typed_config = config_cls.model_validate(record.connection_config or {})- connector = connector_cls(config=typed_config) # type: ignore[call-arg]+ # Again at every start: what the host resolves to can have changed+ # since the connector was registered.+ for url in connector_cls.outbound_urls(record.connection_config or {}):+ await self._outbound_policy.check_url(url)+ connector = connector_cls( # type: ignore[call-arg]+ config=typed_config, outbound_policy=self._outbound_policy+ )core = ConnectorCore(connector_id=connector_id,diff --git a/core/switch_core/bridges/agent/server_connectors/opencode/client.py b/core/switch_core/bridges/agent/server_connectors/opencode/client.pyindex 05c4c48a0..208730e5f 100644--- a/core/switch_core/bridges/agent/server_connectors/opencode/client.py+++ b/core/switch_core/bridges/agent/server_connectors/opencode/client.py@@ -8,14 +8,24 @@ from typing import Anyimport httpx+from switch_core.outbound import OutboundPolicy, guarded_async_client+logger = logging.getLogger(__name__)class OpenCodeClient:"""HTTP client for the OpenCode server REST API."""- def __init__(self, server_url: str, username: str, password: str) -> None:- self._http = httpx.AsyncClient(+ def __init__(+ self,+ server_url: str,+ username: str,+ password: str,+ outbound_policy: OutboundPolicy,+ ) -> None:+ self._outbound_policy = outbound_policy+ self._http = guarded_async_client(+ outbound_policy,base_url=server_url.rstrip("/"),auth=httpx.BasicAuth(username, password),timeout=300,@@ -85,7 +95,8 @@ class OpenCodeClient:@asynccontextmanagerasync def subscribe_events(self) -> AsyncIterator[AsyncIterator[dict[str, Any]]]:"""Subscribe to the SSE event stream. Yields parsed events."""- stream_client = httpx.AsyncClient(+ stream_client = guarded_async_client(+ self._outbound_policy,base_url=str(self._http._base_url),auth=self._http._auth,timeout=None,diff --git a/core/switch_core/bridges/agent/server_connectors/opencode/connector.py b/core/switch_core/bridges/agent/server_connectors/opencode/connector.pyindex 31c279ba8..ac6657e33 100644--- a/core/switch_core/bridges/agent/server_connectors/opencode/connector.py+++ b/core/switch_core/bridges/agent/server_connectors/opencode/connector.py@@ -22,6 +22,7 @@ from switch_core.bridges.agent.server_connectors.base import (ServerSideConnectorConfig,)from switch_core.bridges.agent.server_connectors.opencode.client import OpenCodeClient+from switch_core.outbound import OutboundPolicylogger = logging.getLogger(__name__)@@ -73,8 +74,15 @@ class OpenCodeConnectionConfig(ServerSideConnectorConfig):class OpenCodeConnector(ServerSideConnector):- def __init__(self, config: OpenCodeConnectionConfig) -> None:+ @classmethod+ def outbound_urls(cls, connection_config: dict[str, object]) -> list[str]:+ return [str(connection_config["server_url"])]++ def __init__(+ self, config: OpenCodeConnectionConfig, outbound_policy: OutboundPolicy+ ) -> None:self._config = config+ self._outbound_policy = outbound_policyself._client: OpenCodeClient | None = Noneself._sessions: dict[tuple[str, str], str] = {}self._agents_names_map: dict[str, str] = {}@@ -84,6 +92,7 @@ class OpenCodeConnector(ServerSideConnector):server_url=self._config.server_url,username=self._config.username,password=self._config.password,+ outbound_policy=self._outbound_policy,)async def stop(self) -> None:diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex f83ebb601..d01f2716a 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -34,6 +34,7 @@ from switch_core.bridges.collaboration.session.renderers.neutral import (request_summary,turn_summary,)+from switch_core.outbound import OutboundPolicyfrom switch_core.room_wide_mention import (ROOM_WIDE_TARGET,defuse_mass_mention_words,@@ -550,6 +551,31 @@ class PlatformAdapter(ABC):"""return connection_config+ @classmethod+ def claimed_workspace(cls, connection_config: dict[str, object]) -> str | None:+ """Name the platform workspace this bridge connects, if it has one.++ One workspace is connected at most once on an instance, across every+ tenant: two bridges into it would each deliver its events to a+ different tenant, and the hosted install path already holds a+ workspace to one tenant. Registration refuses a second claim.++ Quoted verbatim in that refusal, so it must not embed credential+ material. Return None for a platform with no such notion.+ """+ return None++ @classmethod+ def outbound_urls(cls, connection_config: dict[str, object]) -> list[str]:+ """The URLs in this config that Switch itself connects to.++ Checked against the deployment's `OutboundPolicy` before the bridge is+ stored, when its config is edited and each time it starts, so a config+ cannot point Switch at an internal address. Not the platform's own API+ hosts, and not URLs only handed to the platform or put in links.+ """+ return []+@classmethoddef exclusive_resource(cls, connection_config: dict[str, object]) -> str | None:"""Name a host resource this bridge needs to itself, if any.@@ -1332,6 +1358,21 @@ class PlatformAdapter(ABC):only Teams saves types it could not verify."""return None+ def set_outbound_policy(self, policy: OutboundPolicy) -> None:+ """Install the policy for anything this adapter fetches from a URL a+ tenant or agent chose. Set by the lifecycle before the adapter starts."""+ self._outbound_policy = policy++ @property+ def outbound_policy(self) -> OutboundPolicy:+ policy: OutboundPolicy | None = getattr(self, "_outbound_policy", None)+ if policy is None:+ raise RuntimeError(+ f"{type(self).__name__} fetched a URL before its outbound policy "+ "was set"+ )+ return policy+def set_service_url_persister(self, persist: Callable[[str], Awaitable[None]]) -> None:@@ -1343,6 +1384,15 @@ class PlatformAdapter(ABC):carried on inbound activities) override this to persist it."""return None+ def set_tenant_id(self, tenant_id: str) -> None:+ """Tell the adapter which tenant its bridge belongs to.++ Default is a no-op: an adapter's state is its own bridge's and needs+ no tenant. Slack overrides it, because it shares one structure across+ every Slack bridge in the process and has to keep tenants apart in it.+ """+ return None+def set_channel_team_persister(self, persist: Callable[[str, str], Awaitable[None]]) -> None:diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.pyindex 4dc82cc5a..00500ba0e 100644--- a/core/switch_core/bridges/collaboration/discord/adapter.py+++ b/core/switch_core/bridges/collaboration/discord/adapter.py@@ -550,6 +550,10 @@ class DiscordAdapter(PlatformAdapter):#: it may always delete.removes_answered_cards: ClassVar[bool] = True+ @classmethod+ def claimed_workspace(cls, connection_config: dict[str, object]) -> str | None:+ return f"Discord server {connection_config['guild_id']}"+def __init__(self, *, config: DiscordConnectionConfig) -> None:super().__init__()self._config = configdiff --git a/core/switch_core/bridges/collaboration/ingress.py b/core/switch_core/bridges/collaboration/ingress.pyindex 9f6a40eaa..ed92e4e13 100644--- a/core/switch_core/bridges/collaboration/ingress.py+++ b/core/switch_core/bridges/collaboration/ingress.py@@ -9,6 +9,8 @@ from typing import Anyfrom aiohttp import web+from switch_core.keys import Keyring, Purpose+logger = logging.getLogger(__name__)# What a bridge's callbacks are addressed as. The type is in the path so a@@ -16,9 +18,9 @@ logger = logging.getLogger(__name__)# bridge's id is in it so one listener serves every bridge and every tenant._ROUTE = "/collaboration/{bridge_type}/{bridge_id}/callback"-# What a callback key is derived from, so it is not the same value as anything-# else the server secret is used for.-_KEY_PURPOSE = "collaboration-callback"+# How a bridge's callback key was derived from `JWT_SECRET_KEY` before+# `SECRET_KEYS`; kept so buttons posted then still verify while it is set.+_LEGACY_KEY_PURPOSE = "collaboration-callback"Handler = Callable[[dict[str, Any]], Awaitable[dict[str, Any]]]@@ -64,10 +66,10 @@ class CallbackIngress:any other bridge sharing it."""- def __init__(self, *, host: str, port: int, secret: str) -> None:+ def __init__(self, *, host: str, port: int, keyring: Keyring) -> None:self._host = hostself._port = port- self._secret = secret+ self._keyring = keyringself._handlers: dict[tuple[str, str], Handler] = {}self._runner: web.AppRunner | None = None# Each bridge runs in a task of its own, so two starting together reach@@ -81,6 +83,7 @@ class CallbackIngress:bridge_type,bridge_id,key=self._key_for(bridge_type, bridge_id),+ verification_keys=self._verification_keys_for(bridge_type, bridge_id),)def path_for(self, bridge_type: str, bridge_id: str) -> str:@@ -95,18 +98,39 @@ class CallbackIngress:take one until somebody edits its configuration by hand — and adds asecond secret to keep, back up and rotate. Deriving it costs none ofthat: the key exists the moment the bridge starts, and rotating the- server secret rotates it.+ server keys rotates it.Separated by bridge, so what one bridge accepts another will not, and- by purpose, so it is not the same value as anything else derived from- the same secret. Rotating the server secret invalidates whatever the- old key signed; a platform that has already handed out signed material- is responsible for saying so rather than failing quietly.+ by purpose (`keys.Purpose.BRIDGE_CALLBACK`), so it is not the same value+ as anything else derived from the server's keys. Signing uses the+ current key; `_verification_keys_for` also accepts older ones."""+ return self._bridge_key(+ self._keyring.derive(Purpose.BRIDGE_CALLBACK), bridge_type, bridge_id+ )++ def _verification_keys_for(self, bridge_type: str, bridge_id: str) -> list[str]:+ """Every key a press for this bridge may carry a signature from: each+ key in the keyring, and while `JWT_SECRET_KEY` is set, the key it+ derived before `SECRET_KEYS`, so buttons already posted keep working."""+ keys = [+ self._bridge_key(derived, bridge_type, bridge_id)+ for derived in self._keyring.verification_keys(Purpose.BRIDGE_CALLBACK)+ ]+ if self._keyring.legacy_secret is not None:+ keys.append(+ hmac.new(+ self._keyring.legacy_secret.encode(),+ f"{_LEGACY_KEY_PURPOSE}:{bridge_type}:{bridge_id}".encode(),+ hashlib.sha256,+ ).hexdigest()+ )+ return keys++ @staticmethod+ def _bridge_key(derived: bytes, bridge_type: str, bridge_id: str) -> str:return hmac.new(- self._secret.encode(),- f"{_KEY_PURPOSE}:{bridge_type}:{bridge_id}".encode(),- hashlib.sha256,+ derived, f"{bridge_type}:{bridge_id}".encode(), hashlib.sha256).hexdigest()async def serve(self, bridge_type: str, bridge_id: str, handle: Handler) -> None:@@ -206,7 +230,7 @@ class CallbackEndpoint:Handed to an adapter so it can serve its own callbacks without knowingwhich bridge it is or that it shares a port with anything — and without- ever holding the server secret the key came from.+ ever holding the server keys its keys came from."""def __init__(@@ -216,11 +240,15 @@ class CallbackEndpoint:bridge_id: str,*,key: str,+ verification_keys: list[str],) -> None:self._ingress = ingressself._bridge_type = bridge_typeself._bridge_id = bridge_id+ # Signs what the bridge posts now.self.key = key+ # Verifies a press: `key`, plus older keys still in the keyring.+ self.verification_keys = verification_keys@propertydef path(self) -> str:diff --git a/core/switch_core/bridges/collaboration/install.py b/core/switch_core/bridges/collaboration/install.pyindex 736cf7117..b785c6235 100644--- a/core/switch_core/bridges/collaboration/install.py+++ b/core/switch_core/bridges/collaboration/install.py@@ -56,6 +56,10 @@ def oauth_callback_path(platform: str) -> str:return f"{PUBLIC_PATH_PREFIX}/{platform}/oauth/callback"+def oauth_confirm_path(platform: str) -> str:+ return f"{PUBLIC_PATH_PREFIX}/{platform}/oauth/confirm"++def events_path(platform: str) -> str:return f"{PUBLIC_PATH_PREFIX}/{platform}/events"diff --git a/core/switch_core/bridges/collaboration/install_confirmation.py b/core/switch_core/bridges/collaboration/install_confirmation.pynew file mode 100644index 000000000..89e71f95c--- /dev/null+++ b/core/switch_core/bridges/collaboration/install_confirmation.py@@ -0,0 +1,95 @@+"""The ticket that carries a redeemed grant from the callback to the decision.++An install is not claimed when the platform redirects back. The person who+approved it on the platform may not be the person who started it — a link to a+platform's consent screen can be sent to anyone — so the callback shows them+which Switch organisation the workspace would join, and only an explicit+Connect on that page claims it.++Between the two requests the grant has to live somewhere. It travels in the+page itself, as this ticket, rather than in the database: an approver who+closes the tab leaves nothing behind here, and no bot token is stored for an+install nobody agreed to.++The ticket is encrypted, not just signed, because it carries the bot token. It+is also the proof that whoever submits the decision saw the page: the state+token alone is not, since whoever started the install holds it. The key is+the keyring's key for this purpose (`keys.Purpose`), so a ticket is never+mistakable for any other ciphertext made from the same master key, and one+sealed just before a rotation still opens afterwards while the old key is kept.+"""++from __future__ import annotations++import base64+import json+from dataclasses import dataclass+from datetime import timedelta++from cryptography.fernet import Fernet, InvalidToken, MultiFernet++from switch_core.bridges.collaboration.install import InstallGrant+from switch_core.keys import Keyring, Purpose++#: How long the approver has to choose on the confirmation page.+CONFIRM_TTL = timedelta(minutes=15)+++class InstallTicketError(RuntimeError):+ """A ticket was malformed, not ours, or older than `CONFIRM_TTL`."""+++@dataclass(frozen=True)+class InstallTicket:+ tenant_id: str+ state_id: str+ platform: str+ grant: InstallGrant+++def _fernet(key: bytes) -> Fernet:+ return Fernet(base64.urlsafe_b64encode(key))+++def seal(ticket: InstallTicket, *, keyring: Keyring) -> str:+ payload = json.dumps(+ {+ "tid": ticket.tenant_id,+ "sid": ticket.state_id,+ "plat": ticket.platform,+ "ws": ticket.grant.external_workspace_id,+ "name": ticket.grant.workspace_name,+ "tok": ticket.grant.bot_token,+ "scopes": ticket.grant.scopes,+ },+ separators=(",", ":"),+ )+ return (+ _fernet(keyring.derive(Purpose.INSTALL_CONFIRM))+ .encrypt(payload.encode())+ .decode()+ )+++def open_ticket(token: str, *, keyring: Keyring) -> InstallTicket:+ opener = MultiFernet(+ [_fernet(key) for key in keyring.verification_keys(Purpose.INSTALL_CONFIRM)]+ )+ try:+ raw = opener.decrypt(token.encode(), ttl=int(CONFIRM_TTL.total_seconds()))+ except InvalidToken:+ raise InstallTicketError(+ "install confirmation is not one this deployment issued, or has expired"+ ) from None+ decoded = json.loads(raw)+ return InstallTicket(+ tenant_id=decoded["tid"],+ state_id=decoded["sid"],+ platform=decoded["plat"],+ grant=InstallGrant(+ external_workspace_id=decoded["ws"],+ workspace_name=decoded["name"],+ bot_token=decoded["tok"],+ scopes=decoded["scopes"],+ ),+ )diff --git a/core/switch_core/bridges/collaboration/install_routes.py b/core/switch_core/bridges/collaboration/install_routes.pyindex fb8818228..f3f6278c7 100644--- a/core/switch_core/bridges/collaboration/install_routes.py+++ b/core/switch_core/bridges/collaboration/install_routes.py@@ -27,8 +27,9 @@ from __future__ import annotationsimport htmlimport logging+from typing import Annotated, Literal-from fastapi import APIRouter, BackgroundTasks, Query, Request, Response+from fastapi import APIRouter, BackgroundTasks, Form, Query, Request, Responsefrom starlette.responses import HTMLResponse, PlainTextResponsefrom switch_core.bridges.collaboration.install import (@@ -38,10 +39,15 @@ from switch_core.bridges.collaboration.install import (WebhookAuthenticityError,WebhookEndpoint,WebhookPayloadError,+ oauth_confirm_path,+)+from switch_core.bridges.collaboration.install_confirmation import (+ InstallTicketError,)from switch_core.bridges.collaboration.install_service import (InstallPlatformMismatch,MessagingInstallService,+ PendingInstall,Revocation,WebhookBridgeUnavailable,WebhookTarget,@@ -64,14 +70,64 @@ _PAGE = """<!doctype html>h1 {{ font-size: 1.25rem; }}p {{ color: #444; }}</style></head>-<body><h1>{title}</h1><p>{detail}</p></body></html>+<body><h1>{title}</h1><p>{detail}</p>{extra}</body></html>"""+_CONFIRM_FORM = """<dl>+ <dt>{platform} workspace</dt><dd>{workspace}</dd>+ <dt>Switch organisation</dt><dd>{organisation}</dd>+ <dt>Requested by</dt><dd>{requested_by}</dd>+</dl>+<form method="post" action="{action}">+ <input type="hidden" name="ticket" value="{ticket}">+ <button type="submit" name="decision" value="connect">Connect</button>+ <button type="submit" name="decision" value="cancel">Cancel</button>+</form>+<p>If you do not recognise this organisation or the person who requested it,+choose Cancel. Closing this page connects nothing, but leaves the app in your+workspace until you remove it there.</p>+"""-def _page(*, title: str, detail: str, status: int) -> HTMLResponse:+#: Every page here is a decision or the outcome of one; none may be framed by+#: another site (a framed Connect button is a clickjacking target), cached, or+#: leak the callback's query string as a referrer.+_PAGE_HEADERS = {+ "Content-Security-Policy": (+ "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; "+ "frame-ancestors 'none'; base-uri 'none'"+ ),+ "X-Frame-Options": "DENY",+ "Cache-Control": "no-store",+ "Referrer-Policy": "no-referrer",+}+++def _page(*, title: str, detail: str, status: int, extra: str = "") -> HTMLResponse:return HTMLResponse(- _PAGE.format(title=html.escape(title), detail=html.escape(detail)),+ _PAGE.format(title=html.escape(title), detail=html.escape(detail), extra=extra),status_code=status,+ headers=_PAGE_HEADERS,+ )+++def _confirmation_page(pending: PendingInstall) -> HTMLResponse:+ return _page(+ title=f"Connect this {pending.platform} workspace to Switch?",+ detail=(+ "The app was approved on the platform. Check the organisation below "+ "before it is connected."+ ),+ status=200,+ extra=_CONFIRM_FORM.format(+ platform=html.escape(pending.platform),+ workspace=html.escape(+ f"{pending.workspace_name} ({pending.external_workspace_id})"+ ),+ organisation=html.escape(pending.organisation),+ requested_by=html.escape(pending.requested_by),+ action=html.escape(oauth_confirm_path(pending.platform)),+ ticket=html.escape(pending.ticket),+ ),)@@ -114,7 +170,7 @@ def create_messaging_install_router()try:- install = await service.complete(+ pending = await service.complete(platform=platform, code=code, state_token=state)except (InstallStateError, InstallPlatformMismatch) as failure:@@ -136,6 +192,67 @@ def create_messaging_install_router(detail=str(failure),status=400,)+ except MessagingInstallError as failure:+ return _page(+ title="Install could not be completed",+ detail=str(failure),+ status=400,+ )++ return _confirmation_page(pending)++ @router.post("/{platform}/oauth/confirm")+ async def oauth_confirm(+ platform: str,+ ticket: Annotated[str, Form()],+ decision: Annotated[Literal["connect", "cancel"], Form()],+ ) -> HTMLResponse:+ try:+ if decision == "cancel":+ try:+ grant = await service.cancel(platform=platform, ticket=ticket)+ except MessagingInstallError as failure:+ logger.error(+ "Could not revoke the %s token of a cancelled install: %s",+ platform,+ failure,+ )+ return _page(+ title="Cancel did not finish",+ detail=(+ f"Switch could not give the app's access back to "+ f"{platform}. Nothing was connected to Switch. Go "+ "back and press Cancel again; if it keeps failing, "+ f"remove the app from the {platform} workspace."+ ),+ status=502,+ )+ return _page(+ title="Install cancelled",+ detail=(+ f"Nothing was connected to Switch. The {platform} "+ f"workspace {grant.workspace_name} may still list the "+ "app; remove it there if you no longer want it."+ ),+ status=200,+ )+ install = await service.confirm(platform=platform, ticket=ticket)+ except (InstallTicketError, InstallPlatformMismatch) as failure:+ logger.warning("Refused a %s install confirmation: %s", platform, failure)+ return _page(+ title="Install could not be completed",+ detail=(+ "This confirmation is not one Switch recognises, or it has "+ "expired. Start the install again from Switch."+ ),+ status=400,+ )+ except MessagingInstallStateError as failure:+ return _page(+ title="Install already decided",+ detail=str(failure),+ status=400,+ )except MessagingInstallClaimedError as failure:return _page(title="Workspace already connected",diff --git a/core/switch_core/bridges/collaboration/install_service.py b/core/switch_core/bridges/collaboration/install_service.pyindex 352b9b5df..4d46085ae 100644--- a/core/switch_core/bridges/collaboration/install_service.py+++ b/core/switch_core/bridges/collaboration/install_service.py@@ -17,12 +17,17 @@ The finishing order is load-bearing and not the obvious one:outage burns the link — the customer starts a ten-second flow again, andthe property we keep in exchange is that a captured state is worth nothing.3. **Exchange the code**, which is the only network call.-4. **Claim the workspace**, which is where a workspace already held by another+4. **Ask the approver to confirm**, on a page naming the Switch organisation+ and who started the install. Whoever approved on the platform need not be+ whoever started the flow — the consent link can be sent to anyone — so+ nothing is claimed until they choose Connect. The grant waits in the page,+ sealed, and the choice is recorded once.+5. **Claim the workspace**, which is where a workspace already held by anothertenant fails, in the database rather than in a check above it.-5. **Register the bridge** from the rendered connection config, exactly as if+6. **Register the bridge** from the rendered connection config, exactly as ifan operator had typed the token in, and point the install row at it.-Step 5 last is deliberate too: a bridge that exists with no install row behind+Step 6 last is deliberate too: a bridge that exists with no install row behindit is an orphan nothing can revoke, whereas an install row with no bridge is arecorded credential waiting to be used, which is a state the schema alreadyallows for.@@ -60,32 +65,46 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.install import (InboundWebhook,+ InstallGrant,MessagingAppInstaller,MessagingInstallerRegistry,+ MessagingInstallError,WebhookEndpoint,oauth_callback_path,public_url,)+from switch_core.bridges.collaboration.install_confirmation import (+ CONFIRM_TTL,+ InstallTicket,+ open_ticket,+ seal,+)from switch_core.bridges.collaboration.install_state import (InstallState,mint,verify,)from switch_core.bridges.collaboration.lifecycle_service import (+ BridgeClaimConflict,CollaborationBridgeLifecycleService,)-from switch_core.bridges.collaboration.models import BridgeStartRefused-from switch_core.crypto import decrypt_token, encrypt_token-from switch_core.db.models import MessagingInstall+from switch_core.bridges.collaboration.models import (+ BridgeCredentialError,+ BridgeStartRefused,+)+from switch_core.db.audit import AuditAction, record_audit_event+from switch_core.db.models import MessagingInstall, Tenant, Userfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.messaging_event_store import MessagingEventReceiptStorefrom switch_core.db.stores.messaging_install_store import (INSTALL_ACTIVE,INSTALL_DISCONNECTED,INSTALL_REVOKED,+ MessagingInstallClaimedError,MessagingInstallStore,)from switch_core.db.tenant_lookup import tenant_of_messaging_install+from switch_core.keys import Keyringfrom switch_core.tenant_context import no_tenant, tenant_scopelogger = logging.getLogger(__name__)@@ -135,6 +154,22 @@ class WebhookTarget:adapter: PlatformAdapter+@dataclass(frozen=True)+class PendingInstall:+ """A redeemed grant waiting for the approver's Connect or Cancel.++ Everything the confirmation page shows, and the sealed `ticket` its forms+ send back. `requested_by` is the email of whoever started the install.+ """++ platform: str+ workspace_name: str+ external_workspace_id: str+ organisation: str+ requested_by: str+ ticket: str++class InstallPlatformMismatch(RuntimeError):"""A state minted for one platform arrived at another's callback.@@ -156,7 +191,7 @@ class MessagingInstallService:installers: MessagingInstallerRegistry,lifecycle: CollaborationBridgeLifecycleService,public_origin: str,- secret: str,+ keyring: Keyring,) -> None:self._session_factory = session_factoryself._store = store@@ -164,7 +199,7 @@ class MessagingInstallService:self._installers = installersself._lifecycle = lifecycleself._public_origin = public_origin- self._secret = secret+ self._keyring = keyringdef _redirect_uri(self, platform: str) -> str:"""Where the platform sends the browser back to.@@ -198,7 +233,7 @@ class MessagingInstallService:InstallState(tenant_id=state.tenant_id, state_id=state.id, platform=platform),- secret=self._secret,+ keyring=self._keyring,)return installer.authorize_url(state=token, redirect_uri=self._redirect_uri(platform)@@ -206,14 +241,15 @@ class MessagingInstallService:async def complete(self, *, platform: str, code: str, state_token: str- ) -> MessagingInstall:- """Finish an install begun elsewhere, on behalf of nobody in particular.+ ) -> PendingInstall:+ """Redeem the platform's code and return what the approver must confirm.The caller is unauthenticated: everything trusted here comes out of thesignature on `state_token` or out of the platform's own response.+ Nothing is claimed yet — see `confirm`."""installer = self._installers.get(platform)- state = verify(state_token, secret=self._secret)+ state = verify(state_token, keyring=self._keyring)if state.platform != platform:raise InstallPlatformMismatch(f"an install state for {state.platform} was presented to the "@@ -233,8 +269,76 @@ class MessagingInstallService:code=code, redirect_uri=self._redirect_uri(platform))+ # Refused here rather than after the approver has chosen Connect on+ # a page offering a workspace that cannot be had. `confirm` checks+ # again, since the workspace may be claimed in between.+ try:+ await self._lifecycle.reject_claim_conflict(+ platform, installer.connection_config(grant)+ )+ except BridgeClaimConflict as exc:+ raise MessagingInstallClaimedError(str(exc)) from exc+async with tenant_session(self._session_factory, state.tenant_id+ ) as session:+ tenant = await session.get(Tenant, state.tenant_id)+ requester = await session.get(User, burnt.created_by_user_id)+ if tenant is None or requester is None:+ raise RuntimeError(+ f"install state {state.state_id} names a tenant or user "+ "that no longer exists"+ )+ organisation = tenant.name+ requested_by = requester.email++ return PendingInstall(+ platform=platform,+ workspace_name=grant.workspace_name,+ external_workspace_id=grant.external_workspace_id,+ organisation=organisation,+ requested_by=requested_by,+ ticket=seal(+ InstallTicket(+ tenant_id=state.tenant_id,+ state_id=state.state_id,+ platform=platform,+ grant=grant,+ ),+ keyring=self._keyring,+ ),+ )++ async def confirm(self, *, platform: str, ticket: str) -> MessagingInstall:+ """The approver chose Connect: claim the workspace and build its bridge."""+ opened = self._open(platform, ticket)+ installer = self._installers.get(platform)+ grant = opened.grant++ with tenant_scope(opened.tenant_id):+ async with tenant_session(+ self._session_factory, opened.tenant_id+ ) as session:+ decided = await self._store.decide_state(+ session,+ state_id=opened.state_id,+ platform=platform,+ window=CONFIRM_TTL,+ )+ await session.commit()++ connection_config = installer.connection_config(grant)++ # Before the install is recorded: registering the bridge re-checks+ # this, but a refusal there would leave an active install with no+ # bridge, holding the workspace for nothing.+ try:+ await self._lifecycle.reject_claim_conflict(platform, connection_config)+ except BridgeClaimConflict as exc:+ raise MessagingInstallClaimedError(str(exc)) from exc++ async with tenant_session(+ self._session_factory, opened.tenant_id) as session:install = await self._store.record_install(session,@@ -244,47 +348,145 @@ class MessagingInstallService:# deployment-level (Discord), not per-install; there is# nothing to encrypt and the column is nullable for it.encrypted_bot_token=(- encrypt_token(grant.bot_token, self._secret)+ self._keyring.encrypt(grant.bot_token)if grant.bot_token is not Noneelse None),scopes=grant.scopes,- user_id=burnt.created_by_user_id,+ user_id=decided.created_by_user_id,)install_id = install.idawait session.commit()- bridge = await self._lifecycle.register(- bridge_type=platform,- display_name=grant.workspace_name,- connection_config=installer.connection_config(grant),- # Off, though the granted scopes would allow it. Nobody was- # asked: an install has no registration form, and letting an- # app create channels in a customer's workspace is a decision- # someone should make rather than inherit.- channel_creation_enabled=False,- # A person installed the app: this is them connecting their- # platform, which is exactly what onboarding measures.- preconfigured=False,- )+ try:+ bridge = await self._lifecycle.register(+ bridge_type=platform,+ display_name=grant.workspace_name,+ connection_config=connection_config,+ # Off, though the granted scopes would allow it. Nobody was+ # asked: an install has no registration form, and letting+ # an app create channels in a customer's workspace is a+ # decision someone should make rather than inherit.+ channel_creation_enabled=False,+ # A person installed the app: this is them connecting their+ # platform, which is exactly what onboarding measures.+ preconfigured=False,+ )+ except Exception as exc:+ # An active install with no bridge would hold the workspace,+ # refusing every reinstall until someone disconnected it by+ # hand — a platform blip during the credential check would be+ # enough. Ending it releases the workspace for the retry.+ async with tenant_session(+ self._session_factory, opened.tenant_id+ ) as session:+ await self._store.end(+ session, install_id=install_id, status=INSTALL_DISCONNECTED+ )+ await session.commit()+ logger.warning(+ "Ended %s install %s for workspace %s: its bridge could not "+ "be registered (%s)",+ platform,+ install_id,+ grant.external_workspace_id,+ exc,+ )+ if isinstance(exc, BridgeCredentialError):+ raise MessagingInstallError(+ f"{exc} Start the install again from Switch."+ ) from exc+ raiseasync with tenant_session(- self._session_factory, state.tenant_id+ self._session_factory, opened.tenant_id) as session:attached = await self._store.attach_bridge(session, install_id=install_id, bridge_id=bridge.id)+ await record_audit_event(+ session,+ tenant_id=opened.tenant_id,+ actor_user_id=decided.created_by_user_id,+ action=AuditAction.MESSAGING_INSTALL_CONNECTED,+ target_type="messaging_install",+ target_id=install_id,+ details={+ "platform": platform,+ "external_workspace_id": grant.external_workspace_id,+ "workspace_name": grant.workspace_name,+ "bridge_id": bridge.id,+ "scopes": grant.scopes,+ },+ )await session.commit()logger.info("Installed %s workspace %s for tenant %s as bridge %s",platform,grant.external_workspace_id,- state.tenant_id,+ opened.tenant_id,bridge.id,)return attached+ async def cancel(self, *, platform: str, ticket: str) -> InstallGrant:+ """The approver chose Cancel: give the credential back, then record it.++ The token is revoked only when no active install holds the workspace.+ A platform hands the same bot token to every install of one app into+ one workspace, so revoking it while another install holds that+ workspace would cut that install off.++ The decision commits only once the revocation has succeeded. The token+ is stored nowhere else, so a cancel recorded ahead of a failed+ revocation would leave a live credential nothing could reach again.+ Until the commit the state row stays locked, so a Connect submitted+ meanwhile waits for this outcome rather than racing it.+ """+ opened = self._open(platform, ticket)+ grant = opened.grant++ with tenant_scope(opened.tenant_id):+ async with tenant_session(+ self._session_factory, opened.tenant_id+ ) as session:+ await self._store.decide_state(+ session,+ state_id=opened.state_id,+ platform=platform,+ window=CONFIRM_TTL,+ )+ if grant.bot_token is not None:+ with no_tenant():+ holder = await tenant_of_messaging_install(+ self._session_factory,+ platform,+ grant.external_workspace_id,+ )+ if holder is None:+ await self._installers.get(platform).revoke(+ bot_token=grant.bot_token+ )+ await session.commit()++ logger.info(+ "Install of %s workspace %s for tenant %s was cancelled by its approver",+ platform,+ grant.external_workspace_id,+ opened.tenant_id,+ )+ return grant++ def _open(self, platform: str, ticket: str) -> InstallTicket:+ opened = open_ticket(ticket, keyring=self._keyring)+ if opened.platform != platform:+ raise InstallPlatformMismatch(+ f"an install confirmation for {opened.platform} was presented to "+ f"the {platform} callback"+ )+ return opened+async def refuse_uninstalled_bridge(self,*,@@ -368,7 +570,7 @@ class MessagingInstallService:with tenant_scope(tenant_id):if token is not None:await self._installers.get(platform).revoke(- bot_token=decrypt_token(token, self._secret)+ bot_token=self._keyring.decrypt(token))async with tenant_session(self._session_factory, tenant_id) as session:diff --git a/core/switch_core/bridges/collaboration/install_state.py b/core/switch_core/bridges/collaboration/install_state.pyindex fda5928be..9f2d4693b 100644--- a/core/switch_core/bridges/collaboration/install_state.py+++ b/core/switch_core/bridges/collaboration/install_state.py@@ -27,10 +27,11 @@ victim's tenant — message injection into someone else's rooms. Single use isthe missing half and only the database can provide it: the row named here isburnt with a conditional update, and a second attempt finds nothing to burn.-The signing key is derived from `JWT_SECRET_KEY` rather than being another-value to deploy, but it is *derived* rather than reused: a token minted here-must never be mistakable for an agent's JWT, or for whatever the next thing to-want a signature turns out to be.+The signing key is the keyring's key for this purpose (`keys.Purpose`),+derived rather than reused: a token minted here must never be mistakable for a+session JWT, or for whatever the next thing to want a signature turns out to+be. Verification accepts any key in the keyring, and while `JWT_SECRET_KEY` is+still set, a state minted with it before `SECRET_KEYS` existed."""from __future__ import annotations@@ -41,10 +42,11 @@ import hmacimport jsonfrom dataclasses import dataclass-#: Distinguishes this key from every other use of `JWT_SECRET_KEY`, and this-#: token format from whatever replaces it. Changing either string invalidates-#: every state in flight, which for a flow measured in seconds is free.-_KEY_INFO = b"switch/messaging-install-state/v1"+from switch_core.keys import Keyring, Purpose++#: How a state was signed with `JWT_SECRET_KEY` before `SECRET_KEYS`; kept so+#: a state in flight across the upgrade still verifies.+_LEGACY_KEY_INFO = b"switch/messaging-install-state/v1"_PREFIX = "v1."@@ -74,8 +76,15 @@ class InstallState:platform: str-def _signing_key(secret: str) -> bytes:- return hmac.new(secret.encode(), _KEY_INFO, hashlib.sha256).digest()+def _verification_keys(keyring: Keyring) -> list[bytes]:+ keys = keyring.verification_keys(Purpose.INSTALL_STATE)+ if keyring.legacy_secret is not None:+ keys.append(+ hmac.new(+ keyring.legacy_secret.encode(), _LEGACY_KEY_INFO, hashlib.sha256+ ).digest()+ )+ return keysdef _b64(raw: bytes) -> str:@@ -86,7 +95,7 @@ def _unb64(encoded: str) -> bytes:return base64.urlsafe_b64decode(encoded + "=" * (-len(encoded) % 4))-def mint(state: InstallState, *, secret: str) -> str:+def mint(state: InstallState, *, keyring: Keyring) -> str:"""Sign a state for the platform to hand back to us unchanged."""payload = _b64(json.dumps(@@ -95,11 +104,13 @@ def mint(state: InstallState, *, secret: str) -> str:sort_keys=True,).encode())- signature = hmac.new(_signing_key(secret), payload.encode(), hashlib.sha256)+ signature = hmac.new(+ keyring.derive(Purpose.INSTALL_STATE), payload.encode(), hashlib.sha256+ )return f"{_PREFIX}{payload}.{_b64(signature.digest())}"-def verify(token: str, *, secret: str) -> InstallState:+def verify(token: str, *, keyring: Keyring) -> InstallState:"""Recover the state from a token, or raise.Nothing here touches the database, and nothing here is trusted before the@@ -114,11 +125,14 @@ def verify(token: str, *, secret: str) -> InstallState:except ValueError:raise InstallStateError("install state is malformed") from None- expected = hmac.new(_signing_key(secret), payload.encode(), hashlib.sha256).digest()try:- matches = hmac.compare_digest(_unb64(signature), expected)+ presented = _unb64(signature)except ValueError:raise InstallStateError("install state is malformed") from None+ matches = False+ for key in _verification_keys(keyring):+ expected = hmac.new(key, payload.encode(), hashlib.sha256).digest()+ matches = hmac.compare_digest(presented, expected) or matchesif not matches:raise InstallStateError("install state was not signed by this deployment")diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.pyindex 51b24c07e..e8c4e5256 100644--- a/core/switch_core/bridges/collaboration/lifecycle_service.py+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py@@ -19,6 +19,7 @@ from switch_core.bridges.collaboration.models import (BridgeConnectionConfig,BridgeCredentialError,BridgeOperationError,+ BridgeStartRefused,)from switch_core.clients.actor import Actorfrom switch_core.clients.client_factory import ClientFactory@@ -37,6 +38,7 @@ from switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.tenant_lookup import all_tenant_ids, tenant_of_collaboration_bridgefrom switch_core.deeplinks import gateway_url_warning+from switch_core.outbound import OutboundURLRefusedfrom switch_core.provisioning import Provisioningfrom switch_core.telemetry import TelemetryService, emit_safelyfrom switch_core.telemetry.ages import UNKNOWN_AGE, age_days, seconds_since@@ -284,6 +286,10 @@ def _workspace_consumer_localpart(bridge_type: str, display_name: str) -> str:return f"switch-bridge-{bridge_type}-{safe_name}-{uuid4().hex[:8]}"+class BridgeClaimConflict(ValueError):+ """A bridge would claim a host resource or platform workspace another holds."""++class BridgeStartGuard(Protocol):"""Asked before a bridge starts whether it may; raises `BridgeStartRefused`."""@@ -342,7 +348,9 @@ class CollaborationBridgeLifecycleService:self._session_activity_service = session_activity_serviceself._connections = connectionsself._bridge_starting_listeners: list[Callable[[PlatformAdapter], None]] = []- self._bridge_start_guards: list[BridgeStartGuard] = []+ self._bridge_start_guards: list[BridgeStartGuard] = [+ self._refuse_disallowed_urls+ ]self._adapter_registry: dict[str, type[PlatformAdapter]] = {}self._config_registry: dict[str, type[BridgeConnectionConfig]] = {}@@ -370,6 +378,11 @@ class CollaborationBridgeLifecycleService:# (see PlatformAdapter.exclusive_resource). Lets a second# claimant be refused by name instead of failing on the resource.self._held_resources: dict[str, str] = {}+ # bridge_id -> the platform workspace it connects while running (see+ # PlatformAdapter.claimed_workspace). Only for the warning below:+ # registration refuses a second claim, but rows predating that check+ # still start.+ self._running_workspaces: dict[str, str] = {}# Started and not deliberately stopped. A crash removes a bridge from# `_bridges` and leaves it here, which is what makes "configured but no# longer running" answerable.@@ -388,7 +401,7 @@ class CollaborationBridgeLifecycleService:self._callback_ingress = CallbackIngress(host=config.collaboration_callback_host,port=config.collaboration_callback_port,- secret=config.jwt_secret_key,+ keyring=config.keyring,)self._callback_endpoints: dict[str, CallbackEndpoint] = {}# Serialises registration. The exclusivity check reads the stored@@ -448,6 +461,32 @@ class CollaborationBridgeLifecycleService:"""self._bridge_start_guards.append(guard)+ async def check_outbound_urls(+ self, bridge_type: str, connection_config: Mapping[str, object]+ ) -> None:+ """Raise `OutboundURLRefused` if the config names a URL Switch may not reach."""+ adapter_cls = self._adapter_registry.get(bridge_type)+ if adapter_cls is None:+ return+ policy = self._config.outbound_policy+ for url in adapter_cls.outbound_urls(dict(connection_config)):+ await policy.check_url(url)++ async def _refuse_disallowed_urls(+ self,+ *,+ bridge_id: str,+ tenant_id: str,+ bridge_type: str,+ connection_config: Mapping[str, object],+ ) -> None:+ """Start guard: re-checked at every start and edit, because what a+ hostname resolves to can change after the bridge was registered."""+ try:+ await self.check_outbound_urls(bridge_type, connection_config)+ except OutboundURLRefused as exc:+ raise BridgeStartRefused(f"Bridge {bridge_id}: {exc}") from exc+async def check_start_guards(self,*,@@ -545,6 +584,29 @@ class CollaborationBridgeLifecycleService:raise ValueError(f"Unknown bridge type: {bridge_type}")config_cls.model_validate(connection_config)+ async def check_edited_connection_config(+ self,+ *,+ bridge_id: str,+ bridge_type: str,+ connection_config: dict[str, object],+ ) -> None:+ """Hold an edited config to what registration holds a new one to.++ An edit can change what registration checked — which workspace the+ bridge claims, or the credentials proving it — so it is checked the+ same way before it is stored: valid for the type, no claim another+ bridge holds, and credentials the platform accepts. Raises+ `ValidationError`, `BridgeClaimConflict` or `BridgeCredentialError`.+ """+ self.validate_connection_config(bridge_type, connection_config)+ await self.reject_claim_conflict(+ bridge_type, connection_config, exclude_bridge_id=bridge_id+ )+ adapter_cls = self._adapter_registry.get(bridge_type)+ if adapter_cls is not None:+ await adapter_cls.verify_credentials(connection_config)+async def start_all(self) -> None:# Every tenant's active bridges, read one tenant at a time. Which# tenants there are comes from the exemption (`db/tenant_lookup.py`);@@ -583,41 +645,48 @@ class CollaborationBridgeLifecycleService:except Exception:logger.exception("Failed to start bridge %s", bridge.id)- async def _reject_resource_conflict(+ async def reject_claim_conflict(self,bridge_type: str,connection_config: dict[str, object],*,exclude_bridge_id: str | None = None,) -> None:- """Refuse a bridge that would contend for a resource another one holds.+ """Refuse a bridge that would claim what another bridge already holds.- Checked against every stored bridge rather than the running set, so the- answer does not depend on whether the incumbent happens to be up.+ Two kinds of claim: a host resource the process can hold once (see+ `PlatformAdapter.exclusive_resource`), and a platform workspace+ connected at most once on the instance (see+ `PlatformAdapter.claimed_workspace`). Checked against every stored+ bridge rather than the running set, so the answer does not depend on+ whether the incumbent happens to be up.++ Raises `BridgeClaimConflict`."""adapter_cls = self._adapter_registry.get(bridge_type)if adapter_cls is None:return- wanted = adapter_cls.exclusive_resource(connection_config)- if wanted is None:+ wanted_resource = adapter_cls.exclusive_resource(connection_config)+ wanted_workspace = adapter_cls.claimed_workspace(connection_config)+ if wanted_resource is None and wanted_workspace is None:return# Captured before the loop below rebinds per tenant. This method is- # only ever reached from an authenticated request, so what is bound- # going in *is* the caller's tenant — the loop then replaces it, once- # per tenant, for the scoped read of that tenant's bridges. A call- # with nothing bound (no request behind it, if one ever exists) is- # treated as belonging to no tenant at all rather than guessed at: it- # can never match `other.tenant_id`, so it falls straight into the- # cross-tenant branch below and gets the non-disclosing message. Fail- # closed, not open.+ # only ever reached from an authenticated request or an install the+ # state token binds, so what is bound going in *is* the caller's+ # tenant — the loop then replaces it, once per tenant, for the scoped+ # read of that tenant's bridges. A call with nothing bound is treated+ # as belonging to no tenant at all rather than guessed at: it can never+ # match `other.tenant_id`, so it falls straight into the cross-tenant+ # branch below and gets the non-disclosing message. Fail closed, not+ # open.caller_tenant_id = current_tenant_id()# Deliberately across every tenant. Two tenants binding the same Slack# workspace, or the same Teams listen port, is precisely the collision- # this exists to refuse — the resource is a property of the host and- # the platform, not of a tenant — so narrowing to the caller's tenant- # would make it miss the case it was written for.+ # this exists to refuse — the claim is a property of the host and the+ # platform, not of a tenant — so narrowing to the caller's tenant would+ # make it miss the case it was written for.existing: list[CollaborationBridge] = []for tenant_id in await all_tenant_ids(self._session_factory):async with tenant_session(self._session_factory, tenant_id) as session:@@ -633,7 +702,7 @@ class CollaborationBridgeLifecycleService:for other in existing:# Guard the None case explicitly: an unflushed row has no id yet, and# `other.id == exclude_bridge_id` would then be None == None and skip- # a bridge that genuinely holds the resource.+ # a bridge that genuinely holds the claim.if exclude_bridge_id is not None and other.id == exclude_bridge_id:continueif other.type != bridge_type:@@ -641,33 +710,46 @@ class CollaborationBridgeLifecycleService:other_cls = self._adapter_registry.get(other.type)if other_cls is None:continue+ other_config = other.connection_config or {}try:- held = other_cls.exclusive_resource(other.connection_config or {})+ held_resource = other_cls.exclusive_resource(other_config)+ held_workspace = other_cls.claimed_workspace(other_config)except Exception:# A stored config we can no longer parse should not block a new# bridge — it is its own problem, and it is already logged when# that bridge tries to start.logger.warning(- "Could not read the exclusive resource of bridge %s (%s)",+ "Could not read the claims of bridge %s (%s)",other.id,other.type,exc_info=True,)continue- if held != wanted:+ if wanted_resource is not None and held_resource == wanted_resource:+ wanted = wanted_resource+ same_tenant_advice = (+ f"two {bridge_type} bridges cannot share it. Delete that "+ "bridge first, or give this one a different listen_port in "+ "its connection_config — noting the Helm chart publishes "+ "only one Teams port, so a second one needs its own Service "+ "port and route."+ )+ elif wanted_workspace is not None and held_workspace == wanted_workspace:+ wanted = wanted_workspace+ same_tenant_advice = (+ "a workspace can be connected only once. Delete that bridge "+ "first if this one is meant to replace it."+ )+ else:continueif caller_tenant_id is not None and other.tenant_id == caller_tenant_id:# The incumbent is the caller's own bridge, so naming it tells# the caller nothing they cannot already see on their own# bridge list — and the name is what turns this from "refused"# into "refused, and here is the one to delete or move".- raise ValueError(+ raise BridgeClaimConflict(f"'{other.display_name}' already uses {wanted} on this "- f"instance, and two {bridge_type} bridges cannot share it. "- "Delete that bridge first, or give this one a different "- "listen_port in its connection_config — noting the Helm "- "chart publishes only one Teams port, so a second one needs "- "its own Service port and route."+ f"instance, and {same_tenant_advice}")# The incumbent belongs to a different tenant (or the caller's# tenant could not be determined at all — see the fail-closed note@@ -680,7 +762,7 @@ class CollaborationBridgeLifecycleService:# information about the incumbent.## "already claimed on this instance" is still a narrow leak: it- # tells the caller *someone* holds this resource, which they would+ # tells the caller *someone* holds this claim, which they would# not otherwise know. That is unavoidable if the collision is to be# refused at all rather than silently misconfigured, and it is a# great deal less than a bridge name and a tenant identity.@@ -693,11 +775,11 @@ class CollaborationBridgeLifecycleService:other.id,other.tenant_id,)- raise ValueError(+ raise BridgeClaimConflict(f"{wanted} is already claimed by a {bridge_type} bridge on "- "this instance and cannot be shared. This is a host- and "- "platform-level limit, not specific to your workspace; an "- "operator can see which bridge holds it."+ "this instance and cannot be shared. This is an instance-wide "+ "limit, not specific to your workspace; an operator can see "+ "which bridge holds it.")async def register(@@ -746,7 +828,8 @@ class CollaborationBridgeLifecycleService:validated = config_cls.model_validate(connection_config)connection_config = validated.model_dump(mode="json")- await self._reject_resource_conflict(bridge_type, connection_config)+ await self.reject_claim_conflict(bridge_type, connection_config)+ await self.check_outbound_urls(bridge_type, connection_config)# Before anything is written. The adapter runs in a background task# whose failures are logged and swallowed, so credentials that are wrong@@ -864,6 +947,19 @@ class CollaborationBridgeLifecycleService:"Only one of them can run; delete one, or give it ""a different listen_port.")+ workspace = adapter_cls.claimed_workspace(bridge.connection_config or {})+ if workspace is not None:+ for other_id, held in self._running_workspaces.items():+ if held == workspace and other_id != bridge_id:+ logger.warning(+ "Bridge %s (%s) connects %s, which bridge %s also "+ "connects. Its events may reach either bridge's "+ "tenant; delete one of them.",+ bridge_id,+ bridge.type,+ workspace,+ other_id,+ )typed_config = config_cls.model_validate(bridge.connection_config or {})await self.check_start_guards(@@ -873,6 +969,8 @@ class CollaborationBridgeLifecycleService:connection_config=bridge.connection_config or {},)adapter = adapter_cls(config=typed_config) # type: ignore[call-arg]+ adapter.set_tenant_id(tenant_id)+ adapter.set_outbound_policy(self._config.outbound_policy)adapter.set_service_url_persister(lambda service_url: self._persist_service_url(bridge_id, tenant_id, service_url@@ -965,6 +1063,8 @@ class CollaborationBridgeLifecycleService:self._platforms_seen.add(normalise_platform(bridge.type))if wanted is not None:self._held_resources[bridge_id] = wanted+ if workspace is not None:+ self._running_workspaces[bridge_id] = workspacelogger.info("Started collaboration bridge %s (%s)", bridge_id, bridge.type)except Exception as exc:@@ -1082,6 +1182,7 @@ class CollaborationBridgeLifecycleService:self._bridges.pop(bridge_id, None)self._tasks.pop(bridge_id, None)self._held_resources.pop(bridge_id, None)+ self._running_workspaces.pop(bridge_id, None)# The adapter may already have asked to be served before the# failure, so a crash that leaves the endpoint registered# leaves presses being handled by a bridge that is not running.@@ -1255,6 +1356,7 @@ class CollaborationBridgeLifecycleService:self._bridges.pop(bridge_id, None)self._held_resources.pop(bridge_id, None)+ self._running_workspaces.pop(bridge_id, None)self._started.discard(bridge_id)# A bridge cancelled before it connected never reaches an outcome, and# `_run_bridge`'s handler does not catch `CancelledError`, so itsdiff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.pyindex a19f11b29..14651f316 100644--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py@@ -14,8 +14,8 @@ from contextvars import ContextVarfrom dataclasses import dataclass, replacefrom datetime import UTC, datetimefrom typing import Any, ClassVar+from urllib.parse import SplitResult, urlsplit-import httpximport requests as sync_requestsfrom mattermostdriver import Driverfrom mattermostdriver.exceptions import (@@ -27,6 +27,7 @@ from mattermostdriver.exceptions import (NotEnoughPermissions,ResourceNotFound,)+from pydantic import field_validatorfrom switch_core.agent_icon import default_icon_urlfrom switch_core.bridges.collaboration.adapter import (@@ -53,6 +54,7 @@ from switch_core.bridges.collaboration.mattermost.callback import (interrupt_action,read_press,)+from switch_core.bridges.collaboration.mattermost.http_client import NoRedirectClientfrom switch_core.bridges.collaboration.models import (Attachment,AttachmentFailure,@@ -83,6 +85,7 @@ from switch_core.bridges.collaboration.session.renderers.neutral import (render_request,turn_status,)+from switch_core.outbound import guarded_async_clientfrom switch_core.sessions.contract import TURN_ENDEDlogger = logging.getLogger(__name__)@@ -212,6 +215,17 @@ class _Rendered:plain: str+def _server_url(value: str) -> SplitResult:+ """`url` as the driver reads it (`_create_driver`): no scheme means http."""+ value = value.strip()+ return urlsplit(value if "://" in value else f"http://{value}")+++# The port `_create_driver` connects to when the URL names none — not 80 for+# http, but Mattermost's own.+_DRIVER_DEFAULT_PORTS = {"http": 8065, "https": 443}++class MattermostConnectionConfig(BridgeConnectionConfig):url: stradmin_user: str@@ -242,6 +256,20 @@ class MattermostConnectionConfig(BridgeConnectionConfig):# carry no buttons and stay answerable by typing.callback_base_url: str | None = None+ @field_validator("url")+ @classmethod+ def _url_names_a_server(cls, value: str) -> str:+ """`url` is what the bridge's claim on a team is worked out from, so+ it is checked here rather than failing deep inside that."""+ parts = _server_url(value)+ if parts.scheme.lower() not in ("http", "https") or not parts.hostname:+ raise ValueError("url must be an http(s) URL naming the server")+ try:+ parts.port+ except ValueError as exc:+ raise ValueError(f"url has an invalid port: {exc}") from exc+ return value+# A refusal being collected for the person who pressed, if a press is what we# are in the middle of. Mattermost has one chance to say something privately —@@ -312,6 +340,30 @@ class MattermostAdapter(PlatformAdapter):#: keeps the channel a record of what was asked and what was decided.removes_answered_cards: ClassVar[bool] = False+ @classmethod+ def claimed_workspace(cls, connection_config: dict[str, object]) -> str | None:+ """The team on its server, compared in canonical form so a trailing+ slash, letter case, a missing scheme or an explicit default port does+ not make the same team look like a different one. Defaults are the+ driver's, so `http://mm` and `mm:8065` are one server and `mm:80`+ another."""+ url = _server_url(str(connection_config["url"]))+ scheme = url.scheme.lower()+ port = url.port+ default_port = _DRIVER_DEFAULT_PORTS.get(scheme)+ host = (url.hostname or "").lower()+ if port is not None and port != default_port:+ host = f"{host}:{port}"+ path = url.path.rstrip("/")+ team = str(connection_config["team_name"]).lower()+ return f"Mattermost team {team} on {scheme}://{host}{path}"++ @classmethod+ def outbound_urls(cls, connection_config: dict[str, object]) -> list[str]:+ # The driver connects without our pinning, so this check at+ # registration, edit and start is the guard for the server URL.+ return [_server_url(str(connection_config["url"])).geturl()]+def __init__(self, *, config: MattermostConnectionConfig) -> None:super().__init__()self._config = config@@ -505,7 +557,7 @@ class MattermostAdapter(PlatformAdapter):"""if self._callback is None:raise CallbackRefused("This bridge takes no callbacks.", status=404)- press = read_press(self._callback.key, body)+ press = read_press(self._callback.verification_keys, body)if press is None:raise CallbackRefused("Not a press this bridge will act on.", status=401)if isinstance(press, ActivityPress):@@ -2295,6 +2347,22 @@ class MattermostAdapter(PlatformAdapter):# the response has to be a PNG it can accept.return default_icon_url(agent_name, image_format="png")+ async def _fetch_icon(self, url: str) -> bytes | None:+ """The icon's bytes, or None if it is larger than the ceiling."""+ async with guarded_async_client(+ self.outbound_policy, follow_redirects=False, timeout=10.0+ ) as client:+ async with client.stream("GET", url) as resp:+ resp.raise_for_status()+ chunks: list[bytes] = []+ size = 0+ async for chunk in resp.aiter_bytes():+ size += len(chunk)+ if size > _MAX_BOT_ICON_BYTES:+ return None+ chunks.append(chunk)+ return b"".join(chunks)+async def _set_bot_icon(self, bot_id: str, agent_name: str) -> None:if not self._admin_driver or not self._main_loop:logger.error("[BOT-ICON] skipping %s: no driver or loop", agent_name)@@ -2305,19 +2373,16 @@ class MattermostAdapter(PlatformAdapter):logger.debug("[BOT-ICON] fetching avatar for %s", agent_name)# This is the one place Switch dereferences an agent's icon URL# rather than handing it to a platform, so the fetch is bounded:- # redirects off (a permitted host could otherwise bounce us to an- # internal one, which validation at write time cannot foresee) and- # a size ceiling so a hostile response cannot be read unbounded.- async with httpx.AsyncClient(follow_redirects=False) as client:- resp = await client.get(url, timeout=10.0)- resp.raise_for_status()- image_bytes = resp.content- if len(image_bytes) > _MAX_BOT_ICON_BYTES:+ # only addresses the outbound policy allows, checked as the+ # connection is made (validation at write time cannot see what a+ # name resolves to later), no redirects, and a size ceiling+ # enforced while reading rather than after.+ image_bytes = await self._fetch_icon(url)+ if image_bytes is None:logger.error(- "[BOT-ICON] icon for %s is %d bytes, over the %d limit — "+ "[BOT-ICON] icon for %s is over the %d byte limit — ""leaving the current icon in place",agent_name,- len(image_bytes),_MAX_BOT_ICON_BYTES,)return@@ -2333,6 +2398,8 @@ class MattermostAdapter(PlatformAdapter):upload_url,headers={"Authorization": f"Bearer {token}"},files={"image": ("icon.png", data, "image/png")},+ allow_redirects=False,+ timeout=30,)if not r.ok:logger.error(@@ -2694,7 +2761,7 @@ class MattermostAdapter(PlatformAdapter):opts["login_id"] = login_idopts["password"] = password- return Driver(opts)+ return Driver(opts, client_cls=NoRedirectClient)def _mm_api(self, method: str, endpoint: str, data: dict[str, Any] | None = Nonediff --git a/core/switch_core/bridges/collaboration/mattermost/callback.py b/core/switch_core/bridges/collaboration/mattermost/callback.pyindex 146f5ab26..6d38781bb 100644--- a/core/switch_core/bridges/collaboration/mattermost/callback.py+++ b/core/switch_core/bridges/collaboration/mattermost/callback.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport hashlibimport hmacimport logging+from collections.abc import Sequencefrom dataclasses import dataclassfrom typing import Any@@ -227,7 +228,7 @@ def _button_name(control: Control) -> str:def read_press(- secret: str, body: dict[str, Any]+ verification_keys: Sequence[str], body: dict[str, Any]) -> Press | ActivityPress | InterruptPress | None:"""What a callback is asking for, or None if it is not ours to act on.@@ -254,9 +255,9 @@ def read_press(if not isinstance(switch, dict):return Noneif set(switch) == {"channel", "signature"}:- return _activity_press(secret, switch, body)+ return _activity_press(verification_keys, switch, body)if set(switch) == {"channel", "turn", "signature"}:- return _interrupt_press(secret, switch, body)+ return _interrupt_press(verification_keys, switch, body)# Nothing but what was signed. The signature covers the card and the# option, so a field beside them is one it does not vouch for — and a# reader added later would be reading an unsigned value out of a context@@ -274,8 +275,8 @@ def read_press(return Noneif not isinstance(signature, str) or not signature:return None- if not hmac.compare_digest(- signature, _sign(secret, _ANSWER_PURPOSE, f"{token}:{position}")+ if not _signed_by_any(+ verification_keys, signature, _ANSWER_PURPOSE, f"{token}:{position}"):logger.warning("Rejected a Mattermost action callback for request %s: the context "@@ -300,7 +301,7 @@ def read_press(def _activity_press(- secret: str, switch: dict[str, Any], body: dict[str, Any]+ verification_keys: Sequence[str], switch: dict[str, Any], body: dict[str, Any]) -> ActivityPress | None:"""A press on the button that opens a turn's tool calls, or None.@@ -314,7 +315,7 @@ def _activity_press(return Noneif not isinstance(signature, str) or not signature:return None- if not hmac.compare_digest(signature, _sign(secret, _ACTIVITY_PURPOSE, channel)):+ if not _signed_by_any(verification_keys, signature, _ACTIVITY_PURPOSE, channel):logger.warning("Rejected a Mattermost activity callback for channel %s: the ""context signature does not verify. Either it was not signed with "@@ -331,7 +332,7 @@ def _activity_press(def _interrupt_press(- secret: str, switch: dict[str, Any], body: dict[str, Any]+ verification_keys: Sequence[str], switch: dict[str, Any], body: dict[str, Any]) -> InterruptPress | None:"""A press on the button that stops the agent's current work, or None.@@ -350,8 +351,8 @@ def _interrupt_press(return Noneif not isinstance(signature, str) or not signature:return None- if not hmac.compare_digest(- signature, _sign(secret, _INTERRUPT_PURPOSE, f"{channel}:{turn}")+ if not _signed_by_any(+ verification_keys, signature, _INTERRUPT_PURPOSE, f"{channel}:{turn}"):logger.warning("Rejected a Mattermost stop callback for turn %s in channel %s: "@@ -416,6 +417,20 @@ def _presser(body: dict[str, Any]) -> tuple[str, str, str] | None:return user_id, post_id, channel_id+def _signed_by_any(+ verification_keys: Sequence[str], signature: str, purpose: str, subject: str+) -> bool:+ """Whether any of the bridge's keys signed this. A button posted before+ a key rotation carries the older key's signature and still works while+ that key is kept."""+ matched = False+ for key in verification_keys:+ matched = (+ hmac.compare_digest(signature, _sign(key, purpose, subject)) or matched+ )+ return matched++def _sign(secret: str, purpose: str, subject: str) -> str:message = f"{purpose}:{subject}".encode()return hmac.new(secret.encode(), message, hashlib.sha256).hexdigest()diff --git a/core/switch_core/bridges/collaboration/mattermost/http_client.py b/core/switch_core/bridges/collaboration/mattermost/http_client.pynew file mode 100644index 000000000..7e6e3968c--- /dev/null+++ b/core/switch_core/bridges/collaboration/mattermost/http_client.py@@ -0,0 +1,100 @@+"""The mattermostdriver client, without following redirects.++The server URL is the tenant's, so a redirect from it can point anywhere,+including an address the outbound policy would refuse. The driver's own client+calls `requests.get` / `post` / ... with their defaults, which follow+redirects, and offers no option to stop it. This replaces its one request+method with the same request made with `allow_redirects=False`, and raises the+same exception types for the same statuses.+"""++from __future__ import annotations++import logging+from typing import Any++import requests+from mattermostdriver.client import Client+from mattermostdriver.exceptions import (+ ContentTooLarge,+ FeatureDisabled,+ InvalidOrMissingParameters,+ MethodNotAllowed,+ NoAccessTokenProvided,+ NotEnoughPermissions,+ ResourceNotFound,+)++logger = logging.getLogger(__name__)++_ERRORS_BY_STATUS: dict[int, type[requests.HTTPError]] = {+ 400: InvalidOrMissingParameters,+ 401: NoAccessTokenProvided,+ 403: NotEnoughPermissions,+ 404: ResourceNotFound,+ 405: MethodNotAllowed,+ 413: ContentTooLarge,+ 501: FeatureDisabled,+}+++class MattermostRedirectRefused(requests.HTTPError):+ """The Mattermost server answered with a redirect, which is not followed."""+++class NoRedirectClient(Client): # type: ignore[misc]+ def make_request(+ self,+ method: str,+ endpoint: str,+ options: Any = None,+ params: Any = None,+ data: Any = None,+ files: Any = None,+ basepath: str | None = None,+ ) -> requests.Response:+ if basepath:+ url = "{scheme:s}://{url:s}:{port:d}{basepath:s}".format(+ scheme=self._options["scheme"],+ url=self._options["url"],+ port=self._options["port"],+ basepath=basepath,+ )+ else:+ url = self.url+ request_params: dict[str, Any] = {+ "headers": self.auth_header(),+ "verify": self._verify,+ "json": options if options is not None else {},+ "params": params if params is not None else {},+ "data": data if data is not None else {},+ "files": files,+ "timeout": self.request_timeout,+ "allow_redirects": False,+ }+ if self._auth is not None:+ request_params["auth"] = self._auth()++ response = requests.request(method.upper(), url + endpoint, **request_params)+ if response.is_redirect:+ raise MattermostRedirectRefused(+ f"The Mattermost server redirected {endpoint} to "+ f"{response.headers.get('Location')!r}. Switch does not follow "+ "redirects from a Mattermost server; set the bridge's url to "+ "the address the server answers on.",+ response=response,+ )+ try:+ response.raise_for_status()+ except requests.HTTPError as exc:+ try:+ body = exc.response.json()+ message = body.get("message", body)+ except ValueError:+ message = response.text+ logger.error("Mattermost %s %s failed: %s", method, endpoint, message)+ error = _ERRORS_BY_STATUS.get(exc.response.status_code)+ if error is not None:+ raise error(message) from None+ raise+ return responsediff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex 74f9273e3..a87b91873 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -10,7 +10,9 @@ from collections.abc import Awaitable, Callablefrom dataclasses import dataclass, field, replacefrom datetime import datetimefrom typing import Any, ClassVar, Literal, NoReturn+from urllib.parse import urlsplit+import aiohttpimport httpxfrom pydantic import BaseModel, Field, model_validatorfrom pydantic.json_schema import SkipJsonSchema@@ -36,6 +38,7 @@ from switch_core.bridges.collaboration.models import (Attachment,AttachmentFailure,BridgeConnectionConfig,+ BridgeCredentialError,ChannelType,DirectoryUser,InboundAgentJoin,@@ -244,6 +247,9 @@ class SlackConnectionConfig(BridgeConnectionConfig):# A turn whose end never arrives — the agent died, the session was dropped —# leaves its stream open with nothing to close it. Far more than this many at# once is a bridge holding turns nobody is waiting on, so the oldest goes.+# Where Slack serves private files from, commercial and GovSlack.+_SLACK_FILE_DOMAINS = ("slack.com", "slack-gov.com")+_MAX_OPEN_STREAMS = 100# Far above the open-stream bound on purpose. An entry here is what stops a@@ -351,11 +357,47 @@ class SlackAdapter(PlatformAdapter):# Every Slack bridge in this process shares one, because resolving a# mention that crossed a workspace boundary means reading a group another- # bridge minted. Rebind it to a fresh instance to isolate a test.+ # bridge minted; the directory keeps each tenant's apart. Rebind it to a+ # fresh instance to isolate a test.agent_group_directory: ClassVar[SlackAgentGroupDirectory] = (SlackAgentGroupDirectory())+ @classmethod+ def claimed_workspace(cls, connection_config: dict[str, object]) -> str | None:+ return f"Slack workspace {connection_config['workspace_id']}"++ @classmethod+ async def verify_credentials(cls, connection_config: dict[str, object]) -> None:+ """Check the bot token works and belongs to the configured workspace.++ `workspace_id` is what a workspace is claimed by, so it has to be the+ token's workspace and not merely a value someone typed. On an+ Enterprise Grid org it may name the org rather than the workspace.+ """+ config = SlackConnectionConfig.model_validate(connection_config)+ try:+ auth = await AsyncWebClient(token=config.bot_token).auth_test()+ except SlackApiError as exc:+ raise BridgeCredentialError(+ f"Slack refused the bot token: {exc.response.get('error', exc)}"+ ) from exc+ except (aiohttp.ClientError, TimeoutError) as exc:+ raise BridgeCredentialError(+ f"Could not reach Slack to check the bot token: "+ f"{exc or type(exc).__name__}. Try again."+ ) from exc+ authenticated = {+ str(auth.get("team_id") or ""),+ str(auth.get("enterprise_id") or ""),+ } - {""}+ if config.workspace_id not in authenticated:+ raise BridgeCredentialError(+ f"The bot token belongs to Slack workspace "+ f"{auth.get('team_id')}, not {config.workspace_id}. Set "+ "workspace_id to the workspace the app is installed in."+ )+def __init__(self, *, config: SlackConnectionConfig) -> None:super().__init__()self._config = config@@ -364,6 +406,7 @@ class SlackAdapter(PlatformAdapter):self._bot_user_id: str = ""self._bot_id: str = ""self._team_id: str = ""+ self._tenant_id: str | None = Noneself._user_cache: dict[str, SlackUser] = {}self._channel_name_cache: dict[str, str] = {}self._seen_ts: OrderedDict[str, None] = OrderedDict()@@ -497,6 +540,17 @@ class SlackAdapter(PlatformAdapter):await self._socket_client.connect()logger.info("Slack Socket Mode connected")+ def set_tenant_id(self, tenant_id: str) -> None:+ self._tenant_id = tenant_id++ def _directory_tenant(self) -> str:+ if self._tenant_id is None:+ raise RuntimeError(+ "Slack adapter used the shared agent group directory before "+ "set_tenant_id() was called"+ )+ return self._tenant_id+async def stop(self) -> None:if self._socket_client:try:@@ -505,7 +559,8 @@ class SlackAdapter(PlatformAdapter):passself._socket_client = Noneself._web_client = None- self.agent_group_directory.forget(self._team_id)+ if self._tenant_id is not None:+ self.agent_group_directory.forget(self._tenant_id, self._team_id)logger.info("Slack adapter stopped")# ── Messaging ────────────────────────────────────────────────────────────@@ -2268,7 +2323,9 @@ class SlackAdapter(PlatformAdapter):await self._web_client.usergroups_disable(usergroup=group_id)self._agent_group_ids.pop(folded, None)self._agent_group_names.pop(group_id, None)- self.agent_group_directory.discard(self._team_id, group_id)+ self.agent_group_directory.discard(+ self._directory_tenant(), self._team_id, group_id+ )self._agent_groups_disabled[folded] = group_idlogger.info("Disabled Slack user group %s for agent %s", group_id, agent_name)@@ -2413,7 +2470,9 @@ class SlackAdapter(PlatformAdapter):def _remember_agent_group(self, group_id: str, agent_name: str) -> None:self._agent_group_ids[agent_name.casefold()] = group_idself._agent_group_names[group_id] = agent_name- self.agent_group_directory.add(self._team_id, group_id, agent_name)+ self.agent_group_directory.add(+ self._directory_tenant(), self._team_id, group_id, agent_name+ )@staticmethoddef _usergroup_handle(agent_name: str) -> str:@@ -2491,7 +2550,9 @@ class SlackAdapter(PlatformAdapter):else:self._remember_agent_group(group_id, name)- self.agent_group_directory.replace(self._team_id, self._agent_group_names)+ self.agent_group_directory.replace(+ self._directory_tenant(), self._team_id, self._agent_group_names+ )self._agent_groups_loaded = Truelogger.info("Loaded %d Slack agent user groups (%d disabled, %d other groups seen)",@@ -3040,7 +3101,18 @@ class SlackAdapter(PlatformAdapter):return attachments, failuresasync def _download_file(self, url: str) -> bytes:- """Fetch a Slack private file URL with the bot token, returning bytes."""+ """Fetch a Slack private file URL with the bot token, returning bytes.++ Refuses any host but Slack's own: the request carries the bot token,+ and the URL is read out of an event rather than built here.+ """+ parts = urlsplit(url)+ host = (parts.hostname or "").lower()+ if parts.scheme != "https" or not any(+ host == domain or host.endswith(f".{domain}")+ for domain in _SLACK_FILE_DOMAINS+ ):+ raise ValueError(f"{url!r} is not a Slack file URL")async with httpx.AsyncClient() as client:resp = await client.get(url,@@ -3262,7 +3334,7 @@ class SlackAdapter(PlatformAdapter):group_id = match.group(1)agent_name = self._agent_group_names.get(group_id- ) or self.agent_group_directory.resolve(group_id)+ ) or self.agent_group_directory.resolve(self._directory_tenant(), group_id)if agent_name:return f"@{agent_name}"label = match.group(2)diff --git a/core/switch_core/bridges/collaboration/slack/agent_groups.py b/core/switch_core/bridges/collaboration/slack/agent_groups.pyindex c864399e9..02ed3e685 100644--- a/core/switch_core/bridges/collaboration/slack/agent_groups.py+++ b/core/switch_core/bridges/collaboration/slack/agent_groups.py@@ -4,7 +4,7 @@ from collections.abc import Mappingclass SlackAgentGroupDirectory:- """Agent user group id → agent name, pooled across every Slack workspace.+ """Agent user group id → agent name, pooled across a tenant's Slack workspaces.A workspace bot token lists only that workspace's user groups, so eachbridge mints and learns its own group per agent. An Enterprise Grid@@ -14,28 +14,43 @@ class SlackAgentGroupDirectory:that resolves a user group by id, which leaves the bridge that created itas the only place its meaning exists.+ Pooled per tenant, never across them: the process runs every tenant's+ bridges, and a group another tenant's bridge minted names an agent this+ tenant cannot address. Two tenants can also connect workspaces of the same+ Grid org, so the workspace boundary alone would not keep them apart.+Contributions are kept per workspace so a bridge reloading or shutting downwithdraws its own without disturbing anyone else's."""def __init__(self) -> None:- self._by_workspace: dict[str, dict[str, str]] = {}+ self._by_tenant: dict[str, dict[str, dict[str, str]]] = {}- def replace(self, workspace_id: str, agent_names: Mapping[str, str]) -> None:+ def replace(+ self, tenant_id: str, workspace_id: str, agent_names: Mapping[str, str]+ ) -> None:"""Publish a workspace's whole set, dropping what it published before."""- self._by_workspace[workspace_id] = dict(agent_names)-- def add(self, workspace_id: str, group_id: str, agent_name: str) -> None:- self._by_workspace.setdefault(workspace_id, {})[group_id] = agent_name-- def discard(self, workspace_id: str, group_id: str) -> None:- self._by_workspace.get(workspace_id, {}).pop(group_id, None)-- def forget(self, workspace_id: str) -> None:- self._by_workspace.pop(workspace_id, None)-- def resolve(self, group_id: str) -> str | None:- for groups in self._by_workspace.values():+ self._by_tenant.setdefault(tenant_id, {})[workspace_id] = dict(agent_names)++ def add(+ self, tenant_id: str, workspace_id: str, group_id: str, agent_name: str+ ) -> None:+ workspaces = self._by_tenant.setdefault(tenant_id, {})+ workspaces.setdefault(workspace_id, {})[group_id] = agent_name++ def discard(self, tenant_id: str, workspace_id: str, group_id: str) -> None:+ self._by_tenant.get(tenant_id, {}).get(workspace_id, {}).pop(group_id, None)++ def forget(self, tenant_id: str, workspace_id: str) -> None:+ workspaces = self._by_tenant.get(tenant_id)+ if workspaces is None:+ return+ workspaces.pop(workspace_id, None)+ if not workspaces:+ del self._by_tenant[tenant_id]++ def resolve(self, tenant_id: str, group_id: str) -> str | None:+ for groups in self._by_tenant.get(tenant_id, {}).values():agent_name = groups.get(group_id)if agent_name is not None:return agent_namediff --git a/core/switch_core/bridges/collaboration/slack/install.py b/core/switch_core/bridges/collaboration/slack/install.pyindex 09beb5119..522ebbf9c 100644--- a/core/switch_core/bridges/collaboration/slack/install.py+++ b/core/switch_core/bridges/collaboration/slack/install.py@@ -21,6 +21,7 @@ from collections.abc import Mappingfrom typing import Any, ClassVarfrom urllib.parse import parse_qsl, urlencode+import aiohttpfrom slack_sdk.errors import SlackApiErrorfrom slack_sdk.signature import SignatureVerifierfrom slack_sdk.web.async_client import AsyncWebClient@@ -205,6 +206,10 @@ class SlackAppInstaller(MessagingAppInstaller):async def revoke(self, *, bot_token: str) -> None:try:response = await AsyncWebClient(token=bot_token).auth_revoke()+ except (aiohttp.ClientError, TimeoutError) as error:+ raise MessagingInstallError(+ f"Could not reach Slack to revoke the bot token: {error!r}"+ ) from errorexcept SlackApiError as error:reason = error.response.get("error", "")if reason in _ALREADY_DEAD:diff --git a/core/switch_core/clients/client_lifecycle_service.py b/core/switch_core/clients/client_lifecycle_service.pyindex 8a6f6c74a..d89535f07 100644--- a/core/switch_core/clients/client_lifecycle_service.py+++ b/core/switch_core/clients/client_lifecycle_service.py@@ -23,6 +23,10 @@ from switch_core.tenant_context import no_tenant, tenant_scopelogger = logging.getLogger(__name__)+class TenantIsolationNotInForce(Exception):+ """A second tenant was asked for on a deployment that cannot keep tenants apart."""++class ClientLifecycleService:def __init__(self,@@ -33,8 +37,10 @@ class ClientLifecycleService:client_factory: ClientFactory,session_factory: async_sessionmaker[AsyncSession],config: SwitchConfig,+ tenants_isolated: bool,) -> None:self._provisioning = provisioning+ self._tenants_isolated = tenants_isolatedself._client_store = client_storeself._tenant_store = tenant_storeself._client_factory = client_factory@@ -140,6 +146,14 @@ class ClientLifecycleService:created, and to nothing else. The id is generated here rather than bythe database for that reason."""+ if not self._tenants_isolated:+ raise TenantIsolationNotInForce(+ "This server is not isolating tenants: its database connection is "+ "not subject to the row-level-security policies, and it runs only "+ "because DB_REQUIRE_RESTRICTED_ROLE is false, which allows a single "+ "workspace. Connect it as the restricted runtime role before "+ "creating another."+ )tenant = Tenant(id=str(uuid.uuid4()), name=name, slug=slug)async with tenant_session(self._session_factory, tenant.id) as session:await self._tenant_store.create(session, tenant)diff --git a/core/switch_core/config.py b/core/switch_core/config.pyindex d976e4f6e..7242de80a 100644--- a/core/switch_core/config.py+++ b/core/switch_core/config.py@@ -2,6 +2,7 @@ import osimport reimport sslimport uuid+from functools import cached_propertyfrom pathlib import Pathfrom typing import Literalfrom urllib.parse import urlsplit@@ -9,6 +10,9 @@ from urllib.parse import urlsplitfrom pydantic import AliasChoices, Field, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDict+from switch_core.keys import Keyring+from switch_core.outbound import OutboundPolicy+# A Postgres time value: a bare count of milliseconds, or a count with a unit._PG_INTERVAL_RE = re.compile(r"^\d+\s*(us|ms|s|min|h|d)?$")@@ -56,6 +60,12 @@ class SwitchConfig(BaseSettings):db_owner_user: str | None = Nonedb_owner_password: str | None = None+ # Apply migrations and re-issue grants at boot. Turn off where a separate+ # step runs `switch-migrate` as the owner before the server starts (the+ # Helm chart's init container), so the serving process never holds the+ # owner's password. Boot then only checks the schema is at head.+ db_migrate_on_boot: bool = True+# Refuse to serve when the runtime connection is not actually subject to# the policies — a superuser, a `BYPASSRLS` role, or the owner of the# scoped tables. On by default because the failure it catches is silent: a@@ -63,9 +73,11 @@ class SwitchConfig(BaseSettings):# like one that is, right up until a second customer reads the first's# rooms.#- # Set false only for a deployment that has not created its runtime role- # yet. Boot then logs at `error` on every start, because that is a- # deployment with no tenant isolation in it.+ # Set false only for a single-tenant deployment that has not created its+ # runtime role yet. Boot then logs at `error` on every start, because that+ # is a deployment with no tenant isolation in it. It keeps to one+ # workspace: refused with open sign-up, refused at boot once more than one+ # is stored, and no workspace can be created while it runs.db_require_restricted_role: bool = True# The server half of every member's `@localpart:server` id. Not a@@ -79,14 +91,31 @@ class SwitchConfig(BaseSettings):)agent_registration_token: str- # JWT auth- jwt_secret_key: str+ # The server's master keys, `<id>:<secret>` comma-separated, current+ # first. Every signing and encryption key is derived from these, one per+ # purpose; older entries only open what they encrypted or signed. See+ # `keys.py` and docs/old/key-rotation.md.+ secret_keys: str+ # Legacy: the one secret everything used before SECRET_KEYS. Set, it opens+ # stored values and verifies sessions and signatures made with it; boot+ # re-encrypts those values under the current key. Remove it once that has+ # run and whatever it signed may stop working.+ jwt_secret_key: str | None = None++ # Private hosts Switch may reach at a URL a tenant or agent supplied (a+ # Mattermost server, an OpenCode server, an agent icon): comma-separated+ # hostnames and CIDRs. Anything else that is not a public address is+ # refused. Link-local and metadata addresses are refused even when listed.+ # See `outbound.py`.+ outbound_allowed_private_hosts: str = ""# Gateway admin seedgateway_admin_email: strgateway_admin_password: str- # OIDC (optional — enables OAuth token validation on the MCP server)+ # OIDC (optional — enables OAuth token validation on the MCP server).+ # The audience is required with the issuer: without it, a token the same+ # IdP minted for any other application would be accepted here.oauth_issuer_url: str | None = Noneoauth_audience: str | None = Noneoauth_verify_issuer: bool = True@@ -134,10 +163,10 @@ class SwitchConfig(BaseSettings):gateway_oidc_require_email_verified: bool = True# Lets the password login path be disabled (OIDC-only) without code changes.gateway_password_login_enabled: bool = True- # Sets the Secure flag on the switch_auth cookie. Defaults to False so local- # dev over plain HTTP keeps working; deployments serving over HTTPS must set- # this true so the JWT session cookie is never sent over an insecure channel.- gateway_cookie_secure: bool = False+ # Sets the Secure flag on the gateway's cookies (the switch_auth session+ # and the OIDC sign-in cookie), so they are never sent over plain HTTP.+ # Only a local stack served over http:// should turn it off.+ gateway_cookie_secure: bool = True# Off by default: a person who belongs to more than one tenant and has not# selected one on their session gets the same 403 a single-tenant@@ -725,6 +754,44 @@ class SwitchConfig(BaseSettings):)return self+ @model_validator(mode="after")+ def _validate_secret_keys(self) -> "SwitchConfig":+ Keyring.parse(self.secret_keys, legacy_secret=self.jwt_secret_key)+ return self++ @cached_property+ def keyring(self) -> Keyring:+ return Keyring.parse(self.secret_keys, legacy_secret=self.jwt_secret_key)++ @model_validator(mode="after")+ def _validate_oauth_audience(self) -> "SwitchConfig":+ if self.oauth_issuer_url and not self.oauth_audience:+ raise ValueError(+ "OAUTH_AUDIENCE is required when OAUTH_ISSUER_URL is set: "+ "without it, agent tokens are accepted whatever application "+ "the IdP issued them for."+ )+ return self++ @model_validator(mode="after")+ def _validate_db_require_restricted_role(self) -> "SwitchConfig":+ if not self.db_require_restricted_role and self.gateway_signup_mode == "open":+ raise ValueError(+ "DB_REQUIRE_RESTRICTED_ROLE=false cannot be combined with "+ "GATEWAY_SIGNUP_MODE=open: anyone may then create a workspace "+ "on a deployment that does not isolate them from each other."+ )+ return self++ @model_validator(mode="after")+ def _validate_outbound_allowed_private_hosts(self) -> "SwitchConfig":+ OutboundPolicy.parse(self.outbound_allowed_private_hosts)+ return self++ @property+ def outbound_policy(self) -> OutboundPolicy:+ return OutboundPolicy.parse(self.outbound_allowed_private_hosts)+@model_validator(mode="after")def _validate_db_user(self) -> "SwitchConfig":# `db_user` is the runtime role name, and `db/runtime_role.py` buildsdiff --git a/core/switch_core/crypto.py b/core/switch_core/crypto.pydeleted file mode 100644index c1326cdc5..000000000--- a/core/switch_core/crypto.py+++ /dev/null@@ -1,20 +0,0 @@-from __future__ import annotations--import base64-import hashlib--from cryptography.fernet import Fernet---def _derive_fernet_key(secret: str) -> bytes:- return base64.urlsafe_b64encode(hashlib.sha256(secret.encode()).digest())---def encrypt_token(plaintext: str, secret: str) -> str:- f = Fernet(_derive_fernet_key(secret))- return f.encrypt(plaintext.encode()).decode()---def decrypt_token(encrypted: str, secret: str) -> str:- f = Fernet(_derive_fernet_key(secret))- return f.decrypt(encrypted.encode()).decode()diff --git a/core/switch_core/db/audit.py b/core/switch_core/db/audit.pynew file mode 100644index 000000000..e0032104d--- /dev/null+++ b/core/switch_core/db/audit.py@@ -0,0 +1,83 @@+"""The tenant audit log: append an event in the caller's transaction, read it back.++Functions rather than an injected store because there is nothing to hold: each+call takes the session of the change it records, so the event commits or rolls+back with that change.+"""++from __future__ import annotations++from datetime import datetime+from enum import StrEnum+from typing import Any++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.db.models import AuditEvent+++class AuditAction(StrEnum):+ TENANT_CREATED = "tenant.created"+ INVITATION_CREATED = "invitation.created"+ INVITATION_REVOKED = "invitation.revoked"+ INVITATION_ACCEPTED = "invitation.accepted"+ MEMBER_JOINED_BY_DOMAIN = "member.joined_by_domain"+ MEMBER_ROLE_CHANGED = "member.role_changed"+ MEMBER_REMOVED = "member.removed"+ JOIN_DOMAIN_ADDED = "join_domain.added"+ JOIN_DOMAIN_REMOVED = "join_domain.removed"+ API_KEY_CREATED = "api_key.created"+ API_KEY_REVEALED = "api_key.revealed"+ API_KEY_DELETED = "api_key.deleted"+ BRIDGE_CREATED = "collaboration_bridge.created"+ BRIDGE_UPDATED = "collaboration_bridge.updated"+ BRIDGE_DEFAULT_SET = "collaboration_bridge.default_set"+ BRIDGE_DELETED = "collaboration_bridge.deleted"+ BRIDGE_IDENTITY_CLAIMED = "collaboration_bridge.identity_claimed"+ BRIDGE_IDENTITY_RELEASED = "collaboration_bridge.identity_released"+ MESSAGING_INSTALL_STARTED = "messaging_install.started"+ MESSAGING_INSTALL_CONNECTED = "messaging_install.connected"+ MESSAGING_INSTALL_DISCONNECTED = "messaging_install.disconnected"+++async def record_audit_event(+ session: AsyncSession,+ *,+ tenant_id: str,+ actor_user_id: str | None,+ action: AuditAction,+ target_type: str,+ target_id: str | None,+ details: dict[str, Any] | None,+) -> AuditEvent:+ """Add an event to `session`; it lands when the caller commits."""+ event = AuditEvent(+ tenant_id=tenant_id,+ actor_user_id=actor_user_id,+ action=action.value,+ target_type=target_type,+ target_id=target_id,+ details=details,+ )+ session.add(event)+ await session.flush()+ return event+++async def list_audit_events(+ session: AsyncSession,+ *,+ tenant_id: str,+ limit: int,+ before: datetime | None,+) -> list[AuditEvent]:+ """Newest first. Names its tenant as well as relying on the policy, for the+ reason `JoinDomainStore` gives."""+ query = select(AuditEvent).where(AuditEvent.tenant_id == tenant_id)+ if before is not None:+ query = query.where(AuditEvent.occurred_at < before)+ result = await session.execute(+ query.order_by(AuditEvent.occurred_at.desc(), AuditEvent.id.desc()).limit(limit)+ )+ return list(result.scalars().all())diff --git a/core/switch_core/db/encrypted_json.py b/core/switch_core/db/encrypted_json.pynew file mode 100644index 000000000..fe1b50412--- /dev/null+++ b/core/switch_core/db/encrypted_json.py@@ -0,0 +1,126 @@+"""A JSONB column whose whole value is encrypted at rest.++For connection settings — a collaboration bridge's or a server connector's —+which carry platform credentials (bot tokens, app passwords, a server+password) next to ordinary settings. Encrypting the whole value rather than+named fields means a credential field an adapter adds later is covered without+anyone remembering to list it.++The stored shape is ``{"_enc": "<encrypted value>"}``, encrypted by the+server's `Keyring`; the application only ever sees the decrypted dict. A value+without that shape predates encryption: it is returned as it is, and+`reencrypt_stale_values` rewrites such rows at boot, along with any encrypted+under a key that is no longer current.++The keyring is process-wide because a column type is: SQLAlchemy builds it once+with the model, long before any configuration exists. `configure` must run+before the first read or write, and either raises if it has not.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from sqlalchemy import func, or_, select+from sqlalchemy.dialects.postgresql import JSONB+from sqlalchemy.engine import Dialect+from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.orm import attributes+from sqlalchemy.types import TypeDecorator++from switch_core.keys import Keyring++logger = logging.getLogger(__name__)++_ENVELOPE_KEY = "_enc"+_keyring: Keyring | None = None+++class EncryptionNotConfiguredError(RuntimeError):+ pass+++def configure(keyring: Keyring) -> None:+ """Set the keyring encrypted columns are encrypted with."""+ global _keyring+ _keyring = keyring+++def _require_keyring() -> Keyring:+ if _keyring is None:+ raise EncryptionNotConfiguredError(+ "An encrypted column was read or written before "+ "switch_core.db.encrypted_json.configure() was called."+ )+ return _keyring+++def is_encrypted(value: Any) -> bool:+ return isinstance(value, dict) and set(value) == {_ENVELOPE_KEY}+++class EncryptedJSONB(TypeDecorator[dict[str, Any]]):+ impl = JSONB+ cache_ok = True++ def __init__(self) -> None:+ # `None` is SQL NULL, not the JSON `null` a plain JSONB column writes:+ # there is nothing to encrypt in an absent config.+ super().__init__(none_as_null=True)++ def process_bind_param(+ self, value: dict[str, Any] | None, dialect: Dialect+ ) -> dict[str, str] | None:+ if value is None:+ return None+ return {_ENVELOPE_KEY: _require_keyring().encrypt(json.dumps(value))}++ def process_result_value(+ self, value: Any, dialect: Dialect+ ) -> dict[str, Any] | None:+ if value is None:+ return None+ if is_encrypted(value):+ decrypted: dict[str, Any] = json.loads(+ _require_keyring().decrypt(value[_ENVELOPE_KEY])+ )+ return decrypted+ logger.warning(+ "Read a connection config that is not yet encrypted at rest; it "+ "will be encrypted the next time it is written or at next boot."+ )+ plain: dict[str, Any] = value+ return plain+++async def reencrypt_stale_values(+ session: AsyncSession, model: type[Any], column: str+) -> int:+ """Rewrite every row of `model` whose `column` is not encrypted under the+ current key: still plaintext, or encrypted with an older or legacy key.++ Runs on the caller's session, so under whatever tenant it is bound to —+ the boot fan-out calls it once per tenant. Returns how many rows it+ rewrote; the caller commits.+ """+ stored = model.__table__.c[column]+ current = _require_keyring().current_prefix()+ rows = await session.execute(+ select(model.id).where(+ func.jsonb_typeof(stored) == "object",+ or_(+ ~func.jsonb_exists(stored, _ENVELOPE_KEY),+ ~stored[_ENVELOPE_KEY].astext.startswith(current, autoescape=True),+ ),+ )+ )+ ids = list(rows.scalars())+ if not ids:+ return 0+ instances = await session.execute(select(model).where(model.id.in_(ids)))+ for instance in instances.scalars():+ attributes.flag_modified(instance, column)+ await session.flush()+ return len(ids)diff --git a/core/switch_core/db/key_rotation.py b/core/switch_core/db/key_rotation.pynew file mode 100644index 000000000..e17ba8730--- /dev/null+++ b/core/switch_core/db/key_rotation.py@@ -0,0 +1,94 @@+"""Re-encrypt stored secrets under the current key, at boot.++Every encrypted value carries the id of the key that encrypted it. After a+key is added to the front of `SECRET_KEYS`, or on the first boot after+`SECRET_KEYS` replaces `JWT_SECRET_KEY`, values under any other key are+rewritten here, so the older key can be removed once this has run.++The columns are listed here rather than discovered: each is a different shape+(a JSON envelope, a bare string), and a new encrypted column is a deliberate+addition this list should be part of.+"""++from __future__ import annotations++import logging+from typing import Any++from sqlalchemy import select, update+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.encrypted_json import reencrypt_stale_values+from switch_core.db.models import (+ ApiKey,+ CollaborationBridge,+ MessagingInstall,+ ServerConnector,+)+from switch_core.db.session_scope import tenant_session+from switch_core.keys import Keyring++logger = logging.getLogger(__name__)++_ENCRYPTED_JSON_COLUMNS: tuple[tuple[type[Any], str], ...] = (+ (CollaborationBridge, "connection_config"),+ (ServerConnector, "connection_config"),+)+_ENCRYPTED_TEXT_COLUMNS: tuple[tuple[type[Any], str], ...] = (+ (ApiKey, "encrypted_key"),+ (MessagingInstall, "encrypted_bot_token"),+)+++async def reencrypt_stale_text(+ session: AsyncSession, keyring: Keyring, model: type[Any], column: str+) -> int:+ """Rewrite each value of a string column not under the current key.++ Raises `UndecryptableError` for a value no key opens: that is a key+ removed too early, and continuing would leave a credential nothing can+ read while reporting the rotation done.+ """+ stored = model.__table__.c[column]+ rows = await session.execute(+ select(model.id, stored).where(+ stored.is_not(None),+ ~stored.startswith(keyring.current_prefix(), autoescape=True),+ )+ )+ count = 0+ for row_id, value in rows.all():+ await session.execute(+ update(model)+ .where(model.id == row_id)+ .values({column: keyring.encrypt(keyring.decrypt(value))})+ )+ count += 1+ return count+++async def reencrypt_stored_secrets(+ session_factory: async_sessionmaker[AsyncSession],+ keyring: Keyring,+ tenant_ids: list[str],+) -> None:+ """Bring every tenant's encrypted values onto the current key."""+ total = 0+ for tenant_id in tenant_ids:+ async with tenant_session(session_factory, tenant_id) as session:+ for model, column in _ENCRYPTED_JSON_COLUMNS:+ total += await reencrypt_stale_values(session, model, column)+ for model, column in _ENCRYPTED_TEXT_COLUMNS:+ total += await reencrypt_stale_text(session, keyring, model, column)+ await session.commit()+ if total:+ logger.warning(+ "Re-encrypted %d stored secret(s) under key %r. Older keys and "+ "JWT_SECRET_KEY are no longer needed to read stored values.",+ total,+ keyring.current.id,+ )+ else:+ logger.info(+ "Every stored secret is encrypted under key %r.", keyring.current.id+ )diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex 02658f66c..03b62fba1 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -26,6 +26,7 @@ from sqlalchemy.dialects.postgresql import JSONBfrom sqlalchemy.orm import Mapped, declared_attr, mapped_columnfrom switch_core.db.base import Base+from switch_core.db.encrypted_json import EncryptedJSONBfrom switch_core.db.notify_ddl import (CREATE_NOTIFY_FUNCTION,CREATE_NOTIFY_TRIGGER,@@ -259,6 +260,7 @@ class OidcIdentity(Base):class ApiKey(TenantScoped, Base):__tablename__ = "api_keys"__table_args__ = (+ Index("ix_api_keys_tenant_id", "tenant_id"),UniqueConstraint("id", "tenant_id", name="uq_api_keys_id_tenant"),)@@ -315,6 +317,7 @@ class Invitation(TenantScoped, Base):__tablename__ = "invitations"__table_args__ = (+ Index("ix_invitations_tenant_id", "tenant_id"),CheckConstraint("role IN ('owner', 'admin', 'member')", name="ck_invitations_role"),@@ -385,6 +388,46 @@ class TenantJoinDomain(TenantScoped, Base):)+class AuditEvent(TenantScoped, Base):+ """One security-relevant change in a tenant: who did what, to what, when.++ Written in the same transaction as the change it records wherever that+ change is made on the caller's session, so a change that rolls back+ leaves no event. Where a service commits the change on sessions of its+ own (registering or removing a bridge, disconnecting an install), the+ event is written after it succeeds, so it never describes a change that+ did not happen.++ Append-only for the runtime role: `grant_runtime_role` takes `UPDATE` and+ `DELETE` on this table back off it, so the process serving requests can+ add to the history but not rewrite it.++ `actor_user_id` carries no foreign key, so the history outlives the+ account; it is null when no signed-in person acted. `details` holds+ identifiers and field names, never secrets or the values of connection+ settings.++ `occurred_at` defaults to `clock_timestamp()`, not `now()`: two events in+ one transaction would otherwise share a timestamp, and the read pages back+ by it.+ """++ __tablename__ = "audit_events"+ __table_args__ = (+ Index("ix_audit_events_tenant_occurred_at", "tenant_id", "occurred_at"),+ )++ id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)+ occurred_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), server_default=func.clock_timestamp(), nullable=False+ )+ actor_user_id: Mapped[str | None] = mapped_column(Text, nullable=True)+ action: Mapped[str] = mapped_column(Text, nullable=False)+ target_type: Mapped[str] = mapped_column(Text, nullable=False)+ target_id: Mapped[str | None] = mapped_column(Text, nullable=True)+ details: Mapped[dict | None] = mapped_column(JSONB, nullable=True)++# ── Clients ────────────────────────────────────────────────────────────────────@@ -413,6 +456,7 @@ class Client(TenantScoped, Base):class ClientRoom(TenantScoped, Base):__tablename__ = "client_rooms"__table_args__ = (+ Index("ix_client_rooms_tenant_id", "tenant_id"),ForeignKeyConstraint(["tenant_id", "client_id"],["clients.tenant_id", "clients.id"],@@ -439,6 +483,14 @@ class Agent(TenantScoped, Base):__tablename__ = "agents"__table_args__ = (Index("ix_agents_parent_agent_id", "parent_agent_id"),+ # Deployment-wide, not per tenant: an OIDC sign-in resolves the agent+ # from its client id before any tenant is known.+ Index(+ "uq_agents_oauth_client_id",+ "oauth_client_id",+ unique=True,+ postgresql_where=text("oauth_client_id IS NOT NULL"),+ ),UniqueConstraint("tenant_id", "name", name="uq_agents_tenant_name"),UniqueConstraint("id", "tenant_id", name="uq_agents_id_tenant"),ForeignKeyConstraint(@@ -509,6 +561,7 @@ class Agent(TenantScoped, Base):class Tool(TenantScoped, Base):__tablename__ = "tools"__table_args__ = (+ Index("ix_tools_tenant_id", "tenant_id"),ForeignKeyConstraint(["tenant_id", "agent_id"],["agents.tenant_id", "agents.id"],@@ -533,6 +586,7 @@ class Tool(TenantScoped, Base):class Model(TenantScoped, Base):__tablename__ = "models"__table_args__ = (+ Index("ix_models_tenant_id", "tenant_id"),ForeignKeyConstraint(["tenant_id", "agent_id"],["agents.tenant_id", "agents.id"],@@ -575,12 +629,14 @@ agent_skills = Table(["skills.tenant_id", "skills.id"],name="fk_agent_skills_skill",),+ Index("ix_agent_skills_tenant_id", "tenant_id"),)class Skill(TenantScoped, Base):__tablename__ = "skills"__table_args__ = (+ Index("ix_skills_tenant_id", "tenant_id"),UniqueConstraint("id", "tenant_id", name="uq_skills_id_tenant"),ForeignKeyConstraint(["tenant_id", "owner_agent_id"],@@ -640,6 +696,7 @@ room_agents = Table(["agents.tenant_id", "agents.id"],name="fk_room_agents_agent",),+ Index("ix_room_agents_tenant_id", "tenant_id"),)room_skills = Table(@@ -664,6 +721,7 @@ room_skills = Table(["skills.tenant_id", "skills.id"],name="fk_room_skills_skill",),+ Index("ix_room_skills_tenant_id", "tenant_id"),)@@ -793,6 +851,7 @@ class RoomGroup(TenantScoped, Base):__tablename__ = "room_groups"__table_args__ = (+ Index("ix_room_groups_tenant_id", "tenant_id"),CheckConstraint("parent_group_id <> id", name="room_groups_no_self_parent"),UniqueConstraint("id", "tenant_id", name="uq_room_groups_id_tenant"),ForeignKeyConstraint(@@ -826,6 +885,7 @@ class RoomLink(TenantScoped, Base):__tablename__ = "room_links"__table_args__ = (+ Index("ix_room_links_tenant_id", "tenant_id"),CheckConstraint("source_room_id <> target_room_id", name="room_links_no_self"),ForeignKeyConstraint(["tenant_id", "source_room_id"],@@ -855,6 +915,7 @@ class RoomLink(TenantScoped, Base):class Task(TenantScoped, Base):__tablename__ = "tasks"__table_args__ = (+ Index("ix_tasks_tenant_id", "tenant_id"),ForeignKeyConstraint(["tenant_id", "room_id"],["rooms.tenant_id", "rooms.id"],@@ -919,6 +980,7 @@ room_references = Table(["references.tenant_id", "references.id"],name="fk_room_references_reference",),+ Index("ix_room_references_tenant_id", "tenant_id"),)room_documents = Table(@@ -943,12 +1005,14 @@ room_documents = Table(["documents.tenant_id", "documents.id"],name="fk_room_documents_document",),+ Index("ix_room_documents_tenant_id", "tenant_id"),)class Reference(TenantScoped, Base):__tablename__ = "references"__table_args__ = (+ Index("ix_references_tenant_id", "tenant_id"),UniqueConstraint("id", "tenant_id", name="uq_references_id_tenant"),)@@ -999,6 +1063,7 @@ class ReferenceType(TenantScoped, Base):class Document(TenantScoped, Base):__tablename__ = "documents"__table_args__ = (+ Index("ix_documents_tenant_id", "tenant_id"),Index("uq_documents_room_name","room_id",@@ -1056,6 +1121,7 @@ class Template(TenantScoped, Base):__tablename__ = "templates"__table_args__ = (+ Index("ix_templates_tenant_id", "tenant_id"),# Not widened to include the tenant: an owner belongs to one, so# scoping the name to the owner already scopes it to the tenant.UniqueConstraint("owner_id", "name", name="uq_templates_owner_name"),@@ -1124,6 +1190,7 @@ room_packages = Table(["packages.tenant_id", "packages.id"],name="fk_room_packages_package",),+ Index("ix_room_packages_tenant_id", "tenant_id"),)package_references = Table(@@ -1148,6 +1215,7 @@ package_references = Table(["references.tenant_id", "references.id"],name="fk_package_references_reference",),+ Index("ix_package_references_tenant_id", "tenant_id"),)package_documents = Table(@@ -1172,12 +1240,14 @@ package_documents = Table(["documents.tenant_id", "documents.id"],name="fk_package_documents_document",),+ Index("ix_package_documents_tenant_id", "tenant_id"),)class Package(TenantScoped, Base):__tablename__ = "packages"__table_args__ = (+ Index("ix_packages_tenant_id", "tenant_id"),UniqueConstraint("id", "tenant_id", name="uq_packages_id_tenant"),)@@ -1199,6 +1269,7 @@ class Package(TenantScoped, Base):class CollaborationBridge(TenantScoped, Base):__tablename__ = "collaboration_bridges"__table_args__ = (+ Index("ix_collaboration_bridges_tenant_id", "tenant_id"),# The bridge new rooms land on when no bridge is named. At most one row# per tenant may be true; this partial unique index is what actually# enforces that, so concurrent writers cannot produce two defaults.@@ -1219,7 +1290,9 @@ class CollaborationBridge(TenantScoped, Base):id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)type: Mapped[str] = mapped_column(Text, nullable=False)display_name: Mapped[str] = mapped_column(Text, nullable=False)- connection_config: Mapped[dict | None] = mapped_column(JSONB, nullable=True)+ connection_config: Mapped[dict | None] = mapped_column(+ EncryptedJSONB, nullable=True+ )client_id: Mapped[str] = mapped_column(Text, nullable=False)status: Mapped[str] = mapped_column(Text, nullable=False)agent_greetings_enabled: Mapped[bool] = mapped_column(@@ -1298,7 +1371,7 @@ class MessagingInstall(TenantScoped, Base):install is recorded and not yet serving.`encrypted_bot_token` uses the same key as every other credential this- schema stores (`crypto.encrypt_token` over the configured secret), so it+ schema stores (`Keyring.encrypt`, the at-rest key), so itis protected against a stolen dump and not against a compromised process.A per-tenant key is a stronger boundary and a later decision. It isnullable so that an install which has ended can keep its record without@@ -1313,6 +1386,7 @@ class MessagingInstall(TenantScoped, Base):__tablename__ = "messaging_installs"__table_args__ = (+ Index("ix_messaging_installs_tenant_id", "tenant_id"),Index("uq_messaging_installs_workspace","platform",@@ -1381,9 +1455,14 @@ class MessagingInstallState(TenantScoped, Base):is a bound on how long the platform's round trip may take; `consumed_at`is the fact of redemption, kept rather than deleted so an operator askingwhy a link stopped working can see it was used rather than lost.++ `decided_at` is the second single use. Redeeming the state does not claim+ the workspace: the callback asks whoever approved it to confirm which+ organisation it joins, and their Connect or Cancel is recorded here, once."""__tablename__ = "messaging_install_states"+ __table_args__ = (Index("ix_messaging_install_states_tenant_id", "tenant_id"),)id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)platform: Mapped[str] = mapped_column(Text, nullable=False)@@ -1397,6 +1476,9 @@ class MessagingInstallState(TenantScoped, Base):consumed_at: Mapped[str | None] = mapped_column(DateTime(timezone=True), nullable=True)+ decided_at: Mapped[str | None] = mapped_column(+ DateTime(timezone=True), nullable=True+ )class MessagingEventReceipt(TenantScoped, Base):@@ -1471,6 +1553,7 @@ class MessagingEventReceipt(TenantScoped, Base):class ServerConnector(TenantScoped, Base):__tablename__ = "server_connectors"__table_args__ = (+ Index("ix_server_connectors_tenant_id", "tenant_id"),ForeignKeyConstraint(["tenant_id", "api_key_id"],["api_keys.tenant_id", "api_keys.id"],@@ -1481,7 +1564,9 @@ class ServerConnector(TenantScoped, Base):id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)type: Mapped[str] = mapped_column(Text, nullable=False)display_name: Mapped[str] = mapped_column(Text, nullable=False)- connection_config: Mapped[dict | None] = mapped_column(JSONB, nullable=True)+ connection_config: Mapped[dict | None] = mapped_column(+ EncryptedJSONB, nullable=True+ )api_key_id: Mapped[str] = mapped_column(Text, nullable=False)status: Mapped[str] = mapped_column(Text, nullable=False)created_at: Mapped[str] = mapped_column(@@ -1495,6 +1580,7 @@ class ServerConnector(TenantScoped, Base):class ExternalUser(TenantScoped, Base):__tablename__ = "external_users"__table_args__ = (+ Index("ix_external_users_tenant_id", "tenant_id"),UniqueConstraint("bridge_id", "external_user_id"),UniqueConstraint("id", "tenant_id", name="uq_external_users_id_tenant"),ForeignKeyConstraint(@@ -1534,6 +1620,7 @@ class ExternalUserClaim(TenantScoped, Base):__tablename__ = "external_user_claims"__table_args__ = (+ Index("ix_external_user_claims_tenant_id", "tenant_id"),Index("ix_external_user_claims_user_id", "user_id"),ForeignKeyConstraint(["tenant_id", "external_user_id"],@@ -1577,6 +1664,7 @@ class AgentSession(TenantScoped, Base):__tablename__ = "agent_sessions"__table_args__ = (+ Index("ix_agent_sessions_tenant_id", "tenant_id"),Index("uq_agent_sessions_agent_room",text("agent_id"),@@ -1626,6 +1714,7 @@ class AgentRuntimeState(TenantScoped, Base):__tablename__ = "agent_runtime_states"__table_args__ = (+ Index("ix_agent_runtime_states_tenant_id", "tenant_id"),UniqueConstraint("agent_id", "room_id", name="uq_agent_runtime_states_agent_room"),@@ -1687,6 +1776,7 @@ class RoomRole(TenantScoped, Base):__tablename__ = "room_roles"__table_args__ = (+ Index("ix_room_roles_tenant_id", "tenant_id"),UniqueConstraint("room_id", "name", name="uq_room_roles_room_name"),UniqueConstraint("id", "tenant_id", name="uq_room_roles_id_tenant"),ForeignKeyConstraint(@@ -1734,6 +1824,7 @@ class RoleLease(TenantScoped, Base):__tablename__ = "role_leases"__table_args__ = (+ Index("ix_role_leases_tenant_id", "tenant_id"),UniqueConstraint("agent_id", name="uq_role_leases_agent"),Index("ix_role_leases_role_id", "role_id"),ForeignKeyConstraint(@@ -1785,6 +1876,7 @@ class BridgeMessageMap(TenantScoped, Base):__tablename__ = "bridge_message_map"__table_args__ = (+ Index("ix_bridge_message_map_tenant_id", "tenant_id"),UniqueConstraint("bridge_id", "transport_event_id"),UniqueConstraint("bridge_id", "external_post_id"),ForeignKeyConstraint(@@ -1981,6 +2073,7 @@ class MessageAttachment(TenantScoped, Base):__tablename__ = "message_attachments"__table_args__ = (+ Index("ix_message_attachments_tenant_id", "tenant_id"),Index("ix_message_attachments_message", "message_id"),ForeignKeyConstraint(["tenant_id", "message_id"],@@ -2020,6 +2113,7 @@ class DeliveryCursor(TenantScoped, Base):__tablename__ = "delivery_cursors"__table_args__ = (+ Index("ix_delivery_cursors_tenant_id", "tenant_id"),UniqueConstraint("agent_id", "room_id", name="uq_delivery_cursors_agent_room"),ForeignKeyConstraint(["tenant_id", "agent_id"],@@ -2478,6 +2572,7 @@ class UsageBudget(TenantScoped, Base):__tablename__ = "usage_budgets"__table_args__ = (+ Index("ix_usage_budgets_tenant_id", "tenant_id"),ForeignKeyConstraint(["tenant_id", "agent_id"],["agents.tenant_id", "agents.id"],diff --git a/core/switch_core/db/runtime_role.py b/core/switch_core/db/runtime_role.pyindex 05d87799f..afe02c908 100644--- a/core/switch_core/db/runtime_role.py+++ b/core/switch_core/db/runtime_role.py@@ -153,6 +153,12 @@ async def grant_runtime_role(owner: AsyncConnection, role: str) -> None:it is a statement about what this owner creates, and this owner createsonly this schema.+ `audit_events` is the one table the role may not change once written: it+ gets `SELECT` and `INSERT` there and nothing else, so a compromised or+ buggy process can add to a tenant's history but not rewrite it. The+ revoke follows the blanket grant on every boot, so the next boot puts it+ back if anything granted more in between.+No `CREATE` on the schema, and no ownership: the role is meant to beunable to alter the tables it reads, which is what keeps it subject totheir policies.@@ -161,6 +167,7 @@ async def grant_runtime_role(owner: AsyncConnection, role: str) -> None:for statement in (f"GRANT USAGE ON SCHEMA public TO {identifier}",f"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {identifier}",+ f"REVOKE UPDATE, DELETE ON audit_events FROM {identifier}",f"GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO {identifier}","REVOKE EXECUTE ON ALL FUNCTIONS IN SCHEMA public FROM PUBLIC",f"GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO {identifier}",diff --git a/core/switch_core/db/schema_version.py b/core/switch_core/db/schema_version.pynew file mode 100644index 000000000..17a83d90e--- /dev/null+++ b/core/switch_core/db/schema_version.py@@ -0,0 +1,38 @@+"""Refuse to serve on a schema this build's migrations have not brought to head.++For a server that does not migrate at boot (`DB_MIGRATE_ON_BOOT=false`): the+migration ran somewhere else, as the schema owner, and this process holds only+the runtime role. The check is what stops a server whose migration step was+skipped or failed from serving against tables it does not expect.+"""++from __future__ import annotations++from alembic.config import Config as AlembicConfig+from alembic.runtime.migration import MigrationContext+from alembic.script import ScriptDirectory+from sqlalchemy.engine import Connection+from sqlalchemy.ext.asyncio import AsyncEngine+++class SchemaNotAtHeadError(RuntimeError):+ """The database's Alembic revision is not this build's head."""+++def _current_heads(connection: Connection) -> set[str]:+ return set(MigrationContext.configure(connection).get_current_heads())+++async def require_schema_at_head(+ engine: AsyncEngine, alembic_cfg: AlembicConfig+) -> None:+ expected = set(ScriptDirectory.from_config(alembic_cfg).get_heads())+ async with engine.connect() as connection:+ current = await connection.run_sync(_current_heads)+ if current != expected:+ raise SchemaNotAtHeadError(+ f"the database is at revision {sorted(current) or 'none'} but this "+ f"build expects {sorted(expected)}. DB_MIGRATE_ON_BOOT is false, so "+ "migrations must run before the server starts (switch-migrate, as "+ "the schema owner)."+ )diff --git a/core/switch_core/db/stores/messaging_install_store.py b/core/switch_core/db/stores/messaging_install_store.pyindex 97479cfbf..feb1b50a5 100644--- a/core/switch_core/db/stores/messaging_install_store.py+++ b/core/switch_core/db/stores/messaging_install_store.py@@ -112,6 +112,42 @@ class MessagingInstallStore:)return state+ async def decide_state(+ self,+ session: AsyncSession,+ *,+ state_id: str,+ platform: str,+ window: timedelta,+ ) -> MessagingInstallState:+ """Record the approver's Connect or Cancel on a redeemed state, or raise.++ One statement for the same reason as `redeem_state`: two submissions+ of the same confirmation page must not both go through. Only a state+ redeemed within `window` can be decided.+ """+ now = datetime.now(UTC)+ result = await session.execute(+ update(MessagingInstallState)+ .where(+ MessagingInstallState.id == state_id,+ MessagingInstallState.tenant_id == require_tenant_id(),+ MessagingInstallState.platform == platform,+ MessagingInstallState.consumed_at.is_not(None),+ MessagingInstallState.consumed_at > now - window,+ MessagingInstallState.decided_at.is_(None),+ )+ .values(decided_at=now)+ .returning(MessagingInstallState)+ )+ state = result.scalars().one_or_none()+ if state is None:+ raise MessagingInstallStateError(+ "this install has already been confirmed or cancelled, or the "+ "confirmation has expired. Start the install again from Switch."+ )+ return state+async def record_install(self,session: AsyncSession,diff --git a/core/switch_core/db/tenant_lookup.py b/core/switch_core/db/tenant_lookup.pyindex b7f60ad10..c2420893c 100644--- a/core/switch_core/db/tenant_lookup.py+++ b/core/switch_core/db/tenant_lookup.py@@ -193,9 +193,9 @@ from switch_core.tenant_context import no_tenantclass TenantLookupError(RuntimeError):"""A lookup that must name at most one tenant named several.- Only reachable for a key that is not unique by constraint — today only- `agents.oauth_client_id`, which has no unique index. Raised rather than- resolved by picking one: a credential that resolves to two tenants is a+ Every key these lookups take is unique by constraint, so this is a+ guard against a schema that has drifted from the models rather than an+ expected answer. Raised rather than resolved by picking one: a credential that resolves to two tenants is aprovisioning fault, and guessing which one it meant is how a caller endsup authenticated into somebody else's data."""@@ -287,9 +287,8 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = (),purpose=("Which tenant an agent authenticating by OIDC belongs to. The "- "column carries no unique index, so this is the one lookup that "- "can legitimately answer twice; the caller refuses rather than "- "picking."+ "client id is unique across the deployment by index; the caller "+ "still refuses rather than picking if it ever answers twice."),),TenantLookup(diff --git a/core/switch_core/gateway/api_keys.py b/core/switch_core/gateway/api_keys.pyindex 11aa7d256..33fad3cf6 100644--- a/core/switch_core/gateway/api_keys.py+++ b/core/switch_core/gateway/api_keys.py@@ -9,7 +9,7 @@ from fastapi import APIRouter, Depends, HTTPExceptionfrom sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.config import SwitchConfig-from switch_core.crypto import decrypt_token, encrypt_token+from switch_core.db.audit import AuditAction, record_audit_eventfrom switch_core.db.models import ApiKey, Userfrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.gateway.auth import get_current_user@@ -77,11 +77,20 @@ async def create_api_key(key = ApiKey(user_id=user.id,key_hash=key_hash,- encrypted_key=encrypt_token(plaintext, config.jwt_secret_key),+ encrypted_key=config.keyring.encrypt(plaintext),label=req.label,type="registration",)await api_key_store.create(session, key)+ await record_audit_event(+ session,+ tenant_id=key.tenant_id,+ actor_user_id=user.id,+ action=AuditAction.API_KEY_CREATED,+ target_type="api_key",+ target_id=key.id,+ details={"label": key.label, "type": key.type},+ )await session.commit()logger.info("Created API key '%s' for user %s", req.label, user.email)@@ -110,7 +119,17 @@ async def reveal_api_key(if key.user_id != user.id:raise HTTPException(status_code=403, detail="Not authorized to reveal this key")- plaintext = decrypt_token(key.encrypted_key, config.jwt_secret_key)+ plaintext = config.keyring.decrypt(key.encrypted_key)+ await record_audit_event(+ session,+ tenant_id=key.tenant_id,+ actor_user_id=user.id,+ action=AuditAction.API_KEY_REVEALED,+ target_type="api_key",+ target_id=key.id,+ details={"label": key.label},+ )+ await session.commit()return RevealKeyResponse(key=plaintext)@@ -127,6 +146,15 @@ async def delete_api_key(if key.user_id != user.id:raise HTTPException(status_code=403, detail="Not authorized to delete this key")key_hash = key.key_hash+ await record_audit_event(+ session,+ tenant_id=key.tenant_id,+ actor_user_id=user.id,+ action=AuditAction.API_KEY_DELETED,+ target_type="api_key",+ target_id=key.id,+ details={"label": key.label, "type": key.type},+ )await api_key_store.delete(session, key_id)await session.commit()get_protocol().api_key_cache.invalidate(key_hash)diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.pyindex 75ba6e889..c2aa69b60 100644--- a/core/switch_core/gateway/app.py+++ b/core/switch_core/gateway/app.py@@ -53,6 +53,7 @@ from switch_core.gateway.rooms import router as rooms_routerfrom switch_core.gateway.template_runs import router as template_runs_routerfrom switch_core.gateway.templates import router as templates_routerfrom switch_core.gateway.tenants import router as tenants_router+from switch_core.keys import Purposefrom switch_core.room_service import RoomServicefrom switch_core.sessions.errors import SessionErrorfrom switch_core.sessions.http import session_error_response@@ -120,9 +121,12 @@ def create_gateway_app(# (`session`) is separate from the `switch_auth` auth cookie.app.add_middleware(SessionMiddleware,- secret_key=config.jwt_secret_key,+ # Current key only: this cookie lives for one login round trip, so a+ # rotation costs at most a login started in the minutes before it.+ secret_key=config.keyring.derive(Purpose.OIDC_LOGIN_COOKIE).hex(),same_site="lax",max_age=600,+ https_only=config.gateway_cookie_secure,)if config.gateway_oidc_enabled:register_oidc_client(config)diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.pyindex d2737cd85..c29eb70c3 100644--- a/core/switch_core/gateway/auth.py+++ b/core/switch_core/gateway/auth.py@@ -34,6 +34,7 @@ from switch_core.gateway.schemas import (SessionStateUser,TenantMembershipResponse,)+from switch_core.keys import Keyring, KeyringError, Purposefrom switch_core.logging_context import log_contextfrom switch_core.tenant_context import tenant_scope@@ -67,7 +68,7 @@ def verify_password(password: str, password_hash: str | None) -> bool:def create_jwt(- user_id: str, email: str, role: str, secret_key: str, tenant_id: str | None+ user_id: str, email: str, role: str, keyring: Keyring, tenant_id: str | None) -> str:"""Sign a session JWT. `tenant_id` is the caller's selected tenant, or`None` for a session that has not selected one yet (a fresh login, or a@@ -86,13 +87,18 @@ def create_jwt(+ datetime.timedelta(hours=JWT_EXPIRY_HOURS),"iat": datetime.datetime.now(datetime.UTC),}- return jwt.encode(payload, secret_key, algorithm=JWT_ALGORITHM)+ return jwt.encode(+ payload,+ keyring.derive(Purpose.SESSION),+ algorithm=JWT_ALGORITHM,+ headers={"kid": keyring.current.id},+ )def set_session_cookie(response: Response,user: User,- secret_key: str,+ keyring: Keyring,secure: bool,tenant_id: str | None,) -> None:@@ -108,7 +114,7 @@ def set_session_cookie(`secure` gates the Secure flag: True on HTTPS deployments so the JWT isnever sent over plain HTTP, False for local dev served over http://."""- token = create_jwt(user.id, user.email, user.role, secret_key, tenant_id)+ token = create_jwt(user.id, user.email, user.role, keyring, tenant_id)response.set_cookie(key="switch_auth",value=token,@@ -120,9 +126,30 @@ def set_session_cookie()-def decode_jwt(token: str, secret_key: str) -> dict:+def _session_key(token: str, keyring: Keyring) -> bytes | str:+ """The key a session token was signed with, named by its `kid`.++ A token with no `kid` was signed with `JWT_SECRET_KEY` before+ `SECRET_KEYS`, and verifies only while that is still set.+ """+ key_id = jwt.get_unverified_header(token).get("kid")+ if key_id is None:+ if keyring.legacy_secret is None:+ raise jwt.InvalidTokenError("session predates SECRET_KEYS")+ return keyring.legacy_secret+ if not isinstance(key_id, str):+ raise jwt.InvalidTokenError("malformed kid")try:- return jwt.decode(token, secret_key, algorithms=[JWT_ALGORITHM])+ return keyring.derive(Purpose.SESSION, key_id)+ except KeyringError as exc:+ raise jwt.InvalidTokenError(str(exc)) from exc+++def decode_jwt(token: str, keyring: Keyring) -> dict:+ try:+ return jwt.decode(+ token, _session_key(token, keyring), algorithms=[JWT_ALGORITHM]+ )except jwt.ExpiredSignatureError:raise HTTPException(status_code=401, detail="Token expired")except jwt.InvalidTokenError:@@ -145,7 +172,7 @@ async def _authenticate(token = request.cookies.get("switch_auth")if token is None:raise HTTPException(status_code=401, detail="Not authenticated")- payload = decode_jwt(token, config.jwt_secret_key)+ payload = decode_jwt(token, config.keyring)async with session_factory() as system_session:if not await user_store.exists(system_session, payload["sub"]):raise HTTPException(status_code=401, detail="User not found")diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.pyindex 5bfb0e194..0a460defa 100644--- a/core/switch_core/gateway/auth_routes.py+++ b/core/switch_core/gateway/auth_routes.py@@ -117,7 +117,7 @@ async def login(set_session_cookie(response,user,- config.jwt_secret_key,+ config.keyring,config.gateway_cookie_secure,await initial_tenant_claim(session_factory, user_store, user),)@@ -144,7 +144,7 @@ async def refresh(set_session_cookie(response,user,- config.jwt_secret_key,+ config.keyring,config.gateway_cookie_secure,request.state.tenant_id,)diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.pyindex 826261353..f4cf2cc5d 100644--- a/core/switch_core/gateway/collaborations.py+++ b/core/switch_core/gateway/collaborations.py@@ -11,6 +11,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.bridges.collaboration.adapter import DirectorySearchBusyfrom switch_core.bridges.collaboration.lifecycle_service import (+ BridgeClaimConflict,CollaborationBridgeLifecycleService,)from switch_core.bridges.collaboration.models import (@@ -19,7 +20,13 @@ from switch_core.bridges.collaboration.models import (BridgeStartRefused,DirectoryUser,)-from switch_core.db.models import CollaborationBridge, ExternalUser, User+from switch_core.db.audit import AuditAction, record_audit_event+from switch_core.db.models import (+ CollaborationBridge,+ ExternalUser,+ User,+ require_tenant_id,+)from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.messaging_install_store import MessagingInstallStore@@ -174,7 +181,7 @@ async def create_bridge(# Admin-only: a bridge is an unowned, workspace-wide integration holding# platform secrets, so there is no owner to scope to (unlike connectors,# whose authz is owner-or-admin) — registering one is an admin action.- _user: Annotated[User, Depends(require_tenant_admin)],+ user: Annotated[User, Depends(require_tenant_admin)],) -> BridgeDetail:# A shared bridge runs on this deployment's own app, which is in every# tenant's workspaces, so it is made only by installing the app — the one@@ -208,8 +215,21 @@ async def create_bridge(is_default = bridge.is_defaultif req.set_as_default:await bridge_store.set_default(session, bridge.id)- await session.commit()is_default = True+ await record_audit_event(+ session,+ tenant_id=bridge.tenant_id,+ actor_user_id=user.id,+ action=AuditAction.BRIDGE_CREATED,+ target_type="collaboration_bridge",+ target_id=bridge.id,+ details={+ "type": bridge.type,+ "display_name": bridge.display_name,+ "set_as_default": req.set_as_default,+ },+ )+ await session.commit()return await _detail(bridge, room_count=0, collab_lifecycle=collab_lifecycle, is_default=is_default@@ -225,13 +245,22 @@ async def set_default_bridge(collab_lifecycle: Annotated[CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)],- _user: Annotated[User, Depends(require_tenant_admin)],+ user: Annotated[User, Depends(require_tenant_admin)],) -> BridgeDetail:"""Nominate a bridge as the instance default, demoting the previous one."""try:bridge = await bridge_store.set_default(session, bridge_id)except ValueError as exc:raise HTTPException(status_code=404, detail=str(exc)) from exc+ await record_audit_event(+ session,+ tenant_id=bridge.tenant_id,+ actor_user_id=user.id,+ action=AuditAction.BRIDGE_DEFAULT_SET,+ target_type="collaboration_bridge",+ target_id=bridge.id,+ details=None,+ )await session.commit()rooms = await room_store.get_by_bridge(session, bridge_id)@@ -276,7 +305,7 @@ async def update_bridge(],# Admin-only for the same reason as registering one: a bridge is an unowned,# workspace-wide integration, so there is no owner to scope mutation to.- _user: Annotated[User, Depends(require_tenant_admin)],+ user: Annotated[User, Depends(require_tenant_admin)],) -> BridgeDetail:bridge = await bridge_store.get(session, bridge_id)if bridge is None:@@ -319,7 +348,9 @@ async def update_bridge(detail="event_delivery cannot be changed on an existing connection.",)try:- collab_lifecycle.validate_connection_config(bridge.type, merged)+ await collab_lifecycle.check_edited_connection_config(+ bridge_id=bridge_id, bridge_type=bridge.type, connection_config=merged+ )# Asked now rather than at the restart below, so an edit that would# point a shared bridge at a workspace this tenant never installed# into is refused instead of stored and then failing to start.@@ -333,9 +364,26 @@ async def update_bridge(raise HTTPException(status_code=422, detail=str(exc)) from excexcept BridgeStartRefused as exc:raise HTTPException(status_code=422, detail=str(exc)) from exc+ except (BridgeClaimConflict, BridgeCredentialError) as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from excbridge = await bridge_store.merge_connection_config(session, bridge_id, dict(payload.connection_config))+ await record_audit_event(+ session,+ tenant_id=bridge.tenant_id,+ actor_user_id=user.id,+ action=AuditAction.BRIDGE_UPDATED,+ target_type="collaboration_bridge",+ target_id=bridge_id,+ details={+ "agent_greetings_enabled": payload.agent_greetings_enabled,+ "channel_creation_enabled": payload.channel_creation_enabled,+ "connection_config_keys": sorted(payload.connection_config)+ if payload.connection_config is not None+ else None,+ },+ )await session.commit()# A running adapter holds the config it was built with, so a change only@@ -616,7 +664,12 @@ async def claim_bridge_identity(status_code=403,detail="Only an admin may claim a messaging identity for another user",)- if await user_store.get(session, target_user_id) is None:+ # Membership, not existence: `users` is deployment-wide, and a claim+ # names who the account is recognised as inside this tenant.+ if (+ await user_store.tenant_role(session, require_tenant_id(), target_user_id)+ is None+ ):raise HTTPException(status_code=404, detail="Switch user not found")external_user = await external_user_store.get_by_external_id(@@ -662,6 +715,15 @@ async def claim_bridge_identity()await external_user_store.claim(session, external_user, target_user_id)+ await record_audit_event(+ session,+ tenant_id=external_user.tenant_id,+ actor_user_id=user.id,+ action=AuditAction.BRIDGE_IDENTITY_CLAIMED,+ target_type="external_user",+ target_id=external_user.id,+ details={"bridge_id": bridge_id, "user_id": target_user_id},+ )await session.commit()return await _identity_summary(@@ -722,6 +784,15 @@ async def release_bridge_identity(status_code=404,detail="That user has no claim on this messaging account",)+ await record_audit_event(+ session,+ tenant_id=external_user.tenant_id,+ actor_user_id=user.id,+ action=AuditAction.BRIDGE_IDENTITY_RELEASED,+ target_type="external_user",+ target_id=external_user.id,+ details={"bridge_id": bridge_id, "user_id": target_user_id},+ )await session.commit()return await _identity_summary(session, external_user_store, user_store, external_user@@ -741,7 +812,7 @@ async def delete_bridge(],# Admin-only: deleting a bridge cascades into deleting every room on it, so# this is the most destructive operation on the router.- _user: Annotated[User, Depends(require_tenant_admin)],+ user: Annotated[User, Depends(require_tenant_admin)],) -> dict[str, bool]:bridge = await bridge_store.get(session, bridge_id)if bridge is None:@@ -767,8 +838,24 @@ async def delete_bridge()rooms = await room_store.get_by_bridge(session, bridge_id)+ tenant_id = bridge.tenant_id+ details = {+ "type": bridge.type,+ "display_name": bridge.display_name,+ "rooms_deleted": len(rooms),+ }for room in rooms:await room_service.delete_room(room.id)await collab_lifecycle.remove(bridge_id)+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=user.id,+ action=AuditAction.BRIDGE_DELETED,+ target_type="collaboration_bridge",+ target_id=bridge_id,+ details=details,+ )+ await session.commit()return {"ok": True}diff --git a/core/switch_core/gateway/messaging_installs.py b/core/switch_core/gateway/messaging_installs.pyindex d763bcf94..e2341a206 100644--- a/core/switch_core/gateway/messaging_installs.py+++ b/core/switch_core/gateway/messaging_installs.py@@ -19,6 +19,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.bridges.collaboration.install import MessagingInstallErrorfrom switch_core.bridges.collaboration.install_service import MessagingInstallService+from switch_core.db.audit import AuditAction, record_audit_eventfrom switch_core.db.models import User, require_tenant_idfrom switch_core.db.stores.messaging_install_store import MessagingInstallNotFoundfrom switch_core.gateway.auth import require_tenant_admin@@ -107,6 +108,15 @@ async def begin_install(except MessagingInstallError as failure:raise HTTPException(status_code=404, detail=str(failure)) from failure+ await record_audit_event(+ session,+ tenant_id=require_tenant_id(),+ actor_user_id=user.id,+ action=AuditAction.MESSAGING_INSTALL_STARTED,+ target_type="messaging_install",+ target_id=None,+ details={"platform": platform},+ )await session.commit()logger.info("Started a %s install for user %s", platform, user.id)return InstallStart(authorize_url=authorize_url)@@ -138,6 +148,7 @@ async def list_installs(@router.delete("/installs/{install_id}")async def disconnect_install(install_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],service: Annotated[MessagingInstallService | None, Depends(get_install_service)],user: Annotated[User, Depends(require_tenant_admin)],) -> InstalledApp:@@ -147,7 +158,8 @@ async def disconnect_install(at the platform and tears a bridge down, and holding this request'stransaction open across both would keep a row locked while somebody else'sAPI is slow. The service opens what it needs, in the order failure can be- recovered from.+ recovered from. The request's session is used only afterwards, to record+ the disconnect in the audit log.**Rooms that used the bridge become internal-only**, which is why this is adelete an operator has to ask for rather than anything inferred.@@ -164,5 +176,18 @@ async def disconnect_install(# which the operator needs to be told rather than left to guess.raise HTTPException(status_code=502, detail=str(failure)) from failure+ await record_audit_event(+ session,+ tenant_id=ended.tenant_id,+ actor_user_id=user.id,+ action=AuditAction.MESSAGING_INSTALL_DISCONNECTED,+ target_type="messaging_install",+ target_id=install_id,+ details={+ "platform": ended.platform,+ "external_workspace_id": ended.external_workspace_id,+ },+ )+ await session.commit()logger.info("User %s disconnected messaging install %s", user.id, install_id)return InstalledApp.model_validate(ended, from_attributes=True)diff --git a/core/switch_core/gateway/oidc_routes.py b/core/switch_core/gateway/oidc_routes.pyindex 156941842..7b0e35d14 100644--- a/core/switch_core/gateway/oidc_routes.py+++ b/core/switch_core/gateway/oidc_routes.py@@ -220,7 +220,7 @@ async def oidc_callback(set_session_cookie(response,user,- config.jwt_secret_key,+ config.keyring,config.gateway_cookie_secure,await initial_tenant_claim(session_factory, user_store, user),)diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 6ad2950a3..9cf1a007c 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -737,6 +737,9 @@ class SessionStateResponse(BaseModel):invite_email_enabled: bool+MAX_INVITATION_USES = 100++class InvitationCreateRequest(BaseModel):role: str = "member"# None mints a shareable link; set, the invitation is addressed to one@@ -746,7 +749,9 @@ class InvitationCreateRequest(BaseModel):# roughly 2.4e9 hours, so an unbounded value turns a bad request into a 500.# A year is well beyond any legitimate invitation's life.expires_in_hours: int = Field(default=168, gt=0, le=8760)- uses_remaining: int = Field(default=1, ge=1)+ # Capped so a shareable link cannot be made effectively unlimited: a link+ # that leaks keeps admitting strangers until it runs out.+ uses_remaining: int = Field(default=1, ge=1, le=MAX_INVITATION_USES)@field_validator("email")@classmethod@@ -798,6 +803,16 @@ class AddressedInvitationAcceptRequest(BaseModel):invitation_id: str+class AuditEventDetail(BaseModel):+ id: str+ occurred_at: str+ actor_user_id: str | None+ action: str+ target_type: str+ target_id: str | None+ details: dict[str, Any] | None++class JoinDomainDetail(BaseModel):domain: strcreated_by: strdiff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex 6b7ef191f..66f1b62f7 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -13,8 +13,12 @@ from sqlalchemy.exc import DBAPIError, IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.protocol.agent_core import AgentCore-from switch_core.clients.client_lifecycle_service import ClientLifecycleService+from switch_core.clients.client_lifecycle_service import (+ ClientLifecycleService,+ TenantIsolationNotInForce,+)from switch_core.config import SwitchConfig+from switch_core.db.audit import AuditAction, list_audit_events, record_audit_eventfrom switch_core.db.models import (Invitation,Tenant,@@ -87,6 +91,7 @@ from switch_core.gateway.invite_mail import (from switch_core.gateway.schemas import (AddressedInvitation,AddressedInvitationAcceptRequest,+ AuditEventDetail,BudgetCreateRequest,BudgetResponse,BudgetUpdateRequest,@@ -351,6 +356,8 @@ async def _provision_workspace(tenant = await client_lifecycle.create_tenant(name, slug)except TenantSlugTaken:continue+ except TenantIsolationNotInForce as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from excbreakif tenant is None:logger.error(@@ -368,6 +375,15 @@ async def _provision_workspace(await user_store.add_membership(session, tenant_id=tenant.id, user_id=caller.id, role="owner")+ await record_audit_event(+ session,+ tenant_id=tenant.id,+ actor_user_id=caller.id,+ action=AuditAction.TENANT_CREATED,+ target_type="tenant",+ target_id=tenant.id,+ details={"name": tenant.name, "slug": tenant.slug},+ )await session.commit()except Exception:logger.error(@@ -448,7 +464,7 @@ async def create_tenant(await user_store.record_last_tenant(session, user, tenant.id)await session.commit()set_session_cookie(- response, user, config.jwt_secret_key, config.gateway_cookie_secure, tenant.id+ response, user, config.keyring, config.gateway_cookie_secure, tenant.id)return TenantMembershipResponse(id=tenant.id, slug=tenant.slug, name=tenant.name, role="owner"@@ -487,7 +503,7 @@ async def switch_tenant(await user_store.record_last_tenant(session, user, tenant_id)await session.commit()set_session_cookie(- response, user, config.jwt_secret_key, config.gateway_cookie_secure, tenant_id+ response, user, config.keyring, config.gateway_cookie_secure, tenant_id)return _session_response(user)@@ -547,6 +563,19 @@ async def create_invitation(uses_remaining=req.uses_remaining,created_by=user.id,)+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=user.id,+ action=AuditAction.INVITATION_CREATED,+ target_type="invitation",+ target_id=invitation.id,+ details={+ "role": invitation.role,+ "email": invitation.email,+ "uses_remaining": invitation.uses_remaining,+ },+ )tenant = await session.get(Tenant, tenant_id)assert tenant is not Noneawait session.commit()@@ -782,13 +811,43 @@ async def list_invitations(return [_invitation_detail(i) for i in invitations][email protected]("/tenants/{tenant_id}/audit-events")+async def list_tenant_audit_events(+ tenant_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ _user: Annotated[User, Depends(require_tenant_admin)],+ limit: Annotated[int, Query(ge=1, le=200)] = 50,+ before: Annotated[datetime | None, Query()] = None,+) -> list[AuditEventDetail]:+ """The bound tenant's audit log, newest first. `owner`/`admin` only.++ Page back by passing the oldest `occurred_at` returned as `before`.+ """+ _require_bound_tenant(tenant_id)+ events = await list_audit_events(+ session, tenant_id=tenant_id, limit=limit, before=before+ )+ return [+ AuditEventDetail(+ id=event.id,+ occurred_at=event.occurred_at.isoformat(),+ actor_user_id=event.actor_user_id,+ action=event.action,+ target_type=event.target_type,+ target_id=event.target_id,+ details=event.details,+ )+ for event in events+ ]++@router.delete("/tenants/{tenant_id}/invitations/{invitation_id}")async def revoke_invitation(tenant_id: str,invitation_id: str,session: Annotated[AsyncSession, Depends(get_session)],invitation_store: Annotated[InvitationStore, Depends(get_invitation_store)],- _user: Annotated[User, Depends(require_tenant_admin)],+ user: Annotated[User, Depends(require_tenant_admin)],) -> InvitationDetail:"""Revoke an invitation of the bound tenant. `owner`/`admin` only."""_require_bound_tenant(tenant_id)@@ -796,6 +855,15 @@ 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+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=user.id,+ action=AuditAction.INVITATION_REVOKED,+ target_type="invitation",+ target_id=invitation.id,+ details=None,+ )await session.commit()return _invitation_detail(invitation)@@ -853,7 +921,7 @@ async def accept_invitation()set_session_cookie(- response, user, config.jwt_secret_key, config.gateway_cookie_secure, tenant_id+ response, user, config.keyring, config.gateway_cookie_secure, tenant_id)return TenantMembershipResponse(id=tenant.id, slug=tenant.slug, name=tenant.name, role=role@@ -888,6 +956,15 @@ async def _join_through(await user_store.add_membership(session, tenant_id=tenant_id, user_id=caller.id, role=role)+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=caller.id,+ action=AuditAction.INVITATION_ACCEPTED,+ target_type="invitation",+ target_id=invitation.id,+ details={"role": role},+ )# Only on the branch that actually joined someone. A caller who# was already a member takes the `else` below and has accepted# nothing — reporting it there would count re-clicking a link as@@ -1018,7 +1095,7 @@ async def accept_my_invitation(set_session_cookie(response,user,- config.jwt_secret_key,+ config.keyring,config.gateway_cookie_secure,req.tenant_id,)@@ -1092,6 +1169,15 @@ async def add_join_domain(raise HTTPException(status_code=409, detail=f"The workspace is already open to {domain}") from exc+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=user.id,+ action=AuditAction.JOIN_DOMAIN_ADDED,+ target_type="join_domain",+ target_id=row.domain,+ details=None,+ )await session.commit()return _join_domain_detail(row)@@ -1102,7 +1188,7 @@ async def remove_join_domain(domain: str,session: Annotated[AsyncSession, Depends(get_session)],join_domain_store: Annotated[JoinDomainStore, Depends(get_join_domain_store)],- _user: Annotated[User, Depends(require_tenant_admin)],+ user: Annotated[User, Depends(require_tenant_admin)],) -> None:"""Stop letting people at a domain join the bound tenant. `owner`/`admin`only, and any domain: closing a workspace needs no proof of anything.@@ -1114,6 +1200,15 @@ async def remove_join_domain(raise HTTPException(status_code=404, detail=f"The workspace is not open to {domain}") from exc+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=user.id,+ action=AuditAction.JOIN_DOMAIN_REMOVED,+ target_type="join_domain",+ target_id=domain.lower(),+ details=None,+ )await session.commit()@@ -1181,10 +1276,19 @@ async def join_tenant_by_domain(await user_store.add_membership(session, tenant_id=tenant_id, user_id=caller.id, role=role)+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=caller.id,+ action=AuditAction.MEMBER_JOINED_BY_DOMAIN,+ target_type="user",+ target_id=caller.id,+ details={"role": role, "domain": domain},+ )tenant, user = await _enter(session, tenant_id, caller, user_store)set_session_cookie(- response, user, config.jwt_secret_key, config.gateway_cookie_secure, tenant_id+ response, user, config.keyring, config.gateway_cookie_secure, tenant_id)return TenantMembershipResponse(id=tenant.id, slug=tenant.slug, name=tenant.name, role=role@@ -1215,7 +1319,7 @@ async def update_member_role(req: MemberUpdateRequest,session: Annotated[AsyncSession, Depends(get_session)],user_store: Annotated[UserStore, Depends(get_user_store)],- _admin: Annotated[User, Depends(require_tenant_admin)],+ admin: Annotated[User, Depends(require_tenant_admin)],is_owner: Annotated[bool, Depends(get_tenant_is_owner)],) -> MemberDetail:"""Change a member's role. `owner`/`admin` only.@@ -1245,6 +1349,16 @@ async def update_member_role(if await user_store.count_owners(session) <= 1:raise HTTPException(status_code=409, detail="Cannot demote the last owner")+ if membership.role != req.role:+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=admin.id,+ action=AuditAction.MEMBER_ROLE_CHANGED,+ target_type="user",+ target_id=user_id,+ details={"from": membership.role, "to": req.role},+ )membership.role = req.roleawait session.commit()@@ -1262,7 +1376,7 @@ async def remove_member(agent_store: Annotated[AgentStore, Depends(get_agent_store)],api_key_store: Annotated[ApiKeyStore, Depends(get_api_key_store)],protocol: Annotated[AgentCore, Depends(get_protocol)],- _admin: Annotated[User, Depends(require_tenant_admin)],+ admin: Annotated[User, Depends(require_tenant_admin)],is_owner: Annotated[bool, Depends(get_tenant_is_owner)],) -> dict[str, bool]:"""Remove a member from the bound tenant. `owner`/`admin` only.@@ -1318,6 +1432,15 @@ async def remove_member(for key in keys:await api_key_store.delete(session, key.id)+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=admin.id,+ action=AuditAction.MEMBER_REMOVED,+ target_type="user",+ target_id=user_id,+ details={"role": membership.role, "api_keys_deleted": len(keys)},+ )await session.delete(membership)await session.commit()diff --git a/core/switch_core/keys.py b/core/switch_core/keys.pynew file mode 100644index 000000000..c525b367b--- /dev/null+++ b/core/switch_core/keys.py@@ -0,0 +1,181 @@+"""The server's secret keys, and the per-purpose keys derived from them.++`SECRET_KEYS` holds one or more master keys, each with an id:+``"<id>:<secret>,<id>:<secret>"``. The first is current: everything new is+encrypted and signed with it. The rest are kept so what they encrypted or+signed still opens, until boot has re-encrypted the stored values and the+signed material has expired; then they can be removed. `docs/old/key-rotation.md`+is the runbook.++Nothing uses a master key directly. Each purpose gets its own key, derived+with HKDF under a label naming the purpose, so a key that leaks from one use+(a session-signing key, say) does not open another (stored credentials).++Encrypted values carry the id of the key that encrypted them, so a keyring+with several keys knows which one to use and can tell which values still need+re-encrypting.++`JWT_SECRET_KEY`, the single secret this replaces, is legacy: when set, it+still opens values and verifies signatures made before `SECRET_KEYS` existed,+exactly as they were made. Boot re-encrypts the stored values under the+current key; removing `JWT_SECRET_KEY` afterwards ends whatever it signed.+"""++from __future__ import annotations++import base64+import hashlib+import re+from dataclasses import dataclass+from enum import StrEnum++from cryptography.fernet import Fernet, InvalidToken+from cryptography.hazmat.primitives import hashes+from cryptography.hazmat.primitives.kdf.hkdf import HKDF++_KEY_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,32}$")+MIN_SECRET_LENGTH = 32++# `<prefix><key id>$<fernet token>`. A Fernet token is URL-safe base64, so it+# never contains `$`, and a legacy value (a bare token) never starts with this.+_ENCRYPTED_PREFIX = "k1$"+++class Purpose(StrEnum):+ SESSION = "gateway-session-jwt"+ OIDC_LOGIN_COOKIE = "gateway-oidc-login-cookie"+ AT_REST = "at-rest-encryption"+ INSTALL_STATE = "messaging-install-state"+ INSTALL_CONFIRM = "messaging-install-confirm"+ BRIDGE_CALLBACK = "collaboration-callback"+++class KeyringError(ValueError):+ """`SECRET_KEYS` is malformed, or a value names a key the keyring lacks."""+++class UndecryptableError(ValueError):+ """A stored value no key in the keyring opens."""+++@dataclass(frozen=True)+class MasterKey:+ id: str+ secret: bytes+++def _hkdf(secret: bytes, purpose: Purpose) -> bytes:+ return HKDF(+ algorithm=hashes.SHA256(),+ length=32,+ salt=None,+ info=f"switch:{purpose.value}".encode(),+ ).derive(secret)+++@dataclass(frozen=True)+class Keyring:+ keys: tuple[MasterKey, ...]+ legacy_secret: str | None++ @classmethod+ def parse(cls, value: str, *, legacy_secret: str | None) -> Keyring:+ keys: list[MasterKey] = []+ for raw in value.split(","):+ entry = raw.strip()+ if not entry:+ continue+ key_id, sep, secret = entry.partition(":")+ if not sep:+ raise KeyringError(+ "SECRET_KEYS entries are <id>:<secret>; one has no ':'."+ )+ if not _KEY_ID_RE.match(key_id):+ raise KeyringError(+ f"SECRET_KEYS key id {key_id!r} must be 1-32 letters, "+ "digits, '-' or '_'."+ )+ if len(secret) < MIN_SECRET_LENGTH:+ raise KeyringError(+ f"SECRET_KEYS key {key_id!r} is shorter than "+ f"{MIN_SECRET_LENGTH} characters."+ )+ if any(k.id == key_id for k in keys):+ raise KeyringError(f"SECRET_KEYS names key {key_id!r} twice.")+ keys.append(MasterKey(id=key_id, secret=secret.encode()))+ if not keys:+ raise KeyringError("SECRET_KEYS must name at least one key.")+ return cls(keys=tuple(keys), legacy_secret=legacy_secret or None)++ @property+ def current(self) -> MasterKey:+ return self.keys[0]++ def _key(self, key_id: str) -> MasterKey:+ for key in self.keys:+ if key.id == key_id:+ return key+ raise KeyringError(f"No key {key_id!r} in SECRET_KEYS.")++ def derive(self, purpose: Purpose, key_id: str | None = None) -> bytes:+ """The key for `purpose` under master key `key_id` (default: current)."""+ key = self.current if key_id is None else self._key(key_id)+ return _hkdf(key.secret, purpose)++ def verification_keys(self, purpose: Purpose) -> list[bytes]:+ """Every key a signature for `purpose` may have been made with: each+ master key's, current first. Legacy material is the caller's to add,+ because how the old secret signed differs by purpose."""+ return [_hkdf(key.secret, purpose) for key in self.keys]++ # ── Encryption at rest ──────────────────────────────────────────────────++ def _fernet(self, key_id: str) -> Fernet:+ return Fernet(base64.urlsafe_b64encode(self.derive(Purpose.AT_REST, key_id)))++ def encrypt(self, plaintext: str) -> str:+ token = self._fernet(self.current.id).encrypt(plaintext.encode()).decode()+ return f"{_ENCRYPTED_PREFIX}{self.current.id}${token}"++ def decrypt(self, value: str) -> str:+ if value.startswith(_ENCRYPTED_PREFIX):+ key_id, sep, token = value[len(_ENCRYPTED_PREFIX) :].partition("$")+ if not sep:+ raise UndecryptableError("Encrypted value is malformed.")+ try:+ fernet = self._fernet(key_id)+ except KeyringError as exc:+ raise UndecryptableError(+ f"Value was encrypted with key {key_id!r}, which is no "+ "longer in SECRET_KEYS."+ ) from exc+ try:+ return fernet.decrypt(token.encode()).decode()+ except InvalidToken as exc:+ raise UndecryptableError(+ f"Key {key_id!r} in SECRET_KEYS does not open this value; "+ "its secret has changed since it was written."+ ) from exc+ if self.legacy_secret is None:+ raise UndecryptableError(+ "Value predates SECRET_KEYS and JWT_SECRET_KEY is not set to open it."+ )+ legacy = Fernet(+ base64.urlsafe_b64encode(+ hashlib.sha256(self.legacy_secret.encode()).digest()+ )+ )+ try:+ return legacy.decrypt(value.encode()).decode()+ except InvalidToken as exc:+ raise UndecryptableError(+ "JWT_SECRET_KEY does not open this value."+ ) from exc++ def is_current(self, value: str) -> bool:+ """Whether `value` is encrypted with the current key."""+ return value.startswith(f"{_ENCRYPTED_PREFIX}{self.current.id}$")++ def current_prefix(self) -> str:+ """What every value encrypted with the current key starts with."""+ return f"{_ENCRYPTED_PREFIX}{self.current.id}$"diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 8e40c76c4..e2c49854e 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -15,6 +15,7 @@ import uvicornfrom alembic import command as alembic_commandfrom alembic.config import Config as AlembicConfigfrom fastapi.responses import JSONResponse+from sqlalchemy.exc import DBAPIErrorfrom sqlalchemy.ext.asyncio import (AsyncEngine,AsyncSession,@@ -86,19 +87,25 @@ from switch_core.clients.client_factory import ClientFactoryfrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.clients.command_consumer import CommandConsumerfrom switch_core.config import SwitchConfig, deprecated_env_names-from switch_core.crypto import encrypt_token+from switch_core.db import encrypted_jsonfrom switch_core.db.boot_lock import boot_lockfrom switch_core.db.engine import (create_engine_from_config,create_session_factory,create_unpooled_engine,)-from switch_core.db.models import TENANT_ZERO_ID, ApiKey, User+from switch_core.db.key_rotation import reencrypt_stored_secrets+from switch_core.db.models import (+ TENANT_ZERO_ID,+ ApiKey,+ User,+)from switch_core.db.runtime_role import (RuntimeRoleError,grant_runtime_role,verify_restricted_role,)+from switch_core.db.schema_version import require_schema_at_headfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_session_store import AgentSessionStorefrom switch_core.db.stores.agent_store import AgentStore@@ -314,25 +321,58 @@ async def _prepare_database(config: SwitchConfig) -> None:)-async def _check_tenant_isolation(config: SwitchConfig, engine: AsyncEngine) -> None:+_INSUFFICIENT_PRIVILEGE = "42501"+++async def _check_tenant_isolation(config: SwitchConfig, engine: AsyncEngine) -> bool:"""Refuse to serve on a connection the policies do not apply to.Before anything else touches the database, because the first thing thatdoes is the admin seeding, and a deployment that is not isolating tenantsshould not get as far as writing a row.++ Returns whether isolation is in force. False only with+ DB_REQUIRE_RESTRICTED_ROLE off, and then the server keeps to the one+ workspace it has: no further tenant may be created while it runs."""try:await verify_restricted_role(engine)except RuntimeRoleError as exc:if config.db_require_restricted_role:raise+ try:+ tenant_count = len(await all_tenant_ids(create_session_factory(engine)))+ except DBAPIError as count_error:+ if getattr(count_error.orig, "sqlstate", None) != _INSUFFICIENT_PRIVILEGE:+ raise+ # The role cannot run the lookups because boot had no owner+ # connection to grant them with. Nothing can resolve a tenant on+ # such a connection, let alone serve a second one, so the count is+ # not needed to keep tenants apart; the role check's own error+ # already names what is missing.+ logger.error(+ "Tenant isolation is NOT in force on this deployment, and the "+ "number of workspaces could not be checked: %s Continuing only "+ "because DB_REQUIRE_RESTRICTED_ROLE is false.",+ exc,+ )+ return False+ if tenant_count > 1:+ raise RuntimeRoleError(+ f"{exc} DB_REQUIRE_RESTRICTED_ROLE=false is only allowed on a "+ f"single-tenant deployment, and this one has {tenant_count} "+ "workspaces."+ ) from exclogger.error("Tenant isolation is NOT in force on this deployment: %s ""Continuing only because DB_REQUIRE_RESTRICTED_ROLE is false. ""Every row-level-security policy in this schema is inert, and any "- "second tenant onboarded here can read the first's data.",+ "second tenant onboarded here can read the first's data, so none "+ "can be created while it runs.",exc,)+ return False+ return Trueasync def run(config: SwitchConfig) -> None:@@ -342,8 +382,9 @@ async def run(config: SwitchConfig) -> None:# — see `main._migrate_and_grant`, which `main()` awaits first. Both use# the schema owner's connection where one is configured, and neither# belongs on the pooled application engine built below.+ encrypted_json.configure(config.keyring)engine = create_engine_from_config(config)- await _check_tenant_isolation(config, engine)+ tenants_isolated = await _check_tenant_isolation(config, engine)session_factory = create_session_factory(engine)# Wired here rather than inside the engine factory, so the database layer# keeps knowing nothing about observability. Unconditional: the listeners@@ -458,6 +499,7 @@ async def run(config: SwitchConfig) -> None:for tenant_id in tenant_ids:async with tenant_session(session_factory, tenant_id) as session:await resource_service.log_builtin_shadowing(session)+ await reencrypt_stored_secrets(session_factory, config.keyring, tenant_ids)# ── Provisioning ─────────────────────────────────────────────────────────provisioning: Provisioning = PostgresProvisioning(@@ -516,6 +558,7 @@ async def run(config: SwitchConfig) -> None:client_factory=client_factory,session_factory=session_factory,config=config,+ tenants_isolated=tenants_isolated,)# ── Collaboration bridge lifecycle ───────────────────────────────────────@@ -602,8 +645,9 @@ async def run(config: SwitchConfig) -> None:api_key_store=api_key_store,protocol=protocol,session_factory=session_factory,- encryption_secret=config.jwt_secret_key,+ keyring=config.keyring,telemetry=telemetry,+ outbound_policy=config.outbound_policy,)connector_lifecycle.register_connector_type("opencode", OpenCodeConnector, OpenCodeConnectionConfig@@ -647,7 +691,7 @@ async def run(config: SwitchConfig) -> None:installers=installers,lifecycle=collab_lifecycle,public_origin=config.messaging_public_url,- secret=config.jwt_secret_key,+ keyring=config.keyring,)# ── Gateway app ───────────────────────────────────────────────────────────@@ -1044,9 +1088,7 @@ async def _seed_agent_registration_bootstrap_key(token_hash = hashlib.sha256(config.agent_registration_token.encode()).hexdigest()- encrypted_key = encrypt_token(- config.agent_registration_token, config.jwt_secret_key- )+ encrypted_key = config.keyring.encrypt(config.agent_registration_token)# Filtered on this tenant as well as on the type, for the same reason# every other fan-out in this change is: `get_by_type` carries no@@ -1393,8 +1435,7 @@ async def _migrate_and_grant(config: SwitchConfig) -> None:`asyncio.to_thread`, on a worker thread that starts with no event loop ofits own, which is exactly what that inner `asyncio.run` needs."""- alembic_ini = Path(__file__).resolve().parent.parent / "alembic.ini"- alembic_cfg = AlembicConfig(str(alembic_ini))+ alembic_cfg = _alembic_config()async with boot_lock(config):await asyncio.to_thread(alembic_command.upgrade, alembic_cfg, "head")await _prepare_database(config)@@ -1404,6 +1445,27 @@ async def _migrate_and_grant(config: SwitchConfig) -> None:)+async def _check_schema_at_head(config: SwitchConfig) -> None:+ """Stand in for `_migrate_and_grant` on a server that does not migrate."""+ if config.db_owner_password is not None:+ logger.warning(+ "DB_OWNER_PASSWORD is set on a server with DB_MIGRATE_ON_BOOT=false, "+ "which never uses it. Remove it from this process's environment."+ )+ engine = create_async_engine(+ config.database_url, poolclass=NullPool, connect_args=config.db_connect_args+ )+ try:+ await require_schema_at_head(engine, _alembic_config())+ finally:+ await engine.dispose()+ logger.info("Database schema is at head; migrations were applied before boot")+++def _alembic_config() -> AlembicConfig:+ return AlembicConfig(str(Path(__file__).resolve().parent.parent / "alembic.ini"))++def migrate() -> None:"""Entry point for migrating a deployment without starting a server.@@ -1440,7 +1502,10 @@ def main() -> None:for warning in deprecated_env_names():logger.warning(warning)- asyncio.run(_migrate_and_grant(config))+ if config.db_migrate_on_boot:+ asyncio.run(_migrate_and_grant(config))+ else:+ asyncio.run(_check_schema_at_head(config))asyncio.run(run(config))diff --git a/core/switch_core/migrations/versions/3e9a6c2b7f14_unique_agent_oauth_client_id.py b/core/switch_core/migrations/versions/3e9a6c2b7f14_unique_agent_oauth_client_id.pynew file mode 100644index 000000000..0b1ee4d1c--- /dev/null+++ b/core/switch_core/migrations/versions/3e9a6c2b7f14_unique_agent_oauth_client_id.py@@ -0,0 +1,57 @@+"""agents.oauth_client_id unique across the deployment++An agent signing in with an OIDC token is identified by the token's client id+before any tenant is known, so the id has to name one agent deployment-wide.+Without a constraint two tenants could register the same one, and the+sign-in lookup would then refuse both. A partial unique index makes the second+registration fail instead; agents without an OAuth client are unaffected.++Revision ID: 3e9a6c2b7f14+Revises: a9e1c3f75b20+Create Date: 2026-10-01 00:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "3e9a6c2b7f14"+down_revision: str | None = "a9e1c3f75b20"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++INDEX = "uq_agents_oauth_client_id"+++def upgrade() -> None:+ duplicates = (+ op.get_bind()+ .execute(+ sa.text(+ "SELECT oauth_client_id FROM agents "+ "WHERE oauth_client_id IS NOT NULL "+ "GROUP BY oauth_client_id HAVING count(*) > 1"+ )+ )+ .scalars()+ .all()+ )+ if duplicates:+ raise RuntimeError(+ "Cannot make agents.oauth_client_id unique: these client ids are "+ f"held by more than one agent: {', '.join(duplicates)}. Clear the "+ "id on all but one agent each, then run the migration again."+ )+ op.create_index(+ INDEX,+ "agents",+ ["oauth_client_id"],+ unique=True,+ postgresql_where=sa.text("oauth_client_id IS NOT NULL"),+ )+++def downgrade() -> None:+ op.drop_index(INDEX, table_name="agents")diff --git a/core/switch_core/migrations/versions/5b8d2e6f0a41_tenant_id_indexes.py b/core/switch_core/migrations/versions/5b8d2e6f0a41_tenant_id_indexes.pynew file mode 100644index 000000000..9606cc4a9--- /dev/null+++ b/core/switch_core/migrations/versions/5b8d2e6f0a41_tenant_id_indexes.py@@ -0,0 +1,79 @@+"""index tenant_id on every tenant table that had no index leading with it++Each of these tables already had a tenant column, a foreign key to `tenants`+and a row-level-security policy filtering on it, but no index whose first+column is `tenant_id` (`uq_<table>_id_tenant` leads with `id`). A query+across one tenant's rows, the policy's filter on such a query, and the+foreign-key check when a tenant row is deleted were each a sequential scan of+the whole table, every tenant's rows included.++**Not `CONCURRENTLY`**, for the same reason as `b8f2d0c41e57`: revisions run+in a transaction, and these tables are small on every deployment today. A+deployment where one is not can build that index by hand first with+`CREATE INDEX CONCURRENTLY ix_<table>_tenant_id ON <table> (tenant_id)`, and+`IF NOT EXISTS` makes this a no-op for it.++Revision ID: 5b8d2e6f0a41+Revises: 9c2e7b4d1a63+Create Date: 2026-10-01 00:00:00.000000++"""++from collections.abc import Sequence++from alembic import op++revision: str = "5b8d2e6f0a41"+down_revision: str | None = "9c2e7b4d1a63"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++_TABLES = (+ "agent_runtime_states",+ "agent_sessions",+ "agent_skills",+ "api_keys",+ "bridge_message_map",+ "client_rooms",+ "collaboration_bridges",+ "delivery_cursors",+ "documents",+ "external_user_claims",+ "external_users",+ "invitations",+ "message_attachments",+ "messaging_install_states",+ "messaging_installs",+ "models",+ "package_documents",+ "package_references",+ "packages",+ "references",+ "role_leases",+ "room_agents",+ "room_documents",+ "room_groups",+ "room_links",+ "room_packages",+ "room_references",+ "room_roles",+ "room_skills",+ "server_connectors",+ "skills",+ "tasks",+ "templates",+ "tools",+ "usage_budgets",+)+++def upgrade() -> None:+ for table in _TABLES:+ op.execute(+ f'CREATE INDEX IF NOT EXISTS ix_{table}_tenant_id ON "{table}" (tenant_id)'+ )+++def downgrade() -> None:+ for table in _TABLES:+ op.execute(f"DROP INDEX IF EXISTS ix_{table}_tenant_id")diff --git a/core/switch_core/migrations/versions/9c2e7b4d1a63_install_state_decided_at.py b/core/switch_core/migrations/versions/9c2e7b4d1a63_install_state_decided_at.pynew file mode 100644index 000000000..d2f55d6b5--- /dev/null+++ b/core/switch_core/migrations/versions/9c2e7b4d1a63_install_state_decided_at.py@@ -0,0 +1,32 @@+"""messaging_install_states.decided_at, for the install confirmation step++An install's callback no longer claims the workspace on arrival; it asks the+approver to confirm the organisation first. `decided_at` records their Connect+or Cancel, set once by a conditional update.++Revision ID: 9c2e7b4d1a63+Revises: 3e9a6c2b7f14+Create Date: 2026-10-01 00:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "9c2e7b4d1a63"+down_revision: str | None = "3e9a6c2b7f14"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column(+ "messaging_install_states",+ sa.Column("decided_at", sa.DateTime(timezone=True), nullable=True),+ )+++def downgrade() -> None:+ op.drop_column("messaging_install_states", "decided_at")diff --git a/core/switch_core/migrations/versions/e4a7c1d93b25_audit_events.py b/core/switch_core/migrations/versions/e4a7c1d93b25_audit_events.pynew file mode 100644index 000000000..6f46cd599--- /dev/null+++ b/core/switch_core/migrations/versions/e4a7c1d93b25_audit_events.py@@ -0,0 +1,73 @@+"""audit_events: the tenant audit log++One row per security-relevant change in a tenant. Tenant-scoped like every+other table and brings its own `tenant_isolation` policy, for the reason+`5daaea6b674d` gives. The runtime role's `UPDATE` and `DELETE` on it are taken+back by `grant_runtime_role` at the next boot, not here, because that is where+every runtime grant is issued.++The policy DDL below is a verbatim copy of `switch_core/db/rls_ddl.py` as it+stood when this migration was written, copied rather than imported so a later+edit to it cannot change what this revision means.++Revision ID: e4a7c1d93b25+Revises: 5b8d2e6f0a41+Create Date: 2026-10-01 00:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op+from sqlalchemy.dialects import postgresql++revision: str = "e4a7c1d93b25"+down_revision: str | None = "5b8d2e6f0a41"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++TABLE = "audit_events"+POLICY_NAME = "tenant_isolation"+ENABLE_RLS = f'ALTER TABLE "{TABLE}" ENABLE ROW LEVEL SECURITY'+CREATE_POLICY = f"""CREATE POLICY {POLICY_NAME} ON "{TABLE}"+ FOR ALL+ USING ("tenant_id" = (SELECT require_tenant_id()))+ WITH CHECK ("tenant_id" = (SELECT require_tenant_id()))"""+DROP_POLICY = f'DROP POLICY IF EXISTS {POLICY_NAME} ON "{TABLE}"'+++def upgrade() -> None:+ op.create_table(+ TABLE,+ sa.Column("id", sa.Text(), nullable=False),+ sa.Column("tenant_id", sa.Text(), nullable=False),+ sa.Column(+ "occurred_at",+ sa.DateTime(timezone=True),+ server_default=sa.text("clock_timestamp()"),+ nullable=False,+ ),+ sa.Column("actor_user_id", sa.Text(), nullable=True),+ sa.Column("action", sa.Text(), nullable=False),+ sa.Column("target_type", sa.Text(), nullable=False),+ sa.Column("target_id", sa.Text(), nullable=True),+ sa.Column("details", postgresql.JSONB(), nullable=True),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(+ ["tenant_id"], ["tenants.id"], name="fk_audit_events_tenant"+ ),+ )+ op.create_index(+ "ix_audit_events_tenant_occurred_at",+ TABLE,+ ["tenant_id", "occurred_at"],+ )+ op.execute(ENABLE_RLS)+ op.execute(CREATE_POLICY)+++def downgrade() -> None:+ op.execute(DROP_POLICY)+ op.drop_index("ix_audit_events_tenant_occurred_at", table_name=TABLE)+ op.drop_table(TABLE)diff --git a/core/switch_core/outbound.py b/core/switch_core/outbound.pynew file mode 100644index 000000000..34b4dd75a--- /dev/null+++ b/core/switch_core/outbound.py@@ -0,0 +1,237 @@+"""Outbound requests to URLs a tenant or an agent chose.++A Mattermost server URL, an OpenCode server URL or an agent's icon is fetched+by Switch from inside the network it runs in. Unchecked, such a URL can name a+service on that network or the cloud instance-metadata endpoint, and the+request carries whatever credentials go with it.++`OutboundPolicy` decides which addresses may be reached: any public address,+plus the private hosts and networks an operator lists in+`OUTBOUND_ALLOWED_PRIVATE_HOSTS` (a bundled Mattermost, a tailnet server, a+local OpenCode in development). Link-local addresses, which include the+metadata endpoints, are refused even when listed.++The check is made on the resolved addresses, not on the hostname, so a public+name pointing at a private address is caught. `guarded_async_client` goes+further and connects to the address it checked, so the name cannot resolve+somewhere else between the check and the connection.+"""++from __future__ import annotations++import asyncio+import ipaddress+import re+import socket+from collections.abc import Iterable+from dataclasses import dataclass+from typing import Any+from urllib.parse import urlsplit++import httpcore+import httpx++IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address+IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network++# Never reachable, whatever the operator lists: link-local covers the AWS,+# GCP and Azure metadata endpoints, and the other two are metadata endpoints+# outside it.+_ALWAYS_BLOCKED_NETWORKS: tuple[IPNetwork, ...] = (+ ipaddress.ip_network("169.254.0.0/16"),+ ipaddress.ip_network("fe80::/10"),+ ipaddress.ip_network("fd00:ec2::254/128"),+ ipaddress.ip_network("100.100.100.200/32"),+)+_ALWAYS_BLOCKED_HOSTNAMES = frozenset({"metadata.google.internal"})++# Underscores are not legal in DNS hostnames but are in Compose service and+# Docker network aliases, which is what most private hosts listed here are.+_HOSTNAME_RE = re.compile(+ r"^[a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?(\.[a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?)*$"+)++_DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443}++# httpx's own defaults, which its pool gets and a bare httpcore pool does not:+# httpcore's are 10 connections with idle ones kept forever, and an OpenCode+# session holds a connection for minutes at a time.+_POOL_LIMITS = httpx.Limits(+ max_connections=100, max_keepalive_connections=20, keepalive_expiry=5.0+)+++class OutboundURLRefused(ValueError):+ """A URL names an address Switch will not connect to on a tenant's behalf."""+++@dataclass(frozen=True)+class OutboundPolicy:+ allowed_hostnames: frozenset[str]+ allowed_networks: tuple[IPNetwork, ...]++ @classmethod+ def parse(cls, value: str) -> OutboundPolicy:+ """Read `OUTBOUND_ALLOWED_PRIVATE_HOSTS`: hostnames and CIDRs, comma-separated."""+ hostnames: set[str] = set()+ networks: list[IPNetwork] = []+ for raw in value.split(","):+ entry = raw.strip().lower()+ if not entry:+ continue+ try:+ networks.append(ipaddress.ip_network(entry, strict=False))+ continue+ except ValueError:+ pass+ if not _HOSTNAME_RE.match(entry):+ raise ValueError(+ f"OUTBOUND_ALLOWED_PRIVATE_HOSTS entry {raw.strip()!r} is "+ "neither a hostname nor an IP network."+ )+ hostnames.add(entry)+ return cls(+ allowed_hostnames=frozenset(hostnames), allowed_networks=tuple(networks)+ )++ def _refusal(self, hostname: str, address: IPAddress) -> str | None:+ if any(address in network for network in _ALWAYS_BLOCKED_NETWORKS):+ return f"{hostname} resolves to {address}, a link-local or metadata address"+ if address.is_global:+ return None+ if hostname in self.allowed_hostnames:+ return None+ if any(address in network for network in self.allowed_networks):+ return None+ return (+ f"{hostname} resolves to {address}, which is not a public address. "+ "An operator can allow it with OUTBOUND_ALLOWED_PRIVATE_HOSTS."+ )++ async def resolve(self, hostname: str, port: int) -> list[str]:+ """Every address `hostname` resolves to, or refuse if any is not allowed.++ One refused address refuses the name: which of several addresses a+ connection lands on is not ours to choose, so all of them must pass.+ """+ hostname = hostname.lower().rstrip(".").strip("[]")+ if hostname in _ALWAYS_BLOCKED_HOSTNAMES:+ raise OutboundURLRefused(f"{hostname} is a metadata endpoint")+ try:+ literal: IPAddress | None = ipaddress.ip_address(hostname)+ except ValueError:+ literal = None+ if literal is not None:+ candidates: Iterable[str] = [hostname]+ else:+ try:+ infos = await asyncio.get_running_loop().getaddrinfo(+ hostname, port, type=socket.SOCK_STREAM+ )+ except socket.gaierror as exc:+ raise OutboundURLRefused(f"{hostname} does not resolve: {exc}") from exc+ candidates = [str(info[4][0]) for info in infos]++ addresses: list[str] = []+ for candidate in candidates:+ address = ipaddress.ip_address(candidate.split("%", 1)[0])+ if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped:+ address = address.ipv4_mapped+ refusal = self._refusal(hostname, address)+ if refusal is not None:+ raise OutboundURLRefused(refusal)+ if str(address) not in addresses:+ addresses.append(str(address))+ if not addresses:+ raise OutboundURLRefused(f"{hostname} resolves to no address")+ return addresses++ async def check_url(+ self, url: str, *, schemes: Iterable[str] = ("http", "https")+ ) -> None:+ """Refuse a URL whose scheme or resolved host is not allowed."""+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ if scheme not in set(schemes):+ raise OutboundURLRefused(+ f"{url!r} must use {' or '.join(sorted(schemes))}, not {scheme or 'no scheme'!r}"+ )+ if not parts.hostname:+ raise OutboundURLRefused(f"{url!r} names no host")+ try:+ port = parts.port or _DEFAULT_PORTS[scheme]+ except ValueError as exc:+ raise OutboundURLRefused(f"{url!r} has an invalid port") from exc+ await self.resolve(parts.hostname, port)+++class _GuardedNetworkBackend(httpcore.AsyncNetworkBackend):+ """Connects only to an address the policy allowed, resolved just now."""++ def __init__(self, policy: OutboundPolicy) -> None:+ self._policy = policy+ self._inner = httpcore.AnyIOBackend()++ async def connect_tcp(+ self,+ host: str,+ port: int,+ timeout: float | None = None,+ local_address: str | None = None,+ socket_options: Iterable[Any] | None = None,+ ) -> httpcore.AsyncNetworkStream:+ addresses = await self._policy.resolve(host, port)+ failure: Exception | None = None+ for address in addresses:+ try:+ return await self._inner.connect_tcp(+ address,+ port,+ timeout=timeout,+ local_address=local_address,+ socket_options=socket_options,+ )+ except (httpcore.ConnectError, httpcore.ConnectTimeout) as exc:+ failure = exc+ assert failure is not None+ raise failure++ async def connect_unix_socket(+ self,+ path: str,+ timeout: float | None = None,+ socket_options: Iterable[Any] | None = None,+ ) -> httpcore.AsyncNetworkStream:+ raise OutboundURLRefused("a guarded client does not connect to Unix sockets")++ async def sleep(self, seconds: float) -> None:+ await self._inner.sleep(seconds)+++def guarded_async_client(+ policy: OutboundPolicy, *, verify: bool = True, **client_kwargs: Any+) -> httpx.AsyncClient:+ """An `httpx.AsyncClient` that can reach only what `policy` allows.++ Each connection resolves its host, checks every address and connects to a+ checked one, so redirects and re-resolution are covered as well. Proxy+ settings from the environment are ignored: through a proxy, the address+ checked would be the proxy's.++ TLS still verifies against the hostname, because httpcore sends the URL's+ host as SNI whatever address the socket connected to.+ """+ transport = httpx.AsyncHTTPTransport(verify=verify, trust_env=False)+ # httpx exposes no way to hand its pool a network backend, so the pool it+ # built is replaced with an equivalent one that has ours.+ # `test_outbound.py` makes a real request through this client and would+ # fail if httpx stopped routing connections through `_pool`.+ limits = _POOL_LIMITS+ transport._pool = httpcore.AsyncConnectionPool(+ ssl_context=httpx.create_ssl_context(verify=verify, trust_env=False),+ max_connections=limits.max_connections,+ max_keepalive_connections=limits.max_keepalive_connections,+ keepalive_expiry=limits.keepalive_expiry,+ network_backend=_GuardedNetworkBackend(policy),+ )+ return httpx.AsyncClient(transport=transport, trust_env=False, **client_kwargs)diff --git a/core/tests/benchmarks/server.py b/core/tests/benchmarks/server.pyindex 3fcfa14ab..91946d3dd 100644--- a/core/tests/benchmarks/server.py+++ b/core/tests/benchmarks/server.py@@ -510,6 +510,7 @@ async def _serve(client_factory=client_factory,session_factory=session_factory,config=config,+ tenants_isolated=True,)room_service = RoomService(diff --git a/core/tests/conftest.py b/core/tests/conftest.pyindex 94330c41a..e335daff4 100644--- a/core/tests/conftest.py+++ b/core/tests/conftest.py@@ -22,12 +22,21 @@ from testcontainers.postgres import PostgresContainer# Importing the models module registers every table on Base.metadata so# create_all provisions the full schema (rooms, room_groups, FKs, …).import switch_core.db.models # noqa: F401+from switch_core.db import encrypted_jsonfrom switch_core.db.base import Basefrom switch_core.db.engine import create_session_factoryfrom switch_core.db.models import TENANT_ZERO_ID, Tenantfrom switch_core.db.runtime_role import grant_runtime_role+from switch_core.keys import Keyringfrom switch_core.tenant_context import tenant_scope+# Production configures this in `main.run()`; every test that touches a+# connection config needs the same, and none needs a particular key.+TEST_KEYRING = Keyring.parse(+ "test:" + "column-encryption-secret" * 2, legacy_secret=None+)+encrypted_json.configure(TEST_KEYRING)+async def _seed_tenant_zero(conn: AsyncConnection) -> None:"""Insert the one tenant every scoped row's `tenant_id` default points at.diff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.pyindex 316811e74..a31e02f9b 100644--- a/core/tests/integration/conftest.py+++ b/core/tests/integration/conftest.py@@ -103,7 +103,7 @@ RUNTIME_ROLE_PREFIX = "switch_app"# ── Throwaway test constants (not secrets — local ephemeral infra) ──────────────SERVER_NAME = "localhost"-JWT_SECRET = "dev-jwt-secret-test"+SECRET_KEYS = "test:dev-secret-key-for-integration-tests-0000"REGISTRATION_TOKEN = "dev-test-token"GATEWAY_ADMIN_EMAIL = "[email protected]"GATEWAY_ADMIN_PASSWORD = "admin"@@ -221,7 +221,7 @@ def _build_config(db_name=db_name,id_server_name=SERVER_NAME,agent_registration_token=REGISTRATION_TOKEN,- jwt_secret_key=JWT_SECRET,+ secret_keys=SECRET_KEYS,gateway_admin_email=GATEWAY_ADMIN_EMAIL,gateway_admin_password=GATEWAY_ADMIN_PASSWORD,frontend_base_url=None,@@ -591,6 +591,7 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:client_factory=client_factory,session_factory=session_factory,config=config,+ tenants_isolated=True,)room_service = RoomService(diff --git a/core/tests/switch_core/bridges/agent/protocol/registration_harness.py b/core/tests/switch_core/bridges/agent/protocol/registration_harness.pyindex 3f87374bf..cda470435 100644--- a/core/tests/switch_core/bridges/agent/protocol/registration_harness.py+++ b/core/tests/switch_core/bridges/agent/protocol/registration_harness.py@@ -21,6 +21,7 @@ from switch_core.db.models import Client, Userfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.user_store import UserStore+from switch_core.keys import KeyringPROFILE = IntegrationProfile(connection_model="session_passive",@@ -74,7 +75,9 @@ def make_service(svc.api_key_cache = ApiKeyCache(ttl_seconds=5.0, max_entries=8) # type: ignore[attr-defined]svc.client_lifecycle = FakeClientLifecycle(session_factory) # type: ignore[attr-defined]svc.collab_lifecycle = NoBridges() # type: ignore[attr-defined]- svc.config = SimpleNamespace(jwt_secret_key="test-secret") # type: ignore[attr-defined]+ svc.config = SimpleNamespace(+ keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None)+ ) # type: ignore[attr-defined]return svcdiff --git a/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py b/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.pyindex b1bfab1f3..5a1b010b3 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py@@ -44,6 +44,7 @@ from switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStore+from switch_core.keys import Keyringfrom switch_core.tenant_context import tenant_scopeTENANT_B = "tenant-b"@@ -91,7 +92,9 @@ def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:svc.user_store = UserStore() # type: ignore[attr-defined]svc.client_lifecycle = _FakeClientLifecycle(session_factory) # type: ignore[attr-defined]svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]- svc.config = SimpleNamespace(jwt_secret_key="test-secret") # type: ignore[attr-defined]+ svc.config = SimpleNamespace(+ keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None)+ ) # type: ignore[attr-defined]return svcdiff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.py b/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.pyindex c11aab461..dcdb027cd 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.py@@ -27,6 +27,7 @@ from switch_core.bridges.agent.protocol.types import (from switch_core.db.models import Client, Userfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStore+from switch_core.keys import Keyring_PROFILE = IntegrationProfile(connection_model="session_passive",@@ -69,7 +70,9 @@ def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:svc.api_key_store = ApiKeyStore() # type: ignore[attr-defined]svc.client_lifecycle = _FakeClientLifecycle(session_factory) # type: ignore[attr-defined]svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]- svc.config = SimpleNamespace(jwt_secret_key="test-secret") # type: ignore[attr-defined]+ svc.config = SimpleNamespace(+ keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None)+ ) # type: ignore[attr-defined]# Duck-typed: the attribute exists on AgentCore after the api-key# cache landed on main; a no-op stand-in keeps this test valid on both# sides of that merge.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.pyindex 51ee5e4b7..36e357153 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.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStore+from switch_core.keys import Keyring_PROFILE = IntegrationProfile(connection_model="session_passive",@@ -69,7 +70,9 @@ def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:svc.user_store = UserStore() # type: ignore[attr-defined]svc.client_lifecycle = _FakeClientLifecycle(session_factory) # type: ignore[attr-defined]svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]- svc.config = SimpleNamespace(jwt_secret_key="test-secret") # type: ignore[attr-defined]+ svc.config = SimpleNamespace(+ keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None)+ ) # type: ignore[attr-defined]return svcdiff --git a/core/tests/switch_core/bridges/agent/server_connectors/opencode/test_connector.py b/core/tests/switch_core/bridges/agent/server_connectors/opencode/test_connector.pyindex 9042b8236..b9bb1c6ad 100644--- a/core/tests/switch_core/bridges/agent/server_connectors/opencode/test_connector.py+++ b/core/tests/switch_core/bridges/agent/server_connectors/opencode/test_connector.py@@ -9,6 +9,7 @@ from switch_core.bridges.agent.server_connectors.opencode.connector import (OpenCodeConnectionConfig,OpenCodeConnector,)+from switch_core.outbound import OutboundPolicySESSION_ID = "sess-1"ROOM_ID = "room-1"@@ -70,7 +71,7 @@ def _connector_with(config = OpenCodeConnectionConfig(server_url="http://localhost", username="u", password="p")- connector = OpenCodeConnector(config)+ connector = OpenCodeConnector(config, OutboundPolicy.parse("localhost"))client = client or _FakeClient(events)connector._client = client # type: ignore[assignment]return connector, clientdiff --git a/core/tests/switch_core/bridges/agent/server_connectors/test_lifecycle_remove_tenant.py b/core/tests/switch_core/bridges/agent/server_connectors/test_lifecycle_remove_tenant.pyindex 8d1fe1720..3955f03fd 100644--- a/core/tests/switch_core/bridges/agent/server_connectors/test_lifecycle_remove_tenant.py+++ b/core/tests/switch_core/bridges/agent/server_connectors/test_lifecycle_remove_tenant.py@@ -38,6 +38,8 @@ from switch_core.db.models import ()from switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.server_connector_store import ServerConnectorStore+from switch_core.keys import Keyring+from switch_core.outbound import OutboundPolicyfrom switch_core.tenant_context import tenant_scopepytestmark = pytest.mark.no_ambient_tenant@@ -105,7 +107,8 @@ def _service(api_key_store=ApiKeyStore(),protocol=None, # type: ignore[arg-type]session_factory=session_factory,- encryption_secret="s" * 32,+ keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None),+ outbound_policy=OutboundPolicy.parse(""),)diff --git a/core/tests/switch_core/bridges/agent/test_api_key_cache.py b/core/tests/switch_core/bridges/agent/test_api_key_cache.pyindex 4cf9d29e1..eef489c71 100644--- a/core/tests/switch_core/bridges/agent/test_api_key_cache.py+++ b/core/tests/switch_core/bridges/agent/test_api_key_cache.py@@ -27,6 +27,7 @@ from switch_core.config import SwitchConfigfrom switch_core.db.models import Agent, ApiKey, Client, Userfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStore+from switch_core.keys import Keyring_PROFILE = IntegrationProfile(connection_model="session_passive",@@ -425,7 +426,9 @@ def _agent_core(svc.client_lifecycle = _FakeClientLifecycle(session_factory) # type: ignore[attr-defined]svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]svc.event_buffer = SimpleNamespace(remove=lambda _agent_id: None) # type: ignore[attr-defined]- svc.config = SimpleNamespace(jwt_secret_key="test-secret") # type: ignore[attr-defined]+ svc.config = SimpleNamespace(+ keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None)+ ) # type: ignore[attr-defined]return svc@@ -437,7 +440,7 @@ _CONFIG_KWARGS = dict(db_name="switch",id_server_name="switch.local",agent_registration_token="token",- jwt_secret_key="jwt",+ secret_keys="test:" + "x" * 40,gateway_admin_email="[email protected]",gateway_admin_password="pw",)diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.pyindex 5e0850572..47e7faf72 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py@@ -28,6 +28,7 @@ from switch_core.bridges.collaboration.telegram.adapter import (TelegramAdapter,TelegramConnectionConfig,)+from switch_core.keys import Keyringdef _service() -> CollaborationBridgeLifecycleService:@@ -41,7 +42,7 @@ def _service() -> CollaborationBridgeLifecycleService:config = MagicMock()config.collaboration_callback_host = "127.0.0.1"config.collaboration_callback_port = 0- config.jwt_secret_key = "server-secret-for-tests"+ config.keyring = Keyring.parse("test:" + "x" * 40, legacy_secret=None)return CollaborationBridgeLifecycleService(bridge_store=None, # type: ignore[arg-type]external_user_store=None, # type: ignore[arg-type]diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_workspace_claims.py b/core/tests/switch_core/bridges/collaboration/test_bridge_workspace_claims.pynew file mode 100644index 000000000..2ce78642e--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_workspace_claims.py@@ -0,0 +1,395 @@+"""One platform workspace, connected at most once on the instance.++Two bridges into the same Slack workspace, Discord server or Mattermost team+would each deliver its events to their own tenant. The hosted install path+already holds a workspace to one tenant; these pin the same rule for bridges+registered by hand, and that Slack's `workspace_id` is the token's own rather+than whatever was typed in.+"""++from __future__ import annotations++import uuid+from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import aiohttp+import pytest+from pydantic import ValidationError+from slack_sdk.errors import SlackApiError+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.collaboration.discord.adapter import (+ DiscordAdapter,+ DiscordConnectionConfig,+)+from switch_core.bridges.collaboration.lifecycle_service import (+ BridgeClaimConflict,+ CollaborationBridgeLifecycleService,+)+from switch_core.bridges.collaboration.mattermost.adapter import (+ MattermostAdapter,+ MattermostConnectionConfig,+)+from switch_core.bridges.collaboration.models import BridgeCredentialError+from switch_core.bridges.collaboration.slack.adapter import (+ SlackAdapter,+ SlackConnectionConfig,+)+from switch_core.db.models import Client, CollaborationBridge, Tenant+from switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.tenant_context import tenant_scope++_SLACK = {"bot_token": "xoxb-test", "app_token": "xapp-test", "workspace_id": "T1"}+_DISCORD = {"bot_token": "discord-test", "guild_id": "111"}+_MATTERMOST = {+ "url": "https://chat.example.invalid",+ "admin_user": "bot",+ "admin_password": "placeholder", # gitleaks:allow+ "team_name": "eng",+}+++def _service(+ session_factory: async_sessionmaker[AsyncSession],+) -> CollaborationBridgeLifecycleService:+ service = CollaborationBridgeLifecycleService(+ bridge_store=CollaborationBridgeStore(),+ external_user_store=MagicMock(),+ bridge_message_map_store=MagicMock(),+ room_store=RoomStore(),+ agent_store=MagicMock(),+ client_store=ClientStore(),+ client_lifecycle=MagicMock(),+ room_service=MagicMock(),+ provisioning=MagicMock(),+ session_factory=session_factory,+ config=MagicMock(),+ client_factory=MagicMock(),+ session_activity_listener=MagicMock(),+ session_activity_service=MagicMock(),+ connections=MagicMock(),+ )+ service.register_adapter("slack", SlackAdapter, SlackConnectionConfig)+ service.register_adapter("discord", DiscordAdapter, DiscordConnectionConfig)+ service.register_adapter(+ "mattermost", MattermostAdapter, MattermostConnectionConfig+ )+ return service+++async def _bridge(+ session_factory: async_sessionmaker[AsyncSession],+ *,+ tenant_id: str,+ bridge_type: str,+ connection_config: dict[str, Any],+ display_name: str = "Incumbent",+) -> None:+ async with session_factory() as session:+ if await session.get(Tenant, tenant_id) is None:+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ await session.flush()+ client = Client(+ tenant_id=tenant_id,+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ display_name="bridge client",+ type="bridge",+ )+ session.add(client)+ await session.flush()+ session.add(+ CollaborationBridge(+ tenant_id=tenant_id,+ type=bridge_type,+ display_name=display_name,+ client_id=client.id,+ status="active",+ connection_config=connection_config,+ )+ )+ await session.commit()+++async def _tenant(session_factory: async_sessionmaker[AsyncSession]) -> str:+ tenant_id = f"tenant-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ await session.commit()+ return tenant_id+++class TestWhatAWorkspaceIs:+ def test_slack_is_claimed_by_its_workspace_id(self) -> None:+ assert SlackAdapter.claimed_workspace(_SLACK) == "Slack workspace T1"++ def test_discord_is_claimed_by_its_server(self) -> None:+ assert DiscordAdapter.claimed_workspace(_DISCORD) == "Discord server 111"++ @pytest.mark.parametrize(+ "url",+ [+ "https://chat.example.invalid",+ "https://chat.example.invalid/",+ "HTTPS://Chat.Example.Invalid:443",+ ],+ )+ def test_a_mattermost_team_is_the_same_however_its_url_is_written(+ self, url: str+ ) -> None:+ config = {**_MATTERMOST, "url": url, "team_name": "Eng"}+ assert (+ MattermostAdapter.claimed_workspace(config)+ == "Mattermost team eng on https://chat.example.invalid"+ )++ @pytest.mark.parametrize(+ "url",+ [+ "chat.example.invalid",+ "http://chat.example.invalid",+ "chat.example.invalid:8065/",+ "HTTP://chat.example.invalid:8065",+ ],+ )+ def test_a_url_with_no_scheme_is_the_server_the_driver_reaches(+ self, url: str+ ) -> None:+ """The driver reads no scheme as http, and http with no port as 8065."""+ config = {**_MATTERMOST, "url": url, "team_name": "eng"}+ assert (+ MattermostAdapter.claimed_workspace(config)+ == "Mattermost team eng on http://chat.example.invalid"+ )++ def test_port_80_is_not_the_drivers_http_default(self) -> None:+ plain = {**_MATTERMOST, "url": "http://chat.example.invalid"}+ on_80 = {**_MATTERMOST, "url": "http://chat.example.invalid:80"}+ assert MattermostAdapter.claimed_workspace(+ plain+ ) != MattermostAdapter.claimed_workspace(on_80)++ def test_a_mattermost_team_on_another_port_is_another_team(self) -> None:+ config = {**_MATTERMOST, "url": "https://chat.example.invalid:8065"}+ assert MattermostAdapter.claimed_workspace(config) != (+ MattermostAdapter.claimed_workspace(_MATTERMOST)+ )+++class TestRegistrationRefusesASecondClaim:+ @pytest.mark.parametrize(+ ("bridge_type", "config"),+ [("slack", _SLACK), ("discord", _DISCORD), ("mattermost", _MATTERMOST)],+ )+ async def test_another_tenants_workspace_is_refused_without_naming_it(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ bridge_type: str,+ config: dict[str, Any],+ ) -> None:+ incumbent = await _tenant(session_factory)+ newcomer = await _tenant(session_factory)+ await _bridge(+ session_factory,+ tenant_id=incumbent,+ bridge_type=bridge_type,+ connection_config=config,+ display_name="Their bridge",+ )++ with tenant_scope(newcomer):+ with pytest.raises(BridgeClaimConflict, match="already claimed") as raised:+ await _service(session_factory).reject_claim_conflict(+ bridge_type, dict(config)+ )+ assert "Their bridge" not in str(raised.value)++ async def test_the_callers_own_bridge_is_named(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ tenant = await _tenant(session_factory)+ await _bridge(+ session_factory,+ tenant_id=tenant,+ bridge_type="slack",+ connection_config=_SLACK,+ display_name="Our Slack",+ )++ with tenant_scope(tenant):+ with pytest.raises(BridgeClaimConflict, match="'Our Slack'") as raised:+ await _service(session_factory).reject_claim_conflict(+ "slack", dict(_SLACK)+ )+ assert "listen_port" not in str(raised.value)++ async def test_a_different_workspace_is_accepted(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ incumbent = await _tenant(session_factory)+ newcomer = await _tenant(session_factory)+ await _bridge(+ session_factory,+ tenant_id=incumbent,+ bridge_type="slack",+ connection_config=_SLACK,+ )++ with tenant_scope(newcomer):+ await _service(session_factory).reject_claim_conflict(+ "slack", {**_SLACK, "workspace_id": "T2"}+ )++ async def test_the_same_id_on_another_platform_is_not_a_clash(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ incumbent = await _tenant(session_factory)+ newcomer = await _tenant(session_factory)+ await _bridge(+ session_factory,+ tenant_id=incumbent,+ bridge_type="discord",+ connection_config={**_DISCORD, "guild_id": "T1"},+ )++ with tenant_scope(newcomer):+ await _service(session_factory).reject_claim_conflict("slack", dict(_SLACK))+++class TestAnEditIsHeldToTheSameRules:+ async def test_an_edit_to_another_tenants_workspace_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ incumbent = await _tenant(session_factory)+ newcomer = await _tenant(session_factory)+ await _bridge(+ session_factory,+ tenant_id=incumbent,+ bridge_type="discord",+ connection_config=_DISCORD,+ )++ with tenant_scope(newcomer):+ with pytest.raises(BridgeClaimConflict, match="already claimed"):+ await _service(session_factory).check_edited_connection_config(+ bridge_id="the-edited-bridge",+ bridge_type="discord",+ connection_config=dict(_DISCORD),+ )++ async def test_editing_a_bridge_does_not_clash_with_itself(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ tenant = await _tenant(session_factory)+ await _bridge(+ session_factory,+ tenant_id=tenant,+ bridge_type="discord",+ connection_config=_DISCORD,+ )+ async with session_factory() as session:+ [bridge] = [+ b+ for b in await CollaborationBridgeStore().get_all(session)+ if b.tenant_id == tenant+ ]++ with tenant_scope(tenant):+ await _service(session_factory).check_edited_connection_config(+ bridge_id=bridge.id,+ bridge_type="discord",+ connection_config={**_DISCORD, "agent_roles": False},+ )++ async def test_an_edited_slack_workspace_id_must_be_the_tokens(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ tenant = await _tenant(session_factory)+ with tenant_scope(tenant), _auth_test(ok=True, team_id="T1"):+ with pytest.raises(BridgeCredentialError, match="T1, not T2"):+ await _service(session_factory).check_edited_connection_config(+ bridge_id="the-edited-bridge",+ bridge_type="slack",+ connection_config={**_SLACK, "workspace_id": "T2"},+ )+++def _auth_test(**response: Any) -> Any:+ return patch(+ "switch_core.bridges.collaboration.slack.adapter.AsyncWebClient.auth_test",+ AsyncMock(return_value=response),+ )+++class TestSlackWorkspaceIdIsTheTokens:+ async def test_the_tokens_workspace_is_accepted(self) -> None:+ with _auth_test(ok=True, team_id="T1"):+ await SlackAdapter.verify_credentials(dict(_SLACK))++ async def test_an_enterprise_grid_org_id_is_accepted(self) -> None:+ with _auth_test(ok=True, team_id="T9", enterprise_id="E1"):+ await SlackAdapter.verify_credentials({**_SLACK, "workspace_id": "E1"})++ async def test_another_workspace_is_refused(self) -> None:+ # Otherwise a tenant could claim a workspace by typing its id, and+ # keep the real holder from connecting it.+ with _auth_test(ok=True, team_id="T2"):+ with pytest.raises(BridgeCredentialError, match="T2, not T1"):+ await SlackAdapter.verify_credentials(dict(_SLACK))++ async def test_a_token_slack_refuses_is_a_credential_error(self) -> None:+ refusal = SlackApiError("invalid_auth", MagicMock())+ refusal.response = {"ok": False, "error": "invalid_auth"} # type: ignore[assignment]+ with patch(+ "switch_core.bridges.collaboration.slack.adapter.AsyncWebClient.auth_test",+ AsyncMock(side_effect=refusal),+ ):+ with pytest.raises(BridgeCredentialError, match="invalid_auth"):+ await SlackAdapter.verify_credentials(dict(_SLACK))++ @pytest.mark.parametrize(+ "failure",+ [aiohttp.ClientConnectionError("connection refused"), TimeoutError()],+ )+ async def test_slack_out_of_reach_is_a_credential_error_not_a_crash(+ self, failure: Exception+ ) -> None:+ """Add and edit answer 400 rather than 500 when Slack cannot be+ reached, and the install flow can tell it apart from a bug."""+ with patch(+ "switch_core.bridges.collaboration.slack.adapter.AsyncWebClient.auth_test",+ AsyncMock(side_effect=failure),+ ):+ with pytest.raises(BridgeCredentialError, match="Could not reach Slack"):+ await SlackAdapter.verify_credentials(dict(_SLACK))+++class TestMattermostUrlIsCheckedUpFront:+ @pytest.mark.parametrize(+ "url",+ [+ "https://chat.example.invalid:99999",+ "https://chat.example.invalid:abc",+ "ftp://chat.example.invalid",+ "https://",+ ],+ )+ async def test_an_edit_with_a_bad_url_is_a_validation_error(+ self, session_factory: async_sessionmaker[AsyncSession], url: str+ ) -> None:+ tenant = await _tenant(session_factory)+ with tenant_scope(tenant):+ with pytest.raises(ValidationError, match="url"):+ await _service(session_factory).check_edited_connection_config(+ bridge_id="the-edited-bridge",+ bridge_type="mattermost",+ connection_config={**_MATTERMOST, "url": url},+ )++ def test_a_url_with_no_scheme_is_still_valid(self) -> None:+ """Bridges configured before the check, the way the driver accepts."""+ MattermostConnectionConfig.model_validate(+ {**_MATTERMOST, "url": "chat.example.invalid:8065"}+ )diff --git a/core/tests/switch_core/bridges/collaboration/test_callback_keys.py b/core/tests/switch_core/bridges/collaboration/test_callback_keys.pynew file mode 100644index 000000000..4a6250d1c--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_callback_keys.py@@ -0,0 +1,91 @@+"""Buttons already posted to Mattermost across key changes.++A button carries a signature made with its bridge's callback key when it was+posted, and can be pressed long after. It keeps working after a rotation while+the old key is kept, and a button posted before `SECRET_KEYS` keeps working+while `JWT_SECRET_KEY` is set.+"""++from __future__ import annotations++import hashlib+import hmac+from typing import Any++from switch_core.bridges.collaboration.ingress import CallbackIngress+from switch_core.bridges.collaboration.mattermost.callback import (+ Press,+ action_context,+ read_press,+)+from switch_core.keys import Keyring++_OLD = "o" * 40+_NEW = "n" * 40+_LEGACY = "legacy-jwt-secret"+++def _endpoint(+ value: str, legacy: str | None = None, bridge_id: str = "bridge-1"+) -> Any:+ ingress = CallbackIngress(+ host="127.0.0.1",+ port=0,+ keyring=Keyring.parse(value, legacy_secret=legacy),+ )+ return ingress.endpoint_for("mattermost", bridge_id)+++def _press(signing_key: str) -> dict[str, Any]:+ return {+ "user_id": "user-1",+ "post_id": "post-1",+ "channel_id": "channel-1",+ "context": action_context(signing_key, "card-1", 1),+ }+++def test_a_button_verifies_with_the_key_it_was_signed_with() -> None:+ endpoint = _endpoint(f"k1:{_OLD}")+ assert isinstance(+ read_press(endpoint.verification_keys, _press(endpoint.key)), Press+ )+++def test_a_button_posted_before_a_rotation_still_works() -> None:+ posted_with = _endpoint(f"old:{_OLD}").key+ after = _endpoint(f"new:{_NEW},old:{_OLD}")+ assert after.key != posted_with+ assert isinstance(read_press(after.verification_keys, _press(posted_with)), Press)+++def test_and_stops_when_its_key_is_removed() -> None:+ posted_with = _endpoint(f"old:{_OLD}").key+ after = _endpoint(f"new:{_NEW}")+ assert read_press(after.verification_keys, _press(posted_with)) is None+++def test_another_bridges_key_does_not_verify() -> None:+ other = _endpoint(f"k1:{_OLD}", bridge_id="bridge-2").key+ assert read_press(_endpoint(f"k1:{_OLD}").verification_keys, _press(other)) is None+++def _legacy_bridge_key() -> str:+ """A bridge's callback key as derived from `JWT_SECRET_KEY` before `SECRET_KEYS`."""+ return hmac.new(+ _LEGACY.encode(), b"collaboration-callback:mattermost:bridge-1", hashlib.sha256+ ).hexdigest()+++def test_a_button_from_before_secret_keys_works_while_the_legacy_secret_is_set() -> (+ None+):+ endpoint = _endpoint(f"k1:{_NEW}", legacy=_LEGACY)+ assert isinstance(+ read_press(endpoint.verification_keys, _press(_legacy_bridge_key())), Press+ )+++def test_and_stops_once_it_is_removed() -> None:+ endpoint = _endpoint(f"k1:{_NEW}")+ assert read_press(endpoint.verification_keys, _press(_legacy_bridge_key())) is Nonediff --git a/core/tests/switch_core/bridges/collaboration/test_collaboration_ingress.py b/core/tests/switch_core/bridges/collaboration/test_collaboration_ingress.pyindex 29710373e..752c32c89 100644--- a/core/tests/switch_core/bridges/collaboration/test_collaboration_ingress.py+++ b/core/tests/switch_core/bridges/collaboration/test_collaboration_ingress.py@@ -25,8 +25,10 @@ from switch_core.bridges.collaboration.ingress import (CallbackIngress,CallbackRefused,)+from switch_core.keys import Keyring-SECRET = "server-secret-for-tests"+SECRET = "server-secret-for-tests-server-secret"+KEYRING = Keyring.parse(f"test:{SECRET}", legacy_secret=None)BRIDGE = "bridge-1"OTHER = "bridge-2"@@ -39,7 +41,7 @@ def _free_port() -> int:def _ingress(port: int) -> CallbackIngress:- return CallbackIngress(host="127.0.0.1", port=port, secret=SECRET)+ return CallbackIngress(host="127.0.0.1", port=port, keyring=KEYRING)async def _post(@@ -363,7 +365,11 @@ def test_a_rotated_server_secret_gives_a_different_key() -> None:port = _free_port()before = _ingress(port).endpoint_for("mattermost", BRIDGE).keyafter = (- CallbackIngress(host="127.0.0.1", port=port, secret="the-next-one")+ CallbackIngress(+ host="127.0.0.1",+ port=port,+ keyring=Keyring.parse("next:" + "the-next-one" * 3, legacy_secret=None),+ ).endpoint_for("mattermost", BRIDGE).key)diff --git a/core/tests/switch_core/bridges/collaboration/test_install_confirmation_page.py b/core/tests/switch_core/bridges/collaboration/test_install_confirmation_page.pynew file mode 100644index 000000000..c27e60992--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_install_confirmation_page.py@@ -0,0 +1,149 @@+"""The install callback's confirmation page, through the public routes.++The service tests cover what Connect and Cancel do; these cover what the+approver's browser sees and sends: a page that names the organisation, carries+the ticket, cannot be framed, and a form post that finishes the install.+"""++from __future__ import annotations++import html+import re++import httpx+import pytest+from fastapi import FastAPI++from switch_core.bridges.collaboration.install import MessagingInstallError+from switch_core.bridges.collaboration.install_routes import (+ create_messaging_install_router,+)+from tests.conftest import RLSHarness++from .test_install_service import _ORIGIN, _begin, _fixture++pytestmark = pytest.mark.no_ambient_tenant+++def _client(service: object) -> httpx.AsyncClient:+ app = FastAPI()+ app.include_router(create_messaging_install_router(service)) # type: ignore[arg-type]+ return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url=_ORIGIN)+++def _ticket(page: str) -> str:+ match = re.search(r'name="ticket" value="([^"]+)"', page)+ assert match is not None, page+ return html.unescape(match.group(1))+++async def test_the_callback_renders_a_confirmation_and_connects_nothing(+ rls_harness: RLSHarness,+) -> None:+ fixture = await _fixture(rls_harness)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)++ async with _client(fixture.service) as client:+ response = await client.get(+ "/messaging/slack/oauth/callback",+ params={"code": "the-code", "state": state},+ )++ assert response.status_code == 200+ assert fixture.tenant_a in response.text+ assert "Acme" in response.text+ assert 'action="/messaging/slack/oauth/confirm"' in response.text+ assert "frame-ancestors 'none'" in response.headers["content-security-policy"]+ assert response.headers["x-frame-options"] == "DENY"+ assert response.headers["cache-control"] == "no-store"+ assert fixture.lifecycle.registered == []+++async def test_connect_on_the_page_finishes_the_install(+ rls_harness: RLSHarness,+) -> None:+ fixture = await _fixture(rls_harness)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)++ async with _client(fixture.service) as client:+ page = await client.get(+ "/messaging/slack/oauth/callback",+ params={"code": "the-code", "state": state},+ )+ ticket = _ticket(page.text)+ connected = await client.post(+ "/messaging/slack/oauth/confirm",+ data={"ticket": ticket, "decision": "connect"},+ )+ again = await client.post(+ "/messaging/slack/oauth/confirm",+ data={"ticket": ticket, "decision": "connect"},+ )++ assert connected.status_code == 200+ assert "Switch is connected" in connected.text+ assert again.status_code == 400+ assert len(fixture.lifecycle.registered) == 1+++async def test_cancel_on_the_page_connects_nothing(rls_harness: RLSHarness) -> None:+ fixture = await _fixture(rls_harness)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)++ async with _client(fixture.service) as client:+ page = await client.get(+ "/messaging/slack/oauth/callback",+ params={"code": "the-code", "state": state},+ )+ cancelled = await client.post(+ "/messaging/slack/oauth/confirm",+ data={"ticket": _ticket(page.text), "decision": "cancel"},+ )++ assert cancelled.status_code == 200+ assert "Install cancelled" in cancelled.text+ assert fixture.lifecycle.registered == []+ assert fixture.installer.revoked_tokens == ["xoxb-granted"]+++async def test_a_cancel_that_could_not_revoke_says_so_and_can_be_retried(+ rls_harness: RLSHarness,+) -> None:+ fixture = await _fixture(rls_harness)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)+ fixture.installer.revoke_error = MessagingInstallError("Slack is down")++ async with _client(fixture.service) as client:+ page = await client.get(+ "/messaging/slack/oauth/callback",+ params={"code": "the-code", "state": state},+ )+ ticket = _ticket(page.text)+ failed = await client.post(+ "/messaging/slack/oauth/confirm",+ data={"ticket": ticket, "decision": "cancel"},+ )+ fixture.installer.revoke_error = None+ retried = await client.post(+ "/messaging/slack/oauth/confirm",+ data={"ticket": ticket, "decision": "cancel"},+ )++ assert failed.status_code == 502+ assert "Cancel did not finish" in failed.text+ assert retried.status_code == 200+ assert "Install cancelled" in retried.text+ assert fixture.installer.revoked_tokens == ["xoxb-granted"]+++async def test_a_forged_ticket_is_refused(rls_harness: RLSHarness) -> None:+ fixture = await _fixture(rls_harness)++ async with _client(fixture.service) as client:+ response = await client.post(+ "/messaging/slack/oauth/confirm",+ data={"ticket": "not-a-ticket", "decision": "connect"},+ )++ assert response.status_code == 400+ assert fixture.lifecycle.registered == []diff --git a/core/tests/switch_core/bridges/collaboration/test_install_service.py b/core/tests/switch_core/bridges/collaboration/test_install_service.pyindex 8753798b9..ad49287ff 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_service.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_service.py@@ -15,10 +15,12 @@ from __future__ import annotationsimport uuidfrom collections.abc import Mapping+from datetime import UTC, datetime, timedeltafrom typing import ClassVarfrom urllib.parse import parse_qs, urlparseimport pytest+from sqlalchemy import updatefrom sqlalchemy.ext.asyncio import async_sessionmakerfrom switch_core.bridges.collaboration.install import (@@ -29,6 +31,9 @@ from switch_core.bridges.collaboration.install import (MessagingInstallError,WebhookEndpoint,)+from switch_core.bridges.collaboration.install_confirmation import (+ InstallTicketError,+)from switch_core.bridges.collaboration.install_service import (InstallPlatformMismatch,MessagingInstallService,@@ -38,11 +43,13 @@ from switch_core.bridges.collaboration.install_state import (InstallStateError,mint,)-from switch_core.crypto import decrypt_token+from switch_core.bridges.collaboration.lifecycle_service import BridgeClaimConflict+from switch_core.bridges.collaboration.models import BridgeCredentialErrorfrom switch_core.db.models import (Client,CollaborationBridge,MessagingInstall,+ MessagingInstallState,Tenant,User,)@@ -57,11 +64,12 @@ from switch_core.db.stores.messaging_install_store import (MessagingInstallStateError,MessagingInstallStore,)+from switch_core.keys import Keyringfrom tests.conftest import RLSHarnesspytestmark = pytest.mark.no_ambient_tenant-_SECRET = "test-secret"+_KEYRING = Keyring.parse("test:" + "s" * 40, legacy_secret=None)_ORIGIN = "https://switch.example"@@ -142,8 +150,24 @@ class _FakeLifecycle:self._suffix = suffixself.registered: list[dict[str, object]] = []self.removed: list[str] = []+ # Set to make the claim check refuse, as the real one does when another+ # bridge already connects the workspace.+ self.claim_conflict: str | None = None+ # Set to make the next registration fail before writing anything, as+ # the real one does when the platform rejects or cannot check the+ # credential. Cleared once raised, so a retry succeeds.+ self.register_failure: Exception | None = None++ async def reject_claim_conflict(+ self, bridge_type: str, connection_config: dict[str, object]+ ) -> None:+ if self.claim_conflict is not None:+ raise BridgeClaimConflict(self.claim_conflict)async def register(self, **kwargs: object) -> CollaborationBridge:+ if self.register_failure is not None:+ failure, self.register_failure = self.register_failure, None+ raise failureself.registered.append(kwargs)async with tenant_session(self._factory, self._tenant_id) as session:client = Client(@@ -219,7 +243,7 @@ async def _fixture(harness: RLSHarness, *, tokenless: bool = False) -> _Fixture:installers=installers,lifecycle=fixture.lifecycle, # type: ignore[arg-type]public_origin=_ORIGIN,- secret=_SECRET,+ keyring=_KEYRING,)return fixture@@ -237,11 +261,17 @@ async def _begin(factory: async_sessionmaker, fixture: _Fixture, tenant_id: str)async def _installed(factory: async_sessionmaker, fixture: _Fixture, tenant_id: str) -> MessagingInstall:- """Run both legs and return the install they produced."""+ """Run both legs, confirm, and return the install they produced."""state = await _begin(factory, fixture, tenant_id)- return await fixture.service.complete(+ return await _land(fixture, state)+++async def _land(fixture: _Fixture, state: str) -> MessagingInstall:+ """Finish the callback and choose Connect on the page it renders."""+ pending = await fixture.service.complete(platform="slack", code="the-code", state_token=state)+ return await fixture.service.confirm(platform="slack", ticket=pending.ticket)async def _reread(@@ -258,9 +288,7 @@ class TestTheRoundTrip:fixture = await _fixture(rls_harness)state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)- install = await fixture.service.complete(- platform="slack", code="the-code", state_token=state- )+ install = await _land(fixture, state)assert install.tenant_id == fixture.tenant_aassert install.external_workspace_id == fixture.workspace@@ -272,12 +300,10 @@ class TestTheRoundTrip:fixture = await _fixture(rls_harness)state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)- install = await fixture.service.complete(- platform="slack", code="the-code", state_token=state- )+ install = await _land(fixture, state)assert "xoxb-granted" not in install.encrypted_bot_token- assert decrypt_token(install.encrypted_bot_token, _SECRET) == "xoxb-granted"+ assert _KEYRING.decrypt(install.encrypted_bot_token) == "xoxb-granted"async def test_it_ends_with_a_bridge_the_install_points_at(self, rls_harness: RLSHarness@@ -287,9 +313,7 @@ class TestTheRoundTrip:fixture = await _fixture(rls_harness)state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)- install = await fixture.service.complete(- platform="slack", code="the-code", state_token=state- )+ install = await _land(fixture, state)assert len(fixture.lifecycle.registered) == 1registered = fixture.lifecycle.registered[0]@@ -363,7 +387,7 @@ class TestWhatTheCallbackWillNotDo:InstallState(tenant_id=fixture.tenant_b, state_id=state_id, platform="slack"),- secret=_SECRET,+ keyring=_KEYRING,)with pytest.raises(MessagingInstallStateError):await fixture.service.complete(@@ -389,7 +413,7 @@ class TestWhatTheCallbackWillNotDo:InstallState(tenant_id=fixture.tenant_a, state_id="whatever", platform="teams"),- secret=_SECRET,+ keyring=_KEYRING,)with pytest.raises(InstallPlatformMismatch):await fixture.service.complete(@@ -421,10 +445,254 @@ class TestWhatTheCallbackWillNotDo:state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)with pytest.raises(MessagingInstallClaimedError):+ await _land(fixture, state)+ assert fixture.lifecycle.registered == []++ async def test_a_workspace_a_manual_bridge_connects_is_refused_before_recording(+ self, rls_harness: RLSHarness+ ) -> None:+ """Refused before the install is written, not when its bridge is+ registered: an install left with no bridge would hold the workspace+ for nothing, and the next attempt would be refused by it."""+ fixture = await _fixture(rls_harness)+ fixture.lifecycle.claim_conflict = (+ f"Slack workspace {fixture.workspace} is already claimed"+ )++ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)+ with pytest.raises(MessagingInstallClaimedError, match="already claimed"):await fixture.service.complete(platform="slack", code="the-code", state_token=state)assert fixture.lifecycle.registered == []+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ assert await fixture.service.list_installs(session) == []++ async def test_a_workspace_claimed_while_the_page_was_open_is_refused_on_connect(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)+ pending = await fixture.service.complete(+ platform="slack", code="the-code", state_token=state+ )+ fixture.lifecycle.claim_conflict = (+ f"Slack workspace {fixture.workspace} is already claimed"+ )++ with pytest.raises(MessagingInstallClaimedError, match="already claimed"):+ await fixture.service.confirm(platform="slack", ticket=pending.ticket)+ assert fixture.lifecycle.registered == []+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ assert await fixture.service.list_installs(session) == []+++class TestAFailedRegistrationReleasesTheWorkspace:+ """The bridge is registered after the install is recorded, and a platform+ blip during its credential check must not leave an active install with no+ bridge holding the workspace against every retry."""++ async def _statuses(self, factory: async_sessionmaker, tenant_id: str) -> list[str]:+ async with tenant_session(factory, tenant_id) as session:+ installs = await MessagingInstallStore().list_for_tenant(session)+ return sorted(install.status for install in installs)++ async def test_a_credential_failure_ends_the_install_and_says_so(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ fixture.lifecycle.register_failure = BridgeCredentialError(+ "Could not reach Slack to check the bot token: timeout. Try again."+ )++ with pytest.raises(MessagingInstallError, match="Start the install again"):+ await _installed(rls_harness.restricted, fixture, fixture.tenant_a)++ assert await self._statuses(rls_harness.restricted, fixture.tenant_a) == [+ INSTALL_DISCONNECTED+ ]+ retry = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)+ assert retry.status == INSTALL_ACTIVE+ assert retry.bridge_id is not None++ async def test_any_other_failure_ends_it_too_and_is_not_disguised(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ fixture.lifecycle.register_failure = RuntimeError("database went away")++ with pytest.raises(RuntimeError, match="database went away"):+ await _installed(rls_harness.restricted, fixture, fixture.tenant_a)++ assert await self._statuses(rls_harness.restricted, fixture.tenant_a) == [+ INSTALL_DISCONNECTED+ ]+++class TestTheConfirmation:+ """The callback asks before it claims, and only the page's answer counts."""++ async def test_the_callback_claims_nothing_and_names_the_organisation(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)++ pending = await fixture.service.complete(+ platform="slack", code="the-code", state_token=state+ )++ assert pending.organisation == fixture.tenant_a+ assert pending.requested_by.endswith("@example.test")+ assert pending.workspace_name == "Acme"+ assert pending.external_workspace_id == fixture.workspace+ assert "xoxb-granted" not in pending.ticket+ assert fixture.lifecycle.registered == []+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ assert await MessagingInstallStore().list_for_tenant(session) == []++ async def test_the_state_token_alone_cannot_connect(+ self, rls_harness: RLSHarness+ ) -> None:+ """Whoever started the install holds the state; only the page holds+ the ticket. Otherwise they could confirm on the approver's behalf."""+ fixture = await _fixture(rls_harness)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)+ await fixture.service.complete(+ platform="slack", code="the-code", state_token=state+ )++ with pytest.raises(InstallTicketError):+ await fixture.service.confirm(platform="slack", ticket=state)+ assert fixture.lifecycle.registered == []++ async def test_a_tampered_ticket_is_refused(self, rls_harness: RLSHarness) -> None:+ fixture = await _fixture(rls_harness)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)+ pending = await fixture.service.complete(+ platform="slack", code="the-code", state_token=state+ )+ flipped = pending.ticket[:-5] + ("A" if pending.ticket[-5] != "A" else "B")+ tampered = flipped + pending.ticket[-4:]++ with pytest.raises(InstallTicketError):+ await fixture.service.confirm(platform="slack", ticket=tampered)++ async def test_a_ticket_for_another_platform_is_refused(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)+ pending = await fixture.service.complete(+ platform="slack", code="the-code", state_token=state+ )++ with pytest.raises(InstallPlatformMismatch):+ await fixture.service.confirm(platform="teams", ticket=pending.ticket)++ async def test_a_confirmation_connects_once(self, rls_harness: RLSHarness) -> None:+ fixture = await _fixture(rls_harness)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)+ pending = await fixture.service.complete(+ platform="slack", code="the-code", state_token=state+ )+ await fixture.service.confirm(platform="slack", ticket=pending.ticket)++ with pytest.raises(MessagingInstallStateError):+ await fixture.service.confirm(platform="slack", ticket=pending.ticket)+ with pytest.raises(MessagingInstallStateError):+ await fixture.service.cancel(platform="slack", ticket=pending.ticket)+ assert len(fixture.lifecycle.registered) == 1+ assert fixture.installer.revoked_tokens == []++ async def test_a_stale_confirmation_is_refused(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)+ pending = await fixture.service.complete(+ platform="slack", code="the-code", state_token=state+ )+ async with rls_harness.owner() as session:+ await session.execute(+ update(MessagingInstallState)+ .where(MessagingInstallState.tenant_id == fixture.tenant_a)+ .values(consumed_at=datetime.now(UTC) - timedelta(hours=1))+ )+ await session.commit()++ with pytest.raises(MessagingInstallStateError):+ await fixture.service.confirm(platform="slack", ticket=pending.ticket)+ assert fixture.lifecycle.registered == []++ async def test_cancel_records_nothing_and_revokes_the_token(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)+ pending = await fixture.service.complete(+ platform="slack", code="the-code", state_token=state+ )++ await fixture.service.cancel(platform="slack", ticket=pending.ticket)++ assert fixture.installer.revoked_tokens == ["xoxb-granted"]+ assert fixture.lifecycle.registered == []+ with pytest.raises(MessagingInstallStateError):+ await fixture.service.confirm(platform="slack", ticket=pending.ticket)+ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ assert await MessagingInstallStore().list_for_tenant(session) == []++ async def test_cancel_leaves_a_token_another_install_is_using(+ self, rls_harness: RLSHarness+ ) -> None:+ """The platform issues one bot token per app and workspace, so revoking+ it here would disconnect the tenant that already holds the workspace."""+ fixture = await _fixture(rls_harness)+ async with tenant_session(rls_harness.restricted, fixture.tenant_b) as session:+ session.add(+ MessagingInstall(+ tenant_id=fixture.tenant_b,+ platform="slack",+ external_workspace_id=fixture.workspace,+ encrypted_bot_token="ciphertext",+ scopes="chat:write",+ status="active",+ installed_by_user_id=fixture.user_id,+ )+ )+ await session.commit()+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)+ pending = await fixture.service.complete(+ platform="slack", code="the-code", state_token=state+ )++ await fixture.service.cancel(platform="slack", ticket=pending.ticket)++ assert fixture.installer.revoked_tokens == []++ async def test_a_cancel_whose_revocation_fails_can_be_retried(+ self, rls_harness: RLSHarness+ ) -> None:+ """The ticket is the only copy of the token, so a cancel recorded+ ahead of a failed revocation would strand a live credential."""+ fixture = await _fixture(rls_harness)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)+ pending = await fixture.service.complete(+ platform="slack", code="the-code", state_token=state+ )+ fixture.installer.revoke_error = MessagingInstallError("Slack is down")++ with pytest.raises(MessagingInstallError):+ await fixture.service.cancel(platform="slack", ticket=pending.ticket)++ fixture.installer.revoke_error = None+ await fixture.service.cancel(platform="slack", ticket=pending.ticket)++ assert fixture.installer.revoked_tokens == ["xoxb-granted"]+ assert fixture.lifecycle.registered == []+ with pytest.raises(MessagingInstallStateError):+ await fixture.service.cancel(platform="slack", ticket=pending.ticket)class TestDisconnecting:@@ -651,9 +919,7 @@ class TestATokenlessGrant:fixture = await _fixture(rls_harness, tokenless=True)state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)- install = await fixture.service.complete(- platform="slack", code="the-code", state_token=state- )+ install = await _land(fixture, state)assert install.encrypted_bot_token is Noneassert install.bridge_id is not Nonediff --git a/core/tests/switch_core/bridges/collaboration/test_install_state.py b/core/tests/switch_core/bridges/collaboration/test_install_state.pyindex 6ba915df0..bdb277899 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_state.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_state.py@@ -22,19 +22,22 @@ from switch_core.bridges.collaboration.install_state import (mint,verify,)+from switch_core.keys import Keyring, Purpose-_SECRET = "test-jwt-secret"+_MASTER = "a" * 40+_KEYRING = Keyring.parse(f"k1:{_MASTER}", legacy_secret=None)+_LEGACY = "test-jwt-secret"_STATE = InstallState(tenant_id="tenant-a", state_id="state-1", platform="slack")def test_a_minted_state_verifies_back_to_what_went_in() -> None:- assert verify(mint(_STATE, secret=_SECRET), secret=_SECRET) == _STATE+ assert verify(mint(_STATE, keyring=_KEYRING), keyring=_KEYRING) == _STATEdef test_the_token_is_safe_in_a_url() -> None:"""It travels as a query parameter through a redirect the platform builds."""- token = mint(_STATE, secret=_SECRET)+ token = mint(_STATE, keyring=_KEYRING)assert all(c.isalnum() or c in "-_." for c in token)@@ -45,7 +48,7 @@ class TestForgery:Swapping the tenant in a captured state is how you would attach yourown workspace to someone else's rooms."""- token = mint(_STATE, secret=_SECRET)+ token = mint(_STATE, keyring=_KEYRING)payload, signature = token.removeprefix("v1.").split(".")decoded = json.loads(base64.urlsafe_b64decode(payload + "=="))decoded["tid"] = "tenant-b"@@ -54,27 +57,29 @@ class TestForgery:)with pytest.raises(InstallStateError):- verify(f"v1.{forged}.{signature}", secret=_SECRET)+ verify(f"v1.{forged}.{signature}", keyring=_KEYRING)def test_a_state_from_another_deployment_is_refused(self) -> None:- token = mint(_STATE, secret="a-different-secret")+ token = mint(+ _STATE, keyring=Keyring.parse(f"k1:{'b' * 40}", legacy_secret=None)+ )with pytest.raises(InstallStateError, match="not signed by this deployment"):- verify(token, secret=_SECRET)+ verify(token, keyring=_KEYRING)- def test_the_key_is_not_the_jwt_key_itself(self) -> None:+ def test_the_key_is_not_the_master_key_itself(self) -> None:"""Domain separation, so one signature can never be read as the other.Asserted by construction rather than by outcome: the token is signed- under a derived key, so signing the same payload with the raw secret- produces something this refuses.+ under a derived key, so signing the same payload with the raw master+ secret produces something this refuses."""- token = mint(_STATE, secret=_SECRET)+ token = mint(_STATE, keyring=_KEYRING)payload = token.removeprefix("v1.").split(".")[0]- raw = hmac.new(_SECRET.encode(), payload.encode(), hashlib.sha256).digest()+ raw = hmac.new(_MASTER.encode(), payload.encode(), hashlib.sha256).digest()naive = base64.urlsafe_b64encode(raw).decode().rstrip("=")with pytest.raises(InstallStateError):- verify(f"v1.{payload}.{naive}", secret=_SECRET)+ verify(f"v1.{payload}.{naive}", keyring=_KEYRING)class TestMalformed:@@ -87,7 +92,7 @@ class TestMalformed:"v1.only-one-part","v1.a.b.c","v1.!!!.!!!",- "v2." + mint(_STATE, secret=_SECRET).removeprefix("v1."),+ "v2." + mint(_STATE, keyring=_KEYRING).removeprefix("v1."),],)def test_garbage_is_an_error_and_not_a_crash(self, token: str) -> None:@@ -97,14 +102,12 @@ class TestMalformed:because the caller is unauthenticated by nature."""with pytest.raises(InstallStateError):- verify(token, secret=_SECRET)+ verify(token, keyring=_KEYRING)def test_a_well_signed_payload_that_is_not_a_state_is_refused(self) -> None:"""Signed by us, but not this. A key used for two things is a bug."""payload = base64.urlsafe_b64encode(b'{"sub":"agent-1"}').decode().rstrip("=")- key = hmac.new(- _SECRET.encode(), b"switch/messaging-install-state/v1", hashlib.sha256- ).digest()+ key = _KEYRING.derive(Purpose.INSTALL_STATE)signature = (base64.urlsafe_b64encode(hmac.new(key, payload.encode(), hashlib.sha256).digest()@@ -114,4 +117,40 @@ class TestMalformed:)with pytest.raises(InstallStateError, match="malformed"):- verify(f"v1.{payload}.{signature}", secret=_SECRET)+ verify(f"v1.{payload}.{signature}", keyring=_KEYRING)+++def _legacy_token(secret: str) -> str:+ """A state as it was signed with `JWT_SECRET_KEY` before `SECRET_KEYS`."""+ payload = (+ base64.urlsafe_b64encode(+ json.dumps(+ {"plat": "slack", "sid": "state-1", "tid": "tenant-a"},+ separators=(",", ":"),+ sort_keys=True,+ ).encode()+ )+ .decode()+ .rstrip("=")+ )+ key = hmac.new(+ secret.encode(), b"switch/messaging-install-state/v1", hashlib.sha256+ ).digest()+ signature = hmac.new(key, payload.encode(), hashlib.sha256).digest()+ return f"v1.{payload}.{base64.urlsafe_b64encode(signature).decode().rstrip('=')}"+++class TestKeyChanges:+ def test_a_state_minted_before_a_rotation_still_verifies(self) -> None:+ rotated = Keyring.parse(f"k2:{'c' * 40},k1:{_MASTER}", legacy_secret=None)+ assert verify(mint(_STATE, keyring=_KEYRING), keyring=rotated) == _STATE++ def test_a_state_signed_with_the_legacy_secret_verifies_while_it_is_set(+ self,+ ) -> None:+ keyring = Keyring.parse(f"k1:{_MASTER}", legacy_secret=_LEGACY)+ assert verify(_legacy_token(_LEGACY), keyring=keyring) == _STATE++ def test_and_not_once_it_is_removed(self) -> None:+ with pytest.raises(InstallStateError, match="not signed"):+ verify(_legacy_token(_LEGACY), keyring=_KEYRING)diff --git a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py b/core/tests/switch_core/bridges/collaboration/test_install_webhook.pyindex ca48cc969..248798a48 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_webhook.py@@ -62,13 +62,14 @@ from switch_core.db.stores.messaging_event_store import (MessagingEventReceiptStore,)from switch_core.db.stores.messaging_install_store import MessagingInstallStore+from switch_core.keys import Keyringfrom switch_core.tenant_context import current_tenant_idfrom tests.conftest import RLSHarnesspytestmark = pytest.mark.no_ambient_tenant_SIGNING_SECRET = "test-signing-secret"-_SECRET = "test-secret"+_KEYRING = Keyring.parse("test:" + "x" * 40, legacy_secret=None)_ORIGIN = "https://switch.example"@@ -282,7 +283,7 @@ async def _fixture(harness: RLSHarness) -> _Fixture:installers=installers,lifecycle=fixture.lifecycle, # type: ignore[arg-type]public_origin=_ORIGIN,- secret=_SECRET,+ keyring=_KEYRING,)app = FastAPI()diff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.pyindex 4c6e517b3..4bf5bbbbf 100644--- a/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py@@ -41,6 +41,7 @@ from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.client_store import ClientStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.room_store import RoomStore+from switch_core.keys import Keyringfrom switch_core.tenant_context import current_tenant_id, tenant_scopefrom tests.conftest import RLSHarness@@ -54,7 +55,7 @@ def _service(config.gateway_public_url = "https://gw.example"config.collaboration_callback_host = "127.0.0.1"config.collaboration_callback_port = callback_port- config.jwt_secret_key = "server-secret-for-tests"+ config.keyring = Keyring.parse("test:" + "x" * 40, legacy_secret=None)return CollaborationBridgeLifecycleService(bridge_store=CollaborationBridgeStore(),external_user_store=MagicMock(),@@ -376,7 +377,7 @@ async def test_a_host_resource_conflict_is_looked_for_across_every_tenant(with tenant_scope(newcomer_tenant):with pytest.raises(ValueError, match="port:3979 is already claimed"):- await service._reject_resource_conflict("teams", {"listen_port": 3979})+ await service.reject_claim_conflict("teams", {"listen_port": 3979})assert sorted(seen) == sorted([TENANT_ZERO_ID, incumbent_tenant, newcomer_tenant]@@ -393,7 +394,7 @@ async def test_a_tenant_scoped_read_of_the_same_data_would_have_missed_the_confl) -> None:"""The row-visibility half of the test above, made real: the sameincumbent bridge, read through `CollaborationBridgeStore.get_all` — the- exact method `_reject_resource_conflict` calls — but scoped to the+ exact method `reject_claim_conflict` calls — but scoped to thenewcomer's tenant instead of left unscoped. It comes back empty, which iswhat would have let a second Teams listener claim the same port undetectedhad the application code above been scoped instead of deliberately@@ -477,7 +478,7 @@ async def test_a_same_tenant_conflict_names_the_incumbent_bridge(with tenant_scope(tenant):with pytest.raises(ValueError) as excinfo:- await service._reject_resource_conflict("teams", {"listen_port": 3979})+ await service.reject_claim_conflict("teams", {"listen_port": 3979})assert "Our Existing Teams" in str(excinfo.value)@@ -523,7 +524,7 @@ async def test_a_cross_tenant_conflict_does_not_name_the_incumbent_or_its_tenantwith tenant_scope(newcomer_tenant):with pytest.raises(ValueError) as excinfo:- await service._reject_resource_conflict("teams", {"listen_port": 3979})+ await service.reject_claim_conflict("teams", {"listen_port": 3979})message = str(excinfo.value)assert "Their Secret Teams" not in message@@ -572,7 +573,7 @@ async def test_a_conflict_with_nothing_bound_fails_closed_to_the_non_disclosing_assert current_tenant_id() is Nonewith pytest.raises(ValueError) as excinfo:- await service._reject_resource_conflict("teams", {"listen_port": 3979})+ await service.reject_claim_conflict("teams", {"listen_port": 3979})message = str(excinfo.value)assert "Their Secret Teams" not in messagediff --git a/core/tests/switch_core/bridges/collaboration/test_mattermost_callback.py b/core/tests/switch_core/bridges/collaboration/test_mattermost_callback.pyindex cef7fe10f..19473d8db 100644--- a/core/tests/switch_core/bridges/collaboration/test_mattermost_callback.py+++ b/core/tests/switch_core/bridges/collaboration/test_mattermost_callback.py@@ -21,8 +21,9 @@ from switch_core.bridges.collaboration.mattermost.callback import (action_context,read_press,)+from switch_core.keys import Keyring-SERVER_SECRET = "server-secret-for-tests"+SERVER_SECRET = "server-secret-for-tests-server-secret"BRIDGE_ID = "bridge-1"OTHER_BRIDGE_ID = "bridge-2"TOKEN = "tok-1"@@ -35,7 +36,11 @@ CHANNEL_ID = "channel-abc"def _key_for(bridge_id: str, secret: str = SERVER_SECRET) -> str:"""The key a bridge would really be handed, derived the way production does."""- ingress = CallbackIngress(host="127.0.0.1", port=0, secret=secret)+ ingress = CallbackIngress(+ host="127.0.0.1",+ port=0,+ keyring=Keyring.parse(f"test:{secret}", legacy_secret=None),+ )return ingress.endpoint_for("mattermost", bridge_id).key@@ -56,7 +61,7 @@ def _body(context: dict[str, Any], **overrides: Any) -> dict[str, Any]:def test_a_signed_press_reads_back_as_what_it_was_built_from() -> None:- press = read_press(_key(), _body(action_context(_key(), TOKEN, POSITION)))+ press = read_press([_key()], _body(action_context(_key(), TOKEN, POSITION)))assert press is not Noneassert press.token == TOKEN@@ -84,21 +89,21 @@ def test_the_signature_is_the_same_every_time_it_is_built() -> None:def test_a_body_with_no_context_is_not_ours() -> None:- assert read_press(_key(), {"user_id": USER_ID, "post_id": POST_ID}) is None+ assert read_press([_key()], {"user_id": USER_ID, "post_id": POST_ID}) is Nonedef test_a_context_from_another_integration_is_passed_over() -> None:- assert read_press(_key(), _body({"action": "something-else"})) is None+ assert read_press([_key()], _body({"action": "something-else"})) is Nonedef test_a_context_that_is_not_an_object_is_not_ours() -> None:- assert read_press(_key(), _body({CONTEXT_KEY: "answer"})) is None+ assert read_press([_key()], _body({CONTEXT_KEY: "answer"})) is Nonedef test_an_unsigned_context_is_refused() -> None:context = {CONTEXT_KEY: {"token": TOKEN, "position": POSITION}}- assert read_press(_key(), _body(context)) is None+ assert read_press([_key()], _body(context)) is Nonedef test_a_position_changed_after_signing_is_refused_and_logged(@@ -108,7 +113,7 @@ def test_a_position_changed_after_signing_is_refused_and_logged(context[CONTEXT_KEY]["position"] = POSITION + 1with caplog.at_level(logging.WARNING):- assert read_press(_key(), _body(context)) is None+ assert read_press([_key()], _body(context)) is Noneassert "signature does not verify" in caplog.text@@ -117,21 +122,21 @@ def test_a_token_changed_after_signing_is_refused() -> None:context = action_context(_key(), TOKEN, POSITION)context[CONTEXT_KEY]["token"] = "tok-2"- assert read_press(_key(), _body(context)) is None+ assert read_press([_key()], _body(context)) is Nonedef test_another_bridges_signature_is_refused() -> None:context = action_context(_key_for(OTHER_BRIDGE_ID), TOKEN, POSITION)- assert read_press(_key(), _body(context)) is None+ assert read_press([_key()], _body(context)) is Nonedef test_a_signature_from_a_rotated_secret_says_so(caplog: Any) -> None:- stale = _key_for(BRIDGE_ID, secret="the-previous-server-secret")+ stale = _key_for(BRIDGE_ID, secret="the-previous-server-secret-000000")context = action_context(stale, TOKEN, POSITION)with caplog.at_level(logging.WARNING):- assert read_press(_key(), _body(context)) is None+ assert read_press([_key()], _body(context)) is Noneassert "rotated" in caplog.textassert TOKEN in caplog.text@@ -140,9 +145,9 @@ def test_a_signature_from_a_rotated_secret_says_so(caplog: Any) -> None:def test_a_press_naming_nobody_is_refused() -> None:context = action_context(_key(), TOKEN, POSITION)- assert read_press(_key(), _body(context, user_id="")) is None- assert read_press(_key(), _body(context, post_id="")) is None- assert read_press(_key(), _body(context, channel_id="")) is None+ assert read_press([_key()], _body(context, user_id="")) is None+ assert read_press([_key()], _body(context, post_id="")) is None+ assert read_press([_key()], _body(context, channel_id="")) is Nonedef test_an_actor_smuggled_into_the_context_is_refused() -> None:@@ -156,7 +161,7 @@ def test_an_actor_smuggled_into_the_context_is_refused() -> None:context = action_context(_key(), TOKEN, POSITION)context[CONTEXT_KEY]["user_id"] = "somebody-else"- assert read_press(_key(), _body(context)) is None+ assert read_press([_key()], _body(context)) is Nonedef test_a_position_that_is_not_a_counting_number_is_refused() -> None:@@ -168,7 +173,7 @@ def test_a_position_that_is_not_a_counting_number_is_refused() -> None:"signature": "whatever",}}- assert read_press(_key(), _body(context)) is None+ assert read_press([_key()], _body(context)) is Nonedef test_a_token_that_is_not_a_string_is_refused() -> None:@@ -180,4 +185,4 @@ def test_a_token_that_is_not_a_string_is_refused() -> None:"signature": "whatever",}}- assert read_press(_key(), _body(context)) is None+ assert read_press([_key()], _body(context)) is Nonediff --git a/core/tests/switch_core/bridges/collaboration/test_mattermost_card_buttons.py b/core/tests/switch_core/bridges/collaboration/test_mattermost_card_buttons.pyindex 0a0f18060..b22089abf 100644--- a/core/tests/switch_core/bridges/collaboration/test_mattermost_card_buttons.py+++ b/core/tests/switch_core/bridges/collaboration/test_mattermost_card_buttons.py@@ -128,7 +128,7 @@ async def test_each_button_is_signed_for_its_own_option() -> None:for button in _buttons(_created(adapter))]assert len({context["signature"] for context in contexts}) == 2- presses = [read_press(_key(), _body({"switch": context})) for context in contexts]+ presses = [read_press([_key()], _body({"switch": context})) for context in contexts]assert [press.position for press in presses if press is not None] == [1, 2]@@ -140,7 +140,7 @@ async def test_a_context_signed_for_one_option_does_not_verify_for_another() ->forged = dict(first["integration"]["context"]["switch"])forged["position"] = second["integration"]["context"]["switch"]["position"]- assert read_press(_key(), _body({"switch": forged})) is None+ assert read_press([_key()], _body({"switch": forged})) is Noneasync def test_the_body_drops_the_options_the_buttons_already_show() -> None:diff --git a/core/tests/switch_core/bridges/collaboration/test_mattermost_press.py b/core/tests/switch_core/bridges/collaboration/test_mattermost_press.pyindex b77f0e094..10594aba4 100644--- a/core/tests/switch_core/bridges/collaboration/test_mattermost_press.py+++ b/core/tests/switch_core/bridges/collaboration/test_mattermost_press.py@@ -31,11 +31,13 @@ from switch_core.bridges.collaboration.mattermost.adapter import ()from switch_core.bridges.collaboration.mattermost.callback import action_contextfrom switch_core.bridges.collaboration.models import InboundInteraction+from switch_core.keys import Keyringfrom .test_collaboration_ingress import _free_portfrom .test_mattermost_sdk_only import _FakeDriver, _FakePosts, _FakeUsers, _posts-SECRET = "server-secret-for-tests"+SECRET = "server-secret-for-tests-server-secret"+KEYRING = Keyring.parse(f"test:{SECRET}", legacy_secret=None)BRIDGE = "bridge-1"OTHER_BRIDGE = "bridge-2"CALLBACK_BASE = "http://switch.example:8081"@@ -78,7 +80,7 @@ def _adapter(def _ingress() -> CallbackIngress:- return CallbackIngress(host="127.0.0.1", port=_free_port(), secret=SECRET)+ return CallbackIngress(host="127.0.0.1", port=_free_port(), keyring=KEYRING)def _users(adapter: MattermostAdapter) -> _FakeUsers:diff --git a/core/tests/switch_core/bridges/collaboration/test_shared_bridge_install_guard.py b/core/tests/switch_core/bridges/collaboration/test_shared_bridge_install_guard.pyindex 790b027f9..79c9e0094 100644--- a/core/tests/switch_core/bridges/collaboration/test_shared_bridge_install_guard.py+++ b/core/tests/switch_core/bridges/collaboration/test_shared_bridge_install_guard.py@@ -28,8 +28,8 @@ from switch_core.db.stores.messaging_install_store import MessagingInstallStorefrom tests.conftest import RLSHarnessfrom .test_install_service import (+ _KEYRING,_ORIGIN,- _SECRET,_begin,_FakeInstaller,_FakeLifecycle,@@ -93,13 +93,14 @@ async def _shared_app(harness: RLSHarness) -> tuple[MessagingInstallService, _Idinstallers=installers,lifecycle=lifecycle, # type: ignore[arg-type]public_origin=_ORIGIN,- secret=_SECRET,+ keyring=_KEYRING,)lifecycle.service = servicelifecycle.workspace_id = base.workspacebase.service = servicestate = await _begin(harness.restricted, base, base.tenant_a)- install = await service.complete(platform="slack", code="c", state_token=state)+ pending = await service.complete(platform="slack", code="c", state_token=state)+ install = await service.confirm(platform="slack", ticket=pending.ticket)assert install.bridge_id is not Nonereturn service, _Ids(tenant_a=base.tenant_a,diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.pyindex 86fbdb5c6..3a4d351b9 100644--- a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py@@ -15,13 +15,15 @@ from switch_core.bridges.collaboration.slack.adapter import (def _adapter() -> SlackAdapter:- return SlackAdapter(+ adapter = SlackAdapter(config=SlackConnectionConfig(bot_token="xoxb-test",app_token="xapp-test",workspace_id="T123",))+ adapter.set_tenant_id("tenant-1")+ return adapterdef _run(coro: Any) -> Any:diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_agent_usergroups.py b/core/tests/switch_core/bridges/collaboration/test_slack_agent_usergroups.pyindex 359ba1e28..2d3b97dc1 100644--- a/core/tests/switch_core/bridges/collaboration/test_slack_agent_usergroups.py+++ b/core/tests/switch_core/bridges/collaboration/test_slack_agent_usergroups.py@@ -112,6 +112,7 @@ def _adapter(enabled: bool = True,groups: list[dict[str, Any]] | None = None,team_id: str = "T123",+ tenant_id: str = "tenant-a",) -> tuple[SlackAdapter, FakeWebClient]:adapter = SlackAdapter(config=SlackConnectionConfig(@@ -124,6 +125,7 @@ def _adapter(# Normally set from auth.test; the shared directory keys contributions on# it, so two adapters in one test must not look like the same workspace.adapter._team_id = team_id+ adapter.set_tenant_id(tenant_id)client = FakeWebClient(groups)adapter._web_client = client # type: ignore[assignment]return adapter, client@@ -457,6 +459,37 @@ def test_a_stopped_bridge_stops_answering_for_its_workspace() -> None:assert sibling.translate_inbound("<!subteam^S001> hi") == "<!subteam^S001> hi"+def test_another_tenants_workspace_never_resolves_the_group() -> None:+ """The directory is shared by every Slack bridge in the process, which+ serves every tenant. A group another tenant's bridge minted names an agent+ this tenant cannot address, so it must stay unresolved here."""+ home, _ = _adapter(+ groups=[_agent_group("S001", "flint-tracker")],+ team_id="T111",+ tenant_id="tenant-a",+ )+ _run(home._load_agent_usergroups())++ foreign, _ = _adapter(team_id="T222", tenant_id="tenant-b")+ _run(foreign._load_agent_usergroups())++ assert foreign.translate_inbound("<!subteam^S001> hi") == "<!subteam^S001> hi"+++def test_a_group_is_unresolvable_before_the_tenant_is_known() -> None:+ adapter = SlackAdapter(+ config=SlackConnectionConfig(+ bot_token="xoxb-test",+ app_token="xapp-test",+ workspace_id="T123",+ agent_usergroups=True,+ )+ )++ with pytest.raises(RuntimeError, match="set_tenant_id"):+ adapter.translate_inbound("<!subteam^S001> hi")++# ── Rate limiting ────────────────────────────────────────────────────────────diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_installer.py b/core/tests/switch_core/bridges/collaboration/test_slack_installer.pyindex ea8695a44..b15e9c65f 100644--- a/core/tests/switch_core/bridges/collaboration/test_slack_installer.py+++ b/core/tests/switch_core/bridges/collaboration/test_slack_installer.py@@ -13,6 +13,7 @@ import jsonimport timefrom urllib.parse import urlencode+import aiohttpimport pytestfrom slack_sdk.web.async_client import AsyncWebClient@@ -215,6 +216,27 @@ class TestRedeem:)+class TestRevoke:+ @pytest.mark.parametrize(+ "failure",+ [aiohttp.ClientConnectionError("connection refused"), TimeoutError()],+ )+ async def test_slack_out_of_reach_is_an_install_error(+ self,+ installer: SlackAppInstaller,+ monkeypatch: pytest.MonkeyPatch,+ failure: Exception,+ ) -> None:+ """So a caller can tell the approver to try again, not answer 500."""++ async def fake(self, **kwargs): # noqa: ANN001, ANN202+ raise failure++ monkeypatch.setattr(AsyncWebClient, "auth_revoke", fake)+ with pytest.raises(MessagingInstallError, match="Could not reach Slack"):+ await installer.revoke(bot_token="xoxb-granted")++class TestParsingAWebhook:"""Turning three differently-shaped bodies into what Socket Mode delivers.diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.py b/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.pyindex e76ce9a05..89833ad2b 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.py@@ -388,7 +388,7 @@ def test_outbound_only_adapters_claim_nothing() -> None:# The one tenant these tests pretend the deployment has. Named rather than# repeated: the stubbed lookup answers with it, and the fake rows have to-# carry it, or the per-tenant filter in `_reject_resource_conflict` drops them.+# carry it, or the per-tenant filter in `reject_claim_conflict` drops them._STUB_TENANT = "tenant-a"diff --git a/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.py b/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.pyindex 00e15b169..351bb72d2 100644--- a/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.py+++ b/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.py@@ -57,6 +57,7 @@ def _service(client_factory=client_factory, # type: ignore[arg-type]session_factory=session_factory,config=MagicMock(),+ tenants_isolated=True,)diff --git a/core/tests/switch_core/clients/test_client_registry_tenants.py b/core/tests/switch_core/clients/test_client_registry_tenants.pyindex 2d8175597..6807d3507 100644--- a/core/tests/switch_core/clients/test_client_registry_tenants.py+++ b/core/tests/switch_core/clients/test_client_registry_tenants.py@@ -73,6 +73,7 @@ def _service(client_factory=_StubFactory(), # type: ignore[arg-type]session_factory=session_factory,config=SimpleNamespace(id_server_name="test"), # type: ignore[arg-type]+ tenants_isolated=True,)diff --git a/core/tests/switch_core/clients/test_client_task_replacement.py b/core/tests/switch_core/clients/test_client_task_replacement.pyindex a4a4d953e..fc371cb3f 100644--- a/core/tests/switch_core/clients/test_client_task_replacement.py+++ b/core/tests/switch_core/clients/test_client_task_replacement.py@@ -42,6 +42,7 @@ def _service() -> ClientLifecycleService:client_factory=MagicMock(),session_factory=MagicMock(),config=MagicMock(),+ tenants_isolated=True,)diff --git a/core/tests/switch_core/clients/test_client_tenant_plumbing.py b/core/tests/switch_core/clients/test_client_tenant_plumbing.pyindex bf06ac251..266ad4ea1 100644--- a/core/tests/switch_core/clients/test_client_tenant_plumbing.py+++ b/core/tests/switch_core/clients/test_client_tenant_plumbing.py@@ -151,6 +151,7 @@ class TestAFreshlyWrittenRowAlreadyCarriesIt:client_factory=MagicMock(),session_factory=session_factory,config=SimpleNamespace(id_server_name="test"), # type: ignore[arg-type]+ tenants_isolated=True,)with tenant_scope(tenant_id):@@ -172,6 +173,7 @@ class TestAFreshlyWrittenRowAlreadyCarriesIt:client_factory=MagicMock(),session_factory=session_factory,config=SimpleNamespace(id_server_name="test"), # type: ignore[arg-type]+ tenants_isolated=True,)record = await service.create_client(diff --git a/core/tests/switch_core/clients/test_ensure_system_client.py b/core/tests/switch_core/clients/test_ensure_system_client.pyindex 4312b8c45..86d65b39d 100644--- a/core/tests/switch_core/clients/test_ensure_system_client.py+++ b/core/tests/switch_core/clients/test_ensure_system_client.py@@ -53,6 +53,7 @@ def _service(client_factory=MagicMock(),session_factory=session_factory,config=SimpleNamespace(id_server_name="test"), # type: ignore[arg-type]+ tenants_isolated=True,)diff --git a/core/tests/switch_core/db/test_dead_peer_detection.py b/core/tests/switch_core/db/test_dead_peer_detection.pyindex c0ddce799..6a8c649cd 100644--- a/core/tests/switch_core/db/test_dead_peer_detection.py+++ b/core/tests/switch_core/db/test_dead_peer_detection.py@@ -37,7 +37,7 @@ _BASE_KWARGS = dict(db_name="switch",id_server_name="switch.local",agent_registration_token="token",- jwt_secret_key="jwt",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",gateway_admin_email="[email protected]",gateway_admin_password="pw",)diff --git a/core/tests/switch_core/db/test_encrypted_connection_config.py b/core/tests/switch_core/db/test_encrypted_connection_config.pynew file mode 100644index 000000000..834c5e047--- /dev/null+++ b/core/tests/switch_core/db/test_encrypted_connection_config.py@@ -0,0 +1,173 @@+"""Connection configs are encrypted at rest, and plaintext ones are converted.++A bridge's connection config carries the platform credentials the server acts+with. These tests read the stored column back with raw SQL — what a database+dump or a stray read-only grant would show — and assert the credential is not+in it, while the application still reads the dict it wrote.++The boot conversion runs through `rls_harness.restricted`, the role the server+connects as, so it is proved to reach every tenant's rows through the+per-tenant fan-out rather than through an owner connection's policy exemption.+"""++from __future__ import annotations++import json+import uuid++import pytest+from sqlalchemy import select, text+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db import encrypted_json+from switch_core.db.key_rotation import reencrypt_stored_secrets+from switch_core.db.models import Client, CollaborationBridge, Tenant+from switch_core.db.session_scope import tenant_session+from tests.conftest import TEST_KEYRING, RLSHarness++pytestmark = pytest.mark.no_ambient_tenant++_SECRET_VALUE = "placeholder-bot-token-for-tests"+++async def _make_tenant(session_factory: async_sessionmaker[AsyncSession]) -> str:+ tenant_id = f"tenant-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ await session.commit()+ return tenant_id+++async def _make_bridge(+ session_factory: async_sessionmaker[AsyncSession],+ tenant_id: str,+ config: dict[str, str],+) -> str:+ async with tenant_session(session_factory, tenant_id) as session:+ client = Client(+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:switch.local",+ display_name="bridge client",+ type="bridge",+ )+ session.add(client)+ await session.flush()+ bridge = CollaborationBridge(+ type="slack",+ display_name="Slack",+ client_id=client.id,+ status="active",+ connection_config=config,+ )+ session.add(bridge)+ await session.commit()+ return bridge.id+++async def _raw_config(+ session_factory: async_sessionmaker[AsyncSession], bridge_id: str+) -> object:+ async with session_factory() as session:+ result = await session.execute(+ text("SELECT connection_config FROM collaboration_bridges WHERE id = :id"),+ {"id": bridge_id},+ )+ return result.scalar_one()+++async def _read_config(+ session_factory: async_sessionmaker[AsyncSession], tenant_id: str, bridge_id: str+) -> dict | None:+ async with tenant_session(session_factory, tenant_id) as session:+ bridge = (+ await session.execute(+ select(CollaborationBridge).where(CollaborationBridge.id == bridge_id)+ )+ ).scalar_one()+ return bridge.connection_config+++async def test_a_written_config_is_stored_encrypted_and_reads_back(+ rls_harness: RLSHarness,+) -> None:+ tenant = await _make_tenant(rls_harness.owner)+ config = {"bot_token": _SECRET_VALUE, "workspace": "example"}++ bridge_id = await _make_bridge(rls_harness.restricted, tenant, config)++ raw = await _raw_config(rls_harness.owner, bridge_id)+ assert encrypted_json.is_encrypted(raw)+ assert _SECRET_VALUE not in json.dumps(raw)+ assert await _read_config(rls_harness.restricted, tenant, bridge_id) == config+++async def test_boot_encrypts_every_tenants_plaintext_configs(+ rls_harness: RLSHarness,+) -> None:+ tenant_a = await _make_tenant(rls_harness.owner)+ tenant_b = await _make_tenant(rls_harness.owner)+ config_a = {"bot_token": f"{_SECRET_VALUE}-a"}+ config_b = {"bot_token": f"{_SECRET_VALUE}-b"}+ bridge_a = await _make_bridge(rls_harness.owner, tenant_a, config_a)+ bridge_b = await _make_bridge(rls_harness.owner, tenant_b, config_b)+ # What a row written before encryption existed looks like.+ async with rls_harness.owner() as session:+ for bridge_id, config in ((bridge_a, config_a), (bridge_b, config_b)):+ await session.execute(+ text(+ "UPDATE collaboration_bridges "+ "SET connection_config = CAST(:config AS jsonb) WHERE id = :id"+ ),+ {"config": json.dumps(config), "id": bridge_id},+ )+ await session.commit()+ assert await _read_config(rls_harness.restricted, tenant_a, bridge_a) == config_a++ await reencrypt_stored_secrets(+ rls_harness.restricted, TEST_KEYRING, [tenant_a, tenant_b]+ )++ for tenant, bridge_id, config in (+ (tenant_a, bridge_a, config_a),+ (tenant_b, bridge_b, config_b),+ ):+ raw = await _raw_config(rls_harness.owner, bridge_id)+ assert encrypted_json.is_encrypted(raw)+ assert config["bot_token"] not in json.dumps(raw)+ assert await _read_config(rls_harness.restricted, tenant, bridge_id) == config+++async def test_boot_conversion_leaves_encrypted_and_empty_configs_alone(+ rls_harness: RLSHarness,+) -> None:+ tenant = await _make_tenant(rls_harness.owner)+ encrypted_id = await _make_bridge(+ rls_harness.owner, tenant, {"bot_token": _SECRET_VALUE}+ )+ before = await _raw_config(rls_harness.owner, encrypted_id)+ async with tenant_session(rls_harness.restricted, tenant) as session:+ empty = CollaborationBridge(+ type="slack",+ display_name="Empty",+ client_id=(+ await session.execute(+ select(CollaborationBridge.client_id).where(+ CollaborationBridge.id == encrypted_id+ )+ )+ ).scalar_one(),+ status="active",+ connection_config=None,+ )+ session.add(empty)+ await session.commit()+ empty_id = empty.id++ async with tenant_session(rls_harness.restricted, tenant) as session:+ rewritten = await encrypted_json.reencrypt_stale_values(+ session, CollaborationBridge, "connection_config"+ )+ await session.commit()++ assert rewritten == 0+ assert await _raw_config(rls_harness.owner, encrypted_id) == before+ assert await _raw_config(rls_harness.owner, empty_id) is Nonediff --git a/core/tests/switch_core/db/test_key_rotation.py b/core/tests/switch_core/db/test_key_rotation.pynew file mode 100644index 000000000..c9a78ab11--- /dev/null+++ b/core/tests/switch_core/db/test_key_rotation.py@@ -0,0 +1,163 @@+"""Boot brings every stored secret onto the current key.++Values are seeded under a legacy `JWT_SECRET_KEY` and under an older key in+`SECRET_KEYS`, in two tenants, and the sweep runs through+`rls_harness.restricted` — the role the server connects as — so it is proved to+reach every tenant's rows through the per-tenant fan-out. The stored columns+are then read back raw, as a dump would show them.+"""++from __future__ import annotations++import base64+import hashlib+import uuid++import pytest+from cryptography.fernet import Fernet+from sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db import encrypted_json+from switch_core.db.key_rotation import reencrypt_stored_secrets+from switch_core.db.models import (+ ApiKey,+ Client,+ CollaborationBridge,+ MessagingInstall,+ Tenant,+ User,+)+from switch_core.db.session_scope import tenant_session+from switch_core.keys import Keyring, UndecryptableError+from tests.conftest import RLSHarness++pytestmark = pytest.mark.no_ambient_tenant++_LEGACY = "legacy-jwt-secret-for-tests"+_OLD = Keyring.parse("old:" + "o" * 40, legacy_secret=_LEGACY)+_NEW = Keyring.parse("new:" + "n" * 40 + ",old:" + "o" * 40, legacy_secret=_LEGACY)+++def _legacy_encrypt(plaintext: str) -> str:+ key = base64.urlsafe_b64encode(hashlib.sha256(_LEGACY.encode()).digest())+ return Fernet(key).encrypt(plaintext.encode()).decode()+++async def _tenant_with_user(owner: async_sessionmaker[AsyncSession]) -> tuple[str, str]:+ suffix = uuid.uuid4().hex[:8]+ async with owner() as session:+ session.add(Tenant(id=f"tenant-{suffix}", slug=suffix, name=suffix))+ user = User(name=f"user-{suffix}", email=f"{suffix}@example.test", role="user")+ session.add(user)+ await session.commit()+ return f"tenant-{suffix}", user.id+++async def _seed(+ restricted: async_sessionmaker[AsyncSession], tenant_id: str, user_id: str+) -> dict[str, str]:+ """One of each encrypted column, the config under the old key and the two+ strings under the legacy secret. Returns their ids."""+ async with tenant_session(restricted, tenant_id) as session:+ client = Client(+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:switch.local",+ display_name="bridge client",+ type="bridge",+ )+ session.add(client)+ await session.flush()+ bridge = CollaborationBridge(+ type="slack",+ display_name="Slack",+ client_id=client.id,+ status="active",+ connection_config={"bot_token": f"xoxb-{tenant_id}"},+ )+ key = ApiKey(+ user_id=user_id,+ key_hash=uuid.uuid4().hex,+ encrypted_key=_legacy_encrypt(f"api-key-{tenant_id}"),+ label="test",+ type="user",+ )+ install = MessagingInstall(+ platform="slack",+ external_workspace_id=f"T-{tenant_id}",+ encrypted_bot_token=_legacy_encrypt(f"install-{tenant_id}"),+ scopes="chat:write",+ status="active",+ installed_by_user_id=user_id,+ )+ session.add_all([bridge, key, install])+ await session.commit()+ return {"bridge": bridge.id, "key": key.id, "install": install.id}+++async def _raw(+ owner: async_sessionmaker[AsyncSession], table: str, column: str, row_id: str+) -> object:+ async with owner() as session:+ result = await session.execute(+ text(f"SELECT {column} FROM {table} WHERE id = :id"), {"id": row_id}+ )+ return result.scalar_one()+++async def test_every_tenants_secrets_end_up_under_the_current_key(+ rls_harness: RLSHarness, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(encrypted_json, "_keyring", _OLD)+ seeded = {}+ for _ in range(2):+ tenant_id, user_id = await _tenant_with_user(rls_harness.owner)+ seeded[tenant_id] = await _seed(rls_harness.restricted, tenant_id, user_id)++ monkeypatch.setattr(encrypted_json, "_keyring", _NEW)+ await reencrypt_stored_secrets(rls_harness.restricted, _NEW, list(seeded))++ current = _NEW.current_prefix()+ for tenant_id, ids in seeded.items():+ config = await _raw(+ rls_harness.owner,+ "collaboration_bridges",+ "connection_config",+ ids["bridge"],+ )+ assert isinstance(config, dict) and config["_enc"].startswith(current)+ assert _NEW.decrypt(config["_enc"]) == f'{{"bot_token": "xoxb-{tenant_id}"}}'++ key = await _raw(rls_harness.owner, "api_keys", "encrypted_key", ids["key"])+ assert isinstance(key, str) and key.startswith(current)+ assert _NEW.decrypt(key) == f"api-key-{tenant_id}"++ token = await _raw(+ rls_harness.owner,+ "messaging_installs",+ "encrypted_bot_token",+ ids["install"],+ )+ assert isinstance(token, str) and token.startswith(current)+ assert _NEW.decrypt(token) == f"install-{tenant_id}"++ # Once done, nothing needs the old key or the legacy secret any more.+ without_old = Keyring.parse("new:" + "n" * 40, legacy_secret=None)+ for ids in seeded.values():+ key = await _raw(rls_harness.owner, "api_keys", "encrypted_key", ids["key"])+ assert isinstance(key, str)+ without_old.decrypt(key)+++async def test_a_value_no_key_opens_stops_the_boot(+ rls_harness: RLSHarness, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A key removed before its values were re-encrypted. Carrying on would+ leave a credential nothing can read while reporting the rotation done."""+ monkeypatch.setattr(encrypted_json, "_keyring", _OLD)+ tenant_id, user_id = await _tenant_with_user(rls_harness.owner)+ await _seed(rls_harness.restricted, tenant_id, user_id)++ too_early = Keyring.parse("new:" + "n" * 40, legacy_secret=None)+ monkeypatch.setattr(encrypted_json, "_keyring", too_early)+ with pytest.raises(UndecryptableError):+ await reencrypt_stored_secrets(rls_harness.restricted, too_early, [tenant_id])diff --git a/core/tests/switch_core/db/test_schema_version.py b/core/tests/switch_core/db/test_schema_version.pynew file mode 100644index 000000000..db36bbd2b--- /dev/null+++ b/core/tests/switch_core/db/test_schema_version.py@@ -0,0 +1,85 @@+"""The check a server that does not migrate at boot runs instead.++Each test writes `alembic_version` by hand in a database of its own, so what is+under test is the comparison against this build's heads, not the migrations.+"""++from __future__ import annotations++from collections.abc import AsyncIterator+from pathlib import Path++import pytest+from alembic.config import Config as AlembicConfig+from alembic.script import ScriptDirectory+from sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine++from switch_core.db.schema_version import SchemaNotAtHeadError, require_schema_at_head++_ALEMBIC_INI = Path(__file__).resolve().parents[3] / "alembic.ini"+_SCRATCH_DB = "schema_version_check"++pytestmark = pytest.mark.no_ambient_tenant+++def alembic_cfg() -> AlembicConfig:+ return AlembicConfig(str(_ALEMBIC_INI))+++async def scratch_engine(postgres_url: str) -> AsyncIterator[AsyncEngine]:+ admin = create_async_engine(postgres_url, isolation_level="AUTOCOMMIT")+ async with admin.connect() as connection:+ await connection.execute(text(f'DROP DATABASE IF EXISTS "{_SCRATCH_DB}"'))+ await connection.execute(text(f'CREATE DATABASE "{_SCRATCH_DB}"'))+ base, _, _ = postgres_url.rpartition("/")+ engine = create_async_engine(f"{base}/{_SCRATCH_DB}")+ try:+ yield engine+ finally:+ await engine.dispose()+ async with admin.connect() as connection:+ await connection.execute(text(f'DROP DATABASE IF EXISTS "{_SCRATCH_DB}"'))+ await admin.dispose()+++async def _stamp(engine: AsyncEngine, *revisions: str) -> None:+ async with engine.begin() as connection:+ await connection.execute(+ text("CREATE TABLE alembic_version (version_num varchar(32) PRIMARY KEY)")+ )+ for revision in revisions:+ await connection.execute(+ text("INSERT INTO alembic_version VALUES (:r)"), {"r": revision}+ )+++async def test_a_database_at_head_is_accepted(+ scratch_engine: AsyncEngine, alembic_cfg: AlembicConfig+) -> None:+ await _stamp(scratch_engine, *ScriptDirectory.from_config(alembic_cfg).get_heads())++ await require_schema_at_head(scratch_engine, alembic_cfg)+++async def test_a_database_behind_head_is_refused(+ scratch_engine: AsyncEngine, alembic_cfg: AlembicConfig+) -> None:+ script = ScriptDirectory.from_config(alembic_cfg)+ (head,) = script.get_heads()+ parents = script.get_revision(head).down_revision+ assert parents is not None+ previous = parents if isinstance(parents, str) else parents[0]+ await _stamp(scratch_engine, previous)++ with pytest.raises(SchemaNotAtHeadError, match="DB_MIGRATE_ON_BOOT"):+ await require_schema_at_head(scratch_engine, alembic_cfg)+++async def test_a_database_never_migrated_is_refused(+ scratch_engine: AsyncEngine, alembic_cfg: AlembicConfig+) -> None:+ with pytest.raises(SchemaNotAtHeadError, match="none"):+ await require_schema_at_head(scratch_engine, alembic_cfg)diff --git a/core/tests/switch_core/db/test_tenant_id_indexes.py b/core/tests/switch_core/db/test_tenant_id_indexes.pynew file mode 100644index 000000000..9bf5aa878--- /dev/null+++ b/core/tests/switch_core/db/test_tenant_id_indexes.py@@ -0,0 +1,42 @@+"""Every tenant table has an index whose first column is `tenant_id`.++The row-level-security policy filters every table on `tenant_id`, queries+across one tenant's rows ask by it, and deleting a tenant checks each table's+foreign key to it. Without an index leading with that column each of those is+a scan of the whole table, every tenant's rows included. A partial index does+not count: it serves only the rows its predicate admits.+"""++from __future__ import annotations++from sqlalchemy import PrimaryKeyConstraint, Table, UniqueConstraint++import switch_core.db.models # noqa: F401 — registers every table on Base.metadata+from switch_core.db.base import Base+++def _leads_with_tenant_id(table: Table) -> bool:+ for index in table.indexes:+ columns = list(index.columns)+ if (+ columns+ and columns[0].name == "tenant_id"+ and index.dialect_options["postgresql"].get("where") is None+ ):+ return True+ for constraint in table.constraints:+ if isinstance(constraint, UniqueConstraint | PrimaryKeyConstraint):+ columns = list(constraint.columns)+ if columns and columns[0].name == "tenant_id":+ return True+ return False+++def test_every_tenant_table_has_an_index_leading_with_tenant_id() -> None:+ missing = sorted(+ table.name+ for table in Base.metadata.tables.values()+ if "tenant_id" in table.c and not _leads_with_tenant_id(table)+ )++ assert missing == []diff --git a/core/tests/switch_core/db/test_tenant_lookup.py b/core/tests/switch_core/db/test_tenant_lookup.pyindex f10b2710e..f1e180d7b 100644--- a/core/tests/switch_core/db/test_tenant_lookup.py+++ b/core/tests/switch_core/db/test_tenant_lookup.py@@ -43,7 +43,7 @@ import pytestfrom alembic.config import Configfrom alembic.script import ScriptDirectoryfrom sqlalchemy import text-from sqlalchemy.exc import DBAPIError+from sqlalchemy.exc import DBAPIError, IntegrityErrorimport switch_corefrom switch_core.db.models import (@@ -64,7 +64,6 @@ from switch_core.db.tenant_lookup import (SECURE_SEARCH_PATH,TENANT_LOOKUPS,TENANT_LOOKUPS_BY_NAME,- TenantLookupError,all_tenant_ids,create_lookup_ddl,tenant_of_agent_oauth_client,@@ -271,10 +270,9 @@ async def _two_populated_tenants(harness: RLSHarness) -> _Fixture:agent_type="always_on",integration_profile={"connection_model": "always_on"},connector_type="test",- # Both tenants carry the same value on a column with no- # unique index: the one lookup that can legitimately- # answer twice, and the case it has to refuse.- oauth_client_id=fixture.oauth_client_a,+ oauth_client_id=(+ fixture.oauth_client_a if tag == "a" else f"oauth-b-{suffix}"+ ),))await session.flush()@@ -617,20 +615,34 @@ class TestWhatTheyAnswer:is None)- async def test_an_ambiguous_answer_is_refused_rather_than_picked(+ async def test_an_oauth_client_resolves_to_the_one_tenant_holding_it(self, rls_harness: RLSHarness) -> None:- """`agents.oauth_client_id` carries no unique index, so two tenants- can register an agent under the same one. Resolving that to a tenant- by taking the first row would authenticate a caller into somebody- else's data on the strength of a duplicate — a provisioning fault- turned into an authorization one — so it raises."""fixture = await _two_populated_tenants(rls_harness)- with pytest.raises(TenantLookupError) as raised:+ assert (await tenant_of_agent_oauth_client(rls_harness.restricted, fixture.oauth_client_a)- assert "refusing to pick one" in str(raised.value)+ == fixture.tenant_a+ )++ async def test_a_second_tenant_cannot_take_an_oauth_client_id(+ self, rls_harness: RLSHarness+ ) -> None:+ """The client id is how an OIDC sign-in finds its agent before any+ tenant is known, so it must name one agent deployment-wide. Were a+ second tenant able to register it, the lookup would have to refuse+ both — the first tenant's agents locked out by someone else's row."""+ fixture = await _two_populated_tenants(rls_harness)+ async with rls_harness.owner() as session:+ with pytest.raises(IntegrityError, match="uq_agents_oauth_client_id"):+ await session.execute(+ text(+ "UPDATE agents SET oauth_client_id = :oauth "+ "WHERE tenant_id = :tenant"+ ),+ {"oauth": fixture.oauth_client_a, "tenant": fixture.tenant_b},+ )class TestWhatTheExemptionDiscloses:diff --git a/core/tests/switch_core/gateway/test_audit_events.py b/core/tests/switch_core/gateway/test_audit_events.pynew file mode 100644index 000000000..57e4ef2d5--- /dev/null+++ b/core/tests/switch_core/gateway/test_audit_events.py@@ -0,0 +1,286 @@+"""The workspace audit log: which gateway actions leave an `audit_events` row,+who can read the log back, and that the runtime role cannot rewrite it."""++from __future__ import annotations++import pytest+from sqlalchemy import select, text+from sqlalchemy.exc import ProgrammingError+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.audit import AuditAction, record_audit_event+from switch_core.db.models import AuditEvent+from switch_core.db.session_scope import tenant_session+from switch_core.gateway import api_keys+from tests.conftest import RLSHarness+from tests.switch_core.gateway.test_tenant_api_routes import (+ TENANT_A,+ TENANT_B,+ _app,+ _client,+ _fake_protocol,+ _make_member,+ _make_tenant,+ _token,+)+++async def _events(+ session_factory: async_sessionmaker[AsyncSession], tenant_id: str+) -> list[AuditEvent]:+ async with session_factory() as session:+ result = await session.execute(+ select(AuditEvent)+ .where(AuditEvent.tenant_id == tenant_id)+ .order_by(AuditEvent.occurred_at)+ )+ return list(result.scalars().all())+++async def _owner(+ session_factory: async_sessionmaker[AsyncSession], tenant_id: str, name: str+) -> tuple[str, str]:+ await _make_tenant(session_factory, tenant_id)+ owner_id = await _make_member(+ session_factory, name=name, tenant_id=tenant_id, role="owner"+ )+ return owner_id, _token(owner_id, f"{name}@example.invalid", tenant_id)+++class TestMembershipEvents:+ async def test_a_role_change_is_recorded_with_both_roles(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ owner_id, token = await _owner(session_factory, TENANT_A, "audit-owner")+ member_id = await _make_member(+ session_factory, name="audit-member", tenant_id=TENANT_A, role="member"+ )++ async with _client(_app(session_factory), token) as client:+ response = await client.patch(+ f"/tenants/{TENANT_A}/members/{member_id}", json={"role": "admin"}+ )+ assert response.status_code == 200, response.text++ [event] = await _events(session_factory, TENANT_A)+ assert event.action == AuditAction.MEMBER_ROLE_CHANGED+ assert event.actor_user_id == owner_id+ assert event.target_type == "user"+ assert event.target_id == member_id+ assert event.details == {"from": "member", "to": "admin"}++ async def test_setting_the_same_role_records_nothing(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _, token = await _owner(session_factory, TENANT_A, "audit-owner")+ member_id = await _make_member(+ session_factory, name="audit-member", tenant_id=TENANT_A, role="member"+ )++ async with _client(_app(session_factory), token) as client:+ response = await client.patch(+ f"/tenants/{TENANT_A}/members/{member_id}", json={"role": "member"}+ )+ assert response.status_code == 200, response.text++ assert await _events(session_factory, TENANT_A) == []++ async def test_removing_a_member_is_recorded(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ owner_id, token = await _owner(session_factory, TENANT_A, "audit-owner")+ member_id = await _make_member(+ session_factory, name="audit-member", tenant_id=TENANT_A, role="member"+ )++ async with _client(_app(session_factory), token) as client:+ response = await client.delete(f"/tenants/{TENANT_A}/members/{member_id}")+ assert response.status_code in (200, 204), response.text++ [event] = await _events(session_factory, TENANT_A)+ assert event.action == AuditAction.MEMBER_REMOVED+ assert event.actor_user_id == owner_id+ assert event.target_id == member_id+ assert event.details is not None+ assert event.details["role"] == "member"++ async def test_a_refused_change_records_nothing(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ owner_id, token = await _owner(session_factory, TENANT_A, "sole-owner")++ async with _client(_app(session_factory), token) as client:+ response = await client.patch(+ f"/tenants/{TENANT_A}/members/{owner_id}", json={"role": "member"}+ )+ assert response.status_code == 409++ assert await _events(session_factory, TENANT_A) == []+++class TestInvitationEvents:+ async def test_creating_and_revoking_an_invitation_are_both_recorded(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ owner_id, token = await _owner(session_factory, TENANT_A, "audit-owner")++ async with _client(_app(session_factory), token) as client:+ created = await client.post(+ f"/tenants/{TENANT_A}/invitations", json={"role": "member"}+ )+ assert created.status_code == 201, created.text+ invitation_id = created.json()["id"]+ revoked = await client.delete(+ f"/tenants/{TENANT_A}/invitations/{invitation_id}"+ )+ assert revoked.status_code == 200, revoked.text++ events = await _events(session_factory, TENANT_A)+ assert [e.action for e in events] == [+ AuditAction.INVITATION_CREATED,+ AuditAction.INVITATION_REVOKED,+ ]+ assert {e.target_id for e in events} == {invitation_id}+ assert {e.actor_user_id for e in events} == {owner_id}+ assert events[0].details is not None+ assert events[0].details["role"] == "member"+++class TestApiKeyEvents:+ async def test_create_reveal_and_delete_are_recorded_without_the_key(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ monkeypatch.setattr(api_keys, "get_protocol", _fake_protocol)+ user_id, token = await _owner(session_factory, TENANT_A, "key-owner")+ app = _app(session_factory)+ app.include_router(api_keys.router, prefix="/api-keys")++ async with _client(app, token) as client:+ created = await client.post("/api-keys", json={"label": "laptop"})+ assert created.status_code == 200, created.text+ key_id = created.json()["id"]+ plaintext = created.json()["key"]+ revealed = await client.get(f"/api-keys/{key_id}/reveal")+ assert revealed.status_code == 200, revealed.text+ deleted = await client.delete(f"/api-keys/{key_id}")+ assert deleted.status_code == 200, deleted.text++ events = await _events(session_factory, TENANT_A)+ assert [e.action for e in events] == [+ AuditAction.API_KEY_CREATED,+ AuditAction.API_KEY_REVEALED,+ AuditAction.API_KEY_DELETED,+ ]+ assert {e.target_id for e in events} == {key_id}+ assert {e.actor_user_id for e in events} == {user_id}+ for event in events:+ assert plaintext not in str(event.details)+++class TestReadingTheLog:+ async def test_admins_read_their_own_tenant_newest_first(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ owner_id, token = await _owner(session_factory, TENANT_A, "audit-owner")+ await _make_tenant(session_factory, TENANT_B)+ for tenant_id, action in (+ (TENANT_A, AuditAction.JOIN_DOMAIN_ADDED),+ (TENANT_B, AuditAction.TENANT_CREATED),+ (TENANT_A, AuditAction.JOIN_DOMAIN_REMOVED),+ ):+ async with tenant_session(session_factory, tenant_id) as session:+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=owner_id,+ action=action,+ target_type="join_domain",+ target_id="example.invalid",+ details=None,+ )+ await session.commit()++ async with _client(_app(session_factory), token) as client:+ response = await client.get(f"/tenants/{TENANT_A}/audit-events")+ assert response.status_code == 200, response.text+ rows = response.json()+ assert [r["action"] for r in rows] == [+ AuditAction.JOIN_DOMAIN_REMOVED,+ AuditAction.JOIN_DOMAIN_ADDED,+ ]++ older = await client.get(+ f"/tenants/{TENANT_A}/audit-events",+ params={"before": rows[0]["occurred_at"]},+ )+ assert older.status_code == 200, older.text+ assert [r["action"] for r in older.json()] == [+ AuditAction.JOIN_DOMAIN_ADDED+ ]++ other_tenant = await client.get(f"/tenants/{TENANT_B}/audit-events")+ assert other_tenant.status_code in (403, 404)++ async def test_a_plain_member_cannot_read_the_log(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ member_id = await _make_member(+ session_factory, name="audit-member", tenant_id=TENANT_A, role="member"+ )+ token = _token(member_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.get(f"/tenants/{TENANT_A}/audit-events")++ assert response.status_code == 403++[email protected]_ambient_tenant+class TestAppendOnly:+ async def _seed(self, rls_harness: RLSHarness) -> None:+ await _make_tenant(rls_harness.owner, TENANT_A)+ await _make_tenant(rls_harness.owner, TENANT_B)+ async with tenant_session(rls_harness.restricted, TENANT_A) as session:+ await record_audit_event(+ session,+ tenant_id=TENANT_A,+ actor_user_id=None,+ action=AuditAction.TENANT_CREATED,+ target_type="tenant",+ target_id=TENANT_A,+ details=None,+ )+ await session.commit()++ async def test_the_runtime_role_can_insert_and_read_its_own_tenant(+ self, rls_harness: RLSHarness+ ) -> None:+ await self._seed(rls_harness)++ async with tenant_session(rls_harness.restricted, TENANT_A) as session:+ mine = (await session.execute(select(AuditEvent))).scalars().all()+ async with tenant_session(rls_harness.restricted, TENANT_B) as session:+ theirs = (await session.execute(select(AuditEvent))).scalars().all()++ assert [e.action for e in mine] == [AuditAction.TENANT_CREATED]+ assert theirs == []++ @pytest.mark.parametrize(+ "statement",+ ["UPDATE audit_events SET action = 'rewritten'", "DELETE FROM audit_events"],+ )+ async def test_the_runtime_role_cannot_rewrite_history(+ self, rls_harness: RLSHarness, statement: str+ ) -> None:+ await self._seed(rls_harness)++ async with tenant_session(rls_harness.restricted, TENANT_A) as session:+ with pytest.raises(ProgrammingError, match="permission denied"):+ await session.execute(text(statement))++ async with rls_harness.owner() as session:+ [event] = (await session.execute(select(AuditEvent))).scalars().all()+ assert event.action == AuditAction.TENANT_CREATEDdiff --git a/core/tests/switch_core/gateway/test_auth_refresh.py b/core/tests/switch_core/gateway/test_auth_refresh.pyindex 7aa49f282..c3eb24cf8 100644--- a/core/tests/switch_core/gateway/test_auth_refresh.py+++ b/core/tests/switch_core/gateway/test_auth_refresh.py@@ -17,14 +17,16 @@ from fastapi import Responsefrom switch_core.db.models import Userfrom switch_core.gateway.auth import decode_jwtfrom switch_core.gateway.auth_routes import refresh+from switch_core.keys import Keyring# Dummy HS256 signing key for these unit tests only — not a real secret._SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow+_KEYRING = Keyring.parse("test:" + _SECRET, legacy_secret=None)def _config(*, cookie_secure: bool = False) -> SimpleNamespace:# refresh() only touches these two config attributes.- return SimpleNamespace(jwt_secret_key=_SECRET, gateway_cookie_secure=cookie_secure)+ return SimpleNamespace(keyring=_KEYRING, gateway_cookie_secure=cookie_secure)def _request(*, tenant_id: str | None) -> SimpleNamespace:@@ -50,7 +52,7 @@ async def test_refresh_remints_cookie_for_current_user() -> None:result = await refresh(_request(tenant_id="tenant-0"), response, user, _config())token = _extract_cookie(response)- payload = decode_jwt(token, _SECRET)+ payload = decode_jwt(token, _KEYRING)assert payload["sub"] == "u-1"assert payload["email"] == "[email protected]"assert payload["role"] == "user"@@ -70,7 +72,7 @@ async def test_refresh_carries_the_selected_tenant_forward() -> None:await refresh(_request(tenant_id="tenant-b"), response, user, _config())token = _extract_cookie(response)- payload = decode_jwt(token, _SECRET)+ payload = decode_jwt(token, _KEYRING)assert payload["tenant_id"] == "tenant-b"diff --git a/core/tests/switch_core/gateway/test_change_password.py b/core/tests/switch_core/gateway/test_change_password.pyindex 20382418d..4c91aac29 100644--- a/core/tests/switch_core/gateway/test_change_password.py+++ b/core/tests/switch_core/gateway/test_change_password.py@@ -29,8 +29,10 @@ from switch_core.gateway import dependencies as gw_depsfrom switch_core.gateway.auth import create_jwt, hash_password, verify_passwordfrom switch_core.gateway.auth_routes import routerfrom switch_core.gateway.schemas import ChangePasswordRequest+from switch_core.keys import Keyring_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow+_KEYRING = Keyring.parse("test:" + _SECRET, legacy_secret=None)_OLD_PASSWORD = "old-password-1"_NEW_PASSWORD = "new-password-1"@@ -57,7 +59,7 @@ def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factoryapp.dependency_overrides[gw_deps.get_user_store] = lambda: _USER_STOREapp.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(- jwt_secret_key=_SECRET,+ keyring=_KEYRING,gateway_cookie_secure=False,gateway_password_login_enabled=True,gateway_tenant_choice_enabled=False,@@ -95,7 +97,7 @@ async def _stored_hash(def _client(app: FastAPI, user_id: str, email: str) -> httpx.AsyncClient:- token = create_jwt(user_id, email, "user", _SECRET, None)+ token = create_jwt(user_id, email, "user", _KEYRING, None)return httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url="http://test",diff --git a/core/tests/switch_core/gateway/test_claim_identity_membership.py b/core/tests/switch_core/gateway/test_claim_identity_membership.pynew file mode 100644index 000000000..9f240c1cf--- /dev/null+++ b/core/tests/switch_core/gateway/test_claim_identity_membership.py@@ -0,0 +1,147 @@+"""An admin can link a messaging identity only to a member of their own tenant.++`users` is deployment-wide, so a user id that exists is not necessarily one+this tenant has any business recognising. The claim decides who an account is+treated as inside the tenant — owner-only addressing reads it — so the target+must be a member, and a non-member gets the same 404 as an id that does not+exist.+"""++from __future__ import annotations++import uuid++import pytest+from fastapi import HTTPException+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import (+ TENANT_ZERO_ID,+ Client,+ CollaborationBridge,+ ExternalUser,+ Tenant,+ TenantMember,+ User,+)+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore+from switch_core.db.stores.external_user_store import ExternalUserStore+from switch_core.db.stores.user_store import UserStore+from switch_core.gateway.collaborations import claim_bridge_identity+from switch_core.gateway.schemas import ClaimIdentityRequest++_EXTERNAL_USERS = ExternalUserStore()+++async def _make_client(session: AsyncSession, client_type: str) -> str:+ client = Client(+ transport_user_id=f"@{client_type}-{uuid.uuid4().hex[:8]}:test",+ display_name=client_type,+ type=client_type,+ )+ session.add(client)+ await session.flush()+ return client.id+++async def _make_user(session: AsyncSession, *, tenant_id: str, role: str) -> User:+ name = f"user-{uuid.uuid4().hex[:8]}"+ user = User(name=name, email=f"{name}@test", role="user", password_hash="x")+ session.add(user)+ await session.flush()+ session.add(TenantMember(tenant_id=tenant_id, user_id=user.id, role=role))+ await session.flush()+ return user+++async def _setup(+ session_factory: async_sessionmaker[AsyncSession],+) -> tuple[str, ExternalUser, User, User, User]:+ other_tenant = f"tenant-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ session.add(Tenant(id=other_tenant, slug=other_tenant, name=other_tenant))+ await session.flush()+ bridge = CollaborationBridge(+ type="mattermost",+ display_name="MM",+ client_id=await _make_client(session, "bridge"),+ status="active",+ )+ session.add(bridge)+ await session.flush()+ external_user = ExternalUser(+ bridge_id=bridge.id,+ external_user_id=f"U{uuid.uuid4().hex[:8]}",+ external_username="alice",+ client_id=await _make_client(session, "external_user"),+ )+ session.add(external_user)+ admin = await _make_user(session, tenant_id=TENANT_ZERO_ID, role="admin")+ member = await _make_user(session, tenant_id=TENANT_ZERO_ID, role="member")+ outsider = await _make_user(session, tenant_id=other_tenant, role="owner")+ await session.commit()+ return bridge.id, external_user, admin, member, outsider+++async def _claim(+ session_factory: async_sessionmaker[AsyncSession],+ *,+ bridge_id: str,+ external_user: ExternalUser,+ caller: User,+ target_user_id: str,+) -> object:+ async with session_factory() as session:+ return await claim_bridge_identity(+ bridge_id,+ ClaimIdentityRequest(+ external_user_id=external_user.external_user_id,+ username=external_user.external_username,+ user_id=target_user_id,+ ),+ session,+ CollaborationBridgeStore(),+ _EXTERNAL_USERS,+ UserStore(),+ None, # type: ignore[arg-type]+ caller,+ True,+ )+++async def test_admin_cannot_claim_an_identity_for_another_tenants_user(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ bridge_id, external_user, admin, _member, outsider = await _setup(session_factory)++ with pytest.raises(HTTPException) as refused:+ await _claim(+ session_factory,+ bridge_id=bridge_id,+ external_user=external_user,+ caller=admin,+ target_user_id=outsider.id,+ )++ assert refused.value.status_code == 404+ async with session_factory() as session:+ assert await _EXTERNAL_USERS.claimant_ids(session, external_user.id) == []+++async def test_admin_can_claim_an_identity_for_a_member(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ bridge_id, external_user, admin, member, _outsider = await _setup(session_factory)++ await _claim(+ session_factory,+ bridge_id=bridge_id,+ external_user=external_user,+ caller=admin,+ target_user_id=member.id,+ )++ async with session_factory() as session:+ assert await _EXTERNAL_USERS.claimant_ids(session, external_user.id) == [+ member.id+ ]diff --git a/core/tests/switch_core/gateway/test_messaging_installs_authz.py b/core/tests/switch_core/gateway/test_messaging_installs_authz.pyindex a3261181c..c700b3cc0 100644--- a/core/tests/switch_core/gateway/test_messaging_installs_authz.py+++ b/core/tests/switch_core/gateway/test_messaging_installs_authz.py@@ -20,8 +20,10 @@ from switch_core.db.stores.user_store import UserStorefrom switch_core.gateway import dependencies as gw_depsfrom switch_core.gateway.auth import create_jwt, require_admin, require_tenant_adminfrom switch_core.gateway.messaging_installs import router+from switch_core.keys import Keyring_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow+_KEYRING = Keyring.parse("test:" + _SECRET, legacy_secret=None)_TENANT = "messaging-installs-authz"@@ -54,7 +56,7 @@ def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()app.dependency_overrides[gw_deps.get_install_service] = lambda: Noneapp.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(- jwt_secret_key=_SECRET, gateway_tenant_choice_enabled=False+ keyring=_KEYRING, gateway_tenant_choice_enabled=False)return app@@ -77,7 +79,7 @@ async def _member(async def _list_installs(session_factory: async_sessionmaker[AsyncSession], user_id: str, name: str) -> httpx.Response:- token = create_jwt(user_id, f"{name}@example.invalid", "user", _SECRET, _TENANT)+ token = create_jwt(user_id, f"{name}@example.invalid", "user", _KEYRING, _TENANT)async with httpx.AsyncClient(transport=httpx.ASGITransport(app=_app(session_factory)),base_url="http://test",diff --git a/core/tests/switch_core/gateway/test_oidc_config.py b/core/tests/switch_core/gateway/test_oidc_config.pyindex eee345aed..cb8b743c0 100644--- a/core/tests/switch_core/gateway/test_oidc_config.py+++ b/core/tests/switch_core/gateway/test_oidc_config.py@@ -21,7 +21,7 @@ def _kwargs(**overrides: object) -> dict[str, object]:db_name="d",id_server_name="m",agent_registration_token="t",- jwt_secret_key="secret",+ secret_keys="test:" + "x" * 40,gateway_admin_email="[email protected]",gateway_admin_password="pw",gateway_oidc_issuer_url=None,diff --git a/core/tests/switch_core/gateway/test_oidc_routes.py b/core/tests/switch_core/gateway/test_oidc_routes.pyindex 1c8d1e1e9..ccf57b834 100644--- a/core/tests/switch_core/gateway/test_oidc_routes.py+++ b/core/tests/switch_core/gateway/test_oidc_routes.py@@ -25,7 +25,7 @@ from switch_core.gateway.auth_routes import auth_configdef _tenant_claim(set_cookie: str) -> str | None:token = set_cookie.split("switch_auth=", 1)[1].split(";", 1)[0]- claim: str | None = decode_jwt(token, "secret").get("tenant_id")+ claim: str | None = decode_jwt(token, _config().keyring).get("tenant_id")return claim@@ -38,7 +38,7 @@ def _config(**overrides: object) -> SwitchConfig:db_name="d",id_server_name="m",agent_registration_token="t",- jwt_secret_key="secret",+ secret_keys="test:" + "x" * 40,gateway_admin_email="[email protected]",gateway_admin_password="pw",gateway_oidc_issuer_url="https://idp.example",diff --git a/core/tests/switch_core/gateway/test_session_keys.py b/core/tests/switch_core/gateway/test_session_keys.pynew file mode 100644index 000000000..70dd2f925--- /dev/null+++ b/core/tests/switch_core/gateway/test_session_keys.py@@ -0,0 +1,82 @@+"""Session tokens across key changes: signed with the current key and named by+`kid`, still valid after a rotation while the old key is kept, and sessions+from before `SECRET_KEYS` valid only while `JWT_SECRET_KEY` is set."""++from __future__ import annotations++import datetime++import jwt+import pytest+from fastapi import HTTPException++from switch_core.gateway.auth import JWT_ALGORITHM, create_jwt, decode_jwt+from switch_core.keys import Keyring, Purpose++_OLD = "o" * 40+_NEW = "n" * 40+_LEGACY = "legacy-jwt-secret"+++def _keyring(value: str, legacy: str | None = None) -> Keyring:+ return Keyring.parse(value, legacy_secret=legacy)+++def _session(keyring: Keyring) -> str:+ return create_jwt("user-1", "[email protected]", "user", keyring, "tenant-1")+++def _legacy_session() -> str:+ """A session as signed before `SECRET_KEYS`: the raw secret, no `kid`."""+ payload = {+ "sub": "user-1",+ "exp": datetime.datetime.now(datetime.UTC) + datetime.timedelta(hours=1),+ }+ return jwt.encode(payload, _LEGACY, algorithm=JWT_ALGORITHM)+++def test_a_session_names_its_key_and_is_not_signed_with_the_master_key() -> None:+ keyring = _keyring(f"k1:{_OLD}")+ token = _session(keyring)+ assert jwt.get_unverified_header(token)["kid"] == "k1"+ with pytest.raises(jwt.InvalidSignatureError):+ jwt.decode(token, _OLD, algorithms=[JWT_ALGORITHM])+ jwt.decode(token, keyring.derive(Purpose.SESSION), algorithms=[JWT_ALGORITHM])+++def test_a_session_survives_a_rotation_while_its_key_is_kept() -> None:+ token = _session(_keyring(f"old:{_OLD}"))+ assert decode_jwt(token, _keyring(f"new:{_NEW},old:{_OLD}"))["sub"] == "user-1"+++def test_and_ends_when_its_key_is_removed() -> None:+ token = _session(_keyring(f"old:{_OLD}"))+ with pytest.raises(HTTPException) as refused:+ decode_jwt(token, _keyring(f"new:{_NEW}"))+ assert refused.value.status_code == 401+++def test_a_forged_kid_does_not_pick_another_purposes_key() -> None:+ """A token signed with some other derived key, claiming a real `kid`."""+ keyring = _keyring(f"k1:{_OLD}")+ forged = jwt.encode(+ {"sub": "user-1"},+ keyring.derive(Purpose.INSTALL_STATE),+ algorithm=JWT_ALGORITHM,+ headers={"kid": "k1"},+ )+ with pytest.raises(HTTPException):+ decode_jwt(forged, keyring)+++def test_a_session_from_before_secret_keys_is_valid_while_the_legacy_secret_is_set() -> (+ None+):+ keyring = _keyring(f"k1:{_NEW}", legacy=_LEGACY)+ assert decode_jwt(_legacy_session(), keyring)["sub"] == "user-1"+++def test_and_ends_once_it_is_removed() -> None:+ with pytest.raises(HTTPException) as refused:+ decode_jwt(_legacy_session(), _keyring(f"k1:{_NEW}"))+ assert refused.value.status_code == 401diff --git a/core/tests/switch_core/gateway/test_shared_bridge_registration.py b/core/tests/switch_core/gateway/test_shared_bridge_registration.pyindex ddac276d2..82b2453a1 100644--- a/core/tests/switch_core/gateway/test_shared_bridge_registration.py+++ b/core/tests/switch_core/gateway/test_shared_bridge_registration.py@@ -16,6 +16,7 @@ import pytestfrom fastapi import HTTPExceptionfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core.bridges.collaboration.lifecycle_service import BridgeClaimConflictfrom switch_core.bridges.collaboration.models import BridgeStartRefusedfrom switch_core.db.models import Client, CollaborationBridge, Userfrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore@@ -29,17 +30,18 @@ _BRIDGE_STORE = CollaborationBridgeStore()class _Lifecycle:"""Records what reached it; refuses any start when told to."""- def __init__(self, *, refuse: bool = False) -> None:+ def __init__(self, *, refuse: bool = False, claimed: bool = False) -> None:self.refuse = refuse+ self.claimed = claimedself.registered: list[dict[str, object]] = []self.checked: list[dict[str, Any]] = []async def register(self, **kwargs: object) -> None:self.registered.append(kwargs)- def validate_connection_config(- self, bridge_type: str, connection_config: dict[str, object]- ) -> None: ...+ async def check_edited_connection_config(self, **kwargs: Any) -> None:+ if self.claimed:+ raise BridgeClaimConflict("Discord server 999 is already claimed")def supports_channel_creation(self, bridge_type: str) -> bool:return False@@ -89,7 +91,7 @@ async def _update(bridge_store=_BRIDGE_STORE,room_store=RoomStore(),collab_lifecycle=lifecycle, # type: ignore[arg-type]- _user=_admin(),+ user=_admin(),)return refused.value@@ -116,7 +118,7 @@ async def test_a_shared_bridge_cannot_be_registered_by_hand() -> None:session=None, # type: ignore[arg-type]bridge_store=_BRIDGE_STORE,collab_lifecycle=lifecycle, # type: ignore[arg-type]- _user=_admin(),+ user=_admin(),)assert refused.value.status_code == 422@@ -158,3 +160,18 @@ async def test_how_a_bridge_receives_events_cannot_be_changed(assert (await _stored_config(session_factory, bridge_id))["event_delivery"] == "shared"+++async def test_an_edit_cannot_claim_a_workspace_another_bridge_holds(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ bridge_id = await _shared_bridge(session)+ await session.commit()+ lifecycle = _Lifecycle(claimed=True)++ refused = await _update(session_factory, bridge_id, lifecycle, {"guild_id": "999"})++ assert refused.status_code == 400+ assert "already claimed" in str(refused.detail)+ assert (await _stored_config(session_factory, bridge_id))["guild_id"] == "111"diff --git a/core/tests/switch_core/gateway/test_template_http.py b/core/tests/switch_core/gateway/test_template_http.pyindex be779fc80..415ce0858 100644--- a/core/tests/switch_core/gateway/test_template_http.py+++ b/core/tests/switch_core/gateway/test_template_http.py@@ -54,7 +54,7 @@ def _config() -> SwitchConfig:db_name="d",id_server_name="test",agent_registration_token="t",- jwt_secret_key="s",+ secret_keys="test:" + "x" * 40,gateway_admin_email="admin@test",gateway_admin_password="pw",)diff --git a/core/tests/switch_core/gateway/test_template_routes.py b/core/tests/switch_core/gateway/test_template_routes.pyindex cdad2c8b6..9108d1b3a 100644--- a/core/tests/switch_core/gateway/test_template_routes.py+++ b/core/tests/switch_core/gateway/test_template_routes.py@@ -59,7 +59,7 @@ def _config(**overrides: object) -> SwitchConfig:"db_name": "d","matrix_server_name": "test","agent_registration_token": "t",- "jwt_secret_key": "s",+ "secret_keys": "test:" + "x" * 40,"gateway_admin_email": "admin@test","gateway_admin_password": "pw",}diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.pyindex ae4da26df..102d4be36 100644--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py@@ -20,6 +20,7 @@ import asyncioimport uuidfrom datetime import UTC, datetime, timedeltafrom types import SimpleNamespace+from unittest.mock import MagicMockimport httpximport pytest@@ -28,6 +29,7 @@ from sqlalchemy import selectfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.db.models import (Agent,ApiKey,@@ -55,8 +57,10 @@ from switch_core.gateway.invite_mail import (InviteMailer,)from switch_core.gateway.tenants import router as tenants_router+from switch_core.keys import Keyring_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow+_KEYRING = Keyring.parse("test:" + _SECRET, legacy_secret=None)TENANT_A = "tenant-api-routes-a"TENANT_B = "tenant-api-routes-b"@@ -140,7 +144,7 @@ def _app(client_lifecycle or _FakeClientLifecycle(session_factory))app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(- jwt_secret_key=_SECRET,+ keyring=_KEYRING,gateway_cookie_secure=False,gateway_tenant_choice_enabled=False,gateway_max_workspaces_per_user=max_workspaces_per_user,@@ -192,13 +196,13 @@ async def _make_member(def _token(user_id: str, email: str, tenant_id: str | None) -> str:- return create_jwt(user_id, email, "user", _SECRET, tenant_id)+ return create_jwt(user_id, email, "user", _KEYRING, tenant_id)def _tenant_claim(response: httpx.Response) -> str | None:token = response.cookies.get("switch_auth")assert token is not None, "no session cookie was minted"- claim: str | None = decode_jwt(token, _SECRET).get("tenant_id")+ claim: str | None = decode_jwt(token, _KEYRING).get("tenant_id")return claim@@ -401,7 +405,7 @@ class TestCreateTenant:user_id = await _make_unaffiliated_user(session_factory, name="operator", role="admin")- token = create_jwt(user_id, "[email protected]", "admin", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "admin", _KEYRING, None)app = _app(session_factory, signup_mode="invite_only")async with _client(app, token) as client:@@ -409,6 +413,37 @@ class TestCreateTenant:assert response.status_code == 201, response.text+ async def test_no_workspace_is_created_where_tenants_are_not_isolated(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """With DB_REQUIRE_RESTRICTED_ROLE off the server keeps to one+ workspace, operators included: a second would run unisolated, and the+ next boot would refuse to start."""+ user_id = await _make_unaffiliated_user(+ session_factory, name="operator", role="admin"+ )+ token = create_jwt(user_id, "[email protected]", "admin", _KEYRING, None)+ lifecycle = ClientLifecycleService(+ provisioning=MagicMock(),+ client_store=MagicMock(),+ tenant_store=TenantStore(),+ client_factory=MagicMock(),+ session_factory=session_factory,+ config=SimpleNamespace(id_server_name="test"), # type: ignore[arg-type]+ tenants_isolated=False,+ )++ app = _app(session_factory, client_lifecycle=lifecycle, signup_mode="open")+ async with _client(app, token) as client:+ response = await client.post("/tenants", json={"name": "Second Co"})++ assert response.status_code == 409, response.text+ assert "DB_REQUIRE_RESTRICTED_ROLE" in response.json()["detail"]+ async with session_factory() as session:+ assert (+ await session.execute(select(Tenant).where(Tenant.name == "Second Co"))+ ).first() is None+async def test_a_failure_other_than_a_taken_slug_is_not_retried(self, session_factory: async_sessionmaker[AsyncSession]) -> None:@@ -648,7 +683,7 @@ class TestWorkspaceCreationLimit:session_factory, name="demoted", tenant_id=TENANT_A, role="member")stale_operator_token = create_jwt(- user_id, "[email protected]", "admin", _SECRET, TENANT_A+ user_id, "[email protected]", "admin", _KEYRING, TENANT_A)async with _client(@@ -741,6 +776,27 @@ class TestInvitationAuthorisation:assert response.status_code == 422, response.text+ @pytest.mark.parametrize(("uses", "status"), [(100, 201), (101, 422)])+ async def test_a_link_cannot_be_made_effectively_unlimited(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ uses: int,+ status: int,+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="a-owner", tenant_id=TENANT_A, role="owner"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.post(+ f"/tenants/{TENANT_A}/invitations",+ json={"role": "member", "uses_remaining": uses},+ )++ assert response.status_code == status, response.text+class TestOwnershipIsOwnerOnly:"""Who owns a workspace is decided by its owners, not by its admins.diff --git a/core/tests/switch_core/gateway/test_tenant_resolution.py b/core/tests/switch_core/gateway/test_tenant_resolution.pyindex 8666dcc48..89f980b91 100644--- a/core/tests/switch_core/gateway/test_tenant_resolution.py+++ b/core/tests/switch_core/gateway/test_tenant_resolution.py@@ -66,9 +66,11 @@ from switch_core.gateway.auth_routes import loginfrom switch_core.gateway.auth_routes import router as auth_routerfrom switch_core.gateway.schemas import LoginRequestfrom switch_core.gateway.tenants import router as tenants_router+from switch_core.keys import Keyringfrom tests.conftest import empty_the_database_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow+_KEYRING = Keyring.parse("test:" + _SECRET, legacy_secret=None)TENANT_B = "tenant-resolution-b"NOT_A_MEMBER_TENANT = "tenant-resolution-not-a-member"@@ -89,7 +91,7 @@ def _app(app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factoryapp.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(- jwt_secret_key=_SECRET, gateway_tenant_choice_enabled=choice_enabled+ keyring=_KEYRING, gateway_tenant_choice_enabled=choice_enabled)@app.get("/whoami")@@ -126,7 +128,7 @@ def _tenants_app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:app.dependency_overrides[gw_deps.get_system_session] = _session_depapp.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(- jwt_secret_key=_SECRET,+ keyring=_KEYRING,gateway_cookie_secure=False,gateway_tenant_choice_enabled=False,)@@ -151,7 +153,7 @@ def _session_app(app.dependency_overrides[gw_deps.get_system_session] = _session_depapp.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(- jwt_secret_key=_SECRET,+ keyring=_KEYRING,gateway_signup_mode=signup_mode,gateway_max_workspaces_per_user=3,invite_email_enabled=invite_email_enabled,@@ -176,7 +178,7 @@ def _login_config() -> SimpleNamespace:# The three attributes `login` reads.return SimpleNamespace(gateway_password_login_enabled=True,- jwt_secret_key=_SECRET,+ keyring=_KEYRING,gateway_cookie_secure=False,)@@ -185,7 +187,7 @@ def _tenant_claim(response: Response | httpx.Response) -> str | None:raw = response.headers.get("set-cookie")assert raw is not None, "no session cookie was minted"token = raw.split("switch_auth=", 1)[1].split(";", 1)[0]- claim: str | None = decode_jwt(token, _SECRET).get("tenant_id")+ claim: str | None = decode_jwt(token, _KEYRING).get("tenant_id")return claim@@ -390,7 +392,7 @@ class TestSessionStateEndpoint:user_id = await _make_user_with_memberships(session_factory, name="ready", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _SECRET, TENANT_B)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, TENANT_B)response = await self._get(session_factory, token, signup_mode="default_tenant")@@ -411,7 +413,7 @@ class TestSessionStateEndpoint:self, session_factory: async_sessionmaker[AsyncSession]) -> None:user_id = await _make_user(session_factory, name="single", tenant_id=TENANT_B)- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)body = (await self._get(session_factory, token, signup_mode="default_tenant")@@ -426,7 +428,7 @@ class TestSessionStateEndpoint:user_id = await _make_user_with_memberships(session_factory, name="chooser", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)body = (await self._get(session_factory, token, signup_mode="default_tenant")@@ -444,7 +446,7 @@ class TestSessionStateEndpoint:contradicted by the very next request."""user_id = await _make_user(session_factory, name="stale", tenant_id=TENANT_B)token = create_jwt(- user_id, "[email protected]", "user", _SECRET, NOT_A_MEMBER_TENANT+ user_id, "[email protected]", "user", _KEYRING, NOT_A_MEMBER_TENANT)body = (@@ -460,7 +462,7 @@ class TestSessionStateEndpoint:user_id = await _make_user_with_memberships(session_factory, name="nowhere", tenant_ids=[])- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)body = (await self._get(session_factory, token, signup_mode="open")).json()@@ -474,7 +476,7 @@ class TestSessionStateEndpoint:user_id = await _make_user_with_memberships(session_factory, name="waiting", tenant_ids=[])- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)body = (await self._get(session_factory, token, signup_mode="invite_only")@@ -489,7 +491,7 @@ class TestSessionStateEndpoint:user_id = await _make_user_with_memberships(session_factory, name="mailer", tenant_ids=[TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)off = await self._get(session_factory, token, signup_mode="open")on = await self._get(@@ -527,7 +529,7 @@ class TestAGatewayRequestBindsTheCallersTenant:await session.commit()user_id = user.id- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)async with _client(_app(session_factory), token) as client:response = await client.get("/whoami")@@ -563,7 +565,7 @@ class TestAClaimSelectsAMembership:session_factory, name="claimant", tenant_ids=[TENANT_ZERO_ID, TENANT_B])token = create_jwt(- user_id, "[email protected]", "user", _SECRET, TENANT_B+ user_id, "[email protected]", "user", _KEYRING, TENANT_B)async with _client(_app(session_factory), token) as client:@@ -579,7 +581,7 @@ class TestAClaimSelectsAMembership:session_factory, name="mismatched", tenant_id=TENANT_ZERO_ID)token = create_jwt(- user_id, "[email protected]", "user", _SECRET, NOT_A_MEMBER_TENANT+ user_id, "[email protected]", "user", _KEYRING, NOT_A_MEMBER_TENANT)async with _client(_app(session_factory), token) as client:@@ -610,7 +612,7 @@ class TestNoClaimWithSeveralMemberships:user_id = await _make_user_with_memberships(session_factory, name="undecided", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)async with _client(_app(session_factory, choice_enabled=False), token@@ -626,7 +628,7 @@ class TestNoClaimWithSeveralMemberships:user_id = await _make_user_with_memberships(session_factory, name="chooser", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)async with _client(_app(session_factory, choice_enabled=True), token) as client:response = await client.get("/whoami")@@ -665,7 +667,7 @@ class TestNoClaimWithSeveralMemberships:user_id = await _make_user_with_memberships(session_factory, name="counted", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)async with _client(_app(session_factory, choice_enabled=True), token) as client:response = await client.get("/whoami")@@ -690,7 +692,7 @@ class TestAUserWithNoMembership:await session.commit()user_id = user.id- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)async with _client(_app(session_factory), token) as client:response = await client.get("/whoami")@@ -712,7 +714,7 @@ class TestConcurrentRequests:async def _call(user_id: str, name: str) -> dict:token = create_jwt(- user_id, f"{name}@example.invalid", "user", _SECRET, None+ user_id, f"{name}@example.invalid", "user", _KEYRING, None)async with _client(app, token) as client:response = await client.get("/whoami", params={"hold": 0.2})@@ -740,7 +742,7 @@ class TestListTenantsEndpoint:user_id = await _make_user_with_memberships(session_factory, name="lister", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)async with _client(_tenants_app(session_factory), token) as client:response = await client.get("/tenants")@@ -761,7 +763,9 @@ class TestListTenantsEndpoint:user_id = await _make_user_with_memberships(session_factory, name="undecided2", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(+ user_id, "[email protected]", "user", _KEYRING, None+ )async with _client(_tenants_app(session_factory), token) as client:response = await client.get("/tenants")@@ -777,7 +781,7 @@ class TestSwitchTenantEndpoint:user_id = await _make_user_with_memberships(session_factory, name="switcher", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)async with _client(_tenants_app(session_factory), token) as client:response = await client.post(f"/tenants/{TENANT_B}/switch")@@ -796,7 +800,7 @@ class TestSwitchTenantEndpoint:user_id = await _make_user(session_factory, name="notmember", tenant_id=TENANT_ZERO_ID)- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)async with _client(_tenants_app(session_factory), token) as client:response = await client.post(f"/tenants/{TENANT_B}/switch")@@ -843,7 +847,7 @@ class TestARequestHoldsOneConnection:user_id = await _make_user(one_connection_session_factory, name="solo", tenant_id=TENANT_ZERO_ID)- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)async with _client(_app(one_connection_session_factory), token) as client:response = await client.get("/whoami")@@ -857,7 +861,7 @@ class TestARequestHoldsOneConnection:user_id = await _make_user(one_connection_session_factory, name="editable", tenant_id=TENANT_ZERO_ID)- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)app = _app(one_connection_session_factory)@app.post("/rename")@@ -900,7 +904,7 @@ class TestTenantListingHoldsOneConnectionAtATime:name="poolsolo",tenant_ids=[TENANT_ZERO_ID, TENANT_B],)- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)async with _client(_tenants_app(one_connection_session_factory), token@@ -960,7 +964,7 @@ class TestSigningInHoldsOneConnectionAtATime:name="poolstate",tenant_ids=[TENANT_ZERO_ID, TENANT_B],)- token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)+ token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)async with _client(_session_app(one_connection_session_factory, signup_mode="open"), tokendiff --git a/core/tests/switch_core/observability/test_bootstrap.py b/core/tests/switch_core/observability/test_bootstrap.pyindex d384b6f03..bc677f899 100644--- a/core/tests/switch_core/observability/test_bootstrap.py+++ b/core/tests/switch_core/observability/test_bootstrap.py@@ -21,7 +21,7 @@ BASE_ENV = {"DB_NAME": "switch","MATRIX_SERVER_NAME": "switch.local","AGENT_REGISTRATION_TOKEN": "token",- "JWT_SECRET_KEY": "jwt",+ "SECRET_KEYS": "test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","GATEWAY_ADMIN_EMAIL": "[email protected]","GATEWAY_ADMIN_PASSWORD": "pw",}diff --git a/core/tests/switch_core/telemetry/test_bridge_connect_reporting.py b/core/tests/switch_core/telemetry/test_bridge_connect_reporting.pyindex 6307b922b..5edb4df3e 100644--- a/core/tests/switch_core/telemetry/test_bridge_connect_reporting.py+++ b/core/tests/switch_core/telemetry/test_bridge_connect_reporting.py@@ -39,6 +39,7 @@ from switch_core.db.models import Client, CollaborationBridgefrom switch_core.db.stores.client_store import ClientStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.room_store import RoomStore+from switch_core.keys import Keyringfrom switch_core.telemetry.service import TelemetryServicefrom switch_core.telemetry.sink import TelemetryRecordfrom tests.switch_core.bridges.collaboration.test_lifecycle_callback_endpoint import (@@ -85,7 +86,7 @@ def _service_with_telemetry(config.gateway_public_url = "https://gw.example"config.collaboration_callback_host = "127.0.0.1"config.collaboration_callback_port = callback_port- config.jwt_secret_key = "server-secret-for-tests"+ config.keyring = Keyring.parse("test:" + "x" * 40, legacy_secret=None)service = CollaborationBridgeLifecycleService(bridge_store=CollaborationBridgeStore(),external_user_store=MagicMock(),diff --git a/core/tests/switch_core/telemetry/test_emitters_are_live.py b/core/tests/switch_core/telemetry/test_emitters_are_live.pyindex a1ebc645e..c0ecc92fc 100644--- a/core/tests/switch_core/telemetry/test_emitters_are_live.py+++ b/core/tests/switch_core/telemetry/test_emitters_are_live.py@@ -26,6 +26,7 @@ from typing import Anyfrom switch_core.bridges.agent.app import create_agent_bridge_appfrom switch_core.bridges.agent.dependencies import get_protocol, get_telemetryfrom switch_core.bridges.agent.protocol.event_buffer import EventBuffer+from switch_core.keys import Keyringfrom switch_core.telemetry.service import TelemetryServicefrom switch_core.telemetry.sink import NullSink@@ -68,7 +69,7 @@ def _config() -> Any:class _Config:agent_auth_cache_ttl_seconds = 1agent_auth_cache_max_entries = 16- jwt_secret_key = "x"+ keyring = Keyring.parse("test:" + "x" * 40, legacy_secret=None)oauth_issuer_url = Noneoauth_audience = Noneoauth_verify_issuer = Truediff --git a/core/tests/switch_core/telemetry/test_merge_fixes.py b/core/tests/switch_core/telemetry/test_merge_fixes.pyindex 312631f56..32ed86c6b 100644--- a/core/tests/switch_core/telemetry/test_merge_fixes.py+++ b/core/tests/switch_core/telemetry/test_merge_fixes.py@@ -55,7 +55,7 @@ def _config(**overrides: object) -> object:"db_name": "d","matrix_server_name": "test","agent_registration_token": "t",- "jwt_secret_key": "k",+ "secret_keys": "test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","gateway_admin_email": "[email protected]","gateway_admin_password": "pw",}diff --git a/core/tests/switch_core/test_config_db_ssl.py b/core/tests/switch_core/test_config_db_ssl.pyindex f5896810a..b5b0903e4 100644--- a/core/tests/switch_core/test_config_db_ssl.py+++ b/core/tests/switch_core/test_config_db_ssl.py@@ -18,7 +18,7 @@ _BASE_KWARGS = dict(db_name="switch",id_server_name="switch.local",agent_registration_token="token",- jwt_secret_key="jwt",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",gateway_admin_email="[email protected]",gateway_admin_password="pw",)diff --git a/core/tests/switch_core/test_config_db_user.py b/core/tests/switch_core/test_config_db_user.pyindex 0fe2d06f0..ba9b6fe6b 100644--- a/core/tests/switch_core/test_config_db_user.py+++ b/core/tests/switch_core/test_config_db_user.py@@ -10,7 +10,7 @@ _BASE_KWARGS = dict(db_name="switch",id_server_name="switch.local",agent_registration_token="token",- jwt_secret_key="jwt",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",gateway_admin_email="[email protected]",gateway_admin_password="pw",)diff --git a/core/tests/switch_core/test_config_discord_app.py b/core/tests/switch_core/test_config_discord_app.pyindex ea86338d7..dbcf10136 100644--- a/core/tests/switch_core/test_config_discord_app.py+++ b/core/tests/switch_core/test_config_discord_app.py@@ -20,7 +20,7 @@ _BASE_KWARGS = dict(db_name="switch",id_server_name="switch.local",agent_registration_token="token",- jwt_secret_key="jwt",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",gateway_admin_email="[email protected]",gateway_admin_password="pw",)diff --git a/core/tests/switch_core/test_config_gateway_public_url.py b/core/tests/switch_core/test_config_gateway_public_url.pyindex 23b530da1..eaaa7c6cd 100644--- a/core/tests/switch_core/test_config_gateway_public_url.py+++ b/core/tests/switch_core/test_config_gateway_public_url.py@@ -10,7 +10,7 @@ _BASE_KWARGS = dict(db_name="switch",id_server_name="switch.local",agent_registration_token="token",- jwt_secret_key="jwt",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",gateway_admin_email="[email protected]",gateway_admin_password="pw",)diff --git a/core/tests/switch_core/test_config_id_server_name.py b/core/tests/switch_core/test_config_id_server_name.pyindex 0938e2180..6c76b9c90 100644--- a/core/tests/switch_core/test_config_id_server_name.py+++ b/core/tests/switch_core/test_config_id_server_name.py@@ -15,7 +15,7 @@ _REQUIRED = {"DB_OWNER_USER": "switch_owner","DB_OWNER_PASSWORD": "x","AGENT_REGISTRATION_TOKEN": "x",- "JWT_SECRET_KEY": "x",+ "SECRET_KEYS": "test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","GATEWAY_ADMIN_EMAIL": "[email protected]","GATEWAY_ADMIN_PASSWORD": "x",}diff --git a/core/tests/switch_core/test_config_max_workspaces.py b/core/tests/switch_core/test_config_max_workspaces.pyindex 5742d9e58..58149f183 100644--- a/core/tests/switch_core/test_config_max_workspaces.py+++ b/core/tests/switch_core/test_config_max_workspaces.py@@ -9,7 +9,7 @@ _BASE_KWARGS = dict(db_name="switch",id_server_name="switch.local",agent_registration_token="token",- jwt_secret_key="jwt",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",gateway_admin_email="[email protected]",)diff --git a/core/tests/switch_core/test_config_oauth_audience.py b/core/tests/switch_core/test_config_oauth_audience.pynew file mode 100644index 000000000..82cb4bd3e--- /dev/null+++ b/core/tests/switch_core/test_config_oauth_audience.py@@ -0,0 +1,48 @@+import pytest++from switch_core.config import SwitchConfig++_BASE_KWARGS = dict(+ db_host="db",+ db_port="5432",+ db_user="postgres",+ db_name="switch",+ id_server_name="switch.local",+ agent_registration_token="token",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",+ gateway_admin_email="[email protected]",+)+++def _config(**overrides: object) -> SwitchConfig:+ return SwitchConfig( # type: ignore[arg-type]+ **{+ **_BASE_KWARGS,+ "db_password": "placeholder", # gitleaks:allow+ "gateway_admin_password": "placeholder", # gitleaks:allow+ **overrides,+ }+ )+++def test_agent_oidc_off_needs_no_audience() -> None:+ assert _config().oauth_audience is None+++def test_an_issuer_with_an_audience_is_accepted() -> None:+ config = _config(+ oauth_issuer_url="https://idp.example.invalid/realms/switch",+ oauth_audience="switch",+ )+ assert config.oauth_audience == "switch"++[email protected]("audience", [None, ""])+def test_an_issuer_without_an_audience_raises(audience: str | None) -> None:+ # Without an audience, a token the IdP minted for any other application+ # would authenticate an agent here.+ with pytest.raises(ValueError, match="OAUTH_AUDIENCE"):+ _config(+ oauth_issuer_url="https://idp.example.invalid/realms/switch",+ oauth_audience=audience,+ )diff --git a/core/tests/switch_core/test_config_observability.py b/core/tests/switch_core/test_config_observability.pyindex e65c727d6..0a46cf7ec 100644--- a/core/tests/switch_core/test_config_observability.py+++ b/core/tests/switch_core/test_config_observability.py@@ -10,7 +10,7 @@ BASE_ENV = {"DB_NAME": "switch","MATRIX_SERVER_NAME": "switch.local","AGENT_REGISTRATION_TOKEN": "token",- "JWT_SECRET_KEY": "jwt",+ "SECRET_KEYS": "test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","GATEWAY_ADMIN_EMAIL": "[email protected]","GATEWAY_ADMIN_PASSWORD": "pw",}diff --git a/core/tests/switch_core/test_config_restricted_role.py b/core/tests/switch_core/test_config_restricted_role.pynew file mode 100644index 000000000..2e27b3f2c--- /dev/null+++ b/core/tests/switch_core/test_config_restricted_role.py@@ -0,0 +1,42 @@+import pytest++from switch_core.config import SwitchConfig++_BASE_KWARGS = dict(+ db_host="db",+ db_port="5432",+ db_user="postgres",+ db_name="switch",+ id_server_name="switch.local",+ agent_registration_token="token",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",+ gateway_admin_email="[email protected]",+)+++def _config(**overrides: object) -> SwitchConfig:+ return SwitchConfig( # type: ignore[arg-type]+ **{+ **_BASE_KWARGS,+ "db_password": "placeholder", # gitleaks:allow+ "gateway_admin_password": "placeholder", # gitleaks:allow+ **overrides,+ }+ )++[email protected]("mode", ["default_tenant", "invite_only"])+def test_opting_out_is_accepted_where_people_cannot_make_workspaces(+ mode: str,+) -> None:+ config = _config(db_require_restricted_role=False, gateway_signup_mode=mode)+ assert config.db_require_restricted_role is False+++def test_opting_out_with_open_signup_raises() -> None:+ with pytest.raises(ValueError, match="DB_REQUIRE_RESTRICTED_ROLE"):+ _config(db_require_restricted_role=False, gateway_signup_mode="open")+++def test_open_signup_with_the_check_on_is_accepted() -> None:+ assert _config(gateway_signup_mode="open").gateway_signup_mode == "open"diff --git a/core/tests/switch_core/test_config_secure_defaults.py b/core/tests/switch_core/test_config_secure_defaults.pynew file mode 100644index 000000000..fed42241c--- /dev/null+++ b/core/tests/switch_core/test_config_secure_defaults.py@@ -0,0 +1,17 @@+"""Defaults a deployment gets by setting nothing.++Both fail towards the hosted deployment: a local http stack opts out of Secure+cookies, and a server whose migrations run elsewhere opts out of migrating.+"""++from __future__ import annotations++from switch_core.config import SwitchConfig+++def test_auth_cookies_are_secure_unless_turned_off() -> None:+ assert SwitchConfig.model_fields["gateway_cookie_secure"].default is True+++def test_the_server_migrates_at_boot_unless_turned_off() -> None:+ assert SwitchConfig.model_fields["db_migrate_on_boot"].default is Truediff --git a/core/tests/switch_core/test_config_slack_app.py b/core/tests/switch_core/test_config_slack_app.pyindex 4711d31f9..55be2d2a0 100644--- a/core/tests/switch_core/test_config_slack_app.py+++ b/core/tests/switch_core/test_config_slack_app.py@@ -20,7 +20,7 @@ _BASE_KWARGS = dict(db_name="switch",id_server_name="switch.local",agent_registration_token="token",- jwt_secret_key="jwt",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",gateway_admin_email="[email protected]",gateway_admin_password="pw",)diff --git a/core/tests/switch_core/test_config_smtp.py b/core/tests/switch_core/test_config_smtp.pyindex a96793960..4b91f7d03 100644--- a/core/tests/switch_core/test_config_smtp.py+++ b/core/tests/switch_core/test_config_smtp.py@@ -10,7 +10,7 @@ _BASE_KWARGS = dict(db_name="switch",id_server_name="switch.local",agent_registration_token="token",- jwt_secret_key="jwt",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",gateway_admin_email="[email protected]",gateway_admin_password="pw",)diff --git a/core/tests/switch_core/test_config_standalone_compose.py b/core/tests/switch_core/test_config_standalone_compose.pyindex 9ab2a1bd5..bdc9bae09 100644--- a/core/tests/switch_core/test_config_standalone_compose.py+++ b/core/tests/switch_core/test_config_standalone_compose.py@@ -28,7 +28,7 @@ _BASE_KWARGS = dict(db_name="switch",id_server_name="switch.local",agent_registration_token="token",- jwt_secret_key="jwt",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",gateway_admin_email="[email protected]",gateway_admin_password="pw",)diff --git a/core/tests/switch_core/test_db_idle_in_transaction_timeout.py b/core/tests/switch_core/test_db_idle_in_transaction_timeout.pyindex bc25fe24b..c2bfd50bf 100644--- a/core/tests/switch_core/test_db_idle_in_transaction_timeout.py+++ b/core/tests/switch_core/test_db_idle_in_transaction_timeout.py@@ -21,7 +21,7 @@ _BASE_KWARGS = dict(db_name="switch",id_server_name="switch.local",agent_registration_token="token",- jwt_secret_key="jwt",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",gateway_admin_email="[email protected]",gateway_admin_password="pw",)diff --git a/core/tests/switch_core/test_db_migration_lock_timeout.py b/core/tests/switch_core/test_db_migration_lock_timeout.pyindex 7abd5ec56..c678d1815 100644--- a/core/tests/switch_core/test_db_migration_lock_timeout.py+++ b/core/tests/switch_core/test_db_migration_lock_timeout.py@@ -24,7 +24,7 @@ _BASE_KWARGS = dict(db_name="switch",id_server_name="switch.local",agent_registration_token="token",- jwt_secret_key="jwt",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",gateway_admin_email="[email protected]",gateway_admin_password="pw",)diff --git a/core/tests/switch_core/test_keys.py b/core/tests/switch_core/test_keys.pynew file mode 100644index 000000000..5d5a500f4--- /dev/null+++ b/core/tests/switch_core/test_keys.py@@ -0,0 +1,129 @@+"""The keyring: parsing `SECRET_KEYS`, per-purpose keys, encryption with key ids."""++from __future__ import annotations++import base64+import hashlib++import pytest+from cryptography.fernet import Fernet++from switch_core.keys import Keyring, KeyringError, Purpose, UndecryptableError++_A = "a" * 40+_B = "b" * 40+++def _keyring(value: str, legacy: str | None = None) -> Keyring:+ return Keyring.parse(value, legacy_secret=legacy)+++class TestParsing:+ def test_the_first_key_is_current(self) -> None:+ keyring = _keyring(f"new:{_B}, old:{_A}")+ assert [k.id for k in keyring.keys] == ["new", "old"]+ assert keyring.current.id == "new"++ def test_a_secret_may_contain_colons(self) -> None:+ assert _keyring(f"k1:{_A}:tail").current.secret == f"{_A}:tail".encode()++ @pytest.mark.parametrize(+ ("value", "message"),+ [+ ("", "at least one key"),+ (_A, "no ':'"),+ (f"bad id:{_A}", "key id"),+ ("k1:short", "shorter than 32"),+ (f"k1:{_A},k1:{_B}", "twice"),+ ],+ )+ def test_malformed_values_are_refused(self, value: str, message: str) -> None:+ with pytest.raises(KeyringError, match=message):+ _keyring(value)++ def test_an_empty_legacy_secret_is_none(self) -> None:+ assert _keyring(f"k1:{_A}", legacy="").legacy_secret is None+++class TestDerivedKeys:+ def test_each_purpose_gets_its_own_key(self) -> None:+ keyring = _keyring(f"k1:{_A}")+ derived = {keyring.derive(purpose) for purpose in Purpose}+ assert len(derived) == len(Purpose)++ def test_no_derived_key_is_the_master_key(self) -> None:+ keyring = _keyring(f"k1:{_A}")+ assert all(keyring.derive(p) != _A.encode() for p in Purpose)++ def test_derivation_is_stable(self) -> None:+ assert _keyring(f"k1:{_A}").derive(Purpose.SESSION) == _keyring(+ f"other:{_B},k1:{_A}"+ ).derive(Purpose.SESSION, "k1")++ def test_verification_keys_are_every_master_keys_current_first(self) -> None:+ keyring = _keyring(f"new:{_B},old:{_A}")+ assert keyring.verification_keys(Purpose.INSTALL_STATE) == [+ keyring.derive(Purpose.INSTALL_STATE, "new"),+ keyring.derive(Purpose.INSTALL_STATE, "old"),+ ]++ def test_an_unknown_key_id_is_refused(self) -> None:+ with pytest.raises(KeyringError, match="No key 'gone'"):+ _keyring(f"k1:{_A}").derive(Purpose.SESSION, "gone")+++class TestEncryption:+ def test_a_value_round_trips_and_names_its_key(self) -> None:+ keyring = _keyring(f"k1:{_A}")+ encrypted = keyring.encrypt("xoxb-secret")+ assert encrypted.startswith("k1$k1$")+ assert "xoxb-secret" not in encrypted+ assert keyring.decrypt(encrypted) == "xoxb-secret"+ assert keyring.is_current(encrypted)++ def test_a_value_under_an_older_key_still_opens(self) -> None:+ old = _keyring(f"k1:{_A}").encrypt("xoxb-secret")+ rotated = _keyring(f"k2:{_B},k1:{_A}")+ assert rotated.decrypt(old) == "xoxb-secret"+ assert not rotated.is_current(old)++ def test_a_value_under_a_removed_key_is_an_error(self) -> None:+ old = _keyring(f"k1:{_A}").encrypt("xoxb-secret")+ with pytest.raises(UndecryptableError, match="no longer in SECRET_KEYS"):+ _keyring(f"k2:{_B}").decrypt(old)++ def test_a_key_whose_secret_changed_is_an_error(self) -> None:+ old = _keyring(f"k1:{_A}").encrypt("xoxb-secret")+ with pytest.raises(UndecryptableError, match="secret has changed"):+ _keyring(f"k1:{_B}").decrypt(old)++ def test_the_at_rest_key_is_not_the_old_scheme(self) -> None:+ """A value encrypted the old way with the master secret is not one the+ new key opens: the legacy path is only for `JWT_SECRET_KEY`."""+ naive = Fernet(base64.urlsafe_b64encode(hashlib.sha256(_A.encode()).digest()))+ with pytest.raises(UndecryptableError):+ _keyring(f"k1:{_A}").decrypt(naive.encrypt(b"x").decode())+++def _legacy_encrypt(secret: str, plaintext: str) -> str:+ """How a value was encrypted with `JWT_SECRET_KEY` before `SECRET_KEYS`."""+ key = base64.urlsafe_b64encode(hashlib.sha256(secret.encode()).digest())+ return Fernet(key).encrypt(plaintext.encode()).decode()+++class TestLegacyValues:+ def test_open_while_the_legacy_secret_is_set(self) -> None:+ keyring = _keyring(f"k1:{_A}", legacy="old-jwt-secret")+ value = _legacy_encrypt("old-jwt-secret", "xoxb-secret")+ assert keyring.decrypt(value) == "xoxb-secret"+ assert not keyring.is_current(value)++ def test_are_an_error_once_it_is_removed(self) -> None:+ value = _legacy_encrypt("old-jwt-secret", "xoxb-secret")+ with pytest.raises(UndecryptableError, match="JWT_SECRET_KEY is not set"):+ _keyring(f"k1:{_A}").decrypt(value)++ def test_are_an_error_under_a_different_legacy_secret(self) -> None:+ value = _legacy_encrypt("old-jwt-secret", "xoxb-secret")+ with pytest.raises(UndecryptableError, match="does not open"):+ _keyring(f"k1:{_A}", legacy="another").decrypt(value)diff --git a/core/tests/switch_core/test_logging_config.py b/core/tests/switch_core/test_logging_config.pyindex eacdad6b9..b1e9e9f39 100644--- a/core/tests/switch_core/test_logging_config.py+++ b/core/tests/switch_core/test_logging_config.py@@ -25,7 +25,7 @@ BASE_ENV = {"DB_NAME": "switch","MATRIX_SERVER_NAME": "switch.local","AGENT_REGISTRATION_TOKEN": "token",- "JWT_SECRET_KEY": "jwt",+ "SECRET_KEYS": "test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","GATEWAY_ADMIN_EMAIL": "[email protected]","GATEWAY_ADMIN_PASSWORD": "pw",}diff --git a/core/tests/switch_core/test_main.py b/core/tests/switch_core/test_main.pyindex 8890bffd0..b1ede72d9 100644--- a/core/tests/switch_core/test_main.py+++ b/core/tests/switch_core/test_main.py@@ -62,7 +62,7 @@ def _config(token: str, *, admin_email: str = ADMIN_EMAIL) -> SwitchConfig:db_name="unused",id_server_name="test",agent_registration_token=token,- jwt_secret_key="test-jwt-secret",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",gateway_admin_email=admin_email,gateway_admin_password="unused",)@@ -85,7 +85,7 @@ def _config_for(postgres_url: str) -> SwitchConfig:db_name=url.database,id_server_name="test",agent_registration_token="unused",- jwt_secret_key="test-jwt-secret",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",gateway_admin_email=ADMIN_EMAIL,gateway_admin_password="unused",)diff --git a/core/tests/switch_core/test_main_tenant_isolation_check.py b/core/tests/switch_core/test_main_tenant_isolation_check.pynew file mode 100644index 000000000..f00e6ac21--- /dev/null+++ b/core/tests/switch_core/test_main_tenant_isolation_check.py@@ -0,0 +1,92 @@+"""Boot's tenant-isolation check, and how far `DB_REQUIRE_RESTRICTED_ROLE=false`+may relax it.++The opt-out exists for a single-tenant deployment that has not created its+runtime role yet. The owner engine stands in for such a deployment: it is a+superuser, so the restricted-role check refuses it.+"""++from __future__ import annotations++import pytest+from sqlalchemy import insert, text++from switch_core.config import SwitchConfig+from switch_core.db.models import Tenant+from switch_core.db.runtime_role import RuntimeRoleError+from switch_core.main import _check_tenant_isolation+from tests.conftest import RLSHarness++pytestmark = pytest.mark.no_ambient_tenant+++def _config(*, require_restricted_role: bool) -> SwitchConfig:+ return SwitchConfig( # type: ignore[call-arg]+ db_host="db",+ db_port="5432",+ db_user="postgres",+ db_name="switch",+ db_password="placeholder", # gitleaks:allow+ id_server_name="switch.local",+ agent_registration_token="token",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",+ gateway_admin_email="[email protected]",+ gateway_admin_password="placeholder", # gitleaks:allow+ db_require_restricted_role=require_restricted_role,+ )+++async def test_an_unrestricted_connection_is_refused_by_default(+ rls_harness: RLSHarness,+) -> None:+ with pytest.raises(RuntimeRoleError):+ await _check_tenant_isolation(+ _config(require_restricted_role=True), rls_harness.owner_engine+ )+++async def test_opting_out_is_allowed_with_one_workspace(+ rls_harness: RLSHarness,+) -> None:+ assert not await _check_tenant_isolation(+ _config(require_restricted_role=False), rls_harness.owner_engine+ )+++async def test_opting_out_is_refused_once_a_second_workspace_exists(+ rls_harness: RLSHarness,+) -> None:+ async with rls_harness.owner_engine.begin() as conn:+ await conn.execute(+ insert(Tenant.__table__).values(id="tenant-two", slug="two", name="Two")+ )++ with pytest.raises(RuntimeRoleError, match="2 workspaces"):+ await _check_tenant_isolation(+ _config(require_restricted_role=False), rls_harness.owner_engine+ )+++async def test_a_restricted_connection_reports_isolation(+ rls_harness: RLSHarness,+) -> None:+ assert await _check_tenant_isolation(+ _config(require_restricted_role=True), rls_harness.restricted_engine+ )+++async def test_opting_out_survives_a_role_boot_could_not_grant(+ rls_harness: RLSHarness,+) -> None:+ """No DB_OWNER_USER, so boot never granted the runtime role the lookups.+ The role check names that; counting workspaces through a lookup the role+ cannot run must not turn it into a permission-denied crash."""+ role = rls_harness.restricted_engine.url.username+ async with rls_harness.owner_engine.begin() as conn:+ await conn.execute(+ text(f'REVOKE EXECUTE ON FUNCTION all_tenant_ids() FROM "{role}"')+ )++ assert not await _check_tenant_isolation(+ _config(require_restricted_role=False), rls_harness.restricted_engine+ )diff --git a/core/tests/switch_core/test_outbound.py b/core/tests/switch_core/test_outbound.pynew file mode 100644index 000000000..6c33ae90c--- /dev/null+++ b/core/tests/switch_core/test_outbound.py@@ -0,0 +1,214 @@+"""The outbound policy, and the client that connects only where it allows."""++from __future__ import annotations++import socket+from collections.abc import AsyncIterator+from typing import Any++import httpx+import pytest+import pytest_asyncio+from aiohttp import web++from switch_core.config import SwitchConfig+from switch_core.outbound import (+ OutboundPolicy,+ OutboundURLRefused,+ guarded_async_client,+)++_NOTHING_ALLOWED = OutboundPolicy.parse("")+++class TestParsing:+ def test_hostnames_and_networks(self) -> None:+ policy = OutboundPolicy.parse(" Mattermost , 10.0.0.0/8,, fd00::/8 ")+ assert policy.allowed_hostnames == frozenset({"mattermost"})+ assert [str(n) for n in policy.allowed_networks] == ["10.0.0.0/8", "fd00::/8"]++ def test_a_compose_service_name_with_an_underscore(self) -> None:+ policy = OutboundPolicy.parse("my_mattermost")+ assert policy.allowed_hostnames == frozenset({"my_mattermost"})++ @pytest.mark.parametrize("entry", ["http://mattermost", "bad host", "-x"])+ def test_anything_else_is_refused(self, entry: str) -> None:+ with pytest.raises(ValueError, match="OUTBOUND_ALLOWED_PRIVATE_HOSTS"):+ OutboundPolicy.parse(entry)++ def test_the_setting_is_checked_at_startup(self) -> None:+ with pytest.raises(ValueError, match="OUTBOUND_ALLOWED_PRIVATE_HOSTS"):+ SwitchConfig( # type: ignore[call-arg]+ db_host="db",+ db_port="5432",+ db_user="postgres",+ db_name="switch",+ db_password="placeholder", # gitleaks:allow+ id_server_name="switch.local",+ agent_registration_token="token",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",+ gateway_admin_email="[email protected]",+ gateway_admin_password="placeholder", # gitleaks:allow+ outbound_allowed_private_hosts="not a host",+ )+++def _resolving_to(monkeypatch: pytest.MonkeyPatch, *addresses: str) -> None:+ async def _getaddrinfo(self: Any, host: str, port: int, **_: Any) -> list[Any]:+ return [+ (+ socket.AF_INET6 if ":" in a else socket.AF_INET,+ socket.SOCK_STREAM,+ 6,+ "",+ (a, port),+ )+ for a in addresses+ ]++ monkeypatch.setattr("asyncio.base_events.BaseEventLoop.getaddrinfo", _getaddrinfo)+++class TestWhatMayBeReached:+ async def test_a_public_address(self) -> None:+ assert await _NOTHING_ALLOWED.resolve("93.184.215.14", 443) == ["93.184.215.14"]++ @pytest.mark.parametrize(+ "address",+ [+ "127.0.0.1",+ "10.1.2.3",+ "192.168.0.1",+ "100.64.0.1",+ "::1",+ "::ffff:127.0.0.1",+ "0.0.0.0",+ ],+ )+ async def test_a_private_address_is_refused(self, address: str) -> None:+ with pytest.raises(OutboundURLRefused, match="not a public address"):+ await _NOTHING_ALLOWED.resolve(address, 80)++ async def test_a_listed_network(self) -> None:+ policy = OutboundPolicy.parse("10.0.0.0/8")+ assert await policy.resolve("10.1.2.3", 80) == ["10.1.2.3"]++ async def test_a_listed_hostname_whatever_it_resolves_to(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _resolving_to(monkeypatch, "10.9.9.9")+ policy = OutboundPolicy.parse("mattermost")+ assert await policy.resolve("Mattermost", 8065) == ["10.9.9.9"]++ async def test_a_public_name_pointing_at_a_private_address(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _resolving_to(monkeypatch, "10.9.9.9")+ with pytest.raises(OutboundURLRefused, match="10.9.9.9"):+ await _NOTHING_ALLOWED.resolve("innocent.example.com", 443)++ async def test_one_private_address_among_public_ones_refuses_the_name(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _resolving_to(monkeypatch, "93.184.215.14", "127.0.0.1")+ with pytest.raises(OutboundURLRefused):+ await _NOTHING_ALLOWED.resolve("mixed.example.com", 443)++ @pytest.mark.parametrize(+ "address", ["169.254.169.254", "fd00:ec2::254", "100.100.100.200"]+ )+ async def test_metadata_is_refused_even_when_listed(self, address: str) -> None:+ policy = OutboundPolicy.parse("169.254.0.0/16,fd00::/8,100.64.0.0/10")+ with pytest.raises(OutboundURLRefused, match="metadata"):+ await policy.resolve(address, 80)++ async def test_the_gcp_metadata_name_is_refused(self) -> None:+ policy = OutboundPolicy.parse("metadata.google.internal")+ with pytest.raises(OutboundURLRefused, match="metadata"):+ await policy.resolve("metadata.google.internal", 80)+++class TestCheckingAURL:+ @pytest.mark.parametrize(+ "url", ["file:///etc/passwd", "gopher://example.com", "example.com/path"]+ )+ async def test_other_schemes_are_refused(self, url: str) -> None:+ with pytest.raises(OutboundURLRefused, match="must use"):+ await _NOTHING_ALLOWED.check_url(url)++ async def test_a_url_with_no_host_is_refused(self) -> None:+ with pytest.raises(OutboundURLRefused, match="no host"):+ await _NOTHING_ALLOWED.check_url("https://")++ async def test_a_private_host_is_refused(self) -> None:+ with pytest.raises(OutboundURLRefused):+ await _NOTHING_ALLOWED.check_url("http://127.0.0.1:8065/")+++@pytest_asyncio.fixture+async def local_server() -> AsyncIterator[int]:+ async def ok(_: web.Request) -> web.Response:+ return web.Response(text="ok")++ async def bounce(request: web.Request) -> web.Response:+ port = request.url.port+ raise web.HTTPFound(f"http://127.0.0.1:{port}/ok")++ app = web.Application()+ app.router.add_get("/ok", ok)+ app.router.add_get("/bounce", bounce)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ port = site._server.sockets[0].getsockname()[1] # type: ignore[union-attr]+ try:+ yield port+ finally:+ await runner.cleanup()+++class TestTheGuardedClient:+ async def test_it_keeps_httpxs_pool_limits(self) -> None:+ """Not httpcore's bare defaults of 10 connections kept idle forever."""+ async with guarded_async_client(_NOTHING_ALLOWED) as client:+ pool = client._transport._pool # type: ignore[attr-defined]+ assert pool._max_connections == 100+ assert pool._max_keepalive_connections == 20+ assert pool._keepalive_expiry == 5.0++ async def test_a_refused_address_is_never_connected_to(+ self, local_server: int+ ) -> None:+ async with guarded_async_client(_NOTHING_ALLOWED) as client:+ with pytest.raises(OutboundURLRefused):+ await client.get(f"http://127.0.0.1:{local_server}/ok")++ async def test_an_allowed_address_is_reached(self, local_server: int) -> None:+ # Also what proves the client's connections still go through the pool+ # `guarded_async_client` replaces; see the note there.+ policy = OutboundPolicy.parse("127.0.0.1/32")+ async with guarded_async_client(policy) as client:+ response = await client.get(f"http://127.0.0.1:{local_server}/ok")+ assert response.text == "ok"++ async def test_a_redirect_to_a_refused_address_is_not_followed_there(+ self, local_server: int+ ) -> None:+ # `localhost` is allowed by name; the redirect names 127.0.0.1, which is+ # not, so the second connection is refused.+ policy = OutboundPolicy.parse("localhost")+ async with guarded_async_client(policy, follow_redirects=True) as client:+ with pytest.raises(OutboundURLRefused):+ await client.get(f"http://localhost:{local_server}/bounce")++ async def test_proxy_settings_in_the_environment_are_ignored(+ self, local_server: int, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ # Through a proxy the address checked would be the proxy's.+ monkeypatch.setenv("HTTP_PROXY", "http://proxy.invalid:3128")+ monkeypatch.setenv("ALL_PROXY", "http://proxy.invalid:3128")+ policy = OutboundPolicy.parse("127.0.0.1/32")+ async with guarded_async_client(policy) as client:+ response = await client.get(f"http://127.0.0.1:{local_server}/ok")+ assert response.status_code == httpx.codes.OKdiff --git a/core/tests/switch_core/test_outbound_fetch_sites.py b/core/tests/switch_core/test_outbound_fetch_sites.pynew file mode 100644index 000000000..559aa1cbe--- /dev/null+++ b/core/tests/switch_core/test_outbound_fetch_sites.py@@ -0,0 +1,303 @@+"""Each place Switch fetches a URL a tenant or agent chose goes through the+outbound policy: bridge and connector configs when stored and started, the+Mattermost driver's redirects, the Mattermost icon fetch, and Slack file+downloads."""++from __future__ import annotations++import json+import threading+from collections.abc import AsyncIterator, Iterator+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from typing import Any+from unittest.mock import MagicMock++import pytest+import pytest_asyncio+from aiohttp import web+from mattermostdriver import Driver+from mattermostdriver.exceptions import ResourceNotFound++from switch_core.bridges.agent.server_connectors.lifecycle import (+ ServerSideConnectorLifecycleService,+)+from switch_core.bridges.agent.server_connectors.opencode.connector import (+ OpenCodeConnectionConfig,+ OpenCodeConnector,+)+from switch_core.bridges.collaboration import mattermost+from switch_core.bridges.collaboration.lifecycle_service import (+ CollaborationBridgeLifecycleService,+)+from switch_core.bridges.collaboration.mattermost.adapter import (+ MattermostAdapter,+ MattermostConnectionConfig,+)+from switch_core.bridges.collaboration.mattermost.http_client import (+ MattermostRedirectRefused,+ NoRedirectClient,+)+from switch_core.bridges.collaboration.models import BridgeStartRefused+from switch_core.bridges.collaboration.slack.adapter import (+ SlackAdapter,+ SlackConnectionConfig,+)+from switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.keys import Keyring+from switch_core.outbound import OutboundPolicy, OutboundURLRefused+++def _mattermost_config(url: str) -> dict[str, object]:+ return {+ "url": url,+ "admin_user": "bot",+ "admin_password": "placeholder", # gitleaks:allow+ "team_name": "eng",+ }+++def _bridge_lifecycle(policy: OutboundPolicy) -> CollaborationBridgeLifecycleService:+ config = MagicMock()+ config.outbound_policy = policy+ service = CollaborationBridgeLifecycleService(+ bridge_store=CollaborationBridgeStore(),+ external_user_store=MagicMock(),+ bridge_message_map_store=MagicMock(),+ room_store=RoomStore(),+ agent_store=MagicMock(),+ client_store=ClientStore(),+ client_lifecycle=MagicMock(),+ room_service=MagicMock(),+ provisioning=MagicMock(),+ session_factory=MagicMock(),+ config=config,+ client_factory=MagicMock(),+ session_activity_listener=MagicMock(),+ session_activity_service=MagicMock(),+ connections=MagicMock(),+ )+ service.register_adapter(+ "mattermost", MattermostAdapter, MattermostConnectionConfig+ )+ return service+++class TestBridgeConfigs:+ async def test_registering_a_private_server_url_is_refused(self) -> None:+ service = _bridge_lifecycle(OutboundPolicy.parse(""))+ with pytest.raises(OutboundURLRefused):+ await service.register(+ bridge_type="mattermost",+ display_name="Internal",+ connection_config=_mattermost_config("http://10.1.2.3:8065"),+ channel_creation_enabled=False,+ preconfigured=False,+ )++ async def test_an_edit_or_start_naming_one_is_refused(self) -> None:+ service = _bridge_lifecycle(OutboundPolicy.parse(""))+ with pytest.raises(BridgeStartRefused, match="10.1.2.3"):+ await service.check_start_guards(+ bridge_id="bridge-1",+ tenant_id="tenant-1",+ bridge_type="mattermost",+ connection_config=_mattermost_config("http://10.1.2.3:8065"),+ )++ async def test_an_allowed_private_host_passes(self) -> None:+ service = _bridge_lifecycle(OutboundPolicy.parse("localhost"))+ await service.check_start_guards(+ bridge_id="bridge-1",+ tenant_id="tenant-1",+ bridge_type="mattermost",+ connection_config=_mattermost_config("http://localhost:8065"),+ )++ async def test_a_url_with_no_scheme_is_checked_as_the_driver_reads_it(+ self,+ ) -> None:+ """The driver takes a scheme-less URL as http, and bridges configured+ that way keep starting; the host is still what is checked."""+ allowed = _bridge_lifecycle(OutboundPolicy.parse("localhost"))+ await allowed.check_start_guards(+ bridge_id="bridge-1",+ tenant_id="tenant-1",+ bridge_type="mattermost",+ connection_config=_mattermost_config("localhost:8065"),+ )+ refused = _bridge_lifecycle(OutboundPolicy.parse(""))+ with pytest.raises(BridgeStartRefused, match="10.1.2.3"):+ await refused.check_start_guards(+ bridge_id="bridge-1",+ tenant_id="tenant-1",+ bridge_type="mattermost",+ connection_config=_mattermost_config("10.1.2.3:8065"),+ )+++class TestConnectorConfigs:+ async def test_registering_a_private_server_url_is_refused(self) -> None:+ service = ServerSideConnectorLifecycleService(+ connector_store=MagicMock(),+ api_key_store=MagicMock(),+ protocol=MagicMock(),+ session_factory=MagicMock(),+ keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None),+ outbound_policy=OutboundPolicy.parse(""),+ )+ service.register_connector_type(+ "opencode", OpenCodeConnector, OpenCodeConnectionConfig+ )+ with pytest.raises(OutboundURLRefused):+ await service.register(+ connector_type="opencode",+ display_name="Internal",+ connection_config={+ "server_url": "http://10.0.0.5:4096",+ "username": "u",+ "password": "p",+ },+ user_id="user-1",+ )+++class _Handler(BaseHTTPRequestHandler):+ def _reply(self, status: int, body: dict[str, Any], **headers: str) -> None:+ payload = json.dumps(body).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(payload)))+ for name, value in headers.items():+ self.send_header(name, value)+ self.end_headers()+ self.wfile.write(payload)++ def do_GET(self) -> None:+ if self.path == "/api/v4/redirect":+ self._reply(302, {}, Location="http://169.254.169.254/latest/meta-data/")+ elif self.path == "/api/v4/missing":+ self._reply(404, {"message": "not here"})+ else:+ self._reply(200, {"ok": True})++ def log_message(self, *_: Any) -> None:+ pass+++def mattermost_server() -> Iterator[int]:+ server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield server.server_address[1]+ finally:+ server.shutdown()+++def _client(port: int) -> NoRedirectClient:+ driver = Driver(+ {"url": "127.0.0.1", "scheme": "http", "port": port, "verify": True},+ client_cls=NoRedirectClient,+ )+ return driver.client # type: ignore[no-any-return]+++class TestTheMattermostDriver:+ def test_a_redirect_is_refused_not_followed(self, mattermost_server: int) -> None:+ with pytest.raises(MattermostRedirectRefused, match="169.254.169.254"):+ _client(mattermost_server).make_request("get", "/redirect")++ def test_errors_keep_the_drivers_types(self, mattermost_server: int) -> None:+ with pytest.raises(ResourceNotFound):+ _client(mattermost_server).make_request("get", "/missing")++ def test_an_ordinary_request(self, mattermost_server: int) -> None:+ response = _client(mattermost_server).make_request("get", "/users/me")+ assert response.json() == {"ok": True}+++@pytest_asyncio.fixture+async def icon_server() -> AsyncIterator[int]:+ async def icon(request: web.Request) -> web.Response:+ return web.Response(body=b"x" * int(request.query["size"]))++ app = web.Application()+ app.router.add_get("/icon.png", icon)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ try:+ yield site._server.sockets[0].getsockname()[1] # type: ignore[union-attr]+ finally:+ await runner.cleanup()+++def _mattermost_adapter(policy: OutboundPolicy) -> MattermostAdapter:+ adapter = MattermostAdapter(+ config=MattermostConnectionConfig.model_validate(+ _mattermost_config("http://localhost:8065")+ )+ )+ adapter.set_outbound_policy(policy)+ return adapter+++class TestTheMattermostIconFetch:+ async def test_an_icon_at_a_refused_address_is_not_fetched(+ self, icon_server: int+ ) -> None:+ adapter = _mattermost_adapter(OutboundPolicy.parse(""))+ with pytest.raises(OutboundURLRefused):+ await adapter._fetch_icon(+ f"http://127.0.0.1:{icon_server}/icon.png?size=10"+ )++ async def test_an_icon_within_the_ceiling(self, icon_server: int) -> None:+ adapter = _mattermost_adapter(OutboundPolicy.parse("127.0.0.1/32"))+ data = await adapter._fetch_icon(+ f"http://127.0.0.1:{icon_server}/icon.png?size=10"+ )+ assert data == b"x" * 10++ async def test_an_icon_over_the_ceiling_is_dropped(+ self, icon_server: int, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(mattermost.adapter, "_MAX_BOT_ICON_BYTES", 1024)+ adapter = _mattermost_adapter(OutboundPolicy.parse("127.0.0.1/32"))+ data = await adapter._fetch_icon(+ f"http://127.0.0.1:{icon_server}/icon.png?size=100000"+ )+ assert data is None++ async def test_an_adapter_without_a_policy_fails_loudly(self) -> None:+ adapter = MattermostAdapter(+ config=MattermostConnectionConfig.model_validate(+ _mattermost_config("http://localhost:8065")+ )+ )+ with pytest.raises(RuntimeError, match="outbound policy"):+ await adapter._fetch_icon("https://example.com/icon.png")+++class TestSlackFileDownloads:+ @pytest.mark.parametrize(+ "url",+ [+ "https://evil.example/files-pri/T1/x",+ "https://files.slack.com.evil.example/x",+ "http://files.slack.com/files-pri/T1/x",+ "https://notslack.com/x",+ ],+ )+ async def test_only_slack_is_sent_the_bot_token(self, url: str) -> None:+ adapter = SlackAdapter(+ config=SlackConnectionConfig(+ bot_token="xoxb-test", app_token="xapp-test", workspace_id="T1"+ )+ )+ with pytest.raises(ValueError, match="not a Slack file URL"):+ await adapter._download_file(url)diff --git a/core/tests/switch_core/test_room_service_tenant_bindings.py b/core/tests/switch_core/test_room_service_tenant_bindings.pyindex e4a1c6ef6..c3e86142f 100644--- a/core/tests/switch_core/test_room_service_tenant_bindings.py+++ b/core/tests/switch_core/test_room_service_tenant_bindings.py@@ -225,6 +225,7 @@ def _registry(client_factory=_StubFactory(), # type: ignore[arg-type]session_factory=session_factory,config=SimpleNamespace(id_server_name="switch.local"), # type: ignore[arg-type]+ tenants_isolated=True,)for tenant_id, client_id, transport_user_id in running:service.start_client(diff --git a/core/tests/switch_core/test_seed_admin_membership.py b/core/tests/switch_core/test_seed_admin_membership.pyindex ea9dd3770..554d3d68c 100644--- a/core/tests/switch_core/test_seed_admin_membership.py+++ b/core/tests/switch_core/test_seed_admin_membership.py@@ -55,7 +55,7 @@ def _config() -> SwitchConfig:db_name="unused",id_server_name="test",agent_registration_token="unused",- jwt_secret_key="test-jwt-secret",+ secret_keys="test:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",gateway_admin_email=ADMIN_EMAIL,gateway_admin_password="hunter2",)diff --git a/core/tests/synthetic/generate_synthetic_db.py b/core/tests/synthetic/generate_synthetic_db.pyindex 9c5eaec5f..851f14022 100644--- a/core/tests/synthetic/generate_synthetic_db.py+++ b/core/tests/synthetic/generate_synthetic_db.py@@ -246,7 +246,7 @@ def _ensure_fake_app_env() -> None:"AGENT_REGISTRATION_TOKEN", "synthetic-fake-token-0000000000000000")os.environ.setdefault(- "JWT_SECRET_KEY", "synthetic-fake-jwt-secret-0000000000000000"+ "SECRET_KEYS", "synthetic:synthetic-fake-secret-key-0000000000000000")os.environ.setdefault("GATEWAY_ADMIN_EMAIL", "[email protected]")os.environ.setdefault("GATEWAY_ADMIN_PASSWORD", "synthetic-fake-admin-pw-0000")diff --git a/core/tests/test_migrate_entrypoint.py b/core/tests/test_migrate_entrypoint.pyindex 5cda0a6e0..e448cd121 100644--- a/core/tests/test_migrate_entrypoint.py+++ b/core/tests/test_migrate_entrypoint.py@@ -22,17 +22,25 @@ REPO_ROOT = Path(__file__).resolve().parents[2]MIGRATE_JOB = (REPO_ROOT / "deploy/remote/helm/switch/templates/switch-core/migrate-job.yaml")+DEPLOYMENT = (+ REPO_ROOT / "deploy/remote/helm/switch/templates/switch-core/deployment.yaml"+)CORE_PYPROJECT = REPO_ROOT / "core/pyproject.toml"ENTRY_POINT = "switch-migrate"-def _job_command() -> list[str]:- match = re.search(- r"^\s*command: (\[.*\])$", MIGRATE_JOB.read_text(), flags=re.MULTILINE+def _commands(template: Path) -> list[list[str]]:+ matches = re.findall(+ r"^\s*command: (\[.*\])$", template.read_text(), flags=re.MULTILINE)- assert match is not None, f"no container command found in {MIGRATE_JOB}"- return re.findall(r'"([^"]+)"', match.group(1))+ assert matches, f"no container command found in {template}"+ return [re.findall(r'"([^"]+)"', match) for match in matches]+++def _job_command() -> list[str]:+ (command,) = _commands(MIGRATE_JOB)+ return commanddef _console_scripts() -> dict[str, str]:@@ -44,6 +52,12 @@ def test_the_job_runs_the_migration_entry_point() -> None:assert _job_command() == [ENTRY_POINT]+def test_the_server_pods_init_container_runs_it_too() -> None:+ # The serving container is not given the owner credentials, so the+ # migration it no longer runs at boot has to run here, before it starts.+ assert [ENTRY_POINT] in _commands(DEPLOYMENT)++def test_the_entry_point_is_installed_by_the_package() -> None:# The image installs the project, so anything declared here lands on PATH# in the same container the Job runs — and anything not declared does not.diff --git a/core/uv.lock b/core/uv.lockindex 4029d3e00..00b9f9be2 100644--- a/core/uv.lock+++ b/core/uv.lock@@ -1908,11 +1908,11 @@ wheels = [[[package]]name = "pyjwt"-version = "2.13.0"+version = "2.15.1"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/3b/81/58d0ac84e1ef3a3843791d6954d94c0b33d526c75eeb1efbce9d0a4c4077/pyjwt-2.13.0.tar.gz", hash = "sha256:41571c89ca91598c79e8ef18a2d07367d4810fbbd6f637794879baf1b7703423", size = 107515, upload-time = "2026-05-21T19:54:36.618Z" }+sdist = { url = "https://files.pythonhosted.org/packages/43/ea/5194e52748b0da83d71e082d75496eaec6e58f419f5e184786ded517e6a9/pyjwt-2.15.1.tar.gz", hash = "sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8", size = 121252, upload-time = "2026-09-28T18:40:42.598Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/a3/5e/ecf12fdb62546d64385c158514e9b2b671f7832108ef2ecd2020ce0af2d1/pyjwt-2.13.0-py3-none-any.whl", hash = "sha256:66adcc2aff09b3f1bbd95fc1e1577df8ac8723c978552fd43304c8a290ac5728", size = 31274, upload-time = "2026-05-21T19:54:35.362Z" },+ { url = "https://files.pythonhosted.org/packages/50/ca/44de4e75f8aadc457f0634be3b542815078ded46dca30efb960edeecad6e/pyjwt-2.15.1-py3-none-any.whl", hash = "sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193", size = 33860, upload-time = "2026-09-28T18:40:41.429Z" },][package.optional-dependencies]@@ -2346,6 +2346,7 @@ dependencies = [{ name = "discord-py" },{ name = "fastapi" },{ name = "fastmcp" },+ { name = "httpcore" },{ name = "httpx" },{ name = "itsdangerous" },{ name = "markdown" },@@ -2381,6 +2382,7 @@ requires-dist = [{ name = "discord-py", specifier = ">=2.4,<3" },{ name = "fastapi", specifier = ">=0.115,<1" },{ name = "fastmcp", specifier = ">=3.2.0,<4" },+ { name = "httpcore", specifier = ">=1.0.9,<2" },{ name = "httpx", specifier = ">=0.28,<1" },{ name = "itsdangerous", specifier = ">=2.1,<3" },{ name = "markdown", specifier = ">=3,<4" },@@ -2453,11 +2455,11 @@ wheels = [[[package]]name = "urllib3"-version = "2.7.0"+version = "2.8.0"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" }+sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" },+ { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" },][[package]]diff --git a/deploy/local/standalone-docker-compose.yml b/deploy/local/standalone-docker-compose.ymlindex 5f144c6bc..ab9128059 100644--- a/deploy/local/standalone-docker-compose.yml+++ b/deploy/local/standalone-docker-compose.yml@@ -212,7 +212,16 @@ services:# supported release reads ID_SERVER_NAME.MATRIX_SERVER_NAME: localhostAGENT_REGISTRATION_TOKEN: ${AGENT_REGISTRATION_TOKEN}- JWT_SECRET_KEY: ${JWT_SECRET_KEY}+ SECRET_KEYS: ${SECRET_KEYS:?required, set it in .env (just init-env generates one)}+ # Legacy, optional: keeps what it signed and encrypted working until the+ # first boot has re-encrypted stored credentials under SECRET_KEYS.+ JWT_SECRET_KEY: ${JWT_SECRET_KEY:-}+ # Served over plain http on this machine by default, where a Secure+ # cookie would never be sent back. Set it to true behind https.+ GATEWAY_COOKIE_SECURE: ${GATEWAY_COOKIE_SECURE:-false}+ # The bundled Mattermost is on the compose network, a private address,+ # so it is always allowed; .env adds to it rather than replacing it.+ OUTBOUND_ALLOWED_PRIVATE_HOSTS: mattermost,${OUTBOUND_ALLOWED_PRIVATE_HOSTS:-}GATEWAY_ADMIN_EMAIL: ${GATEWAY_ADMIN_EMAIL}GATEWAY_ADMIN_PASSWORD: ${GATEWAY_ADMIN_PASSWORD}FRONTEND_BASE_URL: ${FRONTEND_BASE_URL}diff --git a/deploy/remote/helm/switch/templates/NOTES.txt b/deploy/remote/helm/switch/templates/NOTES.txtindex 8f60bd908..4dad7bf24 100644--- a/deploy/remote/helm/switch/templates/NOTES.txt+++ b/deploy/remote/helm/switch/templates/NOTES.txt@@ -127,3 +127,11 @@ Postgres holds everything: every room, every message, every account, and theMattermost database. Back it up. See BACKUP.md andsamples/volumesnapshot.example.yaml for the recommended approaches(CSI VolumeSnapshots, pg_dump / managed-DB backups, Velero).+{{- if and (eq .Values.postgresql.mode "managed") (not (include "switch.runtimePasswordSeparate" .)) }}++── WARNING: database runtime role ──────────────────────────────────────────────+The runtime role switch-core serves requests as ({{ include "switch.postgresUser" . }})+shares the Postgres superuser's password, so the serving container effectively+holds superuser credentials. Set secrets.dbRuntimePassword (or+postgresql.managed.runtimeExistingSecret) to give it a password of its own.+{{- end }}diff --git a/deploy/remote/helm/switch/templates/_helpers.tpl b/deploy/remote/helm/switch/templates/_helpers.tplindex 45d0b99a5..a0a1f4e7a 100644--- a/deploy/remote/helm/switch/templates/_helpers.tpl+++ b/deploy/remote/helm/switch/templates/_helpers.tpl@@ -48,11 +48,17 @@ rendered from this one source and cannot drift from the release's own.{{- if not .Values.postgresql.existingSecret }}POSTGRES_PASSWORD: {{ required "secrets.postgresPassword is required (unless postgresql.existingSecret is set)" .Values.secrets.postgresPassword | b64enc | quote }}{{- end }}+{{- if and (eq .Values.postgresql.mode "managed") .Values.secrets.dbRuntimePassword (not .Values.postgresql.managed.runtimeExistingSecret) }}+DB_RUNTIME_PASSWORD: {{ .Values.secrets.dbRuntimePassword | b64enc | quote }}+{{- end }}{{- if and .Values.postgresql.owner.username (not .Values.postgresql.owner.existingSecret) }}DB_OWNER_PASSWORD: {{ required "secrets.dbOwnerPassword is required when postgresql.owner.username is set (unless postgresql.owner.existingSecret is set)" .Values.secrets.dbOwnerPassword | b64enc | quote }}{{- end }}AGENT_REGISTRATION_TOKEN: {{ required "secrets.agentRegistrationToken is required" .Values.secrets.agentRegistrationToken | b64enc | quote }}-JWT_SECRET_KEY: {{ required "secrets.jwtSecretKey is required" .Values.secrets.jwtSecretKey | b64enc | quote }}+SECRET_KEYS: {{ required "secrets.secretKeys is required (\"<id>:<secret>\", see values.yaml)" .Values.secrets.secretKeys | b64enc | quote }}+{{- with .Values.secrets.jwtSecretKey }}+JWT_SECRET_KEY: {{ . | b64enc | quote }}+{{- end }}GATEWAY_ADMIN_EMAIL: {{ required "secrets.gatewayAdminEmail is required" .Values.secrets.gatewayAdminEmail | b64enc | quote }}GATEWAY_ADMIN_PASSWORD: {{ required "secrets.gatewayAdminPassword is required" .Values.secrets.gatewayAdminPassword | b64enc | quote }}{{- if .Values.mattermost.enabled }}@@ -179,6 +185,42 @@ external secret (e.g. one synced by external-secrets / sealed-secrets).{{- .Values.postgresql.existingSecretKey | default "POSTGRES_PASSWORD" -}}{{- end }}+{{/*+Where DB_USER's password comes from. In mode: managed the runtime role has a+password of its own when secrets.dbRuntimePassword or+postgresql.managed.runtimeExistingSecret is set, and shares the superuser's+otherwise. In mode: existing DB_USER's password is POSTGRES_PASSWORD, as+before.+*/}}+{{- define "switch.runtimePasswordSeparate" -}}+{{- if and .Values.secrets.existingSecret .Values.secrets.dbRuntimePassword -}}+{{- fail "secrets.dbRuntimePassword cannot be used with secrets.existingSecret: the chart renders no Secret to put it in. Store the password in a Secret and name it in postgresql.managed.runtimeExistingSecret (it may be the same Secret as secrets.existingSecret)." -}}+{{- end -}}+{{- if and (eq .Values.postgresql.mode "managed") (or .Values.postgresql.managed.runtimeExistingSecret .Values.secrets.dbRuntimePassword) -}}+true+{{- end -}}+{{- end }}++{{- define "switch.runtimeSecretName" -}}+{{- if not (include "switch.runtimePasswordSeparate" .) -}}+{{- include "switch.postgresSecretName" . -}}+{{- else if .Values.postgresql.managed.runtimeExistingSecret -}}+{{- .Values.postgresql.managed.runtimeExistingSecret -}}+{{- else -}}+{{- include "switch.secretName" . -}}+{{- end -}}+{{- end }}++{{- define "switch.runtimeSecretKey" -}}+{{- if not (include "switch.runtimePasswordSeparate" .) -}}+{{- include "switch.postgresSecretKey" . -}}+{{- else if .Values.postgresql.managed.runtimeExistingSecret -}}+{{- .Values.postgresql.managed.runtimeExistingSecretKey | default "DB_RUNTIME_PASSWORD" -}}+{{- else -}}+DB_RUNTIME_PASSWORD+{{- end -}}+{{- end }}+{{/*DB_OWNER_USER: the schema owner switch-core migrates and grants as.@@ -502,6 +544,11 @@ switch-core container env. Shared by the switch-core Deployment and thepre-upgrade migration Job so they always run against the same configuration(env.py builds a full SwitchConfig, so the migration Job needs every var too).Include with `nindent 12`.++Pass `omitOwnerCredentials: true` in the context for the serving container:+it gets no DB_OWNER_* and DB_MIGRATE_ON_BOOT=false, because its init container+has already migrated as the owner. Only the init container and the Job hold+the owner's password.*/}}{{- define "switch.coreEnv" -}}- name: DB_HOST@@ -513,12 +560,15 @@ Include with `nindent 12`.- name: DB_PASSWORDvalueFrom:secretKeyRef:- name: {{ include "switch.postgresSecretName" . }}- key: {{ include "switch.postgresSecretKey" . }}+ name: {{ include "switch.runtimeSecretName" . }}+ key: {{ include "switch.runtimeSecretKey" . }}- name: DB_NAMEvalue: {{ include "switch.postgresDatabase" . | quote }}{{- $ownerUser := include "switch.postgresOwnerUser" . }}-{{- if $ownerUser }}+{{- if .omitOwnerCredentials }}+- name: DB_MIGRATE_ON_BOOT+ value: "false"+{{- else if $ownerUser }}- name: DB_OWNER_USERvalue: {{ $ownerUser | quote }}- name: DB_OWNER_PASSWORD@@ -575,11 +625,17 @@ this one. Drop it once the oldest supported image reads ID_SERVER_NAME. */}}secretKeyRef:name: {{ include "switch.secretName" . }}key: AGENT_REGISTRATION_TOKEN+- name: SECRET_KEYS+ valueFrom:+ secretKeyRef:+ name: {{ include "switch.secretName" . }}+ key: SECRET_KEYS- name: JWT_SECRET_KEYvalueFrom:secretKeyRef:name: {{ include "switch.secretName" . }}key: JWT_SECRET_KEY+ optional: true- name: GATEWAY_ADMIN_EMAILvalueFrom:secretKeyRef:@@ -631,6 +687,14 @@ this one. Drop it once the oldest supported image reads ID_SERVER_NAME. */}}value: {{ .Values.switchCore.signup.maxWorkspacesPerUser | quote }}- name: GATEWAY_TENANT_CHOICE_ENABLEDvalue: {{ .Values.switchCore.tenantChoiceEnabled | quote }}+{{- $outboundHosts := .Values.switchCore.outbound.allowedPrivateHosts }}+{{- if .Values.mattermost.enabled }}+{{- $outboundHosts = append $outboundHosts (include "switch.mattermostHost" .) }}+{{- end }}+{{- if $outboundHosts }}+- name: OUTBOUND_ALLOWED_PRIVATE_HOSTS+ value: {{ join "," $outboundHosts | quote }}+{{- end }}{{- with .Values.switchCore.smtp }}{{- if .enabled }}{{- if not $.Values.switchCore.frontendBaseUrl }}diff --git a/deploy/remote/helm/switch/templates/postgresql/configmap-init.yaml b/deploy/remote/helm/switch/templates/postgresql/configmap-init.yamlindex eeb6e00b1..1c7f83d56 100644--- a/deploy/remote/helm/switch/templates/postgresql/configmap-init.yaml+++ b/deploy/remote/helm/switch/templates/postgresql/configmap-init.yaml@@ -23,10 +23,9 @@ data:# itself at boot, from the owner connection, immediately after that# migration (core/switch_core/db/runtime_role.py::grant_runtime_role).#- # The role's password is deliberately the bootstrapped superuser's own- # ($POSTGRES_PASSWORD, already in this container's environment): see- # postgresql.managed.runtimeUsername in values.yaml for why that is not a- # second secret to manage.+ # The role's password is $RUNTIME_ROLE_PASSWORD, which is the superuser's+ # own unless a separate one is configured: see+ # postgresql.managed.runtimeUsername in values.yaml.## No `set` line, deliberately. A ConfigMap volume mounts its files without# the executable bit, so the Postgres entrypoint *sources* this rather than@@ -42,7 +41,7 @@ data:#!/bin/bashpsql -v ON_ERROR_STOP=1 -U {{ include "switch.postgresSuperUser" . }} -d postgres \-v role="{{ include "switch.postgresUser" . }}" \- -v pw="$POSTGRES_PASSWORD" <<'SQL'+ -v pw="$RUNTIME_ROLE_PASSWORD" <<'SQL'SELECT format('CREATE ROLE %I LOGIN PASSWORD %L NOSUPERUSER NOCREATEDB NOCREATEROLE NOBYPASSRLS', :'role', :'pw')WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = :'role')\gexecdiff --git a/deploy/remote/helm/switch/templates/postgresql/statefulset.yaml b/deploy/remote/helm/switch/templates/postgresql/statefulset.yamlindex 340b1986b..f66e4ed30 100644--- a/deploy/remote/helm/switch/templates/postgresql/statefulset.yaml+++ b/deploy/remote/helm/switch/templates/postgresql/statefulset.yaml@@ -43,6 +43,11 @@ spec:secretKeyRef:name: {{ include "switch.postgresSecretName" . }}key: {{ include "switch.postgresSecretKey" . }}+ - name: RUNTIME_ROLE_PASSWORD+ valueFrom:+ secretKeyRef:+ name: {{ include "switch.runtimeSecretName" . }}+ key: {{ include "switch.runtimeSecretKey" . }}- name: POSTGRES_DBvalue: {{ .Values.postgresql.database }}- name: PGDATAdiff --git a/deploy/remote/helm/switch/templates/switch-core/create-runtime-role-job.yaml b/deploy/remote/helm/switch/templates/switch-core/create-runtime-role-job.yamlindex 1e6ffd66a..491f76245 100644--- a/deploy/remote/helm/switch/templates/switch-core/create-runtime-role-job.yaml+++ b/deploy/remote/helm/switch/templates/switch-core/create-runtime-role-job.yaml@@ -1,24 +1,15 @@{{- if eq .Values.postgresql.mode "managed" }}{{- $secretOverride := "" }}{{/*-The pre-upgrade copy of the Secret, on exactly the condition that makes it-exist. A hook runs before helm applies the release's ordinary resources, so a-chart-managed Secret read here is the *previous* release's — which is why-migrate-prereqs.yaml renders a copy at a lower hook weight, and why this Job-reads that copy when there is one.--`switchCore.migrations.preUpgradeJob` has to be part of the condition rather-than only `secrets.existingSecret`: the copy is rendered by that same-template, so turning the migration Job off (to run migrations out of band)-also removes the copy, and a Job naming a Secret nobody creates does not fail-somewhere later — its pod never starts, the hook never succeeds, and every-upgrade of the release is blocked. Falling back to the release's own Secret is-correct there: in managed mode the target is always the in-cluster-StatefulSet, whose superuser password was fixed when its volume was-bootstrapped and which no later values change can move, so the previous-release's copy of it is the one that still authenticates.+A hook runs before helm applies the release's ordinary resources, so a+chart-managed Secret read here would be the *previous* release's: a runtime+password set or changed in this upgrade would be missing from it, the pod+would never start, and every upgrade of the release would be blocked.+migrate-prereqs.yaml renders a copy of this release's Secret at a lower hook+weight whenever this Job exists, and this Job reads that copy. An existing+Secret is already in place before the hook runs and is read directly.*/}}-{{- if and .Values.switchCore.migrations.preUpgradeJob (not .Values.secrets.existingSecret) }}+{{- if not .Values.secrets.existingSecret }}{{- $secretOverride = printf "%s-migrate" (include "switch.secretName" .) }}{{- end }}{{- $ctx := merge (dict "secretNameOverride" $secretOverride) . }}@@ -74,7 +65,7 @@ spec:set -eupsql -v ON_ERROR_STOP=1 --host "$PGHOST" --port "$PGPORT" \--username {{ include "switch.postgresSuperUser" . }} --dbname postgres \- -v role="$RUNTIME_ROLE" -v pw="$PGPASSWORD" <<'SQL'+ -v role="$RUNTIME_ROLE" -v pw="$RUNTIME_ROLE_PASSWORD" <<'SQL'SELECT format('CREATE ROLE %I LOGIN PASSWORD %L NOSUPERUSER NOCREATEDB NOCREATEROLE NOBYPASSRLS', :'role', :'pw')WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = :'role')\gexec@@ -87,14 +78,16 @@ spec:value: {{ include "switch.postgresPort" . | quote }}- name: RUNTIME_ROLEvalue: {{ include "switch.postgresUser" . | quote }}- # The same secret PGPASSWORD authenticates this connection as the- # superuser AND the value ALTER ROLE sets the runtime role's- # password to — see the values.yaml comment on- # postgresql.managed.runtimeUsername for why that is one password,- # not two.- name: PGPASSWORDvalueFrom:secretKeyRef:name: {{ include "switch.postgresSecretName" $ctx }}key: {{ include "switch.postgresSecretKey" $ctx }}+ # The superuser's own unless a separate runtime password is+ # configured; see postgresql.managed.runtimeUsername in values.yaml.+ - name: RUNTIME_ROLE_PASSWORD+ valueFrom:+ secretKeyRef:+ name: {{ include "switch.runtimeSecretName" $ctx }}+ key: {{ include "switch.runtimeSecretKey" $ctx }}{{- end }}diff --git a/deploy/remote/helm/switch/templates/switch-core/deployment.yaml b/deploy/remote/helm/switch/templates/switch-core/deployment.yamlindex e00cb4fce..8b1728bd0 100644--- a/deploy/remote/helm/switch/templates/switch-core/deployment.yaml+++ b/deploy/remote/helm/switch/templates/switch-core/deployment.yaml@@ -33,6 +33,22 @@ spec:{{- end }}initContainers:{{- include "switch.waitFor" (dict "name" "postgres" "host" (include "switch.postgresHost" .) "port" (include "switch.postgresPort" .)) | nindent 8 }}+ # Migrates and re-issues grants as the schema owner, so the serving+ # container below never holds the owner's password. Covers a fresh+ # install, where the pre-upgrade Job does not run; on an upgrade it+ # finds nothing pending.+ - name: migrate+ image: {{ include "switch.image" (dict "global" .Values.global "image" .Values.switchCore.image) }}+ imagePullPolicy: {{ .Values.switchCore.imagePullPolicy }}+ command: ["switch-migrate"]+ env:+ {{- include "switch.coreEnv" . | nindent 12 }}+ resources:+ {{- toYaml .Values.switchCore.resources | nindent 12 }}+ {{- if include "switch.dbCaBundleConfigMap" . }}+ volumeMounts:+ {{- include "switch.dbCaBundleVolumeMount" . | nindent 12 }}+ {{- end }}containers:- name: switch-coreimage: {{ include "switch.image" (dict "global" .Values.global "image" .Values.switchCore.image) }}@@ -51,7 +67,7 @@ spec:protocol: TCP{{- end }}env:- {{- include "switch.coreEnv" . | nindent 12 }}+ {{- include "switch.coreEnv" (merge (dict "omitOwnerCredentials" true) .) | nindent 12 }}# Readiness checks the database; liveness deliberately does not.# There is one replica, so a failing readiness probe empties the# Service rather than shifting traffic — which is right while thediff --git a/deploy/remote/helm/switch/templates/switch-core/migrate-prereqs.yaml b/deploy/remote/helm/switch/templates/switch-core/migrate-prereqs.yamlindex 1fc55ea29..87e5e6550 100644--- a/deploy/remote/helm/switch/templates/switch-core/migrate-prereqs.yaml+++ b/deploy/remote/helm/switch/templates/switch-core/migrate-prereqs.yaml@@ -1,4 +1,6 @@-{{- if .Values.switchCore.migrations.preUpgradeJob }}+{{- $migrateJob := .Values.switchCore.migrations.preUpgradeJob }}+{{- $runtimeRoleJob := eq .Values.postgresql.mode "managed" }}+{{- if or $migrateJob $runtimeRoleJob }}# The migration Job runs as a pre-upgrade hook, so it starts before helm applies# the release's ordinary resources. Reading the release's own Secret and CA# ConfigMap therefore gets the *previous* release's values — which makes an@@ -13,6 +15,10 @@# deleted during the apply that follows, taking the running release's# credentials with it.#+# The create-runtime-role Job (mode: managed) is a pre-upgrade hook too and+# reads the same Secret copy, so the copy is rendered for it even when the+# migration Job is off.+## Not needed when the values come from outside the chart — an existing Secret or# ConfigMap is already there before the hook runs.{{- if not .Values.secrets.existingSecret }}@@ -30,7 +36,7 @@ type: Opaquedata:{{- include "switch.secretData" . | nindent 2 }}{{- end }}-{{- if and .Values.postgresql.caBundle.contents (not .Values.postgresql.caBundle.existingConfigMap) }}+{{- if and $migrateJob .Values.postgresql.caBundle.contents (not .Values.postgresql.caBundle.existingConfigMap) }}---apiVersion: v1kind: ConfigMapdiff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yamlindex f54661d03..3ab0aa1f2 100644--- a/deploy/remote/helm/switch/values.yaml+++ b/deploy/remote/helm/switch/values.yaml@@ -82,8 +82,9 @@ ingress:# POSTGRES_PASSWORD (unless postgresql.existingSecret is set),# DB_OWNER_PASSWORD (only if postgresql.owner.username is set, and unless# postgresql.owner.existingSecret is set),-# AGENT_REGISTRATION_TOKEN, JWT_SECRET_KEY, GATEWAY_ADMIN_EMAIL,+# AGENT_REGISTRATION_TOKEN, SECRET_KEYS, GATEWAY_ADMIN_EMAIL,# GATEWAY_ADMIN_PASSWORD,+# JWT_SECRET_KEY (optional, legacy — see secrets.jwtSecretKey),# MATTERMOST_ADMIN_PASSWORD + MATTERMOST_USER_PASSWORD (if mattermost.enabled),# GATEWAY_OIDC_CLIENT_SECRET (if switchCore.oidc.enabled).secrets:@@ -94,7 +95,21 @@ secrets:# Password for postgresql.owner.username. Required when that is set, unless# postgresql.owner.existingSecret names a Secret that already carries it.dbOwnerPassword: ""+ # Password for the managed-mode runtime role (postgresql.managed+ # .runtimeUsername). Optional; see that setting for why to set it. Not+ # usable with existingSecret: use postgresql.managed.runtimeExistingSecret.+ dbRuntimePassword: ""agentRegistrationToken: ""+ # The server's master keys, "<id>:<secret>" comma-separated, current first;+ # each secret at least 32 characters. Every signing and encryption key is+ # derived from these. To rotate, put a new entry first and keep the old one+ # until a boot has re-encrypted stored values (docs/old/key-rotation.md).+ # Generate one with: echo "$(date +%Y%m):$(openssl rand -hex 32)"+ secretKeys: ""+ # Legacy: the single secret used before secretKeys. Keep it set through the+ # first upgrade so existing sessions, Mattermost buttons and stored+ # credentials keep working; the first boot re-encrypts stored credentials+ # under secretKeys. Remove it afterwards.jwtSecretKey: ""gatewayAdminEmail: ""gatewayAdminPassword: ""@@ -246,6 +261,13 @@ switchCore:# lists them, rather than a 403. The gateway UI does not need it; turn it on# once every API client authenticating against this deployment handles it.tenantChoiceEnabled: false+ # Private hosts switch-core may reach at a URL a tenant or agent supplied —+ # a Mattermost server, an OpenCode server, an agent icon. Hostnames or CIDRs.+ # Anything else that is not a public address is refused, and link-local and+ # cloud metadata addresses are refused even when listed. The bundled+ # Mattermost (mattermost.enabled) is added automatically.+ outbound:+ allowedPrivateHosts: []# Invitation e-mails. When enabled, an invitation addressed to an e-mail is# sent there through this SMTP relay (SES SMTP, Postmark, a company relay —# anything that speaks SMTP). Off, the invitation is still created and the@@ -424,9 +446,10 @@ switchCore:replicaCount: 1# Run DB migrations (alembic upgrade head) as a pre-upgrade hook Job, before# the new pods roll, so a failed migration blocks the upgrade instead of- # crash-looping the new pods. switch-core also migrates on startup (which- # covers fresh installs, where pre-upgrade hooks don't run), so the Job is- # idempotent. Disable only if you run migrations out-of-band.+ # crash-looping the new pods. The switch-core pod also migrates in an init+ # container before the server starts (which covers fresh installs, where+ # pre-upgrade hooks don't run), so the Job is idempotent. Disable only if you+ # run migrations out-of-band.migrations:preUpgradeJob: trueresources:@@ -611,10 +634,12 @@ postgresql:# distinct from DB_USER above (or postgresql.external.username for# mode: existing), which name the RUNTIME role every request actually# authenticates as and which the row-level-security policies apply to.- # switch-core uses the owner connection for exactly two things at boot, and- # never to serve a request: applying Alembic migrations, and re-issuing the- # runtime role's grants immediately afterwards, so a table a migration just- # added is usable by the role that is about to need it.+ # switch-core uses the owner connection for exactly two things, and never to+ # serve a request: applying Alembic migrations, and re-issuing the runtime+ # role's grants immediately afterwards, so a table a migration just added is+ # usable by the role that is about to need it. Both run in the migration Job+ # and the pod's init container; the serving container is not given the+ # owner's password at all.## mode: managed defaults this to the bootstrapped "postgres" superuser (the# same account POSTGRES_USER creates on the StatefulSet below) whenever@@ -720,17 +745,23 @@ postgresql:# templates/postgresql/configmap-init.yaml and, for an upgrade of a# deployment that predates it, by the create-runtime-role pre-upgrade hook.#- # Its password is deliberately the bootstrapped superuser's own —- # secrets.postgresPassword, or whatever postgresql.existingSecret resolves- # to — rather than a password of its own. That adds no new required value,- # keeps working unmodified with postgresql.existingSecret, and exposes- # nothing new: this pod already holds that password as DB_OWNER_PASSWORD.- # The point of splitting DB_USER from the superuser is that the- # row-level-security policies apply to the connection serving requests,- # not to compartmentalise passwords between two accounts that already- # trust each other — so change the username here if you want, but there is- # no separate password field to set alongside it.+ # Its password is secrets.dbRuntimePassword, or the key named by+ # runtimeExistingSecret below. Set one of them: the serving container is+ # not given the superuser's password, and a runtime role sharing it hands+ # that password back. Left unset, the role falls back to the superuser's+ # own password (secrets.postgresPassword / postgresql.existingSecret), as+ # releases before this setting did, and the install notes warn about it.+ #+ # With secrets.existingSecret, secrets.dbRuntimePassword is refused (the+ # chart renders no Secret to hold it): set runtimeExistingSecret instead,+ # which may name that same Secret.+ #+ # The create-runtime-role pre-upgrade hook re-applies the password on+ # every upgrade, so setting it on an existing deployment takes effect in+ # that same upgrade.runtimeUsername: switch_app+ runtimeExistingSecret: ""+ runtimeExistingSecretKey: DB_RUNTIME_PASSWORD# Postgres server parameters, passed as `-c name=value`. Each client# connection is a backend process costing several MB of non-reclaimablediff --git a/docs/old/LOCAL_DEVELOPMENT.md b/docs/old/LOCAL_DEVELOPMENT.mdindex 20225b911..feba83cad 100644--- a/docs/old/LOCAL_DEVELOPMENT.md+++ b/docs/old/LOCAL_DEVELOPMENT.md@@ -26,9 +26,10 @@ just gateway-install # install gateway frontend deps (first time only)`just init-env` copies `.env.example` to `.env` and fills every secret fieldthat ships blank — `DB_PASSWORD`, `DB_OWNER_PASSWORD`,-`AGENT_REGISTRATION_TOKEN`, `JWT_SECRET_KEY`, `GATEWAY_ADMIN_PASSWORD`,+`AGENT_REGISTRATION_TOKEN`, `GATEWAY_ADMIN_PASSWORD`,`MATTERMOST_ADMIN_PASSWORD`, `MATTERMOST_USER_PASSWORD` — with a freshly-generated `openssl rand -hex 24` value, then prints the gateway admin login+generated `openssl rand -hex 24` value, sets `SECRET_KEYS` to one generated+key (`local:<64 hex characters>`), then prints the gateway admin loginit just set. The fields ship blank on purpose: it means no defaultcredential (the old `admin`/`admin`) can ever reach a running stack byaccident. The recipe refuses to touch an existing `.env`, so re-running it@@ -37,6 +38,12 @@ never rotates secrets out from under a stack that's already up — delete`.env` automatically for every recipe below (`set dotenv-load := true` inthe justfile), so nothing else needs to source it.+An `.env` from before `SECRET_KEYS` existed makes `just run` fail at startup+naming the missing setting. Add `SECRET_KEYS=local:$(openssl rand -hex 32)`+(the generated value, not the command) and leave `JWT_SECRET_KEY` as it is:+the first boot re-encrypts what it encrypted, and it keeps your current login+valid. [key-rotation.md](key-rotation.md) explains both.+### Two database roles, not one`.env` carries two sets of Postgres credentials, because row-level security@@ -87,6 +94,13 @@ start the gateway frontend — you run both of those yourself, in their ownterminals, so each gets hot-reload while you work. `just down` stops thestack; `just reset` also wipes its volumes (Postgres data included).+switch-core refuses to connect to a private address at a URL a bridge or+connector config names, unless `OUTBOUND_ALLOWED_PRIVATE_HOSTS` lists it. The+`.env.example` default, `localhost`, covers the local Mattermost and an OpenCode+server on your machine. An `.env` from before that setting existed lacks it, and+the Mattermost bridge then refuses to start with a message naming the variable:+add the line from `.env.example`.+`just migrate` runs `alembic upgrade head` against the Postgres started by`just up`. Run it once after the stack is up and again after pulling anychange that adds a migration — `just run` does not apply migrations itselfdiff --git a/docs/old/key-rotation.md b/docs/old/key-rotation.mdnew file mode 100644index 000000000..8d57f8526--- /dev/null+++ b/docs/old/key-rotation.md@@ -0,0 +1,92 @@+# Server keys and rotation++switch-core signs and encrypts with keys derived from `SECRET_KEYS`. This page+covers what the keys protect, how to move a deployment onto them from+`JWT_SECRET_KEY`, and how to rotate them. The code is `core/switch_core/keys.py`+and `core/switch_core/db/key_rotation.py`.++## What the keys protect++`SECRET_KEYS` holds master keys, `<id>:<secret>` comma-separated, current+first. Each secret is at least 32 characters. Nothing uses a master key+directly: each purpose gets its own key, derived with HKDF under a label naming+the purpose, so a key that leaks from one use does not open another.++| Purpose | Kind | Lifetime | After a rotation |+|---|---|---|---|+| Gateway session (`switch_auth` cookie) | signed JWT, `kid` header | 24 hours | verified with the key its `kid` names |+| OIDC login cookie | signed cookie | one login round trip (10 minutes) | current key only; a login in progress at the moment of rotation starts again |+| Messaging install state | signed token | one install round trip | verified with any key in `SECRET_KEYS` |+| Mattermost card buttons | signed context in posted messages | as long as the post | verified with any key in `SECRET_KEYS` |+| Stored credentials: API keys, hosted-install bot tokens, bridge and connector configs | encrypted, value names its key | until changed | re-encrypted under the current key at boot |++The first key is used for everything new. Older keys only verify and decrypt.++## Moving from `JWT_SECRET_KEY`++Before `SECRET_KEYS`, one secret did all of the above. It is now legacy: while+`JWT_SECRET_KEY` is set, it still decrypts values and verifies signatures made+before the upgrade, exactly as they were made.++1. Generate a key and add it as `SECRET_KEYS`, keeping `JWT_SECRET_KEY` set:++ ```bash+ echo "$(date +%Y%m):$(openssl rand -hex 32)"+ ```++ In the Helm chart this is `secrets.secretKeys` (or a `SECRET_KEYS` key in+ `secrets.existingSecret`). Store it in your secrets manager. Every+ environment gets its own.+2. Deploy. On boot, switch-core re-encrypts every stored credential under the+ new key and logs how many it rewrote. Sessions signed before the upgrade+ stay valid until they expire, and buttons on existing Mattermost cards keep+ working. The Helm chart replaces switch-core rather than rolling it, so+ two versions never serve at once. Where they do (several replicas updated+ one by one), a replica still on the previous version cannot verify a+ session the new version signed, so someone who signs in mid-rollout may be+ asked to sign in once more.++ **This step is one-way.** Once the new version has booted, stored+ credentials are encrypted in a format the previous version cannot read, so+ rolling switch-core back would leave it unable to open bridge tokens and+ other stored secrets. The only way back is to restore a database backup+ taken before the upgrade, losing anything written since. Take that backup+ before deploying.+3. When you are ready, remove `JWT_SECRET_KEY` and deploy again. Sessions from+ before step 2 end (people sign in again) and buttons on Mattermost cards+ posted before step 2 stop working; stored credentials are unaffected,+ because step 2 re-encrypted them.++A boot that finds a stored value no configured key opens fails rather than+continuing. That is a key removed too early: put it back.++## Rotating++Rotation takes two deploys, so that where replicas are updated one by one, no+replica is handed a session signed with a key it does not have yet. With the+Helm chart, which replaces switch-core in one step, step 1 is still what keeps+the old key available for decrypting and verifying.++1. Generate a new key and add it **after** the current one:+ `SECRET_KEYS=202610:<old>,202611:<new>`. Deploy. Every replica can now+ verify and decrypt with the new key; nothing uses it yet.+2. Move the new key **first**: `SECRET_KEYS=202611:<new>,202610:<old>`.+ Deploy. New sessions, signatures and encrypted values use the new key, and+ the boot re-encrypts stored credentials under it.+3. Wait at least 24 hours, so sessions signed with the old key have expired.+4. Remove the old key and deploy. Buttons on Mattermost cards posted before+ step 2 stop working; nothing else is affected.++Rotate on a schedule, and at once if a key may have leaked. For a suspected+leak, skip step 1 and the wait: deploy `<new>,<old>`, check the boot log+reports the re-encryption, then deploy `<new>` alone straight away. Stored+credentials need the old key once to be re-encrypted; until the second deploy,+sessions signed with the old key still verify, so keep that window short.+Removing the old key ends every session and stops every Mattermost button+posted before, which is the point.++## Ids++A key id is 1–32 letters, digits, `-` or `_`. It is stored in every encrypted+value and every session token, so it must not change while the key is in use.+A date (`202611`) makes the age of a key obvious.diff --git a/docs/old/observability.md b/docs/old/observability.mdindex 980dc08d0..019328adc 100644--- a/docs/old/observability.md+++ b/docs/old/observability.md@@ -48,7 +48,7 @@ python scripts/otlp_sink.pyDB_HOST=localhost DB_PORT=55432 DB_USER=postgres DB_PASSWORD=check DB_NAME=switch \DB_REQUIRE_RESTRICTED_ROLE=false \MATRIX_SERVER_NAME=switch.local \-AGENT_REGISTRATION_TOKEN=check JWT_SECRET_KEY=check-jwt-secret-key-long-enough \+AGENT_REGISTRATION_TOKEN=check SECRET_KEYS=check:check-secret-key-long-enough-for-32 \[email protected] GATEWAY_ADMIN_PASSWORD=check \SERVER_PORT=8099 LOG_FORMAT=json ENVIRONMENT=local \OTLP_ENDPOINT=http://localhost:4318 \diff --git a/gateway/src/pages/workspace/CreateInvitationDialog.tsx b/gateway/src/pages/workspace/CreateInvitationDialog.tsxindex 8ee08a0f4..31e1ac5c2 100644--- a/gateway/src/pages/workspace/CreateInvitationDialog.tsx+++ b/gateway/src/pages/workspace/CreateInvitationDialog.tsx@@ -18,6 +18,9 @@ import { useCallback, useState } from "react";import { type TenantRole, createInvitation } from "../../data/api";import { type DeliveryNotice, deliveryNotice, inviteUrl } from "../../data/sessionState";+/** Mirrors `MAX_INVITATION_USES` in the server's invitation schema. */+const MAX_INVITATION_USES = 100;+interface Props {open: boolean;tenantId: string;@@ -90,7 +93,7 @@ export default function CreateInvitationDialog({const roles: TenantRole[] = isOwner ? ["member", "admin", "owner"] : ["member", "admin"];const valid =Number.isInteger(Number(hours)) && Number(hours) > 0 && Number(hours) <= 8760 &&- Number.isInteger(Number(uses)) && Number(uses) > 0;+ Number.isInteger(Number(uses)) && Number(uses) > 0 && Number(uses) <= MAX_INVITATION_USES;return (<Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>@@ -157,6 +160,7 @@ export default function CreateInvitationDialog({type="number"value={uses}onChange={(e) => setUses(e.target.value)}+ helperText={`Up to ${MAX_INVITATION_USES}`}fullWidth/></Stack>diff --git a/justfile b/justfileindex 2e528cd61..c4d43ac3d 100644--- a/justfile+++ b/justfile@@ -27,11 +27,12 @@ init-env:ficp .env.example .envfor key in DB_PASSWORD DB_OWNER_PASSWORD \- AGENT_REGISTRATION_TOKEN JWT_SECRET_KEY GATEWAY_ADMIN_PASSWORD \+ AGENT_REGISTRATION_TOKEN GATEWAY_ADMIN_PASSWORD \MATTERMOST_ADMIN_PASSWORD MATTERMOST_USER_PASSWORD; dosecret="$(openssl rand -hex 24)"sed -i.bak "s|^${key}=.*|${key}=${secret}|" .envdone+ sed -i.bak "s|^SECRET_KEYS=.*|SECRET_KEYS=local:$(openssl rand -hex 32)|" .envrm -f .env.bakecho "✅ Wrote .env with freshly generated secrets."echo " Gateway admin login: $(grep '^GATEWAY_ADMIN_EMAIL=' .env | cut -d= -f2-) / $(grep '^GATEWAY_ADMIN_PASSWORD=' .env | cut -d= -f2-)"@@ -71,7 +72,7 @@ reset:# while keeping the repo root as the working directory. Tool configs are passed explicitly since the repo root no longer# holds pyproject.toml / alembic.ini.run:- uv run --project core python -m switch_core.main+ GATEWAY_COOKIE_SECURE="${GATEWAY_COOKIE_SECURE:-false}" uv run --project core python -m switch_core.main# ── Run switch-core as a stand-in for Switch Cloud ────────────────────────────# For testing Switch Console against this checkout instead of whatever a shared@@ -84,7 +85,7 @@ local-cloud:GATEWAY_SMTP_HOST=127.0.0.1 GATEWAY_SMTP_PORT=1025 GATEWAY_SMTP_TLS=none \GATEWAY_SMTP_USERNAME= GATEWAY_SMTP_PASSWORD= \GATEWAY_SMTP_FROM="Switch <[email protected]>" \- FRONTEND_BASE_URL=http://localhost:8000 \+ FRONTEND_BASE_URL=http://localhost:8000 GATEWAY_COOKIE_SECURE=false \uv run --project core python -m switch_core.main# Run Switch Console with "Switch Cloud" pointing at `just local-cloud`, in