From 1cee9bb321f977413443bdd495d571053c7bc330 Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 14:53:08 +0530 Subject: [PATCH 01/15] =?UTF-8?q?feat(core):=20keyed=20FastCDC=20chunking,?= =?UTF-8?q?=20per-chunk=20zstd,=20Padm=C3=A9=20inner=20plaintext=20and=20d?= =?UTF-8?q?ata=20and=20meta=20blobs=20(E1,=20E2,=20E3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .cargo/mutants.toml | 11 +- Cargo.lock | 54 +++ Cargo.toml | 1 + clippy.toml | 2 +- crates/engine/core/Cargo.toml | 21 + crates/engine/core/benches/chunking.rs | 47 ++ crates/engine/core/benches/inner.rs | 52 ++ crates/engine/core/src/blob/blob_context.rs | 42 ++ crates/engine/core/src/blob/blob_id_kind.rs | 55 +++ crates/engine/core/src/blob/chunk_entry.rs | 58 +++ crates/engine/core/src/blob/chunk_keys.rs | 140 ++++++ crates/engine/core/src/blob/data_blob_aad.rs | 43 ++ crates/engine/core/src/blob/meta_blob_aad.rs | 38 ++ crates/engine/core/src/blob/meta_context.rs | 43 ++ crates/engine/core/src/blob/meta_key.rs | 116 +++++ crates/engine/core/src/blob/meta_kind.rs | 72 +++ crates/engine/core/src/blob/mod.rs | 47 ++ crates/engine/core/src/blob/object_class.rs | 15 + crates/engine/core/src/blob/object_opener.rs | 458 ++++++++++++++++++ crates/engine/core/src/blob/object_sealer.rs | 110 +++++ crates/engine/core/src/blob/open_meta_blob.rs | 128 +++++ crates/engine/core/src/blob/opened_chunk.rs | 52 ++ crates/engine/core/src/blob/seal_meta_blob.rs | 26 + crates/engine/core/src/blob/sealed_chunk.rs | 82 ++++ crates/engine/core/src/blob/sealed_meta.rs | 67 +++ crates/engine/core/src/chunk/chunk_params.rs | 53 ++ crates/engine/core/src/chunk/chunk_ref.rs | 100 ++++ crates/engine/core/src/chunk/chunks.rs | 209 ++++++++ crates/engine/core/src/chunk/cut.rs | 248 ++++++++++ crates/engine/core/src/chunk/gear_table.rs | 110 +++++ crates/engine/core/src/chunk/masks.rs | 30 ++ crates/engine/core/src/chunk/mod.rs | 33 ++ crates/engine/core/src/chunk/object_shape.rs | 40 ++ .../engine/core/src/chunk/stream_chunker.rs | 443 +++++++++++++++++ crates/engine/core/src/chunk/stream_error.rs | 80 +++ .../core/src/compress/compress_error.rs | 127 +++++ crates/engine/core/src/compress/compressor.rs | 239 +++++++++ .../engine/core/src/compress/decompressor.rs | 338 +++++++++++++ .../engine/core/src/compress/frame_check.rs | 253 ++++++++++ .../core/src/compress/keep_compressed.rs | 35 ++ crates/engine/core/src/compress/mod.rs | 24 + crates/engine/core/src/error/mod.rs | 7 + crates/engine/core/src/error/read_error.rs | 155 ++++++ crates/engine/core/src/error/write_error.rs | 152 ++++++ crates/engine/core/src/inner/comp.rs | 50 ++ crates/engine/core/src/inner/decode_inner.rs | 173 +++++++ crates/engine/core/src/inner/encode_inner.rs | 86 ++++ crates/engine/core/src/inner/inner_view.rs | 53 ++ crates/engine/core/src/inner/mod.rs | 12 + crates/engine/core/src/lib.rs | 72 +++ crates/engine/core/src/limits.rs | 50 ++ crates/engine/core/src/pad/mod.rs | 5 + crates/engine/core/src/pad/padme.rs | 94 ++++ crates/engine/core/src/test_data.rs | 22 + 54 files changed, 5070 insertions(+), 3 deletions(-) create mode 100644 crates/engine/core/benches/chunking.rs create mode 100644 crates/engine/core/benches/inner.rs create mode 100644 crates/engine/core/src/blob/blob_context.rs create mode 100644 crates/engine/core/src/blob/blob_id_kind.rs create mode 100644 crates/engine/core/src/blob/chunk_entry.rs create mode 100644 crates/engine/core/src/blob/chunk_keys.rs create mode 100644 crates/engine/core/src/blob/data_blob_aad.rs create mode 100644 crates/engine/core/src/blob/meta_blob_aad.rs create mode 100644 crates/engine/core/src/blob/meta_context.rs create mode 100644 crates/engine/core/src/blob/meta_key.rs create mode 100644 crates/engine/core/src/blob/meta_kind.rs create mode 100644 crates/engine/core/src/blob/mod.rs create mode 100644 crates/engine/core/src/blob/object_class.rs create mode 100644 crates/engine/core/src/blob/object_opener.rs create mode 100644 crates/engine/core/src/blob/object_sealer.rs create mode 100644 crates/engine/core/src/blob/open_meta_blob.rs create mode 100644 crates/engine/core/src/blob/opened_chunk.rs create mode 100644 crates/engine/core/src/blob/seal_meta_blob.rs create mode 100644 crates/engine/core/src/blob/sealed_chunk.rs create mode 100644 crates/engine/core/src/blob/sealed_meta.rs create mode 100644 crates/engine/core/src/chunk/chunk_params.rs create mode 100644 crates/engine/core/src/chunk/chunk_ref.rs create mode 100644 crates/engine/core/src/chunk/chunks.rs create mode 100644 crates/engine/core/src/chunk/cut.rs create mode 100644 crates/engine/core/src/chunk/gear_table.rs create mode 100644 crates/engine/core/src/chunk/masks.rs create mode 100644 crates/engine/core/src/chunk/mod.rs create mode 100644 crates/engine/core/src/chunk/object_shape.rs create mode 100644 crates/engine/core/src/chunk/stream_chunker.rs create mode 100644 crates/engine/core/src/chunk/stream_error.rs create mode 100644 crates/engine/core/src/compress/compress_error.rs create mode 100644 crates/engine/core/src/compress/compressor.rs create mode 100644 crates/engine/core/src/compress/decompressor.rs create mode 100644 crates/engine/core/src/compress/frame_check.rs create mode 100644 crates/engine/core/src/compress/keep_compressed.rs create mode 100644 crates/engine/core/src/compress/mod.rs create mode 100644 crates/engine/core/src/error/mod.rs create mode 100644 crates/engine/core/src/error/read_error.rs create mode 100644 crates/engine/core/src/error/write_error.rs create mode 100644 crates/engine/core/src/inner/comp.rs create mode 100644 crates/engine/core/src/inner/decode_inner.rs create mode 100644 crates/engine/core/src/inner/encode_inner.rs create mode 100644 crates/engine/core/src/inner/inner_view.rs create mode 100644 crates/engine/core/src/inner/mod.rs create mode 100644 crates/engine/core/src/limits.rs create mode 100644 crates/engine/core/src/pad/mod.rs create mode 100644 crates/engine/core/src/pad/padme.rs create mode 100644 crates/engine/core/src/test_data.rs diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index ac1d619..bebc495 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -1,6 +1,13 @@ # cargo-mutants settings (https://mutants.rs/filter_mutants.html). -# `^` on flags with no bit in common is `|`, so these mutants cannot change behaviour. exclude_re = [ - 'replace \| with \^ in (map_secret|anonymous|map_marker)$', + # `^` on flags with no bit in common is `|`, so these mutants cannot change behaviour. + 'replace \| with \^ in (map_secret|anonymous|map_marker|frame_check)$', + # padme(2) is 2 by the general formula too (e = 1, s = 1, no low bits to clear). + 'replace < with <= in padme$', + # crypthix-core's Decompressor::stream: frame_check and an output buffer of exactly the + # declared content size let zstd finish the frame in its first call, so whether the loop + # breaks on hint 0 or on no progress never shows; after the frame a further call reads + # nothing and returns a non-zero hint. Both checks stay as defence in depth. + 'replace == with != in stream$', ] diff --git a/Cargo.lock b/Cargo.lock index 65a03aa..b09e7f0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -209,6 +209,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -394,6 +396,16 @@ version = "0.0.0" [[package]] name = "crypthix-core" version = "0.0.0" +dependencies = [ + "criterion", + "crypthix-crypto", + "crypthix-types", + "fastcdc", + "proptest", + "serde", + "serde_json", + "zstd-safe", +] [[package]] name = "crypthix-crypto" @@ -594,6 +606,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "fastcdc" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0431c3132902a1bed6fe77dcfa5d03844e083f263b81288246a2d43dd7d4b2ad" + [[package]] name = "fastrand" version = "2.5.0" @@ -712,6 +730,16 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom", + "libc", +] + [[package]] name = "libc" version = "0.2.191" @@ -761,6 +789,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "poly1305" version = "0.9.1" @@ -1241,6 +1275,7 @@ name = "xtask" version = "0.0.0" dependencies = [ "cargo_metadata", + "toml", ] [[package]] @@ -1274,3 +1309,22 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zstd-safe" +version = "8.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.2+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/Cargo.toml b/Cargo.toml index 3b44b27..ceb1069 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ publish = false # Internal crates other crates depend on. Add an entry when a crate gains its first dependent: # cargo warns about unused ones (see docs/backlog.md#architecture-rules for the layers). crypthix-types = { path = "crates/foundation/types" } +crypthix-crypto = { path = "crates/foundation/crypto" } crypthix-testkit = { path = "crates/foundation/testkit" } # External crates. diff --git a/clippy.toml b/clippy.toml index 6b832d1..cdfe233 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1,3 +1,3 @@ -doc-valid-idents = ["CryptHix", "RabbitMQ", "WinFsp", "FSKit", "BPF-LSM", ".."] +doc-valid-idents = ["CryptHix", "RabbitMQ", "WinFsp", "FSKit", "BPF-LSM", "FastCDC", ".."] allow-unwrap-in-tests = true allow-expect-in-tests = true diff --git a/crates/engine/core/Cargo.toml b/crates/engine/core/Cargo.toml index d99b3ca..0825c17 100644 --- a/crates/engine/core/Cargo.toml +++ b/crates/engine/core/Cargo.toml @@ -10,3 +10,24 @@ publish.workspace = true [lints] workspace = true + +[dependencies] +crypthix-crypto.workspace = true +crypthix-types.workspace = true +zstd-safe = { version = "8.2.0", default-features = false } + +[dev-dependencies] +criterion = { version = "0.8.2", default-features = false, features = ["cargo_bench_support"] } +crypthix-crypto = { workspace = true, features = ["vectors"] } +fastcdc = "5.0.0" +proptest = "1.12.0" +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" + +[[bench]] +name = "chunking" +harness = false + +[[bench]] +name = "inner" +harness = false diff --git a/crates/engine/core/benches/chunking.rs b/crates/engine/core/benches/chunking.rs new file mode 100644 index 0000000..93eec71 --- /dev/null +++ b/crates/engine/core/benches/chunking.rs @@ -0,0 +1,47 @@ +//! Benchmarks of the chunker: FastCDC over 64 MiB in memory and through a reader. + +use std::hint::black_box; + +use criterion::{Criterion, Throughput, criterion_group, criterion_main}; +use crypthix_core::blob::ObjectClass; +use crypthix_core::chunk::{Chunks, GearTable, StreamChunker}; +use crypthix_crypto::key::{KdfKey, XofKey}; +use crypthix_crypto::mac; +use crypthix_types::id::VaultId; + +const LEN: usize = 64 << 20; + +fn setup() -> (GearTable, Vec) { + let seed = KdfKey::random().expect("getrandom works"); + let vault_id = VaultId::try_from_bytes([1; 16]).expect("non-zero"); + let gear = GearTable::derive(&seed, &vault_id).expect("derives"); + let mut data = vec![0u8; LEN]; + mac::xof(&XofKey::random().expect("getrandom works"), &mut data); + (gear, data) +} + +fn chunking(c: &mut Criterion) { + let (gear, data) = setup(); + let mut group = c.benchmark_group("chunking"); + group.sample_size(10); + group.throughput(Throughput::Bytes(LEN as u64)); + group.bench_function("chunks/64MiB", |b| { + b.iter(|| Chunks::new(&gear, ObjectClass::Ordinary, black_box(&data)).count()); + }); + group.bench_function("stream/64MiB", |b| { + b.iter(|| { + let mut chunker = + StreamChunker::new(&gear, ObjectClass::Ordinary, black_box(data.as_slice())) + .expect("window"); + let mut count = 0usize; + while chunker.next_chunk().expect("reads").is_some() { + count += 1; + } + count + }); + }); + group.finish(); +} + +criterion_group!(benches, chunking); +criterion_main!(benches); diff --git a/crates/engine/core/benches/inner.rs b/crates/engine/core/benches/inner.rs new file mode 100644 index 0000000..5467553 --- /dev/null +++ b/crates/engine/core/benches/inner.rs @@ -0,0 +1,52 @@ +//! Benchmarks of a chunk's inner plaintext: compress and pad, then check and decompress, for a +//! 256 KiB chunk that compresses and one that does not. + +use std::hint::black_box; + +use criterion::{Criterion, Throughput, criterion_group, criterion_main}; +use crypthix_core::blob::ObjectClass; +use crypthix_core::compress::{Compressor, Decompressor}; +use crypthix_core::inner::{self, Comp}; +use crypthix_crypto::key::XofKey; +use crypthix_crypto::mac; + +const LEN: usize = 256 << 10; + +fn inner(c: &mut Criterion) { + let text: Vec = b"the quick brown fox jumps over the lazy dog " + .iter() + .copied() + .cycle() + .take(LEN) + .collect(); + let mut random = vec![0u8; LEN]; + mac::xof(&XofKey::random().expect("getrandom works"), &mut random); + let mut compressor = Compressor::new().expect("context"); + let mut decompressor = Decompressor::new(); + let mut group = c.benchmark_group("inner"); + group.throughput(Throughput::Bytes(LEN as u64)); + for (name, chunk) in [("compressible", &text), ("random", &random)] { + group.bench_function(format!("encode/{name}"), |b| { + b.iter(|| compressor.encode_chunk(black_box(chunk), ObjectClass::Ordinary)); + }); + let encoded = compressor + .encode_chunk(chunk, ObjectClass::Ordinary) + .expect("encodes"); + group.bench_function(format!("decode/{name}"), |b| { + b.iter(|| { + let view = inner::decode_inner(black_box(&encoded)).expect("well formed"); + match view.comp() { + Comp::Zstd => decompressor + .decode(view.payload(), LEN as u64) + .map(|plain| plain.len()) + .expect("decodes"), + _ => view.payload().len(), + } + }); + }); + } + group.finish(); +} + +criterion_group!(benches, inner); +criterion_main!(benches); diff --git a/crates/engine/core/src/blob/blob_context.rs b/crates/engine/core/src/blob/blob_context.rs new file mode 100644 index 0000000..be2e5df --- /dev/null +++ b/crates/engine/core/src/blob/blob_context.rs @@ -0,0 +1,42 @@ +//! What a data blob is bound to. + +use crypthix_types::id::{DekId, ObjectId, VaultId}; + +/// The vault, object and DEK a data blob belongs to: the KDF context of its keys (FS-38) and +/// the fixed part of its AAD (FS-55). +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub struct BlobContext { + vault: VaultId, + object: ObjectId, + dek: DekId, +} + +impl BlobContext { + /// The context of one object's chunks under one DEK. + #[must_use] + pub const fn new(vault_id: VaultId, object_id: ObjectId, dek_id: DekId) -> Self { + Self { + vault: vault_id, + object: object_id, + dek: dek_id, + } + } + + /// The vault. + #[must_use] + pub const fn vault_id(&self) -> &VaultId { + &self.vault + } + + /// The object. + #[must_use] + pub const fn object_id(&self) -> &ObjectId { + &self.object + } + + /// The object's DEK. + #[must_use] + pub const fn dek_id(&self) -> &DekId { + &self.dek + } +} diff --git a/crates/engine/core/src/blob/blob_id_kind.rs b/crates/engine/core/src/blob/blob_id_kind.rs new file mode 100644 index 0000000..256c6b4 --- /dev/null +++ b/crates/engine/core/src/blob/blob_id_kind.rs @@ -0,0 +1,55 @@ +//! Keyed or random blob IDs (FS-55, FS-56). + +use crate::blob::ObjectClass; + +/// How the blob IDs of an object's chunks are made (FS-55). +#[non_exhaustive] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub enum BlobIdKind { + /// `MAC(K_blobid, chunk plaintext)`: an unchanged chunk keeps its ID, so the next version of + /// the object reuses its blob (E1). The reader recomputes it (`Binding`, FS-56). + Keyed, + /// 32 random bytes: nothing is reused, so content injected into the object cannot confirm a + /// guess through the number of new packs (T-85). + Random, +} + +impl BlobIdKind { + /// Keyed exactly when the object is of the ordinary class and has two or more chunks; + /// random otherwise. A reader takes the class and the chunk count from the manifest + /// ([`ObjectOpener`](crate::blob::ObjectOpener)); a writer takes the count from the chunker + /// ([`ObjectSealer`](crate::blob::ObjectSealer) with an + /// [`ObjectShape`](crate::chunk::ObjectShape)), so the two always agree. + #[must_use] + pub const fn for_object(class: ObjectClass, chunk_count: u64) -> Self { + match class { + ObjectClass::Ordinary if chunk_count >= 2 => BlobIdKind::Keyed, + ObjectClass::Ordinary | ObjectClass::Secret => BlobIdKind::Random, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_ordinary_objects_of_two_or_more_chunks_are_keyed() { + let cases = [ + (ObjectClass::Ordinary, 0, BlobIdKind::Random), + (ObjectClass::Ordinary, 1, BlobIdKind::Random), + (ObjectClass::Ordinary, 2, BlobIdKind::Keyed), + (ObjectClass::Ordinary, u64::MAX, BlobIdKind::Keyed), + (ObjectClass::Secret, 1, BlobIdKind::Random), + (ObjectClass::Secret, 2, BlobIdKind::Random), + (ObjectClass::Secret, u64::MAX, BlobIdKind::Random), + ]; + for (class, count, kind) in cases { + assert_eq!( + BlobIdKind::for_object(class, count), + kind, + "{class:?} {count}" + ); + } + } +} diff --git a/crates/engine/core/src/blob/chunk_entry.rs b/crates/engine/core/src/blob/chunk_entry.rs new file mode 100644 index 0000000..ab24d42 --- /dev/null +++ b/crates/engine/core/src/blob/chunk_entry.rs @@ -0,0 +1,58 @@ +//! What a manifest says about one chunk. + +use std::fmt; + +use crypthix_types::id::BlobId; + +/// A chunk as its manifest lists it: its blob ID and its length before compression. +/// +/// Its `Debug` shows only the length: a keyed blob ID is a MAC of the chunk's content (FS-55), +/// so even its first bytes are kept out of logs. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct ChunkEntry { + blob_id: BlobId, + plain_len: u64, +} + +impl ChunkEntry { + /// An entry. `plain_len` is checked against the 1 MiB cap when the chunk is opened. + #[must_use] + pub const fn new(blob_id: BlobId, plain_len: u64) -> Self { + Self { blob_id, plain_len } + } + + /// The blob ID. + #[must_use] + pub const fn blob_id(&self) -> &BlobId { + &self.blob_id + } + + /// The chunk's length before compression. + #[must_use] + pub const fn plain_len(&self) -> u64 { + self.plain_len + } +} + +/// Prints the length, not the blob ID. +impl fmt::Debug for ChunkEntry { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ChunkEntry") + .field("plain_len", &self.plain_len) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn debug_shows_the_length_and_no_byte_of_the_blob_id() { + let id = BlobId::try_from_bytes([0xef; 32]).expect("non-zero ID"); + let entry = ChunkEntry::new(id, 4_096); + let printed = format!("{entry:?}"); + assert_eq!(printed, "ChunkEntry { plain_len: 4096, .. }"); + assert!(!printed.contains("ef"), "{printed}"); + } +} diff --git a/crates/engine/core/src/blob/chunk_keys.rs b/crates/engine/core/src/blob/chunk_keys.rs new file mode 100644 index 0000000..f34b868 --- /dev/null +++ b/crates/engine/core/src/blob/chunk_keys.rs @@ -0,0 +1,140 @@ +//! The per-object keys of data blobs (FS-38). + +use std::fmt; + +use crypthix_crypto::kdf::{self, KdfContext}; +use crypthix_crypto::key::{KdfKey, KeyError, MacKey, SealKey}; +use crypthix_crypto::label::{MacKeyLabel, SealKeyLabel}; +use crypthix_types::format_error::FormatError; + +use crate::blob::BlobContext; + +/// `K_chunk` and `K_blobid` of one object: derived from its DEK with its `dek_salt` under +/// `kdf/chunk-key` and `kdf/blob-id-key`, with context `vault_id ‖ object_id ‖ dek_id` (FS-38). +/// +/// The keys keep the [`BlobContext`] they were derived for, which is also the fixed part of the +/// AAD of the object's data blobs (FS-55), so one object's keys are never used with another +/// object's AAD. [`ObjectSealer`](crate::blob::ObjectSealer) and +/// [`ObjectOpener`](crate::blob::ObjectOpener) seal and open with them. +pub struct ChunkKeys { + chunk: SealKey, + blob_id: MacKey, + context: BlobContext, +} + +impl ChunkKeys { + /// Derives the keys of the object `context` names. + /// + /// # Errors + /// + /// - [`KeyError::Format`] with `ZeroValue` if `dek_salt` is all zero (FS-03). + /// - [`KeyError::Memory`] if protected memory cannot be allocated for a key. + /// + /// # Panics + /// + /// On Linux, in a child forked without `exec` after `dek` was made. + pub fn derive( + dek: &KdfKey, + dek_salt: &[u8; 32], + context: BlobContext, + ) -> Result { + if *dek_salt == [0u8; 32] { + return Err(FormatError::ZeroValue.into()); + } + let kdf_context = KdfContext::new() + .field(context.vault_id().as_bytes()) + .field(context.object_id().as_bytes()) + .field(context.dek_id().as_bytes()); + let chunk = kdf::kdf(dek, Some(dek_salt), SealKeyLabel::ChunkKey, &kdf_context)?; + let blob_id = kdf::kdf(dek, Some(dek_salt), MacKeyLabel::BlobIdKey, &kdf_context)?; + Ok(Self { + chunk, + blob_id, + context, + }) + } + + /// The vault, object and DEK the keys were derived for. + #[must_use] + pub const fn context(&self) -> &BlobContext { + &self.context + } + + /// `K_chunk`, which seals the object's data blobs. + #[must_use] + pub const fn chunk_key(&self) -> &SealKey { + &self.chunk + } + + /// `K_blobid`, which keys the blob IDs of an ordinary object. + #[must_use] + pub const fn blob_id_key(&self) -> &MacKey { + &self.blob_id + } +} + +/// Prints no key bytes. +impl fmt::Debug for ChunkKeys { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ChunkKeys(..)") + } +} + +#[cfg(test)] +pub(crate) mod tests { + use crypthix_types::id::{DekId, ObjectId, VaultId}; + + use super::*; + + pub(crate) fn context(object: u8) -> BlobContext { + BlobContext::new( + VaultId::try_from_bytes([1; 16]).expect("non-zero"), + ObjectId::try_from_bytes([object; 16]).expect("non-zero"), + DekId::try_from_bytes([3; 16]).expect("non-zero"), + ) + } + + pub(crate) fn keys(object: u8) -> ChunkKeys { + let dek = KdfKey::from_bytes([9; 32]).expect("non-zero"); + ChunkKeys::derive(&dek, &[7; 32], context(object)).expect("derives") + } + + #[test] + fn keys_follow_the_fs_38_table() { + let dek = KdfKey::from_bytes([9; 32]).expect("non-zero"); + let mut kdf_context = Vec::new(); + kdf_context.extend_from_slice(&[1; 16]); + kdf_context.extend_from_slice(&[2; 16]); + kdf_context.extend_from_slice(&[3; 16]); + let kdf_context = KdfContext::from_bytes(kdf_context); + let chunk: SealKey = + kdf::kdf(&dek, Some(&[7; 32]), SealKeyLabel::ChunkKey, &kdf_context).expect("derives"); + let blob_id: MacKey = + kdf::kdf(&dek, Some(&[7; 32]), MacKeyLabel::BlobIdKey, &kdf_context).expect("derives"); + let keys = keys(2); + assert_eq!(keys.context(), &context(2)); + assert_eq!(keys.chunk_key().to_bytes(), chunk.to_bytes()); + assert_eq!(keys.blob_id_key().to_bytes(), blob_id.to_bytes()); + assert_ne!(chunk.to_bytes(), blob_id.to_bytes()); + assert_ne!( + keys.chunk_key().to_bytes(), + self::keys(4).chunk_key().to_bytes(), + "the object ID is in the context" + ); + assert_eq!(format!("{keys:?}"), "ChunkKeys(..)"); + } + + #[test] + fn the_salt_is_used_and_may_not_be_zero() { + let dek = KdfKey::from_bytes([9; 32]).expect("non-zero"); + let salted = ChunkKeys::derive(&dek, &[8; 32], context(2)).expect("derives"); + assert_ne!( + salted.chunk_key().to_bytes(), + keys(2).chunk_key().to_bytes() + ); + assert_eq!( + ChunkKeys::derive(&dek, &[0; 32], context(2)).map(|_| ()), + Err(KeyError::Format(FormatError::ZeroValue)) + ); + } +} diff --git a/crates/engine/core/src/blob/data_blob_aad.rs b/crates/engine/core/src/blob/data_blob_aad.rs new file mode 100644 index 0000000..a2c7a3e --- /dev/null +++ b/crates/engine/core/src/blob/data_blob_aad.rs @@ -0,0 +1,43 @@ +//! The AAD of a data blob (FS-55). + +use crypthix_crypto::aad::Aad; +use crypthix_crypto::label::AadLabel; +use crypthix_types::id::BlobId; + +use crate::blob::BlobContext; + +/// The blob kind byte of a data blob (format spec 10.4). +pub const DATA_BLOB_KIND: u8 = 0x01; + +/// `u8 len ‖ "crypthix/v0/aad/blob-data" ‖ fmt ‖ suite ‖ vault_id ‖ u8 0x01 ‖ object_id ‖ +/// dek_id ‖ blob_id` (FS-55). +pub fn data_blob_aad(context: &BlobContext, blob_id: &BlobId) -> Aad { + Aad::new(AadLabel::BlobData) + .field(context.vault_id().as_bytes()) + .u8(DATA_BLOB_KIND) + .field(context.object_id().as_bytes()) + .field(context.dek_id().as_bytes()) + .field(blob_id.as_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::blob::chunk_keys::tests::context; + + #[test] + fn layout_is_fs_55() { + let blob_id = BlobId::try_from_bytes([4; 32]).expect("non-zero"); + let aad = data_blob_aad(&context(2), &blob_id); + let label = b"crypthix/v0/aad/blob-data"; + let mut expected = vec![25u8]; + expected.extend_from_slice(label); + expected.extend_from_slice(&[0, 0, 0, 1]); + expected.extend_from_slice(&[1; 16]); + expected.push(0x01); + expected.extend_from_slice(&[2; 16]); + expected.extend_from_slice(&[3; 16]); + expected.extend_from_slice(&[4; 32]); + assert_eq!(aad.as_bytes(), expected.as_slice()); + } +} diff --git a/crates/engine/core/src/blob/meta_blob_aad.rs b/crates/engine/core/src/blob/meta_blob_aad.rs new file mode 100644 index 0000000..f526cd9 --- /dev/null +++ b/crates/engine/core/src/blob/meta_blob_aad.rs @@ -0,0 +1,38 @@ +//! The AAD of a meta blob (FS-57). + +use crypthix_crypto::aad::Aad; +use crypthix_crypto::label::AadLabel; +use crypthix_types::id::BlobId; + +use crate::blob::MetaContext; + +/// `u8 len ‖ "crypthix/v0/aad/blob-meta" ‖ fmt ‖ suite ‖ vault_id ‖ u8 kind ‖ u32be epoch ‖ +/// blob_id` (FS-57). +pub fn meta_blob_aad(context: &MetaContext, blob_id: &BlobId) -> Aad { + Aad::new(AadLabel::BlobMeta) + .field(context.vault_id().as_bytes()) + .u8(context.kind().code()) + .u32be(context.epoch().get()) + .field(blob_id.as_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::blob::MetaKind; + use crate::blob::meta_key::tests::meta_context; + + #[test] + fn layout_is_fs_57() { + let blob_id = BlobId::try_from_bytes([4; 32]).expect("non-zero"); + let aad = meta_blob_aad(&meta_context(MetaKind::GcCandidate, 258), &blob_id); + let mut expected = vec![25u8]; + expected.extend_from_slice(b"crypthix/v0/aad/blob-meta"); + expected.extend_from_slice(&[0, 0, 0, 1]); + expected.extend_from_slice(&[1; 16]); + expected.push(0x08); + expected.extend_from_slice(&[0, 0, 1, 2]); + expected.extend_from_slice(&[4; 32]); + assert_eq!(aad.as_bytes(), expected.as_slice()); + } +} diff --git a/crates/engine/core/src/blob/meta_context.rs b/crates/engine/core/src/blob/meta_context.rs new file mode 100644 index 0000000..c583203 --- /dev/null +++ b/crates/engine/core/src/blob/meta_context.rs @@ -0,0 +1,43 @@ +//! What a meta blob is bound to. + +use crypthix_types::id::{Epoch, VaultId}; + +use crate::blob::MetaKind; + +/// The vault, kind and epoch of a meta blob: the fixed part of its AAD (FS-57). +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub struct MetaContext { + vault_id: VaultId, + kind: MetaKind, + epoch: Epoch, +} + +impl MetaContext { + /// The context of one kind of node under one epoch. + #[must_use] + pub const fn new(vault_id: VaultId, kind: MetaKind, epoch: Epoch) -> Self { + Self { + vault_id, + kind, + epoch, + } + } + + /// The vault. + #[must_use] + pub const fn vault_id(&self) -> &VaultId { + &self.vault_id + } + + /// The kind of node. + #[must_use] + pub const fn kind(&self) -> MetaKind { + self.kind + } + + /// The epoch whose key seals it. + #[must_use] + pub const fn epoch(&self) -> Epoch { + self.epoch + } +} diff --git a/crates/engine/core/src/blob/meta_key.rs b/crates/engine/core/src/blob/meta_key.rs new file mode 100644 index 0000000..0c359c1 --- /dev/null +++ b/crates/engine/core/src/blob/meta_key.rs @@ -0,0 +1,116 @@ +//! The epoch key that seals one kind of meta blob (FS-38, FS-57). + +use std::fmt; + +use crypthix_crypto::kdf::{self, KdfContext}; +use crypthix_crypto::key::{KdfKey, SealKey}; +use crypthix_crypto::label::SealKeyLabel; +use crypthix_crypto::secure_mem::MemError; + +use crate::blob::{MetaContext, MetaKind}; + +/// `K_kind_e` together with the [`MetaContext`] it was derived for: the key that seals one kind +/// of meta blob in one epoch of one vault (FS-38, FS-57). +/// +/// [`seal_meta_blob`](crate::blob::seal_meta_blob) and +/// [`open_meta_blob`](crate::blob::open_meta_blob) take the AAD's vault, kind and epoch from +/// here, so a key is never used with another context's AAD: a location key with a GC-candidate +/// kind byte, or one epoch's key with another epoch, would seal blobs that never open. +pub struct MetaKey { + key: SealKey, + context: MetaContext, +} + +impl MetaKey { + /// `K_kind_e = KDF(KEK_e, -, label, vault_id ‖ u32be(e))` for the context's kind and epoch, + /// where `kek` is that epoch's KEK (FS-38): `kdf/index-key`, `kdf/key-table-key`, + /// `kdf/location-key` (for location and GC-candidate nodes) or `kdf/pack-table-key`. + /// + /// # Errors + /// + /// [`MemError`] if protected memory cannot be allocated for the key. + /// + /// # Panics + /// + /// On Linux, in a child forked without `exec` after `kek` was made. + pub fn derive(kek: &KdfKey, context: MetaContext) -> Result { + let label = match context.kind() { + MetaKind::Index => SealKeyLabel::IndexKey, + MetaKind::KeyTable => SealKeyLabel::KeyTableKey, + MetaKind::Location | MetaKind::GcCandidate => SealKeyLabel::LocationKey, + MetaKind::PackTable => SealKeyLabel::PackTableKey, + }; + let kdf_context = KdfContext::new() + .field(context.vault_id().as_bytes()) + .u32be(context.epoch().get()); + let key = kdf::kdf(kek, None, label, &kdf_context)?; + Ok(Self { key, context }) + } + + /// The seal key, `K_kind_e`. + #[must_use] + pub const fn seal_key(&self) -> &SealKey { + &self.key + } + + /// The vault, kind and epoch the key was derived for. + #[must_use] + pub const fn context(&self) -> &MetaContext { + &self.context + } +} + +/// Prints the context, never the key. +impl fmt::Debug for MetaKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MetaKey") + .field("context", &self.context) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +pub(crate) mod tests { + use crypthix_types::id::{Epoch, VaultId}; + + use super::*; + + pub(crate) fn meta_context(kind: MetaKind, epoch: u32) -> MetaContext { + MetaContext::new( + VaultId::try_from_bytes([1; 16]).expect("non-zero"), + kind, + Epoch::try_new(epoch).expect("non-zero"), + ) + } + + #[test] + fn each_kind_uses_its_fs_38_label_and_context() { + let kek = KdfKey::from_bytes([5; 32]).expect("non-zero"); + let mut context = vec![1u8; 16]; + context.extend_from_slice(&2u32.to_be_bytes()); + let context = KdfContext::from_bytes(context); + let expected = |label: SealKeyLabel| { + let key: SealKey = kdf::kdf(&kek, None, label, &context).expect("derives"); + key.to_bytes() + }; + let cases = [ + (MetaKind::Index, SealKeyLabel::IndexKey), + (MetaKind::KeyTable, SealKeyLabel::KeyTableKey), + (MetaKind::Location, SealKeyLabel::LocationKey), + (MetaKind::PackTable, SealKeyLabel::PackTableKey), + (MetaKind::GcCandidate, SealKeyLabel::LocationKey), + ]; + for (kind, label) in cases { + let key = MetaKey::derive(&kek, meta_context(kind, 2)).expect("derives"); + assert_eq!(key.seal_key().to_bytes(), expected(label), "{kind:?}"); + assert_eq!(key.context(), &meta_context(kind, 2)); + } + let other_epoch = MetaKey::derive(&kek, meta_context(MetaKind::Index, 3)).expect("derives"); + assert_ne!( + other_epoch.seal_key().to_bytes(), + expected(SealKeyLabel::IndexKey) + ); + let printed = format!("{other_epoch:?}"); + assert!(printed.starts_with("MetaKey { context: "), "{printed}"); + } +} diff --git a/crates/engine/core/src/blob/meta_kind.rs b/crates/engine/core/src/blob/meta_kind.rs new file mode 100644 index 0000000..941782e --- /dev/null +++ b/crates/engine/core/src/blob/meta_kind.rs @@ -0,0 +1,72 @@ +//! The kinds of meta blob (format spec 10.4). + +/// A meta blob's kind: the tree node it holds, and its kind byte in the AAD (FS-57). +#[non_exhaustive] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub enum MetaKind { + /// 0x03: a path-index node, sealed under `K_idx_e`. + Index, + /// 0x04: a key-table node, sealed under `K_kt_e`. + KeyTable, + /// 0x05: a location node, sealed under `K_loc_e`. + Location, + /// 0x06: a pack-table node, sealed under `K_pt_e`. + PackTable, + /// 0x08: a GC-candidate node, sealed under `K_loc_e`; the kind byte keeps it apart from + /// location nodes. + GcCandidate, +} + +impl MetaKind { + /// Every kind, in code order. + pub const ALL: [MetaKind; 5] = [ + MetaKind::Index, + MetaKind::KeyTable, + MetaKind::Location, + MetaKind::PackTable, + MetaKind::GcCandidate, + ]; + + /// The kind byte. + #[must_use] + pub const fn code(self) -> u8 { + match self { + MetaKind::Index => 0x03, + MetaKind::KeyTable => 0x04, + MetaKind::Location => 0x05, + MetaKind::PackTable => 0x06, + MetaKind::GcCandidate => 0x08, + } + } + + /// The kind a byte names; `None` for data (0x01), manifest (0x02), the reserved snapshot + /// node (0x07) and anything unknown. + #[must_use] + pub const fn from_code(code: u8) -> Option { + match code { + 0x03 => Some(MetaKind::Index), + 0x04 => Some(MetaKind::KeyTable), + 0x05 => Some(MetaKind::Location), + 0x06 => Some(MetaKind::PackTable), + 0x08 => Some(MetaKind::GcCandidate), + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codes_round_trip_and_others_are_not_meta() { + for kind in MetaKind::ALL { + assert_eq!(MetaKind::from_code(kind.code()), Some(kind)); + } + let known: Vec = MetaKind::ALL.iter().map(|kind| kind.code()).collect(); + assert_eq!(known, [3, 4, 5, 6, 8]); + for code in [0, 1, 2, 7, 9, 0xFF] { + assert_eq!(MetaKind::from_code(code), None, "{code}"); + } + } +} diff --git a/crates/engine/core/src/blob/mod.rs b/crates/engine/core/src/blob/mod.rs new file mode 100644 index 0000000..a46ec5f --- /dev/null +++ b/crates/engine/core/src/blob/mod.rs @@ -0,0 +1,47 @@ +//! Data blobs and meta blobs (format spec 10.4). +//! +//! A data blob is one chunk's inner plaintext sealed under `K_chunk` with an AAD that binds it +//! to its vault, object, DEK and blob ID (FS-55). Its blob ID is keyed per object for ordinary +//! objects of two or more chunks, so an unchanged chunk is reused by the next version of the +//! same object and nothing is shared across objects (T-85); otherwise it is random. A meta blob +//! is a CBOR tree node sealed under its epoch's key for its kind, with a random blob ID (FS-57). +//! +//! Keys are bound to what they were derived for: [`ChunkKeys`] to its object's +//! [`BlobContext`], used through an [`ObjectSealer`] or [`ObjectOpener`] built once per object +//! with its class and chunk count, and a [`MetaKey`] to its [`MetaContext`]. + +mod blob_context; +mod blob_id_kind; +mod chunk_entry; +mod chunk_keys; +mod data_blob_aad; +mod meta_blob_aad; +mod meta_context; +mod meta_key; +mod meta_kind; +mod object_class; +mod object_opener; +mod object_sealer; +mod open_meta_blob; +mod opened_chunk; +mod seal_meta_blob; +mod sealed_chunk; +mod sealed_meta; + +pub use blob_context::BlobContext; +pub use blob_id_kind::BlobIdKind; +pub use chunk_entry::ChunkEntry; +pub use chunk_keys::ChunkKeys; +pub use data_blob_aad::{DATA_BLOB_KIND, data_blob_aad}; +pub use meta_blob_aad::meta_blob_aad; +pub use meta_context::MetaContext; +pub use meta_key::MetaKey; +pub use meta_kind::MetaKind; +pub use object_class::ObjectClass; +pub use object_opener::ObjectOpener; +pub use object_sealer::ObjectSealer; +pub use open_meta_blob::open_meta_blob; +pub use opened_chunk::OpenedChunk; +pub use seal_meta_blob::seal_meta_blob; +pub use sealed_chunk::SealedChunk; +pub use sealed_meta::SealedMeta; diff --git a/crates/engine/core/src/blob/object_class.rs b/crates/engine/core/src/blob/object_class.rs new file mode 100644 index 0000000..579951d --- /dev/null +++ b/crates/engine/core/src/blob/object_class.rs @@ -0,0 +1,15 @@ +//! The two classes of object (FS-52, FS-53, FS-55). + +/// How an object's chunks are cut and written. +#[non_exhaustive] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub enum ObjectClass { + /// Cut with keyed FastCDC (FS-52), compressed where it pays (FS-53), and with keyed blob IDs + /// when the object has two or more chunks, so an unchanged chunk is reused by the next + /// version (FS-55). + Ordinary, + /// Cut at fixed 1 MiB steps without reading the bytes (FS-52), never compressed, so nothing + /// in the object shares a compression context with its secrets (T-40), and always with + /// random blob IDs, so nothing is reused (FS-55, T-85). + Secret, +} diff --git a/crates/engine/core/src/blob/object_opener.rs b/crates/engine/core/src/blob/object_opener.rs new file mode 100644 index 0000000..bf4e257 --- /dev/null +++ b/crates/engine/core/src/blob/object_opener.rs @@ -0,0 +1,458 @@ +//! Opening the data blobs of one object (FS-55, FS-56). + +use crypthix_crypto::cx_aead; +use crypthix_crypto::hash::Hash32; +use crypthix_crypto::mac; +use crypthix_crypto::secure_mem::SecretBuf; +use crypthix_types::format_error::FormatError; + +use crate::blob::{BlobIdKind, ChunkEntry, ChunkKeys, ObjectClass, OpenedChunk, data_blob_aad}; +use crate::compress::Decompressor; +use crate::error::ReadError; +use crate::inner::{Comp, decode_inner}; +use crate::limits::MAX_PLAIN_LEN; + +/// Opens the data blobs of one object, built once from the object's keys and the `class` and +/// `chunk_count` of its signed manifest (FS-55, FS-56). +/// +/// The keys carry the [`BlobContext`](crate::blob::BlobContext) of the AAD, and the blob-ID +/// kind is derived here from the class and the count ([`BlobIdKind::for_object`]), so no call +/// can mix one object's keys with another's AAD or check a chunk under another kind. +#[derive(Debug)] +pub struct ObjectOpener<'k> { + keys: &'k ChunkKeys, + class: ObjectClass, + blob_id_kind: BlobIdKind, +} + +impl<'k> ObjectOpener<'k> { + /// The opener of the object `keys` belong to, with the `class` and `chunk_count` its + /// manifest records. + #[must_use] + pub const fn new(keys: &'k ChunkKeys, class: ObjectClass, chunk_count: u64) -> Self { + Self { + keys, + class, + blob_id_kind: BlobIdKind::for_object(class, chunk_count), + } + } + + /// The object's class. + #[must_use] + pub const fn class(&self) -> ObjectClass { + self.class + } + + /// How the object's blob IDs are made. + #[must_use] + pub const fn blob_id_kind(&self) -> BlobIdKind { + self.blob_id_kind + } + + /// Opens the data blob of `entry` and returns its plaintext. + /// + /// The checks run in this order, and the first failure is the error (FS-93); no plaintext + /// is released before all of them pass: + /// 1. `plain_len` is at most 1 MiB (`Decompress`), before anything is decrypted or + /// allocated; + /// 2. the CX-AEAD open under `K_chunk` and the AAD of FS-55 (`Decrypt`, or `Truncated` / + /// `ZeroValue` for input too short to be a seal or with a zero nonce); + /// 3. the inner plaintext (`Padding`, `Limit`, FS-54); + /// 4. a secret-class object with `comp = 1` (`Padding`): its chunks are never compressed; + /// 5. the payload: a raw one must be exactly `plain_len` bytes, a zstd one must pass every + /// frame check and decompress to exactly `plain_len` bytes (`Decompress`, FS-53); + /// 6. a keyed blob ID must equal `MAC(K_blobid, plaintext)`, compared in constant time + /// (`Binding`, FS-56, FS-15). Random IDs have nothing to recompute. + /// + /// # Errors + /// + /// - [`ReadError::Format`] as above. + /// - [`ReadError::Memory`] if protected memory cannot be allocated for the plaintext. + /// - [`ReadError::Zstd`] if zstd cannot reset its context or runs out of memory. + /// + /// # Panics + /// + /// On Linux, in a child forked without `exec` after the keys were made. + pub fn open( + &self, + decompressor: &mut Decompressor, + entry: &ChunkEntry, + sealed: &[u8], + ) -> Result { + let plain_len = entry.plain_len(); + if plain_len > MAX_PLAIN_LEN { + return Err(FormatError::Decompress.into()); + } + let aad = data_blob_aad(self.keys.context(), entry.blob_id()); + let inner = cx_aead::open(self.keys.chunk_key(), &aad, sealed)?; + let view = decode_inner(&inner)?; + let opened = match (view.comp(), self.class) { + (Comp::Zstd, ObjectClass::Secret) => return Err(FormatError::Padding.into()), + (Comp::Raw, _) => { + if view.payload().len() as u64 != plain_len { + return Err(FormatError::Decompress.into()); + } + OpenedChunk::new(SecretBuf::try_copy_from(view.payload())?) + } + (Comp::Zstd, ObjectClass::Ordinary) => { + OpenedChunk::new(decompressor.decode(view.payload(), plain_len)?) + } + }; + match self.blob_id_kind { + BlobIdKind::Keyed => { + let recomputed = mac::mac(self.keys.blob_id_key(), opened.as_slice()); + let stored = Hash32::try_from_bytes(*entry.blob_id().as_bytes())?; + if recomputed != stored { + return Err(FormatError::Binding.into()); + } + } + BlobIdKind::Random => {} + } + Ok(opened) + } +} + +#[cfg(test)] +mod tests { + use crypthix_crypto::cx_aead::NonceKind; + use crypthix_types::id::{BlobId, DekId, ObjectId, VaultId}; + use proptest::collection::vec; + use proptest::prelude::{any, prop_assert_eq, proptest}; + + use super::*; + use crate::blob::chunk_keys::tests::{context, keys}; + use crate::blob::{BlobContext, ObjectSealer}; + use crate::chunk::ObjectShape; + use crate::compress::Compressor; + use crate::inner::encode_inner; + use crate::test_data::pseudo_random; + + fn text(len: usize) -> Vec { + b"lorem ipsum dolor sit amet " + .iter() + .copied() + .cycle() + .take(len) + .collect() + } + + fn open( + class: ObjectClass, + count: u64, + entry: &ChunkEntry, + sealed: &[u8], + ) -> Result, ReadError> { + open_with(&keys(2), class, count, entry, sealed) + } + + fn open_with( + keys: &ChunkKeys, + class: ObjectClass, + count: u64, + entry: &ChunkEntry, + sealed: &[u8], + ) -> Result, ReadError> { + let mut decompressor = Decompressor::new(); + ObjectOpener::new(keys, class, count) + .open(&mut decompressor, entry, sealed) + .map(|opened| opened.as_slice().to_vec()) + } + + fn seal(class: ObjectClass, count: u64, chunk: &[u8]) -> (ChunkEntry, Vec) { + let mut compressor = Compressor::new().expect("context"); + let keys = keys(2); + let sealed = ObjectSealer::new(&keys, ObjectShape::new(class, count == 1)) + .seal(&mut compressor, chunk) + .expect("seals"); + (*sealed.entry(), sealed.into_sealed()) + } + + /// A data blob sealed by hand around any inner plaintext. + fn seal_inner(blob_id: &BlobId, inner: &[u8]) -> Vec { + seal_inner_in(&context(2), blob_id, inner) + } + + /// A data blob sealed by hand under the keys of object 2 and the AAD of `context`. + fn seal_inner_in(context: &BlobContext, blob_id: &BlobId, inner: &[u8]) -> Vec { + let aad = data_blob_aad(context, blob_id); + cx_aead::seal(keys(2).chunk_key(), &aad, inner, NonceKind::Hedged).expect("seals") + } + + /// The zstd frame of `chunk` as the compressor writes it. + fn frame(chunk: &[u8]) -> Vec { + let mut compressor = Compressor::new().expect("context"); + let inner = compressor + .encode_chunk(chunk, ObjectClass::Ordinary) + .expect("encodes"); + let view = decode_inner(&inner).expect("well formed"); + assert_eq!(view.comp(), Comp::Zstd, "test data compresses"); + view.payload().to_vec() + } + + fn id(byte: u8) -> BlobId { + BlobId::try_from_bytes([byte; 32]).expect("non-zero") + } + + fn format(error: FormatError) -> Result, ReadError> { + Err(ReadError::Format(error)) + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn chunks_round_trip_for_every_class_and_kind() { + for chunk in [text(200_000), pseudo_random(1, 100_000), b"x".to_vec()] { + for (class, count) in [ + (ObjectClass::Ordinary, 1), + (ObjectClass::Ordinary, 2), + (ObjectClass::Secret, 1), + (ObjectClass::Secret, 5), + ] { + let (entry, sealed) = seal(class, count, &chunk); + assert_eq!(entry.plain_len(), chunk.len() as u64); + assert_eq!(open(class, count, &entry, &sealed), Ok(chunk.clone())); + } + } + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn keyed_ids_repeat_within_an_object_and_random_ones_never() { + let chunk = text(100_000); + let (keyed, _) = seal(ObjectClass::Ordinary, 2, &chunk); + let (again, _) = seal(ObjectClass::Ordinary, 3, &chunk); + assert_eq!( + keyed.blob_id(), + again.blob_id(), + "an unchanged chunk keeps its ID" + ); + assert_eq!( + keyed.blob_id().as_bytes(), + mac::mac(keys(2).blob_id_key(), &chunk).as_bytes() + ); + let other_object = keys(4); + assert_ne!( + keyed.blob_id().as_bytes(), + mac::mac(other_object.blob_id_key(), &chunk).as_bytes(), + "IDs are keyed per object" + ); + for (class, count) in [(ObjectClass::Ordinary, 1), (ObjectClass::Secret, 2)] { + let (first, _) = seal(class, count, &chunk); + let (second, _) = seal(class, count, &chunk); + assert_ne!(first.blob_id(), second.blob_id(), "{class:?} {count}"); + } + } + + #[test] + fn every_aad_field_is_bound() { + let chunk = text(1_000); + let decrypt = format(FormatError::Decrypt); + let base = context(2); + let vault = VaultId::try_from_bytes([9; 16]).expect("non-zero"); + let object = ObjectId::try_from_bytes([9; 16]).expect("non-zero"); + let dek = DekId::try_from_bytes([9; 16]).expect("non-zero"); + let changed = [ + BlobContext::new(vault, *base.object_id(), *base.dek_id()), + BlobContext::new(*base.vault_id(), object, *base.dek_id()), + BlobContext::new(*base.vault_id(), *base.object_id(), dek), + ]; + // The inner plaintext of the chunk, sealed under the right key and a changed AAD. + let inner = encode_inner(Comp::Raw, &chunk).expect("encodes"); + let keyed_id = BlobId::try_from_bytes(*mac::mac(keys(2).blob_id_key(), &chunk).as_bytes()) + .expect("non-zero"); + let keyed_entry = ChunkEntry::new(keyed_id, chunk.len() as u64); + let (entry, sealed) = (keyed_entry, seal_inner(&keyed_id, &inner)); + assert_eq!( + open(ObjectClass::Ordinary, 2, &entry, &sealed), + Ok(chunk.clone()), + "the right AAD opens" + ); + for context in changed { + let sealed = seal_inner_in(&context, &keyed_id, &inner); + assert_eq!( + open(ObjectClass::Ordinary, 2, &keyed_entry, &sealed), + decrypt + ); + } + let other_id = ChunkEntry::new(id(9), entry.plain_len()); + assert_eq!(open(ObjectClass::Ordinary, 2, &other_id, &sealed), decrypt); + let mut flipped = sealed.clone(); + flipped[100] ^= 1; + assert_eq!(open(ObjectClass::Ordinary, 2, &entry, &flipped), decrypt); + assert_eq!( + open_with(&keys(4), ObjectClass::Ordinary, 2, &entry, &sealed), + decrypt, + "another object's keys" + ); + assert_eq!( + open(ObjectClass::Ordinary, 2, &entry, &sealed[..71]), + format(FormatError::Truncated) + ); + } + + #[test] + fn plain_len_is_capped_before_the_blob_is_opened() { + let garbage = vec![0x5A; 200]; + let at_cap = ChunkEntry::new(id(1), 1 << 20); + assert_eq!( + open(ObjectClass::Ordinary, 2, &at_cap, &garbage), + format(FormatError::Decrypt) + ); + let over = ChunkEntry::new(id(1), (1 << 20) + 1); + assert_eq!( + open(ObjectClass::Ordinary, 2, &over, &garbage), + format(FormatError::Decompress) + ); + assert_eq!( + open( + ObjectClass::Secret, + 1, + &ChunkEntry::new(id(1), u64::MAX), + &garbage + ), + format(FormatError::Decompress) + ); + } + + #[test] + fn a_keyed_id_that_does_not_match_the_plaintext_is_binding() { + let chunk = b"chunk".to_vec(); + let inner = encode_inner(Comp::Raw, &chunk).expect("encodes"); + let sealed = seal_inner(&id(7), &inner); + let entry = ChunkEntry::new(id(7), 5); + assert_eq!( + open(ObjectClass::Ordinary, 2, &entry, &sealed), + format(FormatError::Binding) + ); + // The same blob with a random ID: nothing to recompute. + assert_eq!( + open(ObjectClass::Ordinary, 1, &entry, &sealed), + Ok(chunk.clone()) + ); + assert_eq!(open(ObjectClass::Secret, 2, &entry, &sealed), Ok(chunk)); + } + + #[test] + fn bad_inner_plaintexts_are_padding_or_limit() { + let entry = ChunkEntry::new(id(7), 5); + let unpadded = seal_inner(&id(7), b"\x00\x00\x00\x00\x00\x05chunk"); + assert_eq!( + open(ObjectClass::Ordinary, 1, &entry, &unpadded), + format(FormatError::Padding) + ); + let mut too_long = vec![0u8, 0]; + too_long.extend_from_slice(&((1u32 << 20) + 1).to_be_bytes()); + let sealed = seal_inner(&id(7), &too_long); + assert_eq!( + open(ObjectClass::Ordinary, 1, &entry, &sealed), + format(FormatError::Limit) + ); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn a_compressed_chunk_of_a_secret_object_is_padding() { + let chunk = text(50_000); + let inner = encode_inner(Comp::Zstd, &frame(&chunk)).expect("encodes"); + let sealed = seal_inner(&id(7), &inner); + let entry = ChunkEntry::new(id(7), 50_000); + assert_eq!( + open(ObjectClass::Secret, 1, &entry, &sealed), + format(FormatError::Padding) + ); + assert_eq!(open(ObjectClass::Ordinary, 1, &entry, &sealed), Ok(chunk)); + } + + #[test] + fn raw_payloads_must_be_exactly_plain_len_bytes() { + let raw = seal_inner(&id(7), &encode_inner(Comp::Raw, b"chunk").expect("encodes")); + for len in [0, 4, 6] { + assert_eq!( + open(ObjectClass::Ordinary, 1, &ChunkEntry::new(id(7), len), &raw), + format(FormatError::Decompress), + "{len}" + ); + } + assert_eq!( + open(ObjectClass::Ordinary, 1, &ChunkEntry::new(id(7), 5), &raw), + Ok(b"chunk".to_vec()) + ); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn payloads_must_give_exactly_plain_len_bytes() { + let chunk = text(50_000); + let zstd = seal_inner( + &id(7), + &encode_inner(Comp::Zstd, &frame(&chunk)).expect("encodes"), + ); + let raw = seal_inner(&id(7), &encode_inner(Comp::Raw, &chunk).expect("encodes")); + for sealed in [&zstd, &raw] { + for len in [49_999, 50_001] { + let entry = ChunkEntry::new(id(7), len); + assert_eq!( + open(ObjectClass::Ordinary, 1, &entry, sealed), + format(FormatError::Decompress), + "{len}" + ); + } + } + let not_a_frame = seal_inner( + &id(7), + &encode_inner(Comp::Zstd, b"garbage").expect("encodes"), + ); + let entry = ChunkEntry::new(id(7), 7); + assert_eq!( + open(ObjectClass::Ordinary, 1, &entry, ¬_a_frame), + format(FormatError::Decompress) + ); + } + + #[test] + fn debug_prints_no_plaintext() { + let entry = ChunkEntry::new(id(7), 6); + let sealed = seal_inner( + &id(7), + &encode_inner(Comp::Raw, b"secret").expect("encodes"), + ); + let mut decompressor = Decompressor::new(); + let keys = keys(2); + let chunk_opener = ObjectOpener::new(&keys, ObjectClass::Ordinary, 1); + assert_eq!(chunk_opener.class(), ObjectClass::Ordinary); + assert_eq!(chunk_opener.blob_id_kind(), BlobIdKind::Random); + let opened = chunk_opener + .open(&mut decompressor, &entry, &sealed) + .expect("opens"); + assert_eq!(format!("{opened:?}"), "OpenedChunk(6 bytes)"); + assert!(!opened.is_empty()); + let printed = format!("{chunk_opener:?}"); + assert!(printed.contains("ChunkKeys(..)"), "{printed}"); + } + + #[test] + fn an_empty_chunk_opens_empty() { + let entry = ChunkEntry::new(id(7), 0); + let sealed = seal_inner(&id(7), &encode_inner(Comp::Raw, b"").expect("encodes")); + let keys = keys(2); + let opened = ObjectOpener::new(&keys, ObjectClass::Ordinary, 1) + .open(&mut Decompressor::new(), &entry, &sealed) + .expect("opens"); + assert!(opened.is_empty()); + assert_eq!(opened.as_slice(), b""); + assert_eq!(format!("{opened:?}"), "OpenedChunk(0 bytes)"); + } + + proptest! { + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn seal_then_open_round_trips( + chunk in vec(0u8..4, 1..20_000), + secret in any::(), + count in 1u64..4, + ) { + let class = if secret { ObjectClass::Secret } else { ObjectClass::Ordinary }; + let (entry, sealed) = seal(class, count, &chunk); + prop_assert_eq!(open(class, count, &entry, &sealed), Ok(chunk)); + } + } +} diff --git a/crates/engine/core/src/blob/object_sealer.rs b/crates/engine/core/src/blob/object_sealer.rs new file mode 100644 index 0000000..9e3601f --- /dev/null +++ b/crates/engine/core/src/blob/object_sealer.rs @@ -0,0 +1,110 @@ +//! Sealing the chunks of one object as data blobs (FS-55). + +use crypthix_crypto::cx_aead::{self, NonceKind}; +use crypthix_crypto::mac; +use crypthix_crypto::random; +use crypthix_types::id::BlobId; + +use crate::blob::{BlobIdKind, ChunkEntry, ChunkKeys, ObjectClass, SealedChunk, data_blob_aad}; +use crate::chunk::ObjectShape; +use crate::compress::Compressor; +use crate::error::WriteError; + +/// Seals the chunks of one object as data blobs (FS-53 to FS-55): compressed where it pays and +/// never for the secret class, padded with Padmé, and sealed under the object's `K_chunk` with +/// a hedged nonce and the AAD of the [`BlobContext`](crate::blob::BlobContext) its keys were +/// derived for. +/// +/// It is built once per object from the object's keys and its [`ObjectShape`], which only the +/// chunker gives and which carries the class the object was cut for, so an object is sealed in +/// the class it was cut in. The blob IDs are keyed, `MAC(K_blobid, chunk)`, exactly for an +/// ordinary object of two or more chunks, and random otherwise ([`BlobIdKind::for_object`]), +/// so no caller can give a single-chunk object keyed IDs (T-85). +#[derive(Debug)] +pub struct ObjectSealer<'k> { + keys: &'k ChunkKeys, + class: ObjectClass, + blob_id_kind: BlobIdKind, +} + +impl<'k> ObjectSealer<'k> { + /// The sealer of the object `keys` belong to, whose chunker gave `shape` + /// ([`ChunkRef::object_shape`](crate::chunk::ChunkRef::object_shape) or + /// [`Chunks::object_shape`](crate::chunk::Chunks::object_shape)); the object's class is + /// the one it was cut for. + #[must_use] + pub const fn new(keys: &'k ChunkKeys, shape: ObjectShape) -> Self { + let class = shape.class(); + let chunk_count = if shape.is_single() { 1 } else { 2 }; + Self { + keys, + class, + blob_id_kind: BlobIdKind::for_object(class, chunk_count), + } + } + + /// The object's class. + #[must_use] + pub const fn class(&self) -> ObjectClass { + self.class + } + + /// How the object's blob IDs are made. + #[must_use] + pub const fn blob_id_kind(&self) -> BlobIdKind { + self.blob_id_kind + } + + /// Seals one chunk of the object. + /// + /// # Errors + /// + /// - [`WriteError::Format`] with `Limit` if `chunk` is longer than 1 MiB, or `ZeroValue` if + /// a blob ID came out all zero (FS-03). + /// - [`WriteError::Random`] if the kernel gives no random blob ID. + /// - [`WriteError::Zstd`] if zstd fails; the chunk is then not stored raw instead. + /// - [`WriteError::Seal`] if the seal fails. + /// - [`WriteError::Memory`] if protected memory cannot be allocated for the inner plaintext. + /// + /// # Panics + /// + /// On Linux, in a child forked without `exec` after the keys were made. + pub fn seal( + &self, + compressor: &mut Compressor, + chunk: &[u8], + ) -> Result { + let inner = compressor.encode_chunk(chunk, self.class)?; + let id_bytes = match self.blob_id_kind { + BlobIdKind::Keyed => *mac::mac(self.keys.blob_id_key(), chunk).as_bytes(), + BlobIdKind::Random => random::bytes::<32>()?, + }; + let blob_id = BlobId::try_from_bytes(id_bytes)?; + let aad = data_blob_aad(self.keys.context(), &blob_id); + let sealed = cx_aead::seal(self.keys.chunk_key(), &aad, &inner, NonceKind::Hedged)?; + let entry = ChunkEntry::new(blob_id, chunk.len() as u64); + Ok(SealedChunk::new(entry, sealed)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::blob::chunk_keys::tests::keys; + + #[test] + fn the_kind_follows_the_class_and_the_chunkers_shape() { + let keys = keys(2); + let cases = [ + (ObjectClass::Ordinary, false, BlobIdKind::Keyed), + (ObjectClass::Ordinary, true, BlobIdKind::Random), + (ObjectClass::Secret, false, BlobIdKind::Random), + (ObjectClass::Secret, true, BlobIdKind::Random), + ]; + for (class, single, kind) in cases { + let sealer = ObjectSealer::new(&keys, ObjectShape::new(class, single)); + assert_eq!(sealer.blob_id_kind(), kind, "{class:?} {single}"); + assert_eq!(sealer.class(), class); + } + } +} diff --git a/crates/engine/core/src/blob/open_meta_blob.rs b/crates/engine/core/src/blob/open_meta_blob.rs new file mode 100644 index 0000000..0170c26 --- /dev/null +++ b/crates/engine/core/src/blob/open_meta_blob.rs @@ -0,0 +1,128 @@ +//! Opening a meta blob (FS-57). + +use crypthix_crypto::cx_aead; +use crypthix_crypto::secure_mem::SecretBuf; +use crypthix_types::id::BlobId; + +use crate::blob::{MetaKey, meta_blob_aad}; +use crate::error::ReadError; + +/// Opens the meta blob `blob_id` under `key`, with the AAD of the context it was derived for, +/// and returns its CBOR in protected memory. The CBOR is not checked here; its decoder applies +/// FS-08 to FS-11. +/// +/// # Errors +/// +/// - [`ReadError::Format`] with `Decrypt` for any change to the key, vault, kind, epoch, blob +/// ID or sealed bytes, or `Truncated` / `ZeroValue` for input too short to be a seal or with +/// a zero nonce. +/// - [`ReadError::Memory`] if protected memory cannot be allocated for the plaintext. +/// +/// # Panics +/// +/// On Linux, in a child forked without `exec` after `key` was made. +pub fn open_meta_blob( + key: &MetaKey, + blob_id: &BlobId, + sealed: &[u8], +) -> Result { + let aad = meta_blob_aad(key.context(), blob_id); + Ok(cx_aead::open(key.seal_key(), &aad, sealed)?) +} + +#[cfg(test)] +mod tests { + use crypthix_crypto::cx_aead::NonceKind; + use crypthix_crypto::key::KdfKey; + use crypthix_types::format_error::FormatError; + use crypthix_types::id::{Epoch, VaultId}; + + use super::*; + use crate::blob::meta_key::tests::meta_context; + use crate::blob::{MetaContext, MetaKind, seal_meta_blob}; + + const DECRYPT: Result<(), ReadError> = Err(ReadError::Format(FormatError::Decrypt)); + + fn kek() -> KdfKey { + KdfKey::from_bytes([5; 32]).expect("non-zero") + } + + fn key(context: MetaContext) -> MetaKey { + MetaKey::derive(&kek(), context).expect("derives") + } + + fn open(key: &MetaKey, blob_id: &BlobId, sealed: &[u8]) -> Result<(), ReadError> { + open_meta_blob(key, blob_id, sealed).map(|_| ()) + } + + #[test] + fn meta_blobs_round_trip_with_random_ids() { + let key = key(meta_context(MetaKind::PackTable, 2)); + let first = seal_meta_blob(&key, b"\xa0").expect("seals"); + let second = seal_meta_blob(&key, b"\xa0").expect("seals"); + assert_ne!(first.blob_id(), second.blob_id(), "blob IDs are random"); + let opened = open_meta_blob(&key, first.blob_id(), first.sealed()).expect("opens"); + assert_eq!(opened.as_slice(), b"\xa0"); + let id = *second.blob_id(); + let bytes = second.into_sealed(); + let opened = open_meta_blob(&key, &id, &bytes).expect("the owned bytes open"); + assert_eq!(opened.as_slice(), b"\xa0"); + } + + #[test] + fn every_bound_field_is_checked() { + let context = meta_context(MetaKind::Location, 2); + let key = key(context); + let sealed = seal_meta_blob(&key, b"node").expect("seals"); + let id = *sealed.blob_id(); + let bytes = sealed.sealed(); + let other_id = BlobId::try_from_bytes([9; 32]).expect("non-zero"); + assert_eq!(open(&key, &other_id, bytes), DECRYPT, "blob ID"); + // A blob sealed under the right key with another context's AAD never opens, so each + // AAD field is bound. A GC-candidate node shares the location key; only the kind byte + // differs. + let later = MetaContext::new( + *context.vault_id(), + context.kind(), + Epoch::try_new(3).expect("non-zero"), + ); + let vault = MetaContext::new( + VaultId::try_from_bytes([2; 16]).expect("non-zero"), + context.kind(), + context.epoch(), + ); + for (other, field) in [ + (meta_context(MetaKind::GcCandidate, 2), "kind"), + (later, "epoch"), + (vault, "vault"), + ] { + let aad = meta_blob_aad(&other, &id); + let resealed = + cx_aead::seal(key.seal_key(), &aad, b"node", NonceKind::Hedged).expect("seals"); + assert_eq!(open(&key, &id, &resealed), DECRYPT, "{field}"); + } + let other_key = self::key(meta_context(MetaKind::Index, 2)); + assert_eq!(open(&other_key, &id, bytes), DECRYPT, "key"); + let mut flipped = bytes.to_vec(); + let last = flipped.len() - 1; + flipped[last] ^= 1; + assert_eq!(open(&key, &id, &flipped), DECRYPT, "tag"); + assert_eq!( + open(&key, &id, &bytes[..71]), + Err(ReadError::Format(FormatError::Truncated)) + ); + } + + #[test] + fn an_all_zero_nonce_is_a_zero_value() { + let key = key(meta_context(MetaKind::KeyTable, 2)); + let sealed = seal_meta_blob(&key, b"node").expect("seals"); + let mut zeroed = sealed.sealed().to_vec(); + zeroed[..cx_aead::NONCE_LEN].fill(0); + assert_eq!( + open(&key, sealed.blob_id(), &zeroed), + Err(ReadError::Format(FormatError::ZeroValue)), + "checked before the tag, which no longer matches" + ); + } +} diff --git a/crates/engine/core/src/blob/opened_chunk.rs b/crates/engine/core/src/blob/opened_chunk.rs new file mode 100644 index 0000000..4df5022 --- /dev/null +++ b/crates/engine/core/src/blob/opened_chunk.rs @@ -0,0 +1,52 @@ +//! An opened data blob. + +use std::fmt; + +use crypthix_crypto::secure_mem::SecretBuf; + +/// A chunk's plaintext in protected memory, released only after every check of +/// [`ObjectOpener::open`](crate::blob::ObjectOpener::open) passed (FS-93). +pub struct OpenedChunk { + /// Exactly the plaintext, so reading it cannot fail. + plain: SecretBuf, + /// `plain.len()`, kept so the length can be had without reading the buffer. + len: usize, +} + +impl OpenedChunk { + /// `plain` is the whole plaintext. A raw chunk is copied out of its inner plaintext, whose + /// header and padding are then wiped with it. + pub(crate) fn new(plain: SecretBuf) -> Self { + let len = plain.len(); + Self { plain, len } + } + + /// The plaintext. + /// + /// # Panics + /// + /// On Linux, in a child forked without `exec` after the chunk was opened. + #[must_use] + pub fn as_slice(&self) -> &[u8] { + self.plain.as_slice() + } + + /// The plaintext's length. + #[must_use] + pub fn len(&self) -> usize { + self.len + } + + /// Whether the plaintext is empty. + #[must_use] + pub fn is_empty(&self) -> bool { + self.len == 0 + } +} + +/// Prints the length, never the plaintext. +impl fmt::Debug for OpenedChunk { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "OpenedChunk({} bytes)", self.len()) + } +} diff --git a/crates/engine/core/src/blob/seal_meta_blob.rs b/crates/engine/core/src/blob/seal_meta_blob.rs new file mode 100644 index 0000000..1140e46 --- /dev/null +++ b/crates/engine/core/src/blob/seal_meta_blob.rs @@ -0,0 +1,26 @@ +//! Sealing a meta blob (FS-57). + +use crypthix_crypto::cx_aead::{self, NonceKind}; +use crypthix_crypto::random; +use crypthix_types::id::BlobId; + +use crate::blob::{MetaKey, SealedMeta, meta_blob_aad}; +use crate::error::WriteError; + +/// Seals the CBOR of a tree node as a meta blob under `key`, with the AAD of the context it was +/// derived for, a random blob ID and a hedged nonce (FS-57). +/// +/// # Errors +/// +/// - [`WriteError::Random`] if the kernel gives no random blob ID. +/// - [`WriteError::Seal`] if the seal fails. +/// +/// # Panics +/// +/// On Linux, in a child forked without `exec` after `key` was made. +pub fn seal_meta_blob(key: &MetaKey, cbor: &[u8]) -> Result { + let blob_id = BlobId::try_from_bytes(random::bytes::<32>()?)?; + let aad = meta_blob_aad(key.context(), &blob_id); + let sealed = cx_aead::seal(key.seal_key(), &aad, cbor, NonceKind::Hedged)?; + Ok(SealedMeta::new(blob_id, sealed)) +} diff --git a/crates/engine/core/src/blob/sealed_chunk.rs b/crates/engine/core/src/blob/sealed_chunk.rs new file mode 100644 index 0000000..af5e981 --- /dev/null +++ b/crates/engine/core/src/blob/sealed_chunk.rs @@ -0,0 +1,82 @@ +//! A sealed data blob. + +use std::fmt; + +use crypthix_types::id::BlobId; + +use crate::blob::ChunkEntry; + +/// A data blob ready to be packed, with what the manifest records about it. +#[must_use] +#[derive(Clone, PartialEq, Eq)] +pub struct SealedChunk { + entry: ChunkEntry, + sealed: Vec, +} + +impl SealedChunk { + pub(crate) const fn new(entry: ChunkEntry, sealed: Vec) -> Self { + Self { entry, sealed } + } + + /// The manifest entry: blob ID and `plain_len`. + #[must_use] + pub const fn entry(&self) -> &ChunkEntry { + &self.entry + } + + /// The blob ID. + #[must_use] + pub const fn blob_id(&self) -> &BlobId { + self.entry.blob_id() + } + + /// The sealed blob: `nonce ‖ C ‖ ciphertext ‖ tag`. + #[must_use] + pub fn sealed(&self) -> &[u8] { + &self.sealed + } + + /// The sealed blob, by value. + #[must_use] + pub fn into_sealed(self) -> Vec { + self.sealed + } +} + +/// Prints the lengths only: not the ciphertext, and not the blob ID, which for a keyed ID is a +/// fingerprint of the chunk within its object (FS-55). +impl fmt::Debug for SealedChunk { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SealedChunk") + .field("plain_len", &self.entry.plain_len()) + .field("sealed_len", &self.sealed.len()) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn debug_prints_lengths_only() { + let id = BlobId::try_from_bytes([0xab; 32]).expect("non-zero ID"); + let sealed = SealedChunk::new(ChunkEntry::new(id, 5), vec![0xcd; 7]); + assert_eq!( + format!("{sealed:?}"), + "SealedChunk { plain_len: 5, sealed_len: 7, .. }" + ); + } + + #[test] + fn accessors_give_back_what_was_sealed() { + let id = BlobId::try_from_bytes([0xab; 32]).expect("non-zero ID"); + let entry = ChunkEntry::new(id, 5); + let sealed = SealedChunk::new(entry, vec![1, 2, 3]); + assert_eq!(sealed.entry(), &entry); + assert_eq!(sealed.blob_id(), &id); + assert_eq!(sealed.sealed(), [1, 2, 3]); + assert_eq!(sealed.into_sealed(), vec![1, 2, 3]); + } +} diff --git a/crates/engine/core/src/blob/sealed_meta.rs b/crates/engine/core/src/blob/sealed_meta.rs new file mode 100644 index 0000000..127d54f --- /dev/null +++ b/crates/engine/core/src/blob/sealed_meta.rs @@ -0,0 +1,67 @@ +//! A sealed meta blob. + +use std::fmt; + +use crypthix_types::id::BlobId; + +/// A meta blob ready to be packed, with its random blob ID. +#[must_use] +#[derive(Clone, PartialEq, Eq)] +pub struct SealedMeta { + blob_id: BlobId, + sealed: Vec, +} + +impl SealedMeta { + pub(crate) const fn new(blob_id: BlobId, sealed: Vec) -> Self { + Self { blob_id, sealed } + } + + /// The blob ID. + #[must_use] + pub const fn blob_id(&self) -> &BlobId { + &self.blob_id + } + + /// The sealed blob: `nonce ‖ C ‖ ciphertext ‖ tag`. + #[must_use] + pub fn sealed(&self) -> &[u8] { + &self.sealed + } + + /// The sealed blob, by value. + #[must_use] + pub fn into_sealed(self) -> Vec { + self.sealed + } +} + +/// Prints the length only, not the ciphertext or the blob ID. +impl fmt::Debug for SealedMeta { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SealedMeta") + .field("sealed_len", &self.sealed.len()) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn debug_prints_the_length_only() { + let id = BlobId::try_from_bytes([0xab; 32]).expect("non-zero ID"); + let sealed = SealedMeta::new(id, vec![0xcd; 7]); + assert_eq!(format!("{sealed:?}"), "SealedMeta { sealed_len: 7, .. }"); + } + + #[test] + fn accessors_give_back_what_was_sealed() { + let id = BlobId::try_from_bytes([0xab; 32]).expect("non-zero ID"); + let sealed = SealedMeta::new(id, vec![1, 2, 3]); + assert_eq!(sealed.blob_id(), &id); + assert_eq!(sealed.sealed(), [1, 2, 3]); + assert_eq!(sealed.into_sealed(), vec![1, 2, 3]); + } +} diff --git a/crates/engine/core/src/chunk/chunk_params.rs b/crates/engine/core/src/chunk/chunk_params.rs new file mode 100644 index 0000000..e320b51 --- /dev/null +++ b/crates/engine/core/src/chunk/chunk_params.rs @@ -0,0 +1,53 @@ +//! The sizes and masks one cut uses. + +use crate::chunk::{MASK_L, MASK_S}; +use crate::limits::{AVG_CHUNK, MAX_CHUNK, MIN_CHUNK}; + +/// Minimum, average and maximum chunk size with their masks. Format 0 has exactly one set, +/// [`ChunkParams::FORMAT_0`]; tests use scaled-down sets so properties run on small inputs. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) struct ChunkParams { + pub(crate) min: usize, + pub(crate) avg: usize, + pub(crate) max: usize, + pub(crate) mask_s: u64, + pub(crate) mask_l: u64, +} + +impl ChunkParams { + /// 64 KiB, 256 KiB and 1 MiB with the level 2 masks for 256 KiB (FS-52). + pub(crate) const FORMAT_0: Self = Self { + min: MIN_CHUNK, + avg: AVG_CHUNK, + max: MAX_CHUNK, + mask_s: MASK_S, + mask_l: MASK_L, + }; + + /// Scaled-down sizes for tests and the `chunker` fuzz target: 64, 256 and 1,024 bytes with + /// the level 2 masks fastcdc selects for a 256-byte average, `MASKS[10]` and `MASKS[6]`. Not + /// a format 0 set: no object is ever cut with it. + pub(crate) const SCALED: Self = Self { + min: 64, + avg: 256, + max: 1024, + mask_s: 0x0000_5900_0353_0000, + mask_l: 0x0000_0000_0180_3110, + }; +} + +#[cfg(test)] +mod tests { + use fastcdc::v2020::{self, Normalization}; + + use super::*; + + #[test] + fn the_scaled_masks_are_those_fastcdc_selects() { + let scaled = ChunkParams::SCALED; + assert_eq!( + (scaled.mask_s, scaled.mask_l), + v2020::select_masks(scaled.avg, Normalization::Level2) + ); + } +} diff --git a/crates/engine/core/src/chunk/chunk_ref.rs b/crates/engine/core/src/chunk/chunk_ref.rs new file mode 100644 index 0000000..0dbb3b5 --- /dev/null +++ b/crates/engine/core/src/chunk/chunk_ref.rs @@ -0,0 +1,100 @@ +//! One chunk of a stream. + +use std::fmt; + +use crate::blob::ObjectClass; +use crate::chunk::ObjectShape; + +/// A chunk cut by a [`StreamChunker`](crate::chunk::StreamChunker), borrowed from its window. +/// +/// [`is_last`](ChunkRef::is_last) is known when the chunk is cut, so a writer knows at the first +/// chunk whether the object has a single chunk, which decides its blob IDs (FS-55). +#[derive(Clone, Copy)] +pub struct ChunkRef<'a> { + bytes: &'a [u8], + index: u64, + is_last: bool, + class: ObjectClass, +} + +impl<'a> ChunkRef<'a> { + pub(crate) const fn new( + bytes: &'a [u8], + index: u64, + is_last: bool, + class: ObjectClass, + ) -> Self { + Self { + bytes, + index, + is_last, + class, + } + } + + /// The chunk's bytes. + #[must_use] + pub const fn bytes(&self) -> &'a [u8] { + self.bytes + } + + /// The chunk's position in the object, from 0. + #[must_use] + pub const fn index(&self) -> u64 { + self.index + } + + /// Whether this is the object's last chunk. On chunk 0 it means the object has one chunk. + #[must_use] + pub const fn is_last(&self) -> bool { + self.is_last + } + + /// The class the object was cut for, and whether it has one chunk or more: one exactly + /// when this is chunk 0 and also the last. Any chunk of the object gives the same answer, + /// so a writer learns it at the first chunk and passes it to + /// [`ObjectSealer::new`](crate::blob::ObjectSealer::new) (FS-55). + #[must_use] + pub const fn object_shape(&self) -> ObjectShape { + ObjectShape::new(self.class, self.index == 0 && self.is_last) + } +} + +/// Prints the length, never the bytes. +impl fmt::Debug for ChunkRef<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ChunkRef") + .field("len", &self.bytes.len()) + .field("index", &self.index) + .field("is_last", &self.is_last) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accessors_give_back_what_was_cut() { + let chunk = ChunkRef::new(b"bytes", 3, true, ObjectClass::Secret); + assert_eq!( + (chunk.bytes(), chunk.index(), chunk.is_last()), + (&b"bytes"[..], 3, true) + ); + assert_eq!( + format!("{chunk:?}"), + "ChunkRef { len: 5, index: 3, is_last: true }" + ); + } + + #[test] + fn the_shape_is_single_only_for_a_first_chunk_that_is_also_last() { + for class in [ObjectClass::Ordinary, ObjectClass::Secret] { + for (index, is_last, single) in [(0, true, true), (0, false, false), (1, true, false)] { + let shape = ChunkRef::new(b"x", index, is_last, class).object_shape(); + assert_eq!(shape, ObjectShape::new(class, single), "{index} {is_last}"); + } + } + } +} diff --git a/crates/engine/core/src/chunk/chunks.rs b/crates/engine/core/src/chunk/chunks.rs new file mode 100644 index 0000000..370f6b7 --- /dev/null +++ b/crates/engine/core/src/chunk/chunks.rs @@ -0,0 +1,209 @@ +//! Cutting data already in memory. + +use std::fmt; +use std::iter::FusedIterator; +use std::ops::Range; + +use crate::blob::ObjectClass; +use crate::chunk::cut::cut_for; +use crate::chunk::{ChunkParams, GearTable, ObjectShape}; + +/// The chunks of `data` in an object of a class, as ranges into it, in order (FS-52). Empty +/// data has none. An ordinary object is cut with keyed FastCDC, so data no longer than 64 KiB +/// is one chunk; a secret-class object is cut into 1 MiB chunks and a shorter last one, without +/// reading its bytes. +/// +/// ``` +/// use crypthix_core::blob::ObjectClass; +/// use crypthix_core::chunk::{Chunks, GearTable}; +/// use crypthix_crypto::key::KdfKey; +/// use crypthix_types::id::VaultId; +/// +/// let gear = GearTable::derive(&KdfKey::random()?, &VaultId::try_from_bytes([1; 16])?)?; +/// let data = vec![0u8; 3 << 20]; +/// let lengths: Vec = +/// Chunks::new(&gear, ObjectClass::Ordinary, &data).map(|range| range.len()).collect(); +/// assert_eq!(lengths, [1 << 20; 3]); +/// let secret = vec![7u8; (5 << 20) / 2]; +/// let lengths: Vec = +/// Chunks::new(&gear, ObjectClass::Secret, &secret).map(|range| range.len()).collect(); +/// assert_eq!(lengths, [1 << 20, 1 << 20, 1 << 19]); +/// assert_eq!(Chunks::new(&gear, ObjectClass::Ordinary, &[]).count(), 0); +/// # Ok::<(), Box>(()) +/// ``` +#[must_use] +#[derive(Clone)] +pub struct Chunks<'a> { + gear: &'a GearTable, + class: ObjectClass, + data: &'a [u8], + offset: usize, + params: ChunkParams, +} + +impl<'a> Chunks<'a> { + /// The chunks of `data` in an object of `class`; `gear` is used for the ordinary class + /// only. + pub fn new(gear: &'a GearTable, class: ObjectClass, data: &'a [u8]) -> Self { + Self::with_params(gear, class, data, ChunkParams::FORMAT_0) + } + + /// The chunks of `data` cut at the scaled-down sizes 64, 256 and 1,024 bytes, with the + /// level 2 masks for a 256-byte average. Not part of the API and not a format 0 cut: it + /// lets the `chunker` fuzz target reach every cut-point edge with inputs of a few KiB, + /// where the format 0 hash is only tested 64 KiB into a chunk. + #[doc(hidden)] + pub fn scaled_for_fuzzing(gear: &'a GearTable, class: ObjectClass, data: &'a [u8]) -> Self { + Self::with_params(gear, class, data, ChunkParams::SCALED) + } + + /// The chunks of `data` with other sizes and masks, for tests. + pub(crate) fn with_params( + gear: &'a GearTable, + class: ObjectClass, + data: &'a [u8], + params: ChunkParams, + ) -> Self { + Self { + gear, + class, + data, + offset: 0, + params, + } + } + + /// The class the chunks are cut for and whether `data` is one chunk or more, which a + /// writer passes to [`ObjectSealer::new`](crate::blob::ObjectSealer::new) (FS-55). It + /// depends on the whole data, not on how far the iterator has gone, and costs one cut. + /// Empty data, which has no chunk to seal, counts as one. + #[must_use] + pub fn object_shape(&self) -> ObjectShape { + let first = cut_for(self.class, self.gear, self.data, &self.params); + ObjectShape::new(self.class, first >= self.data.len()) + } +} + +impl Iterator for Chunks<'_> { + type Item = Range; + + fn next(&mut self) -> Option> { + let rest = self.data.get(self.offset..)?; + let len = cut_for(self.class, self.gear, rest, &self.params); + if len == 0 { + return None; + } + let start = self.offset; + self.offset += len; + Some(start..self.offset) + } +} + +impl FusedIterator for Chunks<'_> {} + +/// Prints the class and position only, never the data. +impl fmt::Debug for Chunks<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Chunks") + .field("class", &self.class) + .field("offset", &self.offset) + .field("len", &self.data.len()) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use proptest::collection::vec; + use proptest::prelude::{any, prop_assert, prop_assert_eq, proptest}; + + use super::*; + use crate::test_data::gear_table as table; + use crate::test_data::pseudo_random; + + const CLASSES: [ObjectClass; 2] = [ObjectClass::Ordinary, ObjectClass::Secret]; + + #[test] + fn empty_data_has_no_chunks_and_stays_done() { + let gear = table(1); + for class in CLASSES { + let mut chunks = Chunks::new(&gear, class, &[]); + assert_eq!(chunks.next(), None); + assert_eq!(chunks.next(), None); + } + } + + #[test] + fn the_shape_is_single_exactly_when_there_is_at_most_one_chunk() { + let gear = table(1); + let params = ChunkParams::SCALED; + for class in CLASSES { + for len in [0, 1, params.min, params.max, params.max + 1, 6_000] { + let data = pseudo_random(3, len); + let chunks = Chunks::with_params(&gear, class, &data, params); + let count = chunks.clone().count(); + let shape = chunks.object_shape(); + assert_eq!(shape.is_single(), count <= 1, "{class:?} {len}"); + assert_eq!(shape.class(), class); + } + } + } + + #[test] + fn debug_shows_no_data() { + let gear = table(1); + let mut chunks = Chunks::new(&gear, ObjectClass::Secret, b"secret"); + assert_eq!( + format!("{chunks:?}"), + "Chunks { class: Secret, offset: 0, len: 6, .. }" + ); + assert_eq!(chunks.next(), Some(0..6)); + assert_eq!( + format!("{chunks:?}"), + "Chunks { class: Secret, offset: 6, len: 6, .. }" + ); + } + + proptest! { + #[test] + #[cfg_attr(miri, ignore = "proptest is slow under Miri")] + fn chunks_tile_the_data_within_the_size_bounds(seed in 1u8.., data in vec(any::(), 0..6_000)) { + let gear = table(seed); + let params = ChunkParams::SCALED; + let ranges: Vec> = + Chunks::with_params(&gear, ObjectClass::Ordinary, &data, params).collect(); + let mut next = 0; + for (i, range) in ranges.iter().enumerate() { + prop_assert_eq!(range.start, next); + next = range.end; + prop_assert!(range.len() <= params.max); + if i + 1 < ranges.len() { + prop_assert!(range.len() >= params.min, "a short chunk before the last"); + } else { + prop_assert!(!range.is_empty()); + } + } + prop_assert_eq!(next, data.len(), "the chunks rebuild the data"); + if data.len() <= params.min { + prop_assert_eq!(ranges.len(), usize::from(!data.is_empty())); + } + } + + #[test] + #[cfg_attr(miri, ignore = "proptest is slow under Miri")] + fn secret_chunks_are_fixed_steps_of_the_maximum( + seed in 1u8.., + data in vec(any::(), 0..6_000), + ) { + let gear = table(seed); + let params = ChunkParams::SCALED; + let ranges: Vec> = + Chunks::with_params(&gear, ObjectClass::Secret, &data, params).collect(); + let expected: Vec> = (0..data.len()) + .step_by(params.max) + .map(|start| start..data.len().min(start + params.max)) + .collect(); + prop_assert_eq!(ranges, expected); + } + } +} diff --git a/crates/engine/core/src/chunk/cut.rs b/crates/engine/core/src/chunk/cut.rs new file mode 100644 index 0000000..25fe5ab --- /dev/null +++ b/crates/engine/core/src/chunk/cut.rs @@ -0,0 +1,248 @@ +//! The cut points: FastCDC 2020 for ordinary objects, fixed size for secret ones (FS-52). + +use crate::blob::ObjectClass; +use crate::chunk::{ChunkParams, GearTable}; + +/// The length of the first chunk of `data` in an ordinary object: all of it if it is no longer +/// than the 64 KiB minimum, otherwise between the minimum and the 1 MiB maximum (FS-52). Zero +/// only for empty `data`. +/// +/// A secret-class object is not cut this way but at fixed 1 MiB steps. To cut a whole object +/// of either class, use [`Chunks`](crate::chunk::Chunks) or +/// [`StreamChunker`](crate::chunk::StreamChunker). +#[must_use] +pub fn cut(gear: &GearTable, data: &[u8]) -> usize { + cut_with(gear, data, &ChunkParams::FORMAT_0) +} + +/// The length of the first chunk of `data` in an object of `class` (FS-52). The ordinary class +/// takes the keyed FastCDC cut. The secret class takes the maximum, or all of `data` if it is +/// shorter, and reads no byte of it: the FastCDC loop indexes the gear table with plaintext +/// bytes and stops early where it cuts, which a process sharing the cache can time, and secret +/// chunks never deduplicate, so content-defined cuts would give them nothing (T-84). +pub(crate) fn cut_for( + class: ObjectClass, + gear: &GearTable, + data: &[u8], + params: &ChunkParams, +) -> usize { + match class { + ObjectClass::Ordinary => cut_with(gear, data, params), + ObjectClass::Secret => data.len().min(params.max), + } +} + +/// [`cut`] with any sizes and masks: the loop of `fastcdc::v2020::cut_gear` 5.0.0, with +/// `gear_ls[b]` computed as `gear[b] << 1`. +fn cut_with(gear: &GearTable, data: &[u8], params: &ChunkParams) -> usize { + let mut remaining = data.len(); + if remaining <= params.min { + return remaining; + } + let mut center = params.avg; + if remaining > params.max { + remaining = params.max; + } else if remaining < center { + center = remaining; + } + // Always 256 words; were it ever not, cutting at the maximum keeps the chunks valid. + let Some(words) = gear.words() else { + debug_assert!(false, "a gear table has 256 words"); + return remaining; + }; + let gear_at = |byte: u8| u64::from_le_bytes(words[usize::from(byte)]); + let (strict, loose) = (params.mask_s, params.mask_l); + let (strict_shifted, loose_shifted) = (strict << 1, loose << 1); + // The pairs of bytes the loop takes; an odd last byte is never tested (FS-52). Iterating + // them instead of indexing keeps the loop free of bounds checks and panics. + let (pairs, _) = data.get(..remaining).unwrap_or(data).as_chunks::<2>(); + // `min <= center <= remaining`, so both splits are in range. + let (strict_pairs, loose_pairs) = pairs.split_at_checked(center / 2).unwrap_or((pairs, &[])); + let first = params.min / 2; + + let mut hash: u64 = 0; + for (index, &[even, odd]) in strict_pairs.iter().enumerate().skip(first) { + let a = index * 2; + hash = (hash << 2).wrapping_add(gear_at(even) << 1); + if hash & strict_shifted == 0 { + return a; + } + hash = hash.wrapping_add(gear_at(odd)); + if hash & strict == 0 { + return a + 1; + } + } + let skipped = first.saturating_sub(strict_pairs.len()); + for (offset, &[even, odd]) in loose_pairs.iter().enumerate().skip(skipped) { + let a = (strict_pairs.len() + offset) * 2; + hash = (hash << 2).wrapping_add(gear_at(even) << 1); + if hash & loose_shifted == 0 { + return a; + } + hash = hash.wrapping_add(gear_at(odd)); + if hash & loose == 0 { + return a + 1; + } + } + remaining +} + +#[cfg(test)] +mod tests { + use fastcdc::v2020; + use proptest::collection::vec; + use proptest::prelude::{Just, Strategy, any, prop_assert_eq, prop_oneof, proptest}; + + use super::*; + use crate::chunk::Chunks; + use crate::limits::{MAX_CHUNK, MIN_CHUNK}; + use crate::test_data::gear_table as table; + use crate::test_data::pseudo_random; + + /// The chunk lengths fastcdc cuts from `data` with `gear`'s words. + fn fastcdc_lengths(gear: &GearTable, data: &[u8], params: &ChunkParams) -> Vec { + let words = gear.to_u64s(); + let shifted: Vec = words.iter().map(|word| word << 1).collect(); + let mut lengths = Vec::new(); + let mut offset = 0; + while offset < data.len() { + let (_, len) = v2020::cut_gear( + &data[offset..], + params.min, + params.avg, + params.max, + params.mask_s, + params.mask_l, + params.mask_s << 1, + params.mask_l << 1, + &words, + &shifted, + ); + lengths.push(len); + offset += len; + } + lengths + } + + fn our_lengths(gear: &GearTable, data: &[u8], params: &ChunkParams) -> Vec { + Chunks::with_params(gear, ObjectClass::Ordinary, data, *params) + .map(|range| range.len()) + .collect() + } + + #[test] + fn short_input_is_one_chunk_and_empty_input_none() { + let gear = table(1); + assert_eq!(cut(&gear, &[]), 0); + assert_eq!(cut(&gear, &[7]), 1); + let data = pseudo_random(2, MIN_CHUNK + 1); + assert_eq!( + cut(&gear, &data[..MIN_CHUNK]), + MIN_CHUNK, + "the minimum is one chunk" + ); + assert!(cut(&gear, &data) >= MIN_CHUNK); + } + + #[test] + #[cfg_attr(miri, ignore = "megabytes of input are slow under Miri")] + fn a_secret_cut_depends_on_the_length_only() { + let params = ChunkParams::FORMAT_0; + for len in [0, 1, MIN_CHUNK, MAX_CHUNK - 1, MAX_CHUNK, MAX_CHUNK + 1] { + let random = cut_for( + ObjectClass::Secret, + &table(1), + &pseudo_random(1, len), + ¶ms, + ); + let zeros = cut_for(ObjectClass::Secret, &table(2), &vec![0; len], ¶ms); + assert_eq!((random, zeros), (len.min(MAX_CHUNK), len.min(MAX_CHUNK))); + } + } + + #[test] + #[cfg_attr(miri, ignore = "megabytes of input are slow under Miri")] + fn zeros_are_cut_at_the_maximum() { + let gear = table(1); + let zeros = vec![0u8; 3 * MAX_CHUNK + 5]; + assert_eq!( + our_lengths(&gear, &zeros, &ChunkParams::FORMAT_0), + fastcdc_lengths(&gear, &zeros, &ChunkParams::FORMAT_0) + ); + } + + #[test] + #[cfg_attr(miri, ignore = "megabytes of input are slow under Miri")] + fn full_size_chunks_match_fastcdc() { + for (seed, len) in [(1, 8 << 20), (2, 3 * MAX_CHUNK + 1), (3, MIN_CHUNK + 1)] { + let gear = table(seed); + let data = pseudo_random(seed, len); + let ours = our_lengths(&gear, &data, &ChunkParams::FORMAT_0); + assert_eq!(ours, fastcdc_lengths(&gear, &data, &ChunkParams::FORMAT_0)); + assert_eq!(ours.iter().sum::(), len); + let (last, rest) = ours.split_last().expect("non-empty input has chunks"); + assert!(*last > 0 && *last <= MAX_CHUNK); + for len in rest { + assert!((MIN_CHUNK..=MAX_CHUNK).contains(len), "{len}"); + } + } + } + + #[test] + #[cfg_attr(miri, ignore = "megabytes of input are slow under Miri")] + fn the_average_is_near_256_kib() { + let gear = table(5); + let data = pseudo_random(5, 32 << 20); + let lengths = our_lengths(&gear, &data, &ChunkParams::FORMAT_0); + let average = data.len() / lengths.len(); + assert!( + (128 << 10..=512 << 10).contains(&average), + "average chunk of {average} bytes" + ); + } + + #[test] + #[cfg_attr(miri, ignore = "megabytes of input are slow under Miri")] + fn a_different_seed_moves_the_boundaries() { + let data = pseudo_random(9, 4 << 20); + let first = our_lengths(&table(1), &data, &ChunkParams::FORMAT_0); + let second = our_lengths(&table(2), &data, &ChunkParams::FORMAT_0); + assert_ne!(first, second); + } + + #[test] + #[cfg_attr(miri, ignore = "megabytes of input are slow under Miri")] + fn an_edit_in_the_middle_changes_few_chunks() { + let gear = table(4); + let data = pseudo_random(4, 8 << 20); + let mut edited = data.clone(); + edited[4 << 20] ^= 1; + let before: Vec<&[u8]> = Chunks::new(&gear, ObjectClass::Ordinary, &data) + .map(|r| &data[r]) + .collect(); + let after: Vec<&[u8]> = Chunks::new(&gear, ObjectClass::Ordinary, &edited) + .map(|r| &edited[r]) + .collect(); + let changed = after.iter().filter(|chunk| !before.contains(chunk)).count(); + assert!((1..=2).contains(&changed), "{changed} chunks changed"); + } + + /// Bytes that cut often: random, a small alphabet, or long runs. + fn data() -> impl Strategy> { + prop_oneof![ + vec(any::(), 0..8_000), + vec(0u8..4, 0..8_000), + vec(prop_oneof![Just(0u8), Just(255u8)], 0..4_000), + ] + } + + proptest! { + #[test] + #[cfg_attr(miri, ignore = "proptest is slow under Miri")] + fn scaled_chunks_match_fastcdc(seed in 1u8.., data in data()) { + let gear = table(seed); + let params = ChunkParams::SCALED; + prop_assert_eq!(our_lengths(&gear, &data, ¶ms), fastcdc_lengths(&gear, &data, ¶ms)); + } + } +} diff --git a/crates/engine/core/src/chunk/gear_table.rs b/crates/engine/core/src/chunk/gear_table.rs new file mode 100644 index 0000000..87e056c --- /dev/null +++ b/crates/engine/core/src/chunk/gear_table.rs @@ -0,0 +1,110 @@ +//! The secret per-vault gear table (FS-52). + +use std::fmt; + +use crypthix_crypto::kdf::{self, KdfContext}; +use crypthix_crypto::key::{KdfKey, XofKey}; +use crypthix_crypto::label::XofKeyLabel; +use crypthix_crypto::mac; +use crypthix_crypto::secure_mem::{MemError, SecretBuf}; +use crypthix_types::id::VaultId; + +use crate::limits::GEAR_TABLE_LEN; + +/// The 256-word gear table of FastCDC, made from the vault's `chunker_seed` so a backend cannot +/// recompute chunk boundaries (FS-52, M-39). +/// +/// It is the first 2,048 bytes of the keyed BLAKE3 XOF under +/// `K_gear = KDF(chunker_seed, -, kdf/gear, vault_id)` over the empty input, read as +/// little-endian `u64` words. The shifted table that FastCDC also uses is computed from it as +/// each word is read. It is kept in a [`SecretBuf`]: plaintext memory, locked where +/// `RLIMIT_MEMLOCK` allows, wiped on free and left out of core dumps and forked children, but +/// not in secret pages as keys are, which fits +/// the design's assumption that the seed may leak anyway: keyed gear tables have been +/// recovered from observed chunk sizes (ePrint 2025/558). Padmé coarsens those sizes and packs +/// hide them (T-84). Only ordinary objects are cut with it; secret-class objects are cut at +/// fixed 1 MiB steps and never index it with their bytes (FS-52). +pub struct GearTable(SecretBuf); + +impl GearTable { + /// Derives the table of a vault. + /// + /// # Errors + /// + /// [`MemError`] if protected memory cannot be allocated for `K_gear` or the table. + /// + /// # Panics + /// + /// On Linux, in a child forked without `exec` after `chunker_seed` was made. + pub fn derive(chunker_seed: &KdfKey, vault_id: &VaultId) -> Result { + let context = KdfContext::new().field(vault_id.as_bytes()); + let key: XofKey = kdf::kdf(chunker_seed, None, XofKeyLabel::Gear, &context)?; + let mut table = SecretBuf::try_zeroed(GEAR_TABLE_LEN)?; + mac::xof(&key, table.as_mut_slice()); + Ok(Self(table)) + } + + /// The 256 words as little-endian bytes. The table is made with exactly 2,048 bytes, so this + /// is never `None`; the conversion is checked rather than asserted so the data path cannot + /// panic, and a cut is free of bounds checks once it has the array. + pub(crate) fn words(&self) -> Option<&[[u8; 8]; 256]> { + let (words, _) = self.0.as_slice().as_chunks::<8>(); + words.try_into().ok() + } + + /// The words as numbers, for the tests that compare with fastcdc. + #[cfg(test)] + pub(crate) fn to_u64s(&self) -> Vec { + self.words() + .expect("256 words") + .iter() + .map(|word| u64::from_le_bytes(*word)) + .collect() + } +} + +/// Prints nothing of the table. +impl fmt::Debug for GearTable { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("GearTable(..)") + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_data::gear_table as table; + + #[test] + fn the_table_is_the_gear_xof_of_the_vault() { + let key = KdfKey::from_bytes([3; 32]).expect("non-zero key"); + let vault_id = VaultId::try_from_bytes([0x11; 16]).expect("non-zero ID"); + let context = KdfContext::new().field(vault_id.as_bytes()); + let xof_key: XofKey = kdf::kdf(&key, None, XofKeyLabel::Gear, &context).expect("derives"); + let mut expected = [0u8; GEAR_TABLE_LEN]; + mac::xof(&xof_key, &mut expected); + let table = GearTable::derive(&key, &vault_id).expect("derives"); + assert_eq!(table.0.as_slice(), expected.as_slice()); + assert_eq!( + table.to_u64s()[1], + u64::from_le_bytes(expected[8..16].try_into().expect("8 bytes")), + "words are little-endian" + ); + } + + #[test] + fn seed_and_vault_both_change_the_table() { + let base = table(3).to_u64s(); + assert_eq!(base, table(3).to_u64s(), "derivation is deterministic"); + assert_ne!(base, table(4).to_u64s(), "seed ignored"); + let key = KdfKey::from_bytes([3; 32]).expect("non-zero key"); + let other_vault = VaultId::try_from_bytes([0x12; 16]).expect("non-zero ID"); + let other = GearTable::derive(&key, &other_vault).expect("derives"); + assert_ne!(base, other.to_u64s(), "vault ignored"); + } + + #[test] + fn debug_prints_no_words() { + assert_eq!(format!("{:?}", table(3)), "GearTable(..)"); + } +} diff --git a/crates/engine/core/src/chunk/masks.rs b/crates/engine/core/src/chunk/masks.rs new file mode 100644 index 0000000..0ad6136 --- /dev/null +++ b/crates/engine/core/src/chunk/masks.rs @@ -0,0 +1,30 @@ +//! The FastCDC masks for an average of 256 KiB at normalisation level 2 (FS-52). +//! +//! `fastcdc::v2020::select_masks` picks them as `MASKS[bits ± 2]` with `bits` the rounded +//! base-2 logarithm of the average, computed through `f64`; for 256 KiB, `bits` is 18. They are +//! written out here so no float is involved, and a test checks them against the crate. + +/// The strict mask, used below the average size: `MASKS[20]`, 20 bits set. +pub const MASK_S: u64 = 0x0000_d917_4753_7000; + +/// The loose mask, used from the average size up to the maximum: `MASKS[16]`, 16 bits set. +pub const MASK_L: u64 = 0x0000_d903_0353_7000; + +#[cfg(test)] +mod tests { + use fastcdc::v2020::{self, Normalization}; + + use super::*; + use crate::limits::AVG_CHUNK; + + #[test] + fn the_masks_are_those_fastcdc_selects() { + assert_eq!( + (MASK_S, MASK_L), + v2020::select_masks(AVG_CHUNK, Normalization::Level2) + ); + assert_eq!(MASK_S, v2020::MASKS[20]); + assert_eq!(MASK_L, v2020::MASKS[16]); + assert_eq!((MASK_S.count_ones(), MASK_L.count_ones()), (20, 16)); + } +} diff --git a/crates/engine/core/src/chunk/mod.rs b/crates/engine/core/src/chunk/mod.rs new file mode 100644 index 0000000..a0d8fd4 --- /dev/null +++ b/crates/engine/core/src/chunk/mod.rs @@ -0,0 +1,33 @@ +//! Content-defined chunking: FastCDC 2020 with a secret per-vault gear table (FS-52). +//! +//! The cut rule is the one of the `fastcdc` crate's `v2020` module, version 5.0.0 (normalised +//! chunking level 2): the loop starts at the minimum size and takes two bytes per step, adding +//! `gear_ls[b] = gear[b] << 1` for the first byte of each pair (after doubling the hash twice) +//! and `gear[b]` for the second, and tests the matching shifted or plain mask after each. It +//! uses the strict mask below the average size and the loose one up to the maximum, and cuts at +//! the maximum when nothing matched. A chunk ends just before the byte whose hash matched. An +//! odd last byte of the scanned range is never tested as a cut point. Input no longer than the +//! minimum is one chunk; empty input has none. +//! +//! [`Chunks`] cuts data already in memory; [`StreamChunker`] cuts a reader through a window of +//! protected memory and gives the same chunks. + +mod chunk_params; +mod chunk_ref; +mod chunks; +mod cut; +mod gear_table; +mod masks; +mod object_shape; +mod stream_chunker; +mod stream_error; + +pub(crate) use chunk_params::ChunkParams; +pub use chunk_ref::ChunkRef; +pub use chunks::Chunks; +pub use cut::cut; +pub use gear_table::GearTable; +pub use masks::{MASK_L, MASK_S}; +pub use object_shape::ObjectShape; +pub use stream_chunker::StreamChunker; +pub use stream_error::StreamError; diff --git a/crates/engine/core/src/chunk/object_shape.rs b/crates/engine/core/src/chunk/object_shape.rs new file mode 100644 index 0000000..62ce97b --- /dev/null +++ b/crates/engine/core/src/chunk/object_shape.rs @@ -0,0 +1,40 @@ +//! An object's class and whether it has one chunk or more, as the chunker found. + +use crate::blob::ObjectClass; + +/// The class an object was cut for and whether it has a single chunk or two or more, which +/// together decide whether its blob IDs are keyed (FS-55). +/// +/// Only the chunker makes one, from the class it cut for and what it cut: +/// [`ChunkRef::object_shape`] and [`Chunks::object_shape`]. A writer therefore cannot claim two +/// or more chunks for an object that has one, which would give a single-chunk object keyed +/// blob IDs that a reader, deriving the kind from the manifest's `chunk_count`, never notices +/// (T-85); nor seal as ordinary an object it cut as secret, or the reverse, since +/// [`ObjectSealer::new`](crate::blob::ObjectSealer::new) takes the class from here. +/// +/// [`ChunkRef::object_shape`]: crate::chunk::ChunkRef::object_shape +/// [`Chunks::object_shape`]: crate::chunk::Chunks::object_shape +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub struct ObjectShape { + class: ObjectClass, + single: bool, +} + +impl ObjectShape { + /// The shape of an object of `class`, with one chunk if `single`. + pub(crate) const fn new(class: ObjectClass, single: bool) -> Self { + Self { class, single } + } + + /// The class the object was cut for, which its sealer uses too. + #[must_use] + pub const fn class(self) -> ObjectClass { + self.class + } + + /// Whether the object has exactly one chunk. + #[must_use] + pub const fn is_single(self) -> bool { + self.single + } +} diff --git a/crates/engine/core/src/chunk/stream_chunker.rs b/crates/engine/core/src/chunk/stream_chunker.rs new file mode 100644 index 0000000..f9606af --- /dev/null +++ b/crates/engine/core/src/chunk/stream_chunker.rs @@ -0,0 +1,443 @@ +//! Cutting a reader. + +use std::fmt; +use std::io::{ErrorKind, Read}; + +use crypthix_crypto::secure_mem::SecretBuf; + +use crate::blob::ObjectClass; +use crate::chunk::cut::cut_for; +use crate::chunk::{ChunkParams, ChunkRef, GearTable, StreamError}; + +/// Cuts the bytes of a reader, for an object of a class, into the same chunks +/// [`Chunks`](crate::chunk::Chunks) gives for them in memory (FS-52), through a window of +/// protected memory twice the maximum chunk size. +/// +/// The window is refilled whenever no more than one maximum chunk is left in it, so a cut +/// always sees either a full maximum chunk and at least one byte past it, or the end of the +/// input. That is also how each chunk knows whether it is the last. Short reads are fine and +/// [`ErrorKind::Interrupted`] is retried. After any error the chunker is fused: every later +/// call returns [`StreamError::Failed`]. +/// +/// ``` +/// use crypthix_core::blob::ObjectClass; +/// use crypthix_core::chunk::{GearTable, StreamChunker}; +/// use crypthix_crypto::key::KdfKey; +/// use crypthix_types::id::VaultId; +/// +/// let gear = GearTable::derive(&KdfKey::random()?, &VaultId::try_from_bytes([1; 16])?)?; +/// let data = vec![0u8; (1 << 20) + 5]; +/// let mut chunker = StreamChunker::new(&gear, ObjectClass::Ordinary, data.as_slice())?; +/// let first = chunker.next_chunk()?.expect("one full chunk"); +/// assert_eq!((first.bytes().len(), first.is_last()), (1 << 20, false)); +/// let second = chunker.next_chunk()?.expect("and the rest"); +/// assert_eq!((second.bytes().len(), second.index(), second.is_last()), (5, 1, true)); +/// assert!(chunker.next_chunk()?.is_none()); +/// # Ok::<(), Box>(()) +/// ``` +pub struct StreamChunker<'g, R> { + gear: &'g GearTable, + class: ObjectClass, + reader: R, + params: ChunkParams, + window: SecretBuf, + /// Start of the bytes not yet cut. + start: usize, + /// End of the bytes read. + end: usize, + /// The reader has returned 0. + eof: bool, + /// Index of the next chunk. + index: u64, + /// A call failed; every later call fails too. + failed: bool, +} + +impl<'g, R: Read> StreamChunker<'g, R> { + /// A chunker over `reader`, for an object of `class`; `gear` is used for the ordinary class + /// only. + /// + /// # Errors + /// + /// [`StreamError::Memory`] if protected memory cannot be allocated for the 2 MiB window. + pub fn new(gear: &'g GearTable, class: ObjectClass, reader: R) -> Result { + Self::with_params(gear, class, reader, ChunkParams::FORMAT_0) + } + + /// A chunker at the scaled-down sizes of + /// [`Chunks::scaled_for_fuzzing`](crate::chunk::Chunks::scaled_for_fuzzing), with a + /// 2 KiB window. Not part of the API and not a format 0 cut; for the `chunker` fuzz target. + /// + /// # Errors + /// + /// [`StreamError::Memory`] if protected memory cannot be allocated for the window. + #[doc(hidden)] + pub fn scaled_for_fuzzing( + gear: &'g GearTable, + class: ObjectClass, + reader: R, + ) -> Result { + Self::with_params(gear, class, reader, ChunkParams::SCALED) + } + + /// A chunker with other sizes and masks, for tests. + pub(crate) fn with_params( + gear: &'g GearTable, + class: ObjectClass, + reader: R, + params: ChunkParams, + ) -> Result { + let window = SecretBuf::try_zeroed(params.max * 2)?; + Ok(Self { + gear, + class, + reader, + params, + window, + start: 0, + end: 0, + eof: false, + index: 0, + failed: false, + }) + } + + /// The next chunk, or `None` after the last one. An empty input has no chunks. + /// + /// # Errors + /// + /// - [`StreamError::Io`] if the reader fails. + /// - [`StreamError::Failed`] on every call after one that failed: the chunker is fused on + /// error, so an input it could not read to the end is never taken as complete. + pub fn next_chunk(&mut self) -> Result>, StreamError> { + if self.failed { + return Err(StreamError::Failed); + } + if !self.eof + && self.end.saturating_sub(self.start) <= self.params.max + && let Err(error) = self.refill() + { + self.failed = true; + return Err(error); + } + if self.start == self.end { + return Ok(None); + } + let window = self.window.as_slice(); + // `start < end <= window.len()` always holds; failing instead keeps this panic-free. + let Some(rest) = window.get(self.start..self.end) else { + self.failed = true; + return Err(StreamError::Failed); + }; + let len = cut_for(self.class, self.gear, rest, &self.params); + let Some(bytes) = rest.get(..len) else { + self.failed = true; + return Err(StreamError::Failed); + }; + self.start += len; + let index = self.index; + self.index = self.index.saturating_add(1); + let is_last = self.eof && self.start == self.end; + Ok(Some(ChunkRef::new(bytes, index, is_last, self.class))) + } + + /// Moves the bytes not yet cut to the front of the window and reads until it is full or the + /// reader ends. + fn refill(&mut self) -> Result<(), StreamError> { + let window = self.window.as_mut_slice(); + if self.start > self.end || self.end > window.len() { + return Err(StreamError::Failed); + } + window.copy_within(self.start..self.end, 0); + self.end -= self.start; + self.start = 0; + loop { + let free = match window.get_mut(self.end..) { + Some(free) if !free.is_empty() => free, + _ => break, + }; + match self.reader.read(free) { + Ok(0) => { + self.eof = true; + break; + } + // A reader that claims more than it was given breaks the `Read` contract. + Ok(read) if read > free.len() => { + return Err(std::io::Error::from(ErrorKind::InvalidData).into()); + } + Ok(read) => self.end += read, + Err(error) if error.kind() == ErrorKind::Interrupted => {} + Err(error) => return Err(error.into()), + } + } + Ok(()) + } +} + +/// Prints the position only, never the window. +impl fmt::Debug for StreamChunker<'_, R> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("StreamChunker") + .field("class", &self.class) + .field("index", &self.index) + .field("eof", &self.eof) + .field("failed", &self.failed) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use std::io; + use std::ops::Range; + + use proptest::collection::vec; + use proptest::prelude::{any, prop_assert_eq, proptest}; + + use super::*; + use crate::chunk::Chunks; + use crate::test_data::gear_table as table; + use crate::test_data::pseudo_random; + + /// A reader that returns at most the next step's bytes per call, and `Interrupted` where a + /// step is 0. + struct Choppy<'a> { + data: &'a [u8], + steps: Vec, + call: usize, + } + + impl Read for Choppy<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let step = self.steps[self.call % self.steps.len()]; + self.call += 1; + if step == 0 { + return Err(io::Error::from(ErrorKind::Interrupted)); + } + let len = step.min(buf.len()).min(self.data.len()); + buf[..len].copy_from_slice(&self.data[..len]); + self.data = &self.data[len..]; + Ok(len) + } + } + + /// Every chunk as its offsets, index, last flag and bytes. + fn streamed( + gear: &GearTable, + class: ObjectClass, + reader: R, + params: ChunkParams, + total: usize, + ) -> Vec<(Range, u64, bool, Vec)> { + let mut chunker = StreamChunker::with_params(gear, class, reader, params).expect("window"); + let mut out = Vec::new(); + let mut offset = 0; + while let Some(chunk) = chunker.next_chunk().expect("reads") { + let len = chunk.bytes().len(); + out.push(( + offset..offset + len, + chunk.index(), + chunk.is_last(), + chunk.bytes().to_vec(), + )); + offset += len; + } + assert_eq!(offset, total); + assert!(chunker.next_chunk().expect("reads").is_none(), "not fused"); + out + } + + fn check_against_memory( + gear: &GearTable, + class: ObjectClass, + data: &[u8], + params: ChunkParams, + steps: Vec, + ) { + let reader = Choppy { + data, + steps, + call: 0, + }; + let streamed = streamed(gear, class, reader, params, data.len()); + let in_memory: Vec> = Chunks::with_params(gear, class, data, params).collect(); + assert_eq!(streamed.len(), in_memory.len()); + for (i, ((range, index, is_last, bytes), expected)) in + streamed.iter().zip(&in_memory).enumerate() + { + assert_eq!(range, expected); + assert_eq!(*index, i as u64); + assert_eq!(*is_last, i + 1 == in_memory.len()); + assert_eq!(bytes.as_slice(), &data[expected.clone()]); + } + } + + // The tests that Miri runs use the scaled sizes: zeroing and wiping a 2 MiB window takes + // minutes there. + #[test] + fn empty_input_has_no_chunks() { + let gear = table(1); + let mut chunker = StreamChunker::with_params( + &gear, + ObjectClass::Ordinary, + io::empty(), + ChunkParams::SCALED, + ) + .expect("window"); + assert!(chunker.next_chunk().expect("reads").is_none()); + } + + #[test] + #[cfg_attr(miri, ignore = "a 2 MiB window takes minutes under Miri")] + fn a_small_input_is_one_last_chunk() { + let gear = table(1); + let mut chunker = + StreamChunker::new(&gear, ObjectClass::Ordinary, &b"tiny"[..]).expect("window"); + let chunk = chunker.next_chunk().expect("reads").expect("one chunk"); + assert_eq!( + (chunk.bytes(), chunk.index(), chunk.is_last()), + (&b"tiny"[..], 0, true) + ); + assert_eq!( + format!("{chunk:?}"), + "ChunkRef { len: 4, index: 0, is_last: true }" + ); + } + + #[test] + fn reader_errors_are_returned() { + struct Broken; + impl Read for Broken { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Err(io::Error::other("disk")) + } + } + struct Liar; + impl Read for Liar { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + Ok(buf.len() + 1) + } + } + let gear = table(1); + let mut chunker = + StreamChunker::with_params(&gear, ObjectClass::Ordinary, Broken, ChunkParams::SCALED) + .expect("window"); + assert!(matches!(chunker.next_chunk(), Err(StreamError::Io(_)))); + assert!(matches!(chunker.next_chunk(), Err(StreamError::Failed))); + let mut chunker = + StreamChunker::with_params(&gear, ObjectClass::Ordinary, Liar, ChunkParams::SCALED) + .expect("window"); + assert!( + matches!(chunker.next_chunk(), Err(StreamError::Io(error)) if error.kind() == ErrorKind::InvalidData) + ); + assert!(matches!(chunker.next_chunk(), Err(StreamError::Failed))); + } + + #[test] + fn a_failed_read_is_never_taken_for_the_end() { + /// Gives `data` once, then fails once, then reports the end. + struct FailsOnce<'a> { + data: &'a [u8], + calls: usize, + } + impl Read for FailsOnce<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.calls += 1; + match self.calls { + 1 => { + let len = buf.len().min(self.data.len()); + buf[..len].copy_from_slice(&self.data[..len]); + Ok(len) + } + 2 => Err(io::Error::other("disk")), + _ => Ok(0), + } + } + } + let gear = table(1); + let data = pseudo_random(4, 100); + let reader = FailsOnce { + data: &data, + calls: 0, + }; + let mut chunker = + StreamChunker::with_params(&gear, ObjectClass::Ordinary, reader, ChunkParams::SCALED) + .expect("window"); + assert!(matches!(chunker.next_chunk(), Err(StreamError::Io(_)))); + for _ in 0..2 { + assert!(matches!(chunker.next_chunk(), Err(StreamError::Failed))); + } + assert!(format!("{chunker:?}").contains("failed: true")); + } + + #[test] + #[cfg_attr(miri, ignore = "megabytes of input are slow under Miri")] + fn full_size_streams_match_memory() { + let gear = table(2); + let data = pseudo_random(2, 5 << 20); + for class in [ObjectClass::Ordinary, ObjectClass::Secret] { + check_against_memory(&gear, class, &data, ChunkParams::FORMAT_0, vec![usize::MAX]); + check_against_memory( + &gear, + class, + &data, + ChunkParams::FORMAT_0, + vec![4096, 0, 65_537, 1], + ); + let zeros = vec![0u8; 2 << 20]; + check_against_memory( + &gear, + class, + &zeros, + ChunkParams::FORMAT_0, + vec![usize::MAX], + ); + } + // A secret object of exactly the maximum is one last chunk; one byte more is two. + for (len, lengths) in [(1 << 20, vec![1 << 20]), ((1 << 20) + 1, vec![1 << 20, 1])] { + let data = pseudo_random(3, len); + let chunks = streamed( + &gear, + ObjectClass::Secret, + data.as_slice(), + ChunkParams::FORMAT_0, + len, + ); + let got: Vec = chunks.iter().map(|(range, ..)| range.len()).collect(); + assert_eq!(got, lengths); + } + } + + proptest! { + #[test] + #[cfg_attr(miri, ignore = "proptest is slow under Miri")] + fn streaming_equals_in_memory( + seed in 1u8.., + data in vec(any::(), 0..6_000), + steps in vec(0usize..700, 1..8), + secret: bool, + ) { + // At least one step reads, so the reader always makes progress. + let mut steps = steps; + steps.push(1); + let gear = table(seed); + let class = if secret { ObjectClass::Secret } else { ObjectClass::Ordinary }; + check_against_memory(&gear, class, &data, ChunkParams::SCALED, steps); + } + + #[test] + #[cfg_attr(miri, ignore = "proptest is slow under Miri")] + fn chunks_reassemble_the_stream(seed in 1u8.., data in vec(0u8..3, 0..6_000)) { + let gear = table(seed); + let chunks = streamed( + &gear, + ObjectClass::Ordinary, + data.as_slice(), + ChunkParams::SCALED, + data.len(), + ); + let rebuilt: Vec = chunks.iter().flat_map(|(_, _, _, bytes)| bytes.clone()).collect(); + prop_assert_eq!(rebuilt, data); + } + } +} diff --git a/crates/engine/core/src/chunk/stream_error.rs b/crates/engine/core/src/chunk/stream_error.rs new file mode 100644 index 0000000..0faf505 --- /dev/null +++ b/crates/engine/core/src/chunk/stream_error.rs @@ -0,0 +1,80 @@ +//! Why a stream could not be cut. + +use std::error::Error; +use std::fmt; +use std::io; + +use crypthix_crypto::secure_mem::MemError; + +/// A [`StreamChunker`](crate::chunk::StreamChunker) failed: no protected memory for its +/// window, the reader failed, or it is used again after a failure. +#[non_exhaustive] +#[must_use] +#[derive(Debug)] +pub enum StreamError { + /// The reader failed with an error other than [`io::ErrorKind::Interrupted`], which is + /// retried. + Io(io::Error), + /// No protected memory for the window. + Memory(MemError), + /// An earlier call failed, and its error was returned then. The chunker is fused on error, + /// so the rest of an input it could not read is never taken for its end. + Failed, +} + +impl fmt::Display for StreamError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + StreamError::Io(_) => "the input could not be read", + StreamError::Memory(_) => "no protected memory for the chunking window", + StreamError::Failed => "the chunker already failed and cuts nothing more", + }) + } +} + +impl Error for StreamError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + StreamError::Io(error) => Some(error), + StreamError::Memory(error) => Some(error), + StreamError::Failed => None, + } + } +} + +impl From for StreamError { + fn from(error: io::Error) -> Self { + StreamError::Io(error) + } +} + +impl From for StreamError { + fn from(error: MemError) -> Self { + StreamError::Memory(error) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn display_names_the_kind_and_source_is_the_cause() { + let io = StreamError::from(io::Error::other("disk")); + assert_eq!(io.to_string(), "the input could not be read"); + assert_eq!( + io.source().map(ToString::to_string), + Some("disk".to_owned()) + ); + let memory = StreamError::from(MemError::MapFailed); + assert_ne!(memory.to_string(), io.to_string()); + assert_eq!( + memory.source().map(ToString::to_string), + Some(MemError::MapFailed.to_string()) + ); + let failed = StreamError::Failed; + assert!(failed.source().is_none()); + assert_ne!(failed.to_string(), io.to_string()); + assert_ne!(failed.to_string(), memory.to_string()); + } +} diff --git a/crates/engine/core/src/compress/compress_error.rs b/crates/engine/core/src/compress/compress_error.rs new file mode 100644 index 0000000..5442c0f --- /dev/null +++ b/crates/engine/core/src/compress/compress_error.rs @@ -0,0 +1,127 @@ +//! A zstd failure. + +use std::error::Error; +use std::fmt; + +use zstd_safe::zstd_sys::ZSTD_ErrorCode; + +use crate::limits::ZSTD_VERSION; + +/// zstd failed for a reason of its own, not because of the input's format. +#[non_exhaustive] +#[must_use] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub enum CompressError { + /// zstd could not allocate a context. + Context, + /// zstd returned an error; its name from `ZSTD_getErrorName`. + Zstd(&'static str), + /// The linked libzstd is not the version FS-53 pins + /// ([`ZSTD_VERSION`](crate::limits::ZSTD_VERSION)); this is the `ZSTD_versionNumber` it + /// reports. A build fault, not a property of any input. + Version(u32), +} + +impl CompressError { + /// The error zstd's `code` names. + pub(crate) fn from_code(code: usize) -> Self { + CompressError::Zstd(zstd_safe::get_error_name(code)) + } + + /// Whether zstd's `code` is `ZSTD_error_memory_allocation`: zstd ran out of memory, which + /// says nothing about the input. + pub(crate) fn is_allocation_failure(code: usize) -> bool { + // zstd returns an error as the negated `ZSTD_ErrorCode`, as a `size_t`. + code == (ZSTD_ErrorCode::ZSTD_error_memory_allocation as usize).wrapping_neg() + } + + /// Checks that the `linked` libzstd version is the one FS-53 pins. + pub(crate) fn check_version(linked: u32) -> Result<(), Self> { + if linked == ZSTD_VERSION { + Ok(()) + } else { + Err(CompressError::Version(linked)) + } + } +} + +impl fmt::Display for CompressError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CompressError::Context => f.write_str("zstd could not allocate a context"), + CompressError::Zstd(name) => write!(f, "zstd failed: {name}"), + CompressError::Version(linked) => write!( + f, + "libzstd {linked} is linked, but FS-53 pins {ZSTD_VERSION}" + ), + } + } +} + +impl Error for CompressError {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn zstd_codes_are_named() { + // ZSTD_error_dstSize_tooSmall, as a negated size_t. + let code = 0usize.wrapping_sub(70); + let error = CompressError::from_code(code); + assert_eq!( + error, + CompressError::Zstd("Destination buffer is too small") + ); + assert_eq!( + error.to_string(), + "zstd failed: Destination buffer is too small" + ); + } + + #[test] + fn only_the_allocation_code_is_an_allocation_failure() { + // ZSTD_error_memory_allocation is 64 and pinned since zstd 1.3.1 (zstd_errors.h). + assert!(CompressError::is_allocation_failure( + 0usize.wrapping_sub(64) + )); + for code in [0, 64, 0usize.wrapping_sub(20), 0usize.wrapping_sub(70)] { + assert!(!CompressError::is_allocation_failure(code), "{code}"); + } + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn the_allocation_code_is_the_one_zstd_names() { + let code = 0usize.wrapping_sub(64); + assert_eq!( + CompressError::from_code(code), + CompressError::Zstd("Allocation error : not enough memory") + ); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn the_pinned_zstd_is_linked() { + assert_eq!(zstd_safe::version_number(), ZSTD_VERSION); + assert_eq!( + CompressError::check_version(zstd_safe::version_number()), + Ok(()) + ); + } + + #[test] + fn any_other_version_is_refused() { + for linked in [0, 10_506, 10_508, 20_000] { + assert_eq!( + CompressError::check_version(linked), + Err(CompressError::Version(linked)) + ); + } + assert_eq!( + CompressError::Version(10_508).to_string(), + "libzstd 10508 is linked, but FS-53 pins 10507" + ); + } +} diff --git a/crates/engine/core/src/compress/compressor.rs b/crates/engine/core/src/compress/compressor.rs new file mode 100644 index 0000000..dc6c29f --- /dev/null +++ b/crates/engine/core/src/compress/compressor.rs @@ -0,0 +1,239 @@ +//! The write side of FS-53. + +use std::fmt; + +use crypthix_crypto::secure_mem::SecretBuf; +use crypthix_types::format_error::FormatError; +use zstd_safe::{CCtx, CParameter}; + +use crate::blob::ObjectClass; +use crate::compress::{CompressError, keep_compressed}; +use crate::error::WriteError; +use crate::inner::{Comp, encode_inner}; +use crate::limits::{MAX_CHUNK, WINDOW_LOG, ZSTD_LEVEL}; + +/// Turns chunks into inner plaintexts (FS-53, FS-54), reusing one zstd context and one scratch +/// buffer of protected memory for the frame. +/// +/// The frame is one zstd frame at level 3 with its content size, no checksum, no dictionary +/// ID and a window of at most 1 MiB. It is kept only if `16 × frame ≤ 15 × chunk` +/// ([`keep_compressed`]); otherwise, and always for the secret class, the chunk is stored raw. +pub struct Compressor { + cctx: CCtx<'static>, + /// Large enough for the frame of a maximum chunk; wiped after each use. + scratch: SecretBuf, +} + +impl Compressor { + /// A compressor with the parameters of FS-53. + /// + /// # Errors + /// + /// - [`WriteError::Zstd`] with [`CompressError::Version`] if the linked libzstd is not + /// the version FS-53 pins, as its output could then differ from the test vectors. + /// - [`WriteError::Zstd`] if zstd cannot make the context or refuses a parameter. + /// - [`WriteError::Memory`] if protected memory cannot be allocated for the scratch buffer. + pub fn new() -> Result { + CompressError::check_version(zstd_safe::version_number())?; + let mut cctx = CCtx::try_create().ok_or(CompressError::Context)?; + let parameters = [ + CParameter::CompressionLevel(ZSTD_LEVEL), + CParameter::ContentSizeFlag(true), + CParameter::ChecksumFlag(false), + CParameter::DictIdFlag(false), + CParameter::WindowLog(WINDOW_LOG), + ]; + for parameter in parameters { + cctx.set_parameter(parameter) + .map_err(CompressError::from_code)?; + } + let scratch = SecretBuf::try_zeroed(zstd_safe::compress_bound(MAX_CHUNK))?; + Ok(Self { cctx, scratch }) + } + + /// The inner plaintext of `chunk`: its zstd frame where that is kept, else the chunk itself + /// (FS-53, FS-54). Objects of the secret class are never compressed. + /// + /// # Errors + /// + /// - [`WriteError::Format`] with `Limit` if `chunk` is longer than 1 MiB. + /// - [`WriteError::Zstd`] if zstd fails. The chunk is then not stored raw instead. + /// - [`WriteError::Memory`] if protected memory cannot be allocated for the inner plaintext. + pub fn encode_chunk( + &mut self, + chunk: &[u8], + class: ObjectClass, + ) -> Result { + if chunk.len() > MAX_CHUNK { + return Err(FormatError::Limit.into()); + } + match class { + ObjectClass::Secret => return encode_inner(Comp::Raw, chunk), + ObjectClass::Ordinary => {} + } + let scratch = self.scratch.as_mut_slice(); + let written = match self.cctx.compress2(scratch, chunk) { + Ok(written) => written, + Err(code) => { + // zstd may have written part of a frame, and does not say how much. + scratch.fill(0); + return Err(CompressError::from_code(code).into()); + } + }; + // zstd never reports more than the buffer it was given; failing instead keeps this + // panic-free. + let Some(frame) = scratch.get_mut(..written) else { + scratch.fill(0); + return Err(CompressError::Zstd("frame longer than its buffer").into()); + }; + let inner = if keep_compressed(frame.len() as u64, chunk.len() as u64) { + encode_inner(Comp::Zstd, frame) + } else { + encode_inner(Comp::Raw, chunk) + }; + frame.fill(0); + inner + } +} + +/// Prints nothing of the scratch buffer. +impl fmt::Debug for Compressor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Compressor(..)") + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::compress::frame_check::frame_check; + use crate::inner::decode_inner; + use crate::test_data::pseudo_random; + + fn text(len: usize) -> Vec { + b"the quick brown fox jumps over the lazy dog. " + .iter() + .copied() + .cycle() + .take(len) + .collect() + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn compressible_chunks_are_kept_as_one_checked_frame() { + let mut compressor = Compressor::new().expect("context"); + let chunk = text(100_000); + let inner = compressor + .encode_chunk(&chunk, ObjectClass::Ordinary) + .expect("encodes"); + let view = decode_inner(&inner).expect("well formed"); + assert_eq!(view.comp(), Comp::Zstd); + assert!(view.payload().len() < 1_000); + assert_eq!(frame_check(view.payload(), 100_000), Ok(())); + // No checksum, no dictionary ID, content size declared. + assert_eq!(view.payload()[4] & 0x0F, 0); + let again = compressor + .encode_chunk(&chunk, ObjectClass::Ordinary) + .expect("encodes"); + assert_eq!( + inner.as_slice(), + again.as_slice(), + "the encoder is deterministic" + ); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn frames_pass_the_reader_checks_at_every_content_size_field() { + // One, two and four-byte content sizes, at the edges where the field widens. + let mut compressor = Compressor::new().expect("context"); + for len in [0, 1, 255, 256, 257, 65_791, 65_792, MAX_CHUNK] { + let chunk = text(len); + let mut frame = vec![0u8; zstd_safe::compress_bound(len)]; + let written = compressor + .cctx + .compress2(&mut frame[..], &chunk) + .expect("compresses"); + frame.truncate(written); + assert_eq!(frame_check(&frame, len as u64), Ok(()), "{len}"); + } + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn incompressible_chunks_are_raw() { + let mut compressor = Compressor::new().expect("context"); + let chunk = pseudo_random(1, 70_000); + let inner = compressor + .encode_chunk(&chunk, ObjectClass::Ordinary) + .expect("encodes"); + let view = decode_inner(&inner).expect("well formed"); + assert_eq!(view.comp(), Comp::Raw); + assert_eq!(view.payload(), chunk.as_slice()); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn secret_chunks_are_never_compressed() { + let mut compressor = Compressor::new().expect("context"); + let chunk = text(100_000); + let inner = compressor + .encode_chunk(&chunk, ObjectClass::Secret) + .expect("encodes"); + let view = decode_inner(&inner).expect("well formed"); + assert_eq!(view.comp(), Comp::Raw); + assert_eq!(view.payload(), chunk.as_slice()); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn chunks_up_to_one_mib_and_no_longer() { + let mut compressor = Compressor::new().expect("context"); + let largest = text(MAX_CHUNK); + let inner = compressor + .encode_chunk(&largest, ObjectClass::Ordinary) + .expect("1 MiB"); + assert_eq!(decode_inner(&inner).map(|view| view.comp()), Ok(Comp::Zstd)); + let random = pseudo_random(2, MAX_CHUNK); + let raw = compressor + .encode_chunk(&random, ObjectClass::Ordinary) + .expect("1 MiB"); + assert_eq!(raw.len(), MAX_CHUNK + (1 << 15)); + for class in [ObjectClass::Ordinary, ObjectClass::Secret] { + let over = text(MAX_CHUNK + 1); + assert_eq!( + compressor.encode_chunk(&over, class).map(|_| ()), + Err(WriteError::Format(FormatError::Limit)) + ); + } + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn a_chunk_that_compresses_too_little_is_raw() { + // Random bytes with a compressible run: zstd saves something, but less than 1/16. + let mut compressor = Compressor::new().expect("context"); + let mut chunk = pseudo_random(3, 16_000); + chunk[..600].fill(0); + let inner = compressor + .encode_chunk(&chunk, ObjectClass::Ordinary) + .expect("encodes"); + assert_eq!(decode_inner(&inner).map(|view| view.comp()), Ok(Comp::Raw)); + let mut frame = vec![0u8; zstd_safe::compress_bound(chunk.len())]; + let mut cctx = CCtx::create(); + cctx.set_parameter(CParameter::CompressionLevel(ZSTD_LEVEL)) + .expect("sets"); + let written = cctx + .compress2(frame.as_mut_slice(), &chunk) + .expect("compresses"); + assert!(written < chunk.len(), "zstd did save a little"); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn debug_prints_nothing() { + let compressor = Compressor::new().expect("context"); + assert_eq!(format!("{compressor:?}"), "Compressor(..)"); + } +} diff --git a/crates/engine/core/src/compress/decompressor.rs b/crates/engine/core/src/compress/decompressor.rs new file mode 100644 index 0000000..716a458 --- /dev/null +++ b/crates/engine/core/src/compress/decompressor.rs @@ -0,0 +1,338 @@ +//! The read side of FS-53. + +use std::fmt; + +use crypthix_crypto::secure_mem::SecretBuf; +use crypthix_types::format_error::FormatError; +use zstd_safe::{DCtx, DParameter, InBuffer, OutBuffer, ResetDirective}; + +use crate::compress::CompressError; +use crate::compress::frame_check::frame_check; +use crate::error::ReadError; +use crate::limits::{MAX_PLAIN_LEN, WINDOW_LOG}; + +/// Decompresses chunk frames into buffers of protected memory of exactly their `plain_len`, +/// reusing one zstd context whose window is capped at 1 MiB (FS-53). +/// +/// The context is made at the first frame that gets past the `plain_len` cap, after the +/// version check, so a reader that only meets raw chunks never calls into libzstd. +pub struct Decompressor { + dctx: Option>, +} + +impl Decompressor { + /// A decompressor whose window will be capped at 1 MiB. It holds no zstd context yet. + #[must_use] + pub fn new() -> Self { + Self { dctx: None } + } + + /// The `plain_len` bytes `frame` decompresses to. + /// + /// In this order, each failure being `Decompress` (FS-53) unless said otherwise: + /// 1. `plain_len` is at most 1 MiB, checked before anything else; + /// 2. on first use, the linked libzstd is the version FS-53 pins and a context is made + /// ([`ReadError::Zstd`] if not), before any other call into libzstd; + /// 3. the frame is exactly one frame with no checksum, no dictionary ID, a declared content + /// size equal to `plain_len` and a window of at most 1 MiB; + /// 4. a streaming decoder writes into a buffer of exactly `plain_len` bytes, and must fill + /// it, finish the frame and use every input byte; output that does not fit, or a frame + /// that ends early, fails. + /// + /// # Errors + /// + /// - [`ReadError::Format`] with `Decompress` as above. + /// - [`ReadError::Memory`] if protected memory cannot be allocated for the output. + /// - [`ReadError::Zstd`] with [`CompressError::Version`] if the linked libzstd is not the + /// version FS-53 pins; otherwise if zstd cannot make, set up or reset the context, or + /// runs out of memory while decoding (it allocates its stream buffers on first use). + pub fn decode(&mut self, frame: &[u8], plain_len: u64) -> Result { + if plain_len > MAX_PLAIN_LEN { + return Err(FormatError::Decompress.into()); + } + let dctx = match &mut self.dctx { + Some(dctx) => dctx, + slot @ None => slot.insert(context(zstd_safe::version_number)?), + }; + frame_check(frame, plain_len)?; + let len = usize::try_from(plain_len).map_err(|_| FormatError::Decompress)?; + // A failed call leaves the context unusable until it is reset (zstd.h). + dctx.reset(ResetDirective::SessionOnly) + .map_err(|code| ReadError::Zstd(CompressError::from_code(code)))?; + let mut plain = SecretBuf::try_zeroed(len)?; + let written = stream(dctx, frame, plain.as_mut_slice())?; + // Defence in depth: zstd already fails a frame whose content differs from its declared + // size, and frame_check made that size `plain_len`, so this cannot fail today. + if written != len { + return Err(FormatError::Decompress.into()); + } + Ok(plain) + } +} + +impl Default for Decompressor { + fn default() -> Self { + Self::new() + } +} + +/// A decompression context with the window capped at 1 MiB, made only once `linked` reports +/// the libzstd version FS-53 pins: no other call into libzstd comes before that check. +fn context(linked: impl FnOnce() -> u32) -> Result, ReadError> { + CompressError::check_version(linked()).map_err(ReadError::Zstd)?; + let mut dctx = DCtx::try_create().ok_or(ReadError::Zstd(CompressError::Context))?; + dctx.set_parameter(DParameter::WindowLogMax(WINDOW_LOG)) + .map_err(|code| ReadError::Zstd(CompressError::from_code(code)))?; + Ok(dctx) +} + +/// Runs the streaming decoder until the frame ends, and returns how much it wrote. +fn stream(dctx: &mut DCtx<'static>, frame: &[u8], out: &mut [u8]) -> Result { + let fail = ReadError::Format(FormatError::Decompress); + let mut output = OutBuffer::around(out); + let mut input = InBuffer::around(frame); + loop { + let before = (input.pos(), output.pos()); + let hint = dctx + .decompress_stream(&mut output, &mut input) + .map_err(stream_error)?; + if hint == 0 { + break; + } + // No progress: the input ended inside the frame, or the output is full and the + // frame has more to give. + if (input.pos(), output.pos()) == before { + return Err(fail); + } + } + // Defence in depth: frame_check found the frame to end exactly at `frame.len()`, and zstd + // stops at the end of a frame, so this cannot fail today. + if input.pos() != frame.len() { + return Err(fail); + } + Ok(output.pos()) +} + +/// What a failed `ZSTD_decompressStream` means: running out of memory is the reader's own +/// trouble, so it must not look like tampering; anything else is the frame's fault. +fn stream_error(code: usize) -> ReadError { + if CompressError::is_allocation_failure(code) { + ReadError::Zstd(CompressError::from_code(code)) + } else { + FormatError::Decompress.into() + } +} + +/// Prints nothing of the context. +impl fmt::Debug for Decompressor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Decompressor(..)") + } +} + +#[cfg(test)] +mod tests { + use proptest::collection::vec; + use proptest::prelude::{any, prop_assert_eq, proptest}; + use zstd_safe::{CCtx, CParameter}; + + use super::*; + use crate::compress::frame_check::tests::raw_frame; + + const FAIL: Result, ReadError> = Err(ReadError::Format(FormatError::Decompress)); + + fn decode(frame: &[u8], plain_len: u64) -> Result, ReadError> { + Decompressor::new() + .decode(frame, plain_len) + .map(|plain| plain.to_vec()) + } + + /// A frame of `data` with the given extra parameters. + fn frame_of(data: &[u8], parameters: &[CParameter]) -> Vec { + let mut cctx = CCtx::create(); + for parameter in parameters { + cctx.set_parameter(*parameter).expect("sets"); + } + let mut frame = vec![0u8; zstd_safe::compress_bound(data.len())]; + let written = cctx + .compress2(frame.as_mut_slice(), data) + .expect("compresses"); + frame.truncate(written); + frame + } + + fn text(len: usize) -> Vec { + b"0123456789abcdef" + .iter() + .copied() + .cycle() + .take(len) + .collect() + } + + #[test] + fn another_libzstd_is_refused_before_any_call_into_it() { + assert_eq!( + context(|| 10_508).map(|_| ()), + Err(ReadError::Zstd(CompressError::Version(10_508))) + ); + } + + #[test] + fn nothing_touches_libzstd_before_the_first_frame_past_the_cap() { + let mut decompressor = Decompressor::default(); + assert_eq!(format!("{decompressor:?}"), "Decompressor(..)"); + assert_eq!( + decompressor + .decode(b"not even a frame", (1 << 20) + 1) + .map(|_| ()), + Err(ReadError::Format(FormatError::Decompress)) + ); + assert!( + decompressor.dctx.is_none(), + "no context for a refused length" + ); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn the_context_is_made_once_and_kept() { + let mut decompressor = Decompressor::new(); + assert!(decompressor.dctx.is_none()); + assert_eq!( + decompressor.decode(b"not even a frame", 5).map(|_| ()), + Err(ReadError::Format(FormatError::Decompress)) + ); + assert!(decompressor.dctx.is_some(), "made at the first frame"); + let plain = decompressor + .decode(&raw_frame(b"hello", 5, 0, None), 5) + .expect("decodes"); + assert_eq!(plain.as_slice(), b"hello"); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn frames_decode_to_exactly_their_length() { + let data = text(300_000); + let frame = frame_of(&data, &[]); + assert_eq!(decode(&frame, 300_000), Ok(data)); + assert_eq!( + decode(&raw_frame(b"hello", 5, 0, None), 5), + Ok(b"hello".to_vec()) + ); + assert_eq!(decode(&raw_frame(b"", 0, 0, None), 0), Ok(Vec::new())); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn plain_len_is_capped_at_one_mib_first() { + let data = text(1 << 20); + let frame = frame_of(&data, &[]); + assert_eq!(decode(&frame, 1 << 20), Ok(data)); + let over = text((1 << 20) + 1); + let frame = frame_of(&over, &[CParameter::WindowLog(20)]); + assert_eq!(decode(&frame, (1 << 20) + 1), FAIL); + assert_eq!(decode(b"not even a frame", u64::MAX), FAIL); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn content_longer_or_shorter_than_declared_fails() { + assert_eq!(decode(&raw_frame(b"hello!", 5, 0, None), 5), FAIL); + assert_eq!(decode(&raw_frame(b"hell", 5, 0, None), 5), FAIL); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn frames_with_a_checksum_fail() { + let data = text(10_000); + let checksum = frame_of(&data, &[CParameter::ChecksumFlag(true)]); + assert_eq!(decode(&checksum, 10_000), FAIL); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn frames_with_a_dictionary_id_fail() { + // Well-formed frames of one raw block that name dictionary 7, then 0x01020304. + let mut frame = raw_frame(b"hello", 5, 1, None); + frame.insert(5, 7); + assert_eq!( + zstd_safe::get_dict_id_from_frame(&frame).map(u32::from), + Some(7) + ); + assert_eq!(decode(&frame, 5), FAIL); + let mut frame = raw_frame(b"hello", 5, 3, None); + frame.splice(5..5, 0x0102_0304_u32.to_le_bytes()); + assert_eq!( + zstd_safe::get_dict_id_from_frame(&frame).map(u32::from), + Some(0x0102_0304) + ); + assert_eq!(decode(&frame, 5), FAIL); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn frames_without_a_content_size_fail() { + let data = text(10_000); + let unknown_size = frame_of(&data, &[CParameter::ContentSizeFlag(false)]); + assert_eq!(decode(&unknown_size, 10_000), FAIL); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn running_out_of_memory_while_decoding_is_not_tampering() { + let allocation = 0usize.wrapping_sub(64); + assert!(matches!( + stream_error(allocation), + ReadError::Zstd(CompressError::Zstd(_)) + )); + // ZSTD_error_corruption_detected and ZSTD_error_dstSize_tooSmall. + for code in [0usize.wrapping_sub(20), 0usize.wrapping_sub(70)] { + assert_eq!(stream_error(code), FormatError::Decompress.into()); + } + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn a_window_over_one_mib_fails() { + // A window descriptor of 2 MiB on content that is small enough. + assert_eq!(decode(&raw_frame(b"hello", 5, 0, Some(11 << 3)), 5), FAIL); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn corrupt_blocks_fail_and_the_context_recovers() { + let data = text(50_000); + let frame = frame_of(&data, &[]); + let mut decompressor = Decompressor::new(); + let mut corrupt = frame.clone(); + let last = corrupt.len() - 1; + corrupt[last / 2] ^= 0xFF; + corrupt[last] ^= 0xFF; + assert!(decompressor.decode(&corrupt, 50_000).is_err()); + let plain = decompressor + .decode(&frame, 50_000) + .expect("a reset context works again"); + assert_eq!(plain.as_slice(), data.as_slice()); + } + + proptest! { + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn round_trips_and_wrong_lengths_fail(data in vec(0u8..8, 0..20_000), delta in 1u64..3) { + let frame = frame_of(&data, &[CParameter::CompressionLevel(3)]); + let len = data.len() as u64; + prop_assert_eq!(decode(&frame, len), Ok(data)); + prop_assert_eq!(decode(&frame, len + delta), FAIL); + if len >= delta { + prop_assert_eq!(decode(&frame, len - delta), FAIL); + } + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn arbitrary_bytes_never_panic(bytes in vec(any::(), 0..200), len in 0u64..300) { + let _ = decode(&bytes, len); + } + } +} diff --git a/crates/engine/core/src/compress/frame_check.rs b/crates/engine/core/src/compress/frame_check.rs new file mode 100644 index 0000000..df3eebc --- /dev/null +++ b/crates/engine/core/src/compress/frame_check.rs @@ -0,0 +1,253 @@ +//! The checks a zstd frame passes before it is decompressed (FS-53). + +use crypthix_types::format_error::FormatError; + +use crate::limits::MAX_PLAIN_LEN; + +/// The magic number of a zstd frame, as its first four bytes. +const ZSTD_MAGIC: [u8; 4] = 0xFD2F_B528_u32.to_le_bytes(); + +/// Frame header descriptor bits (RFC 8878 section 3.1.1.1.1). +const SINGLE_SEGMENT: u8 = 0x20; +const UNUSED: u8 = 0x10; +const RESERVED: u8 = 0x08; +const CHECKSUM: u8 = 0x04; +const DICT_ID: u8 = 0x03; +const FCS_FLAG_SHIFT: u32 = 6; + +/// Checks that `frame` is exactly one zstd frame as FS-53 writes it, declaring `plain_len` +/// bytes of content: the zstd magic (so no skippable frame), the unused and reserved bits +/// clear, no checksum, no dictionary ID, a content size equal to `plain_len` in the shortest +/// field that holds it, a window of at most 1 MiB, and no bytes after the frame. Every failure +/// is `Decompress`. +/// +/// zstd checks the content against the declared size while decoding; these checks make sure +/// the declaration exists and matches before a byte is decoded. libzstd 1.5.7 ignores the +/// unused bit and reads a content size from a wider field than needed (RFC 8878 allows both +/// to a decoder); its encoder never writes either, so a frame with them is not one FS-53 +/// writes and is refused here. +pub(crate) fn frame_check(frame: &[u8], plain_len: u64) -> Result<(), FormatError> { + let fail = FormatError::Decompress; + let Some((magic, rest)) = frame.split_first_chunk::<4>() else { + return Err(fail); + }; + if *magic != ZSTD_MAGIC { + return Err(fail); + } + let Some((&descriptor, rest)) = rest.split_first() else { + return Err(fail); + }; + if descriptor & (UNUSED | RESERVED | CHECKSUM | DICT_ID) != 0 { + return Err(fail); + } + let single_segment = descriptor & SINGLE_SEGMENT != 0; + if descriptor >> FCS_FLAG_SHIFT == 0 && !single_segment { + // No content size at all. + return Err(fail); + } + if descriptor >> FCS_FLAG_SHIFT != fcs_flag(plain_len, single_segment) { + return Err(fail); + } + if !single_segment { + let window = rest.first().map(|&byte| window_size(byte)).ok_or(fail)?; + if window > MAX_PLAIN_LEN { + return Err(fail); + } + } + match zstd_safe::get_frame_content_size(frame) { + Ok(Some(size)) if size == plain_len => {} + _ => return Err(fail), + } + match zstd_safe::find_frame_compressed_size(frame) { + Ok(size) if size == frame.len() => Ok(()), + _ => Err(fail), + } +} + +/// The frame content size flag of the shortest field that holds `size` (RFC 8878 section +/// 3.1.1.1.1), as libzstd's encoder chooses it: one byte only in a single-segment frame, two +/// bytes with an offset of 256, four, then eight from `0xFFFF_FFFF` on. +fn fcs_flag(size: u64, single_segment: bool) -> u8 { + match size { + 0..256 if single_segment => 0, + 256..65_792 => 1, + 0..0xFFFF_FFFF => 2, + _ => 3, + } +} + +/// The window size a window descriptor byte declares (RFC 8878 section 3.1.1.1.2). +fn window_size(descriptor: u8) -> u64 { + let window_log = 10 + u32::from(descriptor >> 3); + let base = 1u64 << window_log; + base + (base / 8) * u64::from(descriptor & 0x07) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// A frame of one raw block holding `content`, declaring `declared` bytes in the shortest + /// field, with the given descriptor bits and, if `window` is `Some`, that window descriptor + /// instead of a single segment. + pub(crate) fn raw_frame( + content: &[u8], + declared: u32, + extra: u8, + window: Option, + ) -> Vec { + let flag = fcs_flag(u64::from(declared), window.is_none()); + sized_frame(content, declared, flag, extra, window) + } + + /// [`raw_frame`] with the content size in the field that `flag` names. + fn sized_frame( + content: &[u8], + declared: u32, + flag: u8, + extra: u8, + window: Option, + ) -> Vec { + let mut frame = ZSTD_MAGIC.to_vec(); + let mut descriptor = (flag << FCS_FLAG_SHIFT) | extra; + if window.is_none() { + descriptor |= SINGLE_SEGMENT; + } + frame.push(descriptor); + frame.extend(window); + let field = match flag { + 0 => vec![u8::try_from(declared).expect("below 256")], + 1 => u16::try_from(declared - 256) + .expect("below 65,792") + .to_le_bytes() + .to_vec(), + 2 => declared.to_le_bytes().to_vec(), + _ => u64::from(declared).to_le_bytes().to_vec(), + }; + frame.extend_from_slice(&field); + let block = u32::try_from(content.len()).expect("small") << 3 | 1; + frame.extend_from_slice(&block.to_le_bytes()[..3]); + frame.extend_from_slice(content); + frame + } + + fn check(frame: &[u8], plain_len: u64) -> Result<(), FormatError> { + frame_check(frame, plain_len) + } + + const FAIL: Result<(), FormatError> = Err(FormatError::Decompress); + + #[test] + fn window_descriptors_decode_as_rfc_8878_says() { + assert_eq!(window_size(0), 1 << 10); + assert_eq!(window_size(10 << 3), 1 << 20); + assert_eq!(window_size(10 << 3 | 1), (1 << 20) + (1 << 17)); + assert_eq!(window_size(9 << 3 | 7), (1 << 19) + 7 * (1 << 16)); + assert_eq!(window_size(11 << 3), 1 << 21); + assert_eq!(window_size(u8::MAX), (1 << 41) + 7 * (1 << 38)); + } + + #[test] + fn short_and_foreign_input_fails_before_calling_zstd() { + for frame in [ + &b""[..], + b"\x28\xB5\x2F", + b"\x28\xB5\x2F\xFD", + b"PK\x03\x04\x00\x00", + ] { + assert_eq!(check(frame, 0), FAIL, "{frame:?}"); + } + let mut skippable = raw_frame(b"x", 1, 0, None); + skippable[..4].copy_from_slice(&0x184D_2A50_u32.to_le_bytes()); + assert_eq!(check(&skippable, 1), FAIL); + for bit in [UNUSED, RESERVED, CHECKSUM, 1, 2, 3] { + assert_eq!(check(&raw_frame(b"x", 1, bit, None), 1), FAIL, "{bit}"); + } + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn a_raw_frame_passes() { + assert_eq!(check(&raw_frame(b"hello", 5, 0, None), 5), Ok(())); + assert_eq!(check(&raw_frame(b"", 0, 0, None), 0), Ok(())); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn the_content_size_must_be_declared_and_equal() { + let frame = raw_frame(b"hello", 5, 0, None); + assert_eq!(check(&frame, 4), FAIL); + assert_eq!(check(&frame, 6), FAIL); + // No content size: descriptor 0 and a window descriptor. + let mut no_size = ZSTD_MAGIC.to_vec(); + no_size.extend_from_slice(&[0x00, 0x00, 0x29, 0, 0]); + no_size.extend_from_slice(b"hello"); + assert_eq!(check(&no_size, 5), FAIL); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn exactly_one_frame_and_nothing_after_it() { + let frame = raw_frame(b"hello", 5, 0, None); + let mut two = frame.clone(); + two.extend_from_slice(&frame); + assert_eq!(check(&two, 5), FAIL); + let mut trailing = frame.clone(); + trailing.push(0); + assert_eq!(check(&trailing, 5), FAIL); + let mut skippable_after = frame.clone(); + skippable_after.extend_from_slice(&0x184D_2A50_u32.to_le_bytes()); + skippable_after.extend_from_slice(&0u32.to_le_bytes()); + assert_eq!(check(&skippable_after, 5), FAIL); + assert_eq!(check(&frame[..frame.len() - 1], 5), FAIL, "truncated"); + } + + #[test] + fn content_size_flags_are_the_shortest_field() { + assert_eq!(fcs_flag(0, true), 0); + assert_eq!(fcs_flag(255, true), 0); + assert_eq!(fcs_flag(255, false), 2, "one byte only in a single segment"); + assert_eq!(fcs_flag(256, true), 1); + assert_eq!(fcs_flag(65_791, false), 1); + assert_eq!(fcs_flag(65_792, true), 2); + assert_eq!(fcs_flag(0xFFFF_FFFE, true), 2); + assert_eq!(fcs_flag(0xFFFF_FFFF, true), 3); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn a_content_size_field_wider_than_needed_fails() { + // Each of these decodes with libzstd 1.5.7. + for flag in [2, 3] { + let frame = sized_frame(b"hello", 5, flag, 0, None); + let mut out = [0u8; 5]; + assert_eq!(zstd_safe::decompress(&mut out[..], &frame), Ok(5), "{flag}"); + assert_eq!(check(&frame, 5), FAIL, "{flag}"); + } + let long = vec![b'a'; 300]; + assert_eq!(check(&sized_frame(&long, 300, 1, 0, None), 300), Ok(())); + assert_eq!(check(&sized_frame(&long, 300, 2, 0, None), 300), FAIL); + let windowed = sized_frame(b"hello", 5, 3, 0, Some(10 << 3)); + assert_eq!(check(&windowed, 5), FAIL); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn the_unused_bit_fails_although_libzstd_ignores_it() { + let frame = raw_frame(b"hello", 5, UNUSED, None); + let mut out = [0u8; 5]; + assert_eq!(zstd_safe::decompress(&mut out[..], &frame), Ok(5)); + assert_eq!(check(&frame, 5), FAIL); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn the_window_is_at_most_one_mib() { + let at_cap = raw_frame(b"hello", 5, 0, Some(10 << 3)); + assert_eq!(check(&at_cap, 5), Ok(())); + let over = raw_frame(b"hello", 5, 0, Some(10 << 3 | 1)); + assert_eq!(check(&over, 5), FAIL); + let double = raw_frame(b"hello", 5, 0, Some(11 << 3)); + assert_eq!(check(&double, 5), FAIL); + } +} diff --git a/crates/engine/core/src/compress/keep_compressed.rs b/crates/engine/core/src/compress/keep_compressed.rs new file mode 100644 index 0000000..31d6af8 --- /dev/null +++ b/crates/engine/core/src/compress/keep_compressed.rs @@ -0,0 +1,35 @@ +//! The store-raw rule (FS-53). + +/// Whether a zstd frame of `frame_len` bytes is kept for a chunk of `plain_len` bytes: only if +/// `16 × frame_len ≤ 15 × plain_len`, so compression saves at least 1/16. Otherwise the chunk is +/// stored raw (FS-53). +/// +/// ``` +/// use crypthix_core::compress::keep_compressed; +/// +/// assert!(keep_compressed(15, 16)); +/// assert!(!keep_compressed(16, 16)); +/// ``` +#[must_use] +pub fn keep_compressed(frame_len: u64, plain_len: u64) -> bool { + // In u128, so no length can overflow. + u128::from(frame_len) * 16 <= u128::from(plain_len) * 15 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_boundary_is_fifteen_sixteenths() { + assert!(keep_compressed(960, 1_024)); + assert!(!keep_compressed(961, 1_024)); + assert!(keep_compressed(983_040, 1 << 20)); + assert!(!keep_compressed(983_041, 1 << 20)); + assert!(keep_compressed(0, 0), "an empty frame of nothing"); + assert!(!keep_compressed(9, 0)); + // Lengths whose products pass u64::MAX. + assert!(keep_compressed(15 << 59, 1 << 63)); + assert!(!keep_compressed((15 << 59) + 1, 1 << 63)); + } +} diff --git a/crates/engine/core/src/compress/mod.rs b/crates/engine/core/src/compress/mod.rs new file mode 100644 index 0000000..9055bb0 --- /dev/null +++ b/crates/engine/core/src/compress/mod.rs @@ -0,0 +1,24 @@ +//! zstd per chunk (FS-53): one frame at level 3 with its content size, no checksum, no +//! dictionary ID and a window of at most 1 MiB, kept only if it saves at least 1/16 of the +//! chunk; never for objects of the secret class (T-40). +//! +//! zstd's working memory is on the C heap, outside protected memory (R-26): it is not wiped when +//! a context is freed, not locked, so it can be swapped out, and not `MADV_DONTFORK`, so a forked +//! child gets a copy. It holds pieces of chunk plaintext: the compression context keeps literals +//! and match-finder tables, and the decompression context keeps decoded literals (its +//! `litExtraBuffer`) and any output it buffers. zstd-safe offers no way to give it a caller's +//! buffer without `unsafe`, which this crate does not use; the encrypt pipeline item plans a +//! `ZSTD_customMem` allocator backed by `secure_mem` in `crypthix-crypto`, which may use +//! `unsafe`. Contexts are reused, so until then it is a bounded residual like the cipher state +//! inside `crypthix-crypto`. + +mod compress_error; +mod compressor; +mod decompressor; +mod frame_check; +mod keep_compressed; + +pub use compress_error::CompressError; +pub use compressor::Compressor; +pub use decompressor::Decompressor; +pub use keep_compressed::keep_compressed; diff --git a/crates/engine/core/src/error/mod.rs b/crates/engine/core/src/error/mod.rs new file mode 100644 index 0000000..15c46b8 --- /dev/null +++ b/crates/engine/core/src/error/mod.rs @@ -0,0 +1,7 @@ +//! The errors of the write and read paths. + +mod read_error; +mod write_error; + +pub use read_error::ReadError; +pub use write_error::WriteError; diff --git a/crates/engine/core/src/error/read_error.rs b/crates/engine/core/src/error/read_error.rs new file mode 100644 index 0000000..9bf25f1 --- /dev/null +++ b/crates/engine/core/src/error/read_error.rs @@ -0,0 +1,155 @@ +//! Why a chunk or meta blob did not open. + +use std::error::Error; +use std::fmt; + +use crypthix_crypto::cx_aead::OpenError; +use crypthix_crypto::key::KeyError; +use crypthix_crypto::secure_mem::MemError; +use crypthix_types::format_error::FormatError; + +use crate::compress::CompressError; + +/// A blob did not open: it breaks a format rule, there was no protected memory for its +/// plaintext, zstd itself failed, or a key could not be derived. +/// +/// A blob that is not what its reference says is always [`ReadError::Format`], with the first +/// failing check of FS-93: `Decompress`, `Decrypt`, `Padding`, `Limit` or `Binding`. A frame +/// that does not decode is such a check, `FormatError::Decompress`; [`ReadError::Zstd`] is zstd +/// failing for a reason of its own. The kinds other than `Format` depend only on the reader's +/// own resources, so they never look like tampering. +/// +/// The failure of a [`KeyError`], as from [`ChunkKeys::derive`](crate::blob::ChunkKeys::derive), +/// converts with `?`: its `Format` and `Memory` kinds to the same kinds here, anything else to +/// [`ReadError::Key`]. +#[non_exhaustive] +#[must_use] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub enum ReadError { + /// The blob breaks a format rule (section 19). + Format(FormatError), + /// No protected memory for the plaintext (O1). + Memory(MemError), + /// zstd itself failed: it could not make or reset a decompression context, ran out of + /// memory while decoding, or is not the libzstd version FS-53 pins + /// ([`CompressError::Version`]). Not a format error: it depends on the reader, not on the + /// frame. Named like [`WriteError::Zstd`](crate::error::WriteError::Zstd). + Zstd(CompressError), + /// A key could not be derived for a reason neither `Format` nor `Memory` names. + Key(KeyError), +} + +impl fmt::Display for ReadError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + ReadError::Format(_) => "the blob did not open", + ReadError::Memory(_) => "no protected memory for the plaintext", + ReadError::Zstd(_) => "zstd failed", + ReadError::Key(_) => "a key could not be derived", + }) + } +} + +impl Error for ReadError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + ReadError::Format(error) => Some(error), + ReadError::Memory(error) => Some(error), + ReadError::Zstd(error) => Some(error), + ReadError::Key(error) => Some(error), + } + } +} + +impl From for ReadError { + fn from(error: FormatError) -> Self { + ReadError::Format(error) + } +} + +impl From for ReadError { + fn from(error: MemError) -> Self { + ReadError::Memory(error) + } +} + +impl From for ReadError { + fn from(error: OpenError) -> Self { + match error { + OpenError::Format(error) => ReadError::Format(error), + OpenError::Memory(error) => ReadError::Memory(error), + // A kind added later is still a failed open; the opaque `Decrypt` reveals nothing. + _ => ReadError::Format(FormatError::Decrypt), + } + } +} + +impl From for ReadError { + fn from(error: KeyError) -> Self { + match error { + KeyError::Format(error) => ReadError::Format(error), + KeyError::Memory(error) => ReadError::Memory(error), + other => ReadError::Key(other), + } + } +} + +#[cfg(test)] +mod tests { + use crypthix_crypto::random::RandomError; + + use super::*; + + #[test] + fn display_names_the_kind_and_source_is_the_cause() { + let cases: [(ReadError, &dyn Error); 4] = [ + (FormatError::Binding.into(), &FormatError::Binding), + (MemError::MapFailed.into(), &MemError::MapFailed), + ( + ReadError::Zstd(CompressError::Context), + &CompressError::Context, + ), + ( + ReadError::Key(KeyError::Random(RandomError)), + &KeyError::Random(RandomError), + ), + ]; + let mut messages = Vec::new(); + for (error, cause) in cases { + let source = error.source().expect("every variant wraps its cause"); + assert_eq!(source.to_string(), cause.to_string()); + messages.push(error.to_string()); + } + messages.sort(); + messages.dedup(); + assert_eq!(messages.len(), 4, "two kinds share a message"); + } + + #[test] + fn a_key_error_keeps_its_kind() { + assert_eq!( + ReadError::from(KeyError::Format(FormatError::ZeroValue)), + ReadError::Format(FormatError::ZeroValue) + ); + assert_eq!( + ReadError::from(KeyError::Memory(MemError::MapFailed)), + ReadError::Memory(MemError::MapFailed) + ); + assert_eq!( + ReadError::from(KeyError::Random(RandomError)), + ReadError::Key(KeyError::Random(RandomError)) + ); + } + + #[test] + fn an_open_error_keeps_its_kind() { + assert_eq!( + ReadError::from(OpenError::Format(FormatError::Decrypt)), + ReadError::Format(FormatError::Decrypt) + ); + assert_eq!( + ReadError::from(OpenError::Memory(MemError::MapFailed)), + ReadError::Memory(MemError::MapFailed) + ); + } +} diff --git a/crates/engine/core/src/error/write_error.rs b/crates/engine/core/src/error/write_error.rs new file mode 100644 index 0000000..d289f1a --- /dev/null +++ b/crates/engine/core/src/error/write_error.rs @@ -0,0 +1,152 @@ +//! Why a chunk or meta blob was not written. + +use std::error::Error; +use std::fmt; + +use crypthix_crypto::cx_aead::SealError; +use crypthix_crypto::key::KeyError; +use crypthix_crypto::random::RandomError; +use crypthix_crypto::secure_mem::MemError; +use crypthix_types::format_error::FormatError; + +use crate::compress::CompressError; + +/// Nothing was written: no protected memory, no randomness, a failed seal or compression, or +/// input that breaks a format rule. +/// +/// A zstd failure is always reported here, never answered by storing the chunk uncompressed, +/// so a broken compressor cannot change what is written behind the caller's back. +/// +/// The failure of a [`KeyError`], as from [`ChunkKeys::derive`](crate::blob::ChunkKeys::derive), +/// converts with `?`: its `Random`, `Memory` and `Format` kinds to the same kinds here, anything +/// else to [`WriteError::Key`]. +#[non_exhaustive] +#[must_use] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub enum WriteError { + /// No protected memory for a plaintext buffer or a key (O1). + Memory(MemError), + /// The kernel could not supply a random blob ID (FS-01). + Random(RandomError), + /// The CX-AEAD seal failed. + Seal(SealError), + /// zstd itself failed (FS-53): it could not make a context, refused a parameter, failed + /// to compress, or is not the libzstd version FS-53 pins. Named like + /// [`ReadError::Zstd`](crate::error::ReadError::Zstd). + Zstd(CompressError), + /// The input breaks a format rule: `Limit` for a chunk or payload over 1 MiB, `ZeroValue` + /// for an all-zero ID. + Format(FormatError), + /// A key could not be derived for a reason none of `Random`, `Memory` and `Format` names. + Key(KeyError), +} + +impl fmt::Display for WriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + WriteError::Memory(_) => "no protected memory to write the chunk", + WriteError::Random(_) => "no randomness for a blob ID", + WriteError::Seal(_) => "the blob could not be sealed", + WriteError::Zstd(_) => "zstd failed", + WriteError::Format(_) => "the input breaks a format rule", + WriteError::Key(_) => "a key could not be derived", + }) + } +} + +impl Error for WriteError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + WriteError::Memory(error) => Some(error), + WriteError::Random(error) => Some(error), + WriteError::Seal(error) => Some(error), + WriteError::Zstd(error) => Some(error), + WriteError::Format(error) => Some(error), + WriteError::Key(error) => Some(error), + } + } +} + +impl From for WriteError { + fn from(error: MemError) -> Self { + WriteError::Memory(error) + } +} + +impl From for WriteError { + fn from(error: RandomError) -> Self { + WriteError::Random(error) + } +} + +impl From for WriteError { + fn from(error: SealError) -> Self { + WriteError::Seal(error) + } +} + +impl From for WriteError { + fn from(error: CompressError) -> Self { + WriteError::Zstd(error) + } +} + +impl From for WriteError { + fn from(error: FormatError) -> Self { + WriteError::Format(error) + } +} + +impl From for WriteError { + fn from(error: KeyError) -> Self { + match error { + KeyError::Random(error) => WriteError::Random(error), + KeyError::Memory(error) => WriteError::Memory(error), + KeyError::Format(error) => WriteError::Format(error), + other => WriteError::Key(other), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn display_names_the_kind_and_source_is_the_cause() { + let key = KeyError::Random(RandomError); + let cases: [(WriteError, &dyn Error); 6] = [ + (MemError::MapFailed.into(), &MemError::MapFailed), + (RandomError.into(), &RandomError), + (SealError::TooLong.into(), &SealError::TooLong), + (CompressError::Context.into(), &CompressError::Context), + (FormatError::Limit.into(), &FormatError::Limit), + (WriteError::Key(key), &key), + ]; + let mut messages = Vec::new(); + for (error, cause) in cases { + let source = error.source().expect("every variant wraps its cause"); + assert_eq!(source.to_string(), cause.to_string()); + messages.push(error.to_string()); + } + messages.sort(); + messages.dedup(); + assert_eq!(messages.len(), 6, "two kinds share a message"); + } + + #[test] + fn a_key_error_keeps_its_kind() { + assert_eq!( + WriteError::from(KeyError::Random(RandomError)), + WriteError::Random(RandomError) + ); + assert_eq!( + WriteError::from(KeyError::Memory(MemError::MapFailed)), + WriteError::Memory(MemError::MapFailed) + ); + assert_eq!( + WriteError::from(KeyError::Format(FormatError::ZeroValue)), + WriteError::Format(FormatError::ZeroValue) + ); + } +} diff --git a/crates/engine/core/src/inner/comp.rs b/crates/engine/core/src/inner/comp.rs new file mode 100644 index 0000000..a53be70 --- /dev/null +++ b/crates/engine/core/src/inner/comp.rs @@ -0,0 +1,50 @@ +//! The compression code of an inner plaintext (FS-54). + +/// How a chunk's payload is stored (FS-53, FS-54). +#[non_exhaustive] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub enum Comp { + /// Code 0: the chunk's own bytes, uncompressed. + Raw, + /// Code 1: one zstd frame of the chunk. + Zstd, +} + +impl Comp { + /// The byte stored in the inner plaintext. + #[must_use] + pub const fn code(self) -> u8 { + match self { + Comp::Raw => 0, + Comp::Zstd => 1, + } + } + + /// The compression a stored byte names; `None` for any byte but 0 and 1, which a reader + /// rejects as `Padding` (FS-54). + #[must_use] + pub const fn from_code(code: u8) -> Option { + match code { + 0 => Some(Comp::Raw), + 1 => Some(Comp::Zstd), + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codes_round_trip_and_nothing_else_is_known() { + for comp in [Comp::Raw, Comp::Zstd] { + assert_eq!(Comp::from_code(comp.code()), Some(comp)); + } + assert_eq!(Comp::Raw.code(), 0); + assert_eq!(Comp::Zstd.code(), 1); + for code in 2..=u8::MAX { + assert_eq!(Comp::from_code(code), None, "{code}"); + } + } +} diff --git a/crates/engine/core/src/inner/decode_inner.rs b/crates/engine/core/src/inner/decode_inner.rs new file mode 100644 index 0000000..891b852 --- /dev/null +++ b/crates/engine/core/src/inner/decode_inner.rs @@ -0,0 +1,173 @@ +//! Checking an inner plaintext (FS-54). + +use crypthix_types::format_error::FormatError; + +use crate::inner::{Comp, InnerView}; +use crate::limits::{INNER_HEADER_LEN, MAX_PAYLOAD_LEN}; +use crate::pad::padme; + +/// Checks an opened inner plaintext and returns its compression and payload (FS-54). +/// +/// The checks run in this order, and the first failure is the error (FS-93): +/// 1. at least the 6 header bytes (`Padding`); +/// 2. `comp` is 0 or 1 (`Padding`); +/// 3. `rsv` is 0 (`Padding`); +/// 4. `payload_len` is at most 1 MiB (`Limit`), before its length is used for anything; +/// 5. the total length is exactly `padme(6 + payload_len)` (`Padding`); +/// 6. every pad byte is zero (`Padding`). +/// +/// # Errors +/// +/// [`FormatError::Padding`] or [`FormatError::Limit`] as above. +pub fn decode_inner(inner: &[u8]) -> Result, FormatError> { + let Some((header, rest)) = inner.split_first_chunk::() else { + return Err(FormatError::Padding); + }; + let [code, rsv, len @ ..] = *header; + let comp = Comp::from_code(code).ok_or(FormatError::Padding)?; + if rsv != 0 { + return Err(FormatError::Padding); + } + let payload_len = u64::from(u32::from_be_bytes(len)); + if payload_len > MAX_PAYLOAD_LEN { + return Err(FormatError::Limit); + } + // At most 6 + 2^20, so the sum and its Padmé length always fit. + let expected = padme(payload_len + INNER_HEADER_LEN as u64); + if expected != Some(inner.len() as u64) { + return Err(FormatError::Padding); + } + let payload_len = usize::try_from(payload_len).map_err(|_| FormatError::Limit)?; + let (payload, pad) = rest + .split_at_checked(payload_len) + .ok_or(FormatError::Padding)?; + if pad.iter().any(|byte| *byte != 0) { + return Err(FormatError::Padding); + } + Ok(InnerView::new(comp, payload)) +} + +#[cfg(test)] +mod tests { + use proptest::collection::vec; + use proptest::prelude::{any, prop_assert_eq, proptest}; + + use super::*; + use crate::inner::encode_inner; + + /// A well-formed inner plaintext of `payload_len` bytes of 0x55, as plain bytes. + fn inner(comp: u8, payload_len: usize) -> Vec { + let total = padme(payload_len as u64 + 6).expect("fits"); + let mut bytes = vec![0u8; usize::try_from(total).expect("fits")]; + bytes[0] = comp; + let len = u32::try_from(payload_len).expect("fits"); + bytes[2..6].copy_from_slice(&len.to_be_bytes()); + bytes[6..6 + payload_len].fill(0x55); + bytes + } + + #[test] + fn a_well_formed_inner_plaintext_decodes() { + let bytes = inner(1, 1_000); + let view = decode_inner(&bytes).expect("well formed"); + assert_eq!(view.comp(), Comp::Zstd); + assert_eq!(view.payload(), &[0x55; 1_000]); + } + + #[test] + fn short_input_is_padding() { + for len in 0..6 { + assert_eq!( + decode_inner(&vec![0; len]).map(|_| ()), + Err(FormatError::Padding) + ); + } + assert!(decode_inner(&[0; 6]).is_ok(), "an empty payload is fine"); + } + + #[test] + fn unknown_comp_and_reserved_byte_are_padding() { + let mut bytes = inner(2, 10); + assert_eq!(decode_inner(&bytes).map(|_| ()), Err(FormatError::Padding)); + bytes[0] = 0; + bytes[1] = 1; + assert_eq!(decode_inner(&bytes).map(|_| ()), Err(FormatError::Padding)); + } + + #[test] + fn payload_len_is_capped_at_one_mib_before_the_length_check() { + let mut header = vec![0u8, 0]; + header.extend_from_slice(&(1u32 << 20).to_be_bytes()); + // Exactly 2^20 is allowed: only the length is wrong here. + assert_eq!(decode_inner(&header).map(|_| ()), Err(FormatError::Padding)); + header[2..6].copy_from_slice(&((1u32 << 20) + 1).to_be_bytes()); + assert_eq!(decode_inner(&header).map(|_| ()), Err(FormatError::Limit)); + header[2..6].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(decode_inner(&header).map(|_| ()), Err(FormatError::Limit)); + // A bad comp code is found first. + header[0] = 9; + assert_eq!(decode_inner(&header).map(|_| ()), Err(FormatError::Padding)); + } + + #[test] + #[cfg_attr(miri, ignore = "megabyte buffers are slow under Miri")] + fn a_full_one_mib_payload_decodes() { + let bytes = inner(0, 1 << 20); + let view = decode_inner(&bytes).expect("2^20 is allowed"); + assert_eq!(view.payload().len(), 1 << 20); + } + + #[test] + fn the_length_must_be_exactly_padme() { + let bytes = inner(0, 1_000); + assert_eq!(bytes.len(), 1_024); + let mut longer = bytes.clone(); + longer.push(0); + assert_eq!(decode_inner(&longer).map(|_| ()), Err(FormatError::Padding)); + assert_eq!( + decode_inner(&bytes[..1_023]).map(|_| ()), + Err(FormatError::Padding) + ); + // Unpadded: header and payload alone. + assert_eq!( + decode_inner(&bytes[..1_006]).map(|_| ()), + Err(FormatError::Padding) + ); + } + + #[test] + fn every_pad_byte_must_be_zero() { + let bytes = inner(0, 1_000); + for at in [1_006, 1_015, 1_023] { + let mut bad = bytes.clone(); + bad[at] = 1; + assert_eq!( + decode_inner(&bad).map(|_| ()), + Err(FormatError::Padding), + "{at}" + ); + } + } + + proptest! { + #[test] + #[cfg_attr(miri, ignore = "proptest is slow under Miri")] + fn encode_then_decode_round_trips(payload in vec(any::(), 0..5_000), zstd in any::()) { + let comp = if zstd { Comp::Zstd } else { Comp::Raw }; + let encoded = encode_inner(comp, &payload).expect("encodes"); + prop_assert_eq!(encoded.len() as u64, padme(payload.len() as u64 + 6).expect("fits")); + let view = decode_inner(&encoded).expect("decodes"); + prop_assert_eq!(view.comp(), comp); + prop_assert_eq!(view.payload(), payload.as_slice()); + } + + #[test] + #[cfg_attr(miri, ignore = "proptest is slow under Miri")] + fn decoding_never_panics_and_accepts_only_its_own_encoding(bytes in vec(any::(), 0..300)) { + if let Ok(view) = decode_inner(&bytes) { + let encoded = encode_inner(view.comp(), view.payload()).expect("encodes"); + prop_assert_eq!(encoded.as_slice(), bytes.as_slice()); + } + } + } +} diff --git a/crates/engine/core/src/inner/encode_inner.rs b/crates/engine/core/src/inner/encode_inner.rs new file mode 100644 index 0000000..34925a5 --- /dev/null +++ b/crates/engine/core/src/inner/encode_inner.rs @@ -0,0 +1,86 @@ +//! Building an inner plaintext (FS-54). + +use crypthix_crypto::secure_mem::SecretBuf; +use crypthix_types::format_error::FormatError; + +use crate::error::WriteError; +use crate::inner::Comp; +use crate::limits::{INNER_HEADER_LEN, MAX_PAYLOAD_LEN}; +use crate::pad::padme; + +/// The inner plaintext of `payload`: `comp ‖ 0 ‖ u32be(len) ‖ payload ‖ zero pad`, padded to +/// `padme(6 + len)` bytes (FS-54), in a new buffer of protected memory. +/// +/// ``` +/// use crypthix_core::inner::{self, Comp}; +/// +/// let inner = inner::encode_inner(Comp::Raw, b"chunk")?; +/// assert_eq!(inner.len(), 12); +/// assert_eq!(&inner[..6], &[0, 0, 0, 0, 0, 5]); +/// let view = inner::decode_inner(&inner)?; +/// assert_eq!(view.payload(), b"chunk"); +/// # Ok::<(), Box>(()) +/// ``` +/// +/// # Errors +/// +/// - [`WriteError::Format`] with `Limit` if `payload` is longer than 1 MiB. +/// - [`WriteError::Memory`] if protected memory cannot be allocated for the result. +pub fn encode_inner(comp: Comp, payload: &[u8]) -> Result { + let payload_len = payload.len() as u64; + if payload_len > MAX_PAYLOAD_LEN { + return Err(FormatError::Limit.into()); + } + let header_len = u32::try_from(payload.len()).map_err(|_| FormatError::Limit)?; + let total = padme(payload_len + INNER_HEADER_LEN as u64) + .and_then(|total| usize::try_from(total).ok()) + .ok_or(FormatError::Limit)?; + let mut inner = SecretBuf::try_zeroed(total)?; + // `padme(6 + len) >= 6 + len`, so both splits succeed; failing instead keeps this + // panic-free. + let (header, rest) = inner + .as_mut_slice() + .split_first_chunk_mut::() + .ok_or(FormatError::Limit)?; + let [code, rsv, len @ ..] = header; + *code = comp.code(); + *rsv = 0; + *len = header_len.to_be_bytes(); + rest.get_mut(..payload.len()) + .ok_or(FormatError::Limit)? + .copy_from_slice(payload); + Ok(inner) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layout_is_header_payload_then_zero_pad() { + let inner = encode_inner(Comp::Zstd, &[0xAB; 1_000]).expect("encodes"); + assert_eq!(inner.len(), 1_024); + assert_eq!(&inner[..6], &[1, 0, 0, 0, 0x03, 0xE8]); + assert!(inner[6..1_006].iter().all(|byte| *byte == 0xAB)); + assert!(inner[1_006..].iter().all(|byte| *byte == 0)); + } + + #[test] + fn an_empty_payload_is_just_the_header() { + let inner = encode_inner(Comp::Raw, &[]).expect("encodes"); + assert_eq!(inner.as_slice(), &[0; 6]); + } + + #[test] + #[cfg_attr(miri, ignore = "megabyte buffers are slow under Miri")] + fn payloads_up_to_one_mib_and_no_longer() { + let largest = vec![7u8; 1 << 20]; + let inner = encode_inner(Comp::Raw, &largest).expect("1 MiB is allowed"); + assert_eq!(inner.len(), (1 << 20) + (1 << 15)); + let over = vec![7u8; (1 << 20) + 1]; + assert_eq!( + encode_inner(Comp::Raw, &over).map(|_| ()), + Err(WriteError::Format(FormatError::Limit)) + ); + } +} diff --git a/crates/engine/core/src/inner/inner_view.rs b/crates/engine/core/src/inner/inner_view.rs new file mode 100644 index 0000000..bd80202 --- /dev/null +++ b/crates/engine/core/src/inner/inner_view.rs @@ -0,0 +1,53 @@ +//! A decoded inner plaintext, borrowed from the opened blob. + +use std::fmt; + +use crate::inner::Comp; + +/// The checked fields of an inner plaintext (FS-54), borrowing its payload. +#[derive(Clone, Copy)] +pub struct InnerView<'a> { + comp: Comp, + payload: &'a [u8], +} + +impl<'a> InnerView<'a> { + /// A view of checked fields. + pub(crate) const fn new(comp: Comp, payload: &'a [u8]) -> Self { + Self { comp, payload } + } + + /// How the payload is stored. + #[must_use] + pub const fn comp(&self) -> Comp { + self.comp + } + + /// The payload: the chunk itself, or one zstd frame of it. + #[must_use] + pub const fn payload(&self) -> &'a [u8] { + self.payload + } +} + +/// Prints the compression and length only: the payload is plaintext. +impl fmt::Debug for InnerView<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("InnerView") + .field("comp", &self.comp) + .field("payload_len", &self.payload.len()) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn debug_shows_no_payload() { + let view = InnerView::new(Comp::Raw, b"secret"); + let text = format!("{view:?}"); + assert_eq!(text, "InnerView { comp: Raw, payload_len: 6 }"); + } +} diff --git a/crates/engine/core/src/inner/mod.rs b/crates/engine/core/src/inner/mod.rs new file mode 100644 index 0000000..4f0ae03 --- /dev/null +++ b/crates/engine/core/src/inner/mod.rs @@ -0,0 +1,12 @@ +//! The inner plaintext of a data blob: `comp ‖ rsv ‖ u32be payload_len ‖ payload ‖ zero pad`, +//! padded to its Padmé length (FS-54). + +mod comp; +mod decode_inner; +mod encode_inner; +mod inner_view; + +pub use comp::Comp; +pub use decode_inner::decode_inner; +pub use encode_inner::encode_inner; +pub use inner_view::InnerView; diff --git a/crates/engine/core/src/lib.rs b/crates/engine/core/src/lib.rs index 74ef3ee..3b075a9 100644 --- a/crates/engine/core/src/lib.rs +++ b/crates/engine/core/src/lib.rs @@ -1 +1,73 @@ //! Write and read pipeline: chunk, compress, pad, encrypt, hash and sign. +//! +//! This crate holds the first stage of the data path, in the fixed order of FS-51: chunk → +//! compress → pad → encrypt. Packs, shards, manifests and the trees come later. +//! +//! - [`chunk`]: FastCDC 2020 with a secret per-vault gear table, 64 KiB / 256 KiB / 1 MiB, for +//! ordinary objects, and fixed 1 MiB chunks for secret-class objects (FS-52), over memory +//! ([`Chunks`](chunk::Chunks)) or a reader ([`StreamChunker`](chunk::StreamChunker)); +//! - [`compress`]: one zstd frame per chunk, kept only if it saves 1/16, never for the secret +//! class, and checked strictly before it is decoded (FS-53); +//! - [`pad`] and [`inner`]: the inner plaintext `comp ‖ rsv ‖ payload_len ‖ payload`, padded +//! with Padmé (FS-54); +//! - [`blob`]: data blobs sealed under `K_chunk` with keyed or random blob IDs (FS-55, FS-56) +//! and meta blobs sealed under their epoch's key (FS-57). +//! +//! Plaintext, compressed chunks and inner plaintexts live only in fixed-size +//! [`SecretBuf`](crypthix_crypto::secure_mem::SecretBuf)s of protected memory; a `Vec` holds +//! only ciphertext. Two residuals remain: zstd's working memory is on the C heap, not wiped, +//! locked or kept from forked children (see [`compress`], R-26), and the gear table, kept in a +//! `SecretBuf` rather than secret pages, is assumed to leak, since keyed chunkers have been +//! attacked from observed chunk sizes; Padmé only coarsens those sizes and packs hide them +//! (T-84). +//! +//! Errors are [`WriteError`](error::WriteError) and [`ReadError`](error::ReadError). A blob +//! that does not match what refers to it is always a +//! [`FormatError`](crypthix_types::format_error::FormatError), the first failing check of +//! FS-93; running out of memory, a zstd failure of its own and a libzstd other than the pinned +//! version are reported apart, so they never look like tampering. +//! +//! ``` +//! use crypthix_core::blob::{ChunkKeys, ObjectClass, ObjectOpener, ObjectSealer}; +//! use crypthix_core::blob::BlobContext; +//! use crypthix_core::chunk::{Chunks, GearTable}; +//! use crypthix_core::compress::{Compressor, Decompressor}; +//! use crypthix_crypto::key::KdfKey; +//! use crypthix_crypto::random; +//! use crypthix_types::id::{DekId, ObjectId, VaultId}; +//! +//! let vault_id = VaultId::try_from_bytes(random::bytes()?)?; +//! let gear = GearTable::derive(&KdfKey::random()?, &vault_id)?; +//! let context = BlobContext::new( +//! vault_id, +//! ObjectId::try_from_bytes(random::bytes()?)?, +//! DekId::try_from_bytes(random::bytes()?)?, +//! ); +//! let keys = ChunkKeys::derive(&KdfKey::random()?, &random::bytes()?, context)?; +//! +//! let file = b"some file contents ".repeat(20_000); +//! let chunks = Chunks::new(&gear, ObjectClass::Ordinary, &file); +//! // The writer takes the class and chunk count from the chunker, the reader from the manifest. +//! let sealer = ObjectSealer::new(&keys, chunks.object_shape()); +//! let ranges: Vec<_> = chunks.collect(); +//! let opener = ObjectOpener::new(&keys, ObjectClass::Ordinary, ranges.len() as u64); +//! let mut compressor = Compressor::new()?; +//! let mut decompressor = Decompressor::new(); +//! for range in ranges { +//! let chunk = &file[range]; +//! let sealed = sealer.seal(&mut compressor, chunk)?; +//! let opened = opener.open(&mut decompressor, sealed.entry(), sealed.sealed())?; +//! assert_eq!(opened.as_slice(), chunk); +//! } +//! # Ok::<(), Box>(()) +//! ``` + +pub mod blob; +pub mod chunk; +pub mod compress; +pub mod error; +pub mod inner; +pub mod limits; +pub mod pad; +#[cfg(test)] +mod test_data; diff --git a/crates/engine/core/src/limits.rs b/crates/engine/core/src/limits.rs new file mode 100644 index 0000000..5a1e9e2 --- /dev/null +++ b/crates/engine/core/src/limits.rs @@ -0,0 +1,50 @@ +//! The fixed sizes and parameters of the data path (format spec 10.1 to 10.3). + +/// The smallest chunk FastCDC cuts, 64 KiB (FS-52). Only an object's last chunk, or the one +/// chunk of an object smaller than this, may be shorter. +pub const MIN_CHUNK: usize = 64 * 1024; + +/// The average chunk size FastCDC aims for, 256 KiB (FS-52). +pub const AVG_CHUNK: usize = 256 * 1024; + +/// The largest chunk FastCDC cuts, 1 MiB (FS-52). +pub const MAX_CHUNK: usize = 1024 * 1024; + +/// The largest `plain_len` of a chunk a reader accepts, 1 MiB (FS-11, FS-53); above it the +/// chunk is `Decompress` before anything is decrypted or allocated. +pub const MAX_PLAIN_LEN: u64 = 1 << 20; + +/// The largest `payload_len` of an inner plaintext, 1 MiB (FS-54); above it the inner plaintext +/// is `Limit`. +pub const MAX_PAYLOAD_LEN: u64 = 1 << 20; + +/// Bytes of the inner plaintext header: `comp ‖ rsv ‖ u32be payload_len` (FS-54). +pub const INNER_HEADER_LEN: usize = 6; + +/// The zstd compression level (FS-53). +pub const ZSTD_LEVEL: i32 = 3; + +/// The largest zstd window, as a base-2 logarithm: 1 MiB (FS-53). +pub const WINDOW_LOG: u32 = 20; + +/// The libzstd version FS-53 pins, as `ZSTD_versionNumber` gives it: 1.5.7. +/// +/// zstd output is not guaranteed to be the same across versions, so the encoder is only known +/// to match the test vectors under this one; any version decodes them. +pub const ZSTD_VERSION: u32 = 10_507; + +/// Bytes of the gear table: 256 little-endian `u64` words (FS-52). +pub const GEAR_TABLE_LEN: usize = 2048; + +const _: () = { + assert!( + MAX_CHUNK as u64 == MAX_PLAIN_LEN, + "a chunk and its plain_len share one cap" + ); + assert!( + MIN_CHUNK.is_multiple_of(2) && AVG_CHUNK.is_multiple_of(2) && MAX_CHUNK.is_multiple_of(2), + "FastCDC cuts two bytes at a time" + ); + assert!(MIN_CHUNK < AVG_CHUNK && AVG_CHUNK < MAX_CHUNK); + assert!(1 << WINDOW_LOG == MAX_PLAIN_LEN); +}; diff --git a/crates/engine/core/src/pad/mod.rs b/crates/engine/core/src/pad/mod.rs new file mode 100644 index 0000000..d819ee9 --- /dev/null +++ b/crates/engine/core/src/pad/mod.rs @@ -0,0 +1,5 @@ +//! Padmé padding of inner plaintexts (FS-54). + +mod padme; + +pub use padme::padme; diff --git a/crates/engine/core/src/pad/padme.rs b/crates/engine/core/src/pad/padme.rs new file mode 100644 index 0000000..6153380 --- /dev/null +++ b/crates/engine/core/src/pad/padme.rs @@ -0,0 +1,94 @@ +//! Padmé (Nikitin et al., PETS 2019), the padding of every inner plaintext (FS-54). + +/// The Padmé length of `len`: for `len ≥ 2`, with `E = ⌊log2 len⌋`, `S = ⌊log2 E⌋ + 1` and +/// `z = E − S`, `len` rounded up to a multiple of `2^z`; `len` itself below 2. +/// +/// The result is at most 12% above `len` and leaks O(log log n) bits of it. Only integer +/// logarithms are used, so there is no rounding and no special case beyond `len < 2`. +/// +/// ``` +/// use crypthix_core::pad::padme; +/// +/// assert_eq!(padme(9), Some(10)); +/// assert_eq!(padme(6 + 1_000), Some(1_024)); +/// ``` +/// +/// Returns `None` only when the rounded length does not fit in a `u64`, for `len` within +/// `2^57` of `u64::MAX`. +#[must_use] +pub const fn padme(len: u64) -> Option { + if len < 2 { + return Some(len); + } + let e = len.ilog2(); + let s = e.ilog2() + 1; + let z = e - s; + let mask = (1u64 << z) - 1; + match len.checked_add(mask) { + Some(sum) => Some(sum & !mask), + None => None, + } +} + +#[cfg(test)] +mod tests { + use proptest::prelude::{prop_assert, prop_assert_eq, proptest}; + + use super::*; + + #[test] + fn small_lengths_are_unchanged() { + for len in 0..=7 { + assert_eq!(padme(len), Some(len), "{len}"); + } + } + + #[test] + fn known_values() { + // E = 3, S = 2, z = 1: round up to even. + assert_eq!(padme(9), Some(10)); + assert_eq!(padme(15), Some(16)); + // E = 10, S = 4, z = 6: multiples of 64. + assert_eq!(padme(1_025), Some(1_088)); + // A full chunk's inner plaintext: E = 20, S = 5, z = 15. + assert_eq!(padme(6 + (1 << 20)), Some((1 << 20) + (1 << 15))); + assert_eq!(padme(1 << 20), Some(1 << 20)); + } + + #[test] + fn the_largest_lengths_overflow_rather_than_wrap() { + assert_eq!(padme(u64::MAX), None); + assert_eq!(padme(1 << 63), Some(1 << 63)); + assert_eq!(padme((1 << 63) + 1), Some((1 << 63) + (1 << 57))); + assert_eq!(padme(u64::MAX - (1 << 57) + 2), None); + assert_eq!( + padme(u64::MAX - (1 << 57) + 1), + Some(u64::MAX - (1 << 57) + 1) + ); + } + + proptest! { + #[test] + #[cfg_attr(miri, ignore = "proptest is slow under Miri; pure integer arithmetic")] + fn padme_rounds_up_to_its_step(len in 2u64..(1 << 40)) { + let padded = padme(len).expect("small lengths fit"); + let e = len.ilog2(); + let step = 1u64 << (e - (e.ilog2() + 1)); + prop_assert!(padded >= len); + prop_assert!(padded - len < step, "padded past the next step"); + prop_assert_eq!(padded % step, 0); + // Overhead below 12% once the length is not tiny. + if len >= 64 { + prop_assert!((padded - len) * 100 < len * 12); + } + } + + #[test] + #[cfg_attr(miri, ignore = "proptest is slow under Miri; pure integer arithmetic")] + fn padme_is_idempotent_and_monotone(len in 0u64..(1 << 40)) { + let padded = padme(len).expect("small lengths fit"); + prop_assert_eq!(padme(padded), Some(padded)); + prop_assert!(padme(len + 1).expect("fits") >= padded); + } + } +} diff --git a/crates/engine/core/src/test_data.rs b/crates/engine/core/src/test_data.rs new file mode 100644 index 0000000..1d106dd --- /dev/null +++ b/crates/engine/core/src/test_data.rs @@ -0,0 +1,22 @@ +//! Deterministic inputs shared by the unit tests. + +use crypthix_crypto::key::{KdfKey, XofKey}; +use crypthix_crypto::mac; +use crypthix_types::id::VaultId; + +use crate::chunk::GearTable; + +/// `len` deterministic pseudo-random bytes: the keyed XOF under `[seed; 32]`. +pub(crate) fn pseudo_random(seed: u8, len: usize) -> Vec { + let key = XofKey::from_bytes([seed; 32]).expect("non-zero key"); + let mut data = vec![0u8; len]; + mac::xof(&key, &mut data); + data +} + +/// The gear table of chunker seed `[seed; 32]` in vault `[0x11; 16]`. +pub(crate) fn gear_table(seed: u8) -> GearTable { + let key = KdfKey::from_bytes([seed; 32]).expect("non-zero key"); + let vault_id = VaultId::try_from_bytes([0x11; 16]).expect("non-zero ID"); + GearTable::derive(&key, &vault_id).expect("derives") +} From 1772b46990fe71036c4ecab38d3f69df1cfa77d2 Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 14:53:20 +0530 Subject: [PATCH 02/15] build: pin zstd-safe and fastcdc behind cargo-deny wrappers and feature bans, and reject system zstd overrides in xtask --- deny.toml | 22 ++++++++ tests/deny.toml | 22 ++++++++ xtask/Cargo.toml | 1 + xtask/src/features.rs | 121 ++++++++++++++++++++++++++++++++++++---- xtask/src/pre_commit.rs | 7 ++- 5 files changed, 159 insertions(+), 14 deletions(-) diff --git a/deny.toml b/deny.toml index c05abb0..48a8f5e 100644 --- a/deny.toml +++ b/deny.toml @@ -76,6 +76,14 @@ deny = [ "aes", "aes-gcm-siv", "aes-siv", "blake2b_simd", "boring", "crypto_box", "crypto_secretbox", "ecdsa", "ed25519-compact", "ed25519-zebra", "k256", "libsodium-sys", "md-5", "openssl-sys", "orion", "p256", "pbkdf2", "rsa", "rust-argon2", "scrypt", "sha1", "sha3", "sodiumoxide", "xsalsa20poly1305", + # Compression and chunking live in crypthix-core alone, so the rule that secret files are + # never compressed (FS-53, T-40) and the pinned zstd and FastCDC versions (FS-52, FS-53) + # have one home. fastcdc is only the differential oracle of core's own chunker, in tests; + # the vector generator and the fuzz harness build and check frames independently. + { crate = "zstd-safe", wrappers = ["crypthix-core", "crypthix-vector-gen", "crypthix-fuzz-harness"], reason = "compression lives in crypthix-core (FS-53, T-40)" }, + { crate = "zstd-sys", wrappers = ["zstd-safe"], reason = "reached only through zstd-safe" }, + { crate = "zstd", reason = "compression lives in crypthix-core, through zstd-safe (FS-53, T-40)" }, + { crate = "fastcdc", wrappers = ["crypthix-core", "crypthix-fuzz-harness"], reason = "test oracle only; core has its own keyed chunker (FS-52)" }, # Keys and plaintext live in crypthix-crypto::secure_mem (O1, T-31), so no second allocator # for secrets: memsec ignores mlock failures, the others lack memfd_secret or are unmaintained. "clear_on_drop", "memsec", "memsecurity", "secmem-alloc", "secrets", @@ -95,6 +103,20 @@ deny = ["reduced-round"] crate = "curve25519-dalek" deny = ["legacy_compatibility"] +# zstd as FS-53 pins it: the bundled library built by zstd-sys's own build script with `cc`, +# never through `cmake`, never a system one (through pkg-config, or `non-cargo`, which emits +# no link metadata so whatever libzstd the linker finds is used), never the `debug` build +# (DEBUGLEVEL=5, which traces internal state to standard error), and none of the legacy +# decoders, dictionary builder, experimental API or multithreading, which the format does not +# use and would only widen the attack surface. +[[bans.features]] +crate = "zstd-sys" +deny = ["legacy", "pkg-config", "non-cargo", "cmake", "debug", "zdict_builder", "experimental", "zstdmt", "seekable", "bindgen"] + +[[bans.features]] +crate = "zstd-safe" +deny = ["legacy", "pkg-config", "cmake", "debug", "zdict_builder", "experimental", "zstdmt", "seekable", "bindgen", "with-rust-allocator"] + [sources] unknown-registry = "deny" unknown-git = "deny" diff --git a/tests/deny.toml b/tests/deny.toml index 6f8d45b..deb82a5 100644 --- a/tests/deny.toml +++ b/tests/deny.toml @@ -87,6 +87,14 @@ deny = [ "aes", "aes-gcm-siv", "aes-siv", "blake2b_simd", "boring", "crypto_box", "crypto_secretbox", "ecdsa", "ed25519-compact", "ed25519-zebra", "k256", "libsodium-sys", "md-5", "openssl-sys", "orion", "p256", "pbkdf2", "rsa", "rust-argon2", "scrypt", "sha1", "sha3", "sodiumoxide", "xsalsa20poly1305", + # Compression and chunking live in crypthix-core alone, so the rule that secret files are + # never compressed (FS-53, T-40) and the pinned zstd and FastCDC versions (FS-52, FS-53) + # have one home. fastcdc is only the differential oracle of core's own chunker, in tests; + # the vector generator and the fuzz harness build and check frames independently. + { crate = "zstd-safe", wrappers = ["crypthix-core", "crypthix-vector-gen", "crypthix-fuzz-harness"], reason = "compression lives in crypthix-core (FS-53, T-40)" }, + { crate = "zstd-sys", wrappers = ["zstd-safe"], reason = "reached only through zstd-safe" }, + { crate = "zstd", reason = "compression lives in crypthix-core, through zstd-safe (FS-53, T-40)" }, + { crate = "fastcdc", wrappers = ["crypthix-core", "crypthix-fuzz-harness"], reason = "test oracle only; core has its own keyed chunker (FS-52)" }, # Keys and plaintext live in crypthix-crypto::secure_mem (O1, T-31), so no second allocator # for secrets: memsec ignores mlock failures, the others lack memfd_secret or are unmaintained. "clear_on_drop", "memsec", "memsecurity", "secmem-alloc", "secrets", @@ -106,6 +114,20 @@ deny = ["reduced-round"] crate = "curve25519-dalek" deny = ["legacy_compatibility"] +# zstd as FS-53 pins it: the bundled library built by zstd-sys's own build script with `cc`, +# never through `cmake`, never a system one (through pkg-config, or `non-cargo`, which emits +# no link metadata so whatever libzstd the linker finds is used), never the `debug` build +# (DEBUGLEVEL=5, which traces internal state to standard error), and none of the legacy +# decoders, dictionary builder, experimental API or multithreading, which the format does not +# use and would only widen the attack surface. +[[bans.features]] +crate = "zstd-sys" +deny = ["legacy", "pkg-config", "non-cargo", "cmake", "debug", "zdict_builder", "experimental", "zstdmt", "seekable", "bindgen"] + +[[bans.features]] +crate = "zstd-safe" +deny = ["legacy", "pkg-config", "cmake", "debug", "zdict_builder", "experimental", "zstdmt", "seekable", "bindgen", "with-rust-allocator"] + [sources] unknown-registry = "deny" unknown-git = "deny" diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 53785a6..a95b5a2 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -10,6 +10,7 @@ publish.workspace = true [dependencies] cargo_metadata.workspace = true +toml = { version = "1.1.8", default-features = false, features = ["std", "parse", "serde"] } [lints] workspace = true diff --git a/xtask/src/features.rs b/xtask/src/features.rs index 2f8cebe..35c8b01 100644 --- a/xtask/src/features.rs +++ b/xtask/src/features.rs @@ -19,6 +19,19 @@ //! Compiler flags can do the same behind Cargo's back: `--cfg feature="vectors"` turns a feature //! on, and `--cfg getrandom_backend=...` replaces the kernel source of every key and nonce //! (FS-01). The check rejects either in `RUSTFLAGS` and in the repository's Cargo config files. +//! It also rejects two ways to link a system libzstd instead of the bundled, pinned one (FS-53), +//! which cargo-deny's bans on `zstd-sys` features cannot see: `ZSTD_SYS_USE_PKG_CONFIG` in those +//! files or in the environment, and a `links` override for `zstd` (a `[target..zstd]` +//! table, or a `zstd` key under `[target.]`) in those files, which makes Cargo skip +//! `zstd-sys`'s build script and link whatever the override names. +//! +//! These checks cover only the repository's own build environment: the process environment of +//! the check and the Cargo config files inside the repository. A user-level +//! `~/.cargo/config.toml`, one in `$CARGO_HOME` or in a directory above the repository, and +//! `--config` on the command line are out of their reach. The backstop is the runtime check in +//! `crypthix-core`: `Compressor::new`, and `Decompressor::decode` before its first call into +//! libzstd, fail with `CompressError::Version` when the linked libzstd is not the version FS-53 +//! pins. use std::collections::{BTreeSet, HashMap, HashSet}; use std::env; @@ -26,6 +39,7 @@ use std::fs; use std::process::Command; use cargo_metadata::{DependencyKind, Metadata, MetadataCommand, Package, PackageId}; +use toml::{Table, Value}; use crate::process::{cargo, repo_root}; @@ -51,11 +65,18 @@ pub(crate) fn check() -> Result<(), String> { for package in metadata.workspace_packages() { problems.extend(manifest_problems(package, &guarded)); } + let files = config_files(); problems.extend( - flag_sources() + env_sources() .iter() + .chain(&files) .flat_map(|(source, text)| flag_problems(source, text)), ); + problems.extend( + files + .iter() + .flat_map(|(source, text)| links_problems(source, text)), + ); problems.extend(resolved_problems(&["--workspace"], &guarded)?); for package in dependents(&metadata, &crypto.id) { let args = ["--package", package, "--all-features", "--target", "all"]; @@ -263,9 +284,9 @@ fn resolved_problems(args: &[&str], guarded: &BTreeSet) -> Result Vec<(String, String)> { +/// The settings a build reads from the environment: the `RUSTFLAGS` variables and +/// `ZSTD_SYS_USE_PKG_CONFIG`, as `(source, text)`. +fn env_sources() -> Vec<(String, String)> { let variables = [ "RUSTFLAGS", "CARGO_BUILD_RUSTFLAGS", @@ -274,6 +295,15 @@ fn flag_sources() -> Vec<(String, String)> { let from_env = variables .iter() .filter_map(|name| env::var(name).ok().map(|value| ((*name).to_owned(), value))); + // Any value turns pkg-config on, so the variable's presence is reported, under its own name. + let zstd = env::var_os(ZSTD_PKG_CONFIG) + .map(|_| ("environment".to_owned(), ZSTD_PKG_CONFIG.to_owned())); + from_env.chain(zstd).collect() +} + +/// The Cargo config files of both workspaces, as `(path, text)`. Files outside the repository +/// are out of reach (see the module docs). +fn config_files() -> Vec<(String, String)> { let root = repo_root(); let files = [ ".cargo/config.toml", @@ -281,18 +311,50 @@ fn flag_sources() -> Vec<(String, String)> { "tests/.cargo/config.toml", "tests/.cargo/config", ]; - let from_files = files.iter().filter_map(|file| { - fs::read_to_string(root.join(file)) - .ok() - .map(|text| ((*file).to_owned(), text)) - }); - from_env.chain(from_files).collect() + files + .iter() + .filter_map(|file| { + fs::read_to_string(root.join(file)) + .ok() + .map(|text| ((*file).to_owned(), text)) + }) + .collect() } -/// Flags that turn on a feature or replace the `getrandom` backend. +/// A `links` override for `zstd` in a Cargo config file: `[target..zstd]`, which makes +/// Cargo skip `zstd-sys`'s build script (it declares `links = "zstd"`) and link what the +/// override names. A file that is not valid TOML is reported too, so it cannot hide one. +fn links_problems(source: &str, text: &str) -> Vec { + let config: Table = match text.parse() { + Ok(config) => config, + Err(error) => return vec![format!("{source} is not valid TOML: {error}")], + }; + let Some(Value::Table(targets)) = config.get("target") else { + return Vec::new(); + }; + targets + .iter() + .filter(|(_, settings)| { + matches!(settings, Value::Table(settings) if settings.contains_key(ZSTD_LINKS)) + }) + .map(|(target, _)| { + format!( + "{source} overrides the `{ZSTD_LINKS}` library for {target}, linking a system \ + zstd instead of the pinned one (FS-53)" + ) + }) + .collect() +} + +/// Flags that turn on a feature or replace the `getrandom` backend, and a system zstd. fn flag_problems(source: &str, text: &str) -> Vec { let compact: String = text.chars().filter(|c| !c.is_whitespace()).collect(); let mut problems = Vec::new(); + if compact.contains(ZSTD_PKG_CONFIG) { + problems.push(format!( + "{source} sets {ZSTD_PKG_CONFIG}, linking a system zstd instead of the pinned one (FS-53)" + )); + } if compact.contains("getrandom_backend") { problems.push(format!( "{source} sets getrandom_backend, replacing the kernel RNG (FS-01)" @@ -306,6 +368,12 @@ fn flag_problems(source: &str, text: &str) -> Vec { problems } +/// The variable that makes `zstd-sys` link a system libzstd through pkg-config. +const ZSTD_PKG_CONFIG: &str = "ZSTD_SYS_USE_PKG_CONFIG"; + +/// The `links` name of `zstd-sys`, which a `[target..zstd]` table overrides. +const ZSTD_LINKS: &str = "zstd"; + /// The guarded features in `cargo tree` lines of the form ` ()|`. /// /// # Errors @@ -461,6 +529,37 @@ mod tests { ); } + #[test] + fn a_system_zstd_through_pkg_config_is_rejected() { + let config = "[env]\nZSTD_SYS_USE_PKG_CONFIG = \"1\"\n"; + let problems = flag_problems(".cargo/config.toml", config); + assert_eq!(problems.len(), 1, "{problems:?}"); + assert_eq!( + flag_problems("environment", ZSTD_PKG_CONFIG).len(), + 1, + "the set variable is reported" + ); + } + + #[test] + fn a_links_override_for_zstd_is_rejected() { + let table = "[target.x86_64-unknown-linux-gnu.zstd]\nrustc-link-lib = [\"zstd\"]\n"; + assert_eq!(links_problems("config", table).len(), 1, "a table"); + let dotted = "[target.aarch64-apple-darwin]\nzstd.rustc-link-search = [\"/opt\"]\n"; + assert_eq!(links_problems("config", dotted).len(), 1, "a dotted key"); + let inline = "target.x86_64-pc-windows-msvc.zstd = { rustc-link-lib = [\"zstd\"] }\n"; + assert_eq!(links_problems("config", inline).len(), 1, "an inline table"); + let fine = "[target.x86_64-unknown-linux-gnu]\nlinker = \"clang\"\n\ + [target.x86_64-unknown-linux-gnu.lzma]\nrustc-link-lib = [\"lzma\"]\n\ + [alias]\nzstd = \"run\"\n"; + assert_eq!(links_problems("config", fine), Vec::::new()); + assert_eq!( + links_problems("config", "[target").len(), + 1, + "invalid TOML is reported" + ); + } + #[test] fn output_without_the_crate_fails() { assert!(resolved_in("", &guarded()).is_err(), "empty output passed"); diff --git a/xtask/src/pre_commit.rs b/xtask/src/pre_commit.rs index fb18325..e031f89 100644 --- a/xtask/src/pre_commit.rs +++ b/xtask/src/pre_commit.rs @@ -11,10 +11,11 @@ use std::process::{Command, ExitCode}; use crate::process::{cargo, run_status}; /// Paths whose changes can break the `tests/` workspace. -const SIDE_INPUTS: [&str; 3] = [ +const SIDE_INPUTS: [&str; 4] = [ "tests/", "crates/foundation/types/", "crates/foundation/crypto/", + "crates/engine/core/", ]; /// Largest file that may be committed, in bytes. @@ -154,8 +155,8 @@ fn checks() -> Result<(), String> { "clippy found problems (see above)", )?; - // `tests/` is its own workspace, built on crypthix-types and crypthix-crypto, so a change to - // any of them can break it. The cargo-fuzz crate is left out: libFuzzer needs a C++ compiler + // `tests/` is its own workspace, built on crypthix-types, crypthix-crypto and crypthix-core, + // so a change to any of them can break it. The cargo-fuzz crate is left out: libFuzzer needs a C++ compiler // even to check, and its binaries only call the harness. let side_changed = staged .iter() From a5990ecd216c9e5a391f082d9304551c5f935d5e Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 14:53:54 +0530 Subject: [PATCH 03/15] test(core): TV-07 vectors from an independent generator for chunking, compression, padding and blobs --- .gitleaks.toml | 1 + crates/engine/core/tests/common/mod.rs | 123 + crates/engine/core/tests/tv07.rs | 520 ++++ tests/test-vectors/README.md | 1 + .../crypthix/v0/tv-07-chunk-blob.json | 2531 +++++++++++++++++ tests/test-vectors/gen/Cargo.toml | 1 + tests/test-vectors/gen/src/cdc.rs | 176 ++ tests/test-vectors/gen/src/inner.rs | 37 + tests/test-vectors/gen/src/lib.rs | 5 + tests/test-vectors/gen/src/padme.rs | 40 + tests/test-vectors/gen/src/seed.rs | 109 +- tests/test-vectors/gen/src/tv07.rs | 1308 +++++++++ tests/test-vectors/gen/src/vector_set.rs | 3 +- tests/test-vectors/gen/src/zstd_frame.rs | 327 +++ 14 files changed, 5179 insertions(+), 3 deletions(-) create mode 100644 crates/engine/core/tests/common/mod.rs create mode 100644 crates/engine/core/tests/tv07.rs create mode 100644 tests/test-vectors/crypthix/v0/tv-07-chunk-blob.json create mode 100644 tests/test-vectors/gen/src/cdc.rs create mode 100644 tests/test-vectors/gen/src/inner.rs create mode 100644 tests/test-vectors/gen/src/padme.rs create mode 100644 tests/test-vectors/gen/src/tv07.rs create mode 100644 tests/test-vectors/gen/src/zstd_frame.rs diff --git a/.gitleaks.toml b/.gitleaks.toml index 7e9c9ed..14c29a1 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -19,4 +19,5 @@ description = "Generated format vectors: keys drawn from the public seed in each paths = [ '''^tests/test-vectors/crypthix/v0/tv-04-domain-separation\.json$''', '''^tests/test-vectors/crypthix/v0/tv-05-cx-aead\.json$''', + '''^tests/test-vectors/crypthix/v0/tv-07-chunk-blob\.json$''', ] diff --git a/crates/engine/core/tests/common/mod.rs b/crates/engine/core/tests/common/mod.rs new file mode 100644 index 0000000..45b1e97 --- /dev/null +++ b/crates/engine/core/tests/common/mod.rs @@ -0,0 +1,123 @@ +//! Helpers shared by the vector runners. +//! +//! This mirrors `crates/foundation/crypto/tests/common/mod.rs`, plus the `zstd` header field and +//! the integer accessors of generated sets. Keep the two in sync: a fix to how vectors are +//! loaded or decoded belongs in both. They are not shared through a `#[path]` module because +//! the crypto crate's tests would then reach up into a crate of a higher layer. + +use std::fs; +use std::path::Path; + +use serde::Deserialize; +use serde::de::DeserializeOwned; +use serde_json::Value; + +/// Reads a vector file under `tests/test-vectors/`. +pub(crate) fn load(relative: &str) -> T { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../../tests/test-vectors") + .join(relative); + let text = + fs::read_to_string(&path).unwrap_or_else(|error| panic!("{}: {error}", path.display())); + serde_json::from_str(&text).unwrap_or_else(|error| panic!("{}: {error}", path.display())) +} + +/// Decodes lowercase or uppercase hex. +pub(crate) fn hex(text: &str) -> Vec { + assert!(text.len().is_multiple_of(2), "odd-length hex: {text}"); + (0..text.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&text[i..i + 2], 16).expect("hex digit")) + .collect() +} + +/// Decodes hex of exactly `N` bytes. +pub(crate) fn hex_array(text: &str) -> [u8; N] { + hex(text).try_into().expect("hex of the expected length") +} + +/// A generated CryptHix set (format spec 20.2), with tests kept as JSON. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct VectorSet { + /// The zstd version the generator linked, for sets that compress. + pub(crate) zstd: Option, + pub(crate) number_of_tests: usize, + pub(crate) test_groups: Vec, +} + +/// One group of a generated set. +#[derive(Deserialize)] +pub(crate) struct VectorGroup { + #[serde(rename = "type")] + pub(crate) kind: String, + pub(crate) tests: Vec, +} + +impl VectorSet { + /// Loads a set and checks it has exactly the expected groups, in order, with these numbers of + /// tests, so a generator change that drops cases fails here as well as in `vectors --check`. + pub(crate) fn load_exact(relative: &str, groups: &[(&str, usize)]) -> Self { + let set: VectorSet = load(relative); + let found: Vec<(&str, usize)> = set + .test_groups + .iter() + .map(|group| (group.kind.as_str(), group.tests.len())) + .collect(); + assert_eq!(found, groups, "{relative}: groups and test counts"); + let total: usize = groups.iter().map(|(_, count)| count).sum(); + assert_eq!(set.number_of_tests, total, "{relative}: numberOfTests"); + set + } +} + +/// A text input of a generated test. +pub(crate) fn text<'a>(test: &'a Value, key: &str) -> &'a str { + test["inputs"][key] + .as_str() + .unwrap_or_else(|| panic!("input {key}")) +} + +/// A byte input of a generated test. +pub(crate) fn input(test: &Value, key: &str) -> Vec { + hex(text(test, key)) +} + +/// A byte input of exactly `N` bytes. +pub(crate) fn input_array(test: &Value, key: &str) -> [u8; N] { + hex_array(text(test, key)) +} + +/// An expected byte output of a generated test. +pub(crate) fn output(test: &Value, key: &str) -> Vec { + hex(test[key].as_str().unwrap_or_else(|| panic!("output {key}"))) +} + +/// An integer input of a generated test. +pub(crate) fn int(test: &Value, key: &str) -> u64 { + test["inputs"][key] + .as_u64() + .unwrap_or_else(|| panic!("integer input {key}")) +} + +/// An expected integer output of a generated test. +pub(crate) fn output_int(test: &Value, key: &str) -> u64 { + test[key] + .as_u64() + .unwrap_or_else(|| panic!("integer output {key}")) +} + +/// An expected list of integers of a generated test. +pub(crate) fn output_ints(test: &Value, key: &str) -> Vec { + test[key] + .as_array() + .unwrap_or_else(|| panic!("output {key}")) + .iter() + .map(|value| value.as_u64().expect("an integer")) + .collect() +} + +/// Whether a generated test has an input named `key`. +pub(crate) fn has_input(test: &Value, key: &str) -> bool { + test["inputs"].get(key).is_some() +} diff --git a/crates/engine/core/tests/tv07.rs b/crates/engine/core/tests/tv07.rs new file mode 100644 index 0000000..8374818 --- /dev/null +++ b/crates/engine/core/tests/tv07.rs @@ -0,0 +1,520 @@ +//! Runs TV-07: chunk boundaries, Padmé, inner plaintexts, compression, decompression, and data +//! and meta blobs (FS-52 to FS-57). +//! +//! The encoder groups (`Compress`, `DataBlobSeal`) expect zstd's exact output, which is only +//! known for the version in the set's header, so they fail outright under any other version. +//! Every other group, decompression included, must pass with any zstd. + +#[allow(dead_code, reason = "each runner uses part of the shared helpers")] +mod common; + +use crypthix_core::blob::{ + self, BlobContext, BlobIdKind, ChunkEntry, ChunkKeys, MetaContext, MetaKey, MetaKind, + ObjectClass, ObjectOpener, ObjectSealer, +}; +use crypthix_core::chunk::{self, Chunks, GearTable, ObjectShape, StreamChunker}; +use crypthix_core::compress::{Compressor, Decompressor}; +use crypthix_core::error::ReadError; +use crypthix_core::inner::{self, Comp}; +use crypthix_core::limits::MAX_CHUNK; +use crypthix_core::pad; +use crypthix_crypto::cx_aead; +use crypthix_crypto::hash; +use crypthix_crypto::key::{KdfKey, XofKey}; +use crypthix_crypto::label::HashLabel; +use crypthix_crypto::mac; +use crypthix_types::id::{BlobId, DekId, Epoch, ObjectId, VaultId}; +use serde_json::Value; + +use common::VectorSet; + +const FILE: &str = "crypthix/v0/tv-07-chunk-blob.json"; + +/// The groups of TV-07 and their sizes. +const GROUPS: [(&str, usize); 8] = [ + ("Chunking", 21), + ("Padme", 12), + ("InnerDecode", 20), + ("Compress", 9), + ("Decompress", 32), + ("DataBlobSeal", 4), + ("DataBlobOpen", 29), + ("MetaBlob", 13), +]; + +/// The groups whose expected bytes come from the zstd encoder. +const ENCODER_GROUPS: [&str; 2] = ["Compress", "DataBlobSeal"]; + +/// Every `expect` the data-blob open matrix must use at least once (format spec 20.4). +const OPEN_RESULTS: [&str; 8] = [ + "Ok", + "Decrypt", + "Binding", + "Padding", + "Limit", + "Decompress", + "Truncated", + "ZeroValue", +]; + +fn comment(test: &Value) -> &str { + test["comment"].as_str().expect("comment") +} + +fn expect(test: &Value) -> &str { + test["expect"].as_str().expect("expect") +} + +fn usize_of(value: u64) -> usize { + usize::try_from(value).expect("fits") +} + +/// The first `len` bytes of the keyed XOF under `key` (the `dataKey` inputs). +fn xof(key: [u8; 32], len: usize) -> Vec { + let key = XofKey::from_bytes(key).expect("non-zero key"); + let mut out = vec![0u8; len]; + mac::xof(&key, &mut out); + out +} + +/// A test's data: `chunk` as hex, `dataKey` and `length` as a stream, `pattern` repeated to +/// `length`, or `zeros`. +fn data(test: &Value) -> Vec { + if common::has_input(test, "chunk") { + common::input(test, "chunk") + } else if common::has_input(test, "pattern") { + let len = usize_of(common::int(test, "length")); + common::input(test, "pattern") + .into_iter() + .cycle() + .take(len) + .collect() + } else if common::has_input(test, "dataKey") { + let len = usize_of(common::int(test, "length")); + xof(common::input_array(test, "dataKey"), len) + } else { + vec![0; usize_of(common::int(test, "zeros"))] + } +} + +fn class(test: &Value) -> ObjectClass { + match common::text(test, "class") { + "ordinary" => ObjectClass::Ordinary, + "secret" => ObjectClass::Secret, + other => panic!("unknown class {other}"), + } +} + +fn kdf_key(test: &Value, name: &str) -> KdfKey { + KdfKey::from_bytes(common::input_array(test, name)).expect("non-zero key") +} + +fn vault_id(test: &Value) -> VaultId { + VaultId::try_from_bytes(common::input_array(test, "vaultId")).expect("non-zero ID") +} + +fn blob_id(bytes: [u8; 32]) -> BlobId { + BlobId::try_from_bytes(bytes).expect("non-zero ID") +} + +/// The format error of a failed open; anything else is a bug in the runner's set-up. +fn error_name(error: ReadError) -> &'static str { + match error { + ReadError::Format(error) => error.name(), + other => panic!("not a format error: {other:?}"), + } +} + +fn check_chunking(test: &Value) { + let seed = kdf_key(test, "chunkerSeed"); + let gear = GearTable::derive(&seed, &vault_id(test)).expect("derives"); + let class = class(test); + let data = data(test); + let expected: Vec = common::output_ints(test, "lengths") + .into_iter() + .map(usize_of) + .collect(); + let chunks = Chunks::new(&gear, class, &data); + let shape = chunks.object_shape(); + assert_eq!(shape.class(), class, "{}: the shape's class", comment(test)); + assert_eq!( + shape.is_single(), + expected.len() <= 1, + "{}: the shape", + comment(test) + ); + let lengths: Vec = chunks.map(|range| range.len()).collect(); + assert_eq!(lengths, expected, "{}: in memory", comment(test)); + if class == ObjectClass::Ordinary { + assert_eq!( + chunk::cut(&gear, &data), + expected.first().copied().unwrap_or(0), + "{}: the first cut", + comment(test) + ); + } + + let mut chunker = StreamChunker::new(&gear, class, data.as_slice()).expect("a window"); + let mut streamed = Vec::new(); + while let Some(chunk) = chunker.next_chunk().expect("reads") { + assert_eq!(chunk.index(), streamed.len() as u64, "{}", comment(test)); + assert_eq!( + chunk.is_last(), + streamed.len() + 1 == expected.len(), + "{}: is_last", + comment(test) + ); + streamed.push(chunk.bytes().len()); + } + assert_eq!(streamed, expected, "{}: streamed", comment(test)); +} + +fn check_padme(test: &Value) { + let padded = pad::padme(common::int(test, "length")); + assert_eq!( + padded, + Some(common::output_int(test, "padded")), + "{}", + comment(test) + ); +} + +/// The inner plaintext of a test: `inner` as hex, or `header`, a payload stream and a zero pad. +fn inner_bytes(test: &Value) -> Vec { + if common::has_input(test, "inner") { + return common::input(test, "inner"); + } + let payload = xof( + common::input_array(test, "dataKey"), + usize_of(common::int(test, "length")), + ); + let pad = vec![0u8; usize_of(common::int(test, "padLength"))]; + [common::input(test, "header"), payload, pad].concat() +} + +fn check_inner(test: &Value) { + let bytes = inner_bytes(test); + match inner::decode_inner(&bytes) { + Ok(view) => { + assert_eq!(expect(test), "Ok", "{}", comment(test)); + assert_eq!( + u64::from(view.comp().code()), + common::output_int(test, "comp"), + "{}", + comment(test) + ); + let payload = if test.get("payload").is_some() { + common::output(test, "payload") + } else { + xof( + common::input_array(test, "dataKey"), + usize_of(common::int(test, "length")), + ) + }; + assert_eq!(view.payload(), payload, "{}", comment(test)); + } + Err(error) => assert_eq!(error.name(), expect(test), "{}", comment(test)), + } +} + +fn check_compress(test: &Value, compressor: &mut Compressor) { + let chunk = data(test); + let inner = compressor + .encode_chunk(&chunk, class(test)) + .expect("encodes"); + assert_eq!( + u64::from(inner[0]), + common::output_int(test, "comp"), + "{}", + comment(test) + ); + assert_eq!( + inner.len() as u64, + common::output_int(test, "innerLength"), + "{}", + comment(test) + ); + if test.get("inner").is_some() { + assert_eq!( + inner.as_slice(), + common::output(test, "inner"), + "{}", + comment(test) + ); + } else { + // A raw inner plaintext given by its length only: the chunk, its header and zero pad. + let view = inner::decode_inner(&inner).expect("well formed"); + assert_eq!( + (view.comp(), view.payload()), + (Comp::Raw, chunk.as_slice()), + "{}", + comment(test) + ); + } +} + +fn check_decompress(test: &Value, decompressor: &mut Decompressor) { + let frame = if common::has_input(test, "frameZeros") { + let zeros = vec![0; usize_of(common::int(test, "frameZeros"))]; + [ + common::input(test, "frameHead"), + zeros, + common::input(test, "frameTail"), + ] + .concat() + } else { + common::input(test, "frame") + }; + let plain_len = common::int(test, "plainLen"); + match decompressor.decode(&frame, plain_len) { + Ok(plain) => { + assert_eq!(expect(test), "Ok", "{}", comment(test)); + let expected = if test.get("plaintextZeros").is_some() { + vec![0; usize_of(common::output_int(test, "plaintextZeros"))] + } else { + common::output(test, "plaintext") + }; + assert_eq!(plain.as_slice(), expected, "{}", comment(test)); + } + Err(error) => assert_eq!(error_name(error), expect(test), "{}", comment(test)), + } +} + +/// The shape the chunker gives an object of `class` and `count` chunks, from a chunker run over +/// one byte or over zeros one byte longer than a maximum chunk; only the chunker makes shapes. +fn shape(class: ObjectClass, count: u64) -> ObjectShape { + let seed = KdfKey::from_bytes([1; 32]).expect("non-zero key"); + let vault_id = VaultId::try_from_bytes([1; 16]).expect("non-zero ID"); + let gear = GearTable::derive(&seed, &vault_id).expect("derives"); + let len = if count == 1 { 1 } else { MAX_CHUNK + 1 }; + let shape = Chunks::new(&gear, class, &vec![0; len]).object_shape(); + assert_eq!(shape.is_single(), count == 1, "{count} chunks"); + assert_eq!(shape.class(), class); + shape +} + +/// The keys of a data-blob test, bound to its context. +fn chunk_keys(test: &Value) -> ChunkKeys { + let context = BlobContext::new( + vault_id(test), + ObjectId::try_from_bytes(common::input_array(test, "objectId")).expect("non-zero ID"), + DekId::try_from_bytes(common::input_array(test, "dekId")).expect("non-zero ID"), + ); + ChunkKeys::derive( + &kdf_key(test, "dek"), + &common::input_array(test, "dekSalt"), + context, + ) + .expect("derives") +} + +fn check_data_seal(test: &Value, compressor: &mut Compressor, decompressor: &mut Decompressor) { + let keys = chunk_keys(test); + let class = class(test); + let count = common::int(test, "chunkCount"); + let chunk = common::input(test, "chunk"); + let expected_id: [u8; 32] = common::hex_array(test["blobId"].as_str().expect("blobId")); + match BlobIdKind::for_object(class, count) { + BlobIdKind::Keyed => { + let keyed = mac::mac(keys.blob_id_key(), &chunk); + assert_eq!(keyed.as_bytes(), &expected_id, "{}", comment(test)); + } + BlobIdKind::Random => assert_eq!( + common::input_array::<32>(test, "blobId"), + expected_id, + "{}: a random ID is given", + comment(test) + ), + other => panic!("unknown blob ID kind {other:?}"), + } + let id = blob_id(expected_id); + + let inner = compressor.encode_chunk(&chunk, class).expect("encodes"); + assert_eq!( + inner.as_slice(), + common::output(test, "inner"), + "{}", + comment(test) + ); + let aad = blob::data_blob_aad(keys.context(), &id); + let a = hash::hash(HashLabel::CxAad, aad.as_bytes()); + let nonce = cx_aead::hedged_nonce( + keys.chunk_key(), + &a, + &inner, + &common::input_array(test, "rand"), + ); + assert_eq!( + nonce.as_slice(), + common::output(test, "nonce"), + "{}", + comment(test) + ); + let sealed = cx_aead::seal_with_nonce(keys.chunk_key(), &aad, &inner, &nonce); + assert_eq!(sealed, common::output(test, "sealed"), "{}", comment(test)); + + let entry = ChunkEntry::new(id, chunk.len() as u64); + let reader = ObjectOpener::new(&keys, class, count); + let opened = reader.open(decompressor, &entry, &sealed).expect("opens"); + assert_eq!(opened.as_slice(), chunk, "{}", comment(test)); + + // The real writer, with its own randomness, gives a blob that opens the same way. + let writer = ObjectSealer::new(&keys, shape(class, count)); + assert_eq!( + writer.blob_id_kind(), + reader.blob_id_kind(), + "{}", + comment(test) + ); + let written = writer.seal(compressor, &chunk).expect("seals"); + if BlobIdKind::for_object(class, count) == BlobIdKind::Keyed { + assert_eq!(written.blob_id(), &id, "{}", comment(test)); + } + let opened = reader + .open(decompressor, written.entry(), written.sealed()) + .expect("opens"); + assert_eq!(opened.as_slice(), chunk, "{}", comment(test)); +} + +/// Checks one data-blob open and returns its `expect`. +fn check_data_open<'a>(test: &'a Value, decompressor: &mut Decompressor) -> &'a str { + let keys = chunk_keys(test); + let entry = ChunkEntry::new( + blob_id(common::input_array(test, "blobId")), + common::int(test, "plainLen"), + ); + let sealed = common::input(test, "sealed"); + let result = ObjectOpener::new(&keys, class(test), common::int(test, "chunkCount")).open( + decompressor, + &entry, + &sealed, + ); + match result { + Ok(opened) => { + assert_eq!(expect(test), "Ok", "{}", comment(test)); + assert_eq!( + opened.as_slice(), + common::output(test, "plaintext"), + "{}", + comment(test) + ); + } + Err(error) => assert_eq!(error_name(error), expect(test), "{}", comment(test)), + } + expect(test) +} + +fn check_meta(test: &Value) { + let kind_code = u8::try_from(common::int(test, "kind")).expect("a byte"); + let kind = MetaKind::from_code(kind_code).expect("a meta kind"); + let epoch = u32::try_from(common::int(test, "epoch")).expect("a u32"); + let context = MetaContext::new( + vault_id(test), + kind, + Epoch::try_new(epoch).expect("non-zero"), + ); + let key = MetaKey::derive(&kdf_key(test, "kek"), context).expect("derives"); + let id = blob_id(common::input_array(test, "blobId")); + + if !common::has_input(test, "cbor") { + let sealed = common::input(test, "sealed"); + match blob::open_meta_blob(&key, &id, &sealed) { + Ok(cbor) => { + assert_eq!(expect(test), "Ok", "{}", comment(test)); + assert_eq!( + cbor.as_slice(), + common::output(test, "cbor"), + "{}", + comment(test) + ); + } + Err(error) => assert_eq!(error_name(error), expect(test), "{}", comment(test)), + } + return; + } + + let cbor = common::input(test, "cbor"); + let aad = blob::meta_blob_aad(&context, &id); + let a = hash::hash(HashLabel::CxAad, aad.as_bytes()); + let nonce = cx_aead::hedged_nonce( + key.seal_key(), + &a, + &cbor, + &common::input_array(test, "rand"), + ); + assert_eq!( + nonce.as_slice(), + common::output(test, "nonce"), + "{}", + comment(test) + ); + let sealed = cx_aead::seal_with_nonce(key.seal_key(), &aad, &cbor, &nonce); + assert_eq!(sealed, common::output(test, "sealed"), "{}", comment(test)); + let opened = blob::open_meta_blob(&key, &id, &sealed).expect("opens"); + assert_eq!(opened.as_slice(), cbor, "{}", comment(test)); + + let written = blob::seal_meta_blob(&key, &cbor).expect("seals"); + let opened = blob::open_meta_blob(&key, written.blob_id(), written.sealed()).expect("opens"); + assert_eq!(opened.as_slice(), cbor, "{}", comment(test)); +} + +/// Every group but the encoder's, which any zstd version must pass. +#[test] +#[cfg_attr(miri, ignore = "zstd is C, which Miri cannot run")] +fn tv07_chunk_blob() { + let set = VectorSet::load_exact(FILE, &GROUPS); + let mut decompressor = Decompressor::new(); + for group in &set.test_groups { + let kind = group.kind.as_str(); + if ENCODER_GROUPS.contains(&kind) { + continue; + } + let mut seen = Vec::new(); + for test in &group.tests { + match kind { + "Chunking" => check_chunking(test), + "Padme" => check_padme(test), + "InnerDecode" => check_inner(test), + "Decompress" => check_decompress(test, &mut decompressor), + "DataBlobOpen" => seen.push(check_data_open(test, &mut decompressor)), + "MetaBlob" => check_meta(test), + other => panic!("unknown group {other}"), + } + } + if kind == "DataBlobOpen" { + for result in OPEN_RESULTS { + assert!(seen.contains(&result), "no open case expects {result}"); + } + } + } +} + +/// The encoder groups: zstd must be the version the vectors were made with (FS-53). +#[test] +#[cfg_attr(miri, ignore = "zstd is C, which Miri cannot run")] +fn tv07_encoder_under_the_pinned_zstd() { + let set = VectorSet::load_exact(FILE, &GROUPS); + let header = set.zstd.as_deref().expect("TV-07 names its zstd version"); + assert_eq!( + zstd_safe::version_string(), + header, + "the encoder groups only hold for the zstd version the vectors were made with" + ); + let mut compressor = Compressor::new().expect("a context"); + let mut decompressor = Decompressor::new(); + for group in &set.test_groups { + match group.kind.as_str() { + "Compress" => { + for test in &group.tests { + check_compress(test, &mut compressor); + } + } + "DataBlobSeal" => { + for test in &group.tests { + check_data_seal(test, &mut compressor, &mut decompressor); + } + } + _ => {} + } + } +} diff --git a/tests/test-vectors/README.md b/tests/test-vectors/README.md index ba6e191..0a1f804 100644 --- a/tests/test-vectors/README.md +++ b/tests/test-vectors/README.md @@ -17,6 +17,7 @@ Each file follows the Wycheproof shape: `testGroups` of `tests`, each with a `tc | TV-03 deterministic CBOR | `crates/foundation/types/tests/vectors.rs` | Generated, deterministic; the `GeneratedDocumentParse` group is built by the runner from its inputs | | TV-04 labels, `H`, `KDF`, `MAC`, the gear-table XOF, derived keys and zero values | `crates/foundation/crypto/tests/tv04.rs` | Generated from the seeded stream; outputs computed by the generator's own section 7 code (`gen/src/cx.rs`) | | TV-05 CX-AEAD seal, open, commitment, hedged and synthetic nonces (including replayed randomness), an all-zero nonce | `crates/foundation/crypto/tests/tv05.rs` | Generated from the seeded stream; outputs computed by `gen/src/cx.rs` | +| TV-07 chunk boundaries, Padmé, inner plaintexts, compression, data and meta blobs | `crates/engine/core/tests/tv07.rs` | Generated from the seeded stream; boundaries from an independent one-byte-at-a-time FastCDC (`gen/src/cdc.rs`) for the `ordinary` class and from the length alone for the `secret` class, frames built by hand (`gen/src/zstd_frame.rs`) or by the zstd encoder named in the header (`zstd`), seals by `gen/src/cx.rs`. Inputs too large for hex are a `dataKey` and `length` (the keyed BLAKE3 XOF over the empty input), a `pattern` repeated to `length`, or `zeros`; a frame with a run of more than 1,024 zero bytes is `frameHead`, `frameZeros` zero bytes, then `frameTail`. The `CutEdges` chunking cases are found by a deterministic search over data keys and chunker seeds, and the generator checks with its own chunker that each cuts where its comment says. The `Compress` and `DataBlobSeal` groups hold only under that zstd version, and the runner fails if it links another; every other group holds under any | | TV-17 versions, criticality, feature bits and GREASE | `crates/foundation/types/tests/vectors.rs` | Generated, deterministic | ## Changing a vector diff --git a/tests/test-vectors/crypthix/v0/tv-07-chunk-blob.json b/tests/test-vectors/crypthix/v0/tv-07-chunk-blob.json new file mode 100644 index 0000000..f798c84 --- /dev/null +++ b/tests/test-vectors/crypthix/v0/tv-07-chunk-blob.json @@ -0,0 +1,2531 @@ +{ + "set": "TV-07", + "structure": "chunk-blob", + "formatVersion": 0, + "suiteId": 1, + "generator": "crypthix-vector-gen, seeded test-rng stream, independent section 7 code", + "seed": "7d6e254f245baeb4c5283911462b04f1c14d67d245502714713dc14b7e742282", + "zstd": "1.5.7", + "notes": { + "SmallFile": { + "cites": [ + "FS-52", + "M-39" + ], + "description": "A file no longer than the 64 KiB minimum is one chunk; an empty file has none. `lengths` lists every chunk." + }, + "CutPoints": { + "cites": [ + "FS-52", + "M-39", + "T-84" + ], + "description": "FastCDC 2020 at level 2 with the vault's gear table: strict mask below 256 KiB, loose to 1 MiB, a cut before the matching byte, never at an odd last byte." + }, + "CutEdges": { + "cites": [ + "FS-52", + "M-39", + "T-84" + ], + "description": "Files found by search so a cut sits on an edge of the rule: at the minimum and one past it, at the switch from the strict to the loose mask (a loose-only match at 2⌊center/2⌋ cuts, one at 2⌊center/2⌋ − 1 does not), at the last position tested, an odd last byte that would match if it were tested, and a repeated pattern that is cut only at the maximum. The generator checks each with its one-byte chunker." + }, + "KeyedGear": { + "cites": [ + "FS-52", + "M-39", + "T-84" + ], + "description": "Another chunker_seed gives another gear table and other boundaries for the same data." + }, + "SecretFixed": { + "cites": [ + "FS-52", + "T-84" + ], + "description": "A secret-class object is cut into 1 MiB chunks and a shorter last one, from its length alone, with no gear-table lookup; an empty one has none." + }, + "Padme": { + "cites": [ + "FS-54", + "M-39", + "T-84" + ], + "description": "padme(L) for L ≥ 2 rounds L up to a multiple of 2^(E−S); below 2 it is L." + }, + "InnerOk": { + "cites": [ + "FS-54", + "M-39" + ], + "description": "A well-formed inner plaintext: comp 0 or 1, rsv 0, zero pad, length padme(6 + payload_len)." + }, + "InnerPadding": { + "cites": [ + "FS-54", + "T-39" + ], + "description": "Unknown comp, non-zero rsv or pad, or a length other than padme(6 + payload_len), is Padding." + }, + "InnerLimit": { + "cites": [ + "FS-54", + "FS-11", + "T-39" + ], + "description": "payload_len up to 2^20 is allowed; above it is Limit, checked before the length." + }, + "CheckOrder": { + "cites": [ + "FS-93", + "FS-53", + "FS-54", + "T-39" + ], + "description": "Two faults at once: the first check in the order of the rules decides." + }, + "Compress": { + "cites": [ + "FS-53", + "T-40" + ], + "description": "One zstd frame at level 3 with its content size, no checksum, no dictionary ID, window ≤ 2^20; equal output is only expected from the zstd version in the header." + }, + "StoreRaw": { + "cites": [ + "FS-53", + "T-40" + ], + "description": "The frame is kept only if 16 × frame ≤ 15 × chunk; otherwise the chunk is stored with comp 0." + }, + "SecretRaw": { + "cites": [ + "FS-53", + "FS-55", + "T-40" + ], + "description": "Chunks of secret-class objects are never compressed; a secret chunk with comp 1 is Padding." + }, + "FrameOk": { + "cites": [ + "FS-53", + "T-39" + ], + "description": "Frames FS-53 allows decode to exactly plain_len bytes with any zstd version; raw and RLE frames are built by hand." + }, + "FrameRejected": { + "cites": [ + "FS-53", + "T-39" + ], + "description": "A frame that is not exactly one frame with content size plain_len in the shortest field that holds it, no checksum, no dictionary ID, the unused and reserved bits clear and a window ≤ 2^20, or whose content differs from its declaration, is Decompress." + }, + "PlainLenCap": { + "cites": [ + "FS-53", + "FS-11", + "T-39" + ], + "description": "plain_len may be 2^20; above that the chunk is Decompress before it is decrypted or decoded." + }, + "DataBlobSeal": { + "cites": [ + "FS-55", + "FS-29", + "M-8", + "T-35" + ], + "description": "Seal(K_chunk, aad, inner, hedged nonce) with the AAD of FS-55; K_chunk and K_blobid from the DEK and dek_salt (FS-38)." + }, + "KeyedBlobId": { + "cites": [ + "FS-55", + "FS-56", + "T-85" + ], + "description": "In an ordinary object of two or more chunks, blob_id = MAC(K_blobid, chunk), checked after opening." + }, + "RandomBlobId": { + "cites": [ + "FS-55", + "T-85" + ], + "description": "In a single-chunk or secret-class object, blob_id is random and not recomputed." + }, + "DataBlobOpen": { + "cites": [ + "FS-55", + "FS-56", + "M-8" + ], + "description": "A data blob opens to its chunk." + }, + "AadBinding": { + "cites": [ + "FS-55", + "M-8", + "T-35" + ], + "description": "A blob sealed under an AAD naming another vault, object, DEK, blob ID, kind or label, or under another key, is Decrypt." + }, + "BlobIdBinding": { + "cites": [ + "FS-56", + "T-85" + ], + "description": "A blob that opens but whose chunk does not MAC to its keyed blob ID is Binding." + }, + "BlobInner": { + "cites": [ + "FS-54", + "T-39" + ], + "description": "A data blob whose inner plaintext is malformed is Padding, or Limit for payload_len over 2^20." + }, + "BlobFrame": { + "cites": [ + "FS-53", + "T-39" + ], + "description": "A data blob whose payload does not decode to exactly plain_len bytes is Decompress." + }, + "SealShape": { + "cites": [ + "FS-28", + "FS-03", + "M-9" + ], + "description": "Input too short to be a seal is Truncated; an all-zero nonce is ZeroValue." + }, + "MetaBlob": { + "cites": [ + "FS-57", + "FS-38", + "M-8" + ], + "description": "Seal(K_kind_e, aad, CBOR, hedged nonce) with the AAD of FS-57; GC-candidate nodes use the location key." + }, + "MetaBlobOpen": { + "cites": [ + "FS-57", + "M-8", + "T-35" + ], + "description": "A meta blob opened with another kind byte, epoch, blob ID, vault or KEK is Decrypt." + } + }, + "testGroups": [ + { + "type": "Chunking", + "tests": [ + { + "tcId": 1, + "comment": "an empty file has no chunks", + "flags": [ + "SmallFile" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "zeros": 0 + }, + "expect": "Ok", + "lengths": [] + }, + { + "tcId": 2, + "comment": "one byte is one chunk", + "flags": [ + "SmallFile" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "dataKey": "d2c23768522e4167fbc3e434ad42d35259735aedbbff4f50f6045a54ecac518f", + "length": 1 + }, + "expect": "Ok", + "lengths": [ + 1 + ] + }, + { + "tcId": 3, + "comment": "one byte under the 64 KiB minimum", + "flags": [ + "SmallFile" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "dataKey": "d2c23768522e4167fbc3e434ad42d35259735aedbbff4f50f6045a54ecac518f", + "length": 65535 + }, + "expect": "Ok", + "lengths": [ + 65535 + ] + }, + { + "tcId": 4, + "comment": "exactly the minimum is one chunk", + "flags": [ + "SmallFile" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "dataKey": "d2c23768522e4167fbc3e434ad42d35259735aedbbff4f50f6045a54ecac518f", + "length": 65536 + }, + "expect": "Ok", + "lengths": [ + 65536 + ] + }, + { + "tcId": 5, + "comment": "one byte over the minimum: no position is tested", + "flags": [ + "CutPoints" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "dataKey": "d2c23768522e4167fbc3e434ad42d35259735aedbbff4f50f6045a54ecac518f", + "length": 65537 + }, + "expect": "Ok", + "lengths": [ + 65537 + ] + }, + { + "tcId": 6, + "comment": "3 MiB of zeros", + "flags": [ + "CutPoints" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "zeros": 3145728 + }, + "expect": "Ok", + "lengths": [ + 1048576, + 1048576, + 1048576 + ] + }, + { + "tcId": 7, + "comment": "an odd tail of 64 KiB + 3 bytes after a boundary: the last byte is never a cut point", + "flags": [ + "CutPoints" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "dataKey": "d2c23768522e4167fbc3e434ad42d35259735aedbbff4f50f6045a54ecac518f", + "length": 1215074 + }, + "expect": "Ok", + "lengths": [ + 115736, + 372439, + 348815, + 312545, + 65539 + ] + }, + { + "tcId": 8, + "comment": "8 MiB of random data", + "flags": [ + "CutPoints" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "dataKey": "d2c23768522e4167fbc3e434ad42d35259735aedbbff4f50f6045a54ecac518f", + "length": 8388608 + }, + "expect": "Ok", + "lengths": [ + 115736, + 372439, + 348815, + 312545, + 321578, + 366686, + 280816, + 375041, + 88012, + 269903, + 291223, + 270265, + 432012, + 302722, + 118126, + 314784, + 522687, + 277174, + 287192, + 268415, + 383242, + 310001, + 269398, + 267334, + 322823, + 288900, + 361284, + 249455 + ] + }, + { + "tcId": 9, + "comment": "the same 8 MiB under another chunker seed", + "flags": [ + "KeyedGear" + ], + "inputs": { + "chunkerSeed": "9ffe20583de7cfcc2afa6fb9080d772195894819079cb3e951de82b56c8fd774", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "dataKey": "d2c23768522e4167fbc3e434ad42d35259735aedbbff4f50f6045a54ecac518f", + "length": 8388608 + }, + "expect": "Ok", + "lengths": [ + 349069, + 289797, + 262598, + 178443, + 237318, + 264325, + 183486, + 345593, + 76933, + 102238, + 375621, + 269143, + 300908, + 277701, + 376084, + 274632, + 214647, + 270964, + 252891, + 386475, + 269488, + 262618, + 478976, + 304836, + 402504, + 385521, + 365831, + 289724, + 340244 + ] + }, + { + "tcId": 10, + "comment": "an empty secret file has no chunks", + "flags": [ + "SecretFixed" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "secret", + "zeros": 0 + }, + "expect": "Ok", + "lengths": [] + }, + { + "tcId": 11, + "comment": "a secret file of exactly 1 MiB is one chunk", + "flags": [ + "SecretFixed" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "secret", + "dataKey": "d2c23768522e4167fbc3e434ad42d35259735aedbbff4f50f6045a54ecac518f", + "length": 1048576 + }, + "expect": "Ok", + "lengths": [ + 1048576 + ] + }, + { + "tcId": 12, + "comment": "a secret file of 1 MiB and one byte is two chunks", + "flags": [ + "SecretFixed" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "secret", + "dataKey": "d2c23768522e4167fbc3e434ad42d35259735aedbbff4f50f6045a54ecac518f", + "length": 1048577 + }, + "expect": "Ok", + "lengths": [ + 1048576, + 1 + ] + }, + { + "tcId": 13, + "comment": "2.5 MiB of a secret file: 1 MiB, 1 MiB, 0.5 MiB", + "flags": [ + "SecretFixed" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "secret", + "dataKey": "d2c23768522e4167fbc3e434ad42d35259735aedbbff4f50f6045a54ecac518f", + "length": 2621440 + }, + "expect": "Ok", + "lengths": [ + 1048576, + 1048576, + 524288 + ] + }, + { + "tcId": 14, + "comment": "the 8 MiB of random data in a secret file: eight 1 MiB chunks", + "flags": [ + "SecretFixed" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "secret", + "dataKey": "d2c23768522e4167fbc3e434ad42d35259735aedbbff4f50f6045a54ecac518f", + "length": 8388608 + }, + "expect": "Ok", + "lengths": [ + 1048576, + 1048576, + 1048576, + 1048576, + 1048576, + 1048576, + 1048576, + 1048576 + ] + }, + { + "tcId": 15, + "comment": "an odd last byte whose hash matches the mask is never tested: one chunk", + "flags": [ + "CutEdges" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "dataKey": "f90f58080c4d1b5c906a30b1e7e63fbf5ccaf5c283b21cb2cca492d6724791e7", + "length": 65539 + }, + "expect": "Ok", + "lengths": [ + 65539 + ] + }, + { + "tcId": 16, + "comment": "a cut at exactly the 64 KiB minimum, the first position tested", + "flags": [ + "CutEdges" + ], + "inputs": { + "chunkerSeed": "a2abdf58a13fde98b9ee260a4bc7853aefe32b35d7653f0ad1c177229bd1caf4", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "dataKey": "a4ad1ae84f0429525aa7f657fa652f10305748c1a587484ef915f960644ba8cc", + "length": 196608 + }, + "expect": "Ok", + "lengths": [ + 65536, + 78742, + 52330 + ] + }, + { + "tcId": 17, + "comment": "a cut at the minimum plus one, the second byte of the first pair", + "flags": [ + "CutEdges" + ], + "inputs": { + "chunkerSeed": "7dce5f294c433a5b6216dc90e306a1604da6aa635f0b560bff0d4e33f0e9a9e7", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "dataKey": "565b19c1f16554631399274cc5a80289b7dfa4b7ea23f5621592502db2e8fe45", + "length": 196608 + }, + "expect": "Ok", + "lengths": [ + 65537, + 131071 + ] + }, + { + "tcId": 18, + "comment": "a cut at 256 KiB, the first position under the loose mask; the strict mask does not match there", + "flags": [ + "CutEdges" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "dataKey": "be3f494c9addf7356a68aa0fd42f2d85e02480bda7b18e507bf840c94447bca7", + "length": 786432 + }, + "expect": "Ok", + "lengths": [ + 262144, + 468804, + 55484 + ] + }, + { + "tcId": 19, + "comment": "the loose mask would match at 256 KiB - 1, the last position under the strict mask: no cut there", + "flags": [ + "CutEdges" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "dataKey": "8df60ac35644447968278a29e1d1b5d2dee6717dd3329f0fd78bc050689db00d", + "length": 786432 + }, + "expect": "Ok", + "lengths": [ + 322221, + 290746, + 173465 + ] + }, + { + "tcId": 20, + "comment": "a strict match at strict_end - 1, the last position tested: a one-byte last chunk", + "flags": [ + "CutEdges" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "dataKey": "58c5b09fe8e47247677d4c1e911214d65103879481497b440cb67ddc19b04299", + "length": 125154 + }, + "expect": "Ok", + "lengths": [ + 125153, + 1 + ] + }, + { + "tcId": 21, + "comment": "a 1,021-byte random pattern repeated over 2 MiB + 5 bytes: no position matches, cut at the 1 MiB maximum", + "flags": [ + "CutEdges" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "pattern": "07265496dd9ddd4288540e006a37e4827b6c5c27f8431e16fb2237f79dfdf8c1c3a80ffa0afeda75d5c2359c21975402d8b410708bf96983b6cdf34d453c83c712f5bfe042891e99d75f69c456d3a1c09324e1b9ade422a3e7aefde84783b236089c7eec04bdcd61508ad07879cbb3e22744da89cbf7b299f73d3b35471ea080eddc5c561cde58961c69a43f7b6bac529b7016ed2b2047d439f53b89f8a712e669e2c1a9e67d16ce74410695209e74bb82b5e5325ef87c760ee9463ee9cb68ad76d69ec7f0970cfc86a3cb52f6caa7f2f53abb476d785971c133549acecf8ccbcf042c9d1d00dd9405247fbedb448abd6455c3c711b028183678bb99aed069d704d8e3d6cf9ba1bb3bc879d6991912dc938b02b946f58f30f8355b637f972992404ad60ba7375417f04eb57583408cfec39547b2f0a7712dd984952b35615f5105486dd9c02478fc724be90686d47a57c5919179d8f3a8a2cc5554eb5adc033c8d8f68e9292f21cf846cf164ae388bd935cc912ca169219f3a8e4c67c210226a28eec6af778ee3dde6300c133e2595975b39e8593d10ba930ffab4bda91bec56be4b37fb96bba7cbda87d886dd40c1dce41c52a2576fce4ab76321acae791e7134fab129b3f891569d313cd84f7d389c7524e2a8ffdabaadd8182cc66fedcd726904443cf84518e654649e50cfe7778434d6dafa071f87642b3b7ed05ad96d57064cc1accf031ffe41972fe3988d232fa689d3da58613593d3f46fde916fe644b0ad4d9de51cdbfe971b3d8020f6dadba661e552e285f72369d4d861916b79111ad0cb36763e736200cbd6f5baf3d87584fa66adb231cc1f99464401e494d1041f252821e529543fc27d79f5431b950e3eae950fb6392162fef66a534772f89af678b5607e84f7c00c65a4ddf55ec1a701af440b0f22cf262dc54b18feaf1600692a3ae0458e2b7b8059c3e6617794f8643f12d8c7bd8e2a8b5ce0ae4a1c375c95d9639f52147ca9310546c4609c2db05c8d7a86263486116c50b62c74c9899887d8a5598443b76125a4450b4e4cf03194471636245415f8ba2ae31150b9e627520759619084a22315848d5081d24504ed96d47de46f683e2f438f8dae6a9c8b66d1c1506d9f7487bd22634f93aaf10cdff2159bafc3bb1257f63e4b30f9e9fdfe80a1b6f4465be04d16fdc75d5410e715971fa661f0098f7aebb6c35472d3682457a0b1f532e914bcec7d96e150d64ffc49a12e492e55a94d62a7a7686bf3c453961280da565c148dc711dc0190def515dc0aa4e16edd3d1c6844529254f9a259145d8bfb14fb1b13646d51089a84f4d06d4f380cd9d3347a42cd6d42dccc81482971caa425dccadc4152f2aea04861c734fa8eb408def6a9b5ade75290cdb52dd38d72638d33bac6c5de42c7d6d52f1abeabc8774920d678d5813234", + "length": 2097157 + }, + "expect": "Ok", + "lengths": [ + 1048576, + 1048576, + 5 + ] + } + ] + }, + { + "type": "Padme", + "tests": [ + { + "tcId": 22, + "comment": "0 stays 0", + "flags": [ + "Padme" + ], + "inputs": { + "length": 0 + }, + "expect": "Ok", + "padded": 0 + }, + { + "tcId": 23, + "comment": "1 stays 1", + "flags": [ + "Padme" + ], + "inputs": { + "length": 1 + }, + "expect": "Ok", + "padded": 1 + }, + { + "tcId": 24, + "comment": "2 stays 2", + "flags": [ + "Padme" + ], + "inputs": { + "length": 2 + }, + "expect": "Ok", + "padded": 2 + }, + { + "tcId": 25, + "comment": "7 stays 7", + "flags": [ + "Padme" + ], + "inputs": { + "length": 7 + }, + "expect": "Ok", + "padded": 7 + }, + { + "tcId": 26, + "comment": "9 rounds to 10", + "flags": [ + "Padme" + ], + "inputs": { + "length": 9 + }, + "expect": "Ok", + "padded": 10 + }, + { + "tcId": 27, + "comment": "an empty payload: 6", + "flags": [ + "Padme" + ], + "inputs": { + "length": 6 + }, + "expect": "Ok", + "padded": 6 + }, + { + "tcId": 28, + "comment": "a 1,000-byte payload: 1,006", + "flags": [ + "Padme" + ], + "inputs": { + "length": 1006 + }, + "expect": "Ok", + "padded": 1024 + }, + { + "tcId": 29, + "comment": "1,025 rounds to a multiple of 64", + "flags": [ + "Padme" + ], + "inputs": { + "length": 1025 + }, + "expect": "Ok", + "padded": 1088 + }, + { + "tcId": 30, + "comment": "a 64 KiB chunk: 65,542", + "flags": [ + "Padme" + ], + "inputs": { + "length": 65542 + }, + "expect": "Ok", + "padded": 67584 + }, + { + "tcId": 31, + "comment": "2^20 stays 2^20", + "flags": [ + "Padme" + ], + "inputs": { + "length": 1048576 + }, + "expect": "Ok", + "padded": 1048576 + }, + { + "tcId": 32, + "comment": "a 1 MiB payload: 2^20 + 6", + "flags": [ + "Padme" + ], + "inputs": { + "length": 1048582 + }, + "expect": "Ok", + "padded": 1081344 + }, + { + "tcId": 33, + "comment": "2^32 + 1", + "flags": [ + "Padme" + ], + "inputs": { + "length": 4294967297 + }, + "expect": "Ok", + "padded": 4362076160 + } + ] + }, + { + "type": "InnerDecode", + "tests": [ + { + "tcId": 34, + "comment": "an empty raw payload is the 6-byte header", + "flags": [ + "InnerOk" + ], + "inputs": { + "inner": "000000000000" + }, + "expect": "Ok", + "comp": 0, + "payload": "" + }, + { + "tcId": 35, + "comment": "a 3-byte zstd payload, padded to 10", + "flags": [ + "InnerOk" + ], + "inputs": { + "inner": "01000000000361626300" + }, + "expect": "Ok", + "comp": 1, + "payload": "616263" + }, + { + "tcId": 36, + "comment": "a 1,000-byte raw payload, padded to 1,024", + "flags": [ + "InnerOk" + ], + "inputs": { + "inner": "0000000003e8deb35e3b6d10702f893e1295fcdad375e60bfd4d121dc0dc9768779ea52879c6f5a542e4a07f05edc4f4e0a021382d8eaa9f965bcaa89e5992c6dfca97d315e08e8d7251e06816af999a194d94f432b1c67cc53ac7aa105b86ab351f172e8b878eb2d82af862887173ed55f85cd60022c4299e15ede66f1765f9d34f0bbea01d497f83978cfc8e5e9298fbee1cdb9ce0c76001fac6b06cb69c7b57d547f41b143180b08f5bcf701c0a4b465e450e49c304dcf9b50c548a35e859f319ea81ea72fd6d26d6a7a23fd73b127356266e3aae52fcdefc2e6c45156172eb895e550282035fca1cebab1dc572c336efb97eb97d749d7358f4978a6a8635a6de9477ce8ddc1d530bbdd9dab8f00a515143d907834c83a4e2eb6680d9383bf7cd40f1fb57ed30a31cd0b6f574001ee52e88a7e071e385303a32910f4c12b9213b06e529c8e36dacbb905e23da919e77cf286027194c3b652e5ff329a40bed31edc7c74d348aadf1e33b1d06d87cccf30d992deba8c8bfd626d5f243c94d1d3ec451101b6aebab66a79e345a88f8bb4c851464d85b035d6a2c8545a57bc304bb9740b7cb1db65719aa44839bb2aeca57bf854bdab161fc7f7525bbd674da950f42a12fd832b89db29a00dfb1d54177535edb436af98a6820a6b507a0f6c5bcd3cad852fbd3b428983945cec95ea2626475a79f5e5974421166644f24c80cd31be02d9176484f3382df8c1b4be3eb26cfea44d92911c8ba8620c63482b99d57039c490b62e090f5ef0b4b74d6a436fd169054d769e941d9a880e8efec07ec2edb6986707cf73798f3767ad814e2785e8a1abdd86ed3ca5b59442aa6f35a7d39c3ffb43d811ce580d245dc07d1e9dcf58c47dd49cedf9ea2973406bce9256b452e7b33614bd519c4240e786229e80546df779474ad89f69bf333363247725cc0fdaf240b5d8be5b858efc6574a25f6d8747bc38456fd0d2050b3502a812a9a870e36c8f5d5539f94ed7c57846539b5bf09302c6119784756c6daff14162bc59549ea0d154de113ae4bd8328c955e8ff761e0dec71cc0d614fa0ee8d86e26a550ad6d2f28c4a8ddcfb57aa644b22df158d31ed0b42612d610578c636a4233b2102f9e1574b7a06af35a838e6170061b06b34370385f5733646d2fc582ce82faa0a47c603af179f7480712d6fc056e318bb7e44c154268fcb6ef86686171b94771f12c744e1f6d8cb10d52ea446ce55e5bf669eb6c34e5a49d3a6ccac14d95bc4b06cc5c2b690f19178a30c33e6ac42908e69651a945a35873fb790758cc03201814ba668c63b3635cf2141939907d29fd060bb2a94c00b93b178cda8bc648d7ee9e36b6c2aeda553c18e325ab69692d818011ffe5e4b121818cef244d4639bbf3426eea34b8526570791859c0aa14000000000000000000000000000000000000" + }, + "expect": "Ok", + "comp": 0, + "payload": "deb35e3b6d10702f893e1295fcdad375e60bfd4d121dc0dc9768779ea52879c6f5a542e4a07f05edc4f4e0a021382d8eaa9f965bcaa89e5992c6dfca97d315e08e8d7251e06816af999a194d94f432b1c67cc53ac7aa105b86ab351f172e8b878eb2d82af862887173ed55f85cd60022c4299e15ede66f1765f9d34f0bbea01d497f83978cfc8e5e9298fbee1cdb9ce0c76001fac6b06cb69c7b57d547f41b143180b08f5bcf701c0a4b465e450e49c304dcf9b50c548a35e859f319ea81ea72fd6d26d6a7a23fd73b127356266e3aae52fcdefc2e6c45156172eb895e550282035fca1cebab1dc572c336efb97eb97d749d7358f4978a6a8635a6de9477ce8ddc1d530bbdd9dab8f00a515143d907834c83a4e2eb6680d9383bf7cd40f1fb57ed30a31cd0b6f574001ee52e88a7e071e385303a32910f4c12b9213b06e529c8e36dacbb905e23da919e77cf286027194c3b652e5ff329a40bed31edc7c74d348aadf1e33b1d06d87cccf30d992deba8c8bfd626d5f243c94d1d3ec451101b6aebab66a79e345a88f8bb4c851464d85b035d6a2c8545a57bc304bb9740b7cb1db65719aa44839bb2aeca57bf854bdab161fc7f7525bbd674da950f42a12fd832b89db29a00dfb1d54177535edb436af98a6820a6b507a0f6c5bcd3cad852fbd3b428983945cec95ea2626475a79f5e5974421166644f24c80cd31be02d9176484f3382df8c1b4be3eb26cfea44d92911c8ba8620c63482b99d57039c490b62e090f5ef0b4b74d6a436fd169054d769e941d9a880e8efec07ec2edb6986707cf73798f3767ad814e2785e8a1abdd86ed3ca5b59442aa6f35a7d39c3ffb43d811ce580d245dc07d1e9dcf58c47dd49cedf9ea2973406bce9256b452e7b33614bd519c4240e786229e80546df779474ad89f69bf333363247725cc0fdaf240b5d8be5b858efc6574a25f6d8747bc38456fd0d2050b3502a812a9a870e36c8f5d5539f94ed7c57846539b5bf09302c6119784756c6daff14162bc59549ea0d154de113ae4bd8328c955e8ff761e0dec71cc0d614fa0ee8d86e26a550ad6d2f28c4a8ddcfb57aa644b22df158d31ed0b42612d610578c636a4233b2102f9e1574b7a06af35a838e6170061b06b34370385f5733646d2fc582ce82faa0a47c603af179f7480712d6fc056e318bb7e44c154268fcb6ef86686171b94771f12c744e1f6d8cb10d52ea446ce55e5bf669eb6c34e5a49d3a6ccac14d95bc4b06cc5c2b690f19178a30c33e6ac42908e69651a945a35873fb790758cc03201814ba668c63b3635cf2141939907d29fd060bb2a94c00b93b178cda8bc648d7ee9e36b6c2aeda553c18e325ab69692d818011ffe5e4b121818cef244d4639bbf3426eea34b8526570791859c0aa14" + }, + { + "tcId": 37, + "comment": "a payload of exactly 1 MiB", + "flags": [ + "InnerLimit" + ], + "inputs": { + "header": "000000100000", + "dataKey": "79c06b0fe0888cc9ed4bf15860a6a2547cce51bf758f23a4788776e16d1d49ec", + "length": 1048576, + "padLength": 32762 + }, + "expect": "Ok", + "comp": 0 + }, + { + "tcId": 38, + "comment": "payload_len 2^20 + 1", + "flags": [ + "InnerLimit" + ], + "inputs": { + "inner": "000000100001" + }, + "expect": "Limit" + }, + { + "tcId": 39, + "comment": "payload_len 2^32 - 1", + "flags": [ + "InnerLimit" + ], + "inputs": { + "inner": "0100ffffffff" + }, + "expect": "Limit" + }, + { + "tcId": 40, + "comment": "payload_len 2^20 with only the header", + "flags": [ + "InnerPadding" + ], + "inputs": { + "inner": "000000100000" + }, + "expect": "Padding" + }, + { + "tcId": 41, + "comment": "no bytes", + "flags": [ + "InnerPadding" + ], + "inputs": { + "inner": "" + }, + "expect": "Padding" + }, + { + "tcId": 42, + "comment": "five bytes, one short of a header", + "flags": [ + "InnerPadding" + ], + "inputs": { + "inner": "0000000000" + }, + "expect": "Padding" + }, + { + "tcId": 43, + "comment": "comp 2", + "flags": [ + "InnerPadding" + ], + "inputs": { + "inner": "0200000003e8deb35e3b6d10702f893e1295fcdad375e60bfd4d121dc0dc9768779ea52879c6f5a542e4a07f05edc4f4e0a021382d8eaa9f965bcaa89e5992c6dfca97d315e08e8d7251e06816af999a194d94f432b1c67cc53ac7aa105b86ab351f172e8b878eb2d82af862887173ed55f85cd60022c4299e15ede66f1765f9d34f0bbea01d497f83978cfc8e5e9298fbee1cdb9ce0c76001fac6b06cb69c7b57d547f41b143180b08f5bcf701c0a4b465e450e49c304dcf9b50c548a35e859f319ea81ea72fd6d26d6a7a23fd73b127356266e3aae52fcdefc2e6c45156172eb895e550282035fca1cebab1dc572c336efb97eb97d749d7358f4978a6a8635a6de9477ce8ddc1d530bbdd9dab8f00a515143d907834c83a4e2eb6680d9383bf7cd40f1fb57ed30a31cd0b6f574001ee52e88a7e071e385303a32910f4c12b9213b06e529c8e36dacbb905e23da919e77cf286027194c3b652e5ff329a40bed31edc7c74d348aadf1e33b1d06d87cccf30d992deba8c8bfd626d5f243c94d1d3ec451101b6aebab66a79e345a88f8bb4c851464d85b035d6a2c8545a57bc304bb9740b7cb1db65719aa44839bb2aeca57bf854bdab161fc7f7525bbd674da950f42a12fd832b89db29a00dfb1d54177535edb436af98a6820a6b507a0f6c5bcd3cad852fbd3b428983945cec95ea2626475a79f5e5974421166644f24c80cd31be02d9176484f3382df8c1b4be3eb26cfea44d92911c8ba8620c63482b99d57039c490b62e090f5ef0b4b74d6a436fd169054d769e941d9a880e8efec07ec2edb6986707cf73798f3767ad814e2785e8a1abdd86ed3ca5b59442aa6f35a7d39c3ffb43d811ce580d245dc07d1e9dcf58c47dd49cedf9ea2973406bce9256b452e7b33614bd519c4240e786229e80546df779474ad89f69bf333363247725cc0fdaf240b5d8be5b858efc6574a25f6d8747bc38456fd0d2050b3502a812a9a870e36c8f5d5539f94ed7c57846539b5bf09302c6119784756c6daff14162bc59549ea0d154de113ae4bd8328c955e8ff761e0dec71cc0d614fa0ee8d86e26a550ad6d2f28c4a8ddcfb57aa644b22df158d31ed0b42612d610578c636a4233b2102f9e1574b7a06af35a838e6170061b06b34370385f5733646d2fc582ce82faa0a47c603af179f7480712d6fc056e318bb7e44c154268fcb6ef86686171b94771f12c744e1f6d8cb10d52ea446ce55e5bf669eb6c34e5a49d3a6ccac14d95bc4b06cc5c2b690f19178a30c33e6ac42908e69651a945a35873fb790758cc03201814ba668c63b3635cf2141939907d29fd060bb2a94c00b93b178cda8bc648d7ee9e36b6c2aeda553c18e325ab69692d818011ffe5e4b121818cef244d4639bbf3426eea34b8526570791859c0aa14000000000000000000000000000000000000" + }, + "expect": "Padding" + }, + { + "tcId": 44, + "comment": "comp 255", + "flags": [ + "InnerPadding" + ], + "inputs": { + "inner": "ff00000003e8deb35e3b6d10702f893e1295fcdad375e60bfd4d121dc0dc9768779ea52879c6f5a542e4a07f05edc4f4e0a021382d8eaa9f965bcaa89e5992c6dfca97d315e08e8d7251e06816af999a194d94f432b1c67cc53ac7aa105b86ab351f172e8b878eb2d82af862887173ed55f85cd60022c4299e15ede66f1765f9d34f0bbea01d497f83978cfc8e5e9298fbee1cdb9ce0c76001fac6b06cb69c7b57d547f41b143180b08f5bcf701c0a4b465e450e49c304dcf9b50c548a35e859f319ea81ea72fd6d26d6a7a23fd73b127356266e3aae52fcdefc2e6c45156172eb895e550282035fca1cebab1dc572c336efb97eb97d749d7358f4978a6a8635a6de9477ce8ddc1d530bbdd9dab8f00a515143d907834c83a4e2eb6680d9383bf7cd40f1fb57ed30a31cd0b6f574001ee52e88a7e071e385303a32910f4c12b9213b06e529c8e36dacbb905e23da919e77cf286027194c3b652e5ff329a40bed31edc7c74d348aadf1e33b1d06d87cccf30d992deba8c8bfd626d5f243c94d1d3ec451101b6aebab66a79e345a88f8bb4c851464d85b035d6a2c8545a57bc304bb9740b7cb1db65719aa44839bb2aeca57bf854bdab161fc7f7525bbd674da950f42a12fd832b89db29a00dfb1d54177535edb436af98a6820a6b507a0f6c5bcd3cad852fbd3b428983945cec95ea2626475a79f5e5974421166644f24c80cd31be02d9176484f3382df8c1b4be3eb26cfea44d92911c8ba8620c63482b99d57039c490b62e090f5ef0b4b74d6a436fd169054d769e941d9a880e8efec07ec2edb6986707cf73798f3767ad814e2785e8a1abdd86ed3ca5b59442aa6f35a7d39c3ffb43d811ce580d245dc07d1e9dcf58c47dd49cedf9ea2973406bce9256b452e7b33614bd519c4240e786229e80546df779474ad89f69bf333363247725cc0fdaf240b5d8be5b858efc6574a25f6d8747bc38456fd0d2050b3502a812a9a870e36c8f5d5539f94ed7c57846539b5bf09302c6119784756c6daff14162bc59549ea0d154de113ae4bd8328c955e8ff761e0dec71cc0d614fa0ee8d86e26a550ad6d2f28c4a8ddcfb57aa644b22df158d31ed0b42612d610578c636a4233b2102f9e1574b7a06af35a838e6170061b06b34370385f5733646d2fc582ce82faa0a47c603af179f7480712d6fc056e318bb7e44c154268fcb6ef86686171b94771f12c744e1f6d8cb10d52ea446ce55e5bf669eb6c34e5a49d3a6ccac14d95bc4b06cc5c2b690f19178a30c33e6ac42908e69651a945a35873fb790758cc03201814ba668c63b3635cf2141939907d29fd060bb2a94c00b93b178cda8bc648d7ee9e36b6c2aeda553c18e325ab69692d818011ffe5e4b121818cef244d4639bbf3426eea34b8526570791859c0aa14000000000000000000000000000000000000" + }, + "expect": "Padding" + }, + { + "tcId": 45, + "comment": "rsv 1", + "flags": [ + "InnerPadding" + ], + "inputs": { + "inner": "0001000003e8deb35e3b6d10702f893e1295fcdad375e60bfd4d121dc0dc9768779ea52879c6f5a542e4a07f05edc4f4e0a021382d8eaa9f965bcaa89e5992c6dfca97d315e08e8d7251e06816af999a194d94f432b1c67cc53ac7aa105b86ab351f172e8b878eb2d82af862887173ed55f85cd60022c4299e15ede66f1765f9d34f0bbea01d497f83978cfc8e5e9298fbee1cdb9ce0c76001fac6b06cb69c7b57d547f41b143180b08f5bcf701c0a4b465e450e49c304dcf9b50c548a35e859f319ea81ea72fd6d26d6a7a23fd73b127356266e3aae52fcdefc2e6c45156172eb895e550282035fca1cebab1dc572c336efb97eb97d749d7358f4978a6a8635a6de9477ce8ddc1d530bbdd9dab8f00a515143d907834c83a4e2eb6680d9383bf7cd40f1fb57ed30a31cd0b6f574001ee52e88a7e071e385303a32910f4c12b9213b06e529c8e36dacbb905e23da919e77cf286027194c3b652e5ff329a40bed31edc7c74d348aadf1e33b1d06d87cccf30d992deba8c8bfd626d5f243c94d1d3ec451101b6aebab66a79e345a88f8bb4c851464d85b035d6a2c8545a57bc304bb9740b7cb1db65719aa44839bb2aeca57bf854bdab161fc7f7525bbd674da950f42a12fd832b89db29a00dfb1d54177535edb436af98a6820a6b507a0f6c5bcd3cad852fbd3b428983945cec95ea2626475a79f5e5974421166644f24c80cd31be02d9176484f3382df8c1b4be3eb26cfea44d92911c8ba8620c63482b99d57039c490b62e090f5ef0b4b74d6a436fd169054d769e941d9a880e8efec07ec2edb6986707cf73798f3767ad814e2785e8a1abdd86ed3ca5b59442aa6f35a7d39c3ffb43d811ce580d245dc07d1e9dcf58c47dd49cedf9ea2973406bce9256b452e7b33614bd519c4240e786229e80546df779474ad89f69bf333363247725cc0fdaf240b5d8be5b858efc6574a25f6d8747bc38456fd0d2050b3502a812a9a870e36c8f5d5539f94ed7c57846539b5bf09302c6119784756c6daff14162bc59549ea0d154de113ae4bd8328c955e8ff761e0dec71cc0d614fa0ee8d86e26a550ad6d2f28c4a8ddcfb57aa644b22df158d31ed0b42612d610578c636a4233b2102f9e1574b7a06af35a838e6170061b06b34370385f5733646d2fc582ce82faa0a47c603af179f7480712d6fc056e318bb7e44c154268fcb6ef86686171b94771f12c744e1f6d8cb10d52ea446ce55e5bf669eb6c34e5a49d3a6ccac14d95bc4b06cc5c2b690f19178a30c33e6ac42908e69651a945a35873fb790758cc03201814ba668c63b3635cf2141939907d29fd060bb2a94c00b93b178cda8bc648d7ee9e36b6c2aeda553c18e325ab69692d818011ffe5e4b121818cef244d4639bbf3426eea34b8526570791859c0aa14000000000000000000000000000000000000" + }, + "expect": "Padding" + }, + { + "tcId": 46, + "comment": "rsv 0x80", + "flags": [ + "InnerPadding" + ], + "inputs": { + "inner": "0080000003e8deb35e3b6d10702f893e1295fcdad375e60bfd4d121dc0dc9768779ea52879c6f5a542e4a07f05edc4f4e0a021382d8eaa9f965bcaa89e5992c6dfca97d315e08e8d7251e06816af999a194d94f432b1c67cc53ac7aa105b86ab351f172e8b878eb2d82af862887173ed55f85cd60022c4299e15ede66f1765f9d34f0bbea01d497f83978cfc8e5e9298fbee1cdb9ce0c76001fac6b06cb69c7b57d547f41b143180b08f5bcf701c0a4b465e450e49c304dcf9b50c548a35e859f319ea81ea72fd6d26d6a7a23fd73b127356266e3aae52fcdefc2e6c45156172eb895e550282035fca1cebab1dc572c336efb97eb97d749d7358f4978a6a8635a6de9477ce8ddc1d530bbdd9dab8f00a515143d907834c83a4e2eb6680d9383bf7cd40f1fb57ed30a31cd0b6f574001ee52e88a7e071e385303a32910f4c12b9213b06e529c8e36dacbb905e23da919e77cf286027194c3b652e5ff329a40bed31edc7c74d348aadf1e33b1d06d87cccf30d992deba8c8bfd626d5f243c94d1d3ec451101b6aebab66a79e345a88f8bb4c851464d85b035d6a2c8545a57bc304bb9740b7cb1db65719aa44839bb2aeca57bf854bdab161fc7f7525bbd674da950f42a12fd832b89db29a00dfb1d54177535edb436af98a6820a6b507a0f6c5bcd3cad852fbd3b428983945cec95ea2626475a79f5e5974421166644f24c80cd31be02d9176484f3382df8c1b4be3eb26cfea44d92911c8ba8620c63482b99d57039c490b62e090f5ef0b4b74d6a436fd169054d769e941d9a880e8efec07ec2edb6986707cf73798f3767ad814e2785e8a1abdd86ed3ca5b59442aa6f35a7d39c3ffb43d811ce580d245dc07d1e9dcf58c47dd49cedf9ea2973406bce9256b452e7b33614bd519c4240e786229e80546df779474ad89f69bf333363247725cc0fdaf240b5d8be5b858efc6574a25f6d8747bc38456fd0d2050b3502a812a9a870e36c8f5d5539f94ed7c57846539b5bf09302c6119784756c6daff14162bc59549ea0d154de113ae4bd8328c955e8ff761e0dec71cc0d614fa0ee8d86e26a550ad6d2f28c4a8ddcfb57aa644b22df158d31ed0b42612d610578c636a4233b2102f9e1574b7a06af35a838e6170061b06b34370385f5733646d2fc582ce82faa0a47c603af179f7480712d6fc056e318bb7e44c154268fcb6ef86686171b94771f12c744e1f6d8cb10d52ea446ce55e5bf669eb6c34e5a49d3a6ccac14d95bc4b06cc5c2b690f19178a30c33e6ac42908e69651a945a35873fb790758cc03201814ba668c63b3635cf2141939907d29fd060bb2a94c00b93b178cda8bc648d7ee9e36b6c2aeda553c18e325ab69692d818011ffe5e4b121818cef244d4639bbf3426eea34b8526570791859c0aa14000000000000000000000000000000000000" + }, + "expect": "Padding" + }, + { + "tcId": 47, + "comment": "the first pad byte is not zero", + "flags": [ + "InnerPadding" + ], + "inputs": { + "inner": "0000000003e8deb35e3b6d10702f893e1295fcdad375e60bfd4d121dc0dc9768779ea52879c6f5a542e4a07f05edc4f4e0a021382d8eaa9f965bcaa89e5992c6dfca97d315e08e8d7251e06816af999a194d94f432b1c67cc53ac7aa105b86ab351f172e8b878eb2d82af862887173ed55f85cd60022c4299e15ede66f1765f9d34f0bbea01d497f83978cfc8e5e9298fbee1cdb9ce0c76001fac6b06cb69c7b57d547f41b143180b08f5bcf701c0a4b465e450e49c304dcf9b50c548a35e859f319ea81ea72fd6d26d6a7a23fd73b127356266e3aae52fcdefc2e6c45156172eb895e550282035fca1cebab1dc572c336efb97eb97d749d7358f4978a6a8635a6de9477ce8ddc1d530bbdd9dab8f00a515143d907834c83a4e2eb6680d9383bf7cd40f1fb57ed30a31cd0b6f574001ee52e88a7e071e385303a32910f4c12b9213b06e529c8e36dacbb905e23da919e77cf286027194c3b652e5ff329a40bed31edc7c74d348aadf1e33b1d06d87cccf30d992deba8c8bfd626d5f243c94d1d3ec451101b6aebab66a79e345a88f8bb4c851464d85b035d6a2c8545a57bc304bb9740b7cb1db65719aa44839bb2aeca57bf854bdab161fc7f7525bbd674da950f42a12fd832b89db29a00dfb1d54177535edb436af98a6820a6b507a0f6c5bcd3cad852fbd3b428983945cec95ea2626475a79f5e5974421166644f24c80cd31be02d9176484f3382df8c1b4be3eb26cfea44d92911c8ba8620c63482b99d57039c490b62e090f5ef0b4b74d6a436fd169054d769e941d9a880e8efec07ec2edb6986707cf73798f3767ad814e2785e8a1abdd86ed3ca5b59442aa6f35a7d39c3ffb43d811ce580d245dc07d1e9dcf58c47dd49cedf9ea2973406bce9256b452e7b33614bd519c4240e786229e80546df779474ad89f69bf333363247725cc0fdaf240b5d8be5b858efc6574a25f6d8747bc38456fd0d2050b3502a812a9a870e36c8f5d5539f94ed7c57846539b5bf09302c6119784756c6daff14162bc59549ea0d154de113ae4bd8328c955e8ff761e0dec71cc0d614fa0ee8d86e26a550ad6d2f28c4a8ddcfb57aa644b22df158d31ed0b42612d610578c636a4233b2102f9e1574b7a06af35a838e6170061b06b34370385f5733646d2fc582ce82faa0a47c603af179f7480712d6fc056e318bb7e44c154268fcb6ef86686171b94771f12c744e1f6d8cb10d52ea446ce55e5bf669eb6c34e5a49d3a6ccac14d95bc4b06cc5c2b690f19178a30c33e6ac42908e69651a945a35873fb790758cc03201814ba668c63b3635cf2141939907d29fd060bb2a94c00b93b178cda8bc648d7ee9e36b6c2aeda553c18e325ab69692d818011ffe5e4b121818cef244d4639bbf3426eea34b8526570791859c0aa14010000000000000000000000000000000000" + }, + "expect": "Padding" + }, + { + "tcId": 48, + "comment": "the last pad byte is not zero", + "flags": [ + "InnerPadding" + ], + "inputs": { + "inner": "0000000003e8deb35e3b6d10702f893e1295fcdad375e60bfd4d121dc0dc9768779ea52879c6f5a542e4a07f05edc4f4e0a021382d8eaa9f965bcaa89e5992c6dfca97d315e08e8d7251e06816af999a194d94f432b1c67cc53ac7aa105b86ab351f172e8b878eb2d82af862887173ed55f85cd60022c4299e15ede66f1765f9d34f0bbea01d497f83978cfc8e5e9298fbee1cdb9ce0c76001fac6b06cb69c7b57d547f41b143180b08f5bcf701c0a4b465e450e49c304dcf9b50c548a35e859f319ea81ea72fd6d26d6a7a23fd73b127356266e3aae52fcdefc2e6c45156172eb895e550282035fca1cebab1dc572c336efb97eb97d749d7358f4978a6a8635a6de9477ce8ddc1d530bbdd9dab8f00a515143d907834c83a4e2eb6680d9383bf7cd40f1fb57ed30a31cd0b6f574001ee52e88a7e071e385303a32910f4c12b9213b06e529c8e36dacbb905e23da919e77cf286027194c3b652e5ff329a40bed31edc7c74d348aadf1e33b1d06d87cccf30d992deba8c8bfd626d5f243c94d1d3ec451101b6aebab66a79e345a88f8bb4c851464d85b035d6a2c8545a57bc304bb9740b7cb1db65719aa44839bb2aeca57bf854bdab161fc7f7525bbd674da950f42a12fd832b89db29a00dfb1d54177535edb436af98a6820a6b507a0f6c5bcd3cad852fbd3b428983945cec95ea2626475a79f5e5974421166644f24c80cd31be02d9176484f3382df8c1b4be3eb26cfea44d92911c8ba8620c63482b99d57039c490b62e090f5ef0b4b74d6a436fd169054d769e941d9a880e8efec07ec2edb6986707cf73798f3767ad814e2785e8a1abdd86ed3ca5b59442aa6f35a7d39c3ffb43d811ce580d245dc07d1e9dcf58c47dd49cedf9ea2973406bce9256b452e7b33614bd519c4240e786229e80546df779474ad89f69bf333363247725cc0fdaf240b5d8be5b858efc6574a25f6d8747bc38456fd0d2050b3502a812a9a870e36c8f5d5539f94ed7c57846539b5bf09302c6119784756c6daff14162bc59549ea0d154de113ae4bd8328c955e8ff761e0dec71cc0d614fa0ee8d86e26a550ad6d2f28c4a8ddcfb57aa644b22df158d31ed0b42612d610578c636a4233b2102f9e1574b7a06af35a838e6170061b06b34370385f5733646d2fc582ce82faa0a47c603af179f7480712d6fc056e318bb7e44c154268fcb6ef86686171b94771f12c744e1f6d8cb10d52ea446ce55e5bf669eb6c34e5a49d3a6ccac14d95bc4b06cc5c2b690f19178a30c33e6ac42908e69651a945a35873fb790758cc03201814ba668c63b3635cf2141939907d29fd060bb2a94c00b93b178cda8bc648d7ee9e36b6c2aeda553c18e325ab69692d818011ffe5e4b121818cef244d4639bbf3426eea34b8526570791859c0aa14000000000000000000000000000000000080" + }, + "expect": "Padding" + }, + { + "tcId": 49, + "comment": "one byte longer than padme(6 + payload_len)", + "flags": [ + "InnerPadding" + ], + "inputs": { + "inner": "0000000003e8deb35e3b6d10702f893e1295fcdad375e60bfd4d121dc0dc9768779ea52879c6f5a542e4a07f05edc4f4e0a021382d8eaa9f965bcaa89e5992c6dfca97d315e08e8d7251e06816af999a194d94f432b1c67cc53ac7aa105b86ab351f172e8b878eb2d82af862887173ed55f85cd60022c4299e15ede66f1765f9d34f0bbea01d497f83978cfc8e5e9298fbee1cdb9ce0c76001fac6b06cb69c7b57d547f41b143180b08f5bcf701c0a4b465e450e49c304dcf9b50c548a35e859f319ea81ea72fd6d26d6a7a23fd73b127356266e3aae52fcdefc2e6c45156172eb895e550282035fca1cebab1dc572c336efb97eb97d749d7358f4978a6a8635a6de9477ce8ddc1d530bbdd9dab8f00a515143d907834c83a4e2eb6680d9383bf7cd40f1fb57ed30a31cd0b6f574001ee52e88a7e071e385303a32910f4c12b9213b06e529c8e36dacbb905e23da919e77cf286027194c3b652e5ff329a40bed31edc7c74d348aadf1e33b1d06d87cccf30d992deba8c8bfd626d5f243c94d1d3ec451101b6aebab66a79e345a88f8bb4c851464d85b035d6a2c8545a57bc304bb9740b7cb1db65719aa44839bb2aeca57bf854bdab161fc7f7525bbd674da950f42a12fd832b89db29a00dfb1d54177535edb436af98a6820a6b507a0f6c5bcd3cad852fbd3b428983945cec95ea2626475a79f5e5974421166644f24c80cd31be02d9176484f3382df8c1b4be3eb26cfea44d92911c8ba8620c63482b99d57039c490b62e090f5ef0b4b74d6a436fd169054d769e941d9a880e8efec07ec2edb6986707cf73798f3767ad814e2785e8a1abdd86ed3ca5b59442aa6f35a7d39c3ffb43d811ce580d245dc07d1e9dcf58c47dd49cedf9ea2973406bce9256b452e7b33614bd519c4240e786229e80546df779474ad89f69bf333363247725cc0fdaf240b5d8be5b858efc6574a25f6d8747bc38456fd0d2050b3502a812a9a870e36c8f5d5539f94ed7c57846539b5bf09302c6119784756c6daff14162bc59549ea0d154de113ae4bd8328c955e8ff761e0dec71cc0d614fa0ee8d86e26a550ad6d2f28c4a8ddcfb57aa644b22df158d31ed0b42612d610578c636a4233b2102f9e1574b7a06af35a838e6170061b06b34370385f5733646d2fc582ce82faa0a47c603af179f7480712d6fc056e318bb7e44c154268fcb6ef86686171b94771f12c744e1f6d8cb10d52ea446ce55e5bf669eb6c34e5a49d3a6ccac14d95bc4b06cc5c2b690f19178a30c33e6ac42908e69651a945a35873fb790758cc03201814ba668c63b3635cf2141939907d29fd060bb2a94c00b93b178cda8bc648d7ee9e36b6c2aeda553c18e325ab69692d818011ffe5e4b121818cef244d4639bbf3426eea34b8526570791859c0aa1400000000000000000000000000000000000000" + }, + "expect": "Padding" + }, + { + "tcId": 50, + "comment": "one byte shorter than padme(6 + payload_len)", + "flags": [ + "InnerPadding" + ], + "inputs": { + "inner": "0000000003e8deb35e3b6d10702f893e1295fcdad375e60bfd4d121dc0dc9768779ea52879c6f5a542e4a07f05edc4f4e0a021382d8eaa9f965bcaa89e5992c6dfca97d315e08e8d7251e06816af999a194d94f432b1c67cc53ac7aa105b86ab351f172e8b878eb2d82af862887173ed55f85cd60022c4299e15ede66f1765f9d34f0bbea01d497f83978cfc8e5e9298fbee1cdb9ce0c76001fac6b06cb69c7b57d547f41b143180b08f5bcf701c0a4b465e450e49c304dcf9b50c548a35e859f319ea81ea72fd6d26d6a7a23fd73b127356266e3aae52fcdefc2e6c45156172eb895e550282035fca1cebab1dc572c336efb97eb97d749d7358f4978a6a8635a6de9477ce8ddc1d530bbdd9dab8f00a515143d907834c83a4e2eb6680d9383bf7cd40f1fb57ed30a31cd0b6f574001ee52e88a7e071e385303a32910f4c12b9213b06e529c8e36dacbb905e23da919e77cf286027194c3b652e5ff329a40bed31edc7c74d348aadf1e33b1d06d87cccf30d992deba8c8bfd626d5f243c94d1d3ec451101b6aebab66a79e345a88f8bb4c851464d85b035d6a2c8545a57bc304bb9740b7cb1db65719aa44839bb2aeca57bf854bdab161fc7f7525bbd674da950f42a12fd832b89db29a00dfb1d54177535edb436af98a6820a6b507a0f6c5bcd3cad852fbd3b428983945cec95ea2626475a79f5e5974421166644f24c80cd31be02d9176484f3382df8c1b4be3eb26cfea44d92911c8ba8620c63482b99d57039c490b62e090f5ef0b4b74d6a436fd169054d769e941d9a880e8efec07ec2edb6986707cf73798f3767ad814e2785e8a1abdd86ed3ca5b59442aa6f35a7d39c3ffb43d811ce580d245dc07d1e9dcf58c47dd49cedf9ea2973406bce9256b452e7b33614bd519c4240e786229e80546df779474ad89f69bf333363247725cc0fdaf240b5d8be5b858efc6574a25f6d8747bc38456fd0d2050b3502a812a9a870e36c8f5d5539f94ed7c57846539b5bf09302c6119784756c6daff14162bc59549ea0d154de113ae4bd8328c955e8ff761e0dec71cc0d614fa0ee8d86e26a550ad6d2f28c4a8ddcfb57aa644b22df158d31ed0b42612d610578c636a4233b2102f9e1574b7a06af35a838e6170061b06b34370385f5733646d2fc582ce82faa0a47c603af179f7480712d6fc056e318bb7e44c154268fcb6ef86686171b94771f12c744e1f6d8cb10d52ea446ce55e5bf669eb6c34e5a49d3a6ccac14d95bc4b06cc5c2b690f19178a30c33e6ac42908e69651a945a35873fb790758cc03201814ba668c63b3635cf2141939907d29fd060bb2a94c00b93b178cda8bc648d7ee9e36b6c2aeda553c18e325ab69692d818011ffe5e4b121818cef244d4639bbf3426eea34b8526570791859c0aa140000000000000000000000000000000000" + }, + "expect": "Padding" + }, + { + "tcId": 51, + "comment": "no pad at all", + "flags": [ + "InnerPadding" + ], + "inputs": { + "inner": "0000000003e8deb35e3b6d10702f893e1295fcdad375e60bfd4d121dc0dc9768779ea52879c6f5a542e4a07f05edc4f4e0a021382d8eaa9f965bcaa89e5992c6dfca97d315e08e8d7251e06816af999a194d94f432b1c67cc53ac7aa105b86ab351f172e8b878eb2d82af862887173ed55f85cd60022c4299e15ede66f1765f9d34f0bbea01d497f83978cfc8e5e9298fbee1cdb9ce0c76001fac6b06cb69c7b57d547f41b143180b08f5bcf701c0a4b465e450e49c304dcf9b50c548a35e859f319ea81ea72fd6d26d6a7a23fd73b127356266e3aae52fcdefc2e6c45156172eb895e550282035fca1cebab1dc572c336efb97eb97d749d7358f4978a6a8635a6de9477ce8ddc1d530bbdd9dab8f00a515143d907834c83a4e2eb6680d9383bf7cd40f1fb57ed30a31cd0b6f574001ee52e88a7e071e385303a32910f4c12b9213b06e529c8e36dacbb905e23da919e77cf286027194c3b652e5ff329a40bed31edc7c74d348aadf1e33b1d06d87cccf30d992deba8c8bfd626d5f243c94d1d3ec451101b6aebab66a79e345a88f8bb4c851464d85b035d6a2c8545a57bc304bb9740b7cb1db65719aa44839bb2aeca57bf854bdab161fc7f7525bbd674da950f42a12fd832b89db29a00dfb1d54177535edb436af98a6820a6b507a0f6c5bcd3cad852fbd3b428983945cec95ea2626475a79f5e5974421166644f24c80cd31be02d9176484f3382df8c1b4be3eb26cfea44d92911c8ba8620c63482b99d57039c490b62e090f5ef0b4b74d6a436fd169054d769e941d9a880e8efec07ec2edb6986707cf73798f3767ad814e2785e8a1abdd86ed3ca5b59442aa6f35a7d39c3ffb43d811ce580d245dc07d1e9dcf58c47dd49cedf9ea2973406bce9256b452e7b33614bd519c4240e786229e80546df779474ad89f69bf333363247725cc0fdaf240b5d8be5b858efc6574a25f6d8747bc38456fd0d2050b3502a812a9a870e36c8f5d5539f94ed7c57846539b5bf09302c6119784756c6daff14162bc59549ea0d154de113ae4bd8328c955e8ff761e0dec71cc0d614fa0ee8d86e26a550ad6d2f28c4a8ddcfb57aa644b22df158d31ed0b42612d610578c636a4233b2102f9e1574b7a06af35a838e6170061b06b34370385f5733646d2fc582ce82faa0a47c603af179f7480712d6fc056e318bb7e44c154268fcb6ef86686171b94771f12c744e1f6d8cb10d52ea446ce55e5bf669eb6c34e5a49d3a6ccac14d95bc4b06cc5c2b690f19178a30c33e6ac42908e69651a945a35873fb790758cc03201814ba668c63b3635cf2141939907d29fd060bb2a94c00b93b178cda8bc648d7ee9e36b6c2aeda553c18e325ab69692d818011ffe5e4b121818cef244d4639bbf3426eea34b8526570791859c0aa14" + }, + "expect": "Padding" + }, + { + "tcId": 52, + "comment": "comp 2 with payload_len 2^20 + 1: comp is checked first", + "flags": [ + "CheckOrder" + ], + "inputs": { + "inner": "020000100001" + }, + "expect": "Padding" + }, + { + "tcId": 53, + "comment": "rsv 1 with payload_len 2^20 + 1: rsv is checked first", + "flags": [ + "CheckOrder" + ], + "inputs": { + "inner": "000100100001" + }, + "expect": "Padding" + } + ] + }, + { + "type": "Compress", + "tests": [ + { + "tcId": 54, + "comment": "1 MiB of zeros", + "flags": [ + "Compress" + ], + "inputs": { + "class": "ordinary", + "zeros": 1048576 + }, + "expect": "Ok", + "comp": 1, + "innerLength": 56, + "inner": "01000000003228b52ffda0000010005400001000000100fbff39c00202001000020010000200100002001000020010000200100003001000" + }, + { + "tcId": 55, + "comment": "5,000 bytes of text", + "flags": [ + "Compress" + ], + "inputs": { + "class": "ordinary", + "chunk": "54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e205468652071" + }, + "expect": "Ok", + "comp": 1, + "innerLength": 72, + "inner": "01000000004028b52ffd608812b50100d40254686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e200100c51ad8ab320000" + }, + { + "tcId": 56, + "comment": "random bytes then zeros: the frame just saves 1/16", + "flags": [ + "StoreRaw" + ], + "inputs": { + "class": "ordinary", + "chunk": "cee3a594a3f6a4c6eb36e5c72dbca99dcb1c2646758cb2675a3a3a98bbc69d3a392330c6d5bbb9040987a1aa1cd21eaff241288d8a98a0bfb8bcd796649411d6f1a56211a04d58f1a3a3d204be02aa2012769b16bc018cc9aec7dcd4e63cf7ce0e2791f1eeda3839b75fe30ce27c412ee74279e44bccccae3b31df6fff004854690f7ebf50194b419e3b49388ea3c1303ba10861da2552a11f82e18e9c4b62f1f5e77ca3f03961a7763ce28c9f97c0d7053a96ac3ee3e9b09fc3661faec235bc6544702e6bff031ed132237ab05f441b257293ff503fa4f61874d5cd19ae1fc036b1e9f288c957f2f4c6023487522e269841c864f7c0aefebc446d22b2e677be0fc600c93c3225219c57ea5e7e25ae08286e0fc4b9a600ebff22fd15bbdb0447a2f61ecc0dd857ec8c082410016fc9693a24157a751f8fcb48f6ddc987190ba81c4a198b525c9717e8af96ae7f8c8338102a5e6c84ecf05fbb2eb472dfb02c5ca3a8e5c308023a182ee731109f124a0f04ad1175f1eecc213352f23d2f47d972bfe69d8e765886206fb6a027e927736236be0c660eace3ee09e650908d9fe8a59c5333afe9d43e55dc9c8523f6b05745d33ebf8c6af91d34c4736cd8001cda7c3008a5e3363cc48b548b7ffeff5f2e9e4e19fefc321f951c28e3eded6e7aba985df066047a64301f4a1ed1c7a1fa89660f58303cdd41dc6210d478e80f937fdb9c5b9c5a8ff194f63c731af10c1d2134272b15a41c5cd3d07d72c088f234dd9c85093ff0f01919484a2e130d1c982c0a9d8217ee959a9109a32d172de7cc357aee9434c89f587c609c37860e7dcf7790c2dee5199a1080a30f8a7e040ada1f49026fb859fa49c455ae180bd06dacec07004d56d04c7c0d04cf8c6291d98937f68ac4810ee168c2de5e69a392ae8732e96a68b4a67f9c7150d88f2b102c33388bf342b674b2e67abdf21e8e128fb6d28135d0d8ee4ef3e5423200dc8321adf5a88061ec91f44f307e6398e2e9f388d2d3cb4b3eda4e4f31918dc1d3a096b13cea11a1fd2ff17183f654edfc726812ea2efec73001e8b634e8d07d0e391c5acd42b5de1ce1512371cf9ed3688b2d93e403f4076a2de6cf808dab938c037272ccb418f134d55dca7a16b1ef5b1bfdc862301aa7a6329a5c7719f82b2b85fe453e7245149e20e4dc57ba287e8f677941e8f076bfd94cd4f6f91c2f871b50994944046eaba246c9865bbc435f087e2956d9ce3d36ad34caabe967a69d0e9897a0862dc3af5dd512ce0a65070ad605fd8b783c36fd6fbabfaaea8991f36d7c9878236ad3f607c33caa6251bf485f6f16a1ae789beef9f9d80b9ddfafdcc7ab3bda5deb5f03e864c051ddd9ab9040d5b6662620b2a95452347e60b1e30982dcf06531b9fb066177b4e2e1e8174f6e7846c10042ee55de255a26749ce9e12577c5184133a2fe0888fb29f50707df137d7aa2ebb1e0a92984b3387210879ea3ec4950277347a47dc4e7633880436bac5fc7bdc4e8776bc1b08f039247e53c24537b9dea1a3a26d2ba9d5a62b8e87cd707ffff6009c703d31e9dc3fd2dc9099526265a68fd52fc716e982f59b4e3bc48a46706555ff64dc932d77fba1ff89b56f4ef832099a8ac03ccaa2f0a32545201404a813e4c4bf726c40105bc45824b13078dc05dfdeded13655cb7bac8bd4070569314888fbcebd8e53abbee7bb472d65d41f068148647791c356c6d57eb37b49a7a46d3db13cd98f6c91bad25ae6cd50c74015ec142f13f9f0858b5c3a908ef818da8946ff25a3dc1c51d08e44778ce24e4293e8e97930c71e9fd1f8070ffebfa7c77cad94dc338e7e5c408cbcb64d45c61e60b648896a0e62386db0e77b5fe7aaac13b6a8267b732942e04909553701ac521c4500c5020a173cfb217ee5c32084fd2b3c2ad5e9bab93eb51e7d1721436f1545e153c971d2b152470974f85aef41c5ec8144ae93e368b2a975443a75b1334f37e1ee4b6ec935aac556fa481db14dae4d1d609c48a4982c18cd98a7f0fe76f925d562825c72e775d1ed965b017f5e372377b87c24e74811804041f1cd79e25f3dddefcdd33f2aed987bd21db9306df2c7f9bbb60d9953e0c2139c6a241adcb8f5b8fea1e543167d0d35ae65f48a7fc0f2a9d19b744310048fbf1dc6b329024ad9b35d3c7137e98c80411cb7b1a18c08591b357997eebe9a0c8ae7dc8dc1609a820eb8035aeead2303f2608939d7e5e260e4700aebe8e78d69c5e8847681519e1e30954b0430402f2e688e8414088d4104e77345f99bd218c6f6fe126d0da78745c04ce21e374f2b7fc61151aa084a0120b9b2a73f4c73b403a563f761aee101ed95d6933453641e714983ecd38f4d10e80e81bc185fd3c7b5334338e1ec5752fc9195fcd8a77999cf27d1c442c615e6839896b39edebf53b686bc94206b037b35440fe8d28100294f0b45245efaf87cdff66def91fdbc69595afd327804a75737e90dd42219679fbb7c96fec22e8a64312befde1712f68f001acf4a0e22ac723c60a851431a0921ecdb28a1a1b99a539aa8ab9609201de590a204e019b2a9ed274648f7b9a8bed0df8cbe339098fe850107098de5a8c22a82c13dfd74218a6c4bf5ebca6837015a1a1e5b440c35d05ed1b6b8b67819955efbc0fd6121f25aab01bb4784f0acd1ea12520575721308c6978ad15644ef59ce8756e174f07937d22bef45e097eca09fc56d2081c871556cad4393a576d041d8b9d084ed9db78d2f0a940bfa8cb937c618e42bb6b78edb351d1645d7a528115c0cc15a389d06c00693468cb959a6774c48beef9a6f10a9ea09096218f5927ddca96067a7d123226d0ec9d0e288f8bdcecf1dd9b076b6840b2b8a405d7cc5c51aa09ca4481a75223a7eafa29a63aa2502a46658d5c6e0b98ccf47d4108544fdece0a2e3628b59ee41c6b8760520720a19156588389b9f1c786697f5f5a827d9f56e53aca1cc9f414f1ad9823302f0f4b185b810532d3e25c7f42458fbcdfcb1564e14777acd708e3361d38b294f03339509252f5ce9d3b1913638ed269f3062310ef94375c9a6f9c42764ba31f847ee16ce2c8b639af3bdadf4602a5b9128d2ab0e7158fd2ac16ca3c61f132d6f413f2807c1b2720bafe4bc2b2388501b1f77a0753872bb728ccef09b3c4babf14caa2459fc2383e8b65db8a7fa78279ef89482b04fbf57b62bd00c8364bf0ae479d15026f5be9a4666d6a25ce5ea3cd8f9b92381f1b376563a338dd90fdeac13d51d20846ae9bc8605c8fd63e13dfce9dbcc8e89eeb320a1f6650b5ceb2e2ede81f1539aad7c25b50d0d2215f766112f0c1d92b57ead4014e7f8c0072fed7aa6af75cf897924210ec7750495cb619987f0efb346d469bf8cb5bfaaf018ce8a088d1174071b82b0789ff76b0514c80459119c5cb4e81a445db3e920cf34351dc0dddc0891d207c2ac3337a965826bd8d9060a7f2ba8c70e49d54be0557407f0c584b8b86ff230da6ba97c3ef2e083f30e4c7bbbe05bb781621ad3739547d58b8301ecde8ca184986415a4119695dcbb1b941b6bd9b12402badac6066cfb0796dafb4b543c16c1992943fd8d2f51b0d0d90528d389fd7805b6289d1d9227b91036f1f83b4c16a53e96f16f9f4fe8ee108e8f990fcd1fce02e35aa0f0e8f416c98253209cf1753551d7c392ca67116cc682a2bb3f936b30470509f6b7d4139dc1f167500a589fa93839eb066018264e4dbaa8fe09f83598146e34fefea5cf8b196536dc04544946992ecddc9e620b055f86e50e3b5a0ac064ecb83eda8d961e30975abb4499be7777650b93fa4ec0ce8b592998969c627de6e4359d722db7f36265fbe9b8a7b9c1c67f3ad7334883260846becc1da851297cb4a495c3acb7e095bd469241a18c0a010dcd20a797fd946d6fdd351082a9bfc64a4da2b6046e083344e020ce37188ae7bdf4fc58cc4df45f192b410b9af6210e16c3ff965717d62805d9acbf9d283cd823d20819a6e66d8f9aff3d30f768c25c96feb1625fa7f9f8ccd12c6919dc3f62e48df7f911dad1b7d857296b2679a94b2c3e35f0f0a36610d5615f454646592573919148263ecb4827dbe2cd70f5084b7183f48e0e6c5f48125d307a02892725248e1f271bee208e01d2aaf1fce4b8cd4fcbe6e843352c0f167fd914aedfe86cd124d444ba9e2259abae64eb465e3fcb507a3e566ed7e4be6b78e6347f258ba999d26568ce8be8e14ee68adf02af053c83a518aa6464e73be5fb6518215e0ba487decec8fbf6a94553f74e9c7f4e7381c6382b866970aaa95b986e4184415b8bc9b1a98d50aabd92ba28c73bdb14c65af3a0fd8b7c3718feddff47b18fa252b4a4ab3a3d4e83663199dee78741c2f020bd1bd4950c61c27cbc71680dbd6ff1a9f2e863439c2890c472521b15dc86eef5cdafd614a7011191a87c5dafe611cb20b46eb47c12d4b587c0d5ff0d03735b7e7fdc828fade1e834a8802b76a4990a6b5d4ba6defb4b238753fe56d6bda7aec212e14b185f4db189ca2d4e466ea47bc4163e8559e197e1fe643083697475a422b7db75e05188fc45d68fc2500af8438a010da4b1bd0ef2f25b833bb1a3eeef5eec2ac86f79e24116f03e692b8aaa6fafce1521100d29b39a6cf5d75a92edd2264b4227dd9f59a709c6202165c49d9efe49b2fcab1b7d74e3c402774dddf63178923d6f1bd4576a13a25ef4788ebf5b3d53a842c7c5184963e8e5bb2f315b2bab1100e350ee4a8ea4ef15b876400cbdfdd0ad70bbc610ab1cbd4a02a71606839aea56a3fcc3f6aae7b4471468ad723d19e49f54fdac3a92715522d9d7616bf6247b2fd4484573a72db2a5c3096d81c1da30520f883efd3a71ff798e8c5007f42613d3116e9667922eac1c60275940322e813a1742acde9eb4d8cb1884c145a5f5146974d3e42f73a150a20468a72dcaf0d1d0eb729e300a78a6ab1795a0d924530270add679dc80b381ab9c157cfa20abb15c0074666b775003ab2f159eb3ae1519b9c716e6817ce7c360080273c6b90904cddec25cb5f28a8e292d801621bdcdf00b9d5843ff976167d49eab357ab030014b46d69ad79f7a4ebbaaef03eda9d95c60763d678c48e032b68c55fb2b684596e2909339b074c5a830e8ed2fede9de30a2805310829845ecbbaed46aeb9288c2086887291e04356bc77aa636359170311dbe1b4fc0d4722866be1669f9152e2474c5e5aa821a27b53219545c163ed921348aceb379414fc477b2d35aeb7d715df535b35ee4d6f277d02bfed4ee25e39e7ec2a9d7d4f1de0e7c63dbe0525ffb908fc231100aaeaf06321e3277632d0ac78fd1ecac1f2c1946a62a896cd26693e4535a20cec5c39bd5dfb848346b0e6ed81e78c7ab900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + }, + "expect": "Ok", + "comp": 1, + "innerLength": 3840, + "inner": "010000000ef328b52ffd60000f4d770004eecee3a594a3f6a4c6eb36e5c72dbca99dcb1c2646758cb2675a3a3a98bbc69d3a392330c6d5bbb9040987a1aa1cd21eaff241288d8a98a0bfb8bcd796649411d6f1a56211a04d58f1a3a3d204be02aa2012769b16bc018cc9aec7dcd4e63cf7ce0e2791f1eeda3839b75fe30ce27c412ee74279e44bccccae3b31df6fff004854690f7ebf50194b419e3b49388ea3c1303ba10861da2552a11f82e18e9c4b62f1f5e77ca3f03961a7763ce28c9f97c0d7053a96ac3ee3e9b09fc3661faec235bc6544702e6bff031ed132237ab05f441b257293ff503fa4f61874d5cd19ae1fc036b1e9f288c957f2f4c6023487522e269841c864f7c0aefebc446d22b2e677be0fc600c93c3225219c57ea5e7e25ae08286e0fc4b9a600ebff22fd15bbdb0447a2f61ecc0dd857ec8c082410016fc9693a24157a751f8fcb48f6ddc987190ba81c4a198b525c9717e8af96ae7f8c8338102a5e6c84ecf05fbb2eb472dfb02c5ca3a8e5c308023a182ee731109f124a0f04ad1175f1eecc213352f23d2f47d972bfe69d8e765886206fb6a027e927736236be0c660eace3ee09e650908d9fe8a59c5333afe9d43e55dc9c8523f6b05745d33ebf8c6af91d34c4736cd8001cda7c3008a5e3363cc48b548b7ffeff5f2e9e4e19fefc321f951c28e3eded6e7aba985df066047a64301f4a1ed1c7a1fa89660f58303cdd41dc6210d478e80f937fdb9c5b9c5a8ff194f63c731af10c1d2134272b15a41c5cd3d07d72c088f234dd9c85093ff0f01919484a2e130d1c982c0a9d8217ee959a9109a32d172de7cc357aee9434c89f587c609c37860e7dcf7790c2dee5199a1080a30f8a7e040ada1f49026fb859fa49c455ae180bd06dacec07004d56d04c7c0d04cf8c6291d98937f68ac4810ee168c2de5e69a392ae8732e96a68b4a67f9c7150d88f2b102c33388bf342b674b2e67abdf21e8e128fb6d28135d0d8ee4ef3e5423200dc8321adf5a88061ec91f44f307e6398e2e9f388d2d3cb4b3eda4e4f31918dc1d3a096b13cea11a1fd2ff17183f654edfc726812ea2efec73001e8b634e8d07d0e391c5acd42b5de1ce1512371cf9ed3688b2d93e403f4076a2de6cf808dab938c037272ccb418f134d55dca7a16b1ef5b1bfdc862301aa7a6329a5c7719f82b2b85fe453e7245149e20e4dc57ba287e8f677941e8f076bfd94cd4f6f91c2f871b50994944046eaba246c9865bbc435f087e2956d9ce3d36ad34caabe967a69d0e9897a0862dc3af5dd512ce0a65070ad605fd8b783c36fd6fbabfaaea8991f36d7c9878236ad3f607c33caa6251bf485f6f16a1ae789beef9f9d80b9ddfafdcc7ab3bda5deb5f03e864c051ddd9ab9040d5b6662620b2a95452347e60b1e30982dcf06531b9fb066177b4e2e1e8174f6e7846c10042ee55de255a26749ce9e12577c5184133a2fe0888fb29f50707df137d7aa2ebb1e0a92984b3387210879ea3ec4950277347a47dc4e7633880436bac5fc7bdc4e8776bc1b08f039247e53c24537b9dea1a3a26d2ba9d5a62b8e87cd707ffff6009c703d31e9dc3fd2dc9099526265a68fd52fc716e982f59b4e3bc48a46706555ff64dc932d77fba1ff89b56f4ef832099a8ac03ccaa2f0a32545201404a813e4c4bf726c40105bc45824b13078dc05dfdeded13655cb7bac8bd4070569314888fbcebd8e53abbee7bb472d65d41f068148647791c356c6d57eb37b49a7a46d3db13cd98f6c91bad25ae6cd50c74015ec142f13f9f0858b5c3a908ef818da8946ff25a3dc1c51d08e44778ce24e4293e8e97930c71e9fd1f8070ffebfa7c77cad94dc338e7e5c408cbcb64d45c61e60b648896a0e62386db0e77b5fe7aaac13b6a8267b732942e04909553701ac521c4500c5020a173cfb217ee5c32084fd2b3c2ad5e9bab93eb51e7d1721436f1545e153c971d2b152470974f85aef41c5ec8144ae93e368b2a975443a75b1334f37e1ee4b6ec935aac556fa481db14dae4d1d609c48a4982c18cd98a7f0fe76f925d562825c72e775d1ed965b017f5e372377b87c24e74811804041f1cd79e25f3dddefcdd33f2aed987bd21db9306df2c7f9bbb60d9953e0c2139c6a241adcb8f5b8fea1e543167d0d35ae65f48a7fc0f2a9d19b744310048fbf1dc6b329024ad9b35d3c7137e98c80411cb7b1a18c08591b357997eebe9a0c8ae7dc8dc1609a820eb8035aeead2303f2608939d7e5e260e4700aebe8e78d69c5e8847681519e1e30954b0430402f2e688e8414088d4104e77345f99bd218c6f6fe126d0da78745c04ce21e374f2b7fc61151aa084a0120b9b2a73f4c73b403a563f761aee101ed95d6933453641e714983ecd38f4d10e80e81bc185fd3c7b5334338e1ec5752fc9195fcd8a77999cf27d1c442c615e6839896b39edebf53b686bc94206b037b35440fe8d28100294f0b45245efaf87cdff66def91fdbc69595afd327804a75737e90dd42219679fbb7c96fec22e8a64312befde1712f68f001acf4a0e22ac723c60a851431a0921ecdb28a1a1b99a539aa8ab9609201de590a204e019b2a9ed274648f7b9a8bed0df8cbe339098fe850107098de5a8c22a82c13dfd74218a6c4bf5ebca6837015a1a1e5b440c35d05ed1b6b8b67819955efbc0fd6121f25aab01bb4784f0acd1ea12520575721308c6978ad15644ef59ce8756e174f07937d22bef45e097eca09fc56d2081c871556cad4393a576d041d8b9d084ed9db78d2f0a940bfa8cb937c618e42bb6b78edb351d1645d7a528115c0cc15a389d06c00693468cb959a6774c48beef9a6f10a9ea09096218f5927ddca96067a7d123226d0ec9d0e288f8bdcecf1dd9b076b6840b2b8a405d7cc5c51aa09ca4481a75223a7eafa29a63aa2502a46658d5c6e0b98ccf47d4108544fdece0a2e3628b59ee41c6b8760520720a19156588389b9f1c786697f5f5a827d9f56e53aca1cc9f414f1ad9823302f0f4b185b810532d3e25c7f42458fbcdfcb1564e14777acd708e3361d38b294f03339509252f5ce9d3b1913638ed269f3062310ef94375c9a6f9c42764ba31f847ee16ce2c8b639af3bdadf4602a5b9128d2ab0e7158fd2ac16ca3c61f132d6f413f2807c1b2720bafe4bc2b2388501b1f77a0753872bb728ccef09b3c4babf14caa2459fc2383e8b65db8a7fa78279ef89482b04fbf57b62bd00c8364bf0ae479d15026f5be9a4666d6a25ce5ea3cd8f9b92381f1b376563a338dd90fdeac13d51d20846ae9bc8605c8fd63e13dfce9dbcc8e89eeb320a1f6650b5ceb2e2ede81f1539aad7c25b50d0d2215f766112f0c1d92b57ead4014e7f8c0072fed7aa6af75cf897924210ec7750495cb619987f0efb346d469bf8cb5bfaaf018ce8a088d1174071b82b0789ff76b0514c80459119c5cb4e81a445db3e920cf34351dc0dddc0891d207c2ac3337a965826bd8d9060a7f2ba8c70e49d54be0557407f0c584b8b86ff230da6ba97c3ef2e083f30e4c7bbbe05bb781621ad3739547d58b8301ecde8ca184986415a4119695dcbb1b941b6bd9b12402badac6066cfb0796dafb4b543c16c1992943fd8d2f51b0d0d90528d389fd7805b6289d1d9227b91036f1f83b4c16a53e96f16f9f4fe8ee108e8f990fcd1fce02e35aa0f0e8f416c98253209cf1753551d7c392ca67116cc682a2bb3f936b30470509f6b7d4139dc1f167500a589fa93839eb066018264e4dbaa8fe09f83598146e34fefea5cf8b196536dc04544946992ecddc9e620b055f86e50e3b5a0ac064ecb83eda8d961e30975abb4499be7777650b93fa4ec0ce8b592998969c627de6e4359d722db7f36265fbe9b8a7b9c1c67f3ad7334883260846becc1da851297cb4a495c3acb7e095bd469241a18c0a010dcd20a797fd946d6fdd351082a9bfc64a4da2b6046e083344e020ce37188ae7bdf4fc58cc4df45f192b410b9af6210e16c3ff965717d62805d9acbf9d283cd823d20819a6e66d8f9aff3d30f768c25c96feb1625fa7f9f8ccd12c6919dc3f62e48df7f911dad1b7d857296b2679a94b2c3e35f0f0a36610d5615f454646592573919148263ecb4827dbe2cd70f5084b7183f48e0e6c5f48125d307a02892725248e1f271bee208e01d2aaf1fce4b8cd4fcbe6e843352c0f167fd914aedfe86cd124d444ba9e2259abae64eb465e3fcb507a3e566ed7e4be6b78e6347f258ba999d26568ce8be8e14ee68adf02af053c83a518aa6464e73be5fb6518215e0ba487decec8fbf6a94553f74e9c7f4e7381c6382b866970aaa95b986e4184415b8bc9b1a98d50aabd92ba28c73bdb14c65af3a0fd8b7c3718feddff47b18fa252b4a4ab3a3d4e83663199dee78741c2f020bd1bd4950c61c27cbc71680dbd6ff1a9f2e863439c2890c472521b15dc86eef5cdafd614a7011191a87c5dafe611cb20b46eb47c12d4b587c0d5ff0d03735b7e7fdc828fade1e834a8802b76a4990a6b5d4ba6defb4b238753fe56d6bda7aec212e14b185f4db189ca2d4e466ea47bc4163e8559e197e1fe643083697475a422b7db75e05188fc45d68fc2500af8438a010da4b1bd0ef2f25b833bb1a3eeef5eec2ac86f79e24116f03e692b8aaa6fafce1521100d29b39a6cf5d75a92edd2264b4227dd9f59a709c6202165c49d9efe49b2fcab1b7d74e3c402774dddf63178923d6f1bd4576a13a25ef4788ebf5b3d53a842c7c5184963e8e5bb2f315b2bab1100e350ee4a8ea4ef15b876400cbdfdd0ad70bbc610ab1cbd4a02a71606839aea56a3fcc3f6aae7b4471468ad723d19e49f54fdac3a92715522d9d7616bf6247b2fd4484573a72db2a5c3096d81c1da30520f883efd3a71ff798e8c5007f42613d3116e9667922eac1c60275940322e813a1742acde9eb4d8cb1884c145a5f5146974d3e42f73a150a20468a72dcaf0d1d0eb729e300a78a6ab1795a0d924530270add679dc80b381ab9c157cfa20abb15c0074666b775003ab2f159eb3ae1519b9c716e6817ce7c360080273c6b90904cddec25cb5f28a8e292d801621bdcdf00b9d5843ff976167d49eab357ab030014b46d69ad79f7a4ebbaaef03eda9d95c60763d678c48e032b68c55fb2b684596e2909339b074c5a830e8ed2fede9de30a2805310829845ecbbaed46aeb9288c2086887291e04356bc77aa636359170311dbe1b4fc0d4722866be1669f9152e2474c5e5aa821a27b53219545c163ed921348aceb379414fc477b2d35aeb7d715df535b35ee4d6f277d02bfed4ee25e39e7ec2a9d7d4f1de0e7c63dbe0525ffb908fc231100aaeaf06321e3277632d0ac78fd1ecac1f2c1946a62a896cd26693e4535a20cec5c39bd5dfb848346b0e6ed81e78c7ab9000100e0ee50811a00000000000000" + }, + { + "tcId": 57, + "comment": "one more random byte: the frame no longer saves 1/16, stored raw", + "flags": [ + "StoreRaw" + ], + "inputs": { + "class": "ordinary", + "chunk": "cee3a594a3f6a4c6eb36e5c72dbca99dcb1c2646758cb2675a3a3a98bbc69d3a392330c6d5bbb9040987a1aa1cd21eaff241288d8a98a0bfb8bcd796649411d6f1a56211a04d58f1a3a3d204be02aa2012769b16bc018cc9aec7dcd4e63cf7ce0e2791f1eeda3839b75fe30ce27c412ee74279e44bccccae3b31df6fff004854690f7ebf50194b419e3b49388ea3c1303ba10861da2552a11f82e18e9c4b62f1f5e77ca3f03961a7763ce28c9f97c0d7053a96ac3ee3e9b09fc3661faec235bc6544702e6bff031ed132237ab05f441b257293ff503fa4f61874d5cd19ae1fc036b1e9f288c957f2f4c6023487522e269841c864f7c0aefebc446d22b2e677be0fc600c93c3225219c57ea5e7e25ae08286e0fc4b9a600ebff22fd15bbdb0447a2f61ecc0dd857ec8c082410016fc9693a24157a751f8fcb48f6ddc987190ba81c4a198b525c9717e8af96ae7f8c8338102a5e6c84ecf05fbb2eb472dfb02c5ca3a8e5c308023a182ee731109f124a0f04ad1175f1eecc213352f23d2f47d972bfe69d8e765886206fb6a027e927736236be0c660eace3ee09e650908d9fe8a59c5333afe9d43e55dc9c8523f6b05745d33ebf8c6af91d34c4736cd8001cda7c3008a5e3363cc48b548b7ffeff5f2e9e4e19fefc321f951c28e3eded6e7aba985df066047a64301f4a1ed1c7a1fa89660f58303cdd41dc6210d478e80f937fdb9c5b9c5a8ff194f63c731af10c1d2134272b15a41c5cd3d07d72c088f234dd9c85093ff0f01919484a2e130d1c982c0a9d8217ee959a9109a32d172de7cc357aee9434c89f587c609c37860e7dcf7790c2dee5199a1080a30f8a7e040ada1f49026fb859fa49c455ae180bd06dacec07004d56d04c7c0d04cf8c6291d98937f68ac4810ee168c2de5e69a392ae8732e96a68b4a67f9c7150d88f2b102c33388bf342b674b2e67abdf21e8e128fb6d28135d0d8ee4ef3e5423200dc8321adf5a88061ec91f44f307e6398e2e9f388d2d3cb4b3eda4e4f31918dc1d3a096b13cea11a1fd2ff17183f654edfc726812ea2efec73001e8b634e8d07d0e391c5acd42b5de1ce1512371cf9ed3688b2d93e403f4076a2de6cf808dab938c037272ccb418f134d55dca7a16b1ef5b1bfdc862301aa7a6329a5c7719f82b2b85fe453e7245149e20e4dc57ba287e8f677941e8f076bfd94cd4f6f91c2f871b50994944046eaba246c9865bbc435f087e2956d9ce3d36ad34caabe967a69d0e9897a0862dc3af5dd512ce0a65070ad605fd8b783c36fd6fbabfaaea8991f36d7c9878236ad3f607c33caa6251bf485f6f16a1ae789beef9f9d80b9ddfafdcc7ab3bda5deb5f03e864c051ddd9ab9040d5b6662620b2a95452347e60b1e30982dcf06531b9fb066177b4e2e1e8174f6e7846c10042ee55de255a26749ce9e12577c5184133a2fe0888fb29f50707df137d7aa2ebb1e0a92984b3387210879ea3ec4950277347a47dc4e7633880436bac5fc7bdc4e8776bc1b08f039247e53c24537b9dea1a3a26d2ba9d5a62b8e87cd707ffff6009c703d31e9dc3fd2dc9099526265a68fd52fc716e982f59b4e3bc48a46706555ff64dc932d77fba1ff89b56f4ef832099a8ac03ccaa2f0a32545201404a813e4c4bf726c40105bc45824b13078dc05dfdeded13655cb7bac8bd4070569314888fbcebd8e53abbee7bb472d65d41f068148647791c356c6d57eb37b49a7a46d3db13cd98f6c91bad25ae6cd50c74015ec142f13f9f0858b5c3a908ef818da8946ff25a3dc1c51d08e44778ce24e4293e8e97930c71e9fd1f8070ffebfa7c77cad94dc338e7e5c408cbcb64d45c61e60b648896a0e62386db0e77b5fe7aaac13b6a8267b732942e04909553701ac521c4500c5020a173cfb217ee5c32084fd2b3c2ad5e9bab93eb51e7d1721436f1545e153c971d2b152470974f85aef41c5ec8144ae93e368b2a975443a75b1334f37e1ee4b6ec935aac556fa481db14dae4d1d609c48a4982c18cd98a7f0fe76f925d562825c72e775d1ed965b017f5e372377b87c24e74811804041f1cd79e25f3dddefcdd33f2aed987bd21db9306df2c7f9bbb60d9953e0c2139c6a241adcb8f5b8fea1e543167d0d35ae65f48a7fc0f2a9d19b744310048fbf1dc6b329024ad9b35d3c7137e98c80411cb7b1a18c08591b357997eebe9a0c8ae7dc8dc1609a820eb8035aeead2303f2608939d7e5e260e4700aebe8e78d69c5e8847681519e1e30954b0430402f2e688e8414088d4104e77345f99bd218c6f6fe126d0da78745c04ce21e374f2b7fc61151aa084a0120b9b2a73f4c73b403a563f761aee101ed95d6933453641e714983ecd38f4d10e80e81bc185fd3c7b5334338e1ec5752fc9195fcd8a77999cf27d1c442c615e6839896b39edebf53b686bc94206b037b35440fe8d28100294f0b45245efaf87cdff66def91fdbc69595afd327804a75737e90dd42219679fbb7c96fec22e8a64312befde1712f68f001acf4a0e22ac723c60a851431a0921ecdb28a1a1b99a539aa8ab9609201de590a204e019b2a9ed274648f7b9a8bed0df8cbe339098fe850107098de5a8c22a82c13dfd74218a6c4bf5ebca6837015a1a1e5b440c35d05ed1b6b8b67819955efbc0fd6121f25aab01bb4784f0acd1ea12520575721308c6978ad15644ef59ce8756e174f07937d22bef45e097eca09fc56d2081c871556cad4393a576d041d8b9d084ed9db78d2f0a940bfa8cb937c618e42bb6b78edb351d1645d7a528115c0cc15a389d06c00693468cb959a6774c48beef9a6f10a9ea09096218f5927ddca96067a7d123226d0ec9d0e288f8bdcecf1dd9b076b6840b2b8a405d7cc5c51aa09ca4481a75223a7eafa29a63aa2502a46658d5c6e0b98ccf47d4108544fdece0a2e3628b59ee41c6b8760520720a19156588389b9f1c786697f5f5a827d9f56e53aca1cc9f414f1ad9823302f0f4b185b810532d3e25c7f42458fbcdfcb1564e14777acd708e3361d38b294f03339509252f5ce9d3b1913638ed269f3062310ef94375c9a6f9c42764ba31f847ee16ce2c8b639af3bdadf4602a5b9128d2ab0e7158fd2ac16ca3c61f132d6f413f2807c1b2720bafe4bc2b2388501b1f77a0753872bb728ccef09b3c4babf14caa2459fc2383e8b65db8a7fa78279ef89482b04fbf57b62bd00c8364bf0ae479d15026f5be9a4666d6a25ce5ea3cd8f9b92381f1b376563a338dd90fdeac13d51d20846ae9bc8605c8fd63e13dfce9dbcc8e89eeb320a1f6650b5ceb2e2ede81f1539aad7c25b50d0d2215f766112f0c1d92b57ead4014e7f8c0072fed7aa6af75cf897924210ec7750495cb619987f0efb346d469bf8cb5bfaaf018ce8a088d1174071b82b0789ff76b0514c80459119c5cb4e81a445db3e920cf34351dc0dddc0891d207c2ac3337a965826bd8d9060a7f2ba8c70e49d54be0557407f0c584b8b86ff230da6ba97c3ef2e083f30e4c7bbbe05bb781621ad3739547d58b8301ecde8ca184986415a4119695dcbb1b941b6bd9b12402badac6066cfb0796dafb4b543c16c1992943fd8d2f51b0d0d90528d389fd7805b6289d1d9227b91036f1f83b4c16a53e96f16f9f4fe8ee108e8f990fcd1fce02e35aa0f0e8f416c98253209cf1753551d7c392ca67116cc682a2bb3f936b30470509f6b7d4139dc1f167500a589fa93839eb066018264e4dbaa8fe09f83598146e34fefea5cf8b196536dc04544946992ecddc9e620b055f86e50e3b5a0ac064ecb83eda8d961e30975abb4499be7777650b93fa4ec0ce8b592998969c627de6e4359d722db7f36265fbe9b8a7b9c1c67f3ad7334883260846becc1da851297cb4a495c3acb7e095bd469241a18c0a010dcd20a797fd946d6fdd351082a9bfc64a4da2b6046e083344e020ce37188ae7bdf4fc58cc4df45f192b410b9af6210e16c3ff965717d62805d9acbf9d283cd823d20819a6e66d8f9aff3d30f768c25c96feb1625fa7f9f8ccd12c6919dc3f62e48df7f911dad1b7d857296b2679a94b2c3e35f0f0a36610d5615f454646592573919148263ecb4827dbe2cd70f5084b7183f48e0e6c5f48125d307a02892725248e1f271bee208e01d2aaf1fce4b8cd4fcbe6e843352c0f167fd914aedfe86cd124d444ba9e2259abae64eb465e3fcb507a3e566ed7e4be6b78e6347f258ba999d26568ce8be8e14ee68adf02af053c83a518aa6464e73be5fb6518215e0ba487decec8fbf6a94553f74e9c7f4e7381c6382b866970aaa95b986e4184415b8bc9b1a98d50aabd92ba28c73bdb14c65af3a0fd8b7c3718feddff47b18fa252b4a4ab3a3d4e83663199dee78741c2f020bd1bd4950c61c27cbc71680dbd6ff1a9f2e863439c2890c472521b15dc86eef5cdafd614a7011191a87c5dafe611cb20b46eb47c12d4b587c0d5ff0d03735b7e7fdc828fade1e834a8802b76a4990a6b5d4ba6defb4b238753fe56d6bda7aec212e14b185f4db189ca2d4e466ea47bc4163e8559e197e1fe643083697475a422b7db75e05188fc45d68fc2500af8438a010da4b1bd0ef2f25b833bb1a3eeef5eec2ac86f79e24116f03e692b8aaa6fafce1521100d29b39a6cf5d75a92edd2264b4227dd9f59a709c6202165c49d9efe49b2fcab1b7d74e3c402774dddf63178923d6f1bd4576a13a25ef4788ebf5b3d53a842c7c5184963e8e5bb2f315b2bab1100e350ee4a8ea4ef15b876400cbdfdd0ad70bbc610ab1cbd4a02a71606839aea56a3fcc3f6aae7b4471468ad723d19e49f54fdac3a92715522d9d7616bf6247b2fd4484573a72db2a5c3096d81c1da30520f883efd3a71ff798e8c5007f42613d3116e9667922eac1c60275940322e813a1742acde9eb4d8cb1884c145a5f5146974d3e42f73a150a20468a72dcaf0d1d0eb729e300a78a6ab1795a0d924530270add679dc80b381ab9c157cfa20abb15c0074666b775003ab2f159eb3ae1519b9c716e6817ce7c360080273c6b90904cddec25cb5f28a8e292d801621bdcdf00b9d5843ff976167d49eab357ab030014b46d69ad79f7a4ebbaaef03eda9d95c60763d678c48e032b68c55fb2b684596e2909339b074c5a830e8ed2fede9de30a2805310829845ecbbaed46aeb9288c2086887291e04356bc77aa636359170311dbe1b4fc0d4722866be1669f9152e2474c5e5aa821a27b53219545c163ed921348aceb379414fc477b2d35aeb7d715df535b35ee4d6f277d02bfed4ee25e39e7ec2a9d7d4f1de0e7c63dbe0525ffb908fc231100aaeaf06321e3277632d0ac78fd1ecac1f2c1946a62a896cd26693e4535a20cec5c39bd5dfb848346b0e6ed81e78c7ab94a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + }, + "expect": "Ok", + "comp": 0, + "innerLength": 4352, + "inner": "000000001000cee3a594a3f6a4c6eb36e5c72dbca99dcb1c2646758cb2675a3a3a98bbc69d3a392330c6d5bbb9040987a1aa1cd21eaff241288d8a98a0bfb8bcd796649411d6f1a56211a04d58f1a3a3d204be02aa2012769b16bc018cc9aec7dcd4e63cf7ce0e2791f1eeda3839b75fe30ce27c412ee74279e44bccccae3b31df6fff004854690f7ebf50194b419e3b49388ea3c1303ba10861da2552a11f82e18e9c4b62f1f5e77ca3f03961a7763ce28c9f97c0d7053a96ac3ee3e9b09fc3661faec235bc6544702e6bff031ed132237ab05f441b257293ff503fa4f61874d5cd19ae1fc036b1e9f288c957f2f4c6023487522e269841c864f7c0aefebc446d22b2e677be0fc600c93c3225219c57ea5e7e25ae08286e0fc4b9a600ebff22fd15bbdb0447a2f61ecc0dd857ec8c082410016fc9693a24157a751f8fcb48f6ddc987190ba81c4a198b525c9717e8af96ae7f8c8338102a5e6c84ecf05fbb2eb472dfb02c5ca3a8e5c308023a182ee731109f124a0f04ad1175f1eecc213352f23d2f47d972bfe69d8e765886206fb6a027e927736236be0c660eace3ee09e650908d9fe8a59c5333afe9d43e55dc9c8523f6b05745d33ebf8c6af91d34c4736cd8001cda7c3008a5e3363cc48b548b7ffeff5f2e9e4e19fefc321f951c28e3eded6e7aba985df066047a64301f4a1ed1c7a1fa89660f58303cdd41dc6210d478e80f937fdb9c5b9c5a8ff194f63c731af10c1d2134272b15a41c5cd3d07d72c088f234dd9c85093ff0f01919484a2e130d1c982c0a9d8217ee959a9109a32d172de7cc357aee9434c89f587c609c37860e7dcf7790c2dee5199a1080a30f8a7e040ada1f49026fb859fa49c455ae180bd06dacec07004d56d04c7c0d04cf8c6291d98937f68ac4810ee168c2de5e69a392ae8732e96a68b4a67f9c7150d88f2b102c33388bf342b674b2e67abdf21e8e128fb6d28135d0d8ee4ef3e5423200dc8321adf5a88061ec91f44f307e6398e2e9f388d2d3cb4b3eda4e4f31918dc1d3a096b13cea11a1fd2ff17183f654edfc726812ea2efec73001e8b634e8d07d0e391c5acd42b5de1ce1512371cf9ed3688b2d93e403f4076a2de6cf808dab938c037272ccb418f134d55dca7a16b1ef5b1bfdc862301aa7a6329a5c7719f82b2b85fe453e7245149e20e4dc57ba287e8f677941e8f076bfd94cd4f6f91c2f871b50994944046eaba246c9865bbc435f087e2956d9ce3d36ad34caabe967a69d0e9897a0862dc3af5dd512ce0a65070ad605fd8b783c36fd6fbabfaaea8991f36d7c9878236ad3f607c33caa6251bf485f6f16a1ae789beef9f9d80b9ddfafdcc7ab3bda5deb5f03e864c051ddd9ab9040d5b6662620b2a95452347e60b1e30982dcf06531b9fb066177b4e2e1e8174f6e7846c10042ee55de255a26749ce9e12577c5184133a2fe0888fb29f50707df137d7aa2ebb1e0a92984b3387210879ea3ec4950277347a47dc4e7633880436bac5fc7bdc4e8776bc1b08f039247e53c24537b9dea1a3a26d2ba9d5a62b8e87cd707ffff6009c703d31e9dc3fd2dc9099526265a68fd52fc716e982f59b4e3bc48a46706555ff64dc932d77fba1ff89b56f4ef832099a8ac03ccaa2f0a32545201404a813e4c4bf726c40105bc45824b13078dc05dfdeded13655cb7bac8bd4070569314888fbcebd8e53abbee7bb472d65d41f068148647791c356c6d57eb37b49a7a46d3db13cd98f6c91bad25ae6cd50c74015ec142f13f9f0858b5c3a908ef818da8946ff25a3dc1c51d08e44778ce24e4293e8e97930c71e9fd1f8070ffebfa7c77cad94dc338e7e5c408cbcb64d45c61e60b648896a0e62386db0e77b5fe7aaac13b6a8267b732942e04909553701ac521c4500c5020a173cfb217ee5c32084fd2b3c2ad5e9bab93eb51e7d1721436f1545e153c971d2b152470974f85aef41c5ec8144ae93e368b2a975443a75b1334f37e1ee4b6ec935aac556fa481db14dae4d1d609c48a4982c18cd98a7f0fe76f925d562825c72e775d1ed965b017f5e372377b87c24e74811804041f1cd79e25f3dddefcdd33f2aed987bd21db9306df2c7f9bbb60d9953e0c2139c6a241adcb8f5b8fea1e543167d0d35ae65f48a7fc0f2a9d19b744310048fbf1dc6b329024ad9b35d3c7137e98c80411cb7b1a18c08591b357997eebe9a0c8ae7dc8dc1609a820eb8035aeead2303f2608939d7e5e260e4700aebe8e78d69c5e8847681519e1e30954b0430402f2e688e8414088d4104e77345f99bd218c6f6fe126d0da78745c04ce21e374f2b7fc61151aa084a0120b9b2a73f4c73b403a563f761aee101ed95d6933453641e714983ecd38f4d10e80e81bc185fd3c7b5334338e1ec5752fc9195fcd8a77999cf27d1c442c615e6839896b39edebf53b686bc94206b037b35440fe8d28100294f0b45245efaf87cdff66def91fdbc69595afd327804a75737e90dd42219679fbb7c96fec22e8a64312befde1712f68f001acf4a0e22ac723c60a851431a0921ecdb28a1a1b99a539aa8ab9609201de590a204e019b2a9ed274648f7b9a8bed0df8cbe339098fe850107098de5a8c22a82c13dfd74218a6c4bf5ebca6837015a1a1e5b440c35d05ed1b6b8b67819955efbc0fd6121f25aab01bb4784f0acd1ea12520575721308c6978ad15644ef59ce8756e174f07937d22bef45e097eca09fc56d2081c871556cad4393a576d041d8b9d084ed9db78d2f0a940bfa8cb937c618e42bb6b78edb351d1645d7a528115c0cc15a389d06c00693468cb959a6774c48beef9a6f10a9ea09096218f5927ddca96067a7d123226d0ec9d0e288f8bdcecf1dd9b076b6840b2b8a405d7cc5c51aa09ca4481a75223a7eafa29a63aa2502a46658d5c6e0b98ccf47d4108544fdece0a2e3628b59ee41c6b8760520720a19156588389b9f1c786697f5f5a827d9f56e53aca1cc9f414f1ad9823302f0f4b185b810532d3e25c7f42458fbcdfcb1564e14777acd708e3361d38b294f03339509252f5ce9d3b1913638ed269f3062310ef94375c9a6f9c42764ba31f847ee16ce2c8b639af3bdadf4602a5b9128d2ab0e7158fd2ac16ca3c61f132d6f413f2807c1b2720bafe4bc2b2388501b1f77a0753872bb728ccef09b3c4babf14caa2459fc2383e8b65db8a7fa78279ef89482b04fbf57b62bd00c8364bf0ae479d15026f5be9a4666d6a25ce5ea3cd8f9b92381f1b376563a338dd90fdeac13d51d20846ae9bc8605c8fd63e13dfce9dbcc8e89eeb320a1f6650b5ceb2e2ede81f1539aad7c25b50d0d2215f766112f0c1d92b57ead4014e7f8c0072fed7aa6af75cf897924210ec7750495cb619987f0efb346d469bf8cb5bfaaf018ce8a088d1174071b82b0789ff76b0514c80459119c5cb4e81a445db3e920cf34351dc0dddc0891d207c2ac3337a965826bd8d9060a7f2ba8c70e49d54be0557407f0c584b8b86ff230da6ba97c3ef2e083f30e4c7bbbe05bb781621ad3739547d58b8301ecde8ca184986415a4119695dcbb1b941b6bd9b12402badac6066cfb0796dafb4b543c16c1992943fd8d2f51b0d0d90528d389fd7805b6289d1d9227b91036f1f83b4c16a53e96f16f9f4fe8ee108e8f990fcd1fce02e35aa0f0e8f416c98253209cf1753551d7c392ca67116cc682a2bb3f936b30470509f6b7d4139dc1f167500a589fa93839eb066018264e4dbaa8fe09f83598146e34fefea5cf8b196536dc04544946992ecddc9e620b055f86e50e3b5a0ac064ecb83eda8d961e30975abb4499be7777650b93fa4ec0ce8b592998969c627de6e4359d722db7f36265fbe9b8a7b9c1c67f3ad7334883260846becc1da851297cb4a495c3acb7e095bd469241a18c0a010dcd20a797fd946d6fdd351082a9bfc64a4da2b6046e083344e020ce37188ae7bdf4fc58cc4df45f192b410b9af6210e16c3ff965717d62805d9acbf9d283cd823d20819a6e66d8f9aff3d30f768c25c96feb1625fa7f9f8ccd12c6919dc3f62e48df7f911dad1b7d857296b2679a94b2c3e35f0f0a36610d5615f454646592573919148263ecb4827dbe2cd70f5084b7183f48e0e6c5f48125d307a02892725248e1f271bee208e01d2aaf1fce4b8cd4fcbe6e843352c0f167fd914aedfe86cd124d444ba9e2259abae64eb465e3fcb507a3e566ed7e4be6b78e6347f258ba999d26568ce8be8e14ee68adf02af053c83a518aa6464e73be5fb6518215e0ba487decec8fbf6a94553f74e9c7f4e7381c6382b866970aaa95b986e4184415b8bc9b1a98d50aabd92ba28c73bdb14c65af3a0fd8b7c3718feddff47b18fa252b4a4ab3a3d4e83663199dee78741c2f020bd1bd4950c61c27cbc71680dbd6ff1a9f2e863439c2890c472521b15dc86eef5cdafd614a7011191a87c5dafe611cb20b46eb47c12d4b587c0d5ff0d03735b7e7fdc828fade1e834a8802b76a4990a6b5d4ba6defb4b238753fe56d6bda7aec212e14b185f4db189ca2d4e466ea47bc4163e8559e197e1fe643083697475a422b7db75e05188fc45d68fc2500af8438a010da4b1bd0ef2f25b833bb1a3eeef5eec2ac86f79e24116f03e692b8aaa6fafce1521100d29b39a6cf5d75a92edd2264b4227dd9f59a709c6202165c49d9efe49b2fcab1b7d74e3c402774dddf63178923d6f1bd4576a13a25ef4788ebf5b3d53a842c7c5184963e8e5bb2f315b2bab1100e350ee4a8ea4ef15b876400cbdfdd0ad70bbc610ab1cbd4a02a71606839aea56a3fcc3f6aae7b4471468ad723d19e49f54fdac3a92715522d9d7616bf6247b2fd4484573a72db2a5c3096d81c1da30520f883efd3a71ff798e8c5007f42613d3116e9667922eac1c60275940322e813a1742acde9eb4d8cb1884c145a5f5146974d3e42f73a150a20468a72dcaf0d1d0eb729e300a78a6ab1795a0d924530270add679dc80b381ab9c157cfa20abb15c0074666b775003ab2f159eb3ae1519b9c716e6817ce7c360080273c6b90904cddec25cb5f28a8e292d801621bdcdf00b9d5843ff976167d49eab357ab030014b46d69ad79f7a4ebbaaef03eda9d95c60763d678c48e032b68c55fb2b684596e2909339b074c5a830e8ed2fede9de30a2805310829845ecbbaed46aeb9288c2086887291e04356bc77aa636359170311dbe1b4fc0d4722866be1669f9152e2474c5e5aa821a27b53219545c163ed921348aceb379414fc477b2d35aeb7d715df535b35ee4d6f277d02bfed4ee25e39e7ec2a9d7d4f1de0e7c63dbe0525ffb908fc231100aaeaf06321e3277632d0ac78fd1ecac1f2c1946a62a896cd26693e4535a20cec5c39bd5dfb848346b0e6ed81e78c7ab94a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + }, + { + "tcId": 58, + "comment": "100 random bytes are stored raw", + "flags": [ + "StoreRaw" + ], + "inputs": { + "class": "ordinary", + "chunk": "3eea3f651bd85ffeee3ddec73a59aff968f34c657bbec6ce3c51366232e2d0076b205d77cf949e09d51a439881273bed19ea9e951cbc2a5e1e5cf91f41722977b52f7b1ea8e628496204c9358a07181314ab48a7208f71c5c343847d7b185f76f3375015" + }, + "expect": "Ok", + "comp": 0, + "innerLength": 112, + "inner": "0000000000643eea3f651bd85ffeee3ddec73a59aff968f34c657bbec6ce3c51366232e2d0076b205d77cf949e09d51a439881273bed19ea9e951cbc2a5e1e5cf91f41722977b52f7b1ea8e628496204c9358a07181314ab48a7208f71c5c343847d7b185f76f3375015000000000000" + }, + { + "tcId": 59, + "comment": "an empty chunk is stored raw", + "flags": [ + "StoreRaw" + ], + "inputs": { + "class": "ordinary", + "chunk": "" + }, + "expect": "Ok", + "comp": 0, + "innerLength": 6, + "inner": "000000000000" + }, + { + "tcId": 60, + "comment": "1 MiB of random data is stored raw", + "flags": [ + "StoreRaw" + ], + "inputs": { + "class": "ordinary", + "dataKey": "9a035ebd1266bfc77e431879f4fa33a6849d6b3d59285afca003ee1b4aef80c7", + "length": 1048576 + }, + "expect": "Ok", + "comp": 0, + "innerLength": 1081344 + }, + { + "tcId": 61, + "comment": "a secret object's text is never compressed", + "flags": [ + "SecretRaw" + ], + "inputs": { + "class": "secret", + "chunk": "54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e205468652071" + }, + "expect": "Ok", + "comp": 0, + "innerLength": 5120, + "inner": "00000000138854686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e205468652071000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + }, + { + "tcId": 62, + "comment": "a secret object's 1 MiB of zeros is never compressed", + "flags": [ + "SecretRaw" + ], + "inputs": { + "class": "secret", + "zeros": 1048576 + }, + "expect": "Ok", + "comp": 0, + "innerLength": 1081344 + } + ] + }, + { + "type": "Decompress", + "tests": [ + { + "tcId": 63, + "comment": "an encoder frame of 3,000 bytes of text", + "flags": [ + "FrameOk" + ], + "inputs": { + "frame": "28b52ffd60b80ab50100d40254686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e200100451cf45519", + "plainLen": 3000 + }, + "expect": "Ok", + "plaintext": "54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f766572" + }, + { + "tcId": 64, + "comment": "a raw block of 5 bytes, one-byte content size", + "flags": [ + "FrameOk" + ], + "inputs": { + "frame": "28b52ffd200529000068656c6c6f", + "plainLen": 5 + }, + "expect": "Ok", + "plaintext": "68656c6c6f" + }, + { + "tcId": 65, + "comment": "an empty raw block, content size 0", + "flags": [ + "FrameOk" + ], + "inputs": { + "frame": "28b52ffd2000010000", + "plainLen": 0 + }, + "expect": "Ok", + "plaintext": "" + }, + { + "tcId": 66, + "comment": "an RLE block of 300 bytes, two-byte content size", + "flags": [ + "FrameOk" + ], + "inputs": { + "frame": "28b52ffd602c0063090061", + "plainLen": 300 + }, + "expect": "Ok", + "plaintext": "616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161" + }, + { + "tcId": 67, + "comment": "a window of exactly 2^20 bytes", + "flags": [ + "FrameOk" + ], + "inputs": { + "frame": "28b52ffd80500500000029000068656c6c6f", + "plainLen": 5 + }, + "expect": "Ok", + "plaintext": "68656c6c6f" + }, + { + "tcId": 68, + "comment": "a raw block of exactly 128 KiB, the largest block", + "flags": [ + "FrameOk" + ], + "inputs": { + "frameHead": "28b52ffda000000200010010", + "frameZeros": 131072, + "frameTail": "", + "plainLen": 131072 + }, + "expect": "Ok", + "plaintextZeros": 131072 + }, + { + "tcId": 69, + "comment": "a compressed block of exactly 128 KiB: raw literals and no sequences", + "flags": [ + "FrameOk" + ], + "inputs": { + "frameHead": "28b52ffd8038fcff0100050010ccff1f", + "frameZeros": 131069, + "frameTail": "", + "plainLen": 131068 + }, + "expect": "Ok", + "plaintextZeros": 131068 + }, + { + "tcId": 70, + "comment": "plain_len 2^20: eight RLE blocks of zeros", + "flags": [ + "PlainLenCap" + ], + "inputs": { + "frame": "28b52ffda0000010000200100002001000020010000200100002001000020010000200100003001000", + "plainLen": 1048576 + }, + "expect": "Ok", + "plaintextZeros": 1048576 + }, + { + "tcId": 71, + "comment": "plain_len 2^20 + 1 is refused before decoding", + "flags": [ + "PlainLenCap" + ], + "inputs": { + "frame": "28b52ffda00100100002001000020010000200100002001000020010000200100002001000020010000b000000", + "plainLen": 1048577 + }, + "expect": "Decompress" + }, + { + "tcId": 72, + "comment": "plain_len one below the declared size", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd200529000068656c6c6f", + "plainLen": 4 + }, + "expect": "Decompress" + }, + { + "tcId": 73, + "comment": "plain_len one above the declared size", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd200529000068656c6c6f", + "plainLen": 6 + }, + "expect": "Decompress" + }, + { + "tcId": 74, + "comment": "the frame holds more than it declares", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd200531000068656c6c6f21", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 75, + "comment": "the frame holds less than it declares", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd200521000068656c6c", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 76, + "comment": "a valid header, then a block of the reserved type 3", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd20052f000068656c6c6f", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 77, + "comment": "an encoder frame with a content checksum", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd64b80ab50100d40254686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e200100451cf45519feb64e8e", + "plainLen": 3000 + }, + "expect": "Decompress" + }, + { + "tcId": 78, + "comment": "an encoder frame without a content size", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd0010b50100d40254686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e200100451cf45519", + "plainLen": 3000 + }, + "expect": "Decompress" + }, + { + "tcId": 79, + "comment": "a dictionary ID", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd21010529000068656c6c6f", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 80, + "comment": "the reserved bit set", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd280529000068656c6c6f", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 81, + "comment": "the unused bit set, which libzstd ignores", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd300529000068656c6c6f", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 82, + "comment": "a four-byte content size for 5 bytes, which libzstd reads", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffda00500000029000068656c6c6f", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 83, + "comment": "an eight-byte content size for 5 bytes, which libzstd reads", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffde0050000000000000029000068656c6c6f", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 84, + "comment": "a four-byte content size for 300 bytes, which libzstd reads", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffda02c01000063090061", + "plainLen": 300 + }, + "expect": "Decompress" + }, + { + "tcId": 85, + "comment": "a window of 2^21 bytes", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd80580500000029000068656c6c6f", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 86, + "comment": "a window of 2^20 + 2^17 bytes", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd80510500000029000068656c6c6f", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 87, + "comment": "a skippable frame alone", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "502a4d1804000000736b6970", + "plainLen": 0 + }, + "expect": "Decompress" + }, + { + "tcId": 88, + "comment": "a skippable frame before the frame", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "502a4d1804000000736b697028b52ffd200529000068656c6c6f", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 89, + "comment": "a skippable frame after the frame", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd200529000068656c6c6f502a4d1804000000736b6970", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 90, + "comment": "two frames", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd200319000068656c28b52ffd20021100006c6f", + "plainLen": 3 + }, + "expect": "Decompress" + }, + { + "tcId": 91, + "comment": "a trailing byte", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd200529000068656c6c6f00", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 92, + "comment": "the last byte cut off", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd200529000068656c6c", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 93, + "comment": "a wrong magic number", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "29b52ffd200529000068656c6c6f", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 94, + "comment": "no bytes", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "", + "plainLen": 0 + }, + "expect": "Decompress" + } + ] + }, + { + "type": "DataBlobSeal", + "tests": [ + { + "tcId": 95, + "comment": "chunk of a two-chunk object, compressed", + "flags": [ + "DataBlobSeal", + "KeyedBlobId" + ], + "inputs": { + "dek": "17a7dac824a32729589bcaec172413d9e99d976d1b0ed80e60379c81dd68fae9", + "dekSalt": "249eb4ef146c06c4d759821e22cebde84710ad244f2b5e2cd9f2459b1e56eb41", + "vaultId": "ec8d131b35b305fb497608f75594c41e", + "objectId": "67287b3d2ffa766196af8f71b64294fb", + "dekId": "25d78db5f9c18a1423db5473f368baa4", + "class": "ordinary", + "chunkCount": 2, + "chunk": "54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f7820", + "rand": "7b369076d937a412bcc5d4aeb5c6bb7380afc12f12674d6ceaffa32941e153bc" + }, + "expect": "Ok", + "blobId": "7a127a67ae4da26d405ea0f72eb90719c9ab083e66df588ceb32637c8bedebe8", + "inner": "01000000004028b52ffd60d006b50100d40254686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e200100051dfeaa0c0000", + "nonce": "287ea362f315efdc12fbfb7d8268f28b7c94709f99eb97c4", + "sealed": "287ea362f315efdc12fbfb7d8268f28b7c94709f99eb97c49e371e0fa89c02249e3c338465906faa4c9d0a8cfb741a3f279b13a4ceb2b67bfef8adf8bcf1a2b3468fcc6cd69882645fc640e9a843d7c2321a5c81abc7d8a1c7a234577ebc312488e0a113120fd7a26f42bd51331a855586871df50d30d34c3640d15d64c42c80860c8a591a4568a054b00eddba31db6b" + }, + { + "tcId": 96, + "comment": "random chunk of a three-chunk object, stored raw", + "flags": [ + "DataBlobSeal", + "KeyedBlobId" + ], + "inputs": { + "dek": "17a7dac824a32729589bcaec172413d9e99d976d1b0ed80e60379c81dd68fae9", + "dekSalt": "249eb4ef146c06c4d759821e22cebde84710ad244f2b5e2cd9f2459b1e56eb41", + "vaultId": "ec8d131b35b305fb497608f75594c41e", + "objectId": "67287b3d2ffa766196af8f71b64294fb", + "dekId": "25d78db5f9c18a1423db5473f368baa4", + "class": "ordinary", + "chunkCount": 3, + "chunk": "4b22bd4dfd68f528f3c8890bac308ce13f22abeb7529a868638b7565d145f273884f26dd7652ae1d7a6f42c3aa507df44bbada94500d198d17e2540eaeca30238507b15cb7277d5fb03d7ba02e83947f7059904ac728f6b81885f70fed52109ed371c33e12c926121ee46def0a72f2f3ec5361ec3e45ea68b6402e469bb9be1250daf7c61b3c20caa06667d3013e1dc94e43c8bc5f0de302e22176ecbb3106e244775f2305bf2472b550dd400385a26ae80a64be3f75fb5dfa9932adcec183dc18b280dbf7ac42b1879bdd6cbeaaffae7b69d61eddfe68a340ee884f05874f77fd881e03c1dff0d59596d67744ef30109c51e1b2e483ea2abee339ee09d71ea5368c3e1f9eb1794d35e7ffced46b3e1cf7dbe4195f1b1c0aad7a2d9b9c2b90e549271f2c5aae99f7a29cb05c55bce81032088ab2a6afaef42df1844835d4aa0ea11f338388fa8bcd2fcb635ec298726df46bd7c3a02c234dc967efda6a215f8fdf90f11e84d6ca8161967ca32b29a4e9e5bfa894cf2da5cdee99d57fff1cdc9ac9deeeb6b46b113dcadd1478baf0618b0ebbb3663db692f399d7921f9fa8cd1ce62bcc0a9c10c15d62bf6ac35008ab5da3ebd4f7d5b1f0c660b84d68c70dc7857a19c31d1ab13e28c6cafeb88bea026e1223a904e3f5ea6b5369cb2e00ad57459eb9ee7b74fd02704b4d64a049c6f351761b404c", + "rand": "897ff64010e755923c7f3bc91c32a8b2627f106b792fccd640ce42d1e8f62f9c" + }, + "expect": "Ok", + "blobId": "956dc90bb0807d0d469c7798b7ac058b91689e317c609e2a5e5b82fbdc86d318", + "inner": "0000000001f44b22bd4dfd68f528f3c8890bac308ce13f22abeb7529a868638b7565d145f273884f26dd7652ae1d7a6f42c3aa507df44bbada94500d198d17e2540eaeca30238507b15cb7277d5fb03d7ba02e83947f7059904ac728f6b81885f70fed52109ed371c33e12c926121ee46def0a72f2f3ec5361ec3e45ea68b6402e469bb9be1250daf7c61b3c20caa06667d3013e1dc94e43c8bc5f0de302e22176ecbb3106e244775f2305bf2472b550dd400385a26ae80a64be3f75fb5dfa9932adcec183dc18b280dbf7ac42b1879bdd6cbeaaffae7b69d61eddfe68a340ee884f05874f77fd881e03c1dff0d59596d67744ef30109c51e1b2e483ea2abee339ee09d71ea5368c3e1f9eb1794d35e7ffced46b3e1cf7dbe4195f1b1c0aad7a2d9b9c2b90e549271f2c5aae99f7a29cb05c55bce81032088ab2a6afaef42df1844835d4aa0ea11f338388fa8bcd2fcb635ec298726df46bd7c3a02c234dc967efda6a215f8fdf90f11e84d6ca8161967ca32b29a4e9e5bfa894cf2da5cdee99d57fff1cdc9ac9deeeb6b46b113dcadd1478baf0618b0ebbb3663db692f399d7921f9fa8cd1ce62bcc0a9c10c15d62bf6ac35008ab5da3ebd4f7d5b1f0c660b84d68c70dc7857a19c31d1ab13e28c6cafeb88bea026e1223a904e3f5ea6b5369cb2e00ad57459eb9ee7b74fd02704b4d64a049c6f351761b404c000000000000", + "nonce": "e9fab955b2d782604a93074495af8b8e52418855058583ea", + "sealed": "e9fab955b2d782604a93074495af8b8e52418855058583eafe013ba6c229c10c1eab1ba3bdea26be13ab8e4b986431ea157c92931c7bb60332e268154e774169017868b428f92df8234645d14afa1c95b7f513e0263dd89c96faa07ff2cd4974e3c8c765d2b81aed9f8a549e8691e47c005f3459d6c2bd87fbd7c8a14b043fac87f930b82013d72217b4e39d752cf99c43d7ef006e96f857189af97febc921db3becc426c5557f556715407531e1809a3315a159c3ab4b0102f1d47b16f37b53f48697d3b2caaab2540d55b8e138112c7447d897caf232c777c03ea4559b07aa365828b186aba7d2e3ac086af1553f3a4f8436abf20a736305942cafe1c0e38aee60fdee1bc129728e590fe9a3f678e774022a9dddd502270e6112bc6592c95fe0eb15fb324ee17881967a19d0403a7086374044ca550cb736e1b95207c077a3366ffddf178b2219766b42605b9c8558fd7f40dfe8fb4fee389f0879d88f59046077afbcea4b05dd4884ab0449c9ab0b28cea197134c9058f3abf41697c0b6ea07ef7e102a51d13127c2f10326030b6a94bc3dae020db63e3f6a29552666ee86426e5d4bf54ecddf6b2806de7f9e8aa47f40ef48b47210fc7a441e793e853d733aaee052428ac93d9caaa6a34594d8a2e7ec4b61bdbe3a75ba33fd87bed28c6f390dfd27d1cbc028c26f82744b718159df95225cb709d835d35c27711d779e8f142397c57f3f0a4d540653ad06bb4804d9f0f3017e2d71ea0c95a498b0aa213aa627e04802472d2037e3368e4303584752360636a792aa8a485dd0c0fd5aab44693986f92cd3d98a" + }, + { + "tcId": 97, + "comment": "the one chunk of a single-chunk object", + "flags": [ + "DataBlobSeal", + "RandomBlobId" + ], + "inputs": { + "dek": "17a7dac824a32729589bcaec172413d9e99d976d1b0ed80e60379c81dd68fae9", + "dekSalt": "249eb4ef146c06c4d759821e22cebde84710ad244f2b5e2cd9f2459b1e56eb41", + "vaultId": "ec8d131b35b305fb497608f75594c41e", + "objectId": "67287b3d2ffa766196af8f71b64294fb", + "dekId": "25d78db5f9c18a1423db5473f368baa4", + "class": "ordinary", + "chunkCount": 1, + "chunk": "54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e", + "blobId": "9efa292cdeb8d24055981d3be1d832f6c067a0b88e106fe415b98ce9a9002ed8", + "rand": "1a55bbb1064b908b95e93bdbe76ded650ec2dc8f71143653d561adcc559b6dab" + }, + "expect": "Ok", + "blobId": "9efa292cdeb8d24055981d3be1d832f6c067a0b88e106fe415b98ce9a9002ed8", + "inner": "01000000004028b52ffd60dc04b50100d40254686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e200100650dfeaa0c0000", + "nonce": "b26cfb488a1cc111d39e064e86d06960523725b18a8593b8", + "sealed": "b26cfb488a1cc111d39e064e86d06960523725b18a8593b85f276a26a89af8abb86cd23304b23be45435518846ff172138d64ac8a95a29422c77d1c8ce1e359d10e66b9f6b521e39b4bce065a207bd7548aea64de6a2f7e1cf48ae638dc8db429a247ede35822a14444ec7d434a60ebcaae477454565c20889861f0b57627c9f0aa5aae0b0ebf370b886c4ab3070f52a" + }, + { + "tcId": 98, + "comment": "chunk of a secret object: raw and a random ID", + "flags": [ + "DataBlobSeal", + "RandomBlobId", + "SecretRaw" + ], + "inputs": { + "dek": "17a7dac824a32729589bcaec172413d9e99d976d1b0ed80e60379c81dd68fae9", + "dekSalt": "249eb4ef146c06c4d759821e22cebde84710ad244f2b5e2cd9f2459b1e56eb41", + "vaultId": "ec8d131b35b305fb497608f75594c41e", + "objectId": "67287b3d2ffa766196af8f71b64294fb", + "dekId": "25d78db5f9c18a1423db5473f368baa4", + "class": "secret", + "chunkCount": 5, + "chunk": "54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f7820", + "blobId": "3774ab5484c4451a5a271bd7391e16fcc39126c0e80586ecf00649cc3c9fcf9a", + "rand": "d97e5d426b20ea2a38078e9299369c75470c2e6975ab13245d538b0123c1bf77" + }, + "expect": "Ok", + "blobId": "3774ab5484c4451a5a271bd7391e16fcc39126c0e80586ecf00649cc3c9fcf9a", + "inner": "0000000007d054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f7820000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "nonce": "c1212f8fed75167d750e1ab8c097e8e485a15202d3d6048b", + "sealed": "c1212f8fed75167d750e1ab8c097e8e485a15202d3d6048bb04345f1deacd05fce99a9d8e8106f7e79463a6ed442eb5009576049e963511200301e049863b1c2e71519c443b4027ee579a0db94d1c20d11a7d1aa01a065d6d794e6694bd43a7180c1eea6206e94440af7bca69be1d4ede4e064bc1f270fa82d09ee8756c6f9bb76f987dc29eba43444ffb2a9e452a7588656ec7e09927f591f88d3dd37f251b85aced2bebd1c50fce84100df86439e71d4dee987164696e6a9df375124a6742c7c49c8ea6ea8249d35d504b88961c3f6dd81410487e79f4b7b645db500c17e3098819dd1b8d6305dca248fdc1442c741c73d5a156eeff6f5ad64419f711dfe608937cfc5fb336b8a5a441a0e98c102817b5c5f1f69d6f12726c2c573612fb46ed2f668efae31bc189bb05bc79870dd2ca5dbe6c7dee0e3f55a2528ba3b15434fbbc1acc4aae376d1d17b0d5fdcf46c79683a87965c4b061376a19c57da1f34d01fa4877e97ca4661aa0f064db9a17915fc1ed6dabf39cb75fad297de32a4cb81aaf0a9d379f87a89a08fd67f5880120dd76a31c69806c26b6395cda770589f077e320e4ca3e92a3f86a4cf5a594dcdd867b3d6a9e6980c64f770975640f8c389e2d69a1d0d8e4245904fbabdaf41bd39a21e8016328d588a8fcf186c4cfddda5098d47ce60ec0d76e3d96866cc34b3f5b05b4efdef53488d5fcda4fa991b688293a36e4e236cf92142eafd4a5ae666d9bbe4c556307c65f2d6f783dade7bbd3084450cb8f4e1eba8bc578879381211802a888ff107769d7a49f22873d95fbb3ad5a92473a5f3a16eb429f0f68d744214d2f8b499ee933554f58961729531c778e1b4a729af38fdad8865b3ebaa0436077da2860330aa899c248728d2de84ec1e1fd44bca2ea1ae64a11ee4d129f9a9ba7030feab1f2f56eb70f668c5776b3ebcb2d2e455fdca886ce7531d4b0901fb8185b25215c0b04c13bb5685cc10fe60e940f0d51f2612d79a70ad3ff468f340660ff7de2acffc7088dec7d19e5ff525d2e042af226b874e1cd1dee4aa5cdcd7b6514b09532a8468c65d75e09c0690a2e4941d3384e21e9e57f4aebb5098623cf89b363e62c75933dd16c105ebc31d4114227390e0015175f4d410aa231683132c0cd3a93bedeb2b2be2290dd2bd87a5cf17ddc72eca4dc823edaf2de93620984d55ab8a5f39424246950e2e6bf2881be315c94f7f9b8212ddb8efed482b689fb8b671926067747584e9cf5791251f50b1e6908cb7ed53459a513270d767ca6ea983918bac58c10fa22e01586d5fc6397b69e7d4e5fff2896fd88388b4699bef2b5aed0ac02c19cefae4fc070aced3145fe7f7ee7ae146a73c768f7db4e6c4bf6c41f6c8ca1da93c2bc7e59bf38900e17979258b0ae800c46d00e45c7f95a6985f7613250515da5618226607683bd87144ccd7d6d519ec9371deb3c531bd404318dec5ed52ac92b5292396cc9c24ebd84b534e1577d2d1ea95d73cca3422f1d0445d52c806fdfb6d0a44a4450f4baec9a0be03c83e0f8089a6d305b8e3116f98a669fbfba684c41cd0ba92dda2e62cf12ff8a947f2ca33d1b3f31e472a4cf1ac629c4f875a0875ed19dca077c4eb12838683dbfd21c93964a958b743b8925272f48c63684c7539a8d75d55c162563c2ba220ca4d171e872ad0185c391d49bd8c10bec823da794a052de5afd0b8346e638c5331a461ed963bcd705a15f779e5736c80f05de7c3968178451b45e614c2b53af0d2b9a99ddddd090fb5ae387385dbe05b353e3f336162ad77f064619d2d7a1dc8ef3ef4d2d7d8a74d9780b43aaa9de6a09153951489980376fe217f94c38d41c2e1732723c28bbaca3b6f3b65f5b4614f6e9d71c16212722a4e4ac4edf9ba352001302735866e5c7b059c8f34fcc5aa685f95b71806df30922a971120d8f6402c771ba279a0bf27ad36cf60f03207242f4824a4699002594f4e09cc72d9396252ac125b3dd1a0b5df2df6b964920d77c9cbb20ccba2f35c6f26d0a1e03878af4ad6fdc360fb05719d6f63c18f4b6c9d306e6cd17b06ae66d976df6c12298924da0b253b87ac782909fa951e4fb4f586fbed987a79734064c7bbcd86c3fab7b1d70d7012a2a182560e1607e791f980047bc371eef29effc416376fe27d850721eeb2a81c48041e4cc806af48dcd98d0f82e6e24aa7fc1cf78d923a2f7533d9ebadf9494f85855626d82026a284c3cc9c44dbc321ff427942534a02098bb4f9594ed0bcc8cc3eb667ea5420a93a170de99f937385ddc21b6e2df81f8af5bc5cf3ca6ffb37f663afc101bf3e2fa1c48684dcd654af028dccd03137141f82dd6cc160e69de15f1bff3737e41dd6148a15de1e8752162076d8ee3d81465d0aa0a4140ae1bd3469ab0b65b3130260cdc3b28381a9361a469ad91a8298540290a79bec54e32e36ce25b7dc4dfde42e532a0f73377fc282e6afe2efbbc1bb59d9843b997d6cf2242a1608204284178497f49ffb6e42355a63343ec83063091a7bda92019e169858cf81ce0643d1e96f954e4ad1ec24798b5ec3c8d5e286593b6b0661497d0c89720ae65c597539841ce0dde59873f8c330b5502f2dd1ebdf226bf00b078233025d02e813bc31ec36cbfb23d5c3e54851e908da0d1bd1c19aa9d94a7b7ca4a747640094a35bd44d9015fb9f72bba953816552126268385babcd3fe42336fd749d0cf864d215392902711cd61a3801216a4c53c3e8919f2a3cf2025513c5a7466164b8e742c72785512705a883365e6f3c9d842d3ebc60a2b9d1c58225c7691a3b349a9c90d9328d85e78dc78b5ba5324ed5a68f6c552a4fcc17c26b96665074fe7e17dbd76ca6019e9a0ae8c7cf0471d2d4472a08d9b274329897af846c220e0247a3ad1d8ebcd16007d83ed81bd003cda6e141125eac53ec431eebbac1a578cc127cd1cce6c56ae1d5d38c9eaf1c1a2145786913c1358d5e144f98028080606b0ff510b240" + } + ] + }, + { + "type": "DataBlobOpen", + "tests": [ + { + "tcId": 99, + "comment": "a compressed chunk of a two-chunk object", + "flags": [ + "DataBlobOpen", + "KeyedBlobId" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452324eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc2b3edb9ba9daa6a8205a9a4c39ba9727f9804b387fd051e63e52a80d74bcccbd58175f5bd7354861ff1a1b994b9610a0c3fa9d17ca6d1dae7c20f9992a9dbe2496efda451ef8b55ea42741eb1fcb586c681fa75bef3197cf" + }, + "expect": "Ok", + "plaintext": "54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f7820" + }, + { + "tcId": 100, + "comment": "a raw chunk of a two-chunk object", + "flags": [ + "DataBlobOpen", + "KeyedBlobId" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452324eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc2a3edb9bae4ada756a878be9566cfd074ff0702774d046fc2f11a9587bbed0ea59415c468f614a71b20609c35dc011bd84a0d52682645ca57069fe9d6dd1ec4ae184e7dddb8c95342dac653b527d3b9b03935c149936a0af259cdf27f0481f20da1c0055596934a95fe9ac930da172eb8e8c56b1df67179cda2d438f4df1b0249e0620690b52ee2f2c85344ceb1765e6b8983219e31c4608bf9a8e405d98781e2985a0299d70fb2469658d4570ddeeb42a3ac5d297bc0647b5712bf4a2a426993d56dff9f4479481d0f05c1ecae49488bd79994422832df81df3c939f47b603dc3e05bcb92bc3aee4590b3fa8f955fb30bbc412dff292d54de22b829aab2d504a64c961452c9f75b70c2e782bcc1d1932d865f248557cc58ffb75827ad137d9a658cc7b4951d9981edaa47c231d7779d465597607c7627c37efefd0772ce4ed0506e17944296c50cb771e2585ff124a5d44d406fbc79587ba5d1164356dca96fb0acbf218c14d2966acaff5d0b7fdd99d30f8cedefb4a2cd0b0b28435706a0be8ec51f46f608c2d3325ab45f61f272cea14e5ad1d8cdf10eda3dbcf40bbb1c7d15bdaa68bca9bd11c525c15df6c343fb46faacf8b8cad817f31505f2d415b878d697311f4befb13eae5bc8f87f508d9c6d47f015d1c89cc34958353341a77bd2e0f00452479067718c99659cf38ea7d82e65df82e9fead04e017ce8b41e1a1787c43ea0869c769d982861299d50e3ac94ea2b4c1c15b37653805415626a145a0e842a5f65f649664aaaacac8ba703d679ea2e1256becb03a7b173fbde0e4eba17c6b6ae91da4827884d02e2b6f5f354f78abf4afc3b05464ea731b98b792511ce63a36de91aed63f9e4a1cdb075c8a5359753b26f8ca76f3f3a2940056b94fd478ba3c55a1fd4a46cb0375a893993b4f157fe3e62d9f0532ebe6a64395d080e835bd8e8b6f75e43766efd6ad9a139e347d057e1abdd662ce2c554b02f4d938e8bc80361fa7ff2ce22a85211c8877d3eb5e010b79a0eeda4eaf9f400cccc74fd260ff5668cb12f60afc41b537e2c76c22a90d459055f1e407f09600887c6872aa7140ae6d5e4d3c36d8e82ac16cf9d7b53e2f6812ae73fa9f43a59bc12a2d06729af118f48d88a6fb9ec8d2cc6318bb2c2bf54c8f23aa10efa4eb657ac62d8c34c26488d6fa39608a11e14215f43c1a4dddf04daef2c643d7392d7c9386ac89b4aef66cc83c7458a7e49d56b9d63c75e801ed9e14a1a50a59d868db9daaee7cd1e4d783d13ea242ca156d4ab8aaf14f217080be516d7bae4f4c5510891b870f67ceb1c8e726dd19ad2fe63c64f779425e8c88e943f00c47b195c27ffd50c412319c691e729a0c3c2bb483f0bce4b99e903398ea6ffffd1449bb5090bec1b28228b5260aa22e36b893431e8ec5ccd12aff33ba045c1f549883c7559b4d8f61568ff7bcec486d5e233c8bbc9cf40cf9e3a0a7e1be410fe4707d216150c7bd4719b6c3d8fbcaa7da3f7a634ff09fa6e8e35283efd452eb3f368b1ff5f64738028b52d715d61d56fa0c89bf8fe09120a1e5dc10cc8679cb50c217507f3bee88f5bfc3d65d76e6f04645982baf459353b380b523c6637731a4c86c8c2f9a29b39ffb98a0f809e7d96fc1caf7a9ee654c05ea093cac859ed3eb619da22fc86f5f32619a63a0af117b19be988a59df4f4f17596b3716fbd552083bc166d11675151167766de70f99b2f8e725744ca2b61702a7251d66278852a118d6b059f836f314b1f710e685737b5390ef410aad645933cdbcb9fe2969171c86b2c53f0c594b2e488aa6575f155ca1a5e7cfae9a699baf0469c7af59596046b5ba2cc60fbfb7040f0c17fe2fd6342e8f809a6f60e55f13b8b7c5e8ea960d433b60d7360b6f0d0bdb4c54370ec8ddc1c7acf833dfc85c723e15696ba9e7e50aaaac19785dd09b1bc20899b6496010f53c46fa0afe1beb4523909dbe74ccd82a50837776ba012964d4184f13f23309cd5387e5d17d04a05aebd0297c6ba1faabeb393863ff89e88f94c1de1d9f7722728f61a6ea15746d66eb93b81b2bf21585949c2acb47890b924b5e112dabb8b55e9b859834e0e6f8b16eb955adf031cf9ac7ccae70c66bdf9d4e4da7f0e735a146b15f9b41d1de447b4b53ee4b80ada77d65901213943a7e32b70b596e447d3e4cbf7d90697f1257502f33fdc520d4ced209b859fb6edf2b53fa16cfbfb517d69b3461768da6dc2e419facd292cb4759752c3f5cdca8b5f8112e84805ad1fc049c5d226cc44ec35021d6ba91d1514cafceb1dc9a104fd7d12bc82ccaf90bca0286fe96a7263205380647146c754901042ce58310f08191bb592e39bb8c8bbf00248e5bae4e7aa9cf85fe8c0112bd5f2ce4e6bc56ac4d13bf2ac0b745dfc0ddbd54ba63b2718b3134b1abddf7481dcebe3384d10896996870525cd07bc6c19fc85db4bf4ce2491e5d3365cfd37f82d0452e1eb40fbadf4196532ce8f20ce0c60ab1b3bdc22eed65fc968cf9cad7d51ece382c9c767e89b9116f6ef9a35b68f391c1767cc2245e06c5bf19617066454490613f082da16faae7b073f571e8d0a48539fa186bd15e70ea2ded3c303946fb2bf071420de970e03d1b6a9dd93411f4d5380ffc48cf934f5697ea6f1909125a09eec4c0bcf2c07c3f2532035d83a3e58e4354f374d7f9fd8828511e27f541103a8240ad162c0f591e9e8ccbf88c1ec0c15d5bd789952eeea687c468b783a209d03375d5c598df7fc73f85faeb8e141295456273b416b557269fa9a80644869f004710a7d6df50ab390f526011167ef4f6ba5846aedaefa46c3ff0332b4c7a989d74bba349c91865c2e5269e69252d1f916a01b0451a4a8c268b0e61375a96775ab4562896a08945947033a51a42e80a0cacbfba6f126ba3dd068a4a" + }, + "expect": "Ok", + "plaintext": "54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f7820" + }, + { + "tcId": 101, + "comment": "the one chunk of a single-chunk object, random ID", + "flags": [ + "DataBlobOpen", + "RandomBlobId" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 1, + "blobId": "e5fe2a5487334d4f959b728ea76fa8ba8faef343cfb1c56ae5ea0014424bc3a5", + "plainLen": 300, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae84523256c37f9ea3932f2ed00ced28a1a5ef036399335529476902d7a330c50569110ee0fd4499c48d9d5a8766798921177c8ba758c9770e88321a1cb6d210de638390e546067d0eeabf8bb4794aa069a5d060ee2f3c385898ffc25894dc4a00475d2beaa6e72ddacd1e4a46d3f0a9634a19687f71ca41108b5906f4b92a00dc389220d1e3ac6b2746618f72b6f8d77608ea488cb2d4da10e51ccf3811d114f61a5b6a97332a99a7081bf6d98f6ccb8c93d68ce22511dd5c706318841cc96f2b0841af28be781c1336ed700476623434fa9ff6e2a83e0dbe325ceefd921e97b440430b2b489cd7ec71e159b60d716550a62938e816ec500acf25cca43d8b8ec7b885c54bb4924c581fa4f2f2738108658af2424ac64bc24e49c08d8d9646fb7c5345e57b110f71fea1244c7486e0b6e8ed8207bd3b67d623cb981dc8890607b6cda1d563dbd5279528225b9adbc4a24ba21e6e1968eab26eb71de48c4a296f8ed8044034ede0d59894d92a5e5177fea7fe61a3" + }, + "expect": "Ok", + "plaintext": "8da0f026c0e82cdc7689a2ecebb186e1fb4a008e5c1490e317d354f6a12fe2e310803deb6f4d8cbc89a1204b6e99b7a1496fc4700325b9d3462a2b4653452e97837949aa1280a0894597264a49a0910f8882d373be4d0ab52d952f07b65e2a2bd5c7cc4289c863fd0f09b3d60cc64b0383165b9da3c80ec9fe49b9240230630fb381489b9f86d078b51688b00eef950fb11ac0fb0dc26af0393bf21b9fe72abbe3768921ffe4b1ee134b13af043a8131dbe57c2073c2cc4ba2a470348bacd1c555cdbd69cf8e7179ce209c34f8f024e29db45019515a109138feb8fe12a6271184e691928b2c544be073419e5b6f40fcdbc15888ff456e8dbce62f0c2a509a00ba3eab29f8035a4492ce6e646e0834696e63ff71e06cf72b10ca3787b18930196f40ab35b72bf6cf674cbb0b" + }, + { + "tcId": 102, + "comment": "a chunk of a secret object, random ID", + "flags": [ + "DataBlobOpen", + "RandomBlobId" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "secret", + "chunkCount": 3, + "blobId": "e5fe2a5487334d4f959b728ea76fa8ba8faef343cfb1c56ae5ea0014424bc3a5", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae84523256c37f9ea3932f2ed00ced28a1a5ef036399335529476902d7a330c50569110ee0fd4499c27144921260c81464a8612267c64db1e649af3f6418e47123f0e763dec6c220cc7dc76ea9fe44979c393daea94a72f5875c96dce98dbc0499f6696eb68e940e9b22bd597a14925ae3ac2a9a2b1bf789e4a4bde55db3b429b9ea9195aa8c7f157c18dd2bd5d4136d7a828b61590ba03c3193f2a910ac1daa9da18557467208c5a57dd157f57b94637cbf0bff4ae46a5baa14f2603688b3c3619e17ecfacf929649fe2e69fb32eff0f17ce99d9d66404e1f67e86caf92393d1d2b90da321f7c5b5fc6dbe36544d88459ff8d6d19526780415bdd0ad450b2b1f745dc418a6ae485182000400b842a5544a8715a2b3a62c279db3b2aba6699d467b38970747253441681ea1aba8f74d4c8d030adbc3827fe43ca935e468d8f082ac6d36d3b2b0a8ec35e353b5b9b1ef9ce4d1654c711cac606d23d88ed30504feab7636e6c6c8e593a3d2f19c16e886b8dab622bed0942411d2496ae0e1701587b9f2d99c7f339652fa1173e779cbc88812f4bf1d68c8fb14e409871f58862099f0e9b749f64f1d14cd8bbc27e3242da3fa56f0eef658a9e152231010cef7bc860b0e7a7bb2b5f72f982b7aaa6013910143a4e11bdb35168576bfae11e0e375f73a20cf5b0cb8f82da792d650aeccf60bbe22f1e156f8ba7595e582ea84ed5d1b594a270cf16020258f169b8abfc05e8a0dc34bea1f6696c4571b1b9552f5a22900b221e1d40b56c3ffad1de86078a5e8a6fa3ac80a1591fdc9470dbe54896a4589d41647d5fe755e53ee3dfc13d73feaa174d068671aaf647a40bc651cb4b7ff1fadd86d6a089ed9cc606daecadab4a90932ff7ad8556d656ae84fab843ca0cdc4be48f6308553e02e6890959d37c12ed2384e9c0ee0cf57577f8bb03615ee954f2d973342053e6f92aa6ef26721f3edcdbde44d321fa8771b35df9506a44b1c6a7be0cc41880f2e453b094ea23c1a631edc32f3ee9eab81844aadcf65628ed12fcd3c15a80b0c4bec5639f58a8a9a6ad0941e1c9cec215c2d3bd115f99af6d678db0efd0ee7ab880e7a1385c93ddfbdd9850ccb6b8dae18ffa086a4a02c4550fa7fc363cb7640b1a6453283ef95136b61283e31ceb6e48699b20e16a990600daf9297f9bf6d65367efbf8cdf68354c9a5001109acc4a29f740104445de4da96aaaa953e1ab526cb32b160af52dea9a4cfa7b52d15e552a45bf6ae0bd59021f9cedfde6a591e5f2374b698750a91eaf928c871e6233418a46d41d2ef440ee1376effe63df52f6681018ff027841a2b6662ed50b2e2108c744f0a4d6a631742f6f2f01543b581e101f35d55ba9f06f1ac6c0e9ba3c3792eec5292f22f13f27e2103e5819cc43cd90607ca3955a6669e29be1edd00d57cdd606f296d22bf45d9f857321f074894943e750a6d5675ac08c54beca0311fe6cf51316ce853b76e3d8c917f2c8284a567e5e5ea979bb3211673c533cbc6d01fc739e03f4e6ead8ae8444a2706a54feb751cc9ed81c6ccaaaf1f3cbfdc5d3e1640fcbe76f63206bc831c444dd1089ce5eabc2ee7160e8c126638c44693be1428cb7a5916909065ebfe208e8074c0e8a9e278a6e580e3a04bac26b1b0fd7ecc0d5bec8e7a9f2a11e6a0aac0850e7787bfb40f93fe698c3ec1cc1e5773ebb9b48d31c99a5353f440e1fb8492fe0a05a7c30de913d0251fb25f559a9f4c52676606264daec821cc1da520548503335609f001262b73cd1db2ef0331f30543921929b0709be383b692bc87d2afbedcc2ae9dcf81b44aea694a40b46fca3dfe7f737a49d7a0daf516b5dbbec88ecd0defbbe6d7755b2f271602076f198fd28c1ebfdf48e96eb3c8680a5e23102b82f625df2b1488633bd5a70dcca9fe23f630d64f7787467d5640ce1aa194410d52a7634c79495fe0c8d14bb84415dc0dc080697839d240cd5bb2c49f5a299dda61320556fa050b903e8353ec0d46b07ed52d91f7b50c7d66cbec0e6dcd2b320e51a298360458a32ea81c2e506349de618f657689ced80e8b1d2fb785602b6bed7873118dee4b9ff8fd8f809cd4cd594ba919262a82e395a2ecaf9ea232518f88a94d41ee1ee7bdecede2a1310175a4416c951c82cb317c1bf93d60793ec5b842cc018e511254f804fa44ceb92e38437c972f18ab09390e387b03141e331a75616f31e54de97b80d48948386540e698119119d3ca28f184a421fac18178a165efb9f95bbf246378bf85a6c9b0373d7740d17bb91edffa1144f73d03d54cab9077161507826bd1858154ca36c379d7347ecb037b426424fe20d06a3b090a48b0da161d63757ae83895d4d6f20343d42d04271ba9f11bc53de2b89c7e5f2ed0fb772da1216f4cc16296b211bfbfdf52bbd7d1aadf46bb7b6008effd1967b1f10819bdfd853ee9de0e0bfb99b818b298606097b57d0270a524162ebda91de422bde5a29ce0115fc6b014797dea4687df9c8e334fc2627b31a3d52f659c4bb3aa182b3d39ae79604d2f98a10c84b392685985cd76c6f60d0a05d82a102b0f0083be43421dbfd12294130b35f42847e0c74c374daa392f28bc15c195a17f2717ed3dcc7ac024f13ba5cff0cbfea5d4979fb20efbf69e5e93305cad428ff3281b34464f28e1c0925879a2b8069c04d0070edc336210feb0abbc10533ff67dfb297c5cc7e3e82fa07bfd0f1bea5fe48af3f3bbf88126f3e8469c4b5c545b2619be02e0430a674b06c3b5268e7453e8df5ce0c1404614bfb7aecb9d68514ad867120f9f95bfb289f70681a238ae723e2ab21ff94ff516990cf9018d2cb4cea1758bd9ae76e175d2cd34fae4e3028839d1c01e0dacde67e232ac5fcaf38796d80fe14bb5ee354062fd808f90db8d32e1d0b6482bec5c6a2453bac7479bacd81b3cd33470e3744016646d45ed1be3d074bb72257e7534304" + }, + "expect": "Ok", + "plaintext": "54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f7820" + }, + { + "tcId": 103, + "comment": "sealed under another vault's AAD", + "flags": [ + "AadBinding" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452326f9ec0d36b6bda99eb98324197a064ede600f84f4bbeeb53e944b15fce767af643f2b70c3b60b847d9ba4d1e0f22ad0b32a245d4af3776156157e958987abdb35ad4fdf3b6e48a57ed7650d5861d3235fe0dce5e2d1389358b3b4c59fb8b274eae60bebdcea8622d66574d96ce1755502b081f9539bd8395" + }, + "expect": "Decrypt" + }, + { + "tcId": 104, + "comment": "sealed under another object's AAD", + "flags": [ + "AadBinding" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae845232dac28c25778604ea2e3fcfe456f876f688df28d2e39e20238ec7ef3dee601a42720c26193fa2b618bd0fb631f0eafe60f205008a092d6f636e59f36ea719ba72c89a125213c42df6d480e4a3a420bf3bacf8e81fac0b51eb662bb929731138cbd402f2367ab0aa806b245d769bb4e388f67479f697741d58" + }, + "expect": "Decrypt" + }, + { + "tcId": 105, + "comment": "sealed under another DEK ID's AAD", + "flags": [ + "AadBinding" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae845232eebf620ff42e1d397e3b4ecf74cb8fb64c6c8126bc5d64695f38035402f0e75f8933b125edc9c5d6234d9b8bbbe999c221896240a0aa0493736ccf2018ebbb47f5ea6fe12fd0290580e0bb7e93f19c3e2706e558b4f4c8abb8cdbbc856816c6a6b569e7565abb83d685bf3575cf0506213e96eb83c9872d4" + }, + "expect": "Decrypt" + }, + { + "tcId": 106, + "comment": "sealed under another blob ID's AAD", + "flags": [ + "AadBinding" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae84523250c92442ecff2773d8b9ce6c9ad44da7ae495278f499fb0065d98bb7344c2621ca5b4febb7275f06feccf753c02a049d13f39ccd319824a130e341a88e1f1336085d504cca137b12923e46c49f4f27aace838409c65133dd265ad5d08368b58babfe5e97b9144a7c48a810eb27aab3ca4009feb99fdf4999" + }, + "expect": "Decrypt" + }, + { + "tcId": 107, + "comment": "sealed with kind byte 0x02", + "flags": [ + "AadBinding" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae845232a897f6a39b1b8a4b562b07ff6691feb12a2802e62ceedae7226ecb9ed1574587131196820d3a133173f83a25e621633a730e448dd834a6bedc26be80e3c8b76a2655d2c7d725a9282a8d976cdbc55ba217889e3e23e9488dfcce6021a804512c1a0c2f350a023607d93f44be46e3138ac4d707dacb22814d" + }, + "expect": "Decrypt" + }, + { + "tcId": 108, + "comment": "sealed under the blob-meta label", + "flags": [ + "AadBinding" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae84523250c2ed2e58a11716620fc7d76374603269042c160391a8177b46e32d420dd7a1779dec2b196bbb8d16b530ef139b08e6057e5deeb655d1c0e17aaebe6a037484eb319fbd9dd4edec9caac01f35d27abcc8f16e510249bef9d4b0c5b6bd35c71fedc1d1c0ac409f72518c4c7910dc40360a461295a5aa4bb7" + }, + "expect": "Decrypt" + }, + { + "tcId": 109, + "comment": "sealed under another key", + "flags": [ + "AadBinding" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae84523202f726bb9f1368a2a358dcd63ad991c158dc1f12af17379c159ed94a719801cf50c66b6a86ac5a2de80a4452d586207212d3a3da37fa97c5e8ccae3b6b66eae99d577224596ed65e667deddfd8826f752db94f8f027b236f15a783c3b9e9b25edf9eb42ccfc2fa516783976035aa550cc636711d2fc83c1a" + }, + "expect": "Decrypt" + }, + { + "tcId": 110, + "comment": "the blob ID of another chunk", + "flags": [ + "BlobIdBinding" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "45f852ef69e5c3f7413ca7616165b1359d4bfb186d3055b221c841d1cf79fd72", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae84523250c92442ecff2773d8b9ce6c9ad44da7ae495278f499fb0065d98bb7344c2621ca5b4febb7275f06feccf753c02a049d13f39ccd319824a130e341a88e1f1336085d504cca137b12923e46c49f4f27aace838409c65133dd265ad5d08368b58babfe5e97b9144a7c48a810eb27aab3ca4009feb99fdf4999" + }, + "expect": "Binding" + }, + { + "tcId": 111, + "comment": "a random blob ID in a two-chunk object", + "flags": [ + "BlobIdBinding" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "e5fe2a5487334d4f959b728ea76fa8ba8faef343cfb1c56ae5ea0014424bc3a5", + "plainLen": 300, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae84523256c37f9ea3932f2ed00ced28a1a5ef036399335529476902d7a330c50569110ee0fd4499c48d9d5a8766798921177c8ba758c9770e88321a1cb6d210de638390e546067d0eeabf8bb4794aa069a5d060ee2f3c385898ffc25894dc4a00475d2beaa6e72ddacd1e4a46d3f0a9634a19687f71ca41108b5906f4b92a00dc389220d1e3ac6b2746618f72b6f8d77608ea488cb2d4da10e51ccf3811d114f61a5b6a97332a99a7081bf6d98f6ccb8c93d68ce22511dd5c706318841cc96f2b0841af28be781c1336ed700476623434fa9ff6e2a83e0dbe325ceefd921e97b440430b2b489cd7ec71e159b60d716550a62938e816ec500acf25cca43d8b8ec7b885c54bb4924c581fa4f2f2738108658af2424ac64bc24e49c08d8d9646fb7c5345e57b110f71fea1244c7486e0b6e8ed8207bd3b67d623cb981dc8890607b6cda1d563dbd5279528225b9adbc4a24ba21e6e1968eab26eb71de48c4a296f8ed8044034ede0d59894d92a5e5177fea7fe61a3" + }, + "expect": "Binding" + }, + { + "tcId": 112, + "comment": "rsv 1", + "flags": [ + "BlobInner" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452324eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc2a3fdb9bae4ada756a878be9566cfd074ff0702774d046fc2f11a9587bbed0ea59415c468f614a71b20609c35dc011bd84a0d52682645ca57069fe9d6dd1ec4ae184e7dddb8c95342dac653b527d3b9b03935c149936a0af259cdf27f0481f20da1c0055596934a95fe9ac930da172eb8e8c56b1df67179cda2d438f4df1b0249e0620690b52ee2f2c85344ceb1765e6b8983219e31c4608bf9a8e405d98781e2985a0299d70fb2469658d4570ddeeb42a3ac5d297bc0647b5712bf4a2a426993d56dff9f4479481d0f05c1ecae49488bd79994422832df81df3c939f47b603dc3e05bcb92bc3aee4590b3fa8f955fb30bbc412dff292d54de22b829aab2d504a64c961452c9f75b70c2e782bcc1d1932d865f248557cc58ffb75827ad137d9a658cc7b4951d9981edaa47c231d7779d465597607c7627c37efefd0772ce4ed0506e17944296c50cb771e2585ff124a5d44d406fbc79587ba5d1164356dca96fb0acbf218c14d2966acaff5d0b7fdd99d30f8cedefb4a2cd0b0b28435706a0be8ec51f46f608c2d3325ab45f61f272cea14e5ad1d8cdf10eda3dbcf40bbb1c7d15bdaa68bca9bd11c525c15df6c343fb46faacf8b8cad817f31505f2d415b878d697311f4befb13eae5bc8f87f508d9c6d47f015d1c89cc34958353341a77bd2e0f00452479067718c99659cf38ea7d82e65df82e9fead04e017ce8b41e1a1787c43ea0869c769d982861299d50e3ac94ea2b4c1c15b37653805415626a145a0e842a5f65f649664aaaacac8ba703d679ea2e1256becb03a7b173fbde0e4eba17c6b6ae91da4827884d02e2b6f5f354f78abf4afc3b05464ea731b98b792511ce63a36de91aed63f9e4a1cdb075c8a5359753b26f8ca76f3f3a2940056b94fd478ba3c55a1fd4a46cb0375a893993b4f157fe3e62d9f0532ebe6a64395d080e835bd8e8b6f75e43766efd6ad9a139e347d057e1abdd662ce2c554b02f4d938e8bc80361fa7ff2ce22a85211c8877d3eb5e010b79a0eeda4eaf9f400cccc74fd260ff5668cb12f60afc41b537e2c76c22a90d459055f1e407f09600887c6872aa7140ae6d5e4d3c36d8e82ac16cf9d7b53e2f6812ae73fa9f43a59bc12a2d06729af118f48d88a6fb9ec8d2cc6318bb2c2bf54c8f23aa10efa4eb657ac62d8c34c26488d6fa39608a11e14215f43c1a4dddf04daef2c643d7392d7c9386ac89b4aef66cc83c7458a7e49d56b9d63c75e801ed9e14a1a50a59d868db9daaee7cd1e4d783d13ea242ca156d4ab8aaf14f217080be516d7bae4f4c5510891b870f67ceb1c8e726dd19ad2fe63c64f779425e8c88e943f00c47b195c27ffd50c412319c691e729a0c3c2bb483f0bce4b99e903398ea6ffffd1449bb5090bec1b28228b5260aa22e36b893431e8ec5ccd12aff33ba045c1f549883c7559b4d8f61568ff7bcec486d5e233c8bbc9cf40cf9e3a0a7e1be410fe4707d216150c7bd4719b6c3d8fbcaa7da3f7a634ff09fa6e8e35283efd452eb3f368b1ff5f64738028b52d715d61d56fa0c89bf8fe09120a1e5dc10cc8679cb50c217507f3bee88f5bfc3d65d76e6f04645982baf459353b380b523c6637731a4c86c8c2f9a29b39ffb98a0f809e7d96fc1caf7a9ee654c05ea093cac859ed3eb619da22fc86f5f32619a63a0af117b19be988a59df4f4f17596b3716fbd552083bc166d11675151167766de70f99b2f8e725744ca2b61702a7251d66278852a118d6b059f836f314b1f710e685737b5390ef410aad645933cdbcb9fe2969171c86b2c53f0c594b2e488aa6575f155ca1a5e7cfae9a699baf0469c7af59596046b5ba2cc60fbfb7040f0c17fe2fd6342e8f809a6f60e55f13b8b7c5e8ea960d433b60d7360b6f0d0bdb4c54370ec8ddc1c7acf833dfc85c723e15696ba9e7e50aaaac19785dd09b1bc20899b6496010f53c46fa0afe1beb4523909dbe74ccd82a50837776ba012964d4184f13f23309cd5387e5d17d04a05aebd0297c6ba1faabeb393863ff89e88f94c1de1d9f7722728f61a6ea15746d66eb93b81b2bf21585949c2acb47890b924b5e112dabb8b55e9b859834e0e6f8b16eb955adf031cf9ac7ccae70c66bdf9d4e4da7f0e735a146b15f9b41d1de447b4b53ee4b80ada77d65901213943a7e32b70b596e447d3e4cbf7d90697f1257502f33fdc520d4ced209b859fb6edf2b53fa16cfbfb517d69b3461768da6dc2e419facd292cb4759752c3f5cdca8b5f8112e84805ad1fc049c5d226cc44ec35021d6ba91d1514cafceb1dc9a104fd7d12bc82ccaf90bca0286fe96a7263205380647146c754901042ce58310f08191bb592e39bb8c8bbf00248e5bae4e7aa9cf85fe8c0112bd5f2ce4e6bc56ac4d13bf2ac0b745dfc0ddbd54ba63b2718b3134b1abddf7481dcebe3384d10896996870525cd07bc6c19fc85db4bf4ce2491e5d3365cfd37f82d0452e1eb40fbadf4196532ce8f20ce0c60ab1b3bdc22eed65fc968cf9cad7d51ece382c9c767e89b9116f6ef9a35b68f391c1767cc2245e06c5bf19617066454490613f082da16faae7b073f571e8d0a48539fa186bd15e70ea2ded3c303946fb2bf071420de970e03d1b6a9dd93411f4d5380ffc48cf934f5697ea6f1909125a09eec4c0bcf2c07c3f2532035d83a3e58e4354f374d7f9fd8828511e27f541103a8240ad162c0f591e9e8ccbf88c1ec0c15d5bd789952eeea687c468b783a209d03375d5c598df7fc73f85faeb8e141295456273b416b557269fa9a80644869f004710a7d6df50ab390f526011167ef4f6ba5846aedaefa46c3ff0332b4c7a989d74bba349c91865c2e5269e69252d1f916a01b0451a4a8c268b0e61375a96775ab4562896a08945947033a5d2a3a9f5a4878233fe5a7d56e5e0fdac" + }, + "expect": "Padding" + }, + { + "tcId": 113, + "comment": "comp 2", + "flags": [ + "BlobInner" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452324eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc283edb9bae4ada756a878be9566cfd074ff0702774d046fc2f11a9587bbed0ea59415c468f614a71b20609c35dc011bd84a0d52682645ca57069fe9d6dd1ec4ae184e7dddb8c95342dac653b527d3b9b03935c149936a0af259cdf27f0481f20da1c0055596934a95fe9ac930da172eb8e8c56b1df67179cda2d438f4df1b0249e0620690b52ee2f2c85344ceb1765e6b8983219e31c4608bf9a8e405d98781e2985a0299d70fb2469658d4570ddeeb42a3ac5d297bc0647b5712bf4a2a426993d56dff9f4479481d0f05c1ecae49488bd79994422832df81df3c939f47b603dc3e05bcb92bc3aee4590b3fa8f955fb30bbc412dff292d54de22b829aab2d504a64c961452c9f75b70c2e782bcc1d1932d865f248557cc58ffb75827ad137d9a658cc7b4951d9981edaa47c231d7779d465597607c7627c37efefd0772ce4ed0506e17944296c50cb771e2585ff124a5d44d406fbc79587ba5d1164356dca96fb0acbf218c14d2966acaff5d0b7fdd99d30f8cedefb4a2cd0b0b28435706a0be8ec51f46f608c2d3325ab45f61f272cea14e5ad1d8cdf10eda3dbcf40bbb1c7d15bdaa68bca9bd11c525c15df6c343fb46faacf8b8cad817f31505f2d415b878d697311f4befb13eae5bc8f87f508d9c6d47f015d1c89cc34958353341a77bd2e0f00452479067718c99659cf38ea7d82e65df82e9fead04e017ce8b41e1a1787c43ea0869c769d982861299d50e3ac94ea2b4c1c15b37653805415626a145a0e842a5f65f649664aaaacac8ba703d679ea2e1256becb03a7b173fbde0e4eba17c6b6ae91da4827884d02e2b6f5f354f78abf4afc3b05464ea731b98b792511ce63a36de91aed63f9e4a1cdb075c8a5359753b26f8ca76f3f3a2940056b94fd478ba3c55a1fd4a46cb0375a893993b4f157fe3e62d9f0532ebe6a64395d080e835bd8e8b6f75e43766efd6ad9a139e347d057e1abdd662ce2c554b02f4d938e8bc80361fa7ff2ce22a85211c8877d3eb5e010b79a0eeda4eaf9f400cccc74fd260ff5668cb12f60afc41b537e2c76c22a90d459055f1e407f09600887c6872aa7140ae6d5e4d3c36d8e82ac16cf9d7b53e2f6812ae73fa9f43a59bc12a2d06729af118f48d88a6fb9ec8d2cc6318bb2c2bf54c8f23aa10efa4eb657ac62d8c34c26488d6fa39608a11e14215f43c1a4dddf04daef2c643d7392d7c9386ac89b4aef66cc83c7458a7e49d56b9d63c75e801ed9e14a1a50a59d868db9daaee7cd1e4d783d13ea242ca156d4ab8aaf14f217080be516d7bae4f4c5510891b870f67ceb1c8e726dd19ad2fe63c64f779425e8c88e943f00c47b195c27ffd50c412319c691e729a0c3c2bb483f0bce4b99e903398ea6ffffd1449bb5090bec1b28228b5260aa22e36b893431e8ec5ccd12aff33ba045c1f549883c7559b4d8f61568ff7bcec486d5e233c8bbc9cf40cf9e3a0a7e1be410fe4707d216150c7bd4719b6c3d8fbcaa7da3f7a634ff09fa6e8e35283efd452eb3f368b1ff5f64738028b52d715d61d56fa0c89bf8fe09120a1e5dc10cc8679cb50c217507f3bee88f5bfc3d65d76e6f04645982baf459353b380b523c6637731a4c86c8c2f9a29b39ffb98a0f809e7d96fc1caf7a9ee654c05ea093cac859ed3eb619da22fc86f5f32619a63a0af117b19be988a59df4f4f17596b3716fbd552083bc166d11675151167766de70f99b2f8e725744ca2b61702a7251d66278852a118d6b059f836f314b1f710e685737b5390ef410aad645933cdbcb9fe2969171c86b2c53f0c594b2e488aa6575f155ca1a5e7cfae9a699baf0469c7af59596046b5ba2cc60fbfb7040f0c17fe2fd6342e8f809a6f60e55f13b8b7c5e8ea960d433b60d7360b6f0d0bdb4c54370ec8ddc1c7acf833dfc85c723e15696ba9e7e50aaaac19785dd09b1bc20899b6496010f53c46fa0afe1beb4523909dbe74ccd82a50837776ba012964d4184f13f23309cd5387e5d17d04a05aebd0297c6ba1faabeb393863ff89e88f94c1de1d9f7722728f61a6ea15746d66eb93b81b2bf21585949c2acb47890b924b5e112dabb8b55e9b859834e0e6f8b16eb955adf031cf9ac7ccae70c66bdf9d4e4da7f0e735a146b15f9b41d1de447b4b53ee4b80ada77d65901213943a7e32b70b596e447d3e4cbf7d90697f1257502f33fdc520d4ced209b859fb6edf2b53fa16cfbfb517d69b3461768da6dc2e419facd292cb4759752c3f5cdca8b5f8112e84805ad1fc049c5d226cc44ec35021d6ba91d1514cafceb1dc9a104fd7d12bc82ccaf90bca0286fe96a7263205380647146c754901042ce58310f08191bb592e39bb8c8bbf00248e5bae4e7aa9cf85fe8c0112bd5f2ce4e6bc56ac4d13bf2ac0b745dfc0ddbd54ba63b2718b3134b1abddf7481dcebe3384d10896996870525cd07bc6c19fc85db4bf4ce2491e5d3365cfd37f82d0452e1eb40fbadf4196532ce8f20ce0c60ab1b3bdc22eed65fc968cf9cad7d51ece382c9c767e89b9116f6ef9a35b68f391c1767cc2245e06c5bf19617066454490613f082da16faae7b073f571e8d0a48539fa186bd15e70ea2ded3c303946fb2bf071420de970e03d1b6a9dd93411f4d5380ffc48cf934f5697ea6f1909125a09eec4c0bcf2c07c3f2532035d83a3e58e4354f374d7f9fd8828511e27f541103a8240ad162c0f591e9e8ccbf88c1ec0c15d5bd789952eeea687c468b783a209d03375d5c598df7fc73f85faeb8e141295456273b416b557269fa9a80644869f004710a7d6df50ab390f526011167ef4f6ba5846aedaefa46c3ff0332b4c7a989d74bba349c91865c2e5269e69252d1f916a01b0451a4a8c268b0e61375a96775ab4562896a08945947033a55abf12d95426ce9ddeed0494291fc589" + }, + "expect": "Padding" + }, + { + "tcId": 114, + "comment": "a pad byte not zero", + "flags": [ + "BlobInner" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452324eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc2a3edb9bae4ada756a878be9566cfd074ff0702774d046fc2f11a9587bbed0ea59415c468f614a71b20609c35dc011bd84a0d52682645ca57069fe9d6dd1ec4ae184e7dddb8c95342dac653b527d3b9b03935c149936a0af259cdf27f0481f20da1c0055596934a95fe9ac930da172eb8e8c56b1df67179cda2d438f4df1b0249e0620690b52ee2f2c85344ceb1765e6b8983219e31c4608bf9a8e405d98781e2985a0299d70fb2469658d4570ddeeb42a3ac5d297bc0647b5712bf4a2a426993d56dff9f4479481d0f05c1ecae49488bd79994422832df81df3c939f47b603dc3e05bcb92bc3aee4590b3fa8f955fb30bbc412dff292d54de22b829aab2d504a64c961452c9f75b70c2e782bcc1d1932d865f248557cc58ffb75827ad137d9a658cc7b4951d9981edaa47c231d7779d465597607c7627c37efefd0772ce4ed0506e17944296c50cb771e2585ff124a5d44d406fbc79587ba5d1164356dca96fb0acbf218c14d2966acaff5d0b7fdd99d30f8cedefb4a2cd0b0b28435706a0be8ec51f46f608c2d3325ab45f61f272cea14e5ad1d8cdf10eda3dbcf40bbb1c7d15bdaa68bca9bd11c525c15df6c343fb46faacf8b8cad817f31505f2d415b878d697311f4befb13eae5bc8f87f508d9c6d47f015d1c89cc34958353341a77bd2e0f00452479067718c99659cf38ea7d82e65df82e9fead04e017ce8b41e1a1787c43ea0869c769d982861299d50e3ac94ea2b4c1c15b37653805415626a145a0e842a5f65f649664aaaacac8ba703d679ea2e1256becb03a7b173fbde0e4eba17c6b6ae91da4827884d02e2b6f5f354f78abf4afc3b05464ea731b98b792511ce63a36de91aed63f9e4a1cdb075c8a5359753b26f8ca76f3f3a2940056b94fd478ba3c55a1fd4a46cb0375a893993b4f157fe3e62d9f0532ebe6a64395d080e835bd8e8b6f75e43766efd6ad9a139e347d057e1abdd662ce2c554b02f4d938e8bc80361fa7ff2ce22a85211c8877d3eb5e010b79a0eeda4eaf9f400cccc74fd260ff5668cb12f60afc41b537e2c76c22a90d459055f1e407f09600887c6872aa7140ae6d5e4d3c36d8e82ac16cf9d7b53e2f6812ae73fa9f43a59bc12a2d06729af118f48d88a6fb9ec8d2cc6318bb2c2bf54c8f23aa10efa4eb657ac62d8c34c26488d6fa39608a11e14215f43c1a4dddf04daef2c643d7392d7c9386ac89b4aef66cc83c7458a7e49d56b9d63c75e801ed9e14a1a50a59d868db9daaee7cd1e4d783d13ea242ca156d4ab8aaf14f217080be516d7bae4f4c5510891b870f67ceb1c8e726dd19ad2fe63c64f779425e8c88e943f00c47b195c27ffd50c412319c691e729a0c3c2bb483f0bce4b99e903398ea6ffffd1449bb5090bec1b28228b5260aa22e36b893431e8ec5ccd12aff33ba045c1f549883c7559b4d8f61568ff7bcec486d5e233c8bbc9cf40cf9e3a0a7e1be410fe4707d216150c7bd4719b6c3d8fbcaa7da3f7a634ff09fa6e8e35283efd452eb3f368b1ff5f64738028b52d715d61d56fa0c89bf8fe09120a1e5dc10cc8679cb50c217507f3bee88f5bfc3d65d76e6f04645982baf459353b380b523c6637731a4c86c8c2f9a29b39ffb98a0f809e7d96fc1caf7a9ee654c05ea093cac859ed3eb619da22fc86f5f32619a63a0af117b19be988a59df4f4f17596b3716fbd552083bc166d11675151167766de70f99b2f8e725744ca2b61702a7251d66278852a118d6b059f836f314b1f710e685737b5390ef410aad645933cdbcb9fe2969171c86b2c53f0c594b2e488aa6575f155ca1a5e7cfae9a699baf0469c7af59596046b5ba2cc60fbfb7040f0c17fe2fd6342e8f809a6f60e55f13b8b7c5e8ea960d433b60d7360b6f0d0bdb4c54370ec8ddc1c7acf833dfc85c723e15696ba9e7e50aaaac19785dd09b1bc20899b6496010f53c46fa0afe1beb4523909dbe74ccd82a50837776ba012964d4184f13f23309cd5387e5d17d04a05aebd0297c6ba1faabeb393863ff89e88f94c1de1d9f7722728f61a6ea15746d66eb93b81b2bf21585949c2acb47890b924b5e112dabb8b55e9b859834e0e6f8b16eb955adf031cf9ac7ccae70c66bdf9d4e4da7f0e735a146b15f9b41d1de447b4b53ee4b80ada77d65901213943a7e32b70b596e447d3e4cbf7d90697f1257502f33fdc520d4ced209b859fb6edf2b53fa16cfbfb517d69b3461768da6dc2e419facd292cb4759752c3f5cdca8b5f8112e84805ad1fc049c5d226cc44ec35021d6ba91d1514cafceb1dc9a104fd7d12bc82ccaf90bca0286fe96a7263205380647146c754901042ce58310f08191bb592e39bb8c8bbf00248e5bae4e7aa9cf85fe8c0112bd5f2ce4e6bc56ac4d13bf2ac0b745dfc0ddbd54ba63b2718b3134b1abddf7481dcebe3384d10896996870525cd07bc6c19fc85db4bf4ce2491e5d3365cfd37f82d0452e1eb40fbadf4196532ce8f20ce0c60ab1b3bdc22eed65fc968cf9cad7d51ece382c9c767e89b9116f6ef9a35b68f391c1767cc2245e06c5bf19617066454490613f082da16faae7b073f571e8d0a48539fa186bd15e70ea2ded3c303946fb2bf071420de970e03d1b6a9dd93411f4d5380ffc48cf934f5697ea6f1909125a09eec4c0bcf2c07c3f2532035d83a3e58e4354f374d7f9fd8828511e27f541103a8240ad162c0f591e9e8ccbf88c1ec0c15d5bd789952eeea687c468b783a209d03375d5c598df7fc73f85faeb8e141295456273b416b557269fa9a80644869f004710a7d6df50ab390f526011167ef4f6ba5846aedaefa46c3ff0332b4c7a989d74bba349c91865c2e5269e69252d1f916a01b0451a4a8c268b0e61375a96775ab4562896a08945947033a447d2ca1363ad90f1e5a89fe30fcdb163" + }, + "expect": "Padding" + }, + { + "tcId": 115, + "comment": "one byte past the Padmé length", + "flags": [ + "BlobInner" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452324eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc2a3edb9bae4ada756a878be9566cfd074ff0702774d046fc2f11a9587bbed0ea59415c468f614a71b20609c35dc011bd84a0d52682645ca57069fe9d6dd1ec4ae184e7dddb8c95342dac653b527d3b9b03935c149936a0af259cdf27f0481f20da1c0055596934a95fe9ac930da172eb8e8c56b1df67179cda2d438f4df1b0249e0620690b52ee2f2c85344ceb1765e6b8983219e31c4608bf9a8e405d98781e2985a0299d70fb2469658d4570ddeeb42a3ac5d297bc0647b5712bf4a2a426993d56dff9f4479481d0f05c1ecae49488bd79994422832df81df3c939f47b603dc3e05bcb92bc3aee4590b3fa8f955fb30bbc412dff292d54de22b829aab2d504a64c961452c9f75b70c2e782bcc1d1932d865f248557cc58ffb75827ad137d9a658cc7b4951d9981edaa47c231d7779d465597607c7627c37efefd0772ce4ed0506e17944296c50cb771e2585ff124a5d44d406fbc79587ba5d1164356dca96fb0acbf218c14d2966acaff5d0b7fdd99d30f8cedefb4a2cd0b0b28435706a0be8ec51f46f608c2d3325ab45f61f272cea14e5ad1d8cdf10eda3dbcf40bbb1c7d15bdaa68bca9bd11c525c15df6c343fb46faacf8b8cad817f31505f2d415b878d697311f4befb13eae5bc8f87f508d9c6d47f015d1c89cc34958353341a77bd2e0f00452479067718c99659cf38ea7d82e65df82e9fead04e017ce8b41e1a1787c43ea0869c769d982861299d50e3ac94ea2b4c1c15b37653805415626a145a0e842a5f65f649664aaaacac8ba703d679ea2e1256becb03a7b173fbde0e4eba17c6b6ae91da4827884d02e2b6f5f354f78abf4afc3b05464ea731b98b792511ce63a36de91aed63f9e4a1cdb075c8a5359753b26f8ca76f3f3a2940056b94fd478ba3c55a1fd4a46cb0375a893993b4f157fe3e62d9f0532ebe6a64395d080e835bd8e8b6f75e43766efd6ad9a139e347d057e1abdd662ce2c554b02f4d938e8bc80361fa7ff2ce22a85211c8877d3eb5e010b79a0eeda4eaf9f400cccc74fd260ff5668cb12f60afc41b537e2c76c22a90d459055f1e407f09600887c6872aa7140ae6d5e4d3c36d8e82ac16cf9d7b53e2f6812ae73fa9f43a59bc12a2d06729af118f48d88a6fb9ec8d2cc6318bb2c2bf54c8f23aa10efa4eb657ac62d8c34c26488d6fa39608a11e14215f43c1a4dddf04daef2c643d7392d7c9386ac89b4aef66cc83c7458a7e49d56b9d63c75e801ed9e14a1a50a59d868db9daaee7cd1e4d783d13ea242ca156d4ab8aaf14f217080be516d7bae4f4c5510891b870f67ceb1c8e726dd19ad2fe63c64f779425e8c88e943f00c47b195c27ffd50c412319c691e729a0c3c2bb483f0bce4b99e903398ea6ffffd1449bb5090bec1b28228b5260aa22e36b893431e8ec5ccd12aff33ba045c1f549883c7559b4d8f61568ff7bcec486d5e233c8bbc9cf40cf9e3a0a7e1be410fe4707d216150c7bd4719b6c3d8fbcaa7da3f7a634ff09fa6e8e35283efd452eb3f368b1ff5f64738028b52d715d61d56fa0c89bf8fe09120a1e5dc10cc8679cb50c217507f3bee88f5bfc3d65d76e6f04645982baf459353b380b523c6637731a4c86c8c2f9a29b39ffb98a0f809e7d96fc1caf7a9ee654c05ea093cac859ed3eb619da22fc86f5f32619a63a0af117b19be988a59df4f4f17596b3716fbd552083bc166d11675151167766de70f99b2f8e725744ca2b61702a7251d66278852a118d6b059f836f314b1f710e685737b5390ef410aad645933cdbcb9fe2969171c86b2c53f0c594b2e488aa6575f155ca1a5e7cfae9a699baf0469c7af59596046b5ba2cc60fbfb7040f0c17fe2fd6342e8f809a6f60e55f13b8b7c5e8ea960d433b60d7360b6f0d0bdb4c54370ec8ddc1c7acf833dfc85c723e15696ba9e7e50aaaac19785dd09b1bc20899b6496010f53c46fa0afe1beb4523909dbe74ccd82a50837776ba012964d4184f13f23309cd5387e5d17d04a05aebd0297c6ba1faabeb393863ff89e88f94c1de1d9f7722728f61a6ea15746d66eb93b81b2bf21585949c2acb47890b924b5e112dabb8b55e9b859834e0e6f8b16eb955adf031cf9ac7ccae70c66bdf9d4e4da7f0e735a146b15f9b41d1de447b4b53ee4b80ada77d65901213943a7e32b70b596e447d3e4cbf7d90697f1257502f33fdc520d4ced209b859fb6edf2b53fa16cfbfb517d69b3461768da6dc2e419facd292cb4759752c3f5cdca8b5f8112e84805ad1fc049c5d226cc44ec35021d6ba91d1514cafceb1dc9a104fd7d12bc82ccaf90bca0286fe96a7263205380647146c754901042ce58310f08191bb592e39bb8c8bbf00248e5bae4e7aa9cf85fe8c0112bd5f2ce4e6bc56ac4d13bf2ac0b745dfc0ddbd54ba63b2718b3134b1abddf7481dcebe3384d10896996870525cd07bc6c19fc85db4bf4ce2491e5d3365cfd37f82d0452e1eb40fbadf4196532ce8f20ce0c60ab1b3bdc22eed65fc968cf9cad7d51ece382c9c767e89b9116f6ef9a35b68f391c1767cc2245e06c5bf19617066454490613f082da16faae7b073f571e8d0a48539fa186bd15e70ea2ded3c303946fb2bf071420de970e03d1b6a9dd93411f4d5380ffc48cf934f5697ea6f1909125a09eec4c0bcf2c07c3f2532035d83a3e58e4354f374d7f9fd8828511e27f541103a8240ad162c0f591e9e8ccbf88c1ec0c15d5bd789952eeea687c468b783a209d03375d5c598df7fc73f85faeb8e141295456273b416b557269fa9a80644869f004710a7d6df50ab390f526011167ef4f6ba5846aedaefa46c3ff0332b4c7a989d74bba349c91865c2e5269e69252d1f916a01b0451a4a8c268b0e61375a96775ab4562896a08945947033a536254cc895b6abd0feda79253a521ac659" + }, + "expect": "Padding" + }, + { + "tcId": 116, + "comment": "payload_len 2^20 + 1", + "flags": [ + "BlobInner" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452324eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc2a3edb8ba99b0261d3c8d4ab9a04c2656e5ff9ac1faa" + }, + "expect": "Limit" + }, + { + "tcId": 117, + "comment": "a secret object's chunk with comp 1", + "flags": [ + "SecretRaw" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "secret", + "chunkCount": 3, + "blobId": "e5fe2a5487334d4f959b728ea76fa8ba8faef343cfb1c56ae5ea0014424bc3a5", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae84523256c37f9ea3932f2ed00ced28a1a5ef036399335529476902d7a330c50569110ee1fd4499c5e1384f58bdd9b10b7e0b02d1b676aeed49b825755be5242cf2fb34df90c13d9429c57ee4e256cd8a6f3cb3ee103ac4cf55d7d7e5c4bb00deba3b00c1e5a9965e569d33e5ba67d2a4eb7fc48c140f9e1d8486a4" + }, + "expect": "Padding" + }, + { + "tcId": 118, + "comment": "a secret object's chunk with comp 1 and a bad frame: comp is checked first", + "flags": [ + "SecretRaw", + "CheckOrder" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "secret", + "chunkCount": 3, + "blobId": "e5fe2a5487334d4f959b728ea76fa8ba8faef343cfb1c56ae5ea0014424bc3a5", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae84523256c37f9ea3932f2ed00ced28a1a5ef036399335529476902d7a330c50569110ee1fd4499c5e5384f58bdddb10b7e0b02d1b676aeed49b825755be5242cf2fb34df90c13d9429c57ee4e256cd8a6f3cb3ee103ac4cf55d7d7e5c4bb00deba3b00c1e5a9965e56bcd4879be229c3c35cff09a950677348c4705aeb7847c2da19f3" + }, + "expect": "Padding" + }, + { + "tcId": 119, + "comment": "a frame with a content checksum", + "flags": [ + "BlobFrame" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452324eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc2b3edb9ba9dea6a8205a9e4c39ba9727f9804b387fd051e63e52a80d74bcccbd58175f5bd7354861ff1a1b994b9610a0c3fa9d17ca6d1dae7c20f9992a9dbe2496efda451ef894b9d023154872124dfe0c81dd86ed8f843d0cb035ee97e22746" + }, + "expect": "Decompress" + }, + { + "tcId": 120, + "comment": "a frame holding more than it declares", + "flags": [ + "BlobFrame" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452324eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc2b3edb9ba98ea6a8205ada96660f967345e73f216f9943f87753d8d211c0cfeb5b673c0970a8000b0bcb" + }, + "expect": "Decompress" + }, + { + "tcId": 121, + "comment": "plain_len one more than the frame declares", + "flags": [ + "BlobFrame" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2001, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452324eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc2b3edb9ba9daa6a8205a9a4c39ba9727f9804b387fd051e63e52a80d74bcccbd58175f5bd7354861ff1a1b994b9610a0c3fa9d17ca6d1dae7c20f9992a9dbe2496efda451ef8b55ea42741eb1fcb586c681fa75bef3197cf" + }, + "expect": "Decompress" + }, + { + "tcId": 122, + "comment": "a raw payload one byte shorter than plain_len", + "flags": [ + "BlobFrame" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2001, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452324eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc2a3edb9bae4ada756a878be9566cfd074ff0702774d046fc2f11a9587bbed0ea59415c468f614a71b20609c35dc011bd84a0d52682645ca57069fe9d6dd1ec4ae184e7dddb8c95342dac653b527d3b9b03935c149936a0af259cdf27f0481f20da1c0055596934a95fe9ac930da172eb8e8c56b1df67179cda2d438f4df1b0249e0620690b52ee2f2c85344ceb1765e6b8983219e31c4608bf9a8e405d98781e2985a0299d70fb2469658d4570ddeeb42a3ac5d297bc0647b5712bf4a2a426993d56dff9f4479481d0f05c1ecae49488bd79994422832df81df3c939f47b603dc3e05bcb92bc3aee4590b3fa8f955fb30bbc412dff292d54de22b829aab2d504a64c961452c9f75b70c2e782bcc1d1932d865f248557cc58ffb75827ad137d9a658cc7b4951d9981edaa47c231d7779d465597607c7627c37efefd0772ce4ed0506e17944296c50cb771e2585ff124a5d44d406fbc79587ba5d1164356dca96fb0acbf218c14d2966acaff5d0b7fdd99d30f8cedefb4a2cd0b0b28435706a0be8ec51f46f608c2d3325ab45f61f272cea14e5ad1d8cdf10eda3dbcf40bbb1c7d15bdaa68bca9bd11c525c15df6c343fb46faacf8b8cad817f31505f2d415b878d697311f4befb13eae5bc8f87f508d9c6d47f015d1c89cc34958353341a77bd2e0f00452479067718c99659cf38ea7d82e65df82e9fead04e017ce8b41e1a1787c43ea0869c769d982861299d50e3ac94ea2b4c1c15b37653805415626a145a0e842a5f65f649664aaaacac8ba703d679ea2e1256becb03a7b173fbde0e4eba17c6b6ae91da4827884d02e2b6f5f354f78abf4afc3b05464ea731b98b792511ce63a36de91aed63f9e4a1cdb075c8a5359753b26f8ca76f3f3a2940056b94fd478ba3c55a1fd4a46cb0375a893993b4f157fe3e62d9f0532ebe6a64395d080e835bd8e8b6f75e43766efd6ad9a139e347d057e1abdd662ce2c554b02f4d938e8bc80361fa7ff2ce22a85211c8877d3eb5e010b79a0eeda4eaf9f400cccc74fd260ff5668cb12f60afc41b537e2c76c22a90d459055f1e407f09600887c6872aa7140ae6d5e4d3c36d8e82ac16cf9d7b53e2f6812ae73fa9f43a59bc12a2d06729af118f48d88a6fb9ec8d2cc6318bb2c2bf54c8f23aa10efa4eb657ac62d8c34c26488d6fa39608a11e14215f43c1a4dddf04daef2c643d7392d7c9386ac89b4aef66cc83c7458a7e49d56b9d63c75e801ed9e14a1a50a59d868db9daaee7cd1e4d783d13ea242ca156d4ab8aaf14f217080be516d7bae4f4c5510891b870f67ceb1c8e726dd19ad2fe63c64f779425e8c88e943f00c47b195c27ffd50c412319c691e729a0c3c2bb483f0bce4b99e903398ea6ffffd1449bb5090bec1b28228b5260aa22e36b893431e8ec5ccd12aff33ba045c1f549883c7559b4d8f61568ff7bcec486d5e233c8bbc9cf40cf9e3a0a7e1be410fe4707d216150c7bd4719b6c3d8fbcaa7da3f7a634ff09fa6e8e35283efd452eb3f368b1ff5f64738028b52d715d61d56fa0c89bf8fe09120a1e5dc10cc8679cb50c217507f3bee88f5bfc3d65d76e6f04645982baf459353b380b523c6637731a4c86c8c2f9a29b39ffb98a0f809e7d96fc1caf7a9ee654c05ea093cac859ed3eb619da22fc86f5f32619a63a0af117b19be988a59df4f4f17596b3716fbd552083bc166d11675151167766de70f99b2f8e725744ca2b61702a7251d66278852a118d6b059f836f314b1f710e685737b5390ef410aad645933cdbcb9fe2969171c86b2c53f0c594b2e488aa6575f155ca1a5e7cfae9a699baf0469c7af59596046b5ba2cc60fbfb7040f0c17fe2fd6342e8f809a6f60e55f13b8b7c5e8ea960d433b60d7360b6f0d0bdb4c54370ec8ddc1c7acf833dfc85c723e15696ba9e7e50aaaac19785dd09b1bc20899b6496010f53c46fa0afe1beb4523909dbe74ccd82a50837776ba012964d4184f13f23309cd5387e5d17d04a05aebd0297c6ba1faabeb393863ff89e88f94c1de1d9f7722728f61a6ea15746d66eb93b81b2bf21585949c2acb47890b924b5e112dabb8b55e9b859834e0e6f8b16eb955adf031cf9ac7ccae70c66bdf9d4e4da7f0e735a146b15f9b41d1de447b4b53ee4b80ada77d65901213943a7e32b70b596e447d3e4cbf7d90697f1257502f33fdc520d4ced209b859fb6edf2b53fa16cfbfb517d69b3461768da6dc2e419facd292cb4759752c3f5cdca8b5f8112e84805ad1fc049c5d226cc44ec35021d6ba91d1514cafceb1dc9a104fd7d12bc82ccaf90bca0286fe96a7263205380647146c754901042ce58310f08191bb592e39bb8c8bbf00248e5bae4e7aa9cf85fe8c0112bd5f2ce4e6bc56ac4d13bf2ac0b745dfc0ddbd54ba63b2718b3134b1abddf7481dcebe3384d10896996870525cd07bc6c19fc85db4bf4ce2491e5d3365cfd37f82d0452e1eb40fbadf4196532ce8f20ce0c60ab1b3bdc22eed65fc968cf9cad7d51ece382c9c767e89b9116f6ef9a35b68f391c1767cc2245e06c5bf19617066454490613f082da16faae7b073f571e8d0a48539fa186bd15e70ea2ded3c303946fb2bf071420de970e03d1b6a9dd93411f4d5380ffc48cf934f5697ea6f1909125a09eec4c0bcf2c07c3f2532035d83a3e58e4354f374d7f9fd8828511e27f541103a8240ad162c0f591e9e8ccbf88c1ec0c15d5bd789952eeea687c468b783a209d03375d5c598df7fc73f85faeb8e141295456273b416b557269fa9a80644869f004710a7d6df50ab390f526011167ef4f6ba5846aedaefa46c3ff0332b4c7a989d74bba349c91865c2e5269e69252d1f916a01b0451a4a8c268b0e61375a96775ab4562896a08945947033a51a42e80a0cacbfba6f126ba3dd068a4a" + }, + "expect": "Decompress" + }, + { + "tcId": 123, + "comment": "a bad frame and a wrong blob ID: the frame is checked first", + "flags": [ + "BlobFrame", + "CheckOrder" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "45f852ef69e5c3f7413ca7616165b1359d4bfb186d3055b221c841d1cf79fd72", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae84523250c92442ecff2773d8b9ce6c9ad44da7ae495278f499fb0065d98bb7344c2621ca5b4febb7235f06feccf353c02a049d13f39ccd319824a130e341a88e1f1336085d504cca137b12923e46c49f4f27aace838409c65133dd265ad5d08368b58babfe5e97b9146b9bd2f883fb14d640cf3ecd046681aa612fb3d3c92f1bef7b73" + }, + "expect": "Decompress" + }, + { + "tcId": 124, + "comment": "a raw payload one byte shorter than plain_len and a wrong blob ID: the length is checked first", + "flags": [ + "BlobFrame", + "CheckOrder" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "45f852ef69e5c3f7413ca7616165b1359d4bfb186d3055b221c841d1cf79fd72", + "plainLen": 2001, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae84523250c92442ecff2773d8b9ce6c9ad44da7ae495278f499fb0065d98bb7344c2621cb5b4febb0b723dbb411e6f6affc6ebda583a7d23a9833bb21a040fd811d0f61090b535192477902df22549e891926b789d9cc388e5872d62a13d2d4c424e7e5dc95630f7c606a162f77f38834b936aaf146ca456d63b30441adb07aaf1f5e3b081937aa3a76d58f7833124306c494a25bac0875de558213a3725e6332c767e5de858779bd58523edc88ac1b8666ad364541aa101de8b9a2d9acbe8c80b0267dadd43a62cb1c87363bc8aa4a7b91240e9980523b2d7f3dc14520eadb92a30e5e57966e843b7b9642903525bdfa99cbdb9b7b1afe90219a753bf96823bce8e907c1882b7db01d6fa0c54370069520a2eb470c69a558d797bfcc9d2969c39f3763f0090717346e126f0714e9372ad31174f4b2c5620e6ee26cf1b1102939d963c33ca8f66a501c0fe7443fdbac02547d537e6fcfb3778bbd674f5144be1a3cb779faf30086314f7aa5e9c7329d4eebaca15d1a0827cfb84e57084f5e5c827d3203c7c96f2b2097f42dbb8246ab1654946c5cfe3f0378cf5a684085359db6e8edcb6c04c3c191118c4746e73d930e8bd1ee945164cd73098716b0e50981ac09dd5cfa2f7feeb87d0ccb212870199b9244cdcf82e671f44aa828c1f258f3f48a5f1723624197c235efc32207dadddb9fcf653882801d4dec8c06a6e5c1719dcb46ada86f28e8052e7b3526642b80e9edf6e4037f509a54025cd7bd8f39e57c189138d88eb73ac779e80499c7fcf3407370c7dc4c7af3c9b46a7fe08f433a90238055445e7dc9475a55a5ddde1a967325b834703b0dedbd9e836720404be42eab023d5c95f49fce5b7489f589032db6ca383957f97593becbedff35346bc34596e642d1c9bb976e33fd6e05b70c9d90f181f918c366fea7cab92d6a9bc70a0274ff1d2653ca39006aeb7b48fe6be012018f0fe49cdbd110b454b2e266ad5ed1c0b79950070a476acbc9a4d45e9ab6ff3b54225466115f594ad773144a55bd528d31e4e7e8ad69e6d78d3a25f103dd80ded94bf4db46ae7158c46ca753d5ded5b94edf5e80e491cb1c670fa197d475f1a74614dbc6fcfa5019b8b7c12a4b8f2467a109eee3d0dc80d2a26efd7caeba8ac1d11424c1a76baa8ba53d22e867876b53b8be7ed4940ec2480e5a75e6202f4608ea6464ddfadd406e401f7549effb7643424254783459d7c8536f03c7ff3e257fa0aea8dd2a3a74bcde20b02b0473a967db9e4881c9b465bc8b7b9508e1853d28377990a20067e6ecf4f5697c9376ef22fbc2eabc0d7e4796d0e1c253d3626731ef16ae0f60db657d9458ad3cd628e4e4aeff5ae957b00c696c2581fa527288bea25d9e2a0d9a284573744b175323deeaf718d025f1f3d45add05ab199c1175a80369c025aaba3efb87a046b142876490d56e0dba890080dda66a643974325bfb8427085de1194346e0276de2a0975f9c3ec559497c24824596197ce5f838ff70f980314b63b116fa2820c7de3d8055eda9aaeef1128634c6eae1b55c42009c546326755ece817c22bd5c8bdfc29bc3e88b1692879b54b5818a8e684849a43cfdf2ab8d7e7428e8dcdadbe9aff5a193a49eb6ef4e8aa7c1b2c4125044675392473df6b821d7b3d07ff791697a412209878805b4d7b50f91ef125e9682d15170674fd24f33251723810f56dfae97f3a08ed5398570b4442fe356ffcfa3d39b360082af8e46382d4b617460d088b3042ce6758c4693a68f1c8aefc15accb3989e637850b500ad0d837f48fa915e6a3491a53793de6742c378672bd0efc3ca832e4cb549a148abf435dddab90945ab3c8c7098ab5097c2ad5bb645d43a0db53cfc07e5fcc46d7dd87e9b77d631dcc26f414af3d00e49906a47d73f1a6f486db687fcf8c570d2ab2e2f6863e08459cbeb872f8b7eb373534c8f3e4b2ce6d079cdab203d080a3b907f4c5ad0faa3b9b26114dd2cff8c35322ad0b6e2634810270d199a6d9a4f1f72abeee495a14dc862606229463a066a1a0d1ab99b06a4080505103b3f51116ba4e05b8ef9bcbed3c45536202bceaae2c37aaf02076968bc20ddf4c66ffff6c61224b4190ed1b7f53e1b63dddad7c4dacc633460af427a3c9f027cd645fe5c3bdfc1d19f232fed9f0e54882350b4ee1d67926d3ef1e866420fa6146e3c91efd530b8b83cc75134dc42dbe764efa16456130d5c23f4ddd175020c3c47e3abcb4c1e1657e28168805b9d2c24932d6a32bf46011f45ed8c58e81e86916acaee624e42bf225b51cef4fa1c6350500c347f8eebb32babc88b5558164c4059f733109656a6a3f54e6c0bee09379bf414a290e9c517a7f798cde68f633bda2905b8dcd8174289ae58cfb50a8cf9e390e872adbb3e4c6a5798701caf24f22ee92ebdd30c0bc773fcdca3b140d0dbc30b66aac514fd4b8d3664d47b5eff1cf9152499ad1988174e2d34eccd3188653b5b5a656d17cbd07409770b133a1f77121a4433cc54e303ad3bf7e19aac17ad4e23cab87ff373f19042fd09c30931fd42a0c6ce479b3057ea57431b5137b5d9c4e63ea319d6e6899205ebf5a3926e610598b87426be564b46b5ba9bf002492641e094cc1667305b888c9c939a7cdc9bbc35e89ab7634a1ae075787b9b19b88b67912d6037e69cae7b20b3189c8f55dc4e120463e985a6bed43c5e0823d0bedf14f0725221d49615d338954939d7bf153bf1e7bc85c95eabf9b86a326adc11dcd003f2682fad4486c149ec1d3dbd18b109ed7df20261f6458338a3e57c478cec9aa1d203c94ae12fae3ec63fe5db85a939114ea8f405bfcb1c2cc4fbd3381bc435fa4c65728a07e2d8f2f9a9809e84e09a3a51518d79c4c1479f26674e82b8c74a2bcb8056c7083746f9e46fd5c8fb929468999c29c82080052b4a643dadb9b54ca3d635f660b28743441153c00a757ce0024812" + }, + "expect": "Decompress" + }, + { + "tcId": 125, + "comment": "plain_len 2^20 + 1 is refused before decryption", + "flags": [ + "PlainLenCap", + "CheckOrder" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 1048577, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452324eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc028bf466c94a88a80ea72e9e6b67f3075cf7763371d042e13846ad0d70a1dbea5c425444dc354d62f71848cd4c8555be82f48c528e6e1bfa25019df3504d3429c61e81be1817c41b4b8fdd6304aa37f4" + }, + "expect": "Decompress" + }, + { + "tcId": 126, + "comment": "71 bytes, one short of a seal", + "flags": [ + "SealShape" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452324eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc2b3edb9ba9daa6a8205a9a4c39ba97" + }, + "expect": "Truncated" + }, + { + "tcId": 127, + "comment": "an all-zero nonce", + "flags": [ + "SealShape" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 2000, + "sealed": "0000000000000000000000000000000000000000000000004eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc2b3edb9ba9daa6a8205a9a4c39ba9727f9804b387fd051e63e52a80d74bcccbd58175f5bd7354861ff1a1b994b9610a0c3fa9d17ca6d1dae7c20f9992a9dbe2496efda451ef8b55ea42741eb1fcb586c681fa75bef3197cf" + }, + "expect": "ZeroValue" + } + ] + }, + { + "type": "MetaBlob", + "tests": [ + { + "tcId": 128, + "comment": "a path-index node", + "flags": [ + "MetaBlob" + ], + "inputs": { + "kek": "61b1c8f4adfcbe0ab96751b6a5ba357b172bea516ed6ad51f36b24028d70e638", + "vaultId": "ad75c3d09a927f5e4fe62133b545e566", + "kind": 3, + "epoch": 3, + "blobId": "27ab2e1f445fd627b93409722dbe30612df6f8caea6321f22c6c53e2db26f3b9", + "cbor": "a1014400010203", + "rand": "0358941c61b00e57203ec108afb13bc0b78bc9b28cfbebc43e47c186f20c93c4" + }, + "expect": "Ok", + "nonce": "0b01d8146d9f648722b3aa2da09d15f1da97329803a63293", + "sealed": "0b01d8146d9f648722b3aa2da09d15f1da97329803a63293d710da644a7b8d6cab5e04393eee9c9b1ec3a59fe70a2848d0bd5cc381e1b7ba82fed071bef856e05afb73b4dbf0cbd6a8dcdffdf90d96" + }, + { + "tcId": 129, + "comment": "a key-table node", + "flags": [ + "MetaBlob" + ], + "inputs": { + "kek": "61b1c8f4adfcbe0ab96751b6a5ba357b172bea516ed6ad51f36b24028d70e638", + "vaultId": "ad75c3d09a927f5e4fe62133b545e566", + "kind": 4, + "epoch": 3, + "blobId": "8ff96d456c141f285aa8ae8651c540db872473b00ee61d4cc2d9102a131d7d77", + "cbor": "a1014400010203", + "rand": "f910ae7bb93e7fddbc278d58ebada4d6f222d4786f6989bbdd7b32acc8e09bcb" + }, + "expect": "Ok", + "nonce": "0705b4277464dabd018139045e5e569732c44d54910ec90c", + "sealed": "0705b4277464dabd018139045e5e569732c44d54910ec90c3405af1adc3607c2434020b8190831462bbff314fb7a4eacc542d8df8026d3306501bdef0a8b73b2c0c82fac1ea52972edec1402b36d6e" + }, + { + "tcId": 130, + "comment": "a location node", + "flags": [ + "MetaBlob" + ], + "inputs": { + "kek": "61b1c8f4adfcbe0ab96751b6a5ba357b172bea516ed6ad51f36b24028d70e638", + "vaultId": "ad75c3d09a927f5e4fe62133b545e566", + "kind": 5, + "epoch": 3, + "blobId": "2dec9a2bde49112d96f5b03592c30ce23b9e9b5378eb53b6e57b0206ed68054b", + "cbor": "a1014400010203", + "rand": "daadfed95afc85c3ae4f50f119e23d102ce2e269bc73ae6849d88e9f34018566" + }, + "expect": "Ok", + "nonce": "3c1df3242e9f4383cbc66d04cd5766e3d4b6c55edafde348", + "sealed": "3c1df3242e9f4383cbc66d04cd5766e3d4b6c55edafde3485b9e475261a0778a25c144d95cd6172f47112278f809725bc6e25b6b64e51a8609724b48576cd366873cb9dca2b2dd548e6d07d6726c64" + }, + { + "tcId": 131, + "comment": "a pack-table node", + "flags": [ + "MetaBlob" + ], + "inputs": { + "kek": "61b1c8f4adfcbe0ab96751b6a5ba357b172bea516ed6ad51f36b24028d70e638", + "vaultId": "ad75c3d09a927f5e4fe62133b545e566", + "kind": 6, + "epoch": 3, + "blobId": "5fd273884e5448b131c2f4451df3a037173c0901d16cdea20c42cd3322179e7c", + "cbor": "a1014400010203", + "rand": "3f1207a0ca92c4cba4ff316d4d43bbc38a1d7a8fd3b360d3cbf50cba48b464cd" + }, + "expect": "Ok", + "nonce": "1fb9bbf5f7b026b03bed58826006e1c48a726c7f9867aa28", + "sealed": "1fb9bbf5f7b026b03bed58826006e1c48a726c7f9867aa282b87cf76f499c13ae0c97053c400b4787e3a0920963091a915de6df9307597536e866fd3bfd66f57d21a3273d6d3fb3c52e1c04f2af3a2" + }, + { + "tcId": 132, + "comment": "a GC-candidate node, under the location key", + "flags": [ + "MetaBlob" + ], + "inputs": { + "kek": "61b1c8f4adfcbe0ab96751b6a5ba357b172bea516ed6ad51f36b24028d70e638", + "vaultId": "ad75c3d09a927f5e4fe62133b545e566", + "kind": 8, + "epoch": 3, + "blobId": "642ee4f15e05ac1b703a573295041af0237c4f214a371f4d6ef4d44b67a39f33", + "cbor": "a1014400010203", + "rand": "76a75a555fccae9fd442ede420fe35c1f180e764af1a503e17bef583f1ebf696" + }, + "expect": "Ok", + "nonce": "9de0311efdd0fd9dbe8a8274a7975ec1a9d2b8896e4ce8a7", + "sealed": "9de0311efdd0fd9dbe8a8274a7975ec1a9d2b8896e4ce8a79730a1ad9a15f749d4236af9abcc3919b08fc0a95cc9ba012eb8ce6d810e9c2e6bb799126007e9a6413e232121ba6b3eab77d7425f136a" + }, + { + "tcId": 133, + "comment": "a location node opens", + "flags": [ + "MetaBlobOpen" + ], + "inputs": { + "kek": "61b1c8f4adfcbe0ab96751b6a5ba357b172bea516ed6ad51f36b24028d70e638", + "vaultId": "ad75c3d09a927f5e4fe62133b545e566", + "kind": 5, + "epoch": 3, + "blobId": "973d0c4c8ec2c5f8d74276037ff861edbc23ce3c98a757d9f1cce5f7d8fe53cd", + "sealed": "763cb19b2879f338837454de6ae95dc5a2aa90602e11f42857f8ea518ddee7b421a5c2a44e8029fb8575fba32631cfc71f87cc0a3bef98a14a8a72b34e36f71819f88c6470d776bb2f0a6f877af457" + }, + "expect": "Ok", + "cbor": "a1014400010203" + }, + { + "tcId": 134, + "comment": "opened as a GC-candidate node: same key, other kind byte", + "flags": [ + "MetaBlobOpen" + ], + "inputs": { + "kek": "61b1c8f4adfcbe0ab96751b6a5ba357b172bea516ed6ad51f36b24028d70e638", + "vaultId": "ad75c3d09a927f5e4fe62133b545e566", + "kind": 8, + "epoch": 3, + "blobId": "973d0c4c8ec2c5f8d74276037ff861edbc23ce3c98a757d9f1cce5f7d8fe53cd", + "sealed": "763cb19b2879f338837454de6ae95dc5a2aa90602e11f42857f8ea518ddee7b421a5c2a44e8029fb8575fba32631cfc71f87cc0a3bef98a14a8a72b34e36f71819f88c6470d776bb2f0a6f877af457" + }, + "expect": "Decrypt" + }, + { + "tcId": 135, + "comment": "opened under another epoch", + "flags": [ + "MetaBlobOpen" + ], + "inputs": { + "kek": "61b1c8f4adfcbe0ab96751b6a5ba357b172bea516ed6ad51f36b24028d70e638", + "vaultId": "ad75c3d09a927f5e4fe62133b545e566", + "kind": 5, + "epoch": 4, + "blobId": "973d0c4c8ec2c5f8d74276037ff861edbc23ce3c98a757d9f1cce5f7d8fe53cd", + "sealed": "763cb19b2879f338837454de6ae95dc5a2aa90602e11f42857f8ea518ddee7b421a5c2a44e8029fb8575fba32631cfc71f87cc0a3bef98a14a8a72b34e36f71819f88c6470d776bb2f0a6f877af457" + }, + "expect": "Decrypt" + }, + { + "tcId": 136, + "comment": "opened under another blob ID", + "flags": [ + "MetaBlobOpen" + ], + "inputs": { + "kek": "61b1c8f4adfcbe0ab96751b6a5ba357b172bea516ed6ad51f36b24028d70e638", + "vaultId": "ad75c3d09a927f5e4fe62133b545e566", + "kind": 5, + "epoch": 3, + "blobId": "2fae9c078cfcfb73350e99dccc0f85c7381e0c67bf4ab255c6a5525b71560093", + "sealed": "763cb19b2879f338837454de6ae95dc5a2aa90602e11f42857f8ea518ddee7b421a5c2a44e8029fb8575fba32631cfc71f87cc0a3bef98a14a8a72b34e36f71819f88c6470d776bb2f0a6f877af457" + }, + "expect": "Decrypt" + }, + { + "tcId": 137, + "comment": "opened in another vault", + "flags": [ + "MetaBlobOpen" + ], + "inputs": { + "kek": "61b1c8f4adfcbe0ab96751b6a5ba357b172bea516ed6ad51f36b24028d70e638", + "vaultId": "ded92a04ff1ba02fedce98944f7fda2e", + "kind": 5, + "epoch": 3, + "blobId": "973d0c4c8ec2c5f8d74276037ff861edbc23ce3c98a757d9f1cce5f7d8fe53cd", + "sealed": "763cb19b2879f338837454de6ae95dc5a2aa90602e11f42857f8ea518ddee7b421a5c2a44e8029fb8575fba32631cfc71f87cc0a3bef98a14a8a72b34e36f71819f88c6470d776bb2f0a6f877af457" + }, + "expect": "Decrypt" + }, + { + "tcId": 138, + "comment": "opened with another epoch's KEK", + "flags": [ + "MetaBlobOpen" + ], + "inputs": { + "kek": "263a43405c04c14fe65bdb514a5eacbeddcb57c9c43a88b7ff785e1562cf0d89", + "vaultId": "ad75c3d09a927f5e4fe62133b545e566", + "kind": 5, + "epoch": 3, + "blobId": "973d0c4c8ec2c5f8d74276037ff861edbc23ce3c98a757d9f1cce5f7d8fe53cd", + "sealed": "763cb19b2879f338837454de6ae95dc5a2aa90602e11f42857f8ea518ddee7b421a5c2a44e8029fb8575fba32631cfc71f87cc0a3bef98a14a8a72b34e36f71819f88c6470d776bb2f0a6f877af457" + }, + "expect": "Decrypt" + }, + { + "tcId": 139, + "comment": "71 bytes, one short of a seal", + "flags": [ + "SealShape" + ], + "inputs": { + "kek": "61b1c8f4adfcbe0ab96751b6a5ba357b172bea516ed6ad51f36b24028d70e638", + "vaultId": "ad75c3d09a927f5e4fe62133b545e566", + "kind": 5, + "epoch": 3, + "blobId": "973d0c4c8ec2c5f8d74276037ff861edbc23ce3c98a757d9f1cce5f7d8fe53cd", + "sealed": "763cb19b2879f338837454de6ae95dc5a2aa90602e11f42857f8ea518ddee7b421a5c2a44e8029fb8575fba32631cfc71f87cc0a3bef98a14a8a72b34e36f71819f88c6470d776" + }, + "expect": "Truncated" + }, + { + "tcId": 140, + "comment": "an all-zero nonce", + "flags": [ + "SealShape" + ], + "inputs": { + "kek": "61b1c8f4adfcbe0ab96751b6a5ba357b172bea516ed6ad51f36b24028d70e638", + "vaultId": "ad75c3d09a927f5e4fe62133b545e566", + "kind": 5, + "epoch": 3, + "blobId": "973d0c4c8ec2c5f8d74276037ff861edbc23ce3c98a757d9f1cce5f7d8fe53cd", + "sealed": "00000000000000000000000000000000000000000000000057f8ea518ddee7b421a5c2a44e8029fb8575fba32631cfc71f87cc0a3bef98a14a8a72b34e36f71819f88c6470d776bb2f0a6f877af457" + }, + "expect": "ZeroValue" + } + ] + } + ], + "numberOfTests": 140 +} diff --git a/tests/test-vectors/gen/Cargo.toml b/tests/test-vectors/gen/Cargo.toml index 25fa3ae..b445229 100644 --- a/tests/test-vectors/gen/Cargo.toml +++ b/tests/test-vectors/gen/Cargo.toml @@ -14,6 +14,7 @@ chacha20poly1305 = { version = "0.11.0", default-features = false } crypthix-crypto = { path = "../../../crates/foundation/crypto", features = ["test-rng"] } hkdf = "0.13.0" sha2 = { version = "0.11.1", default-features = false } +zstd-safe = { version = "8.2.0", default-features = false } [lints] workspace = true diff --git a/tests/test-vectors/gen/src/cdc.rs b/tests/test-vectors/gen/src/cdc.rs new file mode 100644 index 0000000..69ef763 --- /dev/null +++ b/tests/test-vectors/gen/src/cdc.rs @@ -0,0 +1,176 @@ +//! A second FastCDC 2020 chunker, written from the cut rule of FS-52 and the FastCDC 2020 paper +//! (Xia et al., normalised chunking level 2) rather than from `crypthix-core`, so TV-07 checks +//! that crate's chunker against an independent reading of the spec. +//! +//! It takes one byte per step, where the `fastcdc` crate's `v2020` module and `crypthix-core` +//! take two with a shifted table and shifted masks; the two give the same cut points, because +//! `((h << 1) + g) << 1` tested against `mask << 1` is `(h << 1) + g` tested against `mask` +//! when the mask's top bit is clear. The rule: +//! - input no longer than the minimum is one chunk, and empty input has none; +//! - the hash starts at zero at the minimum, rounded down to even, and is `(h << 1) + gear[b]` +//! for each byte `b`; +//! - byte position `p` is tested with the strict mask while `p < 2⌊center / 2⌋`, where `center` +//! is the average or the input length if that is shorter, and with the loose mask after; +//! - only positions below the scanned length rounded down to even are tested, so an odd last +//! byte is never a cut point; +//! - the chunk ends just before the byte whose hash matched, or at the maximum (or the end of +//! the input) when nothing matched. +//! +//! Secret-class objects are not cut by this rule: [`fixed_lengths`] cuts them into chunks of +//! the maximum and a shorter last one, from the length alone. + +use crate::cx; +use crate::labels; + +/// The minimum, average and maximum chunk sizes of format 0 (FS-52). +pub(crate) const MIN: usize = 64 * 1024; +pub(crate) const AVG: usize = 256 * 1024; +pub(crate) const MAX: usize = 1024 * 1024; + +/// The strict mask for a 256 KiB average at normalisation level 2: 20 bits, entry 20 of the +/// FastCDC 2020 mask table. +pub(crate) const MASK_S: u64 = 0x0000_d917_4753_7000; + +/// The loose mask: 16 bits, entry 16 of the same table. +pub(crate) const MASK_L: u64 = 0x0000_d903_0353_7000; + +/// The 256 gear words of a vault: the first 2,048 bytes of the keyed BLAKE3 XOF under +/// `K_gear = KDF(chunker_seed, -, kdf/gear, vault_id)`, read as little-endian `u64`s (FS-52). +pub(crate) fn gear_table(chunker_seed: &[u8; 32], vault_id: &[u8; 16]) -> [u64; 256] { + let key = cx::kdf(chunker_seed, None, labels::full("kdf", "gear"), vault_id); + let mut bytes = [0u8; 2048]; + blake3::Hasher::new_keyed(&key) + .finalize_xof() + .fill(&mut bytes); + let mut words = [0u64; 256]; + let (chunks, _) = bytes.as_chunks::<8>(); + for (word, chunk) in words.iter_mut().zip(chunks) { + *word = u64::from_le_bytes(*chunk); + } + words +} + +/// The hash after the last byte of `window`, starting from zero before its first byte. Each +/// step shifts the earlier bytes one bit further out of the 64-bit word, so the hash at +/// position `p` is this over the bytes from the larger of `2⌊min/2⌋` and `p − 63` to `p`. +pub(crate) fn hash(gear: &[u64; 256], window: &[u8]) -> u64 { + window.iter().fold(0u64, |hash, byte| { + (hash << 1).wrapping_add(gear[usize::from(*byte)]) + }) +} + +/// The length of the first chunk of `data`. +fn cut(gear: &[u64; 256], data: &[u8]) -> usize { + let len = data.len(); + if len <= MIN { + return len; + } + let end = len.min(MAX); + let center = len.min(AVG); + let strict_end = center & !1; + let tested_end = end & !1; + let mut hash = 0u64; + for position in (MIN & !1)..tested_end { + hash = (hash << 1).wrapping_add(gear[usize::from(data[position])]); + let mask = if position < strict_end { + MASK_S + } else { + MASK_L + }; + if hash & mask == 0 { + return position; + } + } + end +} + +/// The lengths of every chunk of `data`, in order. +pub(crate) fn lengths(gear: &[u64; 256], data: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut offset = 0; + while offset < data.len() { + let len = cut(gear, &data[offset..]); + out.push(len); + offset += len; + } + out +} + +/// The lengths of the chunks of a secret-class object of `len` bytes: the maximum, then the +/// rest, with none for an empty object (FS-52). +pub(crate) fn fixed_lengths(len: usize) -> Vec { + let mut out = vec![MAX; len / MAX]; + if !len.is_multiple_of(MAX) { + out.push(len % MAX); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_masks_have_20_and_16_bits_below_bit_63() { + assert_eq!((MASK_S.count_ones(), MASK_L.count_ones()), (20, 16)); + assert_eq!( + MASK_S & MASK_L, + MASK_L, + "the loose mask is part of the strict one" + ); + assert_eq!( + (MASK_S | MASK_L) >> 63, + 0, + "the one-byte rule needs bit 63 clear" + ); + } + + #[test] + fn the_hash_forgets_bytes_64_positions_back() { + let gear = gear_table(&[1; 32], &[2; 16]); + let mut window = [7u8; 70]; + let last_64 = hash(&gear, &window[6..]); + window[..6].copy_from_slice(&[1, 2, 3, 4, 5, 6]); + assert_eq!( + hash(&gear, &window), + last_64, + "only the last 64 bytes count" + ); + window[69] = 8; + assert_ne!(hash(&gear, &window), last_64, "the last byte counts"); + } + + #[test] + fn short_input_is_one_chunk() { + let gear = gear_table(&[1; 32], &[2; 16]); + assert_eq!(lengths(&gear, &[]), Vec::::new()); + assert_eq!(lengths(&gear, &[5; 10]), [10]); + assert_eq!(lengths(&gear, &vec![5; MIN]), [MIN]); + // Above the minimum but below the first pair: nothing is tested. + assert_eq!(lengths(&gear, &vec![5; MIN + 1]), [MIN + 1]); + } + + #[test] + fn chunks_stay_within_the_bounds() { + let gear = gear_table(&[3; 32], &[4; 16]); + let mut data = vec![0u8; 5 * MAX]; + blake3::Hasher::new_keyed(&[9; 32]) + .finalize_xof() + .fill(&mut data); + let lengths = lengths(&gear, &data); + assert_eq!(lengths.iter().sum::(), data.len()); + let (_, rest) = lengths.split_last().expect("chunks"); + for len in rest { + assert!((MIN..=MAX).contains(len), "{len}"); + } + } + + #[test] + fn secret_objects_are_cut_at_the_maximum() { + assert_eq!(fixed_lengths(0), Vec::::new()); + assert_eq!(fixed_lengths(1), [1]); + assert_eq!(fixed_lengths(MAX), [MAX]); + assert_eq!(fixed_lengths(MAX + 1), [MAX, 1]); + assert_eq!(fixed_lengths(5 * MAX / 2), [MAX, MAX, MAX / 2]); + } +} diff --git a/tests/test-vectors/gen/src/inner.rs b/tests/test-vectors/gen/src/inner.rs new file mode 100644 index 0000000..94ca144 --- /dev/null +++ b/tests/test-vectors/gen/src/inner.rs @@ -0,0 +1,37 @@ +//! The inner plaintext of a data blob (FS-54), built by hand rather than with `crypthix-core`. + +use crate::padme::padme; + +/// `comp ‖ rsv ‖ u32be(payload_len) ‖ payload ‖ zero pad` to `padme(6 + payload_len)` bytes. +pub(crate) fn inner(comp: u8, payload: &[u8]) -> Vec { + let len = u32::try_from(payload.len()).expect("a payload under 4 GiB"); + let mut out = vec![comp, 0]; + out.extend_from_slice(&len.to_be_bytes()); + out.extend_from_slice(payload); + out.resize(padded_len(payload.len()), 0); + out +} + +/// `padme(6 + payload_len)` as a length. +pub(crate) fn padded_len(payload_len: usize) -> usize { + let total = padme(payload_len as u64 + 6); + usize::try_from(total).expect("fits in memory") +} + +/// Just the six header bytes: `comp ‖ rsv ‖ u32be(payload_len)`. +pub(crate) fn header(comp: u8, rsv: u8, payload_len: u32) -> Vec { + let mut out = vec![comp, rsv]; + out.extend_from_slice(&payload_len.to_be_bytes()); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layout() { + assert_eq!(inner(0, b""), [0; 6]); + assert_eq!(inner(1, b"abc"), [1, 0, 0, 0, 0, 3, b'a', b'b', b'c', 0]); + } +} diff --git a/tests/test-vectors/gen/src/lib.rs b/tests/test-vectors/gen/src/lib.rs index 74b2d07..b71c991 100644 --- a/tests/test-vectors/gen/src/lib.rs +++ b/tests/test-vectors/gen/src/lib.rs @@ -7,10 +7,13 @@ //! crate's own reading of format spec section 7 ([`cx`]), never with `crypthix-crypto`'s //! primitives, so the two implementations check each other. +mod cdc; mod check; mod cx; +mod inner; mod json; mod labels; +mod padme; mod pre; mod seed; mod test_case; @@ -18,8 +21,10 @@ mod tv02; mod tv03; mod tv04; mod tv05; +mod tv07; mod tv17; mod vector_set; +mod zstd_frame; pub use check::{Mismatch, Problem, check}; pub use json::Json; diff --git a/tests/test-vectors/gen/src/padme.rs b/tests/test-vectors/gen/src/padme.rs new file mode 100644 index 0000000..60b486a --- /dev/null +++ b/tests/test-vectors/gen/src/padme.rs @@ -0,0 +1,40 @@ +//! Padmé (Nikitin et al., PETS 2019), written from FS-54 rather than from `crypthix-core`. + +/// `padme(L)`: for `L ≥ 2`, `E = ⌊log2 L⌋`, `S = ⌊log2 E⌋ + 1`, `z = E − S`, and `L` rounded up +/// to a multiple of `2^z`; `L` itself below 2. +pub(crate) fn padme(len: u64) -> u64 { + if len < 2 { + return len; + } + let e = floor_log2(len); + let s = floor_log2(e) + 1; + let step = 1u64 << (e - s); + len.div_ceil(step) * step +} + +/// `⌊log2 x⌋` for `x ≥ 1`, by counting halvings. +fn floor_log2(mut x: u64) -> u64 { + let mut log = 0; + while x > 1 { + x >>= 1; + log += 1; + } + log +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn worked_values_and_the_overhead_bound() { + // Worked values, and the paper's bound of 12% overhead. + assert_eq!(padme(9), 10); + assert_eq!(padme(1_025), 1_088); + assert_eq!(padme(1 << 20), 1 << 20); + for len in [100u64, 1_000, 65_536 + 7, 3_000_000] { + let padded = padme(len); + assert!(padded >= len && (padded - len) * 100 < len * 12, "{len}"); + } + } +} diff --git a/tests/test-vectors/gen/src/seed.rs b/tests/test-vectors/gen/src/seed.rs index 489eb92..bf14bcd 100644 --- a/tests/test-vectors/gen/src/seed.rs +++ b/tests/test-vectors/gen/src/seed.rs @@ -1,6 +1,6 @@ //! Vector inputs as fuzz seeds. -use crate::test_case::Input; +use crate::test_case::{Input, TestCase}; use crate::vector_set::sets; /// Which fuzz targets a seed feeds. @@ -20,6 +20,16 @@ pub enum SeedTarget { Sealed, /// An Ed25519 public key, signature and message. Signed, + /// A data blob's inner plaintext. + Inner, + /// A zstd frame after its `plain_len` as a 24-bit big-endian number. + Frame, + /// A chunk's plaintext. + Chunk, + /// The input of the `chunker` target: a 24-bit big-endian length, four read sizes, the + /// chunker seed, the vault ID, the data key (all zero for zeros or a pattern) and the + /// pattern, which the target repeats over the file. + Chunker, } impl SeedTarget { @@ -32,8 +42,12 @@ impl SeedTarget { SeedTarget::StoreKey => &["store_key"], SeedTarget::IdText => &["id_text"], SeedTarget::Config => &["config_toml"], - SeedTarget::Sealed => &["cx_open"], + SeedTarget::Sealed => &["cx_open", "data_blob_open"], SeedTarget::Signed => &["verifying_key"], + SeedTarget::Inner => &["inner_plaintext", "data_blob_open"], + SeedTarget::Frame => &["decompress"], + SeedTarget::Chunk => &["data_blob_open"], + SeedTarget::Chunker => &["chunker"], } } } @@ -101,6 +115,66 @@ const SIGNED: [(&str, &str); 3] = [ ), ]; +/// The read sizes of the chunker seeds: a 1-byte read, an interrupted read, then reads of +/// about 1 MiB and 64 KiB (see the `chunker` fuzz target). +const CHUNKER_READS: [u8; 4] = [0, 1, 0xff, 0x0f]; + +/// The integer input `key` of `test`. +fn int_input(test: &TestCase, key: &str) -> Option { + test.inputs.iter().find_map(|(name, input)| match input { + Input::Int(value) if *name == key => Some(*value), + _ => None, + }) +} + +/// The byte input `key` of `test`. +fn bytes_input<'a>(test: &'a TestCase, key: &str) -> Option<&'a [u8]> { + test.inputs.iter().find_map(|(name, input)| match input { + Input::Bytes(bytes) if *name == key => Some(bytes.as_slice()), + _ => None, + }) +} + +/// A 24-bit big-endian length, then `bytes`. +/// +/// # Panics +/// +/// If `len` is negative or does not fit in 24 bits: the vectors never hold such a length. +fn framed(len: i64, bytes: &[u8]) -> Vec { + let len = u32::try_from(len) + .ok() + .filter(|len| *len < 1 << 24) + .expect("a vector length fits in 24 bits"); + [&len.to_be_bytes()[1..], bytes].concat() +} + +/// The `chunker` target's input for a TV-07 chunking test: its length, the read sizes, the +/// chunker seed, the vault ID and the data key, all zero for a run of zeros or a pattern, then +/// the pattern, which the target repeats over the zeros. +fn chunker_seed(test: &TestCase) -> Option> { + let length = int_input(test, "length").or_else(|| int_input(test, "zeros"))?; + let data_key = bytes_input(test, "dataKey").unwrap_or(&[0; 32]); + let mut out = framed(length, &CHUNKER_READS); + out.extend_from_slice(bytes_input(test, "chunkerSeed")?); + out.extend_from_slice(bytes_input(test, "vaultId")?); + out.extend_from_slice(data_key); + out.extend_from_slice(bytes_input(test, "pattern").unwrap_or_default()); + Some(out) +} + +/// The `decompress` target's input for a TV-07 frame given as `frameHead`, `frameZeros` zero +/// bytes and `frameTail`: its `plainLen`, then the frame. +fn zero_run_frame(test: &TestCase) -> Option> { + let zeros = usize::try_from(int_input(test, "frameZeros")?).ok()?; + let frame = [ + bytes_input(test, "frameHead")?, + &vec![0; zeros], + bytes_input(test, "frameTail")?, + ] + .concat(); + Some(framed(int_input(test, "plainLen")?, &frame)) +} + /// Every vector input that a fuzz target can start from, plus a few configs, ID texts and /// signed messages. #[must_use] @@ -116,6 +190,20 @@ pub fn seeds() -> Vec { ("cbor", Input::Bytes(bytes)) => (SeedTarget::Cbor, bytes.clone()), ("path", Input::Text(path)) => (SeedTarget::StoreKey, path.as_bytes().to_vec()), ("sealed", Input::Bytes(bytes)) => (SeedTarget::Sealed, bytes.clone()), + ("inner", Input::Bytes(bytes)) => (SeedTarget::Inner, bytes.clone()), + ("chunk", Input::Bytes(bytes)) => (SeedTarget::Chunk, bytes.clone()), + ("frame", Input::Bytes(bytes)) => match int_input(test, "plainLen") { + Some(plain_len) => (SeedTarget::Frame, framed(plain_len, bytes)), + None => continue, + }, + ("frameHead", Input::Bytes(_)) => match zero_run_frame(test) { + Some(bytes) => (SeedTarget::Frame, bytes), + None => continue, + }, + ("chunkerSeed", Input::Bytes(_)) => match chunker_seed(test) { + Some(bytes) => (SeedTarget::Chunker, bytes), + None => continue, + }, _ => continue, }; // The input name keeps two inputs of one test apart. @@ -151,3 +239,20 @@ pub fn seeds() -> Vec { } out } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn framed_lengths_are_24_bit_big_endian() { + assert_eq!(framed(0x01_02_03, &[9]), [1, 2, 3, 9]); + assert_eq!(framed((1 << 24) - 1, &[]), [0xff; 3]); + } + + #[test] + #[should_panic(expected = "fits in 24 bits")] + fn framed_rejects_a_length_of_2_pow_24() { + let _ = framed(1 << 24, &[]); + } +} diff --git a/tests/test-vectors/gen/src/tv07.rs b/tests/test-vectors/gen/src/tv07.rs new file mode 100644 index 0000000..4f792e2 --- /dev/null +++ b/tests/test-vectors/gen/src/tv07.rs @@ -0,0 +1,1308 @@ +//! TV-07: chunking boundaries, Padmé, the inner plaintext, compression, and data and meta blobs +//! (FS-52 to FS-57). +//! +//! Every output comes from this crate's own code: the one-byte-a-time chunker of [`cdc`], the +//! Padmé of [`padme`], the inner plaintexts of [`inner`], hand-built zstd frames and the +//! section 7 primitives of [`cx`]. Only the encoder frames come from zstd itself (`zstd-safe`, +//! the version in the header): they are inputs to decompression, which any version must accept, +//! and the expected output of the encoder groups, which only the pinned version must match. +//! Inputs too large for hex are given as `dataKey` and `length`, the first `length` bytes of the +//! keyed BLAKE3 XOF under `dataKey` over the empty input, as `pattern` and `length`, the +//! pattern repeated to `length` bytes, or as `zeros`, a run of zero bytes. A frame with a run of +//! more than 1,024 zero bytes is given as `frameHead`, `frameZeros` zero bytes and `frameTail`. + +use crypthix_crypto::test_rng::Stream; + +use crate::cdc; +use crate::cx; +use crate::inner::{self, header, padded_len}; +use crate::labels; +use crate::padme::padme; +use crate::test_case::{Input, TestCase}; +use crate::vector_set::VectorSet; +use crate::zstd_frame::{self, Bent, Block, Header}; + +/// The seed of the set's streams: `BLAKE3("crypthix-vector-gen TV-07")`. +fn seed() -> [u8; 32] { + *blake3::hash(b"crypthix-vector-gen TV-07").as_bytes() +} + +/// 1 MiB, the cap on `plain_len` and `payload_len` (FS-53, FS-54). +const MIB: usize = 1 << 20; + +/// The first `len` bytes of the keyed XOF under `key`. +pub(crate) fn xof(key: &[u8; 32], len: usize) -> Vec { + let mut out = vec![0u8; len]; + blake3::Hasher::new_keyed(key).finalize_xof().fill(&mut out); + out +} + +/// `len` bytes of the keyed XOF under `key`, from `offset`. +fn xof_at(key: &[u8; 32], offset: usize, len: usize) -> Vec { + let mut out = vec![0u8; len]; + let mut reader = blake3::Hasher::new_keyed(key).finalize_xof(); + reader.set_position(u64::try_from(offset).expect("small")); + reader.fill(&mut out); + out +} + +/// Text that compresses well. +fn text(len: usize) -> Vec { + b"The quick brown fox jumps over the lazy dog. " + .iter() + .copied() + .cycle() + .take(len) + .collect() +} + +/// A large input: a keyed XOF stream, a run of zeros, or a short pattern repeated. +#[derive(Clone, Debug)] +enum Big { + Stream([u8; 32], usize), + Zeros(usize), + Pattern(Vec, usize), +} + +impl Big { + fn bytes(&self) -> Vec { + match self { + Big::Stream(key, len) => xof(key, *len), + Big::Zeros(len) => vec![0; *len], + Big::Pattern(pattern, len) => pattern.iter().copied().cycle().take(*len).collect(), + } + } + + fn inputs(&self) -> Vec<(&'static str, Input)> { + match self { + Big::Stream(key, len) => vec![ + ("dataKey", Input::bytes(key)), + ("length", Input::Int(int(*len))), + ], + Big::Zeros(len) => vec![("zeros", Input::Int(int(*len)))], + Big::Pattern(pattern, len) => vec![ + ("pattern", Input::bytes(pattern)), + ("length", Input::Int(int(*len))), + ], + } + } +} + +fn int(value: usize) -> i64 { + i64::try_from(value).expect("small") +} + +fn ints(values: &[usize]) -> Input { + Input::Ints(values.iter().copied().map(int).collect()) +} + +// ---------------------------------------------------------------------------------------------- +// Chunking (FS-52) + +/// How many candidates a search for an edge case tries before it gives up. Each search succeeds +/// with probability about 2^-16 or better per candidate, so the bound is never reached. +const TRIES: u64 = 1 << 24; + +/// The length of the repeated pattern that is never cut before the maximum. +const PATTERN_LEN: usize = 1_021; + +/// The first candidate key under `base`, `H(base, counter)` for counters from 0, for which +/// `found` gives a value. +fn search(base: &[u8; 32], what: &str, mut found: impl FnMut([u8; 32]) -> Option) -> T { + (0..TRIES) + .find_map(|counter| found(*blake3::keyed_hash(base, &counter.to_le_bytes()).as_bytes())) + .unwrap_or_else(|| panic!("no {what} in {TRIES} tries")) +} + +/// The length of the first chunk of `data`. +fn first_cut(gear: &[u64; 256], data: &Big) -> usize { + cdc::lengths(gear, &data.bytes()) + .first() + .copied() + .unwrap_or(0) +} + +/// A chunking case found by search: comment, chunker seed, gear table and data. +type Edge = (&'static str, [u8; 32], [u64; 256], Big); + +/// Files whose cut points sit exactly on the edges of the FS-52 rule, found by a deterministic +/// search over data keys (and chunker seeds, where the edge depends on one gear word) and +/// checked here with the one-byte chunker, so each case shows what its comment says: a +/// chunker off by one at that edge cuts elsewhere. +#[allow(clippy::too_many_lines, reason = "one search per edge")] +fn chunk_edges( + seed: &[u8; 32], + vault_id: &[u8; 16], + chunker_seed: &[u8; 32], + gear: &[u64; 256], +) -> Vec { + use cdc::{AVG, MASK_L, MASK_S, MAX, MIN}; + let mut stream = Stream::new(seed, "chunking-edges"); + let bases: [[u8; 32]; 9] = std::array::from_fn(|_| stream.bytes()); + let matches = |hash: u64, mask: u64| hash & mask == 0; + let mut edges = Vec::new(); + + // An odd length MIN + 3: MIN and MIN + 1 are tested under the strict mask, the last byte + // at MIN + 2 = 2⌊center/2⌋ would be tested under the loose one, and it matches. + let len = MIN + 3; + let key = search(&bases[0], "odd last byte that matches", |key| { + let window = xof_at(&key, MIN, 3); + let hash = |n: usize| cdc::hash(gear, &window[..n]); + (!matches(hash(1), MASK_S) && !matches(hash(2), MASK_S) && matches(hash(3), MASK_L)) + .then_some(key) + }); + let data = Big::Stream(key, len); + let bytes = data.bytes(); + assert_eq!(len & !1, MIN + 2, "the last byte is past the strict range"); + assert!(matches(cdc::hash(gear, &bytes[MIN..]), MASK_L)); + assert_eq!( + cdc::lengths(gear, &bytes), + [len], + "the odd last byte is not a cut point" + ); + edges.push(( + "an odd last byte whose hash matches the mask is never tested: one chunk", + *chunker_seed, + *gear, + data, + )); + + // A cut at MIN: the hash there is one gear word, so first find a table with a word that + // matches the strict mask, then a file with that byte at MIN. + let (min_seed, min_gear, value) = search(&bases[1], "gear word that matches", |seed| { + let gear = cdc::gear_table(&seed, vault_id); + let value = (0..=u8::MAX).find(|byte| matches(gear[usize::from(*byte)], MASK_S))?; + Some((seed, gear, value)) + }); + let key = search(&bases[2], "file with that byte at the minimum", |key| { + (xof_at(&key, MIN, 1)[0] == value).then_some(key) + }); + let data = Big::Stream(key, 3 * MIN); + assert_eq!(first_cut(&min_gear, &data), MIN, "a cut at the minimum"); + edges.push(( + "a cut at exactly the 64 KiB minimum, the first position tested", + min_seed, + min_gear, + data, + )); + + // A cut at MIN + 1, from a pair of bytes whose first does not match. + let (pair_seed, pair_gear, pairs) = search(&bases[3], "pair of bytes that match", |seed| { + let gear = cdc::gear_table(&seed, vault_id); + let pairs: Vec<[u8; 2]> = (0..=u16::MAX) + .map(u16::to_be_bytes) + .filter(|pair| { + !matches(cdc::hash(&gear, &pair[..1]), MASK_S) + && matches(cdc::hash(&gear, pair), MASK_S) + }) + .collect(); + (!pairs.is_empty()).then_some((seed, gear, pairs)) + }); + let key = search(&bases[4], "file with that pair at the minimum", |key| { + let window = xof_at(&key, MIN, 2); + pairs.contains(&[window[0], window[1]]).then_some(key) + }); + let data = Big::Stream(key, 3 * MIN); + assert_eq!( + first_cut(&pair_gear, &data), + MIN + 1, + "a cut one past the minimum" + ); + edges.push(( + "a cut at the minimum plus one, the second byte of the first pair", + pair_seed, + pair_gear, + data, + )); + + // Longer than AVG, so center = AVG and the loose mask starts at AVG. The hash at a position + // depends on the 64 bytes up to it only. + let len = 3 * AVG; + let loose_only = |hash: u64| matches(hash, MASK_L) && !matches(hash, MASK_S); + let key = search(&bases[5], "loose-only match at the average", |key| { + let hash = cdc::hash(gear, &xof_at(&key, AVG - 63, 64)); + (loose_only(hash) && first_cut(gear, &Big::Stream(key, len)) == AVG).then_some(key) + }); + edges.push(( + "a cut at 256 KiB, the first position under the loose mask; the strict mask does not match there", + *chunker_seed, + *gear, + Big::Stream(key, len), + )); + let key = search(&bases[6], "loose-only match before the average", |key| { + let hash = cdc::hash(gear, &xof_at(&key, AVG - 64, 64)); + (loose_only(hash) && first_cut(gear, &Big::Stream(key, len)) > AVG - 1).then_some(key) + }); + edges.push(( + "the loose mask would match at 256 KiB - 1, the last position under the strict mask: no cut there", + *chunker_seed, + *gear, + Big::Stream(key, len), + )); + + // Shorter than AVG: center = len, every tested position is strict, and the last one tested + // is strict_end - 1 = 2⌊len/2⌋ - 1. Find a file whose first strict match is at an odd + // position p, and cut the file to p + 1 bytes. + let (key, cut) = search(&bases[7], "strict match at an odd position", |key| { + let cut = first_cut(gear, &Big::Stream(key, AVG)); + (cut < AVG && cut % 2 == 1).then_some((key, cut)) + }); + let data = Big::Stream(key, cut + 1); + let bytes = data.bytes(); + let window = &bytes[cut.saturating_sub(63).max(MIN)..=cut]; + assert!( + matches(cdc::hash(gear, window), MASK_S), + "a strict match at {cut}" + ); + assert_eq!( + cdc::lengths(gear, &bytes), + [cut, 1], + "a cut at strict_end - 1" + ); + edges.push(( + "a strict match at strict_end - 1, the last position tested: a one-byte last chunk", + *chunker_seed, + *gear, + data, + )); + + // A pattern repeated: the hash takes PATTERN_LEN values, so a pattern none of whose values + // matches the loose mask (or the strict one, which has every bit of the loose) is never cut + // before the maximum. + let len = 2 * MAX + 5; + let pattern = search(&bases[8], "pattern that never matches", |key| { + let pattern = xof(&key, PATTERN_LEN); + let data = Big::Pattern(pattern.clone(), len); + (cdc::lengths(gear, &data.bytes()) == [MAX, MAX, 5]).then_some(pattern) + }); + edges.push(( + "a 1,021-byte random pattern repeated over 2 MiB + 5 bytes: no position matches, cut at the 1 MiB maximum", + *chunker_seed, + *gear, + Big::Pattern(pattern, len), + )); + edges +} + +fn chunking_tests(seed: &[u8; 32]) -> Vec { + let mut stream = Stream::new(seed, "chunking"); + let chunker_seed: [u8; 32] = stream.bytes(); + let other_seed: [u8; 32] = stream.bytes(); + let vault_id: [u8; 16] = stream.bytes(); + let data_key: [u8; 32] = stream.bytes(); + let gear = cdc::gear_table(&chunker_seed, &vault_id); + let other_gear = cdc::gear_table(&other_seed, &vault_id); + + let big = Big::Stream(data_key, 8 * MIB); + let with_lengths = |comment: &'static str, + flag: &'static str, + chunker_seed: &[u8; 32], + class: &'static str, + data: Big, + lengths: &[usize]| { + let mut inputs = vec![ + ("chunkerSeed", Input::bytes(chunker_seed)), + ("vaultId", Input::bytes(&vault_id)), + ("class", Input::text(class)), + ]; + inputs.extend(data.inputs()); + TestCase::new(comment, &[flag], "Ok", inputs).with_outputs(vec![("lengths", ints(lengths))]) + }; + let case = |comment: &'static str, + flag: &'static str, + chunker_seed: &[u8; 32], + gear: &[u64; 256], + data: Big| { + let lengths = cdc::lengths(gear, &data.bytes()); + with_lengths(comment, flag, chunker_seed, "ordinary", data, &lengths) + }; + // A secret-class object is cut from its length alone, never through the gear table. + let secret = |comment: &'static str, data: Big| { + let len = data.bytes().len(); + let lengths = cdc::fixed_lengths(len); + with_lengths( + comment, + "SecretFixed", + &chunker_seed, + "secret", + data, + &lengths, + ) + }; + // An odd tail of MIN + 3 bytes after the first boundary past 1 MiB: positions MIN and + // MIN + 1 are tested, the last byte is not. The earlier boundaries stay where they were. + let prefix = xof(&data_key, 3 * MIB); + let boundary: usize = cdc::lengths(&gear, &prefix) + .iter() + .scan(0, |end, len| { + *end += len; + Some(*end) + }) + .find(|end| *end > MIB) + .expect("a boundary past 1 MiB"); + let odd = Big::Stream(data_key, boundary + cdc::MIN + 3); + let odd_lengths = cdc::lengths(&gear, &odd.bytes()); + assert_eq!(odd_lengths.last(), Some(&(cdc::MIN + 3)), "an odd tail"); + let main_lengths = cdc::lengths(&gear, &big.bytes()); + assert_ne!( + main_lengths, + cdc::lengths(&other_gear, &big.bytes()), + "another chunker seed moves the boundaries" + ); + let s = &chunker_seed; + let g = &gear; + #[rustfmt::skip] + let mut tests = vec![ + case("an empty file has no chunks", "SmallFile", s, g, Big::Zeros(0)), + case("one byte is one chunk", "SmallFile", s, g, Big::Stream(data_key, 1)), + case("one byte under the 64 KiB minimum", "SmallFile", s, g, Big::Stream(data_key, cdc::MIN - 1)), + case("exactly the minimum is one chunk", "SmallFile", s, g, Big::Stream(data_key, cdc::MIN)), + case("one byte over the minimum: no position is tested", "CutPoints", s, g, Big::Stream(data_key, cdc::MIN + 1)), + case("3 MiB of zeros", "CutPoints", s, g, Big::Zeros(3 * MIB)), + case("an odd tail of 64 KiB + 3 bytes after a boundary: the last byte is never a cut point", "CutPoints", s, g, odd), + case("8 MiB of random data", "CutPoints", s, g, big.clone()), + case("the same 8 MiB under another chunker seed", "KeyedGear", &other_seed, &other_gear, big.clone()), + secret("an empty secret file has no chunks", Big::Zeros(0)), + secret("a secret file of exactly 1 MiB is one chunk", Big::Stream(data_key, MIB)), + secret("a secret file of 1 MiB and one byte is two chunks", Big::Stream(data_key, MIB + 1)), + secret("2.5 MiB of a secret file: 1 MiB, 1 MiB, 0.5 MiB", Big::Stream(data_key, 5 * MIB / 2)), + secret("the 8 MiB of random data in a secret file: eight 1 MiB chunks", big), + ]; + for (comment, edge_seed, edge_gear, data) in chunk_edges(seed, &vault_id, &chunker_seed, &gear) + { + tests.push(case(comment, "CutEdges", &edge_seed, &edge_gear, data)); + } + tests +} + +// ---------------------------------------------------------------------------------------------- +// Padmé (FS-54) + +fn padme_tests() -> Vec { + let lengths: [(&'static str, u64); 12] = [ + ("0 stays 0", 0), + ("1 stays 1", 1), + ("2 stays 2", 2), + ("7 stays 7", 7), + ("9 rounds to 10", 9), + ("an empty payload: 6", 6), + ("a 1,000-byte payload: 1,006", 1_006), + ("1,025 rounds to a multiple of 64", 1_025), + ("a 64 KiB chunk: 65,542", 65_542), + ("2^20 stays 2^20", 1 << 20), + ("a 1 MiB payload: 2^20 + 6", (1 << 20) + 6), + ("2^32 + 1", (1 << 32) + 1), + ]; + lengths + .into_iter() + .map(|(comment, len)| { + let value = i64::try_from(len).expect("small"); + let padded = i64::try_from(padme(len)).expect("small"); + TestCase::new( + comment, + &["Padme"], + "Ok", + vec![("length", Input::Int(value))], + ) + .with_outputs(vec![("padded", Input::Int(padded))]) + }) + .collect() +} + +// ---------------------------------------------------------------------------------------------- +// Inner plaintext (FS-54) + +fn inner_case( + comment: &'static str, + flag: &'static str, + expect: &'static str, + bytes: &[u8], +) -> TestCase { + let ok = expect == "Ok"; + let test = TestCase::new( + comment, + &[flag], + expect, + vec![("inner", Input::bytes(bytes))], + ); + if !ok { + return test; + } + let len = u32::from_be_bytes(bytes[2..6].try_into().expect("4 bytes")); + let len = usize::try_from(len).expect("small"); + test.with_outputs(vec![ + ("comp", Input::Int(i64::from(bytes[0]))), + ("payload", Input::bytes(&bytes[6..6 + len])), + ]) +} + +/// `bytes` with `byte` at `index` set to `value`. +fn with(bytes: &[u8], index: usize, value: u8) -> Vec { + let mut out = bytes.to_vec(); + out[index] = value; + out +} + +fn inner_tests(seed: &[u8; 32]) -> Vec { + let mut stream = Stream::new(seed, "inner"); + let payload_key: [u8; 32] = stream.bytes(); + let mut payload = vec![0u8; 1_000]; + stream.fill_bytes(&mut payload); + let thousand = inner::inner(0, &payload); + assert_eq!(thousand.len(), 1_024); + let longer = [thousand.as_slice(), &[0]].concat(); + let cap = u32::try_from(MIB).expect("small"); + + // The 1 MiB payload is too large for hex: header, stream and pad are given apart. + let full = TestCase::new( + "a payload of exactly 1 MiB", + &["InnerLimit"], + "Ok", + vec![ + ("header", Input::Bytes(header(0, 0, cap))), + ("dataKey", Input::bytes(&payload_key)), + ("length", Input::Int(int(MIB))), + ("padLength", Input::Int(int(padded_len(MIB) - MIB - 6))), + ], + ) + .with_outputs(vec![("comp", Input::Int(0))]); + + #[rustfmt::skip] + let tests = vec![ + inner_case("an empty raw payload is the 6-byte header", "InnerOk", "Ok", &inner::inner(0, b"")), + inner_case("a 3-byte zstd payload, padded to 10", "InnerOk", "Ok", &inner::inner(1, b"abc")), + inner_case("a 1,000-byte raw payload, padded to 1,024", "InnerOk", "Ok", &thousand), + full, + inner_case("payload_len 2^20 + 1", "InnerLimit", "Limit", &header(0, 0, cap + 1)), + inner_case("payload_len 2^32 - 1", "InnerLimit", "Limit", &header(1, 0, u32::MAX)), + inner_case("payload_len 2^20 with only the header", "InnerPadding", "Padding", &header(0, 0, cap)), + inner_case("no bytes", "InnerPadding", "Padding", &[]), + inner_case("five bytes, one short of a header", "InnerPadding", "Padding", &[0; 5]), + inner_case("comp 2", "InnerPadding", "Padding", &with(&thousand, 0, 2)), + inner_case("comp 255", "InnerPadding", "Padding", &with(&thousand, 0, 0xff)), + inner_case("rsv 1", "InnerPadding", "Padding", &with(&thousand, 1, 1)), + inner_case("rsv 0x80", "InnerPadding", "Padding", &with(&thousand, 1, 0x80)), + inner_case("the first pad byte is not zero", "InnerPadding", "Padding", &with(&thousand, 1_006, 1)), + inner_case("the last pad byte is not zero", "InnerPadding", "Padding", &with(&thousand, 1_023, 0x80)), + inner_case("one byte longer than padme(6 + payload_len)", "InnerPadding", "Padding", &longer), + inner_case("one byte shorter than padme(6 + payload_len)", "InnerPadding", "Padding", &thousand[..1_023]), + inner_case("no pad at all", "InnerPadding", "Padding", &thousand[..1_006]), + inner_case("comp 2 with payload_len 2^20 + 1: comp is checked first", "CheckOrder", "Padding", &header(2, 0, cap + 1)), + inner_case("rsv 1 with payload_len 2^20 + 1: rsv is checked first", "CheckOrder", "Padding", &header(0, 1, cap + 1)), + ]; + tests +} + +// ---------------------------------------------------------------------------------------------- +// Compression (FS-53): the encoder under the pinned version + +/// The class names the vectors use. +const ORDINARY: &str = "ordinary"; +const SECRET: &str = "secret"; + +/// The inner plaintext FS-53 writes for `chunk`. +fn encode_chunk(chunk: &[u8], class: &str) -> Vec { + if class == SECRET { + return inner::inner(0, chunk); + } + let frame = zstd_frame::encode(chunk, Bent::No); + // Kept only if 16 × frame ≤ 15 × chunk. + if frame.len() * 16 <= chunk.len() * 15 { + inner::inner(1, &frame) + } else { + inner::inner(0, chunk) + } +} + +/// Raw inner plaintexts above this size are given by their length only: they are the chunk +/// itself with the header and a zero pad. +const HEX_INNER_UP_TO: usize = 16 * 1024; + +fn compress_case( + comment: &'static str, + flag: &'static str, + class: &'static str, + chunk: &Chunk, +) -> TestCase { + let bytes = chunk.bytes(); + let inner = encode_chunk(&bytes, class); + let mut inputs = vec![("class", Input::text(class))]; + inputs.extend(chunk.inputs()); + let mut outputs = vec![ + ("comp", Input::Int(i64::from(inner[0]))), + ("innerLength", Input::Int(int(inner.len()))), + ]; + if inner.len() <= HEX_INNER_UP_TO { + outputs.push(("inner", Input::Bytes(inner))); + } + TestCase::new(comment, &[flag], "Ok", inputs).with_outputs(outputs) +} + +/// A chunk: hex if small, else a large input. +#[derive(Clone, Debug)] +enum Chunk { + Hex(Vec), + Big(Big), +} + +impl Chunk { + fn bytes(&self) -> Vec { + match self { + Chunk::Hex(bytes) => bytes.clone(), + Chunk::Big(big) => big.bytes(), + } + } + + fn inputs(&self) -> Vec<(&'static str, Input)> { + match self { + Chunk::Hex(bytes) => vec![("chunk", Input::Bytes(bytes.clone()))], + Chunk::Big(big) => big.inputs(), + } + } +} + +/// Two 4,096-byte chunks of random bytes then zeros, one random byte apart, the first kept +/// compressed and the second stored raw. +fn keep_edge(key: &[u8; 32]) -> (Vec, Vec) { + const LEN: usize = 4_096; + let random = xof(key, LEN); + let chunk = |len: usize| [&random[..len], &vec![0; LEN - len]].concat(); + let kept = |data: &[u8]| zstd_frame::encode(data, Bent::No).len() * 16 <= LEN * 15; + // Bisect between all zeros, which is kept, and all random, which is not. + let (mut low, mut high) = (0, LEN); + assert!(kept(&chunk(low)) && !kept(&chunk(high))); + while high - low > 1 { + let middle = low + (high - low) / 2; + if kept(&chunk(middle)) { + low = middle; + } else { + high = middle; + } + } + let (below, at) = (chunk(low), chunk(high)); + (below, at) +} + +fn compress_tests(seed: &[u8; 32]) -> Vec { + let mut stream = Stream::new(seed, "compress"); + let random_key: [u8; 32] = stream.bytes(); + let edge_key: [u8; 32] = stream.bytes(); + let mut random = vec![0u8; 100]; + stream.fill_bytes(&mut random); + let (kept, raw) = keep_edge(&edge_key); + let zeros = || Chunk::Big(Big::Zeros(MIB)); + #[rustfmt::skip] + let tests = vec![ + compress_case("1 MiB of zeros", "Compress", ORDINARY, &zeros()), + compress_case("5,000 bytes of text", "Compress", ORDINARY, &Chunk::Hex(text(5_000))), + compress_case("random bytes then zeros: the frame just saves 1/16", "StoreRaw", ORDINARY, &Chunk::Hex(kept)), + compress_case("one more random byte: the frame no longer saves 1/16, stored raw", "StoreRaw", ORDINARY, &Chunk::Hex(raw)), + compress_case("100 random bytes are stored raw", "StoreRaw", ORDINARY, &Chunk::Hex(random)), + compress_case("an empty chunk is stored raw", "StoreRaw", ORDINARY, &Chunk::Hex(Vec::new())), + compress_case("1 MiB of random data is stored raw", "StoreRaw", ORDINARY, &Chunk::Big(Big::Stream(random_key, MIB))), + compress_case("a secret object's text is never compressed", "SecretRaw", SECRET, &Chunk::Hex(text(5_000))), + compress_case("a secret object's 1 MiB of zeros is never compressed", "SecretRaw", SECRET, &zeros()), + ]; + tests +} + +// ---------------------------------------------------------------------------------------------- +// Decompression (FS-53): any zstd version + +fn frame_case( + comment: &'static str, + flag: &'static str, + frame: Vec, + plain_len: usize, + plaintext: Option<&[u8]>, +) -> TestCase { + let expect = if plaintext.is_some() { + "Ok" + } else { + "Decompress" + }; + let mut inputs = match longest_zero_run(&frame) { + (start, len) if len > 1_024 => vec![ + ("frameHead", Input::bytes(&frame[..start])), + ("frameZeros", Input::Int(int(len))), + ("frameTail", Input::bytes(&frame[start + len..])), + ], + _ => vec![("frame", Input::Bytes(frame))], + }; + inputs.push(("plainLen", Input::Int(int(plain_len)))); + let test = TestCase::new(comment, &[flag], expect, inputs); + match plaintext { + Some(plaintext) if plaintext.iter().all(|byte| *byte == 0) && plaintext.len() > 1_024 => { + test.with_outputs(vec![("plaintextZeros", Input::Int(int(plaintext.len())))]) + } + Some(plaintext) => test.with_outputs(vec![("plaintext", Input::bytes(plaintext))]), + None => test, + } +} + +/// The start and length of the first longest run of zero bytes in `bytes`. +fn longest_zero_run(bytes: &[u8]) -> (usize, usize) { + let mut best = (0, 0); + let mut start = 0; + for (index, byte) in bytes.iter().enumerate() { + if *byte != 0 { + start = index + 1; + } else if index + 1 - start > best.1 { + best = (start, index + 1 - start); + } + } + best +} + +/// A decompression case: comment, flag, frame, `plain_len` and the plaintext if it decodes. +type FrameCase = (&'static str, &'static str, Vec, usize, Option>); + +fn decompress_tests() -> Vec { + let words = text(3_000); + let encoded = zstd_frame::encode(&words, Bent::No); + let hello = zstd_frame::raw_frame(b"hello"); + let declared = |size: u64, content: &[u8]| { + zstd_frame::frame(&Header::declaring(size), &[Block::Raw(content.to_vec())]) + }; + let windowed = |window: u8| { + let header = Header { + single_segment: false, + window, + ..Header::declaring(5) + }; + zstd_frame::frame(&header, &[Block::Raw(b"hello".to_vec())]) + }; + let bent = |change: fn(&mut Header)| { + let mut header = Header::declaring(5); + change(&mut header); + zstd_frame::frame(&header, &[Block::Raw(b"hello".to_vec())]) + }; + let skippable = zstd_frame::skippable(b"skip"); + let rle = zstd_frame::rle_frame(b'a', 300); + let wide_rle = zstd_frame::frame( + &Header { + fcs_flag: Some(2), + ..Header::declaring(300) + }, + &[Block::Rle(b'a', 300)], + ); + let zeros = vec![0u8; MIB]; + let one_over = zstd_frame::rle_frame(0, MIB + 1); + let mut wrong_magic = hello.clone(); + wrong_magic[0] ^= 1; + let ok = |plaintext: &[u8]| Some(plaintext.to_vec()); + let w20 = Header::window_of(20); + let reserved = zstd_frame::frame(&Header::declaring(5), &[Block::Reserved(b"hello".to_vec())]); + let block_zeros = vec![0u8; zstd_frame::MAX_BLOCK]; + let max_block = zstd_frame::raw_frame(&block_zeros); + // libzstd up to 1.5.2 refused a compressed block of exactly 128 KiB (zstd's + // decompressor_errata.md); its encoder never writes one, so the block is built by hand, + // with a window of 2^17 bytes, since a block may be no larger than the window. + let literals = vec![0u8; zstd_frame::MAX_BLOCK - 4]; + let max_compressed = zstd_frame::frame( + &Header { + single_segment: false, + window: Header::window_of(17), + ..Header::declaring(literals.len() as u64) + }, + &[Block::Compressed(zstd_frame::literals_only(&literals))], + ); + + #[rustfmt::skip] + let cases: Vec = vec![ + ("an encoder frame of 3,000 bytes of text", "FrameOk", encoded.clone(), 3_000, ok(&words)), + ("a raw block of 5 bytes, one-byte content size", "FrameOk", hello.clone(), 5, ok(b"hello")), + ("an empty raw block, content size 0", "FrameOk", zstd_frame::raw_frame(b""), 0, ok(b"")), + ("an RLE block of 300 bytes, two-byte content size", "FrameOk", rle, 300, ok(&[b'a'; 300])), + ("a window of exactly 2^20 bytes", "FrameOk", windowed(w20), 5, ok(b"hello")), + ("a raw block of exactly 128 KiB, the largest block", "FrameOk", max_block, zstd_frame::MAX_BLOCK, ok(&block_zeros)), + ("a compressed block of exactly 128 KiB: raw literals and no sequences", "FrameOk", max_compressed, literals.len(), ok(&literals)), + ("plain_len 2^20: eight RLE blocks of zeros", "PlainLenCap", zstd_frame::rle_frame(0, MIB), MIB, ok(&zeros)), + ("plain_len 2^20 + 1 is refused before decoding", "PlainLenCap", one_over, MIB + 1, None), + ("plain_len one below the declared size", "FrameRejected", hello.clone(), 4, None), + ("plain_len one above the declared size", "FrameRejected", hello.clone(), 6, None), + ("the frame holds more than it declares", "FrameRejected", declared(5, b"hello!"), 5, None), + ("the frame holds less than it declares", "FrameRejected", declared(5, b"hell"), 5, None), + ("a valid header, then a block of the reserved type 3", "FrameRejected", reserved, 5, None), + ("an encoder frame with a content checksum", "FrameRejected", zstd_frame::encode(&words, Bent::Checksum), 3_000, None), + ("an encoder frame without a content size", "FrameRejected", zstd_frame::encode(&words, Bent::NoContentSize), 3_000, None), + ("a dictionary ID", "FrameRejected", bent(|header| header.dict_id = Some(1)), 5, None), + ("the reserved bit set", "FrameRejected", bent(|header| header.stray_bits = zstd_frame::RESERVED_BIT), 5, None), + ("the unused bit set, which libzstd ignores", "FrameRejected", bent(|header| header.stray_bits = zstd_frame::UNUSED_BIT), 5, None), + ("a four-byte content size for 5 bytes, which libzstd reads", "FrameRejected", bent(|header| header.fcs_flag = Some(2)), 5, None), + ("an eight-byte content size for 5 bytes, which libzstd reads", "FrameRejected", bent(|header| header.fcs_flag = Some(3)), 5, None), + ("a four-byte content size for 300 bytes, which libzstd reads", "FrameRejected", wide_rle, 300, None), + ("a window of 2^21 bytes", "FrameRejected", windowed(Header::window_of(21)), 5, None), + ("a window of 2^20 + 2^17 bytes", "FrameRejected", windowed(w20 | 1), 5, None), + ("a skippable frame alone", "FrameRejected", skippable.clone(), 0, None), + ("a skippable frame before the frame", "FrameRejected", [skippable.as_slice(), &hello].concat(), 5, None), + ("a skippable frame after the frame", "FrameRejected", [hello.as_slice(), &skippable].concat(), 5, None), + ("two frames", "FrameRejected", [zstd_frame::raw_frame(&b"hello"[..3]), zstd_frame::raw_frame(&b"hello"[3..])].concat(), 3, None), + ("a trailing byte", "FrameRejected", [hello.as_slice(), &[0]].concat(), 5, None), + ("the last byte cut off", "FrameRejected", hello[..hello.len() - 1].to_vec(), 5, None), + ("a wrong magic number", "FrameRejected", wrong_magic, 5, None), + ("no bytes", "FrameRejected", Vec::new(), 0, None), + ]; + cases + .into_iter() + .map(|(comment, flag, frame, plain_len, plaintext)| { + frame_case(comment, flag, frame, plain_len, plaintext.as_deref()) + }) + .collect() +} + +// ---------------------------------------------------------------------------------------------- +// Data blobs (FS-55, FS-56) + +/// The keys and context of one object's data blobs. +struct DataContext { + dek: [u8; 32], + dek_salt: [u8; 32], + vault_id: [u8; 16], + object_id: [u8; 16], + dek_id: [u8; 16], +} + +impl DataContext { + fn draw(stream: &mut Stream) -> Self { + Self { + dek: stream.bytes(), + dek_salt: stream.bytes(), + vault_id: stream.bytes(), + object_id: stream.bytes(), + dek_id: stream.bytes(), + } + } + + fn context(&self) -> Vec { + [&self.vault_id[..], &self.object_id, &self.dek_id].concat() + } + + /// `K_chunk` (FS-38). + fn chunk_key(&self) -> [u8; 32] { + let label = labels::full("kdf", "chunk-key"); + cx::kdf(&self.dek, Some(&self.dek_salt), label, &self.context()) + } + + /// `K_blobid` (FS-38). + fn blob_id_key(&self) -> [u8; 32] { + let label = labels::full("kdf", "blob-id-key"); + cx::kdf(&self.dek, Some(&self.dek_salt), label, &self.context()) + } + + /// The keyed blob ID of `chunk` (FS-55). + fn keyed_id(&self, chunk: &[u8]) -> [u8; 32] { + cx::mac(&self.blob_id_key(), chunk) + } + + /// The data-blob AAD with these fields (FS-55). + fn aad(&self, blob_id: &[u8; 32]) -> Vec { + data_aad(&self.vault_id, 0x01, &self.object_id, &self.dek_id, blob_id) + } + + fn inputs(&self) -> Vec<(&'static str, Input)> { + vec![ + ("dek", Input::bytes(&self.dek)), + ("dekSalt", Input::bytes(&self.dek_salt)), + ("vaultId", Input::bytes(&self.vault_id)), + ("objectId", Input::bytes(&self.object_id)), + ("dekId", Input::bytes(&self.dek_id)), + ] + } +} + +fn data_aad( + vault_id: &[u8; 16], + kind: u8, + object_id: &[u8; 16], + dek_id: &[u8; 16], + blob_id: &[u8; 32], +) -> Vec { + cx::aad( + labels::full("aad", "blob-data"), + &[vault_id, &[kind], object_id, dek_id, blob_id], + ) +} + +fn data_seal_tests(seed: &[u8; 32]) -> Vec { + let mut stream = Stream::new(seed, "data-blob-seal"); + let object = DataContext::draw(&mut stream); + let mut random = vec![0u8; 500]; + stream.fill_bytes(&mut random); + let random_ids: [[u8; 32]; 2] = [stream.bytes(), stream.bytes()]; + let rands: [[u8; 32]; 4] = std::array::from_fn(|_| stream.bytes()); + + let case = |comment: &'static str, + flags: &[&'static str], + class: &'static str, + count: usize, + chunk: Vec, + given_id: Option<[u8; 32]>, + rand: &[u8; 32]| { + let blob_id = given_id.unwrap_or_else(|| object.keyed_id(&chunk)); + let inner = encode_chunk(&chunk, class); + let aad = object.aad(&blob_id); + let key = object.chunk_key(); + let nonce = cx::hedged_nonce(&key, &aad, &inner, rand); + let mut inputs = object.inputs(); + inputs.extend([ + ("class", Input::text(class)), + ("chunkCount", Input::Int(int(count))), + ("chunk", Input::Bytes(chunk)), + ]); + if let Some(id) = given_id { + inputs.push(("blobId", Input::bytes(&id))); + } + inputs.push(("rand", Input::bytes(rand))); + TestCase::new(comment, flags, "Ok", inputs).with_outputs(vec![ + ("blobId", Input::bytes(&blob_id)), + ("inner", Input::bytes(&inner)), + ("nonce", Input::bytes(&nonce)), + ("sealed", Input::Bytes(cx::seal(&key, &aad, &inner, &nonce))), + ]) + }; + #[rustfmt::skip] + let tests = vec![ + case("chunk of a two-chunk object, compressed", &["DataBlobSeal", "KeyedBlobId"], ORDINARY, 2, text(2_000), None, &rands[0]), + case("random chunk of a three-chunk object, stored raw", &["DataBlobSeal", "KeyedBlobId"], ORDINARY, 3, random, None, &rands[1]), + case("the one chunk of a single-chunk object", &["DataBlobSeal", "RandomBlobId"], ORDINARY, 1, text(1_500), Some(random_ids[0]), &rands[2]), + case("chunk of a secret object: raw and a random ID", &["DataBlobSeal", "RandomBlobId", "SecretRaw"], SECRET, 5, text(2_000), Some(random_ids[1]), &rands[3]), + ]; + tests +} + +/// One data-blob open test. +struct Open<'a> { + object: &'a DataContext, + class: &'static str, + count: usize, + blob_id: [u8; 32], + plain_len: usize, + sealed: Vec, +} + +impl Open<'_> { + fn case( + self, + comment: &'static str, + flags: &[&'static str], + expect: &'static str, + plaintext: Option<&[u8]>, + ) -> TestCase { + let mut inputs = self.object.inputs(); + inputs.extend([ + ("class", Input::text(self.class)), + ("chunkCount", Input::Int(int(self.count))), + ("blobId", Input::bytes(&self.blob_id)), + ("plainLen", Input::Int(int(self.plain_len))), + ("sealed", Input::Bytes(self.sealed)), + ]); + let test = TestCase::new(comment, flags, expect, inputs); + match plaintext { + Some(plaintext) => test.with_outputs(vec![("plaintext", Input::bytes(plaintext))]), + None => test, + } + } +} + +#[allow(clippy::too_many_lines, reason = "one table of cases")] +fn data_open_tests(seed: &[u8; 32]) -> Vec { + let mut stream = Stream::new(seed, "data-blob-open"); + let object = DataContext::draw(&mut stream); + let other: [u8; 32] = stream.bytes(); + let other_16: [u8; 16] = stream.bytes(); + let random_id: [u8; 32] = stream.bytes(); + let nonce: [u8; 24] = stream.bytes(); + let mut random = vec![0u8; 300]; + stream.fill_bytes(&mut random); + let chunk = text(2_000); + let key = object.chunk_key(); + let id = object.keyed_id(&chunk); + let compressed = encode_chunk(&chunk, ORDINARY); + assert_eq!(compressed[0], 1, "text is compressed"); + let frame = zstd_frame::encode(&chunk, Bent::No); + let raw = inner::inner(0, &chunk); + + // Seals `inner` with the object's own key under the AAD for `blob_id`. + let seal = + |blob_id: &[u8; 32], inner: &[u8]| cx::seal(&key, &object.aad(blob_id), inner, &nonce); + let open = |class, count, blob_id: [u8; 32], plain_len, sealed| Open { + object: &object, + class, + count, + blob_id, + plain_len, + sealed, + }; + // A keyed chunk of a two-chunk object whose inner plaintext is `inner`. + let keyed = |inner: &[u8]| open(ORDINARY, 2, id, chunk.len(), seal(&id, inner)); + let good = seal(&id, &compressed); + let with_aad = |aad: Vec| { + open( + ORDINARY, + 2, + id, + chunk.len(), + cx::seal(&key, &aad, &compressed, &nonce), + ) + }; + let o = &object; + + let mut longer = raw.clone(); + longer.push(0); + let mut bad_pad = raw.clone(); + let last = bad_pad.len() - 1; + bad_pad[last] = 1; + let checksum = inner::inner(1, &zstd_frame::encode(&chunk, Bent::Checksum)); + let over_declared = inner::inner( + 1, + &zstd_frame::frame(&Header::declaring(10), &[Block::Raw(chunk[..11].to_vec())]), + ); + let other_id = object.keyed_id(b"another chunk"); + let random_id_of_raw = seal(&random_id, &inner::inner(0, &random)); + let mut zero_nonce = good.clone(); + zero_nonce[..24].fill(0); + let secret_frame = seal(&random_id, &compressed); + let secret_bad_frame = seal(&random_id, &checksum); + + let ok = Some(chunk.as_slice()); + let data_open = "DataBlobOpen"; + #[rustfmt::skip] + let tests = vec![ + keyed(&compressed).case("a compressed chunk of a two-chunk object", &[data_open, "KeyedBlobId"], "Ok", ok), + keyed(&raw).case("a raw chunk of a two-chunk object", &[data_open, "KeyedBlobId"], "Ok", ok), + open(ORDINARY, 1, random_id, 300, random_id_of_raw.clone()).case("the one chunk of a single-chunk object, random ID", &[data_open, "RandomBlobId"], "Ok", Some(&random)), + open(SECRET, 3, random_id, 2_000, seal(&random_id, &raw)).case("a chunk of a secret object, random ID", &[data_open, "RandomBlobId"], "Ok", ok), + with_aad(data_aad(&other_16, 0x01, &o.object_id, &o.dek_id, &id)).case("sealed under another vault's AAD", &["AadBinding"], "Decrypt", None), + with_aad(data_aad(&o.vault_id, 0x01, &other_16, &o.dek_id, &id)).case("sealed under another object's AAD", &["AadBinding"], "Decrypt", None), + with_aad(data_aad(&o.vault_id, 0x01, &o.object_id, &other_16, &id)).case("sealed under another DEK ID's AAD", &["AadBinding"], "Decrypt", None), + with_aad(data_aad(&o.vault_id, 0x01, &o.object_id, &o.dek_id, &other_id)).case("sealed under another blob ID's AAD", &["AadBinding"], "Decrypt", None), + with_aad(data_aad(&o.vault_id, 0x02, &o.object_id, &o.dek_id, &id)).case("sealed with kind byte 0x02", &["AadBinding"], "Decrypt", None), + with_aad(cx::aad(labels::full("aad", "blob-meta"), &[&o.vault_id, &[0x01], &o.object_id, &o.dek_id, &id])).case("sealed under the blob-meta label", &["AadBinding"], "Decrypt", None), + open(ORDINARY, 2, id, chunk.len(), cx::seal(&other, &object.aad(&id), &compressed, &nonce)).case("sealed under another key", &["AadBinding"], "Decrypt", None), + open(ORDINARY, 2, other_id, chunk.len(), seal(&other_id, &compressed)).case("the blob ID of another chunk", &["BlobIdBinding"], "Binding", None), + open(ORDINARY, 2, random_id, 300, random_id_of_raw).case("a random blob ID in a two-chunk object", &["BlobIdBinding"], "Binding", None), + keyed(&with(&raw, 1, 1)).case("rsv 1", &["BlobInner"], "Padding", None), + keyed(&with(&raw, 0, 2)).case("comp 2", &["BlobInner"], "Padding", None), + keyed(&bad_pad).case("a pad byte not zero", &["BlobInner"], "Padding", None), + keyed(&longer).case("one byte past the Padmé length", &["BlobInner"], "Padding", None), + keyed(&header(0, 0, u32::try_from(MIB).expect("small") + 1)).case("payload_len 2^20 + 1", &["BlobInner"], "Limit", None), + open(SECRET, 3, random_id, 2_000, secret_frame).case("a secret object's chunk with comp 1", &["SecretRaw"], "Padding", None), + open(SECRET, 3, random_id, 2_000, secret_bad_frame).case("a secret object's chunk with comp 1 and a bad frame: comp is checked first", &["SecretRaw", "CheckOrder"], "Padding", None), + keyed(&checksum).case("a frame with a content checksum", &["BlobFrame"], "Decompress", None), + keyed(&over_declared).case("a frame holding more than it declares", &["BlobFrame"], "Decompress", None), + open(ORDINARY, 2, id, chunk.len() + 1, good.clone()).case("plain_len one more than the frame declares", &["BlobFrame"], "Decompress", None), + open(ORDINARY, 2, id, chunk.len() + 1, seal(&id, &raw)).case("a raw payload one byte shorter than plain_len", &["BlobFrame"], "Decompress", None), + open(ORDINARY, 2, other_id, chunk.len(), seal(&other_id, &checksum)).case("a bad frame and a wrong blob ID: the frame is checked first", &["BlobFrame", "CheckOrder"], "Decompress", None), + open(ORDINARY, 2, other_id, chunk.len() + 1, seal(&other_id, &raw)).case("a raw payload one byte shorter than plain_len and a wrong blob ID: the length is checked first", &["BlobFrame", "CheckOrder"], "Decompress", None), + open(ORDINARY, 2, id, MIB + 1, seal(&id, &frame)).case("plain_len 2^20 + 1 is refused before decryption", &["PlainLenCap", "CheckOrder"], "Decompress", None), + open(ORDINARY, 2, id, chunk.len(), good[..71].to_vec()).case("71 bytes, one short of a seal", &["SealShape"], "Truncated", None), + open(ORDINARY, 2, id, chunk.len(), zero_nonce).case("an all-zero nonce", &["SealShape"], "ZeroValue", None), + ]; + tests +} + +// ---------------------------------------------------------------------------------------------- +// Meta blobs (FS-57) + +/// A meta blob's kind byte and the label of its key (FS-38, FS-57). +const META_KINDS: [(u8, &str); 5] = [ + (0x03, "index-key"), + (0x04, "key-table-key"), + (0x05, "location-key"), + (0x06, "pack-table-key"), + (0x08, "location-key"), +]; + +/// `K_kind_e = KDF(KEK_e, -, label, vault_id ‖ u32be(e))`. +fn meta_key(kek: &[u8; 32], vault_id: &[u8; 16], kind: u8, epoch: u32) -> [u8; 32] { + let (_, purpose) = META_KINDS + .iter() + .find(|(code, _)| *code == kind) + .expect("a meta kind"); + let context = [&vault_id[..], &epoch.to_be_bytes()].concat(); + cx::kdf(kek, None, labels::full("kdf", purpose), &context) +} + +fn meta_aad(vault_id: &[u8; 16], kind: u8, epoch: u32, blob_id: &[u8; 32]) -> Vec { + cx::aad( + labels::full("aad", "blob-meta"), + &[vault_id, &[kind], &epoch.to_be_bytes(), blob_id], + ) +} + +fn meta_inputs( + kek: &[u8; 32], + vault_id: &[u8; 16], + kind: u8, + epoch: u32, + blob_id: &[u8; 32], +) -> Vec<(&'static str, Input)> { + vec![ + ("kek", Input::bytes(kek)), + ("vaultId", Input::bytes(vault_id)), + ("kind", Input::Int(i64::from(kind))), + ("epoch", Input::Int(i64::from(epoch))), + ("blobId", Input::bytes(blob_id)), + ] +} + +fn meta_tests(seed: &[u8; 32]) -> Vec { + let mut stream = Stream::new(seed, "meta-blob"); + let kek: [u8; 32] = stream.bytes(); + let other_kek: [u8; 32] = stream.bytes(); + let vault_id: [u8; 16] = stream.bytes(); + let other_vault: [u8; 16] = stream.bytes(); + let epoch = 3; + // A small CBOR map, `{1: h'00010203'}`, standing for a tree node. + let cbor = [0xa1, 0x01, 0x44, 0x00, 0x01, 0x02, 0x03]; + let comments = [ + "a path-index node", + "a key-table node", + "a location node", + "a pack-table node", + "a GC-candidate node, under the location key", + ]; + let mut tests: Vec = META_KINDS + .iter() + .zip(comments) + .map(|((kind, _), comment)| { + let blob_id: [u8; 32] = stream.bytes(); + let rand: [u8; 32] = stream.bytes(); + let key = meta_key(&kek, &vault_id, *kind, epoch); + let aad = meta_aad(&vault_id, *kind, epoch, &blob_id); + let nonce = cx::hedged_nonce(&key, &aad, &cbor, &rand); + let mut inputs = meta_inputs(&kek, &vault_id, *kind, epoch, &blob_id); + inputs.extend([("cbor", Input::bytes(&cbor)), ("rand", Input::bytes(&rand))]); + TestCase::new(comment, &["MetaBlob"], "Ok", inputs).with_outputs(vec![ + ("nonce", Input::bytes(&nonce)), + ("sealed", Input::Bytes(cx::seal(&key, &aad, &cbor, &nonce))), + ]) + }) + .collect(); + + let blob_id: [u8; 32] = stream.bytes(); + let other_id: [u8; 32] = stream.bytes(); + let nonce: [u8; 24] = stream.bytes(); + let location = 0x05; + let key = meta_key(&kek, &vault_id, location, epoch); + let sealed = cx::seal( + &key, + &meta_aad(&vault_id, location, epoch, &blob_id), + &cbor, + &nonce, + ); + let open_bytes = |comment, + flag, + expect, + kek: &[u8; 32], + vault: &[u8; 16], + kind, + epoch, + blob_id: &[u8; 32], + sealed: &[u8]| { + let mut inputs = meta_inputs(kek, vault, kind, epoch, blob_id); + inputs.push(("sealed", Input::bytes(sealed))); + let test = TestCase::new(comment, &[flag], expect, inputs); + if expect == "Ok" { + test.with_outputs(vec![("cbor", Input::bytes(&cbor))]) + } else { + test + } + }; + let open = |comment, expect, kek: &[u8; 32], vault: &[u8; 16], kind, epoch, blob_id| { + open_bytes( + comment, + "MetaBlobOpen", + expect, + kek, + vault, + kind, + epoch, + blob_id, + &sealed, + ) + }; + let mut zero_nonce = sealed.clone(); + zero_nonce[..24].fill(0); + #[rustfmt::skip] + let opens = [ + open("a location node opens", "Ok", &kek, &vault_id, location, epoch, &blob_id), + open("opened as a GC-candidate node: same key, other kind byte", "Decrypt", &kek, &vault_id, 0x08, epoch, &blob_id), + open("opened under another epoch", "Decrypt", &kek, &vault_id, location, epoch + 1, &blob_id), + open("opened under another blob ID", "Decrypt", &kek, &vault_id, location, epoch, &other_id), + open("opened in another vault", "Decrypt", &kek, &other_vault, location, epoch, &blob_id), + open("opened with another epoch's KEK", "Decrypt", &other_kek, &vault_id, location, epoch, &blob_id), + open_bytes("71 bytes, one short of a seal", "SealShape", "Truncated", &kek, &vault_id, location, epoch, &blob_id, &sealed[..71]), + open_bytes("an all-zero nonce", "SealShape", "ZeroValue", &kek, &vault_id, location, epoch, &blob_id, &zero_nonce), + ]; + tests.extend(opens); + tests +} + +/// Every flag of the set, with the rules and threats it cites (FS-94). +#[allow(clippy::too_many_lines, reason = "one table of notes")] +fn notes() -> Vec<(&'static str, &'static [&'static str], &'static str)> { + vec![ + ( + "SmallFile", + &["FS-52", "M-39"], + "A file no longer than the 64 KiB minimum is one chunk; an empty file has none. `lengths` lists every chunk.", + ), + ( + "CutPoints", + &["FS-52", "M-39", "T-84"], + "FastCDC 2020 at level 2 with the vault's gear table: strict mask below 256 KiB, loose to 1 MiB, a cut before the matching byte, never at an odd last byte.", + ), + ( + "CutEdges", + &["FS-52", "M-39", "T-84"], + "Files found by search so a cut sits on an edge of the rule: at the minimum and one past it, at the switch from the strict to the loose mask (a loose-only match at 2⌊center/2⌋ cuts, one at 2⌊center/2⌋ − 1 does not), at the last position tested, an odd last byte that would match if it were tested, and a repeated pattern that is cut only at the maximum. The generator checks each with its one-byte chunker.", + ), + ( + "KeyedGear", + &["FS-52", "M-39", "T-84"], + "Another chunker_seed gives another gear table and other boundaries for the same data.", + ), + ( + "SecretFixed", + &["FS-52", "T-84"], + "A secret-class object is cut into 1 MiB chunks and a shorter last one, from its length alone, with no gear-table lookup; an empty one has none.", + ), + ( + "Padme", + &["FS-54", "M-39", "T-84"], + "padme(L) for L ≥ 2 rounds L up to a multiple of 2^(E−S); below 2 it is L.", + ), + ( + "InnerOk", + &["FS-54", "M-39"], + "A well-formed inner plaintext: comp 0 or 1, rsv 0, zero pad, length padme(6 + payload_len).", + ), + ( + "InnerPadding", + &["FS-54", "T-39"], + "Unknown comp, non-zero rsv or pad, or a length other than padme(6 + payload_len), is Padding.", + ), + ( + "InnerLimit", + &["FS-54", "FS-11", "T-39"], + "payload_len up to 2^20 is allowed; above it is Limit, checked before the length.", + ), + ( + "CheckOrder", + &["FS-93", "FS-53", "FS-54", "T-39"], + "Two faults at once: the first check in the order of the rules decides.", + ), + ( + "Compress", + &["FS-53", "T-40"], + "One zstd frame at level 3 with its content size, no checksum, no dictionary ID, window ≤ 2^20; equal output is only expected from the zstd version in the header.", + ), + ( + "StoreRaw", + &["FS-53", "T-40"], + "The frame is kept only if 16 × frame ≤ 15 × chunk; otherwise the chunk is stored with comp 0.", + ), + ( + "SecretRaw", + &["FS-53", "FS-55", "T-40"], + "Chunks of secret-class objects are never compressed; a secret chunk with comp 1 is Padding.", + ), + ( + "FrameOk", + &["FS-53", "T-39"], + "Frames FS-53 allows decode to exactly plain_len bytes with any zstd version; raw and RLE frames are built by hand.", + ), + ( + "FrameRejected", + &["FS-53", "T-39"], + "A frame that is not exactly one frame with content size plain_len in the shortest field that holds it, no checksum, no dictionary ID, the unused and reserved bits clear and a window ≤ 2^20, or whose content differs from its declaration, is Decompress.", + ), + ( + "PlainLenCap", + &["FS-53", "FS-11", "T-39"], + "plain_len may be 2^20; above that the chunk is Decompress before it is decrypted or decoded.", + ), + ( + "DataBlobSeal", + &["FS-55", "FS-29", "M-8", "T-35"], + "Seal(K_chunk, aad, inner, hedged nonce) with the AAD of FS-55; K_chunk and K_blobid from the DEK and dek_salt (FS-38).", + ), + ( + "KeyedBlobId", + &["FS-55", "FS-56", "T-85"], + "In an ordinary object of two or more chunks, blob_id = MAC(K_blobid, chunk), checked after opening.", + ), + ( + "RandomBlobId", + &["FS-55", "T-85"], + "In a single-chunk or secret-class object, blob_id is random and not recomputed.", + ), + ( + "DataBlobOpen", + &["FS-55", "FS-56", "M-8"], + "A data blob opens to its chunk.", + ), + ( + "AadBinding", + &["FS-55", "M-8", "T-35"], + "A blob sealed under an AAD naming another vault, object, DEK, blob ID, kind or label, or under another key, is Decrypt.", + ), + ( + "BlobIdBinding", + &["FS-56", "T-85"], + "A blob that opens but whose chunk does not MAC to its keyed blob ID is Binding.", + ), + ( + "BlobInner", + &["FS-54", "T-39"], + "A data blob whose inner plaintext is malformed is Padding, or Limit for payload_len over 2^20.", + ), + ( + "BlobFrame", + &["FS-53", "T-39"], + "A data blob whose payload does not decode to exactly plain_len bytes is Decompress.", + ), + ( + "SealShape", + &["FS-28", "FS-03", "M-9"], + "Input too short to be a seal is Truncated; an all-zero nonce is ZeroValue.", + ), + ( + "MetaBlob", + &["FS-57", "FS-38", "M-8"], + "Seal(K_kind_e, aad, CBOR, hedged nonce) with the AAD of FS-57; GC-candidate nodes use the location key.", + ), + ( + "MetaBlobOpen", + &["FS-57", "M-8", "T-35"], + "A meta blob opened with another kind byte, epoch, blob ID, vault or KEK is Decrypt.", + ), + ] +} + +/// TV-07. +pub(crate) fn set() -> VectorSet { + let seed = seed(); + let version = zstd_frame::version(); + assert_eq!(version, "1.5.7", "FS-53 pins zstd 1.5.7"); + VectorSet { + file: "tv-07-chunk-blob.json", + set: "TV-07", + structure: "chunk-blob", + seed: Some(seed), + extra: vec![("zstd", version)], + notes: notes(), + groups: vec![ + ("Chunking", chunking_tests(&seed)), + ("Padme", padme_tests()), + ("InnerDecode", inner_tests(&seed)), + ("Compress", compress_tests(&seed)), + ("Decompress", decompress_tests()), + ("DataBlobSeal", data_seal_tests(&seed)), + ("DataBlobOpen", data_open_tests(&seed)), + ("MetaBlob", meta_tests(&seed)), + ], + } +} diff --git a/tests/test-vectors/gen/src/vector_set.rs b/tests/test-vectors/gen/src/vector_set.rs index d14c1fa..6df0166 100644 --- a/tests/test-vectors/gen/src/vector_set.rs +++ b/tests/test-vectors/gen/src/vector_set.rs @@ -4,7 +4,7 @@ use std::collections::BTreeSet; use crate::json::Json; use crate::test_case::TestCase; -use crate::{tv02, tv03, tv04, tv05, tv17}; +use crate::{tv02, tv03, tv04, tv05, tv07, tv17}; /// What the generator writes into the `generator` field of a set with no randomness. const GENERATOR: &str = "hand-written (crypthix-vector-gen reproduces it)"; @@ -111,6 +111,7 @@ pub fn sets() -> Vec { tv03::set(), tv04::set(), tv05::set(), + tv07::set(), tv17::set(), ] } diff --git a/tests/test-vectors/gen/src/zstd_frame.rs b/tests/test-vectors/gen/src/zstd_frame.rs new file mode 100644 index 0000000..734c222 --- /dev/null +++ b/tests/test-vectors/gen/src/zstd_frame.rs @@ -0,0 +1,327 @@ +//! zstd frames for TV-07: hand-built raw and RLE frames (RFC 8878), which the negative vectors +//! bend one field at a time, and frames made by the zstd encoder (`zstd-safe`, the version the +//! set's header names) for the encoder-equality and valid-frame cases. + +use zstd_safe::{CCtx, CParameter}; + +/// The magic number of a zstd frame, little-endian (RFC 8878 section 3.1.1). +const MAGIC: [u8; 4] = 0xFD2F_B528_u32.to_le_bytes(); + +/// The magic number of a skippable frame (RFC 8878 section 3.1.2). +const SKIPPABLE_MAGIC: [u8; 4] = 0x184D_2A50_u32.to_le_bytes(); + +/// The largest block, 128 KiB (RFC 8878 section 3.1.1.2.4). +pub(crate) const MAX_BLOCK: usize = 128 * 1024; + +/// The unused bit of the frame header descriptor (RFC 8878 section 3.1.1.1.1). +pub(crate) const UNUSED_BIT: u8 = 0x10; + +/// The reserved bit of the frame header descriptor. +pub(crate) const RESERVED_BIT: u8 = 0x08; + +/// One block of a hand-built frame. +#[derive(Clone, Debug)] +pub(crate) enum Block { + /// A raw block: its bytes as they are. + Raw(Vec), + /// An RLE block: one byte repeated. + Rle(u8, usize), + /// A compressed block with the given content, as [`literals_only`] builds it. + Compressed(Vec), + /// A block of the reserved type 3, which no decoder may accept, with the given content. + Reserved(Vec), +} + +/// The frame header fields a vector may set (RFC 8878 section 3.1.1.1). +#[derive(Clone, Copy, Debug)] +pub(crate) struct Header { + /// Single segment: no window descriptor, the window is the content size. + pub(crate) single_segment: bool, + /// The window descriptor byte, when not single segment. + pub(crate) window: u8, + /// The declared content size, if any. + pub(crate) content_size: Option, + /// The content-checksum flag; four checksum bytes follow the last block. + pub(crate) checksum: bool, + /// A one-byte dictionary ID. + pub(crate) dict_id: Option, + /// Descriptor bits FS-53 forbids, set as given: [`UNUSED_BIT`], which libzstd ignores and + /// never sets, and [`RESERVED_BIT`]. + pub(crate) stray_bits: u8, + /// The content-size flag, if not the shortest field that holds the size. + pub(crate) fcs_flag: Option, +} + +impl Header { + /// A single-segment header declaring `content_size`, as FS-53 frames are. + pub(crate) const fn declaring(content_size: u64) -> Self { + Self { + single_segment: true, + window: 0, + content_size: Some(content_size), + checksum: false, + dict_id: None, + stray_bits: 0, + fcs_flag: None, + } + } + + /// The window descriptor of `2^log` bytes: exponent `log − 10`, mantissa 0. + pub(crate) const fn window_of(log: u8) -> u8 { + (log - 10) << 3 + } +} + +/// A frame with `header` and `blocks`, the last one marked as such. +pub(crate) fn frame(header: &Header, blocks: &[Block]) -> Vec { + let mut out = MAGIC.to_vec(); + let (fcs_flag, fcs) = match header.content_size { + None => (0, Vec::new()), + Some(size) => { + // The shortest field, as libzstd writes it, unless the header names another. + let shortest = match size { + 0..256 if header.single_segment => 0, + 256..65_792 => 1, + 0..0xFFFF_FFFF => 2, + _ => 3, + }; + let flag = header.fcs_flag.unwrap_or(shortest); + let field = match flag { + 0 => vec![u8::try_from(size).expect("below 256")], + 1 => { + let value = u16::try_from(size - 256).expect("256 to 65,791"); + value.to_le_bytes().to_vec() + } + 2 => u32::try_from(size) + .expect("below 2^32") + .to_le_bytes() + .to_vec(), + _ => size.to_le_bytes().to_vec(), + }; + (flag, field) + } + }; + let mut descriptor = fcs_flag << 6; + if header.single_segment { + descriptor |= 0x20; + } + descriptor |= header.stray_bits; + if header.checksum { + descriptor |= 0x04; + } + if header.dict_id.is_some() { + descriptor |= 0x01; + } + out.push(descriptor); + if !header.single_segment { + out.push(header.window); + } + if let Some(id) = header.dict_id { + out.push(id); + } + out.extend_from_slice(&fcs); + for (index, block) in blocks.iter().enumerate() { + let last = u32::from(index + 1 == blocks.len()); + let (kind, size, body) = match block { + Block::Raw(bytes) => (0, bytes.len(), bytes.clone()), + Block::Rle(byte, len) => (1, *len, vec![*byte]), + Block::Compressed(content) => (2, content.len(), content.clone()), + Block::Reserved(content) => (3, content.len(), content.clone()), + }; + let size = u32::try_from(size).expect("a block under 2^21 bytes"); + let block_header = last | (kind << 1) | (size << 3); + out.extend_from_slice(&block_header.to_le_bytes()[..3]); + out.extend_from_slice(&body); + } + if header.checksum { + // Not the real XXH64 checksum: a reader must refuse the flag before it gets that far. + out.extend_from_slice(&[0; 4]); + } + out +} + +/// The content of a compressed block that holds `literals` as raw literals and no sequences +/// (RFC 8878 section 3.1.1.3): a three-byte literals section header (`Raw_Literals_Block`, +/// `Size_Format` 3, a 20-bit `Regenerated_Size`), the literals, and a `Number_of_Sequences` +/// byte of 0. It decodes to `literals` and is 4 bytes longer. +pub(crate) fn literals_only(literals: &[u8]) -> Vec { + let size = u32::try_from(literals.len()).expect("under 2^20 bytes"); + assert!(size < 1 << 20, "a 20-bit Regenerated_Size"); + let mut content = vec![ + 0b1100 | u8::try_from((size & 0xF) << 4).expect("four bits"), + u8::try_from((size >> 4) & 0xFF).expect("a byte"), + u8::try_from(size >> 12).expect("a byte"), + ]; + content.extend_from_slice(literals); + content.push(0); + content +} + +/// A single-segment frame of raw blocks holding `content`; an empty content gets one empty +/// block. +pub(crate) fn raw_frame(content: &[u8]) -> Vec { + let mut blocks: Vec = content + .chunks(MAX_BLOCK) + .map(|piece| Block::Raw(piece.to_vec())) + .collect(); + if blocks.is_empty() { + blocks.push(Block::Raw(Vec::new())); + } + frame(&Header::declaring(content.len() as u64), &blocks) +} + +/// A single-segment frame of RLE blocks holding `len` copies of `byte`. +pub(crate) fn rle_frame(byte: u8, len: usize) -> Vec { + let mut blocks = Vec::new(); + let mut left = len; + while left > 0 { + let size = left.min(MAX_BLOCK); + blocks.push(Block::Rle(byte, size)); + left -= size; + } + frame(&Header::declaring(len as u64), &blocks) +} + +/// A skippable frame carrying `data`. +pub(crate) fn skippable(data: &[u8]) -> Vec { + let mut out = SKIPPABLE_MAGIC.to_vec(); + let len = u32::try_from(data.len()).expect("short"); + out.extend_from_slice(&len.to_le_bytes()); + out.extend_from_slice(data); + out +} + +/// The zstd encoder's frame of `data` with the parameters of FS-53 (level 3, content size, no +/// checksum, no dictionary ID, window log 20), or with the checksum on and the content size +/// off when `bent` asks, to make real frames FS-53 forbids. +pub(crate) fn encode(data: &[u8], bent: Bent) -> Vec { + let mut cctx = CCtx::create(); + let parameters = [ + CParameter::CompressionLevel(3), + CParameter::ContentSizeFlag(bent != Bent::NoContentSize), + CParameter::ChecksumFlag(bent == Bent::Checksum), + CParameter::DictIdFlag(false), + CParameter::WindowLog(20), + ]; + for parameter in parameters { + cctx.set_parameter(parameter).expect("a valid parameter"); + } + let mut out = vec![0u8; zstd_safe::compress_bound(data.len())]; + let written = cctx.compress2(&mut out[..], data).expect("compresses"); + out.truncate(written); + out +} + +/// Which FS-53 parameter [`encode`] breaks, if any. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Bent { + /// The parameters of FS-53. + No, + /// With the content checksum. + Checksum, + /// Without the declared content size. + NoContentSize, +} + +/// The zstd version the generator links, which the set's header records. +pub(crate) fn version() -> &'static str { + zstd_safe::version_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn decode(frame: &[u8], capacity: usize) -> Result, usize> { + let mut out = vec![0u8; capacity]; + let written = zstd_safe::decompress(&mut out[..], frame)?; + out.truncate(written); + Ok(out) + } + + #[test] + fn hand_built_frames_decode_with_zstd() { + assert_eq!(decode(&raw_frame(b"hello"), 5), Ok(b"hello".to_vec())); + assert_eq!(decode(&raw_frame(b""), 0), Ok(Vec::new())); + assert_eq!(decode(&rle_frame(7, 300), 300), Ok(vec![7; 300])); + let big = rle_frame(0, 1 << 20); + assert_eq!(decode(&big, 1 << 20), Ok(vec![0; 1 << 20])); + let windowed = Header { + single_segment: false, + window: Header::window_of(20), + ..Header::declaring(5) + }; + let windowed = frame(&windowed, &[Block::Raw(b"hello".to_vec())]); + assert_eq!(decode(&windowed, 5), Ok(b"hello".to_vec())); + // libzstd 1.5.7 decodes what FS-53 refuses: the unused bit, a wider content size. + let hello = [Block::Raw(b"hello".to_vec())]; + for header in [ + Header { + stray_bits: UNUSED_BIT, + ..Header::declaring(5) + }, + Header { + fcs_flag: Some(2), + ..Header::declaring(5) + }, + Header { + fcs_flag: Some(3), + ..Header::declaring(5) + }, + ] { + assert_eq!(decode(&frame(&header, &hello), 5), Ok(b"hello".to_vec())); + } + } + + #[test] + fn blocks_of_exactly_128_kib_decode() { + let raw = raw_frame(&vec![7; MAX_BLOCK]); + assert_eq!(raw.len(), 4 + 1 + 4 + 3 + MAX_BLOCK, "one raw block"); + assert_eq!(decode(&raw, MAX_BLOCK), Ok(vec![7; MAX_BLOCK])); + let literals = vec![7; MAX_BLOCK - 4]; + let content = literals_only(&literals); + assert_eq!(content.len(), MAX_BLOCK); + let header = Header { + single_segment: false, + window: Header::window_of(17), + ..Header::declaring(literals.len() as u64) + }; + let compressed = frame(&header, &[Block::Compressed(content)]); + assert_eq!(decode(&compressed, literals.len()), Ok(literals.clone())); + // The block may be no larger than the window: here 2^17 bytes. With a single segment the + // window is the content size, 4 bytes smaller than the block, and zstd refuses it. + let single = frame( + &Header::declaring(literals.len() as u64), + &[Block::Compressed(literals_only(&literals))], + ); + assert!(decode(&single, literals.len()).is_err()); + } + + #[test] + fn a_reserved_block_fails() { + let reserved = frame(&Header::declaring(5), &[Block::Reserved(b"hello".to_vec())]); + assert!(decode(&reserved, 5).is_err()); + } + + #[test] + fn content_sizes_take_the_shortest_field() { + // Magic, descriptor, field, a three-byte block header. + assert_eq!(raw_frame(&[0; 255]).len(), 4 + 1 + 1 + 3 + 255); + assert_eq!(raw_frame(&[0; 256]).len(), 4 + 1 + 2 + 3 + 256); + assert_eq!(rle_frame(0, 65_791).len(), 4 + 1 + 2 + 3 + 1); + assert_eq!(rle_frame(0, 65_792).len(), 4 + 1 + 4 + 3 + 1); + } + + #[test] + fn encoder_frames_round_trip() { + let data = b"abcabcabc".repeat(100); + for bent in [Bent::No, Bent::Checksum, Bent::NoContentSize] { + assert_eq!(decode(&encode(&data, bent), data.len()), Ok(data.clone())); + } + } + + #[test] + fn the_pinned_version() { + assert_eq!(version(), "1.5.7"); + } +} From d69d09ffa26c7ceb8db17bafe42910c8c307fd74 Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 14:54:06 +0530 Subject: [PATCH 04/15] test(fuzz): add inner_plaintext, decompress, data_blob_open and chunker fuzz targets --- tests/Cargo.lock | 44 +++ tests/README.md | 4 +- tests/fuzz/Cargo.toml | 30 +- tests/fuzz/dicts/zstd.dict | 26 ++ tests/fuzz/fuzz_targets/chunker.rs | 5 + tests/fuzz/fuzz_targets/data_blob_open.rs | 5 + tests/fuzz/fuzz_targets/decompress.rs | 5 + tests/fuzz/fuzz_targets/inner_plaintext.rs | 5 + tests/fuzz/harness/Cargo.toml | 3 + tests/fuzz/harness/src/chunker.rs | 297 ++++++++++++++++++ tests/fuzz/harness/src/data_blob_open.rs | 258 +++++++++++++++ tests/fuzz/harness/src/decompress.rs | 121 +++++++ tests/fuzz/harness/src/inner_plaintext.rs | 39 +++ tests/fuzz/harness/src/lib.rs | 14 +- tests/fuzz/harness/src/targets.rs | 7 +- tests/fuzz/regressions/chunker/.gitkeep | 0 .../fuzz/regressions/data_blob_open/.gitkeep | 0 tests/fuzz/regressions/decompress/.gitkeep | 0 .../fuzz/regressions/inner_plaintext/.gitkeep | 0 xtask/src/side.rs | 18 +- 20 files changed, 873 insertions(+), 8 deletions(-) create mode 100644 tests/fuzz/dicts/zstd.dict create mode 100644 tests/fuzz/fuzz_targets/chunker.rs create mode 100644 tests/fuzz/fuzz_targets/data_blob_open.rs create mode 100644 tests/fuzz/fuzz_targets/decompress.rs create mode 100644 tests/fuzz/fuzz_targets/inner_plaintext.rs create mode 100644 tests/fuzz/harness/src/chunker.rs create mode 100644 tests/fuzz/harness/src/data_blob_open.rs create mode 100644 tests/fuzz/harness/src/decompress.rs create mode 100644 tests/fuzz/harness/src/inner_plaintext.rs create mode 100644 tests/fuzz/regressions/chunker/.gitkeep create mode 100644 tests/fuzz/regressions/data_blob_open/.gitkeep create mode 100644 tests/fuzz/regressions/decompress/.gitkeep create mode 100644 tests/fuzz/regressions/inner_plaintext/.gitkeep diff --git a/tests/Cargo.lock b/tests/Cargo.lock index feea2be..3a36df7 100644 --- a/tests/Cargo.lock +++ b/tests/Cargo.lock @@ -234,6 +234,15 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypthix-core" +version = "0.0.0" +dependencies = [ + "crypthix-crypto", + "crypthix-types", + "zstd-safe", +] + [[package]] name = "crypthix-crypto" version = "0.0.0" @@ -266,12 +275,15 @@ name = "crypthix-fuzz-harness" version = "0.0.0" dependencies = [ "arbitrary", + "crypthix-core", "crypthix-crypto", "crypthix-types", "crypthix-vector-gen", "curve25519-dalek", "ed25519-dalek", + "fastcdc", "minicbor", + "zstd-safe", ] [[package]] @@ -294,6 +306,7 @@ dependencies = [ "jsonschema", "serde_json", "sha2", + "zstd-safe", ] [[package]] @@ -417,6 +430,12 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "fastcdc" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0431c3132902a1bed6fe77dcfa5d03844e083f263b81288246a2d43dd7d4b2ad" + [[package]] name = "fiat-crypto" version = "0.3.0" @@ -806,6 +825,12 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "poly1305" version = "0.9.1" @@ -1298,3 +1323,22 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zstd-safe" +version = "8.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.2+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/tests/README.md b/tests/README.md index 0f2becd..69d3e20 100644 --- a/tests/README.md +++ b/tests/README.md @@ -9,7 +9,7 @@ Cross-crate tests and test tooling live here. Unit tests stay inside each crate, | `integration/` | Cross-crate tests (from Phase 1) | | `bench/`, `demo/` | MVP benchmarks against gocryptfs and the scripted demo (Phase 2) | -`tests/Cargo.toml` makes this folder its own Cargo workspace, outside the main one. That keeps cargo-fuzz's nightly toolchain and C++ libFuzzer out of normal builds, and keeps the `test-rng` and `vectors` features of `crypthix-crypto`, which the generator and the fuzz harness use, from being unified into a release build (format spec FS-01; `cargo xtask check-features` guards the main workspace). Its lints copy the root `[workspace.lints]`; keep the two in sync. `tests/deny.toml` is the root `deny.toml` plus the two licence exceptions only test tooling needs (libFuzzer's NCSA, minicbor's Blue Oak); a test keeps the two files in sync. The generator is the one crate besides `crypthix-crypto` that may use `blake3`, `hkdf`, `sha2` and `chacha20poly1305` directly: it reimplements format spec section 7 to compute TV-04 and TV-05 independently. +`tests/Cargo.toml` makes this folder its own Cargo workspace, outside the main one. That keeps cargo-fuzz's nightly toolchain and C++ libFuzzer out of normal builds, and keeps the `test-rng` and `vectors` features of `crypthix-crypto`, which the generator and the fuzz harness use, from being unified into a release build (format spec FS-01; `cargo xtask check-features` guards the main workspace). Its lints copy the root `[workspace.lints]`; keep the two in sync. `tests/deny.toml` is the root `deny.toml` plus the two licence exceptions only test tooling needs (libFuzzer's NCSA, minicbor's Blue Oak); a test keeps the two files in sync. The generator is the one crate besides `crypthix-crypto` that may use `blake3`, `hkdf`, `sha2` and `chacha20poly1305` directly: it reimplements format spec section 7 to compute TV-04 and TV-05 independently. With `crypthix-core` and the fuzz harness it is also one of the three crates that may use `zstd-safe`: TV-07 builds its frames by hand and takes only encoder output from zstd. ```bash cargo xtask test-extra # on stable: vector check, schema, external vectors, fuzz replay, cargo-deny @@ -20,7 +20,7 @@ cargo xtask fuzz cbor_differential --time 60 # fuzz one target on nightly, or ` ## Fuzzing -Targets: `preamble`, `cbor_document`, `cbor_differential`, `cbor_structured`, `store_key`, `config_toml`, `id_text`, `cx_open` (CX-AEAD open never accepts arbitrary bytes, a seal round-trips, and a flipped byte fails the commitment or the tag check that owns its region) and `verifying_key` (key parsing and strict verification compared with a second reading of FS-14 on curve25519-dalek and `verify_strict`). `cargo xtask fuzz` needs cargo-fuzz (`cargo install cargo-fuzz --locked`) and a nightly toolchain (`rustup toolchain install nightly`; set `CRYPTHIX_FUZZ_TOOLCHAIN` to pin another). It writes every vector input into `fuzz/corpus//` as a seed, reads `fuzz/regressions//` as a second corpus, and runs with the dictionaries in `fuzz/dicts/`. Builds are optimised but keep debug assertions and overflow checks (`-O -a`), with a 10 s timeout and a 64 MB allocation limit per input, so a parser that allocates for a declared length before checking it fails (FS-11). Fuzzing is supported on Linux and macOS; on Windows it is best effort. +Targets: `preamble`, `cbor_document`, `cbor_differential`, `cbor_structured`, `store_key`, `config_toml`, `id_text`, `cx_open` (CX-AEAD open never accepts arbitrary bytes, a seal round-trips, and a flipped byte fails the commitment or the tag check that owns its region) `verifying_key` (key parsing and strict verification compared with a second reading of FS-14 on curve25519-dalek and `verify_strict`), `inner_plaintext` (an accepted inner plaintext re-encodes to itself; only `Padding`, or `Limit` exactly for a well-formed header over 1 MiB), `decompress` (a 3-byte `plain_len`, then a frame: accepted exactly when it is one FS-53 frame that zstd's one-shot decoder turns into the same `plain_len` bytes; only `Decompress`), `data_blob_open` (arbitrary bytes only fail to decrypt; the input sealed as an inner plaintext under the blob's own key and AAD gets the result its stages give alone, in the order of FS-93, so a frame error or a payload of the wrong length comes before a wrong blob ID; a written chunk opens to itself and fails with a flipped byte) and `chunker` (a file of up to 2.25 MiB, past two maximum chunks, a keyed stream with the input's tail XOR-ed over all of it, repeated, so every input byte reaches the hash at every cut point, cut in memory, through a reader with input-chosen read sizes and interruptions, and by `fastcdc::v2020::cut_gear` 5.0.0 with the same gear table, which must all agree, and cut again as a secret-class object, which must give fixed 1 MiB chunks; then the tail alone the same ways at the scaled-down sizes 64, 256 and 1,024 bytes through `crypthix-core`'s hidden `scaled_for_fuzzing` constructors, where a few KiB of input reach every edge of the cut rule). `cargo xtask fuzz` needs cargo-fuzz (`cargo install cargo-fuzz --locked`) and a nightly toolchain (`rustup toolchain install nightly`; set `CRYPTHIX_FUZZ_TOOLCHAIN` to pin another). It writes every vector input into `fuzz/corpus//` as a seed, reads `fuzz/regressions//` as a second corpus, and runs with the dictionaries in `fuzz/dicts/`. Builds are optimised but keep debug assertions and overflow checks (`-O -a`), with a 10 s timeout and a 64 MB allocation limit per input, so a parser that allocates for a declared length before checking it fails (FS-11). Fuzzing is supported on Linux and macOS; on Windows it is best effort. Of the fuzz data folders, only `fuzz/dicts/` and `fuzz/regressions/` are tracked; `corpus/`, `artifacts/` and `coverage/` are local. When a target fails: diff --git a/tests/fuzz/Cargo.toml b/tests/fuzz/Cargo.toml index 70cbd3b..33723f7 100644 --- a/tests/fuzz/Cargo.toml +++ b/tests/fuzz/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "crypthix-fuzz" -description = "cargo-fuzz binaries for the crypthix-types parsers and crypthix-crypto inputs; each calls crypthix-fuzz-harness." +description = "cargo-fuzz binaries for the crypthix-types parsers and the crypthix-crypto and crypthix-core inputs; each calls crypthix-fuzz-harness." version.workspace = true edition.workspace = true rust-version.workspace = true @@ -80,3 +80,31 @@ path = "fuzz_targets/verifying_key.rs" test = false doc = false bench = false + +[[bin]] +name = "inner_plaintext" +path = "fuzz_targets/inner_plaintext.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "decompress" +path = "fuzz_targets/decompress.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "data_blob_open" +path = "fuzz_targets/data_blob_open.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "chunker" +path = "fuzz_targets/chunker.rs" +test = false +doc = false +bench = false diff --git a/tests/fuzz/dicts/zstd.dict b/tests/fuzz/dicts/zstd.dict new file mode 100644 index 0000000..c284e89 --- /dev/null +++ b/tests/fuzz/dicts/zstd.dict @@ -0,0 +1,26 @@ +# libFuzzer dictionary for the zstd frame targets (RFC 8878): magic numbers, frame header +# descriptors, window descriptors around the 1 MiB cap, block headers, and the 3-byte +# plain_len prefixes and inner-plaintext headers at the 1 MiB cap. +magic="\x28\xb5\x2f\xfd" +skippable_magic="\x50\x2a\x4d\x18" +fhd_single_fcs1="\x20" +fhd_single_fcs2="\x60" +fhd_single_fcs4="\xa0" +fhd_single_fcs8="\xe0" +fhd_windowed_fcs4="\x80" +fhd_no_fcs="\x00" +fhd_checksum="\x24" +fhd_dict_id="\x21" +fhd_reserved="\x28" +window_1mib="\x50" +window_over="\x51" +window_2mib="\x58" +block_raw_last_empty="\x01\x00\x00" +block_rle_last_128k="\x03\x00\x10" +block_compressed_last="\x05\x00\x00" +plain_len_1mib="\x10\x00\x00" +plain_len_over="\x10\x00\x01" +fcs4_1mib="\x00\x00\x10\x00" +inner_zstd="\x01\x00" +inner_payload_1mib="\x00\x10\x00\x00" +inner_payload_over="\x00\x10\x00\x01" diff --git a/tests/fuzz/fuzz_targets/chunker.rs b/tests/fuzz/fuzz_targets/chunker.rs new file mode 100644 index 0000000..240451e --- /dev/null +++ b/tests/fuzz/fuzz_targets/chunker.rs @@ -0,0 +1,5 @@ +//! Fuzz target `chunker`: see `crypthix_fuzz_harness::chunker`. + +#![no_main] + +libfuzzer_sys::fuzz_target!(|data: &[u8]| crypthix_fuzz_harness::chunker(data)); diff --git a/tests/fuzz/fuzz_targets/data_blob_open.rs b/tests/fuzz/fuzz_targets/data_blob_open.rs new file mode 100644 index 0000000..b3dfa85 --- /dev/null +++ b/tests/fuzz/fuzz_targets/data_blob_open.rs @@ -0,0 +1,5 @@ +//! Fuzz target `data_blob_open`: see `crypthix_fuzz_harness::data_blob_open`. + +#![no_main] + +libfuzzer_sys::fuzz_target!(|data: &[u8]| crypthix_fuzz_harness::data_blob_open(data)); diff --git a/tests/fuzz/fuzz_targets/decompress.rs b/tests/fuzz/fuzz_targets/decompress.rs new file mode 100644 index 0000000..ce61dc1 --- /dev/null +++ b/tests/fuzz/fuzz_targets/decompress.rs @@ -0,0 +1,5 @@ +//! Fuzz target `decompress`: see `crypthix_fuzz_harness::decompress`. + +#![no_main] + +libfuzzer_sys::fuzz_target!(|data: &[u8]| crypthix_fuzz_harness::decompress(data)); diff --git a/tests/fuzz/fuzz_targets/inner_plaintext.rs b/tests/fuzz/fuzz_targets/inner_plaintext.rs new file mode 100644 index 0000000..c6139a8 --- /dev/null +++ b/tests/fuzz/fuzz_targets/inner_plaintext.rs @@ -0,0 +1,5 @@ +//! Fuzz target `inner_plaintext`: see `crypthix_fuzz_harness::inner_plaintext`. + +#![no_main] + +libfuzzer_sys::fuzz_target!(|data: &[u8]| crypthix_fuzz_harness::inner_plaintext(data)); diff --git a/tests/fuzz/harness/Cargo.toml b/tests/fuzz/harness/Cargo.toml index 509c338..8cfded9 100644 --- a/tests/fuzz/harness/Cargo.toml +++ b/tests/fuzz/harness/Cargo.toml @@ -10,11 +10,14 @@ publish.workspace = true [dependencies] arbitrary = "1.5.0" +crypthix-core = { version = "0.0.0", path = "../../../crates/engine/core" } crypthix-crypto = { path = "../../../crates/foundation/crypto", features = ["vectors"] } crypthix-types = { version = "0.0.0", path = "../../../crates/foundation/types" } curve25519-dalek = { version = "5.0.0", default-features = false } ed25519-dalek = { version = "3.0.0", default-features = false, features = ["fast"] } +fastcdc = "5.0.0" minicbor = { version = "2.3.1", default-features = false, features = ["std", "half"] } +zstd-safe = { version = "8.2.0", default-features = false } [lints] workspace = true diff --git a/tests/fuzz/harness/src/chunker.rs b/tests/fuzz/harness/src/chunker.rs new file mode 100644 index 0000000..60e262a --- /dev/null +++ b/tests/fuzz/harness/src/chunker.rs @@ -0,0 +1,297 @@ +//! Content-defined chunking at full size and at scaled-down sizes (FS-52). +//! +//! The input sets up a file and a reader: +//! +//! | Bytes | Meaning | +//! | ------- | ---------------------------------------------------------------------------- | +//! | 0..3 | the file's length, 24-bit big-endian, at most 2.25 MiB | +//! | 3..7 | read sizes, used in turn: `0` interrupts a read, `n` reads `n × 4,099` bytes | +//! | 7..39 | the chunker seed (all zero: `[1; 32]`) | +//! | 39..55 | the vault ID (all zero: `[1; 16]`) | +//! | 55..87 | the data key: the file is its keyed XOF stream, or zeros if it is all zero | +//! | 87.. | the overlay: XOR-ed onto the whole file, repeated from its start | +//! +//! Missing bytes count as zero; a length over 2.25 MiB is cut to 2.25 MiB: just over two maximum +//! chunks and the reader's 2 MiB window, so a file still reaches a cut at the maximum twice, a +//! last chunk after it and a refill of the window, while each input runs nearly twice as fast +//! as at 4 MiB. The TV-07 chunking inputs are seeds in this form, so their 2.5, 3 and 8 MiB +//! cases are cut to their first 2.25 MiB here (still two maximum chunks of zeros or of a secret +//! file, and several content-defined cuts of the random data); a `pattern` case is a zero data +//! key with the pattern as the overlay. +//! +//! The format 0 hash is only tested from 64 KiB into a chunk and depends on the 64 bytes before +//! the position tested, so the overlay is repeated over the whole file: every input byte +//! reaches the hash at every cut point, and with a zero data key the file is the overlay +//! repeated, which the fuzzer controls entirely. The overlay is also cut on its own at the +//! scaled-down sizes of 64, 256 and 1,024 bytes, where a read size `n` reads `n` bytes and a few +//! KiB of input reach the minimum, the switch of masks, odd tails and the maximum many times. +//! +//! Every file is cut for both classes. For an ordinary object, the chunks [`Chunks`] cuts in +//! memory must be the chunks [`StreamChunker`] cuts through the reader, and the chunks +//! `fastcdc::v2020::cut_gear` 5.0.0 cuts with the same gear table, which this file rebuilds +//! from `chunker_seed` and the vault ID with the crypto crate's KDF and XOF. For a secret-class +//! object, memory and the reader must both give chunks of the maximum and a shorter last one +//! (FS-52). + +use std::io::{self, ErrorKind, Read}; + +use crypthix_core::blob::ObjectClass; +use crypthix_core::chunk::{Chunks, GearTable, MASK_L, MASK_S, StreamChunker}; +use crypthix_core::limits::{AVG_CHUNK, GEAR_TABLE_LEN, MAX_CHUNK, MIN_CHUNK}; +use crypthix_crypto::kdf::{self, KdfContext}; +use crypthix_crypto::key::{KdfKey, XofKey}; +use crypthix_crypto::label::XofKeyLabel; +use crypthix_crypto::mac; +use crypthix_types::id::VaultId; +use fastcdc::v2020::{self, Normalization}; + +/// The longest file the target cuts: 2.25 MiB, past two maximum chunks and the 2 MiB window. +const MAX_LEN: usize = 9 << 18; + +/// The unit of a read size at full size. +const READ_UNIT: usize = 4_099; + +/// Where the overlay starts in the input. +const OVERLAY: usize = 87; + +/// The chunk sizes, masks and read unit of one pass. +#[derive(Clone, Copy)] +struct Scale { + min: usize, + avg: usize, + max: usize, + mask_s: u64, + mask_l: u64, + read_unit: usize, + /// Format 0, or the scaled-down sizes of the `scaled_for_fuzzing` constructors. + full: bool, +} + +impl Scale { + /// Format 0: 64 KiB, 256 KiB and 1 MiB. + const FULL: Self = Self { + min: MIN_CHUNK, + avg: AVG_CHUNK, + max: MAX_CHUNK, + mask_s: MASK_S, + mask_l: MASK_L, + read_unit: READ_UNIT, + full: true, + }; + + /// 64, 256 and 1,024 bytes with the level 2 masks fastcdc selects for 256. + fn scaled() -> Self { + let (mask_s, mask_l) = v2020::select_masks(256, Normalization::Level2); + Self { + min: 64, + avg: 256, + max: 1024, + mask_s, + mask_l, + read_unit: 1, + full: false, + } + } +} + +/// A reader that returns `data` in pieces of the given sizes, in turn, and interrupts a read +/// where the size is 0; the read after an interrupt always returns data. +struct Choppy<'a> { + data: &'a [u8], + sizes: [u8; 4], + unit: usize, + turn: usize, + interrupted: bool, +} + +impl Read for Choppy<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let size = self.sizes[self.turn % self.sizes.len()]; + self.turn += 1; + if size == 0 && !self.interrupted { + self.interrupted = true; + return Err(ErrorKind::Interrupted.into()); + } + self.interrupted = false; + let len = (usize::from(size.max(1)) * self.unit) + .min(buf.len()) + .min(self.data.len()); + let (head, rest) = self.data.split_at(len); + buf[..len].copy_from_slice(head); + self.data = rest; + Ok(len) + } +} + +/// The `N` bytes of `data` from `start`, with zeros for any past its end. +fn field(data: &[u8], start: usize) -> [u8; N] { + std::array::from_fn(|i| data.get(start + i).copied().unwrap_or(0)) +} + +/// The gear words fastcdc takes: the keyed XOF under +/// `K_gear = KDF(chunker_seed, -, kdf/gear, vault_id)`, as little-endian `u64`s (FS-52). +fn gear_words(seed: &KdfKey, vault_id: &VaultId) -> Vec { + let context = KdfContext::new().field(vault_id.as_bytes()); + let key: XofKey = kdf::kdf(seed, None, XofKeyLabel::Gear, &context).expect("derives"); + let mut bytes = [0u8; GEAR_TABLE_LEN]; + mac::xof(&key, &mut bytes); + let (words, _) = bytes.as_chunks::<8>(); + words.iter().map(|word| u64::from_le_bytes(*word)).collect() +} + +/// The chunk lengths of `data` under fastcdc 5.0.0 with `words` at `scale`. +fn fastcdc_lengths(words: &[u64], data: &[u8], scale: Scale) -> Vec { + let shifted: Vec = words.iter().map(|word| word << 1).collect(); + let mut lengths = Vec::new(); + let mut offset = 0; + while offset < data.len() { + let (_, len) = v2020::cut_gear( + &data[offset..], + scale.min, + scale.avg, + scale.max, + scale.mask_s, + scale.mask_l, + scale.mask_s << 1, + scale.mask_l << 1, + words, + &shifted, + ); + lengths.push(len); + offset += len; + } + lengths +} + +/// Cuts `file` for an object of `class` at `scale` in memory and through a reader, checks that +/// the two agree and that the chunks cover the file within the size bounds, and returns the +/// lengths. +fn cut_both_ways( + gear: &GearTable, + class: ObjectClass, + file: &[u8], + sizes: [u8; 4], + scale: Scale, +) -> Vec { + let len = file.len(); + let chunks = if scale.full { + Chunks::new(gear, class, file) + } else { + Chunks::scaled_for_fuzzing(gear, class, file) + }; + let shape = chunks.object_shape(); + let in_memory: Vec = chunks.map(|range| range.len()).collect(); + assert_eq!(shape.class(), class, "the shape's class"); + assert_eq!(shape.is_single(), in_memory.len() <= 1, "the shape"); + + assert_eq!( + in_memory.iter().sum::(), + len, + "the chunks do not cover the file" + ); + if let Some((last, rest)) = in_memory.split_last() { + assert!( + (1..=scale.max).contains(last), + "a last chunk of {last} bytes" + ); + for chunk in rest { + assert!( + (scale.min..=scale.max).contains(chunk), + "a chunk of {chunk} bytes" + ); + } + } + + let reader = Choppy { + data: file, + sizes, + unit: scale.read_unit, + turn: 0, + interrupted: false, + }; + let chunker = if scale.full { + StreamChunker::new(gear, class, reader) + } else { + StreamChunker::scaled_for_fuzzing(gear, class, reader) + }; + let mut chunker = chunker.expect("a window"); + let mut offset = 0; + let mut streamed = Vec::new(); + while let Some(chunk) = chunker.next_chunk().expect("the reader does not fail") { + assert_eq!(chunk.index(), streamed.len() as u64, "chunk index"); + assert_eq!(chunk.object_shape(), shape, "the stream's shape"); + let bytes = chunk.bytes(); + assert_eq!(bytes, &file[offset..offset + bytes.len()], "chunk bytes"); + offset += bytes.len(); + assert_eq!(chunk.is_last(), offset == len, "is_last at {offset}"); + streamed.push(bytes.len()); + } + assert_eq!( + streamed, in_memory, + "the stream cuts other chunks than memory" + ); + in_memory +} + +/// Cuts `file` at `scale` for both classes, in memory and through a reader, and the ordinary +/// class with fastcdc too. +fn check(gear: &GearTable, words: &[u64], file: &[u8], sizes: [u8; 4], scale: Scale) { + let in_memory = cut_both_ways(gear, ObjectClass::Ordinary, file, sizes, scale); + let secret = cut_both_ways(gear, ObjectClass::Secret, file, sizes, scale); + let mut fixed = vec![scale.max; file.len() / scale.max]; + if !file.len().is_multiple_of(scale.max) { + fixed.push(file.len() % scale.max); + } + assert_eq!( + secret, fixed, + "a secret object is not cut at fixed steps of the maximum" + ); + assert_eq!( + fastcdc_lengths(words, file, scale), + in_memory, + "fastcdc 5.0.0 cuts other chunks with the same gear table" + ); +} + +/// Cuts the file `data` describes in memory, through a reader, and with fastcdc, then the +/// overlay alone at the scaled-down sizes. +/// +/// # Panics +/// +/// If the three disagree, a chunk other than the last is outside the minimum to the maximum, +/// the stream's chunk indices, `is_last` or shape are wrong, the chunks do not rebuild the file, +/// or a secret-class object is not cut at fixed steps of the maximum. +pub fn chunker(data: &[u8]) { + let [high, middle, low] = field::<3>(data, 0); + let len = usize::try_from(u32::from_be_bytes([0, high, middle, low])) + .expect("24 bits") + .min(MAX_LEN); + let sizes = field::<4>(data, 3); + let mut seed = field::<32>(data, 7); + if seed == [0; 32] { + seed = [1; 32]; + } + let mut vault = field::<16>(data, 39); + if vault == [0; 16] { + vault = [1; 16]; + } + let data_key = field::<32>(data, 55); + let overlay = data.get(OVERLAY..).unwrap_or_default(); + + let mut file = vec![0u8; len]; + if let Ok(key) = XofKey::from_bytes(data_key) { + mac::xof(&key, &mut file); + } + if !overlay.is_empty() { + for (byte, mask) in file.iter_mut().zip(overlay.iter().cycle()) { + *byte ^= mask; + } + } + + let seed = KdfKey::from_bytes(seed).expect("non-zero seed"); + let vault_id = VaultId::try_from_bytes(vault).expect("non-zero ID"); + let gear = GearTable::derive(&seed, &vault_id).expect("derives"); + let words = gear_words(&seed, &vault_id); + check(&gear, &words, &file, sizes, Scale::FULL); + check(&gear, &words, overlay, sizes, Scale::scaled()); +} diff --git a/tests/fuzz/harness/src/data_blob_open.rs b/tests/fuzz/harness/src/data_blob_open.rs new file mode 100644 index 0000000..01b068c --- /dev/null +++ b/tests/fuzz/harness/src/data_blob_open.rs @@ -0,0 +1,258 @@ +//! Opening data blobs on hostile input (FS-53 to FS-56). +//! +//! Random bytes under fixed keys only reach the length, nonce and AEAD checks, since they never +//! authenticate. So the target also seals the input as an inner plaintext under the blob's own +//! key and AAD, which takes it past the AEAD to the inner-plaintext, frame and blob-ID checks, +//! and checks each against what that stage alone says. Last, it writes the input as a chunk, +//! opens it, and flips one byte the input chooses. + +use std::cell::RefCell; + +use crypthix_core::blob::{ + BlobContext, ChunkEntry, ChunkKeys, ObjectClass, ObjectOpener, ObjectSealer, data_blob_aad, +}; +use crypthix_core::chunk::{Chunks, GearTable, ObjectShape}; +use crypthix_core::compress::{Compressor, Decompressor}; +use crypthix_core::error::ReadError; +use crypthix_core::inner::{self, Comp}; +use crypthix_core::limits::{MAX_CHUNK, MAX_PLAIN_LEN}; +use crypthix_crypto::cx_aead::{self, NONCE_LEN, OVERHEAD}; +use crypthix_crypto::key::KdfKey; +use crypthix_crypto::mac; +use crypthix_types::format_error::FormatError; +use crypthix_types::id::{BlobId, DekId, ObjectId, VaultId}; + +thread_local! { + static COMPRESSOR: RefCell = RefCell::new(Compressor::new().expect("a zstd context")); + static DECOMPRESSOR: RefCell = RefCell::new(Decompressor::new()); + /// The shapes the chunker gives an ordinary and a secret object of two or more chunks. + static MULTIPLE: [ObjectShape; 2] = shapes(MAX_CHUNK + 1); + /// The shapes the chunker gives an ordinary and a secret object of one chunk. + static SINGLE: [ObjectShape; 2] = shapes(1); +} + +/// The shapes the chunker gives `len` zero bytes in an ordinary and in a secret object; only +/// the chunker makes shapes. +fn shapes(len: usize) -> [ObjectShape; 2] { + let seed = KdfKey::from_bytes([1; 32]).expect("non-zero key"); + let vault_id = VaultId::try_from_bytes([1; 16]).expect("non-zero ID"); + let gear = GearTable::derive(&seed, &vault_id).expect("derives"); + let zeros = vec![0; len]; + [ObjectClass::Ordinary, ObjectClass::Secret] + .map(|class| Chunks::new(&gear, class, &zeros).object_shape()) +} + +/// The shape of an object of `class` and `count` chunks. +fn shape_of(class: ObjectClass, count: u64) -> ObjectShape { + let index = usize::from(class == ObjectClass::Secret); + let shape = if count == 1 { + SINGLE.with(|shapes| shapes[index]) + } else { + MULTIPLE.with(|shapes| shapes[index]) + }; + assert_eq!( + (shape.class(), shape.is_single()), + (class, count == 1), + "the chunker's shape of {count} chunks" + ); + shape +} + +/// The fixed nonce the target seals inner plaintexts with; never all zero (FS-03). +const NONCE: [u8; NONCE_LEN] = [1; NONCE_LEN]; + +/// A blob ID no chunk of these keys has. +const OTHER_ID: [u8; 32] = [5; 32]; + +fn id(bytes: [u8; 32]) -> BlobId { + BlobId::try_from_bytes(bytes).expect("non-zero ID") +} + +/// One open of `sealed` as a chunk of an object of `class` with `count` chunks. +fn open( + keys: &ChunkKeys, + (class, count): (ObjectClass, u64), + entry: &ChunkEntry, + sealed: &[u8], +) -> Result, FormatError> { + let reader = ObjectOpener::new(keys, class, count); + let result = + DECOMPRESSOR.with_borrow_mut(|decompressor| reader.open(decompressor, entry, sealed)); + match result { + Ok(opened) => Ok(opened.as_slice().to_vec()), + Err(ReadError::Format(error)) => Err(error), + Err(other) => panic!("a data blob gave {other:?}, which is not a format error"), + } +} + +/// Opens `data` as a data blob, then as a sealed inner plaintext, then seals it as a chunk. +/// +/// # Panics +/// +/// If arbitrary bytes open or fail with anything but `Truncated`, `ZeroValue` or `Decrypt` at +/// the right lengths, `plain_len` over 1 MiB is not refused first, a sealed inner plaintext +/// gives another result than its stages give alone (the payload against `plain_len` before +/// the blob ID among them), or a written chunk does not open to itself or opens with a byte +/// flipped. +pub fn data_blob_open(data: &[u8]) { + let context = BlobContext::new( + VaultId::try_from_bytes([1; 16]).expect("non-zero ID"), + ObjectId::try_from_bytes([2; 16]).expect("non-zero ID"), + DekId::try_from_bytes([3; 16]).expect("non-zero ID"), + ); + let dek = KdfKey::from_bytes([7; 32]).expect("non-zero key"); + let keys = ChunkKeys::derive(&dek, &[9; 32], context).expect("derives"); + let keyed = (ObjectClass::Ordinary, 2); + let secret = (ObjectClass::Secret, 1); + + // Arbitrary bytes as a sealed blob. + let entry = ChunkEntry::new(id(OTHER_ID), 100); + for kind in [keyed, secret] { + match open(&keys, kind, &entry, data) { + Ok(_) => panic!("random bytes opened as a data blob"), + Err(FormatError::Truncated) => assert!(data.len() < OVERHEAD, "Truncated too long"), + Err(FormatError::ZeroValue) => assert_eq!(data[..NONCE_LEN], [0; NONCE_LEN]), + Err(FormatError::Decrypt) => assert!(data.len() >= OVERHEAD, "Decrypt too short"), + Err(other) => panic!("random bytes gave {other:?} instead of failing to decrypt"), + } + } + let over_cap = ChunkEntry::new(id(OTHER_ID), MAX_PLAIN_LEN + 1); + assert_eq!( + open(&keys, keyed, &over_cap, data), + Err(FormatError::Decompress), + "plain_len over 1 MiB must be refused before anything else" + ); + + sealed_inner(&keys, data); + round_trip(&keys, data); +} + +/// `data` as an inner plaintext sealed under its blob's own key and AAD: the result must be +/// what the inner-plaintext check, the class rule, the decompressor and the blob-ID check say +/// on their own (FS-93 order). +fn sealed_inner(keys: &ChunkKeys, data: &[u8]) { + let seal = |blob_id: &BlobId| { + let aad = data_blob_aad(keys.context(), blob_id); + cx_aead::seal_with_nonce(keys.chunk_key(), &aad, data, &NONCE) + }; + let view = match inner::decode_inner(data) { + Ok(view) => view, + Err(error) => { + let sealed = seal(&id(OTHER_ID)); + let entry = ChunkEntry::new(id(OTHER_ID), 0); + for kind in [(ObjectClass::Ordinary, 2), (ObjectClass::Secret, 1)] { + assert_eq!(open(keys, kind, &entry, &sealed), Err(error)); + } + return; + } + }; + // What the chunk is, and the plain_len that names it, by the stage that makes it. + let (plain, plain_len) = match view.comp() { + Comp::Raw => (Ok(view.payload().to_vec()), view.payload().len() as u64), + Comp::Zstd => { + let frame = view.payload(); + let declared = zstd_safe::get_frame_content_size(frame) + .ok() + .flatten() + .filter(|size| *size <= MAX_PLAIN_LEN) + .unwrap_or(0); + let decoded = DECOMPRESSOR.with_borrow_mut(|decompressor| { + decompressor + .decode(frame, declared) + .map(|plain| plain.as_slice().to_vec()) + }); + let decoded = decoded.map_err(|error| match error { + ReadError::Format(error) => error, + other => panic!("decompression gave {other:?}"), + }); + (decoded, declared) + } + other => panic!("decode_inner gave an unknown {other:?}"), + }; + + // A secret object never has comp = 1 (FS-53). + let random = ChunkEntry::new(id(OTHER_ID), plain_len); + let as_secret = open( + keys, + (ObjectClass::Secret, 1), + &random, + &seal(&id(OTHER_ID)), + ); + let secret_expected = if view.comp() == Comp::Raw { + plain.clone() + } else { + Err(FormatError::Padding) + }; + assert_eq!(as_secret, secret_expected, "a secret object's chunk"); + + // An ordinary object of two chunks, with the right keyed ID and a wrong one. + let keyed = (ObjectClass::Ordinary, 2); + match &plain { + Ok(chunk) => { + let right = id(*mac::mac(keys.blob_id_key(), chunk).as_bytes()); + let entry = ChunkEntry::new(right, plain_len); + assert_eq!(open(keys, keyed, &entry, &seal(&right)), Ok(chunk.clone())); + let wrong = ChunkEntry::new(id(OTHER_ID), plain_len); + assert_eq!( + open(keys, keyed, &wrong, &seal(&id(OTHER_ID))), + Err(FormatError::Binding), + "a chunk that does not MAC to its blob ID" + ); + let longer = ChunkEntry::new(right, plain_len + 1); + assert_eq!( + open(keys, keyed, &longer, &seal(&right)), + Err(FormatError::Decompress), + "a chunk shorter than plain_len" + ); + let longer_wrong = ChunkEntry::new(id(OTHER_ID), plain_len + 1); + assert_eq!( + open(keys, keyed, &longer_wrong, &seal(&id(OTHER_ID))), + Err(FormatError::Decompress), + "the payload's length is checked before the blob ID" + ); + } + Err(error) => { + let entry = ChunkEntry::new(id(OTHER_ID), plain_len); + let result = open(keys, keyed, &entry, &seal(&id(OTHER_ID))); + assert_eq!( + result, + Err(*error), + "the frame's own error comes before the blob ID" + ); + } + } +} + +/// `data` written as a chunk of an ordinary and of a secret object opens to itself, and not +/// with a byte flipped. +fn round_trip(keys: &ChunkKeys, data: &[u8]) { + let chunk = &data[..data.len().min(MAX_CHUNK)]; + for (class, count) in [ + (ObjectClass::Ordinary, 2), + (ObjectClass::Ordinary, 1), + (ObjectClass::Secret, 3), + ] { + let writer = ObjectSealer::new(keys, shape_of(class, count)); + let sealed = COMPRESSOR + .with_borrow_mut(|compressor| writer.seal(compressor, chunk)) + .expect("seals"); + let opened = open(keys, (class, count), sealed.entry(), sealed.sealed()); + assert_eq!( + opened.as_deref(), + Ok(chunk), + "a written chunk opens to itself" + ); + + let (Some(&high), Some(&low)) = (data.first(), data.get(1)) else { + continue; + }; + let mut tampered = sealed.sealed().to_vec(); + let index = usize::from(u16::from_be_bytes([high, low])) % tampered.len(); + tampered[index] ^= 0x01; + assert_eq!( + open(keys, (class, count), sealed.entry(), &tampered), + Err(FormatError::Decrypt), + "byte {index} flipped" + ); + } +} diff --git a/tests/fuzz/harness/src/decompress.rs b/tests/fuzz/harness/src/decompress.rs new file mode 100644 index 0000000..0638fac --- /dev/null +++ b/tests/fuzz/harness/src/decompress.rs @@ -0,0 +1,121 @@ +//! zstd frames of chunks on hostile input (FS-53). +//! +//! The input is a `plain_len` as a 24-bit big-endian number, then the frame. The decoder's +//! answer is compared with zstd's one-shot decoder and with this file's own reading of the +//! frame header: it must accept exactly the frames that are one FS-53 frame declaring +//! `plain_len` and that zstd decodes to `plain_len` bytes. + +use std::cell::RefCell; + +use crypthix_core::compress::Decompressor; +use crypthix_core::error::ReadError; +use crypthix_core::limits::MAX_PLAIN_LEN; +use crypthix_types::format_error::FormatError; + +thread_local! { + /// One context for every input, as a reader reuses it, so a context left broken by a + /// failed frame shows up on the next. + static DECOMPRESSOR: RefCell = RefCell::new(Decompressor::new()); +} + +/// Decodes the frame after a 3-byte `plain_len`. +/// +/// # Panics +/// +/// If the output is not exactly `plain_len` bytes or differs from zstd's, an error other than +/// `Decompress` is given, or a frame is accepted or refused against FS-53. +pub fn decompress(data: &[u8]) { + let Some(([high, middle, low], frame)) = data.split_first_chunk::<3>() else { + return; + }; + let plain_len = u64::from(u32::from_be_bytes([0, *high, *middle, *low])); + let result = DECOMPRESSOR.with_borrow_mut(|decompressor| decompressor.decode(frame, plain_len)); + let oracle = oracle(frame, plain_len); + match result { + Ok(plain) => { + assert_eq!(plain.len() as u64, plain_len, "output of the wrong length"); + assert_eq!( + oracle.as_deref(), + Some(plain.as_slice()), + "zstd decodes the frame to other bytes, or not at all" + ); + assert!( + fs53_header(frame, plain_len), + "a frame FS-53 forbids was accepted" + ); + } + Err(ReadError::Format(FormatError::Decompress)) => assert!( + oracle.is_none() || !fs53_header(frame, plain_len), + "a valid FS-53 frame of plain_len bytes was refused" + ), + Err(other) => panic!("a frame gave {other:?}; only Decompress exists"), + } +} + +/// What zstd's one-shot decoder makes of `frame` into exactly `plain_len` bytes, if anything +/// and if `plain_len` is within the cap. +fn oracle(frame: &[u8], plain_len: u64) -> Option> { + if plain_len > MAX_PLAIN_LEN { + return None; + } + let len = usize::try_from(plain_len).ok()?; + let mut out = vec![0u8; len]; + match zstd_safe::decompress(&mut out[..], frame) { + Ok(written) if written == len => Some(out), + _ => None, + } +} + +/// Whether `frame` is exactly one zstd frame whose header FS-53 allows: no unused or reserved +/// bit, checksum or dictionary ID, a declared content size of `plain_len` in the shortest field +/// that holds it, a window of at most 1 MiB, and nothing after the frame (RFC 8878 section +/// 3.1.1). +fn fs53_header(frame: &[u8], plain_len: u64) -> bool { + let Some((magic, rest)) = frame.split_first_chunk::<4>() else { + return false; + }; + let Some((&descriptor, rest)) = rest.split_first() else { + return false; + }; + if u32::from_le_bytes(*magic) != 0xFD2F_B528 || descriptor & 0x1f != 0 { + return false; + } + let single_segment = descriptor & 0x20 != 0; + let (window, rest) = if single_segment { + (None, rest) + } else { + let Some((&window, rest)) = rest.split_first() else { + return false; + }; + (Some(window), rest) + }; + let size_bytes = match (descriptor >> 6, single_segment) { + (0, false) => return false, + (0, true) => 1, + (1, _) => 2, + (2, _) => 4, + _ => 8, + }; + // The shortest field: one byte only without a window descriptor, two with an offset of 256. + let shortest = match plain_len { + 0..256 if single_segment => 1, + 256..65_792 => 2, + 0..0xFFFF_FFFF => 4, + _ => 8, + }; + if size_bytes != shortest { + return false; + } + let Some(field) = rest.get(..size_bytes) else { + return false; + }; + let mut bytes = [0u8; 8]; + bytes[..size_bytes].copy_from_slice(field); + let declared = u64::from_le_bytes(bytes) + if size_bytes == 2 { 256 } else { 0 }; + let window_ok = window.is_none_or(|byte| { + let base = 1u64 << (10 + (byte >> 3)); + base + base / 8 * u64::from(byte & 7) <= MAX_PLAIN_LEN + }); + let one_frame = zstd_safe::find_frame_compressed_size(frame) == Ok(frame.len()); + declared == plain_len && window_ok && one_frame +} diff --git a/tests/fuzz/harness/src/inner_plaintext.rs b/tests/fuzz/harness/src/inner_plaintext.rs new file mode 100644 index 0000000..882dad2 --- /dev/null +++ b/tests/fuzz/harness/src/inner_plaintext.rs @@ -0,0 +1,39 @@ +//! The inner plaintext of a data blob on hostile input (FS-54). +//! +//! An inner plaintext has exactly one encoding for each `(comp, payload)`, so anything the +//! decoder accepts must come back byte for byte when it is encoded again. + +use crypthix_core::inner; +use crypthix_core::limits::{INNER_HEADER_LEN, MAX_PAYLOAD_LEN}; +use crypthix_types::format_error::FormatError; + +/// Decodes `data` as an inner plaintext. +/// +/// # Panics +/// +/// If an accepted input does not re-encode to itself, or the error is not `Padding` or +/// `Limit`, or `Limit` is given for anything but a well-formed header whose `payload_len` is +/// over 1 MiB, or such a header gives anything else. +pub fn inner_plaintext(data: &[u8]) { + // `comp` 0 or 1 and `rsv` 0 with `payload_len` over the cap: the only `Limit` (FS-54). + let over_cap = match data.split_first_chunk::() { + Some(([comp, 0, len @ ..], _)) if *comp <= 1 => { + u64::from(u32::from_be_bytes(*len)) > MAX_PAYLOAD_LEN + } + _ => false, + }; + match inner::decode_inner(data) { + Ok(view) => { + let encoded = + inner::encode_inner(view.comp(), view.payload()).expect("a decoded payload fits"); + assert_eq!( + encoded.as_slice(), + data, + "an inner plaintext that is not the encoding of its own fields was accepted" + ); + } + Err(FormatError::Limit) => assert!(over_cap, "Limit for a payload_len within the cap"), + Err(FormatError::Padding) => assert!(!over_cap, "Padding for a payload_len over the cap"), + Err(other) => panic!("an inner plaintext gave {other:?}; only Padding and Limit exist"), + } +} diff --git a/tests/fuzz/harness/src/lib.rs b/tests/fuzz/harness/src/lib.rs index dfe2b5e..3597d44 100644 --- a/tests/fuzz/harness/src/lib.rs +++ b/tests/fuzz/harness/src/lib.rs @@ -1,6 +1,6 @@ -//! Fuzz target bodies for the `crypthix-types` parsers and the `crypthix-crypto` entry points -//! that read stored bytes (M-29, T-39), and the independent minicbor oracle the CBOR -//! differential target compares against. +//! Fuzz target bodies for the `crypthix-types` parsers and the `crypthix-crypto` and +//! `crypthix-core` entry points that read stored bytes (M-29, T-39), and the independent +//! minicbor oracle the CBOR differential target compares against. //! //! Each target is a plain function of the input bytes that panics when a property fails. The //! cargo-fuzz binaries in `tests/fuzz/fuzz_targets` only call these, and `tests/replay.rs` runs @@ -10,9 +10,13 @@ mod cbor_differential; mod cbor_document; mod cbor_model; mod cbor_structured; +mod chunker; mod config_toml; mod cx_open; +mod data_blob_open; +mod decompress; mod id_text; +mod inner_plaintext; mod oracle; mod preamble; mod store_key; @@ -23,9 +27,13 @@ pub use cbor_differential::{SMALL, cbor_differential}; pub use cbor_document::cbor_document; pub use cbor_model::CborModel; pub use cbor_structured::cbor_structured; +pub use chunker::chunker; pub use config_toml::config_toml; pub use cx_open::cx_open; +pub use data_blob_open::data_blob_open; +pub use decompress::decompress; pub use id_text::id_text; +pub use inner_plaintext::inner_plaintext; pub use oracle::{OracleLimits, accepts}; pub use preamble::preamble; pub use store_key::store_key; diff --git a/tests/fuzz/harness/src/targets.rs b/tests/fuzz/harness/src/targets.rs index a9c23b7..1cacb19 100644 --- a/tests/fuzz/harness/src/targets.rs +++ b/tests/fuzz/harness/src/targets.rs @@ -1,13 +1,14 @@ //! The list of fuzz targets. use crate::{cbor_differential, cbor_document, cbor_structured, config_toml, cx_open, id_text}; +use crate::{chunker, data_blob_open, decompress, inner_plaintext}; use crate::{preamble, store_key, verifying_key}; /// A fuzz target body: panics when a property fails on the input. pub type Target = fn(&[u8]); /// Every target, by the name its fuzz binary and regression directory use. -pub const TARGETS: [(&str, Target); 9] = [ +pub const TARGETS: [(&str, Target); 13] = [ ("preamble", preamble), ("cbor_document", cbor_document), ("cbor_differential", cbor_differential), @@ -17,4 +18,8 @@ pub const TARGETS: [(&str, Target); 9] = [ ("id_text", id_text), ("cx_open", cx_open), ("verifying_key", verifying_key), + ("inner_plaintext", inner_plaintext), + ("decompress", decompress), + ("data_blob_open", data_blob_open), + ("chunker", chunker), ]; diff --git a/tests/fuzz/regressions/chunker/.gitkeep b/tests/fuzz/regressions/chunker/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/tests/fuzz/regressions/data_blob_open/.gitkeep b/tests/fuzz/regressions/data_blob_open/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/tests/fuzz/regressions/decompress/.gitkeep b/tests/fuzz/regressions/decompress/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/tests/fuzz/regressions/inner_plaintext/.gitkeep b/tests/fuzz/regressions/inner_plaintext/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/xtask/src/side.rs b/xtask/src/side.rs index 56ae21a..c41e2d8 100644 --- a/xtask/src/side.rs +++ b/xtask/src/side.rs @@ -20,7 +20,7 @@ struct FuzzTarget { } /// Every fuzz target; a test checks this against `tests/fuzz/fuzz_targets`. -const FUZZ_TARGETS: [FuzzTarget; 9] = [ +const FUZZ_TARGETS: [FuzzTarget; 13] = [ FuzzTarget { name: "preamble", dictionary: None, @@ -57,6 +57,22 @@ const FUZZ_TARGETS: [FuzzTarget; 9] = [ name: "verifying_key", dictionary: None, }, + FuzzTarget { + name: "inner_plaintext", + dictionary: Some("zstd.dict"), + }, + FuzzTarget { + name: "decompress", + dictionary: Some("zstd.dict"), + }, + FuzzTarget { + name: "data_blob_open", + dictionary: Some("zstd.dict"), + }, + FuzzTarget { + name: "chunker", + dictionary: None, + }, ]; /// Seconds per target when `--time` is not given. From f586e42f7036a8d5aacdddabfa7162e957d6701f Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 14:54:19 +0530 Subject: [PATCH 05/15] ci: build, lint, fuzz and Miri-test crypthix-core on every platform job --- .github/workflows/ci.yml | 8 ++++++-- .github/workflows/scheduled.yml | 22 ++++++++++++++++++---- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 154ec3f..9ec175b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,6 +56,7 @@ jobs: - "tests/**" - "crates/foundation/types/**" - "crates/foundation/crypto/**" + - "crates/engine/core/**" - "xtask/**" - "Cargo.lock" - "rust-toolchain.toml" @@ -63,6 +64,7 @@ jobs: crypto: - "crates/foundation/types/**" - "crates/foundation/crypto/**" + - "crates/engine/core/**" - "Cargo.lock" - "rust-toolchain.toml" - ".github/workflows/ci.yml" @@ -80,6 +82,7 @@ jobs: - "tests/Cargo.lock" - "crates/foundation/types/src/**" - "crates/foundation/crypto/src/**" + - "crates/engine/core/src/**" - "xtask/src/side.rs" - ".github/workflows/ci.yml" mutants: @@ -307,7 +310,8 @@ jobs: # secure_mem compiles different code on every OS, and the nightly platform runs come too late # for a pull request, so one other OS's branches are linted here: Windows, cross-compiled on - # Linux, which needs only MinGW's C compiler for the C parts of blake3 and alloca. + # Linux, which needs only MinGW's C compiler for the C parts of blake3, alloca and the libzstd + # that crypthix-core builds from source (zstd-sys). windows-clippy: name: Clippy for Windows needs: changes @@ -330,7 +334,7 @@ jobs: sudo apt-get update sudo apt-get install -y --no-install-recommends gcc-mingw-w64-x86-64 - run: >- - cargo clippy -p crypthix-crypto --all-features --all-targets --locked + cargo clippy -p crypthix-crypto -p crypthix-core --all-features --all-targets --locked --target x86_64-pc-windows-gnu -- -D warnings # Protected key memory on a kernel with the CVE-2026-93243 fix and one without it, booted in diff --git a/.github/workflows/scheduled.yml b/.github/workflows/scheduled.yml index 507f1c8..eec1116 100644 --- a/.github/workflows/scheduled.yml +++ b/.github/workflows/scheduled.yml @@ -52,6 +52,10 @@ jobs: - id_text - cx_open - verifying_key + - inner_plaintext + - decompress + - data_blob_open + - chunker steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -114,7 +118,7 @@ jobs: run: cargo bench --workspace --no-run --locked miri: - name: Miri (crypthix-types, crypthix-crypto) and nightly doctests + name: Miri (crypthix-types, crypthix-crypto, crypthix-core) and nightly doctests if: github.event.schedule != '47 3 * * 1' runs-on: ubuntu-24.04 timeout-minutes: 40 @@ -135,7 +139,13 @@ jobs: # Under Miri secure_mem uses its Heap backing, so Miri checks the slot and arena pointer # logic, SecretVec slices, the open paths and the wipes; the mmap, mprotect, mlock and # memfd_secret code is compiled out and is covered by the native Linux tests instead - # (tests/secure_mem_linux.rs and the Linux unit tests). + # (tests/secure_mem_linux.rs and the Linux unit tests). For crypthix-core too only the unit + # tests run: Padmé, the inner plaintext, the frame header checks, the cut loop on short input, + # the gear table, key derivation, the meta blobs, and data blobs with raw payloads opened end + # to end (the plain_len cap, Decrypt on each AAD field, Padding, Limit, a payload of the + # wrong length and Binding), since the decompressor makes its zstd context only at the + # first frame. zstd is C, which Miri cannot run, so the tests that call it are ignored + # there, as are megabyte inputs and a 2 MiB window. - name: cargo miri test env: MIRIFLAGS: -Zmiri-disable-isolation @@ -143,6 +153,7 @@ jobs: run: | rustup run nightly-2026-10-15 cargo miri test -p crypthix-types --locked rustup run nightly-2026-10-15 cargo miri test -p crypthix-crypto --lib --locked + rustup run nightly-2026-10-15 cargo miri test -p crypthix-core --lib --locked # Only nightly rustdoc checks the error code pinned on a `compile_fail` doctest (such as # `compile_fail,E0277`); stable runs the doctests on every PR but accepts any error. - name: Doctest error codes @@ -186,8 +197,11 @@ jobs: cache-key: platform # xtask is deliberately cross-platform: the pre-commit hook runs it on every OS. - run: cargo test --workspace --all-features --locked - # secure_mem's cfg branches differ per OS, so lint the crate where they are compiled. - - run: cargo clippy -p crypthix-crypto --all-features --all-targets --locked -- -D warnings + # secure_mem's cfg branches differ per OS, so lint the crate where they are compiled, and + # crypthix-core with it, whose zstd-sys builds libzstd with each platform's C compiler. + - run: >- + cargo clippy -p crypthix-crypto -p crypthix-core --all-features --all-targets --locked + -- -D warnings # The crypto tests in kernels with and without the CVE-2026-93243 fix (kernel-test.yml), so # the nightly run also notices a change on the runner image or in the tools that breaks them. From 6827a81d943d3a3c520d173fc94f38f651611233 Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 14:54:19 +0530 Subject: [PATCH 06/15] docs: format spec v0.8 and threat model v0.7 for chunking, compression and padding, and tick E1-E3 --- docs/CONTRIBUTING.md | 4 +-- docs/backlog.md | 8 +++--- docs/format-spec.md | 64 +++++++++++++++++++++++++++++++----------- docs/project-vision.md | 2 +- docs/style-guide.md | 6 ++-- docs/threat-model.md | 19 +++++++------ 6 files changed, 68 insertions(+), 35 deletions(-) diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index c2a84aa..e5abba8 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -17,7 +17,7 @@ cargo fmt --all cargo xtask ci # every job below; or name some: cargo xtask ci lint test ``` -If you change a parser or `crypthix-crypto`, also fuzz it for a few minutes on nightly, for example `cargo xtask fuzz cbor_differential --time 300` or `cargo xtask fuzz cx_open --time 300` (see [Testing](style-guide.md#testing)). +If you change a parser, `crypthix-crypto` or the data path in `crypthix-core`, also fuzz it for a few minutes on nightly, for example `cargo xtask fuzz cbor_differential --time 300`, `cargo xtask fuzz cx_open --time 300` or `cargo xtask fuzz decompress --time 300` (see [Testing](style-guide.md#testing)). ## Commit messages @@ -37,7 +37,7 @@ Every job in [`.github/workflows/ci.yml`](../.github/workflows/ci.yml) runs one | `deny` | cargo-deny on both lockfiles, unused dependencies | cargo-deny, [cargo-shear](https://github.com/Boshen/cargo-shear) | | `side` | The `tests/` workspace tests and `vectors --check` | | -Pull requests also get an external link check ([lychee](https://lychee.cli.rs), `lychee.toml`) of the Markdown files they change, a 20-second fuzz run of every target when a parser or the fuzz harness changes, and an advisory mutation test of the changed lines (cargo-mutants). These jobs and `pr` look at what a pull request changes, so they do not run on pushes to master, whose commits a pull request already checked. Each tool's `cargo xtask` error names how to install it. When `crypthix-crypto` or `crypthix-types` changes, and on master, `windows-clippy` lints `crypthix-crypto` for `x86_64-pc-windows-gnu`, cross-compiled on Linux, so the code `secure_mem` compiles on other systems is checked before the nightly platform runs; locally that is `cargo clippy -p crypthix-crypto --all-features --all-targets --target x86_64-pc-windows-gnu -- -D warnings`, with the target added (`rustup target add x86_64-pc-windows-gnu`) and MinGW's `x86_64-w64-mingw32-gcc` installed. +Pull requests also get an external link check ([lychee](https://lychee.cli.rs), `lychee.toml`) of the Markdown files they change, a 20-second fuzz run of every target when a parser or the fuzz harness changes, and an advisory mutation test of the changed lines (cargo-mutants). These jobs and `pr` look at what a pull request changes, so they do not run on pushes to master, whose commits a pull request already checked. Each tool's `cargo xtask` error names how to install it. When `crypthix-crypto`, `crypthix-types` or `crypthix-core` changes, and on master, `windows-clippy` lints `crypthix-crypto` and `crypthix-core` for `x86_64-pc-windows-gnu`, cross-compiled on Linux, so the code `secure_mem` compiles on other systems, and the libzstd that `crypthix-core` builds from source, are checked before the nightly platform runs; locally that is `cargo clippy -p crypthix-crypto -p crypthix-core --all-features --all-targets --target x86_64-pc-windows-gnu -- -D warnings`, with the target added (`rustup target add x86_64-pc-windows-gnu`) and MinGW's `x86_64-w64-mingw32-gcc` installed. ### Kernel test diff --git a/docs/backlog.md b/docs/backlog.md index a6f7478..ea58682 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -22,9 +22,9 @@ Each phase ends with a [threat-model review](threat-model.md#15-did-we-do-a-good - [x] **Crypto wrappers (E4)** — Thin wrappers over audited crates for suite `0x0001`: XChaCha20-Poly1305 inside the committing CX-AEAD, HKDF-SHA-256, BLAKE3, Argon2id, Ed25519 with strict verification; zeroizing key types; known-answer runners over the vendored Wycheproof, BLAKE3 and ed25519-speccheck vectors and the RFC vectors transcribed with them (TV-01); the seeded `ChaCha20Rng` `test-rng` stream for the vector generator, with a build check that no release binary enables it (FS-01, FS-94); no other crate calls crypto libraries directly, and `cargo-deny` also bans `curve25519-dalek`, `subtle`, `getrandom`, the `rand` crates and the lower-level primitive crates outside this crate. cargo-deny `wrappers` allow only direct parents, so these entries list the audited crates that pull them in (for example `ed25519-dalek`), and `getrandom` stays allowed for dev-dependencies such as `proptest`. Covers key commitment (M-9), keys, IDs and the randomness every nonce is hedged with straight from the kernel's `getrandom` (M-36), the HKDF label registry, signature context prefixes and Ed25519 `verify_strict` (M-37), and vector sets TV-01, TV-04 and TV-05 ([format spec 4.2](format-spec.md#42-suite-0x0001), [7](format-spec.md#7-domain-separation-and-committing-aead)). Decides OQ-13 (FIPS mode): no FIPS mode in format 0. Also landed: every nonce hedged with the key, AAD and plaintext (FS-29), so a VM restored without a VM generation ID cannot repeat a nonce for different data (T-81); TV-04 and TV-05 computed by a second implementation in the vector generator, `cx_open` and `verifying_key` fuzz targets, the `check-features` release check, and FS-14 rejecting mixed-order keys. Moved to the key hierarchy item: `KeyProvider`. `foundation/crypthix-crypto` - [x] **Protected key memory (O1)** — Key buffers in `memfd_secret`, `mlock`, excluded from core dumps, with a fallback on older kernels; covers derived keys and plaintext buffers too, not only the root key (T-31). Landed as `crypthix-crypto::secure_mem`, Linux only; heap elsewhere (plain heap memory, wiped on free, reported as `Fallback::Platform`, and an `init` minimum above `Heap` fails there) until A11 and A12 port it. Every key type, derived or unwrapped, is filled in place in a 32-byte slot of one process-wide pool, at the strongest level the system gives (`memfd_secret`, then `mlock`, then `MADV_DONTDUMP` alone) and never below the minimum an app passes to `secure_mem::init`, which keeps that minimum even when it fails. Opened plaintext, signature inputs and passphrases are `SecretBuf`s, Argon2id memory a vector of the same mappings: `mlock`ed, else only dump-excluded, never on the heap and never in secret pages, which pinned-page I/O (`O_DIRECT`, FUSE `splice`) refuses with `EFAULT` (full reasons in the [`secure_mem` module docs](../crates/foundation/crypto/src/secure_mem/mod.rs)). Everything is `MADV_DONTDUMP` and `MADV_DONTFORK`, behind guard pages and wiped on free. Keys and buffers lock separate shares of `RLIMIT_MEMLOCK`, with enough kept for the pool's every page and guard page, so plaintext cannot push a key arena down a level; the pool, and with it that reserve, is set up before anything locks, by `init` or else with the defaults by the first key or plaintext buffer, after which `init` fails with `AlreadyInitialised` rather than keep less than it asks for, and `secure_mem::status` never sets it up (it reports `initialised: false` until then); secret pages are faulted in through the raw `getrandom` system call, so a kernel that charges them past its limit makes the arena fall back a level instead of raising `SIGBUS`; this relies on copying system calls reaching secret pages, and an `EFAULT` there is reported as `LockLimit`. Keys and buffers do not survive `fork` without `exec`: on Linux the child cannot read them (a `MADV_WIPEONFORK` generation marker tells it what it inherited) and starts an empty pool and lock budget of its own. A buffer the kernel will not map is an error, not an abort: `cx_aead::open` returns `OpenError::Memory` (never the opaque `Decrypt`, and only after the commitment holds), `SigningKey::sign` and `Passphrase::new` return the `MemError` and `VerifyingKey::verify` returns `VerifyError::Memory` (`Passphrase::new` wipes its `String` either way). `secure_mem::status` reports the levels and the `Fallback` reasons of keys and buffers for `crypthix status` and M-13. Moved to the daemon item: `PR_SET_DUMPABLE=0`, `LimitMEMLOCK`, `memfd_secret` in its syscall filter and the minimum level (OQ-18); to M-11 (O3): dropping keys before hibernation, which needs a way to unmap key arenas, since a process that made a key in `memfd_secret` memory blocks hibernation until it exits. Left as is: copies left by moves and stack spills, short-lived and not reliably wiped; and the working state of the cipher and MAC code (CX-AEAD's `K_enc` and `K_n`, the HKDF PRK, the expanded Ed25519 key), on the stack for a whole call and wiped on drop. `foundation/crypthix-crypto` -- [ ] **Chunking, compression and padding (E1, E2, E3)** — FastCDC chunking with secret per-vault parameters (M-39), zstd with auto-skip for already-compressed data and per-chunk compression only (T-40), Padmé padding to size buckets; deduplication only inside one ordinary object and never for secret files (T-85, FS-55); TV-07 ([format spec 10.1–10.4](format-spec.md#10-data-path-chunks-blobs-packs-and-shards)). `engine/crypthix-core` -- [ ] **Encrypt pipeline and signed manifests (E4, E5)** — Data and meta blobs, size-class packs, shards, device-signed manifests with Merkle trees, the path index and the signed vault root (M-8, M-9, M-39, M-40); shard IDs and pack hashes checked before decoding (T-47); read-after-write check (M-45); full write and read path, which reuses its `SecretBuf`s or pools small ones rather than map one per chunk, since each is its own mapping (measure first); vector sets TV-10 to TV-13 (shards with k = 1) and TV-21 ([format spec 10](format-spec.md#10-data-path-chunks-blobs-packs-and-shards), [11](format-spec.md#11-object-manifest), [12](format-spec.md#12-path-index), [14](format-spec.md#14-signed-vault-root-and-monotonicity)). Opens W5: per-device monotonicity only until E18 ([format spec 2.2](format-spec.md#22-limits-of-format-0-in-phase-1)). `engine/crypthix-core` -- [ ] **Key hierarchy (E6)** — Root key → random keyring → random epoch KEKs (M-34) → per-object DEKs; vault signing key and the first device certificate (M-14); passphrase share slot and printed recovery share (M-10, M-18, M-35); wrapped key storage; `KeyProvider` in `crypthix-crypto`, the trait engine crates use to reach epoch KEKs, DEKs and pack keys, where a missed lookup is `MissingKey` and never a stand-in key (rule 5, FS-30); binding each wrapped key's type to its AAD label in `seal_key` and `open_key`, so a DEK wrap cannot be unwrapped as another key type (FS-25); the Unicode normalization of passphrases (section 9.1); root rotation (FS-39); vector sets TV-06, TV-08, TV-09, TV-14 and TV-16 with t = 1 ([format spec 8](format-spec.md#8-key-hierarchy), [9](format-spec.md#9-key-files), [13](format-spec.md#13-vault-config-and-devices)). Opens W4 (rotation is a KEK re-wrap only) and W6 (the passphrase or recovery sheet alone is the root). `engine/crypthix-keys` +- [x] **Chunking, compression and padding (E1, E2, E3)** — FastCDC chunking with secret per-vault parameters (M-39), zstd with auto-skip for already-compressed data and per-chunk compression only (T-40), Padmé padding to size buckets; deduplication only inside one ordinary object and never for secret files (T-85, FS-55); TV-07 ([format spec 10.1–10.4](format-spec.md#10-data-path-chunks-blobs-packs-and-shards)). Landed as `crypthix-core`'s `chunk`, `compress`, `pad`, `inner` and `blob` modules. The chunker is our own two-byte FastCDC 2020 loop over a gear table derived from `chunker_seed` and kept in a `SecretBuf`, cutting where `fastcdc` 5.0.0 does (a differential test and the cut rule now written out in FS-52), over memory (`Chunks`) or a reader (`StreamChunker`, a 2 MiB window that also tells whether a chunk is the last). Both take the object's class: secret-class objects are cut at fixed 1 MiB steps with no gear-table lookup (FS-52, after review: the FastCDC loop leaks bits of the bytes through cache timing and secret objects never deduplicate), and the chunker's `ObjectShape` carries the class, which `ObjectSealer::new` takes from it, so an object is sealed in the class it was cut in. Compression uses `zstd-safe` 8.2.0 with the libzstd 1.5.7 it bundles, built from source (cargo-deny allows it only in `crypthix-core` and the `tests/` tools and bans its `pkg-config`, `non-cargo`, `cmake`, `debug`, `legacy`, `zdict_builder`, `experimental`, `zstdmt`, `seekable` and `bindgen` features; `cargo xtask check-features` rejects `ZSTD_SYS_USE_PKG_CONFIG` and a `links` override for `zstd`, but only in the repository's own build environment, not in a user-level `~/.cargo/config.toml`, `$CARGO_HOME` or `--config`); the backstop for those is the runtime check in `Compressor::new` and in `Decompressor::decode` before its first call into libzstd (the decompressor makes its context lazily, so raw-only reads never call libzstd), which fail with `CompressError::Version` if another libzstd is linked. A frame is kept only if it saves 1/16, never for the secret class, and a zstd error fails the write instead of storing raw. Readers check a frame before decoding it (one frame, zstd magic, no checksum, dictionary ID, unused or reserved bit, content size equal to `plain_len` in the shortest field that holds it, a window of at most 2^20 bytes) and decode into a buffer of exactly `plain_len`. Plaintext, frames and inner plaintexts live only in `SecretBuf`s. Data blobs open in the order of FS-56: `plain_len` cap (`Decompress`), CX-AEAD (`Decrypt`), inner plaintext in the order of FS-54 (at least the 6 header bytes, `comp` 0 or 1 and `rsv` 0, each `Padding`; `payload_len` over 2^20, `Limit`; the total length exactly `padme(6 + payload_len)`, then every pad byte zero, each `Padding`), a compressed chunk of a secret object (`Padding`), the payload (`Decompress`), a keyed blob ID (`Binding`, constant time). Deviations, written into format spec v0.8: a blob ID is keyed exactly for an ordinary object of two or more chunks (`BlobIdKind::for_object`), since a reader cannot tell keyed from random IDs and so derives the kind from the manifest; the kind is fixed once per object, by an `ObjectSealer` from the chunker's `ObjectShape` (which a caller cannot make) and by an `ObjectOpener` from the manifest's class and chunk count, both over `ChunkKeys` that carry the `BlobContext` they were derived for, so a single-chunk object can never get keyed IDs and one object's keys never meet another's AAD; the policy switch for reuse is dropped, as a path that must not reuse chunks is secret class. Meta blobs (FS-57) are sealed and opened here too, under a `MetaKey` that carries the vault, kind and epoch it was derived for. `StreamChunker` is fused on error, so an input it could not read to the end is never taken as complete. TV-07 is generated with an independent byte-at-a-time chunker and hand-built zstd frames; fuzz targets `inner_plaintext`, `decompress`, `data_blob_open` and `chunker`; criterion benches for chunking and the inner plaintext. Moved to the encrypt pipeline item: zstd's working memory in protected memory (on the C heap until then, R-26) and `SecretBuf` pooling; to the key hierarchy item: loading `chunker_seed` and the DEKs from the sealed config and key table into `KdfKey`s, which `crypthix-core` takes as inputs until then. `engine/crypthix-core` +- [ ] **Encrypt pipeline and signed manifests (E4, E5)** — Data and meta blobs, size-class packs, shards, device-signed manifests with Merkle trees, the path index and the signed vault root (M-8, M-9, M-39, M-40); shard IDs and pack hashes checked before decoding (T-47); read-after-write check (M-45); full write and read path, which reuses its `SecretBuf`s or pools small ones rather than map one per chunk, since each is its own mapping (measure first); zstd's working memory in protected memory (R-26: today on the C heap, not wiped, locked or `MADV_DONTFORK`), through a `ZSTD_customMem` allocator backed by `secure_mem` in `crypthix-crypto`, since `zstd-safe` cannot place it without `unsafe`; vector sets TV-10 to TV-13 (shards with k = 1) and TV-21 ([format spec 10](format-spec.md#10-data-path-chunks-blobs-packs-and-shards), [11](format-spec.md#11-object-manifest), [12](format-spec.md#12-path-index), [14](format-spec.md#14-signed-vault-root-and-monotonicity)). Opens W5: per-device monotonicity only until E18 ([format spec 2.2](format-spec.md#22-limits-of-format-0-in-phase-1)). `engine/crypthix-core` +- [ ] **Key hierarchy (E6)** — Root key → random keyring → random epoch KEKs (M-34) → per-object DEKs; vault signing key and the first device certificate (M-14); passphrase share slot and printed recovery share (M-10, M-18, M-35); wrapped key storage; `KeyProvider` in `crypthix-crypto`, the trait engine crates use to reach epoch KEKs, DEKs and pack keys, where a missed lookup is `MissingKey` and never a stand-in key (rule 5, FS-30); binding each wrapped key's type to its AAD label in `seal_key` and `open_key`, so a DEK wrap cannot be unwrapped as another key type (FS-25); loading `chunker_seed` from the sealed config ([format spec 13.1](format-spec.md#131-vault-config)) and the DEKs into `KdfKey`s for `crypthix-core`; the Unicode normalization of passphrases (section 9.1); root rotation (FS-39); vector sets TV-06, TV-08, TV-09, TV-14 and TV-16 with t = 1 ([format spec 8](format-spec.md#8-key-hierarchy), [9](format-spec.md#9-key-files), [13](format-spec.md#13-vault-config-and-devices)). Opens W4 (rotation is a KEK re-wrap only) and W6 (the passphrase or recovery sheet alone is the root). `engine/crypthix-keys` - [ ] **Local storage backend** — Shard, key-file and vault-root I/O on `/var/lib/crypthix//store` behind the `Backend` trait; commit order with compare-and-swap on the root (M-44), crash-tested at every commit step with `crypthix-testkit`, plus torn-write and lost-unsynced-data faults below the `Backend` trait for the file I/O itself. The local backend may use std and `rustix` file APIs behind `cfg(target_os = "linux")`, without `unsafe`, as an exception to rule 4. Directory layout, store names, the single-writer lock and two-phase garbage collection (FS-89, FS-91, FS-92); root sequences checked per device (TV-15); the golden tiny vault, crash and GC vectors (TV-20) ([format spec 14](format-spec.md#14-signed-vault-root-and-monotonicity), [17](format-spec.md#17-commit-rotation-and-garbage-collection), [18](format-spec.md#18-directory-layout)). `engine/crypthix-store` - [ ] **Automatic KEK rotation (E7)** — Scheduled re-wrap of DEKs and pack keys and re-seal of the encrypted trees under a new epoch KEK, in the background (daily by default, [format spec FS-90](format-spec.md#17-commit-rotation-and-garbage-collection)). `engine/crypthix-keys` - [ ] **Embedded event queue (M1)** — Persistent in-process queue for rotation, scrub and repair jobs and alerts, behind the `Bus` trait; jobs are authenticated and carry sequence numbers and expiry (M-12, FS-86, TV-18, [format spec 16](format-spec.md#16-queue-job-envelope)). `foundation/crypthix-bus` @@ -35,7 +35,7 @@ Each phase ends with a [threat-model review](threat-model.md#15-did-we-do-a-good - [ ] **Daemon and local API** — `crypthixd` process that owns keys and wires all crates; JSON-over-Unix-socket API for CLI and extension. Runs as its own system user that owns the store and config, checks socket peers with `SO_PEERCRED` and pidfd, fails closed, and reports Full or Degraded hardening mode (M-13, M-15). Calls `secure_mem::init(Config::default().with_minimum(..))` before the first key or plaintext buffer (a passphrase too; a later `init` fails with `AlreadyInitialised`) and shows `secure_mem::status` in the hardening mode; never forks after making keys without `exec`, since keys do not survive into the child; sets `PR_SET_DUMPABLE=0`, and its unit sets `LimitMEMLOCK=` and allows `memfd_secret` in `SystemCallFilter=` (T-31). Decides OQ-7 (daemon capabilities and users) and OQ-18 (the minimum protection level). Opens W11 (Degraded mode wherever BPF-LSM is off). A root helper mounts the vault and brokers caller identity (M-20, M-21); keys live in a separate key-holder process (M-29). A `cargo-fuzz` target for API messages (M-29). `apps/crypthixd`, `access/crypthix-api` - [ ] **Transparent encrypted folder (A1)** — FUSE mount backed by the engine; open, read, write, rename, delete, mmap-safe; `crypthix mount`. Secret paths use direct I/O with no shared page cache; the caller's UID is checked on every request; lookups and listings follow the same policy (M-1, M-15, M-23); writes the manifest's `fs_attrs` field (*Reserved P2*, [format spec 11](format-spec.md#11-object-manifest)). A `cargo-fuzz` target for FUSE requests (M-29). Decides OQ-14 (`getxattr` leaks). Opens W2: not ransomware-safe until snapshots. `access/crypthix-fs` - [ ] **Program identity resolution** — Caller PID → exe path, binary hash (cached), parent chain, uid, cgroup. pidfd and start-time checks against PID reuse; identity by exe device, inode and hash, never by process name; launch-environment check; reads the exec-time record of the root helper in Full mode (M-2, M-3, M-17, M-20). Decides OQ-3 (container profiles). `access/crypthix-policy` -- [ ] **Per-program policy engine (A2)** — `policy.toml` rules by program and path, most-specific-first matching, default ask for unknown programs and deny for secret paths. Policy changes only through the API (M-7); files that steer allowed programs are protected (M-6); identity by exe, never name (M-3); lookups and listings gated too (M-23); interpreter grants bound to a project and an interactive launch (M-25); no secrets for editors and browsers by default (M-26). Opens W1 until O4 and O5. `access/crypthix-policy` +- [ ] **Per-program policy engine (A2)** — `policy.toml` rules by program and path, most-specific-first matching, default ask for unknown programs and deny for secret paths. Policy changes only through the API (M-7); files that steer allowed programs are protected (M-6); identity by exe, never name (M-3); lookups and listings gated too (M-23); interpreter grants bound to a project and an interactive launch (M-25); no secrets for editors and browsers by default (M-26); per-path rules that make paths of mixed trust (mail stores, chat and app SQLite databases, browser profiles) secret class or store them uncompressed, the recourse for T-40's residual in ordinary objects ([format spec FS-53](format-spec.md#102-compression)). Opens W1 until O4 and O5. `access/crypthix-policy` - [ ] **First-use prompts and deny log (A3, A4)** — Allow once / always / deny prompts via the API, never accepted from the VS Code extension alone (M-26); every denial logged with its process tree, rate-limited and aggregated; approvals recorded with the approving identity and presence method, signed once E12 lands (M-31). `access/crypthix-policy`, `access/crypthix-api` - [ ] **Protected admin actions (A14)** — Loosening policy, unfreezing, deleting snapshots, adding devices and disabling the guard require user presence (passphrase or OS authentication), so malware running as the user cannot switch protection off. Passphrase or polkit first; FIDO2 touch or second-device confirmation later (M-5). Policy and guard config change only here (M-7). Opens W3: passphrase or polkit presence can be faked by same-user code. `access/crypthix-api`, `access/crypthix-policy` - [ ] **AI coding agent guard (U1)** — Agent profiles matching process trees (Claude Code, Cursor, Codex); deny secrets, allow code; per-agent access feed. `crypthix agent run` cgroup launcher and own-exe matching (M-4), agent configs protected as steering files (M-6), agent-write taint (M-24), no secrets for editors and browsers by default (M-26), agent options that keep secrets out of transcripts (M-27); stated as best effort. Decides OQ-8 (agent sandboxes). `access/crypthix-policy` diff --git a/docs/format-spec.md b/docs/format-spec.md index 8e4be60..22bd21f 100644 --- a/docs/format-spec.md +++ b/docs/format-spec.md @@ -4,7 +4,7 @@ | | | | --- | --- | -| Status | Format 0, draft v0.7 after two rounds of persona review; preamble and CBOR implemented in `crypthix-types`, the primitives, label registry and CX-AEAD in `crypthix-crypto`, with generated vectors and fuzz targets. No compatibility promise (see [FS-24](#6-versioning-and-no-downgrade)) | +| Status | Format 0, draft v0.8 after two rounds of persona review; preamble and CBOR implemented in `crypthix-types`, the primitives, label registry and CX-AEAD in `crypthix-crypto`, chunking, compression, padding and data and meta blobs in `crypthix-core`, with generated vectors and fuzz targets. No compatibility promise (see [FS-24](#6-versioning-and-no-downgrade)) | | Owner | Arpan ([@thearpankumar](https://github.com/thearpankumar)) | | Date | 2026-10-29 | | Format / suite | Format version `0x0000`, suite `0x0001` | @@ -111,6 +111,7 @@ Field-table columns: **Key** is the CBOR map key (negative = critical, [FS-09](# | Number of packs, their size classes and write times; shard sizes and counts | Storage itself (R-5) | | An upper bound on how much changed per commit | Pack count and size class per commit | | Whether a commit reused chunks of an ordinary file | Fewer new data packs (residual of [FS-55](#104-blobs)) | +| How many chunks of one version of an ordinary file repeat, for example runs of zeros cut at 1 MiB that share one keyed ID, which point to sparse regions | Fewer blobs than the file's size needs (residual of [FS-55](#104-blobs)) | | For a commit that changes one file: that file's approximate size and its set of packs | The commit's new packs are that file (Padmé bounds the leak per chunk, not per commit) | | When shards are written and deleted, and which were written and deleted together; when compaction runs | Storage itself; garbage collection ([FS-91](#17-commit-rotation-and-garbage-collection)) | | Key-management events: a root rotation (new `vault_id` and keyring), a passphrase change (rewritten slot), a revocation (device-set status) | Clear key files and device sets | @@ -425,7 +426,7 @@ HKDF-Expand is keyed directly by K, which RFC 5869 section 3.3 allows for unifor overhead: 72 bytes. A wrapped 32-byte key is 104 bytes. ``` -**FS-28.** A key wrap and a data seal never share an AAD label: the key-wrap labels (`keyring`, `epoch`, `vault-sign-key`, `device-key`, `dek-wrap`, `pack-key-wrap`, `log-key`) are sealed and opened only as wrapped keys, so a wrapped key's bytes never reach a caller and chosen bytes never become a key (backlog rule 9). An all-zero nonce is `ZeroValue` (FS-03). Open MUST recompute `C` and compare it in constant time before it checks the tag. Any change to the key, nonce or AAD therefore fails as `Commitment`; only a change to the ciphertext or tag reaches `AeadTag`. Both names exist only inside `crypthix-crypto` (behind a `vectors` feature for TV-05); every caller outside that crate sees the one opaque error `Decrypt`, so there is no oracle. An open whose commitment holds but that gets no protected memory for its plaintext fails with a memory error of `crypthix-crypto`, not a format error and never `Decrypt`, so memory pressure is not mistaken for tampering; it reveals nothing, since only a genuine nonce and commitment get that far. +**FS-28.** A key wrap and a data seal never share an AAD label: the key-wrap labels (`keyring`, `epoch`, `vault-sign-key`, `device-key`, `dek-wrap`, `pack-key-wrap`, `log-key`) are sealed and opened only as wrapped keys, so a wrapped key's bytes never reach a caller and chosen bytes never become a key (backlog rule 9). A seal shorter than its 72 bytes of overhead is `Truncated`, and an all-zero nonce is `ZeroValue` (FS-03). Open MUST recompute `C` and compare it in constant time before it checks the tag. Any change to the key, nonce or AAD therefore fails as `Commitment`; only a change to the ciphertext or tag reaches `AeadTag`. Both names exist only inside `crypthix-crypto` (behind a `vectors` feature for TV-05); every caller outside that crate sees the one opaque error `Decrypt`, so there is no oracle. An open whose commitment holds but that gets no protected memory for its plaintext fails with a memory error of `crypthix-crypto`, not a format error and never `Decrypt`, so memory pressure is not mistaken for tampering; it reveals nothing, since only a genuine nonce and commitment get that far. **FS-29.** Nonces are 24 bytes and come in two kinds. Neither is taken straight from `getrandom`: following the hedging framework of [Ristenpart and Yilek (NDSS 2010)](https://www.cs.toronto.edu/~ristenpart/papers/sslhedge.html), the randomness is mixed with the key, the AAD and the plaintext, so repeated randomness (a VM restored from a snapshot, T-81) leaks at most that two seals are equal, the minimum any deterministic scheme leaks ([RFC 8452](https://www.rfc-editor.org/rfc/rfc8452)). This is a privacy bound; authenticity rests, as always, on the commitment and the Poly1305 tag under the per-nonce key: @@ -687,11 +688,24 @@ pack-key wrap, key K_pkwrap_e: ### 10.1 Chunking -**FS-52.** Files are cut with FastCDC (2020, normalised chunking level 2) with minimum 64 KiB, average 256 KiB and maximum 1 MiB. The 256-entry gear table is the first 2,048 bytes of the BLAKE3 XOF in keyed mode under `K_gear`, over the empty input, read as u64 little-endian words; the shifted table, masks and cut rule are those of the FastCDC 2020 paper as implemented by the `fastcdc` crate's `v2020` module (pinned), and TV-07 includes a boundary known-answer test. `chunker_seed` is 32 random bytes in the sealed part of the config, so backends cannot recompute boundaries. The design assumes the seed may still leak, since keyed chunkers have been attacked from observed sizes ([ePrint 2025/558](https://eprint.iacr.org/2025/558)); packs are what hide boundaries (M-39, T-84). A file smaller than the minimum is one chunk; an empty file has no chunks. +**FS-52.** Ordinary objects are cut with FastCDC (2020, normalised chunking level 2) with minimum `min` = 64 KiB, average `avg` = 256 KiB and maximum `max` = 1 MiB. The 256-entry gear table `gear` is the first 2,048 bytes of the BLAKE3 XOF in keyed mode under `K_gear`, over the empty input, read as u64 little-endian words. The masks are `MASK_S = 0x0000d91747537000` (20 bits set) and `MASK_L = 0x0000d90303537000` (16 bits set), entries 20 and 16 of the FastCDC 2020 mask table. The first chunk of `n` remaining bytes is cut by this rule: + +1. If `n ≤ min`, the chunk is all `n` bytes. An empty file therefore has no chunks, and a file no longer than the minimum is one chunk. +2. Otherwise let `end = min(n, max)`, `center = min(n, avg)` and `h = 0`. +3. For each byte position `i` from `2⌊min/2⌋` up to but not including `2⌊end/2⌋`, set `h = (h << 1) + gear[b_i] mod 2^64`, where `b_i` is the byte at `i`. The mask is `MASK_S` while `i < 2⌊center/2⌋` and `MASK_L` after. If `h & mask = 0`, the chunk is bytes `0` to `i − 1`: the cut comes just before the byte that matched. +4. If no position matches, the chunk is the first `end` bytes, so a chunk is cut at `max` at the latest. An odd last byte is never tested, so it is never a cut point. + +The next chunk is cut the same way from where this one ends. This is the cut rule of `fastcdc::v2020::cut_gear` in the `fastcdc` crate 5.0.0, which takes two bytes per step with a shifted table and shifted masks and cuts at the same places; `fastcdc` 3.x differs at odd tails. The masks are fixed here, not chosen by the crate's `select_masks`, which computes them through floating point. TV-07 checks the boundaries against a second chunker in the generator that takes one byte per step. `chunker_seed` is 32 random bytes in the sealed part of the config, so backends cannot recompute boundaries. The design assumes the seed may still leak, since keyed gear tables have been recovered from observed chunk sizes ([ePrint 2025/558](https://eprint.iacr.org/2025/558)); a writer keeps the table in protected plaintext memory (a `SecretBuf`: locked where the memory limit allows, out of core dumps, wiped on free), not in the secret pages that hold keys (FS-31). Packs (FS-59) are what hide the sizes; Padmé (FS-54) only coarsens them, to steps of 8 KiB for a 256 KiB chunk and 32 KiB for a 1 MiB one, so about 5 bits of each chunk's length stay visible in any blob seen outside a pack, as every blob is until packs land with the encrypt pipeline item (M-39, T-84, R-5). + +Objects of the secret class (FS-55) are not cut by this rule. They are cut into chunks of exactly `max` = 1 MiB from the start, with the remainder as a shorter last chunk; an empty object has no chunks, and an object of exactly 1 MiB is one chunk. No byte is looked up in the gear table. The FastCDC loop indexes the table with plaintext bytes and stops early at a cut, so a process sharing the CPU cache could learn bits of the bytes and the cut positions from its timing, and the chunk lengths of every object cut with the table feed the gear-table recovery of T-84. Secret-class chunks get random blob IDs and are never reused, so content-defined boundaries would give them nothing. A reader does not check boundaries, for either class; TV-07 checks both rules. ### 10.2 Compression -**FS-53.** Each chunk is compressed with zstd (version pinned, level 3) into exactly one frame with its content size declared, no checksum, no dictionary, no skippable frames and `window_log ≤ 20`. If `16 × compressed > 15 × plain`, the chunk is stored with `comp = 0`. Objects of the secret class are never compressed, so attacker-influenced data and secrets never share a compression context (T-40). A reader decompresses with a streaming decoder whose output is capped at the chunk's `plain_len` from the manifest, and the result MUST be exactly `plain_len` bytes, at most 1 MiB (`Decompress`). +**FS-53.** Each chunk of an ordinary object is compressed with zstd (libzstd 1.5.7, level 3) into exactly one frame with its content size declared, no checksum, no dictionary ID and `window_log = 20`. Its compressed length is the length of that frame. If `16 × compressed > 15 × plain`, the chunk is stored with `comp = 0`, so a frame is kept only if it saves at least 1/16. A zstd error fails the write; the chunk is never stored raw instead. Each chunk is its own frame, with no dictionary and no history from other chunks. Objects of the secret class are never compressed, so nothing in a secret-class object shares a compression context with its secrets. That keeps attacker-influenced data and secrets apart only where every secret is in a secret-class object. An ordinary object whose content mixes trust levels, such as a mail store, a chat or app SQLite database or a browser profile, can hold injected data and a secret in one chunk, which is the setting of compression injection attacks ([Fábrega et al., IEEE S&P 2024](https://arxiv.org/abs/2411.09228)); Padmé only raises the number of injections such an attack needs, and packs (FS-59) are what hide the sizes it reads. This is a residual for ordinary objects of mixed trust (T-40); the recourse is a per-path policy (P2) that makes such paths secret class or stores them with `comp = 0`. zstd output may differ between versions, so the encoder is pinned. A reader accepts a frame exactly when it passes the header checks below and libzstd 1.5.7 then decodes it to `plain_len` bytes; that, not RFC 8878 alone, defines a valid frame. libzstd 1.5.7 is lenient inside blocks, for example it decodes an RLE block longer than the 128 KiB block maximum that RFC 8878 sets, so a reader built on another decoder must accept what 1.5.7 accepts after these header checks, and nothing more. + +A reader takes `plain_len` from the manifest. Above 2^20 the chunk is `Decompress` before it is decrypted or anything is allocated. After the inner plaintext passes FS-54, a chunk of a secret-class object with `comp = 1` is `Padding`, before its frame is looked at. Then, each failure being `Decompress`: +- with `comp = 0`, `payload_len` MUST equal `plain_len`; +- with `comp = 1`, the payload MUST be exactly one zstd frame: the zstd magic number, so no skippable frame; the unused bit (`0x10`) and the reserved bit of the frame header descriptor clear; no checksum; no dictionary ID; a declared content size equal to `plain_len`, in the shortest field that holds it (one byte only in a single-segment frame below 256 bytes, two bytes with the offset of 256 for 256 to 65,791 bytes, otherwise four), as libzstd's encoder writes it; a window of at most 2^20 bytes, counting the mantissa and not only the exponent; and no bytes after the frame. These are checked before a byte is decoded. RFC 8878 has encoders write the unused bit as zero but decoders ignore it, and lets a size be written in any field that holds it; libzstd 1.5.7 decodes both, but no FS-53 writer produces them, so a reader refuses them rather than accept two encodings of one frame. A streaming decoder then writes into a buffer of exactly `plain_len` bytes, and MUST fill it and end the frame. ### 10.3 Padding and inner plaintext @@ -706,7 +720,7 @@ pack-key wrap, key K_pkwrap_e: PETS 2019): at most 12% overhead, leaking O(log log n) bits of size. ``` -The total length MUST be `padme(6 + payload_len)`, where for `L ≥ 2`: `E = ⌊log2 L⌋`, `S = ⌊log2 E⌋ + 1`, `z = E − S`, `padme(L) = (L + 2^z − 1) & ¬(2^z − 1)` (for `L < 2`, `padme(L) = L`). A reader MUST check that `comp` is 0 or 1, `rsv` is 0, the pad is zero and the length is exactly that (`Padding`). +The payload is the chunk for `comp = 0` and its zstd frame for `comp = 1` (FS-53). The total length MUST be `padme(6 + payload_len)`, where for `L ≥ 2`: `E = ⌊log2 L⌋`, `S = ⌊log2 E⌋ + 1`, `z = E − S`, `padme(L) = (L + 2^z − 1) & ¬(2^z − 1)` (for `L < 2`, `padme(L) = L`). A reader checks, in this order: at least the 6 header bytes (`Padding`); `comp` is 0 or 1 (`Padding`); `rsv` is 0 (`Padding`); `payload_len ≤ 2^20` (`Limit`), before the length is used for anything; the total length is exactly `padme(6 + payload_len)` (`Padding`); every pad byte is zero (`Padding`). ### 10.4 Blobs @@ -728,9 +742,15 @@ aad = u8 len ‖ "crypthix/v0/aad/blob-data" ‖ fmt ‖ suite ‖ vault_id ‖ ‖ object_id ‖ dek_id ‖ blob_id ``` -The AAD binds each chunk to its vault, object and DEK. Version, position, order, count and the final chunk are bound by the manifest, which is signed and lists every chunk ([FS-66](#11-object-manifest), [FS-67](#11-object-manifest)). For ordinary objects `blob_id = MAC(K_blobid, chunk plaintext)`, so an unchanged chunk is reused by the next version without re-encryption (E1). Deduplication stays inside one object, so no one learns whether another file shares a chunk (OQ-9, T-85). For secret-class objects, and for objects of a single chunk, `blob_id` is random and nothing is reused, so content injected into a small or secret file cannot confirm a guess through the number of new packs. Policy MAY turn reuse off for any path. +The AAD binds each chunk to its vault, object and DEK. Version, position, order, count and the final chunk are bound by the manifest, which is signed and lists every chunk ([FS-66](#11-object-manifest), [FS-67](#11-object-manifest)). `blob_id` is keyed, `MAC(K_blobid, chunk plaintext)`, exactly when the object has `class = 0` (ordinary) and two or more chunks; otherwise it is 32 random bytes. A keyed ID lets the next version of the object reuse an unchanged chunk without re-encryption (E1). Deduplication stays inside one object, so no one learns whether another file shares a chunk (OQ-9, T-85). For secret-class objects, and for objects of a single chunk, nothing is reused, so content injected into a small or secret file cannot confirm a guess through the number of new packs. Inside one version of an ordinary object, equal chunks share a keyed ID, so a backend learns how many chunks repeat: runs of zeros, cut at 1 MiB (FS-52), all share one ID, which points to sparse regions ([2.1](#21-what-a-backend-learns)). A keyed ID looks like a random one, so no field records the kind: writer and reader both derive it from the manifest's `class` and `chunk_count`. A path whose chunks must never be reused is marked secret class; there is no other switch. -**FS-56.** After opening an ordinary data blob, the reader MUST recompute `blob_id` from the decrypted chunk and compare (`Binding`). +**FS-56.** After opening a data blob with a keyed `blob_id` (FS-55), the reader MUST recompute it from the decrypted chunk and compare in constant time (`Binding`, FS-15). A random `blob_id` has nothing to recompute. A reader opens a data blob with these checks in this order, and the first failure is the error (FS-93); no plaintext is released before all of them pass: +1. `plain_len ≤ 2^20` (`Decompress`, FS-53), before anything is decrypted or allocated; +2. the CX-AEAD open under `K_chunk` with the AAD of FS-55 (`Decrypt`; `Truncated` or `ZeroValue` as FS-28 says); +3. the inner plaintext (`Padding`, `Limit`, FS-54); +4. a secret-class object with `comp = 1` (`Padding`, FS-53); +5. the payload against `plain_len`, and for `comp = 1` the frame checks and decoding (`Decompress`, FS-53); +6. a keyed `blob_id` (`Binding`). **FS-57.** A meta blob of kind 0x03–0x06 or 0x08 is `Seal(K_kind_e, aad, CBOR, hedged nonce)` with a random `blob_id` and: @@ -1271,8 +1291,8 @@ The names below are the `expect` values of the test vectors. All but `Commitment | `NameMismatch` | FS-06, FS-92 | File name or path does not match the content | | `Flags` | FS-07 | Non-zero preamble flags | | `TrailingBytes` | FS-07 | Bytes past `body_len` | -| `Truncated` | FS-07, FS-11 | File shorter than declared, or input ending inside a CBOR head | -| `Limit` | FS-07, FS-11 | A size, count, depth or fan-out limit exceeded | +| `Truncated` | FS-07, FS-11, FS-28 | File shorter than declared, input ending inside a CBOR head, or a seal shorter than its overhead | +| `Limit` | FS-07, FS-11, FS-54 | A size, count, depth or fan-out limit exceeded | | `NonCanonical` | FS-08 | CBOR not in deterministic form | | `Schema` | FS-09, FS-10 | Wrong type, missing key, wrong size, bad enum, invalid text, misplaced null | | `UnknownCritical` | FS-09, FS-20 | Unknown negative map key | @@ -1297,8 +1317,8 @@ The names below are the `expect` values of the test vectors. All but `Commitment | `Expired` | FS-76, FS-83, FS-86 | Outside a validity window | | `Merkle` | FS-66, FS-72 | Merkle or tree commitment mismatch | | `ChunkList` | FS-67 | Chunk count or length mismatch | -| `Padding` | FS-54, FS-60 | Reserved byte, pad or trailing header bytes not zero; bad compression code | -| `Decompress` | FS-53 | Decompressed size wrong or over the cap | +| `Padding` | FS-53, FS-54, FS-60 | Reserved byte, pad or trailing header bytes not zero; bad compression code; wrong padded length; a compressed chunk in a secret-class object | +| `Decompress` | FS-53 | `plain_len` over the cap; a raw payload not `plain_len` bytes; a payload that is not exactly one allowed zstd frame, or that does not decode to exactly `plain_len` bytes | | `Layout` | FS-60, FS-62 | Pack or shard bounds or parameters inconsistent | | `ShardHash` | FS-63, FS-64 | Shard or pack hash mismatch | | `Path` | FS-71 | Path breaks the normalisation rules | @@ -1313,7 +1333,7 @@ The names below are the `expect` values of the test vectors. All but `Commitment | `Audience` | FS-86 | Job for another vault or recipient | | `Replay` | FS-86 | Job sequence number not above the last seen | -**FS-93.** Every failure maps to exactly one error from this table: the first failing check in the order the rules give. In a CBOR document, items are checked in byte order, so the first item that breaks any rule decides; at one head, its encoding (FS-08: `Truncated`, `NonCanonical`, including a tag, float or simple value used as a map key) comes before the key rules of FS-09 (`Schema`), and those before the item's own rules and limits. Schema checks of a structure (missing keys, wrong types, `UnknownCritical`) run only on a document that passed. No plaintext is released from a chunk before its commitment, tag and blob ID verify, and no file content is released before the chunk list of that read verifies (SP-C2). +**FS-93.** Every failure maps to exactly one error from this table: the first failing check in the order the rules give. In a CBOR document, items are checked in byte order, so the first item that breaks any rule decides; at one head, its encoding (FS-08: `Truncated`, `NonCanonical`, including a tag, float or simple value used as a map key) comes before the key rules of FS-09 (`Schema`), and those before the item's own rules and limits. Schema checks of a structure (missing keys, wrong types, `UnknownCritical`) run only on a document that passed. A data blob is checked in the order of FS-56, its inner plaintext in the order of FS-54. No plaintext is released from a chunk before its commitment, tag and blob ID verify, and no file content is released before the chunk list of that read verifies (SP-C2). --- @@ -1368,7 +1388,7 @@ Files are modelled on [Wycheproof](https://github.com/C2SP/wycheproof) (`testGro - Every `expect` is `Ok` or a name from [section 19](#19-errors). Only TV-05 expects `Commitment` or `AeadTag`; every other set expects `Decrypt` for a CX-AEAD failure. - Every rule that can fail has at least one negative vector. - The generator uses a seeded `ChaCha20Rng` (from the `chacha20` crate) behind the `test-rng` feature of `crypthix-crypto` and draws only through `fill_bytes` on a separately labelled stream per test, seeded with keyed BLAKE3 of the set's `seed` and the label, never through `gen_range` or other distributions that may change between `rand` releases. `cargo xtask check-features` fails if a release build of the main workspace would enable `test-rng` or `vectors` (FS-01). TV-02, TV-03 and TV-17 draw no randomness, and the generator writes their bytes by hand rather than through the decoder they test. For TV-04 and TV-05 the generator computes `H`, `KDF`, `MAC`, CX-AEAD and the nonces with its own code over the audited crates, written from section 7 and not from `crypthix-crypto`, so the two implementations check each other. -- zstd is pinned to one version, since its output may change between versions. +- zstd is pinned to one version, named in the set's `zstd` header (1.5.7 for TV-07), since its encoder output may change between versions. A runner checks encoder output only under that version and fails under another; decoding vectors must pass under any version. - CI regenerates the vectors and diffs them against the committed files (`cargo xtask vectors --check`). Vectors are frozen per format; changing a committed vector needs a changelog row here. - Argon2id vectors run at the 256 MiB floor and are marked slow (`#[ignore]`); the scheduled deep-test job runs them with `--ignored`. - Before the 1.0 audit, a second, independent decoder (for example a short Python reader) runs every set. @@ -1417,9 +1437,17 @@ Files are modelled on [Wycheproof](https://github.com/C2SP/wycheproof) (`testGro | Ciphertext or tag changed | TV-05 | `AeadTag` | FS-28 | | Same key and ciphertext opened with another nonce or AAD | TV-05 | `Commitment` | FS-27, M-9 | | DEK or pack-key wrap moved to another object, pack or epoch | TV-06 | `Decrypt` | FS-50, M-8 | -| Data blob AAD: vault, object, DEK and blob ID changed in turn | TV-07 | `Decrypt` | FS-55, M-8, T-35 | -| Blob decrypts but gives another blob ID | TV-07 | `Binding` | FS-56 | -| Zstd frame larger than declared; `rsv` or pad not zero; unknown `comp` | TV-07 | `Decompress`, `Padding` | FS-53, FS-54 | +| Data blob AAD: vault, object, DEK, blob ID, kind byte and label changed in turn; another key | TV-07 | `Decrypt` | FS-55, M-8, T-35 | +| Data or meta blob one byte shorter than a seal; all-zero nonce | TV-07 | `Truncated`, `ZeroValue` | FS-28, FS-03, FS-57 | +| Blob decrypts but gives another blob ID; a random blob ID in an ordinary object of two or more chunks | TV-07 | `Binding` | FS-55, FS-56, T-85 | +| Inner plaintext shorter than its header; unknown `comp`; `rsv` or a pad byte not zero; one byte longer or shorter than `padme(6 + payload_len)` | TV-07 | `Padding` | FS-54, T-39 | +| `payload_len` exactly 2^20; 2^20 + 1; 2^32 − 1; a bad `comp` or `rsv` with 2^20 + 1 | TV-07 | `Ok`, `Limit`, `Padding` first | FS-54, FS-93, T-39 | +| `plain_len` exactly 2^20; 2^20 + 1, refused before decryption | TV-07 | `Ok`, `Decompress` | FS-53, FS-11, T-39 | +| Zstd frame holding more or less than it declares; content size missing or other than `plain_len`; content size in a wider field than needed (four or eight bytes for 5, four for 300); checksum; dictionary ID; reserved bit; unused bit; skippable frame before, after or alone; two frames; a trailing byte; a cut-off frame; a valid header followed by a block of the reserved type 3; window 2^20 + 2^17 or 2^21 (2^20 is `Ok`); a raw block and a compressed block of exactly 128 KiB, the block maximum, are `Ok` (libzstd up to 1.5.2 refused the compressed one, zstd's decompressor errata) | TV-07 | `Decompress`, `Ok` | FS-53, T-39 | +| Raw payload one byte shorter than `plain_len` | TV-07 | `Decompress` | FS-53 | +| Secret-class chunk with `comp = 1`, also with a bad frame | TV-07 | `Padding` | FS-53, FS-93, T-40 | +| Bad frame, or a raw payload other than `plain_len` bytes, and a wrong blob ID together | TV-07 | `Decompress` | FS-56, FS-93 | +| Meta blob opened with another kind byte, epoch, blob ID, vault or KEK | TV-07 | `Decrypt` | FS-57, M-8, T-35 | | Argon2id `m`, `t` or `p` below the floor; above a ceiling; `m × t` over the cap | TV-08 | `KdfBelowFloor`, `KdfAboveCeiling` | FS-41, M-10, T-26 | | KDF salt or parameter changed in the slot; unknown key added | TV-08 | `Decrypt` | FS-40, M-10 | | Retired epoch file reappears | TV-09 | `Retired` | FS-47, M-34 | @@ -1507,7 +1535,7 @@ Files are modelled on [Wycheproof](https://github.com/C2SP/wycheproof) (`testGro | T-81 Repeated randomness | FS-01, FS-29 | | T-83 Ambiguous encodings | FS-08, FS-13, FS-14, FS-66 | | T-84 Chunk-boundary fingerprinting | FS-52, FS-59, FS-62 | -| T-85 Deduplication oracle | FS-55 | +| T-85 Deduplication oracle | FS-55, FS-56 | | T-86 Tree tampering | FS-72 | | T-87 Retention outlives retirement | FS-47, FS-48 | | T-90 Concurrent writers and crashes | FS-87, FS-89 | @@ -1542,6 +1570,7 @@ All three are tracked in [threat-model section 14](threat-model.md#14-open-quest | Version | Date | Change | | --- | --- | --- | +| v0.8 | 2026-11-10 | From the chunking, compression and padding item (E1, E2, E3) in `crypthix-core`; no valid bytes change, but readers reject more. FS-52 states the FastCDC cut rule and the masks and pins `fastcdc` 5.0.0 as the reference; after review, secret-class objects are cut at fixed 1 MiB steps with no gear-table lookup instead of with FastCDC, since the loop leaks bits of the bytes through cache timing and their lengths feed gear-table recovery while they never deduplicate (writers change, readers do not); FS-52 also says Padmé only coarsens chunk sizes and packs hide them. FS-53 says the separation of attacker data from secrets holds only for secret-class objects, and names ordinary objects of mixed trust as a residual (T-40). FS-55 and 2.1 add that equal chunks inside one version of an ordinary object share a keyed ID, which shows how many repeat. FS-53 pins libzstd 1.5.7, says the compressed length is the frame's, requires `payload_len = plain_len` for `comp = 0`, lists the reader's frame checks (window size, not only its log; the unused bit clear and the content size in its shortest field, which libzstd 1.5.7 does not check; acceptance defined as what libzstd 1.5.7 decodes after those header checks, in place of "frames decode under any version"), and makes a compressed chunk of a secret-class object `Padding`. FS-54 gives its check order and makes `payload_len > 2^20` `Limit`. FS-55: `blob_id` is keyed exactly for ordinary objects of two or more chunks, and the reader derives the kind from the manifest; the policy switch for reuse is dropped, since a path that must not reuse chunks is secret class. FS-56 checks keyed IDs only and gives the data-blob open order. FS-28: a seal shorter than its overhead is `Truncated`. TV-07 added, with an independent byte-at-a-time chunker in the generator and hand-built zstd frames, and with secret-class `Chunking` cases (`SecretFixed`; every `Chunking` test now names its `class`); `CutEdges` cases, found by search and checked by the generator, put a cut at the minimum and one past it, at the switch of masks, at the last position tested, and after a pattern only at the maximum, and give an odd last byte that would match if tested; a `pattern` input is a short byte string repeated to `length`; more negative rows in 20.4, among them a raw payload of the wrong length with a wrong blob ID (`Decompress`), a meta blob too short to be a seal or with an all-zero nonce, a block of the reserved type 3 (`Decompress`) and raw and compressed blocks of exactly 128 KiB (`Ok`; the compressed one hand-built, as libzstd's encoder never writes it and libzstd up to 1.5.2 refused it); a frame with a run of more than 1,024 zero bytes is given as `frameHead`, `frameZeros` and `frameTail` | | v0.7 | 2026-11-08 | From the protected key memory item (O1); no bytes change. FS-31's protected memory is the key pool of `crypthix-crypto::secure_mem`. FS-28: no protected memory for the plaintext is a memory error, never `Decrypt` | | v0.6 | 2026-10-30 | From the crypto wrappers item (`crypthix-crypto`). Every nonce that was random is now hedged (FS-29, FS-55, FS-57, FS-60), because the kernel reseeds after a VM restore only with a VM generation ID (FS-01, T-81); readers are unaffected, since Open reads the nonce from the seal. FS-29 also says a failed RNG seals nothing, states that the equality bound is about privacy and the SIV distinctness bound, and FS-25 names CX-AEAD's internal labels as its one exception. FS-28 separates key-wrap labels from data labels and makes an all-zero nonce `ZeroValue`; the path index text says hedged. TV-05 has a hedged pair with replayed randomness and an all-zero nonce. FS-14 also rejects mixed-order public keys (`WeakKey`): `verify_strict` alone accepts them, as Wycheproof tcId 160 to 180 and speccheck case 3 show. TV-04 and TV-05 added; the generator computes them with its own section 7 code (FS-94), and `expect` may name `Commitment` and `AeadTag` in TV-05 only. The RFC and XChaCha draft vectors are transcribed to JSON (20.1). OQ-13 decided: no FIPS mode in format 0 | | v0.5 | 2026-10-29 | From the fuzzing and test-harness item; no valid bytes change. `tests/` is its own workspace, holding the generator and the fuzz targets (20.1). The vector schema is draft 2020-12; `seed` and `zstd` are optional for sets with no randomness or compression, and sets may add header strings (20.2). The seeded generator stream arrives with `crypthix-crypto` (FS-94). External vectors: Wycheproof, BLAKE3 and ed25519-speccheck vendored unchanged; RFC vectors are transcribed with their runners | @@ -1573,6 +1602,7 @@ All three are tracked in [threat-model section 14](threat-model.md#14-open-quest - [Share with Care: Breaking E2EE in Nextcloud (ePrint 2024/546)](https://eprint.iacr.org/2024/546) - [Zero Knowledge (About) Encryption: A Comparative Security Analysis of Three Cloud-based Password Managers (ePrint 2026/058)](https://eprint.iacr.org/2026/058) - [Breaking and Fixing Content-Defined Chunking (ePrint 2025/558)](https://eprint.iacr.org/2025/558) · [ePrint 2025/532](https://eprint.iacr.org/2025/532) +- Fábrega et al., [Injection Attacks Against End-to-End Encrypted Applications](https://arxiv.org/abs/2411.09228) (IEEE S&P 2024) and [Mitigating Injection Attacks against E2EE Applications via View-Based Partitioning](https://www.usenix.org/conference/usenixsecurity25/presentation/fabrega-partitioning) (USENIX Security 2025) **Standards and constructions** - [RFC 9771: Properties of AEAD algorithms](https://datatracker.ietf.org/doc/rfc9771/) · [Bellare–Hoang, committing AE (ePrint 2022/268)](https://eprint.iacr.org/2022/268) · [CTX (ePrint 2022/1260)](https://eprint.iacr.org/2022/1260) diff --git a/docs/project-vision.md b/docs/project-vision.md index 629e72a..3caed15 100644 --- a/docs/project-vision.md +++ b/docs/project-vision.md @@ -442,7 +442,7 @@ Legend: **MVP** = first public release (0.1) · **v1** = 1.0 · **Later** = afte | ID | Feature | Description | Stage | | --- | --- | --- | --- | -| E1 | Content-defined chunking | FastCDC chunking so edits only rewrite changed chunks; enables deduplication within a vault | MVP | +| E1 | Content-defined chunking | FastCDC chunking with a secret per-vault gear table, so edits only rewrite changed chunks; a new version of an ordinary file reuses its unchanged chunks, with deduplication only inside one object, never across files and never for secret files ([format spec FS-55](format-spec.md#104-blobs)) | MVP | | E2 | Compression | zstd per chunk, skipped automatically for already-compressed data | MVP | | E3 | Size padding | Pad compressed chunks to size buckets so file sizes leak less | MVP | | E4 | Authenticated encryption | XChaCha20-Poly1305 with key commitment per chunk; AAD binds vault, object and DEK, and the signed manifest binds order, count and version ([format spec](format-spec.md)) | MVP | diff --git a/docs/style-guide.md b/docs/style-guide.md index 7a88f9b..1af13fd 100644 --- a/docs/style-guide.md +++ b/docs/style-guide.md @@ -23,9 +23,9 @@ The API design rules are **binding for library crates** (everything under `crate | Workspace lints | `Cargo.toml` `[workspace.lints]` | `missing_docs`, `unsafe_code`, `unreachable_pub`, Clippy `all` and `pedantic`, and the Google-aligned lints listed below | | Clippy config | `clippy.toml` | Project words accepted in docs; `unwrap`/`expect` allowed in tests | | Layer check | `cargo xtask check-layers` | Crate dependency rules from [backlog.md](backlog.md#architecture-rules) | -| Release features | `cargo xtask check-features` | No release build enables the test-only `test-rng` or `vectors` features of `crypthix-crypto` ([format spec FS-01](format-spec.md#4-identifiers-primitives-and-randomness)) | -| cargo-deny | `deny.toml` | Licences, advisories, sources, and "only `crypthix-crypto` imports crypto crates", including `getrandom`, `subtle` and `curve25519-dalek` | -| Pre-commit hook | `.githooks/pre-commit`, `xtask/src/pre_commit.rs` | File hygiene, secrets (gitleaks), formatting and Clippy on staged changes; Clippy and tests of the `tests/` workspace when it, `crypthix-types` or `crypthix-crypto` changes | +| Release features | `cargo xtask check-features` | No release build enables the test-only `test-rng` or `vectors` features of `crypthix-crypto` ([format spec FS-01](format-spec.md#4-identifiers-primitives-and-randomness)); no `ZSTD_SYS_USE_PKG_CONFIG` and no `links` override for `zstd` links a system libzstd. Covers only the repository's own build environment (the environment and the repository's `.cargo/config*` files, not a user-level `~/.cargo/config.toml`, `$CARGO_HOME` or `--config`); the runtime version check in `Compressor::new` and in `Decompressor::decode` before its first call into libzstd (`CompressError::Version`) is the backstop | +| cargo-deny | `deny.toml` | Licences, advisories, sources, and "only `crypthix-crypto` imports crypto crates", including `getrandom`, `subtle` and `curve25519-dalek`; `zstd-safe` and `fastcdc` only in `crypthix-core` and the `tests/` tools, `zstd-sys` only through `zstd-safe`, never the `zstd` crate; and the `zstd-sys` and `zstd-safe` features that would link a system or debug libzstd or widen it (`pkg-config`, `non-cargo`, `cmake`, `debug`, `legacy`, `zdict_builder`, `experimental`, `zstdmt`, `seekable`, `bindgen`) | +| Pre-commit hook | `.githooks/pre-commit`, `xtask/src/pre_commit.rs` | File hygiene, secrets (gitleaks), formatting and Clippy on staged changes; Clippy and tests of the `tests/` workspace when it, `crypthix-types`, `crypthix-crypto` or `crypthix-core` changes | | Line endings | `.gitattributes` | LF in the repository on every platform; vendored test vectors kept byte for byte | | Secret scanner config | `.gitleaks.toml` | Default gitleaks rules; only vendored, transcribed and generated vector JSON is allowlisted, file by file | | Test vectors | `cargo xtask vectors --check` | The committed vectors match the generator byte for byte ([format spec FS-94](format-spec.md#20-test-vectors)) | diff --git a/docs/threat-model.md b/docs/threat-model.md index 6c92379..2fd4056 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -4,7 +4,7 @@ | | | | --- | --- | -| Status | v0.6, Phase 1 in progress: Phase 0 baseline after persona review and the format spec; `crypthix-types`, `crypthix-crypto` and protected key memory (O1) landed | +| Status | v0.7, Phase 1 in progress: Phase 0 baseline after persona review and the format spec; `crypthix-types`, `crypthix-crypto`, protected key memory (O1) and chunking, compression and padding (E1, E2, E3) landed | | Owner | Arpan ([@thearpankumar](https://github.com/thearpankumar)) | | Date | 2026-10-29 | | Covers | Phases 1–4 in detail, Phase 5 in outline ([roadmap](project-vision.md#14-roadmap)) | @@ -461,7 +461,7 @@ Generated from the tables below: each threat appears under every boundary its fl | T-37 | **Key substitution.** A backend or insider supplies its own public key or wrapped key and the client trusts it | S | F8 | 2, 14 | 2024 E2EE cloud storage breaks | | T-38 | **Nonce misuse.** XChaCha's 192-bit nonces, hedged with the key, AAD and plaintext (format spec FS-29), are safe. Per-object DEKs rarely reach AES-GCM's usage limits; the real AES-GCM risks are nonce repetition after a VM restore or fork (T-81) and no key commitment (T-36) | I, T | F5 | 2 | — | | T-39 | **Parser bugs on hostile input.** Malformed manifests, shards, log entries or tokens from a backend crash or confuse the daemon | T, D | F8 | 2 | — | -| T-40 | **Compression size oracle.** Compressing attacker-influenced data together with secrets leaks the secret through ciphertext size | I | F8 | 1, 2 | CRIME, BREACH | +| T-40 | **Compression size oracle.** Compressing attacker-influenced data together with secrets leaks the secret through ciphertext size | I | F8 | 1, 2 | CRIME, BREACH; injection attacks on E2EE backups (Fábrega et al., IEEE S&P 2024) | | T-78 | **Downgrade.** A backend rewrites objects with an older format version or a weaker suite ("XChaCha or AES-GCM", "SHA-256 or BLAKE3") to drop AAD fields; or the user is moved to an older, vulnerable CryptHix release | T | F8, F13 | 2, 16 | Seafile downgrade (2024) | | T-82 | **Hybrid KEM pitfalls.** A naive combiner of X25519 and ML-KEM shared secrets; KEM wraps that do not authenticate the sender (anyone can wrap a KEK to a device); timing leaks in ML-KEM code | S, I | F8, F9 | 2, 14 | KyberSlash (2024) | | T-83 | **Ambiguous encodings.** Non-canonical encodings, one signing key across manifests, log entries and events without a context label, non-strict Ed25519 verification, and a Merkle tree without leaf and node separation allow type confusion and second preimages | T, S | F5, F8 | 2 | RUSTSEC-2022-0093; RFC 6962 | @@ -726,7 +726,7 @@ These have no feature ID. They attach to existing backlog items and are checked | T-28 | M | SP-C8 | Accept (R-4) | Recommend a device or recovery share as the second factor | — | P3 | | T-29 | M | SP-C8 | Mitigate | M-19, M-16 | Hardening | P3 | | T-30 | M | SP-C1 | Mitigate | M-11; IOMMU (AS-1) | Hardening | P3 | -| T-31 | H | SP-B7 | Mitigate | O1 (landed in P1, `crypthix-crypto::secure_mem`): every key in `memfd_secret` pages where the kernel has them (refused to `PTRACE_PEEKDATA`, `process_vm_readv` and `/proc//mem`, though a process allowed to `ptrace` can still inject code), else `mlock`ed, else dump-excluded, never below the app's minimum; opened plaintext, passphrases and Argon2id memory `mlock`ed, else dump-excluded, never on the heap on Linux and never in secret pages (pinned-page I/O such as `O_DIRECT` and FUSE `splice` refuses them with `EFAULT`; full reasons in the [`secure_mem` module docs](../crates/foundation/crypto/src/secure_mem/mod.rs)); all of it `MADV_DONTDUMP` and `MADV_DONTFORK`, behind guard pages and wiped on free. `MADV_DONTDUMP` is what keeps it out of piped `core_pattern` dumps, which ignore `RLIMIT_CORE`. Keys and buffers lock separate shares of `RLIMIT_MEMLOCK`, with a reserve for every key page, so plaintext cannot starve keys; that reserve is fixed before anything locks, by `init` or else the defaults at the first key or buffer, after which `init` fails rather than get less, and `status` never sets it; secret pages are faulted in through the raw `getrandom` system call (not glibc's, which may write from the vDSO in user mode), so a kernel that charges them past a per-user limit makes the key arena fall back a level rather than raise `SIGBUS`; this relies on copying system calls reaching secret pages, and an `EFAULT` there is reported as `LockLimit`. Kernels with the CVE-2026-93243 fix charge secret pages to the user when they are faulted in, and development and CI runner kernels predate it, so that path is checked by the `kernel-test` CI job ([`kernel-test.yml`](../.github/workflows/kernel-test.yml)), which boots a kernel with the fix (Ubuntu mainline 7.3.3) and one without it (6.12.112) and runs the `crypthix-crypto` tests in each. Keys do not survive `fork` without `exec`: on Linux the child cannot read them (told by a `MADV_WIPEONFORK` generation marker, not its pid) and starts its own pool and lock budget. Off Linux (until A11, A12) and under Miri it is all plain heap, wiped on free. Key arenas are never unmapped, so a process with a key in secret memory blocks hibernation until it exits. Left: `PR_SET_DUMPABLE=0`, `LimitMEMLOCK` and the minimum level (OQ-18) with the daemon; copies left by moves and stack spills, short-lived and not reliably wiped; the working state of the cipher and MAC code on the stack, wiped on drop: CX-AEAD's `K_enc` in the XChaCha20-Poly1305 state for a whole seal or open, `K_n` in the keyed BLAKE3 state for a seal's nonce, the HKDF PRK in its HMAC state, and the expanded Ed25519 key; hibernation images of locked pages (AS-6, M-11); M-15, M-29 | Crypto (O1), Hardening | P1, P2 | +| T-31 | H | SP-B7 | Mitigate | O1 (landed in P1, `crypthix-crypto::secure_mem`): every key in `memfd_secret` pages where the kernel has them (refused to `PTRACE_PEEKDATA`, `process_vm_readv` and `/proc//mem`, though a process allowed to `ptrace` can still inject code), else `mlock`ed, else dump-excluded, never below the app's minimum; opened plaintext, passphrases and Argon2id memory `mlock`ed, else dump-excluded, never on the heap on Linux and never in secret pages (pinned-page I/O such as `O_DIRECT` and FUSE `splice` refuses them with `EFAULT`; full reasons in the [`secure_mem` module docs](../crates/foundation/crypto/src/secure_mem/mod.rs)); all of it `MADV_DONTDUMP` and `MADV_DONTFORK`, behind guard pages and wiped on free. `MADV_DONTDUMP` is what keeps it out of piped `core_pattern` dumps, which ignore `RLIMIT_CORE`. Keys and buffers lock separate shares of `RLIMIT_MEMLOCK`, with a reserve for every key page, so plaintext cannot starve keys; that reserve is fixed before anything locks, by `init` or else the defaults at the first key or buffer, after which `init` fails rather than get less, and `status` never sets it; secret pages are faulted in through the raw `getrandom` system call (not glibc's, which may write from the vDSO in user mode), so a kernel that charges them past a per-user limit makes the key arena fall back a level rather than raise `SIGBUS`; this relies on copying system calls reaching secret pages, and an `EFAULT` there is reported as `LockLimit`. Kernels with the CVE-2026-93243 fix charge secret pages to the user when they are faulted in, and development and CI runner kernels predate it, so that path is checked by the `kernel-test` CI job ([`kernel-test.yml`](../.github/workflows/kernel-test.yml)), which boots a kernel with the fix (Ubuntu mainline 7.3.3) and one without it (6.12.112) and runs the `crypthix-crypto` tests in each. Keys do not survive `fork` without `exec`: on Linux the child cannot read them (told by a `MADV_WIPEONFORK` generation marker, not its pid) and starts its own pool and lock budget. Off Linux (until A11, A12) and under Miri it is all plain heap, wiped on free. Key arenas are never unmapped, so a process with a key in secret memory blocks hibernation until it exits. Left: `PR_SET_DUMPABLE=0`, `LimitMEMLOCK` and the minimum level (OQ-18) with the daemon; copies left by moves and stack spills, short-lived and not reliably wiped; the working state of the cipher and MAC code on the stack, wiped on drop: CX-AEAD's `K_enc` in the XChaCha20-Poly1305 state for a whole seal or open, `K_n` in the keyed BLAKE3 state for a seal's nonce, the HKDF PRK in its HMAC state, and the expanded Ed25519 key; hibernation images of locked pages (AS-6, M-11); zstd's working memory in `crypthix-core`, on the C heap (R-26); M-15, M-29 | Crypto (O1), Hardening | P1, P2 | | T-32 | H | SP-C8 | Mitigate | M-14 | Crypto and formats | P1 format, P4 | | T-33 | M | SP-C8 | Mitigate | M-18 | Crypto and formats | P4 | | T-34 | M | SP-C7 | Mitigate | M-14 | Crypto and formats | P1 format, P4 | @@ -735,7 +735,7 @@ These have no feature ID. They attach to existing backlog items and are checked | T-37 | H | SP-C2 | Mitigate | `vault_id` pins the master key (format spec FS-02); every public and wrapped key signed back to the vault or admin root; key material from a backend never trusted | Crypto and formats | P1, P4, P5 | | T-38 | L | SP-C1 | Mitigate | Hedged XChaCha nonces with a per-nonce subkey (CX-AEAD); synthetic nonces for shard headers | Crypto and formats | P1 | | T-39 | M | SP-C2 | Mitigate | `cargo-fuzz` target on every parser | Crypto and formats | P0, P1 | -| T-40 | L | SP-C1 | Mitigate, accept rest (R-5) | Per-chunk compression with E3 padding; no mixing of attacker data and secrets in one chunk | Crypto and formats | P1 | +| T-40 | L | SP-C1 | Mitigate, accept rest (R-5) | Per-chunk compression with E3 padding. E2 (landed in P1, `crypthix-core`): each chunk is its own zstd frame, with no dictionary and no history from other chunks, padded with Padmé (E3); chunks of secret-class objects are never compressed, and a reader rejects a compressed one as `Padding` ([format spec FS-53, FS-54](format-spec.md#102-compression)). That keeps attacker data and secrets out of one compression context only when every secret is in a secret-class object. Left: an ordinary object whose content mixes trust levels (a mail store, a chat or app SQLite database, a browser profile) can hold injected data and a secret in one chunk, the setting of the injection attacks of [Fábrega et al. (IEEE S&P 2024)](https://arxiv.org/abs/2411.09228), whose fix in the application is view-based partitioning ([USENIX Security 2025](https://www.usenix.org/conference/usenixsecurity25/presentation/fabrega-partitioning)). Padmé only raises the number of injections such an attack needs; size-class packs (encrypt pipeline item, FS-59) are what hide the sizes it reads. The recourse is a per-path policy (P2) that makes such paths secret class or stores them uncompressed. The rating stays L: the attack needs both a way to inject into a synced file and a view of the backend, many injections and observed commits per guessed secret, and until packs land it reads sizes through Padmé's steps (R-5) | Crypto and formats | P1, P2 | | T-41 | H | SP-C5 | Mitigate (W5) | E18 counter and log heads | Restore | P4 | | T-42 | M | SP-C5 | Mitigate | E18, maximum head age per backend | Restore | P4 | | T-43 | M | SP-C5 | Mitigate | Signed vault root commits to every tree (format spec FS-78); snapshot roots and log head later | Restore | P1, P3, P4 | @@ -779,8 +779,8 @@ These have no feature ID. They attach to existing backlog items and are checked | T-81 | M | SP-C1 | Mitigate | M-36 | Crypto and formats | P1 | | T-82 | M | SP-C9 | Mitigate | M-38 | Crypto and formats | P4 | | T-83 | M | SP-C2 | Mitigate | M-37 | Crypto and formats | P1 | -| T-84 | H | SP-C11 | Mitigate | M-39 | Crypto and formats | P1 | -| T-85 | M | SP-C11 | Mitigate, accept rest (R-5) | Blob IDs keyed per object; no deduplication for secret files (format spec FS-55) | Crypto and formats | P1 | +| T-84 | H | SP-C11 | Mitigate, accept rest (R-5) | M-39. E1 (landed in P1, `crypthix-core`): FastCDC with a gear table keyed per vault from `chunker_seed` ([format spec FS-52](format-spec.md#101-chunking)). A keyed gear table alone does not hide boundaries: such tables have been recovered from observed chunk sizes, Bupstash's keyed gear included ([ePrint 2025/558](https://eprint.iacr.org/2025/558), Truong, Merz, Scarlata, Günther and Paterson, CCS 2025; [ePrint 2025/532](https://eprint.iacr.org/2025/532)). The design therefore assumes the seed may leak, and keeps the gear table in a `SecretBuf` (locked plaintext memory where the limit allows, not the secret pages keys use). Size-class packs (encrypt pipeline item, FS-59) are what hide the sizes those attacks need; Padmé on every chunk (E3, FS-54) does not hide them but coarsens them: a 256 KiB chunk rounds to 8 KiB steps and a 1 MiB one to 32 KiB, so about 5 bits of each chunk's length stay visible. Secret-class objects are not cut with the gear table at all but at fixed 1 MiB steps ([format spec FS-52](format-spec.md#101-chunking)): the FastCDC loop indexes the table with plaintext bytes and exits early at a cut, which a process sharing the CPU cache can time, and their lengths would feed table recovery, while they never deduplicate. A chunker built on a PRF (Chk-PHTE) was considered and not taken for format 0. Left: chunk count and order, and each blob's Padmé size, until packs land; whatever sizes packs still show (R-5) | Crypto and formats | P1 | +| T-85 | M | SP-C11 | Mitigate, accept rest (R-5) | Blob IDs keyed per object; no deduplication for secret files (format spec FS-55). Landed in P1 (`crypthix-core`): an ID is keyed exactly for an ordinary object of two or more chunks and random for secret-class and single-chunk objects, so nothing of theirs is reused; writer and reader derive the kind from the manifest's class and chunk count, and the reader recomputes keyed IDs ([format spec FS-55, FS-56](format-spec.md#104-blobs)) | Crypto and formats | P1 | | T-86 | H | SP-C10 | Mitigate | M-40 | Restore | P1, P3 | | T-87 | H | SP-C6 | Mitigate, accept rest (R-19) | M-41 | Rotation safety | P4 | | T-88 | H | SP-B5 | Mitigate, accept rest (R-20) | M-42 | Restore | P3, P4 | @@ -882,7 +882,7 @@ A window is a known gap between when a feature ships and when the feature that p | R-2 | Agent detection is best effort; a determined agent or an in-editor assistant can avoid it | T-05, T-14 | §8 AI agent row | | R-3 | In Degraded mode, injection into allowed programs stays possible | T-08 | §17 "Root malware can eventually win" | | R-4 | A firmware TPM can be fault-attacked; a stolen laptop then depends on the passphrase or a second share | T-28 | §8 thief row | -| R-5 | Shard counts, sizes, timing and push sizes leak | T-40, T-59 | §17 "Metadata leaks remain" | +| R-5 | Shard counts, sizes, timing and push sizes leak; per-blob Padmé sizes (about 5 bits of each chunk's length) until packs land (FS-59) | T-40, T-59, T-84 | §17 "Metadata leaks remain" | | R-6 | Plaintext an allowed program read can be sent anywhere | T-12 | §17 "Allowed programs see plaintext" | | R-7 | Secrets in environment variables, history or clipboard are outside the vault | T-13 | — (new in §17) | | R-8 | Killing or unmounting CryptHix denies service; it fails closed but work stops | T-16 | §8 malware row | @@ -903,6 +903,7 @@ A window is a known gap between when a feature ships and when the feature that p | R-23 | `/proc//fd` and `maps` of allowed programs show which secret paths are open to same-UID processes | T-65 | — | | R-24 | In Degraded mode, forced crash dumps of allowed programs stay possible | T-64 | §17 BPF-LSM limit | | R-25 | In teams, guard data is personal data about members | T-97 | — | +| R-26 | zstd's working memory, which holds pieces of chunk plaintext (the compression context keeps literals and match-finder hash tables, the decompression context decoded literals in its `litExtraBuffer`), is on the C heap: not wiped on free, not excluded from core dumps, not locked (so it can be swapped out) and not `MADV_DONTFORK` (so a forked child gets a copy). The encrypt pipeline item plans a `ZSTD_customMem` allocator backed by `secure_mem` in `crypthix-crypto`, which may use `unsafe` | T-31 | — | --- @@ -959,6 +960,7 @@ Decisions already taken (2026-10-29): the daemon runs as its own system user (M- | 2026-10-30 | P0 | Out-of-cycle review for format spec v0.4 and v0.5 and the fuzzing and test-harness item | No new threats or flows. M-29 and M-44 now name what landed in P0 (fuzz targets for the `crypthix-types` parsers, the `crypthix-testkit` crash-point harness) and what waits for P1 and P2; OQ-16 partly answered (SLIP-39). Backlog checked against 11.1, 12.2 and 14: every M-, window and open question is cited by the item it lands with | | 2026-10-30 | P1 | Out-of-cycle review for the crypto wrappers item and format spec v0.6 | No new threats; T-81 and M-36 now state that reseeding after a VM restore needs `vmgenid`, so every random nonce becomes hedged (format spec FS-29), leaving only repeated random IDs and keys as residual risk. Key wraps and data seals use separate AAD labels, so a wrapped key cannot be read out or forged through the data API (rule 9). Checklist 15.2: (1) no new data flow or boundary, the crate runs inside the daemon's existing boundaries; (2) no new STRIDE findings; (3) T-36, T-38, T-81 and T-83 keep their mitigations, tests (TV-01, TV-04, TV-05, fuzz targets `cx_open` and `verifying_key`) and phase; (4) 12.3 is unchanged, crypto does not depend on the hardening mode; (5) vision 8 and 17 still agree. M-9, M-36 and M-37 now name what landed in `crypthix-crypto`; M-37 and FS-14 also reject mixed-order Ed25519 keys, which `verify_strict` alone accepts (Wycheproof tcId 160 to 180, speccheck case 3). OQ-13 answered: no FIPS mode in format 0. TV-04 and TV-05 are computed by a second implementation in the vector generator | | 2026-11-08 | P1 | Out-of-cycle review for the protected key memory item (O1) | No new threats. T-31 now names what O1 landed and what is left: keys in `memfd_secret` pages (unreadable through `PTRACE_PEEKDATA`, `process_vm_readv` and `/proc//mem`, though a process allowed to `ptrace` can still inject code), falling back to `mlock`ed and then dump-excluded memory, with the level reported by `secure_mem::status` for the hardening mode (M-13); plaintext never in secret pages, since pinned-page I/O (`O_DIRECT`, FUSE `splice`) fails on them with `EFAULT` and each costs direct-map and `RLIMIT_MEMLOCK` pages; copying calls such as `write` do reach them. Checklist 15.2: (1) no new data flow; key memory stays inside the daemon boundary (TB-2/3), as the diagram already shows; (2) no new STRIDE findings; `memfd_secret` blocks hibernation, already in AS-6 and M-11; (3) T-31 keeps its risk and phase, with tests for each level (smaps flags, `/proc/self/mem`, a zero `RLIMIT_MEMLOCK`); (4) 12.3 unchanged; (5) vision 8 and 17 still agree. OQ-18 added: the daemon's minimum level. A multi-agent review (security, tests, code quality, scenario coverage, Windows and macOS) then changed the code before it landed: separate lock shares for keys and buffers, prefaulting through the raw `getrandom` system call instead of plain writes that could `SIGBUS`, the fork rule with a `MADV_WIPEONFORK` generation marker instead of the pid, no heap fallback for plaintext on Linux, errors instead of aborts when no buffer can be mapped (`OpenError::Memory`, `VerifyError::Memory`, `MemError::TooLarge`), an `init` that keeps its minimum when it fails and is refused after the first key or buffer (which set up the defaults) rather than silently get less, a `status` that sets up nothing, and `Fallback` reasons for keys and buffers in `status`; T-31 says so. Format spec v0.7: FS-31's protected memory is the `secure_mem` key pool | +| 2026-11-10 | P1 | Out-of-cycle review for the chunking, compression and padding item (E1, E2, E3) | No new threats. T-84 now says that a keyed gear table alone has been broken from observed chunk sizes (ePrint 2025/558, which includes Bupstash's keyed gear, and ePrint 2025/532), so the seed is assumed to leak and Padmé and packs hide the sizes; a PRF chunker (Chk-PHTE) was considered and not taken for format 0. T-40 and T-85 name what landed: one zstd frame per chunk with no dictionary, no compression for the secret class, and blob IDs keyed only for ordinary objects of two or more chunks. R-26 added: zstd's working memory is on the C heap, not wiped and not dump-excluded, since `zstd-safe` has no way to give it a workspace without `unsafe`; the encrypt pipeline item moves it to protected memory. Checklist 15.2: (1) no new data flow; chunking and compression run inside the daemon boundary before encryption (F8); (2) no new STRIDE findings; (3) T-40, T-84 and T-85 keep their risk and phase, with TV-07 and the fuzz targets `inner_plaintext`, `decompress`, `data_blob_open` and `chunker`; (4) 12.3 unchanged; (5) vision 8 and 17 still agree, and vision E1 now says deduplication stays inside one object. Format spec v0.8: the FastCDC cut rule, the reader's zstd frame checks, the inner-plaintext and data-blob check order, and keyed blob IDs exactly for ordinary objects of two or more chunks. After review: secret-class objects are cut at fixed 1 MiB steps with no gear-table lookup (FS-52), since the FastCDC loop leaks bits of plaintext bytes through cache timing and secret chunk lengths would feed T-84's table recovery while secret objects never deduplicate; T-84 says Padmé only coarsens chunk sizes (about 5 bits per chunk) and packs hide them, and R-5 adds per-blob Padmé sizes until packs land; T-40 names ordinary objects of mixed trust (mail stores, chat and app databases, browser profiles) as a residual in the setting of Fábrega et al.'s injection attacks, with a per-path policy (P2) as the recourse, keeping risk L; R-26 adds that zstd's contexts are neither locked nor `MADV_DONTFORK`, with a `ZSTD_customMem` allocator over `secure_mem` planned | ### 15.4 Changelog @@ -970,6 +972,7 @@ Decisions already taken (2026-10-29): the daemon runs as its own system user (M- | v0.4 | 2026-10-30 | Format spec v0.4 and v0.5 and the fuzzing and test-harness item (see review log) | | v0.5 | 2026-10-30 | Crypto wrappers item and format spec v0.6 (see review log) | | v0.6 | 2026-11-08 | Protected key memory item and format spec v0.7 (see review log) | +| v0.7 | 2026-11-10 | Chunking, compression and padding item and format spec v0.8 (see review log) | --- @@ -1038,6 +1041,6 @@ The vision names compliance teams as users ([vision 3](project-vision.md#3-who-i - Linux: [proc_pid_exe(5)](https://man7.org/linux/man-pages/man5/proc_pid_exe.5.html) · [mount.fuse3(8)](https://man7.org/linux/man-pages/man8/mount.fuse3.8.html) · [FUSE I/O modes](https://docs.kernel.org/filesystems/fuse/fuse-io.html) · [FUSE passthrough](https://docs.kernel.org/filesystems/fuse/fuse-passthrough.html) · [core(5)](https://man7.org/linux/man-pages/man5/core.5.html) · [fanotify(7)](https://man7.org/linux/man-pages/man7/fanotify.7.html) · [unix(7) SO_PEERPIDFD](https://man7.org/linux/man-pages/man7/unix.7.html) · [Qualys: Ubuntu user-namespace restriction bypasses](https://blog.qualys.com/vulnerabilities-threat-research/2025/03/27/qualys-tru-discovers-three-bypasses-of-ubuntu-unprivileged-user-namespace-restrictions) · [vmgenid RNG reseeding (LWN)](https://lwn.net/Articles/887207/) - Agents and editors: [Check Point: CVE-2025-59536 and Claude Code project files](https://research.checkpoint.com/2026/rce-and-api-token-exfiltration-through-claude-code-project-files-cve-2025-59536/) · [Check Point: Codex CLI CVE-2025-61260](https://research.checkpoint.com/2025/openai-codex-cli-command-injection-vulnerability/) · [CVE-2025-55284 write-up](https://jmason.ie/2025/08/25/161304a.html) · [GlassWorm (Truesec)](https://www.truesec.com/hub/blog/glassworm-self-propagating-vscode-extension) · [Amazon Q extension prompt (TechRadar)](https://www.techradar.com/pro/hacker-adds-potentially-catastrophic-prompt-to-amazons-ai-coding-service-to-prove-a-point) · [Dev Containers credential sharing](https://code.visualstudio.com/remote/advancedcontainers/sharing-git-credentials) · [Calif: abusing developer trust](https://blog.calif.io/p/vibe-hacking-abusing-developer-trust) · [Claude Code `.claude` directory](https://code.claude.com/docs/en/claude-directory) · [Claude Code sandboxing](https://code.claude.com/docs/en/sandboxing) · [postmark-mcp](https://thehackernews.com/2025/09/first-malicious-mcp-server-found.html) · [Slopsquatting (CSA)](https://labs.cloudsecurityalliance.org/research/csa-research-note-slopsquatting-ai-supply-chain-20260419/) - Supply chain: [crates.io malicious crates faster_log and async_println](https://blog.rust-lang.org/2025/09/24/crates.io-malicious-crates-fasterlog-and-asyncprintln) · [Compromised GitHub Actions (2026)](https://thehackernews.com/2026/09/compromised-github-actions-came-back.html) -- Cryptography: [Chunking attacks on deduplicating storage (ePrint 2025/558)](https://eprint.iacr.org/2025/558) · [ePrint 2025/532](https://eprint.iacr.org/2025/532) · [Harnik et al.: side channels in deduplication](https://doi.org/10.1109/MSP.2010.187) · [Ed25519 validation criteria](https://eprint.iacr.org/2020/1244) · [RUSTSEC-2022-0093](https://rustsec.org/advisories/RUSTSEC-2022-0093.html) · [RFC 6962 Merkle hashing](https://www.rfc-editor.org/rfc/rfc6962#section-2.1) · [RFC 5869 HKDF](https://www.rfc-editor.org/rfc/rfc5869#section-3.2) · [Key commitment CMT-4](https://eprint.iacr.org/2022/268) · [X-Wing paper](https://eprint.iacr.org/2024/039) · [Trail of Bits: Shamir pitfalls](https://blog.trailofbits.com/2021/12/21/disclosing-shamirs-secret-sharing-vulnerabilities-and-announcing-zkdocs/) · [Biscuit specification](https://doc.biscuitsec.org/reference/specifications) · [Wycheproof](https://github.com/C2SP/wycheproof) +- Cryptography: [Chunking attacks on deduplicating storage (ePrint 2025/558)](https://eprint.iacr.org/2025/558) · [ePrint 2025/532](https://eprint.iacr.org/2025/532) · [Injection attacks against E2EE applications (Fábrega et al., IEEE S&P 2024)](https://arxiv.org/abs/2411.09228) · [View-based partitioning (Fábrega et al., USENIX Security 2025)](https://www.usenix.org/conference/usenixsecurity25/presentation/fabrega-partitioning) · [Harnik et al.: side channels in deduplication](https://doi.org/10.1109/MSP.2010.187) · [Ed25519 validation criteria](https://eprint.iacr.org/2020/1244) · [RUSTSEC-2022-0093](https://rustsec.org/advisories/RUSTSEC-2022-0093.html) · [RFC 6962 Merkle hashing](https://www.rfc-editor.org/rfc/rfc6962#section-2.1) · [RFC 5869 HKDF](https://www.rfc-editor.org/rfc/rfc5869#section-3.2) · [Key commitment CMT-4](https://eprint.iacr.org/2022/268) · [X-Wing paper](https://eprint.iacr.org/2024/039) · [Trail of Bits: Shamir pitfalls](https://blog.trailofbits.com/2021/12/21/disclosing-shamirs-secret-sharing-vulnerabilities-and-announcing-zkdocs/) · [Biscuit specification](https://doc.biscuitsec.org/reference/specifications) · [Wycheproof](https://github.com/C2SP/wycheproof) - Storage: [Dropbox data governance](https://help.dropbox.com/accounts-billing/plans-upgrades/data-governance) · [Google Drive revisions](https://developers.google.com/drive/manage-revisions) · [Google Drive API terms](https://developers.google.com/drive/terms) · [Restricted-scope verification](https://developers.google.com/identity/protocols/oauth2/production-readiness/restricted-scope-verification) · [Drive API limits](https://developers.google.com/drive/api/guides/limits) · [Backblaze B2 Object Lock](https://www.backblaze.com/docs/cloud-storage-enable-and-manage-lock-features) · [M-Trends 2025](https://cloud.google.com/blog/topics/threat-intelligence/m-trends-2025/) · [Codefinger S3 ransomware](https://www.bleepingcomputer.com/news/security/ransomware-abuses-amazon-aws-feature-to-encrypt-s3-buckets/) · [Meta on silent data corruption](https://engineering.fb.com/2025/07/22/data-infrastructure/how-meta-keeps-its-ai-hardware-reliable/) · [S3 no charges for unauthorised errors](https://aws.amazon.com/about-aws/whats-new/2024/08/amazon-s3-no-charges-several-http-error-codes) - Compliance: [PCI DSS 4.0 new requirements (BDO)](https://www.bdo.com/getmedia/7a423c2a-ec5d-45c1-b2d0-8a5030d0fa80/ASSR-ASP-PCI-4-0-New-Requirements.pdf) · [HHS HITECH guidance](https://www.foulston.com/uploads/HHS_Issues_HITECH_Guidance.pdf) · [EAR 2021 encryption rule (Goodwin)](https://www.goodwinlaw.com/en/insights/publications/2021/03/03_31-spring-cleaning-us-department-of-commerce) · [OpenSSF Best Practices: cryptography criteria](https://www.bestpractices.dev/en/criteria/0) From 63ef2cfc8b1414defd3169d3338d9bf6573e0dc0 Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 15:55:53 +0530 Subject: [PATCH 07/15] test(core): bound every chunk drain so a non-ending chunker mutant fails fast instead of exhausting memory --- .cargo/mutants.toml | 8 ++++ crates/engine/core/src/chunk/chunks.rs | 13 ++--- crates/engine/core/src/chunk/cut.rs | 13 +++-- .../engine/core/src/chunk/stream_chunker.rs | 39 +++++++++++++-- crates/engine/core/src/test_data.rs | 47 ++++++++++++++++++- crates/engine/core/tests/tv07.rs | 28 ++++++++++- tests/fuzz/harness/src/chunker.rs | 24 +++++++++- 7 files changed, 151 insertions(+), 21 deletions(-) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index bebc495..05ba081 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -10,4 +10,12 @@ exclude_re = [ # breaks on hint 0 or on no progress never shows; after the frame a further call reads # nothing and returns a non-zero hint. Both checks stay as defence in depth. 'replace == with != in stream$', + # cut_with: capping a remainder of exactly the maximum at the maximum changes nothing, and + # neither does lowering the centre to a remainder shorter than the average: a split past the + # end of the pairs falls back to taking them all as strict pairs, as a split at the end does. + 'replace > with >= in cut_with$', + 'replace < with (==|<=) in cut_with$', + # StreamChunker::refill: `start <= end <= window.len()` always holds, so the defensive check + # that fails instead of panicking never fires, whichever operator joins its halves. + 'replace \|\| with && in StreamChunker<.*>::refill$', ] diff --git a/crates/engine/core/src/chunk/chunks.rs b/crates/engine/core/src/chunk/chunks.rs index 370f6b7..9da04c5 100644 --- a/crates/engine/core/src/chunk/chunks.rs +++ b/crates/engine/core/src/chunk/chunks.rs @@ -119,7 +119,7 @@ mod tests { use super::*; use crate::test_data::gear_table as table; - use crate::test_data::pseudo_random; + use crate::test_data::{chunk_ranges, pseudo_random}; const CLASSES: [ObjectClass; 2] = [ObjectClass::Ordinary, ObjectClass::Secret]; @@ -140,9 +140,8 @@ mod tests { for class in CLASSES { for len in [0, 1, params.min, params.max, params.max + 1, 6_000] { let data = pseudo_random(3, len); - let chunks = Chunks::with_params(&gear, class, &data, params); - let count = chunks.clone().count(); - let shape = chunks.object_shape(); + let count = chunk_ranges(&gear, class, &data, params).len(); + let shape = Chunks::with_params(&gear, class, &data, params).object_shape(); assert_eq!(shape.is_single(), count <= 1, "{class:?} {len}"); assert_eq!(shape.class(), class); } @@ -170,8 +169,7 @@ mod tests { fn chunks_tile_the_data_within_the_size_bounds(seed in 1u8.., data in vec(any::(), 0..6_000)) { let gear = table(seed); let params = ChunkParams::SCALED; - let ranges: Vec> = - Chunks::with_params(&gear, ObjectClass::Ordinary, &data, params).collect(); + let ranges = chunk_ranges(&gear, ObjectClass::Ordinary, &data, params); let mut next = 0; for (i, range) in ranges.iter().enumerate() { prop_assert_eq!(range.start, next); @@ -197,8 +195,7 @@ mod tests { ) { let gear = table(seed); let params = ChunkParams::SCALED; - let ranges: Vec> = - Chunks::with_params(&gear, ObjectClass::Secret, &data, params).collect(); + let ranges = chunk_ranges(&gear, ObjectClass::Secret, &data, params); let expected: Vec> = (0..data.len()) .step_by(params.max) .map(|start| start..data.len().min(start + params.max)) diff --git a/crates/engine/core/src/chunk/cut.rs b/crates/engine/core/src/chunk/cut.rs index 25fe5ab..5082b13 100644 --- a/crates/engine/core/src/chunk/cut.rs +++ b/crates/engine/core/src/chunk/cut.rs @@ -94,10 +94,9 @@ mod tests { use proptest::prelude::{Just, Strategy, any, prop_assert_eq, prop_oneof, proptest}; use super::*; - use crate::chunk::Chunks; use crate::limits::{MAX_CHUNK, MIN_CHUNK}; use crate::test_data::gear_table as table; - use crate::test_data::pseudo_random; + use crate::test_data::{chunk_ranges, pseudo_random}; /// The chunk lengths fastcdc cuts from `data` with `gear`'s words. fn fastcdc_lengths(gear: &GearTable, data: &[u8], params: &ChunkParams) -> Vec { @@ -125,7 +124,8 @@ mod tests { } fn our_lengths(gear: &GearTable, data: &[u8], params: &ChunkParams) -> Vec { - Chunks::with_params(gear, ObjectClass::Ordinary, data, *params) + chunk_ranges(gear, ObjectClass::Ordinary, data, *params) + .into_iter() .map(|range| range.len()) .collect() } @@ -217,10 +217,13 @@ mod tests { let data = pseudo_random(4, 8 << 20); let mut edited = data.clone(); edited[4 << 20] ^= 1; - let before: Vec<&[u8]> = Chunks::new(&gear, ObjectClass::Ordinary, &data) + let params = ChunkParams::FORMAT_0; + let before: Vec<&[u8]> = chunk_ranges(&gear, ObjectClass::Ordinary, &data, params) + .into_iter() .map(|r| &data[r]) .collect(); - let after: Vec<&[u8]> = Chunks::new(&gear, ObjectClass::Ordinary, &edited) + let after: Vec<&[u8]> = chunk_ranges(&gear, ObjectClass::Ordinary, &edited, params) + .into_iter() .map(|r| &edited[r]) .collect(); let changed = after.iter().filter(|chunk| !before.contains(chunk)).count(); diff --git a/crates/engine/core/src/chunk/stream_chunker.rs b/crates/engine/core/src/chunk/stream_chunker.rs index f9606af..5b13c4d 100644 --- a/crates/engine/core/src/chunk/stream_chunker.rs +++ b/crates/engine/core/src/chunk/stream_chunker.rs @@ -195,9 +195,8 @@ mod tests { use proptest::prelude::{any, prop_assert_eq, proptest}; use super::*; - use crate::chunk::Chunks; use crate::test_data::gear_table as table; - use crate::test_data::pseudo_random; + use crate::test_data::{chunk_ranges, most_chunks, pseudo_random}; /// A reader that returns at most the next step's bytes per call, and `Interrupted` where a /// step is 0. @@ -221,7 +220,9 @@ mod tests { } } - /// Every chunk as its offsets, index, last flag and bytes. + /// Every chunk of the `total` bytes of `reader` as its offsets, index, last flag and bytes. + /// Fails at once on an empty chunk or more than [`most_chunks`], so a chunker that stops + /// advancing cannot loop on. fn streamed( gear: &GearTable, class: ObjectClass, @@ -229,11 +230,18 @@ mod tests { params: ChunkParams, total: usize, ) -> Vec<(Range, u64, bool, Vec)> { + let most = most_chunks(class, ¶ms, total); let mut chunker = StreamChunker::with_params(gear, class, reader, params).expect("window"); let mut out = Vec::new(); let mut offset = 0; while let Some(chunk) = chunker.next_chunk().expect("reads") { let len = chunk.bytes().len(); + assert!( + out.len() < most && len > 0, + "chunk {} of {len} bytes at {offset} of {total}, at most {most} expected: the \ + chunker is not advancing", + out.len() + ); out.push(( offset..offset + len, chunk.index(), @@ -260,7 +268,7 @@ mod tests { call: 0, }; let streamed = streamed(gear, class, reader, params, data.len()); - let in_memory: Vec> = Chunks::with_params(gear, class, data, params).collect(); + let in_memory = chunk_ranges(gear, class, data, params); assert_eq!(streamed.len(), in_memory.len()); for (i, ((range, index, is_last, bytes), expected)) in streamed.iter().zip(&in_memory).enumerate() @@ -304,6 +312,29 @@ mod tests { ); } + #[test] + fn the_window_holds_two_maximum_chunks() { + /// Records the size of the buffer each read is given, and reports the end. + struct Sizes(Vec); + impl Read for Sizes { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.0.push(buf.len()); + Ok(0) + } + } + let gear = table(1); + let params = ChunkParams::SCALED; + let mut chunker = + StreamChunker::with_params(&gear, ObjectClass::Ordinary, Sizes(Vec::new()), params) + .expect("window"); + assert!(chunker.next_chunk().expect("reads").is_none()); + assert_eq!( + chunker.reader.0, + [2 * params.max], + "the first read fills the window" + ); + } + #[test] fn reader_errors_are_returned() { struct Broken; diff --git a/crates/engine/core/src/test_data.rs b/crates/engine/core/src/test_data.rs index 1d106dd..21f4590 100644 --- a/crates/engine/core/src/test_data.rs +++ b/crates/engine/core/src/test_data.rs @@ -1,10 +1,13 @@ //! Deterministic inputs shared by the unit tests. +use std::ops::Range; + use crypthix_crypto::key::{KdfKey, XofKey}; use crypthix_crypto::mac; use crypthix_types::id::VaultId; -use crate::chunk::GearTable; +use crate::blob::ObjectClass; +use crate::chunk::{ChunkParams, Chunks, GearTable}; /// `len` deterministic pseudo-random bytes: the keyed XOF under `[seed; 32]`. pub(crate) fn pseudo_random(seed: u8, len: usize) -> Vec { @@ -20,3 +23,45 @@ pub(crate) fn gear_table(seed: u8) -> GearTable { let vault_id = VaultId::try_from_bytes([0x11; 16]).expect("non-zero ID"); GearTable::derive(&key, &vault_id).expect("derives") } + +/// The most chunks `len` bytes of an object of `class` can be cut into: every chunk but the +/// last is at least the minimum (the maximum for the secret class) and the last is not empty. +/// A loop over a chunker that goes past it is not advancing and must fail, not run on until +/// it fills memory. +pub(crate) fn most_chunks(class: ObjectClass, params: &ChunkParams, len: usize) -> usize { + let least = match class { + ObjectClass::Ordinary => params.min, + ObjectClass::Secret => params.max, + }; + len / least + 1 +} + +/// The ranges [`Chunks`] cuts `data` into, checked as they come: each must be non-empty, start +/// where the one before ended and stay within `data`, and there must be no more than +/// [`most_chunks`]. A cut that stops advancing panics here at once instead of growing the list +/// without end. +pub(crate) fn chunk_ranges( + gear: &GearTable, + class: ObjectClass, + data: &[u8], + params: ChunkParams, +) -> Vec> { + let most = most_chunks(class, ¶ms, data.len()); + let mut ranges: Vec> = Vec::new(); + let mut end = 0; + for range in Chunks::with_params(gear, class, data, params) { + assert!( + ranges.len() < most, + "more than {most} chunks of {} bytes: the chunker is not advancing", + data.len() + ); + assert!( + range.start == end && range.start < range.end && range.end <= data.len(), + "chunk {range:?} after offset {end} of {} bytes", + data.len() + ); + end = range.end; + ranges.push(range); + } + ranges +} diff --git a/crates/engine/core/tests/tv07.rs b/crates/engine/core/tests/tv07.rs index 8374818..3d21b3e 100644 --- a/crates/engine/core/tests/tv07.rs +++ b/crates/engine/core/tests/tv07.rs @@ -16,7 +16,7 @@ use crypthix_core::chunk::{self, Chunks, GearTable, ObjectShape, StreamChunker}; use crypthix_core::compress::{Compressor, Decompressor}; use crypthix_core::error::ReadError; use crypthix_core::inner::{self, Comp}; -use crypthix_core::limits::MAX_CHUNK; +use crypthix_core::limits::{MAX_CHUNK, MIN_CHUNK}; use crypthix_core::pad; use crypthix_crypto::cx_aead; use crypthix_crypto::hash; @@ -143,7 +143,24 @@ fn check_chunking(test: &Value) { "{}: the shape", comment(test) ); - let lengths: Vec = chunks.map(|range| range.len()).collect(); + // Every chunk but the last is at least the minimum (the maximum for the secret class), so + // a chunker that gives more is not advancing: fail rather than loop on. + let least = match class { + ObjectClass::Ordinary => MIN_CHUNK, + ObjectClass::Secret => MAX_CHUNK, + other => panic!("no chunk bound for {other:?}"), + }; + let most = data.len() / least + 1; + let mut lengths = Vec::new(); + for range in chunks { + assert!( + lengths.len() < most && !range.is_empty(), + "{}: chunk {range:?} after {} chunks, at most {most} expected", + comment(test), + lengths.len() + ); + lengths.push(range.len()); + } assert_eq!(lengths, expected, "{}: in memory", comment(test)); if class == ObjectClass::Ordinary { assert_eq!( @@ -157,6 +174,13 @@ fn check_chunking(test: &Value) { let mut chunker = StreamChunker::new(&gear, class, data.as_slice()).expect("a window"); let mut streamed = Vec::new(); while let Some(chunk) = chunker.next_chunk().expect("reads") { + assert!( + streamed.len() < most && !chunk.bytes().is_empty(), + "{}: streamed chunk {} of {} bytes, at most {most} expected", + comment(test), + streamed.len(), + chunk.bytes().len() + ); assert_eq!(chunk.index(), streamed.len() as u64, "{}", comment(test)); assert_eq!( chunk.is_last(), diff --git a/tests/fuzz/harness/src/chunker.rs b/tests/fuzz/harness/src/chunker.rs index 60e262a..ef00944 100644 --- a/tests/fuzz/harness/src/chunker.rs +++ b/tests/fuzz/harness/src/chunker.rs @@ -180,7 +180,23 @@ fn cut_both_ways( Chunks::scaled_for_fuzzing(gear, class, file) }; let shape = chunks.object_shape(); - let in_memory: Vec = chunks.map(|range| range.len()).collect(); + // Every chunk but the last is at least the minimum (the maximum for the secret class), so a + // chunker that gives more is not advancing: fail rather than loop on. + let least = if class == ObjectClass::Secret { + scale.max + } else { + scale.min + }; + let most = len / least + 1; + let mut in_memory = Vec::new(); + for range in chunks { + assert!( + in_memory.len() < most && !range.is_empty(), + "chunk {range:?} after {} chunks, at most {most} expected", + in_memory.len() + ); + in_memory.push(range.len()); + } assert_eq!(shape.class(), class, "the shape's class"); assert_eq!(shape.is_single(), in_memory.len() <= 1, "the shape"); @@ -218,6 +234,12 @@ fn cut_both_ways( let mut offset = 0; let mut streamed = Vec::new(); while let Some(chunk) = chunker.next_chunk().expect("the reader does not fail") { + assert!( + streamed.len() < most && !chunk.bytes().is_empty(), + "streamed chunk {} of {} bytes, at most {most} expected", + streamed.len(), + chunk.bytes().len() + ); assert_eq!(chunk.index(), streamed.len() as u64, "chunk index"); assert_eq!(chunk.object_shape(), shape, "the stream's shape"); let bytes = chunk.bytes(); From 7366e0c83d06d651d820b8b925aa4b86fd00c85b Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 16:40:41 +0530 Subject: [PATCH 08/15] test(core): fail a test reader on a second read so a retried hard error is caught, not hung --- crates/engine/core/src/chunk/stream_chunker.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/engine/core/src/chunk/stream_chunker.rs b/crates/engine/core/src/chunk/stream_chunker.rs index 5b13c4d..9305006 100644 --- a/crates/engine/core/src/chunk/stream_chunker.rs +++ b/crates/engine/core/src/chunk/stream_chunker.rs @@ -337,9 +337,14 @@ mod tests { #[test] fn reader_errors_are_returned() { - struct Broken; + /// Fails once; a second read means a hard error was retried like `Interrupted`. + struct Broken { + reads: usize, + } impl Read for Broken { fn read(&mut self, _: &mut [u8]) -> io::Result { + self.reads += 1; + assert_eq!(self.reads, 1, "a hard read error must not be retried"); Err(io::Error::other("disk")) } } @@ -350,9 +355,13 @@ mod tests { } } let gear = table(1); - let mut chunker = - StreamChunker::with_params(&gear, ObjectClass::Ordinary, Broken, ChunkParams::SCALED) - .expect("window"); + let mut chunker = StreamChunker::with_params( + &gear, + ObjectClass::Ordinary, + Broken { reads: 0 }, + ChunkParams::SCALED, + ) + .expect("window"); assert!(matches!(chunker.next_chunk(), Err(StreamError::Io(_)))); assert!(matches!(chunker.next_chunk(), Err(StreamError::Failed))); let mut chunker = From cd9e53c527e9e4be69078026f4b9ac3e62f2b0ae Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 16:40:54 +0530 Subject: [PATCH 09/15] ci: give the changed-lines mutants job 90 minutes for PRs that add a whole module --- .github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9ec175b..cdd8a7f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -384,7 +384,8 @@ jobs: needs: changes if: github.event_name == 'pull_request' && needs.changes.outputs.mutants == 'true' runs-on: ubuntu-24.04 - timeout-minutes: 40 + # A PR that adds a whole module brings a few hundred mutants, tested one at a time. + timeout-minutes: 90 permissions: contents: read steps: From 7a212ca25cc53381625d56ffa6644dc7761f853a Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 21:56:47 +0530 Subject: [PATCH 10/15] fix(core): single-segment frames, block-size and store-raw checks on read, a sealer bound to its chunker, and a test-only API surface --- .cargo/mutants.toml | 39 +- crates/engine/core/Cargo.toml | 13 + .../blob/object_opener.txt | 8 + .../proptest-regressions/chunk/chunks.txt | 8 + crates/engine/core/src/blob/blob_id_kind.rs | 7 +- crates/engine/core/src/blob/chunk_keys.rs | 24 +- crates/engine/core/src/blob/data_blob_aad.rs | 10 +- .../engine/core/src/blob/identified_chunk.rs | 87 ++++ crates/engine/core/src/blob/meta_blob_aad.rs | 8 +- crates/engine/core/src/blob/meta_key.rs | 11 +- crates/engine/core/src/blob/meta_kind.rs | 26 +- crates/engine/core/src/blob/mod.rs | 15 +- crates/engine/core/src/blob/object_opener.rs | 161 ++++++- crates/engine/core/src/blob/object_sealer.rs | 420 ++++++++++++++++-- crates/engine/core/src/blob/open_meta_blob.rs | 16 +- crates/engine/core/src/blob/seal_meta_blob.rs | 4 +- crates/engine/core/src/chunk/chunk_params.rs | 4 +- crates/engine/core/src/chunk/chunk_ref.rs | 39 +- crates/engine/core/src/chunk/chunks.rs | 100 ++++- crates/engine/core/src/chunk/cut.rs | 43 +- crates/engine/core/src/chunk/gear_table.rs | 22 +- crates/engine/core/src/chunk/mod.rs | 2 +- crates/engine/core/src/chunk/object_shape.rs | 79 +++- .../engine/core/src/chunk/stream_chunker.rs | 102 ++++- crates/engine/core/src/compress/compressor.rs | 241 ++++++++-- .../engine/core/src/compress/decompressor.rs | 272 +++++++++++- .../engine/core/src/compress/frame_check.rs | 332 +++++++++----- crates/engine/core/src/error/read_error.rs | 9 +- crates/engine/core/src/error/write_error.rs | 12 +- crates/engine/core/src/fault.rs | 127 ++++++ crates/engine/core/src/inner/decode_inner.rs | 163 ++++++- crates/engine/core/src/inner/encode_inner.rs | 18 +- crates/engine/core/src/lib.rs | 25 +- crates/engine/core/src/limits.rs | 3 +- crates/engine/core/src/pad/padme.rs | 2 - crates/engine/core/src/test_data.rs | 34 ++ crates/engine/core/tests/tv07.rs | 94 ++-- 37 files changed, 2168 insertions(+), 412 deletions(-) create mode 100644 crates/engine/core/proptest-regressions/blob/object_opener.txt create mode 100644 crates/engine/core/proptest-regressions/chunk/chunks.txt create mode 100644 crates/engine/core/src/blob/identified_chunk.rs create mode 100644 crates/engine/core/src/fault.rs diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 05ba081..7f929fc 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -1,21 +1,36 @@ # cargo-mutants settings (https://mutants.rs/filter_mutants.html). - +# +# Each exclusion is keyed on a function name, so it would also skip a matching mutant added to +# that function later. Each comment names every expression it is meant to cover; after changing +# one of these functions, compare `cargo mutants --workspace --all-features --list` with the +# same command plus `--no-config`: the difference must be exactly these 14 mutants. exclude_re = [ - # `^` on flags with no bit in common is `|`, so these mutants cannot change behaviour. + # `^` on flags with no bit in common is `|`, so these mutants cannot change behaviour. In + # crypthix-crypto: the `|` of `ProtFlags::READ | ProtFlags::WRITE` in `map_secret`, + # `anonymous` and `map_marker` (one each). In crypthix-core's `frame_check`: the four `|` + # of `SINGLE_SEGMENT | UNUSED | RESERVED | CHECKSUM | DICT_ID`. 'replace \| with \^ in (map_secret|anonymous|map_marker|frame_check)$', - # padme(2) is 2 by the general formula too (e = 1, s = 1, no low bits to clear). + # `padme`: only the `<` of `len < 2`. padme(2) is 2 by the general formula too (e = 1, + # s = 1, no low bits to clear). 'replace < with <= in padme$', - # crypthix-core's Decompressor::stream: frame_check and an output buffer of exactly the - # declared content size let zstd finish the frame in its first call, so whether the loop - # breaks on hint 0 or on no progress never shows; after the frame a further call reads - # nothing and returns a non-zero hint. Both checks stay as defence in depth. + # crypthix-core's `Decompressor::stream`: only the `==` of `hint == 0` and of + # `(input.pos(), output.pos()) == before`, the two `==` in it (not the `!=` of + # `input.pos() != frame.len()`). frame_check and an output buffer of exactly the declared + # content size let zstd finish the frame in its first call, so whether the loop breaks on + # hint 0 or on no progress never shows; after the frame a further call reads nothing and + # returns a non-zero hint. Both checks stay as defence in depth. 'replace == with != in stream$', - # cut_with: capping a remainder of exactly the maximum at the maximum changes nothing, and - # neither does lowering the centre to a remainder shorter than the average: a split past the - # end of the pairs falls back to taking them all as strict pairs, as a split at the end does. + # `cut_with`: only `remaining > params.max` (to `>=`) and `remaining < center` (to `==` or + # `<=`), the one `>` and the one `<` in it (not the `<=` of `remaining <= params.min`). + # Capping a remainder of exactly the maximum at the maximum changes nothing, and neither + # does lowering the centre to a remainder shorter than the average or equal to it: a split + # past the end of the pairs falls back to taking them all as strict pairs, as a split at + # the end does. 'replace > with >= in cut_with$', 'replace < with (==|<=) in cut_with$', - # StreamChunker::refill: `start <= end <= window.len()` always holds, so the defensive check - # that fails instead of panicking never fires, whichever operator joins its halves. + # `StreamChunker::refill`: only the `||` of `self.start > self.end || self.end > + # window.len()`, the one `||` in it. `start <= end <= window.len()` always holds, so the + # defensive check that fails instead of panicking never fires, whichever operator joins + # its halves. 'replace \|\| with && in StreamChunker<.*>::refill$', ] diff --git a/crates/engine/core/Cargo.toml b/crates/engine/core/Cargo.toml index 0825c17..ec73f69 100644 --- a/crates/engine/core/Cargo.toml +++ b/crates/engine/core/Cargo.toml @@ -16,6 +16,15 @@ crypthix-crypto.workspace = true crypthix-types.workspace = true zstd-safe = { version = "8.2.0", default-features = false } +[features] +# Exposes the keys, AADs and chunk constructors that bypass `ObjectSealer`'s binding to its +# object (`ChunkKeys::chunk_key` and `blob_id_key`, `MetaKey::seal_key`, `blob::data_blob_aad` +# and `meta_blob_aad`, `MetaKind::from_code`, `ChunkRef::from_parts` and the +# `scaled_for_fuzzing` chunkers), for the TV-07 runner and the fuzz targets (FS-55, FS-94). +# Release builds must never enable it; `cargo xtask check-features` fails if anything in the +# main workspace does. It must not enable `crypthix-crypto/vectors` either. +vectors = [] + [dev-dependencies] criterion = { version = "0.8.2", default-features = false, features = ["cargo_bench_support"] } crypthix-crypto = { workspace = true, features = ["vectors"] } @@ -31,3 +40,7 @@ harness = false [[bench]] name = "inner" harness = false + +[[test]] +name = "tv07" +required-features = ["vectors"] diff --git a/crates/engine/core/proptest-regressions/blob/object_opener.txt b/crates/engine/core/proptest-regressions/blob/object_opener.txt new file mode 100644 index 0000000..8795e02 --- /dev/null +++ b/crates/engine/core/proptest-regressions/blob/object_opener.txt @@ -0,0 +1,8 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 48def2c0771bb10e8add59eb6f02671ec4fdb12d0b70099b1e2c9d63987c4239 # shrinks to chunk = [0, 0, 1, 1, 3, 3, 0, 2, 3, 3, 2, 1, 2, 3, 1, 0, 0, 2, 1, 3, 0, 1, 0, 2, 2, 1, 3, 0, 3, 1, 2, 1, 2, 1, 1, 1, 3, 1, 1, 3, 3, 3, 1, 0, 2, 0, 1, 3, 1, 0, 0, 1, 1, 3, 3, 3, 3, 1, 0, 3, 1, 1, 1, 0, 1, 1, 2, 1, 1, 0, 2, 0, 1, 1, 2, 1, 2, 3, 0, 1, 3, 3, 2, 2, 0, 3, 0, 3, 2, 3, 2, 3, 1, 3, 3, 0, 2, 3, 0, 0, 2, 1, 2, 0, 0, 1, 0, 1, 1, 3, 2, 2, 0, 1, 3, 0, 3, 1, 3, 2, 1, 0, 3, 3, 0, 3, 1, 2, 3, 3, 1, 0, 0, 0, 2, 2, 1, 0, 1, 2, 3, 0, 2, 0, 0, 1, 3, 1, 3, 1, 3, 1, 0, 2, 0, 1, 2, 0, 3, 3, 1, 2, 3, 3, 1, 2, 2, 0, 2, 0, 3, 2, 2, 3, 0, 3, 1, 2, 1, 1, 2, 0, 2, 2, 0, 1, 2, 0, 1, 2, 1, 0, 0, 0, 3, 3, 3, 2, 1, 1, 3, 3, 0, 3, 1, 1, 1, 0, 3, 3, 2, 1, 1, 2, 1, 1, 2, 3, 2, 2, 1, 1, 2, 3, 0, 0, 2, 2, 1, 3, 1, 3, 1, 1, 2, 1, 2, 1, 3, 3, 0, 0, 2, 0, 2, 1, 2, 3, 2, 0, 2, 0, 1, 1, 3, 1, 2, 1, 3, 2, 0, 2, 0, 3, 0, 3, 3, 0, 1, 3, 3, 2, 1, 1, 3, 0, 0, 3, 1, 2, 0, 3, 3, 2, 1, 3, 3, 1, 1, 3, 0, 0, 0, 3, 0, 2, 1, 3, 0, 0, 3, 1, 1, 2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1, 0, 2, 1, 0, 2, 1, 3, 3, 2, 2, 2, 1, 3, 3, 0, 0, 1, 3, 1, 2, 2, 1, 0, 1, 2, 3, 0, 3, 2, 1, 2, 1, 1, 2, 2, 0, 0, 3, 1, 2, 1, 2, 2, 1, 0, 3, 3, 0, 2, 2, 1, 0, 1, 3, 0, 3, 1, 1, 1, 1, 3, 1, 1, 1, 3, 2, 3, 2, 0, 3, 1, 1, 1, 3, 0, 1, 0, 0, 0, 1, 3, 2, 3, 2, 0, 0, 2, 0, 1, 2, 0, 3, 3, 1, 0, 0, 2, 0, 1, 1, 1, 3, 2, 3, 1, 1, 0, 0, 3, 2, 3, 2, 3, 1, 2, 3, 3, 2, 1, 1, 2, 0, 2, 0, 3, 1, 1, 2, 3, 2, 1, 3, 0], secret = false, count = 3 diff --git a/crates/engine/core/proptest-regressions/chunk/chunks.txt b/crates/engine/core/proptest-regressions/chunk/chunks.txt new file mode 100644 index 0000000..25b7cd9 --- /dev/null +++ b/crates/engine/core/proptest-regressions/chunk/chunks.txt @@ -0,0 +1,8 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 03ab330e97cb11aff0e0f88e4763af815f41028280a800640bd4637780a1dbe5 # shrinks to seed = 1, data = [196, 220, 233, 82, 237, 114, 84, 144, 161, 169, 155, 216, 87, 10, 172, 204, 245, 154, 167, 203, 30, 194, 232, 163, 145, 135, 130, 128, 36, 67, 20, 117, 192, 65, 202, 192, 29, 62, 64, 58, 84, 49, 249, 93, 136, 249, 230, 147, 37, 185, 33, 4, 168, 162, 198, 153, 70, 204, 254, 136, 80, 237, 38, 246, 206, 34, 47, 108, 109, 186, 119, 162, 8, 99, 18, 10, 219, 237, 89, 29, 33, 221, 138, 79, 113, 55, 104, 24, 3, 38, 189, 172, 149, 168, 211, 59, 160, 0, 88, 40, 64, 136, 7, 161, 243, 198, 5, 15, 204, 171, 229, 46, 58, 99, 168, 137, 114, 50, 196, 193, 168, 8, 124, 91, 238, 98, 252, 127, 204, 185, 214, 210, 40, 110, 96, 150, 12, 55, 47, 32, 117, 238, 205, 86, 209, 94, 215, 38, 217, 239, 87, 141, 176, 200, 248, 76, 198, 251, 127, 234, 72, 174, 147, 138, 20, 117, 112, 137, 32, 63, 50, 79, 2, 200, 42, 156, 60, 214, 118, 198, 58, 67, 54, 53, 236, 26, 89, 58, 1, 50, 151, 219, 119, 29, 115, 148, 21, 190, 115, 247, 231, 208, 219, 200, 97, 122, 209, 201, 245, 158, 251, 30, 107, 64, 227, 103, 62, 69, 181, 121, 244, 226, 6, 27, 40, 209, 233, 243, 128, 4, 141, 234, 104, 133, 238, 192, 35, 10, 122, 26, 111, 157, 117, 122, 28, 34, 243, 108, 199, 82, 46, 90, 224, 123, 147, 200, 227, 218, 76, 50, 12, 197, 65, 32, 194, 94, 174, 30, 54, 48, 87, 0, 80, 232, 121, 198, 141, 65, 201, 6, 94, 174, 174, 214, 188, 93, 156, 139, 66, 105, 97, 146, 242, 155, 215, 94, 42, 146, 50, 227, 145, 89, 65, 250, 110, 223, 166, 49, 26, 167, 77, 138, 11, 94, 52, 44, 167, 22, 186, 17, 133, 36, 162, 12, 179, 3, 118, 84, 30, 115] +cc 0943f81661aec186e1d997b21749c1aa9b670d965c11bde9d87e867dd98c2406 # shrinks to seed = 1, data = [10, 136, 186, 113, 77, 214, 9, 156, 48, 213, 205, 174, 3, 80, 60, 175, 31, 22, 4, 100, 200, 255, 128, 16, 185, 73, 57, 175, 69, 68, 124, 172, 143, 10, 100, 133, 132, 67, 233, 149, 105, 248, 109, 106, 31, 196, 32, 220, 149, 203, 209, 193, 5, 248, 111, 95, 43, 219, 165, 116, 53, 126, 246, 147, 130, 42, 115, 76, 123, 254, 100, 81, 160, 0, 184, 101, 168, 163, 90, 89, 223, 216, 187, 110, 129, 209, 1, 188, 217, 242, 8, 17, 238, 49, 61, 229, 140, 148, 209, 135, 197, 26, 32, 164, 248, 246, 91, 200, 48, 80, 170, 41, 217, 248, 113, 159, 228, 128, 3, 215, 142, 113, 174, 124, 136, 116, 191, 63, 96, 45, 94, 79, 13, 170, 147, 127, 191, 6, 119, 6, 136, 224, 185, 164, 122, 119, 3, 223, 243, 110, 51, 7, 187, 118, 162, 96, 58, 168, 27, 247, 66, 196, 177, 231, 108, 35, 155, 189, 215, 49, 76, 205, 11, 77, 242, 157, 50, 135, 252, 228, 70, 146, 145, 192, 33, 5, 114, 95, 114, 219, 45, 148, 205, 9, 29, 125, 242, 211, 183, 39, 191, 2, 228, 233, 241, 126, 163, 229, 115, 4, 35, 83, 168, 31, 167, 60, 130, 169, 93, 143, 154, 159, 238, 109, 40, 86, 249, 176, 132, 154, 124, 254, 105, 36, 183, 209, 110, 18, 91, 202, 238, 176, 128, 23, 206, 83, 163, 46, 191, 24, 76, 163, 136, 130, 181, 246, 96, 74, 63, 249, 142, 8, 99, 247, 118, 83, 97, 101, 183, 103, 169, 199, 172, 212, 239, 177, 163, 246, 150, 218, 46, 245, 15, 71, 76, 213, 8, 109, 172, 0, 159, 220, 24, 252, 152, 169, 68, 245, 244, 80, 230, 6, 141, 20, 190, 187, 127, 95, 119, 131, 231, 182, 173, 5, 30, 143, 237, 255, 253, 172, 65, 154, 244, 7, 84, 187, 200, 8, 101, 105, 119, 223, 9, 27, 156, 181, 39, 210, 140, 119, 231, 203, 68, 234, 229, 42, 88, 185, 107, 197, 216, 100, 20, 62, 99, 127, 26, 81, 26, 238, 203, 187, 94, 112, 178, 106, 248, 101, 51, 252, 76, 129, 135, 157, 87, 237, 147, 13, 43, 249, 5, 85, 38, 23, 90, 76, 172, 38, 49, 134, 49, 166, 229, 221, 160, 97, 250, 117, 109, 21, 189, 56, 130, 230, 189, 123, 238, 56, 222, 202, 56, 179, 109, 202, 245, 68, 161, 202, 134, 200, 167, 120, 88, 190, 134, 147, 200, 120, 60, 136, 148, 82, 188, 116, 90, 129, 223, 182, 254, 177, 90, 7, 60, 75, 10, 168, 190, 120, 13, 1, 137, 241, 212, 154, 2, 174, 164, 224, 167, 139, 185, 177, 74, 79, 220, 78, 144, 111, 253, 21, 181, 62, 237, 251, 8, 189, 144, 141, 224, 254, 44, 179, 160, 40, 2, 59, 181, 225, 224, 111, 212, 219, 9, 249, 230, 158, 96, 221, 215, 63, 231, 46, 243, 129, 176, 200, 213, 27, 50, 173, 30, 183, 140, 91, 124, 225, 192, 73, 103, 250, 168, 30, 33, 164, 22, 170, 254, 58, 30, 45, 71, 39, 64, 252, 1, 89, 255, 180, 232, 41, 63, 186, 195, 37, 200, 225, 129, 250, 107, 18, 180, 95, 86, 50, 46, 80, 217, 13, 149, 214, 130, 225, 28, 7, 240, 242, 213, 247, 116, 213, 238, 19, 54, 201, 126, 137, 165, 111, 20, 163, 157, 11, 124, 1, 47, 63, 175, 146, 176, 247, 236, 29, 164, 241, 172, 134, 21, 16, 187, 23, 156, 17, 115, 100, 42, 112, 72, 200, 113, 108, 85, 199, 99, 66, 38, 79, 142, 81, 81, 244, 100, 175, 97, 141, 61, 212, 252, 100, 47, 19, 193, 150, 112, 87, 144, 150, 148, 34, 59, 140, 230, 126, 95, 176, 108, 162, 58, 52, 10, 211, 238, 55, 117, 123, 225, 69, 152, 253, 20, 30, 69, 47, 125, 4, 172, 218, 108, 113, 167, 81, 47, 80, 216, 249, 191, 149, 142, 87, 90, 80, 180, 19, 144, 249, 105, 105, 83, 1, 71, 54, 53, 188, 137, 64, 2, 172, 217, 188, 11, 185, 231, 156, 223, 211, 93, 233, 220, 158, 151, 138, 58, 211, 9, 255, 206, 14, 173, 14, 252, 249, 198, 200, 87, 211, 44, 170, 236, 68, 127, 92, 177, 14, 253, 57, 139, 43, 189, 212, 242, 69, 203, 10, 243, 246, 177, 83, 61, 21, 238, 189, 234, 238, 174, 88, 33, 102, 53, 65, 115, 7, 112, 39, 101, 74, 132, 28, 96, 185, 131, 3, 141, 200, 91, 123, 104, 223, 51, 63, 222, 125, 125, 196, 154, 3, 205, 110, 217, 204, 146, 240, 246, 7, 234, 254, 86, 1, 194, 183, 96, 147, 136, 109, 180, 118, 179, 116, 149, 6, 185, 25, 124, 59, 35, 118, 92, 126, 76, 92, 155, 83, 206, 2, 250, 36, 7, 86, 190, 213, 139, 48, 123, 71, 125, 159, 117, 189, 155, 67, 133, 12, 47, 85, 6, 163, 62, 228, 199, 17, 191, 237, 111, 204, 149, 1, 104, 166, 85, 109, 98, 1, 157, 125, 157, 92, 217, 247, 226, 109, 121, 131, 74, 199, 143, 29, 107, 45, 155, 114, 212, 113, 79, 216, 201, 150, 164, 162, 128, 103, 177, 246, 145, 121, 222, 26, 179, 49, 246, 162, 50, 20, 199, 121, 139, 78, 241, 128, 206, 240, 153, 197, 80, 60, 151, 49, 56, 63, 171, 111, 105, 40, 81, 195, 144, 135, 184, 63, 113, 42, 54, 169, 93, 19, 174, 235, 19, 173, 181, 138, 83, 78, 11, 230, 57, 193, 109, 66, 43, 157, 180, 34, 23, 212, 12, 196, 166, 195, 242, 72, 121, 254, 142, 194, 102, 154, 34, 30, 149, 216, 26, 66, 193, 16, 80, 138, 232, 56, 44, 207, 159, 103, 139, 65, 157, 185, 251, 210, 183, 112, 14, 143, 189, 228, 23, 175, 29, 247, 94, 203, 232, 187, 11, 57, 122, 74, 81, 6, 252, 46, 250, 174, 157, 143, 86, 130, 5, 48, 67, 33, 68, 106, 228, 190, 17, 231, 3, 78, 117, 60, 211, 154, 227, 228, 210, 38, 113, 196, 96, 137, 150, 137, 200, 239, 92, 31, 57, 210, 99, 59, 159, 34, 106, 215, 11, 230, 191, 249, 248, 233, 121, 192, 104, 42, 178, 103, 72, 130, 162, 201, 60, 221, 133, 188, 9, 86, 22, 63, 157, 178, 43, 128, 153, 116, 76, 85, 189, 84, 177, 174, 128, 113, 60, 113, 15, 42, 177, 249, 87, 165, 39, 135, 69, 231, 234, 239, 106, 136, 62, 251, 199, 78, 136, 14, 41, 62, 238, 208, 17, 209, 217, 92, 237, 172, 130, 246, 83, 223, 216, 166, 109, 129, 54, 175, 107, 146, 114, 223, 13, 187, 125, 138, 124, 124, 94, 188, 225, 25, 31, 224, 90, 36, 243, 11, 76, 177, 49, 3, 214, 180, 185, 99, 217, 133, 253, 47, 90, 3, 217, 89, 230, 6, 77, 16, 33, 82, 17, 221, 64, 63, 31, 211, 76, 58, 166, 243, 184, 242, 0, 71, 243, 140, 132, 188, 87, 249, 37, 175, 3, 3, 73, 144, 71, 175, 221, 111, 143, 211, 3, 114, 95, 53, 228, 53, 44, 100, 91, 135, 58, 118, 88, 184, 95, 141, 46, 4, 205, 128, 164, 220, 209, 112, 24, 1, 30, 224, 224, 245, 174, 93, 147, 87, 130, 126, 233, 173, 20, 206, 180, 10, 211, 170, 143, 22, 251, 246, 0, 167, 8, 33, 246, 171, 55, 18, 233, 186, 43, 82, 168, 122, 101, 46, 211, 125, 7, 67, 77, 105, 184, 236, 176, 1, 203, 198, 14, 22, 240, 62, 137, 57, 35, 44, 221, 252, 28, 196, 25, 201, 218, 42, 20, 13, 170, 181, 4, 93, 124, 18, 148, 213, 14, 173, 105, 26, 36, 222, 106, 185, 154, 188, 167, 50, 128, 101, 116, 37, 244, 161, 116, 118, 136, 143, 6, 212, 157, 129, 177, 148, 245, 41, 143, 15, 12, 225, 96, 37, 147, 124, 196, 194, 173, 199, 21, 99, 96, 225, 231, 207, 225, 38, 20, 160, 64, 115, 240, 245, 169, 72, 255, 26, 200, 231, 179, 37, 72, 238, 117, 18, 64, 71, 186, 218, 127, 34, 116, 152, 178, 48, 82, 184, 92, 154, 98, 161, 232, 36, 119, 22, 145, 110, 42, 127, 117, 141, 38, 240, 167, 200, 6, 99, 6, 171, 142, 237, 80, 168, 148, 248, 209, 136, 51, 114, 13, 245, 213, 106, 209, 175, 180, 126, 184, 59, 39, 130, 177, 86, 178, 228, 107, 224, 24, 100, 162, 243, 107, 130, 254, 176, 198, 235, 87, 56, 126, 132, 180, 162, 202, 104, 54, 6, 122, 81, 216, 187, 55, 16, 33, 187, 247, 155, 218, 198, 126, 85, 47, 234, 142, 148, 149] diff --git a/crates/engine/core/src/blob/blob_id_kind.rs b/crates/engine/core/src/blob/blob_id_kind.rs index 256c6b4..0862b9b 100644 --- a/crates/engine/core/src/blob/blob_id_kind.rs +++ b/crates/engine/core/src/blob/blob_id_kind.rs @@ -17,9 +17,10 @@ pub enum BlobIdKind { impl BlobIdKind { /// Keyed exactly when the object is of the ordinary class and has two or more chunks; /// random otherwise. A reader takes the class and the chunk count from the manifest - /// ([`ObjectOpener`](crate::blob::ObjectOpener)); a writer takes the count from the chunker - /// ([`ObjectSealer`](crate::blob::ObjectSealer) with an - /// [`ObjectShape`](crate::chunk::ObjectShape)), so the two always agree. + /// ([`ObjectOpener`](crate::blob::ObjectOpener)); a writer takes them from the chunker's + /// [`ObjectShape`](crate::chunk::ObjectShape) and records the count + /// [`ObjectSealer::finish`](crate::blob::ObjectSealer::finish) gives, which fails if the + /// chunks sealed contradict the shape, so the two agree. #[must_use] pub const fn for_object(class: ObjectClass, chunk_count: u64) -> Self { match class { diff --git a/crates/engine/core/src/blob/chunk_keys.rs b/crates/engine/core/src/blob/chunk_keys.rs index f34b868..7c00350 100644 --- a/crates/engine/core/src/blob/chunk_keys.rs +++ b/crates/engine/core/src/blob/chunk_keys.rs @@ -60,17 +60,37 @@ impl ChunkKeys { &self.context } - /// `K_chunk`, which seals the object's data blobs. + /// `K_chunk`, which seals the object's data blobs. Public only with the `vectors` feature, + /// for the test-vector runners and fuzz targets: sealing with it directly would bypass the + /// object's AAD and its blob-ID kind. + #[cfg(feature = "vectors")] #[must_use] pub const fn chunk_key(&self) -> &SealKey { &self.chunk } - /// `K_blobid`, which keys the blob IDs of an ordinary object. + /// `K_chunk`, which seals the object's data blobs. + #[cfg(not(feature = "vectors"))] + #[must_use] + pub(crate) const fn chunk_key(&self) -> &SealKey { + &self.chunk + } + + /// `K_blobid`, which keys the blob IDs of an ordinary object. Public only with the + /// `vectors` feature, for the test-vector runners and fuzz targets: a MAC under it for a + /// single-chunk object is the oracle FS-55 rules out (T-85). + #[cfg(feature = "vectors")] #[must_use] pub const fn blob_id_key(&self) -> &MacKey { &self.blob_id } + + /// `K_blobid`, which keys the blob IDs of an ordinary object. + #[cfg(not(feature = "vectors"))] + #[must_use] + pub(crate) const fn blob_id_key(&self) -> &MacKey { + &self.blob_id + } } /// Prints no key bytes. diff --git a/crates/engine/core/src/blob/data_blob_aad.rs b/crates/engine/core/src/blob/data_blob_aad.rs index a2c7a3e..f12ea5e 100644 --- a/crates/engine/core/src/blob/data_blob_aad.rs +++ b/crates/engine/core/src/blob/data_blob_aad.rs @@ -7,10 +7,16 @@ use crypthix_types::id::BlobId; use crate::blob::BlobContext; /// The blob kind byte of a data blob (format spec 10.4). -pub const DATA_BLOB_KIND: u8 = 0x01; +const DATA_BLOB_KIND: u8 = 0x01; /// `u8 len ‖ "crypthix/v0/aad/blob-data" ‖ fmt ‖ suite ‖ vault_id ‖ u8 0x01 ‖ object_id ‖ -/// dek_id ‖ blob_id` (FS-55). +/// dek_id ‖ blob_id` (FS-55). Public only with the `vectors` feature, for the test-vector +/// runners and fuzz targets; [`ObjectSealer`](crate::blob::ObjectSealer) and +/// [`ObjectOpener`](crate::blob::ObjectOpener) build it from the keys' own context. +#[cfg_attr( + not(feature = "vectors"), + expect(unreachable_pub, reason = "public only with `vectors`, for TV-07") +)] pub fn data_blob_aad(context: &BlobContext, blob_id: &BlobId) -> Aad { Aad::new(AadLabel::BlobData) .field(context.vault_id().as_bytes()) diff --git a/crates/engine/core/src/blob/identified_chunk.rs b/crates/engine/core/src/blob/identified_chunk.rs new file mode 100644 index 0000000..87112d8 --- /dev/null +++ b/crates/engine/core/src/blob/identified_chunk.rs @@ -0,0 +1,87 @@ +//! A chunk with the blob ID its sealer worked out for it. + +use std::fmt; + +use crypthix_types::id::BlobId; + +use crate::blob::ChunkKeys; +use crate::chunk::ChunkRef; + +/// A chunk of an object with its keyed blob ID, if the object's blob IDs are keyed, from +/// [`ObjectSealer::identify`](crate::blob::ObjectSealer::identify). +/// +/// A writer looks the keyed ID up among the blobs already stored, then hands the chunk back to +/// the same sealer: to [`reuse`](crate::blob::ObjectSealer::reuse) if a blob of that ID is +/// there, to [`seal_identified`](crate::blob::ObjectSealer::seal_identified) if not, which +/// seals under this ID without computing the MAC again. Only a sealer makes one, and only the +/// sealer of the same keys takes it back, so the ID is never the caller's. +pub struct IdentifiedChunk<'k, 'c> { + keys: &'k ChunkKeys, + chunk: ChunkRef<'c>, + keyed_id: Option, +} + +impl<'k, 'c> IdentifiedChunk<'k, 'c> { + pub(crate) const fn new( + keys: &'k ChunkKeys, + chunk: ChunkRef<'c>, + keyed_id: Option, + ) -> Self { + Self { + keys, + chunk, + keyed_id, + } + } + + /// The keyed blob ID `MAC(K_blobid, chunk)`, or `None` if the object's blob IDs are random: + /// those are drawn when the chunk is sealed and never reused (FS-55). + #[must_use] + pub const fn keyed_id(&self) -> Option<&BlobId> { + self.keyed_id.as_ref() + } + + /// The chunk. + #[must_use] + pub const fn chunk(&self) -> ChunkRef<'c> { + self.chunk + } + + /// The keys of the sealer that identified the chunk, the chunk, and its keyed ID; consumed + /// so that one identification seals or reuses one chunk. + pub(crate) const fn into_parts(self) -> (&'k ChunkKeys, ChunkRef<'c>, Option) { + (self.keys, self.chunk, self.keyed_id) + } +} + +/// Prints the chunk's position and length only: not its bytes, and not its keyed ID, which is +/// a fingerprint of the chunk within its object (FS-55). +impl fmt::Debug for IdentifiedChunk<'_, '_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("IdentifiedChunk") + .field("chunk", &self.chunk) + .field("keyed", &self.keyed_id.is_some()) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::blob::ObjectClass; + use crate::blob::chunk_keys::tests::keys; + + #[test] + fn debug_shows_no_bytes_and_no_id() { + let keys = keys(2); + let id = BlobId::try_from_bytes([0xef; 32]).expect("non-zero ID"); + let chunk = ChunkRef::new(b"secret", 1, false, ObjectClass::Ordinary); + let identified = IdentifiedChunk::new(&keys, chunk, Some(id)); + assert_eq!(identified.keyed_id(), Some(&id)); + assert_eq!(identified.chunk().bytes(), b"secret"); + assert_eq!( + format!("{identified:?}"), + "IdentifiedChunk { chunk: ChunkRef { len: 6, index: 1, is_last: false }, keyed: true, .. }" + ); + } +} diff --git a/crates/engine/core/src/blob/meta_blob_aad.rs b/crates/engine/core/src/blob/meta_blob_aad.rs index f526cd9..7b346ab 100644 --- a/crates/engine/core/src/blob/meta_blob_aad.rs +++ b/crates/engine/core/src/blob/meta_blob_aad.rs @@ -7,7 +7,13 @@ use crypthix_types::id::BlobId; use crate::blob::MetaContext; /// `u8 len ‖ "crypthix/v0/aad/blob-meta" ‖ fmt ‖ suite ‖ vault_id ‖ u8 kind ‖ u32be epoch ‖ -/// blob_id` (FS-57). +/// blob_id` (FS-57). Public only with the `vectors` feature, for the test-vector runners; +/// [`seal_meta_blob`](crate::blob::seal_meta_blob) and +/// [`open_meta_blob`](crate::blob::open_meta_blob) build it from the key's own context. +#[cfg_attr( + not(feature = "vectors"), + expect(unreachable_pub, reason = "public only with `vectors`, for TV-07") +)] pub fn meta_blob_aad(context: &MetaContext, blob_id: &BlobId) -> Aad { Aad::new(AadLabel::BlobMeta) .field(context.vault_id().as_bytes()) diff --git a/crates/engine/core/src/blob/meta_key.rs b/crates/engine/core/src/blob/meta_key.rs index 0c359c1..408b4a2 100644 --- a/crates/engine/core/src/blob/meta_key.rs +++ b/crates/engine/core/src/blob/meta_key.rs @@ -47,12 +47,21 @@ impl MetaKey { Ok(Self { key, context }) } - /// The seal key, `K_kind_e`. + /// The seal key, `K_kind_e`. Public only with the `vectors` feature, for the test-vector + /// runners: sealing with it directly would bypass the context's AAD. + #[cfg(feature = "vectors")] #[must_use] pub const fn seal_key(&self) -> &SealKey { &self.key } + /// The seal key, `K_kind_e`. + #[cfg(not(feature = "vectors"))] + #[must_use] + pub(crate) const fn seal_key(&self) -> &SealKey { + &self.key + } + /// The vault, kind and epoch the key was derived for. #[must_use] pub const fn context(&self) -> &MetaContext { diff --git a/crates/engine/core/src/blob/meta_kind.rs b/crates/engine/core/src/blob/meta_kind.rs index 941782e..4d8f2ae 100644 --- a/crates/engine/core/src/blob/meta_kind.rs +++ b/crates/engine/core/src/blob/meta_kind.rs @@ -18,15 +18,6 @@ pub enum MetaKind { } impl MetaKind { - /// Every kind, in code order. - pub const ALL: [MetaKind; 5] = [ - MetaKind::Index, - MetaKind::KeyTable, - MetaKind::Location, - MetaKind::PackTable, - MetaKind::GcCandidate, - ]; - /// The kind byte. #[must_use] pub const fn code(self) -> u8 { @@ -40,7 +31,9 @@ impl MetaKind { } /// The kind a byte names; `None` for data (0x01), manifest (0x02), the reserved snapshot - /// node (0x07) and anything unknown. + /// node (0x07) and anything unknown. For the unit tests and, with the `vectors` feature, the + /// test-vector runners. + #[cfg(any(test, feature = "vectors"))] #[must_use] pub const fn from_code(code: u8) -> Option { match code { @@ -58,12 +51,21 @@ impl MetaKind { mod tests { use super::*; + /// Every kind, in code order. + const ALL: [MetaKind; 5] = [ + MetaKind::Index, + MetaKind::KeyTable, + MetaKind::Location, + MetaKind::PackTable, + MetaKind::GcCandidate, + ]; + #[test] fn codes_round_trip_and_others_are_not_meta() { - for kind in MetaKind::ALL { + for kind in ALL { assert_eq!(MetaKind::from_code(kind.code()), Some(kind)); } - let known: Vec = MetaKind::ALL.iter().map(|kind| kind.code()).collect(); + let known: Vec = ALL.iter().map(|kind| kind.code()).collect(); assert_eq!(known, [3, 4, 5, 6, 8]); for code in [0, 1, 2, 7, 9, 0xFF] { assert_eq!(MetaKind::from_code(code), None, "{code}"); diff --git a/crates/engine/core/src/blob/mod.rs b/crates/engine/core/src/blob/mod.rs index a46ec5f..4b0a7bb 100644 --- a/crates/engine/core/src/blob/mod.rs +++ b/crates/engine/core/src/blob/mod.rs @@ -8,13 +8,17 @@ //! //! Keys are bound to what they were derived for: [`ChunkKeys`] to its object's //! [`BlobContext`], used through an [`ObjectSealer`] or [`ObjectOpener`] built once per object -//! with its class and chunk count, and a [`MetaKey`] to its [`MetaContext`]. +//! with its class and chunk count, and a [`MetaKey`] to its [`MetaContext`]. The keys, the AADs +//! and the raw seal are not public, so data and meta blobs are sealed and opened only through +//! those; the `vectors` feature, which `cargo xtask check-features` keeps out of release +//! builds, exposes them to the test-vector runners and fuzz targets. mod blob_context; mod blob_id_kind; mod chunk_entry; mod chunk_keys; mod data_blob_aad; +mod identified_chunk; mod meta_blob_aad; mod meta_context; mod meta_key; @@ -32,8 +36,15 @@ pub use blob_context::BlobContext; pub use blob_id_kind::BlobIdKind; pub use chunk_entry::ChunkEntry; pub use chunk_keys::ChunkKeys; -pub use data_blob_aad::{DATA_BLOB_KIND, data_blob_aad}; +#[cfg(feature = "vectors")] +pub use data_blob_aad::data_blob_aad; +#[cfg(not(feature = "vectors"))] +pub(crate) use data_blob_aad::data_blob_aad; +pub use identified_chunk::IdentifiedChunk; +#[cfg(feature = "vectors")] pub use meta_blob_aad::meta_blob_aad; +#[cfg(not(feature = "vectors"))] +pub(crate) use meta_blob_aad::meta_blob_aad; pub use meta_context::MetaContext; pub use meta_key::MetaKey; pub use meta_kind::MetaKind; diff --git a/crates/engine/core/src/blob/object_opener.rs b/crates/engine/core/src/blob/object_opener.rs index bf4e257..96b4118 100644 --- a/crates/engine/core/src/blob/object_opener.rs +++ b/crates/engine/core/src/blob/object_opener.rs @@ -6,10 +6,10 @@ use crypthix_crypto::mac; use crypthix_crypto::secure_mem::SecretBuf; use crypthix_types::format_error::FormatError; -use crate::blob::{BlobIdKind, ChunkEntry, ChunkKeys, ObjectClass, OpenedChunk, data_blob_aad}; -use crate::compress::Decompressor; +use crate::blob::{self, BlobIdKind, ChunkEntry, ChunkKeys, ObjectClass, OpenedChunk}; +use crate::compress::{self, Decompressor}; use crate::error::ReadError; -use crate::inner::{Comp, decode_inner}; +use crate::inner::{self, Comp}; use crate::limits::MAX_PLAIN_LEN; /// Opens the data blobs of one object, built once from the object's keys and the `class` and @@ -59,8 +59,9 @@ impl<'k> ObjectOpener<'k> { /// `ZeroValue` for input too short to be a seal or with a zero nonce); /// 3. the inner plaintext (`Padding`, `Limit`, FS-54); /// 4. a secret-class object with `comp = 1` (`Padding`): its chunks are never compressed; - /// 5. the payload: a raw one must be exactly `plain_len` bytes, a zstd one must pass every - /// frame check and decompress to exactly `plain_len` bytes (`Decompress`, FS-53); + /// 5. the payload: a raw one must be exactly `plain_len` bytes; a zstd one must keep the + /// store-raw rule, `16 × payload_len ≤ 15 × plain_len`, then pass every frame check and + /// decompress to exactly `plain_len` bytes (`Decompress`, FS-53); /// 6. a keyed blob ID must equal `MAC(K_blobid, plaintext)`, compared in constant time /// (`Binding`, FS-56, FS-15). Random IDs have nothing to recompute. /// @@ -83,18 +84,25 @@ impl<'k> ObjectOpener<'k> { if plain_len > MAX_PLAIN_LEN { return Err(FormatError::Decompress.into()); } - let aad = data_blob_aad(self.keys.context(), entry.blob_id()); + let aad = blob::data_blob_aad(self.keys.context(), entry.blob_id()); let inner = cx_aead::open(self.keys.chunk_key(), &aad, sealed)?; - let view = decode_inner(&inner)?; + let view = inner::decode_inner(&inner)?; let opened = match (view.comp(), self.class) { (Comp::Zstd, ObjectClass::Secret) => return Err(FormatError::Padding.into()), (Comp::Raw, _) => { if view.payload().len() as u64 != plain_len { return Err(FormatError::Decompress.into()); } + #[cfg(test)] + crate::fault::allocation()?; OpenedChunk::new(SecretBuf::try_copy_from(view.payload())?) } (Comp::Zstd, ObjectClass::Ordinary) => { + // The store-raw rule: no writer keeps a frame that saves less than 1/16, so + // such a frame is a second encoding of a chunk stored raw (FS-53). + if !compress::keep_compressed(view.payload().len() as u64, plain_len) { + return Err(FormatError::Decompress.into()); + } OpenedChunk::new(decompressor.decode(view.payload(), plain_len)?) } }; @@ -115,6 +123,7 @@ impl<'k> ObjectOpener<'k> { #[cfg(test)] mod tests { use crypthix_crypto::cx_aead::NonceKind; + use crypthix_crypto::secure_mem::MemError; use crypthix_types::id::{BlobId, DekId, ObjectId, VaultId}; use proptest::collection::vec; use proptest::prelude::{any, prop_assert_eq, proptest}; @@ -122,9 +131,9 @@ mod tests { use super::*; use crate::blob::chunk_keys::tests::{context, keys}; use crate::blob::{BlobContext, ObjectSealer}; - use crate::chunk::ObjectShape; - use crate::compress::Compressor; - use crate::inner::encode_inner; + use crate::chunk::ChunkRef; + use crate::compress::{CompressError, Compressor}; + use crate::fault::{self, Fault}; use crate::test_data::pseudo_random; fn text(len: usize) -> Vec { @@ -161,7 +170,9 @@ mod tests { fn seal(class: ObjectClass, count: u64, chunk: &[u8]) -> (ChunkEntry, Vec) { let mut compressor = Compressor::new().expect("context"); let keys = keys(2); - let sealed = ObjectSealer::new(&keys, ObjectShape::new(class, count == 1)) + // Chunk 0 of the object, the last exactly when it has one chunk. + let chunk = ChunkRef::new(chunk, 0, count == 1, class); + let sealed = ObjectSealer::new(&keys, chunk.object_shape()) .seal(&mut compressor, chunk) .expect("seals"); (*sealed.entry(), sealed.into_sealed()) @@ -174,7 +185,7 @@ mod tests { /// A data blob sealed by hand under the keys of object 2 and the AAD of `context`. fn seal_inner_in(context: &BlobContext, blob_id: &BlobId, inner: &[u8]) -> Vec { - let aad = data_blob_aad(context, blob_id); + let aad = blob::data_blob_aad(context, blob_id); cx_aead::seal(keys(2).chunk_key(), &aad, inner, NonceKind::Hedged).expect("seals") } @@ -184,7 +195,7 @@ mod tests { let inner = compressor .encode_chunk(chunk, ObjectClass::Ordinary) .expect("encodes"); - let view = decode_inner(&inner).expect("well formed"); + let view = inner::decode_inner(&inner).expect("well formed"); assert_eq!(view.comp(), Comp::Zstd, "test data compresses"); view.payload().to_vec() } @@ -256,7 +267,7 @@ mod tests { BlobContext::new(*base.vault_id(), *base.object_id(), dek), ]; // The inner plaintext of the chunk, sealed under the right key and a changed AAD. - let inner = encode_inner(Comp::Raw, &chunk).expect("encodes"); + let inner = inner::encode_inner(Comp::Raw, &chunk).expect("encodes"); let keyed_id = BlobId::try_from_bytes(*mac::mac(keys(2).blob_id_key(), &chunk).as_bytes()) .expect("non-zero"); let keyed_entry = ChunkEntry::new(keyed_id, chunk.len() as u64); @@ -316,7 +327,7 @@ mod tests { #[test] fn a_keyed_id_that_does_not_match_the_plaintext_is_binding() { let chunk = b"chunk".to_vec(); - let inner = encode_inner(Comp::Raw, &chunk).expect("encodes"); + let inner = inner::encode_inner(Comp::Raw, &chunk).expect("encodes"); let sealed = seal_inner(&id(7), &inner); let entry = ChunkEntry::new(id(7), 5); assert_eq!( @@ -352,7 +363,7 @@ mod tests { #[cfg_attr(miri, ignore = "calls into libzstd")] fn a_compressed_chunk_of_a_secret_object_is_padding() { let chunk = text(50_000); - let inner = encode_inner(Comp::Zstd, &frame(&chunk)).expect("encodes"); + let inner = inner::encode_inner(Comp::Zstd, &frame(&chunk)).expect("encodes"); let sealed = seal_inner(&id(7), &inner); let entry = ChunkEntry::new(id(7), 50_000); assert_eq!( @@ -364,7 +375,10 @@ mod tests { #[test] fn raw_payloads_must_be_exactly_plain_len_bytes() { - let raw = seal_inner(&id(7), &encode_inner(Comp::Raw, b"chunk").expect("encodes")); + let raw = seal_inner( + &id(7), + &inner::encode_inner(Comp::Raw, b"chunk").expect("encodes"), + ); for len in [0, 4, 6] { assert_eq!( open(ObjectClass::Ordinary, 1, &ChunkEntry::new(id(7), len), &raw), @@ -384,9 +398,12 @@ mod tests { let chunk = text(50_000); let zstd = seal_inner( &id(7), - &encode_inner(Comp::Zstd, &frame(&chunk)).expect("encodes"), + &inner::encode_inner(Comp::Zstd, &frame(&chunk)).expect("encodes"), + ); + let raw = seal_inner( + &id(7), + &inner::encode_inner(Comp::Raw, &chunk).expect("encodes"), ); - let raw = seal_inner(&id(7), &encode_inner(Comp::Raw, &chunk).expect("encodes")); for sealed in [&zstd, &raw] { for len in [49_999, 50_001] { let entry = ChunkEntry::new(id(7), len); @@ -399,7 +416,7 @@ mod tests { } let not_a_frame = seal_inner( &id(7), - &encode_inner(Comp::Zstd, b"garbage").expect("encodes"), + &inner::encode_inner(Comp::Zstd, b"garbage").expect("encodes"), ); let entry = ChunkEntry::new(id(7), 7); assert_eq!( @@ -408,12 +425,68 @@ mod tests { ); } + /// A single-segment frame of an RLE block of 16 `a` bytes and a raw block of `raw` bytes: + /// 13 bytes plus the raw ones, for `16 + raw` bytes of content. + fn rle_then_raw(raw: &[u8]) -> Vec { + let len = 16 + raw.len(); + let mut frame = vec![ + 0x28, + 0xB5, + 0x2F, + 0xFD, + 0x20, + u8::try_from(len).expect("small"), + ]; + frame.extend_from_slice(&(16u32 << 3 | 0b010).to_le_bytes()[..3]); + frame.push(b'a'); + let raw_header = u32::try_from(raw.len()).expect("small") << 3 | 1; + frame.extend_from_slice(&raw_header.to_le_bytes()[..3]); + frame.extend_from_slice(raw); + frame + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn a_frame_that_saves_less_than_a_sixteenth_is_decompress() { + // 45 bytes for 48: 16 × 45 = 15 × 48, kept. 46 for 49 is not. + let kept = rle_then_raw(&[b'b'; 32]); + assert_eq!(kept.len(), 45); + let plain = [vec![b'a'; 16], vec![b'b'; 32]].concat(); + let sealed = seal_inner( + &id(7), + &inner::encode_inner(Comp::Zstd, &kept).expect("encodes"), + ); + let entry = ChunkEntry::new(id(7), 48); + assert_eq!(open(ObjectClass::Ordinary, 1, &entry, &sealed), Ok(plain)); + let over = rle_then_raw(&[b'b'; 33]); + assert_eq!( + Decompressor::new() + .decode(&over, 49) + .map(|plain| plain.len()), + Ok(49) + ); + let sealed = seal_inner( + &id(7), + &inner::encode_inner(Comp::Zstd, &over).expect("encodes"), + ); + let entry = ChunkEntry::new(id(7), 49); + assert_eq!( + open(ObjectClass::Ordinary, 1, &entry, &sealed), + format(FormatError::Decompress) + ); + // Before the blob ID: a keyed object whose ID does not match is still Decompress. + assert_eq!( + open(ObjectClass::Ordinary, 2, &entry, &sealed), + format(FormatError::Decompress) + ); + } + #[test] fn debug_prints_no_plaintext() { let entry = ChunkEntry::new(id(7), 6); let sealed = seal_inner( &id(7), - &encode_inner(Comp::Raw, b"secret").expect("encodes"), + &inner::encode_inner(Comp::Raw, b"secret").expect("encodes"), ); let mut decompressor = Decompressor::new(); let keys = keys(2); @@ -429,10 +502,54 @@ mod tests { assert!(printed.contains("ChunkKeys(..)"), "{printed}"); } + #[test] + fn no_protected_memory_for_a_raw_plaintext_fails_with_memory() { + let chunk = b"chunk".to_vec(); + let inner = inner::encode_inner(Comp::Raw, &chunk).expect("encodes"); + let sealed = seal_inner(&id(7), &inner); + let entry = ChunkEntry::new(id(7), 5); + let _guard = fault::inject(Fault::Allocation(0)); + assert_eq!( + open(ObjectClass::Secret, 1, &entry, &sealed), + Err(ReadError::Memory(MemError::MapFailed)) + ); + assert!(fault::fired()); + assert_eq!(open(ObjectClass::Secret, 1, &entry, &sealed), Ok(chunk)); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn no_protected_memory_for_a_decompressed_plaintext_fails_with_memory() { + let chunk = text(100_000); + let (entry, sealed) = seal(ObjectClass::Ordinary, 2, &chunk); + let _guard = fault::inject(Fault::Allocation(0)); + assert_eq!( + open(ObjectClass::Ordinary, 2, &entry, &sealed), + Err(ReadError::Memory(MemError::MapFailed)) + ); + assert!(fault::fired()); + assert_eq!(open(ObjectClass::Ordinary, 2, &entry, &sealed), Ok(chunk)); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn a_failed_context_reset_while_opening_is_a_zstd_error() { + let chunk = text(100_000); + let (entry, sealed) = seal(ObjectClass::Ordinary, 2, &chunk); + let _guard = fault::inject(Fault::Reset(0usize.wrapping_sub(1))); + assert!(matches!( + open(ObjectClass::Ordinary, 2, &entry, &sealed), + Err(ReadError::Zstd(CompressError::Zstd(_))) + )); + } + #[test] fn an_empty_chunk_opens_empty() { let entry = ChunkEntry::new(id(7), 0); - let sealed = seal_inner(&id(7), &encode_inner(Comp::Raw, b"").expect("encodes")); + let sealed = seal_inner( + &id(7), + &inner::encode_inner(Comp::Raw, b"").expect("encodes"), + ); let keys = keys(2); let opened = ObjectOpener::new(&keys, ObjectClass::Ordinary, 1) .open(&mut Decompressor::new(), &entry, &sealed) diff --git a/crates/engine/core/src/blob/object_sealer.rs b/crates/engine/core/src/blob/object_sealer.rs index 9e3601f..fd39600 100644 --- a/crates/engine/core/src/blob/object_sealer.rs +++ b/crates/engine/core/src/blob/object_sealer.rs @@ -1,12 +1,16 @@ //! Sealing the chunks of one object as data blobs (FS-55). +use std::ptr; + use crypthix_crypto::cx_aead::{self, NonceKind}; use crypthix_crypto::mac; use crypthix_crypto::random; use crypthix_types::id::BlobId; -use crate::blob::{BlobIdKind, ChunkEntry, ChunkKeys, ObjectClass, SealedChunk, data_blob_aad}; -use crate::chunk::ObjectShape; +use crate::blob::{ + self, BlobIdKind, ChunkEntry, ChunkKeys, IdentifiedChunk, ObjectClass, SealedChunk, +}; +use crate::chunk::{ChunkRef, ObjectShape}; use crate::compress::Compressor; use crate::error::WriteError; @@ -15,38 +19,57 @@ use crate::error::WriteError; /// a hedged nonce and the AAD of the [`BlobContext`](crate::blob::BlobContext) its keys were /// derived for. /// -/// It is built once per object from the object's keys and its [`ObjectShape`], which only the -/// chunker gives and which carries the class the object was cut for, so an object is sealed in -/// the class it was cut in. The blob IDs are keyed, `MAC(K_blobid, chunk)`, exactly for an -/// ordinary object of two or more chunks, and random otherwise ([`BlobIdKind::for_object`]), -/// so no caller can give a single-chunk object keyed IDs (T-85). +/// It is built once per object from the object's keys and the [`ObjectShape`] its chunker gave. +/// The blob IDs are keyed, `MAC(K_blobid, chunk)`, exactly for an ordinary object of two or more +/// chunks, and random otherwise ([`BlobIdKind::for_object`]). What it enforces: +/// +/// - every chunk it takes is a [`ChunkRef`], which only the chunker makes, of the sealer's +/// shape: a chunk the chunker cut as an object's only chunk, or cut for the other class, is +/// refused, so no keyed ID is ever computed for it (T-85) and no secret chunk is compressed +/// (T-40); +/// - [`seal`](Self::seal), [`seal_identified`](Self::seal_identified) and +/// [`reuse`](Self::reuse) take chunks 0, 1, 2… in order, and none after the last; +/// - [`finish`](Self::finish) fails unless the last chunk was taken (or the shape has no +/// chunk), and gives the chunk count the manifest must record: exactly one for a single +/// shape, two or more for any other. +/// +/// It does not check that consecutive chunks come from the same chunker: two objects of the +/// same shape could be interleaved. Blobs sealed before a failed `finish` must not be stored. +/// +/// The chunks of one object that are equal get the same keyed ID, so a writer must store one +/// blob per ID: on an ID already stored in this version or the last, it calls `reuse` instead +/// of sealing again (E1). #[derive(Debug)] pub struct ObjectSealer<'k> { keys: &'k ChunkKeys, - class: ObjectClass, + shape: ObjectShape, blob_id_kind: BlobIdKind, + /// Chunks taken so far, sealed or reused: the index the next one must have. + taken: u64, + /// The object's last chunk has been taken. + complete: bool, } impl<'k> ObjectSealer<'k> { /// The sealer of the object `keys` belong to, whose chunker gave `shape` - /// ([`ChunkRef::object_shape`](crate::chunk::ChunkRef::object_shape) or + /// ([`ChunkRef::object_shape`] or /// [`Chunks::object_shape`](crate::chunk::Chunks::object_shape)); the object's class is /// the one it was cut for. #[must_use] pub const fn new(keys: &'k ChunkKeys, shape: ObjectShape) -> Self { - let class = shape.class(); - let chunk_count = if shape.is_single() { 1 } else { 2 }; Self { keys, - class, - blob_id_kind: BlobIdKind::for_object(class, chunk_count), + shape, + blob_id_kind: BlobIdKind::for_object(shape.class(), shape.kind_count()), + taken: 0, + complete: false, } } /// The object's class. #[must_use] pub const fn class(&self) -> ObjectClass { - self.class + self.shape.class() } /// How the object's blob IDs are made. @@ -55,56 +78,385 @@ impl<'k> ObjectSealer<'k> { self.blob_id_kind } - /// Seals one chunk of the object. + /// Works out the keyed blob ID of `chunk` before it is sealed, so a writer can look it up + /// among the blobs already stored (E1). The ID is `None` if the object's blob IDs are + /// random. Pass the result to [`seal_identified`](Self::seal_identified) or + /// [`reuse`](Self::reuse) of this sealer. + /// + /// # Errors + /// + /// - [`WriteError::Sequence`] if `chunk` is not of the sealer's shape. + /// - [`WriteError::Format`] with `ZeroValue` if the keyed ID came out all zero (FS-03). + /// + /// # Panics + /// + /// On Linux, in a child forked without `exec` after the keys were made. + pub fn identify<'c>(&self, chunk: ChunkRef<'c>) -> Result, WriteError> { + if chunk.object_shape() != self.shape { + return Err(WriteError::Sequence); + } + let keyed_id = match self.blob_id_kind { + BlobIdKind::Keyed => { + let mac = mac::mac(self.keys.blob_id_key(), chunk.bytes()); + Some(BlobId::try_from_bytes(*mac.as_bytes())?) + } + BlobIdKind::Random => None, + }; + Ok(IdentifiedChunk::new(self.keys, chunk, keyed_id)) + } + + /// Seals the next chunk of the object: [`identify`](Self::identify), then + /// [`seal_identified`](Self::seal_identified). /// /// # Errors /// - /// - [`WriteError::Format`] with `Limit` if `chunk` is longer than 1 MiB, or `ZeroValue` if - /// a blob ID came out all zero (FS-03). + /// As those two. + /// + /// # Panics + /// + /// On Linux, in a child forked without `exec` after the keys were made. + pub fn seal( + &mut self, + compressor: &mut Compressor, + chunk: ChunkRef<'_>, + ) -> Result { + let identified = self.identify(chunk)?; + self.seal_identified(compressor, identified) + } + + /// Seals the next chunk of the object under the blob ID [`identify`](Self::identify) gave + /// it, or a random one drawn now. + /// + /// # Errors + /// + /// - [`WriteError::Sequence`] if `identified` comes from a sealer of other keys, or is not + /// the next chunk of an object of this sealer's shape. + /// - [`WriteError::Format`] with `Limit` if the chunk is longer than 1 MiB, or `ZeroValue` + /// if a random blob ID came out all zero (FS-03). /// - [`WriteError::Random`] if the kernel gives no random blob ID. /// - [`WriteError::Zstd`] if zstd fails; the chunk is then not stored raw instead. /// - [`WriteError::Seal`] if the seal fails. /// - [`WriteError::Memory`] if protected memory cannot be allocated for the inner plaintext. /// + /// On any error the sealer does not move on, so the same chunk can be given again. + /// /// # Panics /// /// On Linux, in a child forked without `exec` after the keys were made. - pub fn seal( - &self, + pub fn seal_identified( + &mut self, compressor: &mut Compressor, - chunk: &[u8], + identified: IdentifiedChunk<'_, '_>, ) -> Result { - let inner = compressor.encode_chunk(chunk, self.class)?; - let id_bytes = match self.blob_id_kind { - BlobIdKind::Keyed => *mac::mac(self.keys.blob_id_key(), chunk).as_bytes(), - BlobIdKind::Random => random::bytes::<32>()?, + let (keys, chunk, keyed_id) = identified.into_parts(); + self.check_next(keys, chunk)?; + let inner = compressor.encode_chunk(chunk.bytes(), self.class())?; + let blob_id = match keyed_id { + Some(keyed) => keyed, + None => BlobId::try_from_bytes(random::bytes::<32>()?)?, }; - let blob_id = BlobId::try_from_bytes(id_bytes)?; - let aad = data_blob_aad(self.keys.context(), &blob_id); + let aad = blob::data_blob_aad(self.keys.context(), &blob_id); let sealed = cx_aead::seal(self.keys.chunk_key(), &aad, &inner, NonceKind::Hedged)?; - let entry = ChunkEntry::new(blob_id, chunk.len() as u64); + self.advance(chunk); + let entry = ChunkEntry::new(blob_id, chunk.bytes().len() as u64); Ok(SealedChunk::new(entry, sealed)) } + + /// Takes the next chunk of the object without sealing it, because a blob of its keyed ID + /// is already stored, and returns what the manifest records for it (E1, FS-55). + /// + /// # Errors + /// + /// [`WriteError::Sequence`] as for [`seal_identified`](Self::seal_identified), or if the + /// object's blob IDs are random: such blobs are never reused. The sealer then does not move + /// on. + pub fn reuse(&mut self, identified: IdentifiedChunk<'_, '_>) -> Result { + let (keys, chunk, keyed_id) = identified.into_parts(); + self.check_next(keys, chunk)?; + let Some(blob_id) = keyed_id else { + return Err(WriteError::Sequence); + }; + let entry = ChunkEntry::new(blob_id, chunk.bytes().len() as u64); + self.advance(chunk); + Ok(entry) + } + + /// Ends the object and returns the chunk count its manifest must record. + /// + /// # Errors + /// + /// [`WriteError::Sequence`] if the object's last chunk was not taken; an empty object, of + /// no chunk, has none to take. Then the object is incomplete, and nothing sealed for it may + /// be stored. + pub fn finish(self) -> Result { + if self.complete || self.shape.is_empty() { + Ok(self.taken) + } else { + Err(WriteError::Sequence) + } + } + + /// Whether `chunk`, identified under `keys`, is the next chunk of this object, identified + /// under this sealer's keys. + fn check_next(&self, keys: &ChunkKeys, chunk: ChunkRef<'_>) -> Result<(), WriteError> { + let next = ptr::eq(keys, self.keys) + && chunk.object_shape() == self.shape + && chunk.index() == self.taken + && !self.complete; + if next { + Ok(()) + } else { + Err(WriteError::Sequence) + } + } + + /// Moves on past `chunk`, which was sealed or reused. + fn advance(&mut self, chunk: ChunkRef<'_>) { + self.taken = self.taken.saturating_add(1); + self.complete = chunk.is_last(); + } } #[cfg(test)] mod tests { + use crypthix_crypto::secure_mem::MemError; + use super::*; use crate::blob::chunk_keys::tests::keys; + use crate::chunk::ChunkCount; + use crate::compress::CompressError; + use crate::fault::{self, Fault}; + + const SEQUENCE: Result = Err(WriteError::Sequence); + + fn shape(class: ObjectClass, count: ChunkCount) -> ObjectShape { + ObjectShape::new(class, count) + } + + /// Chunk `index` of an object of `class` with `total` chunks. + fn chunk(class: ObjectClass, index: u64, total: u64) -> ChunkRef<'static> { + ChunkRef::new(b"chunk bytes", index, index + 1 == total, class) + } + + /// Seals chunk `index` of an object of `class` and `total` chunks, keeping only the error. + fn seal( + sealer: &mut ObjectSealer<'_>, + class: ObjectClass, + index: u64, + total: u64, + ) -> Result<(), WriteError> { + let mut compressor = Compressor::new().expect("context"); + sealer + .seal(&mut compressor, chunk(class, index, total)) + .map(|_| ()) + } #[test] fn the_kind_follows_the_class_and_the_chunkers_shape() { let keys = keys(2); let cases = [ - (ObjectClass::Ordinary, false, BlobIdKind::Keyed), - (ObjectClass::Ordinary, true, BlobIdKind::Random), - (ObjectClass::Secret, false, BlobIdKind::Random), - (ObjectClass::Secret, true, BlobIdKind::Random), + (ObjectClass::Ordinary, ChunkCount::Many, BlobIdKind::Keyed), + (ObjectClass::Ordinary, ChunkCount::One, BlobIdKind::Random), + (ObjectClass::Ordinary, ChunkCount::Zero, BlobIdKind::Random), + (ObjectClass::Secret, ChunkCount::Many, BlobIdKind::Random), + (ObjectClass::Secret, ChunkCount::One, BlobIdKind::Random), ]; - for (class, single, kind) in cases { - let sealer = ObjectSealer::new(&keys, ObjectShape::new(class, single)); - assert_eq!(sealer.blob_id_kind(), kind, "{class:?} {single}"); + for (class, count, kind) in cases { + let sealer = ObjectSealer::new(&keys, shape(class, count)); + assert_eq!(sealer.blob_id_kind(), kind, "{class:?} {count:?}"); assert_eq!(sealer.class(), class); } } + + #[test] + #[cfg_attr(miri, ignore = "makes a zstd context")] + fn finish_gives_the_count_only_once_the_last_chunk_is_sealed() { + let keys = keys(2); + let secret = ObjectClass::Secret; + let mut whole = ObjectSealer::new(&keys, shape(secret, ChunkCount::Many)); + for index in 0..3 { + seal(&mut whole, secret, index, 3).expect("seals"); + } + assert_eq!(whole.finish(), Ok(3)); + + let mut short = ObjectSealer::new(&keys, shape(secret, ChunkCount::Many)); + for index in 0..2 { + seal(&mut short, secret, index, 3).expect("seals"); + } + assert_eq!(short.finish(), SEQUENCE, "the last chunk is missing"); + + let mut single = ObjectSealer::new(&keys, shape(secret, ChunkCount::One)); + seal(&mut single, secret, 0, 1).expect("seals"); + assert_eq!(single.finish(), Ok(1)); + + for count in [ChunkCount::One, ChunkCount::Many] { + let untouched = ObjectSealer::new(&keys, shape(secret, count)); + assert_eq!(untouched.finish(), SEQUENCE, "{count:?}: nothing sealed"); + } + let empty = ObjectSealer::new(&keys, shape(secret, ChunkCount::Zero)); + assert_eq!( + empty.finish(), + Ok(0), + "an empty object has no chunk to seal" + ); + } + + #[test] + #[cfg_attr(miri, ignore = "makes a zstd context")] + fn chunks_out_of_order_or_past_the_last_are_refused() { + let keys = keys(2); + let secret = ObjectClass::Secret; + let mut sealer = ObjectSealer::new(&keys, shape(secret, ChunkCount::Many)); + assert_eq!( + seal(&mut sealer, secret, 1, 3), + Err(WriteError::Sequence), + "skips chunk 0" + ); + seal(&mut sealer, secret, 0, 3).expect("the refusal did not move the sealer on"); + assert_eq!( + seal(&mut sealer, secret, 0, 3), + Err(WriteError::Sequence), + "chunk 0 again" + ); + seal(&mut sealer, secret, 1, 2).expect("seals the last chunk"); + assert_eq!( + seal(&mut sealer, secret, 2, 3), + Err(WriteError::Sequence), + "a chunk after the last" + ); + assert_eq!(sealer.finish(), Ok(2)); + } + + #[test] + #[cfg_attr(miri, ignore = "makes a zstd context")] + fn a_chunk_of_another_shape_is_refused() { + let keys = keys(2); + let (ordinary, secret) = (ObjectClass::Ordinary, ObjectClass::Secret); + let mut multiple = ObjectSealer::new(&keys, shape(ordinary, ChunkCount::Many)); + assert_eq!( + multiple.identify(chunk(ordinary, 0, 1)).map(|_| ()), + Err(WriteError::Sequence), + "no keyed ID for an object's only chunk" + ); + assert_eq!( + seal(&mut multiple, ordinary, 0, 1), + Err(WriteError::Sequence) + ); + assert_eq!( + seal(&mut multiple, secret, 0, 2), + Err(WriteError::Sequence), + "class" + ); + let mut single = ObjectSealer::new(&keys, shape(ordinary, ChunkCount::One)); + assert_eq!(seal(&mut single, ordinary, 0, 2), Err(WriteError::Sequence)); + let mut empty = ObjectSealer::new(&keys, shape(ordinary, ChunkCount::Zero)); + assert_eq!(seal(&mut empty, ordinary, 0, 1), Err(WriteError::Sequence)); + } + + #[test] + #[cfg_attr(miri, ignore = "makes a zstd context")] + fn only_the_sealer_of_the_same_keys_and_shape_takes_an_identified_chunk() { + let (keys, other_keys) = (keys(2), keys(4)); + let secret = ObjectClass::Secret; + let mut compressor = Compressor::new().expect("context"); + let mut sealer = ObjectSealer::new(&keys, shape(secret, ChunkCount::Many)); + let other = ObjectSealer::new(&other_keys, shape(secret, ChunkCount::Many)); + let foreign = other.identify(chunk(secret, 0, 2)).expect("identifies"); + assert_eq!( + sealer.seal_identified(&mut compressor, foreign).map(|_| ()), + Err(WriteError::Sequence), + "another object's keys" + ); + let single = ObjectSealer::new(&keys, shape(secret, ChunkCount::One)); + let only = single.identify(chunk(secret, 0, 1)).expect("identifies"); + assert_eq!( + sealer.seal_identified(&mut compressor, only).map(|_| ()), + Err(WriteError::Sequence), + "the same keys, another shape" + ); + let own = sealer.identify(chunk(secret, 0, 2)).expect("identifies"); + assert_eq!(own.keyed_id(), None, "secret IDs are random"); + let blob = sealer.seal_identified(&mut compressor, own).expect("seals"); + assert_eq!(blob.entry().plain_len(), 11); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn a_keyed_id_is_worked_out_once_and_sealed_or_reused() { + let keys = keys(2); + let ordinary = ObjectClass::Ordinary; + let mut compressor = Compressor::new().expect("context"); + let mut sealer = ObjectSealer::new(&keys, shape(ordinary, ChunkCount::Many)); + let first = sealer.identify(chunk(ordinary, 0, 3)).expect("identifies"); + let expected = + BlobId::try_from_bytes(*mac::mac(keys.blob_id_key(), b"chunk bytes").as_bytes()) + .expect("non-zero"); + assert_eq!(first.keyed_id(), Some(&expected)); + let blob = sealer + .seal_identified(&mut compressor, first) + .expect("seals"); + assert_eq!(blob.blob_id(), &expected); + + // An equal chunk later in the object has the same ID, so its blob is reused. + let again = sealer.identify(chunk(ordinary, 1, 3)).expect("identifies"); + assert_eq!(again.keyed_id(), Some(&expected)); + let entry = sealer.reuse(again).expect("reuses"); + assert_eq!(entry, ChunkEntry::new(expected, 11)); + let last = sealer + .seal(&mut compressor, chunk(ordinary, 2, 3)) + .expect("seals"); + assert_eq!(last.blob_id(), &expected); + assert_eq!(sealer.finish(), Ok(3)); + } + + #[test] + #[cfg_attr(miri, ignore = "makes a zstd context")] + fn a_random_id_is_never_reused() { + let keys = keys(2); + let secret = ObjectClass::Secret; + let mut sealer = ObjectSealer::new(&keys, shape(secret, ChunkCount::One)); + let identified = sealer.identify(chunk(secret, 0, 1)).expect("identifies"); + assert_eq!(sealer.reuse(identified), Err(WriteError::Sequence)); + seal(&mut sealer, secret, 0, 1).expect("the refusal did not move the sealer on"); + assert_eq!(sealer.finish(), Ok(1)); + } + + #[test] + #[cfg_attr(miri, ignore = "makes a zstd context")] + fn no_protected_memory_for_the_inner_plaintext_fails_and_the_sealer_stays() { + let keys = keys(2); + let mut compressor = Compressor::new().expect("context"); + for class in [ObjectClass::Ordinary, ObjectClass::Secret] { + let mut sealer = ObjectSealer::new(&keys, shape(class, ChunkCount::Many)); + { + let _guard = fault::inject(Fault::Allocation(0)); + assert_eq!( + sealer.seal(&mut compressor, chunk(class, 0, 2)).map(|_| ()), + Err(WriteError::Memory(MemError::MapFailed)), + "{class:?}" + ); + assert!(fault::fired(), "{class:?}"); + } + seal(&mut sealer, class, 0, 2).expect("the failure did not move the sealer on"); + seal(&mut sealer, class, 1, 2).expect("seals"); + assert_eq!(sealer.finish(), Ok(2)); + } + } + + #[test] + #[cfg_attr(miri, ignore = "makes a zstd context")] + fn a_zstd_error_fails_the_seal_and_the_sealer_stays() { + let keys = keys(2); + let mut compressor = Compressor::new().expect("context"); + let class = ObjectClass::Ordinary; + let mut sealer = ObjectSealer::new(&keys, shape(class, ChunkCount::Many)); + { + let _guard = fault::inject(Fault::Compress(0usize.wrapping_sub(1))); + assert!(matches!( + sealer.seal(&mut compressor, chunk(class, 0, 2)), + Err(WriteError::Zstd(CompressError::Zstd(_))) + )); + } + seal(&mut sealer, class, 0, 2).expect("the failure did not move the sealer on"); + } } diff --git a/crates/engine/core/src/blob/open_meta_blob.rs b/crates/engine/core/src/blob/open_meta_blob.rs index 0170c26..c653841 100644 --- a/crates/engine/core/src/blob/open_meta_blob.rs +++ b/crates/engine/core/src/blob/open_meta_blob.rs @@ -4,7 +4,7 @@ use crypthix_crypto::cx_aead; use crypthix_crypto::secure_mem::SecretBuf; use crypthix_types::id::BlobId; -use crate::blob::{MetaKey, meta_blob_aad}; +use crate::blob::{self, MetaKey}; use crate::error::ReadError; /// Opens the meta blob `blob_id` under `key`, with the AAD of the context it was derived for, @@ -26,7 +26,7 @@ pub fn open_meta_blob( blob_id: &BlobId, sealed: &[u8], ) -> Result { - let aad = meta_blob_aad(key.context(), blob_id); + let aad = blob::meta_blob_aad(key.context(), blob_id); Ok(cx_aead::open(key.seal_key(), &aad, sealed)?) } @@ -39,7 +39,7 @@ mod tests { use super::*; use crate::blob::meta_key::tests::meta_context; - use crate::blob::{MetaContext, MetaKind, seal_meta_blob}; + use crate::blob::{MetaContext, MetaKind}; const DECRYPT: Result<(), ReadError> = Err(ReadError::Format(FormatError::Decrypt)); @@ -58,8 +58,8 @@ mod tests { #[test] fn meta_blobs_round_trip_with_random_ids() { let key = key(meta_context(MetaKind::PackTable, 2)); - let first = seal_meta_blob(&key, b"\xa0").expect("seals"); - let second = seal_meta_blob(&key, b"\xa0").expect("seals"); + let first = blob::seal_meta_blob(&key, b"\xa0").expect("seals"); + let second = blob::seal_meta_blob(&key, b"\xa0").expect("seals"); assert_ne!(first.blob_id(), second.blob_id(), "blob IDs are random"); let opened = open_meta_blob(&key, first.blob_id(), first.sealed()).expect("opens"); assert_eq!(opened.as_slice(), b"\xa0"); @@ -73,7 +73,7 @@ mod tests { fn every_bound_field_is_checked() { let context = meta_context(MetaKind::Location, 2); let key = key(context); - let sealed = seal_meta_blob(&key, b"node").expect("seals"); + let sealed = blob::seal_meta_blob(&key, b"node").expect("seals"); let id = *sealed.blob_id(); let bytes = sealed.sealed(); let other_id = BlobId::try_from_bytes([9; 32]).expect("non-zero"); @@ -96,7 +96,7 @@ mod tests { (later, "epoch"), (vault, "vault"), ] { - let aad = meta_blob_aad(&other, &id); + let aad = blob::meta_blob_aad(&other, &id); let resealed = cx_aead::seal(key.seal_key(), &aad, b"node", NonceKind::Hedged).expect("seals"); assert_eq!(open(&key, &id, &resealed), DECRYPT, "{field}"); @@ -116,7 +116,7 @@ mod tests { #[test] fn an_all_zero_nonce_is_a_zero_value() { let key = key(meta_context(MetaKind::KeyTable, 2)); - let sealed = seal_meta_blob(&key, b"node").expect("seals"); + let sealed = blob::seal_meta_blob(&key, b"node").expect("seals"); let mut zeroed = sealed.sealed().to_vec(); zeroed[..cx_aead::NONCE_LEN].fill(0); assert_eq!( diff --git a/crates/engine/core/src/blob/seal_meta_blob.rs b/crates/engine/core/src/blob/seal_meta_blob.rs index 1140e46..4e0c8b3 100644 --- a/crates/engine/core/src/blob/seal_meta_blob.rs +++ b/crates/engine/core/src/blob/seal_meta_blob.rs @@ -4,7 +4,7 @@ use crypthix_crypto::cx_aead::{self, NonceKind}; use crypthix_crypto::random; use crypthix_types::id::BlobId; -use crate::blob::{MetaKey, SealedMeta, meta_blob_aad}; +use crate::blob::{self, MetaKey, SealedMeta}; use crate::error::WriteError; /// Seals the CBOR of a tree node as a meta blob under `key`, with the AAD of the context it was @@ -20,7 +20,7 @@ use crate::error::WriteError; /// On Linux, in a child forked without `exec` after `key` was made. pub fn seal_meta_blob(key: &MetaKey, cbor: &[u8]) -> Result { let blob_id = BlobId::try_from_bytes(random::bytes::<32>()?)?; - let aad = meta_blob_aad(key.context(), &blob_id); + let aad = blob::meta_blob_aad(key.context(), &blob_id); let sealed = cx_aead::seal(key.seal_key(), &aad, cbor, NonceKind::Hedged)?; Ok(SealedMeta::new(blob_id, sealed)) } diff --git a/crates/engine/core/src/chunk/chunk_params.rs b/crates/engine/core/src/chunk/chunk_params.rs index e320b51..d44d7fb 100644 --- a/crates/engine/core/src/chunk/chunk_params.rs +++ b/crates/engine/core/src/chunk/chunk_params.rs @@ -26,7 +26,9 @@ impl ChunkParams { /// Scaled-down sizes for tests and the `chunker` fuzz target: 64, 256 and 1,024 bytes with /// the level 2 masks fastcdc selects for a 256-byte average, `MASKS[10]` and `MASKS[6]`. Not - /// a format 0 set: no object is ever cut with it. + /// a format 0 set: no object is ever cut with it, and it exists only in tests and with the + /// `vectors` feature. + #[cfg(any(test, feature = "vectors"))] pub(crate) const SCALED: Self = Self { min: 64, avg: 256, diff --git a/crates/engine/core/src/chunk/chunk_ref.rs b/crates/engine/core/src/chunk/chunk_ref.rs index 0dbb3b5..7381b65 100644 --- a/crates/engine/core/src/chunk/chunk_ref.rs +++ b/crates/engine/core/src/chunk/chunk_ref.rs @@ -3,12 +3,15 @@ use std::fmt; use crate::blob::ObjectClass; -use crate::chunk::ObjectShape; +use crate::chunk::{ChunkCount, ObjectShape}; -/// A chunk cut by a [`StreamChunker`](crate::chunk::StreamChunker), borrowed from its window. +/// A chunk cut by a [`StreamChunker`](crate::chunk::StreamChunker), borrowed from its window, or +/// by [`Chunks::chunk_refs`](crate::chunk::Chunks::chunk_refs), borrowed from the data. /// /// [`is_last`](ChunkRef::is_last) is known when the chunk is cut, so a writer knows at the first -/// chunk whether the object has a single chunk, which decides its blob IDs (FS-55). +/// chunk whether the object has a single chunk, which decides its blob IDs (FS-55). Only the +/// chunker makes one, so the [`ObjectSealer`](crate::blob::ObjectSealer) that takes it can trust +/// its index, whether it is the last, and its object's class. #[derive(Clone, Copy)] pub struct ChunkRef<'a> { bytes: &'a [u8], @@ -32,6 +35,20 @@ impl<'a> ChunkRef<'a> { } } + /// A chunk with any bytes, index, last flag and class, for the test-vector runners and + /// fuzz targets only: it bypasses the chunker, so it can claim a shape the bytes do not + /// have. + #[cfg(feature = "vectors")] + #[must_use] + pub const fn from_parts( + bytes: &'a [u8], + index: u64, + is_last: bool, + class: ObjectClass, + ) -> Self { + Self::new(bytes, index, is_last, class) + } + /// The chunk's bytes. #[must_use] pub const fn bytes(&self) -> &'a [u8] { @@ -56,7 +73,12 @@ impl<'a> ChunkRef<'a> { /// [`ObjectSealer::new`](crate::blob::ObjectSealer::new) (FS-55). #[must_use] pub const fn object_shape(&self) -> ObjectShape { - ObjectShape::new(self.class, self.index == 0 && self.is_last) + let count = if self.index == 0 && self.is_last { + ChunkCount::One + } else { + ChunkCount::Many + }; + ObjectShape::new(self.class, count) } } @@ -91,9 +113,14 @@ mod tests { #[test] fn the_shape_is_single_only_for_a_first_chunk_that_is_also_last() { for class in [ObjectClass::Ordinary, ObjectClass::Secret] { - for (index, is_last, single) in [(0, true, true), (0, false, false), (1, true, false)] { + let cases = [ + (0, true, ChunkCount::One), + (0, false, ChunkCount::Many), + (1, true, ChunkCount::Many), + ]; + for (index, is_last, count) in cases { let shape = ChunkRef::new(b"x", index, is_last, class).object_shape(); - assert_eq!(shape, ObjectShape::new(class, single), "{index} {is_last}"); + assert_eq!(shape, ObjectShape::new(class, count), "{index} {is_last}"); } } } diff --git a/crates/engine/core/src/chunk/chunks.rs b/crates/engine/core/src/chunk/chunks.rs index 9da04c5..53a5f6c 100644 --- a/crates/engine/core/src/chunk/chunks.rs +++ b/crates/engine/core/src/chunk/chunks.rs @@ -1,12 +1,12 @@ //! Cutting data already in memory. use std::fmt; -use std::iter::FusedIterator; +use std::iter::{self, FusedIterator}; use std::ops::Range; use crate::blob::ObjectClass; -use crate::chunk::cut::cut_for; -use crate::chunk::{ChunkParams, GearTable, ObjectShape}; +use crate::chunk::cut; +use crate::chunk::{ChunkCount, ChunkParams, ChunkRef, GearTable, ObjectShape}; /// The chunks of `data` in an object of a class, as ranges into it, in order (FS-52). Empty /// data has none. An ordinary object is cut with keyed FastCDC, so data no longer than 64 KiB @@ -38,6 +38,8 @@ pub struct Chunks<'a> { class: ObjectClass, data: &'a [u8], offset: usize, + /// Index of the next chunk. + index: u64, params: ChunkParams, } @@ -49,10 +51,10 @@ impl<'a> Chunks<'a> { } /// The chunks of `data` cut at the scaled-down sizes 64, 256 and 1,024 bytes, with the - /// level 2 masks for a 256-byte average. Not part of the API and not a format 0 cut: it + /// level 2 masks for a 256-byte average, for the fuzz targets only: not a format 0 cut. It /// lets the `chunker` fuzz target reach every cut-point edge with inputs of a few KiB, /// where the format 0 hash is only tested 64 KiB into a chunk. - #[doc(hidden)] + #[cfg(feature = "vectors")] pub fn scaled_for_fuzzing(gear: &'a GearTable, class: ObjectClass, data: &'a [u8]) -> Self { Self::with_params(gear, class, data, ChunkParams::SCALED) } @@ -69,18 +71,39 @@ impl<'a> Chunks<'a> { class, data, offset: 0, + index: 0, params, } } - /// The class the chunks are cut for and whether `data` is one chunk or more, which a + /// The class the chunks are cut for and whether `data` is no chunk, one, or more, which a /// writer passes to [`ObjectSealer::new`](crate::blob::ObjectSealer::new) (FS-55). It /// depends on the whole data, not on how far the iterator has gone, and costs one cut. - /// Empty data, which has no chunk to seal, counts as one. #[must_use] pub fn object_shape(&self) -> ObjectShape { - let first = cut_for(self.class, self.gear, self.data, &self.params); - ObjectShape::new(self.class, first >= self.data.len()) + let first = cut::cut_for(self.class, self.gear, self.data, &self.params); + let count = if self.data.is_empty() { + ChunkCount::Zero + } else if first >= self.data.len() { + ChunkCount::One + } else { + ChunkCount::Many + }; + ObjectShape::new(self.class, count) + } + + /// The chunks not yet cut, as the [`ChunkRef`]s an + /// [`ObjectSealer`](crate::blob::ObjectSealer) seals: each with its bytes, its index in the + /// object and whether it is the last. + pub fn chunk_refs(self) -> impl Iterator> { + let mut chunks = self; + iter::from_fn(move || { + let index = chunks.index; + let range = chunks.next()?; + let is_last = range.end == chunks.data.len(); + let bytes = chunks.data.get(range)?; + Some(ChunkRef::new(bytes, index, is_last, chunks.class)) + }) } } @@ -89,12 +112,13 @@ impl Iterator for Chunks<'_> { fn next(&mut self) -> Option> { let rest = self.data.get(self.offset..)?; - let len = cut_for(self.class, self.gear, rest, &self.params); + let len = cut::cut_for(self.class, self.gear, rest, &self.params); if len == 0 { return None; } let start = self.offset; self.offset += len; + self.index = self.index.saturating_add(1); Some(start..self.offset) } } @@ -114,12 +138,11 @@ impl fmt::Debug for Chunks<'_> { #[cfg(test)] mod tests { - use proptest::collection::vec; - use proptest::prelude::{any, prop_assert, prop_assert_eq, proptest}; + use proptest::prelude::{prop_assert, prop_assert_eq, proptest}; use super::*; use crate::test_data::gear_table as table; - use crate::test_data::{chunk_ranges, pseudo_random}; + use crate::test_data::{any_byte, bytes, chunk_ranges, pseudo_random}; const CLASSES: [ObjectClass; 2] = [ObjectClass::Ordinary, ObjectClass::Secret]; @@ -134,7 +157,7 @@ mod tests { } #[test] - fn the_shape_is_single_exactly_when_there_is_at_most_one_chunk() { + fn the_shape_counts_none_one_or_more_chunks() { let gear = table(1); let params = ChunkParams::SCALED; for class in CLASSES { @@ -142,12 +165,53 @@ mod tests { let data = pseudo_random(3, len); let count = chunk_ranges(&gear, class, &data, params).len(); let shape = Chunks::with_params(&gear, class, &data, params).object_shape(); - assert_eq!(shape.is_single(), count <= 1, "{class:?} {len}"); + assert_eq!( + (shape.is_empty(), shape.is_single()), + (count == 0, count == 1), + "{class:?} {len}" + ); assert_eq!(shape.class(), class); } } } + #[test] + fn chunk_refs_are_the_ranges_with_their_index_and_last_flag() { + let gear = table(1); + let params = ChunkParams::SCALED; + for class in CLASSES { + let data = pseudo_random(4, 5_000); + let ranges = chunk_ranges(&gear, class, &data, params); + assert!(ranges.len() > 2, "{class:?}: enough chunks to test"); + let mut chunks = Chunks::with_params(&gear, class, &data, params); + assert_eq!(chunks.next(), Some(ranges[0].clone())); + let shape = chunks.object_shape(); + let refs: Vec> = chunks.chunk_refs().collect(); + assert_eq!(refs.len(), ranges.len() - 1, "{class:?}: the rest"); + for (chunk, range) in refs.iter().zip(&ranges[1..]) { + let index = chunk.index(); + assert_eq!(chunk.bytes(), &data[range.clone()], "{class:?} {index}"); + assert_eq!( + index, + ranges.iter().position(|r| r == range).expect("a range") as u64 + ); + assert_eq!( + chunk.is_last(), + range.end == data.len(), + "{class:?} {index}" + ); + assert_eq!(chunk.object_shape(), shape, "{class:?} {index}"); + } + let one: Vec> = Chunks::with_params(&gear, class, &data[..10], params) + .chunk_refs() + .collect(); + assert_eq!(one.len(), 1); + assert_eq!((one[0].index(), one[0].is_last()), (0, true)); + let none = Chunks::with_params(&gear, class, &[], params).chunk_refs(); + assert_eq!(none.count(), 0); + } + } + #[test] fn debug_shows_no_data() { let gear = table(1); @@ -165,8 +229,7 @@ mod tests { proptest! { #[test] - #[cfg_attr(miri, ignore = "proptest is slow under Miri")] - fn chunks_tile_the_data_within_the_size_bounds(seed in 1u8.., data in vec(any::(), 0..6_000)) { + fn chunks_tile_the_data_within_the_size_bounds(seed in 1u8.., data in bytes(0..6_000, any_byte)) { let gear = table(seed); let params = ChunkParams::SCALED; let ranges = chunk_ranges(&gear, ObjectClass::Ordinary, &data, params); @@ -188,10 +251,9 @@ mod tests { } #[test] - #[cfg_attr(miri, ignore = "proptest is slow under Miri")] fn secret_chunks_are_fixed_steps_of_the_maximum( seed in 1u8.., - data in vec(any::(), 0..6_000), + data in bytes(0..6_000, any_byte), ) { let gear = table(seed); let params = ChunkParams::SCALED; diff --git a/crates/engine/core/src/chunk/cut.rs b/crates/engine/core/src/chunk/cut.rs index 5082b13..9ccfe80 100644 --- a/crates/engine/core/src/chunk/cut.rs +++ b/crates/engine/core/src/chunk/cut.rs @@ -3,23 +3,13 @@ use crate::blob::ObjectClass; use crate::chunk::{ChunkParams, GearTable}; -/// The length of the first chunk of `data` in an ordinary object: all of it if it is no longer -/// than the 64 KiB minimum, otherwise between the minimum and the 1 MiB maximum (FS-52). Zero -/// only for empty `data`. -/// -/// A secret-class object is not cut this way but at fixed 1 MiB steps. To cut a whole object -/// of either class, use [`Chunks`](crate::chunk::Chunks) or -/// [`StreamChunker`](crate::chunk::StreamChunker). -#[must_use] -pub fn cut(gear: &GearTable, data: &[u8]) -> usize { - cut_with(gear, data, &ChunkParams::FORMAT_0) -} - /// The length of the first chunk of `data` in an object of `class` (FS-52). The ordinary class -/// takes the keyed FastCDC cut. The secret class takes the maximum, or all of `data` if it is -/// shorter, and reads no byte of it: the FastCDC loop indexes the gear table with plaintext -/// bytes and stops early where it cuts, which a process sharing the cache can time, and secret -/// chunks never deduplicate, so content-defined cuts would give them nothing (T-84). +/// takes the keyed FastCDC cut: all of `data` if it is no longer than the minimum, otherwise +/// between the minimum and the maximum, and zero only for empty `data`. The secret class takes +/// the maximum, or all of `data` if it is shorter, and reads no byte of it: the FastCDC loop +/// indexes the gear table with plaintext bytes and stops early where it cuts, which a process +/// sharing the cache can time, and secret chunks never deduplicate, so content-defined cuts +/// would give them nothing (T-84). pub(crate) fn cut_for( class: ObjectClass, gear: &GearTable, @@ -32,8 +22,8 @@ pub(crate) fn cut_for( } } -/// [`cut`] with any sizes and masks: the loop of `fastcdc::v2020::cut_gear` 5.0.0, with -/// `gear_ls[b]` computed as `gear[b] << 1`. +/// The keyed FastCDC cut of an ordinary object, with any sizes and masks: the loop of +/// `fastcdc::v2020::cut_gear` 5.0.0, with `gear_ls[b]` computed as `gear[b] << 1`. fn cut_with(gear: &GearTable, data: &[u8], params: &ChunkParams) -> usize { let mut remaining = data.len(); if remaining <= params.min { @@ -90,13 +80,17 @@ fn cut_with(gear: &GearTable, data: &[u8], params: &ChunkParams) -> usize { #[cfg(test)] mod tests { use fastcdc::v2020; - use proptest::collection::vec; - use proptest::prelude::{Just, Strategy, any, prop_assert_eq, prop_oneof, proptest}; + use proptest::prelude::{Strategy, prop_assert_eq, prop_oneof, proptest}; use super::*; use crate::limits::{MAX_CHUNK, MIN_CHUNK}; use crate::test_data::gear_table as table; - use crate::test_data::{chunk_ranges, pseudo_random}; + use crate::test_data::{any_byte, bytes, chunk_ranges, pseudo_random}; + + /// The first format 0 cut of `data` in an ordinary object. + fn cut(gear: &GearTable, data: &[u8]) -> usize { + cut_for(ObjectClass::Ordinary, gear, data, &ChunkParams::FORMAT_0) + } /// The chunk lengths fastcdc cuts from `data` with `gear`'s words. fn fastcdc_lengths(gear: &GearTable, data: &[u8], params: &ChunkParams) -> Vec { @@ -233,15 +227,14 @@ mod tests { /// Bytes that cut often: random, a small alphabet, or long runs. fn data() -> impl Strategy> { prop_oneof![ - vec(any::(), 0..8_000), - vec(0u8..4, 0..8_000), - vec(prop_oneof![Just(0u8), Just(255u8)], 0..4_000), + bytes(0..8_000, any_byte), + bytes(0..8_000, |byte| byte % 4), + bytes(0..4_000, |byte| if byte & 1 == 0 { 0 } else { 255 }), ] } proptest! { #[test] - #[cfg_attr(miri, ignore = "proptest is slow under Miri")] fn scaled_chunks_match_fastcdc(seed in 1u8.., data in data()) { let gear = table(seed); let params = ChunkParams::SCALED; diff --git a/crates/engine/core/src/chunk/gear_table.rs b/crates/engine/core/src/chunk/gear_table.rs index 87e056c..cd07b60 100644 --- a/crates/engine/core/src/chunk/gear_table.rs +++ b/crates/engine/core/src/chunk/gear_table.rs @@ -17,10 +17,10 @@ use crate::limits::GEAR_TABLE_LEN; /// It is the first 2,048 bytes of the keyed BLAKE3 XOF under /// `K_gear = KDF(chunker_seed, -, kdf/gear, vault_id)` over the empty input, read as /// little-endian `u64` words. The shifted table that FastCDC also uses is computed from it as -/// each word is read. It is kept in a [`SecretBuf`]: plaintext memory, locked where -/// `RLIMIT_MEMLOCK` allows, wiped on free and left out of core dumps and forked children, but -/// not in secret pages as keys are, which fits -/// the design's assumption that the seed may leak anyway: keyed gear tables have been +/// each word is read. It is kept in a [`SecretBuf`]: plaintext memory, wiped on free and, on +/// Linux, locked where `RLIMIT_MEMLOCK` allows and left out of core dumps and forked children +/// (plain heap memory elsewhere and under Miri), but not in secret pages as keys are, which +/// fits the design's assumption that the seed may leak anyway: keyed gear tables have been /// recovered from observed chunk sizes (ePrint 2025/558). Padmé coarsens those sizes and packs /// hide them (T-84). Only ordinary objects are cut with it; secret-class objects are cut at /// fixed 1 MiB steps and never index it with their bytes (FS-52). @@ -39,6 +39,8 @@ impl GearTable { pub fn derive(chunker_seed: &KdfKey, vault_id: &VaultId) -> Result { let context = KdfContext::new().field(vault_id.as_bytes()); let key: XofKey = kdf::kdf(chunker_seed, None, XofKeyLabel::Gear, &context)?; + #[cfg(test)] + crate::fault::allocation()?; let mut table = SecretBuf::try_zeroed(GEAR_TABLE_LEN)?; mac::xof(&key, table.as_mut_slice()); Ok(Self(table)) @@ -73,8 +75,20 @@ impl fmt::Debug for GearTable { #[cfg(test)] mod tests { use super::*; + use crate::fault::{self, Fault}; use crate::test_data::gear_table as table; + #[test] + fn no_protected_memory_fails_with_memory() { + let key = KdfKey::from_bytes([3; 32]).expect("non-zero key"); + let vault_id = VaultId::try_from_bytes([0x11; 16]).expect("non-zero ID"); + let _guard = fault::inject(Fault::Allocation(0)); + assert_eq!( + GearTable::derive(&key, &vault_id).map(|_| ()), + Err(MemError::MapFailed) + ); + } + #[test] fn the_table_is_the_gear_xof_of_the_vault() { let key = KdfKey::from_bytes([3; 32]).expect("non-zero key"); diff --git a/crates/engine/core/src/chunk/mod.rs b/crates/engine/core/src/chunk/mod.rs index a0d8fd4..8ada1bd 100644 --- a/crates/engine/core/src/chunk/mod.rs +++ b/crates/engine/core/src/chunk/mod.rs @@ -25,9 +25,9 @@ mod stream_error; pub(crate) use chunk_params::ChunkParams; pub use chunk_ref::ChunkRef; pub use chunks::Chunks; -pub use cut::cut; pub use gear_table::GearTable; pub use masks::{MASK_L, MASK_S}; +pub(crate) use object_shape::ChunkCount; pub use object_shape::ObjectShape; pub use stream_chunker::StreamChunker; pub use stream_error::StreamError; diff --git a/crates/engine/core/src/chunk/object_shape.rs b/crates/engine/core/src/chunk/object_shape.rs index 62ce97b..7783775 100644 --- a/crates/engine/core/src/chunk/object_shape.rs +++ b/crates/engine/core/src/chunk/object_shape.rs @@ -1,29 +1,43 @@ -//! An object's class and whether it has one chunk or more, as the chunker found. +//! An object's class and whether it has no chunk, one, or more, as the chunker found. use crate::blob::ObjectClass; -/// The class an object was cut for and whether it has a single chunk or two or more, which -/// together decide whether its blob IDs are keyed (FS-55). +/// The class an object was cut for and whether it has no chunk, a single chunk, or two or more, +/// which together decide whether its blob IDs are keyed (FS-55). /// /// Only the chunker makes one, from the class it cut for and what it cut: -/// [`ChunkRef::object_shape`] and [`Chunks::object_shape`]. A writer therefore cannot claim two -/// or more chunks for an object that has one, which would give a single-chunk object keyed -/// blob IDs that a reader, deriving the kind from the manifest's `chunk_count`, never notices -/// (T-85); nor seal as ordinary an object it cut as secret, or the reverse, since -/// [`ObjectSealer::new`](crate::blob::ObjectSealer::new) takes the class from here. +/// [`ChunkRef::object_shape`] and [`Chunks::object_shape`]. A shape alone does not say which +/// object it describes, so an [`ObjectSealer`](crate::blob::ObjectSealer) built from it checks +/// every [`ChunkRef`] it seals against it, and its +/// [`finish`](crate::blob::ObjectSealer::finish) fails unless the object's last chunk was +/// sealed. A writer therefore cannot give keyed blob IDs to an object of a single chunk, which a +/// reader, deriving the kind from the manifest's `chunk_count`, would never notice (T-85), nor +/// seal as ordinary an object it cut as secret, or the reverse. /// +/// [`ChunkRef`]: crate::chunk::ChunkRef /// [`ChunkRef::object_shape`]: crate::chunk::ChunkRef::object_shape /// [`Chunks::object_shape`]: crate::chunk::Chunks::object_shape #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct ObjectShape { class: ObjectClass, - single: bool, + count: ChunkCount, +} + +/// How many chunks an object has, as far as its blob IDs care. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub(crate) enum ChunkCount { + /// Empty data: nothing to seal. + Zero, + /// One chunk. + One, + /// Two or more chunks. + Many, } impl ObjectShape { - /// The shape of an object of `class`, with one chunk if `single`. - pub(crate) const fn new(class: ObjectClass, single: bool) -> Self { - Self { class, single } + /// The shape of an object of `class` with `count` chunks. + pub(crate) const fn new(class: ObjectClass, count: ChunkCount) -> Self { + Self { class, count } } /// The class the object was cut for, which its sealer uses too. @@ -32,9 +46,48 @@ impl ObjectShape { self.class } + /// Whether the object has no chunk: its data is empty. + #[must_use] + pub const fn is_empty(self) -> bool { + matches!(self.count, ChunkCount::Zero) + } + /// Whether the object has exactly one chunk. #[must_use] pub const fn is_single(self) -> bool { - self.single + matches!(self.count, ChunkCount::One) + } + + /// The number of chunks [`BlobIdKind::for_object`](crate::blob::BlobIdKind::for_object) + /// needs: 0, 1, or 2 for any number from two. + pub(crate) const fn kind_count(self) -> u64 { + match self.count { + ChunkCount::Zero => 0, + ChunkCount::One => 1, + ChunkCount::Many => 2, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_count_answers_one_question() { + let cases = [ + (ChunkCount::Zero, true, false, 0), + (ChunkCount::One, false, true, 1), + (ChunkCount::Many, false, false, 2), + ]; + for (count, empty, single, kind_count) in cases { + let shape = ObjectShape::new(ObjectClass::Secret, count); + assert_eq!( + (shape.is_empty(), shape.is_single(), shape.kind_count()), + (empty, single, kind_count), + "{count:?}" + ); + assert_eq!(shape.class(), ObjectClass::Secret); + } } } diff --git a/crates/engine/core/src/chunk/stream_chunker.rs b/crates/engine/core/src/chunk/stream_chunker.rs index 9305006..152e5ca 100644 --- a/crates/engine/core/src/chunk/stream_chunker.rs +++ b/crates/engine/core/src/chunk/stream_chunker.rs @@ -1,12 +1,12 @@ //! Cutting a reader. use std::fmt; -use std::io::{ErrorKind, Read}; +use std::io::{self, ErrorKind, Read}; use crypthix_crypto::secure_mem::SecretBuf; use crate::blob::ObjectClass; -use crate::chunk::cut::cut_for; +use crate::chunk::cut; use crate::chunk::{ChunkParams, ChunkRef, GearTable, StreamError}; /// Cuts the bytes of a reader, for an object of a class, into the same chunks @@ -66,12 +66,12 @@ impl<'g, R: Read> StreamChunker<'g, R> { /// A chunker at the scaled-down sizes of /// [`Chunks::scaled_for_fuzzing`](crate::chunk::Chunks::scaled_for_fuzzing), with a - /// 2 KiB window. Not part of the API and not a format 0 cut; for the `chunker` fuzz target. + /// 2 KiB window, for the `chunker` fuzz target only: not a format 0 cut. /// /// # Errors /// /// [`StreamError::Memory`] if protected memory cannot be allocated for the window. - #[doc(hidden)] + #[cfg(feature = "vectors")] pub fn scaled_for_fuzzing( gear: &'g GearTable, class: ObjectClass, @@ -87,6 +87,8 @@ impl<'g, R: Read> StreamChunker<'g, R> { reader: R, params: ChunkParams, ) -> Result { + #[cfg(test)] + crate::fault::allocation()?; let window = SecretBuf::try_zeroed(params.max * 2)?; Ok(Self { gear, @@ -129,7 +131,7 @@ impl<'g, R: Read> StreamChunker<'g, R> { self.failed = true; return Err(StreamError::Failed); }; - let len = cut_for(self.class, self.gear, rest, &self.params); + let len = cut::cut_for(self.class, self.gear, rest, &self.params); let Some(bytes) = rest.get(..len) else { self.failed = true; return Err(StreamError::Failed); @@ -163,7 +165,7 @@ impl<'g, R: Read> StreamChunker<'g, R> { } // A reader that claims more than it was given breaks the `Read` contract. Ok(read) if read > free.len() => { - return Err(std::io::Error::from(ErrorKind::InvalidData).into()); + return Err(io::Error::from(ErrorKind::InvalidData).into()); } Ok(read) => self.end += read, Err(error) if error.kind() == ErrorKind::Interrupted => {} @@ -188,15 +190,16 @@ impl fmt::Debug for StreamChunker<'_, R> { #[cfg(test)] mod tests { - use std::io; use std::ops::Range; + use crypthix_crypto::secure_mem::MemError; use proptest::collection::vec; - use proptest::prelude::{any, prop_assert_eq, proptest}; + use proptest::prelude::{prop_assert_eq, proptest}; use super::*; + use crate::fault::{self, Fault}; use crate::test_data::gear_table as table; - use crate::test_data::{chunk_ranges, most_chunks, pseudo_random}; + use crate::test_data::{any_byte, bytes, chunk_ranges, most_chunks, pseudo_random}; /// A reader that returns at most the next step's bytes per call, and `Interrupted` where a /// step is 0. @@ -373,6 +376,81 @@ mod tests { assert!(matches!(chunker.next_chunk(), Err(StreamError::Failed))); } + #[test] + fn no_protected_memory_for_the_window_fails_with_memory() { + let gear = table(1); + let _guard = fault::inject(Fault::Allocation(0)); + // Fails before the 2 MiB window is allocated, so this is quick under Miri too. + assert!(matches!( + StreamChunker::new(&gear, ObjectClass::Ordinary, &b"data"[..]), + Err(StreamError::Memory(MemError::MapFailed)) + )); + } + + #[test] + fn a_hard_error_on_a_later_refill_is_returned_then_the_chunker_stays_failed() { + /// Fills the first window from `data`, then fails; a third read means the chunker + /// read on after the error. + struct FailsLater<'a> { + data: &'a [u8], + reads: usize, + } + impl Read for FailsLater<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.reads += 1; + match self.reads { + 1 => { + let len = buf.len().min(self.data.len()); + buf[..len].copy_from_slice(&self.data[..len]); + self.data = &self.data[len..]; + Ok(len) + } + 2 => Err(io::Error::other("disk")), + _ => panic!("read {} after a hard error", self.reads), + } + } + } + let gear = table(1); + let params = ChunkParams::SCALED; + // More than the window, so the first read fills it and a later chunk needs a refill. + let data = pseudo_random(5, 3 * params.max); + for class in [ObjectClass::Ordinary, ObjectClass::Secret] { + let reader = FailsLater { + data: &data, + reads: 0, + }; + let mut chunker = + StreamChunker::with_params(&gear, class, reader, params).expect("window"); + let mut offset = 0; + let error = loop { + match chunker.next_chunk() { + Ok(Some(chunk)) => { + let bytes = chunk.bytes(); + assert_eq!(bytes, &data[offset..offset + bytes.len()], "{class:?}"); + assert!(!chunk.is_last(), "{class:?}: the input did not end"); + offset += bytes.len(); + assert!(offset <= 2 * params.max, "{class:?}: cut past the window"); + } + Ok(None) => panic!("{class:?}: a failed read taken for the end"), + Err(error) => break error, + } + }; + assert!(offset > 0, "{class:?}: chunks before the error"); + assert!( + matches!(&error, StreamError::Io(io) if io.to_string() == "disk"), + "{class:?}: {error:?}" + ); + assert_eq!(chunker.reader.reads, 2, "{class:?}"); + for _ in 0..2 { + assert!(matches!(chunker.next_chunk(), Err(StreamError::Failed))); + } + assert_eq!( + chunker.reader.reads, 2, + "{class:?}: no read after the error" + ); + } + } + #[test] fn a_failed_read_is_never_taken_for_the_end() { /// Gives `data` once, then fails once, then reports the end. @@ -450,10 +528,9 @@ mod tests { proptest! { #[test] - #[cfg_attr(miri, ignore = "proptest is slow under Miri")] fn streaming_equals_in_memory( seed in 1u8.., - data in vec(any::(), 0..6_000), + data in bytes(0..6_000, any_byte), steps in vec(0usize..700, 1..8), secret: bool, ) { @@ -466,8 +543,7 @@ mod tests { } #[test] - #[cfg_attr(miri, ignore = "proptest is slow under Miri")] - fn chunks_reassemble_the_stream(seed in 1u8.., data in vec(0u8..3, 0..6_000)) { + fn chunks_reassemble_the_stream(seed in 1u8.., data in bytes(0..6_000, |byte| byte % 3)) { let gear = table(seed); let chunks = streamed( &gear, diff --git a/crates/engine/core/src/compress/compressor.rs b/crates/engine/core/src/compress/compressor.rs index dc6c29f..96d4fc0 100644 --- a/crates/engine/core/src/compress/compressor.rs +++ b/crates/engine/core/src/compress/compressor.rs @@ -7,9 +7,9 @@ use crypthix_types::format_error::FormatError; use zstd_safe::{CCtx, CParameter}; use crate::blob::ObjectClass; -use crate::compress::{CompressError, keep_compressed}; +use crate::compress::{self, CompressError}; use crate::error::WriteError; -use crate::inner::{Comp, encode_inner}; +use crate::inner::{self, Comp}; use crate::limits::{MAX_CHUNK, WINDOW_LOG, ZSTD_LEVEL}; /// Turns chunks into inner plaintexts (FS-53, FS-54), reusing one zstd context and one scratch @@ -17,10 +17,12 @@ use crate::limits::{MAX_CHUNK, WINDOW_LOG, ZSTD_LEVEL}; /// /// The frame is one zstd frame at level 3 with its content size, no checksum, no dictionary /// ID and a window of at most 1 MiB. It is kept only if `16 × frame ≤ 15 × chunk` -/// ([`keep_compressed`]); otherwise, and always for the secret class, the chunk is stored raw. +/// ([`keep_compressed`](compress::keep_compressed)); otherwise, and always for the secret +/// class, the chunk is stored raw. pub struct Compressor { cctx: CCtx<'static>, - /// Large enough for the frame of a maximum chunk; wiped after each use. + /// Large enough for the frame of a maximum chunk. The part zstd is given, the bound of the + /// chunk, is wiped after each use. scratch: SecretBuf, } @@ -47,6 +49,8 @@ impl Compressor { cctx.set_parameter(parameter) .map_err(CompressError::from_code)?; } + #[cfg(test)] + crate::fault::allocation()?; let scratch = SecretBuf::try_zeroed(zstd_safe::compress_bound(MAX_CHUNK))?; Ok(Self { cctx, scratch }) } @@ -68,30 +72,38 @@ impl Compressor { return Err(FormatError::Limit.into()); } match class { - ObjectClass::Secret => return encode_inner(Comp::Raw, chunk), + ObjectClass::Secret => return inner::encode_inner(Comp::Raw, chunk), ObjectClass::Ordinary => {} } - let scratch = self.scratch.as_mut_slice(); - let written = match self.cctx.compress2(scratch, chunk) { - Ok(written) => written, - Err(code) => { - // zstd may have written part of a frame, and does not say how much. - scratch.fill(0); - return Err(CompressError::from_code(code).into()); - } - }; - // zstd never reports more than the buffer it was given; failing instead keeps this - // panic-free. - let Some(frame) = scratch.get_mut(..written) else { - scratch.fill(0); - return Err(CompressError::Zstd("frame longer than its buffer").into()); + // zstd is given only the bound of this chunk, so the slice to wipe afterwards grows with + // the chunk, not with the buffer. The scratch buffer holds the bound of a maximum chunk, + // so this cannot fail; failing instead keeps this panic-free. + let bound = zstd_safe::compress_bound(chunk.len()); + let Some(scratch) = self.scratch.as_mut_slice().get_mut(..bound) else { + return Err(CompressError::Zstd("chunk bound longer than the scratch buffer").into()); }; - let inner = if keep_compressed(frame.len() as u64, chunk.len() as u64) { - encode_inner(Comp::Zstd, frame) - } else { - encode_inner(Comp::Raw, chunk) + let compressed = self.cctx.compress2(&mut *scratch, chunk); + #[cfg(test)] + let compressed = crate::fault::compress(compressed); + let inner = match compressed { + // zstd never reports more than the buffer it was given; failing instead keeps this + // panic-free. + Ok(written) => match scratch.get(..written) { + Some(frame) + if compress::keep_compressed(frame.len() as u64, chunk.len() as u64) => + { + inner::encode_inner(Comp::Zstd, frame) + } + Some(_) => inner::encode_inner(Comp::Raw, chunk), + None => Err(CompressError::Zstd("frame longer than its buffer").into()), + }, + Err(code) => Err(CompressError::from_code(code).into()), }; - frame.fill(0); + // libzstd writes past the length it returns: its bit streams flush whole words, 3 to 7 + // bytes past the frame, and the tests below see up to 53 for some chunks. It never + // writes past the slice it was given, so that whole slice is wiped on every path, not + // only the frame. + scratch.fill(0); inner } } @@ -105,9 +117,11 @@ impl fmt::Debug for Compressor { #[cfg(test)] mod tests { + use crypthix_crypto::secure_mem::MemError; + use super::*; - use crate::compress::frame_check::frame_check; - use crate::inner::decode_inner; + use crate::compress::frame_check; + use crate::fault::{self, Fault}; use crate::test_data::pseudo_random; fn text(len: usize) -> Vec { @@ -127,10 +141,10 @@ mod tests { let inner = compressor .encode_chunk(&chunk, ObjectClass::Ordinary) .expect("encodes"); - let view = decode_inner(&inner).expect("well formed"); + let view = inner::decode_inner(&inner).expect("well formed"); assert_eq!(view.comp(), Comp::Zstd); assert!(view.payload().len() < 1_000); - assert_eq!(frame_check(view.payload(), 100_000), Ok(())); + assert_eq!(frame_check::frame_check(view.payload(), 100_000), Ok(())); // No checksum, no dictionary ID, content size declared. assert_eq!(view.payload()[4] & 0x0F, 0); let again = compressor @@ -156,7 +170,11 @@ mod tests { .compress2(&mut frame[..], &chunk) .expect("compresses"); frame.truncate(written); - assert_eq!(frame_check(&frame, len as u64), Ok(()), "{len}"); + assert_eq!( + frame_check::frame_check(&frame, len as u64), + Ok(()), + "{len}" + ); } } @@ -168,7 +186,7 @@ mod tests { let inner = compressor .encode_chunk(&chunk, ObjectClass::Ordinary) .expect("encodes"); - let view = decode_inner(&inner).expect("well formed"); + let view = inner::decode_inner(&inner).expect("well formed"); assert_eq!(view.comp(), Comp::Raw); assert_eq!(view.payload(), chunk.as_slice()); } @@ -181,7 +199,7 @@ mod tests { let inner = compressor .encode_chunk(&chunk, ObjectClass::Secret) .expect("encodes"); - let view = decode_inner(&inner).expect("well formed"); + let view = inner::decode_inner(&inner).expect("well formed"); assert_eq!(view.comp(), Comp::Raw); assert_eq!(view.payload(), chunk.as_slice()); } @@ -194,7 +212,10 @@ mod tests { let inner = compressor .encode_chunk(&largest, ObjectClass::Ordinary) .expect("1 MiB"); - assert_eq!(decode_inner(&inner).map(|view| view.comp()), Ok(Comp::Zstd)); + assert_eq!( + inner::decode_inner(&inner).map(|view| view.comp()), + Ok(Comp::Zstd) + ); let random = pseudo_random(2, MAX_CHUNK); let raw = compressor .encode_chunk(&random, ObjectClass::Ordinary) @@ -219,7 +240,10 @@ mod tests { let inner = compressor .encode_chunk(&chunk, ObjectClass::Ordinary) .expect("encodes"); - assert_eq!(decode_inner(&inner).map(|view| view.comp()), Ok(Comp::Raw)); + assert_eq!( + inner::decode_inner(&inner).map(|view| view.comp()), + Ok(Comp::Raw) + ); let mut frame = vec![0u8; zstd_safe::compress_bound(chunk.len())]; let mut cctx = CCtx::create(); cctx.set_parameter(CParameter::CompressionLevel(ZSTD_LEVEL)) @@ -230,6 +254,157 @@ mod tests { assert!(written < chunk.len(), "zstd did save a little"); } + /// Chunks of text, random bytes and both, at which zstd writes past the length it returns. + fn residue_chunks() -> Vec> { + let mut chunks = Vec::new(); + for len in [100, 1_000, 5_000, 70_000, 300_000] { + chunks.push(text(len)); + chunks.push(pseudo_random(4, len)); + let mut mixed = pseudo_random(5, len / 2); + mixed.extend(b"abc".iter().copied().cycle().take(len - len / 2)); + chunks.push(mixed); + } + chunks + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn zstd_writes_past_the_frame_it_reports() { + const MARK: u8 = 0xA5; + let mut compressor = Compressor::new().expect("context"); + let mut most = 0; + for chunk in residue_chunks() { + let mut out = vec![MARK; zstd_safe::compress_bound(chunk.len())]; + let written = compressor + .cctx + .compress2(&mut out[..], &chunk) + .expect("compresses"); + let touched = out + .iter() + .rposition(|byte| *byte != MARK) + .map_or(0, |at| at + 1); + most = most.max(touched.saturating_sub(written)); + } + // More than a word: wiping the frame and a word after it would leave bytes behind. + assert!(most > 8, "zstd wrote at most {most} bytes past the frame"); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn nothing_zstd_wrote_survives_in_the_scratch_buffer() { + const MARK: u8 = 0xA5; + let mut compressor = Compressor::new().expect("context"); + for chunk in residue_chunks() { + compressor.scratch.as_mut_slice().fill(MARK); + compressor + .encode_chunk(&chunk, ObjectClass::Ordinary) + .expect("encodes"); + let bound = zstd_safe::compress_bound(chunk.len()); + let (given, beyond) = compressor.scratch.as_slice().split_at(bound); + assert!( + given.iter().all(|byte| *byte == 0), + "residue in the slice zstd was given, for {} bytes", + chunk.len() + ); + assert!( + beyond.iter().all(|byte| *byte == MARK), + "zstd wrote past its slice for {} bytes", + chunk.len() + ); + } + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn frames_are_single_segment_at_every_size() { + // libzstd shrinks the window to the content size, so it writes no window descriptor + // (FS-53): at every size near a power of two and at a stride up to 1 MiB. + let mut compressor = Compressor::new().expect("context"); + let mut lengths: Vec = (0..300).collect(); + lengths.extend((10..=20).flat_map(|log| [(1 << log) - 1, 1 << log, (1 << log) + 1])); + lengths.extend((1..64).map(|step| step * 16_411)); + lengths.retain(|len| *len <= MAX_CHUNK); + let random = pseudo_random(6, MAX_CHUNK); + for len in lengths { + for chunk in [text(len), random[..len].to_vec(), vec![0; len]] { + let mut frame = vec![0u8; zstd_safe::compress_bound(len)]; + let written = compressor + .cctx + .compress2(&mut frame[..], &chunk) + .expect("compresses"); + frame.truncate(written); + assert_eq!(frame[4] & 0x20, 0x20, "{len} bytes"); + assert_eq!( + frame_check::frame_check(&frame, len as u64), + Ok(()), + "{len} bytes" + ); + } + } + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn a_zstd_error_wipes_the_scratch_and_never_stores_raw() { + const MARK: u8 = 0xA5; + // ZSTD_error_GENERIC, as a negated size_t; injected after zstd has written its frame. + let code = 0usize.wrapping_sub(1); + let mut compressor = Compressor::new().expect("context"); + for (chunk, class) in [ + (text(100_000), ObjectClass::Ordinary), + (pseudo_random(7, 70_000), ObjectClass::Ordinary), + ] { + compressor.scratch.as_mut_slice().fill(MARK); + let guard = fault::inject(Fault::Compress(code)); + assert_eq!( + compressor.encode_chunk(&chunk, class).map(|_| ()), + Err(WriteError::Zstd(CompressError::from_code(code))), + "a failed frame is an error, not a raw chunk" + ); + assert!(fault::fired(), "the compressor called zstd"); + drop(guard); + let bound = zstd_safe::compress_bound(chunk.len()); + let (given, beyond) = compressor.scratch.as_slice().split_at(bound); + assert!( + given.iter().all(|byte| *byte == 0), + "zstd's output survives a failed call" + ); + assert!(beyond.iter().all(|byte| *byte == MARK)); + let again = compressor + .encode_chunk(&chunk, class) + .expect("the next call works"); + assert!(inner::decode_inner(&again).is_ok()); + } + // A secret chunk never reaches zstd, so the fault stays armed. + let _guard = fault::inject(Fault::Compress(code)); + compressor + .encode_chunk(&text(1_000), ObjectClass::Secret) + .expect("no zstd for the secret class"); + assert!(!fault::fired()); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn no_protected_memory_fails_with_memory() { + { + let _guard = fault::inject(Fault::Allocation(0)); + assert_eq!( + Compressor::new().map(|_| ()), + Err(WriteError::Memory(MemError::MapFailed)), + "the scratch buffer" + ); + } + let mut compressor = Compressor::new().expect("context"); + for class in [ObjectClass::Ordinary, ObjectClass::Secret] { + let _guard = fault::inject(Fault::Allocation(0)); + assert_eq!( + compressor.encode_chunk(&text(10_000), class).map(|_| ()), + Err(WriteError::Memory(MemError::MapFailed)), + "the inner plaintext" + ); + } + } + #[test] #[cfg_attr(miri, ignore = "calls into libzstd")] fn debug_prints_nothing() { diff --git a/crates/engine/core/src/compress/decompressor.rs b/crates/engine/core/src/compress/decompressor.rs index 716a458..13fbed9 100644 --- a/crates/engine/core/src/compress/decompressor.rs +++ b/crates/engine/core/src/compress/decompressor.rs @@ -7,7 +7,7 @@ use crypthix_types::format_error::FormatError; use zstd_safe::{DCtx, DParameter, InBuffer, OutBuffer, ResetDirective}; use crate::compress::CompressError; -use crate::compress::frame_check::frame_check; +use crate::compress::frame_check; use crate::error::ReadError; use crate::limits::{MAX_PLAIN_LEN, WINDOW_LOG}; @@ -33,8 +33,9 @@ impl Decompressor { /// 1. `plain_len` is at most 1 MiB, checked before anything else; /// 2. on first use, the linked libzstd is the version FS-53 pins and a context is made /// ([`ReadError::Zstd`] if not), before any other call into libzstd; - /// 3. the frame is exactly one frame with no checksum, no dictionary ID, a declared content - /// size equal to `plain_len` and a window of at most 1 MiB; + /// 3. the frame is exactly one single-segment frame, so its window is `plain_len`, with no + /// checksum, no dictionary ID, a declared content size equal to `plain_len` and no block + /// larger than `min(plain_len, 128 KiB)`; /// 4. a streaming decoder writes into a buffer of exactly `plain_len` bytes, and must fill /// it, finish the frame and use every input byte; output that does not fit, or a frame /// that ends early, fails. @@ -54,11 +55,15 @@ impl Decompressor { Some(dctx) => dctx, slot @ None => slot.insert(context(zstd_safe::version_number)?), }; - frame_check(frame, plain_len)?; + frame_check::frame_check(frame, plain_len)?; let len = usize::try_from(plain_len).map_err(|_| FormatError::Decompress)?; // A failed call leaves the context unusable until it is reset (zstd.h). - dctx.reset(ResetDirective::SessionOnly) - .map_err(|code| ReadError::Zstd(CompressError::from_code(code)))?; + let reset = dctx.reset(ResetDirective::SessionOnly); + #[cfg(test)] + let reset = crate::fault::reset(reset); + reset.map_err(|code| ReadError::Zstd(CompressError::from_code(code)))?; + #[cfg(test)] + crate::fault::allocation()?; let mut plain = SecretBuf::try_zeroed(len)?; let written = stream(dctx, frame, plain.as_mut_slice())?; // Defence in depth: zstd already fails a frame whose content differs from its declared @@ -132,12 +137,17 @@ impl fmt::Debug for Decompressor { #[cfg(test)] mod tests { + use crypthix_crypto::secure_mem::MemError; use proptest::collection::vec; - use proptest::prelude::{any, prop_assert_eq, proptest}; + use proptest::prelude::{Strategy, any, prop_assert_eq, prop_oneof, proptest}; + use proptest::sample::Index; use zstd_safe::{CCtx, CParameter}; use super::*; - use crate::compress::frame_check::tests::raw_frame; + use crate::blob::ObjectClass; + use crate::compress::Compressor; + use crate::fault::{self, Fault}; + use crate::inner::{self, Comp}; const FAIL: Result, ReadError> = Err(ReadError::Format(FormatError::Decompress)); @@ -205,7 +215,7 @@ mod tests { ); assert!(decompressor.dctx.is_some(), "made at the first frame"); let plain = decompressor - .decode(&raw_frame(b"hello", 5, 0, None), 5) + .decode(&frame_check::tests::raw_frame(b"hello", 5, 0), 5) .expect("decodes"); assert_eq!(plain.as_slice(), b"hello"); } @@ -217,10 +227,13 @@ mod tests { let frame = frame_of(&data, &[]); assert_eq!(decode(&frame, 300_000), Ok(data)); assert_eq!( - decode(&raw_frame(b"hello", 5, 0, None), 5), + decode(&frame_check::tests::raw_frame(b"hello", 5, 0), 5), Ok(b"hello".to_vec()) ); - assert_eq!(decode(&raw_frame(b"", 0, 0, None), 0), Ok(Vec::new())); + assert_eq!( + decode(&frame_check::tests::raw_frame(b"", 0, 0), 0), + Ok(Vec::new()) + ); } #[test] @@ -238,8 +251,14 @@ mod tests { #[test] #[cfg_attr(miri, ignore = "calls into libzstd")] fn content_longer_or_shorter_than_declared_fails() { - assert_eq!(decode(&raw_frame(b"hello!", 5, 0, None), 5), FAIL); - assert_eq!(decode(&raw_frame(b"hell", 5, 0, None), 5), FAIL); + assert_eq!( + decode(&frame_check::tests::raw_frame(b"hello!", 5, 0), 5), + FAIL + ); + assert_eq!( + decode(&frame_check::tests::raw_frame(b"hell", 5, 0), 5), + FAIL + ); } #[test] @@ -254,14 +273,14 @@ mod tests { #[cfg_attr(miri, ignore = "calls into libzstd")] fn frames_with_a_dictionary_id_fail() { // Well-formed frames of one raw block that name dictionary 7, then 0x01020304. - let mut frame = raw_frame(b"hello", 5, 1, None); + let mut frame = frame_check::tests::raw_frame(b"hello", 5, 1); frame.insert(5, 7); assert_eq!( zstd_safe::get_dict_id_from_frame(&frame).map(u32::from), Some(7) ); assert_eq!(decode(&frame, 5), FAIL); - let mut frame = raw_frame(b"hello", 5, 3, None); + let mut frame = frame_check::tests::raw_frame(b"hello", 5, 3); frame.splice(5..5, 0x0102_0304_u32.to_le_bytes()); assert_eq!( zstd_safe::get_dict_id_from_frame(&frame).map(u32::from), @@ -294,9 +313,62 @@ mod tests { #[test] #[cfg_attr(miri, ignore = "calls into libzstd")] - fn a_window_over_one_mib_fails() { - // A window descriptor of 2 MiB on content that is small enough. - assert_eq!(decode(&raw_frame(b"hello", 5, 0, Some(11 << 3)), 5), FAIL); + fn a_window_descriptor_fails() { + // Not a single segment: a four-byte content size, then a window descriptor of 1 MiB. + let mut frame = vec![0x28, 0xB5, 0x2F, 0xFD, 0x80, 10 << 3]; + frame.extend_from_slice(&5u32.to_le_bytes()); + frame.extend_from_slice(&[0x29, 0, 0]); + frame.extend_from_slice(b"hello"); + let mut out = [0u8; 5]; + assert_eq!(zstd_safe::decompress(&mut out[..], &frame), Ok(5)); + assert_eq!(decode(&frame, 5), FAIL); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn a_block_over_the_block_maximum_fails() { + // One RLE block of 2^20 zeros: libzstd decodes it when the whole frame arrives at once, + // as it does here, so the decoder alone would accept it. + let mut frame = vec![0x28, 0xB5, 0x2F, 0xFD, 0xA0]; + frame.extend_from_slice(&(1u32 << 20).to_le_bytes()); + frame.extend_from_slice(&((1u32 << 23) | 0b011).to_le_bytes()[..3]); + frame.push(0); + let mut decompressor = Decompressor::new(); + let mut out = vec![0u8; 1 << 20]; + assert_eq!(zstd_safe::decompress(&mut out[..], &frame), Ok(1 << 20)); + assert_eq!( + decompressor.decode(&frame, 1 << 20).map(|_| ()), + Err(ReadError::Format(FormatError::Decompress)) + ); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn a_failed_context_reset_is_a_zstd_error() { + // ZSTD_error_GENERIC, as a negated size_t. + let code = 0usize.wrapping_sub(1); + let frame = frame_check::tests::raw_frame(b"hello", 5, 0); + let mut decompressor = Decompressor::new(); + let guard = fault::inject(Fault::Reset(code)); + assert_eq!( + decompressor.decode(&frame, 5).map(|_| ()), + Err(ReadError::Zstd(CompressError::from_code(code))) + ); + assert!(fault::fired(), "the frame passed its checks first"); + drop(guard); + let plain = decompressor.decode(&frame, 5).expect("decodes"); + assert_eq!(plain.as_slice(), b"hello"); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn no_protected_memory_for_the_output_fails_with_memory() { + let frame = frame_check::tests::raw_frame(b"hello", 5, 0); + let _guard = fault::inject(Fault::Allocation(0)); + assert_eq!( + decode(&frame, 5), + Err(ReadError::Memory(MemError::MapFailed)) + ); } #[test] @@ -334,5 +406,169 @@ mod tests { fn arbitrary_bytes_never_panic(bytes in vec(any::(), 0..200), len in 0u64..300) { let _ = decode(&bytes, len); } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn a_changed_frame_is_refused_unless_libzstd_decodes_it_alike( + valid in valid_frame(), + mutation in mutation(), + ) { + let ValidFrame { frame, plain, kind } = valid; + let len = plain.len() as u64; + prop_assert_eq!(decode(&frame, len), Ok(plain.clone()), "the valid frame decodes"); + let header_len = header_len(&frame); + let mut changed = frame.clone(); + let mut plain_len = len; + // What the change must give: an exact plaintext, a refusal, or, for a byte changed + // in a block, either a refusal or what libzstd itself decodes. + let expected: Option, ReadError>> = match mutation { + Mutation::Header(at, xor) => { + changed[at.index(header_len)] ^= xor; + Some(FAIL) + } + Mutation::Descriptor(descriptor) => { + changed[4] = descriptor; + Some(if descriptor == frame[4] { Ok(plain.clone()) } else { FAIL }) + } + Mutation::PlainLen(up) => { + plain_len = if up || len == 0 { len + 1 } else { len - 1 }; + Some(FAIL) + } + Mutation::Truncate(at) => { + changed.truncate(at.index(frame.len())); + Some(FAIL) + } + Mutation::Append(extra) => { + changed.extend_from_slice(&extra); + Some(FAIL) + } + Mutation::Body(at, xor) => { + let at = header_len + at.index(frame.len() - header_len); + changed[at] ^= xor; + // The content of a raw or RLE block is copied out as it is. + let content = at.checked_sub(header_len + 3); + match (kind, content) { + (Kind::Raw, Some(offset)) => { + let mut expected = plain.clone(); + expected[offset] ^= xor; + Some(Ok(expected)) + } + (Kind::Rle(byte), Some(_)) => Some(Ok(vec![byte ^ xor; plain.len()])), + _ => None, + } + } + }; + let result = decode(&changed, plain_len); + match expected { + Some(expected) => prop_assert_eq!(result, expected), + None => match result { + Ok(out) => prop_assert_eq!( + Some(out), + libzstd_decodes(&changed, plain_len), + "accepted, so libzstd decodes it to the same plain_len bytes" + ), + Err(error) => prop_assert_eq!(Err(error), FAIL, "the only error a frame causes"), + }, + } + } + } + + /// What a valid frame holds. + #[derive(Clone, Copy, Debug)] + enum Kind { + /// Compressed blocks, as the compressor writes them. + Compressed, + /// One raw block. + Raw, + /// One RLE block of this byte. + Rle(u8), + } + + /// A frame the reader accepts and the plaintext it decodes to. + #[derive(Clone, Debug)] + struct ValidFrame { + frame: Vec, + plain: Vec, + kind: Kind, + } + + /// The compressor's frame of a compressible chunk, or a hand-built frame of one raw or RLE + /// block. + fn valid_frame() -> impl Strategy { + prop_oneof![ + vec(0u8..4, 0..4_000).prop_map(|plain| { + let inner = Compressor::new() + .expect("context") + .encode_chunk(&plain, ObjectClass::Ordinary) + .expect("encodes"); + let view = inner::decode_inner(&inner).expect("well formed"); + match view.comp() { + Comp::Zstd => ValidFrame { + frame: view.payload().to_vec(), + plain, + kind: Kind::Compressed, + }, + // Too short to compress: the same bytes in a raw block. + _ => raw(plain), + } + }), + vec(any::(), 0..600).prop_map(raw), + (any::(), 0u32..3_000).prop_map(|(byte, len)| ValidFrame { + frame: frame_check::tests::rle_frame(byte, len), + plain: vec![byte; usize::try_from(len).expect("small")], + kind: Kind::Rle(byte), + }), + ] + } + + fn raw(plain: Vec) -> ValidFrame { + let len = u32::try_from(plain.len()).expect("small"); + ValidFrame { + frame: frame_check::tests::raw_frame(&plain, len, 0), + plain, + kind: Kind::Raw, + } + } + + /// One change to a valid frame or to the `plain_len` it is decoded with. + #[derive(Clone, Debug)] + enum Mutation { + /// A byte of the frame header (magic, descriptor or content size) XOR-ed with a + /// non-zero value. + Header(Index, u8), + /// The descriptor set to any value, its own included. + Descriptor(u8), + /// A byte after the header, in a block header or block content, XOR-ed. + Body(Index, u8), + /// `plain_len` one higher, or one lower. + PlainLen(bool), + /// The frame cut to a shorter length. + Truncate(Index), + /// Bytes appended to the frame. + Append(Vec), + } + + fn mutation() -> impl Strategy { + prop_oneof![ + (any::(), 1u8..).prop_map(|(at, xor)| Mutation::Header(at, xor)), + any::().prop_map(Mutation::Descriptor), + (any::(), 1u8..).prop_map(|(at, xor)| Mutation::Body(at, xor)), + any::().prop_map(Mutation::PlainLen), + any::().prop_map(Mutation::Truncate), + vec(any::(), 1..16).prop_map(Mutation::Append), + ] + } + + /// The length of a single-segment frame header: magic, descriptor and content size field. + fn header_len(frame: &[u8]) -> usize { + 5 + [1, 2, 4, 8][usize::from(frame[4] >> 6)] + } + + /// The `plain_len` bytes libzstd's one-shot decoder makes of `frame`, if it makes exactly + /// that many. + fn libzstd_decodes(frame: &[u8], plain_len: u64) -> Option> { + let mut out = vec![0u8; usize::try_from(plain_len).ok()?]; + let written = zstd_safe::decompress(&mut out[..], frame).ok()?; + (written == out.len()).then_some(out) } } diff --git a/crates/engine/core/src/compress/frame_check.rs b/crates/engine/core/src/compress/frame_check.rs index df3eebc..2d48d8b 100644 --- a/crates/engine/core/src/compress/frame_check.rs +++ b/crates/engine/core/src/compress/frame_check.rs @@ -15,19 +15,35 @@ const CHECKSUM: u8 = 0x04; const DICT_ID: u8 = 0x03; const FCS_FLAG_SHIFT: u32 = 6; +/// The largest block, 128 KiB (RFC 8878 section 3.1.1.2.4). +const MAX_BLOCK: u64 = 128 * 1024; + +/// Block types (RFC 8878 section 3.1.1.2.2). +const RAW_BLOCK: u32 = 0; +const RLE_BLOCK: u32 = 1; +const COMPRESSED_BLOCK: u32 = 2; + /// Checks that `frame` is exactly one zstd frame as FS-53 writes it, declaring `plain_len` -/// bytes of content: the zstd magic (so no skippable frame), the unused and reserved bits -/// clear, no checksum, no dictionary ID, a content size equal to `plain_len` in the shortest -/// field that holds it, a window of at most 1 MiB, and no bytes after the frame. Every failure -/// is `Decompress`. +/// bytes of content: the zstd magic (so no skippable frame); the single-segment bit set, so +/// there is no window descriptor and the window is `plain_len`; the unused and reserved bits +/// clear; no checksum; no dictionary ID; a content size equal to `plain_len` in the shortest +/// field that holds it; blocks of a defined type, each no larger than `min(plain_len, 128 KiB)`, +/// the size it regenerates counting for an RLE block; and no bytes after the last block. Every +/// failure is `Decompress`. /// /// zstd checks the content against the declared size while decoding; these checks make sure /// the declaration exists and matches before a byte is decoded. libzstd 1.5.7 ignores the -/// unused bit and reads a content size from a wider field than needed (RFC 8878 allows both -/// to a decoder); its encoder never writes either, so a frame with them is not one FS-53 -/// writes and is refused here. +/// unused bit, reads a content size from a wider field than needed and accepts a window +/// descriptor (RFC 8878 allows all three to a decoder); its encoder never writes them for a +/// chunk of at most 1 MiB, so a frame with them is a second encoding of a chunk and is refused +/// here. libzstd 1.5.7 checks the block maximum only on its block-by-block path, not when it +/// decodes a whole frame in one pass, as `ZSTD_decompressStream` does when given the whole frame +/// and room for its content, so the block headers are walked here. pub(crate) fn frame_check(frame: &[u8], plain_len: u64) -> Result<(), FormatError> { let fail = FormatError::Decompress; + if plain_len > MAX_PLAIN_LEN { + return Err(fail); + } let Some((magic, rest)) = frame.split_first_chunk::<4>() else { return Err(fail); }; @@ -37,84 +53,114 @@ pub(crate) fn frame_check(frame: &[u8], plain_len: u64) -> Result<(), FormatErro let Some((&descriptor, rest)) = rest.split_first() else { return Err(fail); }; - if descriptor & (UNUSED | RESERVED | CHECKSUM | DICT_ID) != 0 { + if descriptor & (SINGLE_SEGMENT | UNUSED | RESERVED | CHECKSUM | DICT_ID) != SINGLE_SEGMENT { return Err(fail); } - let single_segment = descriptor & SINGLE_SEGMENT != 0; - if descriptor >> FCS_FLAG_SHIFT == 0 && !single_segment { - // No content size at all. + let flag = descriptor >> FCS_FLAG_SHIFT; + if flag != fcs_flag(plain_len) { return Err(fail); } - if descriptor >> FCS_FLAG_SHIFT != fcs_flag(plain_len, single_segment) { + let (declared, blocks) = content_size(flag, rest).ok_or(fail)?; + if declared != plain_len { return Err(fail); } - if !single_segment { - let window = rest.first().map(|&byte| window_size(byte)).ok_or(fail)?; - if window > MAX_PLAIN_LEN { - return Err(fail); - } - } - match zstd_safe::get_frame_content_size(frame) { - Ok(Some(size)) if size == plain_len => {} - _ => return Err(fail), - } - match zstd_safe::find_frame_compressed_size(frame) { - Ok(size) if size == frame.len() => Ok(()), + // A single segment's window is its content size. + let block_max = plain_len.min(MAX_BLOCK); + match after_blocks(blocks, block_max) { + Some([]) => Ok(()), _ => Err(fail), } } -/// The frame content size flag of the shortest field that holds `size` (RFC 8878 section -/// 3.1.1.1.1), as libzstd's encoder chooses it: one byte only in a single-segment frame, two -/// bytes with an offset of 256, four, then eight from `0xFFFF_FFFF` on. -fn fcs_flag(size: u64, single_segment: bool) -> u8 { +/// The frame content size flag of the shortest field that holds `size` in a single-segment +/// frame (RFC 8878 section 3.1.1.1.1), as libzstd's encoder chooses it: one byte, two bytes +/// with an offset of 256, four, then eight from `0xFFFF_FFFF` on. +fn fcs_flag(size: u64) -> u8 { match size { - 0..256 if single_segment => 0, + 0..256 => 0, 256..65_792 => 1, - 0..0xFFFF_FFFF => 2, + 65_792..0xFFFF_FFFF => 2, _ => 3, } } -/// The window size a window descriptor byte declares (RFC 8878 section 3.1.1.1.2). -fn window_size(descriptor: u8) -> u64 { - let window_log = 10 + u32::from(descriptor >> 3); - let base = 1u64 << window_log; - base + (base / 8) * u64::from(descriptor & 0x07) +/// The content size in the field that `flag` names at the start of `rest`, in a single-segment +/// frame, and the bytes after it; `None` if the field is cut off. +fn content_size(flag: u8, rest: &[u8]) -> Option<(u64, &[u8])> { + match flag { + 0 => { + let (&size, rest) = rest.split_first()?; + Some((u64::from(size), rest)) + } + 1 => { + let (size, rest) = rest.split_first_chunk::<2>()?; + Some((u64::from(u16::from_le_bytes(*size)) + 256, rest)) + } + 2 => { + let (size, rest) = rest.split_first_chunk::<4>()?; + Some((u64::from(u32::from_le_bytes(*size)), rest)) + } + _ => { + let (size, rest) = rest.split_first_chunk::<8>()?; + Some((u64::from_le_bytes(*size), rest)) + } + } +} + +/// Walks the blocks at the start of `blocks` (RFC 8878 section 3.1.1.2) and returns the bytes +/// after the last one; `None` if a block is cut off, has the reserved type, or is larger than +/// `block_max`, the regenerated size counting for an RLE block. +fn after_blocks(mut blocks: &[u8], block_max: u64) -> Option<&[u8]> { + loop { + let (&[low, middle, high], rest) = blocks.split_first_chunk::<3>()?; + let header = u32::from_le_bytes([low, middle, high, 0]); + let last = header & 1 == 1; + let size = header >> 3; + if u64::from(size) > block_max { + return None; + } + let content_len = match (header >> 1) & 3 { + RAW_BLOCK | COMPRESSED_BLOCK => usize::try_from(size).ok()?, + RLE_BLOCK => 1, + _ => return None, + }; + blocks = rest.get(content_len..)?; + if last { + return Some(blocks); + } + } } #[cfg(test)] pub(crate) mod tests { use super::*; - /// A frame of one raw block holding `content`, declaring `declared` bytes in the shortest - /// field, with the given descriptor bits and, if `window` is `Some`, that window descriptor - /// instead of a single segment. - pub(crate) fn raw_frame( - content: &[u8], - declared: u32, - extra: u8, - window: Option, - ) -> Vec { - let flag = fcs_flag(u64::from(declared), window.is_none()); - sized_frame(content, declared, flag, extra, window) + /// A block header: `last`, `kind` and `size` (RFC 8878 section 3.1.1.2). + fn block_header(last: bool, kind: u32, size: u32) -> [u8; 3] { + let header = u32::from(last) | kind << 1 | size << 3; + let [low, middle, high, _] = header.to_le_bytes(); + [low, middle, high] + } + + /// A single-segment frame of one raw block holding `content`, declaring `declared` bytes in + /// the shortest field, with the given descriptor bits added. + pub(crate) fn raw_frame(content: &[u8], declared: u32, extra: u8) -> Vec { + sized_frame(content, declared, fcs_flag(u64::from(declared)), extra) } /// [`raw_frame`] with the content size in the field that `flag` names. - fn sized_frame( - content: &[u8], - declared: u32, - flag: u8, - extra: u8, - window: Option, - ) -> Vec { + fn sized_frame(content: &[u8], declared: u32, flag: u8, extra: u8) -> Vec { + let mut frame = header_of(declared, flag, extra); + let size = u32::try_from(content.len()).expect("small"); + frame.extend_from_slice(&block_header(true, RAW_BLOCK, size)); + frame.extend_from_slice(content); + frame + } + + /// The magic, the descriptor and the content size field of a single-segment frame. + fn header_of(declared: u32, flag: u8, extra: u8) -> Vec { let mut frame = ZSTD_MAGIC.to_vec(); - let mut descriptor = (flag << FCS_FLAG_SHIFT) | extra; - if window.is_none() { - descriptor |= SINGLE_SEGMENT; - } - frame.push(descriptor); - frame.extend(window); + frame.push((flag << FCS_FLAG_SHIFT) | SINGLE_SEGMENT | extra); let field = match flag { 0 => vec![u8::try_from(declared).expect("below 256")], 1 => u16::try_from(declared - 256) @@ -125,9 +171,23 @@ pub(crate) mod tests { _ => u64::from(declared).to_le_bytes().to_vec(), }; frame.extend_from_slice(&field); - let block = u32::try_from(content.len()).expect("small") << 3 | 1; - frame.extend_from_slice(&block.to_le_bytes()[..3]); - frame.extend_from_slice(content); + frame + } + + /// A single-segment frame of one RLE block of `len` copies of `byte`. + pub(crate) fn rle_frame(byte: u8, len: u32) -> Vec { + blocks_frame(len, &[(RLE_BLOCK, len, &[byte])]) + } + + /// A single-segment frame declaring `declared` bytes with the given blocks, each a type, a + /// `Block_Size` and its content; the last is marked as such. + fn blocks_frame(declared: u32, blocks: &[(u32, u32, &[u8])]) -> Vec { + let mut frame = header_of(declared, fcs_flag(u64::from(declared)), 0); + for (index, (kind, size, content)) in blocks.iter().enumerate() { + let last = index + 1 == blocks.len(); + frame.extend_from_slice(&block_header(last, *kind, *size)); + frame.extend_from_slice(content); + } frame } @@ -137,18 +197,14 @@ pub(crate) mod tests { const FAIL: Result<(), FormatError> = Err(FormatError::Decompress); - #[test] - fn window_descriptors_decode_as_rfc_8878_says() { - assert_eq!(window_size(0), 1 << 10); - assert_eq!(window_size(10 << 3), 1 << 20); - assert_eq!(window_size(10 << 3 | 1), (1 << 20) + (1 << 17)); - assert_eq!(window_size(9 << 3 | 7), (1 << 19) + 7 * (1 << 16)); - assert_eq!(window_size(11 << 3), 1 << 21); - assert_eq!(window_size(u8::MAX), (1 << 41) + 7 * (1 << 38)); + /// What libzstd's one-shot decoder makes of `frame` into `capacity` bytes. + fn zstd_decodes(frame: &[u8], capacity: usize) -> Result { + let mut out = vec![0u8; capacity]; + zstd_safe::decompress(&mut out[..], frame) } #[test] - fn short_and_foreign_input_fails_before_calling_zstd() { + fn short_and_foreign_input_fails() { for frame in [ &b""[..], b"\x28\xB5\x2F", @@ -157,25 +213,37 @@ pub(crate) mod tests { ] { assert_eq!(check(frame, 0), FAIL, "{frame:?}"); } - let mut skippable = raw_frame(b"x", 1, 0, None); + let mut skippable = raw_frame(b"x", 1, 0); skippable[..4].copy_from_slice(&0x184D_2A50_u32.to_le_bytes()); assert_eq!(check(&skippable, 1), FAIL); for bit in [UNUSED, RESERVED, CHECKSUM, 1, 2, 3] { - assert_eq!(check(&raw_frame(b"x", 1, bit, None), 1), FAIL, "{bit}"); + assert_eq!(check(&raw_frame(b"x", 1, bit), 1), FAIL, "{bit}"); } } #[test] - #[cfg_attr(miri, ignore = "calls into libzstd")] - fn a_raw_frame_passes() { - assert_eq!(check(&raw_frame(b"hello", 5, 0, None), 5), Ok(())); - assert_eq!(check(&raw_frame(b"", 0, 0, None), 0), Ok(())); + fn a_frame_cut_inside_its_header_fails() { + let frame = raw_frame(&[b'a'; 300], 300, 0); + assert_eq!(check(&frame, 300), Ok(())); + // Magic and descriptor only; one of the two content size bytes; a cut block header. + for len in [5, 6, 7, 8, 9] { + assert_eq!(check(&frame[..len], 300), FAIL, "{len} bytes"); + } + } + + #[test] + fn raw_and_rle_frames_pass() { + assert_eq!(check(&raw_frame(b"hello", 5, 0), 5), Ok(())); + assert_eq!(check(&raw_frame(b"", 0, 0), 0), Ok(())); + let mixed = blocks_frame(8, &[(RLE_BLOCK, 3, b"a"), (RAW_BLOCK, 5, b"hello")]); + assert_eq!(check(&mixed, 8), Ok(())); + let empty_rle = blocks_frame(0, &[(RLE_BLOCK, 0, b"a")]); + assert_eq!(check(&empty_rle, 0), Ok(())); } #[test] - #[cfg_attr(miri, ignore = "calls into libzstd")] fn the_content_size_must_be_declared_and_equal() { - let frame = raw_frame(b"hello", 5, 0, None); + let frame = raw_frame(b"hello", 5, 0); assert_eq!(check(&frame, 4), FAIL); assert_eq!(check(&frame, 6), FAIL); // No content size: descriptor 0 and a window descriptor. @@ -183,12 +251,12 @@ pub(crate) mod tests { no_size.extend_from_slice(&[0x00, 0x00, 0x29, 0, 0]); no_size.extend_from_slice(b"hello"); assert_eq!(check(&no_size, 5), FAIL); + assert_eq!(check(&frame, MAX_PLAIN_LEN + 1), FAIL); } #[test] - #[cfg_attr(miri, ignore = "calls into libzstd")] fn exactly_one_frame_and_nothing_after_it() { - let frame = raw_frame(b"hello", 5, 0, None); + let frame = raw_frame(b"hello", 5, 0); let mut two = frame.clone(); two.extend_from_slice(&frame); assert_eq!(check(&two, 5), FAIL); @@ -200,18 +268,23 @@ pub(crate) mod tests { skippable_after.extend_from_slice(&0u32.to_le_bytes()); assert_eq!(check(&skippable_after, 5), FAIL); assert_eq!(check(&frame[..frame.len() - 1], 5), FAIL, "truncated"); + let not_last = blocks_frame(5, &[(RAW_BLOCK, 5, b"hello"), (RAW_BLOCK, 0, b"")]); + assert_eq!( + check(¬_last[..not_last.len() - 3], 5), + FAIL, + "no last block" + ); } #[test] fn content_size_flags_are_the_shortest_field() { - assert_eq!(fcs_flag(0, true), 0); - assert_eq!(fcs_flag(255, true), 0); - assert_eq!(fcs_flag(255, false), 2, "one byte only in a single segment"); - assert_eq!(fcs_flag(256, true), 1); - assert_eq!(fcs_flag(65_791, false), 1); - assert_eq!(fcs_flag(65_792, true), 2); - assert_eq!(fcs_flag(0xFFFF_FFFE, true), 2); - assert_eq!(fcs_flag(0xFFFF_FFFF, true), 3); + assert_eq!(fcs_flag(0), 0); + assert_eq!(fcs_flag(255), 0); + assert_eq!(fcs_flag(256), 1); + assert_eq!(fcs_flag(65_791), 1); + assert_eq!(fcs_flag(65_792), 2); + assert_eq!(fcs_flag(0xFFFF_FFFE), 2); + assert_eq!(fcs_flag(0xFFFF_FFFF), 3); } #[test] @@ -219,35 +292,82 @@ pub(crate) mod tests { fn a_content_size_field_wider_than_needed_fails() { // Each of these decodes with libzstd 1.5.7. for flag in [2, 3] { - let frame = sized_frame(b"hello", 5, flag, 0, None); - let mut out = [0u8; 5]; - assert_eq!(zstd_safe::decompress(&mut out[..], &frame), Ok(5), "{flag}"); + let frame = sized_frame(b"hello", 5, flag, 0); + assert_eq!(zstd_decodes(&frame, 5), Ok(5), "{flag}"); assert_eq!(check(&frame, 5), FAIL, "{flag}"); } let long = vec![b'a'; 300]; - assert_eq!(check(&sized_frame(&long, 300, 1, 0, None), 300), Ok(())); - assert_eq!(check(&sized_frame(&long, 300, 2, 0, None), 300), FAIL); - let windowed = sized_frame(b"hello", 5, 3, 0, Some(10 << 3)); - assert_eq!(check(&windowed, 5), FAIL); + assert_eq!(check(&sized_frame(&long, 300, 1, 0), 300), Ok(())); + assert_eq!(check(&sized_frame(&long, 300, 2, 0), 300), FAIL); } #[test] #[cfg_attr(miri, ignore = "calls into libzstd")] fn the_unused_bit_fails_although_libzstd_ignores_it() { - let frame = raw_frame(b"hello", 5, UNUSED, None); - let mut out = [0u8; 5]; - assert_eq!(zstd_safe::decompress(&mut out[..], &frame), Ok(5)); + let frame = raw_frame(b"hello", 5, UNUSED); + assert_eq!(zstd_decodes(&frame, 5), Ok(5)); + assert_eq!(check(&frame, 5), FAIL); + } + + #[test] + #[cfg_attr(miri, ignore = "calls into libzstd")] + fn a_window_descriptor_fails_although_libzstd_decodes_it() { + // Descriptor 0xC0: an eight-byte content size and no single segment, then a window of + // 2^20 bytes, the most FS-53 allows a writer. + let mut frame = ZSTD_MAGIC.to_vec(); + frame.extend_from_slice(&[0xC0, 10 << 3]); + frame.extend_from_slice(&5u64.to_le_bytes()); + frame.extend_from_slice(&block_header(true, RAW_BLOCK, 5)); + frame.extend_from_slice(b"hello"); + assert_eq!(zstd_decodes(&frame, 5), Ok(5)); assert_eq!(check(&frame, 5), FAIL); + // The shortest field for 5 bytes without a single segment is four bytes wide. + let mut four = ZSTD_MAGIC.to_vec(); + four.extend_from_slice(&[0x80, 10 << 3]); + four.extend_from_slice(&5u32.to_le_bytes()); + four.extend_from_slice(&block_header(true, RAW_BLOCK, 5)); + four.extend_from_slice(b"hello"); + assert_eq!(zstd_decodes(&four, 5), Ok(5)); + assert_eq!(check(&four, 5), FAIL); } #[test] #[cfg_attr(miri, ignore = "calls into libzstd")] - fn the_window_is_at_most_one_mib() { - let at_cap = raw_frame(b"hello", 5, 0, Some(10 << 3)); - assert_eq!(check(&at_cap, 5), Ok(())); - let over = raw_frame(b"hello", 5, 0, Some(10 << 3 | 1)); - assert_eq!(check(&over, 5), FAIL); - let double = raw_frame(b"hello", 5, 0, Some(11 << 3)); - assert_eq!(check(&double, 5), FAIL); + fn a_block_over_the_block_maximum_fails_although_libzstd_decodes_it() { + let mib = 1u32 << 20; + let one_rle = blocks_frame(mib, &[(RLE_BLOCK, mib, &[0])]); + assert_eq!(zstd_decodes(&one_rle, 1 << 20), Ok(1 << 20)); + assert_eq!(check(&one_rle, 1 << 20), FAIL); + let max = u32::try_from(MAX_BLOCK).expect("small"); + let rle_over = blocks_frame(max + 1, &[(RLE_BLOCK, max + 1, &[0])]); + assert_eq!(check(&rle_over, MAX_BLOCK + 1), FAIL); + let content = vec![7u8; 128 * 1024 + 1]; + let raw_over = raw_frame(&content, max + 1, 0); + assert_eq!(zstd_decodes(&raw_over, content.len()), Ok(content.len())); + assert_eq!(check(&raw_over, MAX_BLOCK + 1), FAIL); + let raw_at = raw_frame(&content[1..], max, 0); + assert_eq!(check(&raw_at, MAX_BLOCK), Ok(())); + let two = blocks_frame( + max + 1, + &[(RAW_BLOCK, max, &content[1..]), (RLE_BLOCK, 1, &[7])], + ); + assert_eq!(check(&two, MAX_BLOCK + 1), Ok(())); + } + + #[test] + fn a_block_over_the_window_fails() { + // The window of a single segment is its content size. + let rle = blocks_frame(5, &[(RLE_BLOCK, 6, b"a")]); + assert_eq!(check(&rle, 5), FAIL); + let compressed = blocks_frame(5, &[(COMPRESSED_BLOCK, 6, b"abcdef")]); + assert_eq!(check(&compressed, 5), FAIL); + let at_window = blocks_frame(5, &[(RLE_BLOCK, 5, b"a")]); + assert_eq!(check(&at_window, 5), Ok(())); + } + + #[test] + fn a_block_of_the_reserved_type_fails() { + let reserved = blocks_frame(5, &[(3, 5, b"hello")]); + assert_eq!(check(&reserved, 5), FAIL); } } diff --git a/crates/engine/core/src/error/read_error.rs b/crates/engine/core/src/error/read_error.rs index 9bf25f1..976a11b 100644 --- a/crates/engine/core/src/error/read_error.rs +++ b/crates/engine/core/src/error/read_error.rs @@ -14,10 +14,11 @@ use crate::compress::CompressError; /// plaintext, zstd itself failed, or a key could not be derived. /// /// A blob that is not what its reference says is always [`ReadError::Format`], with the first -/// failing check of FS-93: `Decompress`, `Decrypt`, `Padding`, `Limit` or `Binding`. A frame -/// that does not decode is such a check, `FormatError::Decompress`; [`ReadError::Zstd`] is zstd -/// failing for a reason of its own. The kinds other than `Format` depend only on the reader's -/// own resources, so they never look like tampering. +/// failing check of FS-93: `Decompress`, `Decrypt`, `Truncated` (too short to be a seal), +/// `ZeroValue` (an all-zero nonce), `Padding`, `Limit` or `Binding`. A frame that does not +/// decode is such a check, `FormatError::Decompress`; [`ReadError::Zstd`] is zstd failing for a +/// reason of its own. The kinds other than `Format` depend only on the reader's own resources, +/// so they never look like tampering. /// /// The failure of a [`KeyError`], as from [`ChunkKeys::derive`](crate::blob::ChunkKeys::derive), /// converts with `?`: its `Format` and `Memory` kinds to the same kinds here, anything else to diff --git a/crates/engine/core/src/error/write_error.rs b/crates/engine/core/src/error/write_error.rs index d289f1a..bd5d8f4 100644 --- a/crates/engine/core/src/error/write_error.rs +++ b/crates/engine/core/src/error/write_error.rs @@ -39,6 +39,12 @@ pub enum WriteError { Format(FormatError), /// A key could not be derived for a reason none of `Random`, `Memory` and `Format` names. Key(KeyError), + /// An [`ObjectSealer`](crate::blob::ObjectSealer) was given a chunk that is not the next + /// chunk of an object of its shape, a chunk identified by another sealer, or a chunk with a + /// random blob ID to reuse; or it was finished before the object's last chunk. Nothing was + /// sealed and the sealer did not move on. Any blob it sealed before a failed `finish` must + /// not be stored. + Sequence, } impl fmt::Display for WriteError { @@ -50,6 +56,7 @@ impl fmt::Display for WriteError { WriteError::Zstd(_) => "zstd failed", WriteError::Format(_) => "the input breaks a format rule", WriteError::Key(_) => "a key could not be derived", + WriteError::Sequence => "the chunks sealed are not those of the object, in order", }) } } @@ -63,6 +70,7 @@ impl Error for WriteError { WriteError::Zstd(error) => Some(error), WriteError::Format(error) => Some(error), WriteError::Key(error) => Some(error), + WriteError::Sequence => None, } } } @@ -129,9 +137,11 @@ mod tests { assert_eq!(source.to_string(), cause.to_string()); messages.push(error.to_string()); } + assert_eq!(WriteError::Sequence.source().map(ToString::to_string), None); + messages.push(WriteError::Sequence.to_string()); messages.sort(); messages.dedup(); - assert_eq!(messages.len(), 6, "two kinds share a message"); + assert_eq!(messages.len(), 7, "two kinds share a message"); } #[test] diff --git a/crates/engine/core/src/fault.rs b/crates/engine/core/src/fault.rs new file mode 100644 index 0000000..46c265f --- /dev/null +++ b/crates/engine/core/src/fault.rs @@ -0,0 +1,127 @@ +//! Faults the unit tests inject where nothing else makes a dependency fail: protected memory +//! that cannot be allocated, and zstd calls that return an error. +//! +//! The module exists only under `cfg(test)`. Each call site that can fail this way checks it +//! in a `#[cfg(test)]` statement, so a build outside the unit tests has neither the check nor +//! this state. A fault is per thread, is consumed when it fires, and is cleared when the guard +//! [`inject`] returns is dropped, so it never reaches another test. +//! +//! Only the allocations `crypthix-core` makes itself are counted: the inner plaintext, the +//! compressor's scratch buffer, the decompressor's output, a raw chunk's opened copy, the +//! gear table and the stream window. Those inside `crypthix-crypto` (the CX-AEAD open buffer, +//! derived keys) have no seam here; that crate's own tests cover them. + +use std::cell::Cell; + +use crypthix_crypto::secure_mem::MemError; + +/// A fault to inject. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Fault { + /// After this many more allocations of protected memory succeed, the next fails with + /// [`MemError::MapFailed`]. + Allocation(usize), + /// The next `ZSTD_compress2` returns this error code, after it has written its output. + Compress(usize), + /// The next `ZSTD_DCtx_reset` returns this error code. + Reset(usize), +} + +thread_local! { + static FAULT: Cell> = const { Cell::new(None) }; +} + +/// Clears the injected fault when dropped. +#[must_use = "the fault is cleared when the guard is dropped"] +pub(crate) struct Injected(()); + +impl Drop for Injected { + fn drop(&mut self) { + FAULT.with(|fault| fault.set(None)); + } +} + +/// Injects `fault` on this thread until it fires or the guard is dropped. +pub(crate) fn inject(fault: Fault) -> Injected { + FAULT.with(|slot| slot.set(Some(fault))); + Injected(()) +} + +/// Whether the fault has fired. +pub(crate) fn fired() -> bool { + FAULT.with(|fault| fault.get().is_none()) +} + +/// Called before each allocation of protected memory: fails it if an injected +/// [`Fault::Allocation`] has counted down to it. +pub(crate) fn allocation() -> Result<(), MemError> { + FAULT.with(|fault| match fault.get() { + Some(Fault::Allocation(0)) => { + fault.set(None); + Err(MemError::MapFailed) + } + Some(Fault::Allocation(left)) => { + fault.set(Some(Fault::Allocation(left - 1))); + Ok(()) + } + _ => Ok(()), + }) +} + +/// The result of `ZSTD_compress2`, or the injected [`Fault::Compress`] error in its place. +pub(crate) fn compress(result: Result) -> Result { + FAULT.with(|fault| match fault.get() { + Some(Fault::Compress(code)) => { + fault.set(None); + Err(code) + } + _ => result, + }) +} + +/// The result of `ZSTD_DCtx_reset`, or the injected [`Fault::Reset`] error in its place. +pub(crate) fn reset(result: Result) -> Result { + FAULT.with(|fault| match fault.get() { + Some(Fault::Reset(code)) => { + fault.set(None); + Err(code) + } + _ => result, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_allocation_fault_counts_down_then_fires_once() { + let guard = inject(Fault::Allocation(2)); + assert_eq!(allocation(), Ok(())); + assert_eq!(allocation(), Ok(())); + assert!(!fired()); + assert_eq!(allocation(), Err(MemError::MapFailed)); + assert!(fired()); + assert_eq!(allocation(), Ok(()), "a fault fires once"); + drop(guard); + } + + #[test] + fn zstd_faults_replace_only_their_own_call() { + let _guard = inject(Fault::Compress(7)); + assert_eq!(reset(Ok(0)), Ok(0), "a compress fault leaves reset alone"); + assert_eq!(allocation(), Ok(())); + assert_eq!(compress(Ok(5)), Err(7)); + assert_eq!(compress(Ok(5)), Ok(5)); + let _guard = inject(Fault::Reset(9)); + assert_eq!(compress(Ok(5)), Ok(5)); + assert_eq!(reset(Ok(0)), Err(9)); + assert_eq!(reset(Ok(0)), Ok(0)); + } + + #[test] + fn dropping_the_guard_clears_the_fault() { + drop(inject(Fault::Allocation(0))); + assert_eq!(allocation(), Ok(())); + } +} diff --git a/crates/engine/core/src/inner/decode_inner.rs b/crates/engine/core/src/inner/decode_inner.rs index 891b852..a2be6db 100644 --- a/crates/engine/core/src/inner/decode_inner.rs +++ b/crates/engine/core/src/inner/decode_inner.rs @@ -4,7 +4,7 @@ use crypthix_types::format_error::FormatError; use crate::inner::{Comp, InnerView}; use crate::limits::{INNER_HEADER_LEN, MAX_PAYLOAD_LEN}; -use crate::pad::padme; +use crate::pad; /// Checks an opened inner plaintext and returns its compression and payload (FS-54). /// @@ -33,7 +33,7 @@ pub fn decode_inner(inner: &[u8]) -> Result, FormatError> { return Err(FormatError::Limit); } // At most 6 + 2^20, so the sum and its Padmé length always fit. - let expected = padme(payload_len + INNER_HEADER_LEN as u64); + let expected = pad::padme(payload_len + INNER_HEADER_LEN as u64); if expected != Some(inner.len() as u64) { return Err(FormatError::Padding); } @@ -50,14 +50,18 @@ pub fn decode_inner(inner: &[u8]) -> Result, FormatError> { #[cfg(test)] mod tests { use proptest::collection::vec; - use proptest::prelude::{any, prop_assert_eq, proptest}; + use proptest::prelude::{ + Strategy, TestCaseError, any, prop_assert, prop_assert_eq, prop_oneof, proptest, + }; + use proptest::sample::Index; use super::*; - use crate::inner::encode_inner; + use crate::inner; + use crate::test_data::{any_byte, bytes}; /// A well-formed inner plaintext of `payload_len` bytes of 0x55, as plain bytes. fn inner(comp: u8, payload_len: usize) -> Vec { - let total = padme(payload_len as u64 + 6).expect("fits"); + let total = pad::padme(payload_len as u64 + 6).expect("fits"); let mut bytes = vec![0u8; usize::try_from(total).expect("fits")]; bytes[0] = comp; let len = u32::try_from(payload_len).expect("fits"); @@ -149,25 +153,156 @@ mod tests { } } + /// One change to a valid inner plaintext. + #[derive(Clone, Debug)] + enum Mutation { + /// A byte anywhere XOR-ed with a non-zero value. + Flip(Index, u8), + /// One byte more (a zero) or one fewer. + Resize(bool), + /// The `comp` byte set to any value, its own included. + Comp(u8), + /// The `rsv` byte set to any value, zero included. + Rsv(u8), + /// `payload_len` moved by this much, wrapping, with the bytes left as they are. + PayloadLen(i32), + /// `payload_len` set to any value. + AnyPayloadLen(u32), + /// The bytes cut to a shorter length. + Truncate(Index), + /// Bytes appended. + Append(Vec), + } + + fn mutation() -> impl Strategy { + prop_oneof![ + (any::(), 1u8..).prop_map(|(at, xor)| Mutation::Flip(at, xor)), + any::().prop_map(Mutation::Resize), + any::().prop_map(Mutation::Comp), + any::().prop_map(Mutation::Rsv), + prop_oneof![-2i32..=2, -8_192i32..8_192].prop_map(Mutation::PayloadLen), + any::().prop_map(Mutation::AnyPayloadLen), + any::().prop_map(Mutation::Truncate), + vec(any::(), 1..16).prop_map(Mutation::Append), + ] + } + + fn apply(bytes: &mut Vec, mutation: &Mutation) { + match mutation { + Mutation::Flip(at, xor) => { + let at = at.index(bytes.len()); + bytes[at] ^= xor; + } + Mutation::Resize(true) => bytes.push(0), + Mutation::Resize(false) => { + bytes.pop(); + } + Mutation::Comp(comp) => bytes[0] = *comp, + Mutation::Rsv(rsv) => bytes[1] = *rsv, + Mutation::PayloadLen(delta) => { + let len = u32::from_be_bytes(bytes[2..6].try_into().expect("four bytes")); + bytes[2..6].copy_from_slice(&len.wrapping_add_signed(*delta).to_be_bytes()); + } + Mutation::AnyPayloadLen(len) => bytes[2..6].copy_from_slice(&len.to_be_bytes()), + Mutation::Truncate(at) => { + let len = at.index(bytes.len()); + bytes.truncate(len); + } + Mutation::Append(extra) => bytes.extend_from_slice(extra), + } + } + + /// The one inner plaintext `bytes` could be: the encoding of the `comp` and payload its + /// header names, if those are valid; `None` if no encoding starts like `bytes`. + fn candidate(bytes: &[u8]) -> Option<(Comp, Vec, Vec)> { + let header = bytes.get(..6)?; + let comp = match header[0] { + 0 => Comp::Raw, + 1 => Comp::Zstd, + _ => return None, + }; + let len = usize::try_from(u32::from_be_bytes(header[2..6].try_into().ok()?)).ok()?; + let payload = bytes.get(6..6_usize.checked_add(len)?)?; + let encoded = inner::encode_inner(comp, payload).ok()?; + Some((comp, payload.to_vec(), encoded.to_vec())) + } + + /// Checks `decode_inner` against [`candidate`]: it accepts exactly the bytes that are the + /// encoding of what they decode to, and fails otherwise with `Limit` when a valid `comp` + /// and `rsv` precede a `payload_len` over 1 MiB, else with `Padding`. + fn check_canonical(bytes: &[u8]) -> Result<(), TestCaseError> { + let canonical = candidate(bytes).filter(|(_, _, encoded)| encoded == bytes); + match (decode_inner(bytes), canonical) { + (Ok(view), Some((comp, payload, _))) => { + prop_assert_eq!(view.comp(), comp); + prop_assert_eq!(view.payload(), payload.as_slice()); + } + (Ok(_), None) => prop_assert!(false, "accepted bytes that are not an encoding"), + (Err(error), Some(_)) => prop_assert!(false, "refused an encoding: {:?}", error), + (Err(error), None) => { + let over_cap = bytes.len() >= 6 + && bytes[0] <= 1 + && bytes[1] == 0 + && u32::from_be_bytes(bytes[2..6].try_into().expect("four bytes")) > 1 << 20; + let expected = if over_cap { + FormatError::Limit + } else { + FormatError::Padding + }; + prop_assert_eq!(error, expected); + } + } + Ok(()) + } + proptest! { #[test] - #[cfg_attr(miri, ignore = "proptest is slow under Miri")] - fn encode_then_decode_round_trips(payload in vec(any::(), 0..5_000), zstd in any::()) { + fn encode_then_decode_round_trips(payload in bytes(0..5_000, any_byte), zstd in any::()) { let comp = if zstd { Comp::Zstd } else { Comp::Raw }; - let encoded = encode_inner(comp, &payload).expect("encodes"); - prop_assert_eq!(encoded.len() as u64, padme(payload.len() as u64 + 6).expect("fits")); + let encoded = inner::encode_inner(comp, &payload).expect("encodes"); + prop_assert_eq!(encoded.len() as u64, pad::padme(payload.len() as u64 + 6).expect("fits")); let view = decode_inner(&encoded).expect("decodes"); prop_assert_eq!(view.comp(), comp); prop_assert_eq!(view.payload(), payload.as_slice()); } #[test] - #[cfg_attr(miri, ignore = "proptest is slow under Miri")] - fn decoding_never_panics_and_accepts_only_its_own_encoding(bytes in vec(any::(), 0..300)) { - if let Ok(view) = decode_inner(&bytes) { - let encoded = encode_inner(view.comp(), view.payload()).expect("encodes"); - prop_assert_eq!(encoded.as_slice(), bytes.as_slice()); + fn a_changed_encoding_is_accepted_only_if_it_is_still_an_encoding( + payload in bytes(0..3_000, any_byte), + zstd in any::(), + mutation in mutation(), + ) { + let comp = if zstd { Comp::Zstd } else { Comp::Raw }; + let mut bytes = inner::encode_inner(comp, &payload).expect("encodes").to_vec(); + check_canonical(&bytes)?; + let len = bytes.len(); + apply(&mut bytes, &mutation); + check_canonical(&bytes)?; + // Where the outcome follows from the change alone, check it directly too. A new + // `payload_len` can still name a valid encoding, of a payload ending in zeros or + // with fewer bytes, so only [`check_canonical`] judges those. + let keeps = match &mutation { + Mutation::Flip(at, _) => match at.index(len) { + 0 => Some(bytes[0] <= 1), + 1 => Some(false), + 2..6 => None, + at => Some(at < 6 + payload.len()), + }, + Mutation::Comp(code) => Some(*code <= 1), + Mutation::Rsv(rsv) => Some(*rsv == 0), + Mutation::PayloadLen(0) => Some(true), + Mutation::AnyPayloadLen(new) if *new as usize == payload.len() => Some(true), + Mutation::PayloadLen(_) | Mutation::AnyPayloadLen(_) => None, + Mutation::Resize(_) | Mutation::Truncate(_) | Mutation::Append(_) => Some(false), + }; + if let Some(keeps) = keeps { + prop_assert_eq!(decode_inner(&bytes).is_ok(), keeps, "{:?}", mutation); } } + + #[test] + fn arbitrary_bytes_decode_only_if_they_are_an_encoding(bytes in vec(any::(), 0..300)) { + check_canonical(&bytes)?; + } } } diff --git a/crates/engine/core/src/inner/encode_inner.rs b/crates/engine/core/src/inner/encode_inner.rs index 34925a5..bb47a12 100644 --- a/crates/engine/core/src/inner/encode_inner.rs +++ b/crates/engine/core/src/inner/encode_inner.rs @@ -6,7 +6,7 @@ use crypthix_types::format_error::FormatError; use crate::error::WriteError; use crate::inner::Comp; use crate::limits::{INNER_HEADER_LEN, MAX_PAYLOAD_LEN}; -use crate::pad::padme; +use crate::pad; /// The inner plaintext of `payload`: `comp ‖ 0 ‖ u32be(len) ‖ payload ‖ zero pad`, padded to /// `padme(6 + len)` bytes (FS-54), in a new buffer of protected memory. @@ -32,9 +32,11 @@ pub fn encode_inner(comp: Comp, payload: &[u8]) -> Result return Err(FormatError::Limit.into()); } let header_len = u32::try_from(payload.len()).map_err(|_| FormatError::Limit)?; - let total = padme(payload_len + INNER_HEADER_LEN as u64) + let total = pad::padme(payload_len + INNER_HEADER_LEN as u64) .and_then(|total| usize::try_from(total).ok()) .ok_or(FormatError::Limit)?; + #[cfg(test)] + crate::fault::allocation()?; let mut inner = SecretBuf::try_zeroed(total)?; // `padme(6 + len) >= 6 + len`, so both splits succeed; failing instead keeps this // panic-free. @@ -54,7 +56,10 @@ pub fn encode_inner(comp: Comp, payload: &[u8]) -> Result #[cfg(test)] mod tests { + use crypthix_crypto::secure_mem::MemError; + use super::*; + use crate::fault::{self, Fault}; #[test] fn layout_is_header_payload_then_zero_pad() { @@ -65,6 +70,15 @@ mod tests { assert!(inner[1_006..].iter().all(|byte| *byte == 0)); } + #[test] + fn no_protected_memory_fails_with_memory() { + let _guard = fault::inject(Fault::Allocation(0)); + assert_eq!( + encode_inner(Comp::Raw, b"chunk").map(|_| ()), + Err(WriteError::Memory(MemError::MapFailed)) + ); + } + #[test] fn an_empty_payload_is_just_the_header() { let inner = encode_inner(Comp::Raw, &[]).expect("encodes"); diff --git a/crates/engine/core/src/lib.rs b/crates/engine/core/src/lib.rs index 3b075a9..f1bfad8 100644 --- a/crates/engine/core/src/lib.rs +++ b/crates/engine/core/src/lib.rs @@ -14,8 +14,10 @@ //! and meta blobs sealed under their epoch's key (FS-57). //! //! Plaintext, compressed chunks and inner plaintexts live only in fixed-size -//! [`SecretBuf`](crypthix_crypto::secure_mem::SecretBuf)s of protected memory; a `Vec` holds -//! only ciphertext. Two residuals remain: zstd's working memory is on the C heap, not wiped, +//! [`SecretBuf`](crypthix_crypto::secure_mem::SecretBuf)s, wiped on free; a `Vec` holds only +//! ciphertext. On Linux a `SecretBuf` is also locked where `RLIMIT_MEMLOCK` allows and kept out +//! of core dumps; elsewhere, and under Miri, it is plain heap memory +//! ([`secure_mem`](crypthix_crypto::secure_mem)). Two residuals remain: zstd's working memory is on the C heap, not wiped, //! locked or kept from forked children (see [`compress`], R-26), and the gear table, kept in a //! `SecretBuf` rather than secret pages, is assumed to leak, since keyed chunkers have been //! attacked from observed chunk sizes; Padmé only coarsens those sizes and packs hide them @@ -47,15 +49,18 @@ //! //! let file = b"some file contents ".repeat(20_000); //! let chunks = Chunks::new(&gear, ObjectClass::Ordinary, &file); -//! // The writer takes the class and chunk count from the chunker, the reader from the manifest. -//! let sealer = ObjectSealer::new(&keys, chunks.object_shape()); -//! let ranges: Vec<_> = chunks.collect(); -//! let opener = ObjectOpener::new(&keys, ObjectClass::Ordinary, ranges.len() as u64); +//! // The writer takes the object's shape from the chunker and seals the chunks it cut, in +//! // order; `finish` gives the chunk count for the manifest, from which the reader takes it. +//! let mut sealer = ObjectSealer::new(&keys, chunks.object_shape()); //! let mut compressor = Compressor::new()?; +//! let mut written = Vec::new(); +//! for chunk in chunks.chunk_refs() { +//! written.push((chunk.bytes(), sealer.seal(&mut compressor, chunk)?)); +//! } +//! let chunk_count = sealer.finish()?; +//! let opener = ObjectOpener::new(&keys, ObjectClass::Ordinary, chunk_count); //! let mut decompressor = Decompressor::new(); -//! for range in ranges { -//! let chunk = &file[range]; -//! let sealed = sealer.seal(&mut compressor, chunk)?; +//! for (chunk, sealed) in written { //! let opened = opener.open(&mut decompressor, sealed.entry(), sealed.sealed())?; //! assert_eq!(opened.as_slice(), chunk); //! } @@ -66,6 +71,8 @@ pub mod blob; pub mod chunk; pub mod compress; pub mod error; +#[cfg(test)] +mod fault; pub mod inner; pub mod limits; pub mod pad; diff --git a/crates/engine/core/src/limits.rs b/crates/engine/core/src/limits.rs index 5a1e9e2..66d73c3 100644 --- a/crates/engine/core/src/limits.rs +++ b/crates/engine/core/src/limits.rs @@ -30,7 +30,8 @@ pub const WINDOW_LOG: u32 = 20; /// The libzstd version FS-53 pins, as `ZSTD_versionNumber` gives it: 1.5.7. /// /// zstd output is not guaranteed to be the same across versions, so the encoder is only known -/// to match the test vectors under this one; any version decodes them. +/// to match the test vectors under this one. It also defines which frames decode (FS-53), so +/// [`Decompressor`](crate::compress::Decompressor) refuses any other version too. pub const ZSTD_VERSION: u32 = 10_507; /// Bytes of the gear table: 256 little-endian `u64` words (FS-52). diff --git a/crates/engine/core/src/pad/padme.rs b/crates/engine/core/src/pad/padme.rs index 6153380..d8c84cd 100644 --- a/crates/engine/core/src/pad/padme.rs +++ b/crates/engine/core/src/pad/padme.rs @@ -69,7 +69,6 @@ mod tests { proptest! { #[test] - #[cfg_attr(miri, ignore = "proptest is slow under Miri; pure integer arithmetic")] fn padme_rounds_up_to_its_step(len in 2u64..(1 << 40)) { let padded = padme(len).expect("small lengths fit"); let e = len.ilog2(); @@ -84,7 +83,6 @@ mod tests { } #[test] - #[cfg_attr(miri, ignore = "proptest is slow under Miri; pure integer arithmetic")] fn padme_is_idempotent_and_monotone(len in 0u64..(1 << 40)) { let padded = padme(len).expect("small lengths fit"); prop_assert_eq!(padme(padded), Some(padded)); diff --git a/crates/engine/core/src/test_data.rs b/crates/engine/core/src/test_data.rs index 21f4590..09617a5 100644 --- a/crates/engine/core/src/test_data.rs +++ b/crates/engine/core/src/test_data.rs @@ -5,6 +5,7 @@ use std::ops::Range; use crypthix_crypto::key::{KdfKey, XofKey}; use crypthix_crypto::mac; use crypthix_types::id::VaultId; +use proptest::prelude::{BoxedStrategy, Strategy, any}; use crate::blob::ObjectClass; use crate::chunk::{ChunkParams, Chunks, GearTable}; @@ -17,6 +18,39 @@ pub(crate) fn pseudo_random(seed: u8, len: usize) -> Vec { data } +/// A property-test strategy for `len` bytes (start inclusive, end exclusive), each `pick` of an +/// arbitrary byte. +/// +/// Normally proptest draws and shrinks every byte. Under Miri, building that value tree of one +/// value per byte costs more than most of the tests that use it (about three quarters of a +/// chunking property's time), so the bytes are expanded instead from one drawn seed with a +/// 64-bit linear congruential generator, only the seed and the length shrink, and the longest +/// length is halved. +pub(crate) fn bytes(len: Range, pick: fn(u8) -> u8) -> BoxedStrategy> { + if cfg!(miri) { + let len = len.start..(len.end / 2).max(len.start + 1); + (any::(), len) + .prop_map(move |(mut state, len)| { + let mut out = Vec::with_capacity(len); + for _ in 0..len { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + out.push(pick(state.to_be_bytes()[0])); + } + out + }) + .boxed() + } else { + proptest::collection::vec(any::().prop_map(pick), len).boxed() + } +} + +/// Any byte, for [`bytes`]. +pub(crate) fn any_byte(byte: u8) -> u8 { + byte +} + /// The gear table of chunker seed `[seed; 32]` in vault `[0x11; 16]`. pub(crate) fn gear_table(seed: u8) -> GearTable { let key = KdfKey::from_bytes([seed; 32]).expect("non-zero key"); diff --git a/crates/engine/core/tests/tv07.rs b/crates/engine/core/tests/tv07.rs index 3d21b3e..93519de 100644 --- a/crates/engine/core/tests/tv07.rs +++ b/crates/engine/core/tests/tv07.rs @@ -3,7 +3,8 @@ //! //! The encoder groups (`Compress`, `DataBlobSeal`) expect zstd's exact output, which is only //! known for the version in the set's header, so they fail outright under any other version. -//! Every other group, decompression included, must pass with any zstd. +//! The decoding groups give the results FS-53 defines through libzstd 1.5.7; a reader on another +//! decoder must give the same results, and `Decompressor` itself requires 1.5.7. #[allow(dead_code, reason = "each runner uses part of the shared helpers")] mod common; @@ -12,9 +13,9 @@ use crypthix_core::blob::{ self, BlobContext, BlobIdKind, ChunkEntry, ChunkKeys, MetaContext, MetaKey, MetaKind, ObjectClass, ObjectOpener, ObjectSealer, }; -use crypthix_core::chunk::{self, Chunks, GearTable, ObjectShape, StreamChunker}; +use crypthix_core::chunk::{ChunkRef, Chunks, GearTable, StreamChunker}; use crypthix_core::compress::{Compressor, Decompressor}; -use crypthix_core::error::ReadError; +use crypthix_core::error::{ReadError, WriteError}; use crypthix_core::inner::{self, Comp}; use crypthix_core::limits::{MAX_CHUNK, MIN_CHUNK}; use crypthix_core::pad; @@ -32,13 +33,13 @@ const FILE: &str = "crypthix/v0/tv-07-chunk-blob.json"; /// The groups of TV-07 and their sizes. const GROUPS: [(&str, usize); 8] = [ - ("Chunking", 21), + ("Chunking", 22), ("Padme", 12), ("InnerDecode", 20), ("Compress", 9), - ("Decompress", 32), + ("Decompress", 37), ("DataBlobSeal", 4), - ("DataBlobOpen", 29), + ("DataBlobOpen", 35), ("MetaBlob", 13), ]; @@ -138,8 +139,8 @@ fn check_chunking(test: &Value) { let shape = chunks.object_shape(); assert_eq!(shape.class(), class, "{}: the shape's class", comment(test)); assert_eq!( - shape.is_single(), - expected.len() <= 1, + (shape.is_empty(), shape.is_single()), + (expected.is_empty(), expected.len() == 1), "{}: the shape", comment(test) ); @@ -162,14 +163,19 @@ fn check_chunking(test: &Value) { lengths.push(range.len()); } assert_eq!(lengths, expected, "{}: in memory", comment(test)); - if class == ObjectClass::Ordinary { - assert_eq!( - chunk::cut(&gear, &data), - expected.first().copied().unwrap_or(0), - "{}: the first cut", - comment(test) - ); + let mut refs = Vec::new(); + for chunk in Chunks::new(&gear, class, &data).chunk_refs() { + assert!(refs.len() < most, "{}: too many chunk refs", comment(test)); + assert_eq!(chunk.index(), refs.len() as u64, "{}", comment(test)); + assert_eq!(chunk.object_shape(), shape, "{}", comment(test)); + refs.push((chunk.bytes().len(), chunk.is_last())); } + let with_last: Vec<(usize, bool)> = expected + .iter() + .enumerate() + .map(|(index, len)| (*len, index + 1 == expected.len())) + .collect(); + assert_eq!(refs, with_last, "{}: chunk refs", comment(test)); let mut chunker = StreamChunker::new(&gear, class, data.as_slice()).expect("a window"); let mut streamed = Vec::new(); @@ -304,19 +310,6 @@ fn check_decompress(test: &Value, decompressor: &mut Decompressor) { } } -/// The shape the chunker gives an object of `class` and `count` chunks, from a chunker run over -/// one byte or over zeros one byte longer than a maximum chunk; only the chunker makes shapes. -fn shape(class: ObjectClass, count: u64) -> ObjectShape { - let seed = KdfKey::from_bytes([1; 32]).expect("non-zero key"); - let vault_id = VaultId::try_from_bytes([1; 16]).expect("non-zero ID"); - let gear = GearTable::derive(&seed, &vault_id).expect("derives"); - let len = if count == 1 { 1 } else { MAX_CHUNK + 1 }; - let shape = Chunks::new(&gear, class, &vec![0; len]).object_shape(); - assert_eq!(shape.is_single(), count == 1, "{count} chunks"); - assert_eq!(shape.class(), class); - shape -} - /// The keys of a data-blob test, bound to its context. fn chunk_keys(test: &Value) -> ChunkKeys { let context = BlobContext::new( @@ -382,22 +375,45 @@ fn check_data_seal(test: &Value, compressor: &mut Compressor, decompressor: &mut let opened = reader.open(decompressor, &entry, &sealed).expect("opens"); assert_eq!(opened.as_slice(), chunk, "{}", comment(test)); - // The real writer, with its own randomness, gives a blob that opens the same way. - let writer = ObjectSealer::new(&keys, shape(class, count)); + // The real writer, with its own randomness, gives a blob that opens the same way: the + // chunk as chunk 0 of an object of `count` chunks, the last only if there is one. + let first = ChunkRef::from_parts(&chunk, 0, count == 1, class); + let mut writer = ObjectSealer::new(&keys, first.object_shape()); assert_eq!( writer.blob_id_kind(), reader.blob_id_kind(), "{}", comment(test) ); - let written = writer.seal(compressor, &chunk).expect("seals"); - if BlobIdKind::for_object(class, count) == BlobIdKind::Keyed { + let identified = writer.identify(first).expect("identifies"); + let keyed = BlobIdKind::for_object(class, count) == BlobIdKind::Keyed; + assert_eq!( + identified.keyed_id(), + keyed.then_some(&id), + "{}: the keyed ID before sealing", + comment(test) + ); + let written = writer + .seal_identified(compressor, identified) + .expect("seals"); + if keyed { assert_eq!(written.blob_id(), &id, "{}", comment(test)); } let opened = reader .open(decompressor, written.entry(), written.sealed()) .expect("opens"); assert_eq!(opened.as_slice(), chunk, "{}", comment(test)); + let finished = if count == 1 { + Ok(1) + } else { + Err(WriteError::Sequence) + }; + assert_eq!( + writer.finish(), + finished, + "{}: only one chunk sealed", + comment(test) + ); } /// Checks one data-blob open and returns its `expect`. @@ -416,12 +432,12 @@ fn check_data_open<'a>(test: &'a Value, decompressor: &mut Decompressor) -> &'a match result { Ok(opened) => { assert_eq!(expect(test), "Ok", "{}", comment(test)); - assert_eq!( - opened.as_slice(), - common::output(test, "plaintext"), - "{}", - comment(test) - ); + let expected = if test.get("plaintextZeros").is_some() { + vec![0; usize_of(common::output_int(test, "plaintextZeros"))] + } else { + common::output(test, "plaintext") + }; + assert_eq!(opened.as_slice(), expected, "{}", comment(test)); } Err(error) => assert_eq!(error_name(error), expect(test), "{}", comment(test)), } @@ -482,7 +498,7 @@ fn check_meta(test: &Value) { assert_eq!(opened.as_slice(), cbor, "{}", comment(test)); } -/// Every group but the encoder's, which any zstd version must pass. +/// Every group but the encoder's: the results FS-53 defines through libzstd 1.5.7. #[test] #[cfg_attr(miri, ignore = "zstd is C, which Miri cannot run")] fn tv07_chunk_blob() { From 610a769d2c57d4198096829243b9b98679325c77 Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 21:56:58 +0530 Subject: [PATCH 11/15] test(core): TV-07 pins the data-blob cap, block sizes, store-raw, truncated headers and more chunking edges --- tests/test-vectors/README.md | 2 +- .../crypthix/v0/tv-07-chunk-blob.json | 470 +++++++++++++----- tests/test-vectors/gen/src/tv07.rs | 115 +++-- tests/test-vectors/gen/src/zstd_frame.rs | 65 ++- 4 files changed, 481 insertions(+), 171 deletions(-) diff --git a/tests/test-vectors/README.md b/tests/test-vectors/README.md index 0a1f804..a676328 100644 --- a/tests/test-vectors/README.md +++ b/tests/test-vectors/README.md @@ -17,7 +17,7 @@ Each file follows the Wycheproof shape: `testGroups` of `tests`, each with a `tc | TV-03 deterministic CBOR | `crates/foundation/types/tests/vectors.rs` | Generated, deterministic; the `GeneratedDocumentParse` group is built by the runner from its inputs | | TV-04 labels, `H`, `KDF`, `MAC`, the gear-table XOF, derived keys and zero values | `crates/foundation/crypto/tests/tv04.rs` | Generated from the seeded stream; outputs computed by the generator's own section 7 code (`gen/src/cx.rs`) | | TV-05 CX-AEAD seal, open, commitment, hedged and synthetic nonces (including replayed randomness), an all-zero nonce | `crates/foundation/crypto/tests/tv05.rs` | Generated from the seeded stream; outputs computed by `gen/src/cx.rs` | -| TV-07 chunk boundaries, Padmé, inner plaintexts, compression, data and meta blobs | `crates/engine/core/tests/tv07.rs` | Generated from the seeded stream; boundaries from an independent one-byte-at-a-time FastCDC (`gen/src/cdc.rs`) for the `ordinary` class and from the length alone for the `secret` class, frames built by hand (`gen/src/zstd_frame.rs`) or by the zstd encoder named in the header (`zstd`), seals by `gen/src/cx.rs`. Inputs too large for hex are a `dataKey` and `length` (the keyed BLAKE3 XOF over the empty input), a `pattern` repeated to `length`, or `zeros`; a frame with a run of more than 1,024 zero bytes is `frameHead`, `frameZeros` zero bytes, then `frameTail`. The `CutEdges` chunking cases are found by a deterministic search over data keys and chunker seeds, and the generator checks with its own chunker that each cuts where its comment says. The `Compress` and `DataBlobSeal` groups hold only under that zstd version, and the runner fails if it links another; every other group holds under any | +| TV-07 chunk boundaries, Padmé, inner plaintexts, compression, data and meta blobs | `crates/engine/core/tests/tv07.rs` | Generated from the seeded stream; boundaries from an independent one-byte-at-a-time FastCDC (`gen/src/cdc.rs`) for the `ordinary` class and from the length alone for the `secret` class, frames built by hand (`gen/src/zstd_frame.rs`) or by the zstd encoder named in the header (`zstd`), seals by `gen/src/cx.rs`. Inputs too large for hex are a `dataKey` and `length` (the keyed BLAKE3 XOF over the empty input), a `pattern` repeated to `length`, or `zeros`; a frame with a run of more than 1,024 zero bytes is `frameHead`, `frameZeros` zero bytes, then `frameTail`, and an all-zero expected plaintext of more than 1,024 bytes is `plaintextZeros`, its length. The `CutEdges` chunking cases are found by a deterministic search over data keys and chunker seeds, and the generator checks with its own chunker that each cuts where its comment says. The `Compress` and `DataBlobSeal` groups hold only under that zstd version, and the runner fails if it links another. The decoding groups give the results FS-53 defines through libzstd 1.5.7; a reader on another decoder must give the same results, and `crypthix-core`'s own `Decompressor` requires 1.5.7 | | TV-17 versions, criticality, feature bits and GREASE | `crates/foundation/types/tests/vectors.rs` | Generated, deterministic | ## Changing a vector diff --git a/tests/test-vectors/crypthix/v0/tv-07-chunk-blob.json b/tests/test-vectors/crypthix/v0/tv-07-chunk-blob.json index f798c84..00341ac 100644 --- a/tests/test-vectors/crypthix/v0/tv-07-chunk-blob.json +++ b/tests/test-vectors/crypthix/v0/tv-07-chunk-blob.json @@ -28,7 +28,7 @@ "M-39", "T-84" ], - "description": "Files found by search so a cut sits on an edge of the rule: at the minimum and one past it, at the switch from the strict to the loose mask (a loose-only match at 2⌊center/2⌋ cuts, one at 2⌊center/2⌋ − 1 does not), at the last position tested, an odd last byte that would match if it were tested, and a repeated pattern that is cut only at the maximum. The generator checks each with its one-byte chunker." + "description": "Files found by search so a cut sits on an edge of the rule: at the minimum and one past it, at the switch from the strict to the loose mask (a loose-only match at 2⌊center/2⌋ cuts, one at 2⌊center/2⌋ − 1 does not), at the last position tested, an odd last byte that would match if it were tested, a repeated pattern that is cut only at the maximum, and a file between the average and the maximum where no position matches, so it is one chunk. The generator checks each with its one-byte chunker." }, "KeyedGear": { "cites": [ @@ -89,14 +89,15 @@ "FS-53", "T-40" ], - "description": "One zstd frame at level 3 with its content size, no checksum, no dictionary ID, window ≤ 2^20; equal output is only expected from the zstd version in the header." + "description": "One single-segment zstd frame at level 3 with its content size, no checksum, no dictionary ID and window_log 20; equal output is only expected from the zstd version in the header." }, "StoreRaw": { "cites": [ "FS-53", + "FS-56", "T-40" ], - "description": "The frame is kept only if 16 × frame ≤ 15 × chunk; otherwise the chunk is stored with comp 0." + "description": "The frame is kept only if 16 × frame ≤ 15 × chunk; otherwise the chunk is stored with comp 0. A reader refuses a comp 1 payload that breaks the rule as Decompress, before its frame is checked, so each chunk has one encoding." }, "SecretRaw": { "cites": [ @@ -111,14 +112,21 @@ "FS-53", "T-39" ], - "description": "Frames FS-53 allows decode to exactly plain_len bytes with any zstd version; raw and RLE frames are built by hand." + "description": "Frames FS-53 allows decode to exactly plain_len bytes, as libzstd 1.5.7 decodes them; a reader on another decoder must give the same results, and crypthix-core's own Decompressor requires 1.5.7. Raw, RLE and literals-only frames are built by hand." }, "FrameRejected": { "cites": [ "FS-53", "T-39" ], - "description": "A frame that is not exactly one frame with content size plain_len in the shortest field that holds it, no checksum, no dictionary ID, the unused and reserved bits clear and a window ≤ 2^20, or whose content differs from its declaration, is Decompress." + "description": "A frame that is not exactly one single-segment frame with content size plain_len in the shortest field that holds it, no checksum, no dictionary ID and the unused and reserved bits clear, that is cut off, or whose content differs from its declaration, is Decompress." + }, + "BlockSize": { + "cites": [ + "FS-53", + "T-39" + ], + "description": "A block larger than min(window, 128 KiB), where a single segment's window is plain_len and an RLE block counts the bytes it regenerates, is Decompress, though libzstd 1.5.7 decodes such a frame in one pass." }, "PlainLenCap": { "cites": [ @@ -187,7 +195,7 @@ "FS-53", "T-39" ], - "description": "A data blob whose payload does not decode to exactly plain_len bytes is Decompress." + "description": "A data blob whose payload is not exactly plain_len bytes when raw, or does not decode to exactly plain_len bytes when compressed, is Decompress." }, "SealShape": { "cites": [ @@ -633,7 +641,7 @@ }, { "tcId": 20, - "comment": "a strict match at strict_end - 1, the last position tested: a one-byte last chunk", + "comment": "a strict match at 2⌊n/2⌋ − 1, the last position tested: a one-byte last chunk", "flags": [ "CutEdges" ], @@ -669,6 +677,24 @@ 1048576, 5 ] + }, + { + "tcId": 22, + "comment": "320 KiB with no position matching under either mask: one chunk of the whole file, shorter than the maximum", + "flags": [ + "CutEdges" + ], + "inputs": { + "chunkerSeed": "fb10d60244f59fe27c6a6c542ab482c2c379db63ebecbde3e7ca89420172254a", + "vaultId": "2de5e414d2da00da8b7d44ab97fe6d32", + "class": "ordinary", + "dataKey": "b1e9eb6dcf6d66fe85e835ff63e0ac642ba2cd71e80cc6ed466dbcd7bf9f2961", + "length": 327680 + }, + "expect": "Ok", + "lengths": [ + 327680 + ] } ] }, @@ -676,7 +702,7 @@ "type": "Padme", "tests": [ { - "tcId": 22, + "tcId": 23, "comment": "0 stays 0", "flags": [ "Padme" @@ -688,7 +714,7 @@ "padded": 0 }, { - "tcId": 23, + "tcId": 24, "comment": "1 stays 1", "flags": [ "Padme" @@ -700,7 +726,7 @@ "padded": 1 }, { - "tcId": 24, + "tcId": 25, "comment": "2 stays 2", "flags": [ "Padme" @@ -712,7 +738,7 @@ "padded": 2 }, { - "tcId": 25, + "tcId": 26, "comment": "7 stays 7", "flags": [ "Padme" @@ -724,7 +750,7 @@ "padded": 7 }, { - "tcId": 26, + "tcId": 27, "comment": "9 rounds to 10", "flags": [ "Padme" @@ -736,7 +762,7 @@ "padded": 10 }, { - "tcId": 27, + "tcId": 28, "comment": "an empty payload: 6", "flags": [ "Padme" @@ -748,7 +774,7 @@ "padded": 6 }, { - "tcId": 28, + "tcId": 29, "comment": "a 1,000-byte payload: 1,006", "flags": [ "Padme" @@ -760,7 +786,7 @@ "padded": 1024 }, { - "tcId": 29, + "tcId": 30, "comment": "1,025 rounds to a multiple of 64", "flags": [ "Padme" @@ -772,7 +798,7 @@ "padded": 1088 }, { - "tcId": 30, + "tcId": 31, "comment": "a 64 KiB chunk: 65,542", "flags": [ "Padme" @@ -784,7 +810,7 @@ "padded": 67584 }, { - "tcId": 31, + "tcId": 32, "comment": "2^20 stays 2^20", "flags": [ "Padme" @@ -796,7 +822,7 @@ "padded": 1048576 }, { - "tcId": 32, + "tcId": 33, "comment": "a 1 MiB payload: 2^20 + 6", "flags": [ "Padme" @@ -808,7 +834,7 @@ "padded": 1081344 }, { - "tcId": 33, + "tcId": 34, "comment": "2^32 + 1", "flags": [ "Padme" @@ -825,7 +851,7 @@ "type": "InnerDecode", "tests": [ { - "tcId": 34, + "tcId": 35, "comment": "an empty raw payload is the 6-byte header", "flags": [ "InnerOk" @@ -838,7 +864,7 @@ "payload": "" }, { - "tcId": 35, + "tcId": 36, "comment": "a 3-byte zstd payload, padded to 10", "flags": [ "InnerOk" @@ -851,7 +877,7 @@ "payload": "616263" }, { - "tcId": 36, + "tcId": 37, "comment": "a 1,000-byte raw payload, padded to 1,024", "flags": [ "InnerOk" @@ -864,7 +890,7 @@ "payload": "deb35e3b6d10702f893e1295fcdad375e60bfd4d121dc0dc9768779ea52879c6f5a542e4a07f05edc4f4e0a021382d8eaa9f965bcaa89e5992c6dfca97d315e08e8d7251e06816af999a194d94f432b1c67cc53ac7aa105b86ab351f172e8b878eb2d82af862887173ed55f85cd60022c4299e15ede66f1765f9d34f0bbea01d497f83978cfc8e5e9298fbee1cdb9ce0c76001fac6b06cb69c7b57d547f41b143180b08f5bcf701c0a4b465e450e49c304dcf9b50c548a35e859f319ea81ea72fd6d26d6a7a23fd73b127356266e3aae52fcdefc2e6c45156172eb895e550282035fca1cebab1dc572c336efb97eb97d749d7358f4978a6a8635a6de9477ce8ddc1d530bbdd9dab8f00a515143d907834c83a4e2eb6680d9383bf7cd40f1fb57ed30a31cd0b6f574001ee52e88a7e071e385303a32910f4c12b9213b06e529c8e36dacbb905e23da919e77cf286027194c3b652e5ff329a40bed31edc7c74d348aadf1e33b1d06d87cccf30d992deba8c8bfd626d5f243c94d1d3ec451101b6aebab66a79e345a88f8bb4c851464d85b035d6a2c8545a57bc304bb9740b7cb1db65719aa44839bb2aeca57bf854bdab161fc7f7525bbd674da950f42a12fd832b89db29a00dfb1d54177535edb436af98a6820a6b507a0f6c5bcd3cad852fbd3b428983945cec95ea2626475a79f5e5974421166644f24c80cd31be02d9176484f3382df8c1b4be3eb26cfea44d92911c8ba8620c63482b99d57039c490b62e090f5ef0b4b74d6a436fd169054d769e941d9a880e8efec07ec2edb6986707cf73798f3767ad814e2785e8a1abdd86ed3ca5b59442aa6f35a7d39c3ffb43d811ce580d245dc07d1e9dcf58c47dd49cedf9ea2973406bce9256b452e7b33614bd519c4240e786229e80546df779474ad89f69bf333363247725cc0fdaf240b5d8be5b858efc6574a25f6d8747bc38456fd0d2050b3502a812a9a870e36c8f5d5539f94ed7c57846539b5bf09302c6119784756c6daff14162bc59549ea0d154de113ae4bd8328c955e8ff761e0dec71cc0d614fa0ee8d86e26a550ad6d2f28c4a8ddcfb57aa644b22df158d31ed0b42612d610578c636a4233b2102f9e1574b7a06af35a838e6170061b06b34370385f5733646d2fc582ce82faa0a47c603af179f7480712d6fc056e318bb7e44c154268fcb6ef86686171b94771f12c744e1f6d8cb10d52ea446ce55e5bf669eb6c34e5a49d3a6ccac14d95bc4b06cc5c2b690f19178a30c33e6ac42908e69651a945a35873fb790758cc03201814ba668c63b3635cf2141939907d29fd060bb2a94c00b93b178cda8bc648d7ee9e36b6c2aeda553c18e325ab69692d818011ffe5e4b121818cef244d4639bbf3426eea34b8526570791859c0aa14" }, { - "tcId": 37, + "tcId": 38, "comment": "a payload of exactly 1 MiB", "flags": [ "InnerLimit" @@ -879,7 +905,7 @@ "comp": 0 }, { - "tcId": 38, + "tcId": 39, "comment": "payload_len 2^20 + 1", "flags": [ "InnerLimit" @@ -890,7 +916,7 @@ "expect": "Limit" }, { - "tcId": 39, + "tcId": 40, "comment": "payload_len 2^32 - 1", "flags": [ "InnerLimit" @@ -901,7 +927,7 @@ "expect": "Limit" }, { - "tcId": 40, + "tcId": 41, "comment": "payload_len 2^20 with only the header", "flags": [ "InnerPadding" @@ -912,7 +938,7 @@ "expect": "Padding" }, { - "tcId": 41, + "tcId": 42, "comment": "no bytes", "flags": [ "InnerPadding" @@ -923,7 +949,7 @@ "expect": "Padding" }, { - "tcId": 42, + "tcId": 43, "comment": "five bytes, one short of a header", "flags": [ "InnerPadding" @@ -934,7 +960,7 @@ "expect": "Padding" }, { - "tcId": 43, + "tcId": 44, "comment": "comp 2", "flags": [ "InnerPadding" @@ -945,7 +971,7 @@ "expect": "Padding" }, { - "tcId": 44, + "tcId": 45, "comment": "comp 255", "flags": [ "InnerPadding" @@ -956,7 +982,7 @@ "expect": "Padding" }, { - "tcId": 45, + "tcId": 46, "comment": "rsv 1", "flags": [ "InnerPadding" @@ -967,7 +993,7 @@ "expect": "Padding" }, { - "tcId": 46, + "tcId": 47, "comment": "rsv 0x80", "flags": [ "InnerPadding" @@ -978,7 +1004,7 @@ "expect": "Padding" }, { - "tcId": 47, + "tcId": 48, "comment": "the first pad byte is not zero", "flags": [ "InnerPadding" @@ -989,7 +1015,7 @@ "expect": "Padding" }, { - "tcId": 48, + "tcId": 49, "comment": "the last pad byte is not zero", "flags": [ "InnerPadding" @@ -1000,7 +1026,7 @@ "expect": "Padding" }, { - "tcId": 49, + "tcId": 50, "comment": "one byte longer than padme(6 + payload_len)", "flags": [ "InnerPadding" @@ -1011,7 +1037,7 @@ "expect": "Padding" }, { - "tcId": 50, + "tcId": 51, "comment": "one byte shorter than padme(6 + payload_len)", "flags": [ "InnerPadding" @@ -1022,7 +1048,7 @@ "expect": "Padding" }, { - "tcId": 51, + "tcId": 52, "comment": "no pad at all", "flags": [ "InnerPadding" @@ -1033,7 +1059,7 @@ "expect": "Padding" }, { - "tcId": 52, + "tcId": 53, "comment": "comp 2 with payload_len 2^20 + 1: comp is checked first", "flags": [ "CheckOrder" @@ -1044,7 +1070,7 @@ "expect": "Padding" }, { - "tcId": 53, + "tcId": 54, "comment": "rsv 1 with payload_len 2^20 + 1: rsv is checked first", "flags": [ "CheckOrder" @@ -1060,7 +1086,7 @@ "type": "Compress", "tests": [ { - "tcId": 54, + "tcId": 55, "comment": "1 MiB of zeros", "flags": [ "Compress" @@ -1075,7 +1101,7 @@ "inner": "01000000003228b52ffda0000010005400001000000100fbff39c00202001000020010000200100002001000020010000200100003001000" }, { - "tcId": 55, + "tcId": 56, "comment": "5,000 bytes of text", "flags": [ "Compress" @@ -1090,7 +1116,7 @@ "inner": "01000000004028b52ffd608812b50100d40254686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e200100c51ad8ab320000" }, { - "tcId": 56, + "tcId": 57, "comment": "random bytes then zeros: the frame just saves 1/16", "flags": [ "StoreRaw" @@ -1105,7 +1131,7 @@ "inner": "010000000ef328b52ffd60000f4d770004eecee3a594a3f6a4c6eb36e5c72dbca99dcb1c2646758cb2675a3a3a98bbc69d3a392330c6d5bbb9040987a1aa1cd21eaff241288d8a98a0bfb8bcd796649411d6f1a56211a04d58f1a3a3d204be02aa2012769b16bc018cc9aec7dcd4e63cf7ce0e2791f1eeda3839b75fe30ce27c412ee74279e44bccccae3b31df6fff004854690f7ebf50194b419e3b49388ea3c1303ba10861da2552a11f82e18e9c4b62f1f5e77ca3f03961a7763ce28c9f97c0d7053a96ac3ee3e9b09fc3661faec235bc6544702e6bff031ed132237ab05f441b257293ff503fa4f61874d5cd19ae1fc036b1e9f288c957f2f4c6023487522e269841c864f7c0aefebc446d22b2e677be0fc600c93c3225219c57ea5e7e25ae08286e0fc4b9a600ebff22fd15bbdb0447a2f61ecc0dd857ec8c082410016fc9693a24157a751f8fcb48f6ddc987190ba81c4a198b525c9717e8af96ae7f8c8338102a5e6c84ecf05fbb2eb472dfb02c5ca3a8e5c308023a182ee731109f124a0f04ad1175f1eecc213352f23d2f47d972bfe69d8e765886206fb6a027e927736236be0c660eace3ee09e650908d9fe8a59c5333afe9d43e55dc9c8523f6b05745d33ebf8c6af91d34c4736cd8001cda7c3008a5e3363cc48b548b7ffeff5f2e9e4e19fefc321f951c28e3eded6e7aba985df066047a64301f4a1ed1c7a1fa89660f58303cdd41dc6210d478e80f937fdb9c5b9c5a8ff194f63c731af10c1d2134272b15a41c5cd3d07d72c088f234dd9c85093ff0f01919484a2e130d1c982c0a9d8217ee959a9109a32d172de7cc357aee9434c89f587c609c37860e7dcf7790c2dee5199a1080a30f8a7e040ada1f49026fb859fa49c455ae180bd06dacec07004d56d04c7c0d04cf8c6291d98937f68ac4810ee168c2de5e69a392ae8732e96a68b4a67f9c7150d88f2b102c33388bf342b674b2e67abdf21e8e128fb6d28135d0d8ee4ef3e5423200dc8321adf5a88061ec91f44f307e6398e2e9f388d2d3cb4b3eda4e4f31918dc1d3a096b13cea11a1fd2ff17183f654edfc726812ea2efec73001e8b634e8d07d0e391c5acd42b5de1ce1512371cf9ed3688b2d93e403f4076a2de6cf808dab938c037272ccb418f134d55dca7a16b1ef5b1bfdc862301aa7a6329a5c7719f82b2b85fe453e7245149e20e4dc57ba287e8f677941e8f076bfd94cd4f6f91c2f871b50994944046eaba246c9865bbc435f087e2956d9ce3d36ad34caabe967a69d0e9897a0862dc3af5dd512ce0a65070ad605fd8b783c36fd6fbabfaaea8991f36d7c9878236ad3f607c33caa6251bf485f6f16a1ae789beef9f9d80b9ddfafdcc7ab3bda5deb5f03e864c051ddd9ab9040d5b6662620b2a95452347e60b1e30982dcf06531b9fb066177b4e2e1e8174f6e7846c10042ee55de255a26749ce9e12577c5184133a2fe0888fb29f50707df137d7aa2ebb1e0a92984b3387210879ea3ec4950277347a47dc4e7633880436bac5fc7bdc4e8776bc1b08f039247e53c24537b9dea1a3a26d2ba9d5a62b8e87cd707ffff6009c703d31e9dc3fd2dc9099526265a68fd52fc716e982f59b4e3bc48a46706555ff64dc932d77fba1ff89b56f4ef832099a8ac03ccaa2f0a32545201404a813e4c4bf726c40105bc45824b13078dc05dfdeded13655cb7bac8bd4070569314888fbcebd8e53abbee7bb472d65d41f068148647791c356c6d57eb37b49a7a46d3db13cd98f6c91bad25ae6cd50c74015ec142f13f9f0858b5c3a908ef818da8946ff25a3dc1c51d08e44778ce24e4293e8e97930c71e9fd1f8070ffebfa7c77cad94dc338e7e5c408cbcb64d45c61e60b648896a0e62386db0e77b5fe7aaac13b6a8267b732942e04909553701ac521c4500c5020a173cfb217ee5c32084fd2b3c2ad5e9bab93eb51e7d1721436f1545e153c971d2b152470974f85aef41c5ec8144ae93e368b2a975443a75b1334f37e1ee4b6ec935aac556fa481db14dae4d1d609c48a4982c18cd98a7f0fe76f925d562825c72e775d1ed965b017f5e372377b87c24e74811804041f1cd79e25f3dddefcdd33f2aed987bd21db9306df2c7f9bbb60d9953e0c2139c6a241adcb8f5b8fea1e543167d0d35ae65f48a7fc0f2a9d19b744310048fbf1dc6b329024ad9b35d3c7137e98c80411cb7b1a18c08591b357997eebe9a0c8ae7dc8dc1609a820eb8035aeead2303f2608939d7e5e260e4700aebe8e78d69c5e8847681519e1e30954b0430402f2e688e8414088d4104e77345f99bd218c6f6fe126d0da78745c04ce21e374f2b7fc61151aa084a0120b9b2a73f4c73b403a563f761aee101ed95d6933453641e714983ecd38f4d10e80e81bc185fd3c7b5334338e1ec5752fc9195fcd8a77999cf27d1c442c615e6839896b39edebf53b686bc94206b037b35440fe8d28100294f0b45245efaf87cdff66def91fdbc69595afd327804a75737e90dd42219679fbb7c96fec22e8a64312befde1712f68f001acf4a0e22ac723c60a851431a0921ecdb28a1a1b99a539aa8ab9609201de590a204e019b2a9ed274648f7b9a8bed0df8cbe339098fe850107098de5a8c22a82c13dfd74218a6c4bf5ebca6837015a1a1e5b440c35d05ed1b6b8b67819955efbc0fd6121f25aab01bb4784f0acd1ea12520575721308c6978ad15644ef59ce8756e174f07937d22bef45e097eca09fc56d2081c871556cad4393a576d041d8b9d084ed9db78d2f0a940bfa8cb937c618e42bb6b78edb351d1645d7a528115c0cc15a389d06c00693468cb959a6774c48beef9a6f10a9ea09096218f5927ddca96067a7d123226d0ec9d0e288f8bdcecf1dd9b076b6840b2b8a405d7cc5c51aa09ca4481a75223a7eafa29a63aa2502a46658d5c6e0b98ccf47d4108544fdece0a2e3628b59ee41c6b8760520720a19156588389b9f1c786697f5f5a827d9f56e53aca1cc9f414f1ad9823302f0f4b185b810532d3e25c7f42458fbcdfcb1564e14777acd708e3361d38b294f03339509252f5ce9d3b1913638ed269f3062310ef94375c9a6f9c42764ba31f847ee16ce2c8b639af3bdadf4602a5b9128d2ab0e7158fd2ac16ca3c61f132d6f413f2807c1b2720bafe4bc2b2388501b1f77a0753872bb728ccef09b3c4babf14caa2459fc2383e8b65db8a7fa78279ef89482b04fbf57b62bd00c8364bf0ae479d15026f5be9a4666d6a25ce5ea3cd8f9b92381f1b376563a338dd90fdeac13d51d20846ae9bc8605c8fd63e13dfce9dbcc8e89eeb320a1f6650b5ceb2e2ede81f1539aad7c25b50d0d2215f766112f0c1d92b57ead4014e7f8c0072fed7aa6af75cf897924210ec7750495cb619987f0efb346d469bf8cb5bfaaf018ce8a088d1174071b82b0789ff76b0514c80459119c5cb4e81a445db3e920cf34351dc0dddc0891d207c2ac3337a965826bd8d9060a7f2ba8c70e49d54be0557407f0c584b8b86ff230da6ba97c3ef2e083f30e4c7bbbe05bb781621ad3739547d58b8301ecde8ca184986415a4119695dcbb1b941b6bd9b12402badac6066cfb0796dafb4b543c16c1992943fd8d2f51b0d0d90528d389fd7805b6289d1d9227b91036f1f83b4c16a53e96f16f9f4fe8ee108e8f990fcd1fce02e35aa0f0e8f416c98253209cf1753551d7c392ca67116cc682a2bb3f936b30470509f6b7d4139dc1f167500a589fa93839eb066018264e4dbaa8fe09f83598146e34fefea5cf8b196536dc04544946992ecddc9e620b055f86e50e3b5a0ac064ecb83eda8d961e30975abb4499be7777650b93fa4ec0ce8b592998969c627de6e4359d722db7f36265fbe9b8a7b9c1c67f3ad7334883260846becc1da851297cb4a495c3acb7e095bd469241a18c0a010dcd20a797fd946d6fdd351082a9bfc64a4da2b6046e083344e020ce37188ae7bdf4fc58cc4df45f192b410b9af6210e16c3ff965717d62805d9acbf9d283cd823d20819a6e66d8f9aff3d30f768c25c96feb1625fa7f9f8ccd12c6919dc3f62e48df7f911dad1b7d857296b2679a94b2c3e35f0f0a36610d5615f454646592573919148263ecb4827dbe2cd70f5084b7183f48e0e6c5f48125d307a02892725248e1f271bee208e01d2aaf1fce4b8cd4fcbe6e843352c0f167fd914aedfe86cd124d444ba9e2259abae64eb465e3fcb507a3e566ed7e4be6b78e6347f258ba999d26568ce8be8e14ee68adf02af053c83a518aa6464e73be5fb6518215e0ba487decec8fbf6a94553f74e9c7f4e7381c6382b866970aaa95b986e4184415b8bc9b1a98d50aabd92ba28c73bdb14c65af3a0fd8b7c3718feddff47b18fa252b4a4ab3a3d4e83663199dee78741c2f020bd1bd4950c61c27cbc71680dbd6ff1a9f2e863439c2890c472521b15dc86eef5cdafd614a7011191a87c5dafe611cb20b46eb47c12d4b587c0d5ff0d03735b7e7fdc828fade1e834a8802b76a4990a6b5d4ba6defb4b238753fe56d6bda7aec212e14b185f4db189ca2d4e466ea47bc4163e8559e197e1fe643083697475a422b7db75e05188fc45d68fc2500af8438a010da4b1bd0ef2f25b833bb1a3eeef5eec2ac86f79e24116f03e692b8aaa6fafce1521100d29b39a6cf5d75a92edd2264b4227dd9f59a709c6202165c49d9efe49b2fcab1b7d74e3c402774dddf63178923d6f1bd4576a13a25ef4788ebf5b3d53a842c7c5184963e8e5bb2f315b2bab1100e350ee4a8ea4ef15b876400cbdfdd0ad70bbc610ab1cbd4a02a71606839aea56a3fcc3f6aae7b4471468ad723d19e49f54fdac3a92715522d9d7616bf6247b2fd4484573a72db2a5c3096d81c1da30520f883efd3a71ff798e8c5007f42613d3116e9667922eac1c60275940322e813a1742acde9eb4d8cb1884c145a5f5146974d3e42f73a150a20468a72dcaf0d1d0eb729e300a78a6ab1795a0d924530270add679dc80b381ab9c157cfa20abb15c0074666b775003ab2f159eb3ae1519b9c716e6817ce7c360080273c6b90904cddec25cb5f28a8e292d801621bdcdf00b9d5843ff976167d49eab357ab030014b46d69ad79f7a4ebbaaef03eda9d95c60763d678c48e032b68c55fb2b684596e2909339b074c5a830e8ed2fede9de30a2805310829845ecbbaed46aeb9288c2086887291e04356bc77aa636359170311dbe1b4fc0d4722866be1669f9152e2474c5e5aa821a27b53219545c163ed921348aceb379414fc477b2d35aeb7d715df535b35ee4d6f277d02bfed4ee25e39e7ec2a9d7d4f1de0e7c63dbe0525ffb908fc231100aaeaf06321e3277632d0ac78fd1ecac1f2c1946a62a896cd26693e4535a20cec5c39bd5dfb848346b0e6ed81e78c7ab9000100e0ee50811a00000000000000" }, { - "tcId": 57, + "tcId": 58, "comment": "one more random byte: the frame no longer saves 1/16, stored raw", "flags": [ "StoreRaw" @@ -1120,7 +1146,7 @@ "inner": "000000001000cee3a594a3f6a4c6eb36e5c72dbca99dcb1c2646758cb2675a3a3a98bbc69d3a392330c6d5bbb9040987a1aa1cd21eaff241288d8a98a0bfb8bcd796649411d6f1a56211a04d58f1a3a3d204be02aa2012769b16bc018cc9aec7dcd4e63cf7ce0e2791f1eeda3839b75fe30ce27c412ee74279e44bccccae3b31df6fff004854690f7ebf50194b419e3b49388ea3c1303ba10861da2552a11f82e18e9c4b62f1f5e77ca3f03961a7763ce28c9f97c0d7053a96ac3ee3e9b09fc3661faec235bc6544702e6bff031ed132237ab05f441b257293ff503fa4f61874d5cd19ae1fc036b1e9f288c957f2f4c6023487522e269841c864f7c0aefebc446d22b2e677be0fc600c93c3225219c57ea5e7e25ae08286e0fc4b9a600ebff22fd15bbdb0447a2f61ecc0dd857ec8c082410016fc9693a24157a751f8fcb48f6ddc987190ba81c4a198b525c9717e8af96ae7f8c8338102a5e6c84ecf05fbb2eb472dfb02c5ca3a8e5c308023a182ee731109f124a0f04ad1175f1eecc213352f23d2f47d972bfe69d8e765886206fb6a027e927736236be0c660eace3ee09e650908d9fe8a59c5333afe9d43e55dc9c8523f6b05745d33ebf8c6af91d34c4736cd8001cda7c3008a5e3363cc48b548b7ffeff5f2e9e4e19fefc321f951c28e3eded6e7aba985df066047a64301f4a1ed1c7a1fa89660f58303cdd41dc6210d478e80f937fdb9c5b9c5a8ff194f63c731af10c1d2134272b15a41c5cd3d07d72c088f234dd9c85093ff0f01919484a2e130d1c982c0a9d8217ee959a9109a32d172de7cc357aee9434c89f587c609c37860e7dcf7790c2dee5199a1080a30f8a7e040ada1f49026fb859fa49c455ae180bd06dacec07004d56d04c7c0d04cf8c6291d98937f68ac4810ee168c2de5e69a392ae8732e96a68b4a67f9c7150d88f2b102c33388bf342b674b2e67abdf21e8e128fb6d28135d0d8ee4ef3e5423200dc8321adf5a88061ec91f44f307e6398e2e9f388d2d3cb4b3eda4e4f31918dc1d3a096b13cea11a1fd2ff17183f654edfc726812ea2efec73001e8b634e8d07d0e391c5acd42b5de1ce1512371cf9ed3688b2d93e403f4076a2de6cf808dab938c037272ccb418f134d55dca7a16b1ef5b1bfdc862301aa7a6329a5c7719f82b2b85fe453e7245149e20e4dc57ba287e8f677941e8f076bfd94cd4f6f91c2f871b50994944046eaba246c9865bbc435f087e2956d9ce3d36ad34caabe967a69d0e9897a0862dc3af5dd512ce0a65070ad605fd8b783c36fd6fbabfaaea8991f36d7c9878236ad3f607c33caa6251bf485f6f16a1ae789beef9f9d80b9ddfafdcc7ab3bda5deb5f03e864c051ddd9ab9040d5b6662620b2a95452347e60b1e30982dcf06531b9fb066177b4e2e1e8174f6e7846c10042ee55de255a26749ce9e12577c5184133a2fe0888fb29f50707df137d7aa2ebb1e0a92984b3387210879ea3ec4950277347a47dc4e7633880436bac5fc7bdc4e8776bc1b08f039247e53c24537b9dea1a3a26d2ba9d5a62b8e87cd707ffff6009c703d31e9dc3fd2dc9099526265a68fd52fc716e982f59b4e3bc48a46706555ff64dc932d77fba1ff89b56f4ef832099a8ac03ccaa2f0a32545201404a813e4c4bf726c40105bc45824b13078dc05dfdeded13655cb7bac8bd4070569314888fbcebd8e53abbee7bb472d65d41f068148647791c356c6d57eb37b49a7a46d3db13cd98f6c91bad25ae6cd50c74015ec142f13f9f0858b5c3a908ef818da8946ff25a3dc1c51d08e44778ce24e4293e8e97930c71e9fd1f8070ffebfa7c77cad94dc338e7e5c408cbcb64d45c61e60b648896a0e62386db0e77b5fe7aaac13b6a8267b732942e04909553701ac521c4500c5020a173cfb217ee5c32084fd2b3c2ad5e9bab93eb51e7d1721436f1545e153c971d2b152470974f85aef41c5ec8144ae93e368b2a975443a75b1334f37e1ee4b6ec935aac556fa481db14dae4d1d609c48a4982c18cd98a7f0fe76f925d562825c72e775d1ed965b017f5e372377b87c24e74811804041f1cd79e25f3dddefcdd33f2aed987bd21db9306df2c7f9bbb60d9953e0c2139c6a241adcb8f5b8fea1e543167d0d35ae65f48a7fc0f2a9d19b744310048fbf1dc6b329024ad9b35d3c7137e98c80411cb7b1a18c08591b357997eebe9a0c8ae7dc8dc1609a820eb8035aeead2303f2608939d7e5e260e4700aebe8e78d69c5e8847681519e1e30954b0430402f2e688e8414088d4104e77345f99bd218c6f6fe126d0da78745c04ce21e374f2b7fc61151aa084a0120b9b2a73f4c73b403a563f761aee101ed95d6933453641e714983ecd38f4d10e80e81bc185fd3c7b5334338e1ec5752fc9195fcd8a77999cf27d1c442c615e6839896b39edebf53b686bc94206b037b35440fe8d28100294f0b45245efaf87cdff66def91fdbc69595afd327804a75737e90dd42219679fbb7c96fec22e8a64312befde1712f68f001acf4a0e22ac723c60a851431a0921ecdb28a1a1b99a539aa8ab9609201de590a204e019b2a9ed274648f7b9a8bed0df8cbe339098fe850107098de5a8c22a82c13dfd74218a6c4bf5ebca6837015a1a1e5b440c35d05ed1b6b8b67819955efbc0fd6121f25aab01bb4784f0acd1ea12520575721308c6978ad15644ef59ce8756e174f07937d22bef45e097eca09fc56d2081c871556cad4393a576d041d8b9d084ed9db78d2f0a940bfa8cb937c618e42bb6b78edb351d1645d7a528115c0cc15a389d06c00693468cb959a6774c48beef9a6f10a9ea09096218f5927ddca96067a7d123226d0ec9d0e288f8bdcecf1dd9b076b6840b2b8a405d7cc5c51aa09ca4481a75223a7eafa29a63aa2502a46658d5c6e0b98ccf47d4108544fdece0a2e3628b59ee41c6b8760520720a19156588389b9f1c786697f5f5a827d9f56e53aca1cc9f414f1ad9823302f0f4b185b810532d3e25c7f42458fbcdfcb1564e14777acd708e3361d38b294f03339509252f5ce9d3b1913638ed269f3062310ef94375c9a6f9c42764ba31f847ee16ce2c8b639af3bdadf4602a5b9128d2ab0e7158fd2ac16ca3c61f132d6f413f2807c1b2720bafe4bc2b2388501b1f77a0753872bb728ccef09b3c4babf14caa2459fc2383e8b65db8a7fa78279ef89482b04fbf57b62bd00c8364bf0ae479d15026f5be9a4666d6a25ce5ea3cd8f9b92381f1b376563a338dd90fdeac13d51d20846ae9bc8605c8fd63e13dfce9dbcc8e89eeb320a1f6650b5ceb2e2ede81f1539aad7c25b50d0d2215f766112f0c1d92b57ead4014e7f8c0072fed7aa6af75cf897924210ec7750495cb619987f0efb346d469bf8cb5bfaaf018ce8a088d1174071b82b0789ff76b0514c80459119c5cb4e81a445db3e920cf34351dc0dddc0891d207c2ac3337a965826bd8d9060a7f2ba8c70e49d54be0557407f0c584b8b86ff230da6ba97c3ef2e083f30e4c7bbbe05bb781621ad3739547d58b8301ecde8ca184986415a4119695dcbb1b941b6bd9b12402badac6066cfb0796dafb4b543c16c1992943fd8d2f51b0d0d90528d389fd7805b6289d1d9227b91036f1f83b4c16a53e96f16f9f4fe8ee108e8f990fcd1fce02e35aa0f0e8f416c98253209cf1753551d7c392ca67116cc682a2bb3f936b30470509f6b7d4139dc1f167500a589fa93839eb066018264e4dbaa8fe09f83598146e34fefea5cf8b196536dc04544946992ecddc9e620b055f86e50e3b5a0ac064ecb83eda8d961e30975abb4499be7777650b93fa4ec0ce8b592998969c627de6e4359d722db7f36265fbe9b8a7b9c1c67f3ad7334883260846becc1da851297cb4a495c3acb7e095bd469241a18c0a010dcd20a797fd946d6fdd351082a9bfc64a4da2b6046e083344e020ce37188ae7bdf4fc58cc4df45f192b410b9af6210e16c3ff965717d62805d9acbf9d283cd823d20819a6e66d8f9aff3d30f768c25c96feb1625fa7f9f8ccd12c6919dc3f62e48df7f911dad1b7d857296b2679a94b2c3e35f0f0a36610d5615f454646592573919148263ecb4827dbe2cd70f5084b7183f48e0e6c5f48125d307a02892725248e1f271bee208e01d2aaf1fce4b8cd4fcbe6e843352c0f167fd914aedfe86cd124d444ba9e2259abae64eb465e3fcb507a3e566ed7e4be6b78e6347f258ba999d26568ce8be8e14ee68adf02af053c83a518aa6464e73be5fb6518215e0ba487decec8fbf6a94553f74e9c7f4e7381c6382b866970aaa95b986e4184415b8bc9b1a98d50aabd92ba28c73bdb14c65af3a0fd8b7c3718feddff47b18fa252b4a4ab3a3d4e83663199dee78741c2f020bd1bd4950c61c27cbc71680dbd6ff1a9f2e863439c2890c472521b15dc86eef5cdafd614a7011191a87c5dafe611cb20b46eb47c12d4b587c0d5ff0d03735b7e7fdc828fade1e834a8802b76a4990a6b5d4ba6defb4b238753fe56d6bda7aec212e14b185f4db189ca2d4e466ea47bc4163e8559e197e1fe643083697475a422b7db75e05188fc45d68fc2500af8438a010da4b1bd0ef2f25b833bb1a3eeef5eec2ac86f79e24116f03e692b8aaa6fafce1521100d29b39a6cf5d75a92edd2264b4227dd9f59a709c6202165c49d9efe49b2fcab1b7d74e3c402774dddf63178923d6f1bd4576a13a25ef4788ebf5b3d53a842c7c5184963e8e5bb2f315b2bab1100e350ee4a8ea4ef15b876400cbdfdd0ad70bbc610ab1cbd4a02a71606839aea56a3fcc3f6aae7b4471468ad723d19e49f54fdac3a92715522d9d7616bf6247b2fd4484573a72db2a5c3096d81c1da30520f883efd3a71ff798e8c5007f42613d3116e9667922eac1c60275940322e813a1742acde9eb4d8cb1884c145a5f5146974d3e42f73a150a20468a72dcaf0d1d0eb729e300a78a6ab1795a0d924530270add679dc80b381ab9c157cfa20abb15c0074666b775003ab2f159eb3ae1519b9c716e6817ce7c360080273c6b90904cddec25cb5f28a8e292d801621bdcdf00b9d5843ff976167d49eab357ab030014b46d69ad79f7a4ebbaaef03eda9d95c60763d678c48e032b68c55fb2b684596e2909339b074c5a830e8ed2fede9de30a2805310829845ecbbaed46aeb9288c2086887291e04356bc77aa636359170311dbe1b4fc0d4722866be1669f9152e2474c5e5aa821a27b53219545c163ed921348aceb379414fc477b2d35aeb7d715df535b35ee4d6f277d02bfed4ee25e39e7ec2a9d7d4f1de0e7c63dbe0525ffb908fc231100aaeaf06321e3277632d0ac78fd1ecac1f2c1946a62a896cd26693e4535a20cec5c39bd5dfb848346b0e6ed81e78c7ab94a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, { - "tcId": 58, + "tcId": 59, "comment": "100 random bytes are stored raw", "flags": [ "StoreRaw" @@ -1135,7 +1161,7 @@ "inner": "0000000000643eea3f651bd85ffeee3ddec73a59aff968f34c657bbec6ce3c51366232e2d0076b205d77cf949e09d51a439881273bed19ea9e951cbc2a5e1e5cf91f41722977b52f7b1ea8e628496204c9358a07181314ab48a7208f71c5c343847d7b185f76f3375015000000000000" }, { - "tcId": 59, + "tcId": 60, "comment": "an empty chunk is stored raw", "flags": [ "StoreRaw" @@ -1150,7 +1176,7 @@ "inner": "000000000000" }, { - "tcId": 60, + "tcId": 61, "comment": "1 MiB of random data is stored raw", "flags": [ "StoreRaw" @@ -1165,7 +1191,7 @@ "innerLength": 1081344 }, { - "tcId": 61, + "tcId": 62, "comment": "a secret object's text is never compressed", "flags": [ "SecretRaw" @@ -1180,7 +1206,7 @@ "inner": "00000000138854686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e205468652071000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, { - "tcId": 62, + "tcId": 63, "comment": "a secret object's 1 MiB of zeros is never compressed", "flags": [ "SecretRaw" @@ -1199,7 +1225,7 @@ "type": "Decompress", "tests": [ { - "tcId": 63, + "tcId": 64, "comment": "an encoder frame of 3,000 bytes of text", "flags": [ "FrameOk" @@ -1212,7 +1238,7 @@ "plaintext": "54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f766572" }, { - "tcId": 64, + "tcId": 65, "comment": "a raw block of 5 bytes, one-byte content size", "flags": [ "FrameOk" @@ -1225,7 +1251,7 @@ "plaintext": "68656c6c6f" }, { - "tcId": 65, + "tcId": 66, "comment": "an empty raw block, content size 0", "flags": [ "FrameOk" @@ -1238,7 +1264,7 @@ "plaintext": "" }, { - "tcId": 66, + "tcId": 67, "comment": "an RLE block of 300 bytes, two-byte content size", "flags": [ "FrameOk" @@ -1250,19 +1276,6 @@ "expect": "Ok", "plaintext": "616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161" }, - { - "tcId": 67, - "comment": "a window of exactly 2^20 bytes", - "flags": [ - "FrameOk" - ], - "inputs": { - "frame": "28b52ffd80500500000029000068656c6c6f", - "plainLen": 5 - }, - "expect": "Ok", - "plaintext": "68656c6c6f" - }, { "tcId": 68, "comment": "a raw block of exactly 128 KiB, the largest block", @@ -1280,18 +1293,18 @@ }, { "tcId": 69, - "comment": "a compressed block of exactly 128 KiB: raw literals and no sequences", + "comment": "a compressed block of exactly 128 KiB (raw literals, no sequences), then a raw block of 4 bytes", "flags": [ "FrameOk" ], "inputs": { - "frameHead": "28b52ffd8038fcff0100050010ccff1f", + "frameHead": "28b52ffda000000200040010ccff1f", "frameZeros": 131069, - "frameTail": "", - "plainLen": 131068 + "frameTail": "21000000000000", + "plainLen": 131072 }, "expect": "Ok", - "plaintextZeros": 131068 + "plaintextZeros": 131072 }, { "tcId": 70, @@ -1476,30 +1489,68 @@ }, { "tcId": 85, - "comment": "a window of 2^21 bytes", + "comment": "a window descriptor of 2^20 bytes instead of a single segment, which libzstd decodes", "flags": [ "FrameRejected" ], "inputs": { - "frame": "28b52ffd80580500000029000068656c6c6f", + "frame": "28b52ffd80500500000029000068656c6c6f", "plainLen": 5 }, "expect": "Decompress" }, { "tcId": 86, - "comment": "a window of 2^20 + 2^17 bytes", + "comment": "a window descriptor of 2^21 bytes", "flags": [ "FrameRejected" ], "inputs": { - "frame": "28b52ffd80510500000029000068656c6c6f", + "frame": "28b52ffd80580500000029000068656c6c6f", "plainLen": 5 }, "expect": "Decompress" }, { "tcId": 87, + "comment": "one RLE block of 2^20 zeros, over the 128 KiB block maximum, which libzstd decodes in one pass", + "flags": [ + "BlockSize" + ], + "inputs": { + "frame": "28b52ffda00000100003008000", + "plainLen": 1048576 + }, + "expect": "Decompress" + }, + { + "tcId": 88, + "comment": "one raw block of 128 KiB + 1 bytes, which libzstd decodes in one pass", + "flags": [ + "BlockSize" + ], + "inputs": { + "frameHead": "28b52ffda001000200090010", + "frameZeros": 131073, + "frameTail": "", + "plainLen": 131073 + }, + "expect": "Decompress" + }, + { + "tcId": 89, + "comment": "an RLE block of 6 bytes in a frame of 5, larger than the window", + "flags": [ + "BlockSize" + ], + "inputs": { + "frame": "28b52ffd200533000061", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 90, "comment": "a skippable frame alone", "flags": [ "FrameRejected" @@ -1511,7 +1562,7 @@ "expect": "Decompress" }, { - "tcId": 88, + "tcId": 91, "comment": "a skippable frame before the frame", "flags": [ "FrameRejected" @@ -1523,7 +1574,7 @@ "expect": "Decompress" }, { - "tcId": 89, + "tcId": 92, "comment": "a skippable frame after the frame", "flags": [ "FrameRejected" @@ -1535,7 +1586,7 @@ "expect": "Decompress" }, { - "tcId": 90, + "tcId": 93, "comment": "two frames", "flags": [ "FrameRejected" @@ -1547,7 +1598,7 @@ "expect": "Decompress" }, { - "tcId": 91, + "tcId": 94, "comment": "a trailing byte", "flags": [ "FrameRejected" @@ -1559,7 +1610,7 @@ "expect": "Decompress" }, { - "tcId": 92, + "tcId": 95, "comment": "the last byte cut off", "flags": [ "FrameRejected" @@ -1571,7 +1622,43 @@ "expect": "Decompress" }, { - "tcId": 93, + "tcId": 96, + "comment": "the magic number and the descriptor only", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd20", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 97, + "comment": "a two-byte content size cut off after its first byte", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd602c", + "plainLen": 300 + }, + "expect": "Decompress" + }, + { + "tcId": 98, + "comment": "a block header cut off after two bytes", + "flags": [ + "FrameRejected" + ], + "inputs": { + "frame": "28b52ffd20052900", + "plainLen": 5 + }, + "expect": "Decompress" + }, + { + "tcId": 99, "comment": "a wrong magic number", "flags": [ "FrameRejected" @@ -1583,7 +1670,7 @@ "expect": "Decompress" }, { - "tcId": 94, + "tcId": 100, "comment": "no bytes", "flags": [ "FrameRejected" @@ -1600,7 +1687,7 @@ "type": "DataBlobSeal", "tests": [ { - "tcId": 95, + "tcId": 101, "comment": "chunk of a two-chunk object, compressed", "flags": [ "DataBlobSeal", @@ -1624,7 +1711,7 @@ "sealed": "287ea362f315efdc12fbfb7d8268f28b7c94709f99eb97c49e371e0fa89c02249e3c338465906faa4c9d0a8cfb741a3f279b13a4ceb2b67bfef8adf8bcf1a2b3468fcc6cd69882645fc640e9a843d7c2321a5c81abc7d8a1c7a234577ebc312488e0a113120fd7a26f42bd51331a855586871df50d30d34c3640d15d64c42c80860c8a591a4568a054b00eddba31db6b" }, { - "tcId": 96, + "tcId": 102, "comment": "random chunk of a three-chunk object, stored raw", "flags": [ "DataBlobSeal", @@ -1648,7 +1735,7 @@ "sealed": "e9fab955b2d782604a93074495af8b8e52418855058583eafe013ba6c229c10c1eab1ba3bdea26be13ab8e4b986431ea157c92931c7bb60332e268154e774169017868b428f92df8234645d14afa1c95b7f513e0263dd89c96faa07ff2cd4974e3c8c765d2b81aed9f8a549e8691e47c005f3459d6c2bd87fbd7c8a14b043fac87f930b82013d72217b4e39d752cf99c43d7ef006e96f857189af97febc921db3becc426c5557f556715407531e1809a3315a159c3ab4b0102f1d47b16f37b53f48697d3b2caaab2540d55b8e138112c7447d897caf232c777c03ea4559b07aa365828b186aba7d2e3ac086af1553f3a4f8436abf20a736305942cafe1c0e38aee60fdee1bc129728e590fe9a3f678e774022a9dddd502270e6112bc6592c95fe0eb15fb324ee17881967a19d0403a7086374044ca550cb736e1b95207c077a3366ffddf178b2219766b42605b9c8558fd7f40dfe8fb4fee389f0879d88f59046077afbcea4b05dd4884ab0449c9ab0b28cea197134c9058f3abf41697c0b6ea07ef7e102a51d13127c2f10326030b6a94bc3dae020db63e3f6a29552666ee86426e5d4bf54ecddf6b2806de7f9e8aa47f40ef48b47210fc7a441e793e853d733aaee052428ac93d9caaa6a34594d8a2e7ec4b61bdbe3a75ba33fd87bed28c6f390dfd27d1cbc028c26f82744b718159df95225cb709d835d35c27711d779e8f142397c57f3f0a4d540653ad06bb4804d9f0f3017e2d71ea0c95a498b0aa213aa627e04802472d2037e3368e4303584752360636a792aa8a485dd0c0fd5aab44693986f92cd3d98a" }, { - "tcId": 97, + "tcId": 103, "comment": "the one chunk of a single-chunk object", "flags": [ "DataBlobSeal", @@ -1673,7 +1760,7 @@ "sealed": "b26cfb488a1cc111d39e064e86d06960523725b18a8593b85f276a26a89af8abb86cd23304b23be45435518846ff172138d64ac8a95a29422c77d1c8ce1e359d10e66b9f6b521e39b4bce065a207bd7548aea64de6a2f7e1cf48ae638dc8db429a247ede35822a14444ec7d434a60ebcaae477454565c20889861f0b57627c9f0aa5aae0b0ebf370b886c4ab3070f52a" }, { - "tcId": 98, + "tcId": 104, "comment": "chunk of a secret object: raw and a random ID", "flags": [ "DataBlobSeal", @@ -1704,7 +1791,7 @@ "type": "DataBlobOpen", "tests": [ { - "tcId": 99, + "tcId": 105, "comment": "a compressed chunk of a two-chunk object", "flags": [ "DataBlobOpen", @@ -1726,7 +1813,7 @@ "plaintext": "54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f7820" }, { - "tcId": 100, + "tcId": 106, "comment": "a raw chunk of a two-chunk object", "flags": [ "DataBlobOpen", @@ -1748,7 +1835,7 @@ "plaintext": "54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f7820" }, { - "tcId": 101, + "tcId": 107, "comment": "the one chunk of a single-chunk object, random ID", "flags": [ "DataBlobOpen", @@ -1770,7 +1857,7 @@ "plaintext": "8da0f026c0e82cdc7689a2ecebb186e1fb4a008e5c1490e317d354f6a12fe2e310803deb6f4d8cbc89a1204b6e99b7a1496fc4700325b9d3462a2b4653452e97837949aa1280a0894597264a49a0910f8882d373be4d0ab52d952f07b65e2a2bd5c7cc4289c863fd0f09b3d60cc64b0383165b9da3c80ec9fe49b9240230630fb381489b9f86d078b51688b00eef950fb11ac0fb0dc26af0393bf21b9fe72abbe3768921ffe4b1ee134b13af043a8131dbe57c2073c2cc4ba2a470348bacd1c555cdbd69cf8e7179ce209c34f8f024e29db45019515a109138feb8fe12a6271184e691928b2c544be073419e5b6f40fcdbc15888ff456e8dbce62f0c2a509a00ba3eab29f8035a4492ce6e646e0834696e63ff71e06cf72b10ca3787b18930196f40ab35b72bf6cf674cbb0b" }, { - "tcId": 102, + "tcId": 108, "comment": "a chunk of a secret object, random ID", "flags": [ "DataBlobOpen", @@ -1792,7 +1879,7 @@ "plaintext": "54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f672e2054686520717569636b2062726f776e20666f7820" }, { - "tcId": 103, + "tcId": 109, "comment": "sealed under another vault's AAD", "flags": [ "AadBinding" @@ -1812,7 +1899,7 @@ "expect": "Decrypt" }, { - "tcId": 104, + "tcId": 110, "comment": "sealed under another object's AAD", "flags": [ "AadBinding" @@ -1832,7 +1919,7 @@ "expect": "Decrypt" }, { - "tcId": 105, + "tcId": 111, "comment": "sealed under another DEK ID's AAD", "flags": [ "AadBinding" @@ -1852,7 +1939,7 @@ "expect": "Decrypt" }, { - "tcId": 106, + "tcId": 112, "comment": "sealed under another blob ID's AAD", "flags": [ "AadBinding" @@ -1872,7 +1959,7 @@ "expect": "Decrypt" }, { - "tcId": 107, + "tcId": 113, "comment": "sealed with kind byte 0x02", "flags": [ "AadBinding" @@ -1892,7 +1979,7 @@ "expect": "Decrypt" }, { - "tcId": 108, + "tcId": 114, "comment": "sealed under the blob-meta label", "flags": [ "AadBinding" @@ -1912,7 +1999,7 @@ "expect": "Decrypt" }, { - "tcId": 109, + "tcId": 115, "comment": "sealed under another key", "flags": [ "AadBinding" @@ -1932,7 +2019,7 @@ "expect": "Decrypt" }, { - "tcId": 110, + "tcId": 116, "comment": "the blob ID of another chunk", "flags": [ "BlobIdBinding" @@ -1952,7 +2039,7 @@ "expect": "Binding" }, { - "tcId": 111, + "tcId": 117, "comment": "a random blob ID in a two-chunk object", "flags": [ "BlobIdBinding" @@ -1972,7 +2059,7 @@ "expect": "Binding" }, { - "tcId": 112, + "tcId": 118, "comment": "rsv 1", "flags": [ "BlobInner" @@ -1992,7 +2079,7 @@ "expect": "Padding" }, { - "tcId": 113, + "tcId": 119, "comment": "comp 2", "flags": [ "BlobInner" @@ -2012,7 +2099,7 @@ "expect": "Padding" }, { - "tcId": 114, + "tcId": 120, "comment": "a pad byte not zero", "flags": [ "BlobInner" @@ -2032,7 +2119,7 @@ "expect": "Padding" }, { - "tcId": 115, + "tcId": 121, "comment": "one byte past the Padmé length", "flags": [ "BlobInner" @@ -2052,7 +2139,7 @@ "expect": "Padding" }, { - "tcId": 116, + "tcId": 122, "comment": "payload_len 2^20 + 1", "flags": [ "BlobInner" @@ -2072,7 +2159,7 @@ "expect": "Limit" }, { - "tcId": 117, + "tcId": 123, "comment": "a secret object's chunk with comp 1", "flags": [ "SecretRaw" @@ -2092,7 +2179,7 @@ "expect": "Padding" }, { - "tcId": 118, + "tcId": 124, "comment": "a secret object's chunk with comp 1 and a bad frame: comp is checked first", "flags": [ "SecretRaw", @@ -2113,7 +2200,7 @@ "expect": "Padding" }, { - "tcId": 119, + "tcId": 125, "comment": "a frame with a content checksum", "flags": [ "BlobFrame" @@ -2133,7 +2220,7 @@ "expect": "Decompress" }, { - "tcId": 120, + "tcId": 126, "comment": "a frame holding more than it declares", "flags": [ "BlobFrame" @@ -2153,7 +2240,7 @@ "expect": "Decompress" }, { - "tcId": 121, + "tcId": 127, "comment": "plain_len one more than the frame declares", "flags": [ "BlobFrame" @@ -2173,7 +2260,7 @@ "expect": "Decompress" }, { - "tcId": 122, + "tcId": 128, "comment": "a raw payload one byte shorter than plain_len", "flags": [ "BlobFrame" @@ -2193,7 +2280,134 @@ "expect": "Decompress" }, { - "tcId": 123, + "tcId": 129, + "comment": "a raw payload one byte longer than plain_len", + "flags": [ + "BlobFrame" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "50f1306b1bbb6d6ef35ee924bd816b3e866f4c915de8f75f7b6be33d1a4679f3", + "plainLen": 1999, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452324eeca05c2f9e85758226847bc33a14fbe6f39bb65ff4b13f6b641fcfd1beecbc2a3edb9bae4ada756a878be9566cfd074ff0702774d046fc2f11a9587bbed0ea59415c468f614a71b20609c35dc011bd84a0d52682645ca57069fe9d6dd1ec4ae184e7dddb8c95342dac653b527d3b9b03935c149936a0af259cdf27f0481f20da1c0055596934a95fe9ac930da172eb8e8c56b1df67179cda2d438f4df1b0249e0620690b52ee2f2c85344ceb1765e6b8983219e31c4608bf9a8e405d98781e2985a0299d70fb2469658d4570ddeeb42a3ac5d297bc0647b5712bf4a2a426993d56dff9f4479481d0f05c1ecae49488bd79994422832df81df3c939f47b603dc3e05bcb92bc3aee4590b3fa8f955fb30bbc412dff292d54de22b829aab2d504a64c961452c9f75b70c2e782bcc1d1932d865f248557cc58ffb75827ad137d9a658cc7b4951d9981edaa47c231d7779d465597607c7627c37efefd0772ce4ed0506e17944296c50cb771e2585ff124a5d44d406fbc79587ba5d1164356dca96fb0acbf218c14d2966acaff5d0b7fdd99d30f8cedefb4a2cd0b0b28435706a0be8ec51f46f608c2d3325ab45f61f272cea14e5ad1d8cdf10eda3dbcf40bbb1c7d15bdaa68bca9bd11c525c15df6c343fb46faacf8b8cad817f31505f2d415b878d697311f4befb13eae5bc8f87f508d9c6d47f015d1c89cc34958353341a77bd2e0f00452479067718c99659cf38ea7d82e65df82e9fead04e017ce8b41e1a1787c43ea0869c769d982861299d50e3ac94ea2b4c1c15b37653805415626a145a0e842a5f65f649664aaaacac8ba703d679ea2e1256becb03a7b173fbde0e4eba17c6b6ae91da4827884d02e2b6f5f354f78abf4afc3b05464ea731b98b792511ce63a36de91aed63f9e4a1cdb075c8a5359753b26f8ca76f3f3a2940056b94fd478ba3c55a1fd4a46cb0375a893993b4f157fe3e62d9f0532ebe6a64395d080e835bd8e8b6f75e43766efd6ad9a139e347d057e1abdd662ce2c554b02f4d938e8bc80361fa7ff2ce22a85211c8877d3eb5e010b79a0eeda4eaf9f400cccc74fd260ff5668cb12f60afc41b537e2c76c22a90d459055f1e407f09600887c6872aa7140ae6d5e4d3c36d8e82ac16cf9d7b53e2f6812ae73fa9f43a59bc12a2d06729af118f48d88a6fb9ec8d2cc6318bb2c2bf54c8f23aa10efa4eb657ac62d8c34c26488d6fa39608a11e14215f43c1a4dddf04daef2c643d7392d7c9386ac89b4aef66cc83c7458a7e49d56b9d63c75e801ed9e14a1a50a59d868db9daaee7cd1e4d783d13ea242ca156d4ab8aaf14f217080be516d7bae4f4c5510891b870f67ceb1c8e726dd19ad2fe63c64f779425e8c88e943f00c47b195c27ffd50c412319c691e729a0c3c2bb483f0bce4b99e903398ea6ffffd1449bb5090bec1b28228b5260aa22e36b893431e8ec5ccd12aff33ba045c1f549883c7559b4d8f61568ff7bcec486d5e233c8bbc9cf40cf9e3a0a7e1be410fe4707d216150c7bd4719b6c3d8fbcaa7da3f7a634ff09fa6e8e35283efd452eb3f368b1ff5f64738028b52d715d61d56fa0c89bf8fe09120a1e5dc10cc8679cb50c217507f3bee88f5bfc3d65d76e6f04645982baf459353b380b523c6637731a4c86c8c2f9a29b39ffb98a0f809e7d96fc1caf7a9ee654c05ea093cac859ed3eb619da22fc86f5f32619a63a0af117b19be988a59df4f4f17596b3716fbd552083bc166d11675151167766de70f99b2f8e725744ca2b61702a7251d66278852a118d6b059f836f314b1f710e685737b5390ef410aad645933cdbcb9fe2969171c86b2c53f0c594b2e488aa6575f155ca1a5e7cfae9a699baf0469c7af59596046b5ba2cc60fbfb7040f0c17fe2fd6342e8f809a6f60e55f13b8b7c5e8ea960d433b60d7360b6f0d0bdb4c54370ec8ddc1c7acf833dfc85c723e15696ba9e7e50aaaac19785dd09b1bc20899b6496010f53c46fa0afe1beb4523909dbe74ccd82a50837776ba012964d4184f13f23309cd5387e5d17d04a05aebd0297c6ba1faabeb393863ff89e88f94c1de1d9f7722728f61a6ea15746d66eb93b81b2bf21585949c2acb47890b924b5e112dabb8b55e9b859834e0e6f8b16eb955adf031cf9ac7ccae70c66bdf9d4e4da7f0e735a146b15f9b41d1de447b4b53ee4b80ada77d65901213943a7e32b70b596e447d3e4cbf7d90697f1257502f33fdc520d4ced209b859fb6edf2b53fa16cfbfb517d69b3461768da6dc2e419facd292cb4759752c3f5cdca8b5f8112e84805ad1fc049c5d226cc44ec35021d6ba91d1514cafceb1dc9a104fd7d12bc82ccaf90bca0286fe96a7263205380647146c754901042ce58310f08191bb592e39bb8c8bbf00248e5bae4e7aa9cf85fe8c0112bd5f2ce4e6bc56ac4d13bf2ac0b745dfc0ddbd54ba63b2718b3134b1abddf7481dcebe3384d10896996870525cd07bc6c19fc85db4bf4ce2491e5d3365cfd37f82d0452e1eb40fbadf4196532ce8f20ce0c60ab1b3bdc22eed65fc968cf9cad7d51ece382c9c767e89b9116f6ef9a35b68f391c1767cc2245e06c5bf19617066454490613f082da16faae7b073f571e8d0a48539fa186bd15e70ea2ded3c303946fb2bf071420de970e03d1b6a9dd93411f4d5380ffc48cf934f5697ea6f1909125a09eec4c0bcf2c07c3f2532035d83a3e58e4354f374d7f9fd8828511e27f541103a8240ad162c0f591e9e8ccbf88c1ec0c15d5bd789952eeea687c468b783a209d03375d5c598df7fc73f85faeb8e141295456273b416b557269fa9a80644869f004710a7d6df50ab390f526011167ef4f6ba5846aedaefa46c3ff0332b4c7a989d74bba349c91865c2e5269e69252d1f916a01b0451a4a8c268b0e61375a96775ab4562896a08945947033a51a42e80a0cacbfba6f126ba3dd068a4a" + }, + "expect": "Decompress" + }, + { + "tcId": 130, + "comment": "a frame of 45 bytes for 48: exactly 15/16, kept", + "flags": [ + "DataBlobOpen", + "StoreRaw", + "KeyedBlobId" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "5f464ca3da69d1753890724d04a9a682ac62532af855268bfd3a2683ed311577", + "plainLen": 48, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452327e9ef438198afa26f16487ee221c7e8dbebcd2f001d1708ba1399edb81a238b5fbe28153788ce21dda33496c2e6e69a278cf080dcd254d361c65c48622c069aa775ef8b4e320e8dc2bec2dafdb2634dd90265c7695b4bb57d73b684c6b3e821b830080a5" + }, + "expect": "Ok", + "plaintext": "616161616161616161616161616161616262626262626262626262626262626262626262626262626262626262626262" + }, + { + "tcId": 131, + "comment": "a frame of 46 bytes for 49 saves less than 1/16, so a writer stores the chunk raw", + "flags": [ + "StoreRaw" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "4e97caf3dfa49ab6e4674cf9a53bc5091b979b9ccd13e8a5fcd99c6024084de0", + "plainLen": 49, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae845232c0d28b71cdd56d4841e0c24929a927c4ed5167ff2ebfe796dfc7f8c3e6d8ce92572f8c77bea312a5e0b3e96cdc685ff07545b552185324fd0f8535b141f894e84dc80d831bf639964df5e0af38e74673855ea608c19e2ccf1a8aa00b30ccd56962f1d122" + }, + "expect": "Decompress" + }, + { + "tcId": 132, + "comment": "random bytes in a raw-block frame longer than the chunk", + "flags": [ + "StoreRaw" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "d15465efea38d1b6c3e31c9a27fb96e3447508f0be4063e56b4a091ca80b709c", + "plainLen": 300, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae845232be88211035ff792f99a64f0c5b3d337a4827d7293be3ebbed364b28b923ab61a2abe014daa1da996c894430dab42d353860f2b1ec6b6cfa43afcd0580ae9f24514bd729542b4fe90054ee09b59fec0708f56e1b81721dd08db17527043ec2b731991c1dc19281f61e01d2c29d29f34fdd11947ae237f2b6a12ff2c426528b9959807b9d7cf601df2f5fab661be3dab89055237343633aaec394827dee2bf241e14ae6a139c9aed343ab5e2491bcffc5a718ebd54da584892d06c894e788a8d69cce07b43e96144f9ca99a5ab68c3e987406a96745840199deda0cdebc6e02f06fe45fd7a310bf77df39b34c4a8bf936624b009af512e9f47b452ae703dc764a878a6b2b303299aaf1f6535041beaa89882de2fe8ceaecfa95751b7fc5fcb6271b0b3b93171947c326838b0227fb5e399676caca57e6e7f3b053f7471416d430e8741734b590f5574f00147c6303e301c18be7e106302ea7b8e0fd94832db34de1e83c728534923af8691cda27f32b249" + }, + "expect": "Decompress" + }, + { + "tcId": 133, + "comment": "a frame that saves less than 1/16 and a wrong blob ID: the store-raw rule is checked first", + "flags": [ + "StoreRaw", + "CheckOrder" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "45f852ef69e5c3f7413ca7616165b1359d4bfb186d3055b221c841d1cf79fd72", + "plainLen": 49, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae84523250c92442ecff2773d8b9ce6c9ad44da7ae495278f499fb0065d98bb7344c2621ca5b4febb7495f06feccb7b2449f05fccef0c8c736da37b63be248ea8e0f1e23041f5441d05173059d2c5786925b20ba8c958e0e03603e09b3ac0bb788eb3f1b7f2547c8" + }, + "expect": "Decompress" + }, + { + "tcId": 134, + "comment": "plain_len exactly 2^20: a compressed 1 MiB of zeros", + "flags": [ + "DataBlobOpen", + "PlainLenCap", + "KeyedBlobId" + ], + "inputs": { + "dek": "2f92e8f33fc6556ab127c730b62dd86abb300ac4c0783b32ebf3d3825df01f85", + "dekSalt": "66bb72f20ba10b2b83e5c044afc8018512dc90e9d72b9569ee91184f7b72c584", + "vaultId": "a7915da149508b019ac1c22bd7da3605", + "objectId": "10f9c4b4ee5dcbdd89728d0fa99f0edc", + "dekId": "9ce6207e5030ade7b7694f12d7ca37a5", + "class": "ordinary", + "chunkCount": 2, + "blobId": "ee6c1df2b9efba88ef991de3e78c273f55c3ae11c166942e431d889d11fac004", + "plainLen": 1048576, + "sealed": "e326a56f1a9ef9112d0e4fb09e5cb5a7471fee17ae8452322231cfa85666d1b139dd28a59026374a8781ab3e9079a3fc75f6918d2151faeb5e59860af1833210b601fad99fdc2ce18525a5ef0e33afa42d6280bc1a9453ef96290e9cfed4b0a93fb32c15d79e0092c3dd60ee4e1340cfd9c198c051346afe8da47859bba9f6d3" + }, + "expect": "Ok", + "plaintextZeros": 1048576 + }, + { + "tcId": 135, "comment": "a bad frame and a wrong blob ID: the frame is checked first", "flags": [ "BlobFrame", @@ -2214,7 +2428,7 @@ "expect": "Decompress" }, { - "tcId": 124, + "tcId": 136, "comment": "a raw payload one byte shorter than plain_len and a wrong blob ID: the length is checked first", "flags": [ "BlobFrame", @@ -2235,7 +2449,7 @@ "expect": "Decompress" }, { - "tcId": 125, + "tcId": 137, "comment": "plain_len 2^20 + 1 is refused before decryption", "flags": [ "PlainLenCap", @@ -2256,7 +2470,7 @@ "expect": "Decompress" }, { - "tcId": 126, + "tcId": 138, "comment": "71 bytes, one short of a seal", "flags": [ "SealShape" @@ -2276,7 +2490,7 @@ "expect": "Truncated" }, { - "tcId": 127, + "tcId": 139, "comment": "an all-zero nonce", "flags": [ "SealShape" @@ -2301,7 +2515,7 @@ "type": "MetaBlob", "tests": [ { - "tcId": 128, + "tcId": 140, "comment": "a path-index node", "flags": [ "MetaBlob" @@ -2320,7 +2534,7 @@ "sealed": "0b01d8146d9f648722b3aa2da09d15f1da97329803a63293d710da644a7b8d6cab5e04393eee9c9b1ec3a59fe70a2848d0bd5cc381e1b7ba82fed071bef856e05afb73b4dbf0cbd6a8dcdffdf90d96" }, { - "tcId": 129, + "tcId": 141, "comment": "a key-table node", "flags": [ "MetaBlob" @@ -2339,7 +2553,7 @@ "sealed": "0705b4277464dabd018139045e5e569732c44d54910ec90c3405af1adc3607c2434020b8190831462bbff314fb7a4eacc542d8df8026d3306501bdef0a8b73b2c0c82fac1ea52972edec1402b36d6e" }, { - "tcId": 130, + "tcId": 142, "comment": "a location node", "flags": [ "MetaBlob" @@ -2358,7 +2572,7 @@ "sealed": "3c1df3242e9f4383cbc66d04cd5766e3d4b6c55edafde3485b9e475261a0778a25c144d95cd6172f47112278f809725bc6e25b6b64e51a8609724b48576cd366873cb9dca2b2dd548e6d07d6726c64" }, { - "tcId": 131, + "tcId": 143, "comment": "a pack-table node", "flags": [ "MetaBlob" @@ -2377,7 +2591,7 @@ "sealed": "1fb9bbf5f7b026b03bed58826006e1c48a726c7f9867aa282b87cf76f499c13ae0c97053c400b4787e3a0920963091a915de6df9307597536e866fd3bfd66f57d21a3273d6d3fb3c52e1c04f2af3a2" }, { - "tcId": 132, + "tcId": 144, "comment": "a GC-candidate node, under the location key", "flags": [ "MetaBlob" @@ -2396,7 +2610,7 @@ "sealed": "9de0311efdd0fd9dbe8a8274a7975ec1a9d2b8896e4ce8a79730a1ad9a15f749d4236af9abcc3919b08fc0a95cc9ba012eb8ce6d810e9c2e6bb799126007e9a6413e232121ba6b3eab77d7425f136a" }, { - "tcId": 133, + "tcId": 145, "comment": "a location node opens", "flags": [ "MetaBlobOpen" @@ -2413,7 +2627,7 @@ "cbor": "a1014400010203" }, { - "tcId": 134, + "tcId": 146, "comment": "opened as a GC-candidate node: same key, other kind byte", "flags": [ "MetaBlobOpen" @@ -2429,7 +2643,7 @@ "expect": "Decrypt" }, { - "tcId": 135, + "tcId": 147, "comment": "opened under another epoch", "flags": [ "MetaBlobOpen" @@ -2445,7 +2659,7 @@ "expect": "Decrypt" }, { - "tcId": 136, + "tcId": 148, "comment": "opened under another blob ID", "flags": [ "MetaBlobOpen" @@ -2461,7 +2675,7 @@ "expect": "Decrypt" }, { - "tcId": 137, + "tcId": 149, "comment": "opened in another vault", "flags": [ "MetaBlobOpen" @@ -2477,7 +2691,7 @@ "expect": "Decrypt" }, { - "tcId": 138, + "tcId": 150, "comment": "opened with another epoch's KEK", "flags": [ "MetaBlobOpen" @@ -2493,7 +2707,7 @@ "expect": "Decrypt" }, { - "tcId": 139, + "tcId": 151, "comment": "71 bytes, one short of a seal", "flags": [ "SealShape" @@ -2509,7 +2723,7 @@ "expect": "Truncated" }, { - "tcId": 140, + "tcId": 152, "comment": "an all-zero nonce", "flags": [ "SealShape" @@ -2527,5 +2741,5 @@ ] } ], - "numberOfTests": 140 + "numberOfTests": 152 } diff --git a/tests/test-vectors/gen/src/tv07.rs b/tests/test-vectors/gen/src/tv07.rs index 4f792e2..fa87710 100644 --- a/tests/test-vectors/gen/src/tv07.rs +++ b/tests/test-vectors/gen/src/tv07.rs @@ -4,12 +4,14 @@ //! Every output comes from this crate's own code: the one-byte-a-time chunker of [`cdc`], the //! Padmé of [`padme`], the inner plaintexts of [`inner`], hand-built zstd frames and the //! section 7 primitives of [`cx`]. Only the encoder frames come from zstd itself (`zstd-safe`, -//! the version in the header): they are inputs to decompression, which any version must accept, -//! and the expected output of the encoder groups, which only the pinned version must match. +//! the version in the header): they are inputs to decompression, which gives the results FS-53 +//! defines through libzstd 1.5.7, and the expected output of the encoder groups, which only the +//! pinned version must match. //! Inputs too large for hex are given as `dataKey` and `length`, the first `length` bytes of the //! keyed BLAKE3 XOF under `dataKey` over the empty input, as `pattern` and `length`, the //! pattern repeated to `length` bytes, or as `zeros`, a run of zero bytes. A frame with a run of -//! more than 1,024 zero bytes is given as `frameHead`, `frameZeros` zero bytes and `frameTail`. +//! more than 1,024 zero bytes is given as `frameHead`, `frameZeros` zero bytes and `frameTail`, +//! and an all-zero expected plaintext of more than 1,024 bytes as `plaintextZeros`, its length. use crypthix_crypto::test_rng::Stream; @@ -138,7 +140,7 @@ fn chunk_edges( ) -> Vec { use cdc::{AVG, MASK_L, MASK_S, MAX, MIN}; let mut stream = Stream::new(seed, "chunking-edges"); - let bases: [[u8; 32]; 9] = std::array::from_fn(|_| stream.bytes()); + let bases: [[u8; 32]; 10] = std::array::from_fn(|_| stream.bytes()); let matches = |hash: u64, mask: u64| hash & mask == 0; let mut edges = Vec::new(); @@ -260,7 +262,7 @@ fn chunk_edges( "a cut at strict_end - 1" ); edges.push(( - "a strict match at strict_end - 1, the last position tested: a one-byte last chunk", + "a strict match at 2⌊n/2⌋ − 1, the last position tested: a one-byte last chunk", *chunker_seed, *gear, data, @@ -281,6 +283,29 @@ fn chunk_edges( *gear, Big::Pattern(pattern, len), )); + + // Longer than AVG and shorter than MAX, so both masks are used and end = n, with no + // position matching either: the whole file is one chunk. Checked here position by + // position from the hash of the window before it, not only through the chunker. + let len = AVG + MIN; + let key = search(&bases[9], "file with no match below its length", |key| { + (cdc::lengths(gear, &xof(&key, len)) == [len]).then_some(key) + }); + let bytes = xof(&key, len); + for position in MIN..(len & !1) { + let mask = if position < AVG { MASK_S } else { MASK_L }; + let window = &bytes[position.saturating_sub(63).max(MIN)..=position]; + assert!( + !matches(cdc::hash(gear, window), mask), + "a match at {position}" + ); + } + edges.push(( + "320 KiB with no position matching under either mask: one chunk of the whole file, shorter than the maximum", + *chunker_seed, + *gear, + Big::Stream(key, len), + )); edges } @@ -679,6 +704,7 @@ fn decompress_tests() -> Vec { }; let skippable = zstd_frame::skippable(b"skip"); let rle = zstd_frame::rle_frame(b'a', 300); + let rle_head = rle.clone(); let wide_rle = zstd_frame::frame( &Header { fcs_flag: Some(2), @@ -695,18 +721,8 @@ fn decompress_tests() -> Vec { let reserved = zstd_frame::frame(&Header::declaring(5), &[Block::Reserved(b"hello".to_vec())]); let block_zeros = vec![0u8; zstd_frame::MAX_BLOCK]; let max_block = zstd_frame::raw_frame(&block_zeros); - // libzstd up to 1.5.2 refused a compressed block of exactly 128 KiB (zstd's - // decompressor_errata.md); its encoder never writes one, so the block is built by hand, - // with a window of 2^17 bytes, since a block may be no larger than the window. - let literals = vec![0u8; zstd_frame::MAX_BLOCK - 4]; - let max_compressed = zstd_frame::frame( - &Header { - single_segment: false, - window: Header::window_of(17), - ..Header::declaring(literals.len() as u64) - }, - &[Block::Compressed(zstd_frame::literals_only(&literals))], - ); + let over_block = vec![0u8; zstd_frame::MAX_BLOCK + 1]; + let rle_longer = zstd_frame::frame(&Header::declaring(5), &[Block::Rle(b'a', 6)]); #[rustfmt::skip] let cases: Vec = vec![ @@ -714,9 +730,8 @@ fn decompress_tests() -> Vec { ("a raw block of 5 bytes, one-byte content size", "FrameOk", hello.clone(), 5, ok(b"hello")), ("an empty raw block, content size 0", "FrameOk", zstd_frame::raw_frame(b""), 0, ok(b"")), ("an RLE block of 300 bytes, two-byte content size", "FrameOk", rle, 300, ok(&[b'a'; 300])), - ("a window of exactly 2^20 bytes", "FrameOk", windowed(w20), 5, ok(b"hello")), ("a raw block of exactly 128 KiB, the largest block", "FrameOk", max_block, zstd_frame::MAX_BLOCK, ok(&block_zeros)), - ("a compressed block of exactly 128 KiB: raw literals and no sequences", "FrameOk", max_compressed, literals.len(), ok(&literals)), + ("a compressed block of exactly 128 KiB (raw literals, no sequences), then a raw block of 4 bytes", "FrameOk", zstd_frame::max_compressed_block(), zstd_frame::MAX_BLOCK, ok(&block_zeros)), ("plain_len 2^20: eight RLE blocks of zeros", "PlainLenCap", zstd_frame::rle_frame(0, MIB), MIB, ok(&zeros)), ("plain_len 2^20 + 1 is refused before decoding", "PlainLenCap", one_over, MIB + 1, None), ("plain_len one below the declared size", "FrameRejected", hello.clone(), 4, None), @@ -732,14 +747,20 @@ fn decompress_tests() -> Vec { ("a four-byte content size for 5 bytes, which libzstd reads", "FrameRejected", bent(|header| header.fcs_flag = Some(2)), 5, None), ("an eight-byte content size for 5 bytes, which libzstd reads", "FrameRejected", bent(|header| header.fcs_flag = Some(3)), 5, None), ("a four-byte content size for 300 bytes, which libzstd reads", "FrameRejected", wide_rle, 300, None), - ("a window of 2^21 bytes", "FrameRejected", windowed(Header::window_of(21)), 5, None), - ("a window of 2^20 + 2^17 bytes", "FrameRejected", windowed(w20 | 1), 5, None), + ("a window descriptor of 2^20 bytes instead of a single segment, which libzstd decodes", "FrameRejected", windowed(w20), 5, None), + ("a window descriptor of 2^21 bytes", "FrameRejected", windowed(Header::window_of(21)), 5, None), + ("one RLE block of 2^20 zeros, over the 128 KiB block maximum, which libzstd decodes in one pass", "BlockSize", zstd_frame::one_rle_block(MIB), MIB, None), + ("one raw block of 128 KiB + 1 bytes, which libzstd decodes in one pass", "BlockSize", zstd_frame::raw_frame_one_block(&over_block), zstd_frame::MAX_BLOCK + 1, None), + ("an RLE block of 6 bytes in a frame of 5, larger than the window", "BlockSize", rle_longer, 5, None), ("a skippable frame alone", "FrameRejected", skippable.clone(), 0, None), ("a skippable frame before the frame", "FrameRejected", [skippable.as_slice(), &hello].concat(), 5, None), ("a skippable frame after the frame", "FrameRejected", [hello.as_slice(), &skippable].concat(), 5, None), ("two frames", "FrameRejected", [zstd_frame::raw_frame(&b"hello"[..3]), zstd_frame::raw_frame(&b"hello"[3..])].concat(), 3, None), ("a trailing byte", "FrameRejected", [hello.as_slice(), &[0]].concat(), 5, None), ("the last byte cut off", "FrameRejected", hello[..hello.len() - 1].to_vec(), 5, None), + ("the magic number and the descriptor only", "FrameRejected", hello[..5].to_vec(), 5, None), + ("a two-byte content size cut off after its first byte", "FrameRejected", rle_head[..6].to_vec(), 300, None), + ("a block header cut off after two bytes", "FrameRejected", hello[..8].to_vec(), 5, None), ("a wrong magic number", "FrameRejected", wrong_magic, 5, None), ("no bytes", "FrameRejected", Vec::new(), 0, None), ]; @@ -899,6 +920,11 @@ impl Open<'_> { ]); let test = TestCase::new(comment, flags, expect, inputs); match plaintext { + Some(plaintext) + if plaintext.iter().all(|byte| *byte == 0) && plaintext.len() > 1_024 => + { + test.with_outputs(vec![("plaintextZeros", Input::Int(int(plaintext.len())))]) + } Some(plaintext) => test.with_outputs(vec![("plaintext", Input::bytes(plaintext))]), None => test, } @@ -964,6 +990,28 @@ fn data_open_tests(seed: &[u8; 32]) -> Vec { zero_nonce[..24].fill(0); let secret_frame = seal(&random_id, &compressed); let secret_bad_frame = seal(&random_id, &checksum); + let zeros = vec![0u8; MIB]; + let zeros_inner = encode_chunk(&zeros, ORDINARY); + assert_eq!(zeros_inner[0], 1, "zeros are compressed"); + let zeros_id = object.keyed_id(&zeros); + // Frames of an RLE block of 16 bytes and a raw block: 45 bytes for 48 keeps the store-raw + // rule exactly (16 × 45 = 15 × 48); 46 for 49 does not. + let rle_raw = |raw: usize| { + let frame = zstd_frame::frame( + &Header::declaring((16 + raw) as u64), + &[Block::Rle(b'a', 16), Block::Raw(vec![b'b'; raw])], + ); + let plain = [vec![b'a'; 16], vec![b'b'; raw]].concat(); + (inner::inner(1, &frame), plain, frame.len()) + }; + let (edge_inner, edge_plain, edge_len) = rle_raw(32); + assert_eq!((edge_len, edge_plain.len()), (45, 48)); + let edge_id = object.keyed_id(&edge_plain); + let (past_inner, past_plain, past_len) = rle_raw(33); + assert_eq!((past_len, past_plain.len()), (46, 49)); + let past_id = object.keyed_id(&past_plain); + let raw_framed = inner::inner(1, &zstd_frame::raw_frame(&random)); + let random_keyed = object.keyed_id(&random); let ok = Some(chunk.as_slice()); let data_open = "DataBlobOpen"; @@ -993,6 +1041,12 @@ fn data_open_tests(seed: &[u8; 32]) -> Vec { keyed(&over_declared).case("a frame holding more than it declares", &["BlobFrame"], "Decompress", None), open(ORDINARY, 2, id, chunk.len() + 1, good.clone()).case("plain_len one more than the frame declares", &["BlobFrame"], "Decompress", None), open(ORDINARY, 2, id, chunk.len() + 1, seal(&id, &raw)).case("a raw payload one byte shorter than plain_len", &["BlobFrame"], "Decompress", None), + open(ORDINARY, 2, id, chunk.len() - 1, seal(&id, &raw)).case("a raw payload one byte longer than plain_len", &["BlobFrame"], "Decompress", None), + open(ORDINARY, 2, edge_id, 48, seal(&edge_id, &edge_inner)).case("a frame of 45 bytes for 48: exactly 15/16, kept", &[data_open, "StoreRaw", "KeyedBlobId"], "Ok", Some(&edge_plain)), + open(ORDINARY, 2, past_id, 49, seal(&past_id, &past_inner)).case("a frame of 46 bytes for 49 saves less than 1/16, so a writer stores the chunk raw", &["StoreRaw"], "Decompress", None), + open(ORDINARY, 2, random_keyed, 300, seal(&random_keyed, &raw_framed)).case("random bytes in a raw-block frame longer than the chunk", &["StoreRaw"], "Decompress", None), + open(ORDINARY, 2, other_id, 49, seal(&other_id, &past_inner)).case("a frame that saves less than 1/16 and a wrong blob ID: the store-raw rule is checked first", &["StoreRaw", "CheckOrder"], "Decompress", None), + open(ORDINARY, 2, zeros_id, MIB, seal(&zeros_id, &zeros_inner)).case("plain_len exactly 2^20: a compressed 1 MiB of zeros", &[data_open, "PlainLenCap", "KeyedBlobId"], "Ok", Some(&zeros)), open(ORDINARY, 2, other_id, chunk.len(), seal(&other_id, &checksum)).case("a bad frame and a wrong blob ID: the frame is checked first", &["BlobFrame", "CheckOrder"], "Decompress", None), open(ORDINARY, 2, other_id, chunk.len() + 1, seal(&other_id, &raw)).case("a raw payload one byte shorter than plain_len and a wrong blob ID: the length is checked first", &["BlobFrame", "CheckOrder"], "Decompress", None), open(ORDINARY, 2, id, MIB + 1, seal(&id, &frame)).case("plain_len 2^20 + 1 is refused before decryption", &["PlainLenCap", "CheckOrder"], "Decompress", None), @@ -1157,7 +1211,7 @@ fn notes() -> Vec<(&'static str, &'static [&'static str], &'static str)> { ( "CutEdges", &["FS-52", "M-39", "T-84"], - "Files found by search so a cut sits on an edge of the rule: at the minimum and one past it, at the switch from the strict to the loose mask (a loose-only match at 2⌊center/2⌋ cuts, one at 2⌊center/2⌋ − 1 does not), at the last position tested, an odd last byte that would match if it were tested, and a repeated pattern that is cut only at the maximum. The generator checks each with its one-byte chunker.", + "Files found by search so a cut sits on an edge of the rule: at the minimum and one past it, at the switch from the strict to the loose mask (a loose-only match at 2⌊center/2⌋ cuts, one at 2⌊center/2⌋ − 1 does not), at the last position tested, an odd last byte that would match if it were tested, a repeated pattern that is cut only at the maximum, and a file between the average and the maximum where no position matches, so it is one chunk. The generator checks each with its one-byte chunker.", ), ( "KeyedGear", @@ -1197,12 +1251,12 @@ fn notes() -> Vec<(&'static str, &'static [&'static str], &'static str)> { ( "Compress", &["FS-53", "T-40"], - "One zstd frame at level 3 with its content size, no checksum, no dictionary ID, window ≤ 2^20; equal output is only expected from the zstd version in the header.", + "One single-segment zstd frame at level 3 with its content size, no checksum, no dictionary ID and window_log 20; equal output is only expected from the zstd version in the header.", ), ( "StoreRaw", - &["FS-53", "T-40"], - "The frame is kept only if 16 × frame ≤ 15 × chunk; otherwise the chunk is stored with comp 0.", + &["FS-53", "FS-56", "T-40"], + "The frame is kept only if 16 × frame ≤ 15 × chunk; otherwise the chunk is stored with comp 0. A reader refuses a comp 1 payload that breaks the rule as Decompress, before its frame is checked, so each chunk has one encoding.", ), ( "SecretRaw", @@ -1212,12 +1266,17 @@ fn notes() -> Vec<(&'static str, &'static [&'static str], &'static str)> { ( "FrameOk", &["FS-53", "T-39"], - "Frames FS-53 allows decode to exactly plain_len bytes with any zstd version; raw and RLE frames are built by hand.", + "Frames FS-53 allows decode to exactly plain_len bytes, as libzstd 1.5.7 decodes them; a reader on another decoder must give the same results, and crypthix-core's own Decompressor requires 1.5.7. Raw, RLE and literals-only frames are built by hand.", ), ( "FrameRejected", &["FS-53", "T-39"], - "A frame that is not exactly one frame with content size plain_len in the shortest field that holds it, no checksum, no dictionary ID, the unused and reserved bits clear and a window ≤ 2^20, or whose content differs from its declaration, is Decompress.", + "A frame that is not exactly one single-segment frame with content size plain_len in the shortest field that holds it, no checksum, no dictionary ID and the unused and reserved bits clear, that is cut off, or whose content differs from its declaration, is Decompress.", + ), + ( + "BlockSize", + &["FS-53", "T-39"], + "A block larger than min(window, 128 KiB), where a single segment's window is plain_len and an RLE block counts the bytes it regenerates, is Decompress, though libzstd 1.5.7 decodes such a frame in one pass.", ), ( "PlainLenCap", @@ -1262,7 +1321,7 @@ fn notes() -> Vec<(&'static str, &'static [&'static str], &'static str)> { ( "BlobFrame", &["FS-53", "T-39"], - "A data blob whose payload does not decode to exactly plain_len bytes is Decompress.", + "A data blob whose payload is not exactly plain_len bytes when raw, or does not decode to exactly plain_len bytes when compressed, is Decompress.", ), ( "SealShape", diff --git a/tests/test-vectors/gen/src/zstd_frame.rs b/tests/test-vectors/gen/src/zstd_frame.rs index 734c222..539efbf 100644 --- a/tests/test-vectors/gen/src/zstd_frame.rs +++ b/tests/test-vectors/gen/src/zstd_frame.rs @@ -228,6 +228,34 @@ pub(crate) fn version() -> &'static str { zstd_safe::version_string() } +/// A single-segment frame of 2^17 bytes: one compressed block of exactly 128 KiB, the block +/// maximum, holding 2^17 − 4 zero bytes as raw literals, then a raw block of 4 zeros. The +/// encoder never writes such a block, and libzstd up to 1.5.2 refused it (zstd's +/// `decompressor_errata.md`); the raw block brings the content, and so the window, to 128 KiB. +pub(crate) fn max_compressed_block() -> Vec { + let literals = vec![0; MAX_BLOCK - 4]; + frame( + &Header::declaring(MAX_BLOCK as u64), + &[ + Block::Compressed(literals_only(&literals)), + Block::Raw(vec![0; 4]), + ], + ) +} + +/// A single-segment frame of one RLE block of `len` zero bytes, however long. +pub(crate) fn one_rle_block(len: usize) -> Vec { + frame(&Header::declaring(len as u64), &[Block::Rle(0, len)]) +} + +/// A single-segment frame of one raw block holding `content`, however long. +pub(crate) fn raw_frame_one_block(content: &[u8]) -> Vec { + frame( + &Header::declaring(content.len() as u64), + &[Block::Raw(content.to_vec())], + ) +} + #[cfg(test)] mod tests { use super::*; @@ -278,23 +306,32 @@ mod tests { let raw = raw_frame(&vec![7; MAX_BLOCK]); assert_eq!(raw.len(), 4 + 1 + 4 + 3 + MAX_BLOCK, "one raw block"); assert_eq!(decode(&raw, MAX_BLOCK), Ok(vec![7; MAX_BLOCK])); - let literals = vec![7; MAX_BLOCK - 4]; - let content = literals_only(&literals); - assert_eq!(content.len(), MAX_BLOCK); - let header = Header { - single_segment: false, - window: Header::window_of(17), - ..Header::declaring(literals.len() as u64) - }; - let compressed = frame(&header, &[Block::Compressed(content)]); - assert_eq!(decode(&compressed, literals.len()), Ok(literals.clone())); - // The block may be no larger than the window: here 2^17 bytes. With a single segment the - // window is the content size, 4 bytes smaller than the block, and zstd refuses it. - let single = frame( + let compressed = max_compressed_block(); + assert_eq!(decode(&compressed, MAX_BLOCK), Ok(vec![0; MAX_BLOCK])); + // The block may be no larger than the window, which in a single segment is the content + // size: without the raw block after it, the content is 4 bytes smaller than the block, + // and zstd refuses it. + let literals = vec![0; MAX_BLOCK - 4]; + let alone = frame( &Header::declaring(literals.len() as u64), &[Block::Compressed(literals_only(&literals))], ); - assert!(decode(&single, literals.len()).is_err()); + assert!(decode(&alone, literals.len()).is_err()); + } + + #[test] + fn libzstd_decodes_blocks_over_the_maximum_in_one_pass() { + // RFC 8878 caps a block at min(window, 128 KiB); libzstd 1.5.7 checks it only on its + // block-by-block path, so FS-53 checks it before decoding. + assert_eq!( + decode(&one_rle_block(1 << 20), 1 << 20), + Ok(vec![0; 1 << 20]) + ); + let over = raw_frame_one_block(&vec![0; MAX_BLOCK + 1]); + assert_eq!(decode(&over, MAX_BLOCK + 1), Ok(vec![0; MAX_BLOCK + 1])); + // One RLE block longer than the window, which is the content size: refused anyway. + let longer = frame(&Header::declaring(5), &[Block::Rle(b'a', 6)]); + assert!(decode(&longer, 5).is_err()); } #[test] From c523936c85b01b7bb03b7aced98c87615667e3d3 Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 21:57:08 +0530 Subject: [PATCH 12/15] test(fuzz): per-target seed minimums, a spec-literal chunker oracle and stricter blob and frame oracles --- tests/README.md | 4 +- tests/fuzz/harness/Cargo.toml | 2 +- tests/fuzz/harness/src/chunker.rs | 63 ++++++++++++++++++-- tests/fuzz/harness/src/data_blob_open.rs | 70 +++++++++------------- tests/fuzz/harness/src/decompress.rs | 74 ++++++++++++++---------- tests/fuzz/harness/tests/replay.rs | 41 +++++++++++++ 6 files changed, 175 insertions(+), 79 deletions(-) diff --git a/tests/README.md b/tests/README.md index 69d3e20..f34b948 100644 --- a/tests/README.md +++ b/tests/README.md @@ -9,7 +9,7 @@ Cross-crate tests and test tooling live here. Unit tests stay inside each crate, | `integration/` | Cross-crate tests (from Phase 1) | | `bench/`, `demo/` | MVP benchmarks against gocryptfs and the scripted demo (Phase 2) | -`tests/Cargo.toml` makes this folder its own Cargo workspace, outside the main one. That keeps cargo-fuzz's nightly toolchain and C++ libFuzzer out of normal builds, and keeps the `test-rng` and `vectors` features of `crypthix-crypto`, which the generator and the fuzz harness use, from being unified into a release build (format spec FS-01; `cargo xtask check-features` guards the main workspace). Its lints copy the root `[workspace.lints]`; keep the two in sync. `tests/deny.toml` is the root `deny.toml` plus the two licence exceptions only test tooling needs (libFuzzer's NCSA, minicbor's Blue Oak); a test keeps the two files in sync. The generator is the one crate besides `crypthix-crypto` that may use `blake3`, `hkdf`, `sha2` and `chacha20poly1305` directly: it reimplements format spec section 7 to compute TV-04 and TV-05 independently. With `crypthix-core` and the fuzz harness it is also one of the three crates that may use `zstd-safe`: TV-07 builds its frames by hand and takes only encoder output from zstd. +`tests/Cargo.toml` makes this folder its own Cargo workspace, outside the main one. That keeps cargo-fuzz's nightly toolchain and C++ libFuzzer out of normal builds, and keeps the `test-rng` and `vectors` features of `crypthix-crypto` and the `vectors` feature of `crypthix-core`, which the generator and the fuzz harness use, from being unified into a release build (format spec FS-01; `cargo xtask check-features` guards the main workspace). Its lints copy the root `[workspace.lints]`; keep the two in sync. `tests/deny.toml` is the root `deny.toml` plus the two licence exceptions only test tooling needs (libFuzzer's NCSA, minicbor's Blue Oak); a test keeps the two files in sync. The generator is the one crate besides `crypthix-crypto` that may use `blake3`, `hkdf`, `sha2` and `chacha20poly1305` directly: it reimplements format spec section 7 to compute TV-04 and TV-05 independently. With `crypthix-core` and the fuzz harness it is also one of the three crates that may use `zstd-safe`: TV-07 builds its frames by hand and takes only encoder output from zstd. ```bash cargo xtask test-extra # on stable: vector check, schema, external vectors, fuzz replay, cargo-deny @@ -20,7 +20,7 @@ cargo xtask fuzz cbor_differential --time 60 # fuzz one target on nightly, or ` ## Fuzzing -Targets: `preamble`, `cbor_document`, `cbor_differential`, `cbor_structured`, `store_key`, `config_toml`, `id_text`, `cx_open` (CX-AEAD open never accepts arbitrary bytes, a seal round-trips, and a flipped byte fails the commitment or the tag check that owns its region) `verifying_key` (key parsing and strict verification compared with a second reading of FS-14 on curve25519-dalek and `verify_strict`), `inner_plaintext` (an accepted inner plaintext re-encodes to itself; only `Padding`, or `Limit` exactly for a well-formed header over 1 MiB), `decompress` (a 3-byte `plain_len`, then a frame: accepted exactly when it is one FS-53 frame that zstd's one-shot decoder turns into the same `plain_len` bytes; only `Decompress`), `data_blob_open` (arbitrary bytes only fail to decrypt; the input sealed as an inner plaintext under the blob's own key and AAD gets the result its stages give alone, in the order of FS-93, so a frame error or a payload of the wrong length comes before a wrong blob ID; a written chunk opens to itself and fails with a flipped byte) and `chunker` (a file of up to 2.25 MiB, past two maximum chunks, a keyed stream with the input's tail XOR-ed over all of it, repeated, so every input byte reaches the hash at every cut point, cut in memory, through a reader with input-chosen read sizes and interruptions, and by `fastcdc::v2020::cut_gear` 5.0.0 with the same gear table, which must all agree, and cut again as a secret-class object, which must give fixed 1 MiB chunks; then the tail alone the same ways at the scaled-down sizes 64, 256 and 1,024 bytes through `crypthix-core`'s hidden `scaled_for_fuzzing` constructors, where a few KiB of input reach every edge of the cut rule). `cargo xtask fuzz` needs cargo-fuzz (`cargo install cargo-fuzz --locked`) and a nightly toolchain (`rustup toolchain install nightly`; set `CRYPTHIX_FUZZ_TOOLCHAIN` to pin another). It writes every vector input into `fuzz/corpus//` as a seed, reads `fuzz/regressions//` as a second corpus, and runs with the dictionaries in `fuzz/dicts/`. Builds are optimised but keep debug assertions and overflow checks (`-O -a`), with a 10 s timeout and a 64 MB allocation limit per input, so a parser that allocates for a declared length before checking it fails (FS-11). Fuzzing is supported on Linux and macOS; on Windows it is best effort. +Targets: `preamble`, `cbor_document`, `cbor_differential`, `cbor_structured`, `store_key`, `config_toml`, `id_text`, `cx_open` (CX-AEAD open never accepts arbitrary bytes, a seal round-trips, and a flipped byte fails the commitment or the tag check that owns its region), `verifying_key` (key parsing and strict verification compared with a second reading of FS-14 on curve25519-dalek and `verify_strict`), `inner_plaintext` (an accepted inner plaintext re-encodes to itself; only `Padding`, or `Limit` exactly for a well-formed header over 1 MiB), `decompress` (a 3-byte `plain_len`, then a frame: accepted exactly when it is one FS-53 frame that zstd's one-shot decoder turns into the same `plain_len` bytes; only `Decompress`), `data_blob_open` (arbitrary bytes only fail to decrypt; the input sealed as an inner plaintext under the blob's own key and AAD gets the result its stages give alone, in the order of FS-93, so a frame error or a payload of the wrong length comes before a wrong blob ID; a written chunk opens to itself and fails with a flipped byte) and `chunker` (a file of up to 2.25 MiB, past two maximum chunks, a keyed stream with the input's tail XOR-ed over all of it, repeated, so every input byte reaches the hash at every cut point, cut in memory, through a reader with input-chosen read sizes and interruptions, and by `fastcdc::v2020::cut_gear` 5.0.0 with the same gear table, which must all agree, and cut again as a secret-class object, which must give fixed 1 MiB chunks; then the tail alone the same ways at the scaled-down sizes 64, 256 and 1,024 bytes through `crypthix-core`'s `scaled_for_fuzzing` constructors, which only its test-only `vectors` feature exposes, where a few KiB of input reach every edge of the cut rule). `cargo xtask fuzz` needs cargo-fuzz (`cargo install cargo-fuzz --locked`) and a nightly toolchain (`rustup toolchain install nightly`; set `CRYPTHIX_FUZZ_TOOLCHAIN` to pin another). It writes every vector input into `fuzz/corpus//` as a seed, reads `fuzz/regressions//` as a second corpus, and runs with the dictionaries in `fuzz/dicts/`. Builds are optimised but keep debug assertions and overflow checks (`-O -a`), with a 10 s timeout and a 64 MB allocation limit per input, so a parser that allocates for a declared length before checking it fails (FS-11). Inputs are at most 4096 bytes, except for `preamble` and `data_blob_open` (8 KiB) and `decompress` (144 KiB, for frames that reach zstd's 128 KiB block edges); libFuzzer cuts longer corpus files short, so `cargo xtask fuzz` fails if a seed is longer than its target's limit (`max_len` in `xtask/src/side.rs`). The stable replay test pins the fewest seeds the vectors give each target, so a generator change that stops feeding one fails it. Fuzzing is supported on Linux and macOS; on Windows it is best effort. Of the fuzz data folders, only `fuzz/dicts/` and `fuzz/regressions/` are tracked; `corpus/`, `artifacts/` and `coverage/` are local. When a target fails: diff --git a/tests/fuzz/harness/Cargo.toml b/tests/fuzz/harness/Cargo.toml index 8cfded9..2fd8c24 100644 --- a/tests/fuzz/harness/Cargo.toml +++ b/tests/fuzz/harness/Cargo.toml @@ -10,7 +10,7 @@ publish.workspace = true [dependencies] arbitrary = "1.5.0" -crypthix-core = { version = "0.0.0", path = "../../../crates/engine/core" } +crypthix-core = { version = "0.0.0", path = "../../../crates/engine/core", features = ["vectors"] } crypthix-crypto = { path = "../../../crates/foundation/crypto", features = ["vectors"] } crypthix-types = { version = "0.0.0", path = "../../../crates/foundation/types" } curve25519-dalek = { version = "5.0.0", default-features = false } diff --git a/tests/fuzz/harness/src/chunker.rs b/tests/fuzz/harness/src/chunker.rs index ef00944..0e420d4 100644 --- a/tests/fuzz/harness/src/chunker.rs +++ b/tests/fuzz/harness/src/chunker.rs @@ -29,7 +29,11 @@ //! Every file is cut for both classes. For an ordinary object, the chunks [`Chunks`] cuts in //! memory must be the chunks [`StreamChunker`] cuts through the reader, and the chunks //! `fastcdc::v2020::cut_gear` 5.0.0 cuts with the same gear table, which this file rebuilds -//! from `chunker_seed` and the vault ID with the crypto crate's KDF and XOF. For a secret-class +//! from `chunker_seed` and the vault ID with the crypto crate's KDF and XOF. fastcdc takes two +//! bytes per step with a shifted table and shifted masks, as `crypthix-core` does, so a mistake +//! the two share would pass; at the scaled-down sizes the chunks must also be those of the +//! FS-52 rule taken literally, one byte per step, as written out here. (The vector generator +//! has such a chunker too, but only at format 0 sizes and only as a dev-dependency here.) For a secret-class //! object, memory and the reader must both give chunks of the maximum and a shorter last one //! (FS-52). @@ -163,6 +167,46 @@ fn fastcdc_lengths(words: &[u64], data: &[u8], scale: Scale) -> Vec { lengths } +/// The chunk lengths of `data` under the cut rule of FS-52 read literally, one byte per step: +/// the second oracle, beside fastcdc, which steps two bytes at a time with a shifted table and +/// shifted masks as `crypthix-core` does. Written from the rule's text, not from either. +fn one_byte_lengths(words: &[u64], data: &[u8], scale: Scale) -> Vec { + let mut lengths = Vec::new(); + let mut rest = data; + while !rest.is_empty() { + let n = rest.len(); + // 1. No longer than the minimum: the chunk is all of it. + let len = if n <= scale.min { + n + } else { + // 2. end = min(n, max), center = min(n, avg), h = 0. + let end = n.min(scale.max); + let center = n.min(scale.avg); + let mut h: u64 = 0; + // 4. If no position matches, the chunk is the first `end` bytes. + let mut cut = end; + // 3. Positions 2⌊min/2⌋ up to but not including 2⌊end/2⌋; the strict mask while + // i < 2⌊center/2⌋, the loose one after; a match cuts just before byte i. + for i in 2 * (scale.min / 2)..2 * (end / 2) { + h = (h << 1).wrapping_add(words[usize::from(rest[i])]); + let mask = if i < 2 * (center / 2) { + scale.mask_s + } else { + scale.mask_l + }; + if h & mask == 0 { + cut = i; + break; + } + } + cut + }; + lengths.push(len); + rest = &rest[len..]; + } + lengths +} + /// Cuts `file` for an object of `class` at `scale` in memory and through a reader, checks that /// the two agree and that the chunks cover the file within the size bounds, and returns the /// lengths. @@ -198,7 +242,11 @@ fn cut_both_ways( in_memory.push(range.len()); } assert_eq!(shape.class(), class, "the shape's class"); - assert_eq!(shape.is_single(), in_memory.len() <= 1, "the shape"); + assert_eq!( + (shape.is_empty(), shape.is_single()), + (in_memory.is_empty(), in_memory.len() == 1), + "the shape" + ); assert_eq!( in_memory.iter().sum::(), @@ -256,7 +304,7 @@ fn cut_both_ways( } /// Cuts `file` at `scale` for both classes, in memory and through a reader, and the ordinary -/// class with fastcdc too. +/// class with fastcdc too, and at the scaled-down sizes with the one-byte rule of FS-52. fn check(gear: &GearTable, words: &[u64], file: &[u8], sizes: [u8; 4], scale: Scale) { let in_memory = cut_both_ways(gear, ObjectClass::Ordinary, file, sizes, scale); let secret = cut_both_ways(gear, ObjectClass::Secret, file, sizes, scale); @@ -273,6 +321,13 @@ fn check(gear: &GearTable, words: &[u64], file: &[u8], sizes: [u8; 4], scale: Sc in_memory, "fastcdc 5.0.0 cuts other chunks with the same gear table" ); + if !scale.full { + assert_eq!( + one_byte_lengths(words, file, scale), + in_memory, + "the FS-52 rule taken one byte per step cuts other chunks" + ); + } } /// Cuts the file `data` describes in memory, through a reader, and with fastcdc, then the @@ -280,7 +335,7 @@ fn check(gear: &GearTable, words: &[u64], file: &[u8], sizes: [u8; 4], scale: Sc /// /// # Panics /// -/// If the three disagree, a chunk other than the last is outside the minimum to the maximum, +/// If the chunkers disagree, a chunk other than the last is outside the minimum to the maximum, /// the stream's chunk indices, `is_last` or shape are wrong, the chunks do not rebuild the file, /// or a secret-class object is not cut at fixed steps of the maximum. pub fn chunker(data: &[u8]) { diff --git a/tests/fuzz/harness/src/data_blob_open.rs b/tests/fuzz/harness/src/data_blob_open.rs index 01b068c..8158d77 100644 --- a/tests/fuzz/harness/src/data_blob_open.rs +++ b/tests/fuzz/harness/src/data_blob_open.rs @@ -9,10 +9,10 @@ use std::cell::RefCell; use crypthix_core::blob::{ - BlobContext, ChunkEntry, ChunkKeys, ObjectClass, ObjectOpener, ObjectSealer, data_blob_aad, + self, BlobContext, ChunkEntry, ChunkKeys, ObjectClass, ObjectOpener, ObjectSealer, }; -use crypthix_core::chunk::{Chunks, GearTable, ObjectShape}; -use crypthix_core::compress::{Compressor, Decompressor}; +use crypthix_core::chunk::ChunkRef; +use crypthix_core::compress::{self, Compressor, Decompressor}; use crypthix_core::error::ReadError; use crypthix_core::inner::{self, Comp}; use crypthix_core::limits::{MAX_CHUNK, MAX_PLAIN_LEN}; @@ -25,37 +25,6 @@ use crypthix_types::id::{BlobId, DekId, ObjectId, VaultId}; thread_local! { static COMPRESSOR: RefCell = RefCell::new(Compressor::new().expect("a zstd context")); static DECOMPRESSOR: RefCell = RefCell::new(Decompressor::new()); - /// The shapes the chunker gives an ordinary and a secret object of two or more chunks. - static MULTIPLE: [ObjectShape; 2] = shapes(MAX_CHUNK + 1); - /// The shapes the chunker gives an ordinary and a secret object of one chunk. - static SINGLE: [ObjectShape; 2] = shapes(1); -} - -/// The shapes the chunker gives `len` zero bytes in an ordinary and in a secret object; only -/// the chunker makes shapes. -fn shapes(len: usize) -> [ObjectShape; 2] { - let seed = KdfKey::from_bytes([1; 32]).expect("non-zero key"); - let vault_id = VaultId::try_from_bytes([1; 16]).expect("non-zero ID"); - let gear = GearTable::derive(&seed, &vault_id).expect("derives"); - let zeros = vec![0; len]; - [ObjectClass::Ordinary, ObjectClass::Secret] - .map(|class| Chunks::new(&gear, class, &zeros).object_shape()) -} - -/// The shape of an object of `class` and `count` chunks. -fn shape_of(class: ObjectClass, count: u64) -> ObjectShape { - let index = usize::from(class == ObjectClass::Secret); - let shape = if count == 1 { - SINGLE.with(|shapes| shapes[index]) - } else { - MULTIPLE.with(|shapes| shapes[index]) - }; - assert_eq!( - (shape.class(), shape.is_single()), - (class, count == 1), - "the chunker's shape of {count} chunks" - ); - shape } /// The fixed nonce the target seals inner plaintexts with; never all zero (FS-03). @@ -91,9 +60,9 @@ fn open( /// /// If arbitrary bytes open or fail with anything but `Truncated`, `ZeroValue` or `Decrypt` at /// the right lengths, `plain_len` over 1 MiB is not refused first, a sealed inner plaintext -/// gives another result than its stages give alone (the payload against `plain_len` before -/// the blob ID among them), or a written chunk does not open to itself or opens with a byte -/// flipped. +/// gives another result than its stages give alone (the store-raw rule before the frame, and +/// the payload against `plain_len`, one more or one less, before the blob ID among them), or a +/// written chunk does not open to itself or opens with a byte flipped. pub fn data_blob_open(data: &[u8]) { let context = BlobContext::new( VaultId::try_from_bytes([1; 16]).expect("non-zero ID"), @@ -128,11 +97,11 @@ pub fn data_blob_open(data: &[u8]) { } /// `data` as an inner plaintext sealed under its blob's own key and AAD: the result must be -/// what the inner-plaintext check, the class rule, the decompressor and the blob-ID check say -/// on their own (FS-93 order). +/// what the inner-plaintext check, the class rule, the store-raw rule, the decompressor and the +/// blob-ID check say on their own (FS-93 order). fn sealed_inner(keys: &ChunkKeys, data: &[u8]) { let seal = |blob_id: &BlobId| { - let aad = data_blob_aad(keys.context(), blob_id); + let aad = blob::data_blob_aad(keys.context(), blob_id); cx_aead::seal_with_nonce(keys.chunk_key(), &aad, data, &NONCE) }; let view = match inner::decode_inner(data) { @@ -165,7 +134,12 @@ fn sealed_inner(keys: &ChunkKeys, data: &[u8]) { ReadError::Format(error) => error, other => panic!("decompression gave {other:?}"), }); - (decoded, declared) + // The store-raw rule comes before the frame (FS-53, FS-56). + if compress::keep_compressed(frame.len() as u64, declared) { + (decoded, declared) + } else { + (Err(FormatError::Decompress), declared) + } } other => panic!("decode_inner gave an unknown {other:?}"), }; @@ -198,6 +172,14 @@ fn sealed_inner(keys: &ChunkKeys, data: &[u8]) { Err(FormatError::Binding), "a chunk that does not MAC to its blob ID" ); + if let Some(shorter_len) = plain_len.checked_sub(1) { + let shorter = ChunkEntry::new(right, shorter_len); + assert_eq!( + open(keys, keyed, &shorter, &seal(&right)), + Err(FormatError::Decompress), + "a chunk longer than plain_len" + ); + } let longer = ChunkEntry::new(right, plain_len + 1); assert_eq!( open(keys, keyed, &longer, &seal(&right)), @@ -232,9 +214,11 @@ fn round_trip(keys: &ChunkKeys, data: &[u8]) { (ObjectClass::Ordinary, 1), (ObjectClass::Secret, 3), ] { - let writer = ObjectSealer::new(keys, shape_of(class, count)); + // The chunk as chunk 0 of an object of `count` chunks, the last only if there is one. + let first = ChunkRef::from_parts(chunk, 0, count == 1, class); + let mut writer = ObjectSealer::new(keys, first.object_shape()); let sealed = COMPRESSOR - .with_borrow_mut(|compressor| writer.seal(compressor, chunk)) + .with_borrow_mut(|compressor| writer.seal(compressor, first)) .expect("seals"); let opened = open(keys, (class, count), sealed.entry(), sealed.sealed()); assert_eq!( diff --git a/tests/fuzz/harness/src/decompress.rs b/tests/fuzz/harness/src/decompress.rs index 0638fac..0c12e3b 100644 --- a/tests/fuzz/harness/src/decompress.rs +++ b/tests/fuzz/harness/src/decompress.rs @@ -2,8 +2,9 @@ //! //! The input is a `plain_len` as a 24-bit big-endian number, then the frame. The decoder's //! answer is compared with zstd's one-shot decoder and with this file's own reading of the -//! frame header: it must accept exactly the frames that are one FS-53 frame declaring -//! `plain_len` and that zstd decodes to `plain_len` bytes. +//! frame and block headers: it must accept exactly the frames that are one FS-53 frame +//! declaring `plain_len` and that zstd decodes to `plain_len` bytes. zstd's one-shot decoder +//! does not check the block maximum, so the block headers are read here too. use std::cell::RefCell; @@ -66,10 +67,11 @@ fn oracle(frame: &[u8], plain_len: u64) -> Option> { } } -/// Whether `frame` is exactly one zstd frame whose header FS-53 allows: no unused or reserved -/// bit, checksum or dictionary ID, a declared content size of `plain_len` in the shortest field -/// that holds it, a window of at most 1 MiB, and nothing after the frame (RFC 8878 section -/// 3.1.1). +/// Whether `frame` is exactly one zstd frame that FS-53 allows before decoding: a single +/// segment, so no window descriptor and a window of `plain_len`; no unused or reserved bit, +/// checksum or dictionary ID; a declared content size of `plain_len` in the shortest field that +/// holds it; blocks of a defined type no larger than `min(plain_len, 128 KiB)`, an RLE block +/// counting what it regenerates; and nothing after the last block (RFC 8878 section 3.1.1). fn fs53_header(frame: &[u8], plain_len: u64) -> bool { let Some((magic, rest)) = frame.split_first_chunk::<4>() else { return false; @@ -77,30 +79,21 @@ fn fs53_header(frame: &[u8], plain_len: u64) -> bool { let Some((&descriptor, rest)) = rest.split_first() else { return false; }; - if u32::from_le_bytes(*magic) != 0xFD2F_B528 || descriptor & 0x1f != 0 { + // Single segment set, and the unused, reserved, checksum and dictionary bits clear. + if u32::from_le_bytes(*magic) != 0xFD2F_B528 || descriptor & 0x3f != 0x20 { return false; } - let single_segment = descriptor & 0x20 != 0; - let (window, rest) = if single_segment { - (None, rest) - } else { - let Some((&window, rest)) = rest.split_first() else { - return false; - }; - (Some(window), rest) - }; - let size_bytes = match (descriptor >> 6, single_segment) { - (0, false) => return false, - (0, true) => 1, - (1, _) => 2, - (2, _) => 4, + let size_bytes = match descriptor >> 6 { + 0 => 1, + 1 => 2, + 2 => 4, _ => 8, }; - // The shortest field: one byte only without a window descriptor, two with an offset of 256. + // The shortest field: one byte, two with an offset of 256, then four. let shortest = match plain_len { - 0..256 if single_segment => 1, + 0..256 => 1, 256..65_792 => 2, - 0..0xFFFF_FFFF => 4, + 65_792..0xFFFF_FFFF => 4, _ => 8, }; if size_bytes != shortest { @@ -112,10 +105,33 @@ fn fs53_header(frame: &[u8], plain_len: u64) -> bool { let mut bytes = [0u8; 8]; bytes[..size_bytes].copy_from_slice(field); let declared = u64::from_le_bytes(bytes) + if size_bytes == 2 { 256 } else { 0 }; - let window_ok = window.is_none_or(|byte| { - let base = 1u64 << (10 + (byte >> 3)); - base + base / 8 * u64::from(byte & 7) <= MAX_PLAIN_LEN - }); + let blocks_end = blocks_end(&rest[size_bytes..], plain_len.min(128 * 1024)); let one_frame = zstd_safe::find_frame_compressed_size(frame) == Ok(frame.len()); - declared == plain_len && window_ok && one_frame + declared == plain_len && blocks_end == Some(rest.len() - size_bytes) && one_frame +} + +/// Where the blocks at the start of `blocks` end, if each is whole, of a defined type and no +/// larger than `block_max` (RFC 8878 section 3.1.1.2). +fn blocks_end(blocks: &[u8], block_max: u64) -> Option { + let mut at = 0; + loop { + let header = blocks.get(at..at + 3)?; + let header = u32::from(header[0]) | u32::from(header[1]) << 8 | u32::from(header[2]) << 16; + let size = u64::from(header >> 3); + if size > block_max { + return None; + } + let content = match (header >> 1) & 3 { + 1 => 1, + 3 => return None, + _ => usize::try_from(size).ok()?, + }; + at += 3 + content; + if at > blocks.len() { + return None; + } + if header & 1 == 1 { + return Some(at); + } + } } diff --git a/tests/fuzz/harness/tests/replay.rs b/tests/fuzz/harness/tests/replay.rs index b91bee8..7694e6d 100644 --- a/tests/fuzz/harness/tests/replay.rs +++ b/tests/fuzz/harness/tests/replay.rs @@ -3,6 +3,7 @@ //! //! This keeps the fuzz properties in plain `cargo test`; `cargo xtask fuzz` searches further. +use std::collections::BTreeMap; use std::fs; use std::path::Path; @@ -22,11 +23,32 @@ fn target(name: &str) -> Target { *run } +/// The fewest vector seeds each target gets: the current counts. The vectors are generated +/// deterministically, so a lower count means a generator change stopped feeding a target. +/// Raise a count when vectors are added. `cbor_structured` gets no seeds of its own: every seed +/// drives it. +const MIN_SEEDS: [(&str, usize); 12] = [ + ("preamble", 54), + ("cbor_document", 119), + ("cbor_differential", 119), + ("store_key", 6), + ("config_toml", 5), + ("id_text", 9), + ("cx_open", 63), + ("verifying_key", 3), + ("inner_plaintext", 19), + ("decompress", 37), + ("data_blob_open", 92), + ("chunker", 21), +]; + #[test] fn every_vector_input_and_its_bit_flips() { let mut runs = 0usize; + let mut per_target: BTreeMap<&str, usize> = BTreeMap::new(); for seed in seeds() { for name in seed.target.fuzz_targets() { + *per_target.entry(name).or_default() += 1; let run = target(name); run(&seed.bytes); runs += 1; @@ -43,6 +65,25 @@ fn every_vector_input_and_its_bit_flips() { target("cbor_structured")(&seed.bytes); } assert!(runs > 10_000, "only {runs} runs"); + for (name, minimum) in MIN_SEEDS { + let count = per_target.get(name).copied().unwrap_or(0); + assert!( + count >= minimum, + "{name} got {count} seeds, fewer than the {minimum} it had" + ); + } + let unlisted: Vec<&str> = TARGETS + .iter() + .map(|(name, _)| *name) + .filter(|name| { + *name != "cbor_structured" && !MIN_SEEDS.iter().any(|(known, _)| known == name) + }) + .collect(); + assert_eq!( + unlisted, + Vec::<&str>::new(), + "targets without a seed minimum" + ); } #[test] From 14834d8f2fb43c4a326ffa73f7a68ec23e94cb23 Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 21:57:18 +0530 Subject: [PATCH 13/15] build: exact zstd feature allow-list, a static-link check for libzstd, RUSTFLAGS and patch override guards, per-target fuzz lengths --- deny.toml | 23 +- tests/deny.toml | 23 +- xtask/src/ci.rs | 9 +- xtask/src/features.rs | 462 ++++++++++++++++++++++++++++++++-------- xtask/src/main.rs | 6 +- xtask/src/pre_commit.rs | 4 +- xtask/src/side.rs | 86 +++++++- xtask/src/zstd_link.rs | 298 ++++++++++++++++++++++++++ 8 files changed, 796 insertions(+), 115 deletions(-) create mode 100644 xtask/src/zstd_link.rs diff --git a/deny.toml b/deny.toml index 48a8f5e..3699433 100644 --- a/deny.toml +++ b/deny.toml @@ -103,19 +103,26 @@ deny = ["reduced-round"] crate = "curve25519-dalek" deny = ["legacy_compatibility"] -# zstd as FS-53 pins it: the bundled library built by zstd-sys's own build script with `cc`, -# never through `cmake`, never a system one (through pkg-config, or `non-cargo`, which emits -# no link metadata so whatever libzstd the linker finds is used), never the `debug` build -# (DEBUGLEVEL=5, which traces internal state to standard error), and none of the legacy -# decoders, dictionary builder, experimental API or multithreading, which the format does not -# use and would only widen the attack surface. +# zstd as FS-53 pins it: the bundled library built by zstd-sys's own build script with `cc`. +# An exact allow list rather than a deny list, so a feature a later zstd-sys or zstd-safe +# release adds (another way to link a system libzstd, a new build mode) fails until someone +# reviews it. Our build enables no feature of either crate: not `pkg-config` or `non-cargo` +# (a system libzstd; `non-cargo` emits no link metadata, so whatever libzstd the linker finds +# is used), `cmake`, `debug` (DEBUGLEVEL=5, which traces internal state to standard error), +# nor the legacy decoders, dictionary builder, experimental API, multithreading, `seekable`, +# `bindgen` or zstd-safe's `with-rust-allocator`, which the format does not use and would only +# widen the attack surface. `cargo xtask check-features` covers what features cannot express +# (ZSTD_SYS_USE_PKG_CONFIG, `links` overrides, `[patch]`), and `cargo xtask check-zstd-link` +# checks the built library is the vendored one, linked statically. [[bans.features]] crate = "zstd-sys" -deny = ["legacy", "pkg-config", "non-cargo", "cmake", "debug", "zdict_builder", "experimental", "zstdmt", "seekable", "bindgen"] +allow = [] +exact = true [[bans.features]] crate = "zstd-safe" -deny = ["legacy", "pkg-config", "cmake", "debug", "zdict_builder", "experimental", "zstdmt", "seekable", "bindgen", "with-rust-allocator"] +allow = [] +exact = true [sources] unknown-registry = "deny" diff --git a/tests/deny.toml b/tests/deny.toml index deb82a5..cd0422e 100644 --- a/tests/deny.toml +++ b/tests/deny.toml @@ -114,19 +114,26 @@ deny = ["reduced-round"] crate = "curve25519-dalek" deny = ["legacy_compatibility"] -# zstd as FS-53 pins it: the bundled library built by zstd-sys's own build script with `cc`, -# never through `cmake`, never a system one (through pkg-config, or `non-cargo`, which emits -# no link metadata so whatever libzstd the linker finds is used), never the `debug` build -# (DEBUGLEVEL=5, which traces internal state to standard error), and none of the legacy -# decoders, dictionary builder, experimental API or multithreading, which the format does not -# use and would only widen the attack surface. +# zstd as FS-53 pins it: the bundled library built by zstd-sys's own build script with `cc`. +# An exact allow list rather than a deny list, so a feature a later zstd-sys or zstd-safe +# release adds (another way to link a system libzstd, a new build mode) fails until someone +# reviews it. Our build enables no feature of either crate: not `pkg-config` or `non-cargo` +# (a system libzstd; `non-cargo` emits no link metadata, so whatever libzstd the linker finds +# is used), `cmake`, `debug` (DEBUGLEVEL=5, which traces internal state to standard error), +# nor the legacy decoders, dictionary builder, experimental API, multithreading, `seekable`, +# `bindgen` or zstd-safe's `with-rust-allocator`, which the format does not use and would only +# widen the attack surface. `cargo xtask check-features` covers what features cannot express +# (ZSTD_SYS_USE_PKG_CONFIG, `links` overrides, `[patch]`), and `cargo xtask check-zstd-link` +# checks the built library is the vendored one, linked statically. [[bans.features]] crate = "zstd-sys" -deny = ["legacy", "pkg-config", "non-cargo", "cmake", "debug", "zdict_builder", "experimental", "zstdmt", "seekable", "bindgen"] +allow = [] +exact = true [[bans.features]] crate = "zstd-safe" -deny = ["legacy", "pkg-config", "cmake", "debug", "zdict_builder", "experimental", "zstdmt", "seekable", "bindgen", "with-rust-allocator"] +allow = [] +exact = true [sources] unknown-registry = "deny" diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index 7f0eca8..7633aa7 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -10,7 +10,7 @@ use std::env; use std::process::Command; use crate::process::{cargo, repo_root, require_tool, run_status}; -use crate::{commits, docs_check, features, pre_commit, side, vendored}; +use crate::{commits, docs_check, features, pre_commit, side, vendored, zstd_link}; /// One CI job. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -21,7 +21,8 @@ enum Job { Pr, /// Clippy on both workspaces. Clippy, - /// The main workspace tests and doctests. + /// The main workspace tests and doctests, then the check that the tests linked the + /// vendored libzstd. Test, /// Rustdoc with warnings as errors. Doc, @@ -227,7 +228,9 @@ fn test() -> Result<(), String> { run_status( Command::new(cargo()).args(["test", "--doc", "--workspace", "--all-features", "--locked"]), "doctests failed (see above)", - ) + )?; + // After a build, so the check reuses its zstd-sys build script run. + zstd_link::check(&[]) } fn doc() -> Result<(), String> { diff --git a/xtask/src/features.rs b/xtask/src/features.rs index 35c8b01..4fd2a27 100644 --- a/xtask/src/features.rs +++ b/xtask/src/features.rs @@ -1,29 +1,47 @@ //! `cargo xtask check-features`: no release build may enable the test-only features of -//! `crypthix-crypto` (FS-01, FS-94). +//! `crypthix-crypto` or `crypthix-core` (FS-01, FS-55, FS-94). //! -//! `test-rng` is the seeded stream of the vector generator and `vectors` exposes the inner -//! CX-AEAD errors and raw entry points. Only the `tests/` workspace and the crate's own tests use -//! them. A release build could still pick one up: +//! In `crypthix-crypto`, `test-rng` is the seeded stream of the vector generator and `vectors` +//! exposes the inner CX-AEAD errors and raw entry points. In `crypthix-core`, `vectors` exposes +//! the keys, AADs and chunk constructors that bypass `ObjectSealer`'s binding to its object. +//! Only the `tests/` workspace and each crate's own tests use them. A release build could still +//! pick one up: //! //! - through a normal or build dependency that names it, under any name the dependency is //! renamed to; -//! - through a package feature that forwards to it, or to another `crypthix-crypto` feature that -//! enables it; -//! - through `crypthix-crypto`'s own default features. +//! - through a package feature that forwards to it, or to another feature of the same crate +//! that enables it; +//! - through the crate's own default features. //! //! The first two are read from `cargo metadata`. Then `cargo tree`, without dev-dependencies, -//! resolves the whole workspace with default features, and every package that depends on the -//! crate with `--all-features` on every target, and must show neither feature. Any failure to -//! run or read `cargo tree` fails the check. +//! resolves the whole workspace with default features, and every package that depends on a +//! guarded crate with `--all-features` on every target, and must show none of its guarded +//! features. Any failure to run or read `cargo tree` fails the check. //! //! Compiler flags can do the same behind Cargo's back: `--cfg feature="vectors"` turns a feature -//! on, and `--cfg getrandom_backend=...` replaces the kernel source of every key and nonce -//! (FS-01). The check rejects either in `RUSTFLAGS` and in the repository's Cargo config files. -//! It also rejects two ways to link a system libzstd instead of the bundled, pinned one (FS-53), -//! which cargo-deny's bans on `zstd-sys` features cannot see: `ZSTD_SYS_USE_PKG_CONFIG` in those -//! files or in the environment, and a `links` override for `zstd` (a `[target..zstd]` -//! table, or a `zstd` key under `[target.]`) in those files, which makes Cargo skip -//! `zstd-sys`'s build script and link whatever the override names. +//! on, `--cfg feature="pkg-config"` turns on a `zstd-sys` feature that cargo-deny's allow list +//! never sees, and `--cfg getrandom_backend=...` replaces the kernel source of every key and +//! nonce (FS-01). The check rejects any `--cfg feature=` and any `getrandom_backend` in every +//! variable Cargo reads compiler flags from (`RUSTFLAGS`, `CARGO_ENCODED_RUSTFLAGS`, +//! `CARGO_BUILD_RUSTFLAGS`, `CARGO_HOST_RUSTFLAGS` and each `CARGO_TARGET__RUSTFLAGS`) +//! and anywhere in the repository's Cargo config files, which covers their `rustflags` under +//! `[build]`, `[host]` and `[target.]`. +//! +//! It also rejects the ways to link a system or a different libzstd instead of the bundled, +//! pinned one (FS-53) that cargo-deny cannot see: +//! +//! - `ZSTD_SYS_USE_PKG_CONFIG` in those files or in the environment; +//! - a `links` override for `zstd` (a `[target..zstd]` table, or a `zstd` key under +//! `[target.]`) in those files, which makes Cargo skip `zstd-sys`'s build script and +//! link whatever the override names; +//! - a `[patch.]` or `[replace]` entry for `zstd`, `zstd-sys` or `zstd-safe`, under its +//! own name or through `package = "..."`, in those files or in either workspace manifest, +//! which swaps in another copy of the crate and its build script; +//! - a `paths` override in those files: it replaces any crate whose name matches a package in +//! the listed directories, and the check does not read them to find out which, so every one +//! is rejected. +//! +//! `cargo xtask check-zstd-link` then checks what the build actually linked. //! //! These checks cover only the repository's own build environment: the process environment of //! the check and the Cargo config files inside the repository. A user-level @@ -43,27 +61,20 @@ use toml::{Table, Value}; use crate::process::{cargo, repo_root}; -/// The crate whose features are guarded. -const CRATE: &str = "crypthix-crypto"; - -/// Its features that a release build must never enable. -const TEST_ONLY: [&str; 2] = ["test-rng", "vectors"]; +/// The guarded crates, each with its features that a release build must never enable. +const GUARDED: [(&str, &[&str]); 2] = [ + ("crypthix-crypto", &["test-rng", "vectors"]), + ("crypthix-core", &["vectors"]), +]; /// Runs the check on the main workspace. pub(crate) fn check() -> Result<(), String> { let metadata = MetadataCommand::new() .exec() .map_err(|error| format!("cargo metadata failed: {error}"))?; - let crypto = metadata - .workspace_packages() - .into_iter() - .find(|package| package.name.as_str() == CRATE) - .ok_or_else(|| format!("{CRATE} is not a workspace member"))?; - let guarded = guarded_features(&crypto.features); - let mut problems = Vec::new(); - for package in metadata.workspace_packages() { - problems.extend(manifest_problems(package, &guarded)); + for (krate, test_only) in GUARDED { + problems.extend(crate_problems(&metadata, krate, test_only)?); } let files = config_files(); problems.extend( @@ -77,35 +88,68 @@ pub(crate) fn check() -> Result<(), String> { .iter() .flat_map(|(source, text)| links_problems(source, text)), ); - problems.extend(resolved_problems(&["--workspace"], &guarded)?); - for package in dependents(&metadata, &crypto.id) { - let args = ["--package", package, "--all-features", "--target", "all"]; - problems.extend(resolved_problems(&args, &guarded)?); - } + problems.extend( + files + .iter() + .chain(&manifest_files()) + .flat_map(|(source, text)| override_problems(source, text)), + ); if problems.is_empty() { - println!( - "features: no release build enables {}", - TEST_ONLY.join(" or ") - ); + let names: Vec = GUARDED + .iter() + .flat_map(|(krate, test_only)| { + test_only + .iter() + .map(move |feature| format!("{krate}/{feature}")) + }) + .collect(); + println!("features: no release build enables {}", names.join(", ")); Ok(()) } else { for problem in &problems { eprintln!("feature rule violation: {problem}"); } Err(format!( - "{} release builds must not enable test-only features of {CRATE} (FS-01)", + "{} release builds must not enable test-only features (FS-01)", problems.len() )) } } +/// The problems with one guarded crate: manifests that enable or forward to its test-only +/// features, and release builds that resolve them. +fn crate_problems( + metadata: &Metadata, + krate: &str, + test_only: &[&str], +) -> Result, String> { + let package = metadata + .workspace_packages() + .into_iter() + .find(|package| package.name.as_str() == krate) + .ok_or_else(|| format!("{krate} is not a workspace member"))?; + let guarded = guarded_features(&package.features, test_only); + + let mut problems = Vec::new(); + for package in metadata.workspace_packages() { + problems.extend(manifest_problems(package, krate, &guarded)); + } + problems.extend(resolved_problems(krate, &["--workspace"], &guarded)?); + for dependent in dependents(metadata, &package.id) { + let args = ["--package", dependent, "--all-features", "--target", "all"]; + problems.extend(resolved_problems(krate, &args, &guarded)?); + } + Ok(problems) +} + /// The test-only features and every feature of the crate that turns one of them on, directly or /// through other features. fn guarded_features( features: &std::collections::BTreeMap>, + test_only: &[&str], ) -> BTreeSet { - let mut guarded: BTreeSet = TEST_ONLY + let mut guarded: BTreeSet = test_only .iter() .map(|feature| (*feature).to_owned()) .collect(); @@ -124,22 +168,23 @@ fn guarded_features( } } -/// Problems in one package's manifest: dependencies on the crate that turn on a guarded feature +/// Problems in one package's manifest: dependencies on `krate` that turn on a guarded feature /// outside dev-dependencies, and package features that forward to one. -fn manifest_problems(package: &Package, guarded: &BTreeSet) -> Vec { +fn manifest_problems(package: &Package, krate: &str, guarded: &BTreeSet) -> Vec { let mut problems = Vec::new(); // The names this package refers to the crate by: its own name, or a rename. let mut aliases = BTreeSet::new(); for dependency in &package.dependencies { - if dependency.name != CRATE { + if dependency.name != krate { continue; } let alias = dependency .rename .clone() - .unwrap_or_else(|| CRATE.to_owned()); + .unwrap_or_else(|| krate.to_owned()); problems.extend(dependency_problem( &package.name, + krate, &alias, dependency.kind, &dependency.features, @@ -147,12 +192,13 @@ fn manifest_problems(package: &Package, guarded: &BTreeSet) -> Vec) -> Vec, @@ -203,18 +252,18 @@ fn forwarding_problems( let dependency = dependency.strip_suffix('?').unwrap_or(dependency); (aliases.contains(dependency) && guarded.contains(target)).then_some(target) }); - let defaulted = (package == CRATE && feature == "default" && guarded.contains(value)) + let defaulted = (package == krate && feature == "default" && guarded.contains(value)) .then_some(value.as_str()); forwarded .or(defaulted) - .map(|name| format!("{package} feature `{feature}` enables {CRATE}/{name}")) + .map(|name| format!("{package} feature `{feature}` enables {krate}/{name}")) }) .collect() } /// The workspace packages other than the crate that reach it through normal or build /// dependencies, so `--all-features` on them could reach its features. -fn dependents<'a>(metadata: &'a Metadata, crypto: &PackageId) -> Vec<&'a str> { +fn dependents<'a>(metadata: &'a Metadata, krate: &PackageId) -> Vec<&'a str> { let Some(resolve) = &metadata.resolve else { return Vec::new(); }; @@ -238,7 +287,7 @@ fn dependents<'a>(metadata: &'a Metadata, crypto: &PackageId) -> Vec<&'a str> { metadata .workspace_packages() .into_iter() - .filter(|package| package.id != *crypto && reaches(&edges, &package.id, crypto)) + .filter(|package| package.id != *krate && reaches(&edges, &package.id, krate)) .map(|package| package.name.as_str()) .collect() } @@ -262,14 +311,18 @@ fn reaches( false } -/// Asks `cargo tree`, without dev-dependencies, which features of the crate a build with `args` +/// Asks `cargo tree`, without dev-dependencies, which features of `krate` a build with `args` /// resolves. -fn resolved_problems(args: &[&str], guarded: &BTreeSet) -> Result, String> { +fn resolved_problems( + krate: &str, + args: &[&str], + guarded: &BTreeSet, +) -> Result, String> { let output = Command::new(cargo()) .args(["tree", "--locked", "--edges", "no-dev"]) .args(args) .args([ - "--invert", CRATE, "--depth", "0", "--prefix", "none", "--format", "{p}|{f}", + "--invert", krate, "--depth", "0", "--prefix", "none", "--format", "{p}|{f}", ]) .output() .map_err(|error| format!("cannot run cargo tree: {error}"))?; @@ -280,27 +333,106 @@ fn resolved_problems(args: &[&str], guarded: &BTreeSet) -> Result Vec<(String, String)> { - let variables = [ - "RUSTFLAGS", - "CARGO_BUILD_RUSTFLAGS", - "CARGO_ENCODED_RUSTFLAGS", - ]; - let from_env = variables - .iter() - .filter_map(|name| env::var(name).ok().map(|value| ((*name).to_owned(), value))); + let from_env = env::vars_os().filter_map(|(name, value)| { + let name = name.into_string().ok()?; + // A value that is not UTF-8 is read lossily: it still reaches rustc. + is_rustflags_variable(&name).then(|| (name, value.to_string_lossy().into_owned())) + }); // Any value turns pkg-config on, so the variable's presence is reported, under its own name. let zstd = env::var_os(ZSTD_PKG_CONFIG) .map(|_| ("environment".to_owned(), ZSTD_PKG_CONFIG.to_owned())); from_env.chain(zstd).collect() } +/// Whether Cargo passes the variable's value to rustc as flags: `RUSTFLAGS`, +/// `CARGO_ENCODED_RUSTFLAGS`, `CARGO_BUILD_RUSTFLAGS`, `CARGO_HOST_RUSTFLAGS`, or +/// `CARGO_TARGET__RUSTFLAGS` for any triple. Cargo matches variable names exactly, so +/// lower-case spellings are not flags. +fn is_rustflags_variable(name: &str) -> bool { + const FIXED: [&str; 4] = [ + "RUSTFLAGS", + "CARGO_ENCODED_RUSTFLAGS", + "CARGO_BUILD_RUSTFLAGS", + "CARGO_HOST_RUSTFLAGS", + ]; + FIXED.contains(&name) + || name + .strip_prefix("CARGO_TARGET_") + .and_then(|rest| rest.strip_suffix("_RUSTFLAGS")) + .is_some_and(|triple| !triple.is_empty()) +} + +/// Both workspace manifests, as `(path, text)`, for their `[patch]` and `[replace]` tables. +fn manifest_files() -> Vec<(String, String)> { + let root = repo_root(); + ["Cargo.toml", "tests/Cargo.toml"] + .iter() + .filter_map(|file| { + fs::read_to_string(root.join(file)) + .ok() + .map(|text| ((*file).to_owned(), text)) + }) + .collect() +} + +/// `[patch.]` and `[replace]` entries that swap in another `zstd`, `zstd-sys` or +/// `zstd-safe`, and any `paths` override (see the module docs). Invalid TOML is reported by +/// `links_problems` for config files and by Cargo for manifests, so it is skipped here. +fn override_problems(source: &str, text: &str) -> Vec { + let Ok(config) = text.parse::() else { + return Vec::new(); + }; + let mut problems = Vec::new(); + if let Some(Value::Table(registries)) = config.get("patch") { + for (registry, entries) in registries { + let Value::Table(entries) = entries else { + continue; + }; + for (name, entry) in entries { + let package = match entry { + Value::Table(entry) => entry.get("package").and_then(Value::as_str), + _ => None, + }; + if let Some(krate) = [name.as_str()] + .into_iter() + .chain(package) + .find(|krate| ZSTD_CRATES.contains(krate)) + { + problems.push(format!( + "{source} patches {krate} for {registry}, replacing the pinned zstd (FS-53)" + )); + } + } + } + } + if let Some(Value::Table(replaced)) = config.get("replace") { + for spec in replaced.keys() { + // `name:version` or `registry#name@version`; the name is what matters. + let name = spec.rsplit(['#', '/']).next().unwrap_or(spec); + let name = name.split([':', '@']).next().unwrap_or(name); + if ZSTD_CRATES.contains(&name) { + problems.push(format!( + "{source} replaces {spec}, swapping out the pinned zstd (FS-53)" + )); + } + } + } + if config.contains_key("paths") { + problems.push(format!( + "{source} sets `paths`, which can replace zstd-sys or any other crate with a local \ + copy; use `[patch]` for a crate that is not zstd instead" + )); + } + problems +} + /// The Cargo config files of both workspaces, as `(path, text)`. Files outside the repository /// are out of reach (see the module docs). fn config_files() -> Vec<(String, String)> { @@ -360,9 +492,11 @@ fn flag_problems(source: &str, text: &str) -> Vec { "{source} sets getrandom_backend, replacing the kernel RNG (FS-01)" )); } - if compact.contains("feature=") { + // `-C target-feature=+aes` is a CPU feature, not a crate feature. + if compact.replace("target-feature=", "").contains("feature=") { problems.push(format!( - "{source} sets a `--cfg feature=` flag, bypassing Cargo features" + "{source} sets a `--cfg feature=` flag, bypassing Cargo features (a test-only \ + feature, or a zstd-sys one such as pkg-config that cargo-deny cannot see)" )); } problems @@ -374,25 +508,31 @@ const ZSTD_PKG_CONFIG: &str = "ZSTD_SYS_USE_PKG_CONFIG"; /// The `links` name of `zstd-sys`, which a `[target..zstd]` table overrides. const ZSTD_LINKS: &str = "zstd"; -/// The guarded features in `cargo tree` lines of the form ` ()|`. +/// The crates between `crypthix-core` and libzstd, and the `zstd` crate cargo-deny bans, none of +/// which a `[patch]` or `[replace]` may swap out. +const ZSTD_CRATES: [&str; 3] = ["zstd", "zstd-sys", "zstd-safe"]; + +/// The guarded features of `krate` in `cargo tree` lines of the form +/// ` ()|`. /// /// # Errors /// /// If no line names the crate, so a changed output format cannot pass silently. -fn resolved_in(tree: &str, guarded: &BTreeSet) -> Result, String> { +fn resolved_in(krate: &str, tree: &str, guarded: &BTreeSet) -> Result, String> { + let prefix = format!("{krate} v"); let lines: Vec<(&str, &str)> = tree .lines() .filter_map(|line| line.split_once('|')) - .filter(|(package, _)| package.starts_with(&format!("{CRATE} v"))) + .filter(|(package, _)| package.starts_with(&prefix)) .collect(); if lines.is_empty() { - return Err(format!("no line for {CRATE} in its output")); + return Err(format!("no line for {krate} in its output")); } Ok(lines .iter() .flat_map(|(_, features)| features.split(',')) .filter(|feature| guarded.contains(*feature)) - .map(|feature| format!("a release build resolves {CRATE}/{feature}")) + .map(|feature| format!("a release build resolves {krate}/{feature}")) .collect()) } @@ -410,8 +550,11 @@ mod tests { values.iter().map(|value| (*value).to_owned()).collect() } + /// The crypto crate, the first guarded one. + const CRATE: &str = GUARDED[0].0; + fn guarded() -> BTreeSet { - set(&TEST_ONLY) + set(GUARDED[0].1) } #[test] @@ -424,17 +567,57 @@ mod tests { ("std".to_owned(), Vec::new()), ]); assert_eq!( - guarded_features(&features), + guarded_features(&features, GUARDED[0].1), set(&["bench", "deep", "test-rng", "vectors"]) ); } + #[test] + fn the_cores_vectors_feature_is_guarded() { + let (krate, test_only) = GUARDED[1]; + assert_eq!(krate, "crypthix-core"); + let features = BTreeMap::from([("vectors".to_owned(), Vec::new())]); + let guarded = guarded_features(&features, test_only); + assert_eq!(guarded, set(&["vectors"])); + let normal = dependency_problem( + "crypthix-cli", + krate, + krate, + DependencyKind::Normal, + &strings(&["vectors"]), + &guarded, + ); + assert!( + normal.is_some(), + "a normal dependency enabled crypthix-core/vectors" + ); + let forwarded = forwarding_problems( + "crypthix-cli", + krate, + "debug", + &strings(&["crypthix-core/vectors"]), + &set(&[krate]), + &guarded, + ); + assert_eq!(forwarded.len(), 1, "{forwarded:?}"); + let leaked = "crypthix-core v0.0.0 (/x)|vectors\n"; + assert_eq!( + resolved_in(krate, leaked, &guarded).map(|found| found.len()), + Ok(1) + ); + assert!( + resolved_in(krate, "crypthix-crypto v0.0.0 (/x)|vectors\n", &guarded).is_err(), + "another crate's line" + ); + } + #[test] fn normal_and_build_dependencies_may_not_enable_test_features() { let rng = strings(&["test-rng"]); let normal = dependency_problem( "crypthix-cli", CRATE, + CRATE, DependencyKind::Normal, &rng, &guarded(), @@ -443,6 +626,7 @@ mod tests { let build = dependency_problem( "crypthix-cli", CRATE, + CRATE, DependencyKind::Build, &rng, &guarded(), @@ -456,6 +640,7 @@ mod tests { let dev = dependency_problem( "crypthix-keys", CRATE, + CRATE, DependencyKind::Development, &rng, &guarded(), @@ -464,6 +649,7 @@ mod tests { let none = dependency_problem( "crypthix-keys", CRATE, + CRATE, DependencyKind::Normal, &[], &guarded(), @@ -475,10 +661,18 @@ mod tests { fn forwarding_through_any_alias_is_rejected() { let aliases = set(&[CRATE, "cx"]); let enables = strings(&["crypthix-crypto/test-rng", "cx?/vectors", "cx/std", "dep:x"]); - let problems = forwarding_problems("crypthix-cli", "debug", &enables, &aliases, &guarded()); + let problems = forwarding_problems( + "crypthix-cli", + CRATE, + "debug", + &enables, + &aliases, + &guarded(), + ); assert_eq!(problems.len(), 2, "{problems:?}"); let unrelated = forwarding_problems( "crypthix-cli", + CRATE, "x", &strings(&["other/vectors"]), &aliases, @@ -490,10 +684,17 @@ mod tests { #[test] fn the_crate_may_not_default_to_a_test_feature() { let own = set(&[CRATE]); - let defaults = - forwarding_problems(CRATE, "default", &strings(&["test-rng"]), &own, &guarded()); + let defaults = forwarding_problems( + CRATE, + CRATE, + "default", + &strings(&["test-rng"]), + &own, + &guarded(), + ); assert_eq!(defaults.len(), 1); let fine = forwarding_problems( + CRATE, CRATE, "test-rng", &strings(&["dep:chacha20"]), @@ -506,10 +707,10 @@ mod tests { #[test] fn resolved_features_are_read_from_cargo_tree() { let clean = "crypthix-crypto v0.0.0 (/x)|\n"; - assert_eq!(resolved_in(clean, &guarded()), Ok(Vec::new())); + assert_eq!(resolved_in(CRATE, clean, &guarded()), Ok(Vec::new())); let leaked = "crypthix-crypto v0.0.0 (/x)|test-rng,vectors\n"; assert_eq!( - resolved_in(leaked, &guarded()).map(|found| found.len()), + resolved_in(CRATE, leaked, &guarded()).map(|found| found.len()), Ok(2) ); } @@ -541,6 +742,94 @@ mod tests { ); } + #[test] + fn every_rustflags_variable_is_read() { + for name in [ + "RUSTFLAGS", + "CARGO_ENCODED_RUSTFLAGS", + "CARGO_BUILD_RUSTFLAGS", + "CARGO_HOST_RUSTFLAGS", + "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS", + "CARGO_TARGET_AARCH64_APPLE_DARWIN_RUSTFLAGS", + ] { + assert!(is_rustflags_variable(name), "{name}"); + } + for name in [ + "RUSTDOCFLAGS", + "CARGO_TARGET_DIR", + "CARGO_TARGET__RUSTFLAGS", + "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER", + "cargo_build_rustflags", + ] { + assert!(!is_rustflags_variable(name), "{name}"); + } + } + + #[test] + fn zstd_feature_cfgs_in_flags_are_rejected() { + let target = flag_problems( + "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS", + "--cfg feature=\"pkg-config\"", + ); + assert_eq!(target.len(), 1, "{target:?}"); + // CARGO_ENCODED_RUSTFLAGS separates flags with 0x1f, not spaces. + let encoded = flag_problems( + "CARGO_ENCODED_RUSTFLAGS", + "--cfg\u{1f}feature=\"non-cargo\"", + ); + assert_eq!(encoded.len(), 1, "{encoded:?}"); + let config = "[target.'cfg(unix)']\nrustflags = [\"--cfg\", \"feature = \\\"cmake\\\"\"]\n\ + [host]\nrustflags = [\"-C\", \"opt-level=2\"]\n"; + assert_eq!(flag_problems(".cargo/config.toml", config).len(), 1); + assert_eq!( + flag_problems("CARGO_BUILD_RUSTFLAGS", "-C target-cpu=native"), + Vec::::new() + ); + assert_eq!( + flag_problems("RUSTFLAGS", "-C target-feature=+aes,+sse4.1"), + Vec::::new() + ); + assert_eq!( + flag_problems( + "RUSTFLAGS", + "-C target-feature=+aes --cfg feature=\"cmake\"" + ) + .len(), + 1 + ); + } + + #[test] + fn patches_and_replacements_of_zstd_crates_are_rejected() { + for config in [ + "[patch.crates-io]\nzstd-sys = { path = \"../zstd-sys\" }\n", + "[patch.crates-io.zstd-safe]\ngit = \"https://example.com/zstd-rs\"\n", + "[patch.'https://github.com/x/y']\nmine = { path = \"z\", package = \"zstd\" }\n", + "[replace]\n\"zstd-sys:2.1.2+zstd.1.5.7\" = { path = \"z\" }\n", + "[replace]\n\"registry+https://x#zstd-safe@8.2.0\" = { path = \"z\" }\n", + "paths = [\"../vendor/zstd-sys\"]\n", + ] { + assert_eq!(override_problems("config", config).len(), 1, "{config}"); + } + let fine = "[patch.crates-io]\nserde = { path = \"../serde\" }\n\ + zstd-sys-like = { path = \"x\" }\n\ + [replace]\n\"zstdx:1.0.0\" = { path = \"z\" }\n\ + [alias]\npaths = \"run\"\n"; + assert_eq!(override_problems("config", fine), Vec::::new()); + assert_eq!(override_problems("config", "[patch"), Vec::::new()); + } + + #[test] + fn the_repository_has_no_zstd_override() { + let problems: Vec = config_files() + .iter() + .chain(&manifest_files()) + .flat_map(|(source, text)| override_problems(source, text)) + .collect(); + assert_eq!(problems, Vec::::new()); + assert_eq!(manifest_files().len(), 2, "both manifests are read"); + } + #[test] fn a_links_override_for_zstd_is_rejected() { let table = "[target.x86_64-unknown-linux-gnu.zstd]\nrustc-link-lib = [\"zstd\"]\n"; @@ -562,9 +851,12 @@ mod tests { #[test] fn output_without_the_crate_fails() { - assert!(resolved_in("", &guarded()).is_err(), "empty output passed"); assert!( - resolved_in("other v1.0.0|vectors\n", &guarded()).is_err(), + resolved_in(CRATE, "", &guarded()).is_err(), + "empty output passed" + ); + assert!( + resolved_in(CRATE, "other v1.0.0|vectors\n", &guarded()).is_err(), "another crate passed" ); } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 7e90a40..416553e 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -2,6 +2,8 @@ //! //! - `cargo xtask check-layers` checks crate dependencies against the layer rules. //! - `cargo xtask check-features` checks that no release build enables a test-only feature. +//! - `cargo xtask check-zstd-link [--target ]` checks that `zstd-sys` links its own +//! libzstd statically (see `zstd_link.rs`). //! - `cargo xtask pre-commit` runs the pre-commit checks on the staged changes. //! - `cargo xtask install-hooks` enables the hooks in `.githooks/` for this clone. //! - `cargo xtask vectors [--check]` rewrites the test vectors, or checks they are current. @@ -27,6 +29,7 @@ mod pre_commit; mod process; mod side; mod vendored; +mod zstd_link; use std::collections::HashMap; use std::env; @@ -45,6 +48,7 @@ fn main() -> ExitCode { match command { "check-layers" => report(check_layers()), "check-features" if rest.is_empty() => report(features::check()), + "check-zstd-link" => report(zstd_link::check(rest)), "pre-commit" => pre_commit::run(), "install-hooks" => pre_commit::install(), "vectors" => side::vectors(rest), @@ -64,7 +68,7 @@ fn main() -> ExitCode { fn usage() -> ExitCode { eprintln!( - "usage: cargo xtask " ); ExitCode::FAILURE diff --git a/xtask/src/pre_commit.rs b/xtask/src/pre_commit.rs index e031f89..0cd6d1b 100644 --- a/xtask/src/pre_commit.rs +++ b/xtask/src/pre_commit.rs @@ -156,8 +156,8 @@ fn checks() -> Result<(), String> { )?; // `tests/` is its own workspace, built on crypthix-types, crypthix-crypto and crypthix-core, - // so a change to any of them can break it. The cargo-fuzz crate is left out: libFuzzer needs a C++ compiler - // even to check, and its binaries only call the harness. + // so a change to any of them can break it. The cargo-fuzz crate is left out: libFuzzer needs + // a C++ compiler even to check, and its binaries only call the harness. let side_changed = staged .iter() .any(|path| SIDE_INPUTS.iter().any(|prefix| path.starts_with(prefix))); diff --git a/xtask/src/side.rs b/xtask/src/side.rs index c41e2d8..03f9702 100644 --- a/xtask/src/side.rs +++ b/xtask/src/side.rs @@ -7,71 +7,95 @@ use std::env; use std::ffi::OsString; use std::fs; use std::io::ErrorKind; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::{Command, ExitCode}; use crate::process::{cargo, repo_root, require_tool, run_status}; -/// A fuzz target in `tests/fuzz/fuzz_targets`, with the dictionary it uses. +/// A fuzz target in `tests/fuzz/fuzz_targets`, with the dictionary it uses and the longest input +/// libFuzzer may make for it. #[derive(Clone, Copy, Debug)] struct FuzzTarget { name: &'static str, dictionary: Option<&'static str>, + /// libFuzzer's `-max_len`. It also truncates longer corpus files, so it must hold the + /// largest seed the vectors give the target; `run_fuzz` fails if one is longer. + max_len: usize, } +/// `-max_len` for targets whose inputs are short: small inputs keep the fuzzer fast. +const DEFAULT_MAX_LEN: usize = 4096; + /// Every fuzz target; a test checks this against `tests/fuzz/fuzz_targets`. const FUZZ_TARGETS: [FuzzTarget; 13] = [ FuzzTarget { name: "preamble", dictionary: None, + // The keyring vectors at their 4096-byte body cap, with the preamble before it. + max_len: 8 * 1024, }, FuzzTarget { name: "cbor_document", dictionary: Some("cbor.dict"), + max_len: DEFAULT_MAX_LEN, }, FuzzTarget { name: "cbor_differential", dictionary: Some("cbor.dict"), + max_len: DEFAULT_MAX_LEN, }, FuzzTarget { name: "cbor_structured", dictionary: None, + max_len: DEFAULT_MAX_LEN, }, FuzzTarget { name: "store_key", dictionary: None, + max_len: DEFAULT_MAX_LEN, }, FuzzTarget { name: "config_toml", dictionary: Some("toml.dict"), + max_len: DEFAULT_MAX_LEN, }, FuzzTarget { name: "id_text", dictionary: None, + max_len: DEFAULT_MAX_LEN, }, FuzzTarget { name: "cx_open", dictionary: None, + max_len: DEFAULT_MAX_LEN, }, FuzzTarget { name: "verifying_key", dictionary: None, + max_len: DEFAULT_MAX_LEN, }, FuzzTarget { name: "inner_plaintext", dictionary: Some("zstd.dict"), + max_len: DEFAULT_MAX_LEN, }, FuzzTarget { name: "decompress", dictionary: Some("zstd.dict"), + // Frames whose 128 KiB blocks reach zstd's block edges, about 131 KB with the length + // prefix and frame header. + max_len: 144 * 1024, }, FuzzTarget { name: "data_blob_open", dictionary: Some("zstd.dict"), + // Data blobs of TV-07, about 5 KB. + max_len: 8 * 1024, }, FuzzTarget { name: "chunker", dictionary: None, + max_len: DEFAULT_MAX_LEN, }, ]; @@ -209,6 +233,7 @@ fn run_fuzz(targets: &[FuzzTarget], seconds: u64) -> Result<(), String> { run_generator(&["seeds", &corpus_arg])?; for target in targets { let name = target.name; + check_seed_lengths(target, &corpus.join(name))?; println!("fuzz: {name} for {seconds} s"); // libFuzzer refuses a corpus directory that does not exist, and structure-aware targets // get no seeds from the vectors. @@ -238,12 +263,8 @@ fn run_fuzz(targets: &[FuzzTarget], seconds: u64) -> Result<(), String> { .arg(tests_dir().join("fuzz").join("regressions").join(name)) .arg("--") .arg(format!("-max_total_time={seconds}")) - .args([ - "-max_len=4096", - "-timeout=10", - "-rss_limit_mb=2048", - "-malloc_limit_mb=64", - ]); + .arg(format!("-max_len={}", target.max_len)) + .args(["-timeout=10", "-rss_limit_mb=2048", "-malloc_limit_mb=64"]); if let Some(dictionary) = target.dictionary { let path = tests_dir().join("fuzz").join("dicts").join(dictionary); let mut flag = OsString::from("-dict="); @@ -263,6 +284,31 @@ fn run_fuzz(targets: &[FuzzTarget], seconds: u64) -> Result<(), String> { Ok(()) } +/// Fails if a seed in `dir` is longer than the target's `max_len`, which libFuzzer would +/// silently cut short. A missing directory has no seeds. +fn check_seed_lengths(target: &FuzzTarget, dir: &Path) -> Result<(), String> { + let Ok(entries) = fs::read_dir(dir) else { + return Ok(()); + }; + for entry in entries { + let entry = entry.map_err(|error| format!("cannot list {}: {error}", dir.display()))?; + let len = entry + .metadata() + .map_err(|error| format!("cannot read {}: {error}", entry.path().display()))? + .len(); + if usize::try_from(len).map_or(true, |len| len > target.max_len) { + return Err(format!( + "seed {} is {len} bytes, over the {} target's max_len of {}: libFuzzer would \ + truncate it; raise max_len in xtask/src/side.rs", + entry.path().display(), + target.name, + target.max_len + )); + } + } + Ok(()) +} + /// The host triple of `toolchain`, from `rustc -vV`. fn toolchain_host(toolchain: &str) -> Result { let output = Command::new("rustup") @@ -346,4 +392,28 @@ mod tests { listed.sort(); assert_eq!(listed, on_disk, "FUZZ_TARGETS must list every fuzz binary"); } + + #[test] + fn a_seed_over_max_len_fails_the_run() { + let dir = env::temp_dir().join(format!("xtask-seed-lengths-{}", std::process::id())); + fs::create_dir_all(&dir).expect("temporary directory"); + let target = FuzzTarget { + name: "test", + dictionary: None, + max_len: 8, + }; + fs::write(dir.join("short"), [0; 8]).expect("seed written"); + let fits = check_seed_lengths(&target, &dir); + fs::write(dir.join("long"), [0; 9]).expect("seed written"); + let over = check_seed_lengths(&target, &dir); + fs::remove_dir_all(&dir).expect("temporary directory removed"); + assert_eq!(fits, Ok(())); + let error = over.expect_err("a 9-byte seed passed max_len 8"); + assert!(error.contains("9 bytes"), "{error}"); + assert_eq!( + check_seed_lengths(&target, &dir), + Ok(()), + "a missing corpus has no seeds" + ); + } } diff --git a/xtask/src/zstd_link.rs b/xtask/src/zstd_link.rs new file mode 100644 index 0000000..1c51524 --- /dev/null +++ b/xtask/src/zstd_link.rs @@ -0,0 +1,298 @@ +//! `cargo xtask check-zstd-link [--target ]`: `zstd-sys` linked the libzstd it built +//! from its own vendored sources, statically (FS-53). +//! +//! `crypthix-core` checks at run time that libzstd reports version 1.5.7, but a system libzstd +//! 1.5.7 passes that too, built with whatever options its distribution chose. cargo-deny bans +//! the `zstd-sys` features that link a system library and `cargo xtask check-features` rejects +//! the settings that do it behind Cargo's back, but neither looks at what a build actually did. +//! This check does: it asks `cargo check` for `crypthix-core`'s build, takes `zstd-sys`'s +//! `build-script-executed` message, and reads both what Cargo reports it will pass to rustc and +//! the build script's own `output` file next to its `OUT_DIR`. Each must link only +//! `static=zstd` and search only inside that `OUT_DIR`, where the build script put the library +//! it compiled with `cc`. A system library through pkg-config adds a `/usr` (or `/opt`, Homebrew, +//! vcpkg) search path and a dynamic `zstd`; a `links` override skips the build script, so there +//! is no `output` file. Either fails. +//! +//! `cargo check` runs build scripts, and reuses the run of an earlier `cargo build` or `cargo +//! test` with the same profile, so after a test run the check costs a second. + +use std::fs; +use std::io::BufReader; +use std::path::Path; +use std::process::{Command, Stdio}; + +use cargo_metadata::Message; + +use crate::process::cargo; + +/// The library `zstd-sys`'s build script compiles with `cc` and links. +const LIBRARY: &str = "zstd"; + +/// What a `zstd-sys` build passes to rustc for linking. +#[derive(Debug, PartialEq, Eq)] +enum Directive { + /// `rustc-link-lib=[KIND=]NAME`, kept whole after the `=`. + Lib(String), + /// `rustc-link-search=[KIND=]PATH`, kept whole after the `=`. + Search(String), + /// `rustc-link-arg*` and `rustc-flags`, which can name libraries and paths too. + Other(String), +} + +/// Runs the check for the host, or for `--target `. +pub(crate) fn check(args: &[String]) -> Result<(), String> { + let target = match args { + [] => None, + [flag, triple] if flag == "--target" => Some(triple.as_str()), + _ => return Err("usage: cargo xtask check-zstd-link [--target ]".to_owned()), + }; + let mut command = Command::new(cargo()); + command + .args([ + "check", + "--package", + "crypthix-core", + "--all-features", + "--locked", + "--message-format=json-render-diagnostics", + ]) + .stdout(Stdio::piped()); + if let Some(target) = target { + command.args(["--target", target]); + } + let mut child = command + .spawn() + .map_err(|error| format!("cannot run cargo check: {error}"))?; + let stdout = child.stdout.take().ok_or("cargo check gave no output")?; + let mut runs = Vec::new(); + for message in Message::parse_stream(BufReader::new(stdout)) { + let message = message.map_err(|error| format!("cannot read cargo's output: {error}"))?; + if let Message::BuildScriptExecuted(script) = message + && script.package_id.repr.contains("#zstd-sys@") + { + runs.push(script); + } + } + let status = child + .wait() + .map_err(|error| format!("cargo check did not finish: {error}"))?; + if !status.success() { + return Err("cargo check -p crypthix-core failed (see above)".to_owned()); + } + if runs.is_empty() { + return Err("the build ran no zstd-sys build script".to_owned()); + } + + let mut problems = Vec::new(); + for run in &runs { + let out_dir = run.out_dir.as_std_path(); + let reported: Vec = run + .linked_libs + .iter() + .map(|lib| Directive::Lib(lib.to_string())) + .chain( + run.linked_paths + .iter() + .map(|path| Directive::Search(path.to_string())), + ) + .collect(); + problems.extend(link_problems("cargo", &reported, out_dir)); + // The build script writes `output` beside its OUT_DIR; a links override runs none. + let output = out_dir.with_file_name("output"); + match fs::read_to_string(&output) { + Ok(text) => { + let source = output.display().to_string(); + problems.extend(link_problems(&source, &directives(&text), out_dir)); + } + Err(_) => problems.push(format!( + "no build script output beside {}: zstd-sys's build script did not run, so a \ + `links` override supplied the library", + out_dir.display() + )), + } + } + if problems.is_empty() { + println!( + "zstd link: zstd-sys links its own libzstd statically ({} build script run{})", + runs.len(), + if runs.len() == 1 { "" } else { "s" } + ); + Ok(()) + } else { + for problem in &problems { + eprintln!("zstd link: {problem}"); + } + Err(format!( + "zstd-sys does not link its vendored libzstd statically ({} problems, FS-53)", + problems.len() + )) + } +} + +/// The link directives in a build script's output: lines `cargo:KEY=VALUE` or `cargo::KEY=VALUE`. +/// Other lines (the `cc` crate's own logging) are ignored. +fn directives(output: &str) -> Vec { + output + .lines() + .filter_map(|line| { + let rest = line + .strip_prefix("cargo::") + .or_else(|| line.strip_prefix("cargo:"))?; + let (key, value) = rest.split_once('=')?; + match key { + "rustc-link-lib" => Some(Directive::Lib(value.to_owned())), + "rustc-link-search" => Some(Directive::Search(value.to_owned())), + "rustc-flags" => Some(Directive::Other(rest.to_owned())), + _ if key.starts_with("rustc-link-arg") => Some(Directive::Other(rest.to_owned())), + _ => None, + } + }) + .collect() +} + +/// What is wrong with a set of link directives: a library other than `static=zstd`, no +/// `static=zstd` at all, a search path outside `out_dir` (or none inside it), or any linker +/// argument or flag. +fn link_problems(source: &str, directives: &[Directive], out_dir: &Path) -> Vec { + let mut problems = Vec::new(); + let mut static_zstd = false; + let mut searches_out_dir = false; + for directive in directives { + match directive { + Directive::Lib(lib) if *lib == format!("static={LIBRARY}") => static_zstd = true, + Directive::Lib(lib) => { + problems.push(format!("{source} links `{lib}`, not static={LIBRARY}")); + } + Directive::Search(search) => { + // `KIND=PATH`, or a bare `PATH` (kind `all`). + let path = match search.split_once('=') { + Some(("native" | "all" | "dependency" | "crate" | "framework", path)) => path, + _ => search.as_str(), + }; + if Path::new(path).starts_with(out_dir) { + searches_out_dir = true; + } else { + problems.push(format!( + "{source} searches {path} for libraries, outside zstd-sys's OUT_DIR {}", + out_dir.display() + )); + } + } + Directive::Other(line) => { + problems.push(format!("{source} passes the linker `{line}`")); + } + } + } + if !static_zstd { + problems.push(format!("{source} does not link static={LIBRARY}")); + } + if !searches_out_dir { + problems.push(format!( + "{source} does not search zstd-sys's OUT_DIR {}", + out_dir.display() + )); + } + problems +} + +#[cfg(test)] +mod tests { + use super::*; + + const OUT_DIR: &str = "/repo/target/debug/build/zstd-sys-0123/out"; + + /// The output of a real `zstd-sys` 2.1.2 build, shortened. + fn vendored() -> String { + format!( + "cargo:rerun-if-env-changed=ZSTD_SYS_USE_PKG_CONFIG\n\ + CC_x86_64-unknown-linux-gnu = None\n\ + cargo:rerun-if-env-changed=CFLAGS\n\ + cargo:rustc-link-lib=static=zstd\n\ + cargo:rustc-link-search=native={OUT_DIR}\n\ + cargo:root={OUT_DIR}\n\ + cargo:include=/home/u/.cargo/registry/src/x/zstd-sys-2.1.2+zstd.1.5.7/zstd/lib\n" + ) + } + + fn problems(output: &str) -> Vec { + link_problems("output", &directives(output), Path::new(OUT_DIR)) + } + + #[test] + fn the_vendored_build_passes() { + assert_eq!( + directives(&vendored()), + vec![ + Directive::Lib("static=zstd".to_owned()), + Directive::Search(format!("native={OUT_DIR}")), + ] + ); + assert_eq!(problems(&vendored()), Vec::::new()); + } + + #[test] + fn the_new_directive_syntax_is_read_too() { + let output = + format!("cargo::rustc-link-lib=static=zstd\ncargo::rustc-link-search={OUT_DIR}/lib\n"); + assert_eq!(problems(&output), Vec::::new()); + } + + #[test] + fn a_system_libzstd_through_pkg_config_fails() { + let output = "cargo:rerun-if-env-changed=ZSTD_SYS_USE_PKG_CONFIG\n\ + cargo:rustc-link-search=native=/usr/lib/x86_64-linux-gnu\n\ + cargo:rustc-link-lib=zstd\n\ + cargo:include=/usr/include\n"; + let found = problems(output); + // A dynamic zstd, a /usr search path, no static zstd, no OUT_DIR search. + assert_eq!(found.len(), 4, "{found:?}"); + } + + #[test] + fn a_system_search_path_beside_the_vendored_library_fails() { + for path in [ + "/usr/lib", + "/opt/homebrew/lib", + "/lib64", + "/repo/target/debug/build", + ] { + let output = format!("{}cargo:rustc-link-search=native={path}\n", vendored()); + let found = problems(&output); + assert_eq!(found.len(), 1, "{path}: {found:?}"); + assert!(found[0].contains(path), "{found:?}"); + } + let bare = format!("{}cargo:rustc-link-search=/usr/local/lib\n", vendored()); + assert_eq!(problems(&bare).len(), 1, "a search path without a kind"); + } + + #[test] + fn a_dynamic_or_extra_library_fails() { + let dynamic = + format!("cargo:rustc-link-lib=dylib=zstd\ncargo:rustc-link-search=native={OUT_DIR}\n"); + assert_eq!(problems(&dynamic).len(), 2, "dylib, and no static zstd"); + let extra = format!("{}cargo:rustc-link-lib=static=zstd_static\n", vendored()); + assert_eq!(problems(&extra).len(), 1, "a second library"); + } + + #[test] + fn linker_arguments_fail() { + for line in [ + "cargo:rustc-link-arg=-L/usr/lib", + "cargo::rustc-link-arg-bins=-lzstd", + "cargo:rustc-flags=-l zstd -L /usr/lib", + ] { + let output = format!("{}{line}\n", vendored()); + assert_eq!(problems(&output).len(), 1, "{line}"); + } + } + + #[test] + fn empty_output_fails() { + assert_eq!(problems("").len(), 2, "no library and no search path"); + assert_eq!( + problems("CC = None\ncargo:root=/x\n").len(), + 2, + "only non-link lines" + ); + } +} From 7a102fdb913698900a45a3d322670b589143917d Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 21:57:28 +0530 Subject: [PATCH 14/15] ci: test core on Windows per PR and on Intel macOS and i686 nightly, and check the libzstd link on every platform --- .github/workflows/ci.yml | 25 +++++++++++++++++++- .github/workflows/scheduled.yml | 41 +++++++++++++++++++++++++++++---- 2 files changed, 61 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cdd8a7f..84ed582 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -67,6 +67,7 @@ jobs: - "crates/engine/core/**" - "Cargo.lock" - "rust-toolchain.toml" + - "xtask/src/zstd_link.rs" - ".github/workflows/ci.yml" kernel: - "crates/foundation/types/**" @@ -337,6 +338,27 @@ jobs: cargo clippy -p crypthix-crypto -p crypthix-core --all-features --all-targets --locked --target x86_64-pc-windows-gnu -- -D warnings + # crypthix-core's tests on Windows with MSVC, which builds libzstd with cl.exe, so a TV-07 + # mismatch or a link problem there shows up on the pull request, not the next night. + windows-test: + name: Test crypthix-core on Windows + needs: changes + # `changes` is skipped on push, so this job must not require it to succeed. + if: ${{ !cancelled() && (github.event_name == 'push' || needs.changes.outputs.crypto == 'true') }} + runs-on: windows-2025 + timeout-minutes: 30 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: ./.github/actions/setup + with: + cache-key: windows-test + - run: cargo test -p crypthix-core --all-features --locked + - run: cargo xtask check-zstd-link + # Protected key memory on a kernel with the CVE-2026-93243 fix and one without it, booted in # QEMU with virtme-ng (about 5 minutes per kernel, side by side). kernel-test: @@ -426,6 +448,7 @@ jobs: - deny - side - windows-clippy + - windows-test - kernel-test - fuzz-smoke - mutants @@ -436,5 +459,5 @@ jobs: - uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # v1.3.0 with: jobs: ${{ toJSON(needs) }} - allowed-skips: changes, pr, links, side, windows-clippy, kernel-test, fuzz-smoke, mutants + allowed-skips: changes, pr, links, side, windows-clippy, windows-test, kernel-test, fuzz-smoke, mutants allowed-failures: mutants diff --git a/.github/workflows/scheduled.yml b/.github/workflows/scheduled.yml index eec1116..44ac40a 100644 --- a/.github/workflows/scheduled.yml +++ b/.github/workflows/scheduled.yml @@ -1,8 +1,8 @@ # Nightly jobs skip the weekly cron ("47 3 * * 1") so Mondays do not run them twice. # # Long and broad checks kept off the PR path: deep fuzzing and property tests, Miri, nightly -# doctests, fresh advisories, other platforms, other kernels and coverage every night; full -# mutation testing, links, the full secret history and a runner capability probe every week. +# doctests, fresh advisories, other platforms and i686, other kernels and coverage every night; +# full mutation testing, links, the full secret history and a runner capability probe every week. # # A PR that edits this file runs it too, with short time limits, so changes are tested before # they reach the schedule. @@ -145,7 +145,11 @@ jobs: # to end (the plain_len cap, Decrypt on each AAD field, Padding, Limit, a payload of the # wrong length and Binding), since the decompressor makes its zstd context only at the # first frame. zstd is C, which Miri cannot run, so the tests that call it are ignored - # there, as are megabyte inputs and a 2 MiB window. + # there, as are megabyte inputs and a 2 MiB window. The property tests that call no zstd + # run here at their scaled-down sizes (the cut loop, Chunks, StreamChunker against memory, + # Padmé and the inner plaintext under mutation); under Miri their byte inputs come from + # one drawn seed at half the length (test_data::bytes), since proptest's tree of one value + # per byte cost more than the tests. The crypthix-core tests take about 4.5 minutes. - name: cargo miri test env: MIRIFLAGS: -Zmiri-disable-isolation @@ -187,7 +191,9 @@ jobs: strategy: fail-fast: false matrix: - os: [macos-15, windows-2025, ubuntu-24.04-arm] + # macos-15-intel builds zstd's x86_64 assembly (the Huffman decoder) with Apple clang, + # which neither the Arm macOS runner nor Linux does. + os: [macos-15, macos-15-intel, windows-2025, ubuntu-24.04-arm] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -202,6 +208,33 @@ jobs: - run: >- cargo clippy -p crypthix-crypto -p crypthix-core --all-features --all-targets --locked -- -D warnings + # The libzstd the tests ran against is the one zstd-sys built, linked statically, with + # this platform's C compiler and archiver. + - run: cargo xtask check-zstd-link + + # 32-bit x86: usize is 4 bytes, and zstd's encoder takes 32-bit code paths whose output must + # still be the bytes TV-07 pins. Runs on x86_64 Linux with the multilib C toolchain. + i686: + name: Test crypthix-core on i686 Linux + if: github.event.schedule != '47 3 * * 1' + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: ./.github/actions/setup + with: + cache-key: i686 + - name: Install the i686 target and gcc-multilib + run: | + rustup target add i686-unknown-linux-gnu + sudo apt-get update + sudo apt-get install -y --no-install-recommends gcc-multilib + - run: cargo test -p crypthix-core --all-features --locked --target i686-unknown-linux-gnu + - run: cargo xtask check-zstd-link --target i686-unknown-linux-gnu # The crypto tests in kernels with and without the CVE-2026-93243 fix (kernel-test.yml), so # the nightly run also notices a change on the runner image or in the tools that breaks them. From 470c1057ca3a8928df8f27ddf7892d8708020b2f Mon Sep 17 00:00:00 2001 From: thearpankumar Date: Tue, 10 Nov 2026 21:57:28 +0530 Subject: [PATCH 15/15] =?UTF-8?q?docs:=20correct=20the=20zstd=20version,?= =?UTF-8?q?=20limit=20and=20Padm=C3=A9=20leak=20claims,=20add=20the=20dedu?= =?UTF-8?q?p=20injection=20residual=20and=20OQ-19,=20record=20chunk=20reus?= =?UTF-8?q?e=20for=20the=20pipeline?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/CONTRIBUTING.md | 4 ++-- docs/backlog.md | 8 ++++---- docs/format-spec.md | 35 +++++++++++++++++++---------------- docs/project-vision.md | 10 +++++----- docs/style-guide.md | 7 ++++--- docs/threat-model.md | 13 +++++++------ 6 files changed, 41 insertions(+), 36 deletions(-) diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index e5abba8..53363e1 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -32,12 +32,12 @@ Every job in [`.github/workflows/ci.yml`](../.github/workflows/ci.yml) runs one | `lint` | Formatting of both workspaces, layer rules, `check-docs`, `check-vendored`, typos and workflow lint | [typos](https://github.com/crate-ci/typos), [actionlint](https://github.com/rhysd/actionlint), [zizmor](https://docs.zizmor.sh) | | `pr` (pull requests only) | Commit messages, file hygiene and secrets of the commits after `--base` (default `origin/master`) | gitleaks | | `clippy` | Clippy on both workspaces, warnings as errors | | -| `test` | Main workspace tests (nextest) and doctests | [cargo-nextest](https://nexte.st) | +| `test` | Main workspace tests (nextest) and doctests, then `check-zstd-link` (zstd-sys linked its own libzstd statically) | [cargo-nextest](https://nexte.st) | | `doc` | Rustdoc, warnings as errors | | | `deny` | cargo-deny on both lockfiles, unused dependencies | cargo-deny, [cargo-shear](https://github.com/Boshen/cargo-shear) | | `side` | The `tests/` workspace tests and `vectors --check` | | -Pull requests also get an external link check ([lychee](https://lychee.cli.rs), `lychee.toml`) of the Markdown files they change, a 20-second fuzz run of every target when a parser or the fuzz harness changes, and an advisory mutation test of the changed lines (cargo-mutants). These jobs and `pr` look at what a pull request changes, so they do not run on pushes to master, whose commits a pull request already checked. Each tool's `cargo xtask` error names how to install it. When `crypthix-crypto`, `crypthix-types` or `crypthix-core` changes, and on master, `windows-clippy` lints `crypthix-crypto` and `crypthix-core` for `x86_64-pc-windows-gnu`, cross-compiled on Linux, so the code `secure_mem` compiles on other systems, and the libzstd that `crypthix-core` builds from source, are checked before the nightly platform runs; locally that is `cargo clippy -p crypthix-crypto -p crypthix-core --all-features --all-targets --target x86_64-pc-windows-gnu -- -D warnings`, with the target added (`rustup target add x86_64-pc-windows-gnu`) and MinGW's `x86_64-w64-mingw32-gcc` installed. +Pull requests also get an external link check ([lychee](https://lychee.cli.rs), `lychee.toml`) of the Markdown files they change, a 20-second fuzz run of every target when a parser or the fuzz harness changes, and an advisory mutation test of the changed lines (cargo-mutants). These jobs and `pr` look at what a pull request changes, so they do not run on pushes to master, whose commits a pull request already checked. Each tool's `cargo xtask` error names how to install it. When `crypthix-crypto`, `crypthix-types` or `crypthix-core` changes, and on master, `windows-clippy` lints `crypthix-crypto` and `crypthix-core` for `x86_64-pc-windows-gnu`, cross-compiled on Linux, so the code `secure_mem` compiles on other systems, and the libzstd that `crypthix-core` builds from source, are checked before the nightly platform runs; locally that is `cargo clippy -p crypthix-crypto -p crypthix-core --all-features --all-targets --target x86_64-pc-windows-gnu -- -D warnings`, with the target added (`rustup target add x86_64-pc-windows-gnu`) and MinGW's `x86_64-w64-mingw32-gcc` installed. The same changes run `windows-test`: the `crypthix-core` tests, TV-07's pinned frames among them, on Windows with MSVC, then `cargo xtask check-zstd-link`. Every night the workspace tests run on macOS (Arm and Intel), Windows and Arm Linux, and `crypthix-core`'s on 32-bit i686 Linux (through `gcc-multilib`), each followed by `check-zstd-link`. ### Kernel test diff --git a/docs/backlog.md b/docs/backlog.md index ea58682..c5cd785 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -22,8 +22,8 @@ Each phase ends with a [threat-model review](threat-model.md#15-did-we-do-a-good - [x] **Crypto wrappers (E4)** — Thin wrappers over audited crates for suite `0x0001`: XChaCha20-Poly1305 inside the committing CX-AEAD, HKDF-SHA-256, BLAKE3, Argon2id, Ed25519 with strict verification; zeroizing key types; known-answer runners over the vendored Wycheproof, BLAKE3 and ed25519-speccheck vectors and the RFC vectors transcribed with them (TV-01); the seeded `ChaCha20Rng` `test-rng` stream for the vector generator, with a build check that no release binary enables it (FS-01, FS-94); no other crate calls crypto libraries directly, and `cargo-deny` also bans `curve25519-dalek`, `subtle`, `getrandom`, the `rand` crates and the lower-level primitive crates outside this crate. cargo-deny `wrappers` allow only direct parents, so these entries list the audited crates that pull them in (for example `ed25519-dalek`), and `getrandom` stays allowed for dev-dependencies such as `proptest`. Covers key commitment (M-9), keys, IDs and the randomness every nonce is hedged with straight from the kernel's `getrandom` (M-36), the HKDF label registry, signature context prefixes and Ed25519 `verify_strict` (M-37), and vector sets TV-01, TV-04 and TV-05 ([format spec 4.2](format-spec.md#42-suite-0x0001), [7](format-spec.md#7-domain-separation-and-committing-aead)). Decides OQ-13 (FIPS mode): no FIPS mode in format 0. Also landed: every nonce hedged with the key, AAD and plaintext (FS-29), so a VM restored without a VM generation ID cannot repeat a nonce for different data (T-81); TV-04 and TV-05 computed by a second implementation in the vector generator, `cx_open` and `verifying_key` fuzz targets, the `check-features` release check, and FS-14 rejecting mixed-order keys. Moved to the key hierarchy item: `KeyProvider`. `foundation/crypthix-crypto` - [x] **Protected key memory (O1)** — Key buffers in `memfd_secret`, `mlock`, excluded from core dumps, with a fallback on older kernels; covers derived keys and plaintext buffers too, not only the root key (T-31). Landed as `crypthix-crypto::secure_mem`, Linux only; heap elsewhere (plain heap memory, wiped on free, reported as `Fallback::Platform`, and an `init` minimum above `Heap` fails there) until A11 and A12 port it. Every key type, derived or unwrapped, is filled in place in a 32-byte slot of one process-wide pool, at the strongest level the system gives (`memfd_secret`, then `mlock`, then `MADV_DONTDUMP` alone) and never below the minimum an app passes to `secure_mem::init`, which keeps that minimum even when it fails. Opened plaintext, signature inputs and passphrases are `SecretBuf`s, Argon2id memory a vector of the same mappings: `mlock`ed, else only dump-excluded, never on the heap and never in secret pages, which pinned-page I/O (`O_DIRECT`, FUSE `splice`) refuses with `EFAULT` (full reasons in the [`secure_mem` module docs](../crates/foundation/crypto/src/secure_mem/mod.rs)). Everything is `MADV_DONTDUMP` and `MADV_DONTFORK`, behind guard pages and wiped on free. Keys and buffers lock separate shares of `RLIMIT_MEMLOCK`, with enough kept for the pool's every page and guard page, so plaintext cannot push a key arena down a level; the pool, and with it that reserve, is set up before anything locks, by `init` or else with the defaults by the first key or plaintext buffer, after which `init` fails with `AlreadyInitialised` rather than keep less than it asks for, and `secure_mem::status` never sets it up (it reports `initialised: false` until then); secret pages are faulted in through the raw `getrandom` system call, so a kernel that charges them past its limit makes the arena fall back a level instead of raising `SIGBUS`; this relies on copying system calls reaching secret pages, and an `EFAULT` there is reported as `LockLimit`. Keys and buffers do not survive `fork` without `exec`: on Linux the child cannot read them (a `MADV_WIPEONFORK` generation marker tells it what it inherited) and starts an empty pool and lock budget of its own. A buffer the kernel will not map is an error, not an abort: `cx_aead::open` returns `OpenError::Memory` (never the opaque `Decrypt`, and only after the commitment holds), `SigningKey::sign` and `Passphrase::new` return the `MemError` and `VerifyingKey::verify` returns `VerifyError::Memory` (`Passphrase::new` wipes its `String` either way). `secure_mem::status` reports the levels and the `Fallback` reasons of keys and buffers for `crypthix status` and M-13. Moved to the daemon item: `PR_SET_DUMPABLE=0`, `LimitMEMLOCK`, `memfd_secret` in its syscall filter and the minimum level (OQ-18); to M-11 (O3): dropping keys before hibernation, which needs a way to unmap key arenas, since a process that made a key in `memfd_secret` memory blocks hibernation until it exits. Left as is: copies left by moves and stack spills, short-lived and not reliably wiped; and the working state of the cipher and MAC code (CX-AEAD's `K_enc` and `K_n`, the HKDF PRK, the expanded Ed25519 key), on the stack for a whole call and wiped on drop. `foundation/crypthix-crypto` -- [x] **Chunking, compression and padding (E1, E2, E3)** — FastCDC chunking with secret per-vault parameters (M-39), zstd with auto-skip for already-compressed data and per-chunk compression only (T-40), Padmé padding to size buckets; deduplication only inside one ordinary object and never for secret files (T-85, FS-55); TV-07 ([format spec 10.1–10.4](format-spec.md#10-data-path-chunks-blobs-packs-and-shards)). Landed as `crypthix-core`'s `chunk`, `compress`, `pad`, `inner` and `blob` modules. The chunker is our own two-byte FastCDC 2020 loop over a gear table derived from `chunker_seed` and kept in a `SecretBuf`, cutting where `fastcdc` 5.0.0 does (a differential test and the cut rule now written out in FS-52), over memory (`Chunks`) or a reader (`StreamChunker`, a 2 MiB window that also tells whether a chunk is the last). Both take the object's class: secret-class objects are cut at fixed 1 MiB steps with no gear-table lookup (FS-52, after review: the FastCDC loop leaks bits of the bytes through cache timing and secret objects never deduplicate), and the chunker's `ObjectShape` carries the class, which `ObjectSealer::new` takes from it, so an object is sealed in the class it was cut in. Compression uses `zstd-safe` 8.2.0 with the libzstd 1.5.7 it bundles, built from source (cargo-deny allows it only in `crypthix-core` and the `tests/` tools and bans its `pkg-config`, `non-cargo`, `cmake`, `debug`, `legacy`, `zdict_builder`, `experimental`, `zstdmt`, `seekable` and `bindgen` features; `cargo xtask check-features` rejects `ZSTD_SYS_USE_PKG_CONFIG` and a `links` override for `zstd`, but only in the repository's own build environment, not in a user-level `~/.cargo/config.toml`, `$CARGO_HOME` or `--config`); the backstop for those is the runtime check in `Compressor::new` and in `Decompressor::decode` before its first call into libzstd (the decompressor makes its context lazily, so raw-only reads never call libzstd), which fail with `CompressError::Version` if another libzstd is linked. A frame is kept only if it saves 1/16, never for the secret class, and a zstd error fails the write instead of storing raw. Readers check a frame before decoding it (one frame, zstd magic, no checksum, dictionary ID, unused or reserved bit, content size equal to `plain_len` in the shortest field that holds it, a window of at most 2^20 bytes) and decode into a buffer of exactly `plain_len`. Plaintext, frames and inner plaintexts live only in `SecretBuf`s. Data blobs open in the order of FS-56: `plain_len` cap (`Decompress`), CX-AEAD (`Decrypt`), inner plaintext in the order of FS-54 (at least the 6 header bytes, `comp` 0 or 1 and `rsv` 0, each `Padding`; `payload_len` over 2^20, `Limit`; the total length exactly `padme(6 + payload_len)`, then every pad byte zero, each `Padding`), a compressed chunk of a secret object (`Padding`), the payload (`Decompress`), a keyed blob ID (`Binding`, constant time). Deviations, written into format spec v0.8: a blob ID is keyed exactly for an ordinary object of two or more chunks (`BlobIdKind::for_object`), since a reader cannot tell keyed from random IDs and so derives the kind from the manifest; the kind is fixed once per object, by an `ObjectSealer` from the chunker's `ObjectShape` (which a caller cannot make) and by an `ObjectOpener` from the manifest's class and chunk count, both over `ChunkKeys` that carry the `BlobContext` they were derived for, so a single-chunk object can never get keyed IDs and one object's keys never meet another's AAD; the policy switch for reuse is dropped, as a path that must not reuse chunks is secret class. Meta blobs (FS-57) are sealed and opened here too, under a `MetaKey` that carries the vault, kind and epoch it was derived for. `StreamChunker` is fused on error, so an input it could not read to the end is never taken as complete. TV-07 is generated with an independent byte-at-a-time chunker and hand-built zstd frames; fuzz targets `inner_plaintext`, `decompress`, `data_blob_open` and `chunker`; criterion benches for chunking and the inner plaintext. Moved to the encrypt pipeline item: zstd's working memory in protected memory (on the C heap until then, R-26) and `SecretBuf` pooling; to the key hierarchy item: loading `chunker_seed` and the DEKs from the sealed config and key table into `KdfKey`s, which `crypthix-core` takes as inputs until then. `engine/crypthix-core` -- [ ] **Encrypt pipeline and signed manifests (E4, E5)** — Data and meta blobs, size-class packs, shards, device-signed manifests with Merkle trees, the path index and the signed vault root (M-8, M-9, M-39, M-40); shard IDs and pack hashes checked before decoding (T-47); read-after-write check (M-45); full write and read path, which reuses its `SecretBuf`s or pools small ones rather than map one per chunk, since each is its own mapping (measure first); zstd's working memory in protected memory (R-26: today on the C heap, not wiped, locked or `MADV_DONTFORK`), through a `ZSTD_customMem` allocator backed by `secure_mem` in `crypthix-crypto`, since `zstd-safe` cannot place it without `unsafe`; vector sets TV-10 to TV-13 (shards with k = 1) and TV-21 ([format spec 10](format-spec.md#10-data-path-chunks-blobs-packs-and-shards), [11](format-spec.md#11-object-manifest), [12](format-spec.md#12-path-index), [14](format-spec.md#14-signed-vault-root-and-monotonicity)). Opens W5: per-device monotonicity only until E18 ([format spec 2.2](format-spec.md#22-limits-of-format-0-in-phase-1)). `engine/crypthix-core` +- [x] **Chunking, compression and padding (E1, E2, E3)** — FastCDC chunking with secret per-vault parameters (M-39), zstd per chunk only, every ordinary chunk trial-compressed and stored raw when zstd saves under 1/16, so already-compressed data stays raw (T-40), Padmé padding to size buckets; deduplication only inside one ordinary object and never for secret files (T-85, FS-55); TV-07 ([format spec 10.1–10.4](format-spec.md#10-data-path-chunks-blobs-packs-and-shards)). Landed as `crypthix-core`'s `chunk`, `compress`, `pad`, `inner` and `blob` modules. The chunker is our own two-byte FastCDC 2020 loop over a gear table derived from `chunker_seed` and kept in a `SecretBuf`, cutting where `fastcdc` 5.0.0 does (a differential test and the cut rule now written out in FS-52), over memory (`Chunks`) or a reader (`StreamChunker`, a 2 MiB window that also tells whether a chunk is the last). Both take the object's class: secret-class objects are cut at fixed 1 MiB steps with no gear-table lookup (FS-52, after review: the FastCDC loop leaks bits of the bytes through cache timing and secret objects never deduplicate), and the chunker's `ObjectShape` carries the class, which `ObjectSealer::new` takes from it, so an object is sealed in the class it was cut in. Compression uses `zstd-safe` 8.2.0 with the libzstd 1.5.7 it bundles, built from source (cargo-deny allows it only in `crypthix-core` and the `tests/` tools and, after review, holds `zstd-sys` and `zstd-safe` to an exact, empty feature allow list rather than a deny list, so no `pkg-config`, `non-cargo`, `cmake`, `debug`, `legacy`, `zdict_builder`, `experimental`, `zstdmt`, `seekable`, `bindgen` or `with-rust-allocator`, and no feature a later release adds; `cargo xtask check-features` rejects `ZSTD_SYS_USE_PKG_CONFIG`, a `links` override for `zstd`, a `--cfg feature=` in any `RUSTFLAGS` variable including `CARGO_TARGET__RUSTFLAGS` or in config `rustflags`, a `[patch]` or `[replace]` of the zstd crates and any `paths` override, but only in the repository's own build environment, not in a user-level `~/.cargo/config.toml`, `$CARGO_HOME` or `--config`; `cargo xtask check-zstd-link`, run after the tests in CI on Linux, Windows, macOS Arm and Intel, Arm Linux and i686, checks from the build script's output that `zstd-sys` linked only `static=zstd` from its own `OUT_DIR`, which the version check cannot tell from a system libzstd 1.5.7); the backstop for those is the runtime check in `Compressor::new` and in `Decompressor::decode` before its first call into libzstd (the decompressor makes its context lazily, so raw-only reads never call libzstd), which fail with `CompressError::Version` if another libzstd is linked. A frame is kept only if it saves 1/16, never for the secret class, and a zstd error fails the write instead of storing raw. Readers check a frame before decoding it (one frame, zstd magic, no checksum, dictionary ID, unused or reserved bit, content size equal to `plain_len` in the shortest field that holds it, a window of at most 2^20 bytes) and decode into a buffer of exactly `plain_len`. Plaintext, frames and inner plaintexts live only in `SecretBuf`s. Data blobs open in the order of FS-56: `plain_len` cap (`Decompress`), CX-AEAD (`Decrypt`), inner plaintext in the order of FS-54 (at least the 6 header bytes, `comp` 0 or 1 and `rsv` 0, each `Padding`; `payload_len` over 2^20, `Limit`; the total length exactly `padme(6 + payload_len)`, then every pad byte zero, each `Padding`), a compressed chunk of a secret object (`Padding`), the payload (`Decompress`), a keyed blob ID (`Binding`, constant time). Deviations, written into format spec v0.8: a blob ID is keyed exactly for an ordinary object of two or more chunks (`BlobIdKind::for_object`), since a reader cannot tell keyed from random IDs and so derives the kind from the manifest; the kind is fixed once per object, by an `ObjectSealer` from the chunker's `ObjectShape` (which a caller cannot make) and by an `ObjectOpener` from the manifest's class and chunk count, both over `ChunkKeys` that carry the `BlobContext` they were derived for, so one object's keys never meet another's AAD; after review, the sealer takes only the chunker's `ChunkRef`s (`StreamChunker::next_chunk`, `Chunks::chunk_refs`) of its shape, in order, and its `finish` fails unless the last chunk was sealed and gives the manifest's chunk count, so a chunk the chunker cut as an object's only chunk never gets a keyed ID; `ObjectSealer::identify` gives a chunk's keyed ID before it is sealed, and `seal_identified` and `reuse` take that identification back from the same sealer only, for E1 reuse, which itself moved to the encrypt pipeline item; the keys, the AADs, the raw cut and the scaled chunkers are crate-private, exposed only by `crypthix-core`'s test-only `vectors` feature for the TV-07 runner and the fuzz targets, which `cargo xtask check-features` keeps out of release builds like `crypthix-crypto`'s; the policy switch for reuse is dropped, as a path that must not reuse chunks is secret class. Meta blobs (FS-57) are sealed and opened here too, under a `MetaKey` that carries the vault, kind and epoch it was derived for. `StreamChunker` is fused on error, so an input it could not read to the end is never taken as complete. TV-07 is generated with an independent byte-at-a-time chunker and hand-built zstd frames; fuzz targets `inner_plaintext`, `decompress`, `data_blob_open` and `chunker`; criterion benches for chunking and the inner plaintext. Moved to the encrypt pipeline item: zstd's working memory in protected memory (on the C heap until then, R-26) and `SecretBuf` pooling; to the key hierarchy item: loading `chunker_seed` and the DEKs from the sealed config and key table into `KdfKey`s, which `crypthix-core` takes as inputs until then. `engine/crypthix-core` +- [ ] **Encrypt pipeline and signed manifests (E4, E5)** — Data and meta blobs, size-class packs, shards, device-signed manifests with Merkle trees, the path index and the signed vault root (M-8, M-9, M-39, M-40); shard IDs and pack hashes checked before decoding (T-47); read-after-write check (M-45); full write and read path, with chunk reuse (E1, FS-55): before sealing a chunk of a keyed object, look its keyed blob ID (`ObjectSealer::identify`) up in the current version and the previous version of the same object, and on a hit record the stored blob through `ObjectSealer::reuse` instead of sealing it again, which also stores equal chunks of one version as one blob; the full write and read path reuses its `SecretBuf`s or pools small ones rather than map one per chunk, since each is its own mapping (measure first); zstd's working memory in protected memory (R-26: today on the C heap, not wiped, locked or `MADV_DONTFORK`), through a `ZSTD_customMem` allocator backed by `secure_mem` in `crypthix-crypto`, since `zstd-safe` cannot place it without `unsafe`; vector sets TV-10 to TV-13 (shards with k = 1) and TV-21 ([format spec 10](format-spec.md#10-data-path-chunks-blobs-packs-and-shards), [11](format-spec.md#11-object-manifest), [12](format-spec.md#12-path-index), [14](format-spec.md#14-signed-vault-root-and-monotonicity)). Opens W5: per-device monotonicity only until E18 ([format spec 2.2](format-spec.md#22-limits-of-format-0-in-phase-1)). `engine/crypthix-core` - [ ] **Key hierarchy (E6)** — Root key → random keyring → random epoch KEKs (M-34) → per-object DEKs; vault signing key and the first device certificate (M-14); passphrase share slot and printed recovery share (M-10, M-18, M-35); wrapped key storage; `KeyProvider` in `crypthix-crypto`, the trait engine crates use to reach epoch KEKs, DEKs and pack keys, where a missed lookup is `MissingKey` and never a stand-in key (rule 5, FS-30); binding each wrapped key's type to its AAD label in `seal_key` and `open_key`, so a DEK wrap cannot be unwrapped as another key type (FS-25); loading `chunker_seed` from the sealed config ([format spec 13.1](format-spec.md#131-vault-config)) and the DEKs into `KdfKey`s for `crypthix-core`; the Unicode normalization of passphrases (section 9.1); root rotation (FS-39); vector sets TV-06, TV-08, TV-09, TV-14 and TV-16 with t = 1 ([format spec 8](format-spec.md#8-key-hierarchy), [9](format-spec.md#9-key-files), [13](format-spec.md#13-vault-config-and-devices)). Opens W4 (rotation is a KEK re-wrap only) and W6 (the passphrase or recovery sheet alone is the root). `engine/crypthix-keys` - [ ] **Local storage backend** — Shard, key-file and vault-root I/O on `/var/lib/crypthix//store` behind the `Backend` trait; commit order with compare-and-swap on the root (M-44), crash-tested at every commit step with `crypthix-testkit`, plus torn-write and lost-unsynced-data faults below the `Backend` trait for the file I/O itself. The local backend may use std and `rustix` file APIs behind `cfg(target_os = "linux")`, without `unsafe`, as an exception to rule 4. Directory layout, store names, the single-writer lock and two-phase garbage collection (FS-89, FS-91, FS-92); root sequences checked per device (TV-15); the golden tiny vault, crash and GC vectors (TV-20) ([format spec 14](format-spec.md#14-signed-vault-root-and-monotonicity), [17](format-spec.md#17-commit-rotation-and-garbage-collection), [18](format-spec.md#18-directory-layout)). `engine/crypthix-store` - [ ] **Automatic KEK rotation (E7)** — Scheduled re-wrap of DEKs and pack keys and re-seal of the encrypted trees under a new epoch KEK, in the background (daily by default, [format spec FS-90](format-spec.md#17-commit-rotation-and-garbage-collection)). `engine/crypthix-keys` @@ -32,10 +32,10 @@ Each phase ends with a [threat-model review](threat-model.md#15-did-we-do-a-good ## Phase 2: Workspace MVP → 0.1 alpha -- [ ] **Daemon and local API** — `crypthixd` process that owns keys and wires all crates; JSON-over-Unix-socket API for CLI and extension. Runs as its own system user that owns the store and config, checks socket peers with `SO_PEERCRED` and pidfd, fails closed, and reports Full or Degraded hardening mode (M-13, M-15). Calls `secure_mem::init(Config::default().with_minimum(..))` before the first key or plaintext buffer (a passphrase too; a later `init` fails with `AlreadyInitialised`) and shows `secure_mem::status` in the hardening mode; never forks after making keys without `exec`, since keys do not survive into the child; sets `PR_SET_DUMPABLE=0`, and its unit sets `LimitMEMLOCK=` and allows `memfd_secret` in `SystemCallFilter=` (T-31). Decides OQ-7 (daemon capabilities and users) and OQ-18 (the minimum protection level). Opens W11 (Degraded mode wherever BPF-LSM is off). A root helper mounts the vault and brokers caller identity (M-20, M-21); keys live in a separate key-holder process (M-29). A `cargo-fuzz` target for API messages (M-29). `apps/crypthixd`, `access/crypthix-api` +- [ ] **Daemon and local API** — `crypthixd` process that owns keys and wires all crates; JSON-over-Unix-socket API for CLI and extension. Runs as its own system user that owns the store and config, checks socket peers with `SO_PEERCRED` and pidfd, fails closed, and reports Full or Degraded hardening mode (M-13, M-15). Calls `secure_mem::init(Config::default().with_minimum(..))` before the first key or plaintext buffer (a passphrase too; a later `init` fails with `AlreadyInitialised`) and shows `secure_mem::status` in the hardening mode; never forks after making keys without `exec`, since keys do not survive into the child; sets `PR_SET_DUMPABLE=0` and `RLIMIT_CORE` to 0, which also keep zstd's unwiped working memory out of core dumps until the encrypt pipeline item moves it to protected memory (R-26), and its unit sets `LimitMEMLOCK=` and allows `memfd_secret` in `SystemCallFilter=` (T-31). Decides OQ-7 (daemon capabilities and users) and OQ-18 (the minimum protection level). Opens W11 (Degraded mode wherever BPF-LSM is off). A root helper mounts the vault and brokers caller identity (M-20, M-21); keys live in a separate key-holder process (M-29). A `cargo-fuzz` target for API messages (M-29). `apps/crypthixd`, `access/crypthix-api` - [ ] **Transparent encrypted folder (A1)** — FUSE mount backed by the engine; open, read, write, rename, delete, mmap-safe; `crypthix mount`. Secret paths use direct I/O with no shared page cache; the caller's UID is checked on every request; lookups and listings follow the same policy (M-1, M-15, M-23); writes the manifest's `fs_attrs` field (*Reserved P2*, [format spec 11](format-spec.md#11-object-manifest)). A `cargo-fuzz` target for FUSE requests (M-29). Decides OQ-14 (`getxattr` leaks). Opens W2: not ransomware-safe until snapshots. `access/crypthix-fs` - [ ] **Program identity resolution** — Caller PID → exe path, binary hash (cached), parent chain, uid, cgroup. pidfd and start-time checks against PID reuse; identity by exe device, inode and hash, never by process name; launch-environment check; reads the exec-time record of the root helper in Full mode (M-2, M-3, M-17, M-20). Decides OQ-3 (container profiles). `access/crypthix-policy` -- [ ] **Per-program policy engine (A2)** — `policy.toml` rules by program and path, most-specific-first matching, default ask for unknown programs and deny for secret paths. Policy changes only through the API (M-7); files that steer allowed programs are protected (M-6); identity by exe, never name (M-3); lookups and listings gated too (M-23); interpreter grants bound to a project and an interactive launch (M-25); no secrets for editors and browsers by default (M-26); per-path rules that make paths of mixed trust (mail stores, chat and app SQLite databases, browser profiles) secret class or store them uncompressed, the recourse for T-40's residual in ordinary objects ([format spec FS-53](format-spec.md#102-compression)). Opens W1 until O4 and O5. `access/crypthix-policy` +- [ ] **Per-program policy engine (A2)** — `policy.toml` rules by program and path, most-specific-first matching, default ask for unknown programs and deny for secret paths. Policy changes only through the API (M-7); files that steer allowed programs are protected (M-6); identity by exe, never name (M-3); lookups and listings gated too (M-23); interpreter grants bound to a project and an interactive launch (M-25); no secrets for editors and browsers by default (M-26); per-path rules that make paths of mixed trust (mail stores, chat and app SQLite databases, browser profiles, logs) secret class or store them uncompressed, the recourse for T-40's and T-85's residuals in ordinary objects ([format spec FS-53, FS-55](format-spec.md#102-compression)); an ordinary path that is never compressed needs a new `crypthix-core` API, a no-compress mode for `ObjectSealer`, since today every ordinary chunk is trial-compressed. Opens W1 until O4 and O5. `access/crypthix-policy` - [ ] **First-use prompts and deny log (A3, A4)** — Allow once / always / deny prompts via the API, never accepted from the VS Code extension alone (M-26); every denial logged with its process tree, rate-limited and aggregated; approvals recorded with the approving identity and presence method, signed once E12 lands (M-31). `access/crypthix-policy`, `access/crypthix-api` - [ ] **Protected admin actions (A14)** — Loosening policy, unfreezing, deleting snapshots, adding devices and disabling the guard require user presence (passphrase or OS authentication), so malware running as the user cannot switch protection off. Passphrase or polkit first; FIDO2 touch or second-device confirmation later (M-5). Policy and guard config change only here (M-7). Opens W3: passphrase or polkit presence can be faked by same-user code. `access/crypthix-api`, `access/crypthix-policy` - [ ] **AI coding agent guard (U1)** — Agent profiles matching process trees (Claude Code, Cursor, Codex); deny secrets, allow code; per-agent access feed. `crypthix agent run` cgroup launcher and own-exe matching (M-4), agent configs protected as steering files (M-6), agent-write taint (M-24), no secrets for editors and browsers by default (M-26), agent options that keep secrets out of transcripts (M-27); stated as best effort. Decides OQ-8 (agent sandboxes). `access/crypthix-policy` diff --git a/docs/format-spec.md b/docs/format-spec.md index 22bd21f..c0188e1 100644 --- a/docs/format-spec.md +++ b/docs/format-spec.md @@ -111,7 +111,7 @@ Field-table columns: **Key** is the CBOR map key (negative = critical, [FS-09](# | Number of packs, their size classes and write times; shard sizes and counts | Storage itself (R-5) | | An upper bound on how much changed per commit | Pack count and size class per commit | | Whether a commit reused chunks of an ordinary file | Fewer new data packs (residual of [FS-55](#104-blobs)) | -| How many chunks of one version of an ordinary file repeat, for example runs of zeros cut at 1 MiB that share one keyed ID, which point to sparse regions | Fewer blobs than the file's size needs (residual of [FS-55](#104-blobs)) | +| How many chunks of one version of an ordinary file repeat, for example runs of zeros cut at 1 MiB that share one keyed ID, which point to sparse regions | Less new pack space than the file's size needs (residual of [FS-55](#104-blobs)) | | For a commit that changes one file: that file's approximate size and its set of packs | The commit's new packs are that file (Padmé bounds the leak per chunk, not per commit) | | When shards are written and deleted, and which were written and deleted together; when compaction runs | Storage itself; garbage collection ([FS-91](#17-commit-rotation-and-garbage-collection)) | | Key-management events: a root rotation (new `vault_id` and keyring), a passphrase change (rewritten slot), a revocation (device-set status) | Clear key files and device sets | @@ -299,10 +299,11 @@ Bodies are CBOR ([RFC 8949](https://www.rfc-editor.org/rfc/rfc8949)) except wher | Items in one document, counted recursively | 2^22; every head counts once, containers included, so a map entry counts as two | | One byte string | 16 MiB | | Decompressed chunk | `plain_len` from the manifest, at most 1 MiB ([FS-53](#102-compression)) | +| Inner plaintext payload | `payload_len` at most 2^20 ([FS-54](#103-padding-and-inner-plaintext)) | | Tree fan-out (index, key-table, location and pack-table nodes) | 4,096 entries per node | | Tree depth | 16 | -Exceeding a limit is `Limit`. A declared string length or container count larger than the bytes left in the document is `Limit` too, decided at that item's head, before anything is read or allocated for it; input that ends inside a head is `Truncated`. +Exceeding a limit is `Limit`, except a `plain_len` above 2^20, which is `Decompress` (FS-53). A declared string length or container count larger than the bytes left in the document is `Limit` too, decided at that item's head, before anything is read or allocated for it; input that ends inside a head is `Truncated`. ### 5.3 AAD, KDF context and signature input @@ -695,17 +696,17 @@ pack-key wrap, key K_pkwrap_e: 3. For each byte position `i` from `2⌊min/2⌋` up to but not including `2⌊end/2⌋`, set `h = (h << 1) + gear[b_i] mod 2^64`, where `b_i` is the byte at `i`. The mask is `MASK_S` while `i < 2⌊center/2⌋` and `MASK_L` after. If `h & mask = 0`, the chunk is bytes `0` to `i − 1`: the cut comes just before the byte that matched. 4. If no position matches, the chunk is the first `end` bytes, so a chunk is cut at `max` at the latest. An odd last byte is never tested, so it is never a cut point. -The next chunk is cut the same way from where this one ends. This is the cut rule of `fastcdc::v2020::cut_gear` in the `fastcdc` crate 5.0.0, which takes two bytes per step with a shifted table and shifted masks and cuts at the same places; `fastcdc` 3.x differs at odd tails. The masks are fixed here, not chosen by the crate's `select_masks`, which computes them through floating point. TV-07 checks the boundaries against a second chunker in the generator that takes one byte per step. `chunker_seed` is 32 random bytes in the sealed part of the config, so backends cannot recompute boundaries. The design assumes the seed may still leak, since keyed gear tables have been recovered from observed chunk sizes ([ePrint 2025/558](https://eprint.iacr.org/2025/558)); a writer keeps the table in protected plaintext memory (a `SecretBuf`: locked where the memory limit allows, out of core dumps, wiped on free), not in the secret pages that hold keys (FS-31). Packs (FS-59) are what hide the sizes; Padmé (FS-54) only coarsens them, to steps of 8 KiB for a 256 KiB chunk and 32 KiB for a 1 MiB one, so about 5 bits of each chunk's length stay visible in any blob seen outside a pack, as every blob is until packs land with the encrypt pipeline item (M-39, T-84, R-5). +The next chunk is cut the same way from where this one ends. This is the cut rule of `fastcdc::v2020::cut_gear` in the `fastcdc` crate 5.0.0, which takes two bytes per step with a shifted table and shifted masks and cuts at the same places; `fastcdc` 3.x differs at odd tails. The masks are fixed here, not chosen by the crate's `select_masks`, which computes them through floating point. TV-07 checks the boundaries against a second chunker in the generator that takes one byte per step. `chunker_seed` is 32 random bytes in the sealed part of the config, so backends cannot recompute boundaries. The design assumes the seed may still leak, since keyed gear tables have been recovered from observed chunk sizes ([ePrint 2025/558](https://eprint.iacr.org/2025/558)); a writer keeps the table in plaintext memory (a `SecretBuf`: wiped on free and, on Linux, locked where the memory limit allows and out of core dumps; plain heap memory elsewhere), not in the secret pages that hold keys (FS-31). Packs (FS-59) are what hide the sizes; Padmé (FS-54) only coarsens them, to steps of 8 KiB for a 256 KiB chunk and 32 KiB for a 1 MiB one, so about 7 bits of each chunk's length stay visible in any blob seen outside a pack (5 significant bits and the octave: 129 padded lengths between 64 KiB and 1 MiB), as every blob is until packs land with the encrypt pipeline item (M-39, T-84, R-5). Objects of the secret class (FS-55) are not cut by this rule. They are cut into chunks of exactly `max` = 1 MiB from the start, with the remainder as a shorter last chunk; an empty object has no chunks, and an object of exactly 1 MiB is one chunk. No byte is looked up in the gear table. The FastCDC loop indexes the table with plaintext bytes and stops early at a cut, so a process sharing the CPU cache could learn bits of the bytes and the cut positions from its timing, and the chunk lengths of every object cut with the table feed the gear-table recovery of T-84. Secret-class chunks get random blob IDs and are never reused, so content-defined boundaries would give them nothing. A reader does not check boundaries, for either class; TV-07 checks both rules. ### 10.2 Compression -**FS-53.** Each chunk of an ordinary object is compressed with zstd (libzstd 1.5.7, level 3) into exactly one frame with its content size declared, no checksum, no dictionary ID and `window_log = 20`. Its compressed length is the length of that frame. If `16 × compressed > 15 × plain`, the chunk is stored with `comp = 0`, so a frame is kept only if it saves at least 1/16. A zstd error fails the write; the chunk is never stored raw instead. Each chunk is its own frame, with no dictionary and no history from other chunks. Objects of the secret class are never compressed, so nothing in a secret-class object shares a compression context with its secrets. That keeps attacker-influenced data and secrets apart only where every secret is in a secret-class object. An ordinary object whose content mixes trust levels, such as a mail store, a chat or app SQLite database or a browser profile, can hold injected data and a secret in one chunk, which is the setting of compression injection attacks ([Fábrega et al., IEEE S&P 2024](https://arxiv.org/abs/2411.09228)); Padmé only raises the number of injections such an attack needs, and packs (FS-59) are what hide the sizes it reads. This is a residual for ordinary objects of mixed trust (T-40); the recourse is a per-path policy (P2) that makes such paths secret class or stores them with `comp = 0`. zstd output may differ between versions, so the encoder is pinned. A reader accepts a frame exactly when it passes the header checks below and libzstd 1.5.7 then decodes it to `plain_len` bytes; that, not RFC 8878 alone, defines a valid frame. libzstd 1.5.7 is lenient inside blocks, for example it decodes an RLE block longer than the 128 KiB block maximum that RFC 8878 sets, so a reader built on another decoder must accept what 1.5.7 accepts after these header checks, and nothing more. +**FS-53.** Each chunk of an ordinary object is compressed with zstd (libzstd 1.5.7, level 3) into exactly one frame with its content size declared, no checksum, no dictionary ID and `window_log = 20`. For a chunk of at most 1 MiB libzstd shrinks the window to the content size, so the frame is always a single segment: it has no window descriptor and its window is `plain_len`. Its compressed length is the length of that frame. If `16 × compressed > 15 × plain`, the chunk is stored with `comp = 0`, so a frame is kept only if it saves at least 1/16 (the store-raw rule). A reader enforces the rule too, so a chunk has one encoding. A zstd error fails the write; the chunk is never stored raw instead. Each chunk is its own frame, with no dictionary and no history from other chunks. Objects of the secret class are never compressed, so nothing in a secret-class object shares a compression context with its secrets. That keeps attacker-influenced data and secrets apart only where every secret is in a secret-class object. An ordinary object whose content mixes trust levels, such as a mail store, a chat or app SQLite database or a browser profile, can hold injected data and a secret in one chunk, which is the setting of compression injection attacks ([Fábrega et al., IEEE S&P 2024](https://arxiv.org/abs/2411.09228)); Padmé only raises the number of injections such an attack needs, and packs (FS-59) are what hide the sizes it reads. This is a residual for ordinary objects of mixed trust (T-40); the recourse is a per-path policy (P2) that makes such paths secret class or stores them with `comp = 0`. zstd output may differ between versions, so the encoder is pinned. A reader accepts a frame exactly when it passes the checks below and libzstd 1.5.7 then decodes it to `plain_len` bytes; that, not RFC 8878 alone, defines a valid frame, so a reader built on another decoder must accept what 1.5.7 accepts after these checks, and nothing more. A reader takes `plain_len` from the manifest. Above 2^20 the chunk is `Decompress` before it is decrypted or anything is allocated. After the inner plaintext passes FS-54, a chunk of a secret-class object with `comp = 1` is `Padding`, before its frame is looked at. Then, each failure being `Decompress`: - with `comp = 0`, `payload_len` MUST equal `plain_len`; -- with `comp = 1`, the payload MUST be exactly one zstd frame: the zstd magic number, so no skippable frame; the unused bit (`0x10`) and the reserved bit of the frame header descriptor clear; no checksum; no dictionary ID; a declared content size equal to `plain_len`, in the shortest field that holds it (one byte only in a single-segment frame below 256 bytes, two bytes with the offset of 256 for 256 to 65,791 bytes, otherwise four), as libzstd's encoder writes it; a window of at most 2^20 bytes, counting the mantissa and not only the exponent; and no bytes after the frame. These are checked before a byte is decoded. RFC 8878 has encoders write the unused bit as zero but decoders ignore it, and lets a size be written in any field that holds it; libzstd 1.5.7 decodes both, but no FS-53 writer produces them, so a reader refuses them rather than accept two encodings of one frame. A streaming decoder then writes into a buffer of exactly `plain_len` bytes, and MUST fill it and end the frame. +- with `comp = 1`, the payload MUST first keep the store-raw rule, `16 × payload_len ≤ 15 × plain_len`, since no writer keeps a frame that saves less; this needs only the two lengths, so it comes before the frame is read. The payload MUST then be exactly one zstd frame: the zstd magic number, so no skippable frame; the single-segment bit (`0x20`) of the frame header descriptor set, so no window descriptor and a window of `plain_len`; the unused bit (`0x10`) and the reserved bit clear; no checksum; no dictionary ID; a declared content size equal to `plain_len`, in the shortest field that holds it (one byte below 256 bytes, two bytes with the offset of 256 for 256 to 65,791 bytes, otherwise four), as libzstd's encoder writes it; blocks of type raw, RLE or compressed, never the reserved type 3, each with a `Block_Size` of at most `min(plain_len, 128 KiB)`, the `Block_Maximum_Size` of RFC 8878 for a window of `plain_len`, where an RLE block's `Block_Size` is the number of bytes it regenerates; and no bytes after the last block. These are checked before a byte is decoded, by walking the block headers to the frame's end. RFC 8878 has encoders write the unused bit as zero but decoders ignore it, lets a size be written in any field that holds it, and lets any frame carry a window descriptor; libzstd 1.5.7 decodes all three, but no FS-53 writer produces them, so a reader refuses them rather than accept two encodings of one chunk. libzstd 1.5.7 checks the block maximum only on its block-by-block path (`ZSTD_decompressContinue`), not when it decodes a whole frame in one pass, as `ZSTD_decompress` does and as `ZSTD_decompressStream` does when given the whole frame and room for its content; so it decodes, for example, one RLE block of 2^20 bytes, which a reader refuses. A streaming decoder then writes into a buffer of exactly `plain_len` bytes, and MUST fill it and end the frame. ### 10.3 Padding and inner plaintext @@ -742,14 +743,14 @@ aad = u8 len ‖ "crypthix/v0/aad/blob-data" ‖ fmt ‖ suite ‖ vault_id ‖ ‖ object_id ‖ dek_id ‖ blob_id ``` -The AAD binds each chunk to its vault, object and DEK. Version, position, order, count and the final chunk are bound by the manifest, which is signed and lists every chunk ([FS-66](#11-object-manifest), [FS-67](#11-object-manifest)). `blob_id` is keyed, `MAC(K_blobid, chunk plaintext)`, exactly when the object has `class = 0` (ordinary) and two or more chunks; otherwise it is 32 random bytes. A keyed ID lets the next version of the object reuse an unchanged chunk without re-encryption (E1). Deduplication stays inside one object, so no one learns whether another file shares a chunk (OQ-9, T-85). For secret-class objects, and for objects of a single chunk, nothing is reused, so content injected into a small or secret file cannot confirm a guess through the number of new packs. Inside one version of an ordinary object, equal chunks share a keyed ID, so a backend learns how many chunks repeat: runs of zeros, cut at 1 MiB (FS-52), all share one ID, which points to sparse regions ([2.1](#21-what-a-backend-learns)). A keyed ID looks like a random one, so no field records the kind: writer and reader both derive it from the manifest's `class` and `chunk_count`. A path whose chunks must never be reused is marked secret class; there is no other switch. +The AAD binds each chunk to its vault, object and DEK. Version, position, order, count and the final chunk are bound by the manifest, which is signed and lists every chunk ([FS-66](#11-object-manifest), [FS-67](#11-object-manifest)). `blob_id` is keyed, `MAC(K_blobid, chunk plaintext)`, exactly when the object has `class = 0` (ordinary) and two or more chunks; otherwise it is 32 random bytes. A keyed ID lets the next version of the object reuse an unchanged chunk without re-encryption (E1). Deduplication stays inside one object, so no one learns whether another file shares a chunk (OQ-9, T-85). For secret-class objects, and for objects of a single chunk, nothing is reused, so content injected into a small or secret file cannot confirm a guess through the number of new packs. An ordinary object of two or more chunks whose content mixes trust levels, such as a mail store, a chat database or a log, has no such protection: in-object reuse is an injection oracle, since an attacker who injects a chunk of 64 KiB or more equal to an existing chunk with a guessed secret sees fewer new blobs, and steering boundaries is easier once the gear seed leaks (T-84). The recourse is a per-path policy (P2) that makes such paths secret class, as for T-40 (T-85). Inside one version of an ordinary object, equal chunks share a keyed ID, so a backend learns how many chunks repeat: runs of zeros, cut at 1 MiB (FS-52), all share one ID, which points to sparse regions ([2.1](#21-what-a-backend-learns)). A keyed ID looks like a random one, so no field records the kind: writer and reader both derive it from the manifest's `class` and `chunk_count`. A path whose chunks must never be reused is marked secret class; there is no other switch. **FS-56.** After opening a data blob with a keyed `blob_id` (FS-55), the reader MUST recompute it from the decrypted chunk and compare in constant time (`Binding`, FS-15). A random `blob_id` has nothing to recompute. A reader opens a data blob with these checks in this order, and the first failure is the error (FS-93); no plaintext is released before all of them pass: 1. `plain_len ≤ 2^20` (`Decompress`, FS-53), before anything is decrypted or allocated; 2. the CX-AEAD open under `K_chunk` with the AAD of FS-55 (`Decrypt`; `Truncated` or `ZeroValue` as FS-28 says); 3. the inner plaintext (`Padding`, `Limit`, FS-54); 4. a secret-class object with `comp = 1` (`Padding`, FS-53); -5. the payload against `plain_len`, and for `comp = 1` the frame checks and decoding (`Decompress`, FS-53); +5. the payload against `plain_len`: for `comp = 0` its length, for `comp = 1` the store-raw rule, then the frame checks and decoding (`Decompress`, FS-53); 6. a keyed `blob_id` (`Binding`). **FS-57.** A meta blob of kind 0x03–0x06 or 0x08 is `Seal(K_kind_e, aad, CBOR, hedged nonce)` with a random `blob_id` and: @@ -1301,7 +1302,7 @@ The names below are the `expect` values of the test vectors. All but `Commitment | `UnsupportedStruct` | FS-19 | Unknown struct version | | `Downgrade` | FS-17, FS-18 | Format, suite or minimum version lower than the signed state | | `Feature` | FS-21 | Unknown incompat bit, or a write with an unknown ro_compat bit | -| `ZeroValue` | FS-03, FS-04 | Zero key, ID, hash or counter | +| `ZeroValue` | FS-03, FS-04, FS-28 | Zero key, ID, salt, hash, nonce or counter | | `VaultId` | FS-02 | `vault_id` does not match `master_pk` | | `MissingKey` | FS-30 | Key lookup missed | | `Decrypt` | FS-28 | Any failed CX-AEAD check, as seen outside `crypthix-crypto` | @@ -1318,7 +1319,7 @@ The names below are the `expect` values of the test vectors. All but `Commitment | `Merkle` | FS-66, FS-72 | Merkle or tree commitment mismatch | | `ChunkList` | FS-67 | Chunk count or length mismatch | | `Padding` | FS-53, FS-54, FS-60 | Reserved byte, pad or trailing header bytes not zero; bad compression code; wrong padded length; a compressed chunk in a secret-class object | -| `Decompress` | FS-53 | `plain_len` over the cap; a raw payload not `plain_len` bytes; a payload that is not exactly one allowed zstd frame, or that does not decode to exactly `plain_len` bytes | +| `Decompress` | FS-53 | `plain_len` over the cap; a raw payload not `plain_len` bytes; a compressed payload that breaks the store-raw rule, is not exactly one allowed zstd frame, or does not decode to exactly `plain_len` bytes | | `Layout` | FS-60, FS-62 | Pack or shard bounds or parameters inconsistent | | `ShardHash` | FS-63, FS-64 | Shard or pack hash mismatch | | `Path` | FS-71 | Path breaks the normalisation rules | @@ -1388,7 +1389,7 @@ Files are modelled on [Wycheproof](https://github.com/C2SP/wycheproof) (`testGro - Every `expect` is `Ok` or a name from [section 19](#19-errors). Only TV-05 expects `Commitment` or `AeadTag`; every other set expects `Decrypt` for a CX-AEAD failure. - Every rule that can fail has at least one negative vector. - The generator uses a seeded `ChaCha20Rng` (from the `chacha20` crate) behind the `test-rng` feature of `crypthix-crypto` and draws only through `fill_bytes` on a separately labelled stream per test, seeded with keyed BLAKE3 of the set's `seed` and the label, never through `gen_range` or other distributions that may change between `rand` releases. `cargo xtask check-features` fails if a release build of the main workspace would enable `test-rng` or `vectors` (FS-01). TV-02, TV-03 and TV-17 draw no randomness, and the generator writes their bytes by hand rather than through the decoder they test. For TV-04 and TV-05 the generator computes `H`, `KDF`, `MAC`, CX-AEAD and the nonces with its own code over the audited crates, written from section 7 and not from `crypthix-crypto`, so the two implementations check each other. -- zstd is pinned to one version, named in the set's `zstd` header (1.5.7 for TV-07), since its encoder output may change between versions. A runner checks encoder output only under that version and fails under another; decoding vectors must pass under any version. +- zstd is pinned to one version, named in the set's `zstd` header (1.5.7 for TV-07), since its encoder output may change between versions. A runner checks encoder output only under that version and fails under another; decoding vectors give the results FS-53 defines, through libzstd 1.5.7. A reader built on another decoder must give the same results; `crypthix-core`'s own `Decompressor` requires 1.5.7 and refuses any other libzstd (`CompressError::Version`). - CI regenerates the vectors and diffs them against the committed files (`cargo xtask vectors --check`). Vectors are frozen per format; changing a committed vector needs a changelog row here. - Argon2id vectors run at the 256 MiB floor and are marked slow (`#[ignore]`); the scheduled deep-test job runs them with `--ignored`. - Before the 1.0 audit, a second, independent decoder (for example a short Python reader) runs every set. @@ -1442,9 +1443,11 @@ Files are modelled on [Wycheproof](https://github.com/C2SP/wycheproof) (`testGro | Blob decrypts but gives another blob ID; a random blob ID in an ordinary object of two or more chunks | TV-07 | `Binding` | FS-55, FS-56, T-85 | | Inner plaintext shorter than its header; unknown `comp`; `rsv` or a pad byte not zero; one byte longer or shorter than `padme(6 + payload_len)` | TV-07 | `Padding` | FS-54, T-39 | | `payload_len` exactly 2^20; 2^20 + 1; 2^32 − 1; a bad `comp` or `rsv` with 2^20 + 1 | TV-07 | `Ok`, `Limit`, `Padding` first | FS-54, FS-93, T-39 | -| `plain_len` exactly 2^20; 2^20 + 1, refused before decryption | TV-07 | `Ok`, `Decompress` | FS-53, FS-11, T-39 | -| Zstd frame holding more or less than it declares; content size missing or other than `plain_len`; content size in a wider field than needed (four or eight bytes for 5, four for 300); checksum; dictionary ID; reserved bit; unused bit; skippable frame before, after or alone; two frames; a trailing byte; a cut-off frame; a valid header followed by a block of the reserved type 3; window 2^20 + 2^17 or 2^21 (2^20 is `Ok`); a raw block and a compressed block of exactly 128 KiB, the block maximum, are `Ok` (libzstd up to 1.5.2 refused the compressed one, zstd's decompressor errata) | TV-07 | `Decompress`, `Ok` | FS-53, T-39 | -| Raw payload one byte shorter than `plain_len` | TV-07 | `Decompress` | FS-53 | +| `plain_len` exactly 2^20, as a frame and as a data blob of a compressed 1 MiB of zeros; 2^20 + 1, refused before decryption | TV-07 | `Ok`, `Decompress` | FS-53, FS-11, T-39 | +| Zstd frame holding more or less than it declares; content size missing or other than `plain_len`; content size in a wider field than needed (four or eight bytes for 5, four for 300); checksum; dictionary ID; reserved bit; unused bit; a window descriptor in place of a single segment, of 2^20 or 2^21 bytes; skippable frame before, after or alone; two frames; a trailing byte; a frame cut off in its last byte, after the magic number and descriptor, inside a two-byte content size or inside a block header; a valid header followed by a block of the reserved type 3; a raw block of exactly 128 KiB, the block maximum, and a compressed block of exactly 128 KiB followed by a raw block of 4 bytes are `Ok` (libzstd up to 1.5.2 refused the compressed one, zstd's decompressor errata) | TV-07 | `Decompress`, `Ok` | FS-53, T-39 | +| A block over `min(plain_len, 128 KiB)`: one RLE block of 2^20 zeros and one raw block of 128 KiB + 1 bytes, which libzstd 1.5.7 decodes in one pass; an RLE block of 6 bytes in a frame of 5 | TV-07 | `Decompress` | FS-53, T-39 | +| Raw payload one byte shorter or longer than `plain_len` | TV-07 | `Decompress` | FS-53, T-39 | +| A frame of exactly 15/16 of `plain_len` (45 bytes for 48) is `Ok`; one that saves less (46 for 49, or a raw-block frame longer than its chunk) breaks the store-raw rule, also with a wrong blob ID | TV-07 | `Ok`, `Decompress` | FS-53, FS-56, FS-93, T-40 | | Secret-class chunk with `comp = 1`, also with a bad frame | TV-07 | `Padding` | FS-53, FS-93, T-40 | | Bad frame, or a raw payload other than `plain_len` bytes, and a wrong blob ID together | TV-07 | `Decompress` | FS-56, FS-93 | | Meta blob opened with another kind byte, epoch, blob ID, vault or KEK | TV-07 | `Decrypt` | FS-57, M-8, T-35 | @@ -1519,7 +1522,7 @@ Files are modelled on [Wycheproof](https://github.com/C2SP/wycheproof) (`testGro | T-36 No key commitment | FS-27, FS-28 | | T-37 Key substitution | FS-02, FS-46, FS-75 | | T-38 Nonce misuse | FS-05, FS-29 | -| T-39 Parser bugs | FS-08–FS-11, FS-60, FS-62, FS-94 | +| T-39 Parser bugs | FS-08–FS-11, FS-53, FS-54, FS-56, FS-60, FS-62, FS-94 | | T-40 Compression size oracle | FS-53 | | T-41 Rollback | FS-68, FS-80, FS-81 (per device in P1; full in P4) | | T-42 Freeze | FS-83 (*P4*) | @@ -1534,7 +1537,7 @@ Files are modelled on [Wycheproof](https://github.com/C2SP/wycheproof) (`testGro | T-82 Hybrid KEM pitfalls | FS-46 (*P4*) | | T-81 Repeated randomness | FS-01, FS-29 | | T-83 Ambiguous encodings | FS-08, FS-13, FS-14, FS-66 | -| T-84 Chunk-boundary fingerprinting | FS-52, FS-59, FS-62 | +| T-84 Chunk-boundary fingerprinting | FS-52, FS-54, FS-59, FS-62 | | T-85 Deduplication oracle | FS-55, FS-56 | | T-86 Tree tampering | FS-72 | | T-87 Retention outlives retirement | FS-47, FS-48 | @@ -1570,7 +1573,7 @@ All three are tracked in [threat-model section 14](threat-model.md#14-open-quest | Version | Date | Change | | --- | --- | --- | -| v0.8 | 2026-11-10 | From the chunking, compression and padding item (E1, E2, E3) in `crypthix-core`; no valid bytes change, but readers reject more. FS-52 states the FastCDC cut rule and the masks and pins `fastcdc` 5.0.0 as the reference; after review, secret-class objects are cut at fixed 1 MiB steps with no gear-table lookup instead of with FastCDC, since the loop leaks bits of the bytes through cache timing and their lengths feed gear-table recovery while they never deduplicate (writers change, readers do not); FS-52 also says Padmé only coarsens chunk sizes and packs hide them. FS-53 says the separation of attacker data from secrets holds only for secret-class objects, and names ordinary objects of mixed trust as a residual (T-40). FS-55 and 2.1 add that equal chunks inside one version of an ordinary object share a keyed ID, which shows how many repeat. FS-53 pins libzstd 1.5.7, says the compressed length is the frame's, requires `payload_len = plain_len` for `comp = 0`, lists the reader's frame checks (window size, not only its log; the unused bit clear and the content size in its shortest field, which libzstd 1.5.7 does not check; acceptance defined as what libzstd 1.5.7 decodes after those header checks, in place of "frames decode under any version"), and makes a compressed chunk of a secret-class object `Padding`. FS-54 gives its check order and makes `payload_len > 2^20` `Limit`. FS-55: `blob_id` is keyed exactly for ordinary objects of two or more chunks, and the reader derives the kind from the manifest; the policy switch for reuse is dropped, since a path that must not reuse chunks is secret class. FS-56 checks keyed IDs only and gives the data-blob open order. FS-28: a seal shorter than its overhead is `Truncated`. TV-07 added, with an independent byte-at-a-time chunker in the generator and hand-built zstd frames, and with secret-class `Chunking` cases (`SecretFixed`; every `Chunking` test now names its `class`); `CutEdges` cases, found by search and checked by the generator, put a cut at the minimum and one past it, at the switch of masks, at the last position tested, and after a pattern only at the maximum, and give an odd last byte that would match if tested; a `pattern` input is a short byte string repeated to `length`; more negative rows in 20.4, among them a raw payload of the wrong length with a wrong blob ID (`Decompress`), a meta blob too short to be a seal or with an all-zero nonce, a block of the reserved type 3 (`Decompress`) and raw and compressed blocks of exactly 128 KiB (`Ok`; the compressed one hand-built, as libzstd's encoder never writes it and libzstd up to 1.5.2 refused it); a frame with a run of more than 1,024 zero bytes is given as `frameHead`, `frameZeros` and `frameTail` | +| v0.8 | 2026-11-10 | From the chunking, compression and padding item (E1, E2, E3) in `crypthix-core`; no valid bytes change, but readers reject more. FS-52 states the FastCDC cut rule and the masks and pins `fastcdc` 5.0.0 as the reference; after review, secret-class objects are cut at fixed 1 MiB steps with no gear-table lookup instead of with FastCDC, since the loop leaks bits of the bytes through cache timing and their lengths feed gear-table recovery while they never deduplicate (writers change, readers do not); FS-52 also says Padmé only coarsens chunk sizes and packs hide them. FS-53 says the separation of attacker data from secrets holds only for secret-class objects, and names ordinary objects of mixed trust as a residual (T-40). FS-55 and 2.1 add that equal chunks inside one version of an ordinary object share a keyed ID, which shows how many repeat. FS-53 pins libzstd 1.5.7, says the compressed length is the frame's, requires `payload_len = plain_len` for `comp = 0`, lists the reader's frame checks (after review, a single segment, which is all libzstd writes for a chunk of at most 1 MiB, so no window descriptor and a window of `plain_len`; the unused bit clear and the content size in its shortest field, which libzstd 1.5.7 does not check; every block at most `min(plain_len, 128 KiB)`, an RLE block counting what it regenerates, which libzstd 1.5.7 does not check when it decodes a frame in one pass; acceptance defined as what libzstd 1.5.7 decodes after those checks, in place of "frames decode under any version"), makes a reader enforce the store-raw rule, so a chunk has one encoding, and makes a compressed chunk of a secret-class object `Padding`. FS-54 gives its check order and makes `payload_len > 2^20` `Limit`. FS-55: `blob_id` is keyed exactly for ordinary objects of two or more chunks, and the reader derives the kind from the manifest; the policy switch for reuse is dropped, since a path that must not reuse chunks is secret class. FS-56 checks keyed IDs only and gives the data-blob open order, with the store-raw rule before the frame checks in step 5. FS-28: a seal shorter than its overhead is `Truncated`. TV-07 added, with an independent byte-at-a-time chunker in the generator and hand-built zstd frames, and with secret-class `Chunking` cases (`SecretFixed`; every `Chunking` test names its `class`); `CutEdges` cases, found by search and checked by the generator, put a cut at the minimum and one past it, at the switch of masks, at the last position tested, and after a pattern only at the maximum, and give an odd last byte that would match if tested and, after review, a file between 256 KiB and 1 MiB in which no position matches, so it is one chunk; a `pattern` input is a short byte string repeated to `length`; more negative rows in 20.4, among them a raw payload of the wrong length with a wrong blob ID (`Decompress`), a meta blob too short to be a seal or with an all-zero nonce, a block of the reserved type 3 (`Decompress`) and raw and compressed blocks of exactly 128 KiB (`Ok`; the compressed one hand-built, as libzstd's encoder never writes it and libzstd up to 1.5.2 refused it, and followed by a raw block of 4 bytes so a single segment's window holds it), and after review a window descriptor (`Decompress`, no longer `Ok` at 2^20), blocks over the block maximum (`BlockSize`), frames cut off inside the header, a raw payload one byte longer than `plain_len`, a frame breaking the store-raw rule and one exactly at it (`StoreRaw`), and a data blob of `plain_len` 2^20 (`Ok`); a frame with a run of more than 1,024 zero bytes is given as `frameHead`, `frameZeros` and `frameTail`, and an all-zero plaintext of more than 1,024 bytes as `plaintextZeros`. FS-11 lists the `payload_len` limit of FS-54 and makes `plain_len` above 2^20 its one `Decompress` exception. FS-94: decoding vectors give the results FS-53 defines through libzstd 1.5.7, in place of passing under any version. FS-55 names in-object reuse as an injection oracle for ordinary objects of mixed trust (T-85) | | v0.7 | 2026-11-08 | From the protected key memory item (O1); no bytes change. FS-31's protected memory is the key pool of `crypthix-crypto::secure_mem`. FS-28: no protected memory for the plaintext is a memory error, never `Decrypt` | | v0.6 | 2026-10-30 | From the crypto wrappers item (`crypthix-crypto`). Every nonce that was random is now hedged (FS-29, FS-55, FS-57, FS-60), because the kernel reseeds after a VM restore only with a VM generation ID (FS-01, T-81); readers are unaffected, since Open reads the nonce from the seal. FS-29 also says a failed RNG seals nothing, states that the equality bound is about privacy and the SIV distinctness bound, and FS-25 names CX-AEAD's internal labels as its one exception. FS-28 separates key-wrap labels from data labels and makes an all-zero nonce `ZeroValue`; the path index text says hedged. TV-05 has a hedged pair with replayed randomness and an all-zero nonce. FS-14 also rejects mixed-order public keys (`WeakKey`): `verify_strict` alone accepts them, as Wycheproof tcId 160 to 180 and speccheck case 3 show. TV-04 and TV-05 added; the generator computes them with its own section 7 code (FS-94), and `expect` may name `Commitment` and `AeadTag` in TV-05 only. The RFC and XChaCha draft vectors are transcribed to JSON (20.1). OQ-13 decided: no FIPS mode in format 0 | | v0.5 | 2026-10-29 | From the fuzzing and test-harness item; no valid bytes change. `tests/` is its own workspace, holding the generator and the fuzz targets (20.1). The vector schema is draft 2020-12; `seed` and `zstd` are optional for sets with no randomness or compression, and sets may add header strings (20.2). The seeded generator stream arrives with `crypthix-crypto` (FS-94). External vectors: Wycheproof, BLAKE3 and ed25519-speccheck vendored unchanged; RFC vectors are transcribed with their runners | diff --git a/docs/project-vision.md b/docs/project-vision.md index 3caed15..f246fab 100644 --- a/docs/project-vision.md +++ b/docs/project-vision.md @@ -180,7 +180,7 @@ One `crypthixd` process serves each human user and wires together library crates ```mermaid flowchart LR - F["File bytes from an allowed app"] --> C["1. Chunk (FastCDC, secret seed)"] + F["File bytes from an allowed app"] --> C["1. Chunk (keyed FastCDC; fixed 1 MiB for secret files)"] C --> Z["2. Compress (zstd)"] Z --> P["3. Pad (Padmé)"] P --> E["4. Encrypt XChaCha20-Poly1305 with key commitment
key from the object DEK, AAD = vault, object, DEK, blob ID"] @@ -442,8 +442,8 @@ Legend: **MVP** = first public release (0.1) · **v1** = 1.0 · **Later** = afte | ID | Feature | Description | Stage | | --- | --- | --- | --- | -| E1 | Content-defined chunking | FastCDC chunking with a secret per-vault gear table, so edits only rewrite changed chunks; a new version of an ordinary file reuses its unchanged chunks, with deduplication only inside one object, never across files and never for secret files ([format spec FS-55](format-spec.md#104-blobs)) | MVP | -| E2 | Compression | zstd per chunk, skipped automatically for already-compressed data | MVP | +| E1 | Content-defined chunking | FastCDC chunking with a secret per-vault gear table, so edits only rewrite changed chunks; a new version of an ordinary file reuses its unchanged chunks, with deduplication only inside one object, never across files and never for secret or single-chunk files ([format spec FS-55](format-spec.md#104-blobs)) | MVP | +| E2 | Compression | zstd per chunk: every chunk of an ordinary file is trial-compressed and stored raw when zstd saves under 1/16, so already-compressed data stays raw; secret files are never compressed | MVP | | E3 | Size padding | Pad compressed chunks to size buckets so file sizes leak less | MVP | | E4 | Authenticated encryption | XChaCha20-Poly1305 with key commitment per chunk; AAD binds vault, object and DEK, and the signed manifest binds order, count and version ([format spec](format-spec.md)) | MVP | | E5 | Integrity and signatures | BLAKE3 Merkle trees over each object and the path index; manifests signed by the writing device; a signed vault root | MVP | @@ -758,8 +758,8 @@ A running program always sees plaintext in its own memory. CryptHix guarantees t | Encoding | Deterministic CBOR (RFC 8949) after a fixed preamble | Own strict codec in `crypthix-types`: no CBOR crate checks canonical form on decode | | Secret sharing | Shamir | `vsss-rs` | | Erasure coding | Reed-Solomon | `reed-solomon-simd` | -| Compression | zstd | `zstd` | -| Chunking | FastCDC | `fastcdc` | +| Compression | zstd (libzstd 1.5.7, bundled) | `zstd-safe`; the `zstd` crate is banned | +| Chunking | FastCDC 2020 with a keyed gear table | Own loop in `crypthix-core`; `fastcdc` 5.0.0 only as a test oracle | | Capability tokens | Biscuit | `biscuit-auth` | | Filesystem | FUSE | `fuser` | | eBPF / LSM | BPF-LSM programs | `aya` | diff --git a/docs/style-guide.md b/docs/style-guide.md index 1af13fd..a95152f 100644 --- a/docs/style-guide.md +++ b/docs/style-guide.md @@ -23,8 +23,9 @@ The API design rules are **binding for library crates** (everything under `crate | Workspace lints | `Cargo.toml` `[workspace.lints]` | `missing_docs`, `unsafe_code`, `unreachable_pub`, Clippy `all` and `pedantic`, and the Google-aligned lints listed below | | Clippy config | `clippy.toml` | Project words accepted in docs; `unwrap`/`expect` allowed in tests | | Layer check | `cargo xtask check-layers` | Crate dependency rules from [backlog.md](backlog.md#architecture-rules) | -| Release features | `cargo xtask check-features` | No release build enables the test-only `test-rng` or `vectors` features of `crypthix-crypto` ([format spec FS-01](format-spec.md#4-identifiers-primitives-and-randomness)); no `ZSTD_SYS_USE_PKG_CONFIG` and no `links` override for `zstd` links a system libzstd. Covers only the repository's own build environment (the environment and the repository's `.cargo/config*` files, not a user-level `~/.cargo/config.toml`, `$CARGO_HOME` or `--config`); the runtime version check in `Compressor::new` and in `Decompressor::decode` before its first call into libzstd (`CompressError::Version`) is the backstop | -| cargo-deny | `deny.toml` | Licences, advisories, sources, and "only `crypthix-crypto` imports crypto crates", including `getrandom`, `subtle` and `curve25519-dalek`; `zstd-safe` and `fastcdc` only in `crypthix-core` and the `tests/` tools, `zstd-sys` only through `zstd-safe`, never the `zstd` crate; and the `zstd-sys` and `zstd-safe` features that would link a system or debug libzstd or widen it (`pkg-config`, `non-cargo`, `cmake`, `debug`, `legacy`, `zdict_builder`, `experimental`, `zstdmt`, `seekable`, `bindgen`) | +| Release features | `cargo xtask check-features` | No release build enables the test-only `test-rng` or `vectors` features of `crypthix-crypto` ([format spec FS-01](format-spec.md#4-identifiers-primitives-and-randomness)) or the `vectors` feature of `crypthix-core`; no `--cfg feature=` or `getrandom_backend` in `RUSTFLAGS`, `CARGO_ENCODED_RUSTFLAGS`, `CARGO_BUILD_RUSTFLAGS`, `CARGO_HOST_RUSTFLAGS`, any `CARGO_TARGET__RUSTFLAGS` or the `rustflags` of the repository's Cargo config files; no `ZSTD_SYS_USE_PKG_CONFIG`, no `links` override for `zstd`, no `[patch]` or `[replace]` of `zstd`, `zstd-sys` or `zstd-safe` (in those files or either workspace manifest) and no `paths` override swaps in another libzstd. Covers only the repository's own build environment (the environment and the repository's `.cargo/config*` files, not a user-level `~/.cargo/config.toml`, `$CARGO_HOME` or `--config`); the runtime version check in `Compressor::new` and in `Decompressor::decode` before its first call into libzstd (`CompressError::Version`) is the backstop | +| Static libzstd | `cargo xtask check-zstd-link [--target ]` | `zstd-sys`'s build script linked only `static=zstd` and searched only its own `OUT_DIR`, read from Cargo's report and the script's `output` file, so a system libzstd 1.5.7, which the runtime version check accepts, fails; after the tests in CI's `test` job, `windows-test` and every nightly platform job | +| cargo-deny | `deny.toml` | Licences, advisories, sources, and "only `crypthix-crypto` imports crypto crates", including `getrandom`, `subtle` and `curve25519-dalek`; `zstd-safe` and `fastcdc` only in `crypthix-core` and the `tests/` tools, `zstd-sys` only through `zstd-safe`, never the `zstd` crate; and an exact, empty allow list of `zstd-sys` and `zstd-safe` features, so none is enabled (no `pkg-config`, `non-cargo`, `cmake`, `debug`, `legacy`, `zdict_builder`, `experimental`, `zstdmt`, `seekable`, `bindgen` or `with-rust-allocator`) and a feature a later release adds fails until it is reviewed | | Pre-commit hook | `.githooks/pre-commit`, `xtask/src/pre_commit.rs` | File hygiene, secrets (gitleaks), formatting and Clippy on staged changes; Clippy and tests of the `tests/` workspace when it, `crypthix-types`, `crypthix-crypto` or `crypthix-core` changes | | Line endings | `.gitattributes` | LF in the repository on every platform; vendored test vectors kept byte for byte | | Secret scanner config | `.gitleaks.toml` | Default gitleaks rules; only vendored, transcribed and generated vector JSON is allowlisted, file by file | @@ -168,7 +169,7 @@ Where each kind of test lives, and the conventions for each. - **Property tests** use proptest with its default 256 cases. Set `PROPTEST_CASES=4096` for a deep run. Commit every regression file proptest writes, as [its book recommends](https://proptest-rs.github.io/proptest/proptest/failure-persistence.html), so a found case is rerun forever by everyone and by CI: `proptest-regressions/` beside `src/` for unit tests, and `.proptest-regressions` beside an integration test in `tests/`, which has no `lib.rs` above it. Delete a file only together with the test it belongs to. - **Slow tests**, such as Argon2id at its 256 MiB floor, are marked `#[ignore = "slow: "]`. Run them with `cargo test -- --ignored`; the scheduled deep-test job does. - **Tests that depend on the system**, such as `secure_mem`'s on `memfd_secret` and `RLIMIT_MEMLOCK`, skip what the system cannot run by saying so on standard error, never silently, and fail instead where `CRYPTHIX_REQUIRE_SECRETMEM=1` says the system has it (CI sets it). Add such a test to the `success-output` override in `.config/nextest.toml` so its skips show, and a test that needs the user's secret memory to itself to the `threads-required` one, which runs it alone. -- **Test-only features** of `crypthix-crypto` (`test-rng`, `vectors`) are enabled only by the crate's own tests, through `required-features`, and by the `tests/` workspace. `cargo xtask check-features` fails if anything in the main workspace would enable them in a release build. +- **Test-only features** of `crypthix-crypto` (`test-rng`, `vectors`) and `crypthix-core` (`vectors`) are enabled only by the crate's own tests, through `required-features`, and by the `tests/` workspace. `crypthix-core`'s `vectors` must not forward to `crypthix-crypto/vectors`. `cargo xtask check-features` fails if anything in the main workspace would enable them in a release build. - **Crash tests** for anything that writes to a store use `crypthix-testkit` (a dev-dependency only; `check-layers` rejects it anywhere else): `MemoryBackend`, `FaultBackend` for lost replies, injected errors and corrupt uncached reads (assert `applied()` so a misplaced fault cannot pass), and `for_each_crash_point`, which crashes a deterministic workload after every operation and checks what a restart finds (M-44). Faults are whole operations, matching the `Backend` contract; torn writes and reordering below it come with the local backend. - **Benchmarks** use criterion in each crate's `benches/` with `harness = false`. Run them with `cargo bench -p --bench `; `cargo clippy --all-targets` keeps them compiling. diff --git a/docs/threat-model.md b/docs/threat-model.md index 2fd4056..dd9e504 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -779,8 +779,8 @@ These have no feature ID. They attach to existing backlog items and are checked | T-81 | M | SP-C1 | Mitigate | M-36 | Crypto and formats | P1 | | T-82 | M | SP-C9 | Mitigate | M-38 | Crypto and formats | P4 | | T-83 | M | SP-C2 | Mitigate | M-37 | Crypto and formats | P1 | -| T-84 | H | SP-C11 | Mitigate, accept rest (R-5) | M-39. E1 (landed in P1, `crypthix-core`): FastCDC with a gear table keyed per vault from `chunker_seed` ([format spec FS-52](format-spec.md#101-chunking)). A keyed gear table alone does not hide boundaries: such tables have been recovered from observed chunk sizes, Bupstash's keyed gear included ([ePrint 2025/558](https://eprint.iacr.org/2025/558), Truong, Merz, Scarlata, Günther and Paterson, CCS 2025; [ePrint 2025/532](https://eprint.iacr.org/2025/532)). The design therefore assumes the seed may leak, and keeps the gear table in a `SecretBuf` (locked plaintext memory where the limit allows, not the secret pages keys use). Size-class packs (encrypt pipeline item, FS-59) are what hide the sizes those attacks need; Padmé on every chunk (E3, FS-54) does not hide them but coarsens them: a 256 KiB chunk rounds to 8 KiB steps and a 1 MiB one to 32 KiB, so about 5 bits of each chunk's length stay visible. Secret-class objects are not cut with the gear table at all but at fixed 1 MiB steps ([format spec FS-52](format-spec.md#101-chunking)): the FastCDC loop indexes the table with plaintext bytes and exits early at a cut, which a process sharing the CPU cache can time, and their lengths would feed table recovery, while they never deduplicate. A chunker built on a PRF (Chk-PHTE) was considered and not taken for format 0. Left: chunk count and order, and each blob's Padmé size, until packs land; whatever sizes packs still show (R-5) | Crypto and formats | P1 | -| T-85 | M | SP-C11 | Mitigate, accept rest (R-5) | Blob IDs keyed per object; no deduplication for secret files (format spec FS-55). Landed in P1 (`crypthix-core`): an ID is keyed exactly for an ordinary object of two or more chunks and random for secret-class and single-chunk objects, so nothing of theirs is reused; writer and reader derive the kind from the manifest's class and chunk count, and the reader recomputes keyed IDs ([format spec FS-55, FS-56](format-spec.md#104-blobs)) | Crypto and formats | P1 | +| T-84 | H | SP-C11 | Mitigate, accept rest (R-5) | M-39. E1 (landed in P1, `crypthix-core`): FastCDC with a gear table keyed per vault from `chunker_seed` ([format spec FS-52](format-spec.md#101-chunking)). A keyed gear table alone does not hide boundaries: such tables have been recovered from observed chunk sizes, Bupstash's keyed gear included ([ePrint 2025/558](https://eprint.iacr.org/2025/558), Truong, Merz, Scarlata, Günther and Paterson, CCS 2025; [ePrint 2025/532](https://eprint.iacr.org/2025/532)). The design therefore assumes the seed may leak. It keeps the gear table in a `SecretBuf` (plaintext memory, wiped on free and on Linux locked where the limit allows, not the secret pages keys use). Size-class packs (encrypt pipeline item, FS-59) are what hide the sizes those attacks need; Padmé on every chunk (E3, FS-54) does not hide them but coarsens them: a 256 KiB chunk rounds to 8 KiB steps and a 1 MiB one to 32 KiB, so about 7 bits of each chunk's length stay visible (5 significant bits and the octave: 129 padded lengths between 64 KiB and 1 MiB). Secret-class objects are not cut with the gear table at all but at fixed 1 MiB steps ([format spec FS-52](format-spec.md#101-chunking)): the FastCDC loop indexes the table with plaintext bytes and exits early at a cut, which a process sharing the CPU cache can time, and their lengths would feed table recovery, while they never deduplicate. A chunker built on a PRF (Chk-PHTE, ePrint 2025/558) was considered and not taken for format 0; whether a later suite adopts one is OQ-19. Left: chunk count and order, and each blob's Padmé size, until packs land; whatever sizes packs still show (R-5) | Crypto and formats | P1 | +| T-85 | M | SP-C11 | Mitigate, accept rest (R-5) | Blob IDs keyed per object; no deduplication for secret files (format spec FS-55). Landed in P1 (`crypthix-core`): an ID is keyed exactly for an ordinary object of two or more chunks and random for secret-class and single-chunk objects, so nothing of theirs is reused; the writer derives the kind from the chunker's shape, seals only the chunker's chunks of that shape, in order, and records the chunk count its sealer's `finish` gives, which fails if the chunks sealed contradict the shape; the reader derives it from the manifest's class and chunk count and recomputes keyed IDs ([format spec FS-55, FS-56](format-spec.md#104-blobs)). Left: inside one ordinary object of two or more chunks whose content mixes trust levels (a mail store, a chat database, a log), reuse is an injection oracle: an attacker who injects a chunk of 64 KiB or more equal to an existing chunk with a guessed secret sees fewer new blobs, and steering boundaries to make such a chunk is easier once the gear seed leaks (T-84). The recourse is the per-path policy (P2) that makes such paths secret class, as for T-40 | Crypto and formats | P1 | | T-86 | H | SP-C10 | Mitigate | M-40 | Restore | P1, P3 | | T-87 | H | SP-C6 | Mitigate, accept rest (R-19) | M-41 | Rotation safety | P4 | | T-88 | H | SP-B5 | Mitigate, accept rest (R-20) | M-42 | Restore | P3, P4 | @@ -882,7 +882,7 @@ A window is a known gap between when a feature ships and when the feature that p | R-2 | Agent detection is best effort; a determined agent or an in-editor assistant can avoid it | T-05, T-14 | §8 AI agent row | | R-3 | In Degraded mode, injection into allowed programs stays possible | T-08 | §17 "Root malware can eventually win" | | R-4 | A firmware TPM can be fault-attacked; a stolen laptop then depends on the passphrase or a second share | T-28 | §8 thief row | -| R-5 | Shard counts, sizes, timing and push sizes leak; per-blob Padmé sizes (about 5 bits of each chunk's length) until packs land (FS-59) | T-40, T-59, T-84 | §17 "Metadata leaks remain" | +| R-5 | Shard counts, sizes, timing and push sizes leak; per-blob Padmé sizes (about 7 bits of each chunk's length) until packs land (FS-59) | T-40, T-59, T-84 | §17 "Metadata leaks remain" | | R-6 | Plaintext an allowed program read can be sent anywhere | T-12 | §17 "Allowed programs see plaintext" | | R-7 | Secrets in environment variables, history or clipboard are outside the vault | T-13 | — (new in §17) | | R-8 | Killing or unmounting CryptHix denies service; it fails closed but work stops | T-16 | §8 malware row | @@ -903,7 +903,7 @@ A window is a known gap between when a feature ships and when the feature that p | R-23 | `/proc//fd` and `maps` of allowed programs show which secret paths are open to same-UID processes | T-65 | — | | R-24 | In Degraded mode, forced crash dumps of allowed programs stay possible | T-64 | §17 BPF-LSM limit | | R-25 | In teams, guard data is personal data about members | T-97 | — | -| R-26 | zstd's working memory, which holds pieces of chunk plaintext (the compression context keeps literals and match-finder hash tables, the decompression context decoded literals in its `litExtraBuffer`), is on the C heap: not wiped on free, not excluded from core dumps, not locked (so it can be swapped out) and not `MADV_DONTFORK` (so a forked child gets a copy). The encrypt pipeline item plans a `ZSTD_customMem` allocator backed by `secure_mem` in `crypthix-crypto`, which may use `unsafe` | T-31 | — | +| R-26 | zstd's working memory, which holds pieces of chunk plaintext (the compression context keeps literals and match-finder hash tables, the decompression context decoded literals in its `litExtraBuffer`), is on the C heap: not wiped on free, not excluded from core dumps, not locked (so it can be swapped out) and not `MADV_DONTFORK` (so a forked child gets a copy). A freed context goes back to the C allocator's free lists unwiped, so its bytes can turn up in later allocations or a core dump. The encrypt pipeline item plans a `ZSTD_customMem` allocator backed by `secure_mem` in `crypthix-crypto`, which may use `unsafe`. Until it lands, the daemon should make itself non-dumpable (`PR_SET_DUMPABLE` 0, with the protection level of OQ-18) and set `RLIMIT_CORE` to 0 | T-31 | — | --- @@ -929,6 +929,7 @@ A window is a known gap between when a feature ships and when the feature that p | OQ-16 | Recovery text: whether to offer an optional QR code. *Partly answered (v0.4):* the wordlist is SLIP-39 ([format spec FS-45](format-spec.md#92-share-plaintext-and-recovery-text)) | CLI v0 (P1) | | OQ-17 | Should text strings also forbid other invisible characters (U+2028, U+2029, U+200B, U+FEFF, tag characters), or all of Unicode category Cf ([format spec 22](format-spec.md#22-open-items))? | Format 1 freeze at the external audit | | OQ-18 | Which minimum protection level should the daemon require of `secure_mem::init`: `Locked` everywhere, or `Secret` with a refusal to start on kernels without `memfd_secret` (off by default before Linux 6.5, so on Ubuntu 22.04 GA and Debian 12)? And should it raise `RLIMIT_MEMLOCK` itself or rely on `LimitMEMLOCK=` in its unit? | Daemon (P2) | +| OQ-19 | Should a later suite adopt a provably secure keyed chunker built on a PRF ([ePrint 2025/558](https://eprint.iacr.org/2025/558)), so that T-84 does not rest on packs alone? Until packs land R-5 stays open | Next suite, after packs (FS-59) land with the encrypt pipeline item | Decisions already taken (2026-10-29): the daemon runs as its own system user (M-15), with a root helper that mounts, loads BPF-LSM and brokers identity (M-20, M-21); A14 uses passphrase or polkit in 0.1 and moves to M-5; per-device signing keys and TPM-protected device keys are format requirements (M-14); new mitigations stay as M- IDs attached to existing backlog items. @@ -960,7 +961,7 @@ Decisions already taken (2026-10-29): the daemon runs as its own system user (M- | 2026-10-30 | P0 | Out-of-cycle review for format spec v0.4 and v0.5 and the fuzzing and test-harness item | No new threats or flows. M-29 and M-44 now name what landed in P0 (fuzz targets for the `crypthix-types` parsers, the `crypthix-testkit` crash-point harness) and what waits for P1 and P2; OQ-16 partly answered (SLIP-39). Backlog checked against 11.1, 12.2 and 14: every M-, window and open question is cited by the item it lands with | | 2026-10-30 | P1 | Out-of-cycle review for the crypto wrappers item and format spec v0.6 | No new threats; T-81 and M-36 now state that reseeding after a VM restore needs `vmgenid`, so every random nonce becomes hedged (format spec FS-29), leaving only repeated random IDs and keys as residual risk. Key wraps and data seals use separate AAD labels, so a wrapped key cannot be read out or forged through the data API (rule 9). Checklist 15.2: (1) no new data flow or boundary, the crate runs inside the daemon's existing boundaries; (2) no new STRIDE findings; (3) T-36, T-38, T-81 and T-83 keep their mitigations, tests (TV-01, TV-04, TV-05, fuzz targets `cx_open` and `verifying_key`) and phase; (4) 12.3 is unchanged, crypto does not depend on the hardening mode; (5) vision 8 and 17 still agree. M-9, M-36 and M-37 now name what landed in `crypthix-crypto`; M-37 and FS-14 also reject mixed-order Ed25519 keys, which `verify_strict` alone accepts (Wycheproof tcId 160 to 180, speccheck case 3). OQ-13 answered: no FIPS mode in format 0. TV-04 and TV-05 are computed by a second implementation in the vector generator | | 2026-11-08 | P1 | Out-of-cycle review for the protected key memory item (O1) | No new threats. T-31 now names what O1 landed and what is left: keys in `memfd_secret` pages (unreadable through `PTRACE_PEEKDATA`, `process_vm_readv` and `/proc//mem`, though a process allowed to `ptrace` can still inject code), falling back to `mlock`ed and then dump-excluded memory, with the level reported by `secure_mem::status` for the hardening mode (M-13); plaintext never in secret pages, since pinned-page I/O (`O_DIRECT`, FUSE `splice`) fails on them with `EFAULT` and each costs direct-map and `RLIMIT_MEMLOCK` pages; copying calls such as `write` do reach them. Checklist 15.2: (1) no new data flow; key memory stays inside the daemon boundary (TB-2/3), as the diagram already shows; (2) no new STRIDE findings; `memfd_secret` blocks hibernation, already in AS-6 and M-11; (3) T-31 keeps its risk and phase, with tests for each level (smaps flags, `/proc/self/mem`, a zero `RLIMIT_MEMLOCK`); (4) 12.3 unchanged; (5) vision 8 and 17 still agree. OQ-18 added: the daemon's minimum level. A multi-agent review (security, tests, code quality, scenario coverage, Windows and macOS) then changed the code before it landed: separate lock shares for keys and buffers, prefaulting through the raw `getrandom` system call instead of plain writes that could `SIGBUS`, the fork rule with a `MADV_WIPEONFORK` generation marker instead of the pid, no heap fallback for plaintext on Linux, errors instead of aborts when no buffer can be mapped (`OpenError::Memory`, `VerifyError::Memory`, `MemError::TooLarge`), an `init` that keeps its minimum when it fails and is refused after the first key or buffer (which set up the defaults) rather than silently get less, a `status` that sets up nothing, and `Fallback` reasons for keys and buffers in `status`; T-31 says so. Format spec v0.7: FS-31's protected memory is the `secure_mem` key pool | -| 2026-11-10 | P1 | Out-of-cycle review for the chunking, compression and padding item (E1, E2, E3) | No new threats. T-84 now says that a keyed gear table alone has been broken from observed chunk sizes (ePrint 2025/558, which includes Bupstash's keyed gear, and ePrint 2025/532), so the seed is assumed to leak and Padmé and packs hide the sizes; a PRF chunker (Chk-PHTE) was considered and not taken for format 0. T-40 and T-85 name what landed: one zstd frame per chunk with no dictionary, no compression for the secret class, and blob IDs keyed only for ordinary objects of two or more chunks. R-26 added: zstd's working memory is on the C heap, not wiped and not dump-excluded, since `zstd-safe` has no way to give it a workspace without `unsafe`; the encrypt pipeline item moves it to protected memory. Checklist 15.2: (1) no new data flow; chunking and compression run inside the daemon boundary before encryption (F8); (2) no new STRIDE findings; (3) T-40, T-84 and T-85 keep their risk and phase, with TV-07 and the fuzz targets `inner_plaintext`, `decompress`, `data_blob_open` and `chunker`; (4) 12.3 unchanged; (5) vision 8 and 17 still agree, and vision E1 now says deduplication stays inside one object. Format spec v0.8: the FastCDC cut rule, the reader's zstd frame checks, the inner-plaintext and data-blob check order, and keyed blob IDs exactly for ordinary objects of two or more chunks. After review: secret-class objects are cut at fixed 1 MiB steps with no gear-table lookup (FS-52), since the FastCDC loop leaks bits of plaintext bytes through cache timing and secret chunk lengths would feed T-84's table recovery while secret objects never deduplicate; T-84 says Padmé only coarsens chunk sizes (about 5 bits per chunk) and packs hide them, and R-5 adds per-blob Padmé sizes until packs land; T-40 names ordinary objects of mixed trust (mail stores, chat and app databases, browser profiles) as a residual in the setting of Fábrega et al.'s injection attacks, with a per-path policy (P2) as the recourse, keeping risk L; R-26 adds that zstd's contexts are neither locked nor `MADV_DONTFORK`, with a `ZSTD_customMem` allocator over `secure_mem` planned | +| 2026-11-10 | P1 | Out-of-cycle review for the chunking, compression and padding item (E1, E2, E3) | No new threats. T-84 now says that a keyed gear table alone has been broken from observed chunk sizes (ePrint 2025/558, which includes Bupstash's keyed gear, and ePrint 2025/532), so the seed is assumed to leak, packs hide the sizes and Padmé only coarsens them; a PRF chunker (Chk-PHTE) was considered and not taken for format 0. T-40 and T-85 name what landed: one zstd frame per chunk with no dictionary, no compression for the secret class, and blob IDs keyed only for ordinary objects of two or more chunks. R-26 added: zstd's working memory is on the C heap, not wiped and not dump-excluded, since `zstd-safe` has no way to give it a workspace without `unsafe`; the encrypt pipeline item moves it to protected memory. Checklist 15.2: (1) no new data flow; chunking and compression run inside the daemon boundary before encryption (F8); (2) no new STRIDE findings; (3) T-40, T-84 and T-85 keep their risk; T-40 adds phase P2 for the per-path policy and T-84 now accepts the rest (R-5); all three are tested by TV-07 and the fuzz targets `inner_plaintext`, `decompress`, `data_blob_open` and `chunker`; (4) 12.3 unchanged; (5) vision 8 and 17 still agree, and vision E1 now says deduplication stays inside one object. Format spec v0.8: the FastCDC cut rule, the reader's zstd frame checks, the inner-plaintext and data-blob check order, and keyed blob IDs exactly for ordinary objects of two or more chunks. After review: secret-class objects are cut at fixed 1 MiB steps with no gear-table lookup (FS-52), since the FastCDC loop leaks bits of plaintext bytes through cache timing and secret chunk lengths would feed T-84's table recovery while secret objects never deduplicate; T-84 says Padmé only coarsens chunk sizes (about 7 bits per chunk: 5 significant bits and the octave) and packs hide them, and R-5 adds per-blob Padmé sizes until packs land; T-40 names ordinary objects of mixed trust (mail stores, chat and app databases, browser profiles) as a residual in the setting of Fábrega et al.'s injection attacks, with a per-path policy (P2) as the recourse, keeping risk L; R-26 adds that zstd's contexts are neither locked nor `MADV_DONTFORK`, with a `ZSTD_customMem` allocator over `secure_mem` planned. After a second review: T-85 names in-object reuse as an injection oracle for ordinary objects of mixed trust, with the per-path policy (P2) as the recourse; R-26 adds that freed contexts go back to the allocator unwiped and that the daemon should be non-dumpable with no core limit until the allocator lands; OQ-19 asks whether a later suite adopts a provably secure PRF-based chunker | ### 15.4 Changelog @@ -1041,6 +1042,6 @@ The vision names compliance teams as users ([vision 3](project-vision.md#3-who-i - Linux: [proc_pid_exe(5)](https://man7.org/linux/man-pages/man5/proc_pid_exe.5.html) · [mount.fuse3(8)](https://man7.org/linux/man-pages/man8/mount.fuse3.8.html) · [FUSE I/O modes](https://docs.kernel.org/filesystems/fuse/fuse-io.html) · [FUSE passthrough](https://docs.kernel.org/filesystems/fuse/fuse-passthrough.html) · [core(5)](https://man7.org/linux/man-pages/man5/core.5.html) · [fanotify(7)](https://man7.org/linux/man-pages/man7/fanotify.7.html) · [unix(7) SO_PEERPIDFD](https://man7.org/linux/man-pages/man7/unix.7.html) · [Qualys: Ubuntu user-namespace restriction bypasses](https://blog.qualys.com/vulnerabilities-threat-research/2025/03/27/qualys-tru-discovers-three-bypasses-of-ubuntu-unprivileged-user-namespace-restrictions) · [vmgenid RNG reseeding (LWN)](https://lwn.net/Articles/887207/) - Agents and editors: [Check Point: CVE-2025-59536 and Claude Code project files](https://research.checkpoint.com/2026/rce-and-api-token-exfiltration-through-claude-code-project-files-cve-2025-59536/) · [Check Point: Codex CLI CVE-2025-61260](https://research.checkpoint.com/2025/openai-codex-cli-command-injection-vulnerability/) · [CVE-2025-55284 write-up](https://jmason.ie/2025/08/25/161304a.html) · [GlassWorm (Truesec)](https://www.truesec.com/hub/blog/glassworm-self-propagating-vscode-extension) · [Amazon Q extension prompt (TechRadar)](https://www.techradar.com/pro/hacker-adds-potentially-catastrophic-prompt-to-amazons-ai-coding-service-to-prove-a-point) · [Dev Containers credential sharing](https://code.visualstudio.com/remote/advancedcontainers/sharing-git-credentials) · [Calif: abusing developer trust](https://blog.calif.io/p/vibe-hacking-abusing-developer-trust) · [Claude Code `.claude` directory](https://code.claude.com/docs/en/claude-directory) · [Claude Code sandboxing](https://code.claude.com/docs/en/sandboxing) · [postmark-mcp](https://thehackernews.com/2025/09/first-malicious-mcp-server-found.html) · [Slopsquatting (CSA)](https://labs.cloudsecurityalliance.org/research/csa-research-note-slopsquatting-ai-supply-chain-20260419/) - Supply chain: [crates.io malicious crates faster_log and async_println](https://blog.rust-lang.org/2025/09/24/crates.io-malicious-crates-fasterlog-and-asyncprintln) · [Compromised GitHub Actions (2026)](https://thehackernews.com/2026/09/compromised-github-actions-came-back.html) -- Cryptography: [Chunking attacks on deduplicating storage (ePrint 2025/558)](https://eprint.iacr.org/2025/558) · [ePrint 2025/532](https://eprint.iacr.org/2025/532) · [Injection attacks against E2EE applications (Fábrega et al., IEEE S&P 2024)](https://arxiv.org/abs/2411.09228) · [View-based partitioning (Fábrega et al., USENIX Security 2025)](https://www.usenix.org/conference/usenixsecurity25/presentation/fabrega-partitioning) · [Harnik et al.: side channels in deduplication](https://doi.org/10.1109/MSP.2010.187) · [Ed25519 validation criteria](https://eprint.iacr.org/2020/1244) · [RUSTSEC-2022-0093](https://rustsec.org/advisories/RUSTSEC-2022-0093.html) · [RFC 6962 Merkle hashing](https://www.rfc-editor.org/rfc/rfc6962#section-2.1) · [RFC 5869 HKDF](https://www.rfc-editor.org/rfc/rfc5869#section-3.2) · [Key commitment CMT-4](https://eprint.iacr.org/2022/268) · [X-Wing paper](https://eprint.iacr.org/2024/039) · [Trail of Bits: Shamir pitfalls](https://blog.trailofbits.com/2021/12/21/disclosing-shamirs-secret-sharing-vulnerabilities-and-announcing-zkdocs/) · [Biscuit specification](https://doc.biscuitsec.org/reference/specifications) · [Wycheproof](https://github.com/C2SP/wycheproof) +- Cryptography: [Breaking and Fixing Content-Defined Chunking (ePrint 2025/558, CCS 2025)](https://eprint.iacr.org/2025/558) · [Chunking Attacks on File Backup Services using Content-Defined Chunking (ePrint 2025/532)](https://eprint.iacr.org/2025/532) · [Injection attacks against E2EE applications (Fábrega et al., IEEE S&P 2024)](https://arxiv.org/abs/2411.09228) · [View-based partitioning (Fábrega et al., USENIX Security 2025)](https://www.usenix.org/conference/usenixsecurity25/presentation/fabrega-partitioning) · [Harnik et al.: side channels in deduplication](https://doi.org/10.1109/MSP.2010.187) · [Ed25519 validation criteria](https://eprint.iacr.org/2020/1244) · [RUSTSEC-2022-0093](https://rustsec.org/advisories/RUSTSEC-2022-0093.html) · [RFC 6962 Merkle hashing](https://www.rfc-editor.org/rfc/rfc6962#section-2.1) · [RFC 5869 HKDF](https://www.rfc-editor.org/rfc/rfc5869#section-3.2) · [Key commitment CMT-4](https://eprint.iacr.org/2022/268) · [X-Wing paper](https://eprint.iacr.org/2024/039) · [Trail of Bits: Shamir pitfalls](https://blog.trailofbits.com/2021/12/21/disclosing-shamirs-secret-sharing-vulnerabilities-and-announcing-zkdocs/) · [Biscuit specification](https://doc.biscuitsec.org/reference/specifications) · [Wycheproof](https://github.com/C2SP/wycheproof) - Storage: [Dropbox data governance](https://help.dropbox.com/accounts-billing/plans-upgrades/data-governance) · [Google Drive revisions](https://developers.google.com/drive/manage-revisions) · [Google Drive API terms](https://developers.google.com/drive/terms) · [Restricted-scope verification](https://developers.google.com/identity/protocols/oauth2/production-readiness/restricted-scope-verification) · [Drive API limits](https://developers.google.com/drive/api/guides/limits) · [Backblaze B2 Object Lock](https://www.backblaze.com/docs/cloud-storage-enable-and-manage-lock-features) · [M-Trends 2025](https://cloud.google.com/blog/topics/threat-intelligence/m-trends-2025/) · [Codefinger S3 ransomware](https://www.bleepingcomputer.com/news/security/ransomware-abuses-amazon-aws-feature-to-encrypt-s3-buckets/) · [Meta on silent data corruption](https://engineering.fb.com/2025/07/22/data-infrastructure/how-meta-keeps-its-ai-hardware-reliable/) · [S3 no charges for unauthorised errors](https://aws.amazon.com/about-aws/whats-new/2024/08/amazon-s3-no-charges-several-http-error-codes) - Compliance: [PCI DSS 4.0 new requirements (BDO)](https://www.bdo.com/getmedia/7a423c2a-ec5d-45c1-b2d0-8a5030d0fa80/ASSR-ASP-PCI-4-0-New-Requirements.pdf) · [HHS HITECH guidance](https://www.foulston.com/uploads/HHS_Issues_HITECH_Guidance.pdf) · [EAR 2021 encryption rule (Goodwin)](https://www.goodwinlaw.com/en/insights/publications/2021/03/03_31-spring-cleaning-us-department-of-commerce) · [OpenSSF Best Practices: cryptography criteria](https://www.bestpractices.dev/en/criteria/0)