Skip to main content

owlauth_client/
client.rs

1use std::{
2    net::IpAddr,
3    panic::{AssertUnwindSafe, catch_unwind},
4    sync::{
5        Arc,
6        atomic::{AtomicBool, Ordering},
7    },
8    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
9};
10
11use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
12use serde::{Serialize, de::DeserializeOwned};
13use sha2::{Digest, Sha256};
14use subtle::ConstantTimeEq;
15use time::{OffsetDateTime, format_description::well_known::Rfc3339};
16use url::Url;
17use zeroize::Zeroizing;
18
19use crate::{
20    BrowserLogoutPreparation, CompletionResponse, CredentialPair, CredentialPairRecord,
21    CredentialPairWire, CurrentUser, Error, ErrorCategory, HandoffGuard, HandoffRequest,
22    HttpMethod, HttpRequest, HttpResponse, JwksDocument, LocalAction, LoginStart,
23    LoginStartRequest, LoginStartResponse, PendingLogin, PendingLoginRecord, PublicConfiguration,
24    RefreshRequest, RetryPolicy, RuntimeErrorWire, Transport, TransportFailure,
25    TransportFailureKind, ValidatedCallback,
26    error::{configuration, protocol},
27    transport::default_transport,
28};
29
30const MAX_RESPONSE_BYTES: usize = 65_536;
31const PENDING_SCHEMA_VERSION: u8 = 1;
32
33#[derive(Clone, Copy)]
34struct ResponsePolicy {
35    operation: &'static str,
36    expected_status: u16,
37    sensitive: bool,
38    action: LocalAction,
39}
40
41impl ResponsePolicy {
42    const fn new(
43        operation: &'static str,
44        expected_status: u16,
45        sensitive: bool,
46        action: LocalAction,
47    ) -> Self {
48        Self {
49            operation,
50            expected_status,
51            sensitive,
52            action,
53        }
54    }
55}
56
57/// Cloneable caller-controlled cancellation boundary for one SDK operation.
58#[derive(Clone, Default)]
59pub struct CancellationToken {
60    inner: Arc<CancellationState>,
61}
62
63#[derive(Default)]
64struct CancellationState {
65    cancelled: AtomicBool,
66    notify: tokio::sync::Notify,
67}
68
69impl CancellationToken {
70    #[must_use]
71    pub fn new() -> Self {
72        Self::default()
73    }
74
75    /// Requests cancellation. Calling this method more than once has no additional effect.
76    pub fn cancel(&self) {
77        if !self.inner.cancelled.swap(true, Ordering::AcqRel) {
78            self.inner.notify.notify_waiters();
79        }
80    }
81
82    #[must_use]
83    pub fn is_cancelled(&self) -> bool {
84        self.inner.cancelled.load(Ordering::Acquire)
85    }
86
87    async fn cancelled(&self) {
88        loop {
89            if self.is_cancelled() {
90                return;
91            }
92            let notified = self.inner.notify.notified();
93            if self.is_cancelled() {
94                return;
95            }
96            notified.await;
97        }
98    }
99}
100
101impl std::fmt::Debug for CancellationToken {
102    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        formatter
104            .debug_struct("CancellationToken")
105            .field("cancelled", &self.is_cancelled())
106            .finish()
107    }
108}
109
110/// Optional controls for one SDK operation.
111#[derive(Clone, Debug, Default)]
112pub struct OperationOptions {
113    cancellation: Option<CancellationToken>,
114}
115
116impl OperationOptions {
117    #[must_use]
118    pub const fn new() -> Self {
119        Self { cancellation: None }
120    }
121
122    #[must_use]
123    pub fn with_cancellation(cancellation: CancellationToken) -> Self {
124        Self {
125            cancellation: Some(cancellation),
126        }
127    }
128
129    #[must_use]
130    pub const fn cancellation(&self) -> Option<&CancellationToken> {
131        self.cancellation.as_ref()
132    }
133}
134
135/// Immutable one-Project/one-Application client configuration.
136#[derive(Clone, Debug, Eq, PartialEq)]
137pub struct ClientConfig {
138    pub runtime_url: String,
139    pub project_id: String,
140    pub application_id: String,
141    pub publishable_key: String,
142    pub allow_insecure_loopback: bool,
143    pub deadline: Duration,
144}
145
146impl ClientConfig {
147    #[must_use]
148    pub fn new(
149        runtime_url: impl Into<String>,
150        project_id: impl Into<String>,
151        application_id: impl Into<String>,
152        publishable_key: impl Into<String>,
153    ) -> Self {
154        Self {
155            runtime_url: runtime_url.into(),
156            project_id: project_id.into(),
157            application_id: application_id.into(),
158            publishable_key: publishable_key.into(),
159            allow_insecure_loopback: false,
160            deadline: Duration::from_secs(30),
161        }
162    }
163}
164
165/// Injectable entropy source used only to make deterministic tests possible.
166pub trait EntropySource: Send + Sync {
167    /// Fills the destination with cryptographically secure random bytes.
168    ///
169    /// # Errors
170    /// Returns an error when secure entropy is unavailable.
171    fn fill(&self, destination: &mut [u8]) -> Result<(), Error>;
172}
173
174/// Injectable Unix clock.
175pub trait Clock: Send + Sync {
176    fn now_unix_seconds(&self) -> i64;
177}
178
179#[derive(Debug)]
180struct OsEntropy;
181impl EntropySource for OsEntropy {
182    fn fill(&self, destination: &mut [u8]) -> Result<(), Error> {
183        getrandom::fill(destination).map_err(|_| {
184            Error::new(
185                ErrorCategory::Transport,
186                "entropy_unavailable",
187                "Secure randomness is unavailable.",
188                RetryPolicy::Never,
189                LocalAction::None,
190                "start_login",
191            )
192        })
193    }
194}
195
196#[derive(Debug)]
197struct SystemClock;
198impl Clock for SystemClock {
199    fn now_unix_seconds(&self) -> i64 {
200        SystemTime::now()
201            .duration_since(UNIX_EPOCH)
202            .map_or(0, |value| {
203                i64::try_from(value.as_secs()).unwrap_or(i64::MAX)
204            })
205    }
206}
207
208/// Secret-free result classification for an optional SDK debug event.
209#[non_exhaustive]
210#[derive(Clone, Copy, Debug, Eq, PartialEq)]
211pub enum SdkDebugOutcome {
212    Success,
213    RuntimeError,
214    TransportError,
215    Timeout,
216    Cancelled,
217    InvalidResponse,
218    Indeterminate,
219}
220
221/// Closed, secret-free completion event emitted only when a debug hook is configured.
222#[derive(Clone, Debug, Eq, PartialEq)]
223pub struct SdkDebugEvent {
224    pub operation: &'static str,
225    pub method: HttpMethod,
226    pub outcome: SdkDebugOutcome,
227    pub elapsed_millis: u64,
228    pub dispatched: bool,
229    pub status: Option<u16>,
230    pub category: Option<ErrorCategory>,
231    pub code: Option<String>,
232    pub request_id: Option<String>,
233}
234
235/// Optional observer for safe SDK completion events.
236pub trait DebugHook: Send + Sync {
237    fn emit(&self, event: &SdkDebugEvent);
238}
239
240/// Async Project Auth protocol client. It owns no pending or credential persistence.
241#[derive(Clone)]
242pub struct Client {
243    base: Url,
244    origin: String,
245    project_id: String,
246    application_id: String,
247    publishable_key: String,
248    deadline: Duration,
249    transport: Arc<dyn Transport>,
250    entropy: Arc<dyn EntropySource>,
251    clock: Arc<dyn Clock>,
252    debug_hook: Option<Arc<dyn DebugHook>>,
253}
254
255impl std::fmt::Debug for Client {
256    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257        formatter
258            .debug_struct("Client")
259            .field("base_url", &self.base.as_str())
260            .field("project_id", &self.project_id)
261            .field("application_id", &self.application_id)
262            .field("publishable_key", &self.publishable_key)
263            .field("deadline", &self.deadline)
264            .finish_non_exhaustive()
265    }
266}
267
268impl Client {
269    /// Creates a client with the production HTTP transport, OS entropy, and system clock.
270    ///
271    /// # Errors
272    /// Returns a configuration error when URL, identifiers, or deadline are invalid.
273    pub fn new(config: ClientConfig) -> Result<Self, Error> {
274        Self::with_dependencies(
275            config,
276            default_transport()?,
277            Arc::new(OsEntropy),
278            Arc::new(SystemClock),
279        )
280    }
281
282    /// Constructs a client with explicit protocol dependencies for deterministic tests and custom transport policy.
283    ///
284    /// # Errors
285    /// Returns a configuration error when URL, identifiers, or deadline are invalid.
286    pub fn with_dependencies(
287        config: ClientConfig,
288        transport: Arc<dyn Transport>,
289        entropy: Arc<dyn EntropySource>,
290        clock: Arc<dyn Clock>,
291    ) -> Result<Self, Error> {
292        let base = validate_base_url(&config.runtime_url, config.allow_insecure_loopback)?;
293        validate_identifier(&config.project_id, 96, "project_id")?;
294        validate_identifier(&config.application_id, 96, "application_id")?;
295        validate_identifier(&config.publishable_key, 128, "publishable_key")?;
296        if !(Duration::from_millis(1)..=Duration::from_mins(2)).contains(&config.deadline) {
297            return Err(configuration(
298                "invalid_deadline",
299                "The Runtime deadline is outside the supported range.",
300            ));
301        }
302        let origin = base.origin().ascii_serialization();
303        Ok(Self {
304            base,
305            origin,
306            project_id: config.project_id,
307            application_id: config.application_id,
308            publishable_key: config.publishable_key,
309            deadline: config.deadline,
310            transport,
311            entropy,
312            clock,
313            debug_hook: None,
314        })
315    }
316
317    /// Installs an optional secret-free completion observer. Hook panics are isolated from protocol outcomes.
318    #[must_use]
319    pub fn with_debug_hook(mut self, debug_hook: Arc<dyn DebugHook>) -> Self {
320        self.debug_hook = Some(debug_hook);
321        self
322    }
323
324    #[must_use]
325    pub fn base_url(&self) -> &str {
326        self.base.as_str()
327    }
328    #[must_use]
329    pub fn project_id(&self) -> &str {
330        &self.project_id
331    }
332    #[must_use]
333    pub fn application_id(&self) -> &str {
334        &self.application_id
335    }
336
337    /// Restores an explicitly exported pending-login record into this exact client without I/O.
338    ///
339    /// # Errors
340    /// Returns a configuration error for a stale, malformed, or cross-context record.
341    pub fn restore_pending_login(&self, value: PendingLoginRecord) -> Result<PendingLogin, Error> {
342        let now = self.clock.now_unix_seconds();
343        let now = i128::from(now);
344        let created_at = i128::from(value.created_at);
345        let expires_at = i128::from(value.expires_at);
346        if value.schema_version != PENDING_SCHEMA_VERSION
347            || value.runtime_origin != self.origin
348            || value.runtime_base_path != self.base.path()
349            || value.project_id != self.project_id
350            || value.application_id != self.application_id
351            || validate_redirect(&value.redirect_uri).is_err()
352            || !(43..=128).contains(&value.verifier.len())
353            || !value
354                .verifier
355                .bytes()
356                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
357            || value.state.is_empty()
358            || value.state.chars().count() > 1024
359            || created_at > now + 60
360            || expires_at < created_at - 60
361            || expires_at > created_at + 660
362            || expires_at > now + 660
363            || now > expires_at + 60
364        {
365            return Err(configuration(
366                "invalid_pending_record",
367                "The pending-login record is invalid or belongs to another client.",
368            ));
369        }
370        Ok(PendingLogin {
371            schema_version: value.schema_version,
372            runtime_origin: value.runtime_origin,
373            runtime_base_path: value.runtime_base_path,
374            project_id: value.project_id,
375            application_id: value.application_id,
376            redirect_uri: value.redirect_uri,
377            verifier: Zeroizing::new(value.verifier),
378            state: Zeroizing::new(value.state),
379            created_at: value.created_at,
380            expires_at: value.expires_at,
381            guard: Arc::new(HandoffGuard::new()),
382        })
383    }
384
385    /// Restores an explicitly exported credential generation into this exact client without I/O.
386    ///
387    /// # Errors
388    /// Returns a configuration error for a malformed, expired, or cross-context record.
389    pub fn restore_credentials(
390        &self,
391        value: CredentialPairRecord,
392    ) -> Result<CredentialPair, Error> {
393        let now = self.clock.now_unix_seconds();
394        let now_bound = i128::from(now);
395        let access_expiry = i128::from(value.access_expires_at);
396        let remaining =
397            i64::try_from((access_expiry - now_bound).clamp(0, 3600)).unwrap_or_default();
398        let session_expiry = parse_time(&value.session_expires_at, "restore_credentials").ok();
399        if value.schema_version != 1
400            || value.runtime_origin != self.origin
401            || value.runtime_base_path != self.base.path()
402            || value.project_id != self.project_id
403            || value.application_id != self.application_id
404            || value.user_id.is_empty()
405            || value.user_id.len() > 96
406            || value.session_id.is_empty()
407            || value.session_id.len() > 64
408            || value.refresh_generation <= 0
409            || !valid_bearer_token(&value.access_token, 16_384)
410            || !valid_opaque_token(&value.refresh_token, 256)
411            || value.token_type != "Bearer"
412            || access_expiry > now_bound + 3660
413            || value.projection_revision <= 0
414            || value.projection_revision != value.projection.projection_revision
415            || value.user_id != value.projection.user_id
416            || !valid_projection(&value.projection)
417            || session_expiry.is_none_or(|expiry| i128::from(expiry) < now_bound - 60)
418        {
419            return Err(configuration(
420                "invalid_credential_record",
421                "The credential record is invalid or belongs to another client.",
422            ));
423        }
424        Ok(CredentialPair::from_record(value, remaining))
425    }
426
427    /// Fetches bounded public Project/Application configuration.
428    ///
429    /// # Errors
430    /// Returns a typed transport, Runtime, or protocol error.
431    pub async fn public_configuration(&self) -> Result<PublicConfiguration, Error> {
432        self.public_configuration_with_options(&OperationOptions::default())
433            .await
434    }
435
436    /// Fetches public configuration with explicit operation controls.
437    ///
438    /// # Errors
439    /// Returns a typed transport, Runtime, or protocol error.
440    pub async fn public_configuration_with_options(
441        &self,
442        options: &OperationOptions,
443    ) -> Result<PublicConfiguration, Error> {
444        let mut url = self.endpoint(&format!(
445            "v1/projects/{}/auth/config",
446            encode_path(&self.project_id)
447        ))?;
448        url.query_pairs_mut()
449            .append_pair("application_id", &self.application_id);
450        let value: PublicConfiguration = self
451            .get_json(url, "get_public_application_config", 200, options)
452            .await?;
453        if value.project_public_id != self.project_id
454            || value.application_public_id != self.application_id
455            || !value
456                .publishable_keys
457                .iter()
458                .any(|key| key == &self.publishable_key)
459        {
460            return Err(protocol(
461                "get_public_application_config",
462                "context_mismatch",
463            ));
464        }
465        if value.project_display_name.is_empty()
466            || value.project_display_name.chars().count() > 128
467            || value.application_display_name.is_empty()
468            || value.application_display_name.chars().count() > 128
469            || value.providers.len() > 50
470            || value.publishable_keys.len() > 50
471            || value
472                .publishable_keys
473                .iter()
474                .any(|key| key.is_empty() || key.len() > 128)
475            || value.providers.iter().any(|provider| {
476                provider.key.is_empty()
477                    || provider.key.len() > 64
478                    || provider.display_name.is_empty()
479                    || provider.display_name.chars().count() > 128
480                    || !matches!(provider.kind.as_str(), "oidc" | "google" | "github")
481            })
482            || {
483                let mut keys = std::collections::BTreeSet::new();
484                value
485                    .providers
486                    .iter()
487                    .any(|provider| !keys.insert(&provider.key))
488            }
489        {
490            return Err(protocol(
491                "get_public_application_config",
492                "invalid_response",
493            ));
494        }
495        Ok(value)
496    }
497
498    /// Fetches Project JWKS and signing revision metadata.
499    ///
500    /// # Errors
501    /// Returns a typed transport, Runtime, or protocol error.
502    pub async fn project_jwks(&self) -> Result<JwksDocument, Error> {
503        self.project_jwks_with_options(&OperationOptions::default())
504            .await
505    }
506
507    /// Fetches Project JWKS with explicit operation controls.
508    ///
509    /// # Errors
510    /// Returns a typed transport, Runtime, or protocol error.
511    pub async fn project_jwks_with_options(
512        &self,
513        options: &OperationOptions,
514    ) -> Result<JwksDocument, Error> {
515        let url = self.endpoint(&format!(
516            "projects/{}/.well-known/jwks.json",
517            encode_path(&self.project_id)
518        ))?;
519        let value: JwksDocument = self.get_json(url, "get_project_jwks", 200, options).await?;
520        if value.keys.len() > 100
521            || value.revision <= 0
522            || value.signing_epoch <= 0
523            || value.keys.iter().any(|key| {
524                key.kty != "OKP"
525                    || key.crv != "Ed25519"
526                    || key.alg != "EdDSA"
527                    || key.key_use != "sig"
528                    || key.kid.is_empty()
529                    || key.kid.len() > 128
530                    || !valid_ed25519_key(&key.x)
531            })
532            || {
533                let mut kids = std::collections::BTreeSet::new();
534                value.keys.iter().any(|key| !kids.insert(&key.kid))
535            }
536        {
537            return Err(protocol("get_project_jwks", "invalid_response"));
538        }
539        Ok(value)
540    }
541
542    /// Creates fresh S256 PKCE/state and starts a generic Hosted login without navigation.
543    ///
544    /// # Errors
545    /// Returns a configuration, entropy, transport, login, or protocol error.
546    pub async fn begin_login(
547        &self,
548        redirect_uri: &str,
549        application_state: Option<&str>,
550        presentation_hint: Option<&str>,
551    ) -> Result<LoginStart, Error> {
552        self.begin_login_with_options(
553            redirect_uri,
554            application_state,
555            presentation_hint,
556            &OperationOptions::default(),
557        )
558        .await
559    }
560
561    /// Starts Hosted login with explicit operation controls.
562    ///
563    /// # Errors
564    /// Returns a configuration, entropy, transport, login, or protocol error.
565    pub async fn begin_login_with_options(
566        &self,
567        redirect_uri: &str,
568        application_state: Option<&str>,
569        presentation_hint: Option<&str>,
570        options: &OperationOptions,
571    ) -> Result<LoginStart, Error> {
572        validate_redirect(redirect_uri)?;
573        if presentation_hint.is_some_and(|value| value.is_empty() || value.chars().count() > 64) {
574            return Err(configuration(
575                "invalid_presentation_hint",
576                "The presentation hint is invalid.",
577            ));
578        }
579        let verifier = self.random_base64(32, "start_login")?;
580        let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));
581        let state = match application_state {
582            Some(value) if !value.is_empty() && value.chars().count() <= 1024 => value.to_owned(),
583            Some(_) => {
584                return Err(configuration(
585                    "invalid_application_state",
586                    "The Application state is invalid.",
587                ));
588            }
589            None => self.random_base64(32, "start_login")?,
590        };
591        let request = LoginStartRequest {
592            application_id: &self.application_id,
593            publishable_key: &self.publishable_key,
594            redirect_uri,
595            pkce_challenge: &challenge,
596            state: &state,
597            presentation_hint,
598        };
599        let url = self.endpoint(&format!(
600            "v1/projects/{}/auth/login/start",
601            encode_path(&self.project_id)
602        ))?;
603        let created_at = self.clock.now_unix_seconds();
604        let response: LoginStartResponse = self
605            .post_json(
606                url,
607                &request,
608                ResponsePolicy::new("start_login", 201, false, LocalAction::DiscardPendingLogin),
609                None,
610                options,
611            )
612            .await?;
613        if response.hosted_url.chars().count() > 512 || has_ambiguous_url_path(&response.hosted_url)
614        {
615            return Err(protocol("start_login", "invalid_hosted_url"));
616        }
617        let hosted = Url::parse(&response.hosted_url)
618            .map_err(|_| protocol("start_login", "invalid_hosted_url"))?;
619        if hosted.origin().ascii_serialization() != self.origin
620            || !hosted.path().starts_with(self.base.path())
621            || hosted.username() != ""
622            || hosted.password().is_some()
623            || hosted.fragment().is_some()
624        {
625            return Err(protocol("start_login", "invalid_hosted_url"));
626        }
627        let expires_at = parse_time(&response.expires_at, "start_login")?;
628        let created_at_bound = i128::from(created_at);
629        let expires_at_bound = i128::from(expires_at);
630        if expires_at_bound < created_at_bound - 60 || expires_at_bound > created_at_bound + 660 {
631            return Err(protocol("start_login", "invalid_expiry"));
632        }
633        Ok(LoginStart {
634            hosted_url: hosted.to_string(),
635            pending: PendingLogin {
636                schema_version: PENDING_SCHEMA_VERSION,
637                runtime_origin: self.origin.clone(),
638                runtime_base_path: self.base.path().to_owned(),
639                project_id: self.project_id.clone(),
640                application_id: self.application_id.clone(),
641                redirect_uri: redirect_uri.to_owned(),
642                verifier: Zeroizing::new(verifier),
643                state: Zeroizing::new(state),
644                created_at,
645                expires_at,
646                guard: Arc::new(HandoffGuard::new()),
647            },
648        })
649    }
650
651    /// Validates local callback input without consuming pending state on malformed input.
652    /// A successful validation returns a value sharing the pending login's one-use guard.
653    ///
654    /// # Errors
655    /// Returns a handoff error for expiry, state, redirect, or context mismatch.
656    pub fn validate_callback(
657        &self,
658        callback_url: &str,
659        pending: &PendingLogin,
660    ) -> Result<ValidatedCallback, Error> {
661        let fail = |code| {
662            Error::new(
663                ErrorCategory::Handoff,
664                code,
665                "The login callback is invalid or expired.",
666                RetryPolicy::Never,
667                LocalAction::DiscardPendingLogin,
668                "exchange_handoff",
669            )
670        };
671        if !pending.available() {
672            return Err(fail("pending_consumed"));
673        }
674        if pending.schema_version != PENDING_SCHEMA_VERSION
675            || pending.runtime_origin != self.origin
676            || pending.runtime_base_path != self.base.path()
677            || pending.project_id != self.project_id
678            || pending.application_id != self.application_id
679            || i128::from(self.clock.now_unix_seconds()) > i128::from(pending.expires_at) + 60
680        {
681            return Err(fail("pending_context_mismatch"));
682        }
683        if callback_url.len() > 4096 {
684            return Err(fail("invalid_callback"));
685        }
686        let callback = Url::parse(callback_url).map_err(|_| fail("invalid_callback"))?;
687        let expected = Url::parse(&pending.redirect_uri).map_err(|_| fail("invalid_callback"))?;
688        if callback.scheme() != expected.scheme()
689            || callback.host_str() != expected.host_str()
690            || callback.port_or_known_default() != expected.port_or_known_default()
691            || callback.path() != expected.path()
692            || callback.fragment().is_some()
693            || callback.username() != ""
694            || callback.password().is_some()
695        {
696            return Err(fail("redirect_mismatch"));
697        }
698        let expected_query: Vec<(String, String)> = expected
699            .query_pairs()
700            .map(|(a, b)| (a.into_owned(), b.into_owned()))
701            .collect();
702        if expected_query
703            .iter()
704            .any(|(key, _)| matches!(key.as_str(), "handoff" | "state" | "error"))
705        {
706            return Err(fail("invalid_callback"));
707        }
708        let mut handoff = None;
709        let mut callback_error = None;
710        let mut state = None;
711        let mut remaining = Vec::new();
712        for (key, value) in callback.query_pairs() {
713            match key.as_ref() {
714                "handoff" if handoff.is_none() => handoff = Some(value.into_owned()),
715                "error" if callback_error.is_none() => callback_error = Some(value.into_owned()),
716                "state" if state.is_none() => state = Some(value.into_owned()),
717                "handoff" | "error" | "state" => return Err(fail("invalid_callback")),
718                _ => remaining.push((key.into_owned(), value.into_owned())),
719            }
720        }
721        let state = state
722            .filter(|value| !value.is_empty() && value.chars().count() <= 1024)
723            .ok_or_else(|| fail("state_mismatch"))?;
724        if remaining != expected_query
725            || !bool::from(state.as_bytes().ct_eq(pending.state.as_bytes()))
726            || handoff.is_some() == callback_error.is_some()
727        {
728            return Err(fail("invalid_callback"));
729        }
730        if callback_error
731            .as_ref()
732            .is_some_and(|value| value.is_empty() || value.len() > 64)
733        {
734            return Err(fail("invalid_callback"));
735        }
736        if callback_error.is_some() {
737            return Err(fail("login_failed"));
738        }
739        let handoff = handoff
740            .filter(|value| !value.is_empty() && value.len() <= 256)
741            .ok_or_else(|| fail("missing_handoff"))?;
742        Ok(ValidatedCallback {
743            handoff: Zeroizing::new(handoff),
744            verifier: pending.verifier.clone(),
745            guard: Arc::clone(&pending.guard),
746        })
747    }
748
749    /// Exchanges locally validated one-use handoff material without automatic retry.
750    ///
751    /// # Errors
752    /// Returns `Indeterminate` when a post-dispatch outcome cannot be known safely.
753    pub async fn exchange_handoff(
754        &self,
755        callback: &ValidatedCallback,
756    ) -> Result<CredentialPair, Error> {
757        self.exchange_handoff_with_options(callback, &OperationOptions::default())
758            .await
759    }
760
761    /// Exchanges handoff material with explicit operation controls.
762    ///
763    /// # Errors
764    /// Returns `Indeterminate` when a post-dispatch outcome cannot be known safely.
765    pub async fn exchange_handoff_with_options(
766        &self,
767        callback: &ValidatedCallback,
768        options: &OperationOptions,
769    ) -> Result<CredentialPair, Error> {
770        let request = HandoffRequest {
771            application_id: &self.application_id,
772            publishable_key: &self.publishable_key,
773            handoff: callback.handoff.as_str(),
774            pkce_verifier: callback.verifier.as_str(),
775        };
776        let url = self.endpoint(&format!(
777            "v1/projects/{}/auth/handoff/exchange",
778            encode_path(&self.project_id)
779        ))?;
780        let wire: CredentialPairWire = self
781            .post_json(
782                url,
783                &request,
784                ResponsePolicy::new(
785                    "exchange_handoff",
786                    200,
787                    true,
788                    LocalAction::QuarantinePendingLogin,
789                ),
790                Some(&callback.guard),
791                options,
792            )
793            .await?;
794        self.validate_credentials(
795            wire,
796            "exchange_handoff",
797            LocalAction::QuarantinePendingLogin,
798        )
799    }
800
801    /// Validates a callback and exchanges its handoff as one explicit operation.
802    ///
803    /// # Errors
804    /// Returns a handoff, transport, protocol, or indeterminate error.
805    pub async fn complete_login(
806        &self,
807        callback_url: &str,
808        pending: &PendingLogin,
809    ) -> Result<CredentialPair, Error> {
810        self.complete_login_with_options(callback_url, pending, &OperationOptions::default())
811            .await
812    }
813
814    /// Validates and exchanges a login callback with explicit operation controls.
815    ///
816    /// # Errors
817    /// Returns a handoff, transport, protocol, cancellation, or indeterminate error.
818    pub async fn complete_login_with_options(
819        &self,
820        callback_url: &str,
821        pending: &PendingLogin,
822        options: &OperationOptions,
823    ) -> Result<CredentialPair, Error> {
824        let callback = self.validate_callback(callback_url, pending)?;
825        self.exchange_handoff_with_options(&callback, options).await
826    }
827
828    /// Rotates one explicit credential generation without automatic retry.
829    ///
830    /// # Errors
831    /// Returns a refresh, protocol, transport, or indeterminate error.
832    pub async fn refresh(&self, current: &CredentialPair) -> Result<CredentialPair, Error> {
833        self.refresh_with_options(current, &OperationOptions::default())
834            .await
835    }
836
837    /// Rotates one credential generation with explicit operation controls.
838    ///
839    /// # Errors
840    /// Returns a refresh, protocol, transport, cancellation, or indeterminate error.
841    pub async fn refresh_with_options(
842        &self,
843        current: &CredentialPair,
844        options: &OperationOptions,
845    ) -> Result<CredentialPair, Error> {
846        self.check_pair_context(current, "refresh_session")?;
847        let request = RefreshRequest {
848            application_id: &self.application_id,
849            publishable_key: &self.publishable_key,
850            refresh_token: current.refresh_token().expose(),
851        };
852        let url = self.endpoint(&format!(
853            "v1/projects/{}/auth/sessions/refresh",
854            encode_path(&self.project_id)
855        ))?;
856        let wire: CredentialPairWire = self
857            .post_json(
858                url,
859                &request,
860                ResponsePolicy::new(
861                    "refresh_session",
862                    200,
863                    true,
864                    LocalAction::QuarantineCredentials,
865                ),
866                None,
867                options,
868            )
869            .await?;
870        let next =
871            self.validate_credentials(wire, "refresh_session", LocalAction::QuarantineCredentials)?;
872        if next.user_id() != current.user_id()
873            || next.session_id() != current.session_id()
874            || current
875                .refresh_generation()
876                .checked_add(1)
877                .is_none_or(|generation| next.refresh_generation() != generation)
878        {
879            return Err(indeterminate_response(
880                "refresh_session",
881                "invalid_response_after_dispatch",
882                LocalAction::QuarantineCredentials,
883                200,
884            ));
885        }
886        Ok(next)
887    }
888
889    /// Retrieves the bounded current Project user for an exact context-bound credential pair.
890    ///
891    /// # Errors
892    /// Returns an authentication, protocol, or transport error.
893    pub async fn current_user(&self, credentials: &CredentialPair) -> Result<CurrentUser, Error> {
894        self.current_user_with_options(credentials, &OperationOptions::default())
895            .await
896    }
897
898    /// Retrieves the current user with explicit operation controls.
899    ///
900    /// # Errors
901    /// Returns an authentication, protocol, transport, or cancellation error.
902    pub async fn current_user_with_options(
903        &self,
904        credentials: &CredentialPair,
905        options: &OperationOptions,
906    ) -> Result<CurrentUser, Error> {
907        let url = self.endpoint(&format!(
908            "v1/projects/{}/auth/users/me",
909            encode_path(&self.project_id)
910        ))?;
911        let value: CurrentUser = self
912            .bearer_json(
913                HttpMethod::Get,
914                url,
915                credentials,
916                ResponsePolicy::new("get_current_user", 200, false, LocalAction::None),
917                options,
918            )
919            .await?;
920        if value.project_id != self.project_id
921            || value.application_id != self.application_id
922            || value.user_id != value.projection.user_id
923            || value.projection_revision != value.projection.projection_revision
924            || !valid_projection(&value.projection)
925            || parse_time(&value.authenticated_at, "get_current_user").is_err()
926            || parse_time(&value.session_expires_at, "get_current_user").map_or(true, |expiry| {
927                i128::from(expiry) < i128::from(self.clock.now_unix_seconds()) - 60
928            })
929        {
930            return Err(protocol("get_current_user", "context_mismatch"));
931        }
932        Ok(value)
933    }
934
935    /// Revokes only the exact Application session represented by a context-bound pair.
936    ///
937    /// # Errors
938    /// Returns a session error or `Indeterminate` after an ambiguous dispatch.
939    pub async fn logout_application(&self, credentials: &CredentialPair) -> Result<(), Error> {
940        self.logout_application_with_options(credentials, &OperationOptions::default())
941            .await
942    }
943
944    /// Revokes an Application session with explicit operation controls.
945    ///
946    /// # Errors
947    /// Returns a session, cancellation, or indeterminate error.
948    pub async fn logout_application_with_options(
949        &self,
950        credentials: &CredentialPair,
951        options: &OperationOptions,
952    ) -> Result<(), Error> {
953        let url = self.endpoint(&format!(
954            "v1/projects/{}/auth/sessions/logout",
955            encode_path(&self.project_id)
956        ))?;
957        let value: CompletionResponse = self
958            .bearer_json(
959                HttpMethod::Post,
960                url,
961                credentials,
962                ResponsePolicy::new(
963                    "logout_application_session",
964                    200,
965                    true,
966                    LocalAction::QuarantineCredentials,
967                ),
968                options,
969            )
970            .await?;
971        if !value.completed {
972            return Err(indeterminate_response(
973                "logout_application_session",
974                "invalid_response_after_dispatch",
975                LocalAction::QuarantineCredentials,
976                200,
977            ));
978        }
979        Ok(())
980    }
981
982    /// Creates a Hosted Project-browser logout target without navigating to it.
983    ///
984    /// # Errors
985    /// Returns a session, protocol, transport, or indeterminate error.
986    pub async fn prepare_browser_logout(
987        &self,
988        credentials: &CredentialPair,
989    ) -> Result<BrowserLogoutPreparation, Error> {
990        self.prepare_browser_logout_with_options(credentials, &OperationOptions::default())
991            .await
992    }
993
994    /// Creates a browser logout target with explicit operation controls.
995    ///
996    /// # Errors
997    /// Returns a session, protocol, transport, cancellation, or indeterminate error.
998    pub async fn prepare_browser_logout_with_options(
999        &self,
1000        credentials: &CredentialPair,
1001        options: &OperationOptions,
1002    ) -> Result<BrowserLogoutPreparation, Error> {
1003        let url = self.endpoint(&format!(
1004            "v1/projects/{}/auth/browser-logout/prepare",
1005            encode_path(&self.project_id)
1006        ))?;
1007        let value: BrowserLogoutPreparation = self
1008            .bearer_json(
1009                HttpMethod::Post,
1010                url,
1011                credentials,
1012                ResponsePolicy::new(
1013                    "prepare_browser_logout",
1014                    201,
1015                    true,
1016                    LocalAction::QuarantineCredentials,
1017                ),
1018                options,
1019            )
1020            .await?;
1021        if value.hosted_url.chars().count() > 512 || has_ambiguous_url_path(&value.hosted_url) {
1022            return Err(indeterminate_response(
1023                "prepare_browser_logout",
1024                "invalid_response_after_dispatch",
1025                LocalAction::QuarantineCredentials,
1026                201,
1027            ));
1028        }
1029        let hosted = Url::parse(&value.hosted_url).map_err(|_| {
1030            indeterminate_response(
1031                "prepare_browser_logout",
1032                "invalid_response_after_dispatch",
1033                LocalAction::QuarantineCredentials,
1034                201,
1035            )
1036        })?;
1037        if hosted.origin().ascii_serialization() != self.origin
1038            || !hosted.path().starts_with(self.base.path())
1039            || hosted.fragment().is_some()
1040            || hosted.username() != ""
1041            || hosted.password().is_some()
1042        {
1043            return Err(indeterminate_response(
1044                "prepare_browser_logout",
1045                "invalid_response_after_dispatch",
1046                LocalAction::QuarantineCredentials,
1047                201,
1048            ));
1049        }
1050        let expires_at = parse_time(&value.expires_at, "prepare_browser_logout").map_err(|_| {
1051            indeterminate_response(
1052                "prepare_browser_logout",
1053                "invalid_response_after_dispatch",
1054                LocalAction::QuarantineCredentials,
1055                201,
1056            )
1057        })?;
1058        let received_at = i128::from(self.clock.now_unix_seconds());
1059        let expires_at_bound = i128::from(expires_at);
1060        if expires_at_bound < received_at - 60 || expires_at_bound > received_at + 120 {
1061            return Err(indeterminate_response(
1062                "prepare_browser_logout",
1063                "invalid_response_after_dispatch",
1064                LocalAction::QuarantineCredentials,
1065                201,
1066            ));
1067        }
1068        Ok(value)
1069    }
1070
1071    fn random_base64(&self, size: usize, operation: &'static str) -> Result<String, Error> {
1072        let mut bytes = vec![0_u8; size];
1073        self.entropy.fill(&mut bytes).map_err(|_| {
1074            Error::new(
1075                ErrorCategory::Transport,
1076                "entropy_unavailable",
1077                "Secure randomness is unavailable.",
1078                RetryPolicy::Never,
1079                LocalAction::None,
1080                operation,
1081            )
1082        })?;
1083        Ok(URL_SAFE_NO_PAD.encode(bytes))
1084    }
1085
1086    fn endpoint(&self, relative: &str) -> Result<Url, Error> {
1087        self.base
1088            .join(relative)
1089            .map_err(|_| protocol("configuration", "invalid_endpoint"))
1090    }
1091
1092    async fn get_json<T: DeserializeOwned>(
1093        &self,
1094        url: Url,
1095        operation: &'static str,
1096        expected_status: u16,
1097        options: &OperationOptions,
1098    ) -> Result<T, Error> {
1099        self.execute(
1100            HttpRequest {
1101                method: HttpMethod::Get,
1102                url: url.to_string(),
1103                headers: vec![("accept".into(), "application/json".into())],
1104                body: None,
1105                max_response_bytes: MAX_RESPONSE_BYTES,
1106            },
1107            ResponsePolicy::new(operation, expected_status, false, LocalAction::None),
1108            None,
1109            options,
1110        )
1111        .await
1112    }
1113
1114    async fn post_json<T: DeserializeOwned, B: Serialize + Sync>(
1115        &self,
1116        url: Url,
1117        body: &B,
1118        policy: ResponsePolicy,
1119        one_use_guard: Option<&Arc<HandoffGuard>>,
1120        options: &OperationOptions,
1121    ) -> Result<T, Error> {
1122        let body = serde_json::to_vec(body)
1123            .map_err(|_| protocol(policy.operation, "request_serialization"))?;
1124        self.execute(
1125            HttpRequest {
1126                method: HttpMethod::Post,
1127                url: url.to_string(),
1128                headers: vec![
1129                    ("accept".into(), "application/json".into()),
1130                    ("content-type".into(), "application/json".into()),
1131                ],
1132                body: Some(body),
1133                max_response_bytes: MAX_RESPONSE_BYTES,
1134            },
1135            policy,
1136            one_use_guard,
1137            options,
1138        )
1139        .await
1140    }
1141
1142    async fn bearer_json<T: DeserializeOwned>(
1143        &self,
1144        method: HttpMethod,
1145        url: Url,
1146        credentials: &CredentialPair,
1147        policy: ResponsePolicy,
1148        options: &OperationOptions,
1149    ) -> Result<T, Error> {
1150        self.check_pair_context(credentials, policy.operation)?;
1151        self.execute(
1152            HttpRequest {
1153                method,
1154                url: url.to_string(),
1155                headers: vec![
1156                    ("accept".into(), "application/json".into()),
1157                    (
1158                        "authorization".into(),
1159                        format!("Bearer {}", credentials.access_token().expose()),
1160                    ),
1161                ],
1162                body: None,
1163                max_response_bytes: MAX_RESPONSE_BYTES,
1164            },
1165            policy,
1166            None,
1167            options,
1168        )
1169        .await
1170    }
1171
1172    async fn execute<T: DeserializeOwned>(
1173        &self,
1174        request: HttpRequest,
1175        policy: ResponsePolicy,
1176        one_use_guard: Option<&Arc<HandoffGuard>>,
1177        options: &OperationOptions,
1178    ) -> Result<T, Error> {
1179        if options
1180            .cancellation()
1181            .is_some_and(CancellationToken::is_cancelled)
1182        {
1183            return Err(transport_error(
1184                TransportFailure::new(TransportFailureKind::Cancelled, false),
1185                policy.operation,
1186                policy.sensitive,
1187                policy.action,
1188            ));
1189        }
1190        if one_use_guard.is_some_and(|guard| !guard.reserve()) {
1191            return Err(Error::new(
1192                ErrorCategory::Handoff,
1193                "pending_consumed",
1194                "The pending login has already been reserved or consumed.",
1195                RetryPolicy::Never,
1196                LocalAction::DiscardPendingLogin,
1197                policy.operation,
1198            ));
1199        }
1200
1201        let method = request.method;
1202        let started = Instant::now();
1203        let send = self.transport.send(request, self.deadline);
1204        tokio::pin!(send);
1205        let outcome = if let Some(cancellation) = options.cancellation() {
1206            tokio::select! {
1207                biased;
1208                response = &mut send => response,
1209                () = cancellation.cancelled() => Err(TransportFailure::new(
1210                    TransportFailureKind::Cancelled,
1211                    true,
1212                )),
1213            }
1214        } else {
1215            send.await
1216        };
1217        let response = match outcome {
1218            Ok(response) => {
1219                if let Some(guard) = one_use_guard {
1220                    guard.consume();
1221                }
1222                response
1223            }
1224            Err(failure) => {
1225                if let Some(guard) = one_use_guard {
1226                    if failure.dispatched {
1227                        guard.consume();
1228                    } else {
1229                        guard.release();
1230                    }
1231                }
1232                let error =
1233                    transport_error(failure, policy.operation, policy.sensitive, policy.action);
1234                self.emit_error_debug(
1235                    policy.operation,
1236                    method,
1237                    started,
1238                    failure.dispatched,
1239                    None,
1240                    &error,
1241                );
1242                return Err(error);
1243            }
1244        };
1245        let result = parse_response(
1246            &response,
1247            policy.operation,
1248            policy.expected_status,
1249            policy.sensitive,
1250            policy.action,
1251        );
1252        match &result {
1253            Ok(_) => self.emit_success_debug(policy.operation, method, started, response.status),
1254            Err(error) => self.emit_error_debug(
1255                policy.operation,
1256                method,
1257                started,
1258                true,
1259                Some(response.status),
1260                error,
1261            ),
1262        }
1263        result
1264    }
1265
1266    fn emit_success_debug(
1267        &self,
1268        operation: &'static str,
1269        method: HttpMethod,
1270        started: Instant,
1271        status: u16,
1272    ) {
1273        self.emit_debug(&SdkDebugEvent {
1274            operation,
1275            method,
1276            outcome: SdkDebugOutcome::Success,
1277            elapsed_millis: elapsed_millis(started),
1278            dispatched: true,
1279            status: Some(status),
1280            category: None,
1281            code: None,
1282            request_id: None,
1283        });
1284    }
1285
1286    fn emit_error_debug(
1287        &self,
1288        operation: &'static str,
1289        method: HttpMethod,
1290        started: Instant,
1291        dispatched: bool,
1292        response_status: Option<u16>,
1293        error: &Error,
1294    ) {
1295        self.emit_debug(&SdkDebugEvent {
1296            operation,
1297            method,
1298            outcome: debug_outcome(error.category()),
1299            elapsed_millis: elapsed_millis(started),
1300            dispatched,
1301            status: error.status().or(response_status),
1302            category: Some(error.category()),
1303            code: Some(error.code().to_owned()),
1304            request_id: error.request_id().map(str::to_owned),
1305        });
1306    }
1307
1308    fn emit_debug(&self, event: &SdkDebugEvent) {
1309        if let Some(debug_hook) = &self.debug_hook {
1310            let _ = catch_unwind(AssertUnwindSafe(|| debug_hook.emit(event)));
1311        }
1312    }
1313
1314    fn validate_credentials(
1315        &self,
1316        wire: CredentialPairWire,
1317        operation: &'static str,
1318        action: LocalAction,
1319    ) -> Result<CredentialPair, Error> {
1320        let now = self.clock.now_unix_seconds();
1321        if wire.project_id != self.project_id
1322            || wire.application_id != self.application_id
1323            || wire.user_id.is_empty()
1324            || wire.user_id.len() > 96
1325            || wire.session_id.is_empty()
1326            || wire.session_id.len() > 64
1327            || wire.refresh_generation <= 0
1328            || !valid_bearer_token(&wire.access_token, 16_384)
1329            || !valid_opaque_token(&wire.refresh_token, 256)
1330            || wire.token_type != "Bearer"
1331            || !(1..=3600).contains(&wire.expires_in)
1332            || wire.projection_revision <= 0
1333            || wire.projection_revision != wire.projection.projection_revision
1334            || wire.user_id != wire.projection.user_id
1335            || !valid_projection(&wire.projection)
1336            || parse_time(&wire.session_expires_at, operation)
1337                .map_or(true, |expiry| i128::from(expiry) < i128::from(now) - 60)
1338        {
1339            return Err(indeterminate_response(
1340                operation,
1341                "invalid_response_after_dispatch",
1342                action,
1343                200,
1344            ));
1345        }
1346        let access_expires_at = now.checked_add(wire.expires_in).ok_or_else(|| {
1347            indeterminate_response(operation, "invalid_response_after_dispatch", action, 200)
1348        })?;
1349        Ok(CredentialPair::from_wire(
1350            wire,
1351            self.origin.clone(),
1352            self.base.path().to_owned(),
1353            access_expires_at,
1354        ))
1355    }
1356
1357    fn check_pair_context(
1358        &self,
1359        pair: &CredentialPair,
1360        operation: &'static str,
1361    ) -> Result<(), Error> {
1362        if pair.runtime_origin() != self.origin
1363            || pair.runtime_base_path() != self.base.path()
1364            || pair.project_id() != self.project_id
1365            || pair.application_id() != self.application_id
1366            || pair.refresh_generation() <= 0
1367        {
1368            return Err(protocol(operation, "credential_context_mismatch"));
1369        }
1370        Ok(())
1371    }
1372}
1373
1374fn elapsed_millis(started: Instant) -> u64 {
1375    u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)
1376}
1377
1378const fn debug_outcome(category: ErrorCategory) -> SdkDebugOutcome {
1379    match category {
1380        ErrorCategory::Protocol => SdkDebugOutcome::InvalidResponse,
1381        ErrorCategory::Transport => SdkDebugOutcome::TransportError,
1382        ErrorCategory::Timeout => SdkDebugOutcome::Timeout,
1383        ErrorCategory::Cancelled => SdkDebugOutcome::Cancelled,
1384        ErrorCategory::Indeterminate => SdkDebugOutcome::Indeterminate,
1385        _ => SdkDebugOutcome::RuntimeError,
1386    }
1387}
1388
1389fn validate_base_url(value: &str, allow_loopback: bool) -> Result<Url, Error> {
1390    if has_ambiguous_url_path(value) {
1391        return Err(configuration(
1392            "invalid_runtime_url",
1393            "The Runtime URL is invalid.",
1394        ));
1395    }
1396    let mut url = Url::parse(value)
1397        .map_err(|_| configuration("invalid_runtime_url", "The Runtime URL is invalid."))?;
1398    if url.username() != ""
1399        || url.password().is_some()
1400        || url.query().is_some()
1401        || url.fragment().is_some()
1402        || url.host_str().is_none()
1403    {
1404        return Err(configuration(
1405            "invalid_runtime_url",
1406            "The Runtime URL is invalid.",
1407        ));
1408    }
1409    let loopback = url.host_str().is_some_and(is_loopback_host);
1410    if url.scheme() != "https" && !(allow_loopback && loopback && url.scheme() == "http") {
1411        return Err(configuration(
1412            "insecure_runtime_url",
1413            "HTTPS is required outside explicit loopback development.",
1414        ));
1415    }
1416    if !url.path().ends_with('/') {
1417        let path = format!("{}/", url.path());
1418        url.set_path(&path);
1419    }
1420    Ok(url)
1421}
1422
1423fn has_ambiguous_url_path(value: &str) -> bool {
1424    let lower = value.to_ascii_lowercase();
1425    if value.contains('\\')
1426        || lower.contains("%2f")
1427        || lower.contains("%5c")
1428        || lower.contains("%25")
1429    {
1430        return true;
1431    }
1432    let Some((_, authority_and_path)) = value.split_once("://") else {
1433        return true;
1434    };
1435    let Some(path_start) = authority_and_path.find('/') else {
1436        return false;
1437    };
1438    let path = &authority_and_path[path_start..];
1439    let path = path.split_once('?').map_or(path, |(path, _)| path);
1440    let path = path.split_once('#').map_or(path, |(path, _)| path);
1441    path.split('/').any(|segment| {
1442        let decoded = segment.to_ascii_lowercase().replace("%2e", ".");
1443        decoded == "." || decoded == ".."
1444    })
1445}
1446
1447fn validate_identifier(value: &str, maximum: usize, field: &str) -> Result<(), Error> {
1448    if value.is_empty()
1449        || value.len() > maximum
1450        || !value
1451            .bytes()
1452            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
1453    {
1454        return Err(configuration(
1455            "invalid_identifier",
1456            &format!("The configured {field} is invalid."),
1457        ));
1458    }
1459    Ok(())
1460}
1461
1462fn validate_redirect(value: &str) -> Result<(), Error> {
1463    let invalid = || configuration("invalid_redirect_uri", "The redirect URI is invalid.");
1464    let lower = value.to_ascii_lowercase();
1465    if !(8..=2048).contains(&value.len())
1466        || value.contains('\\')
1467        || value.bytes().any(|byte| byte.is_ascii_whitespace())
1468        || lower.contains("%2f")
1469        || lower.contains("%5c")
1470    {
1471        return Err(invalid());
1472    }
1473    let url = Url::parse(value).map_err(|_| invalid())?;
1474    if url.as_str() != value
1475        || url.fragment().is_some()
1476        || url.username() != ""
1477        || url.password().is_some()
1478        || url.host_str().is_some_and(|host| host.contains('*'))
1479        || url
1480            .query_pairs()
1481            .any(|(name, _)| matches!(name.as_ref(), "handoff" | "error" | "state"))
1482    {
1483        return Err(invalid());
1484    }
1485    let admitted = match url.scheme() {
1486        "https" => url.host_str().is_some(),
1487        "http" => url.host_str().is_some_and(is_loopback_host),
1488        scheme => {
1489            scheme.contains('.')
1490                && url.host_str().is_none()
1491                && !matches!(
1492                    scheme,
1493                    "about"
1494                        | "blob"
1495                        | "data"
1496                        | "file"
1497                        | "ftp"
1498                        | "javascript"
1499                        | "mailto"
1500                        | "vbscript"
1501                        | "ws"
1502                        | "wss"
1503                )
1504        }
1505    };
1506    if !admitted {
1507        return Err(invalid());
1508    }
1509    Ok(())
1510}
1511
1512fn is_loopback_host(host: &str) -> bool {
1513    host == "localhost"
1514        || host
1515            .parse::<IpAddr>()
1516            .is_ok_and(|address| address.is_loopback())
1517}
1518
1519fn encode_path(value: &str) -> String {
1520    url::form_urlencoded::byte_serialize(value.as_bytes()).collect()
1521}
1522
1523fn parse_time(value: &str, operation: &'static str) -> Result<i64, Error> {
1524    if value.len() > 64 {
1525        return Err(protocol(operation, "invalid_timestamp"));
1526    }
1527    OffsetDateTime::parse(value, &Rfc3339)
1528        .map(OffsetDateTime::unix_timestamp)
1529        .map_err(|_| protocol(operation, "invalid_timestamp"))
1530}
1531
1532fn valid_ed25519_key(value: &str) -> bool {
1533    URL_SAFE_NO_PAD
1534        .decode(value)
1535        .is_ok_and(|bytes| bytes.len() == 32 && URL_SAFE_NO_PAD.encode(bytes) == value)
1536}
1537
1538fn valid_bearer_token(value: &str, maximum: usize) -> bool {
1539    !value.is_empty()
1540        && value.len() <= maximum
1541        && value.bytes().all(|byte| {
1542            byte.is_ascii_alphanumeric()
1543                || matches!(byte, b'-' | b'.' | b'_' | b'~' | b'+' | b'/' | b'=')
1544        })
1545}
1546
1547fn valid_opaque_token(value: &str, maximum: usize) -> bool {
1548    !value.is_empty()
1549        && value.len() <= maximum
1550        && value
1551            .bytes()
1552            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~'))
1553}
1554
1555fn valid_projection(value: &crate::UserProjection) -> bool {
1556    !value.user_id.is_empty()
1557        && value.user_id.len() <= 96
1558        && value.user_revision > 0
1559        && value.projection_schema == "owlauth.user.v1"
1560        && value.projection_revision > 0
1561        && value
1562            .display_name
1563            .as_ref()
1564            .is_none_or(|name| name.chars().count() <= 128)
1565        && value
1566            .picture_url
1567            .as_ref()
1568            .is_none_or(|url| url.chars().count() <= 2048)
1569        && value.locale.as_ref().is_none_or(|locale| {
1570            (2..=35).contains(&locale.len())
1571                && !locale.starts_with('-')
1572                && !locale.ends_with('-')
1573                && !locale.contains("--")
1574                && locale
1575                    .bytes()
1576                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
1577        })
1578        && value.verified_email.as_ref().is_none_or(|email| {
1579            (3..=320).contains(&email.chars().count()) && !email.chars().any(char::is_control)
1580        })
1581        && value.status == "active"
1582        && parse_time(&value.created_at, "projection").is_ok()
1583        && parse_time(&value.updated_at, "projection").is_ok()
1584}
1585
1586fn transport_error(
1587    failure: TransportFailure,
1588    operation: &'static str,
1589    sensitive: bool,
1590    action: LocalAction,
1591) -> Error {
1592    if sensitive && failure.dispatched {
1593        return Error::new(
1594            ErrorCategory::Indeterminate,
1595            "outcome_indeterminate",
1596            "The Runtime outcome cannot be determined safely.",
1597            RetryPolicy::Never,
1598            action,
1599            operation,
1600        );
1601    }
1602    let (category, code, message) = match failure.kind {
1603        TransportFailureKind::Timeout => (
1604            ErrorCategory::Timeout,
1605            "timeout",
1606            "The Runtime request timed out.",
1607        ),
1608        TransportFailureKind::Cancelled => (
1609            ErrorCategory::Cancelled,
1610            "cancelled",
1611            "The Runtime request was cancelled.",
1612        ),
1613        TransportFailureKind::ResponseTooLarge => (
1614            ErrorCategory::Protocol,
1615            "invalid_response",
1616            "Runtime returned an invalid or incompatible response.",
1617        ),
1618        TransportFailureKind::Transport => (
1619            ErrorCategory::Transport,
1620            "transport_error",
1621            "The Runtime request could not be completed.",
1622        ),
1623    };
1624    Error::new(
1625        category,
1626        code,
1627        message,
1628        if failure.kind == TransportFailureKind::ResponseTooLarge {
1629            RetryPolicy::Never
1630        } else {
1631            RetryPolicy::ApplicationDecision
1632        },
1633        if failure.dispatched {
1634            action
1635        } else {
1636            LocalAction::None
1637        },
1638        operation,
1639    )
1640}
1641
1642fn protocol_with_action(operation: &'static str, code: &str, action: LocalAction) -> Error {
1643    Error::new(
1644        ErrorCategory::Protocol,
1645        code,
1646        "Runtime returned an invalid or incompatible response.",
1647        RetryPolicy::Never,
1648        action,
1649        operation,
1650    )
1651}
1652
1653fn indeterminate_response(
1654    operation: &'static str,
1655    code: &str,
1656    action: LocalAction,
1657    status: u16,
1658) -> Error {
1659    Error::new(
1660        ErrorCategory::Indeterminate,
1661        code,
1662        "Runtime may have committed the operation; do not replay it.",
1663        RetryPolicy::Never,
1664        action,
1665        operation,
1666    )
1667    .with_runtime(status, None)
1668}
1669
1670fn invalid_response(
1671    operation: &'static str,
1672    _code: &str,
1673    sensitive: bool,
1674    action: LocalAction,
1675    status: u16,
1676) -> Error {
1677    if sensitive {
1678        indeterminate_response(operation, "invalid_response_after_dispatch", action, status)
1679    } else {
1680        protocol_with_action(operation, "invalid_response", action).with_runtime(status, None)
1681    }
1682}
1683
1684fn parse_response<T: DeserializeOwned>(
1685    response: &HttpResponse,
1686    operation: &'static str,
1687    expected_status: u16,
1688    sensitive: bool,
1689    action: LocalAction,
1690) -> Result<T, Error> {
1691    if response.body.len() > MAX_RESPONSE_BYTES {
1692        return Err(invalid_response(
1693            operation,
1694            "response_too_large",
1695            sensitive,
1696            action,
1697            response.status,
1698        ));
1699    }
1700    let content_types: Vec<&str> = response
1701        .headers
1702        .iter()
1703        .filter(|(name, _)| name.eq_ignore_ascii_case("content-type"))
1704        .map(|(_, value)| value.split(';').next().unwrap_or_default().trim())
1705        .collect();
1706    if content_types.len() != 1 || !content_types[0].eq_ignore_ascii_case("application/json") {
1707        return Err(invalid_response(
1708            operation,
1709            "invalid_content_type",
1710            sensitive,
1711            action,
1712            response.status,
1713        ));
1714    }
1715    if response.status == expected_status {
1716        return serde_json::from_slice(&response.body).map_err(|_| {
1717            invalid_response(
1718                operation,
1719                "invalid_json_response",
1720                sensitive,
1721                action,
1722                response.status,
1723            )
1724        });
1725    }
1726    if !allowed_error_statuses(operation).contains(&response.status) {
1727        return Err(invalid_response(
1728            operation,
1729            "unexpected_status",
1730            sensitive,
1731            action,
1732            response.status,
1733        ));
1734    }
1735    parse_runtime_error(response, operation, sensitive, action)
1736}
1737
1738fn parse_runtime_error<T>(
1739    response: &HttpResponse,
1740    operation: &'static str,
1741    sensitive: bool,
1742    action: LocalAction,
1743) -> Result<T, Error> {
1744    let wire = serde_json::from_slice::<RuntimeErrorWire>(&response.body).map_err(|_| {
1745        invalid_response(
1746            operation,
1747            "invalid_error_response",
1748            sensitive,
1749            action,
1750            response.status,
1751        )
1752    })?;
1753    if wire.message.is_empty()
1754        || wire.message.chars().count() > 256
1755        || wire.request_id.is_empty()
1756        || wire.request_id.chars().count() > 128
1757    {
1758        return Err(invalid_response(
1759            operation,
1760            "invalid_error_response",
1761            sensitive,
1762            action,
1763            response.status,
1764        ));
1765    }
1766    let retry_after_seconds =
1767        runtime_retry_after(response, &wire.code, operation, sensitive, action)?;
1768    let request_id = sanitize_request_id(Some(wire.request_id));
1769    let code = wire.code;
1770    if !valid_runtime_error_code(&code) {
1771        return Err(invalid_response(
1772            operation,
1773            "invalid_error_response",
1774            sensitive,
1775            action,
1776            response.status,
1777        ));
1778    }
1779    if response.status == 408 {
1780        if code != "request_timeout" {
1781            return Err(invalid_response(
1782                operation,
1783                "invalid_timeout_response",
1784                sensitive,
1785                action,
1786                response.status,
1787            ));
1788        }
1789        return Err(runtime_request_timeout(
1790            operation, sensitive, action, request_id,
1791        ));
1792    }
1793    if sensitive && response.status >= 500 {
1794        return Err(indeterminate_response(
1795            operation,
1796            "runtime_5xx_after_dispatch",
1797            action,
1798            response.status,
1799        ));
1800    }
1801    let (category, retry, local_action) =
1802        runtime_error_semantics(response.status, &code, operation, action);
1803    let mut error = Error::new(
1804        category,
1805        code,
1806        "Runtime rejected the Project Auth operation.",
1807        retry,
1808        local_action,
1809        operation,
1810    )
1811    .with_runtime(response.status, request_id);
1812    if let Some(seconds) = retry_after_seconds {
1813        error = error.with_retry_after(seconds);
1814    }
1815    Err(error)
1816}
1817
1818fn runtime_retry_after(
1819    response: &HttpResponse,
1820    code: &str,
1821    operation: &'static str,
1822    sensitive: bool,
1823    action: LocalAction,
1824) -> Result<Option<u64>, Error> {
1825    if response.status != 429 {
1826        return Ok(None);
1827    }
1828    if code != "rate_limited" {
1829        return Err(invalid_response(
1830            operation,
1831            "invalid_rate_limit_response",
1832            sensitive,
1833            action,
1834            response.status,
1835        ));
1836    }
1837    retry_after_seconds(response).map(Some).ok_or_else(|| {
1838        invalid_response(
1839            operation,
1840            "invalid_rate_limit_response",
1841            sensitive,
1842            action,
1843            response.status,
1844        )
1845    })
1846}
1847
1848fn runtime_request_timeout(
1849    operation: &'static str,
1850    sensitive: bool,
1851    action: LocalAction,
1852    request_id: Option<String>,
1853) -> Error {
1854    let (category, retry, local_action, message) = if sensitive {
1855        (
1856            ErrorCategory::Indeterminate,
1857            RetryPolicy::Never,
1858            action,
1859            "Runtime may have committed the operation; do not replay it.",
1860        )
1861    } else {
1862        (
1863            ErrorCategory::Timeout,
1864            RetryPolicy::ApplicationDecision,
1865            LocalAction::None,
1866            "The Runtime request exceeded its server-side deadline.",
1867        )
1868    };
1869    Error::new(
1870        category,
1871        "request_timeout",
1872        message,
1873        retry,
1874        local_action,
1875        operation,
1876    )
1877    .with_runtime(408, request_id)
1878}
1879
1880fn sanitize_request_id(value: Option<String>) -> Option<String> {
1881    value.filter(|value| {
1882        !value.is_empty()
1883            && value.len() <= 128
1884            && value.bytes().all(|byte| {
1885                byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':')
1886            })
1887    })
1888}
1889
1890fn valid_runtime_error_code(code: &str) -> bool {
1891    let mut bytes = code.bytes();
1892    code.len() <= 64
1893        && bytes.next().is_some_and(|byte| byte.is_ascii_lowercase())
1894        && bytes.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1895}
1896
1897fn allowed_error_statuses(operation: &str) -> &'static [u16] {
1898    match operation {
1899        "get_public_application_config" | "start_login" => &[400, 404, 408, 429, 503],
1900        "get_project_jwks" => &[404, 408, 429, 503],
1901        "exchange_handoff" | "refresh_session" => &[400, 408, 409, 429, 503],
1902        "get_current_user" | "logout_application_session" | "prepare_browser_logout" => {
1903            &[401, 408, 429, 503]
1904        }
1905        _ => &[],
1906    }
1907}
1908
1909fn retry_after_seconds(response: &HttpResponse) -> Option<u64> {
1910    let values: Vec<&str> = response
1911        .headers
1912        .iter()
1913        .filter(|(name, _)| name.eq_ignore_ascii_case("retry-after"))
1914        .map(|(_, value)| value.as_str())
1915        .collect();
1916    if values.len() != 1
1917        || values[0].is_empty()
1918        || !values[0].bytes().all(|byte| byte.is_ascii_digit())
1919    {
1920        return None;
1921    }
1922    values[0]
1923        .parse::<u64>()
1924        .ok()
1925        .filter(|seconds| *seconds <= 86_400)
1926}
1927
1928fn runtime_error_semantics(
1929    status: u16,
1930    code: &str,
1931    operation: &'static str,
1932    action: LocalAction,
1933) -> (ErrorCategory, RetryPolicy, LocalAction) {
1934    if status == 429 && code == "rate_limited" {
1935        return match operation {
1936            "exchange_handoff" => (
1937                ErrorCategory::RateLimited,
1938                RetryPolicy::Never,
1939                LocalAction::DiscardPendingLogin,
1940            ),
1941            "refresh_session" | "logout_application_session" | "prepare_browser_logout" => (
1942                ErrorCategory::RateLimited,
1943                RetryPolicy::ApplicationDecision,
1944                LocalAction::None,
1945            ),
1946            _ => (
1947                ErrorCategory::RateLimited,
1948                RetryPolicy::SafeAfterDelay,
1949                LocalAction::None,
1950            ),
1951        };
1952    }
1953    match operation {
1954        "start_login" => (
1955            ErrorCategory::Login,
1956            RetryPolicy::Never,
1957            LocalAction::DiscardPendingLogin,
1958        ),
1959        "exchange_handoff" => (
1960            ErrorCategory::Handoff,
1961            RetryPolicy::Never,
1962            LocalAction::DiscardPendingLogin,
1963        ),
1964        "refresh_session" => (
1965            ErrorCategory::Refresh,
1966            RetryPolicy::Never,
1967            LocalAction::ClearCredentials,
1968        ),
1969        "get_current_user" => (
1970            ErrorCategory::Authentication,
1971            RetryPolicy::Never,
1972            LocalAction::Reauthenticate,
1973        ),
1974        "logout_application_session" | "prepare_browser_logout" => {
1975            (ErrorCategory::Session, RetryPolicy::Never, action)
1976        }
1977        _ if status >= 500 => (
1978            ErrorCategory::Transport,
1979            RetryPolicy::ApplicationDecision,
1980            action,
1981        ),
1982        _ => (ErrorCategory::Protocol, RetryPolicy::Never, action),
1983    }
1984}