feat(sources): enforce supported source allowlist
Assign stable keys to the three supported sources, preserve excluded historical rows, and expose history read-only in admin. Add migration, coverage, and responsive browser spec. Refs #13 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@ -39,10 +39,10 @@ func TestArticleCapsMigrationAndInvalidAdminUpdatesAreAtomicPostgres(t *testing.
|
||||
`CREATE TABLE users (id TEXT PRIMARY KEY,email TEXT,password_hash TEXT,role TEXT,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`INSERT INTO users(id,email,password_hash,role) VALUES ('admin-id','admin@example.test','hash','admin')`,
|
||||
`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
|
||||
`CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, enabled BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, source_key TEXT, enabled BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE scrape_schedules (id UUID PRIMARY KEY, day_of_week INT NOT NULL, hour INT NOT NULL, minute INT NOT NULL)`,
|
||||
`INSERT INTO settings (key,value) VALUES ('summary_max_articles','733')`,
|
||||
`INSERT INTO sources (id,name,type) VALUES ('00000000-0000-0000-0000-000000000001','Yahoo Finance','stocktwits')`,
|
||||
`INSERT INTO sources (id,name,type,source_key) VALUES ('00000000-0000-0000-0000-000000000001','Yahoo Finance','stocktwits','yahoo_finance')`,
|
||||
} {
|
||||
if _, err = db.Exec(statement); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
117
backend/internal/api/admin_sources_ticket13_postgres_test.go
Normal file
117
backend/internal/api/admin_sources_ticket13_postgres_test.go
Normal file
@ -0,0 +1,117 @@
|
||||
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 TestAdminSourcesExposeSupportStateAndRejectHistoricalUpdateAtomicallyPostgres(t *testing.T) {
|
||||
dbURL := postgresTestURL(t)
|
||||
db, err := sql.Open("postgres", dbURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
schema := fmt.Sprintf("ticket13_admin_sources_%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() })
|
||||
for _, q := range []string{`CREATE TABLE users(id TEXT PRIMARY KEY,email TEXT,role TEXT,password_hash TEXT,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`, `INSERT INTO users(id,email,role,password_hash) VALUES('admin-id','admin@example.test','admin','hash')`, `CREATE TABLE sources(id TEXT PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,article_limit INTEGER DEFAULT 20,source_key TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`, `INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES('old-id','Reuters','reuters',true,42,NULL),('y-id','Yahoo Finance','stocktwits',true,83,'yahoo_finance')`} {
|
||||
if _, err = db.Exec(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
const secret = "ticket13-admin-route-test"
|
||||
token, err := auth.GenerateToken("admin-id", "admin@example.test", "admin", secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil), secret)
|
||||
get := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/admin/sources", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
router.ServeHTTP(get, req)
|
||||
if get.Code != http.StatusOK {
|
||||
t.Fatalf("GET sources status=%d body=%s", get.Code, get.Body.String())
|
||||
}
|
||||
var envelope struct {
|
||||
Data []map[string]any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(get.Body.Bytes(), &envelope); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows := envelope.Data
|
||||
var old map[string]any
|
||||
var supported map[string]any
|
||||
for _, row := range rows {
|
||||
if row["id"] == "old-id" {
|
||||
old = row
|
||||
}
|
||||
if row["id"] == "y-id" {
|
||||
supported = row
|
||||
}
|
||||
}
|
||||
if old == nil {
|
||||
t.Fatalf("GET omitted historical source: %s", get.Body.String())
|
||||
}
|
||||
for field, want := range map[string]any{"source_key": nil, "supported": false, "enabled": true, "operational": false} {
|
||||
if _, exists := old[field]; !exists {
|
||||
t.Errorf("historical response omitted %s: row=%v", field, old)
|
||||
}
|
||||
if old[field] != want {
|
||||
t.Errorf("historical %s=%v, want %v; row=%v", field, old[field], want, old)
|
||||
}
|
||||
}
|
||||
for _, secretField := range []string{"api_key", "password", "credentials", "article", "content", "url"} {
|
||||
if _, ok := old[secretField]; ok {
|
||||
t.Errorf("GET sources exposed forbidden %q", secretField)
|
||||
}
|
||||
}
|
||||
if supported == nil {
|
||||
t.Fatalf("GET omitted supported source: %s", get.Body.String())
|
||||
}
|
||||
for field, want := range map[string]any{"source_key": "yahoo_finance", "supported": true, "operational": true} {
|
||||
if supported[field] != want {
|
||||
t.Errorf("supported source %s=%v, want %v; row=%v", field, supported[field], want, supported)
|
||||
}
|
||||
}
|
||||
put := httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodPut, "/api/admin/sources/old-id", bytes.NewBufferString(`{"enabled":true,"article_limit":99}`))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(put, req)
|
||||
if put.Code != http.StatusConflict {
|
||||
t.Errorf("PUT historical source status=%d body=%s, want 409 source_not_supported", put.Code, put.Body.String())
|
||||
}
|
||||
if !bytes.Contains(put.Body.Bytes(), []byte("source_not_supported")) {
|
||||
t.Errorf("PUT error body=%s, want source_not_supported", put.Body.String())
|
||||
}
|
||||
var enabled bool
|
||||
var cap int
|
||||
if err := db.QueryRow(`SELECT enabled,article_limit FROM sources WHERE id='old-id'`).Scan(&enabled, &cap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !enabled || cap != 42 {
|
||||
t.Fatalf("rejected update mutated historical row enabled=%v cap=%d", enabled, cap)
|
||||
}
|
||||
}
|
||||
@ -36,11 +36,11 @@ func TestGenerationSucceedsWithoutArticleTablesAndRollsBackSummaryPostgres(t *te
|
||||
for _, statement := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,language TEXT DEFAULT 'fr',ranking_mode TEXT DEFAULT 'title')`,
|
||||
`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,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)`,
|
||||
`INSERT INTO users(id) VALUES('00000000-0000-0000-0000-000000000001')`,
|
||||
`INSERT INTO sources(id,name,type,enabled) VALUES('00000000-0000-0000-0000-000000000002','Fixture','fixture',true)`,
|
||||
`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)`,
|
||||
} {
|
||||
if _, err := db.Exec(statement); err != nil {
|
||||
@ -48,7 +48,7 @@ func TestGenerationSucceedsWithoutArticleTablesAndRollsBackSummaryPostgres(t *te
|
||||
}
|
||||
}
|
||||
repo := models.NewRepository(db)
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: repo}, Scrapers: map[string]scraper.Scraper{"fixture": memoryFeed{}}, Ranker: passRanker{}, Summarizer: safeSummarizer{}})
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: repo}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: memoryFeed{}}, Ranker: passRanker{}, Summarizer: safeSummarizer{}})
|
||||
result, err := uc.Generate(context.Background(), "00000000-0000-0000-0000-000000000001")
|
||||
if err != nil || result.Summary == nil || result.Outcome.Status != "succeeded" {
|
||||
t.Fatalf("result=%+v err=%v", result, err)
|
||||
|
||||
@ -233,7 +233,16 @@ func (h *Handler) ListSources(c *gin.Context) {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
httputil.OK(c, sources)
|
||||
type sourceResponse struct {
|
||||
models.Source
|
||||
Supported bool `json:"supported"`
|
||||
Operational bool `json:"operational"`
|
||||
}
|
||||
result := make([]sourceResponse, 0, len(sources))
|
||||
for _, source := range sources {
|
||||
result = append(result, sourceResponse{Source: source, Supported: source.Supported(), Operational: source.Operational()})
|
||||
}
|
||||
httputil.OK(c, result)
|
||||
}
|
||||
|
||||
type updateSourceRequest struct {
|
||||
@ -248,6 +257,14 @@ func (h *Handler) UpdateSource(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
if err := h.repo.UpdateSource(c.Param("id"), req.Enabled, req.ArticleLimit); err != nil {
|
||||
if errors.Is(err, models.ErrSourceNotSupported) {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "source_not_supported"})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
httputil.NotFound(c)
|
||||
return
|
||||
}
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user