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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Tighten host-token Proxmox bootstrap grant (#1644)
[email protected]7e4a4464a13a
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 624e728797..53673a131e 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -5342,6 +5342,33 @@ credentials are mutated, serialized completion, and one-shot consumption — ahost token that completes a PVE bootstrap cannot later bootstrap PBS, andnon-Proxmox request types never hold a grant.+The grant is time-bounded independently of the token that carries it. Install+tokens are minted without an expiry because the agent reports with them for the+life of the install, so the bootstrap grant carries its own 24-hour clock from+mint (`install_issued_at`, falling back to the token's creation time; a record+with neither fails the grant closed). Past that window the token keeps+reporting and stays update-only, the denial takes the same 403 path as any+other ungranted token, and the server logs the expiry distinctly so an operator+running a stale install command sees why source creation was refused.++Grant consumption and source creation must fail together. The one-shot grant is+consumed and durably persisted BEFORE the created source is written, and a+failed source save rolls the consumption back. The opposite order leaves a+persistently failing token store able to write a source while the grant stays+live, which is a repeatable create-a-source primitive under one install token.+Either the source is persisted and the grant is spent, or neither happened and+the install can be retried.++A host install token that has already auto-registered its Proxmox source+carries a `bound_hostname` written by the registration bootstrap, with no+`bound_agent_id` and no exec binding version. That is still a clean first use+of the command channel: the first command enrollment whose hostname matches the+bound one binds the fresh runtime agent ID and the current binding version,+rather than being admitted by the legacy pre-v6.1.1 identity-migration branch.+The registration-bound hostname is authoritative and is not rewritten by an+equivalent spelling the agent reports, because the still-unconsumed install+grant compares against it.+A blocked registration is not a silent skip. When the pre-registration checkreports `canRegister=false`, the agent must log at error level, return a setuperror to its caller, and record the operator-facing reason in adiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex a5a463d502..7c77aee1b6 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -1628,6 +1628,22 @@ payload shape change when the portal presents compact client rows.Non-canonical request types never hold the grant, and the grant keeps itssettings-authorized `issued_via` requirement, first-hostname binding,serialized completion, and single consumption across types.+ That grant is also time-bounded on its own clock: install tokens are minted+ without an expiry, so the bootstrap capability expires 24 hours after mint+ (`install_issued_at`, falling back to the record's creation time, and fails+ closed with neither). An expired grant answers `canRegister:false` and the+ same 403 as any ungranted token while the token keeps reporting, and the+ denial is logged distinctly from a token that never held a grant.+ Consumption ordering is part of the contract: the grant is consumed and+ persisted before the created source is written, and a failed source save+ rolls the consumption back, so a failing token store can never leave a+ persisted source next to a live grant.+ The exec binding contract follows from that grant: a `bound_hostname`+ written by auto-register (no `bound_agent_id`, no binding version) is a+ clean first use of the command channel, so a matching hostname binds the+ fresh runtime agent ID through the first-use path rather than the legacy+ identity-migration branch, and the registration-bound hostname is not+ rewritten by an equivalent spelling the agent reports.That same contract owns auto-register WebSocket event intent: a successfulcompletion that creates a new PVE/PBS node may broadcast`node_auto_registered`, but successful idempotent matches or credentialdiff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex fd64e449c6..e9d7c3a9ea 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -890,6 +890,16 @@ fully-qualified equivalence rule rather than ad-hoc case folding. Theaccept/reject decision is single-sourced (`evaluateAgentExecBinding`) and theagent config gate must consume the same decision, so no surface can advertisecommand execution that channel admission would refuse.+That binding boundary also covers install tokens that auto-registered a Proxmox+source before their agent ever reached the command channel. The registration+bootstrap writes `bound_hostname` with no `bound_agent_id` and no binding+version (#1644), which is the record shape the legacy pre-v6.1.1 migration+branch exists to repair. Such a token is a clean first use instead: an+equivalent hostname binds the fresh machine-derived agent ID and the current+binding version through the first-use path, an unrelated hostname still fails+closed, and the registration-bound hostname is never overwritten by an+equivalent spelling the agent reports, because the install grant compares+against it.Telemetry/privacy disclosures now also route through the shipped frontend docsboundary: `frontend-modern/src/utils/docsLinks.ts` is the canonical frontendowner for privacy-document URLs, while `frontend-modern/public/docs/PRIVACY.md`diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex f9d7da9709..903b99c9d1 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -4135,6 +4135,14 @@ invalid-setup-token branch off a 401/403 status, and that their manualcompletion and rerun guidance names the live Settings → Infrastructure page,so adjacent setup flows surface reachable auth-failure guidance instead of adead server-string grep and a retired page name (#1644).+That same dependency also owns the write ordering between the API token store+and the nodes store during an install-token bootstrap: the one-shot grant is+consumed and persisted to the token store before the created source is written+to the nodes store, and a failed nodes write rolls the consumption back. A+token-store write that fails after the nodes write would otherwise leave a+persisted source next to a still-live one-shot grant, so a persistently failing+token store becomes a repeatable source-creation primitive. Either both stores+advanced or neither did.That same shared dependency also assumes generated setup scripts preservesetup-token auth guidance, so adjacent setup flows do not regress back tostale API-token instructions after the backend has already standardized on thediff --git a/internal/api/agent_exec_token_binding.go b/internal/api/agent_exec_token_binding.goindex 36d401f0d5..50ee7cd6fd 100644--- a/internal/api/agent_exec_token_binding.go+++ b/internal/api/agent_exec_token_binding.go@@ -90,6 +90,16 @@ func evaluateAgentExecBinding(record *config.APITokenRecord, requestedID, requesreturn agentExecBindingDecision{}}+ // An install token that already auto-registered a Proxmox source carries a+ // bound_hostname written by the registration bootstrap, with no+ // bound_agent_id and no binding version (#1644). That is still a clean+ // first use of the command channel, not a legacy pre-v6.1.1 record, so bind+ // it here with the fresh runtime agent ID instead of letting it fall+ // through to the legacy-migration branch.+ if canBindAutoRegisteredAgentInstallExecToken(record, requestedID, requestedHost) {+ return agentExecBindingDecision{admit: true, firstBind: true}+ }+// Pre-v6.1.1 deploy tokens could carry a server-synthesized agent ID even// though the runtime derives its ID from machine-id. Migrate that// hostname-bound legacy record exactly once, then enforce identity.@@ -181,7 +191,13 @@ func (r *Router) admitAgentExecToken(token string, agentID string, hostname striagentExecBindingVersionKey,)record.Metadata["bound_agent_id"] = requestedID- record.Metadata["bound_hostname"] = requestedHost+ // A bound_hostname already written by the Proxmox auto-register+ // bootstrap is authoritative: it is what the still-unconsumed install+ // grant compares against, so an equivalent-but-different spelling+ // reported by the agent must not overwrite it.+ if strings.TrimSpace(record.Metadata["bound_hostname"]) == "" {+ record.Metadata["bound_hostname"] = requestedHost+ }record.Metadata["bound_at"] = time.Now().UTC().Format(time.RFC3339)record.Metadata[agentExecBindingVersionKey] = agentExecBindingVersionif r.persistence != nil {@@ -394,3 +410,40 @@ func canBindAgentInstallExecToken(record *config.APITokenRecord, agentID string,return false}}++// canBindAutoRegisteredAgentInstallExecToken reports whether an install token+// whose bound_hostname was populated by the Proxmox auto-register bootstrap may+// take the clean first-use exec bind. The registration path writes+// bound_hostname without bound_agent_id or a binding version, so the record+// looks identical to a pre-v6.1.1 deploy token; without this the first command+// enrollment of a freshly installed Proxmox host is admitted by the+// legacy-migration branch, which exists to repair old records and is not the+// contract this flow should depend on. Hostname equivalence is still required.+func canBindAutoRegisteredAgentInstallExecToken(record *config.APITokenRecord, agentID string, hostname string) bool {+ if record == nil || strings.TrimSpace(agentID) == "" || strings.TrimSpace(hostname) == "" {+ return false+ }+ if strings.TrimSpace(record.Metadata["bound_agent_id"]) != "" {+ return false+ }+ if strings.TrimSpace(record.Metadata[agentExecBindingVersionKey]) != "" {+ return false+ }+ boundHost := strings.TrimSpace(record.Metadata["bound_hostname"])+ if boundHost == "" || !agentExecHostnamesMatch(boundHost, strings.TrimSpace(hostname)) {+ return false+ }++ switch strings.TrimSpace(record.Metadata["install_type"]) {+ case proxmoxInstallTypePVE, proxmoxInstallTypePBS, agentInstallTypeHost:+ default:+ return false+ }++ switch strings.TrimSpace(record.Metadata["issued_via"]) {+ case agentInstallIssuedViaConfig, agentInstallIssuedViaHosted:+ return true+ default:+ return false+ }+}diff --git a/internal/api/agent_install_command_shared.go b/internal/api/agent_install_command_shared.goindex b65026dc26..436fda94eb 100644--- a/internal/api/agent_install_command_shared.go+++ b/internal/api/agent_install_command_shared.go@@ -8,6 +8,7 @@ import ("net/url""strconv""strings"+ "time""github.com/rcourtman/pulse-go-rewrite/internal/config"internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"@@ -99,6 +100,15 @@ func issueAndPersistAgentInstallToken(cfg *config.Config, persistence *config.Coreturn "", nil, fmt.Errorf("%w: %w", errAgentInstallTokenRecord, err)}+ // Install tokens are minted without an expiry because the agent reports+ // with them for the life of the install. Stamp the mint time so the+ // one-shot Proxmox bootstrap grant they carry can expire on its own clock+ // (proxmoxInstallBootstrapGrantTTL) instead of staying live forever.+ if record.Metadata == nil {+ record.Metadata = make(map[string]string)+ }+ record.Metadata[agentInstallTokenIssuedAtKey] = record.CreatedAt.UTC().Format(time.RFC3339)+config.Mu.Lock()defer config.Mu.Unlock()diff --git a/internal/api/config_setup_handlers.go b/internal/api/config_setup_handlers.goindex 67edbb4c91..4bc7bdbff7 100644--- a/internal/api/config_setup_handlers.go+++ b/internal/api/config_setup_handlers.go@@ -56,8 +56,52 @@ const (proxmoxInstallRegistrationHostKey = "proxmox_registration_host"proxmoxInstallRegistrationNodeKey = "proxmox_registration_node"proxmoxInstallRegistrationAtKey = "proxmox_registration_at"+ // agentInstallTokenIssuedAtKey records when an install token was minted so+ // the one-shot source-creation grant can expire independently of the+ // token's own (unbounded) reporting lifetime.+ agentInstallTokenIssuedAtKey = "install_issued_at")+// proxmoxInstallBootstrapGrantTTL bounds how long after mint the one-shot+// Proxmox source-creation grant stays exercisable. Install tokens are minted+// without an expiry because the agent keeps reporting with them forever, so+// without this bound every host install token on a Proxmox box would carry a+// live create-a-source capability for the lifetime of the install. The window+// only has to cover copy-paste-and-run of the installer command.+const proxmoxInstallBootstrapGrantTTL = 24 * time.Hour++// proxmoxInstallGrantExpiredMessage is the distinct denial log for a grant+// that was otherwise valid but is past proxmoxInstallBootstrapGrantTTL. The+// request still takes the ordinary update-only path and its 403.+const proxmoxInstallGrantExpiredMessage = "Proxmox install bootstrap grant expired; install token stays update-only"++// proxmoxInstallGrantIssuedAt resolves the grant clock for a token record.+// Tokens minted after #1644 carry an explicit install_issued_at; older records+// fall back to the token's own creation timestamp. A record with neither is+// treated as having no grant clock at all, which fails the grant closed.+func proxmoxInstallGrantIssuedAt(record *config.APITokenRecord) (time.Time, bool) {+ if record == nil {+ return time.Time{}, false+ }+ if raw := strings.TrimSpace(record.Metadata[agentInstallTokenIssuedAtKey]); raw != "" {+ if parsed, err := time.Parse(time.RFC3339, raw); err == nil {+ return parsed.UTC(), true+ }+ }+ if !record.CreatedAt.IsZero() {+ return record.CreatedAt.UTC(), true+ }+ return time.Time{}, false+}++func proxmoxInstallGrantExpiredAt(record *config.APITokenRecord, now time.Time) bool {+ issuedAt, ok := proxmoxInstallGrantIssuedAt(record)+ if !ok {+ return true+ }+ return now.UTC().Sub(issuedAt) >= proxmoxInstallBootstrapGrantTTL+}+// installTokenTypeGrantsBootstrap decides whether an install token minted for// installType may bootstrap a source of requestedType. Proxmox-typed tokens// stay pinned to their declared type. A generic host-agent install token may@@ -72,7 +116,11 @@ func installTokenTypeGrantsBootstrap(installType, requestedType string) bool {return installType == agentInstallTypeHost && isCanonicalAutoRegisterType(requestedType)}-func canBootstrapProxmoxInstallRegistration(record *config.APITokenRecord, req *AutoRegisterRequest) bool {+// proxmoxInstallGrantEligible applies every bootstrap-grant bound except the+// mint-age TTL. It is split out so an expired-but-otherwise-valid grant can be+// reported with its own denial log instead of being indistinguishable from a+// token that never held a grant.+func proxmoxInstallGrantEligible(record *config.APITokenRecord, req *AutoRegisterRequest) bool {if record == nil || req == nil || strings.TrimSpace(req.Source) != "agent" {return false}@@ -97,6 +145,21 @@ func canBootstrapProxmoxInstallRegistration(record *config.APITokenRecord, req *return true}+// proxmoxInstallGrantExpiredForRequest reports a grant that would have been+// exercisable but for the mint-age TTL.+func proxmoxInstallGrantExpiredForRequest(record *config.APITokenRecord, req *AutoRegisterRequest) bool {+ return proxmoxInstallGrantEligible(record, req) &&+ proxmoxInstallGrantExpiredAt(record, time.Now().UTC())+}++func canBootstrapProxmoxInstallRegistration(record *config.APITokenRecord, req *AutoRegisterRequest) bool {+ return canBootstrapProxmoxInstallRegistrationAt(record, req, time.Now().UTC())+}++func canBootstrapProxmoxInstallRegistrationAt(record *config.APITokenRecord, req *AutoRegisterRequest, now time.Time) bool {+ return proxmoxInstallGrantEligible(record, req) && !proxmoxInstallGrantExpiredAt(record, now)+}+func completedProxmoxInstallRegistrationMatches(record *config.APITokenRecord, req *AutoRegisterRequest) bool {if record == nil || req == nil ||!strings.EqualFold(strings.TrimSpace(record.Metadata[proxmoxInstallRegistrationCompletedKey]), "true") {@@ -177,10 +240,21 @@ func (h *ConfigHandlers) proxmoxInstallBootstrapAvailable(ctx context.Context, rreturn false}-func (h *ConfigHandlers) completeProxmoxInstallBootstrap(ctx context.Context, req *AutoRegisterRequest, host, node string) error {+// proxmoxInstallBootstrapConsumption records a grant consumption that can be+// undone when the work it authorized fails to persist. Consumption is durable+// before the source is written, so an unrecoverable SaveNodesConfig must put+// the grant back rather than leave a consumed grant with no source (or, worse,+// leave the grant live next to a persisted source).+type proxmoxInstallBootstrapConsumption struct {+ tokenID string+ previousMetadata map[string]string+ consumed bool+}++func (h *ConfigHandlers) completeProxmoxInstallBootstrap(ctx context.Context, req *AutoRegisterRequest, host, node string) (*proxmoxInstallBootstrapConsumption, error) {auth, ok := getAgentAutoRegAuth(ctx)if !ok || !auth.installBootstrap || strings.TrimSpace(auth.tokenID) == "" {- return nil+ return nil, nil}persistence := h.getPersistence(ctx)@@ -189,7 +263,7 @@ func (h *ConfigHandlers) completeProxmoxInstallBootstrap(ctx context.Context, recfg := h.getConfig(ctx)if cfg == nil {- return fmt.Errorf("configuration unavailable")+ return nil, fmt.Errorf("configuration unavailable")}for i := range cfg.APITokens {record := &cfg.APITokens[i]@@ -197,10 +271,10 @@ func (h *ConfigHandlers) completeProxmoxInstallBootstrap(ctx context.Context, recontinue}if completedProxmoxInstallRegistrationMatches(record, req) {- return nil+ return nil, nil}if !canBootstrapProxmoxInstallRegistration(record, req) {- return fmt.Errorf("Proxmox install registration grant is no longer available")+ return nil, fmt.Errorf("Proxmox install registration grant is no longer available")}if record.Metadata == nil {record.Metadata = make(map[string]string)@@ -218,12 +292,59 @@ func (h *ConfigHandlers) completeProxmoxInstallBootstrap(ctx context.Context, reif 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, fmt.Errorf("persist Proxmox install registration grant: %w", err)}}- return nil+ return &proxmoxInstallBootstrapConsumption{+ tokenID: record.ID,+ previousMetadata: previousMetadata,+ consumed: true,+ }, nil+ }+ return nil, fmt.Errorf("Proxmox install token no longer exists")+}++// rollbackProxmoxInstallBootstrap restores a grant consumed by+// completeProxmoxInstallBootstrap. It is best effort by necessity — the token+// store just failed us once — but it keeps the common case atomic: either the+// source is persisted and the grant is spent, or neither happened.+func (h *ConfigHandlers) rollbackProxmoxInstallBootstrap(ctx context.Context, consumption *proxmoxInstallBootstrapConsumption) {+ if consumption == nil || !consumption.consumed {+ return+ }++ persistence := h.getPersistence(ctx)+ config.Mu.Lock()+ defer config.Mu.Unlock()++ cfg := h.getConfig(ctx)+ if cfg == nil {+ return+ }+ for i := range cfg.APITokens {+ record := &cfg.APITokens[i]+ if record.ID != consumption.tokenID {+ continue+ }+ restored := make(map[string]string, len(consumption.previousMetadata))+ for key, value := range consumption.previousMetadata {+ restored[key] = value+ }+ record.Metadata = restored+ if persistence != nil {+ if err := persistence.SaveAPITokens(cfg.APITokens); err != nil {+ log.Error().+ Err(err).+ Str("token_id", consumption.tokenID).+ Msg("Failed to restore Proxmox install registration grant after a failed source save")+ return+ }+ }+ log.Warn().+ Str("token_id", consumption.tokenID).+ Msg("Restored Proxmox install registration grant after a failed source save")+ return}- return fmt.Errorf("Proxmox install token no longer exists")}// HandleSetupScript serves the setup script for Proxmox/PBS nodes@@ -1514,6 +1635,14 @@ func (h *ConfigHandlers) handleAutoRegister(w http.ResponseWriter, r *http.Requerecord.OrgID != "" && record.OrgID != requestOrgIDif !orgMismatch {installBootstrap := canBootstrapProxmoxInstallRegistration(record, &req)+ if !installBootstrap && proxmoxInstallGrantExpiredForRequest(record, &req) {+ log.Warn().+ Str("token_id", record.ID).+ Str("type", req.Type).+ Str("host", req.Host).+ Str("grant_ttl", proxmoxInstallBootstrapGrantTTL.String()).+ Msg(proxmoxInstallGrantExpiredMessage)+ }authenticated = truer = r.WithContext(context.WithValue(r.Context(), agentAutoRegContextKey{}, agentAutoRegAuth{tokenID: record.ID,@@ -1663,7 +1792,7 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *hif actualName == "" {actualName = req.ServerName}- if err := h.completeProxmoxInstallBootstrap(r.Context(), req, normalizedCandidates[0], actualName); err != nil {+ if _, err := h.completeProxmoxInstallBootstrap(r.Context(), req, normalizedCandidates[0], actualName); err != nil {log.Error().Err(err).Str("type", req.Type).@@ -1918,9 +2047,32 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *hafterFingerprint := nodesConfigFingerprint(postCfg.PVEInstances, postCfg.PBSInstances, postCfg.PMGInstances)configChanged := beforeFingerprint != afterFingerprint+ actualName := h.findInstanceNameByHost(r.Context(), req.Type, host)+ if actualName == "" {+ actualName = serverName+ }++ // Consume the one-shot install grant BEFORE the source is persisted. The+ // other order leaves a repeatable create-a-source primitive whenever the+ // token store write fails persistently: the node lands on disk while the+ // grant stays unconsumed, so the same install token can be replayed. If+ // the node save then fails, the consumption is rolled back so the failure+ // stays atomic and a genuine retry still works.+ consumption, err := h.completeProxmoxInstallBootstrap(r.Context(), req, host, actualName)+ if 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+ }+if configChanged {if err := h.getPersistence(r.Context()).SaveNodesConfig(postCfg.PVEInstances, postCfg.PBSInstances, postCfg.PMGInstances); err != nil {log.Error().Err(err).Msg("Failed to save auto-registered node")+ h.rollbackProxmoxInstallBootstrap(r.Context(), consumption)http.Error(w, "Failed to save configuration", http.StatusInternalServerError)return}@@ -1931,19 +2083,6 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *hMsg("Auto-register resulted in no persisted-config change; skipping SaveNodesConfig and monitor reload")}- actualName := h.findInstanceNameByHost(r.Context(), req.Type, host)- 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 fulldiff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex c54e041936..fd777aebc7 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -21940,3 +21940,76 @@ func TestContract_AgentCommandSessionLookupSurvivesStaleHostTokenID(t *testing.Tt.Fatal("unknown agent reported as connected")}}++// The one-shot Proxmox source-creation grant carried by an agent-install token+// is time-bounded independently of the token itself. Install tokens are minted+// without an expiry because the agent reports with them forever, so without+// this bound every host install token sitting on a Proxmox box would keep a+// live create-a-source capability for the life of the install (#1644).+func TestContract_ProxmoxInstallBootstrapGrantIsTimeBounded(t *testing.T) {+ if proxmoxInstallBootstrapGrantTTL != 24*time.Hour {+ t.Fatalf("Proxmox install bootstrap grant TTL = %s, want 24h", proxmoxInstallBootstrapGrantTTL)+ }+ if strings.TrimSpace(proxmoxInstallGrantExpiredMessage) == "" {+ t.Fatal("expired bootstrap grants must have their own denial message")+ }++ record := newTokenRecord(t, "contract-install-grant-ttl.12345678", []string{config.ScopeAgentReport}, map[string]string{+ "install_type": agentInstallTypeHost,+ "issued_via": agentInstallIssuedViaConfig,+ })+ req := &AutoRegisterRequest{+ Type: "pve",+ Host: "https://pve-contract.local:8006",+ ServerName: "pve-contract",+ Source: "agent",+ }+ mintedAt := record.CreatedAt.UTC()++ if !canBootstrapProxmoxInstallRegistrationAt(&record, req, mintedAt) {+ t.Fatal("a freshly minted install token did not hold its bootstrap grant")+ }+ if !canBootstrapProxmoxInstallRegistrationAt(&record, req, mintedAt.Add(proxmoxInstallBootstrapGrantTTL-time.Minute)) {+ t.Fatal("bootstrap grant expired before its TTL elapsed")+ }+ if canBootstrapProxmoxInstallRegistrationAt(&record, req, mintedAt.Add(proxmoxInstallBootstrapGrantTTL)) {+ t.Fatal("bootstrap grant survived its TTL")+ }+ if !proxmoxInstallGrantEligible(&record, req) {+ t.Fatal("TTL assertions were vacuous: the fixture is not otherwise grant eligible")+ }+}++// An install token whose bound_hostname was written by the Proxmox+// auto-register bootstrap still takes the clean first-use exec bind. That+// record shape (bound_hostname, no bound_agent_id, no binding version) is+// indistinguishable from a pre-v6.1.1 deploy token, and command enrollment for+// a freshly installed Proxmox host must not depend on the legacy repair branch+// (#1644).+func TestContract_AutoRegisteredInstallTokenTakesCleanExecFirstBind(t *testing.T) {+ record := newTokenRecord(t, "contract-autoreg-exec-bind.12345678", []string{config.ScopeAgentExec}, map[string]string{+ "install_type": agentInstallTypeHost,+ "issued_via": agentInstallIssuedViaConfig,+ "bound_hostname": "pve-contract",+ })++ decision := evaluateAgentExecBinding(&record, "agent-machine-id", "pve-contract")+ if !decision.admit || !decision.firstBind {+ t.Fatalf("auto-registered install token exec decision = %+v, want a clean first bind", decision)+ }+ if decision.legacyMigrate {+ t.Fatal("auto-registered install token was admitted through the legacy migration branch")+ }++ // The binding is still hostname-gated: a different host holding the same+ // token gets no first-use bind.+ if other := evaluateAgentExecBinding(&record, "agent-machine-id", "pve-elsewhere"); other.firstBind {+ t.Fatalf("install token first-bound an unrelated hostname: %+v", other)+ }++ // A record already carrying a binding version is not a first use.+ record.Metadata[agentExecBindingVersionKey] = agentExecBindingVersion+ if bound := evaluateAgentExecBinding(&record, "agent-machine-id", "pve-contract"); bound.firstBind {+ t.Fatalf("an already-versioned binding was replayed as a first use: %+v", bound)+ }+}diff --git a/internal/api/issue1644_host_install_token_proxmox_test.go b/internal/api/issue1644_host_install_token_proxmox_test.goindex 156c5fbe4f..9e79e164a4 100644--- a/internal/api/issue1644_host_install_token_proxmox_test.go+++ b/internal/api/issue1644_host_install_token_proxmox_test.go@@ -5,8 +5,11 @@ import ("encoding/json""net/http""net/http/httptest"+ "os"+ "path/filepath""strings""testing"+ "time""github.com/rcourtman/pulse-go-rewrite/internal/config")@@ -127,20 +130,27 @@ func TestIssue1644HostInstallTokenGrantStaysHostnameBound(t *testing.T) {}handler := newTestConfigHandlers(t, cfg)- firstRec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{- Type: "pve",- Host: "https://pve-bound.local:8006",- TokenID: "pulse-monitor@pve!pulse-pve-bound",- TokenValue: "proxmox-secret",- ServerName: "pve-bound",- Source: "agent",+ // Bind the grant WITHOUT consuming it: the agent's pre-registration check+ // binds the first presenting hostname and leaves the grant available for+ // the completion that follows. Completing a registration first would make+ // the cross-host assertion below pass on the spent-grant path instead of+ // the hostname binding, which is the thing under test.+ checkRec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{+ Type: "pve",+ Host: "https://pve-bound.local:8006",+ ServerName: "pve-bound",+ Source: "agent",+ CheckRegistration: true,})- if firstRec.Code != http.StatusOK {- t.Fatalf("bound host-token registration status = %d, body=%s", firstRec.Code, firstRec.Body.String())+ if checkRec.Code != http.StatusOK {+ t.Fatalf("binding registration check status = %d, body=%s", checkRec.Code, checkRec.Body.String())}if got := cfg.APITokens[0].Metadata["bound_hostname"]; got != "pve-bound" {t.Fatalf("bound hostname = %q, want %q", got, "pve-bound")}+ if got := cfg.APITokens[0].Metadata[proxmoxInstallRegistrationCompletedKey]; strings.EqualFold(got, "true") {+ t.Fatalf("registration check consumed the grant (%s=%q); the cross-host assertion below would be vacuous", proxmoxInstallRegistrationCompletedKey, got)+ }otherHostRec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{Type: "pve",@@ -153,8 +163,382 @@ func TestIssue1644HostInstallTokenGrantStaysHostnameBound(t *testing.T) {if otherHostRec.Code != http.StatusForbidden {t.Fatalf("cross-host host-token registration status = %d, want 403; body=%s", otherHostRec.Code, otherHostRec.Body.String())}+ if len(cfg.PVEInstances) != 0 {+ t.Fatalf("PVE instances = %d, want 0 after cross-host rejection of an unconsumed grant", len(cfg.PVEInstances))+ }+ if got := cfg.APITokens[0].Metadata["bound_hostname"]; got != "pve-bound" {+ t.Fatalf("bound hostname after rejection = %q, want %q", got, "pve-bound")+ }++ // The grant itself is still live: the bound host completes normally. This+ // proves the rejection above came from the hostname binding and not from a+ // consumed or otherwise unusable grant.+ boundHostRec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{+ Type: "pve",+ Host: "https://pve-bound.local:8006",+ TokenID: "pulse-monitor@pve!pulse-pve-bound",+ TokenValue: "proxmox-secret",+ ServerName: "pve-bound",+ Source: "agent",+ })+ if boundHostRec.Code != http.StatusOK {+ t.Fatalf("bound-host registration status = %d, body=%s", boundHostRec.Code, boundHostRec.Body.String())+ }if len(cfg.PVEInstances) != 1 {- t.Fatalf("PVE instances = %d, want 1 after cross-host rejection", len(cfg.PVEInstances))+ t.Fatalf("PVE instances = %d, want 1 after the bound host completes", len(cfg.PVEInstances))+ }+}++func TestIssue1644HostInstallTokenBootstrapGrantExpiresAfterTTL(t *testing.T) {+ stubAutoRegisterNetworkDeps(t)++ rawToken := "issue-1644-host-expired.12345678"+ record := newTokenRecord(t, rawToken, []string{config.ScopeAgentReport}, map[string]string{+ "install_type": agentInstallTypeHost,+ "issued_via": agentInstallIssuedViaConfig,+ agentInstallTokenIssuedAtKey: time.Now().UTC().+ Add(-proxmoxInstallBootstrapGrantTTL - time.Hour).+ Format(time.RFC3339),+ })+ cfg := &config.Config{+ DataPath: t.TempDir(),+ APITokens: []config.APITokenRecord{record},+ }+ handler := newTestConfigHandlers(t, cfg)++ req := &AutoRegisterRequest{+ Type: "pve",+ Host: "https://pve-stale.local:8006",+ ServerName: "pve-stale",+ Source: "agent",+ }+ if !proxmoxInstallGrantEligible(&record, req) {+ t.Fatal("expired-grant fixture is not otherwise eligible; the TTL assertion would be vacuous")+ }+ if !proxmoxInstallGrantExpiredForRequest(&record, req) {+ t.Fatal("grant minted beyond the TTL was not reported as expired")+ }+ if canBootstrapProxmoxInstallRegistration(&record, req) {+ t.Fatal("grant minted beyond the TTL still authorized a bootstrap")+ }++ checkRec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{+ Type: "pve",+ Host: "https://pve-stale.local:8006",+ ServerName: "pve-stale",+ Source: "agent",+ CheckRegistration: true,+ })+ if checkRec.Code != http.StatusOK {+ t.Fatalf("expired-grant registration check status = %d, body=%s", checkRec.Code, checkRec.Body.String())+ }+ var check autoRegisterCheckResponse+ if err := json.Unmarshal(checkRec.Body.Bytes(), &check); err != nil {+ t.Fatalf("decode registration check: %v", err)+ }+ if check.CanRegister {+ t.Fatal("expired grant reported canRegister=true")+ }+ if got := cfg.APITokens[0].Metadata["bound_hostname"]; got != "" {+ t.Fatalf("expired grant bound a hostname (%q); it must not take the binding path", got)+ }++ registerRec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{+ Type: "pve",+ Host: "https://pve-stale.local:8006",+ TokenID: "pulse-monitor@pve!pulse-pve-stale",+ TokenValue: "proxmox-secret",+ ServerName: "pve-stale",+ Source: "agent",+ })+ if registerRec.Code != http.StatusForbidden {+ t.Fatalf("expired-grant registration status = %d, want 403; body=%s", registerRec.Code, registerRec.Body.String())+ }+ if len(cfg.PVEInstances) != 0 {+ t.Fatalf("PVE instances = %d, want 0 for an expired grant", len(cfg.PVEInstances))+ }+}++func TestIssue1644HostInstallTokenBootstrapGrantSurvivesInsideTTL(t *testing.T) {+ stubAutoRegisterNetworkDeps(t)++ rawToken := "issue-1644-host-fresh.12345678"+ record := newTokenRecord(t, rawToken, []string{config.ScopeAgentReport}, map[string]string{+ "install_type": agentInstallTypeHost,+ "issued_via": agentInstallIssuedViaConfig,+ agentInstallTokenIssuedAtKey: time.Now().UTC().+ Add(-proxmoxInstallBootstrapGrantTTL + time.Hour).+ Format(time.RFC3339),+ })+ cfg := &config.Config{+ DataPath: t.TempDir(),+ APITokens: []config.APITokenRecord{record},+ }+ handler := newTestConfigHandlers(t, cfg)++ registerRec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{+ Type: "pve",+ Host: "https://pve-fresh.local:8006",+ TokenID: "pulse-monitor@pve!pulse-pve-fresh",+ TokenValue: "proxmox-secret",+ ServerName: "pve-fresh",+ Source: "agent",+ })+ if registerRec.Code != http.StatusOK {+ t.Fatalf("in-TTL registration status = %d, body=%s", registerRec.Code, registerRec.Body.String())+ }+ if len(cfg.PVEInstances) != 1 {+ t.Fatalf("PVE instances = %d, want 1 for a grant inside the TTL", len(cfg.PVEInstances))+ }+}++func TestIssue1644InstallTokenMintStampsGrantIssuedAt(t *testing.T) {+ cfg := &config.Config{+ DataPath: t.TempDir(),+ AuthUser: "admin",+ AuthPass: "hashed-password",+ }+ handler := newTestConfigHandlers(t, cfg)+ mintHostInstallToken(t, handler)++ if len(cfg.APITokens) != 1 {+ t.Fatalf("API tokens = %d, want 1", len(cfg.APITokens))+ }+ raw := strings.TrimSpace(cfg.APITokens[0].Metadata[agentInstallTokenIssuedAtKey])+ if raw == "" {+ t.Fatalf("minted install token is missing %q; the bootstrap grant would have no expiry clock", agentInstallTokenIssuedAtKey)+ }+ issuedAt, err := time.Parse(time.RFC3339, raw)+ if err != nil {+ t.Fatalf("parse %s=%q: %v", agentInstallTokenIssuedAtKey, raw, err)+ }+ if delta := time.Since(issuedAt); delta < -time.Minute || delta > time.Minute {+ t.Fatalf("%s = %s is not the mint time (delta %s)", agentInstallTokenIssuedAtKey, raw, delta)+ }+}++// Issue #1644 follow-up: SaveNodesConfig ran before the grant was consumed, so+// a persistently failing token-store write left a created source on disk next+// to a live grant — a repeatable create-a-source primitive. The grant is now+// consumed first and rolled back when the source fails to persist, so the+// failure is atomic: no source, and the grant is still exactly one use.+func TestIssue1644FailedSourceSaveRollsBackGrantConsumption(t *testing.T) {+ stubAutoRegisterNetworkDeps(t)++ dataPath := t.TempDir()+ cfg := &config.Config{+ DataPath: dataPath,+ AuthUser: "admin",+ AuthPass: "hashed-password",+ }+ handler := newTestConfigHandlers(t, cfg)+ rawToken := mintHostInstallToken(t, handler)++ // Block only the nodes store: a directory where the nodes file belongs+ // fails the rename, while API token writes keep working.+ if err := os.MkdirAll(filepath.Join(dataPath, "nodes.enc"), 0o755); err != nil {+ t.Fatalf("block nodes config persistence: %v", err)+ }++ registerRec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{+ Type: "pve",+ Host: "https://pve-rollback.local:8006",+ TokenID: "pulse-monitor@pve!pulse-pve-rollback",+ TokenValue: "proxmox-secret",+ ServerName: "pve-rollback",+ Source: "agent",+ })+ if registerRec.Code != http.StatusInternalServerError {+ t.Fatalf("blocked source save status = %d, want 500; body=%s", registerRec.Code, registerRec.Body.String())+ }++ if got := cfg.APITokens[0].Metadata[proxmoxInstallRegistrationCompletedKey]; strings.EqualFold(strings.TrimSpace(got), "true") {+ t.Fatalf("grant stayed consumed (%s=%q) after the source failed to persist", proxmoxInstallRegistrationCompletedKey, got)+ }++ persisted, err := config.NewConfigPersistence(dataPath).LoadAPITokens()+ if err != nil {+ t.Fatalf("load persisted API tokens: %v", err)+ }+ if len(persisted) != 1 {+ t.Fatalf("persisted API tokens = %d, want 1", len(persisted))+ }+ if got := persisted[0].Metadata[proxmoxInstallRegistrationCompletedKey]; strings.EqualFold(strings.TrimSpace(got), "true") {+ t.Fatalf("persisted grant stayed consumed (%s=%q) after the source failed to persist", proxmoxInstallRegistrationCompletedKey, got)+ }++ // With the nodes store working again the same install completes exactly+ // once, and the restored grant is spent by that completion.+ if err := os.Remove(filepath.Join(dataPath, "nodes.enc")); err != nil {+ t.Fatalf("unblock nodes config persistence: %v", err)+ }+ retryRec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{+ Type: "pve",+ Host: "https://pve-rollback.local:8006",+ TokenID: "pulse-monitor@pve!pulse-pve-rollback",+ TokenValue: "proxmox-secret",+ ServerName: "pve-rollback",+ Source: "agent",+ })+ if retryRec.Code != http.StatusOK {+ t.Fatalf("retry after restored persistence status = %d, body=%s", retryRec.Code, retryRec.Body.String())+ }+ if !strings.EqualFold(cfg.APITokens[0].Metadata[proxmoxInstallRegistrationCompletedKey], "true") {+ t.Fatal("retry did not consume the restored grant")+ }+}++// Issue #1644 follow-up: with SaveNodesConfig running first, a persistently+// failing token-store write left the source on disk while the grant stayed+// unconsumed — replay the install and every new host URL under the bound+// hostname creates another source. Consuming first means a token-store failure+// aborts before anything is persisted.+func TestIssue1644FailedGrantConsumptionLeavesNoPersistedSource(t *testing.T) {+ stubAutoRegisterNetworkDeps(t)++ dataPath := t.TempDir()+ cfg := &config.Config{+ DataPath: dataPath,+ AuthUser: "admin",+ AuthPass: "hashed-password",+ }+ handler := newTestConfigHandlers(t, cfg)+ rawToken := mintHostInstallToken(t, handler)++ // Bind the hostname while the token store still works, so the failure+ // under test is the grant consumption and not the first-use binding.+ checkRec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{+ Type: "pve",+ Host: "https://pve-replay.local:8006",+ ServerName: "pve-replay",+ Source: "agent",+ CheckRegistration: true,+ })+ if checkRec.Code != http.StatusOK {+ t.Fatalf("binding registration check status = %d, body=%s", checkRec.Code, checkRec.Body.String())+ }++ // Block only the token store: a directory where the API token file belongs+ // fails the rename, while the nodes config would still save happily.+ apiTokensFile := filepath.Join(dataPath, "api_tokens.json")+ if err := os.Remove(apiTokensFile); err != nil {+ t.Fatalf("clear API token file: %v", err)+ }+ if err := os.MkdirAll(apiTokensFile, 0o755); err != nil {+ t.Fatalf("block API token persistence: %v", err)+ }++ registerRec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{+ Type: "pve",+ Host: "https://pve-replay.local:8006",+ TokenID: "pulse-monitor@pve!pulse-pve-replay",+ TokenValue: "proxmox-secret",+ ServerName: "pve-replay",+ Source: "agent",+ })+ if registerRec.Code != http.StatusInternalServerError {+ t.Fatalf("blocked grant consumption status = %d, want 500; body=%s", registerRec.Code, registerRec.Body.String())+ }+ if _, err := os.Stat(filepath.Join(dataPath, "nodes.enc")); !os.IsNotExist(err) {+ t.Fatalf("source was persisted despite an unconsumable grant (stat nodes.enc err = %v); the install is replayable", err)+ }+ if strings.EqualFold(strings.TrimSpace(cfg.APITokens[0].Metadata[proxmoxInstallRegistrationCompletedKey]), "true") {+ t.Fatal("failed grant consumption left the completion marker behind")+ }+}++// Issue #1644 follow-up: the auto-register path writes bound_hostname for host+// install tokens without bound_agent_id or a binding version, which is exactly+// the shape canBindAgentInstallExecToken refuses. The first command-channel+// enrollment of a freshly auto-registered Proxmox host must take the clean+// first-use bind rather than the legacy pre-v6.1.1 migration branch.+func TestIssue1644AutoRegisteredHostTokenBindsExecOnFirstUse(t *testing.T) {+ stubAutoRegisterNetworkDeps(t)++ dataPath := t.TempDir()+ cfg := &config.Config{+ DataPath: dataPath,+ AuthUser: "admin",+ AuthPass: "hashed-password",+ }+ handler := newTestConfigHandlers(t, cfg)++ installReq := httptest.NewRequest(+ http.MethodPost,+ "/api/agent-install-command",+ strings.NewReader(`{"type":"host","name":"issue-1644-exec","enableCommands":true}`),+ )+ installReq.Host = "pulse.example:7655"+ installRec := httptest.NewRecorder()+ handler.HandleAgentInstallCommand(installRec, installReq)+ if installRec.Code != http.StatusOK {+ t.Fatalf("host install token mint 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 host install token response: %v", err)+ }+ rawToken := strings.TrimSpace(install.Token)+ if rawToken == "" {+ t.Fatal("host install token mint omitted runtime token")+ }+ if !cfg.APITokens[0].HasScope(config.ScopeAgentExec) {+ t.Fatalf("commands-enabled host install token is missing %s: %v", config.ScopeAgentExec, cfg.APITokens[0].Scopes)+ }++ registerRec := runAgentAutoRegister(t, handler, rawToken, AutoRegisterRequest{+ Type: "pve",+ Host: "https://pve-exec.local:8006",+ TokenID: "pulse-monitor@pve!pulse-pve-exec",+ TokenValue: "proxmox-secret",+ ServerName: "pve-exec",+ Source: "agent",+ })+ if registerRec.Code != http.StatusOK {+ t.Fatalf("host-token pve registration status = %d, body=%s", registerRec.Code, registerRec.Body.String())+ }+ if got := cfg.APITokens[0].Metadata["bound_hostname"]; got != "pve-exec" {+ t.Fatalf("auto-register bound hostname = %q, want %q", got, "pve-exec")+ }+ if got := strings.TrimSpace(cfg.APITokens[0].Metadata["bound_agent_id"]); got != "" {+ t.Fatalf("auto-register wrote bound_agent_id = %q; the exec first-use path assumes it is empty", got)+ }++ // The agent enrols on the command channel with its machine-id derived+ // runtime ID and the same hostname, spelled as the reporting FQDN.+ decision := evaluateAgentExecBinding(&cfg.APITokens[0], "agent-machine-id", "pve-exec.lan")+ if !decision.admit || !decision.firstBind {+ t.Fatalf("auto-registered install token exec decision = %+v, want a clean first bind", decision)+ }+ if decision.legacyMigrate {+ t.Fatal("auto-registered install token was admitted through the legacy migration branch")+ }++ router := &Router{+ config: cfg,+ persistence: config.NewConfigPersistence(dataPath),+ }+ admission, ok := router.admitAgentExecToken(rawToken, "agent-machine-id", "pve-exec.lan")+ if !ok {+ t.Fatal("auto-registered host install token was rejected on the command channel")+ }+ if admission.AgentID != "agent-machine-id" {+ t.Fatalf("admitted agent id = %q, want %q", admission.AgentID, "agent-machine-id")+ }++ config.Mu.RLock()+ defer config.Mu.RUnlock()+ bound := cfg.APITokens[0].Metadata+ if got := bound["bound_agent_id"]; got != "agent-machine-id" {+ t.Fatalf("bound_agent_id = %q, want %q", got, "agent-machine-id")+ }+ if got := bound[agentExecBindingVersionKey]; got != agentExecBindingVersion {+ t.Fatalf("%s = %q, want %q", agentExecBindingVersionKey, got, agentExecBindingVersion)+ }+ // The install grant compares req.ServerName against bound_hostname, so an+ // equivalent FQDN spelling from the agent must not rewrite it.+ if got := bound["bound_hostname"]; got != "pve-exec" {+ t.Fatalf("bound_hostname after exec bind = %q, want the auto-registered %q", got, "pve-exec")}}