Files
uptimesebi/internal/api/evidence_test.go
T
Sebastian UnterschützandClaude Opus 5.5 e26194d260
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 13m0s
ci / test (pull_request) Successful in 13m56s
ci / build (pull_request) Successful in 19m56s
ci / image (pull_request) Successful in 5m50s
fix(evidence): spread periodic evidence and store a report's in one go
Checkers send evidence of healthy checks every 10 minutes, first with
the first result after they start. When checkers restart together, as
after a self-update, every monitor's evidence came in the same minute,
every 10 minutes. The API stored each in a transaction of its own while
the checker waited, reports took up to 36 seconds, the checkers' slots
filled and runs piled up: the overdue waves seen in prod.

Evidence sent for another reason than the period now puts the next
periodic one at a random point of the period, and the API writes all of
a report's evidence in one transaction, with one query each for the
successes to replace and the failures last kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 18:16:05 +01:00

170 lines
6.8 KiB
Go

package api_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
)
func TestEvidence(t *testing.T) {
e := newEnv(t)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go e.api.RunScheduler(ctx)
var healthy atomic.Bool
site := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.Redirect(w, r, "/app", http.StatusFound)
return
}
http.SetCookie(w, &http.Cookie{Name: "sid", Value: "cookie-secret"})
if !healthy.Load() {
w.WriteHeader(http.StatusBadGateway)
_, _ = w.Write([]byte(`<script>alert("pwned")</script> upstream down`))
return
}
_, _ = w.Write([]byte("all good"))
}))
defer site.Close()
tok, region := e.platformChecker(t, uniq("eu-"))
e.startChecker(t, tok)
owner := e.browser(t)
owner.signup("o@"+uniq("ev")+".test", uniq("ev-"))
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "Shop", "type": "http", "target": site.URL + "/", "interval_seconds": 10, "timeout_ms": 2000,
"confirmations": 1, "regions": []string{region}, "config": map[string]any{"verify_tls": false, "headers": map[string]string{"X-Token": "header-secret"}},
})
if st != http.StatusCreated {
t.Fatalf("create monitor = %d %v", st, body)
}
id := body["id"].(string)
evidence := func() []any {
_, b := owner.do("GET", "/api/v1/org/monitors/"+id+"/evidence", nil)
list, _ := b["evidence"].([]any)
return list
}
waitFor(t, 15*time.Second, "evidence of the failure", func() bool { return len(evidence()) > 0 })
first := evidence()[0].(map[string]any)
_, detail := owner.do("GET", "/api/v1/org/monitors/"+id+"/evidence/"+first["id"].(string), nil)
raw := mustJSON(detail)
for _, want := range []string{`"status":302`, `"status":502`, `"not_after"`, `upstream down`} {
if !strings.Contains(raw, want) {
t.Errorf("evidence lacks %s: %.600s", want, raw)
}
}
steps := detail["evidence"].(map[string]any)["steps"].([]any)
cookie := steps[len(steps)-1].(map[string]any)["response_headers"].(map[string]any)["Set-Cookie"].([]any)
if len(cookie) != 1 || cookie[0] != "sid=<redacted>" {
t.Errorf("Set-Cookie = %v, want the name only", cookie)
}
for _, secret := range []string{"cookie-secret", "header-secret"} {
if strings.Contains(raw, secret) {
t.Errorf("evidence contains %s", secret)
}
}
// The page shows the body as text, never as markup.
_, _, page := owner.page("/monitors/" + id + "/evidence/" + first["id"].(string))
if strings.Contains(page, `<script>alert("pwned")`) || !strings.Contains(page, "&lt;script&gt;") {
t.Error("the evidence page renders the response body as HTML")
}
if !strings.Contains(page, "502 Bad Gateway") || !strings.Contains(page, "/app") {
t.Error("the evidence page lacks the redirect chain")
}
if _, _, mp := owner.page("/monitors/" + id); !strings.Contains(mp, "/evidence/") {
t.Error("the monitor page does not link the evidence")
}
// A lasting outage with the same error is kept once.
time.Sleep(12 * time.Second)
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND NOT ok`, id); n != 1 {
t.Errorf("failure evidence rows = %d, want 1", n)
}
healthy.Store(true)
waitFor(t, 25*time.Second, "evidence of a success", func() bool {
return e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND ok`, id) == 1
})
// Readers get neither the list nor the page.
viewer := e.joinVia(t, owner.invite("v@"+uniq("ev")+".test", owner.roleID("viewer")))
if st, _ := viewer.do("GET", "/api/v1/org/monitors/"+id+"/evidence", nil); st != http.StatusForbidden {
t.Errorf("viewer lists evidence = %d, want 403", st)
}
if got := viewer.visit("/monitors/" + id + "/evidence/" + first["id"].(string)); got.Path != "/" {
t.Errorf("viewer opening evidence ended at %s, want /", got.Path)
}
if _, _, vp := viewer.page("/monitors/" + id); strings.Contains(vp, "/evidence/") {
t.Error("the monitor page links evidence for a viewer")
}
}
// TestEvidenceBatch stores a report with evidence of several monitors and
// runs at once, as a checker sends after a backlog.
func TestEvidenceBatch(t *testing.T) {
e := newEnv(t)
tok, region := e.platformChecker(t, uniq("ev-batch-"))
owner := e.browser(t)
owner.signup("o@"+uniq("evb")+".test", uniq("evb-"))
monitor := func() uuid.UUID {
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
})
return uuid.MustParse(m["id"].(string))
}
up, down := monitor(), monitor()
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
ev := json.RawMessage(`{"steps":[]}`)
at := time.Now().Add(-time.Minute).Truncate(time.Millisecond)
run := func(m uuid.UUID, after time.Duration, ok bool, msg string) agentapi.Result {
return agentapi.Result{MonitorID: m, ScheduledAt: at.Add(after), StartedAt: at.Add(after), OK: ok, Error: msg, Evidence: ev}
}
if err := client.Report(context.Background(), []agentapi.Result{
run(up, 0, true, ""),
run(up, time.Second, true, ""),
run(down, 0, false, "boom"),
run(down, time.Second, false, "boom"),
run(down, 2*time.Second, false, "other"),
}); err != nil {
t.Fatal(err)
}
// The latest success only; failures unless the same one was just kept.
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND ok AND time = $2`, up, at.Add(time.Second)); n != 1 {
t.Errorf("success evidence of the latest run = %d rows, want 1", n)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1`, up); n != 1 {
t.Errorf("success evidence rows = %d, want 1", n)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND NOT ok`, down); n != 2 {
t.Errorf("failure evidence rows = %d, want 2: boom once, then other", n)
}
// The next report replaces the success and thins out the failure
// already kept.
if err := client.Report(context.Background(), []agentapi.Result{
run(up, 5*time.Second, true, ""),
run(down, 10*time.Second, false, "other"),
}); err != nil {
t.Fatal(err)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND ok AND time = $2`, up, at.Add(5*time.Second)); n != 1 {
t.Errorf("success evidence after the next report: latest run kept %d times, want 1", n)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1`, up); n != 1 {
t.Errorf("success evidence rows after the next report = %d, want 1", n)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND NOT ok`, down); n != 2 {
t.Errorf("failure evidence rows after the next report = %d, want still 2", n)
}
}