Skip to main content

phoenix_view/
assets.rs

1use std::{
2    collections::{HashMap, HashSet},
3    fs,
4    path::{Component, Path, PathBuf},
5};
6
7use serde::{Deserialize, Serialize};
8use thiserror::Error;
9
10pub const ASSET_MANIFEST_SCHEMA: u8 = 1;
11
12#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
13pub struct AssetManifest {
14    pub schema: u8,
15    pub version: String,
16    pub contract_hash: String,
17    #[serde(default = "default_public_path")]
18    pub public_path: String,
19    pub entries: HashMap<String, AssetEntry>,
20}
21
22#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
23pub struct AssetEntry {
24    pub file: String,
25    #[serde(default)]
26    pub css: Vec<String>,
27    #[serde(default)]
28    pub imports: Vec<String>,
29}
30
31#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
32pub struct RendererManifest {
33    pub schema: u8,
34    pub version: String,
35    pub contract_hash: String,
36    pub entry: String,
37}
38
39impl RendererManifest {
40    /// Load and validate the SSR renderer build manifest.
41    ///
42    /// # Errors
43    ///
44    /// Returns an error for unreadable/invalid JSON or unsafe build identity.
45    pub fn load(path: impl AsRef<Path>) -> Result<Self, AssetManifestError> {
46        let path = path.as_ref();
47        let bytes = fs::read(path).map_err(|source| AssetManifestError::Read {
48            path: path.to_path_buf(),
49            source,
50        })?;
51        let manifest: Self = serde_json::from_slice(&bytes).map_err(AssetManifestError::Decode)?;
52        manifest.validate()?;
53        Ok(manifest)
54    }
55
56    /// Validate schema, build identity, and renderer entry path.
57    ///
58    /// # Errors
59    ///
60    /// Returns an error when any field is unsafe or unsupported.
61    pub fn validate(&self) -> Result<(), AssetManifestError> {
62        if self.schema != ASSET_MANIFEST_SCHEMA {
63            return Err(AssetManifestError::UnsupportedSchema(self.schema));
64        }
65        if self.version.is_empty() || self.contract_hash.is_empty() {
66            return Err(AssetManifestError::MissingIdentity);
67        }
68        validate_asset_path(&self.entry)
69    }
70}
71
72impl AssetManifest {
73    /// Load and validate a production asset manifest.
74    ///
75    /// # Errors
76    ///
77    /// Returns an error when the file cannot be read, JSON is invalid, the
78    /// schema is unsupported, or any asset path can escape the asset root.
79    pub fn load(path: impl AsRef<Path>) -> Result<Self, AssetManifestError> {
80        let path = path.as_ref();
81        let bytes = fs::read(path).map_err(|source| AssetManifestError::Read {
82            path: path.to_path_buf(),
83            source,
84        })?;
85        let manifest: Self = serde_json::from_slice(&bytes).map_err(AssetManifestError::Decode)?;
86        manifest.validate()?;
87        Ok(manifest)
88    }
89
90    /// Validate the manifest without reading from disk.
91    ///
92    /// # Errors
93    ///
94    /// Returns an error for unsupported schemas, invalid public prefixes, or
95    /// unsafe/duplicated asset paths.
96    pub fn validate(&self) -> Result<(), AssetManifestError> {
97        if self.schema != ASSET_MANIFEST_SCHEMA {
98            return Err(AssetManifestError::UnsupportedSchema(self.schema));
99        }
100        if self.version.is_empty() || self.contract_hash.is_empty() {
101            return Err(AssetManifestError::MissingIdentity);
102        }
103        if !self.public_path.starts_with('/') || !self.public_path.ends_with('/') {
104            return Err(AssetManifestError::InvalidPublicPath(
105                self.public_path.clone(),
106            ));
107        }
108        let mut paths = HashSet::new();
109        for entry in self.entries.values() {
110            for path in std::iter::once(&entry.file)
111                .chain(entry.css.iter())
112                .chain(entry.imports.iter())
113            {
114                validate_asset_path(path)?;
115                if !paths.insert(path) {
116                    return Err(AssetManifestError::DuplicateAsset(path.clone()));
117                }
118            }
119        }
120        Ok(())
121    }
122
123    #[must_use]
124    pub fn entry(&self, name: &str) -> Option<&AssetEntry> {
125        self.entries.get(name)
126    }
127
128    /// Verify that Rust and browser artifacts were generated from the same
129    /// contract set.
130    ///
131    /// # Errors
132    ///
133    /// Returns a mismatch error when the expected hash differs.
134    pub fn verify_contract(&self, expected: &str) -> Result<(), AssetManifestError> {
135        if self.contract_hash == expected {
136            Ok(())
137        } else {
138            Err(AssetManifestError::ContractMismatch {
139                expected: expected.to_owned(),
140                actual: self.contract_hash.clone(),
141            })
142        }
143    }
144
145    /// Produce the public URL for a manifest-owned asset.
146    ///
147    /// # Errors
148    ///
149    /// Returns an error if the path is not present in the manifest.
150    pub fn url(&self, asset: &str) -> Result<String, AssetManifestError> {
151        if !self.owned_assets().contains(asset) {
152            return Err(AssetManifestError::UnknownAsset(asset.to_owned()));
153        }
154        Ok(format!("{}{}", self.public_path, asset))
155    }
156
157    /// Resolve an incoming static URL to a file below `root`.
158    ///
159    /// Only exact files declared by the manifest are resolvable. This avoids
160    /// using user-controlled paths as general filesystem paths.
161    ///
162    /// # Errors
163    ///
164    /// Returns an error for the wrong URL prefix or an undeclared asset.
165    pub fn resolve_static(
166        &self,
167        root: impl AsRef<Path>,
168        request_path: &str,
169    ) -> Result<PathBuf, AssetManifestError> {
170        let relative = request_path
171            .strip_prefix(&self.public_path)
172            .ok_or_else(|| AssetManifestError::UnknownAsset(request_path.to_owned()))?;
173        if !self.owned_assets().contains(relative) {
174            return Err(AssetManifestError::UnknownAsset(relative.to_owned()));
175        }
176        Ok(root.as_ref().join(relative))
177    }
178
179    fn owned_assets(&self) -> HashSet<&str> {
180        self.entries
181            .values()
182            .flat_map(|entry| {
183                std::iter::once(entry.file.as_str())
184                    .chain(entry.css.iter().map(String::as_str))
185                    .chain(entry.imports.iter().map(String::as_str))
186            })
187            .collect()
188    }
189}
190
191fn default_public_path() -> String {
192    "/assets/".to_owned()
193}
194
195fn validate_asset_path(path: &str) -> Result<(), AssetManifestError> {
196    let candidate = Path::new(path);
197    let safe = !path.is_empty()
198        && !path.contains('\\')
199        && !candidate.is_absolute()
200        && candidate.components().all(|component| {
201            matches!(component, Component::Normal(_)) && !component.as_os_str().is_empty()
202        });
203    if safe {
204        Ok(())
205    } else {
206        Err(AssetManifestError::UnsafeAsset(path.to_owned()))
207    }
208}
209
210#[derive(Debug, Error)]
211pub enum AssetManifestError {
212    #[error("failed to read asset manifest {path}: {source}")]
213    Read {
214        path: PathBuf,
215        #[source]
216        source: std::io::Error,
217    },
218    #[error("failed to decode the asset manifest: {0}")]
219    Decode(serde_json::Error),
220    #[error("asset manifest schema {0} is not supported")]
221    UnsupportedSchema(u8),
222    #[error("asset manifest version and contract hash must be non-empty")]
223    MissingIdentity,
224    #[error("asset public path must begin and end with '/': {0}")]
225    InvalidPublicPath(String),
226    #[error("asset manifest contains an unsafe path: {0}")]
227    UnsafeAsset(String),
228    #[error("asset manifest declares the same file more than once: {0}")]
229    DuplicateAsset(String),
230    #[error("asset is not declared by the production manifest: {0}")]
231    UnknownAsset(String),
232    #[error("contract hash mismatch (expected {expected}, manifest has {actual})")]
233    ContractMismatch { expected: String, actual: String },
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    fn manifest() -> AssetManifest {
241        AssetManifest {
242            schema: ASSET_MANIFEST_SCHEMA,
243            version: "sha256-build".to_owned(),
244            contract_hash: "fnv1a-contract".to_owned(),
245            public_path: "/assets/".to_owned(),
246            entries: HashMap::from([(
247                "client".to_owned(),
248                AssetEntry {
249                    file: "phoenix-a1.js".to_owned(),
250                    css: vec!["phoenix-b2.css".to_owned()],
251                    imports: vec!["chunks/page-c3.js".to_owned()],
252                },
253            )]),
254        }
255    }
256
257    #[test]
258    fn resolves_only_manifest_owned_files() {
259        let manifest = manifest();
260        manifest.validate().unwrap();
261        assert_eq!(
262            manifest
263                .resolve_static("public/assets", "/assets/chunks/page-c3.js")
264                .unwrap(),
265            PathBuf::from("public/assets/chunks/page-c3.js")
266        );
267        assert!(
268            manifest
269                .resolve_static("public/assets", "/assets/../secret")
270                .is_err()
271        );
272        assert!(manifest.url("not-in-manifest.js").is_err());
273    }
274
275    #[test]
276    fn rejects_unsafe_paths_and_contract_drift() {
277        let mut invalid = manifest();
278        invalid.entries.get_mut("client").unwrap().file = "../escape.js".to_owned();
279        assert!(matches!(
280            invalid.validate(),
281            Err(AssetManifestError::UnsafeAsset(_))
282        ));
283        assert!(matches!(
284            manifest().verify_contract("different"),
285            Err(AssetManifestError::ContractMismatch { .. })
286        ));
287    }
288
289    #[test]
290    fn read_errors_include_manifest_path() {
291        for result in [
292            AssetManifest::load("missing-assets-manifest.json").map(|_| ()),
293            RendererManifest::load("missing-renderer-manifest.json").map(|_| ()),
294        ] {
295            assert!(matches!(
296                result,
297                Err(AssetManifestError::Read { path, source })
298                    if source.kind() == std::io::ErrorKind::NotFound
299                        && path.to_string_lossy().starts_with("missing-")
300            ));
301        }
302    }
303}