diff --git a/concurrency.go b/concurrency.go index d6c5090..eecf116 100644 --- a/concurrency.go +++ b/concurrency.go @@ -95,6 +95,9 @@ func (c *concurrencyLearner) observe(provider string, resp *http.Response, err e if next < 1 { next = 1 } + if next > learnedCeiling-1 { + next = learnedCeiling - 1 + } if s.learned == 0 || next < s.learned { s.learned = next } diff --git a/concurrency_test.go b/concurrency_test.go new file mode 100644 index 0000000..a79ae7f --- /dev/null +++ b/concurrency_test.go @@ -0,0 +1,36 @@ +package traefikllmgateway + +import ( + "net/http" + "testing" +) + +// TestConcurrencyLearner_OverloadStaysBelowCeiling pins that an overload +// observation on an unknown limit never learns a value at or above the +// ceiling, however many requests were in flight. +func TestConcurrencyLearner_OverloadStaysBelowCeiling(t *testing.T) { + t.Parallel() + tests := []struct { + name string + inFlight int + }{ + {name: "one in flight", inFlight: 1}, + {name: "typical load", inFlight: 8}, + {name: "exactly at ceiling", inFlight: 2 * learnedCeiling}, + {name: "far above ceiling", inFlight: 1000}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + c := newConcurrencyLearner(0) + for range tt.inFlight { + _ = c.begin("p") + } + c.observe("p", &http.Response{StatusCode: http.StatusTooManyRequests}, nil) + got := c.limit("p") + if got < 1 || got > learnedCeiling-1 { + t.Errorf("limit = %d, want in [1, %d]", got, learnedCeiling-1) + } + }) + } +} diff --git a/providers.go b/providers.go index f06bb3e..08adb45 100644 --- a/providers.go +++ b/providers.go @@ -231,7 +231,14 @@ func newAdapterHTTPClient(timeout time.Duration) *http.Client { } tr.MaxIdleConnsPerHost = adapterIdleConnsPerHost tr.ResponseHeaderTimeout = timeout - return &http.Client{Transport: tr} + // Redirects are not followed: the client re-sends provider API key + // headers, and a hijacked redirect target would receive them. + return &http.Client{ + Transport: tr, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + } } // attemptRecorder is invoked once per upstream HTTP attempt a shared diff --git a/providers_test.go b/providers_test.go index 2bab1b8..4b9473f 100644 --- a/providers_test.go +++ b/providers_test.go @@ -6,8 +6,11 @@ import ( "errors" "io" "net/http" + "net/http/httptest" + "sync/atomic" "testing" "testing/iotest" + "time" ) // TestProviderPassthroughEnabled is the security+performance audit @@ -210,3 +213,49 @@ func TestReadAllLimited_PropagatesNonEOFError(t *testing.T) { t.Errorf("readAllLimited err = %v, want errors.Is match for %v", gotErr, injected) } } + +// TestAdapterHTTPClient_RedirectHandling pins that the adapter client +// never follows a redirect, so provider API key headers are not re-sent +// to a redirect target. +func TestAdapterHTTPClient_RedirectHandling(t *testing.T) { + t.Parallel() + tests := []struct { + name string + wantStatus int + wantFollowed bool + }{ + {name: "redirect returned to caller, target not contacted", wantStatus: http.StatusFound, wantFollowed: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + var followed atomic.Bool + target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + followed.Store(true) + })) + t.Cleanup(target.Close) + redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL, http.StatusFound) + })) + t.Cleanup(redirector.Close) + + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, redirector.URL, nil) + if err != nil { + t.Fatalf("NewRequestWithContext: %v", err) + } + req.Header.Set("x-api-key", "test-key") + resp, err := newAdapterHTTPClient(time.Second).Do(req) + if err != nil { + t.Fatalf("Do: %v", err) + } + t.Cleanup(func() { _ = resp.Body.Close() }) + + if resp.StatusCode != tt.wantStatus { + t.Errorf("status = %d, want %d", resp.StatusCode, tt.wantStatus) + } + if got := followed.Load(); got != tt.wantFollowed { + t.Errorf("redirect target contacted = %v, want %v", got, tt.wantFollowed) + } + }) + } +} diff --git a/retry.go b/retry.go index 545b7a1..fa7ee74 100644 --- a/retry.go +++ b/retry.go @@ -171,7 +171,7 @@ func defaultWaitFn(ctx context.Context, d time.Duration) bool { // tries total); the maximum, maxRetryAttempts, is 3 retries (four tries // total). A value outside 1..maxRetryAttempts is a config error. // rc.Backoff defaults to defaultRetryBackoff when left empty, and must -// parse via time.ParseDuration either way. +// parse via time.ParseDuration to a positive duration either way. func newRetryPolicy(rc RetryConfig) (*retryPolicy, error) { if !rc.Enabled { return &retryPolicy{enabled: false, waitFn: defaultWaitFn}, nil @@ -193,6 +193,9 @@ func newRetryPolicy(rc RetryConfig) (*retryPolicy, error) { if err != nil { return nil, fmt.Errorf("llmgateway: retry.backoff: %w", err) } + if backoff <= 0 { + return nil, fmt.Errorf("llmgateway: retry.backoff must be positive, got %q", backoffStr) + } return &retryPolicy{enabled: true, attempts: attempts, backoff: backoff, waitFn: defaultWaitFn}, nil } @@ -263,6 +266,10 @@ func (p *retryPolicy) waitBefore(attempt int, resp *http.Response) (wait time.Du } } + // Compare before multiplying: a backoff at or above the cap must not overflow the shift. + if p.backoff >= maxRetryWait { + return maxRetryWait, false + } wait = p.backoff * time.Duration(int64(1)< maxRetryWait { wait = maxRetryWait diff --git a/retry_test.go b/retry_test.go index ca7ec75..165c999 100644 --- a/retry_test.go +++ b/retry_test.go @@ -1087,3 +1087,52 @@ func TestRetryPolicy_Do_NoAttemptRecorderInContext_NoPanic(t *testing.T) { t.Errorf("resp.StatusCode = %d, want 200", resp.StatusCode) } } + +// TestNewRetryPolicy_RejectsNonPositiveBackoff pins that a zero or +// negative backoff is a config error, not a silent no-wait retry. +func TestNewRetryPolicy_RejectsNonPositiveBackoff(t *testing.T) { + t.Parallel() + tests := []struct { + name string + backoff string + wantErr bool + }{ + {name: "zero", backoff: "0s", wantErr: true}, + {name: "negative", backoff: "-1s", wantErr: true}, + {name: "positive", backoff: "1ms", wantErr: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + _, err := newRetryPolicy(RetryConfig{Enabled: true, Backoff: tt.backoff}) + if (err != nil) != tt.wantErr { + t.Errorf("newRetryPolicy(Backoff:%q) err = %v, wantErr %v", tt.backoff, err, tt.wantErr) + } + }) + } +} + +// TestRetryPolicy_WaitBeforeLargeBackoffCapped pins that a backoff at or +// above the cap returns the cap for every attempt, without overflowing. +func TestRetryPolicy_WaitBeforeLargeBackoffCapped(t *testing.T) { + t.Parallel() + tests := []struct { + name string + backoff time.Duration + }{ + {name: "equal to cap", backoff: maxRetryWait}, + {name: "int64 overflow range", backoff: time.Duration(1) << 62}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + p := &retryPolicy{enabled: true, attempts: maxRetryAttempts, backoff: tt.backoff, waitFn: defaultWaitFn} + for attempt := 1; attempt <= maxRetryAttempts; attempt++ { + got, fromRetryAfter := p.waitBefore(attempt, nil) + if got != maxRetryWait || fromRetryAfter { + t.Errorf("attempt %d: waitBefore = (%v, %v), want (%v, false)", attempt, got, fromRetryAfter, maxRetryWait) + } + } + }) + } +} diff --git a/routes_passthrough.go b/routes_passthrough.go index a5a5198..4fc311d 100644 --- a/routes_passthrough.go +++ b/routes_passthrough.go @@ -442,11 +442,15 @@ func newTeeBudget(limit int64) *teeBudget { return &teeBudget{limit: limit} } // reserve claims n bytes and reports whether the budget had room. func (b *teeBudget) reserve(n int64) bool { - if atomic.AddInt64(&b.used, n) > b.limit { - atomic.AddInt64(&b.used, -n) - return false + for { + cur := atomic.LoadInt64(&b.used) + if cur+n > b.limit { + return false + } + if atomic.CompareAndSwapInt64(&b.used, cur, cur+n) { + return true + } } - return true } func (b *teeBudget) free(n int64) { atomic.AddInt64(&b.used, -n) } diff --git a/security_fixes_test.go b/security_fixes_test.go index 86b9c4c..ad0738c 100644 --- a/security_fixes_test.go +++ b/security_fixes_test.go @@ -351,3 +351,35 @@ func TestLogSafe(t *testing.T) { assert.Equal(t, `a\nllmgw[x] ERROR forged`, logSafe("a\nllmgw[x] ERROR forged")) assert.Equal(t, `a\r\nb`, logSafe("a\r\nb")) } + +// TestTeeBudget_ReserveNeverExceedsLimit pins that concurrent reserves +// grant exactly the budget: used never passes limit, and no reserve is +// denied while room remains. +func TestTeeBudget_ReserveNeverExceedsLimit(t *testing.T) { + t.Parallel() + const ( + limit = 100 + chunk = 10 + workers = 50 + ) + b := newTeeBudget(limit) + var granted atomic.Int64 + var overshoot atomic.Bool + var wg sync.WaitGroup + for range workers { + wg.Add(1) + go func() { + defer wg.Done() + if b.reserve(chunk) { + granted.Add(chunk) + } + if atomic.LoadInt64(&b.used) > limit { + overshoot.Store(true) + } + }() + } + wg.Wait() + assert.False(t, overshoot.Load(), "used must never exceed limit") + assert.EqualValues(t, limit, granted.Load(), "exactly the budget is granted") + assert.EqualValues(t, limit, atomic.LoadInt64(&b.used)) +} diff --git a/sse.go b/sse.go index 424b935..aa0eedd 100644 --- a/sse.go +++ b/sse.go @@ -39,6 +39,11 @@ const sseScannerMaxLineSize = 4 * 1024 * 1024 // tuning knob. const sseMaxEventBytes = 8 * 1024 * 1024 +// sseDataLineOverhead is the per-"data:" line cost counted against +// sseMaxEventBytes: 1 byte for the joined "\n" plus the 16-byte string +// header the dataLines slice retains for the line. +const sseDataLineOverhead = 1 + 16 + // errSSEEventTooLarge is returned by readSSE when one event's accumulated // "data:" payload exceeds sseMaxEventBytes. It mirrors how the per-line // cap surfaces (bufio.ErrTooLong is returned as-is): the caller's stream @@ -195,10 +200,11 @@ func readSSE(r io.Reader, fn func(sseEvent) error) error { case "event": event = value case "data": - // +1 for the "\n" this line will contribute to the joined - // payload. Checked BEFORE appending, so the cap bounds what is - // actually held rather than catching it one line late. - dataBytes += len(value) + 1 + // Each line costs its payload plus the "\n" it adds to the + // joined payload plus the string header dataLines retains, so + // many empty lines cannot amplify past the cap. Checked BEFORE + // appending, so the cap bounds what is actually held. + dataBytes += len(value) + sseDataLineOverhead if dataBytes > sseMaxEventBytes { return errSSEEventTooLarge } diff --git a/sse_test.go b/sse_test.go index 95f7840..71ce3cf 100644 --- a/sse_test.go +++ b/sse_test.go @@ -571,3 +571,30 @@ func TestNewFlushWriter_AssertsFlusherOnce(t *testing.T) { } }) } + +// TestReadSSE_EmptyDataLinesCountTheirRetainedCost pins that an event of +// many empty "data:" lines hits the size cap on retained cost, not just +// payload bytes. +func TestReadSSE_EmptyDataLinesCountTheirRetainedCost(t *testing.T) { + t.Parallel() + maxLines := sseMaxEventBytes / sseDataLineOverhead + tests := []struct { + wantErr error + name string + lines int + }{ + {name: "few lines", lines: 10, wantErr: nil}, + {name: "just under the cap", lines: maxLines - 10, wantErr: nil}, + {name: "past the cap", lines: maxLines + 10, wantErr: errSSEEventTooLarge}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + input := strings.Repeat("data:\n", tt.lines) + "\n" + err := readSSE(strings.NewReader(input), func(sseEvent) error { return nil }) + if !errors.Is(err, tt.wantErr) { + t.Errorf("readSSE err = %v, want %v", err, tt.wantErr) + } + }) + } +}