Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion docs/curator-handbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion docs/handbuch-kuratoren.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `_`. |
Expand Down
1 change: 1 addition & 0 deletions src/Commonage.Web/Pages/Items/Details.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
3 changes: 3 additions & 0 deletions src/Commonage.Web/Pages/Items/Details.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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!;
Expand All @@ -33,6 +35,7 @@ public async Task<IActionResult> 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}";
Expand Down
33 changes: 33 additions & 0 deletions src/Commonage.Web/Pages/Shared/_DublinCore.cshtml
Original file line number Diff line number Diff line change
@@ -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. *@
<link rel="schema.DC" href="http://purl.org/dc/elements/1.1/" />
<meta name="DC.title" content="@Model.Title" />
@if (Model.Description is not null)
{
<meta name="DC.description" content="@Model.Description" />
}
@if (Model.DateText is not null)
{
<meta name="DC.date" content="@Model.DateText" />
}
@if (Model.Credit is not null)
{
<meta name="DC.creator" content="@Model.Credit" />
}
@if (Model.Rights is not null)
{
<meta name="DC.rights" content="@Model.Rights" />
}
@if (Model.Language is not null)
{
<meta name="DC.language" content="@Model.Language" />
}
@foreach (var subject in Model.Subjects)
{
<meta name="DC.subject" content="@subject" />
}
<meta name="DC.identifier" content="@Model.Identifier" />
@if (Model.Type is not null)
{
<meta name="DC.type" content="@Model.Type" />
}
9 changes: 9 additions & 0 deletions src/Commonage.Web/Pages/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@
{
<link rel="canonical" href="@canonical" />
}
@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. *@
<link rel="alternate" type="application/json" href="@record.JsonAddress" />
@if (identity.AllowSearchEngines)
{
<partial name="_DublinCore" model="record" />
}
}
@if (!isPrivatePage && identity.AllowSearchEngines)
{
var address = Context.Request.BaseAddress();
Expand Down
1 change: 1 addition & 0 deletions src/Commonage.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@
app.MapMediaEndpoints();
app.MapDateCheck();
app.MapPublicFeeds();
app.MapPublicItemJson();
app.MapBrandingEndpoints();
app.MapStaticAssets();
app.MapRazorPages()
Expand Down
123 changes: 123 additions & 0 deletions src/Commonage.Web/Search/PublicItemRecord.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// What a public item says about itself to a program: the JSON at <c>/items/{id}.json</c> 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 <see cref="ArchiveItem"/> later
/// stays private until someone adds it here on purpose.
/// </summary>
/// <param name="Identifier">The address of the item's page.</param>
/// <param name="DateText">The date as written ("circa 1950"); <paramref name="DateFrom"/> and <paramref name="DateTo"/> are the days it can stand for.</param>
/// <param name="Credit">Exactly what the page prints as the credit.</param>
/// <param name="Rights">The address of what others may do with it.</param>
/// <param name="Type">A DCMI type (Image, Sound, Text), only from files visitors get.</param>
/// <param name="Description">Left out, with the files, when the contributor did not agree to sharing beyond the website.</param>
public sealed record PublicItemRecord(
string Identifier,
string Title,
string? Description,
string? DateText,
string? DateFrom,
string? DateTo,
string? Credit,
string? Rights,
string? Language,
IReadOnlyList<string> Subjects,
string? Type,
string Collection,
IReadOnlyList<PublicFileRecord> Files)
{
/// <summary>The page of a visible item. Needs the collection, contribution and tags loaded; the files are the ones visitors may have.</summary>
public static PublicItemRecord From(ArchiveItem item, IReadOnlyCollection<MediaFile> 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);
}

/// <param name="Kind">image, audio or document.</param>
/// <param name="Url">A picture's page-sized copy, a recording's tag-free copy, or a document's first page image.</param>
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);
}

/// <summary>
/// <c>/items/{id}.json</c>. 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 <c>ETag</c> or <c>Last-Modified</c>, because the time of the last edit could be one made during an embargo.
/// </summary>
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<IResult> 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");
}
}
2 changes: 1 addition & 1 deletion tests/Commonage.Tests/EndpointAccessTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading