압축 보안 회귀 검사와 폴더 게시 수용 기준을 추가함
- 작성자
- 코노모리 카논
- 작성 시각
- 커밋
c19f1c5b472aa23c624b1ae69d0e4660988d9fc5- 부모
- ee76385
변경된 파일 61개
+2,759-0변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.
| @@ -0,0 +1,49 @@ | ||
| 1 | 추가: # Runtime/Worker와 OS별 회귀 검토 | |
| 2 | 추가: | |
| 3 | 추가: ## 실행 증거와 범위 | |
| 4 | 추가: | |
| 5 | 추가: 2026-11-09 UTC 기준 담당 테스트와 검토 문서의 기록임. Core/Runtime/Worker와 UI 구현은 읽기 검토만 수행함. 현재 C#은 Core 41개, 기존 Runtime 21개, 메모리 해제 26개, 폴더 게시 10개로 총 98개 등록 상태임. 로컬 .NET SDK가 없어 최신 C# 컴파일과 실행은 미실행임. | |
| 6 | 추가: | |
| 7 | 추가: - 로컬 Ubuntu 26.04.1 LTS x86_64에서 `python3 -B tests/run_checks.py`의 샘플/정적/실행기 검사 33개 통과 기록이 있음. 실제 C# 작업자나 네이티브 게시의 통과 근거가 아님. | |
| 8 | 추가: - 총괄의 Windows round5 보고에서 이전 C# 62개가 통과함. 새 ZIP 파일 내용, 기존 파일/입력 충돌 보존과 부모/최종 symlink 거부에 관한 결과임. | |
| 9 | 추가: - round6은 `2026-11-09T14:44:04.604469Z`의 src/tests 102개 파일 고정 스냅샷임. 총괄 보고상 Desktop/Core/Runtime/Worker 빌드 경고/오류 0, Core41 통과, Runtime56은 CS0266 컴파일 실패로 전부 미실행임. 당시 폴더 게이트는 전체 실패 폐쇄였음. | |
| 10 | 추가: - CS0266은 `ExtractionPublicationTests.cs`의 `DirectoryInfo info;`를 `FileSystemInfo info;`로 한 줄 수정하여 별도 전달함. 단독 패치 SHA-256은 `3e2eab3a0a61de4aa967f79a87240e5eae067e81cbe5708575a8f59524049ab5`임. 현재 파일은 후속 플랫폼 계약 변경까지 포함하므로 이 단독 패치와 구분해야 함. | |
| 11 | 추가: - 현재 98개 전체와 Windows 새 폴더 게시, Ubuntu 각 LTS의 C# 실행 결과는 아직 없음. 등록 수, 소스 검토, 과거 스냅샷 통과와 현재 실행을 합산하지 않음. | |
| 12 | 추가: | |
| 13 | 추가: [플랫폼 행렬](../tests/security/platform_matrix.json), [해제 수용 범위](../tests/extraction/coverage.json)와 [폴더 소스 검토](../tests/extraction/folder_publication_review.json)에 보고 출처, 검토 소스 해시 및 미실행 조건을 남김. | |
| 14 | 추가: | |
| 15 | 추가: ## 새 폴더 플랫폼 계약 | |
| 16 | 추가: | |
| 17 | 추가: `NewFolderPublisher.IsSupportedPlatform`은 Windows/Linux x64의 구현 진입 여부임. 일반 UI의 `SupportsSafeExtraction=false`나 실제 저장 환경의 지원 판정과 별개로 검사함. Windows는 로컬 NTFS 및 현재 사용자/SYSTEM/Administrators 쓰기 경계, Linux는 부모 fd의 mount ID/장치 번호와 검증된 procfs mountinfo의 ext4 또는 xfs 유형 일치, 현재 euid 소유, 그룹/기타 쓰기 금지를 요구함. Linux의 openat2/statx/renameat2와 procfs 확인 실패는 실패 폐쇄임. | |
| 18 | 추가: | |
| 19 | 추가: ext2/ext3/ext4가 공유하는 `0xEF53`만으로 ext4를 판별할 수 없다는 검토를 backend에 전달함. 이후 XFS만 허용한 임시 수정이 있었고, 최신 구현은 부모 fd의 mount ID/장치/유형 대조를 추가함. ext2/ext3 유형과 일치하지 않는 마운트 정보는 임시 폴더 생성 전에 거부함. 이는 소스 변경 확인이며 실제 마운트별 실행 증거가 아님. [statfs 식별값](https://man7.org/linux/man-pages/man2/statfs.2.html) | |
| 20 | 추가: | |
| 21 | 추가: [FolderEnvironment](../tests/runtime/FolderEnvironment.cs)는 테스트가 새로 만든 부모의 저장 조건을 제품 API와 별도로 조회함. Windows는 관리형 ACL 조회와 드라이브 정보를 사용하고, Linux는 statfs/statx와 현재 스레드 mountinfo를 대조함. 조회된 조건이 지원 범위라면 `folder.platform_contract`도 실제 게시 성공과 트리/파일 해시를 요구함. 알려진 미지원 조건이면 새 목적지, 기존 원본 파일과 기존 폴더를 대상으로 정확한 실패 오류, 바이트 보존 및 임시 항목 부재를 요구함. [관리형 ACL 조회 계약](https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemaclextensions.getaccesscontrol?view=net-10.0), [드라이브 정보](https://learn.microsoft.com/en-us/dotnet/api/system.io.driveinfo?view=net-10.0) | |
| 22 | 추가: | |
| 23 | 추가: 저장 전제조건이 미충족인 환경에서 새 폴더 성공, 충돌, 최종 링크 및 동시 게시 수용 검사는 SKIP으로 기록하며 PASS에 합산하지 않음. 제품 `PublishAsync`가 실패했다는 이유로 SKIP하지 않음. 예상 지원 조건에서 게시가 실패하면 FAIL임. 사전 취소, 변조 내용, 실패한 해제 결과와 부모 symlink 거부는 저장 파일시스템 미지원과 분리함. 심볼릭 링크 생성 권한 부족도 해당 사례의 SKIP으로 남김. | |
| 24 | 추가: | |
| 25 | 추가: 테스트 환경 관찰은 보안 경계를 구현하는 코드가 아님. 제품의 부모 핸들 고정, procfs 대체 방어, inode/파일 ID 재검증, 네이티브 원자성이나 경합 안전성을 이 관찰만으로 증명하지 않음. 권한 변경과 새 마운트 없이 관찰하지 못한 부정 조건은 미검증임. 한 번의 플랫폼 계약 통과를 모든 파일시스템/ACL 분기 통과로 표시하면 안 됨. | |
| 26 | 추가: | |
| 27 | 추가: ## 보존, 무결성과 취소 | |
| 28 | 추가: | |
| 29 | 추가: 기존 Core 및 단일 ZIP 게시 62개의 성공/오류 기대값을 변경하지 않음. 비정상 응답 상태와 `Completed + Error`는 `EngineFailure` 및 생성물 폐기를 요구하며 backend 수정이 반영된 소스를 확인함. 이 두 사례의 이전 Windows 통과 보고는 해당 고정 스냅샷에 한정함. | |
| 30 | 추가: | |
| 31 | 추가: 해제는 자체 생성한 작은 ZIP 22개로 정상 Stored/Deflate 내용과 SHA-256, 경로 이탈/절대 경로, 파일-폴더 충돌 양방향, OS 이름/대소문자, 링크 타입/메타데이터, CRC/길이 손상, 누적 항목/처리/출력 예산을 검사함. 제품은 별도 작업자에서 실제 디코딩 길이와 CRC를 직접 확인함. `.NET`이 CRC를 자동 검증한다고 가정하지 않음. 메모리 해제 완료를 디스크 게시 완료로 표시하지 않음. | |
| 32 | 추가: | |
| 33 | 추가: 폴더 수용 검사는 새 트리 전체 항목과 파일 바이트, 원본과 기존 대상의 해시/표식, 기존 링크와 링크 대상 보존, 잔류 임시 이름 및 `CleanupFailed`를 각각 검사함. 실패 오류를 `OutputUnavailable` 등 여러 값 중 아무거나 허용하도록 바꾸지 않음. 폴더 쓰기 전에 이미 취소된 요청과 입력 복사 중 결정적 취소를 실제 쓰기 중 취소의 증거로 사용하지 않음. | |
| 34 | 추가: | |
| 35 | 추가: [동시 게시 검사](../tests/runtime/FolderConcurrencyTests.cs)는 서로 다른 내용의 두 요청을 같은 최종 이름으로 시작함. 정확히 한 성공과 한 `OutputConflict`, 패자 임시 정리, 승자 트리/해시, 원본 및 출력 부모 밖 표식 보존을 요구함. 시작 장벽은 있으나 네이티브 rename 호출의 정확한 겹침은 강제하지 않음. 아직 실제 실행하지 않았음. | |
| 36 | 추가: | |
| 37 | 추가: ## 남은 위험과 검사 | |
| 38 | 추가: | |
| 39 | 추가: - Windows 자식 핸들 종료 후 rename 및 충돌 후 재개방/파일 ID 검사와 삭제, Linux 이름 확인 후 unlinkat는 실제 검증이 필요함. 실행 사용자 전체나 관리자 계정이 장악된 상황까지 방어한다고 주장하지 않음. | |
| 40 | 추가: - Linux mkdir 성공 후 핸들 획득 실패는 `unboundCreation`과 정리 실패 보고로 연결된 소스를 확인함. 결정적 실패 주입과 실제 잔존 이름/외부 표식 보존은 미검증임. | |
| 41 | 추가: - 실제 경로 교체, junction/hardlink, 외부 항목 삽입, 마운트/namespace/procfs 변경, 쓰기 중 취소, 늦은 취소, 정리 실패, 강제 종료와 전원 손실은 별도 검증이 남음. | |
| 42 | 추가: - 입력 16 MiB, 프레임 32 MiB와 항목/출력 예산은 프로세스 메모리 상한이 아님. ZIP 중앙 디렉터리 할당, JSON/Base64/배열 복사, 메타데이터 파싱 비용과 동기 네이티브 I/O의 강제 종료 한계가 남음. Windows Job Object/Linux 자원 제한과 대용량 지원을 검증했다고 표시하지 않음. | |
| 43 | 추가: - `WorkerPlatform`의 앱 기준 절대 경로는 배포 폴더 신뢰를 전제로 함. 실행 파일 무결성, 설치 패키지, JAR 제외 및 동의 없는 기본 연결 변경 금지는 실제 설치 환경에서 별도 검증이 필요함. | |
| 44 | 추가: | |
| 45 | 추가: ## 재실행과 브랜치 범위 | |
| 46 | 추가: | |
| 47 | 추가: 승인된 .NET 10 SDK 환경에서 `python3 -B tests/run_checks.py --core --runtime`로 실행함. 테스트 코드, 대역, 샘플과 빌드/실행 임시 자료는 루트 tests/ 아래에 둠. `tests/security/.work`와 bin/obj, 로그, 내부 잠금 및 개인 설정은 소스 브랜치에서 제외함. 파일시스템과 환경 관찰, PASS/FAIL/SKIP 수 및 소스 해시를 함께 남겨야 함. | |
| 48 | 추가: | |
| 49 | 추가: `features/archive-security-tests`에는 tests/와 이 문서 및 SECURITY_REVIEW만 포함함. Core/Runtime/Worker 소스가 있는 별도 기능 브랜치와 UI 정적 검사의 UI 소스가 통합되어야 전체 검사를 실행할 수 있음. C# 미실행 상태를 draft PR에 명시하며 일반 해제 활성화나 main 병합은 이 변경의 범위가 아님. |
| @@ -0,0 +1,179 @@ | ||
| 1 | 추가: # Zipelo Core 보안 검토 | |
| 2 | 추가: | |
| 3 | 추가: ## 기록 범위와 최신 상태 | |
| 4 | 추가: | |
| 5 | 추가: 아래 1~8장은 최초 Core 29개 단계의 역사적 소스 검토임. 그 시점의 미구현 설명, 예상 결함과 행 번호를 최신 제품 상태로 해석하지 않음. 암호 요청 직렬화, 초기화 정리와 게시 계약의 후속 수정은 [CORE_FIXES](CORE_FIXES.md)에 기록되어 있으며, 작업자 분리와 ZIP 목록/생성/메모리 해제 및 조건부 폴더 게시 구현이 이후 추가됨. | |
| 6 | 추가: | |
| 7 | 추가: 최신 테스트는 Core 41개와 Runtime 57개로 총 98개 등록 상태임. 총괄 보고상 Windows 이전 62개는 통과했고 round6 고정 스냅샷은 Core41 통과, Runtime56 컴파일 실패로 미실행임. CS0266 타입 수정은 별도 전달했지만 최신 98개의 C# 컴파일 및 실제 OS 실행은 이 검토자가 수행하지 않았음. Python 샘플/정적 검사를 네이티브 검증으로 계산하지 않음. | |
| 8 | 추가: | |
| 9 | 추가: 현재 게시 계약과 미검증 조건은 [Runtime 검토](RUNTIME_SECURITY_REVIEW.md), [플랫폼 행렬](../tests/security/platform_matrix.json), [폴더 검토 기록](../tests/extraction/folder_publication_review.json)을 기준으로 확인함. 일반 해제 capability/UI는 비활성 상태임. | |
| 10 | 추가: | |
| 11 | 추가: ## 최초 검토 원문 | |
| 12 | 추가: | |
| 13 | 추가: 검토일: 2026-11-09. 대상: 현재 로컬 Core 소스와 C# 회귀 테스트 29개. 검토 방식: 소스, 호출 흐름, 테스트 대역과 단언문 대조. 제품 코드와 테스트는 변경하거나 실행하지 않았다. | |
| 14 | 추가: | |
| 15 | 추가: ## 1. 결론과 판단 범위 | |
| 16 | 추가: | |
| 17 | 추가: 문자열 경로 차단, 동일 작업의 출력 이름 충돌 검사, 실제 복사량 누적, 실패 후 출력 확정 차단, 암호 콜백 종료 시 폐기 로직은 존재한다. 그러나 실제 저장 계층, 압축 엔진, 작업자 격리와 강제 종료는 없다. 따라서 목적지 밖 쓰기 방지, 원본 불변, 제한 시간 내 중단을 제품 차원에서 보장할 수 없다. | |
| 18 | 추가: | |
| 19 | 추가: 현재 앱은 [App.xaml.cs 10행](../src/Zipelo.Desktop/App.xaml.cs#L10)에서 `UnavailableWorkspace`를 사용한다. [WorkspacePort.cs 48행](../src/Zipelo.Desktop/WorkspacePort.cs#L48)은 사용 가능 상태를 false로 반환한다. 아래 높은 우선순위 항목은 실제 엔진 연결 전 해소할 결함 또는 구현 공백이며, 현재 제품에서 공격이 재현되었다는 뜻은 아니다. | |
| 20 | 추가: | |
| 21 | 추가: - 우선순위 높음: 실제 저장 시 링크와 경로 교체 방어 부재, 처리량 계측 밖의 엔진 작업, 강제 시간 제한과 취소 완료 보장 부재, 출력 확정 도중 실패의 결과 계약 부족. | |
| 22 | 추가: - 우선순위 보통: 동시 암호 요청의 시도 번호와 상태 경합, 잘못된 제한값에 대한 정리 경로 누락, 정리 실패 시 원래 오류 소실. | |
| 23 | 추가: - C# 29개는 등록 수와 내용을 확인했으며 컴파일과 실행은 미실행이다. 통과 또는 실패 수를 산출하지 않았다. | |
| 24 | 추가: | |
| 25 | 추가: ## 2. 경로와 실제 파일 생성 | |
| 26 | 추가: | |
| 27 | 추가: ### 2.1 문자열 정책과 작업 안의 충돌 검사 | |
| 28 | 추가: | |
| 29 | 추가: [OutputPathPolicy.cs 8행](../src/Zipelo.Core/OutputPathPolicy.cs#L8)은 길이 제한, 구분자 변환, 빈 세그먼트, `.`과 `..`, 끝의 공백과 점, 비정규화 Unicode, 제어 문자, 콜론과 기타 금지 문자, Windows 예약 이름을 검사한다. 절대 경로, 드라이브 상대 경로, UNC와 장치 경로는 이 규칙에 걸리도록 구성되어 있다. 이 함수는 파일시스템을 열거나 최종 목적지를 확인하지 않는다. | |
| 30 | 추가: | |
| 31 | 추가: [EngineContext.cs 72행](../src/Zipelo.Core/EngineContext.cs#L72)은 항목 종류가 일반 파일이 아니면 쓰기를 거부한다. 이 동작은 어댑터가 링크 항목을 올바르게 분류한다는 전제다. 기존 목적지의 링크를 탐지하는 동작과는 별개이며 빈 디렉터리 생성도 현재 허용하지 않는다. | |
| 32 | 추가: | |
| 33 | 추가: [EngineContext.cs 78행](../src/Zipelo.Core/EngineContext.cs#L78)은 정책을 통과한 경로를 대소문자 무시 비교로 확인하여 같은 이름과 파일/자식 경로 충돌을 거부한다. 예를 들어 `Readme.txt`와 `README.TXT`, `file`과 `file/child`의 순서 두 가지가 검사 대상이다. 실패 후 `Failure`와 항목 결과를 남기므로 엔진이 해당 예외를 삼켜도 [ArchiveJob.cs 62행](../src/Zipelo.Core/ArchiveJob.cs#L62)이 출력 확정을 막는다. | |
| 34 | 추가: | |
| 35 | 추가: 이 검사는 현재 작업이 등록한 문자열끼리의 비교다. 기존 파일, 다른 작업의 출력, 파일시스템 별칭, 원본과 출력의 동일 파일 여부는 검사하지 않는다. 경로 목록 전체를 매번 순회하므로 출력 파일 수가 n개일 때 비교 횟수는 누적하여 O(n²)이며, 대량의 빈 파일에도 비용이 발생한다. 실제 성능 영향은 측정하지 않았다. | |
| 36 | 추가: | |
| 37 | 추가: ### 2.2 높은 우선순위: 저장 계층의 보호는 미구현 | |
| 38 | 추가: | |
| 39 | 추가: [ArchiveContracts.cs 62행](../src/Zipelo.Core/ArchiveContracts.cs#L62)에 핸들 기준 링크/junction, 경로 교체 경쟁, 기존 파일 충돌과 원본 보존 의무가 주석으로 선언되어 있다. 실제 제품 구현은 오류만 반환하는 [UnavailableOutput 71행](../src/Zipelo.Core/ArchiveContracts.cs#L71)뿐이다. | |
| 40 | 추가: | |
| 41 | 추가: 따라서 안전한 문자열 `folder/file.txt`도 목적지의 `folder`가 외부를 가리키거나 검사 이후 교체되는 경우에 안전하다는 근거가 없다. 실제 출력이 없는 현재 상태에서 목적지 이탈을 재현한 것은 아니며, 문자열 검사를 통과했다는 이유로 일반 파일 생성 API에 바로 전달하면 안 된다. | |
| 42 | 추가: | |
| 43 | 추가: 필요한 후속 작업은 루트부터 최종 파일까지 실제 객체의 경계를 유지하는 저장 계층, 기존 대상의 비덮어쓰기, 원본과의 동일성 확인, 작업 소유 임시 파일만 정리하는 수명 규칙이다. 실제 생성과 출력 확정 시점 모두에 적용해야 한다. | |
| 44 | 추가: | |
| 45 | 추가: 연동 전 수용 기준은 기존 심볼릭 링크, junction, 하드 링크 별칭, 부모 경로 교체, 최종 파일 교체, 동시 작업 충돌에서 외부 및 기존 파일의 목록과 내용이 유지되는 것이다. 테스트 영역 안에 가짜 외부 목적지를 만들고 실제 Windows 저장 구현을 검증해야 한다. 해당 검사는 아직 없다. | |
| 46 | 추가: | |
| 47 | 추가: ## 3. 자원 예산과 취소 | |
| 48 | 추가: | |
| 49 | 추가: ### 3.1 지금 적용되는 예산 | |
| 50 | 추가: | |
| 51 | 추가: [JobBudget.cs 18행](../src/Zipelo.Core/JobBudget.cs#L18)은 양수 제한값을 요구한다. [53행](../src/Zipelo.Core/JobBudget.cs#L53)의 잠금과 잔여량 비교는 동시 청구와 정수 오버플로를 고려한다. 제한을 넘긴 뒤 `exhausted`를 유지하여 후속 작업이 예산을 재사용하지 못하게 한다. | |
| 52 | 추가: | |
| 53 | 추가: [EngineContext.cs 93행](../src/Zipelo.Core/EngineContext.cs#L93)은 헤더의 선언 크기 대신 읽은 바이트 수를 처리량과 출력량에 누적한 뒤 목적지에 쓴다. 항목마다 예산 인스턴스를 새로 만들지 않는다. 따라서 이 경로를 통해 목적지에 넘기는 바이트는 청구에 성공한 양으로 제한된다. | |
| 54 | 추가: | |
| 55 | 추가: 다만 읽기가 청구보다 먼저다. 최대 65,536바이트 버퍼에 반환된 마지막 덩어리가 제한을 넘으면 그 덩어리는 출력되지 않지만 이미 읽힌 뒤이며 사용량에는 반영되지 않는다. 디코더가 그 읽기를 준비하며 수행한 선행 해제량이나 메모리 사용까지 같은 값이라고 해석하면 안 된다. | |
| 56 | 추가: | |
| 57 | 추가: ### 3.2 높은 우선순위: 엔진 내부 처리와 메모리의 계측 공백 | |
| 58 | 추가: | |
| 59 | 추가: [JobBudget.cs 49행](../src/Zipelo.Core/JobBudget.cs#L49)은 중간 TAR, 솔리드 선행 처리와 복구 재시도를 같은 예산에 청구하도록 요구하지만, 강제하는 실행 경로는 없다. 엔진이 디코딩을 끝내고 작은 스트림만 넘기거나 목록만 보고하면 앞선 작업량은 Core가 알 수 없다. 이는 임의의 외부 코드가 안전 경계를 돌파했다는 발견이 아니라, 신뢰하는 어댑터에 필요한 계측 의무가 아직 구현되지 않았다는 뜻이다. | |
| 60 | 추가: | |
| 61 | 추가: [EngineContext.cs 40행](../src/Zipelo.Core/EngineContext.cs#L40)의 목록 경로는 항목 수만 청구한다. [Register 166행](../src/Zipelo.Core/EngineContext.cs#L166)은 ID 중복과 선언 크기는 검사하지만 목록 이름과 ID의 길이, 전체 메타데이터 크기를 제한하지 않는다. `JobLimits`에도 메모리와 CPU 한도는 없다. 파서 단계의 할당은 Core 등록보다 먼저 발생할 수 있다. | |
| 62 | 추가: | |
| 63 | 추가: 필요한 후속 검증은 단계 전환, 중첩 TAR, 솔리드 선행 처리, 암호 재시도와 복구 재시도의 합산, 큰 메타데이터와 메모리 할당, 마지막 청구 실패 덩어리의 의미다. 현재 중간 처리 테스트는 대역이 직접 `ChargeProcessed(2, ...)`를 호출하는 경우만 다룬다. | |
| 64 | 추가: | |
| 65 | 추가: ### 3.3 높은 우선순위: 시간 제한과 취소 완료는 협력에 의존 | |
| 66 | 추가: | |
| 67 | 추가: [JobBudget.cs 37행](../src/Zipelo.Core/JobBudget.cs#L37)은 호출될 때만 경과 시간을 검사한다. [ArchiveJob.cs 31행](../src/Zipelo.Core/ArchiveJob.cs#L31)은 호출자 취소 토큰만 연결하며 시간 초과를 예약하지 않는다. 엔진 실행, 읽기, 쓰기, 검증, 암호 제공자, 출력 확정과 정리 중 어느 하나가 반환하지 않으면 다음 검사도 실행되지 않는다. `DisposeAsync`에는 취소 토큰 인자조차 없다. | |
| 68 | 추가: | |
| 69 | 추가: 사용자 취소는 `Cancelling` 이벤트로 전달되고, 협력하는 호출이 취소 예외를 반환하면 [ArchiveJob.cs 78행](../src/Zipelo.Core/ArchiveJob.cs#L78)이 `Cancelled`로 처리한다. [85행](../src/Zipelo.Core/ArchiveJob.cs#L85)의 정리를 기다린 다음 종료 이벤트를 보내는 흐름은 존재한다. 그러나 멈춘 디코더나 정리를 일정 시간 안에 종료시키는 작업자 감독과 강제 종료는 없다. 마지막 `budget.Check` 이후 오래 걸린 출력 확정은 시간 제한을 넘겨도 성공으로 끝날 수 있다. | |
| 70 | 추가: | |
| 71 | 추가: 시간 초과 시 토큰 취소만 추가해도 비협력 작업은 멈추지 않는다. 후속 설계에는 작업자 종료 확인, 정리의 소유권과 제한 시간, 사용자 취소와 시간 초과의 구분, 암호 입력 대기 시간을 예산에 포함할지에 대한 정책이 필요하다. 종료를 기다리는 쪽만 포기하고 작업자가 계속 쓰게 해서는 안 된다. | |
| 72 | 추가: | |
| 73 | 추가: 기존 테스트는 시작 전 취소, 복사 도중 토큰 취소, 출력 확정 직전 토큰 확인을 다룬다. 멈춘 호출, 취소 무시, 확정 완료와 취소의 경합, 정리 지연 및 실제 프로세스 종료 검사는 없다. 가짜 시계를 사용하는 예산 테스트도 `Check`를 직접 호출하므로 시간에 따른 자동 중단의 증거가 아니다. | |
| 74 | 추가: | |
| 75 | 추가: ## 4. 출력 확정, 검증 상태와 원본 불변 | |
| 76 | 추가: | |
| 77 | 추가: ### 4.1 높은 우선순위: 출력 일부 확정 후 실패를 표현할 계약 부족 | |
| 78 | 추가: | |
| 79 | 추가: [ArchiveJob.cs 71행](../src/Zipelo.Core/ArchiveJob.cs#L71)은 `CommitAsync` 전체가 반환해야 `committed`를 true로 바꾼다. 실패하면 [93행](../src/Zipelo.Core/ArchiveJob.cs#L93)이 모든 `Staged` 항목을 실패로 바꾼다. 인터페이스는 취소 후 게시 금지를 명시하지만 일반 입출력 오류 시 전체 원복이나 항목별 확정 결과를 반환하는 방식은 명시하지 않는다. | |
| 80 | 추가: | |
| 81 | 추가: 정적 시나리오는 두 파일 중 첫 파일을 최종 위치로 옮긴 뒤 두 번째 파일에서 저장 오류가 발생하는 경우다. 원복이 보장되지 않는 저장 구현이라면 실제 첫 파일이 남았는데 결과는 전부 실패로 표시된다. 현재 저장 구현이 없으므로 실제 디스크에서 재현한 결함은 아니다. `JobState.Partial`은 선언되어 있지만 현재 `ArchiveJob`에서 선택되지 않는다. | |
| 82 | 추가: | |
| 83 | 추가: 저장 계층 구현 전에 전체 확정 실패 시 작업 소유 결과를 원복할지, 부분 확정을 지원하고 항목별 실제 결과를 반환할지 결정해야 한다. 기존 파일 보존과 함께 출력 확정 중 디스크 부족, 파일 충돌, 취소, 비정상 종료의 결과 정확성을 검사해야 한다. | |
| 84 | 추가: | |
| 85 | 추가: ### 4.2 정리 실패가 주 오류를 덮어씀 | |
| 86 | 추가: | |
| 87 | 추가: [ArchiveJob.cs 87행](../src/Zipelo.Core/ArchiveJob.cs#L87)은 정리 예외가 발생하면 이미 정한 오류를 항상 `OutputUnavailable`로 바꾼다. 무결성 실패 후 정리 실패가 이어지면 원래 `IntegrityFailure`는 작업 오류에서 사라진다. 항목에 기록된 오류가 남을 수도 있으나 두 오류를 모두 설명하는 계약은 없다. | |
| 88 | 추가: | |
| 89 | 추가: 출력 확정이 성공한 후 정리만 실패한 경우에는 전체 작업이 `Failed`인 동시에 확정된 항목은 `Extracted`로 유지된다. 이를 원복 완료로 안내해서는 안 된다. 주 오류, 정리 오류, 확정된 결과를 각각 보존하는 표현이 필요하다. 현재 `CleanupFailure` 테스트는 출력이 없는 작업만 사용하므로 이 두 조합을 검증하지 않는다. | |
| 90 | 추가: | |
| 91 | 추가: ### 4.3 무결성 검증과 작업 완료를 구분해야 함 | |
| 92 | 추가: | |
| 93 | 추가: [EngineContext.cs 108행](../src/Zipelo.Core/EngineContext.cs#L108)은 검증 콜백이 `Failed`이면 확정을 막고, `Unavailable` 또는 `NotChecked`이면 해당 상태를 보존한 채 확정할 수 있다. [CoreTests.cs 242행](../tests/security/CoreTests.cs#L242)은 `Unavailable`인 항목의 작업 완료를 의도적으로 기대한다. 따라서 `Completed`는 CRC 또는 인증 검증 통과를 뜻하지 않는다. | |
| 94 | 추가: | |
| 95 | 추가: Core가 CRC나 암호 인증을 계산하지는 않는다. 검증 콜백의 정확성, 검증 가능한 형식에서 `NotChecked`를 허용할지, 부분 복구 결과의 표시 정책은 어댑터와 UI 연결 시 확정해야 한다. 현재 `Verify` 작업의 항목별 검증 결과를 추가하는 별도 API도 없으므로 이 기능의 완성을 주장할 수 없다. | |
| 96 | 추가: | |
| 97 | 추가: ### 4.4 원본 보존의 실제 보장 범위 | |
| 98 | 추가: | |
| 99 | 추가: [ArchiveJob.cs 49행](../src/Zipelo.Core/ArchiveJob.cs#L49)은 입력이 읽기 가능하고 쓰기 불가능한지 확인한다. Core는 입력에 쓰거나 입력 수명을 종료하는 호출을 하지 않는다. 다만 원본 파일을 여는 계층, 공유 방식, 출력과 원본의 파일 동일성 검사, 복구 사본 생성은 없다. | |
| 100 | 추가: | |
| 101 | 추가: 입력 스트림 객체는 그대로 어댑터에 전달된다. 경로 문자열을 별도 인자로 넘기지 않는다는 계약은 프로세스 격리나 파일 접근 권한 제한과 같지 않으며, `FileStream` 같은 구체 객체가 가진 정보를 감추는 래퍼도 없다. 엔진 어댑터는 신뢰하는 코드라는 전제가 필요하다. | |
| 102 | 추가: | |
| 103 | 추가: [CoreTests.cs 424행](../tests/security/CoreTests.cs#L424)은 샘플 사본의 SHA-256, 표식 파일과 파일 수를 비교하도록 작성되어 있다. 출력은 메모리 대역이므로 실제 출력이 원본을 덮는 경우, 하드 링크로 같은 파일을 가리키는 경우, 복구 실패와 저장 공간 부족에서 원본 보존을 입증하지 못한다. 이 C# 테스트 자체도 실행하지 않았다. | |
| 104 | 추가: | |
| 105 | 추가: ## 5. 암호 수명과 요청 경합 | |
| 106 | 추가: | |
| 107 | 추가: ### 5.1 지금 존재하는 보호 | |
| 108 | 추가: | |
| 109 | 추가: [ArchiveContracts.cs 42행](../src/Zipelo.Core/ArchiveContracts.cs#L42)은 반환된 `SecureString`의 소유권을 Core로 넘기도록 한다. [EngineContext.cs 154행](../src/Zipelo.Core/EngineContext.cs#L154)의 `using`은 암호가 전달된 뒤 정상 종료, 소비자 예외 또는 취소 검사 실패로 범위를 벗어날 때 폐기한다. null 응답은 작업 취소로 연결한다. 작업별 시도 제한과 요청 ID도 존재한다. | |
| 110 | 추가: | |
| 111 | 추가: Core의 이벤트와 결과 타입은 암호를 포함하지 않고 예외 원문 대신 오류 코드를 사용한다. 현재 `src/`를 읽고 관련 호출을 검색했을 때 암호의 로그, 명령행, 환경변수와 영구 파일 기록 경로는 발견하지 않았다. 이는 실제 IPC, 엔진 변환 코드, 덤프와 외부 관찰 검증을 대신하지 않는다. | |
| 112 | 추가: | |
| 113 | 추가: `using`은 콜백이 끝나야 실행된다. 제공자가 반환하지 않으면 제공자 소유 암호를 Core가 정리할 수 없고, 소비자가 멈추면 Core가 소유한 암호의 폐기도 지연된다. 소비자가 만든 평문 복사본과 네이티브 버퍼 수명도 관리하지 않는다. 폐기 후 접근이 실패한다는 테스트는 메모리에 모든 복사본이 사라졌다는 증거가 아니다. | |
| 114 | 추가: | |
| 115 | 추가: ### 5.2 구현 결함: 동시 요청의 시도 번호와 상태 경합 | |
| 116 | 추가: | |
| 117 | 추가: [EngineContext.cs 144행](../src/Zipelo.Core/EngineContext.cs#L144)은 `Interlocked.Increment`의 반환값을 저장하지 않는다. [154행](../src/Zipelo.Core/EngineContext.cs#L154)에서 요청을 만들 때 공유 필드 `passwordAttempts`를 다시 읽는다. 두 호출이 각각 카운터를 1과 2로 올린 뒤 첫 호출이 요청을 만들면 두 요청 모두 시도 번호 2를 받을 수 있다. | |
| 118 | 추가: | |
| 119 | 추가: 암호 요청은 항목 처리용 `serial`을 사용하지 않는다. 하나의 요청이 끝나면 다른 요청이 대기 중이어도 `Running` 상태를 보낼 수 있다. 전체 시도 횟수 제한을 우회한다는 주장은 아니며, 동시 호출 시 요청 표시와 작업 상태가 잘못될 수 있다는 결함이다. 현재 인터페이스에는 암호 요청 동시 실행을 금지하는 명시적 계약도 없다. | |
| 120 | 추가: | |
| 121 | 추가: [MainWindow.xaml.cs 205행](../src/Zipelo.Desktop/MainWindow.xaml.cs#L205)은 이미 암호창이 있으면 null을 반환한다. 두 인터페이스가 그대로 연결되면 겹친 요청이 사용자 취소처럼 처리될 가능성도 있으나, 현재 Core/UI 어댑터가 없어 동작을 재현하지 않았다. | |
| 122 | 추가: | |
| 123 | 추가: 후속 수정안은 증가 결과를 지역값으로 보존하고 요청을 작업별로 직렬화하거나 동시 요청을 명시적으로 거부하는 것이다. 요청별 응답 귀속, 취소 후 늦은 응답 폐기, 종료 시 남은 암호 폐기를 함께 정의해야 한다. 기존 테스트는 순차 시도 번호와 서로 다른 요청 ID만 확인한다. | |
| 124 | 추가: | |
| 125 | 추가: ## 6. 작업 초기화와 미리보기 | |
| 126 | 추가: | |
| 127 | 추가: ### 6.1 구현 결함: 제한값 오류가 출력 정리 범위 밖에서 발생 | |
| 128 | 추가: | |
| 129 | 추가: [ArchiveJob.cs 25행](../src/Zipelo.Core/ArchiveJob.cs#L25)에서 일회 실행 표시를 설정한 후 [30행](../src/Zipelo.Core/ArchiveJob.cs#L30)에서 제한값을 검증한다. 이 검증은 출력 정리를 보장하는 try/finally보다 앞에 있다. 잘못된 `JobLimits`로 호출하면 예외가 바로 전파되고 전달된 출력 트랜잭션의 정리와 종료 이벤트가 수행되지 않는다. | |
| 130 | 추가: | |
| 131 | 추가: 이는 잘못된 호스트 설정에서 발생하는 수명 계약 결함이며 악성 압축파일만으로 유발됨을 확인한 것은 아니다. 생성자에서 제한을 먼저 검증하거나 출력 소유권을 넘겨받은 뒤의 초기화를 정리 범위에 포함해야 한다. [CoreTests.cs 100행](../tests/security/CoreTests.cs#L100)은 `JobBudget` 자체의 잘못된 값만 검사하므로 `ArchiveJob` 정리 누락을 다루지 않는다. | |
| 132 | 추가: | |
| 133 | 추가: ### 6.2 미리보기는 구현 검증 대상이 아직 없음 | |
| 134 | 추가: | |
| 135 | 추가: [EngineContext.cs 67행](../src/Zipelo.Core/EngineContext.cs#L67)은 `Preview`에서 추출용 쓰기를 허용하지 않는다. [CoreTests.cs 416행](../tests/security/CoreTests.cs#L416)은 이 호출이 거부되는지만 검사한다. 렌더러, 파일 형식 판별, 외부 리소스 차단, 평문 임시 파일 수명과 별도 프로세스는 구현되어 있지 않다. | |
| 136 | 추가: | |
| 137 | 추가: 현재 소스에서 자동 외부 실행과 통신 호출을 발견하지 않았다는 사실을, 향후 미리보기의 실행 및 통신 차단 검증 통과로 해석하면 안 된다. 렌더러가 마련된 뒤 위장 확장자, HTML/SVG, 외부 URL, 큰 이미지 및 종료 후 임시 파일을 실제로 관찰해야 한다. | |
| 138 | 추가: | |
| 139 | 추가: ## 7. C# 29개 테스트의 검토 결과 | |
| 140 | 추가: | |
| 141 | 추가: [CoreTests.Cases 12행](../tests/security/CoreTests.cs#L12)에 등록된 29개를 아래처럼 대조했다. 다음 수는 작성된 사례 수이며 실행 통과 수가 아니다. | |
| 142 | 추가: | |
| 143 | 추가: 1. 경로 2개: 정상 상대 경로와 Unicode, 경로 이탈과 Windows 이름 규칙. 문자열 정책만 검사하며 실제 파일 생성 없음. | |
| 144 | 추가: 2. 예산 단독 4개: 경계와 소진 유지, 음수와 오버플로, 수동 시계 경계, 병렬 청구. 자동 시간 초과와 프로세스 자원 제한 없음. | |
| 145 | 추가: 3. 작업 기본 4개: 쓰기 가능 입력 거부, 미연결 엔진, 미연결 출력, 작업 재사용 거부. 초기화 실패 뒤 출력 정리 검증 없음. | |
| 146 | 추가: 4. 출력 6개: 경로 사전 차단, 압축 내부 링크 분류 거부, 대소문자와 부모 충돌, 저장 계층 충돌 전달, 무결성 실패 후 미확정, 검증 불가 상태 유지. 실제 기존 파일과 링크/junction 검증 없음. | |
| 147 | 추가: 5. 작업 예산 3개: 헤더와 무관한 실제 복사량, 수동 중간 처리와 항목 누적, 삼킨 경로 오류 후 확정 금지. 마지막 사례 이름은 `budget.swallowed_failure_cannot_commit`이지만 입력은 경로 오류이며 예산 예외를 삼키는 사례는 아님. | |
| 148 | 추가: 6. 취소 3개: 시작 전, 복사 중, 출력 확정 직전. 취소 완료 시간, 비협력 호출, 확정 후 취소와 종료 경합 없음. | |
| 149 | 추가: 7. 관찰자와 정리 2개: 관찰자 예외 격리, 출력이 없는 작업의 정리 실패. 정리 지연과 원래 오류 보존, 확정 후 정리 실패 없음. | |
| 150 | 추가: 8. 암호 3개: null 취소, 정상/예외 종료의 폐기, 순차 시도 제한과 요청 ID. 동시 요청, 제공자/소비자 대기 중 취소, 늦은 응답과 다른 작업 재사용 없음. | |
| 151 | 추가: 9. 미리보기 1개: 추출용 쓰기 API 거부. 실행, 네트워크와 렌더링 검증 없음. | |
| 152 | 추가: 10. 샘플 1개: 내부에서 정상, 경로 이탈 두 종류, 충돌 두 종류, 링크, 잘린 ZIP의 7개 시나리오를 다룸. 입력 SHA-256과 메모리 출력을 비교하도록 작성됨. 제품 압축 엔진 검사가 아님. | |
| 153 | 추가: | |
| 154 | 추가: [TestSupport.cs 50행](../tests/security/TestSupport.cs#L50)의 `EngineStub`은 테스트 함수를 호출하는 대역이고, [72행](../tests/security/TestSupport.cs#L72)의 `RecordingOutput`은 메모리에서 확정 여부를 기록한다. 특히 `ExistingConflict`는 실제 파일을 만들지 않고 `CreateError = OutputConflict`를 주입한다. `CancelBeforeCommit`도 대역이 직접 토큰을 확인한다. 테스트 이름만으로 저장 계층이 안전하다고 판단할 수 없다. | |
| 155 | 추가: | |
| 156 | 추가: CRC 손상 샘플은 C# 샘플 루프에 포함되지 않는다. 무결성 실패 테스트는 콜백에 `VerificationState.Failed`를 주입하므로 실제 CRC 또는 인증 검출을 확인하지 않는다. 기존 Python 샘플 검사는 샘플 자체의 손상 확인에 해당한다. | |
| 157 | 추가: | |
| 158 | 추가: [Program.cs 13행](../tests/security/Program.cs#L13)은 테스트 작업 경로와 기존 reparse point를 사전 검사한다. 이 검사는 테스트 실행의 기본 경로 제한이며 악의적인 동시 경로 교체 방어의 증거가 아니다. [tests/run_checks.py 72행](../tests/run_checks.py#L72)의 실행에는 시간 제한이 없으므로 향후 멈추는 대역 테스트를 추가할 때 외부 종료 한도도 필요하다. | |
| 159 | 추가: | |
| 160 | 추가: ## 8. 후속 결정과 검증 순서 | |
| 161 | 추가: | |
| 162 | 추가: 현재 라운드는 문서 검토만 수행한다. 아래는 미해결 범위의 담당과 수용 기준이며 구현 요청의 재배정 또는 완료 선언이 아니다. | |
| 163 | 추가: | |
| 164 | 추가: - 백엔드: 실제 저장 계층의 경계와 비덮어쓰기, 원본 동일성, 출력 확정과 부분 실패 계약을 먼저 정한다. 실제 파일시스템에서도 항목 결과와 남은 파일이 일치해야 한다. | |
| 165 | 추가: - 백엔드: 엔진 내부 누적 계측, 메타데이터와 메모리 제한, 작업자 종료 및 정리 한도를 정한다. 취소 완료는 작업자가 더 쓰지 못함을 확인한 뒤 표시해야 한다. | |
| 166 | 추가: - 백엔드와 프론트엔드: 암호 요청의 직렬화, 늦은 응답 폐기, 검증 불가와 부분 결과 표시를 연결 계약에 반영한다. UI 상세 계획 문서의 소유권은 프론트엔드에 있다. | |
| 167 | 추가: - 버그픽스: 구현 계약이 정해지면 동시 암호 요청, 초기화 실패 정리, 복합 오류, 부분 확정, 예산 외 작업과 취소 지연의 회귀 사례를 추가한다. 현재 `tests/`는 보존했다. | |
| 168 | 추가: - 승인된 .NET/Windows 검증 환경: 기존 29개의 컴파일과 실행부터 확인한 뒤 실제 저장, 엔진, IPC와 미리보기 검증을 진행한다. 이번에는 VM 복사, 빌드, 실행과 패키지 설치를 시도하지 않았다. | |
| 169 | 추가: | |
| 170 | 추가: ## 9. 확인 근거와 변경 범위 | |
| 171 | 추가: | |
| 172 | 추가: - 저장소 루트와 origin이 `/home/user/projects/zipelo`, `Team-LJY/zipelo`에 일치함을 Git으로 확인했다. 브랜치는 `docs/initial-project-plan`, 아직 커밋이 없는 상태다. 브랜치를 전환하지 않았다. | |
| 173 | 추가: - Core 소스 5개, 프로젝트 설정, C# 테스트와 대역 및 실행기, 기존 `coverage.json`을 읽고 관련 Desktop 호출을 대조했다. `Cases`의 등록 항목은 29개다. | |
| 174 | 추가: - `dotnet`은 현재 PATH에 없다. 제품 빌드, Python/C# 테스트와 Windows 검증은 이번 라운드에서 모두 미실행이다. | |
| 175 | 추가: - [coverage.json](../tests/security/coverage.json)에 기록된 이전 Python 15개 통과와 C# 미실행 상태를 확인했다. 이전 기록을 이번 실행 결과로 계산하지 않는다. | |
| 176 | 추가: - 이번 변경은 이 문서 하나다. 작성 직전 공유 잠금 안에서 Git 상태와 대상 파일 부재, 검토한 `src/`와 `tests/` 내용의 불변을 다시 확인했다. | |
| 177 | 추가: - 검토 스냅샷의 `src/` 16개 파일 묶음 SHA-256: `ad1cfede4e30c8adacd868a54f81e5367ed0ce29e8fff4cab75364c87d1d6e78`. | |
| 178 | 추가: - 검토 스냅샷의 `tests/` 19개 파일 묶음 SHA-256: `fa73e172adde3c97bb88d7b90b8ce5f6c3ae50e491d00425f938e09350e0b672`. | |
| 179 | 추가: - 묶음 해시는 정렬한 각 파일의 프로젝트 상대 경로 UTF-8, NUL 바이트, 파일 바이트를 순서대로 SHA-256에 넣어 계산했다. 파일이 바뀌면 위 행 번호와 판단을 다시 확인해야 한다. |
| @@ -0,0 +1,125 @@ | ||
| 1 | 추가: import hashlib | |
| 2 | 추가: import importlib.util | |
| 3 | 추가: import io | |
| 4 | 추가: import json | |
| 5 | 추가: from pathlib import Path | |
| 6 | 추가: import stat | |
| 7 | 추가: import struct | |
| 8 | 추가: import unittest | |
| 9 | 추가: import zipfile | |
| 10 | 추가: import zlib | |
| 11 | 추가: | |
| 12 | 추가: | |
| 13 | 추가: DIRECTORY = Path(__file__).resolve().parent | |
| 14 | 추가: SPEC = importlib.util.spec_from_file_location("zipelo_extraction_factory", DIRECTORY / "fixture_factory.py") | |
| 15 | 추가: FACTORY = importlib.util.module_from_spec(SPEC) | |
| 16 | 추가: SPEC.loader.exec_module(FACTORY) | |
| 17 | 추가: | |
| 18 | 추가: | |
| 19 | 추가: class ExtractionFixtureTests(unittest.TestCase): | |
| 20 | 추가: def test_samples_and_manifest_are_reproducible(self): | |
| 21 | 추가: samples = FACTORY.build_samples() | |
| 22 | 추가: self.assertEqual(22, len(samples)) | |
| 23 | 추가: self.assertEqual(set(samples), {path.name for path in (DIRECTORY / "fixtures").iterdir()}) | |
| 24 | 추가: for name, data in samples.items(): | |
| 25 | 추가: with self.subTest(name=name): | |
| 26 | 추가: path = DIRECTORY / "fixtures" / name | |
| 27 | 추가: self.assertFalse(path.is_symlink()) | |
| 28 | 추가: self.assertEqual(data, path.read_bytes()) | |
| 29 | 추가: self.assertLessEqual(len(data), FACTORY.MAX_SAMPLE_BYTES) | |
| 30 | 추가: self.assertEqual(FACTORY.build_manifest(samples), json.loads((DIRECTORY / "fixtures.json").read_text())) | |
| 31 | 추가: | |
| 32 | 추가: def test_normal_contents_and_hashes_for_both_methods(self): | |
| 33 | 추가: samples = FACTORY.build_samples() | |
| 34 | 추가: manifest = FACTORY.build_manifest(samples) | |
| 35 | 추가: for name in ("normal-stored.zip", "normal-deflated.zip"): | |
| 36 | 추가: with self.subTest(name=name), zipfile.ZipFile(io.BytesIO(samples[name])) as zipped: | |
| 37 | 추가: self.assertEqual(4, len(zipped.infolist())) | |
| 38 | 추가: self.assertTrue(zipped.getinfo("nested/").is_dir()) | |
| 39 | 추가: for entry, expected in manifest["normal_files"].items(): | |
| 40 | 추가: data = zipped.read(entry) | |
| 41 | 추가: self.assertEqual(expected["bytes"], len(data)) | |
| 42 | 추가: self.assertEqual(expected["sha256"], hashlib.sha256(data).hexdigest()) | |
| 43 | 추가: | |
| 44 | 추가: def test_unsafe_names_are_metadata_only(self): | |
| 45 | 추가: samples = FACTORY.build_samples() | |
| 46 | 추가: expected = { | |
| 47 | 추가: "traversal.zip": "../escape.txt", | |
| 48 | 추가: "backslash-traversal.zip": "..\\escape.txt", | |
| 49 | 추가: "absolute-posix.zip": "/escape.txt", | |
| 50 | 추가: "absolute-drive.zip": "C:/escape.txt", | |
| 51 | 추가: "absolute-unc.zip": "//server/share/escape.txt", | |
| 52 | 추가: } | |
| 53 | 추가: for name, entry in expected.items(): | |
| 54 | 추가: with self.subTest(name=name), zipfile.ZipFile(io.BytesIO(samples[name])) as zipped: | |
| 55 | 추가: self.assertEqual([entry], zipped.namelist()) | |
| 56 | 추가: | |
| 57 | 추가: def test_conflicts_and_os_names_remain_distinct(self): | |
| 58 | 추가: samples = FACTORY.build_samples() | |
| 59 | 추가: expected = { | |
| 60 | 추가: "duplicate.zip": ["same.txt", "same.txt"], | |
| 61 | 추가: "file-before-child.zip": ["node", "node/child"], | |
| 62 | 추가: "child-before-file.zip": ["node/child", "node"], | |
| 63 | 추가: "case-distinct.zip": ["Readme.txt", "README.TXT"], | |
| 64 | 추가: "linux-names.zip": ["CON", "name:stream"], | |
| 65 | 추가: } | |
| 66 | 추가: for name, entries in expected.items(): | |
| 67 | 추가: with self.subTest(name=name), zipfile.ZipFile(io.BytesIO(samples[name])) as zipped: | |
| 68 | 추가: self.assertEqual(entries, zipped.namelist()) | |
| 69 | 추가: self.assertIsNone(zipped.testzip()) | |
| 70 | 추가: | |
| 71 | 추가: def test_link_metadata_without_live_filesystem_links(self): | |
| 72 | 추가: samples = FACTORY.build_samples() | |
| 73 | 추가: with zipfile.ZipFile(io.BytesIO(samples["symlink.zip"])) as zipped: | |
| 74 | 추가: self.assertTrue(stat.S_ISLNK(zipped.infolist()[0].external_attr >> 16)) | |
| 75 | 추가: with zipfile.ZipFile(io.BytesIO(samples["special-fifo.zip"])) as zipped: | |
| 76 | 추가: self.assertTrue(stat.S_ISFIFO(zipped.infolist()[0].external_attr >> 16)) | |
| 77 | 추가: with zipfile.ZipFile(io.BytesIO(samples["unix-hardlink.zip"])) as zipped: | |
| 78 | 추가: item = zipped.infolist()[0] | |
| 79 | 추가: self.assertTrue(stat.S_ISREG(item.external_attr >> 16)) | |
| 80 | 추가: tag, size = struct.unpack_from("<HH", item.extra) | |
| 81 | 추가: self.assertEqual(0x000D, tag) | |
| 82 | 추가: self.assertEqual(12 + len(b"../sentinel.txt"), size) | |
| 83 | 추가: self.assertEqual(b"../sentinel.txt", item.extra[16:]) | |
| 84 | 추가: self.assertEqual(0, item.file_size) | |
| 85 | 추가: | |
| 86 | 추가: def test_crc_damage_is_independent_of_lengths(self): | |
| 87 | 추가: samples = FACTORY.build_samples() | |
| 88 | 추가: for name in ("bad-payload-crc.zip", "bad-header-crc.zip"): | |
| 89 | 추가: with self.subTest(name=name), zipfile.ZipFile(io.BytesIO(samples[name])) as zipped: | |
| 90 | 추가: self.assertEqual(len(FACTORY.PAYLOAD), zipped.infolist()[0].file_size) | |
| 91 | 추가: self.assertEqual("payload.txt", zipped.testzip()) | |
| 92 | 추가: | |
| 93 | 추가: def test_length_damage_preserves_decoded_payload_and_crc(self): | |
| 94 | 추가: samples = FACTORY.build_samples() | |
| 95 | 추가: for name, declared in (("length-smaller.zip", len(FACTORY.PAYLOAD) - 1), | |
| 96 | 추가: ("length-larger.zip", len(FACTORY.PAYLOAD) + 1)): | |
| 97 | 추가: data = samples[name] | |
| 98 | 추가: central = data.index(b"PK\x01\x02") | |
| 99 | 추가: with self.subTest(name=name): | |
| 100 | 추가: self.assertEqual(declared, struct.unpack_from("<I", data, 22)[0]) | |
| 101 | 추가: self.assertEqual(declared, struct.unpack_from("<I", data, central + 24)[0]) | |
| 102 | 추가: compressed = struct.unpack_from("<I", data, 18)[0] | |
| 103 | 추가: start = 30 + sum(struct.unpack_from("<HH", data, 26)) | |
| 104 | 추가: decoded = zlib.decompress(data[start:start + compressed], -15) | |
| 105 | 추가: self.assertEqual(FACTORY.PAYLOAD, decoded) | |
| 106 | 추가: self.assertNotEqual(declared, len(decoded)) | |
| 107 | 추가: self.assertEqual(zlib.crc32(decoded), struct.unpack_from("<I", data, 14)[0]) | |
| 108 | 추가: self.assertEqual(zlib.crc32(decoded), struct.unpack_from("<I", data, central + 16)[0]) | |
| 109 | 추가: | |
| 110 | 추가: def test_header_disagreement_and_truncation_are_separate(self): | |
| 111 | 추가: samples = FACTORY.build_samples() | |
| 112 | 추가: data = samples["local-central-length.zip"] | |
| 113 | 추가: central = data.index(b"PK\x01\x02") | |
| 114 | 추가: self.assertNotEqual(struct.unpack_from("<I", data, 22)[0], struct.unpack_from("<I", data, central + 24)[0]) | |
| 115 | 추가: with self.assertRaises(zipfile.BadZipFile): | |
| 116 | 추가: zipfile.ZipFile(io.BytesIO(samples["truncated.zip"])) | |
| 117 | 추가: | |
| 118 | 추가: def test_cumulative_sample_needs_aggregate_budget(self): | |
| 119 | 추가: with zipfile.ZipFile(io.BytesIO(FACTORY.build_samples()["cumulative.zip"])) as zipped: | |
| 120 | 추가: self.assertEqual([8, 8], [item.file_size for item in zipped.infolist()]) | |
| 121 | 추가: self.assertEqual(16, sum(len(zipped.read(item)) for item in zipped.infolist())) | |
| 122 | 추가: | |
| 123 | 추가: | |
| 124 | 추가: if __name__ == "__main__": | |
| 125 | 추가: unittest.main() |
| @@ -0,0 +1,134 @@ | ||
| 1 | 추가: { | |
| 2 | 추가: "schema_version": 1, | |
| 3 | 추가: "date": "2026-11-09", | |
| 4 | 추가: "previous_windows_report": { | |
| 5 | 추가: "source_message": "64900540-164a-463a-ab79-61c1f8a763c0", | |
| 6 | 추가: "result": "총괄이 Windows C# 62개 전부 통과 및 Desktop/Core/Runtime/Worker 빌드 경고 0 오류 0으로 보고함", | |
| 7 | 추가: "scope": "기존 게시 검사까지의 결과이며 이번 해제 검사 35개나 Ubuntu 네이티브 실행의 근거가 아님", | |
| 8 | 추가: "snapshot": "이 메시지에는 새 스냅샷 시각과 해시가 제공되지 않음" | |
| 9 | 추가: }, | |
| 10 | 추가: "current_checks": { | |
| 11 | 추가: "python": { | |
| 12 | 추가: "passed": 33, | |
| 13 | 추가: "failed": 0, | |
| 14 | 추가: "command": "python3 -B tests/run_checks.py", | |
| 15 | 추가: "environment": "Ubuntu 26.04.1 LTS x86_64, Python 3.14.4" | |
| 16 | 추가: }, | |
| 17 | 추가: "csharp": { | |
| 18 | 추가: "core": 41, | |
| 19 | 추가: "existing_runtime": 21, | |
| 20 | 추가: "new_extraction_memory": 26, | |
| 21 | 추가: "new_folder_publication": 10, | |
| 22 | 추가: "total": 98, | |
| 23 | 추가: "compile": "not_run: local .NET SDK absent", | |
| 24 | 추가: "unit_or_worker_execution": "not_run", | |
| 25 | 추가: "windows_native_execution": "not_run for current 98 cases; round6 Core41 passed, Runtime56 compile failed and not executed (manager report)", | |
| 26 | 추가: "ubuntu_24_native_execution": "not_run", | |
| 27 | 추가: "ubuntu_26_native_execution": "not_run" | |
| 28 | 추가: }, | |
| 29 | 추가: "meaning": "Python 검사는 샘플 구조, 재현성 및 기존 정적/실행기 검사임. C# 또는 실제 저장 검증 통과가 아님" | |
| 30 | 추가: }, | |
| 31 | 추가: "api_bindings": { | |
| 32 | 추가: "worker": "ZipWorkerClient.ExtractAsync(Guid, Stream, JobLimits, CancellationToken)", | |
| 33 | 추가: "memory_result": "ZipWorkerResult.ExtractedEntries, ZipExtractedEntry(ArchiveEntry, byte[], uint Crc32)", | |
| 34 | 추가: "publisher": "NewFolderPublisher.PublishAsync(ZipWorkerResult, string destinationPath, CancellationToken)", | |
| 35 | 추가: "status": "메모리 성공은 Completed/None 및 모든 항목 Staged/Passed, 디스크 게시 완료와 구분함", | |
| 36 | 추가: "general_ui": "SupportsSafeExtraction=false 유지 검사", | |
| 37 | 추가: "publisher_gate": "Windows/Linux x64에서 구현 진입 가능. 대상 파일시스템과 쓰기 경계는 호출 때 검사함. 일반 UI 해제는 계속 비활성임" | |
| 38 | 추가: }, | |
| 39 | 추가: "fixtures": { | |
| 40 | 추가: "count": 22, | |
| 41 | 추가: "total_bytes": 4292, | |
| 42 | 추가: "maximum_per_file": 4096, | |
| 43 | 추가: "manifest": "tests/extraction/fixtures.json", | |
| 44 | 추가: "generator": "python3 -B tests/extraction/fixture_factory.py", | |
| 45 | 추가: "source": "자체 생성. 외부 압축파일이나 실제 파일시스템 링크가 아님", | |
| 46 | 추가: "unix_link_reference": "https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT", | |
| 47 | 추가: "unix_link_section": "4.5.7 (0x000d), 링크 메타데이터 한 종류의 거부를 검사함" | |
| 48 | 추가: }, | |
| 49 | 추가: "acceptance": { | |
| 50 | 추가: "normal": "Stored/Deflate, 파일별 SHA-256과 길이, 빈 파일과 디렉터리, 원본 해시 보존", | |
| 51 | 추가: "paths": "../, POSIX 절대 경로 및 // 경로 거부. Windows 역슬래시/드라이브 경로 거부. Linux에서는 해당 문자열의 합법적 이름을 그대로 보존", | |
| 52 | 추가: "collisions": "정확한 중복, 파일 뒤 자식, 자식 뒤 파일은 OutputConflict", | |
| 53 | 추가: "case": "Windows Readme/README 충돌, Linux 두 이름과 바이트 보존", | |
| 54 | 추가: "links": "symlink 타입, UNIX 0x000d 링크 메타데이터, FIFO는 UnsupportedEntry", | |
| 55 | 추가: "integrity": "payload CRC, 양쪽 헤더 CRC 손상, 양쪽 헤더 길이 과소/과대, local/central 길이 불일치 및 EOCD 절단은 IntegrityFailure", | |
| 56 | 추가: "budgets": "입력 바이트와 실제 해제 바이트 누적, 출력 합계와 항목 수의 정확한 경계 성공 및 초과 실패, 실패 시 부분 결과 없음", | |
| 57 | 추가: "cancel": "메모리 해제 시작 전 및 입력 읽기 진입 후 결정적 취소. 폴더 게시 시작 전 취소. 기존 파일/원본 보존", | |
| 58 | 추가: "publication": "새 폴더의 실제 파일/해시 일치. 기존 폴더/입력 파일 충돌은 OutputConflict, 병합/덮어쓰기 금지. 충돌 전 임시 결과가 작성되는 구현에서 정리 후 최상위 항목 집합 일치", | |
| 59 | 추가: "failure": "메모리 내용 변조는 IntegrityFailure, 실패한 해제 결과는 EngineFailure로 게시 거부. 임시 이름/정리 실패 없음", | |
| 60 | 추가: "filesystem_links": "부모 symlink는 UnsafePath, 최종 symlink는 지원 저장 조건에서 OutputConflict. 기존 링크와 대상 표식 보존. 생성 권한 부재 또는 최종 링크의 저장 전제조건 미충족은 SKIP이며 성공으로 계산하지 않음", | |
| 61 | 추가: "closed_gate": "Windows/Linux x64 구현 진입 여부와 일반 UI 비활성을 별도로 검사함. 테스트 생성 부모의 Windows 로컬 NTFS/쓰기 ACL 또는 Linux mount ID/장치/유형 ext4 또는 xfs/현재 UID/그룹 및 기타 쓰기 금지를 독립 조회함. 알려진 미지원 조건은 실제 API의 정확한 실패 오류와 원본/기존 대상/잔류 항목 보존을 검사함. 지원 조건에서는 실제 게시/해시 성공이 필수임", | |
| 62 | 추가: "concurrent_publication": "두 작업의 같은 최종 이름 경쟁에서 한 작업만 성공, 패자 OutputConflict와 임시 정리, 원본/외부 표식 보존 및 승자 트리/해시를 검사함. 소스만 준비했으며 정확한 native 호출 겹침은 강제하지 않음", | |
| 63 | 추가: "environment_skips": "새 폴더 생성/충돌/최종 링크/동시 게시의 저장 전제조건이 조회상 미충족이면 해당 수용 사례는 SKIP임. 제품 PublishAsync 실패를 이유로 SKIP하지 않음. 사전 취소/내용 변조/실패한 해제/부모 symlink 거부는 저장 파일시스템 미지원과 분리함. SKIP은 PASS에 합산하지 않음" | |
| 64 | 추가: }, | |
| 65 | 추가: "platforms": { | |
| 66 | 추가: "windows-x64": { | |
| 67 | 추가: "memory": 26, | |
| 68 | 추가: "publication": "실제 API에 8개 기존 수용 검사와 동시 게시 1개가 연결됨. OS/파일시스템/쓰기 경계 조건 아래 실행이 필요함", | |
| 69 | 추가: "current_execution": "not_run", | |
| 70 | 추가: "positive_publication_cases": "실제 성공/충돌/무결성/보존 오류 기대값 유지. 새 폴더 저장 전제조건을 독립 조회하며 미충족 수용 검사는 SKIP으로 구분함" | |
| 71 | 추가: }, | |
| 72 | 추가: "ubuntu-24.04-lts-x64": { | |
| 73 | 추가: "memory": 26, | |
| 74 | 추가: "publication": "실제 API에 8개 기존 수용 검사와 동시 게시 1개가 연결됨. OS/파일시스템/쓰기 경계 조건 아래 실행이 필요함", | |
| 75 | 추가: "positive_publication_cases": "실제 성공/충돌/무결성/보존 오류 기대값 유지. 새 폴더 저장 전제조건을 독립 조회하며 미충족 수용 검사는 SKIP으로 구분함", | |
| 76 | 추가: "current_execution": "not_run" | |
| 77 | 추가: }, | |
| 78 | 추가: "ubuntu-26.04-lts-x64": { | |
| 79 | 추가: "memory": 26, | |
| 80 | 추가: "publication": "실제 API에 8개 기존 수용 검사와 동시 게시 1개가 연결됨. OS/파일시스템/쓰기 경계 조건 아래 실행이 필요함", | |
| 81 | 추가: "positive_publication_cases": "실제 성공/충돌/무결성/보존 오류 기대값 유지. 새 폴더 저장 전제조건을 독립 조회하며 미충족 수용 검사는 SKIP으로 구분함", | |
| 82 | 추가: "current_execution": "Python 샘플 검사만 실행. C# 미실행" | |
| 83 | 추가: } | |
| 84 | 추가: }, | |
| 85 | 추가: "not_covered": [ | |
| 86 | 추가: "최신 98개와 새 네이티브 폴더 게시의 C# 컴파일 및 실제 실행. 이전 97개 고정 스냅샷은 Runtime 컴파일 실패 보고임", | |
| 87 | 추가: "Windows junction 및 실제 부모/최종 경로 교체 경합", | |
| 88 | 추가: "실제 파일시스템 hardlink 및 다른 ZIP 링크 메타데이터 방언", | |
| 89 | 추가: "쓰기 도중 취소, 게시 직후 늦은 취소, 정리 실패 주입, 강제 프로세스 종료 후 잔류 결과", | |
| 90 | 추가: "마운트 교체, 네트워크 파일시스템 및 Windows NTFS 외 파일시스템", | |
| 91 | 추가: "Ubuntu 두 LTS와 Windows의 새 폴더 게시 실제 실행 및 환경별 지원 조건 검증", | |
| 92 | 추가: "ZIP64, 암호화, 분할 및 복구, 데이터 descriptor 변형과 Deflate 내부 이상을 포괄하는 검증", | |
| 93 | 추가: "프로세스 OS 메모리/CPU 제한 및 대용량 성능", | |
| 94 | 추가: "권한을 변경하거나 마운트를 새로 만들지 않아 모든 ACL/소유자/미지원 파일시스템 조합을 강제 실행하지 못함. 한 실행에서 관찰되지 않은 플랫폼 계약 분기는 미검증임", | |
| 95 | 추가: "FolderEnvironment의 경로 기반 관찰은 테스트 환경 분류용이며 제품 핸들 경계나 procfs 대체 방어의 증명이 아님. procfs 검증 실패/마운트 교체의 결정적 주입이 남음" | |
| 96 | 추가: ], | |
| 97 | 추가: "source_review": "ZipExtractor는 별도 작업자에서 CRC를 직접 계산하고 실제 해제 길이와 대조함. .NET이 자동 검증한다고 가정하지 않음. 이 기록은 실행 증거가 아님", | |
| 98 | 추가: "reviewed_source_sha256": { | |
| 99 | 추가: "src/Zipelo.Runtime/ZipExtraction.cs": "a7fcbd766dc0df71483ceb19bbf6fc02c4964d3ae290e368a92bb64ddfac3625", | |
| 100 | 추가: "src/Zipelo.Runtime/ZipWorkerClient.cs": "5df676f75957cf081237671585ce6ad2098c6f8c8ed1392efece28960a3ebbd0", | |
| 101 | 추가: "src/Zipelo.Runtime/NewFolderPublisher.cs": "fe77406a2f7716f740fe52f4296b8639043806060a75983b759fec674eb2169e", | |
| 102 | 추가: "src/Zipelo.Runtime/WindowsFolderPublication.cs": "9e3b8727bbe486c5b7d8614ec65872b8169f361ef1c2ea56f835e1e170a297aa", | |
| 103 | 추가: "src/Zipelo.Worker/ZipExtractor.cs": "f25abc6ceb49af9e63d71cd5def28530057734d73d9618f316d41d31fe30da61", | |
| 104 | 추가: "src/Zipelo.Runtime/PendingFolderPublication.cs": "55315417e5b78d7114e3e856f66194cb59fcb6d981b95168004d5a10e39fd03a", | |
| 105 | 추가: "src/Zipelo.Runtime/WindowsFolderGuard.cs": "8924c914edbf246a4335c89bdecea0f099c7d76701c1430192a6a51066112df7", | |
| 106 | 추가: "src/Zipelo.Runtime/LinuxFolderPublication.cs": "6840730b865afa73bf1cbd1494c936b56f9cc3b2b74f958694785c02ee61f2d8" | |
| 107 | 추가: }, | |
| 108 | 추가: "existing_62_preserved": "기존 Core/RuntimeTests/PublicationTests의 기대값을 변경하지 않음. 새 해제 테스트만 추가하고 folder.platform_contract의 폐기된 전체 false 기대값을 명시적으로 변경된 저장 계약에 맞춤", | |
| 109 | 추가: "latest_folder_review": "tests/extraction/folder_publication_review.json", | |
| 110 | 추가: "round6_report": { | |
| 111 | 추가: "source_message": "8e7a3d5d-3ce8-4067-9814-c834baaa79bf", | |
| 112 | 추가: "snapshot": "2026-11-09T14:44:04.604469Z", | |
| 113 | 추가: "files": 102, | |
| 114 | 추가: "build": "총괄 보고: Desktop/Core/Runtime/Worker 경고 0 오류 0", | |
| 115 | 추가: "core": { | |
| 116 | 추가: "passed": 41, | |
| 117 | 추가: "failed": 0 | |
| 118 | 추가: }, | |
| 119 | 추가: "runtime": { | |
| 120 | 추가: "registered": 56, | |
| 121 | 추가: "executed": 0, | |
| 122 | 추가: "compile_error": "CS0266 ExtractionPublicationTests.cs(125,22)" | |
| 123 | 추가: }, | |
| 124 | 추가: "scope": "97개 등록 스냅샷의 역사적 결과이며 최신 98개 또는 새 폴더 네이티브 구현 검증 결과가 아님" | |
| 125 | 추가: }, | |
| 126 | 추가: "isolated_compile_fix": { | |
| 127 | 추가: "file": "tests/runtime/ExtractionPublicationTests.cs", | |
| 128 | 추가: "change": "DirectoryInfo info; -> FileSystemInfo info; 한 줄 타입 수정", | |
| 129 | 추가: "before_sha256": "4aca9bcddafc7d0b79030766b24e6171ed5e9e7bedf8d2a9d018c4dfb2135062", | |
| 130 | 추가: "isolated_patch_sha256": "3e2eab3a0a61de4aa967f79a87240e5eae067e81cbe5708575a8f59524049ab5", | |
| 131 | 추가: "scope": "6498a73c-b12c-4d6f-847e-75cf5e8c8a25 메시지로 별도 패치 전달 완료. 현재 파일에는 후속 플랫폼 계약 검사 변경도 포함됨", | |
| 132 | 추가: "csharp_retest": "not_run by this reviewer" | |
| 133 | 추가: } | |
| 134 | 추가: } |
| @@ -0,0 +1,141 @@ | ||
| 1 | 추가: import hashlib | |
| 2 | 추가: import io | |
| 3 | 추가: import json | |
| 4 | 추가: from pathlib import Path | |
| 5 | 추가: import stat | |
| 6 | 추가: import struct | |
| 7 | 추가: import warnings | |
| 8 | 추가: import zipfile | |
| 9 | 추가: | |
| 10 | 추가: | |
| 11 | 추가: DIRECTORY = Path(__file__).resolve().parent | |
| 12 | 추가: ROOT = DIRECTORY.parents[1] | |
| 13 | 추가: FIXTURES = DIRECTORY / "fixtures" | |
| 14 | 추가: STAMP = (2024, 1, 1, 0, 0, 0) | |
| 15 | 추가: REGULAR = stat.S_IFREG | 0o600 | |
| 16 | 추가: PAYLOAD = b"zipelo-extraction-content\n" | |
| 17 | 추가: MAX_SAMPLE_BYTES = 4096 | |
| 18 | 추가: UNIX_FIELD_REFERENCE = "https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT" | |
| 19 | 추가: | |
| 20 | 추가: | |
| 21 | 추가: def archive(entries, compression=zipfile.ZIP_STORED): | |
| 22 | 추가: output = io.BytesIO() | |
| 23 | 추가: with zipfile.ZipFile(output, "w") as zipped, warnings.catch_warnings(): | |
| 24 | 추가: warnings.filterwarnings("ignore", message="Duplicate name:", category=UserWarning) | |
| 25 | 추가: for name, content, mode, extra in entries: | |
| 26 | 추가: info = zipfile.ZipInfo(name, STAMP) | |
| 27 | 추가: info.create_system = 3 | |
| 28 | 추가: info.external_attr = mode << 16 | |
| 29 | 추가: if stat.S_ISDIR(mode): | |
| 30 | 추가: info.external_attr |= 0x10 | |
| 31 | 추가: info.extra = extra | |
| 32 | 추가: info.compress_type = compression | |
| 33 | 추가: zipped.writestr(info, content) | |
| 34 | 추가: result = output.getvalue() | |
| 35 | 추가: if len(result) > MAX_SAMPLE_BYTES: | |
| 36 | 추가: raise ValueError("작은 수용 샘플의 크기 상한을 넘음") | |
| 37 | 추가: return result | |
| 38 | 추가: | |
| 39 | 추가: | |
| 40 | 추가: def regular(name, content=PAYLOAD): | |
| 41 | 추가: return (name, content, REGULAR, b"") | |
| 42 | 추가: | |
| 43 | 추가: | |
| 44 | 추가: def mutate_field(data, local_offset, central_offset, value): | |
| 45 | 추가: changed = bytearray(data) | |
| 46 | 추가: central = data.index(b"PK\x01\x02") | |
| 47 | 추가: struct.pack_into("<I", changed, local_offset, value) | |
| 48 | 추가: struct.pack_into("<I", changed, central + central_offset, value) | |
| 49 | 추가: return bytes(changed) | |
| 50 | 추가: | |
| 51 | 추가: | |
| 52 | 추가: def build_samples(): | |
| 53 | 추가: normal = [ | |
| 54 | 추가: regular("hello.txt"), | |
| 55 | 추가: ("nested/", b"", stat.S_IFDIR | 0o700, b""), | |
| 56 | 추가: regular("nested/data.bin", bytes(range(32))), | |
| 57 | 추가: regular("nested/empty.txt", b""), | |
| 58 | 추가: ] | |
| 59 | 추가: single = archive([regular("payload.txt")], zipfile.ZIP_DEFLATED) | |
| 60 | 추가: stored = archive([regular("payload.txt")]) | |
| 61 | 추가: bad_payload = bytearray(stored) | |
| 62 | 추가: bad_payload[stored.index(PAYLOAD)] ^= 1 | |
| 63 | 추가: bad_crc = struct.unpack_from("<I", single, 14)[0] ^ 1 | |
| 64 | 추가: mismatch = bytearray(single) | |
| 65 | 추가: struct.pack_into("<I", mismatch, 22, len(PAYLOAD) + 1) | |
| 66 | 추가: # UNIX 링크 대상 이름은 NUL 없이 12바이트 고정 필드 뒤에 저장함. | |
| 67 | 추가: link_target = b"../sentinel.txt" | |
| 68 | 추가: unix_data = struct.pack("<IIHH", 0, 0, 0, 0) + link_target | |
| 69 | 추가: unix_extra = struct.pack("<HH", 0x000D, len(unix_data)) + unix_data | |
| 70 | 추가: return { | |
| 71 | 추가: "normal-stored.zip": archive(normal), | |
| 72 | 추가: "normal-deflated.zip": archive(normal, zipfile.ZIP_DEFLATED), | |
| 73 | 추가: "traversal.zip": archive([regular("../escape.txt")]), | |
| 74 | 추가: "backslash-traversal.zip": archive([regular("..\\escape.txt")]), | |
| 75 | 추가: "absolute-posix.zip": archive([regular("/escape.txt")]), | |
| 76 | 추가: "absolute-drive.zip": archive([regular("C:/escape.txt")]), | |
| 77 | 추가: "absolute-unc.zip": archive([regular("//server/share/escape.txt")]), | |
| 78 | 추가: "duplicate.zip": archive([regular("same.txt", b"one"), regular("same.txt", b"two")]), | |
| 79 | 추가: "file-before-child.zip": archive([regular("node", b"one"), regular("node/child", b"two")]), | |
| 80 | 추가: "child-before-file.zip": archive([regular("node/child", b"one"), regular("node", b"two")]), | |
| 81 | 추가: "case-distinct.zip": archive([regular("Readme.txt", b"first"), regular("README.TXT", b"second")]), | |
| 82 | 추가: "linux-names.zip": archive([regular("CON", b"one"), regular("name:stream", b"two")]), | |
| 83 | 추가: "symlink.zip": archive([("link", link_target, stat.S_IFLNK | 0o777, b"")]), | |
| 84 | 추가: "unix-hardlink.zip": archive([("link", b"", REGULAR, unix_extra)]), | |
| 85 | 추가: "special-fifo.zip": archive([("pipe", b"", stat.S_IFIFO | 0o600, b"")]), | |
| 86 | 추가: "bad-payload-crc.zip": bytes(bad_payload), | |
| 87 | 추가: "bad-header-crc.zip": mutate_field(single, 14, 16, bad_crc), | |
| 88 | 추가: "length-smaller.zip": mutate_field(single, 22, 24, len(PAYLOAD) - 1), | |
| 89 | 추가: "length-larger.zip": mutate_field(single, 22, 24, len(PAYLOAD) + 1), | |
| 90 | 추가: "local-central-length.zip": bytes(mismatch), | |
| 91 | 추가: "truncated.zip": single[:-12], | |
| 92 | 추가: "cumulative.zip": archive([regular("first.bin", bytes(range(8))), regular("second.bin", bytes(range(8, 16)))]), | |
| 93 | 추가: } | |
| 94 | 추가: | |
| 95 | 추가: | |
| 96 | 추가: def build_manifest(samples): | |
| 97 | 추가: entries = [] | |
| 98 | 추가: for name, data in sorted(samples.items()): | |
| 99 | 추가: entries.append({"file": name, "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}) | |
| 100 | 추가: return { | |
| 101 | 추가: "schema_version": 1, | |
| 102 | 추가: "source": "자체 생성한 작은 ZIP 샘플이며 디스크 해제를 수행하지 않음", | |
| 103 | 추가: "unix_link_reference": UNIX_FIELD_REFERENCE, | |
| 104 | 추가: "unix_link_section": "4.5.7, 0x000d 링크 메타데이터의 거부 검사. 모든 ZIP 링크 방언을 대표하지 않음", | |
| 105 | 추가: "normal_files": { | |
| 106 | 추가: "hello.txt": {"bytes": len(PAYLOAD), "sha256": hashlib.sha256(PAYLOAD).hexdigest()}, | |
| 107 | 추가: "nested/data.bin": {"bytes": 32, "sha256": hashlib.sha256(bytes(range(32))).hexdigest()}, | |
| 108 | 추가: "nested/empty.txt": {"bytes": 0, "sha256": hashlib.sha256(b"").hexdigest()}, | |
| 109 | 추가: }, | |
| 110 | 추가: "samples": entries, | |
| 111 | 추가: } | |
| 112 | 추가: | |
| 113 | 추가: | |
| 114 | 추가: def write_new(path, content): | |
| 115 | 추가: if path.is_symlink(): | |
| 116 | 추가: raise ValueError("샘플 경로의 링크를 허용하지 않음") | |
| 117 | 추가: if path.exists(): | |
| 118 | 추가: if path.read_bytes() != content: | |
| 119 | 추가: raise ValueError("기존 샘플을 덮어쓰지 않음") | |
| 120 | 추가: return | |
| 121 | 추가: with path.open("xb") as output: | |
| 122 | 추가: output.write(content) | |
| 123 | 추가: | |
| 124 | 추가: | |
| 125 | 추가: def main(): | |
| 126 | 추가: if DIRECTORY != ROOT / "tests" / "extraction": | |
| 127 | 추가: raise ValueError("프로젝트 tests 아래 경로가 필요함") | |
| 128 | 추가: for path in (FIXTURES, *FIXTURES.parents): | |
| 129 | 추가: if path.is_symlink(): | |
| 130 | 추가: raise ValueError("샘플 경로의 링크를 허용하지 않음") | |
| 131 | 추가: FIXTURES.mkdir(exist_ok=True) | |
| 132 | 추가: samples = build_samples() | |
| 133 | 추가: for name, content in samples.items(): | |
| 134 | 추가: write_new(FIXTURES / name, content) | |
| 135 | 추가: manifest = json.dumps(build_manifest(samples), ensure_ascii=False, indent=4) + "\n" | |
| 136 | 추가: write_new(DIRECTORY / "fixtures.json", manifest.encode("utf-8")) | |
| 137 | 추가: print(f"해제 샘플 {len(samples)}개, {sum(map(len, samples.values()))}바이트") | |
| 138 | 추가: | |
| 139 | 추가: | |
| 140 | 추가: if __name__ == "__main__": | |
| 141 | 추가: main() |
| @@ -0,0 +1,132 @@ | ||
| 1 | 추가: { | |
| 2 | 추가: "schema_version": 1, | |
| 3 | 추가: "source": "자체 생성한 작은 ZIP 샘플이며 디스크 해제를 수행하지 않음", | |
| 4 | 추가: "unix_link_reference": "https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT", | |
| 5 | 추가: "unix_link_section": "4.5.7, 0x000d 링크 메타데이터의 거부 검사. 모든 ZIP 링크 방언을 대표하지 않음", | |
| 6 | 추가: "normal_files": { | |
| 7 | 추가: "hello.txt": { | |
| 8 | 추가: "bytes": 26, | |
| 9 | 추가: "sha256": "bc52abc01915711bf043e6a8169c344d58d43b3f8e64d4ae3ace763e002f1a7e" | |
| 10 | 추가: }, | |
| 11 | 추가: "nested/data.bin": { | |
| 12 | 추가: "bytes": 32, | |
| 13 | 추가: "sha256": "630dcd2966c4336691125448bbb25b4ff412a49c732db2c8abc1b8581bd710dd" | |
| 14 | 추가: }, | |
| 15 | 추가: "nested/empty.txt": { | |
| 16 | 추가: "bytes": 0, | |
| 17 | 추가: "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" | |
| 18 | 추가: } | |
| 19 | 추가: }, | |
| 20 | 추가: "samples": [ | |
| 21 | 추가: { | |
| 22 | 추가: "file": "absolute-drive.zip", | |
| 23 | 추가: "bytes": 150, | |
| 24 | 추가: "sha256": "f34b9e6f8c735ddf809c7d68f656896e16bf360cfd6a9d763c77c6a03dd9dbb8" | |
| 25 | 추가: }, | |
| 26 | 추가: { | |
| 27 | 추가: "file": "absolute-posix.zip", | |
| 28 | 추가: "bytes": 146, | |
| 29 | 추가: "sha256": "8db3ea3d316f4474c6802fa5930eff42544697a1a9f51c9791758bd4205e7165" | |
| 30 | 추가: }, | |
| 31 | 추가: { | |
| 32 | 추가: "file": "absolute-unc.zip", | |
| 33 | 추가: "bytes": 174, | |
| 34 | 추가: "sha256": "d6abe8b820436780f1abfcf79df9e652804f0082b4e675bf69328f9416f05fff" | |
| 35 | 추가: }, | |
| 36 | 추가: { | |
| 37 | 추가: "file": "backslash-traversal.zip", | |
| 38 | 추가: "bytes": 150, | |
| 39 | 추가: "sha256": "7735776dd0001464ba7ea6e076c7c5f6f5190717d9403bcd4f997b7663972274" | |
| 40 | 추가: }, | |
| 41 | 추가: { | |
| 42 | 추가: "file": "bad-header-crc.zip", | |
| 43 | 추가: "bytes": 148, | |
| 44 | 추가: "sha256": "aa33807af138ffff9d30455d823b397c4b200d42100ba73bdf7a5b4161829aad" | |
| 45 | 추가: }, | |
| 46 | 추가: { | |
| 47 | 추가: "file": "bad-payload-crc.zip", | |
| 48 | 추가: "bytes": 146, | |
| 49 | 추가: "sha256": "5c02bf6c98da1fdfd7b62e8a9a39a51ffe90bb6f4ecd6ac3ee7f101440f3910b" | |
| 50 | 추가: }, | |
| 51 | 추가: { | |
| 52 | 추가: "file": "case-distinct.zip", | |
| 53 | 추가: "bytes": 225, | |
| 54 | 추가: "sha256": "15bb0bbce2a786b649e2c929566a39129de1fb6615bddca034c236d3ed6e09ed" | |
| 55 | 추가: }, | |
| 56 | 추가: { | |
| 57 | 추가: "file": "child-before-file.zip", | |
| 58 | 추가: "bytes": 208, | |
| 59 | 추가: "sha256": "44e0272c04056f47651fad69301a0f1627400b0bc9d4edc98eef5f5aef9390a8" | |
| 60 | 추가: }, | |
| 61 | 추가: { | |
| 62 | 추가: "file": "cumulative.zip", | |
| 63 | 추가: "bytes": 228, | |
| 64 | 추가: "sha256": "271007b76bae9c0728c8ea99186624a3dfb9697b6b9d44e9104bbbe564e9286f" | |
| 65 | 추가: }, | |
| 66 | 추가: { | |
| 67 | 추가: "file": "duplicate.zip", | |
| 68 | 추가: "bytes": 212, | |
| 69 | 추가: "sha256": "85313cb8b056bfd0efae98953f2f0b0e56058a6a858791fda9df9a17f0a31dfa" | |
| 70 | 추가: }, | |
| 71 | 추가: { | |
| 72 | 추가: "file": "file-before-child.zip", | |
| 73 | 추가: "bytes": 208, | |
| 74 | 추가: "sha256": "7f583dd54a3c37898a3e62c5b4b8a8d536d31c0b75a896a3b15870b3145f68c6" | |
| 75 | 추가: }, | |
| 76 | 추가: { | |
| 77 | 추가: "file": "length-larger.zip", | |
| 78 | 추가: "bytes": 148, | |
| 79 | 추가: "sha256": "f558e5604c67d7ffc6ce098017cc6c850e30fff3e2296b6c36b2d51386deb92e" | |
| 80 | 추가: }, | |
| 81 | 추가: { | |
| 82 | 추가: "file": "length-smaller.zip", | |
| 83 | 추가: "bytes": 148, | |
| 84 | 추가: "sha256": "325e2dbceb68de1171f335fc4879ff3800200ccf92c75d4ba3ba89388d00918e" | |
| 85 | 추가: }, | |
| 86 | 추가: { | |
| 87 | 추가: "file": "linux-names.zip", | |
| 88 | 추가: "bytes": 208, | |
| 89 | 추가: "sha256": "ed03e65f5e4c8e8fc1f08dd95a941dccb9fec8cc27de46620f4255393d4d813a" | |
| 90 | 추가: }, | |
| 91 | 추가: { | |
| 92 | 추가: "file": "local-central-length.zip", | |
| 93 | 추가: "bytes": 148, | |
| 94 | 추가: "sha256": "ecada1333b78027897c59ab79e197addcf1ca87dea608be8311bae0de0606649" | |
| 95 | 추가: }, | |
| 96 | 추가: { | |
| 97 | 추가: "file": "normal-deflated.zip", | |
| 98 | 추가: "bytes": 486, | |
| 99 | 추가: "sha256": "896a3b5141cf108dfbc3d4545c433d09bb10934284d2d0e479964a936be92200" | |
| 100 | 추가: }, | |
| 101 | 추가: { | |
| 102 | 추가: "file": "normal-stored.zip", | |
| 103 | 추가: "bytes": 478, | |
| 104 | 추가: "sha256": "127f9a3e81c3b328dba2adf598f74aff0a81e2b9643b8a3329f7ec3af4016147" | |
| 105 | 추가: }, | |
| 106 | 추가: { | |
| 107 | 추가: "file": "special-fifo.zip", | |
| 108 | 추가: "bytes": 106, | |
| 109 | 추가: "sha256": "afbfcdc410d541735aa57569637b3c6a3ba7228bacdcce6b6e6d169cfb1b864f" | |
| 110 | 추가: }, | |
| 111 | 추가: { | |
| 112 | 추가: "file": "symlink.zip", | |
| 113 | 추가: "bytes": 121, | |
| 114 | 추가: "sha256": "e9f4b9390dbe47ac88f2b0459bd3b61f45c248abc1221afa80c038ebc97ab5e7" | |
| 115 | 추가: }, | |
| 116 | 추가: { | |
| 117 | 추가: "file": "traversal.zip", | |
| 118 | 추가: "bytes": 150, | |
| 119 | 추가: "sha256": "26fd5a4dd0e7b446654de04cfe338bc199d738c07e4b628df1cfd5b5e91b74f3" | |
| 120 | 추가: }, | |
| 121 | 추가: { | |
| 122 | 추가: "file": "truncated.zip", | |
| 123 | 추가: "bytes": 136, | |
| 124 | 추가: "sha256": "2062f2807806082c034c4ed457aa908a5f8496a3a32e07368ab8dd90e3ea9056" | |
| 125 | 추가: }, | |
| 126 | 추가: { | |
| 127 | 추가: "file": "unix-hardlink.zip", | |
| 128 | 추가: "bytes": 168, | |
| 129 | 추가: "sha256": "6ccd7ac5c36002da86309aacf36d6211e4e9d9c1b7b5431c4a8851d18193f2c6" | |
| 130 | 추가: } | |
| 131 | 추가: ] | |
| 132 | 추가: } |
바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기| @@ -0,0 +1,168 @@ | ||
| 1 | 추가: { | |
| 2 | 추가: "schema_version": 1, | |
| 3 | 추가: "reviewed_at_utc": "2026-11-09T15:13:13.685294+00:00", | |
| 4 | 추가: "scope": "현재 새 폴더 게시의 독립 소스 검토와 수용 검사 연결 확인. 실제 C# 및 네이티브 실행 증거가 아님", | |
| 5 | 추가: "branch": "docs/initial-project-plan", | |
| 6 | 추가: "frozen_windows_snapshot": { | |
| 7 | 추가: "at": "2026-11-09T14:44:04.604469Z", | |
| 8 | 추가: "source_message": "0af7d7e8-9895-4939-8b29-02fcdecd8b61", | |
| 9 | 추가: "registered_cases": 97, | |
| 10 | 추가: "result": "총괄 round6 보고: Core41 통과, Runtime56 CS0266 컴파일 실패로 전부 미실행" | |
| 11 | 추가: }, | |
| 12 | 추가: "source_sha256": { | |
| 13 | 추가: "src/Zipelo.Runtime/NewFolderPublisher.cs": "fe77406a2f7716f740fe52f4296b8639043806060a75983b759fec674eb2169e", | |
| 14 | 추가: "src/Zipelo.Runtime/PendingFolderPublication.cs": "55315417e5b78d7114e3e856f66194cb59fcb6d981b95168004d5a10e39fd03a", | |
| 15 | 추가: "src/Zipelo.Runtime/WindowsFolderPublication.cs": "9e3b8727bbe486c5b7d8614ec65872b8169f361ef1c2ea56f835e1e170a297aa", | |
| 16 | 추가: "src/Zipelo.Runtime/WindowsFolderGuard.cs": "8924c914edbf246a4335c89bdecea0f099c7d76701c1430192a6a51066112df7", | |
| 17 | 추가: "src/Zipelo.Runtime/LinuxFolderPublication.cs": "6840730b865afa73bf1cbd1494c936b56f9cc3b2b74f958694785c02ee61f2d8" | |
| 18 | 추가: }, | |
| 19 | 추가: "findings": [ | |
| 20 | 추가: { | |
| 21 | 추가: "id": "linux-mkdir-open-cleanup-gap", | |
| 22 | 추가: "status": "source_followup_addressed_runtime_unverified", | |
| 23 | 추가: "source": "src/Zipelo.Runtime/LinuxFolderPublication.cs:31", | |
| 24 | 추가: "condition": "mkdirat 성공 후 openat2가 EMFILE 또는 I/O 오류로 실패하는 경우", | |
| 25 | 추가: "observed": "Create가 핸들을 반환하기 전에 예외가 발생해 PendingFolderPublication.Owned에 생성 디렉터리가 등록되지 않음. 기존 Abort는 이 이름을 처리하지 않음", | |
| 26 | 추가: "required": "생성 후 핸들 획득 실패의 소유권과 정리 결과를 명시적으로 추적해야 함. 안전한 정리를 증명 못하면 CleanupFailed와 잔류 임시 이름을 반환해야 하며 정리 성공으로 표시하면 안 됨", | |
| 27 | 추가: "verification": "결정적 네이티브 실패 주입으로 mkdir 성공/open 실패 순서를 증명하고 외부 sentinel 보존 및 정리 진단 확인 필요. 실제 실행 미실행", | |
| 28 | 추가: "followup": "후속 소스에서 unboundCreation을 mkdirat 직후 기록하고 Abort 성공 여부에 반영함. 이 조건의 실제 실패 주입과 잔류 이름 반환은 미실행임" | |
| 29 | 추가: }, | |
| 30 | 추가: { | |
| 31 | 추가: "id": "windows-close-before-rename-boundary", | |
| 32 | 추가: "status": "documented_boundary_native_unverified", | |
| 33 | 추가: "source": "src/Zipelo.Runtime/WindowsFolderPublication.cs:25", | |
| 34 | 추가: "observed": "게시 직전 자식 핸들을 닫고 실패 시 파일 ID를 비교해 재개방한 뒤 핸들 삭제함. 닫힌 구간의 변조 방어는 개인 쓰기 ACL과 신뢰 주체 경계에 의존함", | |
| 35 | 추가: "required": "관리자/실행 계정 장악 방어로 확대 설명하지 않음. 일반 동시 작업의 최종 이름 충돌은 원자적 덮어쓰기 금지로 분리 검증함. ACL 조회 결과만으로 임의 동시 권한 변경까지 차단한다고 주장하지 않음", | |
| 36 | 추가: "verification": "실제 NTFS 자식 핸들 종료 후 rename 및 충돌 후 재개방/정리, ACL 거부, 정리 실패 검증 미실행" | |
| 37 | 추가: }, | |
| 38 | 추가: { | |
| 39 | 추가: "id": "linux-unlink-name-boundary", | |
| 40 | 추가: "status": "documented_boundary_native_unverified", | |
| 41 | 추가: "source": "src/Zipelo.Runtime/LinuxFolderPublication.cs:115", | |
| 42 | 추가: "observed": "RequireName 후 unlinkat는 별도 호출임. 같은 UID 또는 권한 있는 주체의 동시 이름 교체를 원자적으로 막는 조건부 삭제가 아님", | |
| 43 | 추가: "required": "소유 UID와 타 계정 쓰기 금지를 위협 범위의 전제조건으로 명시함. 전제조건 없는 공유 쓰기 디렉터리에서 안전하다고 표시하지 않음", | |
| 44 | 추가: "verification": "타 계정 ACL/마운트/이름 교체 경합은 미실행. 열린 dirfd만으로 정리 경쟁을 증명했다고 표시하지 않음" | |
| 45 | 추가: }, | |
| 46 | 추가: { | |
| 47 | 추가: "id": "preserved-platform-contract-conflict", | |
| 48 | 추가: "status": "source_test_contract_updated_runtime_unverified", | |
| 49 | 추가: "source": "tests/runtime/ExtractionPublicationTests.cs:21", | |
| 50 | 추가: "observed": "NewFolderPublisher.IsSupportedPlatform이 Windows/Linux x64에서 true로 바뀜. 기존 folder.platform_contract는 false와 OutputUnavailable을 요구하므로 소스상 충돌함", | |
| 51 | 추가: "required": "9a5765b1-02d8-4b15-a4cb-dfa90b643cae 지시에 따라 안전 기대값을 유지하고 폐기된 전체 false 검사만 최신 저장 조건으로 조정함", | |
| 52 | 추가: "verification": "실행 실패 보고가 아니라 소스 비교로 확인한 예상 실패임", | |
| 53 | 추가: "followup": "Windows/Linux x64 구현 진입 여부와 일반 UI 비활성을 별도로 검사함. 테스트 생성 부모의 Windows 로컬 NTFS/쓰기 ACL 또는 Linux mount ID/장치/유형 ext4 또는 xfs/현재 UID/그룹 및 기타 쓰기 금지를 독립 조회함. 알려진 미지원 조건은 실제 API의 정확한 실패 오류와 원본/기존 대상/잔류 항목 보존을 검사함. 지원 조건에서는 실제 게시/해시 성공이 필수임 새 폴더 생성/충돌/최종 링크/동시 게시의 저장 전제조건이 조회상 미충족이면 해당 수용 사례는 SKIP임. 제품 PublishAsync 실패를 이유로 SKIP하지 않음. 사전 취소/내용 변조/실패한 해제/부모 symlink 거부는 저장 파일시스템 미지원과 분리함. SKIP은 PASS에 합산하지 않음" | |
| 54 | 추가: }, | |
| 55 | 추가: { | |
| 56 | 추가: "id": "linux-ext-family-not-distinguished", | |
| 57 | 추가: "status": "source_followup_mount_identity_added_runtime_unverified", | |
| 58 | 추가: "source": "src/Zipelo.Runtime/LinuxFolderPublication.cs:24", | |
| 59 | 추가: "observed": "fstatfs의 0xEF53 값은 ext2/ext3/ext4가 공유함. 이 값만 허용하면서 ext4만 확인했다고 설명할 수 없음", | |
| 60 | 추가: "required": "허용 대상의 정확한 판별 또는 계약/실패 폐쇄 범위를 backend에서 정리해야 함. 미검증 ext2/ext3를 검증된 ext4라고 처리하지 않음", | |
| 61 | 추가: "reference": "https://man7.org/linux/man-pages/man2/statfs.2.html", | |
| 62 | 추가: "verification": "공식 상수와 소스 비교. ext2/ext3 마운트 생성이나 실제 실행 없음", | |
| 63 | 추가: "followup": "XFS만 허용한 임시 수정 뒤 최신 소스는 부모 fd statx mount ID/장치 번호와 procfs task mountinfo를 대조함. ext magic만으로 허용하지 않고 유형 ext4 또는 xfs 일치, 조회 전후 ID/장치/inode/magic 확인을 요구함. ext2/ext3 유형과 확인 불가 조건은 생성 전 실패 폐쇄임. 실제 C# 검증 아님" | |
| 64 | 추가: } | |
| 65 | 추가: ], | |
| 66 | 추가: "acceptance_binding": { | |
| 67 | 추가: "status": "기존 8개와 동시 게시 1개의 PublishAsync 연결 유지. 성공과 정확한 오류/보존 기준을 유지하면서 저장 조건 관찰을 추가함", | |
| 68 | 추가: "existing_eight": [ | |
| 69 | 추가: "folder.new_folder_contents_hashes_and_source", | |
| 70 | 추가: "folder.existing_folder_preserved_and_temporary_cleanup", | |
| 71 | 추가: "folder.existing_source_file_preserved_and_temporary_cleanup", | |
| 72 | 추가: "folder.precancel_preserves_originals", | |
| 73 | 추가: "folder.tampered_bytes_not_published", | |
| 74 | 추가: "folder.failed_extraction_not_published", | |
| 75 | 추가: "folder.reject_parent_symlink", | |
| 76 | 추가: "folder.reject_leaf_symlink" | |
| 77 | 추가: ], | |
| 78 | 추가: "general_gate": "Windows/Linux x64 구현 진입 여부와 일반 UI 비활성을 별도로 검사함. 테스트 생성 부모의 Windows 로컬 NTFS/쓰기 ACL 또는 Linux mount ID/장치/유형 ext4 또는 xfs/현재 UID/그룹 및 기타 쓰기 금지를 독립 조회함. 알려진 미지원 조건은 실제 API의 정확한 실패 오류와 원본/기존 대상/잔류 항목 보존을 검사함. 지원 조건에서는 실제 게시/해시 성공이 필수임", | |
| 79 | 추가: "filesystem_preconditions": "Windows 로컬 NTFS/쓰기 ACL, Linux mount ID/장치/유형 ext4 또는 xfs/현재 UID/그룹 및 기타 쓰기 금지. openat2/statx/renameat2/procfs 지원도 필요하며 실제 호출 실패를 통과로 처리하지 않음", | |
| 80 | 추가: "skip_policy": "새 폴더 생성/충돌/최종 링크/동시 게시의 저장 전제조건이 조회상 미충족이면 해당 수용 사례는 SKIP임. 제품 PublishAsync 실패를 이유로 SKIP하지 않음. 사전 취소/내용 변조/실패한 해제/부모 symlink 거부는 저장 파일시스템 미지원과 분리함. SKIP은 PASS에 합산하지 않음" | |
| 81 | 추가: }, | |
| 82 | 추가: "execution_separation": { | |
| 83 | 추가: "source_review": "위 파일의 현재 읽은 내용만 검토함", | |
| 84 | 추가: "csharp_compile": "not_run: local dotnet absent", | |
| 85 | 추가: "windows_native": "not_run by this reviewer", | |
| 86 | 추가: "ubuntu_24_native": "not_run", | |
| 87 | 추가: "ubuntu_26_native": "not_run", | |
| 88 | 추가: "python": { | |
| 89 | 추가: "command": "python3 -B tests/run_checks.py", | |
| 90 | 추가: "passed": 33, | |
| 91 | 추가: "failed": 0, | |
| 92 | 추가: "meaning": "샘플/기존 정적/실행기 검사. 새 C# 검사나 네이티브 게시의 성공 증거가 아님" | |
| 93 | 추가: } | |
| 94 | 추가: }, | |
| 95 | 추가: "pending_conditions": [ | |
| 96 | 추가: "동시 게시 검사 소스를 준비했으나 실제 실행은 남아 있음. 정확한 네이티브 경합을 강제하지는 않음", | |
| 97 | 추가: "파일 쓰기 진입이 확인된 뒤의 취소와 게시 완료 뒤의 늦은 취소를 분리함. 타이머나 사전 취소로 대체하지 않음", | |
| 98 | 추가: "부모/자식 교체, 실제 junction/hardlink와 외부 항목 삽입 경합은 별도 실행 증거가 필요함", | |
| 99 | 추가: "권한 변경이나 SDK 설치 없이 재현할 수 없는 검사는 미실행으로 남김" | |
| 100 | 추가: ], | |
| 101 | 추가: "references": [ | |
| 102 | 추가: "https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_rename_information", | |
| 103 | 추가: "https://learn.microsoft.com/en-us/windows/win32/api/aclapi/nf-aclapi-getsecurityinfo", | |
| 104 | 추가: "https://man7.org/linux/man-pages/man2/unlink.2.html", | |
| 105 | 추가: "https://man7.org/linux/man-pages/man2/rename.2.html", | |
| 106 | 추가: "https://man7.org/linux/man-pages/man2/statfs.2.html" | |
| 107 | 추가: ], | |
| 108 | 추가: "initial_review_source_sha256": { | |
| 109 | 추가: "src/Zipelo.Runtime/NewFolderPublisher.cs": "5add3511d888461d8bc649333c2fe9f3d5ff695411714228632f237c1844da30", | |
| 110 | 추가: "src/Zipelo.Runtime/PendingFolderPublication.cs": "0c691d0eccd89b34b409655695ffe640d09372acf60f8c89f6e6e8aa0df27117", | |
| 111 | 추가: "src/Zipelo.Runtime/WindowsFolderPublication.cs": "04ea141450f062d8c100d28bf2d9dd1266a87f1456e2375d487cdd313e1dabaa", | |
| 112 | 추가: "src/Zipelo.Runtime/WindowsFolderGuard.cs": "c1f832dc955531e3e8654feb10232e68bfdf921f1d50b0b51f5c0566b36a70b9", | |
| 113 | 추가: "src/Zipelo.Runtime/LinuxFolderPublication.cs": "6fb8f3aa9c111155d727a5031dfb08c1f8cd74a5b2d23f5945c1a16503c12a19" | |
| 114 | 추가: }, | |
| 115 | 추가: "new_test": { | |
| 116 | 추가: "id": "folder.concurrent_same_name_one_winner", | |
| 117 | 추가: "source": "tests/runtime/FolderConcurrencyTests.cs", | |
| 118 | 추가: "binding": "NewFolderPublisher.PublishAsync", | |
| 119 | 추가: "cases_added": 1, | |
| 120 | 추가: "total_registered": 98, | |
| 121 | 추가: "acceptance": "같은 최종 이름으로 두 요청을 시작해 정확히 한 Published/None과 한 OutputConflict, 패자 임시 정리, 승자 전체 트리/파일 SHA-256, 원본 및 부모 밖 표식 보존을 검사함", | |
| 122 | 추가: "limit": "같은 시작 장벽은 사용하지만 네이티브 rename 호출의 정확한 겹침을 강제하지 않음. 경로 교체 경합이나 쓰기 중 취소의 증거가 아님", | |
| 123 | 추가: "execution": "not_run" | |
| 124 | 추가: }, | |
| 125 | 추가: "round6_report": { | |
| 126 | 추가: "source_message": "8e7a3d5d-3ce8-4067-9814-c834baaa79bf", | |
| 127 | 추가: "snapshot": "2026-11-09T14:44:04.604469Z", | |
| 128 | 추가: "files": 102, | |
| 129 | 추가: "build": "총괄 보고: Desktop/Core/Runtime/Worker 경고 0 오류 0", | |
| 130 | 추가: "core": { | |
| 131 | 추가: "passed": 41, | |
| 132 | 추가: "failed": 0 | |
| 133 | 추가: }, | |
| 134 | 추가: "runtime": { | |
| 135 | 추가: "registered": 56, | |
| 136 | 추가: "executed": 0, | |
| 137 | 추가: "compile_error": "CS0266 ExtractionPublicationTests.cs(125,22)" | |
| 138 | 추가: }, | |
| 139 | 추가: "scope": "97개 등록 스냅샷의 역사적 결과이며 최신 98개 또는 새 폴더 네이티브 구현 검증 결과가 아님" | |
| 140 | 추가: }, | |
| 141 | 추가: "isolated_compile_fix": { | |
| 142 | 추가: "file": "tests/runtime/ExtractionPublicationTests.cs", | |
| 143 | 추가: "change": "DirectoryInfo info; -> FileSystemInfo info; 한 줄 타입 수정", | |
| 144 | 추가: "before_sha256": "4aca9bcddafc7d0b79030766b24e6171ed5e9e7bedf8d2a9d018c4dfb2135062", | |
| 145 | 추가: "isolated_patch_sha256": "3e2eab3a0a61de4aa967f79a87240e5eae067e81cbe5708575a8f59524049ab5", | |
| 146 | 추가: "scope": "6498a73c-b12c-4d6f-847e-75cf5e8c8a25 메시지로 별도 패치 전달 완료. 현재 파일에는 후속 플랫폼 계약 검사 변경도 포함됨", | |
| 147 | 추가: "csharp_retest": "not_run by this reviewer" | |
| 148 | 추가: }, | |
| 149 | 추가: "historical_test_baseline_sha256": { | |
| 150 | 추가: "tests/runtime/ExtractionPublicationTests.cs": "4aca9bcddafc7d0b79030766b24e6171ed5e9e7bedf8d2a9d018c4dfb2135062", | |
| 151 | 추가: "tests/runtime/ExtractionTests.cs": "9b3c91b2b68694c94e43e80f885f204d7b7d1530a3a7ee8665af2a79382dc3b4", | |
| 152 | 추가: "tests/runtime/Program.cs": "01594a5604de8c257573721b316356baed987050f54778b5db804fa158bc5798", | |
| 153 | 추가: "tests/runtime/ProtocolPeer.cs": "2281458b3459cc205a3b7f3b3484208a7b8ce2595b803d22b48182c21df019b0", | |
| 154 | 추가: "tests/runtime/PublicationTests.cs": "8282b1e0ba19ab67d3a782eb6f41f09a399d2ad20e7982a1bef7dc4bf63fe18f", | |
| 155 | 추가: "tests/runtime/RuntimeTests.cs": "280a394b92c3ccd73f7165c9754cc4e6a3340ada38db59f1c264d9676b1079c9", | |
| 156 | 추가: "tests/security/CoreRegressions.cs": "ec057028990ffc697c665c825a19de5a8893a245877a355217ccb67483663429", | |
| 157 | 추가: "tests/security/CoreTests.cs": "07edd94d65c37b065dc38bcad2e260de54075a74a583419d8d64afadd731295a", | |
| 158 | 추가: "tests/security/PlatformRegressions.cs": "35764df1a192d82b8b264f01f61d2c3e7871341c032111997ec93b1473a95c6b", | |
| 159 | 추가: "tests/security/Program.cs": "3dde4c8bb2c59a115530481474e70d4763eef03f10d6007d6dce323e2e82fc4f", | |
| 160 | 추가: "tests/security/TestSupport.cs": "4ac81f742e1eab9a45c0e045b23309f09d68c7b82759060ddf4362ac4b854a3f" | |
| 161 | 추가: }, | |
| 162 | 추가: "current_folder_test_sha256": { | |
| 163 | 추가: "tests/runtime/ExtractionPublicationTests.cs": "fa3c1996279e0cd43380139281510f860942d8ab207c92aa48f842f8ed163922", | |
| 164 | 추가: "tests/runtime/FolderEnvironment.cs": "2315a49ad2f20531138cb8a639111a0ae40bb3bc3eb39b92c6cbfd54938c2aeb", | |
| 165 | 추가: "tests/runtime/FolderConcurrencyTests.cs": "0e1015734fb0766a26f9db623d99f7e675a92c83ede5b0e35609d9476083cbe6", | |
| 166 | 추가: "tests/runtime/Zipelo.RuntimeTests.csproj": "2a9f75f3d4365ce92e6a92f015a1dc7eec4cd0568b135b8c062a29a3190443ce" | |
| 167 | 추가: } | |
| 168 | 추가: } |
| @@ -0,0 +1,80 @@ | ||
| 1 | 추가: from pathlib import Path | |
| 2 | 추가: import re | |
| 3 | 추가: import unittest | |
| 4 | 추가: import xml.etree.ElementTree as ET | |
| 5 | 추가: | |
| 6 | 추가: | |
| 7 | 추가: ROOT = Path(__file__).resolve().parents[2] | |
| 8 | 추가: DESKTOP = ROOT / "src" / "Zipelo.Desktop" | |
| 9 | 추가: XAML_NAME = "{http://schemas.microsoft.com/winfx/2006/xaml}Name" | |
| 10 | 추가: | |
| 11 | 추가: | |
| 12 | 추가: class DesktopStructureTests(unittest.TestCase): | |
| 13 | 추가: def test_markup_events_have_code_handlers(self): | |
| 14 | 추가: for path in DESKTOP.glob("*.xaml"): | |
| 15 | 추가: tree = ET.parse(path) | |
| 16 | 추가: code = Path(str(path) + ".cs").read_text() | |
| 17 | 추가: for element in tree.iter(): | |
| 18 | 추가: for event in ("Click", "Closing"): | |
| 19 | 추가: if event in element.attrib: | |
| 20 | 추가: handler = element.attrib[event] | |
| 21 | 추가: self.assertRegex(code, rf"\b{re.escape(handler)}\s*\(") | |
| 22 | 추가: | |
| 23 | 추가: def test_named_controls_used_by_code_exist(self): | |
| 24 | 추가: tree = ET.parse(DESKTOP / "MainWindow.xaml") | |
| 25 | 추가: controls = { | |
| 26 | 추가: element.attrib[XAML_NAME]: element | |
| 27 | 추가: for element in tree.iter() | |
| 28 | 추가: if XAML_NAME in element.attrib | |
| 29 | 추가: } | |
| 30 | 추가: for name in ( | |
| 31 | 추가: "OpenButton", "CreateButton", "ExtractButton", "ArchiveTitle", | |
| 32 | 추가: "Availability", "Files", "EmptyState", "Status", "Progress", "StopButton", | |
| 33 | 추가: ): | |
| 34 | 추가: self.assertIn(name, controls) | |
| 35 | 추가: self.assertEqual(controls["Files"].attrib["IsReadOnly"], "True") | |
| 36 | 추가: self.assertEqual(controls["StopButton"].attrib["IsEnabled"], "False") | |
| 37 | 추가: self.assertEqual(controls["Status"].attrib["AutomationProperties.LiveSetting"], "Polite") | |
| 38 | 추가: | |
| 39 | 추가: def test_password_has_no_plaintext_binding_or_persistence(self): | |
| 40 | 추가: tree = ET.parse(DESKTOP / "PasswordWindow.xaml") | |
| 41 | 추가: secret = next(element for element in tree.iter() if element.attrib.get(XAML_NAME) == "Secret") | |
| 42 | 추가: self.assertTrue(secret.tag.endswith("PasswordBox")) | |
| 43 | 추가: for path in DESKTOP.glob("*.cs"): | |
| 44 | 추가: code = path.read_text() | |
| 45 | 추가: self.assertNotRegex(code, r"\bSecret\.Password\b") | |
| 46 | 추가: self.assertNotRegex(code, r"(?:Console|Debug|Trace)\.Write") | |
| 47 | 추가: self.assertNotIn("Process.Start", code) | |
| 48 | 추가: self.assertNotIn("SetEnvironmentVariable", code) | |
| 49 | 추가: code = (DESKTOP / "PasswordWindow.xaml.cs").read_text() | |
| 50 | 추가: self.assertIn("Secret.Clear()", code) | |
| 51 | 추가: self.assertIn("SecurePassword", code) | |
| 52 | 추가: | |
| 53 | 추가: def test_startup_explicitly_has_no_engine(self): | |
| 54 | 추가: code = (DESKTOP / "App.xaml.cs").read_text() | |
| 55 | 추가: self.assertIn("new UnavailableWorkspace()", code) | |
| 56 | 추가: port = (DESKTOP / "WorkspacePort.cs").read_text() | |
| 57 | 추가: self.assertIn("IsAvailable => false", port) | |
| 58 | 추가: self.assertIn("throw new NotSupportedException", port) | |
| 59 | 추가: | |
| 60 | 추가: def test_download_placeholder_has_no_external_or_active_content(self): | |
| 61 | 추가: tree = ET.parse(ROOT / "assets" / "download-pending.svg") | |
| 62 | 추가: for element in tree.iter(): | |
| 63 | 추가: self.assertNotIn(element.tag.split("}")[-1], ("script", "foreignObject", "image", "a")) | |
| 64 | 추가: for attribute in element.attrib: | |
| 65 | 추가: self.assertFalse(attribute.startswith("on")) | |
| 66 | 추가: self.assertNotIn("href", attribute) | |
| 67 | 추가: self.assertIn("준비 중", "".join(tree.getroot().itertext())) | |
| 68 | 추가: | |
| 69 | 추가: def test_publish_is_windows_x64_without_unsafe_trimming(self): | |
| 70 | 추가: tree = ET.parse(DESKTOP / "Properties" / "PublishProfiles" / "WindowsX64.pubxml") | |
| 71 | 추가: self.assertEqual(tree.findtext(".//RuntimeIdentifier"), "win-x64") | |
| 72 | 추가: self.assertEqual(tree.findtext(".//PublishTrimmed"), "false") | |
| 73 | 추가: ET.parse(DESKTOP / "Zipelo.Desktop.csproj") | |
| 74 | 추가: manifest = ET.parse(DESKTOP / "app.manifest") | |
| 75 | 추가: privilege = next(element for element in manifest.iter() if element.tag.endswith("requestedExecutionLevel")) | |
| 76 | 추가: self.assertEqual(privilege.attrib["level"], "asInvoker") | |
| 77 | 추가: | |
| 78 | 추가: | |
| 79 | 추가: if __name__ == "__main__": | |
| 80 | 추가: unittest.main() |
| @@ -0,0 +1,144 @@ | ||
| 1 | 추가: import argparse | |
| 2 | 추가: import importlib.util | |
| 3 | 추가: import os | |
| 4 | 추가: from pathlib import Path | |
| 5 | 추가: import shutil | |
| 6 | 추가: import subprocess | |
| 7 | 추가: import sys | |
| 8 | 추가: import tempfile | |
| 9 | 추가: import unittest | |
| 10 | 추가: | |
| 11 | 추가: | |
| 12 | 추가: ROOT = Path(__file__).resolve().parents[1] | |
| 13 | 추가: TESTS = ROOT / "tests" | |
| 14 | 추가: SECURITY = TESTS / "security" | |
| 15 | 추가: BUILD_TIMEOUT = 120 | |
| 16 | 추가: CORE_TIMEOUT = 60 | |
| 17 | 추가: | |
| 18 | 추가: | |
| 19 | 추가: def python_checks(): | |
| 20 | 추가: suite = unittest.TestSuite() | |
| 21 | 추가: for index, path in enumerate(sorted(TESTS.rglob("check_*.py"))): | |
| 22 | 추가: if any(part in (".work", "bin", "obj", "__pycache__") for part in path.relative_to(TESTS).parts): | |
| 23 | 추가: continue | |
| 24 | 추가: spec = importlib.util.spec_from_file_location(f"zipelo_checks_{index}", path) | |
| 25 | 추가: module = importlib.util.module_from_spec(spec) | |
| 26 | 추가: spec.loader.exec_module(module) | |
| 27 | 추가: suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module)) | |
| 28 | 추가: return unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() | |
| 29 | 추가: | |
| 30 | 추가: | |
| 31 | 추가: def check_work_path(path): | |
| 32 | 추가: work = SECURITY / ".work" | |
| 33 | 추가: if ".." in path.parts or (path != work and not path.is_relative_to(work)): | |
| 34 | 추가: raise ValueError("프로젝트 안의 테스트 임시 영역이 필요함") | |
| 35 | 추가: for ancestor in (path, *path.parents): | |
| 36 | 추가: if ancestor.is_symlink() or (hasattr(ancestor, "is_junction") and ancestor.is_junction()): | |
| 37 | 추가: raise ValueError("테스트 작업 경로의 링크를 허용하지 않음") | |
| 38 | 추가: | |
| 39 | 추가: | |
| 40 | 추가: def core_checks(): | |
| 41 | 추가: return csharp_checks("security", "Zipelo.SecurityTests", CORE_TIMEOUT) | |
| 42 | 추가: | |
| 43 | 추가: | |
| 44 | 추가: def runtime_checks(): | |
| 45 | 추가: return csharp_checks("runtime", "Zipelo.RuntimeTests", 120) | |
| 46 | 추가: | |
| 47 | 추가: | |
| 48 | 추가: def csharp_checks(folder, assembly_name, timeout): | |
| 49 | 추가: dotnet = shutil.which("dotnet") | |
| 50 | 추가: if dotnet is None: | |
| 51 | 추가: print("미실행: .NET 10 SDK가 PATH에 없어 C# 검사를 빌드하거나 실행하지 못함", flush=True) | |
| 52 | 추가: return 2 | |
| 53 | 추가: | |
| 54 | 추가: work = SECURITY / ".work" | |
| 55 | 추가: check_work_path(work) | |
| 56 | 추가: work.mkdir(exist_ok=True) | |
| 57 | 추가: | |
| 58 | 추가: # 빌드 결과, SDK 캐시와 실행 입력을 이번 테스트 소유 폴더에만 둠. | |
| 59 | 추가: with tempfile.TemporaryDirectory(prefix="run-", dir=work) as temporary: | |
| 60 | 추가: sandbox = Path(temporary) | |
| 61 | 추가: check_work_path(sandbox) | |
| 62 | 추가: environment = os.environ.copy() | |
| 63 | 추가: for variable, child in ( | |
| 64 | 추가: ("DOTNET_CLI_HOME", "dotnet-home"), | |
| 65 | 추가: ("NUGET_PACKAGES", "nuget-packages"), | |
| 66 | 추가: ("NUGET_HTTP_CACHE_PATH", "nuget-http-cache"), | |
| 67 | 추가: ("TMPDIR", "temp"), | |
| 68 | 추가: ("TMP", "temp"), | |
| 69 | 추가: ("TEMP", "temp"), | |
| 70 | 추가: ): | |
| 71 | 추가: location = sandbox / child | |
| 72 | 추가: location.mkdir(exist_ok=True) | |
| 73 | 추가: environment[variable] = str(location) | |
| 74 | 추가: environment["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1" | |
| 75 | 추가: environment["DOTNET_SKIP_FIRST_TIME_EXPERIENCE"] = "1" | |
| 76 | 추가: environment["DOTNET_CLI_WORKLOAD_UPDATE_NOTIFY_DISABLE"] = "true" | |
| 77 | 추가: binary_directory = sandbox / "bin" | |
| 78 | 추가: build = [ | |
| 79 | 추가: dotnet, | |
| 80 | 추가: "build", | |
| 81 | 추가: str(TESTS / folder / f"{assembly_name}.csproj"), | |
| 82 | 추가: "--configuration", "Release", | |
| 83 | 추가: "--artifacts-path", str(sandbox / "artifacts"), | |
| 84 | 추가: "--output", str(binary_directory), | |
| 85 | 추가: "--configfile", str(SECURITY / "NuGet.Config"), | |
| 86 | 추가: "--disable-build-servers", | |
| 87 | 추가: "-p:UseAppHost=false", | |
| 88 | 추가: ] | |
| 89 | 추가: print(f"C# 테스트 빌드: tests/{folder}/{assembly_name}.csproj", flush=True) | |
| 90 | 추가: try: | |
| 91 | 추가: built = subprocess.run( | |
| 92 | 추가: build, cwd=sandbox, env=environment, check=False, timeout=BUILD_TIMEOUT | |
| 93 | 추가: ) | |
| 94 | 추가: if built.returncode != 0: | |
| 95 | 추가: return built.returncode | |
| 96 | 추가: | |
| 97 | 추가: assembly = binary_directory / f"{assembly_name}.dll" | |
| 98 | 추가: check_work_path(assembly) | |
| 99 | 추가: if not assembly.is_file(): | |
| 100 | 추가: print("실행 실패: 빌드된 테스트 DLL이 없음", flush=True) | |
| 101 | 추가: return 2 | |
| 102 | 추가: | |
| 103 | 추가: if folder == "runtime": | |
| 104 | 추가: for name in ("Zipelo.Worker.dll", "Zipelo.Worker.deps.json", "Zipelo.Worker.runtimeconfig.json"): | |
| 105 | 추가: artifact = binary_directory / name | |
| 106 | 추가: check_work_path(artifact) | |
| 107 | 추가: if not artifact.is_file(): | |
| 108 | 추가: print(f"실행 실패: 작업자 빌드 파일이 없음: {name}", flush=True) | |
| 109 | 추가: return 2 | |
| 110 | 추가: | |
| 111 | 추가: # 빌드 옵션을 앱 인수로 넘기지 않고 루트와 임시 경로만 전달함. | |
| 112 | 추가: command = [dotnet, str(assembly), str(ROOT), str(sandbox)] | |
| 113 | 추가: print(f"{assembly_name} DLL 실행", flush=True) | |
| 114 | 추가: completed = subprocess.run( | |
| 115 | 추가: command, cwd=sandbox, env=environment, check=False, timeout=timeout | |
| 116 | 추가: ) | |
| 117 | 추가: return completed.returncode | |
| 118 | 추가: except subprocess.TimeoutExpired: | |
| 119 | 추가: print("실행 실패: C# 빌드 또는 테스트 제한 시간을 초과함", flush=True) | |
| 120 | 추가: return 124 | |
| 121 | 추가: | |
| 122 | 추가: | |
| 123 | 추가: def main(): | |
| 124 | 추가: parser = argparse.ArgumentParser(description="프로젝트 루트 tests/의 검사를 실행함") | |
| 125 | 추가: parser.add_argument("--core", action="store_true", help=".NET 10 코어 회귀 검사도 실행함") | |
| 126 | 추가: parser.add_argument("--runtime", action="store_true", help="실제 ZIP 작업자와 프로토콜 회귀 검사도 실행함") | |
| 127 | 추가: options = parser.parse_args() | |
| 128 | 추가: sys.dont_write_bytecode = True | |
| 129 | 추가: if not python_checks(): | |
| 130 | 추가: return 1 | |
| 131 | 추가: for enabled, run in ((options.core, core_checks), (options.runtime, runtime_checks)): | |
| 132 | 추가: if enabled: | |
| 133 | 추가: code = run() | |
| 134 | 추가: if code != 0: | |
| 135 | 추가: return code | |
| 136 | 추가: if not options.core: | |
| 137 | 추가: print("미실행: 코어 회귀 검사. .NET 10 SDK 환경에서 --core로 실행해야 함", flush=True) | |
| 138 | 추가: if not options.runtime: | |
| 139 | 추가: print("미실행: 런타임 회귀 검사. .NET 10 SDK 환경에서 --runtime으로 실행해야 함", flush=True) | |
| 140 | 추가: return 0 | |
| 141 | 추가: | |
| 142 | 추가: | |
| 143 | 추가: if __name__ == "__main__": | |
| 144 | 추가: raise SystemExit(main()) |
| @@ -0,0 +1,232 @@ | ||
| 1 | 추가: using System.Security.Cryptography; | |
| 2 | 추가: using System.Text.Json; | |
| 3 | 추가: using Zipelo.Core; | |
| 4 | 추가: using Zipelo.Runtime; | |
| 5 | 추가: using Zipelo.SecurityTests; | |
| 6 | 추가: | |
| 7 | 추가: namespace Zipelo.RuntimeTests; | |
| 8 | 추가: | |
| 9 | 추가: internal sealed partial class ExtractionTests | |
| 10 | 추가: { | |
| 11 | 추가: private static void RequireFolderImplementation() | |
| 12 | 추가: { | |
| 13 | 추가: if (!NewFolderPublisher.IsSupportedPlatform) | |
| 14 | 추가: { | |
| 15 | 추가: throw new CaseSkippedException("이 OS의 새 폴더 게시가 실패 폐쇄 상태이므로 실제 게시 검사 미실행"); | |
| 16 | 추가: } | |
| 17 | 추가: } | |
| 18 | 추가: | |
| 19 | 추가: private static void RequireFolderDestination(string parent) | |
| 20 | 추가: { | |
| 21 | 추가: var environment = FolderEnvironment.Inspect(parent); | |
| 22 | 추가: if (environment.Rejection is not null) | |
| 23 | 추가: { | |
| 24 | 추가: throw new CaseSkippedException("실제 게시 수용 검사 미실행: " + environment.Description); | |
| 25 | 추가: } | |
| 26 | 추가: } | |
| 27 | 추가: | |
| 28 | 추가: private async Task FolderPlatform() | |
| 29 | 추가: { | |
| 30 | 추가: var entryAvailable = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture == | |
| 31 | 추가: System.Runtime.InteropServices.Architecture.X64 && (OperatingSystem.IsWindows() || OperatingSystem.IsLinux()); | |
| 32 | 추가: Check.Equal(entryAvailable, NewFolderPublisher.IsSupportedPlatform); | |
| 33 | 추가: Check.That(!Worker.SupportsSafeExtraction, "OS 검증 전에 일반 UI의 해제를 활성화함"); | |
| 34 | 추가: var area = await NewArea(); | |
| 35 | 추가: var environment = FolderEnvironment.Inspect(area.Root); | |
| 36 | 추가: Console.WriteLine("OBSERVED folder.platform_contract: " + environment.Description); | |
| 37 | 추가: var extracted = await ExtractArea(area); | |
| 38 | 추가: var destination = Path.Combine(area.Root, "result"); | |
| 39 | 추가: if (environment.Rejection is not { } expectedError) | |
| 40 | 추가: { | |
| 41 | 추가: var result = await NewFolderPublisher.PublishAsync(extracted, destination, default); | |
| 42 | 추가: Check.That(result.Published, "지원 저장 조건에서 실제 게시가 실패함"); | |
| 43 | 추가: Check.Equal(ArchiveError.None, result.Error); | |
| 44 | 추가: Check.That(!result.CleanupFailed && result.TemporaryFileName is null, "성공 뒤 임시 결과가 남음"); | |
| 45 | 추가: await Preserved(area, "source.zip", "sentinel.txt", "result"); | |
| 46 | 추가: await VerifyPublishedTree(destination, Successful(extracted)); | |
| 47 | 추가: return; | |
| 48 | 추가: } | |
| 49 | 추가: | |
| 50 | 추가: var existing = Path.Combine(area.Root, "existing"); | |
| 51 | 추가: Directory.CreateDirectory(existing); | |
| 52 | 추가: await File.WriteAllTextAsync(Path.Combine(existing, "keep.txt"), "기존 폴더 표식"); | |
| 53 | 추가: foreach (var target in new[] { destination, area.Source, existing }) | |
| 54 | 추가: { | |
| 55 | 추가: var result = await NewFolderPublisher.PublishAsync(extracted, target, default); | |
| 56 | 추가: await Preserved(area, "source.zip", "sentinel.txt", "existing"); | |
| 57 | 추가: ExactChildren(existing, "keep.txt"); | |
| 58 | 추가: Check.Equal("기존 폴더 표식", await File.ReadAllTextAsync(Path.Combine(existing, "keep.txt"))); | |
| 59 | 추가: PublicationFailure(result, expectedError); | |
| 60 | 추가: } | |
| 61 | 추가: } | |
| 62 | 추가: | |
| 63 | 추가: private async Task PublishFolder() | |
| 64 | 추가: { | |
| 65 | 추가: RequireFolderImplementation(); | |
| 66 | 추가: var area = await NewArea(); | |
| 67 | 추가: RequireFolderDestination(area.Root); | |
| 68 | 추가: var destination = Path.Combine(area.Root, "result"); | |
| 69 | 추가: var extracted = await ExtractArea(area); | |
| 70 | 추가: Successful(extracted); | |
| 71 | 추가: var result = await NewFolderPublisher.PublishAsync(extracted, destination, default); | |
| 72 | 추가: await Preserved(area, "source.zip", "sentinel.txt", "result"); | |
| 73 | 추가: Check.That(result.Published, "안전 규칙을 만족하는 새 폴더 게시가 실패함"); | |
| 74 | 추가: Check.Equal(ArchiveError.None, result.Error); | |
| 75 | 추가: Check.That(!result.CleanupFailed && result.TemporaryFileName is null, "성공 뒤 임시 결과가 남음"); | |
| 76 | 추가: ExactChildren(destination, "hello.txt", "nested"); | |
| 77 | 추가: ExactChildren(Path.Combine(destination, "nested"), "data.bin", "empty.txt"); | |
| 78 | 추가: using var manifest = JsonDocument.Parse(await File.ReadAllTextAsync( | |
| 79 | 추가: Path.Combine(root, "tests", "extraction", "fixtures.json"))); | |
| 80 | 추가: foreach (var expected in manifest.RootElement.GetProperty("normal_files").EnumerateObject()) | |
| 81 | 추가: { | |
| 82 | 추가: var path = Path.Combine(destination, expected.Name.Replace('/', Path.DirectorySeparatorChar)); | |
| 83 | 추가: var bytes = await File.ReadAllBytesAsync(path); | |
| 84 | 추가: Check.Equal(expected.Value.GetProperty("bytes").GetInt32(), bytes.Length); | |
| 85 | 추가: Check.Equal(expected.Value.GetProperty("sha256").GetString(), Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant()); | |
| 86 | 추가: } | |
| 87 | 추가: } | |
| 88 | 추가: | |
| 89 | 추가: private async Task FolderConflict(bool folder) | |
| 90 | 추가: { | |
| 91 | 추가: RequireFolderImplementation(); | |
| 92 | 추가: var area = await NewArea(); | |
| 93 | 추가: RequireFolderDestination(area.Root); | |
| 94 | 추가: var destination = folder ? Path.Combine(area.Root, "existing") : area.Source; | |
| 95 | 추가: if (folder) | |
| 96 | 추가: { | |
| 97 | 추가: Directory.CreateDirectory(destination); | |
| 98 | 추가: await File.WriteAllTextAsync(Path.Combine(destination, "keep.txt"), "기존 폴더 내용"); | |
| 99 | 추가: } | |
| 100 | 추가: var result = await NewFolderPublisher.PublishAsync(await ExtractArea(area), destination, default); | |
| 101 | 추가: await Preserved(area, folder ? ["source.zip", "sentinel.txt", "existing"] : ["source.zip", "sentinel.txt"]); | |
| 102 | 추가: if (folder) | |
| 103 | 추가: { | |
| 104 | 추가: ExactChildren(destination, "keep.txt"); | |
| 105 | 추가: Check.Equal("기존 폴더 내용", await File.ReadAllTextAsync(Path.Combine(destination, "keep.txt"))); | |
| 106 | 추가: } | |
| 107 | 추가: PublicationFailure(result, ArchiveError.OutputConflict); | |
| 108 | 추가: } | |
| 109 | 추가: | |
| 110 | 추가: private async Task FolderPreCancelled() | |
| 111 | 추가: { | |
| 112 | 추가: var area = await NewArea(); | |
| 113 | 추가: var extracted = await ExtractArea(area); | |
| 114 | 추가: using var cancellation = new CancellationTokenSource(); | |
| 115 | 추가: cancellation.Cancel(); | |
| 116 | 추가: foreach (var destination in new[] { Path.Combine(area.Root, "result"), area.Source }) | |
| 117 | 추가: { | |
| 118 | 추가: var result = await NewFolderPublisher.PublishAsync(extracted, destination, cancellation.Token); | |
| 119 | 추가: await Preserved(area, "source.zip", "sentinel.txt"); | |
| 120 | 추가: PublicationFailure(result, ArchiveError.Cancelled); | |
| 121 | 추가: } | |
| 122 | 추가: } | |
| 123 | 추가: | |
| 124 | 추가: private async Task FolderRejectsTamperedBytes() | |
| 125 | 추가: { | |
| 126 | 추가: RequireFolderImplementation(); | |
| 127 | 추가: var area = await NewArea(); | |
| 128 | 추가: var extracted = await ExtractArea(area); | |
| 129 | 추가: var items = Successful(extracted); | |
| 130 | 추가: items.Single(item => item.Entry.Name == "hello.txt").Content[0] ^= 1; | |
| 131 | 추가: var result = await NewFolderPublisher.PublishAsync(extracted, Path.Combine(area.Root, "result"), default); | |
| 132 | 추가: await Preserved(area, "source.zip", "sentinel.txt"); | |
| 133 | 추가: PublicationFailure(result, ArchiveError.IntegrityFailure); | |
| 134 | 추가: } | |
| 135 | 추가: | |
| 136 | 추가: private async Task FolderRejectsFailedExtraction() | |
| 137 | 추가: { | |
| 138 | 추가: RequireFolderImplementation(); | |
| 139 | 추가: var area = await NewArea(); | |
| 140 | 추가: var extracted = await Extract("bad-payload-crc.zip"); | |
| 141 | 추가: Failure(extracted, ArchiveError.IntegrityFailure); | |
| 142 | 추가: var result = await NewFolderPublisher.PublishAsync(extracted, Path.Combine(area.Root, "result"), default); | |
| 143 | 추가: await Preserved(area, "source.zip", "sentinel.txt"); | |
| 144 | 추가: PublicationFailure(result, ArchiveError.EngineFailure); | |
| 145 | 추가: } | |
| 146 | 추가: | |
| 147 | 추가: private async Task FolderRejectsLink(bool parent) | |
| 148 | 추가: { | |
| 149 | 추가: RequireFolderImplementation(); | |
| 150 | 추가: var area = await NewArea(); | |
| 151 | 추가: if (!parent) { RequireFolderDestination(area.Root); } | |
| 152 | 추가: var target = Path.Combine(area.Root, "target"); | |
| 153 | 추가: Directory.CreateDirectory(target); | |
| 154 | 추가: await File.WriteAllTextAsync(Path.Combine(target, "keep.txt"), "링크 대상 내용"); | |
| 155 | 추가: var link = Path.Combine(area.Root, "link"); | |
| 156 | 추가: FileSystemInfo info; | |
| 157 | 추가: try { info = Directory.CreateSymbolicLink(link, target); } | |
| 158 | 추가: catch (UnauthorizedAccessException) when (OperatingSystem.IsWindows()) | |
| 159 | 추가: { | |
| 160 | 추가: throw new CaseSkippedException("Windows 심볼릭 링크 생성 권한이 없어 해당 사례 미실행"); | |
| 161 | 추가: } | |
| 162 | 추가: catch (IOException failure) when (OperatingSystem.IsWindows() && (failure.HResult & 0xFFFF) == 1314) | |
| 163 | 추가: { | |
| 164 | 추가: throw new CaseSkippedException("Windows 심볼릭 링크 생성 권한이 없어 해당 사례 미실행"); | |
| 165 | 추가: } | |
| 166 | 추가: try | |
| 167 | 추가: { | |
| 168 | 추가: var originalTarget = info.LinkTarget; | |
| 169 | 추가: Check.That(originalTarget is not null, "검사 링크의 대상 정보가 없음"); | |
| 170 | 추가: var destination = parent ? Path.Combine(link, "result") : link; | |
| 171 | 추가: var result = await NewFolderPublisher.PublishAsync(await ExtractArea(area), destination, default); | |
| 172 | 추가: await Preserved(area, "source.zip", "sentinel.txt", "target", "link"); | |
| 173 | 추가: ExactChildren(target, "keep.txt"); | |
| 174 | 추가: Check.Equal("링크 대상 내용", await File.ReadAllTextAsync(Path.Combine(target, "keep.txt"))); | |
| 175 | 추가: info.Refresh(); | |
| 176 | 추가: Check.That((info.Attributes & FileAttributes.ReparsePoint) != 0, "기존 링크를 교체함"); | |
| 177 | 추가: Check.Equal(originalTarget, info.LinkTarget); | |
| 178 | 추가: PublicationFailure(result, parent ? ArchiveError.UnsafePath : ArchiveError.OutputConflict); | |
| 179 | 추가: } | |
| 180 | 추가: finally { info.Delete(); } | |
| 181 | 추가: } | |
| 182 | 추가: | |
| 183 | 추가: private static void PublicationFailure(ZipPublicationResult result, ArchiveError error) | |
| 184 | 추가: { | |
| 185 | 추가: Check.That(!result.Published, "실패한 해제 결과를 게시 완료로 표시함"); | |
| 186 | 추가: Check.Equal(error, result.Error); | |
| 187 | 추가: Check.That(!result.CleanupFailed && result.TemporaryFileName is null, "작업 소유 임시 결과를 정리하지 못함"); | |
| 188 | 추가: } | |
| 189 | 추가: | |
| 190 | 추가: private async Task<Area> NewArea() | |
| 191 | 추가: { | |
| 192 | 추가: var directory = Path.Combine(sandbox, "extract-" + Guid.NewGuid().ToString("N")); | |
| 193 | 추가: Directory.CreateDirectory(directory); | |
| 194 | 추가: var source = Path.Combine(directory, "source.zip"); | |
| 195 | 추가: File.Copy(FixturePath("normal-deflated.zip"), source); | |
| 196 | 추가: await File.WriteAllTextAsync(Path.Combine(directory, "sentinel.txt"), "기존 표식"); | |
| 197 | 추가: return new(directory, source, SHA256.HashData(await File.ReadAllBytesAsync(source))); | |
| 198 | 추가: } | |
| 199 | 추가: | |
| 200 | 추가: private static async Task<ZipWorkerResult> ExtractArea(Area area) | |
| 201 | 추가: { | |
| 202 | 추가: await using var input = new FileStream(area.Source, FileMode.Open, FileAccess.Read, FileShare.Read); | |
| 203 | 추가: var result = await Worker.ExtractAsync(Guid.NewGuid(), input, Limits, default); | |
| 204 | 추가: Successful(result); | |
| 205 | 추가: return result; | |
| 206 | 추가: } | |
| 207 | 추가: | |
| 208 | 추가: private static async Task Preserved(Area area, params string[] expected) | |
| 209 | 추가: { | |
| 210 | 추가: var hash = SHA256.HashData(await File.ReadAllBytesAsync(area.Source)); | |
| 211 | 추가: Check.That(area.SourceHash.SequenceEqual(hash), "해제나 게시 실패로 원본이 변경됨"); | |
| 212 | 추가: Check.Equal("기존 표식", await File.ReadAllTextAsync(Path.Combine(area.Root, "sentinel.txt"))); | |
| 213 | 추가: ExactChildren(area.Root, expected, allowLinks: true); | |
| 214 | 추가: } | |
| 215 | 추가: | |
| 216 | 추가: private static void ExactChildren(string directory, params string[] expected) | |
| 217 | 추가: => ExactChildren(directory, expected, allowLinks: false); | |
| 218 | 추가: | |
| 219 | 추가: private static void ExactChildren(string directory, string[] expected, bool allowLinks) | |
| 220 | 추가: { | |
| 221 | 추가: var paths = Directory.GetFileSystemEntries(directory); | |
| 222 | 추가: Check.That(paths.Select(path => Path.GetFileName(path) ?? throw new InvalidOperationException()).Order(StringComparer.Ordinal) | |
| 223 | 추가: .SequenceEqual(expected.Order(StringComparer.Ordinal)), "예상하지 않은 파일이나 임시 결과가 남음"); | |
| 224 | 추가: if (!allowLinks) | |
| 225 | 추가: { | |
| 226 | 추가: Check.That(paths.All(path => (File.GetAttributes(path) & FileAttributes.ReparsePoint) == 0), | |
| 227 | 추가: "새 결과에 링크가 포함됨"); | |
| 228 | 추가: } | |
| 229 | 추가: } | |
| 230 | 추가: | |
| 231 | 추가: private sealed record Area(string Root, string Source, byte[] SourceHash); | |
| 232 | 추가: } |
| @@ -0,0 +1,196 @@ | ||
| 1 | 추가: using System.Security.Cryptography; | |
| 2 | 추가: using System.Text; | |
| 3 | 추가: using System.Text.Json; | |
| 4 | 추가: using Zipelo.Core; | |
| 5 | 추가: using Zipelo.Runtime; | |
| 6 | 추가: using Zipelo.SecurityTests; | |
| 7 | 추가: | |
| 8 | 추가: namespace Zipelo.RuntimeTests; | |
| 9 | 추가: | |
| 10 | 추가: internal sealed partial class ExtractionTests(string root, string sandbox) | |
| 11 | 추가: { | |
| 12 | 추가: private static JobLimits Limits => new(32, 1024 * 1024, 1024 * 1024, TimeSpan.FromSeconds(15), 3); | |
| 13 | 추가: private static ZipWorkerClient Worker => new(Path.Combine(AppContext.BaseDirectory, "Zipelo.Worker.dll"), | |
| 14 | 추가: Environment.ProcessPath ?? throw new InvalidOperationException()); | |
| 15 | 추가: | |
| 16 | 추가: public IEnumerable<(string Name, Func<Task> Run)> Cases() | |
| 17 | 추가: { | |
| 18 | 추가: yield return ("extract.stored_contents_hashes_and_source", () => Normal("normal-stored.zip")); | |
| 19 | 추가: yield return ("extract.deflated_contents_hashes_and_source", () => Normal("normal-deflated.zip")); | |
| 20 | 추가: foreach (var name in new[] { "traversal", "absolute-posix", "absolute-unc" }) | |
| 21 | 추가: { | |
| 22 | 추가: yield return ($"extract.reject_{name}", () => Reject(name + ".zip", ArchiveError.UnsafePath)); | |
| 23 | 추가: } | |
| 24 | 추가: yield return ("extract.backslash_policy_by_os", () => NamesByOs("backslash-traversal.zip", | |
| 25 | 추가: ArchiveError.UnsafePath, new Dictionary<string, byte[]> { ["..\\escape.txt"] = Payload })); | |
| 26 | 추가: yield return ("extract.drive_name_policy_by_os", () => NamesByOs("absolute-drive.zip", | |
| 27 | 추가: ArchiveError.UnsafePath, new Dictionary<string, byte[]> { ["C:/escape.txt"] = Payload })); | |
| 28 | 추가: foreach (var name in new[] { "duplicate", "file-before-child", "child-before-file" }) | |
| 29 | 추가: { | |
| 30 | 추가: yield return ($"extract.reject_{name}", () => Reject(name + ".zip", ArchiveError.OutputConflict)); | |
| 31 | 추가: } | |
| 32 | 추가: yield return ("extract.case_policy_by_os", () => NamesByOs("case-distinct.zip", ArchiveError.OutputConflict, | |
| 33 | 추가: new Dictionary<string, byte[]> { ["Readme.txt"] = "first"u8.ToArray(), ["README.TXT"] = "second"u8.ToArray() })); | |
| 34 | 추가: yield return ("extract.legal_linux_names", () => NamesByOs("linux-names.zip", ArchiveError.UnsafePath, | |
| 35 | 추가: new Dictionary<string, byte[]> { ["CON"] = "one"u8.ToArray(), ["name:stream"] = "two"u8.ToArray() })); | |
| 36 | 추가: foreach (var name in new[] { "symlink", "unix-hardlink", "special-fifo" }) | |
| 37 | 추가: { | |
| 38 | 추가: yield return ($"extract.reject_{name}", () => Reject(name + ".zip", ArchiveError.UnsupportedEntry)); | |
| 39 | 추가: } | |
| 40 | 추가: foreach (var name in new[] { "bad-payload-crc", "bad-header-crc", "length-smaller", "length-larger", | |
| 41 | 추가: "local-central-length", "truncated" }) | |
| 42 | 추가: { | |
| 43 | 추가: yield return ($"extract.reject_{name}", () => Reject(name + ".zip", ArchiveError.IntegrityFailure)); | |
| 44 | 추가: } | |
| 45 | 추가: yield return ("extract.cumulative_output_budget", () => Budget("output")); | |
| 46 | 추가: yield return ("extract.cumulative_processed_budget", () => Budget("processed")); | |
| 47 | 추가: yield return ("extract.cumulative_entry_budget", () => Budget("entries")); | |
| 48 | 추가: yield return ("extract.cancel_before_read", PreCancelled); | |
| 49 | 추가: yield return ("extract.cancel_during_input_copy", CancelInput); | |
| 50 | 추가: yield return ("folder.platform_contract", FolderPlatform); | |
| 51 | 추가: yield return ("folder.new_folder_contents_hashes_and_source", PublishFolder); | |
| 52 | 추가: yield return ("folder.existing_folder_preserved_and_temporary_cleanup", () => FolderConflict(true)); | |
| 53 | 추가: yield return ("folder.existing_source_file_preserved_and_temporary_cleanup", () => FolderConflict(false)); | |
| 54 | 추가: yield return ("folder.precancel_preserves_originals", FolderPreCancelled); | |
| 55 | 추가: yield return ("folder.tampered_bytes_not_published", FolderRejectsTamperedBytes); | |
| 56 | 추가: yield return ("folder.failed_extraction_not_published", FolderRejectsFailedExtraction); | |
| 57 | 추가: yield return ("folder.reject_parent_symlink", () => FolderRejectsLink(true)); | |
| 58 | 추가: yield return ("folder.reject_leaf_symlink", () => FolderRejectsLink(false)); | |
| 59 | 추가: yield return ("folder.concurrent_same_name_one_winner", FolderConcurrentPublish); | |
| 60 | 추가: } | |
| 61 | 추가: | |
| 62 | 추가: private static byte[] Payload => "zipelo-extraction-content\n"u8.ToArray(); | |
| 63 | 추가: private string FixturePath(string name) => Path.Combine(root, "tests", "extraction", "fixtures", name); | |
| 64 | 추가: | |
| 65 | 추가: private async Task<ZipWorkerResult> Extract(string name, JobLimits? limits = null) | |
| 66 | 추가: { | |
| 67 | 추가: var path = FixturePath(name); | |
| 68 | 추가: var before = SHA256.HashData(await File.ReadAllBytesAsync(path)); | |
| 69 | 추가: ZipWorkerResult result; | |
| 70 | 추가: await using (var input = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) | |
| 71 | 추가: { | |
| 72 | 추가: result = await Worker.ExtractAsync(Guid.NewGuid(), input, limits ?? Limits, default); | |
| 73 | 추가: Check.That(input.CanRead && !input.CanWrite, "해제 요청이 원본 스트림 소유권을 변경함"); | |
| 74 | 추가: } | |
| 75 | 추가: var after = SHA256.HashData(await File.ReadAllBytesAsync(path)); | |
| 76 | 추가: Check.That(before.SequenceEqual(after), "해제 요청이 원본 ZIP을 변경함"); | |
| 77 | 추가: return result; | |
| 78 | 추가: } | |
| 79 | 추가: | |
| 80 | 추가: private static IReadOnlyList<ZipExtractedEntry> Successful(ZipWorkerResult result) | |
| 81 | 추가: { | |
| 82 | 추가: Check.Equal(JobState.Completed, result.Job.State); | |
| 83 | 추가: Check.Equal(ArchiveError.None, result.Job.Error); | |
| 84 | 추가: Check.That(result.CreatedZip is null, "해제 요청이 생성 ZIP을 반환함"); | |
| 85 | 추가: var items = result.ExtractedEntries ?? throw new InvalidOperationException(); | |
| 86 | 추가: Check.Equal(items.Count, result.Job.Entries.Count); | |
| 87 | 추가: for (var index = 0; index < items.Count; index++) | |
| 88 | 추가: { | |
| 89 | 추가: Check.Equal(items[index].Entry, result.Job.Entries[index].Entry); | |
| 90 | 추가: Check.Equal(EntryOutcome.Staged, result.Job.Entries[index].Outcome); | |
| 91 | 추가: Check.Equal(VerificationState.Passed, result.Job.Entries[index].Verification); | |
| 92 | 추가: Check.Equal(ArchiveError.None, result.Job.Entries[index].Error); | |
| 93 | 추가: Check.Equal((long?)items[index].Content.LongLength, items[index].Entry.DeclaredSize); | |
| 94 | 추가: } | |
| 95 | 추가: return items; | |
| 96 | 추가: } | |
| 97 | 추가: | |
| 98 | 추가: private static void Failure(ZipWorkerResult result, ArchiveError error) | |
| 99 | 추가: { | |
| 100 | 추가: Check.Equal(error, result.Job.Error); | |
| 101 | 추가: Check.Equal(error == ArchiveError.Cancelled ? JobState.Cancelled : JobState.Failed, result.Job.State); | |
| 102 | 추가: Check.That(result.CreatedZip is null && result.ExtractedEntries is null, | |
| 103 | 추가: "실패나 취소 뒤 부분 해제 결과를 반환함"); | |
| 104 | 추가: } | |
| 105 | 추가: | |
| 106 | 추가: private async Task Normal(string name) | |
| 107 | 추가: { | |
| 108 | 추가: var items = Successful(await Extract(name)); | |
| 109 | 추가: Check.Equal(4, items.Count); | |
| 110 | 추가: var directory = items.Single(item => item.Entry.Kind == EntryKind.Directory); | |
| 111 | 추가: Check.Equal("nested", directory.Entry.Name); | |
| 112 | 추가: Check.Equal(0, directory.Content.Length); | |
| 113 | 추가: using var manifest = JsonDocument.Parse(await File.ReadAllTextAsync( | |
| 114 | 추가: Path.Combine(root, "tests", "extraction", "fixtures.json"))); | |
| 115 | 추가: var expected = manifest.RootElement.GetProperty("normal_files"); | |
| 116 | 추가: foreach (var item in items.Where(item => item.Entry.Kind == EntryKind.File)) | |
| 117 | 추가: { | |
| 118 | 추가: var entry = expected.GetProperty(item.Entry.Name); | |
| 119 | 추가: Check.Equal(entry.GetProperty("bytes").GetInt32(), item.Content.Length); | |
| 120 | 추가: Check.Equal(entry.GetProperty("sha256").GetString(), Convert.ToHexString(SHA256.HashData(item.Content)).ToLowerInvariant()); | |
| 121 | 추가: } | |
| 122 | 추가: Check.Equal(3, items.Count(item => item.Entry.Kind == EntryKind.File)); | |
| 123 | 추가: } | |
| 124 | 추가: | |
| 125 | 추가: private async Task Reject(string name, ArchiveError error) => Failure(await Extract(name), error); | |
| 126 | 추가: | |
| 127 | 추가: private async Task NamesByOs(string name, ArchiveError windowsError, IReadOnlyDictionary<string, byte[]> expected) | |
| 128 | 추가: { | |
| 129 | 추가: var result = await Extract(name); | |
| 130 | 추가: if (OperatingSystem.IsWindows()) { Failure(result, windowsError); return; } | |
| 131 | 추가: var items = Successful(result); | |
| 132 | 추가: Check.Equal(expected.Count, items.Count); | |
| 133 | 추가: var names = new HashSet<string>(StringComparer.Ordinal); | |
| 134 | 추가: foreach (var item in items) | |
| 135 | 추가: { | |
| 136 | 추가: Check.That(names.Add(item.Entry.Name), "대소문자가 다른 파일을 합침"); | |
| 137 | 추가: Check.That(expected[item.Entry.Name].SequenceEqual(item.Content), "Linux 이름이나 내용을 변경함"); | |
| 138 | 추가: } | |
| 139 | 추가: } | |
| 140 | 추가: | |
| 141 | 추가: private async Task Budget(string kind) | |
| 142 | 추가: { | |
| 143 | 추가: var inputBytes = new FileInfo(FixturePath("cumulative.zip")).Length; | |
| 144 | 추가: var exact = Limits with { MaxEntries = 2, MaxOutputBytes = 16, MaxProcessedBytes = inputBytes + 16 }; | |
| 145 | 추가: Check.Equal(2, Successful(await Extract("cumulative.zip", exact)).Count); | |
| 146 | 추가: var tooSmall = kind switch | |
| 147 | 추가: { | |
| 148 | 추가: "output" => exact with { MaxOutputBytes = 15 }, | |
| 149 | 추가: "processed" => exact with { MaxProcessedBytes = inputBytes + 15 }, | |
| 150 | 추가: "entries" => exact with { MaxEntries = 1 }, | |
| 151 | 추가: _ => throw new InvalidOperationException() | |
| 152 | 추가: }; | |
| 153 | 추가: Failure(await Extract("cumulative.zip", tooSmall), ArchiveError.BudgetExceeded); | |
| 154 | 추가: } | |
| 155 | 추가: | |
| 156 | 추가: private static async Task PreCancelled() | |
| 157 | 추가: { | |
| 158 | 추가: using var cancellation = new CancellationTokenSource(); | |
| 159 | 추가: cancellation.Cancel(); | |
| 160 | 추가: using var input = new MemoryStream(Payload, false); | |
| 161 | 추가: Failure(await Worker.ExtractAsync(Guid.NewGuid(), input, Limits, cancellation.Token), ArchiveError.Cancelled); | |
| 162 | 추가: Check.Equal(0L, input.Position); | |
| 163 | 추가: Check.That(input.CanRead, "사전 취소로 호출자의 스트림을 닫음"); | |
| 164 | 추가: } | |
| 165 | 추가: | |
| 166 | 추가: private static async Task CancelInput() | |
| 167 | 추가: { | |
| 168 | 추가: using var input = new GatedInput(); | |
| 169 | 추가: using var cancellation = new CancellationTokenSource(); | |
| 170 | 추가: var operation = Worker.ExtractAsync(Guid.NewGuid(), input, Limits, cancellation.Token); | |
| 171 | 추가: try | |
| 172 | 추가: { | |
| 173 | 추가: await input.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); | |
| 174 | 추가: cancellation.Cancel(); | |
| 175 | 추가: Failure(await operation.WaitAsync(TimeSpan.FromSeconds(5)), ArchiveError.Cancelled); | |
| 176 | 추가: Check.That(input.CanRead, "입력 복사 취소로 호출자의 스트림을 닫음"); | |
| 177 | 추가: } | |
| 178 | 추가: finally | |
| 179 | 추가: { | |
| 180 | 추가: cancellation.Cancel(); | |
| 181 | 추가: await operation.WaitAsync(TimeSpan.FromSeconds(5)); | |
| 182 | 추가: } | |
| 183 | 추가: } | |
| 184 | 추가: | |
| 185 | 추가: private sealed class GatedInput : MemoryStream | |
| 186 | 추가: { | |
| 187 | 추가: public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); | |
| 188 | 추가: public GatedInput() : base(Payload, false) { } | |
| 189 | 추가: public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken token = default) | |
| 190 | 추가: { | |
| 191 | 추가: Entered.TrySetResult(); | |
| 192 | 추가: await Task.Delay(Timeout.Infinite, token); | |
| 193 | 추가: return 0; | |
| 194 | 추가: } | |
| 195 | 추가: } | |
| 196 | 추가: } |
| @@ -0,0 +1,91 @@ | ||
| 1 | 추가: using System.Security.Cryptography; | |
| 2 | 추가: using Zipelo.Core; | |
| 3 | 추가: using Zipelo.Runtime; | |
| 4 | 추가: using Zipelo.SecurityTests; | |
| 5 | 추가: | |
| 6 | 추가: namespace Zipelo.RuntimeTests; | |
| 7 | 추가: | |
| 8 | 추가: internal sealed partial class ExtractionTests | |
| 9 | 추가: { | |
| 10 | 추가: private async Task FolderConcurrentPublish() | |
| 11 | 추가: { | |
| 12 | 추가: RequireFolderImplementation(); | |
| 13 | 추가: var area = await NewArea(); | |
| 14 | 추가: RequireFolderDestination(area.Root); | |
| 15 | 추가: var external = Path.Combine(sandbox, "folder-external-" + Guid.NewGuid().ToString("N")); | |
| 16 | 추가: Directory.CreateDirectory(external); | |
| 17 | 추가: var externalFile = Path.Combine(external, "keep.txt"); | |
| 18 | 추가: var externalBytes = "출력 부모 밖의 보존 표식"u8.ToArray(); | |
| 19 | 추가: await File.WriteAllBytesAsync(externalFile, externalBytes); | |
| 20 | 추가: var inputs = new[] { await ExtractArea(area), await Extract("cumulative.zip") }; | |
| 21 | 추가: foreach (var input in inputs) { Successful(input); } | |
| 22 | 추가: var destination = Path.Combine(area.Root, "result"); | |
| 23 | 추가: var start = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); | |
| 24 | 추가: using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); | |
| 25 | 추가: | |
| 26 | 추가: async Task<ZipPublicationResult> Attempt(int index) | |
| 27 | 추가: { | |
| 28 | 추가: await start.Task; | |
| 29 | 추가: return await NewFolderPublisher.PublishAsync(inputs[index], destination, cancellation.Token); | |
| 30 | 추가: } | |
| 31 | 추가: | |
| 32 | 추가: // 두 요청을 같은 시작 장벽에서 풀되 네이티브 호출의 정확한 겹침을 보장하지는 않음. | |
| 33 | 추가: var attempts = new[] { Attempt(0), Attempt(1) }; | |
| 34 | 추가: start.SetResult(); | |
| 35 | 추가: var results = await Task.WhenAll(attempts); | |
| 36 | 추가: await Preserved(area, "source.zip", "sentinel.txt", "result"); | |
| 37 | 추가: ExactChildren(external, "keep.txt"); | |
| 38 | 추가: var afterExternal = await File.ReadAllBytesAsync(externalFile); | |
| 39 | 추가: Check.That(externalBytes.SequenceEqual(afterExternal), "출력 부모 밖의 기존 파일을 변경함"); | |
| 40 | 추가: Check.Equal(1, results.Count(result => result.Published)); | |
| 41 | 추가: var winner = Array.FindIndex(results, result => result.Published); | |
| 42 | 추가: Check.Equal(ArchiveError.None, results[winner].Error); | |
| 43 | 추가: Check.That(!results[winner].CleanupFailed && results[winner].TemporaryFileName is null, | |
| 44 | 추가: "동시 게시 성공 뒤 임시 결과나 정리 실패가 남음"); | |
| 45 | 추가: PublicationFailure(results[1 - winner], ArchiveError.OutputConflict); | |
| 46 | 추가: await VerifyPublishedTree(destination, Successful(inputs[winner])); | |
| 47 | 추가: } | |
| 48 | 추가: | |
| 49 | 추가: private static async Task VerifyPublishedTree(string directory, IReadOnlyList<ZipExtractedEntry> items) | |
| 50 | 추가: { | |
| 51 | 추가: Check.That((File.GetAttributes(directory) & FileAttributes.ReparsePoint) == 0, | |
| 52 | 추가: "게시 루트가 링크로 바뀜"); | |
| 53 | 추가: var expected = new Dictionary<string, bool>(StringComparer.Ordinal); | |
| 54 | 추가: foreach (var item in items) | |
| 55 | 추가: { | |
| 56 | 추가: var segments = item.Entry.Name.Split('/'); | |
| 57 | 추가: for (var index = 0; index < segments.Length; index++) | |
| 58 | 추가: { | |
| 59 | 추가: expected[string.Join('/', segments.Take(index + 1))] = | |
| 60 | 추가: index < segments.Length - 1 || item.Entry.Kind == EntryKind.Directory; | |
| 61 | 추가: } | |
| 62 | 추가: } | |
| 63 | 추가: var actual = new Dictionary<string, bool>(StringComparer.Ordinal); | |
| 64 | 추가: var pending = new Queue<(string Path, string Prefix)>(); | |
| 65 | 추가: pending.Enqueue((directory, "")); | |
| 66 | 추가: while (pending.TryDequeue(out var parent)) | |
| 67 | 추가: { | |
| 68 | 추가: foreach (var path in Directory.GetFileSystemEntries(parent.Path)) | |
| 69 | 추가: { | |
| 70 | 추가: var attributes = File.GetAttributes(path); | |
| 71 | 추가: Check.That((attributes & FileAttributes.ReparsePoint) == 0, "게시 결과에 외부 링크가 포함됨"); | |
| 72 | 추가: var name = Path.GetFileName(path); | |
| 73 | 추가: var relative = parent.Prefix.Length == 0 ? name : parent.Prefix + "/" + name; | |
| 74 | 추가: var folder = (attributes & FileAttributes.Directory) != 0; | |
| 75 | 추가: Check.That(expected.TryGetValue(relative, out var expectedFolder) && expectedFolder == folder, | |
| 76 | 추가: "다른 게시 작업의 내용이나 예상하지 않은 항목이 섞임"); | |
| 77 | 추가: actual.Add(relative, folder); | |
| 78 | 추가: if (folder) { pending.Enqueue((path, relative)); } | |
| 79 | 추가: } | |
| 80 | 추가: } | |
| 81 | 추가: Check.Equal(expected.Count, actual.Count); | |
| 82 | 추가: foreach (var item in items.Where(item => item.Entry.Kind == EntryKind.File)) | |
| 83 | 추가: { | |
| 84 | 추가: var path = Path.Combine(directory, item.Entry.Name.Replace('/', Path.DirectorySeparatorChar)); | |
| 85 | 추가: var bytes = await File.ReadAllBytesAsync(path); | |
| 86 | 추가: Check.Equal(item.Content.Length, bytes.Length); | |
| 87 | 추가: Check.That(SHA256.HashData(item.Content).SequenceEqual(SHA256.HashData(bytes)), | |
| 88 | 추가: "동시 게시 승자의 파일 해시가 다름"); | |
| 89 | 추가: } | |
| 90 | 추가: } | |
| 91 | 추가: } |
| @@ -0,0 +1,116 @@ | ||
| 1 | 추가: using System.Runtime.InteropServices; | |
| 2 | 추가: using System.Runtime.Versioning; | |
| 3 | 추가: using System.Security.AccessControl; | |
| 4 | 추가: using System.Security.Principal; | |
| 5 | 추가: using Zipelo.Core; | |
| 6 | 추가: using Zipelo.SecurityTests; | |
| 7 | 추가: | |
| 8 | 추가: namespace Zipelo.RuntimeTests; | |
| 9 | 추가: | |
| 10 | 추가: internal sealed record FolderEnvironment(ArchiveError? Rejection, string Description) | |
| 11 | 추가: { | |
| 12 | 추가: internal static FolderEnvironment Inspect(string newlyCreatedParent) | |
| 13 | 추가: { | |
| 14 | 추가: if (RuntimeInformation.ProcessArchitecture != Architecture.X64) | |
| 15 | 추가: { | |
| 16 | 추가: return Closed("x64 이외 아키텍처"); | |
| 17 | 추가: } | |
| 18 | 추가: if (OperatingSystem.IsWindows()) { return Windows(newlyCreatedParent); } | |
| 19 | 추가: if (OperatingSystem.IsLinux()) { return Linux(newlyCreatedParent); } | |
| 20 | 추가: return Closed("Windows/Linux 이외 OS"); | |
| 21 | 추가: } | |
| 22 | 추가: | |
| 23 | 추가: [SupportedOSPlatform("linux")] | |
| 24 | 추가: private static FolderEnvironment Linux(string parent) | |
| 25 | 추가: { | |
| 26 | 추가: // 별도 경로 관찰로 기대 조건을 정하며 제품 게시 결과로 SKIP 여부를 정하지 않음. | |
| 27 | 추가: var buffer = new byte[256]; | |
| 28 | 추가: Check.Equal(0, Statfs(parent, buffer)); | |
| 29 | 추가: var magic = BitConverter.ToInt64(buffer, 0); | |
| 30 | 추가: var expectedType = magic switch { 0xEF53 => "ext4", 0x58465342 => "xfs", _ => null }; | |
| 31 | 추가: if (expectedType is null) { return Closed($"Linux 미지원 파일시스템 0x{magic:X}"); } | |
| 32 | 추가: var status = new byte[256]; | |
| 33 | 추가: if (Statx(-100, parent, 0x100, 0x17FF, status) != 0 || | |
| 34 | 추가: (BitConverter.ToUInt32(status, 0) & 0x100A) != 0x100A) | |
| 35 | 추가: { | |
| 36 | 추가: return Closed("Linux mount ID/소유자/모드 조회 불가"); | |
| 37 | 추가: } | |
| 38 | 추가: var mountId = BitConverter.ToUInt64(status, 144); | |
| 39 | 추가: var device = FormattableString.Invariant($"{BitConverter.ToUInt32(status, 136)}:{BitConverter.ToUInt32(status, 140)}"); | |
| 40 | 추가: string content; | |
| 41 | 추가: try { content = File.ReadAllText("/proc/thread-self/mountinfo"); } | |
| 42 | 추가: catch (IOException) { return Closed("Linux mountinfo 조회 불가"); } | |
| 43 | 추가: catch (UnauthorizedAccessException) { return Closed("Linux mountinfo 읽기 권한 없음"); } | |
| 44 | 추가: var matching = content.Split('\n', StringSplitOptions.RemoveEmptyEntries) | |
| 45 | 추가: .Select(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries)) | |
| 46 | 추가: .Where(parts => parts.Length > 0 && ulong.TryParse(parts[0], out var id) && id == mountId).ToArray(); | |
| 47 | 추가: if (matching.Length != 1) { return Closed("Linux mountinfo 레코드 누락 또는 중복"); } | |
| 48 | 추가: var fields = matching[0]; | |
| 49 | 추가: var separator = Array.IndexOf(fields, "-"); | |
| 50 | 추가: if (separator < 6 || fields.Length != separator + 4 || fields[2] != device || fields[separator + 1] != expectedType) | |
| 51 | 추가: { | |
| 52 | 추가: return Closed("Linux mount ID/장치/파일시스템 유형 불일치"); | |
| 53 | 추가: } | |
| 54 | 추가: var mode = BitConverter.ToUInt16(status, 28); | |
| 55 | 추가: if (BitConverter.ToUInt32(status, 20) != GetEffectiveUser() || (mode & 0x12) != 0) | |
| 56 | 추가: { | |
| 57 | 추가: return Closed("Linux 부모 소유자 또는 그룹/기타 쓰기 조건 불충족"); | |
| 58 | 추가: } | |
| 59 | 추가: return new(null, $"Linux {expectedType}, mount ID/장치 일치, 현재 UID 소유, 그룹 및 기타 쓰기 없음"); | |
| 60 | 추가: } | |
| 61 | 추가: | |
| 62 | 추가: [SupportedOSPlatform("windows")] | |
| 63 | 추가: private static FolderEnvironment Windows(string parent) | |
| 64 | 추가: { | |
| 65 | 추가: var drive = new DriveInfo(Path.GetPathRoot(parent) ?? throw new InvalidOperationException()); | |
| 66 | 추가: if (parent.StartsWith(@"\\", StringComparison.Ordinal)) | |
| 67 | 추가: { | |
| 68 | 추가: return new(ArchiveError.UnsafePath, "Windows 네트워크 경로"); | |
| 69 | 추가: } | |
| 70 | 추가: if (drive.DriveType is not (DriveType.Fixed or DriveType.Removable)) | |
| 71 | 추가: { | |
| 72 | 추가: return Closed("Windows 로컬 고정/이동식 드라이브 이외 유형"); | |
| 73 | 추가: } | |
| 74 | 추가: if (!string.Equals(drive.DriveFormat, "NTFS", StringComparison.OrdinalIgnoreCase)) | |
| 75 | 추가: { | |
| 76 | 추가: return Closed("Windows 미지원 파일시스템 " + drive.DriveFormat); | |
| 77 | 추가: } | |
| 78 | 추가: var security = new DirectoryInfo(parent).GetAccessControl(AccessControlSections.Owner | AccessControlSections.Access); | |
| 79 | 추가: var descriptor = new RawSecurityDescriptor(security.GetSecurityDescriptorBinaryForm(), 0); | |
| 80 | 추가: using var identity = WindowsIdentity.GetCurrent(); | |
| 81 | 추가: var trusted = new HashSet<string>(StringComparer.Ordinal) { "S-1-5-18", "S-1-5-32-544" }; | |
| 82 | 추가: if (identity.User is { } user) { trusted.Add(user.Value); } | |
| 83 | 추가: if (descriptor.Owner is null || !trusted.Contains(descriptor.Owner.Value) || descriptor.DiscretionaryAcl is null) | |
| 84 | 추가: { | |
| 85 | 추가: return Closed("NTFS 부모 소유자 또는 DACL 조건 불충족"); | |
| 86 | 추가: } | |
| 87 | 추가: const FileSystemRights mutation = FileSystemRights.Write | FileSystemRights.Delete | | |
| 88 | 추가: FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership; | |
| 89 | 추가: foreach (GenericAce entry in descriptor.DiscretionaryAcl) | |
| 90 | 추가: { | |
| 91 | 추가: if (entry is not CommonAce ace || ace.IsCallback) | |
| 92 | 추가: { | |
| 93 | 추가: return Closed("NTFS 부모의 미지원 ACE"); | |
| 94 | 추가: } | |
| 95 | 추가: if (ace.AceQualifier == AceQualifier.AccessDenied) { continue; } | |
| 96 | 추가: if (ace.AceQualifier != AceQualifier.AccessAllowed) { return Closed("NTFS 부모의 미지원 ACE 유형"); } | |
| 97 | 추가: var writes = (ace.AccessMask & (int)mutation) != 0 || (ace.AccessMask & 0x52000000) != 0; | |
| 98 | 추가: if (!writes || trusted.Contains(ace.SecurityIdentifier.Value)) { continue; } | |
| 99 | 추가: if ((ace.AceFlags & AceFlags.InheritOnly) != 0 && | |
| 100 | 추가: ace.SecurityIdentifier.IsWellKnown(WellKnownSidType.CreatorOwnerSid)) { continue; } | |
| 101 | 추가: return Closed("NTFS 부모의 신뢰 범위 밖 쓰기 ACE"); | |
| 102 | 추가: } | |
| 103 | 추가: return new(null, "Windows NTFS, 현재 사용자/SYSTEM/Administrators 쓰기 경계"); | |
| 104 | 추가: } | |
| 105 | 추가: | |
| 106 | 추가: private static FolderEnvironment Closed(string reason) => new(ArchiveError.OutputUnavailable, reason); | |
| 107 | 추가: | |
| 108 | 추가: [DllImport("libc", EntryPoint = "statfs", SetLastError = true)] | |
| 109 | 추가: private static extern int Statfs(string path, [Out] byte[] buffer); | |
| 110 | 추가: | |
| 111 | 추가: [DllImport("libc", EntryPoint = "statx", SetLastError = true)] | |
| 112 | 추가: private static extern int Statx(int directory, string path, int flags, uint mask, [Out] byte[] buffer); | |
| 113 | 추가: | |
| 114 | 추가: [DllImport("libc", EntryPoint = "geteuid")] | |
| 115 | 추가: private static extern uint GetEffectiveUser(); | |
| 116 | 추가: } |
| @@ -0,0 +1,55 @@ | ||
| 1 | 추가: using Zipelo.SecurityTests; | |
| 2 | 추가: | |
| 3 | 추가: namespace Zipelo.RuntimeTests; | |
| 4 | 추가: | |
| 5 | 추가: internal static class Program | |
| 6 | 추가: { | |
| 7 | 추가: public static async Task<int> Main(string[] arguments) | |
| 8 | 추가: { | |
| 9 | 추가: // 인수 없는 자식 실행은 프로토콜 실패 주입 전용임. | |
| 10 | 추가: if (arguments.Length == 0) { return await ProtocolPeer.Run(); } | |
| 11 | 추가: if (arguments.Length != 2) { return 2; } | |
| 12 | 추가: var root = Path.GetFullPath(arguments[0]); | |
| 13 | 추가: var sandbox = Path.GetFullPath(arguments[1]); | |
| 14 | 추가: var work = Path.Combine(root, "tests", "security", ".work"); | |
| 15 | 추가: if (!File.Exists(Path.Combine(root, "src", "Zipelo.Runtime", "Zipelo.Runtime.csproj")) || | |
| 16 | 추가: !sandbox.StartsWith(work + Path.DirectorySeparatorChar, StringComparison.Ordinal) || | |
| 17 | 추가: !Directory.Exists(sandbox)) | |
| 18 | 추가: { | |
| 19 | 추가: return 2; | |
| 20 | 추가: } | |
| 21 | 추가: for (DirectoryInfo? directory = new(sandbox); directory is not null; directory = directory.Parent) | |
| 22 | 추가: { | |
| 23 | 추가: if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) { return 2; } | |
| 24 | 추가: } | |
| 25 | 추가: var tests = new RuntimeTests(root, sandbox); | |
| 26 | 추가: var passed = 0; | |
| 27 | 추가: var failed = 0; | |
| 28 | 추가: var skipped = 0; | |
| 29 | 추가: foreach (var (name, run) in tests.Cases()) | |
| 30 | 추가: { | |
| 31 | 추가: try | |
| 32 | 추가: { | |
| 33 | 추가: await run(); | |
| 34 | 추가: Console.WriteLine($"PASS {name}"); | |
| 35 | 추가: passed++; | |
| 36 | 추가: } | |
| 37 | 추가: catch (CaseSkippedException exception) | |
| 38 | 추가: { | |
| 39 | 추가: Console.WriteLine($"SKIP {name}: {exception.Message}"); | |
| 40 | 추가: skipped++; | |
| 41 | 추가: } | |
| 42 | 추가: catch (Exception exception) | |
| 43 | 추가: { | |
| 44 | 추가: Console.Error.WriteLine($"FAIL {name}: {exception.GetType().Name}"); | |
| 45 | 추가: failed++; | |
| 46 | 추가: } | |
| 47 | 추가: } | |
| 48 | 추가: Console.WriteLine($"런타임 회귀 검사: {passed} 통과, {failed} 실패, {skipped} 미실행"); | |
| 49 | 추가: Console.WriteLine($"실행 환경: {System.Runtime.InteropServices.RuntimeInformation.OSDescription}, " + | |
| 50 | 추가: System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture); | |
| 51 | 추가: return failed == 0 ? 0 : 1; | |
| 52 | 추가: } | |
| 53 | 추가: } | |
| 54 | 추가: | |
| 55 | 추가: internal sealed class CaseSkippedException(string message) : Exception(message) { } |
| @@ -0,0 +1,75 @@ | ||
| 1 | 추가: using System.Buffers.Binary; | |
| 2 | 추가: using System.Text.Json; | |
| 3 | 추가: using Zipelo.Core; | |
| 4 | 추가: using Zipelo.Runtime; | |
| 5 | 추가: | |
| 6 | 추가: namespace Zipelo.RuntimeTests; | |
| 7 | 추가: | |
| 8 | 추가: // 제품 작업자를 대체하지 않는 비정상 응답 시험용 자식 프로세스임. | |
| 9 | 추가: internal static class ProtocolPeer | |
| 10 | 추가: { | |
| 11 | 추가: public static async Task<int> Run() | |
| 12 | 추가: { | |
| 13 | 추가: using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); | |
| 14 | 추가: var input = Console.OpenStandardInput(); | |
| 15 | 추가: var output = Console.OpenStandardOutput(); | |
| 16 | 추가: var header = new byte[4]; | |
| 17 | 추가: await input.ReadExactlyAsync(header, timeout.Token); | |
| 18 | 추가: var size = BinaryPrimitives.ReadInt32LittleEndian(header); | |
| 19 | 추가: if (size <= 0 || size > 4096) { return 2; } | |
| 20 | 추가: var bytes = new byte[size]; | |
| 21 | 추가: await input.ReadExactlyAsync(bytes, timeout.Token); | |
| 22 | 추가: using var document = JsonDocument.Parse(bytes); | |
| 23 | 추가: var request = document.RootElement; | |
| 24 | 추가: var id = request.GetProperty("JobId").GetGuid(); | |
| 25 | 추가: var mode = request.GetProperty("Names")[0].GetString(); | |
| 26 | 추가: if (mode == "hang") | |
| 27 | 추가: { | |
| 28 | 추가: var marker = System.Text.Encoding.UTF8.GetString(request.GetProperty("Inputs")[0].GetBytesFromBase64()); | |
| 29 | 추가: var directory = Path.GetDirectoryName(marker)!; | |
| 30 | 추가: // 실행기가 검증한 sandbox 안의 표식만 작성함. | |
| 31 | 추가: if (!Path.IsPathFullyQualified(marker) || !Directory.Exists(directory) || | |
| 32 | 추가: !Path.GetRelativePath(directory, marker).Equals("child.pid", StringComparison.Ordinal) || | |
| 33 | 추가: !directory.StartsWith(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar, | |
| 34 | 추가: StringComparison.Ordinal) || | |
| 35 | 추가: !directory.Contains(Path.Combine("tests", "security", ".work") + Path.DirectorySeparatorChar, | |
| 36 | 추가: StringComparison.Ordinal)) | |
| 37 | 추가: { | |
| 38 | 추가: return 2; | |
| 39 | 추가: } | |
| 40 | 추가: await File.WriteAllTextAsync(marker + ".pending", Environment.ProcessId.ToString(), timeout.Token); | |
| 41 | 추가: File.Move(marker + ".pending", marker); | |
| 42 | 추가: await Task.Delay(Timeout.Infinite, timeout.Token); | |
| 43 | 추가: return 2; | |
| 44 | 추가: } | |
| 45 | 추가: if (mode == "exit") { return 9; } | |
| 46 | 추가: if (mode is "zero" or "negative" or "oversized") | |
| 47 | 추가: { | |
| 48 | 추가: var length = mode == "zero" ? 0 : mode == "negative" ? -1 : 32 * 1024 * 1024 + 1; | |
| 49 | 추가: BinaryPrimitives.WriteInt32LittleEndian(header, length); | |
| 50 | 추가: await output.WriteAsync(header, timeout.Token); | |
| 51 | 추가: await output.FlushAsync(timeout.Token); | |
| 52 | 추가: return 0; | |
| 53 | 추가: } | |
| 54 | 추가: if (mode is "truncated" or "bad-json") | |
| 55 | 추가: { | |
| 56 | 추가: BinaryPrimitives.WriteInt32LittleEndian(header, mode == "truncated" ? 10 : 1); | |
| 57 | 추가: await output.WriteAsync(header, timeout.Token); | |
| 58 | 추가: await output.WriteAsync(new byte[] { (byte)'{' }, timeout.Token); | |
| 59 | 추가: await output.FlushAsync(timeout.Token); | |
| 60 | 추가: return 0; | |
| 61 | 추가: } | |
| 62 | 추가: | |
| 63 | 추가: var state = mode == "nonterminal" ? JobState.Running : JobState.Completed; | |
| 64 | 추가: var error = mode == "success-error" ? ArchiveError.IntegrityFailure : ArchiveError.None; | |
| 65 | 추가: var result = new ZipWorkerResult( | |
| 66 | 추가: new(mode == "wrong-id" ? Guid.NewGuid() : id, state, Array.Empty<EntryResult>(), error), | |
| 67 | 추가: mode is "missing-zip" or "nonterminal" ? null : new byte[] { 80, 75 }); | |
| 68 | 추가: var payload = JsonSerializer.SerializeToUtf8Bytes(result); | |
| 69 | 추가: BinaryPrimitives.WriteInt32LittleEndian(header, payload.Length); | |
| 70 | 추가: await output.WriteAsync(header, timeout.Token); | |
| 71 | 추가: await output.WriteAsync(payload, timeout.Token); | |
| 72 | 추가: await output.FlushAsync(timeout.Token); | |
| 73 | 추가: return 0; | |
| 74 | 추가: } | |
| 75 | 추가: } |
| @@ -0,0 +1,145 @@ | ||
| 1 | 추가: using System.IO.Compression; | |
| 2 | 추가: using Zipelo.Core; | |
| 3 | 추가: using Zipelo.Runtime; | |
| 4 | 추가: using Zipelo.SecurityTests; | |
| 5 | 추가: | |
| 6 | 추가: namespace Zipelo.RuntimeTests; | |
| 7 | 추가: | |
| 8 | 추가: internal sealed partial class RuntimeTests | |
| 9 | 추가: { | |
| 10 | 추가: private string PublicationDirectory() | |
| 11 | 추가: { | |
| 12 | 추가: var directory = Path.Combine(sandbox, Guid.NewGuid().ToString("N")); | |
| 13 | 추가: Directory.CreateDirectory(directory); | |
| 14 | 추가: return directory; | |
| 15 | 추가: } | |
| 16 | 추가: | |
| 17 | 추가: private static async Task<ZipWorkerResult> Artifact() | |
| 18 | 추가: { | |
| 19 | 추가: var result = await Create(Worker, "input.txt", new byte[] { 2, 4, 6 }); | |
| 20 | 추가: Check.Equal(JobState.Completed, result.Job.State); | |
| 21 | 추가: Check.That(result.CreatedZip is { Length: > 0 }, "실제 생성물이 없음"); | |
| 22 | 추가: return result; | |
| 23 | 추가: } | |
| 24 | 추가: | |
| 25 | 추가: private static void PublicationFailed(ZipPublicationResult result, ArchiveError error) | |
| 26 | 추가: { | |
| 27 | 추가: Check.That(!result.Published, "실패한 게시를 성공으로 표시함"); | |
| 28 | 추가: Check.Equal(error, result.Error); | |
| 29 | 추가: Check.That(!result.CleanupFailed && result.TemporaryFileName is null, "작업 임시 파일 정리에 실패함"); | |
| 30 | 추가: } | |
| 31 | 추가: | |
| 32 | 추가: private async Task PublishNewFile() | |
| 33 | 추가: { | |
| 34 | 추가: var directory = PublicationDirectory(); | |
| 35 | 추가: var destination = Path.Combine(directory, "new.zip"); | |
| 36 | 추가: var artifact = await Artifact(); | |
| 37 | 추가: var result = await NewZipPublisher.PublishAsync(artifact, destination, default); | |
| 38 | 추가: Check.That(result.Published && !result.CleanupFailed, "새 파일 게시 또는 정리에 실패함"); | |
| 39 | 추가: Check.Equal(ArchiveError.None, result.Error); | |
| 40 | 추가: Check.That(result.TemporaryFileName is null, "성공한 게시에 임시 파일이 보고됨"); | |
| 41 | 추가: var actual = await File.ReadAllBytesAsync(destination); | |
| 42 | 추가: Check.That(actual.SequenceEqual(artifact.CreatedZip!), "게시 바이트가 생성물과 다름"); | |
| 43 | 추가: Check.That(Directory.GetFileSystemEntries(directory).SequenceEqual(new[] { destination }), "임시 파일이 남음"); | |
| 44 | 추가: using var input = File.OpenRead(destination); | |
| 45 | 추가: using var zip = new ZipArchive(input, ZipArchiveMode.Read); | |
| 46 | 추가: Check.Equal("input.txt", zip.Entries.Single().FullName); | |
| 47 | 추가: } | |
| 48 | 추가: | |
| 49 | 추가: private async Task PublishConflictPreservesSource(bool useSourcePath) | |
| 50 | 추가: { | |
| 51 | 추가: var directory = PublicationDirectory(); | |
| 52 | 추가: var source = Path.Combine(directory, "input.txt"); | |
| 53 | 추가: var occupied = Path.Combine(directory, "existing.zip"); | |
| 54 | 추가: byte[] original = [3, 5, 7]; | |
| 55 | 추가: byte[] existing = [11, 13]; | |
| 56 | 추가: await File.WriteAllBytesAsync(source, original); | |
| 57 | 추가: await File.WriteAllBytesAsync(occupied, existing); | |
| 58 | 추가: ZipWorkerResult artifact; | |
| 59 | 추가: await using (var input = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read)) | |
| 60 | 추가: { | |
| 61 | 추가: artifact = await Worker.CreateAsync(Guid.NewGuid(), [new("input.txt", input)], Limits, null, default); | |
| 62 | 추가: } | |
| 63 | 추가: Check.Equal(JobState.Completed, artifact.Job.State); | |
| 64 | 추가: var destination = useSourcePath ? source : occupied; | |
| 65 | 추가: var result = await NewZipPublisher.PublishAsync(artifact, destination, default); | |
| 66 | 추가: // 오류 분류가 틀려도 파일 보존과 임시 파일 잔존 여부를 먼저 확인함. | |
| 67 | 추가: var sourceAfter = await File.ReadAllBytesAsync(source); | |
| 68 | 추가: var occupiedAfter = await File.ReadAllBytesAsync(occupied); | |
| 69 | 추가: Check.That(original.SequenceEqual(sourceAfter), "원본 파일이 변경됨"); | |
| 70 | 추가: Check.That(existing.SequenceEqual(occupiedAfter), "기존 출력 파일이 변경됨"); | |
| 71 | 추가: Check.Equal(2, Directory.GetFileSystemEntries(directory).Length); | |
| 72 | 추가: PublicationFailed(result, ArchiveError.OutputConflict); | |
| 73 | 추가: } | |
| 74 | 추가: | |
| 75 | 추가: private async Task PublishPreCancelled() | |
| 76 | 추가: { | |
| 77 | 추가: var directory = PublicationDirectory(); | |
| 78 | 추가: var sentinel = Path.Combine(directory, "existing.txt"); | |
| 79 | 추가: await File.WriteAllTextAsync(sentinel, "보존"); | |
| 80 | 추가: var artifact = await Artifact(); | |
| 81 | 추가: using var cancellation = new CancellationTokenSource(); | |
| 82 | 추가: cancellation.Cancel(); | |
| 83 | 추가: foreach (var destination in new[] { sentinel, Path.Combine(directory, "new.zip") }) | |
| 84 | 추가: { | |
| 85 | 추가: PublicationFailed(await NewZipPublisher.PublishAsync(artifact, destination, cancellation.Token), | |
| 86 | 추가: ArchiveError.Cancelled); | |
| 87 | 추가: } | |
| 88 | 추가: Check.Equal("보존", await File.ReadAllTextAsync(sentinel)); | |
| 89 | 추가: Check.Equal(1, Directory.GetFileSystemEntries(directory).Length); | |
| 90 | 추가: } | |
| 91 | 추가: | |
| 92 | 추가: private async Task PublishFailurePreservesFiles() | |
| 93 | 추가: { | |
| 94 | 추가: var directory = PublicationDirectory(); | |
| 95 | 추가: var sentinel = Path.Combine(directory, "sentinel.txt"); | |
| 96 | 추가: await File.WriteAllTextAsync(sentinel, "보존"); | |
| 97 | 추가: var artifact = await Artifact(); | |
| 98 | 추가: var failed = artifact with { Job = artifact.Job with { State = JobState.Failed, Error = ArchiveError.IntegrityFailure } }; | |
| 99 | 추가: PublicationFailed(await NewZipPublisher.PublishAsync(failed, sentinel, default), ArchiveError.UnsupportedOperation); | |
| 100 | 추가: PublicationFailed(await NewZipPublisher.PublishAsync(artifact, "relative.zip", default), ArchiveError.UnsafePath); | |
| 101 | 추가: PublicationFailed(await NewZipPublisher.PublishAsync(artifact, Path.Combine(directory, "absent", "new.zip"), default), | |
| 102 | 추가: ArchiveError.OutputUnavailable); | |
| 103 | 추가: Check.Equal("보존", await File.ReadAllTextAsync(sentinel)); | |
| 104 | 추가: Check.Equal(1, Directory.GetFileSystemEntries(directory).Length); | |
| 105 | 추가: } | |
| 106 | 추가: | |
| 107 | 추가: private async Task PublishRejectsLinks(bool parentLink) | |
| 108 | 추가: { | |
| 109 | 추가: var directory = PublicationDirectory(); | |
| 110 | 추가: var target = Path.Combine(directory, "target"); | |
| 111 | 추가: Directory.CreateDirectory(target); | |
| 112 | 추가: var sentinel = Path.Combine(target, "sentinel.txt"); | |
| 113 | 추가: await File.WriteAllTextAsync(sentinel, "보존"); | |
| 114 | 추가: var link = Path.Combine(directory, parentLink ? "link" : "existing.zip"); | |
| 115 | 추가: FileSystemInfo linkInfo; | |
| 116 | 추가: try | |
| 117 | 추가: { | |
| 118 | 추가: linkInfo = parentLink | |
| 119 | 추가: ? Directory.CreateSymbolicLink(link, target) | |
| 120 | 추가: : File.CreateSymbolicLink(link, sentinel); | |
| 121 | 추가: } | |
| 122 | 추가: catch (Exception exception) when (OperatingSystem.IsWindows() && | |
| 123 | 추가: (exception is UnauthorizedAccessException || exception is IOException && | |
| 124 | 추가: (exception.HResult & 0xFFFF) == 1314)) | |
| 125 | 추가: { | |
| 126 | 추가: throw new CaseSkippedException("Windows 심볼릭 링크 생성 권한이 없어 해당 사례 미실행"); | |
| 127 | 추가: } | |
| 128 | 추가: try | |
| 129 | 추가: { | |
| 130 | 추가: var originalLinkTarget = linkInfo.LinkTarget; | |
| 131 | 추가: Check.That(originalLinkTarget is not null, "검사용 링크가 생성되지 않음"); | |
| 132 | 추가: var artifact = await Artifact(); | |
| 133 | 추가: var destination = parentLink ? Path.Combine(link, "new.zip") : link; | |
| 134 | 추가: var result = await NewZipPublisher.PublishAsync(artifact, destination, default); | |
| 135 | 추가: Check.Equal("보존", await File.ReadAllTextAsync(sentinel)); | |
| 136 | 추가: Check.Equal(1, Directory.GetFileSystemEntries(target).Length); | |
| 137 | 추가: Check.Equal(2, Directory.GetFileSystemEntries(directory).Length); | |
| 138 | 추가: linkInfo.Refresh(); | |
| 139 | 추가: Check.That((linkInfo.Attributes & FileAttributes.ReparsePoint) != 0, "기존 링크가 교체됨"); | |
| 140 | 추가: Check.Equal(originalLinkTarget, linkInfo.LinkTarget); | |
| 141 | 추가: PublicationFailed(result, parentLink ? ArchiveError.UnsafePath : ArchiveError.OutputConflict); | |
| 142 | 추가: } | |
| 143 | 추가: finally { linkInfo.Delete(); } | |
| 144 | 추가: } | |
| 145 | 추가: } |
| @@ -0,0 +1,316 @@ | ||
| 1 | 추가: using System.Diagnostics; | |
| 2 | 추가: using System.IO.Compression; | |
| 3 | 추가: using System.Security.Cryptography; | |
| 4 | 추가: using System.Text; | |
| 5 | 추가: using Zipelo.Core; | |
| 6 | 추가: using Zipelo.Runtime; | |
| 7 | 추가: using Zipelo.SecurityTests; | |
| 8 | 추가: | |
| 9 | 추가: namespace Zipelo.RuntimeTests; | |
| 10 | 추가: | |
| 11 | 추가: internal sealed partial class RuntimeTests(string root, string sandbox) | |
| 12 | 추가: { | |
| 13 | 추가: private static JobLimits Limits => new(32, 1024 * 1024, 1024 * 1024, TimeSpan.FromSeconds(15), 3); | |
| 14 | 추가: private static string Host => Environment.ProcessPath ?? throw new InvalidOperationException(); | |
| 15 | 추가: private static ZipWorkerClient Worker => new(Path.Combine(AppContext.BaseDirectory, "Zipelo.Worker.dll"), Host); | |
| 16 | 추가: private static ZipWorkerClient Peer => new(typeof(Program).Assembly.Location, Host); | |
| 17 | 추가: | |
| 18 | 추가: public IEnumerable<(string Name, Func<Task> Run)> Cases() | |
| 19 | 추가: { | |
| 20 | 추가: yield return ("runtime.absolute_worker_path_and_missing_files", Paths); | |
| 21 | 추가: yield return ("runtime.readonly_input_and_options", InputsAndOptions); | |
| 22 | 추가: yield return ("runtime.actual_bytes_and_16mib_limit", InputLimits); | |
| 23 | 추가: yield return ("runtime.cancel_before_read_and_during_copy", InputCancellation); | |
| 24 | 추가: yield return ("runtime.reject_frame_lengths_and_corruption", InvalidFrames); | |
| 25 | 추가: yield return ("runtime.reject_exit_id_and_missing_artifact", InvalidResults); | |
| 26 | 추가: yield return ("runtime.reject_nonterminal_result", () => InvalidState("nonterminal")); | |
| 27 | 추가: yield return ("runtime.reject_success_with_error", () => InvalidState("success-error")); | |
| 28 | 추가: yield return ("runtime.cancel_waits_for_worker_exit", () => StopWorker(false)); | |
| 29 | 추가: yield return ("runtime.deadline_waits_for_worker_exit", () => StopWorker(true)); | |
| 30 | 추가: yield return ("zip.real_list_preserves_source_and_unverified_entries", ListZip); | |
| 31 | 추가: yield return ("zip.real_create_roundtrip_and_cumulative_budgets", CreateZip); | |
| 32 | 추가: yield return ("zip.os_names_case_and_parent_collisions", ZipNames); | |
| 33 | 추가: yield return ("zip.corruption_and_listing_budget", ListFailures); | |
| 34 | 추가: yield return ("publication.new_file_exact_bytes", PublishNewFile); | |
| 35 | 추가: yield return ("publication.conflict_preserves_existing_file", () => PublishConflictPreservesSource(false)); | |
| 36 | 추가: yield return ("publication.conflict_preserves_input_source", () => PublishConflictPreservesSource(true)); | |
| 37 | 추가: yield return ("publication.precancel_preserves_existing", PublishPreCancelled); | |
| 38 | 추가: yield return ("publication.failure_preserves_existing", PublishFailurePreservesFiles); | |
| 39 | 추가: yield return ("publication.rejects_parent_symlink", () => PublishRejectsLinks(true)); | |
| 40 | 추가: yield return ("publication.rejects_leaf_symlink", () => PublishRejectsLinks(false)); | |
| 41 | 추가: foreach (var item in new ExtractionTests(root, sandbox).Cases()) { yield return item; } | |
| 42 | 추가: } | |
| 43 | 추가: | |
| 44 | 추가: private static void Failed(ZipWorkerResult result, ArchiveError error) | |
| 45 | 추가: { | |
| 46 | 추가: Check.Equal(error, result.Job.Error); | |
| 47 | 추가: Check.Equal(error == ArchiveError.Cancelled ? JobState.Cancelled : JobState.Failed, result.Job.State); | |
| 48 | 추가: Check.That(result.CreatedZip is null, "실패한 작업이 생성물을 반환함"); | |
| 49 | 추가: } | |
| 50 | 추가: | |
| 51 | 추가: private static async Task<ZipWorkerResult> Create(ZipWorkerClient client, string name, | |
| 52 | 추가: byte[]? bytes = null, JobLimits? limits = null, CancellationToken token = default) | |
| 53 | 추가: { | |
| 54 | 추가: using var input = new MemoryStream(bytes ?? new byte[] { 1 }, false); | |
| 55 | 추가: return await client.CreateAsync(Guid.NewGuid(), [new(name, input)], limits ?? Limits, null, token); | |
| 56 | 추가: } | |
| 57 | 추가: | |
| 58 | 추가: private Task Paths() | |
| 59 | 추가: { | |
| 60 | 추가: Check.Throws<ArgumentException>(() => new ZipWorkerClient("worker/Zipelo.Worker")); | |
| 61 | 추가: Check.Throws<ArgumentException>(() => new ZipWorkerClient(Path.Combine(sandbox, "worker.dll"), "dotnet")); | |
| 62 | 추가: Check.Throws<ArgumentException>(() => WorkerPlatform.GetWorkerPath("relative")); | |
| 63 | 추가: var expected = OperatingSystem.IsWindows() ? "Zipelo.Worker.exe" : "Zipelo.Worker"; | |
| 64 | 추가: Check.Equal(Path.Combine(sandbox, "worker", expected), WorkerPlatform.GetWorkerPath(sandbox)); | |
| 65 | 추가: var missing = new ZipWorkerClient(Path.Combine(sandbox, "absent-worker.dll"), Host); | |
| 66 | 추가: Check.That(!missing.IsAvailable && missing.Capabilities.Count == 0, "없는 작업자를 사용 가능으로 표시함"); | |
| 67 | 추가: Check.That(!Worker.SupportsSafeExtraction && !Worker.SupportsEncryption && !Worker.SupportsSplitVolumes, | |
| 68 | 추가: "미구현 기능을 사용 가능으로 표시함"); | |
| 69 | 추가: Check.That(Worker.IsAvailable && Peer.IsAvailable, "검사에 필요한 빌드 산출물이 없음"); | |
| 70 | 추가: return Task.CompletedTask; | |
| 71 | 추가: } | |
| 72 | 추가: | |
| 73 | 추가: private static async Task InputsAndOptions() | |
| 74 | 추가: { | |
| 75 | 추가: using var writable = new MemoryStream(new byte[] { 1 }); | |
| 76 | 추가: Failed(await Worker.ListAsync(Guid.NewGuid(), writable, Limits, default), ArchiveError.UnsupportedOperation); | |
| 77 | 추가: using var input = new MemoryStream(new byte[] { 1 }, false); | |
| 78 | 추가: foreach (var option in new[] { new ZipCreationOptions(Encrypt: true), new ZipCreationOptions(SplitVolumeBytes: 1) }) | |
| 79 | 추가: { | |
| 80 | 추가: Failed(await Worker.CreateAsync(Guid.NewGuid(), [new("a", input)], Limits, option, default), | |
| 81 | 추가: ArchiveError.UnsupportedOperation); | |
| 82 | 추가: Check.Equal(0L, input.Position); | |
| 83 | 추가: } | |
| 84 | 추가: Failed(await Create(Worker, new string('x', 1025)), ArchiveError.BudgetExceeded); | |
| 85 | 추가: var many = Enumerable.Range(0, 1025).Select(index => new ZipCreateInput(index.ToString(), input)).ToArray(); | |
| 86 | 추가: Failed(await Worker.CreateAsync(Guid.NewGuid(), many, Limits, null, default), ArchiveError.BudgetExceeded); | |
| 87 | 추가: Check.That(input.CanRead, "호출자 입력의 수명을 작업자가 종료함"); | |
| 88 | 추가: } | |
| 89 | 추가: | |
| 90 | 추가: private static async Task InputLimits() | |
| 91 | 추가: { | |
| 92 | 추가: using var tiny = new MemoryStream(new byte[] { 1, 2, 3, 4 }, false); | |
| 93 | 추가: Failed(await Worker.ListAsync(Guid.NewGuid(), tiny, Limits with { MaxProcessedBytes = 3 }, default), | |
| 94 | 추가: ArchiveError.BudgetExceeded); | |
| 95 | 추가: // 큰 파일을 만들지 않고 일정한 버퍼로 입력 상한을 시험함. | |
| 96 | 추가: using var large = new GeneratedInput(16L * 1024 * 1024 + 1); | |
| 97 | 추가: Failed(await Worker.ListAsync(Guid.NewGuid(), large, Limits with { MaxProcessedBytes = 32L * 1024 * 1024 }, | |
| 98 | 추가: default), ArchiveError.BudgetExceeded); | |
| 99 | 추가: Check.Equal(16L * 1024 * 1024 + 1, large.BytesRead); | |
| 100 | 추가: } | |
| 101 | 추가: | |
| 102 | 추가: private static async Task InputCancellation() | |
| 103 | 추가: { | |
| 104 | 추가: using var cancelled = new CancellationTokenSource(); | |
| 105 | 추가: cancelled.Cancel(); | |
| 106 | 추가: using var untouched = new MemoryStream(new byte[] { 1 }, false); | |
| 107 | 추가: Failed(await Worker.ListAsync(Guid.NewGuid(), untouched, Limits, cancelled.Token), ArchiveError.Cancelled); | |
| 108 | 추가: Check.Equal(0L, untouched.Position); | |
| 109 | 추가: using var source = new WaitingInput(); | |
| 110 | 추가: using var pending = new CancellationTokenSource(); | |
| 111 | 추가: var operation = Worker.ListAsync(Guid.NewGuid(), source, Limits, pending.Token); | |
| 112 | 추가: try | |
| 113 | 추가: { | |
| 114 | 추가: await source.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); | |
| 115 | 추가: pending.Cancel(); | |
| 116 | 추가: Failed(await operation.WaitAsync(TimeSpan.FromSeconds(5)), ArchiveError.Cancelled); | |
| 117 | 추가: } | |
| 118 | 추가: finally { pending.Cancel(); } | |
| 119 | 추가: } | |
| 120 | 추가: | |
| 121 | 추가: private static async Task InvalidFrames() | |
| 122 | 추가: { | |
| 123 | 추가: foreach (var mode in new[] { "zero", "negative", "oversized" }) | |
| 124 | 추가: { | |
| 125 | 추가: Failed(await Create(Peer, mode), ArchiveError.BudgetExceeded); | |
| 126 | 추가: } | |
| 127 | 추가: foreach (var mode in new[] { "truncated", "bad-json" }) | |
| 128 | 추가: { | |
| 129 | 추가: Failed(await Create(Peer, mode), ArchiveError.EngineFailure); | |
| 130 | 추가: } | |
| 131 | 추가: } | |
| 132 | 추가: | |
| 133 | 추가: private static async Task InvalidResults() | |
| 134 | 추가: { | |
| 135 | 추가: foreach (var mode in new[] { "exit", "wrong-id", "missing-zip" }) | |
| 136 | 추가: { | |
| 137 | 추가: Failed(await Create(Peer, mode), ArchiveError.EngineFailure); | |
| 138 | 추가: } | |
| 139 | 추가: } | |
| 140 | 추가: | |
| 141 | 추가: private static async Task InvalidState(string mode) | |
| 142 | 추가: { | |
| 143 | 추가: Failed(await Create(Peer, mode), ArchiveError.EngineFailure); | |
| 144 | 추가: } | |
| 145 | 추가: | |
| 146 | 추가: private async Task StopWorker(bool deadline) | |
| 147 | 추가: { | |
| 148 | 추가: var directory = Path.Combine(sandbox, Guid.NewGuid().ToString("N")); | |
| 149 | 추가: Directory.CreateDirectory(directory); | |
| 150 | 추가: var marker = Path.Combine(directory, "child.pid"); | |
| 151 | 추가: using var cancellation = new CancellationTokenSource(); | |
| 152 | 추가: var operation = Create(Peer, "hang", Encoding.UTF8.GetBytes(marker), | |
| 153 | 추가: Limits with { MaxDuration = TimeSpan.FromSeconds(deadline ? 5 : 15) }, cancellation.Token); | |
| 154 | 추가: Process? child = null; | |
| 155 | 추가: try | |
| 156 | 추가: { | |
| 157 | 추가: // 자식의 준비 표식을 기다리므로 취소 시점을 시작 시간 추측에 의존하지 않음. | |
| 158 | 추가: using var guard = new CancellationTokenSource(TimeSpan.FromSeconds(8)); | |
| 159 | 추가: while (child is null) | |
| 160 | 추가: { | |
| 161 | 추가: if (File.Exists(marker) && int.TryParse(await File.ReadAllTextAsync(marker, guard.Token), out var id)) | |
| 162 | 추가: { | |
| 163 | 추가: child = Process.GetProcessById(id); | |
| 164 | 추가: } | |
| 165 | 추가: else | |
| 166 | 추가: { | |
| 167 | 추가: Check.That(!operation.IsCompleted, "자식 준비 전에 작업이 종료됨"); | |
| 168 | 추가: await Task.Delay(10, guard.Token); | |
| 169 | 추가: } | |
| 170 | 추가: } | |
| 171 | 추가: if (!deadline) { cancellation.Cancel(); } | |
| 172 | 추가: var result = await operation.WaitAsync(TimeSpan.FromSeconds(10)); | |
| 173 | 추가: Failed(result, deadline ? ArchiveError.BudgetExceeded : ArchiveError.Cancelled); | |
| 174 | 추가: Check.That(child.HasExited, "취소 응답 뒤에도 작업자가 남아 있음"); | |
| 175 | 추가: } | |
| 176 | 추가: finally | |
| 177 | 추가: { | |
| 178 | 추가: cancellation.Cancel(); | |
| 179 | 추가: try { await operation.WaitAsync(TimeSpan.FromSeconds(10)); } | |
| 180 | 추가: finally | |
| 181 | 추가: { | |
| 182 | 추가: if (child is not null) | |
| 183 | 추가: { | |
| 184 | 추가: try | |
| 185 | 추가: { | |
| 186 | 추가: if (!child.HasExited) | |
| 187 | 추가: { | |
| 188 | 추가: child.Kill(entireProcessTree: true); | |
| 189 | 추가: await child.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(5)); | |
| 190 | 추가: } | |
| 191 | 추가: } | |
| 192 | 추가: finally { child.Dispose(); } | |
| 193 | 추가: } | |
| 194 | 추가: } | |
| 195 | 추가: } | |
| 196 | 추가: } | |
| 197 | 추가: | |
| 198 | 추가: private async Task ListZip() | |
| 199 | 추가: { | |
| 200 | 추가: var source = Path.Combine(sandbox, "list-source.zip"); | |
| 201 | 추가: File.Copy(Path.Combine(root, "tests", "security", "fixtures", "normal.zip"), source); | |
| 202 | 추가: var before = SHA256.HashData(await File.ReadAllBytesAsync(source)); | |
| 203 | 추가: await using (var input = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read)) | |
| 204 | 추가: { | |
| 205 | 추가: var result = await Worker.ListAsync(Guid.NewGuid(), input, Limits, default); | |
| 206 | 추가: Check.Equal(JobState.Completed, result.Job.State); | |
| 207 | 추가: Check.Equal(ArchiveError.None, result.Job.Error); | |
| 208 | 추가: Check.That(result.CreatedZip is null, "목록 요청이 생성물을 반환함"); | |
| 209 | 추가: Check.Equal(2, result.Job.Entries.Count); | |
| 210 | 추가: Check.Equal("hello.txt", result.Job.Entries[0].Entry.Name); | |
| 211 | 추가: Check.That(result.Job.Entries.All(entry => entry.Outcome == EntryOutcome.Listed && | |
| 212 | 추가: entry.Verification == VerificationState.NotChecked), "목록을 내용 검증 완료로 표시함"); | |
| 213 | 추가: Check.That(input.CanRead && !input.CanWrite, "읽기 전용 입력의 소유권이 깨짐"); | |
| 214 | 추가: } | |
| 215 | 추가: var after = SHA256.HashData(await File.ReadAllBytesAsync(source)); | |
| 216 | 추가: Check.That(before.SequenceEqual(after), "목록 요청이 원본을 변경함"); | |
| 217 | 추가: } | |
| 218 | 추가: | |
| 219 | 추가: private static async Task CreateZip() | |
| 220 | 추가: { | |
| 221 | 추가: byte[] bytes = [7, 8, 9]; | |
| 222 | 추가: var result = await Create(Worker, "hello.txt", bytes); | |
| 223 | 추가: Check.Equal(JobState.Completed, result.Job.State); | |
| 224 | 추가: Check.Equal(ArchiveError.None, result.Job.Error); | |
| 225 | 추가: var zip = result.CreatedZip ?? throw new InvalidOperationException(); | |
| 226 | 추가: using var data = new MemoryStream(zip, false); | |
| 227 | 추가: using var archive = new ZipArchive(data, ZipArchiveMode.Read); | |
| 228 | 추가: Check.Equal(1, archive.Entries.Count); | |
| 229 | 추가: Check.Equal("hello.txt", archive.Entries[0].FullName); | |
| 230 | 추가: using var decoded = new MemoryStream(); | |
| 231 | 추가: using var entryStream = archive.Entries[0].Open(); | |
| 232 | 추가: await entryStream.CopyToAsync(decoded); | |
| 233 | 추가: Check.That(bytes.SequenceEqual(decoded.ToArray()), "생성 ZIP 내용이 입력과 다름"); | |
| 234 | 추가: Failed(await Create(Worker, "hello.txt", bytes, Limits with { MaxProcessedBytes = bytes.Length }), | |
| 235 | 추가: ArchiveError.BudgetExceeded); | |
| 236 | 추가: Failed(await Create(Worker, "hello.txt", bytes, Limits with { MaxOutputBytes = 16 }), ArchiveError.BudgetExceeded); | |
| 237 | 추가: Failed(await Create(Worker, "hello.txt", bytes, Limits with { MaxEntries = 1 }), ArchiveError.BudgetExceeded); | |
| 238 | 추가: } | |
| 239 | 추가: | |
| 240 | 추가: private static async Task ZipNames() | |
| 241 | 추가: { | |
| 242 | 추가: using var first = new MemoryStream(new byte[] { 1 }, false); | |
| 243 | 추가: using var second = new MemoryStream(new byte[] { 2 }, false); | |
| 244 | 추가: var result = await Worker.CreateAsync(Guid.NewGuid(), | |
| 245 | 추가: [new("Readme.txt", first), new("README.TXT", second)], Limits, null, default); | |
| 246 | 추가: if (OperatingSystem.IsWindows()) { Failed(result, ArchiveError.OutputConflict); } | |
| 247 | 추가: else | |
| 248 | 추가: { | |
| 249 | 추가: Check.Equal(JobState.Completed, result.Job.State); | |
| 250 | 추가: using var stream = new MemoryStream(result.CreatedZip ?? throw new InvalidOperationException(), false); | |
| 251 | 추가: using var zip = new ZipArchive(stream, ZipArchiveMode.Read); | |
| 252 | 추가: Check.That(zip.Entries.Select(entry => entry.FullName).SequenceEqual(new[] { "Readme.txt", "README.TXT" }), | |
| 253 | 추가: "Linux 이름을 합치거나 변경함"); | |
| 254 | 추가: } | |
| 255 | 추가: foreach (var name in new[] { "CON", "name:stream", "name.", "e\u0301.txt", "back\\slash" }) | |
| 256 | 추가: { | |
| 257 | 추가: var named = await Create(Worker, name); | |
| 258 | 추가: if (OperatingSystem.IsWindows() && name != "back\\slash") { Failed(named, ArchiveError.UnsafePath); } | |
| 259 | 추가: else | |
| 260 | 추가: { | |
| 261 | 추가: Check.Equal(JobState.Completed, named.Job.State); | |
| 262 | 추가: using var stream = new MemoryStream(named.CreatedZip ?? throw new InvalidOperationException(), false); | |
| 263 | 추가: using var zip = new ZipArchive(stream, ZipArchiveMode.Read); | |
| 264 | 추가: Check.Equal(OperatingSystem.IsWindows() ? name.Replace('\\', '/') : name, zip.Entries[0].FullName); | |
| 265 | 추가: } | |
| 266 | 추가: } | |
| 267 | 추가: first.Position = 0; | |
| 268 | 추가: second.Position = 0; | |
| 269 | 추가: Failed(await Worker.CreateAsync(Guid.NewGuid(), [new("file", first), new("file/child", second)], | |
| 270 | 추가: Limits, null, default), ArchiveError.OutputConflict); | |
| 271 | 추가: } | |
| 272 | 추가: | |
| 273 | 추가: private async Task ListFailures() | |
| 274 | 추가: { | |
| 275 | 추가: using var broken = File.OpenRead(Path.Combine(root, "tests", "security", "fixtures", "truncated.zip")); | |
| 276 | 추가: Failed(await Worker.ListAsync(Guid.NewGuid(), broken, Limits, default), ArchiveError.IntegrityFailure); | |
| 277 | 추가: using var normal = File.OpenRead(Path.Combine(root, "tests", "security", "fixtures", "normal.zip")); | |
| 278 | 추가: Failed(await Worker.ListAsync(Guid.NewGuid(), normal, Limits with { MaxEntries = 1 }, default), | |
| 279 | 추가: ArchiveError.BudgetExceeded); | |
| 280 | 추가: } | |
| 281 | 추가: | |
| 282 | 추가: private sealed class GeneratedInput(long length) : Stream | |
| 283 | 추가: { | |
| 284 | 추가: public long BytesRead { get; private set; } | |
| 285 | 추가: public override bool CanRead => true; | |
| 286 | 추가: public override bool CanSeek => false; | |
| 287 | 추가: public override bool CanWrite => false; | |
| 288 | 추가: public override long Length => throw new NotSupportedException(); | |
| 289 | 추가: public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } | |
| 290 | 추가: public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken token = default) | |
| 291 | 추가: { | |
| 292 | 추가: token.ThrowIfCancellationRequested(); | |
| 293 | 추가: var count = (int)Math.Min(buffer.Length, length - BytesRead); | |
| 294 | 추가: buffer.Span[..count].Clear(); | |
| 295 | 추가: BytesRead += count; | |
| 296 | 추가: return ValueTask.FromResult(count); | |
| 297 | 추가: } | |
| 298 | 추가: public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); | |
| 299 | 추가: public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); | |
| 300 | 추가: public override void Flush() => throw new NotSupportedException(); | |
| 301 | 추가: public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); | |
| 302 | 추가: public override void SetLength(long value) => throw new NotSupportedException(); | |
| 303 | 추가: } | |
| 304 | 추가: | |
| 305 | 추가: private sealed class WaitingInput : MemoryStream | |
| 306 | 추가: { | |
| 307 | 추가: public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); | |
| 308 | 추가: public WaitingInput() : base(new byte[] { 1 }, false) { } | |
| 309 | 추가: public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken token = default) | |
| 310 | 추가: { | |
| 311 | 추가: Entered.TrySetResult(); | |
| 312 | 추가: await Task.Delay(Timeout.Infinite, token); | |
| 313 | 추가: return 0; | |
| 314 | 추가: } | |
| 315 | 추가: } | |
| 316 | 추가: } |
| @@ -0,0 +1,23 @@ | ||
| 1 | 추가: <Project Sdk="Microsoft.NET.Sdk"> | |
| 2 | 추가: <PropertyGroup> | |
| 3 | 추가: <OutputType>Exe</OutputType> | |
| 4 | 추가: <TargetFramework>net10.0</TargetFramework> | |
| 5 | 추가: <Nullable>enable</Nullable> | |
| 6 | 추가: <ImplicitUsings>enable</ImplicitUsings> | |
| 7 | 추가: <TreatWarningsAsErrors>true</TreatWarningsAsErrors> | |
| 8 | 추가: <EnableDefaultCompileItems>false</EnableDefaultCompileItems> | |
| 9 | 추가: </PropertyGroup> | |
| 10 | 추가: <ItemGroup> | |
| 11 | 추가: <Compile Include="Program.cs" /> | |
| 12 | 추가: <Compile Include="RuntimeTests.cs" /> | |
| 13 | 추가: <Compile Include="PublicationTests.cs" /> | |
| 14 | 추가: <Compile Include="ExtractionTests.cs" /> | |
| 15 | 추가: <Compile Include="ExtractionPublicationTests.cs" /> | |
| 16 | 추가: <Compile Include="FolderConcurrencyTests.cs" /> | |
| 17 | 추가: <Compile Include="FolderEnvironment.cs" /> | |
| 18 | 추가: <Compile Include="ProtocolPeer.cs" /> | |
| 19 | 추가: <Compile Include="../security/TestSupport.cs" /> | |
| 20 | 추가: <ProjectReference Include="../../src/Zipelo.Runtime/Zipelo.Runtime.csproj" /> | |
| 21 | 추가: <ProjectReference Include="../../src/Zipelo.Worker/Zipelo.Worker.csproj" ReferenceOutputAssembly="false" /> | |
| 22 | 추가: </ItemGroup> | |
| 23 | 추가: </Project> |
| @@ -0,0 +1,4 @@ | ||
| 1 | 추가: .work/ | |
| 2 | 추가: __pycache__/ | |
| 3 | 추가: bin/ | |
| 4 | 추가: obj/ |
| @@ -0,0 +1,354 @@ | ||
| 1 | 추가: using System.Collections.Concurrent; | |
| 2 | 추가: using System.Security; | |
| 3 | 추가: using Zipelo.Core; | |
| 4 | 추가: | |
| 5 | 추가: namespace Zipelo.SecurityTests; | |
| 6 | 추가: | |
| 7 | 추가: internal sealed partial class CoreTests | |
| 8 | 추가: { | |
| 9 | 추가: private static readonly TimeSpan RegressionTimeout = TimeSpan.FromSeconds(5); | |
| 10 | 추가: | |
| 11 | 추가: private static async Task ConcurrentPasswords() | |
| 12 | 추가: { | |
| 13 | 추가: using var firstSecret = TestSecrets.Create(); | |
| 14 | 추가: using var secondSecret = TestSecrets.Create(); | |
| 15 | 추가: var response = new TaskCompletionSource<SecureString?>(TaskCreationOptions.RunContinuationsAsynchronously); | |
| 16 | 추가: var challenges = new ConcurrentQueue<PasswordChallenge>(); | |
| 17 | 추가: var activeCounts = new ConcurrentQueue<int>(); | |
| 18 | 추가: var observed = new ConcurrentQueue<JobEvent>(); | |
| 19 | 추가: var active = 0; | |
| 20 | 추가: var calls = 0; | |
| 21 | 추가: var callsWhileWaiting = 0; | |
| 22 | 추가: var bothPending = false; | |
| 23 | 추가: var waitingPreserved = false; | |
| 24 | 추가: var correctFirst = false; | |
| 25 | 추가: var correctSecond = false; | |
| 26 | 추가: | |
| 27 | 추가: var run = await Execute(Stub(async context => | |
| 28 | 추가: { | |
| 29 | 추가: var first = context.UsePasswordAsync((secret, token) => | |
| 30 | 추가: { | |
| 31 | 추가: correctFirst = ReferenceEquals(firstSecret, secret); | |
| 32 | 추가: return ValueTask.FromResult(0); | |
| 33 | 추가: }).AsTask(); | |
| 34 | 추가: var second = context.UsePasswordAsync((secret, token) => | |
| 35 | 추가: { | |
| 36 | 추가: correctSecond = ReferenceEquals(secondSecret, secret); | |
| 37 | 추가: return ValueTask.FromResult(0); | |
| 38 | 추가: }).AsTask(); | |
| 39 | 추가: try | |
| 40 | 추가: { | |
| 41 | 추가: callsWhileWaiting = Volatile.Read(ref calls); | |
| 42 | 추가: bothPending = !first.IsCompleted && !second.IsCompleted; | |
| 43 | 추가: var eventCount = observed.Count; | |
| 44 | 추가: await context.ListEntryAsync(new("listed", "listed.txt", EntryKind.File, 0)); | |
| 45 | 추가: await Write(context, "written.txt", [1, 2]); | |
| 46 | 추가: var snapshot = observed.ToArray(); | |
| 47 | 추가: waitingPreserved = snapshot[^1].State == JobState.WaitingForPassword && | |
| 48 | 추가: snapshot.Skip(eventCount).All(value => value.State == JobState.WaitingForPassword); | |
| 49 | 추가: } | |
| 50 | 추가: finally | |
| 51 | 추가: { | |
| 52 | 추가: response.TrySetResult(firstSecret); | |
| 53 | 추가: await Task.WhenAll(first, second).WaitAsync(RegressionTimeout); | |
| 54 | 추가: } | |
| 55 | 추가: }), passwords: async (challenge, token) => | |
| 56 | 추가: { | |
| 57 | 추가: challenges.Enqueue(challenge); | |
| 58 | 추가: activeCounts.Enqueue(Interlocked.Increment(ref active)); | |
| 59 | 추가: var call = Interlocked.Increment(ref calls); | |
| 60 | 추가: try | |
| 61 | 추가: { | |
| 62 | 추가: return call == 1 ? await response.Task : secondSecret; | |
| 63 | 추가: } | |
| 64 | 추가: finally { Interlocked.Decrement(ref active); } | |
| 65 | 추가: }, observe: observed.Enqueue); | |
| 66 | 추가: | |
| 67 | 추가: Check.Equal(JobState.Completed, run.Result.State); | |
| 68 | 추가: Check.Equal(1, callsWhileWaiting); | |
| 69 | 추가: Check.That(bothPending, "첫 제공자 응답 전에 다른 요청이 완료됨"); | |
| 70 | 추가: Check.That(waitingPreserved, "항목 진행이 암호 대기 상태를 덮어씀"); | |
| 71 | 추가: Check.Equal(1, activeCounts.Max()); | |
| 72 | 추가: Check.Equal(2, calls); | |
| 73 | 추가: Check.That(correctFirst && correctSecond, "다른 요청의 암호를 소비함"); | |
| 74 | 추가: var requests = challenges.ToArray(); | |
| 75 | 추가: Check.That(requests.Select(value => value.Attempt).SequenceEqual(new[] { 1, 2 }), | |
| 76 | 추가: "동시 요청의 시도 번호가 잘못됨"); | |
| 77 | 추가: Check.Equal(2, requests.Select(value => value.RequestId).Distinct().Count()); | |
| 78 | 추가: Check.That(requests.All(value => value.JobId == run.Result.JobId), "다른 작업의 암호 요청임"); | |
| 79 | 추가: Check.Throws<ObjectDisposedException>(() => { _ = firstSecret.Length; }); | |
| 80 | 추가: Check.Throws<ObjectDisposedException>(() => { _ = secondSecret.Length; }); | |
| 81 | 추가: } | |
| 82 | 추가: | |
| 83 | 추가: private static async Task QueuedPasswordCancellation() | |
| 84 | 추가: { | |
| 85 | 추가: using var cancellation = new CancellationTokenSource(); | |
| 86 | 추가: using var lateSecret = TestSecrets.Create(); | |
| 87 | 추가: var response = new TaskCompletionSource<SecureString?>(TaskCreationOptions.RunContinuationsAsynchronously); | |
| 88 | 추가: var observed = new ConcurrentQueue<JobEvent>(); | |
| 89 | 추가: var calls = 0; | |
| 90 | 추가: var consumed = 0; | |
| 91 | 추가: var run = await Execute(Stub(async context => | |
| 92 | 추가: { | |
| 93 | 추가: ValueTask<int> Consume(SecureString secret, CancellationToken token) | |
| 94 | 추가: { | |
| 95 | 추가: Interlocked.Increment(ref consumed); | |
| 96 | 추가: return ValueTask.FromResult(0); | |
| 97 | 추가: } | |
| 98 | 추가: | |
| 99 | 추가: var first = context.UsePasswordAsync(Consume).AsTask(); | |
| 100 | 추가: var second = context.UsePasswordAsync(Consume).AsTask(); | |
| 101 | 추가: cancellation.Cancel(); | |
| 102 | 추가: try | |
| 103 | 추가: { | |
| 104 | 추가: await Check.ThrowsAsync<OperationCanceledException>( | |
| 105 | 추가: () => second.WaitAsync(RegressionTimeout)); | |
| 106 | 추가: } | |
| 107 | 추가: finally | |
| 108 | 추가: { | |
| 109 | 추가: // 취소를 무시하고 늦게 반환하는 제공자를 재현함. | |
| 110 | 추가: response.TrySetResult(lateSecret); | |
| 111 | 추가: await Check.ThrowsAsync<OperationCanceledException>( | |
| 112 | 추가: () => first.WaitAsync(RegressionTimeout)); | |
| 113 | 추가: } | |
| 114 | 추가: context.CancellationToken.ThrowIfCancellationRequested(); | |
| 115 | 추가: }), passwords: async (challenge, token) => | |
| 116 | 추가: { | |
| 117 | 추가: Interlocked.Increment(ref calls); | |
| 118 | 추가: return await response.Task; | |
| 119 | 추가: }, token: cancellation.Token, observe: observed.Enqueue); | |
| 120 | 추가: | |
| 121 | 추가: Cancelled(run); | |
| 122 | 추가: Check.Equal(1, calls); | |
| 123 | 추가: Check.Equal(0, consumed); | |
| 124 | 추가: Check.Throws<ObjectDisposedException>(() => { _ = lateSecret.Length; }); | |
| 125 | 추가: var events = observed.ToArray(); | |
| 126 | 추가: var cancelIndex = Array.FindIndex(events, value => value.State == JobState.Cancelling); | |
| 127 | 추가: Check.That(cancelIndex >= 0, "취소 요청 이벤트가 없음"); | |
| 128 | 추가: Check.That(events.Skip(cancelIndex).All(value => | |
| 129 | 추가: value.State is JobState.Cancelling or JobState.Cancelled), "취소 뒤 활성 상태가 보고됨"); | |
| 130 | 추가: var count = observed.Count; | |
| 131 | 추가: cancellation.Cancel(); | |
| 132 | 추가: Check.Equal(count, observed.Count); | |
| 133 | 추가: Check.Equal(JobState.Cancelled, events[^1].State); | |
| 134 | 추가: } | |
| 135 | 추가: | |
| 136 | 추가: private static async Task PasswordGateAfterFailures() | |
| 137 | 추가: { | |
| 138 | 추가: var secrets = new List<SecureString>(); | |
| 139 | 추가: var challenges = new List<PasswordChallenge>(); | |
| 140 | 추가: var run = await Execute(Stub(async context => | |
| 141 | 추가: { | |
| 142 | 추가: await Check.ThrowsAsync<IOException>(() => context.UsePasswordAsync( | |
| 143 | 추가: (secret, token) => ValueTask.FromResult(0)).AsTask().WaitAsync(RegressionTimeout)); | |
| 144 | 추가: await Check.ThrowsAsync<IOException>(() => context.UsePasswordAsync<int>( | |
| 145 | 추가: (secret, token) => ValueTask.FromException<int>(new IOException("테스트 소비 실패"))) | |
| 146 | 추가: .AsTask().WaitAsync(RegressionTimeout)); | |
| 147 | 추가: var length = await context.UsePasswordAsync( | |
| 148 | 추가: (secret, token) => ValueTask.FromResult(secret.Length)).AsTask().WaitAsync(RegressionTimeout); | |
| 149 | 추가: Check.That(length > 0, "실패 후 암호 재요청에 실패함"); | |
| 150 | 추가: }), passwords: (challenge, token) => | |
| 151 | 추가: { | |
| 152 | 추가: challenges.Add(challenge); | |
| 153 | 추가: if (challenges.Count == 1) | |
| 154 | 추가: { | |
| 155 | 추가: return ValueTask.FromException<SecureString?>(new IOException("테스트 제공 실패")); | |
| 156 | 추가: } | |
| 157 | 추가: var secret = TestSecrets.Create(); | |
| 158 | 추가: secrets.Add(secret); | |
| 159 | 추가: return ValueTask.FromResult<SecureString?>(secret); | |
| 160 | 추가: }); | |
| 161 | 추가: | |
| 162 | 추가: Check.Equal(JobState.Completed, run.Result.State); | |
| 163 | 추가: Check.That(challenges.Select(value => value.Attempt).SequenceEqual(new[] { 1, 2, 3 }), | |
| 164 | 추가: "재요청의 시도 번호가 잘못됨"); | |
| 165 | 추가: Check.Equal(2, secrets.Count); | |
| 166 | 추가: foreach (var secret in secrets) | |
| 167 | 추가: { | |
| 168 | 추가: Check.Throws<ObjectDisposedException>(() => { _ = secret.Length; }); | |
| 169 | 추가: } | |
| 170 | 추가: } | |
| 171 | 추가: | |
| 172 | 추가: private static async Task PasswordConsumerReentry() | |
| 173 | 추가: { | |
| 174 | 추가: var secrets = new List<SecureString>(); | |
| 175 | 추가: var calls = 0; | |
| 176 | 추가: var run = await Execute(Stub(async context => | |
| 177 | 추가: { | |
| 178 | 추가: var combined = await context.UsePasswordAsync(async (outer, token) => | |
| 179 | 추가: { | |
| 180 | 추가: var length = outer.Length; | |
| 181 | 추가: var innerLength = await context.UsePasswordAsync( | |
| 182 | 추가: (inner, innerToken) => ValueTask.FromResult(inner.Length)); | |
| 183 | 추가: Check.Equal(length, outer.Length); | |
| 184 | 추가: return length + innerLength; | |
| 185 | 추가: }).AsTask().WaitAsync(RegressionTimeout); | |
| 186 | 추가: Check.That(combined > 0, "소비자의 암호 재요청이 완료되지 않음"); | |
| 187 | 추가: }), passwords: (challenge, token) => | |
| 188 | 추가: { | |
| 189 | 추가: calls++; | |
| 190 | 추가: var secret = TestSecrets.Create(); | |
| 191 | 추가: secrets.Add(secret); | |
| 192 | 추가: return ValueTask.FromResult<SecureString?>(secret); | |
| 193 | 추가: }); | |
| 194 | 추가: | |
| 195 | 추가: Check.Equal(JobState.Completed, run.Result.State); | |
| 196 | 추가: Check.Equal(2, calls); | |
| 197 | 추가: foreach (var secret in secrets) | |
| 198 | 추가: { | |
| 199 | 추가: Check.Throws<ObjectDisposedException>(() => { _ = secret.Length; }); | |
| 200 | 추가: } | |
| 201 | 추가: } | |
| 202 | 추가: | |
| 203 | 추가: private static async Task InitializationCleanup() | |
| 204 | 추가: { | |
| 205 | 추가: foreach (var scenario in new[] { "null_limits", "invalid_limits", "input_copy" }) | |
| 206 | 추가: { | |
| 207 | 추가: using var input = new MemoryStream(new byte[] { 1 }, false); | |
| 208 | 추가: var output = new RecordingOutput(); | |
| 209 | 추가: var engine = Stub(_ => Task.CompletedTask); | |
| 210 | 추가: var events = new List<JobEvent>(); | |
| 211 | 추가: var limits = scenario == "null_limits" ? null : | |
| 212 | 추가: scenario == "invalid_limits" ? Limits with { MaxEntries = 0 } : Limits; | |
| 213 | 추가: IReadOnlyList<Stream> inputs = scenario == "input_copy" ? new ThrowingInputs() : new[] { input }; | |
| 214 | 추가: var result = await new ArchiveJob(Guid.NewGuid(), limits!).ExecuteAsync( | |
| 215 | 추가: ArchiveAction.List, "zip", engine, inputs, output, TestSecrets.None, | |
| 216 | 추가: new InlineProgress(events.Add), default); | |
| 217 | 추가: | |
| 218 | 추가: Check.Equal(JobState.Failed, result.State); | |
| 219 | 추가: Check.Equal(scenario == "input_copy" ? ArchiveError.EngineFailure : ArchiveError.UnsupportedOperation, | |
| 220 | 추가: result.Error); | |
| 221 | 추가: Check.Equal(0, engine.Calls); | |
| 222 | 추가: Check.Equal(1, output.DisposeCalls); | |
| 223 | 추가: Check.That(output.Disposed, "초기화 실패 뒤 출력 정리가 누락됨"); | |
| 224 | 추가: Check.Equal(0, output.CreateCalls); | |
| 225 | 추가: Check.Equal(0, output.CommitCalls); | |
| 226 | 추가: Check.Equal(0, result.Entries.Count); | |
| 227 | 추가: Check.Equal(1, events.Count); | |
| 228 | 추가: Check.Equal(JobState.Failed, events[0].State); | |
| 229 | 추가: Check.Equal(0L, events[0].ProcessedBytes); | |
| 230 | 추가: Check.That(input.CanRead, "초기화 실패가 호출자 입력을 폐기함"); | |
| 231 | 추가: } | |
| 232 | 추가: } | |
| 233 | 추가: | |
| 234 | 추가: private static async Task RejectedOutputOwnership() | |
| 235 | 추가: { | |
| 236 | 추가: using var input = new MemoryStream(new byte[] { 1 }, false); | |
| 237 | 추가: var job = new ArchiveJob(Guid.NewGuid(), Limits); | |
| 238 | 추가: var engine = Stub(_ => Task.CompletedTask); | |
| 239 | 추가: var rejected = new RecordingOutput(); | |
| 240 | 추가: try | |
| 241 | 추가: { | |
| 242 | 추가: await Check.ThrowsAsync<ArgumentNullException>(async () => await job.ExecuteAsync( | |
| 243 | 추가: ArchiveAction.List, "zip", null!, [input], rejected, TestSecrets.None, null, default)); | |
| 244 | 추가: Check.Equal(0, rejected.DisposeCalls); | |
| 245 | 추가: } | |
| 246 | 추가: finally { await rejected.DisposeAsync(); } | |
| 247 | 추가: | |
| 248 | 추가: var accepted = new RecordingOutput(); | |
| 249 | 추가: var result = await job.ExecuteAsync(ArchiveAction.List, "zip", engine, [input], | |
| 250 | 추가: accepted, TestSecrets.None, null, default); | |
| 251 | 추가: Check.Equal(JobState.Completed, result.State); | |
| 252 | 추가: Check.Equal(1, accepted.DisposeCalls); | |
| 253 | 추가: | |
| 254 | 추가: var reused = new RecordingOutput(); | |
| 255 | 추가: try | |
| 256 | 추가: { | |
| 257 | 추가: await Check.ThrowsAsync<InvalidOperationException>(async () => await job.ExecuteAsync( | |
| 258 | 추가: ArchiveAction.List, "zip", engine, [input], reused, TestSecrets.None, null, default)); | |
| 259 | 추가: Check.Equal(0, reused.DisposeCalls); | |
| 260 | 추가: } | |
| 261 | 추가: finally { await reused.DisposeAsync(); } | |
| 262 | 추가: } | |
| 263 | 추가: | |
| 264 | 추가: private static async Task IntegrityCleanupFailure() | |
| 265 | 추가: { | |
| 266 | 추가: var run = await Execute(Stub(context => Write(context, "bad.txt", [1], | |
| 267 | 추가: verification: VerificationState.Failed)), output: new RecordingOutput { FailDispose = true }); | |
| 268 | 추가: Failed(run, ArchiveError.IntegrityFailure); | |
| 269 | 추가: Check.Equal(1, run.Output.DisposeCalls); | |
| 270 | 추가: Check.Equal(VerificationState.Failed, run.Result.Entries.Single().Verification); | |
| 271 | 추가: Check.Equal(ArchiveError.IntegrityFailure, run.Result.Entries.Single().Error); | |
| 272 | 추가: } | |
| 273 | 추가: | |
| 274 | 추가: private static async Task CancellationCleanupFailure() | |
| 275 | 추가: { | |
| 276 | 추가: using var cancellation = new CancellationTokenSource(); | |
| 277 | 추가: var run = await Execute(Stub(context => | |
| 278 | 추가: { | |
| 279 | 추가: cancellation.Cancel(); | |
| 280 | 추가: context.CancellationToken.ThrowIfCancellationRequested(); | |
| 281 | 추가: return Task.CompletedTask; | |
| 282 | 추가: }), output: new RecordingOutput { FailDispose = true }, token: cancellation.Token); | |
| 283 | 추가: Failed(run, ArchiveError.Cancelled); | |
| 284 | 추가: Check.Equal(1, run.Output.DisposeCalls); | |
| 285 | 추가: Check.That(!run.Events.Any(value => value.State == JobState.Cancelled), | |
| 286 | 추가: "정리 실패를 정상 취소 완료로 표시함"); | |
| 287 | 추가: } | |
| 288 | 추가: | |
| 289 | 추가: private static async Task LateCommitCancellation() | |
| 290 | 추가: { | |
| 291 | 추가: foreach (var failCleanup in new[] { false, true }) | |
| 292 | 추가: { | |
| 293 | 추가: using var cancellation = new CancellationTokenSource(); | |
| 294 | 추가: var output = new RecordingOutput | |
| 295 | 추가: { | |
| 296 | 추가: AfterCommit = cancellation.Cancel, | |
| 297 | 추가: FailDispose = failCleanup | |
| 298 | 추가: }; | |
| 299 | 추가: var run = await Execute(Stub(context => Write(context, "published.txt", [1])), | |
| 300 | 추가: output: output, token: cancellation.Token); | |
| 301 | 추가: Check.Equal(failCleanup ? JobState.Failed : JobState.Completed, run.Result.State); | |
| 302 | 추가: Check.Equal(failCleanup ? ArchiveError.OutputUnavailable : ArchiveError.None, run.Result.Error); | |
| 303 | 추가: Check.Equal(1, output.CommitCalls); | |
| 304 | 추가: Check.Equal(1, output.DisposeCalls); | |
| 305 | 추가: Check.Equal(1, output.Published.Count); | |
| 306 | 추가: var entry = run.Result.Entries.Single(); | |
| 307 | 추가: Check.Equal(EntryOutcome.Extracted, entry.Outcome); | |
| 308 | 추가: Check.Equal(ArchiveError.None, entry.Error); | |
| 309 | 추가: Check.That(output.Published["published.txt"].SequenceEqual(new byte[] { 1 }), | |
| 310 | 추가: "늦은 취소가 확정된 결과를 바꿈"); | |
| 311 | 추가: } | |
| 312 | 추가: } | |
| 313 | 추가: | |
| 314 | 추가: private static async Task DeferredCleanup() | |
| 315 | 추가: { | |
| 316 | 추가: var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); | |
| 317 | 추가: var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); | |
| 318 | 추가: var observed = new ConcurrentQueue<JobEvent>(); | |
| 319 | 추가: var output = new RecordingOutput | |
| 320 | 추가: { | |
| 321 | 추가: BeforeDispose = async () => | |
| 322 | 추가: { | |
| 323 | 추가: entered.TrySetResult(); | |
| 324 | 추가: await release.Task; | |
| 325 | 추가: } | |
| 326 | 추가: }; | |
| 327 | 추가: var execution = Execute(Stub(_ => Task.CompletedTask), output: output, observe: observed.Enqueue); | |
| 328 | 추가: var completedTooEarly = false; | |
| 329 | 추가: var terminalTooEarly = false; | |
| 330 | 추가: try | |
| 331 | 추가: { | |
| 332 | 추가: await entered.Task.WaitAsync(RegressionTimeout); | |
| 333 | 추가: completedTooEarly = execution.IsCompleted; | |
| 334 | 추가: terminalTooEarly = observed.Any(value => value.State is | |
| 335 | 추가: JobState.Completed or JobState.Partial or JobState.Cancelled or JobState.Failed); | |
| 336 | 추가: } | |
| 337 | 추가: finally { release.TrySetResult(); } | |
| 338 | 추가: | |
| 339 | 추가: var run = await execution.WaitAsync(RegressionTimeout); | |
| 340 | 추가: Check.That(!completedTooEarly, "출력 정리 전에 작업이 완료됨"); | |
| 341 | 추가: Check.That(!terminalTooEarly, "출력 정리 전에 종료 이벤트가 보고됨"); | |
| 342 | 추가: Check.Equal(JobState.Completed, run.Result.State); | |
| 343 | 추가: Check.Equal(1, output.DisposeCalls); | |
| 344 | 추가: Check.Equal(JobState.Completed, observed.Last().State); | |
| 345 | 추가: } | |
| 346 | 추가: | |
| 347 | 추가: private sealed class ThrowingInputs : IReadOnlyList<Stream> | |
| 348 | 추가: { | |
| 349 | 추가: public int Count => 1; | |
| 350 | 추가: public Stream this[int index] => throw new IOException("테스트 입력 복사 실패"); | |
| 351 | 추가: public IEnumerator<Stream> GetEnumerator() => throw new IOException("테스트 입력 복사 실패"); | |
| 352 | 추가: System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); | |
| 353 | 추가: } | |
| 354 | 추가: } |
Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기