team-ljyzipelo

공개

출력 폴더 임시 파일 실패 시 시스템 임시 폴더로 되돌리고 남은 파일을 정리 실패로 알림

리뷰 대응(PR #132).

- 출력 폴더에 임시 파일을 만들지 못하면(읽기 전용, 공간 부족 등) 그 작업의 남은
  임시 파일은 기존 시스템 임시 폴더에 만든다. 손상된 압축파일과 읽기 전용 출력
  폴더가 함께 주어져도 기존 순서대로 Integrity를 보고한다.
- O_TMPFILE 미지원 대체 경로에서 이름을 지우지 못하면 핸들을 닫고 한 번 더 지운다.
  그래도 남으면 Terminal.cleanup을 Failed로 보고해 남은 임시 파일 안내를 표시하고,
  이후 임시 파일은 시스템 임시 폴더에서 계속 만든다.
- 회귀 시험: 손상된 7z + 0500 출력 폴더 → Integrity, 대체 이름 unlink 거부 → 완료 +
  cleanup Failed + 남은 파일 1개. io_fault에 fallback-unlink-denied 모드를 추가했다.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
작성자
LeeJunyoung
작성 시각
커밋
ccb80fd381780ee39825cdd158e767fdd3e2a9c7
부모
97cc563
이 시점의 파일 보기

변경된 파일 6개

+98-5
수정experiments/rust-archive-worker/src/filesystem.rs+5-0
@@ -335,6 +335,11 @@ mod platform {
335335 let file = open(&self.file, std::ffi::OsStr::new(&n), 2 | 0x40 | 0x80)
336336 .map_err(crate::space::io_error)?;
337337 if !self.remove(&n) {
338추가: // 핸들을 닫고 한 번 더 지움. 그래도 남으면 정리 실패로 기록해 결과에 알림.
339추가: drop(file);
340추가: if !self.remove(&n) && !self.absent(&n).unwrap_or(false) {
341추가: crate::spool::note_leftover();
342추가: }
338343 return Err(ErrorCode::Io);
339344 }
340345 if file.metadata().map_err(|_| ErrorCode::Io)?.nlink() != 0 {
수정experiments/rust-archive-worker/src/runtime.rs+4-0
@@ -1259,6 +1259,10 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
12591259 Some(ErrorCode::Internal)
12601260 }
12611261 };
1262추가: // 출력 폴더의 임시 파일 이름을 지우지 못했으면 남은 파일이 있다고 알림.
1263추가: if crate::spool::take_leftover() {
1264추가: context.terminal.cleanup = Cleanup::Failed;
1265추가: }
12621266 let mut state = state
12631267 .lock()
12641268 .map_err(|_| std::io::Error::other("worker state poisoned"))?;
수정experiments/rust-archive-worker/src/spool.rs+24-4
@@ -12,6 +12,8 @@ thread_local! {
1212 // 작업 스레드가 지정한 임시 파일 위치. 없으면 시스템 임시 폴더를 사용함.
1313 static LOCATION: std::cell::RefCell<Option<filesystem::Dir>> =
1414 const { std::cell::RefCell::new(None) };
15추가: // 출력 폴더에 이름 있는 임시 파일을 만든 뒤 이름을 지우지 못했는지 기록함.
16추가: static LEFTOVER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1517}
1618
1719/// 해제 작업의 임시 파일을 출력 폴더에 두도록 지정함. 반환값이 사라지면 해제됨.
@@ -25,9 +27,22 @@ impl Drop for Location {
2527pub(crate) fn place_in(dir: &filesystem::Dir) -> Result<Location> {
2628 let dir = dir.duplicate()?;
2729 LOCATION.with(|location| *location.borrow_mut() = Some(dir));
30추가: LEFTOVER.with(|leftover| leftover.set(false));
2831 Ok(Location(()))
2932}
3033
34추가: /// 출력 폴더에 지우지 못한 임시 파일이 남았음을 기록함. Windows 임시 파일은 닫으면 지워지므로
35추가: /// Linux 대체 이름 경로에서만 사용함.
36추가: #[cfg(target_os = "linux")]
37추가: pub(crate) fn note_leftover() {
38추가: LEFTOVER.with(|leftover| leftover.set(true));
39추가: }
40추가:
41추가: /// 작업 중 출력 폴더에 임시 파일이 남았는지 확인하고 기록을 비움.
42추가: pub(crate) fn take_leftover() -> bool {
43추가: LEFTOVER.with(|leftover| leftover.replace(false))
44추가: }
45추가:
3146pub(crate) fn random_name() -> Result<String> {
3247 let mut random = [0; 16];
3348 crate::crypto::random(&mut random)?;
@@ -36,11 +51,16 @@ pub(crate) fn random_name() -> Result<String> {
3651
3752/// 이름 없는 임시 파일을 만듦. 해제 작업에서는 출력 폴더에, 그 외에는 시스템 임시 폴더에 둠.
3853/// 출력 폴더에 두면 공간 판단이 실제 출력 디스크와 같아지고 /tmp 크기나 할당량에 묶이지 않음.
54추가: /// 출력 폴더에 만들지 못하면(읽기 전용, 공간 부족 등) 이 작업의 남은 임시 파일은 모두
55추가: /// 기존 시스템 임시 폴더에 둠. 그러면 동작과 오류 우선순위가 이전과 같아지며, 출력 폴더
56추가: /// 문제는 원래의 출력 확인 지점에서 보고됨.
3957pub(crate) fn temporary() -> Result<File> {
40삭제: if let Some(file) =
41삭제: LOCATION.with(|location| location.borrow().as_ref().map(filesystem::Dir::temporary))
42삭제: {
43삭제: return file;
58추가: let placed =
59추가: LOCATION.with(|location| location.borrow().as_ref().map(filesystem::Dir::temporary));
60추가: match placed {
61추가: Some(Ok(file)) => return Ok(file),
62추가: Some(Err(_)) => LOCATION.with(|location| *location.borrow_mut() = None),
63추가: None => {}
4464 }
4565 #[cfg(target_os = "linux")]
4666 {
수정tests/rust-archive-worker/hardening.rs+22-0
@@ -824,6 +824,28 @@ mod linux {
824824 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 1);
825825 assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024);
826826 }
827추가: #[test]
828추가: fn destination_fallback_unlink_failure_reports_cleanup_and_moves_to_system_temp() {
829추가: let s = Scratch::new();
830추가: generate(&s, "store", 1024 * 1024);
831추가: let request = start(&s, false, Limits::default().output);
832추가: let child = spawn(&s, request, Some("fallback-unlink-denied"));
833추가: assert_eq!(wait(child.id()).0, 0);
834추가: let events = events(&s);
835추가: let t = terminal(&events);
836추가: // 이름을 지우지 못한 대체 임시 파일은 정리 실패로 알리고, 남은 작업은 시스템 임시 폴더에서 계속함.
837추가: assert_eq!(t.outcome, Outcome::Completed, "{events:?}");
838추가: assert_eq!(t.cleanup, Cleanup::Failed, "{events:?}");
839추가: assert!(s.0.join("paused").exists());
840추가: let leftovers = fs::read_dir(s.0.join("output"))
841추가: .unwrap()
842추가: .map(|entry| entry.unwrap().file_name().into_string().unwrap())
843추가: .filter(|name| name.starts_with(".zipelo-"))
844추가: .count();
845추가: assert_eq!(leftovers, 1, "첫 시도의 대체 임시 파일 하나만 남아야 함");
846추가: assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
847추가: assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024);
848추가: }
827849 struct Subreaper(i32);
828850 impl Subreaper {
829851 fn new() -> Self {
수정tests/rust-archive-worker/io_fault.c+14-1
@@ -26,6 +26,15 @@ __attribute__((constructor)) static void initialize(void) {
2626 real_fstatvfs = dlsym(RTLD_NEXT, "fstatvfs");
2727}
2828
29추가: /* 출력 폴더 임시 파일의 대체 이름(.zipelo-<hex 32>.tmp). 게시 임시 이름(.zipelo-<pid>-<n>.tmp)은 제외함. */
30추가: static int spool_name(const char *path) {
31추가: size_t length = strlen(path);
32추가: if (length != 44 || strncmp(path, ".zipelo-", 8) || strcmp(path + 40, ".tmp")) return 0;
33추가: for (size_t i = 8; i < 40; i++)
34추가: if (!strchr("0123456789abcdef", path[i])) return 0;
35추가: return 1;
36추가: }
37추가:
2938static int output_file(int fd) {
3039 char link[64], path[4096];
3140 snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
@@ -57,7 +66,7 @@ int openat(int fd, const char *path, int flags, ...) {
5766 errno = ENOSPC;
5867 return -1;
5968 }
60삭제: if (fault && !strcmp(fault, "fallback")) {
69추가: if (fault && (!strcmp(fault, "fallback") || !strcmp(fault, "fallback-unlink-denied"))) {
6170 int marker = real_openat(AT_FDCWD, getenv("ZIPELO_TEST_MARKER"), O_CREAT | O_WRONLY, 0600);
6271 if (marker >= 0) close(marker);
6372 errno = EOPNOTSUPP;
@@ -193,6 +202,10 @@ int unlinkat(int fd, const char *path, int flags) {
193202 errno = EACCES;
194203 return -1;
195204 }
205추가: if (fault && !strcmp(fault, "fallback-unlink-denied") && spool_name(path)) {
206추가: errno = EACCES;
207추가: return -1;
208추가: }
196209 int (*real_unlinkat)(int, const char *, int) = dlsym(RTLD_NEXT, "unlinkat");
197210 return real_unlinkat(fd, path, flags);
198211}
수정tests/rust-archive-worker/spool_location.rs+29-0
@@ -72,3 +72,32 @@ fn encrypted_extract_spools_in_destination_when_system_temp_is_unusable() {
7272 );
7373 assert_only_outputs(&s, &["payload.bin"]);
7474}
75추가:
76추가: #[test]
77추가: fn corrupt_archive_error_wins_over_read_only_destination() {
78추가: // 출력 폴더에 임시 파일을 만들 수 없으면 시스템 임시 폴더를 써서 기존 오류 우선순위를 유지함.
79추가: // 손상된 압축파일은 권한 문제가 아니라 손상으로 안내해야 함.
80추가: let bytes = seven_fixture("bad-trailing.7z");
81추가: let writable = Scratch::new();
82추가: let baseline = extract(
83추가: &writable,
84추가: &bytes,
85추가: None,
86추가: Selection::All,
87추가: None,
88추가: Limits::default(),
89추가: );
90추가: assert_eq!(terminal(&baseline).error, ErrorCode::Integrity);
91추가:
92추가: use std::os::unix::fs::PermissionsExt;
93추가: let s = Scratch::new();
94추가: let output = s.0.join("output");
95추가: fs::create_dir(&output).unwrap();
96추가: fs::set_permissions(&output, fs::Permissions::from_mode(0o500)).unwrap();
97추가: let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
98추가: fs::set_permissions(&output, fs::Permissions::from_mode(0o700)).unwrap();
99추가: assert_eq!(terminal(&events).error, ErrorCode::Integrity, "{events:?}");
100추가: assert_eq!(terminal(&events).publication, Publication::None);
101추가: assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
102추가: assert_eq!(fs::read_dir(&output).unwrap().count(), 0);
103추가: }