Skip to main content

byteflow/
attest.rs

1//! Host-side bytecode **integrity fingerprint** (Phase 4).
2//!
3//! [`fingerprint_bf`] is SHA-256 over a `.bf` buffer. It is an **integrity
4//! fingerprint**, not cryptographic attestation: it does not use a secret
5//! key, MAC, or signature scheme. Hosts that want signed module attestation
6//! must layer that on top (non-goal for Byteflow itself).
7//!
8//! The digest is the FIPS 180-4 hash of the raw bytes, so the same buffer
9//! produces the same 32 bytes on every rustc, OS, and pointer width. A value
10//! stored from the previous `DefaultHasher` expansion will not match and
11//! must be recomputed.
12
13// Docs ratchet: public items here predate `missing_docs`. Delete this
14// allow once they are documented; new files get the lint by default.
15#![allow(missing_docs)]
16
17use std::fmt;
18
19use crate::bytecode::{decode, Chunk, FormatError};
20
21/// SHA-256 of `bytes`.
22///
23/// Any SHA-256 implementation can reproduce this (no domain prefix). Suitable
24/// for host-side "did this buffer change?" checks — **not** a signature.
25pub fn fingerprint_bf(bytes: &[u8]) -> [u8; 32] {
26    crate::digest::sha256(bytes)
27}
28
29/// Failure of [`decode_attested`].
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum AttestError {
32    /// Buffer fingerprint did not match the expected digest.
33    DigestMismatch {
34        expected: [u8; 32],
35        actual: [u8; 32],
36    },
37    /// Fingerprint matched but BFV0 decode failed (`TrustLevel::Untrusted`).
38    Decode(String),
39}
40
41impl fmt::Display for AttestError {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        match self {
44            AttestError::DigestMismatch { expected, actual } => {
45                write!(
46                    f,
47                    "bytecode fingerprint mismatch: expected {}, actual {}",
48                    hex32(expected),
49                    hex32(actual)
50                )
51            }
52            AttestError::Decode(msg) => write!(f, "attested decode failed: {msg}"),
53        }
54    }
55}
56
57impl std::error::Error for AttestError {}
58
59fn hex32(bytes: &[u8; 32]) -> String {
60    let mut s = String::with_capacity(64);
61    for b in bytes {
62        use std::fmt::Write as _;
63        let _ = write!(s, "{b:02x}");
64    }
65    s
66}
67
68/// Fingerprint `bytes`, compare to `expected`, then [`decode`] (untrusted).
69///
70/// Digest is checked **before** decode so a wrong expected digest never
71/// spends work on a hostile buffer beyond the fingerprint pass.
72pub fn decode_attested(bytes: &[u8], expected: &[u8; 32]) -> Result<Chunk, AttestError> {
73    let actual = fingerprint_bf(bytes);
74    if &actual != expected {
75        return Err(AttestError::DigestMismatch {
76            expected: *expected,
77            actual,
78        });
79    }
80    decode(bytes).map_err(|e: FormatError| AttestError::Decode(e.to_string()))
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86    use crate::bytecode::{encode, Program};
87
88    #[test]
89    fn roundtrip_fingerprint_then_decode_attested() -> Result<(), AttestError> {
90        let mut program = Program::new("attest-demo");
91        program.function("main", 0, |f| {
92            let a = f.load_i32(41);
93            let b = f.load_i32(1);
94            let sum = f.add(a, b);
95            f.return_(sum);
96        });
97        let chunk = program.build();
98        let bytes = encode(&chunk);
99        let digest = fingerprint_bf(&bytes);
100        let decoded = decode_attested(&bytes, &digest)?;
101        assert_eq!(decoded.name, chunk.name);
102        assert_eq!(decoded.code.len(), chunk.code.len());
103        Ok(())
104    }
105
106    #[test]
107    fn wrong_digest_fails_before_decode() {
108        let mut program = Program::new("attest-bad");
109        program.function("main", 0, |f| {
110            let v = f.load_i32(1);
111            f.return_(v);
112        });
113        let bytes = encode(&program.build());
114        let mut bad = fingerprint_bf(&bytes);
115        bad[0] ^= 0xFF;
116        match decode_attested(&bytes, &bad) {
117            Err(AttestError::DigestMismatch { .. }) => {}
118            other => panic!("expected DigestMismatch, got {other:?}"),
119        }
120    }
121
122    #[test]
123    fn fingerprint_is_sha256_of_the_bytes() {
124        assert_eq!(
125            hex32(&fingerprint_bf(b"")),
126            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
127        );
128        assert_eq!(
129            hex32(&fingerprint_bf(b"abc")),
130            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
131        );
132        let bytes = b"BFV0-not-a-real-module-but-stable";
133        assert_eq!(fingerprint_bf(bytes), fingerprint_bf(bytes));
134    }
135
136    fn hex32(bytes: &[u8; 32]) -> String {
137        let mut s = String::with_capacity(64);
138        for b in bytes {
139            use std::fmt::Write as _;
140            let _ = write!(s, "{b:02x}");
141        }
142        s
143    }
144}