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