feat: expose authenticated playground diagnostics

This commit is contained in:
Jason Xu committed 2026-08-20 00:39:06 +08:00
1 parent 3e0a6f0b62
commit 4f8f195f9f
3 files changed
+253 -8

No files matched your search

+187 -8
View File
@@ -1,6 +1,7 @@
package main
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
@@ -41,17 +42,22 @@ type loginWindow struct {
}
type AdminServer struct {
manager *RuntimeManager
monitor *Monitor
logs *LogHub
logger *slog.Logger
mu sync.Mutex
sessions map[string]adminSession
attempts map[string]loginWindow
manager *RuntimeManager
monitor *Monitor
logs *LogHub
logger *slog.Logger
mu sync.Mutex
sessions map[string]adminSession
attempts map[string]loginWindow
debugAttempts map[string]loginWindow
lastInference *DebugInferenceResult
}
func NewAdminServer(manager *RuntimeManager, monitor *Monitor, logs *LogHub, logger *slog.Logger) *AdminServer {
return &AdminServer{manager: manager, monitor: monitor, logs: logs, logger: logger, sessions: make(map[string]adminSession), attempts: make(map[string]loginWindow)}
return &AdminServer{
manager: manager, monitor: monitor, logs: logs, logger: logger, sessions: make(map[string]adminSession),
attempts: make(map[string]loginWindow), debugAttempts: make(map[string]loginWindow),
}
}
func (a *AdminServer) Handler() http.Handler {
@@ -65,6 +71,8 @@ func (a *AdminServer) Handler() http.Handler {
mux.Handle("POST /api/config/reveal", a.authenticate(a.csrf(http.HandlerFunc(a.handleReveal))))
mux.Handle("PUT /api/account", a.authenticate(a.csrf(http.HandlerFunc(a.handleAccount))))
mux.Handle("GET /api/monitor", a.authenticate(http.HandlerFunc(a.handleMonitor)))
mux.Handle("GET /api/debug/models", a.authenticate(http.HandlerFunc(a.handleDebugModels)))
mux.Handle("POST /api/debug/inference", a.authenticate(a.csrf(http.HandlerFunc(a.handleDebugInference))))
mux.Handle("GET /api/logs", a.authenticate(http.HandlerFunc(a.handleLogs)))
mux.Handle("GET /api/logs/stream", a.authenticate(http.HandlerFunc(a.handleLogStream)))
mux.Handle("/", a.staticHandler())
@@ -392,6 +400,154 @@ func (a *AdminServer) handleMonitor(w http.ResponseWriter, _ *http.Request) {
})
}
type DebugInferenceRequest struct {
Protocol Protocol `json:"protocol"`
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"`
Response any `json:"response"`
}
func (a *AdminServer) handleDebugModels(w http.ResponseWriter, _ *http.Request) {
models, metadata := a.manager.DebugModels()
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, "metadata": metadata, "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
}
route := a.manager.DebugRoute(model, input.Protocol)
encoded, err := json.Marshal(payload)
if err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_request", "request contains unsupported JSON values")
return
}
path := protocolPath(input.Protocol)
request, err := http.NewRequestWithContext(r.Context(), 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])
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 requestID != "" {
upstream := a.monitor.Snapshot().Upstream.Recent
for index := len(upstream) - 1; index >= 0; index-- {
if upstream[index].RequestID == requestID {
route.Anonymous = upstream[index].Anonymous
route.Tier = Tier(upstream[index].Tier)
break
}
}
}
var raw any
if json.Unmarshal(recorder.body.Bytes(), &raw) != nil {
raw = recorder.body.String()
}
raw = sanitizeDebugValue(raw, a.manager.redactor)
result := DebugInferenceResult{
OK: recorder.status >= 200 && recorder.status < 300, HTTPStatus: recorder.status,
DurationMS: max(duration.Milliseconds(), 0), RequestID: requestID, Route: route, 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 strings.Contains(lower, "authorization") || strings.Contains(lower, "cookie") || strings.Contains(lower, "password") || strings.Contains(lower, "secret") || strings.Contains(lower, "api_key") || strings.Contains(lower, "api-key") {
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) handleLogs(w http.ResponseWriter, r *http.Request) {
after, _ := strconv.ParseUint(r.URL.Query().Get("after"), 10, 64)
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
@@ -555,6 +711,29 @@ func (a *AdminServer) recordLoginFailure(client string) {
a.attempts[client] = window
}
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
}
func (a *AdminServer) cleanupSessionsLocked(now time.Time) {
for token, session := range a.sessions {
if now.After(session.Expires) {
+36
View File
@@ -39,6 +39,19 @@ type modelRoute struct {
Anonymous bool
}
type ModelRouteDiagnostic struct {
Model string `json:"model"`
RequestedProtocol Protocol `json:"requested_protocol,omitempty"`
NativeProtocol Protocol `json:"native_protocol"`
ProtocolSource string `json:"protocol_source"`
AvailableZen bool `json:"available_zen"`
AvailableGo bool `json:"available_go"`
Tier Tier `json:"tier,omitempty"`
Anonymous bool `json:"anonymous"`
AnonymousEligibility AnonymousDecision `json:"anonymous_eligibility"`
RouteError string `json:"route_error,omitempty"`
}
type modelCatalog struct {
mu sync.RWMutex
zen map[string]bool
@@ -143,6 +156,29 @@ func (c *modelCatalog) anonymousDecision(model string) AnonymousDecision {
return AnonymousDecision{Allowed: isFreeModel(model), Source: "name_fallback_metadata_pending"}
}
func (c *modelCatalog) Diagnostic(model string, requested Protocol, hasZenKeys, hasGoKeys, hasAnonymous bool) ModelRouteDiagnostic {
c.mu.RLock()
protocol, explicit := c.protocols[model]
zen, goModel := c.zen[model], c.goModels[model]
c.mu.RUnlock()
source := "configured"
if !explicit {
protocol = inferProtocol(model)
source = "inferred"
}
diagnostic := ModelRouteDiagnostic{
Model: model, RequestedProtocol: requested, NativeProtocol: protocol, ProtocolSource: source,
AvailableZen: zen, AvailableGo: goModel, AnonymousEligibility: c.anonymousDecision(model),
}
route, err := c.Route(model, hasZenKeys, hasGoKeys, hasAnonymous)
if err != nil {
diagnostic.RouteError = err.Error()
return diagnostic
}
diagnostic.Tier, diagnostic.Anonymous = route.Tier, route.Anonymous
return diagnostic
}
func isFreeModel(model string) bool {
return strings.Contains(strings.ToLower(model), "free")
}
+30
View File
@@ -281,6 +281,36 @@ func (m *RuntimeManager) Resources() ResourceSnapshot {
return result
}
func (m *RuntimeManager) DebugModels() ([]ModelRouteDiagnostic, MetadataSnapshot) {
runtime := m.current.Load()
if runtime == nil {
return nil, MetadataSnapshot{}
}
gateway := runtime.gateway
models := gateway.catalog.List()
result := make([]ModelRouteDiagnostic, 0, len(models))
for _, model := range models {
if !supportedModel(model) {
continue
}
result = append(result, gateway.catalog.Diagnostic(model, "", len(gateway.cfg.ZenKeys) > 0, len(gateway.cfg.GoKeys) > 0, gateway.cfg.Anonymous))
}
metadata := MetadataSnapshot{}
if gateway.catalog.metadata != nil {
metadata = gateway.catalog.metadata.Snapshot()
}
return result, metadata
}
func (m *RuntimeManager) DebugRoute(model string, requested Protocol) ModelRouteDiagnostic {
runtime := m.current.Load()
if runtime == nil {
return ModelRouteDiagnostic{Model: model, RequestedProtocol: requested, RouteError: "gateway runtime is unavailable"}
}
gateway := runtime.gateway
return gateway.catalog.Diagnostic(model, requested, len(gateway.cfg.ZenKeys) > 0, len(gateway.cfg.GoKeys) > 0, gateway.cfg.Anonymous)
}
func keyStatuses(tier string, pool *nodePool) []KeyStatus {
result := make([]KeyStatus, 0, len(pool.nodes))
for _, node := range pool.nodes {