feat: tighten runtime policy + transport guards
Summary
- Polish pass across the local listener — Socket.IO, SSE, the public OAuth-style callback, the channel inbound bus, and memory recall — to bring each surface in line with the boundaries the rest of the runtime already uses.
- Six small, scope-isolated commits. Each independently reviewable, layered foundation → transport → endpoints → memory.
- No release-cut behaviour shifts for the golden user paths; frontend Socket.IO callers updated atomically.
Problem
- Several local listener surfaces had grown ahead of the shared helpers the rest of the runtime uses for the same job: Socket.IO did its own handshake plumbing while the HTTP path went through
rpc_auth_middleware; SSE accepted a free-formclient_idquery string with no minted token; the public Telegram callback accepted any GET without fetch-metadata sanity checks; the inbound channel bus keyed by channel alone while every other inbound path keys by(channel, sender, reply_target, thread_ts); memory recall rendered every hit into the agent prompt with no provenance hint. - This PR brings each surface back under the same shared helper (or adds a small one where none existed) so behaviour is uniform with the rest of the codebase.
Solution
Layered, scope-isolated commits. Each commit is independently reviewable:
refactor(core/auth): extract a reusableverify_bearer_tokenhelper so non-HTTP transports can use the same comparison the Axum middleware uses internally. Pure refactor — no behaviour change, middleware delegates to the helper.feat(core/socketio): route the Socket.IO handshake throughverify_bearer_token(auth.tokenpayload on the client) plus an Origin allowlist (Tauri shell, localhost loopback, native clients without anOriginheader). Adds anAuthedConnectionmarker on socket extensions so every executable event handler consults the same gate. Frontend (socketService,useDictationHotkey,OverlayApp) passes the per-process bearer viagetCoreRpcToken().feat(core/events): SSE subscribers now mint a single-shot bind token through a small bearer-protected RPC (core.events_subscribe_token) and open/events?client_id=…&token=…. Tokens are bound to the issuedclient_id, single-shot on validate, and time-bounded. Bearer-header callers (CLI, Tauri shell) are still accepted to keep the existing flows green.feat(core/auth): the public Telegram OAuth-style callback gains a fetch-metadata gate.Sec-Fetch-Modemust benavigate,Sec-Fetch-Destmust bedocument, and cross-site redirects must originate fromhttps://t.me/...orhttps://web.telegram.org/.... Older browsers without fetch-metadata headers stay supported via a Referer host fallback.fix(channels/bus): restore per-sender keying on the inbound bus path so it matcheschannels::context::conversation_history_key.DomainEvent::ChannelInboundMessagegrowssender/reply_target/thread_ts(allOption<String>— legacy publishers compile unchanged), and a newderive_inbound_thread_idmirrors the canonical shape.feat(memory): wrap memory-recall hits whose namespace is not on the locally-authored allowlist (or whose key uses a connector prefix) in explicit<untrusted-source>markers via a newmemory_context_safetymodule. Conservative on purpose — defense-in-depth ahead of a follow-up typedProvenanceenum onMemoryEntry.
28 new unit tests across the six modules (see per-commit counts in commit messages).
Submission Checklist
If a section does not apply to this change, mark the item as
N/Awith a one-line reason. Do not delete items.
- [x] Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy
- [x] N/A: in-progress; new modules ship with focused unit tests but full lcov merge has not yet run on this branch — Diff coverage ≥ 80% check will run once tests are green
- [x] N/A: refactor + parity work; no new feature row — Coverage matrix updated
- [x] N/A: no feature IDs touched — All affected feature IDs from the matrix are listed in the PR description under
## Related - [x] No new external network dependencies introduced (mock backend used per Testing Strategy)
- [x] N/A: no user-visible surface change in the golden path; in-tree Socket.IO + SSE callers updated atomically — Manual smoke checklist updated if this touches release-cut surfaces
- [x] N/A: no public tracking issue for this sweep — Linked issue closed via
Closes #NNNin the## Relatedsection
Impact
- Internal parity across local listener surfaces — Socket.IO + SSE + Telegram callback now run on the same helpers the HTTP path already uses.
- Channel inbound keying matches the canonical conversation-history shape.
- Memory recall surfaces a provenance hint to the agent prompt.
- Performance: negligible. SSE bind tokens add one RPC round-trip per subscribe; Socket.IO handshake adds one constant-time string compare; memory recall adds a per-row heuristic +
format!.
Related
- Closes: N/A — no public tracking issue for this sweep.
- Follow-up PR(s)/TODOs:
- Typed
Provenanceenum onMemoryEntry, populated at ingestion, to replace the conservative heuristic in commit 6. - Bot-side
stateparameter wiring for/auth/telegramso the callback can bind to a server-issued nonce in addition to the fetch-metadata gate.
- Typed
AI Authored PR Metadata (required for Codex/Linear PRs)
Linear Issue
- Key: N/A
- URL: N/A
Commit & Branch
- Branch:
feat/runtime-policy-tightening - Commit SHA: see
git log upstream/main..HEAD— 6 commits, layered foundation → memory.
Validation Run
- [x]
pnpm --filter openhuman-app format:check— clean aftercargo fmtpass - [x]
pnpm typecheck— clean - [x] Focused tests:
cargo test --lib core::auth,core::socketio::tests,core::event_bind_tokens,core::jsonrpc::tests::telegram_callback_*,openhuman::channels::bus::inbound_thread_id_tests,openhuman::agent::harness::memory_context_safety— all pass - [x] Rust fmt/check (if changed):
cargo check --manifest-path Cargo.tomlclean - [x] N/A: no src-tauri changes — Tauri fmt/check (if changed)
Validation Blocked
command:N/Aerror:N/Aimpact:N/A
Behavior Changes
- Intended behavior change: Socket.IO handshake now reads
auth.tokenand rejects non-allowlisted origins; SSE/eventsrequires either aBearerheader or a minted bind token; Telegram callback validates fetch-metadata; inbound channel keying matchesconversation_history_key; memory recall wraps connector-namespaced hits in<untrusted-source>. - User-visible effect: None on the golden paths — frontend Socket.IO callers updated atomically.
Parity Contract
- Legacy behavior preserved: Native (no-Origin) Socket.IO clients still accepted; bearer-header callers to
/eventsstill accepted;/auth/telegrambrowsers without fetch-metadata headers still served via Referer fallback; inbound bus publishers withoutsenderproduce the historical channel-only key. - Guard/fallback/dispatch parity checks: Socket.IO
AuthedConnectionmarker + connect-time disconnect; bind-token single-shot with TTL clamp; telegram referer host fallback; memory namespace allowlist + connector key-prefix default-deny.
Duplicate / Superseded PR Handling
- Duplicate PR(s): N/A
- Canonical PR: this one
- Resolution: N/A
Summary by CodeRabbit
-
New Features
- Centralized, authenticated core connections and short-lived event tokens for SSE clients.
- Conversation threading now preserves sender/context so threads remain distinct.
-
Security
- Stronger bearer-token validation and origin checks for callbacks and socket connections.
- Agent memory handling marks/isolates potentially untrusted external content.
-
Tests
- Expanded test suites for socket auth, event bind tokens, origin validation, and memory-safety.
[!NOTE]
Reviews paused
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
- [ ] ▶️ Resume reviews
- [ ] 🔍 Trigger review
📝 Walkthrough
Walkthrough
Adds Socket.IO handshake bearer auth and origin checks, an SSE bind-token lifecycle plus RPC to mint tokens, updates /events to accept bind tokens or Bearer tokens, extends channel inbound events with sender/reply_target/thread_ts and per-thread IDs, and wraps potentially untrusted memory entries before inserting into agent prompts.
Changes
Socket.IO and Event Stream Authentication
| Layer / File(s) | Summary |
|---|---|
Bearer token verification helper src/core/auth.rs |
verify_bearer_token added to validate supplied bearer tokens against the RPC token; unit test ensures empty supplied tokens are rejected. |
Socket.IO connection authentication and origin validation src/core/socketio.rs |
Handshake auth parsing, AuthedConnection marker, Origin allowlist, connection-time bearer verification, and early-disconnect guards for unauthenticated sockets; origin allowlist tests added. |
Event bind-token store src/core/event_bind_tokens.rs, src/core/mod.rs |
In-memory bind-token store with issue/consume, TTL clamping, capacity limits, single-shot semantics, and unit tests; module exported from core. |
Core RPC method for event token minting src/core/dispatch.rs |
Adds core.events_subscribe_token dispatch handler that validates client_id, optional ttl_secs, mints bind tokens via event_bind_tokens::issue, and returns { token, ttl_secs }. |
SSE /events endpoint token security & Telegram origin check src/core/jsonrpc.rs, src/core/jsonrpc_tests.rs |
/events now accepts token and validates either Bearer via verify_bearer_token or single-use bind tokens via event_bind_tokens::consume; invalid creds return 401. Adds telegram_callback_origin_ok origin/fetch-metadata checks and tests; updates advertised events URL template with token. |
Frontend Socket.IO client authentication app/src/hooks/useDictationHotkey.ts, app/src/overlay/OverlayApp.tsx, app/src/services/socketService.ts, app/src/services/coreSocket.ts, app/src/services/__tests__/*, app/src/hooks/__tests__/* |
Introduces createCoreSocket factory and connectCoreSocket; callers fetch getCoreRpcToken() and pass it as coreToken (with per-session authExtras.session); tests/mocks updated to provide the mock core token and verify disposal logic. |
Channel Inbound Context Expansion
| Layer / File(s) | Summary |
|---|---|
Extended ChannelInboundMessage event schema src/core/event_bus/events.rs, src/core/event_bus/events_tests.rs |
DomainEvent::ChannelInboundMessage variant extended with optional sender, reply_target, and thread_ts fields. Test case updated to include new fields as None. |
Socket.IO inbound message context extraction src/openhuman/socket/event_handlers.rs |
*:message handler extracts optional routing fields from payload supporting multiple source keys and publishes them with the event. |
Thread-aware conversation key derivation src/openhuman/channels/bus.rs |
Adds derive_inbound_thread_id to build per-sender/thread conversation keys (channel:<name>[/<sender>][/<reply_target>][#thread:<ts>]), ignoring thread_ts for telegram; inbound handler now uses derived thread_id. |
Memory Context Safety for Agent Prompts
| Layer / File(s) | Summary |
|---|---|
Memory untrustworthiness classification and wrapping src/openhuman/agent/harness/memory_context_safety.rs, src/openhuman/agent/harness/mod.rs |
New classifier is_potentially_untrusted (namespace allowlist & connector-key heuristics) and wrap_untrusted_for_agent emitting <untrusted-source> wrappers; includes unit tests. |
Untrusted memory transformation in prompt building src/openhuman/agent/harness/memory_context.rs |
build_context integrates safety checks and wraps untrusted memory entries with wrap_untrusted_for_agent using a namespace-derived hint (fallback connector). |
Sequence Diagram(s)
sequenceDiagram
participant Browser
participant Frontend
participant CoreRPC
participant CoreService
participant SSE as SSE_/events
Browser->>Frontend: request socket / events URL
Frontend->>CoreRPC: resolveCoreSocketUrl()
Frontend->>CoreRPC: getCoreRpcToken()
Frontend->>CoreService: connectCoreSocket(auth: coreToken + authExtras.session)
Browser->>CoreRPC: core.events_subscribe_token(client_id, ttl_secs?)
CoreRPC->>CoreService: event_bind_tokens::issue(client_id, ttl)
CoreService-->>CoreRPC: { token, valid_until }
Browser->>SSE: GET /events?client_id=...&token=...
SSE->>CoreService: event_bind_tokens::consume(client_id, token)
CoreService-->>SSE: success/failure
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs
- tinyhumansai/openhuman#2114: Related updates to core RPC bearer-token authentication and
/eventstoken validation. - tinyhumansai/openhuman#1727: Overlaps changes to frontend socket connection lifecycle and usage of core socket helpers.
Suggested reviewers
- graycyrus
- senamakel
"🐰 Tokens fetched, origins checked with care,
threads split so each sender's story's there,
untrusted memory wrapped in careful light,
sockets handshake true before they bite.
Hop, sniff, and patch — all snug tonight."
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
| Check name | Status | Explanation |
|---|---|---|
| Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. |
| Title check | ✅ Passed | The title 'feat: tighten runtime policy + transport guards' accurately captures the main objective of the changeset: implementing stricter authentication, authorization, and validation across the Socket.IO transport layer, RPC endpoints, and memory safety systems. The title directly reflects the core theme across all commits (auth verification, origin validation, bind tokens, etc.). |
| Docstring Coverage | ✅ Passed | Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. |
| Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
Comment @coderabbitai help to get the list of available commands and usage tips.
@oxoxDev @graycyrus Thank for fixing this bug!
and one more question: could you please publish advisory https://github.com/tinyhumansai/openhuman/security/advisories/GHSA-h4g4-x264-prgx for security tracking?
Hi @oxoxDev @graycyrus , any update for my advisory reports? thank you!