mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-12-06 11:03:52 +00:00
* fix(admin): list the anonymous user in snapshot views The auth snapshot built users from the key digest map only. The keyless principal never appeared in usage, catalog, metrics or fleet views, and its rejection counter was pruned on a users-file reload. The snapshot now adds the anonymous principal once, with source anonymous. * fix(discovery): keep context lengths when one upstream fails metadata A failing modelBaseUrls upstream dropped its models from the metadata map. The registry replaced the discovered contexts, so those models lost their context length. The failure was also not visible. The adapter now keeps the last good metadata per upstream and reports metadata failures through upstreamErrors. * fix(webui): show provider upstream errors The dashboard ignored upstreamErrors from the admin overview. A provider with a failing modelBaseUrls upstream looked healthy. The provider panel now lists each upstream error, and the breaker rows mark such a provider as degraded. * fix(passthrough): gate and bill passthrough requests by cost budget Refusal text stays under 128 bytes, and only models the provider serves get a per-model counter. When the first 64 KiB does not settle the model, the gate reads the body up to the smaller of maxRequestBytes and the passthrough cap, inside a body-admission slot. It refuses with 402 if the model is missing, repeated, or in a malformed or unterminated object, with 413 if the object does not close within the bound, and with 400 if the body read fails. A priced model after 64 KiB passes and the body reaches the upstream unchanged. A 2xx event stream with no completion usage bills one estimated token per data event. * fix(billing): estimate completion when a stream ends before its usage A streaming unified request that failed after output reached the client recorded zero completion tokens. The gateway now estimates them from the forwarded output bytes and marks the usage as estimated. Streams that report usage, and streams that end cleanly, are unchanged. * fix(cache): key /v1/messages entries on the forwarded anthropic-beta set Two callers that sent different anthropic-beta values shared one cache entry, although the gateway forwards that header upstream. The key now includes the normalised beta set when the header is present. Requests without the header keep their existing key. * docs: state that /v1/messages responses are cached The Caching section named chat and embeddings only. It now names /v1/messages, the beta set in the key, and that entries are shared across users and groups. * fix(passthrough): bill Responses API and Gemini streaming usage shapes Read input_tokens/output_tokens and input_tokens_details.cached_tokens for OpenAI Responses JSON, and response.usage from response.completed SSE events. Decode the Gemini streamGenerateContent JSON array and read usageMetadata from Gemini SSE data events, last one wins. Field names follow the OpenAI Responses API and Gemini GenerateContentResponse references. A truncated array yields no usage. * fix(admin): scrub the re-serialised base URL from provider errors sanitizeProviderErr now also replaces the URL as net/url writes it. A provider baseUrl with userinfo, a query or a fragment logs one construction warning. The config still loads. * fix(proxy): do not relay a redirect that carries a configured target query proxyUpstream answers 502 when an upstream replies with a 3xx Location and the upstream URL holds a query the client did not send. Targets without a configured query still relay redirects. * test(passthrough): rename the client reset reader helper Two packages each declared failingReader in the same test package. The passthrough gate test now uses clientResetReader. * fix(discovery): bound the number and length of discovered model ids A provider keeps at most 10000 discovered ids of at most 256 bytes. The registry drops empty ids, ids with control characters, longer ids and the overflow, and logs the count once per 10 minutes. * fix(mcp): keep the target query when it does not parse mergeQueryStrings now forwards a configured query that ParseQuery rejects, next to the client query, instead of dropping it. * fix(messages): keep tool argument deltas on the open block Blocks that follow an open tool_use block are queued and emitted at stream end, so every delta targets the one open block. * docs: correct failOpen, reload and anonymous access text * chore(webui): regenerate admin assets Rebuilt with make admin-ui for the dashboard changes in this branch.
104 lines
3.0 KiB
Go
104 lines
3.0 KiB
Go
package traefikllmgateway
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func anonSnapshotGateway(t *testing.T, anonGroup string) (http.Handler, *Gateway) {
|
|
t.Helper()
|
|
return memberLimitsGateway(t,
|
|
map[string]*GroupConfig{"friends": {}, "public": {}},
|
|
[]*UserConfig{{Name: "a", Group: "friends", APIKey: "sk-a", Admin: true}},
|
|
func(c *Config) {
|
|
c.Users.AnonymousGroup = anonGroup
|
|
c.Metrics = &MetricsConfig{Enabled: true}
|
|
},
|
|
)
|
|
}
|
|
|
|
func TestSnapshot_IncludesAnonymousPrincipal(t *testing.T) {
|
|
a, err := newAuthStore(anonAuthCfg())
|
|
require.NoError(t, err)
|
|
users, groups := a.snapshot()
|
|
|
|
var anon []userSummary
|
|
for _, u := range users {
|
|
if u.name == anonymousUserName {
|
|
anon = append(anon, u)
|
|
}
|
|
}
|
|
require.Len(t, anon, 1)
|
|
assert.Equal(t, "anonymous", anon[0].source)
|
|
assert.False(t, anon[0].admin)
|
|
assert.Equal(t, "public", anon[0].groupName)
|
|
assert.Equal(t, []string{"public"}, anon[0].groups)
|
|
for _, g := range groups {
|
|
if g.name == "public" {
|
|
assert.Equal(t, 1, g.memberCount)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestSnapshot_NoAnonymousWhenUnset(t *testing.T) {
|
|
cfg := anonAuthCfg()
|
|
cfg.Users.AnonymousGroup = ""
|
|
a, err := newAuthStore(cfg)
|
|
require.NoError(t, err)
|
|
users, _ := a.snapshot()
|
|
for _, u := range users {
|
|
assert.NotEqual(t, anonymousUserName, u.name)
|
|
}
|
|
}
|
|
|
|
func TestAdminUsage_ListsAnonymousUser(t *testing.T) {
|
|
h, gw := anonSnapshotGateway(t, "public")
|
|
rec := memberLimitsChat(t, h, "")
|
|
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
|
|
|
e := findUsageEntry(t, gw.buildAdminUsage().Users, anonymousUserName)
|
|
assert.NotZero(t, e.RequestsPerDay)
|
|
}
|
|
|
|
func TestScopeExists_AnonymousUser(t *testing.T) {
|
|
h, _ := anonSnapshotGateway(t, "public")
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, adminRequest(http.MethodGet, adminUsageHistoryPath+"?scope=user:anonymous&metric=req&window=hour", "sk-a"))
|
|
assert.NotEqual(t, http.StatusNotFound, rec.Code, rec.Body.String())
|
|
}
|
|
|
|
func TestPruneRejectionsAfterReload_KeepsAnonymous(t *testing.T) {
|
|
_, gw := anonSnapshotGateway(t, "public")
|
|
gw.limiter.rejections.increment("user", anonymousUserName)
|
|
gw.pruneRejectionsAfterReload()
|
|
|
|
var kept bool
|
|
for _, s := range gw.limiter.rejections.snapshot() {
|
|
if s.kind == "user" && s.id == anonymousUserName {
|
|
kept = true
|
|
}
|
|
}
|
|
assert.True(t, kept, "anonymous rejection counter must survive a users-file reload")
|
|
}
|
|
|
|
func TestUsageMetrics_ExportAnonymousUser(t *testing.T) {
|
|
h, _ := anonSnapshotGateway(t, "public")
|
|
require.Equal(t, http.StatusOK, memberLimitsChat(t, h, "").Code)
|
|
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, metricsRequest(http.MethodGet, metricsPathDefault, "sk-a"))
|
|
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
|
_, samples := parsePrometheusText(t, rec.Body.Bytes())
|
|
var found bool
|
|
for _, s := range samples {
|
|
if s.name == "llmgateway_requests_total" && s.labels["scope_kind"] == "user" && s.labels["scope_id"] == anonymousUserName {
|
|
found = true
|
|
}
|
|
}
|
|
assert.True(t, found)
|
|
}
|