From cef74002170de8c2748496bba84c54c47c1932ed Mon Sep 17 00:00:00 2001 From: Tausif Zaman Date: Tue, 1 Dec 2026 01:32:03 +0600 Subject: [PATCH] fix(egress): stop retrying JS bot-mitigation checkpoints --- egress/checkpoint.go | 98 ++++++++++++++++++++++++ egress/checkpoint_test.go | 152 ++++++++++++++++++++++++++++++++++++++ egress/egress.go | 9 ++- egress/egress_test.go | 75 +++++++++++++++++++ 4 files changed, 332 insertions(+), 2 deletions(-) create mode 100644 egress/checkpoint.go create mode 100644 egress/checkpoint_test.go diff --git a/egress/checkpoint.go b/egress/checkpoint.go new file mode 100644 index 00000000..0f4ae190 --- /dev/null +++ b/egress/checkpoint.go @@ -0,0 +1,98 @@ +package egress + +import ( + "bytes" + "fmt" + "io" + "net/http" + "strings" +) + +// BotCheckpoint identifies a non-retryable JS bot-mitigation checkpoint. It is +// returned as an error so HTTP tools that omit response headers still surface +// the browser fallback guidance to the agent. +type BotCheckpoint struct { + Provider string + Reason string +} + +func (c BotCheckpoint) Error() string { + return fmt.Sprintf("egress: non-retryable %s JS bot-mitigation checkpoint (%s); stop raw HTTP retries and use browser tooling (playwright-cli / Playwright MCP)", c.Provider, c.Reason) +} + +// DetectBotCheckpoint recognizes explicit mitigation headers or Vercel HTML +// markers on 403/429/503 responses. Generic CDN headers and Retry-After alone +// are not evidence of a JS checkpoint. +func DetectBotCheckpoint(statusCode int, h http.Header, bodyPrefix string) (BotCheckpoint, bool) { + if !botCheckpointStatus(statusCode) { + return BotCheckpoint{}, false + } + switch { + case checkpointHeader(h, "X-Vercel-Mitigated", ""): + return BotCheckpoint{Provider: "vercel", Reason: "x-vercel-mitigated"}, true + case checkpointHeader(h, "Cf-Mitigated", "challenge"): + return BotCheckpoint{Provider: "cloudflare", Reason: "cf-mitigated"}, true + case checkpointHeader(h, "X-Amzn-Waf-Action", "challenge"): + return BotCheckpoint{Provider: "aws-waf", Reason: "x-amzn-waf-action"}, true + } + bodyPrefix = strings.ToLower(bodyPrefix) + if strings.Contains(bodyPrefix, "vercel security checkpoint") || strings.Contains(bodyPrefix, "/.well-known/vercel/security/request-challenge") { + return BotCheckpoint{Provider: "vercel", Reason: "html-challenge-marker"}, true + } + return BotCheckpoint{}, false +} + +func botCheckpointStatus(code int) bool { + return code == http.StatusForbidden || code == http.StatusTooManyRequests || code == http.StatusServiceUnavailable +} + +// An empty value matches header presence, including an empty field value. +// Iterate keys as well as values to support non-canonical RoundTripper headers. +func checkpointHeader(h http.Header, name, value string) bool { + for k, values := range h { + if !strings.EqualFold(k, name) { + continue + } + if value == "" { + return true + } + for _, v := range values { + if strings.EqualFold(strings.TrimSpace(v), value) { + return true + } + } + } + return false +} + +const maxCheckpointBodyPrefix = 8 << 10 + +func detectResponseBotCheckpoint(resp *http.Response) (BotCheckpoint, bool) { + c, ok := DetectBotCheckpoint(resp.StatusCode, resp.Header, "") + if ok || !botCheckpointStatus(resp.StatusCode) || resp.Body == nil { + return c, ok + } + // Only peek when headers are inconclusive. Replay both bytes and any read + // error so an ordinary error response retains its body and Close contract. + prefix, err := io.ReadAll(io.LimitReader(resp.Body, maxCheckpointBodyPrefix)) + resp.Body = &checkpointBody{ReadCloser: resp.Body, prefix: bytes.NewReader(prefix), err: err} + return DetectBotCheckpoint(resp.StatusCode, resp.Header, string(prefix)) +} + +type checkpointBody struct { + io.ReadCloser + prefix *bytes.Reader + err error +} + +func (b *checkpointBody) Read(p []byte) (int, error) { + if b.prefix.Len() > 0 { + return b.prefix.Read(p) + } + if b.err != nil { + err := b.err + b.err = nil + return 0, err + } + return b.ReadCloser.Read(p) +} diff --git a/egress/checkpoint_test.go b/egress/checkpoint_test.go new file mode 100644 index 00000000..be6c9c24 --- /dev/null +++ b/egress/checkpoint_test.go @@ -0,0 +1,152 @@ +package egress + +import ( + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestDetectBotCheckpoint(t *testing.T) { + for _, code := range []int{http.StatusForbidden, http.StatusTooManyRequests, http.StatusServiceUnavailable} { + t.Run(http.StatusText(code), func(t *testing.T) { + for _, tc := range []struct { + name string + h http.Header + body string + want BotCheckpoint + }{ + {name: "vercel challenge", h: http.Header{"X-Vercel-Mitigated": {"challenge"}}, want: BotCheckpoint{"vercel", "x-vercel-mitigated"}}, + {name: "vercel deny mixed case", h: http.Header{"x-vErCeL-mItIgAtEd": {"DeNy"}}, want: BotCheckpoint{"vercel", "x-vercel-mitigated"}}, + {name: "vercel empty header", h: http.Header{"X-Vercel-Mitigated": {""}}, want: BotCheckpoint{"vercel", "x-vercel-mitigated"}}, + {name: "cloudflare", h: http.Header{"Cf-Mitigated": {"challenge"}}, want: BotCheckpoint{"cloudflare", "cf-mitigated"}}, + {name: "cloudflare mixed case and whitespace", h: http.Header{"cF-mItIgAtEd": {" CHALLENGE "}}, want: BotCheckpoint{"cloudflare", "cf-mitigated"}}, + {name: "cloudflare multiple values", h: http.Header{"Cf-Mitigated": {"other", "challenge"}}, want: BotCheckpoint{"cloudflare", "cf-mitigated"}}, + {name: "aws waf", h: http.Header{"X-Amzn-Waf-Action": {"challenge"}}, want: BotCheckpoint{"aws-waf", "x-amzn-waf-action"}}, + {name: "aws waf mixed case and whitespace", h: http.Header{"x-amzn-waf-action": {" Challenge "}}, want: BotCheckpoint{"aws-waf", "x-amzn-waf-action"}}, + {name: "vercel title", body: "VeRcEl SeCuRiTy ChEcKpOiNt", want: BotCheckpoint{"vercel", "html-challenge-marker"}}, + {name: "vercel script", body: ``, want: BotCheckpoint{"vercel", "html-challenge-marker"}}, + {name: "vercel script mixed case", body: "/.WELL-KNOWN/VERCEL/SECURITY/REQUEST-CHALLENGE", want: BotCheckpoint{"vercel", "html-challenge-marker"}}, + {name: "headers take precedence", h: http.Header{"Cf-Mitigated": {"challenge"}}, body: "Vercel Security Checkpoint", want: BotCheckpoint{"cloudflare", "cf-mitigated"}}, + {name: "plain error", body: "Forbidden"}, + {name: "ordinary rate limit", h: http.Header{"Retry-After": {"1"}}, body: "Too Many Requests"}, + {name: "cloudflare CDN only", h: http.Header{"Server": {"cloudflare"}, "Cf-Ray": {"12345"}}}, + {name: "vercel CDN only", h: http.Header{"Server": {"Vercel"}, "X-Vercel-Id": {"12345"}}}, + {name: "aws CDN only", h: http.Header{"Server": {"CloudFront"}, "X-Amzn-Requestid": {"12345"}}}, + {name: "cloudflare not challenge", h: http.Header{"Cf-Mitigated": {"deny"}}}, + {name: "cloudflare empty", h: http.Header{"Cf-Mitigated": {""}}}, + {name: "aws captcha not JS challenge", h: http.Header{"X-Amzn-Waf-Action": {"captcha"}}}, + {name: "aws substring not challenge", h: http.Header{"X-Amzn-Waf-Action": {"not-challenge"}}}, + {name: "generic JS page", body: "Please enable JavaScript to continue"}, + } { + t.Run(tc.name, func(t *testing.T) { + got, ok := DetectBotCheckpoint(code, tc.h, tc.body) + if got != tc.want || ok != (tc.want.Provider != "") { + t.Fatalf("DetectBotCheckpoint = %+v, %v; want %+v, %v", got, ok, tc.want, tc.want.Provider != "") + } + }) + } + }) + } +} + +func TestDetectBotCheckpointOtherStatuses(t *testing.T) { + for _, code := range []int{http.StatusOK, http.StatusFound, http.StatusNotFound, http.StatusInternalServerError} { + for _, h := range []http.Header{ + nil, + {"X-Vercel-Mitigated": {"challenge"}}, + {"Cf-Mitigated": {"challenge"}}, + {"X-Amzn-Waf-Action": {"challenge"}}, + } { + if got, ok := DetectBotCheckpoint(code, h, "Vercel Security Checkpoint"); ok || got != (BotCheckpoint{}) { + t.Errorf("status %d, headers %v: got %+v, %v; want no checkpoint", code, h, got, ok) + } + } + } +} + +type checkpointTestBody struct { + io.Reader + reads, bytes, closes int +} + +func (b *checkpointTestBody) Read(p []byte) (int, error) { + b.reads++ + n, err := b.Reader.Read(p) + b.bytes += n + return n, err +} + +func (b *checkpointTestBody) Close() error { b.closes++; return nil } + +type checkpointTestTransport func(*http.Request) (*http.Response, error) + +func (f checkpointTestTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestCheckpointHeadersSkipBodyAndReleaseSlots(t *testing.T) { + for _, method := range []string{http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPost} { + t.Run(method, func(t *testing.T) { + body := &checkpointTestBody{Reader: strings.NewReader("body must not be read")} + g := New(open) + tr := g.Transport("test", checkpointTestTransport(func(req *http.Request) (*http.Response, error) { + return &http.Response{StatusCode: http.StatusTooManyRequests, Header: http.Header{"X-Vercel-Mitigated": {"challenge"}}, Body: body, Request: req}, nil + })) + req := httptest.NewRequest(method, "https://example.test/", nil) + resp, err := tr.RoundTrip(req) + var checkpoint BotCheckpoint + if resp != nil || !errors.As(err, &checkpoint) || checkpoint.Provider != "vercel" { + t.Fatalf("response = %v, error = %v; want vercel checkpoint error", resp, err) + } + if body.reads != 0 || body.closes != 1 { + t.Fatalf("body reads=%d closes=%d; want 0, 1", body.reads, body.closes) + } + if s := g.Snapshot(); len(s) != 1 || s[0].RPM != 1 || s[0].Inflight != 0 { + t.Fatalf("snapshot = %+v; want one attempt and no occupied slots", s) + } + }) + } +} + +func TestCheckpointPeekBoundedAndPreservesBody(t *testing.T) { + // A marker beyond the peek limit must not trigger detection or be consumed. + want := strings.Repeat("x", maxCheckpointBodyPrefix) + "Vercel Security Checkpoint" + body := &checkpointTestBody{Reader: strings.NewReader(want)} + resp := &http.Response{StatusCode: http.StatusForbidden, Body: body, ContentLength: int64(len(want))} + if c, ok := detectResponseBotCheckpoint(resp); ok { + t.Fatalf("marker beyond prefix detected: %+v", c) + } + if body.bytes != maxCheckpointBodyPrefix || body.closes != 0 || resp.ContentLength != int64(len(want)) { + t.Fatalf("peek: bytes=%d closes=%d content-length=%d", body.bytes, body.closes, resp.ContentLength) + } + got, err := io.ReadAll(resp.Body) + if err != nil || string(got) != want { + t.Fatalf("body not preserved: len=%d, err=%v", len(got), err) + } + resp.Body.Close() + if body.closes != 1 { + t.Fatalf("body closed %d times; want 1", body.closes) + } +} + +type checkpointReadError struct{ err error } + +func (r checkpointReadError) Read([]byte) (int, error) { return 0, r.err } + +func TestCheckpointPeekPreservesReadError(t *testing.T) { + wantErr := errors.New("body read failed") + body := &checkpointTestBody{Reader: io.MultiReader(strings.NewReader("partial body"), checkpointReadError{wantErr})} + resp := &http.Response{StatusCode: http.StatusForbidden, Body: body} + if c, ok := detectResponseBotCheckpoint(resp); ok { + t.Fatalf("unexpected checkpoint: %+v", c) + } + got, err := io.ReadAll(resp.Body) + if string(got) != "partial body" || !errors.Is(err, wantErr) { + t.Fatalf("body = %q, error = %v; want partial body and original read error", got, err) + } + resp.Body.Close() + if body.closes != 1 { + t.Fatalf("body closed %d times; want 1", body.closes) + } +} diff --git a/egress/egress.go b/egress/egress.go index b2ba5832..68fd0df4 100644 --- a/egress/egress.go +++ b/egress/egress.go @@ -525,8 +525,9 @@ type stored struct { // send makes one request within the host's limits. A 429/503 pauses the host // and, for a bodiless GET/HEAD/OPTIONS, is retried up to MaxRetries times; a -// request that may change state is never retried. The slots are held until -// the response body is closed. +// request that may change state is never retried. JS bot checkpoints on +// 403/429/503 instead close the body and return a BotCheckpoint error before +// backoff. The slots are held until the response body is closed. func (t *transport) send(req *http.Request) (*http.Response, error) { host := HostKey(req.URL) for attempt := 0; ; attempt++ { @@ -540,6 +541,10 @@ func (t *transport) send(req *http.Request) (*http.Response, error) { return nil, err } resp.Body = &releaseBody{resp.Body, release} + if checkpoint, ok := detectResponseBotCheckpoint(resp); ok { + resp.Body.Close() + return nil, checkpoint + } if resp.StatusCode != http.StatusTooManyRequests && resp.StatusCode != http.StatusServiceUnavailable { return resp, nil } diff --git a/egress/egress_test.go b/egress/egress_test.go index 55424e56..4b9c7095 100644 --- a/egress/egress_test.go +++ b/egress/egress_test.go @@ -2,6 +2,7 @@ package egress import ( "context" + "errors" "io" "net/http" "net/http/httptest" @@ -151,6 +152,80 @@ func TestBackoff(t *testing.T) { } } +func TestBotCheckpointStopsRetries(t *testing.T) { + for _, code := range []int{http.StatusForbidden, http.StatusTooManyRequests, http.StatusServiceUnavailable} { + t.Run(http.StatusText(code), func(t *testing.T) { + for _, tc := range []struct { + name, header, value, body, provider string + }{ + {"vercel", "X-Vercel-Mitigated", "challenge", "checkpoint body", "vercel"}, + {"vercel deny", "X-Vercel-Mitigated", "deny", "checkpoint body", "vercel"}, + {"cloudflare", "Cf-Mitigated", "ChAlLeNgE", "checkpoint body", "cloudflare"}, + {"aws waf", "X-Amzn-Waf-Action", "CHALLENGE", "checkpoint body", "aws-waf"}, + {"vercel title", "", "", "Vercel Security Checkpoint", "vercel"}, + {"vercel script", "", "", ``, "vercel"}, + {"ordinary error", "", "", "ordinary error body", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + for _, shared := range []bool{false, true} { + name := "unshared" + ctx := t.Context() + if shared { + name, ctx = "task", task("checkpoint") + } + t.Run(name, func(t *testing.T) { + g := New(open) + s := newServer(t, 0, func(_ int64, w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Retry-After", "0") + if tc.header != "" { + w.Header().Set(tc.header, tc.value) + } + w.WriteHeader(code) + _, _ = io.WriteString(w, tc.body) + }) + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, s.URL, nil) + resp, err := (&http.Client{Transport: g.Transport("test", nil)}).Do(req) + wantAttempts := int64(1) + if tc.provider != "" { + var checkpoint BotCheckpoint + if resp != nil || !errors.As(err, &checkpoint) || checkpoint.Provider != tc.provider { + t.Fatalf("response=%v error=%v; want %s checkpoint error", resp, err, tc.provider) + } + for _, hint := range []string{"non-retryable", "stop raw HTTP retries", "playwright-cli", "Playwright MCP"} { + if !strings.Contains(err.Error(), hint) { + t.Errorf("error %q missing guidance %q", err, hint) + } + } + } else { + if err != nil { + t.Fatal(err) + } + got, readErr := io.ReadAll(resp.Body) + resp.Body.Close() + if resp.StatusCode != code || string(got) != tc.body || readErr != nil { + t.Fatalf("ordinary response changed: status=%d body=%q error=%v", resp.StatusCode, got, readErr) + } + if code != http.StatusForbidden { + wantAttempts += int64(open.MaxRetries) + } + } + if s.hits.Load() != wantAttempts { + t.Errorf("attempts=%d; want %d", s.hits.Load(), wantAttempts) + } + if snapshot := g.Snapshot(); len(snapshot) != 1 || snapshot[0].RPM != int(wantAttempts) || snapshot[0].Inflight != 0 { + t.Errorf("snapshot=%+v; want %d sends and no occupied slots", snapshot, wantAttempts) + } + if h := g.host(HostKey(req.URL)); (tc.provider != "" || code == http.StatusForbidden) && !h.notBefore.IsZero() { + t.Errorf("unexpected host backoff: %v", h.notBefore) + } + }) + } + }) + } + }) + } +} + func TestDedupeAndCache(t *testing.T) { p := open p.CacheTTL = 200 * time.Millisecond