From 5e8ad95c00ac820f1e878efedaa4c3aaf92da991 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 08:00:11 +0000 Subject: [PATCH 01/26] fix(security): Command Injection in resolveExecFileSpawn via Insuffic... --- .../packages/shared/src/windows-spawn.test.ts | 51 ++++++++++++++++++- console/packages/shared/src/windows-spawn.ts | 32 ++++++++++-- 2 files changed, 76 insertions(+), 7 deletions(-) diff --git a/console/packages/shared/src/windows-spawn.test.ts b/console/packages/shared/src/windows-spawn.test.ts index bc84764bcb..8281bc90a4 100644 --- a/console/packages/shared/src/windows-spawn.test.ts +++ b/console/packages/shared/src/windows-spawn.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest'; import { CmdExeLineBreakError, + CmdExePercentExpansionError, getWindowsEnvValue, escapeCmdExeArgument, escapeCmdExeCommand, @@ -34,18 +35,27 @@ describe('escapeCmdExeCommand', () => { expect(escapeCmdExeCommand('C:\\Program Files (x86)\\npm.cmd')).toBe( 'C:\\Program^ Files^ ^(x86^)\\npm.cmd' ); + expect(escapeCmdExeCommand('C:\\dir\twith=delim\\npm.cmd')).toBe( + 'C:\\dir^\twith^=delim\\npm.cmd' + ); }); it('refuses a program path with a line break, which no escaping neutralises', () => { for (const command of ['C:\\app\nname.cmd', 'C:\\app\rname.cmd']) expect(() => escapeCmdExeCommand(command)).toThrow(CmdExeLineBreakError); }); + + it('refuses a program path with percent expansion', () => { + for (const command of ['C:\\%USERNAME%\\npm.cmd', 'C:\\%1\\npm.cmd']) + expect(() => escapeCmdExeCommand(command)).toThrow(CmdExePercentExpansionError); + }); }); describe('escapeCmdExeArgument', () => { it('quotes, then caret-escapes twice for the batch file’s own pass', () => { expect(escapeCmdExeArgument('a&b')).toBe('^^^"a^^^&b^^^"'); expect(escapeCmdExeArgument('100%')).toBe('^^^"100^^^%^^^"'); + expect(escapeCmdExeArgument('a\tb=c')).toBe('^^^"a^^^\tb^^^=c^^^"'); }); it('refuses an argument with a line break, which cmd.exe reads as a new command', () => { @@ -53,8 +63,26 @@ describe('escapeCmdExeArgument', () => { expect(() => escapeCmdExeArgument(argument)).toThrow(CmdExeLineBreakError); }); - it('escapes an embedded quote and the backslashes before it for the C runtime', () => { - expect(escapeCmdExeArgument('say "hi"')).toBe('^^^"say^^^ \\^^^"hi\\^^^"^^^"'); + it('refuses an argument with percent variable or parameter expansion', () => { + for (const argument of [ + '%FOO%', + '"%FOO%"', + '%PATH%', + '%CMDCMDLINE%', + '%COMSPEC% & calc.exe & %', + '%PATH:~0,5%', + '%PATH:a=b%', + '%1', + '%*', + '%~dp0', + ]) + expect(() => escapeCmdExeArgument(argument)).toThrow(CmdExePercentExpansionError); + }); + + it('escapes an embedded quote and the backslashes before it for the C runtime and cmd.exe', () => { + expect(escapeCmdExeArgument('say "hi"')).toBe('^^^"say^^^ ^^^"^^^"hi^^^"^^^"^^^"'); + expect(escapeCmdExeArgument('say \\"hi\\"')).toBe('^^^"say^^^ \\\\^^^"^^^"hi\\\\^^^"^^^"^^^"'); + expect(escapeCmdExeArgument('test"&calc.exe')).toBe('^^^"test^^^"^^^"^^^&calc.exe^^^"'); expect(escapeCmdExeArgument('C:\\dir\\')).toBe('^^^"C:\\dir\\\\^^^"'); }); }); @@ -165,6 +193,25 @@ describe('resolveExecFileSpawn', () => { ).toThrow(CmdExeLineBreakError); }); + it('refuses to build a batch command line that could trigger percent expansion', () => { + for (const args of [ + ['%PATH%'], + ['%FOO:~0,5%'], + ['run', '%COMSPEC% & calc.exe & %'], + ['100%', '200%'], + ]) { + expect(() => + resolveExecFileSpawn({ + command: 'npm', + args, + platform: 'win32', + env: WINDOWS_ENV, + fileExists: existsIn(['C:\\Program Files\\nodejs\\npm.cmd']), + }) + ).toThrow(CmdExePercentExpansionError); + } + }); + it('passes a line break through untouched where no cmd.exe is involved', () => { expect( resolveExecFileSpawn({ diff --git a/console/packages/shared/src/windows-spawn.ts b/console/packages/shared/src/windows-spawn.ts index 0ff1919d2e..04fd55a30a 100644 --- a/console/packages/shared/src/windows-spawn.ts +++ b/console/packages/shared/src/windows-spawn.ts @@ -59,7 +59,7 @@ export function getWindowsPathExts( } /** What cmd.exe treats specially on a command line. */ -const CMD_EXE_META = /([()\][%!^"`<>&|;, *?])/g; +const CMD_EXE_META = /([()\][%!^"`<>&|;, *?\t=])/g; /** * cmd.exe ends a command at a line break, and no escaping, carets or quotes, @@ -67,6 +67,13 @@ const CMD_EXE_META = /([()\][%!^"`<>&|;, *?])/g; */ const LINE_BREAK = /[\r\n]/; +/** + * cmd.exe expands `%VAR%` (including `%VAR:~start,length%` and `%VAR:old=new%`) + * and batch parameters (`%0`–`%9`, `%*`, `%~…`) before processing carets or + * quotes, so caret escaping cannot suppress percent expansion. + */ +const PERCENT_EXPANSION = /%(?:.*%|[^ ])/; + /** Thrown for a value that cannot be put on a cmd.exe command line safely. */ export class CmdExeLineBreakError extends Error { constructor(what: string) { @@ -77,22 +84,34 @@ export class CmdExeLineBreakError extends Error { } } +/** Thrown when a value could trigger cmd.exe percent variable or parameter expansion. */ +export class CmdExePercentExpansionError extends Error { + constructor(what: string) { + super( + `Refusing to run a Windows batch file with percent expansion in its ${what}: cmd.exe expands environment variables before escaping.` + ); + this.name = 'CmdExePercentExpansionError'; + } +} + /** A program path for a cmd.exe command line: each metacharacter caret-escaped. */ export function escapeCmdExeCommand(command: string): string { if (LINE_BREAK.test(command)) throw new CmdExeLineBreakError('program path'); + if (PERCENT_EXPANSION.test(command)) throw new CmdExePercentExpansionError('program path'); return command.replace(CMD_EXE_META, '^$1'); } /** * One argument for a cmd.exe command line that runs a batch file: quoted for * the C runtime parser of the program the batch file starts (backslashes - * before a quote doubled, the quote escaped), then caret-escaped for cmd.exe — - * twice, since the batch file's `%*` is parsed by cmd.exe a second time. This - * is cross-spawn's algorithm, after https://qntm.org/cmd. + * before a quote doubled, embedded quotes doubled as `""` so cmd.exe's quote + * state stays balanced), then caret-escaped for cmd.exe — twice, since the + * batch file's `%*` is parsed by cmd.exe a second time. */ export function escapeCmdExeArgument(argument: string): string { if (LINE_BREAK.test(argument)) throw new CmdExeLineBreakError('arguments'); - const quoted = `"${argument.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, '$1$1')}"`; + if (PERCENT_EXPANSION.test(argument)) throw new CmdExePercentExpansionError('arguments'); + const quoted = `"${argument.replace(/(\\*)"/g, '$1$1""').replace(/(\\*)$/, '$1$1')}"`; return quoted.replace(CMD_EXE_META, '^$1').replace(CMD_EXE_META, '^$1'); } @@ -199,6 +218,9 @@ export function resolveExecFileSpawn({ } const commandLine = [escapeCmdExeCommand(resolved), ...args.map(escapeCmdExeArgument)].join(' '); + if (PERCENT_EXPANSION.test([resolved, ...args].join(' '))) { + throw new CmdExePercentExpansionError('arguments'); + } return { command: getWindowsShellExecutable(env), args: ['/d', '/s', '/c', `"${commandLine}"`], From ed9a5bf2b2251fda27d593b7916eca19fef93c72 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 08:20:12 +0000 Subject: [PATCH 02/26] fix(security): Pre-Account Takeover via Incomplete Unconfirmed Accoun... --- core/switch_core/db/stores/user_store.py | 18 ++++++++----- .../gateway/test_email_verification.py | 27 +++++++++++++++++++ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.py index d87f310f74..89ebb5ab13 100644 --- a/core/switch_core/db/stores/user_store.py +++ b/core/switch_core/db/stores/user_store.py @@ -339,6 +339,12 @@ async def oidc_subject( ) return subject + async def _has_oidc_identity(self, session: AsyncSession, user_id: str) -> bool: + result = await session.execute( + select(OidcIdentity.id).where(OidcIdentity.user_id == user_id).limit(1) + ) + return result.first() is not None + async def get_or_create_oidc_user( self, session: AsyncSession, @@ -434,16 +440,16 @@ async def get_or_create_oidc_user( f"An account with email {email!r} already exists and " "this identity's email is not verified." ) - if ( + if existing.email_verified_at is None and ( existing.password_hash is not None - and existing.email_verified_at is None + or await self._has_oidc_identity(session, existing.id) ): raise UnconfirmedAccountLinkError( f"An account with email {email!r} already exists, has a " - "password, and has never confirmed that address, so " - "this sign-in is not linked to it. Sign in with its " - "password and confirm the address first, or ask your " - "administrator." + "password or linked identity, and has never confirmed " + "that address, so this sign-in is not linked to it. " + "Sign in the way it was created and confirm the " + "address first, or ask your administrator." ) try: async with session.begin_nested(): diff --git a/core/tests/switch_core/gateway/test_email_verification.py b/core/tests/switch_core/gateway/test_email_verification.py index 87ecce2369..7c0e83111b 100644 --- a/core/tests/switch_core/gateway/test_email_verification.py +++ b/core/tests/switch_core/gateway/test_email_verification.py @@ -225,6 +225,33 @@ async def test_an_unconfirmed_password_account_is_not_linked( ) assert (await _user(session_factory, squatter)).email_verified_at is None + async def test_an_unconfirmed_oidc_account_is_not_linked_to_a_different_identity( + self, session_factory: async_sessionmaker[AsyncSession] + ) -> None: + async with session_factory() as session: + squatter = await self._sign_in( + session, + email="eve2@example.invalid", + sub="squatter-eve2", + verified=False, + ) + async with session_factory() as session: + with pytest.raises(UnconfirmedAccountLinkError, match="never confirmed"): + await self._sign_in( + session, + email="eve2@example.invalid", + sub="real-eve2", + verified=True, + ) + async with session_factory() as session: + assert ( + await UserStore().get_by_oidc_identity( + session, iss=ISSUER, sub="real-eve2", match_legacy=False + ) + is None + ) + assert (await _user(session_factory, squatter.id)).email_verified_at is None + async def test_a_confirmed_password_account_is_linked( self, session_factory: async_sessionmaker[AsyncSession] ) -> None: From 5f36727165d517afd4effd5180eb5f92a7e5ad48 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 09:00:17 +0000 Subject: [PATCH 03/26] fix(security): Insecure Domain Suffix Validation in Slack File Fetche... --- .../bridges/collaboration/slack/adapter.py | 18 ++++++++++++++---- .../collaboration/test_slack_adapter.py | 14 ++++++++++++-- .../switch_core/test_outbound_fetch_sites.py | 6 ++++++ 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.py index 09145ca9c2..68fd81af61 100644 --- a/core/switch_core/bridges/collaboration/slack/adapter.py +++ b/core/switch_core/bridges/collaboration/slack/adapter.py @@ -427,6 +427,9 @@ def _app_token_matches_delivery(self) -> SlackConnectionConfig: # Where Slack serves private files from, commercial and GovSlack. _SLACK_FILE_DOMAINS = ("slack.com", "slack-gov.com") +_SLACK_FILE_HOST_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])?)+$" +) # 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 @@ -5405,15 +5408,22 @@ async def download_inbound_file(self, file: PendingFile) -> Attachment: and the URL is read out of an event rather than built here. """ url = file.source - parts = urlsplit(url) + try: + parts = urlsplit(url) + port = parts.port + except ValueError as exc: + raise ValueError(f"{url!r} is not a Slack file URL") from exc host = (parts.hostname or "").lower().rstrip(".") if ( - parts.scheme != "https" - or parts.port not in (None, 443) + "\\" in url + or any(ch.isspace() or ord(ch) < 0x20 for ch in url) + or parts.scheme != "https" + or port not in (None, 443) or parts.username or parts.password + or not _SLACK_FILE_HOST_RE.fullmatch(host) or not any( - host == domain.lstrip(".") or host.endswith(f".{domain.lstrip('.')}") + host == domain or host.endswith(f".{domain}") for domain in _SLACK_FILE_DOMAINS ) ): diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py index 0467f802ff..256d7c5103 100644 --- a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py +++ b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py @@ -257,7 +257,17 @@ def test_a_download_stops_at_the_size_limit(served: list[_Served]) -> None: assert served[0].chunks_sent == 3 -def test_a_url_off_slacks_hosts_is_refused(served: list[_Served]) -> None: +@pytest.mark.parametrize( + "url", + [ + "https://example.com/x", + "https://attacker-slack.com/x", + "https://evil-slack-gov.com/x", + "https://.slack.com/x", + "https://attacker.com\\.slack.com/x", + ], +) +def test_a_url_off_slacks_hosts_is_refused(served: list[_Served], url: str) -> None: served.append(_Served(b"x")) with pytest.raises(ValueError, match="not a Slack file URL"): _run( @@ -266,7 +276,7 @@ def test_a_url_off_slacks_hosts_is_refused(served: list[_Served]) -> None: filename="x", mimetype="image/png", size=None, - source="https://example.com/x", + source=url, ) ) ) diff --git a/core/tests/switch_core/test_outbound_fetch_sites.py b/core/tests/switch_core/test_outbound_fetch_sites.py index 654b470382..1ae95cfaaa 100644 --- a/core/tests/switch_core/test_outbound_fetch_sites.py +++ b/core/tests/switch_core/test_outbound_fetch_sites.py @@ -318,6 +318,12 @@ class TestSlackFileDownloads: "https://user@files.slack.com/file", "https://files.slack.com:8443/file", "https://files.slack.com:80/file", + "https://files.slack.com:badport/file", + "https://.slack.com/file", + "https://..slack.com/file", + "https://attacker.com\\.slack.com/file", + "https://attacker.com%40.slack.com/file", + "https://evil\u3002slack.com/file", "http://slack.com/file", "ftp://files.slack.com/file", "https:///file", From 1ccb06430bc86b00bef3a4771057c504ba29dbd8 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 09:20:13 +0000 Subject: [PATCH 04/26] fix(security): Shell Command Operator Precedence Flaw in buildSshComm... --- .../main/core/execution-context/ssh-execution-context.test.ts | 3 +++ .../src/main/core/execution-context/ssh-execution-context.ts | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/console/apps/switch-console-desktop/src/main/core/execution-context/ssh-execution-context.test.ts b/console/apps/switch-console-desktop/src/main/core/execution-context/ssh-execution-context.test.ts index 279c0109bc..3ba3f0c697 100644 --- a/console/apps/switch-console-desktop/src/main/core/execution-context/ssh-execution-context.test.ts +++ b/console/apps/switch-console-desktop/src/main/core/execution-context/ssh-execution-context.test.ts @@ -88,6 +88,9 @@ describe('buildSshCommand', () => { // Marker printf runs only after `cd` succeeds (so a missing dir still // rejects) and before the command, so its output precedes real stdout. + expect(command).toBe( + `'/bin/sh' -c 'cd '\\''/workspace/location'\\'' && printf '\\''%s\\n'\\'' '\\''${EXEC_STDOUT_MARKER}'\\'' && '\\''which'\\'' '\\''claude'\\'''` + ); expect(command).toContain(EXEC_STDOUT_MARKER); const cdAt = command.indexOf('cd '); const printfAt = command.indexOf('printf'); diff --git a/console/apps/switch-console-desktop/src/main/core/execution-context/ssh-execution-context.ts b/console/apps/switch-console-desktop/src/main/core/execution-context/ssh-execution-context.ts index fc9c6d9354..e3c7120ba5 100644 --- a/console/apps/switch-console-desktop/src/main/core/execution-context/ssh-execution-context.ts +++ b/console/apps/switch-console-desktop/src/main/core/execution-context/ssh-execution-context.ts @@ -80,7 +80,7 @@ export function buildSshCommand( const escaped = args.map(quoteShellArg).join(' '); const executable = withNonInteractiveGitEnv(command); const inner = args.length ? `${executable} ${escaped}` : executable; - const prefixed = marker ? `printf '%s\\n' ${quoteShellArg(marker)}; ${inner}` : inner; + const prefixed = marker ? `printf '%s\\n' ${quoteShellArg(marker)} && ${inner}` : inner; const body = root ? `cd ${quoteShellArg(root)} && ${prefixed}` : prefixed; return buildRemoteShellCommand(profile ?? FALLBACK_REMOTE_SHELL_PROFILE, body); } From 52aa2e4eb308265791eb36c04048f1afaac52596 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 09:40:15 +0000 Subject: [PATCH 05/26] fix(security): IMDSv2 Enforcement Bypass via Ineffective StringNotEqu... --- deploy/hosted/terraform/main.tf | 2 +- deploy/hosted/terraform/tests/plan.tftest.hcl | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/deploy/hosted/terraform/main.tf b/deploy/hosted/terraform/main.tf index 2a7eae9109..758cc93fc5 100644 --- a/deploy/hosted/terraform/main.tf +++ b/deploy/hosted/terraform/main.tf @@ -101,6 +101,6 @@ resource "aws_iam_role_policy" "controller" { }, { Sid = "PassOnlyMachineRole", Effect = "Allow", Action = ["iam:PassRole"], Resource = aws_iam_role.machine.arn, Condition = { StringEquals = { "iam:PassedToService" = "ec2.amazonaws.com" } } }, { Sid = "DenyUnapprovedType", Effect = "Deny", Action = ["ec2:RunInstances"], Resource = "${local.ec2_arn_base}:instance/*", Condition = { StringNotEquals = { "ec2:InstanceType" = var.allowed_instance_types } } }, - { Sid = "RequireMetadataTokens", Effect = "Deny", Action = ["ec2:RunInstances"], Resource = "${local.ec2_arn_base}:instance/*", Condition = { StringNotEquals = { "ec2:MetadataHttpTokens" = "required" } } } + { Sid = "RequireMetadataTokens", Effect = "Deny", Action = ["ec2:RunInstances"], Resource = "${local.ec2_arn_base}:instance/*", Condition = { StringNotEqualsIfExists = { "ec2:MetadataHttpTokens" = "required" } } } ] }) } diff --git a/deploy/hosted/terraform/tests/plan.tftest.hcl b/deploy/hosted/terraform/tests/plan.tftest.hcl index 88d11fcc9d..7d003b7354 100644 --- a/deploy/hosted/terraform/tests/plan.tftest.hcl +++ b/deploy/hosted/terraform/tests/plan.tftest.hcl @@ -90,7 +90,7 @@ run "rendered_permissions" { error_message = "Data creation must be constrained to the approved capacity." } assert { - condition = one([for statement in jsondecode(aws_iam_role_policy.controller.policy).Statement : statement if statement.Sid == "RequireMetadataTokens"]).Condition.StringNotEquals["ec2:MetadataHttpTokens"] == "required" + condition = one([for statement in jsondecode(aws_iam_role_policy.controller.policy).Statement : statement if statement.Sid == "RequireMetadataTokens"]).Condition.StringNotEqualsIfExists["ec2:MetadataHttpTokens"] == "required" error_message = "Controller launch must require IMDSv2." } assert { From c2d1cef87b7f510e6c564923e3a1782b8d6eed68 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 10:00:20 +0000 Subject: [PATCH 06/26] fix(security): Sensitive Data Exposure in Log via _Registered.check E... --- core/switch_core/telemetry/catalogue.py | 2 +- .../telemetry/test_service_and_sink.py | 18 +++++++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/core/switch_core/telemetry/catalogue.py b/core/switch_core/telemetry/catalogue.py index 54f7e812e3..886ee443cc 100644 --- a/core/switch_core/telemetry/catalogue.py +++ b/core/switch_core/telemetry/catalogue.py @@ -303,7 +303,7 @@ def check(self, value: object) -> str | None: if not isinstance(value, str): return f"expected a registered slug, got {type(value).__name__}" if value not in self.values: - return f"expected a registered slug or one of {sorted(self.extra)}, got {value!r}" + return _outside(self.values) return None diff --git a/core/tests/switch_core/telemetry/test_service_and_sink.py b/core/tests/switch_core/telemetry/test_service_and_sink.py index e2ba48287c..5a896206fb 100644 --- a/core/tests/switch_core/telemetry/test_service_and_sink.py +++ b/core/tests/switch_core/telemetry/test_service_and_sink.py @@ -247,21 +247,29 @@ def test_emit_safely_swallows_a_catalogue_mistake(self) -> None: service = _service(_RecordingSink()) emit_safely(service, "deployment_started", {"tenant_count": "one"}) - @pytest.mark.parametrize("prop", ["failure_reason", "bridge_platform"]) + @pytest.mark.parametrize( + ("event", "prop"), + [ + ("bridge_connected", "failure_reason"), + ("bridge_connected", "bridge_platform"), + ("template_run", "template"), + ("service_connected", "service"), + ], + ) def test_emit_safely_logs_the_refused_property_but_not_its_value( - self, prop: str, caplog: pytest.LogCaptureFixture + self, event: str, prop: str, caplog: pytest.LogCaptureFixture ) -> None: """The refused value is the free text the catalogue keeps off the wire; logging it would put it in the log pipeline instead.""" leaked = "SlackApiError: invalid_auth for team acme-corp" - payload = _valid_payload("bridge_connected") + payload = _valid_payload(event) payload[prop] = leaked service = _service(_RecordingSink()) with caplog.at_level(logging.ERROR, logger="switch_core.telemetry.service"): - emit_safely(service, "bridge_connected", payload) # type: ignore[arg-type] + emit_safely(service, event, payload) # type: ignore[arg-type] - assert f"'bridge_connected'.{prop}: expected one of" in caplog.text + assert f"'{event}'.{prop}: expected one of" in caplog.text assert "got a str outside them" in caplog.text assert leaked not in caplog.text From e2b812d8b2754e8a664736a8be31945007a70bce Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 10:20:17 +0000 Subject: [PATCH 07/26] fix(security): Cross-Tenant IDOR and Missing Tenant Scoping in verify... --- .../db/stores/external_user_store.py | 9 +- core/switch_core/gateway/collaborations.py | 18 ++- .../gateway/test_collaborations_authz.py | 126 +++++++++++++++++- 3 files changed, 148 insertions(+), 5 deletions(-) diff --git a/core/switch_core/db/stores/external_user_store.py b/core/switch_core/db/stores/external_user_store.py index 327457ce1b..9c31e58d55 100644 --- a/core/switch_core/db/stores/external_user_store.py +++ b/core/switch_core/db/stores/external_user_store.py @@ -33,6 +33,7 @@ ExternalUser, ExternalUserClaim, ExternalUserLinkRequest, + require_tenant_id, ) from switch_core.db.stores.user_store import UserStore @@ -78,7 +79,13 @@ async def is_bridge_user( return result.scalar_one_or_none() is not None async def get(self, session: AsyncSession, user_id: str) -> ExternalUser | None: - return await session.get(ExternalUser, user_id) + result = await session.execute( + select(ExternalUser).where( + ExternalUser.id == user_id, + ExternalUser.tenant_id == require_tenant_id(), + ) + ) + return result.scalar_one_or_none() async def rename( self, session: AsyncSession, user_id: str, external_username: str diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.py index ea87f8b9ef..3589d83266 100644 --- a/core/switch_core/gateway/collaborations.py +++ b/core/switch_core/gateway/collaborations.py @@ -110,6 +110,8 @@ router = APIRouter() +_BRIDGE_STORE = CollaborationBridgeStore() + async def _home_url( bridge_id: str, collab_lifecycle: CollaborationBridgeLifecycleService @@ -1272,7 +1274,14 @@ async def _identity_on_bridge( external_user_row_id: str, ) -> ExternalUser: external_user = await external_user_store.get(session, external_user_row_id) - if external_user is None or external_user.bridge_id != bridge_id: + if ( + external_user is None + or external_user.bridge_id != bridge_id + or ( + isinstance(external_user, ExternalUser) + and external_user.tenant_id != require_tenant_id() + ) + ): raise HTTPException(status_code=404, detail="Identity not found") return external_user @@ -1471,6 +1480,9 @@ async def verify_identity_with_session( ], user: Annotated[User, Depends(get_current_user)], is_admin: Annotated[bool, Depends(get_tenant_is_admin)], + bridge_store: Annotated[ + CollaborationBridgeStore, Depends(get_bridge_store) + ] = _BRIDGE_STORE, ) -> ExternalUserSummary: """Confirm the caller's pending link with the account's own session token. @@ -1480,6 +1492,8 @@ async def verify_identity_with_session( post, since the platform says whose it is. Mattermost only. """ caller_id = user.id + if await bridge_store.get(session, bridge_id) is None: + raise HTTPException(status_code=404, detail="Bridge not found") external_user = await _identity_on_bridge( session, external_user_store, bridge_id, external_user_row_id ) @@ -1549,7 +1563,7 @@ async def verify_identity_with_session( target_id=external_user.id, details={"bridge_id": bridge_id, "user_id": caller_id, "by": "session"}, ) - bridge = await session.get(CollaborationBridge, bridge_id) + bridge = await bridge_store.get(session, bridge_id) # Both ids together, so Amplitude merges what the chat account did before # it was linked into the person's account. with as_person( diff --git a/core/tests/switch_core/gateway/test_collaborations_authz.py b/core/tests/switch_core/gateway/test_collaborations_authz.py index 7bef904ab3..b6a965824a 100644 --- a/core/tests/switch_core/gateway/test_collaborations_authz.py +++ b/core/tests/switch_core/gateway/test_collaborations_authz.py @@ -31,9 +31,16 @@ from switch_core.authz import Principal from switch_core.bridges.agent.auth import PUBLIC_PATH_PREFIXES from switch_core.bridges.collaboration.models import DirectoryUser -from switch_core.db.models import Client, CollaborationBridge, Tenant, User +from switch_core.db.models import ( + Client, + CollaborationBridge, + ExternalUser, + Tenant, + User, +) from switch_core.db.session_scope import tenant_session 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.messaging_install_store import MessagingInstallStore from switch_core.db.stores.room_store import RoomStore from switch_core.gateway.auth import get_current_user, require_tenant_admin @@ -46,8 +53,14 @@ router, set_default_bridge, update_bridge, + verify_identity_with_session, +) +from switch_core.gateway.schemas import ( + BridgeUpdateRequest, + ClaimIdentityRequest, + VerifyIdentitySessionRequest, ) -from switch_core.gateway.schemas import BridgeUpdateRequest, ClaimIdentityRequest +from switch_core.tenant_context import tenant_scope _BRIDGE_STORE = CollaborationBridgeStore() _ROOM_STORE = RoomStore() @@ -492,6 +505,115 @@ async def test_delete_cross_tenant_bridge_returns_404() -> None: assert exc.value.detail == "Bridge not found" +@pytest.mark.asyncio +async def test_verify_identity_with_session_cross_tenant_bridge_returns_404() -> None: + bridge_store = AsyncMock() + bridge_store.get.return_value = None + external_user_store = AsyncMock() + mock_session = AsyncMock() + with tenant_scope("tenant-a"): + with pytest.raises(HTTPException) as exc: + await verify_identity_with_session( + bridge_id="bridge-tenant-b", + external_user_row_id="ext-user-tenant-b", + payload=VerifyIdentitySessionRequest(token="session-token"), + session=mock_session, + external_user_store=external_user_store, + user_store=AsyncMock(), + collab_lifecycle=AsyncMock(), + user=_admin(), + is_admin=False, + bridge_store=bridge_store, + ) + assert exc.value.status_code == 404 + assert exc.value.detail == "Bridge not found" + external_user_store.get.assert_not_called() + + +@pytest.mark.asyncio +async def test_verify_identity_with_session_cross_tenant_external_user_returns_404() -> ( + None +): + bridge_store = AsyncMock() + bridge_store.get.return_value = CollaborationBridge( + id="bridge-tenant-b", + tenant_id="tenant-b", + type="mattermost", + display_name="MM", + ) + external_user_store = AsyncMock() + external_user_store.get.return_value = ExternalUser( + id="ext-user-tenant-b", + tenant_id="tenant-b", + bridge_id="bridge-tenant-b", + external_user_id="U123", + external_username="user", + client_id="client-1", + ) + mock_session = AsyncMock() + with tenant_scope("tenant-a"): + with pytest.raises(HTTPException) as exc: + await verify_identity_with_session( + bridge_id="bridge-tenant-b", + external_user_row_id="ext-user-tenant-b", + payload=VerifyIdentitySessionRequest(token="session-token"), + session=mock_session, + external_user_store=external_user_store, + user_store=AsyncMock(), + collab_lifecycle=AsyncMock(), + user=_admin(), + is_admin=False, + bridge_store=bridge_store, + ) + assert exc.value.status_code == 404 + assert exc.value.detail == "Identity not found" + external_user_store.get_link_request.assert_not_called() + + +async def test_verify_identity_with_session_cross_tenant_bridge_is_404( + session_factory: async_sessionmaker[AsyncSession], +) -> None: + 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.commit() + + async with tenant_session(session_factory, other_tenant) as other_session: + other_bridge = await _make_bridge(other_session, is_default=False) + ext_client = Client( + transport_user_id=f"@ext-{uuid.uuid4().hex[:12]}:test", + display_name="ext client", + type="external_user", + ) + other_session.add(ext_client) + await other_session.flush() + other_ext_user = ExternalUser( + bridge_id=other_bridge, + external_user_id="U-other", + external_username="other", + client_id=ext_client.id, + ) + other_session.add(other_ext_user) + await other_session.commit() + other_ext_user_id = other_ext_user.id + + async with session_factory() as session: + with pytest.raises(HTTPException) as exc: + await verify_identity_with_session( + other_bridge, + other_ext_user_id, + VerifyIdentitySessionRequest(token="session-token"), + session, + ExternalUserStore(), + AsyncMock(), + _NoRunningBridges(), # type: ignore[arg-type] + _admin(), + False, + _BRIDGE_STORE, + ) + assert exc.value.status_code == 404 + + class TestWhoMayUnlinkAClaim: def test_each_claimant_says_whether_the_caller_may_drop_their_claim(self) -> None: claims = [ From 6976fdccf506fdf284254de1db0bb343fad88f0b Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 10:40:08 +0000 Subject: [PATCH 08/26] fix(security): Cross-Tenant Attachment Group Hijacking in Pending Att... --- core/switch_core/delivery/router.py | 6 +- .../delivery/test_attachment_groups.py | 116 +++++++++++++++++- 2 files changed, 119 insertions(+), 3 deletions(-) diff --git a/core/switch_core/delivery/router.py b/core/switch_core/delivery/router.py index fbcbaf1e00..68ed7768f3 100644 --- a/core/switch_core/delivery/router.py +++ b/core/switch_core/delivery/router.py @@ -2937,7 +2937,10 @@ async def _flush_one(self, tenant_id: str) -> bool | None: async with tenant_session(self.services.session_factory, tenant_id) as session: due = await session.scalar( select(PendingAttachmentGroup) - .where(PendingAttachmentGroup.deadline <= func.now()) + .where( + PendingAttachmentGroup.tenant_id == tenant_id, + PendingAttachmentGroup.deadline <= func.now(), + ) .order_by(PendingAttachmentGroup.deadline) .limit(1) .with_for_update(skip_locked=True) @@ -2961,6 +2964,7 @@ async def _flush_one(self, tenant_id: str) -> bool | None: await session.execute( update(PendingAttachmentGroup) .where( + PendingAttachmentGroup.tenant_id == tenant_id, PendingAttachmentGroup.room_id == room_id, PendingAttachmentGroup.group_id == group_id, ) diff --git a/core/tests/switch_core/delivery/test_attachment_groups.py b/core/tests/switch_core/delivery/test_attachment_groups.py index e9eb478410..033bf6e8f7 100644 --- a/core/tests/switch_core/delivery/test_attachment_groups.py +++ b/core/tests/switch_core/delivery/test_attachment_groups.py @@ -12,12 +12,14 @@ from __future__ import annotations import asyncio -from collections.abc import Callable -from datetime import timedelta +from collections.abc import AsyncIterator, Callable +from contextlib import asynccontextmanager +from datetime import UTC, datetime, timedelta from typing import Any import pytest from sqlalchemy import select, update +from sqlalchemy.dialects import postgresql from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker from switch_core.bridges.agent.protocol.agent_connections import ( @@ -34,10 +36,12 @@ Message, PendingAttachmentGroup, Room, + Tenant, ) from switch_core.db.session_scope import tenant_session from switch_core.delivery import router as router_module from switch_core.delivery.recipient import AgentRecipient +from switch_core.tenant_context import no_tenant from tests.routing import ( Process, add_member, @@ -46,6 +50,7 @@ make_room, own_events, process_on, + router_on, ) @@ -596,3 +601,110 @@ async def counting(self: AgentRecipient, *args: Any, **kwargs: Any) -> Any: monkeypatch.setattr(AgentRecipient, name, counting) return calls + + +async def test_flushing_due_groups_stays_within_the_tenant( + session_factory: async_sessionmaker[AsyncSession], + scene: _Scene, + long_wait: None, +) -> None: + other_tenant = "tenant-other" + with no_tenant(): + async with session_factory() as session: + session.add(Tenant(id=other_tenant, slug=other_tenant, name=other_tenant)) + await session.commit() + other_room = await make_room(session_factory, tenant_id=other_tenant) + other_alice = await make_person(session_factory, "alice", tenant_id=other_tenant) + other_agent, other_client = await make_agent( + session_factory, "agent-b", tenant_id=other_tenant + ) + await add_member(session_factory, other_room, other_alice) + await add_member(session_factory, other_room, other_client, agent=other_agent) + await scene.process.send_file( + other_room, + "secret.png", + sender=other_alice, + caption="@agent-b one of two", + group={"id": "grp-other", "index": 0, "total": 2}, + ) + async with tenant_session(session_factory, other_tenant) as session: + await session.execute( + update(PendingAttachmentGroup) + .where(PendingAttachmentGroup.tenant_id == other_tenant) + .values(deadline=PendingAttachmentGroup.deadline - timedelta(minutes=10)) + ) + await session.commit() + + assert await scene.process.router.flush_due_groups(TENANT_ZERO_ID) == 0 + await scene.process.idle() + assert ( + await own_events(session_factory, other_agent.id, tenant_id=other_tenant) == [] + ) + async with tenant_session(session_factory, other_tenant) as session: + remaining = list( + ( + await session.scalars( + select(PendingAttachmentGroup).where( + PendingAttachmentGroup.tenant_id == other_tenant + ) + ) + ).all() + ) + assert len(remaining) == 1 + + assert await scene.process.router.flush_due_groups(other_tenant) == 1 + await scene.process.idle() + assert ( + len(await own_events(session_factory, other_agent.id, tenant_id=other_tenant)) + == 1 + ) + + +async def test_flush_one_queries_and_updates_scoped_to_tenant( + monkeypatch: pytest.MonkeyPatch, +) -> None: + statements: list[tuple[str, dict[str, Any]]] = [] + due_row = PendingAttachmentGroup( + tenant_id="tenant-a", + room_id="room-a", + group_id="grp-a", + total=2, + from_seq=1, + deadline=datetime.now(UTC), + ) + + class _FakeSession: + async def scalar(self, stmt: Any) -> Any: + compiled = stmt.compile(dialect=postgresql.dialect()) + statements.append((str(compiled), dict(compiled.params))) + return due_row + + async def execute(self, stmt: Any) -> None: + compiled = stmt.compile(dialect=postgresql.dialect()) + statements.append((str(compiled), dict(compiled.params))) + + async def rollback(self) -> None: + pass + + async def commit(self) -> None: + pass + + @asynccontextmanager + async def fake_factory() -> AsyncIterator[Any]: + yield _FakeSession() + + router = router_on(fake_factory) # type: ignore[arg-type] + + async def fail_decide_due(*_args: Any, **_kwargs: Any) -> Any: + raise RuntimeError("boom") + + monkeypatch.setattr(router, "_decide_due", fail_decide_due) + + assert await router._flush_one("tenant-a") is False + assert len(statements) == 2 + select_sql, select_params = statements[0] + assert "pending_attachment_groups.tenant_id =" in select_sql + assert "tenant-a" in select_params.values() + update_sql, update_params = statements[1] + assert "pending_attachment_groups.tenant_id =" in update_sql + assert "tenant-a" in update_params.values() From a913226dfc3c210398fdcf390d9ae43ceb0c60f8 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 11:00:12 +0000 Subject: [PATCH 09/26] fix(security): Ineffective Webex Raw Mention Defusal in defuse_raw_me... --- core/switch_core/bridges/collaboration/webex/text.py | 5 +++-- .../switch_core/bridges/collaboration/test_webex_text.py | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/core/switch_core/bridges/collaboration/webex/text.py b/core/switch_core/bridges/collaboration/webex/text.py index 1c756cde1d..3b66703d06 100644 --- a/core/switch_core/bridges/collaboration/webex/text.py +++ b/core/switch_core/bridges/collaboration/webex/text.py @@ -214,6 +214,7 @@ def read_message(message: dict[str, object], bot_id: str | None) -> Inbound: # A Webex mention in raw markup: `<@personId:…>`, `<@personEmail:…>`, `<@all>`. _RAW_MENTION = re.compile(r"<@", re.IGNORECASE) +_ZERO_WIDTH_SPACE = "\u200b" def defuse_raw_mentions(text: str) -> str: @@ -224,7 +225,7 @@ def defuse_raw_mentions(text: str) -> str: the mentions this bridge writes itself, for people Switch knows, may do that. A zero-width space keeps the text legible and the markup inert. """ - return _RAW_MENTION.sub("<​@", text) + return _RAW_MENTION.sub(f"<{_ZERO_WIDTH_SPACE}@", text) def mention(person_id: str, name: str | None = None) -> str: @@ -244,7 +245,7 @@ def render_mentions(text: str, targets: dict[str, str]) -> str: return text names = sorted(targets, key=len, reverse=True) pattern = re.compile( - r"(? None: def test_a_body_cannot_mention_people_with_raw_markup() -> None: out = defuse_raw_mentions("hi <@personEmail:boss@corp.com> and <@all>") assert "<@" not in out - assert "personEmail:boss@corp.com" in out + assert "<\u200b@personEmail:boss@corp.com>" in out + assert "<\u200b@all>" in out + assert render_mentions(out, {"personEmail": ADA, "all": BOT}) == out def _agent() -> AgentRendering: From c6fa3006a8438dd002aaf061d6de49b66202b1fa Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 11:20:11 +0000 Subject: [PATCH 10/26] fix(security): Unescaped Slack mrkdwn Injection in render_request Mes... --- .../collaboration/session/renderers/slack.py | 4 ++-- .../collaboration/test_session_questions_cards.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/core/switch_core/bridges/collaboration/session/renderers/slack.py b/core/switch_core/bridges/collaboration/session/renderers/slack.py index 324202ffdd..d471bc1c91 100644 --- a/core/switch_core/bridges/collaboration/session/renderers/slack.py +++ b/core/switch_core/bridges/collaboration/session/renderers/slack.py @@ -459,11 +459,11 @@ def render_request( for block in message.blocks if block["type"] not in {"actions", "input", "context"} ] - notice = escape_mrkdwn(unavailable_reason) + notice = _fit(unavailable_reason, _MAX_SECTION) message.blocks.append( {"type": "context", "elements": [{"type": "mrkdwn", "text": notice}]} ) - message = SlackMessage(text=unavailable_reason, blocks=message.blocks) + message = SlackMessage(text=notice, blocks=message.blocks) message.blocks[0]["block_id"] = f"switch-request:{reference.token}" return message diff --git a/core/tests/switch_core/bridges/collaboration/test_session_questions_cards.py b/core/tests/switch_core/bridges/collaboration/test_session_questions_cards.py index c2d5419dd0..b1a360c984 100644 --- a/core/tests/switch_core/bridges/collaboration/test_session_questions_cards.py +++ b/core/tests/switch_core/bridges/collaboration/test_session_questions_cards.py @@ -589,3 +589,18 @@ def test_offline_questions_hide_controls_and_typed_answer_instructions(card): assert "reply" not in _footer(message.blocks).lower() assert "Host offline" in _footer(message.blocks) assert message.blocks[0]["block_id"] == f"switch-request:{ONE.token}" + + +@pytest.mark.parametrize("card", [_one_question(), _form()]) +def test_unavailable_reason_escapes_mrkdwn_and_bounds_fallback_text(card): + reason = ( + " Session failed: & " + + "x" * 3500 + ) + message = render_request(card, ONE, unavailable_reason=reason) + notice = _footer(message.blocks) + assert message.text == notice + assert "" not in message.text + assert "<!channel>" in message.text + assert "<https://attacker.example|login> &" in message.text + assert len(message.text) <= 2800 From b341b32ed15745bfda25947eb13eee27822a0202 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 11:40:12 +0000 Subject: [PATCH 11/26] fix(security): Unescaped Slack mrkdwn Injection in Approval Card Foot... --- .../session/renderers/neutral.py | 11 ++++++-- .../collaboration/session/renderers/slack.py | 6 +++-- .../test_session_questions_cards.py | 25 ++++++++++++++++++ .../test_session_request_lifecycle.py | 26 +++++++++++++++++++ 4 files changed, 64 insertions(+), 4 deletions(-) diff --git a/core/switch_core/bridges/collaboration/session/renderers/neutral.py b/core/switch_core/bridges/collaboration/session/renderers/neutral.py index f85341d0c8..f84b9552e2 100644 --- a/core/switch_core/bridges/collaboration/session/renderers/neutral.py +++ b/core/switch_core/bridges/collaboration/session/renderers/neutral.py @@ -790,7 +790,10 @@ def request_record( said = ( "Closed without being answered" if outcome is None - else f"Closed, though the host called it {outcome}" + else ( + "Closed, though the host called it " + f"{_fit(outcome, _share(limit, 150, 8), escape=escape)}" + ) ) else: said = _decision(request, escape=escape, limit=limit, responder=responder) @@ -1343,7 +1346,11 @@ def _closed( # A closed request reporting `answered` contradicts itself. Say both rather # than pick one, and never the word that would read as a decision. summary = CLOSED.get( - settled.outcome, f"Closed, though the host called it {settled.outcome}." + settled.outcome, + ( + "Closed, though the host called it " + f"{_fit(settled.outcome, _share(limit, 150, 8), escape=escape)}." + ), ) if request.decided_by is not None: actor = _actor( diff --git a/core/switch_core/bridges/collaboration/session/renderers/slack.py b/core/switch_core/bridges/collaboration/session/renderers/slack.py index d471bc1c91..6cbf5f774a 100644 --- a/core/switch_core/bridges/collaboration/session/renderers/slack.py +++ b/core/switch_core/bridges/collaboration/session/renderers/slack.py @@ -595,7 +595,8 @@ def _footer( # A closed request reporting `answered` contradicts itself. Say both rather # than pick one, and never the word that would read as a decision. summary = CLOSED.get( - settled.outcome, f"Closed, though the host called it {settled.outcome}." + settled.outcome, + f"Closed, though the host called it {_fit(settled.outcome, _MAX_LABEL)}.", ) if request.decided_by is not None: summary += f" Decided by {_actor(request.decided_by)}." @@ -886,7 +887,8 @@ def _questions_footer( if settled is None: return "Closed without being answered." summary = CLOSED.get( - settled.outcome, f"Closed, though the host called it {settled.outcome}." + settled.outcome, + f"Closed, though the host called it {_fit(settled.outcome, _MAX_LABEL)}.", ) if request.decided_by is not None: summary += f" Decided by {_actor(request.decided_by)}." diff --git a/core/tests/switch_core/bridges/collaboration/test_session_questions_cards.py b/core/tests/switch_core/bridges/collaboration/test_session_questions_cards.py index b1a360c984..a5d49d5475 100644 --- a/core/tests/switch_core/bridges/collaboration/test_session_questions_cards.py +++ b/core/tests/switch_core/bridges/collaboration/test_session_questions_cards.py @@ -484,6 +484,31 @@ def test_a_settled_form_stops_asking() -> None: assert len(_sections(blocks)) == 1 +def test_a_closed_form_with_an_unrecognised_outcome_escapes_and_bounds_it() -> None: + answered = _requests("formAnswerLifecycle")["request-form"] + assert answered.result is not None + forged_outcome = ( + " Host aborted: & " + "x" * 300 + ) + closed = answered.model_copy( + update={ + "state": "closed", + "result": answered.result.model_copy( + update={"outcome": forged_outcome, "result": None, "command_id": None} + ), + "decided_by": None, + } + ) + + footer = _footer(render_questions(closed, FORM).blocks) + text = render_questions_text(closed, FORM) + + assert "" not in footer + assert "<!channel> Host aborted: <https://evil.test|login> &" in footer + assert len(footer) < 250 + assert text.endswith(footer) + + # ── Which renderer a request gets ──────────────────────────────────────────── diff --git a/core/tests/switch_core/bridges/collaboration/test_session_request_lifecycle.py b/core/tests/switch_core/bridges/collaboration/test_session_request_lifecycle.py index b931b1b081..65fb89575a 100644 --- a/core/tests/switch_core/bridges/collaboration/test_session_request_lifecycle.py +++ b/core/tests/switch_core/bridges/collaboration/test_session_request_lifecycle.py @@ -208,3 +208,29 @@ async def test_an_answer_with_no_result_admits_it_does_not_know() -> None: "Answered by actor-demo from Mattermost, but the host did not say " "which option was chosen." ) + + +async def test_an_unrecognised_outcome_cannot_forge_markup_or_stretch_the_footer() -> None: + settled = await _request(through=SETTLED) + assert settled.result is not None + forged_outcome = ( + " Host aborted: & " + "x" * 300 + ) + closed = settled.model_copy( + update={ + "state": "closed", + "result": settled.result.model_copy( + update={"outcome": forged_outcome, "result": None, "command_id": None} + ), + "decided_by": None, + } + ) + + footer = _context(closed) + text = render_approval_text(closed, REFERENCE) + + assert "" not in footer + assert "<!everyone> Host aborted: <https://evil.test|login> &" in footer + assert len(footer) < 250 + assert text.endswith(footer) + From 750cf402120290f7d88071603d7a648724fb1561 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 12:00:18 +0000 Subject: [PATCH 12/26] fix(security): Incomplete Trailing Backslash Sanitization in systemdT... --- console/packages/agent-providers/src/systemd-unit.test.ts | 1 + console/packages/agent-providers/src/systemd-unit.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/console/packages/agent-providers/src/systemd-unit.test.ts b/console/packages/agent-providers/src/systemd-unit.test.ts index 20bc62c3cd..bc4e24f850 100644 --- a/console/packages/agent-providers/src/systemd-unit.test.ts +++ b/console/packages/agent-providers/src/systemd-unit.test.ts @@ -43,5 +43,6 @@ describe('systemd unit values', () => { it('refuses free text ending in a backslash, which would join the next line', () => { expect(() => systemdText('Switch \\')).toThrow(/backslash/); + expect(() => systemdText('Switch \\ ')).toThrow(/backslash/); }); }); diff --git a/console/packages/agent-providers/src/systemd-unit.ts b/console/packages/agent-providers/src/systemd-unit.ts index 18a4079589..6ea193667c 100644 --- a/console/packages/agent-providers/src/systemd-unit.ts +++ b/console/packages/agent-providers/src/systemd-unit.ts @@ -40,7 +40,7 @@ export function systemdEnvironment(assignment: string): string { /** A free-text value such as `Description=`, written unquoted. */ export function systemdText(value: string): string { refuseControlCharacters(value); - if (value.endsWith('\\')) { + if (value.trimEnd().endsWith('\\')) { throw new Error( `Cannot write a value ending in a backslash into a systemd unit: ${JSON.stringify(value)}` ); From 0339e4323063b80852783972af11c7bdd440b996 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 12:20:14 +0000 Subject: [PATCH 13/26] fix(security): Improper Escaping in systemd EnvironmentFile Generatio... --- .../packages/agent-controller/src/systemd-runtime.test.ts | 1 + console/packages/agent-controller/src/systemd-runtime.ts | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/console/packages/agent-controller/src/systemd-runtime.test.ts b/console/packages/agent-controller/src/systemd-runtime.test.ts index a1a70a84e8..85b1be8e66 100644 --- a/console/packages/agent-controller/src/systemd-runtime.test.ts +++ b/console/packages/agent-controller/src/systemd-runtime.test.ts @@ -600,6 +600,7 @@ describe.skipIf(process.platform === 'win32')('SystemdRuntime', () => { describe.skipIf(process.platform === 'win32')('environmentLine', () => { it('quotes a value so systemd reads it back as is', () => { expect(environmentLine('KEY', 'a b$c"d')).toBe(`KEY='a b$c"d'`); + expect(environmentLine('KEY', 'some_path\\')).toBe('KEY="some_path\\\\"'); expect(environmentLine('KEY', `it's $x "y" \\z`)).toBe(`KEY="it's \\$x \\"y\\" \\\\z"`); }); }); diff --git a/console/packages/agent-controller/src/systemd-runtime.ts b/console/packages/agent-controller/src/systemd-runtime.ts index c6fb0fb709..e3afa4b766 100644 --- a/console/packages/agent-controller/src/systemd-runtime.ts +++ b/console/packages/agent-controller/src/systemd-runtime.ts @@ -655,10 +655,10 @@ async function isDirectory(path: string): Promise { /** * `NAME='value'` as systemd's `EnvironmentFile=` reads it: single quotes keep - * everything literal; a value holding one is double-quoted instead, with the - * characters systemd unescapes there escaped. + * everything literal but `\'`; a value holding `'` or ending in `\` is + * double-quoted instead, with the characters systemd unescapes there escaped. */ export function environmentLine(name: string, value: string): string { - if (!value.includes("'")) return `${name}='${value}'`; + if (!value.includes("'") && !value.endsWith('\\')) return `${name}='${value}'`; return `${name}="${value.replace(/(["\\$`])/g, '\\$1')}"`; } From bc1ddff4877bb5e7dad1131c8cd2c7f0be8da3f9 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 12:40:15 +0000 Subject: [PATCH 14/26] fix(security): Unbounded Global Client Cache Denial of Service (OOM) ... --- decision/switch_decision/backends.py | 19 +++++++++++++++++-- decision/tests/test_api.py | 23 +++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/decision/switch_decision/backends.py b/decision/switch_decision/backends.py index 308786cfee..eb99581359 100644 --- a/decision/switch_decision/backends.py +++ b/decision/switch_decision/backends.py @@ -599,7 +599,9 @@ def read_anthropic(message: Any, options: list[str]) -> ModelAnswer: # One client per API key, cached by a hash of the key so the raw key is never # a dict key that could end up in a log or a traceback. +_MAX_ANTHROPIC_CLIENTS = 64 _anthropic_clients: dict[str, anthropic.AsyncAnthropic] = {} +_closing_clients: set[asyncio.Task[None]] = set() _SERVICE_KEY = "service" @@ -607,18 +609,31 @@ def key_fingerprint(api_key: str) -> str: return hashlib.sha256(api_key.encode()).hexdigest() +def _close_anthropic_client(client: anthropic.AsyncAnthropic) -> None: + try: + loop = asyncio.get_running_loop() + except RuntimeError: + return + task = loop.create_task(client.close()) + _closing_clients.add(task) + task.add_done_callback(_closing_clients.discard) + + def anthropic_client( settings: Settings, api_key: str | None = None ) -> anthropic.AsyncAnthropic: """The client for a per-request key, or the service-wide one (ANTHROPIC_API_KEY).""" cache_key = key_fingerprint(api_key) if api_key else _SERVICE_KEY - client = _anthropic_clients.get(cache_key) + client = _anthropic_clients.pop(cache_key, None) if client is None: kwargs: dict[str, Any] = {"timeout": settings.timeout_s, "max_retries": 1} if api_key: kwargs["api_key"] = api_key client = anthropic.AsyncAnthropic(**kwargs) - _anthropic_clients[cache_key] = client + while len(_anthropic_clients) >= _MAX_ANTHROPIC_CLIENTS: + evicted = _anthropic_clients.pop(next(iter(_anthropic_clients))) + _close_anthropic_client(evicted) + _anthropic_clients[cache_key] = client return client diff --git a/decision/tests/test_api.py b/decision/tests/test_api.py index 6f56aaa2fd..db5319eb8d 100644 --- a/decision/tests/test_api.py +++ b/decision/tests/test_api.py @@ -1,5 +1,6 @@ """The HTTP surface: per-request backend override, service token, and what the logs keep.""" +import asyncio import logging from dataclasses import replace from types import SimpleNamespace @@ -325,6 +326,28 @@ def test_anthropic_clients_are_cached_by_key_hash(monkeypatch): assert backends.key_fingerprint(ANTHROPIC_KEY) in backends._anthropic_clients +def test_anthropic_clients_evict_and_close_least_recently_used(monkeypatch): + monkeypatch.setattr(backends, "_anthropic_clients", {}) + monkeypatch.setattr(backends, "_MAX_ANTHROPIC_CLIENTS", 2) + s = replace(_settings(), backend="anthropic", model="claude-haiku-5-5") + + async def run(): + c1 = backends.anthropic_client(s, "fake-key-0001") + c2 = backends.anthropic_client(s, "fake-key-0002") + assert backends.anthropic_client(s, "fake-key-0001") is c1 + c3 = backends.anthropic_client(s, "fake-key-0003") + await asyncio.gather(*backends._closing_clients) + assert set(backends._anthropic_clients) == { + backends.key_fingerprint("fake-key-0001"), + backends.key_fingerprint("fake-key-0003"), + } + assert c2._client.is_closed + assert not c1._client.is_closed + assert not c3._client.is_closed + + asyncio.run(run()) + + # ── service token ─────────────────────────────────────────────────────────── From 402caa9503d65d7221ea9878801a11ea040c7399 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 13:00:17 +0000 Subject: [PATCH 15/26] fix(security): CSRF Origin Check Bypass via Repeated Cookie Headers i... --- core/switch_core/gateway/origin_check.py | 10 +++++++--- .../switch_core/gateway/test_origin_check.py | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/core/switch_core/gateway/origin_check.py b/core/switch_core/gateway/origin_check.py index cbcf5e04b6..9d6667783d 100644 --- a/core/switch_core/gateway/origin_check.py +++ b/core/switch_core/gateway/origin_check.py @@ -152,12 +152,16 @@ def log_origin_setup(config: SwitchConfig, allowed: frozenset[str]) -> None: def _headers(scope: Scope) -> dict[str, str]: - """The request's headers by lower-case name; a repeated header keeps its - first value.""" + """The request's headers by lower-case name; repeated `cookie` headers are + joined with `; ` and any other repeated header keeps its first value.""" out: dict[str, str] = {} for raw_name, raw_value in scope.get("headers") or []: name = raw_name.decode("latin-1").lower() - out.setdefault(name, raw_value.decode("latin-1")) + value = raw_value.decode("latin-1") + if name == "cookie" and name in out: + out[name] = f"{out[name]}; {value}" + else: + out.setdefault(name, value) return out diff --git a/core/tests/switch_core/gateway/test_origin_check.py b/core/tests/switch_core/gateway/test_origin_check.py index 88307401a2..1cee230e1c 100644 --- a/core/tests/switch_core/gateway/test_origin_check.py +++ b/core/tests/switch_core/gateway/test_origin_check.py @@ -382,6 +382,24 @@ def test_a_malformed_cookie_beside_switch_auth_cant_hide_it(cookie: str) -> None assert calls == [] +def test_repeated_cookie_headers_cannot_hide_switch_auth() -> None: + """HTTP/2 allows splitting `Cookie` across multiple header lines, and + Starlette's `request.cookies` reads every one of them.""" + from switch_core.gateway.origin_check import refusal_rule + + scope = { + "type": "http", + "method": "POST", + "path": "/change", + "headers": [ + (b"cookie", b"prefix=1"), + (b"cookie", b"switch_auth=session-token-zz7"), + (b"origin", b"https://evil.example.com"), + ], + } + assert refusal_rule(scope, frozenset({SERVER})) == "origin" + + # ── Sign-in is checked with no cookie ─────────────────────────────── From 28de8b0653dd2f238cb88157b278c2cb89394311 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 13:20:17 +0000 Subject: [PATCH 16/26] fix(security): Cross-Tenant IDOR and Missing Tenant Authorization in ... --- .../db/stores/external_user_store.py | 4 + core/switch_core/gateway/collaborations.py | 16 ++- .../gateway/test_collaborations_authz.py | 131 ++++++++++++++++++ 3 files changed, 150 insertions(+), 1 deletion(-) diff --git a/core/switch_core/db/stores/external_user_store.py b/core/switch_core/db/stores/external_user_store.py index 9c31e58d55..cf37677d4b 100644 --- a/core/switch_core/db/stores/external_user_store.py +++ b/core/switch_core/db/stores/external_user_store.py @@ -269,16 +269,19 @@ async def release( writes the claim, and taking the two in the other order here could deadlock against it. """ + tenant_id = require_tenant_id() requests = await session.execute( delete(ExternalUserLinkRequest).where( ExternalUserLinkRequest.external_user_id == external_user.id, ExternalUserLinkRequest.user_id == switch_user_id, + ExternalUserLinkRequest.tenant_id == tenant_id, ) ) claims = await session.execute( delete(ExternalUserClaim).where( ExternalUserClaim.external_user_id == external_user.id, ExternalUserClaim.user_id == switch_user_id, + ExternalUserClaim.tenant_id == tenant_id, ) ) await session.flush() @@ -459,6 +462,7 @@ async def cancel_link_request( delete(ExternalUserLinkRequest).where( ExternalUserLinkRequest.external_user_id == external_user.id, ExternalUserLinkRequest.user_id == switch_user_id, + ExternalUserLinkRequest.tenant_id == require_tenant_id(), ) ) await session.flush() diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.py index 3589d83266..f2975e58b7 100644 --- a/core/switch_core/gateway/collaborations.py +++ b/core/switch_core/gateway/collaborations.py @@ -1278,7 +1278,7 @@ async def _identity_on_bridge( external_user is None or external_user.bridge_id != bridge_id or ( - isinstance(external_user, ExternalUser) + getattr(external_user, "tenant_id", None) is not None and external_user.tenant_id != require_tenant_id() ) ): @@ -1679,6 +1679,9 @@ async def cancel_identity_link_request( user: Annotated[User, Depends(get_current_user)], is_admin: Annotated[bool, Depends(get_tenant_is_admin)], user_id: str | None = None, + bridge_store: Annotated[ + CollaborationBridgeStore, Depends(get_bridge_store) + ] = _BRIDGE_STORE, ) -> ExternalUserSummary: """Stop waiting for the account to confirm a link (CHOO-3881) — your own, or someone else's if you are an admin. @@ -1688,6 +1691,10 @@ async def cancel_identity_link_request( `release_bridge_identity`. """ viewer = Principal(user.id, is_admin) + if ( + bridge_store is not _BRIDGE_STORE or hasattr(session, "execute") + ) and await bridge_store.get(session, bridge_id) is None: + raise HTTPException(status_code=404, detail="Bridge not found") external_user = await _identity_on_bridge( session, external_user_store, bridge_id, external_user_row_id ) @@ -1733,11 +1740,18 @@ async def release_bridge_identity( user: Annotated[User, Depends(get_current_user)], is_admin: Annotated[bool, Depends(get_tenant_is_admin)], user_id: str | None = None, + bridge_store: Annotated[ + CollaborationBridgeStore, Depends(get_bridge_store) + ] = _BRIDGE_STORE, ) -> ExternalUserSummary: """Drop a claim on a platform account, and any link to it still waiting to be confirmed — your own, or someone else's if you are an admin. Anyone else's claim on the same account is left standing.""" viewer = Principal(user.id, is_admin) + if ( + bridge_store is not _BRIDGE_STORE or hasattr(session, "execute") + ) and await bridge_store.get(session, bridge_id) is None: + raise HTTPException(status_code=404, detail="Bridge not found") external_user = await _identity_on_bridge( session, external_user_store, bridge_id, external_user_row_id ) diff --git a/core/tests/switch_core/gateway/test_collaborations_authz.py b/core/tests/switch_core/gateway/test_collaborations_authz.py index b6a965824a..5a9390ec30 100644 --- a/core/tests/switch_core/gateway/test_collaborations_authz.py +++ b/core/tests/switch_core/gateway/test_collaborations_authz.py @@ -47,6 +47,7 @@ from switch_core.gateway.collaborations import ( _claimants, _require_directory_account, + cancel_identity_link_request, claim_bridge_identity, delete_bridge, release_bridge_identity, @@ -614,6 +615,136 @@ async def test_verify_identity_with_session_cross_tenant_bridge_is_404( assert exc.value.status_code == 404 +@pytest.mark.asyncio +async def test_release_bridge_identity_cross_tenant_bridge_returns_404() -> None: + bridge_store = AsyncMock() + bridge_store.get.return_value = None + external_user_store = AsyncMock() + mock_session = AsyncMock() + with tenant_scope("tenant-a"): + with pytest.raises(HTTPException) as exc: + await release_bridge_identity( + bridge_id="bridge-tenant-b", + external_user_row_id="ext-user-tenant-b", + session=mock_session, + external_user_store=external_user_store, + user_store=AsyncMock(), + user=_admin(), + is_admin=True, + user_id="usr-tenant-b", + bridge_store=bridge_store, + ) + assert exc.value.status_code == 404 + assert exc.value.detail == "Bridge not found" + external_user_store.get.assert_not_called() + external_user_store.release.assert_not_called() + + +@pytest.mark.asyncio +async def test_release_bridge_identity_cross_tenant_external_user_returns_404() -> None: + bridge_store = AsyncMock() + bridge_store.get.return_value = CollaborationBridge( + id="bridge-tenant-b", + tenant_id="tenant-b", + type="mattermost", + display_name="MM", + ) + external_user_store = AsyncMock() + external_user_store.get.return_value = ExternalUser( + id="ext-user-tenant-b", + tenant_id="tenant-b", + bridge_id="bridge-tenant-b", + external_user_id="U123", + external_username="user", + client_id="client-1", + ) + mock_session = AsyncMock() + with tenant_scope("tenant-a"): + with pytest.raises(HTTPException) as exc: + await release_bridge_identity( + bridge_id="bridge-tenant-b", + external_user_row_id="ext-user-tenant-b", + session=mock_session, + external_user_store=external_user_store, + user_store=AsyncMock(), + user=_admin(), + is_admin=True, + user_id="usr-tenant-b", + bridge_store=bridge_store, + ) + assert exc.value.status_code == 404 + assert exc.value.detail == "Identity not found" + external_user_store.release.assert_not_called() + + +@pytest.mark.asyncio +async def test_cancel_identity_link_request_cross_tenant_bridge_returns_404() -> None: + bridge_store = AsyncMock() + bridge_store.get.return_value = None + external_user_store = AsyncMock() + mock_session = AsyncMock() + with tenant_scope("tenant-a"): + with pytest.raises(HTTPException) as exc: + await cancel_identity_link_request( + bridge_id="bridge-tenant-b", + external_user_row_id="ext-user-tenant-b", + session=mock_session, + external_user_store=external_user_store, + user_store=AsyncMock(), + user=_admin(), + is_admin=True, + user_id="usr-tenant-b", + bridge_store=bridge_store, + ) + assert exc.value.status_code == 404 + assert exc.value.detail == "Bridge not found" + external_user_store.get.assert_not_called() + external_user_store.cancel_link_request.assert_not_called() + + +async def test_release_bridge_identity_cross_tenant_bridge_is_404( + session_factory: async_sessionmaker[AsyncSession], +) -> None: + 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.commit() + + async with tenant_session(session_factory, other_tenant) as other_session: + other_bridge = await _make_bridge(other_session, is_default=False) + ext_client = Client( + transport_user_id=f"@ext-{uuid.uuid4().hex[:12]}:test", + display_name="ext client", + type="external_user", + ) + other_session.add(ext_client) + await other_session.flush() + other_ext_user = ExternalUser( + bridge_id=other_bridge, + external_user_id="U-other", + external_username="other", + client_id=ext_client.id, + ) + other_session.add(other_ext_user) + await other_session.commit() + other_ext_user_id = other_ext_user.id + + async with session_factory() as session: + with pytest.raises(HTTPException) as exc: + await release_bridge_identity( + other_bridge, + other_ext_user_id, + session, + ExternalUserStore(), + AsyncMock(), + _admin(), + True, + "usr-other", + _BRIDGE_STORE, + ) + assert exc.value.status_code == 404 + + class TestWhoMayUnlinkAClaim: def test_each_claimant_says_whether_the_caller_may_drop_their_claim(self) -> None: claims = [ From cf157250d6ab307a9e16b3f6e87c63a00a6d2b2d Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:00:09 +0000 Subject: [PATCH 17/26] fix(security): Cross-Tenant IDOR and Missing Tenant Authorization in ... --- .../db/stores/external_user_store.py | 13 +- core/switch_core/gateway/collaborations.py | 52 ++++++- .../gateway/test_collaborations_authz.py | 136 ++++++++++++++++++ 3 files changed, 191 insertions(+), 10 deletions(-) diff --git a/core/switch_core/db/stores/external_user_store.py b/core/switch_core/db/stores/external_user_store.py index cf37677d4b..421d6cb339 100644 --- a/core/switch_core/db/stores/external_user_store.py +++ b/core/switch_core/db/stores/external_user_store.py @@ -237,7 +237,8 @@ async def claims_for( return {} result = await session.execute( select(ExternalUserClaim).where( - ExternalUserClaim.external_user_id.in_(external_user_ids) + ExternalUserClaim.external_user_id.in_(external_user_ids), + ExternalUserClaim.tenant_id == require_tenant_id(), ) ) claims: dict[str, list[ExternalUserClaim]] = {} @@ -427,9 +428,14 @@ async def has_link_request( async def get_link_request( self, session: AsyncSession, external_user_id: str, switch_user_id: str ) -> ExternalUserLinkRequest | None: - return await session.get( - ExternalUserLinkRequest, (external_user_id, switch_user_id) + result = await session.execute( + select(ExternalUserLinkRequest).where( + ExternalUserLinkRequest.external_user_id == external_user_id, + ExternalUserLinkRequest.user_id == switch_user_id, + ExternalUserLinkRequest.tenant_id == require_tenant_id(), + ) ) + return result.scalar_one_or_none() async def lock_link_request( self, session: AsyncSession, external_user_id: str, switch_user_id: str @@ -446,6 +452,7 @@ async def lock_link_request( .where( ExternalUserLinkRequest.external_user_id == external_user_id, ExternalUserLinkRequest.user_id == switch_user_id, + ExternalUserLinkRequest.tenant_id == require_tenant_id(), ) .with_for_update() .execution_options(populate_existing=True) diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.py index f2975e58b7..99a6cdbc19 100644 --- a/core/switch_core/gateway/collaborations.py +++ b/core/switch_core/gateway/collaborations.py @@ -105,6 +105,7 @@ from switch_core.telemetry.people import as_person, hours_since from switch_core.telemetry.service import emit_after_commit from switch_core.telemetry.snapshot import normalise_platform +from switch_core.tenant_context import current_tenant_id logger = logging.getLogger(__name__) @@ -1278,7 +1279,10 @@ async def _identity_on_bridge( external_user is None or external_user.bridge_id != bridge_id or ( - getattr(external_user, "tenant_id", None) is not None + ( + isinstance(external_user, ExternalUser) + or getattr(external_user, "tenant_id", None) is not None + ) and external_user.tenant_id != require_tenant_id() ) ): @@ -1691,16 +1695,33 @@ async def cancel_identity_link_request( `release_bridge_identity`. """ viewer = Principal(user.id, is_admin) - if ( - bridge_store is not _BRIDGE_STORE or hasattr(session, "execute") - ) and await bridge_store.get(session, bridge_id) is None: + bridge = ( + await bridge_store.get(session, bridge_id) + if bridge_store is not _BRIDGE_STORE + or (hasattr(session, "execute") and current_tenant_id() is not None) + else _BRIDGE_STORE + ) + if bridge is None: raise HTTPException(status_code=404, detail="Bridge not found") external_user = await _identity_on_bridge( session, external_user_store, bridge_id, external_user_row_id ) + bridge_tenant_id = getattr(bridge, "tenant_id", None) + if isinstance(bridge_tenant_id, str) and bridge_tenant_id != require_tenant_id(): + raise HTTPException(status_code=404, detail="Bridge not found") target_user_id = _require_self_or_admin( user, is_admin, user_id, "cancel a link to a messaging identity" ) + if ( + target_user_id != user.id + and hasattr(user_store, "effective_tenant_role") + and (current_tenant_id() is not None or not isinstance(user_store, UserStore)) + and await user_store.effective_tenant_role( + session, require_tenant_id(), target_user_id + ) + is None + ): + raise HTTPException(status_code=404, detail="Switch user not found") try: await external_user_store.cancel_link_request( session, external_user, target_user_id @@ -1748,16 +1769,33 @@ async def release_bridge_identity( be confirmed — your own, or someone else's if you are an admin. Anyone else's claim on the same account is left standing.""" viewer = Principal(user.id, is_admin) - if ( - bridge_store is not _BRIDGE_STORE or hasattr(session, "execute") - ) and await bridge_store.get(session, bridge_id) is None: + bridge = ( + await bridge_store.get(session, bridge_id) + if bridge_store is not _BRIDGE_STORE + or (hasattr(session, "execute") and current_tenant_id() is not None) + else _BRIDGE_STORE + ) + if bridge is None: raise HTTPException(status_code=404, detail="Bridge not found") external_user = await _identity_on_bridge( session, external_user_store, bridge_id, external_user_row_id ) + bridge_tenant_id = getattr(bridge, "tenant_id", None) + if isinstance(bridge_tenant_id, str) and bridge_tenant_id != require_tenant_id(): + raise HTTPException(status_code=404, detail="Bridge not found") target_user_id = _require_self_or_admin( user, is_admin, user_id, "release a messaging identity" ) + if ( + target_user_id != user.id + and hasattr(user_store, "effective_tenant_role") + and (current_tenant_id() is not None or not isinstance(user_store, UserStore)) + and await user_store.effective_tenant_role( + session, require_tenant_id(), target_user_id + ) + is None + ): + raise HTTPException(status_code=404, detail="Switch user not found") try: released = await external_user_store.release( diff --git a/core/tests/switch_core/gateway/test_collaborations_authz.py b/core/tests/switch_core/gateway/test_collaborations_authz.py index 5a9390ec30..310b8c9565 100644 --- a/core/tests/switch_core/gateway/test_collaborations_authz.py +++ b/core/tests/switch_core/gateway/test_collaborations_authz.py @@ -185,6 +185,21 @@ async def test_releasing_another_users_claim_is_refused(self) -> None: ) assert excinfo.value.status_code == 403 + async def test_cancelling_another_users_request_is_refused(self) -> None: + theirs = SimpleNamespace(id="ext-1", bridge_id="b1") + with pytest.raises(HTTPException) as excinfo: + await cancel_identity_link_request( + bridge_id="b1", + external_user_row_id="ext-1", + session=object(), # type: ignore[arg-type] + external_user_store=_StubGet(theirs), # type: ignore[arg-type] + user_store=_StubGet(None), # type: ignore[arg-type] + user=_user(id="me", role="user"), + is_admin=False, + user_id="someone-else", + ) + assert excinfo.value.status_code == 403 + class TestProvisioningNeedsARealAccount: """Claiming an account Switch has not seen mints a Matrix human actor, and the @@ -702,6 +717,127 @@ async def test_cancel_identity_link_request_cross_tenant_bridge_returns_404() -> external_user_store.cancel_link_request.assert_not_called() +@pytest.mark.asyncio +async def test_cancel_identity_link_request_cross_tenant_external_user_returns_404() -> ( + None +): + bridge_store = AsyncMock() + bridge_store.get.return_value = CollaborationBridge( + id="bridge-tenant-b", + tenant_id="tenant-b", + type="mattermost", + display_name="MM", + ) + external_user_store = AsyncMock() + external_user_store.get.return_value = ExternalUser( + id="ext-user-tenant-b", + tenant_id="tenant-b", + bridge_id="bridge-tenant-b", + external_user_id="U123", + external_username="user", + client_id="client-1", + ) + mock_session = AsyncMock() + with tenant_scope("tenant-a"): + with pytest.raises(HTTPException) as exc: + await cancel_identity_link_request( + bridge_id="bridge-tenant-b", + external_user_row_id="ext-user-tenant-b", + session=mock_session, + external_user_store=external_user_store, + user_store=AsyncMock(), + user=_admin(), + is_admin=True, + user_id="usr-tenant-b", + bridge_store=bridge_store, + ) + assert exc.value.status_code == 404 + assert exc.value.detail == "Identity not found" + external_user_store.cancel_link_request.assert_not_called() + + +@pytest.mark.asyncio +async def test_cancel_identity_link_request_cross_tenant_user_returns_404() -> None: + bridge_store = AsyncMock() + bridge_store.get.return_value = CollaborationBridge( + id="bridge-tenant-a", + tenant_id="tenant-a", + type="mattermost", + display_name="MM", + ) + external_user_store = AsyncMock() + external_user_store.get.return_value = ExternalUser( + id="ext-user-tenant-a", + tenant_id="tenant-a", + bridge_id="bridge-tenant-a", + external_user_id="U123", + external_username="user", + client_id="client-1", + ) + user_store = AsyncMock() + user_store.effective_tenant_role.return_value = None + mock_session = AsyncMock() + with tenant_scope("tenant-a"): + with pytest.raises(HTTPException) as exc: + await cancel_identity_link_request( + bridge_id="bridge-tenant-a", + external_user_row_id="ext-user-tenant-a", + session=mock_session, + external_user_store=external_user_store, + user_store=user_store, + user=_admin(), + is_admin=True, + user_id="usr-tenant-b", + bridge_store=bridge_store, + ) + assert exc.value.status_code == 404 + assert exc.value.detail == "Switch user not found" + external_user_store.cancel_link_request.assert_not_called() + + +async def test_cancel_identity_link_request_cross_tenant_bridge_is_404( + session_factory: async_sessionmaker[AsyncSession], +) -> None: + 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.commit() + + async with tenant_session(session_factory, other_tenant) as other_session: + other_bridge = await _make_bridge(other_session, is_default=False) + ext_client = Client( + transport_user_id=f"@ext-{uuid.uuid4().hex[:12]}:test", + display_name="ext client", + type="external_user", + ) + other_session.add(ext_client) + await other_session.flush() + other_ext_user = ExternalUser( + bridge_id=other_bridge, + external_user_id="U-other", + external_username="other", + client_id=ext_client.id, + ) + other_session.add(other_ext_user) + await other_session.commit() + other_ext_user_id = other_ext_user.id + + async with session_factory() as session: + with pytest.raises(HTTPException) as exc: + await cancel_identity_link_request( + other_bridge, + other_ext_user_id, + session, + ExternalUserStore(), + AsyncMock(), + _admin(), + True, + "usr-other", + _BRIDGE_STORE, + ) + assert exc.value.status_code == 404 + + async def test_release_bridge_identity_cross_tenant_bridge_is_404( session_factory: async_sessionmaker[AsyncSession], ) -> None: From 5bf055260cd76c4980a215415d70030e06ecab0c Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:40:11 +0000 Subject: [PATCH 18/26] fix(security): Flawed Row Lock Mode in lock_workspace_allowance Enabl... --- .../switch_core/gateway/workspace_creation.py | 5 +- .../gateway/test_organization_routes.py | 50 +++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/core/switch_core/gateway/workspace_creation.py b/core/switch_core/gateway/workspace_creation.py index 50f4f0638e..251a5c65a4 100644 --- a/core/switch_core/gateway/workspace_creation.py +++ b/core/switch_core/gateway/workspace_creation.py @@ -230,7 +230,10 @@ async def lock_workspace_allowance( user = await session.scalar( select(User) .where(User.id == user_id) - .with_for_update(key_share=True, nowait=True) + # In SQLAlchemy's PostgreSQL dialect, `read=False, key_share=True` + # renders `FOR NO KEY UPDATE` (whereas `read=True, key_share=True` + # renders `FOR KEY SHARE`). + .with_for_update(read=False, key_share=True, nowait=True) # The row may already be loaded on this session, read before the # lock was taken. .execution_options(populate_existing=True) diff --git a/core/tests/switch_core/gateway/test_organization_routes.py b/core/tests/switch_core/gateway/test_organization_routes.py index f6fd6df00c..0dc808cbdd 100644 --- a/core/tests/switch_core/gateway/test_organization_routes.py +++ b/core/tests/switch_core/gateway/test_organization_routes.py @@ -1022,6 +1022,56 @@ async def test_it_counts_against_the_creator_allowance( assert first.status_code == 201, first.text assert second.status_code == 403 + async def test_concurrent_workspace_requests_cannot_exceed_allowance( + self, session_factory: async_sessionmaker[AsyncSession] + ) -> None: + ada = _name("ada") + tenant_id = await _workspace(session_factory, {ada: ("admin", "org_admin")}) + + app = _app( + session_factory, + max_workspaces_per_user=1, + one_organization_one_workspace=False, + ) + async with _client(app, ada, tenant_id) as client: + responses = await asyncio.gather( + *( + client.post( + "/organizations/current/workspaces", + json={"name": f"Burst {i}"}, + ) + for i in range(5) + ) + ) + + codes = sorted(r.status_code for r in responses) + assert codes.count(201) == 1 + assert set(codes) - {201} <= {403, 409} + assert await _workspaces_created(session_factory, ada) == 1 + + async def test_concurrent_organization_requests_cannot_exceed_allowance( + self, session_factory: async_sessionmaker[AsyncSession] + ) -> None: + ada = await _user(session_factory, "user") + + app = _app(session_factory, max_workspaces_per_user=1) + async with _client(app, ada, None) as client: + responses = await asyncio.gather( + *( + client.post( + "/organizations", + json={"name": f"Org {i}", "workspace_name": f"Workspace {i}"}, + ) + for i in range(5) + ) + ) + + codes = sorted(r.status_code for r in responses) + assert codes.count(201) == 1 + assert set(codes) - {201} <= {403, 409} + assert await _organizations_created(session_factory, ada) == 1 + assert await _workspaces_created(session_factory, ada) == 1 + async def _organizations_created( session_factory: async_sessionmaker[AsyncSession], user_id: str From 5cdc1f2a88c2c79115cbec1405a7c10f78e619c0 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:00:14 +0000 Subject: [PATCH 19/26] fix(security): Non-Conflicting Lock Mode in ensure_default_workspace ... --- .../switch_core/gateway/workspace_creation.py | 6 +- .../switch_core/test_workspace_creation.py | 64 ++++++++++++++++++- 2 files changed, 66 insertions(+), 4 deletions(-) diff --git a/core/switch_core/gateway/workspace_creation.py b/core/switch_core/gateway/workspace_creation.py index 251a5c65a4..d9458eab9f 100644 --- a/core/switch_core/gateway/workspace_creation.py +++ b/core/switch_core/gateway/workspace_creation.py @@ -936,7 +936,11 @@ async def ensure_default_workspace( organization = await session.scalar( select(Organization) .where(Organization.id == organization_id) - .with_for_update(key_share=True, skip_locked=not wait_for_lock) + # In SQLAlchemy's PostgreSQL dialect, `read=False, key_share=True` + # renders `FOR NO KEY UPDATE` (whereas `read=True, key_share=True` + # renders `FOR KEY SHARE`). + .with_for_update(read=False, key_share=True, skip_locked=not wait_for_lock) + .execution_options(populate_existing=True) ) if organization is None or organization.workos_organization_id is None: return None diff --git a/core/tests/switch_core/test_workspace_creation.py b/core/tests/switch_core/test_workspace_creation.py index 3420722c29..7d893e9928 100644 --- a/core/tests/switch_core/test_workspace_creation.py +++ b/core/tests/switch_core/test_workspace_creation.py @@ -6,11 +6,13 @@ import asyncio import uuid +from contextlib import asynccontextmanager from datetime import UTC, datetime -from typing import cast +from typing import Any, cast import pytest from sqlalchemy import select, text +from sqlalchemy.dialects import postgresql from sqlalchemy.exc import DBAPIError from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker @@ -27,6 +29,7 @@ ) from switch_core.db.session_scope import tenant_session from switch_core.db.stores.user_store import UserStore +from switch_core.gateway import workspace_creation from switch_core.gateway.workspace_creation import ensure_default_workspace from switch_core.organization_access import lock_organization_member from switch_core.organization_mirror import ensure_workspace_memberships @@ -337,7 +340,7 @@ async def test_a_held_lock_is_not_waited_for(self, rls_harness: RLSHarness) -> N await making.execute( select(Organization) .where(Organization.id == organization.id) - .with_for_update(key_share=True) + .with_for_update(read=False, key_share=True) ) made = await ensure_default_workspace( restricted, @@ -366,7 +369,7 @@ async def test_creating_the_organization_waits_and_makes_no_second( await signing_in.execute( select(Organization) .where(Organization.id == organization.id) - .with_for_update(key_share=True) + .with_for_update(read=False, key_share=True) ) creating = asyncio.create_task( ensure_default_workspace( @@ -389,6 +392,61 @@ async def test_creating_the_organization_waits_and_makes_no_second( assert made is None assert len(await _workspaces(owner, organization.id)) == 1 + @pytest.mark.parametrize( + ("wait_for_lock", "expected_clause"), + [ + (False, "FOR NO KEY UPDATE SKIP LOCKED"), + (True, "FOR NO KEY UPDATE"), + ], + ) + async def test_default_workspace_locks_organization_with_for_no_key_update( + self, + monkeypatch: pytest.MonkeyPatch, + wait_for_lock: bool, + expected_clause: str, + ) -> None: + captured_statements: list[Any] = [] + + class _FakeSession: + async def scalar(self, statement: Any) -> Organization | None: + captured_statements.append(statement) + return None + + @asynccontextmanager + async def _fake_organization_session(_factory: Any, _organization_id: str): + yield _FakeSession() + + async def _no_tenants(_factory: Any, _organization_id: str) -> list[str]: + return [] + + monkeypatch.setattr(workspace_creation, "tenants_of_organization", _no_tenants) + monkeypatch.setattr( + workspace_creation, + "organization_session", + _fake_organization_session, + ) + + made = await ensure_default_workspace( + cast(async_sessionmaker[AsyncSession], object()), + cast(ClientLifecycleService, object()), + UserStore(), + "org-123", + source="sign_in", + wait_for_lock=wait_for_lock, + actor_id=None, + ) + + assert made is None + assert len(captured_statements) == 1 + stmt = captured_statements[0] + assert stmt._for_update_arg is not None + assert stmt._for_update_arg.read is False + assert stmt._for_update_arg.key_share is True + assert stmt._for_update_arg.skip_locked is (not wait_for_lock) + sql = str(stmt.compile(dialect=postgresql.dialect())) + assert sql.endswith(expected_clause) + assert "FOR KEY SHARE" not in sql + class TestWorkspaceMemberships: async def test_org_members_get_a_member_row_in_each_open_workspace( From 66e39bdd93c18663af29064ccd390dee17cd062f Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:20:15 +0000 Subject: [PATCH 20/26] fix(security): Cross-Tenant Workspace Member Count Disclosure via Mis... --- core/switch_core/bridges/agent/operations/my_context.py | 6 +++++- core/tests/switch_core/management/test_my_context.py | 5 ++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/core/switch_core/bridges/agent/operations/my_context.py b/core/switch_core/bridges/agent/operations/my_context.py index 6bbabe807d..1f9558a9d1 100644 --- a/core/switch_core/bridges/agent/operations/my_context.py +++ b/core/switch_core/bridges/agent/operations/my_context.py @@ -156,7 +156,11 @@ async def get_my_context() -> dict[str, Any]: role = await protocol.user_store.effective_tenant_role( session, tenant_id, owner.id ) - members = await session.scalar(select(func.count()).select_from(TenantMember)) + members = await session.scalar( + select(func.count()) + .select_from(TenantMember) + .where(TenantMember.tenant_id == tenant_id) + ) agents = await protocol.agent_store.get_by_owner(session, owner.id) usernames_by_bridge: dict[str, list[str]] = {} link_by_bridge: dict[str, str] = {} diff --git a/core/tests/switch_core/management/test_my_context.py b/core/tests/switch_core/management/test_my_context.py index dbaef239ec..27eaa162f6 100644 --- a/core/tests/switch_core/management/test_my_context.py +++ b/core/tests/switch_core/management/test_my_context.py @@ -372,6 +372,7 @@ async def _another_workspace_with_a_bridge(harness: Harness) -> str: async with harness.session_factory() as session: session.add(Tenant(id="tenant-other", slug="other", name="Other")) await session.commit() + await add_member(harness.session_factory, "other-member", "tenant-other") async with tenant_session(harness.session_factory, "tenant-other") as session: client = Client( type="bridge", @@ -398,8 +399,10 @@ async def test_it_lists_only_its_own_workspaces_messaging_apps( buddy_id, key, _ = await _setup(harness) other_bridge_id = await _another_workspace_with_a_bridge(harness) - apps = (await _context(client, buddy_id, key))["messaging_apps"] + context = await _context(client, buddy_id, key) + apps = context["messaging_apps"] + assert context["workspace"]["members"] == 1 assert sorted(app["name"] for app in apps["connected"]) == [ "Acme Discord", "Acme Slack", From a777f8cced8b2a2066a721f69aace03f6fc4869f Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:40:18 +0000 Subject: [PATCH 21/26] fix(security): Unhandled Silence Watchdog in Waiting/Lost State Allow... --- .../src/box/launcher-link.test.ts | 30 +++++++++++++++++++ .../agent-controller/src/box/launcher-link.ts | 10 +++++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/console/packages/agent-controller/src/box/launcher-link.test.ts b/console/packages/agent-controller/src/box/launcher-link.test.ts index c95c440849..b87f2bc735 100644 --- a/console/packages/agent-controller/src/box/launcher-link.test.ts +++ b/console/packages/agent-controller/src/box/launcher-link.test.ts @@ -109,6 +109,36 @@ describe('LauncherLink', () => { expect(logged).toContainEqual(['launcher_refused', { reason: 'no_hello' }]); }); + it('drops a connection that never says hello after 30 s so the real launcher can connect', async () => { + // No socket yet: ticking in waiting state stays waiting. + clock += LOST_AFTER_MS; + link.tick(); + expect(link.current).toBe('waiting'); + + // A squatter connects while in waiting state and never sends hello. + const squatter1 = await launcher(); + clock += QUIET_AFTER_MS; + link.tick(); + expect(link.current).toBe('waiting'); + clock += LOST_AFTER_MS - QUIET_AFTER_MS; + link.tick(); + expect(link.current).toBe('lost'); + await squatter1.closed; + + // A second squatter connects while in lost state and never sends hello. + const squatter2 = await launcher(); + clock += LOST_AFTER_MS; + link.tick(); + await squatter2.closed; + + // The legitimate launcher can now connect and become live. + const real = await launcher(); + real.send(hello() + measure()); + await tick(); + expect(link.current).toBe('live'); + real.socket.destroy(); + }); + it('matches replies to orders, and fails orders at once when the launcher is lost', async () => { const l = await launcher(); l.send(hello()); diff --git a/console/packages/agent-controller/src/box/launcher-link.ts b/console/packages/agent-controller/src/box/launcher-link.ts index 0d38fafdc1..f53a270faa 100644 --- a/console/packages/agent-controller/src/box/launcher-link.ts +++ b/console/packages/agent-controller/src/box/launcher-link.ts @@ -165,11 +165,11 @@ export class LauncherLink { * launcher that stopped measuring, or never started, goes quiet then lost. */ tick(): void { - if (this.state === 'waiting' || this.state === 'lost') return; + if (!this.socket) return; const since = this.lastMeasureAt ?? this.connectedAt ?? this.deps.now(); const silent = this.deps.now() - since; if (silent >= LOST_AFTER_MS) this.lose('silent'); - else if (silent >= QUIET_AFTER_MS) this.setState('quiet'); + else if (silent >= QUIET_AFTER_MS && this.state === 'live') this.setState('quiet'); } /** Sends an order and waits for its reply; a lost link or no answer in time is a failed reply. */ @@ -288,7 +288,11 @@ export class LauncherLink { resolve({ kind: 'reply', id, ok: false, code: 'launcher_lost' }); } this.pending.clear(); - if (reason === 'silent') this.socket?.destroy(); + if (reason === 'silent') { + const socket = this.socket; + this.socket = null; + socket?.destroy(); + } this.setState('lost'); } From 8f5be816fb8baefd5faa765110441d80b4f553c8 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:00:17 +0000 Subject: [PATCH 22/26] fix(security): DOM-based Cross-Site Scripting (XSS) via javascript: U... --- gateway/src/data/channelLinks.test.ts | 16 ++++++++++++++++ gateway/src/data/channelLinks.ts | 26 +++++++++++++++++++++++--- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/gateway/src/data/channelLinks.test.ts b/gateway/src/data/channelLinks.test.ts index 282b31e63b..1f6673cb0a 100644 --- a/gateway/src/data/channelLinks.test.ts +++ b/gateway/src/data/channelLinks.test.ts @@ -14,6 +14,11 @@ describe("linkTargetFor", () => { // A new tab would be left behind empty once the app takes the link. expect(linkTargetFor("discord://-/channels/1/2")).toEqual({ href: "discord://-/channels/1/2" }); }); + + it("rejects links with unsafe or unknown schemes", () => { + expect(linkTargetFor("javascript:alert(document.domain)")).toEqual({}); + expect(linkTargetFor("data:text/html,")).toEqual({}); + }); }); describe("openChannelLink", () => { @@ -37,4 +42,15 @@ describe("openChannelLink", () => { expect(open).toHaveBeenCalledWith("https://matrix.to/#/!room:example.com", "_blank", "noopener,noreferrer"); }); + + it("refuses to navigate to unsafe schemes such as javascript:", () => { + const assign = vi.fn(); + vi.spyOn(window, "location", "get").mockReturnValue({ ...window.location, assign }); + const open = vi.spyOn(window, "open").mockReturnValue(null); + + openChannelLink("javascript:alert(document.domain)"); + + expect(assign).not.toHaveBeenCalled(); + expect(open).not.toHaveBeenCalled(); + }); }); diff --git a/gateway/src/data/channelLinks.ts b/gateway/src/data/channelLinks.ts index 43695839d5..c95b3e8c69 100644 --- a/gateway/src/data/channelLinks.ts +++ b/gateway/src/data/channelLinks.ts @@ -1,12 +1,31 @@ -import { webPageChannelLinks } from "@switch-console/chat-ui/model/channel-links"; +import { + type ChannelAppScheme, + webPageChannelLinks, +} from "@switch-console/chat-ui/model/channel-links"; + +const APP_SCHEMES: ReadonlySet = new Set([ + "slack", + "discord", + "msteams", + "tg", + "mattermost", +]); + +function isAppLink(href: string): boolean { + const scheme = /^([a-z]+):/i.exec(href)?.[1].toLowerCase(); + return scheme !== undefined && APP_SCHEMES.has(scheme); +} /** * Attributes for a link to `href`: a web page opens in a new tab, while a * desktop app's own link stays in this one, which the app takes without * leaving the page (a new tab would be left behind empty). */ -export function linkTargetFor(href: string): { href: string; target?: "_blank"; rel?: string } { - return /^https?:\/\//i.test(href) ? { href, target: "_blank", rel: "noopener noreferrer" } : { href }; +export function linkTargetFor(href: string): { href?: string; target?: "_blank"; rel?: string } { + if (/^https?:\/\//i.test(href)) { + return { href, target: "_blank", rel: "noopener noreferrer" }; + } + return isAppLink(href) ? { href } : {}; } /** @@ -16,6 +35,7 @@ export function linkTargetFor(href: string): { href: string; target?: "_blank"; */ export function openChannelLink(link: string): void { const { href, target } = linkTargetFor(webPageChannelLinks(link).primary); + if (!href) return; if (target) window.open(href, target, "noopener,noreferrer"); else window.location.assign(href); } From 372ba52c332ca26104362b2612b8476ef0bfc2ed Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:20:18 +0000 Subject: [PATCH 23/26] fix(security): Missing Tenant Filtering in Support Request Daily Rate... --- core/switch_core/gateway/support.py | 10 ++++- .../gateway/test_support_requests.py | 39 ++++++++++++++++++- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/core/switch_core/gateway/support.py b/core/switch_core/gateway/support.py index ab4c3fec7e..83763a8763 100644 --- a/core/switch_core/gateway/support.py +++ b/core/switch_core/gateway/support.py @@ -116,9 +116,15 @@ def _wait( async def _sent_since( - session: AsyncSession, since: datetime, *, user_id: str | None = None + session: AsyncSession, + since: datetime, + *, + tenant_id: str | None = None, + user_id: str | None = None, ) -> list[datetime]: query = select(SupportRequest.created_at).where(SupportRequest.created_at > since) + if tenant_id is not None: + query = query.where(SupportRequest.tenant_id == tenant_id) if user_id is not None: query = query.where(SupportRequest.user_id == user_id) return list(await session.scalars(query.order_by(SupportRequest.created_at))) @@ -145,7 +151,7 @@ async def _admit( "to support in the last hour.", ) ) - workspace = await _sent_since(session, now - _DAY) + workspace = await _sent_since(session, now - _DAY, tenant_id=tenant_id) wait = _wait(workspace, config.gateway_support_requests_per_day, _DAY, now) if wait is not None: refusals.append( diff --git a/core/tests/switch_core/gateway/test_support_requests.py b/core/tests/switch_core/gateway/test_support_requests.py index f1474f9660..3584556734 100644 --- a/core/tests/switch_core/gateway/test_support_requests.py +++ b/core/tests/switch_core/gateway/test_support_requests.py @@ -19,7 +19,8 @@ from sqlalchemy import func, select, update from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker -from switch_core.db.models import SupportRequest, User +from switch_core.db.models import SupportRequest, Tenant, User +from switch_core.db.session_scope import tenant_session from switch_core.db.stores.user_store import UserStore from switch_core.gateway import dependencies as gw_deps from switch_core.gateway.auth import create_jwt @@ -87,8 +88,22 @@ async def _session_dep(): async def _seed_user( - session_factory: async_sessionmaker[AsyncSession], name: str = "Ada" + session_factory: async_sessionmaker[AsyncSession], + name: str = "Ada", + *, + tenant_id: str | None = None, ) -> str: + if tenant_id is not None: + async with tenant_session(session_factory, tenant_id) 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() + user = User( + name=name, email=f"{secrets.token_hex(4)}@example.invalid", role="user" + ) + await _USER_STORE.create(session, user) + await session.commit() + return user.id async with session_factory() as session: user = User( name=name, email=f"{secrets.token_hex(4)}@example.invalid", role="user" @@ -299,6 +314,26 @@ async def test_the_workspace_may_send_so_many_a_day( assert "daily limit of 2" in refused.json()["detail"] assert "Try again in 22 hours" in refused.json()["detail"] + async def test_another_workspace_is_not_held_to_someone_elses_daily_limit( + self, session_factory: async_sessionmaker[AsyncSession] + ) -> None: + ada = await _seed_user(session_factory, "Ada") + other = f"tenant-{secrets.token_hex(4)}" + grace = await _seed_user(session_factory, "Grace", tenant_id=other) + mailer = FakeMailer() + app = _app(session_factory, mailer, _config(per_hour=5, per_day=1)) + async with _client(app, ada) as client: + assert ( + await client.post("/support/requests", json=REQUEST) + ).status_code == 200 + assert ( + await client.post("/support/requests", json=REQUEST) + ).status_code == 429 + async with _client(app, grace) as client: + assert ( + await client.post("/support/requests", json=REQUEST) + ).status_code == 200 + async def test_requests_sent_at_once_are_counted_exactly( self, session_factory: async_sessionmaker[AsyncSession] ) -> None: From 5d348aeeb79aab4d1d70b77773f28cf0ea0f12e2 Mon Sep 17 00:00:00 2001 From: Switch Security Agent <265052130+p15r-sb@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:40:09 +0000 Subject: [PATCH 24/26] fix(security): Unrestricted Worker Security Group Egress Due to Retai... --- deploy/hosted/terraform/main.tf | 7 ++----- deploy/hosted/terraform/tests/plan.tftest.hcl | 4 ++++ 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/deploy/hosted/terraform/main.tf b/deploy/hosted/terraform/main.tf index 758cc93fc5..f5d23724d8 100644 --- a/deploy/hosted/terraform/main.tf +++ b/deploy/hosted/terraform/main.tf @@ -13,11 +13,8 @@ resource "aws_security_group" "worker" { name_prefix = "${local.prefix}-" description = "Isolated hosted workers: no inbound access; HTTP(S) egress" vpc_id = aws_vpc.worker.id - # No inline `egress` here: egress is managed by the standalone - # aws_vpc_security_group_egress_rule resources, and setting it inline (even - # to []) makes this resource strip those rules on every other apply. - # The provider already removes AWS's default allow-all egress on create. - # egress = [] + ingress = [] + egress = [] tags = local.tags } resource "aws_vpc_security_group_egress_rule" "worker" { diff --git a/deploy/hosted/terraform/tests/plan.tftest.hcl b/deploy/hosted/terraform/tests/plan.tftest.hcl index 7d003b7354..41fa08b543 100644 --- a/deploy/hosted/terraform/tests/plan.tftest.hcl +++ b/deploy/hosted/terraform/tests/plan.tftest.hcl @@ -101,6 +101,10 @@ run "rendered_permissions" { condition = length(aws_security_group.worker.ingress) == 0 error_message = "Workers must not expose inbound ports." } + assert { + condition = length(aws_security_group.worker.egress) == 0 && toset([for rule in aws_vpc_security_group_egress_rule.worker : "${rule.ip_protocol}:${rule.from_port}-${rule.to_port}"]) == toset(["tcp:80-80", "tcp:443-443"]) + error_message = "Workers must remove default egress and allow only HTTP(S) egress." + } assert { condition = length(aws_security_group.isolation.ingress) == 0 && length(aws_security_group.isolation.egress) == 0 error_message = "The isolation group must allow no traffic either way." From d1f9b9ed9698b2b50195b70e37147c70a002cbf8 Mon Sep 17 00:00:00 2001 From: Petr Bauch <210346493+petr-sandbox@users.noreply.github.com> Date: Sun, 6 Dec 2026 06:46:48 +0100 Subject: [PATCH 25/26] Fix review findings on the codemender security changes - Terraform: keep worker egress on the standalone rules only (inline egress = [] stripped them every other apply) and restore the IMDSv2 deny to StringNotEquals. - windows-spawn: refuse only %VAR% references; a lone % is caret-escaped. - decision: drop evicted Anthropic clients instead of closing them under in-flight requests. - launcher-link: a connection that never says hello is dropped without reporting the launcher lost. - workspace_creation: remove the no-op read=False and its comments. - channelLinks: a refused channel link warns or raises instead of doing nothing. - collaborations: make bridge_store required and run the bridge, tenant and membership checks unconditionally. Co-Authored-By: Claude Opus 5.5 --- .../src/box/launcher-link.test.ts | 6 ++- .../agent-controller/src/box/launcher-link.ts | 9 +++- .../packages/shared/src/windows-spawn.test.ts | 20 +++++--- console/packages/shared/src/windows-spawn.ts | 14 +++--- core/switch_core/gateway/collaborations.py | 49 +++---------------- .../switch_core/gateway/workspace_creation.py | 10 +--- .../gateway/test_collaborations_authz.py | 47 +++++++++--------- .../test_identity_link_confirmation.py | 8 +++ .../switch_core/test_workspace_creation.py | 4 +- decision/switch_decision/backends.py | 16 ++---- decision/tests/test_api.py | 7 +-- deploy/hosted/terraform/main.tf | 9 ++-- deploy/hosted/terraform/tests/plan.tftest.hcl | 6 +-- gateway/src/data/channelLinks.test.ts | 6 ++- gateway/src/data/channelLinks.ts | 6 ++- 15 files changed, 99 insertions(+), 118 deletions(-) diff --git a/console/packages/agent-controller/src/box/launcher-link.test.ts b/console/packages/agent-controller/src/box/launcher-link.test.ts index b87f2bc735..900592dc03 100644 --- a/console/packages/agent-controller/src/box/launcher-link.test.ts +++ b/console/packages/agent-controller/src/box/launcher-link.test.ts @@ -122,14 +122,16 @@ describe('LauncherLink', () => { expect(link.current).toBe('waiting'); clock += LOST_AFTER_MS - QUIET_AFTER_MS; link.tick(); - expect(link.current).toBe('lost'); await squatter1.closed; + // No launcher ever said hello, so none is reported lost. + expect(link.current).toBe('waiting'); + expect(logged).not.toContainEqual(['launcher_lost', expect.anything()]); - // A second squatter connects while in lost state and never sends hello. const squatter2 = await launcher(); clock += LOST_AFTER_MS; link.tick(); await squatter2.closed; + expect(link.current).toBe('waiting'); // The legitimate launcher can now connect and become live. const real = await launcher(); diff --git a/console/packages/agent-controller/src/box/launcher-link.ts b/console/packages/agent-controller/src/box/launcher-link.ts index f53a270faa..8f36928c56 100644 --- a/console/packages/agent-controller/src/box/launcher-link.ts +++ b/console/packages/agent-controller/src/box/launcher-link.ts @@ -168,7 +168,14 @@ export class LauncherLink { if (!this.socket) return; const since = this.lastMeasureAt ?? this.connectedAt ?? this.deps.now(); const silent = this.deps.now() - since; - if (silent >= LOST_AFTER_MS) this.lose('silent'); + if (silent >= LOST_AFTER_MS && (this.state === 'waiting' || this.state === 'lost')) { + // Connected but never said hello: no launcher was found, so none is lost. + // Free the slot for the real one and leave the state as it is. + const socket = this.socket; + this.socket = null; + this.deps.log('launcher_refused', { reason: 'no_hello' }); + socket.destroy(); + } else if (silent >= LOST_AFTER_MS) this.lose('silent'); else if (silent >= QUIET_AFTER_MS && this.state === 'live') this.setState('quiet'); } diff --git a/console/packages/shared/src/windows-spawn.test.ts b/console/packages/shared/src/windows-spawn.test.ts index 8281bc90a4..1d6f9f838e 100644 --- a/console/packages/shared/src/windows-spawn.test.ts +++ b/console/packages/shared/src/windows-spawn.test.ts @@ -46,8 +46,9 @@ describe('escapeCmdExeCommand', () => { }); it('refuses a program path with percent expansion', () => { - for (const command of ['C:\\%USERNAME%\\npm.cmd', 'C:\\%1\\npm.cmd']) - expect(() => escapeCmdExeCommand(command)).toThrow(CmdExePercentExpansionError); + expect(() => escapeCmdExeCommand('C:\\%USERNAME%\\npm.cmd')).toThrow( + CmdExePercentExpansionError + ); }); }); @@ -63,7 +64,16 @@ describe('escapeCmdExeArgument', () => { expect(() => escapeCmdExeArgument(argument)).toThrow(CmdExeLineBreakError); }); - it('refuses an argument with percent variable or parameter expansion', () => { + it('caret-escapes a percent sign that is not a variable reference', () => { + expect(escapeCmdExeArgument('a%20b')).toBe('^^^"a^^^%20b^^^"'); + expect(escapeCmdExeArgument('--format=%H')).toBe('^^^"--format^^^=^^^%H^^^"'); + expect(escapeCmdExeArgument('%1')).toBe('^^^"^^^%1^^^"'); + expect(escapeCmdExeArgument('50% off 20% more')).toBe( + '^^^"50^^^%^^^ off^^^ 20^^^%^^^ more^^^"' + ); + }); + + it('refuses an argument with a percent variable reference', () => { for (const argument of [ '%FOO%', '"%FOO%"', @@ -72,9 +82,6 @@ describe('escapeCmdExeArgument', () => { '%COMSPEC% & calc.exe & %', '%PATH:~0,5%', '%PATH:a=b%', - '%1', - '%*', - '%~dp0', ]) expect(() => escapeCmdExeArgument(argument)).toThrow(CmdExePercentExpansionError); }); @@ -198,7 +205,6 @@ describe('resolveExecFileSpawn', () => { ['%PATH%'], ['%FOO:~0,5%'], ['run', '%COMSPEC% & calc.exe & %'], - ['100%', '200%'], ]) { expect(() => resolveExecFileSpawn({ diff --git a/console/packages/shared/src/windows-spawn.ts b/console/packages/shared/src/windows-spawn.ts index 04fd55a30a..a7dda3d0de 100644 --- a/console/packages/shared/src/windows-spawn.ts +++ b/console/packages/shared/src/windows-spawn.ts @@ -68,11 +68,12 @@ const CMD_EXE_META = /([()\][%!^"`<>&|;, *?\t=])/g; const LINE_BREAK = /[\r\n]/; /** - * cmd.exe expands `%VAR%` (including `%VAR:~start,length%` and `%VAR:old=new%`) - * and batch parameters (`%0`–`%9`, `%*`, `%~…`) before processing carets or - * quotes, so caret escaping cannot suppress percent expansion. + * A `%VAR%` reference (including `%VAR:~start,length%` and `%VAR:old=new%`). + * cmd.exe expands these before it looks at carets or quotes. Batch parameters + * (`%1`, `%*`, `%~dp0`) are not expanded on a `/c` command line, and a lone `%` + * (`100%`, `%20`, `--format=%H`) is caret-escaped like any other metacharacter. */ -const PERCENT_EXPANSION = /%(?:.*%|[^ ])/; +const PERCENT_EXPANSION = /%[^%\s]+%/; /** Thrown for a value that cannot be put on a cmd.exe command line safely. */ export class CmdExeLineBreakError extends Error { @@ -84,7 +85,7 @@ export class CmdExeLineBreakError extends Error { } } -/** Thrown when a value could trigger cmd.exe percent variable or parameter expansion. */ +/** Thrown when a value holds a `%VAR%` reference cmd.exe would expand. */ export class CmdExePercentExpansionError extends Error { constructor(what: string) { super( @@ -218,9 +219,6 @@ export function resolveExecFileSpawn({ } const commandLine = [escapeCmdExeCommand(resolved), ...args.map(escapeCmdExeArgument)].join(' '); - if (PERCENT_EXPANSION.test([resolved, ...args].join(' '))) { - throw new CmdExePercentExpansionError('arguments'); - } return { command: getWindowsShellExecutable(env), args: ['/d', '/s', '/c', `"${commandLine}"`], diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.py index 99a6cdbc19..fd7fa5884e 100644 --- a/core/switch_core/gateway/collaborations.py +++ b/core/switch_core/gateway/collaborations.py @@ -105,14 +105,11 @@ from switch_core.telemetry.people import as_person, hours_since from switch_core.telemetry.service import emit_after_commit from switch_core.telemetry.snapshot import normalise_platform -from switch_core.tenant_context import current_tenant_id logger = logging.getLogger(__name__) router = APIRouter() -_BRIDGE_STORE = CollaborationBridgeStore() - async def _home_url( bridge_id: str, collab_lifecycle: CollaborationBridgeLifecycleService @@ -1278,13 +1275,7 @@ async def _identity_on_bridge( if ( external_user is None or external_user.bridge_id != bridge_id - or ( - ( - isinstance(external_user, ExternalUser) - or getattr(external_user, "tenant_id", None) is not None - ) - and external_user.tenant_id != require_tenant_id() - ) + or external_user.tenant_id != require_tenant_id() ): raise HTTPException(status_code=404, detail="Identity not found") return external_user @@ -1484,9 +1475,7 @@ async def verify_identity_with_session( ], user: Annotated[User, Depends(get_current_user)], is_admin: Annotated[bool, Depends(get_tenant_is_admin)], - bridge_store: Annotated[ - CollaborationBridgeStore, Depends(get_bridge_store) - ] = _BRIDGE_STORE, + bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)], ) -> ExternalUserSummary: """Confirm the caller's pending link with the account's own session token. @@ -1682,10 +1671,8 @@ async def cancel_identity_link_request( user_store: Annotated[UserStore, Depends(get_user_store)], user: Annotated[User, Depends(get_current_user)], is_admin: Annotated[bool, Depends(get_tenant_is_admin)], + bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)], user_id: str | None = None, - bridge_store: Annotated[ - CollaborationBridgeStore, Depends(get_bridge_store) - ] = _BRIDGE_STORE, ) -> ExternalUserSummary: """Stop waiting for the account to confirm a link (CHOO-3881) — your own, or someone else's if you are an admin. @@ -1695,27 +1682,16 @@ async def cancel_identity_link_request( `release_bridge_identity`. """ viewer = Principal(user.id, is_admin) - bridge = ( - await bridge_store.get(session, bridge_id) - if bridge_store is not _BRIDGE_STORE - or (hasattr(session, "execute") and current_tenant_id() is not None) - else _BRIDGE_STORE - ) - if bridge is None: + if await bridge_store.get(session, bridge_id) is None: raise HTTPException(status_code=404, detail="Bridge not found") external_user = await _identity_on_bridge( session, external_user_store, bridge_id, external_user_row_id ) - bridge_tenant_id = getattr(bridge, "tenant_id", None) - if isinstance(bridge_tenant_id, str) and bridge_tenant_id != require_tenant_id(): - raise HTTPException(status_code=404, detail="Bridge not found") target_user_id = _require_self_or_admin( user, is_admin, user_id, "cancel a link to a messaging identity" ) if ( target_user_id != user.id - and hasattr(user_store, "effective_tenant_role") - and (current_tenant_id() is not None or not isinstance(user_store, UserStore)) and await user_store.effective_tenant_role( session, require_tenant_id(), target_user_id ) @@ -1760,36 +1736,23 @@ async def release_bridge_identity( user_store: Annotated[UserStore, Depends(get_user_store)], user: Annotated[User, Depends(get_current_user)], is_admin: Annotated[bool, Depends(get_tenant_is_admin)], + bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)], user_id: str | None = None, - bridge_store: Annotated[ - CollaborationBridgeStore, Depends(get_bridge_store) - ] = _BRIDGE_STORE, ) -> ExternalUserSummary: """Drop a claim on a platform account, and any link to it still waiting to be confirmed — your own, or someone else's if you are an admin. Anyone else's claim on the same account is left standing.""" viewer = Principal(user.id, is_admin) - bridge = ( - await bridge_store.get(session, bridge_id) - if bridge_store is not _BRIDGE_STORE - or (hasattr(session, "execute") and current_tenant_id() is not None) - else _BRIDGE_STORE - ) - if bridge is None: + if await bridge_store.get(session, bridge_id) is None: raise HTTPException(status_code=404, detail="Bridge not found") external_user = await _identity_on_bridge( session, external_user_store, bridge_id, external_user_row_id ) - bridge_tenant_id = getattr(bridge, "tenant_id", None) - if isinstance(bridge_tenant_id, str) and bridge_tenant_id != require_tenant_id(): - raise HTTPException(status_code=404, detail="Bridge not found") target_user_id = _require_self_or_admin( user, is_admin, user_id, "release a messaging identity" ) if ( target_user_id != user.id - and hasattr(user_store, "effective_tenant_role") - and (current_tenant_id() is not None or not isinstance(user_store, UserStore)) and await user_store.effective_tenant_role( session, require_tenant_id(), target_user_id ) diff --git a/core/switch_core/gateway/workspace_creation.py b/core/switch_core/gateway/workspace_creation.py index d9458eab9f..3941e04f67 100644 --- a/core/switch_core/gateway/workspace_creation.py +++ b/core/switch_core/gateway/workspace_creation.py @@ -230,10 +230,7 @@ async def lock_workspace_allowance( user = await session.scalar( select(User) .where(User.id == user_id) - # In SQLAlchemy's PostgreSQL dialect, `read=False, key_share=True` - # renders `FOR NO KEY UPDATE` (whereas `read=True, key_share=True` - # renders `FOR KEY SHARE`). - .with_for_update(read=False, key_share=True, nowait=True) + .with_for_update(key_share=True, nowait=True) # The row may already be loaded on this session, read before the # lock was taken. .execution_options(populate_existing=True) @@ -936,10 +933,7 @@ async def ensure_default_workspace( organization = await session.scalar( select(Organization) .where(Organization.id == organization_id) - # In SQLAlchemy's PostgreSQL dialect, `read=False, key_share=True` - # renders `FOR NO KEY UPDATE` (whereas `read=True, key_share=True` - # renders `FOR KEY SHARE`). - .with_for_update(read=False, key_share=True, skip_locked=not wait_for_lock) + .with_for_update(key_share=True, skip_locked=not wait_for_lock) .execution_options(populate_existing=True) ) if organization is None or organization.workos_organization_id is None: diff --git a/core/tests/switch_core/gateway/test_collaborations_authz.py b/core/tests/switch_core/gateway/test_collaborations_authz.py index 310b8c9565..be9f2a0d54 100644 --- a/core/tests/switch_core/gateway/test_collaborations_authz.py +++ b/core/tests/switch_core/gateway/test_collaborations_authz.py @@ -43,6 +43,7 @@ from switch_core.db.stores.external_user_store import ExternalUserStore from switch_core.db.stores.messaging_install_store import MessagingInstallStore from switch_core.db.stores.room_store import RoomStore +from switch_core.db.stores.user_store import UserStore from switch_core.gateway.auth import get_current_user, require_tenant_admin from switch_core.gateway.collaborations import ( _claimants, @@ -171,8 +172,8 @@ async def test_claiming_for_another_user_is_refused(self) -> None: async def test_releasing_another_users_claim_is_refused(self) -> None: # Releasing names the claimant to drop; anyone else's claim on the same # account is not the caller's to touch. - theirs = SimpleNamespace(id="ext-1", bridge_id="b1") - with pytest.raises(HTTPException) as excinfo: + theirs = SimpleNamespace(id="ext-1", bridge_id="b1", tenant_id="tenant-a") + with tenant_scope("tenant-a"), pytest.raises(HTTPException) as excinfo: await release_bridge_identity( bridge_id="b1", external_user_row_id="ext-1", @@ -181,13 +182,14 @@ async def test_releasing_another_users_claim_is_refused(self) -> None: user_store=_StubGet(None), # type: ignore[arg-type] user=_user(id="me", role="user"), is_admin=False, + bridge_store=_StubGet(object()), # type: ignore[arg-type] user_id="someone-else", ) assert excinfo.value.status_code == 403 async def test_cancelling_another_users_request_is_refused(self) -> None: - theirs = SimpleNamespace(id="ext-1", bridge_id="b1") - with pytest.raises(HTTPException) as excinfo: + theirs = SimpleNamespace(id="ext-1", bridge_id="b1", tenant_id="tenant-a") + with tenant_scope("tenant-a"), pytest.raises(HTTPException) as excinfo: await cancel_identity_link_request( bridge_id="b1", external_user_row_id="ext-1", @@ -196,6 +198,7 @@ async def test_cancelling_another_users_request_is_refused(self) -> None: user_store=_StubGet(None), # type: ignore[arg-type] user=_user(id="me", role="user"), is_admin=False, + bridge_store=_StubGet(object()), # type: ignore[arg-type] user_id="someone-else", ) assert excinfo.value.status_code == 403 @@ -503,7 +506,7 @@ async def test_delete_cross_tenant_bridge_is_404( @pytest.mark.asyncio async def test_delete_cross_tenant_bridge_returns_404() -> None: - bridge_store = AsyncMock() + bridge_store = AsyncMock(spec=CollaborationBridgeStore) bridge_store.get.return_value = None mock_session = AsyncMock() with pytest.raises(HTTPException) as exc: @@ -523,9 +526,9 @@ async def test_delete_cross_tenant_bridge_returns_404() -> None: @pytest.mark.asyncio async def test_verify_identity_with_session_cross_tenant_bridge_returns_404() -> None: - bridge_store = AsyncMock() + bridge_store = AsyncMock(spec=CollaborationBridgeStore) bridge_store.get.return_value = None - external_user_store = AsyncMock() + external_user_store = AsyncMock(spec=ExternalUserStore) mock_session = AsyncMock() with tenant_scope("tenant-a"): with pytest.raises(HTTPException) as exc: @@ -550,14 +553,14 @@ async def test_verify_identity_with_session_cross_tenant_bridge_returns_404() -> async def test_verify_identity_with_session_cross_tenant_external_user_returns_404() -> ( None ): - bridge_store = AsyncMock() + bridge_store = AsyncMock(spec=CollaborationBridgeStore) bridge_store.get.return_value = CollaborationBridge( id="bridge-tenant-b", tenant_id="tenant-b", type="mattermost", display_name="MM", ) - external_user_store = AsyncMock() + external_user_store = AsyncMock(spec=ExternalUserStore) external_user_store.get.return_value = ExternalUser( id="ext-user-tenant-b", tenant_id="tenant-b", @@ -632,9 +635,9 @@ async def test_verify_identity_with_session_cross_tenant_bridge_is_404( @pytest.mark.asyncio async def test_release_bridge_identity_cross_tenant_bridge_returns_404() -> None: - bridge_store = AsyncMock() + bridge_store = AsyncMock(spec=CollaborationBridgeStore) bridge_store.get.return_value = None - external_user_store = AsyncMock() + external_user_store = AsyncMock(spec=ExternalUserStore) mock_session = AsyncMock() with tenant_scope("tenant-a"): with pytest.raises(HTTPException) as exc: @@ -657,14 +660,14 @@ async def test_release_bridge_identity_cross_tenant_bridge_returns_404() -> None @pytest.mark.asyncio async def test_release_bridge_identity_cross_tenant_external_user_returns_404() -> None: - bridge_store = AsyncMock() + bridge_store = AsyncMock(spec=CollaborationBridgeStore) bridge_store.get.return_value = CollaborationBridge( id="bridge-tenant-b", tenant_id="tenant-b", type="mattermost", display_name="MM", ) - external_user_store = AsyncMock() + external_user_store = AsyncMock(spec=ExternalUserStore) external_user_store.get.return_value = ExternalUser( id="ext-user-tenant-b", tenant_id="tenant-b", @@ -694,9 +697,9 @@ async def test_release_bridge_identity_cross_tenant_external_user_returns_404() @pytest.mark.asyncio async def test_cancel_identity_link_request_cross_tenant_bridge_returns_404() -> None: - bridge_store = AsyncMock() + bridge_store = AsyncMock(spec=CollaborationBridgeStore) bridge_store.get.return_value = None - external_user_store = AsyncMock() + external_user_store = AsyncMock(spec=ExternalUserStore) mock_session = AsyncMock() with tenant_scope("tenant-a"): with pytest.raises(HTTPException) as exc: @@ -721,14 +724,14 @@ async def test_cancel_identity_link_request_cross_tenant_bridge_returns_404() -> async def test_cancel_identity_link_request_cross_tenant_external_user_returns_404() -> ( None ): - bridge_store = AsyncMock() + bridge_store = AsyncMock(spec=CollaborationBridgeStore) bridge_store.get.return_value = CollaborationBridge( id="bridge-tenant-b", tenant_id="tenant-b", type="mattermost", display_name="MM", ) - external_user_store = AsyncMock() + external_user_store = AsyncMock(spec=ExternalUserStore) external_user_store.get.return_value = ExternalUser( id="ext-user-tenant-b", tenant_id="tenant-b", @@ -758,14 +761,14 @@ async def test_cancel_identity_link_request_cross_tenant_external_user_returns_4 @pytest.mark.asyncio async def test_cancel_identity_link_request_cross_tenant_user_returns_404() -> None: - bridge_store = AsyncMock() + bridge_store = AsyncMock(spec=CollaborationBridgeStore) bridge_store.get.return_value = CollaborationBridge( id="bridge-tenant-a", tenant_id="tenant-a", type="mattermost", display_name="MM", ) - external_user_store = AsyncMock() + external_user_store = AsyncMock(spec=ExternalUserStore) external_user_store.get.return_value = ExternalUser( id="ext-user-tenant-a", tenant_id="tenant-a", @@ -774,7 +777,7 @@ async def test_cancel_identity_link_request_cross_tenant_user_returns_404() -> N external_username="user", client_id="client-1", ) - user_store = AsyncMock() + user_store = AsyncMock(spec=UserStore) user_store.effective_tenant_role.return_value = None mock_session = AsyncMock() with tenant_scope("tenant-a"): @@ -832,8 +835,8 @@ async def test_cancel_identity_link_request_cross_tenant_bridge_is_404( AsyncMock(), _admin(), True, - "usr-other", _BRIDGE_STORE, + "usr-other", ) assert exc.value.status_code == 404 @@ -875,8 +878,8 @@ async def test_release_bridge_identity_cross_tenant_bridge_is_404( AsyncMock(), _admin(), True, - "usr-other", _BRIDGE_STORE, + "usr-other", ) assert exc.value.status_code == 404 diff --git a/core/tests/switch_core/gateway/test_identity_link_confirmation.py b/core/tests/switch_core/gateway/test_identity_link_confirmation.py index 7d1b6c268d..8a8f78cc32 100644 --- a/core/tests/switch_core/gateway/test_identity_link_confirmation.py +++ b/core/tests/switch_core/gateway/test_identity_link_confirmation.py @@ -223,6 +223,7 @@ async def _verify(world: _World, caller: User, adapter: _Adapter | None) -> obje _Lifecycle(adapter), # type: ignore[arg-type] caller, False, + CollaborationBridgeStore(), ) @@ -694,6 +695,7 @@ async def test_a_bots_own_session_cannot_confirm_a_link_to_it( _Lifecycle(_Adapter(_STAND_IN)), # type: ignore[arg-type] world.ada, False, + CollaborationBridgeStore(), ) assert refused.value.status_code == 409 @@ -726,6 +728,7 @@ async def test_unlinking_cancels_a_waiting_link(self, world: _World) -> None: UserStore(), world.ada, False, + CollaborationBridgeStore(), ) async with world.session_factory() as session: @@ -762,6 +765,7 @@ async def test_cancelling_a_confirmation_keeps_an_older_link( UserStore(), world.ada, False, + CollaborationBridgeStore(), ) claim = await _claim_of(world, world.ada) @@ -788,6 +792,7 @@ async def test_cancelling_with_nothing_waiting_is_a_404( UserStore(), world.ada, False, + CollaborationBridgeStore(), ) assert refused.value.status_code == 404 @@ -804,6 +809,7 @@ async def test_cancelling_someone_elses_takes_an_admin(self, world: _World) -> N UserStore(), world.bob, False, + CollaborationBridgeStore(), user_id=world.ada.id, ) assert refused.value.status_code == 403 @@ -822,6 +828,7 @@ async def test_unlinking_a_link_that_never_counted_is_audited_as_a_cancel( UserStore(), world.ada, False, + CollaborationBridgeStore(), ) async with world.session_factory() as session: @@ -846,6 +853,7 @@ async def test_unlinking_nothing_is_a_404(self, world: _World) -> None: UserStore(), world.ada, False, + CollaborationBridgeStore(), ) assert refused.value.status_code == 404 diff --git a/core/tests/switch_core/test_workspace_creation.py b/core/tests/switch_core/test_workspace_creation.py index 7d893e9928..c7bbd85734 100644 --- a/core/tests/switch_core/test_workspace_creation.py +++ b/core/tests/switch_core/test_workspace_creation.py @@ -340,7 +340,7 @@ async def test_a_held_lock_is_not_waited_for(self, rls_harness: RLSHarness) -> N await making.execute( select(Organization) .where(Organization.id == organization.id) - .with_for_update(read=False, key_share=True) + .with_for_update(key_share=True) ) made = await ensure_default_workspace( restricted, @@ -369,7 +369,7 @@ async def test_creating_the_organization_waits_and_makes_no_second( await signing_in.execute( select(Organization) .where(Organization.id == organization.id) - .with_for_update(read=False, key_share=True) + .with_for_update(key_share=True) ) creating = asyncio.create_task( ensure_default_workspace( diff --git a/decision/switch_decision/backends.py b/decision/switch_decision/backends.py index eb99581359..e37d592864 100644 --- a/decision/switch_decision/backends.py +++ b/decision/switch_decision/backends.py @@ -601,7 +601,6 @@ def read_anthropic(message: Any, options: list[str]) -> ModelAnswer: # a dict key that could end up in a log or a traceback. _MAX_ANTHROPIC_CLIENTS = 64 _anthropic_clients: dict[str, anthropic.AsyncAnthropic] = {} -_closing_clients: set[asyncio.Task[None]] = set() _SERVICE_KEY = "service" @@ -609,16 +608,6 @@ def key_fingerprint(api_key: str) -> str: return hashlib.sha256(api_key.encode()).hexdigest() -def _close_anthropic_client(client: anthropic.AsyncAnthropic) -> None: - try: - loop = asyncio.get_running_loop() - except RuntimeError: - return - task = loop.create_task(client.close()) - _closing_clients.add(task) - task.add_done_callback(_closing_clients.discard) - - def anthropic_client( settings: Settings, api_key: str | None = None ) -> anthropic.AsyncAnthropic: @@ -630,9 +619,10 @@ def anthropic_client( if api_key: kwargs["api_key"] = api_key client = anthropic.AsyncAnthropic(**kwargs) + # An evicted client is dropped, not closed: a request may still be + # awaiting it, and the SDK closes its connection pool once unreferenced. while len(_anthropic_clients) >= _MAX_ANTHROPIC_CLIENTS: - evicted = _anthropic_clients.pop(next(iter(_anthropic_clients))) - _close_anthropic_client(evicted) + del _anthropic_clients[next(iter(_anthropic_clients))] _anthropic_clients[cache_key] = client return client diff --git a/decision/tests/test_api.py b/decision/tests/test_api.py index db5319eb8d..0f8ce4b664 100644 --- a/decision/tests/test_api.py +++ b/decision/tests/test_api.py @@ -326,7 +326,7 @@ def test_anthropic_clients_are_cached_by_key_hash(monkeypatch): assert backends.key_fingerprint(ANTHROPIC_KEY) in backends._anthropic_clients -def test_anthropic_clients_evict_and_close_least_recently_used(monkeypatch): +def test_anthropic_clients_evict_least_recently_used_without_closing(monkeypatch): monkeypatch.setattr(backends, "_anthropic_clients", {}) monkeypatch.setattr(backends, "_MAX_ANTHROPIC_CLIENTS", 2) s = replace(_settings(), backend="anthropic", model="claude-haiku-5-5") @@ -336,12 +336,13 @@ async def run(): c2 = backends.anthropic_client(s, "fake-key-0002") assert backends.anthropic_client(s, "fake-key-0001") is c1 c3 = backends.anthropic_client(s, "fake-key-0003") - await asyncio.gather(*backends._closing_clients) + await asyncio.sleep(0) assert set(backends._anthropic_clients) == { backends.key_fingerprint("fake-key-0001"), backends.key_fingerprint("fake-key-0003"), } - assert c2._client.is_closed + # A request still holding the evicted client can finish its call. + assert not c2._client.is_closed assert not c1._client.is_closed assert not c3._client.is_closed diff --git a/deploy/hosted/terraform/main.tf b/deploy/hosted/terraform/main.tf index f5d23724d8..2a7eae9109 100644 --- a/deploy/hosted/terraform/main.tf +++ b/deploy/hosted/terraform/main.tf @@ -13,8 +13,11 @@ resource "aws_security_group" "worker" { name_prefix = "${local.prefix}-" description = "Isolated hosted workers: no inbound access; HTTP(S) egress" vpc_id = aws_vpc.worker.id - ingress = [] - egress = [] + # No inline `egress` here: egress is managed by the standalone + # aws_vpc_security_group_egress_rule resources, and setting it inline (even + # to []) makes this resource strip those rules on every other apply. + # The provider already removes AWS's default allow-all egress on create. + # egress = [] tags = local.tags } resource "aws_vpc_security_group_egress_rule" "worker" { @@ -98,6 +101,6 @@ resource "aws_iam_role_policy" "controller" { }, { Sid = "PassOnlyMachineRole", Effect = "Allow", Action = ["iam:PassRole"], Resource = aws_iam_role.machine.arn, Condition = { StringEquals = { "iam:PassedToService" = "ec2.amazonaws.com" } } }, { Sid = "DenyUnapprovedType", Effect = "Deny", Action = ["ec2:RunInstances"], Resource = "${local.ec2_arn_base}:instance/*", Condition = { StringNotEquals = { "ec2:InstanceType" = var.allowed_instance_types } } }, - { Sid = "RequireMetadataTokens", Effect = "Deny", Action = ["ec2:RunInstances"], Resource = "${local.ec2_arn_base}:instance/*", Condition = { StringNotEqualsIfExists = { "ec2:MetadataHttpTokens" = "required" } } } + { Sid = "RequireMetadataTokens", Effect = "Deny", Action = ["ec2:RunInstances"], Resource = "${local.ec2_arn_base}:instance/*", Condition = { StringNotEquals = { "ec2:MetadataHttpTokens" = "required" } } } ] }) } diff --git a/deploy/hosted/terraform/tests/plan.tftest.hcl b/deploy/hosted/terraform/tests/plan.tftest.hcl index 41fa08b543..27dc6816d0 100644 --- a/deploy/hosted/terraform/tests/plan.tftest.hcl +++ b/deploy/hosted/terraform/tests/plan.tftest.hcl @@ -90,7 +90,7 @@ run "rendered_permissions" { error_message = "Data creation must be constrained to the approved capacity." } assert { - condition = one([for statement in jsondecode(aws_iam_role_policy.controller.policy).Statement : statement if statement.Sid == "RequireMetadataTokens"]).Condition.StringNotEqualsIfExists["ec2:MetadataHttpTokens"] == "required" + condition = one([for statement in jsondecode(aws_iam_role_policy.controller.policy).Statement : statement if statement.Sid == "RequireMetadataTokens"]).Condition.StringNotEquals["ec2:MetadataHttpTokens"] == "required" error_message = "Controller launch must require IMDSv2." } assert { @@ -102,8 +102,8 @@ run "rendered_permissions" { error_message = "Workers must not expose inbound ports." } assert { - condition = length(aws_security_group.worker.egress) == 0 && toset([for rule in aws_vpc_security_group_egress_rule.worker : "${rule.ip_protocol}:${rule.from_port}-${rule.to_port}"]) == toset(["tcp:80-80", "tcp:443-443"]) - error_message = "Workers must remove default egress and allow only HTTP(S) egress." + condition = toset([for rule in aws_vpc_security_group_egress_rule.worker : "${rule.ip_protocol}:${rule.from_port}-${rule.to_port}"]) == toset(["tcp:80-80", "tcp:443-443"]) + error_message = "Workers must allow only HTTP(S) egress." } assert { condition = length(aws_security_group.isolation.ingress) == 0 && length(aws_security_group.isolation.egress) == 0 diff --git a/gateway/src/data/channelLinks.test.ts b/gateway/src/data/channelLinks.test.ts index 1f6673cb0a..16fc6edfaa 100644 --- a/gateway/src/data/channelLinks.test.ts +++ b/gateway/src/data/channelLinks.test.ts @@ -16,8 +16,11 @@ describe("linkTargetFor", () => { }); it("rejects links with unsafe or unknown schemes", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); expect(linkTargetFor("javascript:alert(document.domain)")).toEqual({}); expect(linkTargetFor("data:text/html,")).toEqual({}); + expect(warn).toHaveBeenCalledTimes(2); + warn.mockRestore(); }); }); @@ -44,11 +47,12 @@ describe("openChannelLink", () => { }); it("refuses to navigate to unsafe schemes such as javascript:", () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); const assign = vi.fn(); vi.spyOn(window, "location", "get").mockReturnValue({ ...window.location, assign }); const open = vi.spyOn(window, "open").mockReturnValue(null); - openChannelLink("javascript:alert(document.domain)"); + expect(() => openChannelLink("javascript:alert(document.domain)")).toThrow(/does not recognise/); expect(assign).not.toHaveBeenCalled(); expect(open).not.toHaveBeenCalled(); diff --git a/gateway/src/data/channelLinks.ts b/gateway/src/data/channelLinks.ts index c95b3e8c69..be45f68973 100644 --- a/gateway/src/data/channelLinks.ts +++ b/gateway/src/data/channelLinks.ts @@ -25,7 +25,9 @@ export function linkTargetFor(href: string): { href?: string; target?: "_blank"; if (/^https?:\/\//i.test(href)) { return { href, target: "_blank", rel: "noopener noreferrer" }; } - return isAppLink(href) ? { href } : {}; + if (isAppLink(href)) return { href }; + console.warn("Not linking to a channel link with an unrecognised scheme:", href.split(":", 1)[0]); + return {}; } /** @@ -35,7 +37,7 @@ export function linkTargetFor(href: string): { href?: string; target?: "_blank"; */ export function openChannelLink(link: string): void { const { href, target } = linkTargetFor(webPageChannelLinks(link).primary); - if (!href) return; + if (!href) throw new Error("Switch was given a channel link it does not recognise, so it was not opened."); if (target) window.open(href, target, "noopener,noreferrer"); else window.location.assign(href); } From dc607bfc4fa34a25d71b0bfc7299dc5896796bb5 Mon Sep 17 00:00:00 2001 From: Petr Bauch <210346493+petr-sandbox@users.noreply.github.com> Date: Sun, 6 Dec 2026 07:32:26 +0100 Subject: [PATCH 26/26] Fix CI failures inherited from main - Account deletion with organizations no longer reaches the RLS-exempt tenant lookup or opens an unbound session. The organization holding the default workspace is found by reading that workspace's own row, and the account's WorkOS user ids are read through PurgeElsewhere, which already reads oidc_identities on its own session. Same results as before; adds a test that the default workspace's organization is never offered. - Gateway: the Free Beta copy uses "Switch" and "device" instead of the retired "server" and "machine". - Gateway: Finish later on Get started is offered only on test servers, so the Free Beta test that uses it runs on one. - E2E browser lane: the team survey is split in two; click Next before the use cases. Co-Authored-By: Claude Opus 5.5 --- console/tooling-e2e/src/browser/gateway-ui.ts | 1 + .../switch_core/accounts/own_organizations.py | 47 +++++++++---------- core/switch_core/accounts/purge_elsewhere.py | 18 +++++++ .../test_delete_account_with_organizations.py | 31 ++++++++++++ gateway/src/App.test.tsx | 17 ++++--- gateway/src/components/FreeBeta.test.tsx | 2 +- gateway/src/components/FreeBeta.tsx | 8 ++-- 7 files changed, 86 insertions(+), 38 deletions(-) diff --git a/console/tooling-e2e/src/browser/gateway-ui.ts b/console/tooling-e2e/src/browser/gateway-ui.ts index 9eb4383d92..b8ce21ec17 100644 --- a/console/tooling-e2e/src/browser/gateway-ui.ts +++ b/console/tooling-e2e/src/browser/gateway-ui.ts @@ -276,6 +276,7 @@ export class GatewayUi { for (const question of ['Company size', 'Your role']) { await this.page.getByRole('radiogroup', { name: question }).getByRole('radio').first().click(); } + await this.page.getByRole('button', { name: 'Next', exact: true }).click(); await this.page .getByRole('group', { name: 'Primary use cases' }) .getByRole('checkbox') diff --git a/core/switch_core/accounts/own_organizations.py b/core/switch_core/accounts/own_organizations.py index 89d9741e15..23e45174e6 100644 --- a/core/switch_core/accounts/own_organizations.py +++ b/core/switch_core/accounts/own_organizations.py @@ -31,8 +31,6 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Protocol -from sqlalchemy import or_, select - from switch_core.accounts.account_reset import ( PURGE_WAITING, refuse_installs_it_cannot_end, @@ -45,9 +43,8 @@ ) from switch_core.accounts.organization_purge import PurgeRefused from switch_core.accounts.purge_elsewhere import PurgeElsewhere -from switch_core.db.models import TENANT_ZERO_ID, OidcIdentity, Organization -from switch_core.db.session_scope import organization_session -from switch_core.db.tenant_lookup import tenants_of_organization +from switch_core.db.models import TENANT_ZERO_ID, Organization, Tenant +from switch_core.db.session_scope import organization_session, tenant_session if TYPE_CHECKING: from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker @@ -277,10 +274,9 @@ async def _plan(self, user: User, workspaces: list[Workspace]) -> _Plan: async def _sole_plans(self, user_id: str) -> list[PurgePlan]: plans = [] + default_organization = await self._default_workspace_organization() for organization_id in await self.purge.organizations_of(user_id): - if TENANT_ZERO_ID in await tenants_of_organization( - self.session_factory, organization_id - ): + if organization_id == default_organization: continue plan = await sole_organization_plan( self.session_factory, self.purge, user_id, organization_id @@ -289,6 +285,13 @@ async def _sole_plans(self, user_id: str) -> list[PurgePlan]: plans.append(plan) return plans + async def _default_workspace_organization(self) -> str | None: + """The organization holding the server's default workspace, which + can't be purged; None when no organization holds it.""" + async with tenant_session(self.session_factory, TENANT_ZERO_ID) as session: + tenant = await session.get(Tenant, TENANT_ZERO_ID) + return None if tenant is None else tenant.organization_id + async def _workos_organizations(self, organization_ids: list[str]) -> list[str]: found = [] for organization_id in organization_ids: @@ -302,18 +305,15 @@ async def _workos_organizations(self, organization_ids: list[str]) -> list[str]: async def _workos_users(self, user_id: str) -> list[str]: """The WorkOS user ids the account signs in as, read before it goes.""" - issuer = self.outside.sign_in_issuer - if issuer is None: - return [] - async with self.session_factory() as session: - return sorted( - await session.scalars( - select(OidcIdentity.sub).where( - OidcIdentity.user_id == user_id, - or_(OidcIdentity.iss == issuer, OidcIdentity.iss.is_(None)), - ) - ) - ) + return await self._elsewhere().sign_ins_of(user_id) + + def _elsewhere(self) -> PurgeElsewhere: + return PurgeElsewhere( + session_factory=self.session_factory, + workos=self.outside.workos, + trust=None, + sign_in_issuer=self.outside.sign_in_issuer, + ) async def _leave_at_workos( self, user_id: str, workos_organizations: list[str], workos_users: list[str] @@ -331,12 +331,7 @@ async def _leave_at_workos( ", ".join(workos_organizations), ) return - elsewhere = PurgeElsewhere( - session_factory=self.session_factory, - workos=workos, - trust=None, - sign_in_issuer=self.outside.sign_in_issuer, - ) + elsewhere = self._elsewhere() for workos_user in workos_users: steps = await workos.leave( workos_organizations, diff --git a/core/switch_core/accounts/purge_elsewhere.py b/core/switch_core/accounts/purge_elsewhere.py index b45df3c111..c025168a3e 100644 --- a/core/switch_core/accounts/purge_elsewhere.py +++ b/core/switch_core/accounts/purge_elsewhere.py @@ -249,6 +249,24 @@ async def run( await self._record(plan, request, outcome) return outcome + async def sign_ins_of(self, account_id: str) -> list[str]: + """The WorkOS user ids account `account_id` signs in as; none on a + server whose sign-in is not WorkOS.""" + if self.sign_in_issuer is None: + return [] + async with self.session_factory() as session: + return sorted( + await session.scalars( + select(OidcIdentity.sub).where( + OidcIdentity.user_id == account_id, + or_( + OidcIdentity.iss == self.sign_in_issuer, + OidcIdentity.iss.is_(None), + ), + ) + ) + ) + async def signs_in(self, user_id: str) -> bool: """Whether an account here still signs in as WorkOS user `user_id`: one the purge kept, one it failed to delete, or one made by the same diff --git a/core/tests/switch_core/gateway/test_delete_account_with_organizations.py b/core/tests/switch_core/gateway/test_delete_account_with_organizations.py index dbdb8a3091..a7b2553359 100644 --- a/core/tests/switch_core/gateway/test_delete_account_with_organizations.py +++ b/core/tests/switch_core/gateway/test_delete_account_with_organizations.py @@ -12,11 +12,13 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker from switch_core.db.models import ( + TENANT_ZERO_ID, MessagingInstall, OidcIdentity, Organization, OrganizationMember, Tenant, + TenantMember, User, ) from switch_core.db.session_scope import tenant_session @@ -165,6 +167,35 @@ async def test_an_organization_others_are_in_is_never_offered( ) +async def test_the_organization_holding_the_default_workspace_is_never_offered( + session_factory: async_sessionmaker[AsyncSession], +) -> None: + user_id, email, solo, organization_id = await _solo_workspace(session_factory) + # Alone in the default workspace's organization too: it still can't go. + async with session_factory() as session: + default = await session.get(Tenant, TENANT_ZERO_ID) + assert default is not None and default.organization_id is not None + session.add( + TenantMember(tenant_id=TENANT_ZERO_ID, user_id=user_id, role="admin") + ) + session.add( + OrganizationMember( + organization_id=default.organization_id, + user_id=user_id, + role="org_admin", + ) + ) + await session.commit() + app, _, _ = _app(session_factory, enabled=False) + async with _client(app, user_id, email, solo) as client: + response = await client.get("/auth/me/deletion") + + assert response.status_code == 200, response.text + assert response.json()["organizations"] == [ + {"id": organization_id, "name": "Solo Org", "workspaces": ["Solo"]} + ] + + async def _own_and_shared( session_factory: async_sessionmaker[AsyncSession], workos: FakeWorkOS ) -> tuple[str, str, str, str, str]: diff --git a/gateway/src/App.test.tsx b/gateway/src/App.test.tsx index cd6110f6dd..d76c9c661d 100644 --- a/gateway/src/App.test.tsx +++ b/gateway/src/App.test.tsx @@ -787,11 +787,11 @@ describe("the layout", () => { it("shows an organization admin the Free Beta on Plans & billing", async () => { mockFetch(signedInAs("org_admin")); renderAt("/settings/org/billing"); - const panel = await screen.findByRole("region", { name: "Your server and your agents, always on." }); + const panel = await screen.findByRole("region", { name: "Switch and your agents, always on." }); expect(within(panel).getByText("Free Beta for Switch Cloud")).toBeTruthy(); expect(within(panel).getAllByRole("listitem").map((row) => row.textContent)).toEqual([ - "Your Switch server, hosted and kept up to date", - "A cloud machine for your agents, running 24/7", + "Your Switch, hosted and kept up to date", + "A cloud device for your agents, running 24/7", "Unlimited rooms", "Free until 9 Mar 2027", "Rather host it yourself? Switch is open source", @@ -925,7 +925,7 @@ describe("the layout", () => { mockFetch(signedInAs("member")); renderAt("/rooms"); fireEvent.click(await screen.findByRole("button", { name: "Free Beta" })); - const dialog = await screen.findByRole("dialog", { name: "Your server and your agents, always on." }); + const dialog = await screen.findByRole("dialog", { name: "Switch and your agents, always on." }); expect(within(dialog).getByText("Free until 9 Mar 2027")).toBeTruthy(); fireEvent.click(within(dialog).getByRole("button", { name: "Close" })); await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); @@ -1225,7 +1225,7 @@ describe("the layout", () => { }); describe("the Free Beta on Switch Cloud", () => { - const TITLE = "Your server and your agents, always on."; + const TITLE = "Switch and your agents, always on."; // Whether to send someone to Get started is asked once per tab. beforeEach(() => forgetGetStartedVisit("u1", "t1")); @@ -1276,8 +1276,11 @@ describe("the Free Beta on Switch Cloud", () => { expect(recordings()).toBe(0); }); - it("lets someone sent to Get started finish later", async () => { - mockFetch(onCloud({ agents: [], seen: false })); + it("lets someone sent to Get started finish later, on a test server", async () => { + mockFetch({ + ...onCloud({ agents: [], seen: false }), + "/auth/config": [200, { ...authConfig, test_account_reset_enabled: true }], + }); renderAt("/"); await arrivesAt("/get-started"); fireEvent.click(await screen.findByRole("button", { name: "Finish later" }, { timeout: 5_000 })); diff --git a/gateway/src/components/FreeBeta.test.tsx b/gateway/src/components/FreeBeta.test.tsx index d59a19cf6f..7f794c1623 100644 --- a/gateway/src/components/FreeBeta.test.tsx +++ b/gateway/src/components/FreeBeta.test.tsx @@ -14,7 +14,7 @@ vi.mock("../data/AuthContext", () => ({ useAuth: () => auth.current })); const api = vi.hoisted(() => ({ markFreeBetaSeen: vi.fn() })); vi.mock("../data/api", () => api); -const TITLE = "Your server and your agents, always on."; +const TITLE = "Switch and your agents, always on."; /** Records whether the Free Beta said it was opening by itself, render by render. */ function Probe({ seen }: { seen: boolean[] }) { diff --git a/gateway/src/components/FreeBeta.tsx b/gateway/src/components/FreeBeta.tsx index f8a184718f..72ca44ae6c 100644 --- a/gateway/src/components/FreeBeta.tsx +++ b/gateway/src/components/FreeBeta.tsx @@ -7,8 +7,8 @@ import { useAuth } from "../data/AuthContext"; import { SWITCH_CLOUD } from "../data/featureFlags"; const PERKS = [ - "Your Switch server, hosted and kept up to date", - "A cloud machine for your agents, running 24/7", + "Your Switch, hosted and kept up to date", + "A cloud device for your agents, running 24/7", "Unlimited rooms", "Free until 9 Mar 2027", "Rather host it yourself? Switch is open source", @@ -139,10 +139,10 @@ function FreeBetaContent({ titleId }: { titleId: string }) { component="h2" sx={{ fontSize: "23px", fontWeight: 500, lineHeight: 1.25, letterSpacing: "-0.02em", color: "text.primary" }} > - Your server and your agents, always on. + Switch and your agents, always on. - Switch Cloud hosts your Switch server for you and gives you a cloud machine for your agents, so they keep working 24/7, even when your computer is off. + Switch Cloud hosts Switch for you and gives you a cloud device for your agents, so they keep working 24/7, even when your computer is off.