Files
Khaemhat/tests/Khaemhat.Web.Tests/Files/AttachmentServiceTests.cs
T
Alby96andClaude Opus 5.5 b341ade9e9 feat: attachments, file store and in-house PDF/CSV/XLSX/ZIP writers (#34)
Documents need attachments and generated files (SPEC 9.4) before the UI of
M3 can show them, and the spec forbids external libraries for PDF and
spreadsheets.

- VolumeFileStore keeps files under <data>/files/<COMPANY>/<yyyy>/<guid>,
  writing a .part file in the same folder with size limit and SHA-256, then
  quota and scanner checks (IFileScanner hook, no-op by default).
- attachments table (migration 007) with kind, version series, lock, trash
  and the uploading user; AttachmentService uploads, adds generated files as
  the next version, lists, opens, zips, locks, trashes, restores and purges
  after 30 days (new system job system.attachments-trash).
- FileGenerationService runs IFileGenerator implementations into the store;
  three generators for the fictitious test document (PDF, CSV, XLSX).
- CsvWriter (Italian Excel defaults, formula-injection guard), XlsxWriter,
  ZipStreamWriter and PdfWriter (standard Type1 fonts, WinAnsi, AFM widths,
  JPEG, Flate, xref) only write asynchronously, so they can stream to an
  HTTP response.
- ADR 0021 records versioning, storage layout, PDF scope and CSV defaults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:06:48 +01:00

255 lines
14 KiB
C#

using System.IO.Compression;
using System.Security.Cryptography;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Files;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Jobs;
using Khaemhat.Application.Security;
using Khaemhat.Core.Files;
using Khaemhat.Core.Instance;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Infrastructure.Files;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Files;
/// <summary>
/// Attachments and generated files on a real instance (issue #34): versions, download, trash and purge, locks, limits.
/// </summary>
[TestClass]
public sealed class AttachmentServiceTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
[TestMethod]
public async Task GeneratedAttachment_IsVersioned_AndRegenerateAddsTheNextVersion()
{
await using var fixture = await Fixture.StartAsync();
var (attachments, generation, company) = (fixture.Attachments, fixture.Generation, fixture.Company);
CollectionAssert.AreEqual(
new[] { DemoCsvGenerator.GeneratorCode, DemoPdfGenerator.GeneratorCode, DemoXlsxGenerator.GeneratorCode },
generation.AvailableFor(DemoDocument.Entity).Select(g => g.Code).ToArray());
Assert.IsEmpty(generation.AvailableFor("sales.invoice"));
var v1 = await generation.GenerateAsync(Root, company, DemoDocument.Entity, 7, DemoPdfGenerator.GeneratorCode);
var v2 = await generation.GenerateAsync(Root, company, DemoDocument.Entity, 7, DemoPdfGenerator.GeneratorCode);
await generation.GenerateAsync(Root, company, DemoDocument.Entity, 7, DemoCsvGenerator.GeneratorCode);
await generation.GenerateAsync(Root, company, DemoDocument.Entity, 7, DemoXlsxGenerator.GeneratorCode);
Assert.AreEqual((1, AttachmentKind.Generated, "documento-di-prova-7.pdf"), (v1.Version, v1.Kind, v1.FileName));
Assert.AreEqual((2, "v2", "documento-di-prova-7_v2.pdf"), (v2.Version, v2.VersionLabel, v2.FileName));
Assert.AreEqual((PdfWriter.MediaType, AttachmentPreview.Pdf, DemoPdfGenerator.GeneratorCode), (v2.Mime, v2.Preview, v2.GeneratedBy));
Assert.AreEqual(TestInstance.SuperUser, v2.CreatedBy);
var latest = await attachments.ListAsync(Root, company, DemoDocument.Entity, 7);
Assert.HasCount(3, latest);
Assert.AreEqual(v2.Id, latest.Single(a => a.GeneratedBy == DemoPdfGenerator.GeneratorCode).Id);
Assert.IsTrue(latest.All(a => a.IsLatest));
Assert.AreEqual(3, await attachments.CountAsync(Root, company, DemoDocument.Entity, 7));
var all = await attachments.ListAsync(Root, company, DemoDocument.Entity, 7, includeOlderVersions: true);
Assert.HasCount(4, all);
Assert.IsFalse(all.Single(a => a.Id == v1.Id).IsLatest);
Assert.IsEmpty(await attachments.ListAsync(Root, company, DemoDocument.Entity, 8), "Attachments belong to one record only.");
// The generated PDF is a PDF, and the history records the insert.
await using (var pdf = await attachments.OpenAsync(Root, company, v2.Id))
{
using var reader = new StreamReader(pdf.Content);
var text = await reader.ReadToEndAsync();
StringAssert.StartsWith(text, "%PDF-1.7");
StringAssert.EndsWith(text, "%%EOF\n");
}
await using var unitOfWork = await fixture.Factory.CreateAsync(DatabaseScope.Company(company));
Assert.HasCount(1, await AuditTrail.HistoryAsync(unitOfWork, nameof(Attachment), v2.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)));
Assert.ThrowsExactly<ValidationFailedException>(() => generation.GenerateAsync(Root, company, "sales.invoice", 7, DemoPdfGenerator.GeneratorCode).GetAwaiter().GetResult());
}
[TestMethod]
public async Task Upload_ThenDownload_ReturnsTheSameBytes()
{
await using var fixture = await Fixture.StartAsync();
var (attachments, company) = (fixture.Attachments, fixture.Company);
var content = RandomNumberGenerator.GetBytes(300_000);
var uploaded = await attachments.UploadAsync(Root, company, "sales.invoice", 15, "C:\\Documenti\\ordine cliente.PDF", "text/html", new MemoryStream(content));
var again = await attachments.UploadAsync(Root, company, "sales.invoice", 15, "Ordine Cliente.pdf", null, new MemoryStream(content[..1000]));
Assert.AreEqual(("ordine cliente.PDF", MediaTypes.Pdf, AttachmentKind.Uploaded, 1), (uploaded.Name, uploaded.Mime, uploaded.Kind, uploaded.Version));
Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(content)), uploaded.Sha256);
Assert.AreEqual(content.Length, uploaded.Size);
Assert.AreEqual(2, again.Version, "A file with the same name becomes the next version.");
await using var download = await attachments.OpenAsync(Root, company, uploaded.Id);
using var copy = new MemoryStream();
await download.Content.CopyToAsync(copy);
CollectionAssert.AreEqual(content, copy.ToArray());
Assert.AreEqual(uploaded.Sha256, Convert.ToHexStringLower(SHA256.HashData(copy.ToArray())));
// "Scarica tutto": a ZIP with the latest versions.
var csv = await attachments.UploadAsync(Root, company, "sales.invoice", 15, "righe.csv", null, new MemoryStream("a;b\r\n"u8.ToArray()));
using var zipped = new MemoryStream();
Assert.AreEqual(2, await attachments.WriteZipAsync(Root, company, "sales.invoice", 15, zipped));
using var zip = new ZipArchive(new MemoryStream(zipped.ToArray()), ZipArchiveMode.Read);
CollectionAssert.AreEquivalent(new[] { "Ordine Cliente_v2.pdf", "righe.csv" }, zip.Entries.Select(e => e.FullName).ToArray());
Assert.AreEqual(AttachmentPreview.Csv, csv.Preview);
}
[TestMethod]
public async Task DeletingTheDocument_MovesAttachmentsToTheTrash_AndThePurgeRemovesThemAfter30Days()
{
await using var fixture = await Fixture.StartAsync();
var (attachments, generation, company) = (fixture.Attachments, fixture.Generation, fixture.Company);
var pdf = await generation.GenerateAsync(Root, company, DemoDocument.Entity, 3, DemoPdfGenerator.GeneratorCode);
var photo = await attachments.UploadAsync(Root, company, DemoDocument.Entity, 3, "foto.jpg", null, new MemoryStream(new byte[100]));
var keys = await fixture.StorageKeysAsync();
Assert.IsTrue(keys.All(k => fixture.Store.Exists(company, k)));
Assert.AreEqual(2, await attachments.TrashForEntityAsync(Root, company, DemoDocument.Entity, 3));
Assert.IsEmpty(await attachments.ListAsync(Root, company, DemoDocument.Entity, 3));
CollectionAssert.AreEquivalent(new[] { pdf.Id, photo.Id }, (await attachments.ListTrashAsync(Root, company)).Select(a => a.Id).ToArray());
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => attachments.OpenAsync(Root, company, pdf.Id));
// Restorable within 30 days; deleting one attachment also goes through the trash.
Assert.AreEqual(2, await attachments.RestoreForEntityAsync(Root, company, DemoDocument.Entity, 3));
await attachments.DeleteAsync(Root, company, photo.Id);
await attachments.RestoreAsync(Root, company, photo.Id);
Assert.HasCount(2, await attachments.ListAsync(Root, company, DemoDocument.Entity, 3));
await attachments.TrashForEntityAsync(Root, company, DemoDocument.Entity, 3);
fixture.Clock.Advance(TimeSpan.FromDays(29));
Assert.AreEqual(0, await attachments.PurgeTrashAsync(company));
fixture.Clock.Advance(TimeSpan.FromDays(2));
Assert.AreEqual(2, await attachments.PurgeTrashAsync(company));
Assert.IsEmpty(await fixture.StorageKeysAsync());
Assert.IsTrue(keys.All(k => !fixture.Store.Exists(company, k)));
Assert.IsEmpty(await attachments.ListTrashAsync(Root, company));
}
[TestMethod]
public async Task LockedAttachment_CannotBeDeleted_NorItsDocument()
{
await using var fixture = await Fixture.StartAsync();
var (attachments, company) = (fixture.Attachments, fixture.Company);
var xml = await attachments.AddAsync(
Root, company, "sales.invoice", 21, new AttachmentFile(AttachmentKind.EInvoice, "IT01234567890_00001.xml"),
(output, ct) => output.WriteAsync("<FatturaElettronica/>"u8.ToArray(), ct).AsTask());
var other = await attachments.UploadAsync(Root, company, "sales.invoice", 21, "nota.txt", null, new MemoryStream("x"u8.ToArray()));
await attachments.LockAsync(Root, company, xml.Id);
Assert.IsTrue((await attachments.GetAsync(Root, company, xml.Id))!.Locked);
Assert.AreEqual((MediaTypes.Xml, AttachmentPreview.Xml), (xml.Mime, xml.Preview));
var error = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => attachments.DeleteAsync(Root, company, xml.Id));
CollectionAssert.Contains(error.Errors.ToList(), AttachmentService.LockedError);
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => attachments.TrashForEntityAsync(Root, company, "sales.invoice", 21));
Assert.HasCount(2, await attachments.ListAsync(Root, company, "sales.invoice", 21), "A refused deletion changes nothing.");
await attachments.DeleteAsync(Root, company, other.Id);
Assert.HasCount(1, await attachments.ListAsync(Root, company, "sales.invoice", 21));
}
[TestMethod]
public async Task SizeLimit_IsEnforced_AndUsersStayInTheirCompany()
{
await using var fixture = await Fixture.StartAsync();
var (attachments, company) = (fixture.Attachments, fixture.Company);
var settings = fixture.App.Services.GetRequiredService<SystemSettingsStore>();
Assert.AreEqual(FileLimits.DefaultMaxBytes, (await attachments.GetLimitsAsync()).MaxBytes);
await settings.SetAsync(AttachmentService.MaxUploadSetting, "1");
var error = await Assert.ThrowsExactlyAsync<ValidationFailedException>(
() => attachments.UploadAsync(Root, company, "sales.invoice", 1, "grande.pdf", null, new MemoryStream(new byte[(1024 * 1024) + 1])));
CollectionAssert.Contains(error.Errors.ToList(), AttachmentService.TooLargeError);
Assert.IsEmpty(await attachments.ListAsync(Root, company, "sales.invoice", 1));
Assert.AreEqual(0, (await attachments.GetUsageAsync(Root, company)).Files);
await attachments.UploadAsync(Root, company, "sales.invoice", 1, "giusto.pdf", null, new MemoryStream(new byte[1024 * 1024]));
await Assert.ThrowsExactlyAsync<ValidationFailedException>(
() => attachments.UploadAsync(Root, company, "sales.invoice", 1, "vuoto.pdf", null, new MemoryStream()));
await Assert.ThrowsExactlyAsync<ValidationFailedException>(
() => attachments.UploadAsync(Root, company, "Not An Entity", 1, "a.pdf", null, new MemoryStream(new byte[1])));
var stranger = new Actor("mario", UserLevel.Standard, null, 1, "ALTRA");
await Assert.ThrowsExactlyAsync<AccessDeniedException>(() => attachments.ListAsync(stranger, company, "sales.invoice", 1));
var withoutRoles = new Actor("lucia", UserLevel.Standard, null, 999, company);
await Assert.ThrowsExactlyAsync<AccessDeniedException>(() => attachments.ListAsync(withoutRoles, company, "sales.invoice", 1));
await settings.SetAsync(AttachmentService.MaxUploadSetting, null);
}
[TestMethod]
public async Task TrashPurge_IsASystemTask()
{
await using var fixture = await Fixture.StartAsync();
var scheduler = fixture.App.Services.GetRequiredService<JobScheduler>();
await scheduler.EnsureSystemTasksAsync();
Assert.AreEqual(JobOutcome.Succeeded, await scheduler.RunAsync("system.attachments-trash"));
}
/// <summary>A started instance with an attachment service on a clock the test moves.</summary>
private sealed class Fixture : IAsyncDisposable
{
private Fixture(WebApplication app, string company)
{
App = app;
Company = company;
var services = app.Services;
Factory = services.GetRequiredService<IUnitOfWorkFactory>();
Store = services.GetRequiredService<IFileStore>();
Attachments = new AttachmentService(
Factory, Store, services.GetRequiredService<PermissionService>(), services.GetRequiredService<AuditTrail>(),
services.GetRequiredService<SystemSettingsStore>(), services.GetRequiredService<FileStoreOptions>(), Clock);
Generation = new FileGenerationService(services.GetRequiredService<FileGeneratorRegistry>(), Attachments, services.GetRequiredService<PermissionService>(), Clock);
}
public WebApplication App { get; }
public string Company { get; }
public MovableClock Clock { get; } = new();
public IUnitOfWorkFactory Factory { get; }
public IFileStore Store { get; }
public AttachmentService Attachments { get; }
public FileGenerationService Generation { get; }
public static async Task<Fixture> StartAsync()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
return new Fixture(app, company);
}
public async Task<List<string>> StorageKeysAsync()
{
await using var unitOfWork = await Factory.CreateAsync(DatabaseScope.Company(Company));
return (await unitOfWork.Repository<Attachment, long>().ListAsync(Query.For<Attachment>())).Items.Select(a => a.StorageKey).ToList();
}
public async ValueTask DisposeAsync()
{
await App.StopAsync();
await App.DisposeAsync();
}
}
private sealed class MovableClock : TimeProvider
{
private DateTimeOffset _now = DateTimeOffset.UtcNow;
public void Advance(TimeSpan time) => _now += time;
public override DateTimeOffset GetUtcNow() => _now;
}
}