1#![allow(clippy::doc_markdown)]
9
10use std::collections::HashMap;
24
25use serde::{Deserialize, Serialize};
26
27pub type NamedSecuritySchemes = HashMap<String, SecurityScheme>;
32
33include!("generated/security.rs");
35
36impl<'de> Deserialize<'de> for StringList {
37 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
38 deserializer.deserialize_any(StringListVisitor)
39 }
40}
41
42struct StringListVisitor;
44
45impl<'de> serde::de::Visitor<'de> for StringListVisitor {
46 type Value = StringList;
47
48 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 f.write_str("a StringList object {\"list\": [...]}, an array of strings, or null")
50 }
51
52 fn visit_unit<E: serde::de::Error>(self) -> Result<StringList, E> {
53 Ok(StringList { list: Vec::new() })
54 }
55
56 fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<StringList, A::Error> {
57 let mut list = Vec::new();
58 while let Some(s) = seq.next_element::<String>()? {
59 list.push(s);
60 }
61 Ok(StringList { list })
62 }
63
64 fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<StringList, A::Error> {
65 let mut list: Option<Vec<String>> = None;
66 while let Some(key) = map.next_key::<String>()? {
67 if key == "list" {
68 if list.is_some() {
69 return Err(serde::de::Error::duplicate_field("list"));
70 }
71 list = Some(map.next_value::<Option<Vec<String>>>()?.unwrap_or_default());
73 } else {
74 map.next_value::<serde::de::IgnoredAny>()?;
76 }
77 }
78 Ok(StringList {
79 list: list.unwrap_or_default(),
80 })
81 }
82}
83
84const SCHEME_ARMS: [(&str, &str); 5] = [
96 ("apiKeySecurityScheme", "api_key_security_scheme"),
97 ("httpAuthSecurityScheme", "http_auth_security_scheme"),
98 ("oauth2SecurityScheme", "oauth2_security_scheme"),
99 (
100 "openIdConnectSecurityScheme",
101 "open_id_connect_security_scheme",
102 ),
103 ("mtlsSecurityScheme", "mtls_security_scheme"),
104];
105
106impl SecurityScheme {
107 #[must_use]
109 pub const fn arm_name(&self) -> &'static str {
110 match self {
111 Self::ApiKey(_) => SCHEME_ARMS[0].0,
112 Self::Http(_) => SCHEME_ARMS[1].0,
113 Self::OAuth2(_) => SCHEME_ARMS[2].0,
114 Self::OpenIdConnect(_) => SCHEME_ARMS[3].0,
115 Self::MutualTls(_) => SCHEME_ARMS[4].0,
116 }
117 }
118
119 pub(crate) fn validate(&self) -> Result<(), &'static str> {
126 match self {
127 Self::ApiKey(s) if s.name.is_empty() => Err("an apiKeySecurityScheme needs a name"),
128 Self::Http(s) if s.scheme.is_empty() => Err("an httpAuthSecurityScheme needs a scheme"),
129 Self::OpenIdConnect(s) if s.open_id_connect_url.is_empty() => {
130 Err("an openIdConnectSecurityScheme needs an openIdConnectUrl")
131 }
132 Self::OpenIdConnect(s) if !is_url(&s.open_id_connect_url) => {
133 Err("an openIdConnectSecurityScheme's openIdConnectUrl is not a URL")
134 }
135 Self::OAuth2(s)
137 if s.oauth2_metadata_url
138 .as_deref()
139 .is_some_and(|u| !u.is_empty() && !is_https_url(u)) =>
140 {
141 Err("an oauth2SecurityScheme's oauth2MetadataUrl must be an https URL")
142 }
143 Self::OAuth2(s) => s.flows.validate(),
144 Self::ApiKey(_) | Self::Http(_) | Self::OpenIdConnect(_) | Self::MutualTls(_) => Ok(()),
145 }
146 }
147}
148
149impl Serialize for SecurityScheme {
150 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
151 use serde::ser::SerializeMap;
152 let mut map = serializer.serialize_map(Some(1))?;
153 let key = self.arm_name();
154 match self {
155 Self::ApiKey(v) => map.serialize_entry(key, v)?,
156 Self::Http(v) => map.serialize_entry(key, v)?,
157 Self::OAuth2(v) => map.serialize_entry(key, v.as_ref())?,
158 Self::OpenIdConnect(v) => map.serialize_entry(key, v)?,
159 Self::MutualTls(v) => map.serialize_entry(key, v)?,
160 }
161 map.end()
162 }
163}
164
165#[derive(Deserialize)]
170#[serde(tag = "type")]
171enum LegacySecurityScheme {
172 #[serde(rename = "apiKey")]
173 ApiKey(ApiKeySecurityScheme),
174 #[serde(rename = "http")]
175 Http(HttpAuthSecurityScheme),
176 #[serde(rename = "oauth2")]
177 OAuth2(Box<OAuth2SecurityScheme>),
178 #[serde(rename = "openIdConnect")]
179 OpenIdConnect(OpenIdConnectSecurityScheme),
180 #[serde(rename = "mutualTLS")]
181 MutualTls(MutualTlsSecurityScheme),
182}
183
184impl From<LegacySecurityScheme> for SecurityScheme {
185 fn from(v: LegacySecurityScheme) -> Self {
186 match v {
187 LegacySecurityScheme::ApiKey(x) => Self::ApiKey(x),
188 LegacySecurityScheme::Http(x) => Self::Http(x),
189 LegacySecurityScheme::OAuth2(x) => Self::OAuth2(x),
190 LegacySecurityScheme::OpenIdConnect(x) => Self::OpenIdConnect(x),
191 LegacySecurityScheme::MutualTls(x) => Self::MutualTls(x),
192 }
193 }
194}
195
196impl<'de> Deserialize<'de> for SecurityScheme {
197 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
198 use serde::de::Error as _;
199
200 let map = serde_json::Map::<String, serde_json::Value>::deserialize(deserializer)?;
206
207 let arms = SCHEME_ARMS
211 .iter()
212 .filter(|(json_name, proto_name)| {
213 map.contains_key(*json_name) || map.contains_key(*proto_name)
214 })
215 .count();
216 if arms > 1 {
217 return Err(D::Error::custom(format!(
218 "a SecurityScheme sets exactly one scheme; this one sets {arms}"
219 )));
220 }
221
222 for (index, (json_name, proto_name)) in SCHEME_ARMS.iter().enumerate() {
223 let Some(inner) = map.get(*json_name).or_else(|| map.get(*proto_name)) else {
224 continue;
225 };
226 let inner = inner.clone();
227 macro_rules! parse {
230 ($variant:expr_2021) => {
231 $variant(serde_json::from_value(inner).map_err(D::Error::custom)?)
232 };
233 }
234 return Ok(match index {
235 0 => parse!(Self::ApiKey),
236 1 => parse!(Self::Http),
237 2 => Self::OAuth2(Box::new(
238 serde_json::from_value(inner).map_err(D::Error::custom)?,
239 )),
240 3 => parse!(Self::OpenIdConnect),
241 _ => parse!(Self::MutualTls),
244 });
245 }
246
247 serde_json::from_value::<LegacySecurityScheme>(serde_json::Value::Object(map))
252 .map(Into::into)
253 .map_err(D::Error::custom)
254 }
255}
256
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
269#[serde(rename_all = "lowercase")]
270pub enum ApiKeyLocation {
271 Header,
273 Query,
275 Cookie,
277}
278
279impl OAuthFlows {
290 #[allow(deprecated)] fn validate(&self) -> Result<(), &'static str> {
300 match self {
301 Self::AuthorizationCode(f) if f.authorization_url.is_empty() => {
302 Err("an authorizationCode flow needs an authorizationUrl")
303 }
304 Self::AuthorizationCode(f) if f.token_url.is_empty() => {
305 Err("an authorizationCode flow needs a tokenUrl")
306 }
307 Self::ClientCredentials(f) if f.token_url.is_empty() => {
308 Err("a clientCredentials flow needs a tokenUrl")
309 }
310 Self::DeviceCode(f) if f.device_authorization_url.is_empty() => {
311 Err("a deviceCode flow needs a deviceAuthorizationUrl")
312 }
313 Self::DeviceCode(f) if f.token_url.is_empty() => {
314 Err("a deviceCode flow needs a tokenUrl")
315 }
316 Self::AuthorizationCode(f) => urls(
317 [&f.authorization_url, &f.token_url],
318 f.refresh_url.as_deref(),
319 ),
320 Self::ClientCredentials(f) => urls([&f.token_url], f.refresh_url.as_deref()),
321 Self::DeviceCode(f) => urls(
322 [&f.device_authorization_url, &f.token_url],
323 f.refresh_url.as_deref(),
324 ),
325 Self::Implicit(f) => {
326 urls([&f.authorization_url], f.refresh_url.as_deref()).and_then(|()| {
327 tls([&f.authorization_url], f.refresh_url.as_deref())
328 .then_some(())
329 .ok_or(
330 "an implicit flow's authorizationUrl and refreshUrl must be https URLs \
331 (a2a.proto: the OAuth2 standard requires the use of TLS)",
332 )
333 })
334 }
335 Self::Password(f) => urls([&f.token_url], f.refresh_url.as_deref()).and_then(|()| {
336 tls([&f.token_url], f.refresh_url.as_deref())
337 .then_some(())
338 .ok_or(
339 "a password flow's tokenUrl and refreshUrl must be https URLs \
340 (a2a.proto: the OAuth2 standard requires the use of TLS)",
341 )
342 }),
343 }
344 }
345}
346
347fn tls<const N: usize>(required: [&String; N], refresh: Option<&str>) -> bool {
349 let mut all = required.into_iter().map(String::as_str).chain(refresh);
350 all.all(|u| u.is_empty() || is_https_url(u))
351}
352
353fn urls<const N: usize>(required: [&String; N], refresh: Option<&str>) -> Result<(), &'static str> {
356 let all = required.into_iter().map(String::as_str).chain(refresh);
357 if all.filter(|u| !u.is_empty()).all(is_url) {
358 Ok(())
359 } else {
360 Err("an OAuth flow URL is not in the form of a URL (scheme://authority...)")
361 }
362}
363
364pub(crate) fn is_url(s: &str) -> bool {
370 let Some((scheme, rest)) = s.split_once("://") else {
371 return false;
372 };
373 let mut chars = scheme.chars();
374 chars.next().is_some_and(|c| c.is_ascii_alphabetic())
375 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
376 && !rest.is_empty()
377 && !rest.starts_with('/')
378 && !s.chars().any(|c| c.is_whitespace() || c.is_control())
379}
380
381pub(crate) fn is_https_url(s: &str) -> bool {
383 is_url(s)
384 && s.get(..8)
385 .is_some_and(|p| p.eq_ignore_ascii_case("https://"))
386}
387
388#[cfg(test)]
409#[path = "security_url_tests.rs"]
410mod url_tests;
411
412#[cfg(test)]
413mod tests {
414 use super::*;
415
416 #[test]
419 fn a_scheme_with_two_arms_is_refused() {
420 let api_key = serde_json::json!({"location": "header", "name": "X-Key"});
421 let http = serde_json::json!({"scheme": "Bearer"});
422 for two in [
423 serde_json::json!({"apiKeySecurityScheme": api_key, "httpAuthSecurityScheme": http}),
424 serde_json::json!({"api_key_security_scheme": api_key, "httpAuthSecurityScheme": http}),
425 serde_json::json!({"mtlsSecurityScheme": {}, "openIdConnectSecurityScheme": {"openIdConnectUrl": "https://x"}}),
426 ] {
427 let err = serde_json::from_value::<SecurityScheme>(two.clone()).expect_err("two arms");
428 assert!(err.to_string().contains("sets 2"), "{two}: {err}");
429 }
430 for one in [
432 serde_json::json!({"apiKeySecurityScheme": api_key}),
433 serde_json::json!({"api_key_security_scheme": api_key}),
434 ] {
435 serde_json::from_value::<SecurityScheme>(one).expect("one arm");
436 }
437 }
438
439 #[test]
440 fn api_key_scheme_roundtrip() {
441 let scheme = SecurityScheme::ApiKey(ApiKeySecurityScheme {
442 location: ApiKeyLocation::Header,
443 name: "X-API-Key".into(),
444 description: None,
445 });
446 let json = serde_json::to_string(&scheme).expect("serialize");
447 assert!(
448 json.contains("\"apiKeySecurityScheme\""),
449 "must emit the v1.0 oneof arm name: {json}"
450 );
451 assert!(
452 json.contains("\"location\":\"header\""),
453 "must emit the proto field name 'location', not v0.3's 'in': {json}"
454 );
455 assert!(
456 !json.contains("\"type\""),
457 "the v0.3 discriminator must not be emitted: {json}"
458 );
459
460 let back: SecurityScheme = serde_json::from_str(&json).expect("deserialize");
461 match &back {
462 SecurityScheme::ApiKey(s) => {
463 assert_eq!(s.location, ApiKeyLocation::Header);
464 assert_eq!(s.name, "X-API-Key");
465 }
466 _ => panic!("expected ApiKey variant"),
467 }
468 }
469
470 #[test]
471 fn http_bearer_scheme_roundtrip() {
472 let scheme = SecurityScheme::Http(HttpAuthSecurityScheme {
473 scheme: "bearer".into(),
474 bearer_format: Some("JWT".into()),
475 description: None,
476 });
477 let json = serde_json::to_string(&scheme).expect("serialize");
478 assert!(json.contains("\"httpAuthSecurityScheme\""), "{json}");
479 let back: SecurityScheme = serde_json::from_str(&json).expect("deserialize");
480 if let SecurityScheme::Http(h) = back {
481 assert_eq!(h.bearer_format.as_deref(), Some("JWT"));
482 } else {
483 panic!("wrong variant");
484 }
485 }
486
487 #[test]
491 fn oauth_flows_without_a_scopes_key_parse_as_empty() {
492 let flows: OAuthFlows = serde_json::from_value(serde_json::json!({
493 "clientCredentials": {"tokenUrl": "https://id.example.com/token"}
494 }))
495 .expect("a flow with its empty scopes omitted parses");
496 let OAuthFlows::ClientCredentials(cc) = &flows else {
497 panic!("expected clientCredentials, got {flows:?}");
498 };
499 assert!(cc.scopes.is_empty());
500 for flow in [
501 serde_json::json!({"authorizationCode": {"authorizationUrl": "a", "tokenUrl": "t"}}),
502 serde_json::json!({"deviceCode": {"deviceAuthorizationUrl": "d", "tokenUrl": "t"}}),
503 serde_json::json!({"implicit": {"authorizationUrl": "a"}}),
504 serde_json::json!({"password": {"tokenUrl": "t"}}),
505 ] {
506 serde_json::from_value::<OAuthFlows>(flow.clone())
507 .unwrap_or_else(|e| panic!("{flow}: {e}"));
508 }
509 }
510
511 #[test]
512 fn oauth2_scheme_roundtrip() {
513 let scheme = SecurityScheme::OAuth2(Box::new(OAuth2SecurityScheme {
514 flows: OAuthFlows::ClientCredentials(ClientCredentialsFlow {
515 token_url: "https://auth.example.com/token".into(),
516 refresh_url: None,
517 scopes: HashMap::from([("read".into(), "Read access".into())]),
518 }),
519 oauth2_metadata_url: None,
520 description: None,
521 }));
522 let json = serde_json::to_string(&scheme).expect("serialize");
523 assert!(json.contains("\"oauth2SecurityScheme\""), "{json}");
524 let back: SecurityScheme = serde_json::from_str(&json).expect("deserialize");
525 match &back {
526 SecurityScheme::OAuth2(o) => match &o.flows {
527 OAuthFlows::ClientCredentials(cc) => {
528 assert_eq!(cc.token_url, "https://auth.example.com/token");
529 assert_eq!(
530 cc.scopes.get("read").map(String::as_str),
531 Some("Read access")
532 );
533 }
534 _ => panic!("expected ClientCredentials flow"),
535 },
536 _ => panic!("expected OAuth2 variant"),
537 }
538 }
539
540 #[test]
541 fn mutual_tls_scheme_roundtrip() {
542 let scheme = SecurityScheme::MutualTls(MutualTlsSecurityScheme { description: None });
543 let json = serde_json::to_string(&scheme).expect("serialize");
544 assert!(json.contains("\"mtlsSecurityScheme\""), "{json}");
545 let back: SecurityScheme = serde_json::from_str(&json).expect("deserialize");
546 match &back {
547 SecurityScheme::MutualTls(m) => {
548 assert!(m.description.is_none());
549 }
550 _ => panic!("expected MutualTls variant"),
551 }
552 }
553
554 #[test]
555 fn api_key_location_serialization() {
556 assert_eq!(
557 serde_json::to_string(&ApiKeyLocation::Header).expect("ser"),
558 "\"header\""
559 );
560 assert_eq!(
561 serde_json::to_string(&ApiKeyLocation::Query).expect("ser"),
562 "\"query\""
563 );
564 assert_eq!(
565 serde_json::to_string(&ApiKeyLocation::Cookie).expect("ser"),
566 "\"cookie\""
567 );
568 }
569
570 #[test]
571 fn wire_format_security_requirement() {
572 let req = SecurityRequirement {
574 schemes: HashMap::from([(
575 "oauth2".into(),
576 StringList {
577 list: vec!["read".into(), "write".into()],
578 },
579 )]),
580 };
581 let json = serde_json::to_string(&req).unwrap();
582 let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
583 assert_eq!(
584 parsed["schemes"]["oauth2"]["list"],
585 serde_json::json!(["read", "write"])
586 );
587
588 let back: SecurityRequirement = serde_json::from_str(&json).unwrap();
590 assert_eq!(back.schemes["oauth2"].list, vec!["read", "write"]);
591 }
592
593 #[test]
594 #[allow(deprecated)] fn wire_format_password_oauth_flow() {
596 let flows = OAuthFlows::Password(PasswordOAuthFlow {
597 token_url: "https://auth.example.com/token".into(),
598 refresh_url: None,
599 scopes: HashMap::from([("read".into(), "Read access".into())]),
600 });
601 let json = serde_json::to_string(&flows).unwrap();
602 assert!(
603 json.contains("\"password\""),
604 "password flow must be present: {json}"
605 );
606
607 let back: OAuthFlows = serde_json::from_str(&json).unwrap();
608 match back {
609 OAuthFlows::Password(p) => {
610 assert_eq!(p.token_url, "https://auth.example.com/token");
611 }
612 _ => panic!("expected Password flow"),
613 }
614 }
615}