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.

Mint host agent install tokens server-side with the exec scope the checkbox asks for

rcourtmand56659a40287
diff --git a/frontend-modern/src/api/nodes.ts b/frontend-modern/src/api/nodes.ts
index 1e1b0b5dd1..1e9bce691d 100644
--- a/frontend-modern/src/api/nodes.ts
+++ b/frontend-modern/src/api/nodes.ts
@@ -1,4 +1,5 @@
import type { ClusterEndpoint, NodeConfig } from '../types/nodes';
+import type { APITokenRecord } from '../types/api';
import { apiFetch, apiFetchJSON } from '@/utils/apiClient';
import {
arrayOrUndefined,
@@ -52,6 +53,16 @@ export type AgentInstallCommandResponse = {
command: string;
};
+type RawHostAgentInstallTokenResponse = {
+ token?: unknown;
+ record?: APITokenRecord | null;
+};
+
+export type HostAgentInstallTokenResponse = {
+ token: string;
+ record: APITokenRecord;
+};
+
type RawProxmoxSetupCommandResponse = {
type?: unknown;
host?: unknown;
@@ -246,6 +257,34 @@ export class NodesAPI {
return normalizeAgentInstallCommandResponse(response);
}
+ /**
+ * Mint an install token for the generic unified host agent flow. The server
+ * decides the scopes from enableCommands at mint time (scopes cannot be
+ * upgraded on an existing token) and stamps the metadata that makes the
+ * token eligible for first-use command-channel binding.
+ */
+ static async createHostAgentInstallToken(params: {
+ enableCommands: boolean;
+ name?: string;
+ }): Promise<HostAgentInstallTokenResponse> {
+ const response = await apiFetchJSON<RawHostAgentInstallTokenResponse>(
+ '/api/agent-install-command',
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ type: 'host',
+ enableCommands: params.enableCommands,
+ ...(params.name ? { name: params.name } : {}),
+ }),
+ },
+ );
+ const token = trimmedString(response.token);
+ if (!token || !response.record) {
+ throw new Error('Invalid host agent install token response');
+ }
+ return { token, record: response.record };
+ }
+
static async getProxmoxSetupCommand(params: {
type: 'pve' | 'pbs';
host: string;
diff --git a/frontend-modern/src/components/Settings/__tests__/InfrastructureOperationsModel.test.tsx b/frontend-modern/src/components/Settings/__tests__/InfrastructureOperationsModel.test.tsx
index 448e1e80ab..9dd4cfe1c1 100644
--- a/frontend-modern/src/components/Settings/__tests__/InfrastructureOperationsModel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/InfrastructureOperationsModel.test.tsx
@@ -348,12 +348,14 @@ describe('infrastructure operations model', () => {
expect(useInfrastructureConfiguredNodesStateSource).not.toContain('...nodeData,');
});
- it('keeps reusable install tokens out of the command-exec scope', () => {
- expect(useInfrastructureInstallStateSource).toContain('AGENT_REPORT_SCOPE');
- expect(useInfrastructureInstallStateSource).toContain('AGENT_CONFIG_READ_SCOPE');
- expect(useInfrastructureInstallStateSource).toContain('DOCKER_REPORT_SCOPE');
- expect(useInfrastructureInstallStateSource).toContain('KUBERNETES_REPORT_SCOPE');
+ it('delegates install-token scopes to the server mint endpoint', () => {
+ // The server decides scopes from the command-execution choice at mint
+ // time (#1586); the frontend must not compose install-token scope lists.
+ expect(useInfrastructureInstallStateSource).toContain('createHostAgentInstallToken');
+ expect(useInfrastructureInstallStateSource).toContain('enableCommands: withCommands');
+ expect(useInfrastructureInstallStateSource).not.toContain('SecurityAPI.createToken');
expect(useInfrastructureInstallStateSource).not.toContain('AGENT_EXEC_SCOPE');
+ expect(useInfrastructureInstallStateSource).not.toContain('AGENT_REPORT_SCOPE');
});
it('keeps infrastructure install and operations surfaces free of retired commercial telemetry wrappers', () => {
diff --git a/frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx b/frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx
index 23b74a116f..2ebf7153a2 100644
--- a/frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx
+++ b/frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx
@@ -1,16 +1,11 @@
import { createEffect, createMemo, createSignal, onCleanup, onMount } from 'solid-js';
import { useLocation, useNavigate } from '@solidjs/router';
import { MonitoringAPI } from '@/api/monitoring';
+import { NodesAPI } from '@/api/nodes';
import { SecurityAPI, type APITokenRecord } from '@/api/security';
import { notificationStore } from '@/stores/notifications';
import type { AgentLookupResponse, ConnectedInfrastructureItem } from '@/types/api';
import type { SecurityStatus } from '@/types/config';
-import {
- AGENT_CONFIG_READ_SCOPE,
- AGENT_REPORT_SCOPE,
- DOCKER_REPORT_SCOPE,
- KUBERNETES_REPORT_SCOPE,
-} from '@/constants/apiScopes';
import { copyToClipboard } from '@/utils/clipboard';
import { getPulseBaseUrl } from '@/utils/url';
import { logger } from '@/utils/logger';
@@ -256,14 +251,16 @@ Pulse prepares the first-host install token from setup so you can move straight
) => {
setIsGeneratingToken(true);
try {
+ // The server owns install-token semantics. It decides the scopes from
+ // the command-execution choice at mint time (scopes cannot be upgraded
+ // on an existing token) and stamps the metadata the command channel
+ // needs for first-use binding (#1586).
+ const withCommands = enableCommands();
const desiredName = tokenName().trim() || buildDefaultTokenName();
- const scopes = [
- AGENT_REPORT_SCOPE,
- AGENT_CONFIG_READ_SCOPE,
- DOCKER_REPORT_SCOPE,
- KUBERNETES_REPORT_SCOPE,
- ];
- const { token, record } = await SecurityAPI.createToken(desiredName, scopes);
+ const { token, record } = await NodesAPI.createHostAgentInstallToken({
+ enableCommands: withCommands,
+ name: desiredName,
+ });
if (disposed) {
return;
@@ -276,7 +273,9 @@ Pulse prepares the first-host install token from setup so you can move straight
setSetupHandoffAutoTokenFailed(false);
if (options.notifySuccess) {
notificationStore.success(
- 'Token generated with Agent config, reporting, Docker, and Kubernetes permissions.',
+ withCommands
+ ? 'Token generated with Agent config, reporting, Docker, Kubernetes, and command execution permissions.'
+ : 'Token generated with Agent config, reporting, Docker, and Kubernetes permissions.',
4000,
);
}
@@ -309,6 +308,34 @@ Pulse prepares the first-host install token from setup so you can move straight
await generateInstallToken('manual', { notifySuccess: true });
};
+ // Toggling command execution changes which scopes the token needs, and an
+ // already-minted token cannot be upgraded. Regenerate it so the copied
+ // command always carries a token that matches the checkbox (#1586).
+ const handleEnableCommandsChange = (value: boolean) => {
+ if (value === enableCommands()) return;
+ setEnableCommands(value);
+ if (currentToken() && !isGeneratingToken()) {
+ const source = latestTokenSource() ?? 'manual';
+ const supersededTokenId = latestRecord()?.id;
+ void generateInstallToken(source, { notifySuccess: false }).then(() => {
+ if (disposed || !currentToken()) return;
+ notificationStore.info(
+ value
+ ? 'Token regenerated with command execution permission. Copy the install command again.'
+ : 'Token regenerated without command execution permission. Copy the install command again.',
+ 5000,
+ );
+ // The superseded token was never handed to an agent; revoke it so
+ // toggling does not accumulate orphaned install tokens.
+ if (supersededTokenId && supersededTokenId !== latestRecord()?.id) {
+ SecurityAPI.deleteToken(supersededTokenId).catch((err) => {
+ logger.warn('Failed to revoke superseded install token', err);
+ });
+ }
+ });
+ }
+ };
+
const resolvedCommandToken = () => {
if (requiresToken()) {
return currentToken() || TOKEN_PLACEHOLDER;
@@ -545,7 +572,7 @@ Pulse prepares the first-host install token from setup so you can move straight
selectedAgentUrl,
setCustomAgentUrl,
setCustomCaPath,
- setEnableCommands,
+ setEnableCommands: handleEnableCommandsChange,
setInsecureMode,
setLookupValue,
setTokenName,
diff --git a/internal/api/agent_exec_token_binding.go b/internal/api/agent_exec_token_binding.go
index 4f16c3f674..ed6f5e6950 100644
--- a/internal/api/agent_exec_token_binding.go
+++ b/internal/api/agent_exec_token_binding.go
@@ -47,7 +47,7 @@ func (r *Router) validateAgentExecToken(token string, agentID string, hostname s
boundID := strings.TrimSpace(record.Metadata["bound_agent_id"])
boundHost := strings.TrimSpace(record.Metadata["bound_hostname"])
- if boundID == "" && boundHost == "" && canBindProxmoxAgentInstallExecToken(record, requestedID, requestedHost) {
+ if boundID == "" && boundHost == "" && canBindAgentInstallExecToken(record, requestedID, requestedHost) {
issuedVia := strings.TrimSpace(record.Metadata["issued_via"])
installType := strings.TrimSpace(record.Metadata["install_type"])
if record.Metadata == nil {
@@ -75,7 +75,7 @@ func (r *Router) validateAgentExecToken(token string, agentID string, hostname s
Str("hostname", requestedHost).
Str("issued_via", issuedVia).
Str("install_type", installType).
- Msg("Bound Proxmox agent install token to first command agent registration")
+ Msg("Bound agent install token to first command agent registration")
return true
}
@@ -108,7 +108,7 @@ func (r *Router) validateAgentExecToken(token string, agentID string, hostname s
return false
}
-func canBindProxmoxAgentInstallExecToken(record *config.APITokenRecord, agentID string, hostname string) bool {
+func canBindAgentInstallExecToken(record *config.APITokenRecord, agentID string, hostname string) bool {
if record == nil || strings.TrimSpace(agentID) == "" || strings.TrimSpace(hostname) == "" {
return false
}
@@ -118,7 +118,7 @@ func canBindProxmoxAgentInstallExecToken(record *config.APITokenRecord, agentID
}
switch strings.TrimSpace(record.Metadata["install_type"]) {
- case proxmoxInstallTypePVE, proxmoxInstallTypePBS:
+ case proxmoxInstallTypePVE, proxmoxInstallTypePBS, agentInstallTypeHost:
default:
return false
}
diff --git a/internal/api/agent_ingest.go b/internal/api/agent_ingest.go
index ac7e097b63..6536131414 100644
--- a/internal/api/agent_ingest.go
+++ b/internal/api/agent_ingest.go
@@ -551,7 +551,7 @@ func commandConfigAllowedForToken(record *config.APITokenRecord, host models.Hos
return true
}
- return boundID == "" && boundHost == "" && canBindProxmoxAgentInstallExecToken(record, requestedID, requestedHost)
+ return boundID == "" && boundHost == "" && canBindAgentInstallExecToken(record, requestedID, requestedHost)
}
func (h *UnifiedAgentHandlers) ensureAgentTokenMatch(w http.ResponseWriter, r *http.Request, agentID string) bool {
diff --git a/internal/api/agent_install_command_shared.go b/internal/api/agent_install_command_shared.go
index bebe75b839..dbab19b7f2 100644
--- a/internal/api/agent_install_command_shared.go
+++ b/internal/api/agent_install_command_shared.go
@@ -16,6 +16,10 @@ import (
const (
proxmoxInstallTypePVE = "pve"
proxmoxInstallTypePBS = "pbs"
+ // agentInstallTypeHost marks install tokens minted for the generic unified
+ // host agent flow (Settings > Infrastructure > Add Pulse Agent), as opposed
+ // to the Proxmox-specific pve/pbs installer.
+ agentInstallTypeHost = "host"
)
var (
@@ -41,11 +45,33 @@ func proxmoxAgentInstallScopes() []string {
}
}
+// hostAgentInstallScopes returns the scopes for a generic unified host agent
+// install token. The exec scope is included only when the operator asked for
+// command execution, because the token is minted before the agent enrols and
+// scopes cannot be upgraded on an existing token.
+func hostAgentInstallScopes(enableCommands bool) []string {
+ scopes := []string{
+ config.ScopeAgentReport,
+ config.ScopeAgentConfigRead,
+ config.ScopeAgentManage,
+ config.ScopeDockerReport,
+ config.ScopeKubernetesReport,
+ }
+ if enableCommands {
+ scopes = append(scopes, config.ScopeAgentExec)
+ }
+ return scopes
+}
+
type issueAgentInstallTokenOptions struct {
TokenName string
OrgID string
OwnerUserID string
Metadata map[string]string
+ // Scopes overrides the default Proxmox install scope set when non-empty
+ // (used by the generic host agent flow, which honours the operator's
+ // command-execution choice instead of always granting exec).
+ Scopes []string
}
func issueAndPersistAgentInstallToken(cfg *config.Config, persistence *config.ConfigPersistence, opts issueAgentInstallTokenOptions) (string, *config.APITokenRecord, error) {
@@ -58,7 +84,11 @@ func issueAndPersistAgentInstallToken(cfg *config.Config, persistence *config.Co
return "", nil, fmt.Errorf("%w: %w", errAgentInstallTokenGeneration, err)
}
- record, err := config.NewAPITokenRecord(rawToken, opts.TokenName, proxmoxAgentInstallScopes())
+ scopes := opts.Scopes
+ if len(scopes) == 0 {
+ scopes = proxmoxAgentInstallScopes()
+ }
+ record, err := config.NewAPITokenRecord(rawToken, opts.TokenName, scopes)
if err != nil {
return "", nil, fmt.Errorf("%w: %w", errAgentInstallTokenRecord, err)
}
diff --git a/internal/api/config_setup_handlers.go b/internal/api/config_setup_handlers.go
index 6dbfe4c6af..f70c36c79b 100644
--- a/internal/api/config_setup_handlers.go
+++ b/internal/api/config_setup_handlers.go
@@ -1791,14 +1791,16 @@ func (h *ConfigHandlers) generateOrLoadSSHKey(sshDir, privateKeyPath, publicKeyP
// AgentInstallCommandRequest represents a request for an agent install command
type AgentInstallCommandRequest struct {
- Type string `json:"type"` // "pve" or "pbs"
+ Type string `json:"type"` // "pve", "pbs", or "host"
EnableCommands bool `json:"enableCommands,omitempty"`
+ Name string `json:"name,omitempty"` // optional token name (host installs)
}
// AgentInstallCommandResponse contains the generated install command
type AgentInstallCommandResponse struct {
- Command string `json:"command"`
- Token string `json:"token"`
+ Command string `json:"command"`
+ Token string `json:"token"`
+ Record *apiTokenDTO `json:"record,omitempty"`
}
// HandleAgentInstallCommand generates an API token and install command for agent-based Proxmox setup
@@ -1814,6 +1816,11 @@ func (h *ConfigHandlers) handleAgentInstallCommand(w http.ResponseWriter, r *htt
return
}
+ if strings.EqualFold(strings.TrimSpace(req.Type), agentInstallTypeHost) {
+ h.handleHostAgentInstallToken(w, r, req)
+ return
+ }
+
installType, err := normalizeProxmoxInstallType(req.Type)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
@@ -1874,3 +1881,52 @@ func (h *ConfigHandlers) handleAgentInstallCommand(w http.ResponseWriter, r *htt
Token: rawToken,
})
}
+
+// handleHostAgentInstallToken mints an install token for the generic unified
+// host agent flow (Settings > Infrastructure > Add Pulse Agent). The exec
+// scope must be decided here at mint time, because scopes cannot be upgraded
+// on an existing token; the frontend regenerates the token when the operator
+// toggles command execution. The install_type metadata makes the token
+// eligible for first-use binding in canBindAgentInstallExecToken, without
+// which the command channel rejects it even with the scope present (#1586).
+func (h *ConfigHandlers) handleHostAgentInstallToken(w http.ResponseWriter, r *http.Request, req AgentInstallCommandRequest) {
+ cfg := h.getConfig(r.Context())
+ persistence := h.getPersistence(r.Context())
+
+ if !authConfiguredForAgentLifecycle(cfg) {
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(AgentInstallCommandResponse{})
+ return
+ }
+
+ tokenName := strings.TrimSpace(req.Name)
+ if tokenName == "" {
+ tokenName = fmt.Sprintf("host-agent-%d", time.Now().Unix())
+ }
+ rawToken, record, err := issueAndPersistAgentInstallToken(cfg, persistence, issueAgentInstallTokenOptions{
+ TokenName: tokenName,
+ OwnerUserID: apiTokenOwnerUserIDForRequest(cfg, r),
+ Scopes: hostAgentInstallScopes(req.EnableCommands),
+ Metadata: map[string]string{
+ "install_type": agentInstallTypeHost,
+ "issued_via": agentInstallIssuedViaConfig,
+ },
+ })
+ if err != nil {
+ log.Error().Err(err).Str("token_name", tokenName).Msg("Failed to create host agent install token")
+ http.Error(w, "Failed to generate API token", http.StatusInternalServerError)
+ return
+ }
+
+ log.Info().
+ Str("type", agentInstallTypeHost).
+ Bool("enable_commands", req.EnableCommands).
+ Msg("Generated host agent install token")
+
+ dto := toAPITokenDTO(*record)
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(AgentInstallCommandResponse{
+ Token: rawToken,
+ Record: &dto,
+ })
+}
diff --git a/internal/api/host_agent_install_token_test.go b/internal/api/host_agent_install_token_test.go
new file mode 100644
index 0000000000..d513db19da
--- /dev/null
+++ b/internal/api/host_agent_install_token_test.go
@@ -0,0 +1,103 @@
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+func decodeHostAgentInstallResponse(t *testing.T, rec *httptest.ResponseRecorder) AgentInstallCommandResponse {
+ t.Helper()
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected status OK, got %d: %s", rec.Code, rec.Body.String())
+ }
+ var resp AgentInstallCommandResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("failed to decode response: %v", err)
+ }
+ return resp
+}
+
+func TestHandleAgentInstallCommand_HostWithCommands(t *testing.T) {
+ cfg := &config.Config{DataPath: t.TempDir(), AuthUser: "admin", AuthPass: "hashed-password"}
+ handler := newTestConfigHandlers(t, cfg)
+
+ body := []byte(`{"type":"host","enableCommands":true,"name":"nuc-agent"}`)
+ req := httptest.NewRequest(http.MethodPost, "/api/agent-install-command", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandleAgentInstallCommand(rec, req)
+
+ resp := decodeHostAgentInstallResponse(t, rec)
+ if resp.Token == "" {
+ t.Fatalf("expected token in response")
+ }
+ if resp.Record == nil {
+ t.Fatalf("expected token record in response")
+ }
+ if resp.Record.Name != "nuc-agent" {
+ t.Fatalf("expected requested token name, got %q", resp.Record.Name)
+ }
+ if len(cfg.APITokens) != 1 {
+ t.Fatalf("expected API token to be persisted")
+ }
+ record := cfg.APITokens[0]
+ if !record.HasScope(config.ScopeAgentExec) {
+ t.Fatalf("expected exec scope on commands-enabled host install token, got %v", record.Scopes)
+ }
+ if !record.HasScope(config.ScopeDockerReport) || !record.HasScope(config.ScopeAgentReport) {
+ t.Fatalf("expected reporting scopes on host install token, got %v", record.Scopes)
+ }
+ if got := record.Metadata["install_type"]; got != agentInstallTypeHost {
+ t.Fatalf("install_type metadata = %q, want %q", got, agentInstallTypeHost)
+ }
+ if got := record.Metadata["issued_via"]; got != agentInstallIssuedViaConfig {
+ t.Fatalf("issued_via metadata = %q, want %q", got, agentInstallIssuedViaConfig)
+ }
+ if !canBindAgentInstallExecToken(&record, "agent-nuc", "nuc") {
+ t.Fatalf("expected host install token to be eligible for first-use exec binding")
+ }
+}
+
+func TestHandleAgentInstallCommand_HostWithoutCommands(t *testing.T) {
+ cfg := &config.Config{DataPath: t.TempDir(), AuthUser: "admin", AuthPass: "hashed-password"}
+ handler := newTestConfigHandlers(t, cfg)
+
+ body := []byte(`{"type":"host","enableCommands":false}`)
+ req := httptest.NewRequest(http.MethodPost, "/api/agent-install-command", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandleAgentInstallCommand(rec, req)
+
+ resp := decodeHostAgentInstallResponse(t, rec)
+ if resp.Token == "" {
+ t.Fatalf("expected token in response")
+ }
+ if len(cfg.APITokens) != 1 {
+ t.Fatalf("expected API token to be persisted")
+ }
+ record := cfg.APITokens[0]
+ if record.HasScope(config.ScopeAgentExec) {
+ t.Fatalf("expected no exec scope without enableCommands, got %v", record.Scopes)
+ }
+}
+
+func TestHandleAgentInstallCommand_HostOmitsTokenWhenAuthOptional(t *testing.T) {
+ cfg := &config.Config{DataPath: t.TempDir()}
+ handler := newTestConfigHandlers(t, cfg)
+
+ body := []byte(`{"type":"host","enableCommands":true}`)
+ req := httptest.NewRequest(http.MethodPost, "/api/agent-install-command", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandleAgentInstallCommand(rec, req)
+
+ resp := decodeHostAgentInstallResponse(t, rec)
+ if resp.Token != "" {
+ t.Fatalf("expected optional-auth host install response to omit token, got %q", resp.Token)
+ }
+ if len(cfg.APITokens) != 0 {
+ t.Fatalf("expected optional-auth host install to avoid persisting API tokens")
+ }
+}