| 1 | using System.Collections.Concurrent; |
| 2 | using System.Security; |
| 3 | using Zipelo.Core; |
| 4 | |
| 5 | namespace Zipelo.SecurityTests; |
| 6 | |
| 7 | internal sealed partial class CoreTests |
| 8 | { |
| 9 | private static readonly TimeSpan RegressionTimeout = TimeSpan.FromSeconds(5); |
| 10 | |
| 11 | private static async Task ConcurrentPasswords() |
| 12 | { |
| 13 | using var firstSecret = TestSecrets.Create(); |
| 14 | using var secondSecret = TestSecrets.Create(); |
| 15 | var response = new TaskCompletionSource<SecureString?>(TaskCreationOptions.RunContinuationsAsynchronously); |
| 16 | var challenges = new ConcurrentQueue<PasswordChallenge>(); |
| 17 | var activeCounts = new ConcurrentQueue<int>(); |
| 18 | var observed = new ConcurrentQueue<JobEvent>(); |
| 19 | var active = 0; |
| 20 | var calls = 0; |
| 21 | var callsWhileWaiting = 0; |
| 22 | var bothPending = false; |
| 23 | var waitingPreserved = false; |
| 24 | var correctFirst = false; |
| 25 | var correctSecond = false; |
| 26 | |
| 27 | var run = await Execute(Stub(async context => |
| 28 | { |
| 29 | var first = context.UsePasswordAsync((secret, token) => |
| 30 | { |
| 31 | correctFirst = ReferenceEquals(firstSecret, secret); |
| 32 | return ValueTask.FromResult(0); |
| 33 | }).AsTask(); |
| 34 | var second = context.UsePasswordAsync((secret, token) => |
| 35 | { |
| 36 | correctSecond = ReferenceEquals(secondSecret, secret); |
| 37 | return ValueTask.FromResult(0); |
| 38 | }).AsTask(); |
| 39 | try |
| 40 | { |
| 41 | callsWhileWaiting = Volatile.Read(ref calls); |
| 42 | bothPending = !first.IsCompleted && !second.IsCompleted; |
| 43 | var eventCount = observed.Count; |
| 44 | await context.ListEntryAsync(new("listed", "listed.txt", EntryKind.File, 0)); |
| 45 | await Write(context, "written.txt", [1, 2]); |
| 46 | var snapshot = observed.ToArray(); |
| 47 | waitingPreserved = snapshot[^1].State == JobState.WaitingForPassword && |
| 48 | snapshot.Skip(eventCount).All(value => value.State == JobState.WaitingForPassword); |
| 49 | } |
| 50 | finally |
| 51 | { |
| 52 | response.TrySetResult(firstSecret); |
| 53 | await Task.WhenAll(first, second).WaitAsync(RegressionTimeout); |
| 54 | } |
| 55 | }), passwords: async (challenge, token) => |
| 56 | { |
| 57 | challenges.Enqueue(challenge); |
| 58 | activeCounts.Enqueue(Interlocked.Increment(ref active)); |
| 59 | var call = Interlocked.Increment(ref calls); |
| 60 | try |
| 61 | { |
| 62 | return call == 1 ? await response.Task : secondSecret; |
| 63 | } |
| 64 | finally { Interlocked.Decrement(ref active); } |
| 65 | }, observe: observed.Enqueue); |
| 66 | |
| 67 | Check.Equal(JobState.Completed, run.Result.State); |
| 68 | Check.Equal(1, callsWhileWaiting); |
| 69 | Check.That(bothPending, "첫 제공자 응답 전에 다른 요청이 완료됨"); |
| 70 | Check.That(waitingPreserved, "항목 진행이 암호 대기 상태를 덮어씀"); |
| 71 | Check.Equal(1, activeCounts.Max()); |
| 72 | Check.Equal(2, calls); |
| 73 | Check.That(correctFirst && correctSecond, "다른 요청의 암호를 소비함"); |
| 74 | var requests = challenges.ToArray(); |
| 75 | Check.That(requests.Select(value => value.Attempt).SequenceEqual(new[] { 1, 2 }), |
| 76 | "동시 요청의 시도 번호가 잘못됨"); |
| 77 | Check.Equal(2, requests.Select(value => value.RequestId).Distinct().Count()); |
| 78 | Check.That(requests.All(value => value.JobId == run.Result.JobId), "다른 작업의 암호 요청임"); |
| 79 | Check.Throws<ObjectDisposedException>(() => { _ = firstSecret.Length; }); |
| 80 | Check.Throws<ObjectDisposedException>(() => { _ = secondSecret.Length; }); |
| 81 | } |
| 82 | |
| 83 | private static async Task QueuedPasswordCancellation() |
| 84 | { |
| 85 | using var cancellation = new CancellationTokenSource(); |
| 86 | using var lateSecret = TestSecrets.Create(); |
| 87 | var response = new TaskCompletionSource<SecureString?>(TaskCreationOptions.RunContinuationsAsynchronously); |
| 88 | var observed = new ConcurrentQueue<JobEvent>(); |
| 89 | var calls = 0; |
| 90 | var consumed = 0; |
| 91 | var run = await Execute(Stub(async context => |
| 92 | { |
| 93 | ValueTask<int> Consume(SecureString secret, CancellationToken token) |
| 94 | { |
| 95 | Interlocked.Increment(ref consumed); |
| 96 | return ValueTask.FromResult(0); |
| 97 | } |
| 98 | |
| 99 | var first = context.UsePasswordAsync(Consume).AsTask(); |
| 100 | var second = context.UsePasswordAsync(Consume).AsTask(); |
| 101 | cancellation.Cancel(); |
| 102 | try |
| 103 | { |
| 104 | await Check.ThrowsAsync<OperationCanceledException>( |
| 105 | () => second.WaitAsync(RegressionTimeout)); |
| 106 | } |
| 107 | finally |
| 108 | { |
| 109 | // 취소를 무시하고 늦게 반환하는 제공자를 재현함. |
| 110 | response.TrySetResult(lateSecret); |
| 111 | await Check.ThrowsAsync<OperationCanceledException>( |
| 112 | () => first.WaitAsync(RegressionTimeout)); |
| 113 | } |
| 114 | context.CancellationToken.ThrowIfCancellationRequested(); |
| 115 | }), passwords: async (challenge, token) => |
| 116 | { |
| 117 | Interlocked.Increment(ref calls); |
| 118 | return await response.Task; |
| 119 | }, token: cancellation.Token, observe: observed.Enqueue); |
| 120 | |
| 121 | Cancelled(run); |
| 122 | Check.Equal(1, calls); |
| 123 | Check.Equal(0, consumed); |
| 124 | Check.Throws<ObjectDisposedException>(() => { _ = lateSecret.Length; }); |
| 125 | var events = observed.ToArray(); |
| 126 | var cancelIndex = Array.FindIndex(events, value => value.State == JobState.Cancelling); |
| 127 | Check.That(cancelIndex >= 0, "취소 요청 이벤트가 없음"); |
| 128 | Check.That(events.Skip(cancelIndex).All(value => |
| 129 | value.State is JobState.Cancelling or JobState.Cancelled), "취소 뒤 활성 상태가 보고됨"); |
| 130 | var count = observed.Count; |
| 131 | cancellation.Cancel(); |
| 132 | Check.Equal(count, observed.Count); |
| 133 | Check.Equal(JobState.Cancelled, events[^1].State); |
| 134 | } |
| 135 | |
| 136 | private static async Task PasswordGateAfterFailures() |
| 137 | { |
| 138 | var secrets = new List<SecureString>(); |
| 139 | var challenges = new List<PasswordChallenge>(); |
| 140 | var run = await Execute(Stub(async context => |
| 141 | { |
| 142 | await Check.ThrowsAsync<IOException>(() => context.UsePasswordAsync( |
| 143 | (secret, token) => ValueTask.FromResult(0)).AsTask().WaitAsync(RegressionTimeout)); |
| 144 | await Check.ThrowsAsync<IOException>(() => context.UsePasswordAsync<int>( |
| 145 | (secret, token) => ValueTask.FromException<int>(new IOException("테스트 소비 실패"))) |
| 146 | .AsTask().WaitAsync(RegressionTimeout)); |
| 147 | var length = await context.UsePasswordAsync( |
| 148 | (secret, token) => ValueTask.FromResult(secret.Length)).AsTask().WaitAsync(RegressionTimeout); |
| 149 | Check.That(length > 0, "실패 후 암호 재요청에 실패함"); |
| 150 | }), passwords: (challenge, token) => |
| 151 | { |
| 152 | challenges.Add(challenge); |
| 153 | if (challenges.Count == 1) |
| 154 | { |
| 155 | return ValueTask.FromException<SecureString?>(new IOException("테스트 제공 실패")); |
| 156 | } |
| 157 | var secret = TestSecrets.Create(); |
| 158 | secrets.Add(secret); |
| 159 | return ValueTask.FromResult<SecureString?>(secret); |
| 160 | }); |
| 161 | |
| 162 | Check.Equal(JobState.Completed, run.Result.State); |
| 163 | Check.That(challenges.Select(value => value.Attempt).SequenceEqual(new[] { 1, 2, 3 }), |
| 164 | "재요청의 시도 번호가 잘못됨"); |
| 165 | Check.Equal(2, secrets.Count); |
| 166 | foreach (var secret in secrets) |
| 167 | { |
| 168 | Check.Throws<ObjectDisposedException>(() => { _ = secret.Length; }); |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | private static async Task PasswordConsumerReentry() |
| 173 | { |
| 174 | var secrets = new List<SecureString>(); |
| 175 | var calls = 0; |
| 176 | var run = await Execute(Stub(async context => |
| 177 | { |
| 178 | var combined = await context.UsePasswordAsync(async (outer, token) => |
| 179 | { |
| 180 | var length = outer.Length; |
| 181 | var innerLength = await context.UsePasswordAsync( |
| 182 | (inner, innerToken) => ValueTask.FromResult(inner.Length)); |
| 183 | Check.Equal(length, outer.Length); |
| 184 | return length + innerLength; |
| 185 | }).AsTask().WaitAsync(RegressionTimeout); |
| 186 | Check.That(combined > 0, "소비자의 암호 재요청이 완료되지 않음"); |
| 187 | }), passwords: (challenge, token) => |
| 188 | { |
| 189 | calls++; |
| 190 | var secret = TestSecrets.Create(); |
| 191 | secrets.Add(secret); |
| 192 | return ValueTask.FromResult<SecureString?>(secret); |
| 193 | }); |
| 194 | |
| 195 | Check.Equal(JobState.Completed, run.Result.State); |
| 196 | Check.Equal(2, calls); |
| 197 | foreach (var secret in secrets) |
| 198 | { |
| 199 | Check.Throws<ObjectDisposedException>(() => { _ = secret.Length; }); |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | private static async Task InitializationCleanup() |
| 204 | { |
| 205 | foreach (var scenario in new[] { "null_limits", "invalid_limits", "input_copy" }) |
| 206 | { |
| 207 | using var input = new MemoryStream(new byte[] { 1 }, false); |
| 208 | var output = new RecordingOutput(); |
| 209 | var engine = Stub(_ => Task.CompletedTask); |
| 210 | var events = new List<JobEvent>(); |
| 211 | var limits = scenario == "null_limits" ? null : |
| 212 | scenario == "invalid_limits" ? Limits with { MaxEntries = 0 } : Limits; |
| 213 | IReadOnlyList<Stream> inputs = scenario == "input_copy" ? new ThrowingInputs() : new[] { input }; |
| 214 | var result = await new ArchiveJob(Guid.NewGuid(), limits!).ExecuteAsync( |
| 215 | ArchiveAction.List, "zip", engine, inputs, output, TestSecrets.None, |
| 216 | new InlineProgress(events.Add), default); |
| 217 | |
| 218 | Check.Equal(JobState.Failed, result.State); |
| 219 | Check.Equal(scenario == "input_copy" ? ArchiveError.EngineFailure : ArchiveError.UnsupportedOperation, |
| 220 | result.Error); |
| 221 | Check.Equal(0, engine.Calls); |
| 222 | Check.Equal(1, output.DisposeCalls); |
| 223 | Check.That(output.Disposed, "초기화 실패 뒤 출력 정리가 누락됨"); |
| 224 | Check.Equal(0, output.CreateCalls); |
| 225 | Check.Equal(0, output.CommitCalls); |
| 226 | Check.Equal(0, result.Entries.Count); |
| 227 | Check.Equal(1, events.Count); |
| 228 | Check.Equal(JobState.Failed, events[0].State); |
| 229 | Check.Equal(0L, events[0].ProcessedBytes); |
| 230 | Check.That(input.CanRead, "초기화 실패가 호출자 입력을 폐기함"); |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | private static async Task RejectedOutputOwnership() |
| 235 | { |
| 236 | using var input = new MemoryStream(new byte[] { 1 }, false); |
| 237 | var job = new ArchiveJob(Guid.NewGuid(), Limits); |
| 238 | var engine = Stub(_ => Task.CompletedTask); |
| 239 | var rejected = new RecordingOutput(); |
| 240 | try |
| 241 | { |
| 242 | await Check.ThrowsAsync<ArgumentNullException>(async () => await job.ExecuteAsync( |
| 243 | ArchiveAction.List, "zip", null!, [input], rejected, TestSecrets.None, null, default)); |
| 244 | Check.Equal(0, rejected.DisposeCalls); |
| 245 | } |
| 246 | finally { await rejected.DisposeAsync(); } |
| 247 | |
| 248 | var accepted = new RecordingOutput(); |
| 249 | var result = await job.ExecuteAsync(ArchiveAction.List, "zip", engine, [input], |
| 250 | accepted, TestSecrets.None, null, default); |
| 251 | Check.Equal(JobState.Completed, result.State); |
| 252 | Check.Equal(1, accepted.DisposeCalls); |
| 253 | |
| 254 | var reused = new RecordingOutput(); |
| 255 | try |
| 256 | { |
| 257 | await Check.ThrowsAsync<InvalidOperationException>(async () => await job.ExecuteAsync( |
| 258 | ArchiveAction.List, "zip", engine, [input], reused, TestSecrets.None, null, default)); |
| 259 | Check.Equal(0, reused.DisposeCalls); |
| 260 | } |
| 261 | finally { await reused.DisposeAsync(); } |
| 262 | } |
| 263 | |
| 264 | private static async Task IntegrityCleanupFailure() |
| 265 | { |
| 266 | var run = await Execute(Stub(context => Write(context, "bad.txt", [1], |
| 267 | verification: VerificationState.Failed)), output: new RecordingOutput { FailDispose = true }); |
| 268 | Failed(run, ArchiveError.IntegrityFailure); |
| 269 | Check.Equal(1, run.Output.DisposeCalls); |
| 270 | Check.Equal(VerificationState.Failed, run.Result.Entries.Single().Verification); |
| 271 | Check.Equal(ArchiveError.IntegrityFailure, run.Result.Entries.Single().Error); |
| 272 | } |
| 273 | |
| 274 | private static async Task CancellationCleanupFailure() |
| 275 | { |
| 276 | using var cancellation = new CancellationTokenSource(); |
| 277 | var run = await Execute(Stub(context => |
| 278 | { |
| 279 | cancellation.Cancel(); |
| 280 | context.CancellationToken.ThrowIfCancellationRequested(); |
| 281 | return Task.CompletedTask; |
| 282 | }), output: new RecordingOutput { FailDispose = true }, token: cancellation.Token); |
| 283 | Failed(run, ArchiveError.Cancelled); |
| 284 | Check.Equal(1, run.Output.DisposeCalls); |
| 285 | Check.That(!run.Events.Any(value => value.State == JobState.Cancelled), |
| 286 | "정리 실패를 정상 취소 완료로 표시함"); |
| 287 | } |
| 288 | |
| 289 | private static async Task LateCommitCancellation() |
| 290 | { |
| 291 | foreach (var failCleanup in new[] { false, true }) |
| 292 | { |
| 293 | using var cancellation = new CancellationTokenSource(); |
| 294 | var output = new RecordingOutput |
| 295 | { |
| 296 | AfterCommit = cancellation.Cancel, |
| 297 | FailDispose = failCleanup |
| 298 | }; |
| 299 | var run = await Execute(Stub(context => Write(context, "published.txt", [1])), |
| 300 | output: output, token: cancellation.Token); |
| 301 | Check.Equal(failCleanup ? JobState.Failed : JobState.Completed, run.Result.State); |
| 302 | Check.Equal(failCleanup ? ArchiveError.OutputUnavailable : ArchiveError.None, run.Result.Error); |
| 303 | Check.Equal(1, output.CommitCalls); |
| 304 | Check.Equal(1, output.DisposeCalls); |
| 305 | Check.Equal(1, output.Published.Count); |
| 306 | var entry = run.Result.Entries.Single(); |
| 307 | Check.Equal(EntryOutcome.Extracted, entry.Outcome); |
| 308 | Check.Equal(ArchiveError.None, entry.Error); |
| 309 | Check.That(output.Published["published.txt"].SequenceEqual(new byte[] { 1 }), |
| 310 | "늦은 취소가 확정된 결과를 바꿈"); |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | private static async Task DeferredCleanup() |
| 315 | { |
| 316 | var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); |
| 317 | var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); |
| 318 | var observed = new ConcurrentQueue<JobEvent>(); |
| 319 | var output = new RecordingOutput |
| 320 | { |
| 321 | BeforeDispose = async () => |
| 322 | { |
| 323 | entered.TrySetResult(); |
| 324 | await release.Task; |
| 325 | } |
| 326 | }; |
| 327 | var execution = Execute(Stub(_ => Task.CompletedTask), output: output, observe: observed.Enqueue); |
| 328 | var completedTooEarly = false; |
| 329 | var terminalTooEarly = false; |
| 330 | try |
| 331 | { |
| 332 | await entered.Task.WaitAsync(RegressionTimeout); |
| 333 | completedTooEarly = execution.IsCompleted; |
| 334 | terminalTooEarly = observed.Any(value => value.State is |
| 335 | JobState.Completed or JobState.Partial or JobState.Cancelled or JobState.Failed); |
| 336 | } |
| 337 | finally { release.TrySetResult(); } |
| 338 | |
| 339 | var run = await execution.WaitAsync(RegressionTimeout); |
| 340 | Check.That(!completedTooEarly, "출력 정리 전에 작업이 완료됨"); |
| 341 | Check.That(!terminalTooEarly, "출력 정리 전에 종료 이벤트가 보고됨"); |
| 342 | Check.Equal(JobState.Completed, run.Result.State); |
| 343 | Check.Equal(1, output.DisposeCalls); |
| 344 | Check.Equal(JobState.Completed, observed.Last().State); |
| 345 | } |
| 346 | |
| 347 | private sealed class ThrowingInputs : IReadOnlyList<Stream> |
| 348 | { |
| 349 | public int Count => 1; |
| 350 | public Stream this[int index] => throw new IOException("테스트 입력 복사 실패"); |
| 351 | public IEnumerator<Stream> GetEnumerator() => throw new IOException("테스트 입력 복사 실패"); |
| 352 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); |
| 353 | } |
| 354 | } |