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, codes};
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)]
62pub struct Fresh;
63
64impl Access for Public {
65 const LEVEL: AccessLevel = AccessLevel::Public;
66}
67impl Access for MaybeAuthenticated {
68 const LEVEL: AccessLevel = AccessLevel::Optional;
69}
70impl Access for Authenticated {
71 const LEVEL: AccessLevel = AccessLevel::Required;
72}
73impl Access for Fresh {
74 const LEVEL: AccessLevel = AccessLevel::Fresh;
75}
76
77pub trait Endpoint<D: Adapter>: Send + Sync + 'static {
82 const METHOD: Method;
83 const PATH: &'static str;
84 type Access: Access;
85 type Input: DeserializeOwned + Send + 'static;
86 type Output: Serialize + Send + 'static;
87
88 fn call(
89 &self,
90 ctx: Ctx<D, Self::Access>,
91 input: Self::Input,
92 ) -> impl Future<Output = Result<Self::Output, AuthError>> + Send;
93}
94
95#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize, Serialize)]
97pub struct Empty {}
98
99#[derive(Clone, Debug)]
101pub struct RequestInfo {
102 pub method: Method,
103 pub path: String,
104 pub params: Vec<(String, String)>,
105 pub query: Option<String>,
106 pub headers: HeaderMap,
107 pub ip: Option<String>,
108 pub user_agent: Option<String>,
109}
110
111impl RequestInfo {
112 pub(crate) fn synthetic(method: Method, path: &str, headers: HeaderMap) -> Self {
113 let user_agent = header_str(&headers, http::header::USER_AGENT);
114 Self {
115 method,
116 path: path.to_owned(),
117 params: Vec::new(),
118 query: None,
119 headers,
120 ip: None,
121 user_agent,
122 }
123 }
124}
125
126pub(crate) fn header_str(headers: &HeaderMap, name: HeaderName) -> Option<String> {
127 headers
128 .get(name)
129 .and_then(|v| v.to_str().ok())
130 .map(str::to_owned)
131}
132
133pub(crate) struct PendingEvent {
134 type_id: TypeId,
135 event: Arc<dyn Any + Send + Sync>,
136}
137
138#[derive(Default)]
140pub(crate) struct Effects {
141 pub cookies: Vec<SetCookie>,
142 pub redirect: Option<String>,
143 pub headers: Vec<(HeaderName, HeaderValue)>,
144 pub events: Vec<PendingEvent>,
145}
146
147pub(crate) type ErasedBefore<D> = Arc<
148 dyn Fn(
149 HookCtx<D>,
150 Box<dyn Any + Send>,
151 ) -> BoxFuture<'static, Result<Before<Box<dyn Any + Send>>, AuthError>>
152 + Send
153 + Sync,
154>;
155pub(crate) type ErasedAfter<D> = Arc<
156 dyn Fn(
157 HookCtx<D>,
158 Box<dyn Any + Send>,
159 ) -> BoxFuture<'static, Result<After<Box<dyn Any + Send>>, AuthError>>
160 + Send
161 + Sync,
162>;
163pub(crate) type ErasedGate<D> = Arc<
164 dyn Fn(HookCtx<D>, SignInAttempt) -> BoxFuture<'static, Result<Gate, AuthError>> + Send + Sync,
165>;
166
167pub(crate) struct OwnedGate<D> {
169 pub owner: &'static str,
170 pub gate: ErasedGate<D>,
171}
172pub(crate) type ErasedResponseHook<D> = Arc<dyn Fn(&Ctx<D>, &mut Response) + Send + Sync>;
173pub(crate) type ErasedSessionHook<D> =
174 Arc<dyn Fn(HookCtx<D>, SessionView) -> BoxFuture<'static, Result<(), AuthError>> + Send + Sync>;
175pub(crate) type ErasedSessionGate<D> = Arc<
176 dyn Fn(HookCtx<D>, SessionView, SessionUse) -> BoxFuture<'static, Result<(), AuthError>>
177 + Send
178 + Sync,
179>;
180pub(crate) type FixedExpiry = Arc<dyn Fn(&SessionView) -> bool + Send + Sync>;
181pub(crate) type ErasedUserInputHook<D> = Arc<
182 dyn Fn(
183 HookCtx<D>,
184 serde_json::Map<String, serde_json::Value>,
185 crate::internal::UserInput,
186 )
187 -> BoxFuture<'static, Result<serde_json::Map<String, serde_json::Value>, AuthError>>
188 + Send
189 + Sync,
190>;
191pub(crate) type ErasedClaimHook<D> = Arc<
192 dyn for<'a> Fn(crate::internal::Claim<'a, D>) -> BoxFuture<'a, Result<(), AuthError>>
193 + Send
194 + Sync,
195>;
196pub(crate) type ErasedEventHandler<D> = Arc<
197 dyn Fn(Arc<dyn Any + Send + Sync>, Ctx<D>) -> BoxFuture<'static, Result<(), AuthError>>
198 + Send
199 + Sync,
200>;
201
202pub(crate) struct EndpointHooks<D> {
203 pub before: Vec<ErasedBefore<D>>,
204 pub after: Vec<ErasedAfter<D>>,
205}
206
207impl<D> Default for EndpointHooks<D> {
208 fn default() -> Self {
209 Self {
210 before: Vec::new(),
211 after: Vec::new(),
212 }
213 }
214}
215
216pub enum Before<I> {
218 Continue(I),
220 Respond(Response),
222}
223
224pub enum After<O> {
226 Continue(O),
227 Respond(Response),
228}
229
230#[derive(Debug)]
232pub enum Gate {
233 Allow,
234 Deny(AuthError),
235 Challenge(serde_json::Value),
239}
240
241#[derive(Clone, Debug)]
243pub struct SignInAttempt {
244 pub user: UserView,
245 pub method: Cow<'static, str>,
248 pub remember_me: bool,
249}
250
251#[derive(Clone, Copy, Debug, PartialEq, Eq)]
253pub enum SessionUse {
254 Request,
257 Sensitive,
259}
260
261pub type HookCtx<D> = Ctx<D, MaybeAuthenticated>;
263
264#[derive(Clone, Debug)]
266pub enum Resolved {
267 Token(String),
269 User(Id),
271}
272
273pub trait SessionResolver<D: Adapter>: Send + Sync + 'static {
275 fn resolve(
276 &self,
277 ctx: &Ctx<D>,
278 headers: &HeaderMap,
279 ) -> impl Future<Output = Result<Option<Resolved>, AuthError>> + Send;
280}
281
282pub(crate) trait ErasedResolver<D>: Send + Sync {
283 fn resolve<'a>(
284 &'a self,
285 ctx: &'a Ctx<D>,
286 headers: &'a HeaderMap,
287 ) -> BoxFuture<'a, Result<Option<Resolved>, AuthError>>;
288}
289
290impl<D: Adapter, R: SessionResolver<D>> ErasedResolver<D> for R {
291 fn resolve<'a>(
292 &'a self,
293 ctx: &'a Ctx<D>,
294 headers: &'a HeaderMap,
295 ) -> BoxFuture<'a, Result<Option<Resolved>, AuthError>> {
296 Box::pin(SessionResolver::resolve(self, ctx, headers))
297 }
298}
299
300pub(crate) type MethodTable<D> = Vec<(Method, Arc<dyn ErasedEndpoint<D>>)>;
301
302pub(crate) struct Shared<D> {
304 pub migrations: crate::migrate::Migrations,
305 pub db: D,
306 pub schema: Schema,
307 pub keys: Keys,
308 pub config: CoreConfig,
309 pub passwords: Passwords,
310 pub mailer: Option<Arc<dyn DynMailer>>,
311 pub plugins: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
312 pub hooks: HashMap<TypeId, EndpointHooks<D>>,
313 pub gates: Vec<OwnedGate<D>>,
314 pub resolvers: Vec<Arc<dyn ErasedResolver<D>>>,
315 pub response_hooks: Vec<ErasedResponseHook<D>>,
316 pub session_hooks: Vec<ErasedSessionHook<D>>,
317 pub session_gates: Vec<ErasedSessionGate<D>>,
318 pub fixed_expiry: Vec<FixedExpiry>,
319 pub claim_hooks: Vec<ErasedClaimHook<D>>,
320 pub user_input_hooks: Vec<ErasedUserInputHook<D>>,
321 pub events: HashMap<TypeId, Vec<ErasedEventHandler<D>>>,
322 pub router: matchit::Router<MethodTable<D>>,
323 pub rate_limiter: RateLimiter,
324 pub cache_fingerprint: u64,
325}
326
327pub struct Ctx<D, A = Public> {
329 pub(crate) shared: Arc<Shared<D>>,
330 pub(crate) within: Option<Arc<D>>,
332 pub(crate) request: Arc<RequestInfo>,
333 pub(crate) session: Option<Arc<SessionView>>,
334 pub(crate) effects: Arc<Mutex<Effects>>,
335 _access: PhantomData<fn() -> A>,
336}
337
338impl<D, A> Clone for Ctx<D, A> {
339 fn clone(&self) -> Self {
340 Self {
341 shared: self.shared.clone(),
342 within: self.within.clone(),
343 request: self.request.clone(),
344 session: self.session.clone(),
345 effects: self.effects.clone(),
346 _access: PhantomData,
347 }
348 }
349}
350
351impl<D, A> std::fmt::Debug for Ctx<D, A> {
352 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
353 write!(f, "Ctx({} {})", self.request.method, self.request.path)
354 }
355}
356
357impl<D: Adapter, A> Ctx<D, A> {
358 pub(crate) fn new(
359 shared: Arc<Shared<D>>,
360 within: Option<Arc<D>>,
361 request: Arc<RequestInfo>,
362 session: Option<Arc<SessionView>>,
363 effects: Arc<Mutex<Effects>>,
364 ) -> Self {
365 Self {
366 shared,
367 within,
368 request,
369 session,
370 effects,
371 _access: PhantomData,
372 }
373 }
374
375 pub(crate) fn retype<B>(&self) -> Ctx<D, B> {
376 Ctx::new(
377 self.shared.clone(),
378 self.within.clone(),
379 self.request.clone(),
380 self.session.clone(),
381 self.effects.clone(),
382 )
383 }
384
385 pub fn db(&self) -> Db<'_, D> {
387 Db::new(self.adapter(), &self.shared.schema)
388 }
389
390 pub fn db_on<'t, Q: Queries>(&'t self, queries: &'t Q) -> Db<'t, Q> {
392 Db::new(queries, &self.shared.schema)
393 }
394
395 pub fn adapter(&self) -> &D {
398 self.within.as_deref().unwrap_or(&self.shared.db)
399 }
400
401 pub fn schema(&self) -> &Schema {
402 &self.shared.schema
403 }
404
405 pub fn keys(&self) -> &Keys {
406 &self.shared.keys
407 }
408
409 pub fn oauth_token_bytes(&self, token: &str) -> Vec<u8> {
414 if self.shared.config.plaintext_oauth_tokens {
415 token.as_bytes().to_vec()
416 } else {
417 self.shared.keys.encrypt(token.as_bytes())
418 }
419 }
420
421 pub fn config(&self) -> &CoreConfig {
422 &self.shared.config
423 }
424
425 pub fn passwords(&self) -> &Passwords {
426 &self.shared.passwords
427 }
428
429 pub fn now(&self) -> OffsetDateTime {
430 OffsetDateTime::now_utc()
431 }
432
433 pub fn new_id(&self) -> Result<Id, AuthError> {
436 self.shared.config.ids.generate()
437 }
438
439 pub fn request(&self) -> &RequestInfo {
440 &self.request
441 }
442
443 pub fn headers(&self) -> &HeaderMap {
444 &self.request.headers
445 }
446
447 pub fn ip(&self) -> Option<&str> {
448 self.request.ip.as_deref()
449 }
450
451 pub fn user_agent(&self) -> Option<&str> {
452 self.request.user_agent.as_deref()
453 }
454
455 pub fn param(&self, name: &str) -> Option<&str> {
457 self.request
458 .params
459 .iter()
460 .find(|(k, _)| k == name)
461 .map(|(_, v)| v.as_str())
462 }
463
464 pub fn plugin<P: Plugin>(&self) -> &P {
467 self.try_plugin::<P>().unwrap_or_else(|| {
468 panic!(
469 "plugin `{}` is not registered; list it in `Requires`",
470 P::ID
471 )
472 })
473 }
474
475 pub fn try_plugin<P: Plugin>(&self) -> Option<&P> {
476 self.shared
477 .plugins
478 .get(&TypeId::of::<P>())
479 .and_then(|p| p.downcast_ref::<P>())
480 }
481
482 pub fn emit<E: Event>(&self, event: E) {
484 self.effects.lock().unwrap().events.push(PendingEvent {
485 type_id: TypeId::of::<E>(),
486 event: Arc::new(event),
487 });
488 }
489
490 pub fn set_cookie(&self, cookie: SetCookie) {
491 let mut effects = self.effects.lock().unwrap();
492 effects.cookies.retain(|c| c.name != cookie.name);
493 effects.cookies.push(cookie);
494 }
495
496 pub fn cookie(&self, name: &str) -> Option<&str> {
497 cookies::read(&self.request.headers, name)
498 }
499
500 pub fn set_signed_cookie(&self, name: &str, value: &str, max_age: Option<Duration>) {
502 let name = self.shared.config.cookie_name(name);
503 let value = self.shared.keys.sign(SignPurpose::Cookie, value);
504 self.set_cookie(SetCookie::new(name, value, max_age));
505 }
506
507 pub fn signed_cookie(&self, name: &str) -> Option<String> {
509 let raw = self.cookie(&self.shared.config.cookie_name(name))?;
510 let keys = &self.shared.keys;
511 keys.verify(SignPurpose::Cookie, &keys.decode_cookie(raw))
512 .map(str::to_owned)
513 }
514
515 pub fn signed_token_cookie(&self, name: &str) -> Option<String> {
519 let raw = self.cookie(&self.shared.config.cookie_name(name))?;
520 let keys = &self.shared.keys;
521 keys.verify_token(&keys.decode_cookie(raw))
522 .map(str::to_owned)
523 }
524
525 pub fn delete_cookie(&self, name: &str) {
526 self.set_cookie(SetCookie::delete(self.shared.config.cookie_name(name)));
527 }
528
529 pub fn redirect(&self, url: impl Into<String>) {
533 self.effects.lock().unwrap().redirect = Some(url.into());
534 }
535
536 pub fn set_header(&self, name: HeaderName, value: HeaderValue) {
537 self.effects.lock().unwrap().headers.push((name, value));
538 }
539
540 pub fn internal(&self) -> Internal<'_, D, A> {
542 Internal::new(self)
543 }
544
545 pub(crate) fn mailer(&self) -> Option<&Arc<dyn DynMailer>> {
546 self.shared.mailer.as_ref()
547 }
548
549 pub async fn sensitive_session(&self) -> Result<SessionView, AuthError> {
556 crate::session::sensitive(
557 &self.shared,
558 self.within.as_ref(),
559 &self.request,
560 &self.effects,
561 self.session.as_deref(),
562 )
563 .await
564 }
565
566 pub async fn authoritative_session(&self) -> Result<SessionView, AuthError> {
574 crate::session::authoritative(
575 &self.shared,
576 self.within.as_ref(),
577 &self.request,
578 &self.effects,
579 self.session.as_deref(),
580 )
581 .await
582 }
583
584 pub fn dont_remember(&self) -> bool {
588 let config = &self.shared.config;
589 let flag = config.cookie_name(crate::session::DONT_REMEMBER);
590 let token = config.cookie_name(crate::session::SESSION_TOKEN);
591 let effects = self.effects.lock().unwrap();
592 let sets = |name: &str| {
593 effects
594 .cookies
595 .iter()
596 .any(|c| c.name == name && c.max_age != Some(Duration::ZERO))
597 };
598 if sets(&flag) {
599 return true;
600 }
601 if sets(&token) {
602 return false;
603 }
604 drop(effects);
605 self.signed_token_cookie(crate::session::DONT_REMEMBER)
606 .is_some()
607 }
608}
609
610impl<D: Adapter> Ctx<D, MaybeAuthenticated> {
611 pub fn session(&self) -> Option<&SessionView> {
612 self.session.as_deref()
613 }
614}
615
616impl<D: Adapter> Ctx<D, Authenticated> {
617 pub fn session(&self) -> &SessionView {
618 self.session
619 .as_deref()
620 .expect("Authenticated endpoints only run with a session")
621 }
622}
623
624impl<D: Adapter> Ctx<D, Fresh> {
625 pub fn session(&self) -> &SessionView {
626 self.session
627 .as_deref()
628 .expect("Fresh endpoints only run with a session")
629 }
630}
631
632pub(crate) enum Outcome<O> {
633 Output(O),
634 Response(Response),
635}
636
637pub(crate) struct Executed<O> {
638 pub result: Result<Outcome<O>, AuthError>,
639 pub effects: Effects,
640}
641
642pub(crate) async fn execute<D: Adapter, E: Endpoint<D>>(
645 shared: &Arc<Shared<D>>,
646 within: Option<Arc<D>>,
647 endpoint: &E,
648 request: Arc<RequestInfo>,
649 input: E::Input,
650) -> Executed<E::Output> {
651 let effects = Arc::new(Mutex::new(Effects::default()));
652 let result = run::<D, E>(shared, within, endpoint, request, input, &effects).await;
653 let effects = std::mem::take(&mut *effects.lock().unwrap());
654 Executed { result, effects }
655}
656
657async fn run<D: Adapter, E: Endpoint<D>>(
658 shared: &Arc<Shared<D>>,
659 within: Option<Arc<D>>,
660 endpoint: &E,
661 request: Arc<RequestInfo>,
662 input: E::Input,
663 effects: &Arc<Mutex<Effects>>,
664) -> Result<Outcome<E::Output>, AuthError> {
665 let level = <E::Access as Access>::LEVEL;
666 let session = match level {
667 AccessLevel::Public => None,
668 _ => crate::session::resolve(shared, within.as_ref(), &request, effects)
669 .await?
670 .map(Arc::new),
671 };
672 match (level, &session) {
673 (AccessLevel::Required | AccessLevel::Fresh, None) => return Err(AuthError::unauthorized()),
674 (AccessLevel::Fresh, Some(s)) if s.ephemeral || !shared.config.is_fresh(&s.session) => {
675 return Err(AuthError::not_fresh());
676 }
677 _ => {}
678 }
679
680 let ctx: Ctx<D, E::Access> =
681 Ctx::new(shared.clone(), within, request, session, effects.clone());
682 let hooks = shared.hooks.get(&TypeId::of::<E>());
683 let mut input = input;
684 for before in hooks.map(|h| h.before.as_slice()).unwrap_or_default() {
685 match before(ctx.retype(), Box::new(input)).await? {
686 Before::Continue(next) => {
687 input = *next
688 .downcast::<E::Input>()
689 .expect("hook keeps the input type")
690 }
691 Before::Respond(response) => return Ok(Outcome::Response(response)),
692 }
693 }
694 let mut output = endpoint.call(ctx.clone(), input).await?;
695 for after in hooks.map(|h| h.after.as_slice()).unwrap_or_default() {
696 match after(ctx.retype(), Box::new(output)).await? {
697 After::Continue(next) => {
698 output = *next
699 .downcast::<E::Output>()
700 .expect("hook keeps the output type")
701 }
702 After::Respond(response) => return Ok(Outcome::Response(response)),
703 }
704 }
705 Ok(Outcome::Output(output))
706}
707
708pub(crate) async fn dispatch_events<D: Adapter>(
709 shared: &Arc<Shared<D>>,
710 events: Vec<PendingEvent>,
711) {
712 for pending in events {
713 let Some(handlers) = shared.events.get(&pending.type_id) else {
714 continue;
715 };
716 for handler in handlers {
717 let request = Arc::new(RequestInfo::synthetic(
718 Method::POST,
719 "/event",
720 HeaderMap::new(),
721 ));
722 let ctx = Ctx::new(shared.clone(), None, request, None, Arc::default());
723 if let Err(err) = handler(pending.event.clone(), ctx).await {
724 tracing::error!(error = %err, "fastauth event handler failed");
725 }
726 }
727 }
728}
729
730pub(crate) trait ErasedEndpoint<D>: Send + Sync {
731 fn handle<'a>(
732 &'a self,
733 shared: &'a Arc<Shared<D>>,
734 request: Arc<RequestInfo>,
735 body: Bytes,
736 ) -> BoxFuture<'a, Response>;
737}
738
739pub(crate) struct Erased<E>(pub E);
740
741impl<D: Adapter, E: Endpoint<D>> ErasedEndpoint<D> for Erased<E> {
742 fn handle<'a>(
743 &'a self,
744 shared: &'a Arc<Shared<D>>,
745 request: Arc<RequestInfo>,
746 body: Bytes,
747 ) -> BoxFuture<'a, Response> {
748 Box::pin(async move {
749 let input = match decode_input::<E::Input>(&request, &body) {
750 Ok(input) => input,
751 Err(err) => return err.into_response(),
752 };
753 let mut executed = execute(shared, None, &self.0, request.clone(), input).await;
754 if executed.result.is_ok() {
755 let events = std::mem::take(&mut executed.effects.events);
756 dispatch_events(shared, events).await;
757 }
758 let result = executed.result.and_then(|outcome| match outcome {
759 Outcome::Output(output) => serde_json::to_vec(&output)
760 .map(|b| Outcome::Output(Bytes::from(b)))
761 .map_err(AuthError::internal),
762 Outcome::Response(response) => Ok(Outcome::Response(response)),
763 });
764 let mut response = into_response(&shared.config, result, executed.effects);
765 if !shared.response_hooks.is_empty() {
766 let ctx: Ctx<D> = Ctx::new(shared.clone(), None, request, None, Arc::default());
767 for hook in &shared.response_hooks {
768 hook(&ctx, &mut response);
769 }
770 }
771 response
772 })
773 }
774}
775
776fn decode_input<I: DeserializeOwned>(request: &RequestInfo, body: &[u8]) -> Result<I, AuthError> {
780 let invalid = |e: &dyn std::fmt::Display| {
781 AuthError::bad_request(crate::error::codes::INVALID_BODY, e.to_string())
782 };
783 let query = request.query.as_deref().unwrap_or("");
784 if query.contains('\0') || query.contains("%00") || json_has_nul(body) {
785 return Err(invalid(&"request text can't contain a NUL character"));
786 }
787 if request.method == Method::GET || request.method == Method::HEAD {
788 return serde_urlencoded::from_str(request.query.as_deref().unwrap_or(""))
789 .map_err(|e| invalid(&e));
790 }
791 if body.iter().all(u8::is_ascii_whitespace) {
792 return serde_json::from_slice(b"{}")
793 .or_else(|_| serde_json::from_slice(b"null"))
794 .map_err(|e| invalid(&e));
795 }
796 serde_json::from_slice(body).map_err(|e| invalid(&e))
797}
798
799fn json_has_nul(json: &[u8]) -> bool {
803 let mut i = 0;
804 while i < json.len() {
805 if json[i] == b'\\' {
806 if json[i + 1..].starts_with(b"u0000") {
807 return true;
808 }
809 i += 2;
810 } else {
811 i += 1;
812 }
813 }
814 false
815}
816
817pub(crate) fn into_response(
818 config: &CoreConfig,
819 result: Result<Outcome<Bytes>, AuthError>,
820 effects: Effects,
821) -> Response {
822 let mut response = match result {
823 Ok(Outcome::Response(response)) => response,
824 Ok(Outcome::Output(_)) if effects.redirect.is_some() => {
825 let target = effects.redirect.as_deref().unwrap_or("/");
826 match config.resolve_redirect(target) {
827 Some(location) => {
828 let mut response = Response::new(Bytes::new());
829 *response.status_mut() = StatusCode::FOUND;
830 if let Ok(location) = HeaderValue::from_str(location.as_str()) {
831 response.headers_mut().insert(LOCATION, location);
832 }
833 response
834 }
835 None => AuthError::new(
836 StatusCode::FORBIDDEN,
837 codes::INVALID_CALLBACK_URL,
838 "callback URL is not on a trusted origin",
839 )
840 .into_response(),
841 }
842 }
843 Ok(Outcome::Output(body)) => {
844 let mut response = Response::new(body);
845 response
846 .headers_mut()
847 .insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
848 response
849 }
850 Err(err) => err.into_response(),
851 };
852 for cookie in &effects.cookies {
853 if let Ok(value) = HeaderValue::from_str(&cookie.to_header(config)) {
854 response.headers_mut().append(SET_COOKIE, value);
855 }
856 }
857 for (name, value) in effects.headers {
858 response.headers_mut().append(name, value);
859 }
860 response
861}