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