a2a_protocol_types/provenance/
sign.rs1use base64::Engine;
9use base64::engine::general_purpose::URL_SAFE_NO_PAD;
10use ring::rand::SystemRandom;
11use ring::signature::{self, EcdsaKeyPair, Ed25519KeyPair, KeyPair};
12
13use super::{Content, ContentSignature, Provenance, provenance_of, set};
14use crate::error::{A2aError, A2aResult};
15use crate::signing::{Jwk, Jwks, VerifyingKey, canonicalize};
16
17pub struct ContentSigner {
19 kid: String,
20 key: Key,
21}
22
23enum Key {
24 Es256(EcdsaKeyPair),
25 EdDsa(Ed25519KeyPair),
26}
27
28impl std::fmt::Debug for ContentSigner {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 f.debug_struct("ContentSigner")
31 .field("alg", &self.alg())
32 .field("kid", &self.kid)
33 .field("key", &"<redacted>")
34 .finish()
35 }
36}
37
38impl ContentSigner {
39 pub fn es256(kid: impl Into<String>, pkcs8: &[u8]) -> A2aResult<Self> {
45 let key = EcdsaKeyPair::from_pkcs8(
46 &signature::ECDSA_P256_SHA256_FIXED_SIGNING,
47 pkcs8,
48 &SystemRandom::new(),
49 )
50 .map_err(|e| A2aError::invalid_params(format!("ES256 PKCS#8 key: {e}")))?;
51 Ok(Self {
52 kid: kid.into(),
53 key: Key::Es256(key),
54 })
55 }
56
57 pub fn ed25519(kid: impl Into<String>, pkcs8: &[u8]) -> A2aResult<Self> {
63 let key = Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8)
64 .map_err(|e| A2aError::invalid_params(format!("Ed25519 PKCS#8 key: {e}")))?;
65 Ok(Self {
66 kid: kid.into(),
67 key: Key::EdDsa(key),
68 })
69 }
70
71 #[must_use]
73 pub const fn alg(&self) -> &'static str {
74 match self.key {
75 Key::Es256(_) => "ES256",
76 Key::EdDsa(_) => "EdDSA",
77 }
78 }
79
80 #[must_use]
82 pub fn public_jwk(&self) -> Jwk {
83 let key = match &self.key {
84 Key::Es256(k) => VerifyingKey::Es256(k.public_key().as_ref().to_vec()),
85 Key::EdDsa(k) => VerifyingKey::EdDsa(k.public_key().as_ref().to_vec()),
86 };
87 Jwk::from_verifying_key(&key, Some(&self.kid))
88 }
89
90 fn sign(&self, input: &[u8]) -> A2aResult<Vec<u8>> {
91 Ok(match &self.key {
92 Key::Es256(k) => k
93 .sign(&SystemRandom::new(), input)
94 .map_err(|e| A2aError::internal(format!("signing failed: {e}")))?
95 .as_ref()
96 .to_vec(),
97 Key::EdDsa(k) => k.sign(input).as_ref().to_vec(),
98 })
99 }
100}
101
102pub fn sign_content<C: Content>(content: &mut C, signer: &ContentSigner) -> A2aResult<()> {
114 let mut provenance = provenance_of(content)?.unwrap_or_default();
115 provenance.signature = None;
116 set(content, &provenance);
117 let header = serde_json::json!({ "alg": signer.alg(), "kid": signer.kid });
118 let protected = URL_SAFE_NO_PAD.encode(
119 serde_json::to_vec(&header)
120 .map_err(|e| A2aError::internal(format!("header serialization: {e}")))?,
121 );
122 let sig = signer.sign(signing_input(content, &protected)?.as_bytes())?;
123 provenance.signature = Some(ContentSignature {
124 protected,
125 signature: URL_SAFE_NO_PAD.encode(sig),
126 });
127 set(content, &provenance);
128 Ok(())
129}
130
131pub fn verify_content<C: Content + Clone>(content: &C, jwks: &Jwks) -> A2aResult<Provenance> {
141 let provenance = provenance_of(content)?
142 .ok_or_else(|| A2aError::invalid_params("the content carries no provenance"))?;
143 let sig = provenance
144 .signature
145 .clone()
146 .ok_or_else(|| A2aError::invalid_params("the content's provenance is not signed"))?;
147 let header: serde_json::Value = URL_SAFE_NO_PAD
148 .decode(&sig.protected)
149 .ok()
150 .and_then(|h| serde_json::from_slice(&h).ok())
151 .ok_or_else(|| A2aError::invalid_params("malformed signature header"))?;
152 if header.get("crit").is_some() {
156 return Err(A2aError::invalid_params(
157 "signature header names critical extensions (crit), which this verifier does not support",
158 ));
159 }
160 let alg = header["alg"].as_str().unwrap_or_default();
161 let kid = header["kid"].as_str();
162 let candidates = jwks.candidates(kid, alg);
163 if candidates.is_empty() {
164 return Err(A2aError::invalid_params(format!(
165 "no {alg} key in the set with kid {kid:?}"
166 )));
167 }
168
169 let mut unsigned = content.clone();
174 if let Some(serde_json::Value::Object(p)) = unsigned
175 .metadata_mut()
176 .as_mut()
177 .and_then(|m| m.get_mut(super::PROVENANCE_METADATA_KEY))
178 {
179 p.remove("signature");
180 }
181 let input = signing_input(&unsigned, &sig.protected)?;
182 let sig_bytes = URL_SAFE_NO_PAD
183 .decode(&sig.signature)
184 .map_err(|_| A2aError::invalid_params("the signature is not base64url"))?;
185 if candidates
186 .iter()
187 .any(|k| k.verify(alg, input.as_bytes(), &sig_bytes).is_ok())
188 {
189 Ok(provenance)
190 } else {
191 Err(A2aError::invalid_params(
192 "the content's signature does not verify: it was changed after signing, or \
193 signed by another key",
194 ))
195 }
196}
197
198fn signing_input<C: Content>(content: &C, protected: &str) -> A2aResult<String> {
201 let value = serde_json::to_value(content)
202 .map_err(|e| A2aError::internal(format!("content serialization: {e}")))?;
203 Ok(format!(
204 "{protected}.{}",
205 URL_SAFE_NO_PAD.encode(canonicalize(&value)?)
206 ))
207}
208
209#[cfg(test)]
210mod tests;