ic_host_artifacts/artifact/
mod.rs1use sha2::{Digest, Sha256};
9use std::{
10 fmt,
11 io::{self, Read},
12 str::FromStr,
13};
14
15mod chunks;
16mod copy;
17#[cfg(feature = "gzip")]
18mod gzip;
19mod hashing;
20mod matching;
21#[cfg(test)]
22mod test_support;
23#[cfg(test)]
24mod tests;
25mod writer;
26
27pub use chunks::{ChunkDigestError, chunk_digests};
28pub use copy::{CopyError, copy_reader};
29#[cfg(feature = "gzip")]
30pub use gzip::{GzipError, decode_gzip, encode_gzip, gzip_matches, hash_gzip, hash_gzip_or_raw};
31pub use hashing::HashingWriter;
32pub use matching::MatchingWriter;
33pub use writer::{BoundedWriter, WriterError};
34
35#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
37pub struct Sha256Digest([u8; 32]);
38
39impl Sha256Digest {
40 #[must_use]
42 pub const fn from_bytes(bytes: [u8; 32]) -> Self {
43 Self(bytes)
44 }
45
46 #[must_use]
48 pub const fn as_bytes(&self) -> &[u8; 32] {
49 &self.0
50 }
51
52 #[must_use]
54 pub fn compute(bytes: &[u8]) -> Self {
55 Self(Sha256::digest(bytes).into())
56 }
57}
58
59impl fmt::Display for Sha256Digest {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 for byte in self.0 {
62 write!(f, "{byte:02x}")?;
63 }
64 Ok(())
65 }
66}
67
68#[derive(Clone, Copy, Debug, Eq, PartialEq)]
70pub enum DigestParseError {
71 Length {
73 actual: usize,
75 },
76 Digit {
78 offset: usize,
80 },
81}
82
83impl fmt::Display for DigestParseError {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 match self {
86 Self::Length { actual } => {
87 write!(f, "SHA-256 requires 64 hex bytes, received {actual}")
88 }
89 Self::Digit { offset } => write!(f, "invalid lowercase SHA-256 digit at byte {offset}"),
90 }
91 }
92}
93impl std::error::Error for DigestParseError {}
94
95impl FromStr for Sha256Digest {
96 type Err = DigestParseError;
97
98 fn from_str(text: &str) -> Result<Self, Self::Err> {
99 if text.len() != 64 {
100 return Err(DigestParseError::Length { actual: text.len() });
101 }
102 let mut bytes = [0; 32];
103 for (offset, digit) in text.bytes().enumerate() {
104 let nibble = match digit {
105 b'0'..=b'9' => digit - b'0',
106 b'a'..=b'f' => digit - b'a' + 10,
107 _ => return Err(DigestParseError::Digit { offset }),
108 };
109 bytes[offset / 2] |= nibble << if offset % 2 == 0 { 4 } else { 0 };
110 }
111 Ok(Self(bytes))
112 }
113}
114
115#[derive(Clone, Copy, Debug, Eq, PartialEq)]
117pub struct ArtifactIdentity {
118 pub bytes: u64,
120 pub sha256: Sha256Digest,
122}
123
124impl ArtifactIdentity {
125 pub fn verify(self, expected: Sha256Digest) -> Result<Self, ArtifactError> {
133 if self.sha256 != expected {
134 return Err(ArtifactError::DigestMismatch {
135 expected,
136 actual: self,
137 });
138 }
139 Ok(self)
140 }
141}
142
143#[derive(Debug)]
145pub enum ArtifactError {
146 Io(io::Error),
148 NotRegularFile,
150 LimitExceeded {
152 limit: u64,
154 },
155 DigestMismatch {
157 expected: Sha256Digest,
159 actual: ArtifactIdentity,
161 },
162 Allocation(std::collections::TryReserveError),
164}
165
166impl fmt::Display for ArtifactError {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 match self {
169 Self::Io(source) => write!(f, "artifact read failed: {source}"),
170 Self::NotRegularFile => f.write_str("artifact path is not a regular file"),
171 Self::LimitExceeded { limit } => write!(f, "artifact exceeds {limit} bytes"),
172 Self::DigestMismatch { expected, actual } => write!(
173 f,
174 "artifact SHA-256 is {}, expected {expected}",
175 actual.sha256
176 ),
177 Self::Allocation(source) => write!(f, "artifact allocation failed: {source}"),
178 }
179 }
180}
181impl std::error::Error for ArtifactError {
182 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
183 match self {
184 Self::Io(source) => Some(source),
185 Self::Allocation(source) => Some(source),
186 _ => None,
187 }
188 }
189}
190impl From<io::Error> for ArtifactError {
191 fn from(source: io::Error) -> Self {
192 Self::Io(source)
193 }
194}
195
196impl From<ArtifactError> for io::Error {
198 fn from(error: ArtifactError) -> Self {
199 match error {
200 ArtifactError::Io(source) => source,
201 other => Self::other(other),
202 }
203 }
204}
205
206pub fn hash_reader(
216 mut reader: impl Read,
217 max_bytes: u64,
218) -> Result<ArtifactIdentity, ArtifactError> {
219 let mut hasher = Sha256::new();
220 let bytes = visit_reader::<ArtifactError>(&mut reader, max_bytes, |chunk| {
221 hasher.update(chunk);
222 Ok(())
223 })?;
224 Ok(ArtifactIdentity {
225 bytes,
226 sha256: Sha256Digest(hasher.finalize().into()),
227 })
228}
229
230pub fn verify_reader(
235 reader: impl Read,
236 max_bytes: u64,
237 expected: Sha256Digest,
238) -> Result<ArtifactIdentity, ArtifactError> {
239 hash_reader(reader, max_bytes)?.verify(expected)
240}
241
242pub fn read_reader(mut reader: impl Read, max_bytes: usize) -> Result<Vec<u8>, ArtifactError> {
251 let mut bytes = Vec::new();
252 visit_reader::<ArtifactError>(&mut reader, max_bytes as u64, |chunk| {
253 reserve_bounded(&mut bytes, chunk.len(), max_bytes).map_err(ArtifactError::Allocation)?;
254 bytes.extend_from_slice(chunk);
255 Ok(())
256 })?;
257 Ok(bytes)
258}
259
260fn reserve_bounded<T>(
263 items: &mut Vec<T>,
264 additional: usize,
265 limit: usize,
266) -> Result<(), std::collections::TryReserveError> {
267 let required = items.len() + additional;
268 if required > items.capacity() {
269 let capacity = items.capacity().saturating_mul(2).max(required).min(limit);
270 items.try_reserve_exact(capacity - items.len())?;
271 }
272 Ok(())
273}
274
275fn visit_reader<E: From<ArtifactError>>(
276 reader: &mut impl Read,
277 limit: u64,
278 mut visit: impl FnMut(&[u8]) -> Result<(), E>,
279) -> Result<u64, E> {
280 let mut bytes = 0_u64;
281 let mut buffer = [0_u8; 16 * 1024];
282 loop {
283 let remaining = usize::try_from(limit - bytes).unwrap_or(usize::MAX);
284 let allowance = remaining.saturating_add(1).min(buffer.len());
285 let count = match reader.read(&mut buffer[..allowance]) {
286 Ok(count) => count,
287 Err(source) if source.kind() == io::ErrorKind::Interrupted => continue,
288 Err(source) => return Err(ArtifactError::Io(source).into()),
289 };
290 if count > allowance {
291 return Err(ArtifactError::Io(io::Error::new(
292 io::ErrorKind::InvalidData,
293 "reader returned more bytes than its buffer can hold",
294 ))
295 .into());
296 }
297 if count == 0 {
298 return Ok(bytes);
299 }
300 if count as u64 > limit - bytes {
301 return Err(ArtifactError::LimitExceeded { limit }.into());
302 }
303 visit(&buffer[..count])?;
304 bytes += count as u64;
305 }
306}