1use std::any::{Any, TypeId};
5use std::borrow::Cow;
6use std::collections::HashMap;
7use std::future::Future;
8use std::marker::PhantomData;
9use std::pin::Pin;
10use std::sync::{Arc, Mutex};
11
12use bytes::Bytes;
13use http::header::{CONTENT_TYPE, LOCATION, SET_COOKIE};
14use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
15use serde::Serialize;
16use serde::de::DeserializeOwned;
17use time::{Duration, OffsetDateTime};
18
19use crate::adapter::{Adapter, Queries};
20use crate::config::CoreConfig;
21use crate::cookies::{self, SetCookie};
22use crate::crypto::{Keys, Passwords, SignPurpose};
23use crate::error::AuthError;
24use crate::events::Event;
25use crate::internal::Internal;
26use crate::mail::DynMailer;
27use crate::plugin::Plugin;
28use crate::query::Db;
29use crate::rate_limit::RateLimiter;
30use crate::schema::Schema;
31use crate::session::{SessionView, UserView};
32use crate::value::Id;
33
34pub type Response = http::Response<Bytes>;
35pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum AccessLevel {
39 Public,
40 Optional,
41 Required,
42 Fresh,
43}
44
45pub trait Access: Send + Sync + 'static {
47 const LEVEL: AccessLevel;
48}
49
50#[derive(Debug)]
52pub struct Public;
53#[derive(Debug)]
55pub struct MaybeAuthenticated;
56#[derive(Debug)]
58pub struct Authenticated;
59#[derive(Debug)]
61pub struct Fresh;
62
63impl Access for Public {
64 const LEVEL: AccessLevel = AccessLevel::Public;
65}
66impl Access for MaybeAuthenticated {
67 const LEVEL: AccessLevel = AccessLevel::Optional;
68}
69impl Access for Authenticated {
70 const LEVEL: AccessLevel = AccessLevel::Required;
71}
72impl Access for Fresh {
73 const LEVEL: AccessLevel = AccessLevel::Fresh;
74}
75
76pub trait Endpoint<D: Adapter>: Send + Sync + 'static {
81 const METHOD: Method;
82 const PATH: &'static str;
83 type Access: Access;
84 type Input: DeserializeOwned + Send + 'static;
85 type Output: Serialize + Send + 'static;
86
87 fn call(
88 &self,
89 ctx: Ctx<D, Self::Access>,
90 input: Self::Input,
91 ) -> impl Future<Output = Result<Self::Output, AuthError>> + Send;
92}
93
94#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize, Serialize)]
96pub struct Empty {}
97
98#[derive(Clone, Debug)]
100pub struct RequestInfo {
101 pub method: Method,
102 pub path: String,
103 pub params: Vec<(String, String)>,
104 pub query: Option<String>,
105 pub headers: HeaderMap,
106 pub ip: Option<String>,
107 pub user_agent: Option<String>,
108}
109
110impl RequestInfo {
111 pub(crate) fn synthetic(method: Method, path: &str, headers: HeaderMap) -> Self {
112 let user_agent = header_str(&headers, http::header::USER_AGENT);
113 Self {
114 method,
115 path: path.to_owned(),
116 params: Vec::new(),
117 query: None,
118 headers,
119 ip: None,
120 user_agent,
121 }
122 }
123}
124
125pub(crate) fn header_str(headers: &HeaderMap, name: HeaderName) -> Option<String> {
126 headers
127 .get(name)
128 .and_then(|v| v.to_str().ok())
129 .map(str::to_owned)
130}
131
132pub(crate) struct PendingEvent {
133 type_id: TypeId,
134 event: Arc<dyn Any + Send + Sync>,
135}
136
137#[derive(Default)]
139pub(crate) struct Effects {
140 pub cookies: Vec<SetCookie>,
141 pub redirect: Option<String>,
142 pub headers: Vec<(HeaderName, HeaderValue)>,
143 pub events: Vec<PendingEvent>,
144}
145
146pub(crate) type ErasedBefore<D> = Arc<
147 dyn Fn(
148 HookCtx<D>,
149 Box<dyn Any + Send>,
150 ) -> BoxFuture<'static, Result<Before<Box<dyn Any + Send>>, AuthError>>
151 + Send
152 + Sync,
153>;
154pub(crate) type ErasedAfter<D> = Arc<
155 dyn Fn(
156 HookCtx<D>,
157 Box<dyn Any + Send>,
158 ) -> BoxFuture<'static, Result<After<Box<dyn Any + Send>>, AuthError>>
159 + Send
160 + Sync,
161>;
162pub(crate) type ErasedGate<D> = Arc<
163 dyn Fn(HookCtx<D>, SignInAttempt) -> BoxFuture<'static, Result<Gate, AuthError>> + Send + Sync,
164>;
165
166pub(crate) struct OwnedGate<D> {
168 pub owner: &'static str,
169 pub gate: ErasedGate<D>,
170}
171pub(crate) type ErasedResponseHook<D> = Arc<dyn Fn(&Ctx<D>, &mut Response) + Send + Sync>;
172pub(crate) type ErasedEventHandler<D> = Arc<
173 dyn Fn(Arc<dyn Any + Send + Sync>, Ctx<D>) -> BoxFuture<'static, Result<(), AuthError>>
174 + Send
175 + Sync,
176>;
177
178pub(crate) struct EndpointHooks<D> {
179 pub before: Vec<ErasedBefore<D>>,
180 pub after: Vec<ErasedAfter<D>>,
181}
182
183impl<D> Default for EndpointHooks<D> {
184 fn default() -> Self {
185 Self {
186 before: Vec::new(),
187 after: Vec::new(),
188 }
189 }
190}
191
192pub enum Before<I> {
194 Continue(I),
196 Respond(Response),
198}
199
200pub enum After<O> {
202 Continue(O),
203 Respond(Response),
204}
205
206#[derive(Debug)]
208pub enum Gate {
209 Allow,
210 Deny(AuthError),
211 Challenge(serde_json::Value),
215}
216
217#[derive(Clone, Debug)]
219pub struct SignInAttempt {
220 pub user: UserView,
221 pub method: Cow<'static, str>,
224 pub remember_me: bool,
225}
226
227pub type HookCtx<D> = Ctx<D, MaybeAuthenticated>;
229
230#[derive(Clone, Debug)]
232pub enum Resolved {
233 Token(String),
235 User(Id),
237}
238
239pub trait SessionResolver<D: Adapter>: Send + Sync + 'static {
241 fn resolve(
242 &self,
243 ctx: &Ctx<D>,
244 headers: &HeaderMap,
245 ) -> impl Future<Output = Result<Option<Resolved>, AuthError>> + Send;
246}
247
248pub(crate) trait ErasedResolver<D>: Send + Sync {
249 fn resolve<'a>(
250 &'a self,
251 ctx: &'a Ctx<D>,
252 headers: &'a HeaderMap,
253 ) -> BoxFuture<'a, Result<Option<Resolved>, AuthError>>;
254}
255
256impl<D: Adapter, R: SessionResolver<D>> ErasedResolver<D> for R {
257 fn resolve<'a>(
258 &'a self,
259 ctx: &'a Ctx<D>,
260 headers: &'a HeaderMap,
261 ) -> BoxFuture<'a, Result<Option<Resolved>, AuthError>> {
262 Box::pin(SessionResolver::resolve(self, ctx, headers))
263 }
264}
265
266pub(crate) type MethodTable<D> = Vec<(Method, Arc<dyn ErasedEndpoint<D>>)>;
267
268pub(crate) struct Shared<D> {
270 pub db: D,
271 pub schema: Schema,
272 pub keys: Keys,
273 pub config: CoreConfig,
274 pub passwords: Passwords,
275 pub mailer: Option<Arc<dyn DynMailer>>,
276 pub plugins: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
277 pub hooks: HashMap<TypeId, EndpointHooks<D>>,
278 pub gates: Vec<OwnedGate<D>>,
279 pub resolvers: Vec<Arc<dyn ErasedResolver<D>>>,
280 pub response_hooks: Vec<ErasedResponseHook<D>>,
281 pub events: HashMap<TypeId, Vec<ErasedEventHandler<D>>>,
282 pub router: matchit::Router<MethodTable<D>>,
283 pub rate_limiter: RateLimiter,
284 pub cache_fingerprint: u64,
285}
286
287pub struct Ctx<D, A = Public> {
289 pub(crate) shared: Arc<Shared<D>>,
290 pub(crate) within: Option<Arc<D>>,
292 pub(crate) request: Arc<RequestInfo>,
293 pub(crate) session: Option<Arc<SessionView>>,
294 pub(crate) effects: Arc<Mutex<Effects>>,
295 _access: PhantomData<fn() -> A>,
296}
297
298impl<D, A> Clone for Ctx<D, A> {
299 fn clone(&self) -> Self {
300 Self {
301 shared: self.shared.clone(),
302 within: self.within.clone(),
303 request: self.request.clone(),
304 session: self.session.clone(),
305 effects: self.effects.clone(),
306 _access: PhantomData,
307 }
308 }
309}
310
311impl<D, A> std::fmt::Debug for Ctx<D, A> {
312 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313 write!(f, "Ctx({} {})", self.request.method, self.request.path)
314 }
315}
316
317impl<D: Adapter, A> Ctx<D, A> {
318 pub(crate) fn new(
319 shared: Arc<Shared<D>>,
320 within: Option<Arc<D>>,
321 request: Arc<RequestInfo>,
322 session: Option<Arc<SessionView>>,
323 effects: Arc<Mutex<Effects>>,
324 ) -> Self {
325 Self {
326 shared,
327 within,
328 request,
329 session,
330 effects,
331 _access: PhantomData,
332 }
333 }
334
335 pub(crate) fn retype<B>(&self) -> Ctx<D, B> {
336 Ctx::new(
337 self.shared.clone(),
338 self.within.clone(),
339 self.request.clone(),
340 self.session.clone(),
341 self.effects.clone(),
342 )
343 }
344
345 pub fn db(&self) -> Db<'_, D> {
347 Db::new(self.adapter(), &self.shared.schema)
348 }
349
350 pub fn db_on<'t, Q: Queries>(&'t self, queries: &'t Q) -> Db<'t, Q> {
352 Db::new(queries, &self.shared.schema)
353 }
354
355 pub fn adapter(&self) -> &D {
358 self.within.as_deref().unwrap_or(&self.shared.db)
359 }
360
361 pub fn schema(&self) -> &Schema {
362 &self.shared.schema
363 }
364
365 pub fn keys(&self) -> &Keys {
366 &self.shared.keys
367 }
368
369 pub fn config(&self) -> &CoreConfig {
370 &self.shared.config
371 }
372
373 pub fn passwords(&self) -> &Passwords {
374 &self.shared.passwords
375 }
376
377 pub fn now(&self) -> OffsetDateTime {
378 OffsetDateTime::now_utc()
379 }
380
381 pub fn new_id(&self) -> Result<Id, AuthError> {
384 self.shared.config.ids.generate()
385 }
386
387 pub fn request(&self) -> &RequestInfo {
388 &self.request
389 }
390
391 pub fn headers(&self) -> &HeaderMap {
392 &self.request.headers
393 }
394
395 pub fn ip(&self) -> Option<&str> {
396 self.request.ip.as_deref()
397 }
398
399 pub fn user_agent(&self) -> Option<&str> {
400 self.request.user_agent.as_deref()
401 }
402
403 pub fn param(&self, name: &str) -> Option<&str> {
405 self.request
406 .params
407 .iter()
408 .find(|(k, _)| k == name)
409 .map(|(_, v)| v.as_str())
410 }
411
412 pub fn plugin<P: Plugin>(&self) -> &P {
415 self.try_plugin::<P>().unwrap_or_else(|| {
416 panic!(
417 "plugin `{}` is not registered; list it in `Requires`",
418 P::ID
419 )
420 })
421 }
422
423 pub fn try_plugin<P: Plugin>(&self) -> Option<&P> {
424 self.shared
425 .plugins
426 .get(&TypeId::of::<P>())
427 .and_then(|p| p.downcast_ref::<P>())
428 }
429
430 pub fn emit<E: Event>(&self, event: E) {
432 self.effects.lock().unwrap().events.push(PendingEvent {
433 type_id: TypeId::of::<E>(),
434 event: Arc::new(event),
435 });
436 }
437
438 pub fn set_cookie(&self, cookie: SetCookie) {
439 let mut effects = self.effects.lock().unwrap();
440 effects.cookies.retain(|c| c.name != cookie.name);
441 effects.cookies.push(cookie);
442 }
443
444 pub fn cookie(&self, name: &str) -> Option<&str> {
445 cookies::read(&self.request.headers, name)
446 }
447
448 pub fn set_signed_cookie(&self, name: &str, value: &str, max_age: Option<Duration>) {
450 let name = self.shared.config.cookie_name(name);
451 let value = self.shared.keys.sign(SignPurpose::Cookie, value);
452 self.set_cookie(SetCookie::new(name, value, max_age));
453 }
454
455 pub fn signed_cookie(&self, name: &str) -> Option<String> {
457 let raw = self.cookie(&self.shared.config.cookie_name(name))?;
458 self.shared
459 .keys
460 .verify(SignPurpose::Cookie, raw)
461 .map(str::to_owned)
462 }
463
464 pub fn delete_cookie(&self, name: &str) {
465 self.set_cookie(SetCookie::delete(self.shared.config.cookie_name(name)));
466 }
467
468 pub fn redirect(&self, url: impl Into<String>) {
470 self.effects.lock().unwrap().redirect = Some(url.into());
471 }
472
473 pub fn set_header(&self, name: HeaderName, value: HeaderValue) {
474 self.effects.lock().unwrap().headers.push((name, value));
475 }
476
477 pub fn internal(&self) -> Internal<'_, D, A> {
479 Internal::new(self)
480 }
481
482 pub(crate) fn mailer(&self) -> Option<&Arc<dyn DynMailer>> {
483 self.shared.mailer.as_ref()
484 }
485}
486
487impl<D: Adapter> Ctx<D, MaybeAuthenticated> {
488 pub fn session(&self) -> Option<&SessionView> {
489 self.session.as_deref()
490 }
491}
492
493impl<D: Adapter> Ctx<D, Authenticated> {
494 pub fn session(&self) -> &SessionView {
495 self.session
496 .as_deref()
497 .expect("Authenticated endpoints only run with a session")
498 }
499}
500
501impl<D: Adapter> Ctx<D, Fresh> {
502 pub fn session(&self) -> &SessionView {
503 self.session
504 .as_deref()
505 .expect("Fresh endpoints only run with a session")
506 }
507}
508
509pub(crate) enum Outcome<O> {
510 Output(O),
511 Response(Response),
512}
513
514pub(crate) struct Executed<O> {
515 pub result: Result<Outcome<O>, AuthError>,
516 pub effects: Effects,
517}
518
519pub(crate) async fn execute<D: Adapter, E: Endpoint<D>>(
522 shared: &Arc<Shared<D>>,
523 within: Option<Arc<D>>,
524 endpoint: &E,
525 request: Arc<RequestInfo>,
526 input: E::Input,
527) -> Executed<E::Output> {
528 let effects = Arc::new(Mutex::new(Effects::default()));
529 let result = run::<D, E>(shared, within, endpoint, request, input, &effects).await;
530 let effects = std::mem::take(&mut *effects.lock().unwrap());
531 Executed { result, effects }
532}
533
534async fn run<D: Adapter, E: Endpoint<D>>(
535 shared: &Arc<Shared<D>>,
536 within: Option<Arc<D>>,
537 endpoint: &E,
538 request: Arc<RequestInfo>,
539 input: E::Input,
540 effects: &Arc<Mutex<Effects>>,
541) -> Result<Outcome<E::Output>, AuthError> {
542 let level = <E::Access as Access>::LEVEL;
543 let session = match level {
544 AccessLevel::Public => None,
545 _ => crate::session::resolve(shared, within.as_ref(), &request, effects)
546 .await?
547 .map(Arc::new),
548 };
549 match (level, &session) {
550 (AccessLevel::Required | AccessLevel::Fresh, None) => return Err(AuthError::unauthorized()),
551 (AccessLevel::Fresh, Some(s)) if !shared.config.is_fresh(&s.session) => {
552 return Err(AuthError::not_fresh());
553 }
554 _ => {}
555 }
556
557 let ctx: Ctx<D, E::Access> =
558 Ctx::new(shared.clone(), within, request, session, effects.clone());
559 let hooks = shared.hooks.get(&TypeId::of::<E>());
560 let mut input = input;
561 for before in hooks.map(|h| h.before.as_slice()).unwrap_or_default() {
562 match before(ctx.retype(), Box::new(input)).await? {
563 Before::Continue(next) => {
564 input = *next
565 .downcast::<E::Input>()
566 .expect("hook keeps the input type")
567 }
568 Before::Respond(response) => return Ok(Outcome::Response(response)),
569 }
570 }
571 let mut output = endpoint.call(ctx.clone(), input).await?;
572 for after in hooks.map(|h| h.after.as_slice()).unwrap_or_default() {
573 match after(ctx.retype(), Box::new(output)).await? {
574 After::Continue(next) => {
575 output = *next
576 .downcast::<E::Output>()
577 .expect("hook keeps the output type")
578 }
579 After::Respond(response) => return Ok(Outcome::Response(response)),
580 }
581 }
582 Ok(Outcome::Output(output))
583}
584
585pub(crate) async fn dispatch_events<D: Adapter>(
586 shared: &Arc<Shared<D>>,
587 events: Vec<PendingEvent>,
588) {
589 for pending in events {
590 let Some(handlers) = shared.events.get(&pending.type_id) else {
591 continue;
592 };
593 for handler in handlers {
594 let request = Arc::new(RequestInfo::synthetic(
595 Method::POST,
596 "/event",
597 HeaderMap::new(),
598 ));
599 let ctx = Ctx::new(shared.clone(), None, request, None, Arc::default());
600 if let Err(err) = handler(pending.event.clone(), ctx).await {
601 tracing::error!(error = %err, "fastauth event handler failed");
602 }
603 }
604 }
605}
606
607pub(crate) trait ErasedEndpoint<D>: Send + Sync {
608 fn handle<'a>(
609 &'a self,
610 shared: &'a Arc<Shared<D>>,
611 request: Arc<RequestInfo>,
612 body: Bytes,
613 ) -> BoxFuture<'a, Response>;
614}
615
616pub(crate) struct Erased<E>(pub E);
617
618impl<D: Adapter, E: Endpoint<D>> ErasedEndpoint<D> for Erased<E> {
619 fn handle<'a>(
620 &'a self,
621 shared: &'a Arc<Shared<D>>,
622 request: Arc<RequestInfo>,
623 body: Bytes,
624 ) -> BoxFuture<'a, Response> {
625 Box::pin(async move {
626 let input = match decode_input::<E::Input>(&request, &body) {
627 Ok(input) => input,
628 Err(err) => return err.into_response(),
629 };
630 let mut executed = execute(shared, None, &self.0, request.clone(), input).await;
631 if executed.result.is_ok() {
632 let events = std::mem::take(&mut executed.effects.events);
633 dispatch_events(shared, events).await;
634 }
635 let result = executed.result.and_then(|outcome| match outcome {
636 Outcome::Output(output) => serde_json::to_vec(&output)
637 .map(|b| Outcome::Output(Bytes::from(b)))
638 .map_err(AuthError::internal),
639 Outcome::Response(response) => Ok(Outcome::Response(response)),
640 });
641 let mut response = into_response(&shared.config, result, executed.effects);
642 if !shared.response_hooks.is_empty() {
643 let ctx: Ctx<D> = Ctx::new(shared.clone(), None, request, None, Arc::default());
644 for hook in &shared.response_hooks {
645 hook(&ctx, &mut response);
646 }
647 }
648 response
649 })
650 }
651}
652
653fn decode_input<I: DeserializeOwned>(request: &RequestInfo, body: &[u8]) -> Result<I, AuthError> {
654 let invalid = |e: &dyn std::fmt::Display| {
655 AuthError::bad_request(crate::error::codes::INVALID_BODY, e.to_string())
656 };
657 if request.method == Method::GET || request.method == Method::HEAD {
658 return serde_urlencoded::from_str(request.query.as_deref().unwrap_or(""))
659 .map_err(|e| invalid(&e));
660 }
661 if body.iter().all(u8::is_ascii_whitespace) {
662 return serde_json::from_slice(b"{}")
663 .or_else(|_| serde_json::from_slice(b"null"))
664 .map_err(|e| invalid(&e));
665 }
666 serde_json::from_slice(body).map_err(|e| invalid(&e))
667}
668
669pub(crate) fn into_response(
670 config: &CoreConfig,
671 result: Result<Outcome<Bytes>, AuthError>,
672 effects: Effects,
673) -> Response {
674 let mut response = match result {
675 Ok(Outcome::Response(response)) => response,
676 Ok(Outcome::Output(_)) if effects.redirect.is_some() => {
677 let mut response = Response::new(Bytes::new());
678 *response.status_mut() = StatusCode::FOUND;
679 if let Ok(location) = HeaderValue::from_str(effects.redirect.as_deref().unwrap_or("/"))
680 {
681 response.headers_mut().insert(LOCATION, location);
682 }
683 response
684 }
685 Ok(Outcome::Output(body)) => {
686 let mut response = Response::new(body);
687 response
688 .headers_mut()
689 .insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
690 response
691 }
692 Err(err) => err.into_response(),
693 };
694 for cookie in &effects.cookies {
695 if let Ok(value) = HeaderValue::from_str(&cookie.to_header(config)) {
696 response.headers_mut().append(SET_COOKIE, value);
697 }
698 }
699 for (name, value) in effects.headers {
700 response.headers_mut().append(name, value);
701 }
702 response
703}