| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | use std::collections::HashMap; |
| 19 | use std::fmt; |
| 20 | use std::path::Path; |
| 21 | use std::sync::Arc; |
| 22 | use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; |
| 23 | |
| 24 | use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; |
| 25 | use futures_util::StreamExt; |
| 26 | use iz_core::config::OidcConfig; |
| 27 | use iz_core::token::constant_time_eq; |
| 28 | use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; |
| 29 | use serde::Deserialize; |
| 30 | use serde_json::{Map, Value}; |
| 31 | use sha2::{Digest, Sha256}; |
| 32 | use tokio::sync::Mutex; |
| 33 | |
| 34 | |
| 35 | pub const DIRECTORY_SCOPE: &str = "directory.read"; |
| 36 | |
| 37 | pub const IM_AUDIENCE: &str = "im"; |
| 38 | |
| 39 | pub const SIGN_IN_SCOPE: &str = "openid profile email"; |
| 40 | |
| 41 | pub const BACKCHANNEL_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout"; |
| 42 | |
| 43 | |
| 44 | |
| 45 | pub const IM_TIMEOUT: Duration = Duration::from_secs(10); |
| 46 | |
| 47 | pub const LEEWAY_SECS: u64 = 60; |
| 48 | |
| 49 | pub const MAX_IAT_AHEAD_SECS: u64 = 300; |
| 50 | |
| 51 | |
| 52 | pub const MAX_RESPONSE_BYTES: usize = 256 * 1024; |
| 53 | |
| 54 | const DISCOVERY_TTL: Duration = Duration::from_secs(3600); |
| 55 | |
| 56 | const KEYS_TTL: Duration = Duration::from_secs(600); |
| 57 | |
| 58 | |
| 59 | const UNKNOWN_KEY_REFETCH: Duration = Duration::from_secs(60); |
| 60 | |
| 61 | const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60); |
| 62 | |
| 63 | |
| 64 | #[derive(Debug, thiserror::Error)] |
| 65 | pub enum ImError { |
| 66 | |
| 67 | |
| 68 | #[error("the token names a key that is not published")] |
| 69 | UnknownKey, |
| 70 | |
| 71 | #[error("the token was rejected: {0}")] |
| 72 | Rejected(String), |
| 73 | |
| 74 | #[error("the account service cannot be reached: {0}")] |
| 75 | Unavailable(String), |
| 76 | |
| 77 | #[error("the account service answered in an unexpected way: {0}")] |
| 78 | BadResponse(String), |
| 79 | } |
| 80 | |
| 81 | |
| 82 | pub type ImResult<T> = std::result::Result<T, ImError>; |
| 83 | |
| 84 | |
| 85 | #[derive(Debug, Deserialize)] |
| 86 | pub struct Discovery { |
| 87 | |
| 88 | pub issuer: String, |
| 89 | |
| 90 | pub authorization_endpoint: String, |
| 91 | |
| 92 | pub token_endpoint: String, |
| 93 | |
| 94 | pub jwks_uri: String, |
| 95 | |
| 96 | #[serde(default)] |
| 97 | pub end_session_endpoint: Option<String>, |
| 98 | } |
| 99 | |
| 100 | |
| 101 | #[derive(Deserialize)] |
| 102 | pub struct TokenResponse { |
| 103 | |
| 104 | #[serde(default)] |
| 105 | pub id_token: Option<String>, |
| 106 | |
| 107 | #[serde(default)] |
| 108 | pub access_token: Option<String>, |
| 109 | |
| 110 | #[serde(default)] |
| 111 | pub expires_in: Option<u64>, |
| 112 | } |
| 113 | |
| 114 | |
| 115 | impl fmt::Debug for TokenResponse { |
| 116 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 117 | f.debug_struct("TokenResponse") |
| 118 | .field("id_token", &self.id_token.as_ref().map(|_| "<redacted>")) |
| 119 | .field( |
| 120 | "access_token", |
| 121 | &self.access_token.as_ref().map(|_| "<redacted>"), |
| 122 | ) |
| 123 | .field("expires_in", &self.expires_in) |
| 124 | .finish() |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | |
| 129 | #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] |
| 130 | pub struct IdClaims { |
| 131 | |
| 132 | pub sub: String, |
| 133 | |
| 134 | #[serde(default)] |
| 135 | pub sid: Option<String>, |
| 136 | |
| 137 | #[serde(default)] |
| 138 | pub email: Option<String>, |
| 139 | |
| 140 | #[serde(default)] |
| 141 | pub name: Option<String>, |
| 142 | |
| 143 | #[serde(default)] |
| 144 | pub admin: bool, |
| 145 | |
| 146 | #[serde(default)] |
| 147 | pub locale: Option<String>, |
| 148 | |
| 149 | #[serde(default)] |
| 150 | pub zoneinfo: Option<String>, |
| 151 | |
| 152 | #[serde(default)] |
| 153 | pub picture_version: i64, |
| 154 | |
| 155 | #[serde(default)] |
| 156 | pub iat: i64, |
| 157 | } |
| 158 | |
| 159 | |
| 160 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 161 | pub struct LogoutClaims { |
| 162 | |
| 163 | pub jti: String, |
| 164 | |
| 165 | pub sid: Option<String>, |
| 166 | |
| 167 | pub sub: Option<String>, |
| 168 | } |
| 169 | |
| 170 | #[derive(Deserialize)] |
| 171 | struct JwksDocument { |
| 172 | keys: Vec<Jwk>, |
| 173 | } |
| 174 | |
| 175 | #[derive(Deserialize)] |
| 176 | struct Jwk { |
| 177 | kty: String, |
| 178 | #[serde(default)] |
| 179 | crv: Option<String>, |
| 180 | #[serde(default)] |
| 181 | x: Option<String>, |
| 182 | #[serde(default)] |
| 183 | kid: Option<String>, |
| 184 | #[serde(default)] |
| 185 | alg: Option<String>, |
| 186 | } |
| 187 | |
| 188 | |
| 189 | #[derive(Default)] |
| 190 | pub struct KeySet { |
| 191 | keys: HashMap<String, DecodingKey>, |
| 192 | } |
| 193 | |
| 194 | impl KeySet { |
| 195 | |
| 196 | pub fn from_jwks(bytes: &[u8]) -> ImResult<KeySet> { |
| 197 | let document: JwksDocument = serde_json::from_slice(bytes) |
| 198 | .map_err(|e| ImError::BadResponse(format!("the key set is not JSON: {e}")))?; |
| 199 | let mut keys = HashMap::new(); |
| 200 | for jwk in document.keys { |
| 201 | let (Some(kid), Some(x)) = (jwk.kid.as_deref(), jwk.x.as_deref()) else { |
| 202 | continue; |
| 203 | }; |
| 204 | let is_ed25519 = jwk.kty == "OKP" && jwk.crv.as_deref() == Some("Ed25519"); |
| 205 | if !is_ed25519 || jwk.alg.as_deref().is_some_and(|alg| alg != "EdDSA") { |
| 206 | continue; |
| 207 | } |
| 208 | match DecodingKey::from_ed_components(x) { |
| 209 | Ok(key) => { |
| 210 | keys.insert(kid.to_owned(), key); |
| 211 | } |
| 212 | Err(e) => tracing::warn!(kid, error = %e, "skipping an unreadable signing key"), |
| 213 | } |
| 214 | } |
| 215 | Ok(KeySet { keys }) |
| 216 | } |
| 217 | |
| 218 | fn get(&self, kid: &str) -> Option<&DecodingKey> { |
| 219 | self.keys.get(kid) |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | |
| 224 | pub struct OidcClient { |
| 225 | issuer: String, |
| 226 | client_id: String, |
| 227 | client_secret: String, |
| 228 | redirect_uri: String, |
| 229 | post_logout_uri: String, |
| 230 | |
| 231 | http: reqwest::Client, |
| 232 | |
| 233 | stream_http: reqwest::Client, |
| 234 | discovery: Mutex<Option<(Instant, Arc<Discovery>)>>, |
| 235 | keys: Mutex<KeyCache>, |
| 236 | |
| 237 | |
| 238 | refresh: Mutex<()>, |
| 239 | |
| 240 | service: Mutex<HashMap<(String, String), (Instant, String)>>, |
| 241 | } |
| 242 | |
| 243 | #[derive(Default)] |
| 244 | struct KeyCache { |
| 245 | |
| 246 | current: Option<(Instant, Arc<KeySet>)>, |
| 247 | |
| 248 | last_fetch: Option<Instant>, |
| 249 | } |
| 250 | |
| 251 | impl OidcClient { |
| 252 | |
| 253 | |
| 254 | pub fn new( |
| 255 | config: &OidcConfig, |
| 256 | base_url: &str, |
| 257 | client_secret: String, |
| 258 | ) -> iz_core::Result<Self> { |
| 259 | |
| 260 | |
| 261 | let http = reqwest::Client::builder() |
| 262 | .timeout(IM_TIMEOUT) |
| 263 | .connect_timeout(IM_TIMEOUT) |
| 264 | .redirect(reqwest::redirect::Policy::none()) |
| 265 | .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION"))) |
| 266 | .build() |
| 267 | .map_err(|e| iz_core::Error::Config(format!("cannot build the HTTP client: {e}")))?; |
| 268 | let stream_http = reqwest::Client::builder() |
| 269 | .connect_timeout(IM_TIMEOUT) |
| 270 | .redirect(reqwest::redirect::Policy::none()) |
| 271 | .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION"))) |
| 272 | .build() |
| 273 | .map_err(|e| iz_core::Error::Config(format!("cannot build the HTTP client: {e}")))?; |
| 274 | Ok(OidcClient { |
| 275 | issuer: config.issuer.clone(), |
| 276 | client_id: config.client_id.clone(), |
| 277 | client_secret, |
| 278 | redirect_uri: format!("{base_url}/auth/callback"), |
| 279 | post_logout_uri: format!("{base_url}/"), |
| 280 | http, |
| 281 | stream_http, |
| 282 | discovery: Mutex::new(None), |
| 283 | keys: Mutex::new(KeyCache::default()), |
| 284 | refresh: Mutex::new(()), |
| 285 | service: Mutex::new(HashMap::new()), |
| 286 | }) |
| 287 | } |
| 288 | |
| 289 | |
| 290 | pub fn issuer(&self) -> &str { |
| 291 | &self.issuer |
| 292 | } |
| 293 | |
| 294 | |
| 295 | pub fn http(&self) -> &reqwest::Client { |
| 296 | &self.http |
| 297 | } |
| 298 | |
| 299 | |
| 300 | pub fn stream_http(&self) -> &reqwest::Client { |
| 301 | &self.stream_http |
| 302 | } |
| 303 | |
| 304 | |
| 305 | pub async fn discovery(&self) -> ImResult<Arc<Discovery>> { |
| 306 | let mut slot = self.discovery.lock().await; |
| 307 | if let Some((at, doc)) = slot.as_ref() |
| 308 | && at.elapsed() < DISCOVERY_TTL |
| 309 | { |
| 310 | return Ok(doc.clone()); |
| 311 | } |
| 312 | let url = format!("{}/.well-known/openid-configuration", self.issuer); |
| 313 | let response = self.http.get(url).send().await.map_err(unavailable)?; |
| 314 | if !response.status().is_success() { |
| 315 | return Err(ImError::Unavailable(format!( |
| 316 | "discovery answered {}", |
| 317 | response.status().as_u16() |
| 318 | ))); |
| 319 | } |
| 320 | let body = read_limited(response, MAX_RESPONSE_BYTES).await?; |
| 321 | let doc: Discovery = serde_json::from_slice(&body) |
| 322 | .map_err(|e| ImError::BadResponse(format!("discovery: {e}")))?; |
| 323 | if doc.issuer != self.issuer { |
| 324 | return Err(ImError::BadResponse( |
| 325 | "discovery names another issuer".into(), |
| 326 | )); |
| 327 | } |
| 328 | let doc = Arc::new(doc); |
| 329 | *slot = Some((Instant::now(), doc.clone())); |
| 330 | Ok(doc) |
| 331 | } |
| 332 | |
| 333 | |
| 334 | |
| 335 | |
| 336 | |
| 337 | async fn key_set(&self, refetch_unknown: bool) -> ImResult<Arc<KeySet>> { |
| 338 | if let Some(keys) = self.keys_without_fetch(refetch_unknown).await? { |
| 339 | return Ok(keys); |
| 340 | } |
| 341 | |
| 342 | |
| 343 | |
| 344 | let _single_flight = self.refresh.lock().await; |
| 345 | if let Some(keys) = self.keys_without_fetch(refetch_unknown).await? { |
| 346 | return Ok(keys); |
| 347 | } |
| 348 | |
| 349 | |
| 350 | if refetch_unknown { |
| 351 | self.keys.lock().await.last_fetch = Some(Instant::now()); |
| 352 | } |
| 353 | let fetched = self.fetch_keys().await; |
| 354 | let mut cache = self.keys.lock().await; |
| 355 | if fetched.is_err() { |
| 356 | cache.last_fetch = Some(Instant::now()); |
| 357 | } |
| 358 | match fetched { |
| 359 | Ok(keys) => { |
| 360 | cache.current = Some((Instant::now(), keys.clone())); |
| 361 | Ok(keys) |
| 362 | } |
| 363 | Err(error) => match &cache.current { |
| 364 | Some((_, keys)) => { |
| 365 | tracing::warn!(error = %error, "oidc: key fetch failed, keeping the cached keys"); |
| 366 | Ok(keys.clone()) |
| 367 | } |
| 368 | None => Err(error), |
| 369 | }, |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | |
| 374 | |
| 375 | |
| 376 | async fn keys_without_fetch(&self, refetch_unknown: bool) -> ImResult<Option<Arc<KeySet>>> { |
| 377 | let cache = self.keys.lock().await; |
| 378 | let attempted_recently = cache |
| 379 | .last_fetch |
| 380 | .is_some_and(|at| at.elapsed() < UNKNOWN_KEY_REFETCH); |
| 381 | match &cache.current { |
| 382 | Some((at, keys)) => { |
| 383 | let fresh = at.elapsed() < KEYS_TTL && !refetch_unknown; |
| 384 | Ok((fresh || attempted_recently).then(|| keys.clone())) |
| 385 | } |
| 386 | None if attempted_recently => Err(ImError::Unavailable( |
| 387 | "the key set has not been fetched yet".into(), |
| 388 | )), |
| 389 | None => Ok(None), |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | |
| 394 | async fn fetch_keys(&self) -> ImResult<Arc<KeySet>> { |
| 395 | let discovery = self.discovery().await?; |
| 396 | let response = self |
| 397 | .http |
| 398 | .get(&discovery.jwks_uri) |
| 399 | .send() |
| 400 | .await |
| 401 | .map_err(unavailable)?; |
| 402 | if !response.status().is_success() { |
| 403 | return Err(ImError::Unavailable(format!( |
| 404 | "the key set answered {}", |
| 405 | response.status().as_u16() |
| 406 | ))); |
| 407 | } |
| 408 | let body = read_limited(response, MAX_RESPONSE_BYTES).await?; |
| 409 | Ok(Arc::new(KeySet::from_jwks(&body)?)) |
| 410 | } |
| 411 | |
| 412 | |
| 413 | |
| 414 | async fn with_keys<T>(&self, check: impl Fn(&KeySet) -> ImResult<T>) -> ImResult<T> { |
| 415 | let keys = self.key_set(false).await?; |
| 416 | match check(&keys) { |
| 417 | Err(ImError::UnknownKey) => { |
| 418 | let keys = self.key_set(true).await?; |
| 419 | match check(&keys) { |
| 420 | Err(ImError::UnknownKey) => { |
| 421 | Err(ImError::Rejected("the signing key is not published".into())) |
| 422 | } |
| 423 | other => other, |
| 424 | } |
| 425 | } |
| 426 | other => other, |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | |
| 431 | pub async fn authorize_url( |
| 432 | &self, |
| 433 | state: &str, |
| 434 | nonce: &str, |
| 435 | challenge: &str, |
| 436 | ) -> ImResult<String> { |
| 437 | let discovery = self.discovery().await?; |
| 438 | let mut url = reqwest::Url::parse(&discovery.authorization_endpoint) |
| 439 | .map_err(|e| ImError::BadResponse(format!("authorization endpoint: {e}")))?; |
| 440 | url.query_pairs_mut() |
| 441 | .append_pair("response_type", "code") |
| 442 | .append_pair("client_id", &self.client_id) |
| 443 | .append_pair("redirect_uri", &self.redirect_uri) |
| 444 | .append_pair("scope", SIGN_IN_SCOPE) |
| 445 | .append_pair("state", state) |
| 446 | .append_pair("nonce", nonce) |
| 447 | .append_pair("code_challenge", challenge) |
| 448 | .append_pair("code_challenge_method", "S256"); |
| 449 | Ok(url.into()) |
| 450 | } |
| 451 | |
| 452 | |
| 453 | |
| 454 | pub async fn end_session_url( |
| 455 | &self, |
| 456 | id_token_hint: Option<&str>, |
| 457 | state: &str, |
| 458 | ) -> ImResult<String> { |
| 459 | let discovery = self.discovery().await?; |
| 460 | let endpoint = discovery |
| 461 | .end_session_endpoint |
| 462 | .as_deref() |
| 463 | .ok_or_else(|| ImError::BadResponse("no end_session_endpoint".into()))?; |
| 464 | let mut url = reqwest::Url::parse(endpoint) |
| 465 | .map_err(|e| ImError::BadResponse(format!("end_session endpoint: {e}")))?; |
| 466 | { |
| 467 | let mut query = url.query_pairs_mut(); |
| 468 | if let Some(hint) = id_token_hint { |
| 469 | query.append_pair("id_token_hint", hint); |
| 470 | } |
| 471 | query |
| 472 | .append_pair("post_logout_redirect_uri", &self.post_logout_uri) |
| 473 | .append_pair("state", state); |
| 474 | } |
| 475 | Ok(url.into()) |
| 476 | } |
| 477 | |
| 478 | |
| 479 | pub async fn exchange_code(&self, code: &str, verifier: &str) -> ImResult<TokenResponse> { |
| 480 | let discovery = self.discovery().await?; |
| 481 | let form = [ |
| 482 | ("grant_type", "authorization_code"), |
| 483 | ("code", code), |
| 484 | ("redirect_uri", self.redirect_uri.as_str()), |
| 485 | ("code_verifier", verifier), |
| 486 | ]; |
| 487 | self.post_token(&discovery.token_endpoint, &form).await |
| 488 | } |
| 489 | |
| 490 | |
| 491 | pub async fn service_token(&self) -> ImResult<String> { |
| 492 | self.client_token(IM_AUDIENCE, DIRECTORY_SCOPE).await |
| 493 | } |
| 494 | |
| 495 | |
| 496 | |
| 497 | |
| 498 | pub async fn client_token(&self, audience: &str, scope: &str) -> ImResult<String> { |
| 499 | let key = (audience.to_owned(), scope.to_owned()); |
| 500 | let mut slots = self.service.lock().await; |
| 501 | if let Some((until, token)) = slots.get(&key) |
| 502 | && Instant::now() < *until |
| 503 | { |
| 504 | return Ok(token.clone()); |
| 505 | } |
| 506 | let discovery = self.discovery().await?; |
| 507 | let form = [ |
| 508 | ("grant_type", "client_credentials"), |
| 509 | ("scope", scope), |
| 510 | ("audience", audience), |
| 511 | ]; |
| 512 | let response = self.post_token(&discovery.token_endpoint, &form).await?; |
| 513 | let token = response |
| 514 | .access_token |
| 515 | .filter(|token| !token.is_empty()) |
| 516 | .ok_or_else(|| ImError::BadResponse("the token answer has no access token".into()))?; |
| 517 | let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0)); |
| 518 | let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN); |
| 519 | slots.insert(key, (until, token.clone())); |
| 520 | Ok(token) |
| 521 | } |
| 522 | |
| 523 | |
| 524 | async fn post_token(&self, url: &str, form: &[(&str, &str)]) -> ImResult<TokenResponse> { |
| 525 | let response = self |
| 526 | .http |
| 527 | .post(url) |
| 528 | .basic_auth(&self.client_id, Some(&self.client_secret)) |
| 529 | .form(form) |
| 530 | .send() |
| 531 | .await |
| 532 | .map_err(unavailable)?; |
| 533 | let status = response.status(); |
| 534 | let body = read_limited(response, MAX_RESPONSE_BYTES).await?; |
| 535 | if !status.is_success() { |
| 536 | |
| 537 | return Err(ImError::Rejected(format!( |
| 538 | "the token endpoint answered {}", |
| 539 | status.as_u16() |
| 540 | ))); |
| 541 | } |
| 542 | serde_json::from_slice(&body) |
| 543 | .map_err(|e| ImError::BadResponse(format!("the token answer: {e}"))) |
| 544 | } |
| 545 | |
| 546 | |
| 547 | pub async fn verify_id_token(&self, token: &str, nonce: &str) -> ImResult<IdClaims> { |
| 548 | check_shape(token)?; |
| 549 | let now = unix_now(); |
| 550 | self.with_keys(|keys| { |
| 551 | verify_id_token(keys, &self.issuer, &self.client_id, token, nonce, now) |
| 552 | }) |
| 553 | .await |
| 554 | } |
| 555 | |
| 556 | |
| 557 | pub async fn verify_logout_token(&self, token: &str) -> ImResult<LogoutClaims> { |
| 558 | check_shape(token)?; |
| 559 | let now = unix_now(); |
| 560 | self.with_keys(|keys| verify_logout_token(keys, &self.issuer, &self.client_id, token, now)) |
| 561 | .await |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | |
| 566 | pub fn pkce_challenge(verifier: &str) -> String { |
| 567 | BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) |
| 568 | } |
| 569 | |
| 570 | |
| 571 | pub fn unix_now() -> u64 { |
| 572 | SystemTime::now() |
| 573 | .duration_since(UNIX_EPOCH) |
| 574 | .map_or(0, |d| d.as_secs()) |
| 575 | } |
| 576 | |
| 577 | |
| 578 | pub fn verify_id_token( |
| 579 | keys: &KeySet, |
| 580 | issuer: &str, |
| 581 | client_id: &str, |
| 582 | token: &str, |
| 583 | nonce: &str, |
| 584 | now: u64, |
| 585 | ) -> ImResult<IdClaims> { |
| 586 | let claims = verify_signature(keys, issuer, client_id, token)?; |
| 587 | check_iat(&claims, now)?; |
| 588 | let sent = str_claim(&claims, "nonce") |
| 589 | .ok_or_else(|| ImError::Rejected("the nonce claim is missing".into()))?; |
| 590 | if !constant_time_eq(sent.as_bytes(), nonce.as_bytes()) { |
| 591 | return Err(ImError::Rejected( |
| 592 | "the nonce does not match this sign-in".into(), |
| 593 | )); |
| 594 | } |
| 595 | let id: IdClaims = serde_json::from_value(Value::Object(claims)) |
| 596 | .map_err(|e| ImError::Rejected(format!("the claims are malformed: {e}")))?; |
| 597 | if id.sub.is_empty() || id.sub.len() > 64 { |
| 598 | return Err(ImError::Rejected("the subject is not a member id".into())); |
| 599 | } |
| 600 | Ok(id) |
| 601 | } |
| 602 | |
| 603 | |
| 604 | |
| 605 | |
| 606 | pub fn verify_logout_token( |
| 607 | keys: &KeySet, |
| 608 | issuer: &str, |
| 609 | client_id: &str, |
| 610 | token: &str, |
| 611 | now: u64, |
| 612 | ) -> ImResult<LogoutClaims> { |
| 613 | let claims = verify_signature(keys, issuer, client_id, token)?; |
| 614 | check_iat(&claims, now)?; |
| 615 | if claims.contains_key("nonce") { |
| 616 | return Err(ImError::Rejected( |
| 617 | "a logout token must not carry a nonce".into(), |
| 618 | )); |
| 619 | } |
| 620 | let events = claims |
| 621 | .get("events") |
| 622 | .and_then(Value::as_object) |
| 623 | .ok_or_else(|| ImError::Rejected("the events claim is missing".into()))?; |
| 624 | if !events.contains_key(BACKCHANNEL_EVENT) { |
| 625 | return Err(ImError::Rejected( |
| 626 | "the event is not back-channel logout".into(), |
| 627 | )); |
| 628 | } |
| 629 | let jti = str_claim(&claims, "jti") |
| 630 | .ok_or_else(|| ImError::Rejected("the jti claim is missing".into()))?; |
| 631 | let sid = str_claim(&claims, "sid"); |
| 632 | let sub = str_claim(&claims, "sub"); |
| 633 | if sid.is_none() && sub.is_none() { |
| 634 | return Err(ImError::Rejected( |
| 635 | "the token names neither sid nor sub".into(), |
| 636 | )); |
| 637 | } |
| 638 | Ok(LogoutClaims { jti, sid, sub }) |
| 639 | } |
| 640 | |
| 641 | |
| 642 | |
| 643 | fn check_shape(token: &str) -> ImResult<()> { |
| 644 | if token.split('.').count() != 3 { |
| 645 | return Err(ImError::Rejected( |
| 646 | "the token does not have three segments".into(), |
| 647 | )); |
| 648 | } |
| 649 | let header = decode_header(token) |
| 650 | .map_err(|e| ImError::Rejected(format!("the header is malformed: {e}")))?; |
| 651 | if header.alg != Algorithm::EdDSA { |
| 652 | return Err(ImError::Rejected(format!( |
| 653 | "the algorithm {:?} is not accepted", |
| 654 | header.alg |
| 655 | ))); |
| 656 | } |
| 657 | if header.kid.is_none() { |
| 658 | return Err(ImError::Rejected("the header has no kid".into())); |
| 659 | } |
| 660 | Ok(()) |
| 661 | } |
| 662 | |
| 663 | |
| 664 | |
| 665 | fn verify_signature( |
| 666 | keys: &KeySet, |
| 667 | issuer: &str, |
| 668 | client_id: &str, |
| 669 | token: &str, |
| 670 | ) -> ImResult<Map<String, Value>> { |
| 671 | |
| 672 | let header = decode_header(token) |
| 673 | .map_err(|e| ImError::Rejected(format!("the header is malformed: {e}")))?; |
| 674 | if header.alg != Algorithm::EdDSA { |
| 675 | return Err(ImError::Rejected(format!( |
| 676 | "the algorithm {:?} is not accepted", |
| 677 | header.alg |
| 678 | ))); |
| 679 | } |
| 680 | let kid = header |
| 681 | .kid |
| 682 | .as_deref() |
| 683 | .ok_or_else(|| ImError::Rejected("the header has no kid".into()))?; |
| 684 | let key = keys.get(kid).ok_or(ImError::UnknownKey)?; |
| 685 | let mut validation = Validation::new(Algorithm::EdDSA); |
| 686 | validation.leeway = LEEWAY_SECS; |
| 687 | validation.validate_nbf = true; |
| 688 | validation.set_issuer(&[issuer]); |
| 689 | validation.set_audience(&[client_id]); |
| 690 | validation.set_required_spec_claims(&["exp", "iss", "aud"]); |
| 691 | let data = decode::<Map<String, Value>>(token, key, &validation) |
| 692 | .map_err(|e| ImError::Rejected(e.to_string()))?; |
| 693 | |
| 694 | if !audience_is(data.claims.get("aud"), client_id) { |
| 695 | return Err(ImError::Rejected( |
| 696 | "the aud claim is not the client id".into(), |
| 697 | )); |
| 698 | } |
| 699 | Ok(data.claims) |
| 700 | } |
| 701 | |
| 702 | |
| 703 | |
| 704 | fn audience_is(aud: Option<&Value>, expected: &str) -> bool { |
| 705 | match aud { |
| 706 | Some(Value::String(single)) => single == expected, |
| 707 | Some(Value::Array(items)) => { |
| 708 | items.len() == 1 && items.first().and_then(Value::as_str) == Some(expected) |
| 709 | } |
| 710 | _ => false, |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | |
| 715 | fn check_iat(claims: &Map<String, Value>, now: u64) -> ImResult<()> { |
| 716 | let iat = claims |
| 717 | .get("iat") |
| 718 | .and_then(Value::as_u64) |
| 719 | .ok_or_else(|| ImError::Rejected("the iat claim is missing".into()))?; |
| 720 | if iat > now.saturating_add(MAX_IAT_AHEAD_SECS) { |
| 721 | return Err(ImError::Rejected("the iat claim is in the future".into())); |
| 722 | } |
| 723 | Ok(()) |
| 724 | } |
| 725 | |
| 726 | |
| 727 | fn str_claim(claims: &Map<String, Value>, name: &str) -> Option<String> { |
| 728 | claims |
| 729 | .get(name) |
| 730 | .and_then(Value::as_str) |
| 731 | .filter(|s| !s.is_empty()) |
| 732 | .map(str::to_owned) |
| 733 | } |
| 734 | |
| 735 | fn unavailable(error: reqwest::Error) -> ImError { |
| 736 | ImError::Unavailable(error.without_url().to_string()) |
| 737 | } |
| 738 | |
| 739 | |
| 740 | |
| 741 | pub async fn read_limited(response: reqwest::Response, limit: usize) -> ImResult<Vec<u8>> { |
| 742 | let too_large = || ImError::BadResponse("the answer is too large".into()); |
| 743 | if response |
| 744 | .content_length() |
| 745 | .is_some_and(|len| len > u64::try_from(limit).unwrap_or(u64::MAX)) |
| 746 | { |
| 747 | return Err(too_large()); |
| 748 | } |
| 749 | let mut body = Vec::new(); |
| 750 | let mut chunks = response.bytes_stream(); |
| 751 | while let Some(chunk) = chunks.next().await { |
| 752 | let chunk = chunk.map_err(unavailable)?; |
| 753 | if body.len() + chunk.len() > limit { |
| 754 | return Err(too_large()); |
| 755 | } |
| 756 | body.extend_from_slice(&chunk); |
| 757 | } |
| 758 | Ok(body) |
| 759 | } |
| 760 | |
| 761 | |
| 762 | |
| 763 | pub fn read_client_secret(path: &Path) -> iz_core::Result<String> { |
| 764 | #[cfg(unix)] |
| 765 | { |
| 766 | use std::os::unix::fs::PermissionsExt; |
| 767 | let mode = std::fs::metadata(path)?.permissions().mode(); |
| 768 | if mode & 0o077 != 0 { |
| 769 | return Err(iz_core::Error::Config(format!( |
| 770 | "client secret {} is group or world accessible (mode {:o}); expected 0600", |
| 771 | path.display(), |
| 772 | mode & 0o777 |
| 773 | ))); |
| 774 | } |
| 775 | } |
| 776 | let text = std::fs::read_to_string(path)?; |
| 777 | let secret = text.trim().to_owned(); |
| 778 | if secret.is_empty() { |
| 779 | return Err(iz_core::Error::Config(format!( |
| 780 | "client secret {} is empty", |
| 781 | path.display() |
| 782 | ))); |
| 783 | } |
| 784 | Ok(secret) |
| 785 | } |
| 786 | |
| 787 | #[cfg(test)] |
| 788 | pub(crate) mod test_support { |
| 789 | |
| 790 | |
| 791 | |
| 792 | use aws_lc_rs::rand::SystemRandom; |
| 793 | use aws_lc_rs::signature::{Ed25519KeyPair, KeyPair}; |
| 794 | use jsonwebtoken::{EncodingKey, Header, encode}; |
| 795 | use serde_json::{Value, json}; |
| 796 | |
| 797 | use super::KeySet; |
| 798 | |
| 799 | |
| 800 | pub const ISSUER: &str = "https://im.example.com"; |
| 801 | |
| 802 | pub const CLIENT_ID: &str = "iz"; |
| 803 | |
| 804 | |
| 805 | pub struct Signer { |
| 806 | pub keys: KeySet, |
| 807 | encoding: EncodingKey, |
| 808 | } |
| 809 | |
| 810 | impl Signer { |
| 811 | pub fn generate() -> Signer { |
| 812 | let pkcs8 = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).expect("keygen"); |
| 813 | let pair = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).expect("pkcs8"); |
| 814 | let x = base64::Engine::encode( |
| 815 | &base64::prelude::BASE64_URL_SAFE_NO_PAD, |
| 816 | pair.public_key().as_ref(), |
| 817 | ); |
| 818 | let jwks = json!({"keys": [{"kty": "OKP", "crv": "Ed25519", "x": x, "kid": "k1", "use": "sig", "alg": "EdDSA"}]}); |
| 819 | Signer { |
| 820 | keys: KeySet::from_jwks(jwks.to_string().as_bytes()).expect("jwks"), |
| 821 | encoding: EncodingKey::from_ed_der(pkcs8.as_ref()), |
| 822 | } |
| 823 | } |
| 824 | |
| 825 | |
| 826 | pub fn sign(&self, claims: &Value) -> String { |
| 827 | self.sign_with_kid("k1", claims) |
| 828 | } |
| 829 | |
| 830 | |
| 831 | pub fn sign_with_kid(&self, kid: &str, claims: &Value) -> String { |
| 832 | let mut header = Header::new(jsonwebtoken::Algorithm::EdDSA); |
| 833 | header.kid = Some(kid.into()); |
| 834 | encode(&header, claims, &self.encoding).expect("sign") |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | |
| 839 | pub fn id_claims(now: u64, nonce: &str) -> Value { |
| 840 | json!({ |
| 841 | "iss": ISSUER, "aud": CLIENT_ID, "sub": "01JMEMBER0000000000000000A", |
| 842 | "exp": now + 600, "iat": now, "auth_time": now, "nonce": nonce, |
| 843 | "sid": "sid-1", "email": "ada@example.com", "email_verified": true, |
| 844 | "name": "Ada", "admin": false, "locale": "en", "zoneinfo": "Europe/Istanbul", |
| 845 | "picture_version": 1 |
| 846 | }) |
| 847 | } |
| 848 | |
| 849 | |
| 850 | pub fn logout_claims(now: u64, jti: &str) -> Value { |
| 851 | json!({ |
| 852 | "iss": ISSUER, "aud": CLIENT_ID, "iat": now, "exp": now + 120, "jti": jti, |
| 853 | "sid": "sid-1", "sub": "01JMEMBER0000000000000000A", |
| 854 | "events": {"http://schemas.openid.net/event/backchannel-logout": {}} |
| 855 | }) |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | #[cfg(test)] |
| 860 | mod tests { |
| 861 | use super::test_support::{CLIENT_ID, ISSUER, Signer, id_claims, logout_claims}; |
| 862 | use super::*; |
| 863 | use serde_json::json; |
| 864 | |
| 865 | const NOW: u64 = 1_800_000_000; |
| 866 | |
| 867 | fn unsigned(header: &str, payload: &Value) -> String { |
| 868 | let h = BASE64_URL_SAFE_NO_PAD.encode(header); |
| 869 | let p = BASE64_URL_SAFE_NO_PAD.encode(payload.to_string()); |
| 870 | format!("{h}.{p}.") |
| 871 | } |
| 872 | |
| 873 | #[test] |
| 874 | fn pkce_challenge_matches_the_rfc_7636_example() { |
| 875 | assert_eq!( |
| 876 | pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), |
| 877 | "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" |
| 878 | ); |
| 879 | } |
| 880 | |
| 881 | #[test] |
| 882 | fn a_well_formed_id_token_is_accepted() { |
| 883 | let signer = Signer::generate(); |
| 884 | let token = signer.sign(&id_claims(NOW, "n-1")); |
| 885 | let id = verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW).unwrap(); |
| 886 | assert_eq!(id.sub, "01JMEMBER0000000000000000A"); |
| 887 | assert_eq!(id.sid.as_deref(), Some("sid-1")); |
| 888 | assert_eq!(id.picture_version, 1); |
| 889 | } |
| 890 | |
| 891 | #[test] |
| 892 | fn an_unsigned_alg_none_token_is_refused() { |
| 893 | let signer = Signer::generate(); |
| 894 | let token = unsigned(r#"{"alg":"none","kid":"k1"}"#, &id_claims(NOW, "n-1")); |
| 895 | assert!(matches!( |
| 896 | verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW), |
| 897 | Err(ImError::Rejected(_)) |
| 898 | )); |
| 899 | } |
| 900 | |
| 901 | #[test] |
| 902 | fn a_token_for_another_audience_is_refused() { |
| 903 | let signer = Signer::generate(); |
| 904 | let mut claims = id_claims(NOW, "n-1"); |
| 905 | claims["aud"] = json!("in"); |
| 906 | let token = signer.sign(&claims); |
| 907 | assert!(matches!( |
| 908 | verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW), |
| 909 | Err(ImError::Rejected(_)) |
| 910 | )); |
| 911 | } |
| 912 | |
| 913 | #[test] |
| 914 | fn an_expired_token_is_refused_but_leeway_is_allowed() { |
| 915 | |
| 916 | let now = unix_now(); |
| 917 | let signer = Signer::generate(); |
| 918 | let mut claims = id_claims(now, "n-1"); |
| 919 | claims["exp"] = json!(now - 3600); |
| 920 | let token = signer.sign(&claims); |
| 921 | assert!(verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", now).is_err()); |
| 922 | let mut claims = id_claims(now, "n-1"); |
| 923 | claims["exp"] = json!(now - 30); |
| 924 | let token = signer.sign(&claims); |
| 925 | assert!(verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", now).is_ok()); |
| 926 | } |
| 927 | |
| 928 | #[test] |
| 929 | fn a_wrong_nonce_is_refused() { |
| 930 | let signer = Signer::generate(); |
| 931 | let token = signer.sign(&id_claims(NOW, "n-1")); |
| 932 | assert!(matches!( |
| 933 | verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-2", NOW), |
| 934 | Err(ImError::Rejected(_)) |
| 935 | )); |
| 936 | } |
| 937 | |
| 938 | #[test] |
| 939 | fn an_unknown_key_id_asks_for_a_refetch() { |
| 940 | let signer = Signer::generate(); |
| 941 | let token = signer.sign_with_kid("k2", &id_claims(NOW, "n-1")); |
| 942 | assert!(matches!( |
| 943 | verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW), |
| 944 | Err(ImError::UnknownKey) |
| 945 | )); |
| 946 | } |
| 947 | |
| 948 | #[test] |
| 949 | fn a_logout_token_needs_the_event_and_no_nonce() { |
| 950 | let signer = Signer::generate(); |
| 951 | let good = signer.sign(&logout_claims(NOW, "j-1")); |
| 952 | let claims = verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &good, NOW).unwrap(); |
| 953 | assert_eq!(claims.jti, "j-1"); |
| 954 | assert_eq!(claims.sid.as_deref(), Some("sid-1")); |
| 955 | |
| 956 | let mut with_nonce = logout_claims(NOW, "j-2"); |
| 957 | with_nonce["nonce"] = json!("n"); |
| 958 | let token = signer.sign(&with_nonce); |
| 959 | assert!(verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &token, NOW).is_err()); |
| 960 | |
| 961 | let mut no_event = logout_claims(NOW, "j-3"); |
| 962 | no_event["events"] = json!({}); |
| 963 | let token = signer.sign(&no_event); |
| 964 | assert!(verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &token, NOW).is_err()); |
| 965 | } |
| 966 | |
| 967 | #[test] |
| 968 | fn the_key_set_keeps_only_ed25519_keys_with_a_kid() { |
| 969 | let set = KeySet::from_jwks( |
| 970 | br#"{"keys":[{"kty":"RSA","kid":"r1","n":"x","e":"AQAB"},{"kty":"OKP","crv":"Ed25519","kid":"no-x"}]}"#, |
| 971 | ) |
| 972 | .unwrap(); |
| 973 | assert!(set.keys.is_empty()); |
| 974 | } |
| 975 | } |