Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(origin): handle missing origin header in request validation

Steven Enamakel2fbb3f4a24a3
diff --git a/crates/openhuman-rpc/src/origin.rs b/crates/openhuman-rpc/src/origin.rs
new file mode 100644
index 0000000000..f36defcea5
--- /dev/null
+++ b/crates/openhuman-rpc/src/origin.rs
@@ -0,0 +1,73 @@
+//! Which browser origins may call a core's HTTP API.
+//!
+//! The core's RPC server only ever serves three legitimate browser consumers:
+//! 1. The bundled Tauri v2 webview — `tauri://localhost` on macOS/Linux and
+//! `http(s)://tauri.localhost` on Windows.
+//! 2. The Vite dev server during `pnpm dev` — any port on loopback hosts.
+//! 3. Operator-controlled debug harnesses opted in via [`ALLOWED_ORIGINS_ENV`].
+//!
+//! Anything else (a random web page that has somehow obtained the bearer token
+//! via leaked logs / screenshots / a compromised third-party origin) must be
+//! refused — the bearer token alone is not enough authorization without an
+//! origin binding.
+//!
+//! This is the CORS rule for `/rpc` and the other HTTP routes. The core's
+//! Socket.IO handshake has its own URL-parsing check that accepts a slightly
+//! different set (any scheme on a loopback or `tauri.localhost` host); both
+//! read the same [`ALLOWED_ORIGINS_ENV`]. Converging the two is a behavior
+//! change and is left as follow-up.
+//!
+//! The function here is pure: the caller reads the environment and passes the
+//! extra allowlist in, which keeps this crate free of I/O and makes the rule
+//! testable without mutating process-global state.
+
+/// Environment variable for additional comma-separated origins to allow.
+/// Intended for debug harnesses and E2E setups that don't run on loopback —
+/// e.g. `OPENHUMAN_CORE_ALLOWED_ORIGINS=https://e2e.internal,http://my-debugger:8080`.
+pub const ALLOWED_ORIGINS_ENV: &str = "OPENHUMAN_CORE_ALLOWED_ORIGINS";
+
+/// Decides whether a browser `Origin` header value is allowed to make
+/// authenticated cross-origin requests against a core's HTTP API.
+///
+/// `extra_origins` is the raw value of [`ALLOWED_ORIGINS_ENV`], if set: a
+/// comma-separated list matched exactly, never by prefix or host.
+#[must_use]
+pub fn is_origin_allowed_with_extra(origin: &str, extra_origins: Option<&str>) -> bool {
+ // Tauri v2 webview origins. Windows uses an HTTP(S) custom host; macOS
+ // and Linux use the `tauri://` scheme. We accept both for portability.
+ if matches!(
+ origin,
+ "tauri://localhost" | "http://tauri.localhost" | "https://tauri.localhost"
+ ) {
+ return true;
+ }
+
+ // Loopback origins on any port (Vite dev server, E2E driver, CLI tools).
+ if let Some(rest) = origin.strip_prefix("http://") {
+ let authority = rest.split('/').next().unwrap_or("");
+ let host = if let Some(stripped) = authority.strip_prefix('[') {
+ // IPv6 literal: `[::1]:1420` → `::1`
+ stripped.split(']').next().unwrap_or("")
+ } else {
+ authority.split(':').next().unwrap_or("")
+ };
+ if matches!(host, "127.0.0.1" | "localhost" | "::1") {
+ return true;
+ }
+ }
+
+ // Env override: comma-separated exact matches.
+ if let Some(extra) = extra_origins {
+ for candidate in extra.split(',').map(str::trim).filter(|s| !s.is_empty()) {
+ if candidate == origin {
+ return true;
+ }
+ }
+ }
+
+ false
+}
+
+#[cfg(test)]
+#[path = "origin_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-rpc/src/origin_tests.rs b/crates/openhuman-rpc/src/origin_tests.rs
new file mode 100644
index 0000000000..70a6b5030e
--- /dev/null
+++ b/crates/openhuman-rpc/src/origin_tests.rs
@@ -0,0 +1,82 @@
+use super::*;
+
+#[test]
+fn allows_tauri_webview_origins() {
+ for origin in [
+ "tauri://localhost",
+ "http://tauri.localhost",
+ "https://tauri.localhost",
+ ] {
+ assert!(
+ is_origin_allowed_with_extra(origin, None),
+ "expected {origin} to be allowed"
+ );
+ }
+}
+
+#[test]
+fn allows_loopback_with_any_port() {
+ for origin in [
+ "http://127.0.0.1:1420",
+ "http://localhost:5173",
+ "http://[::1]:4444",
+ "http://localhost",
+ ] {
+ assert!(
+ is_origin_allowed_with_extra(origin, None),
+ "expected {origin} to be allowed"
+ );
+ }
+}
+
+#[test]
+fn rejects_disallowed_origins() {
+ for origin in [
+ "https://attacker.example",
+ "http://evil.localhost.attacker.example",
+ "https://127.0.0.1.attacker.example",
+ // HTTPS variant of localhost is NOT a configuration we ship — refuse.
+ "https://localhost",
+ "null",
+ "",
+ ] {
+ assert!(
+ !is_origin_allowed_with_extra(origin, None),
+ "expected {origin} to be rejected"
+ );
+ }
+}
+
+#[test]
+fn env_override_allows_extra_origins() {
+ let extra_origins = Some("https://debug.internal, http://harness:9000");
+
+ assert!(is_origin_allowed_with_extra(
+ "https://debug.internal",
+ extra_origins
+ ));
+ assert!(is_origin_allowed_with_extra(
+ "http://harness:9000",
+ extra_origins
+ ));
+ assert!(!is_origin_allowed_with_extra(
+ "https://debug.internal.attacker.example",
+ extra_origins
+ ));
+}
+
+#[test]
+fn env_override_does_not_allow_lookalike_suffixes() {
+ assert!(!is_origin_allowed_with_extra(
+ "https://debug.internal.attacker.example",
+ Some("https://debug.internal")
+ ));
+}
+
+#[test]
+fn env_override_ignores_empty_entries() {
+ assert!(!is_origin_allowed_with_extra(
+ "https://attacker.example",
+ Some(" , ,")
+ ));
+}
diff --git a/crates/openhuman-rpc/src/params_tests.rs b/crates/openhuman-rpc/src/params_tests.rs
new file mode 100644
index 0000000000..f46cf3bb42
--- /dev/null
+++ b/crates/openhuman-rpc/src/params_tests.rs
@@ -0,0 +1,124 @@
+use super::*;
+use serde_json::json;
+
+#[test]
+fn params_to_object_accepts_object() {
+ let map = params_to_object(json!({"a": 1, "b": "x"})).unwrap();
+ assert_eq!(map.len(), 2);
+ assert_eq!(map.get("a"), Some(&json!(1)));
+}
+
+#[test]
+fn params_to_object_accepts_null_as_empty_map() {
+ let map = params_to_object(json!(null)).unwrap();
+ assert!(map.is_empty());
+}
+
+#[test]
+fn params_to_object_rejects_array() {
+ let err = params_to_object(json!([1, 2, 3])).unwrap_err();
+ assert!(err.contains("invalid params"));
+ assert!(err.contains("array"));
+}
+
+#[test]
+fn params_to_object_rejects_scalars() {
+ assert!(params_to_object(json!(42)).unwrap_err().contains("number"));
+ assert!(params_to_object(json!("hi"))
+ .unwrap_err()
+ .contains("string"));
+ assert!(params_to_object(json!(true)).unwrap_err().contains("bool"));
+}
+
+#[test]
+fn json_type_name_labels_every_json_variant() {
+ assert_eq!(json_type_name(&json!(null)), "null");
+ assert_eq!(json_type_name(&json!(true)), "bool");
+ assert_eq!(json_type_name(&json!(3)), "number");
+ assert_eq!(json_type_name(&json!("s")), "string");
+ assert_eq!(json_type_name(&json!([])), "array");
+ assert_eq!(json_type_name(&json!({})), "object");
+}
+
+#[test]
+fn parse_json_params_roundtrips_object() {
+ let v = parse_json_params(r#"{"k":1}"#).unwrap();
+ assert_eq!(v, json!({"k": 1}));
+}
+
+#[test]
+fn parse_json_params_reports_error_message() {
+ let err = parse_json_params("{not json").unwrap_err();
+ assert!(err.contains("invalid JSON params"));
+}
+
+#[test]
+fn validation_messages_keep_their_wire_wording() {
+ assert_eq!(
+ unknown_param_message("api_key", "config", "update_model_settings"),
+ "unknown param 'api_key' for config.update_model_settings"
+ );
+ assert_eq!(
+ missing_required_param_message("session_id", "active session identifier"),
+ "missing required param 'session_id': active session identifier"
+ );
+ assert_eq!(
+ params_to_object(json!([])).unwrap_err(),
+ "invalid params: expected object or null, got array"
+ );
+}
+
+#[test]
+fn is_param_validation_error_matches_every_emitted_shape() {
+ // Driven from the emitters rather than literals, so the matcher and the
+ // messages cannot drift apart.
+ assert!(is_param_validation_error(&unknown_param_message(
+ "x", "ns", "fn"
+ )));
+ assert!(is_param_validation_error(&missing_required_param_message(
+ "x", "comment"
+ )));
+ assert!(is_param_validation_error(
+ &params_to_object(json!("s")).unwrap_err()
+ ));
+}
+
+#[test]
+fn is_param_validation_error_matches_the_three_validator_shapes() {
+ // Regression guard for OPENHUMAN-TAURI-20: pre-#1467 cores rejected
+ // `api_key` because it wasn't in the schema yet. The error string
+ // must keep matching here so it gets logged at info level and never
+ // reaches Sentry as an unactionable client/server skew event.
+ assert!(is_param_validation_error(
+ "unknown param 'api_key' for config.update_model_settings"
+ ));
+ // `all::validate_params` — missing required field.
+ assert!(is_param_validation_error(
+ "missing required param 'session_id': active session identifier"
+ ));
+ // `params_to_object` — params field is the wrong JSON shape.
+ assert!(is_param_validation_error(
+ "invalid params: expected object or null, got array"
+ ));
+}
+
+#[test]
+fn is_param_validation_error_does_not_match_unrelated_errors() {
+ // Handler-side / network / auth failures must still be reported.
+ assert!(!is_param_validation_error(
+ "backend returned 401 Unauthorized"
+ ));
+ assert!(!is_param_validation_error("network timeout"));
+ assert!(!is_param_validation_error(
+ "config.update_model_settings: store write failed"
+ ));
+ // Empty and substring-only matches don't qualify either.
+ assert!(!is_param_validation_error(""));
+ assert!(!is_param_validation_error(
+ "rpc failed: unknown param 'x' for ns.fn"
+ ));
+ // The JSON-string parse error is a CLI input error, not a params-shape one.
+ assert!(!is_param_validation_error(
+ &parse_json_params("{").unwrap_err()
+ ));
+}