mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-12-06 11:03:52 +00:00
feat(auth): add users.anonymousAcceptAnyKey for clients that need a key
The OpenAI SDKs refuse to start without an API key, so keyless callers set a placeholder key. With users.anonymousGroup alone, that placeholder gets 401. Set users.anonymousAcceptAnyKey to true to serve a key that matches no user as "anonymous". A configured user's key still resolves to that user. A placeholder key does not count toward the auth-failure throttle. The admin API and the metrics key fallback still use identifyKeyed, so they still need a valid key. The option is false by default, and it needs users.anonymousGroup.
This commit is contained in:
@@ -738,6 +738,7 @@ taken back.
|
||||
|---|---|---|---|
|
||||
| `file` | `string` | — | Path to a JSON users file, merged over `inline` and hot-reloaded — see [Users file](#users-file-format). |
|
||||
| `anonymousGroup` | `string` | — | Opt-in anonymous access — see [Anonymous access](#anonymous-access). Must name a configured group. |
|
||||
| `anonymousAcceptAnyKey` | `bool` | `false` | Also serve a key that matches no user as `anonymous`. Needs `anonymousGroup`. |
|
||||
| `inline` | `[]UserConfig` | `[]` | Resolved once at plugin construction. |
|
||||
|
||||
#### Anonymous access
|
||||
@@ -766,6 +767,17 @@ users:
|
||||
- The name `anonymous` is reserved while this is set. An inline or file user
|
||||
with that name is a config error.
|
||||
|
||||
Some clients cannot omit the key: the OpenAI SDKs refuse to start without
|
||||
one, so callers set a placeholder. Set `users.anonymousAcceptAnyKey: true`
|
||||
to serve those requests as `anonymous` too:
|
||||
|
||||
- A key that matches a configured user still runs as that user.
|
||||
- Any other key, or a malformed `Authorization` header, runs as
|
||||
`anonymous` and does not count toward the auth-failure throttle.
|
||||
- A user who mistypes a key gets the anonymous group's grant instead of a
|
||||
401.
|
||||
- The admin API and the metrics key fallback still need a valid admin key.
|
||||
|
||||
Anyone who can reach the gateway can spend the providers this group allows.
|
||||
Set group `limits` and `memberLimits`, and restrict who can reach the route
|
||||
at the proxy.
|
||||
|
||||
@@ -173,3 +173,94 @@ func TestGateway_AnonymousModeOffKeepsKeyRequired(t *testing.T) {
|
||||
t.Fatalf("status %d, want 401", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentify_AnonymousAcceptAnyKey(t *testing.T) {
|
||||
cfg := anonAuthCfg()
|
||||
cfg.Users.AnonymousAcceptAnyKey = true
|
||||
a, err := newAuthStore(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tests := []struct {
|
||||
headers map[string]string
|
||||
name string
|
||||
wantUser string
|
||||
wantGroup string
|
||||
}{
|
||||
{name: "no credentials", wantUser: anonymousUserName, wantGroup: "public"},
|
||||
{name: "valid bearer", headers: map[string]string{"Authorization": "Bearer sk-secret"}, wantUser: "a", wantGroup: "eng"},
|
||||
{name: "valid x-api-key", headers: map[string]string{"x-api-key": "sk-secret"}, wantUser: "a", wantGroup: "eng"},
|
||||
{name: "dummy bearer", headers: map[string]string{"Authorization": "Bearer sk-dummy"}, wantUser: anonymousUserName, wantGroup: "public"},
|
||||
{name: "dummy x-api-key", headers: map[string]string{"x-api-key": "sk-dummy"}, wantUser: anonymousUserName, wantGroup: "public"},
|
||||
{name: "non-bearer scheme", headers: map[string]string{"Authorization": "Basic dXNlcjpwYXNz"}, wantUser: anonymousUserName, wantGroup: "public"},
|
||||
{name: "empty bearer", headers: map[string]string{"Authorization": "Bearer "}, wantUser: anonymousUserName, wantGroup: "public"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
r := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
||||
for k, v := range tc.headers {
|
||||
r.Header.Set(k, v)
|
||||
}
|
||||
u, grp, ok := a.identify(r)
|
||||
if !ok {
|
||||
t.Fatal("want a principal")
|
||||
}
|
||||
if u.name != tc.wantUser || grp.name != tc.wantGroup {
|
||||
t.Fatalf("got user %q group %q, want %q %q", u.name, grp.name, tc.wantUser, tc.wantGroup)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentify_AnonymousAcceptAnyKeyRecordsNoFailures(t *testing.T) {
|
||||
cfg := anonAuthCfg()
|
||||
cfg.Users.AnonymousAcceptAnyKey = true
|
||||
a, err := newAuthStore(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
||||
r.Header.Set("Authorization", "Bearer sk-dummy")
|
||||
for range authFailureLimit + 1 {
|
||||
a.identify(r)
|
||||
}
|
||||
if a.authThrottled(clientIP(r)) {
|
||||
t.Fatal("a dummy key admitted as anonymous must not count as an auth failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewAuthStore_AnonymousAcceptAnyKeyNeedsGroup(t *testing.T) {
|
||||
cfg := anonAuthCfg()
|
||||
cfg.Users.AnonymousGroup = ""
|
||||
cfg.Users.AnonymousAcceptAnyKey = true
|
||||
_, err := newAuthStore(cfg)
|
||||
if err == nil || !strings.Contains(err.Error(), "anonymousAcceptAnyKey needs users.anonymousGroup") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateway_AnonymousAcceptAnyKey(t *testing.T) {
|
||||
cfg := newAdminTestConfig()
|
||||
cfg.Groups["public"] = &GroupConfig{Models: []string{"a-model-1"}}
|
||||
cfg.Users.AnonymousGroup = "public"
|
||||
cfg.Users.AnonymousAcceptAnyKey = true
|
||||
cfg.Metrics = &MetricsConfig{Enabled: true}
|
||||
h, _ := newAdminGatewayHandle(t, cfg)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, adminRequest(http.MethodGet, "/v1/models", "sk-dummy"))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("/v1/models with a dummy key: status %d, body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if body := rec.Body.String(); !strings.Contains(body, "a-model-1") || strings.Contains(body, "z-model") {
|
||||
t.Fatalf("/v1/models must list only the anonymous group's models: %s", body)
|
||||
}
|
||||
|
||||
for _, p := range []string{adminOverviewPath, adminUsagePath, adminTargetsPath, metricsPath(cfg)} {
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, adminRequest(http.MethodGet, p, "sk-dummy"))
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("%s with a dummy key: status %d, want 401", p, rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -731,7 +731,9 @@ type authStore struct {
|
||||
inline map[[32]byte]*authEntry
|
||||
// anonymous is the principal for keyless requests; nil unless
|
||||
// UsersConfig.AnonymousGroup is set.
|
||||
anonymous *authEntry
|
||||
anonymous *authEntry
|
||||
// anonymousAnyKey admits an unknown key as anonymous instead of 401.
|
||||
anonymousAnyKey bool
|
||||
lastReloadErrMsg string
|
||||
failureLog logGate
|
||||
throttleLog logGate
|
||||
@@ -811,6 +813,9 @@ func newAuthStore(cfg *Config) (*authStore, error) {
|
||||
return nil, err
|
||||
}
|
||||
a.anonymous = anon
|
||||
a.anonymousAnyKey = cfg.Users.AnonymousAcceptAnyKey
|
||||
} else if cfg.Users != nil && cfg.Users.AnonymousAcceptAnyKey {
|
||||
return nil, fmt.Errorf("llmgateway: users.anonymousAcceptAnyKey needs users.anonymousGroup")
|
||||
}
|
||||
|
||||
if cfg.Users != nil {
|
||||
@@ -1276,29 +1281,45 @@ func (a *authStore) shouldLogThrottleEngaged() (log bool, suppressed int64) {
|
||||
// — there is no separate secret-bytes compare here for a non-constant-time
|
||||
// implementation to leak timing from).
|
||||
func (a *authStore) identify(r *http.Request) (*user, *group, bool) {
|
||||
if a.anonymous != nil && !hasCredentialHeader(r.Header) {
|
||||
if a.anonymous == nil {
|
||||
return a.identifyKeyed(r)
|
||||
}
|
||||
if !hasCredentialHeader(r.Header) {
|
||||
return a.anonymous.user, a.anonymous.group, true
|
||||
}
|
||||
return a.identifyKeyed(r)
|
||||
if !a.anonymousAnyKey {
|
||||
return a.identifyKeyed(r)
|
||||
}
|
||||
if entry, ok := a.lookupKey(r); ok {
|
||||
return entry.user, entry.group, true
|
||||
}
|
||||
return a.anonymous.user, a.anonymous.group, true
|
||||
}
|
||||
|
||||
// identifyKeyed is identify without the anonymous fallback: the request
|
||||
// must present a configured user's key. The admin API uses it.
|
||||
func (a *authStore) identifyKeyed(r *http.Request) (*user, *group, bool) {
|
||||
key, ok := presentedKey(r)
|
||||
if ok {
|
||||
digest := sha256.Sum256([]byte(key))
|
||||
a.mu.RLock()
|
||||
entry, found := a.byDigest[digest]
|
||||
a.mu.RUnlock()
|
||||
if found {
|
||||
return entry.user, entry.group, true
|
||||
}
|
||||
if entry, ok := a.lookupKey(r); ok {
|
||||
return entry.user, entry.group, true
|
||||
}
|
||||
a.recordAuthFailure(clientIP(r))
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
// lookupKey resolves r's presented key to a configured user. A miss records
|
||||
// no auth failure; the caller decides whether it is one.
|
||||
func (a *authStore) lookupKey(r *http.Request) (*authEntry, bool) {
|
||||
key, ok := presentedKey(r)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
digest := sha256.Sum256([]byte(key))
|
||||
a.mu.RLock()
|
||||
entry, found := a.byDigest[digest]
|
||||
a.mu.RUnlock()
|
||||
return entry, found
|
||||
}
|
||||
|
||||
// hasCredentialHeader reports whether h carries an Authorization or
|
||||
// x-api-key header at all. Any such header, even a malformed or empty one,
|
||||
// opts the request out of anonymous access, so a bad credential still
|
||||
|
||||
@@ -370,6 +370,9 @@ type UsersConfig struct {
|
||||
// key. Empty (the default) requires a key on every route.
|
||||
AnonymousGroup string `json:"anonymousGroup,omitempty"`
|
||||
Inline []*UserConfig `json:"inline,omitempty"`
|
||||
// AnonymousAcceptAnyKey also serves a key that matches no user as
|
||||
// "anonymous", for clients that cannot omit the key. Needs AnonymousGroup.
|
||||
AnonymousAcceptAnyKey bool `json:"anonymousAcceptAnyKey,omitempty"`
|
||||
}
|
||||
|
||||
// UserConfig describes one API-key holder.
|
||||
|
||||
Reference in New Issue
Block a user