oak_core/hash_format.rs
1//! Content-addressing format versions: the v1 (current) and v2 (prepared,
2//! dormant) hash preimages for every Oak object kind.
3//!
4//! # Why this module exists
5//!
6//! **v1 — what ships today — has two structural weaknesses.**
7//!
8//! 1. *No domain separation.* Every object kind (blob, chunk, tree, commit)
9//! hashes its raw bytes with bare BLAKE3, so identical bytes in different
10//! roles collide: the empty blob, the empty-tree sentinel, and the empty
11//! chunk share one hash; a small file's single chunk hash equals its blob
12//! hash; a blob whose content happens to be a valid canonical tree
13//! serialization hashes identically to that tree. Git prefixes every
14//! object with `"<type> <len>\0"` for exactly this reason.
15//!
16//! 2. *Ambiguous commit preimage.* The commit hash covers
17//! `branch\nparent\nmerge\nmanifest\nauthor\nmessage\ntimestamp` joined by
18//! `\n`. Fields containing `\n` can shift bytes between positions (two
19//! distinct commits, one preimage), and the `files: Vec<FileChange>` list
20//! is excluded entirely, so the per-commit file-change rows can diverge
21//! between client and server without changing the commit hash.
22//!
23//! The compatible half of the fix landed alongside this module: tree entry
24//! names are validated (no `\t`/`\n`/`\0`/`/`, no `.`/`..`, non-empty),
25//! `Hash` deserialization requires real lowercase hex, and commit creation
26//! rejects `\n`/`\t`/`\0` in branch names and authors (both are Oak-generated
27//! or config values, so nothing legal is rejected). With branch, author, and
28//! the RFC 3339 timestamp all `\n`-free, the message — the one field that may
29//! legitimately contain newlines — can no longer bleed into a neighbor, so
30//! the v1 preimage is unambiguous *for data Oak will now accept*. What
31//! validation cannot fix is domain separation and the excluded files list:
32//! those change every hash, hence v2.
33//!
34//! **v2 preimages** (all BLAKE3, all length-safe):
35//!
36//! - blob: `"oak-blob\0" ++ content`
37//! - chunk: `"oak-chunk\0" ++ content`
38//! - tree: `"oak-tree\0" ++ canonical entry bytes` (same line format as v1)
39//! - commit: `"oak-commit\0" ++ field ++ field ++ ...` where every field is
40//! length-prefixed (`{decimal byte length}:{bytes}`, netstring-style) and
41//! optional fields encode as a single `-` byte when absent — so `None` and
42//! `Some("")` are distinct and no field can impersonate its neighbor
43//! regardless of content. Field order: branch name, parent hash, merge
44//! parent hash, manifest hash, author, message, RFC 3339 timestamp, then
45//! the file-change list (a length-prefixed count followed by each change's
46//! path, type letter, old/new blob hashes, old path, and old/new modes,
47//! every one length-prefixed or `-`). Including the files list makes the
48//! commit hash commit to its `commit_files` rows.
49//!
50//! # Versioning and migration story
51//!
52//! The format is a repo-level flag: [`HashFormat::from_metadata`] parses the
53//! `hash_format` metadata value ([`crate::MetadataKey::HashFormat`]), and an
54//! absent value means v1, so every existing repository — including the Oak
55//! repo itself and everything on the server — keeps hashing and verifying
56//! byte-identically. **Nothing writes that key yet**: no CLI command, no
57//! migration. v2 cannot be enabled today, only exercised through this module
58//! in tests.
59//!
60//! Flipping a repo to v2 is a full re-hash of every object (blob, chunk,
61//! tree, commit) plus rewrite of every row keyed by hash, so it must be an
62//! explicit offline migration (`oak upgrade --hash-format=v2` or similar),
63//! never a default. Mixed-format push/pull is not supported: the server and
64//! client must agree on the repo's format, which the protocol will need to
65//! advertise before any migration ships. Until then, the golden tests in
66//! this module pin the v1 preimages so no refactor can drift them silently.
67
68use crate::error::{OakError, Result};
69use crate::hash::{hash_bytes, Hash};
70use crate::{ChangeType, FileChange, FileMode};
71use chrono::{DateTime, Utc};
72
73/// Repository-level content-addressing format. See the module docs for the
74/// preimage definitions and the migration story.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
76pub enum HashFormat {
77 /// Bare BLAKE3 over raw bytes; `\n`-joined commit fields, files excluded.
78 /// The format of every existing repository.
79 #[default]
80 V1,
81 /// Domain-prefixed BLAKE3, length-prefixed commit fields, files included.
82 /// Prepared but not enabled anywhere — no CLI command or migration can
83 /// switch a repo to it yet.
84 V2,
85}
86
87impl HashFormat {
88 /// Parse the repo-level `hash_format` metadata value. Absent means v1 —
89 /// the format of every repository written before the flag existed. An
90 /// unrecognized value is an error (a newer repo this build can't read),
91 /// not a silent fallback.
92 pub fn from_metadata(value: Option<&str>) -> Result<Self> {
93 match value {
94 None | Some("v1") => Ok(HashFormat::V1),
95 Some("v2") => Ok(HashFormat::V2),
96 Some(other) => Err(OakError::Config(format!(
97 "unknown hash format {other:?} (this build understands v1 and v2)"
98 ))),
99 }
100 }
101
102 /// Canonical metadata value for this format.
103 pub fn as_str(&self) -> &'static str {
104 match self {
105 HashFormat::V1 => "v1",
106 HashFormat::V2 => "v2",
107 }
108 }
109}
110
111/// Hash a blob's content under the given format.
112pub fn hash_blob(format: HashFormat, content: &[u8]) -> Hash {
113 domain_hash(format, b"oak-blob\0", content)
114}
115
116/// Hash a chunk's content under the given format.
117pub fn hash_chunk(format: HashFormat, content: &[u8]) -> Hash {
118 domain_hash(format, b"oak-chunk\0", content)
119}
120
121/// Hash a tree's canonical entry bytes (see [`crate::Tree::canonical_bytes`])
122/// under the given format.
123pub fn hash_tree(format: HashFormat, canonical_bytes: &[u8]) -> Hash {
124 domain_hash(format, b"oak-tree\0", canonical_bytes)
125}
126
127fn domain_hash(format: HashFormat, domain: &[u8], content: &[u8]) -> Hash {
128 match format {
129 HashFormat::V1 => hash_bytes(content),
130 HashFormat::V2 => {
131 let mut preimage = Vec::with_capacity(domain.len() + content.len());
132 preimage.extend_from_slice(domain);
133 preimage.extend_from_slice(content);
134 hash_bytes(&preimage)
135 }
136 }
137}
138
139/// Everything a commit hash is derived from. Borrowed view over
140/// [`crate::Commit`]'s fields so `Commit::with_timestamp` can hash before
141/// constructing the struct.
142#[derive(Clone, Copy)]
143pub struct CommitFields<'a> {
144 pub branch_name: &'a str,
145 pub parent_hash: Option<&'a Hash>,
146 pub merge_parent_hash: Option<&'a Hash>,
147 pub manifest_hash: &'a Hash,
148 pub author: &'a str,
149 pub message: Option<&'a str>,
150 pub timestamp: &'a DateTime<Utc>,
151 /// Hashed under v2 only; v1 ignores it (its historical weakness).
152 pub files: &'a [FileChange],
153}
154
155/// Hash a commit under the given format.
156pub fn hash_commit(format: HashFormat, f: &CommitFields) -> Hash {
157 match format {
158 HashFormat::V1 => {
159 // The shipped preimage, byte for byte. `None` hashes like the
160 // empty string for parents and message (`None` vs `Some("")` is
161 // documented as indistinguishable in v1), and `files` is absent.
162 let content = format!(
163 "{}\n{}\n{}\n{}\n{}\n{}\n{}",
164 f.branch_name,
165 f.parent_hash.map(|h| h.as_str()).unwrap_or_default(),
166 f.merge_parent_hash.map(|h| h.as_str()).unwrap_or_default(),
167 f.manifest_hash,
168 f.author,
169 f.message.unwrap_or_default(),
170 f.timestamp.to_rfc3339()
171 );
172 hash_bytes(content.as_bytes())
173 }
174 HashFormat::V2 => {
175 let mut p = Vec::new();
176 p.extend_from_slice(b"oak-commit\0");
177 field(&mut p, f.branch_name.as_bytes());
178 opt_field(&mut p, f.parent_hash.map(|h| h.as_str()));
179 opt_field(&mut p, f.merge_parent_hash.map(|h| h.as_str()));
180 field(&mut p, f.manifest_hash.as_str().as_bytes());
181 field(&mut p, f.author.as_bytes());
182 opt_field(&mut p, f.message);
183 field(&mut p, f.timestamp.to_rfc3339().as_bytes());
184 field(&mut p, f.files.len().to_string().as_bytes());
185 for c in f.files {
186 field(&mut p, c.path.as_bytes());
187 field(&mut p, change_type_str(c.change_type).as_bytes());
188 opt_field(&mut p, c.old_blob_hash.as_ref().map(|h| h.as_str()));
189 opt_field(&mut p, c.new_blob_hash.as_ref().map(|h| h.as_str()));
190 opt_field(&mut p, c.old_path.as_deref());
191 opt_field(&mut p, c.old_mode.map(mode_str));
192 opt_field(&mut p, c.new_mode.map(mode_str));
193 }
194 hash_bytes(&p)
195 }
196 }
197}
198
199/// Hash a commit under the **frozen legacy v1 preimage** that predates
200/// `merge_parent_hash` (commits created before ~April 2026, when the merge
201/// parent entered the preimage). Six newline-joined fields — identical to
202/// today's v1 except the `merge_parent` line is absent entirely:
203///
204/// ```text
205/// branch\nparent\nmanifest\nauthor\nmessage\ntimestamp.to_rfc3339()
206/// ```
207///
208/// This format is used **only** to verify peer-claimed hashes of commits
209/// from that era (all of which have no merge parent); nothing may ever hash
210/// a new commit with it. `f.merge_parent_hash` and `f.files` are ignored —
211/// callers must gate on `merge_parent_hash` being absent.
212pub fn hash_commit_v1_pre_merge_parent(f: &CommitFields) -> Hash {
213 let content = format!(
214 "{}\n{}\n{}\n{}\n{}\n{}",
215 f.branch_name,
216 f.parent_hash.map(|h| h.as_str()).unwrap_or_default(),
217 f.manifest_hash,
218 f.author,
219 f.message.unwrap_or_default(),
220 f.timestamp.to_rfc3339()
221 );
222 hash_bytes(content.as_bytes())
223}
224
225/// Append one length-prefixed field: `{decimal byte length}:{bytes}`.
226fn field(out: &mut Vec<u8>, bytes: &[u8]) {
227 out.extend_from_slice(bytes.len().to_string().as_bytes());
228 out.push(b':');
229 out.extend_from_slice(bytes);
230}
231
232/// Append an optional field: `-` when absent, length-prefixed when present
233/// (so `None` ≠ `Some("")` — `-` vs `0:`).
234fn opt_field(out: &mut Vec<u8>, value: Option<&str>) {
235 match value {
236 None => out.push(b'-'),
237 Some(v) => field(out, v.as_bytes()),
238 }
239}
240
241fn change_type_str(t: ChangeType) -> &'static str {
242 match t {
243 ChangeType::Added => "A",
244 ChangeType::Modified => "M",
245 ChangeType::Deleted => "D",
246 ChangeType::Renamed => "R",
247 }
248}
249
250fn mode_str(m: FileMode) -> &'static str {
251 match m {
252 FileMode::Regular => "regular",
253 FileMode::Executable => "executable",
254 FileMode::Symlink => "symlink",
255 }
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261 use crate::hash::hash_string;
262 use crate::{Commit, FileMode, ManifestEntry, TreeEntry, TreeEntryKind};
263 use chrono::TimeZone;
264
265 fn fixed_timestamp() -> DateTime<Utc> {
266 Utc.with_ymd_and_hms(2024, 1, 2, 3, 4, 5).unwrap()
267 }
268
269 fn sample_files() -> Vec<FileChange> {
270 vec![FileChange {
271 path: "src/lib.rs".to_string(),
272 change_type: ChangeType::Modified,
273 old_blob_hash: Some(hash_string("old")),
274 new_blob_hash: Some(hash_string("new")),
275 old_path: None,
276 old_mode: Some(FileMode::Regular),
277 new_mode: Some(FileMode::Regular),
278 }]
279 }
280
281 // ---- v1 stability (golden values + equivalence with the live paths) ----
282 //
283 // STOP: the hex values pinned below are the v1 content-addressing format,
284 // which is FROZEN. Every object on every existing server (oak.space and
285 // every user's repos) was hashed this way. If a change to the hashing code
286 // makes one of these assertions fail, the fix is to REVERT the change, not
287 // to update the expected value — updating it re-breaks compatibility with
288 // all stored data (clones/mounts fail with "commit hash mismatch"). A new
289 // format must be a new `HashFormat` variant behind an explicit migration,
290 // never an edit to these constants. See the module docs for why.
291
292 /// BLAKE3 of the empty input — the v1 hash shared by the empty blob, the
293 /// empty-tree sentinel, and the empty chunk (the v1 weakness v2 removes).
294 const V1_EMPTY: &str = "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262";
295
296 #[test]
297 fn v1_blob_chunk_tree_are_bare_blake3() {
298 for content in [&b""[..], b"hello world", b"\x00\x01\xff"] {
299 let expected = hash_bytes(content);
300 assert_eq!(hash_blob(HashFormat::V1, content), expected);
301 assert_eq!(hash_chunk(HashFormat::V1, content), expected);
302 assert_eq!(hash_tree(HashFormat::V1, content), expected);
303 }
304 }
305
306 #[test]
307 fn v1_empty_golden() {
308 assert_eq!(hash_blob(HashFormat::V1, b"").as_str(), V1_EMPTY);
309 assert_eq!(crate::Tree::empty_hash().as_str(), V1_EMPTY);
310 // `Blob::empty_hash` is the sentinel the client matches on before it
311 // will synthesize a blob the server never sent (`ensure_empty_blob`).
312 // Pin it here so a hash-format change can't quietly turn that
313 // synthesis into "reconstruct the wrong bytes for some other hash".
314 assert_eq!(crate::Blob::empty_hash().as_str(), V1_EMPTY);
315 assert_eq!(crate::Blob::empty().hash.as_str(), V1_EMPTY);
316 assert!(crate::Blob::is_empty_hash(&crate::Blob::empty_hash()));
317 assert!(!crate::Blob::is_empty_hash(&hash_blob(
318 HashFormat::V1,
319 b"not empty"
320 )));
321 }
322
323 #[test]
324 fn v1_blob_golden() {
325 // Pinned current value: BLAKE3("hello world").
326 assert_eq!(
327 hash_blob(HashFormat::V1, b"hello world").as_str(),
328 "d74981efa70a0c880b8d8c1985d075dbcbf679b99a5f9914e5aaf96b831a9e24"
329 );
330 }
331
332 #[test]
333 fn v1_tree_golden() {
334 let tree = crate::Tree::new(vec![
335 TreeEntry {
336 name: "a.txt".to_string(),
337 kind: TreeEntryKind::Blob,
338 hash: hash_string("a"),
339 mode: FileMode::Regular,
340 },
341 TreeEntry {
342 name: "sub".to_string(),
343 kind: TreeEntryKind::Tree,
344 hash: hash_string("sub"),
345 mode: FileMode::Regular,
346 },
347 ])
348 .unwrap();
349 // Pinned current value for this fixed two-entry tree.
350 assert_eq!(
351 tree.hash.as_str(),
352 "26fa3b9ad707a970f25bb9821cde463e244307bfe8234a1237eed50a421e85ea"
353 );
354 assert_eq!(
355 hash_tree(HashFormat::V1, &tree.canonical_bytes()),
356 tree.hash
357 );
358 }
359
360 #[test]
361 fn v1_commit_matches_live_commit_path_and_golden() {
362 let manifest = hash_string("manifest");
363 let files = sample_files();
364 let commit = Commit::with_timestamp(
365 "main".to_string(),
366 None,
367 None,
368 manifest.clone(),
369 "tester".to_string(),
370 Some("a message".to_string()),
371 files.clone(),
372 fixed_timestamp(),
373 )
374 .unwrap();
375 let ts = fixed_timestamp();
376 let via_module = hash_commit(
377 HashFormat::V1,
378 &CommitFields {
379 branch_name: "main",
380 parent_hash: None,
381 merge_parent_hash: None,
382 manifest_hash: &manifest,
383 author: "tester",
384 message: Some("a message"),
385 timestamp: &ts,
386 files: &files,
387 },
388 );
389 assert_eq!(commit.hash, via_module);
390 // Pinned current value for these fixed inputs.
391 assert_eq!(
392 commit.hash.as_str(),
393 "6b575aadf3ed7e96f242a521087baf9498a67e3b107ee6a2880ab321151912fb"
394 );
395 }
396
397 #[test]
398 fn v1_manifest_root_golden() {
399 let manifest = crate::Manifest::new(vec![ManifestEntry {
400 path: "dir/file.txt".to_string(),
401 blob_hash: hash_string("content"),
402 mode: FileMode::Regular,
403 }]);
404 // Pinned current value: root tree hash of this one-file manifest.
405 assert_eq!(
406 manifest.hash.as_str(),
407 "863eb9a88032134f08722aa08b4aaa346d7408c17dbea4597957175bf907ab2f"
408 );
409 }
410
411 // ---- v2 properties ----
412
413 #[test]
414 fn v2_domains_separate_identical_bytes() {
415 for content in [&b""[..], b"same bytes"] {
416 let blob = hash_blob(HashFormat::V2, content);
417 let chunk = hash_chunk(HashFormat::V2, content);
418 let tree = hash_tree(HashFormat::V2, content);
419 assert_ne!(blob, chunk);
420 assert_ne!(blob, tree);
421 assert_ne!(chunk, tree);
422 // And none of them collide with v1's bare hash of the same bytes.
423 let v1 = hash_bytes(content);
424 assert_ne!(blob, v1);
425 assert_ne!(chunk, v1);
426 assert_ne!(tree, v1);
427 }
428 }
429
430 #[test]
431 fn v2_empty_blob_differs_from_empty_tree() {
432 assert_ne!(
433 hash_blob(HashFormat::V2, b""),
434 hash_tree(HashFormat::V2, b"")
435 );
436 }
437
438 #[test]
439 fn v2_commit_includes_files() {
440 let manifest = hash_string("manifest");
441 let files = sample_files();
442 let ts = fixed_timestamp();
443 let base = CommitFields {
444 branch_name: "main",
445 parent_hash: None,
446 merge_parent_hash: None,
447 manifest_hash: &manifest,
448 author: "tester",
449 message: None,
450 timestamp: &ts,
451 files: &[],
452 };
453 let without = hash_commit(HashFormat::V2, &base);
454 let with = hash_commit(
455 HashFormat::V2,
456 &CommitFields {
457 files: &files,
458 ..base
459 },
460 );
461 assert_ne!(without, with);
462 // v1 ignores files: the same two inputs collide there (the known
463 // weakness this format version exists to fix).
464 let v1_without = hash_commit(HashFormat::V1, &base);
465 let v1_with = hash_commit(
466 HashFormat::V1,
467 &CommitFields {
468 files: &files,
469 ..base
470 },
471 );
472 assert_eq!(v1_without, v1_with);
473 }
474
475 #[test]
476 fn v2_none_and_empty_message_differ() {
477 let manifest = hash_string("manifest");
478 let ts = fixed_timestamp();
479 let base = CommitFields {
480 branch_name: "main",
481 parent_hash: None,
482 merge_parent_hash: None,
483 manifest_hash: &manifest,
484 author: "tester",
485 message: None,
486 timestamp: &ts,
487 files: &[],
488 };
489 let none = hash_commit(HashFormat::V2, &base);
490 let empty = hash_commit(
491 HashFormat::V2,
492 &CommitFields {
493 message: Some(""),
494 ..base
495 },
496 );
497 assert_ne!(none, empty);
498 }
499
500 #[test]
501 fn v2_fields_cannot_shift_between_positions() {
502 // In v1 these two commits collide: ("x\ny", "z") vs ("x", "y\nz") in
503 // adjacent fields produce one preimage. Length prefixes fix that.
504 let manifest = hash_string("manifest");
505 let ts = fixed_timestamp();
506 let a = hash_commit(
507 HashFormat::V2,
508 &CommitFields {
509 branch_name: "main",
510 parent_hash: None,
511 merge_parent_hash: None,
512 manifest_hash: &manifest,
513 author: "x\ny",
514 message: Some("z"),
515 timestamp: &ts,
516 files: &[],
517 },
518 );
519 let b = hash_commit(
520 HashFormat::V2,
521 &CommitFields {
522 branch_name: "main",
523 parent_hash: None,
524 merge_parent_hash: None,
525 manifest_hash: &manifest,
526 author: "x",
527 message: Some("y\nz"),
528 timestamp: &ts,
529 files: &[],
530 },
531 );
532 assert_ne!(a, b);
533 }
534
535 // ---- format flag plumbing ----
536
537 // ---- v1 commit timestamp serialization (regression guard) ----
538 //
539 // The v1 commit preimage embeds `timestamp.to_rfc3339()` (see
540 // `hash_commit`). Real commits carry subsecond precision and arbitrary UTC
541 // offsets — e.g. the oak.space `main` HEAD at the time of writing was
542 // `2026-06-27T04:33:39.965405+00:00` (microseconds). The other v1 golden
543 // tests all use a *clean* whole-second UTC timestamp, so a change to how
544 // fractional seconds or the offset render (e.g. switching to
545 // `SecondsFormat::Nanos`, a `Z` suffix, or truncating sub-seconds) would
546 // silently change the hash of every real commit while leaving those goldens
547 // green — and break verification against every already-stored commit on the
548 // server. These cases pin that exact behavior.
549
550 /// `DateTime<Utc>::to_rfc3339()` is the only timestamp serialization the v1
551 /// commit hash depends on. Pin its observable contract directly so a chrono
552 /// bump or a deliberate format swap is caught in isolation, with a readable
553 /// diff, before it cascades into a commit-hash change.
554 #[test]
555 fn rfc3339_timestamp_rendering_is_stable() {
556 use chrono::DateTime;
557 let render = |s: &str| {
558 DateTime::parse_from_rfc3339(s)
559 .unwrap()
560 .with_timezone(&Utc)
561 .to_rfc3339()
562 };
563 // Subsecond digits auto-scale to 0/3/6/9 places; UTC always renders as
564 // a literal `+00:00` offset (never `Z`); a non-UTC offset normalizes to
565 // UTC. Each of these is a property a careless change would flip.
566 assert_eq!(
567 render("2024-01-02T03:04:05+00:00"),
568 "2024-01-02T03:04:05+00:00"
569 );
570 assert_eq!(
571 render("2026-06-27T04:33:39.250+00:00"),
572 "2026-06-27T04:33:39.250+00:00"
573 );
574 assert_eq!(
575 render("2026-06-27T04:33:39.965405+00:00"),
576 "2026-06-27T04:33:39.965405+00:00"
577 );
578 assert_eq!(
579 render("2026-06-27T04:33:39.123456789+00:00"),
580 "2026-06-27T04:33:39.123456789+00:00"
581 );
582 // Wire timestamps arrive as strings, get parsed, then re-rendered when
583 // the commit hash is recomputed for verification (see
584 // `protocol::commit_data_to_core`). A `+05:30` offset must collapse to
585 // the canonical UTC form, or the recomputed hash would never match.
586 assert_eq!(
587 render("2026-06-27T04:33:39.965405+05:30"),
588 "2026-06-26T23:03:39.965405+00:00"
589 );
590 }
591
592 /// Golden v1 commit hashes for timestamps with real-world precision and
593 /// offsets. Same commit fields, only the timestamp varies, so a drift in
594 /// timestamp serialization is the only thing that can move these.
595 #[test]
596 fn v1_commit_timestamp_precision_golden() {
597 use chrono::DateTime;
598 let manifest = hash_string("manifest");
599 let parent = hash_string("parent");
600 let commit_hash = |rfc: &str| {
601 let ts = DateTime::parse_from_rfc3339(rfc)
602 .unwrap()
603 .with_timezone(&Utc);
604 hash_commit(
605 HashFormat::V1,
606 &CommitFields {
607 branch_name: "main",
608 parent_hash: Some(&parent),
609 merge_parent_hash: None,
610 manifest_hash: &manifest,
611 author: "Zach <zach@oak.space>",
612 message: Some("subject\n\nbody"),
613 timestamp: &ts,
614 files: &[],
615 },
616 )
617 .0
618 };
619 // (input timestamp, pinned commit hash) — these must never change.
620 for (rfc, expected) in [
621 (
622 "2024-01-02T03:04:05+00:00",
623 "e4fe01caceba2c8fb905de9477af391e9c9ac50195f48025e922f70608868ae0",
624 ),
625 (
626 "2026-06-27T04:33:39.250+00:00",
627 "7a667e00cf11830eb56b2014827566dd92fd379be836f49cbcb24939dc367081",
628 ),
629 (
630 "2026-06-27T04:33:39.965405+00:00",
631 "ed0e25d76ab3af99c91b19a0b96e7e3ae8e972c92a3bf8106b392813f29506a9",
632 ),
633 (
634 "2026-06-27T04:33:39.123456789+00:00",
635 "bd691a79fccc1a680c59ab7fdeb06d0506af828d62703605d35e72cf55798070",
636 ),
637 (
638 "2026-06-27T04:33:39.965405+05:30",
639 "5154b359afbae5b4a92afcb076867baf531ce6d19c3cc3ebe4ee15f159575065",
640 ),
641 ] {
642 assert_eq!(commit_hash(rfc), expected, "commit hash drift for {rfc}");
643 }
644 }
645
646 /// A merge commit (both `parent_hash` and `merge_parent_hash` set) exercises
647 /// two hash-position fields the single-parent goldens leave empty. Pinned so
648 /// a change to how those fields serialize is caught.
649 #[test]
650 fn v1_merge_commit_golden() {
651 use chrono::DateTime;
652 let manifest = hash_string("manifest");
653 let parent = hash_string("parent");
654 let merge = hash_string("merge");
655 let ts = DateTime::parse_from_rfc3339("2026-06-27T04:33:39.965405+00:00")
656 .unwrap()
657 .with_timezone(&Utc);
658 let h = hash_commit(
659 HashFormat::V1,
660 &CommitFields {
661 branch_name: "main",
662 parent_hash: Some(&parent),
663 merge_parent_hash: Some(&merge),
664 manifest_hash: &manifest,
665 author: "tester",
666 message: Some("merge"),
667 timestamp: &ts,
668 files: &[],
669 },
670 );
671 assert_eq!(
672 h.as_str(),
673 "1375c4cb565921d18c3a06c5b6366ba4aa802c71d228cc4e32f750b1f5d4c99d"
674 );
675 }
676
677 #[test]
678 fn format_flag_defaults_to_v1_and_rejects_unknown() {
679 assert_eq!(HashFormat::from_metadata(None).unwrap(), HashFormat::V1);
680 assert_eq!(
681 HashFormat::from_metadata(Some("v1")).unwrap(),
682 HashFormat::V1
683 );
684 assert_eq!(
685 HashFormat::from_metadata(Some("v2")).unwrap(),
686 HashFormat::V2
687 );
688 assert!(HashFormat::from_metadata(Some("v3")).is_err());
689 assert_eq!(HashFormat::default(), HashFormat::V1);
690 }
691}