From 28ccbe38d45ede66616040c2dcdac9816ec3bff7 Mon Sep 17 00:00:00 2001 From: "pulse-triage[bot]" <249995291+pulse-triage[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:40:50 +0000 Subject: [PATCH] Avoid redundant API token scope allocations Use caller-local scratch for the read-only role check and take the canonical scope copy directly in detached snapshots. Preserve the write-time recheck and keep the normalization path shared. Cover accepted and refused role vocabularies, legacy defaults, scratch overflow, ownership and allocation cost. Contract-Neutral: Internal allocation reduction only; digest comparisons, lookup order, expiry and role decisions, durable authority, last-used metadata, detached ownership, wire values and rendered states are unchanged. Change-source: pulse-maintainer --- internal/config/api_token_lookup_test.go | 95 ++++++++++++++++++++++++ internal/config/api_tokens.go | 30 ++++---- 2 files changed, 111 insertions(+), 14 deletions(-) diff --git a/internal/config/api_token_lookup_test.go b/internal/config/api_token_lookup_test.go index 669c918632..50a2c933dd 100644 --- a/internal/config/api_token_lookup_test.go +++ b/internal/config/api_token_lookup_test.go @@ -3,6 +3,7 @@ package config import ( "fmt" "reflect" + "slices" "strings" "testing" "time" @@ -91,6 +92,100 @@ func TestAPITokenInventoryReadOnlyLeavesLegacyMetadataUnchanged(t *testing.T) { } } +func TestAPITokenInventoryScopeNormalizationAgreesAcrossOperations(t *testing.T) { + const raw = "synthetic-token-scope-normalization" + collector := auth.RuntimeRoleMonitoringCollector + paddedReport := "\u2003host-agent:report\t" + configRead := " host-agent:config:read " + wide := append(slices.Repeat([]string{paddedReport}, 8), configRead) + wideUnknown := append(slices.Clone(wide), " unknown:scope ") + + for _, tc := range []struct { + name, role string + scopes []string + canonical []string + allow bool + }{ + {"absent", "", nil, []string{ScopeWildcard}, true}, + {"empty", "", []string{}, []string{ScopeWildcard}, true}, + {"explicit-blank", "", []string{"\t", ""}, []string{""}, true}, + {"alias-order", " " + collector + " ", []string{configRead, paddedReport, ScopeAgentConfigRead}, + []string{ScopeAgentConfigRead, ScopeAgentReport}, true}, + {"collector-missing-required", collector, []string{paddedReport, ScopeAgentReport}, []string{ScopeAgentReport}, false}, + {"collector-no-scopes", collector, nil, []string{ScopeWildcard}, false}, + {"collector-wide", collector, wide, []string{ScopeAgentReport, ScopeAgentConfigRead}, true}, + {"collector-wide-extra", collector, wideUnknown, []string{ScopeAgentReport, ScopeAgentConfigRead, "unknown:scope"}, false}, + {"runner", auth.RuntimeRoleActionRunner, []string{" " + ScopeAgentExec, ScopeAgentExec}, []string{ScopeAgentExec}, true}, + {"runner-wildcard", auth.RuntimeRoleActionRunner, []string{ScopeAgentExec, ScopeWildcard}, []string{ScopeAgentExec, ScopeWildcard}, false}, + {"legacy-full-trust", auth.RuntimeRoleLegacyFullTrust, []string{ScopeAgentExec, ScopeWildcard}, []string{ScopeAgentExec, ScopeWildcard}, true}, + {"unknown-role", "unknown", []string{ScopeAgentExec}, []string{ScopeAgentExec}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := &Config{APITokens: []APITokenRecord{{ + ID: "synthetic-id", Hash: auth.HashAPIToken(raw), OrgID: "client-a", + Scopes: slices.Clone(tc.scopes), Metadata: map[string]string{auth.RuntimeRoleMetadataKey: tc.role}, + }}} + live := &cfg.APITokens[0] + original := *live + original.Scopes = slices.Clone(live.Scopes) + + if got := cfg.IsValidAPIToken(raw); got != tc.allow { + t.Fatalf("read-only decision = %t, want %t", got, tc.allow) + } + snapshot := live.Clone() + if !slices.Equal(snapshot.Scopes, tc.canonical) { + t.Fatalf("snapshot scopes = %q, want %q", snapshot.Scopes, tc.canonical) + } + snapshot.Scopes[0] = "fixture-only" + if !reflect.DeepEqual(*live, original) { + t.Fatal("read-only check or editing the snapshot changed live scopes or metadata") + } + + record, got := cfg.ValidateAPIToken(raw) + if got != tc.allow || (record == live) != tc.allow || (live.LastUsedAt != nil) != tc.allow { + t.Fatalf("write decision = %t, want %t with metadata updated only on acceptance", got, tc.allow) + } + if !slices.Equal(live.Scopes, tc.canonical) { + t.Fatalf("saved runtime scopes = %q, want %q", live.Scopes, tc.canonical) + } + }) + } +} + +func TestAPITokenInventorySmallScopePrecheckNeedsNoExtraAllocation(t *testing.T) { + const raw = "synthetic-auth-precheck-present" + const missing = "synthetic-auth-precheck-missing" + for _, tc := range []struct { + name, role string + scopes []string + }{ + {"wildcard-default", "", nil}, + {"scoped-api", "", []string{ScopeMonitoringRead}}, + {"collector", auth.RuntimeRoleMonitoringCollector, []string{ScopeAgentReport, ScopeAgentConfigRead, ScopeDockerReport, ScopeKubernetesReport}}, + {"eight-legacy-inputs", auth.RuntimeRoleMonitoringCollector, append(slices.Repeat([]string{"host-agent:report"}, 7), " host-agent:config:read ")}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := &Config{APITokens: []APITokenRecord{{ + ID: "synthetic-id", Hash: auth.HashAPIToken(raw), Scopes: tc.scopes, + Metadata: map[string]string{auth.RuntimeRoleMetadataKey: tc.role}, + }}} + measure := func(bearer string, want bool) float64 { + return testing.AllocsPerRun(100, func() { + if cfg.IsValidAPIToken(bearer) != want { + panic("authentication decision changed") + } + }) + } + // Both inputs hash one bearer and check one record. An accepted + // authorisation with a small scope list needs no extra allocation. + miss, hit := measure(missing, false), measure(raw, true) + if hit > miss { + t.Fatalf("accepted precheck allocated %.0f times vs %.0f for a miss", hit, miss) + } + }) + } +} + // Measure the authentication work itself. Inventory construction and credential // hashing for saved records are outside the timed loop; no secrets or providers // are involved. Include cheap first matches as well as late/missing lookups. diff --git a/internal/config/api_tokens.go b/internal/config/api_tokens.go index 7f7f5fa8eb..badaaebef9 100644 --- a/internal/config/api_tokens.go +++ b/internal/config/api_tokens.go @@ -94,11 +94,6 @@ func (r *APITokenRecord) ensureID() { // ensureScopes normalizes stored/runtime scopes, applying defaults and // rewriting any legacy aliases into canonical scope identifiers. func (r *APITokenRecord) ensureScopes() { - if len(r.Scopes) == 0 { - r.Scopes = []string{ScopeWildcard} - return - } - r.Scopes = normalizeScopes(r.Scopes) } @@ -113,7 +108,7 @@ func (r *APITokenRecord) IsExpired() bool { // Clone returns a detached copy of the record's mutable fields. func (r *APITokenRecord) Clone() APITokenRecord { clone := *r - clone.Scopes = append([]string(nil), r.Scopes...) + clone.Scopes = normalizeScopes(r.Scopes) // The canonical result already owns its storage. if r.LastUsedAt != nil { t := *r.LastUsedAt clone.LastUsedAt = &t @@ -122,7 +117,6 @@ func (r *APITokenRecord) Clone() APITokenRecord { t := *r.ExpiresAt clone.ExpiresAt = &t } - clone.ensureScopes() // Deep copy OrgIDs slice if r.OrgIDs != nil { @@ -430,12 +424,11 @@ func (c *Config) IsValidAPIToken(rawToken string) bool { if record.IsExpired() { return false } - record.ensureScopes() + // Admission only reads the normalized values. Keep common scope + // lists in scratch owned by this call, never in the live record. + var scratch [8]string role := strings.TrimSpace(record.Metadata[auth.RuntimeRoleMetadataKey]) - if err := auth.ValidateRoleScopes(role, record.Scopes); err != nil { - return false - } - return true + return auth.ValidateRoleScopes(role, normalizeScopesInto(scratch[:0], record.Scopes)) == nil } } return false @@ -489,11 +482,20 @@ func (c *Config) SortAPITokens() { // normalizeScopes applies defaults and returns a canonical safe copy of the // input slice for persistence and runtime storage. func normalizeScopes(scopes []string) []string { + return normalizeScopesInto(nil, scopes) +} + +// normalizeScopesInto uses caller-owned scratch, which must not overlap scopes. +// Pass nil when the result must have its own storage. +func normalizeScopesInto(scratch, scopes []string) []string { if len(scopes) == 0 { - return []string{ScopeWildcard} + return append(scratch[:0], ScopeWildcard) + } + result := scratch[:0] + if cap(result) < len(scopes) { + result = make([]string, 0, len(scopes)) } seen := make(map[string]struct{}, len(scopes)) - result := make([]string, 0, len(scopes)) for _, scope := range scopes { scope = canonicalizeScopeAlias(scope) if _, exists := seen[scope]; exists {