1use crate::program::TOP;
27use serde::Deserialize;
28use std::fmt;
29use std::time::Duration;
30use url::Url;
31
32pub const LOGIN_SCOPE: &str = "openid profile email offline_access";
36
37const DEVICE_CODE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";
39
40const SLOW_DOWN_INCREMENT_SECS: u64 = 5;
43
44const DEFAULT_POLL_INTERVAL_SECS: u64 = 5;
47
48#[derive(Debug, Clone)]
54pub struct PublicConfig {
55 pub issuer: String,
56 pub cli_client_id: String,
57 pub audience: Option<String>,
61 pub bazaar_mcp_url: Option<String>,
64}
65
66#[derive(Deserialize)]
72struct PublicConfigWire {
73 #[serde(default)]
74 oidc_enabled: bool,
75 #[serde(default)]
76 issuer: Option<String>,
77 #[serde(default)]
78 cli_client_id: Option<String>,
79 #[serde(default)]
80 audience: Option<String>,
81 #[serde(default)]
82 bazaar_mcp_url: Option<String>,
83}
84
85#[derive(Debug, Clone)]
93pub struct Discovery {
94 pub device_authorization_endpoint: Option<String>,
95 pub token_endpoint: String,
96 pub revocation_endpoint: Option<String>,
97}
98
99#[derive(Deserialize)]
102struct DiscoveryDoc {
103 issuer: String,
104 #[serde(default)]
105 device_authorization_endpoint: Option<String>,
106 token_endpoint: String,
107 #[serde(default)]
108 revocation_endpoint: Option<String>,
109}
110
111#[derive(Clone, Deserialize)]
113pub struct DeviceAuth {
114 pub device_code: String,
116 pub user_code: String,
119 pub verification_uri: String,
120 #[serde(default)]
121 pub verification_uri_complete: Option<String>,
122 #[serde(default = "default_device_expires_in")]
123 pub expires_in: u64,
124 #[serde(default = "default_interval")]
125 pub interval: u64,
126}
127
128fn default_device_expires_in() -> u64 {
129 600
130}
131
132fn default_interval() -> u64 {
133 DEFAULT_POLL_INTERVAL_SECS
134}
135
136impl fmt::Debug for DeviceAuth {
138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139 f.debug_struct("DeviceAuth")
140 .field("device_code", &"<redacted>")
141 .field("user_code", &self.user_code)
142 .field("verification_uri", &self.verification_uri)
143 .field(
144 "verification_uri_complete",
145 &self.verification_uri_complete.is_some(),
146 )
147 .field("expires_in", &self.expires_in)
148 .field("interval", &self.interval)
149 .finish()
150 }
151}
152
153#[derive(Clone, Deserialize)]
160pub struct TokenSet {
161 pub access_token: String,
163 #[serde(default)]
165 pub refresh_token: Option<String>,
166 #[serde(default)]
167 pub expires_in: i64,
168}
169
170impl TokenSet {
171 pub fn access_expires_at(&self, now: i64) -> i64 {
175 now.saturating_add(self.expires_in)
176 }
177}
178
179impl fmt::Debug for TokenSet {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 f.debug_struct("TokenSet")
183 .field("access_token", &"<redacted>")
184 .field(
185 "refresh_token",
186 &self.refresh_token.as_ref().map(|_| "<redacted>"),
187 )
188 .field("expires_in", &self.expires_in)
189 .finish()
190 }
191}
192
193#[derive(Deserialize)]
195struct OauthErrorBody {
196 error: String,
197 #[serde(default)]
198 error_description: Option<String>,
199}
200
201#[derive(Debug)]
206pub enum OidcError {
207 NoKeycloak,
212 IdpUnavailable { detail: String },
216 IssuerMismatch { expected: String, found: String },
220 SessionExpired,
222 AccessDenied,
224 DeviceCodeExpired,
226 PollTimeout { waited_secs: u64 },
228 EndpointUnavailable { what: &'static str },
230 InsecureIssuer { issuer: String },
233 EndpointOriginMismatch {
236 what: &'static str,
237 endpoint: String,
238 issuer: String,
239 },
240 Oauth {
242 error: String,
243 description: Option<String>,
244 },
245 Transport(String),
247}
248
249impl fmt::Display for OidcError {
250 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251 match self {
252 Self::NoKeycloak => write!(
253 f,
254 "this Visdom server has no Keycloak/SSO configured, so interactive login is \
255 unavailable"
256 ),
257 Self::IdpUnavailable { detail } => write!(
258 f,
259 "the identity provider is temporarily unavailable ({detail}) — this is not a \
260 configuration problem; retry `{TOP} login` in a moment"
261 ),
262 Self::IssuerMismatch { expected, found } => write!(
263 f,
264 "issuer mismatch: the server said the issuer is '{expected}', but its discovery \
265 document identifies itself as '{found}'"
266 ),
267 Self::SessionExpired => write!(
268 f,
269 "your session has expired — run `{TOP} login` to sign in again"
270 ),
271 Self::AccessDenied => write!(f, "the login was denied in the browser (access_denied)"),
272 Self::DeviceCodeExpired => write!(
273 f,
274 "the login code expired before it was approved — run `{TOP} login` again"
275 ),
276 Self::PollTimeout { waited_secs } => write!(
277 f,
278 "gave up waiting for browser approval after {waited_secs}s — run \
279 `{TOP} login` again"
280 ),
281 Self::EndpointUnavailable { what } => write!(
282 f,
283 "the identity provider does not advertise a {what} endpoint"
284 ),
285 Self::InsecureIssuer { issuer } => write!(
286 f,
287 "refusing to use the insecure issuer '{issuer}': signing in would send a \
288 long-lived refresh token over an unencrypted connection. Use an https issuer \
289 (http is allowed only for a loopback address during local development)."
290 ),
291 Self::EndpointOriginMismatch {
292 what,
293 endpoint,
294 issuer,
295 } => write!(
296 f,
297 "the identity provider's discovery document points its {what} endpoint at \
298 '{endpoint}', which is not the issuer's origin ('{issuer}'). Refusing, rather \
299 than sending credentials to an unrelated host."
300 ),
301 Self::Oauth { error, description } => match description {
302 Some(d) => write!(f, "identity provider rejected the request: {error} ({d})"),
303 None => write!(f, "identity provider rejected the request: {error}"),
304 },
305 Self::Transport(m) => write!(f, "{m}"),
306 }
307 }
308}
309
310impl std::error::Error for OidcError {}
311
312pub fn canonical_issuer(issuer: &str) -> String {
317 issuer.trim().trim_end_matches('/').to_string()
318}
319
320pub async fn fetch_public_config(
344 client: &reqwest::Client,
345 server_url: &str,
346) -> Result<PublicConfig, OidcError> {
347 let url = format!(
348 "{}/api/v1/auth/public-config",
349 server_url.trim_end_matches('/')
350 );
351 let resp = client.get(&url).send().await.map_err(transport)?;
352 let status = resp.status();
353
354 if status.is_server_error() {
355 return Err(OidcError::IdpUnavailable {
356 detail: format!("server returned {status}"),
357 });
358 }
359 if !status.is_success() {
360 return Err(OidcError::Transport(format!("GET {url} returned {status}")));
361 }
362
363 let wire: PublicConfigWire = resp
364 .json()
365 .await
366 .map_err(|e| OidcError::Transport(format!("malformed auth public-config response: {e}")))?;
367
368 if !wire.oidc_enabled {
369 return Err(OidcError::NoKeycloak);
370 }
371 let missing = |field: &'static str| {
372 OidcError::Transport(format!(
373 "the server reports SSO is enabled but its auth public-config omits `{field}` — the \
374 server is misconfigured; report this to whoever operates it"
375 ))
376 };
377 Ok(PublicConfig {
378 issuer: wire
379 .issuer
380 .filter(|s| !s.trim().is_empty())
381 .ok_or_else(|| missing("issuer"))?,
382 cli_client_id: wire
383 .cli_client_id
384 .filter(|s| !s.trim().is_empty())
385 .ok_or_else(|| missing("cli_client_id"))?,
386 audience: wire.audience.filter(|s| !s.trim().is_empty()),
387 bazaar_mcp_url: wire.bazaar_mcp_url.filter(|s| !s.trim().is_empty()),
388 })
389}
390
391pub async fn discover(client: &reqwest::Client, issuer: &str) -> Result<Discovery, OidcError> {
406 let expected = canonical_issuer(issuer);
407 let issuer_url = Url::parse(&expected).map_err(|e| {
408 OidcError::Transport(format!("'{expected}' is not a valid issuer URL: {e}"))
409 })?;
410 require_secure(&issuer_url)?;
411
412 let url = format!("{expected}/.well-known/openid-configuration");
413 let resp = client.get(&url).send().await.map_err(transport)?;
414 let status = resp.status();
415 if !status.is_success() {
416 return Err(OidcError::Transport(format!("GET {url} returned {status}")));
417 }
418 let doc: DiscoveryDoc = resp
419 .json()
420 .await
421 .map_err(|e| OidcError::Transport(format!("malformed discovery document: {e}")))?;
422
423 let found = canonical_issuer(&doc.issuer);
424 if found != expected {
425 return Err(OidcError::IssuerMismatch { expected, found });
426 }
427
428 let origin = issuer_url.origin();
429 let checked =
430 |endpoint: Option<String>, what: &'static str| -> Result<Option<String>, OidcError> {
431 let Some(endpoint) = endpoint else {
432 return Ok(None);
433 };
434 let parsed = Url::parse(&endpoint).map_err(|e| {
435 OidcError::Transport(format!(
436 "the discovery document's {what} endpoint '{endpoint}' is not a valid URL: {e}"
437 ))
438 })?;
439 if parsed.origin() != origin {
440 return Err(OidcError::EndpointOriginMismatch {
441 what,
442 endpoint,
443 issuer: expected.clone(),
444 });
445 }
446 Ok(Some(endpoint))
447 };
448
449 let token_endpoint = checked(Some(doc.token_endpoint), "token")?
450 .expect("checked() returns Some for a Some input");
451 Ok(Discovery {
452 device_authorization_endpoint: checked(
453 doc.device_authorization_endpoint,
454 "device authorization",
455 )?,
456 token_endpoint,
457 revocation_endpoint: checked(doc.revocation_endpoint, "revocation")?,
458 })
459}
460
461fn require_secure(issuer: &Url) -> Result<(), OidcError> {
468 if issuer.scheme() == "https" || is_loopback_host(issuer) {
469 return Ok(());
470 }
471 Err(OidcError::InsecureIssuer {
472 issuer: issuer.to_string(),
473 })
474}
475
476fn is_loopback_host(url: &Url) -> bool {
478 match url.host() {
479 Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
480 Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
481 Some(url::Host::Domain(d)) => d == "localhost" || d.ends_with(".localhost"),
482 None => false,
483 }
484}
485
486pub fn is_browser_safe(url: &str) -> bool {
493 Url::parse(url)
494 .map(|u| matches!(u.scheme(), "http" | "https"))
495 .unwrap_or(false)
496}
497
498pub async fn device_start(
501 client: &reqwest::Client,
502 discovery: &Discovery,
503 client_id: &str,
504) -> Result<DeviceAuth, OidcError> {
505 let endpoint = discovery.device_authorization_endpoint.as_deref().ok_or(
506 OidcError::EndpointUnavailable {
507 what: "device authorization",
508 },
509 )?;
510 let resp = post_form(
511 client,
512 endpoint,
513 &[("client_id", client_id), ("scope", LOGIN_SCOPE)],
514 )
515 .send()
516 .await
517 .map_err(transport)?;
518 let status = resp.status();
519 if !status.is_success() {
520 let body = resp.text().await.unwrap_or_default();
523 return Err(
524 oauth_error_from_body(&body).unwrap_or(OidcError::Transport(format!(
525 "device authorization request returned {status}"
526 ))),
527 );
528 }
529 resp.json::<DeviceAuth>()
530 .await
531 .map_err(|e| OidcError::Transport(format!("malformed device authorization response: {e}")))
532}
533
534pub async fn poll_token_with<S, F>(
542 client: &reqwest::Client,
543 discovery: &Discovery,
544 client_id: &str,
545 device: &DeviceAuth,
546 mut sleep: S,
547) -> Result<TokenSet, OidcError>
548where
549 S: FnMut(Duration) -> F,
550 F: std::future::Future<Output = ()>,
551{
552 let mut interval = if device.interval == 0 {
553 DEFAULT_POLL_INTERVAL_SECS
554 } else {
555 device.interval
556 };
557 let mut waited: u64 = 0;
558
559 loop {
560 sleep(Duration::from_secs(interval)).await;
561 waited = waited.saturating_add(interval);
562
563 let attempt = token_request(
564 client,
565 &discovery.token_endpoint,
566 &[
567 ("grant_type", DEVICE_CODE_GRANT),
568 ("client_id", client_id),
569 ("device_code", &device.device_code),
570 ],
571 )
572 .await;
573
574 match attempt {
575 Ok(tokens) => return Ok(tokens),
576 Err(OidcError::Oauth { error, description }) => match error.as_str() {
577 "authorization_pending" => {}
579 "slow_down" => interval = interval.saturating_add(SLOW_DOWN_INCREMENT_SECS),
581 "access_denied" => return Err(OidcError::AccessDenied),
582 "expired_token" => return Err(OidcError::DeviceCodeExpired),
583 _ => return Err(OidcError::Oauth { error, description }),
584 },
585 Err(e) => return Err(e),
588 }
589
590 if waited >= device.expires_in {
593 return Err(OidcError::PollTimeout {
594 waited_secs: waited,
595 });
596 }
597 }
598}
599
600pub async fn refresh(
602 client: &reqwest::Client,
603 discovery: &Discovery,
604 client_id: &str,
605 refresh_token: &str,
606) -> Result<TokenSet, OidcError> {
607 let result = token_request(
608 client,
609 &discovery.token_endpoint,
610 &[
611 ("grant_type", "refresh_token"),
612 ("client_id", client_id),
613 ("refresh_token", refresh_token),
614 ],
615 )
616 .await;
617
618 match result {
619 Err(OidcError::Oauth { error, .. }) if error == "invalid_grant" => {
623 Err(OidcError::SessionExpired)
624 }
625 other => other,
626 }
627}
628
629pub async fn revoke(
633 client: &reqwest::Client,
634 discovery: &Discovery,
635 client_id: &str,
636 refresh_token: &str,
637) -> Result<(), OidcError> {
638 let endpoint = discovery
639 .revocation_endpoint
640 .as_deref()
641 .ok_or(OidcError::EndpointUnavailable { what: "revocation" })?;
642 let resp = post_form(
643 client,
644 endpoint,
645 &[
646 ("client_id", client_id),
647 ("token", refresh_token),
648 ("token_type_hint", "refresh_token"),
649 ],
650 )
651 .send()
652 .await
653 .map_err(transport)?;
654 let status = resp.status();
655 if !status.is_success() {
656 return Err(OidcError::Transport(format!(
657 "revocation endpoint returned {status}"
658 )));
659 }
660 Ok(())
661}
662
663async fn token_request(
670 client: &reqwest::Client,
671 token_endpoint: &str,
672 form: &[(&str, &str)],
673) -> Result<TokenSet, OidcError> {
674 let resp = post_form(client, token_endpoint, form)
675 .send()
676 .await
677 .map_err(transport)?;
678 let status = resp.status();
679
680 if status.is_success() {
681 return resp
685 .json::<TokenSet>()
686 .await
687 .map_err(|e| OidcError::Transport(format!("malformed token response: {e}")));
688 }
689
690 let body = resp.text().await.unwrap_or_default();
691 Err(
692 oauth_error_from_body(&body).unwrap_or(OidcError::Transport(format!(
693 "token endpoint returned {status}"
694 ))),
695 )
696}
697
698fn oauth_error_from_body(body: &str) -> Option<OidcError> {
701 serde_json::from_str::<OauthErrorBody>(body)
702 .ok()
703 .map(|b| OidcError::Oauth {
704 error: b.error,
705 description: b.error_description,
706 })
707}
708
709fn transport(e: reqwest::Error) -> OidcError {
710 OidcError::Transport(format!("network error: {e}"))
711}
712
713pub fn unverified_audiences(access_token: &str) -> Option<Vec<String>> {
725 let payload = access_token.split('.').nth(1)?;
726 let json = base64url_decode(payload)?;
727 let claims: serde_json::Value = serde_json::from_slice(&json).ok()?;
728 match claims.get("aud")? {
729 serde_json::Value::String(one) => Some(vec![one.clone()]),
730 serde_json::Value::Array(many) => Some(
731 many.iter()
732 .filter_map(|v| v.as_str().map(String::from))
733 .collect(),
734 ),
735 _ => None,
736 }
737}
738
739fn base64url_decode(input: &str) -> Option<Vec<u8>> {
742 let mut out = Vec::with_capacity(input.len() * 3 / 4);
743 let mut acc: u32 = 0;
744 let mut bits: u32 = 0;
745 for byte in input.bytes() {
746 let value = match byte {
747 b'A'..=b'Z' => byte - b'A',
748 b'a'..=b'z' => byte - b'a' + 26,
749 b'0'..=b'9' => byte - b'0' + 52,
750 b'-' => 62,
751 b'_' => 63,
752 b'=' => break,
754 _ => return None,
755 } as u32;
756 acc = (acc << 6) | value;
757 bits += 6;
758 if bits >= 8 {
759 bits -= 8;
760 out.push((acc >> bits) as u8);
761 }
762 }
763 Some(out)
764}
765
766fn post_form(
774 client: &reqwest::Client,
775 url: &str,
776 pairs: &[(&str, &str)],
777) -> reqwest::RequestBuilder {
778 let body = url::form_urlencoded::Serializer::new(String::new())
779 .extend_pairs(pairs)
780 .finish();
781 client
782 .post(url)
783 .header(
784 reqwest::header::CONTENT_TYPE,
785 "application/x-www-form-urlencoded",
786 )
787 .body(body)
788}
789
790#[cfg(test)]
791mod tests {
792 use super::*;
793 use crate::test_helpers::{http_json, spawn_seq, RECV_TIMEOUT};
794 use std::sync::{Arc, Mutex};
795
796 fn discovery_at(base: &str) -> Discovery {
798 Discovery {
799 device_authorization_endpoint: Some(format!("{base}/device")),
800 token_endpoint: format!("{base}/token"),
801 revocation_endpoint: Some(format!("{base}/revoke")),
802 }
803 }
804
805 fn device_auth(interval: u64, expires_in: u64) -> DeviceAuth {
806 DeviceAuth {
807 device_code: "dev-code".into(),
808 user_code: "WDJB-MJHT".into(),
809 verification_uri: "https://idp.test/device".into(),
810 verification_uri_complete: None,
811 expires_in,
812 interval,
813 }
814 }
815
816 fn recording_sleep(
819 log: Arc<Mutex<Vec<u64>>>,
820 ) -> impl FnMut(Duration) -> std::future::Ready<()> {
821 move |d| {
822 log.lock().unwrap().push(d.as_secs());
823 std::future::ready(())
824 }
825 }
826
827 #[tokio::test]
828 async fn poll_retries_on_authorization_pending_then_succeeds() {
829 let (base, rx) = spawn_seq(vec![
830 http_json("400 Bad Request", r#"{"error":"authorization_pending"}"#),
831 http_json(
832 "200 OK",
833 r#"{"access_token":"at","refresh_token":"rt","expires_in":300}"#,
834 ),
835 ]);
836 let log = Arc::new(Mutex::new(Vec::new()));
837 let client = reqwest::Client::new();
838 let tokens = poll_token_with(
839 &client,
840 &discovery_at(&base),
841 "tracing-cli",
842 &device_auth(5, 600),
843 recording_sleep(log.clone()),
844 )
845 .await
846 .expect("a pending poll followed by success must succeed");
847
848 assert_eq!(tokens.access_token, "at");
849 assert_eq!(tokens.refresh_token.as_deref(), Some("rt"));
850 let first = rx.recv_timeout(RECV_TIMEOUT).expect("no first poll");
852 let second = rx.recv_timeout(RECV_TIMEOUT).expect("no second poll");
853 for req in [&first, &second] {
854 assert!(req.contains("POST /token"), "unexpected request: {req}");
855 assert!(
856 req.contains("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code"),
857 "poll must use the device_code grant: {req}"
858 );
859 assert!(req.contains("device_code=dev-code"), "missing device_code");
860 assert!(req.contains("client_id=tracing-cli"), "missing client_id");
861 assert!(
862 !req.contains("client_secret"),
863 "tracing-cli is a PUBLIC client; no secret may be sent: {req}"
864 );
865 }
866 assert_eq!(*log.lock().unwrap(), vec![5, 5]);
867 }
868
869 #[tokio::test]
870 async fn slow_down_raises_interval_by_five_seconds() {
871 let (base, _rx) = spawn_seq(vec![
872 http_json("400 Bad Request", r#"{"error":"slow_down"}"#),
873 http_json("400 Bad Request", r#"{"error":"authorization_pending"}"#),
874 http_json("200 OK", r#"{"access_token":"at","expires_in":300}"#),
875 ]);
876 let log = Arc::new(Mutex::new(Vec::new()));
877 let client = reqwest::Client::new();
878 poll_token_with(
879 &client,
880 &discovery_at(&base),
881 "tracing-cli",
882 &device_auth(5, 600),
883 recording_sleep(log.clone()),
884 )
885 .await
886 .expect("slow_down must not be fatal");
887
888 assert_eq!(*log.lock().unwrap(), vec![5, 10, 10]);
891 }
892
893 #[tokio::test]
894 async fn expired_token_is_terminal_with_its_own_message() {
895 let (base, _rx) = spawn_seq(vec![http_json(
896 "400 Bad Request",
897 r#"{"error":"expired_token"}"#,
898 )]);
899 let client = reqwest::Client::new();
900 let err = poll_token_with(
901 &client,
902 &discovery_at(&base),
903 "tracing-cli",
904 &device_auth(5, 600),
905 recording_sleep(Arc::new(Mutex::new(Vec::new()))),
906 )
907 .await
908 .expect_err("expired_token must be terminal");
909
910 assert!(matches!(err, OidcError::DeviceCodeExpired), "got {err:?}");
911 assert!(
912 err.to_string().contains("expired"),
913 "message must say the code expired: {err}"
914 );
915 assert!(
916 !err.to_string().contains("denied"),
917 "expired must not read like a denial: {err}"
918 );
919 }
920
921 #[tokio::test]
922 async fn access_denied_is_terminal_with_its_own_message() {
923 let (base, _rx) = spawn_seq(vec![http_json(
924 "400 Bad Request",
925 r#"{"error":"access_denied"}"#,
926 )]);
927 let client = reqwest::Client::new();
928 let err = poll_token_with(
929 &client,
930 &discovery_at(&base),
931 "tracing-cli",
932 &device_auth(5, 600),
933 recording_sleep(Arc::new(Mutex::new(Vec::new()))),
934 )
935 .await
936 .expect_err("access_denied must be terminal");
937
938 assert!(matches!(err, OidcError::AccessDenied), "got {err:?}");
939 assert!(
940 err.to_string().contains("denied"),
941 "message must say the login was denied: {err}"
942 );
943 assert!(
944 !err.to_string().contains("expired"),
945 "denial must not read like an expiry: {err}"
946 );
947 }
948
949 #[tokio::test]
950 async fn poll_gives_up_after_the_device_codes_own_expiry() {
951 let pending = || http_json("400 Bad Request", r#"{"error":"authorization_pending"}"#);
954 let (base, rx) = spawn_seq(vec![pending(), pending(), pending()]);
955 let log = Arc::new(Mutex::new(Vec::new()));
956 let client = reqwest::Client::new();
957 let err = poll_token_with(
958 &client,
959 &discovery_at(&base),
960 "tracing-cli",
961 &device_auth(5, 10),
962 recording_sleep(log.clone()),
963 )
964 .await
965 .expect_err("must give up once the device code's own lifetime is spent");
966
967 assert!(
968 matches!(err, OidcError::PollTimeout { waited_secs: 10 }),
969 "got {err:?}"
970 );
971 assert_eq!(*log.lock().unwrap(), vec![5, 5]);
972 assert!(rx.recv_timeout(RECV_TIMEOUT).is_ok());
973 assert!(rx.recv_timeout(RECV_TIMEOUT).is_ok());
974 assert!(
975 rx.recv_timeout(Duration::from_millis(200)).is_err(),
976 "the budget must cap polling; a third poll went out"
977 );
978 }
979
980 #[tokio::test]
981 async fn discovery_rejects_mismatched_issuer_naming_both_values() {
982 let (base, _rx) = spawn_seq(vec![http_json(
985 "200 OK",
986 r#"{"issuer":"https://idp.test/realms/other","token_endpoint":"https://idp.test/token"}"#,
987 )]);
988 let client = reqwest::Client::new();
989 let err = discover(&client, &base)
990 .await
991 .expect_err("a self-reported issuer mismatch must be rejected");
992
993 let msg = err.to_string();
994 assert!(
995 msg.contains(&base),
996 "error must name the expected issuer ({base}): {msg}"
997 );
998 assert!(
999 msg.contains("https://idp.test/realms/other"),
1000 "error must name the issuer found in the document: {msg}"
1001 );
1002 }
1003
1004 #[tokio::test]
1005 async fn discovery_accepts_issuer_differing_only_by_trailing_slash() {
1006 let (base, _rx) = crate::test_helpers::spawn_seq_with(|base| {
1009 vec![http_json(
1010 "200 OK",
1011 &format!(
1013 r#"{{"issuer":"{base}/","token_endpoint":"{base}/token","device_authorization_endpoint":"{base}/device","revocation_endpoint":"{base}/revoke"}}"#
1014 ),
1015 )]
1016 });
1017 let client = reqwest::Client::new();
1018 let disc = discover(&client, &format!("{base}/"))
1019 .await
1020 .expect("trailing slashes must be canonicalised away, not treated as a mismatch");
1021 assert_eq!(disc.token_endpoint, format!("{base}/token"));
1022 assert_eq!(disc.revocation_endpoint, Some(format!("{base}/revoke")));
1023 }
1024
1025 #[tokio::test]
1034 async fn discovery_refuses_a_plaintext_issuer() {
1035 let client = reqwest::Client::new();
1036 let err = discover(&client, "http://idp.example.com/realms/v")
1037 .await
1038 .expect_err("a plaintext issuer must be refused");
1039 assert!(
1040 matches!(err, OidcError::InsecureIssuer { .. }),
1041 "got {err:?}"
1042 );
1043 let msg = err.to_string();
1044 assert!(
1045 msg.contains("refresh token") && msg.contains("https"),
1046 "{msg}"
1047 );
1048 }
1049
1050 #[tokio::test]
1053 async fn discovery_allows_a_loopback_issuer_over_http() {
1054 let (base, _rx) = crate::test_helpers::spawn_seq_with(|base| {
1055 vec![http_json(
1056 "200 OK",
1057 &format!(r#"{{"issuer":"{base}","token_endpoint":"{base}/token"}}"#),
1058 )]
1059 });
1060 assert!(base.starts_with("http://127.0.0.1"));
1062 let client = reqwest::Client::new();
1063 discover(&client, &base)
1064 .await
1065 .expect("loopback http must stay usable for local development");
1066 }
1067
1068 #[tokio::test]
1071 async fn discovery_rejects_an_endpoint_on_another_origin() {
1072 let (base, _rx) = crate::test_helpers::spawn_seq_with(|base| {
1073 vec![http_json(
1074 "200 OK",
1075 &format!(
1076 r#"{{"issuer":"{base}","token_endpoint":"https://evil.example.com/token"}}"#
1077 ),
1078 )]
1079 });
1080 let client = reqwest::Client::new();
1081 let err = discover(&client, &base)
1082 .await
1083 .expect_err("a token endpoint on another origin must be refused");
1084 assert!(
1085 matches!(err, OidcError::EndpointOriginMismatch { what: "token", .. }),
1086 "got {err:?}"
1087 );
1088 let msg = err.to_string();
1089 assert!(
1090 msg.contains("evil.example.com"),
1091 "must name the endpoint: {msg}"
1092 );
1093 assert!(msg.contains(&base), "must name the issuer: {msg}");
1094 }
1095
1096 #[tokio::test]
1099 async fn discovery_rejects_an_offsite_revocation_endpoint() {
1100 let (base, _rx) = crate::test_helpers::spawn_seq_with(|base| {
1101 vec![http_json(
1102 "200 OK",
1103 &format!(
1104 r#"{{"issuer":"{base}","token_endpoint":"{base}/token","revocation_endpoint":"https://evil.example.com/revoke"}}"#
1105 ),
1106 )]
1107 });
1108 let client = reqwest::Client::new();
1109 let err = discover(&client, &base).await.unwrap_err();
1110 assert!(
1111 matches!(
1112 err,
1113 OidcError::EndpointOriginMismatch {
1114 what: "revocation",
1115 ..
1116 }
1117 ),
1118 "got {err:?}"
1119 );
1120 }
1121
1122 #[tokio::test]
1125 async fn discovery_treats_a_different_port_as_a_different_origin() {
1126 let (base, _rx) = crate::test_helpers::spawn_seq_with(|base| {
1127 vec![http_json(
1132 "200 OK",
1133 &format!(r#"{{"issuer":"{base}","token_endpoint":"http://127.0.0.1:9/token"}}"#),
1134 )]
1135 });
1136 let client = reqwest::Client::new();
1137 let err = discover(&client, &base).await.unwrap_err();
1138 assert!(
1139 matches!(err, OidcError::EndpointOriginMismatch { .. }),
1140 "got {err:?}"
1141 );
1142 }
1143
1144 #[test]
1147 fn require_secure_exempts_loopback_by_name_and_address() {
1148 for allowed in [
1149 "https://idp.example.com/realms/v",
1150 "http://localhost:8080/realms/v",
1151 "http://keycloak.localhost/realms/v",
1152 "http://127.0.0.1:8080/realms/v",
1153 "http://[::1]:8080/realms/v",
1154 ] {
1155 require_secure(&Url::parse(allowed).unwrap())
1156 .unwrap_or_else(|e| panic!("{allowed} must be allowed: {e}"));
1157 }
1158 for refused in [
1159 "http://idp.example.com/realms/v",
1160 "http://localhost.evil.example.com/realms/v",
1162 "http://10.0.0.5:8080/realms/v",
1163 ] {
1164 let err = require_secure(&Url::parse(refused).unwrap())
1165 .expect_err("{refused} must be refused");
1166 assert!(matches!(err, OidcError::InsecureIssuer { .. }), "{refused}");
1167 }
1168 }
1169
1170 #[test]
1173 fn is_browser_safe_allows_only_http_and_https() {
1174 assert!(is_browser_safe("https://idp.example.com/device?code=X"));
1175 assert!(is_browser_safe("http://localhost:8080/device"));
1176
1177 for hostile in [
1178 "file:///etc/passwd",
1179 "file:///Users/me/.ssh/id_rsa",
1180 "javascript:alert(1)",
1181 "data:text/html,<script>alert(1)</script>",
1182 "vscode://file/etc/passwd",
1183 "smb://attacker.example.com/share",
1184 "not a url at all",
1185 "",
1186 ] {
1187 assert!(
1188 !is_browser_safe(hostile),
1189 "{hostile} must not be handed to the desktop URL handler"
1190 );
1191 }
1192 }
1193
1194 #[tokio::test]
1195 async fn public_config_oidc_disabled_is_permanent_no_keycloak() {
1196 let (base, _rx) = spawn_seq(vec![http_json("200 OK", r#"{"oidc_enabled":false}"#)]);
1197 let client = reqwest::Client::new();
1198 let err = fetch_public_config(&client, &base)
1199 .await
1200 .expect_err("oidc_enabled:false must not parse as a usable config");
1201 assert!(matches!(err, OidcError::NoKeycloak), "got {err:?}");
1202 }
1203
1204 #[tokio::test]
1209 async fn public_config_5xx_is_transient_not_no_keycloak() {
1210 for status in [
1211 "503 Service Unavailable",
1212 "502 Bad Gateway",
1213 "500 Internal Server Error",
1214 ] {
1215 let (base, _rx) = spawn_seq(vec![http_json(status, r#"{"error":"backend down"}"#)]);
1216 let client = reqwest::Client::new();
1217 let err = fetch_public_config(&client, &base).await.unwrap_err();
1218 assert!(
1219 matches!(err, OidcError::IdpUnavailable { .. }),
1220 "{status} must be the retryable variant; got {err:?}"
1221 );
1222 let msg = err.to_string();
1223 assert!(
1224 msg.contains("temporarily unavailable") && msg.contains("retry"),
1225 "message must read as retryable: {msg}"
1226 );
1227 assert!(
1228 !msg.to_lowercase().contains("api key"),
1229 "must not send the user off to get an API key: {msg}"
1230 );
1231 }
1232 }
1233
1234 #[tokio::test]
1238 async fn public_config_5xx_with_unparseable_body_is_transient() {
1239 for body in ["", "not json at all", "<html>502 Bad Gateway</html>"] {
1240 let (base, _rx) = spawn_seq(vec![http_json("503 Service Unavailable", body)]);
1241 let client = reqwest::Client::new();
1242 let err = fetch_public_config(&client, &base).await.unwrap_err();
1243 assert!(
1244 matches!(err, OidcError::IdpUnavailable { .. }),
1245 "body {body:?} must yield the retryable variant, got {err:?}"
1246 );
1247 }
1248 }
1249
1250 #[tokio::test]
1251 async fn public_config_200_parses_issuer_client_id_and_audience() {
1252 let (base, rx) = spawn_seq(vec![http_json(
1253 "200 OK",
1254 r#"{"oidc_enabled":true,"issuer":"https://idp.test/realms/visdom","audience":"tracevault","cli_client_id":"tracing-cli"}"#,
1255 )]);
1256 let client = reqwest::Client::new();
1257 let cfg = fetch_public_config(&client, &format!("{base}/"))
1258 .await
1259 .unwrap();
1260 assert_eq!(cfg.issuer, "https://idp.test/realms/visdom");
1261 assert_eq!(cfg.cli_client_id, "tracing-cli");
1262 assert_eq!(cfg.audience.as_deref(), Some("tracevault"));
1263 let req = rx.recv_timeout(RECV_TIMEOUT).unwrap();
1264 assert!(
1265 req.contains("GET /api/v1/auth/public-config"),
1266 "unexpected request: {req}"
1267 );
1268 }
1269
1270 #[tokio::test]
1273 async fn public_config_without_audience_still_resolves() {
1274 let (base, _rx) = spawn_seq(vec![http_json(
1275 "200 OK",
1276 r#"{"oidc_enabled":true,"issuer":"https://idp.test/realms/v","cli_client_id":"tracing-cli"}"#,
1277 )]);
1278 let client = reqwest::Client::new();
1279 let cfg = fetch_public_config(&client, &base).await.unwrap();
1280 assert_eq!(cfg.audience, None);
1281 assert_eq!(cfg.bazaar_mcp_url, None);
1282 }
1283
1284 #[tokio::test]
1285 async fn public_config_with_bazaar_mcp_url() {
1286 let (base, _rx) = spawn_seq(vec![http_json(
1287 "200 OK",
1288 r#"{"oidc_enabled":true,"issuer":"https://idp.test/realms/v","cli_client_id":"tracing-cli","bazaar_mcp_url":"https://ctx.example.com/mcp/remote"}"#,
1289 )]);
1290 let client = reqwest::Client::new();
1291 let cfg = fetch_public_config(&client, &base).await.unwrap();
1292 assert_eq!(
1293 cfg.bazaar_mcp_url.as_deref(),
1294 Some("https://ctx.example.com/mcp/remote")
1295 );
1296 }
1297
1298 #[tokio::test]
1302 async fn public_config_enabled_but_incomplete_is_a_named_error() {
1303 for (body, field) in [
1304 (
1305 r#"{"oidc_enabled":true,"cli_client_id":"tracing-cli"}"#,
1306 "issuer",
1307 ),
1308 (
1309 r#"{"oidc_enabled":true,"issuer":"https://idp.test/realms/v"}"#,
1310 "cli_client_id",
1311 ),
1312 (
1313 r#"{"oidc_enabled":true,"issuer":" ","cli_client_id":"tracing-cli"}"#,
1314 "issuer",
1315 ),
1316 ] {
1317 let (base, _rx) = spawn_seq(vec![http_json("200 OK", body)]);
1318 let client = reqwest::Client::new();
1319 let err = fetch_public_config(&client, &base).await.unwrap_err();
1320 let msg = err.to_string();
1321 assert!(
1322 msg.contains(field) && msg.contains("misconfigured"),
1323 "must name the missing field `{field}`: {msg}"
1324 );
1325 assert!(
1326 !matches!(err, OidcError::NoKeycloak),
1327 "an incomplete config is not the same as no Keycloak: {msg}"
1328 );
1329 }
1330 }
1331
1332 #[tokio::test]
1333 async fn device_start_requests_offline_access_scope() {
1334 let (base, rx) = spawn_seq(vec![http_json(
1335 "200 OK",
1336 r#"{"device_code":"dc","user_code":"ABCD-EFGH","verification_uri":"https://idp.test/device","expires_in":600,"interval":5}"#,
1337 )]);
1338 let client = reqwest::Client::new();
1339 let device = device_start(&client, &discovery_at(&base), "tracing-cli")
1340 .await
1341 .unwrap();
1342 assert_eq!(device.user_code, "ABCD-EFGH");
1343 let req = rx.recv_timeout(RECV_TIMEOUT).unwrap();
1344 assert!(
1345 req.contains("offline_access"),
1346 "offline_access is what yields a refresh token: {req}"
1347 );
1348 assert!(req.contains("client_id=tracing-cli"));
1349 }
1350
1351 #[tokio::test]
1352 async fn refresh_invalid_grant_maps_to_session_expired() {
1353 let (base, _rx) = spawn_seq(vec![http_json(
1354 "400 Bad Request",
1355 r#"{"error":"invalid_grant","error_description":"Token is not active"}"#,
1356 )]);
1357 let client = reqwest::Client::new();
1358 let err = refresh(&client, &discovery_at(&base), "tracing-cli", "rt")
1359 .await
1360 .expect_err("invalid_grant must be a distinct 'session expired' error");
1361 assert!(matches!(err, OidcError::SessionExpired), "got {err:?}");
1362 assert!(
1363 err.to_string().contains("tracevault login"),
1364 "message must tell the user how to recover: {err}"
1365 );
1366 }
1367
1368 #[tokio::test]
1369 async fn revoke_sends_refresh_token_hint() {
1370 let (base, rx) = spawn_seq(vec![http_json("200 OK", "{}")]);
1371 let client = reqwest::Client::new();
1372 revoke(&client, &discovery_at(&base), "tracing-cli", "rt")
1373 .await
1374 .unwrap();
1375 let req = rx.recv_timeout(RECV_TIMEOUT).unwrap();
1376 assert!(req.contains("POST /revoke"), "unexpected request: {req}");
1377 assert!(req.contains("token_type_hint=refresh_token"), "{req}");
1378 }
1379
1380 #[tokio::test]
1381 async fn revoke_without_endpoint_is_a_named_error() {
1382 let disc = Discovery {
1383 device_authorization_endpoint: None,
1384 token_endpoint: "https://idp.test/token".into(),
1385 revocation_endpoint: None,
1386 };
1387 let client = reqwest::Client::new();
1388 let err = revoke(&client, &disc, "tracing-cli", "rt")
1389 .await
1390 .expect_err("no revocation endpoint must be an explicit error");
1391 assert!(err.to_string().contains("revocation"), "{err}");
1392 }
1393
1394 #[test]
1397 fn debug_impls_redact_secrets() {
1398 let device = device_auth(5, 600);
1399 let dbg = format!("{device:?}");
1400 assert!(!dbg.contains("dev-code"), "device_code leaked: {dbg}");
1401
1402 let tokens = TokenSet {
1403 access_token: "super-secret-access".into(),
1404 refresh_token: Some("super-secret-refresh".into()),
1405 expires_in: 300,
1406 };
1407 let dbg = format!("{tokens:?}");
1408 assert!(!dbg.contains("super-secret-access"), "access leaked: {dbg}");
1409 assert!(
1410 !dbg.contains("super-secret-refresh"),
1411 "refresh leaked: {dbg}"
1412 );
1413 }
1414
1415 fn base64url_encode(bytes: &[u8]) -> String {
1418 const ALPHABET: &[u8; 64] =
1419 b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1420 let mut out = String::new();
1421 for chunk in bytes.chunks(3) {
1422 let b = [
1423 chunk[0],
1424 *chunk.get(1).unwrap_or(&0),
1425 *chunk.get(2).unwrap_or(&0),
1426 ];
1427 let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
1428 for shift in [18, 12, 6, 0].iter().take(chunk.len() + 1) {
1431 out.push(ALPHABET[((n >> shift) & 63) as usize] as char);
1432 }
1433 }
1434 out
1435 }
1436
1437 fn unsigned_jwt(payload_json: &str) -> String {
1448 format!(
1449 "{}.{}.signature-not-checked",
1450 base64url_encode(br#"{"alg":"none"}"#),
1451 base64url_encode(payload_json.as_bytes())
1452 )
1453 }
1454
1455 #[test]
1460 fn base64url_encode_matches_a_known_value() {
1461 assert_eq!(base64url_encode(b"not-json"), "bm90LWpzb24");
1462 assert_eq!(
1463 base64url_decode(&base64url_encode(b"abc")),
1464 Some(b"abc".to_vec())
1465 );
1466 for raw in [&b"a"[..], &b"ab"[..], &b"abc"[..], &b"abcd"[..]] {
1468 assert_eq!(
1469 base64url_decode(&base64url_encode(raw)),
1470 Some(raw.to_vec()),
1471 "round trip failed for {raw:?}"
1472 );
1473 }
1474 }
1475
1476 #[test]
1478 fn unverified_audiences_reads_string_and_array_forms() {
1479 assert_eq!(
1480 unverified_audiences(&unsigned_jwt(r#"{"aud":"tracevault","sub":"u"}"#)),
1481 Some(vec!["tracevault".to_string()])
1482 );
1483 assert_eq!(
1484 unverified_audiences(&unsigned_jwt(
1485 r#"{"aud":["account","tracevault"],"sub":"u"}"#
1486 )),
1487 Some(vec!["account".to_string(), "tracevault".to_string()])
1488 );
1489 assert_eq!(
1490 unverified_audiences(&unsigned_jwt(r#"{"aud":"some-other-app"}"#)),
1491 Some(vec!["some-other-app".to_string()])
1492 );
1493 }
1494
1495 #[test]
1498 fn unverified_audiences_is_none_when_it_cannot_tell() {
1499 assert_eq!(unverified_audiences(&unsigned_jwt(r#"{"sub":"u"}"#)), None);
1501 assert_eq!(unverified_audiences("opaque-token"), None);
1503 assert_eq!(unverified_audiences(""), None);
1504 assert_eq!(unverified_audiences("a.!!!not-base64!!!.c"), None);
1506 assert_eq!(unverified_audiences("a.bm90LWpzb24.c"), None);
1508 }
1509
1510 #[test]
1511 fn base64url_decode_handles_padding_and_rejects_junk() {
1512 assert_eq!(base64url_decode("aGVsbG8"), Some(b"hello".to_vec()));
1513 assert_eq!(base64url_decode("aGVsbG8="), Some(b"hello".to_vec()));
1514 assert_eq!(base64url_decode("--__"), Some(vec![0xfb, 0xef, 0xff]));
1517 assert!(base64url_decode("not valid!").is_none());
1518 }
1519
1520 #[test]
1521 fn canonical_issuer_trims_whitespace_and_trailing_slashes() {
1522 assert_eq!(
1523 canonical_issuer(" https://idp.test/realms/v// "),
1524 "https://idp.test/realms/v"
1525 );
1526 }
1527}