feat(sources): add managed RSS feeds (#41)
This commit is contained in:
146
backend/internal/ai/quanwen_generation_ticket41_test.go
Normal file
146
backend/internal/ai/quanwen_generation_ticket41_test.go
Normal file
@ -0,0 +1,146 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"github.com/tradarr/backend/internal/scraper/quanwenrss"
|
||||
"github.com/tradarr/backend/internal/sourcefeeds"
|
||||
)
|
||||
|
||||
type rss41Repo struct {
|
||||
input generation.UserInput
|
||||
saved generation.GenerationRecord
|
||||
}
|
||||
|
||||
func (r *rss41Repo) LoadUserInput(context.Context, string) (generation.UserInput, error) {
|
||||
return r.input, nil
|
||||
}
|
||||
func (r *rss41Repo) SaveGeneration(_ context.Context, _ string, record generation.GenerationRecord) error {
|
||||
r.saved = record
|
||||
return nil
|
||||
}
|
||||
|
||||
type rss41Loader struct{}
|
||||
|
||||
func (rss41Loader) SourceFeedURLs(_ context.Context, key string) ([]string, error) {
|
||||
return sourcefeeds.Defaults(key), nil
|
||||
}
|
||||
func TestTicket41RSSMergeThreePassSelectionAndFullSummaryPrompt(t *testing.T) {
|
||||
item := func(title, id, host, body string, full, dated bool) string {
|
||||
date := ""
|
||||
if dated {
|
||||
date = "<pubDate>Fri, 02 Jan 2026 03:04:05 GMT</pubDate>"
|
||||
}
|
||||
field := "description"
|
||||
if full {
|
||||
field = "content:encoded"
|
||||
}
|
||||
return fmt.Sprintf(`<item><title>%s</title><link>https://%s/news/%s</link><guid>%s</guid>%s<%s><![CDATA[<article><p>%s</p></article>]]></%s></item>`, title, host, id, id, date, field, body, field)
|
||||
}
|
||||
literal := item("Watched Company literal", "literal", "www.bloomberg.com", "Synthetic full literal body.", true, true)
|
||||
direct := item("Synthetic direct", "direct", "www.bloomberg.com", "Synthetic full direct body.", true, true)
|
||||
indirect := item("Synthetic indirect", "indirect", "www.bloomberg.com", "Synthetic full indirect body.", true, true)
|
||||
partial := item("Synthetic partial", "partial", "www.bloomberg.com", "Synthetic teaser excluded from Laya.", false, true)
|
||||
investment := item("Synthetic investment", "investment", "www.investing.com", "Synthetic complete investment body.", true, false)
|
||||
urls := sourcefeeds.Defaults(sourcefeeds.Bloomberg)
|
||||
bodies := map[string]string{urls[0]: literal, urls[1]: literal + direct, urls[2]: indirect, urls[3]: partial, sourcefeeds.Defaults(sourcefeeds.Investing)[0]: investment}
|
||||
fetches := 0
|
||||
client := &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
|
||||
fetches++
|
||||
if r.URL.Host != sourcefeeds.Host {
|
||||
t.Fatal("article host was fetched")
|
||||
}
|
||||
status := 200
|
||||
content, ok := bodies[r.URL.String()]
|
||||
if !ok {
|
||||
status = 503
|
||||
}
|
||||
body := `<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel>` + content + `</channel></rss>`
|
||||
return &http.Response{StatusCode: status, Header: make(http.Header), Request: r, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://fixture.invalid"})
|
||||
passes := []string{}
|
||||
ranker.client = &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
|
||||
var payload struct {
|
||||
States []struct{ Title, Content string }
|
||||
Questions map[string]any
|
||||
}
|
||||
if json.NewDecoder(r.Body).Decode(&payload) != nil {
|
||||
t.Fatal("invalid Laya request")
|
||||
}
|
||||
pass := ""
|
||||
for key := range payload.Questions {
|
||||
pass = key
|
||||
}
|
||||
passes = append(passes, pass)
|
||||
results := []any{}
|
||||
for _, state := range payload.States {
|
||||
if strings.Contains(state.Title, "partial") || state.Title == "Watched Company literal" || state.Content == "" {
|
||||
t.Fatal("partial article or literal first-pass selection leaked into Laya")
|
||||
}
|
||||
yes := state.Title == "Synthetic direct" || state.Title == "Synthetic investment"
|
||||
if pass == "indirect_mention" {
|
||||
yes = state.Title == "Synthetic indirect"
|
||||
}
|
||||
probability := 0.1
|
||||
if yes {
|
||||
probability = 0.9
|
||||
}
|
||||
results = append(results, map[string]any{"answers": map[string]any{pass: map[string]any{"type": "noul", "noul": probability, "answer_confidence": 0.99}}, "usage": map[string]any{"truncated": false, "state_tokens_dropped": 0}})
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"results": results, "total_usage": map[string]any{"input_tokens": 1}})
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(string(raw)))}, nil
|
||||
})}
|
||||
bloom, invest := models.SourceBloomberg, models.SourceInvesting
|
||||
repo := &rss41Repo{input: generation.UserInput{Language: "fr", RankingMode: "title_content", SummaryContext: "Synthetic personalized context", SummaryPromptTokenBudget: 250000, GlobalLimit: 4, Assets: []models.UserAsset{{Name: "Watched Company", Symbol: "INTERNAL"}}, Sources: []models.Source{{ID: "b", Type: "bloomberg", SourceKey: &bloom, Enabled: true, ArticleLimit: 4}, {ID: "i", Type: "investing_com", SourceKey: &invest, Enabled: true, ArticleLimit: 1}}}}
|
||||
provider := &incident37Provider{}
|
||||
summarizer := fullGenerationSummarizer{provider: provider, providerName: "openai", model: "gpt-4o-mini"}
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, LayaRanker: ranker, Summarizer: summarizer, Scrapers: map[string]scraper.Scraper{bloom: quanwenrss.New(bloom, rss41Loader{}, client), invest: quanwenrss.New(invest, rss41Loader{}, client)}})
|
||||
result, err := uc.Generate(context.Background(), "fixture-user")
|
||||
if err != nil || result.Summary == nil || provider.calls != 1 || fetches != 6 || len(passes) != 2 || passes[0] != "direct_mention" || passes[1] != "indirect_mention" || result.Outcome.Selected != 4 || result.Outcome.ContentIncomplete != 1 || result.Outcome.Status != "partial" {
|
||||
t.Fatal("RSS source/three-pass/synthesis integration contract failed")
|
||||
}
|
||||
if result.Outcome.SourceStats[0].Candidates != 4 || result.Outcome.SourceStats[0].Feeds == nil || result.Outcome.SourceStats[0].Feeds.Failed != 1 {
|
||||
t.Fatal("dedup/source limit/feed diagnostics are wrong")
|
||||
}
|
||||
var prompt struct {
|
||||
Articles []struct {
|
||||
Title, Content, Source string
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
}
|
||||
Indices []map[string]string
|
||||
Context struct{ Instructions string }
|
||||
}
|
||||
at := strings.Index(provider.prompt, "\n")
|
||||
if at < 0 || json.Unmarshal([]byte(provider.prompt[at+1:]), &prompt) != nil || len(prompt.Articles) != 4 || prompt.Context.Instructions != repo.input.SummaryContext || len(prompt.Indices) != 1 || prompt.Indices[0]["name"] != "Watched Company" {
|
||||
t.Fatal("summary lost full articles/watchlist/context")
|
||||
}
|
||||
nullable := false
|
||||
for _, article := range prompt.Articles {
|
||||
if article.Content == "" || strings.Contains(article.Title, "partial") {
|
||||
t.Fatal("summary received incomplete content")
|
||||
}
|
||||
if article.Source == invest {
|
||||
nullable = article.PublishedAt == nil
|
||||
}
|
||||
}
|
||||
if !nullable {
|
||||
t.Fatal("missing RSS date was invented")
|
||||
}
|
||||
saved, _ := json.Marshal(repo.saved.Outcome)
|
||||
for _, private := range []string{"http://", "https://", "Synthetic full", "Synthetic complete", "Watched Company", "personalized context"} {
|
||||
if strings.Contains(string(saved), private) {
|
||||
t.Fatal("sensitive article data persisted in outcome")
|
||||
}
|
||||
}
|
||||
}
|
||||
127
backend/internal/ai/quanwen_source_limit_ticket41_test.go
Normal file
127
backend/internal/ai/quanwen_source_limit_ticket41_test.go
Normal file
@ -0,0 +1,127 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"github.com/tradarr/backend/internal/scraper/quanwenrss"
|
||||
"github.com/tradarr/backend/internal/sourcefeeds"
|
||||
)
|
||||
|
||||
func TestTicket41RSSSourceLimitKeepsNewestUniqueArticlesThroughLayaAndSummary(t *testing.T) {
|
||||
const limit = 3
|
||||
item := func(id int, dated bool) string {
|
||||
date := ""
|
||||
if dated {
|
||||
date = fmt.Sprintf("<pubDate>Fri, 02 Jan 2026 %02d:00:00 GMT</pubDate>", id)
|
||||
}
|
||||
return fmt.Sprintf(`<item><title>Synthetic candidate %d</title><link>https://www.bloomberg.com/news/articles/2026-01-02/fixture-%d</link><guid>fixture-%d</guid>%s<content:encoded><![CDATA[<p>Synthetic complete body %d.</p>]]></content:encoded></item>`, id, id, id, date, id)
|
||||
}
|
||||
// Eight unique articles across all five feeds, including one undated item.
|
||||
// The first feed itself exceeds N, with its newest item after position N.
|
||||
// Other newest items arrive in later feeds; duplicates must not consume N.
|
||||
urls := sourcefeeds.Defaults(models.SourceBloomberg)
|
||||
bodies := map[string]string{
|
||||
urls[0]: item(1, true) + item(2, true) + item(3, true) + item(7, true),
|
||||
urls[1]: item(1, true) + item(6, true),
|
||||
urls[2]: item(4, true) + item(6, true),
|
||||
urls[3]: item(5, true) + item(2, true),
|
||||
urls[4]: item(8, false),
|
||||
}
|
||||
fetches := 0
|
||||
client := &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
|
||||
body, ok := bodies[r.URL.String()]
|
||||
if !ok || r.URL.Host != sourcefeeds.Host {
|
||||
t.Fatal("request escaped fixture feed routes")
|
||||
}
|
||||
fetches++
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Request: r, Body: io.NopCloser(strings.NewReader(`<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel>` + body + `</channel></rss>`))}, nil
|
||||
})}
|
||||
expected := []string{"Synthetic candidate 7", "Synthetic candidate 6", "Synthetic candidate 5"}
|
||||
layaCalls := 0
|
||||
ranker, err := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://fixture.invalid"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ranker.client = &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
|
||||
layaCalls++
|
||||
var payload struct {
|
||||
States []struct{ Title, Content string }
|
||||
Questions map[string]any
|
||||
}
|
||||
if json.NewDecoder(r.Body).Decode(&payload) != nil {
|
||||
t.Fatal("invalid fixture ranking request")
|
||||
}
|
||||
titles := []string{}
|
||||
results := []any{}
|
||||
for _, state := range payload.States {
|
||||
titles = append(titles, state.Title)
|
||||
results = append(results, map[string]any{"answers": map[string]any{"direct_mention": map[string]any{"type": "noul", "noul": 0.9, "answer_confidence": 0.99}}, "usage": map[string]any{"truncated": false, "state_tokens_dropped": 0}})
|
||||
}
|
||||
if !reflect.DeepEqual(titles, expected) {
|
||||
t.Fatalf("ranking did not receive precisely the N newest unique articles: got %v, want %v", titles, expected)
|
||||
}
|
||||
for i, state := range payload.States {
|
||||
if state.Content != fmt.Sprintf("Synthetic complete body %d.", 7-i) {
|
||||
t.Fatal("ranking received the wrong full body")
|
||||
}
|
||||
}
|
||||
if len(payload.Questions) != 1 || payload.Questions["direct_mention"] == nil {
|
||||
t.Fatal("unexpected selection pass")
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"results": results, "total_usage": map[string]any{"input_tokens": 1}})
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(string(raw)))}, nil
|
||||
})}
|
||||
key := models.SourceBloomberg
|
||||
feed := quanwenrss.New(key, rss41Loader{}, client)
|
||||
pool, err := feed.Scrape(context.Background(), nil)
|
||||
if err != nil || len(pool) != 8 || len(pool) <= limit {
|
||||
t.Fatal("fixture does not establish more than N unique articles after multi-feed merge")
|
||||
}
|
||||
fetches = 0
|
||||
repo := &rss41Repo{input: generation.UserInput{Language: "fr", RankingMode: "title_content", SummaryContext: "Synthetic source limit context", SummaryPromptTokenBudget: 250000, GlobalLimit: 10, Assets: []models.UserAsset{{Name: "Followed Company", Symbol: "INTERNAL"}}, Sources: []models.Source{{ID: "b", Type: "bloomberg", SourceKey: &key, Enabled: true, ArticleLimit: limit}}}}
|
||||
provider := &incident37Provider{}
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, LayaRanker: ranker, Summarizer: fullGenerationSummarizer{provider: provider, providerName: "openai", model: "gpt-4o-mini"}, Scrapers: map[string]scraper.Scraper{key: feed}})
|
||||
result, err := uc.Generate(context.Background(), "fixture-user")
|
||||
if err != nil || result.Summary == nil || fetches != 5 || layaCalls != 1 || provider.calls != 1 {
|
||||
t.Fatal("multi-feed source limit integration did not reach ranking and synthesis")
|
||||
}
|
||||
if result.Outcome.TotalCandidates != limit || result.Outcome.Selected != limit || result.Outcome.ContentComplete != limit || len(result.Outcome.SourceStats) != 1 || result.Outcome.SourceStats[0].Candidates != limit {
|
||||
t.Fatal("source limit was not applied before ranking")
|
||||
}
|
||||
counts := result.Outcome.SourceStats[0].Feeds
|
||||
if counts == nil || counts.Attempted != 5 || counts.Succeeded != 5 || counts.Failed != 0 {
|
||||
t.Fatal("not all configured feeds were merged")
|
||||
}
|
||||
var prompt struct {
|
||||
Articles []struct {
|
||||
Title, Content, Source string
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
}
|
||||
}
|
||||
at := strings.Index(provider.prompt, "\n")
|
||||
if at < 0 || json.Unmarshal([]byte(provider.prompt[at+1:]), &prompt) != nil {
|
||||
t.Fatal("invalid summary prompt")
|
||||
}
|
||||
titles := []string{}
|
||||
for i, a := range prompt.Articles {
|
||||
titles = append(titles, a.Title)
|
||||
expectedDate := time.Date(2026, 1, 2, 7-i, 0, 0, 0, time.UTC)
|
||||
if a.Content != fmt.Sprintf("Synthetic complete body %d.", 7-i) || a.Source != key || a.PublishedAt == nil || !a.PublishedAt.Equal(expectedDate) {
|
||||
t.Fatal("summary lost the newest article's full body/source/observed date")
|
||||
}
|
||||
}
|
||||
if !reflect.DeepEqual(titles, expected) {
|
||||
t.Fatalf("summary did not receive precisely the N newest unique articles: got %v, want %v", titles, expected)
|
||||
}
|
||||
}
|
||||
@ -3,9 +3,12 @@ package handlers
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"github.com/tradarr/backend/internal/sourcefeeds"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
@ -234,7 +237,7 @@ func (h *Handler) ListAIModels(c *gin.Context) {
|
||||
func (h *Handler) ListSources(c *gin.Context) {
|
||||
sources, err := h.repo.ListSources()
|
||||
if err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "source_configuration_unavailable"})
|
||||
return
|
||||
}
|
||||
type sourceResponse struct {
|
||||
@ -244,23 +247,51 @@ func (h *Handler) ListSources(c *gin.Context) {
|
||||
}
|
||||
result := make([]sourceResponse, 0, len(sources))
|
||||
for _, source := range sources {
|
||||
if source.SourceKey != nil && sourcefeeds.Supported(*source.SourceKey) {
|
||||
source.FeedURLs, err = h.repo.SourceFeedURLs(c.Request.Context(), *source.SourceKey)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "source_configuration_unavailable"})
|
||||
return
|
||||
}
|
||||
}
|
||||
result = append(result, sourceResponse{Source: source, Supported: source.Supported(), Operational: source.Operational()})
|
||||
}
|
||||
httputil.OK(c, result)
|
||||
}
|
||||
|
||||
type updateSourceRequest struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ArticleLimit *int `json:"article_limit" binding:"omitempty,min=1,max=200"`
|
||||
FeedURLs json.RawMessage `json:"feed_urls"`
|
||||
Enabled bool `json:"enabled"`
|
||||
ArticleLimit *int `json:"article_limit" binding:"omitempty,min=1,max=200"`
|
||||
}
|
||||
|
||||
func (h *Handler) UpdateSource(c *gin.Context) {
|
||||
var req updateSourceRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
httputil.BadRequest(c, err)
|
||||
var req *updateSourceRequest
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 8192)
|
||||
decoder := json.NewDecoder(c.Request.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&req); err != nil || req == nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "source_configuration_invalid"})
|
||||
return
|
||||
}
|
||||
if err := h.repo.UpdateSource(c.Param("id"), req.Enabled, req.ArticleLimit); err != nil {
|
||||
if err := decoder.Decode(&struct{}{}); err != io.EOF || (req.ArticleLimit != nil && (*req.ArticleLimit < 1 || *req.ArticleLimit > 200)) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "source_configuration_invalid"})
|
||||
return
|
||||
}
|
||||
var feeds *[]string
|
||||
if len(req.FeedURLs) > 0 {
|
||||
var values []string
|
||||
if err := json.Unmarshal(req.FeedURLs, &values); err != nil || values == nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "source_feeds_invalid"})
|
||||
return
|
||||
}
|
||||
feeds = &values
|
||||
}
|
||||
if err := h.repo.UpdateSourceConfig(c.Param("id"), req.Enabled, req.ArticleLimit, feeds); err != nil {
|
||||
if errors.Is(err, sourcefeeds.ErrInvalid) || errors.Is(err, sourcefeeds.ErrUnsupported) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, models.ErrSourceNotSupported) {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "source_not_supported"})
|
||||
return
|
||||
@ -269,7 +300,7 @@ func (h *Handler) UpdateSource(c *gin.Context) {
|
||||
httputil.NotFound(c)
|
||||
return
|
||||
}
|
||||
httputil.InternalError(c, err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "source_configuration_unavailable"})
|
||||
return
|
||||
}
|
||||
httputil.OK(c, gin.H{"ok": true})
|
||||
|
||||
164
backend/internal/api/source_feeds_ticket41_postgres_test.go
Normal file
164
backend/internal/api/source_feeds_ticket41_postgres_test.go
Normal file
@ -0,0 +1,164 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"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"
|
||||
"github.com/tradarr/backend/internal/sourcefeeds"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTicket41MigrationAdminFeedConfigurationIsAtomicAndPrivatePostgres(t *testing.T) {
|
||||
db, err := sql.Open("postgres", postgresTestURL(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
db.SetMaxOpenConns(1)
|
||||
schema := fmt.Sprintf("rss41_%d", time.Now().UnixNano())
|
||||
if _, err = db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
|
||||
if _, err = db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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','admin@example.test','admin','hash'),('user','user@example.test','user','hash')`,
|
||||
`CREATE TABLE sources(id UUID PRIMARY KEY,name TEXT,type TEXT CONSTRAINT sources_type_check CHECK(type IN ('bloomberg','stocktwits','cnbc_business','watcherguru','reuters')),source_key TEXT UNIQUE CONSTRAINT sources_source_key_check CHECK(source_key IN ('bloomberg','yahoo_finance','cnbc_business','watcher_guru')),enabled BOOLEAN,article_limit INTEGER,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`INSERT INTO sources(id,name,type,source_key,enabled,article_limit) VALUES('00000000-0000-0000-0000-000000004101','Bloomberg','bloomberg','bloomberg',false,77),('00000000-0000-0000-0000-000000004102','Yahoo Finance','stocktwits','yahoo_finance',true,83),('00000000-0000-0000-0000-000000004103','CNBC Business','cnbc_business','cnbc_business',true,31)`,
|
||||
`CREATE TABLE articles(id TEXT PRIMARY KEY,source_id UUID REFERENCES sources(id),title TEXT)`,
|
||||
`INSERT INTO articles VALUES('history','00000000-0000-0000-0000-000000004101','Synthetic history')`,
|
||||
} {
|
||||
if _, err = db.Exec(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
raw, err := os.ReadFile("../database/migrations/000021_quanwen_rss.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(`ALTER TABLE sources ADD CONSTRAINT refuse_investing_fixture CHECK(name <> 'Investing.com')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(string(raw)); err == nil {
|
||||
t.Fatal("migration fixture did not fail")
|
||||
}
|
||||
var noChild bool
|
||||
if err = db.QueryRow(`SELECT to_regclass('source_feeds') IS NULL`).Scan(&noChild); err != nil || !noChild {
|
||||
t.Fatal("failed migration leaked child table")
|
||||
}
|
||||
if _, err = db.Exec(`ALTER TABLE sources DROP CONSTRAINT refuse_investing_fixture`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(string(raw)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var count int
|
||||
if err = db.QueryRow(`SELECT count(*) FROM source_feeds`).Scan(&count); err != nil || count != 6 {
|
||||
t.Fatal("default feed migration failed")
|
||||
}
|
||||
if err = db.QueryRow(`SELECT count(*) FROM sources WHERE (source_key='bloomberg' AND article_limit=77 AND NOT enabled) OR (source_key='yahoo_finance' AND article_limit=83 AND enabled) OR (source_key='cnbc_business' AND article_limit=31 AND enabled)`).Scan(&count); err != nil || count != 3 {
|
||||
t.Fatal("migration changed existing source switches/caps")
|
||||
}
|
||||
if err = db.QueryRow(`SELECT count(*) FROM articles WHERE id='history'`).Scan(&count); err != nil || count != 1 {
|
||||
t.Fatal("history changed")
|
||||
}
|
||||
const secret = "ticket41-fixture"
|
||||
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil), secret)
|
||||
token, _ := auth.GenerateToken("admin", "admin@example.test", "admin", secret)
|
||||
user, _ := auth.GenerateToken("user", "user@example.test", "user", secret)
|
||||
request := func(method, path, body, token string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
if token != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
path := "/api/admin/sources/00000000-0000-0000-0000-000000004101"
|
||||
approved := sourcefeeds.Defaults(sourcefeeds.Bloomberg)[2]
|
||||
good, _ := json.Marshal(map[string]any{"enabled": true, "article_limit": 12, "feed_urls": []string{approved}})
|
||||
for _, token := range []string{"", user} {
|
||||
if w := request(http.MethodPut, path, string(good), token); w.Code != 401 && w.Code != 403 {
|
||||
t.Fatal("non-admin mutated feeds")
|
||||
}
|
||||
}
|
||||
for _, body := range []string{
|
||||
`null`, `{"enabled":true,"feed_urls":null}`, `{"enabled":true,"feed_urls":[]}`,
|
||||
`{"enabled":true,"article_limit":0}`, `{"enabled":true,"feed_urls":[""]}`,
|
||||
`{"enabled":true,"feed_urls":["https://127.0.0.1/PRIVATE_CANARY"]}`,
|
||||
`{"enabled":true,"feed_urls":["https://feed.quanwenrss.com/feed/investing-news.xml"]}`,
|
||||
fmt.Sprintf(`{"enabled":true,"feed_urls":[%q,%q]}`, approved, approved),
|
||||
`{"enabled":true,"PRIVATE_CANARY":"ignored"}`, strings.Repeat(" ", 8193) + `{}`,
|
||||
} {
|
||||
w := request(http.MethodPut, path, body, token)
|
||||
if w.Code != 400 || strings.Contains(w.Body.String(), "PRIVATE_CANARY") || strings.Contains(w.Body.String(), "http") {
|
||||
t.Error("invalid admin configuration accepted or response exposed raw values")
|
||||
}
|
||||
}
|
||||
var enabled bool
|
||||
var cap int
|
||||
if err = db.QueryRow(`SELECT enabled,article_limit FROM sources WHERE source_key='bloomberg'`).Scan(&enabled, &cap); err != nil || enabled || cap != 77 {
|
||||
t.Fatal("rejected update was not atomic")
|
||||
}
|
||||
if w := request(http.MethodPut, path, string(good), token); w.Code != 200 {
|
||||
t.Fatal("valid source configuration rejected")
|
||||
}
|
||||
if err = db.QueryRow(`SELECT count(*) FROM source_feeds WHERE source_id='00000000-0000-0000-0000-000000004101'`).Scan(&count); err != nil || count != 1 {
|
||||
t.Fatal("configuration was not replaced")
|
||||
}
|
||||
w := request(http.MethodGet, "/api/admin/sources", "", token)
|
||||
var result struct {
|
||||
Data []models.Source `json:"data"`
|
||||
}
|
||||
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &result) != nil {
|
||||
t.Fatal("admin cannot read saved feed configuration")
|
||||
}
|
||||
found := false
|
||||
for _, s := range result.Data {
|
||||
if s.SourceKey != nil && *s.SourceKey == models.SourceBloomberg {
|
||||
found = s.Enabled && s.ArticleLimit == 12 && len(s.FeedURLs) == 1 && s.FeedURLs[0] == approved
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("saved feed configuration does not round-trip")
|
||||
}
|
||||
if w := request(http.MethodPut, path, `{"enabled":false}`, token); w.Code != 200 {
|
||||
t.Fatal("omitted feed configuration rejected")
|
||||
}
|
||||
values, err := models.NewRepository(db).SourceFeedURLs(context.Background(), models.SourceBloomberg)
|
||||
if err != nil || len(values) != 1 || values[0] != approved {
|
||||
t.Fatal("omitting feeds erased saved configuration")
|
||||
}
|
||||
down, err := os.ReadFile("../database/migrations/000021_quanwen_rss.down.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(string(down)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = db.QueryRow(`SELECT count(*) FROM source_feeds`).Scan(&count); err != nil || count != 2 {
|
||||
t.Fatal("downgrade removed configuration")
|
||||
}
|
||||
if err = db.QueryRow(`SELECT count(*) FROM articles WHERE id='history'`).Scan(&count); err != nil || count != 1 {
|
||||
t.Fatal("downgrade removed history")
|
||||
}
|
||||
|
||||
}
|
||||
30
backend/internal/api/source_feeds_ticket41_test.go
Normal file
30
backend/internal/api/source_feeds_ticket41_test.go
Normal file
@ -0,0 +1,30 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/api/handlers"
|
||||
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTicket41RejectsNullConfigurationsBeforeDatabase(t *testing.T) {
|
||||
const secret = "ticket41-null-fixture"
|
||||
router := gin.New()
|
||||
router.Use(gin.Recovery())
|
||||
handler := handlers.New(nil, &config.Config{JWTSecret: secret}, nil, nil, nil, nil)
|
||||
router.PUT("/api/admin/sources/:id", handler.UpdateSource)
|
||||
for _, body := range []string{`null`, `{"enabled":true,"feed_urls":null}`} {
|
||||
r := httptest.NewRequest(http.MethodPut, "/api/admin/sources/fixture", bytes.NewBufferString(body))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, r)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Error("null source configuration reached repository")
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,2 @@
|
||||
-- Keep source identity, RSS configuration and historical references on downgrade.
|
||||
UPDATE sources SET enabled=false WHERE source_key='investing_com';
|
||||
@ -0,0 +1,36 @@
|
||||
-- Configuration only: preserve source IDs, settings, credentials and history.
|
||||
DO $migration$
|
||||
BEGIN
|
||||
LOCK TABLE sources IN ACCESS EXCLUSIVE MODE;
|
||||
ALTER TABLE sources DROP CONSTRAINT sources_type_check;
|
||||
ALTER TABLE sources ADD CONSTRAINT sources_type_check
|
||||
CHECK(type IN ('bloomberg','stocktwits','reuters','watcherguru','cnbc_business','investing_com'));
|
||||
ALTER TABLE sources DROP CONSTRAINT sources_source_key_check;
|
||||
ALTER TABLE sources ADD CONSTRAINT sources_source_key_check
|
||||
CHECK(source_key IN ('yahoo_finance','bloomberg','watcher_guru','cnbc_business','investing_com'));
|
||||
INSERT INTO sources(id,name,type,enabled,article_limit,source_key)
|
||||
VALUES(gen_random_uuid(),'Investing.com','investing_com',true,20,'investing_com');
|
||||
CREATE TABLE source_feeds (
|
||||
source_id UUID NOT NULL REFERENCES sources(id),
|
||||
position INTEGER NOT NULL CHECK(position >= 0 AND position < 5),
|
||||
url TEXT NOT NULL CHECK(url IN (
|
||||
'https://feed.quanwenrss.com/feed/bloomberg-latest.xml',
|
||||
'https://feed.quanwenrss.com/feed/bloomberg-economics.xml',
|
||||
'https://feed.quanwenrss.com/feed/bloomberg-technology.xml',
|
||||
'https://feed.quanwenrss.com/feed/bloomberg-politics.xml',
|
||||
'https://feed.quanwenrss.com/feed/bloomberg-technology-ai.xml',
|
||||
'https://feed.quanwenrss.com/feed/investing-news.xml')),
|
||||
PRIMARY KEY(source_id,position), UNIQUE(source_id,url)
|
||||
);
|
||||
INSERT INTO source_feeds(source_id,position,url)
|
||||
SELECT s.id,f.position,f.url FROM sources s CROSS JOIN (VALUES
|
||||
(0,'https://feed.quanwenrss.com/feed/bloomberg-latest.xml'),
|
||||
(1,'https://feed.quanwenrss.com/feed/bloomberg-economics.xml'),
|
||||
(2,'https://feed.quanwenrss.com/feed/bloomberg-technology.xml'),
|
||||
(3,'https://feed.quanwenrss.com/feed/bloomberg-politics.xml'),
|
||||
(4,'https://feed.quanwenrss.com/feed/bloomberg-technology-ai.xml')
|
||||
) AS f(position,url) WHERE s.source_key='bloomberg';
|
||||
INSERT INTO source_feeds(source_id,position,url)
|
||||
SELECT id,0,'https://feed.quanwenrss.com/feed/investing-news.xml' FROM sources WHERE source_key='investing_com';
|
||||
END
|
||||
$migration$;
|
||||
@ -29,20 +29,21 @@ type Candidate struct {
|
||||
orderFrozen bool
|
||||
}
|
||||
type SourceStat struct {
|
||||
SourceKey string `json:"source_key"`
|
||||
ContentComplete int `json:"content_complete"`
|
||||
ContentIncomplete int `json:"content_incomplete"`
|
||||
ContentUnavailable int `json:"content_unavailable"`
|
||||
DatesAvailable int `json:"dates_available"`
|
||||
SourceID string `json:"source_id"`
|
||||
SourceType string `json:"source_type"`
|
||||
Status string `json:"status"`
|
||||
Candidates int `json:"candidates"`
|
||||
LayaSelected int `json:"laya_selected"`
|
||||
Selected int `json:"selected"`
|
||||
ArticleLimit int `json:"article_limit"`
|
||||
ContentFallbacks int `json:"content_fallbacks"`
|
||||
FailureCode string `json:"failure_code,omitempty"`
|
||||
Feeds *scraper.FeedCounts `json:"feeds,omitempty"`
|
||||
SourceKey string `json:"source_key"`
|
||||
ContentComplete int `json:"content_complete"`
|
||||
ContentIncomplete int `json:"content_incomplete"`
|
||||
ContentUnavailable int `json:"content_unavailable"`
|
||||
DatesAvailable int `json:"dates_available"`
|
||||
SourceID string `json:"source_id"`
|
||||
SourceType string `json:"source_type"`
|
||||
Status string `json:"status"`
|
||||
Candidates int `json:"candidates"`
|
||||
LayaSelected int `json:"laya_selected"`
|
||||
Selected int `json:"selected"`
|
||||
ArticleLimit int `json:"article_limit"`
|
||||
ContentFallbacks int `json:"content_fallbacks"`
|
||||
FailureCode string `json:"failure_code,omitempty"`
|
||||
}
|
||||
type GenerationOutcome struct {
|
||||
ContentComplete int `json:"content_complete"`
|
||||
@ -220,7 +221,17 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
if *source.SourceKey == models.SourceYahooFinance {
|
||||
sourceSymbols = yahooSymbols(input.Assets)
|
||||
}
|
||||
articles, err = feed.Scrape(ctx, append([]string(nil), sourceSymbols...))
|
||||
if reported, ok := feed.(scraper.ReportedScraper); ok {
|
||||
var counts scraper.FeedCounts
|
||||
articles, counts, err = reported.ScrapeWithDiagnostics(ctx, append([]string(nil), sourceSymbols...))
|
||||
stat.Feeds = &counts
|
||||
if counts.Failed > 0 && counts.Succeeded > 0 {
|
||||
stat.Status = "partial"
|
||||
partial = true
|
||||
}
|
||||
} else {
|
||||
articles, err = feed.Scrape(ctx, append([]string(nil), sourceSymbols...))
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
stat.Status = "failed"
|
||||
|
||||
@ -36,6 +36,7 @@ type UserAsset struct {
|
||||
}
|
||||
|
||||
type Source struct {
|
||||
FeedURLs []string `json:"feed_urls,omitempty"`
|
||||
SourceKey *string `json:"source_key"`
|
||||
ArticleLimit int `json:"article_limit"`
|
||||
ID string `json:"id"`
|
||||
|
||||
@ -149,7 +149,7 @@ func (r *Repository) ListSources() ([]Source, error) {
|
||||
func (r *Repository) GetSourceByType(sourceType string) (*Source, error) {
|
||||
s := &Source{}
|
||||
err := r.db.QueryRow(`
|
||||
SELECT id, name, type, enabled, created_at, article_limit, source_key FROM sources WHERE type=$1 AND source_key IN ('yahoo_finance','bloomberg','cnbc_business')`, sourceType,
|
||||
SELECT id, name, type, enabled, created_at, article_limit, source_key FROM sources WHERE type=$1 AND source_key IN ('yahoo_finance','bloomberg','cnbc_business','investing_com')`, sourceType,
|
||||
).Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit, &s.SourceKey)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
@ -160,22 +160,7 @@ func (r *Repository) GetSourceByType(sourceType string) (*Source, error) {
|
||||
var ErrSourceNotSupported = errors.New("source_not_supported")
|
||||
|
||||
func (r *Repository) UpdateSource(id string, enabled bool, articleLimit *int) error {
|
||||
tx, err := r.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var key *string
|
||||
if err = tx.QueryRow(`SELECT source_key FROM sources WHERE id=$1 FOR UPDATE`, id).Scan(&key); err != nil {
|
||||
return err
|
||||
}
|
||||
if key == nil || !SupportedSourceKey(*key) {
|
||||
return ErrSourceNotSupported
|
||||
}
|
||||
if _, err = tx.Exec(`UPDATE sources SET enabled=$1,article_limit=COALESCE($2,article_limit) WHERE id=$3`, enabled, articleLimit, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
return r.UpdateSourceConfig(id, enabled, articleLimit, nil)
|
||||
}
|
||||
|
||||
// ── Scrape Credentials ─────────────────────────────────────────────────────
|
||||
|
||||
70
backend/internal/models/source_feeds.go
Normal file
70
backend/internal/models/source_feeds.go
Normal file
@ -0,0 +1,70 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/tradarr/backend/internal/sourcefeeds"
|
||||
)
|
||||
|
||||
func (r *Repository) SourceFeedURLs(ctx context.Context, key string) ([]string, error) {
|
||||
if !sourcefeeds.Supported(key) {
|
||||
return nil, sourcefeeds.ErrUnsupported
|
||||
}
|
||||
rows, err := r.db.QueryContext(ctx, `SELECT f.url FROM source_feeds f JOIN sources s ON s.id=f.source_id WHERE s.source_key=$1 ORDER BY f.position LIMIT 6`, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
values := []string{}
|
||||
for rows.Next() {
|
||||
var value string
|
||||
if err := rows.Scan(&value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return sourcefeeds.Validate(key, values)
|
||||
}
|
||||
|
||||
// UpdateSourceConfig replaces configuration and switches in one transaction.
|
||||
// Omitted feeds preserve the saved configuration; an empty replacement is invalid.
|
||||
func (r *Repository) UpdateSourceConfig(id string, enabled bool, limit *int, feeds *[]string) error {
|
||||
if limit != nil && (*limit < 1 || *limit > 200) {
|
||||
return sourcefeeds.ErrInvalid
|
||||
}
|
||||
tx, err := r.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var key *string
|
||||
if err := tx.QueryRow(`SELECT source_key FROM sources WHERE id=$1 FOR UPDATE`, id).Scan(&key); err != nil {
|
||||
return err
|
||||
}
|
||||
if key == nil || !SupportedSourceKey(*key) {
|
||||
return ErrSourceNotSupported
|
||||
}
|
||||
var normalized []string
|
||||
if feeds != nil {
|
||||
normalized, err = sourcefeeds.Validate(*key, *feeds)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err = tx.Exec(`UPDATE sources SET enabled=$1,article_limit=COALESCE($2,article_limit) WHERE id=$3`, enabled, limit, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if feeds != nil {
|
||||
if _, err = tx.Exec(`DELETE FROM source_feeds WHERE source_id=$1`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
for position, value := range normalized {
|
||||
if _, err = tx.Exec(`INSERT INTO source_feeds(source_id,position,url) VALUES($1,$2,$3)`, id, position, value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@ -3,13 +3,14 @@ package models
|
||||
const (
|
||||
SourceYahooFinance = "yahoo_finance"
|
||||
SourceBloomberg = "bloomberg"
|
||||
SourceInvesting = "investing_com"
|
||||
SourceWatcherGuru = "watcher_guru" // Historical identity; no longer executable.
|
||||
SourceCNBCBusiness = "cnbc_business"
|
||||
)
|
||||
|
||||
func SupportedSourceKey(key string) bool {
|
||||
switch key {
|
||||
case SourceYahooFinance, SourceBloomberg, SourceCNBCBusiness:
|
||||
case SourceYahooFinance, SourceBloomberg, SourceCNBCBusiness, SourceInvesting:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
|
||||
34
backend/internal/scraper/quanwenrss/access.go
Normal file
34
backend/internal/scraper/quanwenrss/access.go
Normal file
@ -0,0 +1,34 @@
|
||||
package quanwenrss
|
||||
|
||||
import (
|
||||
"golang.org/x/net/html"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Restriction evidence is inspected before presentation chrome is removed.
|
||||
func bodyRestricted(raw string) bool {
|
||||
t := html.NewTokenizer(strings.NewReader(raw))
|
||||
for {
|
||||
kind := t.Next()
|
||||
if kind == html.ErrorToken {
|
||||
return false
|
||||
}
|
||||
if kind != html.StartTagToken && kind != html.SelfClosingTagToken {
|
||||
continue
|
||||
}
|
||||
token := t.Token()
|
||||
for _, a := range token.Attr {
|
||||
value := strings.ToLower(a.Val)
|
||||
if (a.Key == "data-content-state" && (value == "partial" || value == "incomplete")) || (a.Key == "data-content-truncated" && value == "true") || (a.Key == "data-accessible" && value == "false") {
|
||||
return true
|
||||
}
|
||||
if a.Key == "class" || a.Key == "id" || a.Key == "data-component" || a.Key == "data-testid" || a.Key == "data-test" || a.Key == "src" {
|
||||
for _, marker := range []string{"paywall", "giftarticle", "captcha", "challenge", "cf-chl", "placeholder", "skeleton", "truncated", "partial"} {
|
||||
if strings.Contains(value, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
119
backend/internal/scraper/quanwenrss/collector.go
Normal file
119
backend/internal/scraper/quanwenrss/collector.go
Normal file
@ -0,0 +1,119 @@
|
||||
package quanwenrss
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"github.com/tradarr/backend/internal/scraper/sourcehttp"
|
||||
"github.com/tradarr/backend/internal/sourcefeeds"
|
||||
)
|
||||
|
||||
const MaxSourceBytes = 12 * 1024 * 1024
|
||||
|
||||
var errUnavailable = errors.New("rss_source_unavailable")
|
||||
|
||||
type FeedLoader interface {
|
||||
SourceFeedURLs(context.Context, string) ([]string, error)
|
||||
}
|
||||
type Collector struct {
|
||||
source string
|
||||
loader FeedLoader
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func New(source string, loader FeedLoader, client *http.Client) *Collector {
|
||||
if client == nil {
|
||||
client = &http.Client{Transport: sourcehttp.NewTransport(nil, nil)}
|
||||
}
|
||||
bounded := *client
|
||||
bounded.Timeout = 10 * time.Second
|
||||
// Redirects are revalidated against the exact source/path allowlist; article
|
||||
// hosts and cross-source paths are never delegated to the transport.
|
||||
bounded.CheckRedirect = func(r *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 3 {
|
||||
return http.ErrUseLastResponse
|
||||
}
|
||||
normalized, err := sourcefeeds.Validate(source, []string{r.URL.String()})
|
||||
if err != nil {
|
||||
return http.ErrUseLastResponse
|
||||
}
|
||||
r.URL, _ = url.Parse(normalized[0])
|
||||
return nil
|
||||
}
|
||||
return &Collector{source: source, loader: loader, client: &bounded}
|
||||
}
|
||||
func (c *Collector) Name() string { return c.source }
|
||||
func (c *Collector) Scrape(ctx context.Context, symbols []string) ([]scraper.Article, error) {
|
||||
articles, _, err := c.ScrapeWithDiagnostics(ctx, symbols)
|
||||
return articles, err
|
||||
}
|
||||
func (c *Collector) ScrapeWithDiagnostics(ctx context.Context, _ []string) ([]scraper.Article, scraper.FeedCounts, error) {
|
||||
counts := scraper.FeedCounts{}
|
||||
if c.loader == nil {
|
||||
return nil, counts, errUnavailable
|
||||
}
|
||||
values, err := c.loader.SourceFeedURLs(ctx, c.source)
|
||||
if err != nil {
|
||||
return nil, counts, errUnavailable
|
||||
}
|
||||
values, err = sourcefeeds.Validate(c.source, values)
|
||||
if err != nil {
|
||||
return nil, counts, errUnavailable
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||
defer cancel()
|
||||
pools := [][]scraper.Article{}
|
||||
consumed := 0
|
||||
for _, value := range values {
|
||||
counts.Attempted++
|
||||
articles, n, err := c.fetch(ctx, value, MaxSourceBytes-consumed)
|
||||
consumed += n
|
||||
if err != nil {
|
||||
counts.Failed++
|
||||
continue
|
||||
}
|
||||
counts.Succeeded++
|
||||
pools = append(pools, articles)
|
||||
}
|
||||
if counts.Succeeded == 0 {
|
||||
return nil, counts, errUnavailable
|
||||
}
|
||||
return Merge(pools), counts, nil
|
||||
}
|
||||
func (c *Collector) fetch(ctx context.Context, value string, remaining int) ([]scraper.Article, int, error) {
|
||||
if remaining <= 0 || ctx.Err() != nil {
|
||||
return nil, 0, errUnavailable
|
||||
}
|
||||
// Defense in depth: never trust a stored configuration without validation.
|
||||
if _, err := sourcefeeds.Validate(c.source, []string{value}); err != nil {
|
||||
return nil, 0, errUnavailable
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, value, nil)
|
||||
if err != nil {
|
||||
return nil, 0, errUnavailable
|
||||
}
|
||||
req.Header.Set("Accept", "application/rss+xml, application/xml")
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, 0, errUnavailable
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, 0, errUnavailable
|
||||
}
|
||||
limit := min(remaining, MaxFeedBytes)
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, int64(limit)+1))
|
||||
if err != nil || len(raw) > limit {
|
||||
return nil, len(raw), errUnavailable
|
||||
}
|
||||
articles, err := Parse(raw, c.source)
|
||||
if err != nil {
|
||||
return nil, len(raw), errUnavailable
|
||||
}
|
||||
return articles, len(raw), nil
|
||||
}
|
||||
126
backend/internal/scraper/quanwenrss/collector_test.go
Normal file
126
backend/internal/scraper/quanwenrss/collector_test.go
Normal file
@ -0,0 +1,126 @@
|
||||
package quanwenrss
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"github.com/tradarr/backend/internal/sourcefeeds"
|
||||
)
|
||||
|
||||
type loaderFunc func(context.Context, string) ([]string, error)
|
||||
|
||||
func (f loaderFunc) SourceFeedURLs(ctx context.Context, key string) ([]string, error) {
|
||||
return f(ctx, key)
|
||||
}
|
||||
|
||||
type fixtureTransport func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f fixtureTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
func fixtureRSS(id, date, body string) string {
|
||||
return `<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><item><title>Synthetic ` + id + `</title><link>https://www.bloomberg.com/news/articles/2026-01-02/` + id + `</link><guid>` + id + `</guid><pubDate>` + date + `</pubDate><content:encoded><![CDATA[<article><p>` + body + `</p></article>]]></content:encoded></item></channel></rss>`
|
||||
}
|
||||
func TestCollectorMergesAllConfiguredFeedsWithoutArticleRequestsAndPreservesPartialSuccess(t *testing.T) {
|
||||
urls := sourcefeeds.Defaults(Bloomberg)
|
||||
calls := 0
|
||||
client := &http.Client{Transport: fixtureTransport(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if r.URL.Host != sourcefeeds.Host {
|
||||
t.Fatal("article URL or external host was fetched")
|
||||
}
|
||||
status := 200
|
||||
body := fixtureRSS("shared", "Fri, 02 Jan 2026 03:04:05 GMT", "Synthetic complete shared body.")
|
||||
if r.URL.String() == urls[1] {
|
||||
status = 503
|
||||
body = "PRIVATE raw upstream response"
|
||||
}
|
||||
if r.URL.String() == urls[2] {
|
||||
body = fixtureRSS("newer", "Fri, 02 Jan 2026 04:04:05 GMT", "Synthetic complete newer body.")
|
||||
}
|
||||
return &http.Response{StatusCode: status, Header: make(http.Header), Request: r, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
c := New(Bloomberg, loaderFunc(func(context.Context, string) ([]string, error) { return urls, nil }), client)
|
||||
got, stats, err := c.ScrapeWithDiagnostics(context.Background(), nil)
|
||||
if err != nil || calls != 5 || stats != (scraper.FeedCounts{Attempted: 5, Succeeded: 4, Failed: 1}) || len(got) != 2 || got[0].Title != "Synthetic newer" || scraper.ContentStatus(got[0]) != scraper.ContentComplete {
|
||||
t.Fatal("multi-feed merge/partial outcome failed")
|
||||
}
|
||||
}
|
||||
func TestStoredFeedPolicyIsRevalidatedBeforeAnyTransport(t *testing.T) {
|
||||
for _, urls := range [][]string{nil, {"https://127.0.0.1/private"}, {sourcefeeds.Defaults(Investing)[0]}, {"https://feed.quanwenrss.com/feed/unknown.xml"}} {
|
||||
calls := 0
|
||||
c := New(Bloomberg, loaderFunc(func(context.Context, string) ([]string, error) { return urls, nil }), &http.Client{Transport: fixtureTransport(func(*http.Request) (*http.Response, error) { calls++; return nil, errors.New("PRIVATE") })})
|
||||
if _, _, err := c.ScrapeWithDiagnostics(context.Background(), nil); err == nil || calls != 0 {
|
||||
t.Fatal("invalid saved configuration reached transport")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestFeedRedirectsAndFailuresCannotLeakOrFetchArticleHosts(t *testing.T) {
|
||||
allowed := sourcefeeds.Defaults(Bloomberg)[0]
|
||||
for _, destination := range []string{"https://127.0.0.1/private", "https://www.bloomberg.com/news/articles/private", sourcefeeds.Defaults(Investing)[0], "https://feed.quanwenrss.com/feed/unknown.xml"} {
|
||||
calls := 0
|
||||
c := New(Bloomberg, loaderFunc(func(context.Context, string) ([]string, error) { return []string{allowed}, nil }), &http.Client{Transport: fixtureTransport(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
return &http.Response{StatusCode: 302, Header: http.Header{"Location": []string{destination}}, Request: r, Body: io.NopCloser(strings.NewReader("PRIVATE"))}, nil
|
||||
})})
|
||||
_, s, err := c.ScrapeWithDiagnostics(context.Background(), nil)
|
||||
if err == nil || calls != 1 || s.Failed != 1 || err.Error() != "rss_source_unavailable" {
|
||||
t.Fatal("unsafe redirect or raw upstream error escaped")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestGUIDMergeBridgesAliasesAndSourceSortingKeepsNullDatesLast(t *testing.T) {
|
||||
pools := [][]scraper.Article{}
|
||||
for i := 0; i < 3; i++ {
|
||||
raw := fixtureRSS(fmt.Sprintf("fixture-%d", i), "Fri, 02 Jan 2026 03:04:05 GMT", "Synthetic body.")
|
||||
raw = strings.Replace(raw, fmt.Sprintf("<guid>fixture-%d</guid>", i), "<guid>shared</guid>", 1)
|
||||
got, err := Parse([]byte(raw), Bloomberg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pools = append(pools, got)
|
||||
}
|
||||
got := Merge(pools)
|
||||
if len(got) != 1 || got[0].Title != "Synthetic fixture-0" {
|
||||
t.Fatal("stable GUID did not deduplicate aliases")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceBudgetAndAllFailedFeedsAreExplicitWithoutSilentTruncation(t *testing.T) {
|
||||
calls := 0
|
||||
urls := sourcefeeds.Defaults(Bloomberg)
|
||||
c := New(Bloomberg, loaderFunc(func(context.Context, string) ([]string, error) { return urls, nil }), &http.Client{Transport: fixtureTransport(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Request: r, Body: io.NopCloser(strings.NewReader(strings.Repeat("x", MaxFeedBytes+1)))}, nil
|
||||
})})
|
||||
got, s, err := c.ScrapeWithDiagnostics(context.Background(), nil)
|
||||
if err == nil || got != nil || s.Succeeded != 0 || s.Failed != 5 || calls != 3 {
|
||||
t.Fatal("source byte budget did not stop body reads/requests or return explicit unavailable")
|
||||
}
|
||||
}
|
||||
func TestApprovedSameHostRedirectRemainsBoundedToFeedPaths(t *testing.T) {
|
||||
urls := sourcefeeds.Defaults(Bloomberg)
|
||||
calls := 0
|
||||
c := New(Bloomberg, loaderFunc(func(context.Context, string) ([]string, error) { return urls[:1], nil }), &http.Client{Transport: fixtureTransport(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
header := make(http.Header)
|
||||
status := 200
|
||||
body := fixtureRSS("fixture", "", "Synthetic complete body.")
|
||||
if calls == 1 {
|
||||
status = 302
|
||||
header.Set("Location", urls[1])
|
||||
}
|
||||
if calls > 2 || r.URL.Host != sourcefeeds.Host {
|
||||
t.Fatal("unbounded/external redirect")
|
||||
}
|
||||
return &http.Response{StatusCode: status, Header: header, Request: r, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})})
|
||||
got, s, err := c.ScrapeWithDiagnostics(context.Background(), nil)
|
||||
if err != nil || calls != 2 || s.Succeeded != 1 || len(got) != 1 || got[0].PublishedAt != nil {
|
||||
t.Fatal("approved redirect or nullable RSS date failed")
|
||||
}
|
||||
}
|
||||
420
backend/internal/scraper/quanwenrss/rss.go
Normal file
420
backend/internal/scraper/quanwenrss/rss.go
Normal file
@ -0,0 +1,420 @@
|
||||
// Package quanwenrss parses transient RSS data without following article links.
|
||||
package quanwenrss
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"io"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
const (
|
||||
Investing = "investing_com"
|
||||
Bloomberg = "bloomberg"
|
||||
MaxFeedBytes = 4 * 1024 * 1024
|
||||
MaxDepth = 32
|
||||
MaxItems = 200
|
||||
MaxFieldBytes = 256 * 1024
|
||||
contentNamespace = "http://purl.org/rss/1.0/modules/content/"
|
||||
dcNamespace = "http://purl.org/dc/elements/1.1/"
|
||||
)
|
||||
|
||||
var errInvalid = errors.New("rss_feed_invalid")
|
||||
|
||||
// Parse is entirely offline. The approved QuanwenRSS contract identifies the
|
||||
// namespaced content:encoded field as full text, subject to identity/access limits.
|
||||
func Parse(raw []byte, source string) ([]scraper.Article, error) {
|
||||
if (source != Investing && source != Bloomberg) || len(raw) > MaxFeedBytes {
|
||||
return nil, errInvalid
|
||||
}
|
||||
dec := xml.NewDecoder(bytes.NewReader(raw))
|
||||
depth, channelDepth, itemDepth, fieldDepth, items, channels := 0, 0, 0, 0, 0, 0
|
||||
rootSeen, rootClosed := false, false
|
||||
var fields map[string]string
|
||||
field := ""
|
||||
var text strings.Builder
|
||||
out := []scraper.Article{}
|
||||
for {
|
||||
token, err := dec.Token()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errInvalid
|
||||
}
|
||||
switch t := token.(type) {
|
||||
case xml.Directive:
|
||||
return nil, errInvalid
|
||||
case xml.ProcInst:
|
||||
if t.Target != "xml" || rootSeen {
|
||||
return nil, errInvalid
|
||||
}
|
||||
case xml.StartElement:
|
||||
depth++
|
||||
if depth > MaxDepth || rootClosed {
|
||||
return nil, errInvalid
|
||||
}
|
||||
if depth == 1 {
|
||||
if rootSeen || t.Name.Local != "rss" || t.Name.Space != "" {
|
||||
return nil, errInvalid
|
||||
}
|
||||
rootSeen = true
|
||||
}
|
||||
if depth == 2 && t.Name.Local == "channel" && t.Name.Space == "" {
|
||||
channels++
|
||||
channelDepth = depth
|
||||
if channels != 1 {
|
||||
return nil, errInvalid
|
||||
}
|
||||
}
|
||||
if channelDepth != 0 && depth == channelDepth+1 && t.Name.Local == "item" && t.Name.Space == "" {
|
||||
items++
|
||||
if items > MaxItems {
|
||||
return nil, errInvalid
|
||||
}
|
||||
itemDepth = depth
|
||||
fields = map[string]string{}
|
||||
}
|
||||
if itemDepth != 0 && depth == itemDepth+1 {
|
||||
field = ""
|
||||
if t.Name.Space == "" {
|
||||
switch t.Name.Local {
|
||||
case "title", "link", "description", "pubDate", "guid":
|
||||
field = t.Name.Local
|
||||
}
|
||||
}
|
||||
if t.Name.Local == "encoded" && t.Name.Space == contentNamespace {
|
||||
field = "encoded"
|
||||
}
|
||||
if t.Name.Local == "date" && t.Name.Space == dcNamespace {
|
||||
field = "date"
|
||||
}
|
||||
if field != "" {
|
||||
if _, seen := fields[field]; seen {
|
||||
return nil, errInvalid
|
||||
}
|
||||
fieldDepth = depth
|
||||
text.Reset()
|
||||
}
|
||||
}
|
||||
if field == "encoded" && fieldDepth > 0 && depth > fieldDepth {
|
||||
fields["encoded_nested"] = "true"
|
||||
}
|
||||
case xml.CharData:
|
||||
if depth == 0 && strings.TrimSpace(string(t)) != "" {
|
||||
return nil, errInvalid
|
||||
}
|
||||
if field != "" && fieldDepth != 0 {
|
||||
if text.Len()+len(t) > MaxFieldBytes {
|
||||
return nil, errInvalid
|
||||
}
|
||||
text.Write(t)
|
||||
}
|
||||
case xml.EndElement:
|
||||
if fieldDepth == depth && field != "" {
|
||||
fields[field] = text.String()
|
||||
field = ""
|
||||
fieldDepth = 0
|
||||
text.Reset()
|
||||
}
|
||||
if itemDepth == depth {
|
||||
a, keep, err := article(fields, source)
|
||||
if err != nil {
|
||||
return nil, errInvalid
|
||||
}
|
||||
if keep {
|
||||
out = append(out, a)
|
||||
}
|
||||
itemDepth = 0
|
||||
fields = nil
|
||||
}
|
||||
if channelDepth == depth {
|
||||
channelDepth = 0
|
||||
}
|
||||
depth--
|
||||
if depth == 0 {
|
||||
rootClosed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !rootSeen || !rootClosed || depth != 0 || channels != 1 {
|
||||
return nil, errInvalid
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func article(fields map[string]string, source string) (scraper.Article, bool, error) {
|
||||
a := scraper.Article{Source: source, ContentState: scraper.ContentUnavailable}
|
||||
value := strings.TrimSpace(fields["link"])
|
||||
u, err := url.Parse(value)
|
||||
host := "www.bloomberg.com"
|
||||
if source == Investing {
|
||||
host = "www.investing.com"
|
||||
}
|
||||
if len(fields["guid"]) > 4096 {
|
||||
return a, false, errInvalid
|
||||
}
|
||||
a.FeedGUID = strings.TrimSpace(fields["guid"])
|
||||
if (value == "" && a.FeedGUID == "") || (value != "" && (err != nil || len(value) > 4096 || u.Scheme != "https" || u.User != nil || u.Opaque != "" || !strings.EqualFold(u.Host, host) || u.Path == "" || u.Path == "/")) {
|
||||
return a, false, nil
|
||||
}
|
||||
if len(fields["title"]) > 4096 {
|
||||
return a, false, errInvalid
|
||||
}
|
||||
a.Title, err = cleanText(fields["title"])
|
||||
if err != nil {
|
||||
return a, false, err
|
||||
}
|
||||
if a.Title == "" {
|
||||
return a, false, nil
|
||||
}
|
||||
a.URL = value
|
||||
body := fields["encoded"]
|
||||
if strings.TrimSpace(body) == "" {
|
||||
body = fields["description"]
|
||||
}
|
||||
a.Content, err = cleanText(body)
|
||||
if err != nil {
|
||||
return a, false, err
|
||||
}
|
||||
if strings.TrimSpace(a.Content) != "" && a.Content != a.Title {
|
||||
a.ContentState = scraper.ContentIncomplete
|
||||
if strings.TrimSpace(fields["encoded"]) != "" && fields["encoded_nested"] != "true" && !bodyRestricted(fields["encoded"]) {
|
||||
a.ContentState = scraper.ContentComplete
|
||||
}
|
||||
} else {
|
||||
a.Content = ""
|
||||
}
|
||||
first, second := rssDate(fields["pubDate"]), rssDate(fields["date"])
|
||||
a.PublishedAt = first
|
||||
if first == nil {
|
||||
a.PublishedAt = second
|
||||
} else if second != nil && !first.Equal(*second) {
|
||||
a.PublishedAt = nil
|
||||
}
|
||||
return a, true, nil
|
||||
}
|
||||
func rssDate(value string) *time.Time {
|
||||
value = strings.TrimSpace(value)
|
||||
layouts := []string{time.RFC3339Nano, time.RFC1123Z, time.RFC822Z}
|
||||
if strings.HasSuffix(value, " GMT") || strings.HasSuffix(value, " UTC") {
|
||||
layouts = append(layouts, time.RFC1123, time.RFC822)
|
||||
}
|
||||
for _, layout := range layouts {
|
||||
if t, err := time.Parse(layout, value); err == nil {
|
||||
t = t.UTC()
|
||||
return &t
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func cleanText(value string) (string, error) {
|
||||
// Bound nesting before invoking the HTML tree builder (also for malformed
|
||||
// fragments with many unclosed tags); no DOM/network side effects are used.
|
||||
tokenizer := html.NewTokenizer(strings.NewReader(value))
|
||||
tokenizer.SetMaxBuf(MaxFieldBytes)
|
||||
nesting, tokens := 0, 0
|
||||
for {
|
||||
kind := tokenizer.Next()
|
||||
if kind == html.ErrorToken {
|
||||
if tokenizer.Err() != io.EOF {
|
||||
return "", errInvalid
|
||||
}
|
||||
break
|
||||
}
|
||||
tokens++
|
||||
if tokens > 20000 {
|
||||
return "", errInvalid
|
||||
}
|
||||
if kind == html.StartTagToken {
|
||||
name, _ := tokenizer.TagName()
|
||||
switch string(name) {
|
||||
case "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr":
|
||||
default:
|
||||
nesting++
|
||||
}
|
||||
if nesting > 64 {
|
||||
return "", errInvalid
|
||||
}
|
||||
}
|
||||
if kind == html.EndTagToken && nesting > 0 {
|
||||
nesting--
|
||||
}
|
||||
}
|
||||
doc, err := html.Parse(strings.NewReader(value))
|
||||
if err != nil {
|
||||
return "", errInvalid
|
||||
}
|
||||
var text strings.Builder
|
||||
nodes := 0
|
||||
var walk func(*html.Node, int) error
|
||||
walk = func(n *html.Node, depth int) error {
|
||||
nodes++
|
||||
if depth > 64 || nodes > 20000 {
|
||||
return errInvalid
|
||||
}
|
||||
if n.Type == html.ElementNode {
|
||||
switch n.Data {
|
||||
case "script", "style", "noscript", "iframe", "object", "embed", "form", "nav", "aside", "footer", "header", "svg":
|
||||
return nil
|
||||
}
|
||||
for _, a := range n.Attr {
|
||||
if a.Key == "hidden" || a.Key == "aria-hidden" && a.Val == "true" {
|
||||
return nil
|
||||
}
|
||||
if a.Key == "class" || a.Key == "data-component" {
|
||||
v := strings.ToLower(a.Val)
|
||||
for _, marker := range []string{"advertisement", "related-stories", "placeholder", "skeleton", "promo"} {
|
||||
if strings.Contains(v, marker) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
block := false
|
||||
switch n.Data {
|
||||
case "p", "div", "section", "article", "h1", "h2", "h3", "h4", "h5", "h6", "li", "ul", "ol", "blockquote", "pre", "figcaption", "tr", "br":
|
||||
block = true
|
||||
}
|
||||
if block {
|
||||
text.WriteByte('\n')
|
||||
}
|
||||
if n.Type == html.TextNode {
|
||||
text.WriteString(n.Data)
|
||||
}
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
if err := walk(c, depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if block {
|
||||
text.WriteByte('\n')
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := walk(doc, 0); err != nil {
|
||||
return "", err
|
||||
}
|
||||
lines := []string{}
|
||||
for _, line := range strings.Split(text.String(), "\n") {
|
||||
if line = strings.Join(strings.Fields(line), " "); line != "" {
|
||||
lines = append(lines, line)
|
||||
}
|
||||
}
|
||||
return strings.Join(lines, "\n\n"), nil
|
||||
}
|
||||
|
||||
// Merge preserves the first listing's identity. It does not impose a per-feed
|
||||
// cap: the generation use case applies its source limit after this merged pool.
|
||||
func Merge(feeds [][]scraper.Article) []scraper.Article {
|
||||
|
||||
flat := []scraper.Article{}
|
||||
for _, pool := range feeds {
|
||||
flat = append(flat, pool...)
|
||||
}
|
||||
parents := make([]int, len(flat))
|
||||
for i := range parents {
|
||||
parents[i] = i
|
||||
}
|
||||
var find func(int) int
|
||||
find = func(i int) int {
|
||||
if parents[i] != i {
|
||||
parents[i] = find(parents[i])
|
||||
}
|
||||
return parents[i]
|
||||
}
|
||||
identities := map[string]int{}
|
||||
for i, a := range flat {
|
||||
keys := []string{}
|
||||
if a.URL != "" {
|
||||
keys = append(keys, "url:"+dedupKey(a.URL))
|
||||
}
|
||||
if a.FeedGUID != "" {
|
||||
keys = append(keys, "guid:"+a.Source+":"+a.FeedGUID)
|
||||
}
|
||||
for _, key := range keys {
|
||||
if j, ok := identities[key]; ok {
|
||||
x, y := find(i), find(j)
|
||||
if x < y {
|
||||
parents[y] = x
|
||||
} else {
|
||||
parents[x] = y
|
||||
}
|
||||
} else {
|
||||
identities[key] = i
|
||||
}
|
||||
}
|
||||
}
|
||||
out := []scraper.Article{}
|
||||
groups := map[int]int{}
|
||||
conflicts := map[int]bool{}
|
||||
rank := func(a scraper.Article) int {
|
||||
switch scraper.ContentStatus(a) {
|
||||
case scraper.ContentComplete:
|
||||
return 3
|
||||
case scraper.ContentIncomplete:
|
||||
return 2
|
||||
default:
|
||||
return 1
|
||||
}
|
||||
}
|
||||
for i, a := range flat {
|
||||
group := find(i)
|
||||
index, exists := groups[group]
|
||||
if !exists {
|
||||
groups[group] = len(out)
|
||||
out = append(out, a)
|
||||
continue
|
||||
}
|
||||
first := &out[index]
|
||||
if !conflicts[group] {
|
||||
if first.PublishedAt == nil {
|
||||
first.PublishedAt = a.PublishedAt
|
||||
} else if a.PublishedAt != nil && !first.PublishedAt.Equal(*a.PublishedAt) {
|
||||
first.PublishedAt = nil
|
||||
conflicts[group] = true
|
||||
}
|
||||
}
|
||||
if rank(a) > rank(*first) || rank(a) == rank(*first) && len(a.Content) > len(first.Content) {
|
||||
first.Content = a.Content
|
||||
first.ContentState = a.ContentState
|
||||
first.ContentTruncated = a.ContentTruncated
|
||||
}
|
||||
}
|
||||
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
a, b := out[i].PublishedAt, out[j].PublishedAt
|
||||
if a == nil {
|
||||
return false
|
||||
}
|
||||
if b == nil {
|
||||
return true
|
||||
}
|
||||
return a.After(*b)
|
||||
})
|
||||
return out
|
||||
}
|
||||
func dedupKey(value string) string {
|
||||
u, err := url.Parse(value)
|
||||
if err != nil {
|
||||
return value
|
||||
}
|
||||
u.Fragment = ""
|
||||
u.Host = strings.ToLower(u.Host)
|
||||
q := u.Query()
|
||||
for key := range q {
|
||||
if strings.HasPrefix(strings.ToLower(key), "utm_") {
|
||||
q.Del(key)
|
||||
}
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
147
backend/internal/scraper/quanwenrss/rss_test.go
Normal file
147
backend/internal/scraper/quanwenrss/rss_test.go
Normal file
@ -0,0 +1,147 @@
|
||||
package quanwenrss
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
func TestContractualRSSPreservesCleanFullBodyAndDate(t *testing.T) {
|
||||
raw, err := os.ReadFile("testdata/investing.xml")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := Parse(raw, Investing)
|
||||
if err != nil || len(got) != 2 {
|
||||
t.Fatal("synthetic RSS articles were not parsed")
|
||||
}
|
||||
expected := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
|
||||
if got[0].PublishedAt == nil || !got[0].PublishedAt.Equal(expected) || got[1].PublishedAt != nil {
|
||||
t.Fatal("RSS dates were invented or lost")
|
||||
}
|
||||
if !strings.Contains(got[0].Content, "Final synthetic paragraph.") || strings.Contains(got[0].Content, "EXCLUDED") || strings.Contains(got[0].Content, "<") {
|
||||
t.Fatal("RSS editorial body was not cleaned")
|
||||
}
|
||||
if scraper.ContentStatus(got[0]) != scraper.ContentComplete || scraper.ContentStatus(got[1]) != scraper.ContentIncomplete {
|
||||
t.Fatal("contractual encoded body or description completeness is wrong")
|
||||
}
|
||||
}
|
||||
func TestMergeDeduplicatesBeforeApplyingSourceLimitAndKeepsStableListing(t *testing.T) {
|
||||
date := time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC)
|
||||
listed := "https://www.bloomberg.com/news/articles/2026-01-02/synthetic"
|
||||
first := []scraper.Article{{Title: "Synthetic initial", URL: listed, Content: "Synthetic teaser", ContentState: scraper.ContentIncomplete}, {Title: "Synthetic second", URL: listed + "-second"}}
|
||||
second := []scraper.Article{{Title: "Synthetic duplicate", URL: listed + "?utm_source=fixture", Content: "Synthetic longer but unproven body", ContentState: scraper.ContentIncomplete, PublishedAt: &date}, {Title: "Synthetic third", URL: listed + "-third"}}
|
||||
got := Merge([][]scraper.Article{first, second})
|
||||
if len(got) != 3 || got[0].URL != listed || got[0].Title != "Synthetic initial" || got[0].PublishedAt == nil {
|
||||
t.Fatal("source merge lost stable association or consumed source capacity with duplicate")
|
||||
}
|
||||
if scraper.ContentStatus(got[0]) == scraper.ContentComplete {
|
||||
t.Fatal("merge invented completeness")
|
||||
}
|
||||
}
|
||||
func TestRSSRejectsUnsafeOrOversizedDocumentsWithoutRawErrors(t *testing.T) {
|
||||
for _, raw := range []string{
|
||||
`<!DOCTYPE rss [<!ENTITY p "PRIVATE_CANARY">]><rss><channel/></rss>`,
|
||||
`<rss><channel><item>`, strings.Repeat("x", MaxFeedBytes+1),
|
||||
`<rss><channel>` + strings.Repeat("<x>", MaxDepth+1) + strings.Repeat("</x>", MaxDepth+1) + `</channel></rss>`,
|
||||
} {
|
||||
_, err := Parse([]byte(raw), Investing)
|
||||
if err == nil || strings.Contains(err.Error(), "PRIVATE") || strings.Contains(err.Error(), "http") {
|
||||
t.Fatal("RSS bound or sanitized error contract failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestRSSArticleReferencesAreNotTransportTargets(t *testing.T) {
|
||||
raw := `<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel>`
|
||||
for _, u := range []string{"https://127.0.0.1/private", "http://www.investing.com/news/fixture", "https://www.investing.com.evil.invalid/news/fixture", "https://private:secret@www.investing.com/news/fixture", "https://www.bloomberg.com/news/articles/fixture"} {
|
||||
raw += `<item><title>Synthetic</title><link>` + u + `</link></item>`
|
||||
}
|
||||
raw += `</channel></rss>`
|
||||
got, err := Parse([]byte(raw), Investing)
|
||||
if err != nil || len(got) != 0 {
|
||||
t.Fatal("unsafe RSS association was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBloombergSyntheticFixtureAndNamespacedContent(t *testing.T) {
|
||||
raw, err := os.ReadFile("testdata/bloomberg.xml")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := Parse(raw, Bloomberg)
|
||||
if err != nil || len(got) != 1 || got[0].PublishedAt == nil || scraper.ContentStatus(got[0]) != scraper.ContentComplete {
|
||||
t.Fatal("Bloomberg RSS content/date contract failed")
|
||||
}
|
||||
// A lookalike extension cannot assert or replace trusted content:encoded.
|
||||
fake := `<rss xmlns:fake="urn:fixture"><channel><item><title>Synthetic headline</title><link>https://www.investing.com/news/synthetic-fixture</link><description>Synthetic teaser.</description><fake:encoded>Untrusted extension payload</fake:encoded></item></channel></rss>`
|
||||
got, err = Parse([]byte(fake), Investing)
|
||||
if err != nil || len(got) != 1 || got[0].Content != "Synthetic teaser." {
|
||||
t.Fatal("untrusted encoded namespace was accepted")
|
||||
}
|
||||
}
|
||||
func TestRSSItemFieldAndHTMLLimitsFailWithoutTruncation(t *testing.T) {
|
||||
item := `<item><title>Synthetic headline</title><link>https://www.investing.com/news/synthetic-fixture</link></item>`
|
||||
for _, raw := range []string{
|
||||
`<rss><channel>` + strings.Repeat(item, MaxItems+1) + `</channel></rss>`,
|
||||
`<rss><channel><item><title>` + strings.Repeat("x", MaxFieldBytes+1) + `</title></item></channel></rss>`,
|
||||
`<rss><channel><item><description><![CDATA[` + strings.Repeat("<div>", 1000) + `]]></description><title>Synthetic</title><link>https://www.investing.com/news/synthetic-fixture</link></item></channel></rss>`,
|
||||
`<rss><channel><item><title>A</title><title>B</title></item></channel></rss>`,
|
||||
`<rss><channel/><channel/></rss>`,
|
||||
} {
|
||||
if _, err := Parse([]byte(raw), Investing); err == nil || err.Error() != "rss_feed_invalid" {
|
||||
t.Fatal("RSS resource limit/ambiguity was ignored or raw error escaped")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestMergeKeepsSemanticLinksDistinctAndRemovesConflictingDates(t *testing.T) {
|
||||
first := time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC)
|
||||
second := first.Add(time.Hour)
|
||||
link := "https://www.investing.com/news/fixture?story=1"
|
||||
got := Merge([][]scraper.Article{{{URL: link, PublishedAt: &first}}, {{URL: link + "&utm_source=fixture", PublishedAt: &second}}, {{URL: link, PublishedAt: &first}, {URL: "https://www.investing.com/news/fixture?story=2"}}})
|
||||
if len(got) != 2 || got[0].PublishedAt != nil {
|
||||
t.Fatal("semantic identities were conflated or conflicting date reinstated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket41ContractualEncodedBodyCanBeCompleteButMarkersCannot(t *testing.T) {
|
||||
for _, source := range []string{Bloomberg, Investing} {
|
||||
file := "testdata/bloomberg.xml"
|
||||
if source == Investing {
|
||||
file = "testdata/investing.xml"
|
||||
}
|
||||
raw, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
full, err := Parse(raw, source)
|
||||
if err != nil || len(full) == 0 || scraper.ContentStatus(full[0]) != scraper.ContentComplete {
|
||||
t.Fatal("contractual full-body field was not recognized")
|
||||
}
|
||||
for _, marker := range []string{`<div class="paywall"></div>`, `<div id="challengeGate"></div>`, `<div data-content-state="partial"></div>`, `<div data-content-truncated="true"></div>`, `<div class="placeholder"></div>`} {
|
||||
blocked := strings.Replace(string(raw), "</article>", marker+"</article>", 1)
|
||||
got, err := Parse([]byte(blocked), source)
|
||||
if err != nil || len(got) == 0 || scraper.ContentStatus(got[0]) == scraper.ContentComplete {
|
||||
t.Fatal("restriction/partial marker was promoted to complete")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStableGUIDOnlyItemsDoNotInventLinksOrCollapseUnrelatedItems(t *testing.T) {
|
||||
raw := `<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel>`
|
||||
for _, id := range []string{"opaque-one", "opaque-two", "opaque-one"} {
|
||||
raw += `<item><guid>` + id + `</guid><title>Synthetic headline</title><content:encoded><![CDATA[<p>Synthetic complete body.</p>]]></content:encoded></item>`
|
||||
}
|
||||
raw += `</channel></rss>`
|
||||
got, err := Parse([]byte(raw), Investing)
|
||||
if err != nil || len(got) != 3 {
|
||||
t.Fatal("stable GUID-only items lost")
|
||||
}
|
||||
merged := Merge([][]scraper.Article{got})
|
||||
if len(merged) != 2 || merged[0].URL != "" || scraper.ContentStatus(merged[0]) != scraper.ContentComplete {
|
||||
t.Fatal("opaque identity invented URL or collapsed distinct GUIDs")
|
||||
}
|
||||
}
|
||||
5
backend/internal/scraper/quanwenrss/testdata/bloomberg.xml
vendored
Normal file
5
backend/internal/scraper/quanwenrss/testdata/bloomberg.xml
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0"?>
|
||||
<!-- Synthetic fixture only. Representative approved content:encoded full-text contract. -->
|
||||
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||
<channel><item><title>Synthetic Bloomberg headline</title><link>https://www.bloomberg.com/news/articles/2026-01-02/synthetic-fixture</link><dc:date>2026-01-02T03:04:05Z</dc:date><content:encoded><![CDATA[<article><p>Synthetic first paragraph.</p><p>Final synthetic paragraph.</p></article>]]></content:encoded></item></channel>
|
||||
</rss>
|
||||
7
backend/internal/scraper/quanwenrss/testdata/investing.xml
vendored
Normal file
7
backend/internal/scraper/quanwenrss/testdata/investing.xml
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
<?xml version="1.0"?>
|
||||
<!-- Synthetic fixture only; no publisher HTML or article text. -->
|
||||
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
|
||||
<channel>
|
||||
<item><title>Synthetic editorial headline</title><link>https://www.investing.com/news/stock-market-news/synthetic-fixture</link><pubDate>Fri, 02 Jan 2026 03:04:05 GMT</pubDate><description>Synthetic teaser.</description><content:encoded><![CDATA[<article><h2>Synthetic heading.</h2><p>Synthetic first paragraph.</p><script>EXCLUDED script</script><nav>EXCLUDED navigation</nav><aside>EXCLUDED sidebar</aside><div class="advertisement">EXCLUDED ad</div><p>Final synthetic paragraph.</p></article>]]></content:encoded></item>
|
||||
<item><title>Synthetic second headline</title><link>https://www.investing.com/news/economy-news/synthetic-second</link><pubDate>unreliable fixture date</pubDate><description><![CDATA[<p>Synthetic teaser only.</p>]]></description></item>
|
||||
</channel></rss>
|
||||
@ -26,6 +26,7 @@ func ContentStatus(a Article) string {
|
||||
}
|
||||
|
||||
type Article struct {
|
||||
FeedGUID string
|
||||
ContentState string
|
||||
Source string
|
||||
Title string
|
||||
@ -41,6 +42,16 @@ type Scraper interface {
|
||||
Scrape(ctx context.Context, symbols []string) ([]Article, error)
|
||||
}
|
||||
|
||||
// FeedCounts contains only aggregate fetch outcomes, never feed/article values.
|
||||
type FeedCounts struct {
|
||||
Attempted int `json:"attempted"`
|
||||
Succeeded int `json:"succeeded"`
|
||||
Failed int `json:"failed"`
|
||||
}
|
||||
type ReportedScraper interface {
|
||||
ScrapeWithDiagnostics(context.Context, []string) ([]Article, FeedCounts, error)
|
||||
}
|
||||
|
||||
// ArticleEnricher is an optional, transient enrichment port. Generation calls
|
||||
// it only after source limits, never for the full collected list.
|
||||
type ArticleEnricher interface {
|
||||
|
||||
@ -70,7 +70,7 @@ func NewTransport(resolver Resolver, dial DialFunc) *http.Transport {
|
||||
return nil, errUnavailable
|
||||
}
|
||||
switch strings.ToLower(host) {
|
||||
case "finance.yahoo.com", "feeds.finance.yahoo.com", "www.cnbc.com":
|
||||
case "finance.yahoo.com", "feeds.finance.yahoo.com", "www.cnbc.com", "feed.quanwenrss.com":
|
||||
default:
|
||||
return nil, errUnavailable
|
||||
}
|
||||
|
||||
@ -24,7 +24,7 @@ func (f resolverFunc) LookupNetIP(c context.Context, n, h string) ([]netip.Addr,
|
||||
return f(c, n, h)
|
||||
}
|
||||
func TestForbiddenDNSAnswersNeverDial(t *testing.T) {
|
||||
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com"} {
|
||||
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com", "feed.quanwenrss.com"} {
|
||||
for _, value := range []string{"0.0.0.0", "10.0.0.1", "100.64.0.1", "127.0.0.1", "169.254.1.1", "172.16.0.1", "192.168.0.1", "192.0.0.9", "192.0.2.1", "198.18.0.1", "198.51.100.1", "203.0.113.1", "224.0.0.1", "240.0.0.1", "255.255.255.255", "::", "::1", "fc00::1", "fe80::1", "ff02::1", "2001:db8::1", "2002:0808:0808::1", "64:ff9b::808:808", "2001::1", "3fff::1", "::ffff:127.0.0.1"} {
|
||||
t.Run(host+"/"+value, func(t *testing.T) {
|
||||
dials := 0
|
||||
@ -67,7 +67,7 @@ func TestDNSFailsClosedAndNumericPinning(t *testing.T) {
|
||||
}
|
||||
}
|
||||
func TestPinnedTLSRetainsSNIAndHost(t *testing.T) {
|
||||
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com"} {
|
||||
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com", "feed.quanwenrss.com"} {
|
||||
t.Run(host, func(t *testing.T) {
|
||||
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
template := &x509.Certificate{SerialNumber: big.NewInt(1), DNSNames: []string{host}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
|
||||
@ -116,7 +116,7 @@ func TestPinnedTLSRetainsSNIAndHost(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestEveryNewConnectionRevalidatesDNS(t *testing.T) {
|
||||
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com"} {
|
||||
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com", "feed.quanwenrss.com"} {
|
||||
lookups, dials := 0, 0
|
||||
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) {
|
||||
lookups++
|
||||
|
||||
65
backend/internal/sourcefeeds/config.go
Normal file
65
backend/internal/sourcefeeds/config.go
Normal file
@ -0,0 +1,65 @@
|
||||
// Package sourcefeeds defines the closed, shared admin/runtime RSS allowlist.
|
||||
package sourcefeeds
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const Bloomberg = "bloomberg"
|
||||
const Investing = "investing_com"
|
||||
const Host = "feed.quanwenrss.com"
|
||||
const MaxFeeds = 5
|
||||
|
||||
var ErrInvalid = errors.New("source_feeds_invalid")
|
||||
var ErrUnsupported = errors.New("source_feeds_not_supported")
|
||||
|
||||
func Supported(source string) bool { return source == Bloomberg || source == Investing }
|
||||
func Defaults(source string) []string {
|
||||
var paths []string
|
||||
switch source {
|
||||
case Bloomberg:
|
||||
paths = []string{"bloomberg-latest.xml", "bloomberg-economics.xml", "bloomberg-technology.xml", "bloomberg-politics.xml", "bloomberg-technology-ai.xml"}
|
||||
case Investing:
|
||||
paths = []string{"investing-news.xml"}
|
||||
}
|
||||
out := make([]string, 0, len(paths))
|
||||
for _, path := range paths {
|
||||
out = append(out, "https://"+Host+"/feed/"+path)
|
||||
}
|
||||
return out
|
||||
}
|
||||
func Validate(source string, values []string) ([]string, error) {
|
||||
if !Supported(source) {
|
||||
return nil, ErrUnsupported
|
||||
}
|
||||
allowed := Defaults(source)
|
||||
if len(values) == 0 || len(values) > len(allowed) {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
out := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
if len(value) > 256 || value != strings.TrimSpace(value) || strings.Contains(value, "#") {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
u, err := url.Parse(value)
|
||||
if err != nil || u.Scheme != "https" || (!strings.EqualFold(u.Host, Host) && !strings.EqualFold(u.Host, Host+":443")) || u.User != nil || u.Opaque != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.RawPath != "" || (u.Port() != "" && u.Port() != "443") {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
normalized := "https://" + Host + u.Path
|
||||
matched := false
|
||||
for _, known := range allowed {
|
||||
if normalized == known {
|
||||
matched = true
|
||||
}
|
||||
}
|
||||
if !matched || seen[normalized] {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
seen[normalized] = true
|
||||
out = append(out, normalized)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
28
backend/internal/sourcefeeds/config_test.go
Normal file
28
backend/internal/sourcefeeds/config_test.go
Normal file
@ -0,0 +1,28 @@
|
||||
package sourcefeeds
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAdminAndRuntimeUseClosedSourceSpecificFeedAllowlist(t *testing.T) {
|
||||
for _, source := range []string{Bloomberg, Investing} {
|
||||
defaults := Defaults(source)
|
||||
if _, err := Validate(source, defaults); err != nil {
|
||||
t.Fatal("approved defaults rejected")
|
||||
}
|
||||
for _, bad := range [][]string{nil, {""}, {"http://" + Host + "/feed/investing-news.xml"}, {"https://127.0.0.1/feed/investing-news.xml"}, {"https://" + Host + ".evil.invalid/feed/investing-news.xml"}, {"https://user:secret@" + Host + "/feed/investing-news.xml"}, {"https://" + Host + ":444/feed/investing-news.xml"}, {"https://" + Host + "/feed/unknown.xml"}, {defaults[0] + "?key=secret"}, {defaults[0] + "#"}, {defaults[0], defaults[0]}, {"https://" + Host + "/feed/%69nvesting-news.xml"}} {
|
||||
if _, err := Validate(source, bad); err != ErrInvalid {
|
||||
t.Fatal("invalid source feed configuration accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, err := Validate(Bloomberg, Defaults(Investing)); err != ErrInvalid {
|
||||
t.Fatal("cross-source feed accepted")
|
||||
}
|
||||
if _, err := Validate("yahoo_finance", Defaults(Investing)); err != ErrUnsupported {
|
||||
t.Fatal("non-RSS source accepted feed mutation")
|
||||
}
|
||||
original := Defaults(Bloomberg)
|
||||
original[0] = "private"
|
||||
if Defaults(Bloomberg)[0] == "private" {
|
||||
t.Fatal("mutable allowlist")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user