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)) +}