Skip to main content

vault_core/
jwks.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! The public half of a `signing_key` as a JSON Web Key Set (Phase 24.5).
4//!
5//! A service that signs tokens publishes its *public* keys at a `jwks_uri`, and a
6//! rotation needs the old and the new key listed together for as long as tokens
7//! signed by the old one are still in flight - which is why the entry has a
8//! first-class "previous key" slot. This turns what the vault holds (a PEM or a
9//! JWK) into the document a verifier fetches.
10//!
11//! **Only public material is ever produced.** A JWK that arrives with private
12//! members (`d`, `p`, `q`, `dp`, `dq`, `qi`, `k`) has them stripped, and a PEM that
13//! is a private key is refused rather than derived from: publishing the wrong
14//! half is the one mistake a key set cannot take back. Nothing is verified or
15//! generated here; keys are re-encoded, never operated on.
16//!
17//! PEM `PUBLIC KEY` (SPKI) is read for RSA, EC (P-256, P-384, P-521), Ed25519 and
18//! X25519; `RSA PUBLIC KEY` (PKCS#1) for RSA. A key without a `kid` gets its RFC
19//! 7638 thumbprint, which is what a verifier would compute for it anyway.
20
21use base64::Engine;
22use serde_json::{json, Map, Value};
23use sha2::{Digest, Sha256};
24
25fn b64u(b: &[u8]) -> String {
26    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b)
27}
28
29/// One DER element: `(tag, contents, rest)`.
30fn tlv(b: &[u8]) -> Result<(u8, &[u8], &[u8]), String> {
31    let (&tag, b) = b.split_first().ok_or("Truncated key (DER)")?;
32    let (&l0, b) = b.split_first().ok_or("Truncated key (DER)")?;
33    let (len, b) = if l0 < 0x80 {
34        (usize::from(l0), b)
35    } else {
36        let n = usize::from(l0 & 0x7f);
37        if n == 0 || n > 4 || b.len() < n {
38            return Err("Unsupported DER length".into());
39        }
40        let len = b[..n]
41            .iter()
42            .fold(0usize, |a, &x| (a << 8) | usize::from(x));
43        (len, &b[n..])
44    };
45    if b.len() < len {
46        return Err("Truncated key (DER)".into());
47    }
48    Ok((tag, &b[..len], &b[len..]))
49}
50
51fn pem_body(text: &str, label: &str) -> Option<Vec<u8>> {
52    let begin = format!("-----BEGIN {label}-----");
53    let end = format!("-----END {label}-----");
54    let i = text.find(&begin)? + begin.len();
55    let j = text[i..].find(&end)? + i;
56    let b64: String = text[i..j].lines().map(str::trim).collect();
57    base64::engine::general_purpose::STANDARD
58        .decode(b64.as_bytes())
59        .ok()
60}
61
62/// An unsigned big-endian integer without its DER sign byte.
63fn uint(contents: &[u8]) -> &[u8] {
64    match contents {
65        [0, rest @ ..] if !rest.is_empty() => rest,
66        c => c,
67    }
68}
69
70fn rsa_jwk(seq: &[u8]) -> Result<Value, String> {
71    let (_, n, rest) = tlv(seq)?;
72    let (_, e, _) = tlv(rest)?;
73    Ok(json!({ "kty": "RSA", "n": b64u(uint(n)), "e": b64u(uint(e)) }))
74}
75
76/// A JWK from a PEM public key.
77fn jwk_from_pem(text: &str) -> Result<Value, String> {
78    if text.contains("PRIVATE KEY-----") {
79        return Err(
80            "That is a private key. Put the public key in the entry: a key set publishes the public half only.".into(),
81        );
82    }
83    if let Some(der) = pem_body(text, "RSA PUBLIC KEY") {
84        let (tag, seq, _) = tlv(&der)?;
85        if tag != 0x30 {
86            return Err("Not an RSA public key".into());
87        }
88        return rsa_jwk(seq);
89    }
90    let der = pem_body(text, "PUBLIC KEY")
91        .ok_or("Expected a PEM `PUBLIC KEY` (or `RSA PUBLIC KEY`) block, or a JWK in JSON")?;
92    let (tag, spki, _) = tlv(&der)?;
93    if tag != 0x30 {
94        return Err("Not a SubjectPublicKeyInfo".into());
95    }
96    let (tag, alg, rest) = tlv(spki)?;
97    if tag != 0x30 {
98        return Err("Not a SubjectPublicKeyInfo".into());
99    }
100    let (tag, bits, _) = tlv(rest)?;
101    if tag != 0x03 || bits.first() != Some(&0) {
102        return Err("Unsupported key bit string".into());
103    }
104    let key = &bits[1..];
105    let (_, oid, params) = tlv(alg)?;
106    const RSA: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01];
107    const EC: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01];
108    const ED25519: &[u8] = &[0x2b, 0x65, 0x70];
109    const X25519: &[u8] = &[0x2b, 0x65, 0x6e];
110    match oid {
111        RSA => {
112            let (tag, seq, _) = tlv(key)?;
113            if tag != 0x30 {
114                return Err("Not an RSA public key".into());
115            }
116            rsa_jwk(seq)
117        }
118        EC => {
119            let (_, curve, _) = tlv(params)?;
120            let (name, size): (&str, usize) = match curve {
121                [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07] => ("P-256", 32),
122                [0x2b, 0x81, 0x04, 0x00, 0x22] => ("P-384", 48),
123                [0x2b, 0x81, 0x04, 0x00, 0x23] => ("P-521", 66),
124                _ => return Err("Only the P-256, P-384 and P-521 curves are supported".into()),
125            };
126            if key.len() != 1 + 2 * size || key[0] != 4 {
127                return Err("Only uncompressed EC points are supported".into());
128            }
129            Ok(json!({
130                "kty": "EC", "crv": name,
131                "x": b64u(&key[1..=size]), "y": b64u(&key[1 + size..]),
132            }))
133        }
134        ED25519 | X25519 if key.len() == 32 => Ok(json!({
135            "kty": "OKP",
136            "crv": if oid == ED25519 { "Ed25519" } else { "X25519" },
137            "x": b64u(key),
138        })),
139        _ => Err("Unsupported key type (RSA, EC P-256/384/521, Ed25519 and X25519 are)".into()),
140    }
141}
142
143const PRIVATE_MEMBERS: [&str; 8] = ["d", "p", "q", "dp", "dq", "qi", "k", "oth"];
144
145/// A public JWK from either spelling the vault might hold, with no private members.
146pub fn public_jwk(text: &str) -> Result<Value, String> {
147    let t = text.trim();
148    if t.starts_with('{') {
149        let mut v: Value =
150            serde_json::from_str(t).map_err(|e| format!("The JWK is not JSON: {e}"))?;
151        let o = v.as_object_mut().ok_or("A JWK is a JSON object")?;
152        if !o.contains_key("kty") {
153            return Err("The JWK has no `kty`".into());
154        }
155        for m in PRIVATE_MEMBERS {
156            o.remove(m);
157        }
158        return Ok(v);
159    }
160    jwk_from_pem(t)
161}
162
163/// The RFC 7638 thumbprint of a public JWK, which is the `kid` a verifier would
164/// derive and the one used when the entry names none.
165pub fn thumbprint(jwk: &Value) -> Result<String, String> {
166    let members: &[&str] = match jwk.get("kty").and_then(Value::as_str) {
167        Some("RSA") => &["e", "kty", "n"],
168        Some("EC") => &["crv", "kty", "x", "y"],
169        Some("OKP") => &["crv", "kty", "x"],
170        _ => return Err("Only RSA, EC and OKP keys have a thumbprint here".into()),
171    };
172    let mut m = Map::new();
173    for k in members {
174        let v = jwk
175            .get(*k)
176            .and_then(Value::as_str)
177            .ok_or_else(|| format!("The JWK has no `{k}`"))?;
178        m.insert((*k).into(), json!(v));
179    }
180    // serde_json's map is ordered by key, which is the order RFC 7638 asks for.
181    let canonical = serde_json::to_string(&Value::Object(m)).map_err(|e| e.to_string())?;
182    Ok(b64u(&Sha256::digest(canonical.as_bytes())))
183}
184
185/// `use` for a `usage` word the entry holds.
186fn use_for(usage: &str) -> &'static str {
187    match usage.trim().to_ascii_lowercase().as_str() {
188        "encrypt" | "enc" | "decrypt" => "enc",
189        _ => "sig",
190    }
191}
192
193/// One entry of the key set: the key with its `kid`, `alg` and `use`.
194pub fn entry_jwk(key: &str, kid: &str, alg: &str, usage: &str) -> Result<Value, String> {
195    let mut jwk = public_jwk(key)?;
196    let o = jwk.as_object_mut().ok_or("A JWK is a JSON object")?;
197    if !kid.is_empty() {
198        o.insert("kid".into(), json!(kid));
199    } else if !o.contains_key("kid") {
200        let t = thumbprint(&Value::Object(o.clone()))?;
201        o.insert("kid".into(), json!(t));
202    }
203    if !alg.is_empty() {
204        o.insert("alg".into(), json!(alg));
205    }
206    o.entry("use").or_insert_with(|| json!(use_for(usage)));
207    Ok(jwk)
208}
209
210/// The key set for a `signing_key` entry: the current key and, while a rotation is
211/// open, the previous one. `None` for a part that is empty.
212pub fn key_set(
213    current: (&str, &str, &str),
214    previous: (&str, &str),
215    alg: &str,
216    usage: &str,
217) -> Result<Value, String> {
218    let mut keys = Vec::new();
219    if current.0.trim().is_empty() {
220        return Err("`public_key` is empty; fill it in before emitting".into());
221    }
222    keys.push(entry_jwk(current.0, current.1, alg, usage)?);
223    if !previous.0.trim().is_empty() {
224        let k = entry_jwk(previous.0, previous.1, alg, usage)?;
225        if k["kid"] == keys[0]["kid"] {
226            return Err(
227                "The previous key has the same key id as the current one; a verifier could not tell them apart"
228                    .into(),
229            );
230        }
231        keys.push(k);
232    }
233    Ok(json!({ "keys": keys }))
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    /// Public keys made by Python's `cryptography` package, with the JWK and the
241    /// RFC 7638 thumbprint it computed for each: a second implementation, not this
242    /// one agreeing with itself.
243    fn vectors() -> Value {
244        serde_json::from_str(include_str!("../tests/fixtures/jwk-vectors.json")).unwrap()
245    }
246
247    #[test]
248    fn every_supported_key_type_comes_out_as_the_jwk_an_independent_implementation_made() {
249        let v = vectors();
250        for name in ["rsa", "p256", "p384", "p521", "ed25519", "x25519"] {
251            let pem = v[name]["pem"].as_str().unwrap();
252            let got = public_jwk(pem).unwrap();
253            assert_eq!(got, v[name]["jwk"], "{name}");
254            assert_eq!(
255                thumbprint(&got).unwrap(),
256                v[name]["kid"].as_str().unwrap(),
257                "{name}"
258            );
259        }
260        // PKCS#1 spelling of the RSA key.
261        assert_eq!(
262            public_jwk(v["rsa"]["pkcs1"].as_str().unwrap()).unwrap(),
263            v["rsa"]["jwk"]
264        );
265    }
266
267    #[test]
268    fn the_thumbprint_matches_the_rfc_8037_example() {
269        let k =
270            json!({"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"});
271        assert_eq!(
272            thumbprint(&k).unwrap(),
273            "kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k"
274        );
275    }
276
277    #[test]
278    fn private_material_never_reaches_the_set() {
279        // A JWK pasted with its private members: they are dropped.
280        let with_d =
281            json!({"kty":"OKP","crv":"Ed25519","x":"AAAA","d":"SECRETSECRET","k":"x"}).to_string();
282        let k = public_jwk(&with_d).unwrap();
283        assert!(k.get("d").is_none() && k.get("k").is_none());
284        assert!(!k.to_string().contains("SECRETSECRET"));
285        // A private PEM is refused, not derived from.
286        let err =
287            public_jwk("-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----").unwrap_err();
288        assert!(err.contains("private key"), "{err}");
289        let err =
290            public_jwk("-----BEGIN RSA PRIVATE KEY-----\nAAAA\n-----END RSA PRIVATE KEY-----")
291                .unwrap_err();
292        assert!(err.contains("private key"), "{err}");
293    }
294
295    #[test]
296    fn a_rotation_lists_both_keys_and_refuses_two_with_one_id() {
297        let v = vectors();
298        let a = v["ed25519"]["pem"].as_str().unwrap();
299        let b = v["p256"]["pem"].as_str().unwrap();
300        let set = key_set((a, "", ""), (b, ""), "EdDSA", "sign").unwrap();
301        let keys = set["keys"].as_array().unwrap();
302        assert_eq!(keys.len(), 2);
303        assert_eq!(
304            keys[0]["kid"], v["ed25519"]["kid"],
305            "no kid given: the thumbprint"
306        );
307        assert_eq!(keys[0]["use"], "sig");
308        assert_eq!(keys[0]["alg"], "EdDSA");
309        assert_eq!(keys[1]["crv"], "P-256");
310        // Only the current key while no rotation is open.
311        assert_eq!(
312            key_set((a, "k1", ""), ("", ""), "", "").unwrap()["keys"][0]["kid"],
313            "k1"
314        );
315        assert_eq!(
316            key_set((a, "k1", ""), ("", ""), "", "").unwrap()["keys"]
317                .as_array()
318                .unwrap()
319                .len(),
320            1
321        );
322        // The same id twice is a key set a verifier cannot use.
323        assert!(key_set((a, "same", ""), (b, "same"), "", "").is_err());
324        assert!(key_set(("", "", ""), ("", ""), "", "").is_err());
325        assert_eq!(entry_jwk(a, "", "", "encrypt").unwrap()["use"], "enc");
326    }
327
328    #[test]
329    fn garbage_is_an_error_and_never_a_panic() {
330        for bad in [
331            "",
332            "hello",
333            "{",
334            "[]",
335            "{\"a\":1}",
336            "-----BEGIN PUBLIC KEY-----\n!!!\n-----END PUBLIC KEY-----",
337        ] {
338            assert!(public_jwk(bad).is_err(), "{bad:?}");
339        }
340        for n in 0..200u32 {
341            let der: Vec<u8> = (0..40u32)
342                .map(|i| (i.wrapping_mul(n + 7) & 0xff) as u8)
343                .collect();
344            let pem = format!(
345                "-----BEGIN PUBLIC KEY-----\n{}\n-----END PUBLIC KEY-----",
346                base64::engine::general_purpose::STANDARD.encode(der)
347            );
348            let _ = public_jwk(&pem);
349        }
350    }
351}