Skip to content

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

feat(session): format code with rustfmt

Steven Enamakeleaa3ca3761ef
diff --git a/crates/openhuman-session/src/cache.rs b/crates/openhuman-session/src/cache.rs
index ad2b7912c8..69992838f5 100644
--- a/crates/openhuman-session/src/cache.rs
+++ b/crates/openhuman-session/src/cache.rs
@@ -272,8 +272,11 @@ impl CurrentUserCache {
}
let timeout = fetch_timeout();
- match tokio::time::timeout(timeout, self.refresh_now(client, credential, generation, false))
- .await
+ match tokio::time::timeout(
+ timeout,
+ self.refresh_now(client, credential, generation, false),
+ )
+ .await
{
Ok(Ok(user)) => Ok(self.with_result(&key, user)),
Ok(Err(error)) => Err(error),
@@ -381,7 +384,9 @@ impl CurrentUserCache {
}
};
if !committed {
- log::debug!("{LOG_PREFIX} discarding refresh that raced sign-out or an identity switch");
+ log::debug!(
+ "{LOG_PREFIX} discarding refresh that raced sign-out or an identity switch"
+ );
}
Ok(fetched)
}
diff --git a/crates/openhuman-session/src/cache_tests.rs b/crates/openhuman-session/src/cache_tests.rs
index f181ab58bb..b8c37f6c22 100644
--- a/crates/openhuman-session/src/cache_tests.rs
+++ b/crates/openhuman-session/src/cache_tests.rs
@@ -11,16 +11,28 @@ fn client(backend: &Backend) -> SessionClient {
fn fetch_timeout_parsing_clamps_to_range() {
assert_eq!(parse_fetch_timeout_secs(None), DEFAULT_FETCH_TIMEOUT_SECS);
assert_eq!(parse_fetch_timeout_secs(Some(" 8 ")), 8);
- assert_eq!(parse_fetch_timeout_secs(Some("1")), DEFAULT_FETCH_TIMEOUT_SECS);
- assert_eq!(parse_fetch_timeout_secs(Some("13")), DEFAULT_FETCH_TIMEOUT_SECS);
- assert_eq!(parse_fetch_timeout_secs(Some("abc")), DEFAULT_FETCH_TIMEOUT_SECS);
+ assert_eq!(
+ parse_fetch_timeout_secs(Some("1")),
+ DEFAULT_FETCH_TIMEOUT_SECS
+ );
+ assert_eq!(
+ parse_fetch_timeout_secs(Some("13")),
+ DEFAULT_FETCH_TIMEOUT_SECS
+ );
+ assert_eq!(
+ parse_fetch_timeout_secs(Some("abc")),
+ DEFAULT_FETCH_TIMEOUT_SECS
+ );
}
#[test]
fn backoff_doubles_from_a_floor_and_saturates() {
let t = Duration::from_secs(5);
assert_eq!(backoff_base_for(t), Duration::from_secs(10));
- assert_eq!(backoff_base_for(Duration::from_secs(12)), Duration::from_secs(24));
+ assert_eq!(
+ backoff_base_for(Duration::from_secs(12)),
+ Duration::from_secs(24)
+ );
assert_eq!(backoff_for(0, t), Duration::from_secs(10));
assert_eq!(backoff_for(1, t), Duration::from_secs(10));
assert_eq!(backoff_for(2, t), Duration::from_secs(20));
@@ -34,11 +46,17 @@ async fn fresh_entry_is_served_without_a_request() {
let backend = Backend::start(vec![MeAnswer::Ok(me_user())]).await;
let cache = CurrentUserCache::new();
let cred = Credential::session(LIVE_JWT);
- let first = cache.get_or_refresh(&client(&backend), &cred, false).await.unwrap();
+ let first = cache
+ .get_or_refresh(&client(&backend), &cred, false)
+ .await
+ .unwrap();
assert_eq!(first.user.as_ref().unwrap()["_id"], "user-123");
assert!(!first.stale);
assert_eq!(first.stale_seconds, Some(0));
- let second = cache.get_or_refresh(&client(&backend), &cred, false).await.unwrap();
+ let second = cache
+ .get_or_refresh(&client(&backend), &cred, false)
+ .await
+ .unwrap();
assert_eq!(second.user, first.user);
assert_eq!(backend.me_calls(), 1);
assert_eq!(cache.peek(), first.user);
@@ -46,11 +64,21 @@ async fn fresh_entry_is_served_without_a_request() {
#[tokio::test]
async fn force_bypasses_the_cache() {
- let backend = Backend::start(vec![MeAnswer::Ok(me_user()), MeAnswer::Ok(json!({ "_id": "user-123", "name": "Renamed" }))]).await;
+ let backend = Backend::start(vec![
+ MeAnswer::Ok(me_user()),
+ MeAnswer::Ok(json!({ "_id": "user-123", "name": "Renamed" })),
+ ])
+ .await;
let cache = CurrentUserCache::new();
let cred = Credential::session(LIVE_JWT);
- cache.get_or_refresh(&client(&backend), &cred, false).await.unwrap();
- let forced = cache.get_or_refresh(&client(&backend), &cred, true).await.unwrap();
+ cache
+ .get_or_refresh(&client(&backend), &cred, false)
+ .await
+ .unwrap();
+ let forced = cache
+ .get_or_refresh(&client(&backend), &cred, true)
+ .await
+ .unwrap();
assert_eq!(forced.user.unwrap()["name"], "Renamed");
assert_eq!(backend.me_calls(), 2);
}
@@ -127,9 +155,15 @@ async fn forget_drops_the_positive_entry() {
let backend = Backend::start(vec![MeAnswer::Ok(me_user())]).await;
let cache = CurrentUserCache::new();
let cred = Credential::session(LIVE_JWT);
- cache.get_or_refresh(&client(&backend), &cred, false).await.unwrap();
+ cache
+ .get_or_refresh(&client(&backend), &cred, false)
+ .await
+ .unwrap();
cache.forget();
assert_eq!(cache.peek(), None);
- cache.get_or_refresh(&client(&backend), &cred, false).await.unwrap();
+ cache
+ .get_or_refresh(&client(&backend), &cred, false)
+ .await
+ .unwrap();
assert_eq!(backend.me_calls(), 2);
}
diff --git a/crates/openhuman-session/src/client.rs b/crates/openhuman-session/src/client.rs
index 31dbbec10b..a9dae533c4 100644
--- a/crates/openhuman-session/src/client.rs
+++ b/crates/openhuman-session/src/client.rs
@@ -267,7 +267,10 @@ impl SessionClient {
/// Exchange a one-time login token for a session JWT
/// (`POST /auth/login-token/consume`).
- pub async fn consume_login_token(&self, login_token: &str) -> Result<String, SessionClientError> {
+ pub async fn consume_login_token(
+ &self,
+ login_token: &str,
+ ) -> Result<String, SessionClientError> {
let token = login_token.trim();
if token.is_empty() {
return Err(SessionClientError::EmptyLoginToken);
@@ -330,7 +333,10 @@ impl SessionClient {
}
}
- async fn validate_once_with_retry(&self, credential: &Credential) -> Result<Value, FetchMeError> {
+ async fn validate_once_with_retry(
+ &self,
+ credential: &Credential,
+ ) -> Result<Value, FetchMeError> {
match self.fetch_me(credential).await {
Ok(user) => Ok(user),
Err(first) if first.is_availability_failure() => {
diff --git a/crates/openhuman-session/src/client_tests.rs b/crates/openhuman-session/src/client_tests.rs
index cb97b209b7..48de68a1ce 100644
--- a/crates/openhuman-session/src/client_tests.rs
+++ b/crates/openhuman-session/src/client_tests.rs
@@ -54,13 +54,19 @@ async fn consume_login_token_returns_jwt_and_sends_attribution_headers() {
assert_eq!(jwt, LIVE_JWT);
assert_eq!(backend.consume_calls(), vec![json!({ "token": "tok" })]);
- let user = client.fetch_me(&Credential::session(LIVE_JWT)).await.unwrap();
+ let user = client
+ .fetch_me(&Credential::session(LIVE_JWT))
+ .await
+ .unwrap();
assert_eq!(user["_id"], "user-123");
let calls = backend.state.me_calls.lock().unwrap();
let h = &calls[0];
assert_eq!(h.get("x-sdk-name").unwrap(), "opencompany");
assert_eq!(h.get("x-core-version").unwrap(), "1.2.3+abc");
- assert_eq!(h.get("authorization").unwrap().to_str().unwrap(), format!("Bearer {LIVE_JWT}"));
+ assert_eq!(
+ h.get("authorization").unwrap().to_str().unwrap(),
+ format!("Bearer {LIVE_JWT}")
+ );
assert!(h.get("x-api-key").is_none());
}
@@ -98,8 +104,14 @@ async fn fetch_me_classifies_statuses() {
let backend = Backend::start(vec![MeAnswer::Status(401), MeAnswer::Status(503)]).await;
let client = SessionClient::new(&backend.url, &headers()).unwrap();
let cred = Credential::session(LIVE_JWT);
- assert!(matches!(client.fetch_me(&cred).await, Err(FetchMeError::Rejected(_))));
- assert!(matches!(client.fetch_me(&cred).await, Err(FetchMeError::Transient(_))));
+ assert!(matches!(
+ client.fetch_me(&cred).await,
+ Err(FetchMeError::Rejected(_))
+ ));
+ assert!(matches!(
+ client.fetch_me(&cred).await,
+ Err(FetchMeError::Transient(_))
+ ));
}
#[tokio::test]
@@ -116,7 +128,10 @@ async fn validate_for_store_retries_once_after_transient() {
let _env = ENV_LOCK.lock().await;
let backend = Backend::start(vec![MeAnswer::Status(502), MeAnswer::Ok(me_user())]).await;
let client = SessionClient::new(&backend.url, &headers()).unwrap();
- let user = client.validate_for_store(&Credential::session(LIVE_JWT)).await.unwrap();
+ let user = client
+ .validate_for_store(&Credential::session(LIVE_JWT))
+ .await
+ .unwrap();
assert_eq!(user["_id"], "user-123");
assert_eq!(backend.me_calls(), 2);
}
@@ -127,7 +142,9 @@ async fn validate_for_store_does_not_retry_a_rejection() {
let backend = Backend::start(vec![MeAnswer::Status(401), MeAnswer::Ok(me_user())]).await;
let client = SessionClient::new(&backend.url, &headers()).unwrap();
assert!(matches!(
- client.validate_for_store(&Credential::session(LIVE_JWT)).await,
+ client
+ .validate_for_store(&Credential::session(LIVE_JWT))
+ .await,
Err(FetchMeError::Rejected(_))
));
assert_eq!(backend.me_calls(), 1);
@@ -139,7 +156,9 @@ async fn validate_for_store_times_out_into_transport() {
std::env::set_var(VALIDATION_BUDGET_ENV, "100");
let backend = Backend::start(vec![MeAnswer::Slow(2_000)]).await;
let client = SessionClient::new(&backend.url, &headers()).unwrap();
- let result = client.validate_for_store(&Credential::session(LIVE_JWT)).await;
+ let result = client
+ .validate_for_store(&Credential::session(LIVE_JWT))
+ .await;
std::env::remove_var(VALIDATION_BUDGET_ENV);
match result {
Err(FetchMeError::Transport(message)) => assert!(message.contains("timeout"), "{message}"),
diff --git a/crates/openhuman-session/src/credential_tests.rs b/crates/openhuman-session/src/credential_tests.rs
index 4a6670e089..2914312c84 100644
--- a/crates/openhuman-session/src/credential_tests.rs
+++ b/crates/openhuman-session/src/credential_tests.rs
@@ -29,12 +29,22 @@ fn local_shape_requires_exactly_three_segments_with_local_signature() {
#[test]
fn credential_kind_round_trips_its_wire_values() {
- for kind in [CredentialKind::Session, CredentialKind::ApiKey, CredentialKind::Local] {
+ for kind in [
+ CredentialKind::Session,
+ CredentialKind::ApiKey,
+ CredentialKind::Local,
+ ] {
assert_eq!(CredentialKind::parse(kind.as_str()), Some(kind));
}
- assert_eq!(CredentialKind::parse(" api-key "), Some(CredentialKind::ApiKey));
+ assert_eq!(
+ CredentialKind::parse(" api-key "),
+ Some(CredentialKind::ApiKey)
+ );
assert_eq!(CredentialKind::parse("jwt"), None);
- assert_eq!(serde_json::to_value(CredentialKind::ApiKey).unwrap(), json!("api-key"));
+ assert_eq!(
+ serde_json::to_value(CredentialKind::ApiKey).unwrap(),
+ json!("api-key")
+ );
}
#[test]
@@ -62,7 +72,10 @@ fn jwt_exp_decoding_and_liveness() {
#[test]
fn user_id_from_jwt_claims_prefers_sub() {
- assert_eq!(user_id_from_jwt_claims(LIVE_JWT).as_deref(), Some("user-123"));
+ assert_eq!(
+ user_id_from_jwt_claims(LIVE_JWT).as_deref(),
+ Some("user-123")
+ );
assert_eq!(user_id_from_jwt_claims(LIVE_JWT_NO_SUB), None);
assert_eq!(user_id_from_jwt_claims(OPAQUE_TOKEN), None);
}
diff --git a/crates/openhuman-session/src/identity.rs b/crates/openhuman-session/src/identity.rs
index df212aa175..552e232b38 100644
--- a/crates/openhuman-session/src/identity.rs
+++ b/crates/openhuman-session/src/identity.rs
@@ -15,7 +15,9 @@ fn slot() -> &'static RwLock<Option<String>> {
/// Record the signed-in user id (or clear it with `None`).
pub fn set_user_id(user_id: Option<String>) {
let mut guard = slot().write().unwrap_or_else(|p| p.into_inner());
- *guard = user_id.map(|id| id.trim().to_string()).filter(|id| !id.is_empty());
+ *guard = user_id
+ .map(|id| id.trim().to_string())
+ .filter(|id| !id.is_empty());
}
/// Forget the signed-in user id.
diff --git a/crates/openhuman-session/src/lib.rs b/crates/openhuman-session/src/lib.rs
index 00453fa3e2..b046a8216b 100644
--- a/crates/openhuman-session/src/lib.rs
+++ b/crates/openhuman-session/src/lib.rs
@@ -33,8 +33,8 @@ pub(crate) mod test_support;
pub use cache::{CachedUser, CurrentUserCache};
pub use client::{ClientHeaders, FetchMeError, SessionClient, SessionClientError};
pub use credential::{
- decode_jwt_exp, jwt_is_live, user_id_from_jwt_claims, user_id_from_profile_payload,
- Credential, CredentialKind,
+ decode_jwt_exp, jwt_is_live, user_id_from_jwt_claims, user_id_from_profile_payload, Credential,
+ CredentialKind,
};
pub use link::{CoreAuthState, CoreLink};
pub use manager::{SessionError, SessionEvent, SessionManager, SessionState};
diff --git a/crates/openhuman-session/src/link_tests.rs b/crates/openhuman-session/src/link_tests.rs
index 53a444482a..147fbc6202 100644
--- a/crates/openhuman-session/src/link_tests.rs
+++ b/crates/openhuman-session/src/link_tests.rs
@@ -24,7 +24,8 @@ fn core_auth_state_parses_camel_case_and_kind() {
assert_eq!(state.kind(), Some(CredentialKind::ApiKey));
assert_eq!(state.expires_at.as_deref(), Some("2100-01-01T00:00:00Z"));
- let signed_out: CoreAuthState = serde_json::from_value(json!({ "isAuthenticated": false })).unwrap();
+ let signed_out: CoreAuthState =
+ serde_json::from_value(json!({ "isAuthenticated": false })).unwrap();
assert_eq!(signed_out.kind(), None);
}
@@ -32,9 +33,14 @@ fn core_auth_state_parses_camel_case_and_kind() {
async fn push_credential_sends_kind_user_id_and_user() {
let core = FakeCore::new("http://backend");
let credential = Credential::session("jwt-1");
- let state = push_credential(core.as_ref(), &credential, Some(" u1 "), Some(&json!({ "id": "u1" })))
- .await
- .unwrap();
+ let state = push_credential(
+ core.as_ref(),
+ &credential,
+ Some(" u1 "),
+ Some(&json!({ "id": "u1" })),
+ )
+ .await
+ .unwrap();
assert!(state.is_authenticated);
assert_eq!(state.user_id.as_deref(), Some("u1"));
let (method, params) = core.calls().pop().unwrap();
@@ -60,7 +66,9 @@ async fn push_credential_omits_blank_user_id_and_missing_user() {
#[tokio::test]
async fn clear_credential_passes_kind_or_nothing() {
let core = FakeCore::new("http://backend");
- clear_credential(core.as_ref(), Some(CredentialKind::ApiKey)).await.unwrap();
+ clear_credential(core.as_ref(), Some(CredentialKind::ApiKey))
+ .await
+ .unwrap();
clear_credential(core.as_ref(), None).await.unwrap();
let calls = core.calls();
assert_eq!(calls[0].0, AUTH_CLEAR_CREDENTIAL);
@@ -75,8 +83,14 @@ async fn session_token_and_backend_url_unwrap_envelopes() {
push_credential(core.as_ref(), &Credential::session("jwt-2"), None, None)
.await
.unwrap();
- assert_eq!(core_session_token(core.as_ref()).await.unwrap().as_deref(), Some("jwt-2"));
- assert_eq!(resolve_backend_url(core.as_ref()).await.unwrap(), "http://backend/");
+ assert_eq!(
+ core_session_token(core.as_ref()).await.unwrap().as_deref(),
+ Some("jwt-2")
+ );
+ assert_eq!(
+ resolve_backend_url(core.as_ref()).await.unwrap(),
+ "http://backend/"
+ );
}
#[tokio::test]
diff --git a/crates/openhuman-session/src/manager.rs b/crates/openhuman-session/src/manager.rs
index 59914a344a..e871eee797 100644
--- a/crates/openhuman-session/src/manager.rs
+++ b/crates/openhuman-session/src/manager.rs
@@ -16,8 +16,8 @@ use tokio::task::JoinHandle;
use crate::cache::{CachedUser, CurrentUserCache};
use crate::client::{ClientHeaders, FetchMeError, SessionClient};
use crate::credential::{
- decode_jwt_exp, jwt_is_live, user_id_from_jwt_claims, user_id_from_profile_payload,
- Credential, CredentialKind,
+ decode_jwt_exp, jwt_is_live, user_id_from_jwt_claims, user_id_from_profile_payload, Credential,
+ CredentialKind,
};
use crate::identity;
use crate::link::{self, CoreAuthState, CoreLink};
@@ -141,7 +141,8 @@ impl<L: CoreLink> SessionManager<L> {
}
}
let client = Arc::new(
- SessionClient::new(&base, &self.headers).map_err(|e| SessionError::Backend(e.to_string()))?,
+ SessionClient::new(&base, &self.headers)
+ .map_err(|e| SessionError::Backend(e.to_string()))?,
);
log::debug!("{LOG_PREFIX} session client bound to {}", client.base_url());
*self.client.lock().unwrap_or_else(|p| p.into_inner()) = Some(Arc::clone(&client));
@@ -180,7 +181,10 @@ impl<L: CoreLink> SessionManager<L> {
}
/// Exchange a one-time login token for a JWT and store it.
- pub async fn login_with_token(self: &Arc<Self>, login_token: &str) -> Result<SessionState, SessionError> {
+ pub async fn login_with_token(
+ self: &Arc<Self>,
+ login_token: &str,
+ ) -> Result<SessionState, SessionError> {
let client = self.client().await?;
let jwt = client
.consume_login_token(login_token)
@@ -223,7 +227,9 @@ impl<L: CoreLink> SessionManager<L> {
}
let now = chrono::Utc::now();
- if decode_jwt_exp(&credential.secret).is_some() && jwt_is_live(&credential.secret, now).is_none() {
+ if decode_jwt_exp(&credential.secret).is_some()
+ && jwt_is_live(&credential.secret, now).is_none()
+ {
return Err(SessionError::Expired);
}
@@ -233,13 +239,19 @@ impl<L: CoreLink> SessionManager<L> {
let user_id = user_id_from_profile_payload(&me)
.or_else(|| user.as_ref().and_then(user_id_from_profile_payload))
.or_else(|| user_id_from_jwt_claims(&credential.secret));
- log::info!("{LOG_PREFIX} session JWT verified via GET /auth/me on {}", client.base_url());
- self.push(&credential, user_id.as_deref(), Some(&me)).await?;
+ log::info!(
+ "{LOG_PREFIX} session JWT verified via GET /auth/me on {}",
+ client.base_url()
+ );
+ self.push(&credential, user_id.as_deref(), Some(&me))
+ .await?;
self.cache.seed(&client, &credential, me);
self.changed().await
}
Err(FetchMeError::Rejected(reason)) => {
- log::warn!("{LOG_PREFIX} GET /auth/me rejected the session token; not stored: {reason}");
+ log::warn!(
+ "{LOG_PREFIX} GET /auth/me rejected the session token; not stored: {reason}"
+ );
Err(SessionError::Rejected(reason))
}
Err(error) => {
@@ -257,7 +269,8 @@ impl<L: CoreLink> SessionManager<L> {
"{LOG_PREFIX} backend unreachable ({reason}); storing pending session for user_id={user_id} and revalidating in the background"
);
let pending = json!({ PENDING_BACKEND_VALIDATION_FIELD: true });
- self.push(&credential, Some(&user_id), Some(&pending)).await?;
+ self.push(&credential, Some(&user_id), Some(&pending))
+ .await?;
self.cache.forget();
self.spawn_revalidation(credential);
self.changed().await
@@ -300,7 +313,10 @@ impl<L: CoreLink> SessionManager<L> {
let user_id = user_id_from_profile_payload(&me)
.or_else(|| user_id_from_jwt_claims(&credential.secret));
log::info!("{LOG_PREFIX} pending session confirmed via GET /auth/me");
- if let Err(e) = manager.push(&credential, user_id.as_deref(), Some(&me)).await {
+ if let Err(e) = manager
+ .push(&credential, user_id.as_deref(), Some(&me))
+ .await
+ {
log::warn!("{LOG_PREFIX} failed to store revalidated session: {e}");
}
manager.cache.seed(&client, &credential, me);
@@ -310,8 +326,12 @@ impl<L: CoreLink> SessionManager<L> {
return;
}
Err(FetchMeError::Rejected(reason)) => {
- log::warn!("{LOG_PREFIX} pending session rejected by backend; clearing: {reason}");
- manager.clear_session_credential("pending-revalidation").await;
+ log::warn!(
+ "{LOG_PREFIX} pending session rejected by backend; clearing: {reason}"
+ );
+ manager
+ .clear_session_credential("pending-revalidation")
+ .await;
return;
}
Err(error) => {
@@ -329,7 +349,9 @@ impl<L: CoreLink> SessionManager<L> {
}
async fn clear_session_credential(&self, source: &str) {
- if let Err(e) = link::clear_credential(self.link.as_ref(), Some(CredentialKind::Session)).await {
+ if let Err(e) =
+ link::clear_credential(self.link.as_ref(), Some(CredentialKind::Session)).await
+ {
log::warn!("{LOG_PREFIX} failed to clear rejected session credential: {e}");
}
self.cache.forget();
@@ -385,7 +407,11 @@ impl<L: CoreLink> SessionManager<L> {
self.current_user_for(&core, force).await
}
- async fn current_user_for(&self, core: &CoreAuthState, force: bool) -> Result<CachedUser, SessionError> {
+ async fn current_user_for(
+ &self,
+ core: &CoreAuthState,
+ force: bool,
+ ) -> Result<CachedUser, SessionError> {
if !core.is_authenticated {
return Ok(CachedUser {
user: None,
@@ -415,14 +441,19 @@ impl<L: CoreLink> SessionManager<L> {
// The shell (or a previous process) accepted this token
// while the backend was down; the confirmation just came in.
let user_id = cached.user.as_ref().and_then(user_id_from_profile_payload);
- if let Err(e) = self.push(&credential, user_id.as_deref(), cached.user.as_ref()).await {
+ if let Err(e) = self
+ .push(&credential, user_id.as_deref(), cached.user.as_ref())
+ .await
+ {
log::warn!("{LOG_PREFIX} failed to store confirmed pending session: {e}");
}
}
Ok(cached)
}
Err(FetchMeError::Rejected(reason)) => {
- log::warn!("{LOG_PREFIX} GET /auth/me rejected the stored session; signing out: {reason}");
+ log::warn!(
+ "{LOG_PREFIX} GET /auth/me rejected the stored session; signing out: {reason}"
+ );
self.clear_session_credential("auth/me").await;
Err(SessionError::Rejected(reason))
}
diff --git a/crates/openhuman-session/src/manager_tests.rs b/crates/openhuman-session/src/manager_tests.rs
index 4c04696d7c..2fb0980ac4 100644
--- a/crates/openhuman-session/src/manager_tests.rs
+++ b/crates/openhuman-session/src/manager_tests.rs
@@ -1,10 +1,10 @@
use super::*;
use crate::client::ClientHeaders;
+use crate::test_support::ENV_LOCK;
use crate::test_support::{
me_user, Backend, FakeCore, MeAnswer, EXPIRED_JWT, LIVE_JWT, LIVE_JWT_NO_SUB, LOCAL_TOKEN,
OPAQUE_TOKEN,
};
-use crate::test_support::ENV_LOCK;
use std::sync::Arc;
fn manager(core: &Arc<FakeCore>) -> Arc<SessionManager<FakeCore>> {
@@ -30,7 +30,10 @@ async fn login_with_token_exchanges_validates_and_stores() {
let state = m.login_with_token("tok").await.unwrap();
assert!(state.core.is_authenticated);
assert_eq!(state.core.user_id.as_deref(), Some("user-123"));
- assert_eq!(state.current_user.as_ref().unwrap()["email"], "[email protected]");
+ assert_eq!(
+ state.current_user.as_ref().unwrap()["email"],
+ );
assert!(!state.current_user_stale);
let stored = core.session().unwrap();
@@ -39,7 +42,10 @@ async fn login_with_token_exchanges_validates_and_stores() {
assert_eq!(stored.user_id.as_deref(), Some("user-123"));
assert_eq!(stored.user.unwrap()["_id"], "user-123");
assert_eq!(identity::peek_user_id().as_deref(), Some("user-123"));
- assert!(matches!(drain(&mut rx).await.as_slice(), [SessionEvent::Changed(_)]));
+ assert!(matches!(
+ drain(&mut rx).await.as_slice(),
+ [SessionEvent::Changed(_)]
+ ));
}
#[tokio::test]
@@ -52,7 +58,10 @@ async fn rejected_jwt_is_never_stored() {
Err(SessionError::Rejected(_))
));
assert_eq!(core.session(), None);
- assert!(!core.methods().iter().any(|m| m == link::AUTH_SET_CREDENTIAL));
+ assert!(!core
+ .methods()
+ .iter()
+ .any(|m| m == link::AUTH_SET_CREDENTIAL));
}
#[tokio::test]
@@ -91,7 +100,9 @@ async fn unreachable_backend_refuses_tokens_without_exp_or_subject() {
Err(SessionError::Transient(_))
));
assert_eq!(
- m.store_session_token(LIVE_JWT_NO_SUB, None).await.unwrap_err(),
+ m.store_session_token(LIVE_JWT_NO_SUB, None)
+ .await
+ .unwrap_err(),
SessionError::UserIdUnavailable
);
assert_eq!(core.session(), None);
@@ -102,8 +113,13 @@ async fn caller_supplied_user_id_rescues_a_subjectless_jwt_offline() {
let core = FakeCore::new("http://127.0.0.1:9");
let m = manager(&core);
let user = serde_json::json!({ "id": "from-caller" });
- m.store_session_token(LIVE_JWT_NO_SUB, Some(user)).await.unwrap();
- assert_eq!(core.session().unwrap().user_id.as_deref(), Some("from-caller"));
+ m.store_session_token(LIVE_JWT_NO_SUB, Some(user))
+ .await
+ .unwrap();
+ assert_eq!(
+ core.session().unwrap().user_id.as_deref(),
+ Some("from-caller")
+ );
m.cancel_revalidation();
}
@@ -134,7 +150,10 @@ async fn api_key_store_and_clear() {
assert_eq!(core.api_key.lock().unwrap().as_deref(), Some("sk-1"));
let state = m.clear_api_key().await.unwrap();
assert!(!state.core.is_authenticated);
- assert!(matches!(m.store_api_key("").await, Err(SessionError::Invalid(_))));
+ assert!(matches!(
+ m.store_api_key("").await,
+ Err(SessionError::Invalid(_))
+ ));
}
#[tokio::test]
@@ -165,10 +184,15 @@ async fn current_user_rejection_signs_out_and_emits_expired() {
let m = manager(&core);
m.login_with_token("tok").await.unwrap();
let mut rx = m.subscribe();
- assert!(matches!(m.current_user(true).await, Err(SessionError::Rejected(_))));
+ assert!(matches!(
+ m.current_user(true).await,
+ Err(SessionError::Rejected(_))
+ ));
assert_eq!(core.session(), None);
let events = drain(&mut rx).await;
- assert!(events.iter().any(|e| matches!(e, SessionEvent::Expired { source } if source == "auth/me")));
+ assert!(events
+ .iter()
+ .any(|e| matches!(e, SessionEvent::Expired { source } if source == "auth/me")));
assert!(events
.iter()
.any(|e| matches!(e, SessionEvent::Changed(s) if !s.core.is_authenticated)));
@@ -186,7 +210,10 @@ async fn current_user_serves_the_stored_user_stale_while_the_backend_is_down() {
let current = m.current_user(true).await.unwrap();
assert!(current.stale);
assert_eq!(current.user.unwrap()["_id"], "user-123");
- assert!(core.session().is_some(), "an outage must not sign the user out");
+ assert!(
+ core.session().is_some(),
+ "an outage must not sign the user out"
+ );
}
#[tokio::test]
@@ -203,7 +230,11 @@ async fn current_user_confirms_a_pending_session_once_the_backend_answers() {
let current = m.current_user(false).await.unwrap();
assert_eq!(current.user.as_ref().unwrap()["email"], "[email protected]");
let stored = core.session().unwrap();
- assert!(stored.user.unwrap().get(PENDING_BACKEND_VALIDATION_FIELD).is_none());
+ assert!(stored
+ .user
+ .unwrap()
+ .get(PENDING_BACKEND_VALIDATION_FIELD)
+ .is_none());
}
#[tokio::test]
@@ -244,10 +275,20 @@ async fn core_failures_surface_as_core_errors() {
#[test]
fn session_error_display_carries_stable_prefixes() {
- assert!(SessionError::Rejected("x".into()).to_string().starts_with("REJECTED:"));
+ assert!(SessionError::Rejected("x".into())
+ .to_string()
+ .starts_with("REJECTED:"));
assert!(SessionError::Expired.to_string().starts_with("EXPIRED:"));
- assert!(SessionError::Transient("x".into()).to_string().starts_with("TRANSIENT:"));
- assert!(SessionError::UserIdUnavailable.to_string().starts_with("USER_ID_UNAVAILABLE:"));
- assert!(SessionError::ConsumeFailed("x".into()).to_string().starts_with("CONSUME_FAILED:"));
- assert!(SessionError::Core("x".into()).to_string().starts_with("CORE:"));
+ assert!(SessionError::Transient("x".into())
+ .to_string()
+ .starts_with("TRANSIENT:"));
+ assert!(SessionError::UserIdUnavailable
+ .to_string()
+ .starts_with("USER_ID_UNAVAILABLE:"));
+ assert!(SessionError::ConsumeFailed("x".into())
+ .to_string()
+ .starts_with("CONSUME_FAILED:"));
+ assert!(SessionError::Core("x".into())
+ .to_string()
+ .starts_with("CORE:"));
}