| 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 ZipWorkerClient Worker => TestWorkerLaunch.Worker; |
| 15 | private static ZipWorkerClient Peer => TestWorkerLaunch.Peer; |
| 16 | |
| 17 | public IEnumerable<(string Name, Func<Task> Run)> Cases() |
| 18 | { |
| 19 | yield return ("runtime.absolute_worker_path_and_missing_files", Paths); |
| 20 | yield return ("runtime.readonly_input_and_options", InputsAndOptions); |
| 21 | yield return ("runtime.actual_bytes_and_16mib_limit", InputLimits); |
| 22 | yield return ("runtime.cancel_before_read_and_during_copy", InputCancellation); |
| 23 | yield return ("runtime.reject_frame_lengths_and_corruption", InvalidFrames); |
| 24 | yield return ("runtime.reject_exit_id_and_missing_artifact", InvalidResults); |
| 25 | yield return ("runtime.reject_nonterminal_result", () => InvalidState("nonterminal")); |
| 26 | yield return ("runtime.reject_success_with_error", () => InvalidState("success-error")); |
| 27 | yield return ("runtime.cancel_waits_for_worker_exit", () => StopWorker(false)); |
| 28 | yield return ("runtime.deadline_waits_for_worker_exit", () => StopWorker(true)); |
| 29 | yield return ("zip.real_list_preserves_source_and_unverified_entries", ListZip); |
| 30 | yield return ("zip.real_create_roundtrip_and_cumulative_budgets", CreateZip); |
| 31 | yield return ("zip.os_names_case_and_parent_collisions", ZipNames); |
| 32 | yield return ("zip.corruption_and_listing_budget", ListFailures); |
| 33 | yield return ("publication.new_file_exact_bytes", PublishNewFile); |
| 34 | yield return ("publication.conflict_preserves_existing_file", () => PublishConflictPreservesSource(false)); |
| 35 | yield return ("publication.conflict_preserves_input_source", () => PublishConflictPreservesSource(true)); |
| 36 | yield return ("publication.precancel_preserves_existing", PublishPreCancelled); |
| 37 | yield return ("publication.failure_preserves_existing", PublishFailurePreservesFiles); |
| 38 | yield return ("publication.rejects_parent_symlink", () => PublishRejectsLinks(true)); |
| 39 | yield return ("publication.rejects_leaf_symlink", () => PublishRejectsLinks(false)); |
| 40 | foreach (var item in new ExtractionTests(root, sandbox).Cases()) { yield return item; } |
| 41 | } |
| 42 | |
| 43 | private static void Failed(ZipWorkerResult result, ArchiveError error) |
| 44 | { |
| 45 | Check.Equal(error, result.Job.Error); |
| 46 | Check.Equal(error == ArchiveError.Cancelled ? JobState.Cancelled : JobState.Failed, result.Job.State); |
| 47 | Check.That(result.CreatedZip is null, "실패한 작업이 생성물을 반환함"); |
| 48 | } |
| 49 | |
| 50 | private static async Task<ZipWorkerResult> Create(ZipWorkerClient client, string name, |
| 51 | byte[]? bytes = null, JobLimits? limits = null, CancellationToken token = default) |
| 52 | { |
| 53 | using var input = new MemoryStream(bytes ?? new byte[] { 1 }, false); |
| 54 | return await client.CreateAsync(Guid.NewGuid(), [new(name, input)], limits ?? Limits, null, token); |
| 55 | } |
| 56 | |
| 57 | private Task Paths() |
| 58 | { |
| 59 | Check.Throws<ArgumentException>(() => new ZipWorkerClient("worker/Zipelo.Worker")); |
| 60 | Check.Throws<ArgumentException>(() => new ZipWorkerClient(Path.Combine(sandbox, "worker.dll"), "dotnet")); |
| 61 | Check.Throws<ArgumentException>(() => WorkerPlatform.GetWorkerPath("relative")); |
| 62 | var expected = OperatingSystem.IsWindows() ? "Zipelo.Worker.exe" : "Zipelo.Worker"; |
| 63 | Check.Equal(Path.Combine(sandbox, "worker", expected), WorkerPlatform.GetWorkerPath(sandbox)); |
| 64 | var missing = new ZipWorkerClient(Path.Combine(sandbox, "absent-worker.dll"), TestWorkerLaunch.DotnetHost); |
| 65 | Check.That(!missing.IsAvailable && missing.Capabilities.Count == 0, "없는 작업자를 사용 가능으로 표시함"); |
| 66 | Check.That(!Worker.SupportsSafeExtraction && !Worker.SupportsEncryption && !Worker.SupportsSplitVolumes, |
| 67 | "미구현 기능을 사용 가능으로 표시함"); |
| 68 | Check.That(Worker.IsAvailable && Peer.IsAvailable, "검사에 필요한 빌드 산출물이 없음"); |
| 69 | return Task.CompletedTask; |
| 70 | } |
| 71 | |
| 72 | private static async Task InputsAndOptions() |
| 73 | { |
| 74 | using var writable = new MemoryStream(new byte[] { 1 }); |
| 75 | Failed(await Worker.ListAsync(Guid.NewGuid(), writable, Limits, default), ArchiveError.UnsupportedOperation); |
| 76 | using var input = new MemoryStream(new byte[] { 1 }, false); |
| 77 | foreach (var option in new[] { new ZipCreationOptions(Encrypt: true), new ZipCreationOptions(SplitVolumeBytes: 1) }) |
| 78 | { |
| 79 | Failed(await Worker.CreateAsync(Guid.NewGuid(), [new("a", input)], Limits, option, default), |
| 80 | ArchiveError.UnsupportedOperation); |
| 81 | Check.Equal(0L, input.Position); |
| 82 | } |
| 83 | Failed(await Create(Worker, new string('x', 1025)), ArchiveError.BudgetExceeded); |
| 84 | var many = Enumerable.Range(0, 1025).Select(index => new ZipCreateInput(index.ToString(), input)).ToArray(); |
| 85 | Failed(await Worker.CreateAsync(Guid.NewGuid(), many, Limits, null, default), ArchiveError.BudgetExceeded); |
| 86 | Check.That(input.CanRead, "호출자 입력의 수명을 작업자가 종료함"); |
| 87 | } |
| 88 | |
| 89 | private static async Task InputLimits() |
| 90 | { |
| 91 | using var tiny = new MemoryStream(new byte[] { 1, 2, 3, 4 }, false); |
| 92 | Failed(await Worker.ListAsync(Guid.NewGuid(), tiny, Limits with { MaxProcessedBytes = 3 }, default), |
| 93 | ArchiveError.BudgetExceeded); |
| 94 | // 큰 파일을 만들지 않고 일정한 버퍼로 입력 상한을 시험함. |
| 95 | using var large = new GeneratedInput(16L * 1024 * 1024 + 1); |
| 96 | Failed(await Worker.ListAsync(Guid.NewGuid(), large, Limits with { MaxProcessedBytes = 32L * 1024 * 1024 }, |
| 97 | default), ArchiveError.BudgetExceeded); |
| 98 | Check.Equal(16L * 1024 * 1024 + 1, large.BytesRead); |
| 99 | } |
| 100 | |
| 101 | private static async Task InputCancellation() |
| 102 | { |
| 103 | using var cancelled = new CancellationTokenSource(); |
| 104 | cancelled.Cancel(); |
| 105 | using var untouched = new MemoryStream(new byte[] { 1 }, false); |
| 106 | Failed(await Worker.ListAsync(Guid.NewGuid(), untouched, Limits, cancelled.Token), ArchiveError.Cancelled); |
| 107 | Check.Equal(0L, untouched.Position); |
| 108 | using var source = new WaitingInput(); |
| 109 | using var pending = new CancellationTokenSource(); |
| 110 | var operation = Worker.ListAsync(Guid.NewGuid(), source, Limits, pending.Token); |
| 111 | try |
| 112 | { |
| 113 | await source.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); |
| 114 | pending.Cancel(); |
| 115 | Failed(await operation.WaitAsync(TimeSpan.FromSeconds(5)), ArchiveError.Cancelled); |
| 116 | } |
| 117 | finally { pending.Cancel(); } |
| 118 | } |
| 119 | |
| 120 | private static async Task InvalidFrames() |
| 121 | { |
| 122 | foreach (var mode in new[] { "zero", "negative", "oversized" }) |
| 123 | { |
| 124 | Failed(await Create(Peer, mode), ArchiveError.BudgetExceeded); |
| 125 | } |
| 126 | foreach (var mode in new[] { "truncated", "bad-json" }) |
| 127 | { |
| 128 | Failed(await Create(Peer, mode), ArchiveError.EngineFailure); |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | private static async Task InvalidResults() |
| 133 | { |
| 134 | foreach (var mode in new[] { "exit", "wrong-id", "missing-zip" }) |
| 135 | { |
| 136 | Failed(await Create(Peer, mode), ArchiveError.EngineFailure); |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | private static async Task InvalidState(string mode) |
| 141 | { |
| 142 | Failed(await Create(Peer, mode), ArchiveError.EngineFailure); |
| 143 | } |
| 144 | |
| 145 | private async Task StopWorker(bool deadline) |
| 146 | { |
| 147 | var directory = Path.Combine(sandbox, Guid.NewGuid().ToString("N")); |
| 148 | Directory.CreateDirectory(directory); |
| 149 | var marker = Path.Combine(directory, "child.pid"); |
| 150 | using var cancellation = new CancellationTokenSource(); |
| 151 | var operation = Create(Peer, "hang", Encoding.UTF8.GetBytes(marker), |
| 152 | Limits with { MaxDuration = TimeSpan.FromSeconds(deadline ? 5 : 15) }, cancellation.Token); |
| 153 | Process? child = null; |
| 154 | try |
| 155 | { |
| 156 | // 자식의 준비 표식을 기다리므로 취소 시점을 시작 시간 추측에 의존하지 않음. |
| 157 | using var guard = new CancellationTokenSource(TimeSpan.FromSeconds(8)); |
| 158 | while (child is null) |
| 159 | { |
| 160 | if (File.Exists(marker) && int.TryParse(await File.ReadAllTextAsync(marker, guard.Token), out var id)) |
| 161 | { |
| 162 | child = Process.GetProcessById(id); |
| 163 | } |
| 164 | else |
| 165 | { |
| 166 | Check.That(!operation.IsCompleted, "자식 준비 전에 작업이 종료됨"); |
| 167 | await Task.Delay(10, guard.Token); |
| 168 | } |
| 169 | } |
| 170 | if (!deadline) { cancellation.Cancel(); } |
| 171 | var result = await operation.WaitAsync(TimeSpan.FromSeconds(10)); |
| 172 | Failed(result, deadline ? ArchiveError.BudgetExceeded : ArchiveError.Cancelled); |
| 173 | Check.That(child.HasExited, "취소 응답 뒤에도 작업자가 남아 있음"); |
| 174 | } |
| 175 | finally |
| 176 | { |
| 177 | cancellation.Cancel(); |
| 178 | try { await operation.WaitAsync(TimeSpan.FromSeconds(10)); } |
| 179 | finally |
| 180 | { |
| 181 | if (child is not null) |
| 182 | { |
| 183 | try |
| 184 | { |
| 185 | if (!child.HasExited) |
| 186 | { |
| 187 | child.Kill(entireProcessTree: true); |
| 188 | await child.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(5)); |
| 189 | } |
| 190 | } |
| 191 | finally { child.Dispose(); } |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | private async Task ListZip() |
| 198 | { |
| 199 | var source = Path.Combine(sandbox, "list-source.zip"); |
| 200 | File.Copy(Path.Combine(root, "tests", "security", "fixtures", "normal.zip"), source); |
| 201 | var before = SHA256.HashData(await File.ReadAllBytesAsync(source)); |
| 202 | await using (var input = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read)) |
| 203 | { |
| 204 | var result = await Worker.ListAsync(Guid.NewGuid(), input, Limits, default); |
| 205 | Check.Equal(JobState.Completed, result.Job.State); |
| 206 | Check.Equal(ArchiveError.None, result.Job.Error); |
| 207 | Check.That(result.CreatedZip is null, "목록 요청이 생성물을 반환함"); |
| 208 | Check.Equal(2, result.Job.Entries.Count); |
| 209 | Check.Equal("hello.txt", result.Job.Entries[0].Entry.Name); |
| 210 | Check.That(result.Job.Entries.All(entry => entry.Outcome == EntryOutcome.Listed && |
| 211 | entry.Verification == VerificationState.NotChecked), "목록을 내용 검증 완료로 표시함"); |
| 212 | Check.That(input.CanRead && !input.CanWrite, "읽기 전용 입력의 소유권이 깨짐"); |
| 213 | } |
| 214 | var after = SHA256.HashData(await File.ReadAllBytesAsync(source)); |
| 215 | Check.That(before.SequenceEqual(after), "목록 요청이 원본을 변경함"); |
| 216 | } |
| 217 | |
| 218 | private static async Task CreateZip() |
| 219 | { |
| 220 | byte[] bytes = [7, 8, 9]; |
| 221 | var result = await Create(Worker, "hello.txt", bytes); |
| 222 | Check.Equal(JobState.Completed, result.Job.State); |
| 223 | Check.Equal(ArchiveError.None, result.Job.Error); |
| 224 | var zip = result.CreatedZip ?? throw new InvalidOperationException(); |
| 225 | using var data = new MemoryStream(zip, false); |
| 226 | using var archive = new ZipArchive(data, ZipArchiveMode.Read); |
| 227 | Check.Equal(1, archive.Entries.Count); |
| 228 | Check.Equal("hello.txt", archive.Entries[0].FullName); |
| 229 | using var decoded = new MemoryStream(); |
| 230 | using var entryStream = archive.Entries[0].Open(); |
| 231 | await entryStream.CopyToAsync(decoded); |
| 232 | Check.That(bytes.SequenceEqual(decoded.ToArray()), "생성 ZIP 내용이 입력과 다름"); |
| 233 | Failed(await Create(Worker, "hello.txt", bytes, Limits with { MaxProcessedBytes = bytes.Length }), |
| 234 | ArchiveError.BudgetExceeded); |
| 235 | Failed(await Create(Worker, "hello.txt", bytes, Limits with { MaxOutputBytes = 16 }), ArchiveError.BudgetExceeded); |
| 236 | Failed(await Create(Worker, "hello.txt", bytes, Limits with { MaxEntries = 1 }), ArchiveError.BudgetExceeded); |
| 237 | } |
| 238 | |
| 239 | private static async Task ZipNames() |
| 240 | { |
| 241 | using var first = new MemoryStream(new byte[] { 1 }, false); |
| 242 | using var second = new MemoryStream(new byte[] { 2 }, false); |
| 243 | var result = await Worker.CreateAsync(Guid.NewGuid(), |
| 244 | [new("Readme.txt", first), new("README.TXT", second)], Limits, null, default); |
| 245 | if (OperatingSystem.IsWindows()) { Failed(result, ArchiveError.OutputConflict); } |
| 246 | else |
| 247 | { |
| 248 | Check.Equal(JobState.Completed, result.Job.State); |
| 249 | using var stream = new MemoryStream(result.CreatedZip ?? throw new InvalidOperationException(), false); |
| 250 | using var zip = new ZipArchive(stream, ZipArchiveMode.Read); |
| 251 | Check.That(zip.Entries.Select(entry => entry.FullName).SequenceEqual(new[] { "Readme.txt", "README.TXT" }), |
| 252 | "Linux 이름을 합치거나 변경함"); |
| 253 | } |
| 254 | foreach (var name in new[] { "CON", "name:stream", "name.", "e\u0301.txt", "back\\slash" }) |
| 255 | { |
| 256 | var named = await Create(Worker, name); |
| 257 | if (OperatingSystem.IsWindows() && name != "back\\slash") { Failed(named, ArchiveError.UnsafePath); } |
| 258 | else |
| 259 | { |
| 260 | Check.Equal(JobState.Completed, named.Job.State); |
| 261 | using var stream = new MemoryStream(named.CreatedZip ?? throw new InvalidOperationException(), false); |
| 262 | using var zip = new ZipArchive(stream, ZipArchiveMode.Read); |
| 263 | Check.Equal(OperatingSystem.IsWindows() ? name.Replace('\\', '/') : name, zip.Entries[0].FullName); |
| 264 | } |
| 265 | } |
| 266 | first.Position = 0; |
| 267 | second.Position = 0; |
| 268 | Failed(await Worker.CreateAsync(Guid.NewGuid(), [new("file", first), new("file/child", second)], |
| 269 | Limits, null, default), ArchiveError.OutputConflict); |
| 270 | } |
| 271 | |
| 272 | private async Task ListFailures() |
| 273 | { |
| 274 | using var broken = File.OpenRead(Path.Combine(root, "tests", "security", "fixtures", "truncated.zip")); |
| 275 | Failed(await Worker.ListAsync(Guid.NewGuid(), broken, Limits, default), ArchiveError.IntegrityFailure); |
| 276 | using var normal = File.OpenRead(Path.Combine(root, "tests", "security", "fixtures", "normal.zip")); |
| 277 | Failed(await Worker.ListAsync(Guid.NewGuid(), normal, Limits with { MaxEntries = 1 }, default), |
| 278 | ArchiveError.BudgetExceeded); |
| 279 | } |
| 280 | |
| 281 | private sealed class GeneratedInput(long length) : Stream |
| 282 | { |
| 283 | public long BytesRead { get; private set; } |
| 284 | public override bool CanRead => true; |
| 285 | public override bool CanSeek => false; |
| 286 | public override bool CanWrite => false; |
| 287 | public override long Length => throw new NotSupportedException(); |
| 288 | public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } |
| 289 | public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken token = default) |
| 290 | { |
| 291 | token.ThrowIfCancellationRequested(); |
| 292 | var count = (int)Math.Min(buffer.Length, length - BytesRead); |
| 293 | buffer.Span[..count].Clear(); |
| 294 | BytesRead += count; |
| 295 | return ValueTask.FromResult(count); |
| 296 | } |
| 297 | public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); |
| 298 | public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); |
| 299 | public override void Flush() => throw new NotSupportedException(); |
| 300 | public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); |
| 301 | public override void SetLength(long value) => throw new NotSupportedException(); |
| 302 | } |
| 303 | |
| 304 | private sealed class WaitingInput : MemoryStream |
| 305 | { |
| 306 | public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); |
| 307 | public WaitingInput() : base(new byte[] { 1 }, false) { } |
| 308 | public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken token = default) |
| 309 | { |
| 310 | Entered.TrySetResult(); |
| 311 | await Task.Delay(Timeout.Infinite, token); |
| 312 | return 0; |
| 313 | } |
| 314 | } |
| 315 | } |