using System.Security.Cryptography; using Febe.Core.Library; using Febe.Tests.Support; namespace Febe.Tests.Library; [TestClass] public sealed class SafeFileWriterTests { private static byte[] Content(int size, int seed = 1) { var bytes = new byte[size]; new Random(seed).NextBytes(bytes); return bytes; } [TestMethod] public async Task WritesTheFileWithItsHashAndPublicationTime() { using var temp = new TempFolder(); var content = Content(300_000); var published = new DateTimeOffset(2024, 5, 6, 7, 8, 9, TimeSpan.Zero); var saved = await new SafeFileWriter().SaveAsync(new MemoryStream(content), temp.Path, "post/2024/foto_1.jpg", new SafeWriteOptions { LastWriteTime = published }); Assert.AreEqual("post/2024/foto_1.jpg", saved.RelativePath); Assert.AreEqual(Path.Combine(temp.Path, "post", "2024", "foto_1.jpg"), saved.FullPath); CollectionAssert.AreEqual(content, await File.ReadAllBytesAsync(saved.FullPath)); Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(content)), saved.Sha256); Assert.AreEqual(content.Length, saved.Bytes); Assert.IsTrue(saved.LastWriteTimeSet); Assert.AreEqual(published.UtcDateTime, File.GetLastWriteTimeUtc(saved.FullPath)); Assert.IsEmpty(Directory.GetFiles(temp.Path, "*.part", SearchOption.AllDirectories)); } [TestMethod] public async Task NeverOverwritesAnExistingFile() { using var temp = new TempFolder(); var writer = new SafeFileWriter(); var first = await writer.SaveAsync(new MemoryStream(Content(10, 1)), temp.Path, "post/a.jpg"); var second = await writer.SaveAsync(new MemoryStream(Content(10, 2)), temp.Path, "post/a.jpg"); var third = await writer.SaveAsync(new MemoryStream(Content(10, 3)), temp.Path, "post/a.jpg"); Assert.AreEqual("post/a.jpg", first.RelativePath); Assert.AreEqual("post/a (2).jpg", second.RelativePath); Assert.AreEqual("post/a (3).jpg", third.RelativePath); CollectionAssert.AreEqual(Content(10, 1), await File.ReadAllBytesAsync(first.FullPath), "Il primo file è rimasto com'era."); } [TestMethod] public async Task ConcurrentWritesToTheSameNameAllSurvive() { using var temp = new TempFolder(); var writer = new SafeFileWriter(); var results = await Task.WhenAll(Enumerable.Range(0, 12).Select(i => Task.Run(() => writer.SaveAsync(new MemoryStream(Content(5000, i)), temp.Path, "storie/x.mp4")))); Assert.AreEqual(12, results.Select(r => r.RelativePath).Distinct().Count()); foreach (var (result, i) in results.Select((r, i) => (r, i))) { CollectionAssert.AreEqual(Content(5000, i), await File.ReadAllBytesAsync(result.FullPath)); } } [TestMethod] public async Task UsesATemporaryNameWhileWriting() { using var temp = new TempFolder(); string[]? during = null; var stream = new ObservingStream(Content(1_000_000), 400_000, () => during = Directory.GetFiles(Path.Combine(temp.Path, "post"))); await new SafeFileWriter().SaveAsync(stream, temp.Path, "post/finale.jpg"); Assert.IsNotNull(during); Assert.HasCount(1, during); Assert.IsTrue(SafeFileWriter.IsTemporaryFile(during[0]), during[0]); Assert.StartsWith(".febe-", Path.GetFileName(during[0])); Assert.IsTrue(File.Exists(Path.Combine(temp.Path, "post", "finale.jpg"))); } [TestMethod] public async Task AnInterruptedDownloadLeavesNoFile() { using var temp = new TempFolder(); var broken = new ObservingStream(Content(1_000_000), 300_000, () => throw new IOException("Connessione interrotta")); await Assert.ThrowsExactlyAsync(() => new SafeFileWriter().SaveAsync(broken, temp.Path, "post/finale.jpg")); Assert.IsFalse(File.Exists(Path.Combine(temp.Path, "post", "finale.jpg"))); Assert.IsEmpty(Directory.GetFiles(temp.Path, "*", SearchOption.AllDirectories)); } [TestMethod] public async Task ACancelledDownloadLeavesNoFile() { using var temp = new TempFolder(); using var cancel = new CancellationTokenSource(); var stream = new ObservingStream(Content(1_000_000), 300_000, cancel.Cancel); await Assert.ThrowsAsync(() => new SafeFileWriter().SaveAsync(stream, temp.Path, "storie/v.mp4", ct: cancel.Token)); Assert.IsEmpty(Directory.GetFiles(temp.Path, "*", SearchOption.AllDirectories)); } [TestMethod] public async Task ATooLargeFileIsDropped() { using var temp = new TempFolder(); await Assert.ThrowsExactlyAsync(() => new SafeFileWriter().SaveAsync(new MemoryStream(Content(500_000)), temp.Path, "post/v.mp4", new SafeWriteOptions { MaxBytes = 200_000 })); Assert.IsEmpty(Directory.GetFiles(temp.Path, "*", SearchOption.AllDirectories)); } [TestMethod] public async Task TheNameCanDependOnTheHash() { using var temp = new TempFolder(); var content = Content(2048); var saved = await new SafeFileWriter().SaveAsync(new MemoryStream(content), temp.Path, "profilo", d => $"profilo/{d.Sha256[..8]}_{d.Bytes}.jpg"); Assert.AreEqual($"profilo/{Convert.ToHexStringLower(SHA256.HashData(content))[..8]}_2048.jpg", saved.RelativePath); } [TestMethod] public async Task LongNamesAreShortenedAndUnsafeNamesCleaned() { using var temp = new TempFolder(); var writer = new SafeFileWriter(); var name = "evidenza/" + new string('t', 200) + "/" + new string('n', 200) + "_1.jpg"; var saved = await writer.SaveAsync(new MemoryStream(Content(10)), temp.Path, name); Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, saved.FullPath.Length); Assert.EndsWith(".jpg", saved.RelativePath); var reserved = await writer.SaveAsync(new MemoryStream(Content(10)), temp.Path, "post/CON.jpg"); Assert.AreEqual("post/CON_.jpg", reserved.RelativePath); // «..» is not a valid name on Windows: it becomes «_», so nothing can be written outside the folder. var escape = await writer.SaveAsync(new MemoryStream(Content(10)), temp.Path, "../fuori/a.jpg"); Assert.AreEqual("_/fuori/a.jpg", escape.RelativePath); Assert.StartsWith(temp.Path, escape.FullPath); } [TestMethod] public void CleanupRemovesOnlyTemporaryFiles() { using var temp = new TempFolder(); Directory.CreateDirectory(temp.Combine("post")); File.WriteAllText(temp.Combine("post", ".febe-abc123.part"), "x"); File.WriteAllText(temp.Combine(".febe-def456.part"), "x"); File.WriteAllText(temp.Combine("post", "foto.jpg"), "x"); File.WriteAllText(temp.Combine("post", "foto.part"), "x"); Assert.AreEqual(2, SafeFileWriter.CleanupTemporaryFiles(temp.Path)); Assert.IsTrue(File.Exists(temp.Combine("post", "foto.jpg"))); Assert.IsTrue(File.Exists(temp.Combine("post", "foto.part"))); } /// A stream that runs an action once, after a given number of bytes has been read. private sealed class ObservingStream(byte[] data, int triggerAt, Action action) : MemoryStream(data) { private bool _fired; public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) { if (!_fired && Position >= triggerAt) { _fired = true; action(); } await Task.Yield(); cancellationToken.ThrowIfCancellationRequested(); return await base.ReadAsync(buffer[..Math.Min(buffer.Length, 64 * 1024)], cancellationToken); } } }