Skip to main content

fastauth_core/
endpoint.rs

1//! Endpoints, the request context, hooks, and the execution pipeline shared by HTTP
2//! requests and server-side API calls.
3
4use std::any::{Any, TypeId};
5use std::borrow::Cow;
6use std::collections::HashMap;
7use std::future::Future;
8use std::marker::PhantomData;
9use std::pin::Pin;
10use std::sync::{Arc, Mutex};
11
12use bytes::Bytes;
13use http::header::{CONTENT_TYPE, LOCATION, SET_COOKIE};
14use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
15use serde::Serialize;
16use serde::de::DeserializeOwned;
17use time::{Duration, OffsetDateTime};
18
19use crate::adapter::{Adapter, Queries};
20use crate::config::CoreConfig;
21use crate::cookies::{self, SetCookie};
22use crate::crypto::{Keys, Passwords, SignPurpose};
23use crate::error::{AuthError, codes};
24use crate::events::Event;
25use crate::internal::Internal;
26use crate::mail::DynMailer;
27use crate::plugin::Plugin;
28use crate::query::Db;
29use crate::rate_limit::RateLimiter;
30use crate::schema::Schema;
31use crate::session::{SessionView, UserView};
32use crate::value::Id;
33
34pub type Response = http::Response<Bytes>;
35pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum AccessLevel {
39    Public,
40    Optional,
41    Required,
42    Fresh,
43}
44
45/// How much session an endpoint needs. It decides what `Ctx::session` returns.
46pub trait Access: Send + Sync + 'static {
47    const LEVEL: AccessLevel;
48}
49
50/// No session lookup; `ctx.session()` doesn't exist.
51#[derive(Debug)]
52pub struct Public;
53/// `ctx.session()` returns `Option<&SessionView>`.
54#[derive(Debug)]
55pub struct MaybeAuthenticated;
56/// 401 without a session; `ctx.session()` returns `&SessionView`.
57#[derive(Debug)]
58pub struct Authenticated;
59/// Like `Authenticated`, plus 403 `SESSION_NOT_FRESH` when the session is older than `fresh_age`
60/// or ephemeral (an API key's), which is never a recent sign-in.
61#[derive(Debug)]
62pub struct Fresh;
63
64impl Access for Public {
65    const LEVEL: AccessLevel = AccessLevel::Public;
66}
67impl Access for MaybeAuthenticated {
68    const LEVEL: AccessLevel = AccessLevel::Optional;
69}
70impl Access for Authenticated {
71    const LEVEL: AccessLevel = AccessLevel::Required;
72}
73impl Access for Fresh {
74    const LEVEL: AccessLevel = AccessLevel::Fresh;
75}
76
77/// An auth endpoint: a typed function first, an HTTP route second.
78///
79/// `GET` endpoints read `Input` from the query string, everything else from the JSON body.
80/// `PATH` is relative to the base path and uses `{name}` for parameters.
81pub trait Endpoint<D: Adapter>: Send + Sync + 'static {
82    const METHOD: Method;
83    const PATH: &'static str;
84    type Access: Access;
85    type Input: DeserializeOwned + Send + 'static;
86    type Output: Serialize + Send + 'static;
87
88    fn call(
89        &self,
90        ctx: Ctx<D, Self::Access>,
91        input: Self::Input,
92    ) -> impl Future<Output = Result<Self::Output, AuthError>> + Send;
93}
94
95/// An empty input or output: `{}`.
96#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize, Serialize)]
97pub struct Empty {}
98
99/// What the request looked like. For server API calls, headers are whatever the caller passed.
100#[derive(Clone, Debug)]
101pub struct RequestInfo {
102    pub method: Method,
103    pub path: String,
104    pub params: Vec<(String, String)>,
105    pub query: Option<String>,
106    pub headers: HeaderMap,
107    pub ip: Option<String>,
108    pub user_agent: Option<String>,
109}
110
111impl RequestInfo {
112    pub(crate) fn synthetic(method: Method, path: &str, headers: HeaderMap) -> Self {
113        let user_agent = header_str(&headers, http::header::USER_AGENT);
114        Self {
115            method,
116            path: path.to_owned(),
117            params: Vec::new(),
118            query: None,
119            headers,
120            ip: None,
121            user_agent,
122        }
123    }
124}
125
126pub(crate) fn header_str(headers: &HeaderMap, name: HeaderName) -> Option<String> {
127    headers
128        .get(name)
129        .and_then(|v| v.to_str().ok())
130        .map(str::to_owned)
131}
132
133pub(crate) struct PendingEvent {
134    type_id: TypeId,
135    event: Arc<dyn Any + Send + Sync>,
136}
137
138/// Side effects an endpoint asks for: cookies, a redirect, headers, events.
139#[derive(Default)]
140pub(crate) struct Effects {
141    pub cookies: Vec<SetCookie>,
142    pub redirect: Option<String>,
143    pub headers: Vec<(HeaderName, HeaderValue)>,
144    pub events: Vec<PendingEvent>,
145}
146
147pub(crate) type ErasedBefore<D> = Arc<
148    dyn Fn(
149            HookCtx<D>,
150            Box<dyn Any + Send>,
151        ) -> BoxFuture<'static, Result<Before<Box<dyn Any + Send>>, AuthError>>
152        + Send
153        + Sync,
154>;
155pub(crate) type ErasedAfter<D> = Arc<
156    dyn Fn(
157            HookCtx<D>,
158            Box<dyn Any + Send>,
159        ) -> BoxFuture<'static, Result<After<Box<dyn Any + Send>>, AuthError>>
160        + Send
161        + Sync,
162>;
163pub(crate) type ErasedGate<D> = Arc<
164    dyn Fn(HookCtx<D>, SignInAttempt) -> BoxFuture<'static, Result<Gate, AuthError>> + Send + Sync,
165>;
166
167/// A sign-in gate and the id of the plugin that registered it (`"app"` for the app's own).
168pub(crate) struct OwnedGate<D> {
169    pub owner: &'static str,
170    pub gate: ErasedGate<D>,
171}
172pub(crate) type ErasedResponseHook<D> = Arc<dyn Fn(&Ctx<D>, &mut Response) + Send + Sync>;
173pub(crate) type ErasedSessionHook<D> =
174    Arc<dyn Fn(HookCtx<D>, SessionView) -> BoxFuture<'static, Result<(), AuthError>> + Send + Sync>;
175pub(crate) type ErasedSessionGate<D> = Arc<
176    dyn Fn(HookCtx<D>, SessionView, SessionUse) -> BoxFuture<'static, Result<(), AuthError>>
177        + Send
178        + Sync,
179>;
180pub(crate) type FixedExpiry = Arc<dyn Fn(&SessionView) -> bool + Send + Sync>;
181pub(crate) type ErasedEventHandler<D> = Arc<
182    dyn Fn(Arc<dyn Any + Send + Sync>, Ctx<D>) -> BoxFuture<'static, Result<(), AuthError>>
183        + Send
184        + Sync,
185>;
186
187pub(crate) struct EndpointHooks<D> {
188    pub before: Vec<ErasedBefore<D>>,
189    pub after: Vec<ErasedAfter<D>>,
190}
191
192impl<D> Default for EndpointHooks<D> {
193    fn default() -> Self {
194        Self {
195            before: Vec::new(),
196            after: Vec::new(),
197        }
198    }
199}
200
201/// What a before hook decides.
202pub enum Before<I> {
203    /// Run the endpoint with this (possibly changed) input.
204    Continue(I),
205    /// Skip the endpoint and answer with this response.
206    Respond(Response),
207}
208
209/// What an after hook decides.
210pub enum After<O> {
211    Continue(O),
212    Respond(Response),
213}
214
215/// What a sign-in gate decides, after credentials check out and before a session exists.
216#[derive(Debug)]
217pub enum Gate {
218    Allow,
219    Deny(AuthError),
220    /// Answer the sign-in with this JSON (e.g. `{"twoFactorRedirect": true}`), no session.
221    /// Gates registered after this one don't run yet: the plugin that challenged finishes the
222    /// sign-in with [`Internal::complete_sign_in`], which runs every gate but its own.
223    Challenge(serde_json::Value),
224}
225
226/// The sign-in a gate is judging.
227#[derive(Clone, Debug)]
228pub struct SignInAttempt {
229    pub user: UserView,
230    /// `"email"`, `"social"`, `"magic-link"`, ... A sign-in finished after a challenge keeps
231    /// the method it started with.
232    pub method: Cow<'static, str>,
233    pub remember_me: bool,
234}
235
236/// What a session gate is checking a session for.
237#[derive(Clone, Copy, Debug, PartialEq, Eq)]
238pub enum SessionUse {
239    /// The request's session, from a cookie, the cookie cache or a resolver (bearer token,
240    /// API key). Runs on every request that looks a session up.
241    Request,
242    /// [`Ctx::sensitive_session`]: the session is about to create or change a credential.
243    Sensitive,
244}
245
246/// The context hooks, gates and event handlers get.
247pub type HookCtx<D> = Ctx<D, MaybeAuthenticated>;
248
249/// What a session resolver found for a request without a session cookie.
250#[derive(Clone, Debug)]
251pub enum Resolved {
252    /// A session token from somewhere other than the cookie (e.g. a bearer header).
253    Token(String),
254    /// A user, with a session that exists only for this request (e.g. an API key).
255    User(Id),
256}
257
258/// Turns non-cookie credentials into a session. Tried in registration order.
259pub trait SessionResolver<D: Adapter>: Send + Sync + 'static {
260    fn resolve(
261        &self,
262        ctx: &Ctx<D>,
263        headers: &HeaderMap,
264    ) -> impl Future<Output = Result<Option<Resolved>, AuthError>> + Send;
265}
266
267pub(crate) trait ErasedResolver<D>: Send + Sync {
268    fn resolve<'a>(
269        &'a self,
270        ctx: &'a Ctx<D>,
271        headers: &'a HeaderMap,
272    ) -> BoxFuture<'a, Result<Option<Resolved>, AuthError>>;
273}
274
275impl<D: Adapter, R: SessionResolver<D>> ErasedResolver<D> for R {
276    fn resolve<'a>(
277        &'a self,
278        ctx: &'a Ctx<D>,
279        headers: &'a HeaderMap,
280    ) -> BoxFuture<'a, Result<Option<Resolved>, AuthError>> {
281        Box::pin(SessionResolver::resolve(self, ctx, headers))
282    }
283}
284
285pub(crate) type MethodTable<D> = Vec<(Method, Arc<dyn ErasedEndpoint<D>>)>;
286
287/// Everything shared by all requests. Built once by `.build()`.
288pub(crate) struct Shared<D> {
289    pub db: D,
290    pub schema: Schema,
291    pub keys: Keys,
292    pub config: CoreConfig,
293    pub passwords: Passwords,
294    pub mailer: Option<Arc<dyn DynMailer>>,
295    pub plugins: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
296    pub hooks: HashMap<TypeId, EndpointHooks<D>>,
297    pub gates: Vec<OwnedGate<D>>,
298    pub resolvers: Vec<Arc<dyn ErasedResolver<D>>>,
299    pub response_hooks: Vec<ErasedResponseHook<D>>,
300    pub session_hooks: Vec<ErasedSessionHook<D>>,
301    pub session_gates: Vec<ErasedSessionGate<D>>,
302    pub fixed_expiry: Vec<FixedExpiry>,
303    pub events: HashMap<TypeId, Vec<ErasedEventHandler<D>>>,
304    pub router: matchit::Router<MethodTable<D>>,
305    pub rate_limiter: RateLimiter,
306    pub cache_fingerprint: u64,
307}
308
309/// The per-request context. Cheap to clone; hooks and event handlers get their own copy.
310pub struct Ctx<D, A = Public> {
311    pub(crate) shared: Arc<Shared<D>>,
312    /// The adapter a server API call runs on instead of `shared.db` (`Api::within`).
313    pub(crate) within: Option<Arc<D>>,
314    pub(crate) request: Arc<RequestInfo>,
315    pub(crate) session: Option<Arc<SessionView>>,
316    pub(crate) effects: Arc<Mutex<Effects>>,
317    _access: PhantomData<fn() -> A>,
318}
319
320impl<D, A> Clone for Ctx<D, A> {
321    fn clone(&self) -> Self {
322        Self {
323            shared: self.shared.clone(),
324            within: self.within.clone(),
325            request: self.request.clone(),
326            session: self.session.clone(),
327            effects: self.effects.clone(),
328            _access: PhantomData,
329        }
330    }
331}
332
333impl<D, A> std::fmt::Debug for Ctx<D, A> {
334    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
335        write!(f, "Ctx({} {})", self.request.method, self.request.path)
336    }
337}
338
339impl<D: Adapter, A> Ctx<D, A> {
340    pub(crate) fn new(
341        shared: Arc<Shared<D>>,
342        within: Option<Arc<D>>,
343        request: Arc<RequestInfo>,
344        session: Option<Arc<SessionView>>,
345        effects: Arc<Mutex<Effects>>,
346    ) -> Self {
347        Self {
348            shared,
349            within,
350            request,
351            session,
352            effects,
353            _access: PhantomData,
354        }
355    }
356
357    pub(crate) fn retype<B>(&self) -> Ctx<D, B> {
358        Ctx::new(
359            self.shared.clone(),
360            self.within.clone(),
361            self.request.clone(),
362            self.session.clone(),
363            self.effects.clone(),
364        )
365    }
366
367    /// Typed queries on the adapter this call runs on.
368    pub fn db(&self) -> Db<'_, D> {
369        Db::new(self.adapter(), &self.shared.schema)
370    }
371
372    /// Typed queries inside a transaction: `let tx = ctx.adapter().begin().await?; ctx.db_on(&tx)`.
373    pub fn db_on<'t, Q: Queries>(&'t self, queries: &'t Q) -> Db<'t, Q> {
374        Db::new(queries, &self.shared.schema)
375    }
376
377    /// The adapter this call runs on: the configured one, or the one a server API call
378    /// passed to `Api::within` (for sqlx, one bound to the app's transaction).
379    pub fn adapter(&self) -> &D {
380        self.within.as_deref().unwrap_or(&self.shared.db)
381    }
382
383    pub fn schema(&self) -> &Schema {
384        &self.shared.schema
385    }
386
387    pub fn keys(&self) -> &Keys {
388        &self.shared.keys
389    }
390
391    pub fn config(&self) -> &CoreConfig {
392        &self.shared.config
393    }
394
395    pub fn passwords(&self) -> &Passwords {
396        &self.shared.passwords
397    }
398
399    pub fn now(&self) -> OffsetDateTime {
400        OffsetDateTime::now_utc()
401    }
402
403    /// A new id from the configured [`IdStrategy`](crate::config::IdStrategy). Fails only
404    /// when a custom generator returns an invalid id: a 500 whose detail is logged.
405    pub fn new_id(&self) -> Result<Id, AuthError> {
406        self.shared.config.ids.generate()
407    }
408
409    pub fn request(&self) -> &RequestInfo {
410        &self.request
411    }
412
413    pub fn headers(&self) -> &HeaderMap {
414        &self.request.headers
415    }
416
417    pub fn ip(&self) -> Option<&str> {
418        self.request.ip.as_deref()
419    }
420
421    pub fn user_agent(&self) -> Option<&str> {
422        self.request.user_agent.as_deref()
423    }
424
425    /// A path parameter, e.g. `{token}` in `/reset-password/{token}`.
426    pub fn param(&self, name: &str) -> Option<&str> {
427        self.request
428            .params
429            .iter()
430            .find(|(k, _)| k == name)
431            .map(|(_, v)| v.as_str())
432    }
433
434    /// A plugin's config. Panics if it isn't registered, which `Plugin::Requires` rules out
435    /// for dependencies. Use `try_plugin` for optional ones.
436    pub fn plugin<P: Plugin>(&self) -> &P {
437        self.try_plugin::<P>().unwrap_or_else(|| {
438            panic!(
439                "plugin `{}` is not registered; list it in `Requires`",
440                P::ID
441            )
442        })
443    }
444
445    pub fn try_plugin<P: Plugin>(&self) -> Option<&P> {
446        self.shared
447            .plugins
448            .get(&TypeId::of::<P>())
449            .and_then(|p| p.downcast_ref::<P>())
450    }
451
452    /// Queues an event; handlers run after the endpoint succeeds.
453    pub fn emit<E: Event>(&self, event: E) {
454        self.effects.lock().unwrap().events.push(PendingEvent {
455            type_id: TypeId::of::<E>(),
456            event: Arc::new(event),
457        });
458    }
459
460    pub fn set_cookie(&self, cookie: SetCookie) {
461        let mut effects = self.effects.lock().unwrap();
462        effects.cookies.retain(|c| c.name != cookie.name);
463        effects.cookies.push(cookie);
464    }
465
466    pub fn cookie(&self, name: &str) -> Option<&str> {
467        cookies::read(&self.request.headers, name)
468    }
469
470    /// Sets `{prefix}.{name}`, signed with the cookie key.
471    pub fn set_signed_cookie(&self, name: &str, value: &str, max_age: Option<Duration>) {
472        let name = self.shared.config.cookie_name(name);
473        let value = self.shared.keys.sign(SignPurpose::Cookie, value);
474        self.set_cookie(SetCookie::new(name, value, max_age));
475    }
476
477    /// Reads `{prefix}.{name}` and checks its signature.
478    pub fn signed_cookie(&self, name: &str) -> Option<String> {
479        let raw = self.cookie(&self.shared.config.cookie_name(name))?;
480        self.shared
481            .keys
482            .verify(SignPurpose::Cookie, raw)
483            .map(str::to_owned)
484    }
485
486    pub fn delete_cookie(&self, name: &str) {
487        self.set_cookie(SetCookie::delete(self.shared.config.cookie_name(name)));
488    }
489
490    /// Answer with a 302 to `url` instead of JSON. `url` must pass
491    /// [`CoreConfig::is_safe_redirect`]; `Location` is the URL it resolves to, and an unsafe
492    /// `url` answers 403 `INVALID_CALLBACK_URL` instead.
493    pub fn redirect(&self, url: impl Into<String>) {
494        self.effects.lock().unwrap().redirect = Some(url.into());
495    }
496
497    pub fn set_header(&self, name: HeaderName, value: HeaderValue) {
498        self.effects.lock().unwrap().headers.push((name, value));
499    }
500
501    /// Core operations plugins build on: users, sessions, sign-in, verification values, email.
502    pub fn internal(&self) -> Internal<'_, D, A> {
503        Internal::new(self)
504    }
505
506    pub(crate) fn mailer(&self) -> Option<&Arc<dyn DynMailer>> {
507        self.shared.mailer.as_ref()
508    }
509
510    /// The request's session read again from the database, for endpoints that create or
511    /// change a credential (API keys, passkeys, linked accounts, two-factor). Skips the
512    /// cookie cache, so a revoked session is refused at once, and runs the session gates
513    /// with [`SessionUse::Sensitive`], where plugins refuse sessions that shouldn't mint
514    /// credentials (admin: impersonation sessions). 401 without a stored session, including
515    /// ephemeral ones such as an API key's.
516    pub async fn sensitive_session(&self) -> Result<SessionView, AuthError> {
517        crate::session::sensitive(
518            &self.shared,
519            self.within.as_ref(),
520            &self.request,
521            &self.effects,
522            self.session.as_deref(),
523        )
524        .await
525    }
526}
527
528impl<D: Adapter> Ctx<D, MaybeAuthenticated> {
529    pub fn session(&self) -> Option<&SessionView> {
530        self.session.as_deref()
531    }
532}
533
534impl<D: Adapter> Ctx<D, Authenticated> {
535    pub fn session(&self) -> &SessionView {
536        self.session
537            .as_deref()
538            .expect("Authenticated endpoints only run with a session")
539    }
540}
541
542impl<D: Adapter> Ctx<D, Fresh> {
543    pub fn session(&self) -> &SessionView {
544        self.session
545            .as_deref()
546            .expect("Fresh endpoints only run with a session")
547    }
548}
549
550pub(crate) enum Outcome<O> {
551    Output(O),
552    Response(Response),
553}
554
555pub(crate) struct Executed<O> {
556    pub result: Result<Outcome<O>, AuthError>,
557    pub effects: Effects,
558}
559
560/// Runs one endpoint: session by access level, before hooks, the call, after hooks.
561/// Events are left in the effects for the caller to dispatch or defer.
562pub(crate) async fn execute<D: Adapter, E: Endpoint<D>>(
563    shared: &Arc<Shared<D>>,
564    within: Option<Arc<D>>,
565    endpoint: &E,
566    request: Arc<RequestInfo>,
567    input: E::Input,
568) -> Executed<E::Output> {
569    let effects = Arc::new(Mutex::new(Effects::default()));
570    let result = run::<D, E>(shared, within, endpoint, request, input, &effects).await;
571    let effects = std::mem::take(&mut *effects.lock().unwrap());
572    Executed { result, effects }
573}
574
575async fn run<D: Adapter, E: Endpoint<D>>(
576    shared: &Arc<Shared<D>>,
577    within: Option<Arc<D>>,
578    endpoint: &E,
579    request: Arc<RequestInfo>,
580    input: E::Input,
581    effects: &Arc<Mutex<Effects>>,
582) -> Result<Outcome<E::Output>, AuthError> {
583    let level = <E::Access as Access>::LEVEL;
584    let session = match level {
585        AccessLevel::Public => None,
586        _ => crate::session::resolve(shared, within.as_ref(), &request, effects)
587            .await?
588            .map(Arc::new),
589    };
590    match (level, &session) {
591        (AccessLevel::Required | AccessLevel::Fresh, None) => return Err(AuthError::unauthorized()),
592        (AccessLevel::Fresh, Some(s)) if s.ephemeral || !shared.config.is_fresh(&s.session) => {
593            return Err(AuthError::not_fresh());
594        }
595        _ => {}
596    }
597
598    let ctx: Ctx<D, E::Access> =
599        Ctx::new(shared.clone(), within, request, session, effects.clone());
600    let hooks = shared.hooks.get(&TypeId::of::<E>());
601    let mut input = input;
602    for before in hooks.map(|h| h.before.as_slice()).unwrap_or_default() {
603        match before(ctx.retype(), Box::new(input)).await? {
604            Before::Continue(next) => {
605                input = *next
606                    .downcast::<E::Input>()
607                    .expect("hook keeps the input type")
608            }
609            Before::Respond(response) => return Ok(Outcome::Response(response)),
610        }
611    }
612    let mut output = endpoint.call(ctx.clone(), input).await?;
613    for after in hooks.map(|h| h.after.as_slice()).unwrap_or_default() {
614        match after(ctx.retype(), Box::new(output)).await? {
615            After::Continue(next) => {
616                output = *next
617                    .downcast::<E::Output>()
618                    .expect("hook keeps the output type")
619            }
620            After::Respond(response) => return Ok(Outcome::Response(response)),
621        }
622    }
623    Ok(Outcome::Output(output))
624}
625
626pub(crate) async fn dispatch_events<D: Adapter>(
627    shared: &Arc<Shared<D>>,
628    events: Vec<PendingEvent>,
629) {
630    for pending in events {
631        let Some(handlers) = shared.events.get(&pending.type_id) else {
632            continue;
633        };
634        for handler in handlers {
635            let request = Arc::new(RequestInfo::synthetic(
636                Method::POST,
637                "/event",
638                HeaderMap::new(),
639            ));
640            let ctx = Ctx::new(shared.clone(), None, request, None, Arc::default());
641            if let Err(err) = handler(pending.event.clone(), ctx).await {
642                tracing::error!(error = %err, "fastauth event handler failed");
643            }
644        }
645    }
646}
647
648pub(crate) trait ErasedEndpoint<D>: Send + Sync {
649    fn handle<'a>(
650        &'a self,
651        shared: &'a Arc<Shared<D>>,
652        request: Arc<RequestInfo>,
653        body: Bytes,
654    ) -> BoxFuture<'a, Response>;
655}
656
657pub(crate) struct Erased<E>(pub E);
658
659impl<D: Adapter, E: Endpoint<D>> ErasedEndpoint<D> for Erased<E> {
660    fn handle<'a>(
661        &'a self,
662        shared: &'a Arc<Shared<D>>,
663        request: Arc<RequestInfo>,
664        body: Bytes,
665    ) -> BoxFuture<'a, Response> {
666        Box::pin(async move {
667            let input = match decode_input::<E::Input>(&request, &body) {
668                Ok(input) => input,
669                Err(err) => return err.into_response(),
670            };
671            let mut executed = execute(shared, None, &self.0, request.clone(), input).await;
672            if executed.result.is_ok() {
673                let events = std::mem::take(&mut executed.effects.events);
674                dispatch_events(shared, events).await;
675            }
676            let result = executed.result.and_then(|outcome| match outcome {
677                Outcome::Output(output) => serde_json::to_vec(&output)
678                    .map(|b| Outcome::Output(Bytes::from(b)))
679                    .map_err(AuthError::internal),
680                Outcome::Response(response) => Ok(Outcome::Response(response)),
681            });
682            let mut response = into_response(&shared.config, result, executed.effects);
683            if !shared.response_hooks.is_empty() {
684                let ctx: Ctx<D> = Ctx::new(shared.clone(), None, request, None, Arc::default());
685                for hook in &shared.response_hooks {
686                    hook(&ctx, &mut response);
687                }
688            }
689            response
690        })
691    }
692}
693
694fn decode_input<I: DeserializeOwned>(request: &RequestInfo, body: &[u8]) -> Result<I, AuthError> {
695    let invalid = |e: &dyn std::fmt::Display| {
696        AuthError::bad_request(crate::error::codes::INVALID_BODY, e.to_string())
697    };
698    if request.method == Method::GET || request.method == Method::HEAD {
699        return serde_urlencoded::from_str(request.query.as_deref().unwrap_or(""))
700            .map_err(|e| invalid(&e));
701    }
702    if body.iter().all(u8::is_ascii_whitespace) {
703        return serde_json::from_slice(b"{}")
704            .or_else(|_| serde_json::from_slice(b"null"))
705            .map_err(|e| invalid(&e));
706    }
707    serde_json::from_slice(body).map_err(|e| invalid(&e))
708}
709
710pub(crate) fn into_response(
711    config: &CoreConfig,
712    result: Result<Outcome<Bytes>, AuthError>,
713    effects: Effects,
714) -> Response {
715    let mut response = match result {
716        Ok(Outcome::Response(response)) => response,
717        Ok(Outcome::Output(_)) if effects.redirect.is_some() => {
718            let target = effects.redirect.as_deref().unwrap_or("/");
719            match config.resolve_redirect(target) {
720                Some(location) => {
721                    let mut response = Response::new(Bytes::new());
722                    *response.status_mut() = StatusCode::FOUND;
723                    if let Ok(location) = HeaderValue::from_str(location.as_str()) {
724                        response.headers_mut().insert(LOCATION, location);
725                    }
726                    response
727                }
728                None => AuthError::new(
729                    StatusCode::FORBIDDEN,
730                    codes::INVALID_CALLBACK_URL,
731                    "callback URL is not on a trusted origin",
732                )
733                .into_response(),
734            }
735        }
736        Ok(Outcome::Output(body)) => {
737            let mut response = Response::new(body);
738            response
739                .headers_mut()
740                .insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
741            response
742        }
743        Err(err) => err.into_response(),
744    };
745    for cookie in &effects.cookies {
746        if let Ok(value) = HeaderValue::from_str(&cookie.to_header(config)) {
747            response.headers_mut().append(SET_COOKIE, value);
748        }
749    }
750    for (name, value) in effects.headers {
751        response.headers_mut().append(name, value);
752    }
753    response
754}