The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(security): validate JWT audience claim in credential verification
Steven Enamakel53bae99c0ec0
diff --git a/crates/openhuman-core/src/backend/client.rs b/crates/openhuman-core/src/backend/client.rsindex 91514319f3..4c39477173 100644--- a/crates/openhuman-core/src/backend/client.rs+++ b/crates/openhuman-core/src/backend/client.rs@@ -1,7 +1,7 @@-//! HTTP client for TinyHumans / AlphaHuman API routes (`/auth/...`, etc.).+//! [`BackendClient`]: authenticated JSON calls to hosted-backend routes over+//! the [`BackendTransport`] port, and the typed errors they surface.use anyhow::{Context, Result};-use base64::Engine;use reqwest::{Client, Method, Url};use serde_json::{json, Value};@@ -297,40 +297,7 @@ fn parse_api_response_value(value: Value) -> Result<Value> {Ok(Value::Object(unwrapped))}-fn user_id_from_object(obj: &serde_json::Map<String, Value>) -> Option<String> {- for key in ["id", "_id", "userId"] {- if let Some(s) = obj.get(key).and_then(|x| x.as_str()) {- let t = s.trim();- if !t.is_empty() {- return Some(t.to_string());- }- }- }- None-}--/// Best-effort extraction of a user ID from an authenticated profile payload.-///-/// This function handles various envelope formats, including raw user objects-/// or those nested under `data` or `user` keys.-pub fn user_id_from_profile_payload(payload: &Value) -> Option<String> {- let obj = payload.as_object()?;- if let Some(data) = obj.get("data").and_then(|v| v.as_object()) {- return user_id_from_object(data).or_else(|| {- data.get("user")- .and_then(|u| u.as_object())- .and_then(user_id_from_object)- });- }-- user_id_from_object(obj).or_else(|| {- obj.get("user")- .and_then(|u| u.as_object())- .and_then(user_id_from_object)- })-}--/// A client for interacting with the TinyHumans / AlphaHuman backend API.+/// A client for authenticated hosted-backend routes.////// Owns the *routes* and the error classification; the HTTP round-trip itself/// rides the process [`BackendTransport`] (see [`crate::backend::transport`]),@@ -363,6 +330,26 @@ impl BackendClient {Ok(Self { base })}+ /// A client for the backend origin the installed transport resolves from+ /// `config.api_url` (see [`crate::backend::base_url`]).+ ///+ /// Without a transport this fails with+ /// [`BackendApiError::BackendUnavailable`], which+ /// [`flatten_authed_error`] turns into the `BACKEND_UNAVAILABLE:` sentinel.+ pub fn from_config(config: &crate::config::Config) -> Result<Self> {+ match crate::backend::base_url(&config.api_url) {+ Ok(base) => Self::new(&base),+ Err(BackendTransportError::Unavailable) => {+ log::debug!("[backend-api] no backend transport installed; client unavailable");+ Err(anyhow::Error::new(BackendApiError::BackendUnavailable {+ method: "ANY".to_string(),+ path: String::new(),+ }))+ }+ Err(other) => Err(anyhow::Error::new(other)),+ }+ }+/// The backend origin this client resolves routes against.pub fn base_url(&self) -> &str {self.base.as_str()@@ -948,92 +935,6 @@ impl BackendClient {}}-/// AES-256-GCM decrypt compatible with backend `encryptMessageFromString` (IV 16 + tag 16 + ciphertext, base64).-pub fn decrypt_handoff_blob(b64_ciphertext: &str, key_str: &str) -> Result<String> {- let key = key_bytes_from_string(key_str)?;- let combined = base64::engine::general_purpose::STANDARD- .decode(b64_ciphertext.trim())- .context("base64-decode encrypted payload")?;- if combined.len() < 32 {- anyhow::bail!("encrypted payload too short");- }- let iv = &combined[0..16];- let tag = &combined[16..32];- let ciphertext = &combined[32..];-- // aes-gcm expects ciphertext || tag- let mut ct_with_tag = Vec::with_capacity(ciphertext.len() + tag.len());- ct_with_tag.extend_from_slice(ciphertext);- ct_with_tag.extend_from_slice(tag);-- use aes_gcm::aead::generic_array::typenum::U16;- use aes_gcm::aead::{Aead, KeyInit};- use aes_gcm::aes::Aes256;- use aes_gcm::AesGcm;- type Aes256Gcm16 = AesGcm<Aes256, U16>;-- let cipher =- Aes256Gcm16::new_from_slice(&key).map_err(|e| anyhow::anyhow!("invalid AES key: {e}"))?;- let nonce = aes_gcm::aead::generic_array::GenericArray::from_slice(iv);- let plain = cipher- .decrypt(nonce, ct_with_tag.as_ref())- .map_err(|e| anyhow::anyhow!("AES-GCM decrypt failed: {e}"))?;-- String::from_utf8(plain).context("handoff plaintext is not UTF-8")-}--/// Decode the shared encryption key into 32 raw AES bytes.-///-/// Accepts, in order of preference:-/// 1. base64url without padding — the current backend format (e.g.-/// a 43-char alphanumeric string using `-` / `_`). This must be tried-/// BEFORE standard base64 because `-`/`_` are invalid in the standard-/// alphabet and would fail cleanly, whereas a standard-base64 string-/// never contains `-`/`_` so base64url_no_pad will still decode it-/// correctly as long as there's no padding.-/// 2. base64url with padding.-/// 3. Standard base64 with padding (legacy backend format).-/// 4. Standard base64 without padding.-/// 5. A raw 32-byte ASCII key (len == 32, used as-is).-///-/// NOTE: the key is only decoded locally for AES-GCM key material in-/// `decrypt_handoff_blob`. The key sent back to the backend (in the-/// `{ key: ... }` POST body of `fetch_integration_tokens_handoff`) is the-/// original string — never re-encoded — so base64url keys stay base64url-/// on the wire.-fn key_bytes_from_string(key: &str) -> Result<Vec<u8>> {- let trimmed = key.trim();-- // Raw 32-byte ASCII key- if trimmed.len() == 32 && !trimmed.contains(['+', '/', '-', '_', '=']) {- return Ok(trimmed.as_bytes().to_vec());- }-- use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};-- // `base64::Engine` has generic methods and therefore isn't- // dyn-compatible, so we unroll the attempts instead of looping over- // a slice of trait objects.- macro_rules! try_decode {- ($engine:expr) => {- if let Ok(decoded) = $engine.decode(trimmed) {- if decoded.len() == 32 {- return Ok(decoded);- }- }- };- }- try_decode!(URL_SAFE_NO_PAD);- try_decode!(URL_SAFE);- try_decode!(STANDARD);- try_decode!(STANDARD_NO_PAD);-- anyhow::bail!(- "encryption key must decode to 32 raw bytes (raw, base64, or base64url accepted; got len={})",- trimmed.len()- );-}-#[cfg(test)]#[path = "client_tests.rs"]-mod key_bytes_from_string_tests;+mod tests;diff --git a/crates/openhuman-core/src/security/credentials/jwt.rs b/crates/openhuman-core/src/security/credentials/jwt.rsindex 4cfcc1b874..19dc58cbd2 100644--- a/crates/openhuman-core/src/security/credentials/jwt.rs+++ b/crates/openhuman-core/src/security/credentials/jwt.rs@@ -77,6 +77,39 @@ pub fn decode_jwt_exp(token: &str) -> Option<DateTime<Utc>> {DateTime::<Utc>::from_timestamp(decode_jwt_exp_unix(token)?, 0)}+fn user_id_from_object(obj: &serde_json::Map<String, Value>) -> Option<String> {+ for key in ["id", "_id", "userId"] {+ if let Some(s) = obj.get(key).and_then(|x| x.as_str()) {+ let t = s.trim();+ if !t.is_empty() {+ return Some(t.to_string());+ }+ }+ }+ None+}++/// Best-effort extraction of a user ID from an authenticated profile payload.+///+/// This function handles various envelope formats, including raw user objects+/// or those nested under `data` or `user` keys.+pub fn user_id_from_profile_payload(payload: &Value) -> Option<String> {+ let obj = payload.as_object()?;+ if let Some(data) = obj.get("data").and_then(|v| v.as_object()) {+ return user_id_from_object(data).or_else(|| {+ data.get("user")+ .and_then(|u| u.as_object())+ .and_then(user_id_from_object)+ });+ }++ user_id_from_object(obj).or_else(|| {+ obj.get("user")+ .and_then(|u| u.as_object())+ .and_then(user_id_from_object)+ })+}+#[cfg(test)]#[path = "jwt_tests.rs"]mod tests;