feat(sources): add managed RSS feeds (#41)

This commit is contained in:
2026-11-25 01:42:27 +01:00
parent 12acb36612
commit 136d9b3b59
38 changed files with 2103 additions and 67 deletions

View 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
}
}
}
}
}
}

View 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
}

View 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")
}
}

View 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()
}

View 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")
}
}

View 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>

View 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>