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