Skip to main content

bynk_project/
assets.rs

1//! #1883 (static assets), slice 1b: the project's assets folder — the one
2//! directory an `asset name = "path"` declaration may name a file in — and
3//! the walk that reads it.
4//!
5//! Assets are public by construction, so they come only from
6//! `<project root>/assets/` (decided on #1883 after the review of #1903): a
7//! declaration can never publish `.env` or a `.bynk` source by mistake. The
8//! checker states the rule (`bynk.asset.outside_assets_dir`); the driver and
9//! the test harnesses list the folder as an [`AssetFolder`], so `bynk-emit`
10//! and `bynk-check` stay disk-free and read the bytes of only the files a
11//! declaration names, and the LSP lists it with [`list_asset_files`] for the
12//! existence check.
13
14use std::collections::BTreeSet;
15use std::fmt;
16use std::io;
17use std::path::{Path, PathBuf};
18use std::sync::Arc;
19
20/// The project's assets folder, relative to the project root.
21pub const PROJECT_ASSETS_DIR: &str = "assets";
22
23/// `path` as the key [`list_asset_files`] files it under: separators made
24/// `/`, and empty and `.` segments dropped, so `./assets//board.css` and
25/// `assets\board.css` both become `assets/board.css`. A `..` segment is kept
26/// (the checker rejects it separately, `bynk.asset.unsafe_path`).
27pub fn normalise_asset_path(path: &str) -> String {
28    path.split(['/', '\\'])
29        .filter(|seg| !seg.is_empty() && *seg != ".")
30        .collect::<Vec<_>>()
31        .join("/")
32}
33
34/// Whether the normalised `path` names a file inside the assets folder —
35/// `assets/<at least one more segment>`.
36pub fn is_in_assets_dir(path: &str) -> bool {
37    let normalised = normalise_asset_path(path);
38    let mut segs = normalised.split('/');
39    segs.next() == Some(PROJECT_ASSETS_DIR) && segs.next().is_some()
40}
41
42/// The project's embedded-text folder, relative to the project root (#2387).
43/// Unlike [`PROJECT_ASSETS_DIR`] nothing in it is served: an `embed` compiles a
44/// file's text into the code. It is listed and read as an [`AssetFolder`]
45/// ([`EmbedFolder`]).
46pub const PROJECT_EMBEDS_DIR: &str = "embeds";
47
48/// The project's `embeds/` folder as the compiler sees it: an [`AssetFolder`]
49/// over `embeds/` instead of `assets/` (#2387).
50pub type EmbedFolder = AssetFolder;
51
52/// Whether the normalised `path` names a file inside the embeds folder —
53/// `embeds/<at least one more segment>`.
54pub fn is_in_embeds_dir(path: &str) -> bool {
55    let normalised = normalise_asset_path(path);
56    let mut segs = normalised.split('/');
57    segs.next() == Some(PROJECT_EMBEDS_DIR) && segs.next().is_some()
58}
59
60/// The project's test-fixture folder, relative to the project root (#2841).
61/// Nothing in it is deployed: a suite's `fixture` reads a file's text into test
62/// output only. It is listed and read as an [`AssetFolder`] ([`FixtureFolder`]).
63pub const PROJECT_FIXTURES_DIR: &str = "fixtures";
64
65/// The project's `fixtures/` folder as the compiler sees it (#2841).
66pub type FixtureFolder = AssetFolder;
67
68/// Whether the normalised `path` names a file inside the fixtures folder —
69/// `fixtures/<at least one more segment>`.
70pub fn is_in_fixtures_dir(path: &str) -> bool {
71    let normalised = normalise_asset_path(path);
72    let mut segs = normalised.split('/');
73    segs.next() == Some(PROJECT_FIXTURES_DIR) && segs.next().is_some()
74}
75
76/// Standard-library P4b (#2608): the project's D1 migrations folder,
77/// relative to the project root. Each `D1` instance's migrations are
78/// `migrations/<database>/NNNN_<name>.sql`; it is listed and read as an
79/// [`AssetFolder`].
80pub const PROJECT_MIGRATIONS_DIR: &str = "migrations";
81
82/// Reads one listed asset file's bytes, given its normalised key.
83pub type AssetReader = dyn Fn(&str) -> io::Result<Vec<u8>> + Send + Sync;
84
85/// The project's `assets/` folder as the compiler sees it: the files in it,
86/// listed up front, and a reader the compiler calls for the bytes of only
87/// those a declaration names. A large file nothing declares is never read.
88///
89/// The caller decides where the bytes come from: [`AssetFolder::on_disk`]
90/// for a real build, [`AssetFolder::new`] with its own reader otherwise.
91/// `bynk-emit` only ever calls [`AssetFolder::read`], so it stays disk-free.
92#[derive(Clone)]
93pub struct AssetFolder {
94    files: BTreeSet<String>,
95    reader: Arc<AssetReader>,
96}
97
98impl AssetFolder {
99    /// A folder of `files` (normalised keys, `assets/board.css`) whose bytes
100    /// come from `reader`. The compiler calls `reader` only with a key in
101    /// `files`, at most once per build.
102    pub fn new(files: BTreeSet<String>, reader: Arc<AssetReader>) -> Self {
103        Self { files, reader }
104    }
105
106    /// `<project_root>/assets/`, listed now ([`list_asset_files`]: regular
107    /// files only, symbolic links not followed, a missing folder empty) and
108    /// read later, file by file, as the compiler asks. The folder's real
109    /// location is fixed now too, so a read whose path resolves anywhere else
110    /// — a directory swapped for a symbolic link after the listing — is
111    /// refused rather than published.
112    pub fn on_disk(project_root: &Path) -> io::Result<Self> {
113        Self::on_disk_in(project_root, PROJECT_ASSETS_DIR, false)
114    }
115
116    /// [`AssetFolder::on_disk`] for the project's `embeds/` folder (#2387):
117    /// the same listing and the same refusals, a different directory.
118    pub fn embeds_on_disk(project_root: &Path) -> io::Result<Self> {
119        Self::on_disk_in(project_root, PROJECT_EMBEDS_DIR, false)
120    }
121
122    /// [`AssetFolder::on_disk`] for the project's `fixtures/` folder (#2841).
123    pub fn fixtures_on_disk(project_root: &Path) -> io::Result<Self> {
124        Self::on_disk_in(project_root, PROJECT_FIXTURES_DIR, false)
125    }
126
127    /// [`AssetFolder::on_disk`] for the project's `migrations/` folder
128    /// (#2608): the same refusals, but the listing keeps a symbolic link or
129    /// other non-regular entry ([`list_migration_files`]), so reading it is
130    /// refused rather than the migration silently missing.
131    pub fn migrations_on_disk(project_root: &Path) -> io::Result<Self> {
132        Self::on_disk_in(project_root, PROJECT_MIGRATIONS_DIR, true)
133    }
134
135    fn on_disk_in(project_root: &Path, folder: &str, keep_links: bool) -> io::Result<Self> {
136        let files = list_files_in(project_root, folder, keep_links)?;
137        if files.is_empty() {
138            // Nothing listed, so `read` never reaches the reader.
139            return Ok(Self::new(files, Arc::new(|_: &str| Err(not_listed()))));
140        }
141        let root: PathBuf = project_root.to_path_buf();
142        let dir = std::fs::canonicalize(root.join(folder))?;
143        Ok(Self::new(
144            files,
145            Arc::new(move |key: &str| read_listed_file(&root, &dir, key)),
146        ))
147    }
148
149    /// The files in the folder, by normalised key.
150    pub fn files(&self) -> &BTreeSet<String> {
151        &self.files
152    }
153
154    /// The bytes of the listed file `key`. A key the listing does not hold is
155    /// `NotFound` without consulting the reader, so no caller can steer it
156    /// outside the folder (`normalise_asset_path` keeps `..` segments).
157    pub fn read(&self, key: &str) -> io::Result<Vec<u8>> {
158        if !self.files.contains(key) {
159            return Err(not_listed());
160        }
161        (self.reader)(key)
162    }
163}
164
165impl fmt::Debug for AssetFolder {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        f.debug_struct("AssetFolder")
168            .field("files", &self.files)
169            .finish_non_exhaustive()
170    }
171}
172
173fn not_listed() -> io::Error {
174    io::Error::new(io::ErrorKind::NotFound, "not a listed asset file")
175}
176
177/// Read the listed file `key` under `root`, refusing it if it has become a
178/// symbolic link since the folder was listed, or if its path now resolves
179/// outside `dir` (the assets folder's canonical path, fixed at listing) —
180/// a folder on the way swapped for a link — so no link is ever followed.
181fn read_listed_file(root: &Path, dir: &Path, key: &str) -> io::Result<Vec<u8>> {
182    let path = root.join(key);
183    if !std::fs::symlink_metadata(&path)?.file_type().is_file() {
184        return Err(io::Error::new(
185            io::ErrorKind::InvalidInput,
186            "not a regular file",
187        ));
188    }
189    let resolved = std::fs::canonicalize(&path)?;
190    if !resolved.starts_with(dir) {
191        return Err(io::Error::new(
192            io::ErrorKind::InvalidInput,
193            "resolves outside the assets folder",
194        ));
195    }
196    std::fs::read(resolved)
197}
198
199/// Every regular file under `<project_root>/assets/`, by its normalised
200/// project-relative path (`assets/board.css`), without reading any bytes.
201/// Symbolic links are not followed, so a link cannot pull a file in from
202/// outside the folder; a missing folder is an empty set.
203pub fn list_asset_files(project_root: &Path) -> io::Result<BTreeSet<String>> {
204    list_files_in(project_root, PROJECT_ASSETS_DIR, false)
205}
206
207/// [`list_asset_files`] for the project's `embeds/` folder (#2387).
208pub fn list_embed_files(project_root: &Path) -> io::Result<BTreeSet<String>> {
209    list_files_in(project_root, PROJECT_EMBEDS_DIR, false)
210}
211
212/// [`list_asset_files`] for the project's `fixtures/` folder (#2841).
213pub fn list_fixture_files(project_root: &Path) -> io::Result<BTreeSet<String>> {
214    list_files_in(project_root, PROJECT_FIXTURES_DIR, false)
215}
216
217/// [`list_asset_files`] for the project's `migrations/` folder (#2608), except
218/// that a symbolic link or other non-regular entry is listed too, unfollowed.
219/// An asset nothing declares can be skipped quietly, but a skipped migration
220/// is a schema change that never runs, so the listing keeps it and reading it
221/// is refused ([`AssetFolder::read`]), which the checker reports.
222pub fn list_migration_files(project_root: &Path) -> io::Result<BTreeSet<String>> {
223    list_files_in(project_root, PROJECT_MIGRATIONS_DIR, true)
224}
225
226fn list_files_in(
227    project_root: &Path,
228    folder: &str,
229    keep_links: bool,
230) -> io::Result<BTreeSet<String>> {
231    let mut out = BTreeSet::new();
232    walk(project_root, folder, keep_links, &mut |rel| {
233        out.insert(rel);
234    })?;
235    Ok(out)
236}
237
238fn walk(
239    project_root: &Path,
240    folder: &str,
241    keep_links: bool,
242    visit: &mut dyn FnMut(String),
243) -> io::Result<()> {
244    let dir = project_root.join(folder);
245    if !dir.is_dir() {
246        return Ok(());
247    }
248    walk_dir(&dir, folder, keep_links, visit)
249}
250
251fn walk_dir(
252    dir: &Path,
253    rel: &str,
254    keep_links: bool,
255    visit: &mut dyn FnMut(String),
256) -> io::Result<()> {
257    let mut entries = std::fs::read_dir(dir)?.collect::<Result<Vec<_>, _>>()?;
258    entries.sort_by_key(|e| e.file_name());
259    for entry in entries {
260        // `DirEntry::file_type` does not follow a symlink, so a link is
261        // neither a file nor a directory here: skipped, or with `keep_links`
262        // listed as it stands and never descended into.
263        let ty = entry.file_type()?;
264        let name = entry.file_name().to_string_lossy().into_owned();
265        let child = format!("{rel}/{name}");
266        if ty.is_dir() {
267            walk_dir(&entry.path(), &child, keep_links, visit)?;
268        } else if ty.is_file() || keep_links {
269            visit(child);
270        }
271    }
272    Ok(())
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278
279    #[test]
280    fn normalise_and_folder_membership() {
281        assert_eq!(
282            normalise_asset_path("./assets//board.css"),
283            "assets/board.css"
284        );
285        assert_eq!(
286            normalise_asset_path("assets\\img\\a.png"),
287            "assets/img/a.png"
288        );
289        assert!(is_in_assets_dir("assets/board.css"));
290        assert!(is_in_assets_dir("./assets/.well-known/security.txt"));
291        assert!(!is_in_assets_dir("assets"));
292        assert!(!is_in_assets_dir("assets/"));
293        assert!(!is_in_assets_dir(".env"));
294        assert!(!is_in_assets_dir("src/app/page.bynk"));
295        assert!(!is_in_assets_dir("public/assets/x.css"));
296    }
297
298    /// #2387: `embeds/` is listed and read like `assets/`, and the two folders
299    /// do not see each other's files.
300    #[test]
301    fn the_embeds_folder_is_listed_apart_from_assets() {
302        assert!(is_in_embeds_dir("embeds/page.html"));
303        assert!(is_in_embeds_dir("./embeds//a/b.txt"));
304        assert!(!is_in_embeds_dir("embeds"));
305        assert!(!is_in_embeds_dir("assets/page.html"));
306        assert!(!is_in_assets_dir("embeds/page.html"));
307
308        let root = std::env::temp_dir().join(format!("bynk-project-embeds-{}", std::process::id()));
309        let _ = std::fs::remove_dir_all(&root);
310        std::fs::create_dir_all(root.join("embeds/mail")).unwrap();
311        std::fs::create_dir_all(root.join("assets")).unwrap();
312        std::fs::write(root.join("embeds/page.html"), b"<p>").unwrap();
313        std::fs::write(root.join("embeds/mail/welcome.txt"), b"hi").unwrap();
314        std::fs::write(root.join("assets/board.css"), b"a{}").unwrap();
315
316        let embeds = AssetFolder::embeds_on_disk(&root).unwrap();
317        assert_eq!(
318            embeds.files().iter().cloned().collect::<Vec<_>>(),
319            vec!["embeds/mail/welcome.txt", "embeds/page.html"]
320        );
321        assert_eq!(embeds.read("embeds/page.html").unwrap(), b"<p>");
322        // The assets folder's file is not in the embeds listing, so it cannot
323        // be read through it.
324        assert_eq!(
325            embeds.read("assets/board.css").unwrap_err().kind(),
326            io::ErrorKind::NotFound
327        );
328        assert_eq!(
329            list_asset_files(&root)
330                .unwrap()
331                .into_iter()
332                .collect::<Vec<_>>(),
333            vec!["assets/board.css"]
334        );
335        assert!(
336            AssetFolder::embeds_on_disk(&root.join("nowhere"))
337                .unwrap()
338                .files()
339                .is_empty()
340        );
341        let _ = std::fs::remove_dir_all(&root);
342    }
343
344    #[test]
345    fn the_walk_reads_regular_files_and_skips_links() {
346        let root = std::env::temp_dir().join(format!("bynk-project-assets-{}", std::process::id()));
347        let _ = std::fs::remove_dir_all(&root);
348        std::fs::create_dir_all(root.join("assets/img")).unwrap();
349        std::fs::write(root.join("assets/board.css"), b"body{}").unwrap();
350        std::fs::write(root.join("assets/img/a.png"), [0x89, 0x00]).unwrap();
351        std::fs::write(root.join("secret.txt"), b"no").unwrap();
352        #[cfg(unix)]
353        std::os::unix::fs::symlink(root.join("secret.txt"), root.join("assets/leak.txt")).unwrap();
354
355        let folder = AssetFolder::on_disk(&root).unwrap();
356        assert_eq!(
357            folder.files().iter().cloned().collect::<Vec<_>>(),
358            vec!["assets/board.css", "assets/img/a.png"]
359        );
360        assert_eq!(folder.read("assets/img/a.png").unwrap(), vec![0x89, 0x00]);
361        // Only listed keys are read: a link, or a `..` escape, is refused
362        // by name, whatever the reader would do with it.
363        #[cfg(unix)]
364        assert!(folder.read("assets/leak.txt").is_err());
365        assert_eq!(
366            folder.read("assets/../secret.txt").unwrap_err().kind(),
367            io::ErrorKind::NotFound
368        );
369        assert!(
370            AssetFolder::on_disk(&root.join("nowhere"))
371                .unwrap()
372                .files()
373                .is_empty()
374        );
375        let _ = std::fs::remove_dir_all(&root);
376    }
377
378    /// Review of #2609: a linked migration is listed, unfollowed, so reading
379    /// it is refused and the checker reports it, where a linked asset is
380    /// simply skipped.
381    #[cfg(unix)]
382    #[test]
383    fn a_linked_migration_is_listed_and_its_read_refused() {
384        let root = std::env::temp_dir().join(format!(
385            "bynk-project-migrations-link-{}",
386            std::process::id()
387        ));
388        let _ = std::fs::remove_dir_all(&root);
389        std::fs::create_dir_all(root.join("migrations/shop-orders")).unwrap();
390        std::fs::create_dir_all(root.join("shared")).unwrap();
391        std::fs::write(root.join("migrations/shop-orders/0001_init.sql"), b"x").unwrap();
392        std::fs::write(root.join("shared/0002.sql"), b"y").unwrap();
393        std::os::unix::fs::symlink(
394            root.join("shared/0002.sql"),
395            root.join("migrations/shop-orders/0002_add.sql"),
396        )
397        .unwrap();
398        std::os::unix::fs::symlink(root.join("shared"), root.join("migrations/shop-old")).unwrap();
399
400        let folder = AssetFolder::migrations_on_disk(&root).unwrap();
401        assert_eq!(
402            folder.files().iter().cloned().collect::<Vec<_>>(),
403            vec![
404                "migrations/shop-old",
405                "migrations/shop-orders/0001_init.sql",
406                "migrations/shop-orders/0002_add.sql",
407            ]
408        );
409        assert_eq!(list_migration_files(&root).unwrap(), *folder.files());
410        assert_eq!(
411            folder.read("migrations/shop-orders/0001_init.sql").unwrap(),
412            b"x"
413        );
414        assert_eq!(
415            folder
416                .read("migrations/shop-orders/0002_add.sql")
417                .unwrap_err()
418                .kind(),
419            io::ErrorKind::InvalidInput
420        );
421        let _ = std::fs::remove_dir_all(&root);
422    }
423
424    /// Review of #1905: a directory inside `assets/` swapped for a symbolic
425    /// link between the listing and the read does not pull a file in from
426    /// outside the folder, though the file at the end is a regular one.
427    #[cfg(unix)]
428    #[test]
429    fn a_folder_swapped_for_a_link_after_listing_is_not_followed() {
430        let root =
431            std::env::temp_dir().join(format!("bynk-project-assets-swap-{}", std::process::id()));
432        let _ = std::fs::remove_dir_all(&root);
433        std::fs::create_dir_all(root.join("assets/css")).unwrap();
434        std::fs::write(root.join("assets/css/palette.css"), b"a{}").unwrap();
435        std::fs::create_dir_all(root.join("outside")).unwrap();
436        std::fs::write(root.join("outside/palette.css"), b"secret").unwrap();
437
438        let folder = AssetFolder::on_disk(&root).unwrap();
439        assert_eq!(folder.read("assets/css/palette.css").unwrap(), b"a{}");
440        std::fs::remove_dir_all(root.join("assets/css")).unwrap();
441        std::os::unix::fs::symlink(root.join("outside"), root.join("assets/css")).unwrap();
442        let err = folder.read("assets/css/palette.css").unwrap_err();
443        assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{err}");
444        let _ = std::fs::remove_dir_all(&root);
445    }
446}