Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

27.1 KB
Raw Blame
package api

import (
	"bytes"
	"crypto/ed25519"
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"sync"
	"testing"
	"time"

	"github.com/rcourtman/pulse-go-rewrite/internal/config"
	"github.com/rcourtman/pulse-go-rewrite/internal/models"
	"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
	"github.com/rcourtman/pulse-go-rewrite/internal/remoteconfig"
	"github.com/rcourtman/pulse-go-rewrite/internal/utils"
	agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
)

func resetConfigSigningStateForTests() {
	configSigningState = struct {
		once sync.Once
		key  ed25519.PrivateKey
		err  error
	}{}
}

func generateSigningKey(t *testing.T) string {
	t.Helper()

	_, priv := generateSigningKeyPair(t)
	return priv
}

func generateSigningKeyPair(t *testing.T) (string, string) {
	t.Helper()

	_, priv, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatalf("GenerateKey: %v", err)
	}
	return base64.StdEncoding.EncodeToString(priv.Public().(ed25519.PublicKey)), base64.StdEncoding.EncodeToString(priv)
}

func decodeErrorCode(t *testing.T, rec *httptest.ResponseRecorder) string {
	t.Helper()

	var resp struct {
		Code string `json:"code"`
	}
	if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
		t.Fatalf("decode error response: %v", err)
	}
	return resp.Code
}

func TestUnifiedAgentHandlers_HandleReportMethodNotAllowed(t *testing.T) {
	handler := newUnifiedAgentHandlerForTests(t)

	req := httptest.NewRequest(http.MethodGet, "/api/agents/agent/report", nil)
	rec := httptest.NewRecorder()

	handler.HandleReport(rec, req)

	if rec.Code != http.StatusMethodNotAllowed {
		t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)
	}
}

func TestUnifiedAgentHandlers_HandleReportInvalidJSON(t *testing.T) {
	handler := newUnifiedAgentHandlerForTests(t)

	req := httptest.NewRequest(http.MethodPost, "/api/agents/agent/report", bytes.NewBufferString("{"))
	rec := httptest.NewRecorder()

	handler.HandleReport(rec, req)

	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "invalid_json" {
		t.Fatalf("expected error code %q, got %q", "invalid_json", code)
	}
}

func TestUnifiedAgentHandlers_HandleReportInvalidReport(t *testing.T) {
	handler := newUnifiedAgentHandlerForTests(t)

	report := agentshost.Report{
		Agent: agentshost.AgentInfo{ID: "agent-err"},
		Host:  agentshost.HostInfo{Hostname: ""},
	}
	body, _ := json.Marshal(report)

	req := httptest.NewRequest(http.MethodPost, "/api/agents/agent/report", bytes.NewReader(body))
	rec := httptest.NewRecorder()

	handler.HandleReport(rec, req)

	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "invalid_report" {
		t.Fatalf("expected error code %q, got %q", "invalid_report", code)
	}
}

func TestUnifiedAgentHandlers_HandleReportIncludesConfigOverride(t *testing.T) {
	handler, monitor := newUnifiedAgentHandlers(t, nil)

	hostID := "machine-override"
	enabled := true
	if err := monitor.UpdateHostAgentConfig(hostID, &enabled); err != nil {
		t.Fatalf("UpdateHostAgentConfig: %v", err)
	}

	report := agentshost.Report{
		Agent: agentshost.AgentInfo{ID: "agent-override"},
		Host: agentshost.HostInfo{
			ID:       hostID,
			Hostname: "host-override.local",
			Platform: "linux",
		},
	}
	body, _ := json.Marshal(report)

	req := httptest.NewRequest(http.MethodPost, "/api/agents/agent/report", bytes.NewReader(body))
	rec := httptest.NewRecorder()

	handler.HandleReport(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())
	}

	var resp map[string]any
	if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	if resp["agentId"] != hostID {
		t.Fatalf("expected agentId %q, got %#v", hostID, resp["agentId"])
	}
	cfg, ok := resp["config"].(map[string]any)
	if !ok {
		t.Fatalf("expected config override in response")
	}
	if val, ok := cfg["commandsEnabled"].(bool); !ok || !val {
		t.Fatalf("expected commandsEnabled=true, got %#v", cfg["commandsEnabled"])
	}
}

func TestUnifiedAgentHandlers_HandleGzipReportPreservesWideSMARTInventory(t *testing.T) {
	handler, monitor := newUnifiedAgentHandlers(t, nil)
	smart := make([]agentshost.DiskSMART, 128)
	for index := range smart {
		powerOnHours := int64(1000 + index)
		percentageUsed := index % 100
		smart[index] = agentshost.DiskSMART{
			Device:      fmt.Sprintf("sg%d", index),
			Model:       "ST18000NM019J",
			Serial:      fmt.Sprintf("ZR5D%04d", index),
			WWN:         fmt.Sprintf("5-c500-da60-%04d", index),
			Type:        "sas",
			Controller:  fmt.Sprintf("/dev/sg%d", index/24),
			Target:      fmt.Sprintf("sssraid,0,%d", index),
			SizeBytes:   18000207937536,
			Temperature: 30 + index%8,
			Health:      "PASSED",
			Attributes: &agentshost.SMARTAttributes{
				PowerOnHours:   &powerOnHours,
				PercentageUsed: &percentageUsed,
			},
		}
	}
	report := agentshost.Report{
		Agent: agentshost.AgentInfo{ID: "agent-wide", Version: "6.1.1"},
		Host: agentshost.HostInfo{
			ID:       "machine-wide",
			Hostname: "pve-wide.local",
			Platform: "linux",
		},
		Sensors:   agentshost.Sensors{SMART: smart},
		Timestamp: time.Now().UTC(),
	}
	raw, err := json.Marshal(report)
	if err != nil {
		t.Fatalf("marshal wide report: %v", err)
	}
	compressed, err := utils.CompressJSON(raw)
	if err != nil {
		t.Fatalf("compress wide report: %v", err)
	}

	req := httptest.NewRequest(http.MethodPost, "/api/agents/agent/report", bytes.NewReader(compressed))
	req.Header.Set("Content-Encoding", "gzip")
	rec := httptest.NewRecorder()
	handler.HandleReport(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("wide report status = %d, want 200: %s", rec.Code, rec.Body.String())
	}

	hosts := monitor.GetLiveHostsSnapshot()
	if len(hosts) != 1 {
		t.Fatalf("hosts = %d, want 1", len(hosts))
	}
	if got := len(hosts[0].Sensors.SMART); got != len(smart) {
		t.Fatalf("SMART inventory was truncated: got %d disks, want %d", got, len(smart))
	}
	if last := hosts[0].Sensors.SMART[len(smart)-1]; last.Serial != "ZR5D0127" || last.Target != "sssraid,0,127" {
		t.Fatalf("last SMART entry was corrupted or dropped: %+v", last)
	}
}

func TestUnifiedAgentHandlers_HandleReportSuppressesConfigOverrideForUnboundExecToken(t *testing.T) {
	handler, monitor := newUnifiedAgentHandlers(t, nil)

	hostID := "machine-report-unbound"
	enabled := true
	if err := monitor.UpdateHostAgentConfig(hostID, &enabled); err != nil {
		t.Fatalf("UpdateHostAgentConfig: %v", err)
	}

	report := agentshost.Report{
		Agent: agentshost.AgentInfo{ID: "agent-report-unbound"},
		Host: agentshost.HostInfo{
			ID:       hostID,
			Hostname: "host-report-unbound.local",
			Platform: "linux",
		},
	}
	body, _ := json.Marshal(report)

	req := httptest.NewRequest(http.MethodPost, "/api/agents/agent/report", bytes.NewReader(body))
	attachAPITokenRecord(req, &config.APITokenRecord{
		ID:     "install-token",
		Scopes: []string{config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeAgentExec},
	})
	rec := httptest.NewRecorder()

	handler.HandleReport(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())
	}

	var resp map[string]any
	if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	cfg, ok := resp["config"].(map[string]any)
	if !ok {
		t.Fatalf("expected config override in response")
	}
	if val, ok := cfg["commandsEnabled"].(bool); !ok || val {
		t.Fatalf("expected commandsEnabled=false for unbound exec token, got %#v", cfg["commandsEnabled"])
	}
}

func TestUnifiedAgentHandlers_HandleDeleteHostErrors(t *testing.T) {
	handler := newUnifiedAgentHandlerForTests(t)

	req := httptest.NewRequest(http.MethodGet, "/api/agents/agent/host-1", nil)
	rec := httptest.NewRecorder()
	handler.HandleDeleteHost(rec, req)
	if rec.Code != http.StatusMethodNotAllowed {
		t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)
	}

	req = httptest.NewRequest(http.MethodDelete, "/api/agents/agent/", nil)
	rec = httptest.NewRecorder()
	handler.HandleDeleteHost(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "missing_agent_id" {
		t.Fatalf("expected error code %q, got %q", "missing_agent_id", code)
	}
}

func TestUnifiedAgentHandlers_HandleAllowReenrollErrors(t *testing.T) {
	handler := newUnifiedAgentHandlerForTests(t)

	req := httptest.NewRequest(http.MethodGet, "/api/agents/agent/host-1/allow-reenroll", nil)
	rec := httptest.NewRecorder()
	handler.HandleAllowReenroll(rec, req)
	if rec.Code != http.StatusMethodNotAllowed {
		t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)
	}

	req = httptest.NewRequest(http.MethodPost, "/api/agents/agent//allow-reenroll", nil)
	rec = httptest.NewRecorder()
	handler.HandleAllowReenroll(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "missing_agent_id" {
		t.Fatalf("expected error code %q, got %q", "missing_agent_id", code)
	}
}

func TestUnifiedAgentHandlers_HandleConfigErrors(t *testing.T) {
	handler := newUnifiedAgentHandlerForTests(t, models.Host{
		ID:      "host-1",
		TokenID: "token-1",
	})

	req := httptest.NewRequest(http.MethodPost, "/api/agents/agent/host-1/config", nil)
	rec := httptest.NewRecorder()
	handler.HandleConfig(rec, req)
	if rec.Code != http.StatusMethodNotAllowed {
		t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)
	}

	req = httptest.NewRequest(http.MethodGet, "/api/agents/agent//config", nil)
	rec = httptest.NewRecorder()
	handler.HandleConfig(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "missing_agent_id" {
		t.Fatalf("expected error code %q, got %q", "missing_agent_id", code)
	}

	req = httptest.NewRequest(http.MethodGet, "/api/agents/agent/host-1/config", nil)
	attachAPITokenRecord(req, &config.APITokenRecord{
		ID:     "token-2",
		Scopes: []string{config.ScopeAgentConfigRead},
	})
	rec = httptest.NewRecorder()
	handler.HandleConfig(rec, req)
	if rec.Code != http.StatusNotFound {
		t.Fatalf("expected status %d, got %d", http.StatusNotFound, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "agent_not_found" {
		t.Fatalf("expected error code %q, got %q", "agent_not_found", code)
	}
}

func TestUnifiedAgentHandlers_HandleConfigPatchErrors(t *testing.T) {
	handler := newUnifiedAgentHandlerForTests(t)

	req := httptest.NewRequest(http.MethodPatch, "/api/agents/agent/host-1/config", bytes.NewBufferString("{"))
	rec := httptest.NewRecorder()
	handler.HandleConfig(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "invalid_json" {
		t.Fatalf("expected error code %q, got %q", "invalid_json", code)
	}

	req = httptest.NewRequest(http.MethodPatch, "/api/agents/agent/host-1/config", bytes.NewBufferString(`{"commandsEnabled":true}`))
	rec = httptest.NewRecorder()
	handler.HandleConfig(rec, req)
	if rec.Code != http.StatusInternalServerError {
		t.Fatalf("expected status %d, got %d", http.StatusInternalServerError, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "update_failed" {
		t.Fatalf("expected error code %q, got %q", "update_failed", code)
	}
}

func TestUnifiedAgentHandlers_EnsureAgentTokenMatchScopes(t *testing.T) {
	handler := newUnifiedAgentHandlerForTests(t)

	req := httptest.NewRequest(http.MethodGet, "/api/agents/agent/host-1/config", nil)
	attachAPITokenRecord(req, &config.APITokenRecord{
		ID:     "token-1",
		Scopes: []string{config.ScopeWildcard},
	})
	rec := httptest.NewRecorder()
	if ok := handler.ensureAgentTokenMatch(rec, req, "missing"); !ok {
		t.Fatalf("expected wildcard scope to allow access")
	}
	if rec.Code != http.StatusOK {
		t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)
	}

	req = httptest.NewRequest(http.MethodGet, "/api/agents/agent/host-1/config", nil)
	attachAPITokenRecord(req, &config.APITokenRecord{
		ID:     "token-1",
		Scopes: []string{config.ScopeAgentConfigRead},
	})
	rec = httptest.NewRecorder()
	if ok := handler.ensureAgentTokenMatch(rec, req, "missing"); ok {
		t.Fatalf("expected missing host to fail")
	}
	if rec.Code != http.StatusNotFound {
		t.Fatalf("expected status %d, got %d", http.StatusNotFound, rec.Code)
	}
}

func TestUnifiedAgentHandlers_HandleConfigSigningRequiredMissingKey(t *testing.T) {
	handler := newUnifiedAgentHandlerForTests(t, models.Host{ID: "host-1"})

	t.Setenv("PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED", "true")
	t.Setenv("PULSE_AGENT_CONFIG_SIGNING_KEY", "")
	resetConfigSigningStateForTests()
	t.Cleanup(resetConfigSigningStateForTests)

	req := httptest.NewRequest(http.MethodGet, "/api/agents/agent/host-1/config", nil)
	rec := httptest.NewRecorder()
	handler.HandleConfig(rec, req)
	if rec.Code != http.StatusInternalServerError {
		t.Fatalf("expected status %d, got %d", http.StatusInternalServerError, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "config_signing_failed" {
		t.Fatalf("expected error code %q, got %q", "config_signing_failed", code)
	}
}

func TestUnifiedAgentHandlers_HandleConfigSigningSuccess(t *testing.T) {
	handler := newUnifiedAgentHandlerForTests(t, models.Host{ID: "host-1"})

	t.Setenv("PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED", "true")
	t.Setenv("PULSE_AGENT_CONFIG_SIGNING_KEY", generateSigningKey(t))
	resetConfigSigningStateForTests()
	t.Cleanup(resetConfigSigningStateForTests)

	req := httptest.NewRequest(http.MethodGet, "/api/agents/agent/host-1/config", nil)
	rec := httptest.NewRecorder()
	handler.HandleConfig(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)
	}

	var resp struct {
		Success bool                       `json:"success"`
		AgentID string                     `json:"agentId"`
		Config  monitoring.HostAgentConfig `json:"config"`
	}
	if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	if resp.AgentID != "host-1" {
		t.Fatalf("expected agentId %q, got %q", "host-1", resp.AgentID)
	}
	if resp.Config.Signature == "" {
		t.Fatalf("expected config signature to be set")
	}
	if resp.Config.IssuedAt == nil || resp.Config.ExpiresAt == nil {
		t.Fatalf("expected issuedAt/expiresAt to be set")
	}
	if !resp.Config.ExpiresAt.After(*resp.Config.IssuedAt) {
		t.Fatalf("expected expiresAt after issuedAt")
	}
}

func TestUnifiedAgentHandlers_HandleConfigSignsDesiredMetadata(t *testing.T) {
	handler, monitor := newUnifiedAgentHandlers(t, nil)
	hostID := seedUnifiedAgentHost(t, monitor)

	commandsEnabled := true
	if err := monitor.UpdateHostAgentConfig(hostID, &commandsEnabled); err != nil {
		t.Fatalf("UpdateHostAgentConfig: %v", err)
	}

	publicKey, privateKey := generateSigningKeyPair(t)
	t.Setenv("PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED", "true")
	t.Setenv("PULSE_AGENT_CONFIG_SIGNING_KEY", privateKey)
	t.Setenv("PULSE_AGENT_CONFIG_PUBLIC_KEYS", publicKey)
	resetConfigSigningStateForTests()
	t.Cleanup(resetConfigSigningStateForTests)

	req := httptest.NewRequest(http.MethodGet, "/api/agents/agent/"+hostID+"/config", nil)
	rec := httptest.NewRecorder()
	handler.HandleConfig(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())
	}

	var resp struct {
		Success bool                       `json:"success"`
		AgentID string                     `json:"agentId"`
		Config  monitoring.HostAgentConfig `json:"config"`
	}
	if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	if resp.AgentID != hostID {
		t.Fatalf("expected agentId %q, got %q", hostID, resp.AgentID)
	}
	if resp.Config.DesiredConfig == nil {
		t.Fatalf("expected desired config metadata")
	}
	expected, err := remoteconfig.BuildDesiredConfigMetadata(resp.Config.CommandsEnabled, resp.Config.Settings)
	if err != nil {
		t.Fatalf("BuildDesiredConfigMetadata: %v", err)
	}
	if *resp.Config.DesiredConfig != expected {
		t.Fatalf("desired config metadata = %#v, want %#v", *resp.Config.DesiredConfig, expected)
	}
	if resp.Config.Signature == "" || resp.Config.IssuedAt == nil || resp.Config.ExpiresAt == nil {
		t.Fatalf("expected signature and timestamps")
	}

	payload := remoteconfig.SignedConfigPayload{
		AgentID:         resp.AgentID,
		IssuedAt:        *resp.Config.IssuedAt,
		ExpiresAt:       *resp.Config.ExpiresAt,
		CommandsEnabled: resp.Config.CommandsEnabled,
		Settings:        resp.Config.Settings,
	}
	if err := remoteconfig.VerifyConfigPayloadSignature(payload, resp.Config.Signature); err != nil {
		t.Fatalf("VerifyConfigPayloadSignature: %v", err)
	}
}

func TestUnifiedAgentHandlers_HandleConfigSuppressesCommandsForUnboundExecToken(t *testing.T) {
	handler, monitor := newUnifiedAgentHandlers(t, nil)
	hostID := seedUnifiedAgentHost(t, monitor)
	state := monitorState(t, monitor)
	state.UpsertHost(models.Host{
		ID:       hostID,
		Hostname: "host-1.local",
		TokenID:  "install-token",
	})

	commandsEnabled := true
	if err := monitor.UpdateHostAgentConfig(hostID, &commandsEnabled); err != nil {
		t.Fatalf("UpdateHostAgentConfig: %v", err)
	}

	req := httptest.NewRequest(http.MethodGet, "/api/agents/agent/"+hostID+"/config", nil)
	attachAPITokenRecord(req, &config.APITokenRecord{
		ID:     "install-token",
		Scopes: []string{config.ScopeAgentConfigRead, config.ScopeAgentReport, config.ScopeAgentExec},
	})
	rec := httptest.NewRecorder()
	handler.HandleConfig(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())
	}

	var resp struct {
		Config monitoring.HostAgentConfig `json:"config"`
	}
	if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	if resp.Config.CommandsEnabled == nil || *resp.Config.CommandsEnabled {
		t.Fatalf("commandsEnabled = %+v, want false for unbound exec token", resp.Config.CommandsEnabled)
	}
}

func TestUnifiedAgentHandlers_HandleConfigPreservesCommandsForBoundExecToken(t *testing.T) {
	handler, monitor := newUnifiedAgentHandlers(t, nil)
	hostID := seedUnifiedAgentHost(t, monitor)
	state := monitorState(t, monitor)
	state.UpsertHost(models.Host{
		ID:       hostID,
		Hostname: "host-1.local",
		TokenID:  "runtime-token",
	})

	commandsEnabled := true
	if err := monitor.UpdateHostAgentConfig(hostID, &commandsEnabled); err != nil {
		t.Fatalf("UpdateHostAgentConfig: %v", err)
	}

	req := httptest.NewRequest(http.MethodGet, "/api/agents/agent/"+hostID+"/config", nil)
	attachAPITokenRecord(req, &config.APITokenRecord{
		ID:     "runtime-token",
		Scopes: []string{config.ScopeAgentConfigRead, config.ScopeAgentReport, config.ScopeAgentExec},
		Metadata: map[string]string{
			"bound_hostname": "host-1.local",
		},
	})
	rec := httptest.NewRecorder()
	handler.HandleConfig(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())
	}

	var resp struct {
		Config monitoring.HostAgentConfig `json:"config"`
	}
	if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	if resp.Config.CommandsEnabled == nil || !*resp.Config.CommandsEnabled {
		t.Fatalf("commandsEnabled = %+v, want true for bound exec token", resp.Config.CommandsEnabled)
	}
}

func TestUnifiedAgentHandlers_HandleConfigPreservesCommandsForFirstUseProxmoxInstallToken(t *testing.T) {
	handler, monitor := newUnifiedAgentHandlers(t, nil)
	hostID := seedUnifiedAgentHost(t, monitor)
	state := monitorState(t, monitor)
	state.UpsertHost(models.Host{
		ID:       hostID,
		Hostname: "pve-1",
		TokenID:  "proxmox-install-token",
	})

	commandsEnabled := true
	if err := monitor.UpdateHostAgentConfig(hostID, &commandsEnabled); err != nil {
		t.Fatalf("UpdateHostAgentConfig: %v", err)
	}

	req := httptest.NewRequest(http.MethodGet, "/api/agents/agent/"+hostID+"/config", nil)
	attachAPITokenRecord(req, &config.APITokenRecord{
		ID:     "proxmox-install-token",
		Scopes: []string{config.ScopeAgentConfigRead, config.ScopeAgentReport, config.ScopeAgentExec},
		Metadata: map[string]string{
			"install_type": proxmoxInstallTypePVE,
			"issued_via":   agentInstallIssuedViaConfig,
		},
	})
	rec := httptest.NewRecorder()
	handler.HandleConfig(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())
	}

	var resp struct {
		Config monitoring.HostAgentConfig `json:"config"`
	}
	if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	if resp.Config.CommandsEnabled == nil || !*resp.Config.CommandsEnabled {
		t.Fatalf("commandsEnabled = %+v, want true for first-use Proxmox install token", resp.Config.CommandsEnabled)
	}
}

func TestUnifiedAgentHandlers_HandleConfigInvalidKeyAllowed(t *testing.T) {
	handler := newUnifiedAgentHandlerForTests(t, models.Host{ID: "host-1"})

	t.Setenv("PULSE_AGENT_CONFIG_SIGNATURE_REQUIRED", "false")
	t.Setenv("PULSE_AGENT_CONFIG_SIGNING_KEY", "not-base64")
	resetConfigSigningStateForTests()
	t.Cleanup(resetConfigSigningStateForTests)

	req := httptest.NewRequest(http.MethodGet, "/api/agents/agent/host-1/config", nil)
	rec := httptest.NewRecorder()
	handler.HandleConfig(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)
	}

	var resp struct {
		Config monitoring.HostAgentConfig `json:"config"`
	}
	if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	if resp.Config.Signature != "" {
		t.Fatalf("expected no signature when signing key is invalid")
	}
	if resp.Config.IssuedAt != nil || resp.Config.ExpiresAt != nil {
		t.Fatalf("expected no issuedAt/expiresAt when signing key is invalid")
	}
}

func TestUnifiedAgentHandlers_HandleUninstallErrors(t *testing.T) {
	handler := newUnifiedAgentHandlerForTests(t)

	req := httptest.NewRequest(http.MethodGet, "/api/agents/agent/uninstall", nil)
	rec := httptest.NewRecorder()
	handler.HandleUninstall(rec, req)
	if rec.Code != http.StatusMethodNotAllowed {
		t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)
	}

	req = httptest.NewRequest(http.MethodPost, "/api/agents/agent/uninstall", bytes.NewBufferString("{"))
	rec = httptest.NewRecorder()
	handler.HandleUninstall(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "invalid_json" {
		t.Fatalf("expected error code %q, got %q", "invalid_json", code)
	}

	req = httptest.NewRequest(http.MethodPost, "/api/agents/agent/uninstall", bytes.NewBufferString(`{"agentId":""}`))
	rec = httptest.NewRecorder()
	handler.HandleUninstall(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "missing_agent_id" {
		t.Fatalf("expected error code %q, got %q", "missing_agent_id", code)
	}
}

func TestUnifiedAgentHandlers_HandleUninstallMissingHostStillSucceeds(t *testing.T) {
	handler, _ := newUnifiedAgentHandlers(t, nil)

	req := httptest.NewRequest(http.MethodPost, "/api/agents/agent/uninstall", bytes.NewBufferString(`{"agentId":"missing"}`))
	rec := httptest.NewRecorder()
	handler.HandleUninstall(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)
	}
}

func TestUnifiedAgentHandlers_HandleLinkUnlinkErrors(t *testing.T) {
	handler := newUnifiedAgentHandlerForTests(t)

	req := httptest.NewRequest(http.MethodGet, "/api/agents/agent/link", nil)
	rec := httptest.NewRecorder()
	handler.HandleLink(rec, req)
	if rec.Code != http.StatusMethodNotAllowed {
		t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)
	}

	req = httptest.NewRequest(http.MethodPost, "/api/agents/agent/link", bytes.NewBufferString("{"))
	rec = httptest.NewRecorder()
	handler.HandleLink(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "invalid_json" {
		t.Fatalf("expected error code %q, got %q", "invalid_json", code)
	}

	req = httptest.NewRequest(http.MethodPost, "/api/agents/agent/link", bytes.NewBufferString(`{"agentId":"","nodeId":"node-1"}`))
	rec = httptest.NewRecorder()
	handler.HandleLink(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "missing_agent_id" {
		t.Fatalf("expected error code %q, got %q", "missing_agent_id", code)
	}

	req = httptest.NewRequest(http.MethodPost, "/api/agents/agent/link", bytes.NewBufferString(`{"agentId":"host-1","nodeId":""}`))
	rec = httptest.NewRecorder()
	handler.HandleLink(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "missing_node_id" {
		t.Fatalf("expected error code %q, got %q", "missing_node_id", code)
	}

	req = httptest.NewRequest(http.MethodPost, "/api/agents/agent/link", bytes.NewBufferString(`{"agentId":"host-1","nodeId":"node-1"}`))
	rec = httptest.NewRecorder()
	handler.HandleLink(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "link_failed" {
		t.Fatalf("expected error code %q, got %q", "link_failed", code)
	}

	req = httptest.NewRequest(http.MethodGet, "/api/agents/agent/unlink", nil)
	rec = httptest.NewRecorder()
	handler.HandleUnlink(rec, req)
	if rec.Code != http.StatusMethodNotAllowed {
		t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, rec.Code)
	}

	req = httptest.NewRequest(http.MethodPost, "/api/agents/agent/unlink", bytes.NewBufferString("{"))
	rec = httptest.NewRecorder()
	handler.HandleUnlink(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "invalid_json" {
		t.Fatalf("expected error code %q, got %q", "invalid_json", code)
	}

	req = httptest.NewRequest(http.MethodPost, "/api/agents/agent/unlink", bytes.NewBufferString(`{"agentId":""}`))
	rec = httptest.NewRecorder()
	handler.HandleUnlink(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "missing_agent_id" {
		t.Fatalf("expected error code %q, got %q", "missing_agent_id", code)
	}

	req = httptest.NewRequest(http.MethodPost, "/api/agents/agent/unlink", bytes.NewBufferString(`{"agentId":"missing"}`))
	rec = httptest.NewRecorder()
	handler.HandleUnlink(rec, req)
	if rec.Code != http.StatusNotFound {
		t.Fatalf("expected status %d, got %d", http.StatusNotFound, rec.Code)
	}
	if code := decodeErrorCode(t, rec); code != "unlink_failed" {
		t.Fatalf("expected error code %q, got %q", "unlink_failed", code)
	}
}