1use http::{HeaderMap, Method, Uri};
6
7use super::WebBotAuthError;
8use super::structured::{BareItem, Dictionary, InnerList, Item, List, ListEntry, Parameters};
9
10const DICTIONARY_FIELDS: &[&str] =
13 &["signature", "signature-input", "signature-agent", "accept-signature"];
14
15#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct ComponentId {
30 name: String,
31 params: Parameters,
32}
33
34impl ComponentId {
35 pub fn new(name: impl Into<String>) -> Self {
37 Self { name: name.into(), params: Parameters::new() }
38 }
39
40 pub fn signature_agent(member: impl Into<String>) -> Self {
43 Self::new(super::SIGNATURE_AGENT).with_param("key", BareItem::String(member.into()))
44 }
45
46 pub fn with_param(mut self, key: impl Into<String>, value: BareItem) -> Self {
48 self.params.insert(key, value);
49 self
50 }
51
52 pub fn name(&self) -> &str {
54 &self.name
55 }
56
57 pub fn params(&self) -> &Parameters {
59 &self.params
60 }
61
62 pub fn serialize(&self) -> Result<String, WebBotAuthError> {
69 self.to_item()
70 .serialize()
71 .map_err(|e| WebBotAuthError::SignatureBase { reason: e.to_string() })
72 }
73
74 fn to_item(&self) -> Item {
75 Item { bare_item: BareItem::String(self.name.clone()), params: self.params.clone() }
76 }
77
78 fn from_item(item: &Item) -> Option<Self> {
79 let name = item.bare_item.as_str()?;
80 Some(Self { name: name.to_string(), params: item.params.clone() })
81 }
82
83 pub(crate) fn same_as(&self, other: &Self) -> bool {
85 self.name == other.name
86 && self.params.len() == other.params.len()
87 && self.params.iter().all(|(key, value)| other.params.get(key) == Some(value))
88 }
89
90 fn string_param(&self, key: &str) -> Option<&str> {
91 self.params.get(key).and_then(BareItem::as_str)
92 }
93
94 fn flag(&self, key: &str) -> Result<bool, WebBotAuthError> {
95 match self.params.get(key) {
96 None => Ok(false),
97 Some(BareItem::Boolean(true)) => Ok(true),
98 Some(_) => {
99 Err(base_error(format!("parameter `{key}` on {} must be a flag", self.name)))
100 }
101 }
102 }
103}
104
105#[derive(Debug, Clone, Default, PartialEq, Eq)]
123pub struct SignatureInput {
124 pub components: Vec<ComponentId>,
126 pub params: Parameters,
128}
129
130impl SignatureInput {
131 pub fn new(components: Vec<ComponentId>) -> Self {
133 Self { components, params: Parameters::new() }
134 }
135
136 pub fn parse_field(value: &str) -> Result<Vec<(String, Self)>, WebBotAuthError> {
143 let malformed = |reason: String| WebBotAuthError::MalformedField {
144 field: super::SIGNATURE_INPUT.to_string(),
145 reason,
146 };
147 let dict = Dictionary::parse_unique(value).map_err(|e| malformed(e.to_string()))?;
148 dict.iter()
149 .map(|(label, member)| {
150 let ListEntry::InnerList(list) = member else {
151 return Err(malformed(format!("member `{label}` is not an inner list")));
152 };
153 let components = list
154 .items
155 .iter()
156 .map(ComponentId::from_item)
157 .collect::<Option<Vec<_>>>()
158 .ok_or_else(|| {
159 malformed(format!(
160 "member `{label}` lists a component that is not a string"
161 ))
162 })?;
163 Ok((label.to_string(), Self { components, params: list.params.clone() }))
164 })
165 .collect()
166 }
167
168 pub fn serialize(&self) -> Result<String, WebBotAuthError> {
176 self.to_inner_list()
177 .serialize()
178 .map_err(|e| WebBotAuthError::SignatureBase { reason: e.to_string() })
179 }
180
181 pub(crate) fn to_inner_list(&self) -> InnerList {
182 InnerList {
183 items: self.components.iter().map(ComponentId::to_item).collect(),
184 params: self.params.clone(),
185 }
186 }
187
188 pub fn created(&self) -> Option<i64> {
190 self.params.get("created").and_then(BareItem::as_integer)
191 }
192
193 pub fn expires(&self) -> Option<i64> {
195 self.params.get("expires").and_then(BareItem::as_integer)
196 }
197
198 pub fn keyid(&self) -> Option<&str> {
200 self.params.get("keyid").and_then(BareItem::as_str)
201 }
202
203 pub fn alg(&self) -> Option<&str> {
205 self.params.get("alg").and_then(BareItem::as_str)
206 }
207
208 pub fn tag(&self) -> Option<&str> {
210 self.params.get("tag").and_then(BareItem::as_str)
211 }
212
213 pub fn nonce(&self) -> Option<&str> {
215 self.params.get("nonce").and_then(BareItem::as_str)
216 }
217
218 pub fn covers(&self, component: &ComponentId) -> bool {
220 self.components.iter().any(|covered| covered.same_as(component))
221 }
222}
223
224#[derive(Debug, Clone, Copy)]
249pub struct RequestHead<'a> {
250 method: &'a Method,
251 uri: &'a Uri,
252 headers: &'a HeaderMap,
253 default_scheme: &'a str,
254}
255
256impl<'a> RequestHead<'a> {
257 pub fn new(method: &'a Method, uri: &'a Uri, headers: &'a HeaderMap) -> Self {
259 Self { method, uri, headers, default_scheme: "https" }
260 }
261
262 pub fn from_request<B>(request: &'a http::Request<B>) -> Self {
264 Self::new(request.method(), request.uri(), request.headers())
265 }
266
267 pub fn with_default_scheme(mut self, scheme: &'a str) -> Self {
269 self.default_scheme = scheme;
270 self
271 }
272
273 pub fn headers(&self) -> &'a HeaderMap {
275 self.headers
276 }
277
278 pub fn signature_base(&self, input: &SignatureInput) -> Result<String, WebBotAuthError> {
285 signature_base(input, |component| self.component_value(component))
286 }
287
288 fn scheme(&self) -> String {
289 self.uri.scheme_str().unwrap_or(self.default_scheme).to_ascii_lowercase()
290 }
291
292 fn authority(&self) -> Result<String, WebBotAuthError> {
293 let raw = match self.uri.authority() {
294 Some(authority) => authority.as_str().to_string(),
295 None => {
296 let mut hosts = self.headers.get_all(http::header::HOST).iter();
297 let (Some(host), None) = (hosts.next(), hosts.next()) else {
298 return Err(base_error("the request has no single authority or Host field"));
299 };
300 host.to_str()
301 .map_err(|_| base_error("the Host field is not ASCII"))?
302 .trim()
303 .to_string()
304 }
305 };
306 let authority: http::uri::Authority =
307 raw.parse().map_err(|_| base_error(format!("`{raw}` is not a valid authority")))?;
308 if authority.as_str().contains('@') {
309 return Err(base_error("the authority must not carry user information"));
310 }
311 let host = authority.host().to_ascii_lowercase();
312 let default_port = match self.scheme().as_str() {
313 "https" => Some(443),
314 "http" => Some(80),
315 _ => None,
316 };
317 Ok(match authority.port_u16() {
318 Some(port) if Some(port) != default_port => format!("{host}:{port}"),
319 Some(_) | None => host,
320 })
321 }
322
323 fn path(&self) -> &str {
324 match self.uri.path() {
325 "" => "/",
326 path => path,
327 }
328 }
329
330 fn component_value(&self, component: &ComponentId) -> Result<String, WebBotAuthError> {
331 let name = component.name();
332 if component.params.get("req").is_some() {
333 return Err(base_error(format!(
334 "`{name}` has the `req` flag, which a request cannot use"
335 )));
336 }
337 if name.starts_with('@') {
338 let allowed: &[&str] = if name == "@query-param" { &["name"] } else { &[] };
339 if let Some((key, _)) = component.params.iter().find(|(key, _)| !allowed.contains(key))
340 {
341 return Err(base_error(format!("parameter `{key}` does not apply to `{name}`")));
342 }
343 }
344 match name {
345 "@method" => Ok(self.method.as_str().to_string()),
346 "@scheme" => Ok(self.scheme()),
347 "@authority" => self.authority(),
348 "@path" => Ok(self.path().to_string()),
349 "@query" => Ok(format!("?{}", self.uri.query().unwrap_or_default())),
350 "@target-uri" => {
351 let query = self.uri.query().map(|q| format!("?{q}")).unwrap_or_default();
352 Ok(format!("{}://{}{}{query}", self.scheme(), self.authority()?, self.path()))
353 }
354 "@request-target" => Ok(self
355 .uri
356 .path_and_query()
357 .map_or_else(|| self.path().to_string(), |pq| pq.as_str().to_string())),
358 "@query-param" => {
359 let wanted = component
360 .string_param("name")
361 .ok_or_else(|| base_error("`@query-param` needs a string `name` parameter"))?;
362 query_param(self.uri.query().unwrap_or_default(), wanted)
363 }
364 "@status" => Err(base_error("`@status` applies only to responses")),
365 "@signature-params" => {
366 Err(base_error("`@signature-params` must not be listed as a covered component"))
367 }
368 _ if name.starts_with('@') => {
369 Err(base_error(format!("`{name}` is not a derived component this verifier knows")))
370 }
371 _ => self.field_value(component),
372 }
373 }
374
375 fn field_value(&self, component: &ComponentId) -> Result<String, WebBotAuthError> {
376 let name = component.name();
377 if name.is_empty() || name.bytes().any(|b| b.is_ascii_uppercase()) {
378 return Err(base_error(format!("field name `{name}` must be lowercase and non-empty")));
379 }
380 if let Some((key, _)) =
381 component.params.iter().find(|(key, _)| !["key", "sf", "bs", "tr"].contains(key))
382 {
383 return Err(base_error(format!("parameter `{key}` does not apply to field `{name}`")));
384 }
385 if component.flag("tr")? {
386 return Err(base_error(format!("trailer `{name}` is not available")));
387 }
388 let values = self
389 .headers
390 .get_all(name)
391 .iter()
392 .map(|value| {
393 value
394 .to_str()
395 .map(|v| v.trim_matches([' ', '\t']).to_string())
396 .map_err(|_| base_error(format!("field `{name}` is not ASCII")))
397 })
398 .collect::<Result<Vec<_>, _>>()?;
399 if values.is_empty() {
400 return Err(base_error(format!("the request has no `{name}` field")));
401 }
402 let key = component.params.get("key");
403 let sf = component.flag("sf")?;
404 if component.flag("bs")? {
405 if key.is_some() || sf {
406 return Err(base_error(format!(
407 "`bs` cannot combine with `key` or `sf` on `{name}`"
408 )));
409 }
410 let wrapped = List(
411 values
412 .into_iter()
413 .map(|v| ListEntry::Item(Item::new(BareItem::ByteSequence(v.into_bytes()))))
414 .collect(),
415 );
416 return wrapped.serialize().map_err(|e| base_error(e.to_string()));
417 }
418 let combined = values.join(", ");
419 if key.is_none() && !sf {
420 return Ok(combined);
421 }
422 if !DICTIONARY_FIELDS.contains(&name) {
423 return Err(base_error(format!("the structured type of field `{name}` is not known")));
424 }
425 let dict = Dictionary::parse(&combined)
426 .map_err(|e| base_error(format!("field `{name}` is not a dictionary: {e}")))?;
427 let serialized = match key {
428 Some(BareItem::String(member)) => dict
429 .get(member)
430 .ok_or_else(|| base_error(format!("field `{name}` has no member `{member}`")))?
431 .serialize(),
432 Some(_) => return Err(base_error(format!("`key` on `{name}` must be a string"))),
433 None => dict.serialize(),
434 };
435 serialized.map_err(|e| base_error(e.to_string()))
436 }
437}
438
439pub(crate) fn signature_base(
441 input: &SignatureInput,
442 mut resolve: impl FnMut(&ComponentId) -> Result<String, WebBotAuthError>,
443) -> Result<String, WebBotAuthError> {
444 let mut base = String::new();
445 for (index, component) in input.components.iter().enumerate() {
446 if input.components[..index].iter().any(|earlier| earlier.same_as(component)) {
447 return Err(base_error(format!("`{}` is covered twice", component.name())));
448 }
449 let value = resolve(component)?;
450 if value.contains(['\n', '\r']) || !value.is_ascii() {
451 return Err(base_error(format!(
452 "the value of `{}` contains a newline or non-ASCII character",
453 component.name()
454 )));
455 }
456 base.push_str(&component.serialize()?);
457 base.push_str(": ");
458 base.push_str(&value);
459 base.push('\n');
460 }
461 base.push_str("\"@signature-params\": ");
462 base.push_str(&input.serialize()?);
463 Ok(base)
464}
465
466fn base_error(reason: impl Into<String>) -> WebBotAuthError {
467 WebBotAuthError::SignatureBase { reason: reason.into() }
468}
469
470fn query_param(query: &str, wanted: &str) -> Result<String, WebBotAuthError> {
473 let mut found = query
474 .split('&')
475 .filter(|pair| !pair.is_empty())
476 .map(|pair| pair.split_once('=').unwrap_or((pair, "")))
477 .filter(|(name, _)| form_encode(&form_decode(name)) == wanted)
478 .map(|(_, value)| form_encode(&form_decode(value)));
479 match (found.next(), found.next()) {
480 (Some(value), None) => Ok(value),
481 (None, _) => Err(base_error(format!("the query has no parameter `{wanted}`"))),
482 (Some(_), Some(_)) => {
483 Err(base_error(format!("query parameter `{wanted}` occurs more than once")))
484 }
485 }
486}
487
488fn form_decode(input: &str) -> Vec<u8> {
489 let bytes = input.as_bytes();
490 let mut out = Vec::with_capacity(bytes.len());
491 let mut index = 0;
492 while index < bytes.len() {
493 match bytes[index] {
494 b'+' => out.push(b' '),
495 b'%' if index + 2 < bytes.len() => {
496 match (hex_value(bytes[index + 1]), hex_value(bytes[index + 2])) {
497 (Some(high), Some(low)) => {
498 out.push(high << 4 | low);
499 index += 2;
500 }
501 _ => out.push(b'%'),
502 }
503 }
504 byte => out.push(byte),
505 }
506 index += 1;
507 }
508 out
509}
510
511fn hex_value(byte: u8) -> Option<u8> {
512 char::from(byte).to_digit(16).and_then(|digit| u8::try_from(digit).ok())
513}
514
515fn form_encode(bytes: &[u8]) -> String {
518 let text = String::from_utf8_lossy(bytes);
519 let mut out = String::with_capacity(text.len());
520 for byte in text.bytes() {
521 if byte.is_ascii_alphanumeric() || b"*-._".contains(&byte) {
522 out.push(char::from(byte));
523 } else {
524 out.push_str(&format!("%{byte:02X}"));
525 }
526 }
527 out
528}
529
530#[cfg(test)]
531mod tests {
532 use super::*;
533
534 fn head_base(uri: &str, components: &[ComponentId]) -> Result<String, WebBotAuthError> {
535 let request = http::Request::get(uri).body(()).unwrap();
536 RequestHead::from_request(&request)
537 .signature_base(&SignatureInput::new(components.to_vec()))
538 }
539
540 #[test]
541 fn query_param_values_follow_rfc_9421_examples() {
542 let query = "var=this%20is%20a%20big%0Amultiline%20value&bar=with+plus+whitespace&fa%C3%A7ade%22%3A%20=something";
544 assert_eq!(query_param(query, "var").unwrap(), "this%20is%20a%20big%0Amultiline%20value");
545 assert_eq!(query_param(query, "bar").unwrap(), "with%20plus%20whitespace");
546 assert_eq!(query_param(query, "fa%C3%A7ade%22%3A%20").unwrap(), "something");
547 let query = "param=value&foo=bar&baz=batman&qux=";
548 assert_eq!(query_param(query, "baz").unwrap(), "batman");
549 assert_eq!(query_param(query, "qux").unwrap(), "");
550 assert!(query_param(query, "missing").is_err());
551 assert!(query_param("a=1&a=2", "a").is_err());
552 }
553
554 #[test]
555 fn derived_components_follow_rfc_9421_section_2_2() {
556 let base = head_base(
557 "https://www.example.com/path?param=value&foo=bar&baz=bat%2Dman",
558 &[
559 ComponentId::new("@scheme"),
560 ComponentId::new("@query"),
561 ComponentId::new("@request-target"),
562 ComponentId::new("@query-param").with_param("name", BareItem::String("baz".into())),
563 ],
564 )
565 .unwrap();
566 let lines: Vec<&str> = base.lines().collect();
567 assert_eq!(lines[0], "\"@scheme\": https");
568 assert_eq!(lines[1], "\"@query\": ?param=value&foo=bar&baz=bat%2Dman");
569 assert_eq!(lines[2], "\"@request-target\": /path?param=value&foo=bar&baz=bat%2Dman");
570 assert_eq!(lines[3], "\"@query-param\";name=\"baz\": bat-man");
571 }
572
573 #[test]
574 fn empty_query_and_path_normalise() {
575 let base = head_base(
576 "https://example.com",
577 &[ComponentId::new("@path"), ComponentId::new("@query")],
578 )
579 .unwrap();
580 assert!(base.starts_with("\"@path\": /\n\"@query\": ?\n"));
581 }
582
583 #[test]
584 fn authority_drops_default_port_and_lowercases() {
585 let base =
586 head_base("https://EXAMPLE.com:443/x", &[ComponentId::new("@authority")]).unwrap();
587 assert!(base.starts_with("\"@authority\": example.com\n"));
588 let base =
589 head_base("https://example.com:8443/x", &[ComponentId::new("@authority")]).unwrap();
590 assert!(base.starts_with("\"@authority\": example.com:8443\n"));
591 }
592
593 #[test]
594 fn invalid_components_are_errors() {
595 let uri = "https://example.com/";
596 assert!(head_base(uri, &[ComponentId::new("@status")]).is_err());
597 assert!(head_base(uri, &[ComponentId::new("@signature-params")]).is_err());
598 assert!(head_base(uri, &[ComponentId::new("@unknown")]).is_err());
599 assert!(head_base(uri, &[ComponentId::new("x-missing")]).is_err());
600 assert!(head_base(uri, &[ComponentId::new("Host")]).is_err());
601 assert!(
602 head_base(
603 uri,
604 &[ComponentId::new("@authority").with_param("req", BareItem::Boolean(true))]
605 )
606 .is_err()
607 );
608 assert!(
609 head_base(uri, &[ComponentId::new("@authority"), ComponentId::new("@authority")])
610 .is_err()
611 );
612 }
613
614 #[test]
615 fn field_parameters_follow_rfc_9421_section_2_1() {
616 let request = http::Request::get("https://example.com/")
617 .header("example-header", "value, with, lots")
618 .header("example-header", "of, commas")
619 .header(
620 "signature-agent",
621 "a=\"https://a.example\", b=\"https://b.example\";type=jwks_uri",
622 )
623 .body(())
624 .unwrap();
625 let input = SignatureInput::new(vec![
626 ComponentId::new("example-header"),
627 ComponentId::new("example-header").with_param("bs", BareItem::Boolean(true)),
628 ComponentId::new("signature-agent").with_param("sf", BareItem::Boolean(true)),
629 ComponentId::signature_agent("b"),
630 ]);
631 let base = RequestHead::from_request(&request).signature_base(&input).unwrap();
632 let lines: Vec<&str> = base.lines().collect();
633 assert_eq!(lines[0], "\"example-header\": value, with, lots, of, commas");
634 assert_eq!(
635 lines[1],
636 "\"example-header\";bs: :dmFsdWUsIHdpdGgsIGxvdHM=:, :b2YsIGNvbW1hcw==:"
637 );
638 assert_eq!(
639 lines[2],
640 "\"signature-agent\";sf: a=\"https://a.example\", b=\"https://b.example\";type=jwks_uri"
641 );
642 assert_eq!(lines[3], "\"signature-agent\";key=\"b\": \"https://b.example\";type=jwks_uri");
643 }
644}