using System.Globalization; using System.Net.Mime; using Khaemhat.Application.Files; using Khaemhat.Application.Security; using Khaemhat.Web.Security; namespace Khaemhat.Web.Hosting; /// /// The addresses that send files to the browser (SPEC ยง9.4, mockup 024-025): an attachment, all the attachments of a /// record as ZIP, a file generated on the fly (print preview). The services check company and permissions; only PDF /// and common images open in the browser, everything else is downloaded. /// public static class FileEndpoints { /// The content security policy of a file opened in the browser: framed by this site only, no scripts. public const string InlinePolicy = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; object-src 'self'; frame-ancestors 'self'"; /// The base address. public const string BasePath = "/files"; /// The address of an attachment, opened in the browser when it can be. /// The attachment. /// The address relative to the application. public static string View(long id) => BasePath[1..] + "/" + id.ToString(CultureInfo.InvariantCulture); /// The address that downloads an attachment. /// The attachment. /// The address relative to the application. public static string Download(long id) => View(id) + "?download=1"; /// The address of the ZIP with all the attachments of a record. /// The entity. /// The record. /// The address relative to the application. public static string Zip(string entity, long entityId) => BasePath[1..] + "/zip?entity=" + Uri.EscapeDataString(entity) + "&id=" + entityId.ToString(CultureInfo.InvariantCulture); /// The address of a file generated on the fly, without attaching it. /// The entity. /// The record. /// The generator code. /// Whether to download it instead of opening it. /// The address relative to the application. public static string Generated(string entity, long entityId, string generator, bool download = false) => BasePath[1..] + "/generate?entity=" + Uri.EscapeDataString(entity) + "&id=" + entityId.ToString(CultureInfo.InvariantCulture) + "&generator=" + Uri.EscapeDataString(generator) + (download ? "&download=1" : string.Empty); /// Whether a media type may be shown by the browser instead of downloaded. /// The media type. /// for PDF and common images. public static bool OpensInBrowser(string mime) => MediaTypes.PreviewOf(mime) is AttachmentPreview.Pdf or AttachmentPreview.Image; /// Maps the addresses. /// The application. public static void MapFiles(this IEndpointRouteBuilder endpoints) { endpoints.MapGet(BasePath + "/{id:long}", (HttpContext context, long id, AttachmentService attachments) => RunAsync(context, async actor => { var file = await attachments.OpenAsync(actor, Company(actor), id, context.RequestAborted).ConfigureAwait(false); context.Response.RegisterForDisposeAsync(file); return Send(context, file.Content, file.Attachment.Mime, file.Attachment.FileName); })); endpoints.MapGet(BasePath + "/zip", (HttpContext context, string entity, long id, AttachmentService attachments) => RunAsync(context, async actor => { // Read the list first: missing rights fail before the download starts. var company = Company(actor); var list = await attachments.ListAsync(actor, company, entity, id, cancellationToken: context.RequestAborted).ConfigureAwait(false); var name = MediaTypes.CleanFileName(entity.Replace('.', '-') + "-" + id.ToString(CultureInfo.InvariantCulture) + "-allegati.zip"); return list.Count == 0 ? Results.NotFound() : Results.Stream(output => attachments.WriteZipAsync(actor, company, entity, id, output, context.RequestAborted), MediaTypes.Zip, name); })); endpoints.MapGet(BasePath + "/generate", (HttpContext context, string entity, long id, string generator, FileGenerationService files) => RunAsync(context, async actor => { var content = new MemoryStream(); context.Response.RegisterForDisposeAsync(content); var (name, mime) = await files.WriteAsync(actor, Company(actor), entity, id, generator, content, context.RequestAborted).ConfigureAwait(false); content.Position = 0; return Send(context, content, mime, name); })); } private static string Company(Actor actor) => actor.CompanyCode ?? throw new AccessDeniedException(SecurityErrors.PermissionDenied, "Files belong to a company: choose one first."); private static async Task RunAsync(HttpContext context, Func> action) { if (SessionCookie.ActorOf(context.User) is not { } actor) { return Results.Unauthorized(); } try { return await action(actor).ConfigureAwait(false); } catch (AccessDeniedException) { return Results.StatusCode(StatusCodes.Status403Forbidden); } catch (ValidationFailedException ex) when (ex.Errors.Contains(AttachmentService.NotFoundError)) { return Results.NotFound(); } catch (ValidationFailedException) { return Results.BadRequest(); } } private static IResult Send(HttpContext context, Stream content, string mime, string fileName) { var download = context.Request.Query.ContainsKey("download") || !OpensInBrowser(mime); if (download) { return Results.File(content, mime, fileName, enableRangeProcessing: true); } var disposition = new ContentDisposition { Inline = true, FileName = fileName }; context.Response.Headers.ContentDisposition = disposition.ToString(); context.Response.Headers.CacheControl = "private, no-store"; // Shown inside the preview of this site only: no scripts, no other framing site. context.Response.Headers.ContentSecurityPolicy = InlinePolicy; context.Response.Headers.XFrameOptions = "SAMEORIGIN"; return Results.File(content, mime, enableRangeProcessing: true); } }