mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-12-06 11:03:52 +00:00
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:
@@ -0,0 +1,51 @@
|
||||
// This file checks that withConfiguredURL keeps the attempt recorder reachable under Yaegi. Context keys of equal
|
||||
// size match each other in the interpreter, so a lost recorder would silently stop provider accounting.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
)
|
||||
|
||||
const cuProbeOK = "ok"
|
||||
|
||||
const cuProbeSource = `
|
||||
func configuredURLKeyProbe() string {
|
||||
r, err := http.NewRequest("GET", "http://h.invalid/", nil)
|
||||
if err != nil {
|
||||
return "request: " + err.Error()
|
||||
}
|
||||
called := false
|
||||
ctx := PKG.withAttemptRecorder(r.Context(), func(resp *http.Response, err error) { called = true })
|
||||
r = PKG.withConfiguredURL(r.WithContext(ctx), "http://h.invalid/v1")
|
||||
rec := PKG.attemptRecorderFromContext(r.Context())
|
||||
if rec == nil {
|
||||
return "attempt recorder lost after withConfiguredURL"
|
||||
}
|
||||
rec(nil, nil)
|
||||
if !called {
|
||||
return "attempt recorder did not fire"
|
||||
}
|
||||
return "ok"
|
||||
}`
|
||||
|
||||
// exerciseConfiguredURLKey wraps a request with withConfiguredURL under the interpreter and checks the attempt recorder still fires.
|
||||
func exerciseConfiguredURLKey(i *interp.Interpreter, pkgName string) error {
|
||||
if _, err := i.Eval(`import "net/http"`); err != nil {
|
||||
return fmt.Errorf("configured url probe: import net/http under yaegi: %w", err)
|
||||
}
|
||||
if _, err := i.Eval(strings.ReplaceAll(cuProbeSource, "PKG", pkgName)); err != nil {
|
||||
return fmt.Errorf("configured url probe: declare the probe under yaegi: %w", err)
|
||||
}
|
||||
v, err := i.Eval("configuredURLKeyProbe()")
|
||||
if err != nil {
|
||||
return fmt.Errorf("configured url probe: run under yaegi: %w", err)
|
||||
}
|
||||
if got := v.String(); got != cuProbeOK {
|
||||
return fmt.Errorf("configured url probe: %s", got)
|
||||
}
|
||||
fmt.Println("yaegi-check: the attempt recorder survived withConfiguredURL under the interpreter")
|
||||
return nil
|
||||
}
|
||||
@@ -1097,6 +1097,16 @@ func run() error {
|
||||
if err := exerciseSharedState(i, pkgName); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := exerciseConfiguredURLKey(i, pkgName); err != nil {
|
||||
return err
|
||||
}
|
||||
// exerciseMessagesCacheUnrewritten runs after every shared-handler
|
||||
// probe: it builds its own Gateway (own upstream, own fake Redis,
|
||||
// cache enabled) and shares no counter or endpoint with any earlier
|
||||
// probe, so it neither perturbs nor is perturbed by them.
|
||||
if err := exerciseMessagesCacheUnrewritten(i, pkgName); err != nil {
|
||||
return err
|
||||
}
|
||||
return exerciseAdminRedesignStats(i, pkgName)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
// This file probes the /v1/messages response-cache rule that a reply
|
||||
// relayed WITHOUT its model field rewritten must never be stored. The
|
||||
// rule travels on the route's own usage value (usage.noStore), not on a
|
||||
// type assertion against the response writer: under Yaegi v0.16.1 such
|
||||
// an assertion never matches an interpreted wrapper type, so the array
|
||||
// reply would be cached and the second identical request answered from
|
||||
// it. A compiled test cannot observe that divergence; only this harness
|
||||
// can.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
)
|
||||
|
||||
const (
|
||||
messagesCacheUserAPIKey = "sk-messages-cache-user" // #nosec G101 -- test fixture literal, not a real credential
|
||||
messagesCacheGroupName = "mcgroup"
|
||||
messagesCacheModel = "claude-cache-probe"
|
||||
messagesCacheArrayBody = `[1,2,3]`
|
||||
)
|
||||
|
||||
// messagesCacheObjectBody is a normal, rewritable Anthropic-shaped reply:
|
||||
// the control case proving the cache still works on the same gateway.
|
||||
const messagesCacheObjectBody = `{"id":"msg_cache_probe","type":"message","role":"assistant","model":"claude-upstream-real","content":[{"type":"text","text":"pong"}],"stop_reason":"end_turn","usage":{"input_tokens":7,"output_tokens":3}}`
|
||||
|
||||
// newMessagesCacheHandler builds one interpreted Gateway with the
|
||||
// response cache enabled against a fake Redis, following
|
||||
// newAdminRedesignHandler's shape (cache.go's buildResponseCache needs a
|
||||
// real Redis client, not just cache.enabled).
|
||||
func newMessagesCacheHandler(i *interp.Interpreter, pkgName, upstreamURL, redisAddr string) (http.Handler, error) {
|
||||
cfgVal, err := i.Eval(pkgName + ".CreateConfig()")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("messages-cache probe: call %s.CreateConfig() under yaegi: %w", pkgName, err)
|
||||
}
|
||||
if !cfgVal.CanInterface() {
|
||||
return nil, fmt.Errorf("messages-cache probe: %s.CreateConfig() result cannot be used via reflect.Value.Interface", pkgName)
|
||||
}
|
||||
|
||||
cfgJSON := `{` +
|
||||
`"providers":{"anthropic":{"type":"anthropic","baseUrl":"` + upstreamURL + `","apiKey":"sk-anth","models":["` + messagesCacheModel + `"]}},` +
|
||||
`"groups":{"` + messagesCacheGroupName + `":{}},` +
|
||||
`"users":{"inline":[{"name":"mc-alice","group":"` + messagesCacheGroupName + `","apiKey":"` + messagesCacheUserAPIKey + `"}]},` +
|
||||
`"redis":{"address":"` + redisAddr + `"},` +
|
||||
`"cache":{"enabled":true,"ttl":"1m"}` +
|
||||
`}`
|
||||
if err = json.Unmarshal([]byte(cfgJSON), cfgVal.Interface()); err != nil {
|
||||
return nil, fmt.Errorf("messages-cache probe: decode its own config into the interpreted Config: %w", err)
|
||||
}
|
||||
|
||||
newVal, err := i.Eval(pkgName + ".New")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("messages-cache probe: resolve %s.New under yaegi: %w", pkgName, err)
|
||||
}
|
||||
if newVal.Kind() != reflect.Func {
|
||||
return nil, fmt.Errorf("messages-cache probe: %s.New is not a function (kind %s)", pkgName, newVal.Kind())
|
||||
}
|
||||
next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})
|
||||
results := newVal.Call([]reflect.Value{
|
||||
reflect.ValueOf(context.Background()),
|
||||
reflect.ValueOf(next),
|
||||
cfgVal,
|
||||
reflect.ValueOf("llmgw-check-messages-cache"),
|
||||
})
|
||||
if len(results) != 2 {
|
||||
return nil, fmt.Errorf("messages-cache probe: %s.New returned %d values, want 2 (http.Handler, error)", pkgName, len(results))
|
||||
}
|
||||
if errVal := results[1]; !errVal.IsNil() {
|
||||
return nil, fmt.Errorf("messages-cache probe: %s.New returned an error: %v", pkgName, errVal.Interface())
|
||||
}
|
||||
handler, ok := results[0].Interface().(http.Handler)
|
||||
if !ok || handler == nil {
|
||||
return nil, fmt.Errorf("messages-cache probe: %s.New's returned value is not a usable http.Handler", pkgName)
|
||||
}
|
||||
return handler, nil
|
||||
}
|
||||
|
||||
// exerciseMessagesCacheUnrewritten sends the same /v1/messages request
|
||||
// twice against a fake upstream that answers with a JSON array, and
|
||||
// fails unless BOTH requests reach the upstream (a cache miss each time).
|
||||
// It then repeats the pair against a normal JSON object reply and fails
|
||||
// unless the second request is a cache hit, so the miss assertion above
|
||||
// cannot pass by the cache being broken outright.
|
||||
func exerciseMessagesCacheUnrewritten(i *interp.Interpreter, pkgName string) error {
|
||||
var arrayHits, objectHits int64
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if strings.Contains(string(raw), "array-probe") {
|
||||
atomic.AddInt64(&arrayHits, 1)
|
||||
_, _ = w.Write([]byte(messagesCacheArrayBody))
|
||||
return
|
||||
}
|
||||
atomic.AddInt64(&objectHits, 1)
|
||||
_, _ = w.Write([]byte(messagesCacheObjectBody))
|
||||
}))
|
||||
defer upstream.Close()
|
||||
|
||||
redisLn, redisErr := newProbeRedisFake()
|
||||
if redisErr != nil {
|
||||
return redisErr
|
||||
}
|
||||
defer func() { _ = redisLn.Close() }()
|
||||
|
||||
handler, handlerErr := newMessagesCacheHandler(i, pkgName, upstream.URL, redisLn.Addr().String())
|
||||
if handlerErr != nil {
|
||||
return handlerErr
|
||||
}
|
||||
|
||||
send := func(marker string) (*httptest.ResponseRecorder, error) {
|
||||
body := `{"model":"` + messagesCacheModel + `","max_tokens":16,"messages":[{"role":"user","content":"` + marker + `"}]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("x-api-key", messagesCacheUserAPIKey)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
return rec, fmt.Errorf("messages-cache probe: POST /v1/messages (%s): status = %d, want 200, body=%s", marker, rec.Code, rec.Body.String())
|
||||
}
|
||||
return rec, nil
|
||||
}
|
||||
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
rec, err := send("array-probe")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rec.Body.String() != messagesCacheArrayBody {
|
||||
return fmt.Errorf("messages-cache probe: array reply %d body = %q, want %q verbatim", attempt, rec.Body.String(), messagesCacheArrayBody)
|
||||
}
|
||||
if got := rec.Header().Get("X-Llmgw-Cache"); got == "hit" {
|
||||
return fmt.Errorf("messages-cache probe: array reply request %d was served from the response cache (X-Llmgw-Cache: hit) — a reply relayed without its model rewrite must never be stored", attempt)
|
||||
}
|
||||
}
|
||||
if got := atomic.LoadInt64(&arrayHits); got != 2 {
|
||||
return fmt.Errorf("messages-cache probe: unrewritten array reply reached the upstream %d times, want 2 (both requests must miss); the interpreted skip-store path did not take effect", got)
|
||||
}
|
||||
|
||||
firstObj, err := send("object-probe")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if got := firstObj.Header().Get("X-Llmgw-Cache"); got != "miss" {
|
||||
return fmt.Errorf("messages-cache probe: first object reply X-Llmgw-Cache = %q, want miss (body=%s)", got, firstObj.Body.String())
|
||||
}
|
||||
secondObj, err := send("object-probe")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if got := secondObj.Header().Get("X-Llmgw-Cache"); got != "hit" {
|
||||
return fmt.Errorf("messages-cache probe: second object reply X-Llmgw-Cache = %q, want hit (a normal rewritable reply must still be cached; body=%s)", got, secondObj.Body.String())
|
||||
}
|
||||
if got := atomic.LoadInt64(&objectHits); got != 1 {
|
||||
return fmt.Errorf("messages-cache probe: object reply reached the upstream %d times, want 1 (the second request must be a cache hit)", got)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user