feat: add a demo abuse report queue
Store anonymous reports with signed form protection, durable attempt and queue limits, and post-purge retention. Add human-operator list and resolve APIs with isolated CLI commands and safe terminal rendering. Report requests verify forwarded addresses using cached keys only. Independent review and the branch census remain controller and Task 6 gates.
docs/site/cli.md+3 −0internal/console/apidemo.go+2 −0internal/console/apidemooperator.go+5 −0internal/console/apidemoreports.go+242 −0internal/console/authcli.go+6 −1internal/console/claim_invariant_test.go+1 −0internal/console/demo_gate_test.go+17 −0internal/console/demo_reports.go+218 −0internal/console/demo_reports_test.go+526 −0internal/console/demo_store.go+9 −0internal/console/store_gate.go+2 −0internal/console/templates/demo_report.html+31 −0internal/edge/demo_banner_test.go+15 −0system_demos.go+104 −0system_demos_api.go+40 −0system_demos_test.go+54 −0
CI failed — run details
Intent
<task-notification> <task-id>bge0nx43l</task-id> <tool-use-id>toolu_01Tb8hPuPgoXp8HLFC93bfG9</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6e566fe9-9aca-47cb-9753-64e881b0d285/tasks/bge0nx43l.output</output-file> <status>completed</status> <summary>Background command "Wait for N-P2-1 fix run" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>ad9a08e2f432bd3b5</task-id> <tool-use-id>toolu_019mxVp7cDRgEJ4y1KVYcL3n</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6e566fe9-9aca-47cb-9753-64e881b0d285/tasks/ad9a08e2f432bd3b5.output</output-file> <status>completed</status> <summary>Agent "Check Task 4 ack fix (Opus)" 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>**N-P2-1: ADDRESSED.** The fix is at `internal/host/demo_serving.go:132`, `:145-148`, `:155-164` and `:209-214`. I found no new P1 or P2 in the fix diff. All five things you asked me to check hold: - **A transient error withholds the ack but nothing else stops.** A registry read error, or an `Initialize`/`checkAssignment` error that is neither `ErrTrafficUnavailable` nor `sql.ErrNoRows`, sets `installed=false`. That covers SQLite BUSY, I/O errors and the 5 s deadline. The loop carries on, so healthy entries still serve. The control is still saved, and the ack is set only when `installed` is true. Connect is unchanged: retirements are still queued after a refused control (`demo_jobs.go:495-503`). A retried `Initialize` is idempotent, and a failed insert rolls back the assignment row too. - **Permanent refusals are still acknowledged and cannot loop.** These leave `installed` alone: invalid, expired, duplicate, retired, wrong domain, registry mismatch, a cap mismatch or terminal assignment, and a missing counter row. After the ack, the console sends `Initialize=false`, `checkAssignment` refuses for the same permanent reason, and the box acks again. - **The console marks initialized only for acknowledged revisions.** Console production code is unchanged. `ackDemoServing` does nothing for `ack==0` (`internal/console/demo_serving.go:166-169`) and marks only entries of the issued revision that was acked. The next control still carries `Initialize=true`. - **No unacknowledged control extends serving validity or resets a counter.** An entry that failed to install is never in `s.demos`, so it isn't served. Healthy entries are renewed under the same probe, replay and clock checks as before; serving validity never depended on the ack. `Initialize` never re-creates a counter row for an existing or terminal assignment, and the retry test checks that a spent request survives. - **The witness tests are real.** They use a real SQLite trigger to fail one insert, a real closed-then-reopened registry, and the real console websocket and `demo_caps` row. The fix report shows the red run before the production change. I ran `go test -p 1 ./internal/host -run 'TestDemo(ServingStream|Traffic)' -count=1`: everything passed in 37 s. It had to run with the sandbox off, because the Go build cache (`~/.cache/go-build`) is read-only inside the sandbox. Three P3s for the follow-up list: - **A withheld ack also pauses build jobs for the whole box.** Job intake (`demo_serving.go:261`, used at `demo_jobs.go:508`) and `demoJobAllowed` (`:282`) both need `ack>0`. While one demo's transient failure holds the ack back, jobs for healthy demos are dropped too. The console re-sends queued jobs every 10 s, so it only costs a delay. The original fail-the-whole-control behaviour had the same effect. - **A UNIQUE conflict is treated as transient when it is permanent.** A UNIQUE(host) or UNIQUE(demo_id) conflict on the `demo_assignments` insert (`demo_traffic.go:121`) would hold the ack back on every control while that demo is listed. The console can't produce this today: host tombstones are permanent, demo IDs are unique and a lifetime is set once. Only a restored console database or a manual edit could reach it. Treating constraint errors as permanent would close it. - **One test relies on its fixture.** `TestDemoServingStreamRegistryRetry` doesn't assert that the ack was non-zero before the failed renewal. Report written to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-2/.superpowers/sdd/2026-11-04-agent-start-demo-2-edge-protections/task-4-check-r2fix.md`.</result> <usage><subagent_tokens>84850</subagent_tokens><tool_uses>18</tool_uses><duration_ms>232936</duration_ms></usage> </task-notification>
Attributed to this commit: 14.0 g CO₂e (1,520,898 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on agent-start-demo-2, 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/site/cli.md b/docs/site/cli.md| index 31ae8bf3c..548d46441 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -2755,6 +2755,9 @@ carlos system demos serving off |
| carlos system demos takedown --host shop.example.com |
| carlos system demos takedown-status --host shop.example.com |
| carlos system demos serving on |
| +carlos system demos reports --limit 50 |
| +carlos system demos reports --after <id> --limit 50 |
| +carlos system demos reports resolve --id <id> |
| ``` |
| Caps apply to one lifetime: 2,000 requests and 200,000,000 body bytes by default. |
diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go| index 965f04213..d04b18655 100644 |
| --- a/internal/console/apidemo.go |
| +++ b/internal/console/apidemo.go |
| @@ -261,6 +261,8 @@ func (s *Server) registerDemoRoutes() { |
| if !s.cfg.Demo.Enabled && !s.cfg.Demo.BoxMode() { |
| return |
| } |
| + s.registerRoute("GET /demo/report", s.handleDemoReport) |
| + s.registerRoute("POST /demo/report", s.handleDemoReport) |
| s.registerRoute("POST /api/box/demo-retirements/ack", s.handleDemoRetirementAck) |
| s.registerRoute("POST /api/demo/apps", s.handleDemoPublish) |
| s.registerRoute("GET /api/box/demo-builds", s.handleDemoBuildStream) |
diff --git a/internal/console/apidemooperator.go b/internal/console/apidemooperator.go| index 44861c439..7f9406378 100644 |
| --- a/internal/console/apidemooperator.go |
| +++ b/internal/console/apidemooperator.go |
| @@ -6,6 +6,7 @@ import ( |
| "io" |
| "log" |
| "net/http" |
| + "strings" |
| "time" |
| "github.com/carlosframework/platform/internal/demobuild" |
| @@ -16,6 +17,7 @@ func (s *Server) registerDemoOperatorRoutes() { |
| if !s.cfg.Demo.BoxMode() { |
| return |
| } |
| + s.registerDemoReportOperatorRoutes() |
| s.cliRoute("GET /api/cli/system/demos", svcrole.Set{}, s.handleAPIDemosStatus) |
| s.cliRoute("PUT /api/cli/system/demos/serving", svcrole.Set{}, s.handleAPIDemosServing) |
| s.cliRoute("POST /api/cli/system/demos/takedown", svcrole.Set{}, s.handleAPIDemosTakedown) |
| @@ -150,6 +152,9 @@ func (s *Server) writeDemoOperatorStatus(w http.ResponseWriter, r *http.Request, |
| } |
| func demoOperatorPath(path string) bool { |
| + if path == "/api/cli/system/demos/reports" || (strings.HasPrefix(path, "/api/cli/system/demos/reports/") && strings.HasSuffix(path, "/resolve")) { |
| + return true |
| + } |
| switch path { |
| case "/api/cli/system/demos", "/api/cli/system/demos/serving", "/api/cli/system/demos/takedown": |
| return true |
diff --git a/internal/console/apidemoreports.go b/internal/console/apidemoreports.go| new file mode 100644 |
| index 000000000..8ade96d89 |
| --- /dev/null |
| +++ b/internal/console/apidemoreports.go |
| @@ -0,0 +1,242 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/hmac" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "crypto/subtle" |
| + "encoding/base64" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/url" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edgeproof" |
| + "github.com/carlosframework/platform/internal/svcrole" |
| +) |
| + |
| +const demoReportCookie = "__Host-carlos-demo-report" |
| + |
| +var demoReportCopy = map[string]string{ |
| + "title": "Report a demo", "host": "Demo address", "category": "Reason", |
| + "phishing": "Phishing", "harmful": "Harmful content", "other": "Other", |
| + "details": "Details", "hint": "Do not include passwords or personal information.", |
| + "submit": "Send report", "sent": "Your report was sent to the operator.", |
| + "refused": "We could not accept this report. Reload the form and try again.", |
| + "busy": "Reports are temporarily limited. Try again later.", |
| +} |
| + |
| +func (s *Server) registerDemoReportOperatorRoutes() { |
| + s.cliRoute("GET /api/cli/system/demos/reports", svcrole.Set{}, s.handleAPIDemoReports) |
| + s.cliRoute("POST /api/cli/system/demos/reports/{id}/resolve", svcrole.Set{}, s.handleAPIDemoReportResolve) |
| +} |
| + |
| +func (s *Server) demoReportMAC(ctx context.Context, payload string) ([]byte, error) { |
| + var salt []byte |
| + if err := s.store.db.QueryRowContext(ctx, `SELECT ip_salt FROM demo_settings WHERE id=1`).Scan(&salt); err != nil { |
| + return nil, err |
| + } |
| + if len(salt) != 32 { |
| + return nil, ErrDemoReportRefused |
| + } |
| + mac := hmac.New(sha256.New, salt) |
| + mac.Write([]byte("demo-report-csrf\x00" + payload)) |
| + return mac.Sum(nil), nil |
| +} |
| +func (s *Server) demoReportToken(ctx context.Context, now time.Time) (string, error) { |
| + var nonce [32]byte |
| + if _, err := rand.Read(nonce[:]); err != nil { |
| + return "", err |
| + } |
| + payload := fmt.Sprintf("%d.%s", now.Add(15*time.Minute).Unix(), base64.RawURLEncoding.EncodeToString(nonce[:])) |
| + mac, err := s.demoReportMAC(ctx, payload) |
| + if err != nil { |
| + return "", err |
| + } |
| + return payload + "." + base64.RawURLEncoding.EncodeToString(mac), nil |
| +} |
| +func (s *Server) validDemoReportToken(r *http.Request, token string, now time.Time) bool { |
| + if len(token) > 128 { |
| + return false |
| + } |
| + cookies := r.CookiesNamed(demoReportCookie) |
| + if len(cookies) != 1 || subtle.ConstantTimeCompare([]byte(cookies[0].Value), []byte(token)) != 1 { |
| + return false |
| + } |
| + parts := strings.Split(token, ".") |
| + if len(parts) != 3 { |
| + return false |
| + } |
| + expiry, err := strconv.ParseInt(parts[0], 10, 64) |
| + if err != nil || expiry <= now.Unix() || expiry > now.Add(15*time.Minute).Unix() { |
| + return false |
| + } |
| + nonce, err := base64.RawURLEncoding.Strict().DecodeString(parts[1]) |
| + if err != nil || len(nonce) != 32 { |
| + return false |
| + } |
| + got, err := base64.RawURLEncoding.Strict().DecodeString(parts[2]) |
| + if err != nil { |
| + return false |
| + } |
| + want, err := s.demoReportMAC(r.Context(), parts[0]+"."+parts[1]) |
| + return err == nil && hmac.Equal(got, want) |
| +} |
| +func (s *Server) demoReportOrigin() bool { |
| + u, err := url.Parse(s.cfg.Origin) |
| + return err == nil && u.Scheme == "https" && u.Hostname() != "" && u.User == nil && u.Opaque == "" && u.Path == "" && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && !strings.ContainsAny(s.cfg.Origin, "\\\r\n\t ") |
| +} |
| +func (s *Server) renderDemoReport(w http.ResponseWriter, status int, host, token, message string) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Referrer-Policy", "no-referrer") |
| + w.Header().Set("X-Content-Type-Options", "nosniff") |
| + w.Header().Set("X-Frame-Options", "DENY") |
| + w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'") |
| + _ = s.writeTemplate(w, status, "demo_report", struct { |
| + Copy map[string]string |
| + Host, Token, Message string |
| + }{demoReportCopy, host, token, message}) |
| +} |
| +func (s *Server) demoReportError(w http.ResponseWriter, err error) { |
| + status, key := 400, "refused" |
| + if errors.Is(err, ErrDemoReportLimit) { |
| + status, key = 429, "busy" |
| + } else if !errors.Is(err, ErrDemoReportRefused) { |
| + status, key = 503, "busy" |
| + } |
| + s.renderDemoReport(w, status, "", "", demoReportCopy[key]) |
| +} |
| +func (s *Server) handleDemoReport(w http.ResponseWriter, r *http.Request) { |
| + if s.cfg.HostClaim || !s.cfg.Demo.BoxMode() || !s.demoReportOrigin() { |
| + s.demoReportError(w, ErrDemoReportRefused) |
| + return |
| + } |
| + now := time.Now() |
| + if r.Method == http.MethodGet || r.Method == http.MethodHead { |
| + q, err := url.ParseQuery(r.URL.RawQuery) |
| + if err != nil || len(q) != 1 || len(q["host"]) != 1 { |
| + s.demoReportError(w, ErrDemoReportRefused) |
| + return |
| + } |
| + host := q.Get("host") |
| + if _, err = s.store.reportHost(r.Context(), host, now); err != nil { |
| + s.demoReportError(w, err) |
| + return |
| + } |
| + token, err := s.demoReportToken(r.Context(), now) |
| + if err != nil { |
| + s.demoReportError(w, err) |
| + return |
| + } |
| + http.SetCookie(w, &http.Cookie{Name: demoReportCookie, Value: token, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: 900, Expires: now.Add(15 * time.Minute)}) |
| + s.renderDemoReport(w, 200, host, token, "") |
| + return |
| + } |
| + // Failed forms consume the same durable budget as accepted reports. |
| + hash, err := s.store.spendDemoReport(r.Context(), s.clientIPWithProof(r, s.demoReportForwardedByEdge), now) |
| + if err != nil { |
| + s.demoReportError(w, err) |
| + return |
| + } |
| + r.Body = http.MaxBytesReader(w, r.Body, 4096) |
| + defer r.Body.Close() |
| + if len(r.Header.Values("Origin")) != 1 || r.Header.Get("Origin") != s.cfg.Origin || r.URL.RawQuery != "" || r.URL.ForceQuery || r.Header.Get("Content-Type") != "application/x-www-form-urlencoded" || r.ParseForm() != nil { |
| + s.demoReportError(w, ErrDemoReportRefused) |
| + return |
| + } |
| + if len(r.PostForm) != 4 { |
| + s.demoReportError(w, ErrDemoReportRefused) |
| + return |
| + } |
| + for _, key := range []string{"host", "category", "details", "csrf"} { |
| + if len(r.PostForm[key]) != 1 { |
| + s.demoReportError(w, ErrDemoReportRefused) |
| + return |
| + } |
| + } |
| + if !s.validDemoReportToken(r, r.PostForm.Get("csrf"), now) { |
| + s.demoReportError(w, ErrDemoReportRefused) |
| + return |
| + } |
| + _, err = s.store.addDemoReportSpent(r.Context(), r.PostForm.Get("host"), r.PostForm.Get("category"), r.PostForm.Get("details"), hash, now) |
| + if err != nil { |
| + s.demoReportError(w, err) |
| + return |
| + } |
| + s.renderDemoReport(w, 200, "", "", demoReportCopy["sent"]) |
| +} |
| +func (s *Store) reportHost(ctx context.Context, host string, now time.Time) (string, error) { |
| + if s.claimGated() { |
| + return "", ErrDemoReportRefused |
| + } |
| + return reportHostID(ctx, s.db, host, now) |
| +} |
| +func (s *Server) handleAPIDemoReports(w http.ResponseWriter, r *http.Request) { |
| + if _, ok := s.demoOperator(w, r); !ok { |
| + return |
| + } |
| + q, err := url.ParseQuery(r.URL.RawQuery) |
| + limit := 50 |
| + if err != nil { |
| + jsonError(w, 400, demoReportCopy["refused"]) |
| + return |
| + } |
| + for key, values := range q { |
| + if (key != "after" && key != "limit") || len(values) != 1 { |
| + jsonError(w, 400, demoReportCopy["refused"]) |
| + return |
| + } |
| + } |
| + if values, ok := q["limit"]; ok { |
| + limit, err = strconv.Atoi(values[0]) |
| + if err != nil { |
| + jsonError(w, 400, demoReportCopy["refused"]) |
| + return |
| + } |
| + } |
| + reports, next, err := s.store.ListDemoReports(r.Context(), q.Get("after"), limit) |
| + if err != nil { |
| + status := 503 |
| + if errors.Is(err, ErrDemoReportRefused) { |
| + status = 400 |
| + } |
| + jsonError(w, status, demoReportCopy["refused"]) |
| + return |
| + } |
| + writeJSON(w, 200, struct { |
| + Reports []DemoReport `json:"reports"` |
| + Next string `json:"next,omitempty"` |
| + }{reports, next}) |
| +} |
| +func (s *Server) handleAPIDemoReportResolve(w http.ResponseWriter, r *http.Request) { |
| + actor, ok := s.demoOperator(w, r) |
| + if !ok { |
| + return |
| + } |
| + if err := s.store.ResolveDemoReport(r.Context(), r.PathValue("id"), actor, time.Now()); err != nil { |
| + if errors.Is(err, ErrDemoReportRefused) { |
| + http.NotFound(w, r) |
| + } else { |
| + jsonError(w, 503, demoReportCopy["busy"]) |
| + } |
| + return |
| + } |
| + writeJSON(w, 200, map[string]string{"state": "resolved"}) |
| +} |
| + |
| +// The report door never loads keys or accepts the rollout's unsigned fallback. |
| +// A cold or stale cache conservatively groups loopback requests at their peer. |
| +func (s *Server) demoReportForwardedByEdge(r *http.Request, xff string) bool { |
| + st := &s.edgeProof |
| + st.mu.Lock() |
| + defer st.mu.Unlock() |
| + now := time.Now() |
| + if st.at.IsZero() || now.Sub(st.at) < 0 || now.Sub(st.at) >= edgeProofKeyTTL { |
| + return false |
| + } |
| + return edgeproof.Verify(st.current, st.next, r.Host, xff, r.Header.Get(edgeproof.Header), now) |
| +} |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index ccbf82c81..46a049a3b 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -1202,6 +1202,11 @@ func (s *Server) registerCLIRoutes() { |
| // appends its own view of the peer with SetXForwarded, so everything before |
| // it may have been supplied by the client. |
| func (s *Server) clientIP(r *http.Request) string { |
| + return s.clientIPWithProof(r, s.forwardedByEdge) |
| +} |
| + |
| +// Report requests use cached proof keys, so resolving an IP cannot read storage. |
| +func (s *Server) clientIPWithProof(r *http.Request, verify func(*http.Request, string) bool) string { |
| host, _, err := net.SplitHostPort(r.RemoteAddr) |
| if err != nil { |
| host = r.RemoteAddr |
| @@ -1215,7 +1220,7 @@ func (s *Server) clientIP(r *http.Request) string { |
| if xff == "" { |
| return host |
| } |
| - if isLoopbackPeer(host) && !s.forwardedByEdge(r, xff) { |
| + if isLoopbackPeer(host) && !verify(r, xff) { |
| return host |
| } |
| parts := strings.Split(xff, ",") |
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index 2945df249..ad14e000e 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -183,6 +183,7 @@ type claimWindow struct { |
| // every writer is reached. A new boundary method or gated table fails the |
| // coverage step until a door reaches it or a reason is written here. |
| var claimWriterReasons = map[string]string{ |
| + "sql/demo_reports": "demo reports refuse claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
| "sql/demo_serving": "demo serving refuses claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied", |
| "sql/demo_caps": "demo caps refuse claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied", |
| "sql/demo_retirements": "anonymous demo retirement refuses claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
diff --git a/internal/console/demo_gate_test.go b/internal/console/demo_gate_test.go| index bdc959ff8..0db70e215 100644 |
| --- a/internal/console/demo_gate_test.go |
| +++ b/internal/console/demo_gate_test.go |
| @@ -2,6 +2,10 @@ package console |
| import ( |
| "context" |
| + "errors" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| "path/filepath" |
| "testing" |
| ) |
| @@ -22,6 +26,7 @@ func TestDemoSQLClaimsRefuseBuildState(t *testing.T) { |
| // than succeed without firing a trigger. |
| for _, query := range []string{ |
| `INSERT INTO demo_apps(demo_id,account_id,account_sqid,app,name,fleet,claim_token_hash,created_at,creating_ip,source_sha256,client) VALUES('demo',7,'shop','blog','shop','demo',zeroblob(32),1,'hash',X'','test')`, |
| + `INSERT INTO demo_reports(id,demo_id,host,category,details,created_at,ip_hash) VALUES('report','demo','shop.example.com','other','',1,zeroblob(32))`, |
| `INSERT INTO demo_jobs(id,demo_id,generation,attempt,box,deadline,state,wire,job) VALUES('job','demo',1,1,'box',1,'queued',X'',X'')`, |
| `INSERT INTO demo_job_outbox(job_id,source) VALUES('job',X'')`, |
| `INSERT INTO demo_retirements(demo_id,wire) VALUES('demo',X'')`, |
| @@ -40,9 +45,21 @@ func TestDemoSQLClaimsRefuseBuildState(t *testing.T) { |
| } |
| defer s.Close() |
| seedGateApp(t, s) |
| + if _, err := s.AddDemoReport(context.Background(), "shop.example.com", "other", "", "192.0.2.1", time.Now()); !errors.Is(err, demo.ErrConfig) { |
| + t.Fatalf("claims report: %v", err) |
| + } |
| + var attempts int |
| + if err := s.db.QueryRow(`SELECT count(*) FROM demo_report_attempts`).Scan(&attempts); err != nil || attempts != 0 { |
| + t.Fatalf("claims attempts %d: %v", attempts, err) |
| + } |
| + if rule := claimSQLTables["demo_report_attempts"]; rule.NonApp == "" || rule.App != "" { |
| + t.Fatal("attempts must remain deployment-scoped") |
| + } |
| err = s.withClaimSQL(context.Background(), []claimSQLScope{gateScope}, allowAllClaimSQL, func(v *Store) error { |
| for _, query := range []string{ |
| `INSERT INTO demo_serving(id,enabled,revision,changed_at,changed_by) VALUES(1,1,1,1,'')`, |
| + `INSERT INTO demo_reports(id,demo_id,host,category,details,created_at,ip_hash) VALUES('other','demo','shop.example.com','other','',1,zeroblob(32))`, |
| + `UPDATE demo_reports SET state='resolved'`, `DELETE FROM demo_reports`, |
| `UPDATE demo_serving SET enabled=1`, `DELETE FROM demo_serving`, |
| `INSERT INTO demo_caps(demo_id,lifetime,request_cap,byte_cap) VALUES('other','life',2000,200000000)`, |
| `UPDATE demo_caps SET initialized=1`, `DELETE FROM demo_caps`, |
diff --git a/internal/console/demo_reports.go b/internal/console/demo_reports.go| new file mode 100644 |
| index 000000000..633fb2290 |
| --- /dev/null |
| +++ b/internal/console/demo_reports.go |
| @@ -0,0 +1,218 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/hmac" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/hex" |
| + "errors" |
| + "fmt" |
| + "strconv" |
| + "strings" |
| + "time" |
| + "unicode" |
| + "unicode/utf8" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| +) |
| + |
| +var ErrDemoReportRefused = errors.New("demo report refused") |
| +var ErrDemoReportLimit = errors.New("demo report limited") |
| + |
| +// DemoReport is the operator view. Reporter hashes and resolution actors stay local. |
| +type DemoReport struct { |
| + ID string `json:"id"` |
| + Host string `json:"host"` |
| + Category string `json:"category"` |
| + Details string `json:"details"` |
| + State string `json:"state"` |
| + CreatedAt int64 `json:"createdAt"` |
| +} |
| + |
| +func (s *Store) migrateDemoReports() error { |
| + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS demo_reports ( |
| + id TEXT PRIMARY KEY, demo_id TEXT NOT NULL, host TEXT NOT NULL, |
| + category TEXT NOT NULL CHECK(category IN ('phishing','harmful','other')), |
| + details TEXT NOT NULL, created_at INTEGER NOT NULL, |
| + state TEXT NOT NULL DEFAULT 'open' CHECK(state IN ('open','resolved')), |
| + resolved_at INTEGER NOT NULL DEFAULT 0, resolved_by TEXT NOT NULL DEFAULT '', |
| + ip_hash BLOB NOT NULL CHECK(length(ip_hash)=32)); |
| + CREATE INDEX IF NOT EXISTS demo_reports_order ON demo_reports(created_at,id); |
| + CREATE INDEX IF NOT EXISTS demo_reports_host ON demo_reports(host,created_at); |
| + CREATE TABLE IF NOT EXISTS demo_report_attempts(ip_hash BLOB NOT NULL CHECK(length(ip_hash)=32), attempted_at INTEGER NOT NULL); |
| + CREATE INDEX IF NOT EXISTS demo_report_attempts_time ON demo_report_attempts(attempted_at); |
| + CREATE INDEX IF NOT EXISTS demo_report_attempts_ip ON demo_report_attempts(ip_hash,attempted_at);`) |
| + return err |
| +} |
| + |
| +func (s *Store) spendDemoReport(ctx context.Context, ip string, now time.Time) ([]byte, error) { |
| + ip, err := demo.CanonicalIP(ip) |
| + if err != nil || now.Unix() <= 0 { |
| + return nil, ErrDemoReportRefused |
| + } |
| + tx, err := s.demoTx(ctx) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer tx.Rollback() |
| + if _, err = tx.ExecContext(ctx, `DELETE FROM demo_report_attempts WHERE attempted_at<=?`, now.Add(-24*time.Hour).UnixNano()); err != nil { |
| + return nil, err |
| + } |
| + var salt []byte |
| + if err = tx.QueryRowContext(ctx, `SELECT ip_salt FROM demo_settings WHERE id=1`).Scan(&salt); err != nil { |
| + return nil, err |
| + } |
| + if len(salt) != 32 { |
| + return nil, ErrDemoReportRefused |
| + } |
| + mac := hmac.New(sha256.New, salt) |
| + mac.Write([]byte(ip)) |
| + hash := mac.Sum(nil) |
| + var total, atIP int |
| + if err = tx.QueryRowContext(ctx, `SELECT count(*),coalesce(sum(ip_hash=? AND attempted_at>?),0) FROM demo_report_attempts`, hash, now.Add(-time.Hour).UnixNano()).Scan(&total, &atIP); err != nil { |
| + return nil, err |
| + } |
| + if total >= 500 || atIP >= 10 { |
| + return nil, ErrDemoReportLimit |
| + } |
| + if _, err = tx.ExecContext(ctx, `INSERT INTO demo_report_attempts(ip_hash,attempted_at) VALUES(?,?)`, hash, now.UnixNano()); err != nil { |
| + return nil, err |
| + } |
| + if err = tx.Commit(); err != nil { |
| + return nil, err |
| + } |
| + return hash, nil |
| +} |
| + |
| +func reportHostID(ctx context.Context, q interface { |
| + QueryRowContext(context.Context, string, ...any) *sql.Row |
| +}, host string, now time.Time) (string, error) { |
| + if !demoExactHost(host) { |
| + return "", ErrDemoReportRefused |
| + } |
| + var id string |
| + err := q.QueryRowContext(ctx, `SELECT demo_id FROM demo_apps WHERE host=? AND (purged_at=0 OR purged_at>?)`, host, now.Add(-7*24*time.Hour).Unix()).Scan(&id) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return "", ErrDemoReportRefused |
| + } |
| + return id, err |
| +} |
| + |
| +func (s *Store) AddDemoReport(ctx context.Context, host, category, details, ip string, now time.Time) (string, error) { |
| + hash, err := s.spendDemoReport(ctx, ip, now) |
| + if err != nil { |
| + return "", err |
| + } |
| + return s.addDemoReportSpent(ctx, host, category, details, hash, now) |
| +} |
| + |
| +// The HTTP door spends before parsing or CSRF validation, then calls this once. |
| +func (s *Store) addDemoReportSpent(ctx context.Context, host, category, details string, hash []byte, now time.Time) (string, error) { |
| + if (category != "phishing" && category != "harmful" && category != "other") || len(details) > 1000 || !utf8.ValidString(details) || strings.ContainsFunc(details, func(r rune) bool { |
| + return (unicode.IsControl(r) && r != '\n' && r != '\t' && r != '\r') || unicode.In(r, unicode.Cf) |
| + }) { |
| + return "", ErrDemoReportRefused |
| + } |
| + tx, err := s.demoTx(ctx) |
| + if err != nil { |
| + return "", err |
| + } |
| + defer tx.Rollback() |
| + demoID, err := reportHostID(ctx, tx, host, now) |
| + if err != nil { |
| + return "", err |
| + } |
| + var total, atHost int |
| + if err = tx.QueryRowContext(ctx, `SELECT count(*),coalesce(sum(host=? AND created_at>?),0) FROM demo_reports`, host, now.Add(-24*time.Hour).Unix()).Scan(&total, &atHost); err != nil { |
| + return "", err |
| + } |
| + if total >= 2000 || atHost >= 20 { |
| + return "", ErrDemoReportLimit |
| + } |
| + var nonce [16]byte |
| + if _, err = rand.Read(nonce[:]); err != nil { |
| + return "", err |
| + } |
| + id := fmt.Sprintf("%016x-%s", now.Unix(), hex.EncodeToString(nonce[:])) |
| + if _, err = tx.ExecContext(ctx, `INSERT INTO demo_reports(id,demo_id,host,category,details,created_at,ip_hash) VALUES(?,?,?,?,?,?,?)`, id, demoID, host, category, details, now.Unix(), hash); err != nil { |
| + return "", err |
| + } |
| + if err = tx.Commit(); err != nil { |
| + return "", err |
| + } |
| + return id, nil |
| +} |
| + |
| +// The time embedded in the ID keeps a cursor usable after its row is pruned. |
| +func demoReportCursor(id string) (int64, error) { |
| + if len(id) != 49 || id[16] != '-' || id != strings.ToLower(id) { |
| + return 0, ErrDemoReportRefused |
| + } |
| + stamp, err := strconv.ParseInt(id[:16], 16, 64) |
| + if err != nil || stamp <= 0 { |
| + return 0, ErrDemoReportRefused |
| + } |
| + if _, err = hex.DecodeString(id[17:]); err != nil { |
| + return 0, ErrDemoReportRefused |
| + } |
| + return stamp, nil |
| +} |
| +func (s *Store) ListDemoReports(ctx context.Context, after string, limit int) ([]DemoReport, string, error) { |
| + if s.claimGated() || limit < 1 || limit > 100 { |
| + return nil, "", ErrDemoReportRefused |
| + } |
| + var stamp int64 |
| + if after != "" { |
| + var err error |
| + stamp, err = demoReportCursor(after) |
| + if err != nil { |
| + return nil, "", err |
| + } |
| + } |
| + rows, err := s.db.QueryContext(ctx, `SELECT id,host,category,details,state,created_at FROM demo_reports WHERE created_at>? OR (created_at=? AND id>?) ORDER BY created_at,id LIMIT ?`, stamp, stamp, after, limit+1) |
| + if err != nil { |
| + return nil, "", err |
| + } |
| + defer rows.Close() |
| + out := make([]DemoReport, 0) |
| + for rows.Next() { |
| + var r DemoReport |
| + if err = rows.Scan(&r.ID, &r.Host, &r.Category, &r.Details, &r.State, &r.CreatedAt); err != nil { |
| + return nil, "", err |
| + } |
| + out = append(out, r) |
| + } |
| + if err = rows.Err(); err != nil { |
| + return nil, "", err |
| + } |
| + next := "" |
| + if len(out) > limit { |
| + out = out[:limit] |
| + next = out[len(out)-1].ID |
| + } |
| + return out, next, nil |
| +} |
| +func (s *Store) ResolveDemoReport(ctx context.Context, id, actor string, now time.Time) error { |
| + if _, err := demoReportCursor(id); err != nil { |
| + return err |
| + } |
| + tx, err := s.demoTx(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + var state string |
| + if err = tx.QueryRowContext(ctx, `SELECT state FROM demo_reports WHERE id=?`, id).Scan(&state); errors.Is(err, sql.ErrNoRows) { |
| + return ErrDemoReportRefused |
| + } else if err != nil { |
| + return err |
| + } |
| + if state == "open" { |
| + if _, err = tx.ExecContext(ctx, `UPDATE demo_reports SET state='resolved',resolved_at=?,resolved_by=? WHERE id=?`, now.Unix(), actor, id); err != nil { |
| + return err |
| + } |
| + } |
| + return tx.Commit() |
| +} |
diff --git a/internal/console/demo_reports_test.go b/internal/console/demo_reports_test.go| new file mode 100644 |
| index 000000000..00819f04c |
| --- /dev/null |
| +++ b/internal/console/demo_reports_test.go |
| @@ -0,0 +1,526 @@ |
| +package console |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edgeproof" |
| + "github.com/carlosframework/platform/internal/svcrole" |
| +) |
| + |
| +func reportFixture(t *testing.T) (*Server, DemoRow) { |
| + t.Helper() |
| + s := demoTestServer(t) |
| + s.cfg.Origin = "https://console.example.com" |
| + d, err := s.store.ReserveDemo(t.Context(), demoTestAdmission(t, s.cfg.Demo)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return s, d |
| +} |
| +func reportForm(t *testing.T, s *Server, host string) (*http.Cookie, url.Values) { |
| + t.Helper() |
| + r := httptest.NewRequest("GET", "/demo/report?host="+url.QueryEscape(host), nil) |
| + w := httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 200 || strings.Contains(w.Body.String(), "<script") { |
| + t.Fatalf("form %d %s", w.Code, w.Body.String()) |
| + } |
| + cookies := w.Result().Cookies() |
| + if len(cookies) != 1 { |
| + t.Fatalf("cookies %v", cookies) |
| + } |
| + c := cookies[0] |
| + if c.Name != "__Host-carlos-demo-report" || !c.Secure || !c.HttpOnly || c.SameSite != http.SameSiteStrictMode || c.Path != "/" || c.Domain != "" || c.MaxAge != 900 { |
| + t.Fatalf("cookie %+v", c) |
| + } |
| + return c, url.Values{"host": {host}, "category": {"phishing"}, "details": {"<script>alert(1)</script>"}, "csrf": {c.Value}} |
| +} |
| +func reportPost(s *Server, c *http.Cookie, v url.Values, origin, ip string) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest("POST", "/demo/report", strings.NewReader(v.Encode())) |
| + r.RemoteAddr = ip + ":1234" |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.Header.Set("Origin", origin) |
| + r.Header.Set("X-Forwarded-For", "203.0.113.99") |
| + if c != nil { |
| + r.AddCookie(c) |
| + } |
| + w := httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + return w |
| +} |
| +func TestDemoReportQueue(t *testing.T) { |
| + s, d := reportFixture(t) |
| + c, v := reportForm(t, s, d.Host) |
| + rows, _, err := s.store.ListDemoReports(t.Context(), "", 50) |
| + if err != nil || len(rows) != 0 { |
| + t.Fatalf("prefetch %v %v", rows, err) |
| + } |
| + w := reportPost(s, c, v, s.cfg.Origin, "192.0.2.1") |
| + if w.Code != 200 || !strings.Contains(w.Body.String(), "Your report was sent to the operator.") || w.Header().Get("Location") != "" { |
| + t.Fatalf("post %d %s", w.Code, w.Body.String()) |
| + } |
| + rows, _, err = s.store.ListDemoReports(t.Context(), "", 50) |
| + if err != nil || len(rows) != 1 || rows[0].Host != d.Host || rows[0].State != "open" { |
| + t.Fatalf("rows %+v %v", rows, err) |
| + } |
| + now := time.Now() |
| + if err = s.store.ResolveDemoReport(t.Context(), rows[0].ID, "operator@example.com", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = s.store.ResolveDemoReport(t.Context(), rows[0].ID, "other@example.com", now.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + var actor string |
| + s.store.db.QueryRow(`SELECT resolved_by FROM demo_reports`).Scan(&actor) |
| + if actor != "operator@example.com" { |
| + t.Fatalf("resolve changed actor: %s", actor) |
| + } |
| + for i := 0; i < 3; i++ { |
| + if _, err = s.store.AddDemoReport(t.Context(), d.Host, "other", "", fmt.Sprintf("192.0.2.%d", i+2), now); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + first, next, err := s.store.ListDemoReports(t.Context(), "", 2) |
| + if err != nil || len(first) != 2 || next != first[1].ID { |
| + t.Fatalf("page %+v %q %v", first, next, err) |
| + } |
| + second, next, err := s.store.ListDemoReports(t.Context(), next, 2) |
| + if err != nil || len(second) != 2 || next != "" || second[0].ID == first[1].ID { |
| + t.Fatalf("page2 %+v %q %v", second, next, err) |
| + } |
| +} |
| +func TestDemoReportAbuse(t *testing.T) { |
| + for _, kind := range []string{"origin", "missing-cookie", "token", "duplicate", "foreign", "oversize", "utf8", "control", "query", "expired-cookie"} { |
| + t.Run(kind, func(t *testing.T) { |
| + s, d := reportFixture(t) |
| + c, v := reportForm(t, s, d.Host) |
| + origin := s.cfg.Origin |
| + switch kind { |
| + case "origin": |
| + origin = "https://evil.example.com" |
| + case "missing-cookie": |
| + c = nil |
| + case "token": |
| + v.Set("csrf", "forged") |
| + case "duplicate": |
| + v.Add("host", d.Host) |
| + case "foreign": |
| + v.Set("host", "https://example.com/") |
| + case "oversize": |
| + v.Set("details", strings.Repeat("x", 4097)) |
| + case "utf8": |
| + v.Set("details", string([]byte{255})) |
| + case "control": |
| + v.Set("details", "bad\x1b[31m") |
| + case "query": |
| + v.Set("redirect", "https://example.com/") |
| + case "expired-cookie": |
| + c.Value, _ = s.demoReportToken(t.Context(), time.Now().Add(-16*time.Minute)) |
| + v.Set("csrf", c.Value) |
| + } |
| + w := reportPost(s, c, v, origin, "192.0.2.1") |
| + if w.Code != 400 || w.Header().Get("Location") != "" || !strings.Contains(w.Body.String(), "We could not accept this report.") { |
| + t.Fatalf("refusal %d %s", w.Code, w.Body.String()) |
| + } |
| + var attempts, rows int |
| + s.store.db.QueryRow(`SELECT count(*) FROM demo_report_attempts`).Scan(&attempts) |
| + s.store.db.QueryRow(`SELECT count(*) FROM demo_reports`).Scan(&rows) |
| + if attempts != 1 || rows != 0 { |
| + t.Fatalf("attempts %d rows %d", attempts, rows) |
| + } |
| + }) |
| + } |
| + t.Run("forged-xff", func(t *testing.T) { |
| + s, d := reportFixture(t) |
| + c, v := reportForm(t, s, d.Host) |
| + v.Set("category", "invalid") |
| + for i := 0; i < 11; i++ { |
| + w := reportPost(s, c, v, s.cfg.Origin, "192.0.2.1") |
| + want := 400 |
| + if i == 10 { |
| + want = 429 |
| + } |
| + if w.Code != want { |
| + t.Fatalf("attempt %d: %d", i, w.Code) |
| + } |
| + } |
| + }) |
| +} |
| +func TestDemoReportRetention(t *testing.T) { |
| + st, path := demoTestStore(t) |
| + d, err := st.ReserveDemo(t.Context(), demoTestAdmission(t, demoTestConfig(t))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + now := time.Now() |
| + id, err := st.AddDemoReport(t.Context(), d.Host, "other", "details", "192.0.2.1", now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + other, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer other.Close() |
| + rows, _, err := other.ListDemoReports(t.Context(), "", 50) |
| + if err != nil || len(rows) != 1 || rows[0].ID != id { |
| + t.Fatalf("restart %+v %v", rows, err) |
| + } |
| + if _, err = st.db.Exec(`UPDATE demo_apps SET purged_at=?,state='retired' WHERE demo_id=?`, now.Unix(), d.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = st.db.Exec(`INSERT INTO demo_host_tombstones(host,demo_id,purged_at) VALUES(?,?,?)`, d.Host, d.ID, now.Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = other.AddDemoReport(t.Context(), d.Host, "other", "", "192.0.2.2", now.Add(6*24*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + late := now.Add(7 * 24 * time.Hour) |
| + for _, host := range []string{d.Host, "shop.example.com"} { |
| + if _, err = other.AddDemoReport(t.Context(), host, "other", "", "192.0.2.3", late); !errors.Is(err, ErrDemoReportRefused) { |
| + t.Fatalf("old/unknown %v", err) |
| + } |
| + } |
| + if err = other.WipeDemoAbuse(t.Context(), late.Add(25*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, table := range []string{"demo_reports", "demo_report_attempts"} { |
| + var n int |
| + other.db.QueryRow(`SELECT count(*) FROM ` + table).Scan(&n) |
| + if n != 0 { |
| + t.Fatalf("%s retained %d", table, n) |
| + } |
| + } |
| + var n int |
| + other.db.QueryRow(`SELECT count(*) FROM demo_host_tombstones WHERE host=?`, d.Host).Scan(&n) |
| + if n != 1 { |
| + t.Fatal("tombstone lost") |
| + } |
| +} |
| +func TestDemoReportWhileStopped(t *testing.T) { |
| + s, d := reportFixture(t) |
| + s.cfg.Demo.Enabled = false |
| + s.cfg.Demo.EdgeProtections = false |
| + s.cfg.Releases = nil |
| + if _, err := s.store.db.Exec(`UPDATE demo_serving SET enabled=0`); err != nil { |
| + t.Fatal(err) |
| + } |
| + c, v := reportForm(t, s, d.Host) |
| + w := reportPost(s, c, v, s.cfg.Origin, "192.0.2.1") |
| + if w.Code != 200 { |
| + t.Fatalf("stopped %d %s", w.Code, w.Body.String()) |
| + } |
| +} |
| + |
| +func TestDemoReportBudgets(t *testing.T) { |
| + t.Run("per-ip-restart", func(t *testing.T) { |
| + st, path := demoTestStore(t) |
| + now := time.Now() |
| + for i := 0; i < 10; i++ { |
| + if _, err := st.AddDemoReport(t.Context(), "shop.example.com", "invalid", "", "::ffff:192.0.2.1", now); !errors.Is(err, ErrDemoReportRefused) { |
| + t.Fatal(err) |
| + } |
| + } |
| + other, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer other.Close() |
| + if _, err = other.AddDemoReport(t.Context(), "shop.example.com", "other", "", "192.0.2.1", now); !errors.Is(err, ErrDemoReportLimit) { |
| + t.Fatalf("restart cap %v", err) |
| + } |
| + if _, err = other.AddDemoReport(t.Context(), "shop.example.com", "other", "", "192.0.2.1", now.Add(time.Hour)); !errors.Is(err, ErrDemoReportRefused) { |
| + t.Fatalf("hour reset %v", err) |
| + } |
| + }) |
| + t.Run("host-concurrent", func(t *testing.T) { |
| + st, path := demoTestStore(t) |
| + d, err := st.ReserveDemo(t.Context(), demoTestAdmission(t, demoTestConfig(t))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + other, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer other.Close() |
| + now := time.Now() |
| + results := make(chan error, 40) |
| + for i := 0; i < 40; i++ { |
| + go func(i int) { |
| + db := st |
| + if i%2 == 0 { |
| + db = other |
| + } |
| + _, err := db.AddDemoReport(t.Context(), d.Host, "other", "", fmt.Sprintf("192.0.2.%d", i+1), now) |
| + results <- err |
| + }(i) |
| + } |
| + accepted := 0 |
| + for i := 0; i < 40; i++ { |
| + err := <-results |
| + if err == nil { |
| + accepted++ |
| + } else if !errors.Is(err, ErrDemoReportLimit) { |
| + t.Fatal(err) |
| + } |
| + } |
| + if accepted != 20 { |
| + t.Fatalf("accepted %d", accepted) |
| + } |
| + if _, err = other.AddDemoReport(t.Context(), d.Host, "other", "", "192.0.2.99", now.Add(24*time.Hour)); err != nil { |
| + t.Fatalf("day reset %v", err) |
| + } |
| + }) |
| + t.Run("global-restart", func(t *testing.T) { |
| + st, path := demoTestStore(t) |
| + now := time.Now() |
| + if _, err := st.db.Exec(`WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<500) INSERT INTO demo_report_attempts SELECT zeroblob(32),? FROM n`, now.UnixNano()); err != nil { |
| + t.Fatal(err) |
| + } |
| + other, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer other.Close() |
| + if _, err = other.AddDemoReport(t.Context(), "shop.example.com", "other", "", "192.0.2.1", now); !errors.Is(err, ErrDemoReportLimit) { |
| + t.Fatalf("global %v", err) |
| + } |
| + if _, err = other.AddDemoReport(t.Context(), "shop.example.com", "other", "", "192.0.2.1", now.Add(24*time.Hour)); !errors.Is(err, ErrDemoReportRefused) { |
| + t.Fatalf("reset %v", err) |
| + } |
| + }) |
| + t.Run("full-queue", func(t *testing.T) { |
| + s, d := reportFixture(t) |
| + now := time.Now() |
| + if _, err := s.store.db.Exec(`WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<2000) INSERT INTO demo_reports(id,demo_id,host,category,details,created_at,ip_hash) SELECT cast(x AS TEXT),?,'shop.example.com','other','',?,zeroblob(32) FROM n`, d.ID, now.Add(-48*time.Hour).Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + c, v := reportForm(t, s, d.Host) |
| + w := reportPost(s, c, v, s.cfg.Origin, "192.0.2.1") |
| + if w.Code != 429 { |
| + t.Fatalf("queue %d %s", w.Code, w.Body.String()) |
| + } |
| + var n int |
| + s.store.db.QueryRow(`SELECT count(*) FROM demo_reports`).Scan(&n) |
| + if n != 2000 { |
| + t.Fatalf("eviction %d", n) |
| + } |
| + }) |
| +} |
| + |
| +func TestDemoReportOperatorAuthority(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.Demo = demoTestConfig(t) |
| + fx.srv.registerDemoOperatorRoutes() |
| + fx.srv.cfg.SystemOperators = []string{"operator@example.com"} |
| + owner := cliToken(t, fx, "owner@example.com", "report-owner") |
| + if err := fx.st.AddMember(OpsAccountID, "owner@example.com", RoleOwner, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + listed := cliToken(t, fx, "operator@example.com", "report-listed") |
| + member := cliToken(t, fx, "member@example.com", "report-member") |
| + if err := fx.st.AddMember(OpsAccountID, "member@example.com", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + svc := serviceToken(t, fx.st, OpsAccountID, "report-admin", "shop", svcrole.Admin) |
| + app, err := fx.st.NewAppToken(OpsAccountID, "shop", "owner@example.com", "report-app", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + id := fmt.Sprintf("%016x-%s", time.Now().Unix(), strings.Repeat("a", 32)) |
| + if _, err = fx.st.db.Exec(`INSERT INTO demo_reports(id,demo_id,host,category,details,created_at,ip_hash) VALUES(?,'demo','shop.example.com','other',?,?,?)`, id, "<script>alert(1)</script>", time.Now().Unix(), []byte(strings.Repeat("x", 32))); err != nil { |
| + t.Fatal(err) |
| + } |
| + paths := []struct{ method, path string }{{"GET", "/api/cli/system/demos/reports"}, {"POST", "/api/cli/system/demos/reports/" + id + "/resolve"}} |
| + for _, p := range paths { |
| + var want string |
| + for _, token := range []string{member, svc, app, "forged", ""} { |
| + status, _, body := rawReq(t, p.method, fx.ts.URL+p.path, token, "") |
| + if want == "" { |
| + want = body |
| + } |
| + if status != 404 || body != want { |
| + t.Fatalf("authority %s %d %s", p.path, status, body) |
| + } |
| + } |
| + for _, token := range []string{owner, listed} { |
| + status, _, body := rawReq(t, p.method, fx.ts.URL+p.path, token, "") |
| + if status != 200 { |
| + t.Fatalf("operator %d %s", status, body) |
| + } |
| + for _, secret := range []string{"ip_hash", "claim_token", "resolved_by", strings.Repeat("x", 32), "<script>"} { |
| + if strings.Contains(body, secret) { |
| + t.Fatalf("leak %s: %s", secret, body) |
| + } |
| + } |
| + } |
| + } |
| + for _, query := range []string{"?limit=0", "?limit=101", "?limit=x", "?after=invalid", "?limit=1&limit=2", "?secret=x"} { |
| + status, _, _ := rawReq(t, "GET", fx.ts.URL+paths[0].path+query, owner, "") |
| + if status != 400 { |
| + t.Fatalf("query %s %d", query, status) |
| + } |
| + } |
| +} |
| + |
| +func TestDemoReportEscapingAndUniformRefusal(t *testing.T) { |
| + s, d := reportFixture(t) |
| + w := httptest.NewRecorder() |
| + s.renderDemoReport(w, 200, `"><script>alert(1)</script>`, "token", "") |
| + if strings.Contains(w.Body.String(), "<script>") || !strings.Contains(w.Body.String(), "<script>") || !strings.Contains(w.Header().Get("Content-Security-Policy"), "default-src 'none'") { |
| + t.Fatalf("escape %s", w.Body.String()) |
| + } |
| + c, v := reportForm(t, s, d.Host) |
| + v.Set("details", strings.Repeat("a", 1000)) |
| + if w := reportPost(s, c, v, s.cfg.Origin, "192.0.2.1"); w.Code != 200 { |
| + t.Fatalf("1000 %d", w.Code) |
| + } |
| + v.Set("details", strings.Repeat("é", 501)) |
| + if w := reportPost(s, c, v, s.cfg.Origin, "192.0.2.2"); w.Code != 400 { |
| + t.Fatalf("1002 bytes %d", w.Code) |
| + } |
| + if _, err := s.store.db.Exec(`UPDATE demo_apps SET purged_at=? WHERE demo_id=?`, time.Now().Add(-7*24*time.Hour).Unix(), d.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + var want string |
| + for _, host := range []string{d.Host, "shop.example.com", "shop.example.com:443", "https://example.com", "SHOP.example.com"} { |
| + r := httptest.NewRequest("GET", "/demo/report?host="+url.QueryEscape(host), nil) |
| + w := httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if want == "" { |
| + want = w.Body.String() |
| + } |
| + if w.Code != 400 || w.Body.String() != want { |
| + t.Fatalf("uniform %s %d", host, w.Code) |
| + } |
| + } |
| +} |
| + |
| +func TestDemoReportForwardingUsesNoStorage(t *testing.T) { |
| + s, d := reportFixture(t) |
| + storage := &demoCountingStore{Store: s.cfg.Releases} |
| + storage.fail.Store(true) |
| + s.cfg.Releases = storage |
| + c, v := reportForm(t, s, d.Host) |
| + key := []byte("0123456789abcdef0123456789abcdef") |
| + for i, mode := range []string{"cold", "valid", "forged", "stale", "unsigned", "wrong-host", "extra-xff"} { |
| + now := time.Now() |
| + xff := fmt.Sprintf("198.51.100.%d", i+1) |
| + r := httptest.NewRequest("POST", "https://console.example.com/demo/report", strings.NewReader(v.Encode())) |
| + r.RemoteAddr = "127.0.0.1:1234" |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.Header.Set("Origin", s.cfg.Origin) |
| + r.AddCookie(c) |
| + r.Header.Set("X-Forwarded-For", xff) |
| + r.Header.Set(edgeproof.Header, edgeproof.Sign(key, r.Host, xff, now)) |
| + s.edgeProof.mu.Lock() |
| + s.edgeProof.at = now |
| + s.edgeProof.current = key |
| + switch mode { |
| + case "cold": |
| + s.edgeProof.at = time.Time{} |
| + case "stale": |
| + s.edgeProof.at = now.Add(-time.Minute) |
| + case "forged": |
| + r.Header.Set(edgeproof.Header, "forged") |
| + case "unsigned": |
| + r.Header.Del(edgeproof.Header) |
| + case "wrong-host": |
| + r.Header.Set(edgeproof.Header, edgeproof.Sign(key, "shop.example.com", xff, now)) |
| + case "extra-xff": |
| + r.Header.Add("X-Forwarded-For", "192.0.2.99") |
| + } |
| + s.edgeProof.mu.Unlock() |
| + got := s.clientIPWithProof(r, s.demoReportForwardedByEdge) |
| + want := "127.0.0.1" |
| + if mode == "valid" { |
| + want = xff |
| + } |
| + if got != want { |
| + t.Fatalf("%s IP %s want %s", mode, got, want) |
| + } |
| + w := httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 200 { |
| + t.Fatalf("%s %d %s", mode, w.Code, w.Body.String()) |
| + } |
| + } |
| + if storage.gets.Load() != 0 || storage.puts.Load() != 0 || storage.polls.Load() != 0 || storage.lists.Load() != 0 { |
| + t.Fatal("report touched storage") |
| + } |
| +} |
| + |
| +func TestDemoReportCookieAndOrigin(t *testing.T) { |
| + for _, mode := range []string{"missing-origin", "http-origin", "null-origin", "duplicate-origin", "duplicate-cookie", "forged-matching-cookie", "future-cookie", "query-values"} { |
| + t.Run(mode, func(t *testing.T) { |
| + s, d := reportFixture(t) |
| + c, v := reportForm(t, s, d.Host) |
| + if mode == "forged-matching-cookie" { |
| + c.Value = strings.Repeat("x", len(c.Value)) |
| + v.Set("csrf", c.Value) |
| + } |
| + if mode == "future-cookie" { |
| + c.Value, _ = s.demoReportToken(t.Context(), time.Now().Add(time.Hour)) |
| + v.Set("csrf", c.Value) |
| + } |
| + target := "/demo/report" |
| + if mode == "query-values" { |
| + target += "?host=" + d.Host |
| + } |
| + r := httptest.NewRequest("POST", target, strings.NewReader(v.Encode())) |
| + r.RemoteAddr = "192.0.2.1:1234" |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.Header.Set("Origin", s.cfg.Origin) |
| + r.AddCookie(c) |
| + switch mode { |
| + case "missing-origin": |
| + r.Header.Del("Origin") |
| + case "http-origin": |
| + r.Header.Set("Origin", "http://console.example.com") |
| + case "null-origin": |
| + r.Header.Set("Origin", "null") |
| + case "duplicate-origin": |
| + r.Header.Add("Origin", s.cfg.Origin) |
| + case "duplicate-cookie": |
| + r.AddCookie(c) |
| + } |
| + w := httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 400 { |
| + t.Fatalf("%d %s", w.Code, w.Body.String()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoReportCursorAfterPrune(t *testing.T) { |
| + s, d := reportFixture(t) |
| + now := time.Now() |
| + for i := 0; i < 3; i++ { |
| + if _, err := s.store.AddDemoReport(t.Context(), d.Host, "other", "", "192.0.2.1", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + first, next, err := s.store.ListDemoReports(t.Context(), "", 1) |
| + if err != nil || len(first) != 1 || next == "" { |
| + t.Fatalf("first %+v %s %v", first, next, err) |
| + } |
| + if _, err = s.store.db.Exec(`DELETE FROM demo_reports WHERE id=?`, next); err != nil { |
| + t.Fatal(err) |
| + } |
| + rest, _, err := s.store.ListDemoReports(t.Context(), next, 100) |
| + if err != nil || len(rest) != 2 { |
| + t.Fatalf("pruned cursor %+v %v", rest, err) |
| + } |
| + if rest[0].ID >= rest[1].ID { |
| + t.Fatalf("unstable same-time order %+v", rest) |
| + } |
| +} |
diff --git a/internal/console/demo_store.go b/internal/console/demo_store.go| index 45fe43d1d..218937b16 100644 |
| --- a/internal/console/demo_store.go |
| +++ b/internal/console/demo_store.go |
| @@ -83,6 +83,9 @@ CREATE TABLE IF NOT EXISTS demo_retirements(demo_id TEXT PRIMARY KEY, wire BLOB |
| if err := s.migrateDemoServing(); err != nil { |
| return err |
| } |
| + if err := s.migrateDemoReports(); err != nil { |
| + return err |
| + } |
| return s.migrateDemoJobs() |
| } |
| @@ -432,6 +435,12 @@ func (s *Store) WipeDemoAbuse(ctx context.Context, now time.Time) error { |
| } |
| defer tx.Rollback() |
| cutoff := now.Add(-7 * 24 * time.Hour).Unix() |
| + if _, err = tx.ExecContext(ctx, `DELETE FROM demo_report_attempts WHERE attempted_at<=?`, now.Add(-24*time.Hour).UnixNano()); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `DELETE FROM demo_reports WHERE demo_id IN (SELECT demo_id FROM demo_apps WHERE purged_at>0 AND purged_at<=?)`, cutoff); err != nil { |
| + return err |
| + } |
| if _, err = tx.ExecContext(ctx, `UPDATE demo_apps SET creating_ip='',source_sha256=X'',client='' WHERE purged_at>0 AND purged_at<=? AND (creating_ip!='' OR length(source_sha256)>0 OR client!='')`, cutoff); err != nil { |
| return err |
| } |
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go| index a7a7b2b8f..13824b8f0 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -188,6 +188,8 @@ var claimAppsTerminal = map[string][]string{ |
| // cannot silently ship ungated. There is deliberately no exemption class: |
| // audit and mail telemetry are app-scoped and are gated like the rest. |
| var claimSQLTables = map[string]claimSQLTable{ |
| + "demo_reports": {App: "demo_id", Refuse: "anonymous demo reports require claims mode off"}, |
| + "demo_report_attempts": {NonApp: "deployment report attempt budget keyed by salted IP hash and time; names no app"}, |
| "demo_serving": {App: "id", Refuse: "anonymous demo serving requires claims mode off"}, |
| "demo_caps": {App: "demo_id", Refuse: "anonymous demo caps require claims mode off"}, |
| "demo_retirements": {App: "demo_id", Refuse: "anonymous demo retirement requires claims mode off"}, |
diff --git a/internal/console/templates/demo_report.html b/internal/console/templates/demo_report.html| new file mode 100644 |
| index 000000000..c1b6d16e2 |
| --- /dev/null |
| +++ b/internal/console/templates/demo_report.html |
| @@ -0,0 +1,31 @@ |
| +{{define "demo_report"}}<!doctype html> |
| +<html lang="en"> |
| +<head> |
| +<meta charset="utf-8"> |
| +<meta name="viewport" content="width=device-width, initial-scale=1"> |
| +<title>{{.Copy.title}}</title> |
| +<link rel="stylesheet" href="{{asset "rastrillo/tokens.css"}}"> |
| +<link rel="stylesheet" href="{{asset "rastrillo/day.css"}}"> |
| +</head> |
| +<body> |
| +<main> |
| +<h1>{{.Copy.title}}</h1> |
| +{{if .Message}}<p role="status">{{.Message}}</p>{{else}} |
| +<form method="post" action="/demo/report"> |
| +<input type="hidden" name="csrf" value="{{.Token}}"> |
| +<p><label for="host">{{.Copy.host}}</label> |
| +<input id="host" name="host" value="{{.Host}}" readonly></p> |
| +<p><label for="category">{{.Copy.category}}</label> |
| +<select id="category" name="category" required> |
| +<option value="phishing">{{.Copy.phishing}}</option> |
| +<option value="harmful">{{.Copy.harmful}}</option> |
| +<option value="other">{{.Copy.other}}</option> |
| +</select></p> |
| +<p><label for="details">{{.Copy.details}}</label> |
| +<textarea id="details" name="details" maxlength="1000" aria-describedby="details-hint"></textarea></p> |
| +<p id="details-hint">{{.Copy.hint}}</p> |
| +<button type="submit">{{.Copy.submit}}</button> |
| +</form>{{end}} |
| +</main> |
| +</body> |
| +</html>{{end}} |
diff --git a/internal/edge/demo_banner_test.go b/internal/edge/demo_banner_test.go| index 51d92ab4f..8888a6e33 100644 |
| --- a/internal/edge/demo_banner_test.go |
| +++ b/internal/edge/demo_banner_test.go |
| @@ -490,3 +490,18 @@ type demoCloseWitness struct { |
| } |
| func (b *demoCloseWitness) Close() error { b.closed = true; return nil } |
| + |
| +func TestDemoReportBannerDestination(t *testing.T) { |
| + markup, err := demoBannerMarkup("shop.example.com", "https://console.example.com/") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.Contains(markup, `href="https://console.example.com/demo/report?host=shop.example.com" target="_blank" rel="noopener noreferrer"`) { |
| + t.Fatalf("link %s", markup) |
| + } |
| + for _, origin := range []string{"", "http://console.example.com", "https://console.example.com/?token=secret", "https://console.example.com/#secret", "https://user:secret@console.example.com", "https://console.example.com/foreign", "https://console.example.com\\@example.com"} { |
| + if _, err := demoBannerMarkup("shop.example.com", origin); err == nil { |
| + t.Fatalf("unsafe origin %q", origin) |
| + } |
| + } |
| +} |
diff --git a/system_demos.go b/system_demos.go| index cbe4e5b9b..b41207129 100644 |
| --- a/system_demos.go |
| +++ b/system_demos.go |
| @@ -5,7 +5,10 @@ import ( |
| "fmt" |
| "log" |
| "os" |
| + "strconv" |
| "strings" |
| + "time" |
| + "unicode" |
| "github.com/carlosframework/platform/internal/demo" |
| ) |
| @@ -23,6 +26,10 @@ func runSystemDemos(args []string) { |
| invalid() |
| return |
| } |
| + if args[0] == "reports" { |
| + runSystemDemosReports(args[1:]) |
| + return |
| + } |
| verb := args[0] |
| rest := args[1:] |
| host, console := "", "" |
| @@ -132,3 +139,100 @@ func printDemoServing(d systemDemoView) { |
| } |
| fmt.Fprintf(stdout, "Serving: %s (%s)\n", desired, confirmed) |
| } |
| + |
| +func demoReportTerminal(s string) string { |
| + return strings.Map(func(r rune) rune { |
| + if unicode.IsControl(r) || unicode.In(r, unicode.Cf) { |
| + return -1 |
| + } |
| + return r |
| + }, strings.ToValidUTF8(s, "")) |
| +} |
| +func demoReportCLIKey(s string) bool { |
| + if s == "" || len(s) > 128 { |
| + return false |
| + } |
| + for _, r := range s { |
| + if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_') { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| +func runSystemDemosReports(args []string) { |
| + invalid := func() { fmt.Fprintln(os.Stderr, systemDemosInvalid); os.Exit(2) } |
| + resolve := len(args) > 0 && args[0] == "resolve" |
| + if resolve { |
| + args = args[1:] |
| + } |
| + values := map[string]string{} |
| + for len(args) > 0 { |
| + if len(args) < 2 { |
| + invalid() |
| + return |
| + } |
| + key := strings.TrimPrefix(args[0], "-") |
| + key = strings.TrimPrefix(key, "-") |
| + if args[0] != "-"+key && args[0] != "--"+key { |
| + invalid() |
| + return |
| + } |
| + if key != "console" && key != "after" && key != "limit" && key != "id" { |
| + invalid() |
| + return |
| + } |
| + if _, exists := values[key]; exists || args[1] == "" { |
| + invalid() |
| + return |
| + } |
| + values[key] = args[1] |
| + args = args[2:] |
| + } |
| + limit := 50 |
| + if raw, ok := values["limit"]; ok { |
| + var err error |
| + limit, err = strconv.Atoi(raw) |
| + if err != nil || limit < 1 || limit > 100 { |
| + invalid() |
| + return |
| + } |
| + } |
| + if resolve { |
| + if !demoReportCLIKey(values["id"]) || values["after"] != "" || values["limit"] != "" { |
| + invalid() |
| + return |
| + } |
| + } else if values["id"] != "" || (values["after"] != "" && !demoReportCLIKey(values["after"])) { |
| + invalid() |
| + return |
| + } |
| + sess, err := resolveMode(values["console"]) |
| + if err != nil { |
| + log.Print(demoReportTerminal(err.Error())) |
| + os.Exit(1) |
| + } |
| + if sess == nil { |
| + fmt.Fprintln(os.Stderr, systemDemosHelp) |
| + os.Exit(1) |
| + } |
| + out, err := sess.systemDemosReports(context.Background(), values["after"], limit, values["id"]) |
| + if err != nil { |
| + log.Print(demoReportTerminal(err.Error())) |
| + os.Exit(1) |
| + } |
| + if resolve { |
| + fmt.Fprintln(stdout, "Report resolved.") |
| + return |
| + } |
| + for _, r := range out.Reports { |
| + state := "Open" |
| + if r.State == "resolved" { |
| + state = "Resolved" |
| + } |
| + reason := map[string]string{"phishing": "Phishing", "harmful": "Harmful content", "other": "Other"}[r.Category] |
| + fmt.Fprintf(stdout, "ID: %s\nHost: %s\nReason: %s\nDetails: %s\nCreated: %s\nState: %s\n", demoReportTerminal(r.ID), demoReportTerminal(r.Host), reason, demoReportTerminal(r.Details), time.Unix(r.CreatedAt, 0).UTC().Format(time.RFC3339), state) |
| + } |
| + if out.Next != "" { |
| + fmt.Fprintf(stdout, "Continue after this report: %s\n", demoReportTerminal(out.Next)) |
| + } |
| +} |
diff --git a/system_demos_api.go b/system_demos_api.go| index 44d2b9505..cb5841c36 100644 |
| --- a/system_demos_api.go |
| +++ b/system_demos_api.go |
| @@ -5,6 +5,7 @@ import ( |
| "encoding/json" |
| "net/http" |
| "net/url" |
| + "strconv" |
| "github.com/carlosframework/platform/internal/demo" |
| ) |
| @@ -57,3 +58,42 @@ func (s *apiSession) systemDemos(ctx context.Context, verb, host string, enabled |
| err = json.Unmarshal(raw, &out) |
| return out, err |
| } |
| + |
| +type systemDemoReports struct { |
| + Reports []struct { |
| + ID string `json:"id"` |
| + Host string `json:"host"` |
| + Category string `json:"category"` |
| + Details string `json:"details"` |
| + State string `json:"state"` |
| + CreatedAt int64 `json:"createdAt"` |
| + } `json:"reports"` |
| + Next string `json:"next"` |
| +} |
| + |
| +func (s *apiSession) systemDemosReports(ctx context.Context, after string, limit int, id string) (systemDemoReports, error) { |
| + path := "/api/cli/system/demos/reports" |
| + var out systemDemoReports |
| + var code int |
| + var raw []byte |
| + var err error |
| + if id != "" { |
| + code, raw, err = s.sendJSON(ctx, http.MethodPost, path+"/"+url.PathEscape(id)+"/resolve", struct{}{}) |
| + } else { |
| + q := url.Values{"limit": {strconv.Itoa(limit)}} |
| + if after != "" { |
| + q.Set("after", after) |
| + } |
| + code, raw, err = s.getJSON(ctx, path+"?"+q.Encode()) |
| + } |
| + if err != nil { |
| + return out, err |
| + } |
| + if code != 200 { |
| + return out, apiErrorFromBody(code, raw) |
| + } |
| + if id == "" { |
| + err = json.Unmarshal(raw, &out) |
| + } |
| + return out, err |
| +} |
diff --git a/system_demos_test.go b/system_demos_test.go| index ad85be548..52f50aa0d 100644 |
| --- a/system_demos_test.go |
| +++ b/system_demos_test.go |
| @@ -90,3 +90,57 @@ func TestSystemDemosRemote(t *testing.T) { |
| t.Fatalf("purged %d %s", code, out) |
| } |
| } |
| + |
| +func TestSystemDemosReports(t *testing.T) { |
| + bin := buildCarlos(t) |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Header.Get("Authorization") != "Bearer tok-operator" { |
| + t.Error("credential") |
| + } |
| + switch r.Method + " " + r.URL.Path { |
| + case "GET /api/cli/system/demos/reports": |
| + if r.URL.Query().Get("limit") != "2" || r.URL.Query().Get("after") != "cursor" { |
| + t.Errorf("query %s", r.URL.RawQuery) |
| + } |
| + io.WriteString(w, `{"reports":[{"id":"report","host":"shop.example.com","category":"other","details":"bad\u001b[31m\ntext\u009b31m","state":"open","createdAt":1}],"next":"next-id"}`) |
| + case "POST /api/cli/system/demos/reports/report/resolve": |
| + io.WriteString(w, `{"state":"resolved"}`) |
| + default: |
| + t.Errorf("unexpected %s %s", r.Method, r.URL) |
| + http.NotFound(w, r) |
| + } |
| + })) |
| + defer ts.Close() |
| + cred := filepath.Join(t.TempDir(), "credentials") |
| + raw, _ := json.Marshal(map[string]any{"version": 1, "credentials": []any{map[string]string{"console": ts.URL, "address": "operator@example.com", "token": "tok-operator"}}}) |
| + if err := os.WriteFile(cred, raw, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + run := func(args ...string) (string, int) { |
| + cmd := exec.Command(bin, append([]string{"system", "demos", "reports"}, args...)...) |
| + cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+cred) |
| + cmd.Dir = t.TempDir() |
| + b, err := cmd.CombinedOutput() |
| + if err == nil { |
| + return string(b), 0 |
| + } |
| + if e, ok := err.(*exec.ExitError); ok { |
| + return string(b), e.ExitCode() |
| + } |
| + t.Fatal(err) |
| + return "", -1 |
| + } |
| + out, code := run("--limit", "2", "--after", "cursor") |
| + if code != 0 || !strings.Contains(out, "Details: ") || strings.ContainsAny(out, "\x1b\u009b") || !strings.Contains(out, "next-id") { |
| + t.Fatalf("list %d %s", code, out) |
| + } |
| + out, code = run("resolve", "--id", "report") |
| + if code != 0 || !strings.Contains(out, "Report resolved.") { |
| + t.Fatalf("resolve %d %s", code, out) |
| + } |
| + for _, args := range [][]string{{"--limit", "0"}, {"--limit", "101"}, {"--limit", "x"}, {"resolve"}, {"resolve", "--id", "../bad"}, {"--limit", "2", "--limit", "3"}, {"--id", "report"}, {"resolve", "--id", "report", "--after", "cursor"}} { |
| + if _, code := run(args...); code != 2 { |
| + t.Fatalf("usage %v %d", args, code) |
| + } |
| + } |
| +} |