openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

feat(core): pass in-process RPC bearer via internal handle, not process env

Open oxoxDev opened this issue 6 months ago • 3 comments

Summary

  • Stop publishing the in-process core's per-launch RPC bearer token as a process-global environment variable inside the Tauri shell.
  • Pass the bearer to the embedded server through an internal Option<Arc<String>> handoff instead.
  • Standalone CLI / Docker / cloud-deploy paths that use OPENHUMAN_CORE_TOKEN as configuration are unchanged.

Problem

Post-#1061 the core runs as an in-process tokio task inside the Tauri shell — it is not a child sidecar anymore. The Tauri shell, however, still hands the per-launch RPC bearer to the embedded core by setting OPENHUMAN_CORE_TOKEN as a process-global env var (a leftover from the sidecar era):

// app/src-tauri/src/core_process.rs (pre-change)
std::env::set_var("OPENHUMAN_CORE_TOKEN", self.rpc_token.as_str());

A process-global env var is the wrong transport for an in-process secret. The bearer is then visible to:

  • any other process running as the same UID on macOS (sysctl(KERN_PROCARGS2) / ps eww -p <pid> — no TCC prompt, no entitlement, no Accessibility / Full Disk Access requirement);
  • any other process running as the same UID on Linux without hidepid configured (/proc/<pid>/environ).

The bearer check itself is correct (constant-time, matches a per-launch hex secret). The problem is purely the transport.

docs/SECURITY_AUDIT.md lines 167 + 186 already track this as an open item ("Review OPENHUMAN_CORE_TOKEN lifetime and exposure scope").

Solution

  1. src/core/auth.rs — add a new in-memory init path:
    pub fn init_rpc_token_with_value(token: &str) -> anyhow::Result<()>
    
    Sets the RPC_TOKEN OnceLock directly. No env read, no file read. The existing init_rpc_token env+file fallback for the standalone CLI / Docker / cloud is untouched.
  2. src/core/jsonrpc.rs — extend run_server_embedded_with_ready + run_server_inner to accept Option<Arc<String>>. When the embedded entry is called from the Tauri shell, pass Some(rpc_token); the new helper seeds RPC_TOKEN before any reader runs. When None (standalone CLI / Docker / cloud), fall back to the existing init_rpc_token(workspace_dir) behavior.
  3. app/src-tauri/src/core_process.rs — delete the std::env::set_var call; pass the token in via the extended embedded-entry signature. The token already lives in CoreProcessHandle.rpc_token: Arc<String> and is reachable in-memory; no env crossing is needed.
  4. src/core/jsonrpc.rs approval-gate session_id reader (:1843-1857) — replace std::env::var("OPENHUMAN_CORE_TOKEN") with crate::core::auth::get_rpc_token(). Same value, sourced from the in-memory RPC_TOKEN post-init. Audit-grouping continuity preserved.
  5. scripts/test-webhook-flow.sh — replace the ps eww token-extraction branch with a read of the existing debug-only token file at ${TMPDIR:-/tmp}/openhuman-e2e-rpc-token (already written by core_process.rs under #[cfg(debug_assertions)], mode 0600). Release-build users continue to set the env var themselves, matching the script's existing precedence.
  6. docs/SECURITY_AUDIT.md lines 167 + 186 — mark the audit-item resolved.

Init ordering verified

The approval-gate auth::get_rpc_token() read at src/core/jsonrpc.rs:1843 runs inside bootstrap_core_runtime(...) which is awaited from run_server_inner after init_rpc_token_with_value(...) / init_rpc_token(...). Same-task ordering — no race. The bearer is always populated by the time the read happens.

Preserved unchanged (legitimate env-as-config surfaces)

  • init_rpc_token env + file fallback at src/core/auth.rs — standalone CLI / Docker / cloud (fly secrets set OPENHUMAN_CORE_TOKEN=...) keep working byte-identically.
  • Public-bind warning at src/core/jsonrpc.rs:1417 — operator-supplied config, kept reading env directly.
  • Pairing diagnostics at src/openhuman/security/pairing.rs:19, :290, :320-348 — operator-supplied config, kept reading env directly.
  • Scripts that intentionally rely on env-as-config (print-core-token.sh, docker-entrypoint-core.sh, test-proactive-welcome.sh, test-subconscious-ticks.sh).
  • Tests at src/core/jsonrpc_tests.rs:125, src/openhuman/inference/http/tests.rs:31, tests/inference_provider_e2e.rs:32 (these exercise the CLI / standalone path).
  • core_rpc_token Tauri command at app/src-tauri/src/lib.rs:89-93 — already pulls from state.inner().rpc_token(), not env, so no change required.

Submission Checklist

  • [x] cargo check --workspace clean
  • [x] cargo check --manifest-path app/src-tauri/Cargo.toml clean
  • [x] cargo fmt --all -- --check clean
  • [x] cargo clippy --workspace --no-deps — zero new warnings on changed lines
  • [x] cargo clippy --manifest-path app/src-tauri/Cargo.toml --no-deps — clean on core_process
  • [x] cargo test --manifest-path app/src-tauri/Cargo.toml --lib core_process — 27 / 27 pass (including new ensure_running_does_not_publish_token_to_env regression guard)
  • [x] cargo test --test json_rpc_e2e --no-run — compiles clean
  • [x] N/A: i18n strings — no UI surface touched
  • [x] N/A: frontend typecheck / lint / vitest — no TS surface touched
  • [x] Release notes — bumped docs/SECURITY_AUDIT.md (item 6 marked resolved)

Note: cargo test --lib core::auth cannot run end-to-end on main right now because src/openhuman/config/ops_tests.rs:631 fails E0063: missing fields ... AutonomySettingsPatch on a clean 87f8ef47 (pre-existing, unrelated to this PR). cargo check --tests --lib compiles my auth.rs tests cleanly. A trivial ..Default::default() fix unblocks the full matrix.

Impact

  • Security: removes the leak primitive that lets any same-UID process recover the local RPC bearer via ps eww / KERN_PROCARGS2 / /proc/<pid>/environ. The local RPC surface is the agent control plane, so this is a meaningful local-attack-surface reduction.
  • Compatibility: standalone CLI (openhuman-core serve), Docker (docker-entrypoint-core.sh), and cloud-deploy (fly secrets set ...) paths are unchanged. They keep using OPENHUMAN_CORE_TOKEN as configuration via the existing init_rpc_token env + file fallback.
  • Dev workflow: scripts/test-webhook-flow.sh now reads the per-launch token from the debug-only mode-0600 file the Tauri shell already writes under #[cfg(debug_assertions)], instead of grepping ps eww output. No behavior change for release-build users.
  • Manual macOS verification: after launch, ps eww -p $(pgrep -x OpenHuman) | grep OPENHUMAN_CORE_TOKEN returns no matches; core_rpc_token Tauri command still returns the live bearer; authenticated RPC calls still succeed.

Related

  • Sibling defense-in-depth hardening — wallet-side prepared-quote owner binding lands in #2708.
  • Resolves an internal audit item tracked in docs/SECURITY_AUDIT.md (lines 167 + 186).
  • Follow-up out of scope: the standalone CLI's ~/.openhuman/core.token 0600 file has a similar latent footprint but is operator-managed configuration and lives outside this PR's scope.

AI Authored PR Metadata

  • AI authored: yes — implementation produced by a Claude-driven worktree-dev agent following a plan derived via sequential-thinking MCP.
  • Human review: all seven commits manually reviewed; tests run locally.

Summary by CodeRabbit

  • Security Improvements

    • Bearer token is now passed in-memory instead of through environment variables, reducing exposure surface in the desktop environment.
  • Documentation

    • Updated authentication and deployment documentation to reflect the new in-memory token handling mechanism.

Review Change Stack

oxoxDev avatar May 26 '26 18:05 oxoxDev

📝 Walkthrough

Walkthrough

Move Tauri desktop RPC bearer handling from process-environment variables to an in-memory handoff: add a caller-seeded initializer, extend embedded server startup to accept an optional in-memory token, pass the token from the Tauri host in-memory, and update tests, scripts, and docs.

Changes

Desktop in-memory token handoff

Layer / File(s) Summary
Core in-memory token initializer
src/core/auth.rs
New init_rpc_token_with_value seeds the RPC bearer directly from caller-supplied strings with trimming/validation and idempotency. Tests verify empty-rejection and that re-initialization does not overwrite an already-seeded token.
JSON-RPC server embedded-core token parameter
src/core/jsonrpc.rs
run_server_embedded_with_ready and internal run_server_inner now accept rpc_token: Option<Arc<String>>; during bootstrap, prefer the provided token via init_rpc_token_with_value, falling back to env/file-based init. Approval-gate reads active bearer from auth subsystem instead of directly inspecting OPENHUMAN_CORE_TOKEN.
Tauri desktop token capture and in-memory passing
app/src-tauri/src/core_process.rs
Remove OPENHUMAN_CORE_TOKEN environment-variable setup from ensure_running; instead clone the internal token into token_for_core and pass it in-memory to run_server_embedded_with_ready(rpc_token: Some(_)). Updated doc comments explain the in-memory handoff mechanism.
Test: ensure_running does not set OPENHUMAN_CORE_TOKEN
app/src-tauri/src/core_process_tests.rs
New regression test verifies CoreProcessHandle::ensure_running() does not pollute the process environment with OPENHUMAN_CORE_TOKEN; samples env var before/after spawn with guard-based cleanup.
Configuration, scripts, and documentation updates
.env.example, scripts/test-webhook-flow.sh, AGENTS.md, CLAUDE.md, docs/SECURITY_AUDIT.md, src/openhuman/inference/http/tests.rs
.env.example clarifies the variable should be left blank on desktop. test-webhook-flow.sh now resolves the token from OPENHUMAN_CORE_TOKEN or the freshest of core.token and a debug e2e token file. Contributor docs updated to document in-memory handoff, token-file fallback for debugging, and mark prior env-exposure security concern resolved while noting env-as-config remains valid for non-desktop deployments.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • graycyrus
  • senamakel

"🐇
A token born fresh for every start,
Kept in memory, safe and smart,
The shell whispers it into the core,
No env to leak, no open door,
Hopping secrets kept secure."

🚥 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 clearly and specifically describes the main change: moving RPC bearer token passing from process environment to internal in-memory handle for in-process core execution.
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 26 '26 18:05 coderabbitai[bot]

@oxoxDev unresolved review feedback — please address before we review.

graycyrus avatar May 27 '26 19:05 graycyrus

@graycyrus — CodeRabbit's four inline items addressed in 040d4c4f..361638e3: docs split (SECURITY_AUDIT.md desktop vs CLI/docker/cloud transport), freshest-bearer resolution in test-webhook-flow.sh, rustdoc alignment in src/core/auth.rs (CORE_TOKEN_ENV_VAR + init_rpc_token), and in-memory bearer in the has_explicit_token public-bind check in src/core/jsonrpc.rs. Ready for re-review when you have a slot. (5 CI failures remain and are pre-existing main breakage being unblocked by PR #2710; they'll turn green once #2710 merges and I rebase.)

oxoxDev avatar May 28 '26 05:05 oxoxDev

@graycyrus quick status:

  • coderabbitai re-reviewed and approved at 2026-05-28T06:01Z after I pushed addresses for all four of its earlier inline notes (docs/SECURITY_AUDIT.md §3 split, scripts/test-webhook-flow.sh freshest-mtime resolution, src/core/auth.rs rustdoc consistency, and src/core/jsonrpc.rs has_explicit_token in-memory branch). Each is acknowledged via <review_comment_addressed> on the original threads.
  • CI's earlier failure was a RPC_TOKEN OnceLock race between the new init_rpc_token_with_value_seeds_and_is_idempotent test and the older test_chat_completions_with_bearer_not_rejected_as_auth_error (whichever ran first sealed the OnceLock and the other read a stale value). Just pushed da53de53 making ensure_test_rpc_auth token-agnostic — fix is test-only, no auth-subsystem behavior change.

Re-review when you have a moment 🙏

oxoxDev avatar May 28 '26 07:05 oxoxDev