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