feat(auth): add opt-in anonymous access with users.anonymousGroup (#15)

Set users.anonymousGroup to a configured group to serve requests that
carry no credential as the reserved user "anonymous" in that group. The
group grant applies, and the group memberLimits are the per-user limits
that all keyless callers share.

A request that sends an Authorization or x-api-key header must carry a
valid key, so a wrong or malformed credential still gets 401. The admin
API and the metrics key fallback use identifyKeyed and never admit the
anonymous user. The name "anonymous" is reserved while the option is
set. The option is empty by default, and then every route needs a key as
before.

The .traefik.yml testData now enables anonymous access, and yaegi-check
exercises it under the interpreter.
This commit is contained in:
2026-11-26 23:54:17 +00:00
committed by GitHub
parent 04600a7bc9
commit df1ca8cde2
9 changed files with 309 additions and 17 deletions
+6
View File
@@ -33,7 +33,13 @@ testData:
groups:
default:
providers: []
# Keyless callers, see README.md#anonymous-access.
public:
models: [gpt-test]
memberLimits:
requestsPerMinute: 10
users:
anonymousGroup: public
inline:
- name: tester
group: default
+31
View File
@@ -737,8 +737,39 @@ taken back.
| Field | Type | Default | Semantics |
|---|---|---|---|
| `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. |
| `inline` | `[]UserConfig` | `[]` | Resolved once at plugin construction. |
#### Anonymous access
By default every route except `GET /admin` needs a configured user's key.
Set `users.anonymousGroup` to serve requests that carry **no** credential
as the reserved user `anonymous` in that group:
```yaml
groups:
public:
models: ["gpt-5-mini"]
limits: { requestsPerDay: 5000 }
memberLimits: { requestsPerMinute: 30 }
users:
anonymousGroup: public
```
- A request with no `Authorization` and no `x-api-key` header runs as
`anonymous`. Every keyless caller shares that one principal: the group's
grant applies, and the group's `memberLimits` are its per-user limits.
- A request that sends either header, even an empty or non-Bearer one, must
carry a valid key. A wrong key still gets 401.
- Keyed users work as before.
- The admin API (`/admin/api/*`) and the metrics key fallback (outside `metrics.allowedCIDRs`) always need an admin key.
- The name `anonymous` is reserved while this is set. An inline or file user
with that name is a config error.
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.
### `UserConfig`
| Field | Type | Default | Semantics |
+1 -1
View File
@@ -134,7 +134,7 @@ func (g *Gateway) handleAdmin(sw *statusTrackingWriter, r *http.Request) {
// holder polling the dashboard aggressively is a self-inflicted, not a
// shared, resource cost.
func (g *Gateway) handleAdminAPI(sw *statusTrackingWriter, r *http.Request) {
u, _, ok := g.auth.identify(r)
u, _, ok := g.auth.identifyKeyed(r)
g.logAuthEvent(ok, authEventUserName(u), r)
if !ok {
writeOAIError(sw, http.StatusUnauthorized, "authentication_error", "invalid or missing API key")
+1 -1
View File
@@ -9,7 +9,7 @@ import (
// nonSecretConfigKeys lists every string-valued JSON key in Config reviewed as
// non-secret. A new key must be classified here or in the redaction sets.
var nonSecretConfigKeys = map[string]bool{
"agents": true, "promptCache": true, "inject": true, "key": true, "allowedCIDRs": true, "backoff": true, "cacheTTL": true, "maxDelay": true,
"agents": true, "anonymousGroup": true, "promptCache": true, "inject": true, "key": true, "allowedCIDRs": true, "backoff": true, "cacheTTL": true, "maxDelay": true,
"card": true, "discoveryInterval": true, "file": true, "group": true,
"groups": true, "maxOpenDuration": true, "mcpServers": true,
"kinds": true, "limitExemptKinds": true, "metadataPath": true, "modelAliases": true, "modelBaseUrls": true, "models": true, "name": true,
+175
View File
@@ -0,0 +1,175 @@
package traefikllmgateway
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func anonAuthCfg() *Config {
return &Config{
Providers: map[string]*ProviderConfig{"openai": {Type: "openai", APIKey: "k"}},
Groups: map[string]*GroupConfig{
"eng": {},
"public": {Models: []string{"gpt-5-mini"}, MemberLimits: &LimitsConfig{RequestsPerMinute: 7}},
},
Users: &UsersConfig{
AnonymousGroup: "public",
Inline: []*UserConfig{{Name: "a", Group: "eng", APIKey: "sk-secret"}},
},
}
}
func TestIdentify_AnonymousMode(t *testing.T) {
a, err := newAuthStore(anonAuthCfg())
if err != nil {
t.Fatal(err)
}
tests := []struct {
headers map[string]string
name string
wantUser string
wantGroup string
wantOK bool
}{
{name: "no credentials", wantOK: true, wantUser: anonymousUserName, wantGroup: "public"},
{name: "valid bearer", headers: map[string]string{"Authorization": "Bearer sk-secret"}, wantOK: true, wantUser: "a", wantGroup: "eng"},
{name: "valid x-api-key", headers: map[string]string{"x-api-key": "sk-secret"}, wantOK: true, wantUser: "a", wantGroup: "eng"},
{name: "wrong bearer", headers: map[string]string{"Authorization": "Bearer sk-wrong"}},
{name: "wrong x-api-key", headers: map[string]string{"x-api-key": "sk-wrong"}},
{name: "non-bearer scheme", headers: map[string]string{"Authorization": "Basic dXNlcjpwYXNz"}},
{name: "empty bearer", headers: map[string]string{"Authorization": "Bearer "}},
{name: "blank x-api-key", headers: map[string]string{"x-api-key": " "}},
}
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 != tc.wantOK {
t.Fatalf("ok = %v, want %v", ok, tc.wantOK)
}
if !ok {
return
}
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_AnonymousPrincipalCarriesGroupGrantAndLimits(t *testing.T) {
a, err := newAuthStore(anonAuthCfg())
if err != nil {
t.Fatal(err)
}
u, grp, ok := a.identify(httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil))
if !ok {
t.Fatal("want anonymous principal")
}
if u.admin {
t.Fatal("anonymous principal must never be admin")
}
if u.limits == nil || u.limits.RequestsPerMinute != 7 {
t.Fatalf("limits = %+v, want the group's memberLimits (RequestsPerMinute 7)", u.limits)
}
if !grp.allowsProviderModel("openai", "gpt-5-mini") || grp.allowsProviderModel("openai", "gpt-5") {
t.Fatal("anonymous principal must carry exactly the public group's grant")
}
}
func TestIdentifyKeyed_NeverAnonymous(t *testing.T) {
a, err := newAuthStore(anonAuthCfg())
if err != nil {
t.Fatal(err)
}
if _, _, ok := a.identifyKeyed(httptest.NewRequest(http.MethodGet, adminOverviewPath, nil)); ok {
t.Fatal("identifyKeyed must not admit a keyless request")
}
r := httptest.NewRequest(http.MethodGet, adminOverviewPath, nil)
r.Header.Set("Authorization", "Bearer sk-secret")
if u, _, ok := a.identifyKeyed(r); !ok || u.name != "a" {
t.Fatalf("identifyKeyed with a valid key: user %v ok %v", u, ok)
}
}
func TestNewAuthStore_AnonymousGroupValidation(t *testing.T) {
t.Run("unknown group", func(t *testing.T) {
cfg := anonAuthCfg()
cfg.Users.AnonymousGroup = "nope"
_, err := newAuthStore(cfg)
if err == nil || !strings.Contains(err.Error(), `anonymousGroup references unknown group "nope"`) {
t.Fatalf("err = %v", err)
}
})
t.Run("inline user named anonymous", func(t *testing.T) {
cfg := anonAuthCfg()
cfg.Users.Inline = append(cfg.Users.Inline, &UserConfig{Name: anonymousUserName, Group: "eng", APIKey: "sk-other"})
_, err := newAuthStore(cfg)
if err == nil || !strings.Contains(err.Error(), "reserved") {
t.Fatalf("err = %v", err)
}
})
t.Run("name allowed when mode off", func(t *testing.T) {
cfg := anonAuthCfg()
cfg.Users.AnonymousGroup = ""
cfg.Users.Inline = append(cfg.Users.Inline, &UserConfig{Name: anonymousUserName, Group: "eng", APIKey: "sk-other"})
if _, err := newAuthStore(cfg); err != nil {
t.Fatalf("err = %v", err)
}
})
t.Run("file user named anonymous", func(t *testing.T) {
a, err := newAuthStore(anonAuthCfg())
if err != nil {
t.Fatal(err)
}
err = a.replaceFileUsers([]*UserConfig{{Name: anonymousUserName, Group: "eng", APIKey: "sk-file"}})
if err == nil || !strings.Contains(err.Error(), "reserved") {
t.Fatalf("err = %v", err)
}
})
}
func TestGateway_AnonymousMode(t *testing.T) {
cfg := newAdminTestConfig()
cfg.Groups["public"] = &GroupConfig{Models: []string{"a-model-1"}}
cfg.Users.AnonymousGroup = "public"
cfg.Metrics = &MetricsConfig{Enabled: true}
h, _ := newAdminGatewayHandle(t, cfg)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, adminRequest(http.MethodGet, "/v1/models", ""))
if rec.Code != http.StatusOK {
t.Fatalf("/v1/models without a 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)
}
rec = httptest.NewRecorder()
h.ServeHTTP(rec, adminRequest(http.MethodGet, "/v1/models", "sk-wrong"))
if rec.Code != http.StatusUnauthorized {
t.Fatalf("/v1/models with a wrong key: status %d, want 401", rec.Code)
}
for _, p := range []string{adminOverviewPath, adminUsagePath, adminTargetsPath, metricsPath(cfg)} {
rec = httptest.NewRecorder()
h.ServeHTTP(rec, adminRequest(http.MethodGet, p, ""))
if rec.Code != http.StatusUnauthorized {
t.Fatalf("%s without a key: status %d, want 401", p, rec.Code)
}
}
}
func TestGateway_AnonymousModeOffKeepsKeyRequired(t *testing.T) {
h, _ := newAdminGatewayHandle(t, newAdminTestConfig())
rec := httptest.NewRecorder()
h.ServeHTTP(rec, adminRequest(http.MethodGet, "/v1/models", ""))
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status %d, want 401", rec.Code)
}
}
+63 -7
View File
@@ -729,13 +729,16 @@ type authStore struct {
groups map[string]*group
byDigest map[[32]byte]*authEntry
inline map[[32]byte]*authEntry
lastReloadErrMsg string
failureLog logGate
throttleLog logGate
fileUserCount int
mu sync.RWMutex
buildMu sync.Mutex
reloadMu sync.Mutex
// anonymous is the principal for keyless requests; nil unless
// UsersConfig.AnonymousGroup is set.
anonymous *authEntry
lastReloadErrMsg string
failureLog logGate
throttleLog logGate
fileUserCount int
mu sync.RWMutex
buildMu sync.Mutex
reloadMu sync.Mutex
}
// newAuthStore builds an authStore from cfg's groups and inline users. It
@@ -802,6 +805,14 @@ func newAuthStore(cfg *Config) (*authStore, error) {
}
}
if cfg.Users != nil && cfg.Users.AnonymousGroup != "" {
anon, err := a.anonymousEntry(cfg.Users.AnonymousGroup)
if err != nil {
return nil, err
}
a.anonymous = anon
}
if cfg.Users != nil {
// seenNames rejects two INLINE users sharing the same name
// (security audit finding 5, 2026-08-22) — scoped to inline only,
@@ -1004,6 +1015,9 @@ func (a *authStore) buildEntry(uc *UserConfig) (*authEntry, error) {
if uc.Name == "" {
return nil, fmt.Errorf("llmgateway: user config entry must have a non-empty name")
}
if a.anonymous != nil && uc.Name == anonymousUserName {
return nil, fmt.Errorf("llmgateway: user name %q is reserved while users.anonymousGroup is set", uc.Name)
}
groupNames := effectiveGroupNames(uc.Group, uc.Groups)
if len(groupNames) == 0 {
return nil, fmt.Errorf("llmgateway: user %q must belong to at least one group", uc.Name)
@@ -1262,6 +1276,15 @@ 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) {
return a.anonymous.user, a.anonymous.group, true
}
return a.identifyKeyed(r)
}
// 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))
@@ -1276,6 +1299,39 @@ func (a *authStore) identify(r *http.Request) (*user, *group, bool) {
return nil, nil, false
}
// 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
// gets a 401 instead of silently running as "anonymous".
func hasCredentialHeader(h http.Header) bool {
return len(h.Values("Authorization")) > 0 || len(h.Values("x-api-key")) > 0
}
// anonymousUserName is the reserved name of the anonymous principal.
const anonymousUserName = "anonymous"
// anonymousEntry builds the anonymous principal: a member of groupName
// with that group's memberLimits as its per-user limits. It has no
// digest, so no presented key can ever resolve to it.
func (a *authStore) anonymousEntry(groupName string) (*authEntry, error) {
grp, ok := a.groups[groupName]
if !ok {
return nil, fmt.Errorf("llmgateway: users.anonymousGroup references unknown group %q", groupName)
}
members := []*group{grp}
limits, sources := effectiveUserLimits(nil, members)
return &authEntry{
user: &user{
limits: limits,
limitSources: sources,
groupNames: []string{groupName},
name: anonymousUserName,
groupName: groupName,
},
group: effectiveGroup(members, nil),
}, nil
}
// presentedKey extracts the API key from r's Authorization Bearer header or
// its x-api-key header. Bearer takes priority when both are set.
func presentedKey(r *http.Request) (string, bool) {
+7 -2
View File
@@ -363,8 +363,13 @@ type PacingConfig struct {
// UsersConfig combines inline users with an optional file-backed source.
type UsersConfig struct {
File string `json:"file,omitempty"`
Inline []*UserConfig `json:"inline,omitempty"`
File string `json:"file,omitempty"`
// AnonymousGroup, when set, serves requests that carry no API key as
// the reserved user "anonymous" in this group. A presented key that
// matches no user is still rejected, and the admin API always needs a
// key. Empty (the default) requires a key on every route.
AnonymousGroup string `json:"anonymousGroup,omitempty"`
Inline []*UserConfig `json:"inline,omitempty"`
}
// UserConfig describes one API-key holder.
+1 -1
View File
@@ -130,7 +130,7 @@ func (g *Gateway) handleMetrics(sw *statusTrackingWriter, r *http.Request) {
g.serveMetrics(sw)
return
}
u, _, ok := g.auth.identify(r)
u, _, ok := g.auth.identifyKeyed(r)
g.logAuthEvent(ok, authEventUserName(u), r)
if !ok {
writeOAIError(sw, http.StatusUnauthorized, "authentication_error", "invalid or missing API key")
+24 -5
View File
@@ -2140,12 +2140,31 @@ func exerciseHandler(handler http.Handler, builtinContextTokens int, failoverBHi
return err
}
unauthedReq := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
unauthedRec := httptest.NewRecorder()
handler.ServeHTTP(unauthedRec, unauthedReq)
if unauthedRec.Code != http.StatusUnauthorized {
return fmt.Errorf("GET /v1/models without a key: status = %d, want 401, body=%s", unauthedRec.Code, unauthedRec.Body.String())
return exerciseAnonymousAccess(handler)
}
// exerciseAnonymousAccess drives testData's users.anonymousGroup ("public",
// models [gpt-test]) under Yaegi: a keyless request is served with only that
// group's models, and a bad or malformed credential is still rejected.
func exerciseAnonymousAccess(handler http.Handler) error {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/v1/models", nil))
if rec.Code != http.StatusOK {
return fmt.Errorf("GET /v1/models without a key: status = %d, want 200 (anonymous), body=%s", rec.Code, rec.Body.String())
}
if body := rec.Body.String(); !strings.Contains(body, `"`+testDataWantModel+`"`) || strings.Contains(body, "gpt-test-large") {
return fmt.Errorf("GET /v1/models without a key: want only the anonymous group's models, body=%s", body)
}
for _, authz := range []string{"Bearer wrong-key", "Basic dXNlcjpwYXNz"} {
req := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
req.Header.Set("Authorization", authz)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
return fmt.Errorf("GET /v1/models with Authorization %q: status = %d, want 401", strings.Fields(authz)[0], rec.Code)
}
}
fmt.Println("yaegi-check: anonymous access served keyless /v1/models and rejected bad credentials, interpreted")
return nil
}