a2a_protocol_types/signing/
keys.rs1use base64::Engine;
11use base64::engine::general_purpose::URL_SAFE_NO_PAD;
12use ring::signature;
13use serde::{Deserialize, Serialize};
14
15use crate::error::{A2aError, A2aResult};
16
17const P256_SPKI_PREFIX: [u8; 26] = [
20 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
21 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00,
22];
23
24const ED25519_SPKI_PREFIX: [u8; 12] = [
26 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
27];
28
29pub fn p256_point(bytes: &[u8]) -> Option<&[u8]> {
31 let raw = bytes.strip_prefix(&P256_SPKI_PREFIX[..]).unwrap_or(bytes);
32 (raw.len() == 65 && raw[0] == 0x04).then_some(raw)
33}
34
35pub fn ed25519_key(bytes: &[u8]) -> Option<&[u8]> {
37 let raw = bytes
38 .strip_prefix(&ED25519_SPKI_PREFIX[..])
39 .unwrap_or(bytes);
40 (raw.len() == 32).then_some(raw)
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
45#[non_exhaustive]
46pub enum VerifyingKey {
47 Es256(Vec<u8>),
49 EdDsa(Vec<u8>),
51}
52
53impl VerifyingKey {
54 pub fn from_bytes(alg: &str, bytes: &[u8]) -> A2aResult<Self> {
62 match alg {
63 "ES256" => p256_point(bytes)
64 .map(|p| Self::Es256(p.to_vec()))
65 .ok_or_else(|| {
66 A2aError::invalid_params(
67 "an ES256 key is a 65-byte uncompressed P-256 point, or its SPKI DER",
68 )
69 }),
70 "EdDSA" => ed25519_key(bytes)
71 .map(|k| Self::EdDsa(k.to_vec()))
72 .ok_or_else(|| {
73 A2aError::invalid_params(
74 "an EdDSA key is a 32-byte Ed25519 key, or its SPKI DER",
75 )
76 }),
77 other => Err(A2aError::invalid_params(format!(
78 "unsupported algorithm {other:?}; ES256 and EdDSA are supported"
79 ))),
80 }
81 }
82
83 #[must_use]
85 pub const fn alg(&self) -> &'static str {
86 match self {
87 Self::Es256(_) => "ES256",
88 Self::EdDsa(_) => "EdDSA",
89 }
90 }
91
92 pub(crate) fn verify(&self, alg: &str, input: &[u8], sig: &[u8]) -> A2aResult<()> {
95 if alg != self.alg() {
96 return Err(A2aError::invalid_params(format!(
97 "the signature is {alg}, the key is {}",
98 self.alg()
99 )));
100 }
101 let (algorithm, key): (&dyn signature::VerificationAlgorithm, &[u8]) = match self {
102 Self::Es256(k) => (&signature::ECDSA_P256_SHA256_FIXED, k),
103 Self::EdDsa(k) => (&signature::ED25519, k),
104 };
105 signature::UnparsedPublicKey::new(algorithm, key)
106 .verify(input, sig)
107 .map_err(|_| A2aError::invalid_params("signature verification failed"))
108 }
109}
110
111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
114#[non_exhaustive]
115pub struct Jwk {
116 pub kty: String,
118 #[serde(default, skip_serializing_if = "Option::is_none")]
120 pub crv: Option<String>,
121 #[serde(default, skip_serializing_if = "Option::is_none")]
123 pub x: Option<String>,
124 #[serde(default, skip_serializing_if = "Option::is_none")]
126 pub y: Option<String>,
127 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub kid: Option<String>,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub alg: Option<String>,
133 #[serde(default, rename = "use", skip_serializing_if = "Option::is_none")]
135 pub key_use: Option<String>,
136 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub exp: Option<u64>,
142 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub x5c: Option<Vec<String>>,
150}
151
152impl Jwk {
153 pub fn verifying_key(&self) -> A2aResult<VerifyingKey> {
161 if self.key_use.as_deref().is_some_and(|u| u != "sig") {
162 return Err(A2aError::invalid_params("the JWK is not for signatures"));
163 }
164 let b64 = |m: &Option<String>, name: &str| {
165 let v = m
166 .as_deref()
167 .ok_or_else(|| A2aError::invalid_params(format!("the JWK has no {name}")))?;
168 URL_SAFE_NO_PAD
169 .decode(v)
170 .map_err(|_| A2aError::invalid_params(format!("the JWK's {name} is not base64url")))
171 };
172 let (alg, key) = match (self.kty.as_str(), self.crv.as_deref()) {
173 ("EC", Some("P-256")) => {
174 let coordinate = |m: &Option<String>, name: &str| -> A2aResult<[u8; 32]> {
175 <[u8; 32]>::try_from(b64(m, name)?).map_err(|_| {
176 A2aError::invalid_params(format!("a P-256 JWK's {name} is 32 bytes"))
177 })
178 };
179 let (x, y) = (coordinate(&self.x, "x")?, coordinate(&self.y, "y")?);
180 let mut point = Vec::with_capacity(65);
181 point.push(0x04);
182 point.extend_from_slice(&x);
183 point.extend_from_slice(&y);
184 ("ES256", point)
185 }
186 ("OKP", Some("Ed25519")) => ("EdDSA", b64(&self.x, "x")?),
187 (kty, crv) => {
188 return Err(A2aError::invalid_params(format!(
189 "unsupported JWK {kty}/{crv:?}; EC/P-256 and OKP/Ed25519 are supported"
190 )));
191 }
192 };
193 if self.alg.as_deref().is_some_and(|a| a != alg) {
194 return Err(A2aError::invalid_params(format!(
195 "the JWK's alg contradicts its curve, which is for {alg}"
196 )));
197 }
198 VerifyingKey::from_bytes(alg, &key)
199 }
200
201 #[must_use]
203 pub fn from_verifying_key(key: &VerifyingKey, kid: Option<&str>) -> Self {
204 let (kty, crv, x, y) = match key {
205 VerifyingKey::Es256(p) => (
206 "EC",
207 "P-256",
208 URL_SAFE_NO_PAD.encode(&p[1..33]),
209 Some(URL_SAFE_NO_PAD.encode(&p[33..65])),
210 ),
211 VerifyingKey::EdDsa(k) => ("OKP", "Ed25519", URL_SAFE_NO_PAD.encode(k), None),
212 };
213 Self {
214 kty: kty.to_owned(),
215 crv: Some(crv.to_owned()),
216 x: Some(x),
217 y,
218 kid: kid.map(str::to_owned),
219 alg: Some(key.alg().to_owned()),
220 key_use: Some("sig".to_owned()),
221 exp: None,
222 x5c: None,
223 }
224 }
225
226 #[must_use]
229 pub const fn with_expiry(mut self, exp: u64) -> Self {
230 self.exp = Some(exp);
231 self
232 }
233}
234
235#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
237#[non_exhaustive]
238pub struct Jwks {
239 pub keys: Vec<Jwk>,
241}
242
243impl Jwks {
244 #[must_use]
246 pub const fn new(keys: Vec<Jwk>) -> Self {
247 Self { keys }
248 }
249
250 #[must_use]
264 pub fn candidates(&self, kid: Option<&str>, alg: &str) -> Vec<VerifyingKey> {
265 let now = std::time::SystemTime::now()
266 .duration_since(std::time::UNIX_EPOCH)
267 .map_or(u64::MAX, |d| d.as_secs());
268 self.candidates_at(kid, alg, now)
269 }
270
271 pub(crate) fn candidates_at(
273 &self,
274 kid: Option<&str>,
275 alg: &str,
276 now: u64,
277 ) -> Vec<VerifyingKey> {
278 self.keys
279 .iter()
280 .filter(|k| k.exp.is_none_or(|exp| now < exp))
281 .filter(|k| kid.is_none() || k.kid.as_deref() == kid)
282 .filter_map(|k| Some((k, k.verifying_key().ok()?)))
283 .filter(|(k, key)| {
284 k.x5c
285 .as_deref()
286 .is_none_or(|chain| x5c::admits(chain, key, now))
287 })
288 .map(|(_, key)| key)
289 .filter(|k| k.alg() == alg)
290 .collect()
291 }
292}
293
294mod x5c;
295
296#[cfg(test)]
297mod tests;