a2a_protocol_types/audit/
checkpoint.rs1use base64::Engine;
25use base64::engine::general_purpose::URL_SAFE_NO_PAD;
26use ring::rand::SystemRandom;
27use ring::signature::{self, EcdsaKeyPair, Ed25519KeyPair, KeyPair};
28use serde::{Deserialize, Serialize};
29
30use crate::error::{A2aError, A2aResult};
31
32pub const CHECKPOINT_SCHEMA: &str = "a2a-audit-checkpoint/1";
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37#[non_exhaustive]
38pub enum SigningAlg {
39 Es256,
41 EdDsa,
43}
44
45impl SigningAlg {
46 #[must_use]
48 pub const fn jws_name(self) -> &'static str {
49 match self {
50 Self::Es256 => "ES256",
51 Self::EdDsa => "EdDSA",
52 }
53 }
54
55 fn from_jws(name: &str) -> Option<Self> {
56 match name {
57 "ES256" => Some(Self::Es256),
58 "EdDSA" => Some(Self::EdDsa),
59 _ => None,
60 }
61 }
62}
63
64#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "camelCase")]
67#[non_exhaustive]
68pub struct Checkpoint {
69 pub schema: String,
71 pub kind: String,
73 pub chain: String,
75 pub seq: u64,
77 pub hash: String,
79 pub time: String,
81 #[serde(default)]
83 pub protected: String,
84 #[serde(default)]
86 pub signature: String,
87}
88
89impl Checkpoint {
90 #[must_use]
92 pub fn new(
93 kind: impl Into<String>,
94 chain: impl Into<String>,
95 seq: u64,
96 hash: impl Into<String>,
97 time: impl Into<String>,
98 ) -> Self {
99 Self {
100 schema: CHECKPOINT_SCHEMA.to_owned(),
101 kind: kind.into(),
102 chain: chain.into(),
103 seq,
104 hash: hash.into(),
105 time: time.into(),
106 protected: String::new(),
107 signature: String::new(),
108 }
109 }
110
111 #[must_use]
113 pub const fn is_signed(&self) -> bool {
114 !self.signature.is_empty()
115 }
116
117 fn signing_input(&self, protected: &str) -> A2aResult<String> {
118 let mut body = serde_json::to_value(self)
119 .map_err(|e| A2aError::internal(format!("checkpoint serialization: {e}")))?;
120 if let Some(obj) = body.as_object_mut() {
121 obj.remove("protected");
122 obj.remove("signature");
123 }
124 let canonical = crate::signing::canonicalize(&body)?;
125 Ok(format!("{protected}.{}", URL_SAFE_NO_PAD.encode(canonical)))
126 }
127}
128
129pub struct CheckpointSigner {
131 alg: SigningAlg,
132 kid: String,
133 key: SignerKey,
134}
135
136enum SignerKey {
137 Es256(EcdsaKeyPair),
138 EdDsa(Ed25519KeyPair),
139}
140
141impl std::fmt::Debug for CheckpointSigner {
142 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143 f.debug_struct("CheckpointSigner")
144 .field("alg", &self.alg)
145 .field("kid", &self.kid)
146 .field("key", &"<redacted>")
147 .finish()
148 }
149}
150
151impl CheckpointSigner {
152 pub fn from_pkcs8(alg: SigningAlg, kid: impl Into<String>, pkcs8: &[u8]) -> A2aResult<Self> {
160 let key = match alg {
161 SigningAlg::Es256 => SignerKey::Es256(
162 EcdsaKeyPair::from_pkcs8(
163 &signature::ECDSA_P256_SHA256_FIXED_SIGNING,
164 pkcs8,
165 &SystemRandom::new(),
166 )
167 .map_err(|e| {
168 A2aError::invalid_params(format!(
169 "ES256 key is not PKCS#8 ({e}); a SEC1 `EC PRIVATE KEY` converts with \
170 `openssl pkcs8 -topk8 -nocrypt -outform DER`"
171 ))
172 })?,
173 ),
174 SigningAlg::EdDsa => SignerKey::EdDsa(
179 Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8)
180 .map_err(|e| A2aError::invalid_params(format!("Ed25519 PKCS#8 key: {e}")))?,
181 ),
182 };
183 Ok(Self {
184 alg,
185 kid: kid.into(),
186 key,
187 })
188 }
189
190 #[must_use]
192 pub fn kid(&self) -> &str {
193 &self.kid
194 }
195
196 #[must_use]
198 pub fn public_key(&self) -> TrustedKey {
199 let bytes = match &self.key {
200 SignerKey::Es256(k) => k.public_key().as_ref().to_vec(),
201 SignerKey::EdDsa(k) => k.public_key().as_ref().to_vec(),
202 };
203 TrustedKey::new(self.kid.clone(), self.alg, bytes)
204 }
205
206 pub fn sign(&self, checkpoint: &mut Checkpoint) -> A2aResult<()> {
213 let header = serde_json::json!({ "alg": self.alg.jws_name(), "kid": self.kid });
214 let header = serde_json::to_vec(&header)
215 .map_err(|e| A2aError::internal(format!("header serialization: {e}")))?;
216 let protected = URL_SAFE_NO_PAD.encode(header);
217 let input = checkpoint.signing_input(&protected)?;
218 let sig = match &self.key {
219 SignerKey::Es256(k) => k
220 .sign(&SystemRandom::new(), input.as_bytes())
221 .map_err(|e| A2aError::internal(format!("checkpoint signing: {e}")))?
222 .as_ref()
223 .to_vec(),
224 SignerKey::EdDsa(k) => k.sign(input.as_bytes()).as_ref().to_vec(),
225 };
226 checkpoint.protected = protected;
227 checkpoint.signature = URL_SAFE_NO_PAD.encode(sig);
228 Ok(())
229 }
230}
231
232#[derive(Debug, Clone, PartialEq, Eq)]
234#[non_exhaustive]
235pub struct TrustedKey {
236 pub kid: String,
238 pub alg: SigningAlg,
240 pub public_key: Vec<u8>,
243}
244
245impl TrustedKey {
246 #[must_use]
248 pub fn new(kid: impl Into<String>, alg: SigningAlg, public_key: Vec<u8>) -> Self {
249 Self {
250 kid: kid.into(),
251 alg,
252 public_key,
253 }
254 }
255}
256
257pub fn verify_checkpoint(checkpoint: &Checkpoint, keys: &[TrustedKey]) -> A2aResult<()> {
269 if !checkpoint.is_signed() {
270 return Err(A2aError::invalid_params("checkpoint is unsigned"));
271 }
272 let header = URL_SAFE_NO_PAD
273 .decode(&checkpoint.protected)
274 .map_err(|_| A2aError::invalid_params("checkpoint header is not base64url"))?;
275 let header: serde_json::Value = serde_json::from_slice(&header)
276 .map_err(|_| A2aError::invalid_params("checkpoint header is not JSON"))?;
277 if header.get("crit").is_some() {
281 return Err(A2aError::invalid_params(
282 "checkpoint header names critical extensions (crit), which this verifier does not support",
283 ));
284 }
285 let alg_name = header["alg"].as_str().unwrap_or_default();
286 let alg = SigningAlg::from_jws(alg_name)
287 .ok_or_else(|| A2aError::invalid_params(format!("unsupported alg {alg_name:?}")))?;
288 let kid = header["kid"].as_str().unwrap_or_default();
289 let key = keys
290 .iter()
291 .find(|k| k.kid == kid && k.alg == alg)
292 .ok_or_else(|| A2aError::invalid_params(format!("no trusted {alg_name} key {kid:?}")))?;
293 let sig = URL_SAFE_NO_PAD
294 .decode(&checkpoint.signature)
295 .map_err(|_| A2aError::invalid_params("checkpoint signature is not base64url"))?;
296 let input = checkpoint.signing_input(&checkpoint.protected)?;
297 let verifier: &dyn signature::VerificationAlgorithm = match alg {
298 SigningAlg::Es256 => &signature::ECDSA_P256_SHA256_FIXED,
299 SigningAlg::EdDsa => &signature::ED25519,
300 };
301 signature::UnparsedPublicKey::new(verifier, &key.public_key)
302 .verify(input.as_bytes(), &sig)
303 .map_err(|_| A2aError::invalid_params("checkpoint signature does not verify"))
304}
305
306#[cfg(test)]
307mod tests;