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