forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·9.4 MiB·0d793e7·Tahinli·8 hours ago·359 commits
| 1 | use std::collections::HashSet; |
| 2 | use std::fs::FileType; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | |
| 5 | use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; |
| 6 | |
| 7 | const MAX_NAME_LEN: usize = 128; |
| 8 | const MAX_FILES: usize = 50; |
| 9 | |
| 10 | #[derive(Debug, thiserror::Error)] |
| 11 | pub enum ArtifactError { |
| 12 | #[error("invalid artifact pattern {0:?}: must be relative, without ..")] |
| 13 | Pattern(String), |
| 14 | #[error("invalid artifact glob: {0}")] |
| 15 | Glob(#[from] globset::Error), |
| 16 | #[error("cannot flatten artifact path {0:?} into a valid name")] |
| 17 | Name(String), |
| 18 | #[error("two artifacts flatten to the same name {0:?}")] |
| 19 | Duplicate(String), |
| 20 | #[error("artifact {name:?} is {size} bytes, over the {limit} byte limit")] |
| 21 | TooLarge { name: String, size: u64, limit: u64 }, |
| 22 | #[error("more than {MAX_FILES} artifacts matched")] |
| 23 | TooMany, |
| 24 | #[error("artifact io: {0}")] |
| 25 | Io(#[from] std::io::Error), |
| 26 | } |
| 27 | |
| 28 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 29 | pub struct Artifact { |
| 30 | pub name: String, |
| 31 | pub path: PathBuf, |
| 32 | } |
| 33 | |
| 34 | fn flatten_name(rel: &str) -> Result<String, ArtifactError> { |
| 35 | let joined = rel |
| 36 | .split('/') |
| 37 | .filter(|c| !c.is_empty()) |
| 38 | .collect::<Vec<_>>() |
| 39 | .join("_"); |
| 40 | let mut name: String = joined |
| 41 | .chars() |
| 42 | .map(|c| { |
| 43 | if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '-') { |
| 44 | c |
| 45 | } else { |
| 46 | '_' |
| 47 | } |
| 48 | }) |
| 49 | .collect(); |
| 50 | while name.starts_with('.') { |
| 51 | name.replace_range(0..1, "_"); |
| 52 | } |
| 53 | if name.is_empty() || name.len() > MAX_NAME_LEN { |
| 54 | return Err(ArtifactError::Name(rel.to_owned())); |
| 55 | } |
| 56 | Ok(name) |
| 57 | } |
| 58 | |
| 59 | fn check_pattern(pattern: &str) -> Result<(), ArtifactError> { |
| 60 | let bad = |
| 61 | pattern.is_empty() || pattern.starts_with('/') || pattern.split('/').any(|c| c == ".."); |
| 62 | if bad { |
| 63 | Err(ArtifactError::Pattern(pattern.to_owned())) |
| 64 | } else { |
| 65 | Ok(()) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | fn build_globs(patterns: &[String]) -> Result<GlobSet, ArtifactError> { |
| 70 | let mut builder = GlobSetBuilder::new(); |
| 71 | for p in patterns { |
| 72 | check_pattern(p)?; |
| 73 | builder.add(GlobBuilder::new(p).literal_separator(true).build()?); |
| 74 | } |
| 75 | Ok(builder.build()?) |
| 76 | } |
| 77 | |
| 78 | pub fn collect( |
| 79 | workspace: &Path, |
| 80 | patterns: &[String], |
| 81 | max_bytes_per_file: u64, |
| 82 | ) -> Result<Vec<Artifact>, ArtifactError> { |
| 83 | if patterns.is_empty() { |
| 84 | return Ok(Vec::new()); |
| 85 | } |
| 86 | let globs = build_globs(patterns)?; |
| 87 | let root = workspace.canonicalize()?; |
| 88 | |
| 89 | let mut found: Vec<(String, PathBuf)> = Vec::new(); |
| 90 | let mut stack: Vec<(PathBuf, String)> = vec![(root.clone(), String::new())]; |
| 91 | while let Some((dir, prefix)) = stack.pop() { |
| 92 | let mut entries: Vec<_> = std::fs::read_dir(&dir)?.collect::<Result<_, _>>()?; |
| 93 | entries.sort_by_key(|e| e.file_name()); |
| 94 | for entry in entries { |
| 95 | let file_name = entry.file_name(); |
| 96 | let Some(file_name) = file_name.to_str() else { |
| 97 | continue; |
| 98 | }; |
| 99 | let rel = if prefix.is_empty() { |
| 100 | file_name.to_owned() |
| 101 | } else { |
| 102 | format!("{prefix}/{file_name}") |
| 103 | }; |
| 104 | let file_type: FileType = entry.file_type()?; |
| 105 | if file_type.is_symlink() { |
| 106 | continue; |
| 107 | } |
| 108 | if file_type.is_dir() { |
| 109 | if file_name != ".git" { |
| 110 | stack.push((entry.path(), rel)); |
| 111 | } |
| 112 | } else if file_type.is_file() && globs.is_match(&rel) { |
| 113 | found.push((rel, entry.path())); |
| 114 | if found.len() > MAX_FILES { |
| 115 | return Err(ArtifactError::TooMany); |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | found.sort(); |
| 122 | |
| 123 | let mut seen = HashSet::new(); |
| 124 | let mut out = Vec::with_capacity(found.len()); |
| 125 | for (rel, path) in found { |
| 126 | let real = path.canonicalize()?; |
| 127 | if !real.starts_with(&root) { |
| 128 | continue; |
| 129 | } |
| 130 | let meta = std::fs::symlink_metadata(&real)?; |
| 131 | if !meta.is_file() { |
| 132 | continue; |
| 133 | } |
| 134 | let name = flatten_name(&rel)?; |
| 135 | if !seen.insert(name.clone()) { |
| 136 | return Err(ArtifactError::Duplicate(name)); |
| 137 | } |
| 138 | if meta.len() > max_bytes_per_file { |
| 139 | return Err(ArtifactError::TooLarge { |
| 140 | name, |
| 141 | size: meta.len(), |
| 142 | limit: max_bytes_per_file, |
| 143 | }); |
| 144 | } |
| 145 | out.push(Artifact { name, path: real }); |
| 146 | } |
| 147 | Ok(out) |
| 148 | } |
| 149 | |
| 150 | #[cfg(test)] |
| 151 | mod tests { |
| 152 | use super::*; |
| 153 | use std::os::unix::fs::symlink; |
| 154 | |
| 155 | fn ws_with(files: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) { |
| 156 | let dir = tempfile::tempdir().expect("tempdir"); |
| 157 | let ws = dir.path().join("ws"); |
| 158 | std::fs::create_dir_all(&ws).expect("mkdir"); |
| 159 | for (rel, body) in files { |
| 160 | let p = ws.join(rel); |
| 161 | std::fs::create_dir_all(p.parent().expect("parent")).expect("mkdir"); |
| 162 | std::fs::write(&p, body).expect("write"); |
| 163 | } |
| 164 | (dir, ws) |
| 165 | } |
| 166 | |
| 167 | fn names(found: &[Artifact]) -> Vec<&str> { |
| 168 | found.iter().map(|a| a.name.as_str()).collect() |
| 169 | } |
| 170 | |
| 171 | #[test] |
| 172 | fn flattening_maps_separators_and_hidden_names() { |
| 173 | assert_eq!( |
| 174 | flatten_name("dist/app/v1.tar.gz").expect("ok"), |
| 175 | "dist_app_v1.tar.gz" |
| 176 | ); |
| 177 | assert_eq!(flatten_name(".hidden/x").expect("ok"), "_hidden_x"); |
| 178 | assert_eq!(flatten_name("a b/c~d").expect("ok"), "a_b_c_d"); |
| 179 | assert!(flatten_name("").is_err()); |
| 180 | assert!(flatten_name(&"x".repeat(MAX_NAME_LEN + 1)).is_err()); |
| 181 | } |
| 182 | |
| 183 | #[test] |
| 184 | fn globs_match_inside_the_workspace() { |
| 185 | let (_dir, ws) = ws_with(&[ |
| 186 | ("dist/app.bin", "a"), |
| 187 | ("dist/sub/b.txt", "b"), |
| 188 | ("other.txt", "c"), |
| 189 | ]); |
| 190 | let found = collect(&ws, &["dist/**".to_owned()], 1024).expect("collect"); |
| 191 | assert_eq!(names(&found), vec!["dist_app.bin", "dist_sub_b.txt"]); |
| 192 | let found = collect(&ws, &["dist/*".to_owned()], 1024).expect("collect"); |
| 193 | assert_eq!(names(&found), vec!["dist_app.bin"]); |
| 194 | } |
| 195 | |
| 196 | #[test] |
| 197 | fn parent_directory_patterns_are_rejected() { |
| 198 | let (_dir, ws) = ws_with(&[("x.txt", "x")]); |
| 199 | assert!(matches!( |
| 200 | collect(&ws, &["../*".to_owned()], 1024), |
| 201 | Err(ArtifactError::Pattern(_)) |
| 202 | )); |
| 203 | assert!(matches!( |
| 204 | collect(&ws, &["/etc/passwd".to_owned()], 1024), |
| 205 | Err(ArtifactError::Pattern(_)) |
| 206 | )); |
| 207 | } |
| 208 | |
| 209 | #[test] |
| 210 | fn a_file_outside_the_workspace_is_never_reached() { |
| 211 | let (dir, ws) = ws_with(&[("x.txt", "x")]); |
| 212 | std::fs::write(dir.path().join("secret.txt"), "outside").expect("write"); |
| 213 | symlink(dir.path().join("secret.txt"), ws.join("link.txt")).expect("symlink"); |
| 214 | let found = collect(&ws, &["**".to_owned()], 1024).expect("collect"); |
| 215 | assert_eq!(names(&found), vec!["x.txt"]); |
| 216 | } |
| 217 | |
| 218 | #[test] |
| 219 | fn symlink_to_etc_is_skipped() { |
| 220 | let (_dir, ws) = ws_with(&[("dist/real.txt", "r")]); |
| 221 | symlink("/etc/passwd", ws.join("dist/passwd")).expect("symlink"); |
| 222 | symlink("/etc", ws.join("etc-dir")).expect("symlink"); |
| 223 | let found = collect(&ws, &["**".to_owned()], 1024).expect("collect"); |
| 224 | assert_eq!(names(&found), vec!["dist_real.txt"]); |
| 225 | } |
| 226 | |
| 227 | #[test] |
| 228 | fn oversized_files_are_refused() { |
| 229 | let (_dir, ws) = ws_with(&[("big.bin", "0123456789")]); |
| 230 | assert!(matches!( |
| 231 | collect(&ws, &["*.bin".to_owned()], 4), |
| 232 | Err(ArtifactError::TooLarge { .. }) |
| 233 | )); |
| 234 | } |
| 235 | |
| 236 | #[test] |
| 237 | fn colliding_flattened_names_are_refused() { |
| 238 | let (_dir, ws) = ws_with(&[("a/b.txt", "1"), ("a_b.txt", "2")]); |
| 239 | assert!(matches!( |
| 240 | collect(&ws, &["**".to_owned()], 1024), |
| 241 | Err(ArtifactError::Duplicate(_)) |
| 242 | )); |
| 243 | } |
| 244 | |
| 245 | #[test] |
| 246 | fn git_dir_is_not_collected() { |
| 247 | let (_dir, ws) = ws_with(&[(".git/config", "c"), ("keep.txt", "k")]); |
| 248 | let found = collect(&ws, &["**".to_owned()], 1024).expect("collect"); |
| 249 | assert_eq!(names(&found), vec!["keep.txt"]); |
| 250 | } |
| 251 | } |