Files
leleka/control-plane/src/embedded_spec.rs
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

198 lines
6.6 KiB
Rust

//! Bounded build-time payload copying, shared with ordinary unit tests.
use std::io::{self, Read, Write};
use sha2::{Digest, Sha256};
pub const MAX_BYTES: u64 = 1024 * 1024 * 1024;
const BUFFER_BYTES: usize = 64 * 1024;
fn invalid(message: &'static str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message)
}
fn hex_digest(bytes: &[u8]) -> String {
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}
/// On error the destination may be partial and must not be published as a payload.
pub fn copy_verified(
source: impl Read,
destination: impl Write,
arch: &str,
digest: &str,
revision: &str,
) -> io::Result<u64> {
copy_with_limit(source, destination, arch, digest, revision, MAX_BYTES)
}
fn copy_with_limit(
mut source: impl Read,
mut destination: impl Write,
arch: &str,
digest: &str,
revision: &str,
limit: u64,
) -> io::Result<u64> {
if digest.len() != 64 || !digest.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(invalid(
"embedded engine SHA256 must be 64 hexadecimal characters",
));
}
if revision.len() != 40 || !revision.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(invalid(
"embedded engine source revision must be a full 40-character Git SHA",
));
}
let machine = match arch {
"x86_64" => 62,
"aarch64" => 183,
_ => {
return Err(invalid(
"embedded engines support Linux x86_64 or aarch64 only",
));
}
};
let mut header = [0; 64];
source.read_exact(&mut header)?;
if &header[..7] != b"\x7fELF\x02\x01\x01"
|| !matches!(u16::from_le_bytes([header[16], header[17]]), 2 | 3)
|| u16::from_le_bytes([header[18], header[19]]) != machine
{
return Err(invalid(
"embedded engine must be an ELF64 little-endian executable for the target architecture",
));
}
let mut total = header.len() as u64;
if total > limit {
return Err(invalid("embedded engine exceeds size limit"));
}
let mut hash = Sha256::new();
hash.update(header);
destination.write_all(&header)?;
let mut buffer = [0; BUFFER_BYTES];
loop {
// At the limit, read only one extra byte to distinguish EOF from overflow.
let available = (limit - total + 1).min(BUFFER_BYTES as u64) as usize;
let count = match source.read(&mut buffer[..available]) {
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
result => result?,
};
if count == 0 {
break;
}
total += count as u64;
if total > limit {
return Err(invalid("embedded engine exceeds size limit"));
}
hash.update(&buffer[..count]);
destination.write_all(&buffer[..count])?;
}
if hex_digest(&hash.finalize()) != digest.to_ascii_lowercase() {
return Err(invalid("embedded engine SHA256 mismatch"));
}
destination.flush()?;
Ok(total)
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture(size: usize) -> Vec<u8> {
let mut elf = vec![0x5a; size];
elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
elf[16..18].copy_from_slice(&3u16.to_le_bytes());
elf[18..20].copy_from_slice(&62u16.to_le_bytes());
elf
}
#[test]
fn payload_digest_architecture_and_provenance_are_required() {
let mut elf = fixture(64);
let digest = hex_digest(&Sha256::digest(&elf));
let rev = "a".repeat(40);
assert!(copy_verified(&elf[..], io::sink(), "x86_64", &digest, &rev).is_ok());
assert!(copy_verified(&elf[..], io::sink(), "aarch64", &digest, &rev).is_err());
assert!(copy_verified(&elf[..], io::sink(), "x86_64", &"0".repeat(64), &rev).is_err());
assert!(copy_verified(&elf[..], io::sink(), "x86_64", &digest, "untracked").is_err());
elf[4] = 1;
assert!(copy_verified(&elf[..], io::sink(), "x86_64", &digest, &rev).is_err());
assert!(copy_verified(&b"#!/bin/sh"[..], io::sink(), "x86_64", &digest, &rev).is_err());
}
#[test]
fn copy_is_exact_bounded_and_rejects_overflow_without_copying_extra_bytes() {
let elf = fixture(BUFFER_BYTES * 2 + 19);
let digest = hex_digest(&Sha256::digest(&elf));
let rev = "a".repeat(40);
let mut output = Vec::new();
let mut input = io::Cursor::new(&elf);
assert_eq!(
copy_with_limit(
&mut input,
&mut output,
"x86_64",
&digest,
&rev,
elf.len() as u64
)
.unwrap(),
elf.len() as u64
);
assert_eq!(output, elf);
output.clear();
input.set_position(0);
let cap = BUFFER_BYTES as u64;
assert!(copy_with_limit(&mut input, &mut output, "x86_64", &digest, &rev, cap).is_err());
assert_eq!(input.position(), cap + 1);
assert!(output.len() as u64 <= cap);
}
#[test]
fn io_errors_and_truncated_sources_do_not_pass_verification() {
struct BrokenWriter;
impl Write for BrokenWriter {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
Err(io::Error::other("fixture write failed"))
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
let elf = fixture(BUFFER_BYTES + 31);
let digest = hex_digest(&Sha256::digest(&elf));
let rev = "a".repeat(40);
assert!(copy_verified(&elf[..], BrokenWriter, "x86_64", &digest, &rev).is_err());
assert!(copy_verified(&elf[..elf.len() - 1], io::sink(), "x86_64", &digest, &rev).is_err());
let mut interrupted = true;
let mut input = io::Cursor::new(&elf);
let source = io::Read::by_ref(&mut input);
struct InterruptedOnce<'a> {
inner: &'a mut dyn Read,
first: &'a mut bool,
}
impl Read for InterruptedOnce<'_> {
fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
assert!(out.len() <= BUFFER_BYTES);
if std::mem::take(self.first) {
return Err(io::ErrorKind::Interrupted.into());
}
self.inner.read(out)
}
}
assert!(
copy_verified(
InterruptedOnce {
inner: source,
first: &mut interrupted
},
io::sink(),
"x86_64",
&digest,
&rev
)
.is_ok()
);
}
}