#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
use std::collections::BTreeMap;
use std::time::Duration;
use brygge_mutate::harness::{self, Outcome, Seed};
use brygge_mutate::ops::{Encoding, InterestingPosition};
use sha2::{Digest, Sha256};
use super::{from_bytes, read_from, to_bytes};
use crate::builder::{AtomDraft, IrBuilder};
use crate::model::{
ChangedPart, Content, DropRecord, Flag, FlagKind, ImportProvenance, Ir, LossBoundary,
LossClass, MetadataClaims, PathOp, RefKind, RefRecord, SourceIdentity, SourceKind,
TransformRecord,
};
use crate::status::EpistemicStatus;
const QUICK_ITERATIONS: u64 = 250;
const DEEP_FACTOR: u64 = 400;
const TIME_BUDGET: Duration = Duration::from_secs(2);
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 richer_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 {
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 revision, a bit longer than the first".to_vec())
.unwrap();
let step = b.add_transform(TransformRecord {
name: "renumber".into(),
version: "1.0.0".into(),
params: BTreeMap::new(),
consumed: [0x42; 32],
});
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::Transformed {
step: step 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: step as u64,
changed: vec![ChangedPart::Ops],
prior: Box::new(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: "mutation-seed".into(),
step: None,
},
DropRecord {
class: LossClass::Transform,
what: format!("atom {}", root.to_hex()),
reason: "mutation-seed".into(),
step: Some(step as u64),
},
],
});
b.add_flag(Flag {
kind: FlagKind::BelowConfidenceFloor,
what: "an example flag".into(),
count: 1,
reason: "mutation-seed".into(),
});
b.finish().unwrap()
}
fn simple_ir() -> Ir {
let mut b = IrBuilder::new(provenance());
let blob = b.add_blob(b"x".to_vec()).unwrap();
b.add_atom(AtomDraft {
parents: vec![],
ops: vec![PathOp::Add {
path: "a".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"c0".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
status: EpistemicStatus::Stated,
})
.unwrap();
b.finish().unwrap()
}
fn check(input_len: usize, decoded: &super::Decoded) -> Outcome {
let ceiling = 1096u64.saturating_mul(input_len as u64);
let total_blob_bytes = decoded.ir.content.total_bytes();
if total_blob_bytes > ceiling {
return Outcome::Violation(format!(
"decoded {total_blob_bytes} bytes of blob content from a {input_len}-byte artifact \
(ceiling {ceiling})"
));
}
let record_count = (decoded.ir.atoms.len()
+ decoded.ir.refs.len()
+ decoded.ir.loss.dropped.len()
+ decoded.ir.flags.len()) as u64;
if record_count > ceiling {
return Outcome::Violation(format!(
"decoded {record_count} records from a {input_len}-byte artifact (ceiling {ceiling})"
));
}
Outcome::Ok
}
fn outcome_tag(r: &Result<super::Decoded, crate::Error>) -> &'static str {
match r {
Ok(_) => "ok",
Err(crate::Error::Decode(_)) => "decode",
Err(crate::Error::DigestMismatch) => "digest_mismatch",
Err(crate::Error::PreReleaseArtifact) => "pre_release",
Err(crate::Error::UnsupportedContract { .. }) => "unsupported_contract",
Err(crate::Error::UnknownCriticalField { .. }) => "unknown_critical_field",
Err(crate::Error::NonCanonical(_)) => "non_canonical",
Err(crate::Error::Invariant(_)) => "invariant",
Err(crate::Error::Io(_)) => "io",
Err(crate::Error::ArtifactChanged(_)) => "artifact_changed",
Err(crate::Error::ResourceLimit { .. }) => "resource_limit",
}
}
fn check_equivalent(bytes: &[u8]) -> Result<super::Decoded, Outcome> {
let a = from_bytes(bytes);
let b = read_from(std::io::Cursor::new(bytes.to_vec()));
if outcome_tag(&a) != outcome_tag(&b) {
return Err(Outcome::Violation(format!(
"from_bytes and read_from disagree on a {}-byte input: {} vs {}",
bytes.len(),
outcome_tag(&a),
outcome_tag(&b)
)));
}
a.map_err(|_| Outcome::Ok)
}
fn check_raw(bytes: &[u8]) -> Outcome {
match check_equivalent(bytes) {
Ok(decoded) => check(bytes.len(), &decoded),
Err(outcome) => outcome,
}
}
fn split_header(bytes: &[u8]) -> (Vec<u8>, Vec<u8>) {
let after_format = bytes
.get(9..)
.expect("artifact long enough for format byte");
let mut r = crate::canon::CanonReader::new(after_format);
let _major = r.uvarint().unwrap();
let _minor = r.uvarint().unwrap();
let _patch = r.uvarint().unwrap();
let version_len = after_format.len() - r.remaining();
let version_bytes = after_format.get(..version_len).unwrap().to_vec();
let fixed_prefix = bytes.get(..9).unwrap().to_vec();
let digest_start = 9 + version_len;
let body = bytes.get(digest_start + 32..).unwrap().to_vec();
let mut prefix = fixed_prefix;
prefix.extend_from_slice(&version_bytes);
(prefix, body)
}
fn resign(prefix: &[u8], body: &[u8]) -> Vec<u8> {
let version_bytes = prefix.get(9..).unwrap_or(&[]);
let mut hasher = Sha256::new();
hasher.update(version_bytes);
hasher.update(body);
let digest: [u8; 32] = hasher.finalize().into();
let mut out = Vec::with_capacity(prefix.len() + 32 + body.len());
out.extend_from_slice(prefix);
out.extend_from_slice(&digest);
out.extend_from_slice(body);
out
}
fn check_resigned(prefix: &[u8], mutated_body: &[u8]) -> Outcome {
let full = resign(prefix, mutated_body);
match check_equivalent(&full) {
Ok(decoded) => check(full.len(), &decoded),
Err(outcome) => outcome,
}
}
fn meta_len_position(body: &[u8]) -> InterestingPosition {
let mut r = crate::canon::CanonReader::new(body);
let before = r.remaining();
let _ = r.uvarint();
let len = before - r.remaining();
InterestingPosition {
offset: 0,
encoding: Encoding::Uvarint { len },
ceiling: Some((body.len() - len) as u64),
}
}
#[test]
fn from_bytes_on_mutated_raw_bytes_never_panics_and_never_overclaims() {
let seeds: Vec<Vec<u8>> = vec![to_bytes(&richer_ir()), to_bytes(&simple_ir())];
let specs: Vec<Seed<'_>> = seeds.iter().map(|b| Seed::generic(b)).collect();
harness::run(
env!("CARGO_MANIFEST_DIR"),
"from_bytes_on_mutated_raw_bytes_never_panics_and_never_overclaims",
&specs,
QUICK_ITERATIONS,
DEEP_FACTOR,
TIME_BUDGET,
|_seed_index, bytes| check_raw(bytes),
);
}
#[test]
fn from_bytes_on_a_correctly_resigned_mutated_body_never_panics_and_never_overclaims() {
let full_a = to_bytes(&richer_ir());
let full_b = to_bytes(&simple_ir());
let (prefix_a, body_a) = split_header(&full_a);
let (prefix_b, body_b) = split_header(&full_b);
let pos_a = meta_len_position(&body_a);
let pos_b = meta_len_position(&body_b);
let positions_a = [pos_a];
let positions_b = [pos_b];
let specs = [
Seed::new(&body_a, &positions_a),
Seed::new(&body_b, &positions_b),
];
let prefixes = [prefix_a, prefix_b];
harness::run(
env!("CARGO_MANIFEST_DIR"),
"from_bytes_on_a_correctly_resigned_mutated_body_never_panics_and_never_overclaims",
&specs,
QUICK_ITERATIONS,
DEEP_FACTOR,
TIME_BUDGET,
|seed_index, mutated_body| {
let prefix = prefixes
.get(seed_index)
.expect("the harness never passes an out-of-range seed index");
check_resigned(prefix, mutated_body)
},
);
}
fn deflate_ir() -> Ir {
let mut b = IrBuilder::new(provenance());
let blob = b
.add_blob(b"the quick brown fox jumps over the lazy dog, ".repeat(400))
.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"c0".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
status: EpistemicStatus::Stated,
})
.unwrap();
b.finish().unwrap()
}
fn resign_v3_metadata_only(full: &[u8], mutated_meta_bytes: &[u8]) -> Vec<u8> {
let (prefix, rest) = split_header(full);
let version_bytes = prefix.get(9..).unwrap_or(&[]).to_vec();
let mut r = crate::canon::CanonReader::new(&rest);
let nframes_meta = r.uvarint().unwrap();
for _ in 0..nframes_meta {
let codec = crate::artifact::frame::Codec::from_u64(r.uvarint().unwrap()).unwrap();
let _raw_len = r.uvarint().unwrap();
let stored_len = r.uvarint_len().unwrap();
let _ = codec;
r.raw(stored_len).unwrap();
}
let tail_start = rest.len() - r.remaining();
let tail = rest.get(tail_start..).unwrap().to_vec();
let mut tr = crate::canon::CanonReader::new(&tail);
let nblobs = tr.uvarint().unwrap();
let table_start = tail.len() - tr.remaining();
let mut lens = Vec::with_capacity(nblobs as usize);
for _ in 0..nblobs {
tr.raw32().unwrap();
lens.push(tr.uvarint().unwrap());
}
let table_end = tail.len() - tr.remaining();
let table_bytes = tail.get(table_start..table_end).unwrap();
let nframes_blob = tr.uvarint().unwrap();
let mut blob_bytes = Vec::new();
for _ in 0..nframes_blob {
let codec = crate::artifact::frame::Codec::from_u64(tr.uvarint().unwrap()).unwrap();
let raw_len = tr.uvarint().unwrap();
let stored_len = tr.uvarint_len().unwrap();
let stored = tr.raw(stored_len).unwrap();
crate::artifact::frame::check_frame_bounds(codec, stored.len() as u64, raw_len).unwrap();
crate::artifact::frame::inflate_streamed(codec, stored, raw_len, |chunk| {
blob_bytes.extend_from_slice(chunk);
Ok(())
})
.unwrap();
}
let mut hasher = Sha256::new();
hasher.update(&version_bytes);
hasher.update(crate::canon::uvarint_value(mutated_meta_bytes.len() as u64));
hasher.update(mutated_meta_bytes);
hasher.update(crate::canon::uvarint_value(nblobs));
hasher.update(table_bytes);
hasher.update(&blob_bytes);
let digest: [u8; 32] = hasher.finalize().into();
let mut out = prefix.get(..9).unwrap().to_vec();
out.extend_from_slice(&version_bytes);
out.extend_from_slice(&digest);
let meta_len = mutated_meta_bytes.len() as u64;
let chunk_lens = crate::artifact::frame::fixed_chunk_lens(meta_len);
out.extend_from_slice(&crate::canon::uvarint_value(chunk_lens.len() as u64));
let mut offset = 0usize;
for len in chunk_lens {
let len = len as usize;
let chunk = mutated_meta_bytes.get(offset..offset + len).unwrap();
out.extend_from_slice(&crate::canon::uvarint_value(0)); out.extend_from_slice(&crate::canon::uvarint_value(len as u64));
out.extend_from_slice(&crate::canon::uvarint_value(len as u64));
out.extend_from_slice(chunk);
offset += len;
}
out.extend_from_slice(&tail[table_start..]);
out
}
pub(crate) struct Decomposed {
pub(crate) version_bytes: Vec<u8>,
pub(crate) meta_bytes: Vec<u8>,
pub(crate) table_bytes: Vec<u8>,
pub(crate) blob_bytes: Vec<u8>,
}
pub(crate) fn decompose(full: &[u8]) -> Decomposed {
let (prefix, rest) = split_header(full);
let version_bytes = prefix.get(9..).unwrap_or(&[]).to_vec();
let mut r = crate::canon::CanonReader::new(&rest);
let nframes_meta = r.uvarint().unwrap();
let mut meta_bytes = Vec::new();
for _ in 0..nframes_meta {
let codec = crate::artifact::frame::Codec::from_u64(r.uvarint().unwrap()).unwrap();
let raw_len = r.uvarint().unwrap();
let stored_len = r.uvarint_len().unwrap();
let stored = r.raw(stored_len).unwrap();
crate::artifact::frame::check_frame_bounds(codec, stored.len() as u64, raw_len).unwrap();
crate::artifact::frame::inflate_streamed(codec, stored, raw_len, |chunk| {
meta_bytes.extend_from_slice(chunk);
Ok(())
})
.unwrap();
}
let table_start = rest.len() - r.remaining();
let nblobs = r.uvarint().unwrap();
let mut lens = Vec::with_capacity(nblobs as usize);
for _ in 0..nblobs {
r.raw32().unwrap();
lens.push(r.uvarint().unwrap());
}
let table_end = rest.len() - r.remaining();
let table_bytes = rest.get(table_start..table_end).unwrap().to_vec();
let nframes_blob = r.uvarint().unwrap();
let mut blob_bytes = Vec::new();
for _ in 0..nframes_blob {
let codec = crate::artifact::frame::Codec::from_u64(r.uvarint().unwrap()).unwrap();
let raw_len = r.uvarint().unwrap();
let stored_len = r.uvarint_len().unwrap();
let stored = r.raw(stored_len).unwrap();
crate::artifact::frame::check_frame_bounds(codec, stored.len() as u64, raw_len).unwrap();
crate::artifact::frame::inflate_streamed(codec, stored, raw_len, |chunk| {
blob_bytes.extend_from_slice(chunk);
Ok(())
})
.unwrap();
}
Decomposed {
version_bytes,
meta_bytes,
table_bytes,
blob_bytes,
}
}
pub(crate) fn reassemble_v3(
version_bytes: &[u8],
meta_bytes: &[u8],
table_bytes: &[u8],
blob_bytes: &[u8],
) -> Vec<u8> {
let mut hasher = Sha256::new();
hasher.update(version_bytes);
hasher.update(crate::canon::uvarint_value(meta_bytes.len() as u64));
hasher.update(meta_bytes);
hasher.update(table_bytes);
hasher.update(blob_bytes);
let digest: [u8; 32] = hasher.finalize().into();
let mut out = Vec::new();
out.extend_from_slice(b"BRYGGEIR");
out.push(2);
out.extend_from_slice(version_bytes);
out.extend_from_slice(&digest);
out.extend_from_slice(&crate::canon::uvarint_value(1)); out.extend_from_slice(&crate::canon::uvarint_value(0)); out.extend_from_slice(&crate::canon::uvarint_value(meta_bytes.len() as u64));
out.extend_from_slice(&crate::canon::uvarint_value(meta_bytes.len() as u64));
out.extend_from_slice(meta_bytes);
out.extend_from_slice(table_bytes);
out.extend_from_slice(&crate::canon::uvarint_value(1)); out.extend_from_slice(&crate::canon::uvarint_value(0)); out.extend_from_slice(&crate::canon::uvarint_value(blob_bytes.len() as u64));
out.extend_from_slice(&crate::canon::uvarint_value(blob_bytes.len() as u64));
out.extend_from_slice(blob_bytes);
out
}
fn table_count_position(table_bytes: &[u8]) -> InterestingPosition {
let mut r = crate::canon::CanonReader::new(table_bytes);
let before = r.remaining();
let _ = r.uvarint();
let len = before - r.remaining();
InterestingPosition {
offset: 0,
encoding: Encoding::Uvarint { len },
ceiling: Some((table_bytes.len() - len) as u64),
}
}
#[test]
fn from_bytes_on_a_resigned_mutated_logical_table_never_panics_and_never_overclaims() {
let full_a = to_bytes(&richer_ir());
let full_b = to_bytes(&simple_ir());
let decomposed = [decompose(&full_a), decompose(&full_b)];
let pos_a = table_count_position(&decomposed[0].table_bytes);
let pos_b = table_count_position(&decomposed[1].table_bytes);
let positions_a = [pos_a];
let positions_b = [pos_b];
let specs = [
Seed::new(&decomposed[0].table_bytes, &positions_a),
Seed::new(&decomposed[1].table_bytes, &positions_b),
];
harness::run(
env!("CARGO_MANIFEST_DIR"),
"from_bytes_on_a_resigned_mutated_logical_table_never_panics_and_never_overclaims",
&specs,
QUICK_ITERATIONS,
DEEP_FACTOR,
TIME_BUDGET,
|seed_index, mutated_table| {
let d = decomposed
.get(seed_index)
.expect("the harness never passes an out-of-range seed index");
let full = reassemble_v3(
&d.version_bytes,
&d.meta_bytes,
mutated_table,
&d.blob_bytes,
);
match check_equivalent(&full) {
Ok(decoded) => check(full.len(), &decoded),
Err(outcome) => outcome,
}
},
);
}
#[test]
fn from_bytes_on_a_resigned_mutated_logical_blob_bytes_never_panics_and_never_overclaims() {
let full_a = to_bytes(&richer_ir());
let full_b = to_bytes(&simple_ir());
let decomposed = [decompose(&full_a), decompose(&full_b)];
let specs = [
Seed::generic(&decomposed[0].blob_bytes),
Seed::generic(&decomposed[1].blob_bytes),
];
harness::run(
env!("CARGO_MANIFEST_DIR"),
"from_bytes_on_a_resigned_mutated_logical_blob_bytes_never_panics_and_never_overclaims",
&specs,
QUICK_ITERATIONS,
DEEP_FACTOR,
TIME_BUDGET,
|seed_index, mutated_blob_bytes| {
let d = decomposed
.get(seed_index)
.expect("the harness never passes an out-of-range seed index");
let full = reassemble_v3(
&d.version_bytes,
&d.meta_bytes,
&d.table_bytes,
mutated_blob_bytes,
);
match check_equivalent(&full) {
Ok(decoded) => check(full.len(), &decoded),
Err(outcome) => outcome,
}
},
);
}
fn extract_meta_bytes(full: &[u8]) -> Vec<u8> {
let (_, rest) = split_header(full);
let mut r = crate::canon::CanonReader::new(&rest);
let nframes = r.uvarint().unwrap();
let mut out = Vec::new();
for _ in 0..nframes {
let codec = crate::artifact::frame::Codec::from_u64(r.uvarint().unwrap()).unwrap();
let raw_len = r.uvarint().unwrap();
let stored_len = r.uvarint_len().unwrap();
let stored = r.raw(stored_len).unwrap();
crate::artifact::frame::check_frame_bounds(codec, stored.len() as u64, raw_len).unwrap();
crate::artifact::frame::inflate_streamed(codec, stored, raw_len, |chunk| {
out.extend_from_slice(chunk);
Ok(())
})
.unwrap();
}
out
}
#[test]
fn from_bytes_on_a_resigned_mutated_logical_metadata_never_panics_and_never_overclaims() {
let full_a = to_bytes(&richer_ir());
let full_b = to_bytes(&simple_ir());
let meta_a = extract_meta_bytes(&full_a);
let meta_b = extract_meta_bytes(&full_b);
let specs = [Seed::generic(&meta_a), Seed::generic(&meta_b)];
let fulls = [full_a, full_b];
harness::run(
env!("CARGO_MANIFEST_DIR"),
"from_bytes_on_a_resigned_mutated_logical_metadata_never_panics_and_never_overclaims",
&specs,
QUICK_ITERATIONS,
DEEP_FACTOR,
TIME_BUDGET,
|seed_index, mutated_meta| {
let full = fulls
.get(seed_index)
.expect("the harness never passes an out-of-range seed index");
let resigned = resign_v3_metadata_only(full, mutated_meta);
match check_equivalent(&resigned) {
Ok(decoded) => check(resigned.len(), &decoded),
Err(outcome) => outcome,
}
},
);
}
#[test]
fn from_bytes_on_a_mutated_deflate_frame_never_panics_and_never_overclaims() {
let seed = to_bytes(&deflate_ir());
let specs = [Seed::generic(&seed)];
harness::run(
env!("CARGO_MANIFEST_DIR"),
"from_bytes_on_a_mutated_deflate_frame_never_panics_and_never_overclaims",
&specs,
QUICK_ITERATIONS,
DEEP_FACTOR,
TIME_BUDGET,
|_seed_index, bytes| check_raw(bytes),
);
}