use std::{
collections::{BTreeMap, BTreeSet},
ffi::OsString,
path::{Component, Path, PathBuf},
};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use serde::Deserialize;
use sha2::{Digest, Sha256, Sha384, Sha512};
use crate::{DocumentAssets, ViewError};
pub const TRUNK_ASSET_MANIFEST_FILE: &str = "trunk-assets.json";
pub const TRUNK_ASSET_MANIFEST_ENV: &str = "SERENADE_TRUNK_ASSET_MANIFEST";
pub const TRUNK_DIST_DIRECTORY_ENV: &str = "SERENADE_TRUNK_DIST_DIR";
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct TrunkAssetManifest {
pub public_url: String,
pub html: String,
pub assets: Vec<TrunkAssetReference>,
pub wasm: Vec<TrunkWasmBundle>,
pub document_assets: Vec<TrunkDocumentAsset>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct TrunkDocumentAsset {
pub order: Option<usize>,
pub location: String,
pub html: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct TrunkAssetReference {
pub order: usize,
pub role: String,
pub url: String,
pub content_digest: Option<String>,
pub attributes: BTreeMap<String, String>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct TrunkWasmBundle {
pub app_type: String,
pub order: Option<usize>,
pub js_url: String,
pub js_content_digest: Option<String>,
pub wasm_url: String,
pub wasm_content_digest: Option<String>,
pub wasm_size: u64,
pub initializer_url: Option<String>,
pub initializer_content_digest: Option<String>,
pub init_with_object: bool,
pub import_bindings: bool,
pub import_bindings_name: Option<String>,
pub compression_algorithm: Option<String>,
pub cross_origin: String,
pub inject_scripts: bool,
pub custom_script_pattern: Option<String>,
pub custom_preload_pattern: Option<String>,
pub pattern_parameters: BTreeMap<String, String>,
pub preloads: Vec<TrunkPreloadReference>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct TrunkPreloadReference {
pub rel: String,
pub url: String,
pub content_digest: Option<String>,
pub cross_origin: String,
pub integrity: Option<String>,
#[serde(rename = "as")]
pub as_type: Option<String>,
#[serde(rename = "type")]
pub media_type: Option<String>,
}
impl TrunkAssetManifest {
pub fn read_from_env() -> Result<Self, ViewError> {
Self::read_from_environment(std::env::var_os(TRUNK_ASSET_MANIFEST_ENV))
}
fn read_from_environment(path: Option<OsString>) -> Result<Self, ViewError> {
let path = path.ok_or_else(|| {
ViewError::msg(format!(
"environment variable {TRUNK_ASSET_MANIFEST_ENV} is not set"
))
})?;
Self::read(path)
}
pub fn read(path: impl AsRef<Path>) -> Result<Self, ViewError> {
let path = path.as_ref();
let contents = std::fs::read(path).map_err(|error| {
ViewError::msg(format!("failed to read {}: {error}", path.display()))
})?;
let manifest: Self = serde_json::from_slice(&contents)
.map_err(|error| ViewError::msg(format!("invalid Trunk asset manifest: {error}")))?;
manifest.validate()?;
Ok(manifest)
}
pub fn from_json(contents: &[u8]) -> Result<Self, ViewError> {
let manifest: Self = serde_json::from_slice(contents)
.map_err(|error| ViewError::msg(format!("invalid Trunk asset manifest: {error}")))?;
manifest.validate()?;
Ok(manifest)
}
fn validate(&self) -> Result<(), ViewError> {
if self.public_url.trim().is_empty() {
return Err(ViewError::msg(
"Trunk asset manifest has an empty public URL prefix",
));
}
validate_public_url(&self.public_url)?;
if self.html.trim().is_empty() {
return Err(ViewError::msg(
"Trunk asset manifest has an empty HTML output filename",
));
}
let mut previous_order = None;
for asset in &self.assets {
if !matches!(asset.role.as_str(), "stylesheet" | "script" | "icon") {
return Err(ViewError::msg(format!(
"unsupported Trunk asset role `{}`",
asset.role
)));
}
if asset.url.trim().is_empty() {
return Err(ViewError::msg(format!(
"Trunk {} asset at order {} has an empty URL",
asset.role, asset.order
)));
}
if asset.content_digest.is_none() {
return Err(ViewError::msg(format!(
"Trunk {} asset `{}` is missing its content digest",
asset.role, asset.url
)));
}
if previous_order.is_some_and(|order| asset.order <= order) {
return Err(ViewError::msg(
"Trunk asset manifest entries are not in strictly increasing source order",
));
}
previous_order = Some(asset.order);
}
let mut wasm_orders = BTreeSet::new();
for bundle in &self.wasm {
if !matches!(bundle.app_type.as_str(), "main" | "worker") {
return Err(ViewError::msg(format!(
"unsupported Trunk WASM application type `{}`",
bundle.app_type
)));
}
if bundle.js_url.trim().is_empty() || bundle.wasm_url.trim().is_empty() {
return Err(ViewError::msg(
"Trunk WASM bundle has an empty JavaScript or WebAssembly URL",
));
}
if bundle.js_content_digest.is_none()
|| bundle.wasm_content_digest.is_none()
|| bundle.initializer_url.is_some() != bundle.initializer_content_digest.is_some()
{
return Err(ViewError::msg(
"Trunk WASM bundle is missing a content digest",
));
}
if bundle.order.is_some_and(|order| !wasm_orders.insert(order)) {
return Err(ViewError::msg(
"Trunk WASM bundles have duplicate source order values",
));
}
for preload in &bundle.preloads {
if !matches!(preload.rel.as_str(), "preload" | "modulepreload")
|| preload.url.trim().is_empty()
{
return Err(ViewError::msg(
"Trunk WASM bundle contains an invalid preload reference",
));
}
if preload.content_digest.is_none() {
return Err(ViewError::msg(format!(
"Trunk preload `{}` is missing its content digest",
preload.url
)));
}
}
}
self.validate_document_assets()?;
self.validate_url_prefixes()
}
fn validate_document_assets(&self) -> Result<(), ViewError> {
for asset in &self.document_assets {
if !matches!(asset.location.as_str(), "head" | "body" | "unknown") {
return Err(ViewError::msg(format!(
"Trunk document asset has unsupported location `{}`",
asset.location
)));
}
if asset.html.trim().is_empty() {
return Err(ViewError::msg("Trunk document asset has empty markup"));
}
}
for bundle in &self.wasm {
if bundle.app_type == "main"
&& bundle.inject_scripts
&& !self
.document_assets
.iter()
.any(|asset| asset.order == bundle.order && asset.html.contains("<script"))
{
return Err(ViewError::msg(format!(
"Trunk manifest has no generated loader script for WASM bundle `{}`",
bundle.js_url
)));
}
}
Ok(())
}
pub fn document_assets(&self) -> Result<DocumentAssets, ViewError> {
let (mut head, mut body) = (String::new(), String::new());
for asset in &self.document_assets {
match asset.location.as_str() {
"head" => head.push_str(&asset.html),
"body" => body.push_str(&asset.html),
_ => {
return Err(ViewError::msg(format!(
"Trunk inserted document asset markup outside <head> and <body>: {}",
asset.html
)));
}
}
}
Ok(DocumentAssets::new(head, body))
}
fn validate_url_prefixes(&self) -> Result<(), ViewError> {
let urls = self
.assets
.iter()
.map(|asset| &asset.url)
.chain(self.wasm.iter().flat_map(|bundle| {
[&bundle.js_url, &bundle.wasm_url]
.into_iter()
.chain(&bundle.initializer_url)
.chain(bundle.preloads.iter().map(|preload| &preload.url))
}));
for url in urls {
self.local_asset_path(url)?;
}
Ok(())
}
pub fn validate_output(&self, dist: impl AsRef<Path>) -> Result<(), ViewError> {
let root = canonical_output_root(dist.as_ref())?;
let html_path = safe_relative_path(&self.html)?;
contained_file(&root, &html_path, "HTML output")?;
for asset in &self.assets {
let path = self.local_asset_path(&asset.url)?;
let (file, _) = contained_file(
&root,
&path,
&format!("{} asset `{}`", asset.role, asset.url),
)?;
let integrity = asset.attributes.get("integrity");
verify_digests(&file, asset.content_digest.iter().chain(integrity))?;
}
for bundle in &self.wasm {
let js_path = self.local_asset_path(&bundle.js_url)?;
let (js_file, _) = contained_file(&root, &js_path, "WASM JavaScript loader")?;
verify_digests(&js_file, &bundle.js_content_digest)?;
let wasm_path = self.local_asset_path(&bundle.wasm_url)?;
let (wasm_file, wasm_metadata) =
contained_file(&root, &wasm_path, "WebAssembly module")?;
verify_digests(&wasm_file, &bundle.wasm_content_digest)?;
let actual_size = wasm_metadata.len();
if actual_size != bundle.wasm_size {
return Err(ViewError::msg(format!(
"stale WebAssembly module `{}`: manifest size is {} bytes, file size is {actual_size} bytes",
bundle.wasm_url, bundle.wasm_size
)));
}
if let Some(initializer_url) = &bundle.initializer_url {
let path = self.local_asset_path(initializer_url)?;
let (file, _) = contained_file(&root, &path, "WASM initializer")?;
verify_digests(&file, &bundle.initializer_content_digest)?;
}
for preload in &bundle.preloads {
let path = self.local_asset_path(&preload.url)?;
let (file, _) = contained_file(&root, &path, "WASM preload")?;
verify_digests(
&file,
preload.content_digest.iter().chain(&preload.integrity),
)?;
}
}
Ok(())
}
pub fn resolve_output_file(
&self,
dist: impl AsRef<Path>,
url: &str,
) -> Result<PathBuf, ViewError> {
let relative = self.output_path_for_url(url)?;
let root = canonical_output_root(dist.as_ref())?;
let (file, _) = contained_file(&root, &relative, &format!("output file for `{url}`"))?;
Ok(file)
}
pub fn output_path_for_url(&self, url: &str) -> Result<PathBuf, ViewError> {
let root = self.public_url.trim_end_matches('/');
if url
.strip_prefix(root)
.is_some_and(|rest| rest.is_empty() || rest == "/")
&& !url.is_empty()
{
return safe_relative_path(&self.html);
}
self.local_asset_path(url)
}
fn local_asset_path(&self, url: &str) -> Result<PathBuf, ViewError> {
let relative = url
.strip_prefix(&self.public_url)
.and_then(|relative| {
if self.public_url.ends_with('/') {
Some(relative)
} else {
relative.strip_prefix('/')
}
})
.ok_or_else(|| {
ViewError::msg(format!(
"asset URL `{url}` does not use manifest public URL prefix `{}`",
self.public_url
))
})?;
if relative.contains(['?', '#']) {
return Err(ViewError::msg(format!(
"asset URL `{url}` contains an unsupported query or fragment"
)));
}
safe_relative_path(relative)
}
}
fn safe_relative_path(path: &str) -> Result<PathBuf, ViewError> {
let decoded = percent_decode(path)?;
if decoded.is_empty() || decoded.contains('\\') {
return Err(ViewError::msg(format!(
"invalid relative asset path `{path}`"
)));
}
let path_buf = PathBuf::from(&decoded);
if path_buf.is_absolute()
|| path_buf
.components()
.any(|component| !matches!(component, Component::Normal(_)))
{
return Err(ViewError::msg(format!(
"asset path `{path}` escapes the Trunk output directory"
)));
}
Ok(path_buf)
}
fn percent_decode(path: &str) -> Result<String, ViewError> {
let bytes = path.as_bytes();
let mut decoded = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
if bytes[index] == b'%' {
if index + 2 >= bytes.len() {
return Err(ViewError::msg(format!(
"malformed percent escape in asset path `{path}`"
)));
}
let high = hex_digit(bytes[index + 1]);
let low = hex_digit(bytes[index + 2]);
let (Some(high), Some(low)) = (high, low) else {
return Err(ViewError::msg(format!(
"malformed percent escape in asset path `{path}`"
)));
};
decoded.push((high << 4) | low);
index += 3;
} else {
decoded.push(bytes[index]);
index += 1;
}
}
String::from_utf8(decoded)
.map_err(|_| ViewError::msg(format!("asset path `{path}` is not valid UTF-8")))
}
const fn hex_digit(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
fn canonical_output_root(dist: &Path) -> Result<PathBuf, ViewError> {
dist.canonicalize().map_err(|error| {
ViewError::msg(format!(
"failed to resolve Trunk output directory {}: {error}",
dist.display()
))
})
}
fn validate_public_url(public_url: &str) -> Result<(), ViewError> {
let lower = public_url.to_ascii_lowercase();
let after_scheme = lower
.strip_prefix("https://")
.or_else(|| lower.strip_prefix("http://"));
let allowed_form = after_scheme.map_or_else(
|| public_url.starts_with('/') && !public_url.starts_with("//"),
|rest| !rest.is_empty() && !rest.starts_with('/'),
);
let allowed_characters = public_url
.chars()
.all(|character| character.is_ascii_graphic() && !"\\\"'<>`".contains(character));
if allowed_form && allowed_characters {
Ok(())
} else {
Err(ViewError::msg(format!(
"Trunk asset manifest public URL `{public_url}` must be a root-relative path or an http(s) URL"
)))
}
}
fn contained_file(
root: &Path,
relative: &Path,
description: &str,
) -> Result<(PathBuf, std::fs::Metadata), ViewError> {
let path = root.join(relative);
let resolved = path
.canonicalize()
.map_err(|error| file_error(&path, description, &error))?;
if !resolved.starts_with(root) {
return Err(ViewError::msg(format!(
"{description} {} escapes the Trunk output directory through a symbolic link",
path.display()
)));
}
let metadata = require_file(&resolved, description)?;
Ok((resolved, metadata))
}
fn require_file(path: &Path, description: &str) -> Result<std::fs::Metadata, ViewError> {
match std::fs::metadata(path) {
Ok(metadata) if metadata.is_file() => Ok(metadata),
Ok(_) => Err(ViewError::msg(format!(
"{description} is not a file: {}",
path.display()
))),
Err(error) => Err(file_error(path, description, &error)),
}
}
fn file_error(path: &Path, description: &str, error: &std::io::Error) -> ViewError {
if error.kind() == std::io::ErrorKind::NotFound {
ViewError::msg(format!("{description} is missing: {}", path.display()))
} else {
ViewError::msg(format!(
"failed to inspect {description} {}: {error}",
path.display()
))
}
}
fn verify_digests<'a>(
path: &Path,
digests: impl IntoIterator<Item = &'a String>,
) -> Result<(), ViewError> {
digests
.into_iter()
.try_for_each(|digest| verify_digest(path, digest))
}
fn verify_digest(path: &Path, digest: &str) -> Result<(), ViewError> {
let (algorithm, expected) = digest
.split_once('-')
.ok_or_else(|| ViewError::msg(format!("malformed asset digest `{digest}`")))?;
let expected = STANDARD
.decode(expected)
.map_err(|error| ViewError::msg(format!("malformed asset digest: {error}")))?;
let contents = std::fs::read(path)
.map_err(|error| ViewError::msg(format!("failed to read {}: {error}", path.display())))?;
let actual = match algorithm {
"sha256" => Sha256::digest(contents).to_vec(),
"sha384" => Sha384::digest(contents).to_vec(),
"sha512" => Sha512::digest(contents).to_vec(),
_ => {
return Err(ViewError::msg(format!(
"unsupported asset digest algorithm `{algorithm}`"
)));
}
};
if actual != expected {
return Err(ViewError::msg(format!(
"stale asset {}: content digest check failed",
path.display()
)));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use base64::engine::general_purpose::STANDARD;
use sha2::{Digest, Sha384};
const MANIFEST: &str = r#"{
"public_url": "/app/",
"html": "index.html",
"assets": [
{
"order": 1,
"role": "stylesheet",
"url": "/app/site-123.css",
"content_digest": "sha256-ZGlnZXN0",
"attributes": {"integrity": "sha384-example"}
},
{
"order": 3,
"role": "script",
"url": "/app/app-123.js",
"content_digest": "sha256-ZGlnZXN0",
"attributes": {"type": "module"}
}
],
"wasm": [
{
"app_type": "main",
"order": 2,
"js_url": "/app/app-123.js",
"js_content_digest": "sha256-ZGlnZXN0",
"wasm_url": "/app/app-123_bg.wasm",
"wasm_content_digest": "sha256-ZGlnZXN0",
"wasm_size": 1024,
"initializer_url": null,
"initializer_content_digest": null,
"init_with_object": true,
"import_bindings": false,
"import_bindings_name": null,
"compression_algorithm": null,
"cross_origin": "anonymous",
"inject_scripts": true,
"custom_script_pattern": null,
"custom_preload_pattern": null,
"pattern_parameters": {},
"preloads": [
{
"rel": "modulepreload",
"url": "/app/app-123.js",
"content_digest": "sha256-ZGlnZXN0",
"cross_origin": "anonymous",
"integrity": null,
"as": null,
"type": null
}
]
}
],
"document_assets": [
{
"order": 2,
"location": "head",
"html": "<script type=\"module\">import init from '/app/app-123.js';await init();</script>"
}
]
}"#;
fn manifest_value() -> serde_json::Value {
serde_json::from_str(MANIFEST).expect("fixture JSON should be valid")
}
fn push_document_asset(json: &mut serde_json::Value, asset: serde_json::Value) {
json["document_assets"]
.as_array_mut()
.expect("document assets array")
.push(asset);
}
fn assert_manifest_error(json: &serde_json::Value, expected: &str) {
let bytes = serde_json::to_vec(json).expect("serialize manifest");
let error = TrunkAssetManifest::from_json(&bytes)
.expect_err("manifest should be rejected")
.to_string();
assert!(error.contains(expected), "{error}");
}
#[test]
fn reads_current_asset_and_wasm_metadata() {
let manifest = TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("valid manifest");
assert_eq!(manifest.assets[0].role, "stylesheet");
assert_eq!(manifest.assets[0].url, "/app/site-123.css");
assert_eq!(manifest.wasm[0].wasm_url, "/app/app-123_bg.wasm");
assert_eq!(manifest.wasm[0].preloads[0].rel, "modulepreload");
assert_eq!(manifest.wasm[0].preloads[0].as_type, None);
}
#[test]
fn supports_html_only_manifests() {
let json = br#"{
"public_url": "/",
"html": "index.html",
"assets": [],
"wasm": [],
"document_assets": []
}"#;
let manifest = TrunkAssetManifest::from_json(json).expect("HTML-only manifest");
assert_eq!(manifest.assets, Vec::<TrunkAssetReference>::new());
assert_eq!(manifest.wasm, Vec::<TrunkWasmBundle>::new());
}
#[test]
fn reads_manifest_files_and_environment_values() {
let temp = tempfile::tempdir().expect("temporary directory");
let path = temp.path().join(TRUNK_ASSET_MANIFEST_FILE);
std::fs::write(&path, MANIFEST).expect("write manifest");
let from_file = TrunkAssetManifest::read(&path).expect("read manifest");
assert_eq!(
from_file,
TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("parse manifest")
);
assert_eq!(
TrunkAssetManifest::read_from_environment(Some(path.clone().into_os_string()))
.expect("read environment manifest"),
from_file
);
assert!(
TrunkAssetManifest::read_from_environment(None)
.expect_err("missing manifest path")
.to_string()
.contains("environment variable")
);
let missing = temp.path().join("missing.json");
assert!(
TrunkAssetManifest::read(&missing)
.expect_err("missing file")
.to_string()
.contains("failed to read")
);
std::fs::write(&path, b"{").expect("write malformed manifest");
assert!(
TrunkAssetManifest::read(&path)
.expect_err("malformed file")
.to_string()
.contains("invalid Trunk asset manifest")
);
let configured_path = std::env::var_os(TRUNK_ASSET_MANIFEST_ENV);
assert_eq!(
TrunkAssetManifest::read_from_env().is_ok(),
TrunkAssetManifest::read_from_environment(configured_path).is_ok()
);
}
#[test]
fn rejects_an_injected_main_bundle_without_its_generated_loader() {
let mut json = manifest_value();
json["document_assets"] = serde_json::json!([]);
assert_manifest_error(
&json,
"no generated loader script for WASM bundle `/app/app-123.js`",
);
let mut other_order = manifest_value();
other_order["document_assets"][0]["order"] = 7.into();
assert_manifest_error(&other_order, "no generated loader script");
let mut not_a_script = manifest_value();
not_a_script["document_assets"][0]["html"] =
r#"<link rel="modulepreload" href="/app/app-123.js">"#.into();
assert_manifest_error(¬_a_script, "no generated loader script");
for (field, value) in [
("inject_scripts", false.into()),
("app_type", "worker".into()),
] {
let mut json = manifest_value();
json["document_assets"] = serde_json::json!([]);
json["wasm"][0][field] = value;
let result = TrunkAssetManifest::from_json(json.to_string().as_bytes());
assert!(result.is_ok(), "{field}: {result:?}");
}
}
#[test]
fn ignores_the_version_and_unknown_fields_trunk_writes() {
let expected = TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("manifest");
let mut json = manifest_value();
json.as_object_mut()
.expect("manifest object")
.remove("version");
json["future_field"] = "ignored".into();
assert_eq!(
TrunkAssetManifest::from_json(json.to_string().as_bytes()).expect("no version"),
expected
);
json["version"] = "anything".into();
assert_eq!(
TrunkAssetManifest::from_json(json.to_string().as_bytes()).expect("any version"),
expected
);
}
#[test]
fn rejects_missing_or_invalid_document_assets() {
let mut json = manifest_value();
json.as_object_mut()
.expect("manifest object")
.remove("document_assets");
assert_manifest_error(&json, "missing field `document_assets`");
json["document_assets"] = serde_json::Value::Null;
assert_manifest_error(&json, "invalid type");
}
#[test]
fn rejects_malformed_and_out_of_order_manifests() {
assert!(TrunkAssetManifest::from_json(b"{").is_err());
let mut out_of_order = manifest_value();
out_of_order["assets"][0]["order"] = 4.into();
out_of_order["assets"][1]["order"] = 1.into();
assert!(
TrunkAssetManifest::from_json(out_of_order.to_string().as_bytes())
.expect_err("out-of-order assets")
.to_string()
.contains("strictly increasing source order")
);
}
#[test]
fn rejects_empty_manifest_fields_and_invalid_asset_metadata() {
let mut invalid = manifest_value();
invalid["public_url"] = " ".into();
assert_manifest_error(&invalid, "empty public URL prefix");
let mut invalid = manifest_value();
invalid["html"] = "".into();
assert_manifest_error(&invalid, "empty HTML output filename");
let mut invalid = manifest_value();
invalid["assets"][0]["role"] = "font".into();
assert_manifest_error(&invalid, "unsupported Trunk asset role");
let mut invalid = manifest_value();
invalid["assets"][0]["url"] = "".into();
assert_manifest_error(&invalid, "has an empty URL");
let mut invalid = manifest_value();
invalid["wasm"][0]["js_url"] = "".into();
assert_manifest_error(&invalid, "empty JavaScript or WebAssembly URL");
let mut invalid = manifest_value();
invalid["wasm"][0]["wasm_url"] = "".into();
assert_manifest_error(&invalid, "empty JavaScript or WebAssembly URL");
let mut invalid = manifest_value();
let duplicate_bundle = invalid["wasm"][0].clone();
invalid["wasm"]
.as_array_mut()
.expect("WASM bundles")
.push(duplicate_bundle);
assert_manifest_error(&invalid, "duplicate source order");
let mut invalid = manifest_value();
invalid["wasm"][0]["preloads"][0]["url"] = "".into();
assert_manifest_error(&invalid, "invalid preload reference");
}
#[test]
fn rejects_current_manifests_with_missing_or_inconsistent_digests() {
let mut invalid = manifest_value();
invalid["assets"][0]["content_digest"] = serde_json::Value::Null;
assert_manifest_error(&invalid, "missing its content digest");
let mut invalid = manifest_value();
invalid["wasm"][0]["js_content_digest"] = serde_json::Value::Null;
assert_manifest_error(&invalid, "WASM bundle is missing a content digest");
let mut invalid = manifest_value();
invalid["wasm"][0]["wasm_content_digest"] = serde_json::Value::Null;
assert_manifest_error(&invalid, "WASM bundle is missing a content digest");
let mut invalid = manifest_value();
invalid["wasm"][0]["initializer_url"] = "/app/init.js".into();
assert_manifest_error(&invalid, "WASM bundle is missing a content digest");
let mut invalid = manifest_value();
invalid["wasm"][0]["initializer_content_digest"] = "sha256-ZGlnZXN0".into();
assert_manifest_error(&invalid, "WASM bundle is missing a content digest");
let mut invalid = manifest_value();
invalid["wasm"][0]["preloads"][0]["content_digest"] = serde_json::Value::Null;
assert_manifest_error(&invalid, "missing its content digest");
}
#[test]
fn rejects_invalid_wasm_bootstrap_metadata() {
let mut invalid_app_type: serde_json::Value =
serde_json::from_str(MANIFEST).expect("fixture JSON should be valid");
invalid_app_type["wasm"][0]["app_type"] = "module".into();
let json = serde_json::to_vec(&invalid_app_type).expect("serialize fixture");
assert!(
TrunkAssetManifest::from_json(&json)
.expect_err("invalid WASM application type")
.to_string()
.contains("unsupported Trunk WASM application type")
);
let mut invalid_preload: serde_json::Value =
serde_json::from_str(MANIFEST).expect("fixture JSON should be valid");
invalid_preload["wasm"][0]["preloads"][0]["rel"] = "script".into();
let json = serde_json::to_vec(&invalid_preload).expect("serialize fixture");
assert!(
TrunkAssetManifest::from_json(&json)
.expect_err("invalid WASM preload")
.to_string()
.contains("invalid preload reference")
);
}
fn write_valid_output(dist: &Path) -> TrunkAssetManifest {
std::fs::write(dist.join("index.html"), "<!doctype html>").expect("write HTML");
let css = b"body { color: red; }";
let js = b"export default {};";
let wasm = vec![0; 1024];
std::fs::write(dist.join("site-123.css"), css).expect("write CSS");
std::fs::write(dist.join("app-123.js"), js).expect("write JS");
std::fs::write(dist.join("app-123_bg.wasm"), &wasm).expect("write WASM");
let mut json: serde_json::Value =
serde_json::from_str(MANIFEST).expect("fixture JSON should be valid");
json["assets"][0]["attributes"]["integrity"] =
format!("sha384-{}", STANDARD.encode(Sha384::digest(css))).into();
json["assets"][0]["content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(css))).into();
json["assets"][1]["content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
json["wasm"][0]["js_content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
json["wasm"][0]["wasm_content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(&wasm))).into();
json["wasm"][0]["preloads"][0]["content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
let json = serde_json::to_vec(&json).expect("serialize fixture");
TrunkAssetManifest::from_json(&json).expect("valid manifest")
}
#[test]
fn validate_output_rejects_each_invalid_or_stale_reference() {
type BreakReference = fn(&mut TrunkAssetManifest, &str);
let temp = tempfile::tempdir().expect("temporary directory");
let valid = write_valid_output(temp.path());
let wrong_digest = format!("sha384-{}", STANDARD.encode(Sha384::digest(b"other")));
let cases: [(&str, BreakReference); 10] = [
("../index.html", |m, _| m.html = "../index.html".into()),
("public URL prefix", |m, _| {
m.wasm[0].js_url = "/elsewhere.js".into();
}),
("content digest check failed", |m, d| {
m.wasm[0].js_content_digest = Some(d.into());
}),
("public URL prefix", |m, _| {
m.wasm[0].wasm_url = "/elsewhere.wasm".into();
}),
("content digest check failed", |m, d| {
m.wasm[0].wasm_content_digest = Some(d.into());
}),
("public URL prefix", |m, _| {
m.wasm[0].initializer_url = Some("/elsewhere.js".into());
}),
("public URL prefix", |m, _| {
m.wasm[0].preloads[0].url = "/elsewhere.js".into();
}),
("content digest check failed", |m, d| {
m.wasm[0].preloads[0].content_digest = Some(d.into());
}),
("content digest check failed", |m, d| {
m.wasm[0].preloads[0].integrity = Some(d.into());
}),
("public URL prefix", |m, _| {
m.assets[0].url = "/elsewhere.css".into();
}),
];
for (expected, break_reference) in cases {
let mut manifest = valid.clone();
break_reference(&mut manifest, &wrong_digest);
let error = manifest
.validate_output(temp.path())
.expect_err(expected)
.to_string();
assert!(error.contains(expected), "{expected}: {error}");
}
}
#[test]
fn read_rejects_well_formed_json_that_fails_validation() {
let temp = tempfile::tempdir().expect("temporary directory");
let path = temp.path().join(TRUNK_ASSET_MANIFEST_FILE);
let mut value = manifest_value();
value["assets"][0]["role"] = "invalid".into();
std::fs::write(&path, value.to_string()).expect("write manifest");
assert!(
TrunkAssetManifest::read(&path)
.expect_err("unsupported role")
.to_string()
.contains("unsupported Trunk asset role")
);
}
#[test]
fn validates_all_referenced_files_and_enabled_integrity() {
let temp = tempfile::tempdir().expect("temporary directory");
let manifest = write_valid_output(temp.path());
manifest
.validate_output(temp.path())
.expect("all output files and SRI are valid");
std::fs::write(temp.path().join("site-123.css"), "stale stylesheet")
.expect("replace stylesheet");
assert!(
manifest
.validate_output(temp.path())
.expect_err("stale SRI must fail")
.to_string()
.contains("content digest check failed")
);
}
#[test]
fn rejects_missing_artifacts_stale_wasm_and_unsafe_urls() {
let temp = tempfile::tempdir().expect("temporary directory");
let manifest = write_valid_output(temp.path());
std::fs::remove_file(temp.path().join("site-123.css")).expect("remove CSS");
assert!(
manifest
.validate_output(temp.path())
.expect_err("missing CSS must fail")
.to_string()
.contains("missing")
);
let mut manifest = write_valid_output(temp.path());
manifest.wasm[0].wasm_size += 1;
assert!(
manifest
.validate_output(temp.path())
.expect_err("stale WASM must fail")
.to_string()
.contains("stale WebAssembly module")
);
let mut malicious = manifest;
malicious.assets[0].url = "/app/%2e%2e/secret.css".to_owned();
assert!(
malicious
.validate_output(temp.path())
.expect_err("traversal must fail")
.to_string()
.contains("escapes")
);
}
#[test]
fn rejects_missing_initializer_and_preload_bootstrap_files() {
let temp = tempfile::tempdir().expect("temporary directory");
let mut manifest = write_valid_output(temp.path());
manifest.wasm[0].initializer_url = Some("/app/init-123.js".to_owned());
std::fs::write(temp.path().join("init-123.js"), "export default {};")
.expect("write initializer");
manifest
.validate_output(temp.path())
.expect("initializer is present");
std::fs::remove_file(temp.path().join("init-123.js")).expect("remove initializer");
assert!(
manifest
.validate_output(temp.path())
.expect_err("missing initializer must fail")
.to_string()
.contains("WASM initializer is missing")
);
let mut manifest = write_valid_output(temp.path());
manifest.wasm[0].preloads[0].url = "/app/preload-123.js".to_owned();
std::fs::write(temp.path().join("preload-123.js"), "export default {};")
.expect("write preload");
manifest
.validate_output(temp.path())
.expect("preload is present");
std::fs::remove_file(temp.path().join("preload-123.js")).expect("remove preload");
assert!(
manifest
.validate_output(temp.path())
.expect_err("missing preload must fail")
.to_string()
.contains("WASM preload is missing")
);
}
#[test]
fn rejects_missing_html_and_manifest_urls_outside_public_prefix() {
let temp = tempfile::tempdir().expect("temporary directory");
let manifest = write_valid_output(temp.path());
std::fs::remove_file(temp.path().join("index.html")).expect("remove HTML");
assert!(
manifest
.validate_output(temp.path())
.expect_err("missing HTML must fail")
.to_string()
.contains("missing")
);
let mut wrong_prefix = write_valid_output(temp.path());
wrong_prefix.assets[0].url = "https://other.invalid/site.css".to_owned();
assert!(
wrong_prefix
.validate_output(temp.path())
.expect_err("wrong public URL prefix must fail")
.to_string()
.contains("public URL prefix")
);
}
#[test]
fn asset_urls_require_a_public_prefix_path_boundary() {
let mut manifest =
TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("valid manifest");
for prefix in [
"/app",
"/app/",
"https://cdn.example/app",
"https://cdn.example/app/",
] {
manifest.public_url = prefix.to_owned();
let base = prefix.trim_end_matches('/');
assert_eq!(
manifest
.local_asset_path(&format!("{base}/nested/app.js"))
.expect("matching prefix"),
PathBuf::from("nested/app.js")
);
for suffix in ["le.js", "", "%2fapp.js", "//app.js", "/%2e%2e/app.js"] {
assert!(
manifest
.local_asset_path(&format!("{base}{suffix}"))
.is_err()
);
}
}
manifest.public_url = "/".to_owned();
assert_eq!(
manifest.local_asset_path("/app.js").expect("root prefix"),
PathBuf::from("app.js")
);
}
#[test]
fn output_validation_reports_unresolvable_paths() {
let temp = tempfile::tempdir().expect("temporary directory");
let manifest = write_valid_output(temp.path());
let error = manifest
.validate_output(temp.path().join("missing-dist"))
.expect_err("missing dist must fail")
.to_string();
assert!(
error.contains("failed to resolve Trunk output directory"),
"{error}"
);
let mut through_file = manifest.clone();
through_file.assets[0].url = "/app/index.html/site-123.css".to_owned();
let error = through_file
.validate_output(temp.path())
.expect_err("path through a file must fail")
.to_string();
assert!(error.contains("failed to inspect"), "{error}");
std::fs::create_dir(temp.path().join("folder.css")).expect("directory asset");
let mut directory = manifest;
directory.assets[0].url = "/app/folder.css".to_owned();
let error = directory
.validate_output(temp.path())
.expect_err("directory asset must fail")
.to_string();
assert!(error.contains("is not a file"), "{error}");
}
#[test]
fn output_path_for_url_matches_validation_mapping() {
let manifest = TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("valid manifest");
assert_eq!(
manifest
.output_path_for_url("/app/nested/app-123.js")
.expect("asset under public URL"),
PathBuf::from("nested/app-123.js")
);
for outside in [
"/",
"/app-123.js",
"/apple.js",
"/app//",
"/app/%2e%2e/x",
"/app/x.js?v=1",
] {
assert!(manifest.output_path_for_url(outside).is_err(), "{outside}");
}
}
#[test]
fn output_path_for_url_maps_the_public_root_to_the_html_entry() {
let mut manifest =
TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("valid manifest");
for public_url in ["/app/", "/app"] {
manifest.public_url = public_url.to_owned();
for root in ["/app/", "/app"] {
assert_eq!(
manifest.output_path_for_url(root).expect("public root"),
PathBuf::from("index.html"),
"{public_url} {root}"
);
}
assert!(manifest.output_path_for_url("").is_err());
}
manifest.public_url = "/".to_owned();
assert_eq!(
manifest.output_path_for_url("/").expect("site root"),
PathBuf::from("index.html")
);
assert!(manifest.output_path_for_url("").is_err());
manifest.html = "../escape.html".to_owned();
assert!(manifest.output_path_for_url("/").is_err());
let mut root_asset = TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("valid");
root_asset.assets[0].url = "/app/".to_owned();
let temp = tempfile::tempdir().expect("temporary directory");
write_valid_output(temp.path());
assert!(root_asset.validate_output(temp.path()).is_err());
}
#[test]
#[cfg(unix)]
fn rejects_output_files_that_escape_dist_through_symlinks() {
use std::os::unix::fs::symlink;
let outside = tempfile::tempdir().expect("outside directory");
for name in [
"index.html",
"site-123.css",
"app-123.js",
"app-123_bg.wasm",
] {
let temp = tempfile::tempdir().expect("temporary directory");
let manifest = write_valid_output(temp.path());
let target = outside.path().join(name);
std::fs::rename(temp.path().join(name), &target).expect("move file outside dist");
symlink(&target, temp.path().join(name)).expect("link outside dist");
assert!(
manifest
.validate_output(temp.path())
.expect_err("escaping symlink must fail")
.to_string()
.contains("escapes the Trunk output directory through a symbolic link"),
"{name}"
);
}
let temp = tempfile::tempdir().expect("temporary directory");
let manifest = write_valid_output(temp.path());
std::fs::create_dir(outside.path().join("dir")).expect("outside directory");
std::fs::rename(
temp.path().join("site-123.css"),
outside.path().join("dir/site-123.css"),
)
.expect("move CSS outside dist");
let mut nested = manifest;
nested.assets[0].url = "/app/linked/site-123.css".to_owned();
symlink(outside.path().join("dir"), temp.path().join("linked")).expect("link directory");
assert!(
nested
.validate_output(temp.path())
.expect_err("escaping directory symlink must fail")
.to_string()
.contains("escapes the Trunk output directory")
);
let temp = tempfile::tempdir().expect("temporary directory");
let manifest = write_valid_output(temp.path());
std::fs::create_dir(temp.path().join("real")).expect("inner directory");
std::fs::rename(
temp.path().join("site-123.css"),
temp.path().join("real/site-123.css"),
)
.expect("move CSS inside dist");
symlink("real/site-123.css", temp.path().join("site-123.css")).expect("inner link");
manifest
.validate_output(temp.path())
.expect("symlinks that stay inside dist are accepted");
let linked_root = tempfile::tempdir().expect("link parent");
let linked_dist = linked_root.path().join("dist");
symlink(temp.path(), &linked_dist).expect("link dist root");
manifest
.validate_output(&linked_dist)
.expect("a symlinked dist root is resolved before containment checks");
}
#[test]
#[cfg(unix)]
fn resolve_output_file_serves_only_real_files_inside_dist() {
use std::os::unix::fs::symlink;
let temp = tempfile::tempdir().expect("temporary directory");
let manifest = write_valid_output(temp.path());
let root = temp.path().canonicalize().expect("canonical dist");
assert_eq!(
manifest
.resolve_output_file(temp.path(), "/app/app-123.js")
.expect("listed asset"),
root.join("app-123.js")
);
assert_eq!(
manifest
.resolve_output_file(temp.path(), "/app/")
.expect("public root"),
root.join("index.html")
);
let outside = tempfile::tempdir().expect("outside directory");
std::fs::write(outside.path().join("secret.txt"), "secret").expect("outside file");
symlink(
outside.path().join("secret.txt"),
temp.path().join("unlisted.txt"),
)
.expect("unlisted symlink outside dist");
assert!(
manifest
.resolve_output_file(temp.path(), "/app/unlisted.txt")
.expect_err("unlisted escaping symlink must fail")
.to_string()
.contains("escapes the Trunk output directory")
);
for rejected in ["/app/missing.js", "/app/../secret.txt", "/elsewhere.js"] {
assert!(
manifest.resolve_output_file(temp.path(), rejected).is_err(),
"{rejected}"
);
}
assert!(
manifest
.resolve_output_file(temp.path().join("missing"), "/app/app-123.js")
.is_err()
);
}
#[test]
fn public_url_must_be_root_relative_or_http() {
for accepted in [
"/",
"/app/",
"/app",
"https://cdn.example.com/app/",
"HTTP://cdn.example.com",
] {
let mut value = manifest_value();
value["public_url"] = accepted.into();
for asset in value["assets"].as_array_mut().expect("assets") {
asset["url"] = format!("{}/x.css", accepted.trim_end_matches('/')).into();
}
value["wasm"] = serde_json::json!([]);
let result = TrunkAssetManifest::from_json(value.to_string().as_bytes());
assert!(result.is_ok(), "{accepted}: {:?}", result.err());
}
for rejected in [
"javascript:alert(1)//",
"data:text/html,x/",
"app/",
"//evil.example/",
"https:///app/",
"https://",
"/app\\x/",
"/a b/",
"/a\"x/",
"/<x>/",
] {
let mut value = manifest_value();
value["public_url"] = rejected.into();
assert_manifest_error(&value, "must be a root-relative path or an http(s) URL");
}
let mut asset = manifest_value();
asset["assets"][0]["url"] = "javascript:alert(1)".into();
assert_manifest_error(&asset, "does not use manifest public URL prefix");
let mut preload = manifest_value();
preload["wasm"][0]["preloads"][0]["url"] = "https://evil.example/app/x.js".into();
assert_manifest_error(&preload, "does not use manifest public URL prefix");
}
#[test]
fn rejects_non_file_html_and_missing_wasm_runtime_files() {
let temp = tempfile::tempdir().expect("temporary directory");
let manifest = write_valid_output(temp.path());
std::fs::remove_file(temp.path().join("index.html")).expect("remove HTML file");
std::fs::create_dir(temp.path().join("index.html")).expect("create HTML directory");
assert!(
manifest
.validate_output(temp.path())
.expect_err("HTML output must be a file")
.to_string()
.contains("HTML output is not a file")
);
let temp = tempfile::tempdir().expect("temporary directory");
let mut manifest = write_valid_output(temp.path());
manifest.assets.retain(|asset| asset.role != "script");
std::fs::remove_file(temp.path().join("app-123.js")).expect("remove JS loader");
assert!(
manifest
.validate_output(temp.path())
.expect_err("WASM JavaScript loader must exist")
.to_string()
.contains("WASM JavaScript loader is missing")
);
let temp = tempfile::tempdir().expect("temporary directory");
let mut manifest = write_valid_output(temp.path());
manifest.assets.retain(|asset| asset.role != "script");
std::fs::remove_file(temp.path().join("app-123_bg.wasm")).expect("remove WASM module");
assert!(
manifest
.validate_output(temp.path())
.expect_err("WASM module must exist")
.to_string()
.contains("WebAssembly module is missing")
);
}
#[test]
fn validates_current_content_digests_without_sri() {
let temp = tempfile::tempdir().expect("temporary directory");
write_valid_output(temp.path());
let css = b"body { color: red; }";
let js = b"export default {};";
let wasm = vec![0; 1024];
let mut json: serde_json::Value =
serde_json::from_str(MANIFEST).expect("fixture JSON should be valid");
json["assets"][0]["attributes"]
.as_object_mut()
.expect("asset attributes")
.remove("integrity");
json["assets"][0]["content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(css))).into();
json["assets"][1]["content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
json["wasm"][0]["js_content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
json["wasm"][0]["wasm_content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(&wasm))).into();
json["wasm"][0]["initializer_content_digest"] = serde_json::Value::Null;
json["wasm"][0]["preloads"][0]["content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
let json = serde_json::to_vec(&json).expect("serialize current fixture");
let manifest = TrunkAssetManifest::from_json(&json).expect("valid current manifest");
manifest
.validate_output(temp.path())
.expect("content digests validate without SRI");
std::fs::write(temp.path().join("site-123.css"), b"body { color: blue; }")
.expect("replace with same-length CSS");
assert!(
manifest
.validate_output(temp.path())
.expect_err("stale no-SRI asset must fail")
.to_string()
.contains("content digest check failed")
);
}
#[test]
fn validates_current_initializer_and_preload_integrity() {
let temp = tempfile::tempdir().expect("temporary directory");
write_valid_output(temp.path());
let css = b"body { color: red; }";
let js = b"export default {};";
let wasm = vec![0; 1024];
let initializer = b"export function init() {}";
std::fs::write(temp.path().join("init-123.js"), initializer).expect("write initializer");
let mut json = manifest_value();
json["assets"][0]["attributes"]
.as_object_mut()
.expect("asset attributes")
.remove("integrity");
json["assets"][0]["content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(css))).into();
json["assets"][1]["content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
json["wasm"][0]["js_content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
json["wasm"][0]["wasm_content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(&wasm))).into();
json["wasm"][0]["initializer_url"] = "/app/init-123.js".into();
json["wasm"][0]["initializer_content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(initializer))).into();
json["wasm"][0]["preloads"][0]["content_digest"] =
format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
json["wasm"][0]["preloads"][0]["integrity"] =
format!("sha384-{}", STANDARD.encode(Sha384::digest(js))).into();
let bytes = serde_json::to_vec(&json).expect("serialize current manifest");
let manifest = TrunkAssetManifest::from_json(&bytes).expect("valid current manifest");
manifest
.validate_output(temp.path())
.expect("initializer and preload integrity validate");
std::fs::write(temp.path().join("init-123.js"), b"stale initializer")
.expect("replace initializer");
assert!(
manifest
.validate_output(temp.path())
.expect_err("stale initializer must fail")
.to_string()
.contains("content digest check failed")
);
}
#[test]
fn accepts_current_manifest_with_document_assets() {
let mut json = manifest_value();
push_document_asset(
&mut json,
serde_json::json!({"order": 0, "location": "head", "html": "<style>body{}</style>"}),
);
let manifest =
TrunkAssetManifest::from_json(json.to_string().as_bytes()).expect("current manifest");
assert_eq!(manifest.document_assets.len(), 2);
json["assets"][0]
.as_object_mut()
.expect("asset object")
.remove("content_digest");
assert!(
TrunkAssetManifest::from_json(json.to_string().as_bytes())
.expect_err("current manifest requires digest fields")
.to_string()
.contains("content digest")
);
}
#[test]
fn groups_document_assets_by_location_in_trunk_order() {
let mut json = manifest_value();
json["document_assets"] = serde_json::json!([
{"order": 0, "location": "head", "html": "<link rel=\"stylesheet\" href=\"/a-1.css\">"},
{"order": 1, "location": "body", "html": "<span>inline</span>"},
{"order": 2, "location": "head", "html": "<link rel=\"modulepreload\" href=\"/app-2.js\">"},
{"order": 2, "location": "head", "html": "<script type=\"module\" nonce=\"{{__TRUNK NONCE__}}\">init()</script>"}
]);
let assets = TrunkAssetManifest::from_json(json.to_string().as_bytes())
.expect("current manifest")
.document_assets()
.expect("document assets");
assert_eq!(
assets.head_html(),
concat!(
"<link rel=\"stylesheet\" href=\"/a-1.css\">",
"<link rel=\"modulepreload\" href=\"/app-2.js\">",
"<script type=\"module\" nonce=\"{{__TRUNK NONCE__}}\">init()</script>",
)
);
assert_eq!(assets.body_html(), "<span>inline</span>");
}
#[test]
fn rejects_document_assets_without_markup_or_placement() {
let mut json = manifest_value();
push_document_asset(
&mut json,
serde_json::json!({"order": 0, "location": "unknown", "html": "<style></style>"}),
);
let unplaced = TrunkAssetManifest::from_json(json.to_string().as_bytes())
.expect("unknown locations parse");
assert!(
unplaced
.document_assets()
.expect_err("unknown location")
.to_string()
.contains("outside <head> and <body>")
);
for (invalid, expected) in [
(
serde_json::json!({"order": 0, "location": "footer", "html": "<style></style>"}),
"unsupported location `footer`",
),
(
serde_json::json!({"order": 0, "location": "head", "html": " "}),
"empty markup",
),
] {
let mut json = manifest_value();
push_document_asset(&mut json, invalid);
assert_manifest_error(&json, expected);
}
}
#[test]
fn validates_relative_paths_and_digest_formats() {
assert_eq!(
safe_relative_path("assets/%41.js").expect("decode asset path"),
PathBuf::from("assets/A.js")
);
for path in [
"",
"/absolute.js",
"../secret.js",
"bad\\path.js",
"%",
"%2",
"%GG",
"%FF",
] {
assert!(
safe_relative_path(path).is_err(),
"path should be rejected: {path}"
);
}
let manifest = TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("valid manifest");
assert!(
manifest
.local_asset_path("/app/file.js?debug=true")
.is_err()
);
assert!(manifest.local_asset_path("/app/file.js#section").is_err());
let temp = tempfile::tempdir().expect("temporary directory");
let file = temp.path().join("asset.bin");
std::fs::write(&file, b"content").expect("write asset");
let blocked_directory = temp.path().join("not-a-directory");
std::fs::write(&blocked_directory, b"file").expect("write blocking file");
assert!(
require_file(&blocked_directory.join("asset.bin"), "asset")
.expect_err("non-directory parent")
.to_string()
.contains("failed to inspect")
);
let digest = format!("sha512-{}", STANDARD.encode(Sha512::digest(b"content")));
verify_digest(&file, &digest).expect("validate SHA-512 digest");
assert!(verify_digest(&file, "malformed").is_err());
assert!(verify_digest(&file, "sha256-!").is_err());
assert!(
verify_digest(&file, &format!("unknown-{}", STANDARD.encode(b"content")))
.expect_err("unsupported algorithm")
.to_string()
.contains("unsupported asset digest algorithm")
);
assert!(
verify_digest(
&file,
&format!("sha256-{}", STANDARD.encode(Sha256::digest(b"other")))
)
.expect_err("stale digest")
.to_string()
.contains("content digest check failed")
);
assert!(
verify_digest(
&temp.path().join("missing.bin"),
&format!("sha256-{}", STANDARD.encode(Sha256::digest(b"content")))
)
.expect_err("missing digest file")
.to_string()
.contains("failed to read")
);
}
}