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 ErasedEventHandler<D> = Arc<
172 dyn Fn(Arc<dyn Any + Send + Sync>, Ctx<D>) -> BoxFuture<'static, Result<(), AuthError>>
173 + Send
174 + Sync,
175>;
176
177pub(crate) struct EndpointHooks<D> {
178 pub before: Vec<ErasedBefore<D>>,
179 pub after: Vec<ErasedAfter<D>>,
180}
181
182impl<D> Default for EndpointHooks<D> {
183 fn default() -> Self {
184 Self {
185 before: Vec::new(),
186 after: Vec::new(),
187 }
188 }
189}
190
191pub enum Before<I> {
193 Continue(I),
195 Respond(Response),
197}
198
199pub enum After<O> {
201 Continue(O),
202 Respond(Response),
203}
204
205#[derive(Debug)]
207pub enum Gate {
208 Allow,
209 Deny(AuthError),
210 Challenge(serde_json::Value),
214}
215
216#[derive(Clone, Debug)]
218pub struct SignInAttempt {
219 pub user: UserView,
220 pub method: Cow<'static, str>,
223 pub remember_me: bool,
224}
225
226pub type HookCtx<D> = Ctx<D, MaybeAuthenticated>;
228
229#[derive(Clone, Debug)]
231pub enum Resolved {
232 Token(String),
234 User(Id),
236}
237
238pub trait SessionResolver<D: Adapter>: Send + Sync + 'static {
240 fn resolve(
241 &self,
242 ctx: &Ctx<D>,
243 headers: &HeaderMap,
244 ) -> impl Future<Output = Result<Option<Resolved>, AuthError>> + Send;
245}
246
247pub(crate) trait ErasedResolver<D>: Send + Sync {
248 fn resolve<'a>(
249 &'a self,
250 ctx: &'a Ctx<D>,
251 headers: &'a HeaderMap,
252 ) -> BoxFuture<'a, Result<Option<Resolved>, AuthError>>;
253}
254
255impl<D: Adapter, R: SessionResolver<D>> ErasedResolver<D> for R {
256 fn resolve<'a>(
257 &'a self,
258 ctx: &'a Ctx<D>,
259 headers: &'a HeaderMap,
260 ) -> BoxFuture<'a, Result<Option<Resolved>, AuthError>> {
261 Box::pin(SessionResolver::resolve(self, ctx, headers))
262 }
263}
264
265pub(crate) type MethodTable<D> = Vec<(Method, Arc<dyn ErasedEndpoint<D>>)>;
266
267pub(crate) struct Shared<D> {
269 pub db: D,
270 pub schema: Schema,
271 pub keys: Keys,
272 pub config: CoreConfig,
273 pub passwords: Passwords,
274 pub mailer: Option<Arc<dyn DynMailer>>,
275 pub plugins: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
276 pub hooks: HashMap<TypeId, EndpointHooks<D>>,
277 pub gates: Vec<OwnedGate<D>>,
278 pub resolvers: Vec<Arc<dyn ErasedResolver<D>>>,
279 pub events: HashMap<TypeId, Vec<ErasedEventHandler<D>>>,
280 pub router: matchit::Router<MethodTable<D>>,
281 pub rate_limiter: RateLimiter,
282 pub cache_fingerprint: u64,
283}
284
285pub struct Ctx<D, A = Public> {
287 pub(crate) shared: Arc<Shared<D>>,
288 pub(crate) within: Option<Arc<D>>,
290 pub(crate) request: Arc<RequestInfo>,
291 pub(crate) session: Option<Arc<SessionView>>,
292 pub(crate) effects: Arc<Mutex<Effects>>,
293 _access: PhantomData<fn() -> A>,
294}
295
296impl<D, A> Clone for Ctx<D, A> {
297 fn clone(&self) -> Self {
298 Self {
299 shared: self.shared.clone(),
300 within: self.within.clone(),
301 request: self.request.clone(),
302 session: self.session.clone(),
303 effects: self.effects.clone(),
304 _access: PhantomData,
305 }
306 }
307}
308
309impl<D, A> std::fmt::Debug for Ctx<D, A> {
310 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311 write!(f, "Ctx({} {})", self.request.method, self.request.path)
312 }
313}
314
315impl<D: Adapter, A> Ctx<D, A> {
316 pub(crate) fn new(
317 shared: Arc<Shared<D>>,
318 within: Option<Arc<D>>,
319 request: Arc<RequestInfo>,
320 session: Option<Arc<SessionView>>,
321 effects: Arc<Mutex<Effects>>,
322 ) -> Self {
323 Self {
324 shared,
325 within,
326 request,
327 session,
328 effects,
329 _access: PhantomData,
330 }
331 }
332
333 pub(crate) fn retype<B>(&self) -> Ctx<D, B> {
334 Ctx::new(
335 self.shared.clone(),
336 self.within.clone(),
337 self.request.clone(),
338 self.session.clone(),
339 self.effects.clone(),
340 )
341 }
342
343 pub fn db(&self) -> Db<'_, D> {
345 Db::new(self.adapter(), &self.shared.schema)
346 }
347
348 pub fn db_on<'t, Q: Queries>(&'t self, queries: &'t Q) -> Db<'t, Q> {
350 Db::new(queries, &self.shared.schema)
351 }
352
353 pub fn adapter(&self) -> &D {
356 self.within.as_deref().unwrap_or(&self.shared.db)
357 }
358
359 pub fn schema(&self) -> &Schema {
360 &self.shared.schema
361 }
362
363 pub fn keys(&self) -> &Keys {
364 &self.shared.keys
365 }
366
367 pub fn config(&self) -> &CoreConfig {
368 &self.shared.config
369 }
370
371 pub fn passwords(&self) -> &Passwords {
372 &self.shared.passwords
373 }
374
375 pub fn now(&self) -> OffsetDateTime {
376 OffsetDateTime::now_utc()
377 }
378
379 pub fn new_id(&self) -> Result<Id, AuthError> {
382 self.shared.config.ids.generate()
383 }
384
385 pub fn request(&self) -> &RequestInfo {
386 &self.request
387 }
388
389 pub fn headers(&self) -> &HeaderMap {
390 &self.request.headers
391 }
392
393 pub fn ip(&self) -> Option<&str> {
394 self.request.ip.as_deref()
395 }
396
397 pub fn user_agent(&self) -> Option<&str> {
398 self.request.user_agent.as_deref()
399 }
400
401 pub fn param(&self, name: &str) -> Option<&str> {
403 self.request
404 .params
405 .iter()
406 .find(|(k, _)| k == name)
407 .map(|(_, v)| v.as_str())
408 }
409
410 pub fn plugin<P: Plugin>(&self) -> &P {
413 self.try_plugin::<P>().unwrap_or_else(|| {
414 panic!(
415 "plugin `{}` is not registered; list it in `Requires`",
416 P::ID
417 )
418 })
419 }
420
421 pub fn try_plugin<P: Plugin>(&self) -> Option<&P> {
422 self.shared
423 .plugins
424 .get(&TypeId::of::<P>())
425 .and_then(|p| p.downcast_ref::<P>())
426 }
427
428 pub fn emit<E: Event>(&self, event: E) {
430 self.effects.lock().unwrap().events.push(PendingEvent {
431 type_id: TypeId::of::<E>(),
432 event: Arc::new(event),
433 });
434 }
435
436 pub fn set_cookie(&self, cookie: SetCookie) {
437 let mut effects = self.effects.lock().unwrap();
438 effects.cookies.retain(|c| c.name != cookie.name);
439 effects.cookies.push(cookie);
440 }
441
442 pub fn cookie(&self, name: &str) -> Option<&str> {
443 cookies::read(&self.request.headers, name)
444 }
445
446 pub fn set_signed_cookie(&self, name: &str, value: &str, max_age: Option<Duration>) {
448 let name = self.shared.config.cookie_name(name);
449 let value = self.shared.keys.sign(SignPurpose::Cookie, value);
450 self.set_cookie(SetCookie::new(name, value, max_age));
451 }
452
453 pub fn signed_cookie(&self, name: &str) -> Option<String> {
455 let raw = self.cookie(&self.shared.config.cookie_name(name))?;
456 self.shared
457 .keys
458 .verify(SignPurpose::Cookie, raw)
459 .map(str::to_owned)
460 }
461
462 pub fn delete_cookie(&self, name: &str) {
463 self.set_cookie(SetCookie::delete(self.shared.config.cookie_name(name)));
464 }
465
466 pub fn redirect(&self, url: impl Into<String>) {
468 self.effects.lock().unwrap().redirect = Some(url.into());
469 }
470
471 pub fn set_header(&self, name: HeaderName, value: HeaderValue) {
472 self.effects.lock().unwrap().headers.push((name, value));
473 }
474
475 pub fn internal(&self) -> Internal<'_, D, A> {
477 Internal::new(self)
478 }
479
480 pub(crate) fn mailer(&self) -> Option<&Arc<dyn DynMailer>> {
481 self.shared.mailer.as_ref()
482 }
483}
484
485impl<D: Adapter> Ctx<D, MaybeAuthenticated> {
486 pub fn session(&self) -> Option<&SessionView> {
487 self.session.as_deref()
488 }
489}
490
491impl<D: Adapter> Ctx<D, Authenticated> {
492 pub fn session(&self) -> &SessionView {
493 self.session
494 .as_deref()
495 .expect("Authenticated endpoints only run with a session")
496 }
497}
498
499impl<D: Adapter> Ctx<D, Fresh> {
500 pub fn session(&self) -> &SessionView {
501 self.session
502 .as_deref()
503 .expect("Fresh endpoints only run with a session")
504 }
505}
506
507pub(crate) enum Outcome<O> {
508 Output(O),
509 Response(Response),
510}
511
512pub(crate) struct Executed<O> {
513 pub result: Result<Outcome<O>, AuthError>,
514 pub effects: Effects,
515}
516
517pub(crate) async fn execute<D: Adapter, E: Endpoint<D>>(
520 shared: &Arc<Shared<D>>,
521 within: Option<Arc<D>>,
522 endpoint: &E,
523 request: Arc<RequestInfo>,
524 input: E::Input,
525) -> Executed<E::Output> {
526 let effects = Arc::new(Mutex::new(Effects::default()));
527 let result = run::<D, E>(shared, within, endpoint, request, input, &effects).await;
528 let effects = std::mem::take(&mut *effects.lock().unwrap());
529 Executed { result, effects }
530}
531
532async fn run<D: Adapter, E: Endpoint<D>>(
533 shared: &Arc<Shared<D>>,
534 within: Option<Arc<D>>,
535 endpoint: &E,
536 request: Arc<RequestInfo>,
537 input: E::Input,
538 effects: &Arc<Mutex<Effects>>,
539) -> Result<Outcome<E::Output>, AuthError> {
540 let level = <E::Access as Access>::LEVEL;
541 let session = match level {
542 AccessLevel::Public => None,
543 _ => crate::session::resolve(shared, within.as_ref(), &request, effects)
544 .await?
545 .map(Arc::new),
546 };
547 match (level, &session) {
548 (AccessLevel::Required | AccessLevel::Fresh, None) => return Err(AuthError::unauthorized()),
549 (AccessLevel::Fresh, Some(s)) if !shared.config.is_fresh(&s.session) => {
550 return Err(AuthError::not_fresh());
551 }
552 _ => {}
553 }
554
555 let ctx: Ctx<D, E::Access> =
556 Ctx::new(shared.clone(), within, request, session, effects.clone());
557 let hooks = shared.hooks.get(&TypeId::of::<E>());
558 let mut input = input;
559 for before in hooks.map(|h| h.before.as_slice()).unwrap_or_default() {
560 match before(ctx.retype(), Box::new(input)).await? {
561 Before::Continue(next) => {
562 input = *next
563 .downcast::<E::Input>()
564 .expect("hook keeps the input type")
565 }
566 Before::Respond(response) => return Ok(Outcome::Response(response)),
567 }
568 }
569 let mut output = endpoint.call(ctx.clone(), input).await?;
570 for after in hooks.map(|h| h.after.as_slice()).unwrap_or_default() {
571 match after(ctx.retype(), Box::new(output)).await? {
572 After::Continue(next) => {
573 output = *next
574 .downcast::<E::Output>()
575 .expect("hook keeps the output type")
576 }
577 After::Respond(response) => return Ok(Outcome::Response(response)),
578 }
579 }
580 Ok(Outcome::Output(output))
581}
582
583pub(crate) async fn dispatch_events<D: Adapter>(
584 shared: &Arc<Shared<D>>,
585 events: Vec<PendingEvent>,
586) {
587 for pending in events {
588 let Some(handlers) = shared.events.get(&pending.type_id) else {
589 continue;
590 };
591 for handler in handlers {
592 let request = Arc::new(RequestInfo::synthetic(
593 Method::POST,
594 "/event",
595 HeaderMap::new(),
596 ));
597 let ctx = Ctx::new(shared.clone(), None, request, None, Arc::default());
598 if let Err(err) = handler(pending.event.clone(), ctx).await {
599 tracing::error!(error = %err, "fastauth event handler failed");
600 }
601 }
602 }
603}
604
605pub(crate) trait ErasedEndpoint<D>: Send + Sync {
606 fn handle<'a>(
607 &'a self,
608 shared: &'a Arc<Shared<D>>,
609 request: Arc<RequestInfo>,
610 body: Bytes,
611 ) -> BoxFuture<'a, Response>;
612}
613
614pub(crate) struct Erased<E>(pub E);
615
616impl<D: Adapter, E: Endpoint<D>> ErasedEndpoint<D> for Erased<E> {
617 fn handle<'a>(
618 &'a self,
619 shared: &'a Arc<Shared<D>>,
620 request: Arc<RequestInfo>,
621 body: Bytes,
622 ) -> BoxFuture<'a, Response> {
623 Box::pin(async move {
624 let input = match decode_input::<E::Input>(&request, &body) {
625 Ok(input) => input,
626 Err(err) => return err.into_response(),
627 };
628 let mut executed = execute(shared, None, &self.0, request, input).await;
629 if executed.result.is_ok() {
630 let events = std::mem::take(&mut executed.effects.events);
631 dispatch_events(shared, events).await;
632 }
633 let result = executed.result.and_then(|outcome| match outcome {
634 Outcome::Output(output) => serde_json::to_vec(&output)
635 .map(|b| Outcome::Output(Bytes::from(b)))
636 .map_err(AuthError::internal),
637 Outcome::Response(response) => Ok(Outcome::Response(response)),
638 });
639 into_response(&shared.config, result, executed.effects)
640 })
641 }
642}
643
644fn decode_input<I: DeserializeOwned>(request: &RequestInfo, body: &[u8]) -> Result<I, AuthError> {
645 let invalid = |e: &dyn std::fmt::Display| {
646 AuthError::bad_request(crate::error::codes::INVALID_BODY, e.to_string())
647 };
648 if request.method == Method::GET || request.method == Method::HEAD {
649 return serde_urlencoded::from_str(request.query.as_deref().unwrap_or(""))
650 .map_err(|e| invalid(&e));
651 }
652 if body.iter().all(u8::is_ascii_whitespace) {
653 return serde_json::from_slice(b"{}")
654 .or_else(|_| serde_json::from_slice(b"null"))
655 .map_err(|e| invalid(&e));
656 }
657 serde_json::from_slice(body).map_err(|e| invalid(&e))
658}
659
660pub(crate) fn into_response(
661 config: &CoreConfig,
662 result: Result<Outcome<Bytes>, AuthError>,
663 effects: Effects,
664) -> Response {
665 let mut response = match result {
666 Ok(Outcome::Response(response)) => response,
667 Ok(Outcome::Output(_)) if effects.redirect.is_some() => {
668 let mut response = Response::new(Bytes::new());
669 *response.status_mut() = StatusCode::FOUND;
670 if let Ok(location) = HeaderValue::from_str(effects.redirect.as_deref().unwrap_or("/"))
671 {
672 response.headers_mut().insert(LOCATION, location);
673 }
674 response
675 }
676 Ok(Outcome::Output(body)) => {
677 let mut response = Response::new(body);
678 response
679 .headers_mut()
680 .insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
681 response
682 }
683 Err(err) => err.into_response(),
684 };
685 for cookie in &effects.cookies {
686 if let Ok(value) = HeaderValue::from_str(&cookie.to_header(config)) {
687 response.headers_mut().append(SET_COOKIE, value);
688 }
689 }
690 for (name, value) in effects.headers {
691 response.headers_mut().append(name, value);
692 }
693 response
694}