carlos / platform Public

console: /fleet/legal publishes documents and sets the letterhead

Task 3 of the DPA acceptance plan (spec 3.1, 3.4, 3.6, 3.7). The
operator page lists published versions of the DPA, terms and privacy
policy, publishes a new one (fetched once with the guarded client, the
DPA text checked canonical and stored, its SHA-256 pinned), lists the
accounts with a DPA in force, and saves the letterhead with an optional
PNG or checked SVG logo.

First dpa applies on publishing; first terms/privacy is a baseline with
an entered date; a later dpa that needs notice applies at least 35 days
on. Both writes are gated session, CSRF, operatorOnly, write limit, then
step-up; an uploaded logo is folded into the form so the step-up replay
keeps it. Copy rows DPA-C44 to DPA-C93; claim, perf, route and parity
censuses updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 61ef5ba18140823d7fd50178128e30ed49466eb9 parent 3fe1205
16 files changed, +1,578 −4
  • docs/parity.md +1 −0
  • internal/console/approved_dpa_copy_test.go +11 −0
  • internal/console/claim_invariant_fixtures_test.go +3 −0
  • internal/console/claim_invariant_probes_nonapp_test.go +33 −0
  • internal/console/claim_invariant_probes_read_test.go +1 −0
  • internal/console/oplegal.go +686 −0
  • internal/console/oplegal_test.go +691 −0
  • internal/console/opshell.go +1 −0
  • internal/console/opshell_test.go +2 −2
  • internal/console/opshots_test.go +1 −0
  • internal/console/routedecls.go +6 −0
  • internal/console/server.go +10 −2
  • internal/console/templates/ops_legal.html +126 −0
  • internal/console/testdata/claim-routes.txt +3 −0
  • internal/console/testdata/perf-budgets.txt +2 −0
  • parity/parity.tsv +1 −0

Intent

Human

<task-notification> <task-id>a4f37797b22525a8e</task-id> <tool-use-id>toolu_01CW7eEYnpENRLfwv95axnV4</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/260ddc60-0dfc-4cf8-8857-7688d6275097/tasks/a4f37797b22525a8e.output</output-file> <status>completed</status> <summary>Agent "Implement Task 2: guarded fetch" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE Commit: 3fe12054 "console: refuse a legal fragment ending in "&lt;" and hrefs with format chars". The commit landed even though git printed the stale `packed-refs.lock` error again. Tests: `go test ./internal/console -run 'TestFetchLegal|TestCanonicalAgreement' -count=1` passes. I did not re-run `go vet` and `gofmt` after the final one-word comment edit. They were clean on the code just before it. Changes: - **Trailing `&lt;` or `&lt;/`:** `canonicalAgreement` now refuses "unclosed tag" when the input ends in either. `&lt;p&gt;x&lt;/p&gt;&lt;` and `&lt;p&gt;x&lt;/p&gt;&lt;/` are in the refuse table. - **Format characters in hrefs:** `agreementHref` refuses an href containing a Unicode format character. The U+202E case is now a closed `&lt;a href="/‮x"&gt;t&lt;/a&gt;`, so the href is what gets judged. It expects "link /?x". Concerns: none. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/dpa-and-retention/.superpowers/sdd/2026-11-25-dpa-acceptance/task-2-report.md</result> <usage><subagent_tokens>61918</subagent_tokens><tool_uses>2</tool_uses><duration_ms>70272</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>adaabf29449af7d98</task-id> <tool-use-id>toolu_018jZqrLf5PnLdF5RKSYBTyD</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/260ddc60-0dfc-4cf8-8857-7688d6275097/tasks/adaabf29449af7d98.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 2 fix round 2" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Findings 1. **ADDRESSED.** At `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/dpa-and-retention/internal/console/legalfetch.go:113`, `canonicalAgreement` now returns "unclosed tag" when the input ends in `&lt;` or `&lt;/` (via `bytes.HasSuffix`). Both cases are in the refuse table at `legalfetch_test.go:146-147` (`&lt;p&gt;x&lt;/p&gt;&lt;` and `&lt;p&gt;x&lt;/p&gt;&lt;/`). I checked the case that matters with html.Parse: `&lt;/` followed by `\n&lt;/div&gt;` becomes a bogus comment that swallows `&lt;/div`, so the div never closes and the form ends up inside it. That input is now refused. Against this suffix the trailing `&lt;` turns out harmless (the `&lt;\n` stays text), but refusing it is the right conservative call. 2. **ADDRESSED.** At `legalfetch.go:162`, `agreementHref` now refuses any rune in `unicode.Cf`. The test at `legalfetch_test.go:145` is now a closed `&lt;a href="/\u202ex"&gt;t&lt;/a&gt;` that expects the error "link /?x". That message can only come from the href check. Before the fix this input was accepted (the href starts with `/` and not `//`), so the test now catches the href for the right reason. `go test ./internal/console -run TestCanonicalAgreement -count=1` passes at 3fe12054. ### EOF family probes Each input was wrapped as `"&lt;div&gt;" + input + "\n&lt;/div&gt;\n&lt;form method=\"post\" action=\"/x\"&gt;"` and passed through html.Parse, using a verbatim copy of `canonicalAgreement` at 3fe12054. - `&lt;p&gt;x&lt;/p&gt;&amp;`: accepted, harmless (text `&amp;`) - `&lt;p&gt;x&lt;/p&gt;&amp;am`: accepted, harmless (text `&amp;am`) - `&lt;p&gt;x&lt;/p&gt;&amp;amp`: accepted, harmless (text `&amp;`; Go and the parser agree) - `&lt;p&gt;x&lt;/p&gt;&amp;#`: accepted, harmless (text) - `&lt;p&gt;x&lt;/p&gt;&amp;#x`: accepted, harmless (text `&amp;#x`) - `&lt;p&gt;x&lt;/p&gt;&amp;#x4`: accepted, harmless (text U+0004; affects text only, not markup) - `&lt;p&gt;x &amp;lt`: refused (`unclosed &lt;p&gt;`) - `&lt;p&gt;x&lt;/p&gt;&lt;!`: refused (comment); unrefused it would swallow `&lt;/div` - `&lt;p&gt;x&lt;/p&gt;&lt;?`: refused (comment); unrefused it would swallow `&lt;/div` - `&lt;p&gt;x&lt;/p&gt;&lt;!-`: refused (comment); unrefused it would swallow `&lt;/div` - `&lt;p&gt;x&lt;/p&gt;&lt;!--` and `&lt;!--x--`: refused (comment); unrefused they would swallow the whole suffix, form included - `&lt;p&gt;x&lt;/p&gt;&lt;`: refused (unclosed tag); harmless against this suffix anyway - `&lt;p&gt;x&lt;/p&gt;&lt;/`: refused (unclosed tag); unrefused it would swallow `&lt;/div` - `&lt;p&gt;x&lt;/p&gt;&lt; `: accepted, harmless (text) - `&lt;p&gt;x&lt;/p&gt;&lt;\t`: accepted, harmless (text) - `&lt;p&gt;x&lt;/p&gt;&lt;/ `: refused (comment) - `&lt;p&gt;x&lt;/p&gt;&lt;/&gt;`: refused (comment) - `&lt;p&gt;x&lt;/p&gt;&lt;a`: refused (unclosed tag); unrefused the parser builds `&lt;a &lt;="" div=""&gt;` around the form - `&lt;p&gt;x&lt;/p&gt;y&lt;a`: refused (unclosed tag) - `&lt;p&gt;x&lt;/p&gt;&lt;/p`, `&lt;/a`, `&lt;br`, `&lt;br/`: refused (unclosed tag) - `&lt;p&gt;x&lt;/p&gt;&lt;\r`, `&lt;\n`, `&lt;\r\n`: accepted, harmless (text) - `&lt;p&gt;x&lt;/p&gt;&lt;/\r`, `&lt;/\n`: refused (comment) - `&lt;p&gt;x&lt;/p&gt;\r` and `&lt;p&gt;x&lt;/p&gt;&lt;p&gt;x\r&lt;/p&gt;`: accepted, harmless (CR is normalised to LF) - `&lt;p&gt;x&lt;/p&gt;&lt;\x00` and `&lt;p&gt;x&lt;/p&gt;\x00`: accepted, harmless (text) - `&lt;p&gt;x&lt;/p&gt;&lt; /`, `&lt;=`, `&lt;1`, `&lt;\xff`: accepted, harmless (text) - `&lt;p&gt;x&lt;/p&gt;&lt;&lt;`: refused (unclosed tag) No accepted input in this family was harmful. ### New Issues in the Fix Diff None. ### Out-of-Scope Observations - The `agreementHref` doc comment (`legalfetch.go:159-161`) says a browser "strips or rewrites" all the refused characters. For Unicode format characters that isn't accurate: the URL parser percent-encodes them rather than stripping them. Refusing them is still correct; only the comment's reason is loose. The extended comment line is also longer than the lines around it. Both are cosmetic. - Character references are harmless only because the suffix starts with `\n`. If the template ever put an alphanumeric character or `;` straight after the fragment, a trailing `&amp;am` or `&amp;#x` could join with it. This changes text only, never markup. ### Verdict **Fix round:** Clean</result> <usage><subagent_tokens>52010</subagent_tokens><tool_uses>6</tool_uses><duration_ms>151493</duration_ms></usage> </task-notification>

Attributed to this commit: 18.0 g CO₂e (2,182,646 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on dpa-and-retention, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/parity.md b/docs/parity.md
index a7988f9da..e2ad6c381 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -423,6 +423,7 @@ Discussion #1289.
| op-alert-links | operator | | `GET /alerts/confirm/{token}`<br>`POST /alerts/confirm/{token}`<br>`GET /alerts/unsubscribe/{token}`<br>`POST /alerts/unsubscribe/{token}`<br>`GET /alerts/snooze/{token}`<br>`POST /alerts/snooze/{token}` | Links in fleet alert emails; the token is the credential. |
| op-protection | operator | | `GET /fleet/protection`<br>`GET /fleet/protection/data` | The fleet-wide protection view. |
| op-backups | operator | | `GET /fleet/backups` | What the nightly restore tests found, region by region. |
+| op-legal | operator | | `GET /fleet/legal`<br>`/fleet/legal/publish`<br>`/fleet/legal/letterhead` | Publishing legal documents, the letterhead, and the accounts with a DPA in force. |
| op-architecture | operator | `status [--instances,--layout]` | `GET /fleet/boxes`<br>`/fleet/architecture`<br>`/fleet/architecture/refresh` | The console shows counts and the map, not one row per instance. |
| op-status-live | operator | `status [--live]` | `GET /fleet/boxes` | What every box reported. |
| op-store-approvals | operator | `store approvals`<br>`store approve`<br>`store decline` | `GET /fleet/store`<br>`POST /fleet/store/{account}/{decision}` | Deciding storage applications. |
diff --git a/internal/console/approved_dpa_copy_test.go b/internal/console/approved_dpa_copy_test.go
index 490844f76..5c362bb4b 100644
--- a/internal/console/approved_dpa_copy_test.go
+++ b/internal/console/approved_dpa_copy_test.go
@@ -22,6 +22,17 @@ const (
// named test must exist.
var dpaCopyBuilt = map[string]bool{
// Tasks 3, 5, 6 and 7 add their ids here as they write the text.
+ // Task 3: /fleet/legal (opl.*).
+ "DPA-C44": true, "DPA-C45": true, "DPA-C46": true, "DPA-C47": true, "DPA-C48": true,
+ "DPA-C49": true, "DPA-C50": true, "DPA-C51": true, "DPA-C52": true, "DPA-C53": true,
+ "DPA-C54": true, "DPA-C55": true, "DPA-C56": true, "DPA-C57": true, "DPA-C58": true,
+ "DPA-C59": true, "DPA-C60": true, "DPA-C61": true, "DPA-C62": true, "DPA-C63": true,
+ "DPA-C64": true, "DPA-C65": true, "DPA-C66": true, "DPA-C67": true, "DPA-C68": true,
+ "DPA-C69": true, "DPA-C70": true, "DPA-C71": true, "DPA-C72": true, "DPA-C73": true,
+ "DPA-C74": true, "DPA-C75": true, "DPA-C76": true, "DPA-C77": true, "DPA-C78": true,
+ "DPA-C79": true, "DPA-C80": true, "DPA-C81": true, "DPA-C82": true, "DPA-C83": true,
+ "DPA-C84": true, "DPA-C85": true, "DPA-C86": true, "DPA-C87": true, "DPA-C88": true,
+ "DPA-C89": true, "DPA-C90": true, "DPA-C91": true, "DPA-C92": true, "DPA-C93": true,
}
func parseDPACopyDeck(t *testing.T) []navCopyRow {
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 3d84d36a5..f1cf2cb5d 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -774,6 +774,8 @@ var claimFixtures = map[string]claimFixture{
"route /fleet/alerts/connectors/{id}/test": claimNonApp("operator sends a fleet alert connector a test; one that gets through " +
"confirms a webhook and lifts a suspension (alert_connectors)"),
"route /fleet/alerts/rules/{rule}": claimNonApp("operator sets a fleet alert rule: alert_rules and alert_subscriptions rows"),
+ "route /fleet/legal/publish": claimNonApp("operator publishes a legal document version: one legal_documents row, fetched from the operator's own site; names no app"),
+ "route /fleet/legal/letterhead": claimNonApp("operator saves the letterhead: one letterhead row; names no app"),
// ---- DELETE ----
// Alias-only detach is intentionally unsupported (claimUnsupported); the
@@ -998,6 +1000,7 @@ var claimFixtures = map[string]claimFixture{
"route GET /fleet/protection": claimRead("operator protection page: the edge days of every fleet and the root boxes, read from the bucket; writes nothing"),
"route GET /fleet/protection/data": claimRead("the operator protection page as JSON; writes nothing"),
"route GET /fleet/backups": claimRead("operator restore tests page: instance records, status objects and the restore-test reader's records; writes nothing"),
+ "route GET /fleet/legal": claimRead("operator legal page: legal documents, the letterhead and live DPA acceptances; SQLite only, writes nothing"),
"route GET /fleet/store": claimRead("operator entitlement queue page"),
"route GET /healthz": claimRead("answers ok and the build"),
"route GET /invite/{token}": claimRead("shows an invitation; joining is the POST"),
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go
index 1f76f6830..3fdcc977a 100644
--- a/internal/console/claim_invariant_probes_nonapp_test.go
+++ b/internal/console/claim_invariant_probes_nonapp_test.go
@@ -13,6 +13,7 @@ import (
"fmt"
"github.com/carlosframework/platform/internal/hostactors"
"net/http"
+ "net/http/httptest"
"net/url"
"strconv"
"strings"
@@ -399,6 +400,38 @@ var claimNonAppProbes = map[string]claimProbe{
return ""
},
},
+ // ---- legal documents and the letterhead (oplegal.go) ----
+ "route /fleet/legal/publish": {
+ // The terms' baseline, fetched from a site the legal client trusts.
+ setup: func(t *testing.T, cx *claimCase) {
+ srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte("census terms"))
+ }))
+ t.Cleanup(srv.Close)
+ cx.srv.legalHTTP = legalTestClient(srv)
+ cx.vars["legalsite"] = srv.URL
+ },
+ do: claimFormReply("/fleet/legal/publish", "kind", "terms", "version", "census", "url", "<legalsite>/terms/",
+ "summary", "census", "effective", "2026-01-01"),
+ status: http.StatusSeeOther, loc: "/fleet/legal",
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ if cx.sqlCount(t, `SELECT COUNT(*) FROM legal_documents WHERE kind = 'terms' AND version = 'census' AND needs_notice = 0`) != 1 {
+ return "no census terms baseline"
+ }
+ return ""
+ },
+ },
+ "route /fleet/legal/letterhead": {
+ do: claimFormReply("/fleet/legal/letterhead", "entity", "Shop Limited", "office", "1 Main Street", "number", "123",
+ "signatory", "For Shop Limited", "privacy", "privacy@example.com"),
+ status: http.StatusSeeOther, loc: "/fleet/legal",
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ if cx.sqlCount(t, `SELECT COUNT(*) FROM letterhead WHERE entity = 'Shop Limited'`) != 1 {
+ return "no census letterhead"
+ }
+ return ""
+ },
+ },
"route POST /alerts/confirm/{token}": {
setup: claimWorldAlertLinks,
do: claimAlertDoorPost("/alerts/confirm/<alertconfirm>"),
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go
index d155f594e..c96c8da03 100644
--- a/internal/console/claim_invariant_probes_read_test.go
+++ b/internal/console/claim_invariant_probes_read_test.go
@@ -239,6 +239,7 @@ var claimReadProbes = map[string]claimProbe{
"route GET /fleet/protection": claimPageRead(nil, "/fleet/protection", "<h1>Protection</h1>"),
"route GET /fleet/protection/data": claimPageRead(nil, "/fleet/protection/data", `"unreadable_fleets"`),
"route GET /fleet/backups": claimPageRead(nil, "/fleet/backups", "<h1>Backups</h1>"),
+ "route GET /fleet/legal": claimPageRead(nil, "/fleet/legal", "<h1>Legal</h1>"),
"route GET /fleet/store": claimPageRead(claimWorldApply, "/fleet/store", "<h1>Storage requests</h1>"),
"route GET /healthz": claimPageRead(nil, "/healthz", "ok"),
"route GET /static/{hash}/{file...}": claimPageRead(nil, assetURL("rastrillo/tokens.css"), "--rst-"),
diff --git a/internal/console/oplegal.go b/internal/console/oplegal.go
new file mode 100644
index 000000000..3fa32fe8e
--- /dev/null
+++ b/internal/console/oplegal.go
@@ -0,0 +1,686 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/xml"
+ "errors"
+ "io"
+ "log"
+ "mime"
+ "net/http"
+ "net/url"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+ "unicode"
+ "unicode/utf8"
+)
+
+// The operator's legal page (/fleet/legal, DPA and retention spec §3.1,
+// §3.4, §3.6, §3.7): the published versions of the data processing
+// agreement, the terms and the privacy policy, a form to publish one, the
+// accounts with a DPA in force, and the letterhead. operatorOnly, like every
+// /fleet page; both writes also need a fresh step-up.
+//
+// Publishing fetches the document once with the guarded client
+// (legalfetch.go) and pins its SHA-256. A dpa's agreement text must pass
+// canonicalAgreement and is stored as fetched; it is never shown here.
+
+// The kinds of legal document, in the order the page offers them, and each
+// one's name.
+var legalKinds = []string{"dpa", "terms", "privacy"}
+
+var legalKindLabel = map[string]string{
+ "dpa": "Data processing agreement",
+ "terms": "Terms",
+ "privacy": "Privacy policy",
+}
+
+// The page's messages (DPA copy deck, opl.*).
+const (
+ legalErrFloor = "A change that needs notice applies at least 35 days after publishing."
+ legalErrExists = "That version is already published. Give the new one its own version."
+ legalErrLogo = "The logo must be a PNG or SVG under 200 KB, with no scripts or links."
+ legalLetterheadOK = "Letterhead saved. New acceptances use it; earlier ones keep theirs."
+ // legalErrForm is storeFormCSRF's sentence, for a form missing a field
+ // or carrying one the page cannot use.
+ legalErrForm = "Could not read the form. Please try again."
+)
+
+// legalFetchText is opl.publish.err.fetch: which is the address that could
+// not be fetched, reason fetchLegalText's category.
+func legalFetchText(which string, reason error) string {
+ return "Couldn't fetch " + which + ": " + reason.Error() + "."
+}
+
+// legalCanonicalText is opl.publish.err.canonical, with canonicalAgreement's
+// error as what.
+func legalCanonicalText(what error) string {
+ return "The agreement text has " + what.Error() + ", which isn't allowed. It may only use headings, paragraphs, lists, links and emphasis."
+}
+
+// legalPublishedText is opl.publish.done. The kind's name sits mid-sentence,
+// so its first letter is lowered.
+func legalPublishedText(kind, version string) string {
+ name := legalKindLabel[kind]
+ if r, n := utf8.DecodeRuneInString(name); n > 0 {
+ name = string(unicode.ToLower(r)) + name[n:]
+ }
+ return "Published " + name + " version " + version + "."
+}
+
+const (
+ // legalNoticeFloor is the least time from publishing a version that
+ // needs notice to its effective date: 30 days of notice and 5 for
+ // delivery (spec §3.1).
+ legalNoticeFloor = 35 * 24 * time.Hour
+ // legalFormMax is the most of a /fleet/legal form read: a logo at its
+ // limit, as a file or as the base64 a step-up replays, and the fields.
+ legalFormMax = 1 << 20
+ // letterheadLogoMax is the largest logo, in bytes.
+ letterheadLogoMax = 200 << 10
+ // legalDateLayout is an <input type="date"> value.
+ legalDateLayout = "2006-01-02"
+ // legalLogoField carries an uploaded logo as base64 in the form, so a
+ // step-up's stash, which keeps only form values, replays it.
+ legalLogoField = "logo_data"
+)
+
+// Field limits, in characters.
+const (
+ legalVersionMax = 64
+ legalURLMax = 2048
+ legalSummaryMax = 2000
+ letterheadMax = 200
+ letterheadLong = 500
+)
+
+// legalDraft is the publish form as typed, shown again when it is refused.
+type legalDraft struct {
+ Version, URL, BodyURL, Summary, Effective string
+ NoNotice bool
+}
+
+// legalPublishForm is the publish form for one kind. Mode is "first-dpa"
+// (no dpa yet: it applies on publishing), "later-dpa" (an effective date,
+// or no notice), "baseline" (no row of a terms or privacy kind yet: only the
+// version in force, with the date it took effect) or "later" (notice, or
+// none).
+type legalPublishForm struct {
+ Kind, Mode string
+ Tabs opTabs
+ Draft legalDraft
+}
+
+// legalDocRow is one row of the published versions.
+type legalDocRow struct {
+ Kind, Version, URL, Published, Applies, SHA256, Short string
+ at time.Time
+ id int64
+}
+
+// legalAcceptRow is one account with a DPA in force.
+type legalAcceptRow struct {
+ Account, Sqid, LegalName, Country, Accepted, InForce, AcceptedBy string
+ When time.Time
+}
+
+// legalLetterheadForm is the letterhead form's values: the current
+// letterhead, or what was typed when a save is refused.
+type legalLetterheadForm struct {
+ Entity, Office, Number, VAT, Signatory, Privacy, Footer string
+}
+
+// legalView is the page's data (page.Legal).
+type legalView struct {
+ NoLetterhead bool
+ Docs []legalDocRow
+ Publish legalPublishForm
+ Accepted []legalAcceptRow
+ Letterhead legalLetterheadForm
+}
+
+// legalKindOf is kind when it is a legal kind, else "dpa".
+func legalKindOf(kind string) string {
+ if legalKindLabel[kind] != "" {
+ return kind
+ }
+ return "dpa"
+}
+
+// legalEarliestEffective is the first date a version that needs notice,
+// published at now, may apply from: the day after now plus the floor, since
+// a day starts at midnight UTC.
+func legalEarliestEffective(now time.Time) time.Time {
+ floor := now.UTC().Add(legalNoticeFloor)
+ day := time.Date(floor.Year(), floor.Month(), floor.Day(), 0, 0, 0, 0, time.UTC)
+ if day.Before(floor) {
+ day = day.AddDate(0, 0, 1)
+ }
+ return day
+}
+
+// legalView reads the page: every published document, the publish form for
+// kind (with draft, when a publish was refused), the live acceptances, and
+// the letterhead form (with lh, when a save was refused).
+func (s *Server) legalView(kind string, draft *legalDraft, lh *legalLetterheadForm) (*legalView, error) {
+ v := &legalView{}
+ all := map[string][]LegalDocument{}
+ for _, k := range legalKinds {
+ docs, err := s.store.LegalDocuments(k)
+ if err != nil {
+ return nil, err
+ }
+ all[k] = docs
+ for _, d := range docs {
+ row := legalDocRow{Kind: legalKindLabel[k], Version: d.Version, URL: d.URL,
+ Published: d.PublishedAt.UTC().Format(legalDateLayout), SHA256: d.SHA256, Short: d.SHA256,
+ at: d.PublishedAt, id: d.ID}
+ if d.EffectiveAt != nil {
+ row.Applies = d.EffectiveAt.UTC().Format(legalDateLayout)
+ }
+ if len(row.Short) > 16 {
+ row.Short = row.Short[:16]
+ }
+ v.Docs = append(v.Docs, row)
+ }
+ }
+ // Newest first across the kinds, as each kind's own list is.
+ sort.SliceStable(v.Docs, func(i, j int) bool {
+ if !v.Docs[i].at.Equal(v.Docs[j].at) {
+ return v.Docs[i].at.After(v.Docs[j].at)
+ }
+ return v.Docs[i].id > v.Docs[j].id
+ })
+
+ f := legalPublishForm{Kind: kind, Tabs: opTabs{Label: "Document"}}
+ for _, k := range legalKinds {
+ f.Tabs.Items = append(f.Tabs.Items, opTab{Label: legalKindLabel[k], Href: "/fleet/legal?kind=" + k + "#publish", Current: k == kind})
+ }
+ switch first := len(all[kind]) == 0; {
+ case first && kind == "dpa":
+ f.Mode = "first-dpa"
+ case first:
+ f.Mode = "baseline"
+ case kind == "dpa":
+ f.Mode = "later-dpa"
+ default:
+ f.Mode = "later"
+ }
+ if draft != nil {
+ f.Draft = *draft
+ } else if f.Mode == "later-dpa" {
+ f.Draft.Effective = legalEarliestEffective(s.now()).Format(legalDateLayout)
+ }
+ v.Publish = f
+
+ live, err := s.store.LiveDPAs()
+ if err != nil {
+ return nil, err
+ }
+ versions := map[int64]string{}
+ for _, d := range all["dpa"] {
+ versions[d.ID] = d.Version
+ }
+ now := s.now()
+ for _, a := range live {
+ v.Accepted = append(v.Accepted, legalAcceptRow{
+ Account: a.AccountName, Sqid: a.AccountSqid, LegalName: a.LegalName, Country: a.Country,
+ Accepted: versions[a.DocumentID], InForce: dpaInForce(a.DPAAcceptance, all["dpa"], nil, now).Version,
+ AcceptedBy: a.AcceptedBy, When: a.AcceptedAt,
+ })
+ }
+
+ cur, err := s.store.CurrentLetterhead()
+ if err != nil {
+ return nil, err
+ }
+ v.NoLetterhead = cur == nil
+ switch {
+ case lh != nil:
+ v.Letterhead = *lh
+ case cur != nil:
+ v.Letterhead = legalLetterheadForm{Entity: cur.Entity, Office: cur.RegisteredOffice, Number: cur.CompanyNumber,
+ VAT: cur.VATNumber, Signatory: cur.Signatory, Privacy: cur.PrivacyAddress, Footer: cur.Footer}
+ }
+ return v, nil
+}
+
+// renderLegal writes the page with status, its error notice msg (none when
+// empty), and the forms' drafts.
+func (s *Server) renderLegal(w http.ResponseWriter, r *http.Request, addr, raw string, status int, kind, msg string, draft *legalDraft, lh *legalLetterheadForm) {
+ v, err := s.legalView(legalKindOf(kind), draft, lh)
+ if err != nil {
+ log.Printf("console: legal page: %v", err)
+ http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
+ return
+ }
+ p := s.opPage(addr, raw, "legal")
+ if msg != "" {
+ p.FlashErr = msg
+ } else {
+ p.Flash, p.FlashErr = s.takeFlash(w, r)
+ }
+ p.Legal = v
+ s.render(w, status, "ops_legal", p)
+}
+
+// handleOpLegal serves the page, operators only.
+func (s *Server) handleOpLegal(w http.ResponseWriter, r *http.Request) {
+ addr, raw, ok := s.operatorOnly(w, r)
+ if !ok {
+ return
+ }
+ s.renderLegal(w, r, addr, raw, http.StatusOK, r.URL.Query().Get("kind"), "", nil, nil)
+}
+
+// legalFormGate is a /fleet/legal write's gates before the step-up, in the
+// house order: a POST with a session, its form read, CSRF, operatorOnly,
+// then the write limit. On false it has answered. The caller calls
+// requireFreshAuth last.
+func (s *Server) legalFormGate(w http.ResponseWriter, r *http.Request) (addr, raw string, ok bool) {
+ if r.Method != http.MethodPost {
+ http.NotFound(w, r)
+ return "", "", false
+ }
+ if _, raw, ok = s.session(r); !ok {
+ http.NotFound(w, r)
+ return "", "", false
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, legalFormMax)
+ var err error
+ if mt, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")); mt == "multipart/form-data" {
+ err = r.ParseMultipartForm(legalFormMax)
+ } else {
+ err = r.ParseForm()
+ }
+ if err != nil {
+ s.renderMessage(w, r, http.StatusBadRequest, "Refused", legalErrForm)
+ return "", "", false
+ }
+ if !csrfFormOK(r, raw) {
+ s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
+ return "", "", false
+ }
+ if addr, raw, ok = s.operatorOnly(w, r); !ok {
+ return "", "", false
+ }
+ if !s.allowWrite(Principal{Address: addr}, time.Now()) {
+ s.renderMessage(w, r, http.StatusTooManyRequests, "Refused", "too many requests. Wait a minute and try again")
+ return "", "", false
+ }
+ return addr, raw, true
+}
+
+// legalClient is the client documents are fetched with.
+func (s *Server) legalClient() *http.Client {
+ if s.legalHTTP != nil {
+ return s.legalHTTP
+ }
+ return newLegalHTTPClient()
+}
+
+// legalField is v trimmed, and false when it is longer than max characters
+// or carries a control character (a line break only when lines is set).
+func legalField(v string, max int, lines bool) (string, bool) {
+ v = strings.TrimSpace(strings.ReplaceAll(v, "\r\n", "\n"))
+ if utf8.RuneCountInString(v) > max || !utf8.ValidString(v) {
+ return "", false
+ }
+ for _, r := range v {
+ if unicode.IsControl(r) && !(lines && r == '\n') || unicode.Is(unicode.Cf, r) {
+ return "", false
+ }
+ }
+ return v, true
+}
+
+// handleOpLegalPublish publishes a version of a legal document (spec §3.1,
+// §3.4). Which row it writes depends on the kind and whether one exists:
+//
+// - the first dpa applies on publishing, with no notice;
+// - the first terms or privacy row is the version already in force, with
+// the date it took effect, and no notice;
+// - a later row marked as not needing notice applies on publishing;
+// - a later dpa needs notice and names a date at least 35 days on;
+// - a later terms or privacy row needs notice, and its date stays unset
+// until its notices set it (slice 3).
+//
+// It fetches body_url for a dpa (which must be canonical, and is stored) and
+// url otherwise, and pins the bytes' digest.
+func (s *Server) handleOpLegalPublish(w http.ResponseWriter, r *http.Request) {
+ addr, raw, ok := s.legalFormGate(w, r)
+ if !ok {
+ return
+ }
+ if !s.requireFreshAuth(w, r, addr, raw) {
+ return
+ }
+ kind := r.PostFormValue("kind")
+ d := legalDraft{
+ Version: strings.TrimSpace(r.PostFormValue("version")), URL: strings.TrimSpace(r.PostFormValue("url")),
+ BodyURL: strings.TrimSpace(r.PostFormValue("body_url")), Summary: r.PostFormValue("summary"),
+ Effective: strings.TrimSpace(r.PostFormValue("effective")), NoNotice: r.PostFormValue("no_notice") != "",
+ }
+ fail := func(status int, msg string) {
+ s.renderLegal(w, r, addr, raw, status, kind, msg, &d, nil)
+ }
+ if legalKindLabel[kind] == "" {
+ fail(http.StatusBadRequest, legalErrForm)
+ return
+ }
+ version, okV := legalField(d.Version, legalVersionMax, false)
+ pageURL, okU := legalField(d.URL, legalURLMax, false)
+ summary, okS := legalField(d.Summary, legalSummaryMax, true)
+ bodyURL, okB := legalField(d.BodyURL, legalURLMax, false)
+ if kind != "dpa" {
+ bodyURL, okB = "", true
+ }
+ if !okV || !okU || !okS || !okB || version == "" || pageURL == "" || summary == "" || (kind == "dpa" && bodyURL == "") {
+ fail(http.StatusBadRequest, legalErrForm)
+ return
+ }
+
+ existing, err := s.store.LegalDocuments(kind)
+ if err != nil {
+ log.Printf("console: legal publish: %s documents: %v", kind, err)
+ http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
+ return
+ }
+ // A version already there is refused before anything is fetched; the
+ // insert's own check below covers a publish racing this one.
+ for _, e := range existing {
+ if e.Version == version {
+ fail(http.StatusConflict, legalErrExists)
+ return
+ }
+ }
+ first := len(existing) == 0
+ now := s.now().UTC().Truncate(time.Second)
+ doc := LegalDocument{Kind: kind, Version: version, URL: pageURL, BodyURL: bodyURL, Summary: summary,
+ PublishedAt: now, PublishedBy: addr}
+ switch {
+ case first && kind == "dpa", !first && d.NoNotice:
+ doc.EffectiveAt = &now
+ case first:
+ eff, err := time.Parse(legalDateLayout, d.Effective)
+ if err != nil {
+ fail(http.StatusBadRequest, legalErrForm)
+ return
+ }
+ doc.EffectiveAt = &eff
+ case kind == "dpa":
+ eff, err := time.Parse(legalDateLayout, d.Effective)
+ if err != nil {
+ fail(http.StatusBadRequest, legalErrForm)
+ return
+ }
+ if eff.Before(now.Add(legalNoticeFloor)) {
+ fail(http.StatusBadRequest, legalErrFloor)
+ return
+ }
+ doc.NeedsNotice, doc.EffectiveAt = true, &eff
+ default:
+ doc.NeedsNotice = true
+ }
+
+ fetchURL := pageURL
+ if kind == "dpa" {
+ fetchURL = bodyURL
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), legalFetchTimeout)
+ defer cancel()
+ b, err := fetchLegalText(ctx, s.legalClient(), fetchURL)
+ if err != nil {
+ fail(http.StatusBadRequest, legalFetchText(fetchURL, err))
+ return
+ }
+ if kind == "dpa" {
+ if !utf8.Valid(b) {
+ fail(http.StatusBadRequest, legalCanonicalText(errors.New("text that isn't UTF-8")))
+ return
+ }
+ if err := canonicalAgreement(b); err != nil {
+ fail(http.StatusBadRequest, legalCanonicalText(err))
+ return
+ }
+ doc.Body = string(b)
+ }
+ sum := sha256.Sum256(b)
+ doc.SHA256 = hex.EncodeToString(sum[:])
+
+ if _, err := s.store.PublishLegalDocument(doc); errors.Is(err, ErrLegalVersionExists) {
+ fail(http.StatusConflict, legalErrExists)
+ return
+ } else if err != nil {
+ log.Printf("console: legal publish %s %s: %v", kind, version, err)
+ http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
+ return
+ }
+ s.auditSystem(addr, "legal.publish", kind+" "+version)
+ s.setFlash(w, "ok", legalPublishedText(kind, version))
+ http.Redirect(w, r, "/fleet/legal?kind="+url.QueryEscape(kind)+"#versions", http.StatusSeeOther)
+}
+
+// legalFoldLogo moves an uploaded logo into the form as base64
+// (legalLogoField), replacing any value sent there, so the step-up's stash
+// replays it. A request that is not multipart keeps the field it sent: that
+// is the replay, or a client sending the field itself, and the same check
+// applies to both. An oversize upload is refused here, before the step-up.
+func (s *Server) legalFoldLogo(w http.ResponseWriter, r *http.Request, addr, raw string) bool {
+ if r.MultipartForm == nil {
+ return true
+ }
+ r.PostForm.Del(legalLogoField)
+ files := r.MultipartForm.File["logo"]
+ if len(files) == 0 || files[0].Size == 0 {
+ return true
+ }
+ f, err := files[0].Open()
+ if err != nil {
+ s.renderMessage(w, r, http.StatusBadRequest, "Refused", legalErrForm)
+ return false
+ }
+ defer f.Close()
+ b, err := io.ReadAll(io.LimitReader(f, letterheadLogoMax+1))
+ if err != nil {
+ s.renderMessage(w, r, http.StatusBadRequest, "Refused", legalErrForm)
+ return false
+ }
+ if letterheadLogoType(b) == "" {
+ lh := legalLetterheadDraft(r)
+ s.renderLegal(w, r, addr, raw, http.StatusBadRequest, "", legalErrLogo, nil, &lh)
+ return false
+ }
+ r.PostForm.Set(legalLogoField, base64.RawURLEncoding.EncodeToString(b))
+ return true
+}
+
+// legalLetterheadDraft is the letterhead form as posted.
+func legalLetterheadDraft(r *http.Request) legalLetterheadForm {
+ return legalLetterheadForm{
+ Entity: r.PostFormValue("entity"), Office: r.PostFormValue("office"), Number: r.PostFormValue("number"),
+ VAT: r.PostFormValue("vat"), Signatory: r.PostFormValue("signatory"), Privacy: r.PostFormValue("privacy"),
+ Footer: r.PostFormValue("footer"),
+ }
+}
+
+// handleOpLegalLetterhead saves a new letterhead (spec §3.6), which becomes
+// the current one; acceptances keep the one they were made under. With no
+// logo uploaded, the current letterhead's logo is kept.
+func (s *Server) handleOpLegalLetterhead(w http.ResponseWriter, r *http.Request) {
+ addr, raw, ok := s.legalFormGate(w, r)
+ if !ok {
+ return
+ }
+ if r.MultipartForm != nil {
+ defer r.MultipartForm.RemoveAll()
+ }
+ if !s.legalFoldLogo(w, r, addr, raw) {
+ return
+ }
+ if !s.requireFreshAuth(w, r, addr, raw) {
+ return
+ }
+ d := legalLetterheadDraft(r)
+ fail := func(msg string) {
+ s.renderLegal(w, r, addr, raw, http.StatusBadRequest, "", msg, nil, &d)
+ }
+ l := Letterhead{CreatedAt: s.now().UTC(), CreatedBy: addr}
+ var oks [7]bool
+ l.Entity, oks[0] = legalField(d.Entity, letterheadMax, false)
+ l.RegisteredOffice, oks[1] = legalField(d.Office, letterheadLong, true)
+ l.CompanyNumber, oks[2] = legalField(d.Number, letterheadMax, false)
+ l.VATNumber, oks[3] = legalField(d.VAT, letterheadMax, false)
+ l.Signatory, oks[4] = legalField(d.Signatory, letterheadMax, false)
+ l.Footer, oks[5] = legalField(d.Footer, letterheadLong, false)
+ l.PrivacyAddress, oks[6] = canonicalAddress(d.Privacy)
+ for _, ok := range oks {
+ if !ok {
+ fail(legalErrForm)
+ return
+ }
+ }
+ if l.Entity == "" || l.RegisteredOffice == "" || l.CompanyNumber == "" || l.Signatory == "" {
+ fail(legalErrForm)
+ return
+ }
+ if enc := r.PostFormValue(legalLogoField); enc != "" {
+ b, err := base64.RawURLEncoding.DecodeString(enc)
+ if err != nil {
+ fail(legalErrLogo)
+ return
+ }
+ if l.LogoType = letterheadLogoType(b); l.LogoType == "" {
+ fail(legalErrLogo)
+ return
+ }
+ l.Logo = b
+ } else {
+ cur, err := s.store.CurrentLetterhead()
+ if err != nil {
+ log.Printf("console: letterhead: current: %v", err)
+ http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
+ return
+ }
+ if cur != nil && len(cur.Logo) > 0 {
+ l.Logo, l.LogoType = cur.Logo, cur.LogoType
+ }
+ }
+ id, err := s.store.SetLetterhead(l)
+ if err != nil {
+ log.Printf("console: letterhead: %v", err)
+ http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
+ return
+ }
+ s.auditSystem(addr, "legal.letterhead", "letterhead "+strconv.FormatInt(id, 10))
+ s.setFlash(w, "ok", legalLetterheadOK)
+ http.Redirect(w, r, "/fleet/legal#letterhead", http.StatusSeeOther)
+}
+
+// pngMagic opens every PNG.
+var pngMagic = []byte("\x89PNG\r\n\x1a\n")
+
+// letterheadLogoType is "image/png" or "image/svg+xml" for a logo the
+// letterhead may carry, else "". A logo is at most letterheadLogoMax bytes:
+// a PNG by its magic bytes, or an SVG that svgLogoOK passes.
+func letterheadLogoType(b []byte) string {
+ switch {
+ case len(b) == 0 || len(b) > letterheadLogoMax:
+ return ""
+ case bytes.HasPrefix(b, pngMagic):
+ return "image/png"
+ case svgLogoOK(b):
+ return "image/svg+xml"
+ }
+ return ""
+}
+
+// svgRefused are the SVG elements a logo may not use: script and anything
+// that embeds another document or styles it (CSS can load URLs), and the
+// animation elements, which can set an attribute such as href after this
+// check has read it.
+var svgRefused = map[string]bool{
+ "script": true, "foreignobject": true, "style": true, "iframe": true, "embed": true, "object": true,
+ "set": true, "animate": true, "animatemotion": true, "animatetransform": true, "animatecolor": true,
+ "handler": true, "listener": true,
+}
+
+// svgLogoOK is true for well-formed UTF-8 XML whose root is svg, with no
+// refused element, no on* or style attribute, no xml:base, every href
+// (xlink:href included) a fragment reference ("#..."), and every url(...)
+// in an attribute a fragment reference too. A processing instruction other
+// than the XML declaration (xml-stylesheet loads CSS) and a DOCTYPE with an
+// internal subset (which can add attributes or entities this check would
+// not see) are refused. Unknown entities fail the strict parse.
+func svgLogoOK(b []byte) bool {
+ if !utf8.Valid(b) {
+ return false
+ }
+ dec := xml.NewDecoder(bytes.NewReader(b))
+ dec.Strict = true
+ root := ""
+ for {
+ tok, err := dec.Token()
+ if err == io.EOF {
+ return root == "svg"
+ }
+ if err != nil {
+ return false
+ }
+ switch t := tok.(type) {
+ case xml.StartElement:
+ name := strings.ToLower(t.Name.Local)
+ if root == "" {
+ root = name
+ if root != "svg" {
+ return false
+ }
+ }
+ if svgRefused[name] {
+ return false
+ }
+ for _, a := range t.Attr {
+ key := strings.ToLower(a.Name.Local)
+ switch {
+ case strings.HasPrefix(key, "on"), key == "style", key == "base":
+ return false
+ case key == "href" && !strings.HasPrefix(a.Value, "#"):
+ return false
+ case !svgURLsLocal(a.Value):
+ return false
+ }
+ }
+ case xml.ProcInst:
+ if t.Target != "xml" {
+ return false
+ }
+ case xml.Directive:
+ d := strings.TrimSpace(string(t))
+ if !strings.HasPrefix(d, "DOCTYPE") || strings.Contains(d, "[") {
+ return false
+ }
+ }
+ }
+}
+
+// svgURLsLocal is true when every url( in v, ignoring case, whitespace and
+// quotes, opens a fragment reference.
+func svgURLsLocal(v string) bool {
+ v = strings.ToLower(v)
+ for {
+ i := strings.Index(v, "url(")
+ if i < 0 {
+ return true
+ }
+ v = strings.TrimLeft(v[i+len("url("):], " \t\r\n\f'\"")
+ if !strings.HasPrefix(v, "#") {
+ return false
+ }
+ }
+}
diff --git a/internal/console/oplegal_test.go b/internal/console/oplegal_test.go
new file mode 100644
index 000000000..b71157f9e
--- /dev/null
+++ b/internal/console/oplegal_test.go
@@ -0,0 +1,691 @@
+package console
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/hex"
+ "html"
+ "image"
+ "image/png"
+ "io"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "regexp"
+ "strconv"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// The operator's legal page (/fleet/legal, oplegal.go): publishing legal
+// documents, the letterhead, and the accepted DPAs.
+
+const oplFragment = "<section><h2>Data processing</h2><p>We process <strong>your</strong> data.</p></section>\n"
+
+// oplDeck is a DPA deck row's approved text with its placeholders filled
+// from kv (placeholder name, value, ...).
+func oplDeck(t *testing.T, id string, kv ...string) string {
+ t.Helper()
+ for _, r := range parseDPACopyDeck(t) {
+ if r.ID == id {
+ s := r.New
+ for i := 0; i+1 < len(kv); i += 2 {
+ s = strings.ReplaceAll(s, "{"+kv[i]+"}", kv[i+1])
+ }
+ return s
+ }
+ }
+ t.Fatalf("no deck row %s", id)
+ return ""
+}
+
+// oplText is a page body as a reader sees it: entities decoded.
+func oplText(body string) string { return html.UnescapeString(body) }
+
+// oplSite is a TLS server for the documents an operator publishes, with the
+// console's legal client pointed at it. hits counts its requests.
+func oplSite(t *testing.T, fx *consoleFixture, pages map[string]string) (*httptest.Server, *atomic.Int64) {
+ t.Helper()
+ var hits atomic.Int64
+ srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ b, ok := pages[r.URL.Path]
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ _, _ = io.WriteString(w, b)
+ }))
+ t.Cleanup(srv.Close)
+ fx.srv.legalHTTP = legalTestClient(srv)
+ return srv, &hits
+}
+
+// oplFresh records a fresh step-up for c's session.
+func oplFresh(t *testing.T, fx *consoleFixture, c *http.Client) {
+ t.Helper()
+ if err := fx.st.RecordStepUp(sessionToken(t, fx, c), "paul@keymail.dev", time.Now(), time.Now()); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// oplPublish posts the publish form as c with c's CSRF token.
+func oplPublish(t *testing.T, fx *consoleFixture, c *http.Client, kv ...string) (int, string, string) {
+ t.Helper()
+ v := url.Values{"csrf": {sessionToken(t, fx, c)}}
+ for i := 0; i+1 < len(kv); i += 2 {
+ v.Set(kv[i], kv[i+1])
+ }
+ return postForm(t, c, fx.ts.URL+"/fleet/legal/publish", v)
+}
+
+// oplLetterheadFields is a complete letterhead form without a logo.
+func oplLetterheadFields() map[string]string {
+ return map[string]string{
+ "entity": "Shop Limited",
+ "office": "1 Main Street, Dublin",
+ "number": "123456",
+ "vat": "IE1234567X",
+ "signatory": "For and on behalf of Shop Limited",
+ "privacy": "privacy@example.com",
+ "footer": "Shop is run by Shop Limited.",
+ }
+}
+
+// oplPostLetterhead posts the letterhead form as multipart, with logo as
+// the file part when it is not nil.
+func oplPostLetterhead(t *testing.T, fx *consoleFixture, c *http.Client, fields map[string]string, logo []byte) (int, string, string) {
+ t.Helper()
+ var buf bytes.Buffer
+ mw := multipart.NewWriter(&buf)
+ _ = mw.WriteField("csrf", sessionToken(t, fx, c))
+ for k, v := range fields {
+ _ = mw.WriteField(k, v)
+ }
+ if logo != nil {
+ fw, err := mw.CreateFormFile("logo", "logo")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, _ = fw.Write(logo)
+ }
+ if err := mw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ res, err := c.Post(fx.ts.URL+"/fleet/legal/letterhead", mw.FormDataContentType(), &buf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ b, _ := io.ReadAll(res.Body)
+ return res.StatusCode, res.Header.Get("Location"), string(b)
+}
+
+// oplPNG is a small real PNG.
+func oplPNG(t *testing.T) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ if err := png.Encode(&buf, image.NewGray(image.Rect(0, 0, 2, 2))); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+func oplDocs(t *testing.T, fx *consoleFixture, kind string) []LegalDocument {
+ t.Helper()
+ docs, err := fx.st.LegalDocuments(kind)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return docs
+}
+
+func oplAudits(t *testing.T, fx *consoleFixture, action string) []FeedRow {
+ t.Helper()
+ rows, err := fx.st.ActivityFeed(ActivityFilter{AccountID: OpsAccountID, Actions: []string{action}}, 0, 50)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return rows
+}
+
+func TestOpLegalNonOperator404(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInPaul(t, fx) // signed in, not an operator
+ csrf := sessionToken(t, fx, c)
+ if status, _, body := get(t, c, fx.ts.URL+"/fleet/legal"); status != http.StatusNotFound || body != "404 page not found\n" {
+ t.Fatalf("GET /fleet/legal = %d %q", status, body)
+ }
+ for _, p := range []string{"/fleet/legal/publish", "/fleet/legal/letterhead"} {
+ status, _, body := postForm(t, c, fx.ts.URL+p, url.Values{"csrf": {csrf}, "kind": {"dpa"}, "entity": {"x"}})
+ if status != http.StatusNotFound || body != "404 page not found\n" {
+ t.Errorf("POST %s = %d %q", p, status, body)
+ }
+ // A wrong method answers as a missing route does, for everyone.
+ status, _, body = get(t, c, fx.ts.URL+p)
+ if status != http.StatusNotFound || body != "404 page not found\n" {
+ t.Errorf("GET %s = %d %q", p, status, body)
+ }
+ }
+ // Signed out, too.
+ anon := newBrowser(t)
+ if status, _, _ := get(t, anon, fx.ts.URL+"/fleet/legal"); status != http.StatusNotFound {
+ t.Fatalf("anonymous GET = %d", status)
+ }
+ if n := len(oplDocs(t, fx, "dpa")); n != 0 {
+ t.Fatalf("%d dpa rows", n)
+ }
+ if lh, _ := fx.st.CurrentLetterhead(); lh != nil {
+ t.Fatal("a letterhead was stored")
+ }
+}
+
+func TestOpLegalPublishDPA(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInOperator(t, fx)
+ oplFresh(t, fx, c)
+ srv, _ := oplSite(t, fx, map[string]string{"/dpa/1/agreement.html": oplFragment})
+
+ status, loc, body := oplPublish(t, fx, c, "kind", "dpa", "version", "1",
+ "url", srv.URL+"/dpa/1/", "body_url", srv.URL+"/dpa/1/agreement.html", "summary", "The first agreement.")
+ if status != http.StatusSeeOther || !strings.HasPrefix(loc, "/fleet/legal") {
+ t.Fatalf("publish = %d %q %s", status, loc, body)
+ }
+ docs := oplDocs(t, fx, "dpa")
+ if len(docs) != 1 {
+ t.Fatalf("%d dpa rows, want 1", len(docs))
+ }
+ d := docs[0]
+ if d.Version != "1" || d.URL != srv.URL+"/dpa/1/" || d.BodyURL != srv.URL+"/dpa/1/agreement.html" || d.Summary != "The first agreement." {
+ t.Fatalf("row = %+v", d)
+ }
+ if d.Body != oplFragment || d.SHA256 != oplDigest([]byte(oplFragment)) {
+ t.Fatalf("body %q sha %s, want the served bytes and their digest", d.Body, d.SHA256)
+ }
+ if d.NeedsNotice || d.EffectiveAt == nil || !d.EffectiveAt.Equal(d.PublishedAt) {
+ t.Fatalf("first dpa: needs_notice %v effective %v published %v", d.NeedsNotice, d.EffectiveAt, d.PublishedAt)
+ }
+ if d.PublishedBy != "paul@keymail.dev" {
+ t.Fatalf("published by %q", d.PublishedBy)
+ }
+ if a := oplAudits(t, fx, "legal.publish"); len(a) != 1 || a[0].Detail != "dpa 1" || a[0].Address != "paul@keymail.dev" {
+ t.Fatalf("audit = %+v", a)
+ }
+
+ // The page lists it and says it was published.
+ _, _, page := get(t, c, fx.ts.URL+loc)
+ text := oplText(page)
+ if !strings.Contains(text, oplDeck(t, "DPA-C71", "kind", "data processing agreement", "version", "1")) {
+ t.Fatalf("no done banner:\n%s", page)
+ }
+ if !strings.Contains(page, d.SHA256[:16]) {
+ t.Fatal("the published versions table has no fingerprint")
+ }
+ if strings.Contains(page, "We process") {
+ t.Fatal("the agreement body is shown on the operator page")
+ }
+
+ // The same version again is refused, and nothing is added.
+ status, _, body = oplPublish(t, fx, c, "kind", "dpa", "version", "1",
+ "url", srv.URL+"/dpa/1/", "body_url", srv.URL+"/dpa/1/agreement.html", "summary", "Again.")
+ if status != http.StatusConflict || !strings.Contains(oplText(body), oplDeck(t, "DPA-C70")) {
+ t.Fatalf("duplicate = %d %s", status, body)
+ }
+ if n := len(oplDocs(t, fx, "dpa")); n != 1 {
+ t.Fatalf("%d dpa rows after a duplicate", n)
+ }
+}
+
+func TestOpLegalPublishRefusesNonCanonical(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInOperator(t, fx)
+ oplFresh(t, fx, c)
+ srv, _ := oplSite(t, fx, map[string]string{"/dpa/1/agreement.html": "<p>Hi</p><script>alert(1)</script>"})
+ status, _, body := oplPublish(t, fx, c, "kind", "dpa", "version", "1",
+ "url", srv.URL+"/dpa/1/", "body_url", srv.URL+"/dpa/1/agreement.html", "summary", "First.")
+ if status != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400", status)
+ }
+ if !strings.Contains(oplText(body), "element <script>") {
+ t.Fatalf("the refusal does not name the element:\n%s", body)
+ }
+ if strings.Contains(body, "<script>alert") {
+ t.Fatal("the fetched body was echoed")
+ }
+ if n := len(oplDocs(t, fx, "dpa")); n != 0 {
+ t.Fatalf("%d dpa rows, want none", n)
+ }
+ // The form keeps what was typed.
+ if !strings.Contains(body, `value="`+srv.URL+`/dpa/1/agreement.html"`) {
+ t.Fatal("the form lost the agreement address")
+ }
+}
+
+func TestOpLegalFirstPrivacyIsBaseline(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInOperator(t, fx)
+ oplFresh(t, fx, c)
+ const policy = "<html><body>Privacy policy</body></html>"
+ srv, _ := oplSite(t, fx, map[string]string{"/privacy/1/": policy, "/privacy/2/": policy + " ", "/privacy/3/": policy + " "})
+
+ _, _, page := get(t, c, fx.ts.URL+"/fleet/legal?kind=privacy")
+ text := oplText(page)
+ if !strings.Contains(text, oplDeck(t, "DPA-C64")) || !strings.Contains(text, oplDeck(t, "DPA-C65")) {
+ t.Fatalf("the first privacy form does not offer the baseline:\n%s", page)
+ }
+ if strings.Contains(text, oplDeck(t, "DPA-C63")) {
+ t.Fatal("the baseline form offers a no-notice change")
+ }
+ if !regexp.MustCompile(`<input[^>]*name="effective"[^>]*required`).MatchString(page) {
+ t.Fatal("the baseline form does not require an effective date")
+ }
+
+ // Without the date it is refused.
+ status, _, _ := oplPublish(t, fx, c, "kind", "privacy", "version", "1", "url", srv.URL+"/privacy/1/", "summary", "As it is.")
+ if status != http.StatusBadRequest || len(oplDocs(t, fx, "privacy")) != 0 {
+ t.Fatalf("no date = %d", status)
+ }
+
+ status, loc, body := oplPublish(t, fx, c, "kind", "privacy", "version", "1", "url", srv.URL+"/privacy/1/",
+ "summary", "As it is.", "effective", "2025-05-01")
+ if status != http.StatusSeeOther {
+ t.Fatalf("baseline = %d %q %s", status, loc, body)
+ }
+ docs := oplDocs(t, fx, "privacy")
+ if len(docs) != 1 {
+ t.Fatalf("%d privacy rows", len(docs))
+ }
+ d := docs[0]
+ want := time.Date(2025, 5, 1, 0, 0, 0, 0, time.UTC)
+ if d.NeedsNotice || d.EffectiveAt == nil || !d.EffectiveAt.Equal(want) {
+ t.Fatalf("baseline: needs_notice %v effective %v, want false %v", d.NeedsNotice, d.EffectiveAt, want)
+ }
+ if d.SHA256 != oplDigest([]byte(policy)) || d.Body != "" || d.BodyURL != "" {
+ t.Fatalf("baseline row = %+v", d)
+ }
+
+ // Now a row exists: no baseline, and the no-notice box is offered.
+ _, _, page = get(t, c, fx.ts.URL+"/fleet/legal?kind=privacy")
+ text = oplText(page)
+ if strings.Contains(text, oplDeck(t, "DPA-C64")) || !strings.Contains(text, oplDeck(t, "DPA-C63")) {
+ t.Fatalf("the later privacy form is wrong:\n%s", page)
+ }
+
+ // A later version waits for its notice; a no-notice one applies now.
+ if status, _, body := oplPublish(t, fx, c, "kind", "privacy", "version", "2", "url", srv.URL+"/privacy/2/",
+ "summary", "We changed it.", "effective", "2025-01-01"); status != http.StatusSeeOther {
+ t.Fatalf("later = %d %s", status, body)
+ }
+ if status, _, body := oplPublish(t, fx, c, "kind", "privacy", "version", "3", "url", srv.URL+"/privacy/3/",
+ "summary", "A typo.", "no_notice", "on"); status != http.StatusSeeOther {
+ t.Fatalf("no notice = %d %s", status, body)
+ }
+ byVersion := map[string]LegalDocument{}
+ for _, d := range oplDocs(t, fx, "privacy") {
+ byVersion[d.Version] = d
+ }
+ if d := byVersion["2"]; !d.NeedsNotice || d.EffectiveAt != nil {
+ t.Fatalf("later: needs_notice %v effective %v, want true nil", d.NeedsNotice, d.EffectiveAt)
+ }
+ if d := byVersion["3"]; d.NeedsNotice || d.EffectiveAt == nil || !d.EffectiveAt.Equal(d.PublishedAt) {
+ t.Fatalf("no notice: needs_notice %v effective %v published %v", d.NeedsNotice, d.EffectiveAt, d.PublishedAt)
+ }
+}
+
+func TestOpLegalLaterDPAEffectiveFloor(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInOperator(t, fx)
+ oplFresh(t, fx, c)
+ pages := map[string]string{}
+ for _, v := range []string{"1", "2", "3"} {
+ pages["/dpa/"+v+"/agreement.html"] = "<p>Version " + v + "</p>"
+ }
+ srv, _ := oplSite(t, fx, pages)
+ publish := func(version string, kv ...string) (int, string) {
+ t.Helper()
+ args := append([]string{"kind", "dpa", "version", version, "url", srv.URL + "/dpa/" + version + "/",
+ "body_url", srv.URL + "/dpa/" + version + "/agreement.html", "summary", "Changes."}, kv...)
+ status, _, body := oplPublish(t, fx, c, args...)
+ return status, body
+ }
+ if status, body := publish("1"); status != http.StatusSeeOther {
+ t.Fatalf("v1 = %d %s", status, body)
+ }
+
+ // The later form offers a date already past the floor.
+ _, _, page := get(t, c, fx.ts.URL+"/fleet/legal?kind=dpa")
+ floorDay := time.Now().UTC().Add(35 * 24 * time.Hour)
+ if !strings.Contains(page, `value="`+floorDay.AddDate(0, 0, 1).Format("2006-01-02")+`"`) {
+ t.Fatalf("the later dpa form does not offer the first date past the floor:\n%s", page)
+ }
+
+ early := time.Now().UTC().AddDate(0, 0, 30).Format("2006-01-02")
+ status, body := publish("2", "effective", early)
+ if status != http.StatusBadRequest || !strings.Contains(oplText(body), oplDeck(t, "DPA-C67")) {
+ t.Fatalf("30 days = %d %s", status, body)
+ }
+ // The floor day itself starts before 35 days have passed.
+ if status, _ := publish("2", "effective", floorDay.Format("2006-01-02")); status != http.StatusBadRequest {
+ t.Fatalf("the floor day itself = %d, want 400", status)
+ }
+ if n := len(oplDocs(t, fx, "dpa")); n != 1 {
+ t.Fatalf("%d dpa rows after refusals", n)
+ }
+
+ later := time.Now().UTC().AddDate(0, 0, 36)
+ if status, body := publish("2", "effective", later.Format("2006-01-02")); status != http.StatusSeeOther {
+ t.Fatalf("36 days = %d %s", status, body)
+ }
+ if status, body := publish("3", "no_notice", "on", "effective", early); status != http.StatusSeeOther {
+ t.Fatalf("no notice = %d %s", status, body)
+ }
+ byVersion := map[string]LegalDocument{}
+ for _, d := range oplDocs(t, fx, "dpa") {
+ byVersion[d.Version] = d
+ }
+ d2 := byVersion["2"]
+ wantEff := time.Date(later.Year(), later.Month(), later.Day(), 0, 0, 0, 0, time.UTC)
+ if !d2.NeedsNotice || d2.EffectiveAt == nil || !d2.EffectiveAt.Equal(wantEff) ||
+ d2.EffectiveAt.Before(d2.PublishedAt.Add(35*24*time.Hour)) {
+ t.Fatalf("v2: needs_notice %v effective %v published %v", d2.NeedsNotice, d2.EffectiveAt, d2.PublishedAt)
+ }
+ if d3 := byVersion["3"]; d3.NeedsNotice || d3.EffectiveAt == nil || !d3.EffectiveAt.Equal(d3.PublishedAt) {
+ t.Fatalf("v3: needs_notice %v effective %v", d3.NeedsNotice, d3.EffectiveAt)
+ }
+}
+
+func TestOpLegalLetterhead(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInOperator(t, fx)
+ oplFresh(t, fx, c)
+
+ _, _, page := get(t, c, fx.ts.URL+"/fleet/legal")
+ if !strings.Contains(oplText(page), oplDeck(t, "DPA-C46")) {
+ t.Fatalf("no letterhead, and the page does not say why no pane renders:\n%s", page)
+ }
+
+ fields := oplLetterheadFields()
+ status, loc, body := oplPostLetterhead(t, fx, c, fields, nil)
+ if status != http.StatusSeeOther || !strings.HasPrefix(loc, "/fleet/legal") {
+ t.Fatalf("save = %d %q %s", status, loc, body)
+ }
+ lh, err := fx.st.CurrentLetterhead()
+ if err != nil || lh == nil {
+ t.Fatalf("letterhead %v %v", lh, err)
+ }
+ if lh.Entity != fields["entity"] || lh.RegisteredOffice != fields["office"] || lh.CompanyNumber != fields["number"] ||
+ lh.VATNumber != fields["vat"] || lh.Signatory != fields["signatory"] || lh.PrivacyAddress != fields["privacy"] ||
+ lh.Footer != fields["footer"] || lh.Logo != nil || lh.LogoType != "" || lh.CreatedBy != "paul@keymail.dev" {
+ t.Fatalf("stored %+v", lh)
+ }
+ if a := oplAudits(t, fx, "legal.letterhead"); len(a) != 1 || a[0].Detail != "letterhead "+itoa64(lh.ID) {
+ t.Fatalf("audit = %+v", a)
+ }
+ _, _, page = get(t, c, fx.ts.URL+loc)
+ if strings.Contains(oplText(page), oplDeck(t, "DPA-C46")) {
+ t.Fatal("the no-letterhead notice outlived the letterhead")
+ }
+ if !strings.Contains(oplText(page), oplDeck(t, "DPA-C84")) {
+ t.Fatal("no saved banner")
+ }
+ if !strings.Contains(page, `value="Shop Limited"`) {
+ t.Fatal("the form does not show the current letterhead")
+ }
+
+ first := lh.ID
+ big := append(oplPNG(t), make([]byte, 200<<10)...)
+ big = big[:200<<10+1]
+ for name, logo := range map[string][]byte{
+ "svg with script": []byte(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`),
+ "png over 200 KB": big,
+ "neither": []byte("GIF89a"),
+ } {
+ status, _, body := oplPostLetterhead(t, fx, c, fields, logo)
+ if status != http.StatusBadRequest || !strings.Contains(oplText(body), oplDeck(t, "DPA-C83")) {
+ t.Errorf("%s = %d %s", name, status, body)
+ }
+ }
+ if lh, _ := fx.st.CurrentLetterhead(); lh.ID != first {
+ t.Fatal("a refused logo saved a letterhead")
+ }
+
+ // A good SVG is kept, and a later save without a logo keeps it.
+ svg := []byte(`<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 10 10"><defs><path id="p" d="M0 0h10v10z"/></defs><use xlink:href="#p" fill="url(#g)"/></svg>`)
+ if status, _, body := oplPostLetterhead(t, fx, c, fields, svg); status != http.StatusSeeOther {
+ t.Fatalf("svg = %d %s", status, body)
+ }
+ if lh, _ := fx.st.CurrentLetterhead(); !bytes.Equal(lh.Logo, svg) || lh.LogoType != "image/svg+xml" {
+ t.Fatalf("svg stored as %q %q", lh.Logo, lh.LogoType)
+ }
+ fields["footer"] = ""
+ if status, _, body := oplPostLetterhead(t, fx, c, fields, nil); status != http.StatusSeeOther {
+ t.Fatalf("resave = %d %s", status, body)
+ }
+ if lh, _ := fx.st.CurrentLetterhead(); !bytes.Equal(lh.Logo, svg) || lh.Footer != "" {
+ t.Fatalf("resave lost the logo or kept the footer: %+v", lh)
+ }
+
+ // A missing required field is refused.
+ delete(fields, "entity")
+ if status, _, _ := oplPostLetterhead(t, fx, c, fields, nil); status != http.StatusBadRequest {
+ t.Fatalf("no entity = %d", status)
+ }
+}
+
+func TestOpLegalLogoCheck(t *testing.T) {
+ const ns = `xmlns="http://www.w3.org/2000/svg"`
+ good := []string{
+ `<svg ` + ns + `><rect width="1" height="1" fill="#000"/></svg>`,
+ `<?xml version="1.0" encoding="UTF-8"?>` + "\n" + `<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">` + "\n" + `<svg ` + ns + `><!-- logo --><g><a href="#x"><text>Shop</text></a></g></svg>`,
+ `<svg ` + ns + ` xmlns:xlink="http://www.w3.org/1999/xlink"><use xlink:href="#p"/><rect fill="url( '#g' )"/></svg>`,
+ }
+ for _, s := range good {
+ if got := letterheadLogoType([]byte(s)); got != "image/svg+xml" {
+ t.Errorf("refused %q", s)
+ }
+ }
+ bad := []string{
+ `<svg ` + ns + `><script>alert(1)</script></svg>`,
+ `<svg ` + ns + `><SCRIPT>alert(1)</SCRIPT></svg>`,
+ `<svg ` + ns + `><foreignObject><div/></foreignObject></svg>`,
+ `<svg ` + ns + ` onload="alert(1)"/>`,
+ `<svg ` + ns + `><rect ONCLICK="x"/></svg>`,
+ `<svg ` + ns + `><a href="https://example.com/">x</a></svg>`,
+ `<svg ` + ns + ` xmlns:xlink="http://www.w3.org/1999/xlink"><use xlink:href="https://example.com/a.svg#p"/></svg>`,
+ `<svg ` + ns + `><image href="data:image/png;base64,AAAA"/></svg>`,
+ `<svg ` + ns + `><style>rect{fill:url(https://example.com/)}</style></svg>`,
+ `<svg ` + ns + `><rect style="fill:red"/></svg>`,
+ `<svg ` + ns + `><rect fill="url(https://example.com/#g)"/></svg>`,
+ `<svg ` + ns + `><a><set attributeName="href" to="javascript:alert(1)"/></a></svg>`,
+ `<svg ` + ns + `><animate attributeName="href" values="javascript:alert(1)"/></svg>`,
+ `<?xml-stylesheet href="https://example.com/x.css"?><svg ` + ns + `/>`,
+ `<!DOCTYPE svg [<!ATTLIST svg onload CDATA "alert(1)">]><svg ` + ns + `/>`,
+ `<!DOCTYPE svg [<!ENTITY x "y">]><svg ` + ns + `>&x;</svg>`,
+ `<svg ` + ns + `><rect></svg>`,
+ `<html><body/></html>`,
+ `<svg ` + ns + ` xml:base="https://example.com/"><use href="#p"/></svg>`,
+ "",
+ "not an image",
+ }
+ for _, s := range bad {
+ if got := letterheadLogoType([]byte(s)); got != "" {
+ t.Errorf("accepted %q as %s", s, got)
+ }
+ }
+ png := oplPNG(t)
+ if got := letterheadLogoType(png); got != "image/png" {
+ t.Errorf("png = %q", got)
+ }
+ exact := append(append([]byte{}, png...), make([]byte, 200<<10-len(png))...)
+ if got := letterheadLogoType(exact); got != "image/png" {
+ t.Errorf("a 200 KB png = %q", got)
+ }
+ if got := letterheadLogoType(append(exact, 0)); got != "" {
+ t.Errorf("200 KB + 1 = %q", got)
+ }
+}
+
+func TestOpLegalRequiresFreshAuth(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInOperator(t, fx)
+ srv, hits := oplSite(t, fx, map[string]string{"/dpa/1/agreement.html": oplFragment})
+
+ status, loc, _ := oplPublish(t, fx, c, "kind", "dpa", "version", "1", "url", srv.URL+"/dpa/1/",
+ "body_url", srv.URL+"/dpa/1/agreement.html", "summary", "First.")
+ if status != http.StatusSeeOther || !strings.HasPrefix(loc, fx.fk.srv.URL) {
+ t.Fatalf("publish without a step-up = %d %q, want 303 to Keymail", status, loc)
+ }
+ if n := len(oplDocs(t, fx, "dpa")); n != 0 || hits.Load() != 0 {
+ t.Fatalf("parked publish wrote %d rows and fetched %d times", n, hits.Load())
+ }
+ status, loc, body := completeStepUp(t, fx, c, loc)
+ if status != http.StatusSeeOther || !strings.HasPrefix(loc, "/fleet/legal") {
+ t.Fatalf("resumed publish = %d %q %s", status, loc, body)
+ }
+ if docs := oplDocs(t, fx, "dpa"); len(docs) != 1 || docs[0].Body != oplFragment {
+ t.Fatalf("resumed publish stored %+v", docs)
+ }
+
+ // The letterhead, with a logo that must survive the replay.
+ if err := fx.st.ClearStepUp(sessionToken(t, fx, c)); err != nil {
+ t.Fatal(err)
+ }
+ logo := oplPNG(t)
+ status, loc, _ = oplPostLetterhead(t, fx, c, oplLetterheadFields(), logo)
+ if status != http.StatusSeeOther || !strings.HasPrefix(loc, fx.fk.srv.URL) {
+ t.Fatalf("letterhead without a step-up = %d %q, want 303 to Keymail", status, loc)
+ }
+ if lh, _ := fx.st.CurrentLetterhead(); lh != nil {
+ t.Fatal("a parked letterhead was stored")
+ }
+ status, loc, body = completeStepUp(t, fx, c, loc)
+ if status != http.StatusSeeOther || !strings.HasPrefix(loc, "/fleet/legal") {
+ t.Fatalf("resumed letterhead = %d %q %s", status, loc, body)
+ }
+ lh, _ := fx.st.CurrentLetterhead()
+ if lh == nil || !bytes.Equal(lh.Logo, logo) || lh.LogoType != "image/png" || lh.Entity != "Shop Limited" {
+ t.Fatalf("resumed letterhead = %+v", lh)
+ }
+}
+
+func TestOpLegalCSRF(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInOperator(t, fx)
+ oplFresh(t, fx, c)
+ for _, p := range []string{"/fleet/legal/publish", "/fleet/legal/letterhead"} {
+ status, _, _ := postForm(t, c, fx.ts.URL+p, url.Values{"csrf": {"wrong"}, "kind": {"dpa"}})
+ if status != http.StatusForbidden {
+ t.Errorf("%s with a bad token = %d, want 403", p, status)
+ }
+ }
+}
+
+func TestOpLegalListsAcceptances(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInOperator(t, fx)
+
+ _, _, page := get(t, c, fx.ts.URL+"/fleet/legal")
+ if !strings.Contains(oplText(page), oplDeck(t, "DPA-C93")) {
+ t.Fatal("no empty list text")
+ }
+
+ now := time.Now().UTC().Truncate(time.Second)
+ past := now.Add(-48 * time.Hour)
+ v1, err := fx.st.PublishLegalDocument(LegalDocument{Kind: "dpa", Version: "2026-01", URL: "https://example.com/dpa/1/",
+ SHA256: "aa", Summary: "One", PublishedAt: past.Add(-time.Hour), EffectiveAt: &past, PublishedBy: "paul@keymail.dev"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ // A later version that needed no notice is in force for everyone.
+ if _, err := fx.st.PublishLegalDocument(LegalDocument{Kind: "dpa", Version: "2026-02", URL: "https://example.com/dpa/2/",
+ SHA256: "bb", Summary: "Two", PublishedAt: past, EffectiveAt: &past, PublishedBy: "paul@keymail.dev"}); err != nil {
+ t.Fatal(err)
+ }
+ lhID, err := fx.st.SetLetterhead(Letterhead{Entity: "Op Limited", RegisteredOffice: "R", CompanyNumber: "1",
+ Signatory: "S", PrivacyAddress: "privacy@example.com", CreatedAt: now, CreatedBy: "paul@keymail.dev"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ acct, err := fx.st.AccountBySqid(fx.sqid)
+ if err != nil || acct == nil {
+ t.Fatalf("account %v %v", acct, err)
+ }
+ if _, err := fx.st.AcceptDPA(DPAAcceptance{AccountID: acct.ID, DocumentID: v1, LetterheadID: lhID,
+ LegalName: "Shop Limited", Address: "PRIVATE-ADDRESS", Country: "IE", SignerName: "Kim", SignerRole: "Director",
+ AcceptedBy: "kim@example.com", AcceptedIP: "192.0.2.1", AcceptedAt: now}); err != nil {
+ t.Fatal(err)
+ }
+
+ _, _, page = get(t, c, fx.ts.URL+"/fleet/legal")
+ text := oplText(page)
+ for _, want := range []string{acct.Name, "Shop Limited", "IE", "kim@example.com",
+ "<td>2026-01</td><td>2026-02</td>", oplDeck(t, "DPA-C85")} {
+ if !strings.Contains(text, want) {
+ t.Errorf("the list lacks %q", want)
+ }
+ }
+ if strings.Contains(text, oplDeck(t, "DPA-C93")) {
+ t.Error("the empty text shows beside a row")
+ }
+ if strings.Contains(page, "PRIVATE-ADDRESS") || strings.Contains(page, "192.0.2.1") {
+ t.Error("the list shows the customer's address or IP")
+ }
+}
+
+func TestOpLegalCopy(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInOperator(t, fx)
+ oplFresh(t, fx, c)
+ srv, _ := oplSite(t, fx, map[string]string{
+ "/dpa/1/agreement.html": oplFragment,
+ "/dpa/2/agreement.html": "<p>x</p><div>y</div>",
+ "/terms/1/": "Terms",
+ })
+
+ // Fetch: a 404.
+ missing := srv.URL + "/dpa/9/agreement.html"
+ _, _, body := oplPublish(t, fx, c, "kind", "dpa", "version", "9", "url", srv.URL+"/dpa/9/", "body_url", missing, "summary", "x")
+ if want := oplDeck(t, "DPA-C68", "which", missing, "reason", "status 404"); !strings.Contains(oplText(body), want) {
+ t.Errorf("fetch error: want %q in\n%s", want, body)
+ }
+ // Canonical: a div.
+ _, _, body = oplPublish(t, fx, c, "kind", "dpa", "version", "2", "url", srv.URL+"/dpa/2/",
+ "body_url", srv.URL+"/dpa/2/agreement.html", "summary", "x")
+ if want := oplDeck(t, "DPA-C69", "what", "element <div>"); !strings.Contains(oplText(body), want) {
+ t.Errorf("canonical error: want %q in\n%s", want, body)
+ }
+ // Done, for each kind.
+ for _, tc := range []struct{ kind, label, version string }{
+ {"dpa", "data processing agreement", "1"},
+ {"terms", "terms", "2026-11-25"},
+ } {
+ kv := []string{"kind", tc.kind, "version", tc.version, "summary", "x", "effective", "2025-01-01"}
+ if tc.kind == "dpa" {
+ kv = append(kv, "url", srv.URL+"/dpa/1/", "body_url", srv.URL+"/dpa/1/agreement.html")
+ } else {
+ kv = append(kv, "url", srv.URL+"/terms/1/")
+ }
+ status, loc, body := oplPublish(t, fx, c, kv...)
+ if status != http.StatusSeeOther {
+ t.Fatalf("%s = %d %s", tc.kind, status, body)
+ }
+ _, _, page := get(t, c, fx.ts.URL+loc)
+ if want := oplDeck(t, "DPA-C71", "kind", tc.label, "version", tc.version); !strings.Contains(oplText(page), want) {
+ t.Errorf("done: want %q in\n%s", want, page)
+ }
+ }
+ if got, want := legalPublishedText("privacy", "3"), oplDeck(t, "DPA-C71", "kind", "privacy policy", "version", "3"); got != want {
+ t.Errorf("privacy done = %q, want %q", got, want)
+ }
+}
+
+func itoa64(n int64) string { return strconv.FormatInt(n, 10) }
+
+// oplDigest is the hex SHA-256 of b.
+func oplDigest(b []byte) string {
+ sum := sha256.Sum256(b)
+ return hex.EncodeToString(sum[:])
+}
diff --git a/internal/console/opshell.go b/internal/console/opshell.go
index 12d5d454c..831a87beb 100644
--- a/internal/console/opshell.go
+++ b/internal/console/opshell.go
@@ -41,6 +41,7 @@ var opRail = []opRailItem{
{Key: "metrics", Href: "/fleet/metrics", Label: "Metrics"},
{Key: "alerts", Href: "/fleet/alerts", Label: "Alerts"},
{Key: "backups", Href: "/fleet/backups", Label: fbCopy.Rail},
+ {Key: "legal", Href: "/fleet/legal", Label: "Legal"},
{Key: "store", Href: "/fleet/store", Label: "Storage requests", StoreOnly: true},
{Key: "economics", Href: "/fleet/economics", Label: "Economics"},
{Key: "protection", Href: "/fleet/protection", Label: "Protection"},
diff --git a/internal/console/opshell_test.go b/internal/console/opshell_test.go
index 67a97da0f..0cb3614f4 100644
--- a/internal/console/opshell_test.go
+++ b/internal/console/opshell_test.go
@@ -288,8 +288,8 @@ func TestRailHidesStorageFromOtherOperators(t *testing.T) {
t.Fatalf("/fleet/index = %d", status)
}
links := opNavLinks(t, body)
- if len(links) != 10 {
- t.Fatalf("the rail has %d links, want 10: %+v", len(links), links)
+ if len(links) != 11 {
+ t.Fatalf("the rail has %d links, want 11: %+v", len(links), links)
}
if strings.Contains(body, `href="/fleet/store"`) {
t.Fatal("an operator not on StoreOperators is shown /fleet/store")
diff --git a/internal/console/opshots_test.go b/internal/console/opshots_test.go
index 04d85306d..b4839a7bb 100644
--- a/internal/console/opshots_test.go
+++ b/internal/console/opshots_test.go
@@ -40,6 +40,7 @@ var opShotPages = []struct{ name, path string }{
{"economics-accounts", "/fleet/economics/accounts"},
{"architecture", "/fleet/architecture"},
{"backups", "/fleet/backups"},
+ {"legal", "/fleet/legal"},
}
// opShotsProxy fronts the console for the screenshot browser: every request
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index ddc6da8cc..f9e0ed6f3 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -146,6 +146,12 @@ var routeDecls = []routeDecl{
{Pattern: "GET /fleet/protection/data", Handler: (*Server).handleFleetProtectionData},
// The operator's restore tests (fleetbackups_page.go), operatorOnly.
{Pattern: "GET /fleet/backups", Handler: (*Server).handleFleetBackups},
+ // The operator's legal documents and letterhead (oplegal.go),
+ // operatorOnly. The two writes are registered without a method, as the
+ // alert doors above are: a wrong method answers the unknown route's 404.
+ {Pattern: "GET /fleet/legal", Handler: (*Server).handleOpLegal},
+ {Pattern: "/fleet/legal/publish", Handler: (*Server).handleOpLegalPublish},
+ {Pattern: "/fleet/legal/letterhead", Handler: (*Server).handleOpLegalLetterhead},
// The deployment's map (archpage.go), same operatorOnly gate. BOTH are
// registered WITHOUT a method prefix, for the reason spelled out below
// the economics doors: a "GET /path" pattern answers a POST with 405 +
diff --git a/internal/console/server.go b/internal/console/server.go
index b011e6e50..1158aa025 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1164,8 +1164,12 @@ type Server struct {
// alertTests is each connector's test sends in the last hour.
// alertClock is time.Now outside tests, and alertPassBudget 0 (one
// drain pass's alertPassBudget) outside tests.
- alertHTTP *http.Client
- alertHTTPOnce sync.Once
+ alertHTTP *http.Client
+ alertHTTPOnce sync.Once
+ // legalHTTP fetches the legal documents an operator publishes
+ // (oplegal.go): newLegalHTTPClient, set in NewServer; a test points it
+ // at its own server.
+ legalHTTP *http.Client
alertSeal atomic.Pointer[connectorSeal]
alertTests alertTestWindow
alertClock func() time.Time
@@ -2070,6 +2074,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
perf: cfg.Perf,
billing: newBillingRuntime(cfg.Billing),
seen: map[string]time.Time{},
+ legalHTTP: newLegalHTTPClient(),
}
s.initMedia()
if capacity, err := parseHACapacityConfig(cfg.HACapacityConfig, cfg.HARegions, cfg.HomeRegion); err != nil {
@@ -2591,6 +2596,9 @@ type page struct {
// People is People and accounts' data (/fleet/people, oppeople.go).
People *peopleView
+ // Legal is the legal page's data (/fleet/legal, oplegal.go).
+ Legal *legalView
+
// Feed is Activity's data (/fleet/activity, opactivity.go).
Feed *feedView
diff --git a/internal/console/templates/ops_legal.html b/internal/console/templates/ops_legal.html
new file mode 100644
index 000000000..9836bbf34
--- /dev/null
+++ b/internal/console/templates/ops_legal.html
@@ -0,0 +1,126 @@
+{{/* Legal (/fleet/legal, oplegal.go): the published versions of the
+ legal documents, the form to publish one, the accounts with a DPA in
+ force, and the letterhead. Everything computed in Go arrives in
+ .Legal; every operator-entered string is escaped here. The agreement
+ text itself is never shown on this page. */}}
+{{define "ops_legal"}}{{template "op_top" .}}
+{{template "op_page_header" (opHeader .Title "The agreements customers accept, and the letterhead they're printed on.")}}
+{{template "op_flash" .}}
+{{with .Legal}}
+{{if .NoLetterhead}}
+<div rst-callout rst-tone="warning"><span rst-callout-ic aria-hidden="true">{{icon "triangle-alert"}}</span><div rst-callout-body><p>Customers can't accept a data processing agreement until the letterhead is set.</p></div></div>
+{{end}}
+
+{{if .Docs}}
+<div rst-box-head id="versions"><h2>Published versions</h2></div>
+<div rst-card class="co-table-wrap">
+<table co-table>
+ <tr><th>Document</th><th>Version</th><th>Published</th><th>Applies from</th><th>Fingerprint</th></tr>
+ {{- range .Docs}}
+ <tr><td>{{.Kind}}</td><td><a href="{{.URL}}">{{.Version}}</a></td><td>{{.Published}}</td><td>{{.Applies}}</td><td><code title="{{.SHA256}}">{{.Short}}</code></td></tr>
+ {{- end}}
+</table>
+</div>
+{{end}}
+
+<div rst-box-head id="publish"><h2>Publish a version</h2></div>
+{{with .Publish}}
+<section rst-card co-pad>
+<div co-tabs>{{template "op_seg_tabs" .Tabs}}</div>
+<form method="post" action="/fleet/legal/publish">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ <input type="hidden" name="kind" value="{{.Kind}}">
+ {{- if eq .Mode "baseline"}}
+ <p><strong>Record the version already in force</strong></p>
+ <p co-note>Nothing is sent. This records what customers already have, and the date it took effect.</p>
+ {{- end}}
+ <div rst-field>
+ <label rst-field-label for="opl-version">Version</label>
+ <input rst-input type="text" id="opl-version" name="version" value="{{.Draft.Version}}" maxlength="64" required>
+ </div>
+ <div rst-field>
+ <label rst-field-label for="opl-url">Page address</label>
+ <input rst-input type="url" id="opl-url" name="url" value="{{.Draft.URL}}" required>
+ </div>
+ {{- if eq .Kind "dpa"}}
+ <div rst-field>
+ <label rst-field-label for="opl-body-url">Agreement text address</label>
+ <input rst-input type="url" id="opl-body-url" name="body_url" value="{{.Draft.BodyURL}}" required>
+ </div>
+ {{- end}}
+ <div rst-field>
+ <label rst-field-label for="opl-summary">What changed</label>
+ <textarea rst-textarea id="opl-summary" name="summary" rows="3" maxlength="2000" required>{{.Draft.Summary}}</textarea>
+ </div>
+ {{- if or (eq .Mode "baseline") (eq .Mode "later-dpa")}}
+ <div rst-field>
+ <label rst-field-label for="opl-effective">Applies from</label>
+ <input rst-input type="date" id="opl-effective" name="effective" value="{{.Draft.Effective}}"{{if eq .Mode "baseline"}} required{{end}}>
+ </div>
+ {{- end}}
+ {{- if or (eq .Mode "later-dpa") (eq .Mode "later")}}
+ <div rst-field>
+ <label><span><input type="checkbox" name="no_notice" value="on"{{if .Draft.NoNotice}} checked{{end}}> This change doesn't need notice (a typo fix)</span></label>
+ </div>
+ {{- end}}
+ <button rst-btn="primary" type="submit">Publish</button>
+</form>
+</section>
+{{end}}
+
+<div rst-box-head id="accepted"><h2>Accepted agreements</h2></div>
+{{if .Accepted}}
+<div rst-card class="co-table-wrap">
+<table co-table>
+ <tr><th>Account</th><th>Customer</th><th>Country</th><th>Version accepted</th><th>In force</th><th>Accepted by</th><th>When</th></tr>
+ {{- range .Accepted}}
+ <tr><td>{{if .Sqid}}<a href="/fleet/activity?account={{.Sqid}}">{{.Account}}</a>{{else}}{{.Account}}{{end}}</td><td>{{.LegalName}}</td><td>{{.Country}}</td><td>{{.Accepted}}</td><td>{{.InForce}}</td><td>{{template "op_who" .AcceptedBy}}</td><td title="{{fmtTime .When}}">{{ago .When}}</td></tr>
+ {{- end}}
+</table>
+</div>
+{{else}}
+{{template "op_empty" (opEmpty "" "No account has accepted an agreement yet.")}}
+{{end}}
+
+<div rst-box-head id="letterhead"><h2>Letterhead</h2></div>
+{{with .Letterhead}}
+<form rst-card co-pad method="post" action="/fleet/legal/letterhead" enctype="multipart/form-data">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ <div rst-field>
+ <label rst-field-label for="opl-logo">Logo (optional)</label>
+ <input type="file" id="opl-logo" name="logo" accept="image/png,image/svg+xml">
+ </div>
+ <div rst-field>
+ <label rst-field-label for="opl-entity">Company name</label>
+ <input rst-input type="text" id="opl-entity" name="entity" value="{{.Entity}}" maxlength="200" required>
+ </div>
+ <div rst-field>
+ <label rst-field-label for="opl-office">Registered office</label>
+ <textarea rst-textarea id="opl-office" name="office" rows="3" maxlength="500" required>{{.Office}}</textarea>
+ </div>
+ <div rst-field>
+ <label rst-field-label for="opl-number">Company number</label>
+ <input rst-input type="text" id="opl-number" name="number" value="{{.Number}}" maxlength="200" required>
+ </div>
+ <div rst-field>
+ <label rst-field-label for="opl-vat">VAT number (optional)</label>
+ <input rst-input type="text" id="opl-vat" name="vat" value="{{.VAT}}" maxlength="200">
+ </div>
+ <div rst-field>
+ <label rst-field-label for="opl-signatory">Signs as</label>
+ <input rst-input type="text" id="opl-signatory" name="signatory" value="{{.Signatory}}" maxlength="200" aria-describedby="opl-signatory-hint" required>
+ <p rst-field-hint id="opl-signatory-hint">For example: For and on behalf of Team Tito Limited</p>
+ </div>
+ <div rst-field>
+ <label rst-field-label for="opl-privacy">Privacy email</label>
+ <input rst-input type="email" id="opl-privacy" name="privacy" value="{{.Privacy}}" required>
+ </div>
+ <div rst-field>
+ <label rst-field-label for="opl-footer">Footer line (optional)</label>
+ <input rst-input type="text" id="opl-footer" name="footer" value="{{.Footer}}" maxlength="500">
+ </div>
+ <button rst-btn="primary" type="submit">Save letterhead</button>
+</form>
+{{end}}
+{{end}}
+{{template "op_bottom" .}}{{end}}
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 27e1bfa9d..b9f8132ad 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -15,6 +15,8 @@ route /fleet/billing/sync/status
route /fleet/economics/bill
route /fleet/economics/scenarios
route /fleet/economics/tier
+route /fleet/legal/letterhead
+route /fleet/legal/publish
route DELETE /api/cli/accounts/{account}/subdomain
route DELETE /api/cli/apps/{account}/{app}/domains/{host}
route DELETE /api/cli/apps/{account}/{app}/email/credentials/{name}
@@ -183,6 +185,7 @@ route GET /fleet/boxes
route GET /fleet/economics
route GET /fleet/economics/accounts
route GET /fleet/index
+route GET /fleet/legal
route GET /fleet/metrics
route GET /fleet/people
route GET /fleet/people/{address}
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt
index 991d65d73..cf12d84ef 100644
--- a/internal/console/testdata/perf-budgets.txt
+++ b/internal/console/testdata/perf-budgets.txt
@@ -49,6 +49,8 @@ GET /static/{hash}/{file...} skip: static asset, not a screen; consolePerfSkip l
/fleet/alerts/connectors/{id}/delete skip: POST-only door; a GET answers 404 on its first line by design (alertpages.go)
/fleet/alerts/connectors/{id}/test skip: POST-only door; a GET answers 404 on its first line by design (alertpages.go)
/fleet/alerts/rules/{rule} skip: POST-only door; a GET answers 404 on its first line by design (alertpages.go)
+/fleet/legal/publish skip: POST-only door; a GET answers 404 on its first line by design (oplegal.go)
+/fleet/legal/letterhead skip: POST-only door; a GET answers 404 on its first line by design (oplegal.go)
GET /alerts/confirm/{token} skip: an alert link's page, opened from a message by whoever holds the link; the walk mints no alert token, and it reads one SQLite row
GET /alerts/unsubscribe/{token} skip: an alert link's page, opened from a message by whoever holds the link; the walk mints no alert token, and it reads one SQLite row
GET /alerts/snooze/{token} skip: an alert link's page, opened from a message by whoever holds the link; the walk mints no alert token, and it reads one SQLite row
diff --git a/parity/parity.tsv b/parity/parity.tsv
index b8e681e65..11c96528c 100644
--- a/parity/parity.tsv
+++ b/parity/parity.tsv
@@ -204,6 +204,7 @@ op-alerts operator operator GET /fleet/alerts ; GET /fleet/alerts/history ; /fl
op-alert-links operator operator GET /alerts/confirm/{token} ; POST /alerts/confirm/{token} ; GET /alerts/unsubscribe/{token} ; POST /alerts/unsubscribe/{token} ; GET /alerts/snooze/{token} ; POST /alerts/snooze/{token} Links in fleet alert emails; the token is the credential.
op-protection operator operator GET /fleet/protection ; GET /fleet/protection/data The fleet-wide protection view.
op-backups operator operator GET /fleet/backups What the nightly restore tests found, region by region.
+op-legal operator operator GET /fleet/legal ; /fleet/legal/publish ; /fleet/legal/letterhead Publishing legal documents, the letterhead, and the accounts with a DPA in force.
op-architecture operator operator status [--instances,--layout] GET /fleet/boxes ; /fleet/architecture ; /fleet/architecture/refresh The console shows counts and the map, not one row per instance.
op-status-live operator operator status [--live] GET /fleet/boxes What every box reported.
op-store-approvals operator operator store approvals ; store approve ; store decline GET /fleet/store ; POST /fleet/store/{account}/{decision} Deciding storage applications.