Files
coredns-web-ui/integration_http_race_test.go
T
bryanpedini 53444bec7a test(ui): avoid a literal em dash in the em dash check
- test(ui): avoid a literal em dash in the em dash check
- fix(cli): accept any positive int64 audit count and share the last active admin rule
- fix(api): limit audit before_id to 2^53-1
- fix(api): audit unmatched api requests, bound every request body and record audit write failures
- fix(ui): recheck the account in the login transaction and require existing zones on zone pages
- fix(api): recheck the acting admin and the stored password hash in change transactions
- fix(db): keep committed outcomes on lock release failure, narrow the records contract and trace sql statements
- fix(db): make the initial migration restartable and verify the application schema
- fix(auth): never move last_seen_at backwards on concurrent session touches
- test(api): cover lock release failure after commit and handler tracing without secrets
- fix(test): redact credentials from mysql setup errors
- fix(audit): retain addressed objects on admin refusals
- test(db): cover migration restarts and records contract ranges in mysql
- test(api): verify account races and audit rollback in mysql
- fix(auth): reject password changes after account deletion
- docs: document unknown api audit entries
- fix(audit): bound failure retries and redact sensitive sql parameters
- fix(test): isolate docker resources and cover image cli commands
- test(auth): expect unauthorized after an account deletion race
- fix(db): verify application column widths and foreign keys
2026-11-19 15:46:12 +01:00

349 lines
14 KiB
Go

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
//go:build integration
package main
import (
"context"
"database/sql"
"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")
}
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]
if !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)
}
return 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) }()
tick := time.NewTicker(20 * time.Millisecond)
defer tick.Stop()
for {
var waiting bool
err := it.database.root.QueryRowContext(ctx, "SELECT EXISTS (SELECT 1 FROM performance_schema.data_lock_waits w "+
"JOIN performance_schema.data_locks l ON l.ENGINE = w.ENGINE AND l.ENGINE_LOCK_ID = w.REQUESTING_ENGINE_LOCK_ID "+
"WHERE l.OBJECT_SCHEMA = ? AND l.OBJECT_NAME = ?)",
it.database.name, it.database.prefix+"webui_users").Scan(&waiting)
if err != nil {
t.Fatalf("observe user lock: %v", err)
}
if waiting {
break
}
select {
case w := <-b:
t.Fatalf("second request did not wait on the users table: %d %s", w.Code, w.Body)
case <-ctx.Done():
t.Fatal("second request did not reach a user row lock")
case <-tick.C:
}
}
close(gate.release)
receive := func(ch <-chan *httptest.ResponseRecorder, status int) *httptest.ResponseRecorder {
select {
case w := <-ch:
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
}
}
return receive(a, firstStatus), receive(b, secondStatus)
}
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 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 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)
}
}