diff --git a/CHANGELOG.md b/CHANGELOG.md index 73e8989..d7b74bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,17 @@ version may change things that need attention when updating, and these notes say ## Unreleased +### For visitors and other programs + +- **A public item can be read by a program.** Each public item page now names `/items/{number}.json` as an alternate and carries + Dublin Core tags (`DC.title`, `DC.description`, `DC.date`, `DC.creator`, `DC.rights`, `DC.language`, `DC.subject`, `DC.identifier`, + `DC.type`). The JSON has the title, description, the date as written plus its earliest and latest day, credit, rights, language, + tags, collection and, when visitors get the files, their public addresses. It follows the rules of link previews: an item whose + contributor did not agree to sharing beyond the website leaves out description and files, and a record-only item lists no files. + Nothing a curator keeps to themselves, no contributor details and no original file names are in it. An item visitors cannot see + answers "not found", exactly like its page. The answer is kept for ten minutes. With "Let search engines list this archive" off, + the Dublin Core tags are left out and the JSON says `noindex` (the JSON and its link stay, as they are not a search page). After a take-down or a change to what visitors get, an answer already given can stay in a cache for up to ten minutes. + ### For curators - **Read an export into an archive.** "Read an export into this archive" on the Export page (admins) takes the ZIP file of a Commonage diff --git a/docs/curator-handbook.md b/docs/curator-handbook.md index 60c2568..d324c16 100644 --- a/docs/curator-handbook.md +++ b/docs/curator-handbook.md @@ -119,7 +119,12 @@ An item held back wears a badge in the list ("Record only", "Public from ..."), will see. The list can be filtered under **Kept back from visitors**, and many items can be changed together: tick them, choose **Set what visitors get** or **Set the public-from date** and confirm. Only curators can set either, and each change is in the item's history. -Feeds and the sitemap are kept for ten minutes, so a change can take that long to reach everyone. Taking something back from +Each public item also has a machine-readable copy at its address with `.json` added, and its page carries Dublin Core tags, for +libraries and programs that collect archives. It holds only what the page shows (a record-only item lists no files, and an item +whose contributor did not agree to sharing beyond this website lists neither description nor files), and it follows the same +switch as the feed. + +Feeds, the sitemap and that copy are kept for ten minutes, so a change can take that long to reach everyone. Taking something back from people who already saw it is not possible: whoever saved a picture keeps it. ## Working through many items diff --git a/docs/development.md b/docs/development.md index c1be626..04416bb 100644 --- a/docs/development.md +++ b/docs/development.md @@ -142,6 +142,13 @@ the request, so behind Caddy they depend on `ASPNETCORE_FORWARDEDHEADERS_ENABLED tries that setting. Text goes into XML through `XmlText`, because one pasted control character would make a whole feed unreadable. `ArchiveItem.MayTravel` decides what goes along with a link, and it needs the contribution to be loaded. +`Search/PublicItemRecord.cs` is what an item says to programs: `/items/{id}.json` and the `DC.*` tags (`Pages/Shared/_DublinCore.cshtml`, +written by the layout when the page set `ViewData["Record"]`). `PublicItemRecord` is an allow-list: add a field there on purpose, +and never serialise `ArchiveItem` or `MediaFile`. It follows the link-preview rules, so description and files go with `MayTravel`, +and files with `MediaLevel.Everything`. The endpoint answers a hidden item with `Results.NotFound()` and nothing else, so the +re-executed error page makes it identical to the page's own 404; it sets `public, max-age=600` and no `ETag` or `Last-Modified` +on the 200 only. The dates stay as written (`DateText`) next to the earliest and latest day. + ## Photos of an item `MediaFile.Position` orders an item's photos, and the first is its cover. Anything that picks or lists photos must order by diff --git a/docs/handbuch-kuratoren.md b/docs/handbuch-kuratoren.md index ed84ae9..e6331ef 100644 --- a/docs/handbuch-kuratoren.md +++ b/docs/handbuch-kuratoren.md @@ -130,7 +130,12 @@ Besucher sehen. Die Liste lässt sich unter **Vor Besuchern zurückgehalten** fi ankreuzen, **Festlegen, was Besucher bekommen** oder **Öffentlich-ab-Datum festlegen** wählen und bestätigen. Nur Kuratoren können beides einstellen, und jede Änderung steht im Verlauf des Eintrags. -Feed und Sitemap werden zehn Minuten vorgehalten, eine Änderung kann also so lange brauchen, bis sie überall ankommt. Etwas denen +Jeder öffentliche Eintrag hat außerdem unter seiner Adresse mit angehängtem `.json` eine maschinenlesbare Fassung, und seine Seite enthält +Dublin-Core-Angaben, für Bibliotheken und Programme, die Archive einsammeln. Sie enthält nur, was die Seite zeigt (ein Eintrag nur mit +Datensatz nennt keine Dateien, und bei einem Eintrag, dessen Beitragende nicht über diese Website hinaus zugestimmt haben, fehlen +Beschreibung und Dateien), und sie folgt demselben Schalter wie der Feed. + +Feed, Sitemap und diese Fassung werden zehn Minuten vorgehalten, eine Änderung kann also so lange brauchen, bis sie überall ankommt. Etwas denen wieder wegnehmen, die es schon gesehen haben, geht nicht: Wer ein Bild gespeichert hat, behält es. ## Viele Einträge bearbeiten diff --git a/docs/security.md b/docs/security.md index 570f498..1917a67 100644 --- a/docs/security.md +++ b/docs/security.md @@ -33,6 +33,7 @@ vulnerability, see [SECURITY.md](../SECURITY.md). | PDF files | Only curators can add a PDF; contribution links refuse it. A PDF is recognised by `%PDF-` and read by poppler (`pdfinfo`, `pdftoppm`), a large C++ parser, so it runs as separate processes, never inside the app: each call has a time limit (`Uploads:PdfTimeoutSeconds`, 60) and is killed with its children when it takes longer, the size of the drawn picture is set by us with `-scale-to` whatever size the page claims, at most 300 pages are drawn, and no part of the file or its name reaches a command line (arguments are passed as a list, the file is copied to a random name in an owner-only temporary folder that is removed afterwards). Pages are served only for published items; the PDF stays private. Accepted: a hostile PDF made by a curator could still exploit poppler, which runs with the app's rights in the container; build with `WITH_PDF=false` to remove it. `poppler-utils` comes from the distribution at build time and is not pinned to a version, so a rebuild of the same commit can ship another poppler (accepted; the base image digest is pinned). The text of a PDF (`pdftotext`, same limits, control characters removed, at most 200,000 characters) is only matched by search, never shown, and it is in the index only while the item is not in the bin and the PDF is not in the bin; a draft is found only by curators, as before. The preview queue is single, so a very long PDF delays other previews (at most 60 s per page); copies of a PDF left by a stopped app are removed at the next start. | | Uploads | Files are recognised by their content (magic bytes), never by name or browser type, and stored under random names outside the web root. Originals are never changed or served to visitors. Previews are made by libvips, rotated upright and stripped of all metadata. Images over 250 megapixels get no preview (decompression bombs), also for GIF and AVIF (`Images_with_more_pixels_than_the_limit_get_no_preview`). GIF and AVIF (libheif with an AV1 decoder, from M23) are further decoders reachable from a contribution link; a GIF is read as its first frame only. There is no time limit on a decode, so a very large AVIF costs memory and time on a small server; the pixel limit and the three-attempt guard are the protection. Size limits per file and per request. A file that the preview maker fails on, in whatever way, costs only its own preview, and one that takes the app down is given up after three attempts instead of at every start (`PreviewFailureTests`). | | Browser | Strict Content Security Policy (no inline script or style, no framing, no plugins; only the contribution form may show `blob:` images, for the photos someone has chosen on their own device, and a picture opened on its own has no scripts at all but lets the browser's picture view style itself), `nosniff`, `Referrer-Policy: same-origin` (setup links never leak to other sites), `X-Frame-Options`, `Permissions-Policy`, `Cross-Origin-Opener-Policy`. No `Server` header. `SecurityHeaderTests` checks the headers and that no page contains inline script or style, so the policy can stay strict. | +| Public JSON and Dublin Core | `/items/{id}.json` and the `DC.*` tags in the item page are made from `PublicItemRecord`, a record written out field by field (an allow-list; an entity is never serialised), from `VisibleItems` and `VisibleMedia` only. It follows the link-preview rules (`ArchiveItem.MayTravel`: no description, no files otherwise) and lists no files for a record-only item. Never in it: curator-only fields, contribution or contributor data, original file names, hashes, sizes, storage keys, next or previous items, totals. A hidden or unknown item gets the same empty 404 as its page (one `no-store` error page; no 401 or 403), so the address does not show that something exists. The 200 is `public, max-age=600` with no `ETag` or `Last-Modified` (an edit time could come from an embargo), so after a take-down, a withdrawn consent or a change to record-only, a 200 that was already given can stay in a cache for up to ten minutes. "Let search engines list this archive" deliberately does not switch the JSON or the alternate link off: with it off the JSON answers `X-Robots-Tag: noindex` and the `DC.*` tags are left out. Not in the sitemap. `PublicItemJsonTests`, `VisibilityMatrixTests`, `EndpointAccessTests`. | | Beyond the website | The feed, sitemap and link previews hold nothing a public page does not show, and are switched off with "Let search engines list this archive". Contributions that agreed to "this website" only keep their picture and text out of them. | | Output | Razor encodes all text. The CSV export prefixes cells that start with `=`, `+`, `-` or `@`, so contributed text cannot become a spreadsheet formula. | | Database | All queries go through EF Core with parameters; the only raw SQL (`AccentFolding`) contains no input. Contributor search escapes `%` and `_`. | diff --git a/src/Commonage.Web/Pages/Items/Details.cshtml b/src/Commonage.Web/Pages/Items/Details.cshtml index bd1e9e7..c423a7f 100644 --- a/src/Commonage.Web/Pages/Items/Details.cshtml +++ b/src/Commonage.Web/Pages/Items/Details.cshtml @@ -6,6 +6,7 @@ ViewData["Canonical"] = Model.Address; ViewData["Citation"] = Model.Citation; ViewData["LinkPreview"] = Model.Preview; + ViewData["Record"] = Model.Record; ViewData["RecordOnly"] = Model.Item.MediaLevel == MediaLevel.RecordOnly; } diff --git a/src/Commonage.Web/Pages/Items/Details.cshtml.cs b/src/Commonage.Web/Pages/Items/Details.cshtml.cs index e1c8563..c73f09e 100644 --- a/src/Commonage.Web/Pages/Items/Details.cshtml.cs +++ b/src/Commonage.Web/Pages/Items/Details.cshtml.cs @@ -17,6 +17,8 @@ public class DetailsModel(CommonageDbContext db, ArchiveProfile profile, IString public LinkPreview Preview { get; private set; } = null!; + public PublicItemRecord Record { get; private set; } = null!; + public ArchiveItem Item { get; private set; } = null!; public ItemSurroundings Surroundings { get; private set; } = null!; @@ -33,6 +35,7 @@ public async Task OnGetAsync(int id, CancellationToken cancellati return NotFound(); Item = item; + Record = PublicItemRecord.From(item, item.MediaFiles, await profile.GetAsync(), Request.BaseAddress()); Surroundings = await db.LoadSurroundingsAsync(item, cancellationToken); Address = $"{Request.BaseAddress()}/items/{item.Id}"; diff --git a/src/Commonage.Web/Pages/Shared/_DublinCore.cshtml b/src/Commonage.Web/Pages/Shared/_DublinCore.cshtml new file mode 100644 index 0000000..d17e5bd --- /dev/null +++ b/src/Commonage.Web/Pages/Shared/_DublinCore.cshtml @@ -0,0 +1,33 @@ +@model Commonage.Web.Search.PublicItemRecord +@* The simple Dublin Core elements of a public item, as the page says them. Nothing here is not also in the JSON. *@ + + +@if (Model.Description is not null) +{ + +} +@if (Model.DateText is not null) +{ + +} +@if (Model.Credit is not null) +{ + +} +@if (Model.Rights is not null) +{ + +} +@if (Model.Language is not null) +{ + +} +@foreach (var subject in Model.Subjects) +{ + +} + +@if (Model.Type is not null) +{ + +} diff --git a/src/Commonage.Web/Pages/Shared/_Layout.cshtml b/src/Commonage.Web/Pages/Shared/_Layout.cshtml index 833a5f9..2db9150 100644 --- a/src/Commonage.Web/Pages/Shared/_Layout.cshtml +++ b/src/Commonage.Web/Pages/Shared/_Layout.cshtml @@ -25,6 +25,15 @@ { } + @if (ViewData["Record"] is Commonage.Web.Search.PublicItemRecord record) + { + @* Only a page that is visible gets here, so the address of the JSON is not given away for anything else. *@ + + @if (identity.AllowSearchEngines) + { + + } + } @if (!isPrivatePage && identity.AllowSearchEngines) { var address = Context.Request.BaseAddress(); diff --git a/src/Commonage.Web/Program.cs b/src/Commonage.Web/Program.cs index 4529579..ee52a50 100644 --- a/src/Commonage.Web/Program.cs +++ b/src/Commonage.Web/Program.cs @@ -207,6 +207,7 @@ app.MapMediaEndpoints(); app.MapDateCheck(); app.MapPublicFeeds(); +app.MapPublicItemJson(); app.MapBrandingEndpoints(); app.MapStaticAssets(); app.MapRazorPages() diff --git a/src/Commonage.Web/Search/PublicItemRecord.cs b/src/Commonage.Web/Search/PublicItemRecord.cs new file mode 100644 index 0000000..df7a26a --- /dev/null +++ b/src/Commonage.Web/Search/PublicItemRecord.cs @@ -0,0 +1,123 @@ +using System.Globalization; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Unicode; +using Commonage.Web.Data; +using Commonage.Web.Domain; +using Commonage.Web.Operations; +using Microsoft.EntityFrameworkCore; + +namespace Commonage.Web.Search; + +/// +/// What a public item says about itself to a program: the JSON at /items/{id}.json and the Dublin Core tags in the page. +/// Written out field by field (an allow-list), never made from an entity, so a field added to later +/// stays private until someone adds it here on purpose. +/// +/// The address of the item's page. +/// The date as written ("circa 1950"); and are the days it can stand for. +/// Exactly what the page prints as the credit. +/// The address of what others may do with it. +/// A DCMI type (Image, Sound, Text), only from files visitors get. +/// Left out, with the files, when the contributor did not agree to sharing beyond the website. +public sealed record PublicItemRecord( + string Identifier, + string Title, + string? Description, + string? DateText, + string? DateFrom, + string? DateTo, + string? Credit, + string? Rights, + string? Language, + IReadOnlyList Subjects, + string? Type, + string Collection, + IReadOnlyList Files) +{ + /// The page of a visible item. Needs the collection, contribution and tags loaded; the files are the ones visitors may have. + public static PublicItemRecord From(ArchiveItem item, IReadOnlyCollection visibleFiles, ArchiveIdentity identity, string baseAddress) + { + var travels = item.MayTravel; + var files = travels && item.MediaLevel == MediaLevel.Everything + ? visibleFiles.Where(f => f.Status == ProcessingStatus.Ready).OrderBy(f => f.Position).ThenBy(f => f.Id) + .Select(f => PublicFileRecord.From(f, baseAddress)).ToList() + : []; + return new PublicItemRecord( + $"{baseAddress}/items/{item.Id}", + item.Title, + travels && !string.IsNullOrWhiteSpace(item.Description) ? item.Description : null, + item.DateText, + Day(item.DateFrom), + Day(item.DateTo), + item.Credit, + item.RightsUri ?? identity.DefaultRightsUri, + identity.MaterialLanguage, + item.Tags.OrderBy(t => t.Name, StringComparer.Ordinal).Select(t => t.Name).ToList(), + files.Count == 0 ? null : files[0].Kind switch { "audio" => "Sound", "document" => "Text", _ => "Image" }, + item.Collection.Title, + files); + } + + public string JsonAddress => $"{Identifier}.json"; + + private static string? Day(DateOnly? day) => day?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); +} + +/// image, audio or document. +/// A picture's page-sized copy, a recording's tag-free copy, or a document's first page image. +public sealed record PublicFileRecord(string Kind, string Url, string? AltText, string? Caption, int? Pages) +{ + public static PublicFileRecord From(MediaFile file, string baseAddress) => + file.IsAudio ? new("audio", $"{baseAddress}/media/{file.Id}/audio", null, file.Caption, null) + : file.IsPdf && file.PageCount is > 0 ? new("document", $"{baseAddress}/media/{file.Id}/page/1", null, file.Caption, file.PageCount) + : new("image", $"{baseAddress}/media/{file.Id}/preview", file.AltText, file.Caption, null); +} + +/// +/// /items/{id}.json. An item a visitor cannot see answers exactly as its page does (the same empty "not found", which the +/// error page fills in), so the address cannot be used to find out that something exists. The answer is cached for ten minutes +/// like the feed, and carries no ETag or Last-Modified, because the time of the last edit could be one made during an embargo. +/// +public static class PublicItemJson +{ + private const string CacheControl = "public, max-age=600"; + + private static readonly JsonSerializerOptions Options = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + // Any script stays readable. Markup characters are still escaped. + Encoder = JavaScriptEncoder.Create(UnicodeRanges.All), + WriteIndented = true, + }; + + public static void MapPublicItemJson(this WebApplication app) => app.MapGet("/items/{id:int}.json", ServeAsync); + + private static async Task ServeAsync( + int id, HttpContext context, CommonageDbContext db, ArchiveProfile profile, CancellationToken cancellationToken) + { + var item = await db.VisibleItems + .Include(i => i.Collection) + .Include(i => i.Contribution) + .Include(i => i.Tags) + .AsNoTracking() + .FirstOrDefaultAsync(i => i.Id == id, cancellationToken); + if (item is null) + return Results.NotFound(); + + var files = await db.VisibleMedia + .Where(f => f.ArchiveItemId == id && f.Status == ProcessingStatus.Ready) + .OrderBy(f => f.Position).ThenBy(f => f.Id) + .AsNoTracking() + .ToListAsync(cancellationToken); + var identity = await profile.GetAsync(); + var record = PublicItemRecord.From(item, files, identity, context.Request.BaseAddress()); + + context.Response.Headers.CacheControl = CacheControl; + if (!identity.AllowSearchEngines) + context.Response.Headers["X-Robots-Tag"] = "noindex"; + return Results.Json(record, Options, "application/json"); + } +} diff --git a/tests/Commonage.Tests/EndpointAccessTests.cs b/tests/Commonage.Tests/EndpointAccessTests.cs index e8d6f57..1fc4ada 100644 --- a/tests/Commonage.Tests/EndpointAccessTests.cs +++ b/tests/Commonage.Tests/EndpointAccessTests.cs @@ -14,7 +14,7 @@ public class EndpointAccessTests(CommonageAppFactory app) { private static readonly string[] MeantForVisitors = [ - "/", "/Index", "/search", "/items/{id:int}", "/items/{id:int}/tell", "/help", "/collections", "/collections/{id:int}", + "/", "/Index", "/search", "/items/{id:int}", "/items/{id:int}.json", "/items/{id:int}/tell", "/help", "/collections", "/collections/{id:int}", "/{kind:regex(^(places|people)$)}", "/{slug:regex(^(about|contact|privacy|imprint)$)}", "/SetLanguage", "/Error/{code:int?}", // Published pictures only, see MediaTests. diff --git a/tests/Commonage.Tests/PublicItemJsonTests.cs b/tests/Commonage.Tests/PublicItemJsonTests.cs new file mode 100644 index 0000000..5b47974 --- /dev/null +++ b/tests/Commonage.Tests/PublicItemJsonTests.cs @@ -0,0 +1,347 @@ +using System.Net; +using System.Text.Json; +using System.Text.RegularExpressions; +using Commonage.Web.Domain; +using Commonage.Web.Operations; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Commonage.Tests; + +/// The JSON of a public item and its Dublin Core tags: what the page says, for programs, and not a word more. +[Collection(nameof(AppCollection))] +public class PublicItemJsonTests(CommonageAppFactory app) +{ + private sealed class FixedClock(DateTimeOffset now) : TimeProvider + { + public override DateTimeOffset GetUtcNow() => now; + } + + private sealed record Seeded(string Word, int ItemId, string StorageId); + + private async Task SeedAsync( + string kind, Action? state = null, bool consent = true, MediaLevel level = MediaLevel.Everything, bool tagged = false) + { + var word = TestData.UniqueWord(kind); + var storage = Guid.NewGuid(); + return await app.WithDbAsync(async db => + { + var now = DateTime.UtcNow; + var collection = new Collection { Title = $"Box {word}", CreatedAt = now }; + var item = new ArchiveItem + { + Title = $"Title {word}", Description = $"Words {word}", Collection = collection, CreatedAt = now, UpdatedAt = now, + Credit = $"Credit {word}", MediaLevel = level, RightsUri = RightsOptions.CcBy, + RightsHolder = $"Holder {word}", ReferenceNumber = $"Ref {word}", OriginalLocation = $"Attic {word}", + ReceivedFrom = $"Giver {word}", ReceivedOn = $"Received {word}", InternalNotes = $"Notes {word}", NeedsTranscription = true, + Contribution = new Contribution + { + ContributorName = $"Name {word}", ContributorEmail = $"{word}@example.org", ConsentText = $"Consent {word}", + ConsentCoversSharing = consent, SubmittedAt = now, ReferenceCode = $"RC{word}"[..9], + }, + }; + item.SetDateRange($"around {word}", new DateOnly(1948, 1, 1), new DateOnly(1952, 12, 31)); + // Tags are what the search page ranks as popular, so only the tests that read them add one. + if (tagged) + item.SetTags([new Tag { Name = $"Zone {word}", NormalizedName = $"zone {word}", Kind = TagKind.Place }]); + item.MediaFiles.Add(new MediaFile + { + ArchiveItem = item, OriginalFileName = $"original-{word}.jpg", ContentType = "image/jpeg", Sha256 = new string('a', 64), + SizeBytes = 123456789, StorageId = storage, Status = ProcessingStatus.Ready, AltText = $"Alt {word}", Caption = $"Caption {word}", + ExtractedText = $"Pages {word}", + }); + item.Publish(now); + state?.Invoke(item, now); + db.AddRange(collection, item); + await db.SaveChangesAsync(); + return new Seeded(word, item.Id, storage.ToString("N")); + }); + } + + private async Task<(HttpResponseMessage Response, string Body)> GetAsync(HttpClient client, string address) + { + var response = await client.GetAsync(address); + return (response, await response.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task The_json_says_what_the_page_says_and_none_of_what_is_private() + { + var item = await SeedAsync("everything", tagged: true); + using var visitor = app.CreateClient(); + + var (response, body) = await GetAsync(visitor, $"/items/{item.ItemId}.json"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + Assert.Equal("public, max-age=600", response.Headers.CacheControl?.ToString()); + Assert.Null(response.Headers.ETag); + Assert.Null(response.Content.Headers.LastModified); + using var json = JsonDocument.Parse(body); + var root = json.RootElement; + Assert.Equal($"Title {item.Word}", root.GetProperty("title").GetString()); + Assert.Equal($"Words {item.Word}", root.GetProperty("description").GetString()); + Assert.Equal($"around {item.Word}", root.GetProperty("dateText").GetString()); + Assert.Equal("1948-01-01", root.GetProperty("dateFrom").GetString()); + Assert.Equal("1952-12-31", root.GetProperty("dateTo").GetString()); + Assert.Equal($"Credit {item.Word}", root.GetProperty("credit").GetString()); + Assert.Equal(RightsOptions.CcBy, root.GetProperty("rights").GetString()); + Assert.EndsWith($"/items/{item.ItemId}", root.GetProperty("identifier").GetString()); + Assert.Equal($"Box {item.Word}", root.GetProperty("collection").GetString()); + Assert.Equal($"Zone {item.Word}", Assert.Single(root.GetProperty("subjects").EnumerateArray()).GetString()); + Assert.Equal("Image", root.GetProperty("type").GetString()); + var file = Assert.Single(root.GetProperty("files").EnumerateArray()); + Assert.Matches(@"/media/\d+/preview$", file.GetProperty("url").GetString()); + Assert.Equal($"Alt {item.Word}", file.GetProperty("altText").GetString()); + + // Everything a curator or a contributor keeps to themselves, and what names a stored file, is filled in, and none is there. + foreach (var private_ in new[] + { + $"Holder {item.Word}", $"Ref {item.Word}", $"Attic {item.Word}", $"Giver {item.Word}", $"Received {item.Word}", + $"Notes {item.Word}", $"Name {item.Word}", $"{item.Word}@example.org", $"Consent {item.Word}", $"original-{item.Word}", + new string('a', 64), "123456789", item.StorageId, $"Pages {item.Word}", "needsTranscription", "sizeBytes", "sha256", + "originalFileName", "contribution", "next", "previous", "total", + }) + Assert.DoesNotContain(private_, body, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task A_record_only_item_lists_no_files() + { + var item = await SeedAsync("recordonly", level: MediaLevel.RecordOnly); + using var visitor = app.CreateClient(); + + var (response, body) = await GetAsync(visitor, $"/items/{item.ItemId}.json"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using var json = JsonDocument.Parse(body); + Assert.Empty(json.RootElement.GetProperty("files").EnumerateArray()); + Assert.False(json.RootElement.TryGetProperty("type", out _)); + Assert.Equal($"Words {item.Word}", json.RootElement.GetProperty("description").GetString()); + Assert.DoesNotContain($"Alt {item.Word}", body); + Assert.DoesNotContain($"Caption {item.Word}", body); + Assert.DoesNotContain("/media/", body); + } + + [Fact] + public async Task An_item_that_may_not_travel_leaves_out_its_description_and_files_in_the_json_and_the_tags() + { + var item = await SeedAsync("notravel", consent: false); + using var visitor = app.CreateClient(); + + var (_, body) = await GetAsync(visitor, $"/items/{item.ItemId}.json"); + var (_, page) = await GetAsync(visitor, $"/items/{item.ItemId}"); + + using var json = JsonDocument.Parse(body); + Assert.Equal($"Title {item.Word}", json.RootElement.GetProperty("title").GetString()); + Assert.False(json.RootElement.TryGetProperty("description", out _)); + Assert.Empty(json.RootElement.GetProperty("files").EnumerateArray()); + Assert.DoesNotContain($"Words {item.Word}", body); + Assert.Contains("name=\"DC.title\"", page); + Assert.DoesNotContain("name=\"DC.description\"", page); + Assert.DoesNotContain("name=\"DC.type\"", page); + } + + [Fact] + public async Task Whatever_a_visitor_may_not_see_answers_exactly_as_if_it_did_not_exist() + { + var hidden = new List + { + await SeedAsync("draft", (i, _) => i.Status = ItemStatus.Draft), + await SeedAsync("binned", (i, now) => i.MoveToBin(now)), + await SeedAsync("embargoed", (i, now) => i.SetPublicFrom(DateOnly.FromDateTime(now).AddDays(3), now)), + await SeedAsync("rejected", (i, _) => i.Status = ItemStatus.Rejected), + await SeedAsync("withdrawn", (i, _) => i.Status = ItemStatus.Withdrawn), + await SeedAsync("submitted", (i, _) => i.Status = ItemStatus.Submitted), + }; + using var visitor = app.CreateClient(); + var (missingResponse, missingBody) = await GetAsync(visitor, "/items/2000000000.json"); + + Assert.Equal(HttpStatusCode.NotFound, missingResponse.StatusCode); + Assert.Contains("no-store", missingResponse.Headers.CacheControl?.ToString()); + foreach (var item in hidden) + { + var (response, body) = await GetAsync(visitor, $"/items/{item.ItemId}.json"); + var (pageResponse, _) = await GetAsync(visitor, $"/items/{item.ItemId}"); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, pageResponse.StatusCode); + Assert.Equal(WithoutTokens(missingBody), WithoutTokens(body)); + Assert.Equal(Headers(missingResponse), Headers(response)); + Assert.DoesNotContain(item.Word, body); + } + + // The page of an item that is not there has no alternate link and no tags to give it away either. + Assert.DoesNotContain("application/json", missingBody); + Assert.DoesNotContain("DC.", missingBody); + } + + // Every page carries a form token that is new with each response. + private static string WithoutTokens(string page) => Regex.Replace(page, "value=\"[^\"]{40,}\"", "value=\"\""); + + private static string Headers(HttpResponseMessage response) => string.Join('\n', + response.Headers.Concat(response.Content.Headers).Where(h => h.Key is not ("Date" or "Set-Cookie")).OrderBy(h => h.Key, StringComparer.Ordinal) + .Select(h => $"{h.Key}: {string.Join(',', h.Value)}")); + + [Fact] + public async Task An_embargoed_item_is_not_there_today_and_is_there_tomorrow() + { + var item = await SeedAsync("tomorrow", (i, now) => i.SetPublicFrom(new DateOnly(2031, 5, 10), now)); + async Task StatusAtAsync(DateTimeOffset utc) + { + await using var archive = app.WithWebHostBuilder(b => b.ConfigureTestServices(s => s.AddSingleton(new FixedClock(utc)))); + using var visitor = archive.CreateClient(); + return (await visitor.GetAsync($"/items/{item.ItemId}.json")).StatusCode; + } + + Assert.Equal(HttpStatusCode.NotFound, await StatusAtAsync(new DateTimeOffset(2031, 5, 9, 12, 0, 0, TimeSpan.Zero))); + Assert.Equal(HttpStatusCode.OK, await StatusAtAsync(new DateTimeOffset(2031, 5, 10, 12, 0, 0, TimeSpan.Zero))); + } + + [Fact] + public async Task The_page_names_the_json_and_carries_the_dublin_core_tags_only_when_it_is_visible() + { + var shown = await SeedAsync("tags", tagged: true); + var draft = await SeedAsync("tagsdraft", (i, _) => i.Status = ItemStatus.Draft); + using var visitor = app.CreateClient(); + + var (_, page) = await GetAsync(visitor, $"/items/{shown.ItemId}"); + var (_, hiddenPage) = await GetAsync(visitor, $"/items/{draft.ItemId}"); + + Assert.Matches($"""""", page); + Assert.Contains($"""""", page); + Assert.Contains($"""""", page); + Assert.Contains($"""""", page); + Assert.Contains($"""""", page); + Assert.Contains($"""""", page); + Assert.Contains($"""""", page); + Assert.Contains("""""", page); + Assert.Matches($"""""", page); + Assert.DoesNotContain("DC.", hiddenPage); + Assert.DoesNotContain("application/json", hiddenPage); + Assert.DoesNotContain($"Ref {shown.Word}", page); + } + + [Fact] + public async Task With_search_engines_off_the_json_says_noindex_and_the_page_has_no_dublin_core() + { + var item = await SeedAsync("noengines"); + using var visitor = app.CreateClient(); + var before = await app.WithDbAsync(db => db.ArchiveSettings.AsNoTracking().FirstOrDefaultAsync()); + await SetAllowAsync(false); + try + { + var (response, _) = await GetAsync(visitor, $"/items/{item.ItemId}.json"); + var (_, page) = await GetAsync(visitor, $"/items/{item.ItemId}"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("noindex", Assert.Single(response.Headers.GetValues("X-Robots-Tag"))); + Assert.DoesNotContain("DC.", page); + Assert.Matches(new Regex("""rel="alternate" type="application/json"""), page); + } + finally + { + await SetAllowAsync(before?.AllowSearchEngines ?? true); + } + + async Task SetAllowAsync(bool allow) + { + await app.WithDbAsync(async db => + { + var settings = await db.ArchiveSettings.FirstOrDefaultAsync(); + if (settings is null) + db.ArchiveSettings.Add(settings = new ArchiveSettings()); + settings.AllowSearchEngines = allow; + return await db.SaveChangesAsync(); + }); + app.Services.GetRequiredService().Forget(); + } + } + + [Fact] + public async Task Hostile_text_is_encoded_in_the_tags_and_other_scripts_stay_readable_in_the_json() + { + const string Attack = "\"> & 'x'\nsecond line"; + const string Arabic = "مرحبا بالعالم"; + const string Cjk = "東京の写真 中文"; + var item = await SeedAsync("hostile", (i, _) => + { + i.Title = $"{Attack} {Arabic}"; + i.Description = $"{Attack} {Cjk}"; + }); + using var visitor = app.CreateClient(); + + var (_, page) = await GetAsync(visitor, $"/items/{item.ItemId}"); + var (_, body) = await GetAsync(visitor, $"/items/{item.ItemId}.json"); + + var tags = string.Concat(Regex.Matches(page, "]*>").Select(m => m.Value)); + Assert.Contains("DC.title", tags); + Assert.Contains("DC.description", tags); + Assert.DoesNotContain("\">alert", tags); + Assert.DoesNotContain("", tags); + Assert.Contains("<script>", tags); + Assert.Contains(""", tags); + + // Nothing readable is escaped, and what could break out of a page that embeds the JSON is. + Assert.Contains(Arabic, body); + Assert.Contains(Cjk, body); + Assert.DoesNotContain("\\u0645", body, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("\\u6771", body, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain('<', body); + Assert.DoesNotContain('>', body); + Assert.DoesNotContain('&', body); + Assert.DoesNotContain('\'', body); + Assert.Contains("\\u003C", body, StringComparison.OrdinalIgnoreCase); + Assert.Contains("\\u0026", body); + Assert.Contains("\\u0027", body); + using var json = JsonDocument.Parse(body); + Assert.Equal($"{Attack} {Arabic}", json.RootElement.GetProperty("title").GetString()); + Assert.Equal($"{Attack} {Cjk}", json.RootElement.GetProperty("description").GetString()); + } + + [Fact] + public async Task Only_a_ready_file_that_is_not_in_the_bin_is_listed() + { + var item = await SeedAsync("filestates", (i, now) => + { + MediaFile Extra(string alt, ProcessingStatus status) => new() + { + ArchiveItem = i, OriginalFileName = $"{alt}.jpg", ContentType = "image/jpeg", Sha256 = new string('b', 64), SizeBytes = 10, + StorageId = Guid.NewGuid(), Status = status, AltText = alt, + }; + var binned = Extra("AltBinned", ProcessingStatus.Ready); + binned.DeletedAt = now; + i.MediaFiles.Add(binned); + i.MediaFiles.Add(Extra("AltPending", ProcessingStatus.Pending)); + i.MediaFiles.Add(Extra("AltFailed", ProcessingStatus.Failed)); + i.MediaFiles.Add(Extra("AltReady", ProcessingStatus.Ready)); + }); + using var visitor = app.CreateClient(); + + var (_, body) = await GetAsync(visitor, $"/items/{item.ItemId}.json"); + + using var json = JsonDocument.Parse(body); + var alts = json.RootElement.GetProperty("files").EnumerateArray().Select(f => f.GetProperty("altText").GetString()).ToList(); + Assert.Equal(2, alts.Count); + Assert.Contains($"Alt {item.Word}", alts); + Assert.Contains("AltReady", alts); + } + + [Fact] + public async Task The_sitemap_does_not_list_the_json() + { + var item = await SeedAsync("sitemap"); + using var visitor = app.CreateClient(); + + var (response, body) = await GetAsync(visitor, "/sitemap.xml"); + + if (response.StatusCode == HttpStatusCode.OK) + { + Assert.Contains($"/items/{item.ItemId}<", body); + Assert.DoesNotContain(".json", body); + } + } +} diff --git a/tests/Commonage.Tests/VisibilityMatrixTests.cs b/tests/Commonage.Tests/VisibilityMatrixTests.cs index 2f4f94c..8a75431 100644 --- a/tests/Commonage.Tests/VisibilityMatrixTests.cs +++ b/tests/Commonage.Tests/VisibilityMatrixTests.cs @@ -67,6 +67,7 @@ public async Task Only_published_items_show_up_anywhere_a_visitor_can_look() foreach (var address in Addresses) everything.Append(await TextAsync(visitor, string.Format(address, marked.Word))); everything.Append(await TextAsync(visitor, $"/items/{marked.ItemId}")); + everything.Append(await TextAsync(visitor, $"/items/{marked.ItemId}.json")); everything.Append(await TextAsync(visitor, $"/collections/{marked.CollectionId}")); } var text = everything.ToString();