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:
@ -125,14 +125,19 @@ func (p *Pipeline) GenerateForAll(ctx context.Context) error {
|
||||
}
|
||||
|
||||
// GenerateReportAsync crée le rapport en DB (status=generating) et lance la génération en arrière-plan.
|
||||
func (p *Pipeline) GenerateReportAsync(reportID, excerpt, question string, mgr *ReportManager) {
|
||||
func (p *Pipeline) GenerateReportAsync(ownerID, reportID, excerpt, question string, mgr *ReportManager) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
||||
mgr.Register(reportID, cancel)
|
||||
if err := mgr.RegisterForReport(ownerID, reportID, reportID, cancel, func() (bool, error) { report, err := p.repo.GetReport(reportID, ownerID); return report != nil, err }); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
defer cancel()
|
||||
defer mgr.Remove(reportID)
|
||||
defer mgr.Remove(ownerID, reportID)
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
answer, err := p.callProviderForReport(ctx, excerpt, question)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
@ -164,12 +169,20 @@ func (p *Pipeline) callProviderForReport(ctx context.Context, excerpt, question
|
||||
// history contient tous les messages précédents (user + assistant), dans l'ordre.
|
||||
func (p *Pipeline) GenerateReportMessageAsync(messageID string, report *models.Report, history []models.ReportMessage, mgr *ReportManager) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
||||
mgr.Register(messageID, cancel)
|
||||
if err := mgr.RegisterForReport(report.UserID, report.ID, messageID, cancel, func() (bool, error) {
|
||||
current, err := p.repo.GetReport(report.ID, report.UserID)
|
||||
return current != nil, err
|
||||
}); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
defer cancel()
|
||||
defer mgr.Remove(messageID)
|
||||
defer mgr.Remove(report.UserID, messageID)
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
answer, err := p.callProviderForConversation(ctx, report, history)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
|
||||
@ -5,33 +5,102 @@ import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
// ReportManager tracks in-flight report goroutines so they can be cancelled.
|
||||
type operationKey struct{ owner, id string }
|
||||
type reportOperation struct {
|
||||
cancel context.CancelFunc
|
||||
report string
|
||||
}
|
||||
type reportGate struct {
|
||||
mu sync.Mutex
|
||||
refs int
|
||||
}
|
||||
type ReportManager struct {
|
||||
mu sync.Mutex
|
||||
cancels map[string]context.CancelFunc
|
||||
cancels map[operationKey]reportOperation
|
||||
gates map[operationKey]*reportGate
|
||||
}
|
||||
|
||||
func NewReportManager() *ReportManager {
|
||||
return &ReportManager{cancels: make(map[string]context.CancelFunc)}
|
||||
return &ReportManager{cancels: map[operationKey]reportOperation{}, gates: map[operationKey]*reportGate{}}
|
||||
}
|
||||
|
||||
func (m *ReportManager) Register(id string, cancel context.CancelFunc) {
|
||||
// WithReport serializes existence checks/registration with confirmed deletion.
|
||||
func (m *ReportManager) WithReport(owner, report string, fn func() error) error {
|
||||
key := operationKey{owner, report}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.cancels[id] = cancel
|
||||
g := m.gates[key]
|
||||
if g == nil {
|
||||
g = &reportGate{}
|
||||
m.gates[key] = g
|
||||
}
|
||||
g.refs++
|
||||
m.mu.Unlock()
|
||||
g.mu.Lock()
|
||||
defer func() {
|
||||
g.mu.Unlock()
|
||||
m.mu.Lock()
|
||||
g.refs--
|
||||
if g.refs == 0 {
|
||||
delete(m.gates, key)
|
||||
}
|
||||
m.mu.Unlock()
|
||||
}()
|
||||
return fn()
|
||||
}
|
||||
|
||||
func (m *ReportManager) Cancel(id string) {
|
||||
func (m *ReportManager) Register(owner, operation string, cancel context.CancelFunc) {
|
||||
m.register(owner, operation, operation, cancel)
|
||||
}
|
||||
func (m *ReportManager) register(owner, report, operation string, cancel context.CancelFunc) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if cancel, ok := m.cancels[id]; ok {
|
||||
cancel()
|
||||
delete(m.cancels, id)
|
||||
old, exists := m.cancels[operationKey{owner, operation}]
|
||||
m.cancels[operationKey{owner, operation}] = reportOperation{cancel, report}
|
||||
m.mu.Unlock()
|
||||
if exists {
|
||||
old.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
func (m *ReportManager) Remove(id string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.cancels, id)
|
||||
func (m *ReportManager) RegisterForReport(owner, report, operation string, cancel context.CancelFunc, exists func() (bool, error)) error {
|
||||
err := m.WithReport(owner, report, func() error {
|
||||
ok, err := exists()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return context.Canceled
|
||||
}
|
||||
m.register(owner, report, operation, cancel)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
}
|
||||
return err
|
||||
}
|
||||
func (m *ReportManager) Cancel(owner, operation string) {
|
||||
m.mu.Lock()
|
||||
work, ok := m.cancels[operationKey{owner, operation}]
|
||||
delete(m.cancels, operationKey{owner, operation})
|
||||
m.mu.Unlock()
|
||||
if ok {
|
||||
work.cancel()
|
||||
}
|
||||
}
|
||||
func (m *ReportManager) CancelReport(owner, report string) {
|
||||
callbacks := []context.CancelFunc{}
|
||||
m.mu.Lock()
|
||||
for key, work := range m.cancels {
|
||||
if key.owner == owner && work.report == report {
|
||||
callbacks = append(callbacks, work.cancel)
|
||||
delete(m.cancels, key)
|
||||
}
|
||||
}
|
||||
m.mu.Unlock()
|
||||
for _, cancel := range callbacks {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
func (m *ReportManager) Remove(owner, operation string) {
|
||||
m.mu.Lock()
|
||||
delete(m.cancels, operationKey{owner, operation})
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
60
backend/internal/ai/report_manager_lifecycle_test.go
Normal file
60
backend/internal/ai/report_manager_lifecycle_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
92
backend/internal/ai/report_manager_security_ticket9_test.go
Normal file
92
backend/internal/ai/report_manager_security_ticket9_test.go
Normal file
@ -0,0 +1,92 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The owner is part of the work identity: a report/message identifier alone
|
||||
// must never select another tenant's cancellation function.
|
||||
type ownerScopedReportManager interface {
|
||||
Register(ownerID, operationID string, cancel context.CancelFunc)
|
||||
Cancel(ownerID, operationID string)
|
||||
Remove(ownerID, operationID string)
|
||||
}
|
||||
|
||||
func scopedManager(t *testing.T) ownerScopedReportManager {
|
||||
t.Helper()
|
||||
manager, ok := any(NewReportManager()).(ownerScopedReportManager)
|
||||
if !ok {
|
||||
t.Fatal("ReportManager has no owner-scoped Register/Cancel/Remove contract")
|
||||
}
|
||||
return manager
|
||||
}
|
||||
|
||||
func TestReportManagerScopesEqualOperationIDsByOwner(t *testing.T) {
|
||||
manager := scopedManager(t)
|
||||
var cancelledA, cancelledB atomic.Bool
|
||||
manager.Register("owner-a", "same-report-id", func() { cancelledA.Store(true) })
|
||||
manager.Register("owner-b", "same-report-id", func() { cancelledB.Store(true) })
|
||||
|
||||
manager.Cancel("owner-a", "same-report-id")
|
||||
if !cancelledA.Load() {
|
||||
t.Fatal("cancel for owner-a did not cancel owner-a work")
|
||||
}
|
||||
if cancelledB.Load() {
|
||||
t.Fatal("cancel for owner-a cancelled owner-b work with the same operation ID")
|
||||
}
|
||||
manager.Cancel("owner-b", "same-report-id")
|
||||
if !cancelledB.Load() {
|
||||
t.Fatal("cancel for owner-b did not cancel owner-b work")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportManagerConcurrentOwnerScopedLifecycle(t *testing.T) {
|
||||
manager := scopedManager(t)
|
||||
var cancelledA, cancelledB atomic.Int64
|
||||
var wg sync.WaitGroup
|
||||
for _, owner := range []string{"owner-a", "owner-b"} {
|
||||
owner := owner
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for range 250 {
|
||||
cancel := func() {
|
||||
if owner == "owner-a" {
|
||||
cancelledA.Add(1)
|
||||
} else {
|
||||
cancelledB.Add(1)
|
||||
}
|
||||
}
|
||||
manager.Register(owner, "same-report-id", cancel)
|
||||
manager.Cancel(owner, "same-report-id")
|
||||
manager.Remove(owner, "same-report-id")
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if cancelledA.Load() == 0 || cancelledB.Load() == 0 {
|
||||
t.Fatalf("both owners must complete cancellation; owner-a=%d owner-b=%d", cancelledA.Load(), cancelledB.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// Exercise the current manager's mutex under the race detector even before its
|
||||
// owner-aware API exists; tenant-isolation assertions live above.
|
||||
func TestReportManagerConcurrentRegisterCancelRemoveIsRaceSafe(t *testing.T) {
|
||||
manager := NewReportManager()
|
||||
var wg sync.WaitGroup
|
||||
for range 8 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for range 250 {
|
||||
manager.Register("owner", "shared-id", func() {})
|
||||
manager.Cancel("owner", "shared-id")
|
||||
manager.Remove("owner", "shared-id")
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
Reference in New Issue
Block a user