1use schemars::JsonSchema;
21use serde::{Deserialize, Serialize};
22use std::fmt;
23use url::Url;
24
25#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum MethodPathError {
32 Empty,
34 InvalidFormat(String),
36}
37
38impl fmt::Display for MethodPathError {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 match self {
41 Self::Empty => write!(f, "method path is empty"),
42 Self::InvalidFormat(s) => write!(
43 f,
44 "method path {:?} does not match `^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$`",
45 s
46 ),
47 }
48 }
49}
50
51impl std::error::Error for MethodPathError {}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum IssuerUrlError {
56 InsecureScheme(String),
58}
59
60impl fmt::Display for IssuerUrlError {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 match self {
63 Self::InsecureScheme(u) => write!(
64 f,
65 "issuer URL {:?} must be https:// (or http://localhost)",
66 u
67 ),
68 }
69 }
70}
71
72impl std::error::Error for IssuerUrlError {}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
76pub enum CookieNameError {
77 Empty,
79 InvalidToken(String),
81}
82
83impl fmt::Display for CookieNameError {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 match self {
86 Self::Empty => write!(f, "cookie name is empty"),
87 Self::InvalidToken(s) => write!(
88 f,
89 "cookie name {:?} contains characters outside RFC 6265 token set",
90 s
91 ),
92 }
93 }
94}
95
96impl std::error::Error for CookieNameError {}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum HeaderNameError {
101 Empty,
103 InvalidToken(String),
105}
106
107impl fmt::Display for HeaderNameError {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 match self {
110 Self::Empty => write!(f, "header name is empty"),
111 Self::InvalidToken(s) => write!(
112 f,
113 "header name {:?} contains characters outside RFC 7230 token set",
114 s
115 ),
116 }
117 }
118}
119
120impl std::error::Error for HeaderNameError {}
121
122#[derive(Debug, Clone, PartialEq, Eq)]
124pub enum ClientIdError {
125 Empty,
127}
128
129impl fmt::Display for ClientIdError {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 match self {
132 Self::Empty => write!(f, "client_id is empty"),
133 }
134 }
135}
136
137impl std::error::Error for ClientIdError {}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
141pub enum BackendAuthCapabilitiesError {
142 DefaultOutOfRange { default: usize, len: usize },
144}
145
146impl fmt::Display for BackendAuthCapabilitiesError {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 match self {
149 Self::DefaultOutOfRange { default, len } => write!(
150 f,
151 "default index {} is out of range for mechanisms (len = {})",
152 default, len
153 ),
154 }
155 }
156}
157
158impl std::error::Error for BackendAuthCapabilitiesError {}
159
160#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)]
174#[serde(transparent)]
175pub struct MethodPath(String);
176
177impl MethodPath {
178 pub fn try_new(s: impl Into<String>) -> Result<Self, MethodPathError> {
180 let s = s.into();
181 if s.is_empty() {
182 return Err(MethodPathError::Empty);
183 }
184 if !is_valid_method_path(&s) {
185 return Err(MethodPathError::InvalidFormat(s));
186 }
187 Ok(Self(s))
188 }
189
190 pub fn as_str(&self) -> &str {
192 &self.0
193 }
194
195 pub fn activation(&self) -> &str {
198 self.0.split('.').next().expect("validated: at least one segment")
199 }
200
201 pub fn method(&self) -> &str {
204 self.0.rsplit('.').next().expect("validated: at least one segment")
205 }
206}
207
208impl fmt::Display for MethodPath {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 f.write_str(&self.0)
211 }
212}
213
214fn is_valid_method_path(s: &str) -> bool {
215 let mut segments = s.split('.');
218 let first = match segments.next() {
219 Some(seg) => seg,
220 None => return false,
221 };
222 if !is_valid_path_segment(first) {
223 return false;
224 }
225 let mut has_second_segment = false;
226 for seg in segments {
227 has_second_segment = true;
228 if !is_valid_path_segment(seg) {
229 return false;
230 }
231 }
232 has_second_segment
233}
234
235pub(crate) fn is_valid_path_segment(seg: &str) -> bool {
239 let mut chars = seg.chars();
240 let first = match chars.next() {
241 Some(c) => c,
242 None => return false, };
244 if !first.is_ascii_lowercase() {
245 return false;
246 }
247 for c in chars {
248 if !(c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') {
249 return false;
250 }
251 }
252 true
253}
254
255#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
267#[serde(transparent)]
268pub struct IssuerUrl(#[schemars(with = "String")] Url);
269
270impl IssuerUrl {
271 pub fn try_new(u: Url) -> Result<Self, IssuerUrlError> {
273 let scheme = u.scheme();
274 let is_https = scheme == "https";
275 let is_localhost_http = scheme == "http"
276 && u
277 .host_str()
278 .map(|h| h == "localhost" || h == "127.0.0.1" || h == "[::1]")
279 .unwrap_or(false);
280 if !(is_https || is_localhost_http) {
281 return Err(IssuerUrlError::InsecureScheme(u.to_string()));
282 }
283 Ok(Self(u))
284 }
285
286 pub fn as_url(&self) -> &Url {
288 &self.0
289 }
290}
291
292impl fmt::Display for IssuerUrl {
293 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294 f.write_str(self.0.as_str())
295 }
296}
297
298impl std::hash::Hash for IssuerUrl {
299 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
300 self.0.as_str().hash(state);
301 }
302}
303
304#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
312#[serde(transparent)]
313pub struct ClientId(String);
314
315impl ClientId {
316 pub fn try_new(s: impl Into<String>) -> Result<Self, ClientIdError> {
318 let s = s.into();
319 if s.is_empty() {
320 return Err(ClientIdError::Empty);
321 }
322 Ok(Self(s))
323 }
324
325 pub fn as_str(&self) -> &str {
327 &self.0
328 }
329}
330
331impl fmt::Display for ClientId {
332 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333 f.write_str(&self.0)
334 }
335}
336
337#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
347#[serde(transparent)]
348pub struct CookieName(String);
349
350impl CookieName {
351 pub fn try_new(s: impl Into<String>) -> Result<Self, CookieNameError> {
353 let s = s.into();
354 if s.is_empty() {
355 return Err(CookieNameError::Empty);
356 }
357 if !s.bytes().all(is_rfc7230_token_byte) {
358 return Err(CookieNameError::InvalidToken(s));
359 }
360 Ok(Self(s))
361 }
362
363 pub fn as_str(&self) -> &str {
365 &self.0
366 }
367}
368
369impl fmt::Display for CookieName {
370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371 f.write_str(&self.0)
372 }
373}
374
375fn is_rfc7230_token_byte(b: u8) -> bool {
381 matches!(
382 b,
383 b'!' | b'#'
384 | b'$'
385 | b'%'
386 | b'&'
387 | b'\''
388 | b'*'
389 | b'+'
390 | b'-'
391 | b'.'
392 | b'^'
393 | b'_'
394 | b'`'
395 | b'|'
396 | b'~'
397 | b'0'..=b'9'
398 | b'A'..=b'Z'
399 | b'a'..=b'z'
400 )
401}
402
403#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
413#[serde(transparent)]
414pub struct HeaderName(String);
415
416impl HeaderName {
417 pub fn try_new(s: impl Into<String>) -> Result<Self, HeaderNameError> {
420 let s = s.into();
421 if s.is_empty() {
422 return Err(HeaderNameError::Empty);
423 }
424 if !s.bytes().all(is_rfc7230_token_byte) {
425 return Err(HeaderNameError::InvalidToken(s));
426 }
427 Ok(Self(s.to_ascii_lowercase()))
428 }
429
430 pub fn as_str(&self) -> &str {
432 &self.0
433 }
434}
435
436impl fmt::Display for HeaderName {
437 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
438 f.write_str(&self.0)
439 }
440}
441
442#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
452#[serde(tag = "kind", rename_all = "snake_case")]
453pub enum AuthMechanism {
454 Bearer {
457 header: HeaderName,
459 },
460
461 Cookie {
464 cookie: CookieName,
466 login: MethodPath,
468 #[serde(skip_serializing_if = "Option::is_none", default)]
470 refresh: Option<MethodPath>,
471 #[serde(skip_serializing_if = "Option::is_none", default)]
473 logout: Option<MethodPath>,
474 },
475
476 Oidc {
478 issuer: IssuerUrl,
480 client_id: ClientId,
482 #[serde(skip_serializing_if = "Option::is_none", default)]
485 exchange: Option<MethodPath>,
486 request_scopes: Vec<String>,
490 },
491
492 Anonymous,
501}
502
503impl AuthMechanism {
504 pub fn implied_attachment_site(&self) -> Option<crate::credential::AttachmentSite> {
523 use crate::credential::AttachmentSite;
524 match self {
525 AuthMechanism::Bearer { header } => Some(AttachmentSite::Header {
526 name: header.clone(),
527 }),
528 AuthMechanism::Cookie { cookie, .. } => Some(AttachmentSite::Cookie {
529 name: cookie.clone(),
530 }),
531 AuthMechanism::Oidc { .. } => Some(AttachmentSite::Header {
532 name: HeaderName::try_new("authorization")
533 .expect("static header name is valid"),
534 }),
535 AuthMechanism::Anonymous => None,
536 }
537 }
538}
539
540#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
549pub struct BackendAuthCapabilities {
550 pub mechanisms: Vec<AuthMechanism>,
555
556 #[serde(skip_serializing_if = "Option::is_none", default)]
559 pub default: Option<usize>,
560}
561
562impl BackendAuthCapabilities {
563 pub fn new(
566 mechanisms: Vec<AuthMechanism>,
567 default: Option<usize>,
568 ) -> Result<Self, BackendAuthCapabilitiesError> {
569 if let Some(idx) = default {
570 if idx >= mechanisms.len() {
571 return Err(BackendAuthCapabilitiesError::DefaultOutOfRange {
572 default: idx,
573 len: mechanisms.len(),
574 });
575 }
576 }
577 Ok(Self {
578 mechanisms,
579 default,
580 })
581 }
582
583 pub fn anonymous_default() -> Self {
590 Self {
591 mechanisms: vec![AuthMechanism::Anonymous],
592 default: None,
593 }
594 }
595
596 pub fn implied_attachment_site(&self) -> Option<crate::credential::AttachmentSite> {
611 if let Some(site) = self
612 .default
613 .and_then(|idx| self.mechanisms.get(idx))
614 .and_then(AuthMechanism::implied_attachment_site)
615 {
616 return Some(site);
617 }
618 self.mechanisms
619 .iter()
620 .find_map(AuthMechanism::implied_attachment_site)
621 }
622}
623
624#[cfg(test)]
629mod tests {
630 use super::*;
631 use serde_json::json;
632
633 #[test]
636 fn method_path_accepts_two_segments() {
637 let m = MethodPath::try_new("auth.login").expect("valid");
638 assert_eq!(m.as_str(), "auth.login");
639 assert_eq!(m.activation(), "auth");
640 assert_eq!(m.method(), "login");
641 }
642
643 #[test]
644 fn method_path_accepts_three_segments() {
645 let m = MethodPath::try_new("cone.threads.list").expect("valid");
646 assert_eq!(m.activation(), "cone");
647 assert_eq!(m.method(), "list");
648 }
649
650 #[test]
651 fn method_path_accepts_underscored_segments() {
652 MethodPath::try_new("cone.send_message").expect("underscores ok");
653 MethodPath::try_new("a_b.c_d_e").expect("multiple underscores ok");
654 }
655
656 #[test]
657 fn method_path_rejects_single_segment() {
658 assert!(matches!(
659 MethodPath::try_new("login"),
660 Err(MethodPathError::InvalidFormat(_))
661 ));
662 }
663
664 #[test]
665 fn method_path_rejects_uppercase() {
666 assert!(matches!(
667 MethodPath::try_new("Auth.login"),
668 Err(MethodPathError::InvalidFormat(_))
669 ));
670 assert!(matches!(
671 MethodPath::try_new("auth.Login"),
672 Err(MethodPathError::InvalidFormat(_))
673 ));
674 }
675
676 #[test]
677 fn method_path_rejects_leading_digit() {
678 assert!(matches!(
679 MethodPath::try_new("1auth.login"),
680 Err(MethodPathError::InvalidFormat(_))
681 ));
682 assert!(matches!(
683 MethodPath::try_new("auth.2login"),
684 Err(MethodPathError::InvalidFormat(_))
685 ));
686 }
687
688 #[test]
689 fn method_path_rejects_trailing_dot() {
690 assert!(matches!(
691 MethodPath::try_new("auth."),
692 Err(MethodPathError::InvalidFormat(_))
693 ));
694 }
695
696 #[test]
697 fn method_path_rejects_leading_dot() {
698 assert!(matches!(
699 MethodPath::try_new(".login"),
700 Err(MethodPathError::InvalidFormat(_))
701 ));
702 }
703
704 #[test]
705 fn method_path_rejects_wildcard() {
706 assert!(matches!(
708 MethodPath::try_new("auth.*"),
709 Err(MethodPathError::InvalidFormat(_))
710 ));
711 assert!(matches!(
712 MethodPath::try_new("*"),
713 Err(MethodPathError::InvalidFormat(_))
714 ));
715 }
716
717 #[test]
718 fn method_path_rejects_empty() {
719 assert_eq!(MethodPath::try_new(""), Err(MethodPathError::Empty));
720 }
721
722 #[test]
723 fn method_path_rejects_double_dot() {
724 assert!(matches!(
725 MethodPath::try_new("auth..login"),
726 Err(MethodPathError::InvalidFormat(_))
727 ));
728 }
729
730 #[test]
731 fn method_path_serde_roundtrip() {
732 let m = MethodPath::try_new("auth.login").unwrap();
733 let s = serde_json::to_string(&m).unwrap();
734 assert_eq!(s, "\"auth.login\"");
735 let back: MethodPath = serde_json::from_str(&s).unwrap();
736 assert_eq!(back, m);
737 }
738
739 #[test]
742 fn issuer_url_accepts_https() {
743 let u: Url = "https://accounts.example.com/".parse().unwrap();
744 let i = IssuerUrl::try_new(u.clone()).expect("https ok");
745 assert_eq!(i.as_url(), &u);
746 }
747
748 #[test]
749 fn issuer_url_accepts_localhost_http() {
750 let u: Url = "http://localhost:8080/".parse().unwrap();
751 IssuerUrl::try_new(u).expect("http://localhost ok");
752 let u2: Url = "http://127.0.0.1:8080/".parse().unwrap();
753 IssuerUrl::try_new(u2).expect("http://127.0.0.1 ok");
754 let u3: Url = "http://[::1]:8080/".parse().unwrap();
755 IssuerUrl::try_new(u3).expect("http://[::1] ok");
756 }
757
758 #[test]
759 fn issuer_url_rejects_non_localhost_http() {
760 let u: Url = "http://accounts.example.com/".parse().unwrap();
761 assert!(matches!(
762 IssuerUrl::try_new(u),
763 Err(IssuerUrlError::InsecureScheme(_))
764 ));
765 }
766
767 #[test]
768 fn issuer_url_rejects_other_schemes() {
769 let u: Url = "ftp://example.com/".parse().unwrap();
770 assert!(matches!(
771 IssuerUrl::try_new(u),
772 Err(IssuerUrlError::InsecureScheme(_))
773 ));
774 }
775
776 #[test]
777 fn issuer_url_serde_roundtrip() {
778 let u: Url = "https://accounts.example.com/".parse().unwrap();
779 let i = IssuerUrl::try_new(u).unwrap();
780 let s = serde_json::to_string(&i).unwrap();
781 assert_eq!(s, "\"https://accounts.example.com/\"");
782 let back: IssuerUrl = serde_json::from_str(&s).unwrap();
783 assert_eq!(back, i);
784 }
785
786 #[test]
789 fn client_id_accepts_non_empty() {
790 let c = ClientId::try_new("plexus-substrate").unwrap();
791 assert_eq!(c.as_str(), "plexus-substrate");
792 }
793
794 #[test]
795 fn client_id_rejects_empty() {
796 assert_eq!(ClientId::try_new(""), Err(ClientIdError::Empty));
797 }
798
799 #[test]
802 fn cookie_name_accepts_valid_token() {
803 CookieName::try_new("plexus_session").unwrap();
804 CookieName::try_new("Session-Id").unwrap();
805 CookieName::try_new("a.b.c").unwrap();
806 }
807
808 #[test]
809 fn cookie_name_rejects_separator_chars() {
810 for ch in [' ', '(', ')', ',', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '{', '}', '"'] {
812 let name = format!("a{}b", ch);
813 assert!(
814 matches!(
815 CookieName::try_new(name.clone()),
816 Err(CookieNameError::InvalidToken(_))
817 ),
818 "expected reject for {:?}",
819 name
820 );
821 }
822 }
823
824 #[test]
825 fn cookie_name_rejects_empty() {
826 assert_eq!(CookieName::try_new(""), Err(CookieNameError::Empty));
827 }
828
829 #[test]
832 fn header_name_normalizes_to_lowercase() {
833 let h = HeaderName::try_new("Authorization").unwrap();
834 assert_eq!(h.as_str(), "authorization");
835
836 let h2 = HeaderName::try_new("AUTHORIZATION").unwrap();
838 let h3 = HeaderName::try_new("authorization").unwrap();
839 assert_eq!(h, h2);
840 assert_eq!(h, h3);
841 }
842
843 #[test]
844 fn header_name_rejects_invalid_chars() {
845 assert!(matches!(
846 HeaderName::try_new("X Header"),
847 Err(HeaderNameError::InvalidToken(_))
848 ));
849 assert!(matches!(
850 HeaderName::try_new("X:Header"),
851 Err(HeaderNameError::InvalidToken(_))
852 ));
853 }
854
855 #[test]
856 fn header_name_rejects_empty() {
857 assert_eq!(HeaderName::try_new(""), Err(HeaderNameError::Empty));
858 }
859
860 #[test]
863 fn auth_mechanism_bearer_round_trip() {
864 let m = AuthMechanism::Bearer {
865 header: HeaderName::try_new("authorization").unwrap(),
866 };
867 let v = serde_json::to_value(&m).unwrap();
868 assert_eq!(
869 v,
870 json!({
871 "kind": "bearer",
872 "header": "authorization"
873 })
874 );
875 let back: AuthMechanism = serde_json::from_value(v).unwrap();
876 assert_eq!(back, m);
877 }
878
879 #[test]
880 fn auth_mechanism_cookie_round_trip_minimal() {
881 let m = AuthMechanism::Cookie {
883 cookie: CookieName::try_new("plexus_session").unwrap(),
884 login: MethodPath::try_new("auth.login").unwrap(),
885 refresh: None,
886 logout: None,
887 };
888 let v = serde_json::to_value(&m).unwrap();
889 assert_eq!(
890 v,
891 json!({
892 "kind": "cookie",
893 "cookie": "plexus_session",
894 "login": "auth.login"
895 }),
896 "refresh / logout should be omitted when None"
897 );
898 let back: AuthMechanism = serde_json::from_value(v).unwrap();
899 assert_eq!(back, m);
900 }
901
902 #[test]
903 fn auth_mechanism_cookie_round_trip_full() {
904 let m = AuthMechanism::Cookie {
905 cookie: CookieName::try_new("plexus_session").unwrap(),
906 login: MethodPath::try_new("auth.login").unwrap(),
907 refresh: Some(MethodPath::try_new("auth.refresh").unwrap()),
908 logout: Some(MethodPath::try_new("auth.logout").unwrap()),
909 };
910 let v = serde_json::to_value(&m).unwrap();
911 assert_eq!(
912 v,
913 json!({
914 "kind": "cookie",
915 "cookie": "plexus_session",
916 "login": "auth.login",
917 "refresh": "auth.refresh",
918 "logout": "auth.logout"
919 })
920 );
921 let back: AuthMechanism = serde_json::from_value(v).unwrap();
922 assert_eq!(back, m);
923 }
924
925 #[test]
926 fn auth_mechanism_oidc_round_trip() {
927 let m = AuthMechanism::Oidc {
928 issuer: IssuerUrl::try_new("https://accounts.example.com/".parse().unwrap()).unwrap(),
929 client_id: ClientId::try_new("plexus-substrate").unwrap(),
930 exchange: Some(MethodPath::try_new("auth.exchange").unwrap()),
931 request_scopes: vec!["openid".into(), "profile".into(), "email".into()],
932 };
933 let v = serde_json::to_value(&m).unwrap();
934 assert_eq!(
935 v,
936 json!({
937 "kind": "oidc",
938 "issuer": "https://accounts.example.com/",
939 "client_id": "plexus-substrate",
940 "exchange": "auth.exchange",
941 "request_scopes": ["openid", "profile", "email"]
942 })
943 );
944 let back: AuthMechanism = serde_json::from_value(v).unwrap();
945 assert_eq!(back, m);
946 }
947
948 #[test]
949 fn auth_mechanism_anonymous_round_trip() {
950 let m = AuthMechanism::Anonymous;
951 let v = serde_json::to_value(&m).unwrap();
952 assert_eq!(v, json!({ "kind": "anonymous" }));
953 let back: AuthMechanism = serde_json::from_value(v).unwrap();
954 assert_eq!(back, m);
955 }
956
957 #[test]
960 fn backend_auth_capabilities_constructs_with_valid_default() {
961 let caps = BackendAuthCapabilities::new(
962 vec![
963 AuthMechanism::Bearer {
964 header: HeaderName::try_new("authorization").unwrap(),
965 },
966 AuthMechanism::Cookie {
967 cookie: CookieName::try_new("plexus_session").unwrap(),
968 login: MethodPath::try_new("auth.login").unwrap(),
969 refresh: None,
970 logout: None,
971 },
972 ],
973 Some(1),
974 )
975 .unwrap();
976 assert_eq!(caps.default, Some(1));
977 assert_eq!(caps.mechanisms.len(), 2);
978 }
979
980 #[test]
981 fn backend_auth_capabilities_rejects_out_of_range_default() {
982 let res = BackendAuthCapabilities::new(
983 vec![AuthMechanism::Anonymous],
984 Some(5),
985 );
986 assert_eq!(
987 res,
988 Err(BackendAuthCapabilitiesError::DefaultOutOfRange {
989 default: 5,
990 len: 1,
991 })
992 );
993 }
994
995 #[test]
996 fn backend_auth_capabilities_rejects_default_for_empty_mechanisms() {
997 let res = BackendAuthCapabilities::new(vec![], Some(0));
998 assert_eq!(
999 res,
1000 Err(BackendAuthCapabilitiesError::DefaultOutOfRange {
1001 default: 0,
1002 len: 0,
1003 })
1004 );
1005 }
1006
1007 #[test]
1008 fn backend_auth_capabilities_anonymous_default() {
1009 let caps = BackendAuthCapabilities::anonymous_default();
1010 assert_eq!(caps.mechanisms, vec![AuthMechanism::Anonymous]);
1011 assert_eq!(caps.default, None);
1012
1013 let v = serde_json::to_value(&caps).unwrap();
1015 assert_eq!(
1016 v,
1017 json!({
1018 "mechanisms": [{ "kind": "anonymous" }]
1019 }),
1020 "default should be omitted when None"
1021 );
1022 }
1023
1024 #[test]
1025 fn backend_auth_capabilities_full_wire_form_matches_spec() {
1026 let caps = BackendAuthCapabilities::new(
1028 vec![
1029 AuthMechanism::Bearer {
1030 header: HeaderName::try_new("authorization").unwrap(),
1031 },
1032 AuthMechanism::Cookie {
1033 cookie: CookieName::try_new("plexus_session").unwrap(),
1034 login: MethodPath::try_new("auth.login").unwrap(),
1035 refresh: Some(MethodPath::try_new("auth.refresh").unwrap()),
1036 logout: Some(MethodPath::try_new("auth.logout").unwrap()),
1037 },
1038 AuthMechanism::Oidc {
1039 issuer: IssuerUrl::try_new(
1040 "https://accounts.example.com/".parse().unwrap(),
1041 )
1042 .unwrap(),
1043 client_id: ClientId::try_new("plexus-substrate").unwrap(),
1044 exchange: Some(MethodPath::try_new("auth.exchange").unwrap()),
1045 request_scopes: vec!["openid".into(), "profile".into(), "email".into()],
1046 },
1047 ],
1048 Some(1),
1049 )
1050 .unwrap();
1051
1052 let v = serde_json::to_value(&caps).unwrap();
1053 assert_eq!(
1054 v,
1055 json!({
1056 "mechanisms": [
1057 { "kind": "bearer", "header": "authorization" },
1058 {
1059 "kind": "cookie",
1060 "cookie": "plexus_session",
1061 "login": "auth.login",
1062 "refresh": "auth.refresh",
1063 "logout": "auth.logout"
1064 },
1065 {
1066 "kind": "oidc",
1067 "issuer": "https://accounts.example.com/",
1068 "client_id": "plexus-substrate",
1069 "exchange": "auth.exchange",
1070 "request_scopes": ["openid", "profile", "email"]
1071 }
1072 ],
1073 "default": 1
1074 })
1075 );
1076
1077 let back: BackendAuthCapabilities = serde_json::from_value(v).unwrap();
1079 assert_eq!(back, caps);
1080 }
1081
1082 use crate::credential::AttachmentSite;
1085
1086 fn bearer() -> AuthMechanism {
1087 AuthMechanism::Bearer {
1088 header: HeaderName::try_new("authorization").unwrap(),
1089 }
1090 }
1091
1092 fn cookie() -> AuthMechanism {
1093 AuthMechanism::Cookie {
1094 cookie: CookieName::try_new("plexus_session").unwrap(),
1095 login: MethodPath::try_new("auth.login").unwrap(),
1096 refresh: None,
1097 logout: None,
1098 }
1099 }
1100
1101 fn oidc() -> AuthMechanism {
1102 AuthMechanism::Oidc {
1103 issuer: IssuerUrl::try_new("https://accounts.example.com/".parse().unwrap())
1104 .unwrap(),
1105 client_id: ClientId::try_new("plexus-substrate").unwrap(),
1106 exchange: None,
1107 request_scopes: vec!["openid".into()],
1108 }
1109 }
1110
1111 #[test]
1112 fn mechanism_implied_site_mapping_table() {
1113 assert_eq!(
1114 bearer().implied_attachment_site(),
1115 Some(AttachmentSite::Header {
1116 name: HeaderName::try_new("authorization").unwrap()
1117 })
1118 );
1119 assert_eq!(
1120 cookie().implied_attachment_site(),
1121 Some(AttachmentSite::Cookie {
1122 name: CookieName::try_new("plexus_session").unwrap()
1123 })
1124 );
1125 assert_eq!(
1127 oidc().implied_attachment_site(),
1128 Some(AttachmentSite::Header {
1129 name: HeaderName::try_new("authorization").unwrap()
1130 })
1131 );
1132 assert_eq!(AuthMechanism::Anonymous.implied_attachment_site(), None);
1133 }
1134
1135 #[test]
1136 fn capabilities_implied_site_prefers_default_index() {
1137 let caps = BackendAuthCapabilities::new(vec![bearer(), cookie()], Some(1)).unwrap();
1139 assert_eq!(
1140 caps.implied_attachment_site(),
1141 Some(AttachmentSite::Cookie {
1142 name: CookieName::try_new("plexus_session").unwrap()
1143 })
1144 );
1145 }
1146
1147 #[test]
1148 fn capabilities_implied_site_falls_back_to_first_siteful_mechanism() {
1149 let caps =
1151 BackendAuthCapabilities::new(vec![AuthMechanism::Anonymous, cookie(), bearer()], None)
1152 .unwrap();
1153 assert_eq!(
1154 caps.implied_attachment_site(),
1155 Some(AttachmentSite::Cookie {
1156 name: CookieName::try_new("plexus_session").unwrap()
1157 })
1158 );
1159
1160 let caps =
1162 BackendAuthCapabilities::new(vec![AuthMechanism::Anonymous, bearer()], Some(0))
1163 .unwrap();
1164 assert_eq!(
1165 caps.implied_attachment_site(),
1166 Some(AttachmentSite::Header {
1167 name: HeaderName::try_new("authorization").unwrap()
1168 })
1169 );
1170 }
1171
1172 #[test]
1173 fn capabilities_implied_site_none_for_anonymous_only_and_empty() {
1174 let anon = BackendAuthCapabilities::anonymous_default();
1175 assert_eq!(anon.implied_attachment_site(), None);
1176
1177 let empty = BackendAuthCapabilities::new(vec![], None).unwrap();
1178 assert_eq!(empty.implied_attachment_site(), None);
1179 }
1180}