openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

feat: tighten runtime policy + transport guards

Open oxoxDev opened this issue 6 months ago • 1 comments

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-form client_id query 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:

  1. refactor(core/auth): extract a reusable verify_bearer_token helper so non-HTTP transports can use the same comparison the Axum middleware uses internally. Pure refactor — no behaviour change, middleware delegates to the helper.
  2. feat(core/socketio): route the Socket.IO handshake through verify_bearer_token (auth.token payload on the client) plus an Origin allowlist (Tauri shell, localhost loopback, native clients without an Origin header). Adds an AuthedConnection marker on socket extensions so every executable event handler consults the same gate. Frontend (socketService, useDictationHotkey, OverlayApp) passes the per-process bearer via getCoreRpcToken().
  3. 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 issued client_id, single-shot on validate, and time-bounded. Bearer-header callers (CLI, Tauri shell) are still accepted to keep the existing flows green.
  4. feat(core/auth): the public Telegram OAuth-style callback gains a fetch-metadata gate. Sec-Fetch-Mode must be navigate, Sec-Fetch-Dest must be document, and cross-site redirects must originate from https://t.me/... or https://web.telegram.org/.... Older browsers without fetch-metadata headers stay supported via a Referer host fallback.
  5. fix(channels/bus): restore per-sender keying on the inbound bus path so it matches channels::context::conversation_history_key. DomainEvent::ChannelInboundMessage grows sender / reply_target / thread_ts (all Option<String> — legacy publishers compile unchanged), and a new derive_inbound_thread_id mirrors the canonical shape.
  6. 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 new memory_context_safety module. Conservative on purpose — defense-in-depth ahead of a follow-up typed Provenance enum on MemoryEntry.

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/A with 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 #NNN in the ## Related section

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 Provenance enum on MemoryEntry, populated at ingestion, to replace the conservative heuristic in commit 6.
    • Bot-side state parameter wiring for /auth/telegram so the callback can bind to a server-issued nonce in addition to the fetch-metadata gate.

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 after cargo fmt pass
  • [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.toml clean
  • [x] N/A: no src-tauri changes — Tauri fmt/check (if changed)

Validation Blocked

  • command: N/A
  • error: N/A
  • impact: N/A

Behavior Changes

  • Intended behavior change: Socket.IO handshake now reads auth.token and rejects non-allowlisted origins; SSE /events requires either a Bearer header or a minted bind token; Telegram callback validates fetch-metadata; inbound channel keying matches conversation_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 /events still accepted; /auth/telegram browsers without fetch-metadata headers still served via Referer fallback; inbound bus publishers without sender produce the historical channel-only key.
  • Guard/fallback/dispatch parity checks: Socket.IO AuthedConnection marker + 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.

Review Change Stack

oxoxDev avatar May 20 '26 10:05 oxoxDev

[!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_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to 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

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.

coderabbitai[bot] avatar May 20 '26 10:05 coderabbitai[bot]

@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?

sondt99 avatar Jun 07 '26 00:06 sondt99

Hi @oxoxDev @graycyrus , any update for my advisory reports? thank you!

sondt99 avatar Jun 09 '26 15:06 sondt99