From 3e8318578df631b368de1147b7f056ec44a12239 Mon Sep 17 00:00:00 2001 From: CheerC Date: Tue, 20 Oct 2026 19:37:01 +0800 Subject: [PATCH 1/2] 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() { From fa9a25577e955ec047921b01dec96bcb7b4e25fc Mon Sep 17 00:00:00 2001 From: CheerC Date: Tue, 20 Oct 2026 20:58:48 +0800 Subject: [PATCH 2/2] fix(upstream): stop retrying request-level rejections and ignore placeholder keys A free-tier 400 (context_length_exceeded, invalid_request_error) was treated as retryable: the gateway walked the second anonymous lane, then the keyed tier, and the client received whatever the last tier answered. With the documented placeholder in zen_keys, a 941 KB request that only needed compaction came back as "401 Invalid credential". - classify request-level rejections (400/422 with invalid_request_error, context_length_exceeded, maximum context length, string_above_max_length or prompt is too long) and end the request after the first attempt on both the anonymous and keyed lanes, forwarding the original status and body; 401/403/429 stay retryable because they can be key-specific; - read the body once with peekResponseBody so classification does not consume what the client eventually receives; - drop documented placeholder keys (sk-your-zen-key, change-this-local-key) during config normalization: they never authenticate, and keeping them turns every free-tier fallback into a 401 that hides the real error. Verified end to end by replaying the recorded request against the built binary with the original configuration: 400 with the upstream message, one upstream attempt, an anonymous key_id, and zen/go pools of 0. Co-Authored-By: Claude Code --- internal/config/config.go | 3 + internal/config/placeholder.go | 49 +++++++++ internal/gateway/abuse.go | 63 +++++++++-- internal/gateway/free_tier_error_test.go | 133 +++++++++++++++++++++++ internal/gateway/upstream.go | 36 +++++- 5 files changed, 271 insertions(+), 13 deletions(-) create mode 100644 internal/config/placeholder.go create mode 100644 internal/gateway/free_tier_error_test.go diff --git a/internal/config/config.go b/internal/config/config.go index 3abb32e..6014986 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -217,6 +217,9 @@ func Normalize(path string, cfg Config) (Config, error) { trimList(&cfg.ZenKeys) trimList(&cfg.GoKeys) + // A placeholder copied from the documentation is not a credential. Treating + // it as one routes every free-model failure into a 401 from the keyed tier. + cfg = DropPlaceholderKeys(cfg) cfg.ProxyFile = strings.TrimSpace(cfg.ProxyFile) if err := resolveProxyFiles(path, &cfg); err != nil { return Config{}, err diff --git a/internal/config/placeholder.go b/internal/config/placeholder.go new file mode 100644 index 0000000..99c5334 --- /dev/null +++ b/internal/config/placeholder.go @@ -0,0 +1,49 @@ +package config + +import "strings" + +// placeholderKeys are the example values the shipped documentation uses. They +// are not secrets and no upstream accepts them: a configuration that still +// carries one has simply not been filled in yet. +var placeholderKeys = []string{ + "sk-your-zen-key", + "change-this-local-key", +} + +// IsPlaceholderKey reports whether key is a documented placeholder rather than +// a real credential. Comparison is case-insensitive and ignores surrounding +// whitespace. +func IsPlaceholderKey(key string) bool { + trimmed := strings.ToLower(strings.TrimSpace(key)) + for _, placeholder := range placeholderKeys { + if trimmed == placeholder { + return true + } + } + return false +} + +// DropPlaceholderKeys removes placeholder credentials from the key pools. A +// placeholder can never authenticate, so keeping it only turns every fallback +// that reaches the keyed tiers into a 401 — which then hides the real error +// (the cause of the failover) from the client. Callers still see the configured +// list through the management API; the pools simply behave as if the tier was +// left empty. +func DropPlaceholderKeys(cfg Config) Config { + drop := func(keys []string) []string { + if len(keys) == 0 { + return keys + } + kept := keys[:0] + for _, key := range keys { + if IsPlaceholderKey(key) { + continue + } + kept = append(kept, key) + } + return kept + } + cfg.ZenKeys = drop(cfg.ZenKeys) + cfg.GoKeys = drop(cfg.GoKeys) + return cfg +} diff --git a/internal/gateway/abuse.go b/internal/gateway/abuse.go index 381c011..de30297 100644 --- a/internal/gateway/abuse.go +++ b/internal/gateway/abuse.go @@ -66,22 +66,63 @@ func isNetworkAbuseBlock(status int, body []byte) bool { 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 +// peekResponseBody reads the start of a response body and puts it back in +// front of the rest, so classification and downstream error handling both see +// the full payload. +func peekResponseBody(resp *http.Response) []byte { + if resp == nil || resp.Body == nil { + return nil } prefix, err := io.ReadAll(io.LimitReader(resp.Body, abuseProbeLimit)) + resp.Body = replayBody(prefix, resp.Body) 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 nil + } + return prefix +} + +// peekNetworkAbuseBlock classifies a response without consuming its body. +func peekNetworkAbuseBlock(resp *http.Response) bool { + if resp == nil || resp.StatusCode != http.StatusForbidden { return false } - resp.Body = replayBody(prefix, resp.Body) - return isNetworkAbuseBlock(resp.StatusCode, prefix) + return isNetworkAbuseBlock(resp.StatusCode, peekResponseBody(resp)) +} + +// errDeterministicClientRejection reports that the upstream rejected the +// request itself: the body is malformed, too long for the model, or fails the +// same validation on every credential. Retrying on another key, lane or tier +// cannot change that, so the request must end and the original 4xx must reach +// the client. Without this, the first tier's real error is replaced by +// whatever the next tier answers — typically a 401 from an unconfigured key, +// which tells the client to re-authenticate instead of compacting. +var errDeterministicClientRejection = errors.New("upstream rejected the request deterministically") + +// deterministicMarkers are the error types and codes an upstream uses for a +// request that will fail identically everywhere. The status must be 400 or 422 +// as well: a 401, 403 or 429 can be specific to the credential or the moment. +var deterministicMarkers = []string{ + "invalid_request_error", + "invalid_request", + "context_length_exceeded", + "maximum context length", + "string_above_max_length", + "prompt is too long", +} + +// isDeterministicClientResponse reports whether status and body describe a +// request-level rejection rather than a credential or availability problem. +func isDeterministicClientResponse(status int, body []byte) bool { + if status != http.StatusBadRequest && status != http.StatusUnprocessableEntity { + return false + } + text := strings.ToLower(string(body)) + for _, marker := range deterministicMarkers { + if strings.Contains(text, marker) { + return true + } + } + return false } // replayBody returns a body that yields prefix and then the rest of original. diff --git a/internal/gateway/free_tier_error_test.go b/internal/gateway/free_tier_error_test.go new file mode 100644 index 0000000..45500e8 --- /dev/null +++ b/internal/gateway/free_tier_error_test.go @@ -0,0 +1,133 @@ +package gateway + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "opencode2api/internal/config" + "opencode2api/internal/models" + wire "opencode2api/internal/protocol" +) + +// contextLengthBody is the free tier's answer when a request exceeds the +// model's context window. Retrying it on another key or tier cannot succeed. +const contextLengthBody = `{"error":{"message":"Your request resulted in more tokens than this model's maximum context length allows. Please reduce the length of the messages or run compaction.","type":"invalid_request_error","code":"context_length_exceeded"}}` + +// respondClient answers every request with the given status and body. +func respondClient(counter *atomic.Int64, status int, body string) *http.Client { + return &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + counter.Add(1) + return &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + Request: r, + }, nil + })} +} + +func keyedRoute() models.Route { + route := testFreeRoute() + route.KeyTiers = []config.Tier{config.TierZen} + return route +} + +// TestDoUpstreamTiersStopsAtContextLength pins that a deterministic client error +// ends the request: another key or tier cannot make an over-long context fit, +// and replaying it buries the real cause behind a later authentication error. +func TestDoUpstreamTiersStopsAtContextLength(t *testing.T) { + var requests atomic.Int64 + g, transports := newBlockTestGateway(t, 1) + attachTestClient(transports, 0, respondClient(&requests, http.StatusBadRequest, contextLengthBody)) + g.zenNodes = &upstreamNodes{transports: transports, nodes: []*upstreamNode{{key: "sk-zen"}}} + + resp, _, _, err := g.doUpstreamTiers(context.Background(), keyedRoute(), testBodies(), testRequestIDs(), 0) + if err != nil { + t.Fatalf("error = %v, want the upstream 400 returned as a response", err) + } + if resp == nil { + t.Fatal("response = nil") + } + defer resp.Body.Close() + if requests.Load() != 1 { + t.Fatalf("upstream requests = %d, want 1 (no keyed retry of a deterministic 400)", requests.Load()) + } + body, _ := io.ReadAll(resp.Body) + if !strings.Contains(string(body), "context_length_exceeded") { + t.Fatalf("body = %q, want the upstream 400 body preserved", body) + } + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want 400", resp.StatusCode) + } +} + +// TestDoUpstreamTiersKeepsAuthErrorsRetryable pins the boundary of the rule +// above: a 401 can be specific to one key, so it must still reach the next key. +func TestDoUpstreamTiersKeepsAuthErrorsRetryable(t *testing.T) { + var requests atomic.Int64 + g, transports := newBlockTestGateway(t, 1) + attachTestClient(transports, 0, respondClient(&requests, http.StatusUnauthorized, `{"error":{"message":"Invalid credential"}}`)) + g.zenNodes = &upstreamNodes{transports: transports, nodes: []*upstreamNode{{key: "sk-zen"}}} + g.cfg.Retry.MaxAttempts = 2 + + resp, _, _, err := g.doUpstreamTiers(context.Background(), keyedRoute(), testBodies(), testRequestIDs(), 0) + if err != nil { + t.Fatalf("error = %v", err) + } + if resp == nil { + t.Fatal("response = nil") + } + _ = resp.Body.Close() + if requests.Load() < 2 { + t.Fatalf("upstream requests = %d, want a second key attempt after a 401", requests.Load()) + } +} + +// TestIsDeterministicClientResponse pins the classification the rule uses. +func TestIsDeterministicClientResponse(t *testing.T) { + cases := []struct { + name string + status int + body string + want bool + }{ + {"context length", http.StatusBadRequest, contextLengthBody, true}, + {"generic invalid_request", http.StatusBadRequest, `{"error":{"type":"invalid_request_error","message":"messages: at least one message is required"}}`, true}, + {"validation error", http.StatusUnprocessableEntity, `{"error":{"type":"invalid_request_error","message":"bad shape"}}`, true}, + {"auth", http.StatusUnauthorized, `{"error":{"message":"Invalid credential"}}`, false}, + {"forbidden", http.StatusForbidden, ipAbuseBody, false}, + {"rate limit", http.StatusTooManyRequests, `{"error":{"message":"slow down"}}`, false}, + {"server", http.StatusInternalServerError, `{"error":{"message":"boom"}}`, false}, + {"empty body", http.StatusBadRequest, ``, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := isDeterministicClientResponse(tc.status, []byte(tc.body)); got != tc.want { + t.Fatalf("isDeterministicClientResponse(%d, %q) = %v, want %v", tc.status, tc.body, got, tc.want) + } + }) + } +} + +// TestCopyErrorResponseKeepsUpstreamStatus pins that the client sees the +// upstream status and message, so a 400 is not reported as a 401. +func TestCopyErrorResponseKeepsUpstreamStatus(t *testing.T) { + resp := &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(contextLengthBody)), + } + recorder := httptest.NewRecorder() + copyErrorResponse(recorder, wire.Chat, resp, "req_test") + if recorder.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400", recorder.Code) + } + if !strings.Contains(recorder.Body.String(), "maximum context length") { + t.Fatalf("body = %s, want the upstream message", recorder.Body.String()) + } +} diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index f1a19e4..6bc8004 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -237,6 +237,14 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie return resp, route, attempts, nil } lastResponse, lastErr = resp, err + if errors.Is(err, errDeterministicClientRejection) { + // The request itself was rejected. Another lane or key gets the same + // answer, and retrying only buries this error under the next one, so + // hand the upstream 4xx back as the response (nil error) and let the + // normal error path forward its status and body unchanged. + g.logger.Warn("upstream rejected the request; not retrying on other tiers", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempts", attempts, "model", route.ID) + return lastResponse, effectiveRoute, attempts, nil + } 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 @@ -280,6 +288,15 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie return resp, keyRoute, attempts, nil } if resp != nil { + if isDeterministicClientResponse(resp.StatusCode, peekResponseBody(resp)) { + // Same request-level rejection as on the anonymous lane: no + // other tier can fix it, so return it as is. + g.logger.Warn("upstream rejected the request; not trying other tiers", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempts", attempts, "tier", keyRoute.Tier, "status", resp.StatusCode) + if lastResponse != nil { + httpx.DrainAndClose(lastResponse.Body) + } + return resp, keyRoute, attempts, nil + } if lastResponse != nil { httpx.DrainAndClose(lastResponse.Body) } @@ -316,6 +333,10 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b // 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 + // halted records that the upstream rejected the request itself. The result + // then reports errDeterministicClientRejection so the caller keeps this + // 4xx instead of replacing it with a later tier's answer. + halted := false cursor := g.anonymous.CursorFor(ids.Session) limit := g.anonymous.Len() if g.anonymous.HasPool() && g.cfg.Retry.MaxAttempts > limit { @@ -424,6 +445,13 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b 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 if isDeterministicClientResponse(resp.StatusCode, peekResponseBody(resp)) { + // The request is too long, malformed, or otherwise invalid on + // every lane. Stop here and hand this 4xx to the client. + lastErr = errDeterministicClientRejection + halted = true + g.logger.Warn("upstream rejected the request; not trying other upstreams", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) + 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()) } @@ -437,11 +465,15 @@ 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. + // The caller keeps and forwards this response; a block or a + // deterministic rejection only changes the error so the keyed tiers + // are skipped. if blocked { return lastResponse, errFreeTierIPBlocked, attempts } + if halted { + return lastResponse, errDeterministicClientRejection, attempts + } return lastResponse, nil, attempts } if blocked {