// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini //go:build integration package main import ( "context" "database/sql" "encoding/json" "fmt" "log/slog" "net/http" "net/http/httptest" "strings" "testing" "time" ) type itHTTP struct { database *itDatabase server *WebServer handler http.Handler } func newITHTTP(t *testing.T) itHTTP { t.Helper() d := newITDatabase(t, itOptions{prefix: "http_"}) db, tables := d.migrated(t) s := newWebServer(d.config(t), discardLogger(), db, tables, func() time.Time { return webNow }) s.hashPassword = func(password string) (string, error) { return fakeHash(password), nil } s.verifyPassword = func(password, hash string) bool { return fakeHash(password) == hash } s.store = itCommitGateStore{s.store} return itHTTP{d, s, s.Handler()} } func (it itHTTP) createUser(t *testing.T, username, role string) userRow { t.Helper() u, err := newUserStore(it.server.db, it.server.tables).CreateUser(t.Context(), username, role, fakeHash(testPassword), webNow) if err != nil { t.Fatal(err) } return u } func (it itHTTP) token(t *testing.T, user userRow) string { t.Helper() token, hash, err := newSessionToken(it.server.random) if err != nil { t.Fatal(err) } session := newSessionRow(hash, user.ID, webNow, it.server.cfg.SessionMaxAge, "192.0.2.1", "") if err := newSessionStore(it.server.db, it.server.tables).CreateSession(t.Context(), session); err != nil { t.Fatal(err) } return token } func (it itHTTP) do(ctx context.Context, req webRequest) *httptest.ResponseRecorder { r := httptest.NewRequestWithContext(ctx, req.method, req.path, strings.NewReader(req.body)) r.RemoteAddr = "192.0.2.1:12345" if req.ctype != "" { r.Header.Set("Content-Type", req.ctype) } else if req.body != "" { r.Header.Set("Content-Type", "application/json") } for name, value := range req.header { r.Header.Set(name, value) } if req.token != "" { r.AddCookie(sessionCookie(req.token, false)) } w := httptest.NewRecorder() it.handler.ServeHTTP(w, r) return w } func (it itHTTP) audit(t *testing.T, operation string, status int, actor userRow) auditRow { t.Helper() rows, err := newAuditStore(it.server.db, it.server.tables).ListAudit(t.Context(), auditFilter{Operation: operation, Limit: 20}) if err != nil || len(rows) != 1 { t.Fatalf("%s audit: got %d rows, want 1, error %v", operation, len(rows), err) } e := rows[0] assertITHTTPAudit(t, e, operation, status, actor) return e } func assertITHTTPAudit(t *testing.T, e auditRow, operation string, status int, actor userRow) { t.Helper() if e.Operation != operation || !e.Status.Valid || e.Status.Int64 != int64(status) || !e.UserID.Valid || e.UserID.Int64 != actor.ID || e.Actor != actor.Username || !e.Time.Equal(webNow) || e.Origin != "192.0.2.1" || e.Error.Valid != (status >= 400) { t.Fatalf("%s audit: %+v", operation, e) } if status >= 400 && (e.Before != nil || e.After != nil) { t.Fatalf("%s failure has snapshots: %+v", operation, e) } } type itCommitGateKey struct{} type itCommitGate struct { reached chan struct{} release chan struct{} } type itCommitGateStore struct{ webStore } func (s itCommitGateStore) InTx(ctx context.Context, fn func(webTx) error) error { return s.webStore.InTx(ctx, itGateCommit(ctx, fn)) } func (s itCommitGateStore) InZoneTx(ctx context.Context, zone string, log *slog.Logger, fn func(webTx) error) error { return s.webStore.InZoneTx(ctx, zone, log, itGateCommit(ctx, fn)) } func itGateCommit(ctx context.Context, fn func(webTx) error) func(webTx) error { gate, ok := ctx.Value(itCommitGateKey{}).(*itCommitGate) if !ok { return fn } return func(tx webTx) error { if err := fn(tx); err != nil { return err } close(gate.reached) select { case <-gate.release: return nil case <-ctx.Done(): return ctx.Err() } } } func (it itHTTP) race(t *testing.T, first, second webRequest, firstStatus, secondStatus int) (*httptest.ResponseRecorder, *httptest.ResponseRecorder) { t.Helper() ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) defer cancel() gate := &itCommitGate{make(chan struct{}), make(chan struct{})} a := make(chan *httptest.ResponseRecorder, 1) b := make(chan *httptest.ResponseRecorder, 1) go func() { a <- it.do(context.WithValue(ctx, itCommitGateKey{}, gate), first) }() select { case <-gate.reached: case w := <-a: t.Fatalf("first request stopped before commit: %d %s", w.Code, w.Body) case <-ctx.Done(): t.Fatal("first request did not reach its commit") } go func() { b <- it.do(ctx, second) }() it.waitForUserLock(t, ctx, b) close(gate.release) return itHTTPResponse(t, ctx, a, firstStatus), itHTTPResponse(t, ctx, b, secondStatus) } func (it itHTTP) waitForUserLock(t *testing.T, ctx context.Context, result <-chan *httptest.ResponseRecorder) { t.Helper() it.waitForLock(t, ctx, result, "user row lock", func() (bool, error) { return it.database.rowLockWaiting(ctx, "webui_users") }) } func (it itHTTP) waitForLock(t *testing.T, ctx context.Context, result <-chan *httptest.ResponseRecorder, lock string, observe func() (bool, error)) { t.Helper() tick := time.NewTicker(itLockPollInterval) defer tick.Stop() for { waiting, err := observe() if err != nil { t.Fatalf("observe %s: %v", lock, err) } if waiting { return } select { case w := <-result: t.Fatalf("request did not wait on %s: %d %s", lock, w.Code, w.Body) case <-ctx.Done(): t.Fatalf("request did not reach %s", lock) case <-tick.C: } } } func itHTTPResponse(t *testing.T, ctx context.Context, result <-chan *httptest.ResponseRecorder, status int) *httptest.ResponseRecorder { t.Helper() select { case w := <-result: if w.Code != status { t.Fatalf("request status = %d, want %d, body %s", w.Code, status, w.Body) } return w case <-ctx.Done(): t.Fatal("request did not finish") return nil } } func TestIntegrationPasswordRaces(t *testing.T) { const resetPassword = "admin-reset-password" for _, scenario := range []string{"login_reset", "login_delete", "own_change_reset"} { for _, accountFirst := range []bool{true, false} { t.Run(fmt.Sprintf("%s/account_first_%t", scenario, accountFirst), func(t *testing.T) { it := newITHTTP(t) admin := it.createUser(t, "admin", roleAdmin) user := it.createUser(t, "alice", roleUser) token := it.token(t, user) it.token(t, user) adminToken := it.token(t, admin) account := webRequest{method: "POST", path: "/login", ctype: "application/x-www-form-urlencoded", body: loginForm(user.Username, testPassword, "")} accountOp, accountStatus, rejected := opLogin, http.StatusSeeOther, http.StatusUnauthorized mutation := webRequest{method: "PUT", path: apiPrefix + "/users/alice/password", token: adminToken, body: `{"password":"admin-reset-password"}`} mutationOp, finalPassword := opUserPassword, resetPassword deleteUser := scenario == "login_delete" if deleteUser { mutation = webRequest{method: "DELETE", path: apiPrefix + "/users/alice", token: adminToken, body: `{"confirm":"alice"}`} mutationOp, finalPassword = opUserDelete, testPassword } if scenario == "own_change_reset" { account = webRequest{method: "PUT", path: apiPrefix + "/account/password", token: token, body: `{"current":"secret-password","password":"own-new-password"}`} accountOp, accountStatus, rejected = opPasswordChange, http.StatusNoContent, http.StatusConflict } var response *httptest.ResponseRecorder if accountFirst { response, _ = it.race(t, account, mutation, accountStatus, http.StatusNoContent) } else { _, response = it.race(t, mutation, account, http.StatusNoContent, rejected) accountStatus = rejected } ctx := t.Context() stored, err := newUserStore(it.server.db, it.server.tables).UserByID(ctx, user.ID) if err != nil || stored.PasswordHash != fakeHash(finalPassword) || stored.DeletedAt.Valid != deleteUser || stored.LastLoginAt.Valid != (accountOp == opLogin && accountFirst) { t.Fatalf("unexpected winning account state: hash match %t, deleted %t, login %t, error %v", stored.PasswordHash == fakeHash(finalPassword), stored.DeletedAt.Valid, stored.LastLoginAt.Valid, err) } if n := it.database.count(t, it.server.tables.sql("SELECT COUNT(*) FROM {sessions} WHERE user_id = ?"), user.ID); n != 0 { t.Fatalf("the revoked user has %d surviving sessions", n) } cookies := response.Header().Values("Set-Cookie") if (len(cookies) == 1) != (accountOp == opLogin && accountFirst) { t.Fatalf("unexpected number of cookies: %d", len(cookies)) } a := it.audit(t, accountOp, accountStatus, user) m := it.audit(t, mutationOp, http.StatusNoContent, admin) if (a.ID < m.ID) != accountFirst || m.TargetUserID != (sql.NullInt64{Int64: user.ID, Valid: true}) { t.Fatalf("unexpected audit sequence or mutation target: %+v %+v", a, m) } if !accountFirst { want := msgInvalidLogin if accountOp == opPasswordChange { want = msgPasswordChanged } if a.Error.String != want { t.Fatalf("unexpected rejection audit: %+v", a) } } }) } } } func TestIntegrationAdminMutationAuthorizationRaces(t *testing.T) { for _, operation := range []string{opDelegationGrant, opDelegationRevoke, opUserPassword} { for _, actorOp := range []string{opUserRole, opUserDelete} { for _, writeFirst := range []bool{true, false} { t.Run(fmt.Sprintf("%s/%s/write_first_%t", operation, actorOp, writeFirst), func(t *testing.T) { it := newITHTTP(t) keeper := it.createUser(t, "keeper", roleAdmin) actor := it.createUser(t, "actor", roleAdmin) target := it.createUser(t, "target", roleUser) targetToken := it.token(t, target) write := webRequest{method: "PUT", path: apiPrefix + "/zones/" + testZone + "/users/target", token: it.token(t, actor)} delegations := newDelegationStore(it.server.db, it.server.tables) ctx := t.Context() if operation == opUserPassword { write.path = apiPrefix + "/users/target/password" write.body = `{"password":"target-new-password"}` } else { records := newRecordStore(it.server.db, it.server.tables) _, err := records.InsertRecord(ctx, recordRow{Zone: testZone, Name: "www", TTL: sql.NullInt64{Int64: 3600, Valid: true}, Content: sql.NullString{String: `{"ip":"192.0.2.1"}`, Valid: true}, RecordType: "A"}) if err != nil { t.Fatal(err) } if operation == opDelegationRevoke { write.method = "DELETE" if created, err := delegations.GrantDelegation(ctx, testZone, target.ID, keeper.ID, webNow); !created || err != nil { t.Fatalf("seed delegation: %t, %v", created, err) } } } changeActor := webRequest{method: "PUT", path: apiPrefix + "/users/actor/role", token: it.token(t, keeper), body: `{"role":"user"}`} if actorOp == opUserDelete { changeActor.method, changeActor.path, changeActor.body = "DELETE", apiPrefix+"/users/actor", `{"confirm":"actor"}` } writeStatus := http.StatusNoContent if writeFirst { it.race(t, write, changeActor, writeStatus, http.StatusNoContent) } else { writeStatus = http.StatusForbidden _, response := it.race(t, changeActor, write, http.StatusNoContent, writeStatus) if response.Body.String() != `{"error":"admin role required"}` { t.Fatalf("refusal body: %s", response.Body) } } guard := it.audit(t, actorOp, http.StatusNoContent, keeper) entry := it.audit(t, operation, writeStatus, actor) if (entry.ID < guard.ID) != writeFirst || entry.TargetUserID != (sql.NullInt64{Int64: target.ID, Valid: true}) || guard.TargetUserID != (sql.NullInt64{Int64: actor.ID, Valid: true}) { t.Fatalf("unexpected audit order or target: %+v %+v", entry, guard) } users := newUserStore(it.server.db, it.server.tables) storedActor, err := users.UserByID(ctx, actor.ID) deleted := actorOp == opUserDelete if err != nil || storedActor.DeletedAt.Valid != deleted || (storedActor.Role == roleAdmin) != deleted { t.Fatalf("actor status: role %s, deleted %t, error %v", storedActor.Role, storedActor.DeletedAt.Valid, err) } if operation == opUserPassword { stored, err := users.UserByID(ctx, target.ID) wantPassword, wantSessions := testPassword, 1 if writeFirst { wantPassword, wantSessions = "target-new-password", 0 } if err != nil || stored.PasswordHash != fakeHash(wantPassword) { t.Fatalf("target password has wrong state, error %v", err) } if n := it.database.count(t, it.server.tables.sql("SELECT COUNT(*) FROM {sessions} WHERE user_id = ?"), target.ID); n != wantSessions { t.Fatalf("target session count %d, want %d", n, wantSessions) } if !writeFirst && it.do(ctx, webRequest{method: "GET", path: apiPrefix + "/account", token: targetToken}).Code != http.StatusOK { t.Fatal("target session was revoked by refused password reset") } } else { exists, err := delegations.HasDelegation(ctx, testZone, target.ID) if err != nil || exists != (writeFirst == (operation == opDelegationGrant)) || entry.Zone.String != testZone { t.Fatalf("delegation state %t, audit zone %v, error %v", exists, entry.Zone, err) } } }) } } } } func TestIntegrationZoneCreationDelegationRace(t *testing.T) { for _, createFirst := range []bool{true, false} { t.Run(fmt.Sprintf("create_first_%t", createFirst), func(t *testing.T) { it := newITHTTP(t) creator := it.createUser(t, "creator", roleAdmin) grantor := it.createUser(t, "grantor", roleAdmin) grantee := it.createUser(t, "grantee", roleUser) zone := strings.ReplaceAll(it.database.name, "_", "-") + ".example.org." create := webRequest{method: "POST", path: apiPrefix + "/zones", token: it.token(t, creator), body: strings.Replace(zoneAPITestCreate, "Example.ORG", zone, 1)} grant := webRequest{method: "PUT", path: apiPrefix + "/zones/" + zone + "/users/grantee", token: it.token(t, grantor)} first, second, firstActor := create, grant, creator if !createFirst { first, second, firstActor = grant, create, grantor } ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) defer cancel() tables := it.server.tables gate, err := it.database.root.BeginTx(ctx, nil) if err != nil { t.Fatal(err) } defer gate.Rollback() if _, err := newUserStore(gate, tables).UserByIDForUpdate(ctx, firstActor.ID); err != nil { t.Fatal(err) } a := make(chan *httptest.ResponseRecorder, 1) b := make(chan *httptest.ResponseRecorder, 1) go func() { a <- it.do(ctx, first) }() it.waitForUserLock(t, ctx, a) go func() { b <- it.do(ctx, second) }() it.waitForLock(t, ctx, b, "zone row lock", func() (bool, error) { return it.database.rowLockWaiting(ctx, "webui_locks") }) if err := gate.Commit(); err != nil { t.Fatal(err) } grantStatus := http.StatusNoContent if createFirst { itHTTPResponse(t, ctx, a, http.StatusCreated) itHTTPResponse(t, ctx, b, grantStatus) } else { grantStatus = http.StatusNotFound response := itHTTPResponse(t, ctx, a, grantStatus) if response.Body.String() != `{"error":"zone not found"}` { t.Fatalf("grant before creation: %s", response.Body) } itHTTPResponse(t, ctx, b, http.StatusCreated) } if exists, err := newDelegationStore(it.server.db, tables).HasDelegation(ctx, zone, grantee.ID); err != nil || exists != createFirst { t.Fatalf("delegation exists = %t, want %t, error %v", exists, createFirst, err) } if rows, err := newRecordStore(it.server.db, tables).ZoneRows(ctx, zone); err != nil || len(rows) != 3 { t.Fatalf("created zone has %d records, want 3, error %v", len(rows), err) } if n := it.database.count(t, tables.sql("SELECT COUNT(*) FROM {audit}")); n != 2 { t.Fatalf("audit row count = %d, want 2", n) } created := it.audit(t, opZoneCreate, http.StatusCreated, creator) granted := it.audit(t, opDelegationGrant, grantStatus, grantor) auditZone := sql.NullString{String: zone, Valid: true} if created.Zone != auditZone || created.RecordID.Valid || created.TargetUserID.Valid || created.Before != nil || len(created.After) == 0 || granted.Zone != auditZone || granted.RecordID.Valid || granted.Before != nil { t.Fatalf("unexpected zone race audit: %+v %+v", created, granted) } if createFirst { var snapshot auditDelegationValue if err := json.Unmarshal(granted.After, &snapshot); err != nil || snapshot != (auditDelegationValue{Zone: zone, Username: grantee.Username}) || granted.TargetUserID != (sql.NullInt64{Int64: grantee.ID, Valid: true}) || granted.ID <= created.ID { t.Fatalf("unexpected successful grant audit: %+v, snapshot %+v, error %v", granted, snapshot, err) } } else if granted.TargetUserID.Valid || granted.Error.String != msgZoneNotFound { t.Fatalf("unexpected rejected grant audit: %+v", granted) } }) } } func TestIntegrationAdminsDemotingEachOther(t *testing.T) { it := newITHTTP(t) alice := it.createUser(t, "alice", roleAdmin) bob := it.createUser(t, "bob", roleAdmin) demote := func(actor, target userRow) webRequest { return webRequest{method: "PUT", path: apiPrefix + "/users/" + target.Username + "/role", token: it.token(t, actor), body: `{"role":"user"}`} } _, refused := it.race(t, demote(alice, bob), demote(bob, alice), http.StatusNoContent, http.StatusForbidden) if refused.Body.String() != `{"error":"admin role required"}` { t.Fatalf("refused demotion: %s", refused.Body) } ctx, tables := t.Context(), it.server.tables if n := it.database.count(t, tables.sql("SELECT COUNT(*) FROM {users} WHERE role = 'admin' AND deleted_at IS NULL AND id = ?"), alice.ID); n != 1 { t.Fatal("the first actor did not remain an active admin") } stored, err := newUserStore(it.server.db, tables).UserByID(ctx, bob.ID) if err != nil || stored.Role != roleUser || stored.DeletedAt.Valid { t.Fatalf("the second actor was not demoted to user: role %s, deleted %t, error %v", stored.Role, stored.DeletedAt.Valid, err) } audit := newAuditStore(it.server.db, tables) rows, err := audit.LatestAudit(ctx, 3) if err != nil || len(rows) != 2 { t.Fatalf("mutual demotion audit: got %d rows, want 2, error %v", len(rows), err) } won, lost := rows[0], rows[1] assertITHTTPAudit(t, won, opUserRole, http.StatusNoContent, alice) assertITHTTPAudit(t, lost, opUserRole, http.StatusForbidden, bob) if won.TargetUserID != (sql.NullInt64{Int64: bob.ID, Valid: true}) || lost.TargetUserID != (sql.NullInt64{Int64: alice.ID, Valid: true}) || won.Zone.Valid || lost.Zone.Valid || won.RecordID.Valid || lost.RecordID.Valid || lost.Error.String != msgAdminRequired { t.Fatalf("unexpected mutual demotion audit: %+v %+v", won, lost) } for _, snapshot := range []struct { data []byte want auditUserValue }{{won.Before, auditUserValueOf(bob)}, {won.After, auditUserValueOf(stored)}} { var got auditUserValue if err := json.Unmarshal(snapshot.data, &got); err != nil || got != snapshot.want { t.Fatalf("demotion snapshot = %+v, want %+v, error %v", got, snapshot.want, err) } } } func TestIntegrationUserCreateAuditRollback(t *testing.T) { it := newITHTTP(t) admin := it.createUser(t, "admin", roleAdmin) tn := it.server.tables it.database.rootExec(t, tn.sql("CREATE TRIGGER "+qualifiedIdent(it.database.webui, "fail_create_audit")+" BEFORE INSERT ON {audit} FOR EACH ROW "+ "BEGIN IF NEW.operation = 'user_create' AND NEW.status = 201 THEN "+ "SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'forced success audit failure'; END IF; END")) response := it.do(t.Context(), webRequest{method: "POST", path: apiPrefix + "/users", token: it.token(t, admin), body: `{"username":"newbie","role":"user","password":"long-enough-password"}`}) if response.Code != http.StatusInternalServerError || response.Body.String() != `{"error":"internal error"}` { t.Fatalf("user creation: %d %s", response.Code, response.Body) } if n := it.database.count(t, tn.sql("SELECT COUNT(*) FROM {users} WHERE username = 'newbie'")); n != 0 { t.Fatal("user creation survived a failed audit insert") } entry := it.audit(t, opUserCreate, http.StatusInternalServerError, admin) if entry.TargetUserID.Valid || entry.Error.String != msgInternalError { t.Fatalf("failure audit retained rolled-back data: %+v", entry) } }