Skip to content

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

Check messages with files attached against Switch Trust (#997)

Abel Dantasd22c9c5a490c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a6ab3cfc2..0f043469b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -44,7 +44,55 @@ version of their own to them without also giving them a release of their own.
### [Unreleased]
+#### Added
+- **An agent is told when Switch Trust changed or flagged what it sent.** The
+ result of `post_message` and `send_targeted_message`, the agent HTTP message
+ endpoint, the status endpoint, and the media upload endpoint (for a caption
+ and the files) now carries a `trust` field when Switch Trust did something:
+ `{"outcome": "redacted", "delivered": "<what the room received>"}` when
+ parts were redacted, or `alerted` / `errored` with the `note` posted under
+ the message. A redaction that came with a flag or an incomplete check, say a
+ caption redacted beside a file that was flagged, also says `alert`:
+ `alerted` or `errored`. A message Switch Trust left alone has no `trust`
+ field, so its result is as before. Until now an agent whose words were
+ redacted had no way to know.
+
+#### Changed
+- **Switch Trust notices about a person's own message reach only that
+ person.** When someone's message is blocked, redacted, flagged or not fully
+ checked, the notice used to be posted in the channel, where everyone could
+ see what they had tried to say. Now it goes to the sender alone: an
+ ephemeral message on Slack and Mattermost, and a direct message from the bot
+ on Discord and Telegram. A direct message only works for someone who
+ accepts one: on Discord, unless they turned off messages from server
+ members; on Telegram, only once they have started a chat with the bot, which
+ most members of a group never have, so there most notices are still posted
+ in the group. Microsoft Teams has no way for a bot to do either unprompted,
+ so there the notice is still posted in the channel, as it is for a post by
+ an app or by Telegram's anonymous group admins. switch-core logs a warning
+ each time a notice goes to the channel for want of a private route. Notices
+ about an agent's message are still posted for the room.
+
#### Security
+- **Messages with files attached are checked by Switch Trust.** A message with
+ a file used to skip the check entirely, typed text included, both from a
+ person on a chat platform and from an agent sending files. Now the text is
+ checked as any message is, and so is the text inside each file: plain text,
+ JSON, YAML, CSV, Markdown, source code and anything else that reads as
+ text whatever type or name it is sent with, Word documents (.docx) and
+ PDFs. All of it is checked before anything
+ reaches the room. If the text or any file is blocked, nothing from the
+ message is delivered and the sender is told why. A file whose text Switch
+ Trust would redact blocks the message too, since a file cannot be redacted
+ safely. Files with no text to read, such as images, archives and other
+ binaries, are delivered without a check or a note, since Switch never reads
+ their kind. Scanned or encrypted PDFs and files that cannot be opened are
+ delivered with a note on the message saying Switch Trust did not check
+ them. Only the first
+ 20,000 characters of a file are checked (and at most 200 pages of a PDF):
+ anything past that reaches agents unchecked, and the message carries a note
+ saying the rest was not checked. switch-core now depends on `pypdf` to read
+ PDFs.
- **Counts and replies no longer name private rooms either.** Beyond the
room listings below, a reference, document or package's attached-rooms count
took in every room it was attached to, an agent's detail named every room
@@ -2597,6 +2645,14 @@ version of their own to them without also giving them a release of their own.
terminal can't be picked. No earlier prompt is sent again.
#### Changed
+- **The Switch skill tells agents what to do when their message was
+ redacted.** When a send's result says Switch Trust redacted it, the agent
+ reads what the room received and, if that no longer makes sense, says what
+ it meant in words that pass instead of reposting the original.
+- **The Switch Trust settings say what is checked in attached files.** The
+ text inside a file is checked up to its first 20,000 characters; files with
+ no text to read, such as images and archives, are sent without being
+ checked.
- **No Owner role.** Inviting people and changing roles offer Admin and
Member, and the copy says "an admin of this workspace" where it said "an
owner or admin". A server from before the merge that still reports `owner`
@@ -4804,6 +4860,10 @@ The Switch protocol client and MCP runtime
### [Unreleased]
#### Added
+- **`send_attachment` tells the agent what Switch Trust did.** When Switch
+ Trust redacted the caption, or flagged or could not fully check a file, the
+ result has a `Switch Trust:` line with the same `trust` field `post_message`
+ returns. It used to say only that the files were sent.
- **Waits its turn when Switch is busy opening connections.** A server
pacing a reconnect storm refuses an open as `busy` with when to open again,
which is this agent's place in its queue. The stream now waits that long,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/GuardrailsSection.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/GuardrailsSection.tsx
index 95bd37c82..dfde60db9 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/GuardrailsSection.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/GuardrailsSection.tsx
@@ -168,7 +168,9 @@ export const GuardrailsSection = observer(function GuardrailsSection({
<div className={cn('flex flex-col gap-3 pt-3', !open && 'hidden')}>
<p className="text-xs text-foreground-muted">
Every message this server sends is checked before it goes out once an endpoint and an
- API key are set.
+ API key are set, including the text inside attached files, of which only the first
+ 20,000 characters are checked. Files with no text to read, such as images and
+ archives, are sent without being checked.
</p>
<FieldGroup>
<Field>
diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.md
index 6146a562b..fe036e8a0 100644
--- a/console/packages/plugins/src/switch-skill/SKILL.md
+++ b/console/packages/plugins/src/switch-skill/SKILL.md
@@ -292,8 +292,8 @@ A deployment may run every message through **Switch Trust**, a guardrails
service, before it is sent. This is unrelated to the addressing policy above:
addressing refusals always reach the room; a guardrails block does not.
-If your content is blocked, `post_message`, `send_targeted_message` and
-`update_status` fail with an error instead of posting —
+If your content is blocked, `post_message`, `send_targeted_message`,
+`update_status` and `send_attachment` fail with an error instead of posting,
and a notice appears in the room in place of what you tried to send, so other
participants see that something was withheld rather than nothing happening.
Rephrase and retry, or drop it. A human's message can be blocked the same way;
@@ -309,6 +309,27 @@ Trust flagged reaches you with a trailing `⚠️ _Switch Trust flagged this
message…_` line: that line is Switch's annotation, not something the sender
wrote.
+Files are checked too. The text inside a file you send with
+`send_attachment` goes through Switch Trust with the caption: a file it would
+block or redact blocks the whole send, since a file cannot be redacted safely.
+A file it flagged or could not fully check is still sent, and Switch's note
+about it is added to the first file's caption. That line is Switch's, not
+yours.
+
+Your own sends tell you when this happened. The result of `post_message`,
+`send_targeted_message` and `update_status` carries a `trust` field only when
+Switch Trust changed or flagged what you sent, and `send_attachment` adds it
+on a `Switch Trust:` line:
+`{"outcome": "redacted", "delivered": "<what the room received>"}`, or
+`alerted` / `errored` with the `note` posted under it. A redacted message can
+also have been flagged or not fully checked, say a caption redacted beside a
+file that was flagged: `alert` then says `alerted` or `errored`. When that
+notice could not be posted, `note` is absent and `notice_error` says why: the
+room was not warned. If it says your message
+was redacted, read `delivered`: the room saw that, not what you wrote. When the
+redacted version no longer makes sense, tell the room what you meant in words
+that pass. Don't repost the original.
+
## Questions and approvals
Native question forms can be answered in the Console or from the room. The
diff --git a/console/packages/switch-agent-runtime/src/hosted.test.ts b/console/packages/switch-agent-runtime/src/hosted.test.ts
index 7dc893317..35bad639a 100644
--- a/console/packages/switch-agent-runtime/src/hosted.test.ts
+++ b/console/packages/switch-agent-runtime/src/hosted.test.ts
@@ -97,6 +97,21 @@ describe('the tool catalog', () => {
);
});
+ it('tells the agent what Switch Trust did to what it sent', async () => {
+ const trust = { outcome: 'redacted', delivered: 'see [redacted]', alert: 'errored' };
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => Response.json({ event_id: 'event', trust }))
+ );
+ const ctx = context();
+ writeFileSync(join(ctx.cwd, 'notes.md'), 'hello');
+ const result = await catalog.call(ctx, 'send_attachment', {
+ path: 'notes.md',
+ caption: 'see secret',
+ });
+ expect(result.content[0]!.text).toContain(`Switch Trust: ${JSON.stringify(trust)}`);
+ });
+
it('downloads into the caller’s media directory', async () => {
vi.stubGlobal(
'fetch',
diff --git a/console/packages/switch-agent-runtime/src/hosted.ts b/console/packages/switch-agent-runtime/src/hosted.ts
index 2d10dad02..aa8eec6dc 100644
--- a/console/packages/switch-agent-runtime/src/hosted.ts
+++ b/console/packages/switch-agent-runtime/src/hosted.ts
@@ -503,15 +503,18 @@ async function sendAttachmentTool(
if (!resp.ok) {
throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);
}
- const data = (await resp.json()) as { event_id?: string };
+ const data = (await resp.json()) as { event_id?: string; trust?: unknown };
const names = files.map((f) => f.name).join(', ');
+ // What Switch Trust did to the caption or flagged in the files, only when
+ // it did something, in the same `trust` form post_message returns.
+ const trust = data.trust === undefined ? '' : `\nSwitch Trust: ${JSON.stringify(data.trust)}`;
return {
content: [
{
type: 'text',
text:
`Sent ${files.length === 1 ? names : `${files.length} files (${names})`} ` +
- `to the room (event_id: ${data.event_id ?? 'unknown'}).`,
+ `to the room (event_id: ${data.event_id ?? 'unknown'}).${trust}`,
},
],
};
diff --git a/core/pyproject.toml b/core/pyproject.toml
index 8df9db904..589a0585f 100644
--- a/core/pyproject.toml
+++ b/core/pyproject.toml
@@ -42,6 +42,7 @@ dependencies = [
"discord-py>=2.4,<3",
"python-telegram-bot>=21,<22",
"httpcore>=1.0.9,<2",
+ "pypdf>=6.21.4,<7",
"uvloop>=0.21,<1 ; sys_platform != 'win32'",
]
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index 9b0be5e6f..a768b875f 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -493,7 +493,7 @@ async def send_message(
) -> dict[str, object]:
logger.debug("Recieved message from agent %s: %s", agent.name, req.content)
try:
- event_id = await protocol.send_message(agent.id, req.room_id, req.content)
+ sent = await protocol.send_message(agent.id, req.room_id, req.content)
except BudgetExceeded as e:
raise HTTPException(status_code=429, detail=str(e)) from e
except GuardrailBlockedError as e:
@@ -503,7 +503,10 @@ async def send_message(
except PermissionError as e:
raise HTTPException(status_code=403, detail=str(e)) from e
- return {"ok": True, "event_id": event_id}
+ result: dict[str, object] = {"ok": True, "event_id": sent.event_id}
+ if sent.trust is not None:
+ result["trust"] = sent.trust.to_result()
+ return result
@router.get("/{agent_id}/rooms/{room_id}/media", response_model=None)
@@ -590,6 +593,8 @@ async def upload_media(
)
except BudgetExceeded as e:
raise HTTPException(status_code=429, detail=str(e)) from e
+ except GuardrailBlockedError as e:
+ raise HTTPException(status_code=422, detail=str(e)) from e
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
except PermissionError as e:
@@ -686,18 +691,22 @@ async def update_status(
req: StatusRequest,
agent: Annotated[Agent, Depends(get_agent_from_scope)],
protocol: Annotated[AgentCore, Depends(get_protocol)],
-) -> dict[str, bool]:
+) -> dict[str, object]:
+ """Post a status line in the room. The result carries `trust` only when
+ Switch Trust changed or flagged it, as a sent message's does."""
+ result: dict[str, object] = {"ok": True}
if req.detail:
try:
- await protocol.update_status(agent.id, req.room_id, req.detail)
+ feedback = await protocol.update_status(agent.id, req.room_id, req.detail)
except GuardrailBlockedError as e:
raise HTTPException(status_code=422, detail=str(e)) from e
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
except PermissionError as e:
raise HTTPException(status_code=403, detail=str(e)) from e
-
- return {"ok": True}
+ if feedback is not None:
+ result["trust"] = feedback.to_result()
+ return result
@router.post("/{agent_id}/runtime-state")
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index e59b55865..ca123f93d 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -54,7 +54,7 @@ from switch_core.bridges.agent.protocol.agent_detail import (
)
from switch_core.bridges.agent.protocol.agent_management import ManagedAgentChanges
from switch_core.bridges.agent.protocol.instructions import build_room_instructions
-from switch_core.bridges.agent.protocol.types import IntegrationProfile
+from switch_core.bridges.agent.protocol.types import IntegrationProfile, TrustFeedback
from switch_core.clients.agent_admin import DELETE_CONFIRM_SECONDS
from switch_core.db.models import CollaborationBridge, User, require_tenant_id
from switch_core.db.session_scope import shared_tenant_session
@@ -785,7 +785,7 @@ async def list_participants() -> list[dict[str, Any]]:
@operation
-async def post_message(body: str, thread_id: str | None = None) -> dict[str, str]:
+async def post_message(body: str, thread_id: str | None = None) -> dict[str, Any]:
"""Send a message to the connected room (broadcast, no specific recipient).
Args:
@@ -801,14 +801,26 @@ async def post_message(body: str, thread_id: str | None = None) -> dict[str, str
thread_id.
Returns:
- {"event_id": "<event id>"} for the posted message.
+ {"event_id": "<event id>"} for the posted message, plus `trust` when
+ Switch Trust changed or flagged it (see below). No `trust` means the
+ room received exactly what you sent.
+
+ `trust` is {"outcome": "redacted", "delivered": "<the text the room
+ received>"} when parts of your message were redacted before anyone
+ saw them; {"outcome": "alerted", "note": "<the notice>"} when it was
+ delivered as sent but flagged, with that notice posted under it; or
+ {"outcome": "errored", "note": "<the notice>"} when it was delivered
+ without being fully checked. `note` is there only when the notice was
+ posted in the room; when it could not be, `note` is absent and
+ `notice_error` says why, and the room was not warned. A blocked
+ message is not delivered at all, and the call fails instead.
"""
agent_id = get_agent_id()
room_id = await require_connected_room()
protocol = get_protocol()
- event_id = await protocol.send_message(agent_id, room_id, body, thread_id=thread_id)
- return {"event_id": event_id}
+ sent = await protocol.send_message(agent_id, room_id, body, thread_id=thread_id)
+ return _with_trust({"event_id": sent.event_id}, sent.trust)
@operation
@@ -871,6 +883,9 @@ async def send_targeted_message(
(its bridge is down or has no channel for the room, so the message
never reaches the platform). It says what Switch sent, not what the
platform confirmed.
+
+ `trust` is present, as for post_message, when Switch Trust changed or
+ flagged the message.
"""
agent_id = get_agent_id()
room_id = await require_connected_room()
@@ -884,10 +899,21 @@ async def send_targeted_message(
thread_id=thread_id,
target_roles=target_roles or [],
)
- return {
- "event_id": result.event_id,
- "target_statuses": {n: s.value for n, s in result.target_statuses.items()},
- }
+ return _with_trust(
+ {
+ "event_id": result.event_id,
+ "target_statuses": {n: s.value for n, s in result.target_statuses.items()},
+ },
+ result.trust,
+ )
+
+
+def _with_trust(result: dict[str, Any], trust: TrustFeedback | None) -> dict[str, Any]:
+ """A send's result, with `trust` only when Switch Trust did something:
+ a message it left alone reports nothing about it."""
+ if trust is not None:
+ result["trust"] = trust.to_result()
+ return result
# ── Moderation ───────────────────────────────────────────────────────────────
diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.py
index 430c340c8..094fa4c02 100644
--- a/core/switch_core/bridges/agent/protocol/agent_core.py
+++ b/core/switch_core/bridges/agent/protocol/agent_core.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
import base64
import hashlib
import json
@@ -11,7 +12,7 @@ from collections import Counter
from collections.abc import Awaitable, Callable, Sequence
from dataclasses import dataclass
from datetime import UTC, datetime
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, Literal
from sqlalchemy import select
@@ -70,8 +71,10 @@ from switch_core.bridges.agent.protocol.types import (
RoomDetailDescriptor,
RoomWideMentionStatus,
SendTargetedResult,
+ SentMessage,
ToolCallReport,
ToolSpec,
+ TrustFeedback,
)
from switch_core.bridges.agent.room_access_cache import RoomAccessCache
from switch_core.bridges.collaboration.adapter import (
@@ -146,13 +149,16 @@ from switch_core.tenant_context import current_tenant_id, tenant_scope
from switch_core.transport import (
TransportError,
)
+from switch_core.trust.attachments import check_attachments
from switch_core.trust.client import (
GuardrailBlockedError,
NullTrustClient,
+ TrustCheckResult,
TrustClient,
TrustOutcome,
check_message,
trust_annotation,
+ trust_is_active,
)
if TYPE_CHECKING:
@@ -271,6 +277,42 @@ def _coalesce_attachment_groups(
return [row for row in rows if row.id not in absorbed], merged
+def _trust_feedback(
+ verdict: TrustOutcome | None,
+ delivered: str | None,
+ alert: tuple[str, TrustOutcome] | None,
+ notice_error: str | None,
+) -> TrustFeedback | None:
+ """What to tell an agent Switch Trust did to the text it sent, or None
+ when it let the text through unflagged.
+
+ `verdict` is Switch Trust's outcome for the text (None when it was not
+ checked), `alert` the notice due under the message, if any, and
+ `notice_error` why that notice was not posted (None once it was). A
+ redaction can leave the words as they were, so it is told from the
+ verdict rather than from the delivered text differing from the sent."""
+ note = alert[0] if alert is not None and notice_error is None else None
+ alerted: Literal["alerted", "errored"] | None = None
+ if alert is not None:
+ alerted = "alerted" if alert[1] == "alerted" else "errored"
+ if verdict == "redacted":
+ return TrustFeedback(
+ outcome="redacted",
+ delivered=delivered,
+ alert=alerted,
+ note=note,
+ notice_error=notice_error,
+ )
+ if alerted is None:
+ return None
+ return TrustFeedback(
+ outcome=alerted,
+ delivered=None,
+ note=note,
+ notice_error=notice_error,
+ )
+
+
def _elided_root(root_id: str) -> dict[str, Any]:
"""A stand-in for a thread root with no recorded row.
@@ -1687,7 +1729,7 @@ class AgentCore:
content: str,
thread_root_id: str | None,
client: AgentActor,
- ) -> tuple[str, tuple[str, TrustOutcome] | None]:
+ ) -> tuple[str, tuple[str, TrustOutcome] | None, TrustOutcome]:
"""Check agent-authored content against Switch Trust before it is
sent. Returns the content to actually send — unchanged or redacted —
and, on an ALERTED/ERRORED verdict, an (annotation, outcome) pair for
@@ -1695,7 +1737,8 @@ class AgentCore:
sent (`_post_trust_alert_notice`, threaded under that send's own
event_id rather than under this call's pre-send `thread_root_id`, so
the notice reads as a reply to the flagged message, not to whatever
- thread the agent happened to be posting in). Raises
+ thread the agent happened to be posting in), then the verdict itself,
+ which the caller reports back to the agent (`_trust_feedback`). Raises
`GuardrailBlockedError` on a BLOCKED verdict, or on a REDACTED verdict
Switch Trust gave us nothing to redact with — sending the original
content then would be indistinguishable from not checking at all —
@@ -1707,6 +1750,21 @@ class AgentCore:
content=content,
room_id=room.id,
)
+ return await self._apply_trust_check(
+ room, content, check, thread_root_id, client
+ )
+
+ async def _apply_trust_check(
+ self,
+ room: RoomDescriptor,
+ content: str,
+ check: TrustCheckResult,
+ thread_root_id: str | None,
+ client: AgentActor,
+ ) -> tuple[str, tuple[str, TrustOutcome] | None, TrustOutcome]:
+ """`_enforce_trust` for a check already made, so a caller can run it
+ alongside others (`send_media` checks a caption and its files at
+ once)."""
if check.blocked or (
check.outcome == "redacted" and check.redacted_content is None
):
@@ -1716,7 +1774,7 @@ class AgentCore:
content = check.redacted_content
annotation = trust_annotation(check)
pending_alert = (annotation, check.outcome) if annotation is not None else None
- return content, pending_alert
+ return content, pending_alert, check.outcome
async def _post_trust_blocked_notice(
self, room: RoomDescriptor, thread_root_id: str | None, client: AgentActor
@@ -1753,13 +1811,18 @@ class AgentCore:
reply_to_event_id: str,
annotation: str,
outcome: TrustOutcome,
- ) -> None:
+ ) -> str | None:
"""Tell the room a response was flagged (or could not be fully
checked), as its own notice threaded under the flagged reply's own
event id — not the pre-send thread the agent happened to be posting
in — rather than appended to the reply itself. Mirrors how
`CollaborationCore._post_trust_notice` threads an ALERTED/ERRORED
- human-authored message under the message that triggered it."""
+ human-authored message under the message that triggered it.
+
+ Returns None once the notice is posted, or why it was not (logged as
+ a WARNING), for the sender's `TrustFeedback.notice_error`. A notice
+ that fails does not fail the send: the message is already in the
+ room."""
admin = next(
(
c
@@ -1775,14 +1838,14 @@ class AgentCore:
room.id,
outcome,
)
- return
+ return "no admin client is running to post it"
message_type = (
AdminMessageType.TRUST_ALERTED
if outcome == "alerted"
else AdminMessageType.TRUST_ERRORED
)
try:
- await admin.send_admin(
+ event_id = await admin.send_admin(
room.transport_room_id,
annotation,
message_type=message_type,
@@ -1794,6 +1857,15 @@ class AgentCore:
room.id,
exc_info=True,
)
+ return "posting it failed"
+ if event_id is None:
+ logger.warning(
+ "Could not post a Switch Trust alert notice in %s: the "
+ "transport refused it",
+ room.id,
+ )
+ return "posting it failed"
+ return None
async def _post_role_change_notice(
self, agent_id: str, transport_room_id: str, action: str
@@ -1832,8 +1904,10 @@ class AgentCore:
thread_id: str | None = None,
*,
extra_content: dict[str, object] | None = None,
- ) -> str:
- """Send a message to a room. Returns event_id.
+ ) -> SentMessage:
+ """Send a message to a room. Returns its event_id and, when Switch
+ Trust redacted or flagged it, what it did (`TrustFeedback`), so the
+ agent learns its words changed.
When thread_id is set the message is posted as a reply in that thread
(the id is normalised to the thread root). `extra_content` carries
@@ -1856,12 +1930,12 @@ class AgentCore:
thread_root_id = await self._resolve_thread_root(
client, room.transport_room_id, thread_id
)
- content, pending_alert = await self._enforce_trust(
+ delivered, pending_alert, verdict = await self._enforce_trust(
room, content, thread_root_id, client
)
event_id = await client.send_message(
room.transport_room_id,
- content,
+ delivered,
thread_root_id=thread_root_id,
extra_content=extra_content,
metered=True,
@@ -1873,9 +1947,12 @@ class AgentCore:
event_id,
room.transport_room_id,
)
+ notice_error: str | None = None
if pending_alert is not None:
annotation, outcome = pending_alert
- await self._post_trust_alert_notice(room, event_id, annotation, outcome)
+ notice_error = await self._post_trust_alert_notice(
+ room, event_id, annotation, outcome
+ )
# The agent has replied, so clear any typing indicator raised when the
# inbound message arrived. The message itself is already delivered, so a
# failure here is degraded-but-functional, not a reason to fail the send.
@@ -1885,7 +1962,10 @@ class AgentCore:
logger.warning(
"Failed to clear typing indicator for room %s", room_id, exc_info=True
)
- return event_id
+ return SentMessage(
+ event_id=event_id,
+ trust=_trust_feedback(verdict, delivered, pending_alert, notice_error),
+ )
async def send_media(
self,
@@ -1913,6 +1993,12 @@ class AgentCore:
With more than one file the events share an attachment-group marker so
receivers can coalesce them into one logical message, since a media
event carries one file.
+
+ Raises GuardrailBlockedError if Switch Trust blocks the caption or any
+ file's text; a notice is posted to the room and nothing is sent. A
+ file Switch Trust cannot read is sent with a notice saying so. When it
+ redacted the caption or noted anything, the result also carries
+ `trust` (`TrustFeedback.to_result`).
"""
if not files:
raise ValueError("no attachments provided")
@@ -1939,46 +2025,113 @@ class AgentCore:
client, room.transport_room_id, thread_id
)
+ # The caption is checked as `send_message` checks text, and each file
+ # through the text it carries (`trust/attachments.py`), all before
+ # anything is uploaded, so a refusal leaves nothing in the room.
+ caption_text = caption if caption and caption.strip() else None
+ caption_verdict: TrustOutcome | None = None
+ trust_notes: list[str] = []
+ file_notes: tuple[str, ...] = ()
+ flagged = False
+ if await trust_is_active(self.trust_client):
+ files_check_task = check_attachments(
+ self.trust_client, role="assistant", files=files, room_id=room.id
+ )
+ if caption_text is not None:
+ caption_check, files_check = await asyncio.gather(
+ check_message(
+ self.trust_client,
+ role="assistant",
+ content=caption_text,
+ room_id=room.id,
+ ),
+ files_check_task,
+ )
+ (
+ caption_text,
+ pending_alert,
+ caption_verdict,
+ ) = await self._apply_trust_check(
+ room, caption_text, caption_check, thread_root_id, client
+ )
+ if pending_alert is not None:
+ annotation, outcome = pending_alert
+ trust_notes.append(annotation)
+ flagged = outcome == "alerted"
+ else:
+ files_check = await files_check_task
+ if files_check.block is not None:
+ await self._post_trust_blocked_notice(room, thread_root_id, client)
+ raise GuardrailBlockedError(
+ files_check.block, "; ".join(files_check.block_reasons)
+ )
+ file_notes = files_check.notes
+ trust_notes.extend(file_notes)
+ flagged = flagged or files_check.flagged
+ # What Switch Trust says about the files rides in the first file's
+ # caption, so every agent that receives them receives it too.
+ first_caption = (
+ "\n\n".join(p for p in (caption_text, "\n".join(file_notes)) if p) or None
+ )
+
total = len(files)
group_id = str(uuid.uuid4()) if total > 1 else None
posted: list[dict[str, str]] = []
- for index, (data, filename, mimetype) in enumerate(files):
- media_uri = await client.upload_media(data, mimetype, filename)
- msgtype = "m.image" if mimetype.startswith("image/") else "m.file"
- event_id = await client.send_media(
- room.transport_room_id,
- media_uri,
- filename,
- mimetype,
- len(data),
- msgtype=msgtype,
- caption=(
- caption if index == 0 and caption and caption.strip() else None
- ),
- thread_root_id=thread_root_id,
- group=(
- {"id": group_id, "index": index, "total": total}
- if group_id is not None
- else None
- ),
- metered=True,
- )
- if event_id is None:
- raise ValueError(f"Failed to send media message for '{filename}'")
- posted.append(
- {"event_id": event_id, "mxc": media_uri, "filename": filename}
- )
+ media_alert: tuple[str, TrustOutcome] | None = (
+ ("\n".join(trust_notes), "alerted" if flagged else "errored")
+ if trust_notes
+ else None
+ )
+ notice_error: str | None = None
+ try:
+ for index, (data, filename, mimetype) in enumerate(files):
+ media_uri = await client.upload_media(data, mimetype, filename)
+ msgtype = "m.image" if mimetype.startswith("image/") else "m.file"
+ event_id = await client.send_media(
+ room.transport_room_id,
+ media_uri,
+ filename,
+ mimetype,
+ len(data),
+ msgtype=msgtype,
+ caption=first_caption if index == 0 else None,
+ thread_root_id=thread_root_id,
+ group=(
+ {"id": group_id, "index": index, "total": total}
+ if group_id is not None
+ else None
+ ),
+ metered=True,
+ )
+ if event_id is None:
+ raise ValueError(f"Failed to send media message for '{filename}'")
+ posted.append(
+ {"event_id": event_id, "mxc": media_uri, "filename": filename}
+ )
+ finally:
+ # Also told as a notice to the room's people, even when a later
+ # file failed to send after the first was posted.
+ if media_alert is not None and posted:
+ notice_error = await self._post_trust_alert_notice(
+ room, posted[0]["event_id"], *media_alert
+ )
try:
await self._set_typing(agent_id, room, False)
except Exception:
logger.warning(
"Failed to clear typing indicator for room %s", room_id, exc_info=True
)
- return {
+ result: dict[str, object] = {
"event_id": posted[0]["event_id"],
"mxc": posted[0]["mxc"],
"attachments": posted,
}
+ feedback = _trust_feedback(
+ caption_verdict, caption_text, media_alert, notice_error
+ )
+ if feedback is not None:
+ result["trust"] = feedback.to_result()
+ return result
async def _can_address(
self,
@@ -2160,7 +2313,7 @@ class AgentCore:
mention_tokens += [f"@{name}" for name in target_names]
mention_tokens += [f"@{role}" for role in roles]
body = f"{' '.join(mention_tokens)} {content}"
- event_id = await self.send_message(
+ sent = await self.send_message(
agent_id,
room_id,
body,
@@ -2193,7 +2346,9 @@ class AgentCore:
target_statuses[ROOM_WIDE_TARGET] = self._room_wide_mention_status(
room_id, room_row.bridge_id if room_row is not None else None
)
- return SendTargetedResult(event_id=event_id, target_statuses=target_statuses)
+ return SendTargetedResult(
+ event_id=sent.event_id, target_statuses=target_statuses, trust=sent.trust
+ )
async def _refuse_room_wide_mention_collisions(
self, room_id: str, participants: list[ParticipantDescriptor]
@@ -2291,8 +2446,11 @@ class AgentCore:
raise ValueError(f"Agent not found: {agent_id}")
await collaboration_core.handle_outbound_typing(room.id, agent.name, is_typing)
- async def update_status(self, agent_id: str, room_id: str, detail: str) -> None:
- """Send a status message to a room.
+ async def update_status(
+ self, agent_id: str, room_id: str, detail: str
+ ) -> TrustFeedback | None:
+ """Send a status message to a room, and say what Switch Trust did to
+ it, as `post_message` does (`_trust_feedback`).
Raises GuardrailBlockedError if Switch Trust blocks it.
"""
@@ -2300,21 +2458,29 @@ class AgentCore:
client = self.client_lifecycle.get_by_agent_id(agent_id)
if client is None:
raise ValueError("Agent client not running")
- detail, pending_alert = await self._enforce_trust(room, detail, None, client)
+ detail, pending_alert, verdict = await self._enforce_trust(
+ room, detail, None, client
+ )
event_id = await client.send_message(
room.transport_room_id, f"*{detail}*", format="markdown", metered=True
)
- if pending_alert is not None:
- if event_id is None:
+ if event_id is None:
+ if pending_alert is not None:
logger.warning(
"Status update to %s failed to send; dropping its pending "
"Switch Trust %s notice along with it",
room.id,
pending_alert[1],
)
- else:
- annotation, outcome = pending_alert
- await self._post_trust_alert_notice(room, event_id, annotation, outcome)
+ # Nothing reached the room, so there is nothing to tell.
+ return None
+ notice_error: str | None = None
+ if pending_alert is not None:
+ annotation, outcome = pending_alert
+ notice_error = await self._post_trust_alert_notice(
+ room, event_id, annotation, outcome
+ )
+ return _trust_feedback(verdict, detail, pending_alert, notice_error)
async def set_runtime_state(
self,
diff --git a/core/switch_core/bridges/agent/protocol/types.py b/core/switch_core/bridges/agent/protocol/types.py
index afd78a8c8..ea5f3081a 100644
--- a/core/switch_core/bridges/agent/protocol/types.py
+++ b/core/switch_core/bridges/agent/protocol/types.py
@@ -138,9 +138,42 @@ class RoomWideMentionStatus(StrEnum):
BRIDGE_UNAVAILABLE = "bridge_unavailable"
+class TrustFeedback(BaseModel):
+ """What Switch Trust did to a message an agent sent, for the agent that
+ sent it. Only made when it did something: a message it let through
+ untouched carries none.
+
+ `outcome` is `redacted` when Switch Trust redacted the message, with what
+ the room received in `delivered` (which can match what was sent when
+ there was nothing it could cut); otherwise `alerted` (flagged and
+ delivered as sent) or `errored` (delivered as sent, not fully checked).
+ A redacted message can also have been flagged or not fully checked, say a
+ caption redacted beside a file that was flagged: `alert` then says which,
+ so the redaction does not hide it. `note` is the notice posted in the
+ room under the message, when one was posted. When a notice was due but
+ could not be posted, `note` is unset and `notice_error` says why, so the
+ agent is not told the room was warned when it was not."""
+
+ outcome: Literal["redacted", "alerted", "errored"]
+ delivered: str | None
+ alert: Literal["alerted", "errored"] | None = None
+ note: str | None
+ notice_error: str | None
+
+ def to_result(self) -> dict[str, str]:
+ """The tool-result form: the fields that are set, and no others."""
+ return self.model_dump(exclude_none=True)
+
+
+class SentMessage(BaseModel):
+ event_id: str
+ trust: TrustFeedback | None
+
+
class SendTargetedResult(BaseModel):
event_id: str
target_statuses: dict[str, AgentStatus | RoomWideMentionStatus]
+ trust: TrustFeedback | None
class ParticipantDescriptor(BaseModel):
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index b900c0110..4d702fd05 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -40,6 +40,7 @@ from switch_core.bridges.collaboration.models import (
InboundMessage,
InboundUserJoin,
OutboundAttachment,
+ PrivateNoticeDelivery,
RetireOutcome,
WebhookDeliveryUnsupported,
)
@@ -256,6 +257,13 @@ class RichContentFailed(Exception):
self.text = text
+class PrivateNoticeRefused(Exception):
+ """The platform would not let the bot reach this person privately, as it
+ refuses for someone who never opened a chat with the bot, blocked it, or
+ takes no direct messages. Expected on those platforms, so the caller logs
+ it without a traceback and posts the notice in the channel instead."""
+
+
class ChannelNotBindable(ValueError):
"""A room was asked to bind to a channel that is not this bridge's to bind.
@@ -634,6 +642,15 @@ class PlatformAdapter(ABC):
#: because the base leaves the channel alone.
channel_on_delete: ClassVar[ChannelRetirement] = "kept"
+ #: How `notify_privately` reaches one person about their own message.
+ #:
+ #: A Switch Trust notice about what a person posted (blocked, redacted,
+ #: flagged, not fully checked) is theirs alone, and posting it in the
+ #: channel tells everyone there what they tried to say. `in_channel` here
+ #: because the base has no private route: the caller posts the notice in
+ #: the channel instead and logs a warning saying so.
+ private_notice_delivery: ClassVar[PrivateNoticeDelivery] = "in_channel"
+
def __init__(self) -> None:
# Whether this process holds the bridge: see
# `keeps_quiet_unless_listening`. Set by the lifecycle before `start`.
@@ -2106,6 +2123,36 @@ class PlatformAdapter(ABC):
text,
)
+ async def notify_privately(
+ self,
+ *,
+ channel_id: str,
+ channel_name: str | None,
+ user_id: str,
+ content: str,
+ thread_root_id: str | None,
+ ) -> None:
+ """Say `content` to `user_id` alone, about a message they posted in
+ `channel_id`, the way `private_notice_delivery` declares.
+
+ `content` is Switch Markdown, rendered here as `admin_message` renders
+ its body. `thread_root_id` is where the message sits, for a notice
+ shown in the channel; `channel_name` names the channel in a notice
+ that arrives somewhere else, so the reader can tell which message it
+ is about.
+
+ Raises when the notice cannot be delivered privately, so the caller
+ can post it in the channel instead and say so: `PrivateNoticeRefused`
+ when the platform refuses to reach this person, which is expected,
+ anything else when it failed. A long `content` is split as
+ `admin_message` splits it, so its length never costs the private
+ route. The base has no private
+ route and is never called for one: `private_notice_delivery` is
+ `in_channel` here."""
+ raise NotImplementedError(
+ f"{self.platform_name} has no way to say something to one person privately"
+ )
+
def set_agent_presentation_resolver(
self, resolver: Callable[[str], Awaitable[AgentPresentation | None]]
) -> None:
diff --git a/core/switch_core/bridges/collaboration/collaboration_core.py b/core/switch_core/bridges/collaboration/collaboration_core.py
index 334f497dd..2b0890658 100644
--- a/core/switch_core/bridges/collaboration/collaboration_core.py
+++ b/core/switch_core/bridges/collaboration/collaboration_core.py
@@ -23,6 +23,7 @@ from switch_core.bridges.collaboration.adapter import (
AgentIdentity,
AgentPresentation,
PlatformAdapter,
+ PrivateNoticeRefused,
SupportsSharedConnection,
agent_identity,
)
@@ -94,11 +95,14 @@ from switch_core.transport import (
TransportError,
writes_derived_from,
)
+from switch_core.trust.attachments import AttachmentsVerdict, check_attachments
from switch_core.trust.client import (
NullTrustClient,
+ TrustCheckResult,
TrustClient,
check_message,
trust_annotation,
+ trust_is_active,
trust_redaction_notice,
)
@@ -1267,6 +1271,73 @@ class CollaborationCore:
)
return
+ # A message with files is checked as a whole before anything is
+ # uploaded: the typed text exactly as above, and each file through the
+ # text it carries (`trust/attachments.py`), so a refusal of either
+ # leaves nothing of the message in the room.
+ caption_check: TrustCheckResult | None = None
+ files_check = AttachmentsVerdict()
+ if await trust_is_active(self._trust_client):
+ files = [(a.data, a.filename, a.mimetype) for a in msg.attachments]
+ files_check_task = check_attachments(
+ self._trust_client, role="user", files=files, room_id=room_id
+ )
+ if content.strip():
+ caption_check, files_check = await asyncio.gather(
+ check_message(
+ self._trust_client,
+ role="user",
+ content=content,
+ room_id=room_id,
+ ),
+ files_check_task,
+ )
+ else:
+ files_check = await files_check_task
+ caption_refused = caption_check is not None and (
+ caption_check.blocked
+ or (
+ caption_check.outcome == "redacted"
+ and caption_check.redacted_content is None
+ )
+ )
+ if caption_refused or files_check.blocked:
+ logger.warning(
+ "[BRIDGE-IN] message with %d attachment(s) from %s not relayed: "
+ "Switch Trust text outcome=%s, files: %s, room %s",
+ len(msg.attachments),
+ msg.sender_name,
+ caption_check.outcome if caption_check is not None else "unchecked",
+ "; ".join(files_check.block_reasons) or "not blocked",
+ transport_room_id,
+ )
+ if files_check.blocked:
+ notice = (
+ "🚫 Your message was blocked by Switch Trust and was not "
+ f"delivered to the room: {'; '.join(files_check.block_reasons)}. "
+ "You can still see it, but agents can't access it."
+ )
+ else:
+ notice = (
+ "🚫 Your message was blocked by Switch Trust and was not "
+ "delivered to the room. You can still see it, but agents "
+ "can't access it."
+ )
+ await self._post_trust_notice(msg, notice, AdminMessageType.TRUST_BLOCKED)
+ return
+ if caption_check is not None and caption_check.redacted_content is not None:
+ content = caption_check.redacted_content
+ caption_annotation = (
+ trust_annotation(caption_check) if caption_check is not None else None
+ )
+ trust_notes = [
+ *([caption_annotation] if caption_annotation is not None else []),
+ *files_check.notes,
+ ]
+ if trust_notes:
+ notes_text = "\n".join(trust_notes)
+ content = f"{content}\n\n{notes_text}" if content.strip() else notes_text
+
# Caption convention: the text rides as the caption on the first
# attachment so "text + one image" reaches the agent as a single event;
# remaining attachments are sent as bare media events. The first media
@@ -1322,6 +1393,25 @@ class CollaborationCore:
first_event_id = event_id
if first_event_id is not None:
+ # As for a text-only message, the sender hears what Switch Trust
+ # did only once the message is confirmed in the room.
+ if caption_check is not None and caption_check.redacted_content is not None:
+ redaction_notice = trust_redaction_notice(caption_check)
+ if redaction_notice is not None:
+ await self._post_trust_notice(
+ msg, redaction_notice, AdminMessageType.TRUST_REDACTED
+ )
+ if trust_notes:
+ flagged = files_check.flagged or (
+ caption_check is not None and caption_check.outcome == "alerted"
+ )
+ await self._post_trust_notice(
+ msg,
+ "\n".join(trust_notes),
+ AdminMessageType.TRUST_ALERTED
+ if flagged
+ else AdminMessageType.TRUST_ERRORED,
+ )
await self._record_message_map(
external_channel_id=msg.channel_id,
transport_event_id=first_event_id,
@@ -1331,10 +1421,79 @@ class CollaborationCore:
async def _post_trust_notice(
self, msg: InboundMessage, body: str, message_type: AdminMessageType
) -> None:
- """Tell the sender's platform what Switch Trust did with their message
- — blocked, redacted, alerted, or errored. Never lets a failed notice
- take the inbound message down with it — mirrors
+ """Tell the sender, and only the sender, what Switch Trust did with
+ their message: blocked, redacted, flagged, or not fully checked.
+
+ Each of these is about what one person wrote, so it goes to them the
+ way the platform allows (`private_notice_delivery`). Where it has no
+ private route, or the private one fails, the notice is posted in the
+ channel and a warning says everyone there saw it: a sender left not
+ knowing their message was blocked is worse than a notice others can
+ read. In a direct conversation the channel is already private. An
+ app's post, or one from an account many people share (Telegram's
+ stand-in for anonymous admins), has no one person to reach, so its
+ notice goes straight to the channel. Never lets a failed notice take
+ the inbound message down with it, which mirrors
`AgentCore._post_trust_blocked_notice`."""
+ delivery = self._adapter.private_notice_delivery
+ no_one_to_reach = (
+ msg.sender_is_app
+ or self._adapter.unlinkable_account_reason(msg.sender_id) is not None
+ )
+ if msg.channel_type != "direct":
+ if no_one_to_reach:
+ logger.info(
+ "The Switch Trust %s notice for %s goes in channel %s: an "
+ "app or a shared account has no one person to tell",
+ message_type.value,
+ msg.sender_name,
+ msg.channel_id,
+ )
+ elif delivery == "in_channel":
+ logger.warning(
+ "%s has no way to reach one person privately: posting the "
+ "Switch Trust %s notice for %s in channel %s, where "
+ "everyone in it sees it",
+ self._adapter.platform_name,
+ message_type.value,
+ msg.sender_name,
+ msg.channel_id,
+ )
+ else:
+ try:
+ await self._adapter.notify_privately(
+ channel_id=msg.channel_id,
+ channel_name=msg.channel_name,
+ user_id=msg.sender_id,
+ content=body,
+ # Where the sender is looking: their thread, or the
+ # channel itself for a top-level message, since a
+ # private notice opens no thread anyone would see.
+ thread_root_id=msg.root_id,
+ )
+ return
+ except PrivateNoticeRefused as refused:
+ logger.warning(
+ "%s would not let the bot reach %s privately (%s): "
+ "posting the Switch Trust %s notice in channel %s "
+ "instead, where everyone in it sees it",
+ self._adapter.platform_name,
+ msg.sender_name,
+ refused,
+ message_type.value,
+ msg.channel_id,
+ )
+ except Exception:
+ logger.warning(
+ "Could not send the Switch Trust %s notice to %s by %s: "
+ "posting it in channel %s instead, where everyone in it "
+ "sees it",
+ message_type.value,
+ msg.sender_name,
+ delivery,
+ msg.channel_id,
+ exc_info=True,
+ )
try:
await self._adapter.admin_message(
msg.channel_id,
diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.py
index c85985c60..41337794d 100644
--- a/core/switch_core/bridges/collaboration/discord/adapter.py
+++ b/core/switch_core/bridges/collaboration/discord/adapter.py
@@ -26,6 +26,7 @@ from switch_core.bridges.collaboration.adapter import (
AgentIdentity,
ChannelNotBindable,
PlatformAdapter,
+ PrivateNoticeRefused,
RemovalFailed,
RequestCard,
RichContent,
@@ -61,6 +62,7 @@ from switch_core.bridges.collaboration.models import (
InboundInteraction,
InboundMessage,
InboundUserJoin,
+ PrivateNoticeDelivery,
RetireOutcome,
)
from switch_core.bridges.collaboration.session.renderers import (
@@ -589,6 +591,10 @@ class DiscordAdapter(PlatformAdapter):
# nobody.
notifies_only_by_mention: ClassVar[bool] = True
channel_mention: ClassVar[str | None] = "@everyone"
+ #: Discord shows a bot's message to one member of a channel only in answer
+ #: to an interaction, and a posted message is not one, so a notice about
+ #: it goes to them as a direct message from the bot.
+ private_notice_delivery: ClassVar[PrivateNoticeDelivery] = "direct_message"
# The status is the turn's one post, so the clock rides along with the next
# real change rather than rewriting a message somebody is reading. See the
@@ -1187,6 +1193,36 @@ class DiscordAdapter(PlatformAdapter):
where=f"channel {channel_id}",
)
+ async def notify_privately(
+ self,
+ *,
+ channel_id: str,
+ channel_name: str | None,
+ user_id: str,
+ content: str,
+ thread_root_id: str | None,
+ ) -> None:
+ """A direct message from the bot, naming the channel the message was
+ posted in, split over several if it is past Discord's length cap.
+ Discord refuses it when the person does not accept direct messages
+ from members of the server, and that refusal is raised as
+ `PrivateNoticeRefused`."""
+ client = self._require_client()
+ user = client.get_user(int(user_id)) or await client.fetch_user(int(user_id))
+ body = (
+ f"About your message in <#{channel_id}>:\n"
+ f"{self.translate_outbound(content)}"
+ )
+ try:
+ for chunk in chunk_message(body):
+ await user.send(
+ chunk,
+ suppress_embeds=True,
+ allowed_mentions=NO_MASS_MENTIONS,
+ )
+ except discord.Forbidden as refused:
+ raise PrivateNoticeRefused(str(refused)) from refused
+
async def update_message(
self, channel_id: str, message_ref: str, new_content: str
) -> None:
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index 145090d2f..cd05b4fee 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -72,6 +72,7 @@ from switch_core.bridges.collaboration.models import (
InboundMessage,
InboundUserJoin,
OutboundAttachment,
+ PrivateNoticeDelivery,
RetireOutcome,
)
from switch_core.bridges.collaboration.session.renderers import (
@@ -451,6 +452,9 @@ class MattermostAdapter(PlatformAdapter):
#: carried over: it is the one that reaches the person who can do something.
notifies_only_by_mention: ClassVar[bool] = True
channel_mention: ClassVar[str | None] = "@channel"
+ #: `POST /posts/ephemeral`, made as the admin the bridge connects as: the
+ #: endpoint needs `create_post_ephemeral`, which a system admin holds.
+ private_notice_delivery: ClassVar[PrivateNoticeDelivery] = "ephemeral"
#: The status is the turn's one post, not a line beside it, so the clock
#: advancing is not on its own worth rewriting what a reader is reading.
@@ -933,6 +937,33 @@ class MattermostAdapter(PlatformAdapter):
return
await super().tell_actor(channel_id, actor_ref, actor_name, thread_ref, text)
+ async def notify_privately(
+ self,
+ *,
+ channel_id: str,
+ channel_name: str | None,
+ user_id: str,
+ content: str,
+ thread_root_id: str | None,
+ ) -> None:
+ """An ephemeral post: shown in the channel, in the message's thread,
+ to the person who posted it and to nobody else, and gone on reload."""
+ loop = self._main_loop
+ driver = self._admin_driver
+ if loop is None or driver is None:
+ raise RuntimeError("Mattermost is not connected")
+ post: dict[str, Any] = {
+ "channel_id": channel_id,
+ "message": self.translate_outbound(content),
+ }
+ if thread_root_id is not None:
+ post["root_id"] = thread_root_id
+ await loop.run_in_executor(
+ None,
+ driver.posts.create_ephemeral_post,
+ {"user_id": user_id, "post": post},
+ )
+
# ── Messaging ────────────────────────────────────────────────────────────
async def send_message(
diff --git a/core/switch_core/bridges/collaboration/models.py b/core/switch_core/bridges/collaboration/models.py
index 704c3c9d3..e9cbaf8bc 100644
--- a/core/switch_core/bridges/collaboration/models.py
+++ b/core/switch_core/bridges/collaboration/models.py
@@ -23,6 +23,15 @@ channel Switch has no permission to touch, which somebody removes on the
platform itself.
"""
+PrivateNoticeDelivery = Literal["ephemeral", "direct_message", "in_channel"]
+"""How a bridge says something to one person about a message they posted.
+
+`ephemeral` is shown in the channel to that person alone; `direct_message`
+goes to a private chat between them and the bot; `in_channel` is a platform
+where a bot can do neither unprompted, so the notice is posted where everyone
+in the channel sees it.
+"""
+
class RetireOutcome(BaseModel):
"""What happened to a room's platform channel when the room was deleted.
diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.py
index 0b6c55de6..7fc49eb6d 100644
--- a/core/switch_core/bridges/collaboration/slack/adapter.py
+++ b/core/switch_core/bridges/collaboration/slack/adapter.py
@@ -54,6 +54,7 @@ from switch_core.bridges.collaboration.models import (
InboundMessage,
InboundUserJoin,
OutboundAttachment,
+ PrivateNoticeDelivery,
RetireOutcome,
)
from switch_core.bridges.collaboration.session.renderers.slack import (
@@ -486,6 +487,8 @@ class SlackAdapter(PlatformAdapter):
draws_session_activity: ClassVar[bool] = True
separate_attention_slot: ClassVar[bool] = True
channel_mention: ClassVar[str | None] = "<!channel>"
+ #: `chat.postEphemeral`: in the channel, to one member alone.
+ private_notice_delivery: ClassVar[PrivateNoticeDelivery] = "ephemeral"
#: Cheap on a stream in a way it never was on an edit. An append is rate
#: limited at 100+/min and redraws nothing, so the clock ticks in the one
#: message without disturbing what is open in front of a reader.
@@ -1824,6 +1827,26 @@ class SlackAdapter(PlatformAdapter):
text,
)
+ async def notify_privately(
+ self,
+ *,
+ channel_id: str,
+ channel_name: str | None,
+ user_id: str,
+ content: str,
+ thread_root_id: str | None,
+ ) -> None:
+ """An ephemeral message: shown in the channel, in the message's
+ thread, to the person who posted it and to nobody else."""
+ if not self._web_client:
+ raise RuntimeError("Slack client not connected")
+ await self._web_client.chat_postEphemeral(
+ channel=channel_id,
+ user=user_id,
+ text=self.translate_outbound(content),
+ thread_ts=self._thread_ts_of(thread_root_id),
+ )
+
def adapt_icon_url(self, icon_url: str) -> str:
# Overridden for Slack alone: it flattens a transparent avatar onto
# white. Adjusting here rather than at each call site keeps every place
diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.py
index 2d2d167a5..956b56774 100644
--- a/core/switch_core/bridges/collaboration/teams/adapter.py
+++ b/core/switch_core/bridges/collaboration/teams/adapter.py
@@ -46,6 +46,7 @@ from switch_core.bridges.collaboration.models import (
InboundInteraction,
InboundMessage,
InboundUserJoin,
+ PrivateNoticeDelivery,
)
from switch_core.bridges.collaboration.session.renderers import (
INTERRUPT_QUEUED_NOTE,
@@ -769,6 +770,11 @@ class TeamsAdapter(PlatformAdapter):
# Switch is not granted Channel.Delete.All, so a deleted room's channel
# stays for someone to remove in Teams.
channel_on_delete = "kept"
+ #: A Teams bot cannot show a channel message to one member alone, and
+ #: opening a 1:1 chat needs the app installed for that person, which
+ #: Switch does not arrange, so a notice about someone's message is posted
+ #: in the channel where everyone sees it.
+ private_notice_delivery: ClassVar[PrivateNoticeDelivery] = "in_channel"
docs_slug: ClassVar[str | None] = "microsoft-teams"
# Graph delivers a channel's messages to every subscription made for it,
# so only the process holding the bridge makes, adopts and renews them.
diff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.py
index e097024d7..28076e06c 100644
--- a/core/switch_core/bridges/collaboration/telegram/adapter.py
+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py
@@ -45,6 +45,7 @@ from switch_core.bridges.collaboration.adapter import (
AgentIdentity,
ChannelNotBindable,
PlatformAdapter,
+ PrivateNoticeRefused,
RemovalFailed,
RequestCard,
RichContent,
@@ -69,6 +70,7 @@ from switch_core.bridges.collaboration.models import (
InboundMessage,
InboundUserJoin,
OutboundAttachment,
+ PrivateNoticeDelivery,
RetireOutcome,
)
from switch_core.bridges.collaboration.session.renderers import (
@@ -528,6 +530,9 @@ class TelegramAdapter(PlatformAdapter):
display_name: ClassVar[str] = "Telegram"
# The Bot API has no call to delete or archive a chat.
channel_on_delete = "left"
+ #: A bot cannot show a group message to one member alone, so a notice
+ #: about one goes to them in their private chat with the bot.
+ private_notice_delivery: ClassVar[PrivateNoticeDelivery] = "direct_message"
docs_slug: ClassVar[str | None] = "telegram"
# A quiet self-registered bridge does not poll: Telegram hands each update
# to a single getUpdates caller, so a poller in every process would split
@@ -1366,6 +1371,34 @@ class TelegramAdapter(PlatformAdapter):
thread_root_id,
)
+ async def notify_privately(
+ self,
+ *,
+ channel_id: str,
+ channel_name: str | None,
+ user_id: str,
+ content: str,
+ thread_root_id: str | None,
+ ) -> None:
+ """A message in the person's private chat with the bot, naming the
+ group the message was posted in, split over several if it is past
+ Telegram's length cap. Telegram lets a bot write to someone only after
+ they have started a chat with it, and most members of a group never
+ have, so its refusal is raised as `PrivateNoticeRefused`."""
+ where = f" in {html.escape(channel_name)}" if channel_name else ""
+ bot = self._require_bot()
+ body = f"About your message{where}:\n{self.translate_outbound(content)}"
+ try:
+ for chunk in chunk_message(body):
+ await bot.send_message(
+ chat_id=int(user_id),
+ text=chunk,
+ parse_mode=ParseMode.HTML,
+ link_preview_options=_NO_PREVIEW,
+ )
+ except Forbidden as refused:
+ raise PrivateNoticeRefused(str(refused)) from refused
+
async def update_message(
self, channel_id: str, message_ref: str, new_content: str
) -> None:
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.py
index 323187b1b..4c8e87ef4 100644
--- a/core/switch_core/chats/service.py
+++ b/core/switch_core/chats/service.py
@@ -106,6 +106,14 @@ from switch_core.sessions.attachments import normalise_mime_type
from switch_core.tenant_context import tenant_scope
from switch_core.transport.content import media_content, message_content
from switch_core.transport.types import MessageFormat
+from switch_core.trust.attachments import AttachmentsVerdict, check_attachments
+from switch_core.trust.client import (
+ TrustCheckResult,
+ TrustClient,
+ check_message,
+ trust_annotation,
+ trust_is_active,
+)
if TYPE_CHECKING:
from switch_core.chats.signals import ChatSignals
@@ -180,8 +188,10 @@ class ChatService:
group_chats_enabled: bool,
buddy_slack_handoff_enabled: bool,
connections: AgentConnectionRegistry,
+ trust_client: TrustClient,
) -> None:
self.session_factory = session_factory
+ self._trust_client = trust_client
self._connections = connections
self.agent_chats_enabled = agent_chats_enabled
self.group_chats_enabled = group_chats_enabled
@@ -1747,6 +1757,10 @@ class ChatService:
`mention_spans` say where in `body` each mention is written (UTF-16
offsets, as the Console's strings count); an agent's span is for it as
`mention_agent_ids` is, a person's addresses no agent.
+
+ Switch Trust checks the text and each file first, as it does a
+ message from any other platform, and a refusal of either raises
+ ChatError TRUST_BLOCKED with nothing posted.
"""
mentions = sorted(set(mention_agent_ids))
people = sorted(set(mention_user_ids))
@@ -1775,6 +1789,14 @@ class ChatService:
people = sorted(
{*people, *(span.id for span in mention_spans if span.kind == "user")}
)
+ body = await self._checked_by_trust(
+ tenant_id,
+ user,
+ room_id,
+ request_id=request_id,
+ body=body,
+ upload_ids=upload_ids,
+ )
async with tenant_session(self.session_factory, tenant_id) as session:
room, client = await self.require_member(session, tenant_id, user, room_id)
operation = await self._operation(session, user.id, request_id)
@@ -2117,6 +2139,105 @@ class ChatService:
)
return sorted(rows, key=lambda m: m.seq)
+ async def _checked_by_trust(
+ self,
+ tenant_id: str,
+ user: User,
+ room_id: str,
+ *,
+ request_id: str,
+ body: str,
+ upload_ids: list[str],
+ ) -> str:
+ """The body to post once Switch Trust has checked it and the files
+ (`trust/attachments.py`): redacted if it redacted the text, with a
+ note for anything flagged or not checked. Runs before the send's own
+ transaction, so no database work waits on Switch Trust."""
+ if not await trust_is_active(self._trust_client):
+ return body
+ async with tenant_session(self.session_factory, tenant_id) as session:
+ room, _ = await self.require_member(session, tenant_id, user, room_id)
+ if await self._operation(session, user.id, request_id) is not None:
+ # A retry: `send` answers it with what was posted the first time.
+ return body
+ files: list[tuple[bytes, str, str]] = []
+ for upload_id in upload_ids:
+ upload = await self._staged_upload(session, user.id, room.id, upload_id)
+ blob = await self._media_store.get(session, upload.uri)
+ if blob is None:
+ raise ChatError(
+ 422,
+ "UPLOAD_NOT_FOUND",
+ f"No file was uploaded to this chat as {upload_id}.",
+ )
+ files.append((blob.data, upload.filename, upload.mimetype))
+
+ text_check: TrustCheckResult | None = None
+ files_check = AttachmentsVerdict()
+ if body.strip() and files:
+ text_check, files_check = await asyncio.gather(
+ check_message(
+ self._trust_client, role="user", content=body, room_id=room.id
+ ),
+ check_attachments(
+ self._trust_client, role="user", files=files, room_id=room.id
+ ),
+ )
+ elif body.strip():
+ text_check = await check_message(
+ self._trust_client, role="user", content=body, room_id=room.id
+ )
+ elif files:
+ files_check = await check_attachments(
+ self._trust_client, role="user", files=files, room_id=room.id
+ )
+
+ if text_check is not None and (
+ text_check.blocked
+ or (
+ text_check.outcome == "redacted" and text_check.redacted_content is None
+ )
+ ):
+ categories = (
+ ", ".join(sorted({f.category for f in text_check.findings}))
+ or "policy violation"
+ )
+ logger.warning(
+ "Chat message from user %s in room %s not posted: Switch Trust "
+ "outcome=%s (%s)",
+ user.id,
+ room.id,
+ text_check.outcome,
+ categories,
+ )
+ raise ChatError(
+ 422,
+ "TRUST_BLOCKED",
+ f"Switch Trust blocked this message ({categories}). Nothing was sent.",
+ )
+ if files_check.blocked:
+ reasons = "; ".join(files_check.block_reasons)
+ logger.warning(
+ "Chat message from user %s in room %s not posted: Switch Trust "
+ "blocked its files: %s",
+ user.id,
+ room.id,
+ reasons,
+ )
+ raise ChatError(
+ 422,
+ "TRUST_BLOCKED",
+ f"Switch Trust blocked this message: {reasons}. Nothing was sent.",
+ )
+ if text_check is not None and text_check.redacted_content is not None:
+ body = text_check.redacted_content
+ annotation = trust_annotation(text_check) if text_check is not None else None
+ notes = [*([annotation] if annotation is not None else []), *files_check.notes]
+ if notes:
+ notes_text = "\n".join(notes)
+ body = f"{body}\n\n{notes_text}" if body.strip() else notes_text
+ return body
+
async def _staged_upload(
self, session: AsyncSession, user_id: str, room_id: str, upload_id: str
) -> StagedUpload:
diff --git a/core/switch_core/clients/actor.py b/core/switch_core/clients/actor.py
index 48acd9208..a37314935 100644
--- a/core/switch_core/clients/actor.py
+++ b/core/switch_core/clients/actor.py
@@ -467,8 +467,10 @@ class SystemActor(Actor[ClientConfig]):
message_type: AdminMessageType,
thread_root_id: str | None,
mentions: list[str] | None = None,
- ) -> None:
- await self.send_message(
+ ) -> str | None:
+ """Post an admin notice. Returns its event id, or None when the
+ transport refused it (logged by `send_message`)."""
+ return await self.send_message(
room_id,
body,
format="markdown",
diff --git a/core/switch_core/file_text.py b/core/switch_core/file_text.py
new file mode 100644
index 000000000..d6256a0dd
--- /dev/null
+++ b/core/switch_core/file_text.py
@@ -0,0 +1,585 @@
+"""The text inside an attached file, read so Switch Trust can check it.
+
+A text-like file (text/*, JSON, YAML, CSV, Markdown, source code, or anything
+else that decodes cleanly as UTF-8) is its decoded text, a Word document
+(.docx) is the text of its body and of the headers, footers, notes and
+comments the body links to, and a PDF is the text of its pages, each up to
+`TRUST_FILE_TEXT_LIMIT` characters. Everything else (images, audio, video,
+archives, other office formats, binaries, scanned PDFs with no text layer,
+files that cannot be parsed) has no text that can be read here. The type and
+extension a file arrives with are the sender's to choose, so a file labelled
+as one of those, or named .docx or .pdf but not one, is still read as text
+when its bytes are text.
+
+Word documents and PDFs are parsed in a separate, short-lived process
+(`read_file_text`), killed if it takes longer than
+`_WORKER_TIMEOUT_SECONDS` and, on Linux, held to `_WORKER_MEMORY_BYTES` of
+address space. A small upload can describe an enormous amount of work (a
+compressed XML part, a page with half a million drawing operations), and no
+limit applied inside one parser call bounds that; a process can be killed.
+This module is also that process's entry point (`python -m
+switch_core.file_text`), so it imports nothing from the server.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import io
+import json
+import logging
+import posixpath
+import resource
+import sys
+import weakref
+import zipfile
+import zlib
+from collections.abc import Iterator
+from dataclasses import asdict, dataclass, field
+from typing import IO, Literal
+from urllib.parse import unquote
+from xml.parsers import expat
+
+from pypdf import PageObject, PdfReader
+from pypdf.generic import ArrayObject, DictionaryObject, IndirectObject, NameObject
+
+from switch_core.sessions.attachments import normalise_mime_type
+
+logger = logging.getLogger(__name__)
+
+# The most text taken from one file for a check. Anything in a file past this
+# point reaches agents WITHOUT being checked by Switch Trust. The cap exists
+# because a check has to answer inside `switch_trust_timeout_seconds` (2s by
+# default) and Switch Trust is built for a message's worth of text, not a
+# whole log or book; a slower check would fail open as "could not check"
+# anyway. Every file cut here carries a visible note on the message saying so,
+# and a WARNING is logged, so the gap is never silent.
+TRUST_FILE_TEXT_LIMIT = 20_000
+
+# Bounds on reading documents, so a small upload cannot cost unbounded work.
+# A .docx is a zip: only members stored or deflated are opened (Python's
+# LZMA and bzip2 readers can inflate far past what was asked of them in a
+# single read), and only while their declared size fits what is left of this
+# budget, which zipfile then holds them to. A PDF is read page by page, up to
+# this many pages, through a page tree of at most this many nodes.
+_DOCX_XML_BYTE_BUDGET = 8 * 1024 * 1024
+_DOCX_RELS_BYTE_LIMIT = 1024 * 1024
+_PDF_PAGE_LIMIT = 200
+_PDF_TREE_NODE_LIMIT = 10_000
+
+# The worker process that parses a document. Ten seconds is far more than a
+# real document needs to give up its first 20,000 characters, and short
+# enough that a hostile one cannot hold a message for long. 512 MiB of address
+# space leaves room for the interpreter, pypdf and the largest upload Switch
+# accepts. Two at once keeps a burst of documents from taking every core.
+_WORKER_TIMEOUT_SECONDS = 10.0
+_WORKER_MEMORY_BYTES = 512 * 1024 * 1024
+_WORKER_SLOTS = 2
+
+_DOCX_TYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
+_PDF_TYPE = "application/pdf"
+_W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
+
+# Relationship types (the last segment of a relationship's Type) of the
+# parts a reader of a Word document sees text from, besides the body.
+_DOCX_TEXT_PARTS = frozenset({"header", "footer", "footnotes", "endnotes", "comments"})
+# Relationship types whose content Word shows as part of the document but
+# which are not WordprocessingML this module can read.
+_DOCX_OPAQUE_PARTS = {
+ "aFChunk": "an embedded document",
+ "subDocument": "a subdocument",
+}
+_ZIP_READABLE = frozenset({zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED})
+
+# Types Switch has no way to read the text of. The type is only what the
+# sender declared, so a file of one of these is still read as text when its
+# bytes decode cleanly: real images and archives almost never do, and
+# checking a few that happen to costs far less than relaying unchecked text.
+_TEXTLESS_KINDS: tuple[tuple[str, str], ...] = (
+ ("image/", "images cannot be checked"),
+ ("audio/", "audio cannot be checked"),
+ ("video/", "video cannot be checked"),
+ ("font/", "fonts cannot be checked"),
+ ("application/msword", "older Word documents (.doc) cannot be checked"),
+ (
+ "application/vnd.openxmlformats-officedocument.",
+ "Office documents other than Word cannot be checked",
+ ),
+ ("application/vnd.ms-", "Office documents other than Word cannot be checked"),
+ ("application/vnd.oasis.opendocument.", "OpenDocument files cannot be checked"),
+ ("application/zip", "archives cannot be checked"),
+ ("application/gzip", "archives cannot be checked"),
+ ("application/x-tar", "archives cannot be checked"),
+ ("application/x-7z-compressed", "archives cannot be checked"),
+ ("application/x-rar-compressed", "archives cannot be checked"),
+ ("application/vnd.rar", "archives cannot be checked"),
+ ("application/x-bzip2", "archives cannot be checked"),
+ ("application/x-xz", "archives cannot be checked"),
+)
+
+DocumentKind = Literal["docx", "pdf"]
+
+
+@dataclass(frozen=True)
+class FileText:
+ """The text a file is checked as, or why it has none.
+
+ Exactly one of `text` and `unreadable_reason` is set. `checked_part` is
+ set when only the start of the file was read ("the first 20,000
+ characters"), and `skipped` names the parts of it that could not be read
+ at all (a Word document's embedded document), each for the note that
+ says so. `textless` is set when the file is of a kind Switch never reads
+ text from (an image, an archive, a binary), as opposed to one it tried
+ and failed to read."""
+
+ text: str | None
+ checked_part: str | None = None
+ unreadable_reason: str | None = None
+ skipped: tuple[str, ...] = field(default=())
+ textless: bool = False
+
+
+def _unreadable(reason: str) -> FileText:
+ return FileText(text=None, unreadable_reason=reason)
+
+
+def _capped(
+ text: str, checked_part: str | None = None, skipped: tuple[str, ...] = ()
+) -> FileText:
+ if len(text) > TRUST_FILE_TEXT_LIMIT:
+ return FileText(
+ text=text[:TRUST_FILE_TEXT_LIMIT],
+ checked_part=f"the first {TRUST_FILE_TEXT_LIMIT:,} characters",
+ skipped=skipped,
+ )
+ return FileText(text=text, checked_part=checked_part, skipped=skipped)
+
+
+def _as_text(data: bytes) -> FileText | None:
+ """`data` as text, or None when it is not cleanly text."""
+ try:
+ text = data.decode("utf-8-sig")
+ except UnicodeDecodeError:
+ return None
+ if "\x00" in text:
+ # Valid UTF-8 can still be binary: NUL never appears in real text.
+ return None
+ return _capped(text)
+
+
+def _unparsed(data: bytes, reason: str) -> FileText:
+ """A file sent to a document parser that could not parse it. It went
+ there by its declared type or extension, which the sender chooses, so
+ one whose bytes are text is checked as text instead."""
+ return _as_text(data) or _unreadable(reason)
+
+
+def _refuse_dtd(*_args: object) -> None:
+ # Word never writes a DTD; one here is a crafted file (entity expansion),
+ # not a document. Expat reports the declaration itself, so it is caught
+ # whatever the encoding or chunk boundaries.
+ raise ValueError("document declares a DTD")
+
+
+def _docx_part_text(stream: IO[bytes], budget: int) -> tuple[str, int, bool]:
+ """The visible text of one WordprocessingML part, read through
+ `stream` (a decompressing zip member) a chunk at a time. Returns the
+ text, the bytes read, and whether it stopped before the end of the part
+ (byte budget or text cap reached)."""
+ parser = expat.ParserCreate(namespace_separator="}")
+ pieces: list[str] = []
+ in_text = False
+ length = 0
+
+ def start(tag: str, _attrs: object) -> None:
+ nonlocal in_text
+ name = "{" + tag
+ if name == f"{_W}t":
+ in_text = True
+ elif name == f"{_W}tab":
+ pieces.append("\t")
+ elif name == f"{_W}br":
+ pieces.append("\n")
+
+ def end(tag: str) -> None:
+ nonlocal in_text
+ name = "{" + tag
+ if name == f"{_W}t":
+ in_text = False
+ elif name == f"{_W}p":
+ pieces.append("\n")
+
+ def text(data: str) -> None:
+ nonlocal length
+ if in_text:
+ pieces.append(data)
+ length += len(data)
+
+ parser.StartDoctypeDeclHandler = _refuse_dtd
+ parser.EntityDeclHandler = _refuse_dtd
+ parser.StartElementHandler = start
+ parser.EndElementHandler = end
+ parser.CharacterDataHandler = text
+ read = 0
+ while True:
+ chunk = stream.read(min(64 * 1024, budget - read))
+ if not chunk:
+ stopped_early = bool(stream.read(1))
+ if not stopped_early:
+ parser.Parse(b"", True)
+ return "".join(pieces), read, stopped_early
+ read += len(chunk)
+ parser.Parse(chunk, False)
+ if length > TRUST_FILE_TEXT_LIMIT:
+ return "".join(pieces), read, True
+
+
+_UNREADABLE_COMPRESSION = "uses a compression Switch Trust does not read"
+
+
+def _member_problem(info: zipfile.ZipInfo, budget: int) -> str | None:
+ """Why a zip member is not opened, checked from its header alone."""
+ if info.compress_type not in _ZIP_READABLE:
+ return _UNREADABLE_COMPRESSION
+ if info.file_size > budget:
+ return "is larger than Switch Trust reads"
+ return None
+
+
+@dataclass(frozen=True)
+class _Relationship:
+ kind: str
+ target: str | None
+ """The part's name in the zip, or None for a link outside the file."""
+
+
+def _relationships(
+ archive: zipfile.ZipFile, members: dict[str, zipfile.ZipInfo], source: str
+) -> list[_Relationship] | None:
+ """The relationships of `source` ("" for the package itself), from its
+ .rels part; None when it has none. Raises ValueError when the .rels part
+ cannot be read safely."""
+ directory, name = posixpath.split(source)
+ info = members.get(posixpath.join(directory, "_rels", f"{name}.rels").lower())
+ if info is None:
+ return None
+ problem = _member_problem(info, _DOCX_RELS_BYTE_LIMIT)
+ if problem is not None:
+ raise ValueError(f"{info.filename} {problem}")
+ found: list[_Relationship] = []
+
+ def start(tag: str, attrs: dict[str, str]) -> None:
+ if not tag.endswith("}Relationship") or "Target" not in attrs:
+ return
+ kind = attrs.get("Type", "").rpartition("/")[2]
+ if attrs.get("TargetMode") == "External":
+ found.append(_Relationship(kind, None))
+ return
+ target = unquote(attrs["Target"])
+ path = (
+ target[1:] if target.startswith("/") else posixpath.join(directory, target)
+ )
+ path = posixpath.normpath(path)
+ found.append(_Relationship(kind, None if path.startswith("..") else path))
+
+ parser = expat.ParserCreate(namespace_separator="}")
+ parser.StartDoctypeDeclHandler = _refuse_dtd
+ parser.EntityDeclHandler = _refuse_dtd
+ parser.StartElementHandler = start
+ with archive.open(info) as stream:
+ parser.Parse(stream.read(_DOCX_RELS_BYTE_LIMIT), True)
+ return found
+
+
+def _docx_text(data: bytes) -> FileText:
+ skipped: list[str] = []
+ try:
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ members = {info.filename.lower(): info for info in archive.infolist()}
+ # The body is the part the package names as its main document; a
+ # zip without the package's own list is read as Word lays it out.
+ package = _relationships(archive, members, "")
+ if package is None:
+ main: str | None = "word/document.xml"
+ else:
+ main = next(
+ (r.target for r in package if r.kind == "officeDocument"), None
+ )
+ if main is None or main.lower() not in members:
+ return _unparsed(data, "this Word document could not be read")
+ parts = [members[main.lower()]]
+ try:
+ links = _relationships(archive, members, members[main.lower()].filename)
+ except ValueError as error:
+ skipped.append(f"its headers, footers, notes and comments ({error})")
+ links = []
+ for link in links or []:
+ if link.kind in _DOCX_OPAQUE_PARTS:
+ skipped.append(_DOCX_OPAQUE_PARTS[link.kind])
+ elif link.kind not in _DOCX_TEXT_PARTS:
+ continue
+ elif link.target is None or link.target.lower() not in members:
+ skipped.append(
+ f"a {link.kind} part it links to but does not contain"
+ )
+ elif members[link.target.lower()] not in parts:
+ parts.append(members[link.target.lower()])
+
+ pieces: list[str] = []
+ budget = _DOCX_XML_BYTE_BUDGET
+ stopped_early = False
+ for index, info in enumerate(parts):
+ problem = _member_problem(info, budget)
+ # A body larger than the budget is read up to it rather than
+ # not at all: the reader stops there, so the size its header
+ # declares costs nothing, and its start is still checked.
+ if problem is not None and (
+ index > 0 or problem == _UNREADABLE_COMPRESSION
+ ):
+ if index == 0:
+ return _unreadable(f"this Word document {problem}")
+ skipped.append(f"{info.filename}, which {problem}")
+ continue
+ with archive.open(info) as stream:
+ text, read, stopped_early = _docx_part_text(stream, budget)
+ pieces.append(text)
+ budget -= read
+ if stopped_early:
+ break
+ except (
+ zipfile.BadZipFile,
+ expat.ExpatError,
+ ValueError,
+ OSError,
+ EOFError,
+ zlib.error,
+ # What zipfile raises for an encrypted member.
+ RuntimeError,
+ ):
+ logger.warning("Could not read text from a Word document", exc_info=True)
+ return _unparsed(data, "this Word document could not be read")
+ text = "\n".join(p for p in pieces if p)
+ if not text.strip():
+ if skipped:
+ return _unreadable(
+ f"no text found in this Word document, and {'; '.join(skipped)} "
+ "could not be read"
+ )
+ return _unreadable("no text found in this Word document")
+ # Reading stops early at the text cap, which `_capped` reports, or at the
+ # byte budget, with less text than the cap.
+ checked_part = (
+ "the first part"
+ if stopped_early and len(text) <= TRUST_FILE_TEXT_LIMIT
+ else None
+ )
+ return _capped(text, checked_part, skipped=tuple(skipped))
+
+
+def _pdf_pages(reader: PdfReader) -> Iterator[PageObject]:
+ """The document's pages in order, found one at a time. `reader.pages`
+ walks the whole page tree before giving the first page, which a crafted
+ tree makes as costly as its author likes."""
+ pending: list[tuple[object, dict[str, object]]] = [
+ (reader.root_object.get("/Pages"), {})
+ ]
+ seen: set[tuple[int, int]] = set()
+ visited = 0
+ while pending:
+ visited += 1
+ if visited > _PDF_TREE_NODE_LIMIT:
+ raise ValueError("the page tree is larger than Switch Trust reads")
+ entry, inherited = pending.pop()
+ reference = entry if isinstance(entry, IndirectObject) else None
+ if reference is not None:
+ key = (reference.idnum, reference.generation)
+ if key in seen:
+ continue
+ seen.add(key)
+ entry = reference.get_object()
+ if not isinstance(entry, DictionaryObject):
+ continue
+ kids = entry.get("/Kids")
+ if entry.get("/Type") == "/Pages" or (
+ kids is not None and entry.get("/Type") != "/Page"
+ ):
+ passed_down = dict(inherited)
+ for name in ("/Resources", "/MediaBox", "/CropBox", "/Rotate"):
+ if name in entry:
+ passed_down[name] = entry[name]
+ kids = kids.get_object() if kids is not None else None
+ if isinstance(kids, ArrayObject):
+ pending.extend((kid, passed_down) for kid in reversed(kids))
+ continue
+ page = PageObject(reader, reference)
+ if reference is None:
+ page.update(entry)
+ for name, value in inherited.items():
+ if name not in page:
+ page[NameObject(name)] = value # type: ignore[assignment]
+ yield page
+
+
+def _pdf_text(data: bytes) -> FileText:
+ pieces: list[str] = []
+ length = 0
+ checked_part: str | None = None
+ try:
+ reader = PdfReader(io.BytesIO(data))
+ if reader.is_encrypted:
+ return _unreadable("encrypted PDFs cannot be checked")
+ for number, page in enumerate(_pdf_pages(reader)):
+ if number >= _PDF_PAGE_LIMIT:
+ checked_part = f"the first {_PDF_PAGE_LIMIT} pages"
+ break
+ page_text = page.extract_text() or ""
+ pieces.append(page_text)
+ length += len(page_text)
+ if length > TRUST_FILE_TEXT_LIMIT:
+ break
+ except MemoryError:
+ raise
+ except Exception:
+ # pypdf raises a wide and unstable set of errors on malformed input
+ # (its own, but also ValueError, KeyError, struct errors); any of
+ # them means the same here: this PDF could not be read.
+ logger.warning("Could not read text from a PDF", exc_info=True)
+ return _unparsed(data, "this PDF could not be read")
+ text = "\n".join(pieces)
+ if not text.strip():
+ # A scanned PDF is pictures of text: nothing to check is not clean.
+ return _unreadable("no text found in this PDF, it may be scanned")
+ return _capped(text, checked_part)
+
+
+def _document_kind(data: bytes, mimetype: str, filename: str) -> DocumentKind | None:
+ """Documents are recognised by type or file extension, since platforms
+ often label them application/octet-stream."""
+ kind = normalise_mime_type(mimetype)
+ extension = filename.lower().rpartition(".")[2] if "." in filename else ""
+ if kind == _DOCX_TYPE or extension == "docx":
+ return "docx"
+ if kind == _PDF_TYPE or extension == "pdf" or data.startswith(b"%PDF-"):
+ return "pdf"
+ return None
+
+
+def _document_text(kind: DocumentKind, data: bytes) -> FileText:
+ return _docx_text(data) if kind == "docx" else _pdf_text(data)
+
+
+def extract_file_text(data: bytes, mimetype: str, filename: str) -> FileText:
+ """The text Switch Trust should check for one file, read in this
+ process. Never raw binary: anything that is not cleanly text comes back
+ unreadable, with a reason a person can read. Use `read_file_text` for a
+ file from outside; this parses documents with no bound on time or
+ memory."""
+ document = _document_kind(data, mimetype, filename)
+ if document is not None:
+ return _document_text(document, data)
+ as_text = _as_text(data)
+ if as_text is not None:
+ return as_text
+ kind = normalise_mime_type(mimetype)
+ reason = next(
+ (reason for prefix, reason in _TEXTLESS_KINDS if kind.startswith(prefix)),
+ "binary files cannot be checked",
+ )
+ return FileText(text=None, unreadable_reason=reason, textless=True)
+
+
+_worker_slots: weakref.WeakKeyDictionary[
+ asyncio.AbstractEventLoop, asyncio.Semaphore
+] = weakref.WeakKeyDictionary()
+
+
+def _slots() -> asyncio.Semaphore:
+ loop = asyncio.get_running_loop()
+ slots = _worker_slots.get(loop)
+ if slots is None:
+ slots = _worker_slots[loop] = asyncio.Semaphore(_WORKER_SLOTS)
+ return slots
+
+
+async def read_file_text(data: bytes, mimetype: str, filename: str) -> FileText:
+ """`extract_file_text` for a file from outside: a Word document or a PDF
+ is parsed in a worker process held to a time limit and, on Linux, a
+ memory limit, and one that exceeds either comes back unreadable, with a
+ WARNING logged."""
+ document = _document_kind(data, mimetype, filename)
+ if document is None:
+ return await asyncio.to_thread(extract_file_text, data, mimetype, filename)
+ async with _slots():
+ return await _read_in_worker(document, data, filename)
+
+
+async def _read_in_worker(kind: DocumentKind, data: bytes, filename: str) -> FileText:
+ process = await asyncio.create_subprocess_exec(
+ sys.executable,
+ "-m",
+ "switch_core.file_text",
+ kind,
+ str(_WORKER_MEMORY_BYTES),
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ try:
+ stdout, stderr = await asyncio.wait_for(
+ process.communicate(data), _WORKER_TIMEOUT_SECONDS
+ )
+ except TimeoutError:
+ logger.warning(
+ "Reading the text of %s took longer than %.0fs; stopped it, and the "
+ "file is not checked by Switch Trust",
+ filename,
+ _WORKER_TIMEOUT_SECONDS,
+ )
+ return _unreadable("it took too long to read")
+ finally:
+ if process.returncode is None:
+ process.kill()
+ await process.wait()
+ errors = stderr.decode(errors="replace").strip()[-4000:]
+ try:
+ if process.returncode != 0:
+ raise ValueError(f"exit status {process.returncode}")
+ fields = json.loads(stdout)
+ result = FileText(
+ text=fields["text"],
+ checked_part=fields["checked_part"],
+ unreadable_reason=fields["unreadable_reason"],
+ skipped=tuple(fields["skipped"]),
+ textless=fields["textless"],
+ )
+ except (ValueError, KeyError, TypeError) as error:
+ logger.warning(
+ "Could not read the text of %s within Switch Trust's limits (%s); "
+ "the file is not checked. Reader output: %s",
+ filename,
+ error,
+ errors or "(none)",
+ )
+ return _unreadable("it could not be read within Switch's limits")
+ if result.unreadable_reason is not None and errors:
+ logger.warning("Reading the text of %s: %s", filename, errors)
+ return result
+
+
+def _limit_memory(limit: int) -> None:
+ # Only Linux enforces an address-space limit; elsewhere the time limit
+ # is the only bound.
+ if sys.platform.startswith("linux"):
+ resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
+
+
+def _worker_main(kind: str, memory_limit: int) -> None:
+ _limit_memory(memory_limit)
+ if kind not in ("docx", "pdf"):
+ raise SystemExit(f"unknown document kind {kind!r}")
+ result = _document_text(kind, sys.stdin.buffer.read()) # type: ignore[arg-type]
+ json.dump(asdict(result), sys.stdout)
+
+
+if __name__ == "__main__":
+ logging.basicConfig(level=logging.WARNING)
+ _worker_main(sys.argv[1], int(sys.argv[2]))
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index 43a3c6396..8b96dc6dd 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -1234,6 +1234,7 @@ async def run(config: SwitchConfig, process_id: str) -> None:
group_chats_enabled=config.group_chats_enabled,
buddy_slack_handoff_enabled=config.buddy_slack_handoff_enabled,
connections=connections,
+ trust_client=trust_client,
)
# Changes to people's chats made in another process wake the Console
# streams held here too (`chats/signals.py`).
diff --git a/core/switch_core/trust/attachments.py b/core/switch_core/trust/attachments.py
new file mode 100644
index 000000000..1833ec347
--- /dev/null
+++ b/core/switch_core/trust/attachments.py
@@ -0,0 +1,220 @@
+"""Switch Trust for files: what an attached file is checked as.
+
+Switch Trust only reads text, so a file is checked through the text it
+carries (`switch_core.file_text`): a text-like file as its decoded text, a
+Word document as the text of its body, headers, footers, notes and comments,
+and a PDF as the text of its pages, each up to `TRUST_FILE_TEXT_LIMIT`
+characters. Everything else (images, audio, video, archives, other office
+formats, binaries, scanned PDFs with no text layer, files that cannot be
+parsed within Switch's limits) cannot be read here, and
+`RELAY_UNCHECKED_FILES` decides what happens to it.
+
+A file cannot be redacted the way a message can, so a REDACTED verdict on a
+file's text blocks the message it came with, the same as BLOCKED.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from collections.abc import Sequence
+from dataclasses import dataclass
+
+from switch_core.file_text import (
+ TRUST_FILE_TEXT_LIMIT,
+ FileText,
+ extract_file_text,
+ read_file_text,
+)
+from switch_core.trust.client import (
+ Role,
+ TrustCheckResult,
+ TrustClient,
+ TrustFinding,
+ check_message,
+)
+
+__all__ = [
+ "RELAY_UNCHECKED_FILES",
+ "TRUST_FILE_TEXT_LIMIT",
+ "AttachmentsVerdict",
+ "FileText",
+ "check_attachments",
+ "extract_file_text",
+]
+
+logger = logging.getLogger(__name__)
+
+# What Switch does with a file Switch Trust cannot read (an image, a scanned
+# PDF, an archive), or with the part of one it cannot. True relays it; False
+# blocks the whole message instead. A file Switch tried and failed to read,
+# or read only in part, carries a visible "not checked" note on the message
+# and a WARNING in the log. A file of a kind Switch never reads (an image, an
+# archive, a binary) carries no note: every screenshot would otherwise tell
+# its sender something they already know. This is the one place that choice
+# is made, for people and agents alike.
+RELAY_UNCHECKED_FILES = True
+
+
+@dataclass(frozen=True)
+class AttachmentsVerdict:
+ """What Switch Trust made of a message's files, taken together.
+
+ `blocked` means nothing from the message may be relayed; `block_reasons`
+ says why, one plain phrase per file, for the notice, and `block` is the
+ verdict to report it under. Otherwise `notes`
+ are the visible annotations the message must carry (a file Switch could
+ not read, checked only in part, flagged, or not checked because Switch
+ Trust failed; a file of a kind Switch never reads gets none), and `flagged` is True when one of them is an ALERTED verdict."""
+
+ block: TrustCheckResult | None = None
+ block_reasons: tuple[str, ...] = ()
+ notes: tuple[str, ...] = ()
+ flagged: bool = False
+
+ @property
+ def blocked(self) -> bool:
+ return self.block is not None
+
+
+def _categories(result: TrustCheckResult, fallback: str) -> str:
+ return ", ".join(sorted({f.category for f in result.findings})) or fallback
+
+
+async def check_attachments(
+ client: TrustClient,
+ *,
+ role: Role,
+ files: Sequence[tuple[bytes, str, str]],
+ room_id: str,
+) -> AttachmentsVerdict:
+ """Check every file in `files` ((data, filename, mimetype) each) against
+ Switch Trust, concurrently. Only call this when Switch Trust is on
+ (`trust_is_active`): when it is off, no file is read at all."""
+ texts = await asyncio.gather(
+ *(
+ read_file_text(data, mimetype, filename)
+ for data, filename, mimetype in files
+ )
+ )
+ extracted = [
+ (filename, file_text)
+ for (_data, filename, _mimetype), file_text in zip(files, texts)
+ ]
+ # Indexed by position, not filename: two files in one post can share a name.
+ to_check = [
+ (index, file_text.text)
+ for index, (_filename, file_text) in enumerate(extracted)
+ if file_text.text is not None and file_text.text.strip()
+ ]
+ results = await asyncio.gather(
+ *(
+ check_message(client, role=role, content=text, room_id=room_id)
+ for _index, text in to_check
+ )
+ )
+ checked = {index: result for (index, _), result in zip(to_check, results)}
+
+ block_reasons: list[str] = []
+ block_result: TrustCheckResult | None = None
+ notes: list[str] = []
+ flagged = False
+ for index, (filename, file_text) in enumerate(extracted):
+ unchecked = (
+ [file_text.unreadable_reason]
+ if file_text.unreadable_reason is not None
+ else list(file_text.skipped)
+ )
+ result = checked.get(index)
+ if result is not None and result.outcome == "blocked":
+ block_reasons.append(
+ f"{filename} was blocked ({_categories(result, 'policy violation')})"
+ )
+ block_result = block_result or result
+ continue
+ if result is not None and result.outcome == "redacted":
+ block_reasons.append(
+ f"{filename} holds content Switch Trust would redact "
+ f"({_categories(result, 'policy violation')}), and a file "
+ "cannot be redacted safely"
+ )
+ block_result = block_result or TrustCheckResult(
+ outcome="blocked",
+ policy_id=result.policy_id,
+ policy_name=result.policy_name,
+ findings=result.findings,
+ )
+ continue
+ if unchecked and not RELAY_UNCHECKED_FILES:
+ what = (
+ "could not be checked"
+ if file_text.text is None
+ else "could not all be checked"
+ )
+ block_reasons.append(f"{filename} {what} ({'; '.join(unchecked)})")
+ block_result = block_result or TrustCheckResult(
+ outcome="blocked",
+ policy_id=None,
+ policy_name=None,
+ findings=(
+ TrustFinding(
+ category="unchecked file",
+ detector_name="switch",
+ severity=None,
+ ),
+ ),
+ )
+ continue
+ if result is not None and result.outcome == "alerted":
+ flagged = True
+ notes.append(
+ f"⚠️ _Switch Trust flagged {filename} (not blocked - "
+ f"{_categories(result, 'policy alert')})._"
+ )
+ elif result is not None and result.outcome == "errored":
+ notes.append(f"⚠️ _Switch Trust could not check {filename}._")
+ if file_text.textless:
+ logger.info(
+ "Switch Trust does not read %s attachment %s (%s); relaying it "
+ "in room %s",
+ files[index][2],
+ filename,
+ file_text.unreadable_reason,
+ room_id,
+ )
+ elif unchecked:
+ what = "" if file_text.text is None else "part of "
+ logger.warning(
+ "Switch Trust did not check %s attachment %s (%s); relaying it "
+ "with a note in room %s",
+ what or "the",
+ filename,
+ "; ".join(unchecked),
+ room_id,
+ )
+ notes.append(
+ f"⚠️ _Switch Trust did not check {what}{filename} "
+ f"({'; '.join(unchecked)})._"
+ )
+ # Noted whether or not the checked part held anything: a file padded
+ # with blank space up to the cap is still unchecked past it.
+ if file_text.checked_part is not None:
+ logger.warning(
+ "Switch Trust checked only %s (%d characters) of attachment %s "
+ "(%d bytes) in room %s; the rest reaches the room unchecked",
+ file_text.checked_part,
+ len(file_text.text or ""),
+ filename,
+ len(files[index][0]),
+ room_id,
+ )
+ notes.append(
+ f"⚠️ _Switch Trust checked only {file_text.checked_part} of "
+ f"{filename}; the rest was not checked._"
+ )
+
+ if block_result is not None:
+ return AttachmentsVerdict(
+ block=block_result, block_reasons=tuple(block_reasons)
+ )
+ return AttachmentsVerdict(notes=tuple(notes), flagged=flagged)
diff --git a/core/switch_core/trust/client.py b/core/switch_core/trust/client.py
index 7cc192252..700feb9d1 100644
--- a/core/switch_core/trust/client.py
+++ b/core/switch_core/trust/client.py
@@ -70,12 +70,15 @@ class GuardrailBlockedError(Exception):
without re-deriving it.
"""
- def __init__(self, result: TrustCheckResult) -> None:
+ def __init__(self, result: TrustCheckResult, detail: str | None = None) -> None:
self.result = result
categories = (
", ".join(f.category for f in result.findings) or "policy violation"
)
- super().__init__(f"blocked by Switch Trust ({categories})")
+ message = f"blocked by Switch Trust ({categories})"
+ if detail is not None:
+ message = f"{message}: {detail}"
+ super().__init__(message)
@dataclass(frozen=True)
@@ -115,10 +118,20 @@ class TrustClient(Protocol):
self, *, role: Role, content: str, room_id: str
) -> TrustCheckResult: ...
+ async def is_active(self) -> bool:
+ """Whether a check would reach Switch Trust at all. Lets a caller skip
+ work that only matters when it does, such as reading text out of
+ attached files. Raises `GuardrailsCheckError` when that cannot be
+ told; `trust_is_active` below is the fail-open wrapper."""
+ ...
+
class NullTrustClient:
"""Off: every message is allowed, and no request is made."""
+ async def is_active(self) -> bool:
+ return False
+
async def check(
self, *, role: Role, content: str, room_id: str
) -> TrustCheckResult:
@@ -177,6 +190,22 @@ class DynamicTrustClient:
self._read_at = None
self._checker = None
+ async def is_active(self) -> bool:
+ """True when the settings row holds everything `check` needs to call
+ Switch Trust, the same test `check` applies before calling it."""
+ try:
+ async with self._session_factory() as session:
+ settings = await self._store.get(session)
+ except Exception as error:
+ raise GuardrailsCheckError(
+ f"Could not read Switch Trust settings: {error}"
+ ) from error
+ return (
+ settings is not None
+ and bool(settings.policy_id)
+ and bool(settings.api_key_encrypted)
+ )
+
async def check(
self, *, role: Role, content: str, room_id: str
) -> TrustCheckResult:
@@ -251,6 +280,9 @@ class HttpTrustClient:
self._timeout_seconds = timeout_seconds
self._client = client
+ async def is_active(self) -> bool:
+ return True
+
async def check(
self, *, role: Role, content: str, room_id: str
) -> TrustCheckResult:
@@ -373,3 +405,18 @@ async def check_message(
exc_info=True,
)
return TrustCheckResult(outcome="errored", policy_id=None, policy_name=None)
+
+
+async def trust_is_active(client: TrustClient) -> bool:
+ """`client.is_active`, failing towards checking: when the settings cannot
+ be read, the caller goes on to check, and each check then fails open with
+ the usual visible "could not check" annotation rather than the message
+ quietly skipping Switch Trust."""
+ try:
+ return await client.is_active()
+ except GuardrailsCheckError:
+ logger.warning(
+ "Could not tell whether Switch Trust is on; checking anyway",
+ exc_info=True,
+ )
+ return True
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.py b/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.py
index ea69d001f..e4e598180 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.py
@@ -312,9 +312,9 @@ class TestSendMessage:
get_by_agent_id=lambda _agent_id: _Client()
)
- event_id = await svc.send_message(member_id, room_id, "hello")
+ sent_message = await svc.send_message(member_id, room_id, "hello")
- assert event_id == "$event"
+ assert sent_message.event_id == "$event"
assert sent == [("!r:test", "hello")]
assert counting.opened == 1
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_send_media_trust.py b/core/tests/switch_core/bridges/agent/protocol/test_send_media_trust.py
new file mode 100644
index 000000000..bcc2877a8
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/protocol/test_send_media_trust.py
@@ -0,0 +1,263 @@
+"""Switch Trust on an agent's files: `send_media` checks its caption the way
+`send_message` checks text, and each file's text, before uploading anything."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from switch_core.bridges.agent.protocol.agent_core import AgentCore
+from switch_core.trust.client import (
+ GuardrailBlockedError,
+ TrustCheckResult,
+ TrustFinding,
+)
+
+# The start of a real PNG: not text, so Switch Trust cannot read it.
+_PNG = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR"
+# A PDF that cannot be parsed and is not text: Switch tries to read it and
+# cannot, so it goes out with a "not checked" note.
+_BROKEN_PDF = b"%PDF-1.4\x00garbage"
+_FINDING = (TrustFinding(category="secrets", detector_name="s", severity="high"),)
+
+
+class _ContentTrustClient:
+ def __init__(self, *, active: bool = True) -> None:
+ self._active = active
+ self.checked: list[tuple[str, str]] = []
+
+ async def is_active(self) -> bool:
+ return self._active
+
+ async def check(self, *, role: str, content: str, room_id: str) -> TrustCheckResult:
+ self.checked.append((role, content))
+ if "FORBIDDEN" in content:
+ return TrustCheckResult("blocked", "p", "policy", _FINDING)
+ if "nothing-to-cut" in content:
+ return TrustCheckResult("redacted", "p", "policy", _FINDING, content)
+ if "token-123" in content:
+ return TrustCheckResult(
+ "redacted",
+ "p",
+ "policy",
+ _FINDING,
+ content.replace("token-123", "[redacted]"),
+ )
+ return TrustCheckResult("ok", "p", "policy")
+
+
+class _FakeClient:
+ def __init__(self) -> None:
+ self.uploads: list[str] = []
+ self.sends: list[dict[str, Any]] = []
+ self.agent = SimpleNamespace(name="helper")
+
+ async def upload_media(self, data: bytes, content_type: str, filename: str) -> str:
+ if filename == "unsendable.txt":
+ raise RuntimeError("upload failed")
+ self.uploads.append(filename)
+ return f"mxc://s/{filename}"
+
+ async def send_media(self, room_id, mxc, filename, mimetype, size, **kw): # noqa: ANN001, ANN003, ANN201
+ self.sends.append({"filename": filename, "caption": kw.get("caption")})
+ return f"$media-event-{len(self.sends)}"
+
+
+def _build(
+ trust: _ContentTrustClient, notice_error: str | None = None
+) -> tuple[AgentCore, _FakeClient, list[Any]]:
+ client = _FakeClient()
+ notices: list[Any] = []
+
+ async def _require(agent_id: str, room_id: str):
+ return SimpleNamespace(id=room_id, transport_room_id="!room", bridge_id=None)
+
+ async def _blocked_notice(room, thread_root_id, client_) -> None: # noqa: ANN001
+ notices.append(("blocked", thread_root_id))
+
+ async def _alert_notice(room, event_id, annotation, outcome) -> str | None: # noqa: ANN001
+ notices.append(("alert", event_id, annotation, outcome))
+ return notice_error
+
+ async def _set_typing(*_args: object) -> None:
+ return None
+
+ svc = object.__new__(AgentCore)
+ svc.require_room_poster = _require # type: ignore[assignment]
+ svc.client_lifecycle = SimpleNamespace( # type: ignore[assignment]
+ get_by_agent_id=lambda agent_id: client
+ )
+ svc.config = SimpleNamespace(agent_media_max_bytes=1000) # type: ignore[assignment]
+ svc.trust_client = trust # type: ignore[assignment]
+ svc._post_trust_blocked_notice = _blocked_notice # type: ignore[method-assign]
+ svc._post_trust_alert_notice = _alert_notice # type: ignore[method-assign]
+ svc._set_typing = _set_typing # type: ignore[method-assign]
+ return svc, client, notices
+
+
+async def test_blocked_caption_sends_nothing_and_raises() -> None:
+ trust = _ContentTrustClient()
+ svc, client, notices = _build(trust)
+
+ with pytest.raises(GuardrailBlockedError):
+ await svc.send_media(
+ "agent-1",
+ "room-1",
+ [(_PNG, "cat.png", "image/png")],
+ caption="FORBIDDEN",
+ )
+
+ assert client.uploads == []
+ assert notices == [("blocked", None)]
+ assert ("assistant", "FORBIDDEN") in trust.checked
+
+
+async def test_redacted_caption_is_sent_redacted() -> None:
+ svc, client, _notices = _build(_ContentTrustClient())
+
+ result = await svc.send_media(
+ "agent-1",
+ "room-1",
+ [(b"fine", "notes.txt", "text/plain")],
+ caption="here is token-123",
+ )
+
+ assert client.sends[0]["caption"] == "here is [redacted]"
+ # The agent is told its caption changed, and to what.
+ assert result["trust"] == {"outcome": "redacted", "delivered": "here is [redacted]"}
+
+
+async def test_a_caption_redaction_that_changed_nothing_is_still_reported() -> None:
+ svc, client, _notices = _build(_ContentTrustClient())
+
+ result = await svc.send_media(
+ "agent-1",
+ "room-1",
+ [(b"fine", "notes.txt", "text/plain")],
+ caption="nothing-to-cut here",
+ )
+
+ assert client.sends[0]["caption"] == "nothing-to-cut here"
+ assert result["trust"] == {
+ "outcome": "redacted",
+ "delivered": "nothing-to-cut here",
+ }
+
+
+async def test_blocked_file_text_sends_nothing_and_says_which_file() -> None:
+ svc, client, notices = _build(_ContentTrustClient())
+
+ with pytest.raises(GuardrailBlockedError, match="leak.env"):
+ await svc.send_media(
+ "agent-1",
+ "room-1",
+ [
+ (_PNG, "cat.png", "image/png"),
+ (b"FORBIDDEN", "leak.env", "text/plain"),
+ ],
+ )
+
+ assert client.uploads == []
+ assert notices == [("blocked", None)]
+
+
+async def test_image_is_sent_without_a_notice() -> None:
+ svc, client, notices = _build(_ContentTrustClient())
+
+ result = await svc.send_media("agent-1", "room-1", [(_PNG, "cat.png", "image/png")])
+
+ assert client.uploads == ["cat.png"]
+ assert client.sends[0]["caption"] is None
+ assert notices == []
+ assert "trust" not in result
+
+
+async def test_unreadable_document_is_sent_with_a_not_checked_notice() -> None:
+ svc, client, notices = _build(_ContentTrustClient())
+
+ result = await svc.send_media(
+ "agent-1", "room-1", [(_BROKEN_PDF, "scan.pdf", "application/pdf")]
+ )
+
+ assert client.uploads == ["scan.pdf"]
+ [(kind, event_id, annotation, outcome)] = notices
+ assert (kind, event_id, outcome) == ("alert", "$media-event-1", "errored")
+ assert "did not check scan.pdf" in annotation
+ assert result["trust"] == {"outcome": "errored", "note": annotation}
+
+
+async def test_a_notice_that_could_not_be_posted_is_reported_as_such() -> None:
+ svc, client, notices = _build(
+ _ContentTrustClient(), notice_error="no admin client is running to post it"
+ )
+
+ result = await svc.send_media(
+ "agent-1", "room-1", [(_BROKEN_PDF, "scan.pdf", "application/pdf")]
+ )
+
+ assert client.uploads == ["scan.pdf"]
+ assert len(notices) == 1
+ assert result["trust"] == {
+ "outcome": "errored",
+ "notice_error": "no admin client is running to post it",
+ }
+
+
+async def test_agents_receive_the_not_checked_note_with_the_file() -> None:
+ # The room notice is an admin event that agents are never routed; the
+ # caption of the file itself is what reaches them.
+ svc, client, _notices = _build(_ContentTrustClient())
+
+ await svc.send_media(
+ "agent-1",
+ "room-1",
+ [
+ (_BROKEN_PDF, "scan.pdf", "application/pdf"),
+ (b"fine", "notes.txt", "text/plain"),
+ ],
+ caption="have a look",
+ )
+
+ first, second = client.sends
+ assert first["caption"].startswith("have a look\n\n")
+ assert "did not check scan.pdf" in first["caption"]
+ assert second["caption"] is None
+
+
+async def test_a_later_failed_upload_still_posts_the_notice_for_files_sent() -> None:
+ svc, client, notices = _build(_ContentTrustClient())
+
+ with pytest.raises(RuntimeError):
+ await svc.send_media(
+ "agent-1",
+ "room-1",
+ [
+ (_BROKEN_PDF, "scan.pdf", "application/pdf"),
+ (b"fine", "unsendable.txt", "text/plain"),
+ ],
+ )
+
+ assert client.uploads == ["scan.pdf"]
+ assert "did not check scan.pdf" in client.sends[0]["caption"]
+ [(kind, event_id, annotation, _outcome)] = notices
+ assert (kind, event_id) == ("alert", "$media-event-1")
+ assert "did not check scan.pdf" in annotation
+
+
+async def test_with_trust_off_nothing_is_checked() -> None:
+ trust = _ContentTrustClient(active=False)
+ svc, client, notices = _build(trust)
+
+ result = await svc.send_media(
+ "agent-1",
+ "room-1",
+ [(b"FORBIDDEN", "leak.env", "text/plain")],
+ caption="FORBIDDEN",
+ )
+
+ assert trust.checked == []
+ assert client.sends[0]["caption"] == "FORBIDDEN"
+ assert notices == []
+ assert "trust" not in result
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_send_message_trust_feedback.py b/core/tests/switch_core/bridges/agent/protocol/test_send_message_trust_feedback.py
new file mode 100644
index 000000000..8c2eaffe9
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/protocol/test_send_message_trust_feedback.py
@@ -0,0 +1,336 @@
+"""An agent learns from its own send what Switch Trust did to it: the result
+of `send_message` (and the `post_message` / `send_targeted_message` tools
+over it) carries `trust` when Switch Trust redacted or flagged the message,
+and nothing when it let it through untouched."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from switch_core.bridges.agent.operations import definitions
+from switch_core.bridges.agent.protocol.agent_core import AgentCore, _trust_feedback
+from switch_core.bridges.agent.protocol.types import (
+ SendTargetedResult,
+ SentMessage,
+ TrustFeedback,
+)
+from switch_core.clients.actor import SystemActor
+from switch_core.tenant_context import tenant_scope
+from switch_core.trust.client import TrustCheckResult, TrustFinding
+
+_FINDING = (TrustFinding(category="secrets", detector_name="s", severity="high"),)
+
+
+class _ContentTrustClient:
+ async def check(self, *, role: str, content: str, room_id: str) -> TrustCheckResult:
+ if "nothing-to-cut" in content:
+ return TrustCheckResult("redacted", "p", "policy", _FINDING, content)
+ if "token-123" in content:
+ return TrustCheckResult(
+ "redacted",
+ "p",
+ "policy",
+ _FINDING,
+ content.replace("token-123", "[redacted]"),
+ )
+ if "suspicious" in content:
+ return TrustCheckResult("alerted", "p", "policy", _FINDING)
+ return TrustCheckResult("ok", "p", "policy")
+
+
+class _FakeClient:
+ def __init__(self) -> None:
+ self.sent: list[str] = []
+ self.agent = SimpleNamespace(name="helper")
+
+ async def send_message(self, room_id: str, content: str, **_kw: Any) -> str:
+ self.sent.append(content)
+ return f"$event-{len(self.sent)}"
+
+
+def _build(
+ notice_error: str | None = None,
+) -> tuple[AgentCore, _FakeClient, list[Any]]:
+ """`notice_error` is what the alert notice answers: None when it was
+ posted, else why it was not."""
+ client = _FakeClient()
+ notices: list[Any] = []
+
+ async def _require(agent_id: str, room_id: str) -> SimpleNamespace:
+ return SimpleNamespace(id=room_id, transport_room_id="!room", bridge_id=None)
+
+ async def _alert_notice(room, event_id, annotation, outcome) -> str | None: # noqa: ANN001
+ notices.append((event_id, annotation, outcome))
+ return notice_error
+
+ async def _set_typing(*_args: object) -> None:
+ return None
+
+ svc = object.__new__(AgentCore)
+ svc.require_room_poster = _require # type: ignore[assignment]
+ svc.require_room_member = _require # type: ignore[assignment]
+ svc.client_lifecycle = SimpleNamespace( # type: ignore[assignment]
+ get_by_agent_id=lambda agent_id: client
+ )
+ svc.trust_client = _ContentTrustClient() # type: ignore[assignment]
+ svc._post_trust_alert_notice = _alert_notice # type: ignore[method-assign]
+ svc._set_typing = _set_typing # type: ignore[method-assign]
+ return svc, client, notices
+
+
+async def test_a_redacted_message_reports_what_the_room_received() -> None:
+ svc, client, _ = _build()
+
+ sent = await svc.send_message("agent-1", "room-1", "the key is token-123")
+
+ assert client.sent == ["the key is [redacted]"]
+ assert sent == SentMessage(
+ event_id="$event-1",
+ trust=TrustFeedback(
+ outcome="redacted",
+ delivered="the key is [redacted]",
+ note=None,
+ notice_error=None,
+ ),
+ )
+
+
+async def test_a_redaction_that_changed_nothing_is_still_reported() -> None:
+ """A redacted verdict with nothing it could cut sends the words as they
+ were; the agent is told all the same."""
+ svc, client, _ = _build()
+
+ sent = await svc.send_message("agent-1", "room-1", "nothing-to-cut here")
+
+ assert client.sent == ["nothing-to-cut here"]
+ assert sent.trust == TrustFeedback(
+ outcome="redacted",
+ delivered="nothing-to-cut here",
+ note=None,
+ notice_error=None,
+ )
+
+
+def test_a_redaction_does_not_hide_a_file_that_was_flagged_or_not_checked() -> None:
+ """A caption redacted beside a file Switch Trust could not check: the
+ outcome is the redaction, and `alert` keeps the file's side visible."""
+ feedback = _trust_feedback(
+ "redacted", "see [redacted]", ("the file was not checked", "errored"), None
+ )
+
+ assert feedback is not None
+ assert feedback.to_result() == {
+ "outcome": "redacted",
+ "delivered": "see [redacted]",
+ "alert": "errored",
+ "note": "the file was not checked",
+ }
+
+
+async def test_a_redacted_status_update_reports_what_the_room_received() -> None:
+ svc, client, _ = _build()
+
+ feedback = await svc.update_status("agent-1", "room-1", "reading token-123")
+
+ assert client.sent == ["*reading [redacted]*"]
+ assert feedback == TrustFeedback(
+ outcome="redacted",
+ delivered="reading [redacted]",
+ note=None,
+ notice_error=None,
+ )
+
+
+async def test_a_flagged_status_update_reports_the_notice_posted_under_it() -> None:
+ svc, _, notices = _build()
+
+ feedback = await svc.update_status("agent-1", "room-1", "something suspicious")
+
+ assert feedback is not None
+ assert feedback.outcome == "alerted"
+ assert feedback.note == notices[0][1]
+
+
+async def test_a_clean_status_update_reports_nothing_about_trust() -> None:
+ svc, _, _ = _build()
+
+ assert await svc.update_status("agent-1", "room-1", "working on it") is None
+
+
+async def test_a_flagged_message_reports_the_notice_posted_under_it() -> None:
+ svc, client, notices = _build()
+
+ sent = await svc.send_message("agent-1", "room-1", "something suspicious")
+
+ assert client.sent == ["something suspicious"]
+ assert sent.trust is not None
+ assert sent.trust.outcome == "alerted"
+ assert sent.trust.delivered is None
+ assert sent.trust.note == notices[0][1]
+
+
+async def test_a_flagged_message_whose_notice_failed_says_so() -> None:
+ svc, client, notices = _build(notice_error="no admin client is running to post it")
+
+ sent = await svc.send_message("agent-1", "room-1", "something suspicious")
+
+ assert client.sent == ["something suspicious"]
+ assert len(notices) == 1
+ assert sent.trust == TrustFeedback(
+ outcome="alerted",
+ delivered=None,
+ note=None,
+ notice_error="no admin client is running to post it",
+ )
+ assert sent.trust.to_result() == {
+ "outcome": "alerted",
+ "notice_error": "no admin client is running to post it",
+ }
+
+
+class _Admin(SystemActor):
+ def __init__(self, event_id: str | None) -> None:
+ self._event_id = event_id
+ self.posted: list[str] = []
+
+ async def send_admin(self, room_id: str, body: str, **_kw: Any) -> str | None:
+ self.posted.append(body)
+ return self._event_id
+
+
+def _core_with_admins(*admins: SystemActor) -> AgentCore:
+ svc = object.__new__(AgentCore)
+ svc.client_lifecycle = SimpleNamespace( # type: ignore[assignment]
+ get_by_type=lambda kind, tenant_id: list(admins)
+ )
+ return svc
+
+
+_ROOM = SimpleNamespace(id="room-1", transport_room_id="!room")
+
+
+async def test_an_alert_notice_posted_reports_no_error() -> None:
+ admin = _Admin("$notice")
+ with tenant_scope("tenant-a"):
+ error = await _core_with_admins(admin)._post_trust_alert_notice(
+ _ROOM, # type: ignore[arg-type]
+ "$event",
+ "flagged",
+ "alerted",
+ )
+
+ assert error is None
+ assert admin.posted == ["flagged"]
+
+
[email protected]("admin_running", [False, True])
+async def test_an_alert_notice_not_posted_says_why(
+ admin_running: bool, caplog: pytest.LogCaptureFixture
+) -> None:
+ """With no admin client to post it, or one whose post the transport
+ refused, the notice is reported as not posted."""
+ admins = (_Admin(None),) if admin_running else ()
+ with tenant_scope("tenant-a"):
+ error = await _core_with_admins(*admins)._post_trust_alert_notice(
+ _ROOM, # type: ignore[arg-type]
+ "$event",
+ "flagged",
+ "alerted",
+ )
+
+ assert error is not None
+ assert "Switch Trust" in caplog.text
+
+
+async def test_a_clean_message_reports_nothing_about_trust() -> None:
+ svc, _, _ = _build()
+
+ sent = await svc.send_message("agent-1", "room-1", "hello")
+
+ assert sent == SentMessage(event_id="$event-1", trust=None)
+
+
+class _Protocol:
+ def __init__(self, sent: SentMessage) -> None:
+ self._sent = sent
+
+ async def send_message(self, *_args: Any, **_kwargs: Any) -> SentMessage:
+ return self._sent
+
+ async def send_targeted_message(
+ self, *_args: Any, **_kwargs: Any
+ ) -> SendTargetedResult:
+ return SendTargetedResult(
+ event_id=self._sent.event_id,
+ target_statuses={},
+ trust=self._sent.trust,
+ )
+
+
+def _connected(monkeypatch: pytest.MonkeyPatch, protocol: _Protocol) -> None:
+ async def _room() -> str:
+ return "room-1"
+
+ monkeypatch.setattr(definitions, "get_agent_id", lambda: "agent-1")
+ monkeypatch.setattr(definitions, "require_connected_room", _room)
+ monkeypatch.setattr(definitions, "get_protocol", lambda: protocol)
+
+
+async def test_post_message_result_carries_the_redaction(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _connected(
+ monkeypatch,
+ _Protocol(
+ SentMessage(
+ event_id="$e",
+ trust=TrustFeedback(
+ outcome="redacted",
+ delivered="the key is [redacted]",
+ note=None,
+ notice_error=None,
+ ),
+ )
+ ),
+ )
+
+ result = await definitions.post_message("the key is token-123")
+
+ assert result == {
+ "event_id": "$e",
+ "trust": {"outcome": "redacted", "delivered": "the key is [redacted]"},
+ }
+
+
+async def test_post_message_result_is_unchanged_when_trust_did_nothing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _connected(monkeypatch, _Protocol(SentMessage(event_id="$e", trust=None)))
+
+ assert await definitions.post_message("hello") == {"event_id": "$e"}
+
+
+async def test_send_targeted_message_result_carries_the_redaction(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _connected(
+ monkeypatch,
+ _Protocol(
+ SentMessage(
+ event_id="$e",
+ trust=TrustFeedback(
+ outcome="redacted",
+ delivered="@bob [redacted]",
+ note=None,
+ notice_error=None,
+ ),
+ )
+ ),
+ )
+
+ result = await definitions.send_targeted_message("token-123", target_names=["bob"])
+
+ assert result["trust"] == {"outcome": "redacted", "delivered": "@bob [redacted]"}
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py b/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py
index 38f0086f0..27cba65eb 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py
@@ -10,6 +10,7 @@ from switch_core.bridges.agent.protocol.agent_core import AgentCore
from switch_core.bridges.agent.protocol.types import (
AgentStatus,
RoomWideMentionStatus,
+ SentMessage,
)
@@ -105,9 +106,9 @@ def _build_service(
thread_id: str | None = None,
*,
extra_content: dict[str, object] | None = None,
- ) -> str:
+ ) -> SentMessage:
sent_bodies.append(body)
- return "evt-1"
+ return SentMessage(event_id="evt-1", trust=None)
svc.list_participants = _list_participants # type: ignore[assignment]
svc.send_message = _send_message # type: ignore[assignment]
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_attachments_trust.py b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_attachments_trust.py
new file mode 100644
index 000000000..bb6f6cd45
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_attachments_trust.py
@@ -0,0 +1,269 @@
+"""Switch Trust on a person's message that carries files: the typed text and
+each file's text are checked before anything is uploaded, so a refusal
+leaves nothing in the room. (`test_bridge_inbound_trust.py` covers the
+text-only path; `trust/test_attachments.py` what a file is checked as.)"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+from switch_core.bridges.collaboration.collaboration_core import CollaborationCore
+from switch_core.bridges.collaboration.models import Attachment, InboundMessage
+from switch_core.clients.admin_messages import AdminMessageType
+from switch_core.trust.client import (
+ NullTrustClient,
+ TrustCheckResult,
+ TrustFinding,
+)
+
+_FINDING = (TrustFinding(category="pii/email", detector_name="e", severity="high"),)
+
+
+class _ContentTrustClient:
+ """Blocks text containing FORBIDDEN, redacts "[email protected]", and
+ allows the rest. `active=False` stands in for Switch Trust being off."""
+
+ def __init__(self, *, active: bool = True) -> None:
+ self._active = active
+ self.checked: list[tuple[str, str]] = []
+
+ async def is_active(self) -> bool:
+ return self._active
+
+ async def check(self, *, role: str, content: str, room_id: str) -> TrustCheckResult:
+ self.checked.append((role, content))
+ if "FORBIDDEN" in content:
+ return TrustCheckResult("blocked", "p", "policy", _FINDING)
+ if "[email protected]" in content:
+ return TrustCheckResult(
+ "redacted",
+ "p",
+ "policy",
+ _FINDING,
+ content.replace("[email protected]", "[redacted]"),
+ )
+ return TrustCheckResult("ok", "p", "policy")
+
+
+class _FakeHumanActor:
+ client_id = "human-actor-client"
+ transport_user_id = "@human:s"
+
+ def __init__(self) -> None:
+ self.uploads: list[str] = []
+ self.media: list[dict[str, Any]] = []
+
+ async def upload_media(self, data: bytes, mimetype: str, filename: str) -> str:
+ self.uploads.append(filename)
+ return f"mxc://s/{filename}"
+
+ async def send_media(self, transport_room_id, mxc, filename, mimetype, size, **kw): # noqa: ANN001, ANN003, ANN201
+ self.media.append({"filename": filename, "caption": kw.get("caption")})
+ return f"$evt-{len(self.media) - 1}"
+
+ async def send_message(self, *args: object, **kw: object) -> str:
+ raise AssertionError("a message with files is relayed as media")
+
+
+class _FakeAdapter:
+ """A platform with no private route, so every notice is posted in the
+ channel, where these tests read it."""
+
+ platform_name = "Fake"
+ private_notice_delivery = "in_channel"
+
+ def __init__(self) -> None:
+ self.admin_messages: list[tuple[str, str]] = []
+
+ def translate_inbound(self, content: str) -> str:
+ return content
+
+ def unlinkable_account_reason(self, _external_user_id: str) -> str | None:
+ return None
+
+ async def admin_message(
+ self, channel_id: str, body: str, root_or_ref: str | None, *, message_type: str
+ ) -> None:
+ self.admin_messages.append((body, message_type))
+
+
+async def _none(*_args: object, **_kwargs: object) -> None:
+ return None
+
+
+async def _not_an_agent(_name: str) -> bool:
+ return False
+
+
+def _bridge(trust_client: object) -> SimpleNamespace:
+ human_actor = _FakeHumanActor()
+ recorded: list[dict[str, str]] = []
+
+ async def _ensure_human_in_room(**_kw: object) -> _FakeHumanActor:
+ return human_actor
+
+ async def _record_message_map(**kwargs: str) -> None:
+ recorded.append(kwargs)
+
+ bridge = SimpleNamespace(
+ _bridge_id="bridge-1",
+ _handle_text_answer=_none,
+ _repair_placeholder_username=_none,
+ _adapter=_FakeAdapter(),
+ _channel_to_room={"chan-1": ("room-1", "!room:s")},
+ _channel_locks={},
+ _is_registered_agent=_not_an_agent,
+ _ensure_human_in_room=_ensure_human_in_room,
+ _record_message_map=_record_message_map,
+ _trust_client=trust_client,
+ human_actor=human_actor,
+ recorded=recorded,
+ )
+ bridge._post_trust_notice = lambda msg, body, message_type: (
+ CollaborationCore._post_trust_notice(bridge, msg, body, message_type)
+ )
+ return bridge
+
+
+def _msg(content: str, *attachments: Attachment) -> InboundMessage:
+ return InboundMessage(
+ channel_id="chan-1",
+ channel_type="channel_public",
+ sender_id="U1",
+ sender_name="alice",
+ content=content,
+ message_ref="post-1",
+ attachments=list(attachments),
+ )
+
+
+_IMAGE = Attachment(filename="cat.png", mimetype="image/png", data=b"\x89PNG")
+
+
+async def test_blocked_caption_with_an_image_relays_nothing() -> None:
+ bridge = _bridge(_ContentTrustClient())
+
+ await CollaborationCore._handle_inbound_message(
+ bridge, _msg("FORBIDDEN words", _IMAGE)
+ )
+
+ assert bridge.human_actor.uploads == []
+ assert bridge.human_actor.media == []
+ assert bridge.recorded == []
+ [(body, message_type)] = bridge._adapter.admin_messages
+ assert "blocked by Switch Trust" in body
+ assert message_type == AdminMessageType.TRUST_BLOCKED.value
+
+
+async def test_text_file_with_blocked_content_relays_nothing() -> None:
+ trust = _ContentTrustClient()
+ bridge = _bridge(trust)
+ report = Attachment(
+ filename="report.txt", mimetype="text/plain", data=b"FORBIDDEN data"
+ )
+
+ await CollaborationCore._handle_inbound_message(
+ bridge, _msg("see attached", report, _IMAGE)
+ )
+
+ assert bridge.human_actor.uploads == []
+ assert bridge.human_actor.media == []
+ [(body, message_type)] = bridge._adapter.admin_messages
+ assert "report.txt was blocked" in body
+ assert message_type == AdminMessageType.TRUST_BLOCKED.value
+ # The caption and the file's text were each checked, as the person.
+ assert sorted(trust.checked) == [
+ ("user", "FORBIDDEN data"),
+ ("user", "see attached"),
+ ]
+
+
+async def test_text_file_trust_would_redact_is_blocked_not_relayed() -> None:
+ bridge = _bridge(_ContentTrustClient())
+ contacts = Attachment(
+ filename="contacts.csv", mimetype="text/csv", data=b"[email protected]"
+ )
+
+ await CollaborationCore._handle_inbound_message(bridge, _msg("", contacts))
+
+ assert bridge.human_actor.uploads == []
+ [(body, _)] = bridge._adapter.admin_messages
+ assert "contacts.csv" in body
+ assert "cannot be redacted" in body
+
+
+async def test_image_is_relayed_without_a_note_or_a_notice() -> None:
+ # Switch never reads an image's text, so a screenshot is relayed as it is:
+ # telling its sender so on every post would only be noise.
+ bridge = _bridge(_ContentTrustClient())
+
+ await CollaborationCore._handle_inbound_message(bridge, _msg("look", _IMAGE))
+
+ [media] = bridge.human_actor.media
+ assert media["filename"] == "cat.png"
+ assert media["caption"] == "look"
+ assert bridge._adapter.admin_messages == []
+
+
+async def test_unreadable_document_is_relayed_with_a_note_that_it_was_not_checked() -> (
+ None
+):
+ bridge = _bridge(_ContentTrustClient())
+ scan = Attachment(
+ filename="scan.pdf", mimetype="application/pdf", data=b"%PDF-1.4\x00garbage"
+ )
+
+ await CollaborationCore._handle_inbound_message(bridge, _msg("look", scan))
+
+ [media] = bridge.human_actor.media
+ assert media["caption"].startswith("look\n\n")
+ assert "Switch Trust did not check scan.pdf" in media["caption"]
+ # The sender sees the note too, since the room never echoes their post back.
+ [(body, message_type)] = bridge._adapter.admin_messages
+ assert "did not check scan.pdf" in body
+ assert message_type == AdminMessageType.TRUST_ERRORED.value
+
+
+async def test_redacted_caption_becomes_the_redacted_text() -> None:
+ bridge = _bridge(_ContentTrustClient())
+ notes = Attachment(filename="notes.txt", mimetype="text/plain", data=b"fine")
+
+ await CollaborationCore._handle_inbound_message(
+ bridge, _msg("mail [email protected]", notes)
+ )
+
+ [media] = bridge.human_actor.media
+ assert media["caption"] == "mail [redacted]"
+ [(body, message_type)] = bridge._adapter.admin_messages
+ assert message_type == AdminMessageType.TRUST_REDACTED.value
+
+
+async def test_with_trust_off_files_are_relayed_unchanged_and_unread() -> None:
+ trust = _ContentTrustClient(active=False)
+ bridge = _bridge(trust)
+ report = Attachment(
+ filename="report.txt", mimetype="text/plain", data=b"FORBIDDEN data"
+ )
+
+ await CollaborationCore._handle_inbound_message(
+ bridge, _msg("FORBIDDEN caption", report, _IMAGE)
+ )
+
+ assert trust.checked == []
+ assert [m["filename"] for m in bridge.human_actor.media] == [
+ "report.txt",
+ "cat.png",
+ ]
+ assert bridge.human_actor.media[0]["caption"] == "FORBIDDEN caption"
+ assert bridge._adapter.admin_messages == []
+
+
+async def test_with_the_null_client_files_are_relayed_unchanged() -> None:
+ bridge = _bridge(NullTrustClient())
+
+ await CollaborationCore._handle_inbound_message(bridge, _msg("look", _IMAGE))
+
+ [media] = bridge.human_actor.media
+ assert media["caption"] == "look"
+ assert bridge._adapter.admin_messages == []
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_trust.py b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_trust.py
index 103215973..3c5fe8926 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_trust.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_trust.py
@@ -49,6 +49,12 @@ class _FakeHumanActor:
class _FakeAdapter:
+ """A platform with no private route, so every notice is posted in the
+ channel, where these tests read it."""
+
+ platform_name = "Fake"
+ private_notice_delivery = "in_channel"
+
def __init__(self, *, raise_on_admin_message: bool = False) -> None:
self.admin_messages: list[tuple[str, str, str | None, str]] = []
self._raise_on_admin_message = raise_on_admin_message
@@ -56,6 +62,9 @@ class _FakeAdapter:
def translate_inbound(self, content: str) -> str:
return content
+ def unlinkable_account_reason(self, _external_user_id: str) -> str | None:
+ return None
+
async def admin_message(
self,
channel_id: str,
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_trust_notices_private.py b/core/tests/switch_core/bridges/collaboration/test_bridge_trust_notices_private.py
new file mode 100644
index 000000000..a7ed11c53
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_trust_notices_private.py
@@ -0,0 +1,401 @@
+"""A Switch Trust notice about a person's own message reaches that person
+alone: an ephemeral where the platform has one, a direct message where it has
+not, and the channel, with a warning, where it has neither, the private route
+fails, or there is no one person to reach
+(`CollaborationCore._post_trust_notice`)."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from telegram.error import Forbidden
+
+from switch_core.bridges.collaboration.adapter import PrivateNoticeRefused
+from switch_core.bridges.collaboration.collaboration_core import CollaborationCore
+from switch_core.bridges.collaboration.discord.adapter import DiscordAdapter
+from switch_core.bridges.collaboration.mattermost.adapter import MattermostAdapter
+from switch_core.bridges.collaboration.models import InboundMessage
+from switch_core.bridges.collaboration.slack.adapter import SlackAdapter
+from switch_core.bridges.collaboration.telegram.adapter import TelegramAdapter
+from switch_core.clients.admin_messages import AdminMessageType
+from switch_core.trust.client import TrustCheckResult, TrustFinding
+
+from .test_bridge_inbound_trust import (
+ TRANSPORT_ROOM_ID,
+ _bridge,
+ _FakeHumanActor,
+ _FixedTrustClient,
+)
+
+_BLOCKED = TrustCheckResult(
+ outcome="blocked",
+ policy_id="policy-1",
+ policy_name="default",
+ findings=(
+ TrustFinding(category="pii/email", detector_name="email", severity="high"),
+ ),
+)
+
+_REDACTED = TrustCheckResult(
+ outcome="redacted",
+ policy_id="policy-1",
+ policy_name="default",
+ findings=(
+ TrustFinding(category="pii/email", detector_name="email", severity="high"),
+ ),
+ redacted_content="my email is [redacted]",
+)
+
+
+def _message(
+ *,
+ channel_type: str = "channel_public",
+ sender_id: str = "U-alice",
+ message_ref: str = "C1:111.0",
+ root_id: str | None = None,
+ sender_is_app: bool = False,
+) -> InboundMessage:
+ return InboundMessage(
+ channel_id="chan-1",
+ channel_type=channel_type, # type: ignore[arg-type]
+ channel_name="general",
+ sender_id=sender_id,
+ sender_name="alice",
+ content="my email is [email protected]",
+ message_ref=message_ref,
+ root_id=root_id,
+ sender_is_app=sender_is_app,
+ )
+
+
+class _SlackWeb:
+ def __init__(self) -> None:
+ self.ephemeral: list[dict[str, Any]] = []
+ self.posted: list[dict[str, Any]] = []
+
+ async def chat_postEphemeral(self, **kwargs: Any) -> None:
+ self.ephemeral.append(kwargs)
+
+ async def chat_postMessage(self, **kwargs: Any) -> dict[str, str]:
+ self.posted.append(kwargs)
+ return {"ts": "222.0"}
+
+
+def _slack(web: _SlackWeb) -> SlackAdapter:
+ adapter = SlackAdapter.__new__(SlackAdapter)
+ adapter._web_client = web # type: ignore[assignment]
+ adapter._gateway_public_url = None
+ return adapter
+
+
+async def test_slack_block_notice_is_ephemeral_to_the_sender() -> None:
+ web = _SlackWeb()
+ human_actor = _FakeHumanActor()
+ bridge = _bridge(human_actor, _slack(web), _FixedTrustClient(_BLOCKED)) # type: ignore[arg-type]
+
+ await CollaborationCore._handle_inbound_message(bridge, _message())
+
+ assert human_actor.sent == []
+ assert web.posted == []
+ assert len(web.ephemeral) == 1
+ call = web.ephemeral[0]
+ assert call["channel"] == "chan-1"
+ assert call["user"] == "U-alice"
+ assert "blocked by Switch Trust" in call["text"]
+ # A top-level message gets its notice at the channel root, beside it,
+ # rather than in a thread nobody opened.
+ assert call["thread_ts"] is None
+
+
+async def test_slack_redaction_notice_in_a_thread_is_ephemeral_in_that_thread() -> None:
+ web = _SlackWeb()
+ human_actor = _FakeHumanActor()
+ bridge = _bridge(human_actor, _slack(web), _FixedTrustClient(_REDACTED)) # type: ignore[arg-type]
+
+ async def _root_event(_external_root: str) -> str:
+ return "$root"
+
+ bridge._event_for_external_post = _root_event
+
+ await CollaborationCore._handle_inbound_message(
+ bridge, _message(root_id="C1:100.0")
+ )
+
+ assert human_actor.sent == [(TRANSPORT_ROOM_ID, "my email is [redacted]")]
+ assert web.posted == []
+ assert len(web.ephemeral) == 1
+ assert web.ephemeral[0]["user"] == "U-alice"
+ assert web.ephemeral[0]["thread_ts"] == "100.0"
+ assert "redacted by Switch Trust" in web.ephemeral[0]["text"]
+
+
+class _TelegramBot:
+ def __init__(self) -> None:
+ self.sent: list[dict[str, Any]] = []
+
+ async def send_message(self, **kwargs: Any) -> None:
+ self.sent.append(kwargs)
+
+
+async def test_telegram_block_notice_goes_to_the_senders_private_chat() -> None:
+ bot = _TelegramBot()
+ adapter = TelegramAdapter.__new__(TelegramAdapter)
+ adapter._bot = bot
+ adapter._gateway_public_url = None
+ human_actor = _FakeHumanActor()
+ bridge = _bridge(human_actor, adapter, _FixedTrustClient(_BLOCKED)) # type: ignore[arg-type]
+
+ await CollaborationCore._handle_inbound_message(
+ bridge, _message(sender_id="4242", message_ref="-100:7")
+ )
+
+ assert human_actor.sent == []
+ assert len(bot.sent) == 1
+ assert bot.sent[0]["chat_id"] == 4242
+ assert bot.sent[0]["text"].startswith("About your message in general:")
+ assert "blocked by Switch Trust" in bot.sent[0]["text"]
+
+
+async def test_discord_block_notice_is_a_direct_message_naming_the_channel() -> None:
+ sent: list[tuple[str, dict[str, Any]]] = []
+
+ class _User:
+ async def send(self, content: str, **kwargs: Any) -> None:
+ sent.append((content, kwargs))
+
+ users = {4242: _User()}
+ client = SimpleNamespace(get_user=users.get)
+ adapter = DiscordAdapter.__new__(DiscordAdapter)
+ adapter._connection = SimpleNamespace(client=client) # type: ignore[assignment]
+ adapter._gateway_public_url = None
+ human_actor = _FakeHumanActor()
+ bridge = _bridge(human_actor, adapter, _FixedTrustClient(_BLOCKED)) # type: ignore[arg-type]
+
+ await CollaborationCore._handle_inbound_message(
+ bridge, _message(sender_id="4242", message_ref="1:2")
+ )
+
+ assert human_actor.sent == []
+ assert len(sent) == 1
+ content, _ = sent[0]
+ assert content.startswith("About your message in <#chan-1>:")
+ assert "blocked by Switch Trust" in content
+
+
+async def test_a_long_telegram_notice_is_split_to_fit() -> None:
+ bot = _TelegramBot()
+ adapter = TelegramAdapter.__new__(TelegramAdapter)
+ adapter._bot = bot
+ adapter._gateway_public_url = None
+
+ await adapter.notify_privately(
+ channel_id="-100",
+ channel_name="general",
+ user_id="4242",
+ content="\n".join(f"line {n} " + "x" * 60 for n in range(200)),
+ thread_root_id=None,
+ )
+
+ assert len(bot.sent) > 1
+ assert all(len(sent["text"]) <= 4096 for sent in bot.sent)
+ assert all(sent["chat_id"] == 4242 for sent in bot.sent)
+
+
+async def test_telegrams_refusal_is_raised_as_expected() -> None:
+ class _RefusingBot:
+ async def send_message(self, **_kwargs: Any) -> None:
+ raise Forbidden("Forbidden: bot can't initiate conversation with a user")
+
+ adapter = TelegramAdapter.__new__(TelegramAdapter)
+ adapter._bot = _RefusingBot()
+ adapter._gateway_public_url = None
+
+ with pytest.raises(PrivateNoticeRefused):
+ await adapter.notify_privately(
+ channel_id="-100",
+ channel_name="general",
+ user_id="4242",
+ content="blocked",
+ thread_root_id=None,
+ )
+
+
+async def test_a_long_discord_notice_is_split_to_fit() -> None:
+ sent: list[str] = []
+
+ class _User:
+ async def send(self, content: str, **_kwargs: Any) -> None:
+ sent.append(content)
+
+ client = SimpleNamespace(get_user={4242: _User()}.get)
+ adapter = DiscordAdapter.__new__(DiscordAdapter)
+ adapter._connection = SimpleNamespace(client=client) # type: ignore[assignment]
+ adapter._gateway_public_url = None
+
+ await adapter.notify_privately(
+ channel_id="chan-1",
+ channel_name="general",
+ user_id="4242",
+ content="\n".join(f"line {n} " + "x" * 60 for n in range(100)),
+ thread_root_id=None,
+ )
+
+ assert len(sent) > 1
+ assert all(len(content) <= 2000 for content in sent)
+
+
+class _NoticeAdapter:
+ """A platform whose private route is declared but can be made to fail,
+ recording what reached the channel instead."""
+
+ platform_name = "Fake"
+
+ def __init__(
+ self, delivery: str, *, private_fails: bool, refused: bool = False
+ ) -> None:
+ self.private_notice_delivery = delivery
+ self._private_fails = private_fails
+ self._refused = refused
+ self.private: list[dict[str, Any]] = []
+ self.admin_messages: list[tuple[str, str, str | None, str]] = []
+
+ def translate_inbound(self, content: str) -> str:
+ return content
+
+ def unlinkable_account_reason(self, external_user_id: str) -> str | None:
+ return "a stand-in" if external_user_id == "stand-in" else None
+
+ async def notify_privately(self, **kwargs: Any) -> None:
+ if self._refused:
+ raise PrivateNoticeRefused("Forbidden: bot can't initiate conversation")
+ if self._private_fails:
+ raise RuntimeError("the platform timed out")
+ self.private.append(kwargs)
+
+ async def admin_message(
+ self, channel_id: str, body: str, root_or_ref: str | None, *, message_type: str
+ ) -> None:
+ self.admin_messages.append((channel_id, body, root_or_ref, message_type))
+
+
+async def test_a_refused_direct_message_falls_back_to_the_channel_with_a_warning(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ adapter = _NoticeAdapter("direct_message", private_fails=True)
+ bridge = _bridge(_FakeHumanActor(), adapter, _FixedTrustClient(_BLOCKED)) # type: ignore[arg-type]
+
+ with caplog.at_level(logging.WARNING):
+ await CollaborationCore._handle_inbound_message(bridge, _message())
+
+ assert len(adapter.admin_messages) == 1
+ channel_id, body, root_or_ref, message_type = adapter.admin_messages[0]
+ assert channel_id == "chan-1"
+ assert "blocked by Switch Trust" in body
+ assert root_or_ref == "C1:111.0"
+ assert message_type == AdminMessageType.TRUST_BLOCKED.value
+ assert "everyone in it sees it" in caplog.text
+ assert "timed out" in caplog.text
+
+
+async def test_a_refusal_the_platform_is_expected_to_give_is_logged_without_a_traceback(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """Most members of a Telegram group never started a chat with the bot,
+ so its refusal is routine: one line, not a traceback per notice."""
+ adapter = _NoticeAdapter("direct_message", private_fails=False, refused=True)
+ bridge = _bridge(_FakeHumanActor(), adapter, _FixedTrustClient(_BLOCKED)) # type: ignore[arg-type]
+
+ with caplog.at_level(logging.WARNING):
+ await CollaborationCore._handle_inbound_message(bridge, _message())
+
+ assert len(adapter.admin_messages) == 1
+ [record] = [r for r in caplog.records if "privately" in r.getMessage()]
+ assert "can't initiate conversation" in record.getMessage()
+ assert record.exc_info is None
+
+
+ ("sender_id", "sender_is_app"), [("U-app", True), ("stand-in", False)]
+)
+async def test_an_app_or_a_shared_account_gets_its_notice_in_the_channel(
+ caplog: pytest.LogCaptureFixture, sender_id: str, sender_is_app: bool
+) -> None:
+ """Nobody is behind an app's post to reach privately, and a stand-in
+ account is many people, so the private route is not tried at all."""
+ adapter = _NoticeAdapter("direct_message", private_fails=True)
+ bridge = _bridge(_FakeHumanActor(), adapter, _FixedTrustClient(_BLOCKED)) # type: ignore[arg-type]
+
+ with caplog.at_level(logging.WARNING):
+ await CollaborationCore._handle_inbound_message(
+ bridge, _message(sender_id=sender_id, sender_is_app=sender_is_app)
+ )
+
+ assert adapter.private == []
+ assert len(adapter.admin_messages) == 1
+ assert "privately" not in caplog.text
+ assert "everyone in it sees it" not in caplog.text
+
+
+async def test_a_platform_without_a_private_route_posts_in_channel_and_warns(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ adapter = _NoticeAdapter("in_channel", private_fails=False)
+ bridge = _bridge(_FakeHumanActor(), adapter, _FixedTrustClient(_BLOCKED)) # type: ignore[arg-type]
+
+ with caplog.at_level(logging.WARNING):
+ await CollaborationCore._handle_inbound_message(bridge, _message())
+
+ assert adapter.private == []
+ assert len(adapter.admin_messages) == 1
+ assert "has no way to reach one person privately" in caplog.text
+
+
+async def test_in_a_direct_conversation_the_notice_stays_where_it_is(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """The channel is already just the sender and the bot, so nothing is
+ sent anywhere else and nothing is worth a warning."""
+ adapter = _NoticeAdapter("in_channel", private_fails=False)
+ bridge = _bridge(_FakeHumanActor(), adapter, _FixedTrustClient(_BLOCKED)) # type: ignore[arg-type]
+
+ with caplog.at_level(logging.WARNING):
+ await CollaborationCore._handle_inbound_message(
+ bridge, _message(channel_type="direct")
+ )
+
+ assert len(adapter.admin_messages) == 1
+ assert "privately" not in caplog.text
+
+
+async def test_mattermost_notice_is_an_ephemeral_post_for_the_sender() -> None:
+ created: list[dict[str, Any]] = []
+ driver = SimpleNamespace(
+ posts=SimpleNamespace(create_ephemeral_post=created.append)
+ )
+ adapter = MattermostAdapter.__new__(MattermostAdapter)
+ adapter._main_loop = asyncio.get_running_loop()
+ adapter._admin_driver = driver # type: ignore[assignment]
+ adapter._gateway_public_url = None
+
+ await adapter.notify_privately(
+ channel_id="chan-1",
+ channel_name="town-square",
+ user_id="mm-alice",
+ content="🚫 Your message was blocked by Switch Trust",
+ thread_root_id="post-root",
+ )
+
+ assert created == [
+ {
+ "user_id": "mm-alice",
+ "post": {
+ "channel_id": "chan-1",
+ "message": "🚫 Your message was blocked by Switch Trust",
+ "root_id": "post-root",
+ },
+ }
+ ]
diff --git a/core/tests/switch_core/gateway/conftest.py b/core/tests/switch_core/gateway/conftest.py
index 22488e145..aa34b4bbb 100644
--- a/core/tests/switch_core/gateway/conftest.py
+++ b/core/tests/switch_core/gateway/conftest.py
@@ -53,6 +53,7 @@ from switch_core.session_activity.listener import (
)
from switch_core.signals import SignalBus
from switch_core.transport.invites import InviteBus
+from switch_core.trust.client import NullTrustClient
from tests.conftest import TEST_KEYRING
from tests.routing import router_on
from tests.switch_core.gateway.agent_route_harness import add_agent
@@ -313,6 +314,7 @@ def _chat_service(
group_chats_enabled=True,
buddy_slack_handoff_enabled=True,
connections=connections,
+ trust_client=NullTrustClient(),
)
room_service.on_room_agents_changed(service.sync_room)
return service, room_service
diff --git a/core/tests/switch_core/gateway/test_chats_trust.py b/core/tests/switch_core/gateway/test_chats_trust.py
new file mode 100644
index 000000000..1a7500f2e
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_chats_trust.py
@@ -0,0 +1,140 @@
+"""Switch Trust on a Console chat: a person's message and the files they
+attach are checked before anything is posted, as on every other platform."""
+
+from __future__ import annotations
+
+import httpx
+
+from switch_core.trust.client import TrustCheckResult, TrustFinding
+from tests.switch_core.gateway.conftest import _Harness
+
+_FINDING = (TrustFinding(category="secrets", detector_name="s", severity="high"),)
+
+
+class _ContentTrustClient:
+ """Blocks text containing FORBIDDEN, redacts token-123, flags FLAG."""
+
+ def __init__(self) -> None:
+ self.checked: list[tuple[str, str]] = []
+
+ async def is_active(self) -> bool:
+ return True
+
+ async def check(self, *, role: str, content: str, room_id: str) -> TrustCheckResult:
+ self.checked.append((role, content))
+ if "FORBIDDEN" in content:
+ return TrustCheckResult("blocked", "p", "policy", _FINDING)
+ if "token-123" in content:
+ return TrustCheckResult(
+ "redacted",
+ "p",
+ "policy",
+ _FINDING,
+ content.replace("token-123", "[redacted]"),
+ )
+ if "FLAG" in content:
+ return TrustCheckResult("alerted", "p", "policy", _FINDING)
+ return TrustCheckResult("ok", "p", "policy")
+
+
+async def _chat(chats: _Harness) -> tuple[str, _ContentTrustClient]:
+ trust = _ContentTrustClient()
+ chats.service._trust_client = trust # type: ignore[assignment]
+ agent = await chats.agent("helper", owner=chats.alice)
+ return await chats.new_chat(chats.alice, agent, "c1"), trust
+
+
+async def _upload(
+ chats: _Harness, room_id: str, upload_id: str, data: bytes, name: str, kind: str
+) -> httpx.Response:
+ return await chats.client.post(
+ f"/chats/{room_id}/attachments",
+ data={"uploadId": upload_id},
+ files={"file": (name, data, kind)},
+ headers=chats.as_user(chats.alice),
+ )
+
+
+async def test_a_blocked_file_posts_nothing_and_says_why(chats: _Harness) -> None:
+ room_id, trust = await _chat(chats)
+ assert (
+ await _upload(chats, room_id, "u1", b"FORBIDDEN", "leak.env", "text/plain")
+ ).status_code == 200
+
+ sent = await chats.send(
+ chats.alice, room_id, "s1", "see attached", uploadIds=["u1"]
+ )
+
+ assert sent.status_code == 422
+ detail = sent.json()["detail"]
+ assert detail["code"] == "TRUST_BLOCKED"
+ assert "leak.env was blocked (secrets)" in detail["message"]
+ assert await chats.message_rows(room_id) == []
+ assert ("user", "see attached") in trust.checked
+ assert ("user", "FORBIDDEN") in trust.checked
+
+
+async def test_a_blocked_caption_posts_nothing(chats: _Harness) -> None:
+ room_id, _trust = await _chat(chats)
+ await _upload(chats, room_id, "u1", b"fine", "notes.txt", "text/plain")
+
+ sent = await chats.send(chats.alice, room_id, "s1", "FORBIDDEN", uploadIds=["u1"])
+
+ assert sent.status_code == 422
+ assert sent.json()["detail"]["code"] == "TRUST_BLOCKED"
+ assert await chats.message_rows(room_id) == []
+
+
+async def test_a_blocked_message_without_files_posts_nothing(chats: _Harness) -> None:
+ room_id, _trust = await _chat(chats)
+
+ sent = await chats.send(chats.alice, room_id, "s1", "FORBIDDEN")
+
+ assert sent.status_code == 422
+ assert sent.json()["detail"]["code"] == "TRUST_BLOCKED"
+ assert await chats.message_rows(room_id) == []
+
+
+async def test_an_unchecked_file_is_posted_with_a_note_and_a_redacted_caption(
+ chats: _Harness,
+) -> None:
+ room_id, trust = await _chat(chats)
+ await _upload(
+ chats, room_id, "u1", b"%PDF-1.4\x00garbage", "scan.pdf", "application/pdf"
+ )
+
+ sent = await chats.send(
+ chats.alice, room_id, "s1", "my token-123 FLAG", uploadIds=["u1"]
+ )
+
+ assert sent.status_code == 200
+ [row] = await chats.message_rows(room_id)
+ assert row.body.startswith("my [redacted] FLAG\n\n")
+ assert (
+ "Switch Trust did not check scan.pdf (this PDF could not be read)" in row.body
+ )
+ # The file's bytes were never sent as text.
+ assert [content for _, content in trust.checked] == ["my token-123 FLAG"]
+
+
+async def test_an_image_is_posted_without_a_note(chats: _Harness) -> None:
+ room_id, trust = await _chat(chats)
+ await _upload(chats, room_id, "u1", b"\x89PNG", "cat.png", "image/png")
+
+ sent = await chats.send(chats.alice, room_id, "s1", "look", uploadIds=["u1"])
+
+ assert sent.status_code == 200
+ [row] = await chats.message_rows(room_id)
+ assert row.body == "look"
+ assert [content for _, content in trust.checked] == ["look"]
+
+
+async def test_a_retry_after_the_post_is_answered_without_checking_again(
+ chats: _Harness,
+) -> None:
+ room_id, trust = await _chat(chats)
+ first = await chats.send(chats.alice, room_id, "s1", "hello")
+ again = await chats.send(chats.alice, room_id, "s1", "hello")
+
+ assert first.json() == again.json()
+ assert trust.checked == [("user", "hello")]
diff --git a/core/tests/switch_core/test_room_wide_mention_wakes_no_agent.py b/core/tests/switch_core/test_room_wide_mention_wakes_no_agent.py
index 3898f61ef..7bb37a061 100644
--- a/core/tests/switch_core/test_room_wide_mention_wakes_no_agent.py
+++ b/core/tests/switch_core/test_room_wide_mention_wakes_no_agent.py
@@ -27,6 +27,7 @@ from switch_core.bridges.agent.protocol.agent_core import AgentCore
from switch_core.bridges.agent.protocol.types import (
AgentStatus,
RoomWideMentionStatus,
+ SentMessage,
)
from switch_core.bridges.collaboration.slack.adapter import (
SlackAdapter,
@@ -148,9 +149,9 @@ def _service(
thread_id: str | None = None,
*,
extra_content: dict[str, object] | None = None,
- ) -> str:
+ ) -> SentMessage:
sent.append(_Sent(body, extra_content))
- return f"evt-{len(sent)}"
+ return SentMessage(event_id=f"evt-{len(sent)}", trust=None)
svc.list_participants = _participants # type: ignore[assignment]
svc.send_message = _send_message # type: ignore[assignment]
diff --git a/core/tests/switch_core/trust/test_attachments.py b/core/tests/switch_core/trust/test_attachments.py
new file mode 100644
index 000000000..ddd0d6075
--- /dev/null
+++ b/core/tests/switch_core/trust/test_attachments.py
@@ -0,0 +1,679 @@
+"""What an attached file is checked as, and how a message's files are judged
+together. The two call sites (inbound bridge, agent send_media) are tested
+separately; this covers the decisions they share."""
+
+import io
+import logging
+import sys
+import zipfile
+
+import pytest
+from pypdf import PdfReader, PdfWriter
+
+from switch_core import file_text as file_text_module
+from switch_core.file_text import read_file_text
+from switch_core.trust import attachments
+from switch_core.trust.attachments import (
+ TRUST_FILE_TEXT_LIMIT,
+ AttachmentsVerdict,
+ check_attachments,
+ extract_file_text,
+)
+from switch_core.trust.client import TrustCheckResult, TrustFinding
+
+
+class _ContentTrustClient:
+ """Blocks text containing FORBIDDEN, redacts text containing SECRET,
+ flags text containing FLAG, and allows the rest. Records what it saw."""
+
+ def __init__(self) -> None:
+ self.checked: list[tuple[str, str]] = []
+
+ async def is_active(self) -> bool:
+ return True
+
+ async def check(self, *, role: str, content: str, room_id: str) -> TrustCheckResult:
+ self.checked.append((role, content))
+ finding = (TrustFinding(category="test", detector_name="t", severity="high"),)
+ if "FORBIDDEN" in content:
+ return TrustCheckResult("blocked", "p", "policy", finding)
+ if "SECRET" in content:
+ return TrustCheckResult(
+ "redacted", "p", "policy", finding, content.replace("SECRET", "x")
+ )
+ if "FLAG" in content:
+ return TrustCheckResult("alerted", "p", "policy", finding)
+ return TrustCheckResult("ok", "p", "policy")
+
+
+ ("mimetype", "data"),
+ [
+ ("text/plain", b"hello"),
+ ("application/json", b'{"a": 1}'),
+ ("application/x-yaml", b"a: 1"),
+ ("text/csv; charset=utf-8", b"a,b\n1,2"),
+ ("application/octet-stream", b"print('hi')"),
+ ("image/svg+xml", b"<svg></svg>"),
+ ],
+)
+def test_text_like_files_are_read_as_text(mimetype: str, data: bytes) -> None:
+ file_text = extract_file_text(data, mimetype, "file")
+ assert file_text.text == data.decode()
+ assert file_text.unreadable_reason is None
+
+
+ ("mimetype", "data"),
+ [
+ ("image/png", b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR"),
+ ("application/pdf", b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n\x00"),
+ (
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ b"PK\x03\x04\x14\x00\x00\x00",
+ ),
+ ("application/zip", b"PK\x03\x04\x14\x00\x00\x00"),
+ ("application/octet-stream", b"\xff\xfe\x00\x01"),
+ ("text/plain", b"nul\x00inside"),
+ ],
+)
+def test_files_without_readable_text_are_never_sent_as_text(
+ mimetype: str, data: bytes
+) -> None:
+ file_text = extract_file_text(data, mimetype, "file")
+ assert file_text.text is None
+ assert file_text.unreadable_reason
+
+
+ ("mimetype", "filename"),
+ [
+ ("image/png", "secrets.txt"),
+ ("application/zip", "secrets.zip"),
+ ("audio/mpeg", "secrets.mp3"),
+ ("application/pdf", "notes.pdf"),
+ ("application/octet-stream", "notes.pdf"),
+ ("application/octet-stream", "notes.docx"),
+ (
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "notes.docx",
+ ),
+ ],
+)
+def test_text_labelled_or_named_as_something_else_is_still_checked(
+ mimetype: str, filename: str
+) -> None:
+ # The type and the name are the sender's to choose; the bytes decide.
+ secret = b"API_KEY=placeholder-credential-value\n"
+ file_text = extract_file_text(secret, mimetype, filename)
+ assert file_text.text == secret.decode()
+ assert file_text.unreadable_reason is None
+
+
+async def test_text_named_as_a_document_is_checked_through_the_worker() -> None:
+ secret = b"API_KEY=placeholder-credential-value\n"
+ file_text = await read_file_text(secret, "application/octet-stream", "notes.pdf")
+ assert file_text.text == secret.decode()
+
+
+async def test_an_image_alone_carries_no_note_and_is_not_checked() -> None:
+ client = _ContentTrustClient()
+ verdict = await check_attachments(
+ client, # type: ignore[arg-type]
+ role="user",
+ files=[(b"\x89PNG", "cat.png", "image/png")],
+ room_id="room-1",
+ )
+ assert verdict == AttachmentsVerdict()
+ assert client.checked == []
+
+
+async def test_an_image_still_blocks_when_unchecked_files_are_not_relayed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(attachments, "RELAY_UNCHECKED_FILES", False)
+ verdict = await check_attachments(
+ _ContentTrustClient(), # type: ignore[arg-type]
+ role="user",
+ files=[(b"\x89PNG", "cat.png", "image/png")],
+ room_id="room-1",
+ )
+ assert verdict.blocked
+ assert "cat.png could not be checked" in verdict.block_reasons[0]
+
+
+def test_long_text_is_cut_to_the_limit() -> None:
+ file_text = extract_file_text(
+ b"a" * (TRUST_FILE_TEXT_LIMIT + 5), "text/plain", "big.log"
+ )
+ assert file_text.text is not None
+ assert len(file_text.text) == TRUST_FILE_TEXT_LIMIT
+ assert file_text.checked_part == "the first 20,000 characters"
+
+
+async def test_a_blocked_file_blocks_and_names_the_file() -> None:
+ client = _ContentTrustClient()
+ verdict = await check_attachments(
+ client, # type: ignore[arg-type]
+ role="user",
+ files=[(b"fine", "a.txt", "text/plain"), (b"FORBIDDEN", "b.txt", "text/plain")],
+ room_id="room-1",
+ )
+ assert verdict.blocked
+ assert any("b.txt" in reason for reason in verdict.block_reasons)
+ assert sorted(content for _, content in client.checked) == ["FORBIDDEN", "fine"]
+
+
+async def test_a_redacted_file_blocks_because_a_file_cannot_be_redacted() -> None:
+ verdict = await check_attachments(
+ _ContentTrustClient(), # type: ignore[arg-type]
+ role="user",
+ files=[(b"my SECRET", "notes.md", "text/markdown")],
+ room_id="room-1",
+ )
+ assert verdict.blocked
+ assert verdict.block is not None and verdict.block.outcome == "blocked"
+ assert "cannot be redacted" in verdict.block_reasons[0]
+
+
+async def test_unreadable_flagged_and_long_files_each_carry_a_note() -> None:
+ client = _ContentTrustClient()
+ verdict = await check_attachments(
+ client, # type: ignore[arg-type]
+ role="assistant",
+ files=[
+ (b"\x89PNG", "cat.png", "image/png"),
+ (b"%PDF-1.4\x00garbage", "scan.pdf", "application/pdf"),
+ (b"FLAG", "f.txt", "text/plain"),
+ (b"b" * (TRUST_FILE_TEXT_LIMIT + 1), "long.log", "text/plain"),
+ ],
+ room_id="room-1",
+ )
+ assert not verdict.blocked
+ assert verdict.flagged
+ notes = "\n".join(verdict.notes)
+ assert "did not check scan.pdf (this PDF could not be read)" in notes
+ # An image is a kind Switch never reads, so it carries no note.
+ assert "cat.png" not in notes
+ assert "flagged f.txt" in notes
+ assert (
+ "checked only the first 20,000 characters of long.log; the rest was not checked"
+ in notes
+ )
+ # The image's bytes were never sent.
+ assert all(role == "assistant" for role, _ in client.checked)
+ assert len(client.checked) == 2
+
+
+async def test_a_file_padded_with_blank_space_still_says_the_rest_was_not_checked() -> (
+ None
+):
+ client = _ContentTrustClient()
+ verdict = await check_attachments(
+ client, # type: ignore[arg-type]
+ role="user",
+ files=[(b" " * TRUST_FILE_TEXT_LIMIT + b"FORBIDDEN", "pad.txt", "text/plain")],
+ room_id="room-1",
+ )
+ assert not verdict.blocked
+ assert client.checked == []
+ assert verdict.notes == (
+ "⚠️ _Switch Trust checked only the first 20,000 characters of pad.txt; "
+ "the rest was not checked._",
+ )
+
+
+async def test_unchecked_files_block_when_the_policy_says_so(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(attachments, "RELAY_UNCHECKED_FILES", False)
+ verdict = await check_attachments(
+ _ContentTrustClient(), # type: ignore[arg-type]
+ role="user",
+ files=[(b"\x89PNG", "cat.png", "image/png")],
+ room_id="room-1",
+ )
+ assert verdict.blocked
+ assert "cat.png could not be checked" in verdict.block_reasons[0]
+
+
+_W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+
+
+_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
+
+
+def _part(text: str, padding: int = 0) -> str:
+ return (
+ f'<w:document xmlns:w="{_W_NS}"><w:body><w:p><w:r>'
+ f"<w:t>{text}</w:t></w:r></w:p>{'<w:p/>' * padding}</w:body></w:document>"
+ )
+
+
+def _rels(*links: tuple[str, str, str]) -> str:
+ """A .rels part: (type, target, extra attributes) per relationship."""
+ return (
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/'
+ 'relationships">'
+ + "".join(
+ f'<Relationship Id="r{i}" Type="{_REL}/{kind}" Target="{target}"{extra}/>'
+ for i, (kind, target, extra) in enumerate(links)
+ )
+ + "</Relationships>"
+ )
+
+
+def _zip(members: dict[str, str]) -> bytes:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ for name, content in members.items():
+ archive.writestr(name, content)
+ return buffer.getvalue()
+
+
+def _docx(
+ body: str,
+ *,
+ header: str | None = None,
+ header_name: str = "header1.xml",
+ padding: int = 0,
+ links: tuple[tuple[str, str, str], ...] = (),
+ compression: dict[str, int] | None = None,
+) -> bytes:
+ """A minimal Word document: the package's and the body's relationships,
+ and the parts the reader looks at. `compression` overrides how named
+ members are stored."""
+ members = {
+ "[Content_Types].xml": "<Types/>",
+ "_rels/.rels": _rels(("officeDocument", "word/document.xml", "")),
+ "word/document.xml": _part(body, padding),
+ }
+ body_links = list(links)
+ if header is not None:
+ members[f"word/{header_name}"] = _part(header)
+ body_links.append(("header", header_name, ""))
+ members["word/_rels/document.xml.rels"] = _rels(*body_links)
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
+ for name, content in members.items():
+ archive.writestr(
+ name,
+ content,
+ compress_type=(compression or {}).get(name, zipfile.ZIP_DEFLATED),
+ )
+ return buffer.getvalue()
+
+
+def _pdf(*pages: str | None) -> bytes:
+ """A minimal PDF, one page per entry: a line of Helvetica text, or a
+ page with no text layer at all (None), as a scanned page has."""
+ count = len(pages)
+ kids = " ".join(f"{3 + 2 * i} 0 R" for i in range(count))
+ objects = [
+ "<< /Type /Catalog /Pages 2 0 R >>",
+ f"<< /Type /Pages /Kids [{kids}] /Count {count} >>",
+ ]
+ font = 3 + 2 * count
+ for i, text in enumerate(pages):
+ content = f"BT /F1 12 Tf 72 712 Td ({text}) Tj ET" if text else ""
+ objects.append(
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
+ f"/Resources << /Font << /F1 {font} 0 R >> >> /Contents {4 + 2 * i} 0 R >>"
+ )
+ objects.append(f"<< /Length {len(content)} >>\nstream\n{content}\nendstream")
+ objects.append("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")
+ out = b"%PDF-1.4\n"
+ offsets = []
+ for number, body in enumerate(objects, start=1):
+ offsets.append(len(out))
+ out += f"{number} 0 obj\n{body}\nendobj\n".encode()
+ xref = len(out)
+ out += f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode()
+ for offset in offsets:
+ out += f"{offset:010d} 00000 n \n".encode()
+ out += (
+ f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\n"
+ f"startxref\n{xref}\n%%EOF\n"
+ ).encode()
+ return out
+
+
+_DOCX_TYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
+
+
+def test_a_word_document_is_read_body_and_header() -> None:
+ file_text = extract_file_text(
+ _docx("the body", header="the header"), _DOCX_TYPE, "memo.docx"
+ )
+ assert file_text.text is not None
+ assert "the body" in file_text.text
+ assert "the header" in file_text.text
+
+
+def test_a_word_document_is_recognised_by_extension_alone() -> None:
+ file_text = extract_file_text(
+ _docx("hello"), "application/octet-stream", "memo.docx"
+ )
+ assert file_text.text is not None and "hello" in file_text.text
+
+
+ "data",
+ [
+ b"PK\x03\x04\x00 not really a zip",
+ # A zip without a document body is not a Word document.
+ _docx("x").replace(b"word/document.xml", b"word/documenX.xml"),
+ # Nor is one whose package names a body it does not contain.
+ _zip(
+ {
+ "_rels/.rels": _rels(("officeDocument", "word/gone.xml", "")),
+ "word/document.xml": _part("x"),
+ }
+ ),
+ ],
+)
+def test_a_broken_word_document_is_unchecked_not_an_error(data: bytes) -> None:
+ file_text = extract_file_text(data, _DOCX_TYPE, "memo.docx")
+ assert file_text.text is None
+ assert file_text.unreadable_reason == "this Word document could not be read"
+
+
+def test_a_word_document_declaring_a_dtd_is_refused() -> None:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ archive.writestr(
+ "word/document.xml",
+ '<!DOCTYPE x [<!ENTITY a "aaaa">]><w:document xmlns:w="'
+ f'{_W_NS}"><w:body><w:p><w:r><w:t>&a;</w:t></w:r></w:p></w:body>'
+ "</w:document>",
+ )
+ file_text = extract_file_text(buffer.getvalue(), _DOCX_TYPE, "memo.docx")
+ assert file_text.text is None
+
+
+def test_a_word_document_body_larger_than_the_budget_is_checked_up_to_it(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # A highly compressible body (a zip bomb, in the limit) is inflated only
+ # up to the budget, whatever size it declares, and that much is checked.
+ monkeypatch.setattr(file_text_module, "_DOCX_XML_BYTE_BUDGET", 2_000)
+ file_text = extract_file_text(
+ _docx("API_KEY=early", padding=100_000), _DOCX_TYPE, "bomb.docx"
+ )
+ assert file_text.text is not None
+ assert "API_KEY=early" in file_text.text
+ assert file_text.checked_part == "the first part"
+
+
+def test_a_header_past_the_budget_is_named_as_not_checked(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(file_text_module, "_DOCX_XML_BYTE_BUDGET", 2_000)
+ file_text = extract_file_text(
+ _docx("the body", header="x" * 5_000), _DOCX_TYPE, "memo.docx"
+ )
+ assert file_text.text is not None and "the body" in file_text.text
+ assert file_text.skipped == (
+ "word/header1.xml, which is larger than Switch Trust reads",
+ )
+
+
[email protected]("method", [zipfile.ZIP_LZMA, zipfile.ZIP_BZIP2])
+def test_a_word_document_body_not_stored_or_deflated_is_never_inflated(
+ method: int,
+) -> None:
+ # Python's LZMA and bzip2 readers inflate past what one read asks for, so
+ # a tiny member could cost far more memory than the budget allows.
+ data = _docx("the body", compression={"word/document.xml": method})
+ file_text = extract_file_text(data, _DOCX_TYPE, "memo.docx")
+ assert file_text.text is None
+ assert file_text.unreadable_reason == (
+ "this Word document uses a compression Switch Trust does not read"
+ )
+
+
+def test_a_header_not_stored_or_deflated_is_named_as_not_checked() -> None:
+ data = _docx(
+ "the body",
+ header="FORBIDDEN",
+ compression={"word/header1.xml": zipfile.ZIP_LZMA},
+ )
+ file_text = extract_file_text(data, _DOCX_TYPE, "memo.docx")
+ assert file_text.text is not None and "FORBIDDEN" not in file_text.text
+ assert file_text.skipped == (
+ "word/header1.xml, which uses a compression Switch Trust does not read",
+ )
+
+
+async def test_a_renamed_header_is_found_through_the_relationships() -> None:
+ # Word finds a header by the body's relationships, not by its file name.
+ client = _ContentTrustClient()
+ verdict = await check_attachments(
+ client, # type: ignore[arg-type]
+ role="user",
+ files=[
+ (
+ _docx("the body", header="FORBIDDEN", header_name="custom-header.xml"),
+ "memo.docx",
+ _DOCX_TYPE,
+ )
+ ],
+ room_id="room-1",
+ )
+ assert verdict.blocked
+ assert "memo.docx was blocked" in verdict.block_reasons[0]
+
+
+def test_a_body_the_package_names_elsewhere_is_the_one_read() -> None:
+ data = _zip(
+ {
+ "_rels/.rels": _rels(("officeDocument", "/content/main.xml", "")),
+ "content/main.xml": _part("the real body"),
+ "word/document.xml": _part("a decoy"),
+ }
+ )
+ file_text = extract_file_text(data, _DOCX_TYPE, "memo.docx")
+ assert file_text.text is not None
+ assert "the real body" in file_text.text
+ assert "a decoy" not in file_text.text
+
+
+async def test_parts_of_a_word_document_that_cannot_be_read_carry_a_note() -> None:
+ data = _docx(
+ "the body",
+ links=(
+ ("aFChunk", "afchunk.mht", ""),
+ ("footer", "https://example.com/footer.xml", ' TargetMode="External"'),
+ ("footnotes", "footnotes.xml", ""),
+ ),
+ )
+ file_text = extract_file_text(data, _DOCX_TYPE, "memo.docx")
+ assert file_text.skipped == (
+ "an embedded document",
+ "a footer part it links to but does not contain",
+ "a footnotes part it links to but does not contain",
+ )
+ verdict = await check_attachments(
+ _ContentTrustClient(), # type: ignore[arg-type]
+ role="user",
+ files=[(data, "memo.docx", _DOCX_TYPE)],
+ room_id="room-1",
+ )
+ assert not verdict.blocked
+ [note] = verdict.notes
+ assert "did not check part of memo.docx (an embedded document;" in note
+
+
+def test_a_word_document_with_no_text_is_unchecked() -> None:
+ file_text = extract_file_text(_docx(""), _DOCX_TYPE, "pictures.docx")
+ assert file_text.text is None
+ assert file_text.unreadable_reason == "no text found in this Word document"
+
+
+def test_a_pdf_is_read_page_by_page() -> None:
+ file_text = extract_file_text(
+ _pdf("first page", "second page"), "application/pdf", "doc.pdf"
+ )
+ assert file_text.text is not None
+ assert "first page" in file_text.text
+ assert "second page" in file_text.text
+ assert file_text.checked_part is None
+
+
+def test_a_scanned_pdf_with_no_text_is_unchecked_not_clean() -> None:
+ file_text = extract_file_text(_pdf(None), "application/pdf", "scan.pdf")
+ assert file_text.text is None
+ assert "no text found in this PDF" in (file_text.unreadable_reason or "")
+
+
+def test_a_malformed_pdf_is_unchecked_not_an_error() -> None:
+ file_text = extract_file_text(b"%PDF-1.4\x00garbage", "application/pdf", "x.pdf")
+ assert file_text.unreadable_reason == "this PDF could not be read"
+
+
+def test_an_encrypted_pdf_is_unchecked() -> None:
+ writer = PdfWriter()
+ writer.add_blank_page(100, 100)
+ writer.encrypt("secret")
+ buffer = io.BytesIO()
+ writer.write(buffer)
+ file_text = extract_file_text(buffer.getvalue(), "application/pdf", "x.pdf")
+ assert file_text.unreadable_reason == "encrypted PDFs cannot be checked"
+
+
+def test_a_pdf_past_the_page_limit_says_which_pages_were_checked(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(file_text_module, "_PDF_PAGE_LIMIT", 1)
+ file_text = extract_file_text(_pdf("one", "two"), "application/pdf", "x.pdf")
+ assert file_text.text is not None and "two" not in file_text.text
+ assert file_text.checked_part == "the first 1 pages"
+
+
+def test_a_pdf_is_read_without_walking_its_whole_page_tree(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # `reader.pages` counts every page before giving the first; a crafted
+ # page tree makes that as slow as its author likes.
+ def walk_everything(*_args: object, **_kwargs: object) -> None:
+ raise AssertionError("walked the whole page tree")
+
+ monkeypatch.setattr(PdfReader, "_flatten", walk_everything)
+ file_text = extract_file_text(
+ _pdf("first page", "second page"), "application/pdf", "doc.pdf"
+ )
+ assert file_text.text is not None
+ assert "first page" in file_text.text and "second page" in file_text.text
+
+
+def test_a_pdf_page_inherits_its_fonts_from_the_page_tree() -> None:
+ data = (
+ _pdf("inherited font")
+ .replace(b"/Resources << /Font << /F1 5 0 R >> >> ", b"")
+ .replace(b"/Count 1 >>", b"/Count 1 /Resources << /Font << /F1 5 0 R >> >> >>")
+ )
+ file_text = extract_file_text(data, "application/pdf", "doc.pdf")
+ assert file_text.text is not None and "inherited font" in file_text.text
+
+
+async def test_a_document_that_takes_too_long_to_read_is_not_checked(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ monkeypatch.setattr(file_text_module, "_WORKER_TIMEOUT_SECONDS", 0)
+ client = _ContentTrustClient()
+ with caplog.at_level(logging.WARNING):
+ verdict = await check_attachments(
+ client, # type: ignore[arg-type]
+ role="user",
+ files=[(_pdf("FORBIDDEN"), "slow.pdf", "application/pdf")],
+ room_id="room-1",
+ )
+ assert not verdict.blocked
+ assert verdict.notes == (
+ "⚠️ _Switch Trust did not check slow.pdf (it took too long to read)._",
+ )
+ assert client.checked == []
+ assert "took longer than" in caplog.text
+
+
+async def test_documents_are_read_in_a_worker_process() -> None:
+ word = await read_file_text(_docx("the body"), _DOCX_TYPE, "memo.docx")
+ pdf = await read_file_text(_pdf("a page"), "application/pdf", "doc.pdf")
+ assert word.text is not None and "the body" in word.text
+ assert pdf.text is not None and "a page" in pdf.text
+
+
+ not sys.platform.startswith("linux"), reason="only Linux caps address space"
+)
+async def test_a_document_that_needs_too_much_memory_is_not_checked(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(file_text_module, "_WORKER_MEMORY_BYTES", 1024 * 1024)
+ file_text = await read_file_text(
+ _pdf("x" * 2_000_000), "application/pdf", "doc.pdf"
+ )
+ assert file_text.text is None
+ assert file_text.unreadable_reason == "it could not be read within Switch's limits"
+
+
+async def test_blocked_text_inside_a_word_document_or_a_pdf_blocks() -> None:
+ client = _ContentTrustClient()
+ verdict = await check_attachments(
+ client, # type: ignore[arg-type]
+ role="user",
+ files=[
+ (_docx("FORBIDDEN plan"), "plan.docx", _DOCX_TYPE),
+ (_pdf("FORBIDDEN report"), "report.pdf", "application/pdf"),
+ ],
+ room_id="room-1",
+ )
+ assert verdict.blocked
+ reasons = " ".join(verdict.block_reasons)
+ assert "plan.docx was blocked" in reasons
+ assert "report.pdf was blocked" in reasons
+
+
+async def test_a_scanned_pdf_is_relayed_with_a_not_checked_note() -> None:
+ verdict = await check_attachments(
+ _ContentTrustClient(), # type: ignore[arg-type]
+ role="user",
+ files=[(_pdf(None), "scan.pdf", "application/pdf")],
+ room_id="room-1",
+ )
+ assert not verdict.blocked
+ [note] = verdict.notes
+ assert "did not check scan.pdf" in note
+
+
+def _docx_with(document_xml: bytes) -> bytes:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ archive.writestr("word/document.xml", document_xml)
+ return buffer.getvalue()
+
+
+def test_a_dtd_split_across_read_chunks_is_still_refused() -> None:
+ chunk = 64 * 1024
+ body = (
+ f'<w:document xmlns:w="{_W_NS}"><w:body><w:p><w:r><w:t>&a;</w:t>'
+ "</w:r></w:p></w:body></w:document>"
+ ).encode()
+ head = b'<?xml version="1.0"?>\n'
+ head += b" " * (chunk - len(head) - 4) + b"<!DOCTYPE w:document ["
+ head += b" " * (2 * chunk - len(head) - 4) + b'<!ENTITY a "secret">]>' + body
+ assert b"<!DOCTYPE" not in head[:chunk]
+ assert b"<!ENTITY" not in head[chunk : 2 * chunk]
+ file_text = extract_file_text(_docx_with(head), _DOCX_TYPE, "evil.docx")
+ assert file_text.text is None
+
+
+def test_a_dtd_in_utf16_is_still_refused() -> None:
+ document = (
+ '<?xml version="1.0" encoding="UTF-16"?>'
+ '<!DOCTYPE w:document [<!ENTITY a "secret">]>'
+ f'<w:document xmlns:w="{_W_NS}"><w:body><w:p><w:r><w:t>&a;</w:t>'
+ "</w:r></w:p></w:body></w:document>"
+ ).encode("utf-16")
+ file_text = extract_file_text(_docx_with(document), _DOCX_TYPE, "evil.docx")
+ assert file_text.text is None
diff --git a/core/tests/switch_core/trust/test_client.py b/core/tests/switch_core/trust/test_client.py
index 4def22113..0856a3028 100644
--- a/core/tests/switch_core/trust/test_client.py
+++ b/core/tests/switch_core/trust/test_client.py
@@ -22,6 +22,7 @@ from switch_core.trust.client import (
TrustFinding,
check_message,
trust_annotation,
+ trust_is_active,
)
@@ -496,3 +497,32 @@ def test_trust_annotation_is_none_for_ok_blocked_and_redacted():
for outcome in ("ok", "blocked", "redacted"):
result = TrustCheckResult(outcome=outcome, policy_id=None, policy_name=None)
assert trust_annotation(result) is None
+
+
+async def test_is_active_follows_the_settings_row() -> None:
+ complete = _FakeRow(
+ endpoint="https://trust.example", policy_id="pol_1", api_key_encrypted="enc:k"
+ )
+ no_key = _FakeRow(
+ endpoint="https://trust.example", policy_id="pol_1", api_key_encrypted=None
+ )
+ assert await _dynamic_client(complete, _unreachable).is_active() is True
+ assert await _dynamic_client(no_key, _unreachable).is_active() is False
+ assert await _dynamic_client(None, _unreachable).is_active() is False
+ assert await NullTrustClient().is_active() is False
+
+
+class _UnreadableSettingsClient:
+ async def is_active(self) -> bool:
+ raise GuardrailsCheckError("database unavailable")
+
+ async def check(self, *, role: str, content: str, room_id: str) -> TrustCheckResult:
+ raise AssertionError("not called")
+
+
+async def test_trust_is_active_checks_anyway_when_settings_cannot_be_read() -> None:
+ # Failing towards checking: each check then fails open with its visible
+ # "could not check" note, instead of the message skipping Switch Trust.
+ assert await trust_is_active(_UnreadableSettingsClient()) is True # type: ignore[arg-type]
diff --git a/core/uv.lock b/core/uv.lock
index 6622c429a..eb83947b1 100644
--- a/core/uv.lock
+++ b/core/uv.lock
@@ -1929,6 +1929,15 @@ crypto = [
{ name = "cryptography" },
]
+[[package]]
+name = "pypdf"
+version = "6.21.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/1e/e1/ec8f4d155c997c45917153a5521e60d6ee6389d68abdcbc8e44e564caffc/pypdf-6.21.4.tar.gz", hash = "sha256:c8817e3f888d47a087872ded69812c1ef30cacb871d6e053e0c00bbaf0bc2163", size = 7109255, upload-time = "2026-10-28T17:00:54.81Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3f/4b/77e8ad4ac42c9d93600f40541a50e9feb3a61d2bbee2d76f659346072051/pypdf-6.21.4-py3-none-any.whl", hash = "sha256:33e4fb41ca352810eb4e9838aa0d82d6888a5f8bf682f43e99cce5faa666255c", size = 410430, upload-time = "2026-10-28T17:00:53.146Z" },
+]
+
[[package]]
name = "pyperclip"
version = "1.11.0"
@@ -2399,6 +2408,7 @@ dependencies = [
{ name = "pydantic" },
{ name = "pydantic-settings" },
{ name = "pyjwt" },
+ { name = "pypdf" },
{ name = "python-telegram-bot" },
{ name = "pyyaml" },
{ name = "slack-sdk" },
@@ -2440,6 +2450,7 @@ requires-dist = [
{ name = "pydantic", specifier = ">=2,<3" },
{ name = "pydantic-settings", specifier = ">=2.14.2,<3.0" },
{ name = "pyjwt", specifier = ">=2.14,<3" },
+ { name = "pypdf", specifier = ">=6.21.4,<7" },
{ name = "python-telegram-bot", specifier = ">=21,<22" },
{ name = "pyyaml", specifier = ">=6,<7" },
{ name = "slack-sdk", specifier = ">=3.41.0" },