this repo has no description
1use reqwest::Client; 2use serde::{Deserialize, Serialize}; 3use std::collections::HashMap; 4use std::sync::Arc; 5use tokio::sync::RwLock; 6 7use super::OAuthError; 8 9#[derive(Debug, Clone, Serialize, Deserialize)] 10pub struct ClientMetadata { 11 pub client_id: String, 12 #[serde(skip_serializing_if = "Option::is_none")] 13 pub client_name: Option<String>, 14 #[serde(skip_serializing_if = "Option::is_none")] 15 pub client_uri: Option<String>, 16 #[serde(skip_serializing_if = "Option::is_none")] 17 pub logo_uri: Option<String>, 18 pub redirect_uris: Vec<String>, 19 #[serde(default)] 20 pub grant_types: Vec<String>, 21 #[serde(default)] 22 pub response_types: Vec<String>, 23 #[serde(skip_serializing_if = "Option::is_none")] 24 pub scope: Option<String>, 25 #[serde(skip_serializing_if = "Option::is_none")] 26 pub token_endpoint_auth_method: Option<String>, 27 #[serde(skip_serializing_if = "Option::is_none")] 28 pub dpop_bound_access_tokens: Option<bool>, 29 #[serde(skip_serializing_if = "Option::is_none")] 30 pub jwks: Option<serde_json::Value>, 31 #[serde(skip_serializing_if = "Option::is_none")] 32 pub jwks_uri: Option<String>, 33 #[serde(skip_serializing_if = "Option::is_none")] 34 pub application_type: Option<String>, 35} 36 37impl Default for ClientMetadata { 38 fn default() -> Self { 39 Self { 40 client_id: String::new(), 41 client_name: None, 42 client_uri: None, 43 logo_uri: None, 44 redirect_uris: Vec::new(), 45 grant_types: vec!["authorization_code".to_string()], 46 response_types: vec!["code".to_string()], 47 scope: None, 48 token_endpoint_auth_method: Some("none".to_string()), 49 dpop_bound_access_tokens: None, 50 jwks: None, 51 jwks_uri: None, 52 application_type: None, 53 } 54 } 55} 56 57#[derive(Clone)] 58pub struct ClientMetadataCache { 59 cache: Arc<RwLock<HashMap<String, CachedMetadata>>>, 60 jwks_cache: Arc<RwLock<HashMap<String, CachedJwks>>>, 61 http_client: Client, 62 cache_ttl_secs: u64, 63} 64 65struct CachedMetadata { 66 metadata: ClientMetadata, 67 cached_at: std::time::Instant, 68} 69 70struct CachedJwks { 71 jwks: serde_json::Value, 72 cached_at: std::time::Instant, 73} 74 75impl ClientMetadataCache { 76 pub fn new(cache_ttl_secs: u64) -> Self { 77 Self { 78 cache: Arc::new(RwLock::new(HashMap::new())), 79 jwks_cache: Arc::new(RwLock::new(HashMap::new())), 80 http_client: Client::builder() 81 .timeout(std::time::Duration::from_secs(30)) 82 .connect_timeout(std::time::Duration::from_secs(10)) 83 .build() 84 .unwrap_or_else(|_| Client::new()), 85 cache_ttl_secs, 86 } 87 } 88 89 fn is_loopback_client(client_id: &str) -> bool { 90 if let Ok(url) = reqwest::Url::parse(client_id) { 91 url.scheme() == "http" && url.host_str() == Some("localhost") && url.port().is_none() 92 } else { 93 false 94 } 95 } 96 97 fn build_loopback_metadata(client_id: &str) -> Result<ClientMetadata, OAuthError> { 98 let url = reqwest::Url::parse(client_id) 99 .map_err(|_| OAuthError::InvalidClient("Invalid loopback client_id URL".to_string()))?; 100 let mut redirect_uris = Vec::new(); 101 for (key, value) in url.query_pairs() { 102 if key == "redirect_uri" { 103 redirect_uris.push(value.to_string()); 104 } 105 } 106 if redirect_uris.is_empty() { 107 redirect_uris.push("http://127.0.0.1/callback".to_string()); 108 redirect_uris.push("http://localhost/callback".to_string()); 109 } 110 let scope = Some("atproto transition:generic transition:chat.bsky".to_string()); 111 Ok(ClientMetadata { 112 client_id: client_id.to_string(), 113 client_name: Some("Loopback Client".to_string()), 114 client_uri: None, 115 logo_uri: None, 116 redirect_uris, 117 grant_types: vec![ 118 "authorization_code".to_string(), 119 "refresh_token".to_string(), 120 ], 121 response_types: vec!["code".to_string()], 122 scope, 123 token_endpoint_auth_method: Some("none".to_string()), 124 dpop_bound_access_tokens: Some(false), 125 jwks: None, 126 jwks_uri: None, 127 application_type: Some("native".to_string()), 128 }) 129 } 130 131 pub async fn get(&self, client_id: &str) -> Result<ClientMetadata, OAuthError> { 132 if Self::is_loopback_client(client_id) { 133 return Self::build_loopback_metadata(client_id); 134 } 135 { 136 let cache = self.cache.read().await; 137 if let Some(cached) = cache.get(client_id) 138 && cached.cached_at.elapsed().as_secs() < self.cache_ttl_secs { 139 return Ok(cached.metadata.clone()); 140 } 141 } 142 let metadata = self.fetch_metadata(client_id).await?; 143 { 144 let mut cache = self.cache.write().await; 145 cache.insert( 146 client_id.to_string(), 147 CachedMetadata { 148 metadata: metadata.clone(), 149 cached_at: std::time::Instant::now(), 150 }, 151 ); 152 } 153 Ok(metadata) 154 } 155 156 pub async fn get_jwks( 157 &self, 158 metadata: &ClientMetadata, 159 ) -> Result<serde_json::Value, OAuthError> { 160 if let Some(jwks) = &metadata.jwks { 161 return Ok(jwks.clone()); 162 } 163 let jwks_uri = metadata.jwks_uri.as_ref().ok_or_else(|| { 164 OAuthError::InvalidClient( 165 "Client using private_key_jwt must have jwks or jwks_uri".to_string(), 166 ) 167 })?; 168 { 169 let cache = self.jwks_cache.read().await; 170 if let Some(cached) = cache.get(jwks_uri) 171 && cached.cached_at.elapsed().as_secs() < self.cache_ttl_secs { 172 return Ok(cached.jwks.clone()); 173 } 174 } 175 let jwks = self.fetch_jwks(jwks_uri).await?; 176 { 177 let mut cache = self.jwks_cache.write().await; 178 cache.insert( 179 jwks_uri.clone(), 180 CachedJwks { 181 jwks: jwks.clone(), 182 cached_at: std::time::Instant::now(), 183 }, 184 ); 185 } 186 Ok(jwks) 187 } 188 189 async fn fetch_jwks(&self, jwks_uri: &str) -> Result<serde_json::Value, OAuthError> { 190 if !jwks_uri.starts_with("https://") 191 && (!jwks_uri.starts_with("http://") 192 || (!jwks_uri.contains("localhost") && !jwks_uri.contains("127.0.0.1"))) 193 { 194 return Err(OAuthError::InvalidClient( 195 "jwks_uri must use https (except for localhost)".to_string(), 196 )); 197 } 198 let response = self 199 .http_client 200 .get(jwks_uri) 201 .header("Accept", "application/json") 202 .send() 203 .await 204 .map_err(|e| { 205 OAuthError::InvalidClient(format!("Failed to fetch JWKS from {}: {}", jwks_uri, e)) 206 })?; 207 if !response.status().is_success() { 208 return Err(OAuthError::InvalidClient(format!( 209 "Failed to fetch JWKS: HTTP {}", 210 response.status() 211 ))); 212 } 213 let jwks: serde_json::Value = response 214 .json() 215 .await 216 .map_err(|e| OAuthError::InvalidClient(format!("Invalid JWKS JSON: {}", e)))?; 217 if jwks.get("keys").and_then(|k| k.as_array()).is_none() { 218 return Err(OAuthError::InvalidClient( 219 "JWKS must contain a 'keys' array".to_string(), 220 )); 221 } 222 Ok(jwks) 223 } 224 225 async fn fetch_metadata(&self, client_id: &str) -> Result<ClientMetadata, OAuthError> { 226 if !client_id.starts_with("http://") && !client_id.starts_with("https://") { 227 return Err(OAuthError::InvalidClient( 228 "client_id must be a URL".to_string(), 229 )); 230 } 231 if client_id.starts_with("http://") 232 && !client_id.contains("localhost") 233 && !client_id.contains("127.0.0.1") 234 { 235 return Err(OAuthError::InvalidClient( 236 "Non-localhost client_id must use https".to_string(), 237 )); 238 } 239 let response = self 240 .http_client 241 .get(client_id) 242 .header("Accept", "application/json") 243 .send() 244 .await 245 .map_err(|e| { 246 OAuthError::InvalidClient(format!("Failed to fetch client metadata: {}", e)) 247 })?; 248 if !response.status().is_success() { 249 return Err(OAuthError::InvalidClient(format!( 250 "Failed to fetch client metadata: HTTP {}", 251 response.status() 252 ))); 253 } 254 let mut metadata: ClientMetadata = response.json().await.map_err(|e| { 255 OAuthError::InvalidClient(format!("Invalid client metadata JSON: {}", e)) 256 })?; 257 if metadata.client_id.is_empty() { 258 metadata.client_id = client_id.to_string(); 259 } else if metadata.client_id != client_id { 260 return Err(OAuthError::InvalidClient( 261 "client_id in metadata does not match request".to_string(), 262 )); 263 } 264 self.validate_metadata(&metadata)?; 265 Ok(metadata) 266 } 267 268 fn validate_metadata(&self, metadata: &ClientMetadata) -> Result<(), OAuthError> { 269 if metadata.redirect_uris.is_empty() { 270 return Err(OAuthError::InvalidClient( 271 "redirect_uris is required".to_string(), 272 )); 273 } 274 for uri in &metadata.redirect_uris { 275 self.validate_redirect_uri_format(uri)?; 276 } 277 if !metadata.grant_types.is_empty() 278 && !metadata 279 .grant_types 280 .contains(&"authorization_code".to_string()) 281 { 282 return Err(OAuthError::InvalidClient( 283 "authorization_code grant type is required".to_string(), 284 )); 285 } 286 if !metadata.response_types.is_empty() 287 && !metadata.response_types.contains(&"code".to_string()) 288 { 289 return Err(OAuthError::InvalidClient( 290 "code response type is required".to_string(), 291 )); 292 } 293 Ok(()) 294 } 295 296 pub fn validate_redirect_uri( 297 &self, 298 metadata: &ClientMetadata, 299 redirect_uri: &str, 300 ) -> Result<(), OAuthError> { 301 if metadata.redirect_uris.contains(&redirect_uri.to_string()) { 302 return Ok(()); 303 } 304 if Self::is_loopback_client(&metadata.client_id) 305 && let Ok(req_url) = reqwest::Url::parse(redirect_uri) { 306 let req_host = req_url.host_str().unwrap_or(""); 307 let is_loopback_redirect = req_url.scheme() == "http" 308 && (req_host == "localhost" || req_host == "127.0.0.1" || req_host == "[::1]"); 309 if is_loopback_redirect { 310 for registered in &metadata.redirect_uris { 311 if let Ok(reg_url) = reqwest::Url::parse(registered) { 312 let reg_host = reg_url.host_str().unwrap_or(""); 313 let hosts_match = (req_host == "localhost" && reg_host == "localhost") 314 || (req_host == "127.0.0.1" && reg_host == "127.0.0.1") 315 || (req_host == "[::1]" && reg_host == "[::1]") 316 || (req_host == "localhost" && reg_host == "127.0.0.1") 317 || (req_host == "127.0.0.1" && reg_host == "localhost"); 318 if hosts_match && req_url.path() == reg_url.path() { 319 return Ok(()); 320 } 321 } 322 } 323 } 324 } 325 Err(OAuthError::InvalidRequest( 326 "redirect_uri not registered for client".to_string(), 327 )) 328 } 329 330 fn validate_redirect_uri_format(&self, uri: &str) -> Result<(), OAuthError> { 331 if uri.contains('#') { 332 return Err(OAuthError::InvalidClient( 333 "redirect_uri must not contain a fragment".to_string(), 334 )); 335 } 336 let parsed = reqwest::Url::parse(uri) 337 .map_err(|_| OAuthError::InvalidClient(format!("Invalid redirect_uri: {}", uri)))?; 338 let scheme = parsed.scheme(); 339 if scheme == "http" { 340 let host = parsed.host_str().unwrap_or(""); 341 if host != "localhost" && host != "127.0.0.1" && host != "[::1]" { 342 return Err(OAuthError::InvalidClient( 343 "http redirect_uri only allowed for localhost".to_string(), 344 )); 345 } 346 } else if scheme == "https" { 347 } else if scheme.chars().all(|c| { 348 c.is_ascii_lowercase() || c.is_ascii_digit() || c == '+' || c == '.' || c == '-' 349 }) { 350 if !scheme 351 .chars() 352 .next() 353 .map(|c| c.is_ascii_lowercase()) 354 .unwrap_or(false) 355 { 356 return Err(OAuthError::InvalidClient(format!( 357 "Invalid redirect_uri scheme: {}", 358 scheme 359 ))); 360 } 361 } else { 362 return Err(OAuthError::InvalidClient(format!( 363 "Invalid redirect_uri scheme: {}", 364 scheme 365 ))); 366 } 367 Ok(()) 368 } 369} 370 371impl ClientMetadata { 372 pub fn requires_dpop(&self) -> bool { 373 self.dpop_bound_access_tokens.unwrap_or(false) 374 } 375 376 pub fn auth_method(&self) -> &str { 377 self.token_endpoint_auth_method.as_deref().unwrap_or("none") 378 } 379} 380 381pub async fn verify_client_auth( 382 cache: &ClientMetadataCache, 383 metadata: &ClientMetadata, 384 client_auth: &super::ClientAuth, 385) -> Result<(), OAuthError> { 386 let expected_method = metadata.auth_method(); 387 match (expected_method, client_auth) { 388 ("none", super::ClientAuth::None) => Ok(()), 389 ("none", _) => Err(OAuthError::InvalidClient( 390 "Client is configured for no authentication, but credentials were provided".to_string(), 391 )), 392 ("private_key_jwt", super::ClientAuth::PrivateKeyJwt { client_assertion }) => { 393 verify_private_key_jwt_async(cache, metadata, client_assertion).await 394 } 395 ("private_key_jwt", _) => Err(OAuthError::InvalidClient( 396 "Client requires private_key_jwt authentication".to_string(), 397 )), 398 ("client_secret_post", super::ClientAuth::SecretPost { .. }) => { 399 Err(OAuthError::InvalidClient( 400 "client_secret_post is not supported for ATProto OAuth".to_string(), 401 )) 402 } 403 ("client_secret_basic", super::ClientAuth::SecretBasic { .. }) => { 404 Err(OAuthError::InvalidClient( 405 "client_secret_basic is not supported for ATProto OAuth".to_string(), 406 )) 407 } 408 (method, _) => Err(OAuthError::InvalidClient(format!( 409 "Unsupported or mismatched authentication method: {}", 410 method 411 ))), 412 } 413} 414 415async fn verify_private_key_jwt_async( 416 cache: &ClientMetadataCache, 417 metadata: &ClientMetadata, 418 client_assertion: &str, 419) -> Result<(), OAuthError> { 420 use base64::{ 421 Engine as _, 422 engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}, 423 }; 424 let parts: Vec<&str> = client_assertion.split('.').collect(); 425 if parts.len() != 3 { 426 return Err(OAuthError::InvalidClient( 427 "Invalid client_assertion format".to_string(), 428 )); 429 } 430 let header_bytes = URL_SAFE_NO_PAD 431 .decode(parts[0]) 432 .or_else(|_| STANDARD.decode(parts[0])) 433 .map_err(|_| OAuthError::InvalidClient("Invalid assertion header encoding".to_string()))?; 434 let header: serde_json::Value = serde_json::from_slice(&header_bytes) 435 .map_err(|_| OAuthError::InvalidClient("Invalid assertion header JSON".to_string()))?; 436 let alg = header 437 .get("alg") 438 .and_then(|a| a.as_str()) 439 .ok_or_else(|| OAuthError::InvalidClient("Missing alg in client_assertion".to_string()))?; 440 if !matches!( 441 alg, 442 "ES256" | "ES384" | "RS256" | "RS384" | "RS512" | "EdDSA" 443 ) { 444 return Err(OAuthError::InvalidClient(format!( 445 "Unsupported client_assertion algorithm: {}", 446 alg 447 ))); 448 } 449 let kid = header.get("kid").and_then(|k| k.as_str()); 450 let payload_bytes = URL_SAFE_NO_PAD 451 .decode(parts[1]) 452 .or_else(|_| STANDARD.decode(parts[1])) 453 .map_err(|e| { 454 tracing::warn!(error = %e, payload_part = parts[1], "Invalid assertion payload encoding"); 455 OAuthError::InvalidClient("Invalid assertion payload encoding".to_string()) 456 })?; 457 let payload: serde_json::Value = serde_json::from_slice(&payload_bytes) 458 .map_err(|_| OAuthError::InvalidClient("Invalid assertion payload JSON".to_string()))?; 459 let iss = payload 460 .get("iss") 461 .and_then(|i| i.as_str()) 462 .ok_or_else(|| OAuthError::InvalidClient("Missing iss in client_assertion".to_string()))?; 463 if iss != metadata.client_id { 464 return Err(OAuthError::InvalidClient( 465 "client_assertion iss does not match client_id".to_string(), 466 )); 467 } 468 let sub = payload 469 .get("sub") 470 .and_then(|s| s.as_str()) 471 .ok_or_else(|| OAuthError::InvalidClient("Missing sub in client_assertion".to_string()))?; 472 if sub != metadata.client_id { 473 return Err(OAuthError::InvalidClient( 474 "client_assertion sub does not match client_id".to_string(), 475 )); 476 } 477 let now = chrono::Utc::now().timestamp(); 478 let exp = payload.get("exp").and_then(|e| e.as_i64()); 479 let iat = payload.get("iat").and_then(|i| i.as_i64()); 480 if let Some(exp) = exp { 481 if exp < now { 482 return Err(OAuthError::InvalidClient( 483 "client_assertion has expired".to_string(), 484 )); 485 } 486 } else if let Some(iat) = iat { 487 let max_age_secs = 300; 488 if now - iat > max_age_secs { 489 tracing::warn!( 490 iat = iat, 491 now = now, 492 "client_assertion too old (no exp, using iat)" 493 ); 494 return Err(OAuthError::InvalidClient( 495 "client_assertion is too old".to_string(), 496 )); 497 } 498 } else { 499 return Err(OAuthError::InvalidClient( 500 "client_assertion must have exp or iat claim".to_string(), 501 )); 502 } 503 if let Some(iat) = iat 504 && iat > now + 60 { 505 return Err(OAuthError::InvalidClient( 506 "client_assertion iat is in the future".to_string(), 507 )); 508 } 509 let jwks = cache.get_jwks(metadata).await?; 510 let keys = jwks 511 .get("keys") 512 .and_then(|k| k.as_array()) 513 .ok_or_else(|| OAuthError::InvalidClient("Invalid JWKS: missing keys array".to_string()))?; 514 let matching_keys: Vec<&serde_json::Value> = if let Some(kid) = kid { 515 keys.iter() 516 .filter(|k| k.get("kid").and_then(|v| v.as_str()) == Some(kid)) 517 .collect() 518 } else { 519 keys.iter().collect() 520 }; 521 if matching_keys.is_empty() { 522 return Err(OAuthError::InvalidClient( 523 "No matching key found in client JWKS".to_string(), 524 )); 525 } 526 let signing_input = format!("{}.{}", parts[0], parts[1]); 527 let signature_bytes = URL_SAFE_NO_PAD 528 .decode(parts[2]) 529 .map_err(|_| OAuthError::InvalidClient("Invalid signature encoding".to_string()))?; 530 for key in matching_keys { 531 let key_alg = key.get("alg").and_then(|a| a.as_str()); 532 if key_alg.is_some() && key_alg != Some(alg) { 533 continue; 534 } 535 let kty = key.get("kty").and_then(|k| k.as_str()).unwrap_or(""); 536 let verified = match (alg, kty) { 537 ("ES256", "EC") => verify_es256(key, &signing_input, &signature_bytes), 538 ("ES384", "EC") => verify_es384(key, &signing_input, &signature_bytes), 539 ("RS256" | "RS384" | "RS512", "RSA") => { 540 verify_rsa(alg, key, &signing_input, &signature_bytes) 541 } 542 ("EdDSA", "OKP") => verify_eddsa(key, &signing_input, &signature_bytes), 543 _ => continue, 544 }; 545 if verified.is_ok() { 546 return Ok(()); 547 } 548 } 549 Err(OAuthError::InvalidClient( 550 "client_assertion signature verification failed".to_string(), 551 )) 552} 553 554fn verify_es256( 555 key: &serde_json::Value, 556 signing_input: &str, 557 signature: &[u8], 558) -> Result<(), OAuthError> { 559 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; 560 use p256::EncodedPoint; 561 use p256::ecdsa::{Signature, VerifyingKey, signature::Verifier}; 562 let x = key 563 .get("x") 564 .and_then(|v| v.as_str()) 565 .ok_or_else(|| OAuthError::InvalidClient("Missing x coordinate in EC key".to_string()))?; 566 let y = key 567 .get("y") 568 .and_then(|v| v.as_str()) 569 .ok_or_else(|| OAuthError::InvalidClient("Missing y coordinate in EC key".to_string()))?; 570 let x_bytes = URL_SAFE_NO_PAD 571 .decode(x) 572 .map_err(|_| OAuthError::InvalidClient("Invalid x coordinate encoding".to_string()))?; 573 let y_bytes = URL_SAFE_NO_PAD 574 .decode(y) 575 .map_err(|_| OAuthError::InvalidClient("Invalid y coordinate encoding".to_string()))?; 576 let mut point_bytes = vec![0x04]; 577 point_bytes.extend_from_slice(&x_bytes); 578 point_bytes.extend_from_slice(&y_bytes); 579 let point = EncodedPoint::from_bytes(&point_bytes) 580 .map_err(|_| OAuthError::InvalidClient("Invalid EC point".to_string()))?; 581 let verifying_key = VerifyingKey::from_encoded_point(&point) 582 .map_err(|_| OAuthError::InvalidClient("Invalid EC key".to_string()))?; 583 let sig = Signature::from_slice(signature) 584 .map_err(|_| OAuthError::InvalidClient("Invalid ES256 signature format".to_string()))?; 585 verifying_key 586 .verify(signing_input.as_bytes(), &sig) 587 .map_err(|_| OAuthError::InvalidClient("ES256 signature verification failed".to_string())) 588} 589 590fn verify_es384( 591 key: &serde_json::Value, 592 signing_input: &str, 593 signature: &[u8], 594) -> Result<(), OAuthError> { 595 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; 596 use p384::EncodedPoint; 597 use p384::ecdsa::{Signature, VerifyingKey, signature::Verifier}; 598 let x = key 599 .get("x") 600 .and_then(|v| v.as_str()) 601 .ok_or_else(|| OAuthError::InvalidClient("Missing x coordinate in EC key".to_string()))?; 602 let y = key 603 .get("y") 604 .and_then(|v| v.as_str()) 605 .ok_or_else(|| OAuthError::InvalidClient("Missing y coordinate in EC key".to_string()))?; 606 let x_bytes = URL_SAFE_NO_PAD 607 .decode(x) 608 .map_err(|_| OAuthError::InvalidClient("Invalid x coordinate encoding".to_string()))?; 609 let y_bytes = URL_SAFE_NO_PAD 610 .decode(y) 611 .map_err(|_| OAuthError::InvalidClient("Invalid y coordinate encoding".to_string()))?; 612 let mut point_bytes = vec![0x04]; 613 point_bytes.extend_from_slice(&x_bytes); 614 point_bytes.extend_from_slice(&y_bytes); 615 let point = EncodedPoint::from_bytes(&point_bytes) 616 .map_err(|_| OAuthError::InvalidClient("Invalid EC point".to_string()))?; 617 let verifying_key = VerifyingKey::from_encoded_point(&point) 618 .map_err(|_| OAuthError::InvalidClient("Invalid EC key".to_string()))?; 619 let sig = Signature::from_slice(signature) 620 .map_err(|_| OAuthError::InvalidClient("Invalid ES384 signature format".to_string()))?; 621 verifying_key 622 .verify(signing_input.as_bytes(), &sig) 623 .map_err(|_| OAuthError::InvalidClient("ES384 signature verification failed".to_string())) 624} 625 626fn verify_rsa( 627 _alg: &str, 628 _key: &serde_json::Value, 629 _signing_input: &str, 630 _signature: &[u8], 631) -> Result<(), OAuthError> { 632 Err(OAuthError::InvalidClient( 633 "RSA signature verification not yet supported - use EC keys".to_string(), 634 )) 635} 636 637fn verify_eddsa( 638 key: &serde_json::Value, 639 signing_input: &str, 640 signature: &[u8], 641) -> Result<(), OAuthError> { 642 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; 643 use ed25519_dalek::{Signature, Verifier, VerifyingKey}; 644 let crv = key.get("crv").and_then(|c| c.as_str()).unwrap_or(""); 645 if crv != "Ed25519" { 646 return Err(OAuthError::InvalidClient(format!( 647 "Unsupported EdDSA curve: {}", 648 crv 649 ))); 650 } 651 let x = key 652 .get("x") 653 .and_then(|v| v.as_str()) 654 .ok_or_else(|| OAuthError::InvalidClient("Missing x in OKP key".to_string()))?; 655 let x_bytes = URL_SAFE_NO_PAD 656 .decode(x) 657 .map_err(|_| OAuthError::InvalidClient("Invalid x encoding".to_string()))?; 658 let key_bytes: [u8; 32] = x_bytes 659 .try_into() 660 .map_err(|_| OAuthError::InvalidClient("Invalid Ed25519 key length".to_string()))?; 661 let verifying_key = VerifyingKey::from_bytes(&key_bytes) 662 .map_err(|_| OAuthError::InvalidClient("Invalid Ed25519 key".to_string()))?; 663 let sig_bytes: [u8; 64] = signature 664 .try_into() 665 .map_err(|_| OAuthError::InvalidClient("Invalid EdDSA signature length".to_string()))?; 666 let sig = Signature::from_bytes(&sig_bytes); 667 verifying_key 668 .verify(signing_input.as_bytes(), &sig) 669 .map_err(|_| OAuthError::InvalidClient("EdDSA signature verification failed".to_string())) 670}