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