team-ljyzipelo

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