Files
uptimesebi/internal/api/checker_test.go
T
Sebastian UnterschützandClaude Opus 5.5 a35dadd8f6
ci / test (pull_request) Successful in 9m12s
ci / lint (pull_request) Successful in 12m17s
ci / build (pull_request) Successful in 16m25s
ci / image (pull_request) Successful in 4m40s
feat(agents): self-updating agent image variant
The -autoupdate variant of the checker and status page images adds a
launcher layer. The launcher runs the agent as a child process and keeps
it on the platform's release: GET /agent/v1/update names the API's own
release and the agent image for it, the launcher downloads the binary
for its platform from the registry, accepts it only when the index is
signed with a release key for exactly that version, swaps the agent
gracefully and rolls back when the new release does not become ready or
crashes right after starting. Agents never get ahead of the API, and
installations on unreleased builds are not followed.

CI pushes both variants and signs each index with RELEASE_SIGNING_KEY
(minisign signature in a sha256-<digest>.minisig image next to it). The
image builder moves to internal/agentimage; the API image job takes the
build job's version so the API reports the release its agents are tagged
with. Agents gain a version command.

Closes #129
Closes #128

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

274 lines
8.8 KiB
Go

package api_test
import (
"context"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
"git.zb-server.de/ZB-Server/uptimesebi/internal/checker"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// platformChecker creates a platform region with a checker agent directly
// in the database, as "api agent create" would, and returns the agent token
// and the region ID.
func (e *env) platformChecker(t *testing.T, key string) (string, string) {
t.Helper()
ctx := context.Background()
var (
tok string
region store.Region
)
err := tenant.New(e.dbPool).Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if region, err = q.EnsurePlatformRegion(ctx, store.EnsurePlatformRegionParams{Key: key}); err != nil {
return err
}
var params store.CreateAgentParams
tok, params = api.NewAgentToken(nil, "checker", "test-"+key, &region.ID)
_, err = q.CreateAgent(ctx, params)
return err
})
if err != nil {
t.Fatalf("creating agent: %v", err)
}
return tok, region.ID.String()
}
// startChecker runs a checker instance until the returned stop is called.
func (e *env) startChecker(t *testing.T, token string) (uuid.UUID, func()) {
t.Helper()
id := uuid.New()
client := agentapi.NewClient(e.srv.URL, token, id, "test").WithHTTPClient(e.srv.Client())
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
_ = checker.New(client, 8, slog.New(slog.DiscardHandler)).Run(ctx, 5*time.Second)
}()
var once bool
stop := func() {
if once {
return
}
once = true
cancel()
<-done
}
t.Cleanup(stop)
return id, stop
}
func TestCheckersPerRegion(t *testing.T) {
e := newEnv(t)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go e.api.RunScheduler(ctx)
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/down" {
w.WriteHeader(http.StatusInternalServerError)
}
}))
defer target.Close()
euTok, eu := e.platformChecker(t, uniq("eu-"))
usTok, us := e.platformChecker(t, uniq("us-"))
euA, stopA := e.startChecker(t, euTok)
euB, _ := e.startChecker(t, euTok)
usC, _ := e.startChecker(t, usTok)
owner := e.browser(t)
owner.signup("o@"+uniq("c")+".test", uniq("chk-"))
org := owner.orgID()
// Instances register on their first poll.
waitFor(t, 5*time.Second, "both eu instances registered", func() bool {
_, body := owner.do("GET", "/api/v1/org/regions", nil)
for _, r := range body["regions"].([]any) {
r := r.(map[string]any)
if r["id"] == eu && r["instances"] == float64(2) {
return true
}
}
return false
})
const n = 30
for i := range n {
path := "/up"
if i == 0 {
path = "/down"
}
regions := []string{eu}
if i < 3 {
regions = append(regions, us)
}
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "m", "type": "http", "target": target.URL + path, "interval_seconds": 3600, "regions": regions,
})
if st != http.StatusCreated {
t.Fatalf("create monitor = %d %v", st, body)
}
}
count := func(checker uuid.UUID) (total, failed int) {
_ = e.dbPool.QueryRow(context.Background(),
`SELECT count(*), count(*) FILTER (WHERE NOT ok) FROM check_results WHERE org_id = $1 AND checker_id = $2`,
org, checker).Scan(&total, &failed)
return total, failed
}
waitFor(t, 15*time.Second, "all first runs reported", func() bool {
a, _ := count(euA)
b, _ := count(euB)
c, _ := count(usC)
return a+b == n && c == 3
})
a, aFailed := count(euA)
b, bFailed := count(euB)
if a < 5 || b < 5 {
t.Errorf("eu instances ran %d and %d checks, want both to get a random share of %d", a, b, n)
}
if aFailed+bFailed != 1 {
t.Errorf("failed eu checks = %d, want 1 (the /down monitor)", aFailed+bFailed)
}
_, body := owner.do("GET", "/api/v1/org/monitors", nil)
withLatest := 0
for _, m := range body["monitors"].([]any) {
if len(m.(map[string]any)["latest"].([]any)) > 0 {
withLatest++
}
}
if withLatest != n {
t.Errorf("monitors with latest results = %d, want %d", withLatest, n)
}
// Stopping one eu instance leaves the other to take every eu check.
stopA()
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "after", "type": "tcp", "target": target.Listener.Addr().String(), "interval_seconds": 3600, "regions": []string{eu},
})
if st != http.StatusCreated {
t.Fatalf("create monitor = %d %v", st, body)
}
before, _ := count(euB)
waitFor(t, 10*time.Second, "remaining eu instance runs the new monitor", func() bool {
now, _ := count(euB)
return now == before+1
})
if after, _ := count(euA); after != a {
t.Errorf("stopped instance ran %d more checks", after-a)
}
}
func TestAgentAuth(t *testing.T) {
e := newEnv(t)
tok, _ := e.platformChecker(t, uniq("x-"))
ctx := context.Background()
if _, err := agentapi.NewClient(e.srv.URL, "usa_wrong", uuid.New(), "t").WithHTTPClient(e.srv.Client()).Hello(ctx); !errors.Is(err, agentapi.ErrUnauthorized) {
t.Errorf("Hello(wrong token) = %v, want %v", err, agentapi.ErrUnauthorized)
}
h, err := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "t").WithHTTPClient(e.srv.Client()).Hello(ctx)
if err != nil || h.Kind != "checker" {
t.Errorf("Hello() = %+v, %v; want checker", h, err)
}
// User API tokens and sessions do not open the agent API.
owner := e.browser(t)
owner.signup("a@"+uniq("a")+".test", uniq("auth-"))
st, _ := owner.do("GET", "/agent/v1/hello", nil)
if st == http.StatusOK {
t.Error("session opened the agent API")
}
}
func TestAgentUpdate(t *testing.T) {
e := newEnvWith(t, func(c *config.API) { c.AgentImage = "mirror.example/acme/uptimesebi" })
tok, _ := e.platformChecker(t, uniq("up-"))
ctx := context.Background()
instance := uuid.New()
client := agentapi.NewClient(e.srv.URL, tok, instance, "v1.0.0").WithHTTPClient(e.srv.Client())
u, err := client.Update(ctx)
if err != nil || u.Version != "dev" || u.Image != "" {
t.Errorf("unreleased platform: Update = %+v, %v", u, err)
}
old := buildinfo.Version
buildinfo.Version = "v1.4.2"
t.Cleanup(func() { buildinfo.Version = old })
u, err = client.Update(ctx)
if err != nil || u.Version != "v1.4.2" || u.Image != "mirror.example/acme/uptimesebi-checker:1.4.2" {
t.Errorf("Update = %+v, %v", u, err)
}
// The launcher asking is not an instance of the agent.
if n := e.count(t, `SELECT count(*) FROM agent_instances WHERE id = $1`, instance); n != 0 {
t.Errorf("the update check registered an instance")
}
if _, err := agentapi.NewClient(e.srv.URL, "usa_wrong", uuid.New(), "t").WithHTTPClient(e.srv.Client()).Update(ctx); !errors.Is(err, agentapi.ErrUnauthorized) {
t.Errorf("Update(wrong token) = %v", err)
}
}
func (b *browser) orgID() string {
b.t.Helper()
_, me := b.do("GET", "/api/v1/me", nil)
return me["active_org"].(string)
}
func waitFor(t *testing.T, d time.Duration, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(d)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for: %s", what)
}
time.Sleep(100 * time.Millisecond)
}
}
// A checker that lost the answer to a report sends it again; the results
// must not be stored twice.
func TestResultReportIsIdempotent(t *testing.T) {
e := newEnv(t)
tok, region := e.platformChecker(t, uniq("eu-"))
owner := e.browser(t)
owner.signup("o@"+uniq("id")+".test", uniq("id-"))
_, 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},
})
monitor := uuid.MustParse(m["id"].(string))
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
at := time.Now().Truncate(time.Millisecond)
batch := []agentapi.Result{
{MonitorID: monitor, ScheduledAt: at, StartedAt: at, OK: true},
{MonitorID: monitor, ScheduledAt: at.Add(time.Second), StartedAt: at.Add(time.Second), OK: false},
}
for range 3 {
if err := client.Report(context.Background(), batch); err != nil {
t.Fatal(err)
}
}
if n := e.count(t, `SELECT count(*) FROM check_results WHERE monitor_id = $1`, monitor); n != 2 {
t.Errorf("stored results = %d, want 2", n)
}
// Another instance's run of the same schedule time is its own result.
other := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
if err := other.Report(context.Background(), batch[:1]); err != nil {
t.Fatal(err)
}
if n := e.count(t, `SELECT count(*) FROM check_results WHERE monitor_id = $1`, monitor); n != 3 {
t.Errorf("stored results = %d, want 3", n)
}
}