1use std::sync::Arc;
4use std::time::Duration;
5
6use adk_core::{Clock, SystemClock};
7use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9
10use super::directory::{DirectoryCache, DirectoryCachePolicy, KeyDirectorySource};
11use super::keys::{RFC9421_TEST_KEY_X, verify_ed25519};
12use super::message::{ComponentId, RequestHead, SignatureInput};
13use super::structured::{BareItem, Dictionary, Item, ListEntry};
14use super::{
15 SIGNATURE, SIGNATURE_AGENT, SIGNATURE_INPUT, WEB_BOT_AUTH_TAG, WebBotAuthError, combined_field,
16};
17
18const MAX_SIGNATURES: usize = 8;
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(rename_all = "camelCase")]
44pub struct VerifiedRequester {
45 pub id: String,
47 pub directory_origin: String,
49 pub key_thumbprint: String,
51 pub created: DateTime<Utc>,
53 pub expires: DateTime<Utc>,
55}
56
57impl VerifiedRequester {
58 pub fn new(
60 directory_origin: impl Into<String>,
61 key_thumbprint: impl Into<String>,
62 created: DateTime<Utc>,
63 expires: DateTime<Utc>,
64 ) -> Self {
65 let directory_origin = directory_origin.into();
66 let key_thumbprint = key_thumbprint.into();
67 Self {
68 id: format!("wba:{directory_origin}#{key_thumbprint}"),
69 directory_origin,
70 key_thumbprint,
71 created,
72 expires,
73 }
74 }
75}
76
77#[derive(Debug)]
123pub struct HttpSignatureVerifier {
124 cache: DirectoryCache,
125 clock: Arc<dyn Clock>,
126 max_skew: Duration,
127 max_lifetime: Option<Duration>,
128 required: Vec<ComponentId>,
129 default_scheme: String,
130 allow_test_keys: bool,
131}
132
133impl HttpSignatureVerifier {
134 pub fn builder(source: Arc<dyn KeyDirectorySource>) -> HttpSignatureVerifierBuilder {
136 HttpSignatureVerifierBuilder {
137 source,
138 clock: Arc::new(SystemClock),
139 cache_policy: DirectoryCachePolicy::default(),
140 max_skew: Duration::from_secs(60),
141 max_lifetime: Some(Duration::from_secs(24 * 60 * 60)),
142 required: Vec::new(),
143 default_scheme: "https".to_string(),
144 allow_test_keys: false,
145 }
146 }
147
148 pub async fn verify_request<B>(
155 &self,
156 request: &http::Request<B>,
157 ) -> Result<Option<VerifiedRequester>, WebBotAuthError> {
158 self.verify(RequestHead::from_request(request).with_default_scheme(&self.default_scheme))
159 .await
160 }
161
162 pub async fn verify(
172 &self,
173 head: RequestHead<'_>,
174 ) -> Result<Option<VerifiedRequester>, WebBotAuthError> {
175 let headers = head.headers();
176 let combined = |name: &str| combined_field(headers, name);
177 let inputs = combined(SIGNATURE_INPUT)?;
178 let signatures = combined(SIGNATURE)?;
179 let (inputs, signatures) = match (inputs, signatures) {
180 (None, None) => return Ok(None),
181 (Some(inputs), Some(signatures)) => (inputs, signatures),
182 (Some(_), None) | (None, Some(_)) => {
183 return Err(WebBotAuthError::MalformedField {
184 field: SIGNATURE.to_string(),
185 reason: "Signature and Signature-Input must appear together".into(),
186 });
187 }
188 };
189 let inputs = SignatureInput::parse_field(&inputs)?;
190 let signatures = Dictionary::parse_unique(&signatures).map_err(|e| {
191 WebBotAuthError::MalformedField { field: SIGNATURE.to_string(), reason: e.to_string() }
192 })?;
193 let agent_field = combined(SIGNATURE_AGENT)?;
194 let tagged: Vec<_> = inputs
195 .iter()
196 .filter(|(_, input)| input.tag() == Some(WEB_BOT_AUTH_TAG))
197 .take(MAX_SIGNATURES)
198 .collect();
199 if tagged.is_empty() {
200 return Ok(None);
201 }
202 let now = self.clock.now().timestamp();
203 let mut first_error = None;
204 for (label, input) in tagged {
205 let signature = match signatures.get(label) {
206 Some(ListEntry::Item(Item {
207 bare_item: BareItem::ByteSequence(bytes), ..
208 })) => bytes.as_slice(),
209 Some(_) | None => {
210 first_error.get_or_insert(WebBotAuthError::MalformedField {
211 field: SIGNATURE.to_string(),
212 reason: format!(
213 "no byte-sequence member `{label}` matches Signature-Input"
214 ),
215 });
216 continue;
217 }
218 };
219 match self.verify_one(&head, label, input, signature, agent_field.as_deref(), now).await
220 {
221 Ok(requester) => {
222 tracing::debug!(requester.id = %requester.id, signature.label = %label, "web bot auth signature verified");
223 return Ok(Some(requester));
224 }
225 Err(error) => {
226 tracing::debug!(signature.label = %label, error = %error, "web bot auth signature rejected");
227 first_error.get_or_insert(error);
228 }
229 }
230 }
231 Err(first_error.unwrap_or_else(|| WebBotAuthError::MalformedField {
232 field: SIGNATURE.to_string(),
233 reason: "no signature could be checked".into(),
234 }))
235 }
236
237 async fn verify_one(
238 &self,
239 head: &RequestHead<'_>,
240 label: &str,
241 input: &SignatureInput,
242 signature: &[u8],
243 agent_field: Option<&str>,
244 now: i64,
245 ) -> Result<VerifiedRequester, WebBotAuthError> {
246 let invalid = |parameter: &str, reason: &str| WebBotAuthError::InvalidParameter {
247 label: label.to_string(),
248 parameter: parameter.to_string(),
249 reason: reason.to_string(),
250 };
251 if let Some(alg) = input.params.get("alg")
252 && alg.as_str() != Some("ed25519")
253 {
254 return Err(WebBotAuthError::UnsupportedAlgorithm {
255 label: label.to_string(),
256 alg: alg.serialize().unwrap_or_default(),
257 });
258 }
259 let created =
260 input.created().ok_or_else(|| invalid("created", "missing or not an integer"))?;
261 let expires =
262 input.expires().ok_or_else(|| invalid("expires", "missing or not an integer"))?;
263 let keyid = input.keyid().ok_or_else(|| invalid("keyid", "missing or not a string"))?;
264 if expires < created {
265 return Err(invalid("expires", "precedes created"));
266 }
267
268 let covers_target = input.components.iter().any(|c| {
269 (c.name() == "@authority" || c.name() == "@target-uri") && c.params().is_empty()
270 });
271 if !covers_target {
272 return Err(WebBotAuthError::MissingComponent {
273 label: label.to_string(),
274 component: "@authority or @target-uri".into(),
275 });
276 }
277 if let Some(missing) = self.required.iter().find(|c| !input.covers(c)) {
278 return Err(WebBotAuthError::MissingComponent {
279 label: label.to_string(),
280 component: missing.serialize().unwrap_or_else(|_| missing.name().to_string()),
281 });
282 }
283 let agent = agent_component(label, input)?;
284
285 let skew = i64::try_from(self.max_skew.as_secs()).unwrap_or(i64::MAX);
286 if created > now.saturating_add(skew) {
287 return Err(WebBotAuthError::NotYetValid { label: label.to_string(), created, now });
288 }
289 if now > expires.saturating_add(skew) {
290 return Err(WebBotAuthError::Expired { label: label.to_string(), expires, now });
291 }
292 if let Some(max) = self.max_lifetime
293 && (expires - created).unsigned_abs() > max.as_secs()
294 {
295 return Err(WebBotAuthError::LifetimeTooLong {
296 label: label.to_string(),
297 lifetime_secs: expires - created,
298 max_secs: max.as_secs(),
299 });
300 }
301 if signature.len() != 64 {
302 return Err(WebBotAuthError::BadSignature { label: label.to_string() });
303 }
304
305 let origin = agent_origin(label, agent, agent_field)?;
306 let base = head.signature_base(input)?;
308 let key = self.cache.key(&origin, keyid).await?;
309 if !self.allow_test_keys && key.x == RFC9421_TEST_KEY_X {
310 return Err(WebBotAuthError::TestKey { keyid: keyid.to_string() });
311 }
312 if !key.is_current(now) {
313 return Err(WebBotAuthError::KeyNotCurrent { origin, keyid: keyid.to_string() });
314 }
315 let public_key = key.public_key()?;
316 if !verify_ed25519(&public_key, base.as_bytes(), signature) {
317 return Err(WebBotAuthError::BadSignature { label: label.to_string() });
318 }
319 let timestamp = |value: i64, parameter: &str| {
320 DateTime::from_timestamp(value, 0).ok_or_else(|| invalid(parameter, "out of range"))
321 };
322 Ok(VerifiedRequester::new(
323 origin,
324 keyid,
325 timestamp(created, "created")?,
326 timestamp(expires, "expires")?,
327 ))
328 }
329}
330
331fn agent_component<'a>(
334 label: &str,
335 input: &'a SignatureInput,
336) -> Result<&'a ComponentId, WebBotAuthError> {
337 let covered: Vec<_> = input.components.iter().filter(|c| c.name() == SIGNATURE_AGENT).collect();
338 let chosen = match covered.as_slice() {
339 [only] => Some(*only),
340 _ => covered
341 .iter()
342 .copied()
343 .find(|c| c.params().get("key").and_then(BareItem::as_str) == Some(label)),
344 };
345 chosen.ok_or_else(|| WebBotAuthError::MissingComponent {
346 label: label.to_string(),
347 component: format!("\"signature-agent\";key=\"{label}\""),
348 })
349}
350
351fn agent_origin(
353 label: &str,
354 component: &ComponentId,
355 field: Option<&str>,
356) -> Result<String, WebBotAuthError> {
357 let unusable = |reason: String| WebBotAuthError::InvalidSignatureAgent {
358 label: label.to_string(),
359 reason,
360 };
361 let field = field.ok_or_else(|| unusable("the request has no Signature-Agent field".into()))?;
362 let malformed = |e: super::structured::StructuredFieldError| WebBotAuthError::MalformedField {
363 field: SIGNATURE_AGENT.to_string(),
364 reason: e.to_string(),
365 };
366 let member = match component.params().get("key") {
367 Some(BareItem::String(key)) => {
368 match Dictionary::parse(field).map_err(malformed)?.get(key) {
369 Some(ListEntry::Item(item)) => item.clone(),
370 Some(ListEntry::InnerList(_)) => {
371 return Err(unusable(format!("member `{key}` is not a string")));
372 }
373 None => return Err(unusable(format!("the field has no member `{key}`"))),
374 }
375 }
376 Some(_) => return Err(unusable("the `key` parameter is not a string".into())),
377 None => Item::parse(field).map_err(malformed)?,
379 };
380 let value =
381 member.bare_item.as_str().ok_or_else(|| unusable("the member is not a string".into()))?;
382 match member.params.get("type") {
383 None => {}
384 Some(kind) if kind.as_token() == Some("directory") => {}
385 Some(kind) => {
386 return Err(WebBotAuthError::UnsupportedDiscovery {
387 label: label.to_string(),
388 kind: kind.serialize().unwrap_or_default(),
389 });
390 }
391 }
392 let url = reqwest::Url::parse(value).map_err(|e| unusable(format!("`{value}`: {e}")))?;
393 let is_origin = matches!(url.scheme(), "https" | "http")
394 && url.host_str().is_some()
395 && url.username().is_empty()
396 && url.password().is_none()
397 && url.path() == "/"
398 && url.query().is_none()
399 && url.fragment().is_none();
400 if !is_origin {
401 return Err(unusable(format!("`{value}` is not an http(s) origin")));
402 }
403 Ok(url.origin().ascii_serialization())
404}
405
406pub struct HttpSignatureVerifierBuilder {
408 source: Arc<dyn KeyDirectorySource>,
409 clock: Arc<dyn Clock>,
410 cache_policy: DirectoryCachePolicy,
411 max_skew: Duration,
412 max_lifetime: Option<Duration>,
413 required: Vec<ComponentId>,
414 default_scheme: String,
415 allow_test_keys: bool,
416}
417
418impl std::fmt::Debug for HttpSignatureVerifierBuilder {
419 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
420 f.debug_struct("HttpSignatureVerifierBuilder")
421 .field("max_skew", &self.max_skew)
422 .field("max_lifetime", &self.max_lifetime)
423 .finish_non_exhaustive()
424 }
425}
426
427impl HttpSignatureVerifierBuilder {
428 pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
430 self.clock = clock;
431 self
432 }
433
434 pub fn max_skew(mut self, skew: Duration) -> Self {
436 self.max_skew = skew;
437 self
438 }
439
440 pub fn max_signature_lifetime(mut self, lifetime: Option<Duration>) -> Self {
443 self.max_lifetime = lifetime;
444 self
445 }
446
447 pub fn require_component(mut self, component: ComponentId) -> Self {
449 self.required.push(component);
450 self
451 }
452
453 pub fn cache_policy(mut self, policy: DirectoryCachePolicy) -> Self {
455 self.cache_policy = policy;
456 self
457 }
458
459 pub fn default_scheme(mut self, scheme: impl Into<String>) -> Self {
461 self.default_scheme = scheme.into();
462 self
463 }
464
465 pub fn allow_test_keys(mut self, allow: bool) -> Self {
468 self.allow_test_keys = allow;
469 self
470 }
471
472 pub fn build(self) -> HttpSignatureVerifier {
474 HttpSignatureVerifier {
475 cache: DirectoryCache::new(self.source, self.cache_policy, Arc::clone(&self.clock)),
476 clock: self.clock,
477 max_skew: self.max_skew,
478 max_lifetime: self.max_lifetime,
479 required: self.required,
480 default_scheme: self.default_scheme,
481 allow_test_keys: self.allow_test_keys,
482 }
483 }
484}
485
486#[cfg(test)]
487mod tests {
488 use super::*;
489 use crate::web_bot_auth::InMemoryKeyDirectorySource;
490
491 #[test]
492 fn builder_defaults_match_spec_3_5_section_7_3() {
493 let verifier =
494 HttpSignatureVerifier::builder(Arc::new(InMemoryKeyDirectorySource::new())).build();
495 assert_eq!(verifier.max_skew, Duration::from_secs(60));
496 assert_eq!(verifier.max_lifetime, Some(Duration::from_secs(86_400)));
497 assert_eq!(verifier.default_scheme, "https");
498 assert!(!verifier.allow_test_keys);
499 assert!(verifier.required.is_empty());
500 }
501}