1mod branding;
11mod captcha;
12mod ext;
13mod features;
14
15use std::{
16 collections::BTreeMap,
17 fmt::Formatter,
18 net::{IpAddr, Ipv4Addr},
19};
20
21use chrono::{DateTime, Duration, Utc};
22use http::{Method, Uri, Version};
23use mas_data_model::{
24 AuthorizationGrant, BrowserSession, Client, CompatSsoLogin, CompatSsoLoginState,
25 DeviceCodeGrant, MatrixUser, UlidExt as _, UpstreamOAuthLink, UpstreamOAuthProvider,
26 UpstreamOAuthProviderClaimsImports, UpstreamOAuthProviderDiscoveryMode,
27 UpstreamOAuthProviderOnBackchannelLogout, UpstreamOAuthProviderPkceMode,
28 UpstreamOAuthProviderTokenAuthMethod, User, UserEmailAuthentication,
29 UserEmailAuthenticationCode, UserRecoverySession, UserRegistration,
30};
31use mas_i18n::DataLocale;
32use mas_iana::jose::JsonWebSignatureAlg;
33use mas_policy::{Violation, ViolationVariant};
34use mas_router::{Account, GraphQL, Login, PostAuthAction, UrlBuilder};
35use oauth2_types::{
36 requests::ResponseMode,
37 scope::{OPENID, Scope},
38};
39use rand::{
40 RngExt, SeedableRng,
41 distr::{Alphanumeric, SampleString},
42};
43use rand_chacha::ChaCha8Rng;
44use serde::{Deserialize, Serialize, ser::SerializeStruct};
45use ulid::Ulid;
46use url::Url;
47
48pub use self::{
49 branding::SiteBranding, captcha::WithCaptcha, ext::SiteConfigExt, features::SiteFeatures,
50};
51use crate::{FieldError, FormField, FormState};
52
53pub trait TemplateContext: Serialize {
55 fn with_session(self, current_session: BrowserSession) -> WithSession<Self>
57 where
58 Self: Sized,
59 {
60 WithSession {
61 current_session,
62 inner: self,
63 }
64 }
65
66 fn maybe_with_session(
68 self,
69 current_session: Option<BrowserSession>,
70 ) -> WithOptionalSession<Self>
71 where
72 Self: Sized,
73 {
74 WithOptionalSession {
75 current_session,
76 inner: self,
77 }
78 }
79
80 fn with_csrf<C>(self, csrf_token: C) -> WithCsrf<Self>
82 where
83 Self: Sized,
84 C: ToString,
85 {
86 WithCsrf {
88 csrf_token: csrf_token.to_string(),
89 inner: self,
90 }
91 }
92
93 fn with_language(self, lang: DataLocale) -> WithLanguage<Self>
95 where
96 Self: Sized,
97 {
98 WithLanguage {
99 lang: lang.to_string(),
100 inner: self,
101 }
102 }
103
104 fn with_captcha(self, captcha: Option<mas_data_model::CaptchaConfig>) -> WithCaptcha<Self>
106 where
107 Self: Sized,
108 {
109 WithCaptcha::new(captcha, self)
110 }
111
112 fn sample<R: RngExt>(
117 now: chrono::DateTime<Utc>,
118 rng: &mut R,
119 locales: &[DataLocale],
120 ) -> BTreeMap<SampleIdentifier, Self>
121 where
122 Self: Sized;
123}
124
125#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
126pub struct SampleIdentifier {
127 pub components: Vec<(&'static str, String)>,
128}
129
130impl SampleIdentifier {
131 pub fn from_index(index: usize) -> Self {
132 Self {
133 components: Vec::default(),
134 }
135 .with_appended("index", format!("{index}"))
136 }
137
138 pub fn with_appended(&self, kind: &'static str, locale: String) -> Self {
139 let mut new = self.clone();
140 new.components.push((kind, locale));
141 new
142 }
143}
144
145pub(crate) fn sample_list<T: TemplateContext>(samples: Vec<T>) -> BTreeMap<SampleIdentifier, T> {
146 samples
147 .into_iter()
148 .enumerate()
149 .map(|(index, sample)| (SampleIdentifier::from_index(index), sample))
150 .collect()
151}
152
153impl TemplateContext for () {
154 fn sample<R: RngExt>(
155 _now: chrono::DateTime<Utc>,
156 _rng: &mut R,
157 _locales: &[DataLocale],
158 ) -> BTreeMap<SampleIdentifier, Self>
159 where
160 Self: Sized,
161 {
162 BTreeMap::new()
163 }
164}
165
166#[derive(Serialize, Debug)]
168pub struct WithLanguage<T> {
169 lang: String,
170
171 #[serde(flatten)]
172 inner: T,
173}
174
175impl<T> WithLanguage<T> {
176 pub fn language(&self) -> &str {
178 &self.lang
179 }
180}
181
182impl<T> std::ops::Deref for WithLanguage<T> {
183 type Target = T;
184
185 fn deref(&self) -> &Self::Target {
186 &self.inner
187 }
188}
189
190impl<T: TemplateContext> TemplateContext for WithLanguage<T> {
191 fn sample<R: RngExt>(
192 now: chrono::DateTime<Utc>,
193 rng: &mut R,
194 locales: &[DataLocale],
195 ) -> BTreeMap<SampleIdentifier, Self>
196 where
197 Self: Sized,
198 {
199 let rng = ChaCha8Rng::from_rng(&mut *rng);
201 locales
202 .iter()
203 .flat_map(|locale| {
204 T::sample(now, &mut rng.clone(), locales)
205 .into_iter()
206 .map(|(sample_id, sample)| {
207 (
208 sample_id.with_appended("locale", locale.to_string()),
209 WithLanguage {
210 lang: locale.to_string(),
211 inner: sample,
212 },
213 )
214 })
215 })
216 .collect()
217 }
218}
219
220#[derive(Serialize, Debug)]
222pub struct WithCsrf<T> {
223 csrf_token: String,
224
225 #[serde(flatten)]
226 inner: T,
227}
228
229impl<T: TemplateContext> TemplateContext for WithCsrf<T> {
230 fn sample<R: RngExt>(
231 now: chrono::DateTime<Utc>,
232 rng: &mut R,
233 locales: &[DataLocale],
234 ) -> BTreeMap<SampleIdentifier, Self>
235 where
236 Self: Sized,
237 {
238 T::sample(now, rng, locales)
239 .into_iter()
240 .map(|(k, inner)| {
241 (
242 k,
243 WithCsrf {
244 csrf_token: "fake_csrf_token".into(),
245 inner,
246 },
247 )
248 })
249 .collect()
250 }
251}
252
253#[derive(Serialize, Debug)]
255pub struct WithSession<T> {
256 current_session: BrowserSession,
257
258 #[serde(flatten)]
259 inner: T,
260}
261
262impl<T: TemplateContext> TemplateContext for WithSession<T> {
263 fn sample<R: RngExt>(
264 now: chrono::DateTime<Utc>,
265 rng: &mut R,
266 locales: &[DataLocale],
267 ) -> BTreeMap<SampleIdentifier, Self>
268 where
269 Self: Sized,
270 {
271 BrowserSession::samples(now, rng)
272 .into_iter()
273 .enumerate()
274 .flat_map(|(session_index, session)| {
275 T::sample(now, rng, locales)
276 .into_iter()
277 .map(move |(k, inner)| {
278 (
279 k.with_appended("browser-session", session_index.to_string()),
280 WithSession {
281 current_session: session.clone(),
282 inner,
283 },
284 )
285 })
286 })
287 .collect()
288 }
289}
290
291#[derive(Serialize)]
293pub struct WithOptionalSession<T> {
294 current_session: Option<BrowserSession>,
295
296 #[serde(flatten)]
297 inner: T,
298}
299
300impl<T: TemplateContext> TemplateContext for WithOptionalSession<T> {
301 fn sample<R: RngExt>(
302 now: chrono::DateTime<Utc>,
303 rng: &mut R,
304 locales: &[DataLocale],
305 ) -> BTreeMap<SampleIdentifier, Self>
306 where
307 Self: Sized,
308 {
309 BrowserSession::samples(now, rng)
310 .into_iter()
311 .map(Some) .chain(std::iter::once(None)) .enumerate()
314 .flat_map(|(session_index, session)| {
315 T::sample(now, rng, locales)
316 .into_iter()
317 .map(move |(k, inner)| {
318 (
319 if session.is_some() {
320 k.with_appended("browser-session", session_index.to_string())
321 } else {
322 k
323 },
324 WithOptionalSession {
325 current_session: session.clone(),
326 inner,
327 },
328 )
329 })
330 })
331 .collect()
332 }
333}
334
335pub struct EmptyContext;
337
338impl Serialize for EmptyContext {
339 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
340 where
341 S: serde::Serializer,
342 {
343 let mut s = serializer.serialize_struct("EmptyContext", 0)?;
344 s.serialize_field("__UNUSED", &())?;
347 s.end()
348 }
349}
350
351impl TemplateContext for EmptyContext {
352 fn sample<R: RngExt>(
353 _now: chrono::DateTime<Utc>,
354 _rng: &mut R,
355 _locales: &[DataLocale],
356 ) -> BTreeMap<SampleIdentifier, Self>
357 where
358 Self: Sized,
359 {
360 sample_list(vec![EmptyContext])
361 }
362}
363
364#[derive(Serialize)]
366pub struct IndexContext {
367 discovery_url: Url,
368}
369
370impl IndexContext {
371 #[must_use]
374 pub fn new(discovery_url: Url) -> Self {
375 Self { discovery_url }
376 }
377}
378
379impl TemplateContext for IndexContext {
380 fn sample<R: RngExt>(
381 _now: chrono::DateTime<Utc>,
382 _rng: &mut R,
383 _locales: &[DataLocale],
384 ) -> BTreeMap<SampleIdentifier, Self>
385 where
386 Self: Sized,
387 {
388 sample_list(vec![Self {
389 discovery_url: "https://example.com/.well-known/openid-configuration"
390 .parse()
391 .unwrap(),
392 }])
393 }
394}
395
396#[derive(Serialize)]
398#[serde(rename_all = "camelCase")]
399pub struct AppConfig {
400 root: String,
401 graphql_endpoint: String,
402}
403
404#[derive(Serialize)]
406pub struct AppContext {
407 app_config: AppConfig,
408}
409
410impl AppContext {
411 #[must_use]
413 pub fn from_url_builder(url_builder: &UrlBuilder) -> Self {
414 let root = url_builder.relative_url_for(&Account::default());
415 let graphql_endpoint = url_builder.relative_url_for(&GraphQL);
416 Self {
417 app_config: AppConfig {
418 root,
419 graphql_endpoint,
420 },
421 }
422 }
423}
424
425impl TemplateContext for AppContext {
426 fn sample<R: RngExt>(
427 _now: chrono::DateTime<Utc>,
428 _rng: &mut R,
429 _locales: &[DataLocale],
430 ) -> BTreeMap<SampleIdentifier, Self>
431 where
432 Self: Sized,
433 {
434 let url_builder = UrlBuilder::new("https://example.com/".parse().unwrap(), None, None);
435 sample_list(vec![Self::from_url_builder(&url_builder)])
436 }
437}
438
439#[derive(Serialize)]
441pub struct ApiDocContext {
442 openapi_url: Url,
443 callback_url: Url,
444}
445
446impl ApiDocContext {
447 #[must_use]
450 pub fn from_url_builder(url_builder: &UrlBuilder) -> Self {
451 Self {
452 openapi_url: url_builder.absolute_url_for(&mas_router::ApiSpec),
453 callback_url: url_builder.absolute_url_for(&mas_router::ApiDocCallback),
454 }
455 }
456}
457
458impl TemplateContext for ApiDocContext {
459 fn sample<R: RngExt>(
460 _now: chrono::DateTime<Utc>,
461 _rng: &mut R,
462 _locales: &[DataLocale],
463 ) -> BTreeMap<SampleIdentifier, Self>
464 where
465 Self: Sized,
466 {
467 let url_builder = UrlBuilder::new("https://example.com/".parse().unwrap(), None, None);
468 sample_list(vec![Self::from_url_builder(&url_builder)])
469 }
470}
471
472#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
474#[serde(rename_all = "snake_case")]
475pub enum LoginFormField {
476 Username,
478
479 Password,
481}
482
483impl FormField for LoginFormField {
484 fn keep(&self) -> bool {
485 match self {
486 Self::Username => true,
487 Self::Password => false,
488 }
489 }
490}
491
492#[derive(Serialize)]
494#[serde(tag = "kind", rename_all = "snake_case")]
495pub enum PostAuthContextInner {
496 ContinueAuthorizationGrant {
498 grant: Box<AuthorizationGrant>,
500 },
501
502 ContinueDeviceCodeGrant {
504 grant: Box<DeviceCodeGrant>,
506 },
507
508 ContinueCompatSsoLogin {
511 login: Box<CompatSsoLogin>,
513 },
514
515 ChangePassword,
517
518 LinkUpstream {
520 provider: Box<UpstreamOAuthProvider>,
522
523 link: Box<UpstreamOAuthLink>,
525 },
526
527 ManageAccount,
529}
530
531#[derive(Serialize)]
533pub struct PostAuthContext {
534 pub params: PostAuthAction,
536
537 #[serde(flatten)]
539 pub ctx: PostAuthContextInner,
540}
541
542#[derive(Serialize, Default)]
544pub struct LoginContext {
545 form: FormState<LoginFormField>,
546 next: Option<PostAuthContext>,
547 providers: Vec<UpstreamOAuthProvider>,
548
549 password_only: bool,
553}
554
555impl TemplateContext for LoginContext {
556 fn sample<R: RngExt>(
557 _now: chrono::DateTime<Utc>,
558 _rng: &mut R,
559 _locales: &[DataLocale],
560 ) -> BTreeMap<SampleIdentifier, Self>
561 where
562 Self: Sized,
563 {
564 sample_list(vec![
566 LoginContext {
567 form: FormState::default(),
568 next: None,
569 providers: Vec::new(),
570 password_only: false,
571 },
572 LoginContext {
573 form: FormState::default(),
574 next: None,
575 providers: Vec::new(),
576 password_only: true,
577 },
578 LoginContext {
579 form: FormState::default()
580 .with_error_on_field(LoginFormField::Username, FieldError::Required)
581 .with_error_on_field(
582 LoginFormField::Password,
583 FieldError::Policy {
584 code: None,
585 message: "password too short".to_owned(),
586 },
587 ),
588 next: None,
589 providers: Vec::new(),
590 password_only: false,
591 },
592 LoginContext {
593 form: FormState::default()
594 .with_error_on_field(LoginFormField::Username, FieldError::Exists),
595 next: None,
596 providers: Vec::new(),
597 password_only: false,
598 },
599 ])
600 }
601}
602
603impl LoginContext {
604 #[must_use]
606 pub fn with_form_state(self, form: FormState<LoginFormField>) -> Self {
607 Self { form, ..self }
608 }
609
610 pub fn form_state_mut(&mut self) -> &mut FormState<LoginFormField> {
612 &mut self.form
613 }
614
615 #[must_use]
617 pub fn with_upstream_providers(self, providers: Vec<UpstreamOAuthProvider>) -> Self {
618 Self { providers, ..self }
619 }
620
621 #[must_use]
624 pub fn with_password_only(self, password_only: bool) -> Self {
625 Self {
626 password_only,
627 ..self
628 }
629 }
630
631 #[must_use]
633 pub fn with_post_action(self, context: PostAuthContext) -> Self {
634 Self {
635 next: Some(context),
636 ..self
637 }
638 }
639}
640
641#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
643#[serde(rename_all = "snake_case")]
644pub enum RegisterFormField {
645 Username,
647
648 Email,
650
651 Password,
653
654 PasswordConfirm,
656
657 AcceptTerms,
659}
660
661impl FormField for RegisterFormField {
662 fn keep(&self) -> bool {
663 match self {
664 Self::Username | Self::Email | Self::AcceptTerms => true,
665 Self::Password | Self::PasswordConfirm => false,
666 }
667 }
668}
669
670#[derive(Serialize)]
672struct RegisterPageProvider {
673 name: String,
674 brand: Option<String>,
675 id: String,
677}
678
679impl RegisterPageProvider {
680 fn new(provider: UpstreamOAuthProvider) -> Self {
681 let name = provider
682 .human_name
683 .or_else(|| {
684 provider
685 .issuer
686 .as_deref()
687 .map(|issuer| crate::functions::simplify_url(issuer, true))
688 })
689 .filter(|name| !name.is_empty())
690 .unwrap_or_else(|| provider.id.to_string());
691
692 Self {
693 name,
694 brand: provider.brand_name,
695 id: provider.id.to_string(),
696 }
697 }
698}
699
700#[derive(Serialize)]
702pub struct RegisterContext {
703 providers: Vec<RegisterPageProvider>,
704 login_link: String,
705 form: FormState<RegisterFormField>,
706 graphql_endpoint: String,
707}
708
709impl TemplateContext for RegisterContext {
710 fn sample<R: RngExt>(
711 _now: chrono::DateTime<Utc>,
712 _rng: &mut R,
713 _locales: &[DataLocale],
714 ) -> BTreeMap<SampleIdentifier, Self>
715 where
716 Self: Sized,
717 {
718 let url_builder = UrlBuilder::new("https://example.com/".parse().unwrap(), None, None);
719 sample_list(vec![RegisterContext::new(&url_builder, Vec::new(), None)])
721 }
722}
723
724impl RegisterContext {
725 #[must_use]
728 pub fn new(
729 url_builder: &UrlBuilder,
730 providers: Vec<UpstreamOAuthProvider>,
731 post_auth_action: Option<&PostAuthAction>,
732 ) -> Self {
733 Self {
734 providers: providers
735 .into_iter()
736 .map(RegisterPageProvider::new)
737 .collect(),
738 login_link: url_builder.relative_url_for(&Login::from(post_auth_action.cloned())),
739 form: FormState::default(),
740 graphql_endpoint: url_builder.relative_url_for(&GraphQL),
741 }
742 }
743
744 #[must_use]
746 pub fn with_form_state(self, form: FormState<RegisterFormField>) -> Self {
747 Self { form, ..self }
748 }
749}
750
751#[derive(Serialize)]
753pub struct ConsentContext {
754 grant: AuthorizationGrant,
755 client: Client,
756 action: PostAuthAction,
757 matrix_user: MatrixUser,
758}
759
760impl TemplateContext for ConsentContext {
761 fn sample<R: RngExt>(
762 now: chrono::DateTime<Utc>,
763 rng: &mut R,
764 _locales: &[DataLocale],
765 ) -> BTreeMap<SampleIdentifier, Self>
766 where
767 Self: Sized,
768 {
769 sample_list(
770 Client::samples(now, rng)
771 .into_iter()
772 .flat_map(|client| {
773 [
774 (None, ResponseMode::Query),
775 (None, ResponseMode::Fragment),
776 (None, ResponseMode::FormPost),
777 (Some("some-state".to_owned()), ResponseMode::Query),
778 (Some("some-state".to_owned()), ResponseMode::Fragment),
779 (Some("some-state".to_owned()), ResponseMode::FormPost),
780 ]
781 .map(|(state, response_mode)| {
782 let mut grant = AuthorizationGrant::sample(now, rng);
783 let action = PostAuthAction::continue_grant(grant.id);
784 grant.client_id = client.id;
786 grant.state = state;
787 grant.response_mode = response_mode;
788 Self {
789 grant,
790 client: client.clone(),
791 action,
792 matrix_user: MatrixUser {
793 mxid: "@alice:example.com".to_owned(),
794 display_name: Some("Alice".to_owned()),
795 },
796 }
797 })
798 })
799 .collect(),
800 )
801 }
802}
803
804impl ConsentContext {
805 #[must_use]
807 pub fn new(grant: AuthorizationGrant, client: Client, matrix_user: MatrixUser) -> Self {
808 let action = PostAuthAction::continue_grant(grant.id);
809 Self {
810 grant,
811 client,
812 action,
813 matrix_user,
814 }
815 }
816}
817
818#[derive(Serialize, Debug)]
819#[serde(tag = "grant_type")]
820enum PolicyViolationGrant {
821 #[serde(rename = "authorization_code")]
822 Authorization(AuthorizationGrant),
823 #[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")]
824 DeviceCode(DeviceCodeGrant),
825}
826
827#[derive(Serialize, Debug)]
829pub struct PolicyViolationContext {
830 grant: PolicyViolationGrant,
831 client: Client,
832 action: PostAuthAction,
833 violations: Vec<Violation>,
834}
835
836impl TemplateContext for PolicyViolationContext {
837 fn sample<R: RngExt>(
838 now: chrono::DateTime<Utc>,
839 rng: &mut R,
840 _locales: &[DataLocale],
841 ) -> BTreeMap<SampleIdentifier, Self>
842 where
843 Self: Sized,
844 {
845 sample_list(
846 Client::samples(now, rng)
847 .into_iter()
848 .flat_map(|client| {
849 let mut grant = AuthorizationGrant::sample(now, rng);
850 grant.client_id = client.id;
852
853 let authorization_grant = PolicyViolationContext::for_authorization_grant(
854 grant.clone(),
855 client.clone(),
856 Vec::new(),
857 );
858
859 let authorization_grant_invalid_scope =
860 PolicyViolationContext::for_authorization_grant(
861 grant.clone(),
862 client.clone(),
863 vec![Violation {
864 msg: "scope 'foo' not allowed".to_owned(),
865 redirect_uri: None,
866 field: None,
867 variant: None,
868 }],
869 );
870 let authorization_grant_admin_scope =
871 PolicyViolationContext::for_authorization_grant(
872 grant.clone(),
873 client.clone(),
874 vec![Violation {
875 msg: "scope 'urn:mas:admin' requires admin privileges".to_owned(),
876 redirect_uri: None,
877 field: None,
878 variant: Some(ViolationVariant::AdminScopeNotAllowed),
879 }],
880 );
881
882 let authorization_grant_client_not_allowed =
883 PolicyViolationContext::for_authorization_grant(
884 grant,
885 client.clone(),
886 vec![Violation {
887 msg: "This client is not allowed to login".to_owned(),
888 redirect_uri: None,
889 field: None,
890 variant: Some(ViolationVariant::ClientNotAllowed),
891 }],
892 );
893
894 let device_code_grant = PolicyViolationContext::for_device_code_grant(
895 DeviceCodeGrant {
896 id: Ulid::from_datetime_with_rng(now, rng),
897 state: mas_data_model::DeviceCodeGrantState::Pending,
898 client_id: client.id,
899 scope: [OPENID].into_iter().collect(),
900 user_code: mas_data_model::generate_user_code(rng),
901 device_code: Alphanumeric.sample_string(rng, 32),
902 created_at: now - Duration::try_minutes(5).unwrap(),
903 expires_at: now + Duration::try_minutes(25).unwrap(),
904 ip_address: None,
905 user_agent: None,
906 locale: None,
907 },
908 client.clone(),
909 Vec::new(),
910 );
911
912 let device_code_grant_invalid_scope =
913 PolicyViolationContext::for_device_code_grant(
914 DeviceCodeGrant {
915 id: Ulid::from_datetime_with_rng(now, rng),
916 state: mas_data_model::DeviceCodeGrantState::Pending,
917 client_id: client.id,
918 scope: [OPENID].into_iter().collect(),
919 user_code: mas_data_model::generate_user_code(rng),
920 device_code: Alphanumeric.sample_string(rng, 32),
921 created_at: now - Duration::try_minutes(5).unwrap(),
922 expires_at: now + Duration::try_minutes(25).unwrap(),
923 ip_address: None,
924 user_agent: None,
925 locale: None,
926 },
927 client,
928 vec![Violation {
929 msg: "user has too many active sessions".to_owned(),
930 redirect_uri: None,
931 field: None,
932 variant: Some(ViolationVariant::TooManySessions {
933 need_to_remove: 1,
934 }),
935 }],
936 );
937
938 [
939 authorization_grant,
940 authorization_grant_invalid_scope,
941 authorization_grant_admin_scope,
942 authorization_grant_client_not_allowed,
943 device_code_grant,
944 device_code_grant_invalid_scope,
945 ]
946 })
947 .collect(),
948 )
949 }
950}
951
952impl PolicyViolationContext {
953 #[must_use]
956 pub const fn for_authorization_grant(
957 grant: AuthorizationGrant,
958 client: Client,
959 violations: Vec<Violation>,
960 ) -> Self {
961 let action = PostAuthAction::continue_grant(grant.id);
962 Self {
963 grant: PolicyViolationGrant::Authorization(grant),
964 client,
965 action,
966 violations,
967 }
968 }
969
970 #[must_use]
973 pub const fn for_device_code_grant(
974 grant: DeviceCodeGrant,
975 client: Client,
976 violations: Vec<Violation>,
977 ) -> Self {
978 let action = PostAuthAction::continue_device_code_grant(grant.id);
979 Self {
980 grant: PolicyViolationGrant::DeviceCode(grant),
981 client,
982 action,
983 violations,
984 }
985 }
986}
987
988#[derive(Serialize)]
990pub struct CompatLoginPolicyViolationContext {
991 violations: Vec<Violation>,
992}
993
994impl TemplateContext for CompatLoginPolicyViolationContext {
995 fn sample<R: RngExt>(
996 _now: chrono::DateTime<Utc>,
997 _rng: &mut R,
998 _locales: &[DataLocale],
999 ) -> BTreeMap<SampleIdentifier, Self>
1000 where
1001 Self: Sized,
1002 {
1003 sample_list(vec![
1004 CompatLoginPolicyViolationContext { violations: vec![] },
1005 CompatLoginPolicyViolationContext {
1006 violations: vec![Violation {
1007 msg: "scope 'foo' not allowed".to_owned(),
1008 redirect_uri: None,
1009 field: None,
1010 variant: None,
1011 }],
1012 },
1013 CompatLoginPolicyViolationContext {
1014 violations: vec![Violation {
1015 msg: "user has too many active sessions".to_owned(),
1016 redirect_uri: None,
1017 field: None,
1018 variant: Some(ViolationVariant::TooManySessions { need_to_remove: 1 }),
1019 }],
1020 },
1021 CompatLoginPolicyViolationContext {
1022 violations: vec![Violation {
1023 msg: "This client is not allowed to login".to_owned(),
1024 redirect_uri: None,
1025 field: None,
1026 variant: Some(ViolationVariant::ClientNotAllowed),
1027 }],
1028 },
1029 CompatLoginPolicyViolationContext {
1030 violations: vec![
1031 Violation {
1032 msg: "scope 'foo' not allowed".to_owned(),
1033 redirect_uri: None,
1034 field: None,
1035 variant: None,
1036 },
1037 Violation {
1038 msg: "user has too many active sessions".to_owned(),
1039 redirect_uri: None,
1040 field: None,
1041 variant: Some(ViolationVariant::TooManySessions { need_to_remove: 1 }),
1042 },
1043 ],
1044 },
1045 ])
1046 }
1047}
1048
1049impl CompatLoginPolicyViolationContext {
1050 #[must_use]
1053 pub const fn for_violations(violations: Vec<Violation>) -> Self {
1054 Self { violations }
1055 }
1056}
1057
1058#[derive(Serialize)]
1060pub struct CompatSsoContext {
1061 login: CompatSsoLogin,
1062 action: PostAuthAction,
1063 matrix_user: MatrixUser,
1064}
1065
1066impl TemplateContext for CompatSsoContext {
1067 fn sample<R: RngExt>(
1068 now: chrono::DateTime<Utc>,
1069 rng: &mut R,
1070 _locales: &[DataLocale],
1071 ) -> BTreeMap<SampleIdentifier, Self>
1072 where
1073 Self: Sized,
1074 {
1075 let id = Ulid::from_datetime_with_rng(now, rng);
1076 sample_list(vec![CompatSsoContext::new(
1077 CompatSsoLogin {
1078 id,
1079 redirect_uri: Url::parse("https://app.element.io/").unwrap(),
1080 login_token: "abcdefghijklmnopqrstuvwxyz012345".into(),
1081 created_at: now,
1082 state: CompatSsoLoginState::Pending,
1083 },
1084 MatrixUser {
1085 mxid: "@alice:example.com".to_owned(),
1086 display_name: Some("Alice".to_owned()),
1087 },
1088 )])
1089 }
1090}
1091
1092impl CompatSsoContext {
1093 #[must_use]
1095 pub fn new(login: CompatSsoLogin, matrix_user: MatrixUser) -> Self
1096where {
1097 let action = PostAuthAction::continue_compat_sso_login(login.id);
1098 Self {
1099 login,
1100 action,
1101 matrix_user,
1102 }
1103 }
1104}
1105
1106#[derive(Serialize)]
1108pub struct EmailRecoveryContext {
1109 user: User,
1110 session: UserRecoverySession,
1111 recovery_link: Url,
1112}
1113
1114impl EmailRecoveryContext {
1115 #[must_use]
1117 pub fn new(user: User, session: UserRecoverySession, recovery_link: Url) -> Self {
1118 Self {
1119 user,
1120 session,
1121 recovery_link,
1122 }
1123 }
1124
1125 #[must_use]
1127 pub fn user(&self) -> &User {
1128 &self.user
1129 }
1130
1131 #[must_use]
1133 pub fn session(&self) -> &UserRecoverySession {
1134 &self.session
1135 }
1136}
1137
1138impl TemplateContext for EmailRecoveryContext {
1139 fn sample<R: RngExt>(
1140 now: chrono::DateTime<Utc>,
1141 rng: &mut R,
1142 _locales: &[DataLocale],
1143 ) -> BTreeMap<SampleIdentifier, Self>
1144 where
1145 Self: Sized,
1146 {
1147 sample_list(User::samples(now, rng).into_iter().map(|user| {
1148 let session = UserRecoverySession {
1149 id: Ulid::from_datetime_with_rng(now, rng),
1150 email: "hello@example.com".to_owned(),
1151 user_agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/536.30.1 (KHTML, like Gecko) Version/6.0.5 Safari/536.30.1".to_owned(),
1152 ip_address: Some(IpAddr::from([192_u8, 0, 2, 1])),
1153 locale: "en".to_owned(),
1154 created_at: now,
1155 consumed_at: None,
1156 };
1157
1158 let link = "https://example.com/recovery/complete?ticket=abcdefghijklmnopqrstuvwxyz0123456789".parse().unwrap();
1159
1160 Self::new(user, session, link)
1161 }).collect())
1162 }
1163}
1164
1165#[derive(Serialize)]
1167pub struct EmailVerificationContext {
1168 #[serde(skip_serializing_if = "Option::is_none")]
1169 browser_session: Option<BrowserSession>,
1170 #[serde(skip_serializing_if = "Option::is_none")]
1171 user_registration: Option<UserRegistration>,
1172 authentication_code: UserEmailAuthenticationCode,
1173}
1174
1175impl EmailVerificationContext {
1176 #[must_use]
1178 pub fn new(
1179 authentication_code: UserEmailAuthenticationCode,
1180 browser_session: Option<BrowserSession>,
1181 user_registration: Option<UserRegistration>,
1182 ) -> Self {
1183 Self {
1184 browser_session,
1185 user_registration,
1186 authentication_code,
1187 }
1188 }
1189
1190 #[must_use]
1192 pub fn user(&self) -> Option<&User> {
1193 self.browser_session.as_ref().map(|s| &s.user)
1194 }
1195
1196 #[must_use]
1198 pub fn code(&self) -> &str {
1199 &self.authentication_code.code
1200 }
1201}
1202
1203impl TemplateContext for EmailVerificationContext {
1204 fn sample<R: RngExt>(
1205 now: chrono::DateTime<Utc>,
1206 rng: &mut R,
1207 _locales: &[DataLocale],
1208 ) -> BTreeMap<SampleIdentifier, Self>
1209 where
1210 Self: Sized,
1211 {
1212 sample_list(
1213 BrowserSession::samples(now, rng)
1214 .into_iter()
1215 .map(|browser_session| {
1216 let authentication_code = UserEmailAuthenticationCode {
1217 id: Ulid::from_datetime_with_rng(now, rng),
1218 user_email_authentication_id: Ulid::from_datetime_with_rng(now, rng),
1219 code: "123456".to_owned(),
1220 created_at: now - Duration::try_minutes(5).unwrap(),
1221 expires_at: now + Duration::try_minutes(25).unwrap(),
1222 };
1223
1224 Self {
1225 browser_session: Some(browser_session),
1226 user_registration: None,
1227 authentication_code,
1228 }
1229 })
1230 .collect(),
1231 )
1232 }
1233}
1234
1235#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
1237#[serde(rename_all = "snake_case")]
1238pub enum RegisterStepsVerifyEmailFormField {
1239 Code,
1241}
1242
1243impl FormField for RegisterStepsVerifyEmailFormField {
1244 fn keep(&self) -> bool {
1245 match self {
1246 Self::Code => true,
1247 }
1248 }
1249}
1250
1251#[derive(Serialize)]
1253pub struct RegisterStepsVerifyEmailContext {
1254 form: FormState<RegisterStepsVerifyEmailFormField>,
1255 authentication: UserEmailAuthentication,
1256}
1257
1258impl RegisterStepsVerifyEmailContext {
1259 #[must_use]
1261 pub fn new(authentication: UserEmailAuthentication) -> Self {
1262 Self {
1263 form: FormState::default(),
1264 authentication,
1265 }
1266 }
1267
1268 #[must_use]
1270 pub fn with_form_state(self, form: FormState<RegisterStepsVerifyEmailFormField>) -> Self {
1271 Self { form, ..self }
1272 }
1273}
1274
1275impl TemplateContext for RegisterStepsVerifyEmailContext {
1276 fn sample<R: RngExt>(
1277 now: chrono::DateTime<Utc>,
1278 rng: &mut R,
1279 _locales: &[DataLocale],
1280 ) -> BTreeMap<SampleIdentifier, Self>
1281 where
1282 Self: Sized,
1283 {
1284 let authentication = UserEmailAuthentication {
1285 id: Ulid::from_datetime_with_rng(now, rng),
1286 user_session_id: None,
1287 user_registration_id: None,
1288 email: "foobar@example.com".to_owned(),
1289 created_at: now,
1290 completed_at: None,
1291 };
1292
1293 sample_list(vec![Self {
1294 form: FormState::default(),
1295 authentication,
1296 }])
1297 }
1298}
1299
1300#[derive(Serialize)]
1302pub struct RegisterStepsEmailInUseContext {
1303 email: String,
1304 action: Option<PostAuthAction>,
1305}
1306
1307impl RegisterStepsEmailInUseContext {
1308 #[must_use]
1310 pub fn new(email: String, action: Option<PostAuthAction>) -> Self {
1311 Self { email, action }
1312 }
1313}
1314
1315impl TemplateContext for RegisterStepsEmailInUseContext {
1316 fn sample<R: RngExt>(
1317 _now: chrono::DateTime<Utc>,
1318 _rng: &mut R,
1319 _locales: &[DataLocale],
1320 ) -> BTreeMap<SampleIdentifier, Self>
1321 where
1322 Self: Sized,
1323 {
1324 let email = "hello@example.com".to_owned();
1325 let action = PostAuthAction::continue_grant(Ulid::nil());
1326 sample_list(vec![Self::new(email, Some(action))])
1327 }
1328}
1329
1330#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
1332#[serde(rename_all = "snake_case")]
1333pub enum RegisterStepsDisplayNameFormField {
1334 DisplayName,
1336}
1337
1338impl FormField for RegisterStepsDisplayNameFormField {
1339 fn keep(&self) -> bool {
1340 match self {
1341 Self::DisplayName => true,
1342 }
1343 }
1344}
1345
1346#[derive(Serialize, Default)]
1348pub struct RegisterStepsDisplayNameContext {
1349 form: FormState<RegisterStepsDisplayNameFormField>,
1350}
1351
1352impl RegisterStepsDisplayNameContext {
1353 #[must_use]
1355 pub fn new() -> Self {
1356 Self::default()
1357 }
1358
1359 #[must_use]
1361 pub fn with_form_state(
1362 mut self,
1363 form_state: FormState<RegisterStepsDisplayNameFormField>,
1364 ) -> Self {
1365 self.form = form_state;
1366 self
1367 }
1368}
1369
1370impl TemplateContext for RegisterStepsDisplayNameContext {
1371 fn sample<R: RngExt>(
1372 _now: chrono::DateTime<chrono::Utc>,
1373 _rng: &mut R,
1374 _locales: &[DataLocale],
1375 ) -> BTreeMap<SampleIdentifier, Self>
1376 where
1377 Self: Sized,
1378 {
1379 sample_list(vec![Self {
1380 form: FormState::default(),
1381 }])
1382 }
1383}
1384
1385#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
1387#[serde(rename_all = "snake_case")]
1388pub enum RegisterStepsRegistrationTokenFormField {
1389 Token,
1391}
1392
1393impl FormField for RegisterStepsRegistrationTokenFormField {
1394 fn keep(&self) -> bool {
1395 match self {
1396 Self::Token => true,
1397 }
1398 }
1399}
1400
1401#[derive(Serialize, Default)]
1403pub struct RegisterStepsRegistrationTokenContext {
1404 form: FormState<RegisterStepsRegistrationTokenFormField>,
1405}
1406
1407impl RegisterStepsRegistrationTokenContext {
1408 #[must_use]
1410 pub fn new() -> Self {
1411 Self::default()
1412 }
1413
1414 #[must_use]
1416 pub fn with_form_state(
1417 mut self,
1418 form_state: FormState<RegisterStepsRegistrationTokenFormField>,
1419 ) -> Self {
1420 self.form = form_state;
1421 self
1422 }
1423}
1424
1425impl TemplateContext for RegisterStepsRegistrationTokenContext {
1426 fn sample<R: RngExt>(
1427 _now: chrono::DateTime<chrono::Utc>,
1428 _rng: &mut R,
1429 _locales: &[DataLocale],
1430 ) -> BTreeMap<SampleIdentifier, Self>
1431 where
1432 Self: Sized,
1433 {
1434 sample_list(vec![Self {
1435 form: FormState::default(),
1436 }])
1437 }
1438}
1439
1440#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
1442#[serde(rename_all = "snake_case")]
1443pub enum RecoveryStartFormField {
1444 Email,
1446}
1447
1448impl FormField for RecoveryStartFormField {
1449 fn keep(&self) -> bool {
1450 match self {
1451 Self::Email => true,
1452 }
1453 }
1454}
1455
1456#[derive(Serialize, Default)]
1458pub struct RecoveryStartContext {
1459 form: FormState<RecoveryStartFormField>,
1460}
1461
1462impl RecoveryStartContext {
1463 #[must_use]
1465 pub fn new() -> Self {
1466 Self::default()
1467 }
1468
1469 #[must_use]
1471 pub fn with_form_state(self, form: FormState<RecoveryStartFormField>) -> Self {
1472 Self { form }
1473 }
1474}
1475
1476impl TemplateContext for RecoveryStartContext {
1477 fn sample<R: RngExt>(
1478 _now: chrono::DateTime<Utc>,
1479 _rng: &mut R,
1480 _locales: &[DataLocale],
1481 ) -> BTreeMap<SampleIdentifier, Self>
1482 where
1483 Self: Sized,
1484 {
1485 sample_list(vec![
1486 Self::new(),
1487 Self::new().with_form_state(
1488 FormState::default()
1489 .with_error_on_field(RecoveryStartFormField::Email, FieldError::Required),
1490 ),
1491 Self::new().with_form_state(
1492 FormState::default()
1493 .with_error_on_field(RecoveryStartFormField::Email, FieldError::Invalid),
1494 ),
1495 ])
1496 }
1497}
1498
1499#[derive(Serialize)]
1501pub struct RecoveryProgressContext {
1502 session: UserRecoverySession,
1503 resend_failed_due_to_rate_limit: bool,
1505}
1506
1507impl RecoveryProgressContext {
1508 #[must_use]
1510 pub fn new(session: UserRecoverySession, resend_failed_due_to_rate_limit: bool) -> Self {
1511 Self {
1512 session,
1513 resend_failed_due_to_rate_limit,
1514 }
1515 }
1516}
1517
1518impl TemplateContext for RecoveryProgressContext {
1519 fn sample<R: RngExt>(
1520 now: chrono::DateTime<Utc>,
1521 rng: &mut R,
1522 _locales: &[DataLocale],
1523 ) -> BTreeMap<SampleIdentifier, Self>
1524 where
1525 Self: Sized,
1526 {
1527 let session = UserRecoverySession {
1528 id: Ulid::from_datetime_with_rng(now, rng),
1529 email: "name@mail.com".to_owned(),
1530 user_agent: "Mozilla/5.0".to_owned(),
1531 ip_address: None,
1532 locale: "en".to_owned(),
1533 created_at: now,
1534 consumed_at: None,
1535 };
1536
1537 sample_list(vec![
1538 Self {
1539 session: session.clone(),
1540 resend_failed_due_to_rate_limit: false,
1541 },
1542 Self {
1543 session,
1544 resend_failed_due_to_rate_limit: true,
1545 },
1546 ])
1547 }
1548}
1549
1550#[derive(Serialize)]
1552pub struct RecoveryExpiredContext {
1553 session: UserRecoverySession,
1554}
1555
1556impl RecoveryExpiredContext {
1557 #[must_use]
1559 pub fn new(session: UserRecoverySession) -> Self {
1560 Self { session }
1561 }
1562}
1563
1564impl TemplateContext for RecoveryExpiredContext {
1565 fn sample<R: RngExt>(
1566 now: chrono::DateTime<Utc>,
1567 rng: &mut R,
1568 _locales: &[DataLocale],
1569 ) -> BTreeMap<SampleIdentifier, Self>
1570 where
1571 Self: Sized,
1572 {
1573 let session = UserRecoverySession {
1574 id: Ulid::from_datetime_with_rng(now, rng),
1575 email: "name@mail.com".to_owned(),
1576 user_agent: "Mozilla/5.0".to_owned(),
1577 ip_address: None,
1578 locale: "en".to_owned(),
1579 created_at: now,
1580 consumed_at: None,
1581 };
1582
1583 sample_list(vec![Self { session }])
1584 }
1585}
1586#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
1588#[serde(rename_all = "snake_case")]
1589pub enum RecoveryFinishFormField {
1590 NewPassword,
1592
1593 NewPasswordConfirm,
1595}
1596
1597impl FormField for RecoveryFinishFormField {
1598 fn keep(&self) -> bool {
1599 false
1600 }
1601}
1602
1603#[derive(Serialize)]
1605pub struct RecoveryFinishContext {
1606 user: User,
1607 form: FormState<RecoveryFinishFormField>,
1608}
1609
1610impl RecoveryFinishContext {
1611 #[must_use]
1613 pub fn new(user: User) -> Self {
1614 Self {
1615 user,
1616 form: FormState::default(),
1617 }
1618 }
1619
1620 #[must_use]
1622 pub fn with_form_state(mut self, form: FormState<RecoveryFinishFormField>) -> Self {
1623 self.form = form;
1624 self
1625 }
1626}
1627
1628impl TemplateContext for RecoveryFinishContext {
1629 fn sample<R: RngExt>(
1630 now: chrono::DateTime<Utc>,
1631 rng: &mut R,
1632 _locales: &[DataLocale],
1633 ) -> BTreeMap<SampleIdentifier, Self>
1634 where
1635 Self: Sized,
1636 {
1637 sample_list(
1638 User::samples(now, rng)
1639 .into_iter()
1640 .flat_map(|user| {
1641 vec![
1642 Self::new(user.clone()),
1643 Self::new(user.clone()).with_form_state(
1644 FormState::default().with_error_on_field(
1645 RecoveryFinishFormField::NewPassword,
1646 FieldError::Invalid,
1647 ),
1648 ),
1649 Self::new(user.clone()).with_form_state(
1650 FormState::default().with_error_on_field(
1651 RecoveryFinishFormField::NewPasswordConfirm,
1652 FieldError::Invalid,
1653 ),
1654 ),
1655 ]
1656 })
1657 .collect(),
1658 )
1659 }
1660}
1661
1662#[derive(Serialize)]
1665pub struct UpstreamExistingLinkContext {
1666 linked_user: User,
1667}
1668
1669impl UpstreamExistingLinkContext {
1670 #[must_use]
1672 pub fn new(linked_user: User) -> Self {
1673 Self { linked_user }
1674 }
1675}
1676
1677impl TemplateContext for UpstreamExistingLinkContext {
1678 fn sample<R: RngExt>(
1679 now: chrono::DateTime<Utc>,
1680 rng: &mut R,
1681 _locales: &[DataLocale],
1682 ) -> BTreeMap<SampleIdentifier, Self>
1683 where
1684 Self: Sized,
1685 {
1686 sample_list(
1687 User::samples(now, rng)
1688 .into_iter()
1689 .map(|linked_user| Self { linked_user })
1690 .collect(),
1691 )
1692 }
1693}
1694
1695#[derive(Serialize)]
1698pub struct UpstreamSuggestLink {
1699 post_logout_action: PostAuthAction,
1700}
1701
1702impl UpstreamSuggestLink {
1703 #[must_use]
1705 pub fn new(link: &UpstreamOAuthLink) -> Self {
1706 Self::for_link_id(link.id)
1707 }
1708
1709 fn for_link_id(id: Ulid) -> Self {
1710 let post_logout_action = PostAuthAction::link_upstream(id);
1711 Self { post_logout_action }
1712 }
1713}
1714
1715impl TemplateContext for UpstreamSuggestLink {
1716 fn sample<R: RngExt>(
1717 now: chrono::DateTime<Utc>,
1718 rng: &mut R,
1719 _locales: &[DataLocale],
1720 ) -> BTreeMap<SampleIdentifier, Self>
1721 where
1722 Self: Sized,
1723 {
1724 let id = Ulid::from_datetime_with_rng(now, rng);
1725 sample_list(vec![Self::for_link_id(id)])
1726 }
1727}
1728
1729#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
1731#[serde(rename_all = "snake_case")]
1732pub enum UpstreamRegisterFormField {
1733 Username,
1735
1736 AcceptTerms,
1738}
1739
1740impl FormField for UpstreamRegisterFormField {
1741 fn keep(&self) -> bool {
1742 match self {
1743 Self::Username | Self::AcceptTerms => true,
1744 }
1745 }
1746}
1747
1748#[derive(Serialize)]
1751pub struct UpstreamRegister {
1752 upstream_oauth_link: UpstreamOAuthLink,
1753 upstream_oauth_provider: UpstreamOAuthProvider,
1754 imported_localpart: Option<String>,
1755 force_localpart: bool,
1756 imported_display_name: Option<String>,
1757 force_display_name: bool,
1758 imported_email: Option<String>,
1759 force_email: bool,
1760 form_state: FormState<UpstreamRegisterFormField>,
1761}
1762
1763impl UpstreamRegister {
1764 #[must_use]
1767 pub fn new(
1768 upstream_oauth_link: UpstreamOAuthLink,
1769 upstream_oauth_provider: UpstreamOAuthProvider,
1770 ) -> Self {
1771 Self {
1772 upstream_oauth_link,
1773 upstream_oauth_provider,
1774 imported_localpart: None,
1775 force_localpart: false,
1776 imported_display_name: None,
1777 force_display_name: false,
1778 imported_email: None,
1779 force_email: false,
1780 form_state: FormState::default(),
1781 }
1782 }
1783
1784 pub fn set_localpart(&mut self, localpart: String, force: bool) {
1786 self.imported_localpart = Some(localpart);
1787 self.force_localpart = force;
1788 }
1789
1790 #[must_use]
1792 pub fn with_localpart(self, localpart: String, force: bool) -> Self {
1793 Self {
1794 imported_localpart: Some(localpart),
1795 force_localpart: force,
1796 ..self
1797 }
1798 }
1799
1800 pub fn set_display_name(&mut self, display_name: String, force: bool) {
1802 self.imported_display_name = Some(display_name);
1803 self.force_display_name = force;
1804 }
1805
1806 #[must_use]
1808 pub fn with_display_name(self, display_name: String, force: bool) -> Self {
1809 Self {
1810 imported_display_name: Some(display_name),
1811 force_display_name: force,
1812 ..self
1813 }
1814 }
1815
1816 pub fn set_email(&mut self, email: String, force: bool) {
1818 self.imported_email = Some(email);
1819 self.force_email = force;
1820 }
1821
1822 #[must_use]
1824 pub fn with_email(self, email: String, force: bool) -> Self {
1825 Self {
1826 imported_email: Some(email),
1827 force_email: force,
1828 ..self
1829 }
1830 }
1831
1832 pub fn set_form_state(&mut self, form_state: FormState<UpstreamRegisterFormField>) {
1834 self.form_state = form_state;
1835 }
1836
1837 #[must_use]
1839 pub fn with_form_state(self, form_state: FormState<UpstreamRegisterFormField>) -> Self {
1840 Self { form_state, ..self }
1841 }
1842}
1843
1844impl TemplateContext for UpstreamRegister {
1845 fn sample<R: RngExt>(
1846 now: chrono::DateTime<Utc>,
1847 _rng: &mut R,
1848 _locales: &[DataLocale],
1849 ) -> BTreeMap<SampleIdentifier, Self>
1850 where
1851 Self: Sized,
1852 {
1853 sample_list(vec![Self::new(
1854 UpstreamOAuthLink {
1855 id: Ulid::nil(),
1856 provider_id: Ulid::nil(),
1857 user_id: None,
1858 subject: "subject".to_owned(),
1859 human_account_name: Some("@john".to_owned()),
1860 created_at: now,
1861 },
1862 UpstreamOAuthProvider {
1863 id: Ulid::nil(),
1864 issuer: Some("https://example.com/".to_owned()),
1865 human_name: Some("Example Ltd.".to_owned()),
1866 brand_name: None,
1867 scope: Scope::from_iter([OPENID]),
1868 token_endpoint_auth_method: UpstreamOAuthProviderTokenAuthMethod::ClientSecretBasic,
1869 token_endpoint_signing_alg: None,
1870 id_token_signed_response_alg: JsonWebSignatureAlg::Rs256,
1871 client_id: "client-id".to_owned(),
1872 encrypted_client_secret: None,
1873 claims_imports: UpstreamOAuthProviderClaimsImports::default(),
1874 authorization_endpoint_override: None,
1875 token_endpoint_override: None,
1876 jwks_uri_override: None,
1877 userinfo_endpoint_override: None,
1878 fetch_userinfo: false,
1879 userinfo_signed_response_alg: None,
1880 discovery_mode: UpstreamOAuthProviderDiscoveryMode::Oidc,
1881 pkce_mode: UpstreamOAuthProviderPkceMode::Auto,
1882 response_mode: None,
1883 additional_authorization_parameters: Vec::new(),
1884 forward_login_hint: false,
1885 created_at: now,
1886 disabled_at: None,
1887 on_backchannel_logout: UpstreamOAuthProviderOnBackchannelLogout::DoNothing,
1888 registration_token_required: false,
1889 },
1890 )])
1891 }
1892}
1893
1894#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq)]
1896#[serde(rename_all = "snake_case")]
1897pub enum DeviceLinkFormField {
1898 Code,
1900}
1901
1902impl FormField for DeviceLinkFormField {
1903 fn keep(&self) -> bool {
1904 match self {
1905 Self::Code => true,
1906 }
1907 }
1908}
1909
1910#[derive(Serialize, Default, Debug)]
1912pub struct DeviceLinkContext {
1913 form_state: FormState<DeviceLinkFormField>,
1914}
1915
1916impl DeviceLinkContext {
1917 #[must_use]
1919 pub fn new() -> Self {
1920 Self::default()
1921 }
1922
1923 #[must_use]
1925 pub fn with_form_state(mut self, form_state: FormState<DeviceLinkFormField>) -> Self {
1926 self.form_state = form_state;
1927 self
1928 }
1929}
1930
1931impl TemplateContext for DeviceLinkContext {
1932 fn sample<R: RngExt>(
1933 _now: chrono::DateTime<Utc>,
1934 _rng: &mut R,
1935 _locales: &[DataLocale],
1936 ) -> BTreeMap<SampleIdentifier, Self>
1937 where
1938 Self: Sized,
1939 {
1940 sample_list(vec![
1941 Self::new(),
1942 Self::new().with_form_state(
1943 FormState::default()
1944 .with_error_on_field(DeviceLinkFormField::Code, FieldError::Required),
1945 ),
1946 ])
1947 }
1948}
1949
1950#[derive(Serialize, Debug)]
1952pub struct DeviceConsentContext {
1953 grant: DeviceCodeGrant,
1954 client: Client,
1955 matrix_user: MatrixUser,
1956}
1957
1958impl DeviceConsentContext {
1959 #[must_use]
1961 pub fn new(grant: DeviceCodeGrant, client: Client, matrix_user: MatrixUser) -> Self {
1962 Self {
1963 grant,
1964 client,
1965 matrix_user,
1966 }
1967 }
1968}
1969
1970impl TemplateContext for DeviceConsentContext {
1971 fn sample<R: RngExt>(
1972 now: chrono::DateTime<Utc>,
1973 rng: &mut R,
1974 _locales: &[DataLocale],
1975 ) -> BTreeMap<SampleIdentifier, Self>
1976 where
1977 Self: Sized,
1978 {
1979 sample_list(Client::samples(now, rng)
1980 .into_iter()
1981 .map(|client| {
1982 let grant = DeviceCodeGrant {
1983 id: Ulid::from_datetime_with_rng(now, rng),
1984 state: mas_data_model::DeviceCodeGrantState::Pending,
1985 client_id: client.id,
1986 scope: [OPENID].into_iter().collect(),
1987 user_code: mas_data_model::generate_user_code(rng),
1988 device_code: Alphanumeric.sample_string(rng, 32),
1989 created_at: now - Duration::try_minutes(5).unwrap(),
1990 expires_at: now + Duration::try_minutes(25).unwrap(),
1991 ip_address: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
1992 user_agent: Some("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.0.0 Safari/537.36".to_owned()),
1993 locale: None,
1994 };
1995 Self {
1996 grant,
1997 client,
1998 matrix_user: MatrixUser {
1999 mxid: "@alice:example.com".to_owned(),
2000 display_name: Some("Alice".to_owned()),
2001 }
2002 }
2003 })
2004 .collect())
2005 }
2006}
2007
2008#[derive(Serialize)]
2011pub struct AccountInactiveContext {
2012 user: User,
2013
2014 post_logout_action: Login,
2017}
2018
2019impl AccountInactiveContext {
2020 #[must_use]
2022 pub fn new(user: User) -> Self {
2023 Self {
2024 user,
2025 post_logout_action: Login::default(),
2026 }
2027 }
2028
2029 #[must_use]
2031 pub fn with_post_logout_login(mut self, login: impl Into<Login>) -> Self {
2032 self.post_logout_action = login.into();
2033 self
2034 }
2035}
2036
2037impl TemplateContext for AccountInactiveContext {
2038 fn sample<R: RngExt>(
2039 now: chrono::DateTime<Utc>,
2040 rng: &mut R,
2041 _locales: &[DataLocale],
2042 ) -> BTreeMap<SampleIdentifier, Self>
2043 where
2044 Self: Sized,
2045 {
2046 let action = PostAuthAction::continue_grant(Ulid::from_datetime_with_rng(now, rng));
2047 sample_list(
2048 User::samples(now, rng)
2049 .into_iter()
2050 .flat_map(|user| {
2051 [
2054 AccountInactiveContext::new(user.clone()),
2055 AccountInactiveContext::new(user)
2056 .with_post_logout_login(Some(action.clone())),
2057 ]
2058 })
2059 .collect(),
2060 )
2061 }
2062}
2063
2064#[derive(Serialize)]
2066pub struct DeviceNameContext {
2067 client: Client,
2068 raw_user_agent: String,
2069}
2070
2071impl DeviceNameContext {
2072 #[must_use]
2074 pub fn new(client: Client, user_agent: Option<String>) -> Self {
2075 Self {
2076 client,
2077 raw_user_agent: user_agent.unwrap_or_default(),
2078 }
2079 }
2080}
2081
2082impl TemplateContext for DeviceNameContext {
2083 fn sample<R: RngExt>(
2084 now: chrono::DateTime<Utc>,
2085 rng: &mut R,
2086 _locales: &[DataLocale],
2087 ) -> BTreeMap<SampleIdentifier, Self>
2088 where
2089 Self: Sized,
2090 {
2091 sample_list(Client::samples(now, rng)
2092 .into_iter()
2093 .map(|client| DeviceNameContext {
2094 client,
2095 raw_user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.0.0 Safari/537.36".to_owned(),
2096 })
2097 .collect())
2098 }
2099}
2100
2101#[derive(Serialize)]
2103pub struct FormPostContext<T> {
2104 redirect_uri: Option<Url>,
2105 params: T,
2106}
2107
2108impl<T: TemplateContext> TemplateContext for FormPostContext<T> {
2109 fn sample<R: RngExt>(
2110 now: chrono::DateTime<Utc>,
2111 rng: &mut R,
2112 locales: &[DataLocale],
2113 ) -> BTreeMap<SampleIdentifier, Self>
2114 where
2115 Self: Sized,
2116 {
2117 let sample_params = T::sample(now, rng, locales);
2118 sample_params
2119 .into_iter()
2120 .map(|(k, params)| {
2121 (
2122 k,
2123 FormPostContext {
2124 redirect_uri: "https://example.com/callback".parse().ok(),
2125 params,
2126 },
2127 )
2128 })
2129 .collect()
2130 }
2131}
2132
2133impl<T> FormPostContext<T> {
2134 pub fn new_for_url(redirect_uri: Url, params: T) -> Self {
2137 Self {
2138 redirect_uri: Some(redirect_uri),
2139 params,
2140 }
2141 }
2142
2143 pub fn new_for_current_url(params: T) -> Self {
2146 Self {
2147 redirect_uri: None,
2148 params,
2149 }
2150 }
2151
2152 pub fn with_language(self, lang: &DataLocale) -> WithLanguage<Self> {
2157 WithLanguage {
2158 lang: lang.to_string(),
2159 inner: self,
2160 }
2161 }
2162}
2163
2164#[derive(Default, Serialize, Debug, Clone)]
2166pub struct ErrorContext {
2167 code: Option<&'static str>,
2168 description: Option<String>,
2169 details: Option<String>,
2170 lang: Option<String>,
2171}
2172
2173impl std::fmt::Display for ErrorContext {
2174 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2175 if let Some(code) = &self.code {
2176 writeln!(f, "code: {code}")?;
2177 }
2178 if let Some(description) = &self.description {
2179 writeln!(f, "{description}")?;
2180 }
2181
2182 if let Some(details) = &self.details {
2183 writeln!(f, "details: {details}")?;
2184 }
2185
2186 Ok(())
2187 }
2188}
2189
2190impl TemplateContext for ErrorContext {
2191 fn sample<R: RngExt>(
2192 _now: chrono::DateTime<Utc>,
2193 _rng: &mut R,
2194 _locales: &[DataLocale],
2195 ) -> BTreeMap<SampleIdentifier, Self>
2196 where
2197 Self: Sized,
2198 {
2199 sample_list(vec![
2200 Self::new()
2201 .with_code("sample_error")
2202 .with_description("A fancy description".into())
2203 .with_details("Something happened".into()),
2204 Self::new().with_code("another_error"),
2205 Self::new(),
2206 ])
2207 }
2208}
2209
2210impl ErrorContext {
2211 #[must_use]
2213 pub fn new() -> Self {
2214 Self::default()
2215 }
2216
2217 #[must_use]
2219 pub fn with_code(mut self, code: &'static str) -> Self {
2220 self.code = Some(code);
2221 self
2222 }
2223
2224 #[must_use]
2226 pub fn with_description(mut self, description: String) -> Self {
2227 self.description = Some(description);
2228 self
2229 }
2230
2231 #[must_use]
2233 pub fn with_details(mut self, details: String) -> Self {
2234 self.details = Some(details);
2235 self
2236 }
2237
2238 #[must_use]
2240 pub fn with_language(mut self, lang: &DataLocale) -> Self {
2241 self.lang = Some(lang.to_string());
2242 self
2243 }
2244
2245 #[must_use]
2247 pub fn code(&self) -> Option<&'static str> {
2248 self.code
2249 }
2250
2251 #[must_use]
2253 pub fn description(&self) -> Option<&str> {
2254 self.description.as_deref()
2255 }
2256
2257 #[must_use]
2259 pub fn details(&self) -> Option<&str> {
2260 self.details.as_deref()
2261 }
2262}
2263
2264#[derive(Serialize)]
2266pub struct NotFoundContext {
2267 method: String,
2268 version: String,
2269 uri: String,
2270}
2271
2272impl NotFoundContext {
2273 #[must_use]
2275 pub fn new(method: &Method, version: Version, uri: &Uri) -> Self {
2276 Self {
2277 method: method.to_string(),
2278 version: format!("{version:?}"),
2279 uri: uri.to_string(),
2280 }
2281 }
2282}
2283
2284impl TemplateContext for NotFoundContext {
2285 fn sample<R: RngExt>(
2286 _now: DateTime<Utc>,
2287 _rng: &mut R,
2288 _locales: &[DataLocale],
2289 ) -> BTreeMap<SampleIdentifier, Self>
2290 where
2291 Self: Sized,
2292 {
2293 sample_list(vec![
2294 Self::new(&Method::GET, Version::HTTP_11, &"/".parse().unwrap()),
2295 Self::new(&Method::POST, Version::HTTP_2, &"/foo/bar".parse().unwrap()),
2296 Self::new(
2297 &Method::PUT,
2298 Version::HTTP_10,
2299 &"/foo?bar=baz".parse().unwrap(),
2300 ),
2301 ])
2302 }
2303}