Security architecture

Every MCP tool call passes through a deterministic Rust PolicyEngine before any MTProto request leaves the process. Unknown inputs, ambiguous targets, storage errors, and unauthenticated endpoints fail closed.

1. Execution pipeline

When an MCP client invokes a tool over stdio, /mcp, or pinned /mcp/<alias>, dispatch runs nine ordered gates:

MCP tools/call
  1. Account resolution  (stateless `account` arg or pinned `/mcp/<alias>`; never falls back)
  2. Strict schema parse (`#[serde(deny_unknown_fields)]` rejects unexpected arguments)
  3. Tool authorization  (`enabled_tools ∩ hard_ceiling`; unknown tools fail closed)
  4. Kill-switch check   (`sending_paused` from SQLite halts all Send-tier & paid_reaction calls)
  5. Peer normalization  (`CanonicalChatId` + `read_blacklist` + `chat_migrations` equivalence)
  6. Destination check   (`send_whitelist` membership + live `@username -> peer_id` pinning)
  7. Sandbox & limits    (`PathSandbox` canonicalize + `O_NOFOLLOW`; SQLite rolling rate permits)
  8. Pre-execution audit (`Storage::record_audit` in IMMEDIATE tx; failure aborts the call)
  9. MTProto call        (`grammers` backend) -> output filtered & wrapped in `[external data]`

2. Trust boundaries

Boundary Code location Guarantee
Telegram content → LLM src/security/filter.rs, src/tools/handlers/common.rs Blacklisted peers drop before serialization; reply quotes from blacklisted or unverifiable parents are redacted; responses carry [external data] wrapping and a separate warning block.
LLM → Telegram account src/security/policy.rs hard_ceiling cannot widen at runtime; send_whitelist defaults to strict and empty; safe delete restricts delete_messages to gramcp-sent messages within 60 minutes.
MCP credentials → Admin UI src/settings/ Every Authorization header is inspected; MCP bearer tokens and OAuth 2.1 access tokens always receive HTTP 403 on /settings*.
Account A → Account B src/accounts.rs, src/storage/mod.rs Separate session_<alias>.db files (0600), account-partitioned SQLite tables, per-account OAuth scopes (account:<alias>), and pinned /mcp/<alias> routes.
Media I/O → Host filesystem src/security/paths.rs Uploads canonicalize inside outbox_dir with O_NOFOLLOW; downloads stay in RAM (4 MiB cap) unless inbox_dir is set (atomic temp rename, 50 MiB cap).

3. Built-in OAuth 2.1 server

Remote MCP clients such as Claude.ai custom connectors authenticate via src/oauth/ instead of storing a static bearer token in a hosted UI.

Mechanism Enforcement detail
PKCE S256 43-char unpadded base64url challenges and 43–128 char verifiers compared in constant time; plain is rejected.
Dynamic Client Registration POST /oauth/register validates redirect URIs (https:// or loopback HTTP), caps client count, and charges per-IP rate limits before global buckets.
POST consent & CSRF GET /oauth/authorize never issues codes. Consent enforces strict CSP, X-Frame-Options: DENY, no-store, and HMAC-SHA256 CSRF tokens bound to client, redirect URI, PKCE challenge, subject, scope, and resource.
Code & refresh rotation SQLite stores only SHA-256 hashes. Replaying an already-rotated or revoked refresh token revokes the entire token family and writes an oauth_refresh_reuse audit row.
Per-account scoping Tokens scoped to account:<alias> or RFC 8707 resource work only on /mcp/<alias> and return 403 insufficient_scope elsewhere.

4. HTTP hardening and /settings isolation

In HTTP mode, gramcp refuses to start if /mcp has no authentication configured, caps request bodies at 8 MiB, rejects JSON-RPC batch arrays (-32600), and checks the Host header against allowed_hosts and oauth.issuer against DNS rebinding.

/settings* returns 404 when unconfigured, accepts three composable auth adapters (Argon2id password with lockout, Cloudflare Access RS256 JWKS verification, or loopback-only trusted proxy headers), enforces CSRF checks on state-changing API calls, and sends strict CSP headers (default-src 'none'; script-src 'self'; frame-ancestors 'none').

Security audit log in gramcp /settings showing deny_not_whitelisted, deny_hard_ceiling_exceeded, and deny_read_blacklisted
Every refusal and mutation is persisted in SQLite audit_log with separate retention buckets so denial floods cannot evict mutation history.

Architecture notes

Next: Threat model & refusal codes, or report a policy bypass privately via SECURITY.md.