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.

Bind owner identity across token minting

rcourtman3953554ae10b
diff --git a/docs/release-control/v6/internal/IDENTITY_INVARIANTS.md b/docs/release-control/v6/internal/IDENTITY_INVARIANTS.md
index 09907d94ea..a6b3704296 100644
--- a/docs/release-control/v6/internal/IDENTITY_INVARIANTS.md
+++ b/docs/release-control/v6/internal/IDENTITY_INVARIANTS.md
@@ -60,6 +60,11 @@ principal once a stable user ID exists.
- `owner_user_id` metadata must carry the authenticated principal, not an
arbitrary email copied from a browser payload. Token minting helpers must
reject caller-supplied metadata that attempts to set `owner_user_id`.
+ - User/admin-initiated token minting paths, including security-token
+ creation/regeneration, agent install commands, deploy bootstrap and
+ enrollment runtime tokens, container runtime migration, and first-run
+ security setup must attach owner identity through the shared server-side
+ owner helper rather than through extension metadata.
8. Mobile/relay device identity
- Shape: relay/mobile device registration IDs and platform device tokens.
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 34c8b779f9..6f0084d781 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -188,6 +188,10 @@ profile and assignment columns, but embedded table framing must route through
API-token owner metadata follows the same rule: lifecycle-adjacent setup or
mobile-pairing token flows may consume the shared token helper, but they
must not pass extension metadata that authors or overwrites `owner_user_id`.
+ Agent install command and deploy bootstrap/enrollment tokens must derive
+ owner identity from the API-authenticated caller through the shared
+ server-side token owner helper; bootstrap deploy metadata may bind cluster,
+ job, target, and expected node, but not the human owner.
The canonical durable-principal vocabulary for those shared auth routes is
recorded in `docs/release-control/v6/internal/IDENTITY_INVARIANTS.md`; agent
lifecycle work may consume that identity but must not define a parallel
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index fa610972f2..d26bb16bf9 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -225,7 +225,11 @@ product API routes free of maintainer commercial analytics.
Token owner identity is reserved for the server-authenticated principal:
shared token-minting helpers must derive `owner_user_id` from the current
session or caller token and reject extension metadata that tries to
- overwrite that field.
+ overwrite that field. API-owned token minting paths that bypass
+ `/api/security/tokens`, including agent install, deploy bootstrap/enroll,
+ container runtime migration, quick security setup, and API-token
+ regeneration must still call the shared owner setter and must not encode
+ owner identity inside their extension metadata maps.
The dedicated Pulse Mobile relay token route is part of that same API
contract even though its runtime capability is Relay-owned:
`POST /api/security/tokens/relay-mobile` must pass normal admin and
@@ -3162,7 +3166,10 @@ binding: token create/list responses must preserve the originating
`ownerUserId` together with org scope so long-lived automation credentials
cannot appear detached from their intended human identity, and shared
token-minting helpers must reject caller-supplied metadata that attempts to
-overwrite the reserved `owner_user_id` field.
+overwrite the reserved `owner_user_id` field. That owner binding now extends
+to token constructors outside the generic token manager, including agent
+install, deploy bootstrap/runtime enrollment, container runtime migration,
+first-run setup, and token-regeneration paths.
The shared direct-node/discovery settings boundary now also includes
`frontend-modern/src/utils/infrastructureSettingsPresentation.ts`, so the
customer-facing mutation and validation copy used by the governed runtime
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index 126454c294..fbace13797 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -117,6 +117,11 @@ server-side update execution surfaces.
1. Add or change deployment-type detection, update planning, or apply behavior through `internal/updates/`
2. Add or change release-build metadata injection, Docker build-context allowlists, release artifact assembly, governed promotion metadata resolution, the canonical version file, operator-facing release packet content, prerelease feedback intake wording, historical published-release integrity backfill, release asset validation status publication, download endpoint checksum/signature header proof, or the canonical in-repo v6 upgrade guide through `scripts/build-release.sh`, `scripts/release_asset_common.sh`, `scripts/backfill-release-assets.sh`, `scripts/release_ldflags.sh`, `scripts/check-workflow-dispatch-inputs.py`, `scripts/release_control/render_release_body.py`, `scripts/release_control/resolve_release_promotion.py`, `scripts/release_control/record_rc_to_ga_rehearsal.py`, `scripts/release_control/internal/record_rc_to_ga_rehearsal.py`, `scripts/release_control/release_promotion_policy_support.py`, `.dockerignore`, `Dockerfile`, `.github/ISSUE_TEMPLATE/v6_rc_feedback.yml`, `docs/RELEASE_NOTES.md`, `docs/releases/`, `docs/UPGRADE_v6.md`, `docs/release-control/v6/internal/RELEASE_PROMOTION_POLICY.md`, `docs/release-control/v6/internal/PRE_RELEASE_CHECKLIST.md`, `docs/release-control/v6/internal/RC_TO_GA_REHEARSAL_TEMPLATE.md`, `scripts/validate-release.sh`, `scripts/validate-published-release.sh`, the operator dispatch helpers `scripts/trigger-release.sh` and `scripts/trigger-release-dry-run.sh`, and the governed release workflows `.github/workflows/backfill-release-assets.yml`, `.github/workflows/create-release.yml`, `.github/workflows/deploy-demo-server.yml`, `.github/workflows/helm-pages.yml`, `.github/workflows/publish-docker.yml`, `.github/workflows/publish-helm-chart.yml`, `.github/workflows/promote-floating-tags.yml`, `.github/workflows/release-dry-run.yml`, `.github/workflows/update-demo-server.yml`, and `.github/workflows/validate-release-assets.yml`
3. Add or change root server installer, shell installer, Docker bootstrap installer, Windows installer, container-agent installer, repo-root compose defaults, or auto-update script behavior through `install.sh`, `scripts/install.sh`, `scripts/install-docker.sh`, `scripts/install.ps1`, `scripts/install-container-agent.sh`, `docker-compose.yml`, and `scripts/pulse-auto-update.sh`
+ Deployment bootstrap token behavior remains a deployment-installability
+ trust boundary even when the handler is API-owned. `internal/api/deploy_handlers.go`
+ must preserve server-derived `owner_user_id` lineage on bootstrap tokens and
+ enrollment runtime tokens while keeping deploy binding metadata limited to
+ deploy facts such as cluster, job, target, source agent, and expected node.
4. Add or change server update transport through `internal/api/updates.go` and `frontend-modern/src/api/updates.ts`
5. Add or change local dev-runtime orchestration, managed ownership, browser-runtime proof wiring, frontend/backend coherence diagnostics, canonical developer entry wrappers, dependency manifest floors, frontend build chunking, or dev-runtime helper control surfaces through `scripts/hot-dev.sh`, `scripts/hot-dev-bg.sh`, `scripts/dev-deploy-agent.sh`, `Makefile`, `package.json`, `package-lock.json`, `frontend-modern/package.json`, `frontend-modern/package-lock.json`, `frontend-modern/vite.config.ts`, `go.mod`, `go.sum`, `scripts/dev-check.sh`, `scripts/toggle-mock.sh`, `scripts/clean-mock-alerts.sh`, `scripts/dev-launchd-setup.sh`, `scripts/dev-launchd-wrapper.sh`, `scripts/run_demo_public_browser_smoke.sh`, `scripts/demo_public_browser_smoke.cjs`, `scripts/com.pulse.hot-dev.plist.template`, `tests/integration/scripts/managed-dev-runtime.mjs`, `tests/integration/playwright.config.ts`, `tests/integration/tests/helpers.ts`, `tests/integration/tests/runtime-defaults.ts`, `tests/integration/README.md`, and `tests/integration/QUICK_START.md`
6. Add or change governed release-promotion workflow inputs, operator-facing promotion metadata, the canonical version file, prerelease feedback intake prompts, artifact publication lineage enforcement, release note or changelog packet composition, or stable-promotion rehearsal summaries through `.github/workflows/create-release.yml`, `.github/workflows/helm-pages.yml`, `.github/workflows/publish-docker.yml`, `.github/workflows/publish-helm-chart.yml`, `.github/workflows/promote-floating-tags.yml`, `.github/workflows/release-dry-run.yml`, `.github/workflows/update-demo-server.yml`, `.github/ISSUE_TEMPLATE/v6_rc_feedback.yml`, `docs/RELEASE_NOTES.md`, `docs/releases/`, `docs/release-control/v6/internal/RELEASE_PROMOTION_POLICY.md`, `docs/release-control/v6/internal/PRE_RELEASE_CHECKLIST.md`, `docs/release-control/v6/internal/RC_TO_GA_REHEARSAL_TEMPLATE.md`, `scripts/check-workflow-dispatch-inputs.py`, `scripts/release_control/render_release_body.py`, `scripts/release_control/record_rc_to_ga_rehearsal.py`, `scripts/release_control/internal/record_rc_to_ga_rehearsal.py`, `scripts/release_control/release_promotion_policy_support.py`, `scripts/trigger-release.sh`, and `scripts/trigger-release-dry-run.sh`
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 1aa93fff1c..f85e3d7b3d 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -164,6 +164,11 @@ regression protection.
process version once, but they must not add per-request release lookups,
filesystem walks, or other heavy work just to compute whether an attached
agent is current.
+ Container runtime migration token minting follows that same rule: adding
+ server-derived owner metadata in `internal/api/router.go` must reuse the
+ already-authenticated request context or caller token and must not add
+ monitor scans, persistence reads, or other broad hot-path work before the
+ route-local handler owns the mutation.
Retiring self-hosted trial acquisition follows that same rule: removing
`/auth/trial-activate` and `POST /api/license/trial/start` from public-path
and CSRF inventories must stay as constant-time route-table absence rather
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 509ce12c29..be6111ace4 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -269,7 +269,11 @@ revocation targets, or operator-facing token ownership.
That same token-management boundary also reserves token-owner identity for the
server-authenticated principal. Token-minting helpers must derive
`owner_user_id` from the authenticated session or caller token and reject any
-extension metadata that attempts to overwrite that field.
+extension metadata that attempts to overwrite that field. This applies beyond
+the visible API-token manager: agent install command tokens, deploy bootstrap
+tokens, enrollment runtime tokens, container runtime migration tokens, and
+first-run/regenerated admin tokens must use the same shared server-side owner
+setter rather than carrying owner identity in caller-controlled metadata.
Telemetry/privacy disclosures now also route through the shipped frontend docs
boundary: `frontend-modern/src/utils/docsLinks.ts` is the canonical frontend
owner 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.md
index 8421e958c3..60e6544371 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -163,7 +163,10 @@ stale-plan hash, blast-radius model, or execution protocol outside
Shared API-token transport helpers may be consumed by storage/recovery-
adjacent flows, but `owner_user_id` remains server-authored token identity
metadata; storage/recovery extensions must not pass metadata that authors
- or overwrites that owner field.
+ or overwrites that owner field. Adjacent first-run, regeneration, install,
+ deploy-bootstrap, and enrollment token constructors must attach owner
+ identity through the shared API/security helper, not through recovery or
+ storage metadata maps.
Shared setup-script transport may be reused by storage and recovery-linked
setup flows, but it remains API/lifecycle-owned: generated PVE scripts must
preserve Proxmox `authorized_keys` symlinks by resolving the target before
diff --git a/internal/api/agent_install_command_shared.go b/internal/api/agent_install_command_shared.go
index f477dec152..32aa82932a 100644
--- a/internal/api/agent_install_command_shared.go
+++ b/internal/api/agent_install_command_shared.go
@@ -42,9 +42,10 @@ func proxmoxAgentInstallScopes() []string {
}
type issueAgentInstallTokenOptions struct {
- TokenName string
- OrgID string
- Metadata map[string]string
+ TokenName string
+ OrgID string
+ OwnerUserID string
+ Metadata map[string]string
}
func issueAndPersistAgentInstallToken(cfg *config.Config, persistence *config.ConfigPersistence, opts issueAgentInstallTokenOptions) (string, *config.APITokenRecord, error) {
@@ -63,11 +64,9 @@ func issueAndPersistAgentInstallToken(cfg *config.Config, persistence *config.Co
}
record.OrgID = strings.TrimSpace(opts.OrgID)
- if len(opts.Metadata) > 0 {
- record.Metadata = make(map[string]string, len(opts.Metadata))
- for k, v := range opts.Metadata {
- record.Metadata[k] = v
- }
+ setAPITokenOwnerUserID(record, opts.OwnerUserID)
+ if err := mergeAPITokenMetadata(record, opts.Metadata); err != nil {
+ return "", nil, fmt.Errorf("%w: %w", errAgentInstallTokenRecord, err)
}
config.Mu.Lock()
diff --git a/internal/api/agent_install_command_shared_test.go b/internal/api/agent_install_command_shared_test.go
index a206ede1a8..1554a41081 100644
--- a/internal/api/agent_install_command_shared_test.go
+++ b/internal/api/agent_install_command_shared_test.go
@@ -269,8 +269,9 @@ func TestIssueAndPersistAgentInstallToken(t *testing.T) {
persistence := config.NewConfigPersistence(dataDir)
rawToken, record, err := issueAndPersistAgentInstallToken(cfg, persistence, issueAgentInstallTokenOptions{
- TokenName: "test-install-token",
- OrgID: "acme",
+ TokenName: "test-install-token",
+ OrgID: "acme",
+ OwnerUserID: "alice",
Metadata: map[string]string{
"install_type": "pbs",
"issued_via": "test",
@@ -280,6 +281,7 @@ func TestIssueAndPersistAgentInstallToken(t *testing.T) {
require.NotEmpty(t, rawToken)
require.NotNil(t, record)
require.Equal(t, "acme", record.OrgID)
+ require.Equal(t, "alice", record.Metadata[apiTokenMetadataOwnerUserID])
require.Equal(t, "pbs", record.Metadata["install_type"])
require.Equal(t, "test", record.Metadata["issued_via"])
@@ -287,9 +289,37 @@ func TestIssueAndPersistAgentInstallToken(t *testing.T) {
savedRecord, ok := cfg.ValidateAPIToken(rawToken)
require.True(t, ok)
require.Equal(t, "acme", savedRecord.OrgID)
+ require.Equal(t, "alice", savedRecord.Metadata[apiTokenMetadataOwnerUserID])
tokens, err := persistence.LoadAPITokens()
require.NoError(t, err)
require.Len(t, tokens, 1)
require.True(t, strings.HasPrefix(tokens[0].Name, "test-install-token"))
+ require.Equal(t, "alice", tokens[0].Metadata[apiTokenMetadataOwnerUserID])
+}
+
+func TestIssueAndPersistAgentInstallTokenRejectsOwnerMetadataOverride(t *testing.T) {
+ dataDir := t.TempDir()
+ cfg := &config.Config{DataPath: dataDir}
+ persistence := config.NewConfigPersistence(dataDir)
+
+ rawToken, record, err := issueAndPersistAgentInstallToken(cfg, persistence, issueAgentInstallTokenOptions{
+ TokenName: "bad-install-token",
+ OrgID: "acme",
+ OwnerUserID: "alice",
+ Metadata: map[string]string{
+ apiTokenMetadataOwnerUserID: "mallory",
+ "install_type": "pbs",
+ },
+ })
+ require.Error(t, err)
+ require.ErrorIs(t, err, errAgentInstallTokenRecord)
+ require.Contains(t, err.Error(), "reserved token metadata key")
+ require.Empty(t, rawToken)
+ require.Nil(t, record)
+ require.Empty(t, cfg.APITokens)
+
+ tokens, loadErr := persistence.LoadAPITokens()
+ require.NoError(t, loadErr)
+ require.Empty(t, tokens)
}
diff --git a/internal/api/cloud_agent_install_command.go b/internal/api/cloud_agent_install_command.go
index 3ed4539657..77db1b57de 100644
--- a/internal/api/cloud_agent_install_command.go
+++ b/internal/api/cloud_agent_install_command.go
@@ -56,8 +56,9 @@ func (r *Router) handleHostedTenantAgentInstallCommand(w http.ResponseWriter, re
tokenName := fmt.Sprintf("cloud-tenant-agent-%s-%s-%d", orgID, installType, time.Now().UTC().Unix())
rawToken, record, err := issueAndPersistAgentInstallToken(r.config, r.persistence, issueAgentInstallTokenOptions{
- TokenName: tokenName,
- OrgID: orgID,
+ TokenName: tokenName,
+ OrgID: orgID,
+ OwnerUserID: apiTokenOwnerUserIDForRequest(r.config, req),
Metadata: map[string]string{
"install_type": installType,
"issued_via": "hosted_agent_install_command",
diff --git a/internal/api/config_setup_handlers.go b/internal/api/config_setup_handlers.go
index 69a349bc75..54ea711b12 100644
--- a/internal/api/config_setup_handlers.go
+++ b/internal/api/config_setup_handlers.go
@@ -1553,7 +1553,8 @@ func (h *ConfigHandlers) handleAgentInstallCommand(w http.ResponseWriter, r *htt
if authConfiguredForAgentLifecycle(cfg) {
tokenName := fmt.Sprintf("proxmox-agent-%s-%d", installType, time.Now().Unix())
rawToken, _, err = issueAndPersistAgentInstallToken(cfg, persistence, issueAgentInstallTokenOptions{
- TokenName: tokenName,
+ TokenName: tokenName,
+ OwnerUserID: apiTokenOwnerUserIDForRequest(cfg, r),
Metadata: map[string]string{
"install_type": installType,
"issued_via": "config_agent_install_command",
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 2ca7628b04..7c5eca8e01 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -160,6 +160,46 @@ func TestContract_SSOStablePrincipalProof(t *testing.T) {
}
}
+func TestContract_APITokenOwnerBindingCoversSharedMintingPaths(t *testing.T) {
+ files := map[string][]string{
+ "security_tokens.go": {
+ "setAPITokenOwnerUserID",
+ "apiTokenOwnerUserIDForRequest",
+ "reserved token metadata key",
+ },
+ "agent_install_command_shared.go": {
+ "OwnerUserID string",
+ "setAPITokenOwnerUserID(record, opts.OwnerUserID)",
+ "mergeAPITokenMetadata(record, opts.Metadata)",
+ },
+ "deploy_handlers.go": {
+ "setAPITokenOwnerUserID(record, ownerUserID)",
+ "setAPITokenOwnerUserID(runtimeRecord, apiTokenOwnerUserID(*bootstrapToken))",
+ "apiTokenOwnerUserIDForRequest(h.config, r)",
+ },
+ "router.go": {
+ "setAPITokenOwnerUserID(record, apiTokenOwnerUserIDForRequest(r.config, req))",
+ },
+ "security_setup_fix.go": {
+ "setAPITokenOwnerUserID(tokenRecord, setupRequest.Username)",
+ "setAPITokenOwnerUserID(tokenRecord, apiTokenOwnerUserIDForRequest(r.config, rq))",
+ },
+ }
+
+ for file, needles := range files {
+ source, err := os.ReadFile(filepath.Clean(file))
+ if err != nil {
+ t.Fatalf("read %s: %v", file, err)
+ }
+ text := string(source)
+ for _, needle := range needles {
+ if !strings.Contains(text, needle) {
+ t.Fatalf("%s must contain %q", file, needle)
+ }
+ }
+ }
+}
+
func TestContractAISettingsClampsPaidRuntimeControlsToEntitlements(t *testing.T) {
t.Parallel()
diff --git a/internal/api/deploy_handlers.go b/internal/api/deploy_handlers.go
index a7fabfba37..4485336fde 100644
--- a/internal/api/deploy_handlers.go
+++ b/internal/api/deploy_handlers.go
@@ -728,7 +728,7 @@ func (h *DeployHandlers) closeSSESub(jobID string) {
// MintBootstrapTokenForTarget creates a single-use bootstrap token for a deploy target.
// Used by the deploy job creation flow to issue per-target tokens.
-func (h *DeployHandlers) MintBootstrapTokenForTarget(req deploy.BootstrapTokenRequest) (rawToken string, tokenID string, err error) {
+func (h *DeployHandlers) MintBootstrapTokenForTarget(req deploy.BootstrapTokenRequest, ownerUserID string) (rawToken string, tokenID string, err error) {
if req.TTL <= 0 {
return "", "", fmt.Errorf("TTL must be positive, got %v", req.TTL)
}
@@ -748,7 +748,10 @@ func (h *DeployHandlers) MintBootstrapTokenForTarget(req deploy.BootstrapTokenRe
exp := time.Now().UTC().Add(req.TTL)
record.ExpiresAt = &exp
record.OrgID = req.OrgID
- record.Metadata = req.BuildMetadata()
+ setAPITokenOwnerUserID(record, ownerUserID)
+ if err := mergeAPITokenMetadata(record, req.BuildMetadata()); err != nil {
+ return "", "", fmt.Errorf("attach bootstrap token metadata: %w", err)
+ }
config.Mu.Lock()
h.config.UpsertAPIToken(*record)
@@ -903,6 +906,7 @@ func (h *DeployHandlers) HandleEnroll(w http.ResponseWriter, r *http.Request) {
"bound_hostname": req.Hostname,
"deploy_job_id": jobID,
}
+ setAPITokenOwnerUserID(runtimeRecord, apiTokenOwnerUserID(*bootstrapToken))
config.Mu.Lock()
h.config.UpsertAPIToken(*runtimeRecord)
@@ -1198,7 +1202,7 @@ func (h *DeployHandlers) HandleCreateJob(w http.ResponseWriter, r *http.Request)
SourceAgentID: req.SourceAgentID,
OrgID: orgID,
TTL: 30 * time.Minute,
- })
+ }, apiTokenOwnerUserIDForRequest(h.config, r))
if err != nil {
log.Error().Err(err).Str("target_id", targetID).Msg("Failed to mint bootstrap token")
_ = h.store.UpdateTargetStatus(ctx, targetID, deploy.TargetFailedPermanent, "failed to mint bootstrap token")
@@ -1658,7 +1662,7 @@ func (h *DeployHandlers) HandleRetryJob(w http.ResponseWriter, r *http.Request)
SourceAgentID: job.SourceAgentID,
OrgID: orgID,
TTL: 30 * time.Minute,
- })
+ }, apiTokenOwnerUserIDForRequest(h.config, r))
if err != nil {
log.Error().Err(err).Str("target_id", t.ID).Msg("Failed to mint retry bootstrap token")
_ = h.store.UpdateTargetStatus(ctx, t.ID, deploy.TargetFailedPermanent, "failed to mint bootstrap token for retry")
diff --git a/internal/api/deploy_handlers_test.go b/internal/api/deploy_handlers_test.go
index 765f8150c1..c08d23c264 100644
--- a/internal/api/deploy_handlers_test.go
+++ b/internal/api/deploy_handlers_test.go
@@ -522,6 +522,7 @@ func TestHandleEnroll_Success(t *testing.T) {
h, store := newEnrollTestHandlers(t)
jobID, targetID := seedEnrollJobAndTarget(t, store, deploy.TargetEnrolling)
rec := mintTestBootstrapToken(t, h.config, jobID, targetID, "pve-node2")
+ rec.Metadata[apiTokenMetadataOwnerUserID] = "alice"
req := httptest.NewRequest(http.MethodPost, "/api/agents/agent/enroll", enrollJSON(t, "pve-node2"))
attachAPITokenRecord(req, rec)
@@ -543,10 +544,27 @@ func TestHandleEnroll_Success(t *testing.T) {
if resp["runtimeTokenId"] == nil || resp["runtimeTokenId"] == "" {
t.Fatal("expected runtimeTokenId in response")
}
+ runtimeTokenID, _ := resp["runtimeTokenId"].(string)
if resp["agentId"] != "agent-pve-node2" {
t.Fatalf("expected agentId=agent-pve-node2, got %v", resp["agentId"])
}
+ config.Mu.Lock()
+ var runtimeRecord *config.APITokenRecord
+ for i := range h.config.APITokens {
+ if h.config.APITokens[i].ID == runtimeTokenID {
+ runtimeRecord = &h.config.APITokens[i]
+ break
+ }
+ }
+ config.Mu.Unlock()
+ if runtimeRecord == nil {
+ t.Fatal("runtime token should be stored")
+ }
+ if got := runtimeRecord.Metadata[apiTokenMetadataOwnerUserID]; got != "alice" {
+ t.Fatalf("runtime token owner_user_id = %q, want alice", got)
+ }
+
// Target should now be verifying.
target, err := store.GetTarget(context.Background(), targetID)
if err != nil {
@@ -736,7 +754,7 @@ func TestMintBootstrapTokenForTarget(t *testing.T) {
ClusterID: "c1", NodeID: "n1", ExpectedNode: "pve-3",
JobID: "job-m1", TargetID: "tgt-m1", SourceAgentID: "agent-src",
OrgID: "test-org", TTL: 15 * time.Minute,
- })
+ }, "alice")
if err != nil {
t.Fatalf("MintBootstrapTokenForTarget: %v", err)
}
@@ -766,6 +784,9 @@ func TestMintBootstrapTokenForTarget(t *testing.T) {
if rec.Metadata[deploy.MetaKeyExpectedNode] != "pve-3" {
t.Fatalf("expected expectedNode=pve-3, got %q", rec.Metadata[deploy.MetaKeyExpectedNode])
}
+ if rec.Metadata[apiTokenMetadataOwnerUserID] != "alice" {
+ t.Fatalf("expected owner_user_id=alice, got %q", rec.Metadata[apiTokenMetadataOwnerUserID])
+ }
}
func TestMintBootstrapTokenForTarget_InvalidTTL(t *testing.T) {
@@ -779,7 +800,7 @@ func TestMintBootstrapTokenForTarget_InvalidTTL(t *testing.T) {
ClusterID: "c1", NodeID: "n1", ExpectedNode: "pve-3",
JobID: "job-1", TargetID: "tgt-1", SourceAgentID: "a1",
OrgID: "org", TTL: 0,
- })
+ }, "alice")
if err == nil {
t.Fatal("expected error for zero TTL")
}
@@ -788,7 +809,7 @@ func TestMintBootstrapTokenForTarget_InvalidTTL(t *testing.T) {
ClusterID: "c1", NodeID: "n1", ExpectedNode: "pve-3",
JobID: "job-1", TargetID: "tgt-1", SourceAgentID: "a1",
OrgID: "org", TTL: -5 * time.Minute,
- })
+ }, "alice")
if err == nil {
t.Fatal("expected error for negative TTL")
}
diff --git a/internal/api/identity_invariant_contract_test.go b/internal/api/identity_invariant_contract_test.go
index a78968aab8..1352f18a0d 100644
--- a/internal/api/identity_invariant_contract_test.go
+++ b/internal/api/identity_invariant_contract_test.go
@@ -26,6 +26,10 @@ func TestContract_HostedIdentityUsesStablePrincipals(t *testing.T) {
"saml_handlers.go": readIdentityContractFile(t, "saml_handlers.go"),
"auth_principal_identity.go": readIdentityContractFile(t, "auth_principal_identity.go"),
"security_tokens.go": readIdentityContractFile(t, "security_tokens.go"),
+ "agent_install_command_shared.go": readIdentityContractFile(t, "agent_install_command_shared.go"),
+ "deploy_handlers.go": readIdentityContractFile(t, "deploy_handlers.go"),
+ "router.go": readIdentityContractFile(t, "router.go"),
+ "security_setup_fix.go": readIdentityContractFile(t, "security_setup_fix.go"),
"../cloudcp/stripe/provisioner.go": readIdentityContractFile(t, "../cloudcp/stripe/provisioner.go"),
"../models/organization.go": readIdentityContractFile(t, "../models/organization.go"),
"../../docs/release-control/v6/internal/IDENTITY_INVARIANTS.md": readIdentityContractFile(t, "../../docs/release-control/v6/internal/IDENTITY_INVARIANTS.md"),
@@ -62,9 +66,27 @@ func TestContract_HostedIdentityUsesStablePrincipals(t *testing.T) {
},
"security_tokens.go": {
"mergeAPITokenMetadata",
+ "setAPITokenOwnerUserID",
"reserved token metadata key",
"apiTokenOwnerUserIDForRequest",
},
+ "agent_install_command_shared.go": {
+ "OwnerUserID string",
+ "setAPITokenOwnerUserID(record, opts.OwnerUserID)",
+ "mergeAPITokenMetadata(record, opts.Metadata)",
+ },
+ "deploy_handlers.go": {
+ "setAPITokenOwnerUserID(record, ownerUserID)",
+ "setAPITokenOwnerUserID(runtimeRecord, apiTokenOwnerUserID(*bootstrapToken))",
+ "apiTokenOwnerUserIDForRequest(h.config, r)",
+ },
+ "router.go": {
+ "setAPITokenOwnerUserID(record, apiTokenOwnerUserIDForRequest(r.config, req))",
+ },
+ "security_setup_fix.go": {
+ "setAPITokenOwnerUserID(tokenRecord, setupRequest.Username)",
+ "setAPITokenOwnerUserID(tokenRecord, apiTokenOwnerUserIDForRequest(r.config, rq))",
+ },
"../cloudcp/stripe/provisioner.go": {
"ownerUserID = strings.TrimSpace(user.ID)",
"org.OwnerEmail = ownerEmail",
diff --git a/internal/api/router.go b/internal/api/router.go
index 07358a7ce8..5ad3dde23d 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -9719,6 +9719,7 @@ func (r *Router) handleDiagnosticsDockerPrepareToken(w http.ResponseWriter, req
if record.OrgID == "" {
record.OrgID = "default"
}
+ setAPITokenOwnerUserID(record, apiTokenOwnerUserIDForRequest(r.config, req))
activeConfig := r.config
activePersistence := r.persistence
diff --git a/internal/api/security_setup_fix.go b/internal/api/security_setup_fix.go
index cfcbf9d2af..0691c428c5 100644
--- a/internal/api/security_setup_fix.go
+++ b/internal/api/security_setup_fix.go
@@ -308,6 +308,7 @@ func handleQuickSecuritySetupFixed(r *Router) http.HandlerFunc {
http.Error(w, "Failed to process API token", http.StatusInternalServerError)
return
}
+ setAPITokenOwnerUserID(tokenRecord, setupRequest.Username)
if r.config.HasAPITokens() && r.config.AuthUser == "" && r.config.AuthPass == "" {
// We had API-only access before, now replacing with full security
@@ -566,6 +567,7 @@ func (r *Router) HandleRegenerateAPIToken(w http.ResponseWriter, rq *http.Reques
http.Error(w, "Failed to generate token", http.StatusInternalServerError)
return
}
+ setAPITokenOwnerUserID(tokenRecord, apiTokenOwnerUserIDForRequest(r.config, rq))
config.Mu.Lock()
r.config.APITokens = []config.APITokenRecord{*tokenRecord}
diff --git a/internal/api/security_setup_fix_additional_test.go b/internal/api/security_setup_fix_additional_test.go
index 7eaf7abde2..98e670fec6 100644
--- a/internal/api/security_setup_fix_additional_test.go
+++ b/internal/api/security_setup_fix_additional_test.go
@@ -77,6 +77,47 @@ func TestHandleRegenerateAPIToken_DoesNotRequireEnvFile(t *testing.T) {
}
}
+func TestHandleRegenerateAPITokenInheritsOwnerFromCallerToken(t *testing.T) {
+ dataDir := t.TempDir()
+ rawCallerToken := "regen-owner-token-123.12345678"
+ callerRecord, err := config.NewAPITokenRecord(rawCallerToken, "admin-token", []string{config.ScopeSettingsWrite})
+ if err != nil {
+ t.Fatalf("new caller token record: %v", err)
+ }
+ callerRecord.Metadata = map[string]string{apiTokenMetadataOwnerUserID: "alice"}
+
+ cfg := &config.Config{
+ DataPath: dataDir,
+ ConfigPath: dataDir,
+ APITokens: []config.APITokenRecord{*callerRecord},
+ }
+ cfg.SortAPITokens()
+
+ router := &Router{
+ config: cfg,
+ persistence: config.NewConfigPersistence(cfg.DataPath),
+ }
+ handler := http.HandlerFunc(router.HandleRegenerateAPIToken)
+
+ authLimiter.Reset("127.0.0.1")
+
+ req := newLoopbackRequest(http.MethodPost, "/api/security/regenerate-token", nil)
+ req.Header.Set("X-API-Token", rawCallerToken)
+ rec := httptest.NewRecorder()
+
+ handler.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected status %d, got %d (%s)", http.StatusOK, rec.Code, rec.Body.String())
+ }
+ if len(cfg.APITokens) != 1 {
+ t.Fatalf("expected one regenerated API token, got %d", len(cfg.APITokens))
+ }
+ if got := cfg.APITokens[0].Metadata[apiTokenMetadataOwnerUserID]; got != "alice" {
+ t.Fatalf("regenerated token owner_user_id=%q, want alice", got)
+ }
+}
+
func TestHandleValidateAPIToken_InvalidJSON(t *testing.T) {
router := &Router{config: &config.Config{}}
handler := http.HandlerFunc(router.HandleValidateAPIToken)
@@ -366,6 +407,12 @@ func TestQuickSecuritySetupAcceptsSetupTokenInBody(t *testing.T) {
if router.bootstrapTokenHash != "" {
t.Fatalf("expected bootstrap token hash to be cleared after successful setup")
}
+ if len(cfg.APITokens) != 1 {
+ t.Fatalf("expected one API token, got %d", len(cfg.APITokens))
+ }
+ if got := cfg.APITokens[0].Metadata[apiTokenMetadataOwnerUserID]; got != "bootstrap" {
+ t.Fatalf("setup token owner_user_id=%q, want bootstrap", got)
+ }
}
func TestQuickSecuritySetupRotatesWithBasicAuth(t *testing.T) {
@@ -413,6 +460,9 @@ func TestQuickSecuritySetupRotatesWithBasicAuth(t *testing.T) {
if len(cfg.APITokens) != 1 {
t.Fatalf("expected one API token, got %d", len(cfg.APITokens))
}
+ if got := cfg.APITokens[0].Metadata[apiTokenMetadataOwnerUserID]; got != "newadmin" {
+ t.Fatalf("rotated token owner_user_id=%q, want newadmin", got)
+ }
cookies := rec.Result().Cookies()
sessionCookie := findCookie(cookies, sessionCookieName(false))
diff --git a/internal/api/security_tokens.go b/internal/api/security_tokens.go
index 37c027fed4..d572830616 100644
--- a/internal/api/security_tokens.go
+++ b/internal/api/security_tokens.go
@@ -50,6 +50,20 @@ func mergeAPITokenMetadata(record *config.APITokenRecord, metadata map[string]st
return nil
}
+func setAPITokenOwnerUserID(record *config.APITokenRecord, ownerUserID string) {
+ if record == nil {
+ return
+ }
+ ownerUserID = strings.TrimSpace(ownerUserID)
+ if ownerUserID == "" || strings.HasPrefix(ownerUserID, "token:") {
+ return
+ }
+ if record.Metadata == nil {
+ record.Metadata = make(map[string]string)
+ }
+ record.Metadata[apiTokenMetadataOwnerUserID] = ownerUserID
+}
+
func apiTokenOwnerUserID(record config.APITokenRecord) string {
if record.Metadata == nil {
return ""
@@ -189,12 +203,7 @@ func (r *Router) createAPITokenRecord(
if record.OrgID == "" {
record.OrgID = "default"
}
- if ownerUserID := apiTokenOwnerUserIDForRequest(r.config, req); ownerUserID != "" {
- if record.Metadata == nil {
- record.Metadata = make(map[string]string)
- }
- record.Metadata[apiTokenMetadataOwnerUserID] = ownerUserID
- }
+ setAPITokenOwnerUserID(record, apiTokenOwnerUserIDForRequest(r.config, req))
if err := mergeAPITokenMetadata(record, metadata); err != nil {
return "", nil, err
}
diff --git a/internal/api/security_tokens_owner_binding_test.go b/internal/api/security_tokens_owner_binding_test.go
index 5a18ba499e..30ea87882b 100644
--- a/internal/api/security_tokens_owner_binding_test.go
+++ b/internal/api/security_tokens_owner_binding_test.go
@@ -142,3 +142,24 @@ func TestSecurityTokens_CreateRejectsCallerMetadataOwnerOverride(t *testing.T) {
t.Fatalf("expected no stored tokens after rejected metadata, got %d", len(cfg.APITokens))
}
}
+
+func TestSecurityTokens_OwnerHelperRejectsCallerMetadataOverride(t *testing.T) {
+ record, err := config.NewAPITokenRecord("owner-helper-token-123.12345678", "owner-helper", []string{config.ScopeMonitoringRead})
+ if err != nil {
+ t.Fatalf("new token record: %v", err)
+ }
+
+ setAPITokenOwnerUserID(record, "alice")
+ err = mergeAPITokenMetadata(record, map[string]string{
+ apiTokenMetadataOwnerUserID: "mallory",
+ })
+ if err == nil {
+ t.Fatalf("expected owner_user_id metadata override to be rejected")
+ }
+ if !strings.Contains(err.Error(), "reserved token metadata key") {
+ t.Fatalf("expected reserved metadata error, got %v", err)
+ }
+ if got := record.Metadata[apiTokenMetadataOwnerUserID]; got != "alice" {
+ t.Fatalf("owner_user_id=%q, want alice", got)
+ }
+}