Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
5e8ad95
fix(security): Command Injection in resolveExecFileSpawn via Insuffic...
p15r-sb Dec 5, 2026
ed9a5bf
fix(security): Pre-Account Takeover via Incomplete Unconfirmed Accoun...
p15r-sb Dec 5, 2026
5f36727
fix(security): Insecure Domain Suffix Validation in Slack File Fetche...
p15r-sb Dec 5, 2026
1ccb064
fix(security): Shell Command Operator Precedence Flaw in buildSshComm...
p15r-sb Dec 5, 2026
52aa2e4
fix(security): IMDSv2 Enforcement Bypass via Ineffective StringNotEqu...
p15r-sb Dec 5, 2026
c2d1cef
fix(security): Sensitive Data Exposure in Log via _Registered.check E...
p15r-sb Dec 5, 2026
e2b812d
fix(security): Cross-Tenant IDOR and Missing Tenant Scoping in verify...
p15r-sb Dec 5, 2026
6976fdc
fix(security): Cross-Tenant Attachment Group Hijacking in Pending Att...
p15r-sb Dec 5, 2026
a913226
fix(security): Ineffective Webex Raw Mention Defusal in defuse_raw_me...
p15r-sb Dec 5, 2026
c6fa300
fix(security): Unescaped Slack mrkdwn Injection in render_request Mes...
p15r-sb Dec 5, 2026
b341b32
fix(security): Unescaped Slack mrkdwn Injection in Approval Card Foot...
p15r-sb Dec 5, 2026
750cf40
fix(security): Incomplete Trailing Backslash Sanitization in systemdT...
p15r-sb Dec 5, 2026
0339e43
fix(security): Improper Escaping in systemd EnvironmentFile Generatio...
p15r-sb Dec 5, 2026
bc1ddff
fix(security): Unbounded Global Client Cache Denial of Service (OOM) ...
p15r-sb Dec 5, 2026
402caa9
fix(security): CSRF Origin Check Bypass via Repeated Cookie Headers i...
p15r-sb Dec 5, 2026
28de8b0
fix(security): Cross-Tenant IDOR and Missing Tenant Authorization in ...
p15r-sb Dec 5, 2026
cf15725
fix(security): Cross-Tenant IDOR and Missing Tenant Authorization in ...
p15r-sb Dec 5, 2026
5bf0552
fix(security): Flawed Row Lock Mode in lock_workspace_allowance Enabl...
p15r-sb Dec 5, 2026
5cdc1f2
fix(security): Non-Conflicting Lock Mode in ensure_default_workspace ...
p15r-sb Dec 5, 2026
66e39bd
fix(security): Cross-Tenant Workspace Member Count Disclosure via Mis...
p15r-sb Dec 5, 2026
a777f8c
fix(security): Unhandled Silence Watchdog in Waiting/Lost State Allow...
p15r-sb Dec 5, 2026
8f5be81
fix(security): DOM-based Cross-Site Scripting (XSS) via javascript: U...
p15r-sb Dec 5, 2026
372ba52
fix(security): Missing Tenant Filtering in Support Request Daily Rate...
p15r-sb Dec 5, 2026
5d348ae
fix(security): Unrestricted Worker Security Group Egress Due to Retai...
p15r-sb Dec 5, 2026
d1f9b9e
Fix review findings on the codemender security changes
petr-sandbox Dec 6, 2026
b74cc15
Merge remote-tracking branch 'origin/main' into security/codemender-2…
petr-sandbox Dec 6, 2026
dc607bf
Fix CI failures inherited from main
petr-sandbox Dec 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
32 changes: 32 additions & 0 deletions console/packages/agent-controller/src/box/launcher-link.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,38 @@ 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();
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()]);

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();
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());
Expand Down
19 changes: 15 additions & 4 deletions console/packages/agent-controller/src/box/launcher-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,11 +165,18 @@ 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');
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');
}

/** Sends an order and waits for its reply; a lost link or no answer in time is a failed reply. */
Expand Down Expand Up @@ -288,7 +295,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');
}

Expand Down
1 change: 1 addition & 0 deletions console/tooling-e2e/src/browser/gateway-ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
47 changes: 21 additions & 26 deletions core/switch_core/accounts/own_organizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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]
Expand All @@ -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,
Expand Down
18 changes: 18 additions & 0 deletions core/switch_core/accounts/purge_elsewhere.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion core/switch_core/bridges/agent/operations/my_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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] = {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)}."
Expand Down Expand Up @@ -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)}."
Expand Down
18 changes: 14 additions & 4 deletions core/switch_core/bridges/collaboration/slack/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
)
):
Expand Down
5 changes: 3 additions & 2 deletions core/switch_core/bridges/collaboration/webex/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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"(?<![\w@<])@("
r"(?<![\w@<\u200b])@("
+ "|".join(re.escape(name) for name in names)
+ r")(?![\w.-]*\w)",
re.IGNORECASE,
Expand Down
Loading
Loading