carlos / platform Public

console: DPA store checks and decides inside its write transactions

Branch review findings P1-1, P1-2, P1-3, P2-4 and P2-6.

- The legal store methods take a ctx and use the context-aware SQL
  calls; accountSettingsPage moves from server.go to dpapane.go, so
  server.go is back inside its code-health allowance.
- AcceptDPA checks, in the transaction that inserts, that the account
  is live, the accepting address is still an owner, and the document
  and letterhead exist. The handler answers a gone account or a
  removed owner with the owner gate's 404.
- Publishing fetches first, then decides first row or later, notice
  and effective date, and sets published_at, in the inserting
  transaction. A first-row form (hidden mode field) is refused once
  another row has landed.
- Newest is the highest id everywhere.
- Unique violations are read from the driver's extended code.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 4108d2dc276adaa7b3a620643f09c5c583724109 parent 5760586
13 files changed, +701 −202
  • internal/console/claim_invariant_probes_nonapp_test.go +2 −2
  • internal/console/dpapane.go +68 −14
  • internal/console/dpapane_test.go +81 −6
  • internal/console/dparecord.go +4 −4
  • internal/console/dparecord_test.go +2 −2
  • internal/console/legal_store.go +141 −37
  • internal/console/legal_store_test.go +126 −29
  • internal/console/oplegal.go +78 −50
  • internal/console/oplegal_test.go +190 −13
  • internal/console/ownership.go +1 −1
  • internal/console/server.go +4 −43
  • internal/console/store.go +1 −1
  • internal/console/templates/ops_legal.html +3 −0

Intent

diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go
index dd595cbdf..8d078ab59 100644
--- a/internal/console/claim_invariant_probes_nonapp_test.go
+++ b/internal/console/claim_invariant_probes_nonapp_test.go
@@ -866,12 +866,12 @@ var claimNonAppProbes = map[string]claimProbe{
setup: func(t *testing.T, cx *claimCase) {
body := "<p>census</p>"
eff := time.Now().Add(-time.Hour)
- doc, err := cx.st.PublishLegalDocument(LegalDocument{Kind: "dpa", Version: "census", URL: "https://example.com/dpa/census/",
+ doc, err := cx.st.PublishLegalDocument(t.Context(), LegalDocument{Kind: "dpa", Version: "census", URL: "https://example.com/dpa/census/",
Body: body, SHA256: "census-digest", Summary: "census", PublishedAt: eff, EffectiveAt: &eff, PublishedBy: claimFxOwner})
if err != nil {
t.Fatal(err)
}
- lh, err := cx.st.SetLetterhead(Letterhead{Entity: "Example Hosting Limited", RegisteredOffice: "1 Main Street",
+ lh, err := cx.st.SetLetterhead(t.Context(), Letterhead{Entity: "Example Hosting Limited", RegisteredOffice: "1 Main Street",
CompanyNumber: "1", Signatory: "For Example Hosting Limited", PrivacyAddress: "privacy@example.com",
CreatedBy: claimFxOwner, CreatedAt: time.Now()})
if err != nil {
diff --git a/internal/console/dpapane.go b/internal/console/dpapane.go
index fc9c1cf4a..e39fddf60 100644
--- a/internal/console/dpapane.go
+++ b/internal/console/dpapane.go
@@ -12,6 +12,8 @@ import (
"time"
"unicode"
"unicode/utf8"
+
+ "github.com/carlosframework/platform/internal/telemetry"
)
// The Data processing agreement section of account settings (DPA and
@@ -156,13 +158,13 @@ type dpaPane struct {
// dpaPaneFor fills p.DPA for the account settings page. With no letterhead
// or no dpa document there is no pane. A failed read logs and leaves the
// pane out; it never fails the page.
-func (s *Server) dpaPaneFor(p *page, acct *Account, role string) {
- lh, err := s.store.CurrentLetterhead()
+func (s *Server) dpaPaneFor(ctx context.Context, p *page, acct *Account, role string) {
+ lh, err := s.store.CurrentLetterhead(ctx)
if err != nil {
log.Printf("console: dpa pane %s: letterhead: %v", acct.Sqid, err)
return
}
- doc, err := s.store.NewestLegalDocument("dpa")
+ doc, err := s.store.NewestLegalDocument(ctx, "dpa")
if err != nil {
log.Printf("console: dpa pane %s: newest dpa: %v", acct.Sqid, err)
return
@@ -170,7 +172,7 @@ func (s *Server) dpaPaneFor(p *page, acct *Account, role string) {
if lh == nil || doc == nil {
return
}
- live, err := s.store.LiveDPA(acct.ID)
+ live, err := s.store.LiveDPA(ctx, acct.ID)
if err != nil {
log.Printf("console: dpa pane %s: live acceptance: %v", acct.Sqid, err)
return
@@ -181,7 +183,7 @@ func (s *Server) dpaPaneFor(p *page, acct *Account, role string) {
}
switch {
case live != nil:
- docs, err := s.store.LegalDocuments("dpa")
+ docs, err := s.store.LegalDocuments(ctx, "dpa")
if err != nil {
log.Printf("console: dpa pane %s: documents: %v", acct.Sqid, err)
return
@@ -316,17 +318,18 @@ func (s *Server) handleDPAAccept(w http.ResponseWriter, r *http.Request) {
return
}
+ ctx := r.Context()
settings := accountSettingsURL(acct.Sqid)
fail := func(what string, err error) {
log.Printf("console: dpa accept %s: %s: %v", acct.Sqid, what, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
- doc, err := s.store.NewestLegalDocument("dpa")
+ doc, err := s.store.NewestLegalDocument(ctx, "dpa")
if err != nil {
fail("newest dpa", err)
return
}
- lh, err := s.store.CurrentLetterhead()
+ lh, err := s.store.CurrentLetterhead(ctx)
if err != nil {
fail("letterhead", err)
return
@@ -336,7 +339,7 @@ func (s *Server) handleDPAAccept(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, settings, http.StatusSeeOther)
return
}
- live, err := s.store.LiveDPA(acct.ID)
+ live, err := s.store.LiveDPA(ctx, acct.ID)
if err != nil {
fail("live acceptance", err)
return
@@ -365,13 +368,22 @@ func (s *Server) handleDPAAccept(w http.ResponseWriter, r *http.Request) {
SignerName: form.SignerName, SignerRole: form.SignerRole,
AcceptedBy: addr, AcceptedIP: s.clientIP(r), AcceptedAt: s.now().UTC(),
}
- if _, err := s.store.AcceptDPA(a); err != nil {
- if errors.Is(err, ErrDPAAlreadyInForce) {
+ if s.dpaAcceptHook != nil {
+ s.dpaAcceptHook()
+ }
+ if _, err := s.store.AcceptDPA(ctx, a); err != nil {
+ switch {
+ case errors.Is(err, ErrDPAAlreadyInForce):
+ // Another owner's acceptance landed after the check above.
s.setFlash(w, "ok", dpaAlreadyText)
http.Redirect(w, r, settings, http.StatusSeeOther)
- return
+ case errors.Is(err, ErrDPAAccountGone), errors.Is(err, ErrDPANotOwner):
+ // The account was deleted, or this owner removed, since the
+ // owner gate: the gate's own answer.
+ http.NotFound(w, r)
+ default:
+ fail("record", err)
}
- fail("record", err)
return
}
// The detail names the version only: the customer's details are in the
@@ -379,9 +391,9 @@ func (s *Server) handleDPAAccept(w http.ResponseWriter, r *http.Request) {
s.audit(acct, "", addr, "dpa.accept", "version "+doc.Version)
subject, body := dpaAcceptEmail(doc, lh, a, s.cfg.Origin+settings+"/dpa")
- ctx, cancel := context.WithTimeout(r.Context(), dpaMailTimeout)
+ mctx, cancel := context.WithTimeout(ctx, dpaMailTimeout)
defer cancel()
- if _, err := s.deliver(ctx, addr, subject, body, dpaMailKeymailShare); err != nil {
+ if _, err := s.deliver(mctx, addr, subject, body, dpaMailKeymailShare); err != nil {
// The acceptance stands; the record page has everything the email
// would have said.
log.Printf("console: dpa accept %s: confirmation to %s not delivered: %v", acct.Sqid, addr, err)
@@ -390,6 +402,48 @@ func (s *Server) handleDPAAccept(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, settings, http.StatusSeeOther)
}
+// accountSettingsPage builds the account settings page for a viewer the
+// caller has already admitted with role. On false it has answered. The DPA
+// accept POST (dpapane.go) renders it too, with its pane's form refused.
+func (s *Server) accountSettingsPage(w http.ResponseWriter, r *http.Request, addr, raw string, acct *Account, role string) (page, bool) {
+ p := s.accountPage(w, r, addr, raw, acct, role)
+ p.Title = "Account settings"
+ p.ActiveNav = "settings"
+ n, err := s.store.AppCount(acct.ID)
+ if err != nil {
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read your apps. Please try again.")
+ return p, false
+ }
+ p.HasApps = n > 0
+ p.AccountStore = s.accountStorePane(r.Context(), acct)
+ // The service-credential pane (svcpage.go), owners only — see page's
+ // Services field for why a member gets no section rather than an empty
+ // one.
+ if role == RoleOwner {
+ s.servicePane(&p, acct)
+ }
+ // The account's own Errors log level: the account's telemetry object,
+ // the key the two account forms write, folded over the defaults. No app
+ // layer is read (an empty app name would name apps/<sqid>//telemetry.json,
+ // which nothing writes). A failed read is said rather than defaulted (see
+ // ErrLevelUnread), and never fails the page. A bucketless console folds
+ // the defaults, as telemetry.Resolve does.
+ if s.cfg.Releases == nil {
+ p.ErrLevelSetting = telemetry.Fold(telemetry.Settings{}, telemetry.Settings{})
+ } else if st, _, err := telemetry.Read(r.Context(), s.cfg.Releases, telemetry.AccountKey(acct.Sqid)); err != nil {
+ log.Printf("console: account telemetry %s: %v", acct.Sqid, err)
+ p.ErrLevelUnread = true
+ } else {
+ p.ErrLevelSetting = telemetry.Fold(st, telemetry.Settings{})
+ }
+ // The analytics switch is the OTHER half of that same resolved object —
+ // one settings file, one read — under the name its own section uses.
+ p.AnalyticsSetting, p.AnalyticsUnread = p.ErrLevelSetting, p.ErrLevelUnread
+ s.accountSubdomainPane(r.Context(), &p, acct)
+ s.dpaPaneFor(r.Context(), &p, acct, role)
+ return p, true
+}
+
// renderDPAForm writes the account settings page with status and the pane
// in state ("form" with errs, or "changed"), the typed values kept and the
// newest text and letterhead bound.
diff --git a/internal/console/dpapane_test.go b/internal/console/dpapane_test.go
index 29f15ebd4..d38ec99f4 100644
--- a/internal/console/dpapane_test.go
+++ b/internal/console/dpapane_test.go
@@ -20,7 +20,7 @@ const dpaFragmentV2 = "<section><h2>Data processing, version 2</h2><p>We now als
func dpaPublish(t *testing.T, fx *consoleFixture, version, body string, at time.Time) int64 {
t.Helper()
eff := at
- id, err := fx.st.PublishLegalDocument(LegalDocument{
+ id, err := fx.st.PublishLegalDocument(t.Context(), LegalDocument{
Kind: "dpa", Version: version,
URL: "https://example.com/dpa/" + version + "/",
BodyURL: "https://example.com/dpa/" + version + "/body.html",
@@ -36,7 +36,7 @@ func dpaPublish(t *testing.T, fx *consoleFixture, version, body string, at time.
// dpaLetterhead sets a letterhead whose company name is entity.
func dpaLetterhead(t *testing.T, fx *consoleFixture, entity string) int64 {
t.Helper()
- id, err := fx.st.SetLetterhead(Letterhead{
+ id, err := fx.st.SetLetterhead(t.Context(), Letterhead{
Entity: entity, RegisteredOffice: "1 Main Street, Dublin", CompanyNumber: "123456",
Signatory: "For and on behalf of " + entity, PrivacyAddress: "privacy@example.com",
CreatedBy: "paul@keymail.dev", CreatedAt: time.Now(),
@@ -223,7 +223,7 @@ func TestDPAAccept(t *testing.T) {
if status != http.StatusSeeOther || loc != fx.path("/settings") {
t.Fatalf("accept = %d -> %q, want 303 -> settings:\n%s", status, loc, body)
}
- live, err := fx.st.LiveDPA(OpsAccountID)
+ live, err := fx.st.LiveDPA(t.Context(), OpsAccountID)
if err != nil || live == nil {
t.Fatalf("no live acceptance: %v", err)
}
@@ -442,7 +442,7 @@ func TestDPAAcceptTwiceShowsInForce(t *testing.T) {
if n := dpaRows(t, fx); n != 1 {
t.Fatalf("%d rows after two owners accepted, want 1", n)
}
- live, _ := fx.st.LiveDPA(OpsAccountID)
+ live, _ := fx.st.LiveDPA(t.Context(), OpsAccountID)
if live == nil || live.AcceptedBy != "kim@keymail.dev" {
t.Fatalf("live = %+v, want kim's", live)
}
@@ -478,13 +478,13 @@ func TestDPAPaneCopy(t *testing.T) {
fx := newConsoleFixture(t)
c := signInPaul(t, fx)
docID, lhID := dpaWorld(t, fx)
- if _, err := fx.st.AcceptDPA(DPAAcceptance{AccountID: OpsAccountID, DocumentID: docID, LetterheadID: lhID,
+ if _, err := fx.st.AcceptDPA(t.Context(), DPAAcceptance{AccountID: OpsAccountID, DocumentID: docID, LetterheadID: lhID,
LegalName: "Shop Limited", Address: "1 Main Street", Country: "IE", SignerName: "Ada Lovelace",
SignerRole: "Director", AcceptedBy: "paul@keymail.dev", AcceptedIP: "127.0.0.1", AcceptedAt: at}); err != nil {
t.Fatal(err)
}
eff := time.Now().AddDate(0, 0, 40).UTC()
- if _, err := fx.st.PublishLegalDocument(LegalDocument{Kind: "dpa", Version: "2", URL: "https://example.com/dpa/2/",
+ if _, err := fx.st.PublishLegalDocument(t.Context(), LegalDocument{Kind: "dpa", Version: "2", URL: "https://example.com/dpa/2/",
Body: dpaFragmentV2, SHA256: oplDigest([]byte(dpaFragmentV2)), Summary: "We added a subprocessor for email.",
PublishedAt: time.Now(), EffectiveAt: &eff, NeedsNotice: true, PublishedBy: "paul@keymail.dev"}); err != nil {
t.Fatal(err)
@@ -524,3 +524,78 @@ func TestDPAAcceptEmailCopy(t *testing.T) {
t.Errorf("body =\n%s\nwant\n%s", body, want)
}
}
+
+// Another owner's acceptance lands after the handler's own LiveDPA check
+// and before the insert: the store's unique index refuses the second, and
+// the handler answers it as it answers the check, with the in-force pane.
+func TestDPAAcceptConcurrentOwnerReachesStoreRefusal(t *testing.T) {
+ fx := newConsoleFixture(t)
+ if err := fx.st.AddMember(OpsAccountID, "kim@keymail.dev", RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ docID, lhID := dpaWorld(t, fx)
+ paul := signInPaul(t, fx)
+ csrf := sessionToken(t, fx, paul)
+ dpaFreshAs(t, fx, paul, "paul@keymail.dev")
+ h := dpaHidden(t, dpaSettings(t, fx, paul))
+
+ hooked := 0
+ fx.srv.dpaAcceptHook = func() {
+ hooked++
+ if _, err := fx.st.AcceptDPA(context.Background(), DPAAcceptance{AccountID: OpsAccountID, DocumentID: docID,
+ LetterheadID: lhID, LegalName: "Kim Limited", Address: "2 Main Street", Country: "IE", SignerName: "Kim",
+ SignerRole: "Director", AcceptedBy: "kim@keymail.dev", AcceptedIP: "127.0.0.1", AcceptedAt: time.Now()}); err != nil {
+ t.Error(err)
+ }
+ }
+ status, loc, body := postForm(t, paul, fx.u("/dpa/accept"), dpaPost(csrf, h))
+ if hooked != 1 {
+ t.Fatalf("the hook ran %d times, want 1: the request did not get past the LiveDPA check", hooked)
+ }
+ if status != http.StatusSeeOther || loc != fx.path("/settings") {
+ t.Fatalf("accept = %d -> %q, want 303 -> settings:\n%s", status, loc, body)
+ }
+ if n := dpaRows(t, fx); n != 1 {
+ t.Fatalf("%d rows, want kim's only", n)
+ }
+ if live, _ := fx.st.LiveDPA(t.Context(), OpsAccountID); live == nil || live.AcceptedBy != "kim@keymail.dev" {
+ t.Fatalf("live = %+v, want kim's", live)
+ }
+ fx.srv.dpaAcceptHook = nil
+ page := oplText(dpaSettings(t, fx, paul))
+ if !strings.Contains(page, `<p class="banner">`+oplDeck(t, "DPA-C19")+`</p>`) {
+ t.Errorf("no 'already' banner:\n%s", page)
+ }
+ if audits := oplAudits(t, fx, "dpa.accept"); len(audits) != 0 {
+ t.Errorf("a refused acceptance was audited: %+v", audits)
+ }
+}
+
+// The owner is removed as owner after the owner gate and before the insert:
+// nothing is recorded, and the answer is the owner gate's byte-identical
+// 404. (Deleting or reaping the account in that gap is
+// TestAcceptDPAAfterAccountDeletionRefused: the ops account here cannot be
+// deleted.)
+func TestDPAAcceptOwnerRemovedMidRequest(t *testing.T) {
+ fx := newConsoleFixture(t)
+ dpaWorld(t, fx)
+ paul := signInPaul(t, fx)
+ csrf := sessionToken(t, fx, paul)
+ dpaFreshAs(t, fx, paul, "paul@keymail.dev")
+ h := dpaHidden(t, dpaSettings(t, fx, paul))
+ _, _, unrouted := get(t, paul, fx.ts.URL+"/no/such/path")
+
+ fx.srv.dpaAcceptHook = func() {
+ if _, err := fx.st.db.Exec(`UPDATE memberships SET role = ? WHERE account_id = ? AND address = ?`,
+ RoleMember, OpsAccountID, "paul@keymail.dev"); err != nil {
+ t.Error(err)
+ }
+ }
+ status, loc, body := postForm(t, paul, fx.u("/dpa/accept"), dpaPost(csrf, h))
+ if status != http.StatusNotFound || loc != "" || body != unrouted {
+ t.Fatalf("accept = %d %q %q, want the byte-identical 404 %q", status, loc, body, unrouted)
+ }
+ if n := dpaRows(t, fx); n != 0 {
+ t.Fatalf("%d rows recorded for a removed owner", n)
+ }
+}
diff --git a/internal/console/dparecord.go b/internal/console/dparecord.go
index ed52a0019..817fbc999 100644
--- a/internal/console/dparecord.go
+++ b/internal/console/dparecord.go
@@ -72,7 +72,7 @@ func (s *Server) handleDPARecord(w http.ResponseWriter, r *http.Request) {
log.Printf("console: dpa record %s: %s: %v", acct.Sqid, what, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
- live, err := s.store.LiveDPA(acct.ID)
+ live, err := s.store.LiveDPA(r.Context(), acct.ID)
if err != nil {
fail("live acceptance", err)
return
@@ -84,17 +84,17 @@ func (s *Server) handleDPARecord(w http.ResponseWriter, r *http.Request) {
return
}
} else {
- doc, err := s.store.LegalDocument(live.DocumentID)
+ doc, err := s.store.LegalDocument(r.Context(), live.DocumentID)
if err != nil {
fail("document", err)
return
}
- lh, err := s.store.LetterheadByID(live.LetterheadID)
+ lh, err := s.store.LetterheadByID(r.Context(), live.LetterheadID)
if err != nil {
fail("letterhead", err)
return
}
- docs, err := s.store.LegalDocuments("dpa")
+ docs, err := s.store.LegalDocuments(r.Context(), "dpa")
if err != nil {
fail("documents", err)
return
diff --git a/internal/console/dparecord_test.go b/internal/console/dparecord_test.go
index 815d4ea06..a84f6e854 100644
--- a/internal/console/dparecord_test.go
+++ b/internal/console/dparecord_test.go
@@ -18,7 +18,7 @@ func dpaAcceptFor(t *testing.T, fx *consoleFixture, docID, lhID int64) DPAAccept
SignerName: "Ada Lovelace", SignerRole: "Director", AcceptedBy: "paul@keymail.dev",
AcceptedIP: "127.0.0.1", AcceptedAt: time.Date(2026, 11, 20, 9, 5, 0, 0, time.UTC),
}
- if _, err := fx.st.AcceptDPA(a); err != nil {
+ if _, err := fx.st.AcceptDPA(t.Context(), a); err != nil {
t.Fatal(err)
}
return a
@@ -80,7 +80,7 @@ func TestDPARecordCopy(t *testing.T) {
fx := newConsoleFixture(t)
c := signInPaul(t, fx)
docID := dpaPublish(t, fx, "1", oplFragment, time.Now().Add(-time.Hour))
- lh, err := fx.st.SetLetterhead(Letterhead{
+ lh, err := fx.st.SetLetterhead(t.Context(), Letterhead{
Entity: "Example Hosting Limited", RegisteredOffice: "1 Main Street, Dublin", CompanyNumber: "123456",
VATNumber: "IE1234567X", Signatory: "For Example", PrivacyAddress: "privacy@example.com",
CreatedBy: "paul@keymail.dev", CreatedAt: time.Now(),
diff --git a/internal/console/legal_store.go b/internal/console/legal_store.go
index af1bddd45..5684b8e65 100644
--- a/internal/console/legal_store.go
+++ b/internal/console/legal_store.go
@@ -1,10 +1,13 @@
package console
import (
+ "context"
"database/sql"
"errors"
- "strings"
"time"
+
+ "modernc.org/sqlite"
+ sqlite3 "modernc.org/sqlite/lib"
)
// The legal documents, the letterhead and the DPA acceptances (DPA and
@@ -18,6 +21,16 @@ var (
ErrLegalVersionExists = errors.New("console: that version of this legal document is already published")
// ErrDPAAlreadyInForce: the account already has a live acceptance.
ErrDPAAlreadyInForce = errors.New("console: this account already has a DPA in force")
+ // ErrDPAAccountGone: the account is deleted, or there is no such
+ // account. Nothing may be accepted for it.
+ ErrDPAAccountGone = errors.New("console: the account is deleted or does not exist")
+ // ErrDPANotOwner: the accepting address is not an owner of the account
+ // (any more).
+ ErrDPANotOwner = errors.New("console: the accepting address is not an owner of the account")
+ // ErrDPAUnknownReference: the acceptance names a dpa document or a
+ // letterhead that does not exist. The database does not enforce the
+ // columns' REFERENCES (foreign keys are off), so AcceptDPA checks.
+ ErrDPAUnknownReference = errors.New("console: the acceptance names a document or letterhead that does not exist")
)
// LegalDocument is one published version of a legal document.
@@ -69,8 +82,9 @@ type DPAAcceptanceRow struct {
AccountSqid, AccountName string
}
+// migrateLegal runs at start, with no request ctx.
func (s *Store) migrateLegal() error {
- _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS legal_documents (
+ _, err := s.db.ExecContext(context.Background(), `CREATE TABLE IF NOT EXISTS legal_documents (
id INTEGER PRIMARY KEY,
kind TEXT NOT NULL,
version TEXT NOT NULL,
@@ -118,8 +132,11 @@ CREATE UNIQUE INDEX IF NOT EXISTS dpa_live ON dpa_acceptances(account_id) WHERE
return err
}
+// isUniqueViolation is a UNIQUE constraint failure, by the driver's
+// extended result code (as pendingMintConstraint reads it).
func isUniqueViolation(err error) bool {
- return err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed")
+ var se *sqlite.Error
+ return errors.As(err, &se) && se.Code() == sqlite3.SQLITE_CONSTRAINT_UNIQUE
}
func nullTime(t *time.Time) any {
@@ -139,8 +156,37 @@ func timePtr(n sql.NullInt64) *time.Time {
// PublishLegalDocument appends a document and returns its id, or
// ErrLegalVersionExists when the kind and version are already there.
-func (s *Store) PublishLegalDocument(d LegalDocument) (int64, error) {
- res, err := s.db.Exec(`INSERT INTO legal_documents (kind, version, url, body_url, body, sha256, summary,
+func (s *Store) PublishLegalDocument(ctx context.Context, d LegalDocument) (int64, error) {
+ return s.PublishLegalDocumentWith(ctx, d.Kind, func([]LegalDocument) (LegalDocument, error) { return d, nil })
+}
+
+// errLegalKindMismatch: decide returned a document of another kind.
+var errLegalKindMismatch = errors.New("console: the document to publish is not of the kind read")
+
+// PublishLegalDocumentWith appends the document decide returns, deciding in
+// the transaction that inserts it: decide sees the kind's documents as they
+// stand then, newest first, so whether this is the kind's first row, and
+// what that allows, cannot change between the decision and the insert. An
+// error from decide is returned as is and nothing is written. A version
+// already there is ErrLegalVersionExists.
+func (s *Store) PublishLegalDocumentWith(ctx context.Context, kind string, decide func(existing []LegalDocument) (LegalDocument, error)) (int64, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return 0, err
+ }
+ defer tx.Rollback()
+ existing, err := legalDocuments(ctx, tx, kind)
+ if err != nil {
+ return 0, err
+ }
+ d, err := decide(existing)
+ if err != nil {
+ return 0, err
+ }
+ if d.Kind != kind {
+ return 0, errLegalKindMismatch
+ }
+ res, err := tx.ExecContext(ctx, `INSERT INTO legal_documents (kind, version, url, body_url, body, sha256, summary,
published_at, effective_at, needs_notice, published_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
d.Kind, d.Version, d.URL, d.BodyURL, d.Body, d.SHA256, d.Summary,
d.PublishedAt.Unix(), nullTime(d.EffectiveAt), d.NeedsNotice, d.PublishedBy)
@@ -150,7 +196,11 @@ func (s *Store) PublishLegalDocument(d LegalDocument) (int64, error) {
}
return 0, err
}
- return res.LastInsertId()
+ id, err := res.LastInsertId()
+ if err != nil {
+ return 0, err
+ }
+ return id, tx.Commit()
}
const legalDocumentCols = `id, kind, version, url, COALESCE(body_url, ''), COALESCE(body, ''), sha256, summary,
@@ -158,6 +208,11 @@ const legalDocumentCols = `id, kind, version, url, COALESCE(body_url, ''), COALE
type rowScanner interface{ Scan(dest ...any) error }
+// legalQuerier is the read both the Store's handle and a transaction have.
+type legalQuerier interface {
+ QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
+}
+
func scanLegalDocument(r rowScanner) (LegalDocument, error) {
var d LegalDocument
var pub int64
@@ -171,10 +226,17 @@ func scanLegalDocument(r rowScanner) (LegalDocument, error) {
return d, nil
}
-// LegalDocuments is every document of the kind, newest first.
-func (s *Store) LegalDocuments(kind string) ([]LegalDocument, error) {
- rows, err := s.db.Query(`SELECT `+legalDocumentCols+` FROM legal_documents WHERE kind = ?
- ORDER BY published_at DESC, id DESC`, kind)
+// LegalDocuments is every document of the kind, newest first. Newest is
+// the highest id, everywhere (dpaInForce compares ids too): a document's
+// published_at is set in the transaction that inserts it, so the two
+// orders agree.
+func (s *Store) LegalDocuments(ctx context.Context, kind string) ([]LegalDocument, error) {
+ return legalDocuments(ctx, s.db, kind)
+}
+
+func legalDocuments(ctx context.Context, q legalQuerier, kind string) ([]LegalDocument, error) {
+ rows, err := q.QueryContext(ctx, `SELECT `+legalDocumentCols+` FROM legal_documents WHERE kind = ?
+ ORDER BY id DESC`, kind)
if err != nil {
return nil, err
}
@@ -190,11 +252,11 @@ func (s *Store) LegalDocuments(kind string) ([]LegalDocument, error) {
return out, rows.Err()
}
-// NewestLegalDocument is the latest published document of the kind, or nil,
-// nil when there is none.
-func (s *Store) NewestLegalDocument(kind string) (*LegalDocument, error) {
- d, err := scanLegalDocument(s.db.QueryRow(`SELECT `+legalDocumentCols+` FROM legal_documents WHERE kind = ?
- ORDER BY published_at DESC, id DESC LIMIT 1`, kind))
+// NewestLegalDocument is the latest published document of the kind (the
+// highest id), or nil, nil when there is none.
+func (s *Store) NewestLegalDocument(ctx context.Context, kind string) (*LegalDocument, error) {
+ d, err := scanLegalDocument(s.db.QueryRowContext(ctx, `SELECT `+legalDocumentCols+` FROM legal_documents WHERE kind = ?
+ ORDER BY id DESC LIMIT 1`, kind))
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
@@ -205,8 +267,8 @@ func (s *Store) NewestLegalDocument(kind string) (*LegalDocument, error) {
}
// LegalDocument is the document with this id, or nil, nil.
-func (s *Store) LegalDocument(id int64) (*LegalDocument, error) {
- d, err := scanLegalDocument(s.db.QueryRow(`SELECT `+legalDocumentCols+` FROM legal_documents WHERE id = ?`, id))
+func (s *Store) LegalDocument(ctx context.Context, id int64) (*LegalDocument, error) {
+ d, err := scanLegalDocument(s.db.QueryRowContext(ctx, `SELECT `+legalDocumentCols+` FROM legal_documents WHERE id = ?`, id))
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
@@ -217,12 +279,12 @@ func (s *Store) LegalDocument(id int64) (*LegalDocument, error) {
}
// SetLetterhead appends a letterhead, which becomes the current one.
-func (s *Store) SetLetterhead(l Letterhead) (int64, error) {
+func (s *Store) SetLetterhead(ctx context.Context, l Letterhead) (int64, error) {
var logo any
if len(l.Logo) > 0 {
logo = l.Logo
}
- res, err := s.db.Exec(`INSERT INTO letterhead (logo, logo_type, entity, registered_office, company_number,
+ res, err := s.db.ExecContext(ctx, `INSERT INTO letterhead (logo, logo_type, entity, registered_office, company_number,
vat_number, signatory, privacy_address, footer, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
logo, l.LogoType, l.Entity, l.RegisteredOffice, l.CompanyNumber, l.VATNumber, l.Signatory,
l.PrivacyAddress, l.Footer, l.CreatedAt.Unix(), l.CreatedBy)
@@ -250,19 +312,57 @@ func scanLetterhead(r rowScanner) (*Letterhead, error) {
}
// CurrentLetterhead is the newest letterhead, or nil, nil when none is set.
-func (s *Store) CurrentLetterhead() (*Letterhead, error) {
- return scanLetterhead(s.db.QueryRow(`SELECT ` + letterheadCols + ` FROM letterhead ORDER BY id DESC LIMIT 1`))
+func (s *Store) CurrentLetterhead(ctx context.Context) (*Letterhead, error) {
+ return scanLetterhead(s.db.QueryRowContext(ctx, `SELECT `+letterheadCols+` FROM letterhead ORDER BY id DESC LIMIT 1`))
}
// LetterheadByID is the letterhead with this id, or nil, nil.
-func (s *Store) LetterheadByID(id int64) (*Letterhead, error) {
- return scanLetterhead(s.db.QueryRow(`SELECT `+letterheadCols+` FROM letterhead WHERE id = ?`, id))
+func (s *Store) LetterheadByID(ctx context.Context, id int64) (*Letterhead, error) {
+ return scanLetterhead(s.db.QueryRowContext(ctx, `SELECT `+letterheadCols+` FROM letterhead WHERE id = ?`, id))
}
-// AcceptDPA records an acceptance, or returns ErrDPAAlreadyInForce when the
-// account already has a live one.
-func (s *Store) AcceptDPA(a DPAAcceptance) (int64, error) {
- res, err := s.db.Exec(`INSERT INTO dpa_acceptances (account_id, document_id, letterhead_id, legal_name, address,
+// AcceptDPA records an acceptance. In the one transaction that inserts it,
+// it checks what the caller's gates checked earlier and a concurrent write
+// may have changed since: the account exists and is not deleted
+// (ErrDPAAccountGone; DeleteAccount and ReapAccount end the live acceptance
+// in their own transaction, so one inserted after them would stay live),
+// AcceptedBy is still an owner of it (ErrDPANotOwner), and the document is
+// a dpa document and the letterhead exists (ErrDPAUnknownReference). An
+// account with a live acceptance already is ErrDPAAlreadyInForce.
+func (s *Store) AcceptDPA(ctx context.Context, a DPAAcceptance) (int64, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return 0, err
+ }
+ defer tx.Rollback()
+ var live int
+ if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM accounts WHERE id = ? AND deleted_at = 0`,
+ a.AccountID).Scan(&live); err != nil {
+ return 0, err
+ }
+ if live == 0 {
+ return 0, ErrDPAAccountGone
+ }
+ var role string
+ switch err := tx.QueryRowContext(ctx, `SELECT role FROM memberships WHERE account_id = ? AND address = ?`,
+ a.AccountID, a.AcceptedBy).Scan(&role); {
+ case errors.Is(err, sql.ErrNoRows):
+ return 0, ErrDPANotOwner
+ case err != nil:
+ return 0, err
+ }
+ if role != RoleOwner {
+ return 0, ErrDPANotOwner
+ }
+ var refs int
+ if err := tx.QueryRowContext(ctx, `SELECT (SELECT COUNT(*) FROM legal_documents WHERE id = ? AND kind = 'dpa')
+ + (SELECT COUNT(*) FROM letterhead WHERE id = ?)`, a.DocumentID, a.LetterheadID).Scan(&refs); err != nil {
+ return 0, err
+ }
+ if refs != 2 {
+ return 0, ErrDPAUnknownReference
+ }
+ res, err := tx.ExecContext(ctx, `INSERT INTO dpa_acceptances (account_id, document_id, letterhead_id, legal_name, address,
country, signer_name, signer_role, accepted_by, accepted_ip, accepted_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
a.AccountID, a.DocumentID, a.LetterheadID, a.LegalName, a.Address, a.Country, a.SignerName,
a.SignerRole, a.AcceptedBy, a.AcceptedIP, a.AcceptedAt.Unix())
@@ -272,7 +372,11 @@ func (s *Store) AcceptDPA(a DPAAcceptance) (int64, error) {
}
return 0, err
}
- return res.LastInsertId()
+ id, err := res.LastInsertId()
+ if err != nil {
+ return 0, err
+ }
+ return id, tx.Commit()
}
const dpaCols = `a.id, a.account_id, a.document_id, a.letterhead_id, a.legal_name, a.address, a.country,
@@ -293,8 +397,8 @@ func scanDPA(r rowScanner, extra ...any) (DPAAcceptance, error) {
}
// LiveDPA is the account's acceptance still in force, or nil, nil.
-func (s *Store) LiveDPA(accountID int64) (*DPAAcceptance, error) {
- a, err := scanDPA(s.db.QueryRow(`SELECT `+dpaCols+` FROM dpa_acceptances a
+func (s *Store) LiveDPA(ctx context.Context, accountID int64) (*DPAAcceptance, error) {
+ a, err := scanDPA(s.db.QueryRowContext(ctx, `SELECT `+dpaCols+` FROM dpa_acceptances a
WHERE a.account_id = ? AND a.ended_at IS NULL`, accountID))
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
@@ -306,8 +410,8 @@ func (s *Store) LiveDPA(accountID int64) (*DPAAcceptance, error) {
}
// LiveDPAs is every acceptance in force, newest first, with its account.
-func (s *Store) LiveDPAs() ([]DPAAcceptanceRow, error) {
- rows, err := s.db.Query(`SELECT ` + dpaCols + `, COALESCE(c.sqid, ''), COALESCE(c.name, '')
+func (s *Store) LiveDPAs(ctx context.Context) ([]DPAAcceptanceRow, error) {
+ rows, err := s.db.QueryContext(ctx, `SELECT `+dpaCols+`, COALESCE(c.sqid, ''), COALESCE(c.name, '')
FROM dpa_acceptances a LEFT JOIN accounts c ON c.id = a.account_id
WHERE a.ended_at IS NULL ORDER BY a.accepted_at DESC, a.id DESC`)
if err != nil {
@@ -329,16 +433,16 @@ func (s *Store) LiveDPAs() ([]DPAAcceptanceRow, error) {
// EndDPA ends the account's live acceptance at `at`; none live is not an
// error.
-func (s *Store) EndDPA(accountID int64, at time.Time) error {
- return endDPA(s.db, accountID, at)
+func (s *Store) EndDPA(ctx context.Context, accountID int64, at time.Time) error {
+ return endDPA(ctx, s.db, accountID, at)
}
// endDPA is EndDPA on a db or a transaction, so DeleteAccount can end the
// acceptance in the transaction that removes the account.
-func endDPA(x interface {
- Exec(string, ...any) (sql.Result, error)
+func endDPA(ctx context.Context, x interface {
+ ExecContext(context.Context, string, ...any) (sql.Result, error)
}, accountID int64, at time.Time) error {
- _, err := x.Exec(`UPDATE dpa_acceptances SET ended_at = ? WHERE account_id = ? AND ended_at IS NULL`,
+ _, err := x.ExecContext(ctx, `UPDATE dpa_acceptances SET ended_at = ? WHERE account_id = ? AND ended_at IS NULL`,
at.Unix(), accountID)
return err
}
diff --git a/internal/console/legal_store_test.go b/internal/console/legal_store_test.go
index 6975486c6..0cbe6aa8e 100644
--- a/internal/console/legal_store_test.go
+++ b/internal/console/legal_store_test.go
@@ -12,15 +12,29 @@ func legalTestDoc(version string) LegalDocument {
Summary: "s", PublishedAt: time.Unix(1_700_000_000, 0), NeedsNotice: true, PublishedBy: "op@example.com"}
}
+// legalTestOwner owns the accounts legalTestAccount makes, and accepts in
+// legalTestAcceptance.
+const legalTestOwner = "owner@example.com"
+
+// legalTestAccount creates a live account owned by legalTestOwner.
+func legalTestAccount(t *testing.T, s *Store, sqid string) int64 {
+ t.Helper()
+ acct := testAccountID()
+ if err := s.CreateAccount(acct, sqid, "Shop", legalTestOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ return acct
+}
+
func legalTestAcceptance(acct, doc, lh int64) DPAAcceptance {
return DPAAcceptance{AccountID: acct, DocumentID: doc, LetterheadID: lh, LegalName: "Shop Ltd",
Address: "1 High St", Country: "GB", SignerName: "A Owner", SignerRole: "Director",
- AcceptedBy: "a@example.com", AcceptedIP: "203.0.113.1", AcceptedAt: time.Unix(1_700_000_100, 0)}
+ AcceptedBy: legalTestOwner, AcceptedIP: "203.0.113.1", AcceptedAt: time.Unix(1_700_000_100, 0)}
}
func TestLegalDocumentsAppendOnly(t *testing.T) {
s := openTestStore(t)
- if d, err := s.NewestLegalDocument("dpa"); err != nil || d != nil {
+ if d, err := s.NewestLegalDocument(t.Context(), "dpa"); err != nil || d != nil {
t.Fatalf("empty: %v %v", d, err)
}
v1 := legalTestDoc("1")
@@ -28,35 +42,35 @@ func TestLegalDocumentsAppendOnly(t *testing.T) {
v2 := legalTestDoc("2")
v2.PublishedAt = v1.PublishedAt.Add(time.Hour)
v2.EffectiveAt = &eff
- id1, err := s.PublishLegalDocument(v1)
+ id1, err := s.PublishLegalDocument(t.Context(), v1)
if err != nil {
t.Fatal(err)
}
- if _, err := s.PublishLegalDocument(v2); err != nil {
+ if _, err := s.PublishLegalDocument(t.Context(), v2); err != nil {
t.Fatal(err)
}
- n, err := s.NewestLegalDocument("dpa")
+ n, err := s.NewestLegalDocument(t.Context(), "dpa")
if err != nil || n == nil || n.Version != "2" {
t.Fatalf("newest = %+v, %v", n, err)
}
if n.EffectiveAt == nil || n.EffectiveAt.Unix() != eff.Unix() || !n.NeedsNotice || n.Body != "<p>terms</p>" {
t.Fatalf("round trip = %+v", n)
}
- if _, err := s.PublishLegalDocument(v1); !errors.Is(err, ErrLegalVersionExists) {
+ if _, err := s.PublishLegalDocument(t.Context(), v1); !errors.Is(err, ErrLegalVersionExists) {
t.Fatalf("duplicate = %v", err)
}
- all, err := s.LegalDocuments("dpa")
+ all, err := s.LegalDocuments(t.Context(), "dpa")
if err != nil || len(all) != 2 || all[0].Version != "2" || all[1].Version != "1" {
t.Fatalf("list = %+v, %v", all, err)
}
if all[1].EffectiveAt != nil {
t.Fatalf("v1 effective_at should be nil: %v", all[1].EffectiveAt)
}
- g, err := s.LegalDocument(id1)
+ g, err := s.LegalDocument(t.Context(), id1)
if err != nil || g == nil || g.Version != "1" {
t.Fatalf("by id = %+v, %v", g, err)
}
- if g, err := s.LegalDocument(9999); err != nil || g != nil {
+ if g, err := s.LegalDocument(t.Context(), 9999); err != nil || g != nil {
t.Fatalf("missing = %v %v", g, err)
}
}
@@ -64,25 +78,25 @@ func TestLegalDocumentsAppendOnly(t *testing.T) {
func TestDPAAcceptanceOneLivePerAccount(t *testing.T) {
s := openTestStore(t)
doc, lh := legalTestDocAndLetterhead(t, s)
- acct := testAccountID()
+ acct := legalTestAccount(t, s, "dpa-one")
a := legalTestAcceptance(acct, doc, lh)
- if _, err := s.AcceptDPA(a); err != nil {
+ if _, err := s.AcceptDPA(t.Context(), a); err != nil {
t.Fatal(err)
}
- if _, err := s.AcceptDPA(a); !errors.Is(err, ErrDPAAlreadyInForce) {
+ if _, err := s.AcceptDPA(t.Context(), a); !errors.Is(err, ErrDPAAlreadyInForce) {
t.Fatalf("second = %v", err)
}
- live, err := s.LiveDPA(acct)
+ live, err := s.LiveDPA(t.Context(), acct)
if err != nil || live == nil || live.LegalName != "Shop Ltd" || live.EndedAt != nil || live.LetterheadID != lh {
t.Fatalf("live = %+v, %v", live, err)
}
- if err := s.EndDPA(acct, time.Unix(1_700_000_200, 0)); err != nil {
+ if err := s.EndDPA(t.Context(), acct, time.Unix(1_700_000_200, 0)); err != nil {
t.Fatal(err)
}
- if live, _ := s.LiveDPA(acct); live != nil {
+ if live, _ := s.LiveDPA(t.Context(), acct); live != nil {
t.Fatalf("still live: %+v", live)
}
- if _, err := s.AcceptDPA(a); err != nil {
+ if _, err := s.AcceptDPA(t.Context(), a); err != nil {
t.Fatalf("third = %v", err)
}
}
@@ -94,11 +108,11 @@ func TestEndDPAOnAccountDelete(t *testing.T) {
if err := s.CreateAccount(acct, "dpa-acct", "Shop", "owner@example.com", time.Now()); err != nil {
t.Fatal(err)
}
- id, err := s.AcceptDPA(legalTestAcceptance(acct, doc, lh))
+ id, err := s.AcceptDPA(t.Context(), legalTestAcceptance(acct, doc, lh))
if err != nil {
t.Fatal(err)
}
- rows, err := s.LiveDPAs()
+ rows, err := s.LiveDPAs(t.Context())
if err != nil || len(rows) != 1 || rows[0].AccountSqid != "dpa-acct" || rows[0].AccountName != "Shop" {
t.Fatalf("live rows = %+v, %v", rows, err)
}
@@ -106,7 +120,7 @@ func TestEndDPAOnAccountDelete(t *testing.T) {
if err := s.DeleteAccount(acct, at); err != nil {
t.Fatal(err)
}
- if live, _ := s.LiveDPA(acct); live != nil {
+ if live, _ := s.LiveDPA(t.Context(), acct); live != nil {
t.Fatalf("still live: %+v", live)
}
var ended int64
@@ -117,25 +131,25 @@ func TestEndDPAOnAccountDelete(t *testing.T) {
func TestLetterheadNewestIsCurrent(t *testing.T) {
s := openTestStore(t)
- if l, err := s.CurrentLetterhead(); err != nil || l != nil {
+ if l, err := s.CurrentLetterhead(t.Context()); err != nil || l != nil {
t.Fatalf("empty: %v %v", l, err)
}
l := Letterhead{Logo: []byte("png"), LogoType: "image/png", Entity: "One", RegisteredOffice: "R", CompanyNumber: "1",
VATNumber: "GB1", Signatory: "S", PrivacyAddress: "p@example.com", Footer: "f", CreatedBy: "op", CreatedAt: time.Unix(5, 0)}
- first, err := s.SetLetterhead(l)
+ first, err := s.SetLetterhead(t.Context(), l)
if err != nil {
t.Fatal(err)
}
l.Entity, l.Logo, l.VATNumber = "Two", nil, ""
- second, err := s.SetLetterhead(l)
+ second, err := s.SetLetterhead(t.Context(), l)
if err != nil {
t.Fatal(err)
}
- cur, err := s.CurrentLetterhead()
+ cur, err := s.CurrentLetterhead(t.Context())
if err != nil || cur == nil || cur.ID != second || cur.Entity != "Two" || len(cur.Logo) != 0 {
t.Fatalf("current = %+v, %v", cur, err)
}
- old, err := s.LetterheadByID(first)
+ old, err := s.LetterheadByID(t.Context(), first)
if err != nil || old == nil || old.Entity != "One" || string(old.Logo) != "png" || old.VATNumber != "GB1" ||
old.CreatedAt.Unix() != 5 {
t.Fatalf("first = %+v, %v", old, err)
@@ -144,11 +158,11 @@ func TestLetterheadNewestIsCurrent(t *testing.T) {
func legalTestDocAndLetterhead(t *testing.T, s *Store) (doc, lh int64) {
t.Helper()
- doc, err := s.PublishLegalDocument(legalTestDoc("1"))
+ doc, err := s.PublishLegalDocument(t.Context(), legalTestDoc("1"))
if err != nil {
t.Fatal(err)
}
- lh, err = s.SetLetterhead(Letterhead{Entity: "E", RegisteredOffice: "R", CompanyNumber: "1", Signatory: "S",
+ lh, err = s.SetLetterhead(t.Context(), Letterhead{Entity: "E", RegisteredOffice: "R", CompanyNumber: "1", Signatory: "S",
PrivacyAddress: "p@example.com", CreatedBy: "op", CreatedAt: time.Unix(1, 0)})
if err != nil {
t.Fatal(err)
@@ -163,7 +177,7 @@ func TestEndDPAOnAccountReap(t *testing.T) {
if err := s.CreateAccount(acct, "dpa-reap", "Shop", "owner@example.com", time.Now()); err != nil {
t.Fatal(err)
}
- id, err := s.AcceptDPA(legalTestAcceptance(acct, doc, lh))
+ id, err := s.AcceptDPA(t.Context(), legalTestAcceptance(acct, doc, lh))
if err != nil {
t.Fatal(err)
}
@@ -171,10 +185,10 @@ func TestEndDPAOnAccountReap(t *testing.T) {
if err := s.ReapAccount(acct, at); err != nil {
t.Fatal(err)
}
- if live, err := s.LiveDPA(acct); err != nil || live != nil {
+ if live, err := s.LiveDPA(t.Context(), acct); err != nil || live != nil {
t.Fatalf("still live: %+v, %v", live, err)
}
- if rows, err := s.LiveDPAs(); err != nil || len(rows) != 0 {
+ if rows, err := s.LiveDPAs(t.Context()); err != nil || len(rows) != 0 {
t.Fatalf("live rows = %+v, %v", rows, err)
}
var ended int64
@@ -182,3 +196,86 @@ func TestEndDPAOnAccountReap(t *testing.T) {
t.Fatalf("ended_at = %d, %v", ended, err)
}
}
+
+// An acceptance whose request passed the owner gate before the account was
+// deleted or reaped is refused when it reaches the store: the deletion
+// ended no acceptance (there was none yet), so one inserted now would stay
+// live for an account that no longer exists.
+func TestAcceptDPAAfterAccountDeletionRefused(t *testing.T) {
+ for name, remove := range map[string]func(s *Store, acct int64, at time.Time) error{
+ "delete": (*Store).DeleteAccount,
+ "reap": (*Store).ReapAccount,
+ } {
+ t.Run(name, func(t *testing.T) {
+ s := openTestStore(t)
+ doc, lh := legalTestDocAndLetterhead(t, s)
+ acct := legalTestAccount(t, s, "dpa-gone-"+name)
+ // The owner gate passed here; then the deletion commits.
+ if err := remove(s, acct, time.Unix(1_700_000_050, 0)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.AcceptDPA(t.Context(), legalTestAcceptance(acct, doc, lh)); !errors.Is(err, ErrDPAAccountGone) {
+ t.Fatalf("accept after %s = %v, want ErrDPAAccountGone", name, err)
+ }
+ if live, err := s.LiveDPA(t.Context(), acct); err != nil || live != nil {
+ t.Fatalf("live = %+v, %v", live, err)
+ }
+ var n int
+ if err := s.db.QueryRow(`SELECT COUNT(*) FROM dpa_acceptances WHERE account_id = ?`, acct).Scan(&n); err != nil || n != 0 {
+ t.Fatalf("%d acceptance rows, %v", n, err)
+ }
+ })
+ }
+ // An account that never existed is refused the same way.
+ s := openTestStore(t)
+ doc, lh := legalTestDocAndLetterhead(t, s)
+ if _, err := s.AcceptDPA(t.Context(), legalTestAcceptance(testAccountID(), doc, lh)); !errors.Is(err, ErrDPAAccountGone) {
+ t.Fatalf("no such account = %v, want ErrDPAAccountGone", err)
+ }
+}
+
+// The accepting address must still be an owner when the row is written.
+func TestAcceptDPARefusesNonOwner(t *testing.T) {
+ s := openTestStore(t)
+ doc, lh := legalTestDocAndLetterhead(t, s)
+ acct := legalTestAccount(t, s, "dpa-member")
+ if err := s.AddMember(acct, "member@example.com", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ for _, addr := range []string{"member@example.com", "stranger@example.com"} {
+ a := legalTestAcceptance(acct, doc, lh)
+ a.AcceptedBy = addr
+ if _, err := s.AcceptDPA(t.Context(), a); !errors.Is(err, ErrDPANotOwner) {
+ t.Errorf("%s = %v, want ErrDPANotOwner", addr, err)
+ }
+ }
+ if live, err := s.LiveDPA(t.Context(), acct); err != nil || live != nil {
+ t.Fatalf("live = %+v, %v", live, err)
+ }
+}
+
+// Foreign keys are off, so the REFERENCES on the acceptance's document and
+// letterhead columns enforce nothing: AcceptDPA checks both.
+func TestAcceptDPARefusesUnknownReferences(t *testing.T) {
+ s := openTestStore(t)
+ doc, lh := legalTestDocAndLetterhead(t, s)
+ acct := legalTestAccount(t, s, "dpa-refs")
+ terms := legalTestDoc("t1")
+ terms.Kind = "terms"
+ termsID, err := s.PublishLegalDocument(t.Context(), terms)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for name, a := range map[string]DPAAcceptance{
+ "missing document": legalTestAcceptance(acct, doc+1000, lh),
+ "missing letterhead": legalTestAcceptance(acct, doc, lh+1000),
+ "terms document": legalTestAcceptance(acct, termsID, lh),
+ } {
+ if _, err := s.AcceptDPA(t.Context(), a); !errors.Is(err, ErrDPAUnknownReference) {
+ t.Errorf("%s = %v, want ErrDPAUnknownReference", name, err)
+ }
+ }
+ if live, err := s.LiveDPA(t.Context(), acct); err != nil || live != nil {
+ t.Fatalf("live = %+v, %v", live, err)
+ }
+}
diff --git a/internal/console/oplegal.go b/internal/console/oplegal.go
index 52624f863..284c76bdc 100644
--- a/internal/console/oplegal.go
+++ b/internal/console/oplegal.go
@@ -120,7 +120,6 @@ type legalPublishForm struct {
// legalDocRow is one row of the published versions.
type legalDocRow struct {
Kind, Version, URL, Published, Applies, SHA256, Short string
- at time.Time
id int64
}
@@ -168,11 +167,11 @@ func legalEarliestEffective(now time.Time) time.Time {
// 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) {
+func (s *Server) legalView(ctx context.Context, kind string, draft *legalDraft, lh *legalLetterheadForm) (*legalView, error) {
v := &legalView{}
all := map[string][]LegalDocument{}
for _, k := range legalKinds {
- docs, err := s.store.LegalDocuments(k)
+ docs, err := s.store.LegalDocuments(ctx, k)
if err != nil {
return nil, err
}
@@ -180,7 +179,7 @@ func (s *Server) legalView(kind string, draft *legalDraft, lh *legalLetterheadFo
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}
+ id: d.ID}
if d.EffectiveAt != nil {
row.Applies = d.EffectiveAt.UTC().Format(legalDateLayout)
}
@@ -190,13 +189,9 @@ func (s *Server) legalView(kind string, draft *legalDraft, lh *legalLetterheadFo
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
- })
+ // Newest first across the kinds, as each kind's own list is: by id,
+ // the one order of publication (LegalDocuments).
+ sort.Slice(v.Docs, func(i, j int) bool { return v.Docs[i].id > v.Docs[j].id })
f := legalPublishForm{Kind: kind, Tabs: opTabs{Label: "Document"}}
for _, k := range legalKinds {
@@ -219,7 +214,7 @@ func (s *Server) legalView(kind string, draft *legalDraft, lh *legalLetterheadFo
}
v.Publish = f
- live, err := s.store.LiveDPAs()
+ live, err := s.store.LiveDPAs(ctx)
if err != nil {
return nil, err
}
@@ -236,7 +231,7 @@ func (s *Server) legalView(kind string, draft *legalDraft, lh *legalLetterheadFo
})
}
- cur, err := s.store.CurrentLetterhead()
+ cur, err := s.store.CurrentLetterhead(ctx)
if err != nil {
return nil, err
}
@@ -254,7 +249,7 @@ func (s *Server) legalView(kind string, draft *legalDraft, lh *legalLetterheadFo
// 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)
+ v, err := s.legalView(r.Context(), legalKindOf(kind), draft, lh)
if err != nil {
log.Printf("console: legal page: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
@@ -349,7 +344,9 @@ func legalField(v string, max int, lines bool) (string, bool) {
// 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.
+// url otherwise, and pins the bytes' digest. Which of the rows above it is
+// is decided after the fetch, in the transaction that inserts it
+// (legalPublishDecision).
func (s *Server) handleOpLegalPublish(w http.ResponseWriter, r *http.Request) {
addr, raw, ok := s.legalFormGate(w, r)
if !ok {
@@ -387,49 +384,25 @@ func (s *Server) handleOpLegalPublish(w http.ResponseWriter, r *http.Request) {
return
}
- existing, err := s.store.LegalDocuments(kind)
+ // A version already there is refused before anything is fetched; the
+ // insert's own check covers a publish racing this one.
+ existing, err := s.store.LegalDocuments(r.Context(), 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
- }
+ // Fetch first. Whether this is the kind's first row is decided only
+ // after, in the transaction that inserts it (legalPublishDecision): a
+ // publish that read an empty kind before a slow fetch must not still
+ // count as the first once another has landed.
fetchURL := pageURL
if kind == "dpa" {
fetchURL = bodyURL
@@ -441,6 +414,7 @@ func (s *Server) handleOpLegalPublish(w http.ResponseWriter, r *http.Request) {
fail(http.StatusBadRequest, legalFetchText(fetchURL, err))
return
}
+ doc := LegalDocument{Kind: kind, Version: version, URL: pageURL, BodyURL: bodyURL, Summary: summary, PublishedBy: addr}
if kind == "dpa" {
if !utf8.Valid(b) {
fail(http.StatusBadRequest, legalCanonicalText(errors.New("text that isn't UTF-8")))
@@ -455,10 +429,18 @@ func (s *Server) handleOpLegalPublish(w http.ResponseWriter, r *http.Request) {
sum := sha256.Sum256(b)
doc.SHA256 = hex.EncodeToString(sum[:])
- if _, err := s.store.PublishLegalDocument(doc); errors.Is(err, ErrLegalVersionExists) {
+ _, err = s.store.PublishLegalDocumentWith(r.Context(), kind, func(existing []LegalDocument) (LegalDocument, error) {
+ return s.legalPublishDecision(doc, d, r.PostFormValue("mode"), existing)
+ })
+ var refused legalRefusal
+ switch {
+ case errors.As(err, &refused):
+ fail(refused.status, refused.msg)
+ return
+ case errors.Is(err, ErrLegalVersionExists):
fail(http.StatusConflict, legalErrExists)
return
- } else if err != nil {
+ case err != nil:
log.Printf("console: legal publish %s %s: %v", kind, version, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
@@ -468,6 +450,52 @@ func (s *Server) handleOpLegalPublish(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/fleet/legal?kind="+url.QueryEscape(kind)+"#versions", http.StatusSeeOther)
}
+// legalRefusal is a publish legalPublishDecision refuses: the status and
+// the page's error notice.
+type legalRefusal struct {
+ status int
+ msg string
+}
+
+func (e legalRefusal) Error() string { return e.msg }
+
+// legalPublishDecision completes doc, fetched and checked, from the kind's
+// documents as they stand in the inserting transaction (existing), the
+// form as typed (d) and the form's mode as it was shown: its publish and
+// effective dates, and whether it needs notice. A form shown as the kind's
+// first ("first-dpa" or "baseline") is refused once a row exists: it was
+// filled in for a row that needs no notice, and is not that row any more.
+func (s *Server) legalPublishDecision(doc LegalDocument, d legalDraft, mode string, existing []LegalDocument) (LegalDocument, error) {
+ first := len(existing) == 0
+ if !first && (mode == "first-dpa" || mode == "baseline") {
+ return doc, legalRefusal{http.StatusConflict, legalErrForm}
+ }
+ now := s.now().UTC().Truncate(time.Second)
+ doc.PublishedAt = now
+ switch {
+ case first && doc.Kind == "dpa", !first && d.NoNotice:
+ doc.EffectiveAt = &now
+ case first:
+ eff, err := time.Parse(legalDateLayout, d.Effective)
+ if err != nil {
+ return doc, legalRefusal{http.StatusBadRequest, legalErrForm}
+ }
+ doc.EffectiveAt = &eff
+ case doc.Kind == "dpa":
+ eff, err := time.Parse(legalDateLayout, d.Effective)
+ if err != nil {
+ return doc, legalRefusal{http.StatusBadRequest, legalErrForm}
+ }
+ if eff.Before(now.Add(legalNoticeFloor)) {
+ return doc, legalRefusal{http.StatusBadRequest, legalErrFloor}
+ }
+ doc.NeedsNotice, doc.EffectiveAt = true, &eff
+ default:
+ doc.NeedsNotice = true
+ }
+ return doc, nil
+}
+
// 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
@@ -563,7 +591,7 @@ func (s *Server) handleOpLegalLetterhead(w http.ResponseWriter, r *http.Request)
}
l.Logo = b
} else {
- cur, err := s.store.CurrentLetterhead()
+ cur, err := s.store.CurrentLetterhead(r.Context())
if err != nil {
log.Printf("console: letterhead: current: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
@@ -573,7 +601,7 @@ func (s *Server) handleOpLegalLetterhead(w http.ResponseWriter, r *http.Request)
l.Logo, l.LogoType = cur.Logo, cur.LogoType
}
}
- id, err := s.store.SetLetterhead(l)
+ id, err := s.store.SetLetterhead(r.Context(), l)
if err != nil {
log.Printf("console: letterhead: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
diff --git a/internal/console/oplegal_test.go b/internal/console/oplegal_test.go
index a96289ed5..6e6843719 100644
--- a/internal/console/oplegal_test.go
+++ b/internal/console/oplegal_test.go
@@ -15,6 +15,7 @@ import (
"regexp"
"strconv"
"strings"
+ "sync"
"sync/atomic"
"testing"
"time"
@@ -136,7 +137,7 @@ func oplPNG(t *testing.T) []byte {
func oplDocs(t *testing.T, fx *consoleFixture, kind string) []LegalDocument {
t.Helper()
- docs, err := fx.st.LegalDocuments(kind)
+ docs, err := fx.st.LegalDocuments(t.Context(), kind)
if err != nil {
t.Fatal(err)
}
@@ -195,7 +196,7 @@ func TestOpLegalNonOperator404(t *testing.T) {
if n := len(oplDocs(t, fx, "dpa")); n != 0 {
t.Fatalf("%d dpa rows", n)
}
- if lh, _ := fx.st.CurrentLetterhead(); lh != nil {
+ if lh, _ := fx.st.CurrentLetterhead(t.Context()); lh != nil {
t.Fatal("a letterhead was stored")
}
}
@@ -446,7 +447,7 @@ func TestOpLegalLetterhead(t *testing.T) {
if status != http.StatusSeeOther || !strings.HasPrefix(loc, "/fleet/legal") {
t.Fatalf("save = %d %q %s", status, loc, body)
}
- lh, err := fx.st.CurrentLetterhead()
+ lh, err := fx.st.CurrentLetterhead(t.Context())
if err != nil || lh == nil {
t.Fatalf("letterhead %v %v", lh, err)
}
@@ -482,7 +483,7 @@ func TestOpLegalLetterhead(t *testing.T) {
t.Errorf("%s = %d %s", name, status, body)
}
}
- if lh, _ := fx.st.CurrentLetterhead(); lh.ID != first {
+ if lh, _ := fx.st.CurrentLetterhead(t.Context()); lh.ID != first {
t.Fatal("a refused logo saved a letterhead")
}
@@ -491,14 +492,14 @@ func TestOpLegalLetterhead(t *testing.T) {
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" {
+ if lh, _ := fx.st.CurrentLetterhead(t.Context()); !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 != "" {
+ if lh, _ := fx.st.CurrentLetterhead(t.Context()); !bytes.Equal(lh.Logo, svg) || lh.Footer != "" {
t.Fatalf("resave lost the logo or kept the footer: %+v", lh)
}
@@ -616,14 +617,14 @@ func TestOpLegalRequiresFreshAuth(t *testing.T) {
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 {
+ if lh, _ := fx.st.CurrentLetterhead(t.Context()); 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()
+ lh, _ := fx.st.CurrentLetterhead(t.Context())
if lh == nil || !bytes.Equal(lh.Logo, logo) || lh.LogoType != "image/png" || lh.Entity != "Shop Limited" {
t.Fatalf("resumed letterhead = %+v", lh)
}
@@ -649,7 +650,7 @@ func TestOpLegalCSRF(t *testing.T) {
if n := len(oplDocs(t, fx, "dpa")); n != 0 || hits.Load() != 0 {
t.Fatalf("%d dpa rows, %d fetches", n, hits.Load())
}
- if lh, _ := fx.st.CurrentLetterhead(); lh != nil {
+ if lh, _ := fx.st.CurrentLetterhead(t.Context()); lh != nil {
t.Fatal("a letterhead was stored")
}
@@ -673,17 +674,17 @@ func TestOpLegalListsAcceptances(t *testing.T) {
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/",
+ v1, err := fx.st.PublishLegalDocument(t.Context(), 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/",
+ if _, err := fx.st.PublishLegalDocument(t.Context(), 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",
+ lhID, err := fx.st.SetLetterhead(t.Context(), 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)
@@ -692,7 +693,10 @@ func TestOpLegalListsAcceptances(t *testing.T) {
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,
+ if err := fx.st.AddMember(acct.ID, "kim@example.com", RoleOwner, now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.AcceptDPA(t.Context(), 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)
@@ -780,3 +784,176 @@ func oplRawPost(t *testing.T, c *http.Client, u, ct, body string) (int, string)
b, _ := io.ReadAll(res.Body)
return res.StatusCode, string(b)
}
+
+// oplSlowSite is oplSite whose page at slow is held: arrived is closed when
+// a request for it comes in, and it is answered once release is called.
+func oplSlowSite(t *testing.T, fx *consoleFixture, pages map[string]string, slow string) (srv *httptest.Server, arrived <-chan struct{}, release func()) {
+ t.Helper()
+ in, out := make(chan struct{}), make(chan struct{})
+ var inOnce, outOnce sync.Once
+ srv = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b, ok := pages[r.URL.Path]
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ if r.URL.Path == slow {
+ inOnce.Do(func() { close(in) })
+ <-out
+ }
+ _, _ = io.WriteString(w, b)
+ }))
+ release = func() { outOnce.Do(func() { close(out) }) }
+ t.Cleanup(srv.Close)
+ t.Cleanup(release) // runs first: a held request must not block Close
+ fx.srv.legalHTTP = legalTestClient(srv)
+ return srv, in, release
+}
+
+// oplPostAsync posts the publish form from another goroutine; the reply
+// arrives on the channel as status and body.
+func oplPostAsync(fx *consoleFixture, c *http.Client, csrf string, kv ...string) <-chan [2]string {
+ v := url.Values{"csrf": {csrf}}
+ for i := 0; i+1 < len(kv); i += 2 {
+ v.Set(kv[i], kv[i+1])
+ }
+ done := make(chan [2]string, 1)
+ go func() {
+ res, err := c.PostForm(fx.ts.URL+"/fleet/legal/publish", v)
+ if err != nil {
+ done <- [2]string{"error", err.Error()}
+ return
+ }
+ defer res.Body.Close()
+ b, _ := io.ReadAll(res.Body)
+ done <- [2]string{strconv.Itoa(res.StatusCode), string(b)}
+ }()
+ return done
+}
+
+// oplWait waits for ch, or fails after a while.
+func oplWait[T any](t *testing.T, ch <-chan T, what string) T {
+ t.Helper()
+ select {
+ case v := <-ch:
+ return v
+ case <-time.After(15 * time.Second):
+ t.Fatalf("timed out waiting for %s", what)
+ }
+ var zero T
+ return zero
+}
+
+// Two first publications of a kind overlap: A reads an empty kind and
+// fetches slowly; B publishes meanwhile. Only one row is the kind's first:
+// A, whose form was the first-row form, is refused once B has landed,
+// rather than becoming a second row that needed no notice.
+func TestOpLegalConcurrentFirstPublish(t *testing.T) {
+ for _, tc := range []struct{ kind, mode string }{{"dpa", "first-dpa"}, {"privacy", "baseline"}} {
+ t.Run(tc.kind, func(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInOperator(t, fx)
+ oplFresh(t, fx, c)
+ srv, arrived, release := oplSlowSite(t, fx, map[string]string{"/a": "<p>Version A</p>", "/b": "<p>Version B</p>"}, "/a")
+ form := func(version, path string) []string {
+ kv := []string{"kind", tc.kind, "version", version, "url", srv.URL + path, "summary", "As it is.", "mode", tc.mode}
+ if tc.kind == "dpa" {
+ // A dpa fetches its agreement text; its page is only linked.
+ kv[5] = srv.URL + "/dpa/" + version + "/"
+ kv = append(kv, "body_url", srv.URL+path)
+ } else {
+ kv = append(kv, "effective", "2025-05-01")
+ }
+ return kv
+ }
+
+ // The form both operators had open offered the first row.
+ _, _, page := get(t, c, fx.ts.URL+"/fleet/legal?kind="+tc.kind)
+ if !strings.Contains(page, `name="mode" value="`+tc.mode+`"`) {
+ t.Fatalf("the empty kind's form does not carry mode %q:\n%s", tc.mode, page)
+ }
+
+ a := oplPostAsync(fx, c, sessionToken(t, fx, c), form("A", "/a")...)
+ oplWait(t, arrived, "A's fetch")
+ if status, loc, body := oplPublish(t, fx, c, form("B", "/b")...); status != http.StatusSeeOther {
+ t.Fatalf("B = %d %q %s", status, loc, body)
+ }
+ release()
+ got := oplWait(t, a, "A's reply")
+ if got[0] != strconv.Itoa(http.StatusConflict) || !strings.Contains(got[1], legalErrForm) {
+ t.Fatalf("A = %s, want 409 with the form error:\n%s", got[0], got[1])
+ }
+ docs := oplDocs(t, fx, tc.kind)
+ if len(docs) != 1 || docs[0].Version != "B" || docs[0].NeedsNotice {
+ t.Fatalf("rows = %+v, want B alone as the first row", docs)
+ }
+ })
+ }
+}
+
+// Publications that finish out of the order they started still have one
+// order: the id, which every reader uses. v2 (needs notice) starts first
+// and fetches slowly; v3 (no notice) starts and lands meanwhile. The form
+// offers the highest id, the in-force calculation and the pending line
+// agree with it, and published_at follows the ids.
+func TestOpLegalOutOfOrderPublicationsAgree(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInOperator(t, fx)
+ oplFresh(t, fx, c)
+ var clock atomic.Int64
+ base := time.Now().UTC()
+ clock.Store(base.UnixNano())
+ fx.srv.opNow = func() time.Time { return time.Unix(0, clock.Load()).UTC() }
+ srv, arrived, release := oplSlowSite(t, fx, map[string]string{
+ "/1": "<p>Version 1</p>", "/2": "<p>Version 2</p>", "/3": "<p>Version 3</p>"}, "/2")
+ form := func(version string, kv ...string) []string {
+ return append([]string{"kind", "dpa", "version", version, "url", srv.URL + "/dpa/" + version + "/",
+ "body_url", srv.URL + "/" + version, "summary", "Changes in " + version + "."}, kv...)
+ }
+ if status, _, body := oplPublish(t, fx, c, form("1", "mode", "first-dpa")...); status != http.StatusSeeOther {
+ t.Fatalf("v1 = %d %s", status, body)
+ }
+ dpaLetterhead(t, fx, "Example Hosting Limited")
+
+ eff := base.AddDate(0, 0, 40).Format("2006-01-02")
+ v2 := oplPostAsync(fx, c, sessionToken(t, fx, c), form("2", "mode", "later-dpa", "effective", eff)...)
+ oplWait(t, arrived, "v2's fetch")
+ clock.Add(int64(time.Minute))
+ if status, _, body := oplPublish(t, fx, c, form("3", "mode", "later-dpa", "no_notice", "on")...); status != http.StatusSeeOther {
+ t.Fatalf("v3 = %d %s", status, body)
+ }
+ clock.Add(int64(time.Minute))
+ release()
+ if got := oplWait(t, v2, "v2's reply"); got[0] != strconv.Itoa(http.StatusSeeOther) {
+ t.Fatalf("v2 = %s:\n%s", got[0], got[1])
+ }
+
+ docs := oplDocs(t, fx, "dpa")
+ if len(docs) != 3 || docs[0].Version != "2" || docs[1].Version != "3" || docs[2].Version != "1" {
+ t.Fatalf("newest first = %+v, want 2 (landed last), 3, 1", docs)
+ }
+ for i := 1; i < len(docs); i++ {
+ if docs[i-1].ID <= docs[i].ID || docs[i-1].PublishedAt.Before(docs[i].PublishedAt) {
+ t.Fatalf("%s (id %d, %v) is listed before %s (id %d, %v)", docs[i-1].Version, docs[i-1].ID,
+ docs[i-1].PublishedAt, docs[i].Version, docs[i].ID, docs[i].PublishedAt)
+ }
+ }
+ newest, err := fx.st.NewestLegalDocument(t.Context(), "dpa")
+ if err != nil || newest == nil || newest.ID != docs[0].ID {
+ t.Fatalf("newest = %+v, %v, want v2", newest, err)
+ }
+ // An owner without an acceptance is offered the newest.
+ if h := dpaHidden(t, dpaSettings(t, fx, c)); h["document_id"] != itoa64(newest.ID) {
+ t.Errorf("the form offers document %s, want %d", h["document_id"], newest.ID)
+ }
+ // An owner who accepted v1: v3 (no notice) is in force, v2 is pending,
+ // and pending is the newest the form offers.
+ accepted := DPAAcceptance{AccountID: OpsAccountID, DocumentID: docs[2].ID}
+ now := fx.srv.now()
+ if in := dpaInForce(accepted, docs, nil, now); in.Version != "3" {
+ t.Errorf("in force = %q, want 3", in.Version)
+ }
+ if p := dpaPending(accepted, docs, nil, now); p == nil || p.ID != newest.ID {
+ t.Errorf("pending = %+v, want v2, the newest", p)
+ }
+}
diff --git a/internal/console/ownership.go b/internal/console/ownership.go
index 92f196866..16834ade4 100644
--- a/internal/console/ownership.go
+++ b/internal/console/ownership.go
@@ -974,7 +974,7 @@ func (s *Store) DeleteAccount(accountID int64, now time.Time) error {
return err
}
// Its live DPA acceptance ends with it (legal_store.go).
- if err := endDPA(tx, accountID, now); err != nil {
+ if err := endDPA(ctx, tx, accountID, now); err != nil {
return err
}
// Anyone whose landing spot was this account gets sent back to the picker
diff --git a/internal/console/server.go b/internal/console/server.go
index 9832eacf7..6156b6323 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1168,8 +1168,11 @@ type Server struct {
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.
+ // at its own server. dpaAcceptHook, when set (tests only), runs in
+ // handleDPAAccept after its checks and before the acceptance is
+ // recorded (dpapane.go).
legalHTTP *http.Client
+ dpaAcceptHook func()
alertSeal atomic.Pointer[connectorSeal]
alertTests alertTestWindow
alertClock func() time.Time
@@ -4234,48 +4237,6 @@ func (s *Server) handleAccountSettings(w http.ResponseWriter, r *http.Request) {
s.render(w, http.StatusOK, "account_settings", p)
}
-// accountSettingsPage builds the account settings page for a viewer the
-// caller has already admitted with role. On false it has answered. The DPA
-// accept POST (dpapane.go) renders it too, with its pane's form refused.
-func (s *Server) accountSettingsPage(w http.ResponseWriter, r *http.Request, addr, raw string, acct *Account, role string) (page, bool) {
- p := s.accountPage(w, r, addr, raw, acct, role)
- p.Title = "Account settings"
- p.ActiveNav = "settings"
- n, err := s.store.AppCount(acct.ID)
- if err != nil {
- s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read your apps. Please try again.")
- return p, false
- }
- p.HasApps = n > 0
- p.AccountStore = s.accountStorePane(r.Context(), acct)
- // The service-credential pane (svcpage.go), owners only — see page's
- // Services field for why a member gets no section rather than an empty
- // one.
- if role == RoleOwner {
- s.servicePane(&p, acct)
- }
- // The account's own Errors log level: the account's telemetry object,
- // the key the two account forms write, folded over the defaults. No app
- // layer is read (an empty app name would name apps/<sqid>//telemetry.json,
- // which nothing writes). A failed read is said rather than defaulted (see
- // ErrLevelUnread), and never fails the page. A bucketless console folds
- // the defaults, as telemetry.Resolve does.
- if s.cfg.Releases == nil {
- p.ErrLevelSetting = telemetry.Fold(telemetry.Settings{}, telemetry.Settings{})
- } else if st, _, err := telemetry.Read(r.Context(), s.cfg.Releases, telemetry.AccountKey(acct.Sqid)); err != nil {
- log.Printf("console: account telemetry %s: %v", acct.Sqid, err)
- p.ErrLevelUnread = true
- } else {
- p.ErrLevelSetting = telemetry.Fold(st, telemetry.Settings{})
- }
- // The analytics switch is the OTHER half of that same resolved object —
- // one settings file, one read — under the name its own section uses.
- p.AnalyticsSetting, p.AnalyticsUnread = p.ErrLevelSetting, p.ErrLevelUnread
- s.accountSubdomainPane(r.Context(), &p, acct)
- s.dpaPaneFor(&p, acct, role)
- return p, true
-}
-
// accountPage fills the chrome every account-scoped page shares — the
// switcher, the base URL its forms post to, the viewer's role — and records
// the MRU, so signing in lands you back on the account you were last in.
diff --git a/internal/console/store.go b/internal/console/store.go
index 6cb66fab7..8ad175e5d 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -1948,7 +1948,7 @@ func (s *Store) ReapAccount(accountID int64, now time.Time) error {
return err
}
// Its live DPA acceptance ends with it (legal_store.go).
- if err := endDPA(tx, accountID, now); err != nil {
+ if err := endDPA(context.Background(), tx, accountID, now); err != nil {
return err
}
return tx.Commit()
diff --git a/internal/console/templates/ops_legal.html b/internal/console/templates/ops_legal.html
index 9836bbf34..a66f9668e 100644
--- a/internal/console/templates/ops_legal.html
+++ b/internal/console/templates/ops_legal.html
@@ -30,6 +30,9 @@
<form method="post" action="/fleet/legal/publish">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<input type="hidden" name="kind" value="{{.Kind}}">
+ {{- /* The mode the form was shown in: a first row's form is refused
+ once another row has landed (legalPublishDecision). */}}
+ <input type="hidden" name="mode" value="{{.Mode}}">
{{- 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>