use std::collections::BTreeSet;
use std::path::{Component, Path, PathBuf};
use anyhow::{Context, Result};
use serde::Serialize;
use super::entry_budget::{entry_report, report_or_warn, MAX_STAGE_ENTRY_BYTES};
use super::stored_gzip::{self, write_stored_gzip_siblings};
const MAX_DEPTH: usize = 8;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StageFilesSummary {
pub apps: Vec<String>,
pub gz_written: usize,
}
pub fn run(root: &Path) -> Result<StageFilesSummary> {
let shown_root = root;
let root = std::fs::canonicalize(root)
.with_context(|| format!("resolve stage root {}", shown_root.display()))?;
anyhow::ensure!(
root.is_dir(),
"stage root {} is not a directory",
shown_root.display()
);
let root = root.as_path();
let mut manifests = Vec::new();
find_manifests(root, 0, &mut manifests)
.with_context(|| format!("scan {} for manifests", root.display()))?;
manifests.sort();
let mut summary = StageFilesSummary::default();
for manifest_path in manifests {
let text = std::fs::read_to_string(&manifest_path)
.with_context(|| format!("read {}", manifest_path.display()))?;
let manifest: serde_json::Value = match serde_json::from_str(&text) {
Ok(value) => value,
Err(error) => {
eprintln!(
"warning: {} is not valid JSON, skipped: {error}",
manifest_path.display()
);
continue;
}
};
let Some(ui) = manifest.get("ui").filter(|ui| ui.is_object()) else {
continue;
};
let Some(integrity) = ui.get("integrity").and_then(|value| value.as_object()) else {
eprintln!(
"warning: {} has a ui block without a ui.integrity map, skipped",
manifest_path.display()
);
continue;
};
let app_dir = manifest_path.parent().unwrap_or(root);
let name = app_name(&manifest, app_dir);
let mut tally = Tally::default();
for relative in integrity.keys() {
stage_file(&name, app_dir, relative, &mut tally)?;
}
println!(
"stored gzip: {name}: {} written, {} kept, {} -> {} bytes",
tally.written, tally.kept, tally.raw, tally.stored
);
report_or_warn(app_dir, ui);
summary.gz_written += tally.written;
summary.apps.push(name);
}
if summary.apps.is_empty() {
println!(
"stage-files: no stage or widget manifests under {}",
root.display()
);
}
Ok(summary)
}
#[derive(Default)]
struct Tally {
written: usize,
kept: usize,
raw: u64,
stored: u64,
}
fn stage_file(name: &str, app_dir: &Path, relative: &str, tally: &mut Tally) -> Result<()> {
let rel_path = Path::new(relative);
let plain = rel_path
.components()
.all(|part| matches!(part, Component::Normal(_) | Component::CurDir));
let named = rel_path
.components()
.any(|part| matches!(part, Component::Normal(_)));
if !plain || !named {
eprintln!("warning: {name}: ui.integrity path {relative:?} is not a file inside the app dir, skipped");
return Ok(());
}
let mut cursor = app_dir.to_path_buf();
let mut linked_leaf = false;
for part in rel_path.components() {
let Component::Normal(part) = part else {
continue;
};
cursor.push(part);
let meta = std::fs::symlink_metadata(&cursor).with_context(|| {
format!(
"{name}: ui.integrity file {relative} ({}) is not readable",
cursor.display()
)
})?;
if meta.file_type().is_symlink() {
if cursor.components().count()
== app_dir.components().count() + rel_components(rel_path)
{
linked_leaf = true;
} else {
eprintln!("warning: {name}: ui.integrity path {relative} passes through a symlink, skipped");
return Ok(());
}
}
}
let file = cursor;
let sibling = gzip_sibling_path(&file);
let sibling_meta = std::fs::symlink_metadata(&sibling).ok();
if linked_leaf {
eprintln!("warning: {name}: ui.integrity path {relative} is a symlink, skipped");
if let Some(meta) = sibling_meta {
if meta.file_type().is_file() {
std::fs::remove_file(&sibling)
.with_context(|| format!("remove stale {}", sibling.display()))?;
} else {
eprintln!(
"warning: {name}: {} is not a regular file, left alone",
sibling.display()
);
}
}
return Ok(());
}
let meta = std::fs::symlink_metadata(&file)?;
if !meta.file_type().is_file() {
eprintln!("warning: {name}: ui.integrity path {relative} is not a regular file, skipped");
return Ok(());
}
if let Some(sibling_meta) = sibling_meta {
if !sibling_meta.file_type().is_file() {
eprintln!(
"warning: {name}: {} is not a regular file, left alone",
sibling.display()
);
return Ok(());
}
if sibling_is_current(&file, &sibling) {
tally.kept += 1;
return Ok(());
}
std::fs::remove_file(&sibling)
.with_context(|| format!("remove stale {}", sibling.display()))?;
}
let report = write_stored_gzip_siblings(&file)
.with_context(|| format!("write stored gzip for {}", file.display()))?;
tally.written += report.written;
tally.raw += report.raw_bytes;
tally.stored += report.stored_bytes;
Ok(())
}
fn rel_components(path: &Path) -> usize {
path.components()
.filter(|part| matches!(part, Component::Normal(_)))
.count()
}
fn sibling_is_current(file: &Path, sibling: &Path) -> bool {
use std::io::Read;
let (Ok(raw), Ok(gz)) = (std::fs::read(file), std::fs::read(sibling)) else {
return false;
};
let mut decoded = Vec::with_capacity(raw.len());
flate2::read::GzDecoder::new(gz.as_slice())
.read_to_end(&mut decoded)
.is_ok()
&& decoded == raw
}
fn find_manifests(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) -> std::io::Result<()> {
let meta = std::fs::symlink_metadata(dir)?;
if !meta.file_type().is_dir() {
return Ok(());
}
if depth > MAX_DEPTH {
return Ok(());
}
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let file_type = entry.file_type()?;
if file_type.is_symlink() {
continue;
}
if file_type.is_dir() {
find_manifests(&entry.path(), depth + 1, out)?;
} else if file_type.is_file() && entry.file_name() == "manifest.json" {
out.push(entry.path());
}
}
Ok(())
}
fn app_name(manifest: &serde_json::Value, app_dir: &Path) -> String {
manifest
.get("name")
.and_then(|value| value.as_str())
.map(str::to_owned)
.or_else(|| {
app_dir
.file_name()
.map(|name| name.to_string_lossy().into_owned())
})
.unwrap_or_else(|| "app".to_owned())
}
fn gzip_sibling_path(file: &Path) -> PathBuf {
let mut sibling = file.as_os_str().to_owned();
sibling.push(".gz");
PathBuf::from(sibling)
}
fn forward_relative(root: &Path, path: &Path) -> String {
path.strip_prefix(root)
.unwrap_or(path)
.components()
.filter_map(|component| match component {
Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
_ => None,
})
.collect::<Vec<_>>()
.join("/")
}
fn file_sha256_hex(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
hex::encode(Sha256::digest(bytes))
}
fn integrity_mismatch_detail(declared: &serde_json::Value, bytes: &[u8]) -> Option<String> {
let hex_digest = file_sha256_hex(bytes);
match declared.as_str() {
Some(value) if value == hex_digest => None,
Some(value) => Some(format!("file sha256 is {hex_digest}, manifest has {value}")),
None => Some(format!(
"file sha256 is {hex_digest}, manifest integrity value is not a string"
)),
}
}
enum Located {
File(PathBuf),
Unusable(String),
}
fn locate_integrity_file(app_dir: &Path, relative: &str) -> Result<Located> {
let rel_path = Path::new(relative);
let plain = rel_path
.components()
.all(|part| matches!(part, Component::Normal(_) | Component::CurDir));
let named = rel_path
.components()
.any(|part| matches!(part, Component::Normal(_)));
if !plain || !named {
return Ok(Located::Unusable(
"not a file inside the app dir".to_owned(),
));
}
let mut cursor = app_dir.to_path_buf();
let leaf_components = rel_components(rel_path);
for part in rel_path.components() {
let Component::Normal(part) = part else {
continue;
};
cursor.push(part);
let meta = match std::fs::symlink_metadata(&cursor) {
Ok(meta) => meta,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(Located::Unusable("file not found".to_owned()));
}
Err(error) => {
return Err(error).with_context(|| format!("stat {}", cursor.display()));
}
};
let at_leaf = cursor.components().count() == app_dir.components().count() + leaf_components;
if meta.file_type().is_symlink() {
let why = if at_leaf {
"path is a symlink"
} else {
"path passes through a symlink"
};
return Ok(Located::Unusable(why.to_owned()));
}
if at_leaf && !meta.file_type().is_file() {
return Ok(Located::Unusable("not a regular file".to_owned()));
}
if !at_leaf && !meta.file_type().is_dir() {
return Ok(Located::Unusable(
"not a file inside the app dir".to_owned(),
));
}
}
Ok(Located::File(cursor))
}
fn gzip_finding(relative: &str, file: &Path, bytes: &[u8]) -> Result<Option<Finding>> {
let sibling = gzip_sibling_path(file);
match std::fs::symlink_metadata(&sibling) {
Ok(meta) if meta.file_type().is_file() => {
if sibling_is_current(file, &sibling) {
Ok(None)
} else {
Ok(Some(Finding::error(
"stale-gzip",
relative,
"gzip sibling does not decompress to the file",
)))
}
}
Ok(_) => Ok(Some(Finding::error(
"stale-gzip",
relative,
"gzip sibling is not a regular file",
))),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
if !stored_gzip::is_stored_gzip_candidate(Path::new(relative), bytes.len() as u64) {
return Ok(None);
}
let compressed =
stored_gzip::gzip_best(bytes).with_context(|| format!("gzip {relative}"))?;
if (compressed.len() as u64) < bytes.len() as u64 {
Ok(Some(Finding::error(
"missing-gzip",
relative,
format!(
"stored gzip sibling would be {} bytes, smaller than the {} byte file",
compressed.len(),
bytes.len()
),
)))
} else {
Ok(None)
}
}
Err(error) => Err(error).with_context(|| format!("stat {}", sibling.display())),
}
}
fn collect_regular_files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
let meta = match std::fs::symlink_metadata(dir) {
Ok(meta) => meta,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error).with_context(|| format!("stat {}", dir.display())),
};
if !meta.file_type().is_dir() {
return Ok(());
}
for entry in std::fs::read_dir(dir).with_context(|| format!("read {}", dir.display()))? {
let entry = entry?;
let file_type = entry
.file_type()
.with_context(|| format!("file type {}", entry.path().display()))?;
if file_type.is_symlink() {
continue;
}
if file_type.is_dir() {
collect_regular_files(&entry.path(), out)?;
} else if file_type.is_file() {
out.push(entry.path());
}
}
Ok(())
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
struct Finding {
rule: String,
severity: String,
path: String,
detail: String,
}
impl Finding {
fn error(rule: &str, path: &str, detail: impl Into<String>) -> Self {
Self {
rule: rule.to_owned(),
severity: "error".to_owned(),
path: path.to_owned(),
detail: detail.into(),
}
}
fn warning(rule: &str, path: &str, detail: impl Into<String>) -> Self {
Self {
rule: rule.to_owned(),
severity: "warning".to_owned(),
path: path.to_owned(),
detail: detail.into(),
}
}
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
struct AppCheck {
app: String,
version: String,
manifest: String,
entry_wire_bytes: u64,
entry_ceiling_bytes: u64,
findings: Vec<Finding>,
}
fn format_human(app: &AppCheck) -> String {
if app.findings.is_empty() {
return format!("{}: ok", app.app);
}
let body = app
.findings
.iter()
.map(|finding| {
if finding.path.is_empty() {
format!("{} {}: {}", finding.severity, finding.rule, finding.detail)
} else {
format!(
"{} {} {}: {}",
finding.severity, finding.rule, finding.path, finding.detail
)
}
})
.collect::<Vec<_>>()
.join("; ");
format!("{}: {body}", app.app)
}
fn check_app(root: &Path, manifest_path: &Path, manifest: &serde_json::Value) -> Result<AppCheck> {
let ui = manifest
.get("ui")
.and_then(|value| value.as_object())
.context("check_app called without a ui object")?;
let app_dir = manifest_path.parent().unwrap_or(root);
let integrity = ui.get("integrity").and_then(|value| value.as_object());
let mut findings = Vec::new();
if integrity.map(|map| map.is_empty()).unwrap_or(true) {
findings.push(Finding::error(
"integrity-empty",
"ui.integrity",
"ui block has an empty or missing integrity map",
));
}
let keys: BTreeSet<&str> = integrity
.map(|map| map.keys().map(String::as_str).collect())
.unwrap_or_default();
match ui.get("entry").and_then(|value| value.as_str()) {
Some(entry) if keys.contains(entry) => {}
Some(entry) => findings.push(Finding::error(
"entry-unlisted",
entry,
"ui.entry is not a key of ui.integrity",
)),
None => findings.push(Finding::error("entry-unlisted", "", "ui.entry is missing")),
}
if let Some(icon) = ui.get("icon").and_then(|value| value.as_str()) {
if !keys.contains(icon) {
findings.push(Finding::error(
"entry-unlisted",
icon,
"ui.icon is not a key of ui.integrity",
));
}
}
let mut listed: Vec<&String> = integrity
.map(|map| map.keys().collect())
.unwrap_or_default();
listed.sort();
let mut all_readable = true;
for relative in listed {
let declared = integrity
.and_then(|map| map.get(relative))
.cloned()
.unwrap_or(serde_json::Value::Null);
match locate_integrity_file(app_dir, relative)? {
Located::Unusable(detail) => {
all_readable = false;
findings.push(Finding::error("integrity-missing-file", relative, detail));
}
Located::File(file) => {
let bytes = std::fs::read(&file)
.with_context(|| format!("read {} ({})", relative, file.display()))?;
if let Some(detail) = integrity_mismatch_detail(&declared, &bytes) {
findings.push(Finding::error("integrity-mismatch", relative, detail));
}
if let Some(finding) = gzip_finding(relative, &file, &bytes)? {
findings.push(finding);
}
}
}
}
let mut files = Vec::new();
collect_regular_files(app_dir, &mut files)?;
files.sort();
for file in files {
let name = file
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("");
if !name.ends_with(".gz") {
continue;
}
let rel = forward_relative(app_dir, &file);
let Some(stem) = rel.strip_suffix(".gz") else {
continue;
};
if keys.contains(stem) || keys.contains(rel.as_str()) {
continue;
}
let detail = if stored_gzip::is_stored_gzip_sibling(&file) {
"stored gzip sibling is not listed in ui.integrity"
} else {
"gzip file is not an integrity key"
};
findings.push(Finding::error("stray-gzip", &rel, detail));
}
let entry_wire_bytes = if all_readable {
let report = entry_report(app_dir, manifest.get("ui").expect("ui object"))?;
if report.wire_bytes > MAX_STAGE_ENTRY_BYTES {
let entry = ui
.get("entry")
.and_then(|value| value.as_str())
.unwrap_or("");
findings.push(Finding::warning(
"entry-over-budget",
entry,
format!(
"entry wire bytes {} exceed the {} ceiling",
report.wire_bytes, MAX_STAGE_ENTRY_BYTES
),
));
}
report.wire_bytes
} else {
0
};
let version = manifest
.get("version")
.and_then(|value| value.as_str())
.unwrap_or("")
.to_owned();
Ok(AppCheck {
app: app_name(manifest, app_dir),
version,
manifest: forward_relative(root, manifest_path),
entry_wire_bytes,
entry_ceiling_bytes: MAX_STAGE_ENTRY_BYTES,
findings,
})
}
pub fn check(root: &Path, json: bool, strict: bool) -> Result<()> {
let shown_root = root;
let root = std::fs::canonicalize(root)
.with_context(|| format!("resolve stage root {}", shown_root.display()))?;
anyhow::ensure!(
root.is_dir(),
"stage root {} is not a directory",
shown_root.display()
);
let mut manifests = Vec::new();
find_manifests(&root, 0, &mut manifests)
.with_context(|| format!("scan {} for manifests", root.display()))?;
manifests.sort();
let mut reports = Vec::new();
for manifest_path in manifests {
let text = std::fs::read_to_string(&manifest_path)
.with_context(|| format!("read {}", manifest_path.display()))?;
let manifest: serde_json::Value = match serde_json::from_str(&text) {
Ok(value) => value,
Err(error) => {
eprintln!(
"warning: {} is not valid JSON, skipped: {error}",
manifest_path.display()
);
continue;
}
};
if manifest.get("ui").filter(|ui| ui.is_object()).is_none() {
continue;
}
reports.push(check_app(&root, &manifest_path, &manifest)?);
}
if json {
println!("{}", serde_json::to_string_pretty(&reports)?);
} else if reports.is_empty() {
println!(
"stage-files: no stage or widget manifests under {}",
root.display()
);
} else {
for report in &reports {
println!("{}", format_human(report));
}
}
if strict {
let errors = reports
.iter()
.flat_map(|report| &report.findings)
.filter(|finding| finding.severity == "error")
.count();
if errors > 0 {
anyhow::bail!("stage-files --check: {errors} error finding(s)");
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn big_js() -> String {
"export const value = 'stage file';\n".repeat(200)
}
fn write_app(app_dir: &Path, name: &str, files: &[&str]) {
fs::create_dir_all(app_dir).unwrap();
let mut integrity = serde_json::Map::new();
for file in files {
let path = app_dir.join(file);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, big_js()).unwrap();
integrity.insert((*file).to_owned(), serde_json::json!("sha256-x"));
}
let manifest = serde_json::json!({
"name": name,
"ui": { "kind": "stage", "entry": files[0], "integrity": integrity }
});
fs::write(app_dir.join("manifest.json"), manifest.to_string()).unwrap();
}
fn app_path(root: &Path, app: &str) -> PathBuf {
root.join("usr/lib/node/apps").join(app)
}
#[test]
fn finds_every_app_under_a_package_root() {
let dir = tempfile::tempdir().unwrap();
write_app(&app_path(dir.path(), "a"), "app-a", &["ui/dist/main.js"]);
write_app(&app_path(dir.path(), "b"), "app-b", &["ui/dist/main.js"]);
let summary = run(dir.path()).unwrap();
assert_eq!(summary.apps, vec!["app-a", "app-b"]);
assert_eq!(summary.gz_written, 2);
assert!(app_path(dir.path(), "b")
.join("ui/dist/main.js.gz")
.is_file());
}
#[test]
fn writes_siblings_only_for_integrity_paths() {
let dir = tempfile::tempdir().unwrap();
let app = app_path(dir.path(), "a");
write_app(&app, "app-a", &["ui/dist/main.js"]);
fs::write(app.join("ui/dist/unlisted.js"), big_js()).unwrap();
run(dir.path()).unwrap();
assert!(app.join("ui/dist/main.js.gz").is_file());
assert!(!app.join("ui/dist/unlisted.js.gz").exists());
}
#[test]
fn honours_integrity_paths_outside_ui_dist() {
let dir = tempfile::tempdir().unwrap();
let app = app_path(dir.path(), "a");
write_app(&app, "app-a", &["dist/stage/main.js", "dist/stage.js"]);
let summary = run(dir.path()).unwrap();
assert_eq!(summary.gz_written, 2);
assert!(app.join("dist/stage/main.js.gz").is_file());
assert!(app.join("dist/stage.js.gz").is_file());
}
#[test]
fn second_run_writes_nothing() {
let dir = tempfile::tempdir().unwrap();
write_app(&app_path(dir.path(), "a"), "app-a", &["ui/dist/main.js"]);
assert_eq!(run(dir.path()).unwrap().gz_written, 1);
let first_gz = fs::read(app_path(dir.path(), "a").join("ui/dist/main.js.gz")).unwrap();
let again = run(dir.path()).unwrap();
assert_eq!(again.gz_written, 0);
assert_eq!(again.apps, vec!["app-a"]);
assert_eq!(
fs::read(app_path(dir.path(), "a").join("ui/dist/main.js.gz")).unwrap(),
first_gz
);
}
#[cfg(unix)]
#[test]
fn does_not_follow_symlinks() {
let dir = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
write_app(
&outside.path().join("apps/z"),
"app-z",
&["ui/dist/main.js"],
);
let app = app_path(dir.path(), "a");
write_app(&app, "app-a", &["ui/dist/main.js", "ui/dist/linked.js"]);
fs::remove_file(app.join("ui/dist/linked.js")).unwrap();
std::os::unix::fs::symlink(
outside.path().join("apps/z/ui/dist/main.js"),
app.join("ui/dist/linked.js"),
)
.unwrap();
std::os::unix::fs::symlink(
outside.path().join("apps"),
dir.path().join("usr/lib/node/apps/linked-apps"),
)
.unwrap();
let summary = run(dir.path()).unwrap();
assert_eq!(summary.apps, vec!["app-a"]);
assert!(!outside.path().join("apps/z/ui/dist/main.js.gz").exists());
assert!(!app.join("ui/dist/linked.js.gz").exists());
}
#[test]
fn a_root_without_manifests_is_ok() {
let dir = tempfile::tempdir().unwrap();
let summary = run(dir.path()).unwrap();
assert_eq!(summary, StageFilesSummary::default());
}
#[test]
fn a_path_escaping_the_app_dir_is_skipped() {
let dir = tempfile::tempdir().unwrap();
let app = app_path(dir.path(), "a");
write_app(&app, "app-a", &["ui/dist/main.js"]);
fs::write(app.parent().unwrap().join("secret.js"), big_js()).unwrap();
let manifest = serde_json::json!({
"name": "app-a",
"ui": { "kind": "stage", "entry": "ui/dist/main.js", "integrity": {
"ui/dist/main.js": "sha256-x",
"../secret.js": "sha256-x",
} }
});
fs::write(app.join("manifest.json"), manifest.to_string()).unwrap();
let summary = run(dir.path()).unwrap();
assert_eq!(summary.gz_written, 1);
assert!(!app.parent().unwrap().join("secret.js.gz").exists());
}
#[test]
fn a_stale_sibling_is_rewritten() {
let dir = tempfile::tempdir().unwrap();
let app = app_path(dir.path(), "a");
write_app(&app, "app-a", &["ui/dist/main.js"]);
assert_eq!(run(dir.path()).unwrap().gz_written, 1);
let new_bytes = "export const other = 'changed';\n".repeat(300);
fs::write(app.join("ui/dist/main.js"), &new_bytes).unwrap();
assert_eq!(run(dir.path()).unwrap().gz_written, 1);
let mut decoded = String::new();
std::io::Read::read_to_string(
&mut flate2::read::GzDecoder::new(
fs::File::open(app.join("ui/dist/main.js.gz")).unwrap(),
),
&mut decoded,
)
.unwrap();
assert_eq!(decoded, new_bytes);
}
#[test]
fn a_stale_sibling_of_a_file_that_no_longer_qualifies_is_removed() {
let dir = tempfile::tempdir().unwrap();
let app = app_path(dir.path(), "a");
write_app(&app, "app-a", &["ui/dist/main.js"]);
run(dir.path()).unwrap();
fs::write(app.join("ui/dist/main.js"), "tiny").unwrap();
assert_eq!(run(dir.path()).unwrap().gz_written, 0);
assert!(!app.join("ui/dist/main.js.gz").exists());
}
#[test]
fn an_unparsable_manifest_or_one_without_integrity_is_skipped() {
let dir = tempfile::tempdir().unwrap();
let bad = app_path(dir.path(), "bad");
fs::create_dir_all(&bad).unwrap();
fs::write(bad.join("manifest.json"), "{\"ui\": ").unwrap();
let none = app_path(dir.path(), "none");
fs::create_dir_all(&none).unwrap();
fs::write(
none.join("manifest.json"),
"{\"ui\": {\"kind\": \"stage\"}}",
)
.unwrap();
let summary = run(dir.path()).unwrap();
assert!(summary.apps.is_empty());
}
#[cfg(unix)]
#[test]
fn a_symlinked_parent_dir_is_skipped_and_nothing_is_written_outside() {
let dir = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
fs::create_dir_all(outside.path().join("dist")).unwrap();
fs::write(outside.path().join("dist/main.js"), big_js()).unwrap();
fs::write(outside.path().join("dist/main.js.gz"), b"keep me").unwrap();
let app = app_path(dir.path(), "a");
fs::create_dir_all(&app).unwrap();
std::os::unix::fs::symlink(outside.path(), app.join("ui")).unwrap();
let manifest = serde_json::json!({"name": "app-a", "ui": {"kind": "stage",
"entry": "ui/dist/main.js", "integrity": {"ui/dist/main.js": "sha256-x"}}});
fs::write(app.join("manifest.json"), manifest.to_string()).unwrap();
let summary = run(dir.path());
let _ = summary;
assert_eq!(
fs::read(outside.path().join("dist/main.js.gz")).unwrap(),
b"keep me"
);
}
#[test]
fn a_dot_key_does_not_walk_the_directory() {
let dir = tempfile::tempdir().unwrap();
let app = app_path(dir.path(), "a");
write_app(&app, "app-a", &["ui/dist/main.js"]);
fs::write(app.join("ui/dist/unlisted.js"), big_js()).unwrap();
let manifest = serde_json::json!({"name": "app-a", "ui": {"kind": "stage",
"entry": "ui/dist/main.js", "integrity": {".": "x", "": "x", "ui/dist": "x"}}});
fs::write(app.join("manifest.json"), manifest.to_string()).unwrap();
let _ = run(dir.path());
assert!(!app.join("ui/dist/unlisted.js.gz").exists());
assert!(!app.join("ui/dist/main.js.gz").exists());
}
#[cfg(unix)]
#[test]
fn a_symlinked_root_is_followed_and_a_file_root_is_an_error() {
let dir = tempfile::tempdir().unwrap();
let real = dir.path().join("real");
write_app(&app_path(&real, "a"), "app-a", &["ui/dist/main.js"]);
let link = dir.path().join("link");
std::os::unix::fs::symlink(&real, &link).unwrap();
assert_eq!(run(&link).unwrap().apps, vec!["app-a"]);
let file = dir.path().join("file");
fs::write(&file, "x").unwrap();
assert!(run(&file).is_err());
assert!(run(&dir.path().join("missing")).is_err());
}
#[cfg(unix)]
#[test]
fn a_stale_sibling_beside_a_symlinked_file_is_removed() {
let dir = tempfile::tempdir().unwrap();
let app = app_path(dir.path(), "a");
write_app(&app, "app-a", &["ui/dist/main.js", "ui/dist/linked.js"]);
fs::remove_file(app.join("ui/dist/linked.js")).unwrap();
std::os::unix::fs::symlink(app.join("ui/dist/main.js"), app.join("ui/dist/linked.js"))
.unwrap();
fs::write(app.join("ui/dist/linked.js.gz"), b"stale").unwrap();
run(dir.path()).unwrap();
assert!(!app.join("ui/dist/linked.js.gz").exists());
}
#[test]
fn a_missing_integrity_file_error_names_the_app_and_key() {
let dir = tempfile::tempdir().unwrap();
let app = app_path(dir.path(), "a");
write_app(&app, "app-a", &["ui/dist/main.js"]);
fs::remove_file(app.join("ui/dist/main.js")).unwrap();
let error = format!("{:#}", run(dir.path()).unwrap_err());
assert!(
error.contains("app-a") && error.contains("ui/dist/main.js"),
"{error}"
);
}
#[test]
fn integrity_digest_matches_the_kernel_lowercase_hex_only() {
let bytes = b"stage-bytes";
let hex_digest = file_sha256_hex(bytes);
assert!(integrity_mismatch_detail(&serde_json::json!(hex_digest), bytes).is_none());
assert!(
integrity_mismatch_detail(&serde_json::json!(hex_digest.to_uppercase()), bytes)
.is_some()
);
use sha2::Digest;
let sri = format!(
"sha256-{}",
base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
sha2::Sha256::digest(bytes)
)
);
assert!(
integrity_mismatch_detail(&serde_json::json!(sri), bytes).is_some(),
"the kernel rejects sha256-<base64>"
);
}
}