spec_driven_docs/adapters/
fs.rs1use camino::Utf8Path;
8
9use crate::domain::ownership::Sha256;
10
11pub fn sha256_file(path: &Utf8Path) -> std::io::Result<Sha256> {
17 Ok(Sha256::of(&std::fs::read(path)?))
18}
19
20pub fn claim_run_dir(parent: &Utf8Path, stamp: &str) -> std::io::Result<camino::Utf8PathBuf> {
31 std::fs::create_dir_all(parent)?;
32 let mut counter = 1_u32;
33 loop {
34 let name = if counter == 1 {
35 stamp.to_string()
36 } else {
37 format!("{stamp}-{counter}")
38 };
39 let candidate = parent.join(name);
40 match std::fs::create_dir(&candidate) {
41 Ok(()) => return Ok(candidate),
42 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => counter += 1,
43 Err(error) => return Err(error),
44 }
45 }
46}
47
48pub fn write_file(path: &Utf8Path, bytes: &[u8]) -> std::io::Result<()> {
54 if let Some(parent) = path.parent() {
55 std::fs::create_dir_all(parent)?;
56 }
57 std::fs::write(path, bytes)
58}
59
60pub fn write_atomic(path: &Utf8Path, bytes: &[u8]) -> std::io::Result<()> {
75 use std::io::Write as _;
76 if let Some(parent) = path.parent() {
77 std::fs::create_dir_all(parent)?;
78 }
79 let scratch = path.with_extension(format!("{}.sdd-tmp", path.extension().unwrap_or_default()));
80 let mut file = std::fs::OpenOptions::new()
81 .write(true)
82 .create_new(true)
83 .open(&scratch)
84 .map_err(|error| {
85 std::io::Error::new(
86 error.kind(),
87 format!("{scratch}: {error}; remove the scratch file to retry"),
88 )
89 })?;
90 let written = file.write_all(bytes).and_then(|()| file.sync_all());
91 drop(file);
92 if let Err(error) = written {
93 let _ = std::fs::remove_file(&scratch);
94 return Err(error);
95 }
96 std::fs::rename(&scratch, path).inspect_err(|_| {
97 let _ = std::fs::remove_file(&scratch);
98 })
99}
100
101pub fn write_within(
112 target: &Utf8Path,
113 destination: &Utf8Path,
114 bytes: &[u8],
115) -> std::io::Result<()> {
116 check_destination(target, destination).map_err(|refusal| refused(destination, &refusal))?;
117 write_atomic(&target.join(destination), bytes)
118}
119
120pub fn remove_within(target: &Utf8Path, destination: &Utf8Path) -> std::io::Result<()> {
128 check_destination(target, destination).map_err(|refusal| refused(destination, &refusal))?;
129 std::fs::remove_file(target.join(destination))
130}
131
132fn refused(destination: &Utf8Path, refusal: &DestinationRefusal) -> std::io::Error {
133 std::io::Error::new(
134 std::io::ErrorKind::PermissionDenied,
135 format!("{destination}: {refusal}"),
136 )
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
141pub enum DestinationRefusal {
142 SymlinkEscape,
144 FileBlocksDirectory(String),
146 NotARegularFile,
148}
149
150impl std::fmt::Display for DestinationRefusal {
151 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152 match self {
153 Self::SymlinkEscape => f.write_str("reached through a symlink that leaves the target"),
154 Self::FileBlocksDirectory(blocked) => {
155 write!(f, "a file blocks a directory the write needs: {blocked}")
156 }
157 Self::NotARegularFile => f.write_str("exists and is not a regular file"),
158 }
159 }
160}
161
162pub fn check_destination(
171 target: &Utf8Path,
172 destination: &Utf8Path,
173) -> Result<(), DestinationRefusal> {
174 let mut prefix = target.to_path_buf();
175 let components: Vec<&str> = destination.as_str().split('/').collect();
176 for part in &components[..components.len().saturating_sub(1)] {
177 prefix.push(part);
178 if prefix.is_symlink() {
179 return Err(DestinationRefusal::SymlinkEscape);
180 }
181 if prefix.exists() && !prefix.is_dir() {
182 let blocked = prefix
183 .as_str()
184 .strip_prefix(target.as_str())
185 .map_or(prefix.as_str(), |rest| rest.trim_start_matches('/'));
186 return Err(DestinationRefusal::FileBlocksDirectory(blocked.to_string()));
187 }
188 }
189 let full = target.join(destination);
190 if full.is_symlink() {
191 return Err(DestinationRefusal::SymlinkEscape);
192 }
193 if full.exists() && !full.is_file() {
194 return Err(DestinationRefusal::NotARegularFile);
195 }
196 Ok(())
197}
198
199#[cfg(test)]
200mod tests {
201 #[test]
202 fn two_runs_in_one_second_each_claim_a_directory_of_their_own() {
203 let dir = tempfile::tempdir().unwrap();
204 let parent = camino::Utf8Path::from_path(dir.path())
205 .unwrap()
206 .join("snapshots");
207 let first = claim_run_dir(&parent, "20261009T213000Z").unwrap();
208 let second = claim_run_dir(&parent, "20261009T213000Z").unwrap();
209 let third = claim_run_dir(&parent, "20261009T213000Z").unwrap();
210 assert_eq!(first.file_name(), Some("20261009T213000Z"));
211 assert_eq!(second.file_name(), Some("20261009T213000Z-2"));
212 assert_eq!(third.file_name(), Some("20261009T213000Z-3"));
213 }
214
215 use camino::Utf8PathBuf;
216
217 use super::*;
218
219 fn root(dir: &tempfile::TempDir) -> Utf8PathBuf {
220 Utf8PathBuf::from(dir.path().to_str().unwrap())
221 }
222
223 #[test]
224 fn accepts_a_fresh_and_an_existing_regular_destination() {
225 let dir = tempfile::tempdir().unwrap();
226 let target = root(&dir);
227 assert_eq!(
228 check_destination(&target, Utf8Path::new("a/b/c.md")),
229 Ok(())
230 );
231 write_file(&target.join("a/b/c.md"), b"x").unwrap();
232 assert_eq!(
233 check_destination(&target, Utf8Path::new("a/b/c.md")),
234 Ok(())
235 );
236 }
237
238 #[test]
239 fn refuses_a_symlinked_component_and_a_symlinked_destination() {
240 let dir = tempfile::tempdir().unwrap();
241 let target = root(&dir);
242 let outside = tempfile::tempdir().unwrap();
243 std::os::unix::fs::symlink(outside.path(), target.join("a").as_std_path()).unwrap();
244 assert_eq!(
245 check_destination(&target, Utf8Path::new("a/c.md")),
246 Err(DestinationRefusal::SymlinkEscape)
247 );
248 std::os::unix::fs::symlink("/etc/hosts", target.join("link.md").as_std_path()).unwrap();
249 assert_eq!(
250 check_destination(&target, Utf8Path::new("link.md")),
251 Err(DestinationRefusal::SymlinkEscape)
252 );
253 }
254
255 #[test]
256 fn refuses_a_file_where_a_directory_is_needed_and_a_directory_destination() {
257 let dir = tempfile::tempdir().unwrap();
258 let target = root(&dir);
259 write_file(&target.join("a"), b"file").unwrap();
260 assert_eq!(
261 check_destination(&target, Utf8Path::new("a/c.md")),
262 Err(DestinationRefusal::FileBlocksDirectory("a".to_string()))
263 );
264 std::fs::create_dir(target.join("d.md")).unwrap();
265 assert_eq!(
266 check_destination(&target, Utf8Path::new("d.md")),
267 Err(DestinationRefusal::NotARegularFile)
268 );
269 }
270
271 #[test]
272 fn an_atomic_write_lands_the_bytes_and_leaves_no_scratch_file() {
273 let dir = tempfile::tempdir().unwrap();
274 let path = root(&dir).join("a/debt.yaml");
275 write_atomic(&path, b"first").unwrap();
276 write_atomic(&path, b"second").unwrap();
277 assert_eq!(std::fs::read(&path).unwrap(), b"second");
278 let siblings: Vec<_> = std::fs::read_dir(path.parent().unwrap())
279 .unwrap()
280 .filter_map(Result::ok)
281 .map(|entry| entry.file_name().to_string_lossy().to_string())
282 .collect();
283 assert_eq!(siblings, vec!["debt.yaml".to_string()]);
284 }
285
286 #[test]
287 fn a_pre_existing_scratch_symlink_is_refused_and_nothing_outside_is_touched() {
288 let dir = tempfile::tempdir().unwrap();
289 let target = root(&dir);
290 let outside = tempfile::tempdir().unwrap();
291 let victim = outside.path().join("victim");
292 std::fs::write(&victim, b"keep").unwrap();
293 std::os::unix::fs::symlink(&victim, target.join("debt.yaml.sdd-tmp").as_std_path())
294 .unwrap();
295 let error = write_atomic(&target.join("debt.yaml"), b"new").unwrap_err();
296 assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists);
297 assert_eq!(
298 std::fs::read(&victim).unwrap(),
299 b"keep",
300 "the scratch symlink was followed"
301 );
302 assert!(!target.join("debt.yaml").exists());
303 std::fs::remove_file(target.join("debt.yaml.sdd-tmp")).unwrap();
305 std::fs::write(target.join("debt.yaml.sdd-tmp"), b"stale").unwrap();
306 assert!(write_atomic(&target.join("debt.yaml"), b"new").is_err());
307 }
308
309 #[test]
310 fn a_write_within_refuses_a_symlinked_parent_before_any_byte_lands() {
311 let dir = tempfile::tempdir().unwrap();
312 let target = root(&dir);
313 let outside = tempfile::tempdir().unwrap();
314 std::os::unix::fs::symlink(outside.path(), target.join("docs").as_std_path()).unwrap();
315 let error = write_within(&target, Utf8Path::new("docs/x.md"), b"x").unwrap_err();
316 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
317 assert!(!outside.path().join("x.md").exists(), "the write escaped");
318 assert!(
319 remove_within(&target, Utf8Path::new("docs/x.md")).is_err(),
320 "the removal followed the symlink"
321 );
322 write_within(&target, Utf8Path::new("inside/x.md"), b"x").unwrap();
323 assert_eq!(std::fs::read(target.join("inside/x.md")).unwrap(), b"x");
324 }
325
326 #[test]
327 fn hashes_match_the_domain_digest() {
328 let dir = tempfile::tempdir().unwrap();
329 let path = root(&dir).join("x");
330 write_file(&path, b"payload").unwrap();
331 assert_eq!(sha256_file(&path).unwrap(), Sha256::of(b"payload"));
332 }
333}