proofframe 0.7.2

Rust-native Arrow contracts, exact checks, fingerprints, and verifiable evidence
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! Ed25519-signed proof receipts over canonical JSON reports.
//!
//! A receipt binds a report to an accountable signer using RFC 8785 JSON
//! canonicalization and a BLAKE3 report hash. Verification is fail-closed:
//! schema support, report hash, and signature must all hold.

use std::time::{SystemTime, UNIX_EPOCH};

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::ProofFrameError;
use crate::evidence::{EvidenceV2, PartitionManifestV1};

mod trust;
pub use trust::{TrustPolicy, TrustStore};

/// Ed25519 signing keypair encoded as URL-safe base64.
#[derive(Serialize)]
pub struct Keypair {
    /// Signature algorithm identifier (`Ed25519`).
    pub algorithm: &'static str,
    /// Base64 private signing key; store it in a secret manager.
    pub private_key: String,
    /// Base64 public verifying key.
    pub public_key: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct UnsignedReceipt {
    schema: String,
    algorithm: String,
    engine_version: String,
    issued_at_unix_ms: u64,
    report_hash: String,
    report: Value,
    public_key: String,
}

#[derive(Serialize, Deserialize)]
struct SignedReceipt {
    #[serde(flatten)]
    unsigned: UnsignedReceipt,
    signature: String,
}

/// Result of verifying a signed receipt; every field must hold for `valid`.
#[derive(Serialize)]
pub struct Verification {
    /// `true` only when schema, report hash, and signature all pass.
    pub valid: bool,
    /// `true` when the Ed25519 signature verifies against the public key.
    pub signature_valid: bool,
    /// `true` when the recomputed report hash matches the receipt.
    pub report_hash_matches: bool,
    /// `true` when the receipt schema and algorithm are supported.
    pub schema_supported: bool,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub enum ReceiptSchema {
    #[serde(rename = "proofframe.receipt.v2")]
    V2,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UnsignedReceiptV2 {
    pub schema: ReceiptSchema,
    pub algorithm: String,
    pub engine_version: String,
    pub issued_at_unix_ms: u64,
    pub evidence_hash: [u8; 32],
    pub evidence: EvidenceV2,
    pub public_key: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SignedReceiptV2 {
    pub schema: ReceiptSchema,
    pub unsigned: UnsignedReceiptV2,
    pub signature: String,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub enum PartitionReceiptSchema {
    #[serde(rename = "proofframe.partition-receipt.v1")]
    V1,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UnsignedPartitionReceiptV1 {
    pub schema: PartitionReceiptSchema,
    pub algorithm: String,
    pub engine_version: String,
    pub issued_at_unix_ms: u64,
    pub manifest_hash: [u8; 32],
    pub manifest: PartitionManifestV1,
    pub public_key: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SignedPartitionReceiptV1 {
    pub schema: PartitionReceiptSchema,
    pub unsigned: UnsignedPartitionReceiptV1,
    pub signature: String,
}

/// The outcome of verifying a receipt.
///
/// `valid` means *authentic*: intact, signed, and signed by a key the trust policy
/// accepts. It is never true without a trusted key. [`intact`](Self::intact) answers
/// the narrower question of whether the bytes are unaltered and correctly signed,
/// whoever signed them.
#[derive(Debug, Clone, Serialize)]
pub struct ReceiptVerification {
    pub valid: bool,
    pub signature_valid: bool,
    pub report_hash_matches: bool,
    pub schema_supported: bool,
    pub signer_trusted: bool,
    pub legacy: bool,
}

impl ReceiptVerification {
    /// Supported schema, matching hash and a correct signature, by any key.
    ///
    /// This is integrity, not authenticity: anyone can sign with a key of their own.
    #[must_use]
    pub const fn intact(&self) -> bool {
        self.schema_supported && self.report_hash_matches && self.signature_valid
    }
}

fn canonical(value: &impl Serialize) -> Result<Vec<u8>, ProofFrameError> {
    serde_json_canonicalizer::to_vec(value)
        .map_err(|error| ProofFrameError::InvalidReceipt(error.to_string()))
}

fn validate_i_json(value: &Value) -> Result<(), ProofFrameError> {
    const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
    let out_of_range = || {
        ProofFrameError::InvalidReceipt(
            "Receipt integers must be within the I-JSON safe range".to_string(),
        )
    };
    match value {
        Value::Number(number) => {
            if let Some(value) = number.as_i64() {
                if value.unsigned_abs() > MAX_SAFE_INTEGER {
                    return Err(out_of_range());
                }
            } else if number
                .as_u64()
                .is_some_and(|value| value > MAX_SAFE_INTEGER)
            {
                return Err(out_of_range());
            }
        }
        Value::Array(values) => {
            for item in values {
                validate_i_json(item)?;
            }
        }
        Value::Object(values) => {
            for item in values.values() {
                validate_i_json(item)?;
            }
        }
        _ => {}
    }
    Ok(())
}

fn decode_exact<const N: usize>(encoded: &str, label: &str) -> Result<[u8; N], ProofFrameError> {
    let bytes = URL_SAFE_NO_PAD
        .decode(encoded)
        .map_err(|error| ProofFrameError::InvalidReceipt(format!("Invalid {label}: {error}")))?;
    bytes
        .try_into()
        .map_err(|_| ProofFrameError::InvalidReceipt(format!("Invalid {label} length")))
}

fn now_unix_ms() -> Result<u64, ProofFrameError> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|error| ProofFrameError::InvalidReceipt(error.to_string()))?
        .as_millis()
        .try_into()
        .map_err(|_| {
            ProofFrameError::InvalidReceipt(
                "System timestamp is outside the supported range".to_string(),
            )
        })
}

/// Generate an Ed25519 [`Keypair`] and return it as a JSON string.
pub fn generate_keypair_json() -> Result<String, ProofFrameError> {
    let mut seed = [0_u8; 32];
    getrandom::fill(&mut seed)
        .map_err(|error| ProofFrameError::InvalidReceipt(error.to_string()))?;
    let signing = SigningKey::from_bytes(&seed);
    let output = Keypair {
        algorithm: "Ed25519",
        private_key: URL_SAFE_NO_PAD.encode(signing.to_bytes()),
        public_key: URL_SAFE_NO_PAD.encode(signing.verifying_key().to_bytes()),
    };
    Ok(serde_json::to_string(&output)?)
}

/// Sign a JSON report and return a canonical, Ed25519-signed receipt string.
///
/// Integers outside the I-JSON safe range are rejected to keep JSON number
/// canonicalization unambiguous.
pub fn sign_json(report_json: &str, private_key: &str) -> Result<String, ProofFrameError> {
    let report: Value = serde_json::from_str(report_json)?;
    validate_i_json(&report)?;
    let signing = SigningKey::from_bytes(&decode_exact(private_key, "private key")?);
    let report_hash = blake3::hash(&canonical(&report)?).to_hex().to_string();
    let issued_at_unix_ms = now_unix_ms()?;
    let unsigned = UnsignedReceipt {
        schema: "proofframe.receipt.v1".to_string(),
        algorithm: "Ed25519".to_string(),
        engine_version: env!("CARGO_PKG_VERSION").to_string(),
        issued_at_unix_ms,
        report_hash,
        report,
        public_key: URL_SAFE_NO_PAD.encode(signing.verifying_key().to_bytes()),
    };
    let signature = signing.sign(&canonical(&unsigned)?);
    Ok(serde_json::to_string(&SignedReceipt {
        unsigned,
        signature: URL_SAFE_NO_PAD.encode(signature.to_bytes()),
    })?)
}

/// Sign a strict V2 evidence envelope with an externally managed key.
pub fn sign_v2(
    evidence: EvidenceV2,
    signing: &SigningKey,
) -> Result<SignedReceiptV2, ProofFrameError> {
    let unsigned = UnsignedReceiptV2 {
        schema: ReceiptSchema::V2,
        algorithm: "Ed25519".to_string(),
        engine_version: env!("CARGO_PKG_VERSION").to_string(),
        issued_at_unix_ms: now_unix_ms()?,
        evidence_hash: evidence.digest()?,
        evidence,
        public_key: URL_SAFE_NO_PAD.encode(signing.verifying_key().to_bytes()),
    };
    let signature = signing.sign(&v2_message(&unsigned)?);
    Ok(SignedReceiptV2 {
        schema: ReceiptSchema::V2,
        unsigned,
        signature: URL_SAFE_NO_PAD.encode(signature.to_bytes()),
    })
}

/// Deserialize and sign a strict V2 evidence envelope.
pub fn sign_v2_json(evidence_json: &str, private_key: &str) -> Result<String, ProofFrameError> {
    let evidence: EvidenceV2 = serde_json::from_str(evidence_json)?;
    let signing = SigningKey::from_bytes(&decode_exact(private_key, "private key")?);
    Ok(serde_json::to_string(&sign_v2(evidence, &signing)?)?)
}

/// Sign an ordered partition manifest without changing the frozen receipt V2 envelope.
pub fn sign_partition_manifest(
    manifest: PartitionManifestV1,
    signing: &SigningKey,
) -> Result<SignedPartitionReceiptV1, ProofFrameError> {
    let unsigned = UnsignedPartitionReceiptV1 {
        schema: PartitionReceiptSchema::V1,
        algorithm: "Ed25519".to_string(),
        engine_version: env!("CARGO_PKG_VERSION").to_string(),
        issued_at_unix_ms: now_unix_ms()?,
        manifest_hash: manifest.digest()?,
        manifest,
        public_key: URL_SAFE_NO_PAD.encode(signing.verifying_key().to_bytes()),
    };
    let signature = signing.sign(&partition_message(&unsigned)?);
    Ok(SignedPartitionReceiptV1 {
        schema: PartitionReceiptSchema::V1,
        unsigned,
        signature: URL_SAFE_NO_PAD.encode(signature.to_bytes()),
    })
}

/// Verify manifest integrity, signature validity, and the supplied signer-trust policy.
pub fn verify_partition_manifest_receipt(
    receipt: &SignedPartitionReceiptV1,
    trust: &TrustPolicy,
) -> Result<ReceiptVerification, ProofFrameError> {
    let manifest_valid = receipt.unsigned.manifest.validate().is_ok();
    let schema_supported = receipt.schema == PartitionReceiptSchema::V1
        && receipt.unsigned.schema == PartitionReceiptSchema::V1
        && receipt.unsigned.algorithm == "Ed25519"
        && manifest_valid;
    let expected_hash = receipt.unsigned.manifest.digest_unchecked()?;
    let report_hash_matches = expected_hash == receipt.unsigned.manifest_hash && manifest_valid;
    let public = decode_public_key(&receipt.unsigned.public_key)?;
    let signature = Signature::from_bytes(&decode_exact(&receipt.signature, "signature")?);
    let signature_valid = public
        .verify_strict(&partition_message(&receipt.unsigned)?, &signature)
        .is_ok();
    let signer_trusted = trust.accepts(&public);
    Ok(ReceiptVerification {
        valid: schema_supported && report_hash_matches && signature_valid && signer_trusted,
        signature_valid,
        report_hash_matches,
        schema_supported,
        signer_trusted,
        legacy: false,
    })
}

/// Verify V2 or legacy V1 JSON with an optional expected signer key.
///
/// Without a key no signer is trusted, so the result is never `valid`; check
/// [`ReceiptVerification::intact`] for integrity alone.
pub fn verify_json_with_expected_key(
    receipt_json: &str,
    expected_public_key: Option<&str>,
) -> Result<ReceiptVerification, ProofFrameError> {
    let trust = match expected_public_key {
        Some(key) => TrustPolicy::ExpectedKey(decode_public_key(key)?),
        None => TrustPolicy::SignatureOnly,
    };
    verify_json_with_policy(receipt_json, &trust)
}

/// Verify cryptographic integrity independently from the caller's signer-trust policy.
pub fn verify_v2(
    receipt: &SignedReceiptV2,
    trust: &TrustPolicy,
) -> Result<ReceiptVerification, ProofFrameError> {
    let evidence_semantics_valid = receipt.unsigned.evidence.validate().is_ok();
    let schema_supported = receipt.schema == ReceiptSchema::V2
        && receipt.unsigned.schema == ReceiptSchema::V2
        && receipt.unsigned.algorithm == "Ed25519"
        && evidence_semantics_valid;
    let expected_hash = receipt.unsigned.evidence.digest_unchecked()?;
    let report_hash_matches = expected_hash == receipt.unsigned.evidence_hash;
    let public = decode_public_key(&receipt.unsigned.public_key)?;
    let signature = Signature::from_bytes(&decode_exact(&receipt.signature, "signature")?);
    let signature_valid = public
        .verify_strict(&v2_message(&receipt.unsigned)?, &signature)
        .is_ok();
    let signer_trusted = trust.accepts(&public);
    Ok(ReceiptVerification {
        valid: schema_supported && report_hash_matches && signature_valid && signer_trusted,
        signature_valid,
        report_hash_matches,
        schema_supported,
        signer_trusted,
        legacy: false,
    })
}

/// Verify either strict V2 or the isolated V1 compatibility schema.
pub fn verify_json_with_policy(
    receipt_json: &str,
    trust: &TrustPolicy,
) -> Result<ReceiptVerification, ProofFrameError> {
    let value: Value = serde_json::from_str(receipt_json)?;
    match value.get("schema").and_then(Value::as_str) {
        Some("proofframe.receipt.v2") => {
            let receipt: SignedReceiptV2 = serde_json::from_value(value)?;
            verify_v2(&receipt, trust)
        }
        Some("proofframe.receipt.v1") => {
            let receipt: SignedReceipt = serde_json::from_value(value)?;
            let public = decode_public_key(&receipt.unsigned.public_key)?;
            let verification = verify_json(receipt_json)?;
            let signer_trusted = trust.accepts(&public);
            Ok(ReceiptVerification {
                valid: verification.valid && signer_trusted,
                signature_valid: verification.signature_valid,
                report_hash_matches: verification.report_hash_matches,
                schema_supported: verification.schema_supported,
                signer_trusted,
                legacy: true,
            })
        }
        _ => Ok(ReceiptVerification {
            valid: false,
            signature_valid: false,
            report_hash_matches: false,
            schema_supported: false,
            signer_trusted: false,
            legacy: false,
        }),
    }
}

fn decode_public_key(encoded: &str) -> Result<VerifyingKey, ProofFrameError> {
    VerifyingKey::from_bytes(&decode_exact(encoded, "public key")?)
        .map_err(|error| ProofFrameError::InvalidReceipt(format!("Invalid public key: {error}")))
}

fn v2_message(unsigned: &UnsignedReceiptV2) -> Result<Vec<u8>, ProofFrameError> {
    let canonical = canonical(unsigned)?;
    let mut message = Vec::with_capacity(27 + canonical.len());
    message.extend_from_slice(b"proofframe:receipt:v2\0");
    message.extend_from_slice(&canonical);
    Ok(message)
}

fn partition_message(unsigned: &UnsignedPartitionReceiptV1) -> Result<Vec<u8>, ProofFrameError> {
    let canonical = canonical(unsigned)?;
    let mut message = Vec::with_capacity(39 + canonical.len());
    message.extend_from_slice(b"proofframe:partition-receipt:v1\0");
    message.extend_from_slice(&canonical);
    Ok(message)
}

/// Verify a signed receipt's schema, report hash, and Ed25519 signature.
/// Integrity of a legacy V1 receipt only: `valid` here does not consider who signed it.
///
/// Use [`verify_json_with_policy`] to require a trusted signer.
pub fn verify_json(receipt_json: &str) -> Result<Verification, ProofFrameError> {
    let receipt: SignedReceipt = serde_json::from_str(receipt_json)?;
    validate_i_json(&receipt.unsigned.report)?;
    let schema_supported = receipt.unsigned.schema == "proofframe.receipt.v1"
        && receipt.unsigned.algorithm == "Ed25519";
    let expected_hash = blake3::hash(&canonical(&receipt.unsigned.report)?)
        .to_hex()
        .to_string();
    let report_hash_matches = expected_hash == receipt.unsigned.report_hash;
    let public =
        VerifyingKey::from_bytes(&decode_exact(&receipt.unsigned.public_key, "public key")?)
            .map_err(|error| {
                ProofFrameError::InvalidReceipt(format!("Invalid public key: {error}"))
            })?;
    let signature = Signature::from_bytes(&decode_exact(&receipt.signature, "signature")?);
    let signature_valid = public
        .verify_strict(&canonical(&receipt.unsigned)?, &signature)
        .is_ok();
    Ok(Verification {
        valid: schema_supported && report_hash_matches && signature_valid,
        signature_valid,
        report_hash_matches,
        schema_supported,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn signed_receipts_verify_and_tampering_fails(n in -9_007_199_254_740_990_i64..9_007_199_254_740_990_i64) {
            let keys: Value = serde_json::from_str(&generate_keypair_json().unwrap()).unwrap();
            let private = keys["private_key"].as_str().unwrap();
            let receipt = sign_json(&format!(r#"{{"value":{n}}}"#), private).unwrap();
            prop_assert!(verify_json(&receipt).unwrap().valid);

            let mut tampered: Value = serde_json::from_str(&receipt).unwrap();
            tampered["report"]["value"] = Value::from(n.wrapping_add(1));
            prop_assert!(!verify_json(&tampered.to_string()).unwrap().valid);
        }
    }

    #[test]
    fn rejects_integers_outside_i_json_safe_range() {
        let keys: Value = serde_json::from_str(&generate_keypair_json().unwrap()).unwrap();
        let private = keys["private_key"].as_str().unwrap();
        assert!(sign_json(r#"{"value":9007199254740992}"#, private).is_err());
    }
}