feat(generation): resume manual summary jobs

This commit is contained in:
2026-11-23 17:42:30 +01:00
parent 6afe2bdee0
commit 61cc906e0a
22 changed files with 851 additions and 173 deletions

View File

@ -3,108 +3,55 @@ package handlers_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/api"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/generation"
"github.com/tradarr/backend/internal/models"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
const generationHTTPSecret = "ticket-7-http-contract-secret"
const generationHTTPSecret = "ticket-27-http-contract-secret"
type fakeGenerationUseCase struct {
result generation.Result
err error
userID string
calls int
type fakeJobStarter struct{ user string }
func (f *fakeJobStarter) Start(_ context.Context, user string) (models.GenerationJob, error) {
f.user = user
return models.GenerationJob{ID: "job-id", Status: "running"}, nil
}
func (f *fakeGenerationUseCase) Generate(_ context.Context, userID string) (generation.Result, error) {
f.calls++
f.userID = userID
return f.result, f.err
}
func TestGenerateSummaryHTTPUsesJWTUserAndReturnsAggregateOnlyEnvelopes(t *testing.T) {
previousMode := gin.Mode()
gin.SetMode(gin.TestMode)
t.Cleanup(func() { gin.SetMode(previousMode) })
token, err := auth.GenerateToken("jwt-owner", "owner@example.test", "user", generationHTTPSecret)
if err != nil {
func TestGenerateSummaryHTTPAcceptsJobUsingJWTUser(t *testing.T) {
h := handlers.New(nil, &config.Config{JWTSecret: generationHTTPSecret}, nil, nil, nil, nil)
starter := &fakeJobStarter{}
h.SetGenerationJobs(starter)
router := api.SetupRouter(h, generationHTTPSecret)
token, _ := auth.GenerateToken("jwt-owner", "owner@example.test", "user", generationHTTPSecret)
request := httptest.NewRequest(http.MethodPost, "/api/summaries/generate", strings.NewReader(`{"user_id":"attacker","content":"candidate-secret"}`))
request.Header.Set("Authorization", "Bearer "+token)
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != 202 || starter.user != "jwt-owner" {
t.Fatalf("status=%d user=%s body=%s", response.Code, starter.user, response.Body)
}
if response.Header().Get("Location") != "/api/summaries/generation-jobs/job-id" {
t.Fatal("missing poll location")
}
var envelope struct {
Data models.GenerationJob `json:"data"`
}
if err := json.Unmarshal(response.Body.Bytes(), &envelope); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
status string
wantStatus int
wantSummary bool
}{
{name: "success", status: "succeeded", wantStatus: http.StatusCreated, wantSummary: true},
{name: "partial", status: "partial", wantStatus: http.StatusCreated, wantSummary: true},
{name: "no results", status: "no_results", wantStatus: http.StatusOK, wantSummary: false},
{name: "provider failure", status: "failed", wantStatus: http.StatusBadGateway, wantSummary: false},
if envelope.Data.Status != "running" || strings.Contains(response.Body.String(), "candidate-secret") {
t.Fatal(response.Body)
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fake := &fakeGenerationUseCase{result: generation.Result{
Outcome: generation.GenerationOutcome{
ID: "outcome-aggregate-id", Status: tt.status, Language: "fr", RankingMode: "title",
TotalCandidates: 7, ContentFallbacks: 1, LayaSelected: 2,
Selected: 2, SourceStats: []generation.SourceStat{{SourceID: "source-aggregate-id", SourceType: "fixture", Status: "ok", Candidates: 7, LayaSelected: 2}},
},
}}
if tt.wantSummary {
fake.result.Summary = &models.Summary{ID: "summary-id", UserID: "jwt-owner", Content: "Safe synthesized market summary"}
}
h := handlers.New(nil, &config.Config{JWTSecret: generationHTTPSecret}, nil, nil, ai.NewPipeline(nil, nil), nil)
h.SetGenerationUseCase(fake)
router := api.SetupRouter(h, generationHTTPSecret)
body := `{"user_id":"attacker-user","title":"candidate-title-secret","url":"https://candidate.invalid/private","content":"candidate-content-secret","candidate_id":"candidate-id-secret"}`
request := httptest.NewRequest(http.MethodPost, "/api/summaries/generate", strings.NewReader(body))
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != tt.wantStatus {
t.Fatalf("POST /api/summaries/generate status=%d, want %d: %s", response.Code, tt.wantStatus, response.Body.String())
}
if fake.calls != 1 || fake.userID != "jwt-owner" {
t.Fatalf("use case identity came from client input: calls=%d userID=%q", fake.calls, fake.userID)
}
var envelope struct {
Data struct {
Summary *models.Summary `json:"summary"`
Outcome generation.GenerationOutcome `json:"outcome"`
} `json:"data"`
}
if err := json.Unmarshal(response.Body.Bytes(), &envelope); err != nil {
t.Fatalf("decode generation envelope: %v; body=%s", err, response.Body.String())
}
if (envelope.Data.Summary != nil) != tt.wantSummary || envelope.Data.Outcome.Status != tt.status {
t.Fatalf("unexpected summary/outcome envelope: %+v", envelope.Data)
}
for _, articleValue := range []string{"candidate-title-secret", "https://candidate.invalid/private", "candidate-content-secret", "candidate-id-secret"} {
if strings.Contains(response.Body.String(), articleValue) {
t.Errorf("article candidate data leaked in response: %q", articleValue)
}
}
outcomeJSON, err := json.Marshal(envelope.Data.Outcome)
if err != nil {
t.Fatal(err)
}
for _, articleField := range []string{`"title"`, `"url"`, `"content"`, `"prompt"`, `"candidate_id"`} {
if strings.Contains(string(outcomeJSON), articleField+":") {
t.Errorf("article field %s leaked into outcome: %s", articleField, outcomeJSON)
}
}
})
for _, path := range []string{"/api/summaries/generation-jobs/recent", "/api/summaries/generation-jobs/id"} {
response = httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest("GET", path, nil))
if response.Code != 401 {
t.Fatalf("%s: %d", path, response.Code)
}
}
}