1use std::collections::BTreeMap;
8
9use camino::Utf8PathBuf;
10use mas_iana::jose::JsonWebSignatureAlg;
11use schemars::JsonSchema;
12use serde::{Deserialize, Serialize, de::Error};
13use serde_with::{serde_as, skip_serializing_none};
14use ulid::Ulid;
15use url::Url;
16
17use crate::{ClientSecret, ClientSecretRaw, ConfigurationSection};
18
19#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
21pub struct UpstreamOAuth2Config {
22 pub providers: Vec<Provider>,
24}
25
26impl UpstreamOAuth2Config {
27 pub(crate) fn is_default(&self) -> bool {
29 self.providers.is_empty()
30 }
31}
32
33impl ConfigurationSection for UpstreamOAuth2Config {
34 const PATH: Option<&'static str> = Some("upstream_oauth2");
35
36 fn validate(
37 &self,
38 figment: &figment::Figment,
39 ) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
40 for (index, provider) in self.providers.iter().enumerate() {
41 let annotate = |mut error: figment::Error| {
42 error.metadata = figment
43 .find_metadata(&format!("{root}.providers", root = Self::PATH.unwrap()))
44 .cloned();
45 error.profile = Some(figment::Profile::Default);
46 error.path = vec![
47 Self::PATH.unwrap().to_owned(),
48 "providers".to_owned(),
49 index.to_string(),
50 ];
51 error
52 };
53
54 if !matches!(provider.discovery_mode, DiscoveryMode::Disabled)
55 && provider.issuer.is_none()
56 {
57 return Err(annotate(figment::Error::custom(
58 "The `issuer` field is required when discovery is enabled",
59 ))
60 .into());
61 }
62
63 match provider.token_endpoint_auth_method {
64 TokenAuthMethod::None
65 | TokenAuthMethod::PrivateKeyJwt
66 | TokenAuthMethod::SignInWithApple => {
67 if provider.client_secret.is_some() {
68 return Err(annotate(figment::Error::custom(
69 "Unexpected field `client_secret` for the selected authentication method",
70 )).into());
71 }
72 }
73 TokenAuthMethod::ClientSecretBasic
74 | TokenAuthMethod::ClientSecretPost
75 | TokenAuthMethod::ClientSecretJwt => {
76 if provider.client_secret.is_none() {
77 return Err(annotate(figment::Error::missing_field("client_secret")).into());
78 }
79 }
80 }
81
82 match provider.token_endpoint_auth_method {
83 TokenAuthMethod::None
84 | TokenAuthMethod::ClientSecretBasic
85 | TokenAuthMethod::ClientSecretPost
86 | TokenAuthMethod::SignInWithApple => {
87 if provider.token_endpoint_auth_signing_alg.is_some() {
88 return Err(annotate(figment::Error::custom(
89 "Unexpected field `token_endpoint_auth_signing_alg` for the selected authentication method",
90 )).into());
91 }
92 }
93 TokenAuthMethod::ClientSecretJwt | TokenAuthMethod::PrivateKeyJwt => {
94 if provider.token_endpoint_auth_signing_alg.is_none() {
95 return Err(annotate(figment::Error::missing_field(
96 "token_endpoint_auth_signing_alg",
97 ))
98 .into());
99 }
100 }
101 }
102
103 match provider.token_endpoint_auth_method {
104 TokenAuthMethod::SignInWithApple => {
105 if provider.sign_in_with_apple.is_none() {
106 return Err(
107 annotate(figment::Error::missing_field("sign_in_with_apple")).into(),
108 );
109 }
110 }
111
112 _ => {
113 if provider.sign_in_with_apple.is_some() {
114 return Err(annotate(figment::Error::custom(
115 "Unexpected field `sign_in_with_apple` for the selected authentication method",
116 )).into());
117 }
118 }
119 }
120
121 if provider.claims_imports.skip_confirmation {
122 if provider.claims_imports.localpart.action != ImportAction::Require {
123 return Err(annotate(figment::Error::custom(
124 "The field `action` must be `require` when `skip_confirmation` is set to `true`",
125 )).with_path("claims_imports.localpart").into());
126 }
127
128 if provider.claims_imports.email.action == ImportAction::Suggest {
129 return Err(annotate(figment::Error::custom(
130 "The field `action` must not be `suggest` when `skip_confirmation` is set to `true`",
131 )).with_path("claims_imports.email").into());
132 }
133
134 if provider.claims_imports.displayname.action == ImportAction::Suggest {
135 return Err(annotate(figment::Error::custom(
136 "The field `action` must not be `suggest` when `skip_confirmation` is set to `true`",
137 )).with_path("claims_imports.displayname").into());
138 }
139 }
140
141 if matches!(
142 provider.claims_imports.localpart.on_conflict,
143 OnConflict::Add | OnConflict::Replace | OnConflict::Set
144 ) && !matches!(
145 provider.claims_imports.localpart.action,
146 ImportAction::Force | ImportAction::Require
147 ) {
148 return Err(annotate(figment::Error::custom(
149 "The field `action` must be either `force` or `require` when `on_conflict` is set to `add`, `replace` or `set`",
150 )).with_path("claims_imports.localpart").into());
151 }
152 }
153
154 Ok(())
155 }
156}
157
158#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
160#[serde(rename_all = "snake_case")]
161pub enum ResponseMode {
162 Query,
165
166 FormPost,
171}
172
173#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
175#[serde(rename_all = "snake_case")]
176pub enum TokenAuthMethod {
177 None,
179
180 ClientSecretBasic,
183
184 ClientSecretPost,
187
188 ClientSecretJwt,
191
192 PrivateKeyJwt,
195
196 SignInWithApple,
198}
199
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
202#[serde(rename_all = "lowercase")]
203pub enum ImportAction {
204 #[default]
206 Ignore,
207
208 Suggest,
210
211 Force,
213
214 Require,
216}
217
218impl ImportAction {
219 #[expect(clippy::trivially_copy_pass_by_ref)]
220 const fn is_default(&self) -> bool {
221 matches!(self, ImportAction::Ignore)
222 }
223}
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
227#[serde(rename_all = "lowercase")]
228pub enum OnConflict {
229 #[default]
231 Fail,
232
233 Add,
236
237 Replace,
239
240 Set,
243}
244
245impl OnConflict {
246 #[expect(clippy::trivially_copy_pass_by_ref)]
247 const fn is_default(&self) -> bool {
248 matches!(self, OnConflict::Fail)
249 }
250}
251
252#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
254pub struct SubjectImportPreference {
255 #[serde(default, skip_serializing_if = "Option::is_none")]
259 pub template: Option<String>,
260}
261
262impl SubjectImportPreference {
263 const fn is_default(&self) -> bool {
264 self.template.is_none()
265 }
266}
267
268#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
270pub struct LocalpartImportPreference {
271 #[serde(default, skip_serializing_if = "ImportAction::is_default")]
273 pub action: ImportAction,
274
275 #[serde(default, skip_serializing_if = "Option::is_none")]
279 pub template: Option<String>,
280
281 #[serde(default, skip_serializing_if = "OnConflict::is_default")]
283 pub on_conflict: OnConflict,
284}
285
286impl LocalpartImportPreference {
287 const fn is_default(&self) -> bool {
288 self.action.is_default() && self.template.is_none()
289 }
290}
291
292#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
294pub struct DisplaynameImportPreference {
295 #[serde(default, skip_serializing_if = "ImportAction::is_default")]
297 pub action: ImportAction,
298
299 #[serde(default, skip_serializing_if = "Option::is_none")]
303 pub template: Option<String>,
304}
305
306impl DisplaynameImportPreference {
307 const fn is_default(&self) -> bool {
308 self.action.is_default() && self.template.is_none()
309 }
310}
311
312#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
314pub struct EmailImportPreference {
315 #[serde(default, skip_serializing_if = "ImportAction::is_default")]
317 pub action: ImportAction,
318
319 #[serde(default, skip_serializing_if = "Option::is_none")]
323 pub template: Option<String>,
324}
325
326impl EmailImportPreference {
327 const fn is_default(&self) -> bool {
328 self.action.is_default() && self.template.is_none()
329 }
330}
331
332#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
334pub struct AccountNameImportPreference {
335 #[serde(default, skip_serializing_if = "Option::is_none")]
340 pub template: Option<String>,
341}
342
343impl AccountNameImportPreference {
344 const fn is_default(&self) -> bool {
345 self.template.is_none()
346 }
347}
348
349#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
351pub struct ClaimsImports {
352 #[serde(default, skip_serializing_if = "SubjectImportPreference::is_default")]
354 pub subject: SubjectImportPreference,
355
356 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
361 pub skip_confirmation: bool,
362
363 #[serde(default, skip_serializing_if = "LocalpartImportPreference::is_default")]
365 pub localpart: LocalpartImportPreference,
366
367 #[serde(
369 default,
370 skip_serializing_if = "DisplaynameImportPreference::is_default"
371 )]
372 pub displayname: DisplaynameImportPreference,
373
374 #[serde(default, skip_serializing_if = "EmailImportPreference::is_default")]
376 pub email: EmailImportPreference,
377
378 #[serde(
380 default,
381 skip_serializing_if = "AccountNameImportPreference::is_default"
382 )]
383 pub account_name: AccountNameImportPreference,
384}
385
386impl ClaimsImports {
387 const fn is_default(&self) -> bool {
388 self.subject.is_default()
389 && self.localpart.is_default()
390 && !self.skip_confirmation
391 && self.displayname.is_default()
392 && self.email.is_default()
393 && self.account_name.is_default()
394 }
395}
396
397#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, Default)]
399#[serde(rename_all = "snake_case")]
400pub enum DiscoveryMode {
401 #[default]
403 Oidc,
404
405 Insecure,
407
408 Disabled,
410}
411
412impl DiscoveryMode {
413 #[expect(clippy::trivially_copy_pass_by_ref)]
414 const fn is_default(&self) -> bool {
415 matches!(self, DiscoveryMode::Oidc)
416 }
417}
418
419#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, Default)]
422#[serde(rename_all = "snake_case")]
423pub enum PkceMethod {
424 #[default]
428 Auto,
429
430 Always,
432
433 Never,
435}
436
437impl PkceMethod {
438 #[expect(clippy::trivially_copy_pass_by_ref)]
439 const fn is_default(&self) -> bool {
440 matches!(self, PkceMethod::Auto)
441 }
442}
443
444fn default_true() -> bool {
445 true
446}
447
448#[expect(clippy::trivially_copy_pass_by_ref)]
449fn is_default_true(value: &bool) -> bool {
450 *value
451}
452
453fn is_signed_response_alg_default(signed_response_alg: &JsonWebSignatureAlg) -> bool {
454 *signed_response_alg == signed_response_alg_default()
455}
456
457fn signed_response_alg_default() -> JsonWebSignatureAlg {
458 JsonWebSignatureAlg::Rs256
459}
460
461#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
462pub struct SignInWithApple {
463 #[serde(skip_serializing_if = "Option::is_none")]
465 #[schemars(with = "Option<String>")]
466 pub private_key_file: Option<Utf8PathBuf>,
467
468 #[serde(skip_serializing_if = "Option::is_none")]
470 pub private_key: Option<String>,
471
472 pub team_id: String,
474
475 pub key_id: String,
477}
478
479fn default_scope() -> String {
480 "openid".to_owned()
481}
482
483fn is_default_scope(scope: &str) -> bool {
484 scope == default_scope()
485}
486
487#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, Default)]
489#[serde(rename_all = "snake_case")]
490pub enum OnBackchannelLogout {
491 #[default]
493 DoNothing,
494
495 LogoutBrowserOnly,
497
498 LogoutAll,
501}
502
503impl OnBackchannelLogout {
504 #[expect(clippy::trivially_copy_pass_by_ref)]
505 const fn is_default(&self) -> bool {
506 matches!(self, OnBackchannelLogout::DoNothing)
507 }
508}
509
510#[serde_as]
512#[skip_serializing_none]
513#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
514pub struct Provider {
515 #[serde(default = "default_true", skip_serializing_if = "is_default_true")]
519 pub enabled: bool,
520
521 #[schemars(
523 with = "String",
524 regex(pattern = r"^[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}$"),
525 description = "A ULID as per https://github.com/ulid/spec"
526 )]
527 pub id: Ulid,
528
529 #[serde(skip_serializing_if = "Option::is_none")]
544 pub synapse_idp_id: Option<String>,
545
546 #[serde(skip_serializing_if = "Option::is_none")]
550 pub issuer: Option<String>,
551
552 #[serde(skip_serializing_if = "Option::is_none")]
554 pub human_name: Option<String>,
555
556 #[serde(skip_serializing_if = "Option::is_none")]
569 pub brand_name: Option<String>,
570
571 pub client_id: String,
573
574 #[schemars(with = "ClientSecretRaw")]
579 #[serde_as(as = "serde_with::TryFromInto<ClientSecretRaw>")]
580 #[serde(flatten)]
581 pub client_secret: Option<ClientSecret>,
582
583 pub token_endpoint_auth_method: TokenAuthMethod,
585
586 #[serde(skip_serializing_if = "Option::is_none")]
588 pub sign_in_with_apple: Option<SignInWithApple>,
589
590 #[serde(skip_serializing_if = "Option::is_none")]
595 pub token_endpoint_auth_signing_alg: Option<JsonWebSignatureAlg>,
596
597 #[serde(
602 default = "signed_response_alg_default",
603 skip_serializing_if = "is_signed_response_alg_default"
604 )]
605 pub id_token_signed_response_alg: JsonWebSignatureAlg,
606
607 #[serde(default = "default_scope", skip_serializing_if = "is_default_scope")]
611 pub scope: String,
612
613 #[serde(default, skip_serializing_if = "DiscoveryMode::is_default")]
618 pub discovery_mode: DiscoveryMode,
619
620 #[serde(default, skip_serializing_if = "PkceMethod::is_default")]
625 pub pkce_method: PkceMethod,
626
627 #[serde(default)]
633 pub fetch_userinfo: bool,
634
635 #[serde(skip_serializing_if = "Option::is_none")]
641 pub userinfo_signed_response_alg: Option<JsonWebSignatureAlg>,
642
643 #[serde(skip_serializing_if = "Option::is_none")]
647 pub authorization_endpoint: Option<Url>,
648
649 #[serde(skip_serializing_if = "Option::is_none")]
653 pub userinfo_endpoint: Option<Url>,
654
655 #[serde(skip_serializing_if = "Option::is_none")]
659 pub token_endpoint: Option<Url>,
660
661 #[serde(skip_serializing_if = "Option::is_none")]
665 pub jwks_uri: Option<Url>,
666
667 #[serde(skip_serializing_if = "Option::is_none")]
669 pub response_mode: Option<ResponseMode>,
670
671 #[serde(default, skip_serializing_if = "ClaimsImports::is_default")]
674 pub claims_imports: ClaimsImports,
675
676 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
680 pub additional_authorization_parameters: BTreeMap<String, String>,
681
682 #[serde(default)]
687 pub forward_login_hint: bool,
688
689 #[serde(default, skip_serializing_if = "OnBackchannelLogout::is_default")]
693 pub on_backchannel_logout: OnBackchannelLogout,
694}
695
696impl Provider {
697 pub async fn client_secret(&self) -> anyhow::Result<Option<String>> {
705 Ok(match &self.client_secret {
706 Some(client_secret) => Some(client_secret.value().await?),
707 None => None,
708 })
709 }
710}
711
712#[cfg(test)]
713mod tests {
714 use std::str::FromStr;
715
716 use figment::{
717 Figment, Jail,
718 providers::{Format, Yaml},
719 };
720 use tokio::{runtime::Handle, task};
721
722 use super::*;
723
724 #[tokio::test]
725 async fn load_config() {
726 task::spawn_blocking(|| {
727 Jail::expect_with(|jail| {
728 jail.create_file(
729 "config.yaml",
730 r#"
731 upstream_oauth2:
732 providers:
733 - id: 01GFWR28C4KNE04WG3HKXB7C9R
734 client_id: upstream-oauth2
735 token_endpoint_auth_method: none
736
737 - id: 01GFWR32NCQ12B8Z0J8CPXRRB6
738 client_id: upstream-oauth2
739 client_secret_file: secret
740 token_endpoint_auth_method: client_secret_basic
741
742 - id: 01GFWR3WHR93Y5HK389H28VHZ9
743 client_id: upstream-oauth2
744 client_secret: c1!3n753c237
745 token_endpoint_auth_method: client_secret_post
746
747 - id: 01GFWR43R2ZZ8HX9CVBNW9TJWG
748 client_id: upstream-oauth2
749 client_secret_file: secret
750 token_endpoint_auth_method: client_secret_jwt
751
752 - id: 01GFWR4BNFDCC4QDG6AMSP1VRR
753 client_id: upstream-oauth2
754 token_endpoint_auth_method: private_key_jwt
755 jwks:
756 keys:
757 - kid: "03e84aed4ef4431014e8617567864c4efaaaede9"
758 kty: "RSA"
759 alg: "RS256"
760 use: "sig"
761 e: "AQAB"
762 n: "ma2uRyBeSEOatGuDpCiV9oIxlDWix_KypDYuhQfEzqi_BiF4fV266OWfyjcABbam59aJMNvOnKW3u_eZM-PhMCBij5MZ-vcBJ4GfxDJeKSn-GP_dJ09rpDcILh8HaWAnPmMoi4DC0nrfE241wPISvZaaZnGHkOrfN_EnA5DligLgVUbrA5rJhQ1aSEQO_gf1raEOW3DZ_ACU3qhtgO0ZBG3a5h7BPiRs2sXqb2UCmBBgwyvYLDebnpE7AotF6_xBIlR-Cykdap3GHVMXhrIpvU195HF30ZoBU4dMd-AeG6HgRt4Cqy1moGoDgMQfbmQ48Hlunv9_Vi2e2CLvYECcBw"
763
764 - kid: "d01c1abe249269f72ef7ca2613a86c9f05e59567"
765 kty: "RSA"
766 alg: "RS256"
767 use: "sig"
768 e: "AQAB"
769 n: "0hukqytPwrj1RbMYhYoepCi3CN5k7DwYkTe_Cmb7cP9_qv4ok78KdvFXt5AnQxCRwBD7-qTNkkfMWO2RxUMBdQD0ED6tsSb1n5dp0XY8dSWiBDCX8f6Hr-KolOpvMLZKRy01HdAWcM6RoL9ikbjYHUEW1C8IJnw3MzVHkpKFDL354aptdNLaAdTCBvKzU9WpXo10g-5ctzSlWWjQuecLMQ4G1mNdsR1LHhUENEnOvgT8cDkX0fJzLbEbyBYkdMgKggyVPEB1bg6evG4fTKawgnf0IDSPxIU-wdS9wdSP9ZCJJPLi5CEp-6t6rE_sb2dGcnzjCGlembC57VwpkUvyMw"
770 "#,
771 )?;
772 jail.create_file("secret", r"c1!3n753c237")?;
773
774 let config = Figment::new()
775 .merge(Yaml::file("config.yaml"))
776 .extract_inner::<UpstreamOAuth2Config>("upstream_oauth2")?;
777
778 assert_eq!(config.providers.len(), 5);
779
780 assert_eq!(
781 config.providers[1].id,
782 Ulid::from_str("01GFWR32NCQ12B8Z0J8CPXRRB6").unwrap()
783 );
784
785 assert!(config.providers[0].client_secret.is_none());
786 assert!(matches!(config.providers[1].client_secret, Some(ClientSecret::File(ref p)) if p == "secret"));
787 assert!(matches!(config.providers[2].client_secret, Some(ClientSecret::Value(ref v)) if v == "c1!3n753c237"));
788 assert!(matches!(config.providers[3].client_secret, Some(ClientSecret::File(ref p)) if p == "secret"));
789 assert!(config.providers[4].client_secret.is_none());
790
791 Handle::current().block_on(async move {
792 assert_eq!(config.providers[1].client_secret().await.unwrap().unwrap(), "c1!3n753c237");
793 assert_eq!(config.providers[2].client_secret().await.unwrap().unwrap(), "c1!3n753c237");
794 assert_eq!(config.providers[3].client_secret().await.unwrap().unwrap(), "c1!3n753c237");
795 });
796
797 Ok(())
798 });
799 }).await.unwrap();
800 }
801}