1use 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
16fn signs(d: Option<&Value>, text: &[u8]) -> bool {
19 authored_candidates(text).iter().any(|t| is_str(d, &digest(t)))
20}
21
22pub type Jwk = Object;
24
25#[derive(Clone, Debug, PartialEq)]
27pub struct VerifyResult {
28 pub ok: bool,
29 pub code: &'static str,
31 pub claims: Option<Object>,
33 pub author: Option<Object>,
35 pub reason: String,
37}
38
39pub 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
86pub 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
99pub 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#[derive(Clone, Debug, Default)]
204pub struct VerifyOptions {
205 pub doc: String,
207 pub publisher: String,
209 pub now: Option<i64>,
211}
212
213pub 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#[derive(Clone, Debug, Default)]
232pub struct DeliveryVerifyOptions {
233 pub aud: String,
235 pub authored: Option<Vec<u8>>,
237 pub publisher: String,
239 pub now: Option<i64>,
241}
242
243pub 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
316fn 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
330pub struct SigningKey {
332 pair: Ed25519KeyPair,
333}
334
335impl SigningKey {
336 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 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 pub fn public_key(&self) -> Vec<u8> {
350 self.pair.public_key().as_ref().to_vec()
351 }
352
353 pub fn public_jwk(&self, kid: &str) -> Jwk {
355 public_jwk(&self.public_key(), kid)
356 }
357}
358
359pub 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
371pub 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}