diff --git a/docs/error-ingestion-design.md b/docs/error-ingestion-design.md index e9fcbcab6b..93d7cec8ae 100644 --- a/docs/error-ingestion-design.md +++ b/docs/error-ingestion-design.md @@ -63,6 +63,8 @@ When `BodyStoredExternally` is true the external copy is authoritative and `Body search aid only; it must never be served as the body. `BodySize` is always the original size. External writes happen before the row that points at them is committed. +Error ingestion resolves the unique message id to a GUID once, before the external write. It parses a valid GUID in `ServiceControl.Retry.UniqueMessageId` and converts any other value with `DeterministicGuid.MakeId(value)`, matching Audit ingestion. Without that header, it derives the GUID from the message id and processing endpoint. The external body id uses the canonical string representation of the database `UniqueMessageId`, so a malformed header value never becomes a file path. + ### Groups, endpoints, retention - **Failure groups** live in `FailedMessageGroups`, an association table. A message's group rows diff --git a/docs/message-body-storage.md b/docs/message-body-storage.md index 404bc4fb9e..de2cddbf1d 100644 --- a/docs/message-body-storage.md +++ b/docs/message-body-storage.md @@ -29,7 +29,7 @@ Ingestion writes external bodies before the batch transaction that inserts the r Audit stores a body through `IAuditBodyStoragePersistence` under the UTC ingestion hour of its batch and the unique message id: `yyyyMMddHH/{unique message id}`. The file system store writes `{StoragePath}/yyyyMMddHH/{unique message id}.body`, the Azure Blob store uses the blob name `yyyyMMddHH/{unique message id}`, and the S3 store prepends its key prefix. Callers pass the hour explicitly and the stores do not parse it from the id, so reads use the `CreatedOn` of the row. Storage keeps the first write for an hour and id and ignores later writes. -The body URL keeps the audit body id, `yyyyMMddHH-{unique message id}`, which routes the request to the row. The Error (primary) persisters use `IBodyStoragePersistence` with the body id alone; their file system layout remains `{StoragePath}/{body id}.body`. +The body URL keeps the audit body id, `yyyyMMddHH-{unique message id}`, which routes the request to the row. The Error (primary) persisters use `IBodyStoragePersistence` with the body id alone; their file system layout remains `{StoragePath}/{body id}.body`. Both file system stores validate body ids with `Guid.TryParse` before file system access and throw `ArgumentException` for invalid ids. Audit requires a GUID. Error accepts a GUID or `failedimport-{guid}`, the id of a failed import body. Reading a body streams it from storage with the stored content type, size, and a version derived from the row. A body missing from storage answers 204. diff --git a/src/ServiceControl.Audit.Persistence.EFCore/Implementation/BodyStorage/AuditFileSystemBodyStorage.cs b/src/ServiceControl.Audit.Persistence.EFCore/Implementation/BodyStorage/AuditFileSystemBodyStorage.cs index 7270626b14..cb89d1224e 100644 --- a/src/ServiceControl.Audit.Persistence.EFCore/Implementation/BodyStorage/AuditFileSystemBodyStorage.cs +++ b/src/ServiceControl.Audit.Persistence.EFCore/Implementation/BodyStorage/AuditFileSystemBodyStorage.cs @@ -19,10 +19,10 @@ public class AuditFileSystemBodyStorage(FileSystemBodyStorageSettings settings) public async Task WriteBody(string bodyId, DateTime createdOn, ReadOnlyMemory body, string contentType, CancellationToken cancellationToken = default) { - Directory.CreateDirectory(HourDirectory(createdOn)); - var filePath = GetBodyFilePath(createdOn, bodyId); + Directory.CreateDirectory(HourDirectory(createdOn)); + if (File.Exists(filePath)) { return; @@ -163,7 +163,15 @@ public async Task DeleteBodiesForDay(DateTime day, CancellationToken cancellatio string HourDirectory(DateTime hour) => Path.Combine(StoragePath, AuditBodyStorageKey.HourPrefix(hour)); - string GetBodyFilePath(DateTime createdOn, string bodyId) => Path.Combine(StoragePath, $"{AuditBodyStorageKey.For(createdOn, bodyId)}.body"); + string GetBodyFilePath(DateTime createdOn, string bodyId) + { + if (!Guid.TryParse(bodyId, out _)) + { + throw new ArgumentException("The body id must be a GUID.", nameof(bodyId)); + } + + return Path.Combine(StoragePath, $"{AuditBodyStorageKey.For(createdOn, bodyId)}.body"); + } static void TryDelete(string filePath) { diff --git a/src/ServiceControl.Audit.Persistence.Tests/EFCore/AuditFileSystemBodyStorageTests.cs b/src/ServiceControl.Audit.Persistence.Tests/EFCore/AuditFileSystemBodyStorageTests.cs index 7b307b64ab..f0edcb04d7 100644 --- a/src/ServiceControl.Audit.Persistence.Tests/EFCore/AuditFileSystemBodyStorageTests.cs +++ b/src/ServiceControl.Audit.Persistence.Tests/EFCore/AuditFileSystemBodyStorageTests.cs @@ -13,18 +13,30 @@ namespace ServiceControl.Audit.Persistence.Tests.EFCore; [TestFixture] class AuditFileSystemBodyStorageTests { + const string BodyId = "6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10"; + const string BodyA = "a0000000-0000-4000-8000-00000000000a"; + const string BodyB = "b0000000-0000-4000-8000-00000000000b"; + const string BodyC = "c0000000-0000-4000-8000-00000000000c"; + const string BodyD = "d0000000-0000-4000-8000-00000000000d"; + string tempDir; + string outsideDir; AuditFileSystemBodyStorage store; [SetUp] public void SetUp() { tempDir = Directory.CreateTempSubdirectory("sc-body-tests-").FullName; + outsideDir = Directory.CreateTempSubdirectory("sc-body-outside-").FullName; store = new AuditFileSystemBodyStorage(new FileSystemBodyStorageSettings { StoragePath = tempDir, MinCompressionSize = 64 }); } [TearDown] - public void TearDown() => Directory.Delete(tempDir, recursive: true); + public void TearDown() + { + Directory.Delete(tempDir, recursive: true); + Directory.Delete(outsideDir, recursive: true); + } static readonly DateTime Hour10 = new(2026, 10, 20, 10, 0, 0, DateTimeKind.Utc); static readonly DateTime Hour11 = Hour10.AddHours(1); @@ -34,9 +46,9 @@ public void SetUp() public async Task Round_trips_compressed_and_uncompressed_bodies(int bodyLength) { var body = Encoding.UTF8.GetBytes(new string('a', bodyLength)); - await store.WriteBody("body-1", Hour10, body, "application/json"); + await store.WriteBody(BodyId, Hour10, body, "application/json"); - var result = await store.ReadBody("body-1", Hour10); + var result = await store.ReadBody(BodyId, Hour10); Assert.That(result, Is.Not.Null); using (result.Stream) @@ -52,12 +64,12 @@ public async Task Round_trips_compressed_and_uncompressed_bodies(int bodyLength) } [Test] - public async Task Body_is_stored_in_the_directory_of_its_explicit_hour_whatever_the_id() + public async Task Body_is_stored_in_the_directory_of_its_explicit_hour() { - await store.WriteBody("opaque", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); + await store.WriteBody(BodyId, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); - Assert.That(Relative(), Is.EqualTo(new[] { Path.Combine("2026102010", "opaque.body") })); - var result = await store.ReadBody("opaque", Hour10); + Assert.That(Relative(), Is.EqualTo(new[] { Path.Combine("2026102010", $"{BodyId}.body") })); + var result = await store.ReadBody(BodyId, Hour10); Assert.That(result, Is.Not.Null); result.Stream.Dispose(); } @@ -65,11 +77,11 @@ public async Task Body_is_stored_in_the_directory_of_its_explicit_hour_whatever_ [Test] public async Task Bodies_with_the_same_id_in_different_hours_are_distinct() { - await store.WriteBody("same", Hour10, Encoding.UTF8.GetBytes("ten"), "text/plain"); - await store.WriteBody("same", Hour11, Encoding.UTF8.GetBytes("eleven"), "text/plain"); + await store.WriteBody(BodyId, Hour10, Encoding.UTF8.GetBytes("ten"), "text/plain"); + await store.WriteBody(BodyId, Hour11, Encoding.UTF8.GetBytes("eleven"), "text/plain"); - using var ten = (await store.ReadBody("same", Hour10)).Stream; - using var eleven = (await store.ReadBody("same", Hour11)).Stream; + using var ten = (await store.ReadBody(BodyId, Hour10)).Stream; + using var eleven = (await store.ReadBody(BodyId, Hour11)).Stream; Assert.Multiple(() => { @@ -81,18 +93,18 @@ public async Task Bodies_with_the_same_id_in_different_hours_are_distinct() [Test] public async Task Read_for_another_hour_finds_nothing() { - await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); + await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); - Assert.That(await store.ReadBody("a", Hour11), Is.Null); - Assert.That(await store.ReadBody("a", Hour10.AddDays(-1)), Is.Null); + Assert.That(await store.ReadBody(BodyA, Hour11), Is.Null); + Assert.That(await store.ReadBody(BodyA, Hour10.AddDays(-1)), Is.Null); } [Test] public async Task Read_with_an_unspecified_kind_finds_the_body_of_the_same_clock_hour() { - await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); + await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); - var result = await store.ReadBody("a", DateTime.SpecifyKind(Hour10, DateTimeKind.Unspecified)); + var result = await store.ReadBody(BodyA, DateTime.SpecifyKind(Hour10, DateTimeKind.Unspecified)); Assert.That(result, Is.Not.Null); result.Stream.Dispose(); @@ -101,10 +113,10 @@ public async Task Read_with_an_unspecified_kind_finds_the_body_of_the_same_clock [Test] public async Task Rewriting_a_body_keeps_the_first_write() { - await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("original"), "text/plain"); - await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("different"), "text/plain"); + await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("original"), "text/plain"); + await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("different"), "text/plain"); - using var result = (await store.ReadBody("a", Hour10)).Stream; + using var result = (await store.ReadBody(BodyA, Hour10)).Stream; Assert.That(ReadAll(result), Is.EqualTo(Encoding.UTF8.GetBytes("original"))); } @@ -113,9 +125,9 @@ public async Task Rewriting_a_body_keeps_the_first_write() public async Task Delete_for_hour_removes_only_that_hour() { var body = Encoding.UTF8.GetBytes("payload"); - await store.WriteBody("a", Hour10, body, "text/plain"); - await store.WriteBody("b", Hour10, body, "text/plain"); - await store.WriteBody("a", Hour11, body, "text/plain"); + await store.WriteBody(BodyA, Hour10, body, "text/plain"); + await store.WriteBody(BodyB, Hour10, body, "text/plain"); + await store.WriteBody(BodyA, Hour11, body, "text/plain"); var unrelated = Path.Combine(tempDir, "flat.body"); await File.WriteAllTextAsync(unrelated, "keep"); @@ -123,7 +135,7 @@ public async Task Delete_for_hour_removes_only_that_hour() Assert.Multiple(() => { - Assert.That(Relative(), Is.EquivalentTo(new[] { Path.Combine("2026102011", "a.body"), "flat.body" })); + Assert.That(Relative(), Is.EquivalentTo(new[] { Path.Combine("2026102011", $"{BodyA}.body"), "flat.body" })); Assert.That(Directory.Exists(Path.Combine(tempDir, "2026102010")), Is.False); }); } @@ -131,10 +143,10 @@ public async Task Delete_for_hour_removes_only_that_hour() [Test] public async Task Delete_for_hour_also_removes_temp_files_in_that_hour_only() { - await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); - await store.WriteBody("a", Hour11, Encoding.UTF8.GetBytes("payload"), "text/plain"); - await File.WriteAllTextAsync(Path.Combine(tempDir, "2026102010", "a.body.abc.tmp"), "in progress"); - var otherTemp = Path.Combine(tempDir, "2026102011", "a.body.abc.tmp"); + await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); + await store.WriteBody(BodyA, Hour11, Encoding.UTF8.GetBytes("payload"), "text/plain"); + await File.WriteAllTextAsync(Path.Combine(tempDir, "2026102010", $"{BodyA}.body.abc.tmp"), "in progress"); + var otherTemp = Path.Combine(tempDir, "2026102011", $"{BodyA}.body.abc.tmp"); await File.WriteAllTextAsync(otherTemp, "in progress"); var rootFile = Path.Combine(tempDir, "unrelated.txt"); await File.WriteAllTextAsync(rootFile, "keep"); @@ -153,17 +165,17 @@ public async Task Delete_for_hour_also_removes_temp_files_in_that_hour_only() public async Task Delete_for_day_removes_every_hour_of_that_day_and_no_other() { var body = Encoding.UTF8.GetBytes("payload"); - await store.WriteBody("a", Hour10.Date, body, "text/plain"); - await store.WriteBody("b", Hour10.Date.AddHours(23), body, "text/plain"); - await store.WriteBody("c", Hour10.Date.AddDays(1), body, "text/plain"); - await store.WriteBody("d", Hour10.Date.AddHours(-1), body, "text/plain"); + await store.WriteBody(BodyA, Hour10.Date, body, "text/plain"); + await store.WriteBody(BodyB, Hour10.Date.AddHours(23), body, "text/plain"); + await store.WriteBody(BodyC, Hour10.Date.AddDays(1), body, "text/plain"); + await store.WriteBody(BodyD, Hour10.Date.AddHours(-1), body, "text/plain"); Directory.CreateDirectory(Path.Combine(tempDir, "20261020-unrelated")); await store.DeleteBodiesForDay(Hour10); Assert.Multiple(() => { - Assert.That(Relative(), Is.EquivalentTo(new[] { Path.Combine("2026102100", "c.body"), Path.Combine("2026101923", "d.body") })); + Assert.That(Relative(), Is.EquivalentTo(new[] { Path.Combine("2026102100", $"{BodyC}.body"), Path.Combine("2026101923", $"{BodyD}.body") })); Assert.That(Directory.Exists(Path.Combine(tempDir, "20261020-unrelated")), Is.True); }); } @@ -178,7 +190,7 @@ public void Delete_succeeds_when_nothing_is_stored() [Test] public async Task Delete_honors_cancellation() { - await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); + await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); using var cts = new CancellationTokenSource(); await cts.CancelAsync(); @@ -187,6 +199,40 @@ public async Task Delete_honors_cancellation() Assert.That(Relative(), Has.Length.EqualTo(1)); } + [TestCase(null)] + [TestCase("")] + [TestCase("body-1")] + [TestCase("../6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("..\\6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("/etc/6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("C:\\temp\\6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("failedimport-6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("outside-relative")] + [TestCase("outside-rooted")] + public async Task Invalid_body_ids_are_rejected_without_touching_the_file_system(string bodyId) + { + var outsideFile = Path.Combine(outsideDir, "target.body"); + await File.WriteAllTextAsync(outsideFile, "keep"); + bodyId = bodyId switch + { + "outside-relative" => Path.GetRelativePath(Path.Combine(tempDir, "2026102010"), Path.Combine(outsideDir, "target")), + "outside-rooted" => Path.Combine(outsideDir, "target"), + _ => bodyId + }; + + var write = Assert.ThrowsAsync(() => store.WriteBody(bodyId, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain")); + var read = Assert.ThrowsAsync(() => store.ReadBody(bodyId, Hour10)); + + Assert.Multiple(() => + { + Assert.That(write.ParamName, Is.EqualTo("bodyId")); + Assert.That(read.ParamName, Is.EqualTo("bodyId")); + Assert.That(Directory.GetFileSystemEntries(tempDir), Is.Empty); + Assert.That(Directory.GetFileSystemEntries(outsideDir), Is.EqualTo(new[] { outsideFile })); + Assert.That(File.ReadAllText(outsideFile), Is.EqualTo("keep")); + }); + } + string[] Relative() => Directory.GetFiles(tempDir, "*", SearchOption.AllDirectories).Select(f => Path.GetRelativePath(tempDir, f)).ToArray(); static byte[] ReadAll(Stream stream) diff --git a/src/ServiceControl.Persistence.EFCore/Implementation/BodyStorage/FileSystemBodyStoragePersistence.cs b/src/ServiceControl.Persistence.EFCore/Implementation/BodyStorage/FileSystemBodyStoragePersistence.cs index ba4a043e2b..f6db572b3e 100644 --- a/src/ServiceControl.Persistence.EFCore/Implementation/BodyStorage/FileSystemBodyStoragePersistence.cs +++ b/src/ServiceControl.Persistence.EFCore/Implementation/BodyStorage/FileSystemBodyStoragePersistence.cs @@ -141,7 +141,20 @@ public Task DeleteBodyIfExists(string bodyId, CancellationToken cancellationToke return Task.CompletedTask; } - string GetBodyFilePath(string bodyId) => Path.Combine(StoragePath, $"{bodyId}.body"); + string GetBodyFilePath(string bodyId) + { + const string FailedImportPrefix = "failedimport-"; + var guidText = bodyId is not null && bodyId.StartsWith(FailedImportPrefix, StringComparison.Ordinal) + ? bodyId[FailedImportPrefix.Length..] + : bodyId; + + if (!Guid.TryParse(guidText, out _)) + { + throw new ArgumentException("The body id must be a GUID, optionally prefixed with 'failedimport-'.", nameof(bodyId)); + } + + return Path.Combine(StoragePath, $"{bodyId}.body"); + } static void TryDelete(string filePath) { diff --git a/src/ServiceControl.Persistence.EFCore/Implementation/UnitOfWork/EFRecoverabilityIngestionUnitOfWork.cs b/src/ServiceControl.Persistence.EFCore/Implementation/UnitOfWork/EFRecoverabilityIngestionUnitOfWork.cs index 2b9f37cab5..b8ecdd00e1 100644 --- a/src/ServiceControl.Persistence.EFCore/Implementation/UnitOfWork/EFRecoverabilityIngestionUnitOfWork.cs +++ b/src/ServiceControl.Persistence.EFCore/Implementation/UnitOfWork/EFRecoverabilityIngestionUnitOfWork.cs @@ -17,7 +17,8 @@ public Task RecordFailedProcessingAttempt(MessageContext context, List groups, CancellationToken cancellationToken = default) { - var uniqueMessageId = context.Headers.UniqueId(); + var uniqueMessageIdString = context.Headers.UniqueId(); + var uniqueMessageId = Guid.TryParse(uniqueMessageIdString, out var parsed) ? parsed : DeterministicGuid.MakeId(uniqueMessageIdString); var contentType = context.Headers.GetValueOrDefault(Headers.ContentType, "text/plain"); var bodySize = context.Body.Length; var (bodyText, storeExternally) = MessageBodyClassifier.Classify(context.Headers, context.Body, settings.BodyStorage.MaxBodySizeToStore); @@ -25,7 +26,7 @@ public Task RecordFailedProcessingAttempt(MessageContext context, if (storeExternally) { parentUnitOfWork.RecordBodyWrite( - storagePersistence.WriteBody(uniqueMessageId, context.Body, contentType, cancellationToken)); + storagePersistence.WriteBody(uniqueMessageId.ToString(), context.Body, contentType, cancellationToken)); } var sendingEndpoint = GetMetadata(processingAttempt, "SendingEndpoint"); @@ -33,7 +34,7 @@ public Task RecordFailedProcessingAttempt(MessageContext context, parentUnitOfWork.Record(new RecordedFailedProcessingAttempt { - UniqueMessageId = Guid.Parse(uniqueMessageId), + UniqueMessageId = uniqueMessageId, AttemptedAt = processingAttempt.AttemptedAt, TimeOfFailure = processingAttempt.FailureDetails.TimeOfFailure, Groups = groups, diff --git a/src/ServiceControl.Persistence.Tests/EFCore/EFRecoverabilityIngestionUnitOfWorkTests.cs b/src/ServiceControl.Persistence.Tests/EFCore/EFRecoverabilityIngestionUnitOfWorkTests.cs new file mode 100644 index 0000000000..da12407448 --- /dev/null +++ b/src/ServiceControl.Persistence.Tests/EFCore/EFRecoverabilityIngestionUnitOfWorkTests.cs @@ -0,0 +1,90 @@ +namespace ServiceControl.Persistence.Tests; + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using NServiceBus; +using NServiceBus.Extensibility; +using NServiceBus.Transport; +using NUnit.Framework; +using ServiceControl.MessageFailures; +using ServiceControl.Persistence.EFCore.Abstractions; +using ServiceControl.Persistence.EFCore.Implementation.UnitOfWork; +using ServiceControl.Persistence.Infrastructure; + +// The unit of work is never completed or disposed, so the database, scope and dialect are unused. +[TestFixture] +class EFRecoverabilityIngestionUnitOfWorkTests +{ + const string RetryHeader = "ServiceControl.Retry.UniqueMessageId"; + + InMemoryBodyStoragePersistence storage; + EFRecoverabilityIngestionUnitOfWork unitOfWork; + + [SetUp] + public void SetUp() + { + storage = new InMemoryBodyStoragePersistence(); + var settings = new TestSettings { ConnectionString = "unused", BodyStorage = new FileSystemBodyStorageSettings { StoragePath = "unused" } }; + var parent = new EFIngestionUnitOfWork(null, null, storage, settings, null, TimeProvider.System); + unitOfWork = new EFRecoverabilityIngestionUnitOfWork(parent, storage, settings); + } + + async Task Record(string retryHeaderValue) + { + var headers = new Dictionary + { + [Headers.MessageId] = Guid.NewGuid().ToString(), + [Headers.ProcessingEndpoint] = "Receiver", + [Headers.ContentType] = "application/octet-stream" + }; + if (retryHeaderValue is not null) + { + headers[RetryHeader] = retryHeaderValue; + } + + var context = new MessageContext("native", headers, new byte[] { 1, 2, 3 }, new TransportTransaction(), "receiver", new ContextBag()); + var attempt = new FailedMessage.ProcessingAttempt { Headers = headers }; + + await unitOfWork.RecordFailedProcessingAttempt(context, attempt, []); + + return storage.Written[^1].BodyId; + } + + [TestCase("../traversal")] + [TestCase("not a guid")] + public async Task A_malformed_retry_header_stores_the_body_under_a_deterministic_guid(string value) + { + var first = await Record(value); + var second = await Record(value); + + using (Assert.EnterMultipleScope()) + { + Assert.That(Guid.TryParse(first, out var parsed), Is.True); + Assert.That(parsed, Is.EqualTo(DeterministicGuid.MakeId(value))); + Assert.That(second, Is.EqualTo(first)); + } + } + + [Test] + public async Task A_valid_noncanonical_guid_is_stored_in_canonical_form() + { + var guid = Guid.NewGuid(); + + var bodyId = await Record(guid.ToString("N").ToUpperInvariant()); + + Assert.That(bodyId, Is.EqualTo(guid.ToString())); + } + + [Test] + public async Task A_message_without_a_retry_header_stores_the_body_under_its_derived_guid() + { + var bodyId = await Record(null); + + Assert.That(Guid.TryParse(bodyId, out _), Is.True); + } + + sealed class TestSettings : EFPersisterSettings + { + } +} diff --git a/src/ServiceControl.Persistence.Tests/EFCore/FileSystemBodyStoragePersistenceTests.cs b/src/ServiceControl.Persistence.Tests/EFCore/FileSystemBodyStoragePersistenceTests.cs index 51b7bf5944..40cf1b70e9 100644 --- a/src/ServiceControl.Persistence.Tests/EFCore/FileSystemBodyStoragePersistenceTests.cs +++ b/src/ServiceControl.Persistence.Tests/EFCore/FileSystemBodyStoragePersistenceTests.cs @@ -7,32 +7,42 @@ namespace ServiceControl.Persistence.Tests; using System.Threading.Tasks; using NUnit.Framework; using ServiceControl.Persistence.EFCore.Abstractions; +using ServiceControl.Persistence.EFCore.Entities; using ServiceControl.Persistence.EFCore.Implementation.BodyStorage; [TestFixture] class FileSystemBodyStoragePersistenceTests { + const string BodyId = "6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10"; + const string MissingBodyId = "0b9a1d52-4d7c-4f3e-8a21-5c6e7f8091a2"; + string tempDir; + string outsideDir; FileSystemBodyStoragePersistence store; [SetUp] public void SetUp() { tempDir = Directory.CreateTempSubdirectory("sc-body-tests-").FullName; + outsideDir = Directory.CreateTempSubdirectory("sc-body-outside-").FullName; store = new FileSystemBodyStoragePersistence(new FileSystemBodyStorageSettings { StoragePath = tempDir, MinCompressionSize = 64 }); } [TearDown] - public void TearDown() => Directory.Delete(tempDir, recursive: true); + public void TearDown() + { + Directory.Delete(tempDir, recursive: true); + Directory.Delete(outsideDir, recursive: true); + } [TestCase(11)] [TestCase(100_000)] public async Task Round_trips_compressed_and_uncompressed_bodies(int bodyLength) { var body = Encoding.UTF8.GetBytes(new string('a', bodyLength)); - await store.WriteBody("body-1", body, "application/json"); + await store.WriteBody(BodyId, body, "application/json"); - var result = await store.ReadBody("body-1"); + var result = await store.ReadBody(BodyId); Assert.That(result, Is.Not.Null); using (result.Stream) @@ -50,10 +60,10 @@ public async Task Round_trips_compressed_and_uncompressed_bodies(int bodyLength) [Test] public async Task Rewriting_a_body_keeps_the_first_write() { - await store.WriteBody("body-1", Encoding.UTF8.GetBytes("original"), "text/plain"); - await store.WriteBody("body-1", Encoding.UTF8.GetBytes("different"), "text/plain"); + await store.WriteBody(BodyId, Encoding.UTF8.GetBytes("original"), "text/plain"); + await store.WriteBody(BodyId, Encoding.UTF8.GetBytes("different"), "text/plain"); - var result = await store.ReadBody("body-1"); + var result = await store.ReadBody(BodyId); using (result.Stream) { @@ -64,8 +74,8 @@ public async Task Rewriting_a_body_keeps_the_first_write() [Test] public async Task Missing_body_reads_as_null_and_deletes_quietly() { - Assert.That(await store.ReadBody("missing"), Is.Null); - Assert.DoesNotThrowAsync(() => store.DeleteBodyIfExists("missing")); + Assert.That(await store.ReadBody(MissingBodyId), Is.Null); + Assert.DoesNotThrowAsync(() => store.DeleteBodyIfExists(MissingBodyId)); } [Test] @@ -97,11 +107,71 @@ public async Task Reading_when_the_storage_directory_is_gone_finds_nothing() { Directory.Delete(tempDir, recursive: true); - Assert.That(await store.ReadBody("body-1"), Is.Null); + Assert.That(await store.ReadBody(BodyId), Is.Null); Directory.CreateDirectory(tempDir); } + [Test] + public async Task Failed_import_body_ids_round_trip_and_delete() + { + var bodyId = FailedErrorImportEntity.ExternalBodyId(Guid.Parse(BodyId)); + await store.WriteBody(bodyId, Encoding.UTF8.GetBytes("payload"), "text/plain"); + + Assert.That(File.Exists(Path.Combine(tempDir, $"{bodyId}.body")), Is.True); + var result = await store.ReadBody(bodyId); + Assert.That(result, Is.Not.Null); + using (result.Stream) + { + Assert.That(ReadAll(result.Stream), Is.EqualTo(Encoding.UTF8.GetBytes("payload"))); + } + + await store.DeleteBodyIfExists(bodyId); + + Assert.That(Directory.GetFileSystemEntries(tempDir), Is.Empty); + } + + [TestCase(null)] + [TestCase("")] + [TestCase("body-1")] + [TestCase("../6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("..\\6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("/etc/6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("C:\\temp\\6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("failedimport-")] + [TestCase("failedimport-../x")] + [TestCase("failedimport-..\\x")] + [TestCase("failedimport-6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10/x")] + [TestCase("FAILEDIMPORT-6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("failedimport-failedimport-6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("outside-relative")] + [TestCase("outside-rooted")] + public async Task Invalid_body_ids_are_rejected_without_touching_the_file_system(string bodyId) + { + var outsideFile = Path.Combine(outsideDir, "target.body"); + await File.WriteAllTextAsync(outsideFile, "keep"); + bodyId = bodyId switch + { + "outside-relative" => Path.GetRelativePath(tempDir, Path.Combine(outsideDir, "target")), + "outside-rooted" => Path.Combine(outsideDir, "target"), + _ => bodyId + }; + + var write = Assert.ThrowsAsync(() => store.WriteBody(bodyId, Encoding.UTF8.GetBytes("payload"), "text/plain")); + var read = Assert.ThrowsAsync(() => store.ReadBody(bodyId)); + var delete = Assert.ThrowsAsync(() => store.DeleteBodyIfExists(bodyId)); + + Assert.Multiple(() => + { + Assert.That(write.ParamName, Is.EqualTo("bodyId")); + Assert.That(read.ParamName, Is.EqualTo("bodyId")); + Assert.That(delete.ParamName, Is.EqualTo("bodyId")); + Assert.That(Directory.GetFileSystemEntries(tempDir), Is.Empty); + Assert.That(Directory.GetFileSystemEntries(outsideDir), Is.EqualTo(new[] { outsideFile })); + Assert.That(File.ReadAllText(outsideFile), Is.EqualTo("keep")); + }); + } + static byte[] ReadAll(Stream stream) { using var buffer = new MemoryStream();