Skip to main content

fastauth_core/
auth.rs

1//! The builder, the `Auth` instance, HTTP dispatch and the server API.
2
3use std::collections::BTreeMap;
4use std::future::Future;
5use std::marker::PhantomData;
6use std::net::IpAddr;
7use std::sync::{Arc, Mutex};
8
9use bytes::Bytes;
10use http::header::{COOKIE, ORIGIN, REFERER, USER_AGENT};
11use http::{HeaderMap, HeaderValue, Method, StatusCode};
12use serde::Serialize;
13use url::Url;
14
15use crate::adapter::{Adapter, Transaction};
16use crate::config::{
17    ClientIp, CookieConfig, CoreConfig, EmailPassword, EmailVerification, Secure, SessionConfig,
18};
19use crate::crypto::{Argon2id, Keys, Passwords, Secret, SignPurpose};
20use crate::endpoint::{
21    Effects, Endpoint, Executed, Outcome, RequestInfo, Response, Shared, dispatch_events, execute,
22    header_str,
23};
24use crate::error::{AuthError, BuildError, codes};
25use crate::events::{DeferredEvents, Event};
26use crate::hlist::{Append, Has, Nil, PluginSet, Satisfied};
27use crate::mail::{DynMailer, Mailer};
28use crate::migrate::Migrator;
29use crate::model::{Fields, Model};
30use crate::models::{Session, User};
31use crate::plugin::{Plugin, PluginBuilder, Registry};
32use crate::rate_limit::{RateLimit, RateLimiter};
33use crate::routes;
34use crate::schema::Schema;
35use crate::session::{self, SessionData, UserView};
36
37/// Entry point: `FastAuth::builder()`.
38#[derive(Debug)]
39pub struct FastAuth;
40
41/// Builder state: no database yet.
42#[derive(Debug)]
43pub struct NoDatabase;
44/// Builder state: a required option is missing.
45#[derive(Debug)]
46pub struct Missing;
47/// Builder state: a required option is set.
48#[derive(Debug)]
49pub struct Present;
50
51impl FastAuth {
52    pub fn builder() -> Builder<NoDatabase, (), Nil, Missing, Missing> {
53        Builder {
54            db: NoDatabase,
55            plugins: Nil,
56            secrets: Vec::new(),
57            base_url: None,
58            app_name: "fastauth".into(),
59            base_path: "/api/auth".into(),
60            trusted_origins: Vec::new(),
61            session: SessionConfig::default(),
62            cookies: CookieConfig::default(),
63            email_password: None,
64            email_verification: EmailVerification::default(),
65            rate_limit: RateLimit::default(),
66            client_ip: ClientIp::Socket,
67            mailer: None,
68            app_init: Vec::new(),
69            _state: PhantomData,
70        }
71    }
72}
73
74type AppInit<D> = Box<dyn FnOnce(&mut PluginBuilder<'_, D>) + Send>;
75
76/// Collects configuration. `.build()` only exists once `secret`, `base_url` and `database`
77/// are set: the last three type parameters track that.
78pub struct Builder<D, U, P, S, B> {
79    db: D,
80    plugins: P,
81    secrets: Vec<Secret>,
82    base_url: Option<String>,
83    app_name: String,
84    base_path: String,
85    trusted_origins: Vec<String>,
86    session: SessionConfig,
87    cookies: CookieConfig,
88    email_password: Option<EmailPassword>,
89    email_verification: EmailVerification,
90    rate_limit: RateLimit,
91    client_ip: ClientIp,
92    mailer: Option<Arc<dyn DynMailer>>,
93    app_init: Vec<AppInit<D>>,
94    _state: PhantomData<BuilderState<U, S, B>>,
95}
96
97type BuilderState<U, S, B> = fn() -> (U, S, B);
98
99impl<D, U, P, S, B> std::fmt::Debug for Builder<D, U, P, S, B> {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        f.debug_struct("Builder")
102            .field("base_url", &self.base_url)
103            .finish_non_exhaustive()
104    }
105}
106
107impl<D, U, P, S, B> Builder<D, U, P, S, B> {
108    fn retype<U2, P2, S2, B2>(self, plugins: impl FnOnce(P) -> P2) -> Builder<D, U2, P2, S2, B2> {
109        Builder {
110            db: self.db,
111            plugins: plugins(self.plugins),
112            secrets: self.secrets,
113            base_url: self.base_url,
114            app_name: self.app_name,
115            base_path: self.base_path,
116            trusted_origins: self.trusted_origins,
117            session: self.session,
118            cookies: self.cookies,
119            email_password: self.email_password,
120            email_verification: self.email_verification,
121            rate_limit: self.rate_limit,
122            client_ip: self.client_ip,
123            mailer: self.mailer,
124            app_init: self.app_init,
125            _state: PhantomData,
126        }
127    }
128
129    /// The master secret (at least 32 bytes). See `Secret::from_env`.
130    pub fn secret(mut self, secret: Secret) -> Builder<D, U, P, Present, B> {
131        self.secrets = vec![secret];
132        self.retype(|p| p)
133    }
134
135    /// Several secrets for rotation: the first signs, all verify.
136    pub fn secrets(
137        mut self,
138        secrets: impl IntoIterator<Item = Secret>,
139    ) -> Builder<D, U, P, Present, B> {
140        self.secrets = secrets.into_iter().collect();
141        self.retype(|p| p)
142    }
143
144    /// The public URL of the app, e.g. `https://acme.dk`.
145    pub fn base_url(mut self, url: impl Into<String>) -> Builder<D, U, P, S, Present> {
146        self.base_url = Some(url.into());
147        self.retype(|p| p)
148    }
149
150    pub fn app_name(mut self, name: impl Into<String>) -> Self {
151        self.app_name = name.into();
152        self
153    }
154
155    /// Where auth routes live (default `/api/auth`).
156    pub fn base_path(mut self, path: impl Into<String>) -> Self {
157        self.base_path = path.into();
158        self
159    }
160
161    /// Origins allowed to make cookie-carrying requests and to be redirect targets.
162    pub fn trusted_origins(mut self, origins: impl IntoIterator<Item = impl Into<String>>) -> Self {
163        self.trusted_origins.extend(
164            origins
165                .into_iter()
166                .map(|o| o.into().trim_end_matches('/').to_owned()),
167        );
168        self
169    }
170
171    pub fn email_password(mut self, config: EmailPassword) -> Self {
172        self.email_password = Some(config);
173        self
174    }
175
176    pub fn email_verification(mut self, config: EmailVerification) -> Self {
177        self.email_verification = config;
178        self
179    }
180
181    pub fn session(mut self, config: SessionConfig) -> Self {
182        self.session = config;
183        self
184    }
185
186    pub fn cookies(mut self, config: CookieConfig) -> Self {
187        self.cookies = config;
188        self
189    }
190
191    pub fn rate_limit(mut self, config: RateLimit) -> Self {
192        self.rate_limit = config;
193        self
194    }
195
196    pub fn client_ip(mut self, source: ClientIp) -> Self {
197        self.client_ip = source;
198        self
199    }
200
201    pub fn mailer(mut self, mailer: impl Mailer) -> Self {
202        self.mailer = Some(Arc::new(mailer));
203        self
204    }
205
206    /// The app's own columns on `user`.
207    pub fn user_fields<U2: Fields>(self) -> Builder<D, U2, P, S, B> {
208        self.retype(|p| p)
209    }
210
211    /// Registers a plugin. Its `Requires` must already be registered.
212    pub fn plugin<Pl: Plugin, I>(self, plugin: Pl) -> Builder<D, U, P::Out, S, B>
213    where
214        P: Append<Pl>,
215        Pl::Requires: Satisfied<P, I>,
216    {
217        self.retype(|plugins| plugins.append(Arc::new(plugin)))
218    }
219}
220
221impl<U, P, S, B> Builder<NoDatabase, U, P, S, B> {
222    pub fn database<D: Adapter>(self, db: D) -> Builder<D, U, P, S, B> {
223        Builder {
224            db,
225            plugins: self.plugins,
226            secrets: self.secrets,
227            base_url: self.base_url,
228            app_name: self.app_name,
229            base_path: self.base_path,
230            trusted_origins: self.trusted_origins,
231            session: self.session,
232            cookies: self.cookies,
233            email_password: self.email_password,
234            email_verification: self.email_verification,
235            rate_limit: self.rate_limit,
236            client_ip: self.client_ip,
237            mailer: self.mailer,
238            app_init: Vec::new(),
239            _state: PhantomData,
240        }
241    }
242}
243
244impl<D: Adapter, U, P, S, B> Builder<D, U, P, S, B> {
245    /// Registers app-level hooks, gates, resolvers or endpoints, like a plugin's `init`.
246    pub fn configure(
247        mut self,
248        init: impl FnOnce(&mut PluginBuilder<'_, D>) + Send + 'static,
249    ) -> Self {
250        self.app_init.push(Box::new(init));
251        self
252    }
253
254    /// Runs `handler` after every endpoint that emits `Ev`.
255    pub fn on<Ev, F, Fut>(self, handler: F) -> Self
256    where
257        Ev: Event,
258        F: Fn(Ev, crate::endpoint::Ctx<D>) -> Fut + Send + Sync + 'static,
259        Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
260    {
261        self.configure(move |app| {
262            app.on(handler);
263        })
264    }
265}
266
267impl<D: Adapter, U: Fields, P: PluginSet> Builder<D, U, P, Present, Present> {
268    pub fn build(self) -> Result<Auth<D, U, P>, BuildError> {
269        let mut problems = Vec::new();
270        if self.secrets.is_empty() || self.secrets.iter().any(|s| s.len() < Secret::MIN_LEN) {
271            problems.push(format!(
272                "every secret must be at least {} bytes; generate one with `fastauth secret`",
273                Secret::MIN_LEN
274            ));
275        }
276        let base_url = match Url::parse(self.base_url.as_deref().unwrap_or_default()) {
277            Ok(url) if matches!(url.scheme(), "http" | "https") => url,
278            _ => {
279                problems.push(format!(
280                    "base_url `{}` is not an http(s) URL",
281                    self.base_url.unwrap_or_default()
282                ));
283                Url::parse("http://localhost").expect("valid URL")
284            }
285        };
286        let base_path = format!("/{}", self.base_path.trim_matches('/'));
287        if self
288            .email_password
289            .as_ref()
290            .is_some_and(|e| e.require_email_verification)
291            && self.mailer.is_none()
292        {
293            problems.push("require_email_verification needs a mailer: call .mailer(..)".into());
294        }
295
296        let mut registry = Registry::<D>::new();
297        crate::models::register(&mut registry.schema);
298        routes::register(
299            &mut PluginBuilder {
300                registry: &mut registry,
301            },
302            self.email_password.is_some(),
303        );
304        registry.set_owner("app");
305        registry.schema.extend(User::TABLE, U::columns());
306        self.plugins.register(&mut registry);
307        registry.set_owner("app");
308        for init in self.app_init {
309            init(&mut PluginBuilder {
310                registry: &mut registry,
311            });
312        }
313
314        problems.append(&mut registry.errors);
315        for (type_id, name, owner) in &registry.hook_targets {
316            if !registry.routes.iter().any(|r| r.type_id == *type_id) {
317                problems.push(format!(
318                    "`{owner}` hooks endpoint `{name}`, which no plugin registers"
319                ));
320            }
321        }
322
323        let mut by_path: BTreeMap<&'static str, Vec<_>> = BTreeMap::new();
324        for route in registry.routes {
325            by_path
326                .entry(route.path)
327                .or_default()
328                .push((route.method, route.endpoint));
329        }
330        let mut router = matchit::Router::new();
331        for (path, methods) in by_path {
332            if let Err(err) = router.insert(path, methods) {
333                problems.push(format!("route {path}: {err}"));
334            }
335        }
336
337        let schema = match registry.schema.finish() {
338            Ok(schema) => schema,
339            Err(mut errors) => {
340                problems.append(&mut errors);
341                Schema::default()
342            }
343        };
344        if !problems.is_empty() {
345            return Err(BuildError { problems });
346        }
347
348        let mut rate_limit = self.rate_limit;
349        rate_limit.rules.extend(registry.rate_rules);
350        rate_limit.rules.extend(RateLimit::core_rules());
351
352        let secure_cookies = match self.cookies.secure {
353            Secure::Always => true,
354            Secure::Never => false,
355            Secure::Auto => base_url.scheme() == "https",
356        };
357        let hasher = self.email_password.as_ref().map_or_else(
358            || Arc::new(Argon2id::owasp()) as Arc<dyn crate::crypto::PasswordHasher>,
359            |e| e.hasher.clone(),
360        );
361        let cache_fingerprint =
362            session::fingerprint(schema.expect(Session::TABLE), schema.expect(User::TABLE));
363        let config = CoreConfig {
364            app_name: self.app_name,
365            base_url,
366            base_path,
367            trusted_origins: self.trusted_origins,
368            session: self.session,
369            cookies: self.cookies,
370            email_password: self.email_password,
371            email_verification: self.email_verification,
372            rate_limit: rate_limit.clone(),
373            client_ip: self.client_ip,
374            secure_cookies,
375        };
376        let shared = Shared {
377            db: self.db,
378            schema,
379            keys: Keys::new(self.secrets),
380            config,
381            passwords: Passwords::new(hasher),
382            mailer: self.mailer,
383            plugins: registry.plugins,
384            hooks: registry.hooks,
385            gates: registry.gates,
386            resolvers: registry.resolvers,
387            events: registry.events,
388            router,
389            rate_limiter: RateLimiter::new(rate_limit),
390            cache_fingerprint,
391        };
392        Ok(Auth {
393            shared: Arc::new(shared),
394            plugins: Arc::new(self.plugins),
395            _user: PhantomData,
396        })
397    }
398}
399
400/// The client's socket address. Integrations put it in request extensions.
401#[derive(Clone, Copy, Debug, PartialEq, Eq)]
402pub struct ClientAddr(pub IpAddr);
403
404/// A configured auth instance. Cheap to clone (two `Arc`s).
405///
406/// `D` is the database adapter, `U` the app's user fields, `P` the plugin list
407/// (`plugins![TwoFactor, Organization]`).
408pub struct Auth<D, U = (), P = Nil> {
409    shared: Arc<Shared<D>>,
410    plugins: Arc<P>,
411    _user: PhantomData<fn() -> U>,
412}
413
414impl<D, U, P> Clone for Auth<D, U, P> {
415    fn clone(&self) -> Self {
416        Self {
417            shared: self.shared.clone(),
418            plugins: self.plugins.clone(),
419            _user: PhantomData,
420        }
421    }
422}
423
424impl<D, U, P> std::fmt::Debug for Auth<D, U, P> {
425    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
426        f.debug_struct("Auth")
427            .field("base_path", &self.shared.config.base_path)
428            .finish_non_exhaustive()
429    }
430}
431
432const MAX_BODY: usize = 64 * 1024;
433
434fn origin_of(value: &str) -> Option<String> {
435    Url::parse(value)
436        .ok()
437        .map(|u| u.origin().ascii_serialization())
438}
439
440impl<D: Adapter, U: Fields, P: PluginSet> Auth<D, U, P> {
441    pub fn config(&self) -> &CoreConfig {
442        &self.shared.config
443    }
444
445    pub fn schema(&self) -> &Schema {
446        &self.shared.schema
447    }
448
449    pub fn adapter(&self) -> &D {
450        &self.shared.db
451    }
452
453    pub fn migrator(&self) -> Migrator<'_, D> {
454        Migrator::new(&self.shared.db, &self.shared.schema)
455    }
456
457    /// A registered plugin's config. Doesn't compile when the plugin isn't registered.
458    pub fn plugin<Pl: Plugin, I>(&self) -> &Pl
459    where
460        P: Has<Pl, I>,
461    {
462        self.plugins.get()
463    }
464
465    /// Server-side calls to endpoints: no HTTP, no JSON.
466    pub fn api(&self) -> Api<'_, D> {
467        Api {
468            shared: &self.shared,
469            headers: HeaderMap::new(),
470            within: None,
471        }
472    }
473
474    /// Handles a request under `base_path`. Integrations call this.
475    pub async fn handle(&self, request: http::Request<Bytes>) -> Response {
476        let shared = &self.shared;
477        let config = &shared.config;
478        let (parts, body) = request.into_parts();
479        let Some(path) = parts.uri.path().strip_prefix(config.base_path.as_str()) else {
480            return AuthError::not_found().into_response();
481        };
482        let path = if path.is_empty() { "/" } else { path };
483        let Ok(matched) = shared.router.at(path) else {
484            return AuthError::not_found().into_response();
485        };
486        let Some((_, endpoint)) = matched.value.iter().find(|(m, _)| *m == parts.method) else {
487            return AuthError::new(
488                StatusCode::METHOD_NOT_ALLOWED,
489                codes::METHOD_NOT_ALLOWED,
490                "method not allowed",
491            )
492            .into_response();
493        };
494        if body.len() > MAX_BODY {
495            return AuthError::new(
496                StatusCode::PAYLOAD_TOO_LARGE,
497                codes::INVALID_BODY,
498                "request body is too large",
499            )
500            .into_response();
501        }
502
503        let ip = match &config.client_ip {
504            ClientIp::Socket => parts
505                .extensions
506                .get::<ClientAddr>()
507                .map(|a| a.0.to_string()),
508            ClientIp::Header(name) => parts
509                .headers
510                .get(name.as_str())
511                .and_then(|v| v.to_str().ok())
512                .and_then(|v| v.split(',').next())
513                .map(|v| v.trim().to_owned()),
514        };
515        if !shared
516            .rate_limiter
517            .check(ip.as_deref().unwrap_or("unknown"), path)
518        {
519            return AuthError::too_many_requests().into_response();
520        }
521
522        if !matches!(parts.method, Method::GET | Method::HEAD | Method::OPTIONS) {
523            let origin = header_str(&parts.headers, ORIGIN)
524                .filter(|o| o != "null")
525                .or_else(|| header_str(&parts.headers, REFERER).and_then(|r| origin_of(&r)));
526            let rejected = match &origin {
527                Some(origin) if !config.is_trusted_origin(origin) => {
528                    Some((codes::INVALID_ORIGIN, "invalid origin"))
529                }
530                None if parts.headers.contains_key(COOKIE) => {
531                    Some((codes::MISSING_OR_NULL_ORIGIN, "missing or null origin"))
532                }
533                _ => None,
534            };
535            if let Some((code, message)) = rejected {
536                return AuthError::new(StatusCode::FORBIDDEN, code, message).into_response();
537            }
538        }
539
540        let request = RequestInfo {
541            method: parts.method.clone(),
542            path: path.to_owned(),
543            params: matched
544                .params
545                .iter()
546                .map(|(k, v)| (k.to_owned(), v.to_owned()))
547                .collect(),
548            query: parts.uri.query().map(str::to_owned),
549            user_agent: header_str(&parts.headers, USER_AGENT),
550            headers: parts.headers,
551            ip,
552        };
553        endpoint
554            .clone()
555            .handle(shared, Arc::new(request), body)
556            .await
557    }
558
559    /// The session for these request headers, plus `Set-Cookie` values the caller should
560    /// add to its response (refreshed or cleared cookies).
561    pub async fn session_with_cookies(
562        &self,
563        headers: &HeaderMap,
564    ) -> (
565        Result<Option<SessionData<U, P>>, AuthError>,
566        Vec<HeaderValue>,
567    ) {
568        let request = Arc::new(RequestInfo::synthetic(
569            Method::GET,
570            "/get-session",
571            headers.clone(),
572        ));
573        let effects = Arc::new(Mutex::new(Effects::default()));
574        let result = session::resolve(&self.shared, None, &request, &effects)
575            .await
576            .and_then(|view| {
577                view.map(SessionData::from_view)
578                    .transpose()
579                    .map_err(AuthError::internal)
580            });
581        let cookies = effects
582            .lock()
583            .unwrap()
584            .cookies
585            .iter()
586            .filter_map(|c| HeaderValue::from_str(&c.to_header(&self.shared.config)).ok())
587            .collect();
588        (result, cookies)
589    }
590
591    /// The session for these request headers (cookie, or any registered resolver).
592    pub async fn get_session(
593        &self,
594        headers: &HeaderMap,
595    ) -> Result<Option<SessionData<U, P>>, AuthError> {
596        self.session_with_cookies(headers).await.0
597    }
598
599    /// The session for a raw token, e.g. from a WebSocket query string.
600    pub async fn get_session_by_token(
601        &self,
602        token: &str,
603    ) -> Result<Option<SessionData<U, P>>, AuthError> {
604        let view = session::by_token(&self.shared, &self.shared.db, token).await?;
605        view.map(SessionData::from_view)
606            .transpose()
607            .map_err(AuthError::internal)
608    }
609}
610
611/// What integrations and plugin extension traits need from an auth instance, without
612/// naming its type parameters.
613pub trait AuthInstance: Clone + Send + Sync + 'static {
614    type Db: Adapter;
615    type UserFields: Fields;
616    type Plugins: PluginSet;
617
618    fn config(&self) -> &CoreConfig;
619    fn api(&self) -> Api<'_, Self::Db>;
620    fn handle(&self, request: http::Request<Bytes>) -> impl Future<Output = Response> + Send;
621    #[allow(clippy::type_complexity)]
622    fn session_with_cookies(
623        &self,
624        headers: &HeaderMap,
625    ) -> impl Future<
626        Output = (
627            Result<Option<SessionData<Self::UserFields, Self::Plugins>>, AuthError>,
628            Vec<HeaderValue>,
629        ),
630    > + Send;
631}
632
633impl<D: Adapter, U: Fields, P: PluginSet> AuthInstance for Auth<D, U, P> {
634    type Db = D;
635    type UserFields = U;
636    type Plugins = P;
637
638    fn config(&self) -> &CoreConfig {
639        Auth::config(self)
640    }
641
642    fn api(&self) -> Api<'_, D> {
643        Auth::api(self)
644    }
645
646    fn handle(&self, request: http::Request<Bytes>) -> impl Future<Output = Response> + Send {
647        Auth::handle(self, request)
648    }
649
650    fn session_with_cookies(
651        &self,
652        headers: &HeaderMap,
653    ) -> impl Future<
654        Output = (
655            Result<Option<SessionData<U, P>>, AuthError>,
656            Vec<HeaderValue>,
657        ),
658    > + Send {
659        Auth::session_with_cookies(self, headers)
660    }
661}
662
663#[diagnostic::on_unimplemented(
664    message = "plugin `{Pl}` is not registered on this auth instance",
665    note = "register it with `.plugin(...)` on the builder and list it in your `plugins![..]` alias"
666)]
667/// For plugin extension traits: methods bounded by `Self: HasPlugin<MyPlugin, I>` only
668/// compile on an `Auth` that registered the plugin.
669pub trait HasPlugin<Pl, I>: AuthInstance {
670    fn plugin_arc(&self) -> &Arc<Pl>;
671}
672
673impl<D: Adapter, U: Fields, P: Has<Pl, I>, Pl: Plugin, I> HasPlugin<Pl, I> for Auth<D, U, P> {
674    fn plugin_arc(&self) -> &Arc<Pl> {
675        self.plugins.get()
676    }
677}
678
679/// Server-side endpoint calls. Pass the request's headers (or a session token) for
680/// endpoints that need a session.
681pub struct Api<'a, D> {
682    shared: &'a Arc<Shared<D>>,
683    headers: HeaderMap,
684    within: Option<(Arc<D>, DeferredEvents)>,
685}
686
687impl<D> std::fmt::Debug for Api<'_, D> {
688    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
689        f.write_str("Api")
690    }
691}
692
693/// An endpoint's typed output plus the cookies it wants set.
694#[derive(Debug)]
695pub struct ApiResponse<T> {
696    pub data: T,
697    pub set_cookies: Vec<HeaderValue>,
698}
699
700impl<T: Serialize> ApiResponse<T> {
701    /// The same response the HTTP route would give.
702    pub fn into_http(self) -> Response {
703        let body = serde_json::to_vec(&self.data).unwrap_or_default();
704        let mut response = Response::new(Bytes::from(body));
705        response.headers_mut().insert(
706            http::header::CONTENT_TYPE,
707            HeaderValue::from_static("application/json"),
708        );
709        for cookie in self.set_cookies {
710            response
711                .headers_mut()
712                .append(http::header::SET_COOKIE, cookie);
713        }
714        response
715    }
716}
717
718/// Lets a handler return a server API result as is: the JSON body plus the cookies the
719/// endpoint set, like the HTTP route would answer.
720#[cfg(feature = "axum")]
721impl<T: Serialize> axum_core::response::IntoResponse for ApiResponse<T> {
722    fn into_response(self) -> axum_core::response::Response {
723        self.into_http().map(axum_core::body::Body::from)
724    }
725}
726
727impl<D: Adapter> Api<'_, D> {
728    /// The configured adapter.
729    pub fn adapter(&self) -> &D {
730        &self.shared.db
731    }
732
733    /// Runs every call on `db` instead of the configured adapter (its queries, session
734    /// lookup, hooks and gates), and queues the calls' events on `events` instead of firing
735    /// them.
736    ///
737    /// Each call runs inside its own `db.begin()`, committed when the call succeeds and
738    /// rolled back when it fails, so a failed call leaves `db` as it was. That needs an
739    /// adapter whose `begin` nests inside its own queries: with sqlx, use `.in_tx(&tx)` from
740    /// `fastauth_sqlx::InTx`, which binds the adapter to a transaction and makes `begin` a
741    /// savepoint.
742    pub fn within(mut self, db: D, events: &DeferredEvents) -> Self {
743        self.within = Some((Arc::new(db), events.clone()));
744        self
745    }
746
747    /// Uses these request headers: cookies for the session, user agent and so on.
748    pub fn headers(mut self, headers: &HeaderMap) -> Self {
749        self.headers = headers.clone();
750        self
751    }
752
753    /// Acts as the session with this raw token.
754    pub fn session_token(mut self, token: &str) -> Self {
755        let name = self.shared.config.cookie_name(session::SESSION_TOKEN);
756        let signed = self.shared.keys.sign(SignPurpose::Cookie, token);
757        if let Ok(value) = HeaderValue::from_str(&format!("{name}={signed}")) {
758            self.headers.insert(COOKIE, value);
759        }
760        self
761    }
762
763    /// Runs any endpoint, with its access check, hooks and events.
764    pub async fn call<E: Endpoint<D>>(
765        &self,
766        endpoint: &E,
767        input: E::Input,
768    ) -> Result<ApiResponse<E::Output>, AuthError> {
769        let request = Arc::new(RequestInfo::synthetic(
770            E::METHOD,
771            E::PATH,
772            self.headers.clone(),
773        ));
774        let Some((db, events)) = &self.within else {
775            let mut executed = execute(self.shared, None, endpoint, request, input).await;
776            if executed.result.is_ok() {
777                let pending = std::mem::take(&mut executed.effects.events);
778                dispatch_events(self.shared, pending).await;
779            }
780            return self.respond(executed);
781        };
782        let savepoint = db.begin().await?;
783        let mut executed = execute(self.shared, Some(db.clone()), endpoint, request, input).await;
784        if !matches!(executed.result, Ok(Outcome::Output(_))) {
785            savepoint.rollback().await?;
786            return self.respond(executed);
787        }
788        savepoint.commit().await?;
789        let pending = std::mem::take(&mut executed.effects.events);
790        let shared = self.shared.clone();
791        events.push(Box::new(move || {
792            Box::pin(async move { dispatch_events(&shared, pending).await })
793        }));
794        self.respond(executed)
795    }
796
797    fn respond<O>(&self, executed: Executed<O>) -> Result<ApiResponse<O>, AuthError> {
798        let set_cookies = executed
799            .effects
800            .cookies
801            .iter()
802            .filter_map(|c| HeaderValue::from_str(&c.to_header(&self.shared.config)).ok())
803            .collect();
804        match executed.result? {
805            Outcome::Output(data) => Ok(ApiResponse { data, set_cookies }),
806            Outcome::Response(response) => Err(AuthError::with_message(
807                response.status(),
808                "HOOK_RESPONDED",
809                String::from_utf8_lossy(response.body()).into_owned(),
810            )),
811        }
812    }
813
814    /// Creates a user, plus a credential account when `password` is set. Server-only: there
815    /// is no HTTP route. Validates like sign-up and answers `USER_ALREADY_EXISTS` (422) when
816    /// the email is taken.
817    pub async fn create_user(&self, input: routes::CreateUserInput) -> Result<UserView, AuthError> {
818        Ok(self.call(&routes::CreateUser, input).await?.data)
819    }
820
821    pub async fn sign_up_email(
822        &self,
823        input: routes::SignUpEmailInput,
824    ) -> Result<ApiResponse<routes::SignUpOutput>, AuthError> {
825        self.call(&routes::SignUpEmail, input).await
826    }
827
828    pub async fn sign_in_email(
829        &self,
830        input: routes::SignInEmailInput,
831    ) -> Result<ApiResponse<routes::SignInOutput>, AuthError> {
832        self.call(&routes::SignInEmail, input).await
833    }
834
835    pub async fn sign_out(&self) -> Result<ApiResponse<routes::SignOutOutput>, AuthError> {
836        self.call(&routes::SignOut, crate::endpoint::Empty {}).await
837    }
838
839    pub async fn list_sessions(
840        &self,
841    ) -> Result<ApiResponse<Vec<serde_json::Map<String, serde_json::Value>>>, AuthError> {
842        self.call(&routes::ListSessions, serde_json::Map::new())
843            .await
844    }
845
846    pub async fn revoke_other_sessions(&self) -> Result<ApiResponse<routes::Status>, AuthError> {
847        self.call(&routes::RevokeOtherSessions, crate::endpoint::Empty {})
848            .await
849    }
850
851    pub async fn change_password(
852        &self,
853        input: routes::ChangePasswordInput,
854    ) -> Result<ApiResponse<routes::ChangePasswordOutput>, AuthError> {
855        self.call(&routes::ChangePassword, input).await
856    }
857
858    pub async fn request_password_reset(
859        &self,
860        input: routes::RequestPasswordResetInput,
861    ) -> Result<ApiResponse<routes::RequestPasswordResetOutput>, AuthError> {
862        self.call(&routes::RequestPasswordReset, input).await
863    }
864
865    pub async fn reset_password(
866        &self,
867        input: routes::ResetPasswordInput,
868    ) -> Result<ApiResponse<routes::Status>, AuthError> {
869        self.call(&routes::ResetPassword, input).await
870    }
871}