aien-protocols-mv
Canonical specifications, wire protocols, and schemas for the AIEN sovereign ecosystem
Brought by drakestapleton
aien-protocols-mv / crates / aien-discovery-capsule / src / lib.rs
| 1 | //! The DCP1 family: Discovery Capsule, owner consent, signed retraction, |
| 2 | //! retraction acknowledgement and experience lineage. |
| 3 | //! |
| 4 | //! Spec: `specs/discovery-capsule/SPEC.md` (Draft v0.1, contract 0.1.0, wire |
| 5 | //! version 1). The C reference checker `specs/discovery-capsule/tools/dcp_verify.c` |
| 6 | //! pins the static rules (section 10); [`decode`] gives the same verdict on |
| 7 | //! the same bytes (`tests/vectors.rs`). Signatures and the stateful recipient |
| 8 | //! rules of section 11 live here and in [`recipient`]. |
| 9 | //! |
| 10 | //! A capsule never authorizes itself: nothing in this crate turns a capsule |
| 11 | //! into a grant. [`recipient::admit_execution`] needs the recipient's own |
| 12 | //! passing verdict and the recipient's own capability grant. |
| 13 | #![forbid(unsafe_code)] |
| 14 | |
| 15 | pub mod recipient; |
| 16 | |
| 17 | use aien_provenance::{p256_compressed_key, p256_sign_low_s, p256_verify_low_s}; |
| 18 | use p256::ecdsa::SigningKey; |
| 19 | use sha2::{Digest, Sha256}; |
| 20 | |
| 21 | /// The only wire version. |
| 22 | pub const VERSION: u8 = 1; |
| 23 | /// Record lengths (SPEC.md section 1). |
| 24 | pub const CAPSULE_LEN: usize = 676; |
| 25 | pub const CONSENT_LEN: usize = 388; |
| 26 | pub const RETRACTION_LEN: usize = 284; |
| 27 | pub const ACK_LEN: usize = 148; |
| 28 | pub const LINEAGE_LEN: usize = 588; |
| 29 | |
| 30 | /// `share_scope` values. |
| 31 | pub mod scope { |
| 32 | pub const PRIVATE: u8 = 0; |
| 33 | pub const NAMED: u8 = 1; |
| 34 | pub const COMMUNITY: u8 = 2; |
| 35 | pub const PUBLIC: u8 = 3; |
| 36 | } |
| 37 | /// `permissions` / `purposes` bits. |
| 38 | pub mod perm { |
| 39 | pub const DISCOVER: u8 = 0x01; |
| 40 | pub const READ: u8 = 0x02; |
| 41 | pub const REDISTRIBUTE: u8 = 0x04; |
| 42 | pub const TRAIN: u8 = 0x08; |
| 43 | pub const ALL: u8 = 0x0F; |
| 44 | } |
| 45 | /// Retraction `scope` bits. |
| 46 | pub mod retract { |
| 47 | pub const FUTURE_AVAILABILITY: u8 = 0x01; |
| 48 | pub const RETRIEVAL: u8 = 0x02; |
| 49 | pub const TRAINING: u8 = 0x04; |
| 50 | pub const REPUBLICATION: u8 = 0x08; |
| 51 | pub const ALL: u8 = 0x0F; |
| 52 | } |
| 53 | /// `required_capabilities` bits (a request, never a grant). |
| 54 | pub mod cap { |
| 55 | pub const CPU_COMPUTE: u32 = 1 << 0; |
| 56 | pub const GPU_COMPUTE: u32 = 1 << 1; |
| 57 | pub const CORTEX_READ: u32 = 1 << 2; |
| 58 | pub const WORLD_READ: u32 = 1 << 3; |
| 59 | pub const WORLD_EFFECT: u32 = 1 << 4; |
| 60 | pub const NETWORK: u32 = 1 << 5; |
| 61 | pub const ALL: u32 = 0x3F; |
| 62 | } |
| 63 | /// `license` registry. |
| 64 | pub mod license { |
| 65 | pub const APACHE_2_0: u16 = 1; |
| 66 | pub const MIT: u16 = 2; |
| 67 | pub const CC_BY_4_0: u16 = 3; |
| 68 | pub const CC_BY_SA_4_0: u16 = 4; |
| 69 | pub const CDLA_PERMISSIVE_2_0: u16 = 5; |
| 70 | pub const OWNER_CONSENT_ONLY: u16 = 6; |
| 71 | } |
| 72 | /// Ack `status` values. |
| 73 | pub mod ack_status { |
| 74 | pub const ENFORCED: u8 = 1; |
| 75 | pub const ENFORCED_WITH_RETAINED: u8 = 2; |
| 76 | } |
| 77 | |
| 78 | /// A refusal code from SPEC.md section 12. |
| 79 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 80 | pub enum Refusal { |
| 81 | BadLength, |
| 82 | BadMagic, |
| 83 | Downgrade, |
| 84 | BadVersion, |
| 85 | ReservedNonzero, |
| 86 | BadEnum, |
| 87 | UnknownLicense, |
| 88 | FalseErasureClaim, |
| 89 | MissingField, |
| 90 | BadKey, |
| 91 | BadValidity, |
| 92 | Inconsistent, |
| 93 | ScopeConflict, |
| 94 | PermissionAmplification, |
| 95 | NoConsent, |
| 96 | AncestorCycle, |
| 97 | Duplicate, |
| 98 | BadSignature, |
| 99 | OwnerMismatch, |
| 100 | Private, |
| 101 | NotRecipient, |
| 102 | Expired, |
| 103 | Stale, |
| 104 | Revoked, |
| 105 | NotPermitted, |
| 106 | Conflict, |
| 107 | UnknownCustodian, |
| 108 | SelfAuthorized, |
| 109 | Unverified, |
| 110 | CapabilityDenied, |
| 111 | CrossDataset, |
| 112 | UnknownParent, |
| 113 | } |
| 114 | |
| 115 | impl Refusal { |
| 116 | /// The code name as written in SPEC.md and printed by the C checker. |
| 117 | pub fn name(self) -> &'static str { |
| 118 | match self { |
| 119 | Refusal::BadLength => "DCP_BAD_LENGTH", |
| 120 | Refusal::BadMagic => "DCP_BAD_MAGIC", |
| 121 | Refusal::Downgrade => "DCP_DOWNGRADE", |
| 122 | Refusal::BadVersion => "DCP_BAD_VERSION", |
| 123 | Refusal::ReservedNonzero => "DCP_RESERVED_NONZERO", |
| 124 | Refusal::BadEnum => "DCP_BAD_ENUM", |
| 125 | Refusal::UnknownLicense => "DCP_UNKNOWN_LICENSE", |
| 126 | Refusal::FalseErasureClaim => "DCP_FALSE_ERASURE_CLAIM", |
| 127 | Refusal::MissingField => "DCP_MISSING_FIELD", |
| 128 | Refusal::BadKey => "DCP_BAD_KEY", |
| 129 | Refusal::BadValidity => "DCP_BAD_VALIDITY", |
| 130 | Refusal::Inconsistent => "DCP_INCONSISTENT", |
| 131 | Refusal::ScopeConflict => "DCP_SCOPE_CONFLICT", |
| 132 | Refusal::PermissionAmplification => "DCP_PERMISSION_AMPLIFICATION", |
| 133 | Refusal::NoConsent => "DCP_NO_CONSENT", |
| 134 | Refusal::AncestorCycle => "DCP_ANCESTOR_CYCLE", |
| 135 | Refusal::Duplicate => "DCP_DUPLICATE", |
| 136 | Refusal::BadSignature => "DCP_BAD_SIGNATURE", |
| 137 | Refusal::OwnerMismatch => "DCP_OWNER_MISMATCH", |
| 138 | Refusal::Private => "DCP_PRIVATE", |
| 139 | Refusal::NotRecipient => "DCP_NOT_RECIPIENT", |
| 140 | Refusal::Expired => "DCP_EXPIRED", |
| 141 | Refusal::Stale => "DCP_STALE", |
| 142 | Refusal::Revoked => "DCP_REVOKED", |
| 143 | Refusal::NotPermitted => "DCP_NOT_PERMITTED", |
| 144 | Refusal::Conflict => "DCP_CONFLICT", |
| 145 | Refusal::UnknownCustodian => "DCP_UNKNOWN_CUSTODIAN", |
| 146 | Refusal::SelfAuthorized => "DCP_SELF_AUTHORIZED", |
| 147 | Refusal::Unverified => "DCP_UNVERIFIED", |
| 148 | Refusal::CapabilityDenied => "DCP_CAPABILITY_DENIED", |
| 149 | Refusal::CrossDataset => "DCP_CROSS_DATASET", |
| 150 | Refusal::UnknownParent => "DCP_UNKNOWN_PARENT", |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | /// `DiscoveryCapsuleV1` (section 5). |
| 156 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 157 | pub struct Capsule { |
| 158 | pub share_scope: u8, |
| 159 | pub permissions: u8, |
| 160 | pub precision: u8, |
| 161 | pub license: u16, |
| 162 | pub failure_count: u16, |
| 163 | pub abi_version: u32, |
| 164 | pub required_capabilities: u32, |
| 165 | pub precondition_rank: u8, |
| 166 | pub precondition_dims: [u32; 4], |
| 167 | pub valid_from: u64, |
| 168 | pub expires_at: u64, |
| 169 | pub revocation_seq: u64, |
| 170 | pub meaning_digest: [u8; 32], |
| 171 | pub source_digest: [u8; 32], |
| 172 | pub compiler_digest: [u8; 32], |
| 173 | pub executable_digest: [u8; 32], |
| 174 | pub preconditions_digest: [u8; 32], |
| 175 | pub verifier_ref: [u8; 32], |
| 176 | pub evidence_digest: [u8; 32], |
| 177 | pub failure_cases_digest: [u8; 32], |
| 178 | pub utility_verdict_ref: [u8; 32], |
| 179 | pub science_verdict_ref: [u8; 32], |
| 180 | pub recipient_policy_digest: [u8; 32], |
| 181 | pub recipient_set_digest: [u8; 32], |
| 182 | pub consent_ref: [u8; 32], |
| 183 | pub revocation_head: [u8; 32], |
| 184 | pub parent_capsule: [u8; 32], |
| 185 | pub microjob_ref: [u8; 32], |
| 186 | pub owner_key: [u8; 33], |
| 187 | pub signature: [u8; 64], |
| 188 | } |
| 189 | |
| 190 | /// `OwnerConsentV1` (section 6). `custodians` holds the used slots. |
| 191 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 192 | pub struct Consent { |
| 193 | pub purposes: u8, |
| 194 | pub consent_version: u32, |
| 195 | pub notice_seconds: u32, |
| 196 | pub issued_at: u64, |
| 197 | pub retention_end: u64, |
| 198 | pub provenance_digest: [u8; 32], |
| 199 | pub recipient_digest: [u8; 32], |
| 200 | pub fragment_digest: [u8; 32], |
| 201 | pub payload_digest: [u8; 32], |
| 202 | pub custodians: Vec<[u8; 32]>, |
| 203 | pub owner_key: [u8; 33], |
| 204 | pub signature: [u8; 64], |
| 205 | } |
| 206 | |
| 207 | /// `OwnerRetractionV1` (section 7). `erasure_claim` is always written as 0. |
| 208 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 209 | pub struct Retraction { |
| 210 | pub scope: u8, |
| 211 | pub seq: u64, |
| 212 | pub effective_at: u64, |
| 213 | pub target_digest: [u8; 32], |
| 214 | pub prev_retraction: [u8; 32], |
| 215 | pub provenance_digest: [u8; 32], |
| 216 | pub tombstone_digest: [u8; 32], |
| 217 | pub owner_key: [u8; 33], |
| 218 | pub signer_key: [u8; 33], |
| 219 | pub signature: [u8; 64], |
| 220 | } |
| 221 | |
| 222 | /// `RetractionAckV1` (section 8). |
| 223 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 224 | pub struct Ack { |
| 225 | pub status: u8, |
| 226 | pub acked_at: u64, |
| 227 | pub retraction_digest: [u8; 32], |
| 228 | pub recipient_key: [u8; 33], |
| 229 | pub signature: [u8; 64], |
| 230 | } |
| 231 | |
| 232 | /// `ExperienceLineageV1` (section 9). `parents` and `influenced` hold the |
| 233 | /// used slots. |
| 234 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 235 | pub struct Lineage { |
| 236 | pub content_digest: [u8; 32], |
| 237 | pub dataset_id: [u8; 32], |
| 238 | pub consent_ref: [u8; 32], |
| 239 | pub parents: Vec<[u8; 32]>, |
| 240 | pub influenced: Vec<[u8; 32]>, |
| 241 | pub owner_key: [u8; 33], |
| 242 | pub signature: [u8; 64], |
| 243 | } |
| 244 | |
| 245 | /// Any record of the family. |
| 246 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 247 | // Records are decoded once and moved into `Verified`; boxing the capsule |
| 248 | // would add a heap allocation per decode for no gain. |
| 249 | #[allow(clippy::large_enum_variant)] |
| 250 | pub enum Record { |
| 251 | Capsule(Capsule), |
| 252 | Consent(Consent), |
| 253 | Retraction(Retraction), |
| 254 | Ack(Ack), |
| 255 | Lineage(Lineage), |
| 256 | } |
| 257 | |
| 258 | fn u16_at(b: &[u8], at: usize) -> u16 { |
| 259 | u16::from_be_bytes([b[at], b[at + 1]]) |
| 260 | } |
| 261 | fn u32_at(b: &[u8], at: usize) -> u32 { |
| 262 | u32::from_be_bytes(arr(b, at)) |
| 263 | } |
| 264 | fn u64_at(b: &[u8], at: usize) -> u64 { |
| 265 | u64::from_be_bytes(arr(b, at)) |
| 266 | } |
| 267 | fn arr<const N: usize>(b: &[u8], at: usize) -> [u8; N] { |
| 268 | let mut out = [0u8; N]; |
| 269 | out.copy_from_slice(&b[at..at + N]); |
| 270 | out |
| 271 | } |
| 272 | fn z(b: &[u8]) -> bool { |
| 273 | b.iter().all(|&x| x == 0) |
| 274 | } |
| 275 | fn z32(b: &[u8], at: usize) -> bool { |
| 276 | z(&b[at..at + 32]) |
| 277 | } |
| 278 | fn key_ok(b: &[u8], at: usize) -> bool { |
| 279 | b[at] == 0x02 || b[at] == 0x03 |
| 280 | } |
| 281 | |
| 282 | /// Length, signing-key offset and signature offset of a record type. |
| 283 | fn layout(magic: &[u8]) -> Option<(usize, usize, usize)> { |
| 284 | match magic { |
| 285 | b"DCP1" => Some((CAPSULE_LEN, 576, 612)), |
| 286 | b"DCC1" => Some((CONSENT_LEN, 288, 324)), |
| 287 | b"DCR1" => Some((RETRACTION_LEN, 185, 220)), |
| 288 | b"DCA1" => Some((ACK_LEN, 48, 84)), |
| 289 | b"DCL1" => Some((LINEAGE_LEN, 488, 524)), |
| 290 | _ => None, |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | /// Decode and check one record against the static rules of SPEC.md section |
| 295 | /// 10, in the same order as the C checker. Signatures are not checked here |
| 296 | /// (see [`open`]). |
| 297 | pub fn decode(b: &[u8]) -> Result<Record, Refusal> { |
| 298 | if b.len() < 5 { |
| 299 | return Err(Refusal::BadLength); |
| 300 | } |
| 301 | let (len, _, _) = layout(&b[0..4]).ok_or(Refusal::BadMagic)?; |
| 302 | if b[4] == 0 { |
| 303 | return Err(Refusal::Downgrade); |
| 304 | } |
| 305 | if b[4] > VERSION { |
| 306 | return Err(Refusal::BadVersion); |
| 307 | } |
| 308 | if b.len() != len { |
| 309 | return Err(Refusal::BadLength); |
| 310 | } |
| 311 | match &b[0..4] { |
| 312 | b"DCP1" => check_capsule(b).map(Record::Capsule), |
| 313 | b"DCC1" => check_consent(b).map(Record::Consent), |
| 314 | b"DCR1" => check_retraction(b).map(Record::Retraction), |
| 315 | b"DCA1" => check_ack(b).map(Record::Ack), |
| 316 | _ => check_lineage(b).map(Record::Lineage), |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | fn check_capsule(b: &[u8]) -> Result<Capsule, Refusal> { |
| 321 | let rank = b[20] as usize; |
| 322 | let dims_bad = (rank.min(4)..4).any(|d| u32_at(b, 24 + 4 * d) != 0); |
| 323 | if !z(&b[21..24]) || !z(&b[609..612]) || dims_bad { |
| 324 | return Err(Refusal::ReservedNonzero); |
| 325 | } |
| 326 | let caps = u32_at(b, 16); |
| 327 | if b[5] > scope::PUBLIC |
| 328 | || b[6] & !perm::ALL != 0 |
| 329 | || b[7] > 6 |
| 330 | || caps & !cap::ALL != 0 |
| 331 | || rank > 4 |
| 332 | { |
| 333 | return Err(Refusal::BadEnum); |
| 334 | } |
| 335 | let lic = u16_at(b, 8); |
| 336 | if !(1..=6).contains(&lic) { |
| 337 | return Err(Refusal::UnknownLicense); |
| 338 | } |
| 339 | if u32_at(b, 12) == 0 || (64..288).step_by(32).any(|at| z32(b, at)) || z32(b, 384) { |
| 340 | return Err(Refusal::MissingField); |
| 341 | } |
| 342 | if !key_ok(b, 576) { |
| 343 | return Err(Refusal::BadKey); |
| 344 | } |
| 345 | let (from, until) = (u64_at(b, 40), u64_at(b, 48)); |
| 346 | if from == 0 || until <= from { |
| 347 | return Err(Refusal::BadValidity); |
| 348 | } |
| 349 | if (u16_at(b, 10) != 0) == z32(b, 288) || (u64_at(b, 56) != 0) == z32(b, 480) { |
| 350 | return Err(Refusal::Inconsistent); |
| 351 | } |
| 352 | let (sc, perms) = (b[5], b[6]); |
| 353 | if (sc == scope::PRIVATE && perms != 0) || ((sc == scope::NAMED) == z32(b, 416)) { |
| 354 | return Err(Refusal::ScopeConflict); |
| 355 | } |
| 356 | if perms & (perm::REDISTRIBUTE | perm::TRAIN) != 0 && perms & perm::READ == 0 { |
| 357 | return Err(Refusal::PermissionAmplification); |
| 358 | } |
| 359 | let needs_consent = |
| 360 | perms & (perm::READ | perm::REDISTRIBUTE | perm::TRAIN) != 0 || sc != scope::PRIVATE; |
| 361 | if needs_consent && z32(b, 448) { |
| 362 | return Err(Refusal::NoConsent); |
| 363 | } |
| 364 | Ok(Capsule { |
| 365 | share_scope: sc, |
| 366 | permissions: perms, |
| 367 | precision: b[7], |
| 368 | license: lic, |
| 369 | failure_count: u16_at(b, 10), |
| 370 | abi_version: u32_at(b, 12), |
| 371 | required_capabilities: caps, |
| 372 | precondition_rank: b[20], |
| 373 | precondition_dims: [u32_at(b, 24), u32_at(b, 28), u32_at(b, 32), u32_at(b, 36)], |
| 374 | valid_from: from, |
| 375 | expires_at: until, |
| 376 | revocation_seq: u64_at(b, 56), |
| 377 | meaning_digest: arr(b, 64), |
| 378 | source_digest: arr(b, 96), |
| 379 | compiler_digest: arr(b, 128), |
| 380 | executable_digest: arr(b, 160), |
| 381 | preconditions_digest: arr(b, 192), |
| 382 | verifier_ref: arr(b, 224), |
| 383 | evidence_digest: arr(b, 256), |
| 384 | failure_cases_digest: arr(b, 288), |
| 385 | utility_verdict_ref: arr(b, 320), |
| 386 | science_verdict_ref: arr(b, 352), |
| 387 | recipient_policy_digest: arr(b, 384), |
| 388 | recipient_set_digest: arr(b, 416), |
| 389 | consent_ref: arr(b, 448), |
| 390 | revocation_head: arr(b, 480), |
| 391 | parent_capsule: arr(b, 512), |
| 392 | microjob_ref: arr(b, 544), |
| 393 | owner_key: arr(b, 576), |
| 394 | signature: arr(b, 612), |
| 395 | }) |
| 396 | } |
| 397 | |
| 398 | fn check_consent(b: &[u8]) -> Result<Consent, Refusal> { |
| 399 | let n = b[6] as usize; |
| 400 | let slots_bad = (n.min(4)..4).any(|s| !z32(b, 160 + 32 * s)); |
| 401 | if b[7] != 0 || !z(&b[321..324]) || slots_bad { |
| 402 | return Err(Refusal::ReservedNonzero); |
| 403 | } |
| 404 | if b[5] == 0 || b[5] & !perm::ALL != 0 || n > 4 { |
| 405 | return Err(Refusal::BadEnum); |
| 406 | } |
| 407 | if u32_at(b, 8) == 0 |
| 408 | || [32, 64, 96, 128].iter().any(|&at| z32(b, at)) |
| 409 | || (0..n).any(|s| z32(b, 160 + 32 * s)) |
| 410 | { |
| 411 | return Err(Refusal::MissingField); |
| 412 | } |
| 413 | if !key_ok(b, 288) { |
| 414 | return Err(Refusal::BadKey); |
| 415 | } |
| 416 | let (issued, until) = (u64_at(b, 16), u64_at(b, 24)); |
| 417 | if issued == 0 || until <= issued { |
| 418 | return Err(Refusal::BadValidity); |
| 419 | } |
| 420 | if b[5] & (perm::REDISTRIBUTE | perm::TRAIN) != 0 && b[5] & perm::READ == 0 { |
| 421 | return Err(Refusal::PermissionAmplification); |
| 422 | } |
| 423 | Ok(Consent { |
| 424 | purposes: b[5], |
| 425 | consent_version: u32_at(b, 8), |
| 426 | notice_seconds: u32_at(b, 12), |
| 427 | issued_at: issued, |
| 428 | retention_end: until, |
| 429 | provenance_digest: arr(b, 32), |
| 430 | recipient_digest: arr(b, 64), |
| 431 | fragment_digest: arr(b, 96), |
| 432 | payload_digest: arr(b, 128), |
| 433 | custodians: (0..n).map(|s| arr(b, 160 + 32 * s)).collect(), |
| 434 | owner_key: arr(b, 288), |
| 435 | signature: arr(b, 324), |
| 436 | }) |
| 437 | } |
| 438 | |
| 439 | fn check_retraction(b: &[u8]) -> Result<Retraction, Refusal> { |
| 440 | if b[7] != 0 || !z(&b[218..220]) { |
| 441 | return Err(Refusal::ReservedNonzero); |
| 442 | } |
| 443 | if b[5] == 0 || b[5] & !retract::ALL != 0 { |
| 444 | return Err(Refusal::BadEnum); |
| 445 | } |
| 446 | if b[6] != 0 { |
| 447 | return Err(Refusal::FalseErasureClaim); |
| 448 | } |
| 449 | let seq = u64_at(b, 8); |
| 450 | if seq == 0 || z32(b, 24) || z32(b, 88) || z32(b, 120) { |
| 451 | return Err(Refusal::MissingField); |
| 452 | } |
| 453 | if !key_ok(b, 152) || !key_ok(b, 185) { |
| 454 | return Err(Refusal::BadKey); |
| 455 | } |
| 456 | if u64_at(b, 16) == 0 { |
| 457 | return Err(Refusal::BadValidity); |
| 458 | } |
| 459 | if (seq == 1) != z32(b, 56) { |
| 460 | return Err(Refusal::Inconsistent); |
| 461 | } |
| 462 | Ok(Retraction { |
| 463 | scope: b[5], |
| 464 | seq, |
| 465 | effective_at: u64_at(b, 16), |
| 466 | target_digest: arr(b, 24), |
| 467 | prev_retraction: arr(b, 56), |
| 468 | provenance_digest: arr(b, 88), |
| 469 | tombstone_digest: arr(b, 120), |
| 470 | owner_key: arr(b, 152), |
| 471 | signer_key: arr(b, 185), |
| 472 | signature: arr(b, 220), |
| 473 | }) |
| 474 | } |
| 475 | |
| 476 | fn check_ack(b: &[u8]) -> Result<Ack, Refusal> { |
| 477 | if !z(&b[6..8]) || !z(&b[81..84]) { |
| 478 | return Err(Refusal::ReservedNonzero); |
| 479 | } |
| 480 | if !(1..=2).contains(&b[5]) { |
| 481 | return Err(Refusal::BadEnum); |
| 482 | } |
| 483 | if z32(b, 16) { |
| 484 | return Err(Refusal::MissingField); |
| 485 | } |
| 486 | if !key_ok(b, 48) { |
| 487 | return Err(Refusal::BadKey); |
| 488 | } |
| 489 | if u64_at(b, 8) == 0 { |
| 490 | return Err(Refusal::BadValidity); |
| 491 | } |
| 492 | Ok(Ack { |
| 493 | status: b[5], |
| 494 | acked_at: u64_at(b, 8), |
| 495 | retraction_digest: arr(b, 16), |
| 496 | recipient_key: arr(b, 48), |
| 497 | signature: arr(b, 84), |
| 498 | }) |
| 499 | } |
| 500 | |
| 501 | fn check_lineage(b: &[u8]) -> Result<Lineage, Refusal> { |
| 502 | let (np, ni) = (b[5] as usize, b[6] as usize); |
| 503 | let parents_bad = (np.min(4)..4).any(|s| !z32(b, 104 + 32 * s)); |
| 504 | let infl_bad = (ni.min(8)..8).any(|s| !z32(b, 232 + 32 * s)); |
| 505 | if b[7] != 0 || !z(&b[521..524]) || parents_bad || infl_bad { |
| 506 | return Err(Refusal::ReservedNonzero); |
| 507 | } |
| 508 | if np > 4 || ni > 8 { |
| 509 | return Err(Refusal::BadEnum); |
| 510 | } |
| 511 | if z32(b, 8) |
| 512 | || z32(b, 40) |
| 513 | || z32(b, 72) |
| 514 | || (0..np).any(|s| z32(b, 104 + 32 * s)) |
| 515 | || (0..ni).any(|s| z32(b, 232 + 32 * s)) |
| 516 | { |
| 517 | return Err(Refusal::MissingField); |
| 518 | } |
| 519 | if !key_ok(b, 488) { |
| 520 | return Err(Refusal::BadKey); |
| 521 | } |
| 522 | let parents: Vec<[u8; 32]> = (0..np).map(|s| arr(b, 104 + 32 * s)).collect(); |
| 523 | let content: [u8; 32] = arr(b, 8); |
| 524 | if parents.contains(&content) { |
| 525 | return Err(Refusal::AncestorCycle); |
| 526 | } |
| 527 | for i in 0..np { |
| 528 | if parents[i + 1..].contains(&parents[i]) { |
| 529 | return Err(Refusal::Duplicate); |
| 530 | } |
| 531 | } |
| 532 | Ok(Lineage { |
| 533 | content_digest: content, |
| 534 | dataset_id: arr(b, 40), |
| 535 | consent_ref: arr(b, 72), |
| 536 | parents, |
| 537 | influenced: (0..ni).map(|s| arr(b, 232 + 32 * s)).collect(), |
| 538 | owner_key: arr(b, 488), |
| 539 | signature: arr(b, 524), |
| 540 | }) |
| 541 | } |
| 542 | |
| 543 | fn put32(b: &mut [u8], at: usize, v: &[u8; 32]) { |
| 544 | b[at..at + 32].copy_from_slice(v); |
| 545 | } |
| 546 | |
| 547 | impl Capsule { |
| 548 | /// Write the record, signature included. |
| 549 | pub fn encode(&self) -> Vec<u8> { |
| 550 | let mut b = vec![0u8; CAPSULE_LEN]; |
| 551 | b[0..4].copy_from_slice(b"DCP1"); |
| 552 | b[4] = VERSION; |
| 553 | b[5] = self.share_scope; |
| 554 | b[6] = self.permissions; |
| 555 | b[7] = self.precision; |
| 556 | b[8..10].copy_from_slice(&self.license.to_be_bytes()); |
| 557 | b[10..12].copy_from_slice(&self.failure_count.to_be_bytes()); |
| 558 | b[12..16].copy_from_slice(&self.abi_version.to_be_bytes()); |
| 559 | b[16..20].copy_from_slice(&self.required_capabilities.to_be_bytes()); |
| 560 | b[20] = self.precondition_rank; |
| 561 | for (d, v) in self.precondition_dims.iter().enumerate() { |
| 562 | b[24 + 4 * d..28 + 4 * d].copy_from_slice(&v.to_be_bytes()); |
| 563 | } |
| 564 | b[40..48].copy_from_slice(&self.valid_from.to_be_bytes()); |
| 565 | b[48..56].copy_from_slice(&self.expires_at.to_be_bytes()); |
| 566 | b[56..64].copy_from_slice(&self.revocation_seq.to_be_bytes()); |
| 567 | let digests = [ |
| 568 | &self.meaning_digest, |
| 569 | &self.source_digest, |
| 570 | &self.compiler_digest, |
| 571 | &self.executable_digest, |
| 572 | &self.preconditions_digest, |
| 573 | &self.verifier_ref, |
| 574 | &self.evidence_digest, |
| 575 | &self.failure_cases_digest, |
| 576 | &self.utility_verdict_ref, |
| 577 | &self.science_verdict_ref, |
| 578 | &self.recipient_policy_digest, |
| 579 | &self.recipient_set_digest, |
| 580 | &self.consent_ref, |
| 581 | &self.revocation_head, |
| 582 | &self.parent_capsule, |
| 583 | &self.microjob_ref, |
| 584 | ]; |
| 585 | for (k, d) in digests.iter().enumerate() { |
| 586 | put32(&mut b, 64 + 32 * k, d); |
| 587 | } |
| 588 | b[576..609].copy_from_slice(&self.owner_key); |
| 589 | b[612..676].copy_from_slice(&self.signature); |
| 590 | b |
| 591 | } |
| 592 | |
| 593 | /// Set `owner_key` from `key` and sign. |
| 594 | pub fn sign(&mut self, key: &SigningKey) { |
| 595 | self.owner_key = p256_compressed_key(key); |
| 596 | self.signature = p256_sign_low_s(key, &self.encode()[..612]); |
| 597 | } |
| 598 | |
| 599 | /// `record_digest` (signature excluded). |
| 600 | pub fn digest(&self) -> [u8; 32] { |
| 601 | record_digest(&self.encode()) |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | impl Consent { |
| 606 | /// Write the record, signature included. |
| 607 | pub fn encode(&self) -> Vec<u8> { |
| 608 | let mut b = vec![0u8; CONSENT_LEN]; |
| 609 | b[0..4].copy_from_slice(b"DCC1"); |
| 610 | b[4] = VERSION; |
| 611 | b[5] = self.purposes; |
| 612 | b[6] = self.custodians.len() as u8; |
| 613 | b[8..12].copy_from_slice(&self.consent_version.to_be_bytes()); |
| 614 | b[12..16].copy_from_slice(&self.notice_seconds.to_be_bytes()); |
| 615 | b[16..24].copy_from_slice(&self.issued_at.to_be_bytes()); |
| 616 | b[24..32].copy_from_slice(&self.retention_end.to_be_bytes()); |
| 617 | put32(&mut b, 32, &self.provenance_digest); |
| 618 | put32(&mut b, 64, &self.recipient_digest); |
| 619 | put32(&mut b, 96, &self.fragment_digest); |
| 620 | put32(&mut b, 128, &self.payload_digest); |
| 621 | for (s, c) in self.custodians.iter().take(4).enumerate() { |
| 622 | put32(&mut b, 160 + 32 * s, c); |
| 623 | } |
| 624 | b[288..321].copy_from_slice(&self.owner_key); |
| 625 | b[324..388].copy_from_slice(&self.signature); |
| 626 | b |
| 627 | } |
| 628 | |
| 629 | /// Set `owner_key` from `key` and sign. |
| 630 | pub fn sign(&mut self, key: &SigningKey) { |
| 631 | self.owner_key = p256_compressed_key(key); |
| 632 | self.signature = p256_sign_low_s(key, &self.encode()[..324]); |
| 633 | } |
| 634 | |
| 635 | /// `record_digest` (signature excluded). |
| 636 | pub fn digest(&self) -> [u8; 32] { |
| 637 | record_digest(&self.encode()) |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | impl Retraction { |
| 642 | /// Write the record, signature included (`erasure_claim` is 0). |
| 643 | pub fn encode(&self) -> Vec<u8> { |
| 644 | let mut b = vec![0u8; RETRACTION_LEN]; |
| 645 | b[0..4].copy_from_slice(b"DCR1"); |
| 646 | b[4] = VERSION; |
| 647 | b[5] = self.scope; |
| 648 | b[8..16].copy_from_slice(&self.seq.to_be_bytes()); |
| 649 | b[16..24].copy_from_slice(&self.effective_at.to_be_bytes()); |
| 650 | put32(&mut b, 24, &self.target_digest); |
| 651 | put32(&mut b, 56, &self.prev_retraction); |
| 652 | put32(&mut b, 88, &self.provenance_digest); |
| 653 | put32(&mut b, 120, &self.tombstone_digest); |
| 654 | b[152..185].copy_from_slice(&self.owner_key); |
| 655 | b[185..218].copy_from_slice(&self.signer_key); |
| 656 | b[220..284].copy_from_slice(&self.signature); |
| 657 | b |
| 658 | } |
| 659 | |
| 660 | /// Set `signer_key` from `key` and sign (`owner_key` is left as set). |
| 661 | pub fn sign(&mut self, key: &SigningKey) { |
| 662 | self.signer_key = p256_compressed_key(key); |
| 663 | self.signature = p256_sign_low_s(key, &self.encode()[..220]); |
| 664 | } |
| 665 | |
| 666 | /// `record_digest` (signature excluded). |
| 667 | pub fn digest(&self) -> [u8; 32] { |
| 668 | record_digest(&self.encode()) |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | impl Ack { |
| 673 | /// Write the record, signature included. |
| 674 | pub fn encode(&self) -> Vec<u8> { |
| 675 | let mut b = vec![0u8; ACK_LEN]; |
| 676 | b[0..4].copy_from_slice(b"DCA1"); |
| 677 | b[4] = VERSION; |
| 678 | b[5] = self.status; |
| 679 | b[8..16].copy_from_slice(&self.acked_at.to_be_bytes()); |
| 680 | put32(&mut b, 16, &self.retraction_digest); |
| 681 | b[48..81].copy_from_slice(&self.recipient_key); |
| 682 | b[84..148].copy_from_slice(&self.signature); |
| 683 | b |
| 684 | } |
| 685 | |
| 686 | /// Set `recipient_key` from `key` and sign. |
| 687 | pub fn sign(&mut self, key: &SigningKey) { |
| 688 | self.recipient_key = p256_compressed_key(key); |
| 689 | self.signature = p256_sign_low_s(key, &self.encode()[..84]); |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | impl Lineage { |
| 694 | /// Write the record, signature included. |
| 695 | pub fn encode(&self) -> Vec<u8> { |
| 696 | let mut b = vec![0u8; LINEAGE_LEN]; |
| 697 | b[0..4].copy_from_slice(b"DCL1"); |
| 698 | b[4] = VERSION; |
| 699 | b[5] = self.parents.len() as u8; |
| 700 | b[6] = self.influenced.len() as u8; |
| 701 | put32(&mut b, 8, &self.content_digest); |
| 702 | put32(&mut b, 40, &self.dataset_id); |
| 703 | put32(&mut b, 72, &self.consent_ref); |
| 704 | for (s, p) in self.parents.iter().take(4).enumerate() { |
| 705 | put32(&mut b, 104 + 32 * s, p); |
| 706 | } |
| 707 | for (s, p) in self.influenced.iter().take(8).enumerate() { |
| 708 | put32(&mut b, 232 + 32 * s, p); |
| 709 | } |
| 710 | b[488..521].copy_from_slice(&self.owner_key); |
| 711 | b[524..588].copy_from_slice(&self.signature); |
| 712 | b |
| 713 | } |
| 714 | |
| 715 | /// Set `owner_key` from `key` and sign. |
| 716 | pub fn sign(&mut self, key: &SigningKey) { |
| 717 | self.owner_key = p256_compressed_key(key); |
| 718 | self.signature = p256_sign_low_s(key, &self.encode()[..524]); |
| 719 | } |
| 720 | } |
| 721 | |
| 722 | impl Record { |
| 723 | /// Write the record, signature included. |
| 724 | pub fn encode(&self) -> Vec<u8> { |
| 725 | match self { |
| 726 | Record::Capsule(x) => x.encode(), |
| 727 | Record::Consent(x) => x.encode(), |
| 728 | Record::Retraction(x) => x.encode(), |
| 729 | Record::Ack(x) => x.encode(), |
| 730 | Record::Lineage(x) => x.encode(), |
| 731 | } |
| 732 | } |
| 733 | } |
| 734 | |
| 735 | /// `record_digest`: SHA-256 of every byte before the signature. `bytes` |
| 736 | /// must be a record of known type and length. |
| 737 | pub fn record_digest(bytes: &[u8]) -> [u8; 32] { |
| 738 | let (_, _, sig) = layout(&bytes[0..4]).expect("record of a known type"); |
| 739 | Sha256::digest(&bytes[..sig]).into() |
| 740 | } |
| 741 | |
| 742 | /// A record whose static rules and signature both passed. Only [`open`] |
| 743 | /// makes one, so a recipient rule can never be fed unchecked fields. |
| 744 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 745 | pub struct Verified<T> { |
| 746 | inner: T, |
| 747 | digest: [u8; 32], |
| 748 | } |
| 749 | |
| 750 | impl<T> Verified<T> { |
| 751 | /// The checked record. |
| 752 | pub fn get(&self) -> &T { |
| 753 | &self.inner |
| 754 | } |
| 755 | /// Its `record_digest`. |
| 756 | pub fn digest(&self) -> [u8; 32] { |
| 757 | self.digest |
| 758 | } |
| 759 | } |
| 760 | |
| 761 | /// Check one record's static rules and its signature under the signing key |
| 762 | /// the record names (owner, signer or recipient key). |
| 763 | pub fn open(bytes: &[u8]) -> Result<Verified<Record>, Refusal> { |
| 764 | let record = decode(bytes)?; |
| 765 | let (_, key_at, sig_at) = layout(&bytes[0..4]).expect("decode checked the magic"); |
| 766 | let key: [u8; 33] = arr(bytes, key_at); |
| 767 | let sig: [u8; 64] = arr(bytes, sig_at); |
| 768 | p256_verify_low_s(&key, &bytes[..sig_at], &sig).map_err(|_| Refusal::BadSignature)?; |
| 769 | Ok(Verified { |
| 770 | inner: record, |
| 771 | digest: record_digest(bytes), |
| 772 | }) |
| 773 | } |
| 774 | |
| 775 | macro_rules! open_as { |
| 776 | ($name:ident, $variant:ident, $ty:ty) => { |
| 777 | /// [`open`] for one record type; another type is `DCP_BAD_MAGIC`. |
| 778 | pub fn $name(bytes: &[u8]) -> Result<Verified<$ty>, Refusal> { |
| 779 | let v = open(bytes)?; |
| 780 | match v.inner { |
| 781 | Record::$variant(x) => Ok(Verified { |
| 782 | inner: x, |
| 783 | digest: v.digest, |
| 784 | }), |
| 785 | _ => Err(Refusal::BadMagic), |
| 786 | } |
| 787 | } |
| 788 | }; |
| 789 | } |
| 790 | open_as!(open_capsule, Capsule, Capsule); |
| 791 | open_as!(open_consent, Consent, Consent); |
| 792 | open_as!(open_retraction, Retraction, Retraction); |
| 793 | open_as!(open_ack, Ack, Ack); |
| 794 | open_as!(open_lineage, Lineage, Lineage); |
| 795 | |
| 796 | /// `recipient_set_digest` of a NAMED capsule: keys sorted bytewise, no |
| 797 | /// duplicates (SPEC.md section 9). |
| 798 | pub fn recipients_digest(keys: &[[u8; 33]]) -> [u8; 32] { |
| 799 | let mut sorted = keys.to_vec(); |
| 800 | sorted.sort(); |
| 801 | sorted.dedup(); |
| 802 | let mut h = Sha256::new(); |
| 803 | h.update(b"DCP1-RECIPIENTS"); |
| 804 | for k in &sorted { |
| 805 | h.update(k); |
| 806 | } |
| 807 | h.finalize().into() |
| 808 | } |
| 809 | |
| 810 | /// SHA-256 of a key, the form a consent declares custodians in. |
| 811 | pub fn key_digest(key: &[u8; 33]) -> [u8; 32] { |
| 812 | Sha256::digest(key).into() |
| 813 | } |
| 814 | |
| 815 | fn hex(out: &mut String, bytes: &[u8]) { |
| 816 | const H: &[u8; 16] = b"0123456789abcdef"; |
| 817 | for &x in bytes { |
| 818 | out.push(H[(x >> 4) as usize] as char); |
| 819 | out.push(H[(x & 15) as usize] as char); |
| 820 | } |
| 821 | } |
| 822 | |
| 823 | /// The verdict line in the exact format of `dcp_verify FILE` and |
| 824 | /// `vectors/expected.txt`: `ok type=MAGIC digest=H64 key=H66` (the signing |
| 825 | /// key) or `refuse CODE`. |
| 826 | pub fn verdict_line(bytes: &[u8]) -> String { |
| 827 | match decode(bytes) { |
| 828 | Err(r) => format!("refuse {}", r.name()), |
| 829 | Ok(_) => { |
| 830 | let (_, key_at, _) = layout(&bytes[0..4]).expect("decoded"); |
| 831 | let mut s = format!( |
| 832 | "ok type={} digest=", |
| 833 | std::str::from_utf8(&bytes[0..4]).unwrap() |
| 834 | ); |
| 835 | hex(&mut s, &record_digest(bytes)); |
| 836 | s.push_str(" key="); |
| 837 | hex(&mut s, &bytes[key_at..key_at + 33]); |
| 838 | s |
| 839 | } |
| 840 | } |
| 841 | } |