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    /// The complete bounded stream does not match the admitted digest.
156    DigestMismatch {
157        /// Caller-selected authority.
158        expected: Sha256Digest,
159        /// Observed size and digest.
160        actual: ArtifactIdentity,
161    },
162    /// Storage could not be allocated for a bounded file read.
163    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
196/// Preserve native I/O identity or retain the typed artifact cause at an I/O boundary.
197impl 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
206/// Hash one stream with constant working memory and no reliance on metadata.
207///
208/// Reads at most `max_bytes + 1` bytes, using the extra byte to detect overflow.
209/// Retries interrupted reads only; no subprocess or network retry is performed.
210/// A blocking reader's timeouts remain the caller's responsibility.
211///
212/// # Errors
213/// Returns [`ArtifactError::LimitExceeded`] or the underlying read error.
214/// An impossible reader byte count returns IO [`io::ErrorKind::InvalidData`].
215pub 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
230/// Verify a complete bounded stream before the caller extracts or uses its bytes.
231///
232/// # Errors
233/// Returns read/limit failures or a typed mismatch with the observed identity.
234pub 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
242/// Read one stream into bounded, fallibly allocated storage.
243///
244/// Observes at most `max_bytes + 1` bytes to detect overflow. A blocking reader's
245/// deadline remains caller-owned. Only interrupted reads are retried.
246///
247/// # Errors
248/// Returns read, allocation, or byte-limit failures. An impossible reader byte
249/// count returns IO [`io::ErrorKind::InvalidData`].
250pub 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
260// Callers admit the additional elements against `limit` before reserving.
261// Grow geometrically without requesting capacity beyond that element budget.
262fn 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}