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