fix(security): audit run-4 fixes and run-3 leftovers (#26)

Corrects passthrough metering, the cost gate, credential redaction, reload drain, response headers and the discovery cap.
This commit is contained in:
2026-11-29 10:50:36 +00:00
committed by GitHub
parent 009de03264
commit f1b198bce4
48 changed files with 3598 additions and 211 deletions
+24 -10
View File
@@ -142,7 +142,7 @@ func parseOptions(args []string, stderr *os.File) (*options, error) {
fs.DurationVar(&o.reloadEvery, "reload-interval", envDurationOr("LLMGW_RELOAD_INTERVAL", defaultReloadEvery),
"how often to check the config file for changes; 0 turns polling off (SIGHUP still reloads) [LLMGW_RELOAD_INTERVAL]")
fs.DurationVar(&o.reloadDrain, "reload-drain-timeout", envDurationOr("LLMGW_RELOAD_DRAIN_TIMEOUT", defaultReloadDrain),
"how long a replaced gateway keeps running for its in-flight requests before it is closed [LLMGW_RELOAD_DRAIN_TIMEOUT]")
"how long to wait before warning that a replaced gateway still has in-flight requests; it closes only when the last one ends [LLMGW_RELOAD_DRAIN_TIMEOUT]")
fs.BoolVar(&o.showVersion, "version", false, "print this binary's version and exit")
if err := fs.Parse(args); err != nil {
return nil, err
@@ -260,7 +260,7 @@ func run() error {
}
sw := &swapHandler{}
sw.cur.Store(newGeneration(handler, func() { closeGateway(handler, log) }))
sw.cur.Store(loggedGeneration(handler, log, opts.reloadDrain))
var ready atomic.Bool
srv := &http.Server{
@@ -367,7 +367,8 @@ func run() error {
// The reloader exits on ctx; waiting for it means no swap lands after the close below.
<-reloadDone
// STRICTLY after Shutdown returns. Close releases the pooled Redis
// STRICTLY after Shutdown returns; when it timed out, requests still
// running are abandoned and lose their last Redis writes. Close releases the pooled Redis
// connections shared by the limiter's store and the response cache;
// closing them while requests are still draining would pull Redis out
// from under in-flight handlers, and under the common redis.failOpen
@@ -579,23 +580,36 @@ func yamlToJSON(raw []byte) ([]byte, error) {
return j, nil
}
// logTelemetryOptOut reports which anonymous-telemetry opt-out variable is
// set, if any, so a deployment that believes it opted out can confirm it
// from the startup log. It deliberately does not claim whether a ping
// will actually be sent: that also depends on the build being
// version-stamped, and the root package's decision function is
// unexported.
// logTelemetryOptOut confirms an opt-out only when the client will act on it,
// so a deployment that believes it opted out can trust the startup log. A
// non-empty value the client ignores gets a warning instead. It does not
// claim a ping will be sent: that also depends on the build being
// version-stamped, and the root package's decision function is unexported.
func logTelemetryOptOut(log *logger) {
for _, k := range telemetryOptOutVars {
if v := os.Getenv(k); v != "" {
if v := os.Getenv(k); telemetryTruthy(v) {
log.info("anonymous usage reporting opted out via %s=%s", k, v)
return
}
}
for _, k := range telemetryOptOutVars {
if v := os.Getenv(k); v != "" {
log.warn("%s=%s is not a recognised opt-out value (1, true, yes, on); reporting stays enabled", k, v)
}
}
log.info("anonymous usage reporting not opted out (set DO_NOT_TRACK=1 to disable); " +
"only version-stamped release builds ever send a ping")
}
// telemetryTruthy mirrors the opt-out values oss-telemetry accepts (its telemetry.go, truthy).
func telemetryTruthy(s string) bool {
switch strings.ToLower(strings.TrimSpace(s)) {
case "1", "true", "yes", "on":
return true
}
return false
}
// logger is this binary's own leveled logger. It governs ONLY the
// lifecycle lines written here — the gateway's own output goes straight
// to stderr from the root package's unexported helpers and cannot be
+44 -7
View File
@@ -19,8 +19,10 @@ const genRetired int64 = 1 << 62
// generation is one constructed gateway and the requests running on it.
type generation struct {
h http.Handler
closeFn func()
h http.Handler
closeFn func()
// overdue reports a generation that outlived its drain timeout, with the requests still running on it.
overdue func(running int64)
timer atomic.Pointer[time.Timer]
state atomic.Int64
once sync.Once
@@ -31,6 +33,17 @@ func newGeneration(h http.Handler, closeFn func()) *generation {
return &generation{h: h, closeFn: closeFn}
}
const overdueFormat = "reload: a replaced gateway still has %d running requests after %s; it stays open until they end"
// loggedGeneration wraps h in a generation that closes the gateway and warns when it outlives drain once retired.
func loggedGeneration(h http.Handler, log *logger, drain time.Duration) *generation {
g := newGeneration(h, func() { closeGateway(h, log) })
g.overdue = func(running int64) {
log.warn(overdueFormat, running, drain)
}
return g
}
// enter counts a request in. It returns false when the generation is retired; the caller must not serve on it.
func (g *generation) enter() bool {
if g.state.Add(1)&genRetired != 0 {
@@ -46,7 +59,9 @@ func (g *generation) leave() {
}
}
// retire stops new requests. The gateway closes when the last running request leaves, or after maxWait.
// retire stops new requests. The gateway closes when the last running request leaves, however long that takes.
// A request is never cancelled: closing the gateway under it would drop its Redis-backed accounting.
// Each maxWait after the retire, a generation that still has requests reports them through overdue.
func (g *generation) retire(maxWait time.Duration) {
if !g.markRetired() {
return
@@ -54,7 +69,20 @@ func (g *generation) retire(maxWait time.Duration) {
// Idle MCP event streams have no end of their own; ending them lets their
// clients reconnect to the new generation and this one close.
drainIdleStreams(g.h)
g.timer.Store(time.AfterFunc(maxWait, g.shut))
g.armOverdue(maxWait)
}
// armOverdue schedules the next overdue report in d.
func (g *generation) armOverdue(d time.Duration) {
g.timer.Store(time.AfterFunc(d, func() {
if g.shutDone.Load() {
return
}
if g.overdue != nil {
g.overdue(g.state.Load() &^ genRetired)
}
g.armOverdue(d)
}))
// A shut that ran before the Store could not stop the timer, so stop it here.
if g.shutDone.Load() {
g.stopTimer()
@@ -79,7 +107,7 @@ func (g *generation) markRetired() bool {
}
}
// shut closes the gateway once and stops the drain timer, so a closed generation is not held until it fires.
// shut closes the gateway once and stops the overdue timer, so a closed generation is not held until it fires.
func (g *generation) shut() {
g.once.Do(func() {
g.closeFn()
@@ -102,12 +130,17 @@ type swapHandler struct {
func (s *swapHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for {
g := s.cur.Load()
// A false enter means a swap already installed a newer generation, so the next load finds it.
if g.enter() {
defer g.leave()
g.h.ServeHTTP(w, r)
return
}
// A swap installs the newer generation before it retires the old one, so an unchanged
// pointer means closeCurrent ran and no other generation will come.
if s.cur.Load() == g {
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
}
}
@@ -195,7 +228,11 @@ func (r *reloader) check(force bool) {
}
r.buildErr = ""
r.last = sum
r.swap.swap(newGeneration(h, func() { closeGateway(h, r.log) }), r.drain)
g := newGeneration(h, func() { closeGateway(h, r.log) })
g.overdue = func(running int64) {
r.log.warn(overdueFormat, running, r.drain)
}
r.swap.swap(g, r.drain)
r.log.info("reload: config %s applied", r.path)
}
+140
View File
@@ -0,0 +1,140 @@
package main
import (
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// fakeRedis stands in for the shared Redis client: closing it makes later use fail, as in a real closed pool.
type fakeRedis struct {
closed atomic.Bool
writes atomic.Int32
failed atomic.Int32
}
func (f *fakeRedis) incr() {
if f.closed.Load() {
f.failed.Add(1)
return
}
f.writes.Add(1)
}
func waitFor(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for %s", what)
}
time.Sleep(2 * time.Millisecond)
}
}
// TestGenerationOutlivingDrainTimeoutStaysOpen: a request that runs past the drain timeout still reaches its
// Redis-backed state, and the generation closes only after that request leaves.
func TestGenerationOutlivingDrainTimeoutStaysOpen(t *testing.T) {
redis := &fakeRedis{}
var closes atomic.Int32
release := make(chan struct{})
started := make(chan struct{})
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(started)
<-release
redis.incr()
w.WriteHeader(http.StatusNoContent)
})
oldGen := newGeneration(h, func() { closes.Add(1); redis.closed.Store(true) })
var warned atomic.Int32
oldGen.overdue = func(int64) { warned.Add(1) }
sw := &swapHandler{}
sw.cur.Store(oldGen)
done := make(chan struct{})
rec := httptest.NewRecorder()
go func() {
sw.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
close(done)
}()
<-started
sw.swap(newGeneration(okHandler(), func() {}), 15*time.Millisecond)
waitFor(t, "the overdue warning", func() bool { return warned.Load() >= 1 })
if closes.Load() != 0 {
t.Fatalf("generation closed %d times under a running request", closes.Load())
}
close(release)
<-done
if redis.writes.Load() != 1 || redis.failed.Load() != 0 {
t.Errorf("request after the timeout: writes=%d failed=%d, want 1 and 0", redis.writes.Load(), redis.failed.Load())
}
if closes.Load() != 1 {
t.Errorf("closes = %d after the last request left, want 1", closes.Load())
}
}
func TestGenerationWarnsRepeatedlyWithRunningCount(t *testing.T) {
var closes atomic.Int32
g := countingGen(okHandler(), &closes)
var mu sync.Mutex
var counts []int64
g.overdue = func(n int64) {
mu.Lock()
counts = append(counts, n)
mu.Unlock()
}
g.enter()
g.enter()
g.retire(10 * time.Millisecond)
waitFor(t, "two warnings", func() bool { mu.Lock(); defer mu.Unlock(); return len(counts) >= 2 })
g.leave()
g.leave()
if closes.Load() != 1 {
t.Fatalf("closes = %d, want 1", closes.Load())
}
mu.Lock()
n := len(counts)
first := counts[0]
mu.Unlock()
if first != 2 {
t.Errorf("first warning counted %d running requests, want 2", first)
}
time.Sleep(50 * time.Millisecond)
mu.Lock()
defer mu.Unlock()
if len(counts) != n {
t.Errorf("warnings continued after the generation closed: %d then %d", n, len(counts))
}
}
func TestGenerationNoWarningWhenDrainedInTime(t *testing.T) {
var closes atomic.Int32
g := countingGen(okHandler(), &closes)
var warned atomic.Int32
g.overdue = func(int64) { warned.Add(1) }
g.enter()
g.retire(20 * time.Millisecond)
g.leave()
time.Sleep(60 * time.Millisecond)
if warned.Load() != 0 || closes.Load() != 1 {
t.Errorf("warned=%d closes=%d, want 0 and 1", warned.Load(), closes.Load())
}
}
// TestLoggedGenerationWarnsWhenOverdue covers the generation that main installs first: its first replacement must warn too.
func TestLoggedGenerationWarnsWhenOverdue(t *testing.T) {
g := loggedGeneration(okHandler(), newLogger("info"), 10*time.Millisecond)
g.enter()
out := captureTelemetryStderr(t, func() {
// Called directly: a timer callback could still log while captureTelemetryStderr restores os.Stderr.
g.overdue(1)
})
if !strings.Contains(out, "still has 1 running requests") {
t.Errorf("no overdue warning from the initial generation: %q", out)
}
}
+69
View File
@@ -0,0 +1,69 @@
package main
import (
"bytes"
"context"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
const reloadTargetMarker = "DUMMY-RELOAD-TARGET-0006"
func captureStderr(t *testing.T, fn func()) string {
t.Helper()
orig := os.Stderr
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
os.Stderr = w
defer func() { os.Stderr = orig }()
fn()
_ = w.Close()
var buf bytes.Buffer
if _, err := io.Copy(&buf, r); err != nil {
t.Fatal(err)
}
return buf.String()
}
func TestReloadRejectionLog_OmitsTargetCredential(t *testing.T) {
const tmpl = `providers:
openai:
type: openai
apiKey: test-key
models:
- model-a
mcpServers:
alpha:
url: "%s"
`
for name, raw := range map[string]string{
"mistyped scheme": "htps://mcp.invalid/mcp?api-key=" + reloadTargetMarker,
"unparseable": "https://u:" + reloadTargetMarker + "@mcp.invalid:99x/mcp",
} {
t.Run(name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.yaml")
if err := os.WriteFile(path, []byte(strings.Replace(tmpl, "%s", raw, 1)), 0o600); err != nil {
t.Fatal(err)
}
log := newLogger("error")
build := gatewayBuilder(context.Background(), path, "test", log)
sw := &swapHandler{}
sw.cur.Store(newGeneration(okHandler(), func() {}))
r := newReloader(path, []byte("previous"), build, sw, time.Hour, log)
t.Cleanup(sw.closeCurrent)
out := captureStderr(t, func() { r.check(false) })
if !strings.Contains(out, "rejected") {
t.Fatalf("precondition: no rejection logged: %q", out)
}
if strings.Contains(out, reloadTargetMarker) {
t.Errorf("rejection log carries the target credential: %q", out)
}
})
}
}
+24 -5
View File
@@ -66,21 +66,26 @@ func TestGenerationLifecycle(t *testing.T) {
}
}
func TestGenerationDrainTimeoutForcesClose(t *testing.T) {
func TestGenerationDrainTimeoutKeepsGatewayOpen(t *testing.T) {
var closes atomic.Int32
g := countingGen(okHandler(), &closes)
var warned atomic.Int32
g.overdue = func(int64) { warned.Add(1) }
g.enter()
g.retire(20 * time.Millisecond)
deadline := time.Now().Add(2 * time.Second)
for closes.Load() == 0 && time.Now().Before(deadline) {
for warned.Load() == 0 && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if closes.Load() != 1 {
t.Fatalf("closes = %d after the drain timeout, want 1", closes.Load())
if warned.Load() == 0 {
t.Fatal("no warning after the drain timeout")
}
if closes.Load() != 0 {
t.Fatalf("closes = %d after the drain timeout, want 0", closes.Load())
}
g.leave()
if closes.Load() != 1 {
t.Errorf("a leave after the forced close closed again: %d", closes.Load())
t.Errorf("closes = %d after the last leave, want 1", closes.Load())
}
}
@@ -186,6 +191,20 @@ func TestCloseCurrentTurnsAwayLaterRequests(t *testing.T) {
if g.enter() {
t.Error("enter after closeCurrent must return false")
}
rec := httptest.NewRecorder()
served := make(chan struct{})
go func() {
defer close(served)
sw.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
}()
select {
case <-served:
case <-time.After(2 * time.Second):
t.Fatal("ServeHTTP did not return after closeCurrent")
}
if rec.Code != http.StatusServiceUnavailable {
t.Errorf("status = %d, want 503", rec.Code)
}
}
func TestShutStopsDrainTimer(t *testing.T) {
+121
View File
@@ -0,0 +1,121 @@
package main
import (
"io"
"net/http"
"os"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/lukaszraczylo/oss-telemetry"
)
// captureTelemetryStderr returns what fn writes to os.Stderr.
func captureTelemetryStderr(t *testing.T, fn func()) string {
t.Helper()
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
old := os.Stderr
os.Stderr = w
fn()
os.Stderr = old
_ = w.Close()
b, err := io.ReadAll(r)
if err != nil {
t.Fatal(err)
}
return string(b)
}
// setOptOutEnv clears every opt-out variable, then applies set.
func setOptOutEnv(t *testing.T, set map[string]string) {
t.Helper()
for _, k := range telemetryOptOutVars {
t.Setenv(k, "")
}
for k, v := range set {
t.Setenv(k, v)
}
}
func TestLogTelemetryOptOut_NonTruthyValuesAreNotReportedAsOptedOut(t *testing.T) {
for _, v := range []string{"y", "enabled", "0", "false", "disabled", "t"} {
t.Run(v, func(t *testing.T) {
setOptOutEnv(t, map[string]string{"DO_NOT_TRACK": v})
out := captureTelemetryStderr(t, func() { logTelemetryOptOut(newLogger("info")) })
if strings.Contains(out, "opted out via") {
t.Errorf("value %q reported as an opt-out: %s", v, out)
}
if !strings.Contains(out, "not a recognised opt-out value") {
t.Errorf("value %q got no warning: %s", v, out)
}
if !strings.Contains(out, "not opted out") {
t.Errorf("value %q: missing the not-opted-out line: %s", v, out)
}
})
}
}
func TestLogTelemetryOptOut_SkipsNonTruthyVariableToFindTruthyOne(t *testing.T) {
setOptOutEnv(t, map[string]string{"DO_NOT_TRACK": "0", "OSS_TELEMETRY_DISABLED": "1"})
out := captureTelemetryStderr(t, func() { logTelemetryOptOut(newLogger("info")) })
if !strings.Contains(out, "opted out via OSS_TELEMETRY_DISABLED=1") {
t.Errorf("the truthy variable was not reported: %s", out)
}
if strings.Contains(out, "DO_NOT_TRACK=0") {
t.Errorf("a non-truthy variable was reported: %s", out)
}
}
func TestLogTelemetryOptOut_TruthyValues(t *testing.T) {
for _, v := range []string{"1", "true", "yes", "on", " TRUE ", "On"} {
t.Run(v, func(t *testing.T) {
setOptOutEnv(t, map[string]string{"TRAEFIK_LLMGATEWAY_DISABLE_TELEMETRY": v})
out := captureTelemetryStderr(t, func() { logTelemetryOptOut(newLogger("info")) })
if !strings.Contains(out, "opted out via TRAEFIK_LLMGATEWAY_DISABLE_TELEMETRY=") {
t.Errorf("value %q not reported as an opt-out: %s", v, out)
}
})
}
}
func TestLogTelemetryOptOut_UnsetIsSilentAboutValues(t *testing.T) {
setOptOutEnv(t, nil)
out := captureTelemetryStderr(t, func() { logTelemetryOptOut(newLogger("info")) })
if strings.Contains(out, "WARN") || strings.Contains(out, "opted out via") {
t.Errorf("unset environment produced an opt-out or a warning: %s", out)
}
}
type recordingTransport struct{ n atomic.Int32 }
func (r *recordingTransport) RoundTrip(*http.Request) (*http.Response, error) {
r.n.Add(1)
return &http.Response{StatusCode: http.StatusNoContent, Body: http.NoBody}, nil
}
// TestTelemetryPredicateMatchesVendoredClient drives the real client over a recording transport, so no ping leaves
// the machine, and checks that the log's opt-out decision equals whether the client sent nothing.
func TestTelemetryPredicateMatchesVendoredClient(t *testing.T) {
rt := &recordingTransport{}
old := http.DefaultTransport
http.DefaultTransport = rt
t.Cleanup(func() { http.DefaultTransport = old })
for _, v := range []string{"1", "true", "yes", "on", " Yes ", "TRUE", "0", "false", "y", "t", "enabled", "disabled", "off", "2"} {
for _, k := range telemetryOptOutVars {
setOptOutEnv(t, map[string]string{k: v})
before := rt.n.Load()
telemetry.Send("traefik-llmgateway", "1.0.0")
telemetry.Wait(2 * time.Second)
sent := rt.n.Load() != before
if got := !telemetryTruthy(v); sent != got {
t.Errorf("%s=%q: client sent=%v, predicate says it sends=%v", k, v, sent, got)
}
}
}
}