From 8236329e47379a96fd8808d84e42911c9e77b20a Mon Sep 17 00:00:00 2001 From: "pulse-triage[bot]" <249995291+pulse-triage[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 05:45:17 +0000 Subject: [PATCH 1/4] Parallelize slow internal/api race subtests and speed up fixtures Backend tests (api-0..4) finished last on post-#5350 Pulse Build and Test runs (46109093360, ~1,726 runner-seconds across 5 shards), with the slowest unclaimed internal/api tests executing isolated subtest matrices sequentially, seeding the full default public demo estate where compact mock topologies suffice, or bypassing TestMain's PULSE_TEST_BCRYPT_COST via direct bcrypt.DefaultCost calls. - Parallelize isolated subtest matrices across 14 unclaimed internal/api test files (host_agent_credential_handoff_test.go, agent_snapshot_authority_test.go, resource_read_authority_test.go, token_stream_lifetime_test.go, token_stream_shutdown_test.go, assistant_stream_lifetime_test.go, assistant_json_lifetime_test.go, agent_events_auth_test.go, reporting_boundary_test.go, docker_agents_report_size_test.go, security_setup_fixture_isolation_test.go, websocket_auth_test.go, security_token_withdrawal_test.go, and log_stream_auth_test.go), lifting shared env/session setup out of per-subtest helpers, serializing only the temporary AI alert-analysis binder swap during router construction, and caching read-only source file bytes once in reporting_boundary_test.go. - Use the existing compact 2-node mock integration fixture (newIntegrationServer) for TestStateEndpointReturnsMockData, TestConfigNodesUsesMockTopology, and TestMockModeToggleEndpoint in router_integration_test.go, while preserving newFleetIntegrationServer for multi-page recovery rollup/point tests. - Route four test fixtures (change_password_session_admin_test.go, oidc_only_admin_parity_test.go, platform_admin_session_parity_test.go, and security_status_capability_enforcement_test.go) through pkg/auth.HashPassword so they honor TestMain's PULSE_TEST_BCRYPT_COST instead of bcrypt.DefaultCost. Contract-Neutral: Test-only parallelization and fixture optimization across 19 internal/api test files with zero production code, API behavior, or assertion changes. Change-source: pulse-maintainer --- internal/api/agent_events_auth_test.go | 10 ++++ internal/api/agent_snapshot_authority_test.go | 49 +++++++++++++--- internal/api/assistant_json_lifetime_test.go | 19 ++++--- .../api/assistant_stream_lifetime_test.go | 57 +++++++++++++++---- .../api/change_password_session_admin_test.go | 14 ++--- .../api/docker_agents_report_size_test.go | 8 +++ .../api/host_agent_credential_handoff_test.go | 2 + internal/api/log_stream_auth_test.go | 2 + internal/api/oidc_only_admin_parity_test.go | 7 +-- .../api/platform_admin_session_parity_test.go | 7 +-- internal/api/reporting_boundary_test.go | 52 +++++++++-------- internal/api/resource_read_authority_test.go | 48 +++++++++++++--- internal/api/router_integration_test.go | 6 +- .../security_setup_fixture_isolation_test.go | 2 + ...rity_status_capability_enforcement_test.go | 7 +-- .../api/security_token_withdrawal_test.go | 2 + internal/api/token_stream_lifetime_test.go | 14 ++++- internal/api/token_stream_shutdown_test.go | 8 +++ internal/api/websocket_auth_test.go | 2 + 19 files changed, 235 insertions(+), 81 deletions(-) diff --git a/internal/api/agent_events_auth_test.go b/internal/api/agent_events_auth_test.go index ca002eff9c..adcd82575d 100644 --- a/internal/api/agent_events_auth_test.go +++ b/internal/api/agent_events_auth_test.go @@ -132,7 +132,9 @@ func (w *agentEventRefreshWriter) Flush() { // of WithValue's context to prove it cannot retain earlier refresh snapshots. func TestAgentEventTokenRefreshKeepsBoundedContext(t *testing.T) { for _, transport := range []string{"header", "bearer"} { + transport := transport t.Run(transport, func(t *testing.T) { + t.Parallel() const orgID = "refresh-tenant" token := newTokenRecord(t, agentEventLifecycleToken, []string{config.ScopeMonitoringRead, config.ScopeAIExecute}, nil) token.OrgID = orgID @@ -253,7 +255,9 @@ func TestAgentEventTokenRefreshKeepsBoundedContext(t *testing.T) { func TestAgentEventTokenLifecycleRejectsWithdrawnAuthority(t *testing.T) { for _, transport := range []string{"header", "bearer"} { for _, change := range []string{"revoked", "expired", "read_scope_removed", "org_rebound", "identity_replaced", "principal_replaced", "invalid_role"} { + transport, change := transport, change t.Run(transport+"/"+change, func(t *testing.T) { + t.Parallel() router, cfg, server := newAgentLifecycleRouter(t, time.Hour) primary := openAgentLifecycleStream(t, server, agentEventLifecycleToken, transport) control := openAgentLifecycleStream(t, server, agentEventControlToken, transport) @@ -295,7 +299,9 @@ func TestAgentEventTokenLifecycleRejectsWithdrawnAuthority(t *testing.T) { func TestAgentEventTokenLifecycleClosesIdleStream(t *testing.T) { for _, change := range []string{"revoke", "natural_expiry"} { + change := change t.Run(change, func(t *testing.T) { + t.Parallel() _, cfg, server := newAgentLifecycleRouter(t, 10*time.Millisecond) primary := openAgentLifecycleStream(t, server, agentEventLifecycleToken, "header") config.Mu.Lock() @@ -314,7 +320,9 @@ func TestAgentEventTokenLifecycleClosesIdleStream(t *testing.T) { func TestAgentEventTokenLifecycleResolvesLiveTenantInventory(t *testing.T) { const orgID = "tenant-a" for _, change := range []string{"replaced", "removed", "same_credential_in_new_owner", "changes_during_validation", "no_global_fallback"} { + change := change t.Run(change, func(t *testing.T) { + t.Parallel() record := newTokenRecord(t, agentEventLifecycleToken, []string{config.ScopeMonitoringRead, config.ScopeAIExecute}, nil) record.OrgID = orgID base := &config.Config{} @@ -383,7 +391,9 @@ func TestAgentEventTokenLifecycleResolvesLiveTenantInventory(t *testing.T) { // redacted projection a monitoring:read token gets. func TestAgentEventTokenLifecyclePreservesSessionDisclosure(t *testing.T) { for user, restricted := range map[string]bool{"operator": false, "viewer": true} { + user, restricted := user, restricted t.Run(user, func(t *testing.T) { + t.Parallel() router, cfg, server := newAgentLifecycleRouter(t, time.Hour) config.Mu.Lock() cfg.AuthUser = "operator" diff --git a/internal/api/agent_snapshot_authority_test.go b/internal/api/agent_snapshot_authority_test.go index a05c23e81d..62ec415e3b 100644 --- a/internal/api/agent_snapshot_authority_test.go +++ b/internal/api/agent_snapshot_authority_test.go @@ -64,17 +64,27 @@ type snapshotAuthorityFixture struct { path string } -func newSnapshotAuthorityFixture(t *testing.T, path string, scopes []string) *snapshotAuthorityFixture { +func setupSnapshotAuthorityEnv(t *testing.T) { t.Helper() setMockModeForTest(t, false) t.Setenv("PULSE_AUTH_BYPASS", "false") + InitSessionStore(t.TempDir()) +} + +func newSnapshotAuthorityFixture(t *testing.T, path string, scopes []string) *snapshotAuthorityFixture { + t.Helper() + setupSnapshotAuthorityEnv(t) + return newSnapshotAuthorityFixtureWithEnv(t, path, scopes) +} + +func newSnapshotAuthorityFixtureWithEnv(t *testing.T, path string, scopes []string) *snapshotAuthorityFixture { + t.Helper() cfg := newTestConfigWithTokens(t, newTokenRecord(t, snapshotAuthorityToken, scopes, nil), newTokenRecord(t, snapshotAuthorityControl, []string{config.ScopeWildcard}, nil), ) cfg.AuthUser, cfg.AuthPass = "operator", "fixture-nonempty-hash" cfg.ProxyAuthSecret, cfg.ProxyAuthUserHeader = "snapshot-proxy-fixture", "X-Remote-User" - InitSessionStore(cfg.DataPath) router := newTestRouter(t, cfg, nil, nil, nil, nil, "test") t.Cleanup(router.ShutdownResourceStores) now := time.Now().UTC() @@ -265,11 +275,14 @@ func (f *snapshotAuthorityFixture) changeToken(t *testing.T, change string) { } func TestAgentSnapshotsWithdrawnTokenCannotDisclose(t *testing.T) { + setupSnapshotAuthorityEnv(t) for _, path := range snapshotAuthorityPaths { for _, transport := range []string{"header", "bearer"} { for _, change := range []string{"revoked", "expired", "scope", "organization", "credential", "principal"} { + path, transport, change := path, transport, change t.Run(path+"/"+transport+"/"+change, func(t *testing.T) { - f := newSnapshotAuthorityFixture(t, path, []string{config.ScopeMonitoringRead, config.ScopeAIExecute}) + t.Parallel() + f := newSnapshotAuthorityFixtureWithEnv(t, path, []string{config.ScopeMonitoringRead, config.ScopeAIExecute}) control := f.begin(t, snapshotAuthorityControl, "header") primary := f.begin(t, snapshotAuthorityToken, transport) f.changeToken(t, change) @@ -295,11 +308,19 @@ func TestAgentSnapshotsWithdrawnTokenCannotDisclose(t *testing.T) { } func TestAgentSnapshotsWithdrawnSessionCannotDisclose(t *testing.T) { + setupSnapshotAuthorityEnv(t) for _, path := range snapshotAuthorityPaths { for _, change := range []string{"logout", "expired", "replaced", "principal", "store"} { + path, change := path, change t.Run(path+"/"+change, func(t *testing.T) { - f := newSnapshotAuthorityFixture(t, path, []string{config.ScopeMonitoringRead}) - const raw = "synthetic-snapshot-session" + if change != "store" { + t.Parallel() + } + f := newSnapshotAuthorityFixtureWithEnv(t, path, []string{config.ScopeMonitoringRead}) + raw := "synthetic-snapshot-session-" + path + "-" + change + if change == "store" { + InitSessionStore(t.TempDir()) + } GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", f.router.config.AuthUser) t.Cleanup(func() { GetSessionStore().DeleteSession(raw) }) control := f.begin(t, snapshotAuthorityControl, "header") @@ -317,12 +338,18 @@ func TestAgentSnapshotsWithdrawnSessionCannotDisclose(t *testing.T) { }) } } + // Reset to a parent-owned store after sequential "store" subtests finish + // and before parallel session-mutation subtests begin. + InitSessionStore(t.TempDir()) } func TestAgentSnapshotsCommandWithdrawalAndCurrentRedaction(t *testing.T) { + setupSnapshotAuthorityEnv(t) for _, transport := range []string{"header", "bearer"} { + transport := transport t.Run(transport, func(t *testing.T) { - f := newSnapshotAuthorityFixture(t, snapshotAuthorityPaths[0], []string{config.ScopeMonitoringRead, config.ScopeAIExecute}) + t.Parallel() + f := newSnapshotAuthorityFixtureWithEnv(t, snapshotAuthorityPaths[0], []string{config.ScopeMonitoringRead, config.ScopeAIExecute}) control := f.begin(t, snapshotAuthorityControl, "header") primary := f.begin(t, snapshotAuthorityToken, transport) f.changeToken(t, "command_scope") @@ -335,9 +362,12 @@ func TestAgentSnapshotsCommandWithdrawalAndCurrentRedaction(t *testing.T) { } func TestAgentSnapshotsWithdrawalWithholdsMissingResourceError(t *testing.T) { + setupSnapshotAuthorityEnv(t) for _, kind := range []string{"resource-context", "resource-capabilities"} { + kind := kind t.Run(kind, func(t *testing.T) { - f := newSnapshotAuthorityFixture(t, "/api/agent/"+kind+"/missing", []string{config.ScopeMonitoringRead}) + t.Parallel() + f := newSnapshotAuthorityFixtureWithEnv(t, "/api/agent/"+kind+"/missing", []string{config.ScopeMonitoringRead}) primary := f.begin(t, snapshotAuthorityToken, "header") f.changeToken(t, "revoked") f.provider.unblock() @@ -348,9 +378,12 @@ func TestAgentSnapshotsWithdrawalWithholdsMissingResourceError(t *testing.T) { } func TestAgentSnapshotsKeepAdmissionAndRecovery(t *testing.T) { + setupSnapshotAuthorityEnv(t) for _, path := range snapshotAuthorityPaths { + path := path t.Run(path, func(t *testing.T) { - f := newSnapshotAuthorityFixture(t, path, []string{config.ScopeSettingsRead}) + t.Parallel() + f := newSnapshotAuthorityFixtureWithEnv(t, path, []string{config.ScopeSettingsRead}) f.provider.unblock() f.current(t, "", "header", http.StatusUnauthorized) f.current(t, snapshotAuthorityToken, "header", http.StatusForbidden) diff --git a/internal/api/assistant_json_lifetime_test.go b/internal/api/assistant_json_lifetime_test.go index 7de8fc9257..af10d35b50 100644 --- a/internal/api/assistant_json_lifetime_test.go +++ b/internal/api/assistant_json_lifetime_test.go @@ -45,18 +45,15 @@ func newAssistantJSONFixture(t *testing.T, kind string, scopes []string) *assist t.Helper() licensed := &atomic.Bool{} licensed.Store(true) + var binder func(extensions.AIAlertAnalysisEndpoints, extensions.AIAlertAnalysisRuntime) extensions.AIAlertAnalysisEndpoints if kind == "kubernetes" { - aiAlertAnalysisBindMu.RLock() - previous := aiAlertAnalysisEndpointsBinder - aiAlertAnalysisBindMu.RUnlock() - SetAIAlertAnalysisEndpointsBinder(func(defaults extensions.AIAlertAnalysisEndpoints, runtime extensions.AIAlertAnalysisRuntime) extensions.AIAlertAnalysisEndpoints { + binder = func(defaults extensions.AIAlertAnalysisEndpoints, runtime extensions.AIAlertAnalysisRuntime) extensions.AIAlertAnalysisEndpoints { return assistantJSONAnalysisFixture{defaults, runtime, licensed} - }) - defer SetAIAlertAnalysisEndpointsBinder(previous) + } } // Share the held text-only Ollama and native full-Router setup. The JSON // requests below never open an SSE reader or execute a tool/agent/command. - f := &assistantJSONFixture{newAssistantStreamFixture(t, "json-"+kind, scopes), kind, licensed} + f := &assistantJSONFixture{newAssistantStreamFixtureWithBinder(t, "json-"+kind, scopes, binder), kind, licensed} if kind == "kubernetes" { registry := unifiedresources.NewRegistry(nil) registry.IngestSnapshot(models.StateSnapshot{KubernetesClusters: []models.KubernetesCluster{ @@ -146,7 +143,9 @@ func TestAssistantJSONWithdrawAuthority(t *testing.T) { for _, kind := range []string{"execute", "kubernetes"} { for _, transport := range []string{"header", "bearer"} { for _, change := range []string{"revoked", "expired", "scope_removed", "org_removed", "credential_replaced", "principal_replaced", "invalid_role", "instance_removed"} { + kind, transport, change := kind, transport, change t.Run(kind+"/"+transport+"/"+change, func(t *testing.T) { + t.Parallel() f := newAssistantJSONFixture(t, kind, []string{config.ScopeAIExecute}) control := f.begin(t, "control", assistantControlToken, "header") primary := f.begin(t, "primary", f.token, transport) @@ -202,11 +201,13 @@ func TestAssistantJSONWithdrawAuthority(t *testing.T) { func TestAssistantJSONPreserveReaders(t *testing.T) { for _, kind := range []string{"execute", "kubernetes"} { for _, transport := range []string{"header", "session", "proxy"} { + kind, transport := kind, transport t.Run(kind+"/"+transport, func(t *testing.T) { + t.Parallel() f := newAssistantJSONFixture(t, kind, []string{config.ScopeAIExecute, config.ScopeSettingsRead}) raw := f.token if transport == "session" { - raw = "synthetic-assistant-json-session" + raw = "synthetic-assistant-json-session-" + kind GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", f.router.config.AuthUser) t.Cleanup(func() { GetSessionStore().DeleteSession(raw) }) } @@ -227,7 +228,9 @@ func TestAssistantJSONPreserveReaders(t *testing.T) { func TestAssistantJSONPreserveRequestCancellation(t *testing.T) { for _, kind := range []string{"execute", "kubernetes"} { + kind := kind t.Run(kind, func(t *testing.T) { + t.Parallel() f := newAssistantJSONFixture(t, kind, []string{config.ScopeAIExecute}) req := f.request(t, "primary", f.token, "header") ctx, cancel := context.WithCancel(req.Context()) diff --git a/internal/api/assistant_stream_lifetime_test.go b/internal/api/assistant_stream_lifetime_test.go index f865b19386..4e3741c8fd 100644 --- a/internal/api/assistant_stream_lifetime_test.go +++ b/internal/api/assistant_stream_lifetime_test.go @@ -67,7 +67,20 @@ type assistantStreamFixture struct { otherCalls atomic.Int32 } +var assistantBinderSetupMu sync.Mutex + func newAssistantStreamFixture(t *testing.T, kind string, scopes []string, writeTimeout ...time.Duration) *assistantStreamFixture { + t.Helper() + return newAssistantStreamFixtureWithBinder(t, kind, scopes, nil, writeTimeout...) +} + +func newAssistantStreamFixtureWithBinder( + t *testing.T, + kind string, + scopes []string, + customBinder func(extensions.AIAlertAnalysisEndpoints, extensions.AIAlertAnalysisRuntime) extensions.AIAlertAnalysisEndpoints, + writeTimeout ...time.Duration, +) *assistantStreamFixture { t.Helper() f := &assistantStreamFixture{kind: kind, primary: newAssistantProviderGate(), control: newAssistantProviderGate()} f.licensed.Store(true) @@ -126,18 +139,27 @@ func newAssistantStreamFixture(t *testing.T, kind string, scopes []string, write })) t.Cleanup(provider.Close) - // NewRouter resolves the extension while binding routes. Restore the - // previous binder immediately; tests never run parallel with global setup. - aiAlertAnalysisBindMu.RLock() - previous := aiAlertAnalysisEndpointsBinder - aiAlertAnalysisBindMu.RUnlock() - if kind == "investigate-alert" { - SetAIAlertAnalysisEndpointsBinder(func(defaults extensions.AIAlertAnalysisEndpoints, runtime extensions.AIAlertAnalysisRuntime) extensions.AIAlertAnalysisEndpoints { + // NewRouter resolves the extension while binding routes. Serialize only + // the binder swap + router creation so parallel subtests never observe + // another subtest's temporary binder. + binder := customBinder + if binder == nil && kind == "investigate-alert" { + binder = func(defaults extensions.AIAlertAnalysisEndpoints, runtime extensions.AIAlertAnalysisRuntime) extensions.AIAlertAnalysisEndpoints { return assistantAnalysisFixture{AIAlertAnalysisEndpoints: defaults, runtime: runtime, licensed: &f.licensed} - }) - defer SetAIAlertAnalysisEndpointsBinder(previous) + } } - f.router, f.token = setupExecuteRouterForScopes(t, provider.URL, scopes, true) + assistantBinderSetupMu.Lock() + if binder != nil { + aiAlertAnalysisBindMu.RLock() + previous := aiAlertAnalysisEndpointsBinder + aiAlertAnalysisBindMu.RUnlock() + SetAIAlertAnalysisEndpointsBinder(binder) + f.router, f.token = setupExecuteRouterForScopes(t, provider.URL, scopes, true) + SetAIAlertAnalysisEndpointsBinder(previous) + } else { + f.router, f.token = setupExecuteRouterForScopes(t, provider.URL, scopes, true) + } + assistantBinderSetupMu.Unlock() f.router.config.APITokens = append(f.router.config.APITokens, newTokenRecord(t, assistantControlToken, []string{config.ScopeWildcard}, nil)) f.router.config.AuthUser = "assistant-fixture-admin" f.router.config.ProxyAuthSecret = "synthetic-assistant-proxy-secret" @@ -253,7 +275,9 @@ func TestAssistantStreamsWithdrawAuthority(t *testing.T) { for _, kind := range []string{"execute", "investigate-alert", "chat"} { for _, transport := range []string{"header", "bearer"} { for _, change := range []string{"revoked", "expired", "scope_removed", "org_removed", "credential_replaced", "principal_replaced", "invalid_role"} { + kind, transport, change := kind, transport, change t.Run(kind+"/"+transport+"/"+change, func(t *testing.T) { + t.Parallel() f := newAssistantStreamFixture(t, kind, []string{assistantScope(kind)}) control := f.open(t, "control", assistantControlToken, "header") primary := f.open(t, "primary", f.token, transport) @@ -307,11 +331,13 @@ func TestAssistantStreamsWithdrawAuthority(t *testing.T) { func TestAssistantStreamsPreserveScopeAlternativesAndNonTokenReaders(t *testing.T) { for _, kind := range []string{"execute", "investigate-alert", "chat"} { for _, transport := range []string{"header", "session", "proxy"} { + kind, transport := kind, transport t.Run(kind+"/"+transport, func(t *testing.T) { + t.Parallel() f := newAssistantStreamFixture(t, kind, []string{assistantScope(kind), config.ScopeSettingsRead}) raw := f.token if transport == "session" { - raw = "synthetic-assistant-session" + raw = "synthetic-assistant-session-" + kind GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", f.router.config.AuthUser) t.Cleanup(func() { GetSessionStore().DeleteSession(raw) }) } @@ -330,7 +356,9 @@ func TestAssistantStreamsPreserveScopeAlternativesAndNonTokenReaders(t *testing. } } for _, scopes := range [][]string{{config.ScopeRelayMobileAccess}, {config.ScopeAIChat}, {config.ScopeAIChat, config.ScopeRelayMobileAccess}} { + scopes := scopes t.Run(strings.Join(scopes, "+"), func(t *testing.T) { + t.Parallel() f := newAssistantStreamFixture(t, "chat", scopes) response := f.open(t, "primary", f.token, "header") config.Mu.Lock() @@ -344,7 +372,9 @@ func TestAssistantStreamsPreserveScopeAlternativesAndNonTokenReaders(t *testing. func TestAssistantStreamsRetainAdminAndLicenseGates(t *testing.T) { for _, kind := range []string{"execute", "investigate-alert"} { + kind := kind t.Run(kind, func(t *testing.T) { + t.Parallel() f := newAssistantStreamFixture(t, kind, []string{config.ScopeAIExecute}) response := f.open(t, "primary", f.token, "header") config.Mu.Lock() @@ -364,6 +394,7 @@ func TestAssistantStreamsRetainAdminAndLicenseGates(t *testing.T) { }) } t.Run("extension-license", func(t *testing.T) { + t.Parallel() f := newAssistantStreamFixture(t, "investigate-alert", []string{config.ScopeAIExecute}) f.licensed.Store(false) response, err := f.server.Client().Do(f.request(t, "primary", f.token, "header")) @@ -382,7 +413,9 @@ func TestAssistantStreamsRetainAdminAndLicenseGates(t *testing.T) { // cancels with its request. Exercise the real idle writer, not a new short timer. func TestAssistantStreamsPreserveExecutionLifetimes(t *testing.T) { for _, kind := range []string{"execute", "investigate-alert", "chat"} { + kind := kind t.Run(kind, func(t *testing.T) { + t.Parallel() f := newAssistantStreamFixture(t, kind, []string{assistantScope(kind)}) response := f.open(t, "primary", f.token, "header") config.Mu.Lock() @@ -412,7 +445,9 @@ func TestAssistantStreamsPreserveExecutionLifetimes(t *testing.T) { func TestAssistantStreamsClearNativeServerDeadline(t *testing.T) { for _, kind := range []string{"execute", "investigate-alert", "chat"} { + kind := kind t.Run(kind, func(t *testing.T) { + t.Parallel() f := newAssistantStreamFixture(t, kind, []string{assistantScope(kind)}, 100*time.Millisecond) response := f.open(t, "primary", f.token, "header") // The initial HTTP deadline has passed, but this stream was diff --git a/internal/api/change_password_session_admin_test.go b/internal/api/change_password_session_admin_test.go index d07fe32f6b..423f56377d 100644 --- a/internal/api/change_password_session_admin_test.go +++ b/internal/api/change_password_session_admin_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/rcourtman/pulse-go-rewrite/internal/config" - "golang.org/x/crypto/bcrypt" + internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth" ) const changePasswordProbeCurrent = "correct-admin-password" @@ -18,11 +18,11 @@ const changePasswordProbeCurrent = "correct-admin-password" func newChangePasswordRouter(t *testing.T) (*Router, *config.Config) { t.Helper() dir := t.TempDir() - hashed, err := bcrypt.GenerateFromPassword([]byte(changePasswordProbeCurrent), bcrypt.DefaultCost) + hashed, err := internalauth.HashPassword(changePasswordProbeCurrent) if err != nil { - t.Fatalf("bcrypt: %v", err) + t.Fatalf("hash password: %v", err) } - cfg := &config.Config{DataPath: dir, ConfigPath: dir, AuthUser: "admin", AuthPass: string(hashed)} + cfg := &config.Config{DataPath: dir, ConfigPath: dir, AuthUser: "admin", AuthPass: hashed} router := newTestRouter(t, cfg, nil, nil, nil, nil, "1.0.0") cleanupTestRouter(t, router) return router, cfg @@ -93,9 +93,9 @@ func TestChangePasswordBasicAuthPathUnaffected(t *testing.T) { func newChangePasswordRouterWithToken(t *testing.T, rawToken string, scopes []string) (*Router, *config.Config) { t.Helper() dir := t.TempDir() - hashed, err := bcrypt.GenerateFromPassword([]byte(changePasswordProbeCurrent), bcrypt.DefaultCost) + hashed, err := internalauth.HashPassword(changePasswordProbeCurrent) if err != nil { - t.Fatalf("bcrypt: %v", err) + t.Fatalf("hash password: %v", err) } record, err := config.NewAPITokenRecord(rawToken, "change-password-caller", scopes) if err != nil { @@ -103,7 +103,7 @@ func newChangePasswordRouterWithToken(t *testing.T, rawToken string, scopes []st } cfg := &config.Config{ DataPath: dir, ConfigPath: dir, - AuthUser: "admin", AuthPass: string(hashed), + AuthUser: "admin", AuthPass: hashed, APITokens: []config.APITokenRecord{*record}, } cfg.SortAPITokens() diff --git a/internal/api/docker_agents_report_size_test.go b/internal/api/docker_agents_report_size_test.go index 7f62642cd8..e77423fa8e 100644 --- a/internal/api/docker_agents_report_size_test.go +++ b/internal/api/docker_agents_report_size_test.go @@ -27,7 +27,9 @@ func TestDockerAgentReportSizeContractAcceptsOrdinaryAndLargeFleets(t *testing.T } for _, test := range tests { + test := test t.Run(test.name, func(t *testing.T) { + t.Parallel() handler, _ := newDockerAgentHandlers(t, nil) body := dockerFleetReportBody(t, test.runtime, test.containers) if test.compressed { @@ -50,6 +52,7 @@ func TestDockerAgentReportSizeContractAcceptsOrdinaryAndLargeFleets(t *testing.T func TestDockerAgentReportSizeContractBoundaries(t *testing.T) { t.Run("uncompressed exact encoded limit accepted", func(t *testing.T) { + t.Parallel() handler, _ := newDockerAgentHandlers(t, nil) body := padDockerReportBody(t, dockerFleetReportBody(t, "docker", 1), agentsdocker.ReportEncodedBodyLimitBytes) rec := postDockerReport(handler, body, "") @@ -59,6 +62,7 @@ func TestDockerAgentReportSizeContractBoundaries(t *testing.T) { }) t.Run("uncompressed byte over encoded limit rejected", func(t *testing.T) { + t.Parallel() handler := &DockerAgentHandlers{} body := padDockerReportBody(t, dockerFleetReportBody(t, "docker", 1), agentsdocker.ReportEncodedBodyLimitBytes+1) rec := postDockerReport(handler, body, "") @@ -66,6 +70,7 @@ func TestDockerAgentReportSizeContractBoundaries(t *testing.T) { }) t.Run("gzip exact encoded limit accepted", func(t *testing.T) { + t.Parallel() handler, _ := newDockerAgentHandlers(t, nil) body := gzipAPIReportBodyWithEncodedSize( t, @@ -79,6 +84,7 @@ func TestDockerAgentReportSizeContractBoundaries(t *testing.T) { }) t.Run("gzip byte over encoded limit rejected before decompression", func(t *testing.T) { + t.Parallel() handler := &DockerAgentHandlers{} body := gzipAPIReportBodyWithEncodedSize( t, @@ -90,6 +96,7 @@ func TestDockerAgentReportSizeContractBoundaries(t *testing.T) { }) t.Run("gzip exact decoded limit accepted", func(t *testing.T) { + t.Parallel() handler, _ := newDockerAgentHandlers(t, nil) decoded := padDockerReportBody(t, dockerFleetReportBody(t, "podman", 1), agentsdocker.ReportDecodedBodyLimitBytes) rec := postDockerReport(handler, gzipAPIReportBody(t, decoded), "gzip") @@ -99,6 +106,7 @@ func TestDockerAgentReportSizeContractBoundaries(t *testing.T) { }) t.Run("gzip byte over decoded limit rejected", func(t *testing.T) { + t.Parallel() handler := &DockerAgentHandlers{} decoded := padDockerReportBody(t, dockerFleetReportBody(t, "podman", 1), agentsdocker.ReportDecodedBodyLimitBytes+1) rec := postDockerReport(handler, gzipAPIReportBody(t, decoded), "gzip") diff --git a/internal/api/host_agent_credential_handoff_test.go b/internal/api/host_agent_credential_handoff_test.go index 2b68edbbec..570567ab02 100644 --- a/internal/api/host_agent_credential_handoff_test.go +++ b/internal/api/host_agent_credential_handoff_test.go @@ -59,7 +59,9 @@ func TestHostAgentCredentialFileHandoff(t *testing.T) { {name: "empty file refuses fallback", environment: true, format: "empty", startupErr: true}, {name: "missing file refuses fallback", environment: true, format: "missing", startupErr: true}, } { + tc := tc t.Run(tc.name, func(t *testing.T) { + t.Parallel() adminRaw := "synthetic-handoff-admin.12345678" envRaw := "synthetic-handoff-environment.12345678" admin := newTokenRecord(t, adminRaw, []string{config.ScopeWildcard}, nil) diff --git a/internal/api/log_stream_auth_test.go b/internal/api/log_stream_auth_test.go index f5caabe6b0..1e17ff5610 100644 --- a/internal/api/log_stream_auth_test.go +++ b/internal/api/log_stream_auth_test.go @@ -88,7 +88,9 @@ func wantLogStreamClosed(t *testing.T, reader *bufio.Reader, forbidden string) { func TestLogStreamRejectsWithdrawnTokenAuthority(t *testing.T) { for _, transport := range []string{"header", "bearer"} { for _, change := range []string{"revoked", "expired", "settings_read_removed", "org_rebound", "multi_org_rebound", "identity_replaced", "principal_replaced", "invalid_role"} { + transport, change := transport, change t.Run(transport+"/"+change, func(t *testing.T) { + t.Parallel() _, cfg, server := newLogStreamRouter(t) control := openLogStream(t, server, logStreamControl, "header") primary := openLogStream(t, server, logStreamToken, transport) diff --git a/internal/api/oidc_only_admin_parity_test.go b/internal/api/oidc_only_admin_parity_test.go index 26fa6d361c..4b14c3cf1e 100644 --- a/internal/api/oidc_only_admin_parity_test.go +++ b/internal/api/oidc_only_admin_parity_test.go @@ -10,7 +10,6 @@ import ( "github.com/rcourtman/pulse-go-rewrite/internal/config" "github.com/rcourtman/pulse-go-rewrite/pkg/auth" - "golang.org/x/crypto/bcrypt" ) func adminParitySession(t *testing.T, user string) *http.Cookie { @@ -31,12 +30,12 @@ func adminParityConfig(t *testing.T, adminUser string) *config.Config { } cfg := &config.Config{DataPath: dir, ConfigPath: dir, APITokens: []config.APITokenRecord{*record}} if adminUser != "" { - hashed, err := bcrypt.GenerateFromPassword([]byte("admin-parity-password"), bcrypt.DefaultCost) + hashed, err := auth.HashPassword("admin-parity-password") if err != nil { - t.Fatalf("bcrypt: %v", err) + t.Fatalf("hash password: %v", err) } cfg.AuthUser = adminUser - cfg.AuthPass = string(hashed) + cfg.AuthPass = hashed } return cfg } diff --git a/internal/api/platform_admin_session_parity_test.go b/internal/api/platform_admin_session_parity_test.go index d864e14374..b1081326ec 100644 --- a/internal/api/platform_admin_session_parity_test.go +++ b/internal/api/platform_admin_session_parity_test.go @@ -12,7 +12,6 @@ import ( "github.com/rcourtman/pulse-go-rewrite/internal/config" "github.com/rcourtman/pulse-go-rewrite/internal/models" "github.com/rcourtman/pulse-go-rewrite/pkg/auth" - "golang.org/x/crypto/bcrypt" ) func platformAdminSession(t *testing.T, user string) *http.Cookie { @@ -27,12 +26,12 @@ func platformAdminConfig(t *testing.T, adminUser string) *config.Config { dir := t.TempDir() cfg := &config.Config{DataPath: dir, ConfigPath: dir} if adminUser != "" { - hashed, err := bcrypt.GenerateFromPassword([]byte("platform-admin-password"), bcrypt.DefaultCost) + hashed, err := auth.HashPassword("platform-admin-password") if err != nil { - t.Fatalf("bcrypt: %v", err) + t.Fatalf("hash password: %v", err) } cfg.AuthUser = adminUser - cfg.AuthPass = string(hashed) + cfg.AuthPass = hashed } return cfg } diff --git a/internal/api/reporting_boundary_test.go b/internal/api/reporting_boundary_test.go index d4a6291085..ff3291b35f 100644 --- a/internal/api/reporting_boundary_test.go +++ b/internal/api/reporting_boundary_test.go @@ -112,27 +112,37 @@ func TestReportingSubjectBoundaryExemptionIsExact(t *testing.T) { }) } } + sourceFiles := make(map[string][]byte) + for _, dir := range []string{"internal/api"} { + err := filepath.WalkDir(filepath.Join(repo, dir), func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + if entry.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + rel, err := filepath.Rel(repo, path) + if err != nil { + return err + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + sourceFiles[rel] = data + return nil + }) + if err != nil { + t.Fatal(err) + } + } for _, tc := range variants { + tc := tc t.Run(tc.name, func(t *testing.T) { + t.Parallel() root := t.TempDir() - for _, dir := range []string{"internal/api"} { - err := filepath.WalkDir(filepath.Join(repo, dir), func(path string, entry fs.DirEntry, err error) error { - if err != nil { - return err - } - if entry.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { - return nil - } - rel, err := filepath.Rel(repo, path) - if err != nil { - return err - } - copyReportingBoundaryFile(t, path, filepath.Join(root, rel)) - return nil - }) - if err != nil { - t.Fatal(err) - } + for rel, data := range sourceFiles { + writeReportingBoundaryFile(t, filepath.Join(root, rel), data) } apiDir := filepath.Join(root, "internal/api") if tc.file != "" { @@ -148,12 +158,8 @@ func TestReportingSubjectBoundaryExemptionIsExact(t *testing.T) { } } -func copyReportingBoundaryFile(t *testing.T, source, target string) { +func writeReportingBoundaryFile(t *testing.T, target string, data []byte) { t.Helper() - data, err := os.ReadFile(source) - if err != nil { - t.Fatal(err) - } if err := os.MkdirAll(filepath.Dir(target), 0700); err != nil { t.Fatal(err) } diff --git a/internal/api/resource_read_authority_test.go b/internal/api/resource_read_authority_test.go index f273f1719b..e28ef6869e 100644 --- a/internal/api/resource_read_authority_test.go +++ b/internal/api/resource_read_authority_test.go @@ -28,7 +28,13 @@ var resourceReadAuthorityPaths = []string{ func newResourceReadAuthorityFixture(t *testing.T, path string, scopes []string) *snapshotAuthorityFixture { t.Helper() - f := newSnapshotAuthorityFixture(t, path, scopes) + setupSnapshotAuthorityEnv(t) + return newResourceReadAuthorityFixtureWithEnv(t, path, scopes) +} + +func newResourceReadAuthorityFixtureWithEnv(t *testing.T, path string, scopes []string) *snapshotAuthorityFixture { + t.Helper() + f := newSnapshotAuthorityFixtureWithEnv(t, path, scopes) now := time.Now().UTC() parent := "vm:101" f.provider.resources[0].Metrics = &unified.ResourceMetrics{CPU: &unified.MetricValue{Value: 23, Percent: 23, Unit: "%"}} @@ -89,11 +95,14 @@ func checkResourceReadAuthorityCurrent(t *testing.T, path string, wire snapshotA } func TestResourceReadsWithdrawnTokenCannotDisclose(t *testing.T) { + setupSnapshotAuthorityEnv(t) for _, path := range resourceReadAuthorityPaths { for _, transport := range []string{"header", "bearer"} { for _, change := range []string{"revoked", "expired", "scope", "organization", "credential", "principal"} { + path, transport, change := path, transport, change t.Run(path+"/"+transport+"/"+change, func(t *testing.T) { - f := newResourceReadAuthorityFixture(t, path, []string{config.ScopeMonitoringRead}) + t.Parallel() + f := newResourceReadAuthorityFixtureWithEnv(t, path, []string{config.ScopeMonitoringRead}) control := f.begin(t, snapshotAuthorityControl, "header") primary := f.begin(t, snapshotAuthorityToken, transport) f.changeToken(t, change) @@ -119,11 +128,19 @@ func TestResourceReadsWithdrawnTokenCannotDisclose(t *testing.T) { } func TestResourceReadsWithdrawnSessionCannotDisclose(t *testing.T) { + setupSnapshotAuthorityEnv(t) for _, path := range resourceReadAuthorityPaths { for _, change := range []string{"logout", "expired", "replaced", "principal", "store"} { + path, change := path, change t.Run(path+"/"+change, func(t *testing.T) { - f := newResourceReadAuthorityFixture(t, path, []string{config.ScopeMonitoringRead}) - const raw = "synthetic-resource-read-session" + if change != "store" { + t.Parallel() + } + f := newResourceReadAuthorityFixtureWithEnv(t, path, []string{config.ScopeMonitoringRead}) + raw := "synthetic-resource-read-session-" + path + "-" + change + if change == "store" { + InitSessionStore(t.TempDir()) + } GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", f.router.config.AuthUser) t.Cleanup(func() { GetSessionStore().DeleteSession(raw) }) control := f.begin(t, snapshotAuthorityControl, "header") @@ -141,12 +158,18 @@ func TestResourceReadsWithdrawnSessionCannotDisclose(t *testing.T) { }) } } + // Reset to a parent-owned store after sequential "store" subtests finish + // and before parallel session-mutation subtests begin. + InitSessionStore(t.TempDir()) } func TestResourceReadsWithdrawalWithholdsErrors(t *testing.T) { + setupSnapshotAuthorityEnv(t) for _, path := range []string{"/api/resources/missing", "/api/resources/missing/facets", "/api/resources/missing/metrics", "/api/resources?type=synthetic-invalid-type"} { + path := path t.Run(path, func(t *testing.T) { - f := newResourceReadAuthorityFixture(t, path, []string{config.ScopeMonitoringRead}) + t.Parallel() + f := newResourceReadAuthorityFixtureWithEnv(t, path, []string{config.ScopeMonitoringRead}) primary := f.begin(t, snapshotAuthorityToken, "header") f.changeToken(t, "revoked") f.provider.unblock() @@ -161,9 +184,12 @@ func TestResourceReadsWithdrawalWithholdsErrors(t *testing.T) { } func TestResourceReadsKeepAdmissionAndRecovery(t *testing.T) { + setupSnapshotAuthorityEnv(t) for _, path := range resourceReadAuthorityPaths { + path := path t.Run(path, func(t *testing.T) { - f := newResourceReadAuthorityFixture(t, path, []string{config.ScopeSettingsRead}) + t.Parallel() + f := newResourceReadAuthorityFixtureWithEnv(t, path, []string{config.ScopeSettingsRead}) f.provider.unblock() f.current(t, "", "header", http.StatusUnauthorized) f.current(t, snapshotAuthorityToken, "header", http.StatusForbidden) @@ -181,9 +207,12 @@ func TestResourceReadsKeepAdmissionAndRecovery(t *testing.T) { // their live routing/admission and stable envelopes without database locks or // crash experiments; the response writer's delayed-write tests cover the guard. func TestResourceReadsStoreOnlyEntrancesKeepAdmission(t *testing.T) { + setupSnapshotAuthorityEnv(t) for _, path := range []string{"/api/resources/timeline", "/api/resources/vm:101/timeline", "/api/resources/vm:101/operator-state?view=lookup", "/api/resources/vm:101/maintenance-verifications"} { + path := path t.Run(path, func(t *testing.T) { - f := newResourceReadAuthorityFixture(t, path, []string{config.ScopeSettingsRead}) + t.Parallel() + f := newResourceReadAuthorityFixtureWithEnv(t, path, []string{config.ScopeSettingsRead}) f.provider.unblock() f.current(t, "", "header", http.StatusUnauthorized) f.current(t, snapshotAuthorityToken, "header", http.StatusForbidden) @@ -210,6 +239,7 @@ func TestResourceReadMissingVerificationKeepsAdmission(t *testing.T) { } func TestResourceReadScopeCannotMutate(t *testing.T) { + setupSnapshotAuthorityEnv(t) for _, mutation := range []struct{ method, path string }{ {http.MethodPost, "/api/resources/vm:101/link"}, {http.MethodPost, "/api/resources/vm:101/unlink"}, @@ -219,8 +249,10 @@ func TestResourceReadScopeCannotMutate(t *testing.T) { {http.MethodDelete, "/api/resources/vm:101/operator-state"}, {http.MethodPost, "/api/maintenance-verifications/missing/review"}, } { + mutation := mutation t.Run(mutation.method+mutation.path, func(t *testing.T) { - f := newResourceReadAuthorityFixture(t, mutation.path, []string{config.ScopeMonitoringRead}) + t.Parallel() + f := newResourceReadAuthorityFixtureWithEnv(t, mutation.path, []string{config.ScopeMonitoringRead}) f.provider.unblock() req := f.request(t, snapshotAuthorityToken, "header") req.Method = mutation.method diff --git a/internal/api/router_integration_test.go b/internal/api/router_integration_test.go index 330875455a..7266592fbb 100644 --- a/internal/api/router_integration_test.go +++ b/internal/api/router_integration_test.go @@ -913,7 +913,7 @@ func TestAlertAcknowledge_AllowsPrintableAlertIDs(t *testing.T) { } func TestStateEndpointReturnsMockData(t *testing.T) { - srv := newFleetIntegrationServer(t) + srv := newIntegrationServer(t) res, err := http.Get(srv.server.URL + "/api/state") if err != nil { @@ -1277,7 +1277,7 @@ func TestHealthEndpointHeadAllowed(t *testing.T) { } func TestConfigNodesUsesMockTopology(t *testing.T) { - srv := newFleetIntegrationServer(t) + srv := newIntegrationServer(t) res, err := http.Get(srv.server.URL + "/api/config/nodes") if err != nil { @@ -1300,7 +1300,7 @@ func TestConfigNodesUsesMockTopology(t *testing.T) { } func TestMockModeToggleEndpoint(t *testing.T) { - srv := newFleetIntegrationServer(t) + srv := newIntegrationServer(t) if !mock.IsMockEnabled() { t.Fatalf("mock mode should be enabled at start of test") diff --git a/internal/api/security_setup_fixture_isolation_test.go b/internal/api/security_setup_fixture_isolation_test.go index 31eb74b3fe..9653410102 100644 --- a/internal/api/security_setup_fixture_isolation_test.go +++ b/internal/api/security_setup_fixture_isolation_test.go @@ -24,7 +24,9 @@ func TestQuickSecuritySetupFixturesInFreshProcesses(t *testing.T) { "TestQuickSecuritySetupRotatesWithBasicAuth", "TestQuickSecuritySetupAllowsRecoveryTokenRotation", } { + name := name t.Run(name, func(t *testing.T) { + t.Parallel() ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) defer cancel() cmd := exec.CommandContext(ctx, executable, diff --git a/internal/api/security_status_capability_enforcement_test.go b/internal/api/security_status_capability_enforcement_test.go index 493b7fbbb6..8e4e183888 100644 --- a/internal/api/security_status_capability_enforcement_test.go +++ b/internal/api/security_status_capability_enforcement_test.go @@ -10,7 +10,6 @@ import ( "github.com/rcourtman/pulse-go-rewrite/internal/config" "github.com/rcourtman/pulse-go-rewrite/pkg/auth" - "golang.org/x/crypto/bcrypt" ) func newCapabilityConfig(t *testing.T, adminUser string) *config.Config { @@ -18,12 +17,12 @@ func newCapabilityConfig(t *testing.T, adminUser string) *config.Config { tempDir := t.TempDir() cfg := &config.Config{DataPath: tempDir, ConfigPath: tempDir} if adminUser != "" { - hashed, err := bcrypt.GenerateFromPassword([]byte("capability-password"), bcrypt.DefaultCost) + hashed, err := auth.HashPassword("capability-password") if err != nil { - t.Fatalf("bcrypt: %v", err) + t.Fatalf("hash password: %v", err) } cfg.AuthUser = adminUser - cfg.AuthPass = string(hashed) + cfg.AuthPass = hashed } return cfg } diff --git a/internal/api/security_token_withdrawal_test.go b/internal/api/security_token_withdrawal_test.go index e56e74cfaf..eefa4ea72b 100644 --- a/internal/api/security_token_withdrawal_test.go +++ b/internal/api/security_token_withdrawal_test.go @@ -69,7 +69,9 @@ func TestSecurityTokenMutationRoutesFollowCallerWithdrawal(t *testing.T) { t.Cleanup(resetAdminBypassState) for _, operation := range []string{"create", "rename", "scope"} { for _, change := range []string{"revoked", "rotated", "scope removed", "expired", "rebound", "owner changed"} { + operation, change := operation, change t.Run(operation+"/"+change, func(t *testing.T) { + t.Parallel() router, cfg, caller, target := tokenWithdrawalFixture(t) method, path, body := http.MethodPatch, "/api/security/tokens/"+target.ID, `{"name":"Current collector"}` if operation == "create" { diff --git a/internal/api/token_stream_lifetime_test.go b/internal/api/token_stream_lifetime_test.go index a44d5edbc4..f5e79eac57 100644 --- a/internal/api/token_stream_lifetime_test.go +++ b/internal/api/token_stream_lifetime_test.go @@ -31,7 +31,9 @@ func TestTokenStreamWriterNativeMedia(t *testing.T) { responseMediaCase{"sse_parameters", "Text/Event-Stream; charset=iso-8859-1", "text/event-stream; charset=utf-8"}) for _, media := range cases { for _, commit := range []string{"write", "header", "flush", "informational"} { + media, commit := media, commit t.Run(media.name+"/"+commit, func(t *testing.T) { + t.Parallel() server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithCancel(r.Context()) writer := &tokenStreamWriter{writer: w, flusher: w.(http.Flusher), ctx: ctx, cancel: cancel, allowed: func() bool { return true }} @@ -262,7 +264,9 @@ func TestProtectedReadStreamsWithdrawAuthority(t *testing.T) { for _, kind := range protectedReadKinds { for _, transport := range []string{"header", "bearer"} { for _, change := range []string{"revoked", "expired", "scope_removed", "org_access_removed", "credential_replaced", "principal_replaced", "invalid_role"} { + kind, transport, change := kind, transport, change t.Run(kind+"/"+transport+"/"+change, func(t *testing.T) { + t.Parallel() scope := config.ScopeSettingsRead if kind == "patrol" { scope = config.ScopeAIExecute @@ -316,7 +320,9 @@ func TestProtectedReadStreamsWithdrawAuthority(t *testing.T) { func TestProtectedReadStreamsDurableDeletion(t *testing.T) { for _, kind := range protectedReadKinds { + kind := kind t.Run(kind, func(t *testing.T) { + t.Parallel() f := newProtectedReadFixture(t, []string{config.ScopeSettingsRead, config.ScopeAIExecute}) primary := f.open(t, kind, scopedReadToken, "header") control := f.open(t, kind, scopedReadControl, "header") @@ -373,9 +379,11 @@ func TestProtectedReadStreamsIdleWithdrawal(t *testing.T) { func TestProtectedReadStreamsPreserveSessionAndProxy(t *testing.T) { for _, kind := range protectedReadKinds { for _, transport := range []string{"session", "proxy"} { + kind, transport := kind, transport t.Run(kind+"/"+transport, func(t *testing.T) { + t.Parallel() f := newProtectedReadFixture(t, []string{config.ScopeSettingsRead, config.ScopeAIExecute}) - session := fmt.Sprintf("synthetic-read-session-%d", time.Now().UnixNano()) + session := fmt.Sprintf("synthetic-read-session-%s-%s-%d", kind, transport, time.Now().UnixNano()) GetSessionStore().CreateSession(session, time.Hour, "fixture", "127.0.0.1", "stream-admin") t.Cleanup(func() { GetSessionStore().DeleteSession(session) }) reader := f.open(t, kind, session, transport) @@ -429,7 +437,9 @@ func TestProtectedReadStreamsRetainAdmissionPolicy(t *testing.T) { func TestProtectedReadStreamsKeepOrgAndInstanceSplit(t *testing.T) { for _, kind := range protectedReadKinds { + kind := kind t.Run(kind, func(t *testing.T) { + t.Parallel() f := newProtectedReadFixture(t, []string{config.ScopeSettingsRead, config.ScopeAIExecute}) reader := f.open(t, kind, scopedReadToken, "header") config.Mu.Lock() @@ -447,7 +457,9 @@ func TestProtectedReadStreamsKeepOrgAndInstanceSplit(t *testing.T) { func TestTokenStreamWriterChecksReplayQueueAndFinalClosure(t *testing.T) { for _, stage := range []string{"before_replay", "between_replay", "queued_write", "flush", "after_handler"} { + stage := stage t.Run(stage, func(t *testing.T) { + t.Parallel() cfg := newTestConfigWithTokens(t, newTokenRecord(t, scopedReadToken, []string{config.ScopeSettingsRead}, nil)) revoke := func() { config.Mu.Lock(); cfg.RemoveAPIToken(cfg.APITokens[0].ID); config.Mu.Unlock() } var retained http.ResponseWriter diff --git a/internal/api/token_stream_shutdown_test.go b/internal/api/token_stream_shutdown_test.go index 23c57ee695..ce4fddbc06 100644 --- a/internal/api/token_stream_shutdown_test.go +++ b/internal/api/token_stream_shutdown_test.go @@ -366,6 +366,7 @@ func requireWithin(t *testing.T, label string, done <-chan struct{}) { // withdrawal expire it, and nothing is written afterwards. func TestTokenStreamWriterInterruptsStalledTransport(t *testing.T) { t.Run("close", func(t *testing.T) { + t.Parallel() writer, base, wrote := guardOverStalledTransport(func() bool { return true }) closed := make(chan struct{}) go func() { writer.close(); close(closed) }() @@ -380,6 +381,7 @@ func TestTokenStreamWriterInterruptsStalledTransport(t *testing.T) { }) t.Run("withdrawal", func(t *testing.T) { + t.Parallel() var allowed atomic.Bool allowed.Store(true) writer, _, wrote := guardOverStalledTransport(allowed.Load) @@ -397,6 +399,7 @@ func TestTokenStreamWriterInterruptsStalledTransport(t *testing.T) { }) t.Run("deadline control", func(t *testing.T) { + t.Parallel() writer, base, wrote := guardOverStalledTransport(func() bool { return true }) set := make(chan struct{}) go func() { @@ -421,7 +424,9 @@ func TestTokenStreamWriterInterruptsStalledTransport(t *testing.T) { // proxy reads (no token, no periodic recheck) must both end promptly. func TestUpdateStreamChainRequestCancellationInterruptsBlockedWrites(t *testing.T) { for _, credential := range []string{"token", "proxy"} { + credential := credential t.Run(credential+"/frame", func(t *testing.T) { + t.Parallel() s := newShutdownStreamServer(t) s.dialStreamAs(credential, true) probe, done := s.stream(0) @@ -437,6 +442,7 @@ func TestUpdateStreamChainRequestCancellationInterruptsBlockedWrites(t *testing. }) t.Run(credential+"/preamble", func(t *testing.T) { + t.Parallel() s := newShutdownStreamServer(t) s.broadcaster().Broadcast(heldProgress()) deadline := time.Now().Add(shutdownStreamTimeout) @@ -533,7 +539,9 @@ func (p *panickingTransport) SetWriteDeadline(time.Time) error { // write that no longer exists. func TestTokenStreamWriterClearsIOStateOnTransportPanic(t *testing.T) { for _, op := range []string{"write", "header", "flush"} { + op := op t.Run(op, func(t *testing.T) { + t.Parallel() base := &panickingTransport{ResponseRecorder: httptest.NewRecorder(), op: op} ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/internal/api/websocket_auth_test.go b/internal/api/websocket_auth_test.go index b2f955ee7e..a9ca3aee0e 100644 --- a/internal/api/websocket_auth_test.go +++ b/internal/api/websocket_auth_test.go @@ -112,7 +112,9 @@ func wantMonitoringWebSocketClosed(t *testing.T, conn *gorillaws.Conn) { func TestMonitoringWebSocketRejectsWithdrawnTokenAuthority(t *testing.T) { for _, transport := range []string{"header", "bearer", "query"} { for _, change := range []string{"revoked", "expired", "read_scope_removed", "org_rebound", "identity_replaced", "principal_replaced", "invalid_role"} { + transport, change := transport, change t.Run(transport+"/"+change, func(t *testing.T) { + t.Parallel() _, cfg, server, hub := newMonitoringWebSocketRouter(t) primary := openMonitoringWebSocket(t, server, monitoringWebSocketToken, transport) control := openMonitoringWebSocket(t, server, monitoringWebSocketControl, transport) From fa020f677d922457f381db6272746b6ca0be0de0 Mon Sep 17 00:00:00 2001 From: "pulse-triage[bot]" <249995291+pulse-triage[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:04:58 +0000 Subject: [PATCH 2/4] Keep global-session-store internal/api subtests sequential NewRouter calls ensureSessionStore(cfg.DataPath), which replaces and shuts down the package-global session store whenever a router is built with a new data directory. Keep the six subtest suites that create or mutate entries in GetSessionStore() sequential while retaining parallel execution for all token-only and router-free subtest matrices. Contract-Neutral: Test-only adjustment reverting t.Parallel() on six session-store subtest suites; zero production code or assertion changes. Change-source: pulse-maintainer --- internal/api/agent_events_auth_test.go | 2 -- internal/api/agent_snapshot_authority_test.go | 15 ++------------- internal/api/assistant_json_lifetime_test.go | 4 +--- internal/api/assistant_stream_lifetime_test.go | 4 +--- internal/api/resource_read_authority_test.go | 15 ++------------- internal/api/token_stream_lifetime_test.go | 4 +--- 6 files changed, 7 insertions(+), 37 deletions(-) diff --git a/internal/api/agent_events_auth_test.go b/internal/api/agent_events_auth_test.go index adcd82575d..0d4a0bafd5 100644 --- a/internal/api/agent_events_auth_test.go +++ b/internal/api/agent_events_auth_test.go @@ -391,9 +391,7 @@ func TestAgentEventTokenLifecycleResolvesLiveTenantInventory(t *testing.T) { // redacted projection a monitoring:read token gets. func TestAgentEventTokenLifecyclePreservesSessionDisclosure(t *testing.T) { for user, restricted := range map[string]bool{"operator": false, "viewer": true} { - user, restricted := user, restricted t.Run(user, func(t *testing.T) { - t.Parallel() router, cfg, server := newAgentLifecycleRouter(t, time.Hour) config.Mu.Lock() cfg.AuthUser = "operator" diff --git a/internal/api/agent_snapshot_authority_test.go b/internal/api/agent_snapshot_authority_test.go index 62ec415e3b..858035652f 100644 --- a/internal/api/agent_snapshot_authority_test.go +++ b/internal/api/agent_snapshot_authority_test.go @@ -308,19 +308,11 @@ func TestAgentSnapshotsWithdrawnTokenCannotDisclose(t *testing.T) { } func TestAgentSnapshotsWithdrawnSessionCannotDisclose(t *testing.T) { - setupSnapshotAuthorityEnv(t) for _, path := range snapshotAuthorityPaths { for _, change := range []string{"logout", "expired", "replaced", "principal", "store"} { - path, change := path, change t.Run(path+"/"+change, func(t *testing.T) { - if change != "store" { - t.Parallel() - } - f := newSnapshotAuthorityFixtureWithEnv(t, path, []string{config.ScopeMonitoringRead}) - raw := "synthetic-snapshot-session-" + path + "-" + change - if change == "store" { - InitSessionStore(t.TempDir()) - } + f := newSnapshotAuthorityFixture(t, path, []string{config.ScopeMonitoringRead}) + const raw = "synthetic-snapshot-session" GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", f.router.config.AuthUser) t.Cleanup(func() { GetSessionStore().DeleteSession(raw) }) control := f.begin(t, snapshotAuthorityControl, "header") @@ -338,9 +330,6 @@ func TestAgentSnapshotsWithdrawnSessionCannotDisclose(t *testing.T) { }) } } - // Reset to a parent-owned store after sequential "store" subtests finish - // and before parallel session-mutation subtests begin. - InitSessionStore(t.TempDir()) } func TestAgentSnapshotsCommandWithdrawalAndCurrentRedaction(t *testing.T) { diff --git a/internal/api/assistant_json_lifetime_test.go b/internal/api/assistant_json_lifetime_test.go index af10d35b50..2611408e6f 100644 --- a/internal/api/assistant_json_lifetime_test.go +++ b/internal/api/assistant_json_lifetime_test.go @@ -201,13 +201,11 @@ func TestAssistantJSONWithdrawAuthority(t *testing.T) { func TestAssistantJSONPreserveReaders(t *testing.T) { for _, kind := range []string{"execute", "kubernetes"} { for _, transport := range []string{"header", "session", "proxy"} { - kind, transport := kind, transport t.Run(kind+"/"+transport, func(t *testing.T) { - t.Parallel() f := newAssistantJSONFixture(t, kind, []string{config.ScopeAIExecute, config.ScopeSettingsRead}) raw := f.token if transport == "session" { - raw = "synthetic-assistant-json-session-" + kind + raw = "synthetic-assistant-json-session" GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", f.router.config.AuthUser) t.Cleanup(func() { GetSessionStore().DeleteSession(raw) }) } diff --git a/internal/api/assistant_stream_lifetime_test.go b/internal/api/assistant_stream_lifetime_test.go index 4e3741c8fd..cd7662799d 100644 --- a/internal/api/assistant_stream_lifetime_test.go +++ b/internal/api/assistant_stream_lifetime_test.go @@ -331,13 +331,11 @@ func TestAssistantStreamsWithdrawAuthority(t *testing.T) { func TestAssistantStreamsPreserveScopeAlternativesAndNonTokenReaders(t *testing.T) { for _, kind := range []string{"execute", "investigate-alert", "chat"} { for _, transport := range []string{"header", "session", "proxy"} { - kind, transport := kind, transport t.Run(kind+"/"+transport, func(t *testing.T) { - t.Parallel() f := newAssistantStreamFixture(t, kind, []string{assistantScope(kind), config.ScopeSettingsRead}) raw := f.token if transport == "session" { - raw = "synthetic-assistant-session-" + kind + raw = "synthetic-assistant-session" GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", f.router.config.AuthUser) t.Cleanup(func() { GetSessionStore().DeleteSession(raw) }) } diff --git a/internal/api/resource_read_authority_test.go b/internal/api/resource_read_authority_test.go index e28ef6869e..274fd850de 100644 --- a/internal/api/resource_read_authority_test.go +++ b/internal/api/resource_read_authority_test.go @@ -128,19 +128,11 @@ func TestResourceReadsWithdrawnTokenCannotDisclose(t *testing.T) { } func TestResourceReadsWithdrawnSessionCannotDisclose(t *testing.T) { - setupSnapshotAuthorityEnv(t) for _, path := range resourceReadAuthorityPaths { for _, change := range []string{"logout", "expired", "replaced", "principal", "store"} { - path, change := path, change t.Run(path+"/"+change, func(t *testing.T) { - if change != "store" { - t.Parallel() - } - f := newResourceReadAuthorityFixtureWithEnv(t, path, []string{config.ScopeMonitoringRead}) - raw := "synthetic-resource-read-session-" + path + "-" + change - if change == "store" { - InitSessionStore(t.TempDir()) - } + f := newResourceReadAuthorityFixture(t, path, []string{config.ScopeMonitoringRead}) + const raw = "synthetic-resource-read-session" GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", f.router.config.AuthUser) t.Cleanup(func() { GetSessionStore().DeleteSession(raw) }) control := f.begin(t, snapshotAuthorityControl, "header") @@ -158,9 +150,6 @@ func TestResourceReadsWithdrawnSessionCannotDisclose(t *testing.T) { }) } } - // Reset to a parent-owned store after sequential "store" subtests finish - // and before parallel session-mutation subtests begin. - InitSessionStore(t.TempDir()) } func TestResourceReadsWithdrawalWithholdsErrors(t *testing.T) { diff --git a/internal/api/token_stream_lifetime_test.go b/internal/api/token_stream_lifetime_test.go index f5e79eac57..bd050a46fe 100644 --- a/internal/api/token_stream_lifetime_test.go +++ b/internal/api/token_stream_lifetime_test.go @@ -379,11 +379,9 @@ func TestProtectedReadStreamsIdleWithdrawal(t *testing.T) { func TestProtectedReadStreamsPreserveSessionAndProxy(t *testing.T) { for _, kind := range protectedReadKinds { for _, transport := range []string{"session", "proxy"} { - kind, transport := kind, transport t.Run(kind+"/"+transport, func(t *testing.T) { - t.Parallel() f := newProtectedReadFixture(t, []string{config.ScopeSettingsRead, config.ScopeAIExecute}) - session := fmt.Sprintf("synthetic-read-session-%s-%s-%d", kind, transport, time.Now().UnixNano()) + session := fmt.Sprintf("synthetic-read-session-%d", time.Now().UnixNano()) GetSessionStore().CreateSession(session, time.Hour, "fixture", "127.0.0.1", "stream-admin") t.Cleanup(func() { GetSessionStore().DeleteSession(session) }) reader := f.open(t, kind, session, transport) From de43314f42e1eb4dcbf29071e61d24bf81f7546a Mon Sep 17 00:00:00 2001 From: "pulse-triage[bot]" <249995291+pulse-triage[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:22:37 +0000 Subject: [PATCH 3/4] Keep 24 MiB blocked-write cancellation subtests sequential Each subtest in TestUpdateStreamChainRequestCancellationInterruptsBlockedWrites broadcasts a 24 MiB payload into a stalled socket; running all four concurrently under -race spikes memory pressure on 6 GiB guests without meaningful runtime gain. Keep those four subtests sequential while retaining parallel unit subtests in token_stream_shutdown_test.go. Contract-Neutral: Test-only adjustment reverting t.Parallel() on one 4-subtest blocked-write test to avoid concurrent 24 MiB memory spikes under -race. Change-source: pulse-maintainer --- internal/api/token_stream_shutdown_test.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/internal/api/token_stream_shutdown_test.go b/internal/api/token_stream_shutdown_test.go index ce4fddbc06..c0fcb6356e 100644 --- a/internal/api/token_stream_shutdown_test.go +++ b/internal/api/token_stream_shutdown_test.go @@ -424,9 +424,7 @@ func TestTokenStreamWriterInterruptsStalledTransport(t *testing.T) { // proxy reads (no token, no periodic recheck) must both end promptly. func TestUpdateStreamChainRequestCancellationInterruptsBlockedWrites(t *testing.T) { for _, credential := range []string{"token", "proxy"} { - credential := credential t.Run(credential+"/frame", func(t *testing.T) { - t.Parallel() s := newShutdownStreamServer(t) s.dialStreamAs(credential, true) probe, done := s.stream(0) @@ -442,7 +440,6 @@ func TestUpdateStreamChainRequestCancellationInterruptsBlockedWrites(t *testing. }) t.Run(credential+"/preamble", func(t *testing.T) { - t.Parallel() s := newShutdownStreamServer(t) s.broadcaster().Broadcast(heldProgress()) deadline := time.Now().Add(shutdownStreamTimeout) From 69815679f46c571d6492d382884bb7ffb4170186 Mon Sep 17 00:00:00 2001 From: "pulse-triage[bot]" <249995291+pulse-triage[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:40:15 +0000 Subject: [PATCH 4/4] Restrict internal/api subtest parallelization to router-free tests NewRouter mutates three package-global singletons (ensureSessionStore, ensureCSRFStore, and auth.SetManager), and newTestRouter cleanup calls ShutdownRBAC which closes and clears the global RBAC manager. Remove t.Parallel() from all subtest matrices that construct newTestRouter instances while keeping the 11 strictly router-free / sequential-fixture speedups intact. Contract-Neutral: Test-only revert of t.Parallel() on newTestRouter-based subtest matrices to keep package-global RBAC, session, and CSRF singletons strictly serialized. Change-source: pulse-maintainer --- internal/api/agent_events_auth_test.go | 4 -- internal/api/agent_snapshot_authority_test.go | 34 +++--------- internal/api/assistant_json_lifetime_test.go | 15 +++--- .../api/assistant_stream_lifetime_test.go | 53 ++++--------------- .../api/host_agent_credential_handoff_test.go | 2 - internal/api/log_stream_auth_test.go | 2 - internal/api/resource_read_authority_test.go | 33 +++--------- .../api/security_token_withdrawal_test.go | 2 - internal/api/token_stream_lifetime_test.go | 6 --- internal/api/websocket_auth_test.go | 2 - 10 files changed, 29 insertions(+), 124 deletions(-) diff --git a/internal/api/agent_events_auth_test.go b/internal/api/agent_events_auth_test.go index 0d4a0bafd5..4252d9d2d3 100644 --- a/internal/api/agent_events_auth_test.go +++ b/internal/api/agent_events_auth_test.go @@ -255,9 +255,7 @@ func TestAgentEventTokenRefreshKeepsBoundedContext(t *testing.T) { func TestAgentEventTokenLifecycleRejectsWithdrawnAuthority(t *testing.T) { for _, transport := range []string{"header", "bearer"} { for _, change := range []string{"revoked", "expired", "read_scope_removed", "org_rebound", "identity_replaced", "principal_replaced", "invalid_role"} { - transport, change := transport, change t.Run(transport+"/"+change, func(t *testing.T) { - t.Parallel() router, cfg, server := newAgentLifecycleRouter(t, time.Hour) primary := openAgentLifecycleStream(t, server, agentEventLifecycleToken, transport) control := openAgentLifecycleStream(t, server, agentEventControlToken, transport) @@ -299,9 +297,7 @@ func TestAgentEventTokenLifecycleRejectsWithdrawnAuthority(t *testing.T) { func TestAgentEventTokenLifecycleClosesIdleStream(t *testing.T) { for _, change := range []string{"revoke", "natural_expiry"} { - change := change t.Run(change, func(t *testing.T) { - t.Parallel() _, cfg, server := newAgentLifecycleRouter(t, 10*time.Millisecond) primary := openAgentLifecycleStream(t, server, agentEventLifecycleToken, "header") config.Mu.Lock() diff --git a/internal/api/agent_snapshot_authority_test.go b/internal/api/agent_snapshot_authority_test.go index 858035652f..a05c23e81d 100644 --- a/internal/api/agent_snapshot_authority_test.go +++ b/internal/api/agent_snapshot_authority_test.go @@ -64,27 +64,17 @@ type snapshotAuthorityFixture struct { path string } -func setupSnapshotAuthorityEnv(t *testing.T) { +func newSnapshotAuthorityFixture(t *testing.T, path string, scopes []string) *snapshotAuthorityFixture { t.Helper() setMockModeForTest(t, false) t.Setenv("PULSE_AUTH_BYPASS", "false") - InitSessionStore(t.TempDir()) -} - -func newSnapshotAuthorityFixture(t *testing.T, path string, scopes []string) *snapshotAuthorityFixture { - t.Helper() - setupSnapshotAuthorityEnv(t) - return newSnapshotAuthorityFixtureWithEnv(t, path, scopes) -} - -func newSnapshotAuthorityFixtureWithEnv(t *testing.T, path string, scopes []string) *snapshotAuthorityFixture { - t.Helper() cfg := newTestConfigWithTokens(t, newTokenRecord(t, snapshotAuthorityToken, scopes, nil), newTokenRecord(t, snapshotAuthorityControl, []string{config.ScopeWildcard}, nil), ) cfg.AuthUser, cfg.AuthPass = "operator", "fixture-nonempty-hash" cfg.ProxyAuthSecret, cfg.ProxyAuthUserHeader = "snapshot-proxy-fixture", "X-Remote-User" + InitSessionStore(cfg.DataPath) router := newTestRouter(t, cfg, nil, nil, nil, nil, "test") t.Cleanup(router.ShutdownResourceStores) now := time.Now().UTC() @@ -275,14 +265,11 @@ func (f *snapshotAuthorityFixture) changeToken(t *testing.T, change string) { } func TestAgentSnapshotsWithdrawnTokenCannotDisclose(t *testing.T) { - setupSnapshotAuthorityEnv(t) for _, path := range snapshotAuthorityPaths { for _, transport := range []string{"header", "bearer"} { for _, change := range []string{"revoked", "expired", "scope", "organization", "credential", "principal"} { - path, transport, change := path, transport, change t.Run(path+"/"+transport+"/"+change, func(t *testing.T) { - t.Parallel() - f := newSnapshotAuthorityFixtureWithEnv(t, path, []string{config.ScopeMonitoringRead, config.ScopeAIExecute}) + f := newSnapshotAuthorityFixture(t, path, []string{config.ScopeMonitoringRead, config.ScopeAIExecute}) control := f.begin(t, snapshotAuthorityControl, "header") primary := f.begin(t, snapshotAuthorityToken, transport) f.changeToken(t, change) @@ -333,12 +320,9 @@ func TestAgentSnapshotsWithdrawnSessionCannotDisclose(t *testing.T) { } func TestAgentSnapshotsCommandWithdrawalAndCurrentRedaction(t *testing.T) { - setupSnapshotAuthorityEnv(t) for _, transport := range []string{"header", "bearer"} { - transport := transport t.Run(transport, func(t *testing.T) { - t.Parallel() - f := newSnapshotAuthorityFixtureWithEnv(t, snapshotAuthorityPaths[0], []string{config.ScopeMonitoringRead, config.ScopeAIExecute}) + f := newSnapshotAuthorityFixture(t, snapshotAuthorityPaths[0], []string{config.ScopeMonitoringRead, config.ScopeAIExecute}) control := f.begin(t, snapshotAuthorityControl, "header") primary := f.begin(t, snapshotAuthorityToken, transport) f.changeToken(t, "command_scope") @@ -351,12 +335,9 @@ func TestAgentSnapshotsCommandWithdrawalAndCurrentRedaction(t *testing.T) { } func TestAgentSnapshotsWithdrawalWithholdsMissingResourceError(t *testing.T) { - setupSnapshotAuthorityEnv(t) for _, kind := range []string{"resource-context", "resource-capabilities"} { - kind := kind t.Run(kind, func(t *testing.T) { - t.Parallel() - f := newSnapshotAuthorityFixtureWithEnv(t, "/api/agent/"+kind+"/missing", []string{config.ScopeMonitoringRead}) + f := newSnapshotAuthorityFixture(t, "/api/agent/"+kind+"/missing", []string{config.ScopeMonitoringRead}) primary := f.begin(t, snapshotAuthorityToken, "header") f.changeToken(t, "revoked") f.provider.unblock() @@ -367,12 +348,9 @@ func TestAgentSnapshotsWithdrawalWithholdsMissingResourceError(t *testing.T) { } func TestAgentSnapshotsKeepAdmissionAndRecovery(t *testing.T) { - setupSnapshotAuthorityEnv(t) for _, path := range snapshotAuthorityPaths { - path := path t.Run(path, func(t *testing.T) { - t.Parallel() - f := newSnapshotAuthorityFixtureWithEnv(t, path, []string{config.ScopeSettingsRead}) + f := newSnapshotAuthorityFixture(t, path, []string{config.ScopeSettingsRead}) f.provider.unblock() f.current(t, "", "header", http.StatusUnauthorized) f.current(t, snapshotAuthorityToken, "header", http.StatusForbidden) diff --git a/internal/api/assistant_json_lifetime_test.go b/internal/api/assistant_json_lifetime_test.go index 2611408e6f..7de8fc9257 100644 --- a/internal/api/assistant_json_lifetime_test.go +++ b/internal/api/assistant_json_lifetime_test.go @@ -45,15 +45,18 @@ func newAssistantJSONFixture(t *testing.T, kind string, scopes []string) *assist t.Helper() licensed := &atomic.Bool{} licensed.Store(true) - var binder func(extensions.AIAlertAnalysisEndpoints, extensions.AIAlertAnalysisRuntime) extensions.AIAlertAnalysisEndpoints if kind == "kubernetes" { - binder = func(defaults extensions.AIAlertAnalysisEndpoints, runtime extensions.AIAlertAnalysisRuntime) extensions.AIAlertAnalysisEndpoints { + aiAlertAnalysisBindMu.RLock() + previous := aiAlertAnalysisEndpointsBinder + aiAlertAnalysisBindMu.RUnlock() + SetAIAlertAnalysisEndpointsBinder(func(defaults extensions.AIAlertAnalysisEndpoints, runtime extensions.AIAlertAnalysisRuntime) extensions.AIAlertAnalysisEndpoints { return assistantJSONAnalysisFixture{defaults, runtime, licensed} - } + }) + defer SetAIAlertAnalysisEndpointsBinder(previous) } // Share the held text-only Ollama and native full-Router setup. The JSON // requests below never open an SSE reader or execute a tool/agent/command. - f := &assistantJSONFixture{newAssistantStreamFixtureWithBinder(t, "json-"+kind, scopes, binder), kind, licensed} + f := &assistantJSONFixture{newAssistantStreamFixture(t, "json-"+kind, scopes), kind, licensed} if kind == "kubernetes" { registry := unifiedresources.NewRegistry(nil) registry.IngestSnapshot(models.StateSnapshot{KubernetesClusters: []models.KubernetesCluster{ @@ -143,9 +146,7 @@ func TestAssistantJSONWithdrawAuthority(t *testing.T) { for _, kind := range []string{"execute", "kubernetes"} { for _, transport := range []string{"header", "bearer"} { for _, change := range []string{"revoked", "expired", "scope_removed", "org_removed", "credential_replaced", "principal_replaced", "invalid_role", "instance_removed"} { - kind, transport, change := kind, transport, change t.Run(kind+"/"+transport+"/"+change, func(t *testing.T) { - t.Parallel() f := newAssistantJSONFixture(t, kind, []string{config.ScopeAIExecute}) control := f.begin(t, "control", assistantControlToken, "header") primary := f.begin(t, "primary", f.token, transport) @@ -226,9 +227,7 @@ func TestAssistantJSONPreserveReaders(t *testing.T) { func TestAssistantJSONPreserveRequestCancellation(t *testing.T) { for _, kind := range []string{"execute", "kubernetes"} { - kind := kind t.Run(kind, func(t *testing.T) { - t.Parallel() f := newAssistantJSONFixture(t, kind, []string{config.ScopeAIExecute}) req := f.request(t, "primary", f.token, "header") ctx, cancel := context.WithCancel(req.Context()) diff --git a/internal/api/assistant_stream_lifetime_test.go b/internal/api/assistant_stream_lifetime_test.go index cd7662799d..f865b19386 100644 --- a/internal/api/assistant_stream_lifetime_test.go +++ b/internal/api/assistant_stream_lifetime_test.go @@ -67,20 +67,7 @@ type assistantStreamFixture struct { otherCalls atomic.Int32 } -var assistantBinderSetupMu sync.Mutex - func newAssistantStreamFixture(t *testing.T, kind string, scopes []string, writeTimeout ...time.Duration) *assistantStreamFixture { - t.Helper() - return newAssistantStreamFixtureWithBinder(t, kind, scopes, nil, writeTimeout...) -} - -func newAssistantStreamFixtureWithBinder( - t *testing.T, - kind string, - scopes []string, - customBinder func(extensions.AIAlertAnalysisEndpoints, extensions.AIAlertAnalysisRuntime) extensions.AIAlertAnalysisEndpoints, - writeTimeout ...time.Duration, -) *assistantStreamFixture { t.Helper() f := &assistantStreamFixture{kind: kind, primary: newAssistantProviderGate(), control: newAssistantProviderGate()} f.licensed.Store(true) @@ -139,27 +126,18 @@ func newAssistantStreamFixtureWithBinder( })) t.Cleanup(provider.Close) - // NewRouter resolves the extension while binding routes. Serialize only - // the binder swap + router creation so parallel subtests never observe - // another subtest's temporary binder. - binder := customBinder - if binder == nil && kind == "investigate-alert" { - binder = func(defaults extensions.AIAlertAnalysisEndpoints, runtime extensions.AIAlertAnalysisRuntime) extensions.AIAlertAnalysisEndpoints { + // NewRouter resolves the extension while binding routes. Restore the + // previous binder immediately; tests never run parallel with global setup. + aiAlertAnalysisBindMu.RLock() + previous := aiAlertAnalysisEndpointsBinder + aiAlertAnalysisBindMu.RUnlock() + if kind == "investigate-alert" { + SetAIAlertAnalysisEndpointsBinder(func(defaults extensions.AIAlertAnalysisEndpoints, runtime extensions.AIAlertAnalysisRuntime) extensions.AIAlertAnalysisEndpoints { return assistantAnalysisFixture{AIAlertAnalysisEndpoints: defaults, runtime: runtime, licensed: &f.licensed} - } + }) + defer SetAIAlertAnalysisEndpointsBinder(previous) } - assistantBinderSetupMu.Lock() - if binder != nil { - aiAlertAnalysisBindMu.RLock() - previous := aiAlertAnalysisEndpointsBinder - aiAlertAnalysisBindMu.RUnlock() - SetAIAlertAnalysisEndpointsBinder(binder) - f.router, f.token = setupExecuteRouterForScopes(t, provider.URL, scopes, true) - SetAIAlertAnalysisEndpointsBinder(previous) - } else { - f.router, f.token = setupExecuteRouterForScopes(t, provider.URL, scopes, true) - } - assistantBinderSetupMu.Unlock() + f.router, f.token = setupExecuteRouterForScopes(t, provider.URL, scopes, true) f.router.config.APITokens = append(f.router.config.APITokens, newTokenRecord(t, assistantControlToken, []string{config.ScopeWildcard}, nil)) f.router.config.AuthUser = "assistant-fixture-admin" f.router.config.ProxyAuthSecret = "synthetic-assistant-proxy-secret" @@ -275,9 +253,7 @@ func TestAssistantStreamsWithdrawAuthority(t *testing.T) { for _, kind := range []string{"execute", "investigate-alert", "chat"} { for _, transport := range []string{"header", "bearer"} { for _, change := range []string{"revoked", "expired", "scope_removed", "org_removed", "credential_replaced", "principal_replaced", "invalid_role"} { - kind, transport, change := kind, transport, change t.Run(kind+"/"+transport+"/"+change, func(t *testing.T) { - t.Parallel() f := newAssistantStreamFixture(t, kind, []string{assistantScope(kind)}) control := f.open(t, "control", assistantControlToken, "header") primary := f.open(t, "primary", f.token, transport) @@ -354,9 +330,7 @@ func TestAssistantStreamsPreserveScopeAlternativesAndNonTokenReaders(t *testing. } } for _, scopes := range [][]string{{config.ScopeRelayMobileAccess}, {config.ScopeAIChat}, {config.ScopeAIChat, config.ScopeRelayMobileAccess}} { - scopes := scopes t.Run(strings.Join(scopes, "+"), func(t *testing.T) { - t.Parallel() f := newAssistantStreamFixture(t, "chat", scopes) response := f.open(t, "primary", f.token, "header") config.Mu.Lock() @@ -370,9 +344,7 @@ func TestAssistantStreamsPreserveScopeAlternativesAndNonTokenReaders(t *testing. func TestAssistantStreamsRetainAdminAndLicenseGates(t *testing.T) { for _, kind := range []string{"execute", "investigate-alert"} { - kind := kind t.Run(kind, func(t *testing.T) { - t.Parallel() f := newAssistantStreamFixture(t, kind, []string{config.ScopeAIExecute}) response := f.open(t, "primary", f.token, "header") config.Mu.Lock() @@ -392,7 +364,6 @@ func TestAssistantStreamsRetainAdminAndLicenseGates(t *testing.T) { }) } t.Run("extension-license", func(t *testing.T) { - t.Parallel() f := newAssistantStreamFixture(t, "investigate-alert", []string{config.ScopeAIExecute}) f.licensed.Store(false) response, err := f.server.Client().Do(f.request(t, "primary", f.token, "header")) @@ -411,9 +382,7 @@ func TestAssistantStreamsRetainAdminAndLicenseGates(t *testing.T) { // cancels with its request. Exercise the real idle writer, not a new short timer. func TestAssistantStreamsPreserveExecutionLifetimes(t *testing.T) { for _, kind := range []string{"execute", "investigate-alert", "chat"} { - kind := kind t.Run(kind, func(t *testing.T) { - t.Parallel() f := newAssistantStreamFixture(t, kind, []string{assistantScope(kind)}) response := f.open(t, "primary", f.token, "header") config.Mu.Lock() @@ -443,9 +412,7 @@ func TestAssistantStreamsPreserveExecutionLifetimes(t *testing.T) { func TestAssistantStreamsClearNativeServerDeadline(t *testing.T) { for _, kind := range []string{"execute", "investigate-alert", "chat"} { - kind := kind t.Run(kind, func(t *testing.T) { - t.Parallel() f := newAssistantStreamFixture(t, kind, []string{assistantScope(kind)}, 100*time.Millisecond) response := f.open(t, "primary", f.token, "header") // The initial HTTP deadline has passed, but this stream was diff --git a/internal/api/host_agent_credential_handoff_test.go b/internal/api/host_agent_credential_handoff_test.go index 570567ab02..2b68edbbec 100644 --- a/internal/api/host_agent_credential_handoff_test.go +++ b/internal/api/host_agent_credential_handoff_test.go @@ -59,9 +59,7 @@ func TestHostAgentCredentialFileHandoff(t *testing.T) { {name: "empty file refuses fallback", environment: true, format: "empty", startupErr: true}, {name: "missing file refuses fallback", environment: true, format: "missing", startupErr: true}, } { - tc := tc t.Run(tc.name, func(t *testing.T) { - t.Parallel() adminRaw := "synthetic-handoff-admin.12345678" envRaw := "synthetic-handoff-environment.12345678" admin := newTokenRecord(t, adminRaw, []string{config.ScopeWildcard}, nil) diff --git a/internal/api/log_stream_auth_test.go b/internal/api/log_stream_auth_test.go index 1e17ff5610..f5caabe6b0 100644 --- a/internal/api/log_stream_auth_test.go +++ b/internal/api/log_stream_auth_test.go @@ -88,9 +88,7 @@ func wantLogStreamClosed(t *testing.T, reader *bufio.Reader, forbidden string) { func TestLogStreamRejectsWithdrawnTokenAuthority(t *testing.T) { for _, transport := range []string{"header", "bearer"} { for _, change := range []string{"revoked", "expired", "settings_read_removed", "org_rebound", "multi_org_rebound", "identity_replaced", "principal_replaced", "invalid_role"} { - transport, change := transport, change t.Run(transport+"/"+change, func(t *testing.T) { - t.Parallel() _, cfg, server := newLogStreamRouter(t) control := openLogStream(t, server, logStreamControl, "header") primary := openLogStream(t, server, logStreamToken, transport) diff --git a/internal/api/resource_read_authority_test.go b/internal/api/resource_read_authority_test.go index 274fd850de..f273f1719b 100644 --- a/internal/api/resource_read_authority_test.go +++ b/internal/api/resource_read_authority_test.go @@ -28,13 +28,7 @@ var resourceReadAuthorityPaths = []string{ func newResourceReadAuthorityFixture(t *testing.T, path string, scopes []string) *snapshotAuthorityFixture { t.Helper() - setupSnapshotAuthorityEnv(t) - return newResourceReadAuthorityFixtureWithEnv(t, path, scopes) -} - -func newResourceReadAuthorityFixtureWithEnv(t *testing.T, path string, scopes []string) *snapshotAuthorityFixture { - t.Helper() - f := newSnapshotAuthorityFixtureWithEnv(t, path, scopes) + f := newSnapshotAuthorityFixture(t, path, scopes) now := time.Now().UTC() parent := "vm:101" f.provider.resources[0].Metrics = &unified.ResourceMetrics{CPU: &unified.MetricValue{Value: 23, Percent: 23, Unit: "%"}} @@ -95,14 +89,11 @@ func checkResourceReadAuthorityCurrent(t *testing.T, path string, wire snapshotA } func TestResourceReadsWithdrawnTokenCannotDisclose(t *testing.T) { - setupSnapshotAuthorityEnv(t) for _, path := range resourceReadAuthorityPaths { for _, transport := range []string{"header", "bearer"} { for _, change := range []string{"revoked", "expired", "scope", "organization", "credential", "principal"} { - path, transport, change := path, transport, change t.Run(path+"/"+transport+"/"+change, func(t *testing.T) { - t.Parallel() - f := newResourceReadAuthorityFixtureWithEnv(t, path, []string{config.ScopeMonitoringRead}) + f := newResourceReadAuthorityFixture(t, path, []string{config.ScopeMonitoringRead}) control := f.begin(t, snapshotAuthorityControl, "header") primary := f.begin(t, snapshotAuthorityToken, transport) f.changeToken(t, change) @@ -153,12 +144,9 @@ func TestResourceReadsWithdrawnSessionCannotDisclose(t *testing.T) { } func TestResourceReadsWithdrawalWithholdsErrors(t *testing.T) { - setupSnapshotAuthorityEnv(t) for _, path := range []string{"/api/resources/missing", "/api/resources/missing/facets", "/api/resources/missing/metrics", "/api/resources?type=synthetic-invalid-type"} { - path := path t.Run(path, func(t *testing.T) { - t.Parallel() - f := newResourceReadAuthorityFixtureWithEnv(t, path, []string{config.ScopeMonitoringRead}) + f := newResourceReadAuthorityFixture(t, path, []string{config.ScopeMonitoringRead}) primary := f.begin(t, snapshotAuthorityToken, "header") f.changeToken(t, "revoked") f.provider.unblock() @@ -173,12 +161,9 @@ func TestResourceReadsWithdrawalWithholdsErrors(t *testing.T) { } func TestResourceReadsKeepAdmissionAndRecovery(t *testing.T) { - setupSnapshotAuthorityEnv(t) for _, path := range resourceReadAuthorityPaths { - path := path t.Run(path, func(t *testing.T) { - t.Parallel() - f := newResourceReadAuthorityFixtureWithEnv(t, path, []string{config.ScopeSettingsRead}) + f := newResourceReadAuthorityFixture(t, path, []string{config.ScopeSettingsRead}) f.provider.unblock() f.current(t, "", "header", http.StatusUnauthorized) f.current(t, snapshotAuthorityToken, "header", http.StatusForbidden) @@ -196,12 +181,9 @@ func TestResourceReadsKeepAdmissionAndRecovery(t *testing.T) { // their live routing/admission and stable envelopes without database locks or // crash experiments; the response writer's delayed-write tests cover the guard. func TestResourceReadsStoreOnlyEntrancesKeepAdmission(t *testing.T) { - setupSnapshotAuthorityEnv(t) for _, path := range []string{"/api/resources/timeline", "/api/resources/vm:101/timeline", "/api/resources/vm:101/operator-state?view=lookup", "/api/resources/vm:101/maintenance-verifications"} { - path := path t.Run(path, func(t *testing.T) { - t.Parallel() - f := newResourceReadAuthorityFixtureWithEnv(t, path, []string{config.ScopeSettingsRead}) + f := newResourceReadAuthorityFixture(t, path, []string{config.ScopeSettingsRead}) f.provider.unblock() f.current(t, "", "header", http.StatusUnauthorized) f.current(t, snapshotAuthorityToken, "header", http.StatusForbidden) @@ -228,7 +210,6 @@ func TestResourceReadMissingVerificationKeepsAdmission(t *testing.T) { } func TestResourceReadScopeCannotMutate(t *testing.T) { - setupSnapshotAuthorityEnv(t) for _, mutation := range []struct{ method, path string }{ {http.MethodPost, "/api/resources/vm:101/link"}, {http.MethodPost, "/api/resources/vm:101/unlink"}, @@ -238,10 +219,8 @@ func TestResourceReadScopeCannotMutate(t *testing.T) { {http.MethodDelete, "/api/resources/vm:101/operator-state"}, {http.MethodPost, "/api/maintenance-verifications/missing/review"}, } { - mutation := mutation t.Run(mutation.method+mutation.path, func(t *testing.T) { - t.Parallel() - f := newResourceReadAuthorityFixtureWithEnv(t, mutation.path, []string{config.ScopeMonitoringRead}) + f := newResourceReadAuthorityFixture(t, mutation.path, []string{config.ScopeMonitoringRead}) f.provider.unblock() req := f.request(t, snapshotAuthorityToken, "header") req.Method = mutation.method diff --git a/internal/api/security_token_withdrawal_test.go b/internal/api/security_token_withdrawal_test.go index eefa4ea72b..e56e74cfaf 100644 --- a/internal/api/security_token_withdrawal_test.go +++ b/internal/api/security_token_withdrawal_test.go @@ -69,9 +69,7 @@ func TestSecurityTokenMutationRoutesFollowCallerWithdrawal(t *testing.T) { t.Cleanup(resetAdminBypassState) for _, operation := range []string{"create", "rename", "scope"} { for _, change := range []string{"revoked", "rotated", "scope removed", "expired", "rebound", "owner changed"} { - operation, change := operation, change t.Run(operation+"/"+change, func(t *testing.T) { - t.Parallel() router, cfg, caller, target := tokenWithdrawalFixture(t) method, path, body := http.MethodPatch, "/api/security/tokens/"+target.ID, `{"name":"Current collector"}` if operation == "create" { diff --git a/internal/api/token_stream_lifetime_test.go b/internal/api/token_stream_lifetime_test.go index bd050a46fe..9f3972e807 100644 --- a/internal/api/token_stream_lifetime_test.go +++ b/internal/api/token_stream_lifetime_test.go @@ -264,9 +264,7 @@ func TestProtectedReadStreamsWithdrawAuthority(t *testing.T) { for _, kind := range protectedReadKinds { for _, transport := range []string{"header", "bearer"} { for _, change := range []string{"revoked", "expired", "scope_removed", "org_access_removed", "credential_replaced", "principal_replaced", "invalid_role"} { - kind, transport, change := kind, transport, change t.Run(kind+"/"+transport+"/"+change, func(t *testing.T) { - t.Parallel() scope := config.ScopeSettingsRead if kind == "patrol" { scope = config.ScopeAIExecute @@ -320,9 +318,7 @@ func TestProtectedReadStreamsWithdrawAuthority(t *testing.T) { func TestProtectedReadStreamsDurableDeletion(t *testing.T) { for _, kind := range protectedReadKinds { - kind := kind t.Run(kind, func(t *testing.T) { - t.Parallel() f := newProtectedReadFixture(t, []string{config.ScopeSettingsRead, config.ScopeAIExecute}) primary := f.open(t, kind, scopedReadToken, "header") control := f.open(t, kind, scopedReadControl, "header") @@ -435,9 +431,7 @@ func TestProtectedReadStreamsRetainAdmissionPolicy(t *testing.T) { func TestProtectedReadStreamsKeepOrgAndInstanceSplit(t *testing.T) { for _, kind := range protectedReadKinds { - kind := kind t.Run(kind, func(t *testing.T) { - t.Parallel() f := newProtectedReadFixture(t, []string{config.ScopeSettingsRead, config.ScopeAIExecute}) reader := f.open(t, kind, scopedReadToken, "header") config.Mu.Lock() diff --git a/internal/api/websocket_auth_test.go b/internal/api/websocket_auth_test.go index a9ca3aee0e..b2f955ee7e 100644 --- a/internal/api/websocket_auth_test.go +++ b/internal/api/websocket_auth_test.go @@ -112,9 +112,7 @@ func wantMonitoringWebSocketClosed(t *testing.T, conn *gorillaws.Conn) { func TestMonitoringWebSocketRejectsWithdrawnTokenAuthority(t *testing.T) { for _, transport := range []string{"header", "bearer", "query"} { for _, change := range []string{"revoked", "expired", "read_scope_removed", "org_rebound", "identity_replaced", "principal_replaced", "invalid_role"} { - transport, change := transport, change t.Run(transport+"/"+change, func(t *testing.T) { - t.Parallel() _, cfg, server, hub := newMonitoringWebSocketRouter(t) primary := openMonitoringWebSocket(t, server, monitoringWebSocketToken, transport) control := openMonitoringWebSocket(t, server, monitoringWebSocketControl, transport)