diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs index 94ec7b1..5cf937f 100644 --- a/src/uapi16/content.rs +++ b/src/uapi16/content.rs @@ -183,7 +183,9 @@ impl FileObject { /// directory refers to. /// /// A literal is taken first, as the specification suggests: the - /// manifest carries the data itself. Otherwise the data is in the file + /// manifest carries the data itself. A reader and a writer refuse a + /// literal that does not match the hashes the manifest gives for it and + /// for the data of the object. Otherwise the data is in the file /// next to the manifest that the first contents object without an /// encoding names, or in the file of the object's own name where that /// contents object names no place. A regular file without contents @@ -267,7 +269,7 @@ impl FileObject { /// The data of the file in the literal `literal`: from `offset` on, as /// many bytes as the object says it has. An offset or a size beyond the /// literal takes all there is, which the size of the object then finds. - fn data_in_literal<'a>(&self, literal: &'a [u8], offset: u64) -> &'a [u8] { + pub(crate) fn data_in_literal<'a>(&self, literal: &'a [u8], offset: u64) -> &'a [u8] { let offset = usize::try_from(offset).unwrap_or(usize::MAX); let data = literal.get(offset..).unwrap_or(&[]); match self.size.map(usize::try_from) { @@ -1186,6 +1188,7 @@ impl DataProvider for StreamProvider { #[cfg(all(test, target_os = "linux"))] mod tests { use super::*; + use crate::error::Problem; use crate::testing::{json, manifest, read_whole, sequence, HELLO, TRAILER, WORLD}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -1693,7 +1696,14 @@ mod tests { assert_eq!(files.read(), 5); // A part of a literal is held against the hash of all of the // literal the manifest gives, as a part of a file is, unless the - // object has a hash of its own. + // object has a hash of its own. A reader refuses a literal that + // does not match a hash the manifest gives for it, so only an object + // changed after it was read gets here. + let refused = |record: &str| { + let e = read_whole(&manifest(&[record])).unwrap_err(); + (e.kind(), e.field()) + }; + let contradiction = (ErrorKind::Manifest(Problem::Contradiction), Some(Field::Literal)); for (record, data) in [ ( r#"{"name":"x","contents":[{"literal":"aGVsbG8=","offset":1,"originalSha256":"#, @@ -1704,9 +1714,10 @@ mod tests { "he", ), ] { - let o = object(&format!(r#"{}"{}"}}]}}"#, record, HELLO)); + let mut o = object(&format!(r#"{}"{}"}}]}}"#, record, HELLO)); assert_eq!(copy(&o, &mut provider).unwrap(), data.as_bytes()); - let o = object(&format!(r#"{}"{}"}}]}}"#, record, WORLD)); + assert_eq!(refused(&format!(r#"{}"{}"}}]}}"#, record, WORLD)), contradiction); + o.contents[0].original_sha256 = WORLD.parse().ok(); let e = copy(&o, &mut provider).unwrap_err(); assert_eq!( facts(&e), @@ -1719,16 +1730,25 @@ mod tests { ) ); } - let o = object(&format!( - r#"{{"name":"x","size":2,"sha256":"{}","contents":[{{"literal":"aGVsbG8=","originalSha256":"{}"}}]}}"#, - Sha256::digest(b"he"), - WORLD - )); + let record = |original: &str| { + format!( + r#"{{"name":"x","size":2,"sha256":"{}","contents":[{{"literal":"aGVsbG8=","originalSha256":"{}"}}]}}"#, + Sha256::digest(b"he"), + original + ) + }; + assert_eq!(refused(&record(WORLD)), contradiction); + let mut o = object(&record(HELLO)); + o.contents[0].original_sha256 = WORLD.parse().ok(); assert_eq!(copy(&o, &mut provider).unwrap(), b"he"); // A literal that is not what the object says. - let o = object( - r#"{"name":"x","size":5,"contents":[{"literal":"aGVsbG8="}],"sha256":"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7"}"#, + let record = format!( + r#"{{"name":"x","size":5,"contents":[{{"literal":"aGVsbG8="}}],"sha256":"{}"}}"#, + WORLD ); + assert_eq!(refused(&record), contradiction); + let mut o = object(r#"{"name":"x","size":5,"contents":[{"literal":"aGVsbG8="}]}"#); + o.sha256 = WORLD.parse().ok(); assert_eq!(copy(&o, &mut provider).unwrap_err().kind(), hash); let mut o = object(r#"{"name":"x","contents":[{"literal":"aGVsbG8="}]}"#); o.size = Some(6); diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index aa2334d..aa90fac 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -388,7 +388,7 @@ impl Draft { } // The contents objects were checked when they were read, and hold // what follows from their fields. - let data = object.check_consistency(subject, |contents| Ok(contents.data()))?; + let data = object.check_consistency(subject, object.contents.iter().map(ContentsObject::data))?; object.fill_in_data(data); Ok(()) } @@ -466,8 +466,12 @@ impl FileObject { /// Fills in what follows from the contents objects, as a reader does: /// what each of them says of its own data, and the size and the hash of - /// the data of the object. Where fields contradict each other nothing - /// follows from them, and a writer refuses the object. + /// the data of the object. Only a contents object a reader takes gives + /// anything: one whose values a reader takes, see + /// [`ContentsObject::check_values`], and whose fields agree with each + /// other. Where one of them does not, nothing is filled in for the + /// object either, as a reader refuses its record and a writer refuses + /// the object. pub(crate) fn fill_in_from_contents(&mut self) { // The object is in no record, and what is wrong with it is not // shown, so the number of the record does not matter. @@ -475,33 +479,46 @@ impl FileObject { let data: Vec<_> = self .contents .iter() - .map(|contents| contents.check_consistency(subject).ok()) + .map(|contents| { + contents + .check_values(subject) + .and_then(|()| contents.check_consistency(subject)) + .ok() + }) .collect(); + let taken = data.iter().all(Option::is_some); for (contents, data) in self.contents.iter_mut().zip(data) { if let Some(data) = data { contents.fill_in(data); } } + // A contents object a reader refuses gives nothing for the object + // either. A reader refuses its record. + if !taken { + return; + } let subject = Subject::new(self, ROOT_RECORD); - if let Ok(data) = self.check_consistency(subject, |contents| Ok(contents.data())) { + if let Ok(data) = self.check_consistency(subject, self.contents.iter().map(ContentsObject::data)) { self.fill_in_data(data); } } /// Checks that the fields of the object agree with each other, as the - /// specification requires: `readOnly` and `mode`, and the size and the - /// hash of the object and those of its contents objects. `contents_data` - /// gives what each contents object says of its data: what - /// [`ContentsObject::check_consistency`] returns for it, or what its fields - /// hold once a reader checked and filled it in. Returns the size and the - /// hash of the data of the object: those it gives, and those that follow - /// from its contents objects and from each other. Whether `gptFlags` - /// agrees with the fields that give its flags one by one depends on what - /// the manifest records, see [`FileObject::check_partition_flags`]. + /// specification requires: `readOnly` and `mode`, the size and the + /// hash of the object and those of its contents objects, and the hash + /// of the object and the data in its literals. `contents_data` gives + /// what each contents object says of its data, in their order: what + /// [`ContentsObject::check_consistency`] returned for it, or what its + /// fields hold once a reader checked and filled it in. Returns the size + /// and the hash of the data of the object: those it gives, and those + /// that follow from its contents objects and from each other. Whether + /// `gptFlags` agrees with the fields that give its flags one by one + /// depends on what the manifest records, see + /// [`FileObject::check_partition_flags`]. pub(crate) fn check_consistency( &self, subject: Subject<'_>, - contents_data: impl Fn(&ContentsObject) -> Result, + contents_data: impl Iterator + Clone, ) -> Result { self.inode.check_read_only(subject)?; // The size and the hash of the object and those of its contents @@ -515,13 +532,16 @@ impl FileObject { size: self.size, sha256: self.sha256, }; - for contents in &self.contents { - let original = contents_data(contents)?.original; + for (contents, contents_data) in self.contents.iter().zip(contents_data.clone()) { + let original = contents_data.original; let Some(total) = original.size else { continue; }; - // ContentsObject::check_consistency found the offset inside the data. - let rest = total - contents.offset; + // The offset of a contents object that passed its own check is + // inside the data. + let Some(rest) = total.checked_sub(contents.offset) else { + return Err(Error::offset_beyond_data(subject, contents.offset, total)); + }; match (self.size, data.size) { (Some(stated), _) => { if contents.offset.checked_add(stated).is_none_or(|end| end > total) { @@ -563,9 +583,49 @@ impl FileObject { // What the size and the hash were given or follow from has to agree. data.reconcile() .map_err(|conflict| conflict.into_error(subject, Field::Sha256, Field::Size))?; + if let Some(sha256) = data.sha256 { + self.check_literals(sha256, contents_data, subject)?; + } Ok(data) } + /// Checks that the data of the object in each of its literals without an + /// encoding has the hash `sha256`, the one + /// [`FileObject::check_consistency`] found for the object. The data is + /// the part of the literal that [`FileObject::data_location`] takes: + /// from the offset on, as long as the object is. `contents_data` gives + /// what each contents object says of its data. A literal that is all of + /// the data and has a hash of its own was held against that hash, which + /// the hash of the object agrees with, and is not hashed again. + fn check_literals( + &self, + sha256: Sha256, + contents_data: impl Iterator, + subject: Subject<'_>, + ) -> Result<(), Error> { + for (contents, contents_data) in self.contents.iter().zip(contents_data) { + let Some(literal) = contents.literal().filter(|_| contents.encoding.is_none()) else { + continue; + }; + let part = self.data_in_literal(literal, contents.offset); + if part.len() == literal.len() && contents_data.original.sha256.is_some() { + continue; + } + if Sha256::digest(part) != sha256 { + return Err(Error::manifest( + Problem::Contradiction, + format!( + "{}: the data in literal contents does not match '{}'", + subject, + Field::Sha256 + ), + ) + .at(Field::Literal)); + } + } + Ok(()) + } + /// Checks that the attribute flags of the partition the object /// describes agree where they are given twice: all of them in /// `gptFlags`, and one each in `gptFlagNoAuto`, `gptFlagGrowFileSystem` @@ -712,8 +772,9 @@ impl ContentsObject { /// its data with what follows from them: a literal gives the size of /// the stored data, and without an encoding the stored data is the /// data. A size of 0 and the hash of no data go together. `httpHeaders` - /// come with a URL only, and the offset is inside the data. `subject` - /// names the file object the contents object belongs to. + /// come with a URL only, and the offset is inside the data. A literal + /// has the hash given for the data as it is stored. `subject` names the + /// file object the contents object belongs to. pub(crate) fn check_consistency(&self, subject: Subject<'_>) -> Result { if !self.http_headers.is_empty() && self.url().is_none() { return Err(Error::manifest( @@ -780,14 +841,24 @@ impl ContentsObject { } if let Some(total) = data.original.size { if self.offset > total { + return Err(Error::offset_beyond_data(subject, self.offset, total)); + } + } + // A literal is the data as it is stored. Its hash is the encoded + // hash, and without an encoding the original hash, which is the + // same by now. The original hash of an encoded literal is that of + // the decoded data, which is not checked. + if let (Some(literal), Some(sha256)) = (self.literal(), data.encoded.sha256) { + if Sha256::digest(literal) != sha256 { + let given = match self.encoded_sha256 { + Some(_) => Field::EncodedSha256, + None => Field::OriginalSha256, + }; return Err(Error::manifest( - Problem::InvalidContents, - format!( - "{}: contents offset {} is beyond the data size {}", - subject, self.offset, total - ), + Problem::Contradiction, + format!("{}: literal contents do not match '{}'", subject, given), ) - .at(Field::Offset)); + .at(Field::Literal)); } } Ok(data) @@ -2400,7 +2471,7 @@ mod tests { let subject = Subject::new(object, 1); assert_eq!( object - .check_consistency(subject, |contents| contents.check_consistency(subject)) + .check_consistency(subject, object.contents.iter().map(ContentsObject::data)) .unwrap(), SizeAndHash::default() ); @@ -2412,7 +2483,7 @@ mod tests { let mut given = object.clone(); given.inode.filled_in.remove(Field::ReadOnly); let e = given - .check_consistency(Subject::new(&given, 1), |contents| Ok(contents.data())) + .check_consistency(Subject::new(&given, 1), given.contents.iter().map(ContentsObject::data)) .unwrap_err(); assert_eq!( (e.kind(), e.field()), @@ -2427,7 +2498,12 @@ mod tests { fn consistency_of_objects_not_read() { let check = |object: &FileObject| { let subject = Subject::new(object, 1); - object.check_consistency(subject, |contents| contents.check_consistency(subject)) + let contents_data = object + .contents + .iter() + .map(|contents| contents.check_consistency(subject)) + .collect::, _>>()?; + object.check_consistency(subject, contents_data.into_iter()) }; let file = |size: Option, contents: ContentsObject| { let mut object = FileObject::new(Name::new("x").unwrap()); @@ -2478,6 +2554,51 @@ mod tests { } } + /// set_contents() holds the object against its contents objects, also + /// against one whose offset is beyond its data, which its own check + /// refuses. There is no rest of the data from that offset on, and the + /// size the object has stays. + #[test] + fn set_contents_with_an_offset_beyond_the_data() { + let file = |offset: u64, original_size: u64| { + let mut contents = ContentsObject::new(ContentsSource::File(Name::new("a").unwrap())); + contents.set_offset(offset); + contents.set_original_size(Some(original_size)); + contents + }; + let mut headers = ContentsObject::new(ContentsSource::Implied); + headers.set_http_headers(vec![("A".to_string(), "b".to_string())]); + headers.set_original_size(Some(0)); + headers.set_offset(1); + let mut encoded = ContentsObject::new(ContentsSource::Literal(b"hello".to_vec())); + encoded.set_encoding(Some("gzip".to_string())); + encoded.set_original_size(Some(3)); + encoded.set_offset(4); + let whole = ContentsObject::new(ContentsSource::File(Name::new("a").unwrap())); + for (size, contents) in [ + (None, vec![file(6, 5)]), + (Some(1), vec![file(6, 5)]), + (None, vec![headers]), + (None, vec![encoded]), + (None, vec![whole, file(5, 4)]), + (None, vec![file(u64::MAX, 0)]), + ] { + let mut object = FileObject::new(Name::new("x").unwrap()); + object.set_size(size); + object.set_contents(contents); + assert_eq!(object.size(), size, "{:?}", object); + assert!(!object.filled_in().contains(Field::Size), "{:?}", object); + } + // An object a reader read, with the offset set beyond the data. + let mut object = object(r#"{"name":"x","contents":[{"file":"a","originalSize":5}]}"#); + assert_eq!(object.size(), Some(5)); + let mut contents = object.take_contents(); + contents[0].set_offset(6); + object.set_contents(contents); + assert_eq!(object.size(), None); + assert!(!object.filled_in().contains(Field::Size)); + } + /// `gptFlags` holds the flags that `gptFlagNoAuto`, /// `gptFlagGrowFileSystem` and `readOnly` give one each, and the two /// agree. Where the manifest lists the feature of a field, an object @@ -2818,6 +2939,214 @@ mod tests { } } + /// set_contents() fills in what a reader fills in for the same record, + /// marks and all. Where a contents object has fields that contradict + /// each other or a value a reader refuses, a reader refuses the record, + /// and set_contents() fills in nothing for the object: neither its size + /// nor its hash. + #[test] + fn set_contents_fills_in_what_a_reader_does() { + let hello: Option = HELLO.parse().ok(); + let world: Option = WORLD.parse().ok(); + let literal = || ContentsObject::new(ContentsSource::Literal(b"hello".to_vec())); + let file = || ContentsObject::new(ContentsSource::File(Name::new("a").unwrap())); + let set = |size: Option, sha256: Option, contents: Vec| { + let mut object = FileObject::new(Name::new("x").unwrap()); + object.set_size(size); + object.set_sha256(sha256); + object.set_contents(contents); + object + }; + // The literal "hello" with the hash of "world" gave the object the + // size 5 and the hash of "world". + let mut contents = literal(); + contents.set_original_size(Some(5)); + contents.set_original_sha256(world); + let object = set(None, None, vec![contents]); + assert_eq!((object.size(), object.sha256()), (None, None)); + assert!(object.filled_in().is_empty() && object.contents()[0].filled_in().is_empty()); + let e = refused(&format!( + r#"{{"name":"x","contents":[{{"literal":"aGVsbG8=","originalSize":5,"originalSha256":"{}"}}]}}"#, + WORLD + )); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::Contradiction), Some(Field::Literal)) + ); + // Contents objects that agree give what a reader gives. + let he = Sha256::digest(b"he"); + for (record, object) in [ + ( + r#"{"name":"x","contents":[{"literal":"aGVsbG8="}]}"#.to_string(), + set(None, None, vec![literal()]), + ), + ( + format!( + r#"{{"name":"x","contents":[{{"literal":"aGVsbG8=","originalSha256":"{}"}}]}}"#, + HELLO + ), + set( + None, + None, + vec![ContentsObject { + original_sha256: hello, + ..literal() + }], + ), + ), + ( + format!( + r#"{{"name":"x","size":2,"sha256":"{}","contents":[{{"literal":"aGVsbG8="}}]}}"#, + he + ), + set(Some(2), Some(he), vec![literal()]), + ), + ( + r#"{"name":"x","contents":[{"file":"a","offset":2,"originalSize":7}]}"#.to_string(), + set( + None, + None, + vec![ContentsObject { + offset: 2, + original_size: Some(7), + ..file() + }], + ), + ), + ( + format!( + r#"{{"name":"x","contents":[{{"file":"a","originalSize":5,"originalSha256":"{}"}},{{"literal":"aGVsbG8="}}]}}"#, + HELLO + ), + set( + None, + None, + vec![ + ContentsObject { + original_size: Some(5), + original_sha256: hello, + ..file() + }, + literal(), + ], + ), + ), + ( + r#"{"name":"x","contents":[{"file":"a","encoding":"gzip","encodedSize":3,"originalSize":5}]}"# + .to_string(), + set( + None, + None, + vec![ContentsObject { + encoding: Some("gzip".into()), + encoded_size: Some(3), + original_size: Some(5), + ..file() + }], + ), + ), + ( + r#"{"name":"x","contents":[{"url":"https://example.com/x","httpHeaders":{"A":"b"},"originalSize":5}]}"# + .to_string(), + set( + None, + None, + vec![ContentsObject { + http_headers: vec![("A".into(), "b".into())], + original_size: Some(5), + ..ContentsObject::new(ContentsSource::Url("https://example.com/x".into())) + }], + ), + ), + ] { + assert_eq!(object, self::object(&record), "{}", record); + } + // A contents object that contradicts itself, also next to one that + // agrees, which is filled in all the same. + for (record, contents) in [ + ( + r#"{"name":"x","contents":[{"file":"a","encodedSize":3,"originalSize":5}]}"#.to_string(), + vec![ContentsObject { + encoded_size: Some(3), + original_size: Some(5), + ..file() + }], + ), + ( + format!( + r#"{{"name":"x","contents":[{{"file":"a","originalSize":5,"originalSha256":"{}"}},{{"literal":"aGVsbG8=","originalSha256":"{}"}}]}}"#, + HELLO, WORLD + ), + vec![ + ContentsObject { + original_size: Some(5), + original_sha256: hello, + ..file() + }, + ContentsObject { + original_sha256: world, + ..literal() + }, + ], + ), + ] { + let e = refused(&record); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::Contradiction), "{}", record); + let object = set(None, None, contents); + assert_eq!((object.size(), object.sha256()), (None, None), "{}", record); + assert!(object.filled_in().is_empty(), "{}", record); + assert!(object.contents().last().unwrap().filled_in().is_empty(), "{}", record); + if let [agrees, _] = object.contents() { + assert!(agrees.filled_in().contains(Field::EncodedSize), "{}", record); + } + } + // A contents object with a value a reader refuses: a URL that is + // neither http nor https, the encoding that stands for none and a + // name that is not one of an HTTP header field. + let ftp = || ContentsObject::new(ContentsSource::Url("ftp://example.com/x".into())); + let https = || ContentsObject::new(ContentsSource::Url("https://example.com/x".into())); + for (record, contents, field) in [ + ( + r#"{"name":"x","contents":[{"url":"ftp://example.com/x","originalSize":5}]}"#, + ContentsObject { + original_size: Some(5), + ..ftp() + }, + Field::Url, + ), + ( + r#"{"name":"x","contents":[{"literal":"aGVsbG8=","encoding":"identity","originalSize":5}]}"#, + ContentsObject { + encoding: Some("identity".into()), + original_size: Some(5), + ..literal() + }, + Field::Encoding, + ), + ( + r#"{"name":"x","contents":[{"url":"https://example.com/x","httpHeaders":{"bad name":"b"},"originalSize":5}]}"#, + ContentsObject { + http_headers: vec![("bad name".into(), "b".into())], + original_size: Some(5), + ..https() + }, + Field::HttpHeaders, + ), + ] { + let e = refused(record); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::InvalidContents), Some(field)), + "{}", + record + ); + let object = set(None, None, vec![contents.clone()]); + assert_eq!((object.size(), object.sha256()), (None, None), "{}", record); + assert!(object.filled_in().is_empty(), "{}", record); + assert_eq!(object.contents(), [contents], "{}", record); + } + } + #[test] fn contents_objects() { let contents = |text: &str| { diff --git a/src/uapi16/error.rs b/src/uapi16/error.rs index b797f08..886d2c1 100644 --- a/src/uapi16/error.rs +++ b/src/uapi16/error.rs @@ -624,6 +624,19 @@ impl Error { .at(Field::Contents) } + /// A contents object of the file object `subject` names whose offset + /// `offset` is beyond the size `total` of its data. + pub(crate) fn offset_beyond_data(subject: Subject<'_>, offset: u64, total: u64) -> Error { + Error::manifest( + Problem::InvalidContents, + format!( + "{}: contents offset {} is beyond the data size {}", + subject, offset, total + ), + ) + .at(Field::Offset) + } + /// `object`, which `subject` names, states the flag of the field /// `field`, which it cannot have, see [`FileObject::unpermitted_flag`]. pub(crate) fn unpermitted_flag(object: &FileObject, field: Field, subject: Subject<'_>) -> Error { diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 6263daf..e01ad81 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -794,6 +794,15 @@ impl FlagStates { filled_in }) } + + /// Whether `other` says the same of every flag: set, cleared or not + /// known. Which flags a reader filled in does not count. + pub(crate) fn eq_ignore_filled_in(&self, other: &FlagStates) -> bool { + // Every field is named, so that a new field breaks the build here + // until it is compared. + let FlagStates { stated, set, filled: _ } = self; + *stated == other.stated && *set == other.set + } } /// The fields of an object of a manifest that a reader filled in, which @@ -818,6 +827,13 @@ impl FlagStates { /// manifest fills them in again. The contents objects of a file object /// fill in again what follows from them when they are set, see /// [`FileObject::set_contents`]. +/// +/// `==` of the objects compares these marks too. Equal objects are the +/// same record, and a writer writes or refuses them alike. An object with a +/// value a reader filled in is not equal to one with the same value set. +/// [`FileObject::eq_ignore_filled_in`], [`RootObject::eq_ignore_filled_in`], +/// [`InodeAttributes::eq_ignore_filled_in`] and +/// [`ContentsObject::eq_ignore_filled_in`] compare the values alone. #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] pub struct FilledIn(u16); @@ -1092,6 +1108,10 @@ pub enum ContentsSource { /// and hashes are those of the data as it is stored, the original ones /// those of the decoded data. The file object's data is the part of the /// decoded data that starts at `offset`. +/// +/// `==` compares which values a reader filled in as well, see +/// [`FilledIn`]. [`ContentsObject::eq_ignore_filled_in`] compares the +/// values alone. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct ContentsObject { @@ -1243,6 +1263,33 @@ impl ContentsObject { self.filled_in } + /// Whether `other` has the same values: what the getters return. Unlike + /// `==` it leaves out which values a reader filled in, see + /// [`FilledIn`]. + pub fn eq_ignore_filled_in(&self, other: &ContentsObject) -> bool { + // Every field is named, so that a new field breaks the build here + // until it is compared. + let ContentsObject { + source, + http_headers, + encoding, + encoded_size, + encoded_sha256, + original_size, + original_sha256, + offset, + filled_in: _, + } = self; + *source == other.source + && *http_headers == other.http_headers + && *encoding == other.encoding + && *encoded_size == other.encoded_size + && *encoded_sha256 == other.encoded_sha256 + && *original_size == other.original_size + && *original_sha256 == other.original_sha256 + && *offset == other.offset + } + /// Drops the sizes and hashes a reader filled in, which follow from the /// other fields: they are None, and none is noted as filled in. fn drop_filled_in(&mut self) { @@ -1277,6 +1324,10 @@ impl ContentsObject { /// `chattr(1)` changes, have a field each, such as `flagImmutable`. Only /// regular files and directories have them, the root directory among /// them. +/// +/// `==` compares which values a reader filled in as well, see +/// [`FilledIn`]. [`InodeAttributes::eq_ignore_filled_in`] compares the +/// values alone. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct InodeAttributes { @@ -1485,6 +1536,35 @@ impl InodeAttributes { self.filled_in.union(self.flags.filled_in()) } + /// Whether `other` has the same values: what the getters return. Unlike + /// `==` it leaves out which values a reader filled in, see + /// [`FilledIn`]. + pub fn eq_ignore_filled_in(&self, other: &InodeAttributes) -> bool { + // Every field is named, so that a new field breaks the build here + // until it is compared. + let InodeAttributes { + mode, + uid, + gid, + user_name, + group_name, + mtime_nsec, + user_xattrs, + read_only, + flags, + filled_in: _, + } = self; + *mode == other.mode + && *uid == other.uid + && *gid == other.gid + && *user_name == other.user_name + && *group_name == other.group_name + && *mtime_nsec == other.mtime_nsec + && *user_xattrs == other.user_xattrs + && *read_only == other.read_only + && flags.eq_ignore_filled_in(&other.flags) + } + /// The modification time, if the attributes have one. pub fn mtime(&self) -> Option { self.mtime_nsec.map(|nsec| UNIX_EPOCH + Duration::from_nanos(nsec)) @@ -1613,6 +1693,10 @@ impl InodeAttributes { /// [`InodeAttributes::read_only()`]. Only regular files and directories /// have DOS attributes, and the root directory has none: the root /// directory of FAT has no directory entry to keep them in. +/// +/// `==` compares which values a reader filled in as well, see +/// [`FilledIn`]. [`FileObject::eq_ignore_filled_in`] compares the values +/// alone. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct FileObject { @@ -1734,11 +1818,15 @@ impl FileObject { /// Sets `contents`, and fills in what follows from them as a reader /// does, see [`FilledIn`]: what each contents object says of its own - /// data, and the size and the hash of the data of the file. What a + /// data, and the size and the hash of the data of the file. Only a + /// contents object a reader takes gives anything. Where one has a value + /// a reader refuses, such as a URL that is neither http nor https, or + /// fields that contradict each other, nothing is filled in for it, and + /// the size and the hash of the file are not filled in either. What a /// reader filled in that no longer follows is dropped, and what the /// object states stays. A writer refuses an object whose fields - /// contradict each other, and more than [`MAX_CONTENTS`] contents - /// objects. + /// contradict each other or that has such a value, and more than + /// [`MAX_CONTENTS`] contents objects. /// /// [`MAX_CONTENTS`]: crate::MAX_CONTENTS pub fn set_contents(&mut self, contents: Vec) { @@ -1836,6 +1924,67 @@ impl FileObject { .union(self.inode.filled_in()) } + /// Whether `other` has the same values: what the getters return, those + /// of the contents objects and of the inode attributes among them. + /// Unlike `==` it leaves out which values a reader filled in, see + /// [`FilledIn`]. + /// + /// ``` + /// use uapi16::{FileObject, Name, Object, Reader, Sha256}; + /// + /// let manifest = concat!( + /// "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n", + /// "\x1e{\"name\":\"e\",\"size\":0}\n", + /// "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + /// ); + /// let mut reader = Reader::open(manifest.as_bytes())?; + /// let Some(Object::File(read)) = reader.next().transpose()? else { + /// panic!("no file object"); + /// }; + /// // The reader filled in the hash of no data for the size 0. + /// let mut set = FileObject::new(Name::new("e")?); + /// set.set_size(Some(0)); + /// set.set_sha256(Some(Sha256::EMPTY)); + /// assert!(read.eq_ignore_filled_in(&set)); + /// assert_ne!(*read, set); + /// # Ok::<(), Box>(()) + /// ``` + pub fn eq_ignore_filled_in(&self, other: &FileObject) -> bool { + // Every field is named, so that a new field breaks the build here + // until it is compared. + let FileObject { + name, + inode_type, + size, + sha256, + contents, + inode_token, + major, + minor, + gpt, + dos_flags, + inode, + validity, + filled_in: _, + } = self; + *name == other.name + && *inode_type == other.inode_type + && *size == other.size + && *sha256 == other.sha256 + && contents.len() == other.contents.len() + && contents + .iter() + .zip(&other.contents) + .all(|(contents, other)| contents.eq_ignore_filled_in(other)) + && *inode_token == other.inode_token + && *major == other.major + && *minor == other.minor + && *gpt == other.gpt + && dos_flags.eq_ignore_filled_in(&other.dos_flags) + && inode.eq_ignore_filled_in(&other.inode) + && *validity == other.validity + } + /// Drops the size and the hash a reader filled in, which follow from /// each other and from the contents objects: they are None, and /// neither is noted as filled in. @@ -1978,6 +2127,10 @@ impl FileObject { /// what the manifest records and the order it lists its file objects in, /// and the identity of the file system or of the partition table the file /// objects are placed in. +/// +/// `==` compares which values a reader filled in as well, see +/// [`FilledIn`]. [`RootObject::eq_ignore_filled_in`] compares the values +/// alone. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct RootObject { @@ -2064,6 +2217,28 @@ impl RootObject { self.validity = validity; } + /// Whether `other` has the same values: what the getters return, those + /// of the inode attributes among them. Unlike `==` it leaves out which + /// values a reader filled in, see [`FilledIn`]. + pub fn eq_ignore_filled_in(&self, other: &RootObject) -> bool { + // Every field is named, so that a new field breaks the build here + // until it is compared. + let RootObject { + inode, + file_system, + gpt_disk_uuid, + order, + features, + validity, + } = self; + inode.eq_ignore_filled_in(&other.inode) + && *file_system == other.file_system + && *gpt_disk_uuid == other.gpt_disk_uuid + && *order == other.order + && *features == other.features + && *validity == other.validity + } + /// Whether the object has `field`, one of /// [`RootObject::FEATURE_FIELDS`]. fn has_feature_field(&self, field: Field) -> bool { @@ -2832,4 +3007,160 @@ mod tests { assert_eq!(inode.remove_user_xattr("comment"), Some(b"two".to_vec())); assert_eq!(inode.user_xattrs().map(|xattrs| xattrs.len()), Some(0)); } + + /// eq_ignore_filled_in() compares every value and none of the marks of + /// what a reader filled in, which == compares too. The objects are built + /// with every field named, so that a new field breaks the build here + /// until it has a case below. + #[test] + fn compares_the_values_without_the_marks() { + /// Checks that each of `changes`, which changes one value, makes an + /// object differ from `object` for `eq`, both ways around. + fn each_differs(object: &T, changes: &[Give], eq: fn(&T, &T) -> bool) { + assert!(eq(object, object)); + for change in changes { + let mut changed = object.clone(); + change(&mut changed); + assert!(!eq(object, &changed) && !eq(&changed, object), "{:?}", changed); + } + } + let contents = ContentsObject { + source: ContentsSource::Literal(b"hello".to_vec()), + http_headers: Vec::new(), + encoding: None, + encoded_size: Some(5), + encoded_sha256: None, + original_size: Some(5), + original_sha256: None, + offset: 0, + filled_in: FilledIn::default(), + }; + let inode = InodeAttributes { + mode: Some(Mode::new(0o644).unwrap()), + uid: Some(1), + gid: Some(2), + user_name: Some("u".into()), + group_name: Some("g".into()), + mtime_nsec: Some(3), + user_xattrs: Some(Box::default()), + read_only: Some(false), + flags: FlagStates { + stated: InodeFlags::IMMUTABLE | InodeFlags::NO_DUMP, + set: InodeFlags::IMMUTABLE, + filled: InodeFlags::default(), + }, + filled_in: FilledIn::default(), + }; + let object = FileObject { + name: Name::new("f").unwrap(), + inode_type: InodeType::Regular, + size: Some(5), + sha256: Some(Sha256::digest(b"hello")), + contents: vec![contents.clone()], + inode_token: NonZeroU64::new(1), + major: None, + minor: None, + gpt: None, + dos_flags: FlagStates { + stated: DosFlags::HIDDEN, + set: DosFlags::default(), + filled: DosFlags::default(), + }, + inode: inode.clone(), + validity: ValidityWindow::default(), + filled_in: FilledIn::default(), + }; + let root = RootObject { + inode: inode.clone(), + file_system: FileSystemIdentity::default(), + gpt_disk_uuid: None, + order: None, + features: None, + validity: ValidityWindow::default(), + }; + each_differs( + &contents, + &[ + |c| c.source = ContentsSource::Url("https://example.com/x".into()), + |c| c.http_headers = vec![("A".into(), "b".into())], + |c| c.encoding = Some("gzip".into()), + |c| c.encoded_size = None, + |c| c.encoded_sha256 = Some(Sha256::EMPTY), + |c| c.original_size = None, + |c| c.original_sha256 = Some(Sha256::EMPTY), + |c| c.offset = 1, + ], + ContentsObject::eq_ignore_filled_in, + ); + each_differs( + &inode, + &[ + |i| i.mode = None, + |i| i.uid = None, + |i| i.gid = None, + |i| i.user_name = None, + |i| i.group_name = None, + |i| i.mtime_nsec = None, + |i| i.user_xattrs = None, + |i| i.read_only = None, + // A flag not known any more, and one set instead of cleared. + |i| i.flags.put(InodeFlags::NO_DUMP, None), + |i| i.flags.put(InodeFlags::NO_DUMP, Some(true)), + ], + InodeAttributes::eq_ignore_filled_in, + ); + each_differs( + &object, + &[ + |o| o.name = Name::new("g").unwrap(), + |o| o.inode_type = InodeType::Symlink, + |o| o.size = None, + |o| o.sha256 = None, + |o| o.contents.clear(), + |o| o.contents[0].offset = 1, + |o| o.inode_token = None, + |o| o.major = Some(1), + |o| o.minor = Some(1), + |o| o.gpt = Some(Box::default()), + |o| o.dos_flags.put(DosFlags::HIDDEN, None), + |o| o.dos_flags.put(DosFlags::HIDDEN, Some(true)), + |o| o.inode.uid = None, + |o| o.validity.state = Validity::Revoked, + ], + FileObject::eq_ignore_filled_in, + ); + each_differs( + &root, + &[ + |r| r.inode.uid = None, + |r| r.file_system.label = Some("ESP".into()), + |r| r.gpt_disk_uuid = Some(Uuid::new([1; Uuid::SIZE])), + |r| r.order = Some(Order::CodePoint), + |r| r.features = Some(Features::ALL), + |r| r.validity.until_usec = Some(1), + ], + RootObject::eq_ignore_filled_in, + ); + // The same values, filled in by a reader on one side and set on the + // other. + let mut filled = contents.clone(); + filled.filled_in.insert(Field::EncodedSize); + assert!(filled.eq_ignore_filled_in(&contents) && filled != contents); + let (mut filled, mut set) = (inode.clone(), inode.clone()); + filled.filled_in.insert(Field::ReadOnly); + filled.filled_in.insert(Field::ExtendedAttributes); + filled.flags.fill_in(Features::FLAG_NO_COW, InodeType::Regular); + set.set_flag_no_cow(Some(false)); + assert!(filled.eq_ignore_filled_in(&set) && filled != set); + let (mut filled, mut set) = (object.clone(), object.clone()); + filled.filled_in.insert(Field::Size); + filled.contents[0].filled_in.insert(Field::OriginalSize); + filled.inode.filled_in.insert(Field::ReadOnly); + filled.dos_flags.fill_in(Features::FLAG_ARCHIVE, InodeType::Regular); + set.set_flag_archive(Some(false)); + assert!(filled.eq_ignore_filled_in(&set) && filled != set); + let mut filled = root.clone(); + filled.inode.filled_in.insert(Field::ExtendedAttributes); + assert!(filled.eq_ignore_filled_in(&root) && filled != root); + } } diff --git a/src/uapi16/refused.jsonl b/src/uapi16/refused.jsonl index 4786eae..2e595d2 100644 --- a/src/uapi16/refused.jsonl +++ b/src/uapi16/refused.jsonl @@ -316,6 +316,9 @@ [["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"encodedSize\":4}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents are 5 bytes, not 4"] [["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"originalSize\":4}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents are 5 bytes, not 4"] [["@root","{\"name\":\"x\",\"size\":5,\"contents\":[{\"literal\":\"H4sIAAAAAAAAA8tIzcnJBwCGphA2BQAAAA==\",\"encoding\":\"gzip\",\"encodedSize\":24}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents are 25 bytes, not 24"] +[["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"originalSha256\":\"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7\"}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents do not match 'originalSha256'"] +[["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"encodedSha256\":\"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7\"}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents do not match 'encodedSha256'"] +[["@root","{\"name\":\"x\",\"size\":5,\"contents\":[{\"literal\":\"H4sIAAAAAAAAA8tIzcnJBwCGphA2BQAAAA==\",\"encoding\":\"gzip\",\"encodedSha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\"}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents do not match 'encodedSha256'"] [["@root","{\"name\":\"x\",\"size\":3,\"contents\":[{\"file\":\"a\",\"offset\":-2}]}","@trailer"],"fieldType",1,"x","offset","manifest field 'offset' is not an unsigned integer"] [["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"offset\":6,\"originalSize\":5}]}","@trailer"],"contents",1,"x","offset","manifest object 1: contents offset 6 is beyond the data size 5"] [["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"offset\":6}]}","@trailer"],"contents",1,"x","offset","manifest object 1: contents offset 6 is beyond the data size 5"] @@ -323,6 +326,10 @@ [["@root","{\"name\":\"x\",\"size\":18446744073709551615,\"contents\":[{\"file\":\"a\",\"offset\":2,\"originalSize\":18446744073709551615}]}","@trailer"],"contradiction",1,"x","offset","manifest object 1 (x): offset 2 plus size 18446744073709551615 exceeds the contents size 18446744073709551615"] [["@root","{\"name\":\"x\",\"size\":5,\"contents\":[{\"originalSize\":4}]}","@trailer"],"contradiction",1,"x","offset","manifest object 1 (x): offset 0 plus size 5 exceeds the contents size 4"] [["@root","{\"name\":\"x\",\"size\":5,\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\",\"contents\":[{\"file\":\"a\",\"originalSize\":5,\"originalSha256\":\"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7\"}]}","@trailer"],"contradiction",1,"x","sha256","manifest object 1 (x): object and contents hashes differ"] +[["@root","{\"name\":\"x\",\"size\":5,\"sha256\":\"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7\",\"contents\":[{\"literal\":\"aGVsbG8=\"}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1 (x): the data in literal contents does not match 'sha256'"] +[["@root","{\"name\":\"x\",\"size\":2,\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\",\"contents\":[{\"literal\":\"aGVsbG8=\"}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1 (x): the data in literal contents does not match 'sha256'"] +[["@root","{\"name\":\"x\",\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"offset\":1,\"originalSha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\"}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1 (x): the data in literal contents does not match 'sha256'"] +[["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\"},{\"file\":\"a\",\"originalSize\":5,\"originalSha256\":\"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7\"}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1 (x): the data in literal contents does not match 'sha256'"] [["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\"},{\"file\":\"/b\"}]}","@trailer"],"contents",1,"x","file","manifest object 1: contents file reference: name has an empty component: '/b'"] [["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"/a\"},{\"file\":\"b\",\"encoding\":\"identity\"}]}","@trailer"],"contents",1,"x","file","manifest object 1: contents file reference: name has an empty component: '/a'"] [["@root","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":[]}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: 'extendedAttributes' is not an object"] diff --git a/src/uapi16/tests/fixtures.rs b/src/uapi16/tests/fixtures.rs index a3183b4..2a9912a 100644 --- a/src/uapi16/tests/fixtures.rs +++ b/src/uapi16/tests/fixtures.rs @@ -1,12 +1,13 @@ // SPDX-License-Identifier: LGPL-2.1-or-later //! Manifests written by systemd's own tool, read and written back. They //! are copies of the fixtures of ufat, whose tests/fixtures/README.md says -//! how they were made. +//! how they were made. Only the file `empty` of the special case +//! differs: it has the hash of no data next to its size 0, as +//! systemd-manifest wrote it. -use std::collections::BTreeMap; use std::path::{Path, PathBuf}; -use uapi16::{Error, Field, FileObject, InodeType, Object, Order, Reader, RootObject, SignatureObject, Writer}; +use uapi16::{Error, FileObject, InodeType, Object, Order, Reader, RootObject, Sha256, SignatureObject, Writer}; /// A manifest read to its end: its root file object, its file objects and /// its signature objects. @@ -43,17 +44,17 @@ impl Manifest { Manifest::read(&bytes).unwrap_or_else(|e| panic!("{}: {}", path.display(), e)) } - /// The manifest with the extended attributes a reader filled in taken - /// as ones the objects state. systemd-manifest states the empty ones, - /// which the writer leaves out and a reader fills in again. - fn with_stated_xattrs(mut self) -> Manifest { - let files = self.files.iter_mut().map(FileObject::inode_mut); - for inode in std::iter::once(self.root.inode_mut()).chain(files) { - if inode.filled_in().contains(Field::ExtendedAttributes) { - inode.set_user_xattrs(Some(BTreeMap::new())); - } - } - self + /// Whether `other` has the same objects with the same values, whatever + /// a reader filled in of them. + fn eq_ignore_filled_in(&self, other: &Manifest) -> bool { + self.root.eq_ignore_filled_in(&other.root) + && self.files.len() == other.files.len() + && self + .files + .iter() + .zip(&other.files) + .all(|(file, other)| file.eq_ignore_filled_in(other)) + && self.signatures == other.signatures } /// The manifest the writer writes for the objects. @@ -162,6 +163,9 @@ fn every_fixture_parses() { assert_eq!(readonly.inode().mode().map(u32::from), Some(0o444)); assert!(readonly.inode().is_read_only()); assert!(special.names().contains(&"sub/\u{fc}mlaut \u{221e}.txt")); + let empty = special.files.iter().find(|e| e.name() == "empty").unwrap(); + assert_eq!((empty.size(), empty.sha256()), (Some(0), Some(Sha256::EMPTY))); + assert!(empty.filled_in().is_empty()); let empty = Manifest::load("empty", "Uapi16Manifest"); assert!(empty.files.is_empty()); @@ -169,11 +173,9 @@ fn every_fixture_parses() { } /// The reader reads every manifest systemd-manifest wrote, and what the -/// writer writes for one reads back as the same manifest. That holds since -/// ufat's make-fixtures.sh took the hash of no data out of the empty file -/// of the special case: the writer leaves out a hash given next to the -/// size 0, and the reader marks the one it fills in as filled in, so the -/// objects would differ in that mark. +/// writer writes for one reads back with the same values. systemd-manifest +/// writes empty extended attributes and the hash of no data next to the +/// size 0. The writer leaves both out, and a reader fills them in again. #[test] fn reads_and_writes_back_every_fixture() { for (case, name, files, signatures) in [ @@ -194,11 +196,13 @@ fn reads_and_writes_back_every_fixture() { ); assert_eq!(read.root.order(), Some(Order::CodePoint), "{}", path.display()); let written = read.write().unwrap_or_else(|e| panic!("{}: {}", path.display(), e)); - assert_eq!( - Manifest::read(&written).unwrap().with_stated_xattrs(), - read.with_stated_xattrs(), - "{}", - path.display() + let back = Manifest::read(&written).unwrap(); + assert!( + back.eq_ignore_filled_in(&read), + "{}:\n{:#?}\n{:#?}", + path.display(), + back, + read ); } } diff --git a/src/uapi16/tests/fixtures/special/Uapi16Manifest b/src/uapi16/tests/fixtures/special/Uapi16Manifest index 18d9767..4c4bef5 100644 --- a/src/uapi16/tests/fixtures/special/Uapi16Manifest +++ b/src/uapi16/tests/fixtures/special/Uapi16Manifest @@ -1,7 +1,7 @@ {"extendedAttributes":{"user":{}},"features":["device","gid","group-name","hardlink","mode","mtime","sha256","size","symlink","uid","user-name","user-xattr"],"gid":1000,"groupName":"brauner","mTimeNSec":1699999100000000000,"mediaType":"application/vnd.uapi.16.manifest","mode":509,"order":"codepoint","uid":1000,"userName":"brauner"} {"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000100000000000,"mode":436,"name":"Mixed Case.TXT","sha256":"480c2336b410f1ad5f8bf1b28944490255804b65350c527787e74ebdd511e3a4","size":7,"uid":1000,"userName":"brauner"} {"extendedAttributes":{"user":{"comment":{"text":"set by make-fixtures"}}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000100000000000,"mode":436,"name":"a.txt","sha256":"b640e840b19d378660b32fb51ae18d67dccb4a8596a29e7bd72c1b2ae5928f41","size":6,"uid":1000,"userName":"brauner"} -{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000102000000000,"mode":436,"name":"empty","size":0,"uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000102000000000,"mode":436,"name":"empty","sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","size":0,"uid":1000,"userName":"brauner"} {"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1699999100000000000,"mode":509,"name":"empty dir","type":"dir","uid":1000,"userName":"brauner"} {"contents":[{"literal":"YS50eHQ="}],"gid":1000,"groupName":"brauner","mTimeNSec":1700000102000000000,"name":"link","size":5,"type":"lnk","uid":1000,"userName":"brauner"} {"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1699999100000000000,"mode":509,"name":"sub","type":"dir","uid":1000,"userName":"brauner"} diff --git a/src/uapi16/writer.rs b/src/uapi16/writer.rs index 61840fe..bda6bf7 100644 --- a/src/uapi16/writer.rs +++ b/src/uapi16/writer.rs @@ -469,9 +469,13 @@ impl FileObject { if self.contents.len() > MAX_CONTENTS { return Err(Error::too_many_contents(subject)); } + // What each contents object says of its data. The check of the + // object below takes it from here, so that no literal is hashed + // twice. + let mut contents_data = Vec::with_capacity(self.contents.len()); for contents in &self.contents { contents.check(subject)?; - contents.check_consistency(subject)?; + contents_data.push(contents.check_consistency(subject)?); } let inode = &self.inode; inode.check_xattr_names(subject)?; @@ -496,7 +500,7 @@ impl FileObject { self.check_permitted_fields(subject)?; // The contents objects were checked above. This is for what // follows from them. - self.check_consistency(subject, |contents| contents.check_consistency(subject))?; + self.check_consistency(subject, contents_data.iter().copied())?; Ok(()) } @@ -735,6 +739,16 @@ impl ContentsObject { } } + /// Checks every value of the contents object, one of those of the file + /// object `subject` names, as a reader does: its strings, see + /// [`ContentsObject::check_strings`], and the value of every field, see + /// [`ContentsObject::check`]. [`ContentsObject::check_consistency`] + /// checks the fields against each other. + pub(crate) fn check_values(&self, subject: Subject<'_>) -> Result<(), Error> { + self.check_strings(subject)?; + self.check(subject) + } + /// The header fields in the order of their names, which is the order /// they are written in. fn sorted_headers(&self) -> Vec<&(String, String)> { @@ -829,7 +843,7 @@ mod tests { use crate::object::{ContentsSource, DosFlags, FatSerial, InodeFlags, Mode, Uuid}; use crate::testing::{ directory, everything, json, name, read_whole, record, recording_all, sequence, write_whole, written, Whole, - EMPTY, HELLO, ROOT, SIGNATURE, TRAILER, + EMPTY, HELLO, ROOT, SIGNATURE, TRAILER, WORLD, }; use crate::{Sha256, Writer}; use std::collections::BTreeMap; @@ -1613,6 +1627,22 @@ mod tests { }, Problem::InvalidContents, ), + // A literal against its hash, before the value of a field + // behind it. + ( + format!( + r#"{{"contents":[{{"literal":"aGVsbG8=","originalSha256":"{}"}}],"name":"x","uid":65535}}"#, + WORLD + ), + |o| { + o.contents = vec![ContentsObject { + original_sha256: WORLD.parse().ok(), + ..ContentsObject::new(ContentsSource::Literal(b"hello".to_vec())) + }]; + o.inode.uid = Some(65535); + }, + Problem::Contradiction, + ), // A value, before a missing name. ( r#"{"uid":65535}"#.into(), @@ -1912,7 +1942,11 @@ mod tests { fn file() -> ContentsObject { ContentsObject::new(ContentsSource::File(name("x"))) } - let cases: [(Give, Problem, Option); 17] = [ + /// The literal "hello". + fn hello() -> ContentsObject { + ContentsObject::new(ContentsSource::Literal(b"hello".to_vec())) + } + let cases: [(Give, Problem, Option); 22] = [ // Fields the inode type does not permit. ( |o| (o.inode_type, o.size) = (InodeType::Fifo, Some(1)), @@ -2018,6 +2052,50 @@ mod tests { Problem::Contradiction, Some(Field::Offset), ), + // A literal against the hashes of its contents object, without + // and with an encoding, and against the hash of the object, all + // of the data and a part of it. + ( + |o| { + o.contents = vec![ContentsObject { + original_sha256: WORLD.parse().ok(), + ..hello() + }]; + }, + Problem::Contradiction, + Some(Field::Literal), + ), + ( + |o| { + o.contents = vec![ContentsObject { + encoded_sha256: WORLD.parse().ok(), + ..hello() + }]; + }, + Problem::Contradiction, + Some(Field::Literal), + ), + ( + |o| { + o.contents = vec![ContentsObject { + encoding: Some("gzip".into()), + encoded_sha256: WORLD.parse().ok(), + ..hello() + }]; + }, + Problem::Contradiction, + Some(Field::Literal), + ), + ( + |o| (o.sha256, o.contents) = (WORLD.parse().ok(), vec![hello()]), + Problem::Contradiction, + Some(Field::Literal), + ), + ( + |o| (o.size, o.sha256, o.contents) = (Some(2), HELLO.parse().ok(), vec![hello()]), + Problem::Contradiction, + Some(Field::Literal), + ), ]; let (root, _) = recording_all(); for (give, problem, field) in cases { @@ -2037,6 +2115,68 @@ mod tests { } } + /// A literal is the data as it is stored, so the writer refuses what a + /// reader refuses of it: a literal that does not match a hash of its + /// contents object or the hash of the object. The literal "hello" with + /// the hash of "world" was written and read back once, and only a copy + /// of its data failed. + #[test] + fn checks_literals_against_their_hashes() { + let world = Sha256::digest(b"world"); + let hello = || vec![ContentsObject::new(ContentsSource::Literal(b"hello".to_vec()))]; + let mut contents_first = FileObject::new(name("x")); + contents_first.set_contents(hello()); + contents_first.set_sha256(Some(world)); + let mut hash_first = FileObject::new(name("x")); + hash_first.set_sha256(Some(world)); + hash_first.set_contents(hello()); + let facts = |e: Error| (e.kind(), e.field(), e.record_number(), e.to_string()); + let expected = ( + ErrorKind::Manifest(Problem::Contradiction), + Some(Field::Literal), + Some(1), + "manifest object 1 (x): the data in literal contents does not match 'sha256'".to_string(), + ); + for object in [&contents_first, &hash_first] { + let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); + assert_eq!(facts(writer.file(object).unwrap_err()), expected, "{:?}", object); + } + let record = format!( + r#"{{"contents":[{{"literal":"aGVsbG8="}}],"name":"x","sha256":"{}"}}"#, + WORLD + ); + assert_eq!( + facts(read_whole(&sequence(&[ROOT, &record, TRAILER])).unwrap_err()), + expected + ); + // What agrees is read and written back: a literal with the hash of + // its contents object, a part of one with the hash of the object, + // one with the hash another contents object gives, and an encoded + // one, whose hash of the decoded data is not checked. + for record in [ + format!( + r#"{{"contents":[{{"literal":"aGVsbG8=","originalSha256":"{}"}}],"name":"x"}}"#, + HELLO + ), + format!( + r#"{{"contents":[{{"literal":"aGVsbG8=","offset":1}}],"name":"x","sha256":"{}"}}"#, + Sha256::digest(b"ello") + ), + format!( + r#"{{"contents":[{{"literal":"aGVsbG8="}},{{"file":"a","originalSha256":"{}","originalSize":5}}],"name":"x"}}"#, + HELLO + ), + format!( + r#"{{"contents":[{{"encoding":"gzip","literal":"Z3o=","originalSha256":"{}"}}],"name":"x"}}"#, + WORLD + ), + ] { + let bytes = sequence(&[ROOT, &record, TRAILER]); + let m = read_whole(&bytes).unwrap_or_else(|e| panic!("{}: {}", record, e)); + assert_eq!(write_whole(&m).unwrap(), bytes, "{}", record); + } + } + /// An encoder appends what a writer writes, and nothing where it fails. #[test] fn encodes_what_a_writer_writes() {