This commit was merged in pull request #340.
This commit is contained in:
1 parent
fbf3a7cf29
commit
0e0dfadf56
13 files changed
+686
-237
No files matched your search
Generated
+45
-12
@@ -677,6 +677,7 @@ dependencies = [
|
||||
"firmwerk-core",
|
||||
"firmwerk-repro",
|
||||
"firmwerk-sbom",
|
||||
"flate2",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"git2",
|
||||
@@ -694,6 +695,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"subtle",
|
||||
"tar",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-cron-scheduler",
|
||||
@@ -2126,7 +2128,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2151,6 +2153,16 @@ version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
|
||||
|
||||
[[package]]
|
||||
name = "filetime"
|
||||
version = "0.2.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.9"
|
||||
@@ -2865,7 +2877,7 @@ dependencies = [
|
||||
"libc",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2 0.5.10",
|
||||
"socket2 0.6.2",
|
||||
"system-configuration",
|
||||
"tokio",
|
||||
"tower-layer",
|
||||
@@ -3780,7 +3792,7 @@ version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4367,7 +4379,7 @@ dependencies = [
|
||||
"quinn-udp",
|
||||
"rustc-hash 2.1.1",
|
||||
"rustls",
|
||||
"socket2 0.5.10",
|
||||
"socket2 0.6.2",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -4404,9 +4416,9 @@ dependencies = [
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"socket2 0.5.10",
|
||||
"socket2 0.6.2",
|
||||
"tracing",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4767,7 +4779,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.4.15",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4780,7 +4792,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5309,7 +5321,7 @@ version = "0.8.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451"
|
||||
dependencies = [
|
||||
"heck 0.4.1",
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
@@ -5657,6 +5669,17 @@ version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
|
||||
|
||||
[[package]]
|
||||
name = "tar"
|
||||
version = "0.4.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
|
||||
dependencies = [
|
||||
"filetime",
|
||||
"libc",
|
||||
"xattr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.26.0"
|
||||
@@ -5664,10 +5687,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "82a72c767771b47409d2345987fda8628641887d5466101319899796367354a0"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.3.4",
|
||||
"getrandom 0.4.1",
|
||||
"once_cell",
|
||||
"rustix 1.1.4",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6807,7 +6830,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7321,6 +7344,16 @@ dependencies = [
|
||||
"tap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xattr"
|
||||
version = "1.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rustix 1.1.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xxhash-rust"
|
||||
version = "0.8.15"
|
||||
|
||||
@@ -34,6 +34,9 @@ uuid = { version = "1", features = ["v4", "v5", "serde"] }
|
||||
secrecy = { version = "0.10", features = ["serde"] }
|
||||
regex = "1"
|
||||
zip = { version = "2", features = ["aes-crypto", "deflate"] }
|
||||
# Uploaded tar and tar.gz source archives (ingest).
|
||||
tar = "0.4"
|
||||
flate2 = "1"
|
||||
dashmap = "6"
|
||||
tokio-stream = { version = "0.1", features = ["sync"] }
|
||||
aes-gcm = "0.10"
|
||||
|
||||
@@ -58,6 +58,8 @@ urlencoding = "2"
|
||||
futures-util = "0.3"
|
||||
jsonwebtoken = "9"
|
||||
zip = { workspace = true }
|
||||
tar = { workspace = true }
|
||||
flate2 = { workspace = true }
|
||||
tokio-tungstenite = { version = "0.26", features = ["rustls-tls-webpki-roots"] }
|
||||
futures-core = "0.3"
|
||||
dashmap = { workspace = true }
|
||||
|
||||
@@ -134,6 +134,17 @@ impl DemoTarget {
|
||||
}
|
||||
}
|
||||
|
||||
/// The archive format a fixture directory is uploaded as.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Pack {
|
||||
/// A `.zip`, what the dashboard's users send most.
|
||||
#[default]
|
||||
Zip,
|
||||
/// A `.tar.gz`, as exported from Linux build hosts and git forges.
|
||||
TarGz,
|
||||
}
|
||||
|
||||
/// One artifact of a curated target.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DemoArtifact {
|
||||
@@ -161,6 +172,9 @@ pub struct DemoArtifact {
|
||||
pub pin_tag: Option<String>,
|
||||
#[serde(default)]
|
||||
pub plc_format: Option<PlcFormat>,
|
||||
/// How a directory `upload` is packed before it is sent.
|
||||
#[serde(default)]
|
||||
pub pack: Pack,
|
||||
/// Skip silently when the env var is unset (needs infra not every
|
||||
/// environment has).
|
||||
#[serde(default)]
|
||||
@@ -571,6 +585,7 @@ mod tests {
|
||||
pin: None,
|
||||
pin_tag: None,
|
||||
plc_format: None,
|
||||
pack: Pack::Zip,
|
||||
optional: true,
|
||||
}],
|
||||
enabled_scans: Vec::new(),
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
//! Unpacking uploaded archives (zip, tar, tar.gz) into a working directory.
|
||||
//!
|
||||
//! The stored blob has no file name, so the format is read from its first
|
||||
//! bytes, not guessed from an extension. Every format is held to the same
|
||||
//! [`ExtractLimits`], and nothing an archive says about its own paths or sizes
|
||||
//! is trusted: entries that would leave the destination are skipped, and the
|
||||
//! byte budget counts what is actually written.
|
||||
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use flate2::read::GzDecoder;
|
||||
|
||||
use crate::error::AgentError;
|
||||
|
||||
/// A tar header is one 512-byte block; its magic sits at offset 257.
|
||||
const TAR_BLOCK: u64 = 512;
|
||||
const TAR_MAGIC_OFFSET: usize = 257;
|
||||
const TAR_MAGIC: &[u8] = b"ustar";
|
||||
|
||||
/// What one archive may expand to.
|
||||
///
|
||||
/// Extraction used to trust the archive completely: a few-kilobyte zip bomb
|
||||
/// expands to terabytes and fills the node's disk. The limits are enforced on
|
||||
/// bytes actually written, not on the sizes an entry declares about itself,
|
||||
/// since those are attacker-controlled.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ExtractLimits {
|
||||
/// Most entries (files and directories) one archive may contain.
|
||||
pub max_entries: usize,
|
||||
/// Most bytes the whole archive may expand to on disk.
|
||||
pub max_total_bytes: u64,
|
||||
}
|
||||
|
||||
impl Default for ExtractLimits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_entries: 100_000,
|
||||
max_total_bytes: 2 * 1024 * 1024 * 1024,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The archive formats ingest unpacks.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ArchiveFormat {
|
||||
/// A zip container (also APK/AAB/IPA and CODESYS `.projectarchive`).
|
||||
Zip,
|
||||
/// An uncompressed tar.
|
||||
Tar,
|
||||
/// A gzip-compressed tar (`.tar.gz`, `.tgz`).
|
||||
TarGz,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ArchiveFormat {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Zip => "zip",
|
||||
Self::Tar => "tar",
|
||||
Self::TarGz => "tar.gz",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ArchiveFormat {
|
||||
/// The format of the file at `path`, read from its leading bytes. `None`
|
||||
/// for a file that is not an archive (a single `.st` or `.c` upload), and
|
||||
/// for a gzip that does not hold a tar (a lone compressed file).
|
||||
///
|
||||
/// A gzip whose content cannot be decoded is still reported as
|
||||
/// [`ArchiveFormat::TarGz`]: it was meant to be an archive, and unpacking it
|
||||
/// must fail visibly rather than be scanned as one opaque file.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error when the file cannot be opened or read.
|
||||
pub fn sniff(path: &Path) -> io::Result<Option<Self>> {
|
||||
let head = leading_block(File::open(path)?)?;
|
||||
if head.starts_with(b"PK\x03\x04") || head.starts_with(b"PK\x05\x06") {
|
||||
return Ok(Some(Self::Zip));
|
||||
}
|
||||
if head.starts_with(&[0x1f, 0x8b]) {
|
||||
return Ok(match leading_block(GzDecoder::new(File::open(path)?)) {
|
||||
Ok(inner) if !is_tar_header(&inner) => None,
|
||||
_ => Some(Self::TarGz),
|
||||
});
|
||||
}
|
||||
Ok(is_tar_header(&head).then_some(Self::Tar))
|
||||
}
|
||||
}
|
||||
|
||||
/// The first tar block of `reader`, or less when it is shorter.
|
||||
fn leading_block(reader: impl Read) -> io::Result<Vec<u8>> {
|
||||
// `Read::take` is Python's `f.read(n)`: it stops after `n` bytes.
|
||||
let mut block = Vec::with_capacity(TAR_BLOCK as usize);
|
||||
reader.take(TAR_BLOCK).read_to_end(&mut block)?;
|
||||
Ok(block)
|
||||
}
|
||||
|
||||
/// Whether `block` is a POSIX (ustar) or GNU tar header.
|
||||
fn is_tar_header(block: &[u8]) -> bool {
|
||||
block.get(TAR_MAGIC_OFFSET..TAR_MAGIC_OFFSET + TAR_MAGIC.len()) == Some(TAR_MAGIC)
|
||||
}
|
||||
|
||||
/// Unpack `archive` of the given `format` into `dest` (created if needed),
|
||||
/// refusing archives that exceed `limits`.
|
||||
///
|
||||
/// On any error the partly written `dest` is removed, so a caller never finds
|
||||
/// half an archive (or half a bomb) left behind in the working directory.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error when the archive is corrupt, an entry cannot be written, or
|
||||
/// the archive exceeds `limits`.
|
||||
pub fn extract(
|
||||
format: ArchiveFormat,
|
||||
archive: &Path,
|
||||
dest: &Path,
|
||||
limits: ExtractLimits,
|
||||
) -> Result<(), AgentError> {
|
||||
let result = File::open(archive)
|
||||
.map_err(AgentError::from)
|
||||
.and_then(|file| match format {
|
||||
ArchiveFormat::Zip => extract_zip(file, dest, limits),
|
||||
ArchiveFormat::Tar => extract_tar(file, dest, limits),
|
||||
ArchiveFormat::TarGz => extract_tar(GzDecoder::new(file), dest, limits),
|
||||
});
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_dir_all(dest);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn extract_zip(file: File, dest: &Path, limits: ExtractLimits) -> Result<(), AgentError> {
|
||||
let mut zip =
|
||||
zip::ZipArchive::new(file).map_err(|e| AgentError::Other(format!("open zip: {e}")))?;
|
||||
if zip.len() > limits.max_entries {
|
||||
return Err(too_many_entries(limits));
|
||||
}
|
||||
fs::create_dir_all(dest)?;
|
||||
let mut budget = Budget::new(limits);
|
||||
for i in 0..zip.len() {
|
||||
let mut entry = zip
|
||||
.by_index(i)
|
||||
.map_err(|e| AgentError::Other(format!("read zip entry: {e}")))?;
|
||||
// `enclosed_name` returns `None` for traversal-unsafe paths — skip them.
|
||||
let Some(rel) = entry.enclosed_name() else {
|
||||
continue;
|
||||
};
|
||||
let out = dest.join(rel);
|
||||
if entry.is_dir() {
|
||||
fs::create_dir_all(&out)?;
|
||||
} else {
|
||||
budget.write(&mut entry, &out)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn extract_tar(reader: impl Read, dest: &Path, limits: ExtractLimits) -> Result<(), AgentError> {
|
||||
let mut archive = tar::Archive::new(reader);
|
||||
fs::create_dir_all(dest)?;
|
||||
let mut budget = Budget::new(limits);
|
||||
let entries = archive
|
||||
.entries()
|
||||
.map_err(|e| AgentError::Other(format!("read tar: {e}")))?;
|
||||
for (index, entry) in entries.enumerate() {
|
||||
if index >= limits.max_entries {
|
||||
return Err(too_many_entries(limits));
|
||||
}
|
||||
let mut entry = entry.map_err(|e| AgentError::Other(format!("read tar entry: {e}")))?;
|
||||
let path = entry
|
||||
.path()
|
||||
.map_err(|e| AgentError::Other(format!("read tar entry name: {e}")))?;
|
||||
let Some(rel) = enclosed(&path) else {
|
||||
continue;
|
||||
};
|
||||
let out = dest.join(rel);
|
||||
match entry.header().entry_type() {
|
||||
tar::EntryType::Directory => fs::create_dir_all(&out)?,
|
||||
tar::EntryType::Regular | tar::EntryType::Continuous => {
|
||||
budget.write(&mut entry, &out)?;
|
||||
}
|
||||
// Symbolic and hard links, devices and FIFOs are never created: a
|
||||
// link could point anywhere on the agent's disk, and a later entry
|
||||
// written "through" it would land outside `dest`.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `path` as a relative path that stays inside the destination, or `None` when
|
||||
/// it is absolute, climbs with `..`, or names nothing.
|
||||
fn enclosed(path: &Path) -> Option<PathBuf> {
|
||||
let mut rel = PathBuf::new();
|
||||
for component in path.components() {
|
||||
match component {
|
||||
Component::Normal(part) => rel.push(part),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
|
||||
}
|
||||
}
|
||||
(!rel.as_os_str().is_empty()).then_some(rel)
|
||||
}
|
||||
|
||||
fn too_many_entries(limits: ExtractLimits) -> AgentError {
|
||||
AgentError::Other(format!(
|
||||
"archive has more than the {} entries allowed",
|
||||
limits.max_entries
|
||||
))
|
||||
}
|
||||
|
||||
/// The bytes one extraction may still write.
|
||||
struct Budget {
|
||||
remaining: u64,
|
||||
limit: u64,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
fn new(limits: ExtractLimits) -> Self {
|
||||
Self {
|
||||
remaining: limits.max_total_bytes,
|
||||
limit: limits.max_total_bytes,
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy `entry` to `out`, charging what was written against the budget.
|
||||
fn write(&mut self, entry: &mut impl Read, out: &Path) -> Result<(), AgentError> {
|
||||
if let Some(parent) = out.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
// Read at most one byte past what is left of the budget: getting that
|
||||
// byte proves the archive is over the limit, whatever its headers say.
|
||||
let mut outfile = File::create(out)?;
|
||||
let written = io::copy(&mut entry.take(self.remaining + 1), &mut outfile)?;
|
||||
if written > self.remaining {
|
||||
return Err(AgentError::Other(format!(
|
||||
"archive expands beyond {} bytes",
|
||||
self.limit
|
||||
)));
|
||||
}
|
||||
self.remaining -= written;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
/// A unique scratch directory, removed on drop.
|
||||
struct Scratch(PathBuf);
|
||||
impl Scratch {
|
||||
fn new() -> Self {
|
||||
let p = std::env::temp_dir().join(format!("cs-archive-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir_all(&p).expect("mkdir scratch");
|
||||
Self(p)
|
||||
}
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn roomy() -> ExtractLimits {
|
||||
ExtractLimits::default()
|
||||
}
|
||||
|
||||
/// A tar of `(path, body)` regular files.
|
||||
fn tar_bytes(files: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut builder = tar::Builder::new(Vec::new());
|
||||
for (path, body) in files {
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_size(body.len() as u64);
|
||||
header.set_mode(0o644);
|
||||
header.set_cksum();
|
||||
builder
|
||||
.append_data(&mut header, path, *body)
|
||||
.expect("append");
|
||||
}
|
||||
builder.into_inner().expect("finish tar")
|
||||
}
|
||||
|
||||
fn gzip(bytes: &[u8]) -> Vec<u8> {
|
||||
let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
enc.write_all(bytes).expect("gzip");
|
||||
enc.finish().expect("finish gzip")
|
||||
}
|
||||
|
||||
fn zip_bytes(files: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut w = zip::ZipWriter::new(io::Cursor::new(Vec::new()));
|
||||
let opts: zip::write::SimpleFileOptions = Default::default();
|
||||
for (path, body) in files {
|
||||
w.start_file(*path, opts).expect("start");
|
||||
w.write_all(body).expect("write");
|
||||
}
|
||||
w.finish().expect("finish").into_inner()
|
||||
}
|
||||
|
||||
fn file_with(dir: &Path, name: &str, bytes: &[u8]) -> PathBuf {
|
||||
let p = dir.join(name);
|
||||
fs::write(&p, bytes).expect("write");
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_are_read_from_the_content() {
|
||||
let s = Scratch::new();
|
||||
let tar = tar_bytes(&[("a.c", b"int x;")]);
|
||||
let cases = [
|
||||
(zip_bytes(&[("a.c", b"int x;")]), Some(ArchiveFormat::Zip)),
|
||||
(tar.clone(), Some(ArchiveFormat::Tar)),
|
||||
(gzip(&tar), Some(ArchiveFormat::TarGz)),
|
||||
// A lone gzipped file is not an archive to unpack.
|
||||
(gzip(b"just a log line"), None),
|
||||
(b"PROGRAM main END_PROGRAM".to_vec(), None),
|
||||
(Vec::new(), None),
|
||||
];
|
||||
for (i, (bytes, want)) in cases.into_iter().enumerate() {
|
||||
let path = file_with(s.path(), &format!("blob{i}"), &bytes);
|
||||
assert_eq!(
|
||||
ArchiveFormat::sniff(&path).expect("sniff"),
|
||||
want,
|
||||
"case {i}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tar_gz_unpacks_like_a_zip() {
|
||||
let s = Scratch::new();
|
||||
let files: &[(&str, &[u8])] = &[("proj/Core/Src/main.c", b"int main(void);")];
|
||||
for (name, bytes, format) in [
|
||||
("z", zip_bytes(files), ArchiveFormat::Zip),
|
||||
("t", tar_bytes(files), ArchiveFormat::Tar),
|
||||
("g", gzip(&tar_bytes(files)), ArchiveFormat::TarGz),
|
||||
] {
|
||||
let archive = file_with(s.path(), name, &bytes);
|
||||
let dest = s.path().join(format!("out-{name}"));
|
||||
extract(format, &archive, &dest, roomy()).expect("extract");
|
||||
assert_eq!(
|
||||
fs::read_to_string(dest.join("proj/Core/Src/main.c")).expect("read"),
|
||||
"int main(void);",
|
||||
"{format}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tar_entries_cannot_leave_the_destination() {
|
||||
let s = Scratch::new();
|
||||
// `append_data` refuses `..`, so write the hostile names by hand.
|
||||
let mut builder = tar::Builder::new(Vec::new());
|
||||
for name in ["../escape.txt", "/abs.txt", "ok.txt"] {
|
||||
let mut header = tar::Header::new_old();
|
||||
header.as_old_mut().name[..name.len()].copy_from_slice(name.as_bytes());
|
||||
header.set_size(2);
|
||||
header.set_mode(0o644);
|
||||
header.set_cksum();
|
||||
builder.append(&header, &b"hi"[..]).expect("append");
|
||||
}
|
||||
let mut link = tar::Header::new_gnu();
|
||||
link.set_entry_type(tar::EntryType::Symlink);
|
||||
link.set_size(0);
|
||||
link.set_cksum();
|
||||
builder
|
||||
.append_link(&mut link, "etc", "/etc")
|
||||
.expect("append link");
|
||||
let archive = file_with(s.path(), "evil.tar", &builder.into_inner().expect("tar"));
|
||||
|
||||
let dest = s.path().join("out");
|
||||
extract(ArchiveFormat::Tar, &archive, &dest, roomy()).expect("extract");
|
||||
assert!(dest.join("ok.txt").is_file());
|
||||
assert!(!s.path().join("escape.txt").exists());
|
||||
assert!(!dest.join("abs.txt").exists());
|
||||
assert!(fs::symlink_metadata(dest.join("etc")).is_err(), "no links");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tar_bomb_is_refused_and_cleaned_up() {
|
||||
let s = Scratch::new();
|
||||
let zeros = vec![0u8; 1024 * 1024];
|
||||
let files: Vec<(String, &[u8])> = (0..3)
|
||||
.map(|i| (format!("f{i}.bin"), zeros.as_slice()))
|
||||
.collect();
|
||||
let refs: Vec<(&str, &[u8])> = files.iter().map(|(n, b)| (n.as_str(), *b)).collect();
|
||||
let archive = file_with(s.path(), "bomb", &gzip(&tar_bytes(&refs)));
|
||||
let dest = s.path().join("out");
|
||||
let limits = ExtractLimits {
|
||||
max_entries: 100,
|
||||
max_total_bytes: 2 * 1024 * 1024,
|
||||
};
|
||||
let err = extract(ArchiveFormat::TarGz, &archive, &dest, limits).expect_err("refuse");
|
||||
assert!(err.to_string().contains("expands beyond"), "{err}");
|
||||
assert!(!dest.exists(), "partial output must be removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_entries_are_refused_in_every_format() {
|
||||
let s = Scratch::new();
|
||||
let files: &[(&str, &[u8])] = &[("a", b"1"), ("b", b"2"), ("c", b"3")];
|
||||
let limits = ExtractLimits {
|
||||
max_entries: 2,
|
||||
max_total_bytes: u64::MAX / 2,
|
||||
};
|
||||
for (name, bytes, format) in [
|
||||
("z", zip_bytes(files), ArchiveFormat::Zip),
|
||||
("g", gzip(&tar_bytes(files)), ArchiveFormat::TarGz),
|
||||
] {
|
||||
let archive = file_with(s.path(), name, &bytes);
|
||||
let dest = s.path().join(format!("out-{name}"));
|
||||
let err = extract(format, &archive, &dest, limits).expect_err("refuse");
|
||||
assert!(err.to_string().contains("entries"), "{format}: {err}");
|
||||
assert!(!dest.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_corrupt_tar_gz_fails_instead_of_passing_as_a_file() {
|
||||
let s = Scratch::new();
|
||||
let mut bytes = gzip(&tar_bytes(&[("a.c", b"int x;")]));
|
||||
bytes.truncate(bytes.len() / 2);
|
||||
let archive = file_with(s.path(), "cut", &bytes);
|
||||
assert_eq!(
|
||||
ArchiveFormat::sniff(&archive).expect("sniff"),
|
||||
Some(ArchiveFormat::TarGz)
|
||||
);
|
||||
let dest = s.path().join("out");
|
||||
assert!(extract(ArchiveFormat::TarGz, &archive, &dest, roomy()).is_err());
|
||||
assert!(!dest.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_archive_exactly_at_the_limits_extracts_whole() {
|
||||
let s = Scratch::new();
|
||||
let body = vec![0u8; 1024];
|
||||
let files: &[(&str, &[u8])] = &[("a", &body), ("b", &body), ("c", &body)];
|
||||
let limits = ExtractLimits {
|
||||
max_entries: 3,
|
||||
max_total_bytes: 3 * 1024,
|
||||
};
|
||||
let archive = file_with(s.path(), "t", &tar_bytes(files));
|
||||
let dest = s.path().join("out");
|
||||
extract(ArchiveFormat::Tar, &archive, &dest, limits).expect("at the limit is fine");
|
||||
assert_eq!(fs::read(dest.join("c")).expect("read").len(), 1024);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
//! Content-addressed blob storage and archive extraction for ingest.
|
||||
//! Content-addressed blob storage and working directories for ingest.
|
||||
//!
|
||||
//! Blobs are stored at `<base>/blobs/<sha[0:2]>/<sha>` and deduplicated by
|
||||
//! digest; per-run working directories live under `<base>/work/`.
|
||||
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Read};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
@@ -86,103 +86,6 @@ pub fn store_file(base: &Path, src: &Path, sha: &str) -> Result<PathBuf, AgentEr
|
||||
Ok(dest)
|
||||
}
|
||||
|
||||
/// What one archive may expand to.
|
||||
///
|
||||
/// Extraction used to trust the archive completely: a few-kilobyte zip bomb
|
||||
/// expands to terabytes and fills the node's disk. The limits are enforced on
|
||||
/// bytes actually written, not on the sizes an entry declares about itself,
|
||||
/// since those are attacker-controlled.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ExtractLimits {
|
||||
/// Most entries (files and directories) one archive may contain.
|
||||
pub max_entries: usize,
|
||||
/// Most bytes the whole archive may expand to on disk.
|
||||
pub max_total_bytes: u64,
|
||||
}
|
||||
|
||||
impl Default for ExtractLimits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_entries: 100_000,
|
||||
max_total_bytes: 2 * 1024 * 1024 * 1024,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract a zip into `dest` under the default [`ExtractLimits`].
|
||||
pub fn extract_zip(archive: &Path, dest: &Path) -> Result<(), AgentError> {
|
||||
extract_zip_with(archive, dest, ExtractLimits::default())
|
||||
}
|
||||
|
||||
/// Extract a zip into `dest` (created if needed), refusing archives that
|
||||
/// exceed `limits`. `enclosed_name` sanitizes each entry path, so this is safe
|
||||
/// against zip-slip traversal.
|
||||
///
|
||||
/// On any error the partly written `dest` is removed: callers fall back to
|
||||
/// treating the file as a single blob, and must not find half an archive
|
||||
/// (or half a bomb) left behind in the working directory.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error when the file is not a zip, an entry cannot be read or
|
||||
/// written, or the archive exceeds `limits`.
|
||||
pub fn extract_zip_with(
|
||||
archive: &Path,
|
||||
dest: &Path,
|
||||
limits: ExtractLimits,
|
||||
) -> Result<(), AgentError> {
|
||||
let result = extract_bounded(archive, dest, limits);
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_dir_all(dest);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn extract_bounded(archive: &Path, dest: &Path, limits: ExtractLimits) -> Result<(), AgentError> {
|
||||
let file = File::open(archive)?;
|
||||
let mut zip =
|
||||
zip::ZipArchive::new(file).map_err(|e| AgentError::Other(format!("open zip: {e}")))?;
|
||||
if zip.len() > limits.max_entries {
|
||||
return Err(AgentError::Other(format!(
|
||||
"archive has {} entries, more than the {} allowed",
|
||||
zip.len(),
|
||||
limits.max_entries
|
||||
)));
|
||||
}
|
||||
fs::create_dir_all(dest)?;
|
||||
let mut written_total: u64 = 0;
|
||||
for i in 0..zip.len() {
|
||||
let mut entry = zip
|
||||
.by_index(i)
|
||||
.map_err(|e| AgentError::Other(format!("read zip entry: {e}")))?;
|
||||
// `enclosed_name` returns `None` for traversal-unsafe paths — skip them.
|
||||
let Some(rel) = entry.enclosed_name() else {
|
||||
continue;
|
||||
};
|
||||
let out = dest.join(rel);
|
||||
if entry.is_dir() {
|
||||
fs::create_dir_all(&out)?;
|
||||
continue;
|
||||
}
|
||||
if let Some(parent) = out.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
// Read at most one byte past what is left of the budget: getting that
|
||||
// byte proves the archive is over the limit, whatever its headers say.
|
||||
let budget = limits.max_total_bytes - written_total;
|
||||
let mut outfile = File::create(&out)?;
|
||||
let written = io::copy(&mut (&mut entry).take(budget + 1), &mut outfile)?;
|
||||
if written > budget {
|
||||
return Err(AgentError::Other(format!(
|
||||
"archive expands beyond {} bytes",
|
||||
limits.max_total_bytes
|
||||
)));
|
||||
}
|
||||
written_total += written;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The working directory for one artifact of a target: `<base>/work/<target>/<artifact>`.
|
||||
pub fn work_dir(base: &Path, target_id: &str, artifact_id: &str) -> PathBuf {
|
||||
base.join("work").join(target_id).join(artifact_id)
|
||||
@@ -276,82 +179,4 @@ mod tests {
|
||||
assert!(root.exists(), "store must stay under <base>/tenants");
|
||||
assert!(read_tenant_blob(base.path(), "../../escape", &sha).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_zip_writes_entries() {
|
||||
let base = Scratch::new();
|
||||
let archive = base.path().join("a.zip");
|
||||
{
|
||||
let file = File::create(&archive).expect("create");
|
||||
let mut w = zip::ZipWriter::new(file);
|
||||
let opts: zip::write::SimpleFileOptions = Default::default();
|
||||
w.start_file("dir/hello.txt", opts).expect("start");
|
||||
io::Write::write_all(&mut w, b"hi").expect("write");
|
||||
w.finish().expect("finish");
|
||||
}
|
||||
let dest = base.path().join("out");
|
||||
extract_zip(&archive, &dest).expect("extract");
|
||||
assert_eq!(
|
||||
fs::read_to_string(dest.join("dir/hello.txt")).expect("read"),
|
||||
"hi"
|
||||
);
|
||||
}
|
||||
|
||||
/// Build a zip in `dir` with `files` entries of `size` zero bytes each —
|
||||
/// zeros compress to almost nothing, which is what makes a bomb.
|
||||
fn zip_of_zeros(dir: &Path, files: usize, size: usize) -> PathBuf {
|
||||
let archive = dir.join("bomb.zip");
|
||||
let file = File::create(&archive).expect("create");
|
||||
let mut w = zip::ZipWriter::new(file);
|
||||
let opts: zip::write::SimpleFileOptions = Default::default();
|
||||
let zeros = vec![0u8; size];
|
||||
for i in 0..files {
|
||||
w.start_file(format!("f{i}.bin"), opts).expect("start");
|
||||
io::Write::write_all(&mut w, &zeros).expect("write");
|
||||
}
|
||||
w.finish().expect("finish");
|
||||
archive
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_archive_that_expands_past_the_budget_is_refused_and_cleaned_up() {
|
||||
let base = Scratch::new();
|
||||
// 3 x 1 MiB of zeros: a tiny file on disk, 3 MiB expanded.
|
||||
let archive = zip_of_zeros(base.path(), 3, 1024 * 1024);
|
||||
let dest = base.path().join("out");
|
||||
let limits = ExtractLimits {
|
||||
max_entries: 100,
|
||||
max_total_bytes: 2 * 1024 * 1024,
|
||||
};
|
||||
let err = extract_zip_with(&archive, &dest, limits).expect_err("must refuse");
|
||||
assert!(err.to_string().contains("expands beyond"), "{err}");
|
||||
assert!(!dest.exists(), "partial output must be removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_archive_with_too_many_entries_is_refused() {
|
||||
let base = Scratch::new();
|
||||
let archive = zip_of_zeros(base.path(), 5, 1);
|
||||
let dest = base.path().join("out");
|
||||
let limits = ExtractLimits {
|
||||
max_entries: 4,
|
||||
max_total_bytes: u64::MAX / 2,
|
||||
};
|
||||
let err = extract_zip_with(&archive, &dest, limits).expect_err("must refuse");
|
||||
assert!(err.to_string().contains("entries"), "{err}");
|
||||
assert!(!dest.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_archive_within_the_limits_extracts_whole() {
|
||||
let base = Scratch::new();
|
||||
let archive = zip_of_zeros(base.path(), 3, 1024);
|
||||
let dest = base.path().join("out");
|
||||
let limits = ExtractLimits {
|
||||
max_entries: 3,
|
||||
max_total_bytes: 3 * 1024,
|
||||
};
|
||||
extract_zip_with(&archive, &dest, limits).expect("exactly at the limit is fine");
|
||||
assert_eq!(fs::read(dest.join("f2.bin")).expect("read").len(), 1024);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
//! is also the reconciliation key against sibling products (a firmware sha256
|
||||
//! matches Firmwerk's `Artifact.sha256`).
|
||||
|
||||
pub(crate) mod archive;
|
||||
pub(crate) mod blob;
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -165,8 +166,14 @@ fn ingest_git(
|
||||
}
|
||||
|
||||
/// Store a blob artifact content-addressed. When `extract` is set and the blob
|
||||
/// is a zip container (source archive, APK/AAB/IPA), also unpack it into a
|
||||
/// working directory; otherwise the working path is the stored blob.
|
||||
/// is an archive (zip, tar, tar.gz; source archives and APK/AAB/IPA), also
|
||||
/// unpack it into a working directory; otherwise the working path is the
|
||||
/// stored blob.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// An uploaded source archive that cannot be unpacked is an error: the scan
|
||||
/// must fail visibly rather than complete over a tree that was never there.
|
||||
fn ingest_blob(
|
||||
artifact: &Artifact,
|
||||
ctx: &IngestContext<'_>,
|
||||
@@ -180,31 +187,29 @@ fn ingest_blob(
|
||||
let mut facts = Vec::new();
|
||||
let working_path = if extract {
|
||||
let dest = blob::work_dir(base, ctx.target_id, &artifact.id);
|
||||
match blob::extract_zip(&stored, &dest) {
|
||||
Ok(()) => project_root(dest),
|
||||
Err(e) => {
|
||||
// Not a zip container — this is a single uploaded file (e.g. a
|
||||
// `.st`/`.xml` PLC project or a `.tar.gz`). The content-addressed
|
||||
// blob has no extension, so materialize it into a working dir
|
||||
// under its original name; extension-based scanners (PLC) can then
|
||||
// discover it and report a readable path.
|
||||
facts.push(DetectedFact::new(
|
||||
"archive_unextracted",
|
||||
e.to_string(),
|
||||
"ingest",
|
||||
));
|
||||
match materialize_single(&stored, &dest, &blob_file_name(artifact)) {
|
||||
Ok(dir) => dir,
|
||||
Err(copy_err) => {
|
||||
facts.push(DetectedFact::new(
|
||||
"materialize_failed",
|
||||
copy_err.to_string(),
|
||||
"ingest",
|
||||
));
|
||||
stored.clone()
|
||||
match archive::ArchiveFormat::sniff(&stored)? {
|
||||
Some(format) => {
|
||||
match archive::extract(format, &stored, &dest, archive::ExtractLimits::default()) {
|
||||
Ok(()) => project_root(dest),
|
||||
Err(e) => {
|
||||
let reason =
|
||||
format!("the uploaded {format} archive could not be unpacked: {e}");
|
||||
if artifact.kind == ArtifactKind::SourceArchive {
|
||||
return Err(AgentError::Other(reason));
|
||||
}
|
||||
// A PLC project or mobile package: kept as one file
|
||||
// for the stage that reads it, which reports on it.
|
||||
as_single_file(artifact, &stored, &dest, reason, &mut facts)
|
||||
}
|
||||
}
|
||||
}
|
||||
None => as_single_file(
|
||||
artifact,
|
||||
&stored,
|
||||
&dest,
|
||||
"not an archive".into(),
|
||||
&mut facts,
|
||||
),
|
||||
}
|
||||
} else {
|
||||
stored.clone()
|
||||
@@ -242,6 +247,32 @@ fn project_root(mut dir: PathBuf) -> PathBuf {
|
||||
}
|
||||
}
|
||||
|
||||
/// The working path for a blob that is used as one file rather than unpacked
|
||||
/// (a `.st`/`.xml` PLC project, a single source file), recording `reason`.
|
||||
/// The content-addressed blob has no extension, so it is materialized into
|
||||
/// `dest` under its original name: extension-based scanners (PLC) can then
|
||||
/// discover it and report a readable path.
|
||||
fn as_single_file(
|
||||
artifact: &Artifact,
|
||||
stored: &Path,
|
||||
dest: &Path,
|
||||
reason: String,
|
||||
facts: &mut Vec<DetectedFact>,
|
||||
) -> PathBuf {
|
||||
facts.push(DetectedFact::new("archive_unextracted", reason, "ingest"));
|
||||
match materialize_single(stored, dest, &blob_file_name(artifact)) {
|
||||
Ok(dir) => dir,
|
||||
Err(copy_err) => {
|
||||
facts.push(DetectedFact::new(
|
||||
"materialize_failed",
|
||||
copy_err.to_string(),
|
||||
"ingest",
|
||||
));
|
||||
stored.to_path_buf()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy a stored blob into `dest`/`name`, returning `dest`. Used when an
|
||||
/// "extractable" artifact turns out to be a single file rather than an archive.
|
||||
fn materialize_single(stored: &Path, dest: &Path, name: &str) -> Result<PathBuf, AgentError> {
|
||||
|
||||
@@ -667,14 +667,14 @@ impl PipelineOrchestrator {
|
||||
self.dast_after_code_scan(&target_id, &plan, scan_run_id)
|
||||
.await;
|
||||
}
|
||||
// The ingest stage recorded why. A run over nothing must not
|
||||
// read as a completed scan that found nothing.
|
||||
None => {
|
||||
self.skip_stage(
|
||||
scan_run_id,
|
||||
"code_scan",
|
||||
"the uploaded archive could not be unpacked, so there was \
|
||||
no source tree to scan",
|
||||
)
|
||||
.await;
|
||||
return Err(AgentError::Other(
|
||||
"the uploaded archive could not be unpacked, so there was no \
|
||||
source tree to scan"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1152,6 +1152,7 @@ impl PipelineOrchestrator {
|
||||
Ok(set) => set,
|
||||
Err(e) => {
|
||||
tracing::warn!(target_id, error = %e, "Unified pipeline: ingest for classification failed");
|
||||
self.skip_stage(scan_run_id, "ingest", &e.to_string()).await;
|
||||
return std::collections::HashMap::new();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -42,7 +42,7 @@ use std::time::{Duration, Instant};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use compliance_agent::fixtures::{DemoArtifact, DemoTarget, DemoTargets, Observed};
|
||||
use compliance_agent::fixtures::{DemoArtifact, DemoTarget, DemoTargets, Observed, Pack};
|
||||
|
||||
/// Page size the agent allows at most (`MAX_PAGE_SIZE`).
|
||||
const PAGE: usize = 200;
|
||||
@@ -85,15 +85,18 @@ impl Agent {
|
||||
}
|
||||
|
||||
/// Upload one file artifact the way the dashboard does (multipart). A
|
||||
/// directory is zipped first, so source-tree fixtures stay reviewable as
|
||||
/// plain files in the repository.
|
||||
/// directory is packed first (zip, or tar.gz when the fixture says so), so
|
||||
/// source-tree fixtures stay reviewable as plain files in the repository.
|
||||
async fn upload(&self, target_id: &str, a: &DemoArtifact, path: &Path) -> Result<(), String> {
|
||||
let name = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let (bytes, filename) = if path.is_dir() {
|
||||
(zip_dir(path)?, format!("{name}.zip"))
|
||||
match a.pack {
|
||||
Pack::Zip => (zip_dir(path)?, format!("{name}.zip")),
|
||||
Pack::TarGz => (tar_gz_dir(path)?, format!("{name}.tar.gz")),
|
||||
}
|
||||
} else {
|
||||
let bytes = tokio::fs::read(path)
|
||||
.await
|
||||
@@ -157,10 +160,9 @@ fn text(v: &Value, key: &str) -> String {
|
||||
v[key].as_str().unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
/// Zip a fixture directory in memory, entries in a stable order.
|
||||
fn zip_dir(dir: &Path) -> Result<Vec<u8>, String> {
|
||||
use std::io::Write;
|
||||
|
||||
/// The files under a fixture directory as `(relative path, contents)`, in a
|
||||
/// stable order.
|
||||
fn dir_files(dir: &Path) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
let mut files: Vec<PathBuf> = walkdir::WalkDir::new(dir)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
@@ -168,21 +170,48 @@ fn zip_dir(dir: &Path) -> Result<Vec<u8>, String> {
|
||||
.map(|e| e.into_path())
|
||||
.collect();
|
||||
files.sort();
|
||||
files
|
||||
.into_iter()
|
||||
.map(|file| {
|
||||
let rel = file
|
||||
.strip_prefix(dir)
|
||||
.map_err(|e| e.to_string())?
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
let body = std::fs::read(&file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
Ok((rel, body))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Zip a fixture directory in memory.
|
||||
fn zip_dir(dir: &Path) -> Result<Vec<u8>, String> {
|
||||
use std::io::Write;
|
||||
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let options: zip::write::SimpleFileOptions = Default::default();
|
||||
for file in files {
|
||||
let rel = file
|
||||
.strip_prefix(dir)
|
||||
.map_err(|e| e.to_string())?
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
for (rel, body) in dir_files(dir)? {
|
||||
zip.start_file(rel, options).map_err(|e| e.to_string())?;
|
||||
let body = std::fs::read(&file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
zip.write_all(&body).map_err(|e| e.to_string())?;
|
||||
}
|
||||
Ok(zip.finish().map_err(|e| e.to_string())?.into_inner())
|
||||
}
|
||||
|
||||
/// Pack a fixture directory as a tar.gz in memory, the way `tar czf` would.
|
||||
fn tar_gz_dir(dir: &Path) -> Result<Vec<u8>, String> {
|
||||
let gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
let mut tar = tar::Builder::new(gz);
|
||||
for (rel, body) in dir_files(dir)? {
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_size(body.len() as u64);
|
||||
header.set_mode(0o644);
|
||||
tar.append_data(&mut header, rel, body.as_slice())
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
let gz = tar.into_inner().map_err(|e| e.to_string())?;
|
||||
gz.finish().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The wire name of a snake_case enum (`plc_project`, `project_archive`).
|
||||
fn serde_name<T: Serialize>(value: &T) -> String {
|
||||
serde_json::to_value(value)
|
||||
|
||||
@@ -34,7 +34,7 @@ const TARGET_TYPES: &[(&str, &str, &str)] = &[
|
||||
/// (value, label) for the artifact kinds a user can attach.
|
||||
const ARTIFACT_KINDS: &[(&str, &str)] = &[
|
||||
("git_repo", "Git repository"),
|
||||
("source_archive", "Source archive (zip)"),
|
||||
("source_archive", "Source archive (zip, tar, tar.gz)"),
|
||||
("firmware_image", "Firmware image"),
|
||||
("mobile_package", "Mobile package (APK/IPA)"),
|
||||
("container_image", "Container image"),
|
||||
|
||||
@@ -4,7 +4,8 @@ A small service delivered the way a customer without a git remote delivers one:
|
||||
a zip of the sources. The harness uploads this directory as a `source_archive`
|
||||
artifact, and the baseline asserts it gets the same treatment as a repository —
|
||||
SAST findings, secret detection, a package SBOM from the lockfile, and CVE
|
||||
matching on it.
|
||||
matching on it. `archive-order-intake-tgz` uploads the same directory as a
|
||||
`.tar.gz` (#335), so its baseline must match this one.
|
||||
|
||||
Planted on purpose:
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"scan_status": "completed",
|
||||
"skipped_stages": [],
|
||||
"sbom": [
|
||||
"npm:lodash@4.17.15",
|
||||
"npm:minimist@1.2.0",
|
||||
"npm:order-intake@1.3.0"
|
||||
],
|
||||
"findings": [
|
||||
"gitleaks:github-pat service.env:5",
|
||||
"gitleaks:slack-bot-token service.env:6",
|
||||
"semgrep:cra-ai-7-weak-password-hash auth.py:9"
|
||||
],
|
||||
"cves": [
|
||||
"GHSA-29mw-wpgm-hmr9",
|
||||
"GHSA-35jh-r3h4-6jhm",
|
||||
"GHSA-f23m-r3pf-42rh",
|
||||
"GHSA-p6mc-m468-83gw",
|
||||
"GHSA-r5fr-rjxr-66jc",
|
||||
"GHSA-vh95-rmgr-6w4m",
|
||||
"GHSA-xvch-5gv4-984h",
|
||||
"GHSA-xxjr-mmjv-4gpg"
|
||||
],
|
||||
"registry_rules": [
|
||||
"generic.secrets.security.detected-github-token.detected-github-token",
|
||||
"javascript.express.security.audit.express-check-csurf-middleware-usage.express-check-csurf-middleware-usage",
|
||||
"javascript.express.security.audit.xss.direct-response-write.direct-response-write",
|
||||
"javascript.express.security.injection.raw-html-format.raw-html-format",
|
||||
"javascript.lang.security.detect-child-process.detect-child-process",
|
||||
"python.lang.security.audit.subprocess-shell-true.subprocess-shell-true"
|
||||
]
|
||||
}
|
||||
@@ -314,6 +314,28 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "archive-order-intake-tgz",
|
||||
"name": "Source archive as tar.gz (no git remote)",
|
||||
"target_type": "backend_service",
|
||||
"description": "The same source tree uploaded as a .tar.gz (#335): it must unpack and scan exactly like the zip.",
|
||||
"artifacts": [
|
||||
{
|
||||
"kind": "source_archive",
|
||||
"upload": "fixtures/nightly/archive",
|
||||
"pack": "tar_gz"
|
||||
}
|
||||
],
|
||||
"expect": {
|
||||
"min_sbom_components": 3,
|
||||
"sast_rule_ids": [
|
||||
"github-pat",
|
||||
"slack-bot-token",
|
||||
"python.lang.security.audit.subprocess-shell-true.subprocess-shell-true",
|
||||
"javascript.lang.security.detect-child-process.detect-child-process"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "js-npm-lock-v3",
|
||||
"name": "JavaScript/TypeScript · npm lockfile v3",
|
||||
|
||||
Reference in new issue
Block a user