fix: harden gateway routing and protocol fidelity

Preserve request parameters, tool-call completion reasons and retry session
affinity. Bound upstream header waits, stop expired-context scans and add
opt-in redacted request-body diagnostics.

Isolate Playground diagnostics from production pools, report stream failures
accurately, align readiness with discoverable models and honor Docker listen
configuration.

Split Go and WebUI modules by responsibility, add regression tests and CI,
standardize formatting and rewrite the English and Chinese READMEs.

Refs: #6, #18, #19, #20, #21, #22, #23, #24, #25
This commit is contained in:
Jason Xu committed 2026-09-15 00:43:35 +08:00
1 parent 6d1a3c1098
commit ea29a62eca
51 files changed
+10622 -5688

No files matched your search

+263
View File
@@ -0,0 +1,263 @@
package main
import (
"bytes"
"context"
"encoding/json"
"net/http"
"strings"
"time"
)
// DebugKeySelection tells the Playground whether to use normal routing or to
// exercise one explicitly chosen upstream key.
type DebugKeySelection struct {
Mode string `json:"mode,omitempty"`
Tier Tier `json:"tier,omitempty"`
ID string `json:"id,omitempty"`
}
type DebugInferenceRequest struct {
Protocol Protocol `json:"protocol"`
Key DebugKeySelection `json:"key,omitempty"`
Request map[string]any `json:"request"`
}
type DebugInferenceResult struct {
OK bool `json:"ok"`
HTTPStatus int `json:"http_status"`
DurationMS int64 `json:"duration_ms"`
RequestID string `json:"request_id,omitempty"`
Route ModelRouteDiagnostic `json:"route"`
SelectedKey *DebugKeyView `json:"selected_key,omitempty"`
KeyTest string `json:"key_test,omitempty"`
Response any `json:"response"`
}
func (a *AdminServer) 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")
writeJSON(w, http.StatusOK, map[string]any{"models": models, "keys": keys, "metadata": metadata, "catalog": catalog, "last_inference": last})
}
func (a *AdminServer) 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 !validProtocol(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 := cloneMap(input.Request)
payload["stream"] = false
model := 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 *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 := protocolPath(input.Protocol)
trace := &requestMeta{}
ctx := context.WithValue(withDiagnosticRequest(r.Context()), requestMetaKey{}, 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 len(cfg.ServerKeys) == 0 {
writeAdminError(w, http.StatusServiceUnavailable, "debug_unavailable", "no local server key is configured")
return
}
request.Header.Set("Authorization", "Bearer "+cfg.ServerKeys[0])
if selectedKey != nil {
request = request.WithContext(withDebugKeyOverride(request.Context(), debugKeyOverride{Tier: selectedKey.Tier, KeyID: selectedKey.ID}))
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
recorder := newDebugResponseRecorder()
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 = 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.redactor)
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")
writeJSON(w, http.StatusOK, result)
}
type debugResponseRecorder struct {
header http.Header
body bytes.Buffer
status int
}
func newDebugResponseRecorder() *debugResponseRecorder {
return &debugResponseRecorder{header: make(http.Header), status: http.StatusOK}
}
func (recorder *debugResponseRecorder) Header() http.Header { return recorder.header }
func (recorder *debugResponseRecorder) WriteHeader(status int) {
if recorder.status != http.StatusOK || status == http.StatusOK {
return
}
recorder.status = status
}
func (recorder *debugResponseRecorder) Write(data []byte) (int, error) {
return recorder.body.Write(data)
}
func sanitizeDebugValue(value any, redactor *SecretRedactor) 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, redactor)
}
return result
case []any:
result := make([]any, len(current))
for index, item := range current {
result[index] = sanitizeDebugValue(item, redactor)
}
return result
case string:
return redactor.String(current)
default:
return value
}
}
func (a *AdminServer) 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"
}
}
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
}