//! The JWTs of spaces' credentials (`spec/SPACES-CREDENTIALS.md`): compact //! JWTs signed with ECDSA, read and written; and the keys they are held to, //! an issuer's `#atproto` key from its DID document ("Issuers' keys") or a //! client's JSON Web Key. use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64; use k256::ecdsa::signature::Verifier; use pds_repo::Repo; use serde_json::{Map, Value as Json, json}; /// A compact JWT, its parts read: the header and payload, JSON objects; the /// bytes signed, `
.` as sent; and the signature. pub(crate) struct Jwt { pub header: Map, pub payload: Map, pub signed: String, /// None where the third part is not base64url. pub signature: Option>, } impl Jwt { /// A token of three parts joined by `.`, its header and payload each /// base64url, without padding, of a JSON object; None if it is not. pub fn parse(token: &str) -> Option { let mut parts = token.split('.'); let (Some(h), Some(p), Some(sig), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else { return None; }; let object = |part: &str| match serde_json::from_slice(&B64.decode(part).ok()?).ok()? { Json::Object(m) => Some(m), _ => None, }; Some(Jwt { header: object(h)?, payload: object(p)?, signed: format!("{h}.{p}"), signature: B64.decode(sig).ok(), }) } /// A header field's text. pub fn header(&self, k: &str) -> Option<&str> { self.header.get(k).and_then(Json::as_str) } /// A claim's text. pub fn claim(&self, k: &str) -> Option<&str> { self.payload.get(k).and_then(Json::as_str) } /// A claim that is a number. pub fn number(&self, k: &str) -> Option { self.payload .get(k) .filter(|v| v.is_number()) .and_then(Json::as_f64) } /// The header's `alg`, if it is a string that is not empty. pub fn alg(&self) -> Option<&str> { self.header("alg").filter(|a| !a.is_empty()) } } /// A JWT of type `typ` with these claims, signed by the repository's key: /// `ES256K`, low-S, the key named `#atproto`. pub(crate) fn sign(repo: &Repo, typ: &str, payload: &Json) -> String { let header = B64.encode(json!({ "alg": "ES256K", "typ": typ, "kid": "#atproto" }).to_string()); let payload = B64.encode(payload.to_string()); let sig = repo.sign(format!("{header}.{payload}").as_bytes()); format!("{header}.{payload}.{}", B64.encode(sig)) } /// A token's `jti`: 16 random bytes as 32 lower case hex digits. pub(crate) fn new_jti() -> String { hex::encode(rand::random::<[u8; 16]>()) } /// A public key a JWT may be signed with. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Key { K256(k256::ecdsa::VerifyingKey), P256(p256::ecdsa::VerifyingKey), } /// The multicodecs of a secp256k1 and a P-256 public key, as varints. const SECP256K1_PUB: [u8; 2] = [0xe7, 0x01]; const P256_PUB: [u8; 2] = [0x80, 0x24]; impl Key { /// The `alg` of a JWT signed with this key. pub fn alg(&self) -> &'static str { match self { Key::K256(_) => "ES256K", Key::P256(_) => "ES256", } } /// A key in `Multikey` form, as a `did:key` is less its `did:key:`: `z`, /// base58btc of its multicodec and its compressed point. fn multikey(s: &str) -> Option { let bytes = bs58::decode(s.strip_prefix('z')?).into_vec().ok()?; if let Some(point) = bytes.strip_prefix(&SECP256K1_PUB[..]) { k256::ecdsa::VerifyingKey::from_sec1_bytes(point) .ok() .map(Key::K256) } else { p256::ecdsa::VerifyingKey::from_sec1_bytes(bytes.strip_prefix(&P256_PUB[..])?) .ok() .map(Key::P256) } } /// A key in the legacy form (`atproto/did.md`): `z`, base58btc of the /// point alone, its curve the method's `type`. fn legacy(typ: &str, s: &str) -> Option { let point = bs58::decode(s.strip_prefix('z')?).into_vec().ok()?; match typ { "EcdsaSecp256k1VerificationKey2019" => { k256::ecdsa::VerifyingKey::from_sec1_bytes(&point) .ok() .map(Key::K256) } "EcdsaSecp256r1VerificationKey2019" => { p256::ecdsa::VerifyingKey::from_sec1_bytes(&point) .ok() .map(Key::P256) } _ => None, } } /// The `#atproto` key of `did`'s document: the first verification method /// whose `id` is `#atproto` or `#atproto`, as a `Multikey` or in the /// legacy form. None for a document of another DID. pub fn of_document(doc: &Json, did: &str) -> Option { Key::of_document_named(doc, did, "atproto") } /// The key `#` of `did`'s document, as `of_document` finds `#atproto`. pub fn of_document_named(doc: &Json, did: &str, id: &str) -> Option { if doc["id"] != did { return None; } let (short, full) = (format!("#{id}"), format!("{did}#{id}")); let method = doc["verificationMethod"] .as_array()? .iter() .find(|m| m["id"] == short.as_str() || m["id"] == full.as_str())?; Key::of_method(method) } /// The key of a verification method, as a `Multikey` or in the legacy form. pub fn of_method(method: &Json) -> Option { let (typ, multibase) = ( method["type"].as_str()?, method["publicKeyMultibase"].as_str()?, ); if typ == "Multikey" { Key::multikey(multibase) } else { Key::legacy(typ, multibase) } } /// An elliptic-curve JSON Web Key (RFC 7518 §6.2), on P-256 or secp256k1. pub fn of_jwk(jwk: &Map) -> Option { let coord = |k: &str| { B64.decode(jwk.get(k)?.as_str()?) .ok() .filter(|c| c.len() == 32) }; if jwk.get("kty")?.as_str()? != "EC" { return None; } let point = [&[4u8][..], &coord("x")?, &coord("y")?].concat(); match jwk.get("crv")?.as_str()? { "P-256" => p256::ecdsa::VerifyingKey::from_sec1_bytes(&point) .ok() .map(Key::P256), "secp256k1" => k256::ecdsa::VerifyingKey::from_sec1_bytes(&point) .ok() .map(Key::K256), _ => None, } } /// Whether `sig`, 64 bytes `r ‖ s`, signs `message` with this key under /// `alg`, which must be the key's. A high-S signature verifies only if /// `high_s` says it may. pub fn verifies(&self, alg: &str, message: &[u8], sig: &[u8], high_s: bool) -> bool { if alg != self.alg() || sig.len() != 64 { return false; } match self { Key::K256(k) => { let Ok(sig) = k256::ecdsa::Signature::from_slice(sig) else { return false; }; let low = sig.normalize_s(); let sig = if low == sig { sig } else if high_s { low } else { return false; }; k.verify(message, &sig).is_ok() } Key::P256(k) => { let Ok(sig) = p256::ecdsa::Signature::from_slice(sig) else { return false; }; (high_s || sig.normalize_s() == sig) && k.verify(message, &sig).is_ok() } } } /// The key as issuers' keys are kept (`issuers`): its curve, 0 for /// secp256k1 and 1 for P-256, then its compressed point. pub fn packed(&self) -> [u8; 34] { let mut p = [0u8; 34]; match self { Key::K256(k) => p[1..].copy_from_slice(k.to_sec1_point(true).as_bytes()), Key::P256(k) => { p[0] = 1; p[1..].copy_from_slice(k.to_sec1_point(true).as_bytes()); } } p } /// The key `packed` made. pub fn unpacked(p: &[u8; 34]) -> Option { match p[0] { 0 => k256::ecdsa::VerifyingKey::from_sec1_bytes(&p[1..]) .ok() .map(Key::K256), 1 => p256::ecdsa::VerifyingKey::from_sec1_bytes(&p[1..]) .ok() .map(Key::P256), _ => None, } } } #[cfg(test)] mod tests { use super::*; #[test] fn documents_name_keys() { let k = k256::ecdsa::SigningKey::from_slice(&[7u8; 32]).unwrap(); let p = p256::ecdsa::SigningKey::from_slice(&[7u8; 32]).unwrap(); let did_key = crate::plc::did_key(k.verifying_key()); let doc = |id: &str, typ: &str, mb: &str| json!({ "id": "did:plc:x", "verificationMethod": [{ "id": id, "type": typ, "publicKeyMultibase": mb }] }); let multikey = did_key.trim_start_matches("did:key:"); assert_eq!( Key::of_document(&doc("did:plc:x#atproto", "Multikey", multikey), "did:plc:x"), Some(Key::K256(*k.verifying_key())) ); assert_eq!( Key::of_document(&doc("#atproto", "Multikey", multikey), "did:plc:x"), Some(Key::K256(*k.verifying_key())) ); assert_eq!( Key::of_document(&doc("#atproto", "Multikey", multikey), "did:plc:y"), None ); assert_eq!( Key::of_document(&doc("#atproto_kem", "Multikey", multikey), "did:plc:x"), None ); let mut p256_mk = P256_PUB.to_vec(); p256_mk.extend_from_slice(p.verifying_key().to_sec1_point(true).as_bytes()); let p256_mk = format!("z{}", bs58::encode(p256_mk).into_string()); assert_eq!( Key::of_document(&doc("#atproto", "Multikey", &p256_mk), "did:plc:x"), Some(Key::P256(*p.verifying_key())) ); let raw = |b: &[u8]| format!("z{}", bs58::encode(b).into_string()); let legacy_k = raw(k.verifying_key().to_sec1_point(false).as_bytes()); let legacy_p = raw(p.verifying_key().to_sec1_point(false).as_bytes()); assert_eq!( Key::of_document( &doc("#atproto", "EcdsaSecp256k1VerificationKey2019", &legacy_k), "did:plc:x" ), Some(Key::K256(*k.verifying_key())) ); assert_eq!( Key::of_document( &doc("#atproto", "EcdsaSecp256r1VerificationKey2019", &legacy_p), "did:plc:x" ), Some(Key::P256(*p.verifying_key())) ); assert_eq!( Key::of_document( &doc("#atproto", "EcdsaSecp256r1VerificationKey2019", &legacy_k), "did:plc:x" ), None ); assert_eq!( Key::of_document(&json!({ "id": "did:plc:x" }), "did:plc:x"), None ); } #[test] fn signatures_verify_under_their_alg_and_low_s() { use k256::ecdsa::signature::Signer; let k = k256::ecdsa::SigningKey::from_slice(&[7u8; 32]).unwrap(); let key = Key::K256(*k.verifying_key()); let sig: k256::ecdsa::Signature = k.sign(b"m"); let low = sig.normalize_s(); let order = hex::decode("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") .unwrap(); let high = k256::ecdsa::Signature::from_scalars( low.r().to_bytes(), sub(&order, &low.s().to_bytes()), ) .unwrap(); assert!(key.verifies("ES256K", b"m", &low.to_bytes(), false)); assert!(!key.verifies("ES256K", b"n", &low.to_bytes(), false)); assert!(!key.verifies("ES256", b"m", &low.to_bytes(), false)); assert!(!key.verifies("ES256K", b"m", &high.to_bytes(), false)); assert!(key.verifies("ES256K", b"m", &high.to_bytes(), true)); assert!(!key.verifies("ES256K", b"m", &low.to_der().to_bytes(), true)); let p = p256::ecdsa::SigningKey::from_slice(&[7u8; 32]).unwrap(); let key = Key::P256(*p.verifying_key()); let sig: p256::ecdsa::Signature = p.sign(b"m"); let low = sig.normalize_s(); let order = hex::decode("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551") .unwrap(); let high = p256::ecdsa::Signature::from_scalars( low.r().to_bytes(), sub(&order, &low.s().to_bytes()), ) .unwrap(); assert!(key.verifies("ES256", b"m", &low.to_bytes(), false)); assert!(!key.verifies("ES256K", b"m", &low.to_bytes(), false)); assert!(!key.verifies("ES256", b"m", &high.to_bytes(), false)); assert!(key.verifies("ES256", b"m", &high.to_bytes(), true)); } /// `a − b`, 32 bytes big-endian each. fn sub(a: &[u8], b: &[u8]) -> [u8; 32] { let mut out = [0u8; 32]; let mut borrow = 0i16; for i in (0..32).rev() { let d = a[i] as i16 - b[i] as i16 - borrow; borrow = (d < 0) as i16; out[i] = d.rem_euclid(256) as u8; } out } #[test] fn jwks() { let p = p256::ecdsa::SigningKey::from_slice(&[7u8; 32]).unwrap(); let point = p.verifying_key().to_sec1_point(false); let jwk = json!({ "kty": "EC", "crv": "P-256", "x": B64.encode(point.x().unwrap()), "y": B64.encode(point.y().unwrap()), "kid": "a" }); assert_eq!( Key::of_jwk(jwk.as_object().unwrap()), Some(Key::P256(*p.verifying_key())) ); let mut other = jwk.clone(); other["crv"] = json!("P-384"); assert_eq!(Key::of_jwk(other.as_object().unwrap()), None); other["crv"] = json!("secp256k1"); assert_eq!( Key::of_jwk(other.as_object().unwrap()), None, "a P-256 point is not on secp256k1" ); other["kty"] = json!("RSA"); assert_eq!(Key::of_jwk(other.as_object().unwrap()), None); } }