console: guarded fetch and canonical check for legal documents
Extract newGuardedHTTPClient from the alert client (same behaviour), add fetchLegalText (https only, no redirects, 2 MiB, short errors) and canonicalAgreement (tokenizer allow-list, nothing rewritten).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
internal/console/alertdial.go+10 −3internal/console/legalfetch.go+163 −0internal/console/legalfetch_test.go+144 −0
Intent
<task-notification> <task-id>a22dc8d126166ec89</task-id> <tool-use-id>toolu_017VB9J6fAnmd7zqkibBP8AF</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/260ddc60-0dfc-4cf8-8857-7688d6275097/tasks/a22dc8d126166ec89.output</output-file> <status>completed</status> <summary>Agent "Review Task 1 (spec + quality)" 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>### Spec Compliance - ❌ Issues found: - The brief says the acceptance ends when the account is deleted, and "every account-delete path" must go through that. `Store.ReapAccount` (internal/console/store.go:1906, tombstone at :1946) is a second path that tombstones an account. It is called from internal/console/materialize.go:136. It does not call `endDPA`, so a reaped account keeps a live acceptance with `ended_at IS NULL`. That row shows up in `LiveDPAs` (it uses a LEFT JOIN, so the row stays listed) and blocks nothing, but it is wrong. ReapAccount sets `deleted_at` in the same way as DeleteAccount, so it should call `endDPA(tx, accountID, now)` before commit. No test covers it. The brief's own test (`TestEndDPAOnAccountDelete`) only exercises `DeleteAccount`. - The three tables and their columns match spec §3.1, §3.3 and §3.6 exactly (legal_snapshot of types, NOT NULLs, `UNIQUE(kind, version)`, the partial index `dpa_live`). The interface signatures match the brief. - `internal/console/store_gate.go:273-275` is outside the brief's file list, but it is needed. The report says the schema census fails without it, and the NonApp classification is reasonable. I did not re-run the census tests. - ⚠️ Cannot verify from the diff: - The full console suite was never run to completion, as the report admits. The tests listed as passing are the targeted ones only. - TDD order: the implementer admits they wrote the implementation first and then moved it aside to capture the RED run. ### Strengths - Columns, constraints and the partial unique index match the spec and the brief (internal/console/legal_store.go:96-135). - `DeleteAccount` ends the acceptance with `endDPA(tx, ...)` inside the same transaction as the `deleted_at` update, and both sit before `tx.Commit()` (internal/console/ownership.go:968-980). The rollback defer covers the error paths. - Passing `endDPA` a db-or-tx interface avoids duplicating the SQL. - NULL handling is careful: COALESCE for text columns, NullInt64 for times, empty Logo stored as NULL. - `ended_at` is the only column ever updated. The code follows the append-only rule. - The tests check real round trips: `EffectiveAt` nil versus set, newest-first ordering, an old letterhead still readable by id, and the `ended_at` value read straight from the database. ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) 1. `ReapAccount` does not end the DPA acceptance. See internal/console/store.go:1946 and internal/console/materialize.go:136. This is a second account-tombstoning path. Add `endDPA(tx, accountID, now)` in the same transaction, and add a test that reaps an account holding a live acceptance. #### Minor (Nice to Have) 1. `isUniqueViolation` (internal/console/legal_store.go:131) matches on the error string. This is fragile, and it could confuse a UNIQUE failure from another constraint. It is acceptable here because each insert has only one unique constraint. Check whether the repo already has a shared helper for this before keeping a private one. 2. `TestDPAAcceptanceOneLivePerAccount` and `TestEndDPAOnAccountDelete` ignore the errors from `PublishLegalDocument` and `SetLetterhead` (`doc, _ :=` and `lh, _ :=`). A failure there would surface only as a confusing downstream failure. 3. Foreign keys are declared (`REFERENCES`), and there is no test that `AcceptDPA` refuses a missing document or letterhead. That depends on the connection's foreign-key pragma, which I did not check. ### Assessment **Task quality:** Needs fixes **Reasoning:** The store, schema and `DeleteAccount` change are correct and match the spec. However, `ReapAccount` is a second account-tombstone path that leaves the acceptance live, and the brief's constraint requires every account-delete path to end it.</result> <usage><subagent_tokens>62480</subagent_tokens><tool_uses>7</tool_uses><duration_ms>54177</duration_ms></usage> </task-notification>
Attributed to this commit: 9.22 g CO₂e (1,144,281 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/internal/console/alertdial.go b/internal/console/alertdial.go| index 9c4eedaf0..14af65f4a 100644 |
| --- a/internal/console/alertdial.go |
| +++ b/internal/console/alertdial.go |
| @@ -157,8 +157,15 @@ var errRefusedAddr = errors.New("alert dial: address refused") |
| // newAlertHTTPClient is the client every Slack and webhook send goes |
| // through. Production passes refusedAddr; only a test passes anything else. |
| func newAlertHTTPClient(refused func(netip.Addr) bool) *http.Client { |
| + return newGuardedHTTPClient(refused, alertSendTimeout) |
| +} |
| + |
| +// newGuardedHTTPClient is the dial-guarded client behind the alert sends and |
| +// the legal-document fetch: dial-time refusal, no proxy, no redirects, no |
| +// kept connections, and timeout for the whole exchange. |
| +func newGuardedHTTPClient(refused func(netip.Addr) bool, timeout time.Duration) *http.Client { |
| dialer := &net.Dialer{ |
| - Timeout: alertSendTimeout, |
| + Timeout: timeout, |
| // Control runs on the address being connected to, after any DNS |
| // answer, so a name that rebinds between save and send is caught. |
| Control: func(network, address string, _ syscall.RawConn) error { |
| @@ -177,7 +184,7 @@ func newAlertHTTPClient(refused func(netip.Addr) bool) *http.Client { |
| Transport: &http.Transport{ |
| Proxy: nil, |
| DialContext: dialer.DialContext, |
| - TLSHandshakeTimeout: alertSendTimeout, |
| + TLSHandshakeTimeout: timeout, |
| ForceAttemptHTTP2: true, |
| // No idle connection to a host a tenant chose outlives its send, |
| // HTTP/2 included. Alerts are rare; a fresh dial each time also |
| @@ -186,7 +193,7 @@ func newAlertHTTPClient(refused func(netip.Addr) bool) *http.Client { |
| MaxResponseHeaderBytes: 16 << 10, |
| }, |
| CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, |
| - Timeout: alertSendTimeout, |
| + Timeout: timeout, |
| } |
| } |
diff --git a/internal/console/legalfetch.go b/internal/console/legalfetch.go| new file mode 100644 |
| index 000000000..6842763d7 |
| --- /dev/null |
| +++ b/internal/console/legalfetch.go |
| @@ -0,0 +1,163 @@ |
| +package console |
| + |
| +// The guarded fetch of a published legal document and the check that its |
| +// text is canonical. The operator publishes an agreement by URL; the console |
| +// fetches a bare HTML fragment and refuses it unless every token is on the |
| +// allow-list. Nothing is rewritten, so the stored bytes are exactly the |
| +// fetched bytes and their SHA-256 identifies the text. |
| +// |
| +// Errors here are short and safe to show an operator. They never carry the |
| +// URL or any of the body beyond a truncated token name. |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "time" |
| + "unicode/utf8" |
| + |
| + "golang.org/x/net/html" |
| +) |
| + |
| +const ( |
| + // legalFetchMax is the most of an agreement body read. |
| + legalFetchMax = 2 << 20 |
| + // legalFetchTimeout is the whole exchange. |
| + legalFetchTimeout = 10 * time.Second |
| +) |
| + |
| +// newLegalHTTPClient is the client the console fetches legal documents with. |
| +func newLegalHTTPClient() *http.Client { |
| + return newGuardedHTTPClient(refusedAddr, legalFetchTimeout) |
| +} |
| + |
| +// fetchLegalText GETs rawURL and returns its body. It refuses a non-https |
| +// URL before dialling, a redirect or any status but 200, and a body over |
| +// legalFetchMax. The client's own error names the URL, so it is reduced to a |
| +// category here. |
| +func fetchLegalText(ctx context.Context, c *http.Client, rawURL string) ([]byte, error) { |
| + u, err := url.Parse(rawURL) |
| + if err != nil || u.Scheme != "https" || u.Opaque != "" || u.Host == "" { |
| + return nil, errors.New("not https") |
| + } |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "", nil) |
| + if err != nil { |
| + return nil, errors.New("invalid url") |
| + } |
| + req.URL = u |
| + resp, err := c.Do(req) |
| + if err != nil { |
| + return nil, legalFetchErr(err) |
| + } |
| + defer resp.Body.Close() |
| + if resp.StatusCode != http.StatusOK { |
| + return nil, fmt.Errorf("status %d", resp.StatusCode) |
| + } |
| + b, err := io.ReadAll(io.LimitReader(resp.Body, legalFetchMax+1)) |
| + if err != nil { |
| + return nil, legalFetchErr(err) |
| + } |
| + if len(b) > legalFetchMax { |
| + return nil, errors.New("too large") |
| + } |
| + return b, nil |
| +} |
| + |
| +// legalFetchErr reduces a client or read error to a category. |
| +func legalFetchErr(err error) error { |
| + var netErr net.Error |
| + switch { |
| + case errors.Is(err, errRefusedAddr): |
| + return errors.New("refused address") |
| + case errors.Is(err, context.DeadlineExceeded), errors.As(err, &netErr) && netErr.Timeout(): |
| + return errors.New("timeout") |
| + } |
| + switch sendErrOf(err) { |
| + case "tls": |
| + return errors.New("tls failed") |
| + } |
| + return errors.New("connect failed") |
| +} |
| + |
| +// agreementElements are the elements an agreement fragment may use. |
| +var agreementElements = map[string]bool{ |
| + "section": true, "h2": true, "h3": true, "p": true, "ul": true, "ol": true, |
| + "li": true, "a": true, "strong": true, "em": true, "br": true, |
| +} |
| + |
| +// canonicalAgreement is nil when every token of b is on the allow-list: |
| +// the elements above, text, and on a an href that starts with "/" (not "//") |
| +// or "https://". A self-closing tag is allowed only for br. It returns an |
| +// error naming the first token that is not, so nothing needs rewriting and |
| +// the stored bytes are the fetched bytes. |
| +func canonicalAgreement(b []byte) error { |
| + z := html.NewTokenizer(bytes.NewReader(b)) |
| + for { |
| + switch z.Next() { |
| + case html.ErrorToken: |
| + if err := z.Err(); err != io.EOF { |
| + return errors.New("unreadable html") |
| + } |
| + return nil |
| + case html.TextToken: |
| + case html.CommentToken: |
| + return errors.New("comment") |
| + case html.DoctypeToken: |
| + return errors.New("doctype") |
| + case html.StartTagToken, html.SelfClosingTagToken, html.EndTagToken: |
| + tok := z.Token() |
| + if !agreementElements[tok.Data] { |
| + return fmt.Errorf("element <%s>", shortToken(tok.Data)) |
| + } |
| + if tok.Type == html.SelfClosingTagToken && tok.Data != "br" { |
| + return fmt.Errorf("self-closing <%s>", tok.Data) |
| + } |
| + for _, a := range tok.Attr { |
| + if tok.Data != "a" || a.Key != "href" { |
| + return fmt.Errorf("attribute %s on <%s>", shortToken(a.Key), tok.Data) |
| + } |
| + if !agreementHref(a.Val) { |
| + return fmt.Errorf("link %s", shortToken(a.Val)) |
| + } |
| + } |
| + } |
| + } |
| +} |
| + |
| +// agreementHref is true for a path ("/x", not "//x") or an https URL. Any |
| +// whitespace, control character or backslash is refused: a browser strips |
| +// or rewrites those, so "/\t/host" and "/\host" would read as "//host". |
| +func agreementHref(v string) bool { |
| + for _, r := range v { |
| + if r <= ' ' || r == 0x7f || r == '\\' { |
| + return false |
| + } |
| + } |
| + return (strings.HasPrefix(v, "/") && !strings.HasPrefix(v, "//")) || strings.HasPrefix(v, "https://") |
| +} |
| + |
| +// shortToken is s cut to a length safe to show, with anything unprintable |
| +// replaced. |
| +func shortToken(s string) string { |
| + const max = 24 |
| + var sb strings.Builder |
| + n := 0 |
| + for _, r := range s { |
| + if n == max { |
| + sb.WriteString("…") |
| + break |
| + } |
| + if r < ' ' || r == 0x7f || r == utf8.RuneError { |
| + r = '?' |
| + } |
| + sb.WriteRune(r) |
| + n++ |
| + } |
| + return sb.String() |
| +} |
diff --git a/internal/console/legalfetch_test.go b/internal/console/legalfetch_test.go| new file mode 100644 |
| index 000000000..78d9b17dd |
| --- /dev/null |
| +++ b/internal/console/legalfetch_test.go |
| @@ -0,0 +1,144 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// legalTestClient is the legal client with loopback allowed and srv's |
| +// certificate trusted, so a test server on 127.0.0.1 can answer. |
| +func legalTestClient(srv *httptest.Server) *http.Client { |
| + c := newGuardedHTTPClient(allowLoopback, 10*time.Second) |
| + pool := x509.NewCertPool() |
| + pool.AddCert(srv.Certificate()) |
| + c.Transport.(*http.Transport).TLSClientConfig = &tls.Config{RootCAs: pool} |
| + return c |
| +} |
| + |
| +func TestFetchLegalTextRefusesHTTP(t *testing.T) { |
| + srv, n := countingServer(t, nil) |
| + _, err := fetchLegalText(context.Background(), legalTestClient(srv), strings.Replace(srv.URL, "https://", "http://", 1)) |
| + if err == nil || err.Error() != "not https" { |
| + t.Fatalf("err = %v, want not https", err) |
| + } |
| + if n.Load() != 0 { |
| + t.Fatal("server was dialled") |
| + } |
| +} |
| + |
| +func TestFetchLegalTextRefusesPrivate(t *testing.T) { |
| + srv, n := countingServer(t, nil) |
| + c := newGuardedHTTPClient(refusedAddr, 10*time.Second) |
| + _, err := fetchLegalText(context.Background(), c, srv.URL) |
| + if err == nil || err.Error() != "refused address" { |
| + t.Fatalf("err = %v, want refused address", err) |
| + } |
| + if n.Load() != 0 { |
| + t.Fatal("server was reached") |
| + } |
| +} |
| + |
| +func TestFetchLegalTextOK(t *testing.T) { |
| + srv, _ := countingServer(t, func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("<p>x</p>")) }) |
| + b, err := fetchLegalText(context.Background(), legalTestClient(srv), srv.URL) |
| + if err != nil || string(b) != "<p>x</p>" { |
| + t.Fatalf("got %q, %v", b, err) |
| + } |
| +} |
| + |
| +func TestFetchLegalTextNoRedirect(t *testing.T) { |
| + srv, _ := countingServer(t, func(w http.ResponseWriter, r *http.Request) { |
| + http.Redirect(w, r, "/elsewhere", http.StatusFound) |
| + }) |
| + _, err := fetchLegalText(context.Background(), legalTestClient(srv), srv.URL) |
| + if err == nil || err.Error() != "status 302" { |
| + t.Fatalf("err = %v, want status 302", err) |
| + } |
| +} |
| + |
| +func TestFetchLegalTextStatus(t *testing.T) { |
| + srv, _ := countingServer(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(404) }) |
| + _, err := fetchLegalText(context.Background(), legalTestClient(srv), srv.URL) |
| + if err == nil || err.Error() != "status 404" { |
| + t.Fatalf("err = %v, want status 404", err) |
| + } |
| +} |
| + |
| +func TestFetchLegalTextTooLarge(t *testing.T) { |
| + for _, tc := range []struct { |
| + size int |
| + ok bool |
| + }{{legalFetchMax, true}, {legalFetchMax + 1, false}} { |
| + body := []byte(strings.Repeat("a", tc.size)) |
| + srv, _ := countingServer(t, func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(body) }) |
| + got, err := fetchLegalText(context.Background(), legalTestClient(srv), srv.URL) |
| + if tc.ok && (err != nil || len(got) != tc.size) { |
| + t.Fatalf("size %d: %d bytes, %v", tc.size, len(got), err) |
| + } |
| + if !tc.ok && (err == nil || err.Error() != "too large") { |
| + t.Fatalf("size %d: err = %v, want too large", tc.size, err) |
| + } |
| + } |
| +} |
| + |
| +func TestFetchLegalTextTimeout(t *testing.T) { |
| + srv, _ := countingServer(t, func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() }) |
| + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) |
| + defer cancel() |
| + _, err := fetchLegalText(ctx, legalTestClient(srv), srv.URL) |
| + if err == nil || err.Error() != "timeout" { |
| + t.Fatalf("err = %v, want timeout", err) |
| + } |
| +} |
| + |
| +func TestFetchLegalTextErrorsHideURL(t *testing.T) { |
| + _, err := fetchLegalText(context.Background(), newGuardedHTTPClient(refusedAddr, time.Second), "https://secret.invalid:1/path?token=abc") |
| + if err == nil || strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "token") { |
| + t.Fatalf("err = %v", err) |
| + } |
| +} |
| + |
| +func TestCanonicalAgreementAccepts(t *testing.T) { |
| + ok := []string{ |
| + `<section><h2>Terms & scope</h2><p>Read the <a href="/terms/">terms</a> and <a href="https://example.com/x">more</a>, <strong>now</strong> <em>ok</em>.<br>line<br/>two</p>` + "\n" + |
| + `<ul><li>one</li></ul><ol><li><a>bare</a></li></ol><h3>Sub</h3></section>`, |
| + "", |
| + } |
| + for _, s := range ok { |
| + if err := canonicalAgreement([]byte(s)); err != nil { |
| + t.Errorf("%q: %v", s, err) |
| + } |
| + } |
| +} |
| + |
| +func TestCanonicalAgreementRefuses(t *testing.T) { |
| + for _, c := range []struct{ in, names string }{ |
| + {`<script>x</script>`, "element <script>"}, |
| + {`<p onclick="x">t</p>`, "attribute onclick on <p>"}, |
| + {`<a href="javascript:x">t</a>`, "link javascript:"}, |
| + {`<!-- c -->`, "comment"}, |
| + {`<img src="x">`, "element <img>"}, |
| + {`<a href="http://x">t</a>`, "link http://x"}, |
| + {`<a href="//x/y">t</a>`, "link //x/y"}, |
| + {`<a href="/x" target="_blank">t</a>`, "attribute target on <a>"}, |
| + {`<!doctype html><p>t</p>`, "doctype"}, |
| + {`<p class="x">t</p>`, "attribute class on <p>"}, |
| + {`<a href="mailto:x@y">t</a>`, "link mailto:"}, |
| + {`<p>a</p><style>p{}</style>`, "element <style>"}, |
| + } { |
| + err := canonicalAgreement([]byte(c.in)) |
| + if err == nil { |
| + t.Errorf("%q accepted", c.in) |
| + continue |
| + } |
| + if !strings.Contains(err.Error(), c.names) { |
| + t.Errorf("%q: %q does not name %q", c.in, err, c.names) |
| + } |
| + } |
| +} |