| 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 => TestWorkerLaunch.Worker; |
| 14 | |
| 15 | public IEnumerable<(string Name, Func<Task> Run)> Cases() |
| 16 | { |
| 17 | yield return ("extract.stored_contents_hashes_and_source", () => Normal("normal-stored.zip")); |
| 18 | yield return ("extract.deflated_contents_hashes_and_source", () => Normal("normal-deflated.zip")); |
| 19 | foreach (var name in new[] { "traversal", "absolute-posix", "absolute-unc" }) |
| 20 | { |
| 21 | yield return ($"extract.reject_{name}", () => Reject(name + ".zip", ArchiveError.UnsafePath)); |
| 22 | } |
| 23 | yield return ("extract.backslash_policy_by_os", () => NamesByOs("backslash-traversal.zip", |
| 24 | ArchiveError.UnsafePath, new Dictionary<string, byte[]> { ["..\\escape.txt"] = Payload })); |
| 25 | yield return ("extract.drive_name_policy_by_os", () => NamesByOs("absolute-drive.zip", |
| 26 | ArchiveError.UnsafePath, new Dictionary<string, byte[]> { ["C:/escape.txt"] = Payload })); |
| 27 | foreach (var name in new[] { "duplicate", "file-before-child", "child-before-file" }) |
| 28 | { |
| 29 | yield return ($"extract.reject_{name}", () => Reject(name + ".zip", ArchiveError.OutputConflict)); |
| 30 | } |
| 31 | yield return ("extract.case_policy_by_os", () => NamesByOs("case-distinct.zip", ArchiveError.OutputConflict, |
| 32 | new Dictionary<string, byte[]> { ["Readme.txt"] = "first"u8.ToArray(), ["README.TXT"] = "second"u8.ToArray() })); |
| 33 | yield return ("extract.legal_linux_names", () => NamesByOs("linux-names.zip", ArchiveError.UnsafePath, |
| 34 | new Dictionary<string, byte[]> { ["CON"] = "one"u8.ToArray(), ["name:stream"] = "two"u8.ToArray() })); |
| 35 | foreach (var name in new[] { "symlink", "unix-hardlink", "special-fifo" }) |
| 36 | { |
| 37 | yield return ($"extract.reject_{name}", () => Reject(name + ".zip", ArchiveError.UnsupportedEntry)); |
| 38 | } |
| 39 | foreach (var name in new[] { "bad-payload-crc", "bad-header-crc", "length-smaller", "length-larger", |
| 40 | "local-central-length", "truncated" }) |
| 41 | { |
| 42 | yield return ($"extract.reject_{name}", () => Reject(name + ".zip", ArchiveError.IntegrityFailure)); |
| 43 | } |
| 44 | yield return ("extract.cumulative_output_budget", () => Budget("output")); |
| 45 | yield return ("extract.cumulative_processed_budget", () => Budget("processed")); |
| 46 | yield return ("extract.cumulative_entry_budget", () => Budget("entries")); |
| 47 | yield return ("extract.cancel_before_read", PreCancelled); |
| 48 | yield return ("extract.cancel_during_input_copy", CancelInput); |
| 49 | yield return ("folder.platform_contract", FolderPlatform); |
| 50 | yield return ("folder.new_folder_contents_hashes_and_source", PublishFolder); |
| 51 | yield return ("folder.existing_folder_preserved_and_temporary_cleanup", () => FolderConflict(true)); |
| 52 | yield return ("folder.existing_source_file_preserved_and_temporary_cleanup", () => FolderConflict(false)); |
| 53 | yield return ("folder.precancel_preserves_originals", FolderPreCancelled); |
| 54 | yield return ("folder.tampered_bytes_not_published", FolderRejectsTamperedBytes); |
| 55 | yield return ("folder.failed_extraction_not_published", FolderRejectsFailedExtraction); |
| 56 | yield return ("folder.reject_parent_symlink", () => FolderRejectsLink(true)); |
| 57 | yield return ("folder.reject_leaf_symlink", () => FolderRejectsLink(false)); |
| 58 | yield return ("folder.concurrent_same_name_one_winner", FolderConcurrentPublish); |
| 59 | } |
| 60 | |
| 61 | private static byte[] Payload => "zipelo-extraction-content\n"u8.ToArray(); |
| 62 | private string FixturePath(string name) => Path.Combine(root, "tests", "extraction", "fixtures", name); |
| 63 | |
| 64 | private async Task<ZipWorkerResult> Extract(string name, JobLimits? limits = null) |
| 65 | { |
| 66 | var path = FixturePath(name); |
| 67 | var before = SHA256.HashData(await File.ReadAllBytesAsync(path)); |
| 68 | ZipWorkerResult result; |
| 69 | await using (var input = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) |
| 70 | { |
| 71 | result = await Worker.ExtractAsync(Guid.NewGuid(), input, limits ?? Limits, default); |
| 72 | Check.That(input.CanRead && !input.CanWrite, "해제 요청이 원본 스트림 소유권을 변경함"); |
| 73 | } |
| 74 | var after = SHA256.HashData(await File.ReadAllBytesAsync(path)); |
| 75 | Check.That(before.SequenceEqual(after), "해제 요청이 원본 ZIP을 변경함"); |
| 76 | return result; |
| 77 | } |
| 78 | |
| 79 | private static IReadOnlyList<ZipExtractedEntry> Successful(ZipWorkerResult result) |
| 80 | { |
| 81 | Check.Equal(JobState.Completed, result.Job.State); |
| 82 | Check.Equal(ArchiveError.None, result.Job.Error); |
| 83 | Check.That(result.CreatedZip is null, "해제 요청이 생성 ZIP을 반환함"); |
| 84 | var items = result.ExtractedEntries ?? throw new InvalidOperationException(); |
| 85 | Check.Equal(items.Count, result.Job.Entries.Count); |
| 86 | for (var index = 0; index < items.Count; index++) |
| 87 | { |
| 88 | Check.Equal(items[index].Entry, result.Job.Entries[index].Entry); |
| 89 | Check.Equal(EntryOutcome.Staged, result.Job.Entries[index].Outcome); |
| 90 | Check.Equal(VerificationState.Passed, result.Job.Entries[index].Verification); |
| 91 | Check.Equal(ArchiveError.None, result.Job.Entries[index].Error); |
| 92 | Check.Equal((long?)items[index].Content.LongLength, items[index].Entry.DeclaredSize); |
| 93 | } |
| 94 | return items; |
| 95 | } |
| 96 | |
| 97 | private static void Failure(ZipWorkerResult result, ArchiveError error) |
| 98 | { |
| 99 | Check.Equal(error, result.Job.Error); |
| 100 | Check.Equal(error == ArchiveError.Cancelled ? JobState.Cancelled : JobState.Failed, result.Job.State); |
| 101 | Check.That(result.CreatedZip is null && result.ExtractedEntries is null, |
| 102 | "실패나 취소 뒤 부분 해제 결과를 반환함"); |
| 103 | } |
| 104 | |
| 105 | private async Task Normal(string name) |
| 106 | { |
| 107 | var items = Successful(await Extract(name)); |
| 108 | Check.Equal(4, items.Count); |
| 109 | var directory = items.Single(item => item.Entry.Kind == EntryKind.Directory); |
| 110 | Check.Equal("nested", directory.Entry.Name); |
| 111 | Check.Equal(0, directory.Content.Length); |
| 112 | using var manifest = JsonDocument.Parse(await File.ReadAllTextAsync( |
| 113 | Path.Combine(root, "tests", "extraction", "fixtures.json"))); |
| 114 | var expected = manifest.RootElement.GetProperty("normal_files"); |
| 115 | foreach (var item in items.Where(item => item.Entry.Kind == EntryKind.File)) |
| 116 | { |
| 117 | var entry = expected.GetProperty(item.Entry.Name); |
| 118 | Check.Equal(entry.GetProperty("bytes").GetInt32(), item.Content.Length); |
| 119 | Check.Equal(entry.GetProperty("sha256").GetString(), Convert.ToHexString(SHA256.HashData(item.Content)).ToLowerInvariant()); |
| 120 | } |
| 121 | Check.Equal(3, items.Count(item => item.Entry.Kind == EntryKind.File)); |
| 122 | } |
| 123 | |
| 124 | private async Task Reject(string name, ArchiveError error) => Failure(await Extract(name), error); |
| 125 | |
| 126 | private async Task NamesByOs(string name, ArchiveError windowsError, IReadOnlyDictionary<string, byte[]> expected) |
| 127 | { |
| 128 | var result = await Extract(name); |
| 129 | if (OperatingSystem.IsWindows()) { Failure(result, windowsError); return; } |
| 130 | var items = Successful(result); |
| 131 | Check.Equal(expected.Count, items.Count); |
| 132 | var names = new HashSet<string>(StringComparer.Ordinal); |
| 133 | foreach (var item in items) |
| 134 | { |
| 135 | Check.That(names.Add(item.Entry.Name), "대소문자가 다른 파일을 합침"); |
| 136 | Check.That(expected[item.Entry.Name].SequenceEqual(item.Content), "Linux 이름이나 내용을 변경함"); |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | private async Task Budget(string kind) |
| 141 | { |
| 142 | var inputBytes = new FileInfo(FixturePath("cumulative.zip")).Length; |
| 143 | var exact = Limits with { MaxEntries = 2, MaxOutputBytes = 16, MaxProcessedBytes = inputBytes + 16 }; |
| 144 | Check.Equal(2, Successful(await Extract("cumulative.zip", exact)).Count); |
| 145 | var tooSmall = kind switch |
| 146 | { |
| 147 | "output" => exact with { MaxOutputBytes = 15 }, |
| 148 | "processed" => exact with { MaxProcessedBytes = inputBytes + 15 }, |
| 149 | "entries" => exact with { MaxEntries = 1 }, |
| 150 | _ => throw new InvalidOperationException() |
| 151 | }; |
| 152 | Failure(await Extract("cumulative.zip", tooSmall), ArchiveError.BudgetExceeded); |
| 153 | } |
| 154 | |
| 155 | private static async Task PreCancelled() |
| 156 | { |
| 157 | using var cancellation = new CancellationTokenSource(); |
| 158 | cancellation.Cancel(); |
| 159 | using var input = new MemoryStream(Payload, false); |
| 160 | Failure(await Worker.ExtractAsync(Guid.NewGuid(), input, Limits, cancellation.Token), ArchiveError.Cancelled); |
| 161 | Check.Equal(0L, input.Position); |
| 162 | Check.That(input.CanRead, "사전 취소로 호출자의 스트림을 닫음"); |
| 163 | } |
| 164 | |
| 165 | private static async Task CancelInput() |
| 166 | { |
| 167 | using var input = new GatedInput(); |
| 168 | using var cancellation = new CancellationTokenSource(); |
| 169 | var operation = Worker.ExtractAsync(Guid.NewGuid(), input, Limits, cancellation.Token); |
| 170 | try |
| 171 | { |
| 172 | await input.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); |
| 173 | cancellation.Cancel(); |
| 174 | Failure(await operation.WaitAsync(TimeSpan.FromSeconds(5)), ArchiveError.Cancelled); |
| 175 | Check.That(input.CanRead, "입력 복사 취소로 호출자의 스트림을 닫음"); |
| 176 | } |
| 177 | finally |
| 178 | { |
| 179 | cancellation.Cancel(); |
| 180 | await operation.WaitAsync(TimeSpan.FromSeconds(5)); |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | private sealed class GatedInput : MemoryStream |
| 185 | { |
| 186 | public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); |
| 187 | public GatedInput() : base(Payload, false) { } |
| 188 | public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken token = default) |
| 189 | { |
| 190 | Entered.TrySetResult(); |
| 191 | await Task.Delay(Timeout.Infinite, token); |
| 192 | return 0; |
| 193 | } |
| 194 | } |
| 195 | } |