Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions changelog/unreleased/server-guardrails.md
Original file line number Diff line number Diff line change
@@ -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`。
6 changes: 5 additions & 1 deletion deploy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
41 changes: 41 additions & 0 deletions internal/logs/queue_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
93 changes: 83 additions & 10 deletions internal/logs/recorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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()
Expand All @@ -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
}
}
}
}
}

Expand All @@ -214,27 +245,69 @@ 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() {
if r == nil {
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
}

Expand Down
155 changes: 155 additions & 0 deletions internal/server/authlimit.go
Original file line number Diff line number Diff line change
@@ -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")
}
Loading
Loading