#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
use std::collections::BTreeMap;
use super::*;
use crate::builder::{AtomDraft, IrBuilder};
use crate::canon::CanonReader;
use crate::model::{
ChangedPart, Content, DropRecord, Flag, FlagKind, ImportProvenance, LossBoundary, LossClass,
MetadataClaims, PathOp, RefKind, RefRecord, SourceIdentity, SourceKind, TransformRecord,
};
use crate::status::EpistemicStatus;
fn provenance() -> ImportProvenance {
ImportProvenance {
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: b"repo".to_vec(),
atom_id: b"root".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
brygge_version: "0.1.0".into(),
decoder: "brygge-decode-git".into(),
decoder_version: "0.1.0".into(),
params: BTreeMap::new(),
}
}
fn build() -> Ir {
let mut b = IrBuilder::new(provenance());
let blob = b.add_blob(b"hello world".to_vec()).unwrap();
let root = b
.add_atom(AtomDraft {
parents: vec![],
ops: vec![PathOp::Add {
path: "readme".into(),
content: Content::blob(blob, 0o100_644),
status: EpistemicStatus::Stated,
}],
copies: vec![],
metadata: MetadataClaims {
message: Some(crate::model::Text::utf8("initial")),
..MetadataClaims::default()
},
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: b"repo".to_vec(),
atom_id: b"c1".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
status: EpistemicStatus::Stated,
})
.unwrap();
let child_blob = b.add_blob(b"second".to_vec()).unwrap();
let _child = b
.add_atom(AtomDraft {
parents: vec![root],
ops: vec![PathOp::Add {
path: "second".into(),
content: Content::blob(child_blob, 0o100_644),
status: EpistemicStatus::Stated,
}],
copies: vec![],
metadata: MetadataClaims::default(),
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: b"repo".to_vec(),
atom_id: b"c2".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
status: EpistemicStatus::Stated,
})
.unwrap();
b.finish().unwrap()
}
#[test]
fn roundtrips() {
let ir = build();
let bytes = to_bytes(&ir);
let decoded = from_bytes(&bytes).unwrap();
assert_eq!(decoded.ir, ir);
assert_eq!(decoded.skipped_non_critical_fields, 0);
}
#[test]
fn serialization_is_byte_deterministic() {
let ir = build();
assert_eq!(to_bytes(&ir), to_bytes(&ir));
}
fn build_rich() -> Ir {
let mut b = IrBuilder::new(provenance());
let empty_blob = b.add_blob(Vec::new()).unwrap();
let large_blob = b.add_blob(vec![0x5au8; 200_000]).unwrap();
let root = b
.add_atom(AtomDraft {
parents: vec![],
ops: vec![
PathOp::Add {
path: "empty".into(),
content: Content::blob(empty_blob, 0o100_644),
status: EpistemicStatus::Stated,
},
PathOp::Add {
path: "large".into(),
content: Content::blob(large_blob, 0o100_644),
status: EpistemicStatus::Stated,
},
],
copies: vec![],
metadata: MetadataClaims {
message: Some(crate::model::Text::utf8("root")),
..MetadataClaims::default()
},
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: b"repo".to_vec(),
atom_id: b"c1".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
status: EpistemicStatus::Stated,
})
.unwrap();
b.add_ref(RefRecord {
name: "main".to_string(),
kind: RefKind::Branch,
target: root,
status: EpistemicStatus::Stated,
source: None,
annotation: None,
})
.unwrap();
b.set_loss(LossBoundary {
dropped: vec![DropRecord {
class: LossClass::Representation,
what: "packfiles".to_string(),
reason: "representation, not assertion".to_string(),
step: None,
}],
});
b.add_flag(Flag {
kind: FlagKind::ConventionViolation,
what: "layout".to_string(),
count: 1,
reason: "test fixture".to_string(),
});
b.finish().unwrap()
}
#[test]
fn write_to_equals_to_bytes_and_from_bytes_accepts_it() {
for ir in [build(), build_rich()] {
let via_to_bytes = to_bytes(&ir);
let mut cursor = std::io::Cursor::new(Vec::new());
write_to(&ir, &mut cursor).unwrap();
let via_write_to = cursor.into_inner();
assert_eq!(via_to_bytes, via_write_to);
let decoded = from_bytes(&via_write_to).unwrap();
assert_eq!(decoded.ir, ir);
}
}
fn locate_digest(bytes: &[u8]) -> std::ops::Range<usize> {
let mut vr = CanonReader::new(&bytes[9..]);
vr.uvarint().unwrap();
vr.uvarint().unwrap();
vr.uvarint().unwrap();
let version_len = (bytes.len() - 9) - vr.remaining();
let digest_start = 9 + version_len;
digest_start..digest_start + 32
}
#[test]
fn decoded_digest_equals_the_digest_stored_at_the_artifacts_header() {
let ir = build_rich();
let bytes = to_bytes(&ir);
let stored: [u8; 32] = bytes[locate_digest(&bytes)].try_into().unwrap();
let via_from_bytes = from_bytes(&bytes).unwrap();
assert_eq!(via_from_bytes.digest, stored);
let via_read_from = read_from(std::io::Cursor::new(bytes)).unwrap();
assert_eq!(via_read_from.digest, stored);
}
#[test]
fn read_from_a_cursor_agrees_with_from_bytes() {
for ir in [build(), build_rich()] {
let bytes = to_bytes(&ir);
let decoded = read_from(std::io::Cursor::new(bytes.clone())).unwrap();
assert_eq!(decoded.ir, ir);
for id in ir.content.ids() {
assert_eq!(
decoded.ir.content.get(id).unwrap(),
ir.content.get(id).unwrap()
);
}
}
}
fn scratch_dir(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!(
"brygge-ir-artifact-test-{name}-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn from_file_agrees_with_from_bytes() {
let dir = scratch_dir("from-file");
let path = dir.join("artifact");
let ir = build_rich();
std::fs::write(&path, to_bytes(&ir)).unwrap();
let decoded = from_file(&path).unwrap();
assert_eq!(decoded.ir, ir);
let _ = std::fs::remove_dir_all(&dir);
}
fn incompressible_blob() -> Vec<u8> {
let mut out = Vec::new();
let mut h: [u8; 32] = Sha256::digest(b"brygge-ir artifact test seed").into();
while out.len() < 300 {
h = Sha256::digest(h).into();
out.extend_from_slice(&h);
}
out.truncate(300);
out
}
#[test]
fn a_blob_changed_in_the_file_after_the_pass_is_never_read_as_the_new_bytes() {
let dir = scratch_dir("changed-during-read");
let path = dir.join("artifact");
let mut b = IrBuilder::new(provenance());
let blob = b.add_blob(incompressible_blob()).unwrap();
b.add_atom(AtomDraft {
parents: vec![],
ops: vec![PathOp::Add {
path: "big".into(),
content: Content::blob(blob, 0o100_644),
status: EpistemicStatus::Stated,
}],
copies: vec![],
metadata: MetadataClaims::default(),
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: b"repo".to_vec(),
atom_id: b"c1".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
status: EpistemicStatus::Stated,
})
.unwrap();
let ir = b.finish().unwrap();
let bytes = to_bytes(&ir);
std::fs::write(&path, &bytes).unwrap();
let decoded = from_file(&path).unwrap();
let id = *ir.content.ids().next().expect("one blob");
let original = decoded.ir.content.get(&id).unwrap().unwrap();
assert_eq!(original, incompressible_blob());
let pos = bytes
.windows(original.len())
.position(|w| w == original.as_slice())
.expect("the blob's bytes are findable verbatim in the artifact");
{
use std::io::{Seek, SeekFrom, Write};
let mut f = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
f.seek(SeekFrom::Start(pos as u64 + 1)).unwrap();
f.write_all(&[original[1] ^ 0xff]).unwrap();
}
let err = decoded.ir.content.get(&id).unwrap_err();
assert!(matches!(err, Error::ArtifactChanged(_)), "{err}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn truncation_is_rejected_not_panicked() {
let ir = build();
let bytes = to_bytes(&ir);
let cut = &bytes[..bytes.len() - 1];
assert!(from_bytes(cut).is_err());
assert!(from_bytes(b"BRYGGEIR").is_err());
assert!(from_bytes(b"").is_err());
}
#[test]
fn bad_magic_is_rejected() {
let mut bytes = to_bytes(&build());
bytes[0] = b'X';
assert!(matches!(from_bytes(&bytes), Err(Error::Decode(_))));
}
#[test]
fn format_1_is_a_pre_release_artifact_and_metadata_is_never_parsed() {
let mut bytes = MAGIC.to_vec();
bytes.push(1);
bytes.extend_from_slice(&[0xff; 64]);
match from_bytes(&bytes) {
Err(Error::PreReleaseArtifact) => {}
other => panic!("expected PreReleaseArtifact, got {other:?}"),
}
}
#[test]
fn format_1_with_no_trailing_bytes_at_all_is_still_a_pre_release_artifact() {
let mut bytes = MAGIC.to_vec();
bytes.push(1);
match from_bytes(&bytes) {
Err(Error::PreReleaseArtifact) => {}
other => panic!("expected PreReleaseArtifact, got {other:?}"),
}
}
fn container_with_version(ir: &Ir, major: u64, minor: u64, patch: u64) -> Vec<u8> {
let mut version = crate::canon::CanonWriter::new();
version.uvarint(major);
version.uvarint(minor);
version.uvarint(patch);
let mut body = crate::canon::CanonWriter::new();
let meta = ir.encode_metadata();
body.uvarint(meta.len() as u64);
body.raw(&meta);
body.uvarint(ir.content.len() as u64);
for id in ir.content.ids() {
let bytes = ir.content.get(id).unwrap().unwrap();
body.raw(id.as_bytes());
body.uvarint(bytes.len() as u64);
body.raw(&bytes);
}
let mut hasher = Sha256::new();
hasher.update(version.as_bytes());
hasher.update(body.as_bytes());
let digest: [u8; 32] = hasher.finalize().into();
let mut out = MAGIC.to_vec();
out.push(FORMAT);
out.extend_from_slice(version.as_bytes());
out.extend_from_slice(&digest);
out.extend_from_slice(body.as_bytes());
out
}
#[test]
fn a_matching_patch_bump_is_accepted() {
let ir = build();
let bytes = container_with_version(&ir, 0, 2, 7);
assert!(from_bytes(&bytes).is_ok());
}
#[test]
fn an_unlisted_minor_under_major_zero_is_refused() {
let ir = build();
let bytes = container_with_version(&ir, 0, u64::from(version::CURRENT.minor) + 1, 0);
match from_bytes(&bytes) {
Err(Error::UnsupportedContract { .. }) => {}
other => panic!("expected UnsupportedContract, got {other:?}"),
}
}
#[test]
fn a_newer_major_is_refused() {
let ir = build();
let bytes = container_with_version(&ir, 1, 0, 0);
match from_bytes(&bytes) {
Err(Error::UnsupportedContract { .. }) => {}
other => panic!("expected UnsupportedContract, got {other:?}"),
}
}
fn container_v3_all_stored(ir: &Ir) -> (Vec<u8>, usize, usize, usize) {
let mut version = CanonWriter::new();
version.uvarint(0);
version.uvarint(3);
version.uvarint(0);
let meta_bytes = ir.encode_metadata();
let order = store_order(ir);
let mut hasher = Sha256::new();
hasher.update(version.as_bytes());
hasher.update(canon::uvarint_value(meta_bytes.len() as u64));
hasher.update(&meta_bytes);
hasher.update(canon::uvarint_value(order.len() as u64));
let mut blob_bytes: Vec<Vec<u8>> = Vec::new();
for id in &order {
hasher.update(id.as_bytes());
let bytes = ir.content.get(id).unwrap().unwrap();
hasher.update(canon::uvarint_value(bytes.len() as u64));
blob_bytes.push(bytes);
}
for bytes in &blob_bytes {
hasher.update(bytes);
}
let digest: [u8; 32] = hasher.finalize().into();
let mut out = MAGIC.to_vec();
out.push(FORMAT);
out.extend_from_slice(version.as_bytes());
let digest_start = out.len();
out.extend_from_slice(&digest);
out.extend_from_slice(&canon::uvarint_value(1));
out.extend_from_slice(&canon::uvarint_value(0)); out.extend_from_slice(&canon::uvarint_value(meta_bytes.len() as u64));
out.extend_from_slice(&canon::uvarint_value(meta_bytes.len() as u64));
let meta_stored_start = out.len();
out.extend_from_slice(&meta_bytes);
out.extend_from_slice(&canon::uvarint_value(order.len() as u64));
for (id, bytes) in order.iter().zip(blob_bytes.iter()) {
out.extend_from_slice(id.as_bytes());
out.extend_from_slice(&canon::uvarint_value(bytes.len() as u64));
}
let total: u64 = blob_bytes.iter().map(|b| b.len() as u64).sum();
out.extend_from_slice(&canon::uvarint_value(1));
out.extend_from_slice(&canon::uvarint_value(0)); out.extend_from_slice(&canon::uvarint_value(total));
out.extend_from_slice(&canon::uvarint_value(total));
let blob_stored_start = out.len();
for bytes in &blob_bytes {
out.extend_from_slice(bytes);
}
(out, digest_start, meta_stored_start, blob_stored_start)
}
#[test]
fn a_flipped_version_byte_is_detected_as_a_digest_mismatch() {
let ir = build();
let (mut bytes, digest_start, ..) = container_v3_all_stored(&ir);
bytes[digest_start - 1] ^= 0x01;
match from_bytes(&bytes) {
Err(Error::DigestMismatch) => {}
other => panic!("expected DigestMismatch, got {other:?}"),
}
}
#[test]
fn a_flipped_metadata_byte_is_detected_as_a_digest_mismatch() {
let ir = build();
let (mut bytes, _, meta_stored_start, blob_stored_start) = container_v3_all_stored(&ir);
assert!(blob_stored_start > meta_stored_start);
bytes[meta_stored_start] ^= 0xff;
match from_bytes(&bytes) {
Err(Error::DigestMismatch) => {}
other => panic!("expected DigestMismatch, got {other:?}"),
}
}
#[test]
fn a_flipped_blob_store_byte_is_detected_as_a_digest_mismatch() {
let ir = build();
let (mut bytes, .., blob_stored_start) = container_v3_all_stored(&ir);
assert!(bytes.len() > blob_stored_start);
let last = bytes.len() - 1;
bytes[last] ^= 0xff;
match from_bytes(&bytes) {
Err(Error::DigestMismatch) => {}
other => panic!("expected DigestMismatch, got {other:?}"),
}
}
#[test]
fn atoms_out_of_canonical_order_are_rejected() {
let mut ir = build();
ir.atoms.reverse(); let bytes = to_bytes(&ir);
match from_bytes(&bytes) {
Err(Error::NonCanonical(_)) => {}
other => panic!("expected NonCanonical, got {other:?}"),
}
}
#[test]
fn a_copy_naming_a_later_atom_as_from_atom_is_rejected() {
let mut ir = build();
let mut y = ir.atoms[1].clone();
y.parents.clear(); y.copies.clear();
y.id = y.compute_id();
let mut x = ir.atoms[0].clone();
x.copies.push(crate::model::CopyRecord {
from: "readme".into(),
from_atom: y.id,
to: "impossible".into(),
status: EpistemicStatus::Stated,
});
x.id = x.compute_id(); ir.atoms = vec![x, y];
let bytes = to_bytes(&ir);
match from_bytes(&bytes) {
Err(Error::NonCanonical(_)) => {}
other => panic!("expected NonCanonical, got {other:?}"),
}
}
#[test]
fn a_duplicate_atom_id_is_rejected() {
let mut ir = build();
let dup = ir.atoms[0].clone();
ir.atoms.push(dup);
let bytes = to_bytes(&ir);
match from_bytes(&bytes) {
Err(Error::NonCanonical(_)) => {}
other => panic!("expected NonCanonical, got {other:?}"),
}
}
#[test]
fn an_orphan_blob_is_rejected_by_the_writer() {
let mut ir = build();
ir.content.insert(b"nobody references me".to_vec()).unwrap();
let mut cursor = std::io::Cursor::new(Vec::new());
match write_to(&ir, &mut cursor) {
Err(Error::Invariant(m)) => assert!(m.contains("orphan"), "{m}"),
other => panic!("expected Invariant (orphan), got {other:?}"),
}
}
#[test]
fn an_orphan_blob_in_a_hand_built_artifact_is_rejected_on_read() {
let ir = build();
let extra = b"nobody references me".to_vec();
let extra_id = BlobId::of(&extra);
let mut order = store_order(&ir);
order.push(extra_id);
let mut lens: Vec<u64> = Vec::new();
for id in &order {
lens.push(if *id == extra_id {
extra.len() as u64
} else {
ir.content.get(id).unwrap().unwrap().len() as u64
});
}
let mut version = crate::canon::CanonWriter::new();
version.uvarint(0);
version.uvarint(3);
version.uvarint(0);
let meta_bytes = ir.encode_metadata();
let mut hasher = Sha256::new();
hasher.update(version.as_bytes());
hasher.update(canon::uvarint_value(meta_bytes.len() as u64));
hasher.update(&meta_bytes);
hasher.update(canon::uvarint_value(order.len() as u64));
for (id, len) in order.iter().zip(lens.iter()) {
hasher.update(id.as_bytes());
hasher.update(canon::uvarint_value(*len));
}
for id in &order {
let bytes = if *id == extra_id {
extra.clone()
} else {
ir.content.get(id).unwrap().unwrap()
};
hasher.update(&bytes);
}
let digest: [u8; 32] = hasher.finalize().into();
let mut out = MAGIC.to_vec();
out.push(FORMAT);
out.extend_from_slice(version.as_bytes());
out.extend_from_slice(&digest);
write_frames(
&mut out,
&meta_bytes,
&frame::fixed_chunk_lens(meta_bytes.len() as u64),
false,
)
.unwrap();
out.extend_from_slice(&canon::uvarint_value(order.len() as u64));
for (id, len) in order.iter().zip(lens.iter()) {
out.extend_from_slice(id.as_bytes());
out.extend_from_slice(&canon::uvarint_value(*len));
}
let frame_lens = frame::canonical_frame_raw_lens(lens.iter().copied());
out.extend_from_slice(&canon::uvarint_value(frame_lens.len() as u64));
let mut blob_iter = order.iter();
for &flen in &frame_lens {
let mut buf = Vec::new();
let mut collected = 0u64;
while collected < flen {
let id = blob_iter.next().unwrap();
let bytes = if *id == extra_id {
extra.clone()
} else {
ir.content.get(id).unwrap().unwrap()
};
collected += bytes.len() as u64;
buf.extend_from_slice(&bytes);
}
write_one_frame(&mut out, &buf, false).unwrap();
}
match from_bytes(&out) {
Err(Error::NonCanonical(_)) => {}
other => panic!("expected NonCanonical, got {other:?}"),
}
}
#[test]
fn a_ref_targeting_an_unknown_atom_is_rejected() {
let mut ir = build();
ir.refs.push(crate::model::RefRecord {
name: "refs/heads/ghost".into(),
kind: crate::model::RefKind::Branch,
target: crate::model::AtomId([0xEE; 32]),
status: EpistemicStatus::Stated,
source: None,
annotation: None,
});
let bytes = to_bytes(&ir);
match from_bytes(&bytes) {
Err(Error::NonCanonical(_)) => {}
other => panic!("expected NonCanonical, got {other:?}"),
}
}
fn inject_trailing_field(record_bytes: &[u8], id: u64, critical: bool, value: &[u8]) -> Vec<u8> {
let mut r = CanonReader::new(record_bytes);
let n = r.uvarint().unwrap();
let consumed = record_bytes.len() - r.remaining();
let rest = &record_bytes[consumed..];
let mut w = crate::canon::CanonWriter::new();
w.uvarint(n + 1);
w.raw(rest);
w.uvarint((id << 1) | u64::from(critical));
w.uvarint(value.len() as u64);
w.raw(value);
w.into_bytes()
}
fn container_with_meta(ir: &Ir, meta: &[u8]) -> Vec<u8> {
let mut version = crate::canon::CanonWriter::new();
version.uvarint(0);
version.uvarint(2);
version.uvarint(0);
let mut body = crate::canon::CanonWriter::new();
body.uvarint(meta.len() as u64);
body.raw(meta);
body.uvarint(ir.content.len() as u64);
for id in ir.content.ids() {
let bytes = ir.content.get(id).unwrap().unwrap();
body.raw(id.as_bytes());
body.uvarint(bytes.len() as u64);
body.raw(&bytes);
}
let mut hasher = Sha256::new();
hasher.update(version.as_bytes());
hasher.update(body.as_bytes());
let digest: [u8; 32] = hasher.finalize().into();
let mut out = MAGIC.to_vec();
out.push(FORMAT);
out.extend_from_slice(version.as_bytes());
out.extend_from_slice(&digest);
out.extend_from_slice(body.as_bytes());
out
}
#[test]
fn trailing_bytes_in_metadata_are_rejected() {
let ir = build();
let mut meta = ir.encode_metadata();
meta.extend_from_slice(b"junk"); let bytes = container_with_meta(&ir, &meta);
match from_bytes(&bytes) {
Err(Error::NonCanonical(_)) => {}
other => panic!("expected NonCanonical, got {other:?}"),
}
}
#[test]
fn trailing_bytes_after_the_blob_store_are_rejected() {
let ir = build();
let mut version = crate::canon::CanonWriter::new();
version.uvarint(0);
version.uvarint(2);
version.uvarint(0);
let mut body = crate::canon::CanonWriter::new();
let meta = ir.encode_metadata();
body.uvarint(meta.len() as u64);
body.raw(&meta);
body.uvarint(ir.content.len() as u64);
for id in ir.content.ids() {
let bytes = ir.content.get(id).unwrap().unwrap();
body.raw(id.as_bytes());
body.uvarint(bytes.len() as u64);
body.raw(&bytes);
}
let mut body = body.into_bytes();
body.extend_from_slice(b"junk");
let mut hasher = Sha256::new();
hasher.update(version.as_bytes());
hasher.update(&body);
let digest: [u8; 32] = hasher.finalize().into();
let mut out = MAGIC.to_vec();
out.push(FORMAT);
out.extend_from_slice(version.as_bytes());
out.extend_from_slice(&digest);
out.extend_from_slice(&body);
match from_bytes(&out) {
Err(Error::NonCanonical(_)) => {}
other => panic!("expected NonCanonical, got {other:?}"),
}
}
#[test]
fn an_unknown_non_critical_field_on_ir_is_skipped_and_counted() {
let ir = build();
let meta = inject_trailing_field(&ir.encode_metadata(), 99, false, b"from the future");
let bytes = container_with_meta(&ir, &meta);
let decoded = from_bytes(&bytes).unwrap();
assert_eq!(decoded.skipped_non_critical_fields, 1);
assert_eq!(decoded.ir, ir);
}
#[test]
fn an_unknown_critical_field_on_ir_is_rejected() {
let ir = build();
let meta = inject_trailing_field(&ir.encode_metadata(), 99, true, b"from the future");
let bytes = container_with_meta(&ir, &meta);
match from_bytes(&bytes) {
Err(Error::UnknownCriticalField {
record: "Ir",
tag: 99,
}) => {}
other => panic!("expected UnknownCriticalField, got {other:?}"),
}
}
#[test]
fn truncations_and_single_byte_mutations_never_panic() {
let ir = build();
let bytes = to_bytes(&ir);
for n in 0..=bytes.len() {
let _ = from_bytes(&bytes[..n]); }
for i in 0..bytes.len() {
let mut mutated = bytes.clone();
mutated[i] ^= 0xff;
let _ = from_bytes(&mutated); }
}
const ALL_REF_KINDS: [fn() -> RefKind; 5] = [
|| RefKind::Branch,
|| RefKind::Tag,
|| RefKind::Bookmark,
|| RefKind::NamedBranch,
|| RefKind::Other("phase".to_string()),
];
const ALL_LOSS_CLASSES: [LossClass; 3] = [
LossClass::Representation,
LossClass::AdvisoryUnreliable,
LossClass::Other,
];
const ALL_FLAG_KINDS: [FlagKind; 2] = [
FlagKind::ConventionViolation,
FlagKind::BelowConfidenceFloor,
];
fn ref_of(ir: &Ir, name: &str, kind: RefKind) -> RefRecord {
RefRecord {
name: name.into(),
kind,
target: ir.atoms[0].id,
status: EpistemicStatus::Stated,
source: None,
annotation: None,
}
}
fn drop_of(class: LossClass, what: &str) -> DropRecord {
DropRecord {
class,
what: what.into(),
reason: "r".into(),
step: None,
}
}
fn flag_of(kind: FlagKind, what: &str) -> Flag {
Flag {
kind,
what: what.into(),
count: 1,
reason: "r".into(),
}
}
fn builder_with_atoms() -> IrBuilder {
let ir = build();
let mut b = IrBuilder::new(ir.provenance.clone());
for atom in &ir.atoms {
for op in &atom.ops {
if let PathOp::Add {
content: Content::Blob { blob, .. },
..
} = op
{
b.add_blob(ir.content.get(blob).unwrap().unwrap()).unwrap();
}
}
b.add_atom(AtomDraft {
parents: atom.parents.clone(),
ops: atom.ops.clone(),
copies: atom.copies.clone(),
metadata: atom.metadata.clone(),
source: atom.source.clone(),
status: atom.status.clone(),
})
.unwrap();
}
b
}
#[test]
fn every_pair_of_ref_kinds_roundtrips_in_both_insertion_orders() {
let target = build().atoms[0].id;
for a in ALL_REF_KINDS {
for b in ALL_REF_KINDS {
if a() == b() {
continue;
}
let mut builder = builder_with_atoms();
for kind in [a(), b()] {
builder
.add_ref(RefRecord {
name: "x".into(),
kind,
target,
status: EpistemicStatus::Stated,
source: None,
annotation: None,
})
.unwrap();
}
let ir = builder.finish().unwrap();
let read = from_bytes(&to_bytes(&ir)).unwrap_or_else(|e| panic!("{a:?}/{b:?}: {e}"));
assert_eq!(read.ir.refs, ir.refs);
let variants: Vec<u8> = ir.refs.iter().map(|r| r.kind.variant()).collect();
assert!(variants.windows(2).all(|w| w[0] < w[1]), "{variants:?}");
}
}
}
#[test]
fn every_pair_of_loss_classes_roundtrips_in_both_insertion_orders() {
for a in ALL_LOSS_CLASSES {
for b in ALL_LOSS_CLASSES {
if a == b {
continue;
}
let mut builder = builder_with_atoms();
builder.set_loss(LossBoundary {
dropped: vec![drop_of(a, "same"), drop_of(b, "same")],
});
let ir = builder.finish().unwrap();
let read = from_bytes(&to_bytes(&ir)).unwrap_or_else(|e| panic!("{a:?}/{b:?}: {e}"));
assert_eq!(read.ir.loss, ir.loss);
assert!(ir.loss.dropped[0].class.variant() < ir.loss.dropped[1].class.variant());
}
}
}
#[test]
fn every_pair_of_flag_kinds_roundtrips_in_both_insertion_orders() {
for a in ALL_FLAG_KINDS {
for b in ALL_FLAG_KINDS {
if a == b {
continue;
}
let mut builder = builder_with_atoms();
builder.add_flag(flag_of(a, "same"));
builder.add_flag(flag_of(b, "same"));
let ir = builder.finish().unwrap();
let read = from_bytes(&to_bytes(&ir)).unwrap_or_else(|e| panic!("{a:?}/{b:?}: {e}"));
assert_eq!(read.ir.flags, ir.flags);
assert!(ir.flags[0].kind.variant() < ir.flags[1].kind.variant());
}
}
}
#[test]
fn names_order_before_variants_for_refs_and_variants_before_whats_for_drops_and_flags() {
let mut builder = builder_with_atoms();
let target = build().atoms[0].id;
for (name, kind) in [
("b", RefKind::Branch),
("a", RefKind::NamedBranch),
("a", RefKind::Tag),
] {
builder
.add_ref(RefRecord {
name: name.into(),
kind,
target,
status: EpistemicStatus::Stated,
source: None,
annotation: None,
})
.unwrap();
}
builder.set_loss(LossBoundary {
dropped: vec![
drop_of(LossClass::Other, "a"),
drop_of(LossClass::Representation, "z"),
],
});
builder.add_flag(flag_of(FlagKind::BelowConfidenceFloor, "a"));
builder.add_flag(flag_of(FlagKind::ConventionViolation, "z"));
let ir = builder.finish().unwrap();
from_bytes(&to_bytes(&ir)).unwrap();
let refs: Vec<_> = ir
.refs
.iter()
.map(|r| (r.name.as_str(), r.kind.variant()))
.collect();
assert_eq!(refs, [("a", 1), ("a", 3), ("b", 0)]);
assert_eq!(ir.loss.dropped[0].what, "z");
assert_eq!(ir.flags[0].what, "z");
}
fn assert_non_canonical(ir: &Ir, what: &str) {
match from_bytes(&to_bytes(ir)) {
Err(Error::NonCanonical(m)) => assert!(m.contains(what), "{m}"),
other => panic!("expected NonCanonical ({what}), got {other:?}"),
}
}
#[test]
fn a_hand_built_stream_with_a_pair_in_the_wrong_variant_order_is_non_canonical() {
for a in ALL_REF_KINDS {
for b in ALL_REF_KINDS {
if a().variant() <= b().variant() {
continue;
}
let mut ir = build();
ir.refs = vec![ref_of(&ir, "x", a()), ref_of(&ir, "x", b())];
assert_non_canonical(&ir, "Ir.refs");
}
}
for a in ALL_LOSS_CLASSES {
for b in ALL_LOSS_CLASSES {
if a.variant() <= b.variant() {
continue;
}
let mut ir = build();
ir.loss.dropped = vec![drop_of(a, "same"), drop_of(b, "same")];
assert_non_canonical(&ir, "Ir.dropped");
}
}
for a in ALL_FLAG_KINDS {
for b in ALL_FLAG_KINDS {
if a.variant() <= b.variant() {
continue;
}
let mut ir = build();
ir.flags = vec![flag_of(a, "same"), flag_of(b, "same")];
assert_non_canonical(&ir, "Ir.flags");
}
}
}
#[test]
fn a_hand_built_stream_with_a_duplicate_key_is_non_canonical() {
let mut ir = build();
ir.refs = vec![
ref_of(&ir, "x", RefKind::Other("one".into())),
ref_of(&ir, "x", RefKind::Other("two".into())),
];
assert_non_canonical(&ir, "Ir.refs");
let mut ir = build();
ir.loss.dropped = vec![
drop_of(LossClass::Other, "w"),
drop_of(LossClass::Other, "w"),
];
assert_non_canonical(&ir, "Ir.dropped");
let mut ir = build();
ir.flags = vec![
flag_of(FlagKind::ConventionViolation, "w"),
flag_of(FlagKind::ConventionViolation, "w"),
];
assert_non_canonical(&ir, "Ir.flags");
}
#[test]
fn the_builder_refuses_a_duplicate_key_instead_of_writing_an_unreadable_artifact() {
let target = build().atoms[0].id;
let mut b = builder_with_atoms();
for label in ["one", "two"] {
b.add_ref(RefRecord {
name: "x".into(),
kind: RefKind::Other(label.into()),
target,
status: EpistemicStatus::Stated,
source: None,
annotation: None,
})
.unwrap();
}
assert!(matches!(b.finish(), Err(Error::Invariant(_))));
let mut b = builder_with_atoms();
b.set_loss(LossBoundary {
dropped: vec![
drop_of(LossClass::Other, "w"),
drop_of(LossClass::Other, "w"),
],
});
assert!(matches!(b.finish(), Err(Error::Invariant(_))));
let mut b = builder_with_atoms();
b.add_flag(flag_of(FlagKind::BelowConfidenceFloor, "w"));
b.add_flag(flag_of(FlagKind::BelowConfidenceFloor, "w"));
assert!(matches!(b.finish(), Err(Error::Invariant(_))));
}
fn fixture_ir() -> Ir {
let mut b = IrBuilder::new(provenance());
let empty_blob = b.add_blob(Vec::new()).unwrap();
let blob = b.add_blob(b"hello world".to_vec()).unwrap();
let root = b
.add_atom(AtomDraft {
parents: vec![],
ops: vec![
PathOp::Add {
path: "empty".into(),
content: Content::blob(empty_blob, 0o100_644),
status: EpistemicStatus::Stated,
},
PathOp::Add {
path: "readme".into(),
content: Content::blob(blob, 0o100_644),
status: EpistemicStatus::Stated,
},
],
copies: vec![],
metadata: MetadataClaims {
author: Some(crate::model::Identity {
name: crate::model::Text::utf8("A U Thor"),
email: Some(crate::model::Text::utf8("a@example.com")),
}),
author_time: Some(crate::model::Time {
seconds: 1_700_000_000,
offset_minutes: Some(60),
}),
committer: None,
commit_time: None,
message: Some(crate::model::Text::utf8("initial")),
},
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: b"repo".to_vec(),
atom_id: b"c1".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
status: EpistemicStatus::Stated,
})
.unwrap();
let child_blob = b
.add_blob(b"second revision, a bit longer than the first".to_vec())
.unwrap();
let child = b
.add_atom(AtomDraft {
parents: vec![root],
ops: vec![PathOp::Add {
path: "second".into(),
content: Content::blob(child_blob, 0o100_644),
status: EpistemicStatus::Stated,
}],
copies: vec![],
metadata: MetadataClaims::default(),
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: b"repo".to_vec(),
atom_id: b"c2".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
status: EpistemicStatus::Stated,
})
.unwrap();
b.add_ref(RefRecord {
name: "refs/heads/main".into(),
kind: RefKind::Branch,
target: child,
status: EpistemicStatus::Stated,
source: None,
annotation: None,
})
.unwrap();
b.set_loss(LossBoundary {
dropped: vec![DropRecord {
class: LossClass::Other,
what: "an example drop".into(),
reason: "contract fixture".into(),
step: None,
}],
});
b.add_flag(Flag {
kind: FlagKind::BelowConfidenceFloor,
what: "an example flag".into(),
count: 1,
reason: "contract fixture".into(),
});
b.finish().unwrap()
}
fn fixture_data_path(name: &str) -> std::path::PathBuf {
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/data")
.join(name)
}
#[test]
fn golden_bytes_contract_0_4_0() {
let bytes = to_bytes(&fixture_ir());
let path = fixture_data_path("contract-0.4.0.ir");
if std::env::var("UPDATE_GOLDEN").is_ok() {
std::fs::write(&path, &bytes).unwrap();
return;
}
let golden = std::fs::read(&path).unwrap_or_else(|e| {
panic!(
"{}: {e} (run with UPDATE_GOLDEN=1 to create it)",
path.display()
)
});
assert_eq!(
bytes,
golden,
"to_bytes's output no longer matches {}: a codec or writer change altered the artifact's \
bytes. If intentional, note it in the CHANGELOG and regenerate the file.",
path.display()
);
}
#[test]
fn reads_the_0_3_0_fixture() {
let path = fixture_data_path("contract-0.3.0.ir");
let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
let via_from_bytes = from_bytes(&bytes).unwrap();
assert_eq!(via_from_bytes.contract, ContractVersion::new(0, 3, 0));
assert_eq!(via_from_bytes.ir, fixture_ir());
let via_read_from = read_from(std::io::Cursor::new(bytes)).unwrap();
assert_eq!(via_read_from.contract, ContractVersion::new(0, 3, 0));
assert_eq!(via_read_from.digest, via_from_bytes.digest);
assert_eq!(via_read_from.ir, via_from_bytes.ir);
}
fn write_0_2_0(ir: &Ir) -> Vec<u8> {
let mut version = CanonWriter::new();
version.uvarint(0);
version.uvarint(2);
version.uvarint(0);
let mut body = CanonWriter::new();
let meta = ir.encode_metadata();
body.uvarint(meta.len() as u64);
body.raw(&meta);
body.uvarint(ir.content.len() as u64);
for id in ir.content.ids() {
let bytes = ir.content.get(id).unwrap().unwrap();
body.raw(id.as_bytes());
body.uvarint(bytes.len() as u64);
body.raw(&bytes);
}
let mut hasher = Sha256::new();
hasher.update(version.as_bytes());
hasher.update(body.as_bytes());
let digest: [u8; 32] = hasher.finalize().into();
let mut out = MAGIC.to_vec();
out.push(FORMAT);
out.extend_from_slice(version.as_bytes());
out.extend_from_slice(&digest);
out.extend_from_slice(body.as_bytes());
out
}
#[test]
fn reads_the_0_2_0_fixture() {
let path = fixture_data_path("contract-0.2.0.ir");
if std::env::var("UPDATE_GOLDEN").is_ok() {
std::fs::write(&path, write_0_2_0(&fixture_ir())).unwrap();
}
let bytes = std::fs::read(&path).unwrap_or_else(|e| {
panic!(
"{}: {e} (run with UPDATE_GOLDEN=1 to create it)",
path.display()
)
});
let via_from_bytes = from_bytes(&bytes).unwrap();
assert_eq!(via_from_bytes.contract, ContractVersion::new(0, 2, 0));
assert_eq!(via_from_bytes.ir, fixture_ir());
let via_read_from = read_from(std::io::Cursor::new(bytes)).unwrap();
assert_eq!(via_read_from.contract, ContractVersion::new(0, 2, 0));
assert_eq!(via_read_from.digest, via_from_bytes.digest);
assert_eq!(via_read_from.ir, via_from_bytes.ir);
}
#[test]
fn digest_is_independent_of_the_frame_codec() {
let ir = fixture_ir();
let deflated = to_bytes(&ir);
let mut cursor = std::io::Cursor::new(Vec::new());
write_to_stored_only(&ir, &mut cursor).unwrap();
let stored_only = cursor.into_inner();
assert_ne!(
deflated, stored_only,
"the fixture's repeated-word blob should actually compress smaller"
);
let a = from_bytes(&deflated).unwrap();
let b = from_bytes(&stored_only).unwrap();
assert_eq!(a.digest, b.digest);
assert_eq!(a.ir, b.ir);
assert_eq!(a.ir, ir);
}
#[test]
fn wrong_packing_two_frames_that_should_be_one_is_rejected() {
let ir = build();
let order = store_order(&ir);
let lens: Vec<u64> = order
.iter()
.map(|id| ir.content.get(id).unwrap().unwrap().len() as u64)
.collect();
assert_eq!(
frame::canonical_frame_raw_lens(lens.iter().copied()).len(),
1
);
let bytes_by_id: Vec<Vec<u8>> = order
.iter()
.map(|id| ir.content.get(id).unwrap().unwrap())
.collect();
let mut version = CanonWriter::new();
version.uvarint(0);
version.uvarint(3);
version.uvarint(0);
let meta_bytes = ir.encode_metadata();
let mut hasher = Sha256::new();
hasher.update(version.as_bytes());
hasher.update(canon::uvarint_value(meta_bytes.len() as u64));
hasher.update(&meta_bytes);
hasher.update(canon::uvarint_value(order.len() as u64));
for (id, len) in order.iter().zip(lens.iter()) {
hasher.update(id.as_bytes());
hasher.update(canon::uvarint_value(*len));
}
for bytes in &bytes_by_id {
hasher.update(bytes);
}
let digest: [u8; 32] = hasher.finalize().into();
let mut out = MAGIC.to_vec();
out.push(FORMAT);
out.extend_from_slice(version.as_bytes());
out.extend_from_slice(&digest);
write_frames(
&mut out,
&meta_bytes,
&frame::fixed_chunk_lens(meta_bytes.len() as u64),
false,
)
.unwrap();
out.extend_from_slice(&canon::uvarint_value(order.len() as u64));
for (id, len) in order.iter().zip(lens.iter()) {
out.extend_from_slice(id.as_bytes());
out.extend_from_slice(&canon::uvarint_value(*len));
}
out.extend_from_slice(&canon::uvarint_value(2));
for bytes in &bytes_by_id {
write_one_frame(&mut out, bytes, true).unwrap();
}
match from_bytes(&out) {
Err(Error::NonCanonical(m)) => assert!(m.contains("packing"), "{m}"),
other => panic!("expected NonCanonical (packing), got {other:?}"),
}
}
#[test]
fn a_blob_table_out_of_store_order_is_rejected() {
let ir = build();
let mut order = store_order(&ir);
assert!(order.len() >= 2, "build() has at least two blobs");
order.swap(0, 1); let lens: Vec<u64> = order
.iter()
.map(|id| ir.content.get(id).unwrap().unwrap().len() as u64)
.collect();
let bytes_by_id: Vec<Vec<u8>> = order
.iter()
.map(|id| ir.content.get(id).unwrap().unwrap())
.collect();
let mut version = CanonWriter::new();
version.uvarint(0);
version.uvarint(3);
version.uvarint(0);
let meta_bytes = ir.encode_metadata();
let mut hasher = Sha256::new();
hasher.update(version.as_bytes());
hasher.update(canon::uvarint_value(meta_bytes.len() as u64));
hasher.update(&meta_bytes);
hasher.update(canon::uvarint_value(order.len() as u64));
for (id, len) in order.iter().zip(lens.iter()) {
hasher.update(id.as_bytes());
hasher.update(canon::uvarint_value(*len));
}
for bytes in &bytes_by_id {
hasher.update(bytes);
}
let digest: [u8; 32] = hasher.finalize().into();
let mut out = MAGIC.to_vec();
out.push(FORMAT);
out.extend_from_slice(version.as_bytes());
out.extend_from_slice(&digest);
write_frames(
&mut out,
&meta_bytes,
&frame::fixed_chunk_lens(meta_bytes.len() as u64),
false,
)
.unwrap();
out.extend_from_slice(&canon::uvarint_value(order.len() as u64));
for (id, len) in order.iter().zip(lens.iter()) {
out.extend_from_slice(id.as_bytes());
out.extend_from_slice(&canon::uvarint_value(*len));
}
let frame_lens = frame::canonical_frame_raw_lens(lens.iter().copied());
out.extend_from_slice(&canon::uvarint_value(frame_lens.len() as u64));
let mut blob_iter = bytes_by_id.iter();
for &flen in &frame_lens {
let mut buf = Vec::new();
let mut collected = 0u64;
while collected < flen {
let bytes = blob_iter.next().unwrap();
collected += bytes.len() as u64;
buf.extend_from_slice(bytes);
}
write_one_frame(&mut out, &buf, true).unwrap();
}
match from_bytes(&out) {
Err(Error::NonCanonical(m)) => assert!(m.contains("store order"), "{m}"),
other => panic!("expected NonCanonical (store order), got {other:?}"),
}
}
#[test]
fn versions_outside_readable_are_refused() {
let ir = build();
for (major, minor, patch) in [(0u64, 1u64, 0u64), (0, 5, 0)] {
let bytes = container_with_version(&ir, major, minor, patch);
match from_bytes(&bytes) {
Err(Error::UnsupportedContract { .. }) => {}
other => {
panic!("expected UnsupportedContract for {major}.{minor}.{patch}, got {other:?}")
}
}
}
}
fn peak_rss_kib() -> Option<u64> {
let status = std::fs::read_to_string("/proc/self/status").ok()?;
for line in status.lines() {
if let Some(rest) = line.strip_prefix("VmHWM:") {
return rest.split_whitespace().next()?.parse().ok();
}
}
None
}
fn reset_peak_rss() -> bool {
std::fs::write("/proc/self/clear_refs", "5").is_ok()
}
const DEFLATE_BOMB_RAW_LEN: u64 = 256 * 1024 * 1024;
const DEFLATE_BOMB_CHILD_ENV: &str = "BRYGGE_DEFLATE_BOMB_CHILD";
fn deflate_bomb_bytes() -> Vec<u8> {
let mut b = IrBuilder::new(provenance());
let real_id = b.add_blob(b"small".to_vec()).unwrap();
b.add_atom(AtomDraft {
parents: vec![],
ops: vec![PathOp::Add {
path: "big".into(),
content: Content::blob(real_id, 0o100_644),
status: EpistemicStatus::Stated,
}],
copies: vec![],
metadata: MetadataClaims::default(),
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: b"repo".to_vec(),
atom_id: b"c1".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
status: EpistemicStatus::Stated,
})
.unwrap();
let ir = b.finish().unwrap();
let meta_bytes = ir.encode_metadata();
drop(ir);
let stored = frame::deflate_zeros_streamed(DEFLATE_BOMB_RAW_LEN);
let mut version = CanonWriter::new();
version.uvarint(0);
version.uvarint(3);
version.uvarint(0);
let mut hasher = Sha256::new();
hasher.update(version.as_bytes());
hasher.update(canon::uvarint_value(meta_bytes.len() as u64));
hasher.update(&meta_bytes);
hasher.update(canon::uvarint_value(1)); hasher.update(real_id.as_bytes());
hasher.update(canon::uvarint_value(DEFLATE_BOMB_RAW_LEN));
let zero_chunk = [0u8; 64 * 1024];
let mut remaining = DEFLATE_BOMB_RAW_LEN;
while remaining > 0 {
let n = remaining.min(zero_chunk.len() as u64) as usize;
hasher.update(&zero_chunk[..n]);
remaining -= n as u64;
}
let digest: [u8; 32] = hasher.finalize().into();
let mut bytes = MAGIC.to_vec();
bytes.push(FORMAT);
bytes.extend_from_slice(version.as_bytes());
bytes.extend_from_slice(&digest);
write_frames(
&mut bytes,
&meta_bytes,
&frame::fixed_chunk_lens(meta_bytes.len() as u64),
false,
)
.unwrap();
bytes.extend_from_slice(&canon::uvarint_value(1));
bytes.extend_from_slice(real_id.as_bytes());
bytes.extend_from_slice(&canon::uvarint_value(DEFLATE_BOMB_RAW_LEN));
bytes.extend_from_slice(&canon::uvarint_value(1)); write_frame_body(
&mut bytes,
frame::Codec::Deflate,
DEFLATE_BOMB_RAW_LEN,
&stored,
)
.unwrap();
bytes
}
#[test]
fn deflate_bomb_peak_rss_helper() {
if std::env::var_os(DEFLATE_BOMB_CHILD_ENV).is_none() {
return;
}
let bytes = deflate_bomb_bytes();
let dir = scratch_dir("deflate-bomb-child");
let path = dir.join("artifact");
std::fs::write(&path, &bytes).unwrap();
if !reset_peak_rss() {
let _ = std::fs::remove_dir_all(&dir);
println!("DEFLATE_BOMB_DELTA_KIB=unavailable");
return;
}
let before = peak_rss_kib();
let err = from_file(&path).unwrap_err();
let after = peak_rss_kib();
let _ = std::fs::remove_dir_all(&dir);
assert!(
matches!(err, Error::Decode(ref m) if m.contains("does not match its id")),
"expected a content-address refusal, got {err:?}"
);
match (before, after) {
(Some(before), Some(after)) => {
println!("DEFLATE_BOMB_DELTA_KIB={}", after.saturating_sub(before));
}
_ => println!("DEFLATE_BOMB_DELTA_KIB=unavailable"),
}
}
#[test]
fn a_one_gib_deflate_bomb_streams_through_read_from_within_a_bounded_peak() {
let exe = std::env::current_exe().expect("this test's own binary has a path");
let output = std::process::Command::new(&exe)
.args([
"artifact::tests::deflate_bomb_peak_rss_helper",
"--exact",
"--test-threads=1",
"--nocapture",
])
.env(DEFLATE_BOMB_CHILD_ENV, "1")
.output()
.expect("spawn the child measurement process");
assert!(
output.status.success(),
"the child measurement process failed:\nstdout: {}\nstderr: {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
let stdout = String::from_utf8_lossy(&output.stdout);
let after_marker = stdout
.split("DEFLATE_BOMB_DELTA_KIB=")
.nth(1)
.unwrap_or_else(|| panic!("no DEFLATE_BOMB_DELTA_KIB marker in child output: {stdout}"));
let delta_line = after_marker
.split(|c: char| c.is_whitespace())
.next()
.unwrap_or("");
if delta_line == "unavailable" {
if cfg!(target_os = "linux") {
panic!(
"/proc/self/clear_refs is not writable in the child process, and this is Linux: the \
peak-RSS bound cannot be checked"
);
}
eprintln!(
"skipping: /proc/self/clear_refs is not writable in the child process (not Linux)"
);
return;
}
let delta: u64 = delta_line
.parse()
.unwrap_or_else(|e| panic!("malformed DEFLATE_BOMB_DELTA_KIB value {delta_line:?}: {e}"));
assert!(
delta < 16 * 1024,
"the child process's own peak grew by {delta} KiB above baseline, inflating a 256 MiB claim; \
expected well under 16 MiB"
);
}
#[test]
fn a_frame_whose_raw_len_disagrees_with_the_plan_is_refused_before_its_stored_bytes_are_read() {
let ir = build();
let order = store_order(&ir);
let lens: Vec<u64> = order
.iter()
.map(|id| ir.content.get(id).unwrap().unwrap().len() as u64)
.collect();
let bytes_by_id: Vec<Vec<u8>> = order
.iter()
.map(|id| ir.content.get(id).unwrap().unwrap())
.collect();
let total: u64 = lens.iter().sum();
let mut version = CanonWriter::new();
version.uvarint(0);
version.uvarint(3);
version.uvarint(0);
let meta_bytes = ir.encode_metadata();
let mut hasher = Sha256::new();
hasher.update(version.as_bytes());
hasher.update(canon::uvarint_value(meta_bytes.len() as u64));
hasher.update(&meta_bytes);
hasher.update(canon::uvarint_value(order.len() as u64));
for (id, len) in order.iter().zip(lens.iter()) {
hasher.update(id.as_bytes());
hasher.update(canon::uvarint_value(*len));
}
for bytes in &bytes_by_id {
hasher.update(bytes);
}
let digest: [u8; 32] = hasher.finalize().into();
let mut out = MAGIC.to_vec();
out.push(FORMAT);
out.extend_from_slice(version.as_bytes());
out.extend_from_slice(&digest);
write_frames(
&mut out,
&meta_bytes,
&frame::fixed_chunk_lens(meta_bytes.len() as u64),
false,
)
.unwrap();
out.extend_from_slice(&canon::uvarint_value(order.len() as u64));
for (id, len) in order.iter().zip(lens.iter()) {
out.extend_from_slice(id.as_bytes());
out.extend_from_slice(&canon::uvarint_value(*len));
}
out.extend_from_slice(&canon::uvarint_value(1));
out.extend_from_slice(&canon::uvarint_value(0));
out.extend_from_slice(&canon::uvarint_value(total + 1));
out.extend_from_slice(&canon::uvarint_value(total + 1));
match from_bytes(&out) {
Err(Error::NonCanonical(m)) => assert!(
m.contains("does not match the packing rule"),
"expected the packing-rule refusal, got: {m}"
),
other => panic!("expected NonCanonical (packing rule), got {other:?}"),
}
}
fn many_frame_ir() -> Ir {
let mut b = IrBuilder::new(provenance());
let mut ops = Vec::new();
for i in 0..80 {
let mut content = format!("blob {i} of many, ").into_bytes();
content.resize(200 * 1024, b'.');
let blob = b.add_blob(content).unwrap();
ops.push(PathOp::Add {
path: format!("file-{i:03}"),
content: Content::blob(blob, 0o100_644),
status: EpistemicStatus::Stated,
});
}
for i in 0..3 {
let content = vec![i as u8; 2 * 1024 * 1024]; let blob = b.add_blob(content).unwrap();
ops.push(PathOp::Add {
path: format!("large-{i}"),
content: Content::blob(blob, 0o100_644),
status: EpistemicStatus::Stated,
});
}
b.add_atom(AtomDraft {
parents: vec![],
ops,
copies: vec![],
metadata: MetadataClaims::default(),
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: b"repo".to_vec(),
atom_id: b"c1".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
status: EpistemicStatus::Stated,
})
.unwrap();
b.finish().unwrap()
}
#[test]
fn parallel_blob_frame_compression_is_byte_identical_to_the_serial_writer() {
let ir = many_frame_ir();
let order = store_order(&ir);
let lens: Vec<u64> = order
.iter()
.map(|id| ir.content.get(id).unwrap().unwrap().len() as u64)
.collect();
let frame_lens = frame::canonical_frame_raw_lens(lens.iter().copied());
assert!(
frame_lens.len() > 4,
"this fixture should need several frames"
);
let parallel = to_bytes(&ir);
let mut version = CanonWriter::new();
version.uvarint(u64::from(version::CURRENT.major));
version.uvarint(u64::from(version::CURRENT.minor));
version.uvarint(u64::from(version::CURRENT.patch));
let meta_bytes = ir.encode_metadata();
let mut hasher = Sha256::new();
hasher.update(version.as_bytes());
hasher.update(canon::uvarint_value(meta_bytes.len() as u64));
hasher.update(&meta_bytes);
hasher.update(canon::uvarint_value(order.len() as u64));
for (id, len) in order.iter().zip(lens.iter()) {
hasher.update(id.as_bytes());
hasher.update(canon::uvarint_value(*len));
}
let mut blob_iter = order.iter();
let mut blob_frame_bytes = Vec::new();
blob_frame_bytes.extend_from_slice(&canon::uvarint_value(frame_lens.len() as u64));
for &flen in &frame_lens {
let mut buf = Vec::new();
let mut collected = 0u64;
while collected < flen {
let id = blob_iter.next().unwrap();
let bytes = ir.content.get(id).unwrap().unwrap();
hasher.update(&bytes);
collected += bytes.len() as u64;
buf.extend_from_slice(&bytes);
}
write_one_frame(&mut blob_frame_bytes, &buf, false).unwrap();
}
let digest: [u8; 32] = hasher.finalize().into();
let mut serial = MAGIC.to_vec();
serial.push(FORMAT);
serial.extend_from_slice(version.as_bytes());
serial.extend_from_slice(&digest);
write_frames(
&mut serial,
&meta_bytes,
&frame::fixed_chunk_lens(meta_bytes.len() as u64),
false,
)
.unwrap();
serial.extend_from_slice(&canon::uvarint_value(order.len() as u64));
for (id, len) in order.iter().zip(lens.iter()) {
serial.extend_from_slice(id.as_bytes());
serial.extend_from_slice(&canon::uvarint_value(*len));
}
serial.extend_from_slice(&blob_frame_bytes);
assert_eq!(
parallel, serial,
"the parallel writer's bytes differ from an independent serial re-implementation"
);
let decoded = from_bytes(¶llel).unwrap();
assert_eq!(decoded.ir, ir);
}
fn transform_chain_ir() -> Ir {
let mut b = IrBuilder::new(provenance());
let blob = b.add_blob(b"hello world".to_vec()).unwrap();
let root = b
.add_atom(AtomDraft {
parents: vec![],
ops: vec![PathOp::Add {
path: "readme".into(),
content: Content::blob(blob, 0o100_644),
status: EpistemicStatus::Stated,
}],
copies: vec![],
metadata: MetadataClaims::default(),
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: b"repo".to_vec(),
atom_id: b"c1".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
status: EpistemicStatus::Stated,
})
.unwrap();
let step0 = b.add_transform(TransformRecord {
name: "fix-mode".into(),
version: "1.0.0".into(),
params: BTreeMap::new(),
consumed: [0xaa; 32],
});
let step1 = b.add_transform(TransformRecord {
name: "renumber-author".into(),
version: "2.3.1".into(),
params: BTreeMap::from([("rule".to_string(), "mailmap".to_string())]),
consumed: [0xbb; 32],
});
assert_eq!((step0, step1), (0, 1));
let child_blob = b.add_blob(b"second revision".to_vec()).unwrap();
let child = b
.add_atom(AtomDraft {
parents: vec![root],
ops: vec![PathOp::Add {
path: "second".into(),
content: Content::blob(child_blob, 0o100_755),
status: EpistemicStatus::Transformed {
step: step0 as u64,
changed: vec![ChangedPart::Mode],
prior: Box::new(EpistemicStatus::Stated),
},
}],
copies: vec![],
metadata: MetadataClaims::default(),
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: b"repo".to_vec(),
atom_id: b"c2".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
status: EpistemicStatus::Transformed {
step: step1 as u64,
changed: vec![ChangedPart::Ops],
prior: Box::new(EpistemicStatus::Transformed {
step: step0 as u64,
changed: vec![ChangedPart::Author],
prior: Box::new(EpistemicStatus::Derived(crate::status::Derivation {
kind: crate::status::DerivationKind::NormalizedMetadata,
by: "brygge-decode-git".into(),
decoder_version: "0.1.0".into(),
params: BTreeMap::new(),
confidence: None,
})),
}),
},
})
.unwrap();
b.add_ref(RefRecord {
name: "refs/heads/main".into(),
kind: RefKind::Branch,
target: child,
status: EpistemicStatus::Transformed {
step: step1 as u64,
changed: vec![ChangedPart::Target],
prior: Box::new(EpistemicStatus::Stated),
},
source: None,
annotation: None,
})
.unwrap();
b.set_loss(LossBoundary {
dropped: vec![
DropRecord {
class: LossClass::Transform,
what: format!("op {} workflow-state.txt", root.to_hex()),
reason: "step 0 dropped it".into(),
step: Some(step0 as u64),
},
DropRecord {
class: LossClass::Transform,
what: "ref branch refs/heads/alias".into(),
reason: "step 1 dropped it".into(),
step: Some(step1 as u64),
},
],
});
b.finish().unwrap()
}
#[test]
fn transform_chain_round_trips_through_both_readers_and_digest_of_agrees() {
let ir = transform_chain_ir();
let bytes = to_bytes(&ir);
let via_from_bytes = from_bytes(&bytes).unwrap();
assert_eq!(via_from_bytes.ir, ir);
let via_read_from = read_from(std::io::Cursor::new(bytes)).unwrap();
assert_eq!(via_read_from.ir, ir);
assert_eq!(via_read_from.digest, via_from_bytes.digest);
assert_eq!(digest_of(&ir).unwrap(), via_from_bytes.digest);
}
#[test]
fn digest_of_agrees_with_decoded_digest_for_every_fixture() {
for ir in [
build(),
build_rich(),
fixture_ir(),
many_frame_ir(),
transform_chain_ir(),
] {
let decoded = from_bytes(&to_bytes(&ir)).unwrap();
assert_eq!(digest_of(&ir).unwrap(), decoded.digest);
}
}
#[test]
fn more_than_64_transform_records_is_rejected() {
let ir = Ir {
atoms: vec![],
refs: vec![],
provenance: provenance(),
loss: LossBoundary::default(),
flags: vec![],
content: crate::content::ContentStore::new(),
transforms: (0..65u16)
.map(|i| TransformRecord {
name: "t".into(),
version: "1".into(),
params: BTreeMap::new(),
consumed: [i as u8; 32],
})
.collect(),
};
let bytes = to_bytes(&ir);
match from_bytes(&bytes) {
Err(Error::NonCanonical(m)) => assert!(m.contains("64"), "{m}"),
other => panic!("expected NonCanonical, got {other:?}"),
}
match read_from(std::io::Cursor::new(bytes)) {
Err(Error::NonCanonical(m)) => assert!(m.contains("64"), "{m}"),
other => panic!("expected NonCanonical, got {other:?}"),
}
}
#[test]
fn an_ops_changed_using_the_atom_vocabulary_is_rejected() {
let mut b = IrBuilder::new(provenance());
let blob = b.add_blob(b"x".to_vec()).unwrap();
let step = b.add_transform(TransformRecord {
name: "t".into(),
version: "1".into(),
params: BTreeMap::new(),
consumed: [0u8; 32],
});
b.add_atom(AtomDraft {
parents: vec![],
ops: vec![PathOp::Add {
path: "p".into(),
content: Content::blob(blob, 0o100_644),
status: EpistemicStatus::Transformed {
step: step as u64,
changed: vec![ChangedPart::Author], prior: Box::new(EpistemicStatus::Stated),
},
}],
copies: vec![],
metadata: MetadataClaims::default(),
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: b"repo".to_vec(),
atom_id: b"c1".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
status: EpistemicStatus::Stated,
})
.unwrap();
let ir = b.finish().unwrap();
let bytes = to_bytes(&ir);
match from_bytes(&bytes) {
Err(Error::Decode(m)) => assert!(m.contains("vocabulary"), "{m}"),
other => panic!("expected Decode, got {other:?}"),
}
}
#[test]
fn a_step_on_a_representation_drop_is_rejected() {
let ir = Ir {
atoms: vec![],
refs: vec![],
provenance: provenance(),
loss: LossBoundary {
dropped: vec![DropRecord {
class: LossClass::Representation,
what: "packfiles".into(),
reason: "representation, not assertion".into(),
step: Some(0),
}],
},
flags: vec![],
content: crate::content::ContentStore::new(),
transforms: vec![TransformRecord {
name: "t".into(),
version: "1".into(),
params: BTreeMap::new(),
consumed: [0u8; 32],
}],
};
let bytes = to_bytes(&ir);
match from_bytes(&bytes) {
Err(Error::NonCanonical(m)) => assert!(m.contains("step"), "{m}"),
other => panic!("expected NonCanonical, got {other:?}"),
}
}
#[test]
fn field_6_in_a_0_2_0_artifact_is_rejected() {
let ir = transform_chain_ir();
let bytes = write_0_2_0(&ir);
match from_bytes(&bytes) {
Err(Error::NonCanonical(m)) => assert!(m.contains("field 6"), "{m}"),
other => panic!("expected NonCanonical, got {other:?}"),
}
match read_from(std::io::Cursor::new(bytes)) {
Err(Error::NonCanonical(m)) => assert!(m.contains("field 6"), "{m}"),
other => panic!("expected NonCanonical, got {other:?}"),
}
}