From 3e8318578df631b368de1147b7f056ec44a12239 Mon Sep 17 00:00:00 2001 From: CheerC Date: Tue, 20 Oct 2026 19:37:01 +0800 Subject: [PATCH] fix(upstream): treat the free-tier IP block as terminal for the exit The free tier answers an egress IP it flagged with 403 "abusive traffic". The gateway read that as an ordinary rejection: it tried the second anonymous lane on the same IP, then the keyed tiers from the same IP, and remembered nothing, so every later request and every probe repeated the walk. A single client request produced four upstream 403s on an instance with one exit. - classify the three known IP-block wordings (abuse.go) without consuming the body, so the upstream response stays intact for the caller; - cool only that exit (proxyTransport.blockedUntil) and leave the lane: another lane on the same IP cannot help, and neither can a keyed tier; - keep blocked exits out of anonymousCursor.Next, including its cooldown fallback, and bring them back after a 15 minute TTL; - skip the keyed tiers once the anonymous phase reports the block; - answer clients with 503 free_tier_ip_blocked instead of forwarding the upstream "turn off your VPN" text; - record probes as network_abuse_blocked instead of http_403; - count anonymous attempts, which stayed at zero and broke the telemetry attempt numbers and the request budget. Co-Authored-By: Claude Code --- internal/gateway/abuse.go | 97 +++++++ internal/gateway/free_tier_block_test.go | 320 +++++++++++++++++++++++ internal/gateway/gateway.go | 11 + internal/gateway/pool.go | 62 ++++- internal/gateway/probe.go | 6 + internal/gateway/upstream.go | 35 +++ 6 files changed, 523 insertions(+), 8 deletions(-) create mode 100644 internal/gateway/abuse.go create mode 100644 internal/gateway/free_tier_block_test.go diff --git a/internal/gateway/abuse.go b/internal/gateway/abuse.go new file mode 100644 index 0000000..381c011 --- /dev/null +++ b/internal/gateway/abuse.go @@ -0,0 +1,97 @@ +package gateway + +import ( + "bytes" + "errors" + "io" + "net/http" + "strings" + "time" +) + +// errFreeTierIPBlocked reports that OpenCode's free gateway refused the request +// because it flagged the egress IP, not the request, the key or the session. +// Unlike the shape gates, another lane, key or retry cannot fix it: the same +// IP gets the same answer, and retrying only extends the penalty. The request +// must therefore leave the anonymous lane instead of walking its upstreams, +// and the exit must stay out of the cursor until the block expires. +var errFreeTierIPBlocked = errors.New("free tier blocked the egress IP") + +// freeTierBlockedMessage is what a client receives while its exit is blocked. +// The upstream message tells people to turn off a VPN, which is wrong for a +// server that egresses through a proxy; this one names the real cause and the +// two ways out. +const freeTierBlockedMessage = "OpenCode is blocking free-model traffic from the IP this gateway leaves from, so retrying now cannot succeed. Route the request through another exit or wait for the block to expire." + +// freeTierBlockTTL keeps a blocked exit out of the anonymous cursor. Upstream +// does not publish the block duration, so this is a conservative backoff: long +// enough to stop the retry storm, short enough that an unblocked IP recovers +// without a restart. +const freeTierBlockTTL = 15 * time.Minute + +// freeTierBlockTTL returns the backoff applied to an exit the free tier flagged. +func (g *Gateway) freeTierBlockTTL() time.Duration { + if g != nil && g.freeTierBlock > 0 { + return g.freeTierBlock + } + return freeTierBlockTTL +} + +// abuseProbeLimit bounds how much of a 403 body is read to classify it. +const abuseProbeLimit = 16 << 10 + +// isNetworkAbuseBlock reports whether status and body are the upstream's IP +// abuse rejection. The response is a 403 whose message names the egress +// network, in one of the wordings the gateway has been served: +// +// - "…free models aren't available from your current network because we've +// detected abusive traffic from this IP address…" +// - "Forbidden, OpenCode Free Model Gateway Detect Abuse Traffic" +// - "Abuse of traffic" +// +// The shape gate's 403 ("free tier can only be used from within OpenCode") is +// deliberately not matched: that one is a request-shape problem, which another +// lane or a refreshed body can still fix. +func isNetworkAbuseBlock(status int, body []byte) bool { + if status != http.StatusForbidden { + return false + } + text := strings.ToLower(string(body)) + if strings.Contains(text, "abusive traffic") || + strings.Contains(text, "abuse traffic") || + strings.Contains(text, "abuse of traffic") { + return true + } + return strings.Contains(text, "free models aren't available") && + strings.Contains(text, "from your current network") +} + +// peekNetworkAbuseBlock classifies a response without consuming its body: +// the bytes it reads are put back in front of the rest so downstream error +// handling, and a retry on another exit, still see the full payload. +func peekNetworkAbuseBlock(resp *http.Response) bool { + if resp == nil || resp.Body == nil || resp.StatusCode != http.StatusForbidden { + return false + } + prefix, err := io.ReadAll(io.LimitReader(resp.Body, abuseProbeLimit)) + if err != nil { + // The body is unusable; restore what was read and let the ordinary + // error path deal with the response. + resp.Body = replayBody(prefix, resp.Body) + return false + } + resp.Body = replayBody(prefix, resp.Body) + return isNetworkAbuseBlock(resp.StatusCode, prefix) +} + +// replayBody returns a body that yields prefix and then the rest of original. +func replayBody(prefix []byte, original io.ReadCloser) io.ReadCloser { + return &prefixBody{Reader: io.MultiReader(bytes.NewReader(prefix), original), closer: original} +} + +type prefixBody struct { + io.Reader + closer io.Closer +} + +func (b *prefixBody) Close() error { return b.closer.Close() } diff --git a/internal/gateway/free_tier_block_test.go b/internal/gateway/free_tier_block_test.go new file mode 100644 index 0000000..97e7c7d --- /dev/null +++ b/internal/gateway/free_tier_block_test.go @@ -0,0 +1,320 @@ +package gateway + +import ( + "context" + "errors" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "opencode2api/internal/config" + "opencode2api/internal/identity" + "opencode2api/internal/models" + wire "opencode2api/internal/protocol" + "opencode2api/internal/rotation" +) + +// ipAbuseBody is the response OpenCode's free gateway returns for an egress IP +// it has flagged. The gateway must recognise it instead of treating the 403 as +// a request-shape rejection that another key, lane or proxy can fix. +const ipAbuseBody = `{"type":"error","error":{"type":"FreeTierError","message":"OpenCode's free models aren't available from your current network because we've detected abusive traffic from this IP address. This isn't related to your account. If you're on a VPN or proxy, turn it off and try again, or subscribe to OpenCode Go at https://opencode.ai/go to keep building."}}` + +func TestIsNetworkAbuseBlock(t *testing.T) { + cases := []struct { + name string + status int + body string + want bool + }{ + {"ip block", http.StatusForbidden, ipAbuseBody, true}, + {"short form", http.StatusForbidden, `{"error":{"message":"Forbidden, OpenCode Free Model Gateway Detect Abuse Traffic"}}`, true}, + {"abuse of traffic", http.StatusForbidden, `{"error":{"message":"Abuse of traffic"}}`, true}, + {"network wording", http.StatusForbidden, `{"error":{"message":"OpenCode's free models aren't available from your current network"}}`, true}, + {"shape gate", http.StatusForbidden, `{"type":"error","error":{"type":"FreeTierError","message":"OpenCode's free tier can only be used from within OpenCode"}}`, false}, + {"wrong status", http.StatusTooManyRequests, ipAbuseBody, false}, + {"empty", http.StatusForbidden, ``, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := isNetworkAbuseBlock(tc.status, []byte(tc.body)); got != tc.want { + t.Fatalf("isNetworkAbuseBlock(%d, %q) = %v, want %v", tc.status, tc.body, got, tc.want) + } + }) + } +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +// blockedClient simulates an egress the free tier has flagged: every request +// through it gets the IP abuse 403, whatever the upstream address. +func blockedClient(counter *atomic.Int64) *http.Client { + return &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + counter.Add(1) + return &http.Response{ + StatusCode: http.StatusForbidden, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(ipAbuseBody)), + Request: r, + }, nil + })} +} + +// okClient accepts every request without touching the network. +func okClient(counter *atomic.Int64) *http.Client { + return &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + counter.Add(1) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader("")), + Request: r, + }, nil + })} +} + +// newBlockTestGateway builds the smallest Gateway the anonymous lane needs: +// healthy proxies whose clients the test replaces. +func newBlockTestGateway(t *testing.T, proxies int) (*Gateway, *proxyTransports) { + t.Helper() + transports := &proxyTransports{} + for i := range proxies { + transport := &proxyTransport{index: i, name: "direct"} + transport.healthy.Store(true) + transports.items = append(transports.items, transport) + } + return &Gateway{ + cfg: config.Config{Retry: config.RetryConfig{MaxAttempts: 3, TimeoutSeconds: 30}}, + logger: slog.New(slog.NewTextHandler(io.Discard, nil)), + transports: transports, + zenNodes: &upstreamNodes{transports: transports}, + anonymous: anonymousPool(true, transports, 15*time.Second), + catalog: models.Catalog(config.TierZen, nil), + }, transports +} + +func testRequestIDs() identity.RequestIDs { + return identity.RequestIDs{Session: "ses_test", Project: "opencode2api:test"} +} + +func testFreeRoute() models.Route { + return models.Route{ID: "deepseek-v4.1-flash-free", Tier: config.TierZen, Protocol: wire.Chat, Anonymous: true} +} + +func testBodies() map[config.Tier][]byte { + return map[config.Tier][]byte{config.TierZen: []byte(`{"model":"deepseek-v4.1-flash-free","stream":true,"messages":[{"role":"user","content":"hi"}]}`)} +} + +func attachTestClient(transports *proxyTransports, index int, client *http.Client) { + transports.items[index].client = client + transports.items[index].bun = client +} + +// TestDoAnonymousUpstreamStopsAfterIPTierBlock pins the contract that an IP +// abuse 403 is terminal for the request: the gateway must not try the second +// lane on the same egress (the same IP answers the same way) and must report +// the block distinctly from an ordinary upstream rejection. +func TestDoAnonymousUpstreamStopsAfterIPTierBlock(t *testing.T) { + var requests atomic.Int64 + g, transports := newBlockTestGateway(t, 1) + attachTestClient(transports, 0, blockedClient(&requests)) + + resp, err, attempts := g.doAnonymousUpstream(context.Background(), testFreeRoute(), testBodies(), testRequestIDs(), 0) + if !errors.Is(err, errFreeTierIPBlocked) { + t.Fatalf("error = %v, want errFreeTierIPBlocked", err) + } + if requests.Load() != 1 { + t.Fatalf("upstream requests = %d, want 1 (the second lane must not retry the same egress)", requests.Load()) + } + if attempts != 1 { + t.Fatalf("attempts = %d, want 1", attempts) + } + if resp == nil || resp.StatusCode != http.StatusForbidden { + t.Fatalf("response = %v, want the upstream 403 returned to the caller", resp) + } + body, readErr := io.ReadAll(resp.Body) + if readErr != nil || !strings.Contains(string(body), "abusive traffic") { + t.Fatalf("response body = %q (err %v), want the upstream body intact", body, readErr) + } + _ = resp.Body.Close() + + // A later request must not hammer the same egress again. + before := requests.Load() + resp2, err2, attempts2 := g.doAnonymousUpstream(context.Background(), testFreeRoute(), testBodies(), testRequestIDs(), 0) + if !errors.Is(err2, errFreeTierIPBlocked) { + t.Fatalf("second call error = %v, want errFreeTierIPBlocked", err2) + } + if resp2 != nil { + t.Fatalf("second call response = %v, want nil", resp2) + } + if attempts2 != 0 { + t.Fatalf("second call attempts = %d, want 0", attempts2) + } + if requests.Load() != before { + t.Fatalf("second call sent %d more upstream requests, want 0", requests.Load()-before) + } +} + +// TestDoAnonymousUpstreamServesHealthyProxyAfterBlock pins that the block is a +// property of one egress: another configured exit must still be able to serve +// the request. +func TestDoAnonymousUpstreamServesHealthyProxyAfterBlock(t *testing.T) { + var blockedRequests, goodRequests atomic.Int64 + g, transports := newBlockTestGateway(t, 2) + attachTestClient(transports, 0, blockedClient(&blockedRequests)) + attachTestClient(transports, 1, okClient(&goodRequests)) + // An empty session starts the cursor round-robin at the first proxy. + resp, err, _ := g.doAnonymousUpstream(context.Background(), testFreeRoute(), testBodies(), identity.RequestIDs{Session: ""}, 0) + if err != nil || resp == nil || resp.StatusCode != http.StatusOK { + t.Fatalf("response = %v, err = %v, want a 200 from the second exit", resp, err) + } + _ = resp.Body.Close() + if blockedRequests.Load() == 0 { + t.Fatal("the blocked exit was never tried; the test did not exercise failover") + } + if goodRequests.Load() == 0 { + t.Fatal("the healthy exit was never used") + } +} + +// TestAnonymousCursorSkipsBlockedProxy pins that a blocked egress is not +// reached through the cursor's cooldown fallback either: otherwise every +// client retry keeps hitting the flagged IP. +func TestAnonymousCursorSkipsBlockedProxy(t *testing.T) { + transports := &proxyTransports{} + for i, name := range []string{"blocked", "good"} { + transport := &proxyTransport{index: i, name: name} + transport.healthy.Store(true) + transports.items = append(transports.items, transport) + } + pool := anonymousPool(true, transports, 15*time.Second) + if len(pool.nodes) != 2 { + t.Fatalf("anonymous nodes = %d, want 2", len(pool.nodes)) + } + pool.nodes[0].proxy.markBlocked(time.Now().Add(time.Minute)) + + cursor := pool.CursorFor("") + first := cursor.Next() + if first == nil || first.proxy != transports.items[1] { + t.Fatalf("first node = %v, want the unblocked proxy", first) + } + if next := cursor.Next(); next != nil { + t.Fatalf("second node = %v, want nil once only the blocked proxy remains", next) + } +} + +// TestDoAnonymousUpstreamCountsAttempts pins the attempt counter that feeds +// telemetry and the request budget. It used to stay at zero for every +// anonymous request. +func TestDoAnonymousUpstreamCountsAttempts(t *testing.T) { + var requests atomic.Int64 + g, transports := newBlockTestGateway(t, 1) + attachTestClient(transports, 0, okClient(&requests)) + + resp, err, attempts := g.doAnonymousUpstream(context.Background(), testFreeRoute(), testBodies(), testRequestIDs(), 0) + if err != nil { + t.Fatalf("error = %v", err) + } + if resp == nil { + t.Fatal("response = nil") + } + _ = resp.Body.Close() + if attempts != 1 { + t.Fatalf("attempts = %d, want 1", attempts) + } +} + +// TestDoUpstreamTiersStopsAtIPTierBlock pins that the block also ends the +// request: keyed tiers cannot help when the egress itself is flagged. +func TestDoUpstreamTiersStopsAtIPTierBlock(t *testing.T) { + var requests atomic.Int64 + g, transports := newBlockTestGateway(t, 1) + attachTestClient(transports, 0, blockedClient(&requests)) + g.zenNodes = &upstreamNodes{transports: transports, nodes: []*upstreamNode{{key: "sk-zen"}}} + route := testFreeRoute() + route.KeyTiers = []config.Tier{config.TierZen} + + _, _, _, err := g.doUpstreamTiers(context.Background(), route, testBodies(), testRequestIDs(), 0) + if !errors.Is(err, errFreeTierIPBlocked) { + t.Fatalf("error = %v, want errFreeTierIPBlocked", err) + } + if requests.Load() != 1 { + t.Fatalf("upstream requests = %d, want 1 (no keyed retry on a flagged egress)", requests.Load()) + } +} + +// TestBlockedExitReturnsAfterTTL pins that the block is temporary: once the +// TTL passes the exit is usable again, so a fixed network recovers without a +// restart or a config reload. +func TestBlockedExitReturnsAfterTTL(t *testing.T) { + transports := &proxyTransports{} + transport := &proxyTransport{index: 0, name: "direct"} + transport.healthy.Store(true) + transports.items = append(transports.items, transport) + pool := anonymousPool(true, transports, 15*time.Second) + + pool.nodes[0].proxy.markBlocked(time.Now().Add(-time.Second)) + cursor := pool.CursorFor("") + if node := cursor.Next(); node == nil { + t.Fatal("an expired block still kept the exit out of the cursor") + } +} + +// TestHandleInferenceAnswersBlockWithItsOwnStatus pins the client-visible +// contract: a blocked request is answered with the gateway's 503 and its own +// message, not the upstream 403 telling the reader to turn off a VPN. +func TestHandleInferenceAnswersBlockWithItsOwnStatus(t *testing.T) { + var requests atomic.Int64 + g, transports := newBlockTestGateway(t, 1) + attachTestClient(transports, 0, blockedClient(&requests)) + rotationManager, err := rotation.New("", config.RotationConfig{}) + if err != nil { + t.Fatalf("rotation manager: %v", err) + } + g.rotation = rotationManager + g.cfg.ServerKeys = []string{"sk-local"} + g.cfg.Anonymous = true + g.catalog = models.Catalog(config.TierZen, map[string]string{"deepseek-v4.1-flash-free": "chat"}) + + body := `{"model":"deepseek-v4.1-flash-free","stream":true,"messages":[{"role":"user","content":"hi"}]}` + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer sk-local") + recorder := httptest.NewRecorder() + g.handleInference(wire.Chat)(recorder, req) + + if recorder.Code != http.StatusServiceUnavailable { + t.Fatalf("status = %d, want 503; body = %s", recorder.Code, recorder.Body.String()) + } + if strings.Contains(recorder.Body.String(), "turn it off") { + t.Fatalf("body still forwards the upstream advice: %s", recorder.Body.String()) + } + if !strings.Contains(recorder.Body.String(), "free_tier_ip_blocked") { + t.Fatalf("body = %s, want the free_tier_ip_blocked error type", recorder.Body.String()) + } +} + +// TestProbeAttemptReportsNetworkAbuseBlock pins the probe reason so operators +// can tell an egress block apart from a request-shape rejection in the WebUI +// and the availability file. +func TestProbeAttemptReportsNetworkAbuseBlock(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + _, _ = io.WriteString(w, ipAbuseBody) + })) + defer srv.Close() + + g := &Gateway{} + result := g.probeAttempt(context.Background(), srv.Client(), srv.URL, "public", "deepseek-v4.1-flash-free", wire.Chat, testRequestIDs(), "") + if result.reason != "network_abuse_blocked" { + t.Fatalf("probe reason = %q, want network_abuse_blocked", result.reason) + } + if !result.attempted || result.success { + t.Fatalf("probe result = %+v, want attempted and unsuccessful", result) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 572752c..a44a4b5 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -83,6 +83,9 @@ type Gateway struct { // the header wait. Zero arms no per-attempt deadline: each attempt is then // bounded only by the request-level budget. attemptTimeout time.Duration + // freeTierBlock is how long an exit the free tier flagged stays out of the + // anonymous cursor. Zero uses freeTierBlockTTL. + freeTierBlock time.Duration } // New builds a Gateway for cfg: one proxy transport per runtime proxy (a @@ -319,6 +322,14 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { wire.WriteError(w, external, http.StatusGatewayTimeout, "upstream request timed out", "upstream_timeout", ids.Request) return } + // Every exit this request could use is under the free tier's IP + // block. A 502 would read as a transient upstream fault and invite + // the client to retry into the same penalty, so answer with the + // block itself. + if errors.Is(err, errFreeTierIPBlocked) { + wire.WriteError(w, external, http.StatusServiceUnavailable, freeTierBlockedMessage, "free_tier_ip_blocked", ids.Request) + return + } wire.WriteError(w, external, http.StatusBadGateway, "all upstream attempts failed", "upstream_error", ids.Request) return } diff --git a/internal/gateway/pool.go b/internal/gateway/pool.go index 367019c..992342a 100644 --- a/internal/gateway/pool.go +++ b/internal/gateway/pool.go @@ -30,13 +30,14 @@ import ( // upstream HTTP responses (see syncProxyResult) or a passing health check; // checking claims the single health check allowed in flight. type proxyTransport struct { - index int - name string - pool bool - client *http.Client - bun *http.Client - healthy atomic.Bool - checking atomic.Bool + index int + name string + pool bool + client *http.Client + bun *http.Client + healthy atomic.Bool + checking atomic.Bool + blockedUntil atomic.Int64 } // proxyTransports holds every configured proxy route, indexed by @@ -45,6 +46,24 @@ type proxyTransports struct { items []*proxyTransport } +// blocked reports whether this exit is under the free tier's IP abuse block. +func (t *proxyTransport) blocked(now time.Time) bool { + if t == nil { + return false + } + return t.blockedUntil.Load() > now.UnixNano() +} + +// markBlocked keeps this exit out of the anonymous cursor until until. The +// block is a property of the egress IP, so it is never cleared by a response +// from the same exit: only another exit can serve traffic in the meantime. +func (t *proxyTransport) markBlocked(until time.Time) { + if t == nil { + return + } + t.blockedUntil.Store(until.UnixNano()) +} + // anonymousNodes gives the shared OpenCode "public" credential an independent // cooldown per proxy. Unlike key nodes, anonymous nodes are never rebound: // changing proxy is the failover mechanism because Zen rate-limits them by IP. @@ -95,6 +114,20 @@ func (p *anonymousNodes) Len() int { return len(p.nodes) } +// blockedExits reports whether any exit is currently under the free tier's IP +// block, and no exit at all is available to serve the request. +func (p *anonymousNodes) blockedExits(now time.Time) bool { + if p == nil || len(p.nodes) == 0 { + return false + } + for _, node := range p.nodes { + if node.proxy != nil && !node.proxy.blocked(now) { + return false + } + } + return true +} + // HasPool reports whether any node uses a rotating proxy pool (#pool), which // lets callers make more attempts than there are nodes. func (p *anonymousNodes) HasPool() bool { @@ -137,10 +170,20 @@ func (c *anonymousCursor) Next() *anonymousNode { c.used = make([]bool, n) } now := time.Now().UnixNano() + isBlocked := func(node *anonymousNode) bool { + return node.proxy != nil && node.proxy.blockedUntil.Load() > now + } for c.offset < n { idx := (c.start + c.offset) % n c.offset++ node := c.pool.nodes[idx] + if isBlocked(node) { + // The free tier flagged this egress IP: the answer would be the + // same on every lane, so neither a fresh leg nor the cooldown + // fallback below may return it. + c.used[idx] = true + continue + } if node.proxy.pool || (!c.used[idx] && node.proxy.healthy.Load() && node.cooldownUntil.Load() <= now) { c.used[idx] = true return node @@ -151,7 +194,7 @@ func (c *anonymousCursor) Next() *anonymousNode { idx := (c.start + c.offset) % n c.offset++ node := c.pool.nodes[idx] - if node.proxy.pool { + if node.proxy.pool && !isBlocked(node) { return node } } @@ -165,6 +208,9 @@ func (c *anonymousCursor) Next() *anonymousNode { continue } node := c.pool.nodes[idx] + if isBlocked(node) { + continue + } healthy := node.proxy.healthy.Load() until := node.cooldownUntil.Load() if choice < 0 || (healthy && !choiceHealthy) || (healthy == choiceHealthy && until < earliest) { diff --git a/internal/gateway/probe.go b/internal/gateway/probe.go index 55350aa..0739f85 100644 --- a/internal/gateway/probe.go +++ b/internal/gateway/probe.go @@ -202,6 +202,12 @@ func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, base body, readErr := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) result.reason = fmt.Sprintf("http_%d", resp.StatusCode) if readErr == nil { + // An egress block is not evidence about the model: report it as + // its own reason so operators see it in the WebUI instead of + // reading another anonymous "http_403". + if isNetworkAbuseBlock(resp.StatusCode, body) { + return probeResult{attempted: true, reason: "network_abuse_blocked"} + } result.effortRejected = isEffortRejection(resp.StatusCode, string(body)) if isModelUnavailable(resp.StatusCode, string(body)) { result.reason = "model_unavailable" diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 7833232..f1a19e4 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -237,6 +237,13 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie return resp, route, attempts, nil } lastResponse, lastErr = resp, err + if errors.Is(err, errFreeTierIPBlocked) { + // The free tier flagged the egress IP. A keyed tier leaves from the + // same network and gets the same answer, so stop here instead of + // spending attempts that only lengthen the penalty. + g.logger.Warn("free tier blocked the egress IP; skipping the keyed tiers", "component", "upstream", "event", "free_tier_ip_blocked", "request_id", ids.Request, "attempts", attempts) + return lastResponse, effectiveRoute, attempts, lastErr + } if len(route.KeyTiers) > 0 { g.logger.Debug("anonymous request did not succeed; entering preferred key tiers", "component", "upstream", "event", "anonymous_fallback", "request_id", ids.Request, "attempts", attempts, "key_tiers", route.KeyTiers) } @@ -305,6 +312,10 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) { var lastResponse *http.Response var lastErr error + // blocked records that some exit is under the free tier's IP block. The + // result then reports errFreeTierIPBlocked even when no exit was left to + // try, so the caller does not fall through to the keyed tiers. + blocked := false cursor := g.anonymous.CursorFor(ids.Session) limit := g.anonymous.Len() if g.anonymous.HasPool() && g.cfg.Retry.MaxAttempts > limit { @@ -341,6 +352,10 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b } node := cursor.Next() if node == nil { + // Nothing usable is left. If that is because every exit is under + // the free tier's block, report the block rather than the generic + // no-proxy error, so the keyed tiers are not entered. + blocked = g.anonymous.blockedExits(time.Now()) break } proxies++ @@ -354,6 +369,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b break } setRequestShape(ctx, false, toolAliases[index]) + attempts++ if meta := telemetry.MetaFromContext(ctx); meta != nil { meta.Attempts = attemptOffset + attempts meta.Tier = string(config.TierZen) @@ -397,6 +413,17 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b if isProxyFailure(err) { break } + } else if peekNetworkAbuseBlock(resp) { + // The free tier flagged this egress IP. The other lane leaves + // from the same IP and would answer the same way, so cool the + // exit and move on to another one instead of adding attempts + // that only lengthen the penalty. The body is restored, so the + // caller still forwards the upstream error. + node.proxy.markBlocked(time.Now().Add(g.freeTierBlockTTL())) + lastErr = errFreeTierIPBlocked + blocked = true + g.logger.Warn("free tier blocked the egress IP; cooling the exit", "component", "upstream", "event", "free_tier_ip_blocked", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "proxy", config.RedactURL(node.proxy.name), "block_for", g.freeTierBlockTTL().String()) + break } else { g.logger.Debug("anonymous upstream returned an error response; trying the next upstream or proxy", "component", "upstream", "event", "anonymous_attempt_response_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) } @@ -410,8 +437,16 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b g.observeAnonymousResult(ctx, node, nodeResp, nodeErr) } if lastResponse != nil { + // The caller keeps and forwards this response; a block only changes + // the error so the keyed tiers are skipped. + if blocked { + return lastResponse, errFreeTierIPBlocked, attempts + } return lastResponse, nil, attempts } + if blocked { + return nil, errFreeTierIPBlocked, attempts + } if lastErr == nil { lastErr = errors.New("no healthy anonymous proxies available") if !g.transports.hasHealthy() {