| 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 | } |