1use std::collections::{BTreeMap, HashMap};
31use std::sync::{Arc, RwLock};
32use std::time::Duration;
33
34use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
35use base64::Engine as _;
36use jsonwebtoken::jwk::JwkSet;
37use jsonwebtoken::{Algorithm, DecodingKey, Validation};
38use serde::{Deserialize, Serialize};
39use serde_json::{Map, Value};
40use sha2::{Digest, Sha256};
41use subtle::ConstantTimeEq;
42use url::Url;
43
44pub const DEFAULT_SCOPES: &str = "openid profile email groups roles setor";
47
48const HTTP_TIMEOUT: Duration = Duration::from_secs(10);
52
53pub const MAX_SIGN_OUT_STATE_LEN: usize = 512;
56
57#[derive(Clone)]
63pub struct Config {
64 pub issuer: String,
67 pub client_id: String,
69 pub client_secret: String,
71 pub redirect_uri: String,
73 pub scopes: String,
75}
76
77impl Config {
78 pub fn new(
80 issuer: impl Into<String>,
81 client_id: impl Into<String>,
82 client_secret: impl Into<String>,
83 redirect_uri: impl Into<String>,
84 ) -> Self {
85 Config {
86 issuer: issuer.into(),
87 client_id: client_id.into(),
88 client_secret: client_secret.into(),
89 redirect_uri: redirect_uri.into(),
90 scopes: DEFAULT_SCOPES.to_string(),
91 }
92 }
93
94 pub fn scopes(mut self, scopes: impl Into<String>) -> Self {
96 self.scopes = scopes.into();
97 self
98 }
99}
100
101impl std::fmt::Debug for Config {
103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104 f.debug_struct("Config")
105 .field("issuer", &self.issuer)
106 .field("client_id", &self.client_id)
107 .field("client_secret", &"<redacted>")
108 .field("redirect_uri", &self.redirect_uri)
109 .field("scopes", &self.scopes)
110 .finish()
111 }
112}
113
114#[derive(Debug, thiserror::Error)]
127pub enum Error {
128 #[error("the provider refused the sign-in: {error}")]
130 Provider {
131 error: String,
133 description: Option<String>,
135 },
136 #[error("the callback's state does not match the stored one")]
140 StateMismatch,
141 #[error("issuer mismatch: expected {expected:?}, got {found:?}")]
144 IssuerMismatch {
145 expected: String,
147 found: String,
149 },
150 #[error("malformed callback: {0}")]
152 InvalidCallback(&'static str),
153 #[error("the token exchange was refused ({status}): {error}")]
155 TokenRefused {
156 status: u16,
158 error: String,
161 description: Option<String>,
163 },
164 #[error("invalid ID token: {0}")]
166 InvalidIdToken(String),
167 #[error("discovery failed: {0}")]
169 Discovery(String),
170 #[error("invalid argument: {0}")]
174 InvalidArgument(String),
175 #[error("HTTP error talking to the provider: {0}")]
178 Http(#[from] reqwest::Error),
179}
180
181#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
194pub struct Pending {
195 state: String,
196 nonce: String,
197 code_verifier: String,
198}
199
200impl Pending {
201 fn generate() -> Self {
203 Pending { state: random_token(), nonce: random_token(), code_verifier: random_token() }
204 }
205
206 pub fn state(&self) -> &str {
208 &self.state
209 }
210}
211
212impl std::fmt::Debug for Pending {
214 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215 f.debug_struct("Pending").field("state", &self.state).finish_non_exhaustive()
216 }
217}
218
219fn random_token() -> String {
223 let mut bytes = [0u8; 32];
224 getrandom::fill(&mut bytes).expect("the operating system's random source is unavailable");
228 URL_SAFE_NO_PAD.encode(bytes)
229}
230
231fn pkce_challenge(verifier: &str) -> String {
233 URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
234}
235
236fn same(a: &str, b: &str) -> bool {
242 if a.is_empty() || b.is_empty() {
243 return false;
244 }
245 a.as_bytes().ct_eq(b.as_bytes()).into()
246}
247
248#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
258pub struct Identity {
259 pub sub: String,
261 pub username: Option<String>,
263 pub name: Option<String>,
266 pub email: Option<String>,
268 pub setor: Option<String>,
270 pub groups: Vec<String>,
272 pub group_roles: BTreeMap<String, Vec<String>>,
274 pub claims: Map<String, Value>,
276}
277
278impl Identity {
279 fn from_claims(claims: Map<String, Value>) -> Result<Self, Error> {
283 let text = |key: &str| claims.get(key).and_then(Value::as_str).map(str::to_owned);
284 let sub = text("sub")
285 .filter(|s| !s.is_empty())
286 .ok_or_else(|| Error::InvalidIdToken("no sub claim".into()))?;
287 let strings = |v: &Value| -> Vec<String> {
288 v.as_array()
289 .map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect())
290 .unwrap_or_default()
291 };
292 let groups = claims.get("groups").map(strings).unwrap_or_default();
293 let group_roles = claims
294 .get("group_roles")
295 .and_then(Value::as_object)
296 .map(|m| m.iter().map(|(g, r)| (g.clone(), strings(r))).collect())
297 .unwrap_or_default();
298 Ok(Identity {
299 sub,
300 username: text("preferred_username"),
301 name: text("name"),
302 email: text("email"),
303 setor: text("setor"),
304 groups,
305 group_roles,
306 claims,
307 })
308 }
309
310 pub fn has_group(&self, group: &str) -> bool {
312 self.groups.iter().any(|g| g == group)
313 }
314
315 pub fn has_role(&self, group: &str, role: &str) -> bool {
317 self.roles(group).iter().any(|r| r == role)
318 }
319
320 pub fn roles(&self, group: &str) -> &[String] {
322 self.group_roles.get(group).map(Vec::as_slice).unwrap_or(&[])
323 }
324}
325
326#[derive(Debug, Clone, Deserialize)]
332struct Metadata {
333 issuer: String,
334 authorization_endpoint: String,
335 token_endpoint: String,
336 jwks_uri: String,
337 #[serde(default)]
340 end_session_endpoint: Option<String>,
341}
342
343#[derive(Debug, Clone, Default, PartialEq, Eq)]
346#[non_exhaustive]
347pub struct SignInOptions {
348 pub prompt: Option<String>,
354}
355
356impl SignInOptions {
357 pub fn new() -> Self {
359 Self::default()
360 }
361
362 pub fn prompt(mut self, value: impl Into<String>) -> Self {
364 self.prompt = Some(value.into());
365 self
366 }
367}
368
369#[derive(Clone, Default, PartialEq, Eq)]
372#[non_exhaustive]
373pub struct SignOutOptions {
374 pub post_logout_redirect_uri: Option<String>,
378 pub state: Option<String>,
381 pub id_token_hint: Option<String>,
383}
384
385impl SignOutOptions {
386 pub fn new() -> Self {
388 Self::default()
389 }
390
391 pub fn post_logout_redirect_uri(mut self, uri: impl Into<String>) -> Self {
393 self.post_logout_redirect_uri = Some(uri.into());
394 self
395 }
396
397 pub fn state(mut self, state: impl Into<String>) -> Self {
399 self.state = Some(state.into());
400 self
401 }
402
403 pub fn id_token_hint(mut self, id_token: impl Into<String>) -> Self {
405 self.id_token_hint = Some(id_token.into());
406 self
407 }
408}
409
410impl std::fmt::Debug for SignOutOptions {
412 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
413 f.debug_struct("SignOutOptions")
414 .field("post_logout_redirect_uri", &self.post_logout_redirect_uri)
415 .field("state", &self.state)
416 .field("id_token_hint", &self.id_token_hint.as_ref().map(|_| "<redacted>"))
417 .finish()
418 }
419}
420
421#[derive(Clone, Deserialize)]
424pub struct TokenResponse {
425 pub id_token: String,
428 pub access_token: Option<String>,
430 pub scope: Option<String>,
432}
433
434impl std::fmt::Debug for TokenResponse {
435 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
436 f.debug_struct("TokenResponse").field("scope", &self.scope).finish_non_exhaustive()
437 }
438}
439
440#[derive(Deserialize)]
442struct OAuthError {
443 error: String,
444 error_description: Option<String>,
445}
446
447#[derive(Clone, Debug)]
450pub struct Client {
451 inner: Arc<Inner>,
452}
453
454#[derive(Debug)]
455struct Inner {
456 config: Config,
457 metadata: Metadata,
458 http: reqwest::Client,
459 jwks: RwLock<Arc<JwkSet>>,
463}
464
465impl Client {
466 pub async fn discover(config: Config) -> Result<Self, Error> {
472 let http = reqwest::Client::builder()
473 .timeout(HTTP_TIMEOUT)
474 .redirect(reqwest::redirect::Policy::none())
477 .build()?;
478 Self::discover_with(config, http).await
479 }
480
481 pub async fn discover_with(config: Config, http: reqwest::Client) -> Result<Self, Error> {
484 let url = format!("{}/.well-known/openid-configuration", config.issuer.trim_end_matches('/'));
485 let metadata: Metadata = http.get(&url).send().await?.error_for_status()?.json().await?;
486 check_metadata(&config, &metadata)?;
487 let jwks = fetch_jwks(&http, &metadata.jwks_uri).await?;
488 Ok(Self::from_parts(config, metadata, http, jwks))
489 }
490
491 fn from_parts(config: Config, metadata: Metadata, http: reqwest::Client, jwks: JwkSet) -> Self {
492 Client { inner: Arc::new(Inner { config, metadata, http, jwks: RwLock::new(Arc::new(jwks)) }) }
493 }
494
495 pub fn config(&self) -> &Config {
497 &self.inner.config
498 }
499
500 pub fn start_sign_in(&self) -> (Url, Pending) {
505 self.start_sign_in_with(&SignInOptions::default())
506 }
507
508 pub fn start_sign_in_with(&self, options: &SignInOptions) -> (Url, Pending) {
514 let pending = Pending::generate();
515 let config = &self.inner.config;
516 let mut url = Url::parse(&self.inner.metadata.authorization_endpoint)
517 .expect("authorization_endpoint was validated at discovery");
518 url.query_pairs_mut()
519 .append_pair("response_type", "code")
520 .append_pair("client_id", &config.client_id)
521 .append_pair("redirect_uri", &config.redirect_uri)
522 .append_pair("scope", &config.scopes)
523 .append_pair("state", &pending.state)
524 .append_pair("nonce", &pending.nonce)
525 .append_pair("code_challenge", &pkce_challenge(&pending.code_verifier))
526 .append_pair("code_challenge_method", "S256");
527 if let Some(prompt) = &options.prompt {
528 url.query_pairs_mut().append_pair("prompt", prompt);
529 }
530 (url, pending)
531 }
532
533 pub fn sign_out_url(&self, options: &SignOutOptions) -> Result<Url, Error> {
549 if let Some(state) = &options.state {
550 if state.chars().count() > MAX_SIGN_OUT_STATE_LEN {
551 return Err(Error::InvalidArgument(format!(
552 "the sign-out state is longer than {MAX_SIGN_OUT_STATE_LEN} characters"
553 )));
554 }
555 }
556 let endpoint = self.inner.metadata.end_session_endpoint.as_deref().ok_or_else(|| {
557 Error::Discovery(
558 "the discovery document has no end_session_endpoint (the portal is older than sign-out support)"
559 .into(),
560 )
561 })?;
562 let mut url =
563 Url::parse(endpoint).map_err(|e| Error::Discovery(format!("end_session_endpoint is not a URL: {e}")))?;
564 {
565 let mut query = url.query_pairs_mut();
568 query.append_pair("client_id", &self.inner.config.client_id);
569 for (name, value) in [
570 ("id_token_hint", &options.id_token_hint),
571 ("post_logout_redirect_uri", &options.post_logout_redirect_uri),
572 ("state", &options.state),
573 ] {
574 if let Some(value) = value {
575 query.append_pair(name, value);
576 }
577 }
578 }
579 Ok(url)
580 }
581
582 pub fn password_change_url(&self) -> String {
589 let config = &self.inner.config;
590 let client_id = url::form_urlencoded::byte_serialize(config.client_id.as_bytes()).collect::<String>();
591 format!("{}/admin/account/password?client_id={client_id}", config.issuer.trim_end_matches('/'))
592 }
593
594 pub async fn finish_sign_in(&self, callback_query: &str, pending: &Pending) -> Result<Identity, Error> {
605 let code = self.check_callback(callback_query, pending)?;
606 let tokens = self.exchange_code(&code, &pending.code_verifier).await?;
607 self.verify_id_token(&tokens.id_token, &pending.nonce).await
608 }
609
610 fn check_callback(&self, callback_query: &str, pending: &Pending) -> Result<String, Error> {
613 let params = parse_query(callback_query)?;
614 if let Some(error) = params.get("error") {
615 return Err(Error::Provider {
616 error: error.clone(),
617 description: params.get("error_description").cloned(),
618 });
619 }
620 match params.get("state") {
621 Some(state) if same(state, &pending.state) => {}
622 _ => return Err(Error::StateMismatch),
623 }
624 let issuer = &self.inner.config.issuer;
625 match params.get("iss") {
628 Some(iss) if iss == issuer => {}
629 other => {
630 return Err(Error::IssuerMismatch {
631 expected: issuer.clone(),
632 found: other.cloned().unwrap_or_else(|| "(absent)".into()),
633 });
634 }
635 }
636 params.get("code").filter(|c| !c.is_empty()).cloned().ok_or(Error::InvalidCallback("no code"))
637 }
638
639 pub async fn exchange_code(&self, code: &str, code_verifier: &str) -> Result<TokenResponse, Error> {
646 let config = &self.inner.config;
647 let response = self
648 .inner
649 .http
650 .post(&self.inner.metadata.token_endpoint)
651 .header(reqwest::header::AUTHORIZATION, basic_auth(&config.client_id, &config.client_secret))
652 .form(&[
653 ("grant_type", "authorization_code"),
654 ("code", code),
655 ("redirect_uri", config.redirect_uri.as_str()),
656 ("code_verifier", code_verifier),
657 ])
658 .send()
659 .await?;
660 let status = response.status();
661 if status.is_success() {
662 return Ok(response.json().await?);
663 }
664 let body = response.bytes().await.unwrap_or_default();
667 let parsed: Option<OAuthError> = serde_json::from_slice(&body).ok();
668 Err(Error::TokenRefused {
669 status: status.as_u16(),
670 error: parsed.as_ref().map_or_else(|| format!("http_{}", status.as_u16()), |e| e.error.clone()),
671 description: parsed.and_then(|e| e.error_description),
672 })
673 }
674
675 pub async fn verify_id_token(&self, id_token: &str, nonce: &str) -> Result<Identity, Error> {
680 let bad = |reason: String| Error::InvalidIdToken(reason);
681 let header = jsonwebtoken::decode_header(id_token).map_err(|e| bad(format!("unreadable header: {e}")))?;
682 let kid = header.kid.ok_or_else(|| bad("the token names no key id (kid)".into()))?;
683 let key = self.decoding_key(&kid).await?;
684
685 let config = &self.inner.config;
686 let mut validation = Validation::new(Algorithm::ES256);
687 validation.set_issuer(&[config.issuer.as_str()]);
688 validation.set_audience(&[config.client_id.as_str()]);
689 validation.set_required_spec_claims(&["exp", "iss", "aud", "sub"]);
690 validation.leeway = 60;
692 let data = jsonwebtoken::decode::<Map<String, Value>>(id_token, &key, &validation)
693 .map_err(|e| bad(e.to_string()))?;
694 let claims = data.claims;
695
696 match claims.get("nonce").and_then(Value::as_str) {
697 Some(n) if same(n, nonce) => {}
698 _ => return Err(bad("nonce mismatch".into())),
699 }
700 Identity::from_claims(claims)
701 }
702
703 async fn decoding_key(&self, kid: &str) -> Result<DecodingKey, Error> {
706 let cached = self.inner.jwks.read().expect("jwks lock poisoned").clone();
707 let jwk = match cached.find(kid) {
708 Some(jwk) => jwk.clone(),
709 None => {
710 let fresh = Arc::new(fetch_jwks(&self.inner.http, &self.inner.metadata.jwks_uri).await?);
711 *self.inner.jwks.write().expect("jwks lock poisoned") = fresh.clone();
712 fresh
713 .find(kid)
714 .cloned()
715 .ok_or_else(|| Error::InvalidIdToken(format!("signed with an unknown key {kid:?}")))?
716 }
717 };
718 DecodingKey::from_jwk(&jwk).map_err(|e| Error::InvalidIdToken(format!("unusable key {kid:?}: {e}")))
719 }
720}
721
722fn check_metadata(config: &Config, metadata: &Metadata) -> Result<(), Error> {
725 if metadata.issuer != config.issuer {
726 return Err(Error::IssuerMismatch { expected: config.issuer.clone(), found: metadata.issuer.clone() });
727 }
728 for (name, value) in [
729 ("authorization_endpoint", &metadata.authorization_endpoint),
730 ("token_endpoint", &metadata.token_endpoint),
731 ("jwks_uri", &metadata.jwks_uri),
732 ] {
733 Url::parse(value).map_err(|e| Error::Discovery(format!("{name} is not a URL: {e}")))?;
734 }
735 if let Some(value) = &metadata.end_session_endpoint {
736 Url::parse(value).map_err(|e| Error::Discovery(format!("end_session_endpoint is not a URL: {e}")))?;
737 }
738 Ok(())
739}
740
741async fn fetch_jwks(http: &reqwest::Client, uri: &str) -> Result<JwkSet, Error> {
742 let body = http.get(uri).send().await?.error_for_status()?.bytes().await?;
743 serde_json::from_slice(&body).map_err(|e| Error::Discovery(format!("unreadable key set: {e}")))
744}
745
746fn basic_auth(id: &str, secret: &str) -> String {
749 let enc = |s: &str| url::form_urlencoded::byte_serialize(s.as_bytes()).collect::<String>();
750 format!("Basic {}", STANDARD.encode(format!("{}:{}", enc(id), enc(secret))))
751}
752
753fn parse_query(input: &str) -> Result<HashMap<String, String>, Error> {
756 let query = match input.split_once('?') {
757 Some((_, q)) => q,
758 None => input,
759 };
760 let query = query.split('#').next().unwrap_or("");
761 let mut params = HashMap::new();
762 for (k, v) in url::form_urlencoded::parse(query.as_bytes()) {
763 if params.insert(k.into_owned(), v.into_owned()).is_some() {
764 return Err(Error::InvalidCallback("a parameter is repeated"));
765 }
766 }
767 Ok(params)
768}
769
770#[cfg(test)]
771mod tests {
772 use super::*;
773 use serde_json::json;
774
775 const ISSUER: &str = "https://portal.example.org";
776
777 fn offline_client() -> Client {
780 let config = Config::new(ISSUER, "my-system", "s3cret", "https://app.example.org/auth/callback");
781 let metadata = Metadata {
782 issuer: ISSUER.into(),
783 authorization_endpoint: format!("{ISSUER}/oauth/authorize"),
784 token_endpoint: "http://127.0.0.1:9/oauth/token".into(),
785 jwks_uri: "http://127.0.0.1:9/oauth/jwks".into(),
786 end_session_endpoint: Some(format!("{ISSUER}/oauth/logout")),
787 };
788 Client::from_parts(config, metadata, reqwest::Client::new(), JwkSet { keys: vec![] })
789 }
790
791 fn query(url: &Url) -> HashMap<String, String> {
792 url.query_pairs().map(|(k, v)| (k.into_owned(), v.into_owned())).collect()
793 }
794
795 #[test]
796 fn authorization_url_carries_the_profile() {
797 let client = offline_client();
798 let (url, pending) = client.start_sign_in();
799 assert!(url.as_str().starts_with("https://portal.example.org/oauth/authorize?"));
800 let q = query(&url);
801 assert_eq!(q["response_type"], "code");
802 assert_eq!(q["client_id"], "my-system");
803 assert_eq!(q["redirect_uri"], "https://app.example.org/auth/callback");
804 assert_eq!(q["scope"], DEFAULT_SCOPES);
805 assert_eq!(q["code_challenge_method"], "S256");
806 assert_eq!(q["state"], pending.state);
807 assert_eq!(q["nonce"], pending.nonce);
808 assert_eq!(q["code_challenge"], pkce_challenge(&pending.code_verifier));
809 assert!(!url.as_str().contains(&pending.code_verifier));
811 }
812
813 #[test]
814 fn prompt_is_sent_only_when_asked() {
815 let client = offline_client();
816 let (url, _) = client.start_sign_in();
817 assert!(!query(&url).contains_key("prompt"));
818 let (url, _) = client.start_sign_in_with(&SignInOptions::default());
819 assert!(!query(&url).contains_key("prompt"));
820 let (url, _) = client.start_sign_in_with(&SignInOptions::new().prompt("none"));
821 assert_eq!(query(&url)["prompt"], "none");
822 assert!(url.as_str().ends_with("&prompt=none"));
823 }
824
825 #[test]
826 fn sign_out_url_with_only_the_client_id() {
827 let client = offline_client();
828 let url = client.sign_out_url(&SignOutOptions::new()).unwrap();
829 assert_eq!(url.as_str(), "https://portal.example.org/oauth/logout?client_id=my-system");
830 }
831
832 #[test]
833 fn sign_out_url_orders_and_encodes_the_query() {
834 let client = offline_client();
835 let options = SignOutOptions::new()
836 .state("a b&c?d")
837 .post_logout_redirect_uri("https://app.example.org/signed-out?x=1")
838 .id_token_hint("eyJ.hint.sig");
839 let url = client.sign_out_url(&options).unwrap();
840 assert_eq!(
841 url.as_str(),
842 "https://portal.example.org/oauth/logout?client_id=my-system&id_token_hint=eyJ.hint.sig\
843 &post_logout_redirect_uri=https%3A%2F%2Fapp.example.org%2Fsigned-out%3Fx%3D1&state=a+b%26c%3Fd"
844 );
845 let q = query(&url);
847 assert_eq!(q["state"], "a b&c?d");
848 assert_eq!(q["post_logout_redirect_uri"], "https://app.example.org/signed-out?x=1");
849 }
850
851 #[test]
852 fn sign_out_url_omits_absent_values() {
853 let client = offline_client();
854 let url = client.sign_out_url(&SignOutOptions::new().state("s")).unwrap();
855 assert_eq!(url.as_str(), "https://portal.example.org/oauth/logout?client_id=my-system&state=s");
856 let url = client.sign_out_url(&SignOutOptions::new().post_logout_redirect_uri("https://a.example/")).unwrap();
857 let q = query(&url);
858 assert_eq!(q.len(), 2);
859 assert_eq!(q["client_id"], "my-system");
860 assert!(!q.contains_key("state") && !q.contains_key("id_token_hint"));
861 }
862
863 #[test]
864 fn sign_out_state_longer_than_512_is_refused() {
865 let client = offline_client();
866 let ok = "é".repeat(MAX_SIGN_OUT_STATE_LEN); assert!(client.sign_out_url(&SignOutOptions::new().state(ok)).is_ok());
868 let long = "x".repeat(MAX_SIGN_OUT_STATE_LEN + 1);
869 assert!(matches!(client.sign_out_url(&SignOutOptions::new().state(long)), Err(Error::InvalidArgument(_))));
870 }
871
872 #[test]
873 fn sign_out_without_end_session_endpoint_is_a_discovery_error() {
874 let mut client = offline_client();
875 Arc::get_mut(&mut client.inner).unwrap().metadata.end_session_endpoint = None;
876 let err = client.sign_out_url(&SignOutOptions::new()).unwrap_err();
877 assert!(matches!(&err, Error::Discovery(m) if m.contains("end_session_endpoint")), "{err:?}");
878 }
879
880 #[test]
881 fn discovery_document_without_end_session_endpoint_parses() {
882 let doc = json!({
883 "issuer": ISSUER, "authorization_endpoint": format!("{ISSUER}/oauth/authorize"),
884 "token_endpoint": format!("{ISSUER}/oauth/token"), "jwks_uri": format!("{ISSUER}/oauth/jwks")
885 });
886 let m: Metadata = serde_json::from_value(doc).unwrap();
887 assert_eq!(m.end_session_endpoint, None);
888 }
889
890 #[test]
891 fn sign_out_options_debug_hides_the_id_token() {
892 let o = SignOutOptions::new().id_token_hint("eyJ.secret.sig");
893 assert!(!format!("{o:?}").contains("eyJ.secret.sig"));
894 }
895
896 #[test]
897 fn password_change_url_is_exact() {
898 let client = offline_client();
899 assert_eq!(client.password_change_url(), "https://portal.example.org/admin/account/password?client_id=my-system");
900 let mut client = offline_client();
901 Arc::get_mut(&mut client.inner).unwrap().config.client_id = "a b&c".into();
902 assert_eq!(client.password_change_url(), "https://portal.example.org/admin/account/password?client_id=a+b%26c");
903 }
904
905 #[test]
906 fn custom_scopes_are_sent() {
907 let mut client = offline_client();
908 Arc::get_mut(&mut client.inner).unwrap().config.scopes = "openid profile".into();
909 let (url, _) = client.start_sign_in();
910 assert_eq!(query(&url)["scope"], "openid profile");
911 }
912
913 #[test]
914 fn pending_values_are_random_and_well_formed() {
915 let a = Pending::generate();
916 let b = Pending::generate();
917 for v in [&a.state, &a.nonce, &a.code_verifier] {
918 assert_eq!(v.len(), 43);
920 assert!(v.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_'));
921 }
922 assert_ne!(a.state, a.nonce);
923 assert_ne!(a.nonce, a.code_verifier);
924 assert_ne!(a, b);
925 }
926
927 #[test]
928 fn pkce_challenge_matches_rfc_7636_example() {
929 assert_eq!(
931 pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),
932 "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
933 );
934 }
935
936 #[test]
937 fn pending_round_trips_through_serde() {
938 let p = Pending::generate();
939 let json = serde_json::to_string(&p).unwrap();
940 assert_eq!(serde_json::from_str::<Pending>(&json).unwrap(), p);
941 assert!(!format!("{p:?}").contains(&p.code_verifier));
943 }
944
945 #[test]
946 fn error_callback_is_reported_with_its_code() {
947 let client = offline_client();
948 let (_, p) = client.start_sign_in();
949 let q = format!("error=access_denied&error_description=not+in+group&state={}", p.state);
950 match client.check_callback(&q, &p) {
951 Err(Error::Provider { error, description }) => {
952 assert_eq!(error, "access_denied");
953 assert_eq!(description.as_deref(), Some("not in group"));
954 }
955 other => panic!("expected Provider error, got {other:?}"),
956 }
957 }
958
959 #[test]
960 fn wrong_or_missing_state_is_refused() {
961 let client = offline_client();
962 let (_, p) = client.start_sign_in();
963 assert!(matches!(client.check_callback("code=abc&state=forged", &p), Err(Error::StateMismatch)));
964 assert!(matches!(client.check_callback("code=abc", &p), Err(Error::StateMismatch)));
965 assert!(!same("", ""));
967 assert!(!same("", "x"));
968 assert!(same("x", "x"));
969 }
970
971 #[tokio::test]
972 async fn state_mismatch_stops_before_the_network() {
973 let client = offline_client();
976 let (_, p) = client.start_sign_in();
977 let err = client.finish_sign_in("?code=abc&state=forged", &p).await.unwrap_err();
978 assert!(matches!(err, Error::StateMismatch), "{err:?}");
979 }
980
981 #[test]
982 fn foreign_or_absent_iss_is_refused() {
983 let client = offline_client();
984 let (_, p) = client.start_sign_in();
985 let q = format!("code=abc&state={}&iss=https%3A%2F%2Fevil.example.org", p.state);
986 assert!(matches!(client.check_callback(&q, &p), Err(Error::IssuerMismatch { .. })));
987 let q = format!("code=abc&state={}&iss=https%3A%2F%2Fportal.example.org", p.state);
988 assert_eq!(client.check_callback(&q, &p).unwrap(), "abc");
989 let q = format!("code=abc&state={}", p.state);
991 assert!(matches!(client.check_callback(&q, &p), Err(Error::IssuerMismatch { .. })));
992 }
993
994 #[test]
995 fn full_callback_url_and_malformed_queries() {
996 let client = offline_client();
997 let (_, p) = client.start_sign_in();
998 const ISS: &str = "iss=https%3A%2F%2Fportal.example.org";
999 let url = format!("https://app.example.org/auth/callback?code=xyz&state={}&{ISS}", p.state);
1000 assert_eq!(client.check_callback(&url, &p).unwrap(), "xyz");
1001 let q = format!("state={}&{ISS}", p.state);
1002 assert!(matches!(client.check_callback(&q, &p), Err(Error::InvalidCallback(_))));
1003 let q = format!("code=a&code=b&state={}", p.state);
1004 assert!(matches!(client.check_callback(&q, &p), Err(Error::InvalidCallback(_))));
1005 }
1006
1007 #[test]
1008 fn discovery_with_another_issuer_is_refused() {
1009 let config = Config::new(ISSUER, "c", "s", "https://app.example.org/cb");
1010 let mut metadata = Metadata {
1011 issuer: format!("{ISSUER}/"),
1012 authorization_endpoint: format!("{ISSUER}/oauth/authorize"),
1013 token_endpoint: format!("{ISSUER}/oauth/token"),
1014 jwks_uri: format!("{ISSUER}/oauth/jwks"),
1015 end_session_endpoint: None,
1016 };
1017 assert!(matches!(check_metadata(&config, &metadata), Err(Error::IssuerMismatch { .. })));
1018 metadata.issuer = ISSUER.into();
1019 assert!(check_metadata(&config, &metadata).is_ok());
1020 }
1021
1022 #[test]
1023 fn basic_auth_form_encodes_both_halves() {
1024 assert_eq!(basic_auth("id", "a:b c"), format!("Basic {}", STANDARD.encode("id:a%3Ab+c")));
1026 }
1027
1028 fn claims(v: Value) -> Map<String, Value> {
1029 v.as_object().unwrap().clone()
1030 }
1031
1032 #[test]
1033 fn identity_fields_and_helpers() {
1034 let id = Identity::from_claims(claims(json!({
1035 "sub": "5966f47e", "preferred_username": "ana", "name": "Ana Maria",
1036 "email": "ana@example.org", "setor": "FIN", "groups": ["fiscal"],
1037 "group_roles": {"fiscal": ["analista", "gestor"]}, "extra": 1
1038 })))
1039 .unwrap();
1040 assert_eq!(id.sub, "5966f47e");
1041 assert_eq!(id.username.as_deref(), Some("ana"));
1042 assert_eq!(id.name.as_deref(), Some("Ana Maria"));
1043 assert_eq!(id.email.as_deref(), Some("ana@example.org"));
1044 assert_eq!(id.setor.as_deref(), Some("FIN"));
1045 assert!(id.has_group("fiscal"));
1046 assert!(!id.has_group("other"));
1047 assert!(id.has_role("fiscal", "gestor"));
1048 assert!(!id.has_role("fiscal", "admin"));
1049 assert!(!id.has_role("other", "gestor"));
1050 assert_eq!(id.roles("fiscal"), ["analista", "gestor"]);
1051 assert!(id.roles("other").is_empty());
1052 assert_eq!(id.claims["extra"], 1);
1053 }
1054
1055 #[test]
1056 fn missing_optional_claims_are_empty() {
1057 let id = Identity::from_claims(claims(json!({"sub": "x"}))).unwrap();
1058 assert_eq!(id.username, None);
1059 assert_eq!(id.name, None);
1060 assert_eq!(id.email, None);
1061 assert_eq!(id.setor, None);
1062 assert!(id.groups.is_empty());
1063 assert!(id.group_roles.is_empty());
1064 assert!(id.roles("fiscal").is_empty());
1065 }
1066
1067 #[test]
1068 fn identity_without_sub_is_refused() {
1069 assert!(matches!(
1070 Identity::from_claims(claims(json!({"preferred_username": "ana"}))),
1071 Err(Error::InvalidIdToken(_))
1072 ));
1073 }
1074
1075 #[test]
1076 fn debug_output_hides_the_secret() {
1077 let c = offline_client();
1078 assert!(!format!("{:?}", c.config()).contains("s3cret"));
1079 }
1080
1081 #[tokio::test]
1085 async fn unknown_kid_refreshes_the_key_set_once() {
1086 let Ok(issuer) = std::env::var("RUSCKER_ISSUER") else {
1087 eprintln!("RUSCKER_ISSUER is not set: skipping");
1088 return;
1089 };
1090 let var = |n: &str| std::env::var(n).unwrap();
1091 let config = Config::new(issuer, var("RUSCKER_CLIENT_ID"), var("RUSCKER_CLIENT_SECRET"), var("RUSCKER_REDIRECT_URI"));
1092 let real = Client::discover(config.clone()).await.unwrap();
1093 let client =
1094 Client::from_parts(config, real.inner.metadata.clone(), reqwest::Client::new(), JwkSet { keys: vec![] });
1095
1096 let (url, pending) = client.start_sign_in();
1097 let script = concat!(env!("CARGO_MANIFEST_DIR"), "/../testing/authorize.sh");
1098 let out = std::process::Command::new(script).arg(url.as_str()).output().unwrap();
1099 let callback = String::from_utf8(out.stdout).unwrap();
1100 client.finish_sign_in(callback.trim(), &pending).await.expect("sign-in after a key refresh");
1101 assert!(!client.inner.jwks.read().unwrap().keys.is_empty(), "the cache was refreshed");
1102 }
1103}