Skip to content

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

fix(auth): one session-expiry rule — only a session-credential 401 signs out

M3gA-Mindb2271c492183
diff --git a/app/src/services/__tests__/coreRpcClient.test.ts b/app/src/services/__tests__/coreRpcClient.test.ts
index 0064931bc4..f6997824fb 100644
--- a/app/src/services/__tests__/coreRpcClient.test.ts
+++ b/app/src/services/__tests__/coreRpcClient.test.ts
@@ -782,6 +782,11 @@ describe('coreRpcClient', () => {
describe('classifyRpcError', () => {
test.each([
['GET /teams failed (401 Unauthorized): {"success":false}', undefined, 'auth_expired'],
+ [
+ 'GET /teams failed (500 Internal Server Error): {"status":401,"error":"Unauthorized"}',
+ undefined,
+ 'provider_auth',
+ ],
['Session expired. Please log in again.', undefined, 'auth_expired'],
['some prefix Session expired suffix', undefined, 'auth_expired'],
[
diff --git a/app/src/services/coreRpcClient.ts b/app/src/services/coreRpcClient.ts
index a5079b4dee..3693f2b427 100644
--- a/app/src/services/coreRpcClient.ts
+++ b/app/src/services/coreRpcClient.ts
@@ -197,13 +197,9 @@ export function classifyRpcError(
// Fix for issue #2286: only match when the message starts with an HTTP verb
// followed by a path — this excludes "Discord API error:", "OpenAI API error:", etc.
// HEAD and OPTIONS intentionally excluded — authed_json only uses these five verbs.
- // Aligned with Rust is_session_expired_error: starts-with-verb check + separate
- // contains checks for "401" and "unauthorized" (case-insensitive).
- if (
- /^(GET|POST|PUT|DELETE|PATCH)\s+\//.test(message) &&
- /401/.test(message) &&
- /unauthorized/i.test(message)
- )
+ // Aligned with Rust is_session_expired_error: anchored on the status itself,
+ // so a 500 whose body carries `"status":401` is not an expired session.
+ if (/^(GET|POST|PUT|DELETE|PATCH) \//.test(message) && message.includes(' failed (401'))
return 'auth_expired';
// Everything above matched an explicit backend marker in the message. What
// is left, if the transport gave us a 401, is the LOCAL core's bearer gate
diff --git a/crates/openhuman-core/src/core/README.md b/crates/openhuman-core/src/core/README.md
index e934c90f1e..68b3699122 100644
--- a/crates/openhuman-core/src/core/README.md
+++ b/crates/openhuman-core/src/core/README.md
@@ -313,7 +313,7 @@ Dispatch and auth:
| [`invoke.rs`](./invoke.rs) | `invoke_method` and `default_state`: the in-process entry point and the session-expiry hook. |
| [`dispatch.rs`](./dispatch.rs) | `dispatch`: legacy rewrite, `core.*` methods, registry fallback, unknown-method handling, `KNOWN_PROBE_METHODS`. |
| [`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` and `is_unconfirmed_unauthorized_error`. |
+| `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`). |
| `server_launcher.rs` | `ServerLauncher` port that `run` / `serve` start a server through. |
diff --git a/crates/openhuman-core/src/core/session_expiry.rs b/crates/openhuman-core/src/core/session_expiry.rs
index 58b3e0e623..3e4352d2f9 100644
--- a/crates/openhuman-core/src/core/session_expiry.rs
+++ b/crates/openhuman-core/src/core/session_expiry.rs
@@ -53,17 +53,21 @@ pub fn is_session_expired_error(msg: &str) -> bool {
// The HTTP-method prefix distinguishes these from provider-prefixed errors.
// HEAD and OPTIONS are intentionally excluded — `authed_json` only issues
// the five listed verbs (GET/POST/PUT/DELETE/PATCH) for REST JSON endpoints.
- let lower = msg.to_ascii_lowercase();
- if (lower.contains("401") && lower.contains("unauthorized"))
- && (msg.starts_with("GET /")
- || msg.starts_with("POST /")
- || msg.starts_with("PUT /")
- || msg.starts_with("DELETE /")
- || msg.starts_with("PATCH /"))
- {
- return true;
- }
- false
+ // Anchored on the status itself: a 500 whose body happens to contain
+ // `"status":401` and the word "unauthorized" is not an expired session.
+ ["GET /", "POST /", "PUT /", "DELETE /", "PATCH /"]
+ .iter()
+ .any(|verb| msg.starts_with(verb))
+ && msg.contains(" failed (401")
+}
+
+/// The one status rule for the OpenHuman backend: only a 401 on a request
+/// authenticated with the session credential means the session expired.
+/// 402/403/404 (plan, tier, WAF, proxy) are refusals that keep the session,
+/// and a 401 on an API key means the key was rejected — an API key has no
+/// session to expire.
+pub fn backend_status_means_session_expired(status: u16, api_key: bool) -> bool {
+ status == 401 && !api_key
}
/// Detect auth-looking failures that are not specific enough to clear the
diff --git a/crates/openhuman-core/src/core/session_expiry_tests.rs b/crates/openhuman-core/src/core/session_expiry_tests.rs
index bddb2cde58..7bd47fd31c 100644
--- a/crates/openhuman-core/src/core/session_expiry_tests.rs
+++ b/crates/openhuman-core/src/core/session_expiry_tests.rs
@@ -1,4 +1,7 @@
-use super::{is_session_expired_error, is_unconfirmed_unauthorized_error};
+use super::{
+ backend_status_means_session_expired, is_session_expired_error,
+ is_unconfirmed_unauthorized_error,
+};
#[test]
fn is_session_expired_error_matches_backend_path_401() {
@@ -226,3 +229,25 @@ fn is_session_expired_error_matches_session_jwt_required() {
// Case-insensitive.
assert!(is_session_expired_error("SESSION JWT REQUIRED"));
}
+
+#[test]
+fn is_session_expired_error_does_not_match_a_non_401_with_401_in_its_body() {
+ assert!(!is_session_expired_error(
+ "GET /teams failed (500 Internal Server Error): {\"status\":401,\"error\":\"Unauthorized\"}"
+ ));
+ assert!(!is_session_expired_error(
+ "POST /auth/me failed (403 Forbidden): 401 unauthorized upstream"
+ ));
+}
+
+#[test]
+fn only_a_session_credential_401_means_the_session_expired() {
+ assert!(backend_status_means_session_expired(401, false));
+ assert!(!backend_status_means_session_expired(401, true));
+ for status in [400, 402, 403, 404, 429, 500, 503] {
+ assert!(
+ !backend_status_means_session_expired(status, false),
+ "{status} is a refusal, not an expired session"
+ );
+ }
+}
diff --git a/crates/openhuman-core/src/inference/provider/http_error.rs b/crates/openhuman-core/src/inference/provider/http_error.rs
index e74013b0d0..30d84d3300 100644
--- a/crates/openhuman-core/src/inference/provider/http_error.rs
+++ b/crates/openhuman-core/src/inference/provider/http_error.rs
@@ -24,9 +24,10 @@ pub fn should_report_provider_http_failure(status: reqwest::StatusCode) -> bool
should_report_provider_http_status(status.as_u16())
}
-/// Whether this is the OpenHuman backend rejecting the app session JWT.
+/// Whether this is the OpenHuman backend rejecting the app session JWT. This
+/// path only sends the session credential, so `api_key` is always false.
pub fn is_backend_auth_failure(provider: &str, status: reqwest::StatusCode) -> bool {
- matches!(status.as_u16(), 401 | 403)
+ crate::core::session_expiry::backend_status_means_session_expired(status.as_u16(), false)
&& classify_backend_error(Some(provider), "").is_some_and(|result| result.provider_owned)
}
@@ -102,7 +103,7 @@ pub fn log_byo_provider_auth_failure(
}
}
-/// Publish `SessionExpired` for a backend 401/403 and skip the Sentry report.
+/// Publish `SessionExpired` for a backend session 401 and skip the Sentry report.
/// `message` is re-sanitized before it reaches the subscriber's logs.
pub fn publish_backend_session_expired(
operation: &str,
@@ -183,7 +184,9 @@ impl ErrorReporter for HostErrorReporter<'_> {
};
let decision = select_demotion(&facts, is_backend, self.backend_error_code_owned);
- if matches!(status, 401 | 403) && is_backend {
+ if is_backend
+ && crate::core::session_expiry::backend_status_means_session_expired(status, false)
+ {
publish_backend_session_expired(operation, provider, status_code, self.message);
} else {
match decision {
diff --git a/crates/openhuman-core/src/inference/provider/http_error_tests.rs b/crates/openhuman-core/src/inference/provider/http_error_tests.rs
index 42dab3b4fd..19106ee83d 100644
--- a/crates/openhuman-core/src/inference/provider/http_error_tests.rs
+++ b/crates/openhuman-core/src/inference/provider/http_error_tests.rs
@@ -112,6 +112,23 @@ async fn backend_401_publishes_session_expired_through_reporter() {
assert!(seen.is_some(), "backend 401 must publish SessionExpired");
}
+#[tokio::test]
+async fn backend_403_does_not_publish_session_expired() {
+ install_fixture_backend_classifier();
+ crate::core::bus::init().await.expect("bus init");
+ let mut rx = crate::core::bus::BUS.get().expect("bus").receiver();
+ let marker = "REPORTER_MARKER_FORBIDDEN a paid plan is required";
+ let _ = api_error(FIXTURE_BACKEND, response(StatusCode::FORBIDDEN, marker)).await;
+ let seen = drain_until(&mut rx, |e| match e {
+ DomainEvent::SessionExpired { reason, .. } if reason.contains(marker) => Some(()),
+ _ => None,
+ });
+ assert!(
+ seen.is_none(),
+ "a backend 403 is a refusal, not an expired session"
+ );
+}
+
#[tokio::test]
async fn byo_401_publishes_api_key_rejected_not_session_expired() {
crate::core::bus::init().await.expect("bus init");
@@ -166,16 +183,17 @@ async fn backend_provider_does_not_get_byo_key_rejection() {
/// Sentry). Getting this wrong in either direction is a regression:
/// over-matching silences real misconfig; under-matching is TAURI-RUST-N.
#[test]
-fn is_backend_auth_failure_only_matches_openhuman_backend_401_403() {
+fn is_backend_auth_failure_only_matches_openhuman_backend_401() {
use reqwest::StatusCode;
install_fixture_backend_classifier();
let backend = FIXTURE_BACKEND;
assert!(is_backend_auth_failure(backend, StatusCode::UNAUTHORIZED));
- assert!(is_backend_auth_failure(backend, StatusCode::FORBIDDEN));
- // Non-auth backend statuses stay reportable (real server bugs / transient).
+ // A 403 is a refusal (plan, tier, WAF) and the rest are server faults or
+ // transient: none of them expires the session.
for s in [
+ StatusCode::FORBIDDEN,
StatusCode::INTERNAL_SERVER_ERROR,
StatusCode::TOO_MANY_REQUESTS,
StatusCode::BAD_REQUEST,
diff --git a/crates/openhuman-embed/src/host_internals.rs b/crates/openhuman-embed/src/host_internals.rs
index 1e8b90f942..4039085e37 100644
--- a/crates/openhuman-embed/src/host_internals.rs
+++ b/crates/openhuman-embed/src/host_internals.rs
@@ -91,7 +91,9 @@ pub mod core {
pub use openhuman_core::core::server_launcher::{install_server_launcher, ServeRequest};
}
pub mod session_expiry {
- pub use openhuman_core::core::session_expiry::is_session_expired_error;
+ pub use openhuman_core::core::session_expiry::{
+ backend_status_means_session_expired, is_session_expired_error,
+ };
}
pub mod shutdown {
pub use openhuman_core::core::shutdown::{register, signal};
diff --git a/crates/openhuman-tinyhumans/src/inference/managed_model.rs b/crates/openhuman-tinyhumans/src/inference/managed_model.rs
index 5e45756458..37ef8f4554 100644
--- a/crates/openhuman-tinyhumans/src/inference/managed_model.rs
+++ b/crates/openhuman-tinyhumans/src/inference/managed_model.rs
@@ -37,7 +37,13 @@ impl ManagedOptions {
})
}
+ #[cfg(test)]
fn resolve_bearer(&self, endpoint: &str) -> anyhow::Result<String> {
+ self.resolve_bearer_kind(endpoint).map(|(bearer, _)| bearer)
+ }
+
+ /// The bearer, and whether it is the API key (`true`) or the session JWT.
+ fn resolve_bearer_kind(&self, endpoint: &str) -> anyhow::Result<(String, bool)> {
if let Some(key) = openhuman_embed::__host::security::credentials::api_key::get_api_key_in(
&self.state_dir(),
self.secrets_encrypt,
@@ -52,7 +58,7 @@ impl ManagedOptions {
log::debug!(
"[providers][openhuman-backend] authenticating managed inference with api-key"
);
- return Ok(key);
+ return Ok((key, true));
}
resolve_session_bearer(
&self.state_dir(),
@@ -60,6 +66,7 @@ impl ManagedOptions {
self.auth_profile_override.as_deref(),
"openhuman_backend_model.resolve_bearer",
)
+ .map(|token| (token, false))
}
}
@@ -86,14 +93,20 @@ pub(super) fn build_chat_model(
let endpoint = effective_api_url(&api_url.map(str::to_owned));
let resolver_options = options.clone();
let resolver_endpoint = endpoint.clone();
+ // Which credential the last request carried: an API-key 401 is a rejected
+ // key, not an expired session.
+ let sent_api_key = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let resolver_sent_api_key = sent_api_key.clone();
let mut managed = TinyHumansModel::new(
endpoint,
model,
super::tiers::MODEL_MANAGED_DEFAULT,
move || {
- resolver_options
- .resolve_bearer(&resolver_endpoint)
- .map_err(|error| tinyinference_llm::Error::Model(error.to_string()))
+ let (bearer, api_key) = resolver_options
+ .resolve_bearer_kind(&resolver_endpoint)
+ .map_err(|error| tinyinference_llm::Error::Model(error.to_string()))?;
+ resolver_sent_api_key.store(api_key, std::sync::atomic::Ordering::Relaxed);
+ Ok(bearer)
},
)?
.with_cache_namespace("openhuman")
@@ -102,8 +115,9 @@ pub(super) fn build_chat_model(
.with_error_observer(log_managed_error);
if observe_auth_failures {
- managed = managed.with_managed_auth_failure_handler(|error, context| {
- publish_managed_auth_failure(error, context);
+ managed = managed.with_managed_auth_failure_handler(move |error, context| {
+ let api_key = sent_api_key.load(std::sync::atomic::Ordering::Relaxed);
+ publish_managed_auth_failure(error, context, api_key);
});
}
Ok(managed)
diff --git a/crates/openhuman-tinyhumans/src/inference/managed_model_tests.rs b/crates/openhuman-tinyhumans/src/inference/managed_model_tests.rs
index 7d54e78fa7..51de6557c7 100644
--- a/crates/openhuman-tinyhumans/src/inference/managed_model_tests.rs
+++ b/crates/openhuman-tinyhumans/src/inference/managed_model_tests.rs
@@ -266,82 +266,116 @@ fn managed_endpoint_diagnostic_is_origin_only_or_a_constant_fallback() {
assert_eq!(endpoint_origin_for_log("not a url"), "<invalid endpoint>");
}
-async fn unauthorized_chat_response() -> axum::response::Response {
+/// Serves `status` for every chat request, with `marker` in the error body.
+async fn serve_chat_status(
+ status: axum::http::StatusCode,
+ marker: &'static str,
+) -> (std::net::SocketAddr, tokio::task::JoinHandle<()>) {
use axum::response::IntoResponse;
- (
- axum::http::StatusCode::UNAUTHORIZED,
- axum::Json(serde_json::json!({
- "error": { "message": "HOST_AUTH_CALLBACK_MARKER" }
- })),
- )
- .into_response()
-}
-
-#[tokio::test]
-async fn owner_typed_managed_auth_callback_publishes_session_expiry() {
- use openhuman_embed::__host::core::events::DomainEvent;
-
- openhuman_embed::__host::core::bus::init()
- .await
- .expect("initialize event bus");
- let mut events = openhuman_embed::__host::core::bus::BUS
- .get()
- .expect("event bus initialized")
- .receiver();
- let tmp = tempfile::TempDir::new().expect("temporary credentials");
- openhuman_embed::__host::security::credentials::api_key::store_api_key_in(
- tmp.path(),
- false,
- "test-managed-key",
- )
- .expect("store test API key");
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind fixture server");
let addr = listener.local_addr().expect("fixture address");
let app = axum::Router::new().route(
"/openai/v1/chat/completions",
- axum::routing::post(unauthorized_chat_response),
+ axum::routing::post(move || async move {
+ (
+ status,
+ axum::Json(serde_json::json!({ "error": { "message": marker } })),
+ )
+ .into_response()
+ }),
);
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
- let options = ManagedOptions {
- openhuman_dir: Some(tmp.path().to_path_buf()),
- secrets_encrypt: false,
- ..ManagedOptions::default()
- };
- let model = build_chat_model(
- Some(&format!("http://{addr}")),
- &options,
- "reasoning-v1",
- true,
- None,
- true,
- )
- .expect("build owner model");
+ (addr, server)
+}
- assert!(model
- .invoke(&(), ModelRequest::new(vec![Message::user("ping")]))
+/// Only a 401 on the session credential expires the session: a 403 is a
+/// refusal and an API-key 401 is a rejected key.
+#[tokio::test]
+async fn managed_auth_failure_expires_the_session_only_on_a_session_401() {
+ use axum::http::StatusCode;
+ use openhuman_embed::__host::core::events::DomainEvent;
+
+ openhuman_embed::__host::core::bus::init()
.await
- .is_err());
- server.abort();
+ .expect("initialize event bus");
+ let cases: [(&str, bool, StatusCode, &'static str, Option<&str>); 4] = [
+ (
+ "session 401",
+ false,
+ StatusCode::UNAUTHORIZED,
+ "HOST_AUTH_SESSION_401",
+ Some("openhuman_backend_model.invoke(401)"),
+ ),
+ (
+ "session 403",
+ false,
+ StatusCode::FORBIDDEN,
+ "HOST_AUTH_SESSION_403",
+ None,
+ ),
+ (
+ "api-key 401",
+ true,
+ StatusCode::UNAUTHORIZED,
+ "HOST_AUTH_API_KEY_401",
+ None,
+ ),
+ (
+ "api-key 403",
+ true,
+ StatusCode::FORBIDDEN,
+ "HOST_AUTH_API_KEY_403",
+ None,
+ ),
+ ];
+ for (name, api_key, status, marker, expected) in cases {
+ let mut events = openhuman_embed::__host::core::bus::BUS
+ .get()
+ .expect("event bus initialized")
+ .receiver();
+ let tmp = tempfile::TempDir::new().expect("temporary credentials");
+ seed_app_session(tmp.path(), Some("2999-01-01T00:00:00Z"));
+ if api_key {
+ openhuman_embed::__host::security::credentials::api_key::store_api_key_in(
+ tmp.path(),
+ false,
+ "test-managed-key",
+ )
+ .expect("store test API key");
+ }
+ let (addr, server) = serve_chat_status(status, marker).await;
+ let model = build_chat_model(
+ Some(&format!("http://{addr}")),
+ &managed_options_at(tmp.path()),
+ "reasoning-v1",
+ true,
+ None,
+ true,
+ )
+ .expect("build owner model");
- let mut source = None;
- loop {
- match events.try_recv() {
- Ok(DomainEvent::SessionExpired {
- source: value,
- reason,
- }) if reason.contains("HOST_AUTH_CALLBACK_MARKER") => {
- source = Some(value);
- break;
+ assert!(model
+ .invoke(&(), ModelRequest::new(vec![Message::user("ping")]))
+ .await
+ .is_err());
+ server.abort();
+
+ let mut source = None;
+ loop {
+ match events.try_recv() {
+ Ok(DomainEvent::SessionExpired {
+ source: value,
+ reason,
+ }) if reason.contains(marker) => {
+ source = Some(value);
+ break;
+ }
+ Ok(_) | Err(tinybus::TryRecvError::Lagged(_)) => continue,
+ Err(_) => break,
}
- Ok(_) | Err(tinybus::TryRecvError::Lagged(_)) => continue,
- Err(_) => break,
}
+ assert_eq!(source.as_deref(), expected, "{name}");
}
- assert_eq!(
- source.as_deref(),
- Some("openhuman_backend_model.invoke(401)"),
- "the owner's explicit managed-auth callback must preserve invoke attribution"
- );
}
diff --git a/crates/openhuman-tinyhumans/src/inference/managed_session.rs b/crates/openhuman-tinyhumans/src/inference/managed_session.rs
index 5e9a26db88..217554bdb6 100644
--- a/crates/openhuman-tinyhumans/src/inference/managed_session.rs
+++ b/crates/openhuman-tinyhumans/src/inference/managed_session.rs
@@ -133,14 +133,28 @@ fn maybe_publish_local_session_expiry(operation: &str) {
}
/// Publish expiry only from TinyInference's explicit managed-endpoint
-/// provenance. The provider label is a wire diagnostic and is not an auth
-/// ownership signal.
-pub(super) fn publish_managed_auth_failure(error: &ProviderError, context: TinyHumansAuthFailure) {
+/// provenance, and only for a 401 on the session credential. A 403 is a
+/// refusal (plan, tier, WAF) and an API-key 401 is a rejected key; neither
+/// signs the user out. The provider label is a wire diagnostic and is not an
+/// auth ownership signal.
+pub(super) fn publish_managed_auth_failure(
+ error: &ProviderError,
+ context: TinyHumansAuthFailure,
+ api_key: bool,
+) {
let status = match context.kind() {
TinyHumansAuthFailureKind::Unauthorized => 401,
TinyHumansAuthFailureKind::Forbidden => 403,
TinyHumansAuthFailureKind::Other => return,
};
+ if !openhuman_embed::__host::core::session_expiry::backend_status_means_session_expired(
+ status, api_key,
+ ) {
+ log::warn!(
+ "[providers][openhuman-backend] managed {status} (api_key={api_key}) is a refusal — keeping the session"
+ );
+ return;
+ }
let operation = match context.operation() {
TinyHumansOperation::Invoke => "invoke",
TinyHumansOperation::Stream => "stream",
diff --git a/crates/openhuman-tinyhumans/src/session/client.rs b/crates/openhuman-tinyhumans/src/session/client.rs
index ee04a67685..4518c26f8a 100644
--- a/crates/openhuman-tinyhumans/src/session/client.rs
+++ b/crates/openhuman-tinyhumans/src/session/client.rs
@@ -19,10 +19,6 @@ const CORE_VERSION_HEADER: &str = "x-core-version";
const TAURI_VERSION_HEADER: &str = "x-tauri-version";
const HEADER_VALUE_MAX_LEN: usize = 64;
-/// HTTP statuses that mean "the backend was not healthy", not "the credential
-/// is bad". Shared by store-time validation and the current-user refresh.
-pub const TRANSIENT_STATUSES: &[u16] = &[408, 429, 500, 502, 503, 504, 520];
-
/// Transport-failure phrases treated as transient (same list as the core's
/// `observability::TRANSIENT_TRANSPORT_PHRASES`, kept in sync by hand because
/// this crate must not depend on the core).
@@ -120,9 +116,11 @@ fn sanitize_version(raw: &str) -> Option<String> {
/// Why a `GET /auth/me` did not yield a user.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FetchMeError {
- /// The backend answered and refused the credential (401/403/…).
+ /// The backend answered 401: the session credential is dead.
Rejected(String),
- /// The backend answered with a status from [`TRANSIENT_STATUSES`].
+ /// The backend answered with any other non-2xx status or a `success:false`
+ /// envelope. 402/403/404 are refusals (plan, WAF, proxy), not an expired
+ /// session, so the session is kept and the caller backs off.
Transient(String),
/// The request never got an answer (connect/timeout/TLS/read failure).
Transport(String),
@@ -160,13 +158,16 @@ impl FetchMeError {
// Error bodies are controlled by the backend or an intervening
// proxy. Do not carry them into the manager's logs.
let message = format!("http {status}: {}", error_body_shape(&body));
- if TRANSIENT_STATUSES.contains(&status) || (500..=599).contains(&status) {
- Self::Transient(message)
- } else {
+ // `/auth/me` always carries the session credential.
+ if openhuman_embed::__host::core::session_expiry::backend_status_means_session_expired(
+ status, false,
+ ) {
Self::Rejected(message)
+ } else {
+ Self::Transient(message)
}
}
- tinyhumans_sdk::Error::Envelope { error, .. } => Self::Rejected(error),
+ tinyhumans_sdk::Error::Envelope { error, .. } => Self::Transient(error),
other => {
let message = format!("{other:#}");
if contains_transient_transport_phrase(&message) {
diff --git a/crates/openhuman-tinyhumans/src/session/client_tests.rs b/crates/openhuman-tinyhumans/src/session/client_tests.rs
index fa142dfffd..94273c1c13 100644
--- a/crates/openhuman-tinyhumans/src/session/client_tests.rs
+++ b/crates/openhuman-tinyhumans/src/session/client_tests.rs
@@ -35,6 +35,24 @@ fn base_url_is_normalised_and_validated() {
));
}
+#[test]
+fn fetch_me_error_from_sdk_rejects_only_a_401() {
+ let status = |status| tinyhumans_sdk::Error::Status {
+ status,
+ body: Value::Null,
+ };
+ assert!(matches!(
+ FetchMeError::from_sdk(status(401)),
+ FetchMeError::Rejected(_)
+ ));
+ for code in [400, 402, 403, 404, 429, 500, 503] {
+ assert!(
+ FetchMeError::from_sdk(status(code)).is_availability_failure(),
+ "{code} must keep the session"
+ );
+ }
+}
+
#[test]
fn fetch_me_error_classification() {
assert!(FetchMeError::Transient("503".into()).is_availability_failure());
diff --git a/crates/openhuman-tinyhumans/src/session/manager_tests.rs b/crates/openhuman-tinyhumans/src/session/manager_tests.rs
index bdd7ca7122..6807788b0c 100644
--- a/crates/openhuman-tinyhumans/src/session/manager_tests.rs
+++ b/crates/openhuman-tinyhumans/src/session/manager_tests.rs
@@ -427,6 +427,32 @@ async fn current_user_rejection_signs_out_and_emits_expired() {
assert!(!state.core.is_authenticated);
}
+/// Only a 401 expires the session: a 402/403/404 from `/auth/me` is a refusal
+/// (plan, WAF, proxy) and the stored session survives it.
+#[tokio::test]
+async fn current_user_refusal_keeps_the_session() {
+ for status in [402, 403, 404] {
+ let backend = Backend::start(vec![MeAnswer::Ok(me_user()), MeAnswer::Status(status)]).await;
+ let core = FakeCore::new(&backend.url);
+ let m = manager(&core);
+ m.login_with_token("tok").await.unwrap();
+ let mut rx = m.subscribe();
+ let cached = m.current_user(true).await;
+ assert!(
+ matches!(&cached, Ok(c) if c.stale),
+ "{status}: expected the stored user served stale, got {cached:?}"
+ );
+ assert!(core.session().is_some(), "{status} cleared the session");
+ assert!(
+ !drain(&mut rx)
+ .await
+ .iter()
+ .any(|e| matches!(e, SessionEvent::Expired { .. })),
+ "{status} emitted Expired"
+ );
+ }
+}
+
/// Linking a second provider to the same account is a session refresh, not a
/// different user (matrix 1.2.2).
///