Skip to main content

adk_auth/web_bot_auth/
signer.rs

1//! Signs outgoing requests with Web Bot Auth. Spec 3.5 §7.3 "Outbound".
2
3use std::sync::Arc;
4use std::time::Duration;
5
6use adk_core::{Clock, SystemClock};
7use base64::Engine;
8use base64::engine::general_purpose::STANDARD;
9use http::header::HeaderValue;
10use http::{HeaderMap, Method, Uri};
11
12use super::keys::Ed25519SigningKey;
13use super::message::{ComponentId, RequestHead, SignatureInput};
14use super::structured::{BareItem, Dictionary, Item, ListEntry};
15use super::{
16    SIGNATURE, SIGNATURE_AGENT, SIGNATURE_INPUT, WEB_BOT_AUTH_TAG, WebBotAuthError, combined_field,
17};
18
19/// The time window and nonce of one signature.
20///
21/// [`HttpSignatureSigner`] derives them from its clock, lifetime and a random nonce;
22/// [`sign_head_with`](HttpSignatureSigner::sign_head_with) takes them explicitly, for test
23/// vectors and callers that issue their own nonces.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct SigningParams {
26    /// `created`, Unix seconds.
27    pub created: i64,
28    /// `expires`, Unix seconds.
29    pub expires: i64,
30    /// `nonce`, when one is sent.
31    pub nonce: Option<String>,
32}
33
34/// Signs outgoing requests as a Web Bot Auth agent (draft-ietf-webbotauth-httpsig-protocol-00
35/// §5.2), so a site's crawls, `web_fetch` calls and verifier requests identify it.
36/// Spec 3.5 §7.3 "Outbound".
37///
38/// Each signature covers `@authority`, `@method`, `@path` and `@query` by default (the draft's
39/// required `@authority` narrowed to one request, §5.2) and the signer's `Signature-Agent`
40/// member, and carries `created`, `keyid` (the key's JWK thumbprint), `alg="ed25519"`,
41/// `expires` (five minutes later by default), a random `nonce` and `tag="web-bot-auth"`, in
42/// that order. The `Signature-Agent` value is the origin whose
43/// `/.well-known/http-message-signatures-directory` publishes the key
44/// ([`KeyDirectory`](super::KeyDirectory)).
45///
46/// # Example
47///
48/// ```rust
49/// use std::sync::Arc;
50/// use adk_auth::web_bot_auth::{Ed25519SigningKey, HttpSignatureSigner};
51///
52/// let key = Arc::new(Ed25519SigningKey::generate().unwrap());
53/// let signer = HttpSignatureSigner::builder(key, "https://crawler.example").build().unwrap();
54///
55/// let mut request = reqwest::Client::new().get("https://news.example/feed").build().unwrap();
56/// signer.sign_reqwest(&mut request).unwrap();
57/// assert_eq!(request.headers()["signature-agent"], "sig1=\"https://crawler.example\"");
58/// assert!(request.headers()["signature-input"].to_str().unwrap().contains("tag=\"web-bot-auth\""));
59/// ```
60pub struct HttpSignatureSigner {
61    key: Arc<Ed25519SigningKey>,
62    signature_agent: String,
63    label: String,
64    agent_member: String,
65    components: Vec<ComponentId>,
66    lifetime: Duration,
67    nonce: bool,
68    clock: Arc<dyn Clock>,
69}
70
71impl std::fmt::Debug for HttpSignatureSigner {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        f.debug_struct("HttpSignatureSigner")
74            .field("key", &self.key)
75            .field("signature_agent", &self.signature_agent)
76            .field("label", &self.label)
77            .finish_non_exhaustive()
78    }
79}
80
81impl HttpSignatureSigner {
82    /// Starts a builder for `key`, publishing its directory at the `signature_agent` origin.
83    pub fn builder(
84        key: Arc<Ed25519SigningKey>,
85        signature_agent: impl Into<String>,
86    ) -> HttpSignatureSignerBuilder {
87        HttpSignatureSignerBuilder {
88            key,
89            signature_agent: signature_agent.into(),
90            label: "sig1".to_string(),
91            agent_member: None,
92            components: vec![
93                ComponentId::new("@authority"),
94                ComponentId::new("@method"),
95                ComponentId::new("@path"),
96                ComponentId::new("@query"),
97            ],
98            lifetime: Duration::from_secs(300),
99            nonce: true,
100            clock: Arc::new(SystemClock),
101        }
102    }
103
104    /// The signing key's thumbprint, sent as `keyid`.
105    pub fn keyid(&self) -> &str {
106        self.key.thumbprint()
107    }
108
109    /// Signs an [`http::Request`].
110    ///
111    /// # Errors
112    ///
113    /// As [`sign_head`](Self::sign_head).
114    pub fn sign_request<B>(&self, request: &mut http::Request<B>) -> Result<(), WebBotAuthError> {
115        let method = request.method().clone();
116        let uri = request.uri().clone();
117        self.sign_head(&method, &uri, request.headers_mut())
118    }
119
120    /// Signs a [`reqwest::Request`] before it is sent.
121    ///
122    /// # Errors
123    ///
124    /// As [`sign_head`](Self::sign_head).
125    pub fn sign_reqwest(&self, request: &mut reqwest::Request) -> Result<(), WebBotAuthError> {
126        let method = request.method().clone();
127        let uri: Uri = request.url().as_str().parse().map_err(|e| {
128            WebBotAuthError::SignatureBase { reason: format!("the request URL is not a URI: {e}") }
129        })?;
130        self.sign_head(&method, &uri, request.headers_mut())
131    }
132
133    /// Signs a request given its method, absolute URI and headers, adding the
134    /// `Signature-Agent`, `Signature-Input` and `Signature` fields.
135    ///
136    /// # Errors
137    ///
138    /// Returns [`WebBotAuthError::SignatureBase`] when a covered component is absent from the
139    /// request, and [`WebBotAuthError::MalformedField`] when an existing signature field cannot
140    /// be extended.
141    pub fn sign_head(
142        &self,
143        method: &Method,
144        uri: &Uri,
145        headers: &mut HeaderMap,
146    ) -> Result<(), WebBotAuthError> {
147        let created = self.clock.now().timestamp();
148        let lifetime = i64::try_from(self.lifetime.as_secs()).unwrap_or(i64::MAX);
149        let nonce = self.nonce.then(|| {
150            let mut bytes = [0u8; 32];
151            // A failed fill leaves a zero nonce; the signature stays valid, only less unique.
152            let _ = aws_lc_rs::rand::fill(&mut bytes);
153            STANDARD.encode(bytes)
154        });
155        self.sign_head_with(
156            method,
157            uri,
158            headers,
159            SigningParams { created, expires: created.saturating_add(lifetime), nonce },
160        )
161    }
162
163    /// Signs a request with an explicit time window and nonce.
164    ///
165    /// # Errors
166    ///
167    /// As [`sign_head`](Self::sign_head).
168    pub fn sign_head_with(
169        &self,
170        method: &Method,
171        uri: &Uri,
172        headers: &mut HeaderMap,
173        params: SigningParams,
174    ) -> Result<(), WebBotAuthError> {
175        let malformed = |field: &str, reason: String| WebBotAuthError::MalformedField {
176            field: field.to_string(),
177            reason,
178        };
179        let field = |headers: &HeaderMap, name: &str| -> Result<String, WebBotAuthError> {
180            Ok(combined_field(headers, name)?.unwrap_or_default())
181        };
182        let mut agents = Dictionary::parse(&field(headers, SIGNATURE_AGENT)?)
183            .map_err(|e| malformed(SIGNATURE_AGENT, e.to_string()))?;
184        agents.insert(
185            self.agent_member.clone(),
186            ListEntry::Item(Item::new(BareItem::String(self.signature_agent.clone()))),
187        );
188        set_field(headers, SIGNATURE_AGENT, &agents)?;
189
190        let mut components = self.components.clone();
191        components.push(ComponentId::signature_agent(self.agent_member.clone()));
192        let mut input = SignatureInput::new(components);
193        input.params.insert("created", BareItem::Integer(params.created));
194        input.params.insert("keyid", BareItem::String(self.key.thumbprint().to_string()));
195        input.params.insert("alg", BareItem::String("ed25519".into()));
196        input.params.insert("expires", BareItem::Integer(params.expires));
197        if let Some(nonce) = params.nonce {
198            input.params.insert("nonce", BareItem::String(nonce));
199        }
200        input.params.insert("tag", BareItem::String(WEB_BOT_AUTH_TAG.into()));
201
202        let base = RequestHead::new(method, uri, headers).signature_base(&input)?;
203        let signature = self.key.sign(base.as_bytes());
204
205        let mut inputs = Dictionary::parse(&field(headers, SIGNATURE_INPUT)?)
206            .map_err(|e| malformed(SIGNATURE_INPUT, e.to_string()))?;
207        let mut signatures = Dictionary::parse(&field(headers, SIGNATURE)?)
208            .map_err(|e| malformed(SIGNATURE, e.to_string()))?;
209        inputs.insert(self.label.clone(), ListEntry::InnerList(input.to_inner_list()));
210        signatures.insert(
211            self.label.clone(),
212            ListEntry::Item(Item::new(BareItem::ByteSequence(signature.to_vec()))),
213        );
214        set_field(headers, SIGNATURE_INPUT, &inputs)?;
215        set_field(headers, SIGNATURE, &signatures)
216    }
217}
218
219fn set_field(
220    headers: &mut HeaderMap,
221    name: &'static str,
222    value: &Dictionary,
223) -> Result<(), WebBotAuthError> {
224    let invalid =
225        |reason: String| WebBotAuthError::MalformedField { field: name.to_string(), reason };
226    let serialized = value.serialize().map_err(|e| invalid(e.to_string()))?;
227    let value = HeaderValue::from_str(&serialized).map_err(|e| invalid(e.to_string()))?;
228    headers.insert(name, value);
229    Ok(())
230}
231
232/// Builds an [`HttpSignatureSigner`].
233pub struct HttpSignatureSignerBuilder {
234    key: Arc<Ed25519SigningKey>,
235    signature_agent: String,
236    label: String,
237    agent_member: Option<String>,
238    components: Vec<ComponentId>,
239    lifetime: Duration,
240    nonce: bool,
241    clock: Arc<dyn Clock>,
242}
243
244impl std::fmt::Debug for HttpSignatureSignerBuilder {
245    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246        f.debug_struct("HttpSignatureSignerBuilder")
247            .field("signature_agent", &self.signature_agent)
248            .field("label", &self.label)
249            .finish_non_exhaustive()
250    }
251}
252
253impl HttpSignatureSignerBuilder {
254    /// Sets the signature label. Default `sig1`.
255    pub fn label(mut self, label: impl Into<String>) -> Self {
256        self.label = label.into();
257        self
258    }
259
260    /// Sets the `Signature-Agent` member key. Default: the label.
261    pub fn agent_member(mut self, member: impl Into<String>) -> Self {
262        self.agent_member = Some(member.into());
263        self
264    }
265
266    /// Replaces the covered components; the signer's own `Signature-Agent` member is always
267    /// added. Include `@authority` or `@target-uri`, as the draft requires (§5.2). An outer
268    /// signer covering another signature also covers its `signature-input`, `signature` and
269    /// `signature-agent` members (draft §5.2.2).
270    pub fn components(mut self, components: Vec<ComponentId>) -> Self {
271        self.components = components;
272        self
273    }
274
275    /// Sets how long each signature is valid. Default 5 minutes; the draft recommends at most
276    /// 24 hours (§5.2).
277    pub fn lifetime(mut self, lifetime: Duration) -> Self {
278        self.lifetime = lifetime;
279        self
280    }
281
282    /// Sends a random `nonce` with each signature. Default on.
283    pub fn nonce(mut self, nonce: bool) -> Self {
284        self.nonce = nonce;
285        self
286    }
287
288    /// Sets the clock that `created` is read from.
289    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
290        self.clock = clock;
291        self
292    }
293
294    /// Builds the signer.
295    ///
296    /// # Errors
297    ///
298    /// Returns [`WebBotAuthError::InvalidConfig`] when the `Signature-Agent` value is not an
299    /// http(s) origin, the label or member key is not a structured-field key, or the components
300    /// do not include `@authority` or `@target-uri`.
301    pub fn build(self) -> Result<HttpSignatureSigner, WebBotAuthError> {
302        let invalid = |reason: String| WebBotAuthError::InvalidConfig { reason };
303        let url = reqwest::Url::parse(&self.signature_agent)
304            .map_err(|e| invalid(format!("Signature-Agent `{}`: {e}", self.signature_agent)))?;
305        if !matches!(url.scheme(), "https" | "http")
306            || url.host_str().is_none()
307            || url.path() != "/"
308            || url.query().is_some()
309            || url.fragment().is_some()
310        {
311            return Err(invalid(format!(
312                "Signature-Agent `{}` must be an origin such as https://bot.example",
313                self.signature_agent
314            )));
315        }
316        let agent_member = self.agent_member.unwrap_or_else(|| self.label.clone());
317        for key in [&self.label, &agent_member] {
318            let mut probe = Dictionary::new();
319            probe.insert(key.clone(), ListEntry::Item(Item::new(BareItem::Integer(1))));
320            probe.serialize().map_err(|_| {
321                invalid(format!("`{key}` is not a structured-field key (lowercase, digits, _-.*)"))
322            })?;
323        }
324        if !self.components.iter().any(|c| {
325            (c.name() == "@authority" || c.name() == "@target-uri") && c.params().is_empty()
326        }) {
327            return Err(invalid("the components must include @authority or @target-uri".into()));
328        }
329        let own_member = ComponentId::signature_agent(agent_member.clone());
330        if self.components.iter().any(|c| c.same_as(&own_member)) {
331            return Err(invalid(format!(
332                "the Signature-Agent member `{agent_member}` is covered automatically"
333            )));
334        }
335        Ok(HttpSignatureSigner {
336            key: self.key,
337            signature_agent: self.signature_agent,
338            label: self.label,
339            agent_member,
340            components: self.components,
341            lifetime: self.lifetime,
342            nonce: self.nonce,
343            clock: self.clock,
344        })
345    }
346}