feat(scraper): bound article enrichment diagnostics (#40)

This commit is contained in:
2026-11-25 00:07:45 +01:00
parent a3c70670f6
commit 6883b3976b
53 changed files with 4049 additions and 68 deletions

View File

@ -0,0 +1,98 @@
// Package sourcehttp provides DNS-pinned, proxy-free source connections.
package sourcehttp
import (
"context"
"errors"
"net"
"net/http"
"net/netip"
"strings"
"time"
)
type Resolver interface {
LookupNetIP(context.Context, string, string) ([]netip.Addr, error)
}
type DialFunc func(context.Context, string, string) (net.Conn, error)
var errUnavailable = errors.New("source connection unavailable")
var forbidden = prefixes(
"0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24", "192.0.2.0/24", "192.88.99.0/24", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "224.0.0.0/4", "240.0.0.0/4",
"2001::/23", "2001:db8::/32", "2002::/16", "3fff::/20",
)
func prefixes(values ...string) []netip.Prefix {
out := make([]netip.Prefix, 0, len(values))
for _, v := range values {
out = append(out, netip.MustParsePrefix(v))
}
return out
}
// IsPublicAddress rejects special-use and non-global destinations.
func IsPublicAddress(ip netip.Addr) bool {
if !ip.IsValid() || ip.Zone() != "" {
return false
}
ip = ip.Unmap()
if !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
return false
}
// Only currently allocated global IPv6 unicast, excluding transition/special ranges.
if ip.Is6() && !netip.MustParsePrefix("2000::/3").Contains(ip) {
return false
}
for _, p := range forbidden {
if p.Contains(ip) {
return false
}
}
return true
}
// NewTransport resolves exactly once per new connection, validates the entire
// answer set, and dials only numeric addresses. TLS still uses the request host.
// Nil dependencies select the production resolver and dialer; fixtures inject both.
func NewTransport(resolver Resolver, dial DialFunc) *http.Transport {
if resolver == nil {
resolver = net.DefaultResolver
}
if dial == nil {
dial = (&net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second}).DialContext
}
return &http.Transport{
Proxy: nil, TLSHandshakeTimeout: 10 * time.Second, ResponseHeaderTimeout: 15 * time.Second,
IdleConnTimeout: 90 * time.Second, MaxIdleConns: 20, ForceAttemptHTTP2: true,
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
host, port, err := net.SplitHostPort(address)
if err != nil || port != "443" {
return nil, errUnavailable
}
switch strings.ToLower(host) {
case "finance.yahoo.com", "feeds.finance.yahoo.com", "www.cnbc.com":
default:
return nil, errUnavailable
}
ips, err := resolver.LookupNetIP(ctx, "ip", host)
if err != nil || len(ips) == 0 {
return nil, errUnavailable
}
for _, ip := range ips {
if !IsPublicAddress(ip) {
return nil, errUnavailable
}
}
for _, ip := range ips {
conn, err := dial(ctx, network, net.JoinHostPort(ip.Unmap().String(), port))
if err == nil {
return conn, nil
}
if ctx.Err() != nil {
break
}
}
return nil, errUnavailable
},
}
}

View File

@ -0,0 +1,149 @@
package sourcehttp
import (
"bufio"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"errors"
"io"
"math/big"
"net"
"net/http"
"net/netip"
"testing"
"time"
)
type resolverFunc func(context.Context, string, string) ([]netip.Addr, error)
func (f resolverFunc) LookupNetIP(c context.Context, n, h string) ([]netip.Addr, error) {
return f(c, n, h)
}
func TestForbiddenDNSAnswersNeverDial(t *testing.T) {
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com"} {
for _, value := range []string{"0.0.0.0", "10.0.0.1", "100.64.0.1", "127.0.0.1", "169.254.1.1", "172.16.0.1", "192.168.0.1", "192.0.0.9", "192.0.2.1", "198.18.0.1", "198.51.100.1", "203.0.113.1", "224.0.0.1", "240.0.0.1", "255.255.255.255", "::", "::1", "fc00::1", "fe80::1", "ff02::1", "2001:db8::1", "2002:0808:0808::1", "64:ff9b::808:808", "2001::1", "3fff::1", "::ffff:127.0.0.1"} {
t.Run(host+"/"+value, func(t *testing.T) {
dials := 0
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr(value)}, nil
}), func(context.Context, string, string) (net.Conn, error) { dials++; return nil, errors.New("fixture") })
// HTTP cannot reach a socket or send a request when DNS is rejected.
req, _ := http.NewRequest("GET", "https://"+host+"/fixture", nil)
if _, err := tr.RoundTrip(req); err == nil || dials != 0 {
t.Fatal("forbidden DNS answer reached dial")
}
})
}
}
}
func TestDNSFailsClosedAndNumericPinning(t *testing.T) {
for _, answers := range [][]netip.Addr{nil, {netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("127.0.0.1")}, {netip.Addr{}}, {netip.MustParseAddr("fe80::1%fixture")}} {
dials := 0
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) { return answers, nil }), func(context.Context, string, string) (net.Conn, error) { dials++; return nil, errors.New("fixture") })
if _, err := tr.DialContext(context.Background(), "tcp", "finance.yahoo.com:443"); err == nil || dials != 0 {
t.Fatal("invalid/mixed answer allowed")
}
}
for _, value := range []string{"8.8.8.8", "2606:4700:4700::1111", "::ffff:8.8.8.8"} {
lookups, dials := 0, 0
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) {
lookups++
return []netip.Addr{netip.MustParseAddr(value)}, nil
}), func(_ context.Context, _ string, address string) (net.Conn, error) {
dials++
if address != net.JoinHostPort(netip.MustParseAddr(value).Unmap().String(), "443") {
t.Fatal("dial was not pinned")
}
return nil, errors.New("fixture")
})
tr.DialContext(context.Background(), "tcp", "finance.yahoo.com:443")
if lookups != 1 || dials != 1 || tr.Proxy != nil {
t.Fatal("resolver/dial/proxy contract failed")
}
}
}
func TestPinnedTLSRetainsSNIAndHost(t *testing.T) {
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com"} {
t.Run(host, func(t *testing.T) {
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
template := &x509.Certificate{SerialNumber: big.NewInt(1), DNSNames: []string{host}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
t.Fatal("certificate fixture failed")
}
roots := x509.NewCertPool()
cert, _ := x509.ParseCertificate(der)
roots.AddCert(cert)
observed := make(chan bool, 1)
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
}), func(_ context.Context, _ string, address string) (net.Conn, error) {
if address != "8.8.8.8:443" {
t.Error("unpinned dial")
}
client, server := net.Pipe()
go func() {
defer server.Close()
server.SetDeadline(time.Now().Add(3 * time.Second))
conn := tls.Server(server, &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}})
r, err := http.ReadRequest(bufio.NewReader(conn))
if err != nil {
observed <- false
return
}
observed <- r.Host == host && conn.ConnectionState().ServerName == host
io.WriteString(conn, "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
}()
return client, nil
})
tr.TLSClientConfig = &tls.Config{RootCAs: roots}
defer tr.CloseIdleConnections()
req, _ := http.NewRequest("GET", "https://"+host+"/fixture", nil)
resp, err := tr.RoundTrip(req)
if err != nil {
t.Fatal("pinned TLS fixture failed")
}
resp.Body.Close()
if !<-observed {
t.Fatal("TLS SNI or Host changed")
}
})
}
}
func TestEveryNewConnectionRevalidatesDNS(t *testing.T) {
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com"} {
lookups, dials := 0, 0
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) {
lookups++
if lookups == 1 {
return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
}
return []netip.Addr{netip.MustParseAddr("127.0.0.1")}, nil
}), func(context.Context, string, string) (net.Conn, error) { dials++; return nil, errors.New("fixture") })
tr.DialContext(context.Background(), "tcp", net.JoinHostPort(host, "443"))
tr.DialContext(context.Background(), "tcp", net.JoinHostPort(host, "443"))
if lookups != 2 || dials != 1 {
t.Fatal("rebound DNS reached dial")
}
}
}
func TestResolverErrorsAndDestinationGuardsNeverDial(t *testing.T) {
lookups, dials := 0, 0
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) {
lookups++
return nil, errors.New("private resolver error")
}), func(context.Context, string, string) (net.Conn, error) { dials++; return nil, errors.New("fixture") })
for _, address := range []string{"finance.yahoo.com:443", "www.cnbc.com:443", "finance.yahoo.com:80", "finance.yahoo.com:444", "127.0.0.1:443", "[::1]:443", "finance.yahoo.com.evil.invalid:443"} {
if _, err := tr.DialContext(context.Background(), "tcp", address); err != errUnavailable {
t.Fatal("unsafe or raw connection error")
}
}
if lookups != 2 || dials != 0 {
t.Fatal("destination guard or failed DNS allowed dial")
}
}