From 7ae3285af161db6f798f2a77a71229ffe341d3c1 Mon Sep 17 00:00:00 2001 From: Jascha Wanger Date: Wed, 4 Nov 2026 10:53:16 -0800 Subject: [PATCH 01/11] Add Web Bot Auth: RFC 9421 signatures, key directories, AgentPin binding - httpsig: RFC 9421 signature base, Signature-Input/Signature parsing, Ed25519 signing and strict verification, Content-Digest. - wba: Web Bot Auth profile (draft-ietf-webbotauth-httpsig-protocol-01). Ed25519 keys with RFC 8037 thumbprint keyids, Dictionary Signature-Agent (legacy String form opt-in), verified/invalid/unverified outcomes with key lookup keyed on (URL, keyid), signed directory responses. Reproduces the draft's Ed25519 test vectors and RFC 9421 B.2.6. - resolver_wba (fetch): SSRF-limited directory fetching (https only, no redirects, non-public addresses refused, size/key/time caps) and a cache that a failed refetch never evicts. - Binding: optional cnf.jkt credential claim and web_bot_auth discovery field; verify_bound_request requires the signature to cover the Authorization credential, cnf.jkt to match the keyid, and the issuer to vouch for the Signature-Agent URL. - agentpin-server --wba-key serves a signed key directory for its own hosts only; CLI gains `wba keygen|directory|sign` and `issue --wba-jkt`. The ES256 credential profile is unchanged. --- crates/agentpin-cli/Cargo.toml | 2 + crates/agentpin-cli/src/issue.rs | 43 +- crates/agentpin-cli/src/keygen.rs | 2 +- crates/agentpin-cli/src/main.rs | 4 + crates/agentpin-cli/src/wba.rs | 144 +++ crates/agentpin-server/Cargo.toml | 2 + crates/agentpin-server/src/config.rs | 12 + crates/agentpin-server/src/main.rs | 35 + crates/agentpin-server/src/routes.rs | 114 +- crates/agentpin-server/src/state.rs | 11 + crates/agentpin/Cargo.toml | 6 +- crates/agentpin/src/credential.rs | 63 +- crates/agentpin/src/discovery.rs | 15 + crates/agentpin/src/dns.rs | 1 + crates/agentpin/src/error.rs | 4 + crates/agentpin/src/httpsig.rs | 715 ++++++++++++ crates/agentpin/src/jwt.rs | 12 + crates/agentpin/src/lib.rs | 7 + crates/agentpin/src/net.rs | 191 ++++ crates/agentpin/src/resolver_local.rs | 1 + crates/agentpin/src/resolver_wba.rs | 464 ++++++++ crates/agentpin/src/rotation.rs | 1 + crates/agentpin/src/types/bundle.rs | 1 + crates/agentpin/src/types/credential.rs | 13 + crates/agentpin/src/types/discovery.rs | 15 + crates/agentpin/src/verification.rs | 1 + crates/agentpin/src/wba.rs | 1378 +++++++++++++++++++++++ crates/agentpin/tests/integration.rs | 2 + crates/agentpin/tests/web_bot_auth.rs | 276 +++++ 29 files changed, 3519 insertions(+), 16 deletions(-) create mode 100644 crates/agentpin-cli/src/wba.rs create mode 100644 crates/agentpin/src/httpsig.rs create mode 100644 crates/agentpin/src/resolver_wba.rs create mode 100644 crates/agentpin/src/wba.rs create mode 100644 crates/agentpin/tests/web_bot_auth.rs diff --git a/crates/agentpin-cli/Cargo.toml b/crates/agentpin-cli/Cargo.toml index e9e3c23..dd52fb4 100644 --- a/crates/agentpin-cli/Cargo.toml +++ b/crates/agentpin-cli/Cargo.toml @@ -19,6 +19,8 @@ tokio = { version = "1.0", features = ["full"] } serde_json = "1.0" chrono = "0.4" anyhow = "1.0" +ed25519-dalek = "2.2" +zeroize = "1" [dev-dependencies] tempfile = "3.0" diff --git a/crates/agentpin-cli/src/issue.rs b/crates/agentpin-cli/src/issue.rs index 9fdd9e2..ae39481 100644 --- a/crates/agentpin-cli/src/issue.rs +++ b/crates/agentpin-cli/src/issue.rs @@ -2,7 +2,7 @@ use std::fs; use clap::Args; -use agentpin::credential::issue_credential; +use agentpin::credential::{issue_bound_credential, issue_credential}; use agentpin::crypto; use agentpin::types::capability::Capability; use agentpin::types::constraint::Constraints; @@ -49,6 +49,11 @@ pub struct IssueArgs { /// Path to a JSON file with constraint overrides #[arg(long, conflicts_with = "constraints")] pub constraints_file: Option, + + /// Bind the credential to a Web Bot Auth key: its keyid (JWK + /// thumbprint, as printed by `agentpin wba keygen`), carried as cnf.jkt + #[arg(long)] + pub wba_jkt: Option, } pub fn run(args: IssueArgs) -> anyhow::Result<()> { @@ -78,17 +83,31 @@ pub fn run(args: IssueArgs) -> anyhow::Result<()> { None => None, }; - let jwt = issue_credential( - &signing_key, - &args.kid, - &args.issuer, - &args.agent_id, - args.audience.as_deref(), - capabilities, - constraints, - delegation_chain, - args.ttl, - )?; + let jwt = match &args.wba_jkt { + Some(jkt) => issue_bound_credential( + &signing_key, + &args.kid, + &args.issuer, + &args.agent_id, + args.audience.as_deref(), + capabilities, + constraints, + delegation_chain, + args.ttl, + jkt, + )?, + None => issue_credential( + &signing_key, + &args.kid, + &args.issuer, + &args.agent_id, + args.audience.as_deref(), + capabilities, + constraints, + delegation_chain, + args.ttl, + )?, + }; println!("{}", jwt); Ok(()) diff --git a/crates/agentpin-cli/src/keygen.rs b/crates/agentpin-cli/src/keygen.rs index 526bba1..7595975 100644 --- a/crates/agentpin-cli/src/keygen.rs +++ b/crates/agentpin-cli/src/keygen.rs @@ -58,7 +58,7 @@ pub fn validate_kid(kid: &str) -> anyhow::Result<()> { /// Create `path` with `mode`, refusing to overwrite unless `force`. The mode /// is applied at creation (so a 0600 private key is never world-readable /// even for an instant) and re-applied after an overwrite. -fn write_new_file(path: &Path, contents: &[u8], mode: u32, force: bool) -> anyhow::Result<()> { +pub fn write_new_file(path: &Path, contents: &[u8], mode: u32, force: bool) -> anyhow::Result<()> { let mut opts = fs::OpenOptions::new(); opts.write(true); if force { diff --git a/crates/agentpin-cli/src/main.rs b/crates/agentpin-cli/src/main.rs index 03f4227..0f4332a 100644 --- a/crates/agentpin-cli/src/main.rs +++ b/crates/agentpin-cli/src/main.rs @@ -2,6 +2,7 @@ mod bundle; mod issue; mod keygen; mod verify; +mod wba; use clap::{Parser, Subcommand}; @@ -22,6 +23,8 @@ enum Commands { Verify(verify::VerifyArgs), /// Create a trust bundle from discovery and revocation documents Bundle(bundle::BundleArgs), + /// Web Bot Auth: Ed25519 keys, key directories, request signing + Wba(wba::WbaArgs), } #[tokio::main] @@ -32,6 +35,7 @@ async fn main() -> anyhow::Result<()> { Commands::Issue(args) => issue::run(args)?, Commands::Verify(args) => verify::run(args).await?, Commands::Bundle(args) => bundle::run(args)?, + Commands::Wba(args) => wba::run(args)?, } Ok(()) } diff --git a/crates/agentpin-cli/src/wba.rs b/crates/agentpin-cli/src/wba.rs new file mode 100644 index 0000000..1664164 --- /dev/null +++ b/crates/agentpin-cli/src/wba.rs @@ -0,0 +1,144 @@ +//! `agentpin wba`: Web Bot Auth keys, key directories and request signing. + +use std::fs; +use std::path::Path; + +use clap::{Args, Subcommand}; + +use agentpin::httpsig::{Component, HttpRequest}; +use agentpin::wba::{self, Directory, SignOptions}; + +use crate::keygen::{validate_kid, write_new_file}; + +#[derive(Args)] +pub struct WbaArgs { + #[command(subcommand)] + pub command: WbaCommand, +} + +#[derive(Subcommand)] +pub enum WbaCommand { + /// Generate an Ed25519 signing key; prints its keyid (JWK thumbprint) + Keygen(KeygenArgs), + /// Print the key directory (JWK Set) for one or more keys + Directory(DirectoryArgs), + /// Sign a request and print the Signature-Agent, Signature-Input and + /// Signature headers + Sign(SignArgs), +} + +#[derive(Args)] +pub struct KeygenArgs { + /// File name stem for the key (letters, digits, '.', '_' and '-') + #[arg(long)] + pub name: String, + + /// Output directory + #[arg(long, default_value = ".")] + pub output_dir: String, + + /// Overwrite an existing key file + #[arg(long)] + pub force: bool, +} + +#[derive(Args)] +pub struct DirectoryArgs { + /// Ed25519 private key PEM (repeat for rotation) + #[arg(long = "key", required = true)] + pub keys: Vec, +} + +#[derive(Args)] +pub struct SignArgs { + /// Ed25519 private key PEM + #[arg(long)] + pub key: String, + + /// HTTPS URL of the key directory publishing this key + #[arg(long)] + pub signature_agent: String, + + /// Request URL + #[arg(long)] + pub url: String, + + /// Request method + #[arg(long, default_value = "GET")] + pub method: String, + + /// Header to send and cover, as "Name: value" (repeatable) + #[arg(long = "header")] + pub headers: Vec, + + /// Signature lifetime in seconds (max 86400) + #[arg(long, default_value = "300")] + pub validity: i64, + + /// Send the legacy bare-String Signature-Agent, for verifiers that + /// predate the Dictionary form + #[arg(long)] + pub legacy_signature_agent: bool, +} + +fn load_key(path: &str) -> anyhow::Result { + let pem = zeroize::Zeroizing::new(fs::read_to_string(path)?); + wba::load_signing_key(&pem).map_err(|e| anyhow::anyhow!("{}: {}", path, e)) +} + +pub fn run(args: WbaArgs) -> anyhow::Result<()> { + match args.command { + WbaCommand::Keygen(a) => { + validate_kid(&a.name)?; + let key = wba::generate_signing_key(); + let out_dir = Path::new(&a.output_dir); + fs::create_dir_all(out_dir)?; + let path = out_dir.join(format!("{}.ed25519.pem", a.name)); + write_new_file( + &path, + wba::signing_key_to_pem(&key)?.as_bytes(), + 0o600, + a.force, + )?; + eprintln!( + "Generated Ed25519 Web Bot Auth key: {} (mode 0600)", + path.display() + ); + println!("{}", wba::thumbprint(&key.verifying_key())); + } + WbaCommand::Directory(a) => { + let keys = a + .keys + .iter() + .map(|p| load_key(p)) + .collect::>>()?; + let dir = Directory::from_keys(keys.iter().map(|k| k.as_ref())); + println!("{}", serde_json::to_string_pretty(&dir)?); + } + WbaCommand::Sign(a) => { + let key = load_key(&a.key)?; + let mut req = HttpRequest::new(&a.method, &a.url)?; + let mut opts = SignOptions { + validity_secs: a.validity, + legacy_signature_agent: a.legacy_signature_agent, + ..Default::default() + }; + for h in &a.headers { + let (name, value) = h + .split_once(':') + .ok_or_else(|| anyhow::anyhow!("--header must be \"Name: value\""))?; + let name = name.trim(); + req = req.header(name, value.trim()); + let c = Component::new(&name.to_ascii_lowercase()); + if !opts.components.contains(&c) { + opts.components.push(c); + } + } + for (name, value) in wba::sign_request(&req, &key, &a.signature_agent, &opts)?.to_vec() + { + println!("{}: {}", name, value); + } + } + } + Ok(()) +} diff --git a/crates/agentpin-server/Cargo.toml b/crates/agentpin-server/Cargo.toml index 8fc102c..58cd1ca 100644 --- a/crates/agentpin-server/Cargo.toml +++ b/crates/agentpin-server/Cargo.toml @@ -25,3 +25,5 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] } clap = { version = "4.0", features = ["derive"] } chrono = "0.4" anyhow = "1.0" +ed25519-dalek = "2.2" +zeroize = "1" diff --git a/crates/agentpin-server/src/config.rs b/crates/agentpin-server/src/config.rs index c520271..88855fa 100644 --- a/crates/agentpin-server/src/config.rs +++ b/crates/agentpin-server/src/config.rs @@ -24,6 +24,18 @@ pub struct ServerConfig { /// serves these endpoints under https (AP-23). #[arg(long)] pub hsts: bool, + + /// Ed25519 PKCS#8 PEM key to publish and sign with at + /// /.well-known/http-message-signatures-directory (Web Bot Auth). + /// Repeat for key rotation. + #[arg(long = "wba-key")] + pub wba_keys: Vec, + + /// Extra host the key directory may be served under. The discovery + /// entity is always allowed; requests for any other Host get 404, so the + /// directory's possession proof cannot be minted for a foreign domain. + #[arg(long = "wba-authority")] + pub wba_authorities: Vec, } impl ServerConfig { diff --git a/crates/agentpin-server/src/main.rs b/crates/agentpin-server/src/main.rs index 15d2764..4121f16 100644 --- a/crates/agentpin-server/src/main.rs +++ b/crates/agentpin-server/src/main.rs @@ -38,9 +38,40 @@ async fn main() -> anyhow::Result<()> { None => None, }; + // Optional Web Bot Auth key directory + let wba = if config.wba_keys.is_empty() { + None + } else { + let keys = config + .wba_keys + .iter() + .map(|path| { + let pem = zeroize::Zeroizing::new(std::fs::read_to_string(path)?); + agentpin::wba::load_signing_key(&pem) + .map_err(|e| anyhow::anyhow!("{}: {}", path, e)) + }) + .collect::>>()?; + let body = + agentpin::wba::Directory::from_keys(keys.iter().map(|k| k.as_ref())).to_json()?; + let mut authorities = vec![discovery.entity.to_ascii_lowercase()]; + authorities.extend( + config + .wba_authorities + .iter() + .map(|a| a.to_ascii_lowercase()), + ); + tracing::info!(keys = keys.len(), "Serving Web Bot Auth key directory"); + Some(Arc::new(state::WbaDirectory { + keys, + body, + authorities, + })) + }; + let state = AppState { discovery: Arc::new(RwLock::new(discovery)), revocation: Arc::new(RwLock::new(revocation)), + wba, }; // Build router with security headers @@ -54,6 +85,10 @@ async fn main() -> anyhow::Result<()> { "/.well-known/agent-identity-revocations.json", axum::routing::get(routes::revocations), ) + .route( + "/.well-known/http-message-signatures-directory", + axum::routing::get(routes::wba_directory), + ) .route("/health", axum::routing::get(routes::health)) .with_state(state) .layer(TraceLayer::new_for_http()); diff --git a/crates/agentpin-server/src/routes.rs b/crates/agentpin-server/src/routes.rs index 468349c..88d1393 100644 --- a/crates/agentpin-server/src/routes.rs +++ b/crates/agentpin-server/src/routes.rs @@ -1,6 +1,7 @@ +use agentpin::wba; use axum::extract::State; -use axum::http::header; use axum::http::StatusCode; +use axum::http::{header, HeaderMap}; use axum::response::{IntoResponse, Response}; use axum::Json; @@ -36,6 +37,45 @@ pub async fn revocations(State(state): State) -> Response { } } +/// Web Bot Auth key directory, signed per request (Appendix B.1). The +/// signature covers the request's authority, so only configured hosts are +/// answered. +pub async fn wba_directory(State(state): State, headers: HeaderMap) -> Response { + let Some(dir) = state.wba.as_deref() else { + return StatusCode::NOT_FOUND.into_response(); + }; + let Some(host) = headers + .get(header::HOST) + .and_then(|h| h.to_str().ok()) + .map(|h| h.trim().to_ascii_lowercase()) + else { + return StatusCode::BAD_REQUEST.into_response(); + }; + if !dir.authorities.contains(&host) { + return StatusCode::NOT_FOUND.into_response(); + } + let signed = match wba::sign_directory_response( + &dir.body, + &host, + &dir.keys, + chrono::Utc::now().timestamp(), + wba::MAX_VALIDITY_SECS, + ) { + Ok(h) => h, + Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), + }; + let mut builder = Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, wba::DIRECTORY_MEDIA_TYPE) + .header(header::CACHE_CONTROL, "public, max-age=3600"); + for (name, value) in signed { + builder = builder.header(name, value); + } + builder + .body(axum::body::Body::from(dir.body.clone())) + .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response()) +} + pub async fn health() -> Response { (StatusCode::OK, Json(serde_json::json!({"status": "ok"}))).into_response() } @@ -78,6 +118,7 @@ mod tests { policy_url: None, schemapin_endpoint: None, a2a_endpoint: None, + web_bot_auth: None, max_delegation_depth: 2, updated_at: "2026-01-01T00:00:00Z".to_string(), }; @@ -85,6 +126,7 @@ mod tests { AppState { discovery: Arc::new(RwLock::new(discovery)), revocation: Arc::new(RwLock::new(None)), + wba: None, } } @@ -98,10 +140,80 @@ mod tests { "/.well-known/agent-identity-revocations.json", axum::routing::get(revocations), ) + .route( + "/.well-known/http-message-signatures-directory", + axum::routing::get(wba_directory), + ) .route("/health", axum::routing::get(health)) .with_state(state) } + fn wba_state(key: &ed25519_dalek::SigningKey) -> AppState { + let mut state = test_state(); + state.wba = Some(Arc::new(crate::state::WbaDirectory { + keys: vec![key.clone()], + body: wba::Directory::from_keys([&key.verifying_key()]) + .to_json() + .unwrap(), + authorities: vec!["test.com".to_string()], + })); + state + } + + async fn get_directory(state: AppState, host: Option<&str>) -> Response { + let mut req = Request::builder().uri("/.well-known/http-message-signatures-directory"); + if let Some(h) = host { + req = req.header(header::HOST, h); + } + app(state) + .oneshot(req.body(Body::empty()).unwrap()) + .await + .unwrap() + } + + #[tokio::test] + async fn test_wba_directory_is_signed() { + let key = wba::generate_signing_key(); + let resp = get_directory(wba_state(&key), Some("Test.com")).await; + assert_eq!(resp.status(), StatusCode::OK); + assert_eq!( + resp.headers().get(header::CONTENT_TYPE).unwrap(), + wba::DIRECTORY_MEDIA_TYPE + ); + let headers: Vec<(String, String)> = resp + .headers() + .iter() + .map(|(k, v)| (k.to_string(), v.to_str().unwrap().to_string())) + .collect(); + let body = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + let proven = wba::verify_directory_response( + &body, + &headers, + "test.com", + chrono::Utc::now().timestamp(), + 60, + ) + .unwrap(); + assert_eq!(proven.keys.len(), 1); + assert_eq!( + proven.keys[0].thumbprint(), + wba::thumbprint(&key.verifying_key()) + ); + } + + #[tokio::test] + async fn test_wba_directory_refuses_foreign_host() { + let key = wba::generate_signing_key(); + let resp = get_directory(wba_state(&key), Some("evil.example")).await; + assert_eq!(resp.status(), StatusCode::NOT_FOUND); + let resp = get_directory(wba_state(&key), None).await; + assert_eq!(resp.status(), StatusCode::BAD_REQUEST); + let resp = get_directory(test_state(), Some("test.com")).await; + assert_eq!(resp.status(), StatusCode::NOT_FOUND); + } + #[tokio::test] async fn test_discovery_endpoint() { let state = test_state(); diff --git a/crates/agentpin-server/src/state.rs b/crates/agentpin-server/src/state.rs index 142cb3f..530fed3 100644 --- a/crates/agentpin-server/src/state.rs +++ b/crates/agentpin-server/src/state.rs @@ -2,10 +2,21 @@ use std::sync::Arc; use agentpin::types::discovery::DiscoveryDocument; use agentpin::types::revocation::RevocationDocument; +use ed25519_dalek::SigningKey; use tokio::sync::RwLock; #[derive(Clone)] pub struct AppState { pub discovery: Arc>, pub revocation: Arc>>, + pub wba: Option>, +} + +/// Web Bot Auth key directory served by this instance. +pub struct WbaDirectory { + pub keys: Vec, + /// Serialized JWK Set, signed as served. + pub body: Vec, + /// Lowercase hosts (with non-default port) the directory is served for. + pub authorities: Vec, } diff --git a/crates/agentpin/Cargo.toml b/crates/agentpin/Cargo.toml index 6c647ac..f35cec3 100644 --- a/crates/agentpin/Cargo.toml +++ b/crates/agentpin/Cargo.toml @@ -12,7 +12,7 @@ categories = ["authentication", "cryptography"] [features] default = [] -fetch = ["reqwest", "tokio", "async-trait"] +fetch = ["reqwest", "tokio/net", "async-trait"] dns = ["hickory-resolver", "tokio", "async-trait"] [dependencies] @@ -40,6 +40,10 @@ tempfile = { version = "3.0", optional = true } # Optional dependency for DNS TXT cross-verification (v0.3.0) hickory-resolver = { version = "0.26.1", optional = true } +# Web Bot Auth / RFC 9421 HTTP message signatures (v0.4.0) +ed25519-dalek = { version = "2.2", features = ["rand_core", "pkcs8", "pem", "zeroize"] } +sfv = "0.15" + [dev-dependencies] tempfile = "3.0" tokio = { version = "1.0", features = ["rt-multi-thread", "macros"] } diff --git a/crates/agentpin/src/credential.rs b/crates/agentpin/src/credential.rs index a2bd051..48248aa 100644 --- a/crates/agentpin/src/credential.rs +++ b/crates/agentpin/src/credential.rs @@ -6,7 +6,7 @@ use crate::error::Error; use crate::jwt; use crate::types::capability::Capability; use crate::types::constraint::Constraints; -use crate::types::credential::{DelegationAttestation, JwtHeader, JwtPayload}; +use crate::types::credential::{Confirmation, DelegationAttestation, JwtHeader, JwtPayload}; /// Issue a new agent credential JWT. #[allow(clippy::too_many_arguments)] @@ -20,6 +20,65 @@ pub fn issue_credential( constraints: Option, delegation_chain: Option>, ttl_secs: u64, +) -> Result { + issue( + signing_key, + kid, + issuer, + agent_id, + audience, + capabilities, + constraints, + delegation_chain, + ttl_secs, + None, + ) +} + +/// Issue a credential bound to the agent's Web Bot Auth Ed25519 key: +/// `wba_jkt` (its JWK thumbprint, see [`crate::wba::thumbprint`]) is +/// carried as `cnf.jkt` (spec §18). +#[allow(clippy::too_many_arguments)] +pub fn issue_bound_credential( + signing_key: &SigningKey, + kid: &str, + issuer: &str, + agent_id: &str, + audience: Option<&str>, + capabilities: Vec, + constraints: Option, + delegation_chain: Option>, + ttl_secs: u64, + wba_jkt: &str, +) -> Result { + issue( + signing_key, + kid, + issuer, + agent_id, + audience, + capabilities, + constraints, + delegation_chain, + ttl_secs, + Some(Confirmation { + jkt: wba_jkt.to_string(), + }), + ) +} + +#[allow(clippy::too_many_arguments)] +fn issue( + signing_key: &SigningKey, + kid: &str, + issuer: &str, + agent_id: &str, + audience: Option<&str>, + capabilities: Vec, + constraints: Option, + delegation_chain: Option>, + ttl_secs: u64, + cnf: Option, ) -> Result { let now = Utc::now().timestamp(); @@ -42,7 +101,9 @@ pub fn issue_credential( constraints, delegation_chain, nonce: None, + cnf, }; + jwt::validate_claims(&payload)?; jwt::encode_jwt(&header, &payload, signing_key) } diff --git a/crates/agentpin/src/discovery.rs b/crates/agentpin/src/discovery.rs index cb5ffcb..fd50b84 100644 --- a/crates/agentpin/src/discovery.rs +++ b/crates/agentpin/src/discovery.rs @@ -25,6 +25,7 @@ pub fn build_discovery_document( policy_url: None, schemapin_endpoint: None, a2a_endpoint: None, + web_bot_auth: None, max_delegation_depth, updated_at: updated_at.to_string(), } @@ -69,6 +70,20 @@ pub fn validate_discovery_document( "Discovery document must have at least one public key".to_string(), )); } + // Web Bot Auth directories the entity vouches for (spec §18): any + // https URL, since key directories may be hosted by a provider. + if let Some(ref wba) = doc.web_bot_auth { + if wba.signature_agents.is_empty() || wba.signature_agents.len() > 16 { + return Err(Error::Discovery( + "web_bot_auth.signature_agents must list 1-16 URLs".to_string(), + )); + } + for url in &wba.signature_agents { + crate::wba::normalize_signature_agent(url).map_err(|e| { + Error::Discovery(format!("Invalid web_bot_auth signature agent: {}", e)) + })?; + } + } if doc.max_delegation_depth > 3 { return Err(Error::Discovery( "max_delegation_depth must be 0-3".to_string(), diff --git a/crates/agentpin/src/dns.rs b/crates/agentpin/src/dns.rs index 3f3fd79..7313951 100644 --- a/crates/agentpin/src/dns.rs +++ b/crates/agentpin/src/dns.rs @@ -210,6 +210,7 @@ mod tests { policy_url: None, schemapin_endpoint: None, a2a_endpoint: None, + web_bot_auth: None, max_delegation_depth: 0, updated_at: "2026-05-01T00:00:00Z".to_string(), } diff --git a/crates/agentpin/src/error.rs b/crates/agentpin/src/error.rs index cf396a4..f81d8db 100644 --- a/crates/agentpin/src/error.rs +++ b/crates/agentpin/src/error.rs @@ -46,6 +46,10 @@ pub enum Error { #[error("Transport error: {0}")] Transport(String), + /// RFC 9421 HTTP message signature parsing or construction failed. + #[error("HTTP signature error: {0}")] + HttpSignature(String), + #[error("IO error: {0}")] Io(#[from] std::io::Error), diff --git a/crates/agentpin/src/httpsig.rs b/crates/agentpin/src/httpsig.rs new file mode 100644 index 0000000..b92e66c --- /dev/null +++ b/crates/agentpin/src/httpsig.rs @@ -0,0 +1,715 @@ +//! RFC 9421 HTTP Message Signatures. +//! +//! Builds signature bases, reads and writes the `Signature-Input` and +//! `Signature` fields, and signs and verifies with Ed25519 +//! (`alg="ed25519"`). This is the layer Web Bot Auth ([`crate::wba`]) is +//! built on. +//! +//! Supported component identifiers: `@method`, `@target-uri`, `@authority`, +//! `@scheme`, `@request-target`, `@path`, `@query`, `@status`, and HTTP +//! fields, with the `key` (Dictionary member) and `req` (related request) +//! parameters. Identifiers carrying any other parameter (`sf`, `bs`, `tr`, +//! `name`) are rejected rather than silently mis-serialized. + +use base64::{engine::general_purpose::STANDARD as BASE64, Engine}; +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use sfv::{BareItem, Dictionary, FieldType, InnerList, Item, Key, ListEntry, Parameters, Parser}; +use url::Url; + +use crate::error::Error; + +fn err(msg: impl Into) -> Error { + Error::HttpSignature(msg.into()) +} + +// --------------------------------------------------------------------------- +// Messages +// --------------------------------------------------------------------------- + +/// The parts of an HTTP request a signature can cover. +#[derive(Debug, Clone)] +pub struct HttpRequest { + pub method: String, + pub url: Url, + /// Header fields in order; names are matched case-insensitively. + pub headers: Vec<(String, String)>, +} + +impl HttpRequest { + /// Build a request from a method and an absolute URL. + pub fn new(method: &str, url: &str) -> Result { + let url = Url::parse(url).map_err(|_| err("request URL is not an absolute URL"))?; + if url.host_str().is_none() { + return Err(err("request URL has no host")); + } + Ok(Self { + method: method.to_string(), + url, + headers: Vec::new(), + }) + } + + /// Append a header field. + pub fn header(mut self, name: &str, value: &str) -> Self { + self.headers.push((name.to_string(), value.to_string())); + self + } +} + +/// The parts of an HTTP response a signature can cover. +#[derive(Debug, Clone)] +pub struct HttpResponse { + pub status: u16, + pub headers: Vec<(String, String)>, +} + +/// The message a signature is computed over. A response may carry the +/// request that produced it, for components with the `req` parameter. +#[derive(Debug, Clone, Copy)] +pub enum Message<'a> { + Request(&'a HttpRequest), + Response { + response: &'a HttpResponse, + request: Option<&'a HttpRequest>, + }, +} + +impl Message<'_> { + fn headers(&self) -> &[(String, String)] { + match self { + Message::Request(r) => &r.headers, + Message::Response { response, .. } => &response.headers, + } + } +} + +/// Combined value of every `name` field: each value trimmed, joined with +/// `", "` (RFC 9421 §2.1). `None` when the field is absent. +pub fn combined_field(headers: &[(String, String)], name: &str) -> Option { + let values: Vec<&str> = headers + .iter() + .filter(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.trim()) + .collect(); + if values.is_empty() { + None + } else { + Some(values.join(", ")) + } +} + +/// Parse the combined `name` field as a Structured Field Dictionary; an +/// absent field is an empty Dictionary. +pub fn parse_dictionary_field( + headers: &[(String, String)], + name: &str, +) -> Result { + match combined_field(headers, name) { + None => Ok(Dictionary::new()), + Some(v) => Parser::new(&v) + .parse::() + .map_err(|_| err(format!("{} is not a valid Dictionary", name))), + } +} + +/// Serialize one Dictionary member's value (item or inner list, with its +/// parameters) the way RFC 9421 §2.1.2 covers it. +fn serialize_member(entry: &ListEntry) -> String { + vec![entry.clone()].serialize().unwrap_or_default() +} + +// --------------------------------------------------------------------------- +// Component identifiers +// --------------------------------------------------------------------------- + +/// A covered component identifier. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Component { + /// Lowercase field name or derived component name (`@authority`). + pub name: String, + /// `key` parameter: cover one member of a Dictionary field. + pub key: Option, + /// `req` parameter: resolve against the related request. + pub req: bool, +} + +impl Component { + pub fn new(name: &str) -> Self { + Self { + name: name.to_string(), + key: None, + req: false, + } + } + + /// A Dictionary field member, e.g. `"signature-agent";key="sig1"`. + pub fn keyed(name: &str, key: &str) -> Self { + Self { + key: Some(key.to_string()), + ..Self::new(name) + } + } + + /// A component of the related request, e.g. `"@authority";req`. + pub fn of_request(name: &str) -> Self { + Self { + req: true, + ..Self::new(name) + } + } + + fn to_item(&self) -> Result { + let mut params = Parameters::new(); + if let Some(ref k) = self.key { + params.insert(key("key")?, BareItem::String(sf_string(k)?)); + } + if self.req { + params.insert(key("req")?, BareItem::Boolean(true)); + } + Ok(Item::with_params( + BareItem::String(sf_string(&self.name)?), + params, + )) + } + + fn from_item(item: &Item) -> Result { + let name = item + .bare_item + .as_string() + .ok_or_else(|| err("component identifier is not a String"))? + .as_str() + .to_string(); + if name.is_empty() || name != name.to_ascii_lowercase() { + return Err(err(format!("component name '{}' must be lowercase", name))); + } + if name == "@signature-params" { + return Err(err("@signature-params cannot be covered")); + } + let mut c = Component::new(&name); + for (k, v) in &item.params { + match k.as_str() { + "key" => { + let s = v + .as_string() + .ok_or_else(|| err("key parameter must be a String"))?; + if name.starts_with('@') { + return Err(err("key parameter on a derived component")); + } + c.key = Some(s.as_str().to_string()); + } + "req" => { + if v.as_boolean() != Some(true) { + return Err(err("req parameter must be true")); + } + c.req = true; + } + other => { + return Err(err(format!( + "unsupported component parameter '{}' on '{}'", + other, name + ))) + } + } + } + Ok(c) + } + + fn identifier(&self) -> Result { + Ok(self.to_item()?.serialize()) + } +} + +fn key(s: &str) -> Result { + Key::from_string(s.to_string()).map_err(|_| err(format!("invalid key '{}'", s))) +} + +fn sf_string(s: &str) -> Result { + sfv::String::from_string(s.to_string()).map_err(|_| err("value is not a valid sf-string")) +} + +fn authority(url: &Url) -> Result { + let host = url + .host_str() + .ok_or_else(|| err("URL has no host"))? + .to_ascii_lowercase(); + Ok(match url.port() { + Some(p) => format!("{}:{}", host, p), + None => host, + }) +} + +fn component_value(msg: Message<'_>, c: &Component) -> Result { + let msg = if c.req { + match msg { + Message::Response { + request: Some(r), .. + } => Message::Request(r), + _ => return Err(err("req parameter needs a response with its request")), + } + } else { + msg + }; + + if let Some(derived) = c.name.strip_prefix('@') { + if derived == "status" { + return match msg { + Message::Response { response, .. } => Ok(response.status.to_string()), + Message::Request(_) => Err(err("@status is only valid on a response")), + }; + } + let Message::Request(req) = msg else { + return Err(err(format!("{} needs a request", c.name))); + }; + let url = &req.url; + return match derived { + "method" => Ok(req.method.clone()), + "target-uri" => Ok(url.as_str().to_string()), + "authority" => authority(url), + "scheme" => Ok(url.scheme().to_ascii_lowercase()), + "request-target" => Ok(match url.query() { + Some(q) => format!("{}?{}", url.path(), q), + None => url.path().to_string(), + }), + "path" => Ok(if url.path().is_empty() { + "/".to_string() + } else { + url.path().to_string() + }), + "query" => Ok(format!("?{}", url.query().unwrap_or(""))), + _ => Err(err(format!("unsupported derived component {}", c.name))), + }; + } + + match c.key { + None => combined_field(msg.headers(), &c.name) + .ok_or_else(|| err(format!("covered field '{}' is missing", c.name))), + Some(ref k) => { + let dict = parse_dictionary_field(msg.headers(), &c.name)?; + let entry = dict + .get(k.as_str()) + .ok_or_else(|| err(format!("'{}' has no member '{}'", c.name, k)))?; + Ok(serialize_member(entry)) + } + } +} + +// --------------------------------------------------------------------------- +// Signature parameters +// --------------------------------------------------------------------------- + +/// One `@signature-params` parameter, for signing. Parameters are written +/// in the order given. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Param { + Created(i64), + Expires(i64), + KeyId(String), + Alg(String), + Nonce(String), + Tag(String), +} + +/// Signature parameters as received. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct SignatureParams { + pub created: Option, + pub expires: Option, + pub keyid: Option, + pub alg: Option, + pub nonce: Option, + pub tag: Option, +} + +fn sf_integer(v: i64) -> Result { + sfv::Integer::try_from(v) + .map(BareItem::Integer) + .map_err(|_| err("integer out of range")) +} + +fn build_inner_list(components: &[Component], params: &[Param]) -> Result { + let items = components + .iter() + .map(Component::to_item) + .collect::, _>>()?; + let mut p = Parameters::new(); + for param in params { + let (k, v) = match param { + Param::Created(t) => ("created", sf_integer(*t)?), + Param::Expires(t) => ("expires", sf_integer(*t)?), + Param::KeyId(s) => ("keyid", BareItem::String(sf_string(s)?)), + Param::Alg(s) => ("alg", BareItem::String(sf_string(s)?)), + Param::Nonce(s) => ("nonce", BareItem::String(sf_string(s)?)), + Param::Tag(s) => ("tag", BareItem::String(sf_string(s)?)), + }; + if p.insert(key(k)?, v).is_some() { + return Err(err(format!("duplicate signature parameter '{}'", k))); + } + } + Ok(InnerList::with_params(items, p)) +} + +fn read_params(params: &Parameters) -> Result { + let int = |v: &BareItem, k: &str| { + v.as_integer() + .map(i64::from) + .ok_or_else(|| err(format!("{} must be an Integer", k))) + }; + let string = |v: &BareItem, k: &str| { + v.as_string() + .map(|s| s.as_str().to_string()) + .ok_or_else(|| err(format!("{} must be a String", k))) + }; + let mut out = SignatureParams::default(); + for (k, v) in params { + match k.as_str() { + "created" => out.created = Some(int(v, "created")?), + "expires" => out.expires = Some(int(v, "expires")?), + "keyid" => out.keyid = Some(string(v, "keyid")?), + "alg" => out.alg = Some(string(v, "alg")?), + "nonce" => out.nonce = Some(string(v, "nonce")?), + "tag" => out.tag = Some(string(v, "tag")?), + // Unknown parameters are covered by the signature; ignore them. + _ => {} + } + } + Ok(out) +} + +// --------------------------------------------------------------------------- +// Signature base, parsing, signing, verifying +// --------------------------------------------------------------------------- + +/// Build the signature base (RFC 9421 §2.5) for `components` and the +/// serialized `@signature-params` inner list. +fn signature_base( + msg: Message<'_>, + components: &[Component], + inner: &InnerList, +) -> Result { + let mut base = String::new(); + for c in components { + let value = component_value(msg, c)?; + if value.contains('\n') || value.contains('\r') { + return Err(err("component value contains a line break")); + } + base.push_str(&c.identifier()?); + base.push_str(": "); + base.push_str(&value); + base.push('\n'); + } + let params = vec![ListEntry::InnerList(inner.clone())] + .serialize() + .unwrap_or_default(); + base.push_str("\"@signature-params\": "); + base.push_str(¶ms); + Ok(base) +} + +/// One signature read from `Signature-Input` and `Signature`. +#[derive(Debug, Clone)] +pub struct ParsedSignature { + pub label: String, + pub components: Vec, + pub params: SignatureParams, + pub signature: Vec, + inner: InnerList, +} + +impl ParsedSignature { + /// `true` if the signature covers `component`. + pub fn covers(&self, component: &Component) -> bool { + self.components.contains(component) + } + + /// The exact signature base this signature claims to cover. + pub fn signature_base(&self, msg: Message<'_>) -> Result { + signature_base(msg, &self.components, &self.inner) + } +} + +/// Parse every signature carried in `headers`. A `Signature-Input` member +/// without a matching `Signature` member, or a repeated component, is an +/// error. +pub fn parse_signatures(headers: &[(String, String)]) -> Result, Error> { + let inputs = parse_dictionary_field(headers, "signature-input")?; + let sigs = parse_dictionary_field(headers, "signature")?; + let mut out = Vec::with_capacity(inputs.len()); + for (label, entry) in &inputs { + let ListEntry::InnerList(inner) = entry else { + return Err(err(format!( + "Signature-Input '{}' is not an Inner List", + label + ))); + }; + let signature = match sigs.get(label.as_str()) { + Some(ListEntry::Item(item)) => item + .bare_item + .as_byte_sequence() + .ok_or_else(|| err(format!("Signature '{}' is not a Byte Sequence", label)))? + .to_vec(), + _ => return Err(err(format!("no Signature for label '{}'", label))), + }; + let mut components = Vec::with_capacity(inner.items.len()); + for item in &inner.items { + let c = Component::from_item(item)?; + if components.contains(&c) { + return Err(err(format!("component '{}' is covered twice", c.name))); + } + components.push(c); + } + out.push(ParsedSignature { + label: label.as_str().to_string(), + components, + params: read_params(&inner.params)?, + signature, + inner: inner.clone(), + }); + } + Ok(out) +} + +/// `Signature-Input` and `Signature` member strings for one signature, +/// e.g. `sig1=("@authority");created=1` and `sig1=:...:`. Each is a valid +/// field value on its own, and can be appended as an extra field line. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SignatureFields { + pub signature_input: String, + pub signature: String, +} + +/// Sign `msg` over `components` with Ed25519 under `label`. +pub fn sign_ed25519( + msg: Message<'_>, + label: &str, + components: &[Component], + params: &[Param], + signing_key: &SigningKey, +) -> Result { + for (i, c) in components.iter().enumerate() { + if components[..i].contains(c) { + return Err(err(format!("component '{}' is covered twice", c.name))); + } + } + let inner = build_inner_list(components, params)?; + let base = signature_base(msg, components, &inner)?; + let sig: Signature = signing_key.sign(base.as_bytes()); + + let label_key = key(label)?; + let mut input = Dictionary::new(); + input.insert(label_key.clone(), ListEntry::InnerList(inner)); + let mut signature = Dictionary::new(); + signature.insert( + label_key, + ListEntry::Item(Item::new(BareItem::ByteSequence(sig.to_bytes().to_vec()))), + ); + Ok(SignatureFields { + signature_input: input.serialize().unwrap_or_default(), + signature: signature.serialize().unwrap_or_default(), + }) +} + +/// Verify `sig` over `msg` with an Ed25519 key. Uses strict verification +/// (rejects non-canonical and small-order encodings). +pub fn verify_ed25519( + msg: Message<'_>, + sig: &ParsedSignature, + verifying_key: &VerifyingKey, +) -> Result<(), Error> { + let bytes: [u8; 64] = sig + .signature + .as_slice() + .try_into() + .map_err(|_| Error::SignatureInvalid)?; + let base = sig.signature_base(msg)?; + verifying_key + .verify_strict(base.as_bytes(), &Signature::from_bytes(&bytes)) + .map_err(|_| Error::SignatureInvalid) +} + +/// `Content-Digest` value for `body` using SHA-256 (RFC 9530). +pub fn content_digest(body: &[u8]) -> String { + use sha2::{Digest, Sha256}; + format!("sha-256=:{}:", BASE64.encode(Sha256::digest(body))) +} + +/// `true` when the `Content-Digest` field in `headers` carries a `sha-256` +/// member matching `body`. +pub fn content_digest_matches(headers: &[(String, String)], body: &[u8]) -> bool { + use sha2::{Digest, Sha256}; + let Ok(dict) = parse_dictionary_field(headers, "content-digest") else { + return false; + }; + match dict.get("sha-256") { + Some(ListEntry::Item(item)) => { + item.bare_item.as_byte_sequence() == Some(&Sha256::digest(body)[..]) + } + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ed25519_dalek::pkcs8::DecodePrivateKey; + + /// RFC 9421 Appendix B.1.4 test key (test-key-ed25519). + pub(crate) const RFC_ED25519_PEM: &str = "-----BEGIN PRIVATE KEY-----\n\ + MC4CAQAwBQYDK2VwBCIEIJ+DYvh6SEqVTm50DFtMDoQikTmiCqirVv9mWG9qfSnF\n\ + -----END PRIVATE KEY-----\n"; + + fn rfc_key() -> SigningKey { + SigningKey::from_pkcs8_pem(RFC_ED25519_PEM).unwrap() + } + + /// RFC 9421 Appendix B.2.6: Ed25519 over the RFC test request. + #[test] + fn rfc9421_b26_ed25519_vector() { + let req = HttpRequest::new("POST", "https://example.com/foo?param=Value&Pet=dog") + .unwrap() + .header("Host", "example.com") + .header("Date", "Tue, 20 Apr 2021 02:07:55 GMT") + .header("Content-Type", "application/json") + .header("Content-Length", "18"); + let components = [ + Component::new("date"), + Component::new("@method"), + Component::new("@path"), + Component::new("@authority"), + Component::new("content-type"), + Component::new("content-length"), + ]; + let params = [ + Param::Created(1618884473), + Param::KeyId("test-key-ed25519".into()), + ]; + let fields = sign_ed25519( + Message::Request(&req), + "sig-b26", + &components, + ¶ms, + &rfc_key(), + ) + .unwrap(); + assert_eq!( + fields.signature, + "sig-b26=:wqcAqbmYJ2ji2glfAMaRy4gruYYnx2nEFN2HN6jrnDnQCK1u02Gb04v9EDgwUPiu4A0w6vuQv5lIp5WPpBKRCw==:" + ); + assert_eq!( + fields.signature_input, + "sig-b26=(\"date\" \"@method\" \"@path\" \"@authority\" \"content-type\" \"content-length\");created=1618884473;keyid=\"test-key-ed25519\"" + ); + + let signed = req + .header("Signature-Input", &fields.signature_input) + .header("Signature", &fields.signature); + let parsed = parse_signatures(&signed.headers).unwrap(); + assert_eq!(parsed.len(), 1); + verify_ed25519( + Message::Request(&signed), + &parsed[0], + &rfc_key().verifying_key(), + ) + .unwrap(); + } + + #[test] + fn tampered_component_fails() { + let req = HttpRequest::new("GET", "https://example.com/a").unwrap(); + let fields = sign_ed25519( + Message::Request(&req), + "s", + &[Component::new("@authority"), Component::new("@path")], + &[Param::Created(1)], + &rfc_key(), + ) + .unwrap(); + let mut moved = HttpRequest::new("GET", "https://example.com/b").unwrap(); + moved.headers = vec![ + ("Signature-Input".into(), fields.signature_input), + ("Signature".into(), fields.signature), + ]; + let parsed = parse_signatures(&moved.headers).unwrap(); + assert!(matches!( + verify_ed25519( + Message::Request(&moved), + &parsed[0], + &rfc_key().verifying_key() + ), + Err(Error::SignatureInvalid) + )); + } + + #[test] + fn derived_components() { + let req = HttpRequest::new("GET", "https://Example.COM:8443/p/q?x=1").unwrap(); + let m = Message::Request(&req); + let v = |n: &str| component_value(m, &Component::new(n)).unwrap(); + assert_eq!(v("@authority"), "example.com:8443"); + assert_eq!(v("@scheme"), "https"); + assert_eq!(v("@path"), "/p/q"); + assert_eq!(v("@query"), "?x=1"); + assert_eq!(v("@request-target"), "/p/q?x=1"); + let plain = HttpRequest::new("GET", "https://example.com").unwrap(); + let v = |n: &str| component_value(Message::Request(&plain), &Component::new(n)).unwrap(); + assert_eq!(v("@authority"), "example.com"); + assert_eq!(v("@path"), "/"); + assert_eq!(v("@query"), "?"); + assert!(component_value(Message::Request(&plain), &Component::new("@status")).is_err()); + } + + #[test] + fn combined_fields_and_dictionary_members() { + let req = HttpRequest::new("GET", "https://example.com") + .unwrap() + .header("X-A", " one ") + .header("x-a", "two") + .header("Sig-Agent", "a=\"https://a.test\", b=\"https://b.test\""); + let m = Message::Request(&req); + assert_eq!( + component_value(m, &Component::new("x-a")).unwrap(), + "one, two" + ); + assert_eq!( + component_value(m, &Component::keyed("sig-agent", "b")).unwrap(), + "\"https://b.test\"" + ); + assert!(component_value(m, &Component::keyed("sig-agent", "c")).is_err()); + assert!(component_value(m, &Component::new("missing")).is_err()); + } + + #[test] + fn rejects_bad_identifiers() { + for input in [ + "s=(\"Date\");created=1", + "s=(\"date\";sf);created=1", + "s=(\"@signature-params\");created=1", + "s=(\"date\" \"date\");created=1", + "s=(\"@method\";key=\"x\");created=1", + ] { + let h = vec![ + ("Signature-Input".to_string(), input.to_string()), + ("Signature".to_string(), "s=:AAAA:".to_string()), + ]; + assert!(parse_signatures(&h).is_err(), "{}", input); + } + let missing_sig = vec![( + "Signature-Input".to_string(), + "s=(\"date\");created=1".to_string(), + )]; + assert!(parse_signatures(&missing_sig).is_err()); + } + + #[test] + fn content_digest_roundtrip() { + let body = b"{\"hello\": \"world\"}\n"; + // RFC 9530 Appendix B.1 example value. + assert_eq!( + content_digest(body), + "sha-256=:RK/0qy18MlBSVnWgjwz6lZEWjP/lF5HF9bvEF8FabDg=:" + ); + let h = vec![("Content-Digest".to_string(), content_digest(body))]; + assert!(content_digest_matches(&h, body)); + assert!(!content_digest_matches(&h, b"other")); + assert!(!content_digest_matches(&[], body)); + } +} diff --git a/crates/agentpin/src/jwt.rs b/crates/agentpin/src/jwt.rs index 84a27ad..0bc20d3 100644 --- a/crates/agentpin/src/jwt.rs +++ b/crates/agentpin/src/jwt.rs @@ -114,6 +114,15 @@ pub fn validate_claims(payload: &JwtPayload) -> Result<(), Error> { )); } } + if let Some(ref cnf) = payload.cnf { + // A base64url SHA-256 thumbprint: 43 characters, 32 bytes. + let ok = cnf.jkt.len() == 43 && base64url_decode(&cnf.jkt).is_ok_and(|b| b.len() == 32); + if !ok { + return Err(Error::MalformedCredential( + "cnf.jkt must be a base64url SHA-256 JWK thumbprint".to_string(), + )); + } + } if payload.agentpin_version != CREDENTIAL_VERSION { return Err(Error::MalformedCredential(format!( "Unsupported agentpin_version '{}'", @@ -172,6 +181,7 @@ mod tests { constraints: None, delegation_chain: None, nonce: None, + cnf: None, }; let jwt = encode_jwt(&header, &payload, signing_key).unwrap(); (jwt, header, payload) @@ -225,6 +235,7 @@ mod tests { constraints: None, delegation_chain: None, nonce: None, + cnf: None, }; let jwt = encode_jwt(&header, &payload, &sk).unwrap(); @@ -257,6 +268,7 @@ mod tests { constraints: None, delegation_chain: None, nonce: None, + cnf: None, }; let jwt = encode_jwt(&header, &payload, &sk).unwrap(); diff --git a/crates/agentpin/src/lib.rs b/crates/agentpin/src/lib.rs index b43268b..3765103 100644 --- a/crates/agentpin/src/lib.rs +++ b/crates/agentpin/src/lib.rs @@ -30,3 +30,10 @@ pub mod resolver_local; // v0.3.0: DNS TXT cross-verification at `_agentpin.{domain}`. Parser/matcher // always available; the async fetcher lives behind the `dns` Cargo feature. pub mod dns; + +// v0.4.0: RFC 9421 HTTP Message Signatures and the Web Bot Auth profile +// (Ed25519 request signing, key directories, AgentPin identity binding). +pub mod httpsig; +#[cfg(feature = "fetch")] +pub mod resolver_wba; +pub mod wba; diff --git a/crates/agentpin/src/net.rs b/crates/agentpin/src/net.rs index 88787a0..aadfd18 100644 --- a/crates/agentpin/src/net.rs +++ b/crates/agentpin/src/net.rs @@ -129,6 +129,152 @@ pub async fn fetch_json_bounded(url: &str, opts: &FetchOptions) -> Result