actpub-httpsig 0.2.3

Dual-stack HTTP Message Signatures (Cavage draft-12 + RFC 9421) with RSA & Ed25519 via aws-lc-rs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Parsing and emitting the Cavage `Signature:` header value.
//!
//! The header is a comma-separated list of `name=value` pairs where
//! string-typed parameters (`keyId`, `algorithm`, `headers`, `signature`)
//! are double-quoted and numeric ones (`created`, `expires`) appear
//! without quotes. Parameter order is not significant.

use crate::cavage::canonical::CavageHeaderSet;
use crate::error::Error;

/// Name of the `Signature:` HTTP header.
pub const SIGNATURE_HEADER: &str = "signature";

/// Parsed `Signature:` header parameters.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CavageHeaderParams {
    /// Reference to the public key to verify against.
    pub key_id: String,
    /// Algorithm hint; `None` means "detect from the key itself".
    pub algorithm: Option<String>,
    /// Which headers participate in the signature base string.
    pub headers: CavageHeaderSet,
    /// Base64-encoded signature bytes.
    pub signature: String,
    /// Optional `(created)` timestamp in seconds since the UNIX epoch.
    pub created: Option<i64>,
    /// Optional `(expires)` timestamp in seconds since the UNIX epoch.
    pub expires: Option<i64>,
}

impl CavageHeaderParams {
    /// Parses the raw `Signature:` header value.
    ///
    /// # Errors
    ///
    /// Returns [`Error::MalformedSignatureHeader`] if the parameter list
    /// cannot be decoded, and [`Error::MissingSignatureParameter`] if
    /// `keyId` or `signature` is absent.
    pub fn parse(raw: &str) -> Result<Self, Error> {
        let mut key_id = None;
        let mut algorithm = None;
        let mut headers_field: Option<String> = None;
        let mut signature = None;
        let mut created = None;
        let mut expires = None;

        for pair in split_top_level_commas(raw) {
            let pair = pair.trim();
            if pair.is_empty() {
                continue;
            }
            let (name, value) = split_once_trim(pair, '=').ok_or_else(|| {
                Error::MalformedSignatureHeader(format!("missing `=` in `{pair}`"))
            })?;
            let value = unquote(value)?;
            // Draft §2.1 says "all parameters SHALL appear at most
            // once". Silently overwriting a repeated `keyId` (or any
            // other parameter) is a **parameter-pollution** bug: a
            // peer — or an attacker on the path with trivial header
            // injection — can append a second `keyId` that wins the
            // `=` assignment and reroutes the verifier to a key they
            // control. Fail the parse whenever any parameter we
            // actually consume appears more than once.
            match name {
                "keyId" | "keyid" => {
                    reject_if_set(key_id.as_ref(), "keyId")?;
                    key_id = Some(value.into_owned());
                }
                "algorithm" => {
                    reject_if_set(algorithm.as_ref(), "algorithm")?;
                    algorithm = Some(value.into_owned());
                }
                "headers" => {
                    reject_if_set(headers_field.as_ref(), "headers")?;
                    headers_field = Some(value.into_owned());
                }
                "signature" => {
                    reject_if_set(signature.as_ref(), "signature")?;
                    signature = Some(value.into_owned());
                }
                "created" => {
                    reject_if_set(created.as_ref(), "created")?;
                    created = Some(parse_i64_param("created", &value)?);
                }
                "expires" => {
                    reject_if_set(expires.as_ref(), "expires")?;
                    expires = Some(parse_i64_param("expires", &value)?);
                }
                _ => {
                    // Unknown parameters are ignored per draft §2.1.
                }
            }
        }

        let key_id = key_id.ok_or(Error::MissingSignatureParameter("keyId"))?;
        let signature = signature.ok_or(Error::MissingSignatureParameter("signature"))?;

        // Per draft §2.1.3: "If not specified, [headers] defaults to
        // the single value `(created)`. If the `created` signature
        // parameter is not provided, this parameter defaults to
        // the single value `date`."
        //
        // Fediverse actors always set `headers` explicitly, so the
        // defaulting branch is a pure fallback for spec-correctness.
        let headers = headers_field.map_or_else(
            || {
                if created.is_some() {
                    CavageHeaderSet::new(["(created)"])
                } else {
                    CavageHeaderSet::new(["date"])
                }
            },
            |v| CavageHeaderSet::new(v.split_ascii_whitespace().map(str::to_owned)),
        );

        Ok(Self {
            key_id,
            algorithm,
            headers,
            signature,
            created,
            expires,
        })
    }

    /// Serialises back into a `Signature:` header value.
    ///
    /// String-valued parameters (`keyId`, `algorithm`, `headers`,
    /// `signature`) are quoted and any `\` or `"` character inside
    /// them is backslash-escaped per the Cavage quoted-string grammar.
    #[must_use]
    #[allow(
        clippy::expect_used,
        reason = "writing to an owned `String` via `core::fmt::Write` is infallible; the `Result` only exists to satisfy the trait"
    )]
    pub fn to_header_value(&self) -> String {
        use core::fmt::Write as _;
        let mut out = String::new();
        let infallible = "writing to an owned String is infallible";
        write!(out, r#"keyId="{}""#, escape_quoted(&self.key_id)).expect(infallible);
        if let Some(alg) = &self.algorithm {
            write!(out, r#",algorithm="{}""#, escape_quoted(alg)).expect(infallible);
        }
        write!(
            out,
            r#",headers="{}""#,
            escape_quoted(&self.headers.join_spaces()),
        )
        .expect(infallible);
        if let Some(c) = self.created {
            write!(out, ",created={c}").expect(infallible);
        }
        if let Some(e) = self.expires {
            write!(out, ",expires={e}").expect(infallible);
        }
        write!(out, r#",signature="{}""#, escape_quoted(&self.signature)).expect(infallible);
        out
    }
}

/// Applies the Cavage quoted-string escape rules: `\` → `\\` and
/// `"` → `\"`. All other bytes pass through unchanged.
fn escape_quoted(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len());
    for c in raw.chars() {
        if c == '\\' || c == '"' {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

/// Splits the raw header on top-level commas, skipping commas inside
/// double-quoted regions so that `signature="a,b,c"` does not break.
///
/// The scanner also honours the quoted-string escape sequence `\X`,
/// treating the next character as literal content. Without this a
/// payload containing `\"` would prematurely terminate the quoted
/// region and let an attacker inject additional parameter pairs.
fn split_top_level_commas(raw: &str) -> impl Iterator<Item = &str> {
    let mut parts = Vec::new();
    let mut start = 0;
    let mut in_quotes = false;
    let mut escaped = false;
    for (i, c) in raw.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        match c {
            '\\' if in_quotes => escaped = true,
            '"' => in_quotes = !in_quotes,
            ',' if !in_quotes => {
                parts.push(&raw[start..i]);
                start = i + 1;
            }
            _ => {}
        }
    }
    parts.push(&raw[start..]);
    parts.into_iter()
}

fn split_once_trim(s: &str, c: char) -> Option<(&str, &str)> {
    s.split_once(c).map(|(a, b)| (a.trim(), b.trim()))
}

/// Returns `Err` if `slot` is already `Some`, signalling a repeated
/// parameter. Extracted so the at-most-once check stays a single
/// flat branch per match arm instead of a deeply-nested `if`.
fn reject_if_set<T>(slot: Option<&T>, name: &'static str) -> Result<(), Error> {
    if slot.is_some() {
        return Err(Error::MalformedSignatureHeader(format!(
            "duplicate `{name}` parameter"
        )));
    }
    Ok(())
}

fn parse_i64_param(name: &'static str, value: &str) -> Result<i64, Error> {
    value.parse::<i64>().map_err(|_| {
        Error::MalformedSignatureHeader(format!("`{name}` is not an integer: `{value}`"))
    })
}

fn unquote(raw: &str) -> Result<std::borrow::Cow<'_, str>, Error> {
    if raw.len() < 2 || !raw.starts_with('"') || !raw.ends_with('"') {
        return Ok(std::borrow::Cow::Borrowed(raw));
    }
    let inner = &raw[1..raw.len() - 1];
    if !inner.contains('\\') {
        return Ok(std::borrow::Cow::Borrowed(inner));
    }
    Ok(std::borrow::Cow::Owned(unescape(inner)?))
}

/// Unescapes a quoted-string body: `\<X>` becomes `<X>` for any
/// `<X>`. A trailing lone backslash is an encoding error and is
/// signalled by [`Error::MalformedSignatureHeader`] via the caller
/// re-wrapping; `unquote` upgrades the result to `Cow::Owned` only
/// after confirming the escape sequence is well-formed.
fn unescape(inner: &str) -> Result<String, Error> {
    let mut out = String::with_capacity(inner.len());
    let mut chars = inner.chars();
    while let Some(c) = chars.next() {
        if c == '\\' {
            let next = chars.next().ok_or_else(|| {
                Error::MalformedSignatureHeader(
                    "quoted-string ends with a lone backslash".to_owned(),
                )
            })?;
            out.push(next);
        } else {
            out.push(c);
        }
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use super::*;

    const MASTODON_SAMPLE: &str = r#"keyId="https://mastodon.social/users/alice#main-key",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="Zm9v""#;

    #[test]
    fn parses_mastodon_style_header() {
        let params = CavageHeaderParams::parse(MASTODON_SAMPLE).expect("parse");
        assert_eq!(
            params.key_id,
            "https://mastodon.social/users/alice#main-key"
        );
        assert_eq!(params.algorithm.as_deref(), Some("rsa-sha256"));
        assert_eq!(params.headers.len(), 4);
        assert_eq!(params.signature, "Zm9v");
        assert_eq!(params.created, None);
        assert_eq!(params.expires, None);
    }

    #[test]
    fn header_roundtrips_through_serialisation() {
        let params = CavageHeaderParams::parse(MASTODON_SAMPLE).expect("parse");
        let emitted = params.to_header_value();
        let reparsed = CavageHeaderParams::parse(&emitted).expect("reparse");
        assert_eq!(reparsed, params);
    }

    #[test]
    fn missing_key_id_produces_specific_error() {
        let err =
            CavageHeaderParams::parse(r#"algorithm="rsa-sha256",headers="host",signature="Zm9v""#)
                .expect_err("missing keyId");
        assert!(matches!(err, Error::MissingSignatureParameter("keyId")));
    }

    #[test]
    fn missing_signature_produces_specific_error() {
        let err = CavageHeaderParams::parse(r#"keyId="foo",algorithm="rsa-sha256",headers="host""#)
            .expect_err("missing signature");
        assert!(matches!(err, Error::MissingSignatureParameter("signature")));
    }

    #[test]
    fn unquoted_parameters_are_tolerated() {
        // Some server implementations emit bare tokens for created/expires.
        let raw =
            r#"keyId="foo",headers="host",created=1700000000,expires=1700001000,signature="Zm9v""#;
        let params = CavageHeaderParams::parse(raw).expect("parse");
        assert_eq!(params.created, Some(1_700_000_000));
        assert_eq!(params.expires, Some(1_700_001_000));
    }

    #[test]
    fn unknown_parameters_are_silently_skipped() {
        let raw = r#"keyId="foo",headers="host",signature="Zm9v",future_thing="ignored""#;
        let params = CavageHeaderParams::parse(raw).expect("parse");
        assert_eq!(params.key_id, "foo");
    }

    #[test]
    fn commas_inside_quoted_signature_do_not_split_parameters() {
        let raw = r#"keyId="has,comma",headers="host",signature="ZmF,vo""#;
        let params = CavageHeaderParams::parse(raw).expect("parse");
        assert_eq!(params.key_id, "has,comma");
        assert_eq!(params.signature, "ZmF,vo");
    }

    #[test]
    fn missing_headers_parameter_with_created_defaults_to_created_pseudo() {
        // Per §2.1.3 the default `headers` value is `(created)` when
        // the `created` parameter is present.
        let raw = r#"keyId="k",created=1700000000,signature="Zm9v""#;
        let params = CavageHeaderParams::parse(raw).expect("parse");
        assert_eq!(params.headers.len(), 1);
        assert!(params.headers.iter().any(|h| h == "(created)"));
    }

    #[test]
    fn missing_headers_parameter_without_created_defaults_to_date() {
        // §2.1.3 falls back to `date` when both `headers` and
        // `created` are absent -- the Mastodon-compatible corner case.
        let raw = r#"keyId="k",signature="Zm9v""#;
        let params = CavageHeaderParams::parse(raw).expect("parse");
        assert_eq!(params.headers.len(), 1);
        assert!(params.headers.iter().any(|h| h == "date"));
    }

    #[test]
    fn escaped_double_quote_inside_quoted_string_survives_splitting() {
        // Without the escape-aware splitter this payload would split
        // early at the `"` inside `evil"`, dropping the `,attacker=`
        // trailer into a separate parameter.
        let raw = r#"keyId="legit\"evil",headers="host",signature="Zm9v""#;
        let params = CavageHeaderParams::parse(raw).expect("parse");
        assert_eq!(params.key_id, r#"legit"evil"#);
    }

    #[test]
    fn to_header_value_escapes_embedded_quote_and_backslash() {
        let raw = r#"keyId="legit\"evil\\trail",headers="host",signature="Zm9v""#;
        let params = CavageHeaderParams::parse(raw).expect("parse");
        let emitted = params.to_header_value();
        // Re-parsing must recover the same logical value.
        let reparsed = CavageHeaderParams::parse(&emitted).expect("reparse escaped");
        assert_eq!(reparsed.key_id, r#"legit"evil\trail"#);
        // And the escapes must actually be present on the wire.
        assert!(emitted.contains(r#"\""#));
        assert!(emitted.contains(r"\\"));
    }

    #[test]
    fn parameter_value_with_lone_trailing_backslash_is_rejected() {
        // A quoted value whose contents end in an unpaired backslash
        // is an encoding error: the parser has no way to know which
        // character the `\` was meant to escape.
        let raw = r#"keyId="abc\""#;
        let err = CavageHeaderParams::parse(raw).expect_err("malformed escape must fail");
        assert!(matches!(err, Error::MalformedSignatureHeader(_)));
    }

    #[test]
    fn malformed_escape_reports_error() {
        // A quoted value whose contents end in an unpaired backslash
        // is an encoding error: the parser has no way to know which
        // character the `\` was meant to escape.
        let raw = r#"keyId="abc\""#;
        let err = CavageHeaderParams::parse(raw).expect_err("malformed escape must fail");
        assert!(matches!(err, Error::MalformedSignatureHeader(_)));
    }

    #[test]
    fn duplicate_key_id_is_rejected() {
        // P2-N15 regression: accepting a repeated `keyId` and taking
        // the last value would let an attacker append a second
        // parameter that reroutes the verifier to their own key.
        // The draft mandates at-most-once, and we now enforce it.
        let raw = r#"keyId="https://victim.example/#k",keyId="https://attacker.example/#k",headers="host",signature="Zm9v""#;
        let err = CavageHeaderParams::parse(raw).expect_err("duplicate keyId must be rejected");
        assert!(
            matches!(err, Error::MalformedSignatureHeader(ref s) if s.contains("keyId")),
            "unexpected: {err:?}",
        );
    }

    #[test]
    fn duplicate_signature_is_rejected() {
        let raw = r#"keyId="k",headers="host",signature="Zm9v",signature="YmFy""#;
        let err = CavageHeaderParams::parse(raw).expect_err("duplicate signature must be rejected");
        assert!(matches!(err, Error::MalformedSignatureHeader(_)));
    }

    #[test]
    fn duplicate_algorithm_is_rejected() {
        let raw = r#"keyId="k",algorithm="rsa-sha256",algorithm="hs2019",headers="host",signature="Zm9v""#;
        let err = CavageHeaderParams::parse(raw).expect_err("duplicate algorithm must be rejected");
        assert!(matches!(err, Error::MalformedSignatureHeader(_)));
    }

    #[test]
    fn duplicate_created_is_rejected() {
        let raw =
            r#"keyId="k",created=1700000000,created=1700000001,headers="host",signature="Zm9v""#;
        let err = CavageHeaderParams::parse(raw).expect_err("duplicate created must be rejected");
        assert!(matches!(err, Error::MalformedSignatureHeader(_)));
    }
}