diff --git a/go.mod b/go.mod index 16fa08b..f52d780 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,25 @@ module git.security-command.org/Overlord/dibs go 1.26.0 -require github.com/pelletier/go-toml/v2 v2.4.3 +require ( + github.com/bogdanfinn/fhttp v0.6.9 + github.com/bogdanfinn/tls-client v1.16.0 + github.com/pelletier/go-toml/v2 v2.4.3 + golang.org/x/net v0.60.0 +) + +require ( + github.com/andybalholm/brotli v1.2.0 // indirect + github.com/bdandy/go-errors v1.2.2 // indirect + github.com/bdandy/go-socks4 v1.2.3 // indirect + github.com/bogdanfinn/quic-go-utls v1.0.10-utls // indirect + github.com/bogdanfinn/utls v1.7.8-barnius // indirect + github.com/bogdanfinn/websocket v1.5.6-barnius // indirect + github.com/cloudflare/circl v1.6.5 // indirect + github.com/klauspost/compress v1.18.2 // indirect + github.com/quic-go/qpack v0.6.0 // indirect + github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect + golang.org/x/crypto v0.57.0 // indirect + golang.org/x/sys v0.48.0 // indirect + golang.org/x/text v0.42.0 // indirect +) diff --git a/go.sum b/go.sum index ddaf7d6..588e974 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,52 @@ +github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ= +github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= +github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11Q= +github.com/bdandy/go-errors v1.2.2/go.mod h1:NkYHl4Fey9oRRdbB1CoC6e84tuqQHiqrOcZpqFEkBxM= +github.com/bdandy/go-socks4 v1.2.3 h1:Q6Y2heY1GRjCtHbmlKfnwrKVU/k81LS8mRGLRlmDlic= +github.com/bdandy/go-socks4 v1.2.3/go.mod h1:98kiVFgpdogR8aIGLWLvjDVZ8XcKPsSI/ypGrO+bqHI= +github.com/bogdanfinn/fhttp v0.6.9 h1:F9MsWR1K6JMRlXN4Q/MfjYmptr29nCdycQo+OPBG5U0= +github.com/bogdanfinn/fhttp v0.6.9/go.mod h1:7phoj3f/q54WuiTnCTlAhEoaVcdlruKkSzCSD47LzHk= +github.com/bogdanfinn/quic-go-utls v1.0.10-utls h1:oZN+J3OKMmWaVbI/sx4ULvHiAXbWJKVcvEFW4fkybMU= +github.com/bogdanfinn/quic-go-utls v1.0.10-utls/go.mod h1:bBLJ2Vy68Q7y6VfbG9czd825rTcQua7n+y12RM9Q588= +github.com/bogdanfinn/tls-client v1.16.0 h1:km3YLI6CMRLZnfrC+hGStePPryIicd3hoxFQvHB1itY= +github.com/bogdanfinn/tls-client v1.16.0/go.mod h1:TxbiXlpZhNN5xmxzsr3KhNAeqoEEPJafwgBbyp26Phc= +github.com/bogdanfinn/utls v1.7.8-barnius h1:wRT83mP4hmuMM1/lIpLKKhzaEuyEKjux7VSj7XHFXdg= +github.com/bogdanfinn/utls v1.7.8-barnius/go.mod h1:o5v09jf+9ayMEfcP+8sssNdSMm278cyhBV25H8jb5Lw= +github.com/bogdanfinn/websocket v1.5.6-barnius h1:QpdWVEZ9rKtcT7C2pU19uE2KQw2XevuKTDTzLxfDi/I= +github.com/bogdanfinn/websocket v1.5.6-barnius/go.mod h1:41/rXLDWpqJ5A4gOKSY/z4NLbW/hHZHneRcYM0kbpxA= +github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA= +github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk= +github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4= github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY= github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= +github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leXMWAEjS0mTZ5kUU9KRBriQJc= +github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5/go.mod h1:2JjD2zLQYH5HO74y5+aE3remJQvl6q4Sn6aWA2wD1Ng= +github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= +github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= +go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= +go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/net v0.0.0-20211104170005-ce137452f963/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= +golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/config/positions.go b/internal/config/positions.go index 97978c4..6c4ec40 100644 --- a/internal/config/positions.go +++ b/internal/config/positions.go @@ -22,11 +22,12 @@ func indexPositions(doc []byte) positions { // A parse error stops the index early. The decoder reports it. for p.NextExpression() { e := p.Expression() + if e == nil { continue } switch e.Kind { case unstable.Table, unstable.ArrayTable: keys, first := keyParts(e.Key()) - path := strings.Join(keys, ".") + path := strings.Join(keys, ".") if e.Kind == unstable.ArrayTable { n := arrays[path] arrays[path]++ @@ -36,6 +37,8 @@ func indexPositions(doc []byte) positions { ps.add(&p, path, first) case unstable.KeyValue: ps.keyValue(&p, prefix, e) + default: + // Comments and other expressions have no key to record. } } @@ -56,21 +59,21 @@ func (ps positions) keyValue(p *unstable.Parser, prefix string, kv *unstable.Nod func (ps positions) value(p *unstable.Parser, path string, v *unstable.Node) { switch v.Kind { - case unstable.Array: - it := v.Children() - for i := 0; it.Next(); i++ { - el := it.Node() - elPath := fmt.Sprintf("%s[%d]", path, i) - ps.add(p, elPath, el) - ps.value(p, elPath, el) - } - case unstable.InlineTable: - it := v.Children() - for it.Next() { - if kv := it.Node(); kv.Kind == unstable.KeyValue { - ps.keyValue(p, path, kv) + case unstable.Array: + it := v.Children() + for i := 0; it.Next(); i++ { + el := it.Node() + elPath := fmt.Sprintf("%s[%d]", path, i) + ps.add(p, elPath, el) + ps.value(p, elPath, el) } - } + case unstable.InlineTable: + it := v.Children() + for it.Next() { + if kv := it.Node(); kv.Kind == unstable.KeyValue { ps.keyValue(p, path, kv) } + } + default: + // Scalars have no nested keys. } } diff --git a/internal/fetch/browser.go b/internal/fetch/browser.go new file mode 100644 index 0000000..4eccdd6 --- /dev/null +++ b/internal/fetch/browser.go @@ -0,0 +1,131 @@ +package fetch + +import ( + "fmt" + "net/url" + "runtime" + "strings" + + http "github.com/bogdanfinn/fhttp" + "github.com/bogdanfinn/tls-client/profiles" + "golang.org/x/net/publicsuffix" +) + +// chromeMajor must match chromeProfile: the TLS and HTTP/2 fingerprint come +// from the profile, the headers from the version. Bump both together when +// updating tls-client. +const chromeMajor = 152 + +var chromeProfile = profiles.Chrome_152 + +// Browser is the browser that requests claim to come from. +type Browser struct { + Profile profiles.ClientProfile + Major int + UserAgent string + Platform string // sec-ch-ua-platform, without quotes +} + +// DefaultBrowser returns desktop Chrome on the current OS, so that cookies +// a real browser on this machine obtains later stay valid for us. +func DefaultBrowser() Browser { + ua, platform := "Windows NT 10.0; Win64; x64", "Windows" + + switch runtime.GOOS { + case "darwin": + ua, platform = "Macintosh; Intel Mac OS X 10_15_7", "macOS" + case "linux": + ua, platform = "X11; Linux x86_64", "Linux" + default: + // Windows, and anything else, which Chrome supports no better. + } + + return Browser{ + Profile: chromeProfile, + Major: chromeMajor, + UserAgent: fmt.Sprintf("Mozilla/5.0 (%s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%d.0.0.0 Safari/537.36", ua, chromeMajor), + Platform: platform, + } +} + +// navigationHeaders are the headers Chrome sends when the user opens u by +// typing it or from a bookmark, in Chrome's order. +func (b Browser) navigationHeaders(u *url.URL) http.Header { + return http.Header{ + "sec-ch-ua": {secCHUA(b.Major)}, + "sec-ch-ua-mobile": {"?0"}, + "sec-ch-ua-platform": {`"` + b.Platform + `"`}, + "upgrade-insecure-requests": {"1"}, + "user-agent": {b.UserAgent}, + "accept": {"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"}, + "sec-fetch-site": {"none"}, + "sec-fetch-mode": {"navigate"}, + "sec-fetch-user": {"?1"}, + "sec-fetch-dest": {"document"}, + "accept-encoding": {"gzip, deflate, br, zstd"}, + "accept-language": {acceptLanguage(u.Hostname())}, + "priority": {"u=0, i"}, + http.HeaderOrderKey: { + "sec-ch-ua", + "sec-ch-ua-mobile", + "sec-ch-ua-platform", + "upgrade-insecure-requests", + "user-agent", + "accept", + "sec-fetch-site", + "sec-fetch-mode", + "sec-fetch-user", + "sec-fetch-dest", + "accept-encoding", + "accept-language", + "cookie", + "priority", + }, + } +} + +// secCHUA builds Chrome's sec-ch-ua brand list. Chrome derives the GREASE +// brand and the brand order from its major version (GenerateBrandVersionList +// in Chromium's user_agent_utils.cc), so a fixed string would give us away +// after an update. +func secCHUA(major int) string { + chars := []string{" ", "(", ":", "-", ".", "/", ")", ";", "=", "?", "_"} + versions := []string{"8", "99", "24"} + orders := [][3]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}} + + grease := fmt.Sprintf(`"Not%sA%sBrand";v="%s"`, chars[major%len(chars)], chars[(major+1)%len(chars)], versions[major%len(versions)]) + order := orders[major%len(orders)] + + var brands [3]string + brands[order[0]] = grease + brands[order[1]] = fmt.Sprintf(`"Chromium";v="%d"`, major) + brands[order[2]] = fmt.Sprintf(`"Google Chrome";v="%d"`, major) + + return strings.Join(brands[:], ", ") +} + +// languages maps a public suffix to the Accept-Language a local shopper's +// browser would send. +var languages = map[string]string{ + "de": "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7", + "at": "de-AT,de;q=0.9,en-US;q=0.8,en;q=0.7", + "ch": "de-CH,de;q=0.9,en-US;q=0.8,en;q=0.7", + "co.uk": "en-GB,en;q=0.9", + "uk": "en-GB,en;q=0.9", + "ie": "en-IE,en;q=0.9", + "fr": "fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7", + "be": "nl-BE,nl;q=0.9,fr-BE;q=0.8,fr;q=0.7,en;q=0.6", + "it": "it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7", + "es": "es-ES,es;q=0.9,en-US;q=0.8,en;q=0.7", + "nl": "nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7", + "pl": "pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7", + "se": "sv-SE,sv;q=0.9,en-US;q=0.8,en;q=0.7", + "com": "en-US,en;q=0.9", +} + +func acceptLanguage(host string) string { + suffix, _ := publicsuffix.PublicSuffix(strings.ToLower(host)) + if lang, ok := languages[suffix]; ok { return lang } + + return languages["com"] +} diff --git a/internal/fetch/classify.go b/internal/fetch/classify.go new file mode 100644 index 0000000..15157fb --- /dev/null +++ b/internal/fetch/classify.go @@ -0,0 +1,99 @@ +package fetch + +import ( + "bytes" + "net/http" + "strings" +) + +// Verdict says what a response means for the watcher. +type Verdict int + +const ( + // OK is a page the plugin can parse. + OK Verdict = iota + // NotFound (404, 410) means the item is not available, never an error. + NotFound + // Challenge is a bot check that a real browser may clear. + Challenge + // Blocked is a refusal without a recognisable challenge, e.g. a plain 403 + // or 429. Back off and retry later. + Blocked + // HTTPError is any other non-2xx status. + HTTPError +) + +func (v Verdict) String() string { + switch v { + case OK: + return "ok" + case NotFound: + return "not-found" + case Challenge: + return "challenge" + case Blocked: + return "blocked" + case HTTPError: + return "http-error" + default: + return "unknown" + } +} + +type marker struct { + name string + needle string +} + +// strongMarkers only appear on bot check pages, so they count whatever the +// status. Amazon answers its captcha with a 200, for example. +var strongMarkers = []marker{ + {"cloudflare", "window._cf_chl_opt"}, + {"amazon-captcha", `action="/errors/validateCaptcha"`}, + {"datadome", "geo.captcha-delivery.com"}, + {"perimeterx", `id="px-captcha"`}, +} + +// weakMarkers also show up on normal pages (Cloudflare injects its +// challenge-platform script, shops embed Turnstile in forms), so they only +// count on a refusal status. +var weakMarkers = []marker{ + {"cloudflare", "Just a moment..."}, + {"cloudflare", "/cdn-cgi/challenge-platform/"}, + {"turnstile", "challenges.cloudflare.com/turnstile"}, + {"recaptcha", "www.google.com/recaptcha/"}, + {"hcaptcha", "hcaptcha.com/1/api.js"}, + {"captcha", "captcha"}, +} + +// classify decides the verdict for a response. For Challenge it also names +// the bot check found. +func classify(status int, header http.Header, finalURL string, body []byte) (Verdict, string) { + lower := bytes.ToLower(body) + + if header.Get("cf-mitigated") == "challenge" { return Challenge, "cloudflare" } + if strings.Contains(finalURL, "/errors/validateCaptcha") { return Challenge, "amazon-captcha" } + if name := findMarker(lower, strongMarkers); name != "" { return Challenge, name } + + switch { + case status >= 200 && status < 300: + return OK, "" + case status == http.StatusNotFound || status == http.StatusGone: + return NotFound, "" + case status == http.StatusForbidden || status == http.StatusTooManyRequests || status == http.StatusServiceUnavailable: + if name := findMarker(lower, weakMarkers); name != "" { return Challenge, name } + + return Blocked, "" + default: + return HTTPError, "" + } +} + +// findMarker returns the name of the first marker in the lowercased body. +func findMarker(lower []byte, markers []marker) string { + for _, m := range markers { + if bytes.Contains(lower, []byte(strings.ToLower(m.needle))) { return m.name } + } + + return "" +} diff --git a/internal/fetch/client.go b/internal/fetch/client.go new file mode 100644 index 0000000..765f08c --- /dev/null +++ b/internal/fetch/client.go @@ -0,0 +1,116 @@ +// Package fetch downloads product pages with a browser-like TLS and HTTP/2 +// fingerprint and tells real pages apart from bot checks. +package fetch + +import ( + "context" + "errors" + "fmt" + "io" + stdhttp "net/http" + "net/url" + "time" + + http "github.com/bogdanfinn/fhttp" + tlsclient "github.com/bogdanfinn/tls-client" +) + +const ( + DefaultTimeout = 30 * time.Second + DefaultMaxBody = 16 << 20 +) + +// ErrBodyTooLarge is returned when a response exceeds Options.MaxBody. +var ErrBodyTooLarge = errors.New("response body too large") + +type Options struct { + // Browser to impersonate. Defaults to DefaultBrowser(). + Browser *Browser + // Jar holds the cookies. Defaults to a new, empty jar. + Jar *Jar + // Timeout per request, including redirects. Defaults to DefaultTimeout. + Timeout time.Duration + // MaxBody is the largest body read, after decompression. Defaults to + // DefaultMaxBody. + MaxBody int64 +} + +// Client fetches pages. It is safe for concurrent use. +type Client struct { + http tlsclient.HttpClient + browser Browser + jar *Jar + maxBody int64 +} + +// Response is a fetched page. +type Response struct { + URL string // as requested + FinalURL string // after redirects + Status int + Header stdhttp.Header + Body []byte + Verdict Verdict + // Challenge names the bot check found, such as "cloudflare", when + // Verdict is Challenge. + Challenge string + Elapsed time.Duration +} + +func New(opts Options) (*Client, error) { + browser := DefaultBrowser() + if opts.Browser != nil { browser = *opts.Browser } + if opts.Jar == nil { opts.Jar = NewJar() } + if opts.Timeout == 0 { opts.Timeout = DefaultTimeout } + if opts.MaxBody == 0 { opts.MaxBody = DefaultMaxBody } + + hc, err := tlsclient.NewHttpClient(nil, + tlsclient.WithClientProfile(browser.Profile), + tlsclient.WithRandomTLSExtensionOrder(), + tlsclient.WithCookieJar(opts.Jar), + tlsclient.WithTimeoutMilliseconds(int(opts.Timeout/time.Millisecond)), + ) + if err != nil { return nil, fmt.Errorf("creating HTTP client: %w", err) } + + return &Client{http: hc, browser: browser, jar: opts.Jar, maxBody: opts.MaxBody}, nil +} + +// Jar returns the client's cookie jar. +func (c *Client) Jar() *Jar { return c.jar } + +// Get fetches rawURL the way Chrome opens a bookmark. A response with a bad +// status is not an error: check Verdict. +func (c *Client) Get(ctx context.Context, rawURL string) (*Response, error) { + u, err := url.Parse(rawURL) + if err != nil { return nil, err } + if u.Scheme != "http" && u.Scheme != "https" { return nil, fmt.Errorf("unsupported URL scheme %q", u.Scheme) } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + if err != nil { return nil, err } + req.Header = c.browser.navigationHeaders(u) + + start := time.Now() + resp, err := c.http.Do(req) + if err != nil { return nil, err } + + // fhttp's decompressing readers close the raw body with them. + body := resp.Body + if !resp.Uncompressed && resp.Header.Get("Content-Encoding") != "" { body = http.DecompressBody(resp) } + defer func() { _ = body.Close() }() + + data, err := io.ReadAll(io.LimitReader(body, c.maxBody+1)) + if err != nil { return nil, fmt.Errorf("reading body: %w", err) } + if int64(len(data)) > c.maxBody { return nil, fmt.Errorf("%w: more than %d bytes", ErrBodyTooLarge, c.maxBody) } + + r := &Response{ + URL: rawURL, + FinalURL: resp.Request.URL.String(), + Status: resp.StatusCode, + Header: stdhttp.Header(resp.Header), + Body: data, + Elapsed: time.Since(start), + } + r.Verdict, r.Challenge = classify(r.Status, r.Header, r.FinalURL, r.Body) + + return r, nil +} diff --git a/internal/fetch/fetch_test.go b/internal/fetch/fetch_test.go new file mode 100644 index 0000000..32ccb85 --- /dev/null +++ b/internal/fetch/fetch_test.go @@ -0,0 +1,270 @@ +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", "Metro", OK, ""}, + "cf script on normal page": {200, nil, "", `", Challenge, "cloudflare"}, + "cf title": {403, nil, "", "Just a moment...", Challenge, "cloudflare"}, + "amazon captcha 200": {200, nil, "", `
`, Challenge, "amazon-captcha"}, + "amazon captcha url": {200, nil, "https://www.amazon.de/errors/validateCaptcha?x=1", "", Challenge, "amazon-captcha"}, + "datadome": {403, nil, "", `