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.

Fix Proxmox agent registration authorization flow

rcourtmanb4877b4b4439
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index cfe9177ef2..d35ebd147c 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -2030,6 +2030,12 @@ Agent` secondary handoff against the live setup wizard instead of relying
rollback, progress errors, and durable reconnect replay. The opt-in live
Docker Compose proof must exercise those network modes against a real
daemon; a fake-only sanitizer test is not sufficient lifecycle evidence.
+21. Keep Proxmox runtime health and bootstrap authority separate. Agent-token
+ startup and periodic registration checks must call `/api/auto-register`
+ directly; `/api/setup-script-url` remains `settings:write`. Ordinary agent
+ tokens stay update-only, while a server-minted PVE/PBS install token may
+ consume one declared-type initial registration after durable first-host
+ binding and serialized completion.
## Current State
@@ -5002,3 +5008,45 @@ That handoff is lifecycle continuity only: it prevents post-reload agent
reports and resource projection from observing an orphaned metadata cache, and
does not add a report shape, credential, command, or remote-configuration
authority.
+
+### Proxmox install bootstrap and runtime-health authority
+
+The Proxmox Unified Agent has one canonical runtime registration surface:
+`/api/auto-register`. When the agent already has an API token, startup checks,
+five-minute health checks, token repair, re-registration, and URL-candidate
+changes must authenticate directly to that endpoint. They must not probe
+`/api/setup-script-url` to discover whether the runtime token can mint a setup
+artifact. That endpoint remains an operator control-plane surface protected by
+`settings:write`; an expected denial there is not part of a healthy runtime
+control flow.
+
+Registration checks return separate `registered`, `sourceExists`, and
+`canRegister` facts. A disconnected configured source can therefore be repaired,
+while a removed source paired with an ordinary agent token leaves local
+credentials untouched and directs the operator to run a fresh install command.
+Agents treat the two capability fields as permissive only when talking to an
+older server that omits them during a rolling update.
+
+Ordinary `agent:report` tokens remain limited to registration checks and token
+updates for existing PVE/PBS sources. The PVE/PBS token minted by the
+settings-authorized agent-install command carries a narrower bootstrap
+exception: its server-owned `install_type` and `issued_via` metadata may create
+one source of the declared type. The server binds that grant to the first
+fully validated presenting hostname before local Proxmox credentials are
+mutated, serializes checks with completion, persists the completed type,
+hostname, selected host, node, and time, and then permanently returns the token
+to update-only behavior. A malformed request, wrong type, different hostname,
+reused grant, rejected/rotated token, or arbitrary agent token must fail closed
+with visible authorization diagnostics.
+A positive registration preflight for an already-existing source consumes the
+fresh-install grant without rotating local credentials; a negative preflight
+keeps it available for the immediately following initial completion.
+
+Token-optional installations retain the setup-token bootstrap path. Ordinary
+hosts never enter this Proxmox registration loop, while PVE, PBS, mixed-product
+hosts, restarts, and hosted-tenant install tokens retain the same authority
+split. `internal/hostagent/proxmox_setup_test.go`,
+`internal/api/config_handlers_auto_register_test.go`, and
+`internal/api/proxmox_install_registration_test.go` prove the recurring health,
+first-install, type/host binding, one-time consumption, rejection, and
+concurrent-completion contracts.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 2df817cd99..028120cae7 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -3581,6 +3581,14 @@ off with context, or intentionally has no mobile surface. A `mobile-required`
change is incomplete while either generated projection or the mobile consumer
contract is stale.
+Proxmox runtime registration checks and completions must use the canonical
+`/api/auto-register` transport with `X-API-Token`; the admin-only
+`/api/setup-script-url` route is not a runtime probe. Ordinary
+`agent:report` tokens remain update-only. Only a server-authored config/hosted
+PVE/PBS install token may create one matching source, after durable first-host
+binding, and completion must consume that grant under the serialized
+auto-register mutation boundary.
+
## Current State
### vSphere host composition on the vCenter system row
@@ -8208,3 +8216,40 @@ real router middleware, token persistence/reload, monitor reconstruction,
delete and config handlers, generated install token, alias re-enrollment, and
shared-token isolation. It is the production-path contract proof alongside the
monitoring race and continuity-store tests.
+
+### Proxmox auto-register authorization transport
+
+`POST /api/auto-register` is the sole runtime transport for Unified Agent
+Proxmox registration checks and completions. A caller with a runtime API token
+uses `X-API-Token` directly and omits body `authToken`; body `authToken` remains
+the one-time setup-script/bootstrap transport for token-optional or manual
+setup flows. `/api/setup-script-url` continues to require `settings:write` and
+must not be treated as a runtime capability-probing endpoint.
+
+An authenticated `agent:report` token can read registration state and update
+credentials on a matching existing PVE/PBS source. Only an unused install token
+minted through the config or hosted agent-install command may create a new
+source, and only when its server-authored `install_type` matches. First use
+binds the token after request validation to the presenting hostname; successful
+serialized completion persists consumption and registration identity metadata.
+Malformed requests do not bind the grant. Reuse, cross-type or cross-host use,
+and ordinary agent tokens return `403` for a missing source.
+Authentication failure at the canonical endpoint remains a warning/error
+diagnostic rather than being suppressed as an expected setup-artifact denial.
+
+The registration-check response distinguishes `registered` (the source is
+currently healthy), `sourceExists` (matching persisted configuration exists),
+and `canRegister` (this caller may complete a repair or bootstrap). Current
+agents do not rotate local credentials when a source is missing and
+`canRegister` is false; for rolling-update compatibility, they preserve the
+legacy repair behavior when an older server omits the two newer fields.
+
+Negative `checkRegistration` calls do not consume the install grant; a positive
+match consumes an otherwise-unneeded fresh-install grant so reinstalling an
+already-registered source cannot leave dormant creation authority. Successful
+steady-state authentication/processing emits only at debug severity.
+`internal/api/config_handlers_auto_register_test.go`,
+`internal/api/proxmox_install_registration_test.go`, and
+`internal/hostagent/proxmox_setup_test.go` prove the wire headers, omitted
+setup credential, one-time bootstrap, concurrency, and rejected-token
+diagnostics.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index c7c645102c..c2e26a0a34 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -1863,6 +1863,11 @@ must not treat starter
tolerate absent notification managers and other optional runtime managers
so adjacent browser surfaces inherit a fail-closed API response instead of
a panic after the archive import succeeds.
+25. Treat the shared Proxmox auto-register authority split as lifecycle/API
+ context only. Direct agent-token health checks and a one-time,
+ server-minted install registration grant must not widen backup, snapshot,
+ restore, retention, replication, datastore-management, or recovery-policy
+ authority.
### Attention posture join
@@ -4468,6 +4473,17 @@ Browser-facing storage/recovery surfaces must also treat
`/api/security/status.sessionCapabilities.demoMode` as the canonical
public-demo bootstrap signal instead of inferring demo posture from headers,
`/api/health`, or hostname heuristics.
+
+### Adjacent Proxmox registration authorization neutrality
+
+The shared `internal/api/config_setup_handlers.go` Proxmox registration fix is
+adjacent lifecycle/API authority only. Runtime agents now use
+`/api/auto-register` directly, ordinary agent tokens remain update-only, and a
+server-minted Proxmox install token may consume one type- and host-bound initial
+source grant. This does not grant backup, snapshot, restore, retention,
+replication, datastore-management, or recovery-policy authority. The
+`settings:write` boundary on setup-artifact generation and all existing
+storage/recovery permission and evidence contracts remain unchanged.
That same adjacent platform-connections boundary now also assumes direct
TrueNAS and VMware connection writes fail closed while canonical
monitored-system usage is unavailable. Storage and recovery may depend on the
diff --git a/internal/api/config_handlers.go b/internal/api/config_handlers.go
index 848b6f8ed3..8a2e2ca1f3 100644
--- a/internal/api/config_handlers.go
+++ b/internal/api/config_handlers.go
@@ -213,6 +213,7 @@ type ConfigHandlers struct {
lastClusterDetection map[string]time.Time
recentAutoRegistered map[string]time.Time
recentAutoRegMutex sync.Mutex
+ autoRegisterMutex sync.Mutex
}
// NewConfigHandlers creates a new ConfigHandlers instance
diff --git a/internal/api/config_handlers_auto_register_test.go b/internal/api/config_handlers_auto_register_test.go
index a38c2a9200..1bdc203c63 100644
--- a/internal/api/config_handlers_auto_register_test.go
+++ b/internal/api/config_handlers_auto_register_test.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "strings"
"testing"
"time"
@@ -36,6 +37,43 @@ func newTestConfigHandlers(t *testing.T, cfg *config.Config) *ConfigHandlers {
return h
}
+func TestHandleAutoRegisterProxmoxInstallCheckBindsWithoutConsumingGrant(t *testing.T) {
+ rawToken := "proxmox-install-check.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeAgentReport}, map[string]string{
+ "install_type": "pve",
+ "issued_via": agentInstallIssuedViaConfig,
+ })
+ cfg := &config.Config{
+ DataPath: t.TempDir(),
+ APITokens: []config.APITokenRecord{record},
+ }
+ handler := newTestConfigHandlers(t, cfg)
+
+ rec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{
+ Type: "pve",
+ Host: "https://pve-install.local:8006",
+ ServerName: "pve-install",
+ Source: "agent",
+ CheckRegistration: true,
+ })
+ if rec.Code != http.StatusOK {
+ t.Fatalf("registration check status = %d, body=%s", rec.Code, rec.Body.String())
+ }
+ var response autoRegisterCheckResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode registration check: %v", err)
+ }
+ if response.Registered || response.SourceExists || !response.CanRegister {
+ t.Fatalf("fresh install registration check = %#v, want missing source with completion authority", response)
+ }
+ if got := cfg.APITokens[0].Metadata["bound_hostname"]; got != "pve-install" {
+ t.Fatalf("bound hostname = %q, want pve-install", got)
+ }
+ if strings.EqualFold(cfg.APITokens[0].Metadata[proxmoxInstallRegistrationCompletedKey], "true") {
+ t.Fatal("read-only registration check consumed the one-time install grant")
+ }
+}
+
func TestHandleAutoRegisterRejectsWithoutAuth(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", tempDir)
diff --git a/internal/api/config_setup_handlers.go b/internal/api/config_setup_handlers.go
index f70c36c79b..af32338935 100644
--- a/internal/api/config_setup_handlers.go
+++ b/internal/api/config_setup_handlers.go
@@ -29,12 +29,187 @@ import (
)
// agentAutoRegContextKey marks a request authenticated via agent:report token.
-// When set, handleCanonicalAutoRegister restricts to updating existing nodes only.
+// Ordinary runtime tokens remain update-only. A Proxmox install token minted by
+// a settings:write endpoint may additionally carry one bounded, one-time grant
+// to create the declared PVE/PBS source.
type agentAutoRegContextKey struct{}
+type agentAutoRegAuth struct {
+ tokenID string
+ installBootstrap bool
+}
+
+func getAgentAutoRegAuth(ctx context.Context) (agentAutoRegAuth, bool) {
+ v, ok := ctx.Value(agentAutoRegContextKey{}).(agentAutoRegAuth)
+ return v, ok
+}
+
func isAgentAutoRegAuth(ctx context.Context) bool {
- v, _ := ctx.Value(agentAutoRegContextKey{}).(bool)
- return v
+ _, ok := getAgentAutoRegAuth(ctx)
+ return ok
+}
+
+const (
+ proxmoxInstallRegistrationCompletedKey = "proxmox_registration_completed"
+ proxmoxInstallRegistrationTypeKey = "proxmox_registration_type"
+ proxmoxInstallRegistrationHostnameKey = "proxmox_registration_hostname"
+ proxmoxInstallRegistrationHostKey = "proxmox_registration_host"
+ proxmoxInstallRegistrationNodeKey = "proxmox_registration_node"
+ proxmoxInstallRegistrationAtKey = "proxmox_registration_at"
+)
+
+func canBootstrapProxmoxInstallRegistration(record *config.APITokenRecord, req *AutoRegisterRequest) bool {
+ if record == nil || req == nil || strings.TrimSpace(req.Source) != "agent" {
+ return false
+ }
+ if strings.EqualFold(strings.TrimSpace(record.Metadata[proxmoxInstallRegistrationCompletedKey]), "true") {
+ return false
+ }
+ if strings.TrimSpace(record.Metadata["install_type"]) != strings.TrimSpace(req.Type) {
+ return false
+ }
+ switch strings.TrimSpace(record.Metadata["issued_via"]) {
+ case agentInstallIssuedViaConfig, agentInstallIssuedViaHosted:
+ default:
+ return false
+ }
+ requestedHostname := strings.TrimSpace(req.ServerName)
+ if requestedHostname == "" {
+ return false
+ }
+ if boundHostname := strings.TrimSpace(record.Metadata["bound_hostname"]); boundHostname != "" {
+ return strings.EqualFold(boundHostname, requestedHostname)
+ }
+ return true
+}
+
+func completedProxmoxInstallRegistrationMatches(record *config.APITokenRecord, req *AutoRegisterRequest) bool {
+ if record == nil || req == nil ||
+ !strings.EqualFold(strings.TrimSpace(record.Metadata[proxmoxInstallRegistrationCompletedKey]), "true") {
+ return false
+ }
+ return strings.TrimSpace(record.Metadata[proxmoxInstallRegistrationTypeKey]) == strings.TrimSpace(req.Type) &&
+ strings.EqualFold(
+ strings.TrimSpace(record.Metadata[proxmoxInstallRegistrationHostnameKey]),
+ strings.TrimSpace(req.ServerName),
+ )
+}
+
+// prepareProxmoxInstallBootstrap binds an unused install token to the first
+// fully validated host request that presents it.
+func (h *ConfigHandlers) prepareProxmoxInstallBootstrap(ctx context.Context, req *AutoRegisterRequest) (bool, error) {
+ auth, ok := getAgentAutoRegAuth(ctx)
+ if !ok || !auth.installBootstrap || strings.TrimSpace(auth.tokenID) == "" {
+ return false, nil
+ }
+
+ config.Mu.Lock()
+ defer config.Mu.Unlock()
+
+ cfg := h.getConfig(ctx)
+ if cfg == nil {
+ return false, fmt.Errorf("configuration unavailable")
+ }
+ for i := range cfg.APITokens {
+ record := &cfg.APITokens[i]
+ if record.ID != auth.tokenID {
+ continue
+ }
+ if !canBootstrapProxmoxInstallRegistration(record, req) {
+ return false, nil
+ }
+ if strings.TrimSpace(record.Metadata["bound_hostname"]) != "" {
+ return true, nil
+ }
+
+ if record.Metadata == nil {
+ record.Metadata = make(map[string]string)
+ }
+ previousMetadata := make(map[string]string, len(record.Metadata))
+ for key, value := range record.Metadata {
+ previousMetadata[key] = value
+ }
+ record.Metadata["bound_hostname"] = strings.TrimSpace(req.ServerName)
+ record.Metadata["bound_at"] = time.Now().UTC().Format(time.RFC3339)
+ if persistence := h.getPersistence(ctx); persistence != nil {
+ if err := persistence.SaveAPITokens(cfg.APITokens); err != nil {
+ record.Metadata = previousMetadata
+ return false, fmt.Errorf("persist Proxmox install token host binding: %w", err)
+ }
+ }
+ return true, nil
+ }
+ return false, fmt.Errorf("Proxmox install token no longer exists")
+}
+
+func (h *ConfigHandlers) proxmoxInstallBootstrapAvailable(ctx context.Context, req *AutoRegisterRequest) bool {
+ auth, ok := getAgentAutoRegAuth(ctx)
+ if !ok || !auth.installBootstrap || strings.TrimSpace(auth.tokenID) == "" {
+ return false
+ }
+
+ config.Mu.RLock()
+ defer config.Mu.RUnlock()
+ cfg := h.getConfig(ctx)
+ if cfg == nil {
+ return false
+ }
+ for i := range cfg.APITokens {
+ record := &cfg.APITokens[i]
+ if record.ID == auth.tokenID {
+ return canBootstrapProxmoxInstallRegistration(record, req)
+ }
+ }
+ return false
+}
+
+func (h *ConfigHandlers) completeProxmoxInstallBootstrap(ctx context.Context, req *AutoRegisterRequest, host, node string) error {
+ auth, ok := getAgentAutoRegAuth(ctx)
+ if !ok || !auth.installBootstrap || strings.TrimSpace(auth.tokenID) == "" {
+ return nil
+ }
+
+ persistence := h.getPersistence(ctx)
+ config.Mu.Lock()
+ defer config.Mu.Unlock()
+
+ cfg := h.getConfig(ctx)
+ if cfg == nil {
+ return fmt.Errorf("configuration unavailable")
+ }
+ for i := range cfg.APITokens {
+ record := &cfg.APITokens[i]
+ if record.ID != auth.tokenID {
+ continue
+ }
+ if completedProxmoxInstallRegistrationMatches(record, req) {
+ return nil
+ }
+ if !canBootstrapProxmoxInstallRegistration(record, req) {
+ return fmt.Errorf("Proxmox install registration grant is no longer available")
+ }
+ if record.Metadata == nil {
+ record.Metadata = make(map[string]string)
+ }
+ previousMetadata := make(map[string]string, len(record.Metadata))
+ for key, value := range record.Metadata {
+ previousMetadata[key] = value
+ }
+ record.Metadata[proxmoxInstallRegistrationCompletedKey] = "true"
+ record.Metadata[proxmoxInstallRegistrationTypeKey] = strings.TrimSpace(req.Type)
+ record.Metadata[proxmoxInstallRegistrationHostnameKey] = strings.TrimSpace(req.ServerName)
+ record.Metadata[proxmoxInstallRegistrationHostKey] = strings.TrimSpace(host)
+ record.Metadata[proxmoxInstallRegistrationNodeKey] = strings.TrimSpace(node)
+ record.Metadata[proxmoxInstallRegistrationAtKey] = time.Now().UTC().Format(time.RFC3339)
+ if persistence != nil {
+ if err := persistence.SaveAPITokens(cfg.APITokens); err != nil {
+ record.Metadata = previousMetadata
+ return fmt.Errorf("persist Proxmox install registration grant: %w", err)
+ }
+ }
+ return nil
+ }
+ return fmt.Errorf("Proxmox install token no longer exists")
}
// HandleSetupScript serves the setup script for Proxmox/PBS nodes
@@ -865,7 +1040,9 @@ func (h *ConfigHandlers) notifyAutoUnregisterSuccess(ctx context.Context, req *A
}
type autoRegisterCheckResponse struct {
- Registered bool `json:"registered"`
+ Registered bool `json:"registered"`
+ SourceExists bool `json:"sourceExists"`
+ CanRegister bool `json:"canRegister"`
}
func autoRegisterHostMatchesCandidates(existingHost string, candidates []string) bool {
@@ -959,6 +1136,31 @@ func (h *ConfigHandlers) autoRegisteredNodeExists(ctx context.Context, req *Auto
return false
}
+func (h *ConfigHandlers) autoRegisteredNodeConfigured(ctx context.Context, req *AutoRegisterRequest, candidates []string) bool {
+ if req == nil {
+ return false
+ }
+ cfg := h.getConfig(ctx)
+ if cfg == nil {
+ return false
+ }
+ switch req.Type {
+ case "pve":
+ for _, node := range cfg.PVEInstances {
+ if matched, _ := autoRegisterPVEInstanceMatchesCandidates(node, candidates); matched {
+ return true
+ }
+ }
+ case "pbs":
+ for _, node := range cfg.PBSInstances {
+ if autoRegisterHostMatchesCandidates(node.Host, candidates) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
// isKnownDisconnected reports whether the monitor has a definitive "unhealthy"
// entry for the given instance. Returns false (i.e., assume connected) when
// there is no monitor data yet so we don't mistakenly trigger re-registration
@@ -1280,20 +1482,16 @@ func (h *ConfigHandlers) handleAutoRegister(w http.ResponseWriter, r *http.Reque
h.codeMutex.Unlock()
}
- // Fallback: allow agents with a valid agent:report API token to re-register their
- // Proxmox node. This is needed when an agent reinstalls — it rotates the PVE token
- // but can't fetch a one-time setup token (that endpoint requires settings:write).
- // For security this path is restricted to updating existing nodes only.
+ // Fallback: allow agents with a valid agent:report API token to re-register
+ // an existing Proxmox node. Ordinary tokens remain update-only. A
+ // settings-authorized Proxmox install token may additionally bootstrap one
+ // source of its declared type, bound to the first presenting hostname.
if !authenticated {
if apiToken, hasToken := explicitAPITokenFromRequest(r); hasToken {
- config.Mu.RLock()
+ config.Mu.Lock()
cfg := h.getConfig(r.Context())
- isValid := cfg != nil && cfg.IsValidAPIToken(apiToken)
- config.Mu.RUnlock()
- if isValid {
- config.Mu.Lock()
+ if cfg != nil {
record, ok := cfg.ValidateAPIToken(apiToken)
- config.Mu.Unlock()
if ok && record != nil && record.HasScope(config.ScopeAgentReport) {
// Reject cross-org tokens: if the request context has an explicit
// non-default org, the token must belong to that same org.
@@ -1301,15 +1499,29 @@ func (h *ConfigHandlers) handleAutoRegister(w http.ResponseWriter, r *http.Reque
orgMismatch := requestOrgID != "" && requestOrgID != "default" &&
record.OrgID != "" && record.OrgID != requestOrgID
if !orgMismatch {
+ installBootstrap := canBootstrapProxmoxInstallRegistration(record, &req)
authenticated = true
- r = r.WithContext(context.WithValue(r.Context(), agentAutoRegContextKey{}, true))
- log.Info().
+ r = r.WithContext(context.WithValue(r.Context(), agentAutoRegContextKey{}, agentAutoRegAuth{
+ tokenID: record.ID,
+ installBootstrap: installBootstrap,
+ }))
+ event := log.Info()
+ if req.CheckRegistration {
+ event = log.Debug()
+ }
+ message := "Auto-register authenticated via agent API token (update-only mode)"
+ if installBootstrap {
+ message = "Auto-register authenticated via Proxmox install token"
+ }
+ event.
Str("type", req.Type).
Str("host", req.Host).
- Msg("Auto-register authenticated via agent API token (update-only mode)")
+ Bool("install_bootstrap", installBootstrap).
+ Msg(message)
}
}
}
+ config.Mu.Unlock()
}
}
@@ -1338,9 +1550,17 @@ func (h *ConfigHandlers) handleAutoRegister(w http.ResponseWriter, r *http.Reque
clientIP = forwarded
}
}
- log.Info().Str("clientIP", clientIP).Msg("Auto-register request from")
+ requestEvent := log.Info()
+ if req.CheckRegistration {
+ requestEvent = log.Debug()
+ }
+ requestEvent.Str("clientIP", clientIP).Msg("Auto-register request from")
- log.Info().
+ requestEvent = log.Info()
+ if req.CheckRegistration {
+ requestEvent = log.Debug()
+ }
+ requestEvent.
Str("type", req.Type).
Str("host", req.Host).
Str("tokenId", req.TokenID).
@@ -1353,7 +1573,11 @@ func (h *ConfigHandlers) handleAutoRegister(w http.ResponseWriter, r *http.Reque
// handleCanonicalAutoRegister handles the canonical /api/auto-register flow.
func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *http.Request, req *AutoRegisterRequest, clientIP string) {
- log.Info().
+ event := log.Info()
+ if req.CheckRegistration {
+ event = log.Debug()
+ }
+ event.
Str("type", req.Type).
Str("host", req.Host).
Msg("Processing canonical auto-register request")
@@ -1387,6 +1611,11 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *h
req.ServerName = serverName
req.Source = registrationSource
+ // Serialize checks and completions. Checks can bind or consume an install
+ // grant, and must not race the source mutation performed by completion.
+ h.autoRegisterMutex.Lock()
+ defer h.autoRegisterMutex.Unlock()
+
if req.CheckRegistration {
if typeValue == "" || hostValue == "" || serverName == "" {
missingMessage := canonicalAutoRegisterCheckMissingFieldsMessage(typeValue, hostValue, serverName)
@@ -1404,10 +1633,40 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *h
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
+ if _, err := h.prepareProxmoxInstallBootstrap(r.Context(), req); err != nil {
+ log.Error().
+ Err(err).
+ Str("type", req.Type).
+ Str("host", req.Host).
+ Msg("Failed to bind Proxmox install registration token")
+ http.Error(w, "Failed to persist Proxmox install registration authorization", http.StatusInternalServerError)
+ return
+ }
+ sourceExists := h.autoRegisteredNodeConfigured(r.Context(), req, normalizedCandidates)
+ registered := h.autoRegisteredNodeExists(r.Context(), req, normalizedCandidates)
+ if registered {
+ actualName := h.findInstanceNameByHost(r.Context(), req.Type, normalizedCandidates[0])
+ if actualName == "" {
+ actualName = req.ServerName
+ }
+ if err := h.completeProxmoxInstallBootstrap(r.Context(), req, normalizedCandidates[0], actualName); err != nil {
+ log.Error().
+ Err(err).
+ Str("type", req.Type).
+ Str("host", req.Host).
+ Msg("Failed to consume Proxmox install registration grant for existing source")
+ http.Error(w, "Failed to finalize Proxmox install registration authorization", http.StatusInternalServerError)
+ return
+ }
+ }
+ canRegister := sourceExists || !isAgentAutoRegAuth(r.Context()) ||
+ h.proxmoxInstallBootstrapAvailable(r.Context(), req)
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(autoRegisterCheckResponse{
- Registered: h.autoRegisteredNodeExists(r.Context(), req, normalizedCandidates),
+ Registered: registered,
+ SourceExists: sourceExists,
+ CanRegister: canRegister,
}); err != nil {
log.Error().Err(err).Msg("Failed to encode auto-register registration check response")
}
@@ -1444,6 +1703,15 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *h
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
+ if _, err := h.prepareProxmoxInstallBootstrap(r.Context(), req); err != nil {
+ log.Error().
+ Err(err).
+ Str("type", req.Type).
+ Str("host", req.Host).
+ Msg("Failed to bind Proxmox install registration token")
+ http.Error(w, "Failed to persist Proxmox install registration authorization", http.StatusInternalServerError)
+ return
+ }
log.Info().
Str("requestedHost", req.Host).
@@ -1542,7 +1810,7 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *h
log.Info().Str("host", host).Str("type", "pve").Msg(canonicalAutoRegisterMatchMessage("cluster member endpoint"))
} else {
// Agent-token auth is restricted to updating existing nodes only.
- if isAgentAutoRegAuth(r.Context()) {
+ if isAgentAutoRegAuth(r.Context()) && !h.proxmoxInstallBootstrapAvailable(r.Context(), req) {
log.Warn().Str("host", host).Str("type", "pve").Msg("Agent API token auth rejected for new PVE node registration")
http.Error(w, "agent token auth permits token updates for existing nodes only", http.StatusForbidden)
return
@@ -1620,7 +1888,7 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *h
log.Info().Str("host", host).Str("type", "pbs").Msg(canonicalAutoRegisterMatchMessage("host; updated token in-place"))
} else {
// Agent-token auth is restricted to updating existing nodes only.
- if isAgentAutoRegAuth(r.Context()) {
+ if isAgentAutoRegAuth(r.Context()) && !h.proxmoxInstallBootstrapAvailable(r.Context(), req) {
log.Warn().Str("host", host).Str("type", "pbs").Msg("Agent API token auth rejected for new PBS node registration")
http.Error(w, "agent token auth permits token updates for existing nodes only", http.StatusForbidden)
return
@@ -1653,6 +1921,15 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *h
if actualName == "" {
actualName = serverName
}
+ if err := h.completeProxmoxInstallBootstrap(r.Context(), req, host, actualName); err != nil {
+ log.Error().
+ Err(err).
+ Str("type", req.Type).
+ Str("host", host).
+ Msg("Failed to consume Proxmox install registration grant")
+ http.Error(w, "Failed to finalize Proxmox install registration authorization", http.StatusInternalServerError)
+ return
+ }
h.markAutoRegistered(req.Type, actualName)
// Reload monitor only when the persisted state actually changed. A full
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 88d2228839..7781934699 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -13415,6 +13415,43 @@ func TestContract_AgentExecWebSocketBindsProxmoxInstallTokenOnFirstUse(t *testin
}
}
+func TestContract_ProxmoxInstallTokenCreatesOneDeclaredSource(t *testing.T) {
+ stubAutoRegisterNetworkDeps(t)
+
+ rawToken := "contract-proxmox-registration-install.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeAgentReport}, map[string]string{
+ "install_type": proxmoxInstallTypePVE,
+ "issued_via": agentInstallIssuedViaConfig,
+ })
+ cfg := &config.Config{
+ DataPath: t.TempDir(),
+ APITokens: []config.APITokenRecord{record},
+ }
+ handler := newTestConfigHandlers(t, cfg)
+ payload := AutoRegisterRequest{
+ Type: "pve",
+ Host: "https://contract-pve.local:8006",
+ TokenID: "pulse-monitor@pve!pulse-contract-pve",
+ TokenValue: "contract-proxmox-secret",
+ ServerName: "contract-pve",
+ Source: "agent",
+ }
+
+ first := runAgentAutoRegister(t, handler, rawToken, payload)
+ if first.Code != http.StatusOK {
+ t.Fatalf("first install registration status = %d, body=%s", first.Code, first.Body.String())
+ }
+ if len(cfg.PVEInstances) != 1 {
+ t.Fatalf("PVE instances = %d, want 1", len(cfg.PVEInstances))
+ }
+
+ cfg.PVEInstances = nil
+ reused := runAgentAutoRegister(t, handler, rawToken, payload)
+ if reused.Code != http.StatusForbidden {
+ t.Fatalf("reused install registration status = %d, want 403; body=%s", reused.Code, reused.Body.String())
+ }
+}
+
func TestContract_AgentConfigSuppressesCommandsForUnboundExecToken(t *testing.T) {
handler, monitor := newUnifiedAgentHandlers(t, nil)
hostID := seedUnifiedAgentHost(t, monitor)
diff --git a/internal/api/proxmox_install_registration_test.go b/internal/api/proxmox_install_registration_test.go
new file mode 100644
index 0000000000..8197371ee9
--- /dev/null
+++ b/internal/api/proxmox_install_registration_test.go
@@ -0,0 +1,341 @@
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+func runAgentAutoRegister(t *testing.T, handler *ConfigHandlers, rawToken string, payload AutoRegisterRequest) *httptest.ResponseRecorder {
+ t.Helper()
+ body, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal auto-register payload: %v", err)
+ }
+ req := httptest.NewRequest(http.MethodPost, "/api/auto-register", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-API-Token", rawToken)
+ rec := httptest.NewRecorder()
+ handler.HandleAutoRegister(rec, req)
+ return rec
+}
+
+func TestAgentInstallCommandFirstRunRegistersProxmoxSource(t *testing.T) {
+ stubAutoRegisterNetworkDeps(t)
+
+ cfg := &config.Config{
+ DataPath: t.TempDir(),
+ AuthUser: "admin",
+ AuthPass: "hashed-password",
+ }
+ handler := newTestConfigHandlers(t, cfg)
+ installReq := httptest.NewRequest(
+ http.MethodPost,
+ "/api/agent-install-command",
+ strings.NewReader(`{"type":"pve"}`),
+ )
+ installReq.Host = "pulse.example:7655"
+ installRec := httptest.NewRecorder()
+ handler.HandleAgentInstallCommand(installRec, installReq)
+ if installRec.Code != http.StatusOK {
+ t.Fatalf("agent install command status = %d, body=%s", installRec.Code, installRec.Body.String())
+ }
+ var install AgentInstallCommandResponse
+ if err := json.Unmarshal(installRec.Body.Bytes(), &install); err != nil {
+ t.Fatalf("decode agent install command: %v", err)
+ }
+ if strings.TrimSpace(install.Token) == "" {
+ t.Fatal("agent install command omitted runtime token")
+ }
+ if len(cfg.APITokens) != 1 {
+ t.Fatalf("API tokens = %d, want 1", len(cfg.APITokens))
+ }
+
+ registerRec := runAgentAutoRegister(t, handler, install.Token, AutoRegisterRequest{
+ Type: "pve",
+ Host: "https://pve-first.local:8006",
+ TokenID: "pulse-monitor@pve!pulse-pve-first",
+ TokenValue: "proxmox-secret",
+ ServerName: "pve-first",
+ Source: "agent",
+ })
+ if registerRec.Code != http.StatusOK {
+ t.Fatalf("first-run registration status = %d, body=%s", registerRec.Code, registerRec.Body.String())
+ }
+ if len(cfg.PVEInstances) != 1 {
+ t.Fatalf("PVE instances = %d, want 1", len(cfg.PVEInstances))
+ }
+ if !strings.EqualFold(cfg.APITokens[0].Metadata[proxmoxInstallRegistrationCompletedKey], "true") {
+ t.Fatal("first-run registration did not consume the install grant")
+ }
+
+ persistedTokens, err := config.NewConfigPersistence(cfg.DataPath).LoadAPITokens()
+ if err != nil {
+ t.Fatalf("load persisted install token after registration: %v", err)
+ }
+ restartedCfg := &config.Config{
+ DataPath: cfg.DataPath,
+ APITokens: persistedTokens,
+ }
+ restartedHandler := newTestConfigHandlers(t, restartedCfg)
+ reuseRec := runAgentAutoRegister(t, restartedHandler, install.Token, AutoRegisterRequest{
+ Type: "pve",
+ Host: "https://pve-after-restart.local:8006",
+ TokenID: "pulse-monitor@pve!pulse-pve-after-restart",
+ TokenValue: "different-proxmox-secret",
+ ServerName: "pve-after-restart",
+ Source: "agent",
+ })
+ if reuseRec.Code != http.StatusForbidden {
+ t.Fatalf("persisted install grant reuse status = %d, want 403; body=%s", reuseRec.Code, reuseRec.Body.String())
+ }
+}
+
+func TestProxmoxInstallTokenExistingSourceCheckConsumesGrant(t *testing.T) {
+ rawToken := "install-existing-pve.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeAgentReport}, map[string]string{
+ "install_type": "pve",
+ "issued_via": agentInstallIssuedViaConfig,
+ })
+ cfg := &config.Config{
+ DataPath: t.TempDir(),
+ APITokens: []config.APITokenRecord{record},
+ PVEInstances: []config.PVEInstance{{
+ Name: "existing-pve",
+ Host: "https://existing-pve.local:8006",
+ }},
+ }
+ handler := newTestConfigHandlers(t, cfg)
+
+ rec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{
+ Type: "pve",
+ Host: "https://existing-pve.local:8006",
+ ServerName: "existing-pve",
+ Source: "agent",
+ CheckRegistration: true,
+ })
+ if rec.Code != http.StatusOK {
+ t.Fatalf("existing registration check status = %d, body=%s", rec.Code, rec.Body.String())
+ }
+ var response autoRegisterCheckResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode registration check: %v", err)
+ }
+ if !response.Registered {
+ t.Fatal("existing source check returned registered=false")
+ }
+ if !strings.EqualFold(cfg.APITokens[0].Metadata[proxmoxInstallRegistrationCompletedKey], "true") {
+ t.Fatal("existing source check left the fresh-install grant dormant")
+ }
+}
+
+func TestOrdinaryAgentRegistrationCheckCannotCreateMissingSource(t *testing.T) {
+ rawToken := "ordinary-agent-registration-check.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeAgentReport}, nil)
+ cfg := &config.Config{
+ DataPath: t.TempDir(),
+ APITokens: []config.APITokenRecord{record},
+ }
+ handler := newTestConfigHandlers(t, cfg)
+
+ rec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{
+ Type: "pve",
+ Host: "https://missing-pve.local:8006",
+ ServerName: "missing-pve",
+ Source: "agent",
+ CheckRegistration: true,
+ })
+ if rec.Code != http.StatusOK {
+ t.Fatalf("ordinary agent check status = %d, body=%s", rec.Code, rec.Body.String())
+ }
+ var response autoRegisterCheckResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode ordinary agent check: %v", err)
+ }
+ if response.Registered || response.SourceExists || response.CanRegister {
+ t.Fatalf("ordinary agent missing-source response = %#v, want all false", response)
+ }
+}
+
+func TestProxmoxInstallTokenBootstrapsDeclaredSourceOnce(t *testing.T) {
+ stubAutoRegisterNetworkDeps(t)
+
+ for _, nodeType := range []string{"pve", "pbs"} {
+ t.Run(nodeType, func(t *testing.T) {
+ rawToken := "install-" + nodeType + "-token.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeAgentReport}, map[string]string{
+ "install_type": nodeType,
+ "issued_via": agentInstallIssuedViaConfig,
+ })
+ cfg := &config.Config{
+ DataPath: t.TempDir(),
+ APITokens: []config.APITokenRecord{record},
+ }
+ handler := newTestConfigHandlers(t, cfg)
+ host := fmt.Sprintf("https://%s-node.local:%d", nodeType, map[string]int{"pve": 8006, "pbs": 8007}[nodeType])
+ payload := AutoRegisterRequest{
+ Type: nodeType,
+ Host: host,
+ TokenID: fmt.Sprintf("pulse-monitor@%s!pulse-%s-node", nodeType, nodeType),
+ TokenValue: "proxmox-secret",
+ ServerName: nodeType + "-node",
+ Source: "agent",
+ }
+
+ checkPayload := payload
+ checkPayload.TokenID = ""
+ checkPayload.TokenValue = ""
+ checkPayload.CheckRegistration = true
+ checkRec := runAgentAutoRegister(t, handler, rawToken, checkPayload)
+ if checkRec.Code != http.StatusOK {
+ t.Fatalf("registration check status = %d, body=%s", checkRec.Code, checkRec.Body.String())
+ }
+ if strings.EqualFold(cfg.APITokens[0].Metadata[proxmoxInstallRegistrationCompletedKey], "true") {
+ t.Fatal("read-only registration check consumed the install grant")
+ }
+ if got := cfg.APITokens[0].Metadata["bound_hostname"]; got != payload.ServerName {
+ t.Fatalf("install token bound hostname = %q, want %q", got, payload.ServerName)
+ }
+
+ registerRec := runAgentAutoRegister(t, handler, rawToken, payload)
+ if registerRec.Code != http.StatusOK {
+ t.Fatalf("initial registration status = %d, body=%s", registerRec.Code, registerRec.Body.String())
+ }
+ if !strings.EqualFold(cfg.APITokens[0].Metadata[proxmoxInstallRegistrationCompletedKey], "true") {
+ t.Fatal("successful initial registration did not consume the install grant")
+ }
+ if got := cfg.APITokens[0].Metadata[proxmoxInstallRegistrationTypeKey]; got != nodeType {
+ t.Fatalf("registration type metadata = %q, want %q", got, nodeType)
+ }
+
+ switch nodeType {
+ case "pve":
+ if len(cfg.PVEInstances) != 1 {
+ t.Fatalf("PVE instances = %d, want 1", len(cfg.PVEInstances))
+ }
+ cfg.PVEInstances = nil
+ case "pbs":
+ if len(cfg.PBSInstances) != 1 {
+ t.Fatalf("PBS instances = %d, want 1", len(cfg.PBSInstances))
+ }
+ cfg.PBSInstances = nil
+ }
+
+ reuseRec := runAgentAutoRegister(t, handler, rawToken, payload)
+ if reuseRec.Code != http.StatusForbidden {
+ t.Fatalf("reused install grant status = %d, want 403; body=%s", reuseRec.Code, reuseRec.Body.String())
+ }
+ })
+ }
+}
+
+func TestProxmoxInstallTokenCannotBootstrapDifferentType(t *testing.T) {
+ stubAutoRegisterNetworkDeps(t)
+
+ rawToken := "install-pve-wrong-type.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeAgentReport}, map[string]string{
+ "install_type": "pve",
+ "issued_via": agentInstallIssuedViaConfig,
+ })
+ cfg := &config.Config{
+ DataPath: t.TempDir(),
+ APITokens: []config.APITokenRecord{record},
+ }
+ handler := newTestConfigHandlers(t, cfg)
+ rec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{
+ Type: "pbs",
+ Host: "https://pbs-node.local:8007",
+ TokenID: "pulse-monitor@pbs!pulse-pbs-node",
+ TokenValue: "proxmox-secret",
+ ServerName: "pbs-node",
+ Source: "agent",
+ })
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("cross-type registration status = %d, want 403; body=%s", rec.Code, rec.Body.String())
+ }
+}
+
+func TestProxmoxInstallTokenMalformedRequestDoesNotBindGrant(t *testing.T) {
+ rawToken := "install-pve-malformed.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeAgentReport}, map[string]string{
+ "install_type": "pve",
+ "issued_via": agentInstallIssuedViaConfig,
+ })
+ cfg := &config.Config{
+ DataPath: t.TempDir(),
+ APITokens: []config.APITokenRecord{record},
+ }
+ handler := newTestConfigHandlers(t, cfg)
+
+ rec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{
+ Type: "pve",
+ Host: "https://malformed.local:8006",
+ TokenID: "not-a-canonical-token-id",
+ TokenValue: "proxmox-secret",
+ ServerName: "malformed-host",
+ Source: "agent",
+ })
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("malformed registration status = %d, want 400; body=%s", rec.Code, rec.Body.String())
+ }
+ if got := cfg.APITokens[0].Metadata["bound_hostname"]; got != "" {
+ t.Fatalf("malformed request bound install token to %q", got)
+ }
+}
+
+func TestProxmoxInstallTokenConcurrentBootstrapConsumesOneGrant(t *testing.T) {
+ stubAutoRegisterNetworkDeps(t)
+
+ rawToken := "install-pve-race.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeAgentReport}, map[string]string{
+ "install_type": "pve",
+ "issued_via": agentInstallIssuedViaConfig,
+ })
+ cfg := &config.Config{
+ DataPath: t.TempDir(),
+ APITokens: []config.APITokenRecord{record},
+ }
+ handler := newTestConfigHandlers(t, cfg)
+
+ start := make(chan struct{})
+ statuses := make(chan int, 2)
+ var wg sync.WaitGroup
+ for i := 1; i <= 2; i++ {
+ i := i
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ rec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{
+ Type: "pve",
+ Host: fmt.Sprintf("https://pve-%d.local:8006", i),
+ TokenID: fmt.Sprintf("pulse-monitor@pve!pulse-pve-%d", i),
+ TokenValue: fmt.Sprintf("proxmox-secret-%d", i),
+ ServerName: fmt.Sprintf("pve-%d", i),
+ Source: "agent",
+ })
+ statuses <- rec.Code
+ }()
+ }
+ close(start)
+ wg.Wait()
+ close(statuses)
+
+ counts := map[int]int{}
+ for status := range statuses {
+ counts[status]++
+ }
+ if counts[http.StatusOK] != 1 || counts[http.StatusForbidden] != 1 {
+ t.Fatalf("concurrent statuses = %#v, want one 200 and one 403", counts)
+ }
+ if len(cfg.PVEInstances) != 1 {
+ t.Fatalf("PVE instances = %d, want one successful bootstrap", len(cfg.PVEInstances))
+ }
+}
diff --git a/internal/hostagent/proxmox_setup.go b/internal/hostagent/proxmox_setup.go
index b172538e7d..6bd3860a2e 100644
--- a/internal/hostagent/proxmox_setup.go
+++ b/internal/hostagent/proxmox_setup.go
@@ -86,7 +86,15 @@ type autoRegisterResponse struct {
}
type autoRegisterCheckResponse struct {
- Registered bool `json:"registered"`
+ Registered bool `json:"registered"`
+ SourceExists *bool `json:"sourceExists,omitempty"`
+ CanRegister *bool `json:"canRegister,omitempty"`
+}
+
+type registrationState struct {
+ registered bool
+ sourceExists bool
+ canRegister bool
}
const maxRegistrationCheckResponseBytes = 8 * 1024
@@ -501,15 +509,23 @@ func (p *ProxmoxSetup) RunHealthCheck(ctx context.Context) ([]*ProxmoxSetupResul
}
hostURL := p.getHostURL(ctx, ptype)
- registered, err := p.checkRegistrationWithPulse(ctx, ptype, hostURL)
+ registration, err := p.checkRegistrationWithPulse(ctx, ptype, hostURL)
if err != nil {
p.logger.Warn().Err(err).Str("type", string(ptype)).
Msg("Proxmox health check: could not verify registration with Pulse")
continue
}
- if registered {
+ if registration.registered {
continue // still healthy
}
+ if !registration.canRegister {
+ p.logger.Warn().
+ Str("type", string(ptype)).
+ Str("host", hostURL).
+ Bool("source_exists", registration.sourceExists).
+ Msg("Proxmox health check: Pulse has no matching source and this agent token cannot create one; re-run the Proxmox agent install command")
+ continue
+ }
p.logger.Info().Str("type", string(ptype)).Str("host", hostURL).
Msg("Proxmox health check: node disconnected, re-registering")
@@ -539,7 +555,7 @@ func (p *ProxmoxSetup) runForType(ctx context.Context, ptype proxmoxProductType)
// mutating a Proxmox token. This prevents a missing local marker or a Pulse
// startup outage from rotating credentials that a healthy Pulse instance is
// still using.
- registered, err := p.checkRegistrationWithPulse(ctx, ptype, hostURL)
+ registration, err := p.checkRegistrationWithPulse(ctx, ptype, hostURL)
if err != nil {
p.logger.Warn().
Err(err).
@@ -547,13 +563,21 @@ func (p *ProxmoxSetup) runForType(ctx context.Context, ptype proxmoxProductType)
Msg("Failed to verify Proxmox registration state with Pulse; leaving credentials unchanged")
return nil, nil
}
- if registered {
+ if registration.registered {
if !p.isTypeRegistered(ptype) {
p.markTypeAsRegistered(ptype)
}
p.logger.Info().Str("type", string(ptype)).Msg("Proxmox type already registered, skipping")
return nil, nil
}
+ if !registration.canRegister {
+ p.logger.Warn().
+ Str("type", string(ptype)).
+ Str("host", hostURL).
+ Bool("source_exists", registration.sourceExists).
+ Msg("Pulse has no matching Proxmox source and this agent token cannot create one; leaving local credentials unchanged and requiring a fresh install command")
+ return nil, nil
+ }
if p.isTypeRegistered(ptype) {
p.logger.Info().
Str("type", string(ptype)).
@@ -577,7 +601,7 @@ func (p *ProxmoxSetup) runForType(ctx context.Context, ptype proxmoxProductType)
p.logger.Info().Str("type", string(ptype)).Str("token_id", tokenID).Msg("Created Proxmox API token")
// Register with Pulse
- registered = false
+ registered := false
registerResp, err := p.registerWithPulse(ctx, ptype, hostURL, tokenID, tokenValue)
if err != nil {
p.logger.Warn().Err(err).Str("type", string(ptype)).Msg("Failed to register with Pulse (node may already exist)")
@@ -614,19 +638,17 @@ func (p *ProxmoxSetup) orderedCandidateHosts(ctx context.Context, ptype proxmoxP
return candidateHosts
}
-func (p *ProxmoxSetup) checkRegistrationWithPulse(ctx context.Context, ptype proxmoxProductType, hostURL string) (bool, error) {
- setupToken, err := p.fetchSetupToken(ctx, ptype, hostURL)
- if err != nil {
- var ce *clientError
- var pe *permanentError
- if errors.As(err, &pe) {
- return false, fmt.Errorf("fetch setup token: %w", err)
- }
- if errors.As(err, &ce) {
- // Fall through without a setup token; server will authenticate via X-API-Token.
- setupToken = ""
- } else {
- return false, fmt.Errorf("fetch setup token: %w", err)
+func (p *ProxmoxSetup) checkRegistrationWithPulse(ctx context.Context, ptype proxmoxProductType, hostURL string) (registrationState, error) {
+ // Runtime agent tokens authenticate directly against the canonical
+ // auto-register endpoint. The setup-script-url endpoint is an operator
+ // control-plane surface protected by settings:write and must never be used
+ // as a runtime token-discovery probe.
+ setupToken := ""
+ if strings.TrimSpace(p.apiToken) == "" {
+ var err error
+ setupToken, err = p.fetchSetupToken(ctx, ptype, hostURL)
+ if err != nil {
+ return registrationState{}, fmt.Errorf("fetch setup token: %w", err)
}
}
@@ -642,12 +664,12 @@ func (p *ProxmoxSetup) checkRegistrationWithPulse(ctx context.Context, ptype pro
body, err := json.Marshal(payload)
if err != nil {
- return false, fmt.Errorf("marshal registration-check payload: %w", err)
+ return registrationState{}, fmt.Errorf("marshal registration-check payload: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.pulseURL+"/api/auto-register", bytes.NewReader(body))
if err != nil {
- return false, fmt.Errorf("create registration-check request: %w", err)
+ return registrationState{}, fmt.Errorf("create registration-check request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
if token := autoRegisterAPITokenHeader(p.apiToken, setupToken); token != "" {
@@ -656,7 +678,7 @@ func (p *ProxmoxSetup) checkRegistrationWithPulse(ctx context.Context, ptype pro
resp, err := p.httpClient.Do(req)
if err != nil {
- return false, fmt.Errorf("registration-check request failed: %w", err)
+ return registrationState{}, fmt.Errorf("registration-check request failed: %w", err)
}
defer func() {
if closeErr := resp.Body.Close(); closeErr != nil {
@@ -666,17 +688,35 @@ func (p *ProxmoxSetup) checkRegistrationWithPulse(ctx context.Context, ptype pro
bodyBytes, err := io.ReadAll(io.LimitReader(resp.Body, maxRegistrationCheckResponseBytes))
if err != nil {
- return false, fmt.Errorf("read registration-check response: %w", err)
+ return registrationState{}, fmt.Errorf("read registration-check response: %w", err)
}
if resp.StatusCode >= http.StatusBadRequest {
- return false, fmt.Errorf("registration-check returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))
+ return registrationState{}, &clientError{
+ statusCode: resp.StatusCode,
+ body: strings.TrimSpace(string(bodyBytes)),
+ }
}
var parsed autoRegisterCheckResponse
if err := json.Unmarshal(bodyBytes, &parsed); err != nil {
- return false, fmt.Errorf("decode registration-check response: %w", err)
- }
- return parsed.Registered, nil
+ return registrationState{}, fmt.Errorf("decode registration-check response: %w", err)
+ }
+ // Older Pulse servers returned only registered. Preserve their repair
+ // behavior during rolling updates by treating omitted capability fields as
+ // permissive; current servers always send both fields explicitly.
+ sourceExists := parsed.Registered
+ if parsed.SourceExists != nil {
+ sourceExists = *parsed.SourceExists
+ }
+ canRegister := true
+ if parsed.CanRegister != nil {
+ canRegister = *parsed.CanRegister
+ }
+ return registrationState{
+ registered: parsed.Registered,
+ sourceExists: sourceExists,
+ canRegister: canRegister,
+ }, nil
}
// detectProxmoxType checks for pvesh (PVE) or proxmox-backup-manager (PBS).
@@ -1415,24 +1455,17 @@ func (p *ProxmoxSetup) registerWithPulse(ctx context.Context, ptype proxmoxProdu
}
}
- setupToken, err := p.fetchSetupToken(ctx, ptype, hostURL)
- if err != nil {
- lastErr = fmt.Errorf("fetch setup token: %w", err)
- var ce *clientError
- var pe *permanentError
- if errors.As(lastErr, &pe) {
- return autoRegisterResponse{}, lastErr
- }
- if errors.As(lastErr, &ce) {
- // The setup-script-url endpoint requires settings:write scope; agent tokens
- // only have agent:report. Fall through without a setup token — the server
- // will authenticate via the X-API-Token header instead (update-only path).
- p.logger.Info().
- Int("statusCode", ce.statusCode).
- Str("type", string(ptype)).
- Msg("Setup token fetch returned client error; falling back to agent API token auth")
- setupToken = ""
- } else {
+ setupToken := ""
+ if strings.TrimSpace(p.apiToken) == "" {
+ var err error
+ setupToken, err = p.fetchSetupToken(ctx, ptype, hostURL)
+ if err != nil {
+ lastErr = fmt.Errorf("fetch setup token: %w", err)
+ var ce *clientError
+ var pe *permanentError
+ if errors.As(lastErr, &ce) || errors.As(lastErr, &pe) {
+ return autoRegisterResponse{}, lastErr
+ }
p.logger.Warn().Err(lastErr).
Int("attempt", attempt+1).
Int("max_attempts", len(backoffs)+1).
diff --git a/internal/hostagent/proxmox_setup_network_coverage_test.go b/internal/hostagent/proxmox_setup_network_coverage_test.go
index c4cd14f21d..5bf39cb88a 100644
--- a/internal/hostagent/proxmox_setup_network_coverage_test.go
+++ b/internal/hostagent/proxmox_setup_network_coverage_test.go
@@ -308,8 +308,7 @@ func TestProxmoxSetup_registerWithPulse(t *testing.T) {
t.Run("success sends expected request body and headers", func(t *testing.T) {
var gotReq *http.Request
var gotPayload map[string]any
- var gotSetupReq *http.Request
- var gotSetupPayload map[string]any
+ setupTokenRequests := 0
p := &ProxmoxSetup{
pulseURL: "https://pulse.example",
@@ -319,20 +318,10 @@ func TestProxmoxSetup_registerWithPulse(t *testing.T) {
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
switch req.URL.Path {
case "/api/setup-script-url":
- gotSetupReq = req
-
- bodyBytes, err := io.ReadAll(req.Body)
- if err != nil {
- t.Fatalf("read setup body: %v", err)
- }
-
- if err := json.Unmarshal(bodyBytes, &gotSetupPayload); err != nil {
- t.Fatalf("unmarshal setup body: %v", err)
- }
-
+ setupTokenRequests++
return &http.Response{
- StatusCode: http.StatusOK,
- Body: io.NopCloser(strings.NewReader(canonicalSetupScriptURLResponseJSON("https://pulse.example", "pbs", "https://10.0.0.2:8007", "setup-token-123"))),
+ StatusCode: http.StatusForbidden,
+ Body: io.NopCloser(strings.NewReader("Forbidden")),
Header: make(http.Header),
}, nil
case "/api/auto-register":
@@ -368,26 +357,11 @@ func TestProxmoxSetup_registerWithPulse(t *testing.T) {
t.Fatalf("response nodeName = %q, want %q", resp.NodeName, "node-1")
}
- if gotSetupReq == nil {
- t.Fatalf("expected setup token request to be sent")
- }
if gotReq == nil {
t.Fatalf("expected auto-register request to be sent")
}
- if gotSetupReq.Method != http.MethodPost {
- t.Fatalf("setup method = %q, want %q", gotSetupReq.Method, http.MethodPost)
- }
- if gotSetupReq.URL.Path != "/api/setup-script-url" {
- t.Fatalf("setup path = %q, want %q", gotSetupReq.URL.Path, "/api/setup-script-url")
- }
- if gotSetupReq.Header.Get("X-API-Token") != "api-token" {
- t.Fatalf("setup X-API-Token = %q, want %q", gotSetupReq.Header.Get("X-API-Token"), "api-token")
- }
- if gotSetupPayload["type"] != "pbs" {
- t.Fatalf("setup payload[type] = %#v, want %q", gotSetupPayload["type"], "pbs")
- }
- if gotSetupPayload["host"] != "https://10.0.0.2:8007" {
- t.Fatalf("setup payload[host] = %#v, want %q", gotSetupPayload["host"], "https://10.0.0.2:8007")
+ if setupTokenRequests != 0 {
+ t.Fatalf("setup-script-url requests = %d, want 0", setupTokenRequests)
}
if gotReq.Method != http.MethodPost {
t.Fatalf("method = %q, want %q", gotReq.Method, http.MethodPost)
@@ -398,8 +372,8 @@ func TestProxmoxSetup_registerWithPulse(t *testing.T) {
if gotReq.Header.Get("Content-Type") != "application/json" {
t.Fatalf("Content-Type = %q, want %q", gotReq.Header.Get("Content-Type"), "application/json")
}
- if gotReq.Header.Get("X-API-Token") != "" {
- t.Fatalf("X-API-Token = %q, want empty", gotReq.Header.Get("X-API-Token"))
+ if gotReq.Header.Get("X-API-Token") != "api-token" {
+ t.Fatalf("X-API-Token = %q, want runtime token", gotReq.Header.Get("X-API-Token"))
}
if gotPayload["type"] != "pbs" {
@@ -411,8 +385,8 @@ func TestProxmoxSetup_registerWithPulse(t *testing.T) {
if gotPayload["serverName"] != "node-1" {
t.Fatalf("payload[serverName] = %#v, want %q", gotPayload["serverName"], "node-1")
}
- if gotPayload["authToken"] != "setup-token-123" {
- t.Fatalf("payload[authToken] = %#v, want %q", gotPayload["authToken"], "setup-token-123")
+ if _, exists := gotPayload["authToken"]; exists {
+ t.Fatalf("payload must not contain setup authToken, got %#v", gotPayload["authToken"])
}
if gotPayload["tokenId"] != "token-id" {
t.Fatalf("payload[tokenId] = %#v, want %q", gotPayload["tokenId"], "token-id")
diff --git a/internal/hostagent/proxmox_setup_test.go b/internal/hostagent/proxmox_setup_test.go
index 7c1723185b..ee84de9248 100644
--- a/internal/hostagent/proxmox_setup_test.go
+++ b/internal/hostagent/proxmox_setup_test.go
@@ -134,25 +134,19 @@ func TestProxmoxSetupNormalizePulseURL_AllowsLocalNetworkHTTP(t *testing.T) {
func TestRegisterWithPulse_Payload(t *testing.T) {
var gotPayload autoRegisterRequest
- var setupTokenHeader string
- var setupTokenPayload map[string]any
+ setupTokenRequests := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
t.Fatalf("unexpected method %s", r.Method)
}
switch r.URL.Path {
case "/api/setup-script-url":
- setupTokenHeader = r.Header.Get("X-API-Token")
- if err := json.NewDecoder(r.Body).Decode(&setupTokenPayload); err != nil {
- t.Fatalf("decode setup token payload: %v", err)
- }
- publicURL := "http://" + r.Host
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(canonicalSetupScriptURLResponseJSON(publicURL, "pve", "https://10.0.0.4:8006", "setup-token-123")))
+ setupTokenRequests++
+ http.Error(w, "runtime must not request setup artifacts", http.StatusForbidden)
return
case "/api/auto-register":
- if gotToken := r.Header.Get("X-API-Token"); gotToken != "" {
- t.Fatalf("unexpected X-API-Token header %q", gotToken)
+ if gotToken := r.Header.Get("X-API-Token"); gotToken != "pulse-token" {
+ t.Fatalf("X-API-Token header = %q, want runtime token", gotToken)
}
if err := json.NewDecoder(r.Body).Decode(&gotPayload); err != nil {
t.Fatalf("decode payload: %v", err)
@@ -201,8 +195,8 @@ func TestRegisterWithPulse_Payload(t *testing.T) {
if gotPayload.ServerName != "node-1" {
t.Fatalf("unexpected serverName %q", gotPayload.ServerName)
}
- if gotPayload.AuthToken != "setup-token-123" {
- t.Fatalf("unexpected authToken %q", gotPayload.AuthToken)
+ if gotPayload.AuthToken != "" {
+ t.Fatalf("unexpected setup authToken %q", gotPayload.AuthToken)
}
if gotPayload.TokenID != "token-id" {
t.Fatalf("unexpected tokenId %q", gotPayload.TokenID)
@@ -213,14 +207,8 @@ func TestRegisterWithPulse_Payload(t *testing.T) {
if gotPayload.Source != autoRegisterSourceAgent {
t.Fatalf("unexpected source %q", gotPayload.Source)
}
- if setupTokenHeader != "pulse-token" {
- t.Fatalf("unexpected setup token auth header %q", setupTokenHeader)
- }
- if setupTokenPayload["type"] != "pve" {
- t.Fatalf("unexpected setup token type %#v", setupTokenPayload["type"])
- }
- if setupTokenPayload["host"] != "https://10.0.0.4:8006" {
- t.Fatalf("unexpected setup token host %#v", setupTokenPayload["host"])
+ if setupTokenRequests != 0 {
+ t.Fatalf("setup-script-url requests = %d, want 0", setupTokenRequests)
}
}
@@ -233,6 +221,201 @@ func TestAutoRegisterAPITokenHeader(t *testing.T) {
}
}
+func TestRunHealthCheckUsesAgentTokenDirectly(t *testing.T) {
+ for _, nodeType := range []proxmoxProductType{proxmoxProductPVE, proxmoxProductPBS} {
+ t.Run(string(nodeType), func(t *testing.T) {
+ setupArtifactRequests := 0
+ registrationChecks := 0
+ port := "8006"
+ if nodeType == proxmoxProductPBS {
+ port = "8007"
+ }
+ expectedHost := "https://10.0.0.9:" + port
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/setup-script-url":
+ setupArtifactRequests++
+ http.Error(w, "runtime must not request setup artifacts", http.StatusForbidden)
+ case "/api/auto-register":
+ registrationChecks++
+ if got := r.Header.Get("X-API-Token"); got != "agent-runtime-token" {
+ t.Fatalf("X-API-Token = %q, want runtime token", got)
+ }
+ var payload autoRegisterRequest
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode registration check: %v", err)
+ }
+ if !payload.CheckRegistration {
+ t.Fatalf("expected registration check, got %#v", payload)
+ }
+ if payload.Host != expectedHost {
+ t.Fatalf("host = %q, want %q", payload.Host, expectedHost)
+ }
+ if payload.AuthToken != "" {
+ t.Fatalf("unexpected setup auth token %q", payload.AuthToken)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"registered":true}`))
+ default:
+ t.Fatalf("unexpected path %s", r.URL.Path)
+ }
+ }))
+ defer server.Close()
+
+ mc := &mockCollector{}
+ setup := NewProxmoxSetup(
+ zerolog.Nop(),
+ server.Client(),
+ mc,
+ server.URL,
+ "agent-runtime-token",
+ string(nodeType),
+ "node-1",
+ "10.0.0.9",
+ t.TempDir(),
+ false,
+ )
+ stateFile := setup.stateFileForType(nodeType)
+ mc.statFn = func(name string) (os.FileInfo, error) {
+ if name == stateFile {
+ return nil, nil
+ }
+ return nil, os.ErrNotExist
+ }
+
+ for i := 0; i < 3; i++ {
+ results, err := setup.RunHealthCheck(context.Background())
+ if err != nil {
+ t.Fatalf("RunHealthCheck() iteration %d: %v", i+1, err)
+ }
+ if len(results) != 0 {
+ t.Fatalf("healthy iteration %d returned repair results %#v", i+1, results)
+ }
+ }
+ if registrationChecks != 3 {
+ t.Fatalf("registration checks = %d, want 3", registrationChecks)
+ }
+ if setupArtifactRequests != 0 {
+ t.Fatalf("setup-script-url requests = %d, want 0", setupArtifactRequests)
+ }
+ })
+ }
+}
+
+func TestRunHealthCheckSurfacesRejectedAgentToken(t *testing.T) {
+ setupArtifactRequests := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/setup-script-url":
+ setupArtifactRequests++
+ http.Error(w, "runtime must not request setup artifacts", http.StatusForbidden)
+ case "/api/auto-register":
+ http.Error(w, "token expired or rotated", http.StatusForbidden)
+ default:
+ t.Fatalf("unexpected path %s", r.URL.Path)
+ }
+ }))
+ defer server.Close()
+
+ var logs strings.Builder
+ logger := zerolog.New(&logs)
+ mc := &mockCollector{}
+ setup := NewProxmoxSetup(
+ logger,
+ server.Client(),
+ mc,
+ server.URL,
+ "rejected-agent-token",
+ "pve",
+ "node-1",
+ "10.0.0.9",
+ t.TempDir(),
+ false,
+ )
+ stateFile := setup.pveStateFilePath()
+ mc.statFn = func(name string) (os.FileInfo, error) {
+ if name == stateFile {
+ return nil, nil
+ }
+ return nil, os.ErrNotExist
+ }
+
+ results, err := setup.RunHealthCheck(context.Background())
+ if err != nil {
+ t.Fatalf("RunHealthCheck(): %v", err)
+ }
+ if len(results) != 0 {
+ t.Fatalf("rejected token returned repair results %#v", results)
+ }
+ if setupArtifactRequests != 0 {
+ t.Fatalf("setup-script-url requests = %d, want 0", setupArtifactRequests)
+ }
+ if got := logs.String(); !strings.Contains(got, "HTTP 403") || !strings.Contains(got, "token expired or rotated") {
+ t.Fatalf("authorization failure diagnostics missing from logs: %s", got)
+ }
+}
+
+func TestRunAllLeavesCredentialsUnchangedWhenAgentCannotCreateMissingSource(t *testing.T) {
+ setupArtifactRequests := 0
+ registrationChecks := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/setup-script-url":
+ setupArtifactRequests++
+ http.Error(w, "runtime must not request setup artifacts", http.StatusForbidden)
+ case "/api/auto-register":
+ registrationChecks++
+ if got := r.Header.Get("X-API-Token"); got != "ordinary-agent-token" {
+ t.Fatalf("X-API-Token = %q, want ordinary agent token", got)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"registered":false,"sourceExists":false,"canRegister":false}`))
+ default:
+ t.Fatalf("unexpected path %s", r.URL.Path)
+ }
+ }))
+ defer server.Close()
+
+ var logs strings.Builder
+ logger := zerolog.New(&logs)
+ mc := &mockCollector{
+ statFn: func(string) (os.FileInfo, error) { return nil, os.ErrNotExist },
+ commandCombinedOutputFn: func(ctx context.Context, name string, arg ...string) (string, error) {
+ t.Fatalf("local credential command must not run when server denies source creation: %s %v", name, arg)
+ return "", nil
+ },
+ }
+ setup := NewProxmoxSetup(
+ logger,
+ server.Client(),
+ mc,
+ server.URL,
+ "ordinary-agent-token",
+ "pve",
+ "node-1",
+ "10.0.0.9",
+ t.TempDir(),
+ false,
+ )
+ results, err := setup.RunAll(context.Background())
+ if err != nil {
+ t.Fatalf("RunAll(): %v", err)
+ }
+ if len(results) != 0 {
+ t.Fatalf("missing source returned setup results %#v", results)
+ }
+ if registrationChecks != 1 {
+ t.Fatalf("registration checks = %d, want 1", registrationChecks)
+ }
+ if setupArtifactRequests != 0 {
+ t.Fatalf("setup-script-url requests = %d, want 0", setupArtifactRequests)
+ }
+ if got := logs.String(); !strings.Contains(got, "leaving local credentials unchanged") {
+ t.Fatalf("missing-source diagnostic absent from logs: %s", got)
+ }
+}
+
func TestRegisterWithPulse_AcceptsServerSelectedFallbackHost(t *testing.T) {
var gotPayload autoRegisterRequest
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {