Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ This repository uses [npm](https://docs.npmjs.com/cli/v11/using-npm/workspaces)
| [http-message-sig](./packages/http-message-sig/) | TypeScript | HTTP Message Signatures as defined in RFC 9421 |
| [jsonwebkey-thumbprint](./packages/jsonwebkey-thumbprint/) | TypeScript | JWK Thumbprint as defined in RFC 7638 |
| [web-bot-auth](./packages/web-bot-auth/) | TypeScript | HTTP Message Signatures for Bots as defined in [draft-meunier-webbotauth-httpsig-protocol-01](https://datatracker.ietf.org/doc/draft-meunier-webbotauth-httpsig-protocol/01/) |
| [web-bot-auth](./crates/web-bot-auth/) | Rust | HTTP Message Signatures for Bots as defined in [draft-meunier-webbotauth-httpsig-protocol-00](https://datatracker.ietf.org/doc/draft-meunier-webbotauth-httpsig-protocol/00/) |
| [web-bot-auth](./crates/web-bot-auth/) | Rust | HTTP Message Signatures for Bots as defined in [draft-ietf-webbotauth-httpsig-protocol-01](https://datatracker.ietf.org/doc/html/draft-ietf-webbotauth-httpsig-protocol-01) |
| [http-signature-directory](./crates/http-signature-directory/) | Rust | Validates whether an HTTP message signature directory is correctly signed and valid |

## Security Considerations
Expand Down
2 changes: 1 addition & 1 deletion crates/web-bot-auth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

[crates.io]: https://crates.io/crates/web-bot-auth

A pure Rust implementation of [web-bot-auth](https://github.com/cloudflare/web-bot-auth) as defined by [draft-meunier-webbotauth-httpsig-protocol-00](https://datatracker.ietf.org/doc/draft-meunier-webbotauth-httpsig-protocol/00/).
A pure Rust implementation of [web-bot-auth](https://github.com/cloudflare/web-bot-auth) as defined by [draft-ietf-webbotauth-httpsig-protocol-01](https://datatracker.ietf.org/doc/html/draft-ietf-webbotauth-httpsig-protocol-01).

## Table of Contents

Expand Down
175 changes: 151 additions & 24 deletions crates/web-bot-auth/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,48 @@ pub enum SignatureAgentLink {
LegacyDirectory(String),
}

fn check_nested_coverage(
inputs: &sfv::Dictionary,
outer: &sfv::InnerList,
) -> Result<(), ImplementationError> {
for component in &outer.items {
if !component
.bare_item
.as_string()
.is_some_and(|name| name.as_str().eq_ignore_ascii_case("signature"))
{
continue;
}
let CoveredComponent::HTTP(HTTPField { parameters, .. }) = component.clone().try_into()?
else {
continue;
};
let [HTTPFieldParameters::Key(key)] = parameters.0.as_slice() else {
continue;
};
let input_component = sfv::Item::try_from(HTTPField {
name: "signature-input".into(),
parameters: parameters.clone(),
})?;
let Some(sfv::ListEntry::InnerList(inner)) = inputs.get(key.as_str()) else {
return Err(ImplementationError::ParsingError(format!(
"Missing `Signature-Input` inner list for {key}"
)));
};
if !outer.items.contains(&input_component) {
return Err(ImplementationError::ParsingError(format!(
"Signature must cover `Signature-Input` member {key}"
)));
}
if !inner.items.iter().all(|item| outer.items.contains(item)) {
return Err(ImplementationError::ParsingError(format!(
"Signature must cover every component of `Signature-Input` member {key}"
)));
}
}
Ok(())
}

impl WebBotAuthVerifier {
/// Parse a message into a structure that is ready for verification against an
/// external key with a suitable algorithm. If `alg` is not set, a default will
Expand All @@ -196,8 +238,9 @@ impl WebBotAuthVerifier {
parameters: components::HTTPFieldParametersSet(vec![]),
}));

let message_verifier =
MessageVerifier::parse(message, |(_, innerlist)| {
let message_verifier = MessageVerifier::parse_with_input_check(
message,
|(_, innerlist)| {
innerlist.params.contains_key("keyid")
&& innerlist.params.contains_key("tag")
&& innerlist.params.contains_key("expires")
Expand All @@ -224,25 +267,9 @@ impl WebBotAuthVerifier {
} else {
true
})
})?;

let mut signature_agent_key: Option<String> = None;
for (component, _) in message_verifier.parsed.base.components.iter() {
if let CoveredComponent::HTTP(HTTPField { name, parameters }) = component
&& name == "signature-agent"
&& parameters
.0
.iter()
.all(|parameter| matches!(parameter, HTTPFieldParameters::Key(_)))
{
for parameter in parameters.0.iter() {
if let HTTPFieldParameters::Key(key) = parameter {
signature_agent_key = Some(key.clone());
}
}
break;
}
}
},
check_nested_coverage,
)?;

let parse_link =
|link_str: &str, discovery_type: &Option<SignatureAgentDiscoveryType>, legacy| {
Expand All @@ -263,11 +290,37 @@ impl WebBotAuthVerifier {
ImplementationError::ParsingError(format!("Failed to parse `Signature-Agent`: {error}"))
})?;
let legacy = matches!(header, registry::SignatureAgentHeader::Legacy { .. });
let mut bare_agent = false;
let mut keys = Vec::new();
for component in message_verifier.parsed.base.components.keys() {
if let CoveredComponent::HTTP(HTTPField { name, parameters }) = component
&& name == "signature-agent"
{
match parameters.0.as_slice() {
[] => bare_agent = true,
[HTTPFieldParameters::Key(key)] => keys.push(key),
_ => {}
}
}
}
let signature_agent_key = match keys.as_slice() {
_ if legacy && bare_agent => None,
[] => None,
// A proxy may have relabeled the signature, not the signed member.
[key] => Some(*key),
_ => Some(
keys.into_iter()
.find(|key| key.as_str() == message_verifier.parsed.label.as_str())
.ok_or_else(|| {
ImplementationError::ParsingError(
"Signature must cover its own `Signature-Agent` member".into(),
)
})?,
),
};
let mut parsed_directories = Vec::new();
for entry in header {
if signature_agent_key
.as_ref()
.is_none_or(|key| entry.label == *key)
if signature_agent_key.is_none_or(|key| entry.label == *key)
&& let Some(link) = parse_link(&entry.uri, &entry.discovery_type, legacy)
{
parsed_directories.push(link);
Expand Down Expand Up @@ -441,6 +494,80 @@ mod tests {
}
}

#[test]
fn checks_nested_coverage_and_selects_the_outer_signature_agent() {
struct Message<'a>(&'a str);
impl SignedMessage for Message<'_> {
fn lookup_component(&self, component: &CoveredComponent) -> Vec<String> {
let value = match component {
CoveredComponent::Derived(DerivedComponent::Authority { .. }) => "example.com",
CoveredComponent::Derived(DerivedComponent::Path { .. }) => "/resource",
CoveredComponent::HTTP(HTTPField { name, parameters }) => {
const INNER: &str =
r#"("@authority" "@path" "signature-agent";key="agent")"#;
match (name.as_str(), parameters.0.as_slice()) {
("signature-input", []) => {
return vec![format!(
r#"agent={INNER}, browser=("@authority" {});created=1735689600;expires=1735693200;keyid="test";tag="web-bot-auth""#,
self.0
)];
}
("signature", []) => "agent=:AQ==:, browser=:Ag==:",
("signature-agent", []) => {
r#"agent="https://agent.example", browser="https://browser.example""#
}
("signature-agent", [HTTPFieldParameters::Key(key)])
if key == "browser" =>
{
r#""https://browser.example""#
}
(name, [HTTPFieldParameters::Key(key)]) if key == "agent" => match name
{
"signature-input" => INNER,
"signature" => ":AQ==:",
"signature-agent" => r#""https://agent.example""#,
_ => return vec![],
},
_ => return vec![],
}
}
_ => return vec![],
};
vec![value.to_string()]
}
}

let agent = r#""signature-agent";key="agent""#;
let browser = r#""signature-agent";key="browser""#;
let signature = r#""signature";key="agent""#;
let input = r#""signature-input";key="agent""#;
for components in [
format!(r#"{agent} {browser} {signature} {input} "@path""#),
format!(r#"{browser} {agent} {input} {signature} "@path""#),
] {
let verifier = WebBotAuthVerifier::parse(&Message(&components)).unwrap();
assert_eq!(
verifier.get_signature_agents().as_slice(),
[SignatureAgentLink::Directory(
"https://browser.example".into()
)]
);
}
for (components, expected) in [
(
format!(r#"{agent} {browser} {signature} "@path""#),
"must cover `Signature-Input` member agent",
),
(
format!("{agent} {browser} {signature} {input}"),
"must cover every component of `Signature-Input` member agent",
),
] {
let err = WebBotAuthVerifier::parse(&Message(&components)).unwrap_err();
assert!(err.to_string().contains(expected), "{err}");
}
}

#[test]
fn later_signature_agent_members_replace_earlier_values() {
// A later member replaces the earlier URI even when its parameters make it unusable.
Expand Down
21 changes: 19 additions & 2 deletions crates/web-bot-auth/src/message_signatures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,8 @@ pub trait SignedMessage {
/// Retrieve the raw value(s) of a covered component. Implementations should
/// respect any parameter values set on the covered component per the message
/// signature spec. Component values that cannot be found must return an empty vector.
/// For `key`, return the serialized dictionary member value without its key
/// or `=` (RFC 9421 Section 2.1.2).
/// `CoveredComponent::HTTP` fields are guaranteed to have lowercase ASCII names, so
/// care should be taken to ensure HTTP field names in the message are checked in a
/// case-insensitive way. Only `CoveredComponent::Http` should return a vector with
Expand All @@ -279,6 +281,8 @@ pub trait SignedMessage {
pub trait UnsignedMessage {
/// Obtain a list of covered components to be included. HTTP fields must be lowercased before
/// emitting. It is NOT RECOMMENDED to include `signature` and `signature-input` fields here.
/// For `key`, supply the serialized dictionary member value without its key
/// or `=` (RFC 9421 Section 2.1.2).
/// If signing a Web Bot Auth message, and `Signature-Agent` header is intended present, you MUST
/// include it as a component here for successful verification.
fn fetch_components_to_cover(&self) -> IndexMap<CoveredComponent, String>;
Expand Down Expand Up @@ -557,23 +561,36 @@ impl MessageVerifier {
///
/// Returns `ImplementationErrors` relevant to verifying and parsing.
pub fn parse<P>(message: &impl SignedMessage, pick: P) -> Result<Self, ImplementationError>
where
P: Fn(&(sfv::Key, sfv::InnerList)) -> bool,
{
Self::parse_with_input_check(message, pick, |_, _| Ok(()))
}

pub(crate) fn parse_with_input_check<P>(
message: &impl SignedMessage,
pick: P,
check_input: impl FnOnce(&sfv::Dictionary, &sfv::InnerList) -> Result<(), ImplementationError>,
) -> Result<Self, ImplementationError>
where
P: Fn(&(sfv::Key, sfv::InnerList)) -> bool,
{
let signature_input = parse_signature_dictionary(message, "Signature-Input")?;
let mut signature_header = parse_signature_dictionary(message, "Signature")?;

let (label, innerlist) = signature_input
.into_iter()
.iter()
.filter_map(|(label, listentry)| match listentry {
sfv::ListEntry::InnerList(inner_list) => Some((label, inner_list)),
sfv::ListEntry::InnerList(inner_list) => Some((label.clone(), inner_list.clone())),
sfv::ListEntry::Item(_) => None,
})
.find(pick)
.ok_or(ImplementationError::ParsingError(
"No matching label and signature base found".into(),
))?;

check_input(&signature_input, &innerlist)?;

let signature = match signature_header.shift_remove(&label).ok_or(
ImplementationError::ParsingError("No matching signature found from label".into()),
)? {
Expand Down
2 changes: 2 additions & 0 deletions examples/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ path = "verify.rs"

[dependencies]
indexmap = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
time = { workspace = true }

# workspace dependencies
Expand Down
10 changes: 7 additions & 3 deletions examples/rust/signing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ use web_bot_auth::{
message_signatures::{MessageSigner, UnsignedMessage},
};

const SIGNATURE_AGENT_VALUE: &str =
r#""https://myexample.com/.well-known/http-message-signatures-directory""#;

#[derive(Debug, Default)]
pub(crate) struct MyThing {
signature_input: String,
Expand All @@ -42,8 +45,7 @@ impl UnsignedMessage for MyThing {
"sig1".to_string(),
)]),
}),
r#"sig1="https://myexample.com/.well-known/http-message-signatures-directory""#
.to_string(),
SIGNATURE_AGENT_VALUE.to_string(),
),
])
}
Expand Down Expand Up @@ -81,5 +83,7 @@ fn main() {
assert!(!headers.signature_input.is_empty());
assert!(!headers.signature_header.is_empty());

println!("{:?}", headers);
println!("Signature-Agent: sig1={SIGNATURE_AGENT_VALUE}");
println!("Signature-Input: {}", headers.signature_input);
println!("Signature: {}", headers.signature_header);
}
Loading