Skip to content

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

feat(client): add endpoint resolution and error types

Steven Enamakel68a8a453eaa9
diff --git a/crates/openhuman-tinyhumans/src/client/endpoint.rs b/crates/openhuman-tinyhumans/src/client/endpoint.rs
new file mode 100644
index 0000000000..97a520d02f
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/client/endpoint.rs
@@ -0,0 +1,71 @@
+//! Where a hosted credential may be sent.
+//!
+//! A TinyHumans API key belongs to TinyHumans: only the managed hosts (or a
+//! loopback endpoint for local development) are trusted recipients. Every
+//! credential, session or key, additionally requires HTTPS, except to
+//! loopback. These are the guards `BackendClient` and [`IntegrationsHttp`]
+//! (and, in later stages, the voice and inference callers) run before a
+//! credential is attached to a request.
+//!
+//! [`IntegrationsHttp`]: super::IntegrationsHttp
+
+/// The managed hosts an API key may be sent to over HTTPS.
+pub const MANAGED_API_KEY_HOSTS: [&str; 2] = ["api.tinyhumans.ai", "staging-api.tinyhumans.ai"];
+
+fn is_loopback_host(url: &url::Url) -> bool {
+ match url.host() {
+ Some(url::Host::Domain("localhost")) => true,
+ Some(url::Host::Ipv4(address)) => address.is_loopback(),
+ Some(url::Host::Ipv6(address)) => address.is_loopback(),
+ _ => false,
+ }
+}
+
+/// Whether `endpoint` is safe to carry a backend credential as a bearer.
+///
+/// `https://` always qualifies; plain `http://` only for loopback. A
+/// plaintext non-loopback endpoint would put the credential on the wire in the
+/// clear (CWE-319). Deliberately narrow to the managed-credential path:
+/// `normalize_api_base_url` stays permissive because a library host's BYOK or
+/// local `api_url` can legitimately be plain HTTP.
+pub fn is_safe_endpoint_for_managed_bearer(endpoint: &str) -> bool {
+ let Ok(url) = url::Url::parse(endpoint) else {
+ return false;
+ };
+ match url.scheme() {
+ "https" => true,
+ "http" => is_loopback_host(&url),
+ _ => false,
+ }
+}
+
+/// Whether `endpoint` may receive a TinyHumans API key: the managed hosts over
+/// HTTPS, or a loopback endpoint for local development. An arbitrary TLS host
+/// is not a trusted key recipient.
+pub fn is_managed_endpoint_for_api_key(endpoint: &str) -> bool {
+ let Ok(url) = url::Url::parse(endpoint) else {
+ return false;
+ };
+ if !is_safe_endpoint_for_managed_bearer(endpoint) {
+ return false;
+ }
+ let managed =
+ url.scheme() == "https" && url.host_str().is_some_and(|h| MANAGED_API_KEY_HOSTS.contains(&h));
+ managed || is_loopback_host(&url)
+}
+
+/// Reject `endpoint` unless it may carry `is_api_key`'s credential kind.
+/// The error text is the one the core's callers have always surfaced.
+pub fn validate_credential_endpoint(endpoint: &str, is_api_key: bool) -> anyhow::Result<()> {
+ if is_api_key && !is_managed_endpoint_for_api_key(endpoint) {
+ anyhow::bail!("TinyHumans API key requires the managed backend or a loopback endpoint");
+ }
+ if !is_safe_endpoint_for_managed_bearer(endpoint) {
+ anyhow::bail!("backend credential requires HTTPS or a loopback HTTP endpoint");
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+#[path = "endpoint_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-tinyhumans/src/client/endpoint_tests.rs b/crates/openhuman-tinyhumans/src/client/endpoint_tests.rs
new file mode 100644
index 0000000000..9a65aa4bf5
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/client/endpoint_tests.rs
@@ -0,0 +1,47 @@
+use super::*;
+
+#[test]
+fn api_key_endpoint_is_bound_to_tinyhumans_or_loopback() {
+ assert!(is_managed_endpoint_for_api_key(
+ "https://api.tinyhumans.ai/openai/v1"
+ ));
+ assert!(is_managed_endpoint_for_api_key(
+ "https://staging-api.tinyhumans.ai"
+ ));
+ assert!(is_managed_endpoint_for_api_key(
+ "http://127.0.0.1:18765/openai/v1"
+ ));
+ assert!(is_managed_endpoint_for_api_key(
+ "http://[::1]:18765/openai/v1"
+ ));
+ assert!(is_managed_endpoint_for_api_key("http://localhost:7788"));
+ assert!(!is_managed_endpoint_for_api_key(
+ "https://example.com/openai/v1"
+ ));
+ assert!(!is_managed_endpoint_for_api_key(
+ "http://api.tinyhumans.ai/openai/v1"
+ ));
+ assert!(!is_managed_endpoint_for_api_key(
+ "https://api.tinyhumans.ai.evil.example"
+ ));
+ assert!(!is_managed_endpoint_for_api_key("not a url"));
+}
+
+#[test]
+fn bearer_endpoint_requires_https_or_loopback_http() {
+ assert!(is_safe_endpoint_for_managed_bearer("https://example.com"));
+ assert!(is_safe_endpoint_for_managed_bearer("http://127.0.0.1:1"));
+ assert!(!is_safe_endpoint_for_managed_bearer("http://example.com"));
+ assert!(!is_safe_endpoint_for_managed_bearer("ftp://127.0.0.1"));
+ assert!(!is_safe_endpoint_for_managed_bearer(""));
+}
+
+#[test]
+fn validate_credential_endpoint_reports_the_specific_refusal() {
+ let key_err = validate_credential_endpoint("https://example.com", true).unwrap_err();
+ assert!(key_err.to_string().contains("TinyHumans API key requires"));
+ let bearer_err = validate_credential_endpoint("http://example.com", false).unwrap_err();
+ assert!(bearer_err.to_string().contains("requires HTTPS"));
+ validate_credential_endpoint("https://example.com", false).unwrap();
+ validate_credential_endpoint("http://127.0.0.1:9", true).unwrap();
+}
diff --git a/crates/openhuman-tinyhumans/src/client/error.rs b/crates/openhuman-tinyhumans/src/client/error.rs
new file mode 100644
index 0000000000..b0990b7994
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/client/error.rs
@@ -0,0 +1,95 @@
+//! [`HostedApiError`]: the typed, expected backend states `authed_json`
+//! surfaces for callers to recover from in-flow, and
+//! [`flatten_authed_error`], the chokepoint that turns them into the
+//! sentinel strings `core::observability` classifies.
+
+use openhuman_embed::__host::core::observability::{
+ API_KEY_REJECTED_PREFIX, BACKEND_UNAVAILABLE_PREFIX,
+};
+
+/// Typed errors surfaced by `BackendClient::authed_json` for expected backend
+/// states that callers should recover from rather than funnel into Sentry.
+#[derive(Debug, thiserror::Error)]
+pub enum HostedApiError {
+ /// Edit / delete of a channel message returned 404: the user deleted the
+ /// message on the provider side (Telegram, Discord, Slack, ...) but local
+ /// streaming state still has the id, or the backend GC'd the relay row.
+ /// Callers clear stale state and skip the retry.
+ #[error("message not found on {provider}: {message_id}")]
+ MessageNotFound {
+ /// Channel provider segment (e.g. `"telegram"`, `"discord"`).
+ provider: String,
+ /// Provider-specific message id from the URL.
+ message_id: String,
+ },
+ /// The backend rejected the bearer JWT with `401`. An expected
+ /// user-session state (expired, revoked, rotated), not a bug; the auth
+ /// domain owns recovery.
+ #[error("backend rejected session token on {method} {path}")]
+ Unauthorized {
+ /// HTTP method (`"GET"`, `"POST"`, ...).
+ method: String,
+ /// Request path the 401 came back from (no query string).
+ path: String,
+ },
+ /// The backend rejected a TinyHumans API key (`x-api-key`) with `401`.
+ ///
+ /// Distinct from [`Self::Unauthorized`] on purpose: that variant flattens
+ /// onto the `SESSION_EXPIRED` sentinel, which makes the dispatcher clear
+ /// the app session and sign out. A rejected key on a runtime that never
+ /// had a session must not trigger that recovery.
+ #[error("backend rejected api key on {method} {path}")]
+ ApiKeyRejected {
+ /// HTTP method (`"GET"`, `"POST"`, ...).
+ method: String,
+ /// Request path the 401 came back from (no query string).
+ path: String,
+ },
+ /// `PATCH /channels/<provider>/messages/<id>` returned 404 because the
+ /// backend **implements no such route** (#5230), not because the message
+ /// is gone. Callers keep the message id and only disable the edit
+ /// capability. Must stay distinct from [`Self::MessageNotFound`].
+ #[error(
+ "channel message edit route not implemented by backend ({provider}, message {message_id})"
+ )]
+ ChannelEditUnsupported {
+ /// Channel provider segment (e.g. `"telegram"`, `"discord"`).
+ provider: String,
+ /// Provider-specific message id from the URL.
+ message_id: String,
+ },
+ /// The request could not be sent at all because no transport could be
+ /// built. An expected build condition, never a bug; flattens onto the
+ /// `BACKEND_UNAVAILABLE:` sentinel.
+ #[error("backend transport not available for {method} {path}")]
+ BackendUnavailable {
+ /// HTTP method (`"GET"`, `"POST"`, ...).
+ method: String,
+ /// Request path that could not be sent (no query string).
+ path: String,
+ },
+}
+
+/// Flatten an `authed_json` error onto the JSON-RPC `String` channel.
+///
+/// `Unauthorized` maps onto the existing `SESSION_EXPIRED` sentinel so the
+/// dispatcher skips Sentry and publishes `DomainEvent::SessionExpired` (#3297).
+/// `ApiKeyRejected` and `BackendUnavailable` map onto their own core prefixes.
+/// This keys off the typed downcast, not the Display wording. Every other
+/// error keeps its full `{e:#}` chain so genuine failures still reach Sentry.
+pub fn flatten_authed_error(err: anyhow::Error) -> String {
+ match err.downcast_ref::<HostedApiError>() {
+ Some(HostedApiError::Unauthorized { method, path }) => {
+ format!("SESSION_EXPIRED: backend rejected session token on {method} {path}")
+ }
+ Some(HostedApiError::ApiKeyRejected { method, path }) => {
+ format!("{API_KEY_REJECTED_PREFIX}backend rejected api key on {method} {path}")
+ }
+ Some(HostedApiError::BackendUnavailable { method, path }) => {
+ format!(
+ "{BACKEND_UNAVAILABLE_PREFIX}backend transport not available for {method} {path}"
+ )
+ }
+ _ => format!("{err:#}"),
+ }
+}