Building a fail-closed security boundary between an LLM and Telegram in Rust

System prompts are suggestions. When an MCP server holds a live personal Telegram session, every invariant that matters has to live in deterministic code with explicit failure modes. Here is how gramcp structures that boundary in Rust.

1. One entry point: PolicyEngine<B: TelegramBackend>

Tool handlers never receive a raw Telegram client. Every handler receives &PolicyEngine<B> (src/security/policy.rs), which pairs one account's immutable startup Config, its account-partitioned SQLite Storage, its PathSandbox, RateLimiter, ReadBlacklistGuard, and Arc<B> backend.

Authorization runs before argument-specific side effects and computes the intersection:

allowed = enabled_tools(sqlite) ∩ hard_ceiling(config)

Every tool in src/tools/catalog.rs belongs to exactly one of 7 tiers (Read, Organize, Send, Moderate, Destructive, Account, Money). Because hard_ceiling is loaded once at process startup, neither a compromised MCP session nor someone clicking toggles in /settings can unlock delete_messages or stars_action unless the operator edits config.toml and restarts.

2. Canonical peer identity & structural read blacklisting

Telegram peers have multiple textual forms: user:12345, -100999, channel:999, me, or a basic group ID that later migrated into a supergroup. CanonicalChatId (src/types.rs) normalizes channels/supergroups into a disjoint -(1_000_000_000_000 + raw_id) space separate from basic groups (-<id>) and resolves me alongside the authenticated account's numeric self_user_id.

If read_blacklist is non-empty and self_user_id or a group-migration probe fails, refresh_self_user_id() fails closed with an error instead of running an incomplete filter. Before any read response leaves the server, ReadBlacklistGuard drops blacklisted peers from dialogs, search hits, forwards, members, voters, and stories, and sanitize_reply_quotes() blanks out quote_text whenever a reply points to a blacklisted or unverifiable parent message.

3. Rate limit permits that survive restarts and HTTP cancels

execute_rate_limited_send_action_units (src/tools/handlers/common.rs) reserves N message slots inside a SQLite IMMEDIATE transaction before calling Telegram. Notice one subtle detail in the permit lifecycle:

let mut permit = policy.rate_limiter().reserve_at(chat_id, now_ms, units)?;
permit.disarm_drop_rollback();
match op().await {
    Ok(value) => { permit.commit()?; Ok((value, now_ms)) }
    Err(err)  => { let _ = permit.rollback(); Err(err) }
}

Disarming drop-rollback right before op().await closes a classic async race: if an HTTP client cancels the request mid-flight after MTProto already dispatched the message, dropping the future does not refund the quota slot. Explicit backend errors still roll the permit back cleanly.

4. Pre-execution audit logging & retention isolation

Every mutating tool writes an audit_log row inside an IMMEDIATE SQLite transaction before executing the MTProto call. If disk is full or the database is locked beyond retry, the server returns audit_failed and never sends the Telegram request.

To prevent a prompt-injected loop of rejected calls from pushing real mutations out of the log, retention is split by event class: denial noise (deny_*, username_mismatch, failed logins) keeps the newest 5,000 rows per account, while actual mutations keep the newest 50,000 rows.

5. Framing untrusted output as data

Every external Telegram read passes through render_external_result, which wraps payloads in [external data] and appends a separate trailing ContentBlock warning the model that the content came from other people on Telegram and must never be followed as instructions. Local status, list_accounts, and error results omit the wrapper so policy diagnostics stay unambiguous.

Explore the full security architecture, read the threat model, or run cargo test --all-targets against the mock backend on GitHub.