fix: close record repair and verification gaps
This commit is contained in:
1 parent
9251c85fd8
commit
adff599e08
27 files changed
+787
-153
No files matched your search
+164
-23
@@ -8,6 +8,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
@@ -64,6 +65,9 @@ func (it itHTTP) do(ctx context.Context, req webRequest) *httptest.ResponseRecor
|
||||
} 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))
|
||||
}
|
||||
@@ -79,14 +83,19 @@ func (it itHTTP) audit(t *testing.T, operation string, status int, actor userRow
|
||||
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 ||
|
||||
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)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
type itCommitGateKey struct{}
|
||||
@@ -141,42 +150,53 @@ func (it itHTTP) race(t *testing.T, first, second webRequest, firstStatus, secon
|
||||
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", "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")
|
||||
}
|
||||
|
||||
func (it itHTTP) waitForLock(t *testing.T, ctx context.Context, result <-chan *httptest.ResponseRecorder, lock, query string, args ...any) {
|
||||
t.Helper()
|
||||
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)
|
||||
err := it.database.root.QueryRowContext(ctx, query, args...).Scan(&waiting)
|
||||
if err != nil {
|
||||
t.Fatalf("observe user lock: %v", err)
|
||||
t.Fatalf("observe %s: %v", lock, err)
|
||||
}
|
||||
if waiting {
|
||||
break
|
||||
return
|
||||
}
|
||||
select {
|
||||
case w := <-b:
|
||||
t.Fatalf("second request did not wait on the users table: %d %s", w.Code, w.Body)
|
||||
case w := <-result:
|
||||
t.Fatalf("request did not wait on %s: %d %s", lock, w.Code, w.Body)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("second request did not reach a user row lock")
|
||||
t.Fatalf("request did not reach %s", 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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
return receive(a, firstStatus), receive(b, secondStatus)
|
||||
}
|
||||
|
||||
func TestIntegrationPasswordRaces(t *testing.T) {
|
||||
@@ -326,6 +346,127 @@ func TestIntegrationAdminMutationAuthorizationRaces(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
// Both handlers acquire the zone lock before checking the actor's row.
|
||||
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 named lock", "SELECT EXISTS (SELECT 1 FROM performance_schema.metadata_locks "+
|
||||
"WHERE OBJECT_TYPE = 'USER LEVEL LOCK' AND OBJECT_NAME = ? AND LOCK_STATUS = 'PENDING')", tables.zoneLockName(zone))
|
||||
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)
|
||||
|
||||
Reference in new issue
Block a user