Skip to main content

ic_host_artifacts/artifact/
mod.rs

1//! Bounded streams and raw SHA-256 identities for artifact bytes.
2//!
3//! Consumers own trusted paths, admitted digests, and byte limits. An identity
4//! describes the bytes read; it does not freeze a path for later execution or
5//! certify an executable's version. Copying writes only to a caller-owned sink;
6//! paths, confinement, synchronization, publication and cleanup remain local.
7
8use 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/// Raw SHA-256 identity, without a product-specific prefix or wire format.
36#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
37pub struct Sha256Digest([u8; 32]);
38
39impl Sha256Digest {
40    /// Construct an identity from exact digest bytes.
41    #[must_use]
42    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
43        Self(bytes)
44    }
45
46    /// Borrow the digest bytes.
47    #[must_use]
48    pub const fn as_bytes(&self) -> &[u8; 32] {
49        &self.0
50    }
51
52    /// Hash bytes already held by the caller.
53    #[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/// Invalid lowercase hexadecimal digest authority.
69#[derive(Clone, Copy, Debug, Eq, PartialEq)]
70pub enum DigestParseError {
71    /// The digest does not contain exactly 64 ASCII bytes.
72    Length {
73        /// Observed byte length.
74        actual: usize,
75    },
76    /// A byte is not a lowercase hexadecimal digit.
77    Digit {
78        /// Offset of the invalid byte.
79        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/// Exact size and digest of one bounded byte stream.
116#[derive(Clone, Copy, Debug, Eq, PartialEq)]
117pub struct ArtifactIdentity {
118    /// Number of bytes successfully read.
119    pub bytes: u64,
120    /// SHA-256 of those bytes.
121    pub sha256: Sha256Digest,
122}
123
124impl ArtifactIdentity {
125    /// Compare this observed digest with caller-selected authority.
126    ///
127    /// Does not read, hash, freeze or validate the origin of the identity.
128    /// Size admission and selection of the expected digest remain caller-owned.
129    ///
130    /// # Errors
131    /// Returns a typed mismatch retaining the expected digest and this identity.
132    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/// A bounded read or digest verification failed.
144#[derive(Debug)]
145pub enum ArtifactError {
146    /// The reader or filesystem failed. No partial identity is returned.
147    Io(io::Error),
148    /// The selected path is not a regular file.
149    NotRegularFile,
150    /// A stream exceeded the caller's byte allowance.
151    LimitExceeded {
152        /// Maximum permitted bytes.
153        limit: u64,
154    },
155    /// A bounded stream ended before the caller's exact byte count.
156    LengthMismatch {
157        /// Required bytes.
158        expected: u64,
159        /// Successfully read bytes.
160        actual: u64,
161    },
162    /// The complete bounded stream does not match the admitted digest.
163    DigestMismatch {
164        /// Caller-selected authority.
165        expected: Sha256Digest,
166        /// Observed size and digest.
167        actual: ArtifactIdentity,
168    },
169    /// Storage could not be allocated for a bounded file read.
170    Allocation(std::collections::TryReserveError),
171}
172
173impl fmt::Display for ArtifactError {
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        match self {
176            Self::Io(source) => write!(f, "artifact read failed: {source}"),
177            Self::NotRegularFile => f.write_str("artifact path is not a regular file"),
178            Self::LimitExceeded { limit } => write!(f, "artifact exceeds {limit} bytes"),
179            Self::LengthMismatch { expected, actual } => {
180                write!(f, "artifact has {actual} bytes, expected {expected}")
181            }
182            Self::DigestMismatch { expected, actual } => write!(
183                f,
184                "artifact SHA-256 is {}, expected {expected}",
185                actual.sha256
186            ),
187            Self::Allocation(source) => write!(f, "artifact allocation failed: {source}"),
188        }
189    }
190}
191impl std::error::Error for ArtifactError {
192    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
193        match self {
194            Self::Io(source) => Some(source),
195            Self::Allocation(source) => Some(source),
196            _ => None,
197        }
198    }
199}
200impl From<io::Error> for ArtifactError {
201    fn from(source: io::Error) -> Self {
202        Self::Io(source)
203    }
204}
205
206/// Preserve native I/O identity or retain the typed artifact cause at an I/O boundary.
207impl From<ArtifactError> for io::Error {
208    fn from(error: ArtifactError) -> Self {
209        match error {
210            ArtifactError::Io(source) => source,
211            other => Self::other(other),
212        }
213    }
214}
215
216/// Hash one stream with constant working memory and no reliance on metadata.
217///
218/// Reads at most `max_bytes + 1` bytes, using the extra byte to detect overflow.
219/// Retries interrupted reads only; no subprocess or network retry is performed.
220/// A blocking reader's timeouts remain the caller's responsibility.
221/// Admit the returned identity against a selected digest with [`ArtifactIdentity::verify`].
222///
223/// # Errors
224/// Returns [`ArtifactError::LimitExceeded`] or the underlying read error.
225/// An impossible reader byte count returns IO [`io::ErrorKind::InvalidData`].
226pub fn hash_reader(
227    mut reader: impl Read,
228    max_bytes: u64,
229) -> Result<ArtifactIdentity, ArtifactError> {
230    let mut hasher = Sha256::new();
231    let bytes = visit_reader::<ArtifactError>(&mut reader, max_bytes, |chunk| {
232        hasher.update(chunk);
233        Ok(())
234    })?;
235    Ok(ArtifactIdentity {
236        bytes,
237        sha256: Sha256Digest(hasher.finalize().into()),
238    })
239}
240
241/// Hash a stream whose complete length must equal `expected_bytes`.
242///
243/// Reads at most one byte beyond the selected length to distinguish overflow.
244/// The caller owns the reader's origin, deadline and byte-budget selection.
245///
246/// # Errors
247/// Returns a typed short-length or limit error, or the underlying read error.
248pub fn hash_exact_reader(
249    reader: impl Read,
250    expected_bytes: u64,
251) -> Result<ArtifactIdentity, ArtifactError> {
252    let identity = hash_reader(reader, expected_bytes)?;
253    if identity.bytes != expected_bytes {
254        return Err(ArtifactError::LengthMismatch {
255            expected: expected_bytes,
256            actual: identity.bytes,
257        });
258    }
259    Ok(identity)
260}
261
262/// Read one stream into bounded, fallibly allocated storage.
263///
264/// Observes at most `max_bytes + 1` bytes to detect overflow. A blocking reader's
265/// deadline remains caller-owned. Only interrupted reads are retried.
266///
267/// # Errors
268/// Returns read, allocation, or byte-limit failures. An impossible reader byte
269/// count returns IO [`io::ErrorKind::InvalidData`].
270pub fn read_reader(mut reader: impl Read, max_bytes: usize) -> Result<Vec<u8>, ArtifactError> {
271    let mut bytes = Vec::new();
272    visit_reader::<ArtifactError>(&mut reader, max_bytes as u64, |chunk| {
273        reserve_bounded(&mut bytes, chunk.len(), max_bytes).map_err(ArtifactError::Allocation)?;
274        bytes.extend_from_slice(chunk);
275        Ok(())
276    })?;
277    Ok(bytes)
278}
279
280/// Read a complete stream into bounded storage at an exact selected length.
281///
282/// The caller owns the reader's origin, deadline and byte-budget selection.
283/// Reads at most one byte beyond the selected length to distinguish overflow.
284///
285/// # Errors
286/// Returns a typed short-length or limit error, allocation failure, or read error.
287pub fn read_exact_reader(
288    reader: impl Read,
289    expected_bytes: usize,
290) -> Result<Vec<u8>, ArtifactError> {
291    let bytes = read_reader(reader, expected_bytes)?;
292    if bytes.len() != expected_bytes {
293        return Err(ArtifactError::LengthMismatch {
294            expected: expected_bytes as u64,
295            actual: bytes.len() as u64,
296        });
297    }
298    Ok(bytes)
299}
300
301// Callers admit the additional elements against `limit` before reserving.
302// Grow geometrically without requesting capacity beyond that element budget.
303fn reserve_bounded<T>(
304    items: &mut Vec<T>,
305    additional: usize,
306    limit: usize,
307) -> Result<(), std::collections::TryReserveError> {
308    let required = items.len() + additional;
309    if required > items.capacity() {
310        let capacity = items.capacity().saturating_mul(2).max(required).min(limit);
311        items.try_reserve_exact(capacity - items.len())?;
312    }
313    Ok(())
314}
315
316fn visit_reader<E: From<ArtifactError>>(
317    reader: &mut impl Read,
318    limit: u64,
319    mut visit: impl FnMut(&[u8]) -> Result<(), E>,
320) -> Result<u64, E> {
321    let mut bytes = 0_u64;
322    let mut buffer = [0_u8; 16 * 1024];
323    loop {
324        let remaining = usize::try_from(limit - bytes).unwrap_or(usize::MAX);
325        let allowance = remaining.saturating_add(1).min(buffer.len());
326        let count = match reader.read(&mut buffer[..allowance]) {
327            Ok(count) => count,
328            Err(source) if source.kind() == io::ErrorKind::Interrupted => continue,
329            Err(source) => return Err(ArtifactError::Io(source).into()),
330        };
331        if count > allowance {
332            return Err(ArtifactError::Io(io::Error::new(
333                io::ErrorKind::InvalidData,
334                "reader returned more bytes than its buffer can hold",
335            ))
336            .into());
337        }
338        if count == 0 {
339            return Ok(bytes);
340        }
341        if count as u64 > limit - bytes {
342            return Err(ArtifactError::LimitExceeded { limit }.into());
343        }
344        visit(&buffer[..count])?;
345        bytes += count as u64;
346    }
347}