fix(security): synchronize report lifecycle and current roles

Revalidate admin roles from the database and serialize report generation registration with owner-scoped deletion.

Refs #9

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 21:35:38 +01:00
parent 0ebc531124
commit 609dbff7c1
16 changed files with 668 additions and 35 deletions

View File

@ -0,0 +1,60 @@
package ai
import (
"context"
"sync"
"testing"
)
func TestRegisterDeleteRaceLeavesNoOrphanOperations(t *testing.T) {
for range 100 {
manager := NewReportManager()
exists := true // guarded exclusively by WithReport, including the existence callback
reportCtx, reportCancel := context.WithCancel(context.Background())
messageCtx, messageCancel := context.WithCancel(context.Background())
otherCtx, otherCancel := context.WithCancel(context.Background())
defer otherCancel()
manager.Register("other-owner", "message", otherCancel)
var wg sync.WaitGroup
wg.Add(3)
go func() {
defer wg.Done()
_ = manager.RegisterForReport("owner", "report", "report", reportCancel, func() (bool, error) { return exists, nil })
}()
go func() {
defer wg.Done()
_ = manager.RegisterForReport("owner", "report", "message", messageCancel, func() (bool, error) { return exists, nil })
}()
go func() {
defer wg.Done()
_ = manager.WithReport("owner", "report", func() error { exists = false; manager.CancelReport("owner", "report"); return nil })
}()
wg.Wait()
if reportCtx.Err() == nil || messageCtx.Err() == nil {
t.Fatal("report/message work survived confirmed deletion")
}
if otherCtx.Err() != nil {
t.Fatal("another owner was cancelled")
}
manager.mu.Lock()
count := len(manager.cancels)
gates := len(manager.gates)
manager.mu.Unlock()
if count != 1 || gates != 0 {
t.Fatalf("orphan operations=%d gates=%d", count, gates)
}
}
}
func TestRegistrationChecksExistenceAndCancelsOnLookupFailure(t *testing.T) {
manager := NewReportManager()
ctx, cancel := context.WithCancel(context.Background())
err := manager.RegisterForReport("owner", "deleted-report", "message", cancel, func() (bool, error) { return false, nil })
if err == nil || ctx.Err() == nil {
t.Fatal("deleted report registration accepted")
}
manager.mu.Lock()
defer manager.mu.Unlock()
if len(manager.cancels) != 0 {
t.Fatal("deleted report operation registered")
}
}