claude-code-proxy/proxy/cmd/proxy/main_test.go
sid 8e550b9785 Local fork: hardening + ops improvements (timeout knob, demotion, /livez, drain)
This commit captures both the prior accumulated work-in-progress
(framework migration web/→svelte/, postgres storage, conversation
viewer, dashboard auth, OpenAPI spec, integration tests) AND today's
operational improvements layered on top. History wasn't checkpointed
incrementally; happy to split it via interactive rebase if a reviewer
wants smaller commits.

Today's changes (in addition to the older WIP):

1. Configurable upstream response-header timeout
   - ANTHROPIC_RESPONSE_HEADER_TIMEOUT env (default 300s)
   - Replaces hardcoded 300s in provider/anthropic.go that was firing
     on opus + 1M-context + extended thinking non-streaming requests
   - Files: internal/config/config.go, internal/provider/anthropic.go

2. Structured forward-error diagnostic logging
   - When a forward to Anthropic fails, log a single key=value line
     with request_id, model, stream, body_bytes, has_thinking,
     anthropic_beta, query, elapsed, ctx_err — alongside the existing
     human-readable error line for back-compat
   - Files: internal/handler/handlers.go (logForwardFailure)

3. Full SSE protocol passthrough + Flusher fix
   - handler/handlers.go: forward all SSE lines verbatim (event:, id:,
     retry:, : comments, blank-line terminators), not only data:.
     Previous code produced malformed SSE for strict parsers.
   - middleware/logging.go: explicit Flush() method on responseWriter.
     Embedding http.ResponseWriter (interface) does not auto-promote
     Flush(), so every w.(http.Flusher) check in the streaming
     handler was returning ok=false and SSE writes buffered in net/http
     until the body closed.

4. Non-streaming → streaming demotion (feature-flagged)
   - ANTHROPIC_DEMOTE_NONSTREAMING env (default false)
   - When enabled and the routed provider is anthropic, force stream=true
     upstream for clients that asked for stream=false. Receive SSE,
     accumulate via accumulateSSEToMessage (handles text, tool_use with
     partial_json reassembly, thinking, signature, citations_delta,
     usage merge), and synthesize a single non-streaming JSON response.
   - Eliminates the ResponseHeaderTimeout class of failure entirely.
   - Body rewrite uses json.Decoder + UseNumber() to preserve integer
     precision in unknown nested fields (tool inputs from prior turns).
   - Files: internal/config/config.go, internal/handler/handlers.go,
     cmd/proxy/main.go, cmd/proxy/main_test.go

5. Live operational state: /livez gauge + graceful drain
   - New internal/runtime package: atomic in-flight counter + draining flag
   - New middleware/inflight.go: increments runtime gauge, applied to
     /v1/* subrouter so Messages, ChatCompletions, and ProxyPassthrough
     are all counted
   - /v1/* moved to a gorilla/mux subrouter so the InFlight middleware
     applies surgically; /health, /livez, /openapi.* remain on parent
     router (unauthenticated, uncounted)
   - Health handler returns 503 draining when runtime.IsDraining() is
     true, so Traefik stops routing to a slot before drain begins
   - New /livez handler returns {status, in_flight, draining, timestamp}
   - SIGTERM handler in main.go: SetDraining(true), poll for in_flight==0
     with 32-min ceiling and 1s tick (logs every 10s), then srv.Shutdown
   - Auth bypass list extended with /livez
   - Files: internal/runtime/runtime.go (new),
     internal/middleware/inflight.go (new),
     internal/middleware/auth.go,
     internal/handler/handlers.go (Health, Livez, runtime import),
     cmd/proxy/main.go (subrouter, drain loop)

6. OpenAPI spec updates
   - Document Health 503 response and new DrainingResponse schema
   - Add /livez path with LivezResponse schema
   - Files: internal/handler/openapi.go

Verified: go build ./... clean, go test ./... all pass, go vet clean.
Three rounds of codex peer review across changes 1-5; all feedback
addressed (citations_delta, json.Number precision, drain-loop logging
via lastLog timestamp, PathPrefix tightened to "/v1/").
2026-05-02 15:15:58 -06:00

193 lines
6.3 KiB
Go

package main
import (
"io"
"log"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/seifghazi/claude-code-monitor/internal/config"
httphandler "github.com/seifghazi/claude-code-monitor/internal/handler"
"github.com/seifghazi/claude-code-monitor/internal/model"
"github.com/seifghazi/claude-code-monitor/internal/service"
)
type routerStorageStub struct {
getUsageStatsFn func(startDate, endDate, modelFilter, orgFilter string) (*model.UsageStats, error)
}
func (s *routerStorageStub) SaveRequest(*model.RequestLog) (string, error) { panic("unexpected call") }
func (s *routerStorageStub) GetRequests(int, int, string) ([]model.RequestLog, int, error) {
panic("unexpected call")
}
func (s *routerStorageStub) GetAllRequests(string) ([]*model.RequestLog, error) {
panic("unexpected call")
}
func (s *routerStorageStub) GetRequestByShortID(string) (*model.RequestLog, string, error) {
panic("unexpected call")
}
func (s *routerStorageStub) ClearRequests() (int, error) { panic("unexpected call") }
func (s *routerStorageStub) UpdateRequestWithGrading(string, *model.PromptGrade) error {
panic("unexpected call")
}
func (s *routerStorageStub) UpdateRequestWithResponse(*model.RequestLog) error {
panic("unexpected call")
}
func (s *routerStorageStub) DeleteRequestsOlderThan(time.Duration) (int, error) {
panic("unexpected call")
}
func (s *routerStorageStub) GetDatabaseStats() (map[string]interface{}, error) {
panic("unexpected call")
}
func (s *routerStorageStub) GetUsageStats(startDate, endDate, modelFilter, orgFilter string) (*model.UsageStats, error) {
if s.getUsageStatsFn != nil {
return s.getUsageStatsFn(startDate, endDate, modelFilter, orgFilter)
}
return &model.UsageStats{}, nil
}
func (s *routerStorageStub) GetRequestsSummary(string) ([]*model.RequestSummary, error) {
panic("unexpected call")
}
func (s *routerStorageStub) GetRequestsSummaryPaginated(string, string, string, int, int) ([]*model.RequestSummary, int, error) {
panic("unexpected call")
}
func (s *routerStorageStub) GetStats(string, string, string) (*model.DashboardStats, error) {
panic("unexpected call")
}
func (s *routerStorageStub) GetHourlyStats(string, string, int, string) (*model.HourlyStatsResponse, error) {
panic("unexpected call")
}
func (s *routerStorageStub) GetModelStats(string, string, string) (*model.ModelStatsResponse, error) {
panic("unexpected call")
}
func (s *routerStorageStub) GetLatestRequestDate() (*time.Time, error) { panic("unexpected call") }
func (s *routerStorageStub) GetDistinctOrganizations() ([]string, error) {
panic("unexpected call")
}
func (s *routerStorageStub) GetSettings() (*model.ProxySettings, error) {
panic("unexpected call")
}
func (s *routerStorageStub) SaveSettings(*model.ProxySettings) error { panic("unexpected call") }
func (s *routerStorageStub) GetConfig() *config.StorageConfig { return &config.StorageConfig{} }
func (s *routerStorageStub) EnsureDirectoryExists() error { return nil }
func (s *routerStorageStub) Close() error { return nil }
var _ service.StorageService = (*routerStorageStub)(nil)
func newRouterUnderTest(t *testing.T, cfg *config.Config, storage service.StorageService) http.Handler {
t.Helper()
h := httphandler.New(storage, log.New(io.Discard, "", 0), nil, nil, false)
return buildHandler(cfg, h)
}
func TestBuildHandlerKeepsDiscoveryRoutesPublicWhileProtectingDashboard(t *testing.T) {
cfg := &config.Config{
Auth: config.AuthConfig{
Enabled: true,
Token: "proxy-secret",
APIKeyHeader: "X-API-Key",
DashboardPassword: "dashboard-secret",
},
CORS: config.CORSConfig{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Authorization", "Content-Type", "X-API-Key"},
},
}
router := newRouterUnderTest(t, cfg, &routerStorageStub{
getUsageStatsFn: func(startDate, endDate, modelFilter, orgFilter string) (*model.UsageStats, error) {
return &model.UsageStats{TotalRequests: 11}, nil
},
})
for _, path := range []string{"/health", "/openapi.json", "/openapi.yaml"} {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.RemoteAddr = "10.0.0.5:12345"
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("expected %s to stay public, got %d", path, rr.Code)
}
}
req := httptest.NewRequest(http.MethodGet, "/api/stats", nil)
req.RemoteAddr = "10.0.0.5:12345"
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusUnauthorized {
t.Fatalf("expected dashboard endpoint to require auth, got %d", rr.Code)
}
}
func TestBuildHandlerRequiresBothProxyAndDashboardCredentialsForDashboardAPI(t *testing.T) {
cfg := &config.Config{
Auth: config.AuthConfig{
Enabled: true,
Token: "proxy-secret",
APIKeyHeader: "X-API-Key",
DashboardPassword: "dashboard-secret",
},
CORS: config.CORSConfig{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Authorization", "Content-Type", "X-API-Key"},
},
}
router := newRouterUnderTest(t, cfg, &routerStorageStub{
getUsageStatsFn: func(startDate, endDate, modelFilter, orgFilter string) (*model.UsageStats, error) {
return &model.UsageStats{TotalRequests: 5}, nil
},
})
testCases := []struct {
name string
setup func(*http.Request)
wantStatus int
}{
{
name: "proxy auth only",
setup: func(r *http.Request) {
r.Header.Set("X-API-Key", "proxy-secret")
},
wantStatus: http.StatusUnauthorized,
},
{
name: "dashboard auth only",
setup: func(r *http.Request) {
r.SetBasicAuth("admin", "dashboard-secret")
},
wantStatus: http.StatusUnauthorized,
},
{
name: "both auth layers",
setup: func(r *http.Request) {
r.Header.Set("X-API-Key", "proxy-secret")
r.SetBasicAuth("admin", "dashboard-secret")
},
wantStatus: http.StatusOK,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/stats", nil)
req.RemoteAddr = "10.0.0.5:12345"
tc.setup(req)
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != tc.wantStatus {
t.Fatalf("expected status %d, got %d", tc.wantStatus, rr.Code)
}
})
}
}