using System.Globalization; using System.IO.Compression; using System.Net; using System.Net.Http.Json; using Helpdesk.Application.Catalogs; using Helpdesk.Application.Issues; using Helpdesk.Infrastructure.Persistence; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using static Helpdesk.IntegrationTests.BackendFixture; namespace Helpdesk.IntegrationTests; public sealed class AttachmentTests(BackendFixture fixture) : IClassFixture { [Fact] public async Task AttachmentsRespectFormatAndAccessAndFailedBatchesAreNotSaved() { using var anonymous = fixture.CreateClient(); using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken); var authorUser = await fixture.RegisterAsync(anonymous); var otherUser = await fixture.RegisterAsync(anonymous); using var author = fixture.CreateClient((await LoginAsync(anonymous, authorUser.Email)).AccessToken); using var other = fixture.CreateClient((await LoginAsync(anonymous, otherUser.Email)).AccessToken); var categories = await ReadAsync(author.GetAsync("/api/v1/issue-categories", Cancellation)); var png = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6t1sAAAAASUVORK5CYII="); using var createForm = new MultipartFormDataContent(); createForm.Add(new StringContent("Rozbitý zámek"), "title"); createForm.Add(new StringContent("Dveře nelze odemknout."), "description"); createForm.Add(new StringContent(categories[0].Id.ToString(CultureInfo.InvariantCulture)), "categoryId"); AddFile(createForm, "zamek.png", png); await using var scope = fixture.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); var store = scope.ServiceProvider.GetRequiredService(); try { var issue = await ReadAsync(author.PostAsync("/api/v1/issues", createForm, Cancellation), HttpStatusCode.Created); var pngAttachment = Assert.Single(issue.Attachments); var download = $"/api/v1/attachments/{pngAttachment.Id}"; using var fetched = await author.GetAsync(download, Cancellation); Assert.Equal(HttpStatusCode.OK, fetched.StatusCode); Assert.Equal("image/png", fetched.Content.Headers.ContentType?.MediaType); Assert.Equal("nosniff", Assert.Single(fetched.Headers.GetValues("X-Content-Type-Options"))); Assert.Equal(png, await fetched.Content.ReadAsByteArrayAsync(Cancellation)); await ExpectAsync(other.GetAsync(download, Cancellation), HttpStatusCode.Forbidden); var path = $"/api/v1/issues/{issue.Id}/attachments"; using var mixed = new MultipartFormDataContent(); AddFile(mixed, "spravny.pdf", "%PDF-1.7\n%%EOF"u8.ToArray()); AddFile(mixed, "podvrzeny.png", "obsah nemá formát PNG"u8.ToArray()); await ExpectAsync(author.PostAsync(path, mixed, Cancellation), HttpStatusCode.BadRequest); using var wrongField = new MultipartFormDataContent(); wrongField.Add(new ByteArrayContent(png), "image", "zamek.png"); await ExpectAsync(author.PostAsync(path, wrongField, Cancellation), HttpStatusCode.BadRequest); var afterFailure = await ReadAsync(author.GetAsync($"/api/v1/issues/{issue.Id}", Cancellation)); Assert.Equal(issue.RowVersion, afterFailure.RowVersion); Assert.Equal(pngAttachment.Id, Assert.Single(afterFailure.Attachments).Id); using var files = new MultipartFormDataContent(); AddFile(files, "protokol.pdf", "%PDF-1.7\n%%EOF"u8.ToArray()); AddFile(files, "fotka.jpg", [0xff, 0xd8, 0xff, 0xd9]); AddFile(files, "fotka.heic", [0, 0, 0, 20, .. "ftypmif1"u8, 0, 0, 0, 0, .. "heic"u8]); AddFile(files, "protokol.docx", Docx()); var added = await ReadAsync(admin.PostAsync(path, files, Cancellation)); Assert.Equal(["application/pdf", "image/jpeg", "image/heic", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"], added.Select(item => item.ContentType)); var key = await db.Attachments.Where(item => item.Id == pngAttachment.Id).Select(item => item.StoredFileName).SingleAsync(Cancellation); store.Delete(key); await ExpectAsync(author.GetAsync(download, Cancellation), HttpStatusCode.NotFound); } finally { foreach (var key in await db.Attachments.Select(item => item.StoredFileName).ToListAsync(CancellationToken.None)) store.Delete(key); } } private static void AddFile(MultipartFormDataContent form, string name, byte[] bytes) => form.Add(new ByteArrayContent(bytes), "files", name); private static byte[] Docx() { using var stream = new MemoryStream(); using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) { using (var contentTypes = zip.CreateEntry("[Content_Types].xml").Open()) contentTypes.Write(""u8); using (var document = zip.CreateEntry("word/document.xml").Open()) document.Write(""u8); } return stream.ToArray(); } }