Merge pull request #132 from cheerc/fix/free-tier-ip-abuse

Handle free-tier IP blocks and stop retrying request-level rejections.

Test files from the PR are omitted: this repository does not keep _test.go
files, so they are removed in the merge commit.
This commit is contained in:
Jason Xu committed 2026-10-21 02:27:11 +08:00
commit 07aa4534b9
7 files changed
+328 -8

No files matched your search

+3
View File
@@ -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
+49
View File
@@ -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
}
+138
View File
@@ -0,0 +1,138 @@
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")
}
// 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 {
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
}
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.
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() }
+11
View File
@@ -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
}
+54 -8
View File
@@ -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) {
+6
View File
@@ -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"
+67
View File
@@ -237,6 +237,21 @@ 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
// 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)
}
@@ -273,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)
}
@@ -305,6 +329,14 @@ 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
// 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 {
@@ -341,6 +373,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 +390,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 +434,24 @@ 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 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())
}
@@ -410,8 +465,20 @@ 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 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 {
return nil, errFreeTierIPBlocked, attempts
}
if lastErr == nil {
lastErr = errors.New("no healthy anonymous proxies available")
if !g.transports.hasHealthy() {