Files
opencode2api/internal/admin/debug.go
T
CheerC 6bb3487f7f fix(probe): give probes and the Playground bench their own identity (#162)
The hourly free-model probe presented one pinned identity: project
"opencode2api:default-project" together with a session derived from the
model name. The free tier meters per project id and egress, so every
deployment running the same probe shared one bucket; once a popular exit
had charged that bucket, every probe answered 429 FreeUsageLimitError and
the model was cached as unavailable for an hour while live traffic on the
same process and egress succeeded.

The Playground bench pinned a session indirectly: it sent no session
signal, so DeriveRequestIDs fell back to conversationSeed — the system
prompt plus the first user turn — and every click replaying the same
prompt produced the same session.

Neither path is a conversation, so neither should present one. Each now
mints fresh identity per attempt: a canonical session and a random project
id for the probe, a canonical session per Playground click. Canonical ids
are forwarded verbatim, so the scope mixin does not apply and the shape the
free tier accepts is what goes out.

Verified end to end with the admin UI enabled on a temporary instance.
Three Playground clicks before the change logged the same upstream session
three times (ses_ea4eb1680ffe0B8cZBh0nKJ03A); two clicks after logged
ses_eb2c888f1ffe4Y0DodMQdwvu6c and ses_ed8748efdffe2ez6IH352OdMpV, both
200. Probes on this build measured 8/8 probe_succeeded with a fresh
availability cache — they already succeeded on this exit before the change,
so this is hardening for the charged-bucket case in the report, not a
reproduction of it.
2026-10-29 21:40:31 +08:00

316 lines
11 KiB
Go

package admin
import (
"bytes"
"encoding/json"
"net/http"
"strings"
"time"
"opencode2api/internal/config"
"opencode2api/internal/gateway"
"opencode2api/internal/httpx"
"opencode2api/internal/identity"
"opencode2api/internal/jsonutil"
modelcatalog "opencode2api/internal/models"
"opencode2api/internal/protocol"
"opencode2api/internal/telemetry"
)
// DebugKeySelection tells the Playground whether to use normal routing or to
// exercise one explicitly chosen upstream key. Mode is "auto" (empty means
// auto) or "selected"; in selected mode, Tier and ID pick one of the keys that
// DebugKeys lists.
type DebugKeySelection struct {
Mode string `json:"mode,omitempty"`
Tier config.Tier `json:"tier,omitempty"`
ID string `json:"id,omitempty"`
}
// DebugInferenceRequest is one Playground request: the protocol it is
// expressed in, which upstream key to test (Mode "auto" or "selected", the
// latter naming Tier and ID), and the request body itself.
type DebugInferenceRequest struct {
Protocol protocol.Protocol `json:"protocol"`
Key DebugKeySelection `json:"key,omitempty"`
Request map[string]any `json:"request"`
}
// DebugInferenceResult is the outcome of a Playground request: the status and
// duration of the gateway's answer, the route it took (filled from the request
// trace when one was recorded), the key that was tested and a verdict about
// it, and the response body (or the raw text when it was not JSON), redacted
// and with credential-bearing fields masked.
type DebugInferenceResult struct {
OK bool `json:"ok"`
HTTPStatus int `json:"http_status"`
DurationMS int64 `json:"duration_ms"`
RequestID string `json:"request_id,omitempty"`
Route modelcatalog.RouteDiagnostic `json:"route"`
SelectedKey *gateway.DebugKeyView `json:"selected_key,omitempty"`
KeyTest string `json:"key_test,omitempty"`
Response any `json:"response"`
}
// handleDebugModels lists the routes, the per-key targets, the catalog and the
// result of the last Playground request, so the page can render before the
// first test runs.
func (a *Server) handleDebugModels(w http.ResponseWriter, _ *http.Request) {
models, metadata := a.manager.DebugModels()
catalog := a.manager.Resources().Models
keys := a.manager.DebugKeys()
a.mu.Lock()
last := a.lastInference
a.mu.Unlock()
w.Header().Set("Cache-Control", "no-store")
httpx.WriteJSON(w, http.StatusOK, map[string]any{"models": models, "keys": keys, "metadata": metadata, "catalog": catalog, "last_inference": last})
}
// handleDebugInference runs a request through the gateway itself, in process
// and always non-streaming, and reports what happened. Auto mode follows
// normal routing; selected mode pins one upstream key and disables failover,
// so the verdict describes that key alone. The request is authenticated with
// the first enabled server key, which the gateway accounts to the Playground
// bucket, and the result is kept for handleDebugModels.
func (a *Server) handleDebugInference(w http.ResponseWriter, r *http.Request) {
if !a.allowDebug(clientIP(r)) {
writeAdminError(w, http.StatusTooManyRequests, "debug_rate_limited", "too many Playground requests; retry in one minute")
return
}
var input DebugInferenceRequest
if err := decodeAdminJSON(w, r, &input); err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
if !protocol.Valid(input.Protocol) {
writeAdminError(w, http.StatusBadRequest, "invalid_protocol", "protocol must be chat, responses, or anthropic")
return
}
if input.Request == nil {
writeAdminError(w, http.StatusBadRequest, "invalid_request", "request must be a JSON object")
return
}
payload := jsonutil.CloneMap(input.Request)
payload["stream"] = false
model := jsonutil.StringAt(payload, "model")
if model == "" {
writeAdminError(w, http.StatusBadRequest, "invalid_request", "request.model is required")
return
}
if input.Key.Mode == "" {
input.Key.Mode = "auto"
}
if input.Key.Mode != "auto" && input.Key.Mode != "selected" {
writeAdminError(w, http.StatusBadRequest, "invalid_key_mode", "key.mode must be auto or selected")
return
}
var selectedKey *gateway.DebugKeyView
if input.Key.Mode == "selected" {
selectedKey = a.manager.DebugKey(input.Key.Tier, input.Key.ID)
if selectedKey == nil {
writeAdminError(w, http.StatusBadRequest, "unknown_key_id", "selected key is not configured")
return
}
}
route := a.manager.DebugRoute(model, input.Protocol)
if selectedKey != nil {
selected, routeErr := a.manager.DebugRouteForTier(model, selectedKey.Tier)
if routeErr != nil {
writeAdminError(w, http.StatusBadRequest, "model_unavailable_for_key_tier", routeErr.Error())
return
}
route = selected
}
encoded, err := json.Marshal(payload)
if err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_request", "request contains unsupported JSON values")
return
}
path := protocol.Path(input.Protocol)
trace := &telemetry.RequestMeta{}
ctx := telemetry.WithRequestMeta(gateway.WithDiagnosticRequest(r.Context()), trace)
request, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://gateway.local"+path, bytes.NewReader(encoded))
if err != nil {
writeAdminError(w, http.StatusInternalServerError, "debug_request_failed", "could not construct Gateway request")
return
}
cfg := a.manager.Config()
if cfg.FirstEnabledServerKey() == "" {
writeAdminError(w, http.StatusServiceUnavailable, "debug_unavailable", "no local server key is configured")
return
}
request.Header.Set("Authorization", "Bearer "+cfg.FirstEnabledServerKey())
if selectedKey != nil {
request = request.WithContext(gateway.WithDebugKeyOverride(request.Context(), gateway.DebugKeyOverride{Tier: selectedKey.Tier, KeyID: selectedKey.ID}))
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
// A Playground request is not a conversation: it replays the same prompt on
// every click, so a session derived from the prompt stays one bucket until
// it is charged and every later click answers 429 while live traffic
// succeeds. A fresh session per click keeps the bench on its own bucket.
request.Header.Set("x-opencode-session", benchSession())
recorder := debugResponseRecorder()
started := time.Now()
a.manager.Handler().ServeHTTP(recorder, request)
duration := time.Since(started)
requestID := recorder.Header().Get("x-request-id")
if trace.Channel != "" {
route.Anonymous = trace.Anonymous
route.Tier = config.Tier(trace.Tier)
route.KeyID = trace.KeyID
route.Channel = trace.Channel
route.Attempts = trace.Attempts
route.NativeProtocol = trace.Protocol
}
var raw any
if json.Unmarshal(recorder.body.Bytes(), &raw) != nil {
raw = recorder.body.String()
}
raw = sanitizeDebugValue(raw, a.manager.Redact)
keyTest := ""
if selectedKey != nil {
if current := a.manager.DebugKey(selectedKey.Tier, selectedKey.ID); current != nil {
selectedKey = current
}
keyTest = classifyKeyTest(recorder.status, trace.AttemptOutcome)
}
result := DebugInferenceResult{
OK: recorder.status >= 200 && recorder.status < 300, HTTPStatus: recorder.status,
DurationMS: max(duration.Milliseconds(), 0), RequestID: requestID, Route: route,
SelectedKey: selectedKey, KeyTest: keyTest, Response: raw,
}
a.mu.Lock()
a.lastInference = &result
a.mu.Unlock()
w.Header().Set("Cache-Control", "no-store")
httpx.WriteJSON(w, http.StatusOK, result)
}
// debugResponseCapture is a minimal http.ResponseWriter that keeps the status
// and body of the gateway's answer instead of sending them.
type debugResponseCapture struct {
header http.Header
body bytes.Buffer
status int
}
// debugResponseRecorder returns a response writer that captures the gateway's
// answer for inspection. It starts at 200 and keeps the first status other
// than 200 that is written, so an explicit WriteHeader(200) after an error
// does not hide the error.
func debugResponseRecorder() *debugResponseCapture {
return &debugResponseCapture{header: make(http.Header), status: http.StatusOK}
}
func (recorder *debugResponseCapture) Header() http.Header { return recorder.header }
func (recorder *debugResponseCapture) WriteHeader(status int) {
if recorder.status != http.StatusOK || status == http.StatusOK {
return
}
recorder.status = status
}
func (recorder *debugResponseCapture) Write(data []byte) (int, error) {
return recorder.body.Write(data)
}
// sanitizeDebugValue walks a decoded JSON value, replacing the values of keys
// that name a credential (see sensitiveDebugKey) and running every string
// through redact. Maps and slices are copied; other values are returned as is.
func sanitizeDebugValue(value any, redact func(string) string) any {
switch current := value.(type) {
case map[string]any:
result := make(map[string]any, len(current))
for key, item := range current {
lower := strings.ToLower(key)
if sensitiveDebugKey(lower) {
result[key] = "***"
continue
}
result[key] = sanitizeDebugValue(item, redact)
}
return result
case []any:
result := make([]any, len(current))
for index, item := range current {
result[index] = sanitizeDebugValue(item, redact)
}
return result
case string:
return redact(current)
default:
return value
}
}
// allowDebug rate-limits Playground requests to 12 per client per minute and
// counts the request as it is allowed. When more than 4096 clients are
// tracked, windows older than a minute are dropped.
func (a *Server) allowDebug(client string) bool {
a.mu.Lock()
defer a.mu.Unlock()
now := time.Now()
window := a.debugAttempts[client]
if window.Started.IsZero() || now.Sub(window.Started) >= time.Minute {
window = loginWindow{Started: now}
}
if window.Count >= 12 {
return false
}
window.Count++
a.debugAttempts[client] = window
if len(a.debugAttempts) > 4096 {
for key, candidate := range a.debugAttempts {
if now.Sub(candidate.Started) >= time.Minute {
delete(a.debugAttempts, key)
}
}
}
return true
}
// classifyKeyTest turns a per-key diagnostic into a verdict about that key.
// Only statuses that are unambiguous about the credential are reported as key
// problems: a 4xx request-shape error says nothing about the key, and a 5xx may
// be entirely unrelated to it.
func classifyKeyTest(status int, attemptOutcome string) string {
switch {
case attemptOutcome == "transport_error":
return "transport_error"
case status >= 200 && status < 300:
return "usable"
case status == http.StatusUnauthorized || status == http.StatusForbidden:
return "rejected"
case status == http.StatusTooManyRequests:
return "rate_limited"
case status == 0:
return "unavailable"
case status >= 500:
return "upstream_error"
default:
return "request_error"
}
}
// sensitiveDebugKey reports whether a lowercased JSON key names a credential
// that must not be shown in the Playground.
func sensitiveDebugKey(key string) bool {
for _, hint := range []string{
"authorization", "cookie", "password", "secret", "api_key", "api-key", "x-api-key",
"access_token", "refresh_token", "set-cookie", "credential",
} {
if strings.Contains(key, hint) {
return true
}
}
return false
}
// benchSession returns a fresh upstream session for one Playground request. It
// is canonical so the gateway forwards it verbatim instead of re-encoding it.
func benchSession() string {
return identity.CanonicalSessionID(identity.RandomID("playground", 16))
}