diff --git a/changelog/unreleased/server-guardrails.md b/changelog/unreleased/server-guardrails.md new file mode 100644 index 00000000..1340126a --- /dev/null +++ b/changelog/unreleased/server-guardrails.md @@ -0,0 +1,13 @@ +### English + +- Enforce a tested Content-Security-Policy on every response while keeping console scripts, styles, fonts, and images working. +- Gzip console JSON responses and `/v1/models`; SSE and chat streams stay uncompressed. +- Rate-limit invalid API keys per client, return `429` with `Retry-After`, and clear the counter after a successful authentication. +- Enlarge the request-log queue, wait briefly before dropping, rate-limit the drop log, and expose `log_dropped` / `log_queue` in `/health`. + +### 中文 + +- 所有响应启用经实测的 Content-Security-Policy,同时保持控制台脚本、样式、字体与图片正常加载。 +- 控制台 JSON 与 `/v1/models` 启用 gzip;SSE 与聊天流保持不压缩。 +- 按客户端限制无效 API Key 重试,超限返回 `429` 与 `Retry-After`,鉴权成功即清零。 +- 扩大请求日志队列,满队列短暂等待后再丢弃,丢弃日志限频,并在 `/health` 暴露 `log_dropped` / `log_queue`。 diff --git a/deploy/README.md b/deploy/README.md index 0e129793..013749d5 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -194,7 +194,11 @@ not prompts, responses, tool arguments, or credentials. Console `/api/*` requires the administrator key. `/v1/*` accepts that key or an enabled client key. `/health`, static frontend resources, and `/v1/*` CORS -preflight `OPTIONS` do not require authentication. +preflight `OPTIONS` do not require authentication. Repeated invalid API keys +from one client are rate-limited and answered with `429` and `Retry-After`. + +`/health` also reports `log_dropped` (request-log writes discarded after the +queue grace period) and `log_queue` (writes waiting behind the SQLite writer). Messages / Responses are stateless compatibility APIs, not full official API implementations. They do not store server-side conversations or execute diff --git a/internal/app/app.go b/internal/app/app.go index ac065794..8837f743 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -271,6 +271,8 @@ func (a *App) newHTTP() *httpserver.Server { Console: a.Console, Update: a.Update, CrossProvider: &a.CrossProviderModelPool, + LogDrops: a.Recorder.DroppedWrites, + LogQueueDepth: a.Recorder.QueueDepth, TouchKey: func(ctx context.Context, keyID string) { if a.Control != nil && a.Control.Keys != nil { _ = a.Control.Keys.Touch(ctx, keyID) diff --git a/internal/logs/queue_test.go b/internal/logs/queue_test.go new file mode 100644 index 00000000..9b0b447a --- /dev/null +++ b/internal/logs/queue_test.go @@ -0,0 +1,41 @@ +package logs + +import ( + "sync/atomic" + "testing" + "time" +) + +func TestRequestRecorderCloseDrainsAcceptedWrites(t *testing.T) { + r := NewRequestRecorder(persistOnly{}) + var ran atomic.Int32 + for i := 0; i < 100; i++ { + r.enqueue(func() { ran.Add(1) }) + } + r.Close() + if got := ran.Load(); got != 100 { + t.Fatalf("drained writes = %d, want 100", got) + } +} + +func TestRequestRecorderDropsOnlyAfterQueueGrace(t *testing.T) { + // No loop: the first write fills the buffer and the second must wait out the + // short grace period before being counted as dropped. + r := &RequestRecorder{ + queue: make(chan func(), 1), + stop: make(chan struct{}), + done: make(chan struct{}), + } + r.enqueue(func() {}) + started := time.Now() + r.enqueue(func() {}) + if elapsed := time.Since(started); elapsed < requestLogQueueWait { + t.Fatalf("enqueue returned after %v, want at least %v", elapsed, requestLogQueueWait) + } + if got := r.DroppedWrites(); got != 1 { + t.Fatalf("dropped = %d, want 1", got) + } + if got := r.QueueDepth(); got != 1 { + t.Fatalf("queue depth = %d, want 1", got) + } +} diff --git a/internal/logs/recorder.go b/internal/logs/recorder.go index 6f523fc7..df15b626 100644 --- a/internal/logs/recorder.go +++ b/internal/logs/recorder.go @@ -9,11 +9,22 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "github.com/caigee-cmd/cli2api/internal/accounts" ) +const ( + // Request logging is telemetry, not the request path. The buffer is large + // enough to absorb a burst, and an enqueue waits briefly before giving up so + // a slow SQLite write does not immediately lose rows. Past that point a + // request must not be delayed by logging. + requestLogQueueSize = 4096 + requestLogQueueWait = 25 * time.Millisecond + dropLogInterval = 30 * time.Second +) + // Request-log retention runs in two stages, because a single age-based DELETE // destroys the only copy of the usage history: request_logs is not just the // detail log, it is also the table every aggregate reads (usage page, cost @@ -177,9 +188,14 @@ type OpenRequest struct { type RequestRecorder struct { store RequestPersister queue chan func() + stop chan struct{} + done chan struct{} + closeOnce sync.Once + queueWG sync.WaitGroup mu sync.Mutex closed bool - done chan struct{} + dropped atomic.Uint64 + lastDropLog atomic.Int64 statsCacheMu sync.Mutex statsCache map[string]statsCacheEntry usageCacheMu sync.Mutex @@ -195,7 +211,8 @@ type RequestRecorder struct { func NewRequestRecorder(store RequestPersister) *RequestRecorder { recorder := &RequestRecorder{ store: store, - queue: make(chan func(), 256), + queue: make(chan func(), requestLogQueueSize), + stop: make(chan struct{}), done: make(chan struct{}), } go recorder.loop() @@ -204,8 +221,22 @@ func NewRequestRecorder(store RequestPersister) *RequestRecorder { func (r *RequestRecorder) loop() { defer close(r.done) - for fn := range r.queue { - fn() + for { + select { + case fn := <-r.queue: + fn() + case <-r.stop: + // Drain what was already accepted before shutdown. Close waits for + // in-flight enqueues before closing stop, so nothing new can arrive. + for { + select { + case fn := <-r.queue: + fn() + default: + return + } + } + } } } @@ -214,15 +245,55 @@ func (r *RequestRecorder) enqueue(fn func()) { return } r.mu.Lock() - defer r.mu.Unlock() if r.closed { + r.mu.Unlock() return } + r.queueWG.Add(1) + r.mu.Unlock() + defer r.queueWG.Done() + select { case r.queue <- fn: + return default: - log.Printf("[logs] request recorder queue full, dropping write") } + timer := time.NewTimer(requestLogQueueWait) + defer timer.Stop() + select { + case r.queue <- fn: + case <-timer.C: + r.noteDrop() + } +} + +func (r *RequestRecorder) noteDrop() { + total := r.dropped.Add(1) + now := time.Now().UnixNano() + last := r.lastDropLog.Load() + if last != 0 && now-last < int64(dropLogInterval) { + return + } + if r.lastDropLog.CompareAndSwap(last, now) { + log.Printf("[logs] request recorder queue full, dropped writes total=%d", total) + } +} + +// DroppedWrites is the number of request-log writes rejected because the +// recorder queue stayed full past the short grace period. +func (r *RequestRecorder) DroppedWrites() uint64 { + if r == nil { + return 0 + } + return r.dropped.Load() +} + +// QueueDepth is the number of writes waiting behind the single SQLite writer. +func (r *RequestRecorder) QueueDepth() int { + if r == nil { + return 0 + } + return len(r.queue) } func (r *RequestRecorder) Close() { @@ -230,11 +301,13 @@ func (r *RequestRecorder) Close() { return } r.mu.Lock() - if !r.closed { - r.closed = true - close(r.queue) - } + r.closed = true r.mu.Unlock() + r.closeOnce.Do(func() { + // Wait for enqueues that passed the closed check but have not sent yet. + r.queueWG.Wait() + close(r.stop) + }) <-r.done } diff --git a/internal/server/authlimit.go b/internal/server/authlimit.go new file mode 100644 index 00000000..91ed13ce --- /dev/null +++ b/internal/server/authlimit.go @@ -0,0 +1,155 @@ +package server + +import ( + "net" + "net/http" + "strconv" + "strings" + "sync" + "time" +) + +const ( + // Only failed authentication is counted. Ten bad keys in a minute from one + // client is already a scanner, not a person mistyping a console key. + authFailureLimit = 10 + authFailureWindow = time.Minute + authFailureBlock = time.Minute + authFailureMaxEntries = 4096 +) + +type authFailureEntry struct { + windowStart time.Time + failures int + blockedUntil time.Time +} + +// authFailureLimiter is deliberately in-memory: it protects the SQLite lookup +// and the 401 path, not a durable security audit log. A restart clearing the +// counters is acceptable; an unbounded map is not. +type authFailureLimiter struct { + mu sync.Mutex + now func() time.Time + entries map[string]authFailureEntry +} + +func newAuthFailureLimiter(now func() time.Time) *authFailureLimiter { + if now == nil { + now = time.Now + } + return &authFailureLimiter{now: now, entries: make(map[string]authFailureEntry)} +} + +// blocked reports whether the client is already in a failure cooldown and how +// long remains. It runs before any key lookup. +func (l *authFailureLimiter) blocked(client string) (bool, time.Duration) { + if l == nil { + return false, 0 + } + l.mu.Lock() + defer l.mu.Unlock() + e, ok := l.entries[client] + if !ok { + return false, 0 + } + now := l.now() + if !e.blockedUntil.IsZero() && e.blockedUntil.After(now) { + return true, e.blockedUntil.Sub(now) + } + if e.blockedUntil.IsZero() && now.Sub(e.windowStart) >= authFailureWindow { + delete(l.entries, client) + } + return false, 0 +} + +// failure records a rejected key. The request that reaches the limit is itself +// answered with 429 so a scanner cannot keep probing at full speed. +func (l *authFailureLimiter) failure(client string) (bool, time.Duration) { + if l == nil { + return false, 0 + } + l.mu.Lock() + defer l.mu.Unlock() + now := l.now() + e, ok := l.entries[client] + if !ok || now.Sub(e.windowStart) >= authFailureWindow || (!e.blockedUntil.IsZero() && !now.Before(e.blockedUntil)) { + e = authFailureEntry{windowStart: now} + } + e.failures++ + if e.failures >= authFailureLimit { + e.blockedUntil = now.Add(authFailureBlock) + } + l.entries[client] = e + l.pruneLocked(now) + if !e.blockedUntil.IsZero() && e.blockedUntil.After(now) { + return true, e.blockedUntil.Sub(now) + } + return false, 0 +} + +func (l *authFailureLimiter) success(client string) { + if l == nil { + return + } + l.mu.Lock() + delete(l.entries, client) + l.mu.Unlock() +} + +func (l *authFailureLimiter) pruneLocked(now time.Time) { + if len(l.entries) < authFailureMaxEntries/4 { + return + } + for client, e := range l.entries { + expiredWindow := now.Sub(e.windowStart) >= authFailureWindow + expiredBlock := e.blockedUntil.IsZero() || !now.Before(e.blockedUntil) + if expiredWindow && expiredBlock { + delete(l.entries, client) + } + } + if len(l.entries) > authFailureMaxEntries { + // A spoofed-IP flood must not turn into unbounded memory. Clearing is + // safe: it only forfeits counters, never authentication state. + l.entries = make(map[string]authFailureEntry) + } +} + +func clientIP(r *http.Request) string { + if r == nil { + return "unknown" + } + addr := strings.TrimSpace(r.RemoteAddr) + if host, _, err := net.SplitHostPort(addr); err == nil { + return host + } + if addr == "" { + return "unknown" + } + return addr +} + +// credentialsPresented separates an unauthenticated page load from a wrong +// key guess. The login screen may refresh data without a key; that must not +// consume the failure budget meant for scanners. +func credentialsPresented(r *http.Request) bool { + if r == nil { + return false + } + if secret := strings.TrimSpace(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")); secret != "" { + return true + } + return strings.TrimSpace(r.Header.Get("x-api-key")) != "" +} + +func retryAfterSeconds(d time.Duration) int { + seconds := int((d + time.Second - 1) / time.Second) + if seconds < 1 { + return 1 + } + return seconds +} + +func writeAuthBlocked(w http.ResponseWriter, retry time.Duration) { + w.Header().Set("Retry-After", strconv.Itoa(retryAfterSeconds(retry))) + writeErr(w, http.StatusTooManyRequests, "too_many_auth_failures", "Too many invalid API key attempts") +} diff --git a/internal/server/authlimit_test.go b/internal/server/authlimit_test.go new file mode 100644 index 00000000..5a6e6abf --- /dev/null +++ b/internal/server/authlimit_test.go @@ -0,0 +1,124 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/auth" +) + +func TestAuthFailureLimiterBlocksAndExpires(t *testing.T) { + now := time.Date(2026, 11, 27, 12, 0, 0, 0, time.UTC) + l := newAuthFailureLimiter(func() time.Time { return now }) + for i := 1; i < authFailureLimit; i++ { + if blocked, _ := l.failure("1.2.3.4"); blocked { + t.Fatalf("blocked after %d failures, want %d", i, authFailureLimit) + } + } + blocked, retry := l.failure("1.2.3.4") + if !blocked || retry <= 0 { + t.Fatalf("limit failure = (%v, %v), want blocked with retry", blocked, retry) + } + if blocked, _ := l.blocked("1.2.3.4"); !blocked { + t.Fatal("client should be blocked") + } + if blocked, _ := l.blocked("5.6.7.8"); blocked { + t.Fatal("another client must not be blocked") + } + now = now.Add(authFailureBlock + time.Second) + if blocked, _ := l.blocked("1.2.3.4"); blocked { + t.Fatal("client should be released after cooldown") + } + if blocked, _ := l.failure("1.2.3.4"); blocked { + t.Fatal("first failure after cooldown must not block again") + } + l.success("1.2.3.4") + if blocked, _ := l.blocked("1.2.3.4"); blocked { + t.Fatal("success must clear the failure state") + } +} + +func TestAPIKeyMissingCredentialsDoNotConsumeLimit(t *testing.T) { + s := New(Server{Auth: auth.NewVerifier("right-key", nil)}) + h := s.withAPIKey(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNoContent) + }) + for i := 0; i < authFailureLimit*2; i++ { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/overview", nil)) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("missing-key attempt %d status = %d, want 401", i, rec.Code) + } + } + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/overview", nil) + req.Header.Set("Authorization", "Bearer wrong") + h.ServeHTTP(rec, req) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("first wrong-key status = %d, want 401", rec.Code) + } +} + +func TestAPIKeyFailureLimitReturns429(t *testing.T) { + s := New(Server{Auth: auth.NewVerifier("right-key", nil)}) + h := s.withAPIKey(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNoContent) + }) + + for i := 1; i <= authFailureLimit; i++ { + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/overview", nil) + req.Header.Set("Authorization", "Bearer wrong") + h.ServeHTTP(rec, req) + want := http.StatusUnauthorized + if i == authFailureLimit { + want = http.StatusTooManyRequests + } + if rec.Code != want { + t.Fatalf("attempt %d status = %d, want %d", i, rec.Code, want) + } + if i == authFailureLimit && rec.Header().Get("Retry-After") == "" { + t.Fatal("429 must include Retry-After") + } + } + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/overview", nil) + req.Header.Set("Authorization", "Bearer right-key") + h.ServeHTTP(rec, req) + if rec.Code != http.StatusTooManyRequests { + t.Fatalf("correct key during cooldown status = %d, want 429", rec.Code) + } +} + +func TestAPIKeySuccessResetsFailureLimit(t *testing.T) { + s := New(Server{Auth: auth.NewVerifier("right-key", nil)}) + h := s.withAPIKey(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNoContent) + }) + for i := 1; i < authFailureLimit; i++ { + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/overview", nil) + req.Header.Set("Authorization", "Bearer wrong") + h.ServeHTTP(rec, req) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("attempt %d status = %d, want 401", i, rec.Code) + } + } + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/overview", nil) + req.Header.Set("Authorization", "Bearer right-key") + h.ServeHTTP(rec, req) + if rec.Code != http.StatusNoContent { + t.Fatalf("valid key status = %d, want 204", rec.Code) + } + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/api/overview", nil) + req.Header.Set("Authorization", "Bearer wrong-again") + h.ServeHTTP(rec, req) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("failure after success status = %d, want 401", rec.Code) + } +} diff --git a/internal/server/compress.go b/internal/server/compress.go new file mode 100644 index 00000000..98236ea7 --- /dev/null +++ b/internal/server/compress.go @@ -0,0 +1,164 @@ +package server + +import ( + "compress/gzip" + "net/http" + "strconv" + "strings" +) + +// JSON API responses (logs, usage, account lists) can be large; static assets +// already have their own gzip path. Streaming endpoints (chat, console events) +// are deliberately excluded so SSE flushing is untouched. +func withJSONCompression(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !compressJSONPath(r.URL.Path) || r.Method == http.MethodHead { + next.ServeHTTP(w, r) + return + } + jw := &jsonResponseWriter{ + ResponseWriter: w, + gzipAccepted: acceptsGzip(r.Header.Get("Accept-Encoding")), + } + completed := false + defer func() { + // A panic must not commit a partial JSON response. Let net/http + // abort the connection instead of emitting a truncated payload. + if completed { + _ = jw.Close() + } + }() + next.ServeHTTP(jw, r) + completed = true + }) +} + +func compressJSONPath(path string) bool { + if path == "/v1/models" { + return true + } + if !strings.HasPrefix(path, "/api/") { + return false + } + switch path { + case "/api/events", "/api/chat": + return false + } + return true +} + +type jsonResponseWriter struct { + http.ResponseWriter + gzipAccepted bool + status int + headerReady bool + committed bool + gz *gzip.Writer +} + +func (w *jsonResponseWriter) WriteHeader(status int) { + if w.headerReady { + return + } + w.status = status + w.headerReady = true +} + +func (w *jsonResponseWriter) Write(p []byte) (int, error) { + if !w.headerReady { + w.status = http.StatusOK + w.headerReady = true + } + w.commit(true) + if w.gz != nil { + return w.gz.Write(p) + } + return w.ResponseWriter.Write(p) +} + +func (w *jsonResponseWriter) commit(allowCompress bool) { + if w.committed { + return + } + w.committed = true + header := w.Header() + contentType := header.Get("Content-Type") + if strings.HasPrefix(contentType, "application/json") { + addVary(header, "Accept-Encoding") + } + if allowCompress && + w.gzipAccepted && + w.status != http.StatusNoContent && + w.status != http.StatusNotModified && + strings.HasPrefix(contentType, "application/json") && + header.Get("Content-Encoding") == "" { + header.Set("Content-Encoding", "gzip") + header.Del("Content-Length") + w.gz, _ = gzip.NewWriterLevel(w.ResponseWriter, gzip.BestSpeed) + } + w.ResponseWriter.WriteHeader(w.status) +} + +func (w *jsonResponseWriter) Close() error { + if !w.headerReady { + w.status = http.StatusOK + w.headerReady = true + } + if !w.committed { + w.commit(false) + } + if w.gz != nil { + return w.gz.Close() + } + return nil +} + +func (w *jsonResponseWriter) Unwrap() http.ResponseWriter { + return w.ResponseWriter +} + +func (w *jsonResponseWriter) Flush() { + if !w.committed { + w.commit(false) + } + if w.gz != nil { + _ = w.gz.Flush() + } + if flusher, ok := w.ResponseWriter.(http.Flusher); ok { + flusher.Flush() + } +} + +func addVary(header http.Header, value string) { + for _, existing := range header.Values("Vary") { + for _, item := range strings.Split(existing, ",") { + if strings.EqualFold(strings.TrimSpace(item), value) { + return + } + } + } + header.Add("Vary", value) +} + +func acceptsGzip(value string) bool { + for _, part := range strings.Split(value, ",") { + fields := strings.Split(part, ";") + if !strings.EqualFold(strings.TrimSpace(fields[0]), "gzip") { + continue + } + q := 1.0 + for _, param := range fields[1:] { + p := strings.TrimSpace(param) + if !strings.HasPrefix(strings.ToLower(p), "q=") { + continue + } + if v, err := strconv.ParseFloat(strings.TrimSpace(p[2:]), 64); err == nil { + q = v + } + } + if q > 0 { + return true + } + } + return false +} diff --git a/internal/server/compress_test.go b/internal/server/compress_test.go new file mode 100644 index 00000000..29ef0bca --- /dev/null +++ b/internal/server/compress_test.go @@ -0,0 +1,100 @@ +package server + +import ( + "compress/gzip" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "testing" +) + +func TestJSONCompressionRoundTrip(t *testing.T) { + payload := map[string]any{"items": make([]string, 200), "ok": true} + handler := withJSONCompression(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(payload) + })) + req := httptest.NewRequest(http.MethodGet, "/api/logs", nil) + req.Header.Set("Accept-Encoding", "gzip") + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + + if got := rec.Header().Get("Content-Encoding"); got != "gzip" { + t.Fatalf("Content-Encoding = %q, want gzip", got) + } + if got := rec.Header().Get("Vary"); got != "Accept-Encoding" { + t.Fatalf("Vary = %q, want Accept-Encoding", got) + } + reader, err := gzip.NewReader(rec.Body) + if err != nil { + t.Fatalf("gzip reader: %v", err) + } + defer reader.Close() + var got map[string]any + if err := json.NewDecoder(reader).Decode(&got); err != nil { + t.Fatalf("decode: %v", err) + } + if got["ok"] != true { + t.Fatalf("body = %v", got) + } +} + +func TestJSONCompressionSkipsSSE(t *testing.T) { + handler := withJSONCompression(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + if f, ok := w.(http.Flusher); ok { + f.Flush() + } + _, _ = io.WriteString(w, "event: ping\ndata: {}\n\n") + })) + req := httptest.NewRequest(http.MethodGet, "/api/events", nil) + req.Header.Set("Accept-Encoding", "gzip") + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + if got := rec.Header().Get("Content-Encoding"); got != "" { + t.Fatalf("SSE Content-Encoding = %q, want empty", got) + } + if got := rec.Body.String(); got != "event: ping\ndata: {}\n\n" { + t.Fatalf("SSE body = %q", got) + } +} + +func TestJSONCompressionHonorsZeroQuality(t *testing.T) { + handler := withJSONCompression(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"ok":true}`)) + })) + req := httptest.NewRequest(http.MethodGet, "/v1/models", nil) + req.Header.Set("Accept-Encoding", "gzip;q=0") + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + if got := rec.Header().Get("Content-Encoding"); got != "" { + t.Fatalf("Content-Encoding = %q, want empty", got) + } +} + +func TestJSONCompressionDoesNotCommitHeaderOnPanic(t *testing.T) { + handler := withJSONCompression(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + panic("boom") + })) + req := httptest.NewRequest(http.MethodGet, "/api/logs", nil) + req.Header.Set("Accept-Encoding", "gzip") + rec := httptest.NewRecorder() + func() { + defer func() { + if recover() == nil { + t.Fatal("expected panic") + } + }() + handler.ServeHTTP(rec, req) + }() + if got := rec.Header().Get("Content-Encoding"); got != "" { + t.Fatalf("Content-Encoding = %q, want empty after panic", got) + } + if got := rec.Header().Get("Vary"); got != "" { + t.Fatalf("Vary = %q, want empty after panic", got) + } +} diff --git a/internal/server/health.go b/internal/server/health.go index 766adb66..83b9c149 100644 --- a/internal/server/health.go +++ b/internal/server/health.go @@ -29,5 +29,7 @@ func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { "version": buildinfo.Version, "commit": buildinfo.Commit, "maintenance": s.updater().Maintenance.Load(), + "log_dropped": s.logDrops(), + "log_queue": s.logQueueDepth(), }) } diff --git a/internal/server/health_test.go b/internal/server/health_test.go new file mode 100644 index 00000000..e05b971e --- /dev/null +++ b/internal/server/health_test.go @@ -0,0 +1,28 @@ +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +func TestHealthReportsLogQueueCounters(t *testing.T) { + server := New(Server{ + LogDrops: func() uint64 { return 7 }, + LogQueueDepth: func() int { return 3 }, + }) + + rec := httptest.NewRecorder() + server.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/health", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("health status = %d, want 200", rec.Code) + } + var body map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode health body: %v", err) + } + if body["log_dropped"] != float64(7) || body["log_queue"] != float64(3) { + t.Fatalf("health log counters = %v", body) + } +} diff --git a/internal/server/middleware.go b/internal/server/middleware.go index f17379e2..cce28d1a 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -10,7 +10,7 @@ import ( ) func (s *Server) Handler() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + return withSecurityHeaders(withJSONCompression(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if isOpenAIEndpoint(r.URL.Path) { setOpenAICORSHeaders(w, r) if r.Method == http.MethodOptions { @@ -23,6 +23,20 @@ func (s *Server) Handler() http.Handler { return } s.mux.ServeHTTP(w, r) + }))) +} + +const contentSecurityPolicy = "default-src 'self'; base-uri 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'self'; form-action 'self'" + +func withSecurityHeaders(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + header := w.Header() + header.Set("Content-Security-Policy", contentSecurityPolicy) + header.Set("X-Content-Type-Options", "nosniff") + header.Set("X-Frame-Options", "SAMEORIGIN") + header.Set("Referrer-Policy", "strict-origin-when-cross-origin") + header.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()") + next.ServeHTTP(w, r) }) } @@ -50,11 +64,23 @@ func setOpenAICORSHeaders(w http.ResponseWriter, r *http.Request) { func (s *Server) withAPIKey(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + client := clientIP(r) + if blocked, retry := s.authFailures.blocked(client); blocked { + writeAuthBlocked(w, retry) + return + } identity, ok := s.Auth.Authenticate(r.Context(), r) if !ok { + if credentialsPresented(r) { + if blocked, retry := s.authFailures.failure(client); blocked { + writeAuthBlocked(w, retry) + return + } + } writeErr(w, http.StatusUnauthorized, "invalid_api_key", "Missing/invalid API key") return } + s.authFailures.success(client) if identity.Kind == auth.KindKey && s.TouchKey != nil { s.TouchKey(r.Context(), identity.KeyID) } diff --git a/internal/server/middleware_test.go b/internal/server/middleware_test.go new file mode 100644 index 00000000..111a7576 --- /dev/null +++ b/internal/server/middleware_test.go @@ -0,0 +1,23 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestSecurityHeadersIncludeCSP(t *testing.T) { + server := New(Server{}) + rec := httptest.NewRecorder() + server.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/health", nil)) + + if got := rec.Header().Get("Content-Security-Policy"); got != contentSecurityPolicy { + t.Fatalf("Content-Security-Policy = %q", got) + } + if got := rec.Header().Get("X-Content-Type-Options"); got != "nosniff" { + t.Fatalf("X-Content-Type-Options = %q, want nosniff", got) + } + if got := rec.Header().Get("X-Frame-Options"); got != "SAMEORIGIN" { + t.Fatalf("X-Frame-Options = %q, want SAMEORIGIN", got) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 139c3c79..067d9412 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -4,6 +4,7 @@ import ( "context" "net/http" "sync/atomic" + "time" "github.com/caigee-cmd/cli2api/internal/auth" appconsole "github.com/caigee-cmd/cli2api/internal/console" @@ -20,8 +21,13 @@ type Server struct { Update *appupdate.Coordinator TouchKey func(ctx context.Context, keyID string) CrossProvider *atomic.Bool + // LogDrops / LogQueueDepth expose the request-log writer's backpressure + // counters so an operator can tell telemetry loss from a healthy queue. + LogDrops func() uint64 + LogQueueDepth func() int - mux *http.ServeMux + authFailures *authFailureLimiter + mux *http.ServeMux } func New(cfg Server) *Server { @@ -29,6 +35,9 @@ func New(cfg Server) *Server { if s.mux == nil { s.mux = http.NewServeMux() } + if s.authFailures == nil { + s.authFailures = newAuthFailureLimiter(time.Now) + } out := s out.routes() return &out @@ -58,3 +67,17 @@ func (s *Server) consoleHandler() *appconsole.Handler { func (s *Server) crossProviderOn() bool { return s != nil && s.CrossProvider != nil && s.CrossProvider.Load() } + +func (s *Server) logDrops() uint64 { + if s == nil || s.LogDrops == nil { + return 0 + } + return s.LogDrops() +} + +func (s *Server) logQueueDepth() int { + if s == nil || s.LogQueueDepth == nil { + return 0 + } + return s.LogQueueDepth() +}