feat(ai): add personal summary models and retire Q&A
Add an admin-managed provider model catalog with per-user summary selection, migration backfill, and generation snapshots. Retire report creation and messaging while preserving owner-scoped history. Refs #15 #16 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
142
backend/internal/api/ai_roles_ticket14_postgres_test.go
Normal file
142
backend/internal/api/ai_roles_ticket14_postgres_test.go
Normal file
@ -0,0 +1,142 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lib/pq"
|
||||
"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/models"
|
||||
)
|
||||
|
||||
func TestAdminAIRoleContractIsSummaryOnlyAndPreservesSummaryProviderResolutionPostgres(t *testing.T) {
|
||||
db := ticket14DB(t)
|
||||
for _, q := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,email TEXT NOT NULL,password_hash TEXT NOT NULL,role TEXT NOT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`INSERT INTO users(id,email,password_hash,role) VALUES('00000000-0000-0000-0000-000000000014','admin@example.test','hash','admin')`,
|
||||
`CREATE TABLE settings(key TEXT PRIMARY KEY,value TEXT NOT NULL)`,
|
||||
`CREATE TABLE ai_providers(id UUID PRIMARY KEY,name TEXT NOT NULL,api_key_encrypted TEXT NOT NULL DEFAULT '',model TEXT NOT NULL,endpoint TEXT NOT NULL DEFAULT '',is_active BOOLEAN NOT NULL DEFAULT FALSE,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`INSERT INTO ai_providers(id,name,model,is_active) VALUES('00000000-0000-0000-0000-000000000141','ollama','active-model',true),('00000000-0000-0000-0000-000000000142','openai','provider-model',false)`,
|
||||
`INSERT INTO settings(key,value) VALUES('ai_role_summary_provider','00000000-0000-0000-0000-000000000142'),('ai_role_summary_model','summary-override'),('ai_role_filter_provider','legacy-filter-provider'),('ai_role_filter_model','legacy-filter-model'),('ai_role_report_provider','legacy-report-provider'),('ai_role_report_model','legacy-report-model')`,
|
||||
} {
|
||||
if _, err := db.Exec(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
const secret = "ticket14-admin-ai-secret"
|
||||
token, err := auth.GenerateToken("00000000-0000-0000-0000-000000000014", "admin@example.test", "admin", secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := models.NewRepository(db)
|
||||
router := api.SetupRouter(handlers.New(repo, &config.Config{JWTSecret: secret}, nil, nil, nil, nil), secret)
|
||||
request := func(method, path, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
res := httptest.NewRecorder()
|
||||
router.ServeHTTP(res, req)
|
||||
return res
|
||||
}
|
||||
got := request(http.MethodGet, "/api/admin/ai-roles", "")
|
||||
if got.Code != http.StatusOK {
|
||||
t.Fatalf("GET ai-roles status=%d body=%s", got.Code, got.Body.String())
|
||||
}
|
||||
var envelope struct {
|
||||
Data map[string]json.RawMessage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(got.Body.Bytes(), &envelope); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(envelope.Data) != 1 {
|
||||
t.Errorf("GET /api/admin/ai-roles exposed roles %v; only summary is configurable", keysTicket14(envelope.Data))
|
||||
}
|
||||
if _, ok := envelope.Data["summary"]; !ok {
|
||||
t.Errorf("GET ai-roles omitted persisted summary configuration: %s", got.Body.String())
|
||||
}
|
||||
for _, role := range []string{"filter", "report"} {
|
||||
before := ticket14Setting(t, db, "ai_role_"+role+"_provider")
|
||||
res := request(http.MethodPut, "/api/admin/ai-roles/"+role, `{"provider_id":"replacement","model":"replacement-model"}`)
|
||||
if res.Code != http.StatusBadRequest {
|
||||
t.Errorf("PUT old role %s status=%d body=%s, want 400", role, res.Code, res.Body.String())
|
||||
}
|
||||
if after := ticket14Setting(t, db, "ai_role_"+role+"_provider"); after != before {
|
||||
t.Errorf("rejected %s role update changed provider setting %q -> %q", role, before, after)
|
||||
}
|
||||
}
|
||||
res := request(http.MethodPut, "/api/admin/ai-roles/summary", `{"provider_id":"00000000-0000-0000-0000-000000000142","model":"saved-override"}`)
|
||||
if res.Code != http.StatusOK {
|
||||
t.Fatalf("PUT summary role status=%d body=%s", res.Code, res.Body.String())
|
||||
}
|
||||
if got := ticket14Setting(t, db, "ai_role_summary_provider"); got != "00000000-0000-0000-0000-000000000142" {
|
||||
t.Errorf("persisted summary provider=%q", got)
|
||||
}
|
||||
if got := ticket14Setting(t, db, "ai_role_summary_model"); got != "saved-override" {
|
||||
t.Errorf("persisted summary model override=%q", got)
|
||||
}
|
||||
|
||||
provider, model, err := repo.GetRoleProvider("summary")
|
||||
if err != nil || provider == nil || provider.ID != "00000000-0000-0000-0000-000000000142" || model != "saved-override" {
|
||||
t.Fatalf("explicit summary resolution provider=%+v model=%q err=%v", provider, model, err)
|
||||
}
|
||||
if err := repo.SetRoleProvider("summary", "", "legacy-override"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider, model, err = repo.GetRoleProvider("summary")
|
||||
if err != nil || provider == nil || provider.ID != "00000000-0000-0000-0000-000000000141" || model != "legacy-override" {
|
||||
t.Fatalf("active-provider fallback/override provider=%+v model=%q err=%v", provider, model, err)
|
||||
}
|
||||
if err := repo.SetRoleProvider("summary", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider, model, err = repo.GetRoleProvider("summary")
|
||||
if err != nil || provider == nil || provider.ID != "00000000-0000-0000-0000-000000000141" || model != "active-model" {
|
||||
t.Fatalf("default active-provider fallback provider=%+v model=%q err=%v", provider, model, err)
|
||||
}
|
||||
}
|
||||
|
||||
func ticket14DB(t *testing.T) *sql.DB {
|
||||
t.Helper()
|
||||
db, err := sql.Open("postgres", postgresTestURL(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
schema := fmt.Sprintf("ticket14_%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)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`); _ = db.Close() })
|
||||
return db
|
||||
}
|
||||
func ticket14Setting(t *testing.T, db *sql.DB, key string) string {
|
||||
t.Helper()
|
||||
var value string
|
||||
if err := db.QueryRow(`SELECT value FROM settings WHERE key=$1`, key).Scan(&value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return value
|
||||
}
|
||||
func keysTicket14(values map[string]json.RawMessage) []string {
|
||||
keys := make([]string, 0, len(values))
|
||||
for key := range values {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
@ -34,11 +34,11 @@ func (safeSummarizer) Summarize(context.Context, string, []models.UserAsset, []g
|
||||
func TestGenerationSucceedsWithoutArticleTablesAndRollsBackSummaryPostgres(t *testing.T) {
|
||||
db, _ := ticket7DB(t)
|
||||
for _, statement := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,language TEXT DEFAULT 'fr',ranking_mode TEXT DEFAULT 'title')`,
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,language TEXT DEFAULT 'fr',ranking_mode TEXT DEFAULT 'title',summary_model_id UUID NULL)`,
|
||||
`CREATE TABLE user_assets(id UUID PRIMARY KEY,user_id UUID,symbol TEXT,name TEXT,figi TEXT NULL,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE sources(id UUID PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,article_limit INTEGER DEFAULT 20,source_key TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE settings(key TEXT PRIMARY KEY,value TEXT)`,
|
||||
`CREATE TABLE summaries(id UUID PRIMARY KEY,user_id UUID REFERENCES users(id),content TEXT,ai_provider_id UUID,generated_at TIMESTAMPTZ)`,
|
||||
`CREATE TABLE summaries(id UUID PRIMARY KEY,user_id UUID REFERENCES users(id),content TEXT,ai_provider_id UUID,generated_at TIMESTAMPTZ,summary_model_id UUID NULL,provider_name TEXT NULL,model_name TEXT NULL)`,
|
||||
`INSERT INTO users(id) VALUES('00000000-0000-0000-0000-000000000001')`,
|
||||
`INSERT INTO sources(id,name,type,enabled,source_key) VALUES('00000000-0000-0000-0000-000000000002','Fixture','fixture',true,'yahoo_finance')`,
|
||||
`CREATE TABLE summary_generations(id UUID PRIMARY KEY,user_id UUID,summary_id UUID REFERENCES summaries(id),outcome JSONB NOT NULL,created_at TIMESTAMPTZ)`,
|
||||
|
||||
@ -172,6 +172,10 @@ func (h *Handler) SetActiveAIProvider(c *gin.Context) {
|
||||
|
||||
func (h *Handler) DeleteAIProvider(c *gin.Context) {
|
||||
if err := h.repo.DeleteAIProvider(c.Param("id")); err != nil {
|
||||
if errors.Is(err, models.ErrCatalogConflict) {
|
||||
c.JSON(409, gin.H{"error": "provider_in_use"})
|
||||
return
|
||||
}
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
@ -359,7 +363,7 @@ func (h *Handler) GetDefaultSystemPrompt(c *gin.Context) {
|
||||
// ── AI Roles ───────────────────────────────────────────────────────────────
|
||||
|
||||
func (h *Handler) GetAIRoles(c *gin.Context) {
|
||||
roles := []string{"summary", "report", "filter"}
|
||||
roles := []string{"summary"}
|
||||
resp := gin.H{}
|
||||
for _, role := range roles {
|
||||
providerID, _ := h.repo.GetSetting("ai_role_" + role + "_provider")
|
||||
@ -376,8 +380,8 @@ type updateAIRoleRequest struct {
|
||||
|
||||
func (h *Handler) UpdateAIRole(c *gin.Context) {
|
||||
role := c.Param("role")
|
||||
if role != "summary" && role != "report" && role != "filter" {
|
||||
httputil.BadRequest(c, fmt.Errorf("invalid role: must be summary, report, or filter"))
|
||||
if role != "summary" {
|
||||
httputil.BadRequest(c, fmt.Errorf("legacy role is not configurable"))
|
||||
return
|
||||
}
|
||||
var req updateAIRoleRequest
|
||||
|
||||
@ -11,6 +11,10 @@ import (
|
||||
)
|
||||
|
||||
func preferencesError(c *gin.Context, err error) {
|
||||
if errors.Is(err, models.ErrSummaryModelUnavailable) {
|
||||
c.JSON(400, gin.H{"error": "summary_model_unavailable"})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
httputil.NotFound(c)
|
||||
return
|
||||
|
||||
@ -17,44 +17,7 @@ type reportRequest struct {
|
||||
}
|
||||
|
||||
func (h *Handler) CreateReport(c *gin.Context) {
|
||||
userID := c.GetString("userID")
|
||||
var req reportRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
httputil.BadRequest(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
summary, err := h.repo.GetOwnedSummary(req.SummaryID, userID)
|
||||
if err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
if summary == nil {
|
||||
httputil.NotFound(c)
|
||||
return
|
||||
}
|
||||
for _, excerpt := range req.Excerpts {
|
||||
if strings.TrimSpace(excerpt) == "" || !strings.Contains(summary.Content, excerpt) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "excerpt must come from the summary"})
|
||||
return
|
||||
}
|
||||
}
|
||||
summaryID := &summary.ID
|
||||
|
||||
// Joindre les extraits avec un séparateur visuel
|
||||
excerpt := buildExcerptContext(req.Excerpts)
|
||||
|
||||
// Créer le rapport en DB avec status=generating, retourner immédiatement
|
||||
report, err := h.repo.CreatePendingReport(userID, summaryID, excerpt, req.Question)
|
||||
if err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Lancer la génération en arrière-plan
|
||||
h.pipeline.GenerateReportAsync(userID, report.ID, excerpt, req.Question, h.reportManager)
|
||||
|
||||
c.JSON(http.StatusCreated, report)
|
||||
c.JSON(http.StatusGone, gin.H{"error": "reports_read_only"})
|
||||
}
|
||||
|
||||
func (h *Handler) ListReports(c *gin.Context) {
|
||||
@ -64,6 +27,14 @@ func (h *Handler) ListReports(c *gin.Context) {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
// Historical generating records have no worker after Q&A retirement.
|
||||
// Project an honest interrupted state; never rewrite the stored history.
|
||||
for i := range reports {
|
||||
if reports[i].Status == "generating" {
|
||||
reports[i].Status = "error"
|
||||
reports[i].ErrorMsg = "historical_generation_interrupted"
|
||||
}
|
||||
}
|
||||
httputil.OK(c, reports)
|
||||
}
|
||||
|
||||
@ -111,58 +82,16 @@ func (h *Handler) ListReportMessages(c *gin.Context) {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
for i := range msgs {
|
||||
if msgs[i].Status == "generating" {
|
||||
msgs[i].Status = "error"
|
||||
}
|
||||
}
|
||||
httputil.OK(c, msgs)
|
||||
}
|
||||
|
||||
func (h *Handler) CreateReportMessage(c *gin.Context) {
|
||||
userID := c.GetString("userID")
|
||||
reportID := c.Param("id")
|
||||
|
||||
var req struct {
|
||||
Content string `json:"content" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
httputil.BadRequest(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
report, err := h.repo.GetReport(reportID, userID)
|
||||
if err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
if report == nil || report.Status != "done" {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// Récupérer l'historique pour le contexte IA
|
||||
history, err := h.repo.ListReportMessages(reportID)
|
||||
if err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Persister le message utilisateur
|
||||
userMsg, err := h.repo.CreateReportMessage(reportID, "user", req.Content, "done")
|
||||
if err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Créer le message assistant en attente
|
||||
assistantMsg, err := h.repo.CreateReportMessage(reportID, "assistant", "", "generating")
|
||||
if err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Ajouter le message utilisateur à l'historique avant de lancer la génération
|
||||
history = append(history, *userMsg)
|
||||
|
||||
h.pipeline.GenerateReportMessageAsync(assistantMsg.ID, report, history, h.reportManager)
|
||||
|
||||
c.JSON(http.StatusCreated, assistantMsg)
|
||||
c.JSON(http.StatusGone, gin.H{"error": "reports_read_only"})
|
||||
}
|
||||
|
||||
func buildExcerptContext(excerpts []string) string {
|
||||
|
||||
95
backend/internal/api/handlers/summary_models.go
Normal file
95
backend/internal/api/handlers/summary_models.go
Normal file
@ -0,0 +1,95 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/httputil"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
)
|
||||
|
||||
func catalogHTTPError(c *gin.Context, err error) {
|
||||
switch {
|
||||
case errors.Is(err, models.ErrCatalogConflict):
|
||||
c.JSON(409, gin.H{"error": "summary_model_conflict"})
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
httputil.NotFound(c)
|
||||
default:
|
||||
c.JSON(500, gin.H{"error": "summary model operation failed"})
|
||||
}
|
||||
}
|
||||
func (h *Handler) ListMySummaryModels(c *gin.Context) {
|
||||
rows, err := h.repo.ListSummaryModels(true)
|
||||
if err != nil {
|
||||
catalogHTTPError(c, err)
|
||||
return
|
||||
}
|
||||
type option struct {
|
||||
ID string `json:"id"`
|
||||
Provider string `json:"provider"`
|
||||
Model string `json:"model"`
|
||||
Label string `json:"label"`
|
||||
}
|
||||
result := []option{}
|
||||
for _, row := range rows {
|
||||
result = append(result, option{row.ID, row.Provider, row.Model, row.Label})
|
||||
}
|
||||
httputil.OK(c, result)
|
||||
}
|
||||
func (h *Handler) ListSummaryModels(c *gin.Context) {
|
||||
rows, err := h.repo.ListSummaryModels(false)
|
||||
if err != nil {
|
||||
catalogHTTPError(c, err)
|
||||
return
|
||||
}
|
||||
httputil.OK(c, rows)
|
||||
}
|
||||
func (h *Handler) CreateSummaryModel(c *gin.Context) {
|
||||
var req struct {
|
||||
ProviderID string `json:"provider_id" binding:"required,uuid"`
|
||||
Model string `json:"model" binding:"required,max=256"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
if c.ShouldBindJSON(&req) != nil || strings.TrimSpace(req.Model) == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid summary model"})
|
||||
return
|
||||
}
|
||||
enabled := true
|
||||
if req.Enabled != nil {
|
||||
enabled = *req.Enabled
|
||||
}
|
||||
row, err := h.repo.CreateSummaryModel(req.ProviderID, req.Model, enabled)
|
||||
if err != nil {
|
||||
catalogHTTPError(c, err)
|
||||
return
|
||||
}
|
||||
httputil.Created(c, row)
|
||||
}
|
||||
func (h *Handler) UpdateSummaryModel(c *gin.Context) {
|
||||
var req struct {
|
||||
Enabled *bool `json:"enabled" binding:"required"`
|
||||
}
|
||||
if c.ShouldBindJSON(&req) != nil || !assetUUID.MatchString(c.Param("id")) {
|
||||
c.JSON(400, gin.H{"error": "invalid summary model"})
|
||||
return
|
||||
}
|
||||
if err := h.repo.UpdateSummaryModel(c.Param("id"), *req.Enabled); err != nil {
|
||||
catalogHTTPError(c, err)
|
||||
return
|
||||
}
|
||||
httputil.OK(c, gin.H{"ok": true})
|
||||
}
|
||||
func (h *Handler) DeleteSummaryModel(c *gin.Context) {
|
||||
if !assetUUID.MatchString(c.Param("id")) {
|
||||
c.JSON(400, gin.H{"error": "invalid summary model"})
|
||||
return
|
||||
}
|
||||
if err := h.repo.DeleteSummaryModel(c.Param("id")); err != nil {
|
||||
catalogHTTPError(c, err)
|
||||
return
|
||||
}
|
||||
httputil.NoContent(c)
|
||||
}
|
||||
@ -53,6 +53,9 @@ func TestPreferencesPersistPerUserPostgres(t *testing.T) {
|
||||
if _, err = db.Exec(string(migration)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(`ALTER TABLE users ADD COLUMN summary_model_id UUID NULL`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The two accounts predate migration 11: defaults must backfill both,
|
||||
// preserving credentials and identity.
|
||||
var defaults int
|
||||
|
||||
61
backend/internal/api/reports_readonly_projection_test.go
Normal file
61
backend/internal/api/reports_readonly_projection_test.go
Normal file
@ -0,0 +1,61 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"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/models"
|
||||
)
|
||||
|
||||
func TestRetiredReportCreationNeedsNoDatabaseAndAlwaysReturnsGone(t *testing.T) {
|
||||
h := handlers.New(nil, &config.Config{}, nil, nil, nil, nil)
|
||||
r := api.SetupRouter(h, "readonly-test")
|
||||
token, _ := auth.GenerateToken("owner", "owner@example.test", "user", "readonly-test")
|
||||
for _, path := range []string{"/api/reports", "/api/reports/missing/messages"} {
|
||||
request := httptest.NewRequest("POST", path, nil)
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, request)
|
||||
if w.Code != 410 {
|
||||
t.Fatalf("retired endpoint %s status=%d body=%s", path, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestHistoricalGeneratingReportsAreProjectedInterruptedWithoutWritesPostgres(t *testing.T) {
|
||||
db := ticket14DB(t)
|
||||
for _, q := range []string{
|
||||
`CREATE TABLE reports(id UUID PRIMARY KEY,user_id UUID,summary_id UUID,context_excerpt TEXT,question TEXT,answer TEXT,status TEXT,error_msg TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE report_messages(id UUID PRIMARY KEY,report_id UUID,role TEXT,content TEXT,status TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`INSERT INTO reports VALUES('` + ticket14ReportA + `','` + ticket14OwnerA + `',NULL,'kept excerpt','kept question','','generating','',NOW())`,
|
||||
`INSERT INTO report_messages VALUES('` + ticket14MessageA + `','` + ticket14ReportA + `','assistant','','generating',NOW())`,
|
||||
} {
|
||||
if _, err := db.Exec(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
before := ticket14ReportsSnapshot(t, db)
|
||||
h := handlers.New(models.NewRepository(db), &config.Config{}, nil, nil, nil, nil)
|
||||
r := api.SetupRouter(h, "readonly-test")
|
||||
token, _ := auth.GenerateToken(ticket14OwnerA, "owner@example.test", "user", "readonly-test")
|
||||
for _, path := range []string{"/api/reports", "/api/reports/" + ticket14ReportA + "/messages"} {
|
||||
request := httptest.NewRequest("GET", path, nil)
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, request)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("history status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var response struct{ Data []map[string]any }
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil || len(response.Data) != 1 || response.Data[0]["status"] != "error" {
|
||||
t.Fatalf("history not honestly interrupted: %s err=%v", w.Body.String(), err)
|
||||
}
|
||||
}
|
||||
if after := ticket14ReportsSnapshot(t, db); after != before {
|
||||
t.Fatal("history was rewritten instead of projected read-only")
|
||||
}
|
||||
}
|
||||
123
backend/internal/api/reports_ticket14_postgres_test.go
Normal file
123
backend/internal/api/reports_ticket14_postgres_test.go
Normal file
@ -0,0 +1,123 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"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/models"
|
||||
)
|
||||
|
||||
const (
|
||||
ticket14OwnerA = "00000000-0000-0000-0000-000000000241"
|
||||
ticket14OwnerB = "00000000-0000-0000-0000-000000000242"
|
||||
ticket14SummaryA = "00000000-0000-0000-0000-000000000251"
|
||||
ticket14ReportA = "00000000-0000-0000-0000-000000000261"
|
||||
ticket14ReportB = "00000000-0000-0000-0000-000000000262"
|
||||
ticket14MessageA = "00000000-0000-0000-0000-000000000271"
|
||||
ticket14MessageB = "00000000-0000-0000-0000-000000000272"
|
||||
)
|
||||
|
||||
func TestReportWritesAreGoneWhileHistoricalReadsAndDeletesRemainOwnerScopedPostgres(t *testing.T) {
|
||||
db := ticket14DB(t)
|
||||
for _, q := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,email TEXT,password_hash TEXT,role TEXT,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`INSERT INTO users(id,email) VALUES('` + ticket14OwnerA + `','a@example.test'),('` + ticket14OwnerB + `','b@example.test')`,
|
||||
`CREATE TABLE summaries(id UUID PRIMARY KEY,user_id UUID NOT NULL,content TEXT NOT NULL,ai_provider_id UUID,generated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`INSERT INTO summaries(id,user_id,content) VALUES('` + ticket14SummaryA + `','` + ticket14OwnerA + `','Historical summary excerpt.')`,
|
||||
`CREATE TABLE reports(id UUID PRIMARY KEY DEFAULT gen_random_uuid(),user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,summary_id UUID REFERENCES summaries(id) ON DELETE SET NULL,context_excerpt TEXT NOT NULL,question TEXT NOT NULL,answer TEXT NOT NULL DEFAULT '',status VARCHAR(20) NOT NULL DEFAULT 'done',error_msg TEXT NOT NULL DEFAULT '',created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE report_messages(id UUID PRIMARY KEY DEFAULT gen_random_uuid(),report_id UUID NOT NULL REFERENCES reports(id) ON DELETE CASCADE,role VARCHAR(10) NOT NULL,content TEXT NOT NULL,status VARCHAR(10) NOT NULL DEFAULT 'done',created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`INSERT INTO reports(id,user_id,summary_id,context_excerpt,question,answer,status) VALUES('` + ticket14ReportA + `','` + ticket14OwnerA + `','` + ticket14SummaryA + `','Historical summary excerpt.','Old question','Old answer','done'),('` + ticket14ReportB + `','` + ticket14OwnerB + `',NULL,'B private excerpt','B question','B answer','done')`,
|
||||
`INSERT INTO report_messages(id,report_id,role,content,status) VALUES('` + ticket14MessageA + `','` + ticket14ReportA + `','assistant','Historical message','done'),('` + ticket14MessageB + `','` + ticket14ReportB + `','assistant','B private message','done')`,
|
||||
} {
|
||||
if _, err := db.Exec(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
const secret = "ticket14-reports-secret"
|
||||
ownerA, err := auth.GenerateToken(ticket14OwnerA, "a@example.test", "user", secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ownerB, err := auth.GenerateToken(ticket14OwnerB, "b@example.test", "user", secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil), secret)
|
||||
invoke := func(method, path, token, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
res := httptest.NewRecorder()
|
||||
router.ServeHTTP(res, req)
|
||||
return res
|
||||
}
|
||||
before := ticket14ReportsSnapshot(t, db)
|
||||
for _, tc := range []struct{ name, path, body string }{
|
||||
{"create report", "/api/reports", `{"summary_id":"` + ticket14SummaryA + `","excerpts":["Historical summary excerpt."],"question":"New question"}`},
|
||||
{"create report message", "/api/reports/" + ticket14ReportA + "/messages", `{"content":"New message"}`},
|
||||
} {
|
||||
res := invoke(http.MethodPost, tc.path, ownerA, tc.body)
|
||||
if res.Code != http.StatusGone {
|
||||
t.Errorf("POST %s status=%d body=%s, want 410", tc.path, res.Code, res.Body.String())
|
||||
}
|
||||
}
|
||||
if after := ticket14ReportsSnapshot(t, db); after != before {
|
||||
t.Errorf("410 report endpoints wrote historical or new data\nbefore: %s\nafter: %s", before, after)
|
||||
}
|
||||
|
||||
list := invoke(http.MethodGet, "/api/reports", ownerA, "")
|
||||
if list.Code != http.StatusOK {
|
||||
t.Fatalf("GET owned historical reports status=%d body=%s", list.Code, list.Body.String())
|
||||
}
|
||||
if !strings.Contains(list.Body.String(), ticket14ReportA) || strings.Contains(list.Body.String(), ticket14ReportB) {
|
||||
t.Errorf("GET /reports not owner scoped: %s", list.Body.String())
|
||||
}
|
||||
messages := invoke(http.MethodGet, "/api/reports/"+ticket14ReportA+"/messages", ownerA, "")
|
||||
if messages.Code != http.StatusOK || !strings.Contains(messages.Body.String(), ticket14MessageA) {
|
||||
t.Errorf("GET owned historical messages status=%d body=%s", messages.Code, messages.Body.String())
|
||||
}
|
||||
foreign := invoke(http.MethodGet, "/api/reports/"+ticket14ReportA+"/messages", ownerB, "")
|
||||
if foreign.Code != http.StatusNotFound {
|
||||
t.Errorf("GET foreign historical messages status=%d, want 404", foreign.Code)
|
||||
}
|
||||
deleteForeign := invoke(http.MethodDelete, "/api/reports/"+ticket14ReportA, ownerB, "")
|
||||
if deleteForeign.Code != http.StatusNotFound {
|
||||
t.Errorf("DELETE foreign historical report status=%d, want 404", deleteForeign.Code)
|
||||
}
|
||||
var stillOwnerA, stillOwnerB int
|
||||
if err := db.QueryRow(`SELECT count(*) FILTER(WHERE id=$1),count(*) FILTER(WHERE id=$2) FROM reports`, ticket14ReportA, ticket14ReportB).Scan(&stillOwnerA, &stillOwnerB); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stillOwnerA != 1 || stillOwnerB != 1 {
|
||||
t.Fatalf("foreign delete changed history: ownerA=%d ownerB=%d", stillOwnerA, stillOwnerB)
|
||||
}
|
||||
deleteOwned := invoke(http.MethodDelete, "/api/reports/"+ticket14ReportA, ownerA, "")
|
||||
if deleteOwned.Code != http.StatusNoContent {
|
||||
t.Errorf("DELETE owned historical report status=%d, want 204", deleteOwned.Code)
|
||||
}
|
||||
if err := db.QueryRow(`SELECT count(*) FROM reports WHERE id=$1`, ticket14ReportA).Scan(&stillOwnerA); err != nil || stillOwnerA != 0 {
|
||||
t.Errorf("owned historical report remains count=%d err=%v", stillOwnerA, err)
|
||||
}
|
||||
if err := db.QueryRow(`SELECT count(*) FROM reports WHERE id=$1`, ticket14ReportB).Scan(&stillOwnerB); err != nil || stillOwnerB != 1 {
|
||||
t.Errorf("other user's report changed count=%d err=%v", stillOwnerB, err)
|
||||
}
|
||||
}
|
||||
|
||||
func ticket14ReportsSnapshot(t *testing.T, db *sql.DB) string {
|
||||
t.Helper()
|
||||
var value string
|
||||
err := db.QueryRow(`SELECT jsonb_build_object('reports',(SELECT jsonb_agg(to_jsonb(r) ORDER BY id) FROM reports r),'messages',(SELECT jsonb_agg(to_jsonb(m) ORDER BY id) FROM report_messages m))::text`).Scan(&value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return value
|
||||
}
|
||||
@ -36,6 +36,7 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
|
||||
authed.GET("/indices/search", h.SearchIndices)
|
||||
authed.GET("/me", h.GetMe)
|
||||
authed.GET("/me/preferences", h.GetMyPreferences)
|
||||
authed.GET("/me/summary-models", h.ListMySummaryModels)
|
||||
authed.PUT("/me/preferences", h.UpdateMyPreferences)
|
||||
authed.GET("/me/assets", h.GetMyAssets)
|
||||
authed.POST("/me/assets", h.AddMyAsset)
|
||||
@ -59,6 +60,10 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
|
||||
admin.GET("/credentials", h.GetCredentials)
|
||||
admin.PUT("/credentials", h.UpsertCredentials)
|
||||
|
||||
admin.GET("/ai-models", h.ListSummaryModels)
|
||||
admin.POST("/ai-models", h.CreateSummaryModel)
|
||||
admin.PUT("/ai-models/:id", h.UpdateSummaryModel)
|
||||
admin.DELETE("/ai-models/:id", h.DeleteSummaryModel)
|
||||
admin.GET("/ai-providers", h.ListAIProviders)
|
||||
admin.POST("/ai-providers", h.CreateAIProvider)
|
||||
admin.PUT("/ai-providers/:id", h.UpdateAIProvider)
|
||||
|
||||
135
backend/internal/api/summary_model_generation_test.go
Normal file
135
backend/internal/api/summary_model_generation_test.go
Normal file
@ -0,0 +1,135 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"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"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
type selectionFeed struct{ calls int }
|
||||
|
||||
func (*selectionFeed) Name() string { return "test-only" }
|
||||
func (f *selectionFeed) Scrape(context.Context, []string) ([]scraper.Article, error) {
|
||||
f.calls++
|
||||
return []scraper.Article{{Title: "private-candidate-title", Content: "private-candidate-body", URL: "https://fixture.invalid/private"}}, nil
|
||||
}
|
||||
|
||||
type selectionLaya struct{ calls int }
|
||||
|
||||
func (r *selectionLaya) Rank(_ context.Context, _ string, _ []models.UserAsset, c []generation.Candidate) ([]generation.Candidate, error) {
|
||||
r.calls++
|
||||
return c, nil
|
||||
}
|
||||
|
||||
type selectionProvider struct{ model string }
|
||||
|
||||
func (*selectionProvider) Name() string { return "test-summary" }
|
||||
func (*selectionProvider) ListModels(context.Context) ([]string, error) { return nil, nil }
|
||||
func (p *selectionProvider) Summarize(context.Context, string, ai.GenOptions) (string, error) {
|
||||
return "Safe summary from " + p.model, nil
|
||||
}
|
||||
|
||||
func TestManualGenerationResolvesAccountModelsAndSnapshotsWithoutGlobalFallbackPostgres(t *testing.T) {
|
||||
db := ticket14DB(t)
|
||||
for _, q := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,email TEXT,password_hash TEXT,role TEXT,language TEXT DEFAULT 'en',ranking_mode TEXT DEFAULT 'title',summary_model_id UUID,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE ai_providers(id UUID PRIMARY KEY,name TEXT,api_key_encrypted TEXT DEFAULT '',model TEXT,endpoint TEXT,is_active BOOLEAN DEFAULT false)`,
|
||||
`CREATE TABLE ai_provider_models(id UUID PRIMARY KEY,provider_id UUID REFERENCES ai_providers(id),model TEXT,enabled BOOLEAN DEFAULT true)`,
|
||||
`CREATE TABLE settings(key TEXT PRIMARY KEY,value TEXT)`,
|
||||
`INSERT INTO settings VALUES('summary_max_articles','50'),('ai_role_summary_provider','legacy-must-not-resolve'),('ai_role_summary_model','legacy-must-not-resolve'),('ai_role_filter_provider','legacy-must-not-resolve')`,
|
||||
`CREATE TABLE sources(id UUID PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,created_at TIMESTAMPTZ DEFAULT NOW(),article_limit INT,source_key TEXT)`,
|
||||
`INSERT INTO sources VALUES('00000000-0000-0000-0000-000000001599','Yahoo Finance','stocktwits',true,NOW(),20,'yahoo_finance')`,
|
||||
`CREATE TABLE user_assets(id UUID PRIMARY KEY,user_id UUID,symbol TEXT,name TEXT,figi TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE summaries(id UUID PRIMARY KEY,user_id UUID,content TEXT,ai_provider_id UUID,generated_at TIMESTAMPTZ,summary_model_id UUID,provider_name TEXT,model_name TEXT)`,
|
||||
`CREATE TABLE summary_generations(id UUID PRIMARY KEY,user_id UUID,summary_id UUID,outcome JSONB,created_at TIMESTAMPTZ)`,
|
||||
`INSERT INTO ai_providers VALUES('` + ticket14ProviderA + `','openai','','legacy-default-a','private-endpoint-a',false),('` + ticket14ProviderB + `','ollama','','legacy-default-b','private-endpoint-b',true)`,
|
||||
`INSERT INTO ai_provider_models VALUES('` + ticket14ModelA + `','` + ticket14ProviderA + `','account-model-a',true),('` + ticket14ModelB + `','` + ticket14ProviderB + `','account-model-b',true)`,
|
||||
`INSERT INTO users(id,email,password_hash,role,summary_model_id) VALUES('` + ticket14UserA + `','a@example.test','hash','user','` + ticket14ModelA + `'),('` + ticket14UserB + `','b@example.test','hash','user','` + ticket14ModelB + `'),('` + ticket14Admin + `','none@example.test','hash','user',NULL)`,
|
||||
} {
|
||||
if _, err := db.Exec(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
repo := models.NewRepository(db)
|
||||
feed := &selectionFeed{}
|
||||
laya := &selectionLaya{}
|
||||
resolved := []models.ResolvedSummaryModel{}
|
||||
factory := func(m models.ResolvedSummaryModel) (ai.Provider, error) {
|
||||
resolved = append(resolved, m)
|
||||
return &selectionProvider{model: m.Model}, nil
|
||||
}
|
||||
pipeline := ai.NewPipeline(repo, nil)
|
||||
feeds := map[string]scraper.Scraper{models.SourceYahooFinance: feed}
|
||||
useCase := pipeline.NewGenerationUseCaseWithFactory(feeds, laya, factory)
|
||||
h := handlers.New(repo, &config.Config{}, nil, nil, pipeline, nil)
|
||||
h.SetGenerationUseCase(useCase)
|
||||
const secret = "selection-test-only"
|
||||
router := api.SetupRouter(h, secret)
|
||||
generate := func(user string, status int) generation.Result {
|
||||
t.Helper()
|
||||
token, _ := auth.GenerateToken(user, "fixture@example.test", "user", secret)
|
||||
request := httptest.NewRequest("POST", "/api/summaries/generate", strings.NewReader(`{"user_id":"not-the-owner"}`))
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, request)
|
||||
if w.Code != status {
|
||||
t.Fatalf("status=%d want=%d body=%s", w.Code, status, w.Body.String())
|
||||
}
|
||||
var response struct{ Data generation.Result }
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return response.Data
|
||||
}
|
||||
for _, tc := range []struct{ user, provider, model string }{{ticket14UserA, "openai", "account-model-a"}, {ticket14UserB, "ollama", "account-model-b"}} {
|
||||
result := generate(tc.user, 201)
|
||||
if result.Summary == nil || result.Summary.ProviderName == nil || *result.Summary.ProviderName != tc.provider || result.Summary.ModelName == nil || *result.Summary.ModelName != tc.model {
|
||||
t.Fatalf("wrong actual snapshot: %+v", result.Summary)
|
||||
}
|
||||
var provider, model string
|
||||
if err := db.QueryRow(`SELECT provider_name,model_name FROM summaries WHERE user_id=$1`, tc.user).Scan(&provider, &model); err != nil || provider != tc.provider || model != tc.model {
|
||||
t.Fatalf("stored snapshot=(%s,%s) err=%v", provider, model, err)
|
||||
}
|
||||
}
|
||||
for _, user := range []string{ticket14Admin, ticket14UserB} {
|
||||
if user == ticket14UserB {
|
||||
if _, err := db.Exec(`UPDATE ai_provider_models SET enabled=false WHERE id=$1`, ticket14ModelB); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
result := generate(user, 502)
|
||||
if result.Summary != nil || result.Outcome.FailureCode != "summary_model_unavailable" {
|
||||
t.Fatalf("unsafe missing/disabled selection: %+v", result)
|
||||
}
|
||||
}
|
||||
if feed.calls != 2 || laya.calls != 2 || len(resolved) != 2 {
|
||||
t.Fatalf("preflight failed: scrape=%d laya=%d resolve=%d", feed.calls, laya.calls, len(resolved))
|
||||
}
|
||||
// A configured model cannot replace a missing dedicated Laya engine.
|
||||
h.SetGenerationUseCase(pipeline.NewGenerationUseCaseWithFactory(feeds, nil, factory))
|
||||
result := generate(ticket14UserA, 502)
|
||||
if result.Outcome.FailureCode != "laya_unavailable" || feed.calls != 2 || laya.calls != 2 {
|
||||
t.Fatal("missing Laya reached collection or fell back", result)
|
||||
}
|
||||
var count int
|
||||
if err := db.QueryRow(`SELECT count(*) FROM summaries`).Scan(&count); err != nil || count != 2 {
|
||||
t.Fatal("failed preflight wrote summaries", count, err)
|
||||
}
|
||||
for _, entry := range resolved {
|
||||
if entry.Model == "legacy-must-not-resolve" {
|
||||
t.Fatal(fmt.Sprint("legacy role resolved"))
|
||||
}
|
||||
}
|
||||
}
|
||||
202
backend/internal/api/summary_models_ticket14_postgres_test.go
Normal file
202
backend/internal/api/summary_models_ticket14_postgres_test.go
Normal file
@ -0,0 +1,202 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"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/models"
|
||||
)
|
||||
|
||||
const (
|
||||
ticket14UserA = "00000000-0000-0000-0000-000000001501"
|
||||
ticket14UserB = "00000000-0000-0000-0000-000000001502"
|
||||
ticket14Admin = "00000000-0000-0000-0000-000000001503"
|
||||
ticket14ModelA = "00000000-0000-0000-0000-000000001511"
|
||||
ticket14ModelB = "00000000-0000-0000-0000-000000001512"
|
||||
ticket14ProviderA = "00000000-0000-0000-0000-000000001521"
|
||||
ticket14ProviderB = "00000000-0000-0000-0000-000000001522"
|
||||
)
|
||||
|
||||
func TestPerUserSummaryModelCatalogAPIIsSafeScopedAndPersistsPreferencePostgres(t *testing.T) {
|
||||
db := ticket14DB(t)
|
||||
for _, statement := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,email TEXT NOT NULL,password_hash TEXT NOT NULL,role TEXT NOT NULL,language TEXT NOT NULL DEFAULT 'fr',ranking_mode TEXT NOT NULL DEFAULT 'title',summary_model_id UUID,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE ai_providers(id UUID PRIMARY KEY,name TEXT NOT NULL,api_key_encrypted TEXT NOT NULL,model TEXT NOT NULL,endpoint TEXT NOT NULL,is_active BOOLEAN NOT NULL DEFAULT FALSE,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE ai_provider_models(id UUID PRIMARY KEY,provider_id UUID NOT NULL REFERENCES ai_providers(id),model TEXT NOT NULL,enabled BOOLEAN NOT NULL DEFAULT TRUE,UNIQUE(provider_id,model))`,
|
||||
`ALTER TABLE users ADD CONSTRAINT users_summary_model_fk FOREIGN KEY(summary_model_id) REFERENCES ai_provider_models(id) ON DELETE RESTRICT`,
|
||||
`INSERT INTO users(id,email,password_hash,role) VALUES('` + ticket14UserA + `','a@example.test','hash','user'),('` + ticket14UserB + `','b@example.test','hash','user'),('` + ticket14Admin + `','admin@example.test','hash','admin')`,
|
||||
`INSERT INTO ai_providers(id,name,api_key_encrypted,model,endpoint,is_active) VALUES('` + ticket14ProviderA + `','openai','secret-ciphertext-a','provider-default-a','https://private-a',true),('` + ticket14ProviderB + `','ollama','secret-ciphertext-b','provider-default-b','http://private-b',false)`,
|
||||
`INSERT INTO ai_provider_models(id,provider_id,model,enabled) VALUES('` + ticket14ModelA + `','` + ticket14ProviderA + `','gpt-safe',true),('` + ticket14ModelB + `','` + ticket14ProviderB + `','qwen-safe',true)`,
|
||||
} {
|
||||
if _, err := db.Exec(statement); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
const secret = "ticket14-user-model-test"
|
||||
token := func(id, role string) string {
|
||||
t.Helper()
|
||||
value, err := auth.GenerateToken(id, id+"@example.test", role, secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return value
|
||||
}
|
||||
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil), secret)
|
||||
call := func(method, path, bearer, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||
if bearer != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+bearer)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
res := httptest.NewRecorder()
|
||||
router.ServeHTTP(res, req)
|
||||
return res
|
||||
}
|
||||
aToken, bToken := token(ticket14UserA, "user"), token(ticket14UserB, "user")
|
||||
for _, bearer := range []string{aToken, bToken} {
|
||||
res := call(http.MethodGet, "/api/me/summary-models", bearer, "")
|
||||
if res.Code != http.StatusOK {
|
||||
t.Errorf("GET /api/me/summary-models status=%d body=%s; want 200", res.Code, res.Body.String())
|
||||
continue
|
||||
}
|
||||
if strings.Contains(res.Body.String(), "secret-ciphertext") || strings.Contains(res.Body.String(), "private-a") || strings.Contains(res.Body.String(), "private-b") || strings.Contains(res.Body.String(), "api_key") || strings.Contains(res.Body.String(), "endpoint") {
|
||||
t.Errorf("user model catalog leaked provider credentials/configuration: %s", res.Body.String())
|
||||
}
|
||||
var envelope struct {
|
||||
Data []map[string]any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(res.Body.Bytes(), &envelope); err != nil || len(envelope.Data) != 2 {
|
||||
t.Errorf("user catalog did not return configured model options: rows=%v err=%v", envelope.Data, err)
|
||||
}
|
||||
for _, option := range envelope.Data {
|
||||
if len(option) != 4 || option["id"] == nil || option["provider"] == nil || option["model"] == nil || option["label"] == nil {
|
||||
t.Errorf("model option must contain only id/provider/model/label: %v", option)
|
||||
}
|
||||
}
|
||||
}
|
||||
put := call(http.MethodPut, "/api/me/preferences", aToken, `{"language":"fr","ranking_mode":"title","summary_model_id":"`+ticket14ModelB+`"}`)
|
||||
if put.Code != http.StatusOK {
|
||||
t.Errorf("PUT preferences model selection status=%d body=%s; want 200", put.Code, put.Body.String())
|
||||
}
|
||||
getA := call(http.MethodGet, "/api/me/preferences", aToken, "")
|
||||
if getA.Code != http.StatusOK || !strings.Contains(getA.Body.String(), ticket14ModelB) {
|
||||
t.Errorf("GET own preferences did not return selected model: status=%d body=%s", getA.Code, getA.Body.String())
|
||||
}
|
||||
getB := call(http.MethodGet, "/api/me/preferences", bToken, "")
|
||||
if getB.Code != http.StatusOK || strings.Contains(getB.Body.String(), ticket14ModelB) {
|
||||
t.Errorf("user B observed user A model preference: status=%d body=%s", getB.Code, getB.Body.String())
|
||||
}
|
||||
putB := call(http.MethodPut, "/api/me/preferences", bToken, `{"language":"en","ranking_mode":"title","summary_model_id":"`+ticket14ModelA+`"}`)
|
||||
if putB.Code != http.StatusOK {
|
||||
t.Errorf("user B preference update status=%d body=%s", putB.Code, putB.Body.String())
|
||||
}
|
||||
getAAfterB := call(http.MethodGet, "/api/me/preferences", aToken, "")
|
||||
getBAfter := call(http.MethodGet, "/api/me/preferences", bToken, "")
|
||||
if !strings.Contains(getAAfterB.Body.String(), ticket14ModelB) || !strings.Contains(getBAfter.Body.String(), ticket14ModelA) {
|
||||
t.Errorf("per-user model selections are not isolated: A=%s B=%s", getAAfterB.Body.String(), getBAfter.Body.String())
|
||||
}
|
||||
invalid := call(http.MethodPut, "/api/me/preferences", aToken, `{"language":"fr","ranking_mode":"title","summary_model_id":"00000000-0000-0000-0000-000000001599"}`)
|
||||
if invalid.Code != http.StatusBadRequest {
|
||||
t.Errorf("disabled or non-owned model selection status=%d body=%s; want 400", invalid.Code, invalid.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminSummaryModelCatalogCRUDIsSeparateFromProviderConfigAndProtectsSelectedModelPostgres(t *testing.T) {
|
||||
db := ticket14DB(t)
|
||||
for _, statement := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,email TEXT NOT NULL,password_hash TEXT NOT NULL,role TEXT NOT NULL,summary_model_id UUID,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE ai_providers(id UUID PRIMARY KEY,name TEXT NOT NULL,api_key_encrypted TEXT NOT NULL,model TEXT NOT NULL,endpoint TEXT NOT NULL,is_active BOOLEAN NOT NULL DEFAULT FALSE,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE ai_provider_models(id UUID PRIMARY KEY,provider_id UUID NOT NULL REFERENCES ai_providers(id),model TEXT NOT NULL,enabled BOOLEAN NOT NULL DEFAULT TRUE,UNIQUE(provider_id,model))`,
|
||||
`ALTER TABLE users ADD CONSTRAINT users_summary_model_fk FOREIGN KEY(summary_model_id) REFERENCES ai_provider_models(id) ON DELETE RESTRICT`,
|
||||
`INSERT INTO ai_providers(id,name,api_key_encrypted,model,endpoint) VALUES('` + ticket14ProviderA + `','openai','secret-ciphertext-a','provider-default-a','https://private-a')`,
|
||||
`INSERT INTO ai_provider_models(id,provider_id,model,enabled) VALUES('` + ticket14ModelA + `','` + ticket14ProviderA + `','selected-model',true)`,
|
||||
`INSERT INTO users(id,email,password_hash,role,summary_model_id) VALUES('` + ticket14UserA + `','a@example.test','hash','user','` + ticket14ModelA + `'),('` + ticket14Admin + `','admin@example.test','hash','admin',NULL)`,
|
||||
} {
|
||||
if _, err := db.Exec(statement); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
const secret = "ticket14-admin-model-catalog"
|
||||
tokenFor := func(id, role string) string {
|
||||
value, err := auth.GenerateToken(id, id+"@example.test", role, secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return value
|
||||
}
|
||||
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil), secret)
|
||||
invoke := func(method, path, token, body string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
res := httptest.NewRecorder()
|
||||
router.ServeHTTP(res, req)
|
||||
return res
|
||||
}
|
||||
adminToken, userToken := tokenFor(ticket14Admin, "admin"), tokenFor(ticket14UserA, "user")
|
||||
// Model catalogue management is a distinct resource from provider CRUD.
|
||||
for _, tc := range []struct{ method, path, body string }{
|
||||
{http.MethodGet, "/api/admin/ai-models", ""},
|
||||
{http.MethodPost, "/api/admin/ai-models", `{"provider_id":"` + ticket14ProviderA + `","model":"new-model"}`},
|
||||
{http.MethodPut, "/api/admin/ai-models/" + ticket14ModelA, `{"enabled":false}`},
|
||||
} {
|
||||
res := invoke(tc.method, tc.path, adminToken, tc.body)
|
||||
if res.Code < 200 || res.Code >= 300 {
|
||||
t.Errorf("admin catalog %s %s status=%d body=%s", tc.method, tc.path, res.Code, res.Body.String())
|
||||
}
|
||||
if tc.method == http.MethodGet && (strings.Contains(res.Body.String(), "secret-ciphertext") || strings.Contains(res.Body.String(), "private-a") || strings.Contains(res.Body.String(), "api_key") || strings.Contains(res.Body.String(), "endpoint")) {
|
||||
t.Errorf("admin model catalog leaked provider credentials/configuration: %s", res.Body.String())
|
||||
}
|
||||
}
|
||||
for _, tc := range []struct{ method, path string }{
|
||||
{http.MethodGet, "/api/admin/ai-models"},
|
||||
{http.MethodPost, "/api/admin/ai-models"},
|
||||
{http.MethodPut, "/api/admin/ai-models/" + ticket14ModelA},
|
||||
{http.MethodDelete, "/api/admin/ai-models/" + ticket14ModelA},
|
||||
} {
|
||||
res := invoke(tc.method, tc.path, userToken, `{"provider_id":"`+ticket14ProviderA+`","model":"attempt"}`)
|
||||
if res.Code != http.StatusForbidden {
|
||||
t.Errorf("non-admin catalog %s status=%d body=%s; want 403", tc.method, res.Code, res.Body.String())
|
||||
}
|
||||
}
|
||||
deleteAsAdmin := invoke(http.MethodDelete, "/api/admin/ai-models/"+ticket14ModelA, adminToken, "")
|
||||
if deleteAsAdmin.Code != http.StatusConflict {
|
||||
t.Errorf("delete selected model status=%d body=%s; want 409", deleteAsAdmin.Code, deleteAsAdmin.Body.String())
|
||||
}
|
||||
var count int
|
||||
if err := db.QueryRow(`SELECT count(*) FROM ai_provider_models WHERE id=$1`, ticket14ModelA).Scan(&count); err != nil || count != 1 {
|
||||
t.Errorf("conflicting delete removed selected model: count=%d err=%v", count, err)
|
||||
}
|
||||
var providerCount int
|
||||
if err := db.QueryRow(`SELECT count(*) FROM ai_providers WHERE id=$1`, ticket14ProviderA).Scan(&providerCount); err != nil || providerCount != 1 {
|
||||
t.Errorf("catalog operations changed provider configuration: count=%d err=%v", providerCount, err)
|
||||
}
|
||||
created := invoke(http.MethodPost, "/api/admin/ai-models", adminToken, `{"provider_id":"`+ticket14ProviderA+`","model":"deletable-unselected-model"}`)
|
||||
if created.Code != http.StatusCreated {
|
||||
t.Fatalf("create unselected catalog model status=%d body=%s", created.Code, created.Body.String())
|
||||
}
|
||||
var createdEnvelope struct {
|
||||
Data struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(created.Body.Bytes(), &createdEnvelope); err != nil || createdEnvelope.Data.ID == "" {
|
||||
t.Fatalf("created catalog model response=%s err=%v", created.Body.String(), err)
|
||||
}
|
||||
deleted := invoke(http.MethodDelete, "/api/admin/ai-models/"+createdEnvelope.Data.ID, adminToken, "")
|
||||
if deleted.Code != http.StatusNoContent {
|
||||
t.Errorf("delete unselected catalog model status=%d body=%s; want 204", deleted.Code, deleted.Body.String())
|
||||
}
|
||||
if err := db.QueryRow(`SELECT count(*) FROM ai_provider_models WHERE id=$1`, createdEnvelope.Data.ID).Scan(&count); err != nil || count != 0 {
|
||||
t.Errorf("successfully deleted catalog entry remains count=%d err=%v", count, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user