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.
This commit is contained in:
1 parent
59521dc195
commit
9e87016399
31 files changed
+2331
-154
No files matched your search
@@ -51,13 +51,27 @@ impl SnapshotRejection {
|
||||
|
||||
/// The snapshot of `sheet` that `report` needs: pure, deterministic (document order
|
||||
/// everywhere). A missing asset is left out and caught by `assert_snapshot`.
|
||||
///
|
||||
/// M1 (owner 2026-10-25, R5.6): a report of this sheet stamped with the registered historical
|
||||
/// value of its verified, recomputed content gets a snapshot carrying that same stamp, so its
|
||||
/// archive holds one value and every reader (the frozen N-1 one, a rollback build) keeps it.
|
||||
/// In every other case the snapshot carries the sheet's own value, and the export's strict
|
||||
/// equality refuses a report that differs.
|
||||
pub fn build_sheet_snapshot(sheet: &LoadedSheet, report: &Report) -> SheetSnapshot {
|
||||
let stamp = &report.sheet.document_sha256;
|
||||
let document_sha256 = if report.sheet.sheet_id == sheet.reference.sheet_id
|
||||
&& sheet.recognises_historical_stamp(&report.sheet.sheet_id, stamp)
|
||||
{
|
||||
stamp.clone()
|
||||
} else {
|
||||
sheet.reference.document_sha256.clone()
|
||||
};
|
||||
SheetSnapshot {
|
||||
status: sheet.status,
|
||||
reference: SheetSnapshotRef {
|
||||
sheet_id: sheet.reference.sheet_id.clone(),
|
||||
version_id: sheet.reference.version_id.clone(),
|
||||
document_sha256: sheet.reference.document_sha256.clone(),
|
||||
document_sha256,
|
||||
schema_version: sheet.schema_version,
|
||||
species_id: sheet.species_id.clone(),
|
||||
},
|
||||
|
||||
@@ -37,7 +37,13 @@ pub fn rebase_report_on_sheet(
|
||||
sheet: &LoadedSheet,
|
||||
archived: Option<&SheetSnapshot>,
|
||||
) -> Result<RebaseOutcome, ReadFailure> {
|
||||
if report.sheet.document_sha256 == sheet.reference.document_sha256 {
|
||||
// Same document: equal fingerprints, or the registered historical value of this very sheet,
|
||||
// proven against its verified, recomputed `v1` value (R5.6).
|
||||
let stamped = &report.sheet.document_sha256;
|
||||
if *stamped == sheet.reference.document_sha256
|
||||
|| (report.sheet.sheet_id == sheet.reference.sheet_id
|
||||
&& sheet.recognises_historical_stamp(&report.sheet.sheet_id, stamped))
|
||||
{
|
||||
return Ok(RebaseOutcome {
|
||||
report: report.clone(),
|
||||
unresolved_zones: 0,
|
||||
|
||||
@@ -1,19 +1,27 @@
|
||||
//! The sheet fingerprint convention `sha256-rfc8785-validated-v1` (D-R5.6, owner 2026-10-24,
|
||||
//! BDR-068) and the trusted alias registry. PREPARED, NOT ACTIVE: no reader, writer or
|
||||
//! generated file uses this module until the owner's switch signal (RUST.md §11.19).
|
||||
//! 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 zero integrity issue, 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. `v1` freezes these rules and the validation.
|
||||
//! 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` will declare it at the switch.
|
||||
/// 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";
|
||||
@@ -56,17 +64,17 @@ impl Equivalence {
|
||||
}
|
||||
}
|
||||
|
||||
/// `a` and `b`, two fingerprints stamped for `sheet_id`: equal, a registered pair of that sheet
|
||||
/// (either way round), or different. A real content change is never registered, so it stays
|
||||
/// `Different` and rebases as before.
|
||||
pub fn equivalence(sheet_id: &str, a: &str, b: &str) -> Equivalence {
|
||||
if a == b {
|
||||
/// `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.canonical == a && entry.alias == b)
|
||||
|| (entry.canonical == b && entry.alias == a))
|
||||
entry.sheet_id == sheet_id && entry.alias == stamped && entry.canonical == current
|
||||
});
|
||||
if paired {
|
||||
Equivalence::TrustedAlias
|
||||
@@ -84,6 +92,9 @@ pub enum AliasRefusal {
|
||||
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
|
||||
@@ -116,20 +127,39 @@ pub fn check_declared(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// RFC 8785 text of a JSON value. `None` for a number with no I-JSON form (never produced by
|
||||
/// the core's parser, which refuses non-finite values).
|
||||
pub fn canonical_json(value: &Value) -> Option<String> {
|
||||
let mut out = String::new();
|
||||
write_value(value, &mut out)?;
|
||||
Some(out)
|
||||
/// 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,
|
||||
}
|
||||
|
||||
fn write_value(value: &Value, out: &mut String) -> Option<()> {
|
||||
/// 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())?;
|
||||
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),
|
||||
@@ -139,16 +169,20 @@ fn write_value(value: &Value, out: &mut String) -> Option<()> {
|
||||
if index > 0 {
|
||||
out.push(',');
|
||||
}
|
||||
write_value(item, out)?;
|
||||
write_value(item, depth + 1, out)?;
|
||||
}
|
||||
out.push(']');
|
||||
}
|
||||
Value::Object(map) => write_object(map, out)?,
|
||||
Value::Object(map) => write_object(map, depth, out)?,
|
||||
}
|
||||
Some(())
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_object(map: &serde_json::Map<String, Value>, out: &mut String) -> Option<()> {
|
||||
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))
|
||||
@@ -161,10 +195,10 @@ fn write_object(map: &serde_json::Map<String, Value>, out: &mut String) -> Optio
|
||||
}
|
||||
write_string(key, out);
|
||||
out.push(':');
|
||||
write_value(item, out)?;
|
||||
write_value(item, depth + 1, out)?;
|
||||
}
|
||||
out.push('}');
|
||||
Some(())
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `JSON.stringify` of a string: `"` `\` and the controls escaped (short forms where JSON has
|
||||
@@ -189,44 +223,83 @@ fn write_string(text: &str, out: &mut String) {
|
||||
out.push('"');
|
||||
}
|
||||
|
||||
#[cfg(feature = "fingerprint")]
|
||||
pub use hashing::{FingerprintError, sheet_fingerprint};
|
||||
pub use hashing::{FingerprintError, document_fingerprint, sheet_fingerprint};
|
||||
|
||||
#[cfg(feature = "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::validate_sheet_document;
|
||||
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 issues (their count).
|
||||
/// 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, zero
|
||||
/// integrity issue, then JCS of the typed reading serialised back.
|
||||
/// `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()))?;
|
||||
let issues = validate_sheet_document(&document);
|
||||
if !issues.is_empty() {
|
||||
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).ok_or(FingerprintError::Canonical)?;
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,9 @@ use std::collections::HashMap;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::fingerprint::{
|
||||
AliasRefusal, Equivalence, check_declared, document_fingerprint, equivalence,
|
||||
};
|
||||
use super::index::{IndexedDocument, NoMainView, SheetIndex};
|
||||
use super::schema::AnatomicalSheetDocument;
|
||||
use crate::anatomy::svg::{Element, read_svg};
|
||||
@@ -33,6 +36,24 @@ pub struct BundledRef {
|
||||
pub document_sha256: String,
|
||||
pub schema_version: JsInt,
|
||||
pub species_id: String,
|
||||
/// Descriptive (R5.6): checked against the core's registry at load, never trusted alone.
|
||||
/// Absent: a historical (v0) reference; present, it must be a valid block (`null` refused).
|
||||
#[serde(default, deserialize_with = "present_block")]
|
||||
pub fingerprint: Option<DeclaredFingerprint>,
|
||||
}
|
||||
|
||||
/// `fingerprint` present means a block: an explicit `null` is refused, not read as absent.
|
||||
pub fn present_block<'de, D: serde::Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<Option<DeclaredFingerprint>, D::Error> {
|
||||
DeclaredFingerprint::deserialize(deserializer).map(Some)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct DeclaredFingerprint {
|
||||
pub convention: String,
|
||||
pub aliases: Vec<String>,
|
||||
}
|
||||
|
||||
/// A loaded, indexed sheet.
|
||||
@@ -49,6 +70,9 @@ pub struct LoadedSheet {
|
||||
/// sha256 by `svg_asset_id`; carried into an archive as provenance.
|
||||
pub asset_hashes: HashMap<String, String>,
|
||||
pub migration_map: ReportMigrationMap,
|
||||
/// The `v1` value the loader recomputed from the document and found declared (R5.6); `None`
|
||||
/// for a historical reference (no block). Private: only `from_bundle` sets it.
|
||||
verified_fingerprint: Option<String>,
|
||||
index: SheetIndex,
|
||||
/// Each asset read once at load (R3): the sanitised tree, or why it cannot be drawn. A
|
||||
/// rejection only affects the views on that asset; `assets` keeps the raw texts (the
|
||||
@@ -76,6 +100,8 @@ pub enum LoadError {
|
||||
Shape(serde_json::Error),
|
||||
/// The document has no main view.
|
||||
NoMainView,
|
||||
/// The declared fingerprint block contradicts the core's registry (R5.6).
|
||||
Fingerprint(AliasRefusal),
|
||||
}
|
||||
|
||||
impl From<serde_json::Error> for LoadError {
|
||||
@@ -102,6 +128,9 @@ impl LoadedSheet {
|
||||
.map(|(id, text)| (id.clone(), read_drawing(text)))
|
||||
.collect();
|
||||
let r = data.reference;
|
||||
let verified_fingerprint = check_reference(&r, &document)
|
||||
.map_err(LoadError::Fingerprint)?
|
||||
.then(|| r.document_sha256.clone());
|
||||
Ok(Self {
|
||||
status: data.status,
|
||||
reference: SheetRef {
|
||||
@@ -115,11 +144,32 @@ impl LoadedSheet {
|
||||
assets: data.assets,
|
||||
asset_hashes: data.asset_hashes,
|
||||
migration_map,
|
||||
verified_fingerprint,
|
||||
index,
|
||||
drawings,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the loader verified a `v1` reference (no alias privilege otherwise).
|
||||
pub fn is_fingerprint_verified(&self) -> bool {
|
||||
self.verified_fingerprint.is_some()
|
||||
}
|
||||
|
||||
/// Whether `stamp`, carried by a report of this sheet, is the registered historical value of
|
||||
/// this sheet's current content (R5.6, owner M1 rules): the loader verified a `v1` reference,
|
||||
/// the document as it stands now recomputes to that same value, and the registry binds `stamp`
|
||||
/// to it for this sheet. No declared or stored value stands in for the recomputation, so a
|
||||
/// mutated document or reference, a v0 sheet, another sheet or a forged stamp never qualify.
|
||||
pub fn recognises_historical_stamp(&self, sheet_id: &str, stamp: &str) -> bool {
|
||||
let Some(verified) = &self.verified_fingerprint else {
|
||||
return false;
|
||||
};
|
||||
sheet_id == self.reference.sheet_id
|
||||
&& *verified == self.reference.document_sha256
|
||||
&& equivalence(sheet_id, stamp, verified) == Equivalence::TrustedAlias
|
||||
&& document_fingerprint(&self.document).is_ok_and(|now| now == *verified)
|
||||
}
|
||||
|
||||
pub fn indexed(&self) -> IndexedDocument<'_> {
|
||||
self.index.over(&self.document)
|
||||
}
|
||||
@@ -133,3 +183,28 @@ impl LoadedSheet {
|
||||
self.drawings.get(asset_id)
|
||||
}
|
||||
}
|
||||
|
||||
/// The reference against the document (R5.6): `true` when a `v1` block, checked against the
|
||||
/// registry, declares the value recomputed from the document. With no block the reference is a
|
||||
/// historical one (v0): read as before, unverified (`false`), so an absent block never stands
|
||||
/// for `v1` and never brings an alias.
|
||||
fn check_reference(
|
||||
reference: &BundledRef,
|
||||
document: &AnatomicalSheetDocument,
|
||||
) -> Result<bool, AliasRefusal> {
|
||||
let value = &reference.document_sha256;
|
||||
let Some(declared) = &reference.fingerprint else {
|
||||
return Ok(false);
|
||||
};
|
||||
check_declared(
|
||||
&reference.sheet_id,
|
||||
value,
|
||||
&declared.convention,
|
||||
&declared.aliases,
|
||||
)?;
|
||||
match document_fingerprint(document) {
|
||||
Ok(computed) if computed == *value => Ok(true),
|
||||
Ok(computed) => Err(AliasRefusal::ContentMismatch(computed)),
|
||||
Err(error) => Err(AliasRefusal::ContentMismatch(format!("{error:?}"))),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user