1use 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#[derive(Debug)]
44pub struct FastAuth;
45
46#[derive(Debug)]
48pub struct NoDatabase;
49#[derive(Debug)]
51pub struct Missing;
52#[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
92pub 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 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 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 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 pub fn base_path(mut self, path: impl Into<String>) -> Self {
195 self.base_path = path.into();
196 self
197 }
198
199 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 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 pub fn secondary_storage(mut self, storage: impl SecondaryStorage) -> Self {
262 self.secondary_storage = Some(Arc::new(storage));
263 self
264 }
265
266 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 pub fn multi_instance(mut self, multi_instance: bool) -> Self {
283 self.multi_instance = multi_instance;
284 self
285 }
286
287 pub fn allow_insecure_config(mut self, allow: bool) -> Self {
293 self.allow_insecure = allow;
294 self
295 }
296
297 pub fn column_naming(mut self, naming: ColumnNaming) -> Self {
303 self.storage.naming = naming;
304 self
305 }
306
307 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 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 pub fn session_tokens(mut self, tokens: SessionTokens) -> Self {
341 self.session_tokens = tokens;
342 self
343 }
344
345 pub fn only_owned_accounts(mut self, on: bool) -> Self {
352 self.only_owned_accounts = on;
353 self
354 }
355
356 pub fn store_oauth_tokens_in_plaintext(mut self, on: bool) -> Self {
371 self.plaintext_oauth_tokens = on;
372 self
373 }
374
375 pub fn migrations(mut self, mode: Migrations) -> Self {
380 self.migrations = mode;
381 self
382 }
383
384 pub fn better_auth_compat(mut self, compat: BetterAuthCompat) -> Self {
389 self.better_auth = Some(compat);
390 self
391 }
392
393 pub fn user_fields<U2: Fields>(self) -> Builder<D, U2, P, S, B> {
395 self.retype(|p| p)
396 }
397
398 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 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 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 ®istry.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
745fn 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
757pub struct ClientAddr(pub IpAddr);
758
759pub 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 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 pub async fn prune_verifications(&self) -> Result<u64, AuthError> {
825 prune_verifications(&self.shared).await
826 }
827
828 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 pub fn plugin<Pl: Plugin, I>(&self) -> &Pl
852 where
853 P: Has<Pl, I>,
854 {
855 self.plugins.get()
856 }
857
858 pub fn api(&self) -> Api<'_, D> {
860 Api {
861 shared: &self.shared,
862 headers: HeaderMap::new(),
863 within: None,
864 }
865 }
866
867 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 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 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 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
1005pub 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 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)]
1072pub 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
1084pub 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#[derive(Debug)]
1100pub struct ApiResponse<T> {
1101 pub data: T,
1102 pub set_cookies: Vec<HeaderValue>,
1103}
1104
1105impl<T: Serialize> ApiResponse<T> {
1106 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#[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#[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 pub fn adapter(&self) -> &D {
1146 &self.shared.db
1147 }
1148
1149 pub fn db(&self) -> Db<'_, D> {
1152 Db::new(&self.shared.db, &self.shared.schema)
1153 }
1154
1155 pub fn within(mut self, db: D, events: &DeferredEvents) -> Self {
1165 self.within = Some((Arc::new(db), events.clone()));
1166 self
1167 }
1168
1169 pub fn headers(mut self, headers: &HeaderMap) -> Self {
1171 self.headers = headers.clone();
1172 self
1173 }
1174
1175 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 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 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}