alibi-core 0.6.0

Shared authentication contracts and backend-independent services for Alibi
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//! Trusted endpoint calls keep logical input separate from an optional HTTP request.

use crate::AuthContext;
use crate::session::SessionRequest;
use crate::types::RequestExtensions;
use crate::utils::LockUnpoisoned;
use crate::utils::json::JsValue;
use crate::wire::{SessionView, UserView};
use crate::{AuthError, AuthRequest, AuthResult, AuthSchema, Headers, HttpMethod};
use serde::{Serialize, de::DeserializeOwned};
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};

/// An operation registered by an installed plugin, independently of its HTTP routes.
#[derive(Clone, Debug)]
pub struct EndpointDefinition {
    pub name: &'static str,
    pub operation_id: &'static str,
    pub path: Option<String>,
    pub method: HttpMethod,
}

/// Typed operation input. Dispatch decodes the final input after before-hook patches.
#[derive(Clone, Debug)]
pub struct ServerEndpoint<T> {
    plugin: &'static str,
    name: &'static str,
    body: Option<JsValue>,
    query: Option<JsValue>,
    output: PhantomData<fn() -> T>,
}

impl<T> ServerEndpoint<T> {
    #[must_use]
    pub const fn new(plugin: &'static str, name: &'static str) -> Self {
        Self {
            plugin,
            name,
            body: None,
            query: None,
            output: PhantomData,
        }
    }

    /// # Errors
    /// Returns an error if application input cannot be serialized.
    pub fn with_body(mut self, body: &impl Serialize) -> AuthResult<Self> {
        self.body = Some(crate::utils::json::parse_value(
            &crate::utils::json::to_string(body)?,
        )?);
        Ok(self)
    }

    /// # Errors
    /// Returns an error if application input cannot be serialized.
    pub fn with_query(mut self, query: &impl Serialize) -> AuthResult<Self> {
        self.query = Some(crate::utils::json::parse_value(
            &crate::utils::json::to_string(query)?,
        )?);
        Ok(self)
    }

    #[must_use]
    pub fn with_body_value(mut self, body: JsValue) -> Self {
        self.body = Some(body);
        self
    }

    #[must_use]
    pub fn with_query_value(mut self, query: JsValue) -> Self {
        self.query = Some(query);
        self
    }

    #[must_use]
    pub const fn plugin(&self) -> &'static str {
        self.plugin
    }

    #[must_use]
    pub const fn name(&self) -> &'static str {
        self.name
    }

    #[must_use]
    pub fn input(self) -> (Option<JsValue>, Option<JsValue>) {
        (self.body, self.query)
    }
}

/// Per-call options. Absent headers remain distinct from an explicitly empty collection.
#[derive(Clone, Debug, Default)]
pub struct EndpointOptions {
    pub headers: Option<HashMap<String, String>>,
    pub request: Option<AuthRequest>,
    pub method: Option<HttpMethod>,
}

#[derive(Clone, Debug, Default)]
struct EndpointState {
    session: Option<SessionView>,
    principal: Option<(UserView, SessionView)>,
    response_headers: Headers,
    session_observation: Option<(UserView, SessionView)>,
}

struct VerifiedEndpointUser<S: AuthSchema> {
    user: S::User,
    config: Arc<crate::AuthConfig>,
    database: Arc<dyn crate::AuthStore<S>>,
}

/// Runtime normalization phase, retaining absence in original logical inputs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EndpointPhase {
    Raw,
    Middleware,
    Handler,
}

/// Genuine logical endpoint data available to hooks and application callbacks.
///
/// Clones share trusted session state, observed snapshots and queued headers.
/// Every public dispatch constructs fresh state; supplied HTTP metadata cannot
/// carry a caller-populated virtual principal into this context.
#[derive(Clone, Debug)]
pub struct EndpointCall {
    operation_id: String,
    path: Option<String>,
    method: Option<HttpMethod>,
    body: Option<JsValue>,
    query: Option<JsValue>,
    headers: Option<HashMap<String, String>>,
    request: Option<AuthRequest>,
    default_method: HttpMethod,
    phase: EndpointPhase,
    extensions: RequestExtensions,
    state: Arc<Mutex<EndpointState>>,
}

impl EndpointCall {
    #[must_use]
    pub fn new(
        definition: &EndpointDefinition,
        body: Option<JsValue>,
        query: Option<JsValue>,
        options: EndpointOptions,
    ) -> Self {
        Self {
            operation_id: definition.operation_id.into(),
            path: definition.path.clone(),
            method: options.method,
            body,
            query,
            headers: options.headers.map(|headers| {
                headers
                    .into_iter()
                    .map(|(name, value)| (name.to_ascii_lowercase(), value))
                    .collect()
            }),
            request: options.request.map(fresh_request),
            default_method: definition.method.clone(),
            phase: EndpointPhase::Raw,
            extensions: RequestExtensions::default(),
            state: Arc::new(Mutex::new(EndpointState::default())),
        }
    }

    /// Logical HTTP endpoint input after physical routing and body parsing.
    /// The original physical request remains separate from normalized hook input.
    #[must_use]
    pub fn from_http_request(request: &AuthRequest, route: &crate::AuthRoute) -> Self {
        let body = request
            .extensions()
            .get::<crate::types::ParsedRequestBody>()
            .and_then(|body| match body.as_ref() {
                crate::types::ParsedRequestBody::Value(value) => Some(value.clone()),
                crate::types::ParsedRequestBody::Opaque(_) => None,
            });
        let query = JsValue::Object(
            request
                .query
                .keys()
                .map(|name| {
                    let values = request.query_values(name).unwrap_or_default();
                    let value = if values.len() > 1 {
                        JsValue::Array(values.iter().cloned().map(JsValue::String).collect())
                    } else {
                        JsValue::String(request.query.get(name).cloned().unwrap_or_default())
                    };
                    (name.clone(), value)
                })
                .collect(),
        );
        let definition = EndpointDefinition {
            name: "http",
            operation_id: "http",
            path: Some(route.context_path.as_ref().unwrap_or(&route.path).clone()),
            method: route.method.clone(),
        };
        let mut call = Self::new(
            &definition,
            body,
            Some(query),
            EndpointOptions {
                headers: Some(request.headers.clone()),
                request: Some(
                    crate::hooks::current_request_hook_context()
                        .map_or_else(|| request.clone(), |context| context.request),
                ),
                method: Some(request.method.clone()),
            },
        );
        call.operation_id.clone_from(&route.operation_id);
        call
    }

    #[must_use]
    pub fn operation_id(&self) -> &str {
        &self.operation_id
    }

    #[must_use]
    pub fn path(&self) -> Option<&str> {
        self.path.as_deref()
    }

    #[must_use]
    pub const fn method(&self) -> Option<&HttpMethod> {
        self.method.as_ref()
    }

    #[must_use]
    pub const fn body(&self) -> Option<&JsValue> {
        self.body.as_ref()
    }

    #[must_use]
    pub const fn query(&self) -> Option<&JsValue> {
        self.query.as_ref()
    }

    #[must_use]
    pub const fn headers(&self) -> Option<&HashMap<String, String>> {
        self.headers.as_ref()
    }

    /// Replace logical headers after a physical/plugin header transformation.
    /// Session state and the distinct physical Request are retained.
    pub fn replace_headers(&mut self, headers: HashMap<String, String>) {
        self.headers = Some(headers);
    }

    #[must_use]
    pub const fn request(&self) -> Option<&AuthRequest> {
        self.request.as_ref()
    }

    #[must_use]
    pub const fn phase(&self) -> EndpointPhase {
        self.phase
    }

    #[must_use]
    pub fn has_body(&self) -> bool {
        self.phase != EndpointPhase::Raw || self.body.is_some()
    }

    #[must_use]
    pub fn has_query(&self) -> bool {
        self.phase != EndpointPhase::Raw || self.query.is_some()
    }

    #[must_use]
    pub fn has_method(&self) -> bool {
        self.phase != EndpointPhase::Raw || self.method.is_some()
    }

    /// Middleware callbacks have their own path/query defaults; matchers retain raw input.
    #[must_use]
    pub fn middleware_context(&self) -> Self {
        let mut context = self.clone();
        context.phase = EndpointPhase::Middleware;
        if context.path.as_ref().is_none_or(String::is_empty) {
            context.path = Some("/".into());
        }
        context
    }

    /// A handler receives validated data and its registered method/path defaults.
    #[must_use]
    pub fn handler_context(&self, body: Option<JsValue>, query: Option<JsValue>) -> Self {
        let mut context = self.clone();
        context.phase = EndpointPhase::Handler;
        if context.path.as_ref().is_none_or(String::is_empty) {
            context.path = Some("virtual:".into());
        }
        if context.method.is_none() {
            context.method = Some(context.default_method.clone());
        }
        context.body = body;
        context.query = query;
        context
    }

    /// The nested session getter preserves caller input and validates its own query.
    pub(crate) fn session_read_context(&self) -> Self {
        let mut context = self.clone();
        context.phase = EndpointPhase::Handler;
        if context.path.as_ref().is_none_or(String::is_empty) {
            context.path = Some("virtual:".into());
        }
        context.method = Some(HttpMethod::Get);
        let mut query = indexmap::IndexMap::new();
        for name in ["disableCookieCache", "disableRefresh"] {
            if self
                .query
                .as_ref()
                .and_then(|value| value.get(name))
                .is_some()
            {
                _ = query.insert(name.into(), JsValue::Bool(self.session_query_truthy(name)));
            }
        }
        context.query = Some(JsValue::Object(query));
        context
    }

    #[must_use]
    pub const fn extensions(&self) -> &RequestExtensions {
        &self.extensions
    }

    #[must_use]
    pub const fn default_method(&self) -> &HttpMethod {
        &self.default_method
    }

    #[must_use]
    pub fn virtual_session(&self) -> Option<SessionView> {
        self.state.lock_unpoisoned().session.clone()
    }

    /// Retain the actual model and snapshot after a trusted hook has authenticated them.
    /// This is an application/plugin authority boundary, never client input.
    pub fn establish_session<S: AuthSchema>(
        &self,
        user: S::User,
        user_view: UserView,
        session: SessionView,
        context: &AuthContext<S>,
    ) {
        self.extensions.insert(VerifiedEndpointUser::<S> {
            user,
            config: context.config.clone(),
            database: context.database.clone(),
        });
        let mut state = self.state.lock_unpoisoned();
        state.principal = Some((user_view, session.clone()));
        state.session = Some(session);
    }

    /// Callback-visible authenticated data. This observation does not confer authority.
    #[must_use]
    pub fn session(&self) -> Option<(UserView, SessionView)> {
        self.state.lock_unpoisoned().principal.clone()
    }

    pub fn record_authenticated_session(&self, user: UserView, session: SessionView) {
        self.state.lock_unpoisoned().principal = Some((user, session));
    }

    #[must_use]
    pub fn authenticated_user<S: AuthSchema>(&self, context: &AuthContext<S>) -> Option<S::User> {
        self.extensions
            .get::<VerifiedEndpointUser<S>>()
            .filter(|user| {
                Arc::ptr_eq(&user.config, &context.config)
                    && Arc::ptr_eq(&user.database, &context.database)
            })
            .map(|user| user.user.clone())
    }

    pub fn set_response_header(&self, name: impl Into<String>, value: impl Into<String>) {
        _ = self
            .state
            .lock_unpoisoned()
            .response_headers
            .insert(name, value);
    }

    pub fn queue_response_header(&self, name: impl Into<String>, value: impl Into<String>) {
        self.state
            .lock_unpoisoned()
            .response_headers
            .append(name, value);
    }

    pub fn take_response_headers(&self) -> Headers {
        std::mem::take(&mut self.state.lock_unpoisoned().response_headers)
    }

    pub fn set_session_hook_snapshot(&self, user: UserView, session: SessionView) {
        self.state.lock_unpoisoned().session_observation = Some((user, session));
    }

    #[must_use]
    pub fn session_hook_snapshot(&self) -> Option<(UserView, SessionView)> {
        self.state.lock_unpoisoned().session_observation.clone()
    }

    /// # Errors
    /// Returns a typed decoding error for the current, post-hook body.
    pub fn body_as<T: DeserializeOwned + 'static>(&self) -> AuthResult<T> {
        Ok(crate::utils::json::from_value(
            self.body.clone().unwrap_or(JsValue::Null),
        )?)
    }

    /// # Errors
    /// Returns a typed decoding error for the current, post-hook query.
    pub fn query_as<T: DeserializeOwned + 'static>(&self) -> AuthResult<T> {
        Ok(crate::utils::json::from_value(
            self.query.clone().unwrap_or(JsValue::Null),
        )?)
    }
}

/// Context patches accumulate without replacing the original input seen by later before hooks.
#[derive(Clone, Debug, Default)]
pub struct EndpointContextPatch {
    pub method: Option<HttpMethod>,
    pub request: Option<AuthRequest>,
    pub path: Option<String>,
    pub body: Option<JsValue>,
    pub query: Option<JsValue>,
    pub headers: Option<HashMap<String, String>>,
}

impl EndpointContextPatch {
    pub fn merge(&mut self, patch: Self) {
        if let Some(method) = patch.method {
            self.method = Some(method);
        }
        if let Some(request) = patch.request {
            self.request = Some(request);
        }
        if let Some(path) = patch.path {
            self.path = Some(path);
        }
        merge_optional(&mut self.body, patch.body);
        merge_optional(&mut self.query, patch.query);
        if let Some(headers) = patch.headers {
            self.headers.get_or_insert_with(HashMap::new).extend(
                headers
                    .into_iter()
                    .map(|(name, value)| (name.to_ascii_lowercase(), value)),
            );
        }
    }

    pub fn apply(self, call: &mut EndpointCall) {
        if let Some(method) = self.method {
            call.method = Some(method);
        }
        if let Some(request) = self.request {
            call.request = Some(fresh_request(request));
        }
        if let Some(path) = self.path {
            call.path = Some(path);
        }
        merge_optional(&mut call.body, self.body);
        merge_optional(&mut call.query, self.query);
        if let Some(headers) = self.headers {
            call.headers
                .get_or_insert_with(HashMap::new)
                .extend(headers);
        }
    }
}

fn merge_optional(target: &mut Option<JsValue>, patch: Option<JsValue>) {
    if let Some(patch) = patch.filter(|value| !value.is_null()) {
        if let Some(target) = target {
            merge_value(target, patch);
        } else {
            *target = Some(patch);
        }
    }
}

fn merge_value(target: &mut JsValue, patch: JsValue) {
    if let (JsValue::Object(target), JsValue::Object(patch)) = (&mut *target, &patch) {
        for (name, value) in patch {
            if value.is_null() || matches!(name.as_str(), "__proto__" | "constructor") {
                continue;
            }
            if let Some(target) = target.get_mut(name) {
                merge_value(target, value.clone());
            } else {
                _ = target.insert(name.clone(), value.clone());
            }
        }
    } else {
        *target = patch;
    }
}

/// A before hook can accumulate input changes or finish without reaching the handler/after hooks.
#[derive(Debug)]
pub enum BeforeEndpointAction {
    Patch(Box<EndpointContextPatch>),
    Respond(EndpointResponse),
    /// Reject with an intentional API error and its complete public body.
    Reject(EndpointResponse),
}

/// Validated handler input. The dispatcher retains raw patched data for after hooks.
#[derive(Clone, Debug, Default)]
pub struct EndpointInput {
    pub body: Option<JsValue>,
    pub query: Option<JsValue>,
}

/// A returned value or intentional API error, available to completed endpoint hooks.
#[derive(Debug)]
pub struct EndpointResponse {
    result: Result<JsValue, AuthError>,
    error_body: Option<JsValue>,
    headers: Headers,
    status: Option<u16>,
}

impl EndpointResponse {
    #[must_use]
    pub fn value(value: JsValue) -> Self {
        Self {
            result: Ok(value),
            error_body: None,
            headers: Headers::new(),
            status: None,
        }
    }

    /// # Errors
    /// Returns an error if the endpoint value cannot be serialized.
    pub fn json(value: &impl Serialize) -> AuthResult<Self> {
        Ok(Self::value(crate::utils::json::parse_value(
            &crate::utils::json::to_string(value)?,
        )?))
    }

    #[must_use]
    pub fn error(error: AuthError) -> Self {
        let status = Some(error.status_code());
        Self {
            result: Err(error),
            error_body: None,
            headers: Headers::new(),
            status,
        }
    }

    #[must_use]
    pub fn with_error_body(mut self, body: JsValue) -> Self {
        self.error_body = Some(body);
        self
    }

    #[must_use]
    pub const fn error_body(&self) -> Option<&JsValue> {
        self.error_body.as_ref()
    }

    pub const fn result(&self) -> &Result<JsValue, AuthError> {
        &self.result
    }

    #[must_use]
    pub const fn headers(&self) -> &Headers {
        &self.headers
    }

    #[must_use]
    pub const fn status(&self) -> Option<u16> {
        self.status
    }

    pub fn set_status(&mut self, status: Option<u16>) {
        self.status = status;
    }

    #[must_use]
    pub fn with_status(mut self, status: u16) -> Self {
        self.status = Some(status);
        self
    }

    #[must_use]
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        merge_header(&mut self.headers, name.into(), value.into());
        self
    }

    pub fn merge_headers(&mut self, headers: Headers) {
        for (name, value) in headers {
            merge_header(&mut self.headers, name, value);
        }
    }

    /// Replace a returned value while retaining the actual handler status and headers.
    pub fn replace(&mut self, value: JsValue) {
        self.result = Ok(value);
        self.error_body = None;
    }

    pub fn replace_error(&mut self, error: AuthError) {
        self.result = Err(error);
        self.error_body = None;
    }

    pub fn into_output<T>(self) -> Result<EndpointOutput<T>, EndpointError> {
        match self.result {
            Ok(value) => Ok(EndpointOutput {
                value,
                headers: self.headers,
                status: self.status,
                output: PhantomData,
            }),
            Err(error) => Err(EndpointError {
                error,
                headers: Some(self.headers),
                body: self.error_body.map(Box::new),
            }),
        }
    }
}

fn merge_header(headers: &mut Headers, name: String, value: String) {
    if name.eq_ignore_ascii_case("set-cookie") {
        headers.append(name, value);
    } else {
        _ = headers.insert(name, value);
    }
}

/// Installed application middleware for logical endpoint calls.
#[async_trait::async_trait]
pub trait EndpointHook<S: AuthSchema>: Send + Sync {
    /// Matchers observe raw logical context, before middleware normalization.
    /// # Errors
    /// Returns an application matcher error, which dispatch logs and masks.
    fn matches_before(&self, _call: &EndpointCall, _ctx: &AuthContext<S>) -> AuthResult<bool> {
        Ok(true)
    }

    /// # Errors
    /// Propagates actual callback failures without reaching later hooks or the handler.
    async fn before(
        &self,
        _call: &EndpointCall,
        _ctx: &AuthContext<S>,
    ) -> AuthResult<Option<BeforeEndpointAction>> {
        Ok(None)
    }

    /// # Errors
    /// Propagates actual after-matcher failures.
    fn matches_after(
        &self,
        _call: &EndpointCall,
        _ctx: &AuthContext<S>,
        _response: &EndpointResponse,
    ) -> AuthResult<bool> {
        Ok(true)
    }

    /// # Errors
    /// API errors replace the result and continue; ordinary failures abort remaining hooks.
    async fn after(
        &self,
        _call: &EndpointCall,
        _ctx: &AuthContext<S>,
        response: EndpointResponse,
    ) -> AuthResult<EndpointResponse> {
        Ok(response)
    }
}

/// A successful call retains the actual value, since after hooks can replace its shape.
#[derive(Debug)]
pub struct EndpointOutput<T> {
    value: JsValue,
    headers: Headers,
    status: Option<u16>,
    output: PhantomData<fn() -> T>,
}

impl<T> EndpointOutput<T> {
    #[must_use]
    pub const fn value(&self) -> &JsValue {
        &self.value
    }

    #[must_use]
    pub const fn headers(&self) -> &Headers {
        &self.headers
    }

    #[must_use]
    pub const fn status(&self) -> Option<u16> {
        self.status
    }
}

impl<T: DeserializeOwned + 'static> EndpointOutput<T> {
    /// # Errors
    /// Returns an error if an application hook replaced the expected output type.
    pub fn decode(&self) -> AuthResult<T> {
        Ok(crate::utils::json::from_value(self.value.clone())?)
    }
}

/// Actual application/API failure, with headers accumulated before an API error.
#[derive(Debug)]
pub struct EndpointError {
    pub error: AuthError,
    pub headers: Option<Headers>,
    pub body: Option<Box<JsValue>>,
}

impl From<AuthError> for EndpointError {
    fn from(error: AuthError) -> Self {
        Self {
            error,
            headers: None,
            body: None,
        }
    }
}

impl std::fmt::Display for EndpointError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.error.fmt(formatter)
    }
}

impl std::error::Error for EndpointError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.error)
    }
}

/// Intentional endpoint/API errors continue through after hooks; ordinary failures propagate.
#[must_use]
pub fn is_endpoint_api_error(error: &AuthError) -> bool {
    matches!(error, AuthError::Api { .. } | AuthError::Upstream { .. }) || error.status_code() < 500
}

fn fresh_request(request: AuthRequest) -> AuthRequest {
    let pairs = request
        .query
        .keys()
        .flat_map(|name| {
            request
                .query_values(name)
                .into_iter()
                .flatten()
                .map(|value| (name.clone(), value.clone()))
        })
        .collect::<Vec<_>>();
    let url = request.url().cloned();
    let mut fresh = AuthRequest::from_parts(
        request.method,
        request.path,
        request.headers,
        request.body,
        request.query,
    );
    if let Some(url) = url {
        fresh = fresh.with_url(url);
    }
    fresh.set_query_pairs(pairs);
    fresh
}

tokio::task_local! { static ENDPOINT_CALL_CONTEXT: Option<EndpointCall>; }

#[must_use]
pub fn current_endpoint_call_context() -> Option<EndpointCall> {
    ENDPOINT_CALL_CONTEXT.try_with(Clone::clone).ok().flatten()
}

pub async fn with_endpoint_call_context<T>(
    call: EndpointCall,
    future: impl Future<Output = T>,
) -> T {
    let request = call
        .request()
        .map(crate::hooks::RequestHookContext::from_request);
    crate::hooks::with_optional_request_hook_context(
        request,
        ENDPOINT_CALL_CONTEXT.scope(Some(call), future),
    )
    .await
}

/// Isolate an independent HTTP dispatch from an enclosing logical endpoint call.
pub async fn without_endpoint_call_context<T>(future: impl Future<Output = T>) -> T {
    ENDPOINT_CALL_CONTEXT.scope(None, future).await
}