Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion app/test/e2e/helpers/core-rpc-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ function coreHost(): string {

/** Ports to try when OPENHUMAN_CORE_PORT is unset.
*
* Keep this exactly aligned with connectivity::rpc's desktop fallback range.
* Keep this exactly aligned with openhuman-rpc's `server/listen_port.rs` desktop fallback range.
* A data reset restarts the embedded core; on Windows the preferred socket can
* remain unavailable briefly, so the replacement listener may bind as high as
* 7798. Stopping at 7793 makes every later RPC test wait out the full probe
Expand Down
7 changes: 4 additions & 3 deletions crates/openhuman-app/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions crates/openhuman-app/src/core_process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,12 +383,12 @@ impl CoreProcessHandle {
}
Ok(Err(err)) => {
if let Some(
openhuman_rpc::embed::PickListenPortError::WouldTakeOver {
openhuman_rpc::server::listen_port::PickListenPortError::WouldTakeOver {
preferred,
..
},
) =
err.downcast_ref::<openhuman_rpc::embed::PickListenPortError>()
err.downcast_ref::<openhuman_rpc::server::listen_port::PickListenPortError>()
{
if startup_attempt == 0 {
log::warn!(
Expand Down
2 changes: 0 additions & 2 deletions crates/openhuman-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -310,8 +310,6 @@ async-trait = "0.1"
# crates); declared directly so the keyring module can `use zeroize::Zeroizing`.
zeroize = "1"
hex = "0.4"
# The host-owned SaaS gateway signature uses HMAC with SHA-256.
hmac = "0.12"
tokio-util = { version = "0.7", features = ["rt", "io"] }
# tokio-tungstenite is declared per-target below so the TLS backend
# (native-tls on Windows, rustls on macOS / Linux) matches the reqwest
Expand Down
15 changes: 9 additions & 6 deletions crates/openhuman-core/src/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,11 +203,14 @@ the approval-gate session id. `verify_bearer_token` and `bearer_matches` do
the comparison.

Browser `EventSource` cannot send an `Authorization` header, so `/events`
uses separate bind tokens from [`event_bind_tokens.rs`](./event_bind_tokens.rs). An authenticated
caller invokes `core.events_subscribe_token { client_id }` and then opens
`/events?client_id=<id>&token=<bind>`. A bind token is 256 random bits, tied
to one `client_id`, consumed on first use, and expires after 60 seconds by
default (30 minutes at most). The store caps at 4096 live tokens.
uses separate bind tokens. An authenticated caller invokes
`core.events_subscribe_token { client_id }` and then opens
`/events?client_id=<id>&token=<bind>`. The store belongs to the server
(`openhuman-rpc`'s `server/http/events_bind_tokens.rs`), which installs its
minter through the [`event_bind_tokens.rs`](./event_bind_tokens.rs) hook when
it builds its router. A bind token is 256 random bits, tied to one
`client_id`, consumed on first use, and expires after 60 seconds by default
(30 minutes at most). The store caps at 4096 live tokens.

This is the RPC transport bearer only. User credentials (session JWT, API
key, offline local token) arrive through `auth.set_credential` in
Expand Down Expand Up @@ -315,7 +318,7 @@ Dispatch and auth:
| [`legacy_aliases.rs`](./legacy_aliases.rs) | `resolve_legacy`: retired method names to canonical ones; mirrors `LEGACY_METHOD_ALIASES` in [`app/src/services/rpcMethods.ts`](../../../../app/src/services/rpcMethods.ts). |
| `session_expiry.rs` | `is_session_expired_error`, `is_unconfirmed_unauthorized_error`, and `backend_status_means_session_expired` (the one status rule: only a session-credential 401 expires the session). |
| `auth.rs` | The per-process RPC bearer: init paths, `get_rpc_token`, `verify_bearer_token`, `bearer_matches`. |
| `event_bind_tokens.rs` | Single-shot bind tokens for the `/events` SSE stream (`issue`, `consume`). |
| `event_bind_tokens.rs` | The mint hook behind `core.events_subscribe_token` (`install_minter`); the token store is the RPC server's. |
| `server_launcher.rs` | `ServerLauncher` port that `run` / `serve` start a server through. |
| `http_server_status.rs` | `HTTP_SERVER_COMPILED_IN`, an ungated marker the desktop shell asserts so a core built without `http-server` fails the build. |

Expand Down
19 changes: 14 additions & 5 deletions crates/openhuman-core/src/core/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,11 @@ fn try_core_dispatch(
/// middleware as the rest of `/rpc`) and then opens
/// `/events?client_id=<id>&token=<bind>`. The `/events` handler removes
/// the token from the store on first use, so a leaked URL cannot be
/// replayed by a second subscriber.
fn handle_events_subscribe_token(params: serde_json::Value) -> Result<InvocationResult, String> {
/// replayed by a second subscriber. The store is the server's, reached
/// through the [`event_bind_tokens`](crate::core::event_bind_tokens) hook.
pub(crate) fn handle_events_subscribe_token(
params: serde_json::Value,
) -> Result<InvocationResult, String> {
let obj = params.as_object();
let client_id = obj
.and_then(|m| m.get("client_id"))
Expand All @@ -203,15 +206,21 @@ fn handle_events_subscribe_token(params: serde_json::Value) -> Result<Invocation
.and_then(|v| v.as_u64())
.map(std::time::Duration::from_secs);

let issued =
crate::core::event_bind_tokens::issue(client_id.to_string(), ttl).ok_or_else(|| {
use crate::core::event_bind_tokens::{mint, MintError};
let issued = mint(client_id.to_string(), ttl).map_err(|error| match error {
MintError::AtCapacity => {
log::warn!(
"[events-bind] reject mint: store at capacity (client_id_len={} ttl_secs={:?})",
client_id.len(),
ttl.map(|d| d.as_secs())
);
"events bind-token store at capacity; try again shortly".to_string()
})?;
}
MintError::NoServer => {
log::warn!("[events-bind] reject mint: no server installed a bind-token store");
"events bind tokens need the core's HTTP server, which is not running".to_string()
}
})?;

let ttl_remaining_secs = issued
.valid_until
Expand Down
156 changes: 31 additions & 125 deletions crates/openhuman-core/src/core/event_bind_tokens.rs
Original file line number Diff line number Diff line change
@@ -1,144 +1,50 @@
//! Per-subscription bind tokens for the SSE `/events` endpoint.
//! The mint hook behind `core.events_subscribe_token`.
//!
//! Browser `EventSource` clients cannot attach an `Authorization` header,
//! so the `/events` stream cannot ride on the same bearer-token middleware
//! that protects `POST /rpc`. Instead, an authenticated holder of the
//! per-process RPC bearer first calls
//! `core.events_subscribe_token { client_id }` to mint a short-lived,
//! single-purpose bind token, then opens
//! `/events?client_id=<id>&token=<bind>`.
//!
//! Properties of the bind token:
//! - 256 bits of CSPRNG randomness (hex-encoded; 64 chars on the wire).
//! - Bound to one `client_id` — verifying with any other id rejects.
//! - Single-shot by default: the connect-time validate step removes the
//! token from the store, so a leaked URL cannot be reused.
//! - Time-bounded: minted tokens carry a `valid_until` instant and a
//! small purge pass runs on each lookup to bound store size.
//!
//! This module owns only the in-memory store; the RPC handler that mints
//! tokens lives in `crates/openhuman-core/src/core/dispatch.rs` (the `core.*` namespace),
//! and the `/events` handler in `crates/openhuman-rpc/src/server/http/events.rs` consumes them.

use std::collections::HashMap;
use std::sync::RwLock;
//! Browser `EventSource` clients cannot attach an `Authorization` header, so
//! the SSE `/events` stream takes a single-shot bind token instead. The RPC
//! that mints one is a `core.*` method (see `dispatch.rs`), but the token
//! store belongs to the server that consumes the tokens: `openhuman-rpc`
//! installs its store's minter here when it builds its router. Without a
//! server there is no `/events` stream, and the RPC says so.

use std::sync::OnceLock;
use std::time::{Duration, Instant};

use once_cell::sync::Lazy;

/// Default lifetime of a freshly issued bind token if the caller does not
/// specify one. Long enough for normal subscribe latency, short enough that
/// an accidentally-logged URL stops working before useful exfil. The RPC
/// caller can shorten this with the `ttl_secs` field.
const DEFAULT_TTL: Duration = Duration::from_secs(60);

/// Upper bound the caller can request. Anything larger collapses to this so
/// a misbehaving (or compromised) caller cannot mint long-lived tokens.
const MAX_TTL: Duration = Duration::from_secs(60 * 30);

/// Maximum live tokens in the store. Each token is ~80 bytes plus the
/// `client_id` String; this is a defensive ceiling, not a normal-load cap.
/// When the store is full, the oldest expired entries are evicted; if none
/// are expired, a fresh issue request is rejected so the store cannot grow
/// without bound.
const MAX_TOKENS: usize = 4096;

#[derive(Debug, Clone)]
struct BindEntry {
client_id: String,
valid_until: Instant,
}

static STORE: Lazy<RwLock<HashMap<String, BindEntry>>> =
Lazy::new(|| RwLock::new(HashMap::with_capacity(64)));

/// A freshly-minted bind token plus its expiry. Returned to the RPC caller
/// so the UI can pass both to `/events?client_id=…&token=…`.
/// A freshly minted bind token plus its expiry, returned to the RPC caller
/// so the UI can pass it to `/events?client_id=…&token=…`.
#[derive(Debug, Clone)]
pub struct BindToken {
pub token: String,
pub valid_until: Instant,
}

/// Mint a new bind token tied to `client_id`.
///
/// `ttl_override` lets the caller request a shorter lifetime than the
/// default; anything above `MAX_TTL` is clamped down. Returns `None` if the
/// store is at capacity and no expired entries can be reclaimed — callers
/// should surface this as a transient error rather than retrying in a
/// tight loop.
pub fn issue(client_id: impl Into<String>, ttl_override: Option<Duration>) -> Option<BindToken> {
let ttl = ttl_override.map(|d| d.min(MAX_TTL)).unwrap_or(DEFAULT_TTL);
let client_id = client_id.into();
let valid_until = Instant::now() + ttl;
let token = generate_token();
let entry = BindEntry {
client_id,
valid_until,
};
/// Mints a bind token for a `client_id`, with an optional shorter lifetime.
/// `None` means the store is at capacity.
pub type BindTokenMinter = fn(String, Option<Duration>) -> Option<BindToken>;

let mut store = STORE.write().ok()?;
purge_expired_locked(&mut store);
if store.len() >= MAX_TOKENS {
log::warn!(
"[events-bind] capacity reached ({} entries) — refusing to mint",
store.len()
);
return None;
}
store.insert(token.clone(), entry);
Some(BindToken { token, valid_until })
}
static MINTER: OnceLock<BindTokenMinter> = OnceLock::new();

/// Validate a supplied `(client_id, token)` pair and remove the token from
/// the store on success.
///
/// Returns `true` only when the token exists, is not expired, and the
/// bound `client_id` matches what was supplied. The remove-on-success
/// behaviour is what gives the token its single-shot semantics — an
/// attacker who replays the URL after the legitimate UI has connected
/// gets nothing.
pub fn consume(client_id: &str, token: &str) -> bool {
let Ok(mut store) = STORE.write() else {
return false;
};
purge_expired_locked(&mut store);
// Peek before removing: a wrong `client_id` must NOT consume the token,
// or a single guessed-id request can DoS the legitimate subscriber by
// racing them to the consume.
let Some(entry) = store.get(token) else {
log::debug!("[events-bind] consume: token not found");
return false;
};
if entry.client_id != client_id {
log::warn!("[events-bind] consume: client_id mismatch (token bound to other id)");
return false;
/// Install the server's minter. The first one installed stays; installing
/// again is a no-op.
pub fn install_minter(minter: BindTokenMinter) {
if MINTER.set(minter).is_err() {
log::trace!("[events-bind] a minter is already installed");
}
let entry = store
.remove(token)
.expect("token was present in the binding check above");
log::debug!(
"[events-bind] consume: ok (client_id_len={} ttl_remaining_ms={})",
entry.client_id.len(),
entry
.valid_until
.checked_duration_since(Instant::now())
.unwrap_or_default()
.as_millis()
);
true
}

fn purge_expired_locked(store: &mut HashMap<String, BindEntry>) {
let now = Instant::now();
store.retain(|_, entry| entry.valid_until > now);
/// Why no bind token was minted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MintError {
/// No server installed a minter: there is no `/events` stream to bind.
NoServer,
/// The server's store is full.
AtCapacity,
}

fn generate_token() -> String {
use rand::RngExt as _;
let mut bytes = [0u8; 32];
rand::rng().fill(&mut bytes);
hex::encode(bytes)
/// Mint a bind token through the installed minter.
pub(crate) fn mint(client_id: String, ttl: Option<Duration>) -> Result<BindToken, MintError> {
let minter = MINTER.get().ok_or(MintError::NoServer)?;
minter(client_id, ttl).ok_or(MintError::AtCapacity)
}

#[cfg(test)]
Expand Down
Loading
Loading