interplane.Get Omega
Read in your language

aien-protocols-mv

Canonical specifications, wire protocols, and schemas for the AIEN sovereign ecosystem

Brought by drakestapleton

branch main Branches Tags History

aien-protocols-mv / crates / aien-provenance / src / lib.rs

382 lines · 14008 bytes Raw Blame History
1use aien_protocol_types::Digest32;
2use bitflags::bitflags;
3use p256::ecdsa::signature::{Signer, Verifier};
4use p256::ecdsa::{Signature, SigningKey, VerifyingKey};
5use serde::{Deserialize, Serialize};
6use sha2::{Digest, Sha256};
7use thiserror::Error;
8use uuid::Uuid;
9
10pub fn compute_sha256(bytes: &[u8]) -> Digest32 {
11 let mut hasher = Sha256::new();
12 hasher.update(bytes);
13 let result = hasher.finalize();
14 let mut arr = [0u8; 32];
15 arr.copy_from_slice(&result);
16 Digest32::from_bytes(arr)
17}
18
19pub fn compute_canonical_json_digest<T: Serialize>(val: &T) -> Result<Digest32, serde_json::Error> {
20 let json_bytes = serde_json::to_vec(val)?;
21 Ok(compute_sha256(&json_bytes))
22}
23
24pub fn combine_digests(d1: &Digest32, d2: &Digest32) -> Digest32 {
25 let mut hasher = Sha256::new();
26 hasher.update(d1.as_bytes());
27 hasher.update(d2.as_bytes());
28 let result = hasher.finalize();
29 let mut arr = [0u8; 32];
30 arr.copy_from_slice(&result);
31 Digest32::from_bytes(arr)
32}
33
34bitflags! {
35 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
36 pub struct GrantPermissions: u32 {
37 const READ = 0b0000_0001;
38 const EVALUATE = 0b0000_0010;
39 const TRAIN = 0b0000_0100;
40 const DISTILL = 0b0000_1000;
41 const REDISTRIBUTE = 0b0001_0000;
42 const COMMERCIAL = 0b0010_0000;
43 }
44}
45
46#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
47pub struct SourceGrant {
48 pub grant_id: Uuid,
49 pub source_uri: String,
50 pub license_spdx: String,
51 pub permissions: GrantPermissions,
52 pub issuer: String,
53 pub issuer_signature: Option<Vec<u8>>,
54 pub expires_at_epoch_sec: Option<u64>,
55}
56
57#[derive(Error, Debug, PartialEq, Eq)]
58pub enum ProvenanceError {
59 #[error("Source grant permission denied: required {required:?}, granted {granted:?}")]
60 PermissionDenied {
61 required: GrantPermissions,
62 granted: GrantPermissions,
63 },
64 #[error("Incompatible license: {license} not in allowed set")]
65 IncompatibleLicense { license: String },
66 #[error("Grant has expired at {0}")]
67 GrantExpired(u64),
68 #[error("Missing signature from authority")]
69 MissingSignature,
70 #[error("Invalid signature format: {0}")]
71 InvalidSignatureFormat(String),
72 #[error("Signature verification failed: {0}")]
73 SignatureVerificationFailed(String),
74}
75
76impl SourceGrant {
77 pub fn new(
78 source_uri: String,
79 license_spdx: String,
80 permissions: GrantPermissions,
81 issuer: String,
82 ) -> Self {
83 Self {
84 grant_id: Uuid::new_v4(),
85 source_uri,
86 license_spdx,
87 permissions,
88 issuer,
89 issuer_signature: None,
90 expires_at_epoch_sec: None,
91 }
92 }
93
94 pub fn with_expiration(mut self, expires_at_epoch_sec: u64) -> Self {
95 self.expires_at_epoch_sec = Some(expires_at_epoch_sec);
96 self
97 }
98
99 /// SHA-256 of the v2, domain-separated grant transcript. Legacy signatures
100 /// over concatenated strings are deliberately not verified.
101 pub fn compute_unsigned_digest(&self) -> Digest32 {
102 let mut hasher = Sha256::new();
103 hasher.update(b"AIEN_SOURCE_GRANT_V2\0");
104 hasher.update(self.grant_id.as_bytes());
105 hasher.update((self.source_uri.len() as u64).to_le_bytes());
106 hasher.update(self.source_uri.as_bytes());
107 hasher.update((self.license_spdx.len() as u64).to_le_bytes());
108 hasher.update(self.license_spdx.as_bytes());
109 hasher.update(self.permissions.bits().to_le_bytes());
110 hasher.update((self.issuer.len() as u64).to_le_bytes());
111 hasher.update(self.issuer.as_bytes());
112 match self.expires_at_epoch_sec {
113 Some(exp) => {
114 hasher.update([1]);
115 hasher.update(exp.to_le_bytes());
116 }
117 None => hasher.update([0]),
118 }
119 Digest32(hasher.finalize().into())
120 }
121
122 /// Signs the grant using the authority signing key.
123 pub fn sign(&mut self, authority_signing_key: &SigningKey) {
124 let digest = self.compute_unsigned_digest();
125 let sig: Signature = authority_signing_key.sign(&digest.0);
126 self.issuer_signature = Some(sig.to_bytes().to_vec());
127 }
128
129 /// Verifies the cryptographic signature of the grant against the authority verifying key.
130 pub fn verify_signature(
131 &self,
132 authority_verifying_key: &VerifyingKey,
133 ) -> Result<(), ProvenanceError> {
134 let Some(ref sig_bytes) = self.issuer_signature else {
135 return Err(ProvenanceError::MissingSignature);
136 };
137 let sig = Signature::from_slice(sig_bytes)
138 .map_err(|e| ProvenanceError::InvalidSignatureFormat(e.to_string()))?;
139 let digest = self.compute_unsigned_digest();
140 authority_verifying_key
141 .verify(&digest.0, &sig)
142 .map_err(|e| ProvenanceError::SignatureVerificationFailed(e.to_string()))
143 }
144
145 /// Verifies that the grant has not expired given current epoch timestamp in seconds.
146 pub fn verify_validity(&self, current_epoch_sec: u64) -> Result<(), ProvenanceError> {
147 if let Some(exp) = self.expires_at_epoch_sec {
148 if current_epoch_sec > exp {
149 return Err(ProvenanceError::GrantExpired(exp));
150 }
151 }
152 Ok(())
153 }
154
155 pub fn verify_permission(&self, required: GrantPermissions) -> Result<(), ProvenanceError> {
156 if self.permissions.contains(required) {
157 Ok(())
158 } else {
159 Err(ProvenanceError::PermissionDenied {
160 required,
161 granted: self.permissions,
162 })
163 }
164 }
165
166 pub fn verify_license(&self, allowed_licenses: &[&str]) -> Result<(), ProvenanceError> {
167 if allowed_licenses
168 .iter()
169 .any(|&l| l.eq_ignore_ascii_case(&self.license_spdx))
170 {
171 Ok(())
172 } else {
173 Err(ProvenanceError::IncompatibleLicense {
174 license: self.license_spdx.clone(),
175 })
176 }
177 }
178
179 /// Performs complete authorization verification: license, permissions, expiration, and authority signature.
180 pub fn verify_all(
181 &self,
182 required_permissions: GrantPermissions,
183 allowed_licenses: &[&str],
184 current_epoch_sec: u64,
185 authority_verifying_key: Option<&VerifyingKey>,
186 ) -> Result<(), ProvenanceError> {
187 self.verify_license(allowed_licenses)?;
188 self.verify_permission(required_permissions)?;
189 self.verify_validity(current_epoch_sec)?;
190 if let Some(vk) = authority_verifying_key {
191 self.verify_signature(vk)?;
192 }
193 Ok(())
194 }
195
196 pub fn compute_digest(&self) -> Digest32 {
197 compute_canonical_json_digest(self).unwrap_or(Digest32::ZERO)
198 }
199}
200
201/// Bytes in a SEC1 compressed P-256 public key (first byte 0x02 or 0x03).
202pub const P256_KEY_LEN: usize = 33;
203/// Bytes in a raw P-256 ECDSA signature, `r` then `s`.
204pub const P256_SIG_LEN: usize = 64;
205
206/// The SEC1 compressed encoding of the verifying key of `key`, the form the
207/// fixed-width records of `specs/microjob` and `specs/discovery-capsule` carry.
208pub fn p256_compressed_key(key: &SigningKey) -> [u8; P256_KEY_LEN] {
209 let point = VerifyingKey::from(key).to_sec1_point(true);
210 let mut out = [0u8; P256_KEY_LEN];
211 out.copy_from_slice(point.as_bytes());
212 out
213}
214
215/// ECDSA P-256 / SHA-256 signature over `message`, normalized to low S so one
216/// message and key have one accepted signature form per nonce.
217pub fn p256_sign_low_s(key: &SigningKey, message: &[u8]) -> [u8; P256_SIG_LEN] {
218 let sig: Signature = key.sign(message);
219 let mut out = [0u8; P256_SIG_LEN];
220 out.copy_from_slice(&sig.normalize_s().to_bytes());
221 out
222}
223
224/// Verify a raw low-S ECDSA P-256 / SHA-256 signature over `message` against
225/// a SEC1 compressed public key. A high-S signature is refused even when it
226/// is mathematically valid (malleability).
227pub fn p256_verify_low_s(
228 public_key: &[u8; P256_KEY_LEN],
229 message: &[u8],
230 signature: &[u8; P256_SIG_LEN],
231) -> Result<(), ProvenanceError> {
232 if public_key[0] != 0x02 && public_key[0] != 0x03 {
233 return Err(ProvenanceError::InvalidSignatureFormat(
234 "public key is not SEC1 compressed".into(),
235 ));
236 }
237 let vk = VerifyingKey::from_sec1_bytes(public_key)
238 .map_err(|e| ProvenanceError::InvalidSignatureFormat(e.to_string()))?;
239 let sig = Signature::from_slice(signature)
240 .map_err(|e| ProvenanceError::InvalidSignatureFormat(e.to_string()))?;
241 if sig.normalize_s() != sig {
242 return Err(ProvenanceError::InvalidSignatureFormat(
243 "high-S signature".into(),
244 ));
245 }
246 vk.verify(message, &sig)
247 .map_err(|e| ProvenanceError::SignatureVerificationFailed(e.to_string()))
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253
254 #[test]
255 fn test_sha256_deterministic() {
256 let d1 = compute_sha256(b"hello aien protocols");
257 let d2 = compute_sha256(b"hello aien protocols");
258 assert_eq!(d1, d2);
259 assert_ne!(d1, Digest32::ZERO);
260 }
261
262 #[test]
263 fn test_source_grant_permissions_and_licensing() {
264 let grant = SourceGrant::new(
265 "https://huggingface.co/datasets/aien/benchmark".to_string(),
266 "Apache-2.0".to_string(),
267 GrantPermissions::READ | GrantPermissions::EVALUATE | GrantPermissions::TRAIN,
268 "Atlas Authority".to_string(),
269 );
270
271 assert!(grant.verify_permission(GrantPermissions::TRAIN).is_ok());
272 assert!(grant.verify_permission(GrantPermissions::DISTILL).is_err());
273 assert!(grant.verify_license(&["Apache-2.0", "MIT"]).is_ok());
274 assert!(grant.verify_license(&["GPL-3.0"]).is_err());
275 }
276
277 #[test]
278 fn test_source_grant_signature_and_expiration() {
279 let signing_key = SigningKey::from_slice(&[33u8; 32]).unwrap();
280 let verifying_key = VerifyingKey::from(&signing_key);
281
282 let mut grant = SourceGrant::new(
283 "https://hf.co/datasets/aien/verified".to_string(),
284 "Apache-2.0".to_string(),
285 GrantPermissions::TRAIN | GrantPermissions::DISTILL,
286 "Atlas Provenance Authority".to_string(),
287 )
288 .with_expiration(1000);
289
290 // Missing signature rejected
291 assert_eq!(
292 grant.verify_signature(&verifying_key),
293 Err(ProvenanceError::MissingSignature)
294 );
295
296 // Sign grant
297 grant.sign(&signing_key);
298 assert!(grant.verify_signature(&verifying_key).is_ok());
299
300 // Wrong verifying key rejected
301 let other_key = VerifyingKey::from(&SigningKey::from_slice(&[44u8; 32]).unwrap());
302 assert!(grant.verify_signature(&other_key).is_err());
303
304 // Validity checks
305 assert!(grant.verify_validity(999).is_ok());
306 assert_eq!(
307 grant.verify_validity(1001),
308 Err(ProvenanceError::GrantExpired(1000))
309 );
310
311 // verify_all succeeds within window with valid key
312 assert!(grant
313 .verify_all(
314 GrantPermissions::TRAIN,
315 &["Apache-2.0"],
316 950,
317 Some(&verifying_key)
318 )
319 .is_ok());
320 }
321
322 #[test]
323 fn test_p256_region_signature_low_s() {
324 let key = SigningKey::from_slice(&[7u8; 32]).unwrap();
325 let pubkey = p256_compressed_key(&key);
326 assert!(pubkey[0] == 0x02 || pubkey[0] == 0x03);
327 let sig = p256_sign_low_s(&key, b"region");
328 assert!(p256_verify_low_s(&pubkey, b"region", &sig).is_ok());
329 assert!(p256_verify_low_s(&pubkey, b"regioN", &sig).is_err());
330
331 // The high-S twin of a valid signature is refused.
332 let parsed = Signature::from_slice(&sig).unwrap();
333 let (r, s) = parsed.split_scalars();
334 let high = Signature::from_scalars(r, -*s).unwrap();
335 let mut high_bytes = [0u8; P256_SIG_LEN];
336 high_bytes.copy_from_slice(&high.to_bytes());
337 assert!(p256_verify_low_s(&pubkey, b"region", &high_bytes).is_err());
338 }
339
340 #[test]
341 fn signed_grant_boundary_substitution_is_refused() {
342 let signing_key = SigningKey::from_slice(&[33u8; 32]).unwrap();
343 let verifying_key = VerifyingKey::from(&signing_key);
344 let mut grant = SourceGrant::new(
345 "https://attacker.example/data".into(),
346 "LicenseRef-MIT".into(),
347 GrantPermissions::READ,
348 "Test authority".into(),
349 );
350 grant.sign(&signing_key);
351 assert!(grant.verify_signature(&verifying_key).is_ok());
352 assert!(grant.verify_license(&["MIT"]).is_err());
353
354 let mut substituted = grant.clone();
355 substituted.source_uri.push_str("LicenseRef-");
356 substituted.license_spdx = "MIT".into();
357 assert!(substituted.verify_license(&["MIT"]).is_ok());
358 assert!(matches!(
359 substituted.verify_signature(&verifying_key),
360 Err(ProvenanceError::SignatureVerificationFailed(_))
361 ));
362 assert!(matches!(
363 substituted.verify_all(GrantPermissions::READ, &["MIT"], 0, Some(&verifying_key)),
364 Err(ProvenanceError::SignatureVerificationFailed(_))
365 ));
366
367 // A signature over the retired, ambiguous transcript is never accepted.
368 let mut old = Sha256::new();
369 old.update(grant.grant_id.as_bytes());
370 old.update(grant.source_uri.as_bytes());
371 old.update(grant.license_spdx.as_bytes());
372 old.update(grant.permissions.bits().to_le_bytes());
373 old.update(grant.issuer.as_bytes());
374 old.update(b"exp:none");
375 let old_signature: Signature = signing_key.sign(&old.finalize());
376 grant.issuer_signature = Some(old_signature.to_bytes().to_vec());
377 assert!(matches!(
378 grant.verify_signature(&verifying_key),
379 Err(ProvenanceError::SignatureVerificationFailed(_))
380 ));
381 }
382}