Add Chrome 152 fingerprint and navigation headers, Accept-Language by TLD, challenge/block classification, and a cookie jar that can be saved and exported per host. Bumps x/net, x/text, x/crypto and circl for govulncheck findings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
271 lines
10 KiB
Go
271 lines
10 KiB
Go
package fetch
|
|
|
|
import (
|
|
"compress/gzip"
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
fhttp "github.com/bogdanfinn/fhttp"
|
|
)
|
|
|
|
func TestSecCHUA(t *testing.T) {
|
|
// Real values, from tls-client's examples.
|
|
for major, want := range map[int]string{
|
|
105: `"Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"`,
|
|
107: `"Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"`,
|
|
} {
|
|
if got := secCHUA(major); got != want { t.Errorf("secCHUA(%d) = %s, want %s", major, got, want) }
|
|
}
|
|
}
|
|
|
|
func TestAcceptLanguage(t *testing.T) {
|
|
for host, want := range map[string]string{
|
|
"www.amazon.de": "de-DE,",
|
|
"www.Amazon.co.uk": "en-GB,",
|
|
"www.amazon.fr": "fr-FR,",
|
|
"www.amazon.it": "it-IT,",
|
|
"www.amazon.es": "es-ES,",
|
|
"www.amazon.nl": "nl-NL,",
|
|
"www.amazon.com": "en-US,",
|
|
"www.amazon.co.jp": "en-US,",
|
|
"127.0.0.1": "en-US,",
|
|
} {
|
|
if got := acceptLanguage(host); !strings.HasPrefix(got, want) { t.Errorf("acceptLanguage(%q) = %q, want prefix %q", host, got, want) }
|
|
}
|
|
}
|
|
|
|
func TestDefaultBrowserMatchesProfile(t *testing.T) {
|
|
b := DefaultBrowser()
|
|
if !strings.Contains(b.UserAgent, "Chrome/152.0.0.0") { t.Errorf("user agent %q does not match Chrome %d", b.UserAgent, b.Major) }
|
|
|
|
want := map[string]string{"windows": "Windows", "darwin": "macOS", "linux": "Linux"}[runtime.GOOS]
|
|
if want != "" && b.Platform != want { t.Errorf("platform = %q, want %q", b.Platform, want) }
|
|
}
|
|
|
|
func TestClassify(t *testing.T) {
|
|
cf := http.Header{"Cf-Mitigated": {"challenge"}}
|
|
|
|
for name, tc := range map[string]struct {
|
|
status int
|
|
header http.Header
|
|
finalURL string
|
|
body string
|
|
verdict Verdict
|
|
challenge string
|
|
}{
|
|
"product page": {200, nil, "https://www.amazon.de/dp/X", "<title>Metro</title>", OK, ""},
|
|
"cf script on normal page": {200, nil, "", `<script src="/cdn-cgi/challenge-platform/scripts/jsd/main.js">`, OK, ""},
|
|
"turnstile in a form": {200, nil, "", `<script src="https://challenges.cloudflare.com/turnstile/v0/api.js">`, OK, ""},
|
|
"not found": {404, nil, "", "<title>Page not found</title>", NotFound, ""},
|
|
"gone": {410, nil, "", "", NotFound, ""},
|
|
"cf header": {403, cf, "", "", Challenge, "cloudflare"},
|
|
"cf js challenge": {503, nil, "", "<script>window._cf_chl_opt={}</script>", Challenge, "cloudflare"},
|
|
"cf title": {403, nil, "", "<title>Just a moment...</title>", Challenge, "cloudflare"},
|
|
"amazon captcha 200": {200, nil, "", `<form method="get" action="/errors/validateCaptcha">`, Challenge, "amazon-captcha"},
|
|
"amazon captcha url": {200, nil, "https://www.amazon.de/errors/validateCaptcha?x=1", "", Challenge, "amazon-captcha"},
|
|
"datadome": {403, nil, "", `<iframe src="https://geo.captcha-delivery.com/captcha/">`, Challenge, "datadome"},
|
|
"turnstile on 403": {403, nil, "", `<script src="https://challenges.cloudflare.com/turnstile/v0/api.js">`, Challenge, "turnstile"},
|
|
"plain 403": {403, nil, "", "Access Denied", Blocked, ""},
|
|
"429": {429, nil, "", "slow down", Blocked, ""},
|
|
"amazon 503 dog": {503, nil, "", "Sorry! Something went wrong!", Blocked, ""},
|
|
"500": {500, nil, "", "", HTTPError, ""},
|
|
} {
|
|
t.Run(name, func(t *testing.T) {
|
|
header := tc.header
|
|
if header == nil { header = http.Header{} }
|
|
|
|
v, c := classify(tc.status, header, tc.finalURL, []byte(tc.body))
|
|
if v != tc.verdict || c != tc.challenge { t.Errorf("got %s/%q, want %s/%q", v, c, tc.verdict, tc.challenge) }
|
|
})
|
|
}
|
|
}
|
|
|
|
func mustURL(t *testing.T, raw string) *url.URL {
|
|
t.Helper()
|
|
|
|
u, err := url.Parse(raw)
|
|
if err != nil { t.Fatal(err) }
|
|
|
|
return u
|
|
}
|
|
|
|
func cookieNames(cs []*fhttp.Cookie) string {
|
|
names := make([]string, len(cs))
|
|
for i, c := range cs { names[i] = c.Name + "=" + c.Value }
|
|
|
|
return strings.Join(names, " ")
|
|
}
|
|
|
|
func TestJarExportImport(t *testing.T) {
|
|
now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
|
|
|
|
j := NewJar()
|
|
j.now = func() time.Time { return now }
|
|
j.SetCookies(mustURL(t, "https://www.amazon.de/dp/X"), []*fhttp.Cookie{
|
|
{Name: "session-id", Value: "1", Domain: ".amazon.de", Path: "/"},
|
|
{Name: "host", Value: "2"},
|
|
{Name: "short", Value: "3", MaxAge: 60},
|
|
{Name: "old", Value: "4", Expires: now.Add(-time.Hour)},
|
|
})
|
|
|
|
exported := j.Export()
|
|
got := exported["www.amazon.de"]
|
|
if len(got) != 3 { t.Fatalf("exported %d cookies, want 3: %+v", len(got), got) }
|
|
|
|
byName := map[string]Cookie{}
|
|
for _, c := range got { byName[c.Name] = c }
|
|
|
|
if c := byName["host"]; !c.HostOnly || c.Domain != "www.amazon.de" || c.Path != "/dp" { t.Errorf("host-only cookie: %+v", c) }
|
|
if c := byName["session-id"]; c.HostOnly || c.Domain != "amazon.de" { t.Errorf("domain cookie: %+v", c) }
|
|
if c := byName["short"]; !c.Expires.Equal(now.Add(time.Minute)) { t.Errorf("max-age cookie expires %v", c.Expires) }
|
|
|
|
// A new jar gets the same cookies, scoped the same way.
|
|
k := NewJar()
|
|
k.now = j.now
|
|
for host, cs := range exported { k.Import(host, cs) }
|
|
|
|
if got := cookieNames(k.Cookies(mustURL(t, "https://www.amazon.de/dp/Y"))); !strings.Contains(got, "host=2") || !strings.Contains(got, "session-id=1") {
|
|
t.Errorf("www.amazon.de/dp cookies after import: %s", got)
|
|
}
|
|
|
|
if got := cookieNames(k.Cookies(mustURL(t, "https://smile.amazon.de/"))); got != "session-id=1" { t.Errorf("smile.amazon.de cookies: %q, want only the domain cookie", got) }
|
|
|
|
// The server deletes a cookie.
|
|
j.SetCookies(mustURL(t, "https://www.amazon.de/"), []*fhttp.Cookie{{Name: "session-id", Domain: ".amazon.de", Path: "/", MaxAge: -1}})
|
|
for _, c := range j.Export()["www.amazon.de"] {
|
|
if c.Name == "session-id" { t.Errorf("deleted cookie still exported") }
|
|
}
|
|
|
|
// Later the max-age cookie runs out.
|
|
now = now.Add(2 * time.Minute)
|
|
for _, c := range j.Export()["www.amazon.de"] {
|
|
if c.Name == "short" { t.Errorf("expired cookie still exported") }
|
|
}
|
|
}
|
|
|
|
func TestJarSaveLoad(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), "sub", "cookies.json")
|
|
|
|
j := NewJar()
|
|
j.SetCookies(mustURL(t, "https://www.amazon.co.uk/"), []*fhttp.Cookie{{Name: "a", Value: "1", Path: "/", Expires: time.Now().Add(time.Hour)}})
|
|
if err := j.Save(path); err != nil { t.Fatal(err) }
|
|
|
|
if runtime.GOOS != "windows" {
|
|
info, err := os.Stat(path)
|
|
if err != nil { t.Fatal(err) }
|
|
if perm := info.Mode().Perm(); perm != 0o600 { t.Errorf("cookie file mode %o, want 600", perm) }
|
|
}
|
|
|
|
k := NewJar()
|
|
if err := k.Load(path); err != nil { t.Fatal(err) }
|
|
if got := cookieNames(k.Cookies(mustURL(t, "https://www.amazon.co.uk/x"))); got != "a=1" { t.Errorf("loaded cookies: %q", got) }
|
|
|
|
if err := NewJar().Load(filepath.Join(t.TempDir(), "missing.json")); err != nil { t.Errorf("missing file: %v", err) }
|
|
}
|
|
|
|
func newTestClient(t *testing.T, opts Options) *Client {
|
|
t.Helper()
|
|
|
|
c, err := New(opts)
|
|
if err != nil { t.Fatal(err) }
|
|
|
|
return c
|
|
}
|
|
|
|
func TestClientGet(t *testing.T) {
|
|
var seen []*http.Request
|
|
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
seen = append(seen, r)
|
|
|
|
switch r.URL.Path {
|
|
case "/start":
|
|
http.SetCookie(w, &http.Cookie{Name: "sid", Value: "abc", Path: "/"})
|
|
http.Redirect(w, r, "/product", http.StatusFound)
|
|
case "/product":
|
|
w.Header().Set("Content-Encoding", "gzip")
|
|
zw := gzip.NewWriter(w)
|
|
_, _ = zw.Write([]byte("<title>Metro 2039</title>"))
|
|
_ = zw.Close()
|
|
case "/missing":
|
|
http.NotFound(w, r)
|
|
default:
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
|
|
c := newTestClient(t, Options{})
|
|
|
|
resp, err := c.Get(context.Background(), srv.URL+"/start")
|
|
if err != nil { t.Fatal(err) }
|
|
|
|
if resp.Verdict != OK || resp.Status != 200 { t.Errorf("verdict %s, status %d", resp.Verdict, resp.Status) }
|
|
if resp.FinalURL != srv.URL+"/product" { t.Errorf("final URL %q", resp.FinalURL) }
|
|
if string(resp.Body) != "<title>Metro 2039</title>" { t.Errorf("body %q, want it decompressed", resp.Body) }
|
|
|
|
if len(seen) != 2 { t.Fatalf("server saw %d requests, want 2", len(seen)) }
|
|
|
|
first := seen[0]
|
|
for name, want := range map[string]string{
|
|
"User-Agent": "Chrome/152.0.0.0",
|
|
"Sec-Ch-Ua": `"Google Chrome";v="152"`,
|
|
"Sec-Ch-Ua-Platform": `"`,
|
|
"Sec-Fetch-Mode": "navigate",
|
|
"Accept-Language": "en-US",
|
|
"Accept-Encoding": "gzip",
|
|
} {
|
|
if got := first.Header.Get(name); !strings.Contains(got, want) { t.Errorf("%s = %q, want it to contain %q", name, got, want) }
|
|
}
|
|
|
|
if got := seen[1].Header.Get("Cookie"); got != "sid=abc" { t.Errorf("cookie on redirect = %q, want sid=abc", got) }
|
|
|
|
resp, err = c.Get(context.Background(), srv.URL+"/missing")
|
|
if err != nil { t.Fatal(err) }
|
|
if resp.Verdict != NotFound { t.Errorf("404 verdict %s", resp.Verdict) }
|
|
|
|
if got := c.Jar().Export()["127.0.0.1"]; len(got) != 1 || got[0].Name != "sid" { t.Errorf("jar after requests: %+v", got) }
|
|
}
|
|
|
|
func TestClientBodyLimit(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
_, _ = w.Write([]byte(strings.Repeat("x", 2048)))
|
|
}))
|
|
defer srv.Close()
|
|
|
|
_, err := newTestClient(t, Options{MaxBody: 1024}).Get(context.Background(), srv.URL)
|
|
if !errors.Is(err, ErrBodyTooLarge) { t.Errorf("got %v, want ErrBodyTooLarge", err) }
|
|
}
|
|
|
|
func TestClientContextCancel(t *testing.T) {
|
|
release := make(chan struct{})
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
select {
|
|
case <-release:
|
|
case <-r.Context().Done():
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
defer close(release)
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
|
defer cancel()
|
|
|
|
start := time.Now()
|
|
if _, err := newTestClient(t, Options{}).Get(ctx, srv.URL); err == nil { t.Fatal("want an error from a cancelled request") }
|
|
if elapsed := time.Since(start); elapsed > 5*time.Second { t.Errorf("cancel took %s", elapsed) }
|
|
}
|
|
|
|
func TestClientRejectsOtherSchemes(t *testing.T) {
|
|
if _, err := newTestClient(t, Options{}).Get(context.Background(), "file:///etc/passwd"); err == nil { t.Error("want an error for file://") }
|
|
}
|