feat(scraper): bound article enrichment diagnostics (#40)
This commit is contained in:
@ -0,0 +1,82 @@
|
||||
package articlecontent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestObservedYahooRedirectIdentities(t *testing.T) {
|
||||
initial := "https://finance.yahoo.com/news/fixture-initial.html"
|
||||
final := "https://finance.yahoo.com/news/fixture-final.html"
|
||||
for _, tc := range []struct {
|
||||
name, destination, identity string
|
||||
complete bool
|
||||
}{
|
||||
{"canonical_initial", final, initial, true}, {"canonical_final", final, final, true},
|
||||
{"unobserved", final, "https://finance.yahoo.com/news/fixture-other.html", false},
|
||||
{"third_party_identity", final, "https://example.invalid/fixture.html", false},
|
||||
{"external_redirect", "https://example.invalid/fixture.html", initial, false},
|
||||
{"upgrade_before_fetch", "http://finance.yahoo.com/news/fixture-final.html", initial, true},
|
||||
} {
|
||||
for _, metadata := range []string{"canonical", "NewsArticle"} {
|
||||
t.Run(tc.name+metadata, func(t *testing.T) {
|
||||
calls := 0
|
||||
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
h := make(http.Header)
|
||||
status := 200
|
||||
body := ""
|
||||
if calls == 1 {
|
||||
status = 302
|
||||
h.Set("Location", tc.destination)
|
||||
} else {
|
||||
if r.URL.String() != final {
|
||||
t.Fatal("untrusted redirect fetched")
|
||||
}
|
||||
body = `<link rel="canonical" href="` + tc.identity + `">`
|
||||
if metadata == "NewsArticle" {
|
||||
body = `<script type="application/ld+json">{"@type":"NewsArticle","url":"` + tc.identity + `"}</script>`
|
||||
}
|
||||
body += `<article><div class="caas-body"><p>Synthetic full editorial body.</p></div></article>`
|
||||
}
|
||||
return &http.Response{StatusCode: status, Header: h, Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
|
||||
})}
|
||||
got, err := Enrich(context.Background(), client, "yahoo_finance", []scraper.Article{{URL: initial}})
|
||||
if err != nil || (got[0].ContentState == scraper.ContentComplete) != tc.complete || got[0].URL != initial {
|
||||
t.Fatal("redirect identity contract failed")
|
||||
}
|
||||
if strings.Contains(tc.name, "redirect") || tc.name == "downgrade" {
|
||||
if calls != 1 {
|
||||
t.Fatal("forbidden redirect fetched")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCNBCEditorialMarkerScopeAndGlobalChallenges(t *testing.T) {
|
||||
url := "https://www.cnbc.com/2026/01/02/fixture.html"
|
||||
root := `<div data-module="ArticleBody"><p>Synthetic complete editorial body.</p></div>`
|
||||
for _, tc := range []struct {
|
||||
name, html string
|
||||
state string
|
||||
}{
|
||||
{"detached_newsletter", root + `<aside class="newsletter-paywall"></aside>`, scraper.ContentComplete},
|
||||
{"article_sibling_paywall", `<article>` + root + `<div class="paywall"></div></article>`, scraper.ContentIncomplete},
|
||||
{"wrapper_partial", `<article data-content-truncated="true">` + root + `</article>`, scraper.ContentIncomplete},
|
||||
{"global_challenge", root + `<div id="challenge-page"></div>`, scraper.ContentIncomplete},
|
||||
{"replacement_challenge", `<div id="px-captcha"></div>`, scraper.ContentUnavailable},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := ExtractHTML("cnbc_business", url, []byte(`<link rel="canonical" href="`+url+`">`+tc.html))
|
||||
if got.ContentState != tc.state {
|
||||
t.Fatal("editorial/challenge scope contract failed")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,64 @@
|
||||
package articlecontent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
func TestCandidateBodyLengthIsCountedBeforeIdentityRejection(t *testing.T) {
|
||||
lengths := []int{0, 1, 500, 501, 2000, 2001}
|
||||
pages := make(map[string]string, len(lengths))
|
||||
articles := make([]scraper.Article, 0, len(lengths))
|
||||
rawValues := []string{"candidate_title_canary", "placeholder_text_canary"}
|
||||
for i, n := range lengths {
|
||||
listed := "https://finance.yahoo.com/news/candidate-listed-" + string(rune('a'+i)) + ".html"
|
||||
canonical := "https://finance.yahoo.com/news/candidate-canonical-mismatch-" + string(rune('a'+i)) + ".html"
|
||||
og := "https://finance.yahoo.com/news/candidate-og-mismatch-" + string(rune('a'+i)) + ".html"
|
||||
jsonld := "https://finance.yahoo.com/news/candidate-jsonld-mismatch-" + string(rune('a'+i)) + ".html"
|
||||
candidate := strings.Repeat("x", n)
|
||||
rawValues = append(rawValues, listed, canonical, og, jsonld)
|
||||
if len(candidate) >= 10 {
|
||||
rawValues = append(rawValues, candidate)
|
||||
}
|
||||
pages[listed] = `<link rel="canonical" href="` + canonical + `"><meta property="og:url" content="` + og + `"><script type="application/ld+json">{"@type":"NewsArticle","url":"` + jsonld + `"}</script><div class="caas-body"><p>` + candidate + `</p><div class="article-placeholder">placeholder_text_canary</div></div>`
|
||||
articles = append(articles, scraper.Article{URL: listed, Title: "candidate_title_canary"})
|
||||
}
|
||||
ctx, meter := scraper.WithFetchMetrics(context.Background())
|
||||
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
body, ok := pages[r.URL.String()]
|
||||
if !ok {
|
||||
return nil, io.ErrUnexpectedEOF
|
||||
}
|
||||
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
|
||||
})}
|
||||
got, err := Enrich(ctx, client, "yahoo_finance", articles)
|
||||
metrics := meter.Finish()
|
||||
if err != nil || len(got) != len(lengths) {
|
||||
t.Fatal("fixture enrichment failed")
|
||||
}
|
||||
for i, article := range got {
|
||||
if article.Content != "" || scraper.ContentStatus(article) != scraper.ContentUnavailable {
|
||||
t.Fatalf("identity-rejected fixture %d unexpectedly retained extracted content", i)
|
||||
}
|
||||
}
|
||||
if metrics.Identity.Mismatch != len(lengths) || metrics.Length.Zero != len(lengths) || metrics.Content.Unavailable != len(lengths) {
|
||||
t.Fatal("identity rejection changed the unavailable/empty extracted-content counters")
|
||||
}
|
||||
data := requireAnonymousAggregate(t, metrics, rawValues...)
|
||||
for _, tc := range []struct {
|
||||
bucket string
|
||||
want int
|
||||
}{
|
||||
{"0", 1},
|
||||
{"1-500", 2},
|
||||
{"501-2000", 2},
|
||||
{">2000", 1},
|
||||
} {
|
||||
requireAggregateCounter(t, data, []string{"candidate_body_characters", tc.bucket}, tc.want)
|
||||
}
|
||||
}
|
||||
76
backend/internal/scraper/articlecontent/candidate_length.go
Normal file
76
backend/internal/scraper/articlecontent/candidate_length.go
Normal file
@ -0,0 +1,76 @@
|
||||
package articlecontent
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
// candidateBodyLength measures a unique recognized editorial root without
|
||||
// constructing or retaining candidate text. It runs before identity rejection,
|
||||
// never feeds extraction, and saturates at the largest bucket's lower bound.
|
||||
func candidateBodyLength(root *html.Node) int {
|
||||
total, chunk, paragraphs := 0, 0, 0
|
||||
pendingSpace := false
|
||||
flush := func() {
|
||||
if chunk > 0 {
|
||||
if paragraphs > 0 {
|
||||
total += 2
|
||||
} // Existing editorial paragraph separator.
|
||||
total += chunk
|
||||
paragraphs++
|
||||
}
|
||||
chunk = 0
|
||||
pendingSpace = false
|
||||
}
|
||||
var walk func(*html.Node)
|
||||
walk = func(n *html.Node) {
|
||||
if total+chunk > 2000 || excluded(n) {
|
||||
return
|
||||
}
|
||||
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id") + " " + attr(n, "data-component"))
|
||||
if strings.Contains(marker, "placeholder") || strings.Contains(marker, "skeleton") {
|
||||
return
|
||||
}
|
||||
if n.Type == html.TextNode {
|
||||
for _, r := range n.Data {
|
||||
if unicode.IsSpace(r) {
|
||||
if chunk > 0 {
|
||||
pendingSpace = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if pendingSpace {
|
||||
chunk++
|
||||
pendingSpace = false
|
||||
}
|
||||
chunk++
|
||||
if total+chunk > 2000 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
block := false
|
||||
switch n.Data {
|
||||
case "p", "div", "section", "h1", "h2", "h3", "h4", "h5", "h6", "li", "ul", "ol", "blockquote", "pre", "figcaption", "table", "tr", "td", "th":
|
||||
block = true
|
||||
}
|
||||
if block {
|
||||
flush()
|
||||
}
|
||||
if n.Data == "br" && chunk > 0 {
|
||||
pendingSpace = true
|
||||
}
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
walk(c)
|
||||
}
|
||||
if block {
|
||||
flush()
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
flush()
|
||||
return min(total, 2001)
|
||||
}
|
||||
@ -0,0 +1,49 @@
|
||||
package articlecontent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
func TestCandidateLengthUnicodeBucketsAndExcludedText(t *testing.T) {
|
||||
for _, source := range []string{"yahoo_finance", "cnbc_business"} {
|
||||
pages := map[string]string{}
|
||||
root, base := "caas-body", "https://finance.yahoo.com/news/fixture-"
|
||||
if source == "cnbc_business" {
|
||||
root = "ArticleBody-articleBody"
|
||||
base = "https://www.cnbc.com/2026/02/01/fixture-"
|
||||
}
|
||||
for i, n := range []int{0, 1, 500, 501, 2000, 2001} {
|
||||
target := fmt.Sprintf("%s%d.html", base, i)
|
||||
pages[target] = `<link rel="canonical" href="` + base + `other.html"><div class="` + root + `"><p>` + strings.Repeat("界", n) + `</p><nav>Excluded navigation</nav><div hidden>Excluded hidden</div><script>Excluded script</script><div class="skeleton">Excluded skeleton</div><div id="article-placeholder">Excluded placeholder</div></div><p>Excluded outside text</p>`
|
||||
}
|
||||
m := fetchMetricsForFixturePages(t, source, pages)
|
||||
if !m.CandidateBodySupported || m.CandidateLength != (scraper.LengthCounts{Zero: 1, Small: 2, Medium: 2, Large: 1}) || m.Length.Zero != 6 || m.Content.Unavailable != 6 {
|
||||
t.Fatal("candidate Unicode/exclusion buckets changed article results")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestCandidateLengthNormalizesEditorialWhitespaceWithoutRetainingContent(t *testing.T) {
|
||||
const target = "https://finance.yahoo.com/news/fixture.html"
|
||||
pages := map[string]string{target: `<link rel="canonical" href="` + target + `"><div class="caas-body"><h2> Synthetic heading </h2><p>A <em> Unicode 界 </em> body<br> text.</p><aside>Excluded sidebar</aside></div>`}
|
||||
m := fetchMetricsForFixturePages(t, "yahoo_finance", pages)
|
||||
if m.CandidateLength.Small != 1 || m.Length.Small != 1 || m.Content.Complete != 1 {
|
||||
t.Fatal("candidate length changed valid extraction")
|
||||
}
|
||||
}
|
||||
func TestCandidateLengthDoesNotInventAnEditorialRoot(t *testing.T) {
|
||||
const target = "https://finance.yahoo.com/news/fixture.html"
|
||||
for _, raw := range []string{
|
||||
`<main><p>Synthetic generic page text.</p></main>`,
|
||||
`<div class="caas-body"><p>First ambiguous root.</p></div><div class="caas-body"><p>Second ambiguous root.</p></div>`,
|
||||
`<aside><div class="caas-body"><p>Excluded root.</p></div></aside>`,
|
||||
} {
|
||||
m := fetchMetricsForFixturePages(t, "yahoo_finance", map[string]string{target: raw})
|
||||
if m.CandidateLength.Zero != 1 || m.Content.Unavailable != 1 {
|
||||
t.Fatal("unknown/ambiguous/excluded root was measured as editorial body")
|
||||
}
|
||||
}
|
||||
}
|
||||
228
backend/internal/scraper/articlecontent/diagnostics.go
Normal file
228
backend/internal/scraper/articlecontent/diagnostics.go
Normal file
@ -0,0 +1,228 @@
|
||||
package articlecontent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
// observeGranular reduces existing transient DOM evidence into fixed flags.
|
||||
// Each category/scope contributes at most once per fetch. Nothing here decides
|
||||
// whether content is associated, complete, or usable by the product.
|
||||
func observeGranular(doc *html.Node, roots []*html.Node, source, expected string, aliases []string, content string, extractionEvaluated bool, o *scraper.FetchObservation) {
|
||||
o.GranularSupported = true
|
||||
accepted := map[string]bool{}
|
||||
for _, v := range append([]string{expected}, aliases...) {
|
||||
if k, ok := articleIdentity(source, v); ok {
|
||||
accepted[k] = true
|
||||
}
|
||||
}
|
||||
base, _ := url.Parse(expected)
|
||||
relation := func(value string) (bool, bool) {
|
||||
if value == "" || base == nil {
|
||||
return false, false
|
||||
}
|
||||
ref, err := url.Parse(value)
|
||||
if err != nil {
|
||||
return false, false
|
||||
}
|
||||
k, ok := articleIdentity(source, base.ResolveReference(ref).String())
|
||||
return accepted[k], ok
|
||||
}
|
||||
scope := func(n *html.Node) bool {
|
||||
for p := n; p != nil; p = p.Parent {
|
||||
for _, root := range roots {
|
||||
if p == root {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
// Article wrappers, including metadata beside the body, are editorial.
|
||||
for _, root := range roots {
|
||||
for p := root; p != nil; p = p.Parent {
|
||||
if p.Type == html.ElementNode && p.Data == "article" {
|
||||
for q := n; q != nil; q = q.Parent {
|
||||
if q == p {
|
||||
return true
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
set := func(c *scraper.ScopedEvidenceCounts, inside bool) {
|
||||
if inside {
|
||||
c.ArticleRoot = 1
|
||||
} else {
|
||||
c.OutsideRoot = 1
|
||||
}
|
||||
}
|
||||
identity := func(v any) string {
|
||||
switch x := v.(type) {
|
||||
case string:
|
||||
return x
|
||||
case map[string]any:
|
||||
s, _ := x["@id"].(string)
|
||||
return s
|
||||
}
|
||||
return ""
|
||||
}
|
||||
var metadata func(any, int, bool, *int)
|
||||
metadata = func(value any, depth int, inside bool, visited *int) {
|
||||
*visited++
|
||||
if depth > 32 || *visited > 2000 {
|
||||
return
|
||||
}
|
||||
switch x := value.(type) {
|
||||
case []any:
|
||||
for _, v := range x {
|
||||
metadata(v, depth+1, inside, visited)
|
||||
}
|
||||
case map[string]any:
|
||||
article := false
|
||||
switch typ := x["@type"].(type) {
|
||||
case string:
|
||||
article = typ == "Article" || typ == "NewsArticle" || typ == "ReportageNewsArticle"
|
||||
case []any:
|
||||
for _, typ := range typ {
|
||||
if typ == "Article" || typ == "NewsArticle" || typ == "ReportageNewsArticle" {
|
||||
article = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if article {
|
||||
id := identity(x["url"])
|
||||
if id == "" {
|
||||
id = identity(x["mainEntityOfPage"])
|
||||
}
|
||||
if id == "" {
|
||||
id = identity(x["@id"])
|
||||
}
|
||||
match, _ := relation(id)
|
||||
if id != "" {
|
||||
if match {
|
||||
o.IdentityEvidence.JSONLD.Associated = 1
|
||||
} else {
|
||||
o.IdentityEvidence.JSONLD.Mismatch = 1
|
||||
}
|
||||
}
|
||||
if match {
|
||||
if x["isAccessibleForFree"] == false || strings.EqualFold(identity(x["isAccessibleForFree"]), "false") {
|
||||
set(&o.BlockingEvidence.Accessibility, inside)
|
||||
}
|
||||
if body, ok := x["articleBody"].(string); ok && extractionEvaluated && len(roots) == 1 && strings.Join(strings.Fields(body), " ") != strings.Join(strings.Fields(content), " ") {
|
||||
set(&o.BlockingEvidence.BodyConflict, inside)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, v := range x {
|
||||
switch v.(type) {
|
||||
case map[string]any, []any:
|
||||
metadata(v, depth+1, inside, visited)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Presence is tracked separately for each metadata family; absent means no
|
||||
// nonempty value, rather than an invalid or a different identity.
|
||||
canonicalPresent, ogPresent := false, false
|
||||
recordIdentity := func(c *scraper.MetadataIdentityCounts, value string) {
|
||||
ref, err := url.Parse(value)
|
||||
if err != nil || base == nil || len(value) > 4096 {
|
||||
c.Invalid = 1
|
||||
return
|
||||
}
|
||||
u := base.ResolveReference(ref)
|
||||
host := u.Hostname()
|
||||
valid := (u.Scheme == "https" || u.Scheme == "http") && host != "" && u.User == nil && u.Opaque == "" && !strings.ContainsAny(host, " \t\r\n\\")
|
||||
if port := u.Port(); port != "" {
|
||||
n, err := strconv.Atoi(port)
|
||||
valid = valid && err == nil && n > 0 && n <= 65535
|
||||
}
|
||||
if !valid {
|
||||
c.Invalid = 1
|
||||
return
|
||||
}
|
||||
match, _ := relation(value)
|
||||
if match {
|
||||
c.Associated = 1
|
||||
return
|
||||
}
|
||||
if strings.EqualFold(host, base.Hostname()) {
|
||||
c.SameSourceDifferentIdentity = 1
|
||||
} else {
|
||||
c.ValidOtherHost = 1
|
||||
}
|
||||
}
|
||||
var walk func(*html.Node)
|
||||
walk = func(n *html.Node) {
|
||||
if n.Type == html.ElementNode {
|
||||
inside := scope(n)
|
||||
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id") + " " + attr(n, "data-component"))
|
||||
if strings.Contains(marker, "paywall") || strings.Contains(marker, "giftarticle") || attr(n, "data-test") == "paywall" || attr(n, "data-testid") == "paywall" {
|
||||
set(&o.BlockingEvidence.Paywall, inside)
|
||||
}
|
||||
if challengeMarker(n) {
|
||||
o.BlockingEvidence.Challenge.GlobalPage = 1
|
||||
}
|
||||
if attr(n, "data-content-state") == "partial" || attr(n, "data-content-state") == "incomplete" {
|
||||
set(&o.BlockingEvidence.Partial, inside)
|
||||
}
|
||||
if attr(n, "data-content-truncated") == "true" {
|
||||
set(&o.BlockingEvidence.Truncated, inside)
|
||||
}
|
||||
if strings.Contains(marker, "placeholder") || strings.Contains(marker, "skeleton") {
|
||||
set(&o.BlockingEvidence.Placeholder, inside)
|
||||
}
|
||||
kind, value := "", ""
|
||||
if n.Data == "link" && strings.EqualFold(attr(n, "rel"), "canonical") {
|
||||
kind = "canonical"
|
||||
value = attr(n, "href")
|
||||
}
|
||||
if n.Data == "meta" && attr(n, "property") == "og:url" {
|
||||
kind = "og"
|
||||
value = attr(n, "content")
|
||||
}
|
||||
value = strings.TrimSpace(value)
|
||||
if value != "" {
|
||||
if kind == "canonical" {
|
||||
canonicalPresent = true
|
||||
recordIdentity(&o.IdentityEvidence.Canonical, value)
|
||||
} else {
|
||||
ogPresent = true
|
||||
recordIdentity(&o.IdentityEvidence.OG, value)
|
||||
}
|
||||
}
|
||||
if n.Data == "script" && attr(n, "type") == "application/ld+json" {
|
||||
var text strings.Builder
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
if c.Type == html.TextNode {
|
||||
text.WriteString(c.Data)
|
||||
}
|
||||
}
|
||||
var value any
|
||||
if json.Unmarshal([]byte(text.String()), &value) == nil {
|
||||
visited := 0
|
||||
metadata(value, 0, inside, &visited)
|
||||
}
|
||||
}
|
||||
}
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
walk(c)
|
||||
}
|
||||
}
|
||||
walk(doc)
|
||||
if !canonicalPresent {
|
||||
o.IdentityEvidence.Canonical.Absent = 1
|
||||
}
|
||||
if !ogPresent {
|
||||
o.IdentityEvidence.OG.Absent = 1
|
||||
}
|
||||
}
|
||||
96
backend/internal/scraper/articlecontent/diagnostics_test.go
Normal file
96
backend/internal/scraper/articlecontent/diagnostics_test.go
Normal file
@ -0,0 +1,96 @@
|
||||
package articlecontent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
func TestGranularInstrumentationDoesNotChangeArticleDecisions(t *testing.T) {
|
||||
const target = "https://www.cnbc.com/2026/02/01/fixture.html"
|
||||
for _, part := range []string{
|
||||
`<div data-module="ArticleBody"><p>Synthetic editorial text.</p></div><aside class="paywall"></aside>`,
|
||||
`<article><div data-module="ArticleBody"><p>Synthetic editorial text.</p></div><div class="paywall"></div></article>`,
|
||||
`<div data-module="ArticleBody"><p>Synthetic editorial text.</p><div data-content-state="partial"></div></div>`,
|
||||
`<aside id="challengeGate"></aside>`,
|
||||
`<script type="application/ld+json">{"@type":"NewsArticle","url":"` + target + `","isAccessibleForFree":false,"articleBody":"conflicting synthetic metadata"}</script><div data-module="ArticleBody"><p>Synthetic editorial text.</p></div>`,
|
||||
} {
|
||||
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Request: r, Body: io.NopCloser(strings.NewReader(`<link rel="canonical" href="` + target + `">` + part))}, nil
|
||||
})}
|
||||
plain, _ := Enrich(context.Background(), client, "cnbc_business", []scraper.Article{{URL: target}})
|
||||
ctx, meter := scraper.WithFetchMetrics(context.Background())
|
||||
measured, _ := Enrich(ctx, client, "cnbc_business", []scraper.Article{{URL: target}})
|
||||
if !reflect.DeepEqual(plain, measured) || !meter.Finish().GranularSupported {
|
||||
t.Fatal("diagnostics altered article result")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestGranularEvidenceIsDeduplicatedPerFetchAndUnextractedBodiesAreNotConflicts(t *testing.T) {
|
||||
const target = "https://finance.yahoo.com/news/fixture.html"
|
||||
duplicate := `<link rel="canonical" href="` + target + `"><link rel="canonical" href="` + target + `"><div class="caas-body"><p>Synthetic body.</p><div class="paywall"></div><div class="paywall"></div></div>`
|
||||
m := fetchMetricsForFixturePages(t, "yahoo_finance", map[string]string{target: duplicate})
|
||||
if m.IdentityEvidence.Canonical.Associated != 1 || m.BlockingEvidence.Paywall.ArticleRoot != 1 {
|
||||
t.Fatal("duplicate evidence inflated counters")
|
||||
}
|
||||
// Rejected association returns before extraction: do not invent a conflict
|
||||
// by comparing metadata with an unextracted empty content string.
|
||||
mismatch := `<link rel="canonical" href="https://finance.yahoo.com/news/other.html"><script type="application/ld+json">{"@type":"NewsArticle","url":"` + target + `","articleBody":"Synthetic body."}</script><div class="caas-body"><p>Synthetic body.</p></div>`
|
||||
m = fetchMetricsForFixturePages(t, "yahoo_finance", map[string]string{target: mismatch})
|
||||
if m.BlockingEvidence.BodyConflict.OutsideRoot != 0 || m.IdentityEvidence.JSONLD.Associated != 1 {
|
||||
t.Fatal("unextracted body conflict was invented")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetadataDiagnosticValidityAndAbsenceAreIndependentOfParserTrust(t *testing.T) {
|
||||
const target = "https://finance.yahoo.com/news/fixture.html"
|
||||
for _, kind := range []string{"canonical", "og"} {
|
||||
for _, tc := range []struct {
|
||||
name, value string
|
||||
want scraper.MetadataIdentityCounts
|
||||
}{
|
||||
{"associated", target, scraper.MetadataIdentityCounts{Associated: 1}},
|
||||
{"relative_associated", "/news/fixture.html", scraper.MetadataIdentityCounts{Associated: 1}},
|
||||
{"same_source_other", "/news/other.html", scraper.MetadataIdentityCounts{SameSourceDifferentIdentity: 1}},
|
||||
{"valid_same_host_port", "https://finance.yahoo.com:444/news/fixture.html", scraper.MetadataIdentityCounts{SameSourceDifferentIdentity: 1}},
|
||||
{"valid_other_host", "https://example.invalid/fixture", scraper.MetadataIdentityCounts{ValidOtherHost: 1}},
|
||||
{"invalid_syntax", "http://[invalid", scraper.MetadataIdentityCounts{Invalid: 1}},
|
||||
{"invalid_scheme", "javascript:fixture", scraper.MetadataIdentityCounts{Invalid: 1}},
|
||||
{"invalid_port", "https://example.invalid:99999/fixture", scraper.MetadataIdentityCounts{Invalid: 1}},
|
||||
{"invalid_credentials", "https://private:canary@example.invalid/fixture", scraper.MetadataIdentityCounts{Invalid: 1}},
|
||||
{"empty", "", scraper.MetadataIdentityCounts{Absent: 1}},
|
||||
} {
|
||||
t.Run(kind+"/"+tc.name, func(t *testing.T) {
|
||||
tag := `<link rel="canonical" href="` + tc.value + `">`
|
||||
if kind == "og" {
|
||||
tag = `<meta property="og:url" content="` + tc.value + `">`
|
||||
}
|
||||
m := fetchMetricsForFixturePages(t, "yahoo_finance", map[string]string{target: tag + `<div class="caas-body"><p>Synthetic editorial text.</p></div>`})
|
||||
got, other := m.IdentityEvidence.Canonical, m.IdentityEvidence.OG
|
||||
if kind == "og" {
|
||||
got, other = other, got
|
||||
}
|
||||
if got != tc.want || other.Absent != 1 {
|
||||
t.Fatal("metadata validity/absence category contract failed")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChallengeIsOneGlobalPageSignalEvenAcrossBothScopes(t *testing.T) {
|
||||
const target = "https://www.cnbc.com/2026/02/01/fixture.html"
|
||||
raw := `<link rel="canonical" href="` + target + `"><aside id="challengeGate"></aside><div data-module="ArticleBody"><p>Synthetic editorial text.</p><div id="challengeGate"></div></div>`
|
||||
m := fetchMetricsForFixturePages(t, "cnbc_business", map[string]string{target: raw})
|
||||
if m.BlockingEvidence.Challenge.GlobalPage != 1 || m.Content.Incomplete != 1 {
|
||||
t.Fatal("global challenge semantics changed")
|
||||
}
|
||||
data := requireAnonymousAggregate(t, m)
|
||||
requireNoAggregateCounter(t, data, []string{"blocking_evidence", "challenge", "article_root"})
|
||||
requireNoAggregateCounter(t, data, []string{"blocking_evidence", "challenge", "outside_root"})
|
||||
}
|
||||
@ -10,6 +10,7 @@ import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"golang.org/x/net/html"
|
||||
@ -17,39 +18,54 @@ import (
|
||||
|
||||
const maxHTMLBytes = 16 * 1024 * 1024
|
||||
|
||||
// A listing may use an article path without a filename/date pattern. Trust
|
||||
// only the exact source origin, upgrade HTTP before network I/O, and preserve
|
||||
// semantic query parameters. The original Article.URL is never rewritten.
|
||||
func safeURL(source, value string) (string, bool) {
|
||||
u, err := url.Parse(value)
|
||||
if err != nil || u.Scheme != "https" || u.User != nil || u.Port() != "" || len(value) > 4096 {
|
||||
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Opaque != "" || u.User != nil || u.Port() != "" || len(value) > 4096 || u.Path == "" || u.Path == "/" {
|
||||
return "", false
|
||||
}
|
||||
host := strings.ToLower(u.Hostname())
|
||||
switch source {
|
||||
case "yahoo_finance":
|
||||
if u.Hostname() != "finance.yahoo.com" || !strings.HasPrefix(u.Path, "/news/") || !strings.HasSuffix(u.Path, ".html") {
|
||||
if host != "finance.yahoo.com" {
|
||||
return "", false
|
||||
}
|
||||
case "cnbc_business":
|
||||
if u.Hostname() != "www.cnbc.com" || !strings.HasSuffix(u.Path, ".html") || len(u.Path) < 12 || u.Path[5] != '/' || u.Path[8] != '/' || u.Path[11] != '/' {
|
||||
if host != "www.cnbc.com" {
|
||||
return "", false
|
||||
}
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
u.RawQuery = ""
|
||||
u.Scheme = "https"
|
||||
u.Host = host
|
||||
u.Fragment = ""
|
||||
return u.String(), true
|
||||
}
|
||||
func articleIdentity(source, value string) (string, bool) {
|
||||
value, ok := safeURL(source, value)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
u, _ := url.Parse(value)
|
||||
q := u.Query()
|
||||
for k := range q {
|
||||
if strings.HasPrefix(strings.ToLower(k), "utm_") || k == "guccounter" || k == "guce_referrer" || k == "guce_referrer_sig" {
|
||||
q.Del(k)
|
||||
}
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String(), true
|
||||
}
|
||||
func Enrich(ctx context.Context, client *http.Client, source string, articles []scraper.Article) ([]scraper.Article, error) {
|
||||
scraper.EnableFetchMetrics(ctx)
|
||||
ctx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
out := append([]scraper.Article(nil), articles...)
|
||||
bounded := *client
|
||||
bounded.Timeout = 15 * time.Second
|
||||
bounded.CheckRedirect = func(r *http.Request, via []*http.Request) error {
|
||||
if _, ok := safeURL(source, r.URL.String()); !ok || len(via) >= 3 {
|
||||
return http.ErrUseLastResponse
|
||||
}
|
||||
return nil
|
||||
}
|
||||
cache := map[string]scraper.Article{}
|
||||
for i, a := range out {
|
||||
out[i].Content = ""
|
||||
@ -68,16 +84,54 @@ func Enrich(ctx context.Context, client *http.Client, source string, articles []
|
||||
req.Header.Set("User-Agent", "Tradarr/1.0")
|
||||
req.Header.Set("Accept", "text/html")
|
||||
extracted = scraper.Article{ContentState: scraper.ContentUnavailable}
|
||||
resp, err := bounded.Do(req)
|
||||
// Only an observed, validated redirect chain may change the fetch
|
||||
// identity. Metadata may identify the initial or observed final URL.
|
||||
verifiedFinal := target
|
||||
requestClient := bounded
|
||||
requestClient.CheckRedirect = func(r *http.Request, via []*http.Request) error {
|
||||
normalized, ok := safeURL(source, r.URL.String())
|
||||
if !ok || len(via) >= 3 {
|
||||
return http.ErrUseLastResponse
|
||||
}
|
||||
parsed, _ := url.Parse(normalized)
|
||||
r.URL = parsed
|
||||
verifiedFinal = normalized
|
||||
return nil
|
||||
}
|
||||
observation := scraper.FetchObservation{State: scraper.ContentUnavailable, CandidateBodySupported: true}
|
||||
var trace *scraper.FetchObservation
|
||||
if scraper.FetchMetricsEnabled(ctx) {
|
||||
trace = &observation
|
||||
}
|
||||
resp, err := requestClient.Do(req)
|
||||
if err != nil {
|
||||
observation.Network = true
|
||||
}
|
||||
if err == nil {
|
||||
if resp.StatusCode == http.StatusOK && sameResponseArticle(source, target, resp) {
|
||||
observation.HTTPStatus = resp.StatusCode
|
||||
responseMatches := true
|
||||
if resp.Request != nil && resp.Request.URL != nil {
|
||||
actual, ok := articleIdentity(source, resp.Request.URL.String())
|
||||
expected, _ := articleIdentity(source, verifiedFinal)
|
||||
responseMatches = ok && actual == expected
|
||||
}
|
||||
if !responseMatches {
|
||||
observation.Identity = scraper.IdentityMismatch
|
||||
}
|
||||
if resp.StatusCode == http.StatusOK && responseMatches {
|
||||
raw, readErr := io.ReadAll(io.LimitReader(resp.Body, maxHTMLBytes+1))
|
||||
if readErr == nil && len(raw) <= maxHTMLBytes {
|
||||
extracted = ExtractHTML(source, target, raw)
|
||||
var aliases []string
|
||||
if source == "yahoo_finance" {
|
||||
aliases = []string{target}
|
||||
}
|
||||
extracted = extractHTML(source, verifiedFinal, raw, trace, aliases...)
|
||||
}
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
observation.State = extracted.ContentState
|
||||
scraper.RecordFetch(ctx, observation)
|
||||
cache[target] = extracted
|
||||
}
|
||||
out[i].Content = extracted.Content
|
||||
@ -157,11 +211,20 @@ func missingMarker(n *html.Node) bool {
|
||||
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id") + " " + attr(n, "data-component"))
|
||||
return strings.Contains(marker, "placeholder") || strings.Contains(marker, "skeleton") || attr(n, "data-content-truncated") == "true" || attr(n, "data-content-state") == "partial" || attr(n, "data-content-state") == "incomplete"
|
||||
}
|
||||
|
||||
// Challenges may replace or overlay editorial content, so their scope is global.
|
||||
func challengeMarker(n *html.Node) bool {
|
||||
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id"))
|
||||
return strings.Contains(marker, "captcha") || strings.Contains(marker, "challenge") || strings.HasPrefix(attr(n, "id"), "cf-chl") || strings.Contains(attr(n, "src"), "challenge-platform")
|
||||
}
|
||||
func accessMarker(n *html.Node) bool {
|
||||
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id"))
|
||||
return strings.Contains(marker, "paywall") || strings.Contains(marker, "giftarticle") || strings.Contains(marker, "captcha") || strings.HasPrefix(attr(n, "id"), "cf-chl") || strings.HasPrefix(attr(n, "id"), "challenge") || strings.Contains(attr(n, "src"), "challenge-platform") || attr(n, "data-test") == "paywall" || attr(n, "data-testid") == "paywall" || attr(n, "data-content-state") == "partial" || attr(n, "data-content-state") == "incomplete" || attr(n, "data-content-truncated") == "true"
|
||||
}
|
||||
func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
|
||||
return extractHTML(source, articleURL, raw, nil)
|
||||
}
|
||||
func extractHTML(source, articleURL string, raw []byte, observation *scraper.FetchObservation, aliases ...string) scraper.Article {
|
||||
a := scraper.Article{ContentState: scraper.ContentUnavailable}
|
||||
if len(raw) > maxHTMLBytes {
|
||||
return a
|
||||
@ -170,10 +233,7 @@ func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
|
||||
if err != nil {
|
||||
return a
|
||||
}
|
||||
evidence := inspectEvidence(doc, source, articleURL)
|
||||
if evidence.mismatch {
|
||||
return a
|
||||
}
|
||||
evidence := inspectEvidence(doc, source, articleURL, aliases...)
|
||||
var roots []*html.Node
|
||||
blocked := evidence.blocked
|
||||
var walk func(*html.Node)
|
||||
@ -190,7 +250,7 @@ func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
|
||||
roots = append(roots, n)
|
||||
}
|
||||
}
|
||||
if accessMarker(n) {
|
||||
if accessMarker(n) && (source != "cnbc_business" || challengeMarker(n) || missingMarker(n)) {
|
||||
blocked = true
|
||||
}
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
@ -198,6 +258,61 @@ func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
|
||||
}
|
||||
}
|
||||
walk(doc)
|
||||
extractionEvaluated := false
|
||||
if observation != nil {
|
||||
// Read-only diagnostics: never influence association, dates or completeness.
|
||||
defer func() {
|
||||
observeGranular(doc, roots, source, articleURL, aliases, a.Content, extractionEvaluated, observation)
|
||||
}()
|
||||
}
|
||||
if source == "cnbc_business" {
|
||||
// Generic subscription chrome is unrelated; article wrappers and their
|
||||
// descendants still carry access restrictions. Challenges remain global.
|
||||
var scan func(*html.Node)
|
||||
scan = func(n *html.Node) {
|
||||
if accessMarker(n) || missingMarker(n) {
|
||||
blocked = true
|
||||
}
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
scan(c)
|
||||
}
|
||||
}
|
||||
for _, root := range roots {
|
||||
scan(root)
|
||||
for p := root.Parent; p != nil; p = p.Parent {
|
||||
if accessMarker(p) || missingMarker(p) {
|
||||
blocked = true
|
||||
}
|
||||
if p.Type == html.ElementNode && p.Data == "article" {
|
||||
scan(p)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if observation != nil {
|
||||
if len(roots) == 1 {
|
||||
observation.CandidateBodyLength = candidateBodyLength(roots[0])
|
||||
}
|
||||
observation.Root = scraper.ObservedNo
|
||||
if len(roots) == 1 {
|
||||
observation.Root = scraper.ObservedYes
|
||||
}
|
||||
observation.Identity = scraper.IdentityNo
|
||||
if evidence.associated {
|
||||
observation.Identity = scraper.IdentityYes
|
||||
}
|
||||
if evidence.mismatch {
|
||||
observation.Identity = scraper.IdentityMismatch
|
||||
}
|
||||
observation.Blocking = scraper.ObservedNo
|
||||
if blocked {
|
||||
observation.Blocking = scraper.ObservedYes
|
||||
}
|
||||
}
|
||||
if evidence.mismatch {
|
||||
return a
|
||||
}
|
||||
if evidence.associated && !evidence.dateConflict {
|
||||
a.PublishedAt = evidence.date
|
||||
}
|
||||
@ -216,6 +331,9 @@ func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
|
||||
var collect func(*html.Node)
|
||||
collect = func(n *html.Node) {
|
||||
if missingMarker(n) {
|
||||
if observation != nil {
|
||||
observation.Blocking = scraper.ObservedYes
|
||||
}
|
||||
blocked = true
|
||||
}
|
||||
if excluded(n) {
|
||||
@ -246,6 +364,10 @@ func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
|
||||
collect(roots[0])
|
||||
flush()
|
||||
a.Content = strings.Join(paragraphs, "\n\n")
|
||||
extractionEvaluated = true
|
||||
if observation != nil {
|
||||
observation.Length = utf8.RuneCountInString(a.Content)
|
||||
}
|
||||
if evidence.fullBody != nil && strings.Join(strings.Fields(*evidence.fullBody), " ") != strings.Join(strings.Fields(a.Content), " ") {
|
||||
blocked = true
|
||||
}
|
||||
@ -257,11 +379,3 @@ func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func sameResponseArticle(source, target string, resp *http.Response) bool {
|
||||
if resp.Request == nil || resp.Request.URL == nil {
|
||||
return true
|
||||
}
|
||||
actual, ok := safeURL(source, resp.Request.URL.String())
|
||||
return ok && actual == target
|
||||
}
|
||||
|
||||
@ -25,8 +25,12 @@ func TestTicket39SourceFixtures(t *testing.T) {
|
||||
t.Fatalf("bad full content: state=%s date=%v", a.ContentState, a.PublishedAt)
|
||||
}
|
||||
a = ExtractHTML(source, fixtureArticleURL(source), append(raw, []byte(`<div class="paywall">subscribe</div>`)...))
|
||||
if a.ContentState != scraper.ContentIncomplete {
|
||||
t.Fatal("paywall claimed complete")
|
||||
expected := scraper.ContentIncomplete
|
||||
if source == "cnbc_business" {
|
||||
expected = scraper.ContentComplete
|
||||
}
|
||||
if a.ContentState != expected {
|
||||
t.Fatal("detached paywall scope contract failed")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@ -14,9 +14,18 @@ type articleEvidence struct {
|
||||
fullBody *string
|
||||
}
|
||||
|
||||
func inspectEvidence(doc *html.Node, source, expected string) articleEvidence {
|
||||
func inspectEvidence(doc *html.Node, source, expected string, aliases ...string) articleEvidence {
|
||||
e := articleEvidence{}
|
||||
wanted, valid := safeURL(source, expected)
|
||||
wanted, valid := articleIdentity(source, expected)
|
||||
accepted := map[string]bool{}
|
||||
if valid {
|
||||
accepted[wanted] = true
|
||||
}
|
||||
for _, alias := range aliases {
|
||||
if identity, ok := articleIdentity(source, alias); ok {
|
||||
accepted[identity] = true
|
||||
}
|
||||
}
|
||||
key := func(value string) string {
|
||||
if value == "" {
|
||||
return ""
|
||||
@ -29,7 +38,7 @@ func inspectEvidence(doc *html.Node, source, expected string) articleEvidence {
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
value, ok := safeURL(source, base.ResolveReference(ref).String())
|
||||
value, ok := articleIdentity(source, base.ResolveReference(ref).String())
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
@ -96,7 +105,7 @@ func inspectEvidence(doc *html.Node, source, expected string) articleEvidence {
|
||||
if value != "" {
|
||||
articleIDs++
|
||||
}
|
||||
if valid && key(value) == wanted {
|
||||
if accepted[key(value)] {
|
||||
e.associated = true
|
||||
matching = true
|
||||
if x["isAccessibleForFree"] == false || strings.EqualFold(identity(x["isAccessibleForFree"]), "false") {
|
||||
@ -132,7 +141,7 @@ func inspectEvidence(doc *html.Node, source, expected string) articleEvidence {
|
||||
}
|
||||
if value != "" {
|
||||
primary++
|
||||
if valid && key(value) == wanted {
|
||||
if accepted[key(value)] {
|
||||
e.associated = true
|
||||
} else {
|
||||
e.mismatch = true
|
||||
|
||||
@ -0,0 +1,99 @@
|
||||
package articlecontent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type unreadableMetricBody struct{ t *testing.T }
|
||||
|
||||
func (b unreadableMetricBody) Read([]byte) (int, error) {
|
||||
b.t.Fatal("non-200 body read for diagnostics")
|
||||
return 0, io.EOF
|
||||
}
|
||||
func (unreadableMetricBody) Close() error { return nil }
|
||||
func TestArticleFetchMetricsDescribeHTTPAndParserWithoutChangingClassification(t *testing.T) {
|
||||
const target = "https://finance.yahoo.com/news/metrics.html"
|
||||
base := `<link rel="canonical" href="` + target + `"><div class="caas-body"><p>Synthetic retained content.</p></div>`
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status int
|
||||
html string
|
||||
network bool
|
||||
root scraper.EvidenceFlag
|
||||
identity scraper.IdentityFlag
|
||||
blocking scraper.EvidenceFlag
|
||||
state string
|
||||
}{
|
||||
{"recognized", 200, base, false, scraper.ObservedYes, scraper.IdentityYes, scraper.ObservedNo, scraper.ContentComplete},
|
||||
{"unknown_root", 200, strings.Replace(base, "caas-body", "unrecognized-root", 1), false, scraper.ObservedNo, scraper.IdentityYes, scraper.ObservedNo, scraper.ContentUnavailable},
|
||||
{"unknown_identity", 200, `<div class="caas-body"><p>Synthetic retained content.</p></div>`, false, scraper.ObservedYes, scraper.IdentityNo, scraper.ObservedNo, scraper.ContentIncomplete},
|
||||
{"mismatch", 200, strings.Replace(base, target, target+"-other", 1), false, scraper.ObservedYes, scraper.IdentityMismatch, scraper.ObservedNo, scraper.ContentUnavailable},
|
||||
{"challenge", 200, `<div id="px-captcha"></div>`, false, scraper.ObservedNo, scraper.IdentityNo, scraper.ObservedYes, scraper.ContentUnavailable},
|
||||
{"denied", 403, "", false, scraper.NotEvaluated, scraper.IdentityNotEvaluated, scraper.NotEvaluated, scraper.ContentUnavailable},
|
||||
{"unavailable", 503, "", false, scraper.NotEvaluated, scraper.IdentityNotEvaluated, scraper.NotEvaluated, scraper.ContentUnavailable},
|
||||
{"redirect_denied", 302, "", false, scraper.NotEvaluated, scraper.IdentityNotEvaluated, scraper.NotEvaluated, scraper.ContentUnavailable},
|
||||
{"network", 0, "", true, scraper.NotEvaluated, scraper.IdentityNotEvaluated, scraper.NotEvaluated, scraper.ContentUnavailable},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx, m := scraper.WithFetchMetrics(context.Background())
|
||||
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
if tc.network {
|
||||
return nil, errors.New("synthetic-private-error")
|
||||
}
|
||||
var body io.ReadCloser = io.NopCloser(strings.NewReader(tc.html))
|
||||
if tc.status != 200 {
|
||||
body = unreadableMetricBody{t}
|
||||
}
|
||||
return &http.Response{StatusCode: tc.status, Header: make(http.Header), Body: body, Request: r}, nil
|
||||
})}
|
||||
a, err := Enrich(ctx, client, "yahoo_finance", []scraper.Article{{URL: target}})
|
||||
c := m.Finish()
|
||||
if err != nil || len(a) != 1 || scraper.ContentStatus(a[0]) != tc.state || !c.Supported || c.Attempted != 1 {
|
||||
t.Fatal("measurement changed outcome")
|
||||
}
|
||||
wantRoot := scraper.EvidenceCounts{}
|
||||
add := func(v scraper.EvidenceFlag) *int {
|
||||
switch v {
|
||||
case scraper.ObservedYes:
|
||||
return &wantRoot.Yes
|
||||
case scraper.ObservedNo:
|
||||
return &wantRoot.No
|
||||
}
|
||||
return &wantRoot.NotEvaluated
|
||||
}
|
||||
*add(tc.root) = 1
|
||||
if c.Root != wantRoot {
|
||||
t.Fatalf("root classification %+v", c.Root)
|
||||
}
|
||||
if tc.identity == scraper.IdentityMismatch && c.Identity.Mismatch != 1 || tc.identity == scraper.IdentityYes && c.Identity.Yes != 1 || tc.identity == scraper.IdentityNo && c.Identity.No != 1 || tc.identity == scraper.IdentityNotEvaluated && c.Identity.NotEvaluated != 1 {
|
||||
t.Fatal("identity classification")
|
||||
}
|
||||
if tc.blocking == scraper.ObservedYes && c.Blocking.Yes != 1 || tc.blocking == scraper.ObservedNo && c.Blocking.No != 1 || tc.blocking == scraper.NotEvaluated && c.Blocking.NotEvaluated != 1 {
|
||||
t.Fatal("block classification")
|
||||
}
|
||||
if tc.status == 200 && c.HTTP.TwoXX != 1 || tc.status == 302 && c.HTTP.ThreeXX != 1 || tc.status == 403 && c.HTTP.FourXX != 1 || tc.status == 503 && c.HTTP.FiveXX != 1 || tc.network && c.HTTP.Network != 1 {
|
||||
t.Fatal("HTTP class")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestExtractedLengthBucketsCountUnicodeCharacters(t *testing.T) {
|
||||
for _, n := range []int{0, 1, 500, 501, 2000, 2001} {
|
||||
ctx, m := scraper.WithFetchMetrics(context.Background())
|
||||
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
body := `<link rel="canonical" href="` + r.URL.String() + `"><div class="caas-body"><p>` + strings.Repeat("漢", n) + `</p></div>`
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
|
||||
})}
|
||||
Enrich(ctx, client, "yahoo_finance", []scraper.Article{{URL: "https://finance.yahoo.com/news/length.html"}})
|
||||
c := m.Finish()
|
||||
if n == 0 && c.Length.Zero != 1 || n > 0 && n <= 500 && c.Length.Small != 1 || n > 500 && n <= 2000 && c.Length.Medium != 1 || n > 2000 && c.Length.Large != 1 {
|
||||
t.Fatal("character bucket incorrect")
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,254 @@
|
||||
package articlecontent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
const granularMetricCanary = "fixture_private_body_title_url_secret_canary"
|
||||
|
||||
func jsonLD(t *testing.T, value any) string {
|
||||
t.Helper()
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatal("could not build anonymous metrics fixture")
|
||||
}
|
||||
return `<script type="application/ld+json">` + string(raw) + `</script>`
|
||||
}
|
||||
|
||||
func fetchMetricsForFixturePages(t *testing.T, source string, pages map[string]string) scraper.FetchMetrics {
|
||||
t.Helper()
|
||||
articles := make([]scraper.Article, 0, len(pages))
|
||||
for target := range pages {
|
||||
articles = append(articles, scraper.Article{URL: target, Title: granularMetricCanary})
|
||||
}
|
||||
ctx, meter := scraper.WithFetchMetrics(context.Background())
|
||||
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
body, ok := pages[r.URL.String()]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("fixture route not found")
|
||||
}
|
||||
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
|
||||
})}
|
||||
got, err := Enrich(ctx, client, source, articles)
|
||||
if err != nil || len(got) != len(articles) {
|
||||
t.Fatal("fixture enrichment failed")
|
||||
}
|
||||
return meter.Finish()
|
||||
}
|
||||
|
||||
func requireAnonymousAggregate(t *testing.T, metrics scraper.FetchMetrics, fixtureValues ...string) map[string]any {
|
||||
t.Helper()
|
||||
raw, err := json.Marshal(metrics)
|
||||
if err != nil {
|
||||
t.Fatal("aggregate metrics were not JSON serializable")
|
||||
}
|
||||
serialized := string(raw)
|
||||
for _, value := range append([]string{"http://", "https://", "finance.yahoo.com", "www.cnbc.com", granularMetricCanary}, fixtureValues...) {
|
||||
if strings.Contains(serialized, value) {
|
||||
t.Error("aggregate JSON exposed fixture source data")
|
||||
}
|
||||
}
|
||||
var data map[string]any
|
||||
if err := json.Unmarshal(raw, &data); err != nil {
|
||||
t.Fatal("aggregate metrics JSON could not be inspected")
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func requireAggregateCounter(t *testing.T, data map[string]any, path []string, want int) {
|
||||
t.Helper()
|
||||
var value any = data
|
||||
for _, key := range path {
|
||||
parent, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
t.Errorf("aggregate cause counter is missing: %s", strings.Join(path, "."))
|
||||
return
|
||||
}
|
||||
value, ok = parent[key]
|
||||
if !ok {
|
||||
t.Errorf("aggregate cause counter is missing: %s", strings.Join(path, "."))
|
||||
return
|
||||
}
|
||||
}
|
||||
got, ok := value.(float64)
|
||||
if !ok || int(got) != want {
|
||||
t.Errorf("aggregate cause counter mismatch: %s", strings.Join(path, "."))
|
||||
}
|
||||
}
|
||||
|
||||
func requireNoAggregateCounter(t *testing.T, data map[string]any, path []string) {
|
||||
t.Helper()
|
||||
var value any = data
|
||||
for _, key := range path {
|
||||
parent, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
value, ok = parent[key]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Errorf("global page challenge was incorrectly exposed as root-scoped: %s", strings.Join(path, "."))
|
||||
}
|
||||
|
||||
func TestYahooIdentityCauseMetricsSeparateMetadataKindsAndRelations(t *testing.T) {
|
||||
const sameHostOther = "https://finance.yahoo.com/news/other-fixture.html"
|
||||
const otherHost = "https://www.cnbc.com/2026/01/02/other-fixture.html"
|
||||
const fixtureBody = "Editorial body canary " + granularMetricCanary
|
||||
targets := make([]string, 10)
|
||||
for i := range targets {
|
||||
targets[i] = fmt.Sprintf("https://finance.yahoo.com/news/identity-fixture-%02d.html", i+1)
|
||||
}
|
||||
pages := map[string]string{}
|
||||
for i, target := range targets {
|
||||
metadata := ""
|
||||
switch i {
|
||||
case 0:
|
||||
metadata = `<link rel="canonical" href="` + sameHostOther + `">`
|
||||
case 1:
|
||||
metadata = `<link rel="canonical" href="` + otherHost + `">`
|
||||
case 2:
|
||||
metadata = `<link rel="canonical" href="http://[invalid">`
|
||||
case 3:
|
||||
metadata = ""
|
||||
case 4:
|
||||
metadata = `<meta property="og:url" content="` + sameHostOther + `">`
|
||||
case 5:
|
||||
metadata = `<meta property="og:url" content="` + otherHost + `">`
|
||||
case 6:
|
||||
metadata = `<meta property="og:url" content="http://[invalid">`
|
||||
case 7:
|
||||
metadata = ""
|
||||
case 8:
|
||||
metadata = jsonLD(t, map[string]any{"@type": "NewsArticle", "url": sameHostOther})
|
||||
case 9:
|
||||
metadata = jsonLD(t, map[string]any{"@type": "NewsArticle", "url": target, "articleBody": fixtureBody})
|
||||
}
|
||||
if i < 8 {
|
||||
pages[target] = metadata + `<article><div class="caas-body"></div></article>`
|
||||
} else {
|
||||
pages[target] = metadata + `<article><div class="caas-body"><p>` + fixtureBody + `</p></div></article>`
|
||||
}
|
||||
}
|
||||
metrics := fetchMetricsForFixturePages(t, "yahoo_finance", pages)
|
||||
data := requireAnonymousAggregate(t, metrics, sameHostOther, otherHost, granularMetricCanary)
|
||||
if metrics.Attempted != 10 || metrics.HTTP.TwoXX != 10 || metrics.Root.Yes != 10 {
|
||||
t.Fatal("Yahoo fixture aggregate did not retain bounded anonymous fetch counts")
|
||||
}
|
||||
// Each family appears on 3 of the 10 pages; the remaining 7 are absent,
|
||||
// including pages with only the other family or only JSON-LD.
|
||||
for _, tc := range []struct {
|
||||
kind, cause string
|
||||
want int
|
||||
}{
|
||||
{"canonical", "same_source_different_identity", 1},
|
||||
{"canonical", "valid_other_host", 1},
|
||||
{"canonical", "invalid", 1},
|
||||
{"canonical", "absent", 7},
|
||||
{"og", "same_source_different_identity", 1},
|
||||
{"og", "valid_other_host", 1},
|
||||
{"og", "invalid", 1},
|
||||
{"og", "absent", 7},
|
||||
{"jsonld", "mismatch", 1},
|
||||
{"jsonld", "associated", 1},
|
||||
} {
|
||||
requireAggregateCounter(t, data, []string{"identity_evidence", tc.kind, tc.cause}, tc.want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCNBCChallengeMetricsAreGlobalPageSignalsNotRootScoped(t *testing.T) {
|
||||
const body = "Synthetic editorial paragraph " + granularMetricCanary + ". "
|
||||
text := strings.Repeat(body, 100)
|
||||
pages := map[string]string{}
|
||||
for i, marker := range []string{`<aside id="challengeGate">verification overlay</aside>`, `<div id="challengeGate">verification overlay</div>`} {
|
||||
url := fmt.Sprintf("https://www.cnbc.com/2026/02/02/challenge-fixture-%d.html", i+1)
|
||||
outside, inside := marker, ""
|
||||
if i == 1 {
|
||||
outside, inside = "", marker
|
||||
}
|
||||
pages[url] = `<link rel="canonical" href="` + url + `">` + outside + `<div data-module="ArticleBody"><p>` + text + `</p>` + inside + `</div>`
|
||||
}
|
||||
metrics := fetchMetricsForFixturePages(t, "cnbc_business", pages)
|
||||
data := requireAnonymousAggregate(t, metrics, "www.cnbc.com/2026/02/02/", granularMetricCanary, "verification overlay")
|
||||
if metrics.Attempted != 2 || metrics.HTTP.TwoXX != 2 || metrics.Root.Yes != 2 || metrics.Identity.Yes != 2 || metrics.Length.Large != 2 {
|
||||
t.Fatal("CNBC challenge fixtures did not retain anonymous page/root/body counters")
|
||||
}
|
||||
// Challenges can cover the entire rendered page, including when the marker
|
||||
// sits beside or inside the editorial root. Measure them as page-global;
|
||||
// they are never a root-scoped paywall category.
|
||||
requireAggregateCounter(t, data, []string{"blocking_evidence", "challenge", "global_page"}, 2)
|
||||
requireNoAggregateCounter(t, data, []string{"blocking_evidence", "challenge", "article_root"})
|
||||
requireNoAggregateCounter(t, data, []string{"blocking_evidence", "challenge", "outside_root"})
|
||||
}
|
||||
|
||||
func TestCNBCBlockingCauseMetricsSeparateCategoryAndEditorialScope(t *testing.T) {
|
||||
const longFixtureBody = "Synthetic editorial paragraph " + granularMetricCanary + ". "
|
||||
body := strings.Repeat(longFixtureBody, 100)
|
||||
type scenario struct {
|
||||
category string
|
||||
inside string
|
||||
outside string
|
||||
}
|
||||
scenarios := []scenario{
|
||||
{"paywall", `<div class="paywall">restricted</div>`, `<aside class="paywall">subscription prompt</aside>`},
|
||||
{"partial", `<div data-content-state="partial"></div>`, `<aside data-content-state="partial"></aside>`},
|
||||
{"truncated", `<div data-content-truncated="true"></div>`, `<aside data-content-truncated="true"></aside>`},
|
||||
{"placeholder", `<div class="article-placeholder"></div>`, `<aside class="article-placeholder"></aside>`},
|
||||
}
|
||||
pages := map[string]string{}
|
||||
wants := make(map[string]int)
|
||||
index := 0
|
||||
for _, tc := range scenarios {
|
||||
for _, scoped := range []struct {
|
||||
name, marker string
|
||||
}{{"article_root", tc.inside}, {"outside_root", tc.outside}} {
|
||||
index++
|
||||
url := fmt.Sprintf("https://www.cnbc.com/2026/02/01/fixture-%02d.html", index)
|
||||
inside, outside := "", ""
|
||||
if scoped.name == "article_root" {
|
||||
inside = scoped.marker
|
||||
} else {
|
||||
outside = scoped.marker
|
||||
}
|
||||
pages[url] = `<link rel="canonical" href="` + url + `"><aside>` + outside + `</aside><div data-module="ArticleBody"><p>` + body + `</p>` + inside + `</div>`
|
||||
wants[tc.category+"."+scoped.name] = 1
|
||||
}
|
||||
}
|
||||
for _, scoped := range []string{"article_root", "outside_root"} {
|
||||
for _, category := range []string{"accessibility", "body_conflict"} {
|
||||
index++
|
||||
url := fmt.Sprintf("https://www.cnbc.com/2026/02/01/fixture-%02d.html", index)
|
||||
metadata := map[string]any{"@type": "NewsArticle", "url": url}
|
||||
if category == "accessibility" {
|
||||
metadata["isAccessibleForFree"] = false
|
||||
} else {
|
||||
metadata["articleBody"] = "metadata body does not match the extracted fixture body"
|
||||
}
|
||||
json := jsonLD(t, metadata)
|
||||
if scoped == "article_root" {
|
||||
pages[url] = `<link rel="canonical" href="` + url + `"><div data-module="ArticleBody">` + json + `<p>` + body + `</p></div>`
|
||||
} else {
|
||||
pages[url] = `<link rel="canonical" href="` + url + `">` + json + `<div data-module="ArticleBody"><p>` + body + `</p></div>`
|
||||
}
|
||||
wants[category+"."+scoped] = 1
|
||||
}
|
||||
}
|
||||
metrics := fetchMetricsForFixturePages(t, "cnbc_business", pages)
|
||||
data := requireAnonymousAggregate(t, metrics, "www.cnbc.com/2026/02/01/", granularMetricCanary, "metadata body does not match", "article-placeholder", "subscription prompt")
|
||||
if metrics.Attempted != 12 || metrics.HTTP.TwoXX != 12 || metrics.Root.Yes != 12 || metrics.Identity.Yes != 12 || metrics.Length.Large != 12 {
|
||||
t.Fatal("CNBC fixture aggregate did not retain root, identity and long-body counts")
|
||||
}
|
||||
for name, count := range wants {
|
||||
parts := strings.SplitN(name, ".", 2)
|
||||
requireAggregateCounter(t, data, []string{"blocking_evidence", parts[0], parts[1]}, count)
|
||||
}
|
||||
}
|
||||
105
backend/internal/scraper/articlecontent/listing_identity_test.go
Normal file
105
backend/internal/scraper/articlecontent/listing_identity_test.go
Normal file
@ -0,0 +1,105 @@
|
||||
package articlecontent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAcceptedListingURLsUseHTTPSAndKeepListingIdentity(t *testing.T) {
|
||||
for _, tc := range []struct{ source, listing, fetch string }{{"yahoo_finance", "http://finance.yahoo.com/m/fixture/story?story=1#fragment", "https://finance.yahoo.com/m/fixture/story?story=1"}, {"cnbc_business", "http://www.cnbc.com/business/story?story=1#fragment", "https://www.cnbc.com/business/story?story=1"}} {
|
||||
t.Run(tc.source, func(t *testing.T) {
|
||||
calls := 0
|
||||
root := "caas-body"
|
||||
if tc.source == "cnbc_business" {
|
||||
root = "ArticleBody-articleBody"
|
||||
}
|
||||
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if r.URL.String() != tc.fetch {
|
||||
t.Fatal("unexpected fetch identity")
|
||||
}
|
||||
body := `<link rel="canonical" href="` + tc.fetch + `"><div class="` + root + `"><p>Entire fixture editorial body.</p></div>`
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
|
||||
})}
|
||||
got, err := Enrich(context.Background(), client, tc.source, []scraper.Article{{URL: tc.listing, Title: "listing title"}})
|
||||
if err != nil || calls != 1 || len(got) != 1 || got[0].URL != tc.listing || got[0].Title != "listing title" || got[0].PublishedAt != nil || scraper.ContentStatus(got[0]) != scraper.ContentComplete {
|
||||
t.Fatal("accepted listing identity or nullable-date body lost")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestUnsafeListingURLsNeverFetchOrDisappear(t *testing.T) {
|
||||
for _, url := range []string{"https://127.0.0.1/private", "https://finance.yahoo.com.evil.invalid/story", "https://user:secret@finance.yahoo.com/story", "https://finance.yahoo.com:443/story", "file:///private", "https://www.cnbc.com/story"} {
|
||||
calls := 0
|
||||
c := &http.Client{Transport: roundTrip(func(*http.Request) (*http.Response, error) { calls++; t.Fatal("unsafe fetch"); return nil, nil })}
|
||||
got, err := Enrich(context.Background(), c, "yahoo_finance", []scraper.Article{{URL: url, Title: "preserved"}})
|
||||
if err != nil || calls != 0 || len(got) != 1 || got[0].URL != url || scraper.ContentStatus(got[0]) != scraper.ContentUnavailable {
|
||||
t.Fatal("unsafe listing lost or fetched")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestSameSourceRedirectRequiresObservedChainAndKeepsListing(t *testing.T) {
|
||||
original := "https://finance.yahoo.com/m/story"
|
||||
final := "https://finance.yahoo.com/news/story"
|
||||
calls := 0
|
||||
c := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return &http.Response{StatusCode: 302, Body: io.NopCloser(strings.NewReader("")), Header: http.Header{"Location": []string{final}}, Request: r}, nil
|
||||
}
|
||||
body := `<link rel="canonical" href="` + final + `"><div class="caas-body"><p>Entire fixture editorial body.</p></div>`
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
|
||||
})}
|
||||
got, err := Enrich(context.Background(), c, "yahoo_finance", []scraper.Article{{URL: original, Title: "preserved"}})
|
||||
if err != nil || calls != 2 || len(got) != 1 || got[0].URL != original || scraper.ContentStatus(got[0]) != scraper.ContentComplete {
|
||||
t.Fatal("verified same-source redirect lost listing association")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryIdentitiesAndUnobservedRedirectsCannotCrossAssociateBodies(t *testing.T) {
|
||||
first := "https://finance.yahoo.com/news/story?id=1"
|
||||
second := "https://finance.yahoo.com/news/story?id=2"
|
||||
calls := 0
|
||||
c := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
body := `<link rel="canonical" href="` + first + `"><div class="caas-body"><p>Entire fixture body.</p></div>`
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
|
||||
})}
|
||||
got, err := Enrich(context.Background(), c, "yahoo_finance", []scraper.Article{{URL: first}, {URL: second}})
|
||||
if err != nil || calls != 2 || scraper.ContentStatus(got[0]) != scraper.ContentComplete || scraper.ContentStatus(got[1]) != scraper.ContentUnavailable {
|
||||
t.Fatal("semantic query identities were merged")
|
||||
}
|
||||
c.Transport = roundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
fake, _ := http.NewRequest("GET", first, nil)
|
||||
body := `<link rel="canonical" href="` + first + `"><div class="caas-body"><p>Entire fixture body.</p></div>`
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: fake}, nil
|
||||
})
|
||||
got, err = Enrich(context.Background(), c, "yahoo_finance", []scraper.Article{{URL: second}})
|
||||
if err != nil || scraper.ContentStatus(got[0]) != scraper.ContentUnavailable {
|
||||
t.Fatal("unobserved redirect accepted")
|
||||
}
|
||||
}
|
||||
func TestRedirectUpgradeNeverSendsHTTPAndNullableDateDoesNotInvalidateBody(t *testing.T) {
|
||||
first := "https://www.cnbc.com/business/original"
|
||||
final := "https://www.cnbc.com/business/final"
|
||||
calls := 0
|
||||
c := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if r.URL.Scheme != "https" {
|
||||
t.Fatal("plaintext request")
|
||||
}
|
||||
if calls == 1 {
|
||||
return &http.Response{StatusCode: 302, Body: io.NopCloser(strings.NewReader("")), Header: http.Header{"Location": []string{strings.Replace(final, "https://", "http://", 1)}}, Request: r}, nil
|
||||
}
|
||||
body := `<link rel="canonical" href="` + final + `"><meta property="article:published_time" content="2026-01-02T03:04:05Z"><meta property="article:published_time" content="2026-01-03T03:04:05Z"><div class="ArticleBody-articleBody"><p>Entire fixture body.</p></div>`
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
|
||||
})}
|
||||
got, err := Enrich(context.Background(), c, "cnbc_business", []scraper.Article{{URL: first}})
|
||||
if err != nil || calls != 2 || got[0].URL != first || got[0].PublishedAt != nil || scraper.ContentStatus(got[0]) != scraper.ContentComplete {
|
||||
t.Fatal("redirect or independent date contract broken")
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,42 @@
|
||||
package articlecontent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
func TestRedirectToLiteralPrivateOrReservedAddressNeverReachesTransport(t *testing.T) {
|
||||
for _, target := range []string{
|
||||
"https://127.0.0.1/private",
|
||||
"https://[::1]/private",
|
||||
"https://10.0.0.1/private",
|
||||
"https://169.254.1.1/private",
|
||||
"https://240.0.0.1/private",
|
||||
"https://finance.yahoo.com.evil.invalid/private",
|
||||
} {
|
||||
t.Run("blocked_redirect", func(t *testing.T) {
|
||||
calls := 0
|
||||
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if calls != 1 || r.URL.Host != "finance.yahoo.com" {
|
||||
t.Fatal("redirect target unexpectedly reached the transport")
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusFound,
|
||||
Header: http.Header{"Location": []string{target}},
|
||||
Body: io.NopCloser(strings.NewReader("")),
|
||||
Request: r,
|
||||
}, nil
|
||||
})}
|
||||
got, err := Enrich(context.Background(), client, "yahoo_finance", []scraper.Article{{URL: "https://finance.yahoo.com/news/fixture.html"}})
|
||||
if err != nil || calls != 1 || len(got) != 1 || got[0].Content != "" || scraper.ContentStatus(got[0]) != scraper.ContentUnavailable {
|
||||
t.Fatal("redirect to a forbidden IP or host was followed")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user