Skip to main content

capsule_sdk/
auth.rs

1//! SDK-owned authentication: the session/token store and the auto-refresh engine.
2//!
3//! This is the "SDK owns the complete user flow" foundation: native apps call
4//! [`AuthClient::login`], then hand every request through [`Session::execute`], then
5//! [`Session::logout`] — they never juggle raw access tokens. The store keeps the access + refresh
6//! token pair and:
7//!
8//! - runs a quick **asynchronous pre-flight expiry check** before each request and
9//!   refreshes proactively when the access token is within the refresh skew of
10//!   expiry (`Session::valid_access_token`);
11//! - **single-flights** refreshes — concurrent callers that all see a stale token
12//!   coalesce onto one network refresh (`Session::ensure_refreshed`);
13//! - **retries once on `401`**: an authenticated request that the server rejects is
14//!   refreshed once and replayed, so a token that expired between the pre-flight
15//!   check and the wire is transparently recovered.
16//!
17//! It is hand-rolled over `reqwest` (rustls only) against the server's own
18//! `/v1/auth/{register,login,refresh,logout}`. It does not
19//! route through the generated client, but the reason is no longer that spargen is
20//! parked — spargen ships and generates the typed surface today. What lives here
21//! is token *orchestration*: the pre-flight refresh, the `401`-retry-once replay, and
22//! the session store they mutate. That is deliberately outside generated code, which
23//! owns parsing and serialization and nothing else. Auth requests are
24//! [`crate::net::RetryClass::Interactive`]; the full backoff ladder lives in [`crate::net`], but
25//! the `401`-retry-once and pre-flight
26//! refresh here are the parts the session store owns.
27//!
28//! The OIDC legs ([`AuthClient::begin_oidc_login`] and
29//! [`AuthClient::complete_oidc_login`]) are **not** hand-rolled: neither is token
30//! orchestration, so the exemption above does not cover them, and they call the generated
31//! [`rest::Client`] — every body and every response parsed by generated code, with only the
32//! mapping into [`LoginOutcome`] and [`AuthError`] written here. The browser leg between the
33//! two is the platform's: a loopback listener on the CLI, `ASWebAuthenticationSession` on iOS.
34//! The ceremony is bound to the client that began it: the begin leg mints a secret the
35//! [`OidcAuthorization`] keeps and sends only its hash, and the complete leg presents the secret
36//! and refuses a redirect carrying a `state` it did not begin (issue #517).
37//!
38//! The device-grant legs (RFC 8628, issue #635: [`AuthClient::begin_oidc_device_login`] and
39//! [`AuthClient::poll_oidc_device_login`]) are the same kind of thing: two generated calls, the
40//! begin binding the ceremony to this client the same way, and the poll answering
41//! [`OidcDevicePoll`] — keep polling, slow down, or the [`LoginOutcome`] a password login gives.
42//! The wait between polls is the caller's; these send one request each.
43//!
44//! [`AuthClient::sign_in_options`] reads which sign-ins the server offers from its `server-info`
45//! record, also through the generated client, so a client can leave out a password form the
46//! server would refuse (`auth.password_disabled`, issue #1004). It is advice: the server's own
47//! `403 error.auth.password_disabled` stays the authority.
48//!
49//! ## Testing
50//!
51//! The wire flows (login/refresh/logout, `401` recovery, error mapping) are proven
52//! against a focused in-process mock HTTP server rather than a booted server: booting one
53//! from this crate would invert the dependency — the *server* dev-depends on this crate, not
54//! the other way round — and a mock keeps every wire case deterministic. The round
55//! trip against the real router, over a real socket, lives where the dependency points:
56//! `capsule-server/tests/sdk_client.rs`. The pre-flight and single-flight guarantees are proven with an injected
57//! [`Clock`] — no sleeps, no wall-clock dependence.
58
59use std::sync::Arc;
60
61use capsule_core::crypto::primitives::PROTOCOL_VERSION;
62use capsule_i18n::error_codes;
63use jiff::Timestamp;
64use secrecy::{ExposeSecret, SecretString};
65use serde::{Deserialize, Serialize};
66use tokio::sync::{Mutex, RwLock};
67use tracing::instrument;
68
69use crate::client::absent_unless;
70use crate::net::negotiation::{self, UpgradeRequired};
71use crate::rest;
72
73/// Every request this module sends goes through the protocol window (issue #674): every
74/// response's window is latched, and a `426` is [`AuthError::UpgradeRequired`] rather than a
75/// status a caller has to recognise.
76///
77/// Two strengths, by what the request is for:
78///
79/// - [`send_negotiated`](NegotiatedSend::send_negotiated) — the data requests a [`Session`]
80///   executes on behalf of the upload, album, verify and upgrade paths: a write the latched
81///   window refuses also never leaves.
82/// - [`send_screened`](NegotiatedSend::send_screened) — the session's own upkeep (sign-in,
83///   second factor, registration, refresh, sign-out): never refused here, only by the server's
84///   own `426`. Reads keep working against any server (Versioning — Update Policy), and a read
85///   needs a session; refusing a refresh because the advisory build floor is above this build
86///   would make every read fail the moment its token expired.
87trait NegotiatedSend {
88    /// [`reqwest::RequestBuilder::send`], pre-flighted against the latched window and screened.
89    async fn send_negotiated(self) -> Result<reqwest::Response, AuthError>;
90    /// [`reqwest::RequestBuilder::send`], screened only.
91    async fn send_screened(self) -> Result<reqwest::Response, AuthError>;
92}
93
94impl NegotiatedSend for reqwest::RequestBuilder {
95    async fn send_negotiated(self) -> Result<reqwest::Response, AuthError> {
96        Ok(negotiation::send_negotiated(self).await?)
97    }
98
99    async fn send_screened(self) -> Result<reqwest::Response, AuthError> {
100        Ok(negotiation::send_screened(self).await?)
101    }
102}
103
104impl From<negotiation::SendError> for AuthError {
105    fn from(error: negotiation::SendError) -> Self {
106        match error {
107            negotiation::SendError::Upgrade(refusal) => refusal.into(),
108            negotiation::SendError::Transport(error) => Self::Transport(error),
109        }
110    }
111}
112
113/// Default pre-flight refresh window: refresh once the access token is within this
114/// many seconds of expiry, so an in-flight request never races the boundary.
115const DEFAULT_REFRESH_SKEW_SECS: i64 = 30;
116
117// ─── Clock seam ──────────────────────────────────────────────────────────────
118
119/// Wall-clock seam so token-expiry logic is deterministically testable.
120///
121/// Production uses [`SystemClock`]; tests inject a controllable clock to exercise
122/// pre-flight refresh and single-flight without sleeping.
123pub trait Clock: Send + Sync {
124    /// The current wall-clock instant.
125    fn now(&self) -> Timestamp;
126}
127
128/// The production [`Clock`], backed by the system wall clock.
129#[derive(Debug, Clone, Copy, Default)]
130pub struct SystemClock;
131
132impl Clock for SystemClock {
133    fn now(&self) -> Timestamp {
134        Timestamp::now()
135    }
136}
137
138// ─── Errors ──────────────────────────────────────────────────────────────────
139
140/// Everything the auth flows can fail with. Callers switch on the typed variant
141/// (never a bare HTTP status); [`AuthError::error_code`] yields the stable
142/// `error.*` catalog code for client localization where one applies.
143#[derive(Debug, thiserror::Error)]
144pub enum AuthError {
145    /// Transport-level failure (DNS, TLS, connection, timeout).
146    #[error("network transport error: {0}")]
147    Transport(#[from] reqwest::Error),
148    /// The server will not take this client's writes: it answered `426`, or the window it
149    /// advertised already refuses this build (issue #674). Update the app.
150    #[error(transparent)]
151    UpgradeRequired(Box<UpgradeRequired>),
152    /// The configured base URL could not be parsed.
153    #[error("invalid base URL {url:?}: {reason}")]
154    InvalidBaseUrl {
155        /// The offending URL.
156        url: String,
157        /// Why it was rejected.
158        reason: String,
159    },
160    /// Login was rejected: the credentials were wrong.
161    #[error("invalid credentials")]
162    InvalidCredentials,
163    /// Login was rejected: the account is temporarily locked.
164    #[error("account locked after repeated failed logins")]
165    AccountLocked,
166    /// The server asked the client to back off.
167    ///
168    /// One variant for every `429`, because the client's response is the same: wait
169    /// `retry_after_secs` and try again. `code` keeps which cause the server named (a spent
170    /// budget `error.auth.rate_limited`, a full limiter `error.auth.registration_at_capacity`),
171    /// so [`AuthError::error_code`] renders the server's own message.
172    #[error("rate limited; retry after {retry_after_secs}s")]
173    RateLimited {
174        /// Seconds to wait before retrying, from the `Retry-After` header.
175        retry_after_secs: u64,
176        /// The server's `error.*` code, when it sent one; `error.auth.rate_limited` otherwise.
177        code: Option<String>,
178    },
179    /// The session is gone (refresh token expired or revoked). The user must
180    /// re-authenticate interactively.
181    #[error("session expired or revoked; interactive re-authentication required")]
182    SessionExpired,
183    /// An authenticated operation was attempted with no active session.
184    #[error("no active session; call login() first")]
185    NotAuthenticated,
186
187    /// A code is needed and this caller cannot ask for one.
188    ///
189    /// Only produced by [`LoginOutcome::into_session`]: the login itself answers a
190    /// [`LoginOutcome`], because a second factor is the system working rather than a failure.
191    #[error("this account requires a second factor; complete the sign-in with a code")]
192    SecondFactorRequired,
193
194    /// The server has no identity provider (`error.auth.oidc_not_configured`).
195    ///
196    /// A client that read `auth.oidc: null` from `server-info` never sees this; one that offered
197    /// the option anyway does.
198    #[error("single sign-on is not configured on this server")]
199    OidcNotConfigured,
200    /// The redirect URI this client asked for is not one the server admits
201    /// (`error.auth.oidc_redirect_invalid`). A client or deployment misconfiguration.
202    #[error("the server will not send a person back to this redirect URI")]
203    OidcRedirectInvalid,
204    /// The callback was refused: the ceremony expired or was replayed, the provider refused the
205    /// exchange, or the ID token failed a check. Every one means "start the sign-in again", so
206    /// they are one variant; `code` says which for a log line.
207    #[error("the sign-in through the identity provider was refused ({})", code.as_deref().unwrap_or("no code"))]
208    OidcRejected {
209        /// The server's `error.auth.oidc_*` code, when it sent one.
210        code: Option<String>,
211    },
212    /// The identity provider asserted an address that already has a local account
213    /// (`error.auth.oidc_address_taken`). Never linked: the person signs in with that account's
214    /// password instead.
215    #[error("an account with that address already exists; sign in with its password")]
216    OidcAddressTaken,
217    /// The server's identity provider does not offer the device authorization grant
218    /// (`error.auth.oidc_device_unsupported`): sign in with the browser flow instead.
219    #[error("the identity provider does not offer signing in without a browser")]
220    OidcDeviceUnsupported,
221    /// The person declined the device sign-in at the identity provider
222    /// (`error.auth.oidc_device_denied`).
223    #[error("the sign-in was declined at the identity provider")]
224    OidcDeviceDenied,
225    /// The device sign-in is over: expired, already used, or not this client's
226    /// (`error.auth.oidc_device_expired`). Start again.
227    #[error("the sign-in code expired or was already used")]
228    OidcDeviceExpired,
229    /// The generated client could not reach the server, or could not build the request.
230    ///
231    /// The generated client classifies its transport failures itself (DNS, connection, TLS,
232    /// timeout, redirect policy) and they are not `reqwest::Error`s, so they cannot ride
233    /// [`AuthError::Transport`]; the class and the endpoint are what a caller acts on.
234    #[error("could not reach {endpoint}: {detail}")]
235    Network {
236        /// Which auth endpoint was being reached.
237        endpoint: &'static str,
238        /// The generated client's own description.
239        detail: String,
240    },
241    /// A server response the client does not model.
242    #[error("unexpected {status} response from {endpoint}: {detail}")]
243    Unexpected {
244        /// HTTP status code.
245        status: u16,
246        /// Which auth endpoint produced it.
247        endpoint: &'static str,
248        /// English detail message from the server body, if any.
249        detail: String,
250        /// Stable `error.*` catalog code from the server body, if any.
251        code: Option<String>,
252    },
253    /// A success response whose body did not match the token contract.
254    #[error("malformed server response from {endpoint}: {reason}")]
255    MalformedResponse {
256        /// Which auth endpoint produced it.
257        endpoint: &'static str,
258        /// What was wrong with the body.
259        reason: String,
260    },
261}
262
263impl From<UpgradeRequired> for AuthError {
264    fn from(refusal: UpgradeRequired) -> Self {
265        Self::UpgradeRequired(Box::new(refusal))
266    }
267}
268
269impl AuthError {
270    /// The stable `error.*` catalog code a client localizes, when one applies.
271    ///
272    /// The English [`Display`](std::fmt::Display) form is the developer/log detail;
273    /// clients render a localized high-level message from this code (mirrors the
274    /// server's `ApiError { error, code }` contract).
275    pub fn error_code(&self) -> Option<&str> {
276        match self {
277            Self::InvalidCredentials => Some(error_codes::AUTH_INVALID_CREDENTIALS),
278            Self::RateLimited { code, .. } => {
279                Some(code.as_deref().unwrap_or(error_codes::AUTH_RATE_LIMITED))
280            }
281            Self::OidcNotConfigured => Some(error_codes::AUTH_OIDC_NOT_CONFIGURED),
282            Self::OidcRedirectInvalid => Some(error_codes::AUTH_OIDC_REDIRECT_INVALID),
283            Self::OidcAddressTaken => Some(error_codes::AUTH_OIDC_ADDRESS_TAKEN),
284            Self::OidcDeviceUnsupported => Some(error_codes::AUTH_OIDC_DEVICE_UNSUPPORTED),
285            Self::OidcDeviceDenied => Some(error_codes::AUTH_OIDC_DEVICE_DENIED),
286            Self::OidcDeviceExpired => Some(error_codes::AUTH_OIDC_DEVICE_EXPIRED),
287            Self::OidcRejected { code } | Self::Unexpected { code, .. } => code.as_deref(),
288            Self::UpgradeRequired(refusal) => Some(refusal.error_code()),
289            _ => None,
290        }
291    }
292}
293
294/// Which auth endpoint a wire error came from — drives status→variant mapping.
295#[derive(Clone, Copy)]
296enum Endpoint {
297    Register,
298    Login,
299    VerifyTotp,
300    Refresh,
301    Logout,
302    OidcAuthorize,
303    OidcCallback,
304    OidcDevice,
305    OidcDevicePoll,
306    ServerInfo,
307}
308
309impl Endpoint {
310    fn name(self) -> &'static str {
311        match self {
312            Self::Register => "register",
313            Self::Login => "login",
314            Self::VerifyTotp => "login/verify-totp",
315            Self::Refresh => "refresh",
316            Self::Logout => "logout",
317            Self::OidcAuthorize => "oidc/authorize",
318            Self::OidcCallback => "oidc/callback",
319            Self::OidcDevice => "oidc/device",
320            Self::OidcDevicePoll => "oidc/device/poll",
321            Self::ServerInfo => "server-info",
322        }
323    }
324
325    /// What a `401` from this endpoint means.
326    fn unauthorized_error(self, code: Option<String>) -> AuthError {
327        match self {
328            // Registration does not authenticate an existing session, so a `401` from
329            // it is not a real ceremony outcome; treat it as a credential rejection.
330            Self::Register | Self::Login => AuthError::InvalidCredentials,
331            // `VerifyTotp` is here rather than beside `Login`, and it is not an oversight that
332            // it reads the same as a refresh: a `401` completing a second factor means the
333            // challenge expired or the code did not verify, and both send the caller back to
334            // the password — which is what `SessionExpired` says. Neither is a *credential*
335            // rejection, because the password already verified to get this far.
336            Self::VerifyTotp | Self::Refresh | Self::Logout => AuthError::SessionExpired,
337            // The callback's three `401`s — a spent state, a refused exchange, a refused token —
338            // all mean "start again"; the code is kept for the log. The authorize declares no
339            // `401`, so one from it is a server this client does not model.
340            // The poll's remaining `401`s — a refused exchange, a refused token — are the
341            // callback's and mean the same; its denial and expiry are matched by code first.
342            Self::OidcCallback | Self::OidcDevicePoll => AuthError::OidcRejected { code },
343            // The record is unauthenticated, so a `401` from it is a server this client does not
344            // model either.
345            Self::OidcAuthorize | Self::OidcDevice | Self::ServerInfo => AuthError::Unexpected {
346                status: 401,
347                endpoint: self.name(),
348                detail: String::new(),
349                code,
350            },
351        }
352    }
353
354    /// The typed refusals only the OIDC endpoints make, matched on the catalog code.
355    fn oidc_refusal(self, status: u16, code: Option<&str>) -> Option<AuthError> {
356        match (self, status, code) {
357            (
358                Self::OidcAuthorize | Self::OidcDevice,
359                404,
360                Some(error_codes::AUTH_OIDC_NOT_CONFIGURED),
361            ) => Some(AuthError::OidcNotConfigured),
362            (Self::OidcAuthorize, 400, Some(error_codes::AUTH_OIDC_REDIRECT_INVALID)) => {
363                Some(AuthError::OidcRedirectInvalid)
364            }
365            (
366                Self::OidcCallback | Self::OidcDevicePoll,
367                409,
368                Some(error_codes::AUTH_OIDC_ADDRESS_TAKEN),
369            ) => Some(AuthError::OidcAddressTaken),
370            (Self::OidcDevice, 404, Some(error_codes::AUTH_OIDC_DEVICE_UNSUPPORTED)) => {
371                Some(AuthError::OidcDeviceUnsupported)
372            }
373            (Self::OidcDevicePoll, 401, Some(error_codes::AUTH_OIDC_DEVICE_DENIED)) => {
374                Some(AuthError::OidcDeviceDenied)
375            }
376            (Self::OidcDevicePoll, 401, Some(error_codes::AUTH_OIDC_DEVICE_EXPIRED)) => {
377                Some(AuthError::OidcDeviceExpired)
378            }
379            _ => None,
380        }
381    }
382}
383
384// ─── Wire types ──────────────────────────────────────────────────────────────
385
386#[derive(Serialize)]
387struct LoginRequestBody<'a> {
388    email: &'a str,
389    password: &'a str,
390    /// Advisory device-cohort hash. Rides the session-creation body
391    /// only; **omitted entirely when absent** so "absent stays legal" is literal on
392    /// the wire (no `null` field). Never read by any authorization decision.
393    #[serde(skip_serializing_if = "Option::is_none")]
394    cohort_hash: Option<&'a str>,
395}
396
397/// The registration body: an address and a password, and nothing else.
398///
399/// It carries no username, display name or advisory cohort hash: the server
400/// takes none of them and its body is **strict**, so a field kept for old times' sake would be a
401/// `422` rather than a value quietly ignored.
402#[derive(Serialize)]
403struct RegisterRequestBody<'a> {
404    email: &'a str,
405    password: &'a str,
406}
407
408/// The body that completes a sign-in with a code.
409///
410/// The advisory cohort rides **here** rather than on the login, because this is the request that
411/// opens the session: a second-factor sign-in that sent its cohort on the first leg would attach
412/// it to a session that does not exist yet, and would land in the devices view ungrouped.
413#[derive(Serialize)]
414struct VerifyTotpRequestBody<'a> {
415    mfa_token: &'a str,
416    totp_code: &'a str,
417    #[serde(skip_serializing_if = "Option::is_none")]
418    cohort_hash: Option<&'a str>,
419}
420
421/// The `202 Accepted` body: a half-finished sign-in.
422#[derive(Deserialize)]
423struct SecondFactorChallengeBody {
424    mfa_token: String,
425    expires_by: u64,
426}
427
428#[derive(Serialize)]
429struct RefreshRequestBody<'a> {
430    refresh_token: &'a str,
431}
432
433/// The server's `TokenResponse`. `token_type` and any other
434/// fields are ignored; `expires_by` is the **absolute** Unix-seconds expiry of the
435/// access token.
436#[derive(Deserialize)]
437struct TokenResponseBody {
438    access_token: String,
439    refresh_token: String,
440    expires_by: u64,
441}
442
443/// The server's `ApiError` shape.
444#[derive(Deserialize)]
445struct ApiErrorBody {
446    #[serde(default)]
447    error: String,
448    #[serde(default)]
449    code: Option<String>,
450}
451
452// ─── Token store ─────────────────────────────────────────────────────────────
453
454/// The stored token pair for an active session.
455#[derive(Clone)]
456struct TokenSet {
457    access_token: SecretString,
458    refresh_token: SecretString,
459    /// Absolute instant the access token expires (server `expires_by`).
460    access_expires_at: Timestamp,
461}
462
463impl TokenSet {
464    fn from_wire(endpoint: Endpoint, body: TokenResponseBody) -> Result<Self, AuthError> {
465        let access_expires_at = Timestamp::from_second(body.expires_by as i64).map_err(|e| {
466            AuthError::MalformedResponse {
467                endpoint: endpoint.name(),
468                reason: format!("invalid expires_by {}: {e}", body.expires_by),
469            }
470        })?;
471        Ok(Self {
472            access_token: body.access_token.into(),
473            refresh_token: body.refresh_token.into(),
474            access_expires_at,
475        })
476    }
477}
478
479/// A session's token material for handing to the platform's secure storage so a
480/// session survives process restarts. The SDK owns the store and refresh logic;
481/// the platform owns only the at-rest bytes.
482#[derive(Clone)]
483pub struct PersistedSession {
484    /// The current access token.
485    pub access_token: SecretString,
486    /// The current refresh token.
487    pub refresh_token: SecretString,
488    /// Absolute access-token expiry, Unix seconds (server `expires_by`).
489    pub access_expires_at_unix: i64,
490}
491
492// ─── Endpoints ───────────────────────────────────────────────────────────────
493
494/// Precomputed absolute endpoint URLs derived from the auth base URL.
495struct AuthEndpoints {
496    register: String,
497    login: String,
498    verify_totp: String,
499    refresh: String,
500    logout: String,
501    /// The server root the generated client is built on, for the operations that go through
502    /// it: the auth base with its `/v1/auth` suffix removed, or the base itself when it carries
503    /// none (the in-crate mock serves the generated paths at its root).
504    server_root: String,
505}
506
507impl AuthEndpoints {
508    fn from_base(base_url: &str) -> Result<Self, AuthError> {
509        // Validate scheme/host up front so a bad base fails at construction, not at
510        // first request; we then build paths by concatenation for predictability.
511        reqwest::Url::parse(base_url).map_err(|e| AuthError::InvalidBaseUrl {
512            url: base_url.to_string(),
513            reason: e.to_string(),
514        })?;
515        let trimmed = base_url.trim_end_matches('/');
516        Ok(Self {
517            register: format!("{trimmed}/register"),
518            login: format!("{trimmed}/login"),
519            verify_totp: format!("{trimmed}/login/verify-totp"),
520            refresh: format!("{trimmed}/refresh"),
521            logout: format!("{trimmed}/logout"),
522            server_root: trimmed
523                .strip_suffix("/v1/auth")
524                .unwrap_or(trimmed)
525                .to_owned(),
526        })
527    }
528}
529
530/// A begun sign-in through the identity provider.
531///
532/// The platform sends the person to `authorization_url`, receives the provider's redirect at
533/// the `redirect_uri` it named, and hands this value with the redirect's `state` and `code` to
534/// [`AuthClient::complete_oidc_login`]. Good once, and until `expires_by`.
535///
536/// It is the client's half of the ceremony, and the client must keep it — in memory, or in the
537/// platform's secure storage where the browser leg can outlive the process — because the
538/// callback is refused without its `binding` (issue #517). Never send any of it anywhere but
539/// back to [`AuthClient::complete_oidc_login`].
540///
541/// No `Debug`: the state is the key to the pending ceremony, the URL carries it, and the binding
542/// is the secret that proves this client began it.
543pub struct OidcAuthorization {
544    /// Where to send the person. Carries the whole authorization request in its query.
545    pub authorization_url: String,
546    /// The `state` the provider's redirect will echo.
547    pub state: SecretString,
548    /// The secret binding the ceremony to this client: 256 random bits, unpadded base64url.
549    ///
550    /// Only its S256 hash went to the server, at the authorize; the callback presents the
551    /// secret itself, so a `state` and `code` that some other client began — an attacker's,
552    /// carried to this one — cannot be completed here.
553    pub binding: SecretString,
554    /// The absolute Unix-seconds instant the ceremony stops being redeemable.
555    pub expires_by: u64,
556}
557
558/// How much a `slow_down` raises a device sign-in's polling interval by (RFC 8628 §3.5). The
559/// server raises its own copy by the same amount, which is why the new interval is never sent.
560pub const DEVICE_SLOW_DOWN_STEP_SECS: u64 = 5;
561
562/// A begun device sign-in through the identity provider (RFC 8628, issue #635).
563///
564/// The platform shows the person `user_code` and `verification_uri` — or renders
565/// `verification_uri_complete` as a link or QR code — and polls
566/// [`AuthClient::poll_oidc_device_login`] with this value, waiting `interval_secs` before the
567/// first poll and between every poll, until it answers something other than
568/// [`OidcDevicePoll::Pending`] or `expires_by` passes. On [`OidcDevicePoll::SlowDown`], call
569/// [`slow_down`](Self::slow_down) before waiting again.
570///
571/// Keep it as an [`OidcAuthorization`] is kept: the `binding` is what the server checks on every
572/// poll, and only its hash was sent. No `Debug`: the handle and the binding are a live credential.
573pub struct OidcDeviceAuthorization {
574    /// The handle the server polls the provider under. The server's own; not the device code.
575    pub handle: SecretString,
576    /// The secret binding the ceremony to this client: 256 random bits, unpadded base64url.
577    pub binding: SecretString,
578    /// The code the person types at the verification page. Show it exactly.
579    pub user_code: String,
580    /// Where the person goes, on any device with a browser, to type the code.
581    pub verification_uri: String,
582    /// The same address with the code already in it, when the provider offers one.
583    pub verification_uri_complete: Option<String>,
584    /// How many seconds to wait before each poll, raised by [`slow_down`](Self::slow_down).
585    pub interval_secs: u64,
586    /// The absolute Unix-seconds instant the ceremony stops being honoured.
587    pub expires_by: u64,
588}
589
590impl OidcDeviceAuthorization {
591    /// Raise the interval by [`DEVICE_SLOW_DOWN_STEP_SECS`], as RFC 8628 §3.5 requires on every
592    /// `slow_down` — the server did the same, so the two stay in step.
593    pub fn slow_down(&mut self) {
594        self.interval_secs = self
595            .interval_secs
596            .saturating_add(DEVICE_SLOW_DOWN_STEP_SECS);
597    }
598}
599
600/// What one device poll answered.
601pub enum OidcDevicePoll {
602    /// The person has not finished at the provider. Wait the interval and poll again.
603    Pending,
604    /// Polled too soon, or the provider asked to slow down. Call
605    /// [`OidcDeviceAuthorization::slow_down`], wait, and poll again.
606    SlowDown,
607    /// The sign-in finished: exactly what [`AuthClient::login`] answers.
608    Complete(LoginOutcome),
609}
610
611/// A fresh client binding for one OIDC ceremony: 256 random bits, unpadded base64url.
612fn fresh_oidc_binding() -> SecretString {
613    use base64::Engine as _;
614    let bytes = capsule_core::crypto::rng::random_array::<32>();
615    SecretString::from(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes))
616}
617
618/// The S256 hash of `binding` — unpadded base64url of its SHA-256 (RFC 7636 §4.2's derivation),
619/// the `binding_challenge` the authorize carries.
620fn oidc_binding_challenge(binding: &SecretString) -> String {
621    use base64::Engine as _;
622    use sha2::Digest as _;
623    let digest = sha2::Sha256::digest(binding.expose_secret().as_bytes());
624    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(digest)
625}
626
627/// How a server signs people in, as its `.well-known/capsule/server-info` record publishes it.
628///
629/// Advisory, by contract: the server refuses a password it does not accept with
630/// `403 error.auth.password_disabled` whatever a client read here, so this decides only what a
631/// client offers — never whether a request is safe to send.
632#[derive(Debug, Clone, PartialEq, Eq)]
633pub struct SignInOptions {
634    /// The server's canonical origin.
635    pub server_id: String,
636    /// Whether the server has an identity provider (`auth.oidc` is not `null`).
637    pub oidc: bool,
638    /// Whether the server refuses password registration and sign-in
639    /// (`auth.password_disabled`). A server that predates the switch omits the field, and a
640    /// missing field reads `false`: that server accepts passwords.
641    pub password_disabled: bool,
642}
643
644/// What a password login answered with.
645///
646/// Two variants because the server has two outcomes and says so with a status: `200` with a
647/// token pair, `202` with a challenge. Neither is a failure — an account having a second factor
648/// is the system working — which is why this is a value rather than an `AuthError` variant.
649///
650/// A caller that only supports passwords should match on this and say so, rather than treating
651/// the challenge as an error it cannot describe.
652///
653/// No `Debug`. [`Session`] holds live tokens and deliberately has none, and the challenge here is
654/// a credential in its own right — deriving one would put half a sign-in in any log line that
655/// formatted the value.
656pub enum LoginOutcome {
657    /// The account has no second factor, and this is its session.
658    Session(Session),
659    /// The password verified and a code is still needed.
660    SecondFactorRequired {
661        /// The challenge to present to
662        /// [`verify_second_factor`](AuthClient::verify_second_factor). Good once, and for five
663        /// minutes.
664        mfa_token: SecretString,
665        /// The absolute Unix-seconds instant the challenge stops being honoured.
666        expires_by: u64,
667    },
668}
669
670impl LoginOutcome {
671    /// The session, if the sign-in finished.
672    ///
673    /// A convenience for the callers that genuinely cannot prompt — an automated one, or a test
674    /// against an account known to have no second factor. It returns an error rather than
675    /// panicking, because "this account needs a code and I cannot ask for one" is a runtime
676    /// condition rather than a programming mistake.
677    ///
678    /// # Errors
679    ///
680    /// Returns [`AuthError::SecondFactorRequired`] when a code is needed.
681    pub fn into_session(self) -> Result<Session, AuthError> {
682        match self {
683            Self::Session(session) => Ok(session),
684            Self::SecondFactorRequired { .. } => Err(AuthError::SecondFactorRequired),
685        }
686    }
687}
688
689// ─── AuthClient (entry point) ────────────────────────────────────────────────
690
691/// The unauthenticated entry point: turns credentials (or a persisted session)
692/// into an authenticated [`Session`].
693#[derive(Clone)]
694pub struct AuthClient {
695    http: reqwest::Client,
696    base: Arc<AuthEndpoints>,
697    /// The generated client over the same transport, for the operations that are not token
698    /// orchestration (the OIDC legs).
699    rest: Arc<rest::Client>,
700    clock: Arc<dyn Clock>,
701    refresh_skew_secs: i64,
702    /// The advisory device-cohort hash to ride every session-creation request. `None` ⇒ nothing is
703    /// sent — the server behaves identically
704    /// (the cohort hash is advisory only). Computed by the platform app from its
705    /// primary identifier via [`crate::cohort`] and set with
706    /// [`with_cohort_hash`](AuthClient::with_cohort_hash).
707    cohort_hash: Option<Arc<str>>,
708}
709
710impl AuthClient {
711    /// Build a client against the auth base URL (e.g. `https://api.example.com/auth`).
712    pub fn new(base_url: &str) -> Result<Self, AuthError> {
713        // The SDK's one HTTP client: every request this client sends — and every request a
714        // `Session` built from it executes on behalf of the upload, album and verify paths —
715        // carries the protocol handshake the server's gate requires.
716        let http = crate::net::http_client().map_err(AuthError::Transport)?;
717        Self::from_parts(
718            base_url,
719            Arc::new(SystemClock),
720            http,
721            DEFAULT_REFRESH_SKEW_SECS,
722        )
723    }
724
725    /// Assemble a client from explicit parts (clock + HTTP client + skew). Used by
726    /// [`AuthClient::new`] and by tests that inject a controllable clock.
727    ///
728    /// `http` **must** come from [`crate::net::http_builder`] or [`crate::net::http_client`]: a
729    /// client built any other way sends no protocol handshake, and every gated route refuses it.
730    fn from_parts(
731        base_url: &str,
732        clock: Arc<dyn Clock>,
733        http: reqwest::Client,
734        refresh_skew_secs: i64,
735    ) -> Result<Self, AuthError> {
736        let base = AuthEndpoints::from_base(base_url)?;
737        // Executed on `http` (and so carrying its handshake headers), latching the window like
738        // the typed client (issue #674). The OIDC legs are session upkeep, so only the server's
739        // own `426` refuses them — see `NegotiatedSend`.
740        let backend: Arc<dyn rest::HttpBackend> = Arc::new(crate::client::Negotiate::observing(
741            crate::net::backend(http.clone()),
742        ));
743        let rest = crate::net::generated_client(backend, &base.server_root).map_err(|reason| {
744            AuthError::InvalidBaseUrl {
745                url: base_url.to_string(),
746                reason,
747            }
748        })?;
749        Ok(Self {
750            http,
751            base: Arc::new(base),
752            rest: Arc::new(rest),
753            clock,
754            refresh_skew_secs,
755            cohort_hash: None,
756        })
757    }
758
759    /// Attach the advisory device-cohort hash that rides every subsequent
760    /// session-creation request (login/register) from this client.
761    ///
762    /// The value is a lowercase-hex SHA-256 digest computed by the platform app from
763    /// its primary identifier and the account's `user_id`
764    /// ([`crate::cohort::compute_cohort_hash`]). It is a **grouping aid only** — the
765    /// server never reads it for any authorization decision. Not setting it
766    /// (the default) is fully legal: nothing is sent and the server behaves
767    /// identically.
768    #[must_use]
769    pub fn with_cohort_hash(mut self, cohort_hash: String) -> Self {
770        self.cohort_hash = Some(Arc::from(cohort_hash));
771        self
772    }
773
774    /// The advisory cohort hash this client rides, if configured.
775    fn cohort(&self) -> Option<&str> {
776        self.cohort_hash.as_deref()
777    }
778
779    /// Authenticate with email + password, returning an authenticated [`Session`].
780    ///
781    /// If a cohort hash is configured ([`with_cohort_hash`](AuthClient::with_cohort_hash))
782    /// it rides the request body; otherwise the field is omitted entirely.
783    #[instrument(skip_all)]
784    pub async fn login(&self, email: &str, password: &str) -> Result<LoginOutcome, AuthError> {
785        tracing::info!(
786            cohort_emitted = self.cohort().is_some(),
787            "authenticating via password login"
788        );
789        let response = self
790            .http
791            .post(&self.base.login)
792            .json(&LoginRequestBody {
793                email,
794                password,
795                cohort_hash: self.cohort(),
796            })
797            .send_screened()
798            .await?;
799
800        let outcome = self.read_login_outcome(Endpoint::Login, response).await?;
801        tracing::info!("login answered");
802        Ok(outcome)
803    }
804
805    /// Read how this server signs people in from its unauthenticated
806    /// `.well-known/capsule/server-info` record (one generated call, nothing sent but the
807    /// handshake).
808    ///
809    /// # Errors
810    ///
811    /// [`AuthError::Network`] when the server cannot be reached, [`AuthError::Unexpected`] for a
812    /// status the record does not answer with, and [`AuthError::MalformedResponse`] for a body
813    /// that is not the record. A caller treats every one as "unknown" rather than as a refusal:
814    /// the record is advisory.
815    #[instrument(skip_all)]
816    pub async fn sign_in_options(&self) -> Result<SignInOptions, AuthError> {
817        let info = self
818            .rest
819            .server_info()
820            .await
821            .map_err(|error| {
822                map_rest_error(
823                    Endpoint::ServerInfo,
824                    error,
825                    |rest::ServerInfoError(problem)| Some(problem),
826                )
827            })?
828            .into_inner();
829        let options = SignInOptions {
830            server_id: info.server_id,
831            oidc: info.auth.oidc.is_value(),
832            password_disabled: info.auth.password_disabled.unwrap_or(false),
833        };
834        tracing::debug!(
835            oidc = options.oidc,
836            password_disabled = options.password_disabled,
837            "read the server's sign-in options"
838        );
839        Ok(options)
840    }
841
842    /// Begin a sign-in through the server's identity provider.
843    ///
844    /// `redirect_uri` is where the provider will send the person back — this client's own
845    /// callback, which the server admits if it is the deployment's configured one or a loopback
846    /// IP literal on any port (the shape a CLI's or desktop app's listener has). What comes back
847    /// is where to send the person, the `state` the redirect will echo, and the secret `binding`
848    /// this client keeps: a fresh one per ceremony, of which only the hash is sent.
849    ///
850    /// # Errors
851    ///
852    /// [`AuthError::OidcNotConfigured`] when the server has no provider,
853    /// [`AuthError::OidcRedirectInvalid`] when it refuses the redirect.
854    #[instrument(skip_all)]
855    pub async fn begin_oidc_login(
856        &self,
857        redirect_uri: &str,
858    ) -> Result<OidcAuthorization, AuthError> {
859        tracing::info!("beginning a sign-in through the identity provider");
860        let binding = fresh_oidc_binding();
861        let body = self
862            .rest
863            .begin_oidc_login(
864                rest::BeginOidcLoginParamsRequired {
865                    x_capsule_protocol: PROTOCOL_VERSION.into(),
866                },
867                rest::types::OidcAuthorizeRequest {
868                    redirect_uri: redirect_uri.to_owned(),
869                    binding_challenge: oidc_binding_challenge(&binding),
870                },
871            )
872            .await
873            .map_err(|error| {
874                map_rest_error(Endpoint::OidcAuthorize, error, |refused| match refused {
875                    rest::BeginOidcLoginError::Status400(problem)
876                    | rest::BeginOidcLoginError::Status404(problem)
877                    | rest::BeginOidcLoginError::Status408(problem)
878                    | rest::BeginOidcLoginError::Status415(problem)
879                    | rest::BeginOidcLoginError::Status422(problem)
880                    | rest::BeginOidcLoginError::Status425(problem)
881                    | rest::BeginOidcLoginError::Status426(problem)
882                    | rest::BeginOidcLoginError::Status429(problem)
883                    | rest::BeginOidcLoginError::Status500(problem)
884                    | rest::BeginOidcLoginError::Status503(problem)
885                    | rest::BeginOidcLoginError::Status413(problem) => Some(*problem),
886                })
887            })?
888            .into_inner();
889        Ok(OidcAuthorization {
890            authorization_url: body.authorization_url,
891            state: SecretString::from(body.state),
892            binding,
893            expires_by: body.expires_by,
894        })
895    }
896
897    /// Finish a sign-in through the identity provider with what its redirect carried.
898    ///
899    /// Answers a [`LoginOutcome`] exactly as [`login`](AuthClient::login) does — a session, or a
900    /// second-factor challenge for an account that enrolled one — and the configured cohort hash
901    /// rides this request, because this is the one that opens the session.
902    ///
903    /// `pending` is what [`begin_oidc_login`](AuthClient::begin_oidc_login) answered;
904    /// `redirect_state` and `code` are what the provider's redirect carried. A redirect whose
905    /// `state` is not the one this client began is refused here, before anything is sent: it is
906    /// someone else's ceremony arriving at this client (RFC 6749 §10.12). The server makes the
907    /// same refusal on the `binding`, which is what holds when a client skips this check.
908    ///
909    /// # Errors
910    ///
911    /// [`AuthError::OidcRejected`] for a redirect carrying another ceremony's `state`, a spent or
912    /// expired `state`, a refused exchange or a refused ID token (start again);
913    /// [`AuthError::OidcAddressTaken`] when the provider asserted an address that already has a
914    /// local account.
915    #[instrument(skip_all)]
916    pub async fn complete_oidc_login(
917        &self,
918        pending: &OidcAuthorization,
919        redirect_state: &str,
920        code: &str,
921    ) -> Result<LoginOutcome, AuthError> {
922        tracing::info!(
923            cohort_emitted = self.cohort().is_some(),
924            "completing a sign-in through the identity provider"
925        );
926        if redirect_state != pending.state.expose_secret() {
927            // The code the server gives a `state` it does not hold for this client: the remedy
928            // is the same, and a client localizes one code rather than two.
929            tracing::warn!(
930                "an identity provider redirect carried a state this client did not begin; refused"
931            );
932            return Err(AuthError::OidcRejected {
933                code: Some(error_codes::AUTH_OIDC_STATE_INVALID.to_owned()),
934            });
935        }
936        let answer = self
937            .rest
938            .complete_oidc_login(
939                rest::CompleteOidcLoginParamsRequired {
940                    x_capsule_protocol: PROTOCOL_VERSION.into(),
941                },
942                rest::types::OidcCallbackRequest {
943                    state: pending.state.expose_secret().to_owned(),
944                    code: code.to_owned(),
945                    binding_verifier: pending.binding.expose_secret().to_owned(),
946                    cohort_hash: absent_unless(self.cohort().map(str::to_owned)),
947                    device_id: rest::Nullable::Absent,
948                },
949            )
950            .await
951            .map_err(|error| {
952                map_rest_error(Endpoint::OidcCallback, error, |refused| match refused {
953                    rest::CompleteOidcLoginError::Status400(problem)
954                    | rest::CompleteOidcLoginError::Status401(problem)
955                    | rest::CompleteOidcLoginError::Status408(problem)
956                    | rest::CompleteOidcLoginError::Status409(problem)
957                    | rest::CompleteOidcLoginError::Status415(problem)
958                    | rest::CompleteOidcLoginError::Status422(problem)
959                    | rest::CompleteOidcLoginError::Status425(problem)
960                    | rest::CompleteOidcLoginError::Status426(problem)
961                    | rest::CompleteOidcLoginError::Status500(problem)
962                    | rest::CompleteOidcLoginError::Status413(problem) => Some(*problem),
963                })
964            })?
965            .into_inner();
966        // The status is the discriminator, as on the password login; the generated enum is
967        // exactly that status made a type.
968        let outcome = match answer {
969            rest::CompleteOidcLoginResponse::Status202(challenge) => {
970                tracing::info!("the identity provider sign-in needs a second factor");
971                LoginOutcome::SecondFactorRequired {
972                    mfa_token: SecretString::from(challenge.mfa_token),
973                    expires_by: challenge.expires_by,
974                }
975            }
976            rest::CompleteOidcLoginResponse::Status200(pair) => {
977                let tokens = TokenSet::from_wire(
978                    Endpoint::OidcCallback,
979                    TokenResponseBody {
980                        access_token: pair.access_token,
981                        refresh_token: pair.refresh_token,
982                        expires_by: pair.expires_by,
983                    },
984                )?;
985                tracing::info!("the identity provider sign-in succeeded; session established");
986                LoginOutcome::Session(self.session_with_tokens(tokens))
987            }
988        };
989        Ok(outcome)
990    }
991
992    /// Begin a sign-in through the server's identity provider for a client with no browser of
993    /// its own (RFC 8628, issue #635).
994    ///
995    /// What comes back is what to show the person and the handle to poll with, bound to this
996    /// client by a fresh secret of which only the hash is sent.
997    ///
998    /// # Errors
999    ///
1000    /// [`AuthError::OidcNotConfigured`] when the server has no provider,
1001    /// [`AuthError::OidcDeviceUnsupported`] when its provider does not offer the grant,
1002    /// [`AuthError::RateLimited`] when too many were begun.
1003    #[instrument(skip_all)]
1004    pub async fn begin_oidc_device_login(&self) -> Result<OidcDeviceAuthorization, AuthError> {
1005        tracing::info!("beginning a device sign-in through the identity provider");
1006        let binding = fresh_oidc_binding();
1007        let body = self
1008            .rest
1009            .begin_oidc_device_login(
1010                rest::BeginOidcDeviceLoginParamsRequired {
1011                    x_capsule_protocol: PROTOCOL_VERSION.into(),
1012                },
1013                rest::types::OidcDeviceRequest {
1014                    binding_challenge: oidc_binding_challenge(&binding),
1015                },
1016            )
1017            .await
1018            .map_err(|error| {
1019                map_rest_error(Endpoint::OidcDevice, error, |refused| match refused {
1020                    rest::BeginOidcDeviceLoginError::Status400(problem)
1021                    | rest::BeginOidcDeviceLoginError::Status404(problem)
1022                    | rest::BeginOidcDeviceLoginError::Status408(problem)
1023                    | rest::BeginOidcDeviceLoginError::Status415(problem)
1024                    | rest::BeginOidcDeviceLoginError::Status422(problem)
1025                    | rest::BeginOidcDeviceLoginError::Status425(problem)
1026                    | rest::BeginOidcDeviceLoginError::Status426(problem)
1027                    | rest::BeginOidcDeviceLoginError::Status429(problem)
1028                    | rest::BeginOidcDeviceLoginError::Status500(problem)
1029                    | rest::BeginOidcDeviceLoginError::Status503(problem)
1030                    | rest::BeginOidcDeviceLoginError::Status413(problem) => Some(*problem),
1031                })
1032            })?
1033            .into_inner();
1034        tracing::info!(
1035            interval_secs = body.interval,
1036            "the device sign-in began; waiting for the person"
1037        );
1038        Ok(OidcDeviceAuthorization {
1039            handle: SecretString::from(body.handle),
1040            binding,
1041            user_code: body.user_code,
1042            verification_uri: body.verification_uri,
1043            verification_uri_complete: body.verification_uri_complete.into_option(),
1044            interval_secs: body.interval,
1045            expires_by: body.expires_by,
1046        })
1047    }
1048
1049    /// Poll a device sign-in once (RFC 8628, issue #635).
1050    ///
1051    /// [`OidcDevicePoll::Pending`] and [`OidcDevicePoll::SlowDown`] are RFC 8628's "keep
1052    /// polling"; [`OidcDevicePoll::Complete`] is exactly what [`login`](AuthClient::login)
1053    /// answers — a session, or a second-factor challenge — and the configured cohort hash rides
1054    /// this request, because it is the one that opens the session. Waiting is the caller's: this
1055    /// sends one request and returns.
1056    ///
1057    /// # Errors
1058    ///
1059    /// [`AuthError::OidcDeviceDenied`] when the person declined, [`AuthError::OidcDeviceExpired`]
1060    /// when the ceremony is over, [`AuthError::OidcRejected`] for a refused exchange or ID
1061    /// token, [`AuthError::OidcAddressTaken`] as on the callback.
1062    #[instrument(skip_all)]
1063    pub async fn poll_oidc_device_login(
1064        &self,
1065        pending: &OidcDeviceAuthorization,
1066    ) -> Result<OidcDevicePoll, AuthError> {
1067        let answer = self
1068            .rest
1069            .poll_oidc_device_login(
1070                rest::PollOidcDeviceLoginParamsRequired {
1071                    x_capsule_protocol: PROTOCOL_VERSION.into(),
1072                },
1073                rest::types::OidcDevicePollRequest {
1074                    handle: pending.handle.expose_secret().to_owned(),
1075                    binding_verifier: pending.binding.expose_secret().to_owned(),
1076                    cohort_hash: absent_unless(self.cohort().map(str::to_owned)),
1077                    device_id: rest::Nullable::Absent,
1078                },
1079            )
1080            .await;
1081        let answer =
1082            match answer {
1083                Ok(answer) => answer.into_inner(),
1084                Err(rest::Error::Api(refused)) if keeps_polling(refused.inner()).is_some() => {
1085                    let poll = keeps_polling(refused.inner()).unwrap_or(OidcDevicePoll::Pending);
1086                    tracing::debug!(
1087                        slow_down = matches!(poll, OidcDevicePoll::SlowDown),
1088                        "the device sign-in is not finished"
1089                    );
1090                    return Ok(poll);
1091                }
1092                Err(error) => {
1093                    return Err(map_rest_error(Endpoint::OidcDevicePoll, error, |refused| {
1094                        match refused {
1095                            rest::PollOidcDeviceLoginError::Status400(problem)
1096                            | rest::PollOidcDeviceLoginError::Status401(problem)
1097                            | rest::PollOidcDeviceLoginError::Status408(problem)
1098                            | rest::PollOidcDeviceLoginError::Status409(problem)
1099                            | rest::PollOidcDeviceLoginError::Status415(problem)
1100                            | rest::PollOidcDeviceLoginError::Status422(problem)
1101                            | rest::PollOidcDeviceLoginError::Status425(problem)
1102                            | rest::PollOidcDeviceLoginError::Status426(problem)
1103                            | rest::PollOidcDeviceLoginError::Status429(problem)
1104                            | rest::PollOidcDeviceLoginError::Status500(problem)
1105                            | rest::PollOidcDeviceLoginError::Status413(problem) => Some(*problem),
1106                        }
1107                    }));
1108                }
1109            };
1110        let outcome = match answer {
1111            rest::PollOidcDeviceLoginResponse::Status202(challenge) => {
1112                tracing::info!("the device sign-in needs a second factor");
1113                LoginOutcome::SecondFactorRequired {
1114                    mfa_token: SecretString::from(challenge.mfa_token),
1115                    expires_by: challenge.expires_by,
1116                }
1117            }
1118            rest::PollOidcDeviceLoginResponse::Status200(pair) => {
1119                let tokens = TokenSet::from_wire(
1120                    Endpoint::OidcDevicePoll,
1121                    TokenResponseBody {
1122                        access_token: pair.access_token,
1123                        refresh_token: pair.refresh_token,
1124                        expires_by: pair.expires_by,
1125                    },
1126                )?;
1127                tracing::info!("the device sign-in succeeded; session established");
1128                LoginOutcome::Session(self.session_with_tokens(tokens))
1129            }
1130        };
1131        Ok(OidcDevicePoll::Complete(outcome))
1132    }
1133
1134    /// A `200` is a session and a `202` is a challenge, on every route that opens a session.
1135    ///
1136    /// Read from the **status**, which is where the server puts the distinction; a body flag
1137    /// would be a second place for the two to disagree. Treating the `202` as a token response
1138    /// would send it through `read_tokens` and surface as `MalformedResponse`, which would tell a
1139    /// user with a second factor that their server was broken.
1140    async fn read_login_outcome(
1141        &self,
1142        endpoint: Endpoint,
1143        response: reqwest::Response,
1144    ) -> Result<LoginOutcome, AuthError> {
1145        if response.status() == reqwest::StatusCode::ACCEPTED {
1146            let challenge: SecondFactorChallengeBody =
1147                response
1148                    .json()
1149                    .await
1150                    .map_err(|e| AuthError::MalformedResponse {
1151                        endpoint: endpoint.name(),
1152                        reason: e.to_string(),
1153                    })?;
1154            tracing::info!("the sign-in needs a second factor");
1155            return Ok(LoginOutcome::SecondFactorRequired {
1156                mfa_token: SecretString::from(challenge.mfa_token),
1157                expires_by: challenge.expires_by,
1158            });
1159        }
1160        let tokens = read_tokens(endpoint, response).await?;
1161        tracing::info!("the sign-in succeeded; session established");
1162        Ok(LoginOutcome::Session(self.session_with_tokens(tokens)))
1163    }
1164
1165    /// Complete a sign-in with the code an authenticator app is showing.
1166    ///
1167    /// `mfa_token` is the challenge [`LoginOutcome::SecondFactorRequired`] carried. It is good
1168    /// once and for five minutes; a code is good once, full stop, so a retry after a wrong code
1169    /// re-uses the same challenge and a retry after a *right* one has to start from the password.
1170    #[instrument(skip_all)]
1171    pub async fn verify_second_factor(
1172        &self,
1173        mfa_token: &SecretString,
1174        totp_code: &str,
1175    ) -> Result<Session, AuthError> {
1176        let response = self
1177            .http
1178            .post(&self.base.verify_totp)
1179            .json(&VerifyTotpRequestBody {
1180                mfa_token: mfa_token.expose_secret(),
1181                totp_code,
1182                cohort_hash: self.cohort(),
1183            })
1184            .send_screened()
1185            .await?;
1186        let tokens = read_tokens(Endpoint::VerifyTotp, response).await?;
1187        tracing::info!("second factor accepted; session established");
1188        Ok(self.session_with_tokens(tokens))
1189    }
1190
1191    /// Create a new account and return an authenticated [`Session`] (the server
1192    /// issues tokens on registration). The configured cohort hash rides the body
1193    /// under the same advisory contract as [`login`](AuthClient::login).
1194    #[instrument(skip_all)]
1195    pub async fn register(&self, email: &str, password: &str) -> Result<Session, AuthError> {
1196        tracing::info!(
1197            cohort_emitted = self.cohort().is_some(),
1198            "registering a new account"
1199        );
1200        let response = self
1201            .http
1202            .post(&self.base.register)
1203            .json(&RegisterRequestBody { email, password })
1204            .send_screened()
1205            .await?;
1206        let tokens = read_tokens(Endpoint::Register, response).await?;
1207        tracing::info!("registration succeeded; session established");
1208        Ok(self.session_with_tokens(tokens))
1209    }
1210
1211    /// Rebuild a [`Session`] from a persisted token set (e.g. loaded from the
1212    /// platform keychain at launch). The next request pre-flight-refreshes if the
1213    /// restored access token is already stale.
1214    pub fn resume(&self, persisted: PersistedSession) -> Result<Session, AuthError> {
1215        let access_expires_at =
1216            Timestamp::from_second(persisted.access_expires_at_unix).map_err(|e| {
1217                AuthError::MalformedResponse {
1218                    endpoint: "resume",
1219                    reason: e.to_string(),
1220                }
1221            })?;
1222        Ok(self.session_with_tokens(TokenSet {
1223            access_token: persisted.access_token,
1224            refresh_token: persisted.refresh_token,
1225            access_expires_at,
1226        }))
1227    }
1228
1229    fn session_with_tokens(&self, tokens: TokenSet) -> Session {
1230        Session {
1231            http: self.http.clone(),
1232            base: self.base.clone(),
1233            clock: self.clock.clone(),
1234            refresh_skew_secs: self.refresh_skew_secs,
1235            inner: Arc::new(SessionInner {
1236                tokens: RwLock::new(Some(tokens)),
1237                refresh_gate: Mutex::new(()),
1238            }),
1239        }
1240    }
1241}
1242
1243// ─── Session (authenticated handle) ──────────────────────────────────────────
1244
1245/// Shared mutable session state. `tokens` is the store; `refresh_gate` serializes
1246/// refreshes so concurrent callers single-flight.
1247struct SessionInner {
1248    tokens: RwLock<Option<TokenSet>>,
1249    refresh_gate: Mutex<()>,
1250}
1251
1252/// What prompted a refresh, and therefore how to decide (under the single-flight
1253/// gate) whether the refresh is still needed or a concurrent caller already did it.
1254enum RefreshTrigger {
1255    /// The pre-flight expiry check fired; skip if the stored token is now fresh.
1256    PreFlight,
1257    /// A request was rejected with `401` carrying this (now-stale) access token;
1258    /// skip if the stored token has since been rotated to a different one.
1259    Rejected(String),
1260}
1261
1262impl RefreshTrigger {
1263    fn label(&self) -> &'static str {
1264        match self {
1265            Self::PreFlight => "pre_flight",
1266            Self::Rejected(_) => "unauthorized",
1267        }
1268    }
1269}
1270
1271/// An authenticated session. Cheaply cloneable — every clone shares one token
1272/// store and one single-flight gate, so refreshes coalesce across clones and tasks.
1273#[derive(Clone)]
1274pub struct Session {
1275    http: reqwest::Client,
1276    base: Arc<AuthEndpoints>,
1277    clock: Arc<dyn Clock>,
1278    refresh_skew_secs: i64,
1279    inner: Arc<SessionInner>,
1280}
1281
1282impl Session {
1283    /// This session — the same token store and refresh gate — sending through `http` instead.
1284    ///
1285    /// How a transfer leaves a path behind: a new path generation builds a new client
1286    /// ([`GenerationPool`](crate::net::path::GenerationPool)), and requests sent through it never
1287    /// ride a connection pooled on the old path. `http` **must** come from
1288    /// [`crate::net::http_builder`] or [`crate::net::http_client`], so it carries the handshake.
1289    #[must_use]
1290    pub fn with_http_client(&self, http: reqwest::Client) -> Self {
1291        Self {
1292            http,
1293            ..self.clone()
1294        }
1295    }
1296
1297    /// Whether the session currently holds tokens.
1298    pub async fn is_authenticated(&self) -> bool {
1299        self.inner.tokens.read().await.is_some()
1300    }
1301
1302    /// Snapshot the token material for the platform's secure storage. `None` if the
1303    /// session has been logged out.
1304    pub async fn export(&self) -> Option<PersistedSession> {
1305        let guard = self.inner.tokens.read().await;
1306        guard.as_ref().map(|tokens| PersistedSession {
1307            access_token: tokens.access_token.clone(),
1308            refresh_token: tokens.refresh_token.clone(),
1309            access_expires_at_unix: tokens.access_expires_at.as_second(),
1310        })
1311    }
1312
1313    /// Run an authenticated request, injecting the bearer token and recovering from
1314    /// a `401` by refreshing once and replaying.
1315    ///
1316    /// `build` is the caller's un-authenticated request (path, method, body); the
1317    /// SDK adds the `Authorization` header, so callers never see the token. `build`
1318    /// is invoked again for the retry, so the request is reconstructed with the
1319    /// fresh token (no body-clone requirement).
1320    #[instrument(skip_all)]
1321    pub async fn execute<F>(&self, build: F) -> Result<reqwest::Response, AuthError>
1322    where
1323        F: Fn(&reqwest::Client) -> reqwest::RequestBuilder,
1324    {
1325        let token = self.valid_access_token().await?;
1326        let response = build(&self.http)
1327            .bearer_auth(token.expose_secret())
1328            .send_negotiated()
1329            .await?;
1330        if response.status() != reqwest::StatusCode::UNAUTHORIZED {
1331            return Ok(response);
1332        }
1333
1334        tracing::info!("authenticated request returned 401; refreshing once and retrying");
1335        let stale = token.expose_secret().to_string();
1336        let fresh = self
1337            .ensure_refreshed(RefreshTrigger::Rejected(stale))
1338            .await?;
1339        let retried = build(&self.http)
1340            .bearer_auth(fresh.expose_secret())
1341            .send_negotiated()
1342            .await?;
1343        Ok(retried)
1344    }
1345
1346    /// Force a refresh now (single-flight). A no-op on the wire if a concurrent
1347    /// caller already rotated the token.
1348    #[instrument(skip_all)]
1349    pub async fn refresh(&self) -> Result<(), AuthError> {
1350        let current = {
1351            let guard = self.inner.tokens.read().await;
1352            guard
1353                .as_ref()
1354                .ok_or(AuthError::NotAuthenticated)?
1355                .access_token
1356                .expose_secret()
1357                .to_string()
1358        };
1359        self.ensure_refreshed(RefreshTrigger::Rejected(current))
1360            .await?;
1361        Ok(())
1362    }
1363
1364    /// Refresh because the server **rejected** `stale`, and return the token that replaced
1365    /// it (single-flight).
1366    ///
1367    /// The reactive counterpart to [`bearer`](Session::bearer)'s pre-flight refresh, and the
1368    /// primitive [`crate::client::AuthenticatedClient`]'s `401` layer drives. Passing the
1369    /// exact token the server refused is the whole point: `ensure_refreshed`'s `Rejected`
1370    /// arm compares it against the store, so a caller whose stale token has *already* been
1371    /// rotated by a concurrent refresh gets the fresh token back with no second network
1372    /// call. [`refresh`](Session::refresh) cannot serve this — it re-reads the *current*
1373    /// token and would therefore refresh again on top of that rotation, spending a
1374    /// single-use refresh token the server has already closed.
1375    #[instrument(skip_all)]
1376    pub(crate) async fn refresh_rejected(&self, stale: &str) -> Result<SecretString, AuthError> {
1377        self.ensure_refreshed(RefreshTrigger::Rejected(stale.to_owned()))
1378            .await
1379    }
1380
1381    /// Revoke the session server-side and clear the local store. Idempotent: a
1382    /// server that no longer honors the token (or an already-empty store) still
1383    /// resolves to a cleared, logged-out session.
1384    #[instrument(skip_all)]
1385    pub async fn logout(&self) -> Result<(), AuthError> {
1386        let token = match self.valid_access_token().await {
1387            Ok(token) => token,
1388            Err(AuthError::SessionExpired | AuthError::NotAuthenticated) => {
1389                // Nothing the server can still revoke; drop local state and succeed.
1390                *self.inner.tokens.write().await = None;
1391                return Ok(());
1392            }
1393            Err(other) => return Err(other),
1394        };
1395        let sent = self
1396            .http
1397            .post(&self.base.logout)
1398            .bearer_auth(token.expose_secret())
1399            .send_screened()
1400            .await;
1401        // Any answer clears the local store, a `426` included: an out-of-window client can
1402        // still sign out on this device, and the error says the server-side revoke did not land.
1403        if matches!(sent, Ok(_) | Err(AuthError::UpgradeRequired(_))) {
1404            *self.inner.tokens.write().await = None;
1405        }
1406        let response = sent?;
1407        let status = response.status();
1408        if status.is_success() || status == reqwest::StatusCode::UNAUTHORIZED {
1409            tracing::info!("session logged out; local tokens cleared");
1410            Ok(())
1411        } else {
1412            Err(error_from_response(Endpoint::Logout, response).await)
1413        }
1414    }
1415
1416    /// A currently-valid **bearer access token** for injecting into a request the
1417    /// SDK does not build with [`Session::execute`] — notably the generated REST client's
1418    /// token-provider seam ([`crate::client::AuthenticatedClient`]), where the token is
1419    /// attached by the client rather than by this module. Pre-flight-refreshes exactly like
1420    /// [`Session::execute`]; the reactive half — a `401` the pre-flight check could not
1421    /// foresee — is `refresh_rejected`'s.
1422    #[instrument(skip_all)]
1423    pub async fn bearer(&self) -> Result<SecretString, AuthError> {
1424        self.valid_access_token().await
1425    }
1426
1427    /// Return a currently-valid access token, pre-flight-refreshing if the stored
1428    /// one is within the refresh skew of expiry. The fast path is a shared read; the
1429    /// refresh path single-flights.
1430    #[instrument(skip_all)]
1431    async fn valid_access_token(&self) -> Result<SecretString, AuthError> {
1432        {
1433            let guard = self.inner.tokens.read().await;
1434            let tokens = guard.as_ref().ok_or(AuthError::NotAuthenticated)?;
1435            if !self.needs_refresh(tokens) {
1436                return Ok(tokens.access_token.clone());
1437            }
1438        }
1439        tracing::debug!("access token within refresh skew; pre-flight refreshing");
1440        self.ensure_refreshed(RefreshTrigger::PreFlight).await
1441    }
1442
1443    fn needs_refresh(&self, tokens: &TokenSet) -> bool {
1444        let now = self.clock.now().as_second();
1445        now + self.refresh_skew_secs >= tokens.access_expires_at.as_second()
1446    }
1447
1448    /// Single-flight refresh. The gate serializes callers; the double-check under
1449    /// the gate coalesces everyone who piled up behind the one caller that hit the
1450    /// network, so N concurrent stale-token callers produce exactly one refresh.
1451    #[instrument(skip_all, fields(trigger = trigger.label()))]
1452    async fn ensure_refreshed(&self, trigger: RefreshTrigger) -> Result<SecretString, AuthError> {
1453        let _gate = self.inner.refresh_gate.lock().await;
1454
1455        let refresh_token = {
1456            let guard = self.inner.tokens.read().await;
1457            let tokens = guard.as_ref().ok_or(AuthError::NotAuthenticated)?;
1458            let still_stale = match &trigger {
1459                RefreshTrigger::PreFlight => self.needs_refresh(tokens),
1460                RefreshTrigger::Rejected(stale) => tokens.access_token.expose_secret() == stale,
1461            };
1462            if !still_stale {
1463                tracing::debug!("refresh coalesced with a concurrent single-flight refresh");
1464                return Ok(tokens.access_token.clone());
1465            }
1466            tokens.refresh_token.clone()
1467        };
1468
1469        tracing::info!("refreshing access token via session refresh token");
1470        let new_tokens = self.do_refresh(&refresh_token).await?;
1471        let access_token = new_tokens.access_token.clone();
1472        *self.inner.tokens.write().await = Some(new_tokens);
1473        Ok(access_token)
1474    }
1475
1476    #[instrument(skip_all)]
1477    async fn do_refresh(&self, refresh_token: &SecretString) -> Result<TokenSet, AuthError> {
1478        let response = self
1479            .http
1480            .post(&self.base.refresh)
1481            .json(&RefreshRequestBody {
1482                refresh_token: refresh_token.expose_secret(),
1483            })
1484            .send_screened()
1485            .await?;
1486        read_tokens(Endpoint::Refresh, response).await
1487    }
1488}
1489
1490// ─── Shared response parsing ─────────────────────────────────────────────────
1491
1492/// Parse a `TokenResponse` on success, or map the status/body to a typed error.
1493async fn read_tokens(
1494    endpoint: Endpoint,
1495    response: reqwest::Response,
1496) -> Result<TokenSet, AuthError> {
1497    if !response.status().is_success() {
1498        return Err(error_from_response(endpoint, response).await);
1499    }
1500    let body: TokenResponseBody =
1501        response
1502            .json()
1503            .await
1504            .map_err(|e| AuthError::MalformedResponse {
1505                endpoint: endpoint.name(),
1506                reason: e.to_string(),
1507            })?;
1508    TokenSet::from_wire(endpoint, body)
1509}
1510
1511/// Map a non-success response to a typed [`AuthError`], capturing the server's
1512/// `error.*` code and `Retry-After` where present.
1513async fn error_from_response(endpoint: Endpoint, response: reqwest::Response) -> AuthError {
1514    let status = response.status().as_u16();
1515    let retry_after = retry_after_of(response.headers());
1516    let api_error = response.json::<ApiErrorBody>().await.ok();
1517    let code = api_error.as_ref().and_then(|body| body.code.clone());
1518    let detail = api_error.map_or_else(String::new, |body| body.error);
1519    error_for(endpoint, status, code, detail, retry_after)
1520}
1521
1522/// The `Retry-After` seconds a response carries, if it carries one.
1523fn retry_after_of(headers: &reqwest::header::HeaderMap) -> Option<u64> {
1524    headers
1525        .get(reqwest::header::RETRY_AFTER)
1526        .and_then(|value| value.to_str().ok())
1527        .and_then(|raw| raw.trim().parse::<u64>().ok())
1528}
1529
1530/// One status → variant mapping for both the hand-rolled and the generated paths.
1531fn error_for(
1532    endpoint: Endpoint,
1533    status: u16,
1534    code: Option<String>,
1535    detail: String,
1536    retry_after: Option<u64>,
1537) -> AuthError {
1538    if let Some(refusal) = endpoint.oidc_refusal(status, code.as_deref()) {
1539        return refusal;
1540    }
1541    match status {
1542        401 => endpoint.unauthorized_error(code),
1543        423 => AuthError::AccountLocked,
1544        429 => AuthError::RateLimited {
1545            retry_after_secs: retry_after.unwrap_or(0),
1546            code,
1547        },
1548        other => AuthError::Unexpected {
1549            status: other,
1550            endpoint: endpoint.name(),
1551            detail,
1552            code,
1553        },
1554    }
1555}
1556
1557/// Whether a device poll's refusal is RFC 8628's "keep polling", matched on the catalog code:
1558/// `400 error.auth.oidc_device_pending` or `429 error.auth.oidc_device_slow_down`.
1559fn keeps_polling(refused: &rest::PollOidcDeviceLoginError) -> Option<OidcDevicePoll> {
1560    match refused {
1561        rest::PollOidcDeviceLoginError::Status400(problem)
1562            if problem.code == error_codes::AUTH_OIDC_DEVICE_PENDING =>
1563        {
1564            Some(OidcDevicePoll::Pending)
1565        }
1566        rest::PollOidcDeviceLoginError::Status429(problem)
1567            if problem.code == error_codes::AUTH_OIDC_DEVICE_SLOW_DOWN =>
1568        {
1569            Some(OidcDevicePoll::SlowDown)
1570        }
1571        _ => None,
1572    }
1573}
1574
1575/// Map a generated-client failure to a typed [`AuthError`].
1576///
1577/// `problem` extracts the coded problem a documented refusal carries, so the status → variant
1578/// mapping is the one the hand-rolled path uses; the generated client's own classes — transport,
1579/// timeout, protocol, redirect, construction — become [`AuthError::Network`], an undocumented
1580/// status [`AuthError::Unexpected`], and a body that did not decode [`AuthError::MalformedResponse`].
1581fn map_rest_error<E: std::error::Error + 'static>(
1582    endpoint: Endpoint,
1583    error: rest::Error<E>,
1584    problem: impl FnOnce(E) -> Option<rest::types::CodedProblem>,
1585) -> AuthError {
1586    if let Some(refusal) = crate::client::upgrade_required_of(&error) {
1587        return refusal.into();
1588    }
1589    match error {
1590        rest::Error::Api(refused) => {
1591            let status = refused.status().as_u16();
1592            let retry_after = retry_after_of(refused.headers());
1593            match problem(refused.into_inner()) {
1594                Some(problem) => error_for(
1595                    endpoint,
1596                    status,
1597                    Some(problem.code),
1598                    problem.detail.unwrap_or_default(),
1599                    retry_after,
1600                ),
1601                None => error_for(endpoint, status, None, String::new(), retry_after),
1602            }
1603        }
1604        rest::Error::UnexpectedStatus { status, body, .. } => AuthError::Unexpected {
1605            status: status.as_u16(),
1606            endpoint: endpoint.name(),
1607            detail: String::from_utf8_lossy(&body).into_owned(),
1608            code: None,
1609        },
1610        rest::Error::Decode { path, .. } => AuthError::MalformedResponse {
1611            endpoint: endpoint.name(),
1612            reason: path,
1613        },
1614        other => AuthError::Network {
1615            endpoint: endpoint.name(),
1616            detail: other.to_string(),
1617        },
1618    }
1619}
1620
1621#[cfg(test)]
1622mod tests;