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
311        let mut registry = Registry::<D>::new();
312        crate::models::register(&mut registry.schema);
313        routes::register(
314            &mut PluginBuilder {
315                registry: &mut registry,
316            },
317            self.email_password.is_some(),
318        );
319        registry.set_owner("app");
320        registry.schema.extend(User::TABLE, U::columns());
321        self.plugins.register(&mut registry);
322        registry.set_owner("app");
323        for init in self.app_init {
324            init(&mut PluginBuilder {
325                registry: &mut registry,
326            });
327        }
328
329        problems.append(&mut registry.errors);
330        for (type_id, name, owner) in &registry.hook_targets {
331            if !registry.routes.iter().any(|r| r.type_id == *type_id)
332                && !registry.server_endpoints.contains(type_id)
333            {
334                problems.push(format!(
335                    "`{owner}` hooks endpoint `{name}`, which no plugin registers"
336                ));
337            }
338        }
339
340        let mut by_path: BTreeMap<&'static str, Vec<_>> = BTreeMap::new();
341        for route in registry.routes {
342            by_path
343                .entry(route.path)
344                .or_default()
345                .push((route.method, route.endpoint));
346        }
347        let mut router = matchit::Router::new();
348        for (path, methods) in by_path {
349            if let Err(err) = router.insert(path, methods) {
350                problems.push(format!("route {path}: {err}"));
351            }
352        }
353
354        let schema = match registry.schema.finish(self.ids.storage()) {
355            Ok(schema) => schema,
356            Err(mut errors) => {
357                problems.append(&mut errors);
358                Schema::default()
359            }
360        };
361        if !problems.is_empty() {
362            return Err(BuildError { problems });
363        }
364
365        let mut rate_limit = self.rate_limit;
366        rate_limit.rules.extend(registry.rate_rules);
367        rate_limit.rules.extend(RateLimit::core_rules());
368
369        let secure_cookies = match self.cookies.secure {
370            Secure::Always => true,
371            Secure::Never => false,
372            Secure::Auto => base_url.scheme() == "https",
373        };
374        let hasher = self.email_password.as_ref().map_or_else(
375            || Arc::new(Argon2id::owasp()) as Arc<dyn crate::crypto::PasswordHasher>,
376            |e| e.hasher.clone(),
377        );
378        let cache_fingerprint =
379            session::fingerprint(schema.expect(Session::TABLE), schema.expect(User::TABLE));
380        let config = CoreConfig {
381            app_name: self.app_name,
382            base_url,
383            base_path,
384            trusted_origins: self.trusted_origins,
385            session: self.session,
386            cookies: self.cookies,
387            email_password: self.email_password,
388            email_verification: self.email_verification,
389            rate_limit: rate_limit.clone(),
390            client_ip: self.client_ip,
391            ids: self.ids,
392            secure_cookies,
393        };
394        let shared = Shared {
395            db: self.db,
396            schema,
397            keys: Keys::new(self.secrets),
398            config,
399            passwords: Passwords::new(hasher),
400            mailer: self.mailer,
401            plugins: registry.plugins,
402            hooks: registry.hooks,
403            gates: registry.gates,
404            resolvers: registry.resolvers,
405            response_hooks: registry.response_hooks,
406            events: registry.events,
407            router,
408            rate_limiter: RateLimiter::new(rate_limit),
409            cache_fingerprint,
410        };
411        Ok(Auth {
412            shared: Arc::new(shared),
413            plugins: Arc::new(self.plugins),
414            _user: PhantomData,
415        })
416    }
417}
418
419/// The client's socket address. Integrations put it in request extensions.
420#[derive(Clone, Copy, Debug, PartialEq, Eq)]
421pub struct ClientAddr(pub IpAddr);
422
423/// A configured auth instance. Cheap to clone (two `Arc`s).
424///
425/// `D` is the database adapter, `U` the app's user fields, `P` the plugin list
426/// (`plugins![TwoFactor, Organization]`).
427pub struct Auth<D, U = (), P = Nil> {
428    shared: Arc<Shared<D>>,
429    plugins: Arc<P>,
430    _user: PhantomData<fn() -> U>,
431}
432
433impl<D, U, P> Clone for Auth<D, U, P> {
434    fn clone(&self) -> Self {
435        Self {
436            shared: self.shared.clone(),
437            plugins: self.plugins.clone(),
438            _user: PhantomData,
439        }
440    }
441}
442
443impl<D, U, P> std::fmt::Debug for Auth<D, U, P> {
444    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
445        f.debug_struct("Auth")
446            .field("base_path", &self.shared.config.base_path)
447            .finish_non_exhaustive()
448    }
449}
450
451const MAX_BODY: usize = 64 * 1024;
452
453fn origin_of(value: &str) -> Option<String> {
454    Url::parse(value)
455        .ok()
456        .map(|u| u.origin().ascii_serialization())
457}
458
459impl<D: Adapter, U: Fields, P: PluginSet> Auth<D, U, P> {
460    pub fn config(&self) -> &CoreConfig {
461        &self.shared.config
462    }
463
464    pub fn schema(&self) -> &Schema {
465        &self.shared.schema
466    }
467
468    pub fn adapter(&self) -> &D {
469        &self.shared.db
470    }
471
472    pub fn migrator(&self) -> Migrator<'_, D> {
473        Migrator::new(&self.shared.db, &self.shared.schema)
474    }
475
476    /// A registered plugin's config. Doesn't compile when the plugin isn't registered.
477    pub fn plugin<Pl: Plugin, I>(&self) -> &Pl
478    where
479        P: Has<Pl, I>,
480    {
481        self.plugins.get()
482    }
483
484    /// Server-side calls to endpoints: no HTTP, no JSON.
485    pub fn api(&self) -> Api<'_, D> {
486        Api {
487            shared: &self.shared,
488            headers: HeaderMap::new(),
489            within: None,
490        }
491    }
492
493    /// Handles a request under `base_path`. Integrations call this.
494    pub async fn handle(&self, request: http::Request<Bytes>) -> Response {
495        let shared = &self.shared;
496        let config = &shared.config;
497        let (parts, body) = request.into_parts();
498        let Some(path) = parts.uri.path().strip_prefix(config.base_path.as_str()) else {
499            return AuthError::not_found().into_response();
500        };
501        let path = if path.is_empty() { "/" } else { path };
502        let Ok(matched) = shared.router.at(path) else {
503            return AuthError::not_found().into_response();
504        };
505        let Some((_, endpoint)) = matched.value.iter().find(|(m, _)| *m == parts.method) else {
506            return AuthError::new(
507                StatusCode::METHOD_NOT_ALLOWED,
508                codes::METHOD_NOT_ALLOWED,
509                "method not allowed",
510            )
511            .into_response();
512        };
513        if body.len() > MAX_BODY {
514            return AuthError::new(
515                StatusCode::PAYLOAD_TOO_LARGE,
516                codes::INVALID_BODY,
517                "request body is too large",
518            )
519            .into_response();
520        }
521
522        let ip = match &config.client_ip {
523            ClientIp::Socket => parts
524                .extensions
525                .get::<ClientAddr>()
526                .map(|a| a.0.to_string()),
527            ClientIp::Header(name) => parts
528                .headers
529                .get(name.as_str())
530                .and_then(|v| v.to_str().ok())
531                .and_then(|v| v.split(',').next())
532                .map(|v| v.trim().to_owned()),
533        };
534        if !shared
535            .rate_limiter
536            .check(ip.as_deref().unwrap_or("unknown"), path)
537        {
538            return AuthError::too_many_requests().into_response();
539        }
540
541        if !matches!(parts.method, Method::GET | Method::HEAD | Method::OPTIONS) {
542            let origin = header_str(&parts.headers, ORIGIN)
543                .filter(|o| o != "null")
544                .or_else(|| header_str(&parts.headers, REFERER).and_then(|r| origin_of(&r)));
545            let rejected = match &origin {
546                Some(origin) if !config.is_trusted_origin(origin) => {
547                    Some((codes::INVALID_ORIGIN, "invalid origin"))
548                }
549                None if parts.headers.contains_key(COOKIE) => {
550                    Some((codes::MISSING_OR_NULL_ORIGIN, "missing or null origin"))
551                }
552                _ => None,
553            };
554            if let Some((code, message)) = rejected {
555                return AuthError::new(StatusCode::FORBIDDEN, code, message).into_response();
556            }
557        }
558
559        let request = RequestInfo {
560            method: parts.method.clone(),
561            path: path.to_owned(),
562            params: matched
563                .params
564                .iter()
565                .map(|(k, v)| (k.to_owned(), v.to_owned()))
566                .collect(),
567            query: parts.uri.query().map(str::to_owned),
568            user_agent: header_str(&parts.headers, USER_AGENT),
569            headers: parts.headers,
570            ip,
571        };
572        endpoint
573            .clone()
574            .handle(shared, Arc::new(request), body)
575            .await
576    }
577
578    /// The session for these request headers, plus `Set-Cookie` values the caller should
579    /// add to its response (refreshed or cleared cookies).
580    pub async fn session_with_cookies(
581        &self,
582        headers: &HeaderMap,
583    ) -> (
584        Result<Option<SessionData<U, P>>, AuthError>,
585        Vec<HeaderValue>,
586    ) {
587        let request = Arc::new(RequestInfo::synthetic(
588            Method::GET,
589            "/get-session",
590            headers.clone(),
591        ));
592        let effects = Arc::new(Mutex::new(Effects::default()));
593        let result = session::resolve(&self.shared, None, &request, &effects)
594            .await
595            .and_then(|view| {
596                view.map(SessionData::from_view)
597                    .transpose()
598                    .map_err(AuthError::internal)
599            });
600        let cookies = effects
601            .lock()
602            .unwrap()
603            .cookies
604            .iter()
605            .filter_map(|c| HeaderValue::from_str(&c.to_header(&self.shared.config)).ok())
606            .collect();
607        (result, cookies)
608    }
609
610    /// The session for these request headers (cookie, or any registered resolver).
611    pub async fn get_session(
612        &self,
613        headers: &HeaderMap,
614    ) -> Result<Option<SessionData<U, P>>, AuthError> {
615        self.session_with_cookies(headers).await.0
616    }
617
618    /// The session for a raw token, e.g. from a WebSocket query string.
619    pub async fn get_session_by_token(
620        &self,
621        token: &str,
622    ) -> Result<Option<SessionData<U, P>>, AuthError> {
623        let view = session::by_token(&self.shared, &self.shared.db, token).await?;
624        view.map(SessionData::from_view)
625            .transpose()
626            .map_err(AuthError::internal)
627    }
628}
629
630/// What integrations and plugin extension traits need from an auth instance, without
631/// naming its type parameters.
632pub trait AuthInstance: Clone + Send + Sync + 'static {
633    type Db: Adapter;
634    type UserFields: Fields;
635    type Plugins: PluginSet;
636
637    fn config(&self) -> &CoreConfig;
638    fn api(&self) -> Api<'_, Self::Db>;
639    /// A registered plugin's config, or `None` when `P` isn't registered. For code generic
640    /// over `AuthInstance` (an axum extractor) that can't name the `HasPlugin` index; with a
641    /// concrete `Auth`, a plugin's extension trait is the compile-checked way.
642    fn try_plugin<P: Plugin>(&self) -> Option<&P>;
643    fn handle(&self, request: http::Request<Bytes>) -> impl Future<Output = Response> + Send;
644    #[allow(clippy::type_complexity)]
645    fn session_with_cookies(
646        &self,
647        headers: &HeaderMap,
648    ) -> impl Future<
649        Output = (
650            Result<Option<SessionData<Self::UserFields, Self::Plugins>>, AuthError>,
651            Vec<HeaderValue>,
652        ),
653    > + Send;
654}
655
656impl<D: Adapter, U: Fields, P: PluginSet> AuthInstance for Auth<D, U, P> {
657    type Db = D;
658    type UserFields = U;
659    type Plugins = P;
660
661    fn config(&self) -> &CoreConfig {
662        Auth::config(self)
663    }
664
665    fn api(&self) -> Api<'_, D> {
666        Auth::api(self)
667    }
668
669    fn try_plugin<Pl: Plugin>(&self) -> Option<&Pl> {
670        self.shared
671            .plugins
672            .get(&std::any::TypeId::of::<Pl>())
673            .and_then(|plugin| plugin.downcast_ref::<Pl>())
674    }
675
676    fn handle(&self, request: http::Request<Bytes>) -> impl Future<Output = Response> + Send {
677        Auth::handle(self, request)
678    }
679
680    fn session_with_cookies(
681        &self,
682        headers: &HeaderMap,
683    ) -> impl Future<
684        Output = (
685            Result<Option<SessionData<U, P>>, AuthError>,
686            Vec<HeaderValue>,
687        ),
688    > + Send {
689        Auth::session_with_cookies(self, headers)
690    }
691}
692
693#[diagnostic::on_unimplemented(
694    message = "plugin `{Pl}` is not registered on this auth instance",
695    note = "register it with `.plugin(...)` on the builder and list it in your `plugins![..]` alias"
696)]
697/// For plugin extension traits: methods bounded by `Self: HasPlugin<MyPlugin, I>` only
698/// compile on an `Auth` that registered the plugin.
699pub trait HasPlugin<Pl, I>: AuthInstance {
700    fn plugin_arc(&self) -> &Arc<Pl>;
701}
702
703impl<D: Adapter, U: Fields, P: Has<Pl, I>, Pl: Plugin, I> HasPlugin<Pl, I> for Auth<D, U, P> {
704    fn plugin_arc(&self) -> &Arc<Pl> {
705        self.plugins.get()
706    }
707}
708
709/// Server-side endpoint calls. Pass the request's headers (or a session token) for
710/// endpoints that need a session.
711pub struct Api<'a, D> {
712    shared: &'a Arc<Shared<D>>,
713    headers: HeaderMap,
714    within: Option<(Arc<D>, DeferredEvents)>,
715}
716
717impl<D> std::fmt::Debug for Api<'_, D> {
718    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
719        f.write_str("Api")
720    }
721}
722
723/// An endpoint's typed output plus the cookies it wants set.
724#[derive(Debug)]
725pub struct ApiResponse<T> {
726    pub data: T,
727    pub set_cookies: Vec<HeaderValue>,
728}
729
730impl<T: Serialize> ApiResponse<T> {
731    /// The same response the HTTP route would give.
732    pub fn into_http(self) -> Response {
733        let body = serde_json::to_vec(&self.data).unwrap_or_default();
734        let mut response = Response::new(Bytes::from(body));
735        response.headers_mut().insert(
736            http::header::CONTENT_TYPE,
737            HeaderValue::from_static("application/json"),
738        );
739        for cookie in self.set_cookies {
740            response
741                .headers_mut()
742                .append(http::header::SET_COOKIE, cookie);
743        }
744        response
745    }
746}
747
748/// Lets a handler return a server API result as is: the JSON body plus the cookies the
749/// endpoint set, like the HTTP route would answer.
750#[cfg(feature = "axum")]
751impl<T: Serialize> axum_core::response::IntoResponse for ApiResponse<T> {
752    fn into_response(self) -> axum_core::response::Response {
753        self.into_http().map(axum_core::body::Body::from)
754    }
755}
756
757impl<D: Adapter> Api<'_, D> {
758    /// The configured adapter.
759    pub fn adapter(&self) -> &D {
760        &self.shared.db
761    }
762
763    /// Typed queries on the configured adapter, for code outside an endpoint that has an
764    /// `AuthInstance` but no `Ctx` (an axum extractor reading a plugin's table).
765    pub fn db(&self) -> Db<'_, D> {
766        Db::new(&self.shared.db, &self.shared.schema)
767    }
768
769    /// Runs every call on `db` instead of the configured adapter (its queries, session
770    /// lookup, hooks and gates), and queues the calls' events on `events` instead of firing
771    /// them.
772    ///
773    /// Each call runs inside its own `db.begin()`, committed when the call succeeds and
774    /// rolled back when it fails, so a failed call leaves `db` as it was. That needs an
775    /// adapter whose `begin` nests inside its own queries: with sqlx, use `.in_tx(&tx)` from
776    /// `fastauth_sqlx::InTx`, which binds the adapter to a transaction and makes `begin` a
777    /// savepoint.
778    pub fn within(mut self, db: D, events: &DeferredEvents) -> Self {
779        self.within = Some((Arc::new(db), events.clone()));
780        self
781    }
782
783    /// Uses these request headers: cookies for the session, user agent and so on.
784    pub fn headers(mut self, headers: &HeaderMap) -> Self {
785        self.headers = headers.clone();
786        self
787    }
788
789    /// Acts as the session with this raw token.
790    pub fn session_token(mut self, token: &str) -> Self {
791        let name = self.shared.config.cookie_name(session::SESSION_TOKEN);
792        let signed = self.shared.keys.sign(SignPurpose::Cookie, token);
793        if let Ok(value) = HeaderValue::from_str(&format!("{name}={signed}")) {
794            self.headers.insert(COOKIE, value);
795        }
796        self
797    }
798
799    /// Runs any endpoint, with its access check, hooks and events.
800    pub async fn call<E: Endpoint<D>>(
801        &self,
802        endpoint: &E,
803        input: E::Input,
804    ) -> Result<ApiResponse<E::Output>, AuthError> {
805        let request = Arc::new(RequestInfo::synthetic(
806            E::METHOD,
807            E::PATH,
808            self.headers.clone(),
809        ));
810        let Some((db, events)) = &self.within else {
811            let mut executed = execute(self.shared, None, endpoint, request, input).await;
812            if executed.result.is_ok() {
813                let pending = std::mem::take(&mut executed.effects.events);
814                dispatch_events(self.shared, pending).await;
815            }
816            return self.respond(executed);
817        };
818        let savepoint = db.begin().await?;
819        let mut executed = execute(self.shared, Some(db.clone()), endpoint, request, input).await;
820        if !matches!(executed.result, Ok(Outcome::Output(_))) {
821            savepoint.rollback().await?;
822            return self.respond(executed);
823        }
824        savepoint.commit().await?;
825        let pending = std::mem::take(&mut executed.effects.events);
826        let shared = self.shared.clone();
827        events.push(Box::new(move || {
828            Box::pin(async move { dispatch_events(&shared, pending).await })
829        }));
830        self.respond(executed)
831    }
832
833    fn respond<O>(&self, executed: Executed<O>) -> Result<ApiResponse<O>, AuthError> {
834        let set_cookies = executed
835            .effects
836            .cookies
837            .iter()
838            .filter_map(|c| HeaderValue::from_str(&c.to_header(&self.shared.config)).ok())
839            .collect();
840        match executed.result? {
841            Outcome::Output(data) => Ok(ApiResponse { data, set_cookies }),
842            Outcome::Response(response) => Err(AuthError::with_message(
843                response.status(),
844                "HOOK_RESPONDED",
845                String::from_utf8_lossy(response.body()).into_owned(),
846            )),
847        }
848    }
849
850    /// Creates a user, plus a credential account when `password` is set. Server-only: there
851    /// is no HTTP route. Validates like sign-up and answers
852    /// `USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL` (422) when the email is taken.
853    pub async fn create_user(&self, input: routes::CreateUserInput) -> Result<UserView, AuthError> {
854        Ok(self.call(&routes::CreateUser, input).await?.data)
855    }
856
857    pub async fn sign_up_email(
858        &self,
859        input: routes::SignUpEmailInput,
860    ) -> Result<ApiResponse<routes::SignUpOutput>, AuthError> {
861        self.call(&routes::SignUpEmail, input).await
862    }
863
864    pub async fn sign_in_email(
865        &self,
866        input: routes::SignInEmailInput,
867    ) -> Result<ApiResponse<routes::SignInOutput>, AuthError> {
868        self.call(&routes::SignInEmail, input).await
869    }
870
871    pub async fn sign_out(&self) -> Result<ApiResponse<routes::SignOutOutput>, AuthError> {
872        self.call(&routes::SignOut, crate::endpoint::Empty {}).await
873    }
874
875    pub async fn list_sessions(
876        &self,
877    ) -> Result<ApiResponse<Vec<serde_json::Map<String, serde_json::Value>>>, AuthError> {
878        self.call(&routes::ListSessions, serde_json::Map::new())
879            .await
880    }
881
882    pub async fn revoke_other_sessions(&self) -> Result<ApiResponse<routes::Status>, AuthError> {
883        self.call(&routes::RevokeOtherSessions, crate::endpoint::Empty {})
884            .await
885    }
886
887    pub async fn change_password(
888        &self,
889        input: routes::ChangePasswordInput,
890    ) -> Result<ApiResponse<routes::ChangePasswordOutput>, AuthError> {
891        self.call(&routes::ChangePassword, input).await
892    }
893
894    pub async fn request_password_reset(
895        &self,
896        input: routes::RequestPasswordResetInput,
897    ) -> Result<ApiResponse<routes::RequestPasswordResetOutput>, AuthError> {
898        self.call(&routes::RequestPasswordReset, input).await
899    }
900
901    pub async fn reset_password(
902        &self,
903        input: routes::ResetPasswordInput,
904    ) -> Result<ApiResponse<routes::Status>, AuthError> {
905        self.call(&routes::ResetPassword, input).await
906    }
907}