Files
faunosteo/crates/core/src/domain/sheet/fingerprint.rs
T
bchanot 9e87016399 feat(domain): R5.6 fingerprint switch to sha256-rfc8785-validated-v1
The Rust pipeline is the official seed writer (pnpm import:equine); sheet-ref.json
and report-migration-map.json carry 12d78872...74e2 and the v1 block, the only two
seed files changed. 27c7383c...2660 stays a registered alias, honoured only through
LoadedSheet::recognises_historical_stamp (verified v1, recomputed document). M1: the
snapshot of an old report keeps its stamp; export, archive reader strict. Historical
oracles run in their pre-switch context; equivalence is crate-private.
2026-10-25 02:02:42 +01:00

306 lines
12 KiB
Rust

//! The sheet fingerprint convention `sha256-rfc8785-validated-v1` (D-R5.6, owner 2026-10-24,
//! active since R5.6, BDR-068, BDR-070) and the trusted alias registry (RUST.md §11.19 to §11.22).
//!
//! The value is the SHA-256 of the RFC 8785 (JCS) text of the validated document: the strict
//! typed reading of the R2 contract (`AnatomicalSheetDocument`, Zod's defaults filled, the
//! strict shape refusing unknown keys) with no integrity error (draft warnings allowed, as the
//! publish gate `is_publishable`), serialised back. JCS: members sorted recursively by the
//! UTF-16 code units of their names, numbers as ECMAScript `Number::toString`, strings with the
//! `JSON.stringify` escape set and every other character kept as is (no Unicode normalisation),
//! no whitespace, UTF-8, nesting bounded at `MAX_CANONICAL_DEPTH`. `v1` freezes these rules and
//! the validation.
//!
//! Trust boundary: a registered alias is honoured only through
//! `LoadedSheet::recognises_historical_stamp` (loader-verified `v1` value, recomputed from the
//! document at the decision); `equivalence` is crate-private. Equal fingerprints keep their
//! historical meaning everywhere (the same reference string), which is no proof of content: an
//! API that accepts caller-built data (an export input, a hand-made bundle) is trusted for what
//! it declares, as before R5.6.
use serde_json::Value;
use crate::json::js_number;
/// The convention's name, as `sheet-ref.json` declares it (its `fingerprint` block).
pub const FINGERPRINT_CONVENTION: &str = "sha256-rfc8785-validated-v1";
/// The pre-switch convention: SHA-256 of the Prettier-formatted `document.json` bytes.
pub const LEGACY_CONVENTION: &str = "sha256-prettier-file-bytes-v0";
/// One trusted equivalence: under `sheet_id`, the content whose canonical fingerprint is
/// `canonical` was stamped `alias` under `alias_convention`. Bound to the sheet and to that
/// content, never global; built from the frozen oracles, never from an archive, a bundle or the
/// database.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TrustedAlias {
pub sheet_id: &'static str,
pub canonical: &'static str,
pub alias: &'static str,
pub alias_convention: &'static str,
}
/// The registry, the only authority over equivalences. Equine draft: `alias` is the committed
/// `sheet-ref.json` value and `oracles/r5/fingerprints.json` `today_file_bytes`; `canonical` is
/// the same oracle's `b_rfc8785_validated`, recomputed by `sheet_fingerprint` (test).
pub const TRUSTED_ALIASES: &[TrustedAlias] = &[TrustedAlias {
sheet_id: "503dc301-a8b1-50d4-9e44-0919b2fc2916",
canonical: "12d788727c1e532641bd5b3a7ecf39dbdd25e70350f8a76be5ca917b262874e2",
alias: "27c7383c445c73dc2001ebf4794a3ea63d416910bbbaa0d7848dd720de7c2660",
alias_convention: LEGACY_CONVENTION,
}];
/// How two fingerprints of one sheet relate. The raw values stay with the caller, so a
/// diagnostic can still print both.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Equivalence {
Identical,
/// Different values the registry binds to the same content of this sheet.
TrustedAlias,
Different,
}
impl Equivalence {
pub fn same_document(self) -> bool {
self != Self::Different
}
}
/// `stamped` (what a report or an archive carries) against `current` (the loaded sheet's
/// verified value), both for `sheet_id`: equal; the registered pair of that sheet in this one
/// direction (an old stamp against the canonical value, never the reverse, so a sheet that
/// declares no `v1` value recognises no `v1` stamp); or different. A real content change is
/// never registered, so it stays `Different` and rebases as before.
pub(crate) fn equivalence(sheet_id: &str, stamped: &str, current: &str) -> Equivalence {
if stamped == current {
return Equivalence::Identical;
}
let paired = TRUSTED_ALIASES.iter().any(|entry| {
entry.sheet_id == sheet_id && entry.alias == stamped && entry.canonical == current
});
if paired {
Equivalence::TrustedAlias
} else {
Equivalence::Different
}
}
/// Why declared metadata contradicts the registry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AliasRefusal {
/// The declared convention is not `v1`.
UnknownConvention(String),
/// A declared alias the registry does not bind to this sheet and canonical value.
Untrusted(String),
/// The value declared under `v1` is not a 64-hex value, or is itself a historical alias.
NotCanonical(String),
/// The declared `v1` value is not the document's (the value recomputed, or why it could
/// not be).
ContentMismatch(String),
}
/// Checks what a `sheet-ref.json` declares (descriptive only): the convention must be `v1` and
/// every listed alias must be registered for this sheet and this canonical value. A
/// declaration never creates an equivalence.
pub fn check_declared(
sheet_id: &str,
canonical: &str,
convention: &str,
aliases: &[String],
) -> Result<(), AliasRefusal> {
if convention != FINGERPRINT_CONVENTION {
return Err(AliasRefusal::UnknownConvention(convention.to_owned()));
}
let hex = canonical.len() == 64
&& canonical
.bytes()
.all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
if !hex || TRUSTED_ALIASES.iter().any(|entry| entry.alias == canonical) {
return Err(AliasRefusal::NotCanonical(canonical.to_owned()));
}
for alias in aliases {
let trusted = TRUSTED_ALIASES.iter().any(|entry| {
entry.sheet_id == sheet_id && entry.canonical == canonical && entry.alias == alias
});
if !trusted {
return Err(AliasRefusal::Untrusted(alias.clone()));
}
}
Ok(())
}
/// The deepest nesting `canonical_json` writes: serde_json's own parse limit, so every value the
/// core parsed fits; a value built in code beyond it is refused, never a stack overflow.
pub const MAX_CANONICAL_DEPTH: usize = 128;
/// Why a value has no RFC 8785 text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CanonicalError {
/// A number with no I-JSON form (never produced by the core's parser).
NonFinite,
/// Containers nested deeper than `MAX_CANONICAL_DEPTH`.
TooDeep,
}
/// RFC 8785 text of a JSON value.
pub fn canonical_json(value: &Value) -> Result<String, CanonicalError> {
let mut out = String::new();
write_value(value, 0, &mut out)?;
Ok(out)
}
fn write_value(value: &Value, depth: usize, out: &mut String) -> Result<(), CanonicalError> {
let nested = matches!(value, Value::Array(_) | Value::Object(_));
if nested && depth >= MAX_CANONICAL_DEPTH {
return Err(CanonicalError::TooDeep);
}
match value {
Value::Null => out.push_str("null"),
Value::Bool(flag) => out.push_str(if *flag { "true" } else { "false" }),
Value::Number(number) => {
let float = number
.as_f64()
.filter(|f| f.is_finite())
.ok_or(CanonicalError::NonFinite)?;
out.push_str(&js_number(float));
}
Value::String(text) => write_string(text, out),
Value::Array(items) => {
out.push('[');
for (index, item) in items.iter().enumerate() {
if index > 0 {
out.push(',');
}
write_value(item, depth + 1, out)?;
}
out.push(']');
}
Value::Object(map) => write_object(map, depth, out)?,
}
Ok(())
}
fn write_object(
map: &serde_json::Map<String, Value>,
depth: usize,
out: &mut String,
) -> Result<(), CanonicalError> {
let mut entries: Vec<(Vec<u16>, &String, &Value)> = map
.iter()
.map(|(key, item)| (key.encode_utf16().collect(), key, item))
.collect();
entries.sort_by(|left, right| left.0.cmp(&right.0));
out.push('{');
for (index, (_, key, item)) in entries.iter().enumerate() {
if index > 0 {
out.push(',');
}
write_string(key, out);
out.push(':');
write_value(item, depth + 1, out)?;
}
out.push('}');
Ok(())
}
/// `JSON.stringify` of a string: `"` `\` and the controls escaped (short forms where JSON has
/// them, `\u00xx` lowercase otherwise), everything else verbatim.
fn write_string(text: &str, out: &mut String) {
out.push('"');
for character in text.chars() {
match character {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\u{8}' => out.push_str("\\b"),
'\u{c}' => out.push_str("\\f"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
control if u32::from(control) < 0x20 => {
out.push_str(&format!("\\u{:04x}", u32::from(control)));
}
other => out.push(other),
}
}
out.push('"');
}
pub use hashing::{FingerprintError, document_fingerprint, sheet_fingerprint};
mod hashing {
use sha2::{Digest, Sha256};
use super::canonical_json;
use crate::domain::js::parse_json;
use crate::domain::sheet::schema::AnatomicalSheetDocument;
use crate::domain::sheet::validate::{is_publishable, validate_sheet_document};
/// Why a document has no fingerprint: an invalid sheet is never stamped.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FingerprintError {
Parse(String),
Shape(String),
/// The integrity rules found errors (the count of every issue found).
Invalid(usize),
Canonical,
}
/// `sha256-rfc8785-validated-v1` of a document text: strict parse, R2 shape, then
/// `document_fingerprint`.
pub fn sheet_fingerprint(text: &str) -> Result<String, FingerprintError> {
let value = parse_json(text).map_err(|e| FingerprintError::Parse(e.to_string()))?;
let document: AnatomicalSheetDocument =
serde_json::from_value(value).map_err(|e| FingerprintError::Shape(e.to_string()))?;
document_fingerprint(&document)
}
/// The fingerprint of a typed document: no integrity error, then JCS of its reading
/// serialised back, then SHA-256 (the sheet load recomputes it, R5.6).
pub fn document_fingerprint(
document: &AnatomicalSheetDocument,
) -> Result<String, FingerprintError> {
// Integrity errors refuse a fingerprint; warnings do not (`is_publishable`: a draft may
// hold an annotation with no finding zone or an unreferenced zone, R5.6 rehearsal).
let issues = validate_sheet_document(document);
if !is_publishable(&issues) {
return Err(FingerprintError::Invalid(issues.len()));
}
let validated =
serde_json::to_value(document).map_err(|e| FingerprintError::Shape(e.to_string()))?;
let canonical = canonical_json(&validated).map_err(|_| FingerprintError::Canonical)?;
Ok(Sha256::digest(canonical.as_bytes())
.iter()
.map(|byte| format!("{byte:02x}"))
.collect())
}
}
#[cfg(test)]
mod tests {
use super::{Equivalence, TRUSTED_ALIASES, equivalence};
#[test]
fn the_registered_pair_holds_one_way_for_its_sheet_only() {
let pair = &TRUSTED_ALIASES[0];
let (sheet, alias, canonical) = (pair.sheet_id, pair.alias, pair.canonical);
assert_eq!(
equivalence(sheet, canonical, canonical),
Equivalence::Identical
);
assert_eq!(
equivalence(sheet, alias, canonical),
Equivalence::TrustedAlias
);
assert_eq!(equivalence(sheet, canonical, alias), Equivalence::Different);
let other_sheet = "00000000-0000-0000-0000-000000000000";
assert_eq!(
equivalence(other_sheet, alias, canonical),
Equivalence::Different
);
let other = "a".repeat(64);
assert_eq!(equivalence(sheet, &other, alias), Equivalence::Different);
assert_eq!(
equivalence(sheet, &other, canonical),
Equivalence::Different
);
}
}