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

@ -1,7 +1,9 @@
package handlers
import (
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/crypto"
"github.com/tradarr/backend/internal/generation"
@ -41,3 +43,5 @@ func New(
}
func (h *Handler) SetGenerationUseCase(uc generation.UseCase) { h.generationUseCase = uc }
func (h *Handler) AdminOnly() gin.HandlerFunc { return auth.AdminOnly(h.repo) }

View File

@ -0,0 +1,169 @@
package handlers
import (
"context"
"database/sql"
"fmt"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/lib/pq"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/models"
)
const (
ticket9ReportID = "00000000-0000-0000-0000-000000000911"
ticket9OwnerA = "00000000-0000-0000-0000-000000000901"
ticket9OwnerB = "00000000-0000-0000-0000-000000000902"
)
func TestDeleteForeignReportReturnsNotFoundWithoutCancellingPostgres(t *testing.T) {
previousMode := gin.Mode()
gin.SetMode(gin.TestMode)
t.Cleanup(func() { gin.SetMode(previousMode) })
db := ticket9ReportDB(t)
seedTicket9Report(t, db, ticket9OwnerA)
h := New(models.NewRepository(db), &config.Config{}, nil, nil, nil, nil)
cancelCalled := false
h.reportManager.Register(ticket9OwnerA, ticket9ReportID, func() { cancelCalled = true })
response := invokeTicket9DeleteReport(h, ticket9OwnerB)
if response.Code != http.StatusNotFound {
t.Errorf("DELETE foreign report: got %d, want 404", response.Code)
}
if cancelCalled {
t.Error("DELETE foreign report invoked ReportManager.Cancel")
}
if count := ticket9ReportCount(t, db); count != 1 {
t.Errorf("foreign report row count=%d, want 1", count)
}
}
func TestDeleteOwnedReportCancelsOnlyAfterConfirmedDeletePostgres(t *testing.T) {
previousMode := gin.Mode()
gin.SetMode(gin.TestMode)
t.Cleanup(func() { gin.SetMode(previousMode) })
db := ticket9ReportDB(t)
seedTicket9Report(t, db, ticket9OwnerA)
h := New(models.NewRepository(db), &config.Config{}, nil, nil, nil, nil)
cancelCalled := false
reportsAtCancel := -1
h.reportManager.Register(ticket9OwnerA, ticket9ReportID, func() {
cancelCalled = true
if err := db.QueryRow(`SELECT COUNT(*) FROM reports WHERE id=$1`, ticket9ReportID).Scan(&reportsAtCancel); err != nil {
t.Errorf("count report at cancellation time: %v", err)
}
})
response := invokeTicket9DeleteReport(h, ticket9OwnerA)
if response.Code != http.StatusNoContent {
t.Errorf("DELETE owned report: got %d, want 204", response.Code)
}
if !cancelCalled {
t.Error("DELETE owned report did not cancel its pending report work")
}
if reportsAtCancel != 0 {
t.Errorf("ReportManager.Cancel ran before deletion was confirmed: rows at cancel=%d, want 0", reportsAtCancel)
}
if count := ticket9ReportCount(t, db); count != 0 {
t.Errorf("owned report row count after delete=%d, want 0", count)
}
}
func invokeTicket9DeleteReport(h *Handler, userID string) *httptest.ResponseRecorder {
response := httptest.NewRecorder()
c, _ := gin.CreateTestContext(response)
c.Request = httptest.NewRequest(http.MethodDelete, "/api/reports/"+ticket9ReportID, nil)
c.Params = gin.Params{{Key: "id", Value: ticket9ReportID}}
c.Set("userID", userID)
h.DeleteReport(c)
c.Writer.WriteHeaderNow()
return response
}
func seedTicket9Report(t *testing.T, db *sql.DB, userID string) {
t.Helper()
if _, err := db.Exec(`INSERT INTO reports (id,user_id,summary_id,context_excerpt,question,answer,status,error_msg) VALUES ($1,$2,NULL,'excerpt','question','','generating','')`, ticket9ReportID, userID); err != nil {
t.Fatal(err)
}
}
func ticket9ReportCount(t *testing.T, db *sql.DB) int {
t.Helper()
var count int
if err := db.QueryRow(`SELECT COUNT(*) FROM reports WHERE id=$1`, ticket9ReportID).Scan(&count); err != nil {
t.Fatal(err)
}
return count
}
func ticket9ReportDB(t *testing.T) *sql.DB {
t.Helper()
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
if os.Getenv("TEST_DATABASE_REQUIRED") == "1" {
t.Fatal("TEST_DATABASE_REQUIRED=1 but TEST_DATABASE_URL is empty")
}
t.Skip("TEST_DATABASE_URL absent: isolated PostgreSQL required")
}
db, err := sql.Open("postgres", dsn)
if err != nil {
t.Fatal(err)
}
db.SetMaxOpenConns(1)
schema := fmt.Sprintf("ticket9_reports_%d", time.Now().UnixNano())
if _, err = db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil {
db.Close()
t.Fatal(err)
}
if _, err = db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
_, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
db.Close()
t.Fatal(err)
}
if _, err = db.Exec(`CREATE TABLE reports (id UUID PRIMARY KEY, user_id UUID NOT NULL, summary_id UUID, context_excerpt TEXT NOT NULL, question TEXT NOT NULL, answer TEXT NOT NULL, status TEXT NOT NULL, error_msg TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
_ = db.Close()
})
return db
}
func TestDeleteReportCancelsMessagesAndRejectsLateRegistrationPostgres(t *testing.T) {
db := ticket9ReportDB(t)
seedTicket9Report(t, db, ticket9OwnerA)
repo := models.NewRepository(db)
h := New(repo, &config.Config{}, nil, nil, nil, nil)
reportCtx, reportCancel := context.WithCancel(context.Background())
messageCtx, messageCancel := context.WithCancel(context.Background())
otherCtx, otherCancel := context.WithCancel(context.Background())
defer otherCancel()
exists := func() (bool, error) {
report, err := repo.GetReport(ticket9ReportID, ticket9OwnerA)
return report != nil, err
}
if err := h.reportManager.RegisterForReport(ticket9OwnerA, ticket9ReportID, ticket9ReportID, reportCancel, exists); err != nil {
t.Fatal(err)
}
if err := h.reportManager.RegisterForReport(ticket9OwnerA, ticket9ReportID, "message", messageCancel, exists); err != nil {
t.Fatal(err)
}
h.reportManager.Register(ticket9OwnerB, "message", otherCancel)
if response := invokeTicket9DeleteReport(h, ticket9OwnerA); response.Code != http.StatusNoContent {
t.Fatalf("delete status=%d", response.Code)
}
if reportCtx.Err() == nil || messageCtx.Err() == nil || otherCtx.Err() != nil {
t.Fatal("incorrect report/message cancellation scope")
}
lateCtx, lateCancel := context.WithCancel(context.Background())
if err := h.reportManager.RegisterForReport(ticket9OwnerA, ticket9ReportID, "late-message", lateCancel, exists); err == nil || lateCtx.Err() == nil {
t.Fatal("orphan task accepted after deletion")
}
}

View File

@ -1,6 +1,8 @@
package handlers
import (
"database/sql"
"errors"
"net/http"
"strings"
@ -50,7 +52,7 @@ func (h *Handler) CreateReport(c *gin.Context) {
}
// Lancer la génération en arrière-plan
h.pipeline.GenerateReportAsync(report.ID, excerpt, req.Question, h.reportManager)
h.pipeline.GenerateReportAsync(userID, report.ID, excerpt, req.Question, h.reportManager)
c.JSON(http.StatusCreated, report)
}
@ -68,10 +70,19 @@ func (h *Handler) ListReports(c *gin.Context) {
func (h *Handler) DeleteReport(c *gin.Context) {
userID := c.GetString("userID")
id := c.Param("id")
// Annuler la goroutine si elle tourne encore
h.reportManager.Cancel(id)
if err := h.repo.DeleteReport(id, userID); err != nil {
httputil.InternalError(c, err)
err := h.reportManager.WithReport(userID, id, func() error {
if err := h.repo.DeleteReport(id, userID); err != nil {
return err
}
h.reportManager.CancelReport(userID, id)
return nil
})
if errors.Is(err, sql.ErrNoRows) {
httputil.NotFound(c)
return
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "report deletion failed"})
return
}
c.Status(http.StatusNoContent)