| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | use std::sync::Arc; |
| 14 | use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; |
| 15 | |
| 16 | use base64::prelude::{BASE64_STANDARD, BASE64_URL_SAFE_NO_PAD, Engine as _}; |
| 17 | use in_core::config::Oidc; |
| 18 | use in_core::error::{Error as CoreError, Result as CoreResult}; |
| 19 | use in_core::token::constant_time_eq; |
| 20 | use jsonwebtoken::errors::ErrorKind; |
| 21 | use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode}; |
| 22 | use serde::Deserialize; |
| 23 | use serde_json::{Map, Value}; |
| 24 | use sha2::{Digest, Sha256}; |
| 25 | use tokio::sync::Mutex; |
| 26 | |
| 27 | |
| 28 | pub const CLOCK_LEEWAY_SECS: i64 = 60; |
| 29 | |
| 30 | |
| 31 | pub const MAX_FUTURE_IAT_SECS: i64 = 300; |
| 32 | |
| 33 | |
| 34 | pub const JWKS_MAX_AGE: Duration = Duration::from_secs(10 * 60); |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | pub const JWKS_REFRESH_GAP: Duration = Duration::from_secs(60); |
| 40 | |
| 41 | |
| 42 | const DISCOVERY_RETRY_GAP: Duration = Duration::from_secs(60); |
| 43 | |
| 44 | |
| 45 | pub const HTTP_TIMEOUT: Duration = Duration::from_secs(10); |
| 46 | |
| 47 | |
| 48 | |
| 49 | const STREAM_READ_TIMEOUT: Duration = Duration::from_secs(90); |
| 50 | |
| 51 | |
| 52 | const MAX_DOCUMENT_BYTES: usize = 1024 * 1024; |
| 53 | |
| 54 | |
| 55 | const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60); |
| 56 | |
| 57 | |
| 58 | pub const LOGOUT_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout"; |
| 59 | |
| 60 | |
| 61 | pub const IM_KEY: &str = "im"; |
| 62 | |
| 63 | |
| 64 | pub const DIRECTORY_SCOPE: &str = "directory.read"; |
| 65 | |
| 66 | |
| 67 | pub const FAMILY_KEY: &str = "in"; |
| 68 | |
| 69 | |
| 70 | pub const FILES_SERVICE_SCOPE: &str = "files.service"; |
| 71 | |
| 72 | |
| 73 | #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] |
| 74 | pub enum TokenError { |
| 75 | |
| 76 | #[error("the token is malformed")] |
| 77 | Malformed, |
| 78 | |
| 79 | #[error("the token is not signed with EdDSA")] |
| 80 | Algorithm, |
| 81 | |
| 82 | #[error("the token has no key id")] |
| 83 | NoKeyId, |
| 84 | |
| 85 | #[error("the token names an unknown key")] |
| 86 | UnknownKey, |
| 87 | |
| 88 | #[error("the signature does not verify")] |
| 89 | Signature, |
| 90 | |
| 91 | #[error("the token has expired")] |
| 92 | Expired, |
| 93 | |
| 94 | #[error("the claim {0} is missing or wrong")] |
| 95 | Claim(&'static str), |
| 96 | |
| 97 | #[error("the nonce does not match")] |
| 98 | Nonce, |
| 99 | } |
| 100 | |
| 101 | |
| 102 | #[derive(Debug, thiserror::Error)] |
| 103 | pub enum OidcError { |
| 104 | |
| 105 | #[error(transparent)] |
| 106 | Token(#[from] TokenError), |
| 107 | |
| 108 | #[error("the identity provider is unavailable: {0}")] |
| 109 | Unavailable(String), |
| 110 | |
| 111 | #[error("the identity provider refused the request")] |
| 112 | Refused, |
| 113 | } |
| 114 | |
| 115 | |
| 116 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 117 | pub struct IdClaims { |
| 118 | |
| 119 | pub sub: String, |
| 120 | |
| 121 | pub sid: String, |
| 122 | |
| 123 | pub email: String, |
| 124 | |
| 125 | pub name: String, |
| 126 | |
| 127 | pub admin: bool, |
| 128 | |
| 129 | pub locale: String, |
| 130 | |
| 131 | pub zoneinfo: String, |
| 132 | |
| 133 | pub picture_version: i64, |
| 134 | |
| 135 | pub iat: i64, |
| 136 | } |
| 137 | |
| 138 | |
| 139 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 140 | pub struct LogoutClaims { |
| 141 | |
| 142 | pub jti: String, |
| 143 | |
| 144 | pub sid: Option<String>, |
| 145 | |
| 146 | pub sub: Option<String>, |
| 147 | } |
| 148 | |
| 149 | |
| 150 | |
| 151 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 152 | pub struct Endpoints { |
| 153 | |
| 154 | pub authorization: String, |
| 155 | |
| 156 | pub token: String, |
| 157 | |
| 158 | pub jwks: String, |
| 159 | |
| 160 | pub end_session: String, |
| 161 | } |
| 162 | |
| 163 | |
| 164 | #[derive(Debug, Deserialize)] |
| 165 | struct DiscoveryDocument { |
| 166 | issuer: String, |
| 167 | authorization_endpoint: String, |
| 168 | token_endpoint: String, |
| 169 | jwks_uri: String, |
| 170 | end_session_endpoint: Option<String>, |
| 171 | } |
| 172 | |
| 173 | |
| 174 | #[derive(Debug, Deserialize)] |
| 175 | pub struct Jwk { |
| 176 | #[serde(default)] |
| 177 | kty: String, |
| 178 | #[serde(default)] |
| 179 | crv: String, |
| 180 | #[serde(default)] |
| 181 | x: String, |
| 182 | #[serde(default)] |
| 183 | kid: String, |
| 184 | #[serde(default)] |
| 185 | alg: String, |
| 186 | #[serde(default, rename = "use")] |
| 187 | usage: String, |
| 188 | } |
| 189 | |
| 190 | |
| 191 | #[derive(Debug, Deserialize)] |
| 192 | pub struct Jwks { |
| 193 | keys: Vec<Jwk>, |
| 194 | } |
| 195 | |
| 196 | |
| 197 | pub struct KeySet { |
| 198 | keys: Vec<(String, DecodingKey)>, |
| 199 | } |
| 200 | |
| 201 | impl KeySet { |
| 202 | |
| 203 | |
| 204 | pub fn from_jwks(jwks: &Jwks) -> KeySet { |
| 205 | let keys = jwks |
| 206 | .keys |
| 207 | .iter() |
| 208 | .filter(|key| key.kty == "OKP" && key.crv == "Ed25519") |
| 209 | .filter(|key| key.alg.is_empty() || key.alg == "EdDSA") |
| 210 | .filter(|key| key.usage.is_empty() || key.usage == "sig") |
| 211 | .filter(|key| !key.kid.is_empty()) |
| 212 | .filter_map(|key| { |
| 213 | DecodingKey::from_ed_components(&key.x) |
| 214 | .ok() |
| 215 | .map(|decoding| (key.kid.clone(), decoding)) |
| 216 | }) |
| 217 | .collect(); |
| 218 | KeySet { keys } |
| 219 | } |
| 220 | |
| 221 | |
| 222 | fn get(&self, kid: &str) -> Option<&DecodingKey> { |
| 223 | self.keys |
| 224 | .iter() |
| 225 | .find(|(known, _)| known == kid) |
| 226 | .map(|(_, key)| key) |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | |
| 231 | pub fn now_secs() -> i64 { |
| 232 | SystemTime::now() |
| 233 | .duration_since(UNIX_EPOCH) |
| 234 | .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) |
| 235 | } |
| 236 | |
| 237 | |
| 238 | fn text_claim<'a>( |
| 239 | claims: &'a Map<String, Value>, |
| 240 | name: &'static str, |
| 241 | ) -> Result<&'a str, TokenError> { |
| 242 | claims |
| 243 | .get(name) |
| 244 | .and_then(Value::as_str) |
| 245 | .filter(|value| !value.trim().is_empty()) |
| 246 | .ok_or(TokenError::Claim(name)) |
| 247 | } |
| 248 | |
| 249 | |
| 250 | fn optional_text_claim<'a>(claims: &'a Map<String, Value>, name: &str) -> Option<&'a str> { |
| 251 | claims |
| 252 | .get(name) |
| 253 | .and_then(Value::as_str) |
| 254 | .filter(|value| !value.trim().is_empty()) |
| 255 | } |
| 256 | |
| 257 | |
| 258 | |
| 259 | fn audience_is(aud: Option<&Value>, expected: &str) -> bool { |
| 260 | match aud { |
| 261 | Some(Value::String(single)) => single == expected, |
| 262 | Some(Value::Array(items)) => { |
| 263 | items.len() == 1 && items.first().and_then(Value::as_str) == Some(expected) |
| 264 | } |
| 265 | _ => false, |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | |
| 270 | fn check_iat(claims: &Map<String, Value>, now: i64) -> Result<(), TokenError> { |
| 271 | let iat = claims |
| 272 | .get("iat") |
| 273 | .and_then(Value::as_i64) |
| 274 | .ok_or(TokenError::Claim("iat"))?; |
| 275 | if iat > now + MAX_FUTURE_IAT_SECS { |
| 276 | return Err(TokenError::Claim("iat")); |
| 277 | } |
| 278 | Ok(()) |
| 279 | } |
| 280 | |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 285 | |
| 286 | |
| 287 | pub fn check_header(token: &str) -> Result<String, TokenError> { |
| 288 | let segments: Vec<&str> = token.split('.').collect(); |
| 289 | if segments.len() != 3 { |
| 290 | return Err(TokenError::Malformed); |
| 291 | } |
| 292 | let header_bytes = BASE64_URL_SAFE_NO_PAD |
| 293 | .decode(segments[0]) |
| 294 | .map_err(|_| TokenError::Malformed)?; |
| 295 | let header: Value = serde_json::from_slice(&header_bytes).map_err(|_| TokenError::Malformed)?; |
| 296 | if header.get("alg").and_then(Value::as_str) != Some("EdDSA") { |
| 297 | return Err(TokenError::Algorithm); |
| 298 | } |
| 299 | header |
| 300 | .get("kid") |
| 301 | .and_then(Value::as_str) |
| 302 | .filter(|kid| !kid.is_empty()) |
| 303 | .map(str::to_owned) |
| 304 | .ok_or(TokenError::NoKeyId) |
| 305 | } |
| 306 | |
| 307 | |
| 308 | |
| 309 | |
| 310 | pub fn verify_signed( |
| 311 | keys: &KeySet, |
| 312 | token: &str, |
| 313 | issuer: &str, |
| 314 | ) -> Result<Map<String, Value>, TokenError> { |
| 315 | let kid = check_header(token)?; |
| 316 | let key = keys.get(&kid).ok_or(TokenError::UnknownKey)?; |
| 317 | |
| 318 | let mut validation = Validation::new(Algorithm::EdDSA); |
| 319 | validation.leeway = u64::try_from(CLOCK_LEEWAY_SECS).unwrap_or(0); |
| 320 | validation.validate_exp = true; |
| 321 | |
| 322 | validation.validate_nbf = true; |
| 323 | |
| 324 | validation.validate_aud = false; |
| 325 | validation.set_issuer(&[issuer]); |
| 326 | |
| 327 | |
| 328 | validation.set_required_spec_claims(&["exp", "iss", "iat"]); |
| 329 | let data = |
| 330 | decode::<Map<String, Value>>(token, key, &validation).map_err(|error| { |
| 331 | match error.kind() { |
| 332 | ErrorKind::ExpiredSignature => TokenError::Expired, |
| 333 | ErrorKind::InvalidSignature => TokenError::Signature, |
| 334 | ErrorKind::InvalidIssuer => TokenError::Claim("iss"), |
| 335 | ErrorKind::InvalidAlgorithm => TokenError::Algorithm, |
| 336 | ErrorKind::ImmatureSignature => TokenError::Claim("nbf"), |
| 337 | ErrorKind::MissingRequiredClaim(_) => TokenError::Claim("required claim"), |
| 338 | _ => TokenError::Malformed, |
| 339 | } |
| 340 | })?; |
| 341 | Ok(data.claims) |
| 342 | } |
| 343 | |
| 344 | |
| 345 | |
| 346 | pub fn verify_id_token( |
| 347 | keys: &KeySet, |
| 348 | token: &str, |
| 349 | issuer: &str, |
| 350 | client_id: &str, |
| 351 | nonce: &str, |
| 352 | ) -> Result<IdClaims, TokenError> { |
| 353 | let claims = verify_signed(keys, token, issuer)?; |
| 354 | if !audience_is(claims.get("aud"), client_id) { |
| 355 | return Err(TokenError::Claim("aud")); |
| 356 | } |
| 357 | check_iat(&claims, now_secs())?; |
| 358 | let sent = text_claim(&claims, "nonce")?; |
| 359 | if !constant_time_eq(sent.as_bytes(), nonce.as_bytes()) { |
| 360 | return Err(TokenError::Nonce); |
| 361 | } |
| 362 | let sub = text_claim(&claims, "sub")?.to_owned(); |
| 363 | let sid = text_claim(&claims, "sid")?.to_owned(); |
| 364 | let email = text_claim(&claims, "email")?.to_owned(); |
| 365 | let name = optional_text_claim(&claims, "name") |
| 366 | .unwrap_or(&email) |
| 367 | .to_owned(); |
| 368 | let locale = match optional_text_claim(&claims, "locale") { |
| 369 | Some("tr") => "tr".to_owned(), |
| 370 | _ => "en".to_owned(), |
| 371 | }; |
| 372 | Ok(IdClaims { |
| 373 | sub, |
| 374 | sid, |
| 375 | email, |
| 376 | name, |
| 377 | admin: claims |
| 378 | .get("admin") |
| 379 | .and_then(Value::as_bool) |
| 380 | .unwrap_or(false), |
| 381 | locale, |
| 382 | zoneinfo: optional_text_claim(&claims, "zoneinfo") |
| 383 | .unwrap_or("UTC") |
| 384 | .to_owned(), |
| 385 | iat: claims |
| 386 | .get("iat") |
| 387 | .and_then(Value::as_i64) |
| 388 | .unwrap_or_default(), |
| 389 | picture_version: claims |
| 390 | .get("picture_version") |
| 391 | .and_then(Value::as_i64) |
| 392 | .unwrap_or(0) |
| 393 | .max(0), |
| 394 | }) |
| 395 | } |
| 396 | |
| 397 | |
| 398 | |
| 399 | pub fn verify_logout_token( |
| 400 | keys: &KeySet, |
| 401 | token: &str, |
| 402 | issuer: &str, |
| 403 | client_id: &str, |
| 404 | ) -> Result<LogoutClaims, TokenError> { |
| 405 | let claims = verify_signed(keys, token, issuer)?; |
| 406 | if !audience_is(claims.get("aud"), client_id) { |
| 407 | return Err(TokenError::Claim("aud")); |
| 408 | } |
| 409 | check_iat(&claims, now_secs())?; |
| 410 | if claims.contains_key("nonce") { |
| 411 | return Err(TokenError::Claim("nonce")); |
| 412 | } |
| 413 | let has_event = claims |
| 414 | .get("events") |
| 415 | .and_then(Value::as_object) |
| 416 | .and_then(|events| events.get(LOGOUT_EVENT)) |
| 417 | .is_some_and(Value::is_object); |
| 418 | if !has_event { |
| 419 | return Err(TokenError::Claim("events")); |
| 420 | } |
| 421 | let jti = text_claim(&claims, "jti")?.to_owned(); |
| 422 | let sid = optional_text_claim(&claims, "sid").map(str::to_owned); |
| 423 | let sub = optional_text_claim(&claims, "sub").map(str::to_owned); |
| 424 | if sid.is_none() && sub.is_none() { |
| 425 | return Err(TokenError::Claim("sub")); |
| 426 | } |
| 427 | Ok(LogoutClaims { jti, sid, sub }) |
| 428 | } |
| 429 | |
| 430 | |
| 431 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 432 | pub struct MachineClaims { |
| 433 | |
| 434 | pub subject: String, |
| 435 | |
| 436 | pub scopes: Vec<String>, |
| 437 | |
| 438 | pub svc: Option<String>, |
| 439 | } |
| 440 | |
| 441 | |
| 442 | |
| 443 | |
| 444 | |
| 445 | pub fn verify_machine_token( |
| 446 | keys: &KeySet, |
| 447 | token: &str, |
| 448 | issuer: &str, |
| 449 | audience: &str, |
| 450 | ) -> Result<MachineClaims, TokenError> { |
| 451 | let claims = verify_signed(keys, token, issuer)?; |
| 452 | if !audience_is(claims.get("aud"), audience) { |
| 453 | return Err(TokenError::Claim("aud")); |
| 454 | } |
| 455 | check_iat(&claims, now_secs())?; |
| 456 | let subject = text_claim(&claims, "sub")?.to_owned(); |
| 457 | let scopes = optional_text_claim(&claims, "scope") |
| 458 | .map(|scope| { |
| 459 | scope |
| 460 | .split(' ') |
| 461 | .filter(|s| !s.is_empty()) |
| 462 | .map(str::to_owned) |
| 463 | .collect() |
| 464 | }) |
| 465 | .unwrap_or_default(); |
| 466 | let svc = optional_text_claim(&claims, "svc").map(str::to_owned); |
| 467 | Ok(MachineClaims { |
| 468 | subject, |
| 469 | scopes, |
| 470 | svc, |
| 471 | }) |
| 472 | } |
| 473 | |
| 474 | #[cfg(test)] |
| 475 | impl OidcClient { |
| 476 | |
| 477 | |
| 478 | pub(crate) fn with_keys_for_tests(issuer: &str, client_id: &str, keys: KeySet) -> Self { |
| 479 | let config = Oidc { |
| 480 | issuer: issuer.to_owned(), |
| 481 | client_id: client_id.to_owned(), |
| 482 | client_secret_file: std::path::PathBuf::new(), |
| 483 | }; |
| 484 | let mut client = |
| 485 | Self::new(&config, "https://in.test", "test-secret".to_owned()).expect("client"); |
| 486 | let endpoints = client.standard_endpoints(); |
| 487 | let cache = client.cache.get_mut(); |
| 488 | cache.endpoints = Some(Arc::new(endpoints)); |
| 489 | cache.keys = Some((Instant::now(), Arc::new(keys))); |
| 490 | client |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | |
| 495 | #[cfg(test)] |
| 496 | pub(crate) mod test_support { |
| 497 | use super::*; |
| 498 | use ed25519_dalek::SigningKey; |
| 499 | use ed25519_dalek::pkcs8::EncodePrivateKey; |
| 500 | use jsonwebtoken::{EncodingKey, Header, encode}; |
| 501 | use serde_json::json; |
| 502 | |
| 503 | |
| 504 | pub(crate) const ISSUER: &str = "https://im.example.test"; |
| 505 | |
| 506 | pub(crate) const CLIENT: &str = "in"; |
| 507 | |
| 508 | pub(crate) const KID: &str = "k1"; |
| 509 | |
| 510 | |
| 511 | pub(crate) fn test_key() -> (Vec<u8>, KeySet) { |
| 512 | let mut seed = [0u8; 32]; |
| 513 | rand::fill(&mut seed); |
| 514 | let signing = SigningKey::from_bytes(&seed); |
| 515 | let der = signing.to_pkcs8_der().expect("pkcs8").as_bytes().to_vec(); |
| 516 | let x = BASE64_URL_SAFE_NO_PAD.encode(signing.verifying_key().to_bytes()); |
| 517 | let jwks: Jwks = serde_json::from_value(json!({ |
| 518 | "keys": [{"kty": "OKP", "crv": "Ed25519", "x": x, "kid": KID, "use": "sig", "alg": "EdDSA"}] |
| 519 | })) |
| 520 | .expect("jwks"); |
| 521 | (der, KeySet::from_jwks(&jwks)) |
| 522 | } |
| 523 | |
| 524 | |
| 525 | pub(crate) fn sign(der: &[u8], claims: &Value) -> String { |
| 526 | let mut header = Header::new(Algorithm::EdDSA); |
| 527 | header.kid = Some(KID.to_owned()); |
| 528 | encode(&header, claims, &EncodingKey::from_ed_der(der)).expect("sign") |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | |
| 533 | pub fn pkce_challenge(verifier: &str) -> String { |
| 534 | BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) |
| 535 | } |
| 536 | |
| 537 | |
| 538 | |
| 539 | |
| 540 | pub async fn read_limited( |
| 541 | mut response: reqwest::Response, |
| 542 | limit: usize, |
| 543 | ) -> Result<Option<Vec<u8>>, reqwest::Error> { |
| 544 | if response |
| 545 | .content_length() |
| 546 | .is_some_and(|len| len > u64::try_from(limit).unwrap_or(u64::MAX)) |
| 547 | { |
| 548 | return Ok(None); |
| 549 | } |
| 550 | let mut body = Vec::new(); |
| 551 | while let Some(chunk) = response.chunk().await? { |
| 552 | if body.len() + chunk.len() > limit { |
| 553 | return Ok(None); |
| 554 | } |
| 555 | body.extend_from_slice(&chunk); |
| 556 | } |
| 557 | Ok(Some(body)) |
| 558 | } |
| 559 | |
| 560 | |
| 561 | |
| 562 | async fn read_document(response: reqwest::Response) -> Result<Vec<u8>, OidcError> { |
| 563 | read_limited(response, MAX_DOCUMENT_BYTES) |
| 564 | .await |
| 565 | .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))? |
| 566 | .ok_or_else(|| { |
| 567 | OidcError::Unavailable(format!( |
| 568 | "an answer is larger than {MAX_DOCUMENT_BYTES} bytes" |
| 569 | )) |
| 570 | }) |
| 571 | } |
| 572 | |
| 573 | |
| 574 | |
| 575 | pub fn percent_encode(value: &str) -> String { |
| 576 | let mut out = String::with_capacity(value.len()); |
| 577 | for byte in value.bytes() { |
| 578 | if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { |
| 579 | out.push(char::from(byte)); |
| 580 | } else { |
| 581 | out.push_str(&format!("%{byte:02X}")); |
| 582 | } |
| 583 | } |
| 584 | out |
| 585 | } |
| 586 | |
| 587 | |
| 588 | #[derive(Debug, Deserialize)] |
| 589 | struct TokenResponse { |
| 590 | #[serde(default)] |
| 591 | id_token: Option<String>, |
| 592 | #[serde(default)] |
| 593 | access_token: Option<String>, |
| 594 | #[serde(default)] |
| 595 | expires_in: Option<u64>, |
| 596 | } |
| 597 | |
| 598 | |
| 599 | |
| 600 | #[derive(Default)] |
| 601 | struct Cache { |
| 602 | |
| 603 | endpoints: Option<Arc<Endpoints>>, |
| 604 | |
| 605 | |
| 606 | discovery_failed_at: Option<Instant>, |
| 607 | |
| 608 | keys: Option<(Instant, Arc<KeySet>)>, |
| 609 | |
| 610 | keys_refresh_at: Option<Instant>, |
| 611 | |
| 612 | service: Option<(String, Instant)>, |
| 613 | } |
| 614 | |
| 615 | |
| 616 | |
| 617 | |
| 618 | |
| 619 | |
| 620 | |
| 621 | fn keys_from_cache(cache: &Cache, force: bool) -> Option<Result<Arc<KeySet>, OidcError>> { |
| 622 | let recently_tried = cache |
| 623 | .keys_refresh_at |
| 624 | .is_some_and(|at| at.elapsed() < JWKS_REFRESH_GAP); |
| 625 | match &cache.keys { |
| 626 | Some((at, keys)) if at.elapsed() < JWKS_MAX_AGE && !force => Some(Ok(Arc::clone(keys))), |
| 627 | Some((_, keys)) if recently_tried => Some(Ok(Arc::clone(keys))), |
| 628 | None if recently_tried => Some(Err(OidcError::Unavailable( |
| 629 | "the signing keys are not available yet".to_owned(), |
| 630 | ))), |
| 631 | _ => None, |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | |
| 636 | pub struct OidcClient { |
| 637 | issuer: String, |
| 638 | client_id: String, |
| 639 | client_secret: String, |
| 640 | redirect_uri: String, |
| 641 | http: reqwest::Client, |
| 642 | stream_http: reqwest::Client, |
| 643 | cache: Mutex<Cache>, |
| 644 | |
| 645 | |
| 646 | refresh: Mutex<()>, |
| 647 | } |
| 648 | |
| 649 | impl OidcClient { |
| 650 | |
| 651 | |
| 652 | pub fn new(config: &Oidc, base_url: &str, client_secret: String) -> CoreResult<Self> { |
| 653 | let http = reqwest::Client::builder() |
| 654 | .timeout(HTTP_TIMEOUT) |
| 655 | .connect_timeout(HTTP_TIMEOUT) |
| 656 | .redirect(reqwest::redirect::Policy::none()) |
| 657 | .build() |
| 658 | .map_err(|e| CoreError::Config(format!("cannot build the HTTP client: {e}")))?; |
| 659 | |
| 660 | let stream_http = reqwest::Client::builder() |
| 661 | .connect_timeout(HTTP_TIMEOUT) |
| 662 | .read_timeout(STREAM_READ_TIMEOUT) |
| 663 | .redirect(reqwest::redirect::Policy::none()) |
| 664 | .build() |
| 665 | .map_err(|e| CoreError::Config(format!("cannot build the stream client: {e}")))?; |
| 666 | Ok(Self { |
| 667 | issuer: config.issuer.clone(), |
| 668 | client_id: config.client_id.clone(), |
| 669 | client_secret, |
| 670 | redirect_uri: format!("{base_url}/auth/callback"), |
| 671 | http, |
| 672 | stream_http, |
| 673 | cache: Mutex::new(Cache::default()), |
| 674 | refresh: Mutex::new(()), |
| 675 | }) |
| 676 | } |
| 677 | |
| 678 | |
| 679 | pub fn issuer(&self) -> &str { |
| 680 | &self.issuer |
| 681 | } |
| 682 | |
| 683 | |
| 684 | pub fn http(&self) -> &reqwest::Client { |
| 685 | &self.http |
| 686 | } |
| 687 | |
| 688 | |
| 689 | pub fn stream_http(&self) -> &reqwest::Client { |
| 690 | &self.stream_http |
| 691 | } |
| 692 | |
| 693 | |
| 694 | |
| 695 | pub async fn endpoints(&self) -> Arc<Endpoints> { |
| 696 | { |
| 697 | let cache = self.cache.lock().await; |
| 698 | if let Some(endpoints) = &cache.endpoints { |
| 699 | return Arc::clone(endpoints); |
| 700 | } |
| 701 | if cache |
| 702 | .discovery_failed_at |
| 703 | .is_some_and(|at| at.elapsed() < DISCOVERY_RETRY_GAP) |
| 704 | { |
| 705 | return Arc::new(self.standard_endpoints()); |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | |
| 710 | match self.fetch_discovery().await { |
| 711 | Ok(endpoints) => { |
| 712 | let endpoints = Arc::new(endpoints); |
| 713 | let mut cache = self.cache.lock().await; |
| 714 | cache.endpoints = Some(Arc::clone(&endpoints)); |
| 715 | cache.discovery_failed_at = None; |
| 716 | endpoints |
| 717 | } |
| 718 | Err(error) => { |
| 719 | tracing::warn!(error = %error, "oidc: discovery failed, using the standard paths"); |
| 720 | self.cache.lock().await.discovery_failed_at = Some(Instant::now()); |
| 721 | Arc::new(self.standard_endpoints()) |
| 722 | } |
| 723 | } |
| 724 | } |
| 725 | |
| 726 | |
| 727 | fn standard_endpoints(&self) -> Endpoints { |
| 728 | Endpoints { |
| 729 | authorization: format!("{}/authorize", self.issuer), |
| 730 | token: format!("{}/token", self.issuer), |
| 731 | jwks: format!("{}/jwks.json", self.issuer), |
| 732 | end_session: format!("{}/logout", self.issuer), |
| 733 | } |
| 734 | } |
| 735 | |
| 736 | |
| 737 | async fn fetch_discovery(&self) -> Result<Endpoints, OidcError> { |
| 738 | let url = format!("{}/.well-known/openid-configuration", self.issuer); |
| 739 | let document: DiscoveryDocument = self.get_json(&url).await?; |
| 740 | if document.issuer != self.issuer { |
| 741 | return Err(OidcError::Unavailable( |
| 742 | "discovery names another issuer".to_owned(), |
| 743 | )); |
| 744 | } |
| 745 | let end_session = document |
| 746 | .end_session_endpoint |
| 747 | .unwrap_or_else(|| format!("{}/logout", self.issuer)); |
| 748 | Ok(Endpoints { |
| 749 | authorization: document.authorization_endpoint, |
| 750 | token: document.token_endpoint, |
| 751 | jwks: document.jwks_uri, |
| 752 | end_session, |
| 753 | }) |
| 754 | } |
| 755 | |
| 756 | |
| 757 | async fn get_json<T: serde::de::DeserializeOwned>(&self, url: &str) -> Result<T, OidcError> { |
| 758 | let response = self |
| 759 | .http |
| 760 | .get(url) |
| 761 | .send() |
| 762 | .await |
| 763 | .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))?; |
| 764 | if !response.status().is_success() { |
| 765 | return Err(OidcError::Unavailable(format!( |
| 766 | "{url} answered {}", |
| 767 | response.status() |
| 768 | ))); |
| 769 | } |
| 770 | let bytes = read_document(response).await?; |
| 771 | serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) |
| 772 | } |
| 773 | |
| 774 | |
| 775 | |
| 776 | |
| 777 | async fn load_keys(&self, force: bool) -> Result<Arc<KeySet>, OidcError> { |
| 778 | let decided = keys_from_cache(&*self.cache.lock().await, force); |
| 779 | if let Some(answer) = decided { |
| 780 | return answer; |
| 781 | } |
| 782 | let _single_flight = self.refresh.lock().await; |
| 783 | |
| 784 | let decided = keys_from_cache(&*self.cache.lock().await, force); |
| 785 | if let Some(answer) = decided { |
| 786 | return answer; |
| 787 | } |
| 788 | let endpoints = self.endpoints().await; |
| 789 | |
| 790 | |
| 791 | if force { |
| 792 | self.cache.lock().await.keys_refresh_at = Some(Instant::now()); |
| 793 | } |
| 794 | let fetched = self.get_json::<Jwks>(&endpoints.jwks).await; |
| 795 | let mut cache = self.cache.lock().await; |
| 796 | if fetched.is_err() { |
| 797 | cache.keys_refresh_at = Some(Instant::now()); |
| 798 | } |
| 799 | match fetched { |
| 800 | Ok(jwks) => { |
| 801 | let keys = Arc::new(KeySet::from_jwks(&jwks)); |
| 802 | cache.keys = Some((Instant::now(), Arc::clone(&keys))); |
| 803 | Ok(keys) |
| 804 | } |
| 805 | Err(error) => match &cache.keys { |
| 806 | Some((_, keys)) => { |
| 807 | tracing::warn!(error = %error, "oidc: key fetch failed, keeping the cached keys"); |
| 808 | Ok(Arc::clone(keys)) |
| 809 | } |
| 810 | None => Err(error), |
| 811 | }, |
| 812 | } |
| 813 | } |
| 814 | |
| 815 | |
| 816 | |
| 817 | pub async fn verify_machine_token( |
| 818 | &self, |
| 819 | token: &str, |
| 820 | audience: &str, |
| 821 | ) -> Result<MachineClaims, OidcError> { |
| 822 | self.verify_with(token, |keys| { |
| 823 | verify_machine_token(keys, token, &self.issuer, audience) |
| 824 | }) |
| 825 | .await |
| 826 | } |
| 827 | |
| 828 | |
| 829 | |
| 830 | async fn verify_with<T>( |
| 831 | &self, |
| 832 | token: &str, |
| 833 | check: impl Fn(&KeySet) -> Result<T, TokenError>, |
| 834 | ) -> Result<T, OidcError> { |
| 835 | check_header(token)?; |
| 836 | let keys = self.load_keys(false).await?; |
| 837 | match check(&keys) { |
| 838 | Err(TokenError::UnknownKey) => { |
| 839 | let keys = self.load_keys(true).await?; |
| 840 | Ok(check(&keys)?) |
| 841 | } |
| 842 | outcome => Ok(outcome?), |
| 843 | } |
| 844 | } |
| 845 | |
| 846 | |
| 847 | pub async fn verify_id_token(&self, token: &str, nonce: &str) -> Result<IdClaims, OidcError> { |
| 848 | self.verify_with(token, |keys| { |
| 849 | verify_id_token(keys, token, &self.issuer, &self.client_id, nonce) |
| 850 | }) |
| 851 | .await |
| 852 | } |
| 853 | |
| 854 | |
| 855 | pub async fn verify_logout_token(&self, token: &str) -> Result<LogoutClaims, OidcError> { |
| 856 | self.verify_with(token, |keys| { |
| 857 | verify_logout_token(keys, token, &self.issuer, &self.client_id) |
| 858 | }) |
| 859 | .await |
| 860 | } |
| 861 | |
| 862 | |
| 863 | pub async fn authorize_url( |
| 864 | &self, |
| 865 | state: &str, |
| 866 | nonce: &str, |
| 867 | challenge: &str, |
| 868 | ) -> Result<String, OidcError> { |
| 869 | let endpoints = self.endpoints().await; |
| 870 | let mut url = reqwest::Url::parse(&endpoints.authorization) |
| 871 | .map_err(|e| OidcError::Unavailable(format!("bad authorization endpoint: {e}")))?; |
| 872 | url.query_pairs_mut() |
| 873 | .append_pair("response_type", "code") |
| 874 | .append_pair("client_id", &self.client_id) |
| 875 | .append_pair("redirect_uri", &self.redirect_uri) |
| 876 | .append_pair("scope", "openid profile email") |
| 877 | .append_pair("state", state) |
| 878 | .append_pair("nonce", nonce) |
| 879 | .append_pair("code_challenge", challenge) |
| 880 | .append_pair("code_challenge_method", "S256"); |
| 881 | Ok(url.to_string()) |
| 882 | } |
| 883 | |
| 884 | |
| 885 | pub async fn end_session_url( |
| 886 | &self, |
| 887 | id_token_hint: &str, |
| 888 | post_logout_redirect: &str, |
| 889 | state: &str, |
| 890 | ) -> Result<String, OidcError> { |
| 891 | let endpoints = self.endpoints().await; |
| 892 | let mut url = reqwest::Url::parse(&endpoints.end_session) |
| 893 | .map_err(|e| OidcError::Unavailable(format!("bad end-session endpoint: {e}")))?; |
| 894 | url.query_pairs_mut() |
| 895 | .append_pair("id_token_hint", id_token_hint) |
| 896 | .append_pair("post_logout_redirect_uri", post_logout_redirect) |
| 897 | .append_pair("state", state); |
| 898 | Ok(url.to_string()) |
| 899 | } |
| 900 | |
| 901 | |
| 902 | |
| 903 | pub async fn exchange_code(&self, code: &str, verifier: &str) -> Result<String, OidcError> { |
| 904 | let endpoints = self.endpoints().await; |
| 905 | let response = self |
| 906 | .token_request( |
| 907 | &endpoints.token, |
| 908 | &[ |
| 909 | ("grant_type", "authorization_code"), |
| 910 | ("code", code), |
| 911 | ("redirect_uri", &self.redirect_uri), |
| 912 | ("code_verifier", verifier), |
| 913 | ], |
| 914 | ) |
| 915 | .await?; |
| 916 | response |
| 917 | .id_token |
| 918 | .ok_or(OidcError::Token(TokenError::Claim("id_token"))) |
| 919 | } |
| 920 | |
| 921 | |
| 922 | |
| 923 | pub async fn service_token(&self) -> Result<String, OidcError> { |
| 924 | { |
| 925 | let cache = self.cache.lock().await; |
| 926 | if let Some((token, until)) = &cache.service |
| 927 | && Instant::now() < *until |
| 928 | { |
| 929 | return Ok(token.clone()); |
| 930 | } |
| 931 | } |
| 932 | let endpoints = self.endpoints().await; |
| 933 | let response = self |
| 934 | .token_request( |
| 935 | &endpoints.token, |
| 936 | &[ |
| 937 | ("grant_type", "client_credentials"), |
| 938 | ("scope", DIRECTORY_SCOPE), |
| 939 | ("audience", IM_KEY), |
| 940 | ], |
| 941 | ) |
| 942 | .await?; |
| 943 | let token = response |
| 944 | .access_token |
| 945 | .ok_or(OidcError::Token(TokenError::Claim("access_token")))?; |
| 946 | let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0)); |
| 947 | let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN); |
| 948 | self.cache.lock().await.service = Some((token.clone(), until)); |
| 949 | Ok(token) |
| 950 | } |
| 951 | |
| 952 | |
| 953 | |
| 954 | async fn token_request( |
| 955 | &self, |
| 956 | url: &str, |
| 957 | form: &[(&str, &str)], |
| 958 | ) -> Result<TokenResponse, OidcError> { |
| 959 | let credentials = format!( |
| 960 | "{}:{}", |
| 961 | percent_encode(&self.client_id), |
| 962 | percent_encode(&self.client_secret) |
| 963 | ); |
| 964 | let response = self |
| 965 | .http |
| 966 | .post(url) |
| 967 | .header( |
| 968 | reqwest::header::AUTHORIZATION, |
| 969 | format!("Basic {}", BASE64_STANDARD.encode(credentials)), |
| 970 | ) |
| 971 | .header(reqwest::header::ACCEPT, "application/json") |
| 972 | .form(form) |
| 973 | .send() |
| 974 | .await |
| 975 | .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))?; |
| 976 | let status = response.status(); |
| 977 | if status.is_client_error() { |
| 978 | tracing::warn!(status = %status, "oidc: the token endpoint refused the request"); |
| 979 | return Err(OidcError::Refused); |
| 980 | } |
| 981 | if !status.is_success() { |
| 982 | return Err(OidcError::Unavailable(format!( |
| 983 | "token endpoint answered {status}" |
| 984 | ))); |
| 985 | } |
| 986 | let bytes = read_document(response).await?; |
| 987 | serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | #[cfg(test)] |
| 992 | mod tests { |
| 993 | use super::test_support::{CLIENT, ISSUER, sign, test_key}; |
| 994 | use super::*; |
| 995 | use serde_json::json; |
| 996 | |
| 997 | const NONCE: &str = "nonce-value"; |
| 998 | |
| 999 | fn id_claims(now: i64) -> Value { |
| 1000 | json!({ |
| 1001 | "iss": ISSUER, "sub": "01JTESTSUB", "aud": CLIENT, "exp": now + 300, "iat": now, |
| 1002 | "nonce": NONCE, "sid": "im-session-1", "email": "ann@example.test", "name": "Ann", |
| 1003 | }) |
| 1004 | } |
| 1005 | |
| 1006 | #[test] |
| 1007 | fn a_valid_id_token_is_accepted() { |
| 1008 | let (der, keys) = test_key(); |
| 1009 | let token = sign(&der, &id_claims(now_secs())); |
| 1010 | let claims = verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).expect("valid"); |
| 1011 | assert_eq!(claims.sub, "01JTESTSUB"); |
| 1012 | assert_eq!(claims.sid, "im-session-1"); |
| 1013 | assert_eq!(claims.locale, "en"); |
| 1014 | } |
| 1015 | |
| 1016 | #[test] |
| 1017 | fn an_unsigned_alg_none_token_is_refused() { |
| 1018 | let (_der, keys) = test_key(); |
| 1019 | let header = BASE64_URL_SAFE_NO_PAD.encode(br#"{"alg":"none","kid":"k1","typ":"JWT"}"#); |
| 1020 | let payload = BASE64_URL_SAFE_NO_PAD.encode(id_claims(now_secs()).to_string()); |
| 1021 | let token = format!("{header}.{payload}."); |
| 1022 | assert_eq!( |
| 1023 | verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(), |
| 1024 | Some(TokenError::Algorithm) |
| 1025 | ); |
| 1026 | } |
| 1027 | |
| 1028 | #[test] |
| 1029 | fn a_token_for_another_audience_is_refused() { |
| 1030 | let (der, keys) = test_key(); |
| 1031 | let mut claims = id_claims(now_secs()); |
| 1032 | claims["aud"] = json!("iz"); |
| 1033 | let token = sign(&der, &claims); |
| 1034 | assert_eq!( |
| 1035 | verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(), |
| 1036 | Some(TokenError::Claim("aud")) |
| 1037 | ); |
| 1038 | } |
| 1039 | |
| 1040 | #[test] |
| 1041 | fn an_expired_token_is_refused_beyond_the_leeway() { |
| 1042 | let (der, keys) = test_key(); |
| 1043 | let now = now_secs(); |
| 1044 | let mut claims = id_claims(now); |
| 1045 | claims["exp"] = json!(now - 3 * CLOCK_LEEWAY_SECS); |
| 1046 | let token = sign(&der, &claims); |
| 1047 | assert_eq!( |
| 1048 | verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(), |
| 1049 | Some(TokenError::Expired) |
| 1050 | ); |
| 1051 | } |
| 1052 | |
| 1053 | #[test] |
| 1054 | fn a_wrong_nonce_is_refused() { |
| 1055 | let (der, keys) = test_key(); |
| 1056 | let token = sign(&der, &id_claims(now_secs())); |
| 1057 | assert_eq!( |
| 1058 | verify_id_token(&keys, &token, ISSUER, CLIENT, "another-nonce").err(), |
| 1059 | Some(TokenError::Nonce) |
| 1060 | ); |
| 1061 | } |
| 1062 | |
| 1063 | #[test] |
| 1064 | fn the_pkce_challenge_matches_the_rfc_7636_vector() { |
| 1065 | assert_eq!( |
| 1066 | pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), |
| 1067 | "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" |
| 1068 | ); |
| 1069 | } |
| 1070 | } |