Skip to main content

serenade_view/
trunk_assets.rs

1//! Reader for Trunk's `trunk-assets.json` output.
2
3use std::{
4    collections::{BTreeMap, BTreeSet},
5    ffi::OsString,
6    path::{Component, Path, PathBuf},
7};
8
9use base64::{Engine as _, engine::general_purpose::STANDARD};
10use serde::Deserialize;
11use sha2::{Digest, Sha256, Sha384, Sha512};
12
13use crate::{DocumentAssets, ViewError};
14
15/// Filename emitted by Trunk for its build asset manifest.
16pub const TRUNK_ASSET_MANIFEST_FILE: &str = "trunk-assets.json";
17
18/// Environment variable set by Serenade mode commands with the manifest path.
19pub const TRUNK_ASSET_MANIFEST_ENV: &str = "SERENADE_TRUNK_ASSET_MANIFEST";
20
21/// Environment variable set by `serenade-universal` with the frontend output directory.
22pub const TRUNK_DIST_DIRECTORY_ENV: &str = "SERENADE_TRUNK_DIST_DIR";
23
24/// Assets produced by Trunk for one frontend build.
25#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
26pub struct TrunkAssetManifest {
27    /// Configured public URL prefix.
28    pub public_url: String,
29    /// Finalized HTML output filename.
30    pub html: String,
31    /// External assets in source HTML order.
32    pub assets: Vec<TrunkAssetReference>,
33    /// Rust/WASM bundles; empty when the application has no Rust frontend.
34    pub wasm: Vec<TrunkWasmBundle>,
35    /// Exact markup Trunk generated into its HTML output.
36    pub document_assets: Vec<TrunkDocumentAsset>,
37}
38
39/// Markup generated by one Trunk asset pipeline, as written to Trunk's HTML.
40#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
41pub struct TrunkDocumentAsset {
42    /// Source HTML order, absent for Trunk's implicit Cargo application.
43    pub order: Option<usize>,
44    /// Where Trunk inserted the markup: `head`, `body`, or `unknown`.
45    pub location: String,
46    /// Exact generated markup, including hashed URLs, SRI and nonce placeholders.
47    pub html: String,
48}
49
50/// One external asset emitted by Trunk.
51#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
52pub struct TrunkAssetReference {
53    /// Source HTML order.
54    pub order: usize,
55    /// Asset role (`stylesheet`, `script`, or `icon`).
56    pub role: String,
57    /// Exact public URL.
58    pub url: String,
59    /// SHA-256 content digest emitted by the current manifest schema.
60    pub content_digest: Option<String>,
61    /// Attributes emitted for this asset, excluding its URL attribute.
62    pub attributes: BTreeMap<String, String>,
63}
64
65/// Rust/WASM runtime bundle and initialization information.
66#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
67pub struct TrunkWasmBundle {
68    /// `main` or `worker`.
69    pub app_type: String,
70    /// Source HTML order, absent for Trunk's implicit Cargo application.
71    pub order: Option<usize>,
72    /// Exact wasm-bindgen JavaScript module URL.
73    pub js_url: String,
74    /// SHA-256 content digest emitted by the current manifest schema.
75    pub js_content_digest: Option<String>,
76    /// Exact WebAssembly module URL.
77    pub wasm_url: String,
78    /// SHA-256 content digest emitted by the current manifest schema.
79    pub wasm_content_digest: Option<String>,
80    /// WebAssembly module size in bytes.
81    pub wasm_size: u64,
82    /// Optional custom initializer module URL.
83    pub initializer_url: Option<String>,
84    /// SHA-256 content digest emitted for an initializer by the current manifest schema.
85    pub initializer_content_digest: Option<String>,
86    /// Whether the wasm-bindgen initializer expects a `module_or_path` object.
87    pub init_with_object: bool,
88    /// Whether Rust exports are imported into the initializer.
89    pub import_bindings: bool,
90    /// Optional global variable name for imported bindings.
91    pub import_bindings_name: Option<String>,
92    /// Optional decompression algorithm.
93    pub compression_algorithm: Option<String>,
94    /// Cross-origin mode used for loading resources.
95    pub cross_origin: String,
96    /// Whether Trunk injects the initializer into its HTML.
97    pub inject_scripts: bool,
98    /// Optional Trunk initializer template.
99    pub custom_script_pattern: Option<String>,
100    /// Optional Trunk preload template.
101    pub custom_preload_pattern: Option<String>,
102    /// Parameters available to Trunk's custom templates.
103    pub pattern_parameters: BTreeMap<String, String>,
104    /// Preload references generated by Trunk's SRI pipeline.
105    pub preloads: Vec<TrunkPreloadReference>,
106}
107
108/// One preload generated for a Rust/WASM bundle.
109#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
110pub struct TrunkPreloadReference {
111    /// `preload` or `modulepreload`.
112    pub rel: String,
113    /// Exact public URL.
114    pub url: String,
115    /// SHA-256 content digest emitted by the current manifest schema.
116    pub content_digest: Option<String>,
117    /// `crossorigin` attribute value.
118    pub cross_origin: String,
119    /// SRI value when enabled.
120    pub integrity: Option<String>,
121    /// Optional preload `as` attribute.
122    #[serde(rename = "as")]
123    pub as_type: Option<String>,
124    /// Optional preload `type` attribute.
125    #[serde(rename = "type")]
126    pub media_type: Option<String>,
127}
128
129impl TrunkAssetManifest {
130    /// Reads the manifest path supplied by a Serenade mode command.
131    ///
132    /// Call once during application startup, not once per request.
133    ///
134    /// # Errors
135    ///
136    /// Returns an error when the environment variable is missing or the
137    /// manifest is missing, malformed, or incompatible.
138    pub fn read_from_env() -> Result<Self, ViewError> {
139        Self::read_from_environment(std::env::var_os(TRUNK_ASSET_MANIFEST_ENV))
140    }
141
142    fn read_from_environment(path: Option<OsString>) -> Result<Self, ViewError> {
143        let path = path.ok_or_else(|| {
144            ViewError::msg(format!(
145                "environment variable {TRUNK_ASSET_MANIFEST_ENV} is not set"
146            ))
147        })?;
148        Self::read(path)
149    }
150
151    /// Reads and validates the manifest once, suitable for build/startup use.
152    ///
153    /// # Errors
154    ///
155    /// Returns an error when the file is missing, malformed, incompatible, or
156    /// contains invalid asset references.
157    pub fn read(path: impl AsRef<Path>) -> Result<Self, ViewError> {
158        let path = path.as_ref();
159        let contents = std::fs::read(path).map_err(|error| {
160            ViewError::msg(format!("failed to read {}: {error}", path.display()))
161        })?;
162        let manifest: Self = serde_json::from_slice(&contents)
163            .map_err(|error| ViewError::msg(format!("invalid Trunk asset manifest: {error}")))?;
164        manifest.validate()?;
165        Ok(manifest)
166    }
167
168    /// Parses and validates Trunk manifest JSON bytes.
169    ///
170    /// # Errors
171    ///
172    /// Returns an error for malformed or incompatible manifests.
173    pub fn from_json(contents: &[u8]) -> Result<Self, ViewError> {
174        let manifest: Self = serde_json::from_slice(contents)
175            .map_err(|error| ViewError::msg(format!("invalid Trunk asset manifest: {error}")))?;
176        manifest.validate()?;
177        Ok(manifest)
178    }
179
180    fn validate(&self) -> Result<(), ViewError> {
181        if self.public_url.trim().is_empty() {
182            return Err(ViewError::msg(
183                "Trunk asset manifest has an empty public URL prefix",
184            ));
185        }
186        validate_public_url(&self.public_url)?;
187        if self.html.trim().is_empty() {
188            return Err(ViewError::msg(
189                "Trunk asset manifest has an empty HTML output filename",
190            ));
191        }
192
193        let mut previous_order = None;
194        for asset in &self.assets {
195            if !matches!(asset.role.as_str(), "stylesheet" | "script" | "icon") {
196                return Err(ViewError::msg(format!(
197                    "unsupported Trunk asset role `{}`",
198                    asset.role
199                )));
200            }
201            if asset.url.trim().is_empty() {
202                return Err(ViewError::msg(format!(
203                    "Trunk {} asset at order {} has an empty URL",
204                    asset.role, asset.order
205                )));
206            }
207            if asset.content_digest.is_none() {
208                return Err(ViewError::msg(format!(
209                    "Trunk {} asset `{}` is missing its content digest",
210                    asset.role, asset.url
211                )));
212            }
213            if previous_order.is_some_and(|order| asset.order <= order) {
214                return Err(ViewError::msg(
215                    "Trunk asset manifest entries are not in strictly increasing source order",
216                ));
217            }
218            previous_order = Some(asset.order);
219        }
220
221        let mut wasm_orders = BTreeSet::new();
222        for bundle in &self.wasm {
223            if !matches!(bundle.app_type.as_str(), "main" | "worker") {
224                return Err(ViewError::msg(format!(
225                    "unsupported Trunk WASM application type `{}`",
226                    bundle.app_type
227                )));
228            }
229            if bundle.js_url.trim().is_empty() || bundle.wasm_url.trim().is_empty() {
230                return Err(ViewError::msg(
231                    "Trunk WASM bundle has an empty JavaScript or WebAssembly URL",
232                ));
233            }
234            if bundle.js_content_digest.is_none()
235                || bundle.wasm_content_digest.is_none()
236                || bundle.initializer_url.is_some() != bundle.initializer_content_digest.is_some()
237            {
238                return Err(ViewError::msg(
239                    "Trunk WASM bundle is missing a content digest",
240                ));
241            }
242            if bundle.order.is_some_and(|order| !wasm_orders.insert(order)) {
243                return Err(ViewError::msg(
244                    "Trunk WASM bundles have duplicate source order values",
245                ));
246            }
247            for preload in &bundle.preloads {
248                if !matches!(preload.rel.as_str(), "preload" | "modulepreload")
249                    || preload.url.trim().is_empty()
250                {
251                    return Err(ViewError::msg(
252                        "Trunk WASM bundle contains an invalid preload reference",
253                    ));
254                }
255                if preload.content_digest.is_none() {
256                    return Err(ViewError::msg(format!(
257                        "Trunk preload `{}` is missing its content digest",
258                        preload.url
259                    )));
260                }
261            }
262        }
263        self.validate_document_assets()?;
264        self.validate_url_prefixes()
265    }
266
267    fn validate_document_assets(&self) -> Result<(), ViewError> {
268        for asset in &self.document_assets {
269            if !matches!(asset.location.as_str(), "head" | "body" | "unknown") {
270                return Err(ViewError::msg(format!(
271                    "Trunk document asset has unsupported location `{}`",
272                    asset.location
273                )));
274            }
275            if asset.html.trim().is_empty() {
276                return Err(ViewError::msg("Trunk document asset has empty markup"));
277            }
278        }
279        // Trunk tags a main bundle's injected loader with the bundle's own source order.
280        for bundle in &self.wasm {
281            if bundle.app_type == "main"
282                && bundle.inject_scripts
283                && !self
284                    .document_assets
285                    .iter()
286                    .any(|asset| asset.order == bundle.order && asset.html.contains("<script"))
287            {
288                return Err(ViewError::msg(format!(
289                    "Trunk manifest has no generated loader script for WASM bundle `{}`",
290                    bundle.js_url
291                )));
292            }
293        }
294        Ok(())
295    }
296
297    /// Returns the exact markup Trunk generated for the document, grouped by
298    /// head and body in Trunk's order, ready for [`Document::with_assets`].
299    ///
300    /// This includes stylesheets, scripts, icons, inline assets, preloads and
301    /// the WASM bootstrap, with hashed URLs, SRI attributes and nonce
302    /// placeholders exactly as Trunk wrote them. Call once at startup.
303    ///
304    /// [`Document::with_assets`]: crate::Document::with_assets
305    ///
306    /// # Errors
307    ///
308    /// Returns an error for markup Trunk inserted outside the document head
309    /// or body.
310    pub fn document_assets(&self) -> Result<DocumentAssets, ViewError> {
311        let (mut head, mut body) = (String::new(), String::new());
312        for asset in &self.document_assets {
313            match asset.location.as_str() {
314                "head" => head.push_str(&asset.html),
315                "body" => body.push_str(&asset.html),
316                _ => {
317                    return Err(ViewError::msg(format!(
318                        "Trunk inserted document asset markup outside <head> and <body>: {}",
319                        asset.html
320                    )));
321                }
322            }
323        }
324        Ok(DocumentAssets::new(head, body))
325    }
326
327    /// Requires every referenced URL to sit under `public_url`, so parsed manifests
328    /// never carry another scheme or origin even before output validation.
329    fn validate_url_prefixes(&self) -> Result<(), ViewError> {
330        let urls = self
331            .assets
332            .iter()
333            .map(|asset| &asset.url)
334            .chain(self.wasm.iter().flat_map(|bundle| {
335                [&bundle.js_url, &bundle.wasm_url]
336                    .into_iter()
337                    .chain(&bundle.initializer_url)
338                    .chain(bundle.preloads.iter().map(|preload| &preload.url))
339            }));
340        for url in urls {
341            self.local_asset_path(url)?;
342        }
343        Ok(())
344    }
345
346    /// Validates that every local output referenced by the manifest exists and
347    /// matches its declared size and enabled SRI digests.
348    ///
349    /// # Errors
350    ///
351    /// Returns an error when a reference escapes the output directory, an
352    /// artifact is missing or stale, or an integrity digest does not match.
353    pub fn validate_output(&self, dist: impl AsRef<Path>) -> Result<(), ViewError> {
354        let root = canonical_output_root(dist.as_ref())?;
355        let html_path = safe_relative_path(&self.html)?;
356        contained_file(&root, &html_path, "HTML output")?;
357
358        for asset in &self.assets {
359            let path = self.local_asset_path(&asset.url)?;
360            let (file, _) = contained_file(
361                &root,
362                &path,
363                &format!("{} asset `{}`", asset.role, asset.url),
364            )?;
365            let integrity = asset.attributes.get("integrity");
366            verify_digests(&file, asset.content_digest.iter().chain(integrity))?;
367        }
368
369        for bundle in &self.wasm {
370            let js_path = self.local_asset_path(&bundle.js_url)?;
371            let (js_file, _) = contained_file(&root, &js_path, "WASM JavaScript loader")?;
372            verify_digests(&js_file, &bundle.js_content_digest)?;
373            let wasm_path = self.local_asset_path(&bundle.wasm_url)?;
374            let (wasm_file, wasm_metadata) =
375                contained_file(&root, &wasm_path, "WebAssembly module")?;
376            verify_digests(&wasm_file, &bundle.wasm_content_digest)?;
377            let actual_size = wasm_metadata.len();
378            if actual_size != bundle.wasm_size {
379                return Err(ViewError::msg(format!(
380                    "stale WebAssembly module `{}`: manifest size is {} bytes, file size is {actual_size} bytes",
381                    bundle.wasm_url, bundle.wasm_size
382                )));
383            }
384            if let Some(initializer_url) = &bundle.initializer_url {
385                let path = self.local_asset_path(initializer_url)?;
386                let (file, _) = contained_file(&root, &path, "WASM initializer")?;
387                verify_digests(&file, &bundle.initializer_content_digest)?;
388            }
389            for preload in &bundle.preloads {
390                let path = self.local_asset_path(&preload.url)?;
391                let (file, _) = contained_file(&root, &path, "WASM preload")?;
392                verify_digests(
393                    &file,
394                    preload.content_digest.iter().chain(&preload.integrity),
395                )?;
396            }
397        }
398
399        Ok(())
400    }
401
402    /// Resolves a public URL or request path to the real file it names inside
403    /// the Trunk output directory, for servers that host the output themselves.
404    ///
405    /// Applies [`Self::output_path_for_url`], then follows symbolic links and
406    /// rejects any file whose real location is outside `dist`, including files
407    /// that the manifest does not reference.
408    ///
409    /// # Errors
410    ///
411    /// Returns an error when the URL is not under the public URL, the file is
412    /// missing or not a regular file, or it resolves outside `dist`.
413    pub fn resolve_output_file(
414        &self,
415        dist: impl AsRef<Path>,
416        url: &str,
417    ) -> Result<PathBuf, ViewError> {
418        let relative = self.output_path_for_url(url)?;
419        let root = canonical_output_root(dist.as_ref())?;
420        let (file, _) = contained_file(&root, &relative, &format!("output file for `{url}`"))?;
421        Ok(file)
422    }
423
424    /// Maps a public asset URL or request path to its path relative to the
425    /// Trunk output directory, using the same rules as [`Self::validate_output`].
426    ///
427    /// Servers must use this instead of joining the raw request path onto the
428    /// output directory: with a non-root `public_url` such as `/app/`, the URL
429    /// `/app/app.js` is the output file `app.js`. The public URL root itself,
430    /// with or without its trailing slash (`/app/` or `/app`), is the HTML
431    /// entry point named by [`Self::html`].
432    ///
433    /// # Errors
434    ///
435    /// Returns an error when the URL is not under `public_url` at a path
436    /// boundary, has a query or fragment, or escapes the output directory.
437    pub fn output_path_for_url(&self, url: &str) -> Result<PathBuf, ViewError> {
438        let root = self.public_url.trim_end_matches('/');
439        if url
440            .strip_prefix(root)
441            .is_some_and(|rest| rest.is_empty() || rest == "/")
442            && !url.is_empty()
443        {
444            return safe_relative_path(&self.html);
445        }
446        self.local_asset_path(url)
447    }
448
449    fn local_asset_path(&self, url: &str) -> Result<PathBuf, ViewError> {
450        let relative = url
451            .strip_prefix(&self.public_url)
452            .and_then(|relative| {
453                if self.public_url.ends_with('/') {
454                    Some(relative)
455                } else {
456                    relative.strip_prefix('/')
457                }
458            })
459            .ok_or_else(|| {
460                ViewError::msg(format!(
461                    "asset URL `{url}` does not use manifest public URL prefix `{}`",
462                    self.public_url
463                ))
464            })?;
465        if relative.contains(['?', '#']) {
466            return Err(ViewError::msg(format!(
467                "asset URL `{url}` contains an unsupported query or fragment"
468            )));
469        }
470        safe_relative_path(relative)
471    }
472}
473
474fn safe_relative_path(path: &str) -> Result<PathBuf, ViewError> {
475    let decoded = percent_decode(path)?;
476    if decoded.is_empty() || decoded.contains('\\') {
477        return Err(ViewError::msg(format!(
478            "invalid relative asset path `{path}`"
479        )));
480    }
481    let path_buf = PathBuf::from(&decoded);
482    if path_buf.is_absolute()
483        || path_buf
484            .components()
485            .any(|component| !matches!(component, Component::Normal(_)))
486    {
487        return Err(ViewError::msg(format!(
488            "asset path `{path}` escapes the Trunk output directory"
489        )));
490    }
491    Ok(path_buf)
492}
493
494fn percent_decode(path: &str) -> Result<String, ViewError> {
495    let bytes = path.as_bytes();
496    let mut decoded = Vec::with_capacity(bytes.len());
497    let mut index = 0;
498    while index < bytes.len() {
499        if bytes[index] == b'%' {
500            if index + 2 >= bytes.len() {
501                return Err(ViewError::msg(format!(
502                    "malformed percent escape in asset path `{path}`"
503                )));
504            }
505            let high = hex_digit(bytes[index + 1]);
506            let low = hex_digit(bytes[index + 2]);
507            let (Some(high), Some(low)) = (high, low) else {
508                return Err(ViewError::msg(format!(
509                    "malformed percent escape in asset path `{path}`"
510                )));
511            };
512            decoded.push((high << 4) | low);
513            index += 3;
514        } else {
515            decoded.push(bytes[index]);
516            index += 1;
517        }
518    }
519    String::from_utf8(decoded)
520        .map_err(|_| ViewError::msg(format!("asset path `{path}` is not valid UTF-8")))
521}
522
523const fn hex_digit(byte: u8) -> Option<u8> {
524    match byte {
525        b'0'..=b'9' => Some(byte - b'0'),
526        b'a'..=b'f' => Some(byte - b'a' + 10),
527        b'A'..=b'F' => Some(byte - b'A' + 10),
528        _ => None,
529    }
530}
531
532fn canonical_output_root(dist: &Path) -> Result<PathBuf, ViewError> {
533    dist.canonicalize().map_err(|error| {
534        ViewError::msg(format!(
535            "failed to resolve Trunk output directory {}: {error}",
536            dist.display()
537        ))
538    })
539}
540
541/// Accepts only a root-relative path (`/` or `/app/`) or an absolute `http`/`https`
542/// URL, because the value prefixes every URL that callers emit into HTML.
543fn validate_public_url(public_url: &str) -> Result<(), ViewError> {
544    let lower = public_url.to_ascii_lowercase();
545    let after_scheme = lower
546        .strip_prefix("https://")
547        .or_else(|| lower.strip_prefix("http://"));
548    let allowed_form = after_scheme.map_or_else(
549        || public_url.starts_with('/') && !public_url.starts_with("//"),
550        |rest| !rest.is_empty() && !rest.starts_with('/'),
551    );
552    let allowed_characters = public_url
553        .chars()
554        .all(|character| character.is_ascii_graphic() && !"\\\"'<>`".contains(character));
555    if allowed_form && allowed_characters {
556        Ok(())
557    } else {
558        Err(ViewError::msg(format!(
559            "Trunk asset manifest public URL `{public_url}` must be a root-relative path or an http(s) URL"
560        )))
561    }
562}
563
564/// Resolves `relative` under the canonical output `root`, following symlinks,
565/// and rejects files whose real location is outside that root.
566fn contained_file(
567    root: &Path,
568    relative: &Path,
569    description: &str,
570) -> Result<(PathBuf, std::fs::Metadata), ViewError> {
571    let path = root.join(relative);
572    let resolved = path
573        .canonicalize()
574        .map_err(|error| file_error(&path, description, &error))?;
575    if !resolved.starts_with(root) {
576        return Err(ViewError::msg(format!(
577            "{description} {} escapes the Trunk output directory through a symbolic link",
578            path.display()
579        )));
580    }
581    let metadata = require_file(&resolved, description)?;
582    Ok((resolved, metadata))
583}
584
585fn require_file(path: &Path, description: &str) -> Result<std::fs::Metadata, ViewError> {
586    match std::fs::metadata(path) {
587        Ok(metadata) if metadata.is_file() => Ok(metadata),
588        Ok(_) => Err(ViewError::msg(format!(
589            "{description} is not a file: {}",
590            path.display()
591        ))),
592        Err(error) => Err(file_error(path, description, &error)),
593    }
594}
595
596fn file_error(path: &Path, description: &str, error: &std::io::Error) -> ViewError {
597    if error.kind() == std::io::ErrorKind::NotFound {
598        ViewError::msg(format!("{description} is missing: {}", path.display()))
599    } else {
600        ViewError::msg(format!(
601            "failed to inspect {description} {}: {error}",
602            path.display()
603        ))
604    }
605}
606
607fn verify_digests<'a>(
608    path: &Path,
609    digests: impl IntoIterator<Item = &'a String>,
610) -> Result<(), ViewError> {
611    digests
612        .into_iter()
613        .try_for_each(|digest| verify_digest(path, digest))
614}
615
616fn verify_digest(path: &Path, digest: &str) -> Result<(), ViewError> {
617    let (algorithm, expected) = digest
618        .split_once('-')
619        .ok_or_else(|| ViewError::msg(format!("malformed asset digest `{digest}`")))?;
620    let expected = STANDARD
621        .decode(expected)
622        .map_err(|error| ViewError::msg(format!("malformed asset digest: {error}")))?;
623    let contents = std::fs::read(path)
624        .map_err(|error| ViewError::msg(format!("failed to read {}: {error}", path.display())))?;
625    let actual = match algorithm {
626        "sha256" => Sha256::digest(contents).to_vec(),
627        "sha384" => Sha384::digest(contents).to_vec(),
628        "sha512" => Sha512::digest(contents).to_vec(),
629        _ => {
630            return Err(ViewError::msg(format!(
631                "unsupported asset digest algorithm `{algorithm}`"
632            )));
633        }
634    };
635    if actual != expected {
636        return Err(ViewError::msg(format!(
637            "stale asset {}: content digest check failed",
638            path.display()
639        )));
640    }
641    Ok(())
642}
643
644#[cfg(test)]
645mod tests {
646    use super::*;
647    use base64::engine::general_purpose::STANDARD;
648    use sha2::{Digest, Sha384};
649
650    const MANIFEST: &str = r#"{
651        "public_url": "/app/",
652        "html": "index.html",
653        "assets": [
654            {
655                "order": 1,
656                "role": "stylesheet",
657                "url": "/app/site-123.css",
658                "content_digest": "sha256-ZGlnZXN0",
659                "attributes": {"integrity": "sha384-example"}
660            },
661            {
662                "order": 3,
663                "role": "script",
664                "url": "/app/app-123.js",
665                "content_digest": "sha256-ZGlnZXN0",
666                "attributes": {"type": "module"}
667            }
668        ],
669        "wasm": [
670            {
671                "app_type": "main",
672                "order": 2,
673                "js_url": "/app/app-123.js",
674                "js_content_digest": "sha256-ZGlnZXN0",
675                "wasm_url": "/app/app-123_bg.wasm",
676                "wasm_content_digest": "sha256-ZGlnZXN0",
677                "wasm_size": 1024,
678                "initializer_url": null,
679                "initializer_content_digest": null,
680                "init_with_object": true,
681                "import_bindings": false,
682                "import_bindings_name": null,
683                "compression_algorithm": null,
684                "cross_origin": "anonymous",
685                "inject_scripts": true,
686                "custom_script_pattern": null,
687                "custom_preload_pattern": null,
688                "pattern_parameters": {},
689                "preloads": [
690                    {
691                        "rel": "modulepreload",
692                        "url": "/app/app-123.js",
693                        "content_digest": "sha256-ZGlnZXN0",
694                        "cross_origin": "anonymous",
695                        "integrity": null,
696                        "as": null,
697                        "type": null
698                    }
699                ]
700            }
701        ],
702        "document_assets": [
703            {
704                "order": 2,
705                "location": "head",
706                "html": "<script type=\"module\">import init from '/app/app-123.js';await init();</script>"
707            }
708        ]
709    }"#;
710
711    fn manifest_value() -> serde_json::Value {
712        serde_json::from_str(MANIFEST).expect("fixture JSON should be valid")
713    }
714
715    fn push_document_asset(json: &mut serde_json::Value, asset: serde_json::Value) {
716        json["document_assets"]
717            .as_array_mut()
718            .expect("document assets array")
719            .push(asset);
720    }
721
722    fn assert_manifest_error(json: &serde_json::Value, expected: &str) {
723        let bytes = serde_json::to_vec(json).expect("serialize manifest");
724        let error = TrunkAssetManifest::from_json(&bytes)
725            .expect_err("manifest should be rejected")
726            .to_string();
727        assert!(error.contains(expected), "{error}");
728    }
729
730    #[test]
731    fn reads_current_asset_and_wasm_metadata() {
732        let manifest = TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("valid manifest");
733        assert_eq!(manifest.assets[0].role, "stylesheet");
734        assert_eq!(manifest.assets[0].url, "/app/site-123.css");
735        assert_eq!(manifest.wasm[0].wasm_url, "/app/app-123_bg.wasm");
736        assert_eq!(manifest.wasm[0].preloads[0].rel, "modulepreload");
737        assert_eq!(manifest.wasm[0].preloads[0].as_type, None);
738    }
739
740    #[test]
741    fn supports_html_only_manifests() {
742        let json = br#"{
743            "public_url": "/",
744            "html": "index.html",
745            "assets": [],
746            "wasm": [],
747            "document_assets": []
748        }"#;
749        let manifest = TrunkAssetManifest::from_json(json).expect("HTML-only manifest");
750        assert_eq!(manifest.assets, Vec::<TrunkAssetReference>::new());
751        assert_eq!(manifest.wasm, Vec::<TrunkWasmBundle>::new());
752    }
753
754    #[test]
755    fn reads_manifest_files_and_environment_values() {
756        let temp = tempfile::tempdir().expect("temporary directory");
757        let path = temp.path().join(TRUNK_ASSET_MANIFEST_FILE);
758        std::fs::write(&path, MANIFEST).expect("write manifest");
759        let from_file = TrunkAssetManifest::read(&path).expect("read manifest");
760        assert_eq!(
761            from_file,
762            TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("parse manifest")
763        );
764        assert_eq!(
765            TrunkAssetManifest::read_from_environment(Some(path.clone().into_os_string()))
766                .expect("read environment manifest"),
767            from_file
768        );
769        assert!(
770            TrunkAssetManifest::read_from_environment(None)
771                .expect_err("missing manifest path")
772                .to_string()
773                .contains("environment variable")
774        );
775
776        let missing = temp.path().join("missing.json");
777        assert!(
778            TrunkAssetManifest::read(&missing)
779                .expect_err("missing file")
780                .to_string()
781                .contains("failed to read")
782        );
783
784        std::fs::write(&path, b"{").expect("write malformed manifest");
785        assert!(
786            TrunkAssetManifest::read(&path)
787                .expect_err("malformed file")
788                .to_string()
789                .contains("invalid Trunk asset manifest")
790        );
791
792        let configured_path = std::env::var_os(TRUNK_ASSET_MANIFEST_ENV);
793        assert_eq!(
794            TrunkAssetManifest::read_from_env().is_ok(),
795            TrunkAssetManifest::read_from_environment(configured_path).is_ok()
796        );
797    }
798
799    #[test]
800    fn rejects_an_injected_main_bundle_without_its_generated_loader() {
801        let mut json = manifest_value();
802        json["document_assets"] = serde_json::json!([]);
803        assert_manifest_error(
804            &json,
805            "no generated loader script for WASM bundle `/app/app-123.js`",
806        );
807
808        let mut other_order = manifest_value();
809        other_order["document_assets"][0]["order"] = 7.into();
810        assert_manifest_error(&other_order, "no generated loader script");
811
812        let mut not_a_script = manifest_value();
813        not_a_script["document_assets"][0]["html"] =
814            r#"<link rel="modulepreload" href="/app/app-123.js">"#.into();
815        assert_manifest_error(&not_a_script, "no generated loader script");
816
817        for (field, value) in [
818            ("inject_scripts", false.into()),
819            ("app_type", "worker".into()),
820        ] {
821            let mut json = manifest_value();
822            json["document_assets"] = serde_json::json!([]);
823            json["wasm"][0][field] = value;
824            let result = TrunkAssetManifest::from_json(json.to_string().as_bytes());
825            assert!(result.is_ok(), "{field}: {result:?}");
826        }
827    }
828
829    #[test]
830    fn ignores_the_version_and_unknown_fields_trunk_writes() {
831        let expected = TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("manifest");
832        let mut json = manifest_value();
833        json.as_object_mut()
834            .expect("manifest object")
835            .remove("version");
836        json["future_field"] = "ignored".into();
837        assert_eq!(
838            TrunkAssetManifest::from_json(json.to_string().as_bytes()).expect("no version"),
839            expected
840        );
841        json["version"] = "anything".into();
842        assert_eq!(
843            TrunkAssetManifest::from_json(json.to_string().as_bytes()).expect("any version"),
844            expected
845        );
846    }
847
848    #[test]
849    fn rejects_missing_or_invalid_document_assets() {
850        let mut json = manifest_value();
851        json.as_object_mut()
852            .expect("manifest object")
853            .remove("document_assets");
854        assert_manifest_error(&json, "missing field `document_assets`");
855
856        json["document_assets"] = serde_json::Value::Null;
857        assert_manifest_error(&json, "invalid type");
858    }
859
860    #[test]
861    fn rejects_malformed_and_out_of_order_manifests() {
862        assert!(TrunkAssetManifest::from_json(b"{").is_err());
863
864        let mut out_of_order = manifest_value();
865        out_of_order["assets"][0]["order"] = 4.into();
866        out_of_order["assets"][1]["order"] = 1.into();
867        assert!(
868            TrunkAssetManifest::from_json(out_of_order.to_string().as_bytes())
869                .expect_err("out-of-order assets")
870                .to_string()
871                .contains("strictly increasing source order")
872        );
873    }
874
875    #[test]
876    fn rejects_empty_manifest_fields_and_invalid_asset_metadata() {
877        let mut invalid = manifest_value();
878        invalid["public_url"] = " ".into();
879        assert_manifest_error(&invalid, "empty public URL prefix");
880
881        let mut invalid = manifest_value();
882        invalid["html"] = "".into();
883        assert_manifest_error(&invalid, "empty HTML output filename");
884
885        let mut invalid = manifest_value();
886        invalid["assets"][0]["role"] = "font".into();
887        assert_manifest_error(&invalid, "unsupported Trunk asset role");
888
889        let mut invalid = manifest_value();
890        invalid["assets"][0]["url"] = "".into();
891        assert_manifest_error(&invalid, "has an empty URL");
892
893        let mut invalid = manifest_value();
894        invalid["wasm"][0]["js_url"] = "".into();
895        assert_manifest_error(&invalid, "empty JavaScript or WebAssembly URL");
896
897        let mut invalid = manifest_value();
898        invalid["wasm"][0]["wasm_url"] = "".into();
899        assert_manifest_error(&invalid, "empty JavaScript or WebAssembly URL");
900
901        let mut invalid = manifest_value();
902        let duplicate_bundle = invalid["wasm"][0].clone();
903        invalid["wasm"]
904            .as_array_mut()
905            .expect("WASM bundles")
906            .push(duplicate_bundle);
907        assert_manifest_error(&invalid, "duplicate source order");
908
909        let mut invalid = manifest_value();
910        invalid["wasm"][0]["preloads"][0]["url"] = "".into();
911        assert_manifest_error(&invalid, "invalid preload reference");
912    }
913
914    #[test]
915    fn rejects_current_manifests_with_missing_or_inconsistent_digests() {
916        let mut invalid = manifest_value();
917        invalid["assets"][0]["content_digest"] = serde_json::Value::Null;
918        assert_manifest_error(&invalid, "missing its content digest");
919
920        let mut invalid = manifest_value();
921        invalid["wasm"][0]["js_content_digest"] = serde_json::Value::Null;
922        assert_manifest_error(&invalid, "WASM bundle is missing a content digest");
923
924        let mut invalid = manifest_value();
925        invalid["wasm"][0]["wasm_content_digest"] = serde_json::Value::Null;
926        assert_manifest_error(&invalid, "WASM bundle is missing a content digest");
927
928        let mut invalid = manifest_value();
929        invalid["wasm"][0]["initializer_url"] = "/app/init.js".into();
930        assert_manifest_error(&invalid, "WASM bundle is missing a content digest");
931
932        let mut invalid = manifest_value();
933        invalid["wasm"][0]["initializer_content_digest"] = "sha256-ZGlnZXN0".into();
934        assert_manifest_error(&invalid, "WASM bundle is missing a content digest");
935
936        let mut invalid = manifest_value();
937        invalid["wasm"][0]["preloads"][0]["content_digest"] = serde_json::Value::Null;
938        assert_manifest_error(&invalid, "missing its content digest");
939    }
940
941    #[test]
942    fn rejects_invalid_wasm_bootstrap_metadata() {
943        let mut invalid_app_type: serde_json::Value =
944            serde_json::from_str(MANIFEST).expect("fixture JSON should be valid");
945        invalid_app_type["wasm"][0]["app_type"] = "module".into();
946        let json = serde_json::to_vec(&invalid_app_type).expect("serialize fixture");
947        assert!(
948            TrunkAssetManifest::from_json(&json)
949                .expect_err("invalid WASM application type")
950                .to_string()
951                .contains("unsupported Trunk WASM application type")
952        );
953
954        let mut invalid_preload: serde_json::Value =
955            serde_json::from_str(MANIFEST).expect("fixture JSON should be valid");
956        invalid_preload["wasm"][0]["preloads"][0]["rel"] = "script".into();
957        let json = serde_json::to_vec(&invalid_preload).expect("serialize fixture");
958        assert!(
959            TrunkAssetManifest::from_json(&json)
960                .expect_err("invalid WASM preload")
961                .to_string()
962                .contains("invalid preload reference")
963        );
964    }
965
966    fn write_valid_output(dist: &Path) -> TrunkAssetManifest {
967        std::fs::write(dist.join("index.html"), "<!doctype html>").expect("write HTML");
968        let css = b"body { color: red; }";
969        let js = b"export default {};";
970        let wasm = vec![0; 1024];
971        std::fs::write(dist.join("site-123.css"), css).expect("write CSS");
972        std::fs::write(dist.join("app-123.js"), js).expect("write JS");
973        std::fs::write(dist.join("app-123_bg.wasm"), &wasm).expect("write WASM");
974
975        let mut json: serde_json::Value =
976            serde_json::from_str(MANIFEST).expect("fixture JSON should be valid");
977        json["assets"][0]["attributes"]["integrity"] =
978            format!("sha384-{}", STANDARD.encode(Sha384::digest(css))).into();
979        json["assets"][0]["content_digest"] =
980            format!("sha256-{}", STANDARD.encode(Sha256::digest(css))).into();
981        json["assets"][1]["content_digest"] =
982            format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
983        json["wasm"][0]["js_content_digest"] =
984            format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
985        json["wasm"][0]["wasm_content_digest"] =
986            format!("sha256-{}", STANDARD.encode(Sha256::digest(&wasm))).into();
987        json["wasm"][0]["preloads"][0]["content_digest"] =
988            format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
989        let json = serde_json::to_vec(&json).expect("serialize fixture");
990        TrunkAssetManifest::from_json(&json).expect("valid manifest")
991    }
992
993    #[test]
994    fn validate_output_rejects_each_invalid_or_stale_reference() {
995        type BreakReference = fn(&mut TrunkAssetManifest, &str);
996        let temp = tempfile::tempdir().expect("temporary directory");
997        let valid = write_valid_output(temp.path());
998        let wrong_digest = format!("sha384-{}", STANDARD.encode(Sha384::digest(b"other")));
999        let cases: [(&str, BreakReference); 10] = [
1000            ("../index.html", |m, _| m.html = "../index.html".into()),
1001            ("public URL prefix", |m, _| {
1002                m.wasm[0].js_url = "/elsewhere.js".into();
1003            }),
1004            ("content digest check failed", |m, d| {
1005                m.wasm[0].js_content_digest = Some(d.into());
1006            }),
1007            ("public URL prefix", |m, _| {
1008                m.wasm[0].wasm_url = "/elsewhere.wasm".into();
1009            }),
1010            ("content digest check failed", |m, d| {
1011                m.wasm[0].wasm_content_digest = Some(d.into());
1012            }),
1013            ("public URL prefix", |m, _| {
1014                m.wasm[0].initializer_url = Some("/elsewhere.js".into());
1015            }),
1016            ("public URL prefix", |m, _| {
1017                m.wasm[0].preloads[0].url = "/elsewhere.js".into();
1018            }),
1019            ("content digest check failed", |m, d| {
1020                m.wasm[0].preloads[0].content_digest = Some(d.into());
1021            }),
1022            ("content digest check failed", |m, d| {
1023                m.wasm[0].preloads[0].integrity = Some(d.into());
1024            }),
1025            ("public URL prefix", |m, _| {
1026                m.assets[0].url = "/elsewhere.css".into();
1027            }),
1028        ];
1029        for (expected, break_reference) in cases {
1030            let mut manifest = valid.clone();
1031            break_reference(&mut manifest, &wrong_digest);
1032            let error = manifest
1033                .validate_output(temp.path())
1034                .expect_err(expected)
1035                .to_string();
1036            assert!(error.contains(expected), "{expected}: {error}");
1037        }
1038    }
1039
1040    #[test]
1041    fn read_rejects_well_formed_json_that_fails_validation() {
1042        let temp = tempfile::tempdir().expect("temporary directory");
1043        let path = temp.path().join(TRUNK_ASSET_MANIFEST_FILE);
1044        let mut value = manifest_value();
1045        value["assets"][0]["role"] = "invalid".into();
1046        std::fs::write(&path, value.to_string()).expect("write manifest");
1047        assert!(
1048            TrunkAssetManifest::read(&path)
1049                .expect_err("unsupported role")
1050                .to_string()
1051                .contains("unsupported Trunk asset role")
1052        );
1053    }
1054
1055    #[test]
1056    fn validates_all_referenced_files_and_enabled_integrity() {
1057        let temp = tempfile::tempdir().expect("temporary directory");
1058        let manifest = write_valid_output(temp.path());
1059        manifest
1060            .validate_output(temp.path())
1061            .expect("all output files and SRI are valid");
1062
1063        std::fs::write(temp.path().join("site-123.css"), "stale stylesheet")
1064            .expect("replace stylesheet");
1065        assert!(
1066            manifest
1067                .validate_output(temp.path())
1068                .expect_err("stale SRI must fail")
1069                .to_string()
1070                .contains("content digest check failed")
1071        );
1072    }
1073
1074    #[test]
1075    fn rejects_missing_artifacts_stale_wasm_and_unsafe_urls() {
1076        let temp = tempfile::tempdir().expect("temporary directory");
1077        let manifest = write_valid_output(temp.path());
1078        std::fs::remove_file(temp.path().join("site-123.css")).expect("remove CSS");
1079        assert!(
1080            manifest
1081                .validate_output(temp.path())
1082                .expect_err("missing CSS must fail")
1083                .to_string()
1084                .contains("missing")
1085        );
1086
1087        let mut manifest = write_valid_output(temp.path());
1088        manifest.wasm[0].wasm_size += 1;
1089        assert!(
1090            manifest
1091                .validate_output(temp.path())
1092                .expect_err("stale WASM must fail")
1093                .to_string()
1094                .contains("stale WebAssembly module")
1095        );
1096
1097        let mut malicious = manifest;
1098        malicious.assets[0].url = "/app/%2e%2e/secret.css".to_owned();
1099        assert!(
1100            malicious
1101                .validate_output(temp.path())
1102                .expect_err("traversal must fail")
1103                .to_string()
1104                .contains("escapes")
1105        );
1106    }
1107
1108    #[test]
1109    fn rejects_missing_initializer_and_preload_bootstrap_files() {
1110        let temp = tempfile::tempdir().expect("temporary directory");
1111        let mut manifest = write_valid_output(temp.path());
1112        manifest.wasm[0].initializer_url = Some("/app/init-123.js".to_owned());
1113        std::fs::write(temp.path().join("init-123.js"), "export default {};")
1114            .expect("write initializer");
1115        manifest
1116            .validate_output(temp.path())
1117            .expect("initializer is present");
1118        std::fs::remove_file(temp.path().join("init-123.js")).expect("remove initializer");
1119        assert!(
1120            manifest
1121                .validate_output(temp.path())
1122                .expect_err("missing initializer must fail")
1123                .to_string()
1124                .contains("WASM initializer is missing")
1125        );
1126
1127        let mut manifest = write_valid_output(temp.path());
1128        manifest.wasm[0].preloads[0].url = "/app/preload-123.js".to_owned();
1129        std::fs::write(temp.path().join("preload-123.js"), "export default {};")
1130            .expect("write preload");
1131        manifest
1132            .validate_output(temp.path())
1133            .expect("preload is present");
1134        std::fs::remove_file(temp.path().join("preload-123.js")).expect("remove preload");
1135        assert!(
1136            manifest
1137                .validate_output(temp.path())
1138                .expect_err("missing preload must fail")
1139                .to_string()
1140                .contains("WASM preload is missing")
1141        );
1142    }
1143
1144    #[test]
1145    fn rejects_missing_html_and_manifest_urls_outside_public_prefix() {
1146        let temp = tempfile::tempdir().expect("temporary directory");
1147        let manifest = write_valid_output(temp.path());
1148        std::fs::remove_file(temp.path().join("index.html")).expect("remove HTML");
1149        assert!(
1150            manifest
1151                .validate_output(temp.path())
1152                .expect_err("missing HTML must fail")
1153                .to_string()
1154                .contains("missing")
1155        );
1156
1157        let mut wrong_prefix = write_valid_output(temp.path());
1158        wrong_prefix.assets[0].url = "https://other.invalid/site.css".to_owned();
1159        assert!(
1160            wrong_prefix
1161                .validate_output(temp.path())
1162                .expect_err("wrong public URL prefix must fail")
1163                .to_string()
1164                .contains("public URL prefix")
1165        );
1166    }
1167
1168    #[test]
1169    fn asset_urls_require_a_public_prefix_path_boundary() {
1170        let mut manifest =
1171            TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("valid manifest");
1172        for prefix in [
1173            "/app",
1174            "/app/",
1175            "https://cdn.example/app",
1176            "https://cdn.example/app/",
1177        ] {
1178            manifest.public_url = prefix.to_owned();
1179            let base = prefix.trim_end_matches('/');
1180            assert_eq!(
1181                manifest
1182                    .local_asset_path(&format!("{base}/nested/app.js"))
1183                    .expect("matching prefix"),
1184                PathBuf::from("nested/app.js")
1185            );
1186            for suffix in ["le.js", "", "%2fapp.js", "//app.js", "/%2e%2e/app.js"] {
1187                assert!(
1188                    manifest
1189                        .local_asset_path(&format!("{base}{suffix}"))
1190                        .is_err()
1191                );
1192            }
1193        }
1194        manifest.public_url = "/".to_owned();
1195        assert_eq!(
1196            manifest.local_asset_path("/app.js").expect("root prefix"),
1197            PathBuf::from("app.js")
1198        );
1199    }
1200
1201    #[test]
1202    fn output_validation_reports_unresolvable_paths() {
1203        let temp = tempfile::tempdir().expect("temporary directory");
1204        let manifest = write_valid_output(temp.path());
1205
1206        let error = manifest
1207            .validate_output(temp.path().join("missing-dist"))
1208            .expect_err("missing dist must fail")
1209            .to_string();
1210        assert!(
1211            error.contains("failed to resolve Trunk output directory"),
1212            "{error}"
1213        );
1214
1215        let mut through_file = manifest.clone();
1216        through_file.assets[0].url = "/app/index.html/site-123.css".to_owned();
1217        let error = through_file
1218            .validate_output(temp.path())
1219            .expect_err("path through a file must fail")
1220            .to_string();
1221        assert!(error.contains("failed to inspect"), "{error}");
1222
1223        std::fs::create_dir(temp.path().join("folder.css")).expect("directory asset");
1224        let mut directory = manifest;
1225        directory.assets[0].url = "/app/folder.css".to_owned();
1226        let error = directory
1227            .validate_output(temp.path())
1228            .expect_err("directory asset must fail")
1229            .to_string();
1230        assert!(error.contains("is not a file"), "{error}");
1231    }
1232
1233    #[test]
1234    fn output_path_for_url_matches_validation_mapping() {
1235        let manifest = TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("valid manifest");
1236        assert_eq!(
1237            manifest
1238                .output_path_for_url("/app/nested/app-123.js")
1239                .expect("asset under public URL"),
1240            PathBuf::from("nested/app-123.js")
1241        );
1242        for outside in [
1243            "/",
1244            "/app-123.js",
1245            "/apple.js",
1246            "/app//",
1247            "/app/%2e%2e/x",
1248            "/app/x.js?v=1",
1249        ] {
1250            assert!(manifest.output_path_for_url(outside).is_err(), "{outside}");
1251        }
1252    }
1253
1254    #[test]
1255    fn output_path_for_url_maps_the_public_root_to_the_html_entry() {
1256        let mut manifest =
1257            TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("valid manifest");
1258        for public_url in ["/app/", "/app"] {
1259            manifest.public_url = public_url.to_owned();
1260            for root in ["/app/", "/app"] {
1261                assert_eq!(
1262                    manifest.output_path_for_url(root).expect("public root"),
1263                    PathBuf::from("index.html"),
1264                    "{public_url} {root}"
1265                );
1266            }
1267            assert!(manifest.output_path_for_url("").is_err());
1268        }
1269        manifest.public_url = "/".to_owned();
1270        assert_eq!(
1271            manifest.output_path_for_url("/").expect("site root"),
1272            PathBuf::from("index.html")
1273        );
1274        assert!(manifest.output_path_for_url("").is_err());
1275        manifest.html = "../escape.html".to_owned();
1276        assert!(manifest.output_path_for_url("/").is_err());
1277
1278        let mut root_asset = TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("valid");
1279        root_asset.assets[0].url = "/app/".to_owned();
1280        let temp = tempfile::tempdir().expect("temporary directory");
1281        write_valid_output(temp.path());
1282        assert!(root_asset.validate_output(temp.path()).is_err());
1283    }
1284
1285    #[test]
1286    #[cfg(unix)]
1287    fn rejects_output_files_that_escape_dist_through_symlinks() {
1288        use std::os::unix::fs::symlink;
1289
1290        let outside = tempfile::tempdir().expect("outside directory");
1291        for name in [
1292            "index.html",
1293            "site-123.css",
1294            "app-123.js",
1295            "app-123_bg.wasm",
1296        ] {
1297            let temp = tempfile::tempdir().expect("temporary directory");
1298            let manifest = write_valid_output(temp.path());
1299            let target = outside.path().join(name);
1300            std::fs::rename(temp.path().join(name), &target).expect("move file outside dist");
1301            symlink(&target, temp.path().join(name)).expect("link outside dist");
1302            assert!(
1303                manifest
1304                    .validate_output(temp.path())
1305                    .expect_err("escaping symlink must fail")
1306                    .to_string()
1307                    .contains("escapes the Trunk output directory through a symbolic link"),
1308                "{name}"
1309            );
1310        }
1311
1312        let temp = tempfile::tempdir().expect("temporary directory");
1313        let manifest = write_valid_output(temp.path());
1314        std::fs::create_dir(outside.path().join("dir")).expect("outside directory");
1315        std::fs::rename(
1316            temp.path().join("site-123.css"),
1317            outside.path().join("dir/site-123.css"),
1318        )
1319        .expect("move CSS outside dist");
1320        let mut nested = manifest;
1321        nested.assets[0].url = "/app/linked/site-123.css".to_owned();
1322        symlink(outside.path().join("dir"), temp.path().join("linked")).expect("link directory");
1323        assert!(
1324            nested
1325                .validate_output(temp.path())
1326                .expect_err("escaping directory symlink must fail")
1327                .to_string()
1328                .contains("escapes the Trunk output directory")
1329        );
1330
1331        let temp = tempfile::tempdir().expect("temporary directory");
1332        let manifest = write_valid_output(temp.path());
1333        std::fs::create_dir(temp.path().join("real")).expect("inner directory");
1334        std::fs::rename(
1335            temp.path().join("site-123.css"),
1336            temp.path().join("real/site-123.css"),
1337        )
1338        .expect("move CSS inside dist");
1339        symlink("real/site-123.css", temp.path().join("site-123.css")).expect("inner link");
1340        manifest
1341            .validate_output(temp.path())
1342            .expect("symlinks that stay inside dist are accepted");
1343
1344        let linked_root = tempfile::tempdir().expect("link parent");
1345        let linked_dist = linked_root.path().join("dist");
1346        symlink(temp.path(), &linked_dist).expect("link dist root");
1347        manifest
1348            .validate_output(&linked_dist)
1349            .expect("a symlinked dist root is resolved before containment checks");
1350    }
1351
1352    #[test]
1353    #[cfg(unix)]
1354    fn resolve_output_file_serves_only_real_files_inside_dist() {
1355        use std::os::unix::fs::symlink;
1356
1357        let temp = tempfile::tempdir().expect("temporary directory");
1358        let manifest = write_valid_output(temp.path());
1359        let root = temp.path().canonicalize().expect("canonical dist");
1360        assert_eq!(
1361            manifest
1362                .resolve_output_file(temp.path(), "/app/app-123.js")
1363                .expect("listed asset"),
1364            root.join("app-123.js")
1365        );
1366        assert_eq!(
1367            manifest
1368                .resolve_output_file(temp.path(), "/app/")
1369                .expect("public root"),
1370            root.join("index.html")
1371        );
1372
1373        let outside = tempfile::tempdir().expect("outside directory");
1374        std::fs::write(outside.path().join("secret.txt"), "secret").expect("outside file");
1375        symlink(
1376            outside.path().join("secret.txt"),
1377            temp.path().join("unlisted.txt"),
1378        )
1379        .expect("unlisted symlink outside dist");
1380        assert!(
1381            manifest
1382                .resolve_output_file(temp.path(), "/app/unlisted.txt")
1383                .expect_err("unlisted escaping symlink must fail")
1384                .to_string()
1385                .contains("escapes the Trunk output directory")
1386        );
1387        for rejected in ["/app/missing.js", "/app/../secret.txt", "/elsewhere.js"] {
1388            assert!(
1389                manifest.resolve_output_file(temp.path(), rejected).is_err(),
1390                "{rejected}"
1391            );
1392        }
1393        assert!(
1394            manifest
1395                .resolve_output_file(temp.path().join("missing"), "/app/app-123.js")
1396                .is_err()
1397        );
1398    }
1399
1400    #[test]
1401    fn public_url_must_be_root_relative_or_http() {
1402        for accepted in [
1403            "/",
1404            "/app/",
1405            "/app",
1406            "https://cdn.example.com/app/",
1407            "HTTP://cdn.example.com",
1408        ] {
1409            let mut value = manifest_value();
1410            value["public_url"] = accepted.into();
1411            for asset in value["assets"].as_array_mut().expect("assets") {
1412                asset["url"] = format!("{}/x.css", accepted.trim_end_matches('/')).into();
1413            }
1414            value["wasm"] = serde_json::json!([]);
1415            let result = TrunkAssetManifest::from_json(value.to_string().as_bytes());
1416            assert!(result.is_ok(), "{accepted}: {:?}", result.err());
1417        }
1418        for rejected in [
1419            "javascript:alert(1)//",
1420            "data:text/html,x/",
1421            "app/",
1422            "//evil.example/",
1423            "https:///app/",
1424            "https://",
1425            "/app\\x/",
1426            "/a b/",
1427            "/a\"x/",
1428            "/<x>/",
1429        ] {
1430            let mut value = manifest_value();
1431            value["public_url"] = rejected.into();
1432            assert_manifest_error(&value, "must be a root-relative path or an http(s) URL");
1433        }
1434
1435        let mut asset = manifest_value();
1436        asset["assets"][0]["url"] = "javascript:alert(1)".into();
1437        assert_manifest_error(&asset, "does not use manifest public URL prefix");
1438        let mut preload = manifest_value();
1439        preload["wasm"][0]["preloads"][0]["url"] = "https://evil.example/app/x.js".into();
1440        assert_manifest_error(&preload, "does not use manifest public URL prefix");
1441    }
1442
1443    #[test]
1444    fn rejects_non_file_html_and_missing_wasm_runtime_files() {
1445        let temp = tempfile::tempdir().expect("temporary directory");
1446        let manifest = write_valid_output(temp.path());
1447        std::fs::remove_file(temp.path().join("index.html")).expect("remove HTML file");
1448        std::fs::create_dir(temp.path().join("index.html")).expect("create HTML directory");
1449        assert!(
1450            manifest
1451                .validate_output(temp.path())
1452                .expect_err("HTML output must be a file")
1453                .to_string()
1454                .contains("HTML output is not a file")
1455        );
1456
1457        let temp = tempfile::tempdir().expect("temporary directory");
1458        let mut manifest = write_valid_output(temp.path());
1459        manifest.assets.retain(|asset| asset.role != "script");
1460        std::fs::remove_file(temp.path().join("app-123.js")).expect("remove JS loader");
1461        assert!(
1462            manifest
1463                .validate_output(temp.path())
1464                .expect_err("WASM JavaScript loader must exist")
1465                .to_string()
1466                .contains("WASM JavaScript loader is missing")
1467        );
1468
1469        let temp = tempfile::tempdir().expect("temporary directory");
1470        let mut manifest = write_valid_output(temp.path());
1471        manifest.assets.retain(|asset| asset.role != "script");
1472        std::fs::remove_file(temp.path().join("app-123_bg.wasm")).expect("remove WASM module");
1473        assert!(
1474            manifest
1475                .validate_output(temp.path())
1476                .expect_err("WASM module must exist")
1477                .to_string()
1478                .contains("WebAssembly module is missing")
1479        );
1480    }
1481
1482    #[test]
1483    fn validates_current_content_digests_without_sri() {
1484        let temp = tempfile::tempdir().expect("temporary directory");
1485        write_valid_output(temp.path());
1486        let css = b"body { color: red; }";
1487        let js = b"export default {};";
1488        let wasm = vec![0; 1024];
1489        let mut json: serde_json::Value =
1490            serde_json::from_str(MANIFEST).expect("fixture JSON should be valid");
1491        json["assets"][0]["attributes"]
1492            .as_object_mut()
1493            .expect("asset attributes")
1494            .remove("integrity");
1495        json["assets"][0]["content_digest"] =
1496            format!("sha256-{}", STANDARD.encode(Sha256::digest(css))).into();
1497        json["assets"][1]["content_digest"] =
1498            format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
1499        json["wasm"][0]["js_content_digest"] =
1500            format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
1501        json["wasm"][0]["wasm_content_digest"] =
1502            format!("sha256-{}", STANDARD.encode(Sha256::digest(&wasm))).into();
1503        json["wasm"][0]["initializer_content_digest"] = serde_json::Value::Null;
1504        json["wasm"][0]["preloads"][0]["content_digest"] =
1505            format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
1506        let json = serde_json::to_vec(&json).expect("serialize current fixture");
1507        let manifest = TrunkAssetManifest::from_json(&json).expect("valid current manifest");
1508        manifest
1509            .validate_output(temp.path())
1510            .expect("content digests validate without SRI");
1511
1512        std::fs::write(temp.path().join("site-123.css"), b"body { color: blue; }")
1513            .expect("replace with same-length CSS");
1514        assert!(
1515            manifest
1516                .validate_output(temp.path())
1517                .expect_err("stale no-SRI asset must fail")
1518                .to_string()
1519                .contains("content digest check failed")
1520        );
1521    }
1522
1523    #[test]
1524    fn validates_current_initializer_and_preload_integrity() {
1525        let temp = tempfile::tempdir().expect("temporary directory");
1526        write_valid_output(temp.path());
1527        let css = b"body { color: red; }";
1528        let js = b"export default {};";
1529        let wasm = vec![0; 1024];
1530        let initializer = b"export function init() {}";
1531        std::fs::write(temp.path().join("init-123.js"), initializer).expect("write initializer");
1532
1533        let mut json = manifest_value();
1534        json["assets"][0]["attributes"]
1535            .as_object_mut()
1536            .expect("asset attributes")
1537            .remove("integrity");
1538        json["assets"][0]["content_digest"] =
1539            format!("sha256-{}", STANDARD.encode(Sha256::digest(css))).into();
1540        json["assets"][1]["content_digest"] =
1541            format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
1542        json["wasm"][0]["js_content_digest"] =
1543            format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
1544        json["wasm"][0]["wasm_content_digest"] =
1545            format!("sha256-{}", STANDARD.encode(Sha256::digest(&wasm))).into();
1546        json["wasm"][0]["initializer_url"] = "/app/init-123.js".into();
1547        json["wasm"][0]["initializer_content_digest"] =
1548            format!("sha256-{}", STANDARD.encode(Sha256::digest(initializer))).into();
1549        json["wasm"][0]["preloads"][0]["content_digest"] =
1550            format!("sha256-{}", STANDARD.encode(Sha256::digest(js))).into();
1551        json["wasm"][0]["preloads"][0]["integrity"] =
1552            format!("sha384-{}", STANDARD.encode(Sha384::digest(js))).into();
1553
1554        let bytes = serde_json::to_vec(&json).expect("serialize current manifest");
1555        let manifest = TrunkAssetManifest::from_json(&bytes).expect("valid current manifest");
1556        manifest
1557            .validate_output(temp.path())
1558            .expect("initializer and preload integrity validate");
1559
1560        std::fs::write(temp.path().join("init-123.js"), b"stale initializer")
1561            .expect("replace initializer");
1562        assert!(
1563            manifest
1564                .validate_output(temp.path())
1565                .expect_err("stale initializer must fail")
1566                .to_string()
1567                .contains("content digest check failed")
1568        );
1569    }
1570
1571    #[test]
1572    fn accepts_current_manifest_with_document_assets() {
1573        let mut json = manifest_value();
1574        push_document_asset(
1575            &mut json,
1576            serde_json::json!({"order": 0, "location": "head", "html": "<style>body{}</style>"}),
1577        );
1578        let manifest =
1579            TrunkAssetManifest::from_json(json.to_string().as_bytes()).expect("current manifest");
1580        assert_eq!(manifest.document_assets.len(), 2);
1581
1582        json["assets"][0]
1583            .as_object_mut()
1584            .expect("asset object")
1585            .remove("content_digest");
1586        assert!(
1587            TrunkAssetManifest::from_json(json.to_string().as_bytes())
1588                .expect_err("current manifest requires digest fields")
1589                .to_string()
1590                .contains("content digest")
1591        );
1592    }
1593
1594    #[test]
1595    fn groups_document_assets_by_location_in_trunk_order() {
1596        let mut json = manifest_value();
1597        json["document_assets"] = serde_json::json!([
1598            {"order": 0, "location": "head", "html": "<link rel=\"stylesheet\" href=\"/a-1.css\">"},
1599            {"order": 1, "location": "body", "html": "<span>inline</span>"},
1600            {"order": 2, "location": "head", "html": "<link rel=\"modulepreload\" href=\"/app-2.js\">"},
1601            {"order": 2, "location": "head", "html": "<script type=\"module\" nonce=\"{{__TRUNK NONCE__}}\">init()</script>"}
1602        ]);
1603        let assets = TrunkAssetManifest::from_json(json.to_string().as_bytes())
1604            .expect("current manifest")
1605            .document_assets()
1606            .expect("document assets");
1607        assert_eq!(
1608            assets.head_html(),
1609            concat!(
1610                "<link rel=\"stylesheet\" href=\"/a-1.css\">",
1611                "<link rel=\"modulepreload\" href=\"/app-2.js\">",
1612                "<script type=\"module\" nonce=\"{{__TRUNK NONCE__}}\">init()</script>",
1613            )
1614        );
1615        assert_eq!(assets.body_html(), "<span>inline</span>");
1616    }
1617
1618    #[test]
1619    fn rejects_document_assets_without_markup_or_placement() {
1620        let mut json = manifest_value();
1621        push_document_asset(
1622            &mut json,
1623            serde_json::json!({"order": 0, "location": "unknown", "html": "<style></style>"}),
1624        );
1625        let unplaced = TrunkAssetManifest::from_json(json.to_string().as_bytes())
1626            .expect("unknown locations parse");
1627        assert!(
1628            unplaced
1629                .document_assets()
1630                .expect_err("unknown location")
1631                .to_string()
1632                .contains("outside <head> and <body>")
1633        );
1634
1635        for (invalid, expected) in [
1636            (
1637                serde_json::json!({"order": 0, "location": "footer", "html": "<style></style>"}),
1638                "unsupported location `footer`",
1639            ),
1640            (
1641                serde_json::json!({"order": 0, "location": "head", "html": " "}),
1642                "empty markup",
1643            ),
1644        ] {
1645            let mut json = manifest_value();
1646            push_document_asset(&mut json, invalid);
1647            assert_manifest_error(&json, expected);
1648        }
1649    }
1650
1651    #[test]
1652    fn validates_relative_paths_and_digest_formats() {
1653        assert_eq!(
1654            safe_relative_path("assets/%41.js").expect("decode asset path"),
1655            PathBuf::from("assets/A.js")
1656        );
1657        for path in [
1658            "",
1659            "/absolute.js",
1660            "../secret.js",
1661            "bad\\path.js",
1662            "%",
1663            "%2",
1664            "%GG",
1665            "%FF",
1666        ] {
1667            assert!(
1668                safe_relative_path(path).is_err(),
1669                "path should be rejected: {path}"
1670            );
1671        }
1672
1673        let manifest = TrunkAssetManifest::from_json(MANIFEST.as_bytes()).expect("valid manifest");
1674        assert!(
1675            manifest
1676                .local_asset_path("/app/file.js?debug=true")
1677                .is_err()
1678        );
1679        assert!(manifest.local_asset_path("/app/file.js#section").is_err());
1680
1681        let temp = tempfile::tempdir().expect("temporary directory");
1682        let file = temp.path().join("asset.bin");
1683        std::fs::write(&file, b"content").expect("write asset");
1684        let blocked_directory = temp.path().join("not-a-directory");
1685        std::fs::write(&blocked_directory, b"file").expect("write blocking file");
1686        assert!(
1687            require_file(&blocked_directory.join("asset.bin"), "asset")
1688                .expect_err("non-directory parent")
1689                .to_string()
1690                .contains("failed to inspect")
1691        );
1692
1693        let digest = format!("sha512-{}", STANDARD.encode(Sha512::digest(b"content")));
1694        verify_digest(&file, &digest).expect("validate SHA-512 digest");
1695        assert!(verify_digest(&file, "malformed").is_err());
1696        assert!(verify_digest(&file, "sha256-!").is_err());
1697        assert!(
1698            verify_digest(&file, &format!("unknown-{}", STANDARD.encode(b"content")))
1699                .expect_err("unsupported algorithm")
1700                .to_string()
1701                .contains("unsupported asset digest algorithm")
1702        );
1703        assert!(
1704            verify_digest(
1705                &file,
1706                &format!("sha256-{}", STANDARD.encode(Sha256::digest(b"other")))
1707            )
1708            .expect_err("stale digest")
1709            .to_string()
1710            .contains("content digest check failed")
1711        );
1712        assert!(
1713            verify_digest(
1714                &temp.path().join("missing.bin"),
1715                &format!("sha256-{}", STANDARD.encode(Sha256::digest(b"content")))
1716            )
1717            .expect_err("missing digest file")
1718            .to_string()
1719            .contains("failed to read")
1720        );
1721    }
1722}