Skip to main content

instruction_md/
verify.rs

1//! Attestations: JWS/EdDSA author and delivery signatures (Ed25519, by `ring`). An author signature binds a
2//! version's authored digest; a delivery signature binds what one reader received — the delivered text's digest — and
3//! the resolution it came from (its manifest: the resolved artifact's format, status, document, dependencies and
4//! digest, never its body), with the author signature embedded so the chain is checked in one place.
5
6use std::time::{SystemTime, UNIX_EPOCH};
7
8use ring::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey};
9use serde_json::{Map, Value};
10
11use crate::digest::digest;
12use crate::js::{is_str, js_number, js_value};
13use crate::policy::authored_candidates;
14use crate::types::Object;
15
16/// Whether a text is, or holds, the bytes a digest claim names: itself, or served with its host's
17/// `host-integrations` block, which is outside the signed bytes (S34).
18fn signs(d: Option<&Value>, text: &[u8]) -> bool {
19    authored_candidates(text).iter().any(|t| is_str(d, &digest(t)))
20}
21
22/// A JSON Web Key (OKP / Ed25519 keys are what a registry publishes).
23pub type Jwk = Object;
24
25/// A verification's outcome: ok with the claims, or not ok with a stable code and the reason.
26#[derive(Clone, Debug, PartialEq)]
27pub struct VerifyResult {
28    pub ok: bool,
29    /// What happened, for a program to match on (one of [`VERIFY_CODES`]): `ok`, or why not.
30    pub code: &'static str,
31    /// The verified claims: the author attestation's, or the delivery attestation's.
32    pub claims: Option<Object>,
33    /// A verified delivery's embedded author attestation's claims ([`verify_delivery`] only).
34    pub author: Option<Object>,
35    /// For a person: why not (the TypeScript reference's wording); empty when ok.
36    pub reason: String,
37}
38
39/// Every [`VerifyResult::code`]:
40///
41/// | Code | When |
42/// |---|---|
43/// | `ok` | verified |
44/// | `malformed` | not a compact JWS, or a part that is not base64url JSON |
45/// | `unknown-key` | no key in the set is an Ed25519 JWK to try (an empty set, or none usable) |
46/// | `bad-algorithm` | the header's `alg` is not EdDSA |
47/// | `bad-signature` | no key in the set verifies the signature |
48/// | `unknown-format` | the `spec` claim is not `instruction/1` |
49/// | `typ-mismatch` | the `typ` claim (or the header's) is not the attestation expected (author, delivery) |
50/// | `expired` | the `exp` claim is past |
51/// | `digest-mismatch` | a digest is not the bytes': the authored bytes' (author), the delivered bytes' (delivery), or the resolved document's (the embedded author's) |
52/// | `doc-mismatch` | the author's `doc` is not the one expected, or the embedded author's doc or version is not the delivery's |
53/// | `unpinned-publisher` | the publisher (`pub`) is not the pinned one |
54/// | `audience-mismatch` | the delivery's `aud` is not this reader |
55/// | `manifest-invalid` | the delivery does not name its resolution (format instruction-resolved/1, document, dependencies, resolved_digest) |
56/// | `author-missing` | the delivery embeds no author signature |
57/// | `capabilities-exceeded` | the delivery's capabilities exceed the author attestation's |
58///
59/// A delivery whose embedded author signature fails has that signature's code (`bad-signature`, `expired`…).
60pub const VERIFY_CODES: &[&str] = &[
61    "ok",
62    "malformed",
63    "unknown-key",
64    "bad-algorithm",
65    "bad-signature",
66    "unknown-format",
67    "typ-mismatch",
68    "expired",
69    "digest-mismatch",
70    "doc-mismatch",
71    "unpinned-publisher",
72    "audience-mismatch",
73    "manifest-invalid",
74    "author-missing",
75    "capabilities-exceeded",
76];
77
78impl VerifyResult {
79    fn fail(code: &'static str, reason: impl Into<String>) -> VerifyResult {
80        VerifyResult { ok: false, code, claims: None, author: None, reason: reason.into() }
81    }
82}
83
84const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
85
86/// Base64url without padding.
87pub fn b64url_encode(data: &[u8]) -> String {
88    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
89    for chunk in data.chunks(3) {
90        let n = chunk.iter().enumerate().fold(0u32, |acc, (i, &b)| acc | (b as u32) << (16 - 8 * i));
91        let chars = chunk.len() + 1;
92        for k in 0..chars {
93            out.push(ALPHABET[((n >> (18 - 6 * k)) & 63) as usize] as char);
94        }
95    }
96    out
97}
98
99/// Base64url, padding optional.
100pub fn b64url_decode(s: &str) -> Result<Vec<u8>, String> {
101    let s = s.trim_end_matches('=');
102    let mut out = Vec::with_capacity(s.len() * 3 / 4);
103    let mut acc = 0u32;
104    let mut bits = 0;
105    for (i, c) in s.bytes().enumerate() {
106        let v = match c {
107            b'A'..=b'Z' => c - b'A',
108            b'a'..=b'z' => c - b'a' + 26,
109            b'0'..=b'9' => c - b'0' + 52,
110            b'-' => 62,
111            b'_' => 63,
112            _ => return Err(format!("illegal base64 data at input byte {i}")),
113        };
114        acc = acc << 6 | v as u32;
115        bits += 6;
116        if bits >= 8 {
117            bits -= 8;
118            out.push((acc >> bits) as u8);
119            acc &= (1 << bits) - 1;
120        }
121    }
122    if s.len() % 4 == 1 {
123        return Err(format!("illegal base64 data at input byte {}", s.len()));
124    }
125    Ok(out)
126}
127
128fn ed25519_public_key(jwk: &Jwk) -> Result<Vec<u8>, String> {
129    let x = jwk.get("x").and_then(Value::as_str).unwrap_or("");
130    if !is_str(jwk.get("kty"), "OKP") || !is_str(jwk.get("crv"), "Ed25519") || x.is_empty() {
131        return Err("not an Ed25519 JWK".into());
132    }
133    match b64url_decode(x) {
134        Ok(raw) if raw.len() == 32 => Ok(raw),
135        _ => Err("bad Ed25519 public key".into()),
136    }
137}
138
139fn claim(claims: &Object, key: &str) -> String {
140    js_value(claims.get(key))
141}
142
143fn now() -> i64 {
144    SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64)
145}
146
147fn verify_jws(jws: &str, keys: &[Jwk], expected_typ: &str, now: i64) -> VerifyResult {
148    let parts: Vec<&str> = jws.split('.').collect();
149    if parts.len() != 3 {
150        return VerifyResult::fail("malformed", "signature: Invalid Compact JWS");
151    }
152    let mut last_err = ("unknown-key", "no key verified the signature".to_string());
153    let malformed = |e: String| ("malformed", e);
154    for jwk in keys {
155        let attempt = || -> Result<VerifyResult, (&'static str, String)> {
156            let key = ed25519_public_key(jwk).map_err(|e| ("unknown-key", e))?;
157            let hb = b64url_decode(parts[0]).map_err(malformed)?;
158            let header: Map<String, Value> = serde_json::from_slice(&hb).map_err(|e| malformed(e.to_string()))?;
159            if !is_str(header.get("alg"), "EdDSA") {
160                return Err(("bad-algorithm", "\"alg\" (Algorithm) Header Parameter value not allowed".into()));
161            }
162            let sig = b64url_decode(parts[2]).map_err(malformed)?;
163            let signing = format!("{}.{}", parts[0], parts[1]);
164            UnparsedPublicKey::new(&ED25519, &key)
165                .verify(signing.as_bytes(), &sig)
166                .map_err(|_| ("bad-signature", "signature verification failed".to_string()))?;
167            let pb = b64url_decode(parts[1]).map_err(malformed)?;
168            let claims: Map<String, Value> = serde_json::from_slice(&pb).map_err(|e| malformed(e.to_string()))?;
169            if !is_str(claims.get("spec"), "instruction/1") {
170                return Ok(VerifyResult::fail(
171                    "unknown-format",
172                    format!("signature: unknown attestation format \"{}\"", claim(&claims, "spec")),
173                ));
174            }
175            if !is_str(claims.get("typ"), expected_typ) {
176                return Ok(VerifyResult::fail(
177                    "typ-mismatch",
178                    format!("signature: expected typ \"{expected_typ}\", found \"{}\"", claim(&claims, "typ")),
179                ));
180            }
181            if let Some(Value::String(ht)) = header.get("typ")
182                && !ht.is_empty()
183                && ht != expected_typ
184            {
185                return Ok(VerifyResult::fail("typ-mismatch", format!("signature: header typ \"{ht}\" disagrees with the claim")));
186            }
187            if let Some(exp) = claims.get("exp").and_then(Value::as_f64)
188                && exp < now as f64
189            {
190                return Ok(VerifyResult::fail("expired", format!("signature: expired at {}", js_number(exp))));
191            }
192            Ok(VerifyResult { ok: true, code: "ok", claims: Some(claims), author: None, reason: String::new() })
193        };
194        match attempt() {
195            Ok(r) => return r,
196            Err(e) => last_err = e,
197        }
198    }
199    VerifyResult::fail(last_err.0, format!("signature: {}", last_err.1))
200}
201
202/// What narrows an author verification: the expected doc, the pinned publisher, the clock.
203#[derive(Clone, Debug, Default)]
204pub struct VerifyOptions {
205    /// The document the signature must name (its `doc` claim); empty: any.
206    pub doc: String,
207    /// The pinned publisher (its `pub` claim); empty: any.
208    pub publisher: String,
209    /// Unix seconds; `None`: now.
210    pub now: Option<i64>,
211}
212
213/// Verifies an author signature over the authored bytes with a pinned publisher key set. A served text's
214/// `host-integrations` block (S34) is outside them: the text without it verifies too.
215pub fn verify_author(jws: &str, authored: &[u8], keys: &[Jwk], o: &VerifyOptions) -> VerifyResult {
216    let r = verify_jws(jws, keys, "author", o.now.unwrap_or_else(now));
217    let Some(c) = r.claims.as_ref().filter(|_| r.ok) else { return r };
218    if !signs(c.get("digest"), authored) {
219        return VerifyResult::fail("digest-mismatch", "author: digest does not match the authored bytes");
220    }
221    if !o.doc.is_empty() && !is_str(c.get("doc"), &o.doc) {
222        return VerifyResult::fail("doc-mismatch", format!("author: doc \"{}\" is not \"{}\"", claim(c, "doc"), o.doc));
223    }
224    if !o.publisher.is_empty() && !is_str(c.get("pub"), &o.publisher) {
225        return VerifyResult::fail("unpinned-publisher", format!("publisher \"{}\" is not pinned in instruction_sources", claim(c, "pub")));
226    }
227    r
228}
229
230/// What a delivery verification checks beyond the signatures.
231#[derive(Clone, Debug, Default)]
232pub struct DeliveryVerifyOptions {
233    /// This reader's audience (required): the delivery's `aud` claim must be it.
234    pub aud: String,
235    /// The authored bytes, when known: the author claim's digest must be theirs.
236    pub authored: Option<Vec<u8>>,
237    /// The pinned publisher; empty: any.
238    pub publisher: String,
239    /// Unix seconds; `None`: now.
240    pub now: Option<i64>,
241}
242
243/// Verifies a delivery signature over the delivered bytes, then the embedded author signature (§7.6 steps 2–3). The
244/// delivery's manifest names its resolution — `{format: instruction-resolved/1, status, document: {uri, sha256,
245/// version?}, dependencies, resolved_digest}` ([`crate::Manifest`]) — and the author's digest is the resolved
246/// document's sha256. When ok, `claims` are the delivery's and `author` the embedded author attestation's, both
247/// verified.
248pub fn verify_delivery(jws: &str, delivered: &[u8], delivery_keys: &[Jwk], author_keys: &[Jwk], o: &DeliveryVerifyOptions) -> VerifyResult {
249    let now = o.now.unwrap_or_else(now);
250    let r = verify_jws(jws, delivery_keys, "delivery", now);
251    let Some(c) = r.claims.as_ref().filter(|_| r.ok) else { return r };
252    if !is_str(c.get("aud"), &o.aud) {
253        return VerifyResult::fail("audience-mismatch", format!("delivery: aud \"{}\" is not this reader", claim(c, "aud")));
254    }
255    if !is_str(c.get("digest"), &digest(delivered)) {
256        return VerifyResult::fail("digest-mismatch", "delivery: digest does not match the received bytes");
257    }
258    let manifest = c.get("manifest").and_then(Value::as_object);
259    let document_digest = manifest.and_then(|m| m.get("document")).and_then(|d| d.get("sha256")).and_then(Value::as_str);
260    let has_resolved = manifest.and_then(|m| m.get("resolved_digest")).is_some_and(Value::is_string);
261    let has_dependencies = manifest.and_then(|m| m.get("dependencies")).is_some_and(Value::is_array);
262    let (Some(_), Some(document_digest)) = (manifest.filter(|m| is_str(m.get("format"), "instruction-resolved/1")), document_digest) else {
263        return VerifyResult::fail(
264            "manifest-invalid",
265            "manifest: the delivery names its resolution (format instruction-resolved/1, document, dependencies, resolved_digest)",
266        );
267    };
268    if !has_resolved || !has_dependencies {
269        return VerifyResult::fail(
270            "manifest-invalid",
271            "manifest: the delivery names its resolution (format instruction-resolved/1, document, dependencies, resolved_digest)",
272        );
273    }
274    let Some(Value::String(author)) = c.get("author") else {
275        return VerifyResult::fail("author-missing", "delivery: embedded author signature is required");
276    };
277    let a = verify_jws(author, author_keys, "author", now);
278    let Some(ac) = a.claims.as_ref().filter(|_| a.ok) else { return a };
279    if !crate::js::same_scalar(ac.get("doc"), c.get("doc")) || !crate::js::same_scalar(ac.get("version"), c.get("version")) {
280        return VerifyResult::fail("doc-mismatch", "author: doc/version disagree with the delivery claims");
281    }
282    if !is_str(ac.get("digest"), document_digest) {
283        return VerifyResult::fail("digest-mismatch", "author: digest does not equal the resolved document's sha256");
284    }
285    if let Some(authored) = &o.authored
286        && !signs(ac.get("digest"), authored)
287    {
288        return VerifyResult::fail("digest-mismatch", "author: digest does not match the authored bytes");
289    }
290    if !o.publisher.is_empty() && !is_str(ac.get("pub"), &o.publisher) {
291        return VerifyResult::fail(
292            "unpinned-publisher",
293            format!("publisher \"{}\" is not pinned in instruction_sources", claim(ac, "pub")),
294        );
295    }
296    let author_caps = capabilities(ac.get("capabilities"));
297    let mut excess = Vec::new();
298    if let Some(Value::Array(delivered)) = c.get("capabilities") {
299        for x in delivered {
300            let s = js_value(Some(x));
301            if !author_caps.contains(&s) {
302                excess.push(s);
303            }
304        }
305    }
306    if !excess.is_empty() {
307        return VerifyResult::fail(
308            "capabilities-exceeded",
309            format!("delivery: capabilities [{}] exceed the author attestation [{}]", excess.join(", "), author_caps.join(", ")),
310        );
311    }
312    let author = Some(ac.clone());
313    VerifyResult { author, ..r }
314}
315
316/// A claim's capability list as text, each once, in order (a set's).
317fn capabilities(v: Option<&Value>) -> Vec<String> {
318    let mut out: Vec<String> = Vec::new();
319    if let Some(Value::Array(list)) = v {
320        for x in list {
321            let s = js_value(Some(x));
322            if !out.contains(&s) {
323                out.push(s);
324            }
325        }
326    }
327    out
328}
329
330/// An Ed25519 signing key — for tests and tooling; a registry signs with its own keys.
331pub struct SigningKey {
332    pair: Ed25519KeyPair,
333}
334
335impl SigningKey {
336    /// The key of a 32-byte seed (an Ed25519 private key).
337    pub fn from_seed(seed: &[u8]) -> Result<SigningKey, String> {
338        Ed25519KeyPair::from_seed_unchecked(seed).map(|pair| SigningKey { pair }).map_err(|_| "an Ed25519 seed is 32 bytes".to_string())
339    }
340
341    /// A new random key.
342    pub fn generate() -> Result<SigningKey, String> {
343        let rng = ring::rand::SystemRandom::new();
344        let pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng).map_err(|_| "no randomness".to_string())?;
345        Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).map(|pair| SigningKey { pair }).map_err(|_| "a bad key".to_string())
346    }
347
348    /// The public key's 32 bytes.
349    pub fn public_key(&self) -> Vec<u8> {
350        self.pair.public_key().as_ref().to_vec()
351    }
352
353    /// The public key as a JWK (OKP, Ed25519), with a key id when one is given.
354    pub fn public_jwk(&self, kid: &str) -> Jwk {
355        public_jwk(&self.public_key(), kid)
356    }
357}
358
359/// The JWK of an Ed25519 public key.
360pub fn public_jwk(public_key: &[u8], kid: &str) -> Jwk {
361    let mut jwk = Jwk::new();
362    jwk.insert("kty".into(), "OKP".into());
363    jwk.insert("crv".into(), "Ed25519".into());
364    jwk.insert("x".into(), b64url_encode(public_key).into());
365    if !kid.is_empty() {
366        jwk.insert("kid".into(), kid.into());
367    }
368    jwk
369}
370
371/// Signs claims as a compact EdDSA JWS.
372pub fn sign_jws(claims: &Object, key: &SigningKey, typ: &str) -> String {
373    let mut header = Map::new();
374    header.insert("alg".into(), "EdDSA".into());
375    if !typ.is_empty() {
376        header.insert("typ".into(), typ.into());
377    }
378    let hb = serde_json::to_vec(&Value::Object(header)).unwrap_or_default();
379    let pb = serde_json::to_vec(&Value::Object(claims.clone())).unwrap_or_default();
380    let signing = format!("{}.{}", b64url_encode(&hb), b64url_encode(&pb));
381    let sig = key.pair.sign(signing.as_bytes());
382    format!("{signing}.{}", b64url_encode(sig.as_ref()))
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388
389    #[test]
390    fn base64url() {
391        for data in [&b""[..], b"f", b"fo", b"foo", b"foob", b"fooba", b"foobar", &[0xff, 0xfe, 0x00]] {
392            assert_eq!(b64url_decode(&b64url_encode(data)).unwrap(), data);
393        }
394        assert_eq!(b64url_encode(b"foobar"), "Zm9vYmFy");
395        assert_eq!(b64url_encode(&[0xfb, 0xff]), "-_8");
396        assert!(b64url_decode("a!b").is_err());
397    }
398}