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