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