team-ljyzipelo

공개
316줄16 KB
1using System.Diagnostics;
2using System.IO.Compression;
3using System.Security.Cryptography;
4using System.Text;
5using Zipelo.Core;
6using Zipelo.Runtime;
7using Zipelo.SecurityTests;
8
9namespace Zipelo.RuntimeTests;
10
11internal 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}