Files
Pulse/internal/api/host_agent_install_token_test.go
rcourtman 5719bd4b7b Stop routers when internal/api tests end
No Router built by the internal/api tests was ever freed. At the end of a run
all 1,358 were still reachable, with 26,000 goroutines and 2.86 GiB live, so
peak memory grew with every new test until the release correctness job ran out
of memory on its 7 GiB runner.

Most test sites never stopped their Router's workers. The few that did were
pinned anyway, because the setup-token cleanup worker in ConfigHandlers had no
way to stop and holds callbacks back into the Router. That worker now joins
the Router's shutdown, and package tests build Routers through newTestRouter,
which stops them with the test. Two new tests fail if a Router stays reachable
after shutdown or a package test calls NewRouter directly.

Default command policies now share one compiled pattern set. A private copy
cost 230 KiB and 1.4 ms per call and is now 2.2 KiB and 1.6 us. It accounted
for a quarter of the live test heap. In production each organization's AI
service holds one, so this also saves about 230 KiB per organization.

Measured on pulse-dev at 88c2a21f65 with the same go test -count=1 -p 1 run:
peak RSS of the largest child 6.41 GiB before, 2.44 GiB after. That largest
child is now the compiler: a cold test build alone peaks at 2.34 GiB and the
test binary alone at 1.48 GiB. All package tests pass. CPU time fell about 5%;
wall clock followed the host's load and is not comparable between these runs.

Contract-Neutral: Stops test Router workers and shares compiled policy patterns; no API, policy decision or storage change.
2026-11-05 11:18:30 +00:00

148 lines
5.5 KiB
Go

package api
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/api/agenttokens"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
)
func decodeHostAgentInstallResponse(t *testing.T, rec *httptest.ResponseRecorder) AgentInstallCommandResponse {
t.Helper()
if rec.Code != http.StatusOK {
t.Fatalf("expected status OK, got %d: %s", rec.Code, rec.Body.String())
}
var resp AgentInstallCommandResponse
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
return resp
}
func TestHandleAgentInstallCommand_HostWithCommands(t *testing.T) {
cfg := &config.Config{DataPath: t.TempDir(), AuthUser: "admin", AuthPass: "hashed-password"}
handler := newTestConfigHandlers(t, cfg)
body := []byte(`{"type":"host","enableCommands":true,"name":"nuc-agent"}`)
req := httptest.NewRequest(http.MethodPost, "/api/agent-install-command", bytes.NewReader(body))
rec := httptest.NewRecorder()
handler.HandleAgentInstallCommand(rec, req)
resp := decodeHostAgentInstallResponse(t, rec)
if resp.Token == "" {
t.Fatalf("expected token in response")
}
if resp.Record == nil {
t.Fatalf("expected token record in response")
}
if resp.Record.Name != "nuc-agent" {
t.Fatalf("expected requested token name, got %q", resp.Record.Name)
}
if len(cfg.APITokens) != 1 {
t.Fatalf("expected API token to be persisted")
}
record := cfg.APITokens[0]
if !record.HasScope(config.ScopeAgentExec) {
t.Fatalf("expected exec scope on commands-enabled host install token, got %v", record.Scopes)
}
if !record.HasScope(config.ScopeDockerReport) || !record.HasScope(config.ScopeAgentReport) {
t.Fatalf("expected reporting scopes on host install token, got %v", record.Scopes)
}
if got := record.Metadata["install_type"]; got != agentInstallTypeHost {
t.Fatalf("install_type metadata = %q, want %q", got, agentInstallTypeHost)
}
if got := record.Metadata["issued_via"]; got != agentInstallIssuedViaConfig {
t.Fatalf("issued_via metadata = %q, want %q", got, agentInstallIssuedViaConfig)
}
if got := record.Metadata[agenttokens.CommandPolicyIntentMetadataKey]; got != "enabled" {
t.Fatalf("command_policy_intent metadata = %q, want enabled", got)
}
if !canBindAgentInstallExecToken(&record, "agent-nuc", "nuc") {
t.Fatalf("expected host install token to be eligible for first-use exec binding")
}
}
func TestHandleAgentInstallCommand_HostWithoutCommands(t *testing.T) {
cfg := &config.Config{DataPath: t.TempDir(), AuthUser: "admin", AuthPass: "hashed-password"}
handler := newTestConfigHandlers(t, cfg)
body := []byte(`{"type":"host","enableCommands":false}`)
req := httptest.NewRequest(http.MethodPost, "/api/agent-install-command", bytes.NewReader(body))
rec := httptest.NewRecorder()
handler.HandleAgentInstallCommand(rec, req)
resp := decodeHostAgentInstallResponse(t, rec)
if resp.Token == "" {
t.Fatalf("expected token in response")
}
if len(cfg.APITokens) != 1 {
t.Fatalf("expected API token to be persisted")
}
record := cfg.APITokens[0]
if record.HasScope(config.ScopeAgentExec) {
t.Fatalf("expected no exec scope without enableCommands, got %v", record.Scopes)
}
if got := record.Metadata[agenttokens.CommandPolicyIntentMetadataKey]; got != "disabled" {
t.Fatalf("command_policy_intent metadata = %q, want disabled", got)
}
}
func TestHandleAgentInstallCommand_HostOmitsTokenWhenAuthOptional(t *testing.T) {
cfg := &config.Config{DataPath: t.TempDir()}
handler := newTestConfigHandlers(t, cfg)
body := []byte(`{"type":"host","enableCommands":true}`)
req := httptest.NewRequest(http.MethodPost, "/api/agent-install-command", bytes.NewReader(body))
rec := httptest.NewRecorder()
handler.HandleAgentInstallCommand(rec, req)
resp := decodeHostAgentInstallResponse(t, rec)
if resp.Token != "" {
t.Fatalf("expected optional-auth host install response to omit token, got %q", resp.Token)
}
if len(cfg.APITokens) != 0 {
t.Fatalf("expected optional-auth host install to avoid persisting API tokens")
}
}
func TestRouterSetupHandoffUsesCanonicalRuntimeConfig(t *testing.T) {
dataDir := t.TempDir()
runtimeConfig := &config.Config{DataPath: dataDir, ConfigPath: dataDir}
monitorConfig := &config.Config{DataPath: dataDir, ConfigPath: dataDir}
monitor, err := monitoring.New(monitorConfig)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(monitor.Stop)
router := newTestRouter(t, runtimeConfig, monitor, nil, nil, func() error { return nil }, "1.0.0")
t.Cleanup(router.shutdownBackgroundWorkers)
// The first-session security setup updates the Router-owned config after
// routes have already been wired. The agent-install handoff must observe
// that same canonical config instead of the monitor's startup snapshot.
config.Mu.Lock()
runtimeConfig.AuthUser = "admin"
runtimeConfig.AuthPass = "hashed-password"
config.Mu.Unlock()
body := []byte(`{"type":"host","enableCommands":false}`)
req := httptest.NewRequest(http.MethodPost, "/api/agent-install-command", bytes.NewReader(body))
rec := httptest.NewRecorder()
router.configHandlers.HandleAgentInstallCommand(rec, req)
resp := decodeHostAgentInstallResponse(t, rec)
if resp.Token == "" || resp.Record == nil {
t.Fatalf("expected setup handoff to create a scoped install token")
}
if got := router.configHandlers.Config(req.Context()); got != runtimeConfig {
t.Fatalf("config handler uses config %#v, want Router config %#v", got, runtimeConfig)
}
}