Skip to main content

stackless_core/
source_archive.rs

1//! Bounded source transfer. Every filesystem lookup stays relative to an open directory.
2
3use std::collections::BTreeSet;
4use std::fs::File;
5use std::io::{Read, Write};
6use std::path::{Component, Path};
7
8use base64::{Engine as _, engine::general_purpose::STANDARD};
9use rustix::fd::{AsFd, OwnedFd};
10use rustix::fs::{Dir, FileType, Mode, OFlags, fstat, mkdirat, open, openat};
11use serde::{Deserialize, Serialize};
12
13pub const MAX_BYTES: usize = 64 * 1024 * 1024;
14pub const MAX_ENTRIES: usize = 100_000;
15
16#[derive(Debug, thiserror::Error)]
17#[error("invalid source archive: {0}")]
18pub struct ArchiveError(String);
19
20fn invalid(detail: impl Into<String>) -> ArchiveError {
21    ArchiveError(detail.into())
22}
23fn io(error: impl std::fmt::Display) -> ArchiveError {
24    invalid(error.to_string())
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(deny_unknown_fields)]
29pub struct SourceArchive {
30    pub directories: Vec<String>,
31    pub files: Vec<SourceFile>,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(deny_unknown_fields)]
36pub struct SourceFile {
37    pub path: String,
38    pub executable: bool,
39    /// Base64 keeps binary source files within a bounded JSON frame.
40    pub contents: String,
41}
42
43pub fn excluded(name: &str) -> bool {
44    matches!(
45        name,
46        ".git"
47            | ".stackless-builds"
48            | ".stackless-commands"
49            | ".projects"
50            | ".stackless.env"
51            | ".ssh"
52            | ".aws"
53            | ".azure"
54            | ".config"
55            | ".docker"
56            | ".codex"
57            | ".agents"
58            | ".netrc"
59            | ".vercel-token"
60            | ".render-api-key"
61            | ".cloudflare-api-token"
62            | ".railway-token"
63            | ".wordpress-com-token"
64            | ".laravel-cloud-token"
65            | ".gitlab-token"
66    ) || name == ".env"
67        || name.starts_with(".env.")
68}
69
70fn components(path: &str) -> Result<Vec<&str>, ArchiveError> {
71    let parts: Vec<_> = path.split('/').collect();
72    if path.is_empty()
73        || path.len() > 4096
74        || parts.len() > 100
75        || path.contains('\\')
76        || path.contains('\0')
77        || parts
78            .iter()
79            .any(|part| part.is_empty() || matches!(*part, "." | "..") || excluded(part))
80    {
81        return Err(invalid(
82            "source path is absolute, protected, or escapes its root",
83        ));
84    }
85    Ok(parts)
86}
87
88fn directory_flags() -> OFlags {
89    OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC
90}
91
92impl SourceArchive {
93    pub fn capture(path: &Path) -> Result<Self, ArchiveError> {
94        let canonical = path.canonicalize().map_err(io)?;
95        if canonical.components().any(|component| matches!(component, Component::Normal(name) if excluded(&name.to_string_lossy()))) {
96            return Err(invalid("source root is a protected directory"));
97        }
98        let fd = open(&canonical, directory_flags(), Mode::empty()).map_err(io)?;
99        Self::read_directory(&fd)
100    }
101
102    /// Resolve a configured source root through directory descriptors. A checkout
103    /// cannot redirect the upload to an absolute path, parent, or symlink target.
104    pub fn capture_beneath(root: &Path, relative: &Path) -> Result<Self, ArchiveError> {
105        let mut fd = open(root, directory_flags(), Mode::empty()).map_err(io)?;
106        for component in relative.components() {
107            match component {
108                Component::CurDir => {}
109                Component::Normal(name) if !excluded(&name.to_string_lossy()) => {
110                    fd = openat(&fd, name, directory_flags(), Mode::empty()).map_err(io)?;
111                }
112                _ => {
113                    return Err(invalid(
114                        "source root escapes its checkout or names a protected directory",
115                    ));
116                }
117            }
118        }
119        Self::read_directory(&fd)
120    }
121
122    fn read_directory(fd: &OwnedFd) -> Result<Self, ArchiveError> {
123        let mut archive = Self {
124            directories: vec![],
125            files: vec![],
126        };
127        let mut bytes = 0;
128        archive.walk(fd, "", &mut bytes)?;
129        archive.directories.sort();
130        archive.files.sort_by(|a, b| a.path.cmp(&b.path));
131        Ok(archive)
132    }
133
134    fn walk(
135        &mut self,
136        parent: &OwnedFd,
137        prefix: &str,
138        bytes: &mut usize,
139    ) -> Result<(), ArchiveError> {
140        for entry in Dir::read_from(parent).map_err(io)? {
141            let entry = entry.map_err(io)?;
142            let name = entry
143                .file_name()
144                .to_str()
145                .map_err(|_| invalid("source filename is not UTF-8"))?;
146            if matches!(name, "." | "..") || excluded(name) {
147                continue;
148            }
149            if self.directories.len() + self.files.len() >= MAX_ENTRIES {
150                return Err(invalid("source exceeds 100000 entries"));
151            }
152            let path = if prefix.is_empty() {
153                name.to_owned()
154            } else {
155                format!("{prefix}/{name}")
156            };
157            components(&path)?;
158            // NONBLOCK prevents a substituted FIFO from hanging capture. NOFOLLOW rejects links.
159            let fd = openat(
160                parent,
161                name,
162                OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC | OFlags::NONBLOCK,
163                Mode::empty(),
164            )
165            .map_err(io)?;
166            let stat = fstat(&fd).map_err(io)?;
167            match FileType::from_raw_mode(stat.st_mode) {
168                FileType::Directory => {
169                    self.directories.push(path.clone());
170                    self.walk(&fd, &path, bytes)?;
171                }
172                FileType::RegularFile => {
173                    let mut contents = Vec::new();
174                    File::from(fd)
175                        .take((MAX_BYTES - *bytes + 1) as u64)
176                        .read_to_end(&mut contents)
177                        .map_err(io)?;
178                    *bytes += contents.len();
179                    if *bytes > MAX_BYTES {
180                        return Err(invalid("source exceeds 64 MiB"));
181                    }
182                    self.files.push(SourceFile {
183                        path,
184                        executable: stat.st_mode & 0o111 != 0,
185                        contents: STANDARD.encode(contents),
186                    });
187                }
188                _ => return Err(invalid("source contains a link or special file")),
189            }
190        }
191        Ok(())
192    }
193
194    pub fn validate(&self) -> Result<usize, ArchiveError> {
195        if self.files.len() + self.directories.len() > MAX_ENTRIES {
196            return Err(invalid("source exceeds 100000 entries"));
197        }
198        let mut seen = BTreeSet::new();
199        let mut bytes = 0usize;
200        for path in self
201            .directories
202            .iter()
203            .chain(self.files.iter().map(|file| &file.path))
204        {
205            components(path)?;
206            if !seen.insert(path) {
207                return Err(invalid("source contains duplicate paths"));
208            }
209        }
210        for file in &self.files {
211            if file.contents.len() > MAX_BYTES.div_ceil(3) * 4 {
212                return Err(invalid("source exceeds 64 MiB"));
213            }
214            bytes = bytes.saturating_add(
215                STANDARD
216                    .decode(&file.contents)
217                    .map_err(|_| invalid("source file is not valid base64"))?
218                    .len(),
219            );
220            if bytes > MAX_BYTES {
221                return Err(invalid("source exceeds 64 MiB"));
222            }
223        }
224        Ok(bytes)
225    }
226
227    /// Extract only into a newly created staging directory. Publish the directory atomically.
228    pub fn extract(&self, root: &Path) -> Result<(), ArchiveError> {
229        self.validate()?;
230        let fd = open(root, directory_flags(), Mode::empty()).map_err(io)?;
231        for path in &self.directories {
232            descend(&fd, &components(path)?)?;
233        }
234        for file in &self.files {
235            let parts = components(&file.path)?;
236            let (name, parents) = parts
237                .split_last()
238                .ok_or_else(|| invalid("empty source path"))?;
239            let parent = descend(&fd, parents)?;
240            let mode = if file.executable {
241                Mode::from_raw_mode(0o700)
242            } else {
243                Mode::from_raw_mode(0o600)
244            };
245            let output = openat(
246                &parent,
247                *name,
248                OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
249                mode,
250            )
251            .map_err(io)?;
252            let mut output = File::from(output);
253            output
254                .write_all(
255                    &STANDARD
256                        .decode(&file.contents)
257                        .map_err(|_| invalid("invalid base64"))?,
258                )
259                .map_err(io)?;
260            output.sync_all().map_err(io)?;
261        }
262        Ok(())
263    }
264}
265
266fn descend(parent: &impl AsFd, parts: &[&str]) -> Result<OwnedFd, ArchiveError> {
267    let mut fd = openat(parent, ".", directory_flags(), Mode::empty()).map_err(io)?;
268    for name in parts {
269        match mkdirat(&fd, *name, Mode::from_raw_mode(0o700)) {
270            Ok(()) | Err(rustix::io::Errno::EXIST) => (),
271            Err(error) => return Err(io(error)),
272        }
273        fd = openat(&fd, *name, directory_flags(), Mode::empty()).map_err(io)?;
274    }
275    Ok(fd)
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281    use std::os::unix::fs::{PermissionsExt, symlink};
282
283    #[test]
284    fn capture_and_extract_preserve_files_but_exclude_credentials() {
285        let root = tempfile::tempdir().unwrap();
286        let source = root.path().join("source");
287        let output = root.path().join("output");
288        std::fs::create_dir_all(source.join("empty")).unwrap();
289        std::fs::create_dir(&output).unwrap();
290        std::fs::write(source.join("app"), [0, 255, 128]).unwrap();
291        std::fs::set_permissions(source.join("app"), std::fs::Permissions::from_mode(0o755))
292            .unwrap();
293        for name in [
294            ".env",
295            ".env.local",
296            ".stackless.env",
297            ".netrc",
298            ".vercel-token",
299            ".render-api-key",
300            ".cloudflare-api-token",
301            ".railway-token",
302            ".wordpress-com-token",
303            ".laravel-cloud-token",
304            ".gitlab-token",
305        ] {
306            std::fs::write(source.join(name), "credential-canary").unwrap();
307        }
308        std::fs::create_dir(source.join(".stackless-builds")).unwrap();
309        std::fs::write(
310            source.join(".stackless-builds/fly.toml"),
311            "APP_SECRET=private",
312        )
313        .unwrap();
314        std::fs::create_dir(source.join(".stackless-commands")).unwrap();
315        std::fs::write(
316            source.join(".stackless-commands/output"),
317            "prepare-secret-canary",
318        )
319        .unwrap();
320        let archive = SourceArchive::capture(&source).unwrap();
321        assert_eq!(archive.files.len(), 1);
322        archive.extract(&output).unwrap();
323        assert_eq!(std::fs::read(output.join("app")).unwrap(), [0, 255, 128]);
324        assert!(output.join("empty").is_dir());
325        assert_eq!(
326            std::fs::metadata(output.join("app"))
327                .unwrap()
328                .permissions()
329                .mode()
330                & 0o777,
331            0o700
332        );
333    }
334
335    #[test]
336    fn links_and_path_traversal_cannot_read_or_write_outside_the_source() {
337        let root = tempfile::tempdir().unwrap();
338        let source = root.path().join("source");
339        std::fs::create_dir(&source).unwrap();
340        let outside = root.path().join("outside");
341        std::fs::write(&outside, "private-canary").unwrap();
342        symlink(&outside, source.join("app")).unwrap();
343        assert!(SourceArchive::capture(&source).is_err());
344        for path in [
345            "../outside",
346            "/outside",
347            "a/../../outside",
348            ".ssh/key",
349            "a/.env",
350            "a\\outside",
351        ] {
352            let archive = SourceArchive {
353                directories: vec![],
354                files: vec![SourceFile {
355                    path: path.into(),
356                    executable: false,
357                    contents: STANDARD.encode("overwrite"),
358                }],
359            };
360            assert!(archive.extract(&source).is_err());
361        }
362        let archive = SourceArchive {
363            directories: vec![],
364            files: vec![SourceFile {
365                path: "app".into(),
366                executable: false,
367                contents: STANDARD.encode("overwrite"),
368            }],
369        };
370        assert!(archive.extract(&source).is_err());
371        assert_eq!(std::fs::read_to_string(outside).unwrap(), "private-canary");
372    }
373    #[test]
374    fn configured_root_cannot_escape_checkout_or_follow_directory_symlinks() {
375        use std::os::unix::fs::symlink;
376        let dir = tempfile::tempdir().unwrap();
377        let checkout = dir.path().join("checkout");
378        let outside = dir.path().join("private");
379        std::fs::create_dir_all(checkout.join("app")).unwrap();
380        std::fs::create_dir(&outside).unwrap();
381        std::fs::write(outside.join("secret"), "private-canary").unwrap();
382        std::fs::write(checkout.join("app/index.html"), "app").unwrap();
383        symlink(&outside, checkout.join("redirect")).unwrap();
384        for relative in [
385            Path::new("../private"),
386            outside.as_path(),
387            Path::new("redirect"),
388            Path::new("redirect/subdir"),
389        ] {
390            assert!(SourceArchive::capture_beneath(&checkout, relative).is_err());
391        }
392        let archive = SourceArchive::capture_beneath(&checkout, Path::new("./app")).unwrap();
393        assert_eq!(archive.files.len(), 1);
394        assert_eq!(archive.files[0].path, "index.html");
395        assert_eq!(STANDARD.decode(&archive.files[0].contents).unwrap(), b"app");
396    }
397}