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 ErasedUserInputHook<D> = Arc<
182    dyn Fn(
183            HookCtx<D>,
184            serde_json::Map<String, serde_json::Value>,
185            crate::internal::UserInput,
186        )
187            -> BoxFuture<'static, Result<serde_json::Map<String, serde_json::Value>, AuthError>>
188        + Send
189        + Sync,
190>;
191pub(crate) type ErasedClaimHook<D> = Arc<
192    dyn for<'a> Fn(crate::internal::Claim<'a, D>) -> BoxFuture<'a, Result<(), AuthError>>
193        + Send
194        + Sync,
195>;
196pub(crate) type ErasedEventHandler<D> = Arc<
197    dyn Fn(Arc<dyn Any + Send + Sync>, Ctx<D>) -> BoxFuture<'static, Result<(), AuthError>>
198        + Send
199        + Sync,
200>;
201
202pub(crate) struct EndpointHooks<D> {
203    pub before: Vec<ErasedBefore<D>>,
204    pub after: Vec<ErasedAfter<D>>,
205}
206
207impl<D> Default for EndpointHooks<D> {
208    fn default() -> Self {
209        Self {
210            before: Vec::new(),
211            after: Vec::new(),
212        }
213    }
214}
215
216/// What a before hook decides.
217pub enum Before<I> {
218    /// Run the endpoint with this (possibly changed) input.
219    Continue(I),
220    /// Skip the endpoint and answer with this response.
221    Respond(Response),
222}
223
224/// What an after hook decides.
225pub enum After<O> {
226    Continue(O),
227    Respond(Response),
228}
229
230/// What a sign-in gate decides, after credentials check out and before a session exists.
231#[derive(Debug)]
232pub enum Gate {
233    Allow,
234    Deny(AuthError),
235    /// Answer the sign-in with this JSON (e.g. `{"twoFactorRedirect": true}`), no session.
236    /// Gates registered after this one don't run yet: the plugin that challenged finishes the
237    /// sign-in with [`Internal::complete_sign_in`], which runs every gate but its own.
238    Challenge(serde_json::Value),
239}
240
241/// The sign-in a gate is judging.
242#[derive(Clone, Debug)]
243pub struct SignInAttempt {
244    pub user: UserView,
245    /// `"email"`, `"social"`, `"magic-link"`, ... A sign-in finished after a challenge keeps
246    /// the method it started with.
247    pub method: Cow<'static, str>,
248    pub remember_me: bool,
249}
250
251/// What a session gate is checking a session for.
252#[derive(Clone, Copy, Debug, PartialEq, Eq)]
253pub enum SessionUse {
254    /// The request's session, from a cookie, the cookie cache or a resolver (bearer token,
255    /// API key). Runs on every request that looks a session up.
256    Request,
257    /// [`Ctx::sensitive_session`]: the session is about to create or change a credential.
258    Sensitive,
259}
260
261/// The context hooks, gates and event handlers get.
262pub type HookCtx<D> = Ctx<D, MaybeAuthenticated>;
263
264/// What a session resolver found for a request without a session cookie.
265#[derive(Clone, Debug)]
266pub enum Resolved {
267    /// A session token from somewhere other than the cookie (e.g. a bearer header).
268    Token(String),
269    /// A user, with a session that exists only for this request (e.g. an API key).
270    User(Id),
271}
272
273/// Turns non-cookie credentials into a session. Tried in registration order.
274pub trait SessionResolver<D: Adapter>: Send + Sync + 'static {
275    fn resolve(
276        &self,
277        ctx: &Ctx<D>,
278        headers: &HeaderMap,
279    ) -> impl Future<Output = Result<Option<Resolved>, AuthError>> + Send;
280}
281
282pub(crate) trait ErasedResolver<D>: Send + Sync {
283    fn resolve<'a>(
284        &'a self,
285        ctx: &'a Ctx<D>,
286        headers: &'a HeaderMap,
287    ) -> BoxFuture<'a, Result<Option<Resolved>, AuthError>>;
288}
289
290impl<D: Adapter, R: SessionResolver<D>> ErasedResolver<D> for R {
291    fn resolve<'a>(
292        &'a self,
293        ctx: &'a Ctx<D>,
294        headers: &'a HeaderMap,
295    ) -> BoxFuture<'a, Result<Option<Resolved>, AuthError>> {
296        Box::pin(SessionResolver::resolve(self, ctx, headers))
297    }
298}
299
300pub(crate) type MethodTable<D> = Vec<(Method, Arc<dyn ErasedEndpoint<D>>)>;
301
302/// Everything shared by all requests. Built once by `.build()`.
303pub(crate) struct Shared<D> {
304    pub db: D,
305    pub schema: Schema,
306    pub keys: Keys,
307    pub config: CoreConfig,
308    pub passwords: Passwords,
309    pub mailer: Option<Arc<dyn DynMailer>>,
310    pub plugins: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
311    pub hooks: HashMap<TypeId, EndpointHooks<D>>,
312    pub gates: Vec<OwnedGate<D>>,
313    pub resolvers: Vec<Arc<dyn ErasedResolver<D>>>,
314    pub response_hooks: Vec<ErasedResponseHook<D>>,
315    pub session_hooks: Vec<ErasedSessionHook<D>>,
316    pub session_gates: Vec<ErasedSessionGate<D>>,
317    pub fixed_expiry: Vec<FixedExpiry>,
318    pub claim_hooks: Vec<ErasedClaimHook<D>>,
319    pub user_input_hooks: Vec<ErasedUserInputHook<D>>,
320    pub events: HashMap<TypeId, Vec<ErasedEventHandler<D>>>,
321    pub router: matchit::Router<MethodTable<D>>,
322    pub rate_limiter: RateLimiter,
323    pub cache_fingerprint: u64,
324}
325
326/// The per-request context. Cheap to clone; hooks and event handlers get their own copy.
327pub struct Ctx<D, A = Public> {
328    pub(crate) shared: Arc<Shared<D>>,
329    /// The adapter a server API call runs on instead of `shared.db` (`Api::within`).
330    pub(crate) within: Option<Arc<D>>,
331    pub(crate) request: Arc<RequestInfo>,
332    pub(crate) session: Option<Arc<SessionView>>,
333    pub(crate) effects: Arc<Mutex<Effects>>,
334    _access: PhantomData<fn() -> A>,
335}
336
337impl<D, A> Clone for Ctx<D, A> {
338    fn clone(&self) -> Self {
339        Self {
340            shared: self.shared.clone(),
341            within: self.within.clone(),
342            request: self.request.clone(),
343            session: self.session.clone(),
344            effects: self.effects.clone(),
345            _access: PhantomData,
346        }
347    }
348}
349
350impl<D, A> std::fmt::Debug for Ctx<D, A> {
351    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352        write!(f, "Ctx({} {})", self.request.method, self.request.path)
353    }
354}
355
356impl<D: Adapter, A> Ctx<D, A> {
357    pub(crate) fn new(
358        shared: Arc<Shared<D>>,
359        within: Option<Arc<D>>,
360        request: Arc<RequestInfo>,
361        session: Option<Arc<SessionView>>,
362        effects: Arc<Mutex<Effects>>,
363    ) -> Self {
364        Self {
365            shared,
366            within,
367            request,
368            session,
369            effects,
370            _access: PhantomData,
371        }
372    }
373
374    pub(crate) fn retype<B>(&self) -> Ctx<D, B> {
375        Ctx::new(
376            self.shared.clone(),
377            self.within.clone(),
378            self.request.clone(),
379            self.session.clone(),
380            self.effects.clone(),
381        )
382    }
383
384    /// Typed queries on the adapter this call runs on.
385    pub fn db(&self) -> Db<'_, D> {
386        Db::new(self.adapter(), &self.shared.schema)
387    }
388
389    /// Typed queries inside a transaction: `let tx = ctx.adapter().begin().await?; ctx.db_on(&tx)`.
390    pub fn db_on<'t, Q: Queries>(&'t self, queries: &'t Q) -> Db<'t, Q> {
391        Db::new(queries, &self.shared.schema)
392    }
393
394    /// The adapter this call runs on: the configured one, or the one a server API call
395    /// passed to `Api::within` (for sqlx, one bound to the app's transaction).
396    pub fn adapter(&self) -> &D {
397        self.within.as_deref().unwrap_or(&self.shared.db)
398    }
399
400    pub fn schema(&self) -> &Schema {
401        &self.shared.schema
402    }
403
404    pub fn keys(&self) -> &Keys {
405        &self.shared.keys
406    }
407
408    pub fn config(&self) -> &CoreConfig {
409        &self.shared.config
410    }
411
412    pub fn passwords(&self) -> &Passwords {
413        &self.shared.passwords
414    }
415
416    pub fn now(&self) -> OffsetDateTime {
417        OffsetDateTime::now_utc()
418    }
419
420    /// A new id from the configured [`IdStrategy`](crate::config::IdStrategy). Fails only
421    /// when a custom generator returns an invalid id: a 500 whose detail is logged.
422    pub fn new_id(&self) -> Result<Id, AuthError> {
423        self.shared.config.ids.generate()
424    }
425
426    pub fn request(&self) -> &RequestInfo {
427        &self.request
428    }
429
430    pub fn headers(&self) -> &HeaderMap {
431        &self.request.headers
432    }
433
434    pub fn ip(&self) -> Option<&str> {
435        self.request.ip.as_deref()
436    }
437
438    pub fn user_agent(&self) -> Option<&str> {
439        self.request.user_agent.as_deref()
440    }
441
442    /// A path parameter, e.g. `{token}` in `/reset-password/{token}`.
443    pub fn param(&self, name: &str) -> Option<&str> {
444        self.request
445            .params
446            .iter()
447            .find(|(k, _)| k == name)
448            .map(|(_, v)| v.as_str())
449    }
450
451    /// A plugin's config. Panics if it isn't registered, which `Plugin::Requires` rules out
452    /// for dependencies. Use `try_plugin` for optional ones.
453    pub fn plugin<P: Plugin>(&self) -> &P {
454        self.try_plugin::<P>().unwrap_or_else(|| {
455            panic!(
456                "plugin `{}` is not registered; list it in `Requires`",
457                P::ID
458            )
459        })
460    }
461
462    pub fn try_plugin<P: Plugin>(&self) -> Option<&P> {
463        self.shared
464            .plugins
465            .get(&TypeId::of::<P>())
466            .and_then(|p| p.downcast_ref::<P>())
467    }
468
469    /// Queues an event; handlers run after the endpoint succeeds.
470    pub fn emit<E: Event>(&self, event: E) {
471        self.effects.lock().unwrap().events.push(PendingEvent {
472            type_id: TypeId::of::<E>(),
473            event: Arc::new(event),
474        });
475    }
476
477    pub fn set_cookie(&self, cookie: SetCookie) {
478        let mut effects = self.effects.lock().unwrap();
479        effects.cookies.retain(|c| c.name != cookie.name);
480        effects.cookies.push(cookie);
481    }
482
483    pub fn cookie(&self, name: &str) -> Option<&str> {
484        cookies::read(&self.request.headers, name)
485    }
486
487    /// Sets `{prefix}.{name}`, signed with the cookie key.
488    pub fn set_signed_cookie(&self, name: &str, value: &str, max_age: Option<Duration>) {
489        let name = self.shared.config.cookie_name(name);
490        let value = self.shared.keys.sign(SignPurpose::Cookie, value);
491        self.set_cookie(SetCookie::new(name, value, max_age));
492    }
493
494    /// Reads `{prefix}.{name}` and checks that the current secret signed it.
495    pub fn signed_cookie(&self, name: &str) -> Option<String> {
496        let raw = self.cookie(&self.shared.config.cookie_name(name))?;
497        self.shared
498            .keys
499            .verify(SignPurpose::Cookie, raw)
500            .map(str::to_owned)
501    }
502
503    /// Reads `{prefix}.{name}` holding a session token or a marker that only restricts a
504    /// session, signed by any configured secret (see [`Keys::verify_token`]), so the cookie
505    /// survives a secret rotation.
506    pub fn signed_token_cookie(&self, name: &str) -> Option<String> {
507        let raw = self.cookie(&self.shared.config.cookie_name(name))?;
508        self.shared.keys.verify_token(raw).map(str::to_owned)
509    }
510
511    pub fn delete_cookie(&self, name: &str) {
512        self.set_cookie(SetCookie::delete(self.shared.config.cookie_name(name)));
513    }
514
515    /// Answer with a 302 to `url` instead of JSON. `url` must pass
516    /// [`CoreConfig::is_safe_redirect`]; `Location` is the URL it resolves to, and an unsafe
517    /// `url` answers 403 `INVALID_CALLBACK_URL` instead.
518    pub fn redirect(&self, url: impl Into<String>) {
519        self.effects.lock().unwrap().redirect = Some(url.into());
520    }
521
522    pub fn set_header(&self, name: HeaderName, value: HeaderValue) {
523        self.effects.lock().unwrap().headers.push((name, value));
524    }
525
526    /// Core operations plugins build on: users, sessions, sign-in, verification values, email.
527    pub fn internal(&self) -> Internal<'_, D, A> {
528        Internal::new(self)
529    }
530
531    pub(crate) fn mailer(&self) -> Option<&Arc<dyn DynMailer>> {
532        self.shared.mailer.as_ref()
533    }
534
535    /// The request's session read again from the database, for endpoints that create or
536    /// change a credential (API keys, passkeys, linked accounts, two-factor). Skips the
537    /// cookie cache, so a revoked session is refused at once, and runs the session gates
538    /// with [`SessionUse::Sensitive`], where plugins refuse sessions that shouldn't mint
539    /// credentials (admin: impersonation sessions). 401 without a stored session, including
540    /// ephemeral ones such as an API key's.
541    pub async fn sensitive_session(&self) -> Result<SessionView, AuthError> {
542        crate::session::sensitive(
543            &self.shared,
544            self.within.as_ref(),
545            &self.request,
546            &self.effects,
547            self.session.as_deref(),
548        )
549        .await
550    }
551
552    /// The request's session as the database holds it now, for authorization decisions:
553    /// admin and organization roles and permissions, and endpoints that revoke sessions. A
554    /// session the cookie cache answered is read again and the session gates run on the
555    /// stored row, so a revoked session is refused and a changed role or a ban counts at once.
556    /// Unlike [`sensitive_session`](Self::sensitive_session) it runs the gates with
557    /// [`SessionUse::Request`], so impersonation and resolver sessions (API keys) pass as
558    /// they do on any request. 401 without a session.
559    pub async fn authoritative_session(&self) -> Result<SessionView, AuthError> {
560        crate::session::authoritative(
561            &self.shared,
562            self.within.as_ref(),
563            &self.request,
564            &self.effects,
565            self.session.as_deref(),
566        )
567        .await
568    }
569
570    /// Whether the browser's session cookie is meant to last only for the browser session:
571    /// the session this response sets came from a `rememberMe: false` sign-in or, when the
572    /// response sets none, the request carries the cookie of one.
573    pub fn dont_remember(&self) -> bool {
574        let config = &self.shared.config;
575        let flag = config.cookie_name(crate::session::DONT_REMEMBER);
576        let token = config.cookie_name(crate::session::SESSION_TOKEN);
577        let effects = self.effects.lock().unwrap();
578        let sets = |name: &str| {
579            effects
580                .cookies
581                .iter()
582                .any(|c| c.name == name && c.max_age != Some(Duration::ZERO))
583        };
584        if sets(&flag) {
585            return true;
586        }
587        if sets(&token) {
588            return false;
589        }
590        drop(effects);
591        self.signed_token_cookie(crate::session::DONT_REMEMBER)
592            .is_some()
593    }
594}
595
596impl<D: Adapter> Ctx<D, MaybeAuthenticated> {
597    pub fn session(&self) -> Option<&SessionView> {
598        self.session.as_deref()
599    }
600}
601
602impl<D: Adapter> Ctx<D, Authenticated> {
603    pub fn session(&self) -> &SessionView {
604        self.session
605            .as_deref()
606            .expect("Authenticated endpoints only run with a session")
607    }
608}
609
610impl<D: Adapter> Ctx<D, Fresh> {
611    pub fn session(&self) -> &SessionView {
612        self.session
613            .as_deref()
614            .expect("Fresh endpoints only run with a session")
615    }
616}
617
618pub(crate) enum Outcome<O> {
619    Output(O),
620    Response(Response),
621}
622
623pub(crate) struct Executed<O> {
624    pub result: Result<Outcome<O>, AuthError>,
625    pub effects: Effects,
626}
627
628/// Runs one endpoint: session by access level, before hooks, the call, after hooks.
629/// Events are left in the effects for the caller to dispatch or defer.
630pub(crate) async fn execute<D: Adapter, E: Endpoint<D>>(
631    shared: &Arc<Shared<D>>,
632    within: Option<Arc<D>>,
633    endpoint: &E,
634    request: Arc<RequestInfo>,
635    input: E::Input,
636) -> Executed<E::Output> {
637    let effects = Arc::new(Mutex::new(Effects::default()));
638    let result = run::<D, E>(shared, within, endpoint, request, input, &effects).await;
639    let effects = std::mem::take(&mut *effects.lock().unwrap());
640    Executed { result, effects }
641}
642
643async fn run<D: Adapter, E: Endpoint<D>>(
644    shared: &Arc<Shared<D>>,
645    within: Option<Arc<D>>,
646    endpoint: &E,
647    request: Arc<RequestInfo>,
648    input: E::Input,
649    effects: &Arc<Mutex<Effects>>,
650) -> Result<Outcome<E::Output>, AuthError> {
651    let level = <E::Access as Access>::LEVEL;
652    let session = match level {
653        AccessLevel::Public => None,
654        _ => crate::session::resolve(shared, within.as_ref(), &request, effects)
655            .await?
656            .map(Arc::new),
657    };
658    match (level, &session) {
659        (AccessLevel::Required | AccessLevel::Fresh, None) => return Err(AuthError::unauthorized()),
660        (AccessLevel::Fresh, Some(s)) if s.ephemeral || !shared.config.is_fresh(&s.session) => {
661            return Err(AuthError::not_fresh());
662        }
663        _ => {}
664    }
665
666    let ctx: Ctx<D, E::Access> =
667        Ctx::new(shared.clone(), within, request, session, effects.clone());
668    let hooks = shared.hooks.get(&TypeId::of::<E>());
669    let mut input = input;
670    for before in hooks.map(|h| h.before.as_slice()).unwrap_or_default() {
671        match before(ctx.retype(), Box::new(input)).await? {
672            Before::Continue(next) => {
673                input = *next
674                    .downcast::<E::Input>()
675                    .expect("hook keeps the input type")
676            }
677            Before::Respond(response) => return Ok(Outcome::Response(response)),
678        }
679    }
680    let mut output = endpoint.call(ctx.clone(), input).await?;
681    for after in hooks.map(|h| h.after.as_slice()).unwrap_or_default() {
682        match after(ctx.retype(), Box::new(output)).await? {
683            After::Continue(next) => {
684                output = *next
685                    .downcast::<E::Output>()
686                    .expect("hook keeps the output type")
687            }
688            After::Respond(response) => return Ok(Outcome::Response(response)),
689        }
690    }
691    Ok(Outcome::Output(output))
692}
693
694pub(crate) async fn dispatch_events<D: Adapter>(
695    shared: &Arc<Shared<D>>,
696    events: Vec<PendingEvent>,
697) {
698    for pending in events {
699        let Some(handlers) = shared.events.get(&pending.type_id) else {
700            continue;
701        };
702        for handler in handlers {
703            let request = Arc::new(RequestInfo::synthetic(
704                Method::POST,
705                "/event",
706                HeaderMap::new(),
707            ));
708            let ctx = Ctx::new(shared.clone(), None, request, None, Arc::default());
709            if let Err(err) = handler(pending.event.clone(), ctx).await {
710                tracing::error!(error = %err, "fastauth event handler failed");
711            }
712        }
713    }
714}
715
716pub(crate) trait ErasedEndpoint<D>: Send + Sync {
717    fn handle<'a>(
718        &'a self,
719        shared: &'a Arc<Shared<D>>,
720        request: Arc<RequestInfo>,
721        body: Bytes,
722    ) -> BoxFuture<'a, Response>;
723}
724
725pub(crate) struct Erased<E>(pub E);
726
727impl<D: Adapter, E: Endpoint<D>> ErasedEndpoint<D> for Erased<E> {
728    fn handle<'a>(
729        &'a self,
730        shared: &'a Arc<Shared<D>>,
731        request: Arc<RequestInfo>,
732        body: Bytes,
733    ) -> BoxFuture<'a, Response> {
734        Box::pin(async move {
735            let input = match decode_input::<E::Input>(&request, &body) {
736                Ok(input) => input,
737                Err(err) => return err.into_response(),
738            };
739            let mut executed = execute(shared, None, &self.0, request.clone(), input).await;
740            if executed.result.is_ok() {
741                let events = std::mem::take(&mut executed.effects.events);
742                dispatch_events(shared, events).await;
743            }
744            let result = executed.result.and_then(|outcome| match outcome {
745                Outcome::Output(output) => serde_json::to_vec(&output)
746                    .map(|b| Outcome::Output(Bytes::from(b)))
747                    .map_err(AuthError::internal),
748                Outcome::Response(response) => Ok(Outcome::Response(response)),
749            });
750            let mut response = into_response(&shared.config, result, executed.effects);
751            if !shared.response_hooks.is_empty() {
752                let ctx: Ctx<D> = Ctx::new(shared.clone(), None, request, None, Arc::default());
753                for hook in &shared.response_hooks {
754                    hook(&ctx, &mut response);
755                }
756            }
757            response
758        })
759    }
760}
761
762/// Decodes an endpoint's input from the query (GET, HEAD) or the JSON body. Text holding a
763/// NUL character is refused with 400 `INVALID_REQUEST_BODY` before any field is read:
764/// Postgres can't store it, and SQLite cuts text at it.
765fn decode_input<I: DeserializeOwned>(request: &RequestInfo, body: &[u8]) -> Result<I, AuthError> {
766    let invalid = |e: &dyn std::fmt::Display| {
767        AuthError::bad_request(crate::error::codes::INVALID_BODY, e.to_string())
768    };
769    let query = request.query.as_deref().unwrap_or("");
770    if query.contains('\0') || query.contains("%00") || json_has_nul(body) {
771        return Err(invalid(&"request text can't contain a NUL character"));
772    }
773    if request.method == Method::GET || request.method == Method::HEAD {
774        return serde_urlencoded::from_str(request.query.as_deref().unwrap_or(""))
775            .map_err(|e| invalid(&e));
776    }
777    if body.iter().all(u8::is_ascii_whitespace) {
778        return serde_json::from_slice(b"{}")
779            .or_else(|_| serde_json::from_slice(b"null"))
780            .map_err(|e| invalid(&e));
781    }
782    serde_json::from_slice(body).map_err(|e| invalid(&e))
783}
784
785/// Whether a JSON text holds the escape `\u0000`, the only way valid JSON carries a NUL
786/// (a raw one inside a string is a parse error). Every escape is skipped whole, so the text
787/// `\\u0000` (an escaped backslash) doesn't count.
788fn json_has_nul(json: &[u8]) -> bool {
789    let mut i = 0;
790    while i < json.len() {
791        if json[i] == b'\\' {
792            if json[i + 1..].starts_with(b"u0000") {
793                return true;
794            }
795            i += 2;
796        } else {
797            i += 1;
798        }
799    }
800    false
801}
802
803pub(crate) fn into_response(
804    config: &CoreConfig,
805    result: Result<Outcome<Bytes>, AuthError>,
806    effects: Effects,
807) -> Response {
808    let mut response = match result {
809        Ok(Outcome::Response(response)) => response,
810        Ok(Outcome::Output(_)) if effects.redirect.is_some() => {
811            let target = effects.redirect.as_deref().unwrap_or("/");
812            match config.resolve_redirect(target) {
813                Some(location) => {
814                    let mut response = Response::new(Bytes::new());
815                    *response.status_mut() = StatusCode::FOUND;
816                    if let Ok(location) = HeaderValue::from_str(location.as_str()) {
817                        response.headers_mut().insert(LOCATION, location);
818                    }
819                    response
820                }
821                None => AuthError::new(
822                    StatusCode::FORBIDDEN,
823                    codes::INVALID_CALLBACK_URL,
824                    "callback URL is not on a trusted origin",
825                )
826                .into_response(),
827            }
828        }
829        Ok(Outcome::Output(body)) => {
830            let mut response = Response::new(body);
831            response
832                .headers_mut()
833                .insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
834            response
835        }
836        Err(err) => err.into_response(),
837    };
838    for cookie in &effects.cookies {
839        if let Ok(value) = HeaderValue::from_str(&cookie.to_header(config)) {
840            response.headers_mut().append(SET_COOKIE, value);
841        }
842    }
843    for (name, value) in effects.headers {
844        response.headers_mut().append(name, value);
845    }
846    response
847}