Skip to content

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

fix(tinyhumans): handle backend channel disconnects gracefully

Steven Enamakel40afb77603f1
diff --git a/crates/openhuman-tinyhumans/src/client/backend_channel_tests.rs b/crates/openhuman-tinyhumans/src/client/backend_channel_tests.rs
new file mode 100644
index 0000000000..3489f3356a
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/client/backend_channel_tests.rs
@@ -0,0 +1,436 @@
+use super::*;
+
+#[tokio::test]
+async fn channel_routes_build_expected_requests_and_validate_inputs() {
+ type Requests = Arc<Mutex<Vec<(String, String, Value)>>>;
+ async fn capture(
+ State(seen): State<Requests>,
+ request: axum::http::Request<axum::body::Body>,
+ ) -> Json<Value> {
+ let method = request.method().to_string();
+ let path = request.uri().to_string();
+ let bytes = axum::body::to_bytes(request.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let body = if bytes.is_empty() {
+ Value::Null
+ } else {
+ serde_json::from_slice(&bytes).unwrap()
+ };
+ seen.lock().unwrap().push((method, path, body));
+ Json(json!({ "success": true, "data": { "ok": true } }))
+ }
+
+ let seen = Requests::default();
+ let app = Router::new().fallback(capture).with_state(seen.clone());
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+ let client = BackendClient::new(&format!("http://{addr}")).unwrap();
+
+ client
+ .send_channel_message(" /telegram/ ", "jwt", json!({ "text": "hello" }))
+ .await
+ .unwrap();
+ client
+ .send_channel_reaction("telegram", "jwt", json!({ "emoji": "πŸ‘" }))
+ .await
+ .unwrap();
+ client
+ .create_channel_thread("telegram", "jwt", " topic ")
+ .await
+ .unwrap();
+ client
+ .update_channel_thread("telegram", "jwt", "thread-1", "close")
+ .await
+ .unwrap();
+ client
+ .list_channel_threads("telegram", "jwt", Some(true))
+ .await
+ .unwrap();
+ client
+ .list_channel_threads("telegram", "jwt", Some(false))
+ .await
+ .unwrap();
+ client
+ .list_channel_threads("telegram", "jwt", None)
+ .await
+ .unwrap();
+
+ let requests = seen.lock().unwrap().clone();
+ assert_eq!(
+ requests[0],
+ (
+ "POST".into(),
+ "/channels/telegram/messages".into(),
+ json!({ "text": "hello" })
+ )
+ );
+ assert_eq!(
+ requests[1],
+ (
+ "POST".into(),
+ "/channels/telegram/reactions".into(),
+ json!({ "emoji": "πŸ‘" })
+ )
+ );
+ assert_eq!(
+ requests[2],
+ (
+ "POST".into(),
+ "/channels/telegram/threads".into(),
+ json!({ "title": "topic" })
+ )
+ );
+ assert_eq!(
+ requests[3],
+ (
+ "PATCH".into(),
+ "/channels/telegram/threads/thread-1".into(),
+ json!({ "action": "close" })
+ )
+ );
+ assert_eq!(requests[4].1, "/channels/telegram/threads?active=true");
+ assert_eq!(requests[5].1, "/channels/telegram/threads?active=false");
+ assert_eq!(requests[6].1, "/channels/telegram/threads");
+ drop(requests);
+
+ assert!(client
+ .send_channel_message(" / ", "jwt", json!({}))
+ .await
+ .is_err());
+ assert!(client
+ .send_channel_reaction(" ", "jwt", json!({}))
+ .await
+ .is_err());
+ assert!(client
+ .create_channel_thread("telegram", "jwt", " ")
+ .await
+ .is_err());
+ assert!(client
+ .update_channel_thread("telegram", "jwt", " ", "close")
+ .await
+ .is_err());
+ assert!(client
+ .update_channel_thread("telegram", "jwt", "thread-1", "delete")
+ .await
+ .is_err());
+ assert!(client.list_channel_threads("", "jwt", None).await.is_err());
+}
+
+#[tokio::test]
+async fn authed_json_reports_non_channel_404_still_propagates() {
+ // TAURI-RUST-8C: a GET 404 on a non-channel path (e.g. `/teams/me/usage`)
+ // falls through to `report_error` (not a typed/suppressed state) β€” it must
+ // still return an Err (no suppression) and not a typed `HostedApiError`.
+ let app = Router::new().route(
+ "/teams/me/usage",
+ get(|| async {
+ (
+ axum::http::StatusCode::NOT_FOUND,
+ r#"{"message":"Not Found"}"#,
+ )
+ }),
+ );
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+
+ let base_url = format!("http://{addr}");
+ let client = BackendClient::new(&base_url).unwrap();
+
+ let err = client
+ .authed_json("mock-jwt", Method::GET, "/teams/me/usage", None)
+ .await
+ .unwrap_err();
+ assert!(err.downcast_ref::<HostedApiError>().is_none());
+ let msg = format!("{err:#}");
+ assert!(msg.contains("404"), "error should carry the status: {msg}");
+ assert!(
+ msg.contains("/teams/me/usage"),
+ "error should carry the path: {msg}"
+ );
+}
+
+#[test]
+fn flatten_authed_error_maps_unauthorized_to_session_expired_sentinel() {
+ // #3297: the typed `Unauthorized` (expected session-lapse 401) must flatten
+ // onto a string that the JSON-RPC session-expiry classifiers recognise, so
+ // it is suppressed from Sentry (TAURI-RUST-8WY / 8WZ) instead of leaking.
+ let err = anyhow::Error::new(HostedApiError::Unauthorized {
+ method: "GET".to_string(),
+ path: "/teams/me/usage".to_string(),
+ });
+ let flat = flatten_authed_error(err);
+
+ // Carries the SESSION_EXPIRED sentinel + preserves method/path for logs.
+ assert!(
+ flat.contains("SESSION_EXPIRED"),
+ "expected sentinel, got: {flat}"
+ );
+ assert!(flat.contains("GET"), "method preserved: {flat}");
+ assert!(flat.contains("/teams/me/usage"), "path preserved: {flat}");
+
+ // Contract cross-check: the flattened string MUST classify as session
+ // expiry. This couples the mapping to the actual classifier β€” if either the
+ // sentinel or the classifier drifts, this fails instead of silently leaking.
+ assert!(
+ openhuman_embed::__host::core::observability::is_session_expired_message(&flat),
+ "flattened Unauthorized must classify as session expiry: {flat}"
+ );
+}
+
+#[test]
+fn flatten_authed_error_preserves_non_unauthorized_chain() {
+ // A non-Unauthorized failure (e.g. a transient network/timeout error) keeps
+ // its full `{e:#}` anyhow chain and must NOT be demoted to session expiry β€”
+ // genuine failures still reach Sentry.
+ let err = anyhow::anyhow!("connect timeout").context("backend request GET /teams/me/usage");
+ let flat = flatten_authed_error(err);
+
+ assert!(!flat.contains("SESSION_EXPIRED"), "must not map: {flat}");
+ assert!(flat.contains("connect timeout"), "cause preserved: {flat}");
+ assert!(
+ !openhuman_embed::__host::core::observability::is_session_expired_message(&flat),
+ "non-auth error must NOT classify as session expiry: {flat}"
+ );
+}
+
+#[test]
+fn flatten_authed_error_does_not_swallow_message_not_found() {
+ // `MessageNotFound` is a different expected state handled by its own callers
+ // (channel streaming/delete paths downcast it); it must not be collapsed
+ // into the session-expiry sentinel here.
+ let err = anyhow::Error::new(HostedApiError::MessageNotFound {
+ provider: "telegram".to_string(),
+ message_id: "1103".to_string(),
+ });
+ let flat = flatten_authed_error(err);
+
+ assert!(!flat.contains("SESSION_EXPIRED"), "must not map: {flat}");
+ assert!(
+ flat.contains("message not found"),
+ "display preserved: {flat}"
+ );
+}
+
+#[tokio::test]
+async fn authed_json_403_is_not_demoted_to_unauthorized() {
+ // 403 (Forbidden) is a genuine authorization/permission problem β€” the
+ // token authenticated but lacked scope. That IS a code/config bug we
+ // want to keep in Sentry; only 401 (token rejected as a whole) maps
+ // to the expected-state `Unauthorized` variant.
+ let app = Router::new().route(
+ "/openai/v1/audio/speech",
+ post(|| async { (axum::http::StatusCode::FORBIDDEN, "Forbidden") }),
+ );
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+
+ let base_url = format!("http://{addr}");
+ let client = BackendClient::new(&base_url).unwrap();
+
+ let err = client
+ .authed_json("mock-jwt", Method::POST, "/openai/v1/audio/speech", None)
+ .await
+ .unwrap_err();
+ assert!(
+ err.downcast_ref::<HostedApiError>().is_none(),
+ "403 must not be classified as Unauthorized"
+ );
+}
+
+#[tokio::test]
+async fn authed_json_404_outside_messages_path_still_reports() {
+ // 404 on a non-`/channels/<provider>/messages/<id>` path should NOT be
+ // demoted to MessageNotFound β€” it's a real backend bug or routing
+ // mistake and must keep its Sentry signal.
+ let app = Router::new().route(
+ "/auth/profile",
+ get(|| async { (axum::http::StatusCode::NOT_FOUND, "Not Found") }),
+ );
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+
+ let base_url = format!("http://{addr}");
+ let client = BackendClient::new(&base_url).unwrap();
+
+ let err = client
+ .authed_json("mock-jwt", Method::GET, "/auth/profile", None)
+ .await
+ .unwrap_err();
+ assert!(
+ err.downcast_ref::<HostedApiError>().is_none(),
+ "non-channel-message 404 must not be classified as MessageNotFound"
+ );
+}
+
+#[tokio::test]
+async fn sdk_backed_channel_typing_surfaces_unauthorized_on_401() {
+ let app = Router::new().route(
+ "/channels/telegram/typing",
+ post(|| async { (axum::http::StatusCode::UNAUTHORIZED, "Unauthorized") }),
+ );
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+
+ let client = BackendClient::new(&format!("http://{addr}")).unwrap();
+ let err = client
+ .send_channel_typing("telegram", "mock-jwt")
+ .await
+ .unwrap_err();
+
+ let typed = err.downcast_ref::<HostedApiError>().unwrap();
+ let HostedApiError::Unauthorized { method, path } = typed else {
+ panic!("expected Unauthorized, got {typed:?}");
+ };
+ assert_eq!(method, "POST");
+ assert_eq!(path, "/channels/telegram/typing");
+ // The session-expiry sentinel must still be derivable, so the dispatcher
+ // keeps routing this to re-sign-in rather than to Sentry.
+ assert!(flatten_authed_error(err).starts_with("SESSION_EXPIRED:"));
+}
+
+// ── typed channel-message 404s from the transport ───────────────────────────
+//
+// The transport owns what a channel-message 404 means on the backend; these
+// pin the recovery the client attaches to each variant.
+
+use openhuman_embed::__host::backend::transport::{
+ BackendTransport, BackendTransportError, TransportProfile,
+};
+use openhuman_embed::{BackendRequest, BaseUrlPurpose};
+
+/// A transport that answers every request with the error `make` builds.
+struct FailingTransport(fn() -> BackendTransportError);
+
+#[async_trait::async_trait]
+impl BackendTransport for FailingTransport {
+ async fn send_json(&self, _req: BackendRequest<'_>) -> Result<Value, BackendTransportError> {
+ Err((self.0)())
+ }
+
+ async fn send_multipart(
+ &self,
+ _req: BackendRequest<'_>,
+ _form: reqwest::multipart::Form,
+ ) -> Result<Value, BackendTransportError> {
+ Err((self.0)())
+ }
+
+ fn http_client(&self, _profile: TransportProfile) -> reqwest::Client {
+ reqwest::Client::new()
+ }
+
+ fn base_url(&self, configured: Option<&str>, _purpose: BaseUrlPurpose) -> String {
+ configured.unwrap_or("http://127.0.0.1:9").to_string()
+ }
+
+ fn product_identity(&self) -> String {
+ "test".to_string()
+ }
+
+ fn attribution_headers(&self) -> reqwest::header::HeaderMap {
+ reqwest::header::HeaderMap::new()
+ }
+
+ fn name(&self) -> &'static str {
+ "failing-test-transport"
+ }
+}
+
+fn failing_client(make: fn() -> BackendTransportError) -> BackendClient {
+ BackendClient::new("http://127.0.0.1:9")
+ .unwrap()
+ .with_transport(Arc::new(FailingTransport(make)))
+}
+
+#[tokio::test]
+async fn route_missing_becomes_channel_edit_unsupported() {
+ let client = failing_client(|| BackendTransportError::ChannelMessageRouteMissing {
+ provider: "telegram".into(),
+ message_id: "1103".into(),
+ });
+ let err = client
+ .send_channel_edit("telegram", "1103", "mock-jwt", serde_json::json!({}))
+ .await
+ .unwrap_err();
+ let typed = err.downcast_ref::<HostedApiError>().unwrap();
+ let HostedApiError::ChannelEditUnsupported {
+ provider,
+ message_id,
+ } = typed
+ else {
+ panic!("expected ChannelEditUnsupported, got {typed:?}");
+ };
+ assert_eq!(
+ (provider.as_str(), message_id.as_str()),
+ ("telegram", "1103")
+ );
+}
+
+#[tokio::test]
+async fn message_not_found_becomes_message_not_found() {
+ let client = failing_client(|| BackendTransportError::ChannelMessageNotFound {
+ provider: "discord".into(),
+ message_id: "abc".into(),
+ });
+ let err = client
+ .send_channel_delete("discord", "abc", "mock-jwt")
+ .await
+ .unwrap_err();
+ let typed = err.downcast_ref::<HostedApiError>().unwrap();
+ let HostedApiError::MessageNotFound {
+ provider,
+ message_id,
+ } = typed
+ else {
+ panic!("expected MessageNotFound, got {typed:?}");
+ };
+ assert_eq!((provider.as_str(), message_id.as_str()), ("discord", "abc"));
+ // A missing message is an expected state: it keeps its own chain rather
+ // than turning into a session-expiry sentinel.
+ assert!(!flatten_authed_error(err).starts_with("SESSION_EXPIRED:"));
+}
+
+#[tokio::test]
+async fn unavailable_transport_flattens_to_the_backend_unavailable_sentinel() {
+ let client = failing_client(|| BackendTransportError::Unavailable);
+ let err = client
+ .authed_json("mock-jwt", Method::GET, "/teams/me/usage", None)
+ .await
+ .unwrap_err();
+ let typed = err.downcast_ref::<HostedApiError>().unwrap();
+ assert!(matches!(typed, HostedApiError::BackendUnavailable { .. }));
+ let flat = flatten_authed_error(err);
+ assert!(
+ flat.starts_with(
+ openhuman_embed::__host::core::observability::BACKEND_UNAVAILABLE_PREFIX
+ ),
+ "{flat}"
+ );
+ assert!(flat.contains("GET /teams/me/usage"), "{flat}");
+}
+
+#[test]
+fn api_key_rejected_flattens_to_its_own_prefix_not_session_expired() {
+ let flat = flatten_authed_error(anyhow::Error::new(HostedApiError::ApiKeyRejected {
+ method: "GET".into(),
+ path: "/x".into(),
+ }));
+ assert!(flat.starts_with(openhuman_embed::__host::core::observability::API_KEY_REJECTED_PREFIX));
+ assert!(!flat.contains("SESSION_EXPIRED"));
+}
diff --git a/crates/openhuman-tinyhumans/src/client/backend_client.rs b/crates/openhuman-tinyhumans/src/client/backend_client.rs
index d76ef1f01b..9a3787d421 100644
--- a/crates/openhuman-tinyhumans/src/client/backend_client.rs
+++ b/crates/openhuman-tinyhumans/src/client/backend_client.rs
@@ -170,7 +170,3 @@ impl BackendClient {
#[cfg(test)]
#[path = "backend_client_tests.rs"]
mod tests;
-
-#[cfg(test)]
-#[path = "backend_channel_tests.rs"]
-mod channel_tests;
diff --git a/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs b/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs
new file mode 100644
index 0000000000..063e135dbe
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs
@@ -0,0 +1,363 @@
+use super::*;
+use crate::client::classify::{backend_api_body_shape, BACKEND_API_BODY_SHAPE_MAX_BYTES};
+use crate::client::{flatten_authed_error, HostedApiError};
+use axum::extract::State;
+use axum::http::HeaderMap;
+use axum::routing::{get, post};
+use axum::{Json, Router};
+use reqwest::Method;
+use serde_json::{json, Value};
+use std::sync::{Arc, Mutex};
+use tokio::net::TcpListener;
+
+/// The attribution header the transport stamps on every request.
+const PRODUCT_IDENTITY_HEADER: &str = "x-sdk-name";
+
+#[tokio::test]
+async fn authed_json_rejects_api_key_for_foreign_or_plaintext_endpoint() {
+ use openhuman_embed::__host::security::credentials::session_support::BackendCredential;
+
+ for endpoint in ["https://example.com", "http://example.com"] {
+ let client = BackendClient::new(endpoint).unwrap();
+ let error = client
+ .authed_json(
+ BackendCredential::ApiKey("th_test_key".to_string()),
+ Method::GET,
+ "/probe",
+ None,
+ )
+ .await
+ .unwrap_err();
+ assert!(error.to_string().contains("TinyHumans API key requires"));
+ }
+}
+
+#[derive(Clone, Default)]
+struct CapturedHeaders {
+ entries: Arc<Mutex<Vec<HeaderMap>>>,
+}
+
+impl CapturedHeaders {
+ fn push(&self, headers: &HeaderMap) {
+ self.entries.lock().unwrap().push(headers.clone());
+ }
+
+ fn take(&self) -> Vec<HeaderMap> {
+ self.entries.lock().unwrap().clone()
+ }
+}
+
+async fn spawn_header_capture_server() -> (String, CapturedHeaders) {
+ async fn capture_me(
+ State(captured): State<CapturedHeaders>,
+ headers: HeaderMap,
+ ) -> Json<Value> {
+ captured.push(&headers);
+ Json(json!({
+ "success": true,
+ "data": { "_id": "user-123" }
+ }))
+ }
+
+ async fn capture_probe(
+ State(captured): State<CapturedHeaders>,
+ headers: HeaderMap,
+ ) -> Json<Value> {
+ captured.push(&headers);
+ Json(json!({ "ok": true }))
+ }
+
+ let captured = CapturedHeaders::default();
+ let app = Router::new()
+ .route("/auth/me", get(capture_me))
+ .route("/probe", get(capture_probe))
+ .with_state(captured.clone());
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+
+ (format!("http://{addr}"), captured)
+}
+
+#[tokio::test]
+async fn authed_json_sends_an_api_key_as_x_api_key_and_no_bearer() {
+ // Library mode: the TinyHumans API key rides the SDK REST routes as
+ // `x-api-key`, never as `Authorization: Bearer` (that header is the
+ // managed-inference shape, handled by `OpenHumanBackendModel`).
+ use openhuman_embed::__host::security::credentials::session_support::BackendCredential;
+
+ let (base_url, captured) = spawn_header_capture_server().await;
+ let client = BackendClient::new(&base_url).unwrap();
+
+ let response = client
+ .authed_json(
+ &BackendCredential::ApiKey("th_test_key".to_string()),
+ Method::GET,
+ "/probe",
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(response, json!({ "ok": true }));
+
+ let headers = captured.take();
+ let request_headers = headers.last().unwrap();
+ assert_eq!(
+ request_headers
+ .get("x-api-key")
+ .and_then(|value| value.to_str().ok()),
+ Some("th_test_key")
+ );
+ assert!(
+ request_headers.get("authorization").is_none(),
+ "an API key must not also be sent as a bearer"
+ );
+ assert!(request_headers.get(PRODUCT_IDENTITY_HEADER).is_some());
+}
+
+#[tokio::test]
+async fn authed_json_sends_a_session_credential_as_a_bearer_only() {
+ use openhuman_embed::__host::security::credentials::session_support::BackendCredential;
+
+ let (base_url, captured) = spawn_header_capture_server().await;
+ let client = BackendClient::new(&base_url).unwrap();
+
+ client
+ .authed_json(
+ &BackendCredential::Session("jwt-token".to_string()),
+ Method::GET,
+ "/probe",
+ None,
+ )
+ .await
+ .unwrap();
+
+ let headers = captured.take();
+ let request_headers = headers.last().unwrap();
+ assert_eq!(
+ request_headers
+ .get("authorization")
+ .and_then(|value| value.to_str().ok()),
+ Some("Bearer jwt-token")
+ );
+ assert!(request_headers.get("x-api-key").is_none());
+}
+
+// Regression: OPENHUMAN-TAURI-8K / Sentry issue 7473650958.
+// When config.api_url is a full LLM completions URL (e.g. /v1/chat/completions),
+// Url::join used to produce wrong paths like /v1/chat/teams/me/usage instead of
+// /teams/me/usage β€” BackendClient::new must strip the path to prevent this.
+#[test]
+fn new_strips_path_from_completions_url() {
+ for base in [
+ "https://api.tinyhumans.ai/v1/chat/completions",
+ "https://api.openai.com/v1/chat/completions",
+ "https://api.tinyhumans.ai",
+ "https://api.tinyhumans.ai/",
+ ] {
+ let client = BackendClient::new(base).unwrap();
+ let url = client.url_for("/teams/me/usage").unwrap();
+ assert_eq!(url.path(), "/teams/me/usage", "{base}");
+ }
+}
+
+#[tokio::test]
+async fn authed_json_surfaces_unauthorized_on_401() {
+ // OPENHUMAN-TAURI-4K8: 401 on any authed backend endpoint must surface a
+ // typed `HostedApiError::Unauthorized` and NOT funnel into `report_error`.
+ // The mascot TTS path (`/openai/v1/audio/speech`) was the loudest reporter,
+ // but the same shape fires on every authed endpoint once a session lapses,
+ // so we cover two different paths/methods to prove the suppression is
+ // status-driven, not path-keyed.
+ let app = Router::new()
+ .route(
+ "/openai/v1/audio/speech",
+ post(|| async { (axum::http::StatusCode::UNAUTHORIZED, "Unauthorized") }),
+ )
+ .route(
+ "/referral/stats",
+ get(|| async { (axum::http::StatusCode::UNAUTHORIZED, "Unauthorized") }),
+ );
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+
+ let base_url = format!("http://{addr}");
+ let client = BackendClient::new(&base_url).unwrap();
+
+ // Mascot TTS path β€” the original reporter.
+ let err = client
+ .authed_json(
+ "mock-jwt",
+ Method::POST,
+ "/openai/v1/audio/speech",
+ Some(json!({ "text": "hello" })),
+ )
+ .await
+ .unwrap_err();
+ let typed = err.downcast_ref::<HostedApiError>().unwrap();
+ let HostedApiError::Unauthorized { method, path } = typed else {
+ panic!("expected Unauthorized, got {typed:?}");
+ };
+ assert_eq!(method, "POST");
+ assert_eq!(path, "/openai/v1/audio/speech");
+
+ // Generic GET on a non-TTS path β€” proves the suppression is per-status,
+ // not per-path. (Same root cause: expired/revoked backend session.)
+ let err = client
+ .authed_json("mock-jwt", Method::GET, "/referral/stats", None)
+ .await
+ .unwrap_err();
+ let typed = err.downcast_ref::<HostedApiError>().unwrap();
+ let HostedApiError::Unauthorized { method, path } = typed else {
+ panic!("expected Unauthorized, got {typed:?}");
+ };
+ assert_eq!(method, "GET");
+ assert_eq!(path, "/referral/stats");
+}
+
+/// Regression: a 401 for an API-key-authenticated request must classify as
+/// `HostedApiError::ApiKeyRejected`, not `Unauthorized`. `Unauthorized` is
+/// what `flatten_authed_error` maps onto the `SESSION_EXPIRED` sentinel, and
+/// `core/jsonrpc.rs`'s `is_session_expired_error` treats that sentinel as
+/// "clear the app session and sign out" β€” the wrong recovery for a
+/// library-mode runtime that authenticates with an API key and has no
+/// session at all.
+#[tokio::test]
+async fn authed_json_surfaces_api_key_rejected_not_unauthorized_on_401() {
+ use openhuman_embed::__host::security::credentials::session_support::BackendCredential;
+
+ let app = Router::new().route(
+ "/teams/me/usage",
+ get(|| async { (axum::http::StatusCode::UNAUTHORIZED, "Unauthorized") }),
+ );
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+
+ let base_url = format!("http://{addr}");
+ let client = BackendClient::new(&base_url).unwrap();
+
+ let err = client
+ .authed_json(
+ BackendCredential::ApiKey("th_test_key".to_string()),
+ Method::GET,
+ "/teams/me/usage",
+ None,
+ )
+ .await
+ .unwrap_err();
+ let typed = err.downcast_ref::<HostedApiError>().unwrap();
+ let HostedApiError::ApiKeyRejected { method, path } = typed else {
+ panic!("expected ApiKeyRejected for an api-key credential, got {typed:?}");
+ };
+ assert_eq!(method, "GET");
+ assert_eq!(path, "/teams/me/usage");
+
+ // The flattened message must NOT carry the `SESSION_EXPIRED` sentinel β€”
+ // that would make `core/jsonrpc.rs::is_session_expired_error` clear an
+ // app session that was never the problem.
+ let flattened = flatten_authed_error(err);
+ assert!(
+ !flattened.contains("SESSION_EXPIRED"),
+ "an api-key 401 must not trigger session-expiry recovery: {flattened}"
+ );
+ assert!(flattened.contains("API_KEY_REJECTED"), "{flattened}");
+
+ // A session credential on the same endpoint still classifies as the
+ // original `Unauthorized` / `SESSION_EXPIRED` path β€” this fix must not
+ // regress the existing session-expiry recovery.
+ let err = client
+ .authed_json(
+ BackendCredential::Session("mock-jwt".to_string()),
+ Method::GET,
+ "/teams/me/usage",
+ None,
+ )
+ .await
+ .unwrap_err();
+ let typed = err.downcast_ref::<HostedApiError>().unwrap();
+ assert!(
+ matches!(typed, HostedApiError::Unauthorized { .. }),
+ "expected Unauthorized for a session credential, got {typed:?}"
+ );
+ assert!(flatten_authed_error(err).contains("SESSION_EXPIRED"));
+}
+
+#[test]
+fn backend_api_body_shape_emits_safe_keys_not_values() {
+ // PII guard (Codex P1 on #4058): the body SHAPE must expose only schema-like
+ // top-level key NAMES and NEVER the values β€” a non-2xx body can carry emails /
+ // tokens / profile JSON that would otherwise leak to unscrubbed daily logs.
+ let body = r#"{"error":"not found","email":"[email protected]","token":"sk-secret"}"#;
+ let shape = backend_api_body_shape(body);
+ assert_eq!(shape, "object(keys=3,safe=[email,error,token],redacted=0)");
+ assert!(!shape.contains("[email protected]"), "value leaked: {shape}");
+ assert!(!shape.contains("sk-secret"), "value leaked: {shape}");
+ assert!(!shape.contains("not found"), "value leaked: {shape}");
+}
+
+#[test]
+fn backend_api_body_shape_redacts_pii_and_nonidentifier_keys() {
+ // CodeRabbit Major on #4058: key NAMES are response-controlled too. A foreign
+ // backend can put an email / free text / unicode in the KEY position; those
+ // must be counted as `redacted`, never echoed.
+ let body = r#"{"[email protected]":1,"a b":2,"naΓ―ve":3,"error":4}"#;
+ let shape = backend_api_body_shape(body);
+ // Only the schema-like `error` survives; the other three are redacted.
+ assert_eq!(shape, "object(keys=4,safe=[error],redacted=3)");
+ assert!(!shape.contains("[email protected]"), "PII key leaked: {shape}");
+ assert!(!shape.contains("naΓ―ve"), "non-ascii key leaked: {shape}");
+ assert!(!shape.contains("a b"), "free-text key leaked: {shape}");
+}
+
+#[test]
+fn backend_api_body_shape_classifies_non_object_bodies() {
+ assert_eq!(backend_api_body_shape(""), "empty");
+ assert_eq!(backend_api_body_shape(" "), "empty");
+ assert_eq!(
+ backend_api_body_shape("Cannot GET /teams/me/usage"),
+ "non_json"
+ );
+ assert_eq!(backend_api_body_shape("<html>404</html>"), "non_json");
+ assert_eq!(backend_api_body_shape("[1,2,3]"), "array");
+ assert_eq!(backend_api_body_shape("42"), "scalar");
+}
+
+#[test]
+fn backend_api_body_shape_bounds_long_safe_key_list() {
+ // The `safe=[…]` list is truncated at BACKEND_API_BODY_SHAPE_MAX_BYTES = 120.
+ // Surviving keys are ASCII identifiers (non-ASCII keys are redacted upstream),
+ // so build many ASCII keys to overflow the cap and assert the truncation
+ // CONTRACT: bounded, ellipsis-terminated, and not carrying the last key.
+ let mut obj = serde_json::Map::new();
+ for i in 0..30 {
+ obj.insert(format!("field{i:02}"), json!(1)); // 30 Γ— "fieldNN" (7 bytes) ≫ 120
+ }
+ let body = serde_json::to_string(&Value::Object(obj)).unwrap();
+ let shape = backend_api_body_shape(&body);
+
+ let keys = shape
+ .strip_prefix("object(keys=30,safe=[")
+ .and_then(|s| s.strip_suffix("],redacted=0)"))
+ .unwrap_or_else(|| panic!("unexpected shape: {shape}"));
+ assert!(
+ keys.len() <= BACKEND_API_BODY_SHAPE_MAX_BYTES,
+ "safe list exceeds cap ({} > {BACKEND_API_BODY_SHAPE_MAX_BYTES}): {keys}",
+ keys.len()
+ );
+ assert!(keys.ends_with('…'), "expected ellipsis-terminated: {keys}");
+ assert!(
+ !keys.contains("field29"),
+ "last key should be truncated away: {keys}"
+ );
+}
+
+#[path = "backend_channel_tests.rs"]
+mod channel_tests;