team-ljyzipelo

공개

USTAR 순차 검증과 선택 바이트 처리를 추가함

작성자
시로사키 하나
작성 시각
커밋
eb02cd0bade47333fc04e39da03875e51aace4f4
부모
cc39e89
이 시점의 파일 보기

변경된 파일 4개

+702-0
추가src/Zipelo.Worker/Tar/UstarReader.cs+259-0
@@ -0,0 +1,259 @@
1추가: using System.Globalization;
2추가: using System.Security.Cryptography;
3추가: using System.Text;
4추가: using Zipelo.Core;
5추가:
6추가: namespace Zipelo.Worker.Tar;
7추가:
8추가: internal sealed record UstarLimits(JobLimits Job, long MaxInputBytes, long MaxMetadataBytes);
9추가: internal sealed record UstarResult(IReadOnlyList<ArchiveEntry> Entries, BudgetUsage Usage,
10추가: string InputSha256, VerificationState ContentVerification);
11추가:
12추가: // 수신기는 청크를 복사하거나 즉시 소비함. 성공 반환 전에는 게시하지 않으며 실패 시 전부 폐기함.
13추가: internal delegate ValueTask UstarSink(ArchiveEntry entry, ReadOnlyMemory<byte> bytes, CancellationToken token);
14추가:
15추가: // 입력은 호출자가 독점 보유한 seek 가능 스트림임. 입력과 수신기를 닫지 않음.
16추가: internal sealed class UstarReader
17추가: {
18추가: internal const int ChunkSize = 64 * 1024;
19추가: internal const long InputCap = 16 * 1024 * 1024;
20추가: internal const long MetadataCap = 1024 * 1024;
21추가: private const int BlockSize = 512;
22추가: private static readonly UTF8Encoding Utf8 = new(false, true);
23추가: private readonly JobBudget budget;
24추가: private readonly long inputLimit;
25추가: private readonly long metadataLimit;
26추가: private readonly FileNamePolicy policy;
27추가: private int used;
28추가:
29추가: internal UstarReader(UstarLimits limits, FileNamePolicy policy, TimeProvider? time = null)
30추가: {
31추가: ArgumentNullException.ThrowIfNull(limits);
32추가: ArgumentNullException.ThrowIfNull(limits.Job);
33추가: if (limits.MaxInputBytes <= 0 || limits.MaxMetadataBytes <= 0)
34추가: {
35추가: throw new ArgumentOutOfRangeException(nameof(limits));
36추가: }
37추가: _ = OutputPathPolicy.Comparer(policy);
38추가: this.policy = policy;
39추가: inputLimit = Math.Min(limits.MaxInputBytes, InputCap);
40추가: metadataLimit = Math.Min(limits.MaxMetadataBytes, MetadataCap);
41추가: budget = new JobBudget(limits.Job with
42추가: {
43추가: MaxEntries = Math.Min(limits.Job.MaxEntries, 1024),
44추가: MaxProcessedBytes = Math.Min(limits.Job.MaxProcessedBytes, 128L * 1024 * 1024),
45추가: MaxOutputBytes = Math.Min(limits.Job.MaxOutputBytes, 16L * 1024 * 1024),
46추가: MaxDuration = limits.Job.MaxDuration < TimeSpan.FromMinutes(5)
47추가: ? limits.Job.MaxDuration : TimeSpan.FromMinutes(5)
48추가: }, time);
49추가: }
50추가:
51추가: // 선택은 검증 완료된 목록의 순번 ID로 고정함. 빈 선택은 목록만 반환함.
52추가: internal async Task<UstarResult> ReadAsync(Stream input,
53추가: Func<IReadOnlyList<ArchiveEntry>, IReadOnlyCollection<string>> select,
54추가: UstarSink sink, CancellationToken token)
55추가: {
56추가: ArgumentNullException.ThrowIfNull(input);
57추가: ArgumentNullException.ThrowIfNull(select);
58추가: ArgumentNullException.ThrowIfNull(sink);
59추가: if (Interlocked.Exchange(ref used, 1) != 0) { throw new InvalidOperationException(); }
60추가: budget.Check(token);
61추가: if (!input.CanRead || !input.CanSeek) { throw new ArgumentException("Seekable input required.", nameof(input)); }
62추가: var length = input.Length;
63추가: if (length > inputLimit) { throw new ArchiveException(ArchiveError.BudgetExceeded); }
64추가: if (length < 1024 || length % BlockSize != 0) { Fail(); }
65추가:
66추가: var entries = new List<ArchiveEntry>();
67추가: var first = await ScanAsync(input, length, entries, null, sink, token).ConfigureAwait(false);
68추가: var inventory = entries.AsReadOnly();
69추가: budget.Check(token);
70추가: var requested = select(inventory) ?? throw new ArgumentException("Selection required.", nameof(select));
71추가: budget.Check(token);
72추가: if (requested.Count > entries.Count) { throw new ArchiveException(ArchiveError.UnsupportedEntry); }
73추가: var selected = new HashSet<string>(StringComparer.Ordinal);
74추가: foreach (var id in requested)
75추가: {
76추가: budget.Check(token);
77추가: if (selected.Count >= entries.Count || !selected.Add(id) || !entries.Any(e => e.Id == id))
78추가: {
79추가: throw new ArchiveException(ArchiveError.UnsupportedEntry);
80추가: }
81추가: }
82추가: if (selected.Count != 0)
83추가: {
84추가: var second = await ScanAsync(input, length, entries, selected, sink, token).ConfigureAwait(false);
85추가: if (!CryptographicOperations.FixedTimeEquals(first, second)) { Fail(); }
86추가: }
87추가: budget.Check(token);
88추가: // SHA256은 두 순회 입력의 동일성 확인용임. TAR에는 본문 무결성 값이 없음.
89추가: return new UstarResult(inventory, budget.Usage, Convert.ToHexString(first), VerificationState.Unavailable);
90추가: }
91추가:
92추가: private async Task<byte[]> ScanAsync(Stream input, long length, List<ArchiveEntry> entries,
93추가: HashSet<string>? selected, UstarSink sink, CancellationToken token)
94추가: {
95추가: if (input.Length != length) { Fail(); }
96추가: input.Position = 0;
97추가: using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
98추가: var buffer = new byte[ChunkSize];
99추가: var header = new byte[BlockSize];
100추가: var seen = new Dictionary<string, EntryKind>(OutputPathPolicy.Comparer(policy));
101추가: long consumed = 0;
102추가: long metadata = 0;
103추가: var index = 0;
104추가: while (true)
105추가: {
106추가: await ReadExactAsync(header).ConfigureAwait(false);
107추가: if (IsZero(header))
108추가: {
109추가: await ReadExactAsync(header).ConfigureAwait(false);
110추가: if (!IsZero(header)) { Fail(); }
111추가: while (consumed < length)
112추가: {
113추가: var count = (int)Math.Min(buffer.Length, length - consumed);
114추가: await ReadExactAsync(buffer.AsMemory(0, count)).ConfigureAwait(false);
115추가: if (!IsZero(buffer.AsSpan(0, count))) { Fail(); }
116추가: }
117추가: break;
118추가: }
119추가: if (selected is null) { budget.AddEntry(token); }
120추가: if (metadataLimit - metadata < BlockSize) { throw new ArchiveException(ArchiveError.BudgetExceeded); }
121추가: metadata += BlockSize;
122추가: var entry = ParseHeader(header, index);
123추가: RequireUnique(entry, seen);
124추가: if (selected is null) { entries.Add(entry); }
125추가: else if (index >= entries.Count || entries[index] != entry) { Fail(); }
126추가: index++;
127추가: var size = entry.DeclaredSize!.Value;
128추가: var padding = (BlockSize - size % BlockSize) % BlockSize;
129추가: // 감산 비교로 거대한 선언값의 덧셈 오버플로를 피함.
130추가: if (size > length - consumed || padding > length - consumed - size) { Fail(); }
131추가: var emit = selected?.Contains(entry.Id) == true && entry.Kind == EntryKind.File;
132추가: if (emit) { budget.ReserveOutput(size, token); }
133추가: if (emit && size == 0) { await sink(entry, ReadOnlyMemory<byte>.Empty, token).ConfigureAwait(false); }
134추가: for (long remaining = size; remaining > 0;)
135추가: {
136추가: var count = (int)Math.Min(ChunkSize, remaining);
137추가: await ReadExactAsync(buffer.AsMemory(0, count)).ConfigureAwait(false);
138추가: if (emit) { await sink(entry, buffer.AsMemory(0, count), token).ConfigureAwait(false); }
139추가: budget.Check(token);
140추가: remaining -= count;
141추가: }
142추가: if (padding > 0)
143추가: {
144추가: await ReadExactAsync(buffer.AsMemory(0, (int)padding)).ConfigureAwait(false);
145추가: if (!IsZero(buffer.AsSpan(0, (int)padding))) { Fail(); }
146추가: }
147추가: }
148추가: budget.Check(token);
149추가: if (input.Length != length || input.Position != length || (selected is not null && index != entries.Count)) { Fail(); }
150추가: return hash.GetHashAndReset();
151추가:
152추가: async ValueTask ReadExactAsync(Memory<byte> destination)
153추가: {
154추가: if (destination.Length > length - consumed) { Fail(); }
155추가: while (!destination.IsEmpty)
156추가: {
157추가: budget.Check(token);
158추가: var read = await input.ReadAsync(destination, token).ConfigureAwait(false);
159추가: if (read <= 0 || read > destination.Length) { Fail(); }
160추가: budget.ChargeProcessed(read, token);
161추가: hash.AppendData(destination.Span[..read]);
162추가: consumed += read;
163추가: destination = destination[read..];
164추가: }
165추가: }
166추가: }
167추가:
168추가: private ArchiveEntry ParseHeader(byte[] header, int index)
169추가: {
170추가: var h = header.AsSpan();
171추가: var stored = Octal(h.Slice(148, 8));
172추가: long sum = 0;
173추가: for (var i = 0; i < BlockSize; i++) { sum += i is >= 148 and < 156 ? 32 : h[i]; }
174추가: if (stored != sum) { Fail(); }
175추가: if (!h.Slice(257, 6).SequenceEqual("ustar\0"u8) || !h.Slice(263, 2).SequenceEqual("00"u8))
176추가: {
177추가: throw new ArchiveException(ArchiveError.UnsupportedEntry);
178추가: }
179추가: var kind = h[156] switch
180추가: {
181추가: 0 or (byte)'0' => EntryKind.File,
182추가: (byte)'5' => EntryKind.Directory,
183추가: _ => throw new ArchiveException(ArchiveError.UnsupportedEntry)
184추가: };
185추가: _ = Octal(h.Slice(100, 8));
186추가: _ = Octal(h.Slice(108, 8));
187추가: _ = Octal(h.Slice(116, 8));
188추가: var size = Octal(h.Slice(124, 12));
189추가: _ = Octal(h.Slice(136, 12));
190추가: if (Octal(h.Slice(329, 8), true) != 0 || Octal(h.Slice(337, 8), true) != 0 ||
191추가: !IsZero(h.Slice(157, 100)) || !IsZero(h.Slice(500, 12))) { Fail(); }
192추가: _ = Text(h.Slice(265, 32));
193추가: _ = Text(h.Slice(297, 32));
194추가: var name = Text(h[..100]);
195추가: var prefix = Text(h.Slice(345, 155));
196추가: if (name.Length == 0) { Fail(); }
197추가: if (prefix.Length > 0) { name = prefix + "/" + name; }
198추가: if (kind == EntryKind.Directory && name.EndsWith('/')) { name = name[..^1]; }
199추가: if (kind == EntryKind.Directory && size != 0) { Fail(); }
200추가: if (name.Contains('\\')) { throw new ArchiveException(ArchiveError.UnsafePath); }
201추가: name = string.Join("/", OutputPathPolicy.Validate(name, policy));
202추가: return new ArchiveEntry(index.ToString(CultureInfo.InvariantCulture), name, kind, size);
203추가: }
204추가:
205추가: private void RequireUnique(ArchiveEntry entry, Dictionary<string, EntryKind> seen)
206추가: {
207추가: if (seen.ContainsKey(entry.Name)) { throw new ArchiveException(ArchiveError.OutputConflict); }
208추가: foreach (var previous in seen)
209추가: {
210추가: if ((previous.Value == EntryKind.File && entry.Name.StartsWith(previous.Key + "/", OutputPathPolicy.Comparison(policy))) ||
211추가: (entry.Kind == EntryKind.File && previous.Key.StartsWith(entry.Name + "/", OutputPathPolicy.Comparison(policy))))
212추가: {
213추가: throw new ArchiveException(ArchiveError.OutputConflict);
214추가: }
215추가: }
216추가: seen.Add(entry.Name, entry.Kind);
217추가: }
218추가:
219추가: private static string Text(ReadOnlySpan<byte> field)
220추가: {
221추가: var end = field.IndexOf((byte)0);
222추가: if (end >= 0)
223추가: {
224추가: if (!IsZero(field[end..])) { Fail(); }
225추가: field = field[..end];
226추가: }
227추가: try { return Utf8.GetString(field); }
228추가: catch (DecoderFallbackException) { throw new ArchiveException(ArchiveError.IntegrityFailure); }
229추가: }
230추가:
231추가: private static long Octal(ReadOnlySpan<byte> field, bool allowEmpty = false)
232추가: {
233추가: long value = 0;
234추가: var digits = 0;
235추가: var ended = false;
236추가: foreach (var b in field)
237추가: {
238추가: if (b is 0 or 32)
239추가: {
240추가: if (digits > 0 || b == 0) { ended = true; }
241추가: continue;
242추가: }
243추가: if (ended || b < (byte)'0' || b > (byte)'7') { Fail(); }
244추가: if (value > (long.MaxValue - (b - (byte)'0')) / 8) { Fail(); }
245추가: value = value * 8 + b - (byte)'0';
246추가: digits++;
247추가: }
248추가: if (digits == 0 && !allowEmpty) { Fail(); }
249추가: return value;
250추가: }
251추가:
252추가: private static bool IsZero(ReadOnlySpan<byte> bytes)
253추가: {
254추가: foreach (var b in bytes) { if (b != 0) { return false; } }
255추가: return true;
256추가: }
257추가:
258추가: private static void Fail() => throw new ArchiveException(ArchiveError.IntegrityFailure);
259추가: }
추가tests/tar-stream-reader/Program.cs+376-0
@@ -0,0 +1,376 @@
1추가: using System.Formats.Tar;
2추가: using System.Security.Cryptography;
3추가: using System.Text;
4추가: using Zipelo.Core;
5추가: using Zipelo.Worker.Tar;
6추가:
7추가: var tests = new List<(string Name, Func<Task> Run)>();
8추가: var normal = Fixtures.Archive(new Fixture("folder/", [], '5'), new Fixture("folder/a.txt", "alpha"u8.ToArray()),
9추가: new Fixture("empty", []), new Fixture("b.bin", Enumerable.Range(0, 140000).Select(i => (byte)i).ToArray()));
10추가: var defaults = new UstarLimits(new JobLimits(1024, 128L << 20, 16L << 20, TimeSpan.FromSeconds(15), 1), 16L << 20, 1L << 20);
11추가:
12추가: tests.Add(("list", async () =>
13추가: {
14추가: using var source = new MemoryStream(normal, false);
15추가: using var sink = new HashSink();
16추가: var result = await new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => [], sink.Write, default);
17추가: Check(result.Entries.Count == 4 && result.Entries[0].Name == "folder" && result.Usage.Entries == 4);
18추가: Check(result.Usage.ProcessedBytes == normal.Length && result.Usage.OutputBytes == 0 && sink.Calls == 0);
19추가: Check(result.ContentVerification == VerificationState.Unavailable);
20추가: Check(result.InputSha256 == Convert.ToHexString(SHA256.HashData(normal)) && source.CanRead);
21추가: }));
22추가: tests.Add(("selected.hash.chunks", async () =>
23추가: {
24추가: using var source = new FragmentedStream(normal);
25추가: using var sink = new HashSink();
26추가: var result = await new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => ["2", "3"], sink.Write, default);
27추가: Check(sink.Counts["2"] == 0 && sink.Counts["3"] == 140000 && !sink.Counts.ContainsKey("1"));
28추가: Check(sink.Digest("3") == Convert.ToHexString(SHA256.HashData(Enumerable.Range(0, 140000).Select(i => (byte)i).ToArray())));
29추가: Check(sink.MaxChunk == UstarReader.ChunkSize && result.Usage.ProcessedBytes == normal.Length * 2L);
30추가: Check(result.Usage.OutputBytes == 140000 && result.Usage.Entries == 4);
31추가: }));
32추가: tests.Add(("bcl.ustar.prefix", async () =>
33추가: {
34추가: using var archive = new MemoryStream();
35추가: var prefix = new string('p', 80) + "/" + new string('q', 60);
36추가: using (var writer = new TarWriter(archive, TarEntryFormat.Ustar, leaveOpen: true))
37추가: {
38추가: var entry = new UstarTarEntry(TarEntryType.RegularFile, prefix + "/a") { DataStream = new MemoryStream("ok"u8.ToArray()) };
39추가: writer.WriteEntry(entry);
40추가: }
41추가: using var sink = new HashSink();
42추가: var result = await new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(archive, _ => ["0"], sink.Write, default);
43추가: Check(result.Entries[0].Name == prefix + "/a" && sink.Counts["0"] == 2);
44추가: }));
45추가: tests.Add(("empty.archive", async () => { await Run(new byte[1024]); }));
46추가: tests.Add(("zero.trailing.blocks", async () => { await Run([.. normal, .. new byte[1024]]); }));
47추가: tests.Add(("directory.after.child", async () => { await Run(Fixtures.Archive(new Fixture("a/b", []), new Fixture("a/", [], '5'))); }));
48추가: tests.Add(("linux.case.distinct", async () => { await Run(Fixtures.Archive(new Fixture("A", []), new Fixture("a", []))); }));
49추가: tests.Add(("header.checksum.not.content", async () =>
50추가: {
51추가: var bytes = Fixtures.Archive(new Fixture("a", "one"u8.ToArray()));
52추가: bytes[512] ^= 1;
53추가: var result = await Run(bytes);
54추가: Check(result.ContentVerification == VerificationState.Unavailable);
55추가: }));
56추가:
57추가: Reject("checksum", Mutate(normal, 0, 1), ArchiveError.IntegrityFailure, checksum: false);
58추가: Reject("truncated.header", normal[..511], ArchiveError.IntegrityFailure, checksum: false);
59추가: Reject("truncated.body", Fixtures.Archive(new Fixture("a", new byte[1024]))[..1024], ArchiveError.IntegrityFailure, checksum: false);
60추가: Reject("end.missing", Fixtures.Archive(new Fixture("a", []))[..512], ArchiveError.IntegrityFailure, checksum: false);
61추가: Reject("end.single", Fixtures.Archive(new Fixture("a", []))[..1024], ArchiveError.IntegrityFailure, checksum: false);
62추가: Reject("end.second.nonzero", Mutate(new byte[1024], 512, 1), ArchiveError.IntegrityFailure, checksum: false);
63추가: Reject("trailing.nonzero", [.. normal, .. Enumerable.Repeat((byte)1, 512)], ArchiveError.IntegrityFailure, checksum: false);
64추가: Reject("trailing.partial", [.. normal, (byte)0], ArchiveError.IntegrityFailure, checksum: false);
65추가: Reject("padding.nonzero", Mutate(Fixtures.Archive(new Fixture("a", [1])), 513, 1), ArchiveError.IntegrityFailure, checksum: false);
66추가: Reject("size.huge.octal", Field(Fixtures.Archive(new Fixture("a", [])), 124, "77777777777\0"), ArchiveError.IntegrityFailure);
67추가: Reject("size.base256", Mutate(normal, 124, 128), ArchiveError.IntegrityFailure);
68추가: Reject("size.negative", Field(normal, 124, "-0000000001\0"), ArchiveError.IntegrityFailure);
69추가: Reject("size.invalid.digit", Mutate(normal, 124, (byte)'8'), ArchiveError.IntegrityFailure);
70추가: Reject("size.internal.terminator", Field(normal, 124, "0\00000000001"), ArchiveError.IntegrityFailure);
71추가: Reject("directory.nonzero", Field(normal, 124, "00000000001\0"), ArchiveError.IntegrityFailure);
72추가: Reject("version", Mutate(normal, 264, (byte)'1'), ArchiveError.UnsupportedEntry);
73추가: Reject("gnu.magic", Mutate(normal, 262, (byte)' '), ArchiveError.UnsupportedEntry);
74추가: Reject("linkname.on.file", Mutate(Fixtures.Archive(new Fixture("a", [])), 157, (byte)'x'), ArchiveError.IntegrityFailure);
75추가: Reject("reserved.bytes", Mutate(normal, 500, 1), ArchiveError.IntegrityFailure);
76추가: Reject("name.hidden.after.nul", Mutate(Fixtures.Archive(new Fixture("a", [])), 2, (byte)'b'), ArchiveError.IntegrityFailure);
77추가: Reject("invalid.utf8", Mutate(Fixtures.Archive(new Fixture("a", [])), 0, 255), ArchiveError.IntegrityFailure);
78추가: foreach (var type in new[] { 'x', 'g', 'L', 'K', 'S', '1', '2', '3', '4', '6', '7', 'V', '?' })
79추가: {
80추가: Reject("type." + type, Fixtures.Archive(new Fixture("a", [], type)), ArchiveError.UnsupportedEntry);
81추가: }
82추가: foreach (var name in new[] { "../a", "/root", "a//b", "a/./b", "a/../b", "a\\b", "" })
83추가: {
84추가: Reject("path." + name, Fixtures.Archive(new Fixture(name, [])), name.Length == 0 ? ArchiveError.IntegrityFailure : ArchiveError.UnsafePath);
85추가: }
86추가: foreach (var entries in new[]
87추가: {
88추가: new[] { new Fixture("a", []), new Fixture("a", []) },
89추가: new[] { new Fixture("a/", [], '5'), new Fixture("a", []) },
90추가: new[] { new Fixture("a", []), new Fixture("a/b", []) },
91추가: new[] { new Fixture("a/b", []), new Fixture("a", []) }
92추가: })
93추가: {
94추가: Reject("collision." + tests.Count, Fixtures.Archive(entries), ArchiveError.OutputConflict);
95추가: }
96추가: Reject("windows.case.collision", Fixtures.Archive(new Fixture("A", []), new Fixture("a", [])), ArchiveError.OutputConflict, policy: FileNamePolicy.Windows);
97추가: Reject("windows.device", Fixtures.Archive(new Fixture("CON.txt", [])), ArchiveError.UnsafePath, policy: FileNamePolicy.Windows);
98추가: Reject("windows.drive", Fixtures.Archive(new Fixture("C:/a", [])), ArchiveError.UnsafePath, policy: FileNamePolicy.Windows);
99추가: Reject("unselected.unsafe", Fixtures.Archive(new Fixture("ok", [1]), new Fixture("../bad", [])), ArchiveError.UnsafePath, selection: _ => ["0"]);
100추가: Reject("input.limit", normal, ArchiveError.BudgetExceeded, limits: defaults with { MaxInputBytes = normal.Length - 1 });
101추가: Reject("entries.limit", normal, ArchiveError.BudgetExceeded, limits: defaults with { Job = defaults.Job with { MaxEntries = 3 } });
102추가: Reject("metadata.limit", normal, ArchiveError.BudgetExceeded, limits: defaults with { MaxMetadataBytes = 2047 });
103추가: Reject("processed.first.pass", normal, ArchiveError.BudgetExceeded, limits: defaults with { Job = defaults.Job with { MaxProcessedBytes = normal.Length - 1 } });
104추가: Reject("processed.second.pass.cumulative", normal, ArchiveError.BudgetExceeded,
105추가: limits: defaults with { Job = defaults.Job with { MaxProcessedBytes = normal.Length * 2L - 1 } }, expectNoOutput: false);
106추가: Reject("output.limit", normal, ArchiveError.BudgetExceeded, limits: defaults with { Job = defaults.Job with { MaxOutputBytes = 4 } });
107추가: Reject("entries.hard.cap", Fixtures.Archive(Enumerable.Range(0, 1025).Select(i => new Fixture("f" + i, [])).ToArray()),
108추가: ArchiveError.BudgetExceeded, limits: defaults with { Job = defaults.Job with { MaxEntries = long.MaxValue } });
109추가: Reject("input.hard.cap", new byte[(16 << 20) + 512], ArchiveError.BudgetExceeded,
110추가: limits: defaults with { MaxInputBytes = long.MaxValue });
111추가: Reject("selection.duplicate", normal, ArchiveError.UnsupportedEntry, selection: _ => ["1", "1"]);
112추가: Reject("selection.unknown", normal, ArchiveError.UnsupportedEntry, selection: _ => ["99"]);
113추가:
114추가: tests.Add(("cancel.before.read", async () =>
115추가: {
116추가: using var cts = new CancellationTokenSource();
117추가: cts.Cancel();
118추가: await Cancelled(() => Run(normal, token: cts.Token));
119추가: }));
120추가: tests.Add(("cancel.during.read", async () =>
121추가: {
122추가: using var cts = new CancellationTokenSource();
123추가: using var source = new FragmentedStream(normal, () => cts.Cancel());
124추가: using var sink = new HashSink();
125추가: await Cancelled(() => new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => [], sink.Write, cts.Token));
126추가: Check(sink.Calls == 0);
127추가: }));
128추가: tests.Add(("cancel.sink", async () =>
129추가: {
130추가: using var cts = new CancellationTokenSource();
131추가: using var source = new MemoryStream(normal, false);
132추가: await Cancelled(() => new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => ["3"], (_, _, _) =>
133추가: {
134추가: cts.Cancel();
135추가: return ValueTask.CompletedTask;
136추가: }, cts.Token));
137추가: }));
138추가: tests.Add(("duration.cumulative", async () =>
139추가: {
140추가: var time = new TestTime();
141추가: using var source = new MemoryStream(normal, false);
142추가: using var sink = new HashSink();
143추가: await Error(ArchiveError.BudgetExceeded, () => new UstarReader(defaults, FileNamePolicy.Linux, time).ReadAsync(source, _ =>
144추가: {
145추가: time.Ticks = TimeSpan.FromSeconds(15).Ticks;
146추가: return ["1"];
147추가: }, sink.Write, default));
148추가: Check(sink.Calls == 0);
149추가: }));
150추가: tests.Add(("input.changed.between.passes", async () =>
151추가: {
152추가: var bytes = Fixtures.Archive(new Fixture("a", "old"u8.ToArray()));
153추가: using var source = new MemoryStream(bytes, false);
154추가: using var sink = new HashSink();
155추가: await Error(ArchiveError.IntegrityFailure, () => new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ =>
156추가: {
157추가: bytes[512] ^= 1;
158추가: return ["0"];
159추가: }, sink.Write, default));
160추가: Check(sink.Calls > 0);
161추가: }));
162추가: tests.Add(("input.unselected.changed", async () =>
163추가: {
164추가: var bytes = Fixtures.Archive(new Fixture("a", [1]), new Fixture("b", [2]));
165추가: using var source = new MemoryStream(bytes, false);
166추가: using var sink = new HashSink();
167추가: await Error(ArchiveError.IntegrityFailure, () => new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ =>
168추가: {
169추가: bytes[1536] ^= 1;
170추가: return ["0"];
171추가: }, sink.Write, default));
172추가: }));
173추가: tests.Add(("single.use", async () =>
174추가: {
175추가: var reader = new UstarReader(defaults, FileNamePolicy.Linux);
176추가: using var source = new MemoryStream(normal, false);
177추가: using var sink = new HashSink();
178추가: await reader.ReadAsync(source, _ => [], sink.Write, default);
179추가: try { await reader.ReadAsync(source, _ => [], sink.Write, default); }
180추가: catch (InvalidOperationException) { return; }
181추가: throw new Exception("Reuse accepted.");
182추가: }));
183추가:
184추가: tests.Add(("metadata.exact.boundary", async () =>
185추가: {
186추가: using var source = new MemoryStream(normal, false);
187추가: using var sink = new HashSink();
188추가: var result = await new UstarReader(defaults with { MaxMetadataBytes = 2048 }, FileNamePolicy.Linux)
189추가: .ReadAsync(source, _ => ["0"], sink.Write, default);
190추가: Check(result.Entries.Count == 4 && sink.Calls == 0);
191추가: }));
192추가: tests.Add(("input.limit.exact", async () =>
193추가: {
194추가: using var source = new MemoryStream(normal, false);
195추가: using var sink = new HashSink();
196추가: await new UstarReader(defaults with { MaxInputBytes = normal.Length }, FileNamePolicy.Linux)
197추가: .ReadAsync(source, _ => [], sink.Write, default);
198추가: }));
199추가: tests.Add(("sink.failure.propagates", async () =>
200추가: {
201추가: using var source = new MemoryStream(normal, false);
202추가: var expected = new IOException("Test sink failure.");
203추가: try
204추가: {
205추가: await new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => ["1"],
206추가: (_, _, _) => throw expected, default);
207추가: }
208추가: catch (IOException error) when (ReferenceEquals(error, expected)) { Check(source.CanRead); return; }
209추가: throw new Exception("Sink failure suppressed.");
210추가: }));
211추가: tests.Add(("nonseekable.rejected", async () =>
212추가: {
213추가: using var source = new NonSeekableStream(normal);
214추가: using var sink = new HashSink();
215추가: try { await new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => [], sink.Write, default); }
216추가: catch (ArgumentException) { Check(sink.Calls == 0); return; }
217추가: throw new Exception("Nonseekable input accepted.");
218추가: }));
219추가: tests.Add(("invalid.limits", () =>
220추가: {
221추가: foreach (var limits in new[]
222추가: {
223추가: defaults with { MaxMetadataBytes = 0 }, defaults with { MaxInputBytes = 0 },
224추가: defaults with { Job = defaults.Job with { MaxEntries = 0 } },
225추가: defaults with { Job = defaults.Job with { MaxDuration = TimeSpan.Zero } }
226추가: })
227추가: {
228추가: try { _ = new UstarReader(limits, FileNamePolicy.Linux); }
229추가: catch (ArgumentOutOfRangeException) { continue; }
230추가: throw new Exception("Invalid limits accepted.");
231추가: }
232추가: return Task.CompletedTask;
233추가: }));
234추가:
235추가: var failures = 0;
236추가: foreach (var test in tests)
237추가: {
238추가: try { await test.Run(); Console.WriteLine("PASS " + test.Name); }
239추가: catch (Exception error) { failures++; Console.WriteLine("FAIL " + test.Name + " " + error); }
240추가: }
241추가: Console.WriteLine($"total={tests.Count} failed={failures}");
242추가: return failures == 0 ? 0 : 1;
243추가:
244추가: void Reject(string name, byte[] bytes, ArchiveError code, bool checksum = true, UstarLimits? limits = null,
245추가: FileNamePolicy policy = FileNamePolicy.Linux, Func<IReadOnlyList<ArchiveEntry>, IReadOnlyCollection<string>>? selection = null,
246추가: bool expectNoOutput = true)
247추가: {
248추가: if (checksum && bytes.Length >= 512) { Fixtures.Checksum(bytes.AsSpan(0, 512)); }
249추가: tests.Add((name, async () =>
250추가: {
251추가: using var source = new MemoryStream(bytes, false);
252추가: using var sink = new HashSink();
253추가: await Error(code, () => new UstarReader(limits ?? defaults, policy).ReadAsync(source,
254추가: selection ?? (entries => entries.Where(e => e.Kind == EntryKind.File).Select(e => e.Id).ToArray()), sink.Write, default));
255추가: if (expectNoOutput) { Check(sink.Calls == 0); }
256추가: }));
257추가: }
258추가:
259추가: async Task<UstarResult> Run(byte[] bytes, CancellationToken token = default)
260추가: {
261추가: using var source = new MemoryStream(bytes, false);
262추가: using var sink = new HashSink();
263추가: return await new UstarReader(defaults, FileNamePolicy.Linux).ReadAsync(source, _ => [], sink.Write, token);
264추가: }
265추가:
266추가: static async Task Error(ArchiveError expected, Func<Task> action)
267추가: {
268추가: try { await action(); }
269추가: catch (ArchiveException error) when (error.Code == expected) { return; }
270추가: throw new Exception("Expected " + expected);
271추가: }
272추가:
273추가: static async Task Cancelled(Func<Task> action)
274추가: {
275추가: try { await action(); }
276추가: catch (OperationCanceledException) { return; }
277추가: throw new Exception("Expected cancellation.");
278추가: }
279추가:
280추가: static void Check(bool condition) { if (!condition) { throw new Exception("Assertion failed."); } }
281추가: static byte[] Mutate(byte[] bytes, int index, byte value) { var copy = (byte[])bytes.Clone(); copy[index] = value; return copy; }
282추가: static byte[] Field(byte[] bytes, int offset, string value)
283추가: {
284추가: var copy = (byte[])bytes.Clone();
285추가: Encoding.ASCII.GetBytes(value).CopyTo(copy, offset);
286추가: return copy;
287추가: }
288추가:
289추가: internal sealed record Fixture(string Name, byte[] Data, char Type = '0');
290추가:
291추가: internal static class Fixtures
292추가: {
293추가: internal static byte[] Archive(params Fixture[] entries)
294추가: {
295추가: using var stream = new MemoryStream();
296추가: foreach (var entry in entries)
297추가: {
298추가: var header = new byte[512];
299추가: Encoding.UTF8.GetBytes(entry.Name).CopyTo(header, 0);
300추가: Number(header, 100, 8, 420);
301추가: Number(header, 108, 8, 0);
302추가: Number(header, 116, 8, 0);
303추가: Number(header, 124, 12, entry.Data.LongLength);
304추가: Number(header, 136, 12, 0);
305추가: header[156] = (byte)entry.Type;
306추가: "ustar\000"u8.CopyTo(header.AsSpan(257));
307추가: Checksum(header);
308추가: stream.Write(header);
309추가: stream.Write(entry.Data);
310추가: stream.Write(new byte[(512 - entry.Data.Length % 512) % 512]);
311추가: }
312추가: stream.Write(new byte[1024]);
313추가: return stream.ToArray();
314추가: }
315추가:
316추가: internal static void Checksum(Span<byte> header)
317추가: {
318추가: header.Slice(148, 8).Fill(32);
319추가: var sum = 0;
320추가: foreach (var b in header) { sum += b; }
321추가: Encoding.ASCII.GetBytes(Convert.ToString(sum, 8).PadLeft(6, '0')).CopyTo(header.Slice(148, 6));
322추가: header[154] = 0;
323추가: header[155] = 32;
324추가: }
325추가:
326추가: private static void Number(byte[] bytes, int offset, int width, long value) =>
327추가: Encoding.ASCII.GetBytes(Convert.ToString(value, 8).PadLeft(width - 1, '0') + "\0").CopyTo(bytes, offset);
328추가: }
329추가:
330추가: internal sealed class HashSink : IDisposable
331추가: {
332추가: private readonly Dictionary<string, IncrementalHash> hashes = new();
333추가: internal Dictionary<string, long> Counts { get; } = new();
334추가: internal int Calls { get; private set; }
335추가: internal int MaxChunk { get; private set; }
336추가:
337추가: internal ValueTask Write(ArchiveEntry entry, ReadOnlyMemory<byte> bytes, CancellationToken token)
338추가: {
339추가: token.ThrowIfCancellationRequested();
340추가: if (!hashes.TryGetValue(entry.Id, out var hash))
341추가: {
342추가: hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
343추가: hashes.Add(entry.Id, hash);
344추가: Counts.Add(entry.Id, 0);
345추가: }
346추가: hash.AppendData(bytes.Span);
347추가: Counts[entry.Id] += bytes.Length;
348추가: Calls++;
349추가: MaxChunk = Math.Max(MaxChunk, bytes.Length);
350추가: return ValueTask.CompletedTask;
351추가: }
352추가:
353추가: internal string Digest(string id) => Convert.ToHexString(hashes[id].GetHashAndReset());
354추가: public void Dispose() { foreach (var hash in hashes.Values) { hash.Dispose(); } }
355추가: }
356추가:
357추가: internal sealed class FragmentedStream(byte[] bytes, Action? onRead = null) : MemoryStream(bytes, false)
358추가: {
359추가: public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
360추가: {
361추가: onRead?.Invoke();
362추가: return base.ReadAsync(buffer[..Math.Min(buffer.Length, 97)], cancellationToken);
363추가: }
364추가: }
365추가:
366추가: internal sealed class TestTime : TimeProvider
367추가: {
368추가: internal long Ticks { get; set; }
369추가: public override long TimestampFrequency => TimeSpan.TicksPerSecond;
370추가: public override long GetTimestamp() => Ticks;
371추가: }
372추가:
373추가: internal sealed class NonSeekableStream(byte[] bytes) : MemoryStream(bytes, false)
374추가: {
375추가: public override bool CanSeek => false;
376추가: }
추가tests/tar-stream-reader/Zipelo.TarReaderTests.csproj+13-0
@@ -0,0 +1,13 @@
1추가: <Project Sdk="Microsoft.NET.Sdk">
2추가: <PropertyGroup>
3추가: <OutputType>Exe</OutputType>
4추가: <TargetFramework>net10.0</TargetFramework>
5추가: <Nullable>enable</Nullable>
6추가: <ImplicitUsings>enable</ImplicitUsings>
7추가: <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
8추가: </PropertyGroup>
9추가: <ItemGroup>
10추가: <ProjectReference Include="../../src/Zipelo.Core/Zipelo.Core.csproj" />
11추가: <Compile Include="../../src/Zipelo.Worker/Tar/UstarReader.cs" Link="Production/UstarReader.cs" />
12추가: </ItemGroup>
13추가: </Project>
추가tests/tar-stream-reader/contract.json+54-0
@@ -0,0 +1,54 @@
1추가: {
2추가: "schemaVersion": 1,
3추가: "baseCommit": "cc39e8949a9a04d28a3ddc58850f696b52da6e21",
4추가: "scope": "Worker 내부 USTAR 일반 파일과 디렉터리만 처리함. ZIP, 프로토콜, UI, 게시 및 공개 지원 표시에는 연결하지 않음.",
5추가: "implementation": "하나의 엄격한 수동 USTAR 검증기로 두 순회를 처리함. TarReader 재해석과 확장 메타데이터의 선행 할당을 피함. 정상 호환 표본은 BCL TarWriter로 생성함.",
6추가: "sourceContract": [
7추가: "seek 가능 스트림을 호출자가 독점 보유함. 처음부터 읽으며 스트림을 닫지 않음.",
8추가: "첫 순회에서 선택하지 않은 항목까지 전부 검증함. 읽기 실패 또는 손상은 목록 선택 전 거부함.",
9추가: "선택은 읽기 전용 목록의 순번 ID로 고정함. 빈 선택은 목록 전용임. 디렉터리 선택은 바이트를 발생시키지 않음.",
10추가: "선택이 있으면 두 번째 전체 순회에서 항목을 대조하며 선택 바이트만 전달함. 전체 입력 SHA256이 달라지면 실패함.",
11추가: "입력 SHA256은 순회 간 동일성 검사이며 저장된 내용 무결성 보증이 아님. ContentVerification은 Unavailable임."
12추가: ],
13추가: "sinkContract": [
14추가: "수신기는 최대 64KiB 청크를 즉시 소비하거나 복사함. 전달 메모리를 보관하지 않음.",
15추가: "수신 바이트는 임시 결과임. ReadAsync 성공 반환 전 게시하지 않음. 오류, 취소, 입력 변경 시 전체 결과를 폐기함.",
16추가: "수신기 예외는 그대로 전파함. 빈 파일은 빈 청크 한 번으로 표시함. 파일시스템 출력 및 정리는 이 단위에 없음."
17추가: ],
18추가: "strictSubset": [
19추가: "ustar NUL magic, 00 version, unsigned 헤더 체크섬, 비음수 octal 숫자만 허용함.",
20추가: "NUL 뒤 문자열 여유 영역은 0이어야 하며 이름은 엄격한 UTF8임. prefix 이름을 허용함.",
21추가: "일반 파일 0 또는 NUL, 디렉터리 5만 허용함. 디렉터리 크기는 0임.",
22추가: "PAX x/g, GNU L/K/S, 링크, sparse, 장치, FIFO, 연속 파일, 다중 볼륨 및 미지 유형을 거부함.",
23추가: "본문 padding과 마지막 12바이트 헤더 여유 영역은 0이어야 함. 종료 0블록 두 개와 정렬된 0 후행 블록만 허용함.",
24추가: "경로는 지정한 Windows 또는 Linux OutputPathPolicy로 검사함. 역슬래시는 양쪽에서 거부함. 중복과 파일 조상 충돌은 모든 항목에서 거부함.",
25추가: "uid/gid/mode/mtime은 숫자 문법만 검사하며 복원하지 않음. linkname은 비어 있어야 하며 device 번호는 0이어야 함.",
26추가: "GZip과 TAR.GZ, 암호, 복구, 권한 복원은 연결하지 않음."
27추가: ],
28추가: "limits": {
29추가: "inputBytes": 16777216,
30추가: "entries": 1024,
31추가: "processedBytes": 134217728,
32추가: "outputBytes": 16777216,
33추가: "metadataHeaderBytes": 1048576,
34추가: "durationSeconds": 300,
35추가: "chunkBytes": 65536,
36추가: "rule": "호출자 제한과 각 상한 중 작은 값을 사용함. JobBudget 하나로 두 순회, 선택 콜백 및 수신 시간까지 누적함. 모든 읽은 바이트와 건너뛴 데이터도 처리량에 포함함. 항목 수는 첫 순회만 세며 두 번째 순회는 목록과 대조함. 메타데이터는 순회별 원시 헤더 512바이트 단위 제한이며 실제 관리 힙 크기나 OS 메모리 격리를 뜻하지 않음."
37추가: },
38추가: "failureLimits": [
39추가: "검사는 협조적 취소임. 임의 Stream 또는 수신기가 멈추면 강제 종료하지 못함. 중앙 실행 외부 시간 제한이 필요함.",
40추가: "실패하면 UstarResult를 반환하지 않음. 단일 사용 인스턴스이며 실패 후 재시도도 새 작업임.",
41추가: "네이티브 게시 및 Windows 정리 정지 문제는 별도 미해결임. 이 검사의 통과를 제품 압축 해제 성공으로 취급하지 않음."
42추가: ],
43추가: "validation": {
44추가: "local": "정적 검토만 수행함. dotnet/csc/mcs 부재로 C# 컴파일과 실행은 미검증임.",
45추가: "commands": [
46추가: "dotnet restore src/Zipelo.Worker/Zipelo.Worker.csproj --configfile tests/security/NuGet.Config",
47추가: "dotnet restore tests/tar-stream-reader/Zipelo.TarReaderTests.csproj --configfile tests/security/NuGet.Config",
48추가: "dotnet build src/Zipelo.Worker/Zipelo.Worker.csproj -c Release --no-restore",
49추가: "dotnet build tests/tar-stream-reader/Zipelo.TarReaderTests.csproj -c Release --no-restore",
50추가: "dotnet run --project tests/tar-stream-reader/Zipelo.TarReaderTests.csproj -c Release --no-build"
51추가: ],
52추가: "prerequisites": "중앙의 기존 .NET 10 SDK 및 참조 팩으로 오프라인 restore를 먼저 수행함. 신규 외부 패키지 의존성이 없음. Windows/Linux 양쪽에서 독립 콘솔 검사를 수행함."
53추가: }
54추가: }