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:
2026-11-21 00:11:26 +01:00
parent 4459a81206
commit ac17d27f51
26 changed files with 924 additions and 61 deletions

View File

@ -117,14 +117,14 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
stats := map[string]int{}
partial := false
for _, source := range input.Sources {
if !source.Enabled {
if !source.Operational() {
continue
}
stat := SourceStat{SourceID: source.ID, SourceType: source.Type, ArticleLimit: source.ArticleLimit, Status: "ok"}
if stat.ArticleLimit <= 0 {
stat.ArticleLimit = 20
}
feed := u.Scrapers[source.Type]
feed := u.Scrapers[*source.SourceKey]
var articles []scraper.Article
if feed == nil {
err = fmt.Errorf("unavailable")

View File

@ -92,9 +92,9 @@ func (s *contractSummarizer) Summarize(_ context.Context, language string, _ []m
func TestUseCaseIsolatesTwoUsersAndUsesOnlyEnabledSourcesAndUserInputs(t *testing.T) {
alphaID, betaID := "user-alpha", "user-beta"
alphaSource := models.Source{ID: "alpha-feed", Type: "alpha", Enabled: true, ArticleLimit: 5}
betaSource := models.Source{ID: "beta-feed", Type: "beta", Enabled: true, ArticleLimit: 5}
disabled := models.Source{ID: "disabled-feed", Type: "disabled", Enabled: false, ArticleLimit: 5}
alphaSource := models.Source{ID: "alpha-feed", Type: "alpha", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}
betaSource := models.Source{ID: "beta-feed", Type: "beta", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 5}
disabled := models.Source{ID: "disabled-feed", Type: "disabled", SourceKey: testSourceKey(models.SourceWatcherGuru), Enabled: false, ArticleLimit: 5}
alphaScraper := &contractScraper{name: "alpha", articles: []scraper.Article{{Title: "alpha-only", URL: "https://private.test/alpha", Content: "alpha-secret"}}}
betaScraper := &contractScraper{name: "beta", articles: []scraper.Article{{Title: "beta-only", URL: "https://private.test/beta", Content: "beta-secret"}}}
disabledScraper := &contractScraper{name: "disabled"}
@ -107,7 +107,7 @@ func TestUseCaseIsolatesTwoUsersAndUsesOnlyEnabledSourcesAndUserInputs(t *testin
},
saved: map[string][]GenerationRecord{},
}
useCase := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"alpha": alphaScraper, "beta": betaScraper, "disabled": disabledScraper}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) }})
useCase := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: alphaScraper, models.SourceBloomberg: betaScraper, models.SourceWatcherGuru: disabledScraper}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) }})
alpha, err := useCase.Generate(context.Background(), alphaID)
if err != nil || alpha.Summary == nil {
@ -148,8 +148,8 @@ func TestUseCasePreservesLayaOrderThenAppliesPerSourceAndGlobalCaps(t *testing.T
feedB := &contractScraper{name: "b", articles: articles[2:]}
ranker := &contractRanker{order: []string{"a2", "b1", "a1", "b2", "a3"}}
summarizer := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 3, Assets: []models.UserAsset{{Symbol: "IDX"}}, Sources: []models.Source{{ID: "a", Type: "a", Enabled: true, ArticleLimit: 1}, {ID: "b", Type: "b", Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"a": feedA, "b": feedB}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 3, Assets: []models.UserAsset{{Symbol: "IDX"}}, Sources: []models.Source{{ID: "a", Type: "a", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}, {ID: "b", Type: "b", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feedA, models.SourceBloomberg: feedB}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
if _, err := uc.Generate(context.Background(), "u"); err != nil {
t.Fatal(err)
}
@ -176,10 +176,10 @@ func TestUseCaseNoResultsInvalidLayaAndSummaryFailurePersistNoSummary(t *testing
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 10, Sources: []models.Source{{ID: "s", Type: "s", Enabled: true, ArticleLimit: 10}}}}, saved: map[string][]GenerationRecord{}}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 10, Sources: []models.Source{{ID: "s", Type: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 10}}}}, saved: map[string][]GenerationRecord{}}
ranker := &contractRanker{err: tt.rankErr}
summarizer := &contractSummarizer{err: tt.summaryErr}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"s": &contractScraper{name: "s", articles: tt.articles}}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{name: "s", articles: tt.articles}}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
result, err := uc.Generate(context.Background(), "u")
if err != nil {
t.Fatalf("expected aggregate failure outcome, got error: %v", err)
@ -199,8 +199,8 @@ func TestUseCasePartialSourceFailureCanSummarizeRemainingSources(t *testing.T) {
bad := &contractScraper{name: "bad", err: errors.New("private error with URL https://private.test/article")}
ranker := &contractRanker{order: []string{"good-result"}}
summarizer := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "good", Type: "good", Enabled: true, ArticleLimit: 5}, {ID: "bad", Type: "bad", Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"good": good, "bad": bad}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "good", Type: "good", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}, {ID: "bad", Type: "bad", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: good, models.SourceBloomberg: bad}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
result, err := uc.Generate(context.Background(), "u")
if err != nil || result.Summary == nil || result.Outcome.Status != "partial" {
t.Fatalf("partial source failure result=%+v err=%v", result, err)
@ -221,8 +221,8 @@ func TestUseCaseOutcomeContainsAggregateCountsWithoutArticleIdentifiers(t *testi
feed := &contractScraper{name: "source", articles: []scraper.Article{{Title: "candidate-title-secret", URL: "https://private.test/x", Content: "candidate-content-secret"}}}
ranker := &contractRanker{order: []string{"candidate-title-secret"}}
summarizer := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "source-id", Type: "source", Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"source": feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "source-id", Type: "source", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
result, err := uc.Generate(context.Background(), "u")
if err != nil {
t.Fatal(err)
@ -245,8 +245,8 @@ func TestUseCaseCountsTitleOnlyFallbackWhenContentIsUnavailable(t *testing.T) {
feed := &contractScraper{name: "source", articles: []scraper.Article{{Title: "title-without-content", Content: ""}}}
ranker := &contractRanker{}
summarizer := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "en", RankingMode: "title_content", GlobalLimit: 4, Sources: []models.Source{{ID: "source", Type: "source", Enabled: true, ArticleLimit: 4}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"source": feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "en", RankingMode: "title_content", GlobalLimit: 4, Sources: []models.Source{{ID: "source", Type: "source", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 4}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
result, err := uc.Generate(context.Background(), "u")
if err != nil || result.Summary == nil {
t.Fatalf("content fallback should permit generation: result=%+v err=%v", result, err)
@ -267,3 +267,5 @@ func candidateTitles(candidates []Candidate) []string {
func contains(value, needle string) bool {
return len(needle) > 0 && strings.Contains(value, needle)
}
func testSourceKey(key string) *string { return &key }

View File

@ -52,11 +52,12 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
for _, statement := range []string{
`CREATE TABLE users (id UUID PRIMARY KEY, language TEXT NOT NULL DEFAULT 'fr', ranking_mode TEXT NOT NULL DEFAULT 'title')`,
`CREATE TABLE user_assets (id UUID PRIMARY KEY, user_id UUID NOT NULL, symbol VARCHAR(20) NOT NULL, name TEXT NOT NULL DEFAULT '', figi TEXT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
`CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, enabled BOOLEAN NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), article_limit INT NOT NULL DEFAULT 20)`,
`CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, enabled BOOLEAN NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), article_limit INT NOT NULL DEFAULT 20, source_key TEXT)`,
`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
`INSERT INTO users(id,language,ranking_mode) VALUES ('` + userID + `','fr','title')`,
`INSERT INTO user_assets(id,user_id,symbol,name,figi) VALUES ('00000000-0000-0000-0000-000000000411','` + userID + `','LEGACY','Historic asset',NULL)`,
`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES ('00000000-0000-0000-0000-000000000421','test source','ticket4',TRUE,20)`,
`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES ('00000000-0000-0000-0000-000000000421','test source','ticket4',TRUE,20,'yahoo_finance')`,
`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES ('00000000-0000-0000-0000-000000000422','Historic enabled','reuters',TRUE,42,NULL),('00000000-0000-0000-0000-000000000423','Disabled target','bloomberg',FALSE,77,'bloomberg')`,
`INSERT INTO settings(key,value) VALUES ('summary_max_articles','50')`,
} {
if _, err := db.Exec(statement); err != nil {
@ -68,6 +69,9 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
if err != nil {
t.Fatalf("load legacy generation input from PostgreSQL: %v", err)
}
if len(input.Sources) != 1 || input.Sources[0].SourceKey == nil || *input.Sources[0].SourceKey != models.SourceYahooFinance || input.Sources[0].ArticleLimit != 20 {
t.Fatalf("LoadUserInput must exclude unsupported/disabled sources, preserving target caps: %+v", input.Sources)
}
if len(input.Assets) != 1 || input.Assets[0].Symbol != "LEGACY" || input.Assets[0].Name != "Historic asset" {
t.Fatalf("loaded legacy asset=%+v, want symbol/name preserved", input.Assets)
}
@ -84,7 +88,7 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
fakeRepository := &contractRepository{inputs: map[string]UserInput{userID: input}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{
Repository: fakeRepository,
Scrapers: map[string]scraper.Scraper{"ticket4": feed},
Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed},
Ranker: ranker,
Summarizer: summarizer,
Clock: func() time.Time { return time.Unix(1, 0).UTC() },

View File

@ -33,7 +33,7 @@ func (r RepositoryAdapter) LoadUserInput(ctx context.Context, id string) (UserIn
if value == "" {
limit = 50
}
return UserInput{Language: p.Language, RankingMode: p.RankingMode, GlobalLimit: limit, Assets: assets, Sources: sources}, nil
return UserInput{Language: p.Language, RankingMode: p.RankingMode, GlobalLimit: limit, Assets: assets, Sources: models.OperationalSources(sources)}, nil
}
func (r RepositoryAdapter) SaveGeneration(ctx context.Context, id string, record GenerationRecord) error {
payload, err := json.Marshal(record.Outcome)

View File

@ -0,0 +1,49 @@
package generation
import (
"context"
"encoding/json"
"testing"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
)
func TestGenerationRoutesOnlyAllowlistedSourceKeysEvenWhenLegacyRowsAreEnabled(t *testing.T) {
var sources []models.Source
if err := json.Unmarshal([]byte(`[
{"id":"y","name":"Yahoo Finance","type":"stocktwits","source_key":"yahoo_finance","enabled":true,"article_limit":20},
{"id":"b","name":"Bloomberg","type":"bloomberg","source_key":"bloomberg","enabled":true,"article_limit":20},
{"id":"w","name":"Watcher.Guru","type":"watcherguru","source_key":"watcher_guru","enabled":true,"article_limit":20},
{"id":"s","name":"StockTwits","type":"stocktwits","source_key":null,"enabled":true,"article_limit":20},
{"id":"r","name":"Reuters","type":"reuters","source_key":null,"enabled":true,"article_limit":20}
]`), &sources); err != nil {
t.Fatal(err)
}
repo := &contractRepository{inputs: map[string]UserInput{"user": {Language: "fr", RankingMode: "title", GlobalLimit: 10, Assets: []models.UserAsset{{Symbol: "SPX"}}, Sources: sources}}, saved: map[string][]GenerationRecord{}}
feeds := map[string]*contractScraper{}
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru", "stocktwits", "reuters"} {
feeds[key] = &contractScraper{name: key, articles: []scraper.Article{{Title: key}}}
}
scrapers := map[string]scraper.Scraper{}
for key, feed := range feeds {
scrapers[key] = feed
}
result, err := NewUseCase(Dependencies{Repository: repo, Scrapers: scrapers, Ranker: &contractRanker{}, Summarizer: &contractSummarizer{}}).Generate(context.Background(), "user")
if err != nil || result.Summary == nil {
t.Fatalf("generation result=%+v err=%v", result, err)
}
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru"} {
if len(feeds[key].calls) != 1 {
t.Errorf("target %s calls=%d, want one", key, len(feeds[key].calls))
}
}
for _, key := range []string{"stocktwits", "reuters"} {
if len(feeds[key].calls) != 0 {
t.Errorf("unsupported enabled source %s was invoked %d times", key, len(feeds[key].calls))
}
}
if result.Outcome.TotalCandidates != 3 {
t.Errorf("target candidate count=%d, want 3", result.Outcome.TotalCandidates)
}
}