| 1 | using System.IO.Compression; |
| 2 | using System.Security; |
| 3 | using System.Security.Cryptography; |
| 4 | using Zipelo.Core; |
| 5 | |
| 6 | namespace Zipelo.SecurityTests; |
| 7 | |
| 8 | internal sealed partial class CoreTests(string root, string sandbox) |
| 9 | { |
| 10 | private static JobLimits Limits => new(32, 1024, 1024, TimeSpan.FromSeconds(5), 3); |
| 11 | |
| 12 | public IEnumerable<(string Name, Func<Task> Run)> Cases() |
| 13 | { |
| 14 | yield return ("path.accept_relative_unicode", () => Sync(ValidPaths)); |
| 15 | yield return ("path.reject_traversal_and_windows_aliases", () => Sync(UnsafePaths)); |
| 16 | yield return ("budget.exact_boundary_and_latched_exhaustion", () => Sync(BudgetBoundaries)); |
| 17 | yield return ("budget.reject_negative_and_overflow", () => Sync(BudgetInvalidCharges)); |
| 18 | yield return ("budget.deadline_with_controlled_clock", () => Sync(BudgetDeadline)); |
| 19 | yield return ("budget.concurrent_cumulative_charges", ConcurrentBudget); |
| 20 | yield return ("job.reject_writable_input", WritableInput); |
| 21 | yield return ("job.unavailable_engine_fails", UnavailableEngineFails); |
| 22 | yield return ("job.unavailable_output_fails", UnavailableOutputFails); |
| 23 | yield return ("job.single_use", SingleUse); |
| 24 | yield return ("output.block_path_before_create", UnsafeWrite); |
| 25 | yield return ("output.reject_archive_links", ArchiveLinks); |
| 26 | yield return ("output.reject_parent_collisions", OutputCollisions); |
| 27 | yield return ("output.propagate_existing_file_conflict", ExistingConflict); |
| 28 | yield return ("output.verification_failure_rolls_back", VerificationFailure); |
| 29 | yield return ("output.unavailable_verification_remains_unavailable", VerificationUnavailable); |
| 30 | yield return ("budget.count_actual_bytes_not_header", ActualBytes); |
| 31 | yield return ("budget.accumulate_entries_and_intermediate_work", IntermediateBudget); |
| 32 | yield return ("budget.swallowed_failure_cannot_commit", SwallowedFailure); |
| 33 | yield return ("cancel.before_engine_starts", PreCancelled); |
| 34 | yield return ("cancel.during_copy_prevents_publish", CancelDuringCopy); |
| 35 | yield return ("cancel.before_commit_prevents_publish", CancelBeforeCommit); |
| 36 | yield return ("job.observer_failure_does_not_skip_cleanup", ObserverFailure); |
| 37 | yield return ("job.cleanup_failure_is_not_success", CleanupFailure); |
| 38 | yield return ("password.cancel_without_reprompt", PasswordCancelled); |
| 39 | yield return ("password.disposed_after_success_and_failure", PasswordDisposed); |
| 40 | yield return ("password.attempt_limit_and_request_ids", PasswordAttempts); |
| 41 | yield return ("preview.cannot_use_extraction_output", PreviewRejectsWrite); |
| 42 | yield return ("fixtures.core_policy_and_original_preservation", ArchiveFixtures); |
| 43 | yield return ("password.concurrent_provider_and_waiting_state", ConcurrentPasswords); |
| 44 | yield return ("password.queued_cancel_discards_late_secret", QueuedPasswordCancellation); |
| 45 | yield return ("password.gate_released_after_failures", PasswordGateAfterFailures); |
| 46 | yield return ("password.consumer_can_request_again", PasswordConsumerReentry); |
| 47 | yield return ("job.initialization_failure_cleans_once", InitializationCleanup); |
| 48 | yield return ("job.precondition_rejection_keeps_output_ownership", RejectedOutputOwnership); |
| 49 | yield return ("job.cleanup_preserves_integrity_error", IntegrityCleanupFailure); |
| 50 | yield return ("job.cleanup_after_cancel_is_failed", CancellationCleanupFailure); |
| 51 | yield return ("output.late_cancel_preserves_published_result", LateCommitCancellation); |
| 52 | yield return ("job.terminal_event_waits_for_cleanup", DeferredCleanup); |
| 53 | yield return ("path.windows_and_linux_policy", () => Sync(PlatformNames)); |
| 54 | yield return ("output.case_distinction_by_os", PlatformCaseOutputs); |
| 55 | } |
| 56 | |
| 57 | private static Task Sync(Action check) |
| 58 | { |
| 59 | check(); |
| 60 | return Task.CompletedTask; |
| 61 | } |
| 62 | |
| 63 | private static void ValidPaths() |
| 64 | { |
| 65 | foreach (var name in new[] { "hello.txt", "한글/빈파일.txt", "a\\b.txt", ".hidden", "COM10.txt" }) |
| 66 | { |
| 67 | var segments = OutputPathPolicy.Validate(name); |
| 68 | Check.Equal(name.Replace('\\', '/'), string.Join('/', segments)); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | private static void UnsafePaths() |
| 73 | { |
| 74 | string[] names = [ |
| 75 | "", " ", "../escape.txt", "..\\escape.txt", "a/../../escape.txt", |
| 76 | "/absolute.txt", "\\absolute.txt", "C:\\escape.txt", "C:escape.txt", |
| 77 | "\\\\server\\share\\escape.txt", "\\\\?\\C:\\escape.txt", "\\\\.\\NUL", |
| 78 | "file:stream", "file::$DATA", "a//b", "./file", "folder/", "a/./b", |
| 79 | "name.", "name ", "NUL", "nul.txt", "CON .txt", "AUX", "PRN", |
| 80 | "CONIN$", "CONOUT$", "com1.txt", "LPT9", "COM¹", "LPT².txt", |
| 81 | "name\0.txt", "line\nfeed", "a<b", "a>b", "a\"b", "a|b", "a?b", "a*b", |
| 82 | "e\u0301.txt", new string('a', 256), new string('a', 4097) |
| 83 | ]; |
| 84 | foreach (var name in names) |
| 85 | { |
| 86 | var error = Check.Throws<ArchiveException>(() => OutputPathPolicy.Validate(name)); |
| 87 | Check.Equal(ArchiveError.UnsafePath, error.Code); |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | private static void BudgetBoundaries() |
| 92 | { |
| 93 | var budget = new JobBudget(Limits with { MaxEntries = 1, MaxProcessedBytes = 4, MaxOutputBytes = 3 }); |
| 94 | budget.AddEntry(default); |
| 95 | budget.ChargeProcessed(3, default); |
| 96 | budget.ChargeProcessed(1, default); |
| 97 | budget.ReserveOutput(3, default); |
| 98 | Check.Equal(new BudgetUsage(1, 4, 3), budget.Usage); |
| 99 | Check.Equal(ArchiveError.BudgetExceeded, |
| 100 | Check.Throws<ArchiveException>(() => budget.ChargeProcessed(1, default)).Code); |
| 101 | Check.Equal(new BudgetUsage(1, 4, 3), budget.Usage); |
| 102 | Check.Throws<ArchiveException>(() => budget.ChargeProcessed(0, default)); |
| 103 | |
| 104 | var entries = new JobBudget(Limits with { MaxEntries = 1 }); |
| 105 | entries.AddEntry(default); |
| 106 | Check.Throws<ArchiveException>(() => entries.AddEntry(default)); |
| 107 | var output = new JobBudget(Limits with { MaxOutputBytes = 1 }); |
| 108 | output.ReserveOutput(1, default); |
| 109 | Check.Throws<ArchiveException>(() => output.ReserveOutput(1, default)); |
| 110 | } |
| 111 | |
| 112 | private static void BudgetInvalidCharges() |
| 113 | { |
| 114 | Check.Throws<ArgumentOutOfRangeException>(() => new JobBudget(Limits with { MaxEntries = 0 })); |
| 115 | var budget = new JobBudget(Limits with { MaxProcessedBytes = long.MaxValue }); |
| 116 | Check.Throws<ArgumentOutOfRangeException>(() => budget.ChargeProcessed(-1, default)); |
| 117 | Check.Throws<ArgumentOutOfRangeException>(() => budget.ReserveOutput(-1, default)); |
| 118 | Check.Equal(new BudgetUsage(0, 0, 0), budget.Usage); |
| 119 | budget.ChargeProcessed(long.MaxValue, default); |
| 120 | Check.Throws<ArchiveException>(() => budget.ChargeProcessed(1, default)); |
| 121 | Check.Equal(long.MaxValue, budget.Usage.ProcessedBytes); |
| 122 | } |
| 123 | |
| 124 | private static void BudgetDeadline() |
| 125 | { |
| 126 | var clock = new ManualTimeProvider(); |
| 127 | var budget = new JobBudget(Limits with { MaxDuration = TimeSpan.FromSeconds(1) }, clock); |
| 128 | clock.Advance(TimeSpan.FromTicks(TimeSpan.TicksPerSecond - 1)); |
| 129 | budget.Check(default); |
| 130 | clock.Advance(TimeSpan.FromTicks(1)); |
| 131 | Check.Throws<ArchiveException>(() => budget.Check(default)); |
| 132 | } |
| 133 | |
| 134 | private static async Task ConcurrentBudget() |
| 135 | { |
| 136 | var budget = new JobBudget(Limits with { MaxProcessedBytes = 8 }); |
| 137 | var accepted = 0; |
| 138 | var rejected = 0; |
| 139 | await Task.WhenAll(Enumerable.Range(0, 16).Select(_ => Task.Run(() => |
| 140 | { |
| 141 | try |
| 142 | { |
| 143 | budget.ChargeProcessed(1, default); |
| 144 | Interlocked.Increment(ref accepted); |
| 145 | } |
| 146 | catch (ArchiveException error) when (error.Code == ArchiveError.BudgetExceeded) |
| 147 | { |
| 148 | Interlocked.Increment(ref rejected); |
| 149 | } |
| 150 | }))); |
| 151 | Check.Equal(8, accepted); |
| 152 | Check.Equal(8, rejected); |
| 153 | Check.Equal(8L, budget.Usage.ProcessedBytes); |
| 154 | } |
| 155 | |
| 156 | private static async Task WritableInput() |
| 157 | { |
| 158 | using var input = new MemoryStream(new byte[] { 1, 2, 3 }, true); |
| 159 | var engine = Stub(_ => Task.CompletedTask); |
| 160 | var output = new RecordingOutput(); |
| 161 | var result = await new ArchiveJob(Guid.NewGuid(), Limits).ExecuteAsync( |
| 162 | ArchiveAction.Extract, "zip", engine, [input], output, TestSecrets.None, null, default); |
| 163 | Check.Equal(ArchiveError.UnsupportedOperation, result.Error); |
| 164 | Check.Equal(0, engine.Calls); |
| 165 | Check.That(output.Disposed, "출력 정리가 누락됨"); |
| 166 | Check.That(input.ToArray().SequenceEqual(new byte[] { 1, 2, 3 }), "입력이 변경됨"); |
| 167 | } |
| 168 | |
| 169 | private static async Task UnavailableEngineFails() |
| 170 | { |
| 171 | var run = await Execute(new UnavailableEngine()); |
| 172 | Failed(run, ArchiveError.EngineUnavailable); |
| 173 | } |
| 174 | |
| 175 | private static async Task UnavailableOutputFails() |
| 176 | { |
| 177 | using var input = new MemoryStream(new byte[] { 1 }, false); |
| 178 | var result = await new ArchiveJob(Guid.NewGuid(), Limits).ExecuteAsync( |
| 179 | ArchiveAction.Extract, "zip", Stub(context => Write(context, "a.txt", [1])), |
| 180 | [input], new UnavailableOutput(), TestSecrets.None, null, default); |
| 181 | Check.Equal(JobState.Failed, result.State); |
| 182 | Check.Equal(ArchiveError.OutputUnavailable, result.Error); |
| 183 | } |
| 184 | |
| 185 | private static async Task SingleUse() |
| 186 | { |
| 187 | var job = new ArchiveJob(Guid.NewGuid(), Limits); |
| 188 | using var input = new MemoryStream(new byte[] { 1 }, false); |
| 189 | var engine = Stub(_ => Task.CompletedTask); |
| 190 | await job.ExecuteAsync(ArchiveAction.List, "zip", engine, [input], |
| 191 | new RecordingOutput(), TestSecrets.None, null, default); |
| 192 | await Check.ThrowsAsync<InvalidOperationException>(async () => |
| 193 | await job.ExecuteAsync(ArchiveAction.List, "zip", engine, [input], |
| 194 | new RecordingOutput(), TestSecrets.None, null, default)); |
| 195 | Check.Equal(1, engine.Calls); |
| 196 | } |
| 197 | |
| 198 | private static async Task UnsafeWrite() |
| 199 | { |
| 200 | var run = await Execute(Stub(context => Write(context, "../escape.txt", [1]))); |
| 201 | Failed(run, ArchiveError.UnsafePath); |
| 202 | Check.Equal(0, run.Output.CreateCalls); |
| 203 | } |
| 204 | |
| 205 | private static async Task ArchiveLinks() |
| 206 | { |
| 207 | foreach (var kind in new[] { EntryKind.SymbolicLink, EntryKind.HardLink, EntryKind.Other }) |
| 208 | { |
| 209 | var run = await Execute(Stub(context => Write(context, "link", [1], kind: kind))); |
| 210 | Failed(run, ArchiveError.UnsupportedEntry); |
| 211 | Check.Equal(0, run.Output.CreateCalls); |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | private static async Task OutputCollisions() |
| 216 | { |
| 217 | foreach (var pair in new[] |
| 218 | { |
| 219 | ("file", "file/child"), ("file/child", "file") |
| 220 | }) |
| 221 | { |
| 222 | var run = await Execute(Stub(async context => |
| 223 | { |
| 224 | await Write(context, pair.Item1, [1]); |
| 225 | await Write(context, pair.Item2, [2]); |
| 226 | })); |
| 227 | Failed(run, ArchiveError.OutputConflict); |
| 228 | Check.Equal(1, run.Output.CreateCalls); |
| 229 | Check.That(run.Result.Entries.All(entry => entry.Outcome == EntryOutcome.Failed), |
| 230 | "충돌 후 임시 출력을 성공으로 표시함"); |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | private static async Task ExistingConflict() |
| 235 | { |
| 236 | var output = new RecordingOutput { CreateError = ArchiveError.OutputConflict }; |
| 237 | var run = await Execute(Stub(context => Write(context, "existing.txt", [1])), output: output); |
| 238 | Failed(run, ArchiveError.OutputConflict); |
| 239 | } |
| 240 | |
| 241 | private static async Task VerificationFailure() |
| 242 | { |
| 243 | var run = await Execute(Stub(async context => |
| 244 | { |
| 245 | await Write(context, "good.txt", [1]); |
| 246 | await Write(context, "bad.txt", [2], verification: VerificationState.Failed); |
| 247 | })); |
| 248 | Failed(run, ArchiveError.IntegrityFailure); |
| 249 | Check.Equal(VerificationState.Failed, run.Result.Entries[1].Verification); |
| 250 | Check.That(run.Result.Entries.All(entry => entry.Outcome == EntryOutcome.Failed), |
| 251 | "검증 실패 후 게시하지 않은 출력을 성공으로 표시함"); |
| 252 | } |
| 253 | |
| 254 | private static async Task VerificationUnavailable() |
| 255 | { |
| 256 | var run = await Execute(Stub(context => Write(context, "file.txt", [1], |
| 257 | verification: VerificationState.Unavailable))); |
| 258 | Check.Equal(JobState.Completed, run.Result.State); |
| 259 | Check.Equal(EntryOutcome.Extracted, run.Result.Entries.Single().Outcome); |
| 260 | Check.Equal(VerificationState.Unavailable, run.Result.Entries.Single().Verification); |
| 261 | Check.Equal(1, run.Output.CommitCalls); |
| 262 | } |
| 263 | |
| 264 | private static async Task ActualBytes() |
| 265 | { |
| 266 | var run = await Execute(Stub(async context => |
| 267 | { |
| 268 | using var stream = new ChunkedStream([1, 2, 3, 4, 5]); |
| 269 | await context.WriteEntryAsync(new("one", "tiny.txt", EntryKind.File, 0), stream, |
| 270 | _ => ValueTask.FromResult(VerificationState.Passed)); |
| 271 | }), limits: Limits with { MaxProcessedBytes = 4, MaxOutputBytes = 4 }); |
| 272 | Failed(run, ArchiveError.BudgetExceeded); |
| 273 | Check.Equal(4L, run.Events[^1].ProcessedBytes); |
| 274 | Check.Equal(4, run.Output.Staged["tiny.txt"].ToArray().Length); |
| 275 | } |
| 276 | |
| 277 | private static async Task IntermediateBudget() |
| 278 | { |
| 279 | var run = await Execute(Stub(async context => |
| 280 | { |
| 281 | context.Budget.ChargeProcessed(2, context.CancellationToken); |
| 282 | await Write(context, "one.txt", [1, 2]); |
| 283 | await Write(context, "two.txt", [3, 4]); |
| 284 | }), limits: Limits with { MaxProcessedBytes = 5 }); |
| 285 | Failed(run, ArchiveError.BudgetExceeded); |
| 286 | |
| 287 | var entries = await Execute(Stub(async context => |
| 288 | { |
| 289 | await context.ListEntryAsync(new("one", "one", EntryKind.File, 0)); |
| 290 | await context.ListEntryAsync(new("two", "two", EntryKind.File, 0)); |
| 291 | }), limits: Limits with { MaxEntries = 1 }, action: ArchiveAction.List); |
| 292 | Failed(entries, ArchiveError.BudgetExceeded); |
| 293 | } |
| 294 | |
| 295 | private static async Task SwallowedFailure() |
| 296 | { |
| 297 | var run = await Execute(Stub(async context => |
| 298 | { |
| 299 | await Write(context, "good.txt", [1]); |
| 300 | try |
| 301 | { |
| 302 | await Write(context, "../escape.txt", [2]); |
| 303 | } |
| 304 | catch (ArchiveException) |
| 305 | { |
| 306 | // 어댑터가 오류를 삼켜도 앞선 출력을 게시하지 않아야 함. |
| 307 | } |
| 308 | })); |
| 309 | Failed(run, ArchiveError.UnsafePath); |
| 310 | } |
| 311 | |
| 312 | private static async Task PreCancelled() |
| 313 | { |
| 314 | using var cancellation = new CancellationTokenSource(); |
| 315 | cancellation.Cancel(); |
| 316 | var engine = Stub(_ => Task.CompletedTask); |
| 317 | var run = await Execute(engine, token: cancellation.Token); |
| 318 | Cancelled(run); |
| 319 | Check.Equal(0, engine.Calls); |
| 320 | } |
| 321 | |
| 322 | private static async Task CancelDuringCopy() |
| 323 | { |
| 324 | using var cancellation = new CancellationTokenSource(); |
| 325 | var run = await Execute(Stub(async context => |
| 326 | { |
| 327 | using var stream = new ChunkedStream([1, 2, 3], cancellation.Cancel); |
| 328 | await context.WriteEntryAsync(new("one", "file.txt", EntryKind.File, 3), stream, |
| 329 | _ => ValueTask.FromResult(VerificationState.Passed)); |
| 330 | }), token: cancellation.Token); |
| 331 | Cancelled(run); |
| 332 | Check.Equal(0, run.Output.Staged["file.txt"].ToArray().Length); |
| 333 | } |
| 334 | |
| 335 | private static async Task CancelBeforeCommit() |
| 336 | { |
| 337 | using var cancellation = new CancellationTokenSource(); |
| 338 | var output = new RecordingOutput { BeforeCommit = cancellation.Cancel }; |
| 339 | var run = await Execute(Stub(context => Write(context, "file.txt", [1])), |
| 340 | output: output, token: cancellation.Token); |
| 341 | Cancelled(run); |
| 342 | } |
| 343 | |
| 344 | private static async Task ObserverFailure() |
| 345 | { |
| 346 | using var input = new MemoryStream(new byte[] { 1 }, false); |
| 347 | var output = new RecordingOutput(); |
| 348 | var result = await new ArchiveJob(Guid.NewGuid(), Limits).ExecuteAsync( |
| 349 | ArchiveAction.Extract, "zip", Stub(context => Write(context, "file.txt", [1])), |
| 350 | [input], output, TestSecrets.None, |
| 351 | new InlineProgress(_ => throw new InvalidOperationException("테스트 관찰자 오류")), default); |
| 352 | Check.Equal(JobState.Completed, result.State); |
| 353 | Check.That(output.Disposed, "관찰자 실패로 출력 정리가 누락됨"); |
| 354 | } |
| 355 | |
| 356 | private static async Task CleanupFailure() |
| 357 | { |
| 358 | var run = await Execute(Stub(_ => Task.CompletedTask), |
| 359 | output: new RecordingOutput { FailDispose = true }); |
| 360 | Failed(run, ArchiveError.OutputUnavailable); |
| 361 | } |
| 362 | |
| 363 | private static async Task PasswordCancelled() |
| 364 | { |
| 365 | var requests = 0; |
| 366 | var consumed = false; |
| 367 | var run = await Execute(Stub(async context => |
| 368 | { |
| 369 | await context.UsePasswordAsync((secret, token) => |
| 370 | { |
| 371 | consumed = true; |
| 372 | return ValueTask.FromResult(0); |
| 373 | }); |
| 374 | }), passwords: (challenge, token) => |
| 375 | { |
| 376 | requests++; |
| 377 | return ValueTask.FromResult<SecureString?>(null); |
| 378 | }); |
| 379 | Cancelled(run); |
| 380 | Check.Equal(1, requests); |
| 381 | Check.That(!consumed, "취소된 암호를 소비함"); |
| 382 | Check.That(run.Events.Any(value => value.State == JobState.WaitingForPassword), "암호 대기 상태가 없음"); |
| 383 | } |
| 384 | |
| 385 | private static async Task PasswordDisposed() |
| 386 | { |
| 387 | foreach (var fail in new[] { false, true }) |
| 388 | { |
| 389 | var secret = TestSecrets.Create(); |
| 390 | var expectedLength = secret.Length; |
| 391 | var run = await Execute(Stub(async context => |
| 392 | { |
| 393 | await context.UsePasswordAsync((value, token) => |
| 394 | { |
| 395 | Check.Equal(expectedLength, value.Length); |
| 396 | return fail |
| 397 | ? ValueTask.FromException<int>(new IOException("테스트 암호 소비 실패")) |
| 398 | : ValueTask.FromResult(value.Length); |
| 399 | }); |
| 400 | }), passwords: (challenge, token) => ValueTask.FromResult<SecureString?>(secret)); |
| 401 | Check.Equal(fail ? JobState.Failed : JobState.Completed, run.Result.State); |
| 402 | Check.Throws<ObjectDisposedException>(() => { _ = secret.Length; }); |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | private static async Task PasswordAttempts() |
| 407 | { |
| 408 | var challenges = new List<PasswordChallenge>(); |
| 409 | var run = await Execute(Stub(async context => |
| 410 | { |
| 411 | for (var index = 0; index < 3; index++) |
| 412 | { |
| 413 | await context.UsePasswordAsync((secret, token) => ValueTask.FromResult(secret.Length)); |
| 414 | } |
| 415 | }), limits: Limits with { MaxPasswordAttempts = 2 }, passwords: (challenge, token) => |
| 416 | { |
| 417 | challenges.Add(challenge); |
| 418 | return ValueTask.FromResult<SecureString?>(TestSecrets.Create()); |
| 419 | }); |
| 420 | Failed(run, ArchiveError.PasswordAttemptsExceeded); |
| 421 | Check.Equal(2, challenges.Count); |
| 422 | Check.Equal(1, challenges[0].Attempt); |
| 423 | Check.Equal(2, challenges[1].Attempt); |
| 424 | Check.That(challenges.All(value => value.JobId == run.Result.JobId), "다른 작업에 암호를 요청함"); |
| 425 | Check.Equal(2, challenges.Select(value => value.RequestId).Distinct().Count()); |
| 426 | } |
| 427 | |
| 428 | private static async Task PreviewRejectsWrite() |
| 429 | { |
| 430 | var run = await Execute(Stub(context => Write(context, "preview.html", [1])), |
| 431 | action: ArchiveAction.Preview); |
| 432 | Failed(run, ArchiveError.UnsupportedOperation); |
| 433 | Check.Equal(0, run.Output.CreateCalls); |
| 434 | } |
| 435 | |
| 436 | private async Task ArchiveFixtures() |
| 437 | { |
| 438 | var scenarios = new (string File, ArchiveError Error)[] |
| 439 | { |
| 440 | ("normal.zip", ArchiveError.None), |
| 441 | ("traversal.zip", ArchiveError.UnsafePath), |
| 442 | ("backslash-traversal.zip", OperatingSystem.IsWindows() ? ArchiveError.UnsafePath : ArchiveError.None), |
| 443 | ("case-collision.zip", OperatingSystem.IsWindows() ? ArchiveError.OutputConflict : ArchiveError.None), |
| 444 | ("parent-collision.zip", ArchiveError.OutputConflict), |
| 445 | ("symlink.zip", ArchiveError.UnsupportedEntry), |
| 446 | ("truncated.zip", ArchiveError.EngineFailure) |
| 447 | }; |
| 448 | foreach (var (name, expected) in scenarios) |
| 449 | { |
| 450 | var folder = Path.Combine(sandbox, Guid.NewGuid().ToString("N")); |
| 451 | Directory.CreateDirectory(folder); |
| 452 | var source = Path.Combine(folder, "source.zip"); |
| 453 | File.Copy(Path.Combine(root, "tests", "security", "fixtures", name), source); |
| 454 | var sentinel = Path.Combine(folder, "sentinel.txt"); |
| 455 | await File.WriteAllTextAsync(sentinel, "원본 보존 검사"); |
| 456 | var before = SHA256.HashData(await File.ReadAllBytesAsync(source)); |
| 457 | var output = new RecordingOutput(); |
| 458 | var engine = new EngineStub(async (inputs, context, token) => |
| 459 | { |
| 460 | // BCL ZIP 판독은 테스트 입력 공급용임. 실제 엔진의 지원 또는 CRC 검증으로 계산하지 않음. |
| 461 | using var zip = new ZipArchive(inputs[0], ZipArchiveMode.Read, true); |
| 462 | var index = 0; |
| 463 | foreach (var entry in zip.Entries) |
| 464 | { |
| 465 | var kind = ((entry.ExternalAttributes >> 16) & 0xF000) == 0xA000 |
| 466 | ? EntryKind.SymbolicLink : EntryKind.File; |
| 467 | using var decoded = entry.Open(); |
| 468 | await context.WriteEntryAsync(new((index++).ToString(), entry.FullName, kind, entry.Length), |
| 469 | decoded, _ => ValueTask.FromResult(VerificationState.Unavailable)); |
| 470 | } |
| 471 | }); |
| 472 | await using (var input = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read)) |
| 473 | { |
| 474 | var result = await new ArchiveJob(Guid.NewGuid(), Limits).ExecuteAsync( |
| 475 | ArchiveAction.Extract, "zip", engine, [input], output, TestSecrets.None, null, default); |
| 476 | Check.Equal(expected, result.Error); |
| 477 | Check.Equal(expected == ArchiveError.None ? JobState.Completed : JobState.Failed, result.State); |
| 478 | Check.That(input.CanRead && !input.CanWrite, "입력 수명 또는 읽기 전용 계약이 깨짐"); |
| 479 | } |
| 480 | |
| 481 | var after = SHA256.HashData(await File.ReadAllBytesAsync(source)); |
| 482 | Check.That(before.SequenceEqual(after), "원본 해시가 변경됨"); |
| 483 | Check.Equal("원본 보존 검사", await File.ReadAllTextAsync(sentinel)); |
| 484 | Check.Equal(2, Directory.GetFileSystemEntries(folder).Length); |
| 485 | Check.That(output.Disposed, "샘플 처리 후 정리가 누락됨"); |
| 486 | if (expected == ArchiveError.None) |
| 487 | { |
| 488 | if (name == "normal.zip") |
| 489 | { |
| 490 | Check.Equal(2, output.Published.Count); |
| 491 | Check.That(output.Published["hello.txt"].SequenceEqual("zipelo-safe-test-payload\n"u8.ToArray()), |
| 492 | "정상 출력이 원문과 다름"); |
| 493 | Check.Equal(0, output.Published["한글/빈파일.txt"].Length); |
| 494 | } |
| 495 | else if (name == "case-collision.zip") |
| 496 | { |
| 497 | Check.Equal(2, output.Published.Count); |
| 498 | Check.That(output.Published["Readme.txt"].SequenceEqual("first"u8.ToArray()), "첫 항목이 변경됨"); |
| 499 | Check.That(output.Published["README.TXT"].SequenceEqual("second"u8.ToArray()), "둘째 항목이 변경됨"); |
| 500 | } |
| 501 | else |
| 502 | { |
| 503 | Check.Equal(1, output.Published.Count); |
| 504 | Check.That(output.Published["..\\escape.txt"].SequenceEqual("zipelo-safe-test-payload\n"u8.ToArray()), |
| 505 | "Linux 역슬래시 파일명이 경로 구분자로 해석됨"); |
| 506 | } |
| 507 | } |
| 508 | else |
| 509 | { |
| 510 | Check.Equal(0, output.CommitCalls); |
| 511 | Check.Equal(0, output.Published.Count); |
| 512 | } |
| 513 | } |
| 514 | } |
| 515 | |
| 516 | private static EngineStub Stub(Func<EngineContext, Task> execute) => |
| 517 | new((inputs, context, token) => execute(context)); |
| 518 | |
| 519 | private static async Task Write( |
| 520 | EngineContext context, |
| 521 | string name, |
| 522 | byte[] content, |
| 523 | EntryKind kind = EntryKind.File, |
| 524 | VerificationState verification = VerificationState.Passed) |
| 525 | { |
| 526 | using var decoded = new MemoryStream(content, false); |
| 527 | await context.WriteEntryAsync(new(Guid.NewGuid().ToString("N"), name, kind, content.Length), |
| 528 | decoded, _ => ValueTask.FromResult(verification)); |
| 529 | } |
| 530 | |
| 531 | private sealed record Run(JobResult Result, RecordingOutput Output, List<JobEvent> Events); |
| 532 | |
| 533 | private static async Task<Run> Execute( |
| 534 | IArchiveEngine engine, |
| 535 | RecordingOutput? output = null, |
| 536 | JobLimits? limits = null, |
| 537 | CancellationToken token = default, |
| 538 | PasswordProvider? passwords = null, |
| 539 | ArchiveAction action = ArchiveAction.Extract, |
| 540 | Action<JobEvent>? observe = null) |
| 541 | { |
| 542 | using var input = new MemoryStream(new byte[] { 1, 2, 3 }, false); |
| 543 | var events = new List<JobEvent>(); |
| 544 | output ??= new RecordingOutput(); |
| 545 | var result = await new ArchiveJob(Guid.NewGuid(), limits ?? Limits).ExecuteAsync( |
| 546 | action, "zip", engine, [input], output, passwords ?? TestSecrets.None, |
| 547 | new InlineProgress(value => |
| 548 | { |
| 549 | events.Add(value); |
| 550 | observe?.Invoke(value); |
| 551 | }), token); |
| 552 | Check.That(output.Disposed, "최종 결과 전에 출력 정리가 수행되지 않음"); |
| 553 | Check.Equal(result.State, events[^1].State); |
| 554 | Check.That(events.Select(value => value.Sequence).SequenceEqual( |
| 555 | Enumerable.Range(1, events.Count).Select(value => (long)value)), "이벤트 순서가 잘못됨"); |
| 556 | Check.That(events.All(value => value.JobId == result.JobId), "이벤트 작업 ID가 잘못됨"); |
| 557 | return new(result, output, events); |
| 558 | } |
| 559 | |
| 560 | private static void Failed(Run run, ArchiveError error) |
| 561 | { |
| 562 | Check.Equal(JobState.Failed, run.Result.State); |
| 563 | Check.Equal(error, run.Result.Error); |
| 564 | Check.Equal(0, run.Output.CommitCalls); |
| 565 | Check.Equal(0, run.Output.Published.Count); |
| 566 | } |
| 567 | |
| 568 | private static void Cancelled(Run run) |
| 569 | { |
| 570 | Check.Equal(JobState.Cancelled, run.Result.State); |
| 571 | Check.Equal(ArchiveError.Cancelled, run.Result.Error); |
| 572 | Check.Equal(0, run.Output.CommitCalls); |
| 573 | Check.Equal(0, run.Output.Published.Count); |
| 574 | } |
| 575 | } |