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.

Harden secure runtime separation boundaries

Pulse Test7e92ac8118a7
diff --git a/cmd/pulse-agent-helper/main.go b/cmd/pulse-agent-helper/main.go
index 7976ba5ad9..aba6c4a1d8 100644
--- a/cmd/pulse-agent-helper/main.go
+++ b/cmd/pulse-agent-helper/main.go
@@ -2,13 +2,18 @@ package main
import (
"context"
+ "crypto/sha256"
+ "debug/buildinfo"
+ "encoding/hex"
"errors"
"flag"
"fmt"
+ "io"
"log"
"math"
"net"
"os"
+ "os/exec"
"os/signal"
"os/user"
"path/filepath"
@@ -86,6 +91,8 @@ func run(args []string) error {
}
return updatesignature.VerifyBytes(data, signature)
},
+ InspectVersion: inspectPulseAgentVersion,
+ ValidateCommitter: validatePulseAgentCommitter,
ValidateOwner: agenthelper.StrictRootOwnedFile,
ValidateQuarantineOwner: agenthelper.FileOwnedByUID(uid),
})
@@ -130,6 +137,64 @@ func run(args []string) error {
return server.Serve(ctx, listener)
}
+func inspectPulseAgentVersion(parent context.Context, path string) (string, error) {
+ info, err := buildinfo.ReadFile(path)
+ if err != nil || info.Path != "github.com/rcourtman/pulse-go-rewrite/cmd/pulse-agent" {
+ return "", errors.New("staged command is not the pulse-agent package")
+ }
+ ctx, cancel := context.WithTimeout(parent, 5*time.Second)
+ defer cancel()
+ command := exec.CommandContext(ctx, path, "--version")
+ command.Env = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin"}
+ stdout, err := command.StdoutPipe()
+ if err != nil {
+ return "", err
+ }
+ if err := command.Start(); err != nil {
+ return "", err
+ }
+ output, readErr := io.ReadAll(io.LimitReader(stdout, 4097))
+ if len(output) > 4096 {
+ _ = command.Process.Kill()
+ }
+ waitErr := command.Wait()
+ if readErr != nil {
+ return "", readErr
+ }
+ if waitErr != nil {
+ return "", waitErr
+ }
+ if len(output) > 4096 {
+ return "", errors.New("pulse-agent version output exceeds the bounded size")
+ }
+ version := strings.TrimSpace(string(output))
+ if version == "" || len(version) > 128 || strings.ContainsAny(version, "\x00\r\n") {
+ return "", errors.New("pulse-agent version output is invalid")
+ }
+ return version, nil
+}
+
+func validatePulseAgentCommitter(ctx context.Context, activeDigest string) error {
+ peer, ok := agenthelper.PeerFromContext(ctx)
+ if !ok || peer.PID <= 1 {
+ return errors.New("helper peer process identity is unavailable")
+ }
+ file, err := os.Open(fmt.Sprintf("/proc/%d/exe", peer.PID))
+ if err != nil {
+ return err
+ }
+ defer file.Close()
+ data, err := io.ReadAll(io.LimitReader(file, 100*1024*1024+1))
+ if err != nil || len(data) > 100*1024*1024 {
+ return errors.New("helper peer executable exceeds the bounded agent size")
+ }
+ sum := sha256.Sum256(data)
+ if !strings.EqualFold(hex.EncodeToString(sum[:]), activeDigest) {
+ return errors.New("helper peer is not executing the pending agent binary")
+ }
+ return nil
+}
+
func parseFlags(args []string) (commandConfig, error) {
set := flag.NewFlagSet("pulse-agent-helper", flag.ContinueOnError)
set.SetOutput(os.Stderr)
diff --git a/cmd/pulse-agent-helper/main_test.go b/cmd/pulse-agent-helper/main_test.go
index 81c0d75a96..d0caac1e02 100644
--- a/cmd/pulse-agent-helper/main_test.go
+++ b/cmd/pulse-agent-helper/main_test.go
@@ -1,6 +1,7 @@
package main
import (
+ "context"
"encoding/json"
"math"
"os"
@@ -14,6 +15,16 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/agenthelper"
)
+func TestInspectPulseAgentVersionRejectsWrongGoCommand(t *testing.T) {
+ executable, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := inspectPulseAgentVersion(context.Background(), executable); err == nil || !strings.Contains(err.Error(), "not the pulse-agent package") {
+ t.Fatalf("helper test command accepted as pulse-agent: %v", err)
+ }
+}
+
func TestParseFlagsAcceptsOnlyLocalHelperConfiguration(t *testing.T) {
config, err := parseFlags([]string{
"--socket", "/run/pulse-agent/custom-helper.sock",
diff --git a/cmd/pulse-agent/main_test.go b/cmd/pulse-agent/main_test.go
index ce7d35afba..886751e374 100644
--- a/cmd/pulse-agent/main_test.go
+++ b/cmd/pulse-agent/main_test.go
@@ -1868,11 +1868,11 @@ func (s *pendingUpdateSupervisorStub) WriteQuarantinedSignature(string, string)
return errors.New("not implemented")
}
-func (s *pendingUpdateSupervisorStub) Stage(context.Context, string, string) (agenthelper.UpdateStageResult, error) {
+func (s *pendingUpdateSupervisorStub) Stage(context.Context, string, string, string) (agenthelper.UpdateStageResult, error) {
return agenthelper.UpdateStageResult{}, errors.New("not implemented")
}
-func (s *pendingUpdateSupervisorStub) Activate(context.Context, string, string) (agenthelper.UpdateResult, error) {
+func (s *pendingUpdateSupervisorStub) Activate(context.Context, string, string, string) (agenthelper.UpdateResult, error) {
return agenthelper.UpdateResult{}, errors.New("not implemented")
}
@@ -2399,10 +2399,12 @@ func TestRun_DockerRetry(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
+ server := httptest.NewServer(http.NotFoundHandler())
+ defer server.Close()
errCh := make(chan error)
go func() {
- errCh <- run(ctx, []string{"-token", "T", "-enable-docker=true", "-enable-host=false"}, func(s string) string { return "" })
+ errCh <- run(ctx, []string{"-token", "T", "-url", server.URL, "-enable-docker=true", "-enable-host=false"}, func(s string) string { return "" })
}()
select {
@@ -2472,11 +2474,13 @@ func TestRun_KubeRetry(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
+ server := httptest.NewServer(http.NotFoundHandler())
+ defer server.Close()
errCh := make(chan error)
go func() {
// Only enable kubernetes
- errCh <- run(ctx, []string{"-token", "T", "-enable-kubernetes=true", "-enable-host=false", "-enable-docker=false"}, func(s string) string { return "" })
+ errCh <- run(ctx, []string{"-token", "T", "-url", server.URL, "-enable-kubernetes=true", "-enable-host=false", "-enable-docker=false"}, func(s string) string { return "" })
}()
select {
diff --git a/docs/release-control/v6/internal/AGENT_PRIVILEGE_BOUNDARY_PLAN.md b/docs/release-control/v6/internal/AGENT_PRIVILEGE_BOUNDARY_PLAN.md
index f77b8498a7..9481e0748a 100644
--- a/docs/release-control/v6/internal/AGENT_PRIVILEGE_BOUNDARY_PLAN.md
+++ b/docs/release-control/v6/internal/AGENT_PRIVILEGE_BOUNDARY_PLAN.md
@@ -82,27 +82,46 @@ without changing the product default:
the replacement is locally ready and a newly collected authoritative report
is accepted; explicit commit, restart/power-loss recovery, watchdog rollback,
and fixed staging/quarantine cleanup preserve the last-known-good binary;
+ the helper independently executes `--version` from root-owned staging,
+ rejects a signed artifact that is not the requested advancing collector
+ version, and binds commit to the same process after it execs the active
+ digest;
- runner enrollment persists the canonical hostname, durable credential
rotation invalidates only the superseded live session after storage commits,
and uninstall performs an exact bearer self-revoke without exposing the
secret in argv;
- safe migration rejects effective unit overrides, requires a fresh post-start
- registration timestamp and live helper protocol response, restores complete
- state metadata and Proxmox markers on rollback, and disables rootful Docker
- unless a usable collector-owned rootless socket exists.
+ registration timestamp and live helper protocol response, irreversibly
+ removes `agent:exec` and cross-host `agent:manage` from the host-bound
+ collector credential before local
+ privilege changes, restores only installer-owned state-root metadata and
+ Proxmox markers on rollback, and disables rootful Docker unless a usable
+ collector-owned rootless socket exists. Explicit or automatic rollback may
+ restore the old root service identity, but it removes `--enable-commands`
+ and cannot resurrect the reduced server-side authority;
+- the root action runner is networked and host-mutating by design. Its unit
+ retains kernel/home/control-plane hardening but does not set the host
+ filesystem read-only, because apt and Proxmox operations require their
+ documented host writes.
This is a qualification foundation, not the Slice E ratchet. The generated
-setup default remains the legacy/root profile. A clean disposable arm64 Ubuntu
-systemd exercise now proves exact-committed-main install, migration, explicit
-and automatic rollback, ordinary update isolation, typed helper health, fresh
-registration, continued reporting, separate runner enrollment, durable typed
-receipt replay, exact credential rotation invalidation, and runner self-revoke;
-its secret-free receipt and commit binding are recorded in
+setup default remains the legacy/root profile. The earlier clean disposable
+arm64 Ubuntu systemd exercise remains recorded in
`internal/records/secure-agent-runtime-systemd-receipt-2026-08-30.json` and its
-committed-main attestation. The binding now uses the fail-closed
-`scripts/release_control/secure_runtime_attestation.py` verifier, including an
-exact release-candidate-ref mode for the eventual ratchet proof. The repository
-still needs exact committed release-candidate reproduction,
+committed-main attestation, but it predates the hardening above: its action
+scenario proved a pre-mutation refusal and receipt replay, not a successful
+host mutation; its rollback claim predates irreversible credential reduction;
+and its secret-free receipt is hash-bound but not independently authenticated.
+It is historical evidence, not qualification of the current implementation.
+
+The v3 guarded lab now requires a real verified apt-cache mutation, a separate
+stale-fingerprint refusal, durable receipt replay, an observed collector
+authority-reduction request (with persistence covered by API regressions),
+complete boundary-source hashes, and artifact Go build stamps for
+the exact clean commit. `scripts/release_control/secure_runtime_attestation.py`
+rejects older receipts and labels accepted evidence as artifact-bound,
+self-attested systemd evidence rather than independently authenticated proof.
+The repository still needs a fresh exact committed release-candidate run,
representative Proxmox, SMART, Docker and rootless Podman telemetry/action
parity, appliance profiles, and the external security review. Until those
proofs are recorded, the safe profile remains opt-in and provider degradation
@@ -415,7 +434,9 @@ combined process had it.
## Rollback Boundaries
- Collector rollback restores the prior signed binary and unit while retaining
- agent identity and report credential.
+ agent identity and report credential, but it removes the legacy command flag.
+ The pre-migration credential reduction is deliberately irreversible, so
+ rollback cannot restore `agent:exec` or remote command authority.
- Helper rollback disables its socket and restores the previous declared
telemetry profile; it does not add the collector to privileged groups.
- Action-runner rollback disables and revokes its credential without disabling
diff --git a/docs/release-control/v6/internal/records/secure-agent-runtime-committed-main-attestation-2026-08-30.json b/docs/release-control/v6/internal/records/secure-agent-runtime-committed-main-attestation-2026-08-30.json
index 5f81ede227..54c119318f 100644
--- a/docs/release-control/v6/internal/records/secure-agent-runtime-committed-main-attestation-2026-08-30.json
+++ b/docs/release-control/v6/internal/records/secure-agent-runtime-committed-main-attestation-2026-08-30.json
@@ -2,7 +2,8 @@
"schema_version": 2,
"attestation_tool": "scripts/release_control/secure_runtime_attestation.py",
"attestation_tool_sha256": "7ec7ec958cb1352185b5144dbe6d8f87433608cbc16cfff66f4e7d8b3664a9d7",
- "proof_classification": "exact-committed-main",
+ "proof_classification": "historical-committed-main-artifact-hash-bound-self-attested-systemd",
+ "superseded_for_current_qualification": true,
"qualified_commit": "cb843e37e8a92c56d88a8a2922c23ccd2e4fd21b",
"qualified_ref_at_run": "cb843e37e8a92c56d88a8a2922c23ccd2e4fd21b",
"main_ref_verified": "origin/main",
@@ -10,7 +11,9 @@
"qualified_commit_reachable_from_main": true,
"build_checkout": "detached-worktree",
"build_checkout_clean_except_lab_artifacts": true,
- "disposable_vm_guard_verified": true,
+ "disposable_vm_guard_verified": false,
+ "disposable_vm_guard_not_independently_evidenced": true,
+ "execution_receipt_authentication": "none-secret-free-self-attestation",
"receipt_path": "docs/release-control/v6/internal/records/secure-agent-runtime-systemd-receipt-2026-08-30.json",
"receipt_sha256": "adeeec6bf02a73c27483da31d9e058a8686900324e32960399985e847487a271",
"source_hashes_match_commit": true,
@@ -35,6 +38,12 @@
"all_scenarios_passed": true,
"test_elapsed_seconds": 113.43,
"default_changed": false,
+ "limitations": [
+ "receipt execution was not independently authenticated",
+ "artifact hashes were not checked against Go VCS build identity",
+ "typed action scenario proved refusal before mutation, not successful host mutation",
+ "receipt predates irreversible collector credential reduction and rollback hardening"
+ ],
"residual_proof": [
"exact-release-candidate",
"representative-provider-and-appliance",
diff --git a/docs/release-control/v6/internal/records/secure-agent-runtime-qualification-foundation-2026-08-30.md b/docs/release-control/v6/internal/records/secure-agent-runtime-qualification-foundation-2026-08-30.md
index 273085c65d..a8a8d96f3d 100644
--- a/docs/release-control/v6/internal/records/secure-agent-runtime-qualification-foundation-2026-08-30.md
+++ b/docs/release-control/v6/internal/records/secure-agent-runtime-qualification-foundation-2026-08-30.md
@@ -2,12 +2,10 @@
## Scope
-This slice closes implementation defects found while preparing a real Linux
-systemd qualification of the optional collector/helper/action-runner split. It
-also records an exact committed-main real-systemd qualification of the
-collector/helper migration boundary and the separately credentialed action
-runner lifecycle. It does not flip the installer default and is not exact
-committed release-candidate or representative live-provider proof.
+This record now distinguishes the historical 2026-08-30 run from the hardened
+qualification contract that supersedes it. The historical receipt remains
+unchanged so its hash and provenance can still be checked; it must not be
+presented as qualification of the current collector/helper/action-runner split.
## Landed runtime semantics
@@ -19,7 +17,9 @@ committed release-candidate or representative live-provider proof.
process commits only after local readiness and acceptance of its newly
collected authoritative report. Interrupted, expired, or uncommitted state
recovers to last-known-good, and terminal transitions reap fixed staging and
- quarantine artifacts.
+ quarantine artifacts. Current code additionally verifies the root-staged
+ command reports the requested advancing collector version and binds commit
+ to the activating process after it execs the active digest.
- The action runner uses the canonical enrollment hostname. Durable rotation
invalidates exactly the superseded live organization/token/agent/hostname
session after token storage succeeds. Runner teardown attempts exact
@@ -28,16 +28,18 @@ committed release-candidate or representative live-provider proof.
- Safe-profile apply rejects foreign effective fragments and all systemd
drop-ins before mutation. Commit requires the intended non-root unit, a live
helper protocol response, and a server registration timestamp newer than the
- stopped legacy collector. Rollback restores full state-tree metadata and the
- Proxmox registration markers touched by installation. Transient runtime
- files that disappear while the collector is stopped do not prevent rollback
- from restoring every surviving pre-migration entry. Rootful Docker is
+ stopped legacy collector. Before any local privilege transition it durably
+ removes execution and cross-host management scope from the exact host-bound
+ collector credential.
+ Rollback restores installer-owned state-root metadata and the Proxmox
+ registration markers, but never traverses collector-controlled descendants
+ or resurrects `--enable-commands`. Rootful Docker is
disabled unless the collector owns a usable rootless runtime socket. Local
readiness and helper health receive a bounded startup window before the
separate authoritative registration proof. Installed collector binaries are
pinned to mode `0755` rather than inheriting `mktemp` permissions.
-## Exact committed-main systemd proof
+## Historical systemd evidence and corrected classification
The disposable arm64 Colima profile `pulse-agent-qual` ran Ubuntu 24.04.4,
kernel 6.8.0-117, and systemd 255. A clean detached worktree at commit
@@ -47,16 +49,23 @@ the lab binary. The source hashes in
receipt has SHA-256
`adeeec6bf02a73c27483da31d9e058a8686900324e32960399985e847487a271` and the
separate `secure-agent-runtime-committed-main-attestation-2026-08-30.json`
-binds the receipt, commit, detached checkout, exercised artifacts, and
-disposable-VM guard without altering the generated receipt. The attestation is
+binds the receipt, commit, detached checkout, and supplied artifact hashes
+without altering the generated receipt. The attestation was originally
produced with `scripts/release_control/secure_runtime_attestation.py`, which
fails closed unless the checkout is detached at the full commit, all tracked
files are clean, untracked files are confined to `.lab-artifacts`, the commit
is reachable from main, every receipt source hash matches the commit blob,
-all four artifact hashes match the exercised files, and the canonical twelve
-scenarios all passed in order. Supplying `--release-candidate-ref` additionally
-requires that ref to resolve exactly to the qualified commit and changes the
-proof classification to `exact-release-candidate`.
+all four artifact hashes match the supplied files, and the canonical twelve
+scenario records say they passed in order.
+
+That is useful integrity evidence, but the schema-v2 secret-free receipt is
+not authenticated independently of the operator who supplied it. The old tool
+also reported the disposable-VM guard as verified without consuming evidence
+for that assertion, accepted arbitrary matching artifact bytes without Go VCS
+build identity, and did not require all boundary sources. The current verifier
+requires schema v3, validates the guard claim rather than calling it
+independently verified, checks exact command package and clean-commit Go build
+stamps, and classifies the receipt as artifact-bound self-attestation.
The guarded lab passed all of these destructive scenarios from a clean VM:
- legacy root/command-capable install with rootful Docker enabled;
@@ -64,9 +73,9 @@ The guarded lab passed all of these destructive scenarios from a clean VM:
- migration to a non-root `pulse-agent` collector with no ambient capabilities,
monitoring-only authority, a healthy typed helper, fresh server `lastSeen`,
explicit rootful-Docker degradation, and continued reporting;
-- exact explicit rollback and automatic rollback when server freshness was
- frozen, including stable binary, unit, credential-state, ownership, and mode
- identity;
+- explicit and automatic local rollback when server freshness was frozen;
+ this predates irreversible server-side credential reduction and therefore
+ does not prove the current rollback contract;
- ordinary update without implicit privilege migration, followed by a final
committed safe-profile migration;
- separate root action-runner installation with a canonical hostname and
@@ -82,15 +91,16 @@ The guarded lab passed all of these destructive scenarios from a clean VM:
The receipt is intentionally secret-free and contains source/artifact hashes,
host facts, resulting privilege posture, report timestamps, and the twelve
-scenario outcomes. This is exact committed-main proof. It is still not exact
-release-candidate proof because no release candidate was designated for this
-run.
+scenario outcomes. It proves neither a successful action-runner host mutation
+nor the post-audit credential, rollback, update-artifact, and runner-unit
+hardening. It is retained as historical, hash-bound self-attested evidence.
## Proof classification and residuals
-The focused protocol, update, runner, API, and installer regressions plus the
-committed-main systemd receipt are proof for these semantics. They are not a
-substitute for exact committed release-candidate evidence, representative
+Focused regressions cover the current semantics. A fresh schema-v3 guarded
+systemd receipt is still required and must demonstrate the real apt-cache
+mutation plus stale-fingerprint refusal. Even that self-attested receipt is not
+a substitute for exact release-candidate evidence, representative
provider/appliance qualification, or external review.
The safe profile therefore remains opt-in. The default may not ratchet until
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 14ead6863e..5bed587911 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -43,6 +43,14 @@ host-storage-cleanup, Proxmox guest lifecycle, and container lifecycle/update
operations. Generic shell, exec, unrestricted `read_file`, and deploy requests
are forbidden. Removing or disabling the runner leaves collector monitoring
and the helper unchanged.
+Safe-profile collector credentials carry only `agent:report` and the
+host-bound `agent:config:read` capability; they carry neither `agent:exec` nor
+the broader `agent:manage` scope. Migration to that profile must durably remove
+both scopes from the exact collector token before local privilege separation,
+close only the matching live collector session, and fail closed if persistence
+does not complete. Once the remote authority reduction succeeds, every local
+rollback path must retain a monitoring-only collector service rather than
+restoring `--enable-commands` or otherwise recreating command authority.
When that helper socket is configured, collector startup must complete a
versioned `helper.health` request before the runtime may become ready. A
listening or active systemd socket alone is not helper health. Once the helper
@@ -61,6 +69,12 @@ expired, interrupted, invalid, or uncommitted activation rolls back during
helper recovery or through the deadline watchdog; commit and rollback remove
their fixed staging/quarantine artifacts durably. The first accepted report
retains the previous-version update evidence from that handoff.
+Before staging or activation, the helper must establish that the signed target
+is the Pulse agent Go command, that its declared and operational version equals
+the requested target, and that the target advances the installed version.
+Commit is additionally bound to the activating process ID and to the digest of
+that process's `/proc/<pid>/exe`, preventing an unrelated collector process
+from finalizing a pending replacement.
The runner's server transport currently reuses the combined agent command
WebSocket envelope as a migration boundary. That compatibility path may carry
@@ -71,6 +85,12 @@ have an action-runner migration path, live action-runner session parity is
qualified, and no supported client depends on collector command delivery.
Until those criteria are met, the combined collector command path is explicitly
legacy/full-trust compatibility, not part of the safe profile.
+Because the typed runner performs real package, storage, guest, and container
+mutations, its systemd service cannot use `ProtectSystem=strict`; the runner
+keeps the remaining identity, network, filesystem, capability, protocol, and
+receipt restrictions, while the collector and helper remain separately
+hardened. Qualification must prove an allowed mutation completes as well as
+proving generic command denial.
The runner service persists the same normalized canonical hostname used when
its credential was issued; it must not substitute the machine's incidental OS
hostname when the collector was enrolled under an override. Credential
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index e223190be1..200f6fc16c 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -199,12 +199,19 @@ or false preserves certificate verification. The server, not the browser,
continues to mint and quote the enrollment token.
Install-command credentials are monitoring-only unless the request explicitly
selects command execution. Monitoring credentials carry report and config-read
-scope without `agent:exec`; explicit command-capable credentials add
-`agent:exec`. Hosted PVE, PBS, and PMG commands do not infer execution authority
-from the target platform. Agent Doctor exposes the local command-authority
-profile and the server-derived credential execution scope as separate fields,
-and reports an over-scoped monitoring credential rather than hiding it behind
-the current command-enabled boolean.
+scope without `agent:exec` or `agent:manage`; explicit command-capable
+credentials add `agent:exec` only. Hosted PVE, PBS, and PMG commands do not
+infer execution authority from the target platform. Agent Doctor exposes the
+local command-authority profile and the server-derived credential execution
+scope as separate fields, and reports an over-scoped monitoring credential
+rather than hiding it behind the current command-enabled boolean.
+`POST /api/agents/collector/reduce-authority` is the authenticated, idempotent
+safe-profile migration boundary. Its JSON body identifies the caller's agent
+and canonical hostname; both must match the attached report credential and its
+organization. The transition rejects wildcard credentials, removes
+`agent:exec` and `agent:manage` from that exact token, persists before success,
+restores the full token inventory on persistence failure, and invalidates only
+the exact matching collector session after persistence.
## Canonical Files
@@ -8443,9 +8450,11 @@ top-level preset array that can reintroduce settings-chunk initialization-order
failures in production bundles.
The operator-created Agent preset must match the long-lived lifecycle minimum
used by server-issued agent credentials: `agent:report`, `agent:config:read`,
-and `agent:manage`. The custom create and edit surfaces must expose
-`agent:manage` so an operator can cycle a credential without losing config
-fetch or self-unregister authority. Single-use `agent:enroll`, dedicated
+and no broader management or execution scope. The custom create and edit
+surfaces may expose `agent:manage` only as an explicit operator-management
+choice; it is not part of the Agent preset because it bypasses host-bound
+configuration lookup and carries token-management authority. Single-use
+`agent:enroll`, dedicated
`relay:mobile:access`, and granular governed-action scopes remain backend-owned
and must not be presented as general-purpose token choices.
That same boundary now also includes
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index b7085586eb..e46065d9d2 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -135,9 +135,12 @@ the new binary is trusted. The replacement collector must pass local readiness
and have a fresh authoritative primary report accepted before it sends the
typed commit; helper startup/restart recovery and the watchdog restore the
last-known-good binary when activation is interrupted, expires, or never
-commits. Commit and rollback durably reap the fixed staging and quarantine
-artifacts. A socket-active check is insufficient: installer migration and the
-collector both exercise the versioned helper health protocol.
+commits. Before replacement, the helper proves the signed artifact is the Pulse
+agent command, reports the requested advancing version, and cannot be committed
+by a different process or executable digest. Commit and rollback durably reap
+the fixed staging and quarantine artifacts. A socket-active check is
+insufficient: installer migration and the collector both exercise the
+versioned helper health protocol.
The same supported Linux systemd profile can install `pulse-agent-runner` only
through the separate `--enable-action-runner` choice, a private token file,
@@ -152,6 +155,11 @@ uses a private curl configuration for best-effort exact self-revocation before
local teardown, so the bearer secret does not enter argv. Server unreachability
is warned explicitly but does not make local removal depend on the remote
control plane.
+The runner must retain a writable host filesystem because its closed protocol
+performs real package, storage, guest, and container mutations;
+`ProtectSystem=strict` is therefore forbidden for that unit. This exception
+does not apply to the collector or helper and does not relax the runner's
+separate identity, credential, network, capability, state, or receipt bounds.
Safe-profile migration is never an ordinary update side effect.
`--safe-profile-inspect` is read-only and reports the current authority,
@@ -167,9 +175,14 @@ Apply also fails before mutation when the effective collector fragment differs
from the installer-owned unit or any systemd drop-in is present. Commit requires
the effective non-root/no-ambient-capability unit, a live helper protocol
response, and a registration `lastSeen` newer than the frozen legacy
-collector's value. The rollback manifest restores all state-tree ownership and
-modes plus the Proxmox registration markers the apply path can mutate. Rootful
-Docker is an explicit migration degradation: it is disabled unless a
+collector's value. Before the local transition, apply calls the exact
+host-bound authority-reduction API and fails closed unless `agent:exec` and
+`agent:manage` are durably removed. The rollback manifest restores only the
+installer-owned state-root metadata plus the Proxmox registration markers the
+apply path can mutate; it never replays collector-controlled descendant paths,
+and every rollback strips the legacy command flag rather than reversing the
+server-side reduction. Rootful Docker is an explicit migration degradation: it
+is disabled unless a
collector-owned, readable and writable rootless runtime socket is available;
the safe profile never restores Docker by adding the collector to a
root-equivalent group.
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 6089b9931d..eaa5943d3e 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -30,11 +30,11 @@ is the required concurrency proof.
Pulse-minted Unified Agent credentials follow least authority at issuance.
Implicit and ordinary monitoring installs receive `agent:report` and
-`agent:config:read`, never `agent:exec`. Execution scope is added only for an
-explicit command-capable installer choice. Local runtime authority remains an
-independent ceiling: a credential with `agent:exec` cannot promote a service
-installed as `monitoring-only`, and Agent Doctor must warn when such excess
-scope remains attached to that runtime.
+`agent:config:read`, never `agent:exec` or `agent:manage`. Execution scope is
+added only for an explicit command-capable installer choice. Local runtime
+authority remains an independent ceiling: a credential with `agent:exec`
+cannot promote a service installed as `monitoring-only`, and Agent Doctor must
+warn when such excess scope remains attached to that runtime.
Privileged host telemetry crosses only the local typed helper boundary owned by
`internal/agenthelper/` and `cmd/pulse-agent-helper/main.go`. That root process
@@ -53,6 +53,11 @@ shape, regular-file identity, symlink resistance, and byte ceiling before
copying into fixed root-owned staging. Activation and rollback then revalidate
the root boundary, perform atomic replacement, and durably bind the transition
identity before changing the root-owned collector binary.
+The helper must identify the candidate statically as the Pulse agent Go
+command, require both its build metadata and bounded `--version` output to
+equal the requested target, and reject a target that does not advance the
+installed version. Commit is accepted only from the activating process ID when
+the digest of its live `/proc/<pid>/exe` equals the pending artifact digest.
Activation is not final authority: the helper records a bounded pending state
and last-known-good digest before replacement, and exposes an exact typed
commit. Only the replacement collector's local readiness plus an accepted new
@@ -74,6 +79,11 @@ shell/exec, unrestricted `read_file`, deploy, and trusted-origin bypasses are
forbidden. The legacy combined command channel remains a disclosed full-trust
migration boundary only until runner enrollment and live session parity are
qualified; it is not safe-profile authority.
+The action runner necessarily has a writable host view for its closed mutation
+set, so `ProtectSystem=strict` is not a valid runner sandbox claim. Its separate
+credential, no-listener transport, typed admission, target and digest binding,
+bounded capabilities, state privacy, and durable receipts are the compensating
+boundary; collector and helper filesystem hardening remains independent.
Action-runner issuance and rotation are one durable host-bound transition per
organization and canonical agent ID. Re-issuance replaces the prior runner
record even when the monitored hostname has changed, returns the new plaintext
@@ -89,6 +99,14 @@ credential; browser sessions and a caller-selected token ID are rejected, and
persistence failure restores the prior inventory. Installer teardown keeps the
secret in a private file/config boundary rather than argv and reports remote
revocation failure without retaining local remediation authority.
+Safe-profile migration uses the authenticated
+`POST /api/agents/collector/reduce-authority` transition. The server accepts
+only the caller's exact organization, agent, and canonical hostname; rejects
+wildcard, cross-host, and cross-organization credentials; durably removes both
+`agent:exec` and `agent:manage`; restores a deep token snapshot on persistence
+failure; and then closes only the superseded live collector session. The
+installer must not undo that server-side reduction during local rollback and
+must strip collector command flags from any restored service definition.
Own Pulse's canonical privacy disclosures, outbound usage-data boundary,
and the security-facing settings surfaces that expose authentication posture,
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 4b0dd6cef5..37d061366e 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -42,6 +42,12 @@ self-revocation uses the same durable boundary and cannot select another token,
organization, or host. That rollback protects restart-time
credential truth only; it is not a customer backup, recovery point, restore
operation, or storage-cleanup grant.
+The adjacent collector authority-reduction route removes `agent:exec` and
+`agent:manage` only from the caller's exact host-bound credential and closes
+only its matching command session after durable persistence. This transition
+cannot select, mutate, restore, delete, or reclassify storage/recovery evidence;
+installer rollback retains the reduced credential and restores no
+collector-controlled descendant metadata as a storage snapshot.
The helper-backed collector updater likewise retains only one fixed
last-known-good executable and an identity-bound pending/commit receipt. A
startup recovery or deadline rollback of an uncommitted activation is agent
diff --git a/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx b/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
index c91e99f9a0..ea7f493d19 100644
--- a/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
@@ -7,7 +7,6 @@ import type { Resource } from '@/types/resource';
import {
AI_EXECUTE_SCOPE,
AGENT_CONFIG_READ_SCOPE,
- AGENT_MANAGE_SCOPE,
AGENT_REPORT_SCOPE,
AUDIT_READ_SCOPE,
DOCKER_MANAGE_SCOPE,
@@ -310,11 +309,11 @@ describe('APITokenManager', () => {
});
});
- it('creates manually cycled agent tokens with the runtime lifecycle scopes', async () => {
+ it('creates manually cycled agent tokens with bound collector scopes', async () => {
createTokenMock.mockResolvedValue(
makeToken({
name: 'Replacement agent token',
- scopes: [AGENT_REPORT_SCOPE, AGENT_CONFIG_READ_SCOPE, AGENT_MANAGE_SCOPE],
+ scopes: [AGENT_REPORT_SCOPE, AGENT_CONFIG_READ_SCOPE],
}),
);
@@ -329,7 +328,6 @@ describe('APITokenManager', () => {
await waitFor(() => {
expect(createTokenMock).toHaveBeenCalledWith('Replacement agent token', [
AGENT_CONFIG_READ_SCOPE,
- AGENT_MANAGE_SCOPE,
AGENT_REPORT_SCOPE,
]);
});
diff --git a/frontend-modern/src/components/Settings/__tests__/apiTokenManagerModel.branchcov0713.test.ts b/frontend-modern/src/components/Settings/__tests__/apiTokenManagerModel.branchcov0713.test.ts
index ffd88c7eb5..40d6e77cdc 100644
--- a/frontend-modern/src/components/Settings/__tests__/apiTokenManagerModel.branchcov0713.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/apiTokenManagerModel.branchcov0713.test.ts
@@ -4,7 +4,6 @@ import {
API_SCOPE_OPTIONS,
type APIScopeOption,
AGENT_CONFIG_READ_SCOPE,
- AGENT_MANAGE_SCOPE,
AGENT_REPORT_SCOPE,
AUDIT_READ_SCOPE,
DOCKER_MANAGE_SCOPE,
@@ -520,9 +519,9 @@ describe('getAPITokenScopePresets (full structure)', () => {
expect(byId.get(API_TOKEN_AGENT_PRESET_ID)).toStrictEqual({
id: API_TOKEN_AGENT_PRESET_ID,
label: 'Agent',
- scopes: [AGENT_REPORT_SCOPE, AGENT_CONFIG_READ_SCOPE, AGENT_MANAGE_SCOPE],
+ scopes: [AGENT_REPORT_SCOPE, AGENT_CONFIG_READ_SCOPE],
description:
- 'Allow the Pulse agent to report host metrics, fetch its configuration, and unregister during uninstall.',
+ 'Allow the Pulse agent to report host metrics and fetch only its bound configuration.',
});
expect(byId.get(API_TOKEN_DOCKER_REPORT_PRESET_ID)).toStrictEqual({
id: API_TOKEN_DOCKER_REPORT_PRESET_ID,
diff --git a/frontend-modern/src/components/Settings/apiTokenManagerModel.ts b/frontend-modern/src/components/Settings/apiTokenManagerModel.ts
index 6a39f5c178..7af92a6638 100644
--- a/frontend-modern/src/components/Settings/apiTokenManagerModel.ts
+++ b/frontend-modern/src/components/Settings/apiTokenManagerModel.ts
@@ -3,7 +3,6 @@ import type { APITokenRecord } from '@/api/security';
import {
AUDIT_READ_SCOPE,
AGENT_CONFIG_READ_SCOPE,
- AGENT_MANAGE_SCOPE,
AGENT_REPORT_SCOPE,
API_SCOPE_OPTIONS,
DOCKER_MANAGE_SCOPE,
@@ -92,9 +91,9 @@ export const getAPITokenScopePresets = (
{
id: API_TOKEN_AGENT_PRESET_ID,
label: 'Agent',
- scopes: [AGENT_REPORT_SCOPE, AGENT_CONFIG_READ_SCOPE, AGENT_MANAGE_SCOPE],
+ scopes: [AGENT_REPORT_SCOPE, AGENT_CONFIG_READ_SCOPE],
description:
- 'Allow the Pulse agent to report host metrics, fetch its configuration, and unregister during uninstall.',
+ 'Allow the Pulse agent to report host metrics and fetch only its bound configuration.',
},
{
id: API_TOKEN_DOCKER_REPORT_PRESET_ID,
diff --git a/internal/agentexec/server.go b/internal/agentexec/server.go
index ddd14af33d..92e68bab97 100644
--- a/internal/agentexec/server.go
+++ b/internal/agentexec/server.go
@@ -413,6 +413,47 @@ func (s *Server) InvalidateActionRunnerSession(admission AgentAdmission) bool {
return true
}
+// InvalidateAgentSession closes exactly the currently admitted session for a
+// credential whose authority has changed. Unlike action-runner rotation this
+// accepts either runtime role, but every admission field must still match so a
+// stale or cross-tenant credential transition cannot evict another session.
+func (s *Server) InvalidateAgentSession(admission AgentAdmission) bool {
+ if s == nil {
+ return false
+ }
+ expected := AgentAdmission{
+ OrganizationID: normalizeOrganizationID(admission.OrganizationID),
+ TokenID: strings.TrimSpace(admission.TokenID),
+ AgentID: strings.TrimSpace(admission.AgentID),
+ Hostname: strings.TrimSpace(admission.Hostname),
+ RuntimeRole: strings.TrimSpace(admission.RuntimeRole),
+ ActionCapability: strings.TrimSpace(admission.ActionCapability),
+ }
+ if expected.TokenID == "" || expected.AgentID == "" || expected.Hostname == "" || expected.RuntimeRole == "" {
+ return false
+ }
+ key := agentSessionKey(expected.OrganizationID, expected.AgentID)
+ s.mu.Lock()
+ current, ok := s.agents[key]
+ if !ok || current == nil ||
+ normalizeOrganizationID(current.admission.OrganizationID) != expected.OrganizationID ||
+ strings.TrimSpace(current.admission.TokenID) != expected.TokenID ||
+ strings.TrimSpace(current.admission.AgentID) != expected.AgentID ||
+ !unifiedresources.HostnamesEquivalent(current.admission.Hostname, expected.Hostname) ||
+ strings.TrimSpace(current.admission.RuntimeRole) != expected.RuntimeRole ||
+ strings.TrimSpace(current.admission.ActionCapability) != expected.ActionCapability {
+ s.mu.Unlock()
+ return false
+ }
+ delete(s.agents, key)
+ s.mu.Unlock()
+ current.signalDone()
+ if current.conn != nil {
+ _ = current.conn.Close()
+ }
+ return true
+}
+
func sameActionRunnerAdmission(current, expected AgentAdmission) bool {
return normalizeOrganizationID(current.OrganizationID) == expected.OrganizationID &&
strings.TrimSpace(current.TokenID) == expected.TokenID &&
diff --git a/internal/agentexec/server_websocket_test.go b/internal/agentexec/server_websocket_test.go
index 361d52ed6a..b70a5432ad 100644
--- a/internal/agentexec/server_websocket_test.go
+++ b/internal/agentexec/server_websocket_test.go
@@ -1306,6 +1306,40 @@ func TestInvalidateActionRunnerSessionClosesExactSessionAndUnblocksInflightDispa
}
}
+func TestInvalidateAgentSessionRequiresExactLegacyAdmission(t *testing.T) {
+ admission := AgentAdmission{
+ OrganizationID: "org-a", TokenID: "collector-token", AgentID: "agent-a",
+ Hostname: "node.example", RuntimeRole: RuntimeRoleLegacyFullTrust,
+ }
+ s := NewServerWithAdmissionValidator(func(token, _, _ string) (AgentAdmission, bool) {
+ return admission, token == admission.TokenID
+ }, func(candidate AgentAdmission) bool { return candidate == admission })
+ ts := newWSServer(t, s)
+ defer ts.Close()
+ conn, _, err := dialAgentExecWebSocket(t, ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{
+ AgentID: admission.AgentID, Hostname: admission.Hostname, Token: admission.TokenID,
+ }))
+ if ack := wsReadRegisteredPayload(t, conn); !ack.Success {
+ t.Fatalf("registration failed: %s", ack.Message)
+ }
+ wrong := admission
+ wrong.TokenID = "other-token"
+ if s.InvalidateAgentSession(wrong) {
+ t.Fatal("mismatched token evicted legacy session")
+ }
+ if !s.InvalidateAgentSession(admission) {
+ t.Fatal("exact legacy admission was not invalidated")
+ }
+ if s.IsAgentConnectedForOrganization("org-a", "agent-a") {
+ t.Fatal("invalidated legacy session remained connected")
+ }
+}
+
// registerCancelTestAgent registers agent "a1" over the websocket harness and
// returns after the registration ack has been read.
func registerCancelTestAgent(t *testing.T, s *Server, tsURL string) *cancelTestConn {
diff --git a/internal/agenthelper/server.go b/internal/agenthelper/server.go
index 13575baefb..d1b735a9c0 100644
--- a/internal/agenthelper/server.go
+++ b/internal/agenthelper/server.go
@@ -18,6 +18,16 @@ type Peer struct {
PID int32
}
+type peerContextKey struct{}
+
+// PeerFromContext returns the kernel-authenticated Unix peer for a helper
+// operation. Providers can use it to bind multi-step state transitions to the
+// exact process that initiated them.
+func PeerFromContext(ctx context.Context) (Peer, bool) {
+ peer, ok := ctx.Value(peerContextKey{}).(Peer)
+ return peer, ok
+}
+
type PeerResolver interface {
Resolve(net.Conn) (Peer, error)
}
@@ -156,7 +166,7 @@ func (s *Server) HandleConnection(parent context.Context, conn net.Conn) {
return
}
- operationContext, cancel := context.WithTimeout(parent, time.Duration(request.DeadlineMillis)*time.Millisecond)
+ operationContext, cancel := context.WithTimeout(context.WithValue(parent, peerContextKey{}, peer), time.Duration(request.DeadlineMillis)*time.Millisecond)
defer cancel()
result, operationError := operation.handle(operationContext, request.Payload)
if operationError == nil && operationContext.Err() != nil {
diff --git a/internal/agenthelper/update_activation.go b/internal/agenthelper/update_activation.go
index 2ebf2a1d85..21bcf1ca77 100644
--- a/internal/agenthelper/update_activation.go
+++ b/internal/agenthelper/update_activation.go
@@ -12,6 +12,8 @@ import (
"strings"
"sync"
"time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/utils"
)
const maxUpdateArtifactBytes = 100 * 1024 * 1024
@@ -25,11 +27,13 @@ const (
type UpdateActivateRequest struct {
ArtifactID string `json:"artifactId"`
SHA256 string `json:"sha256"`
+ Version string `json:"version"`
}
type UpdateStageRequest struct {
ArtifactID string `json:"artifactId"`
SHA256 string `json:"sha256"`
+ Version string `json:"version"`
}
type UpdateStageResult struct {
@@ -65,6 +69,8 @@ type UpdateActivatorConfig struct {
TargetPath string
StatePath string
VerifySignature func([]byte, string) error
+ InspectVersion func(context.Context, string) (string, error)
+ ValidateCommitter func(context.Context, string) error
ValidateOwner func(*os.File) error
ValidateQuarantineOwner func(*os.File) error
Now func() time.Time
@@ -80,6 +86,8 @@ type updateActivator struct {
rollbackPath string
statePath string
verifySignature func([]byte, string) error
+ inspectVersion func(context.Context, string) (string, error)
+ validateCommitter func(context.Context, string) error
validateOwner func(*os.File) error
validateQuarantineOwner func(*os.File) error
now func() time.Time
@@ -95,11 +103,12 @@ type durableUpdateState struct {
RollbackSHA256 string `json:"rollbackSha256"`
RollbackDeadline time.Time `json:"rollbackDeadline,omitempty"`
UpdatedAt time.Time `json:"updatedAt"`
+ ActivatorPID int32 `json:"activatorPid,omitempty"`
}
func NewUpdateActivator(config UpdateActivatorConfig) (UpdateProvider, error) {
- if config.VerifySignature == nil || config.ValidateOwner == nil || config.ValidateQuarantineOwner == nil {
- return nil, errors.New("signature, root-ownership, and quarantine-ownership validators are required")
+ if config.VerifySignature == nil || config.InspectVersion == nil || config.ValidateCommitter == nil || config.ValidateOwner == nil || config.ValidateQuarantineOwner == nil {
+ return nil, errors.New("signature, artifact-version, committer, root-ownership, and quarantine-ownership validators are required")
}
for _, path := range []string{config.QuarantineDir, config.StagingDir, config.TargetPath, config.StatePath} {
if path == "" || !filepath.IsAbs(path) || filepath.Clean(path) != path {
@@ -133,7 +142,7 @@ func NewUpdateActivator(config UpdateActivatorConfig) (UpdateProvider, error) {
activator := &updateActivator{
quarantineDir: config.QuarantineDir, stagingDir: config.StagingDir, targetPath: config.TargetPath,
rollbackPath: config.TargetPath + ".last-known-good", statePath: config.StatePath,
- verifySignature: config.VerifySignature, validateOwner: config.ValidateOwner,
+ verifySignature: config.VerifySignature, inspectVersion: config.InspectVersion, validateCommitter: config.ValidateCommitter, validateOwner: config.ValidateOwner,
validateQuarantineOwner: config.ValidateQuarantineOwner, now: now,
rollbackWindow: rollbackWindow, scheduleRollback: scheduleRollback,
}
@@ -150,7 +159,8 @@ func NewUpdateActivator(config UpdateActivatorConfig) (UpdateProvider, error) {
func (u *updateActivator) Stage(ctx context.Context, request UpdateStageRequest) (UpdateStageResult, error) {
u.mu.Lock()
defer u.mu.Unlock()
- if !validArtifactID(request.ArtifactID) || !validSHA256(request.SHA256) {
+ request.Version = strings.TrimSpace(request.Version)
+ if !validArtifactID(request.ArtifactID) || !validSHA256(request.SHA256) || !validArtifactVersion(request.Version) {
return UpdateStageResult{}, invalidArtifact("artifact identity or digest is invalid")
}
if err := u.validateDirectoryWith(u.quarantineDir, u.validateQuarantineOwner); err != nil {
@@ -188,13 +198,33 @@ func (u *updateActivator) Stage(ctx context.Context, request UpdateStageRequest)
if err := u.installStagedArtifact(destination, artifact, signature); err != nil {
return UpdateStageResult{}, &ProviderError{Code: ErrorInternal, Message: "promote quarantined artifact into root staging"}
}
+ removeInvalidStaging := func(message string) (UpdateStageResult, error) {
+ _ = u.removeStagedArtifact(request.ArtifactID)
+ return UpdateStageResult{}, invalidArtifact(message)
+ }
+ candidateVersion, err := u.inspectVersion(ctx, filepath.Join(destination, "pulse-agent"))
+ if err != nil || strings.TrimSpace(candidateVersion) != request.Version {
+ return removeInvalidStaging("signed artifact is not the requested pulse-agent version")
+ }
+ currentVersion, err := u.inspectVersion(ctx, u.targetPath)
+ if err != nil || !validArtifactVersion(strings.TrimSpace(currentVersion)) {
+ return removeInvalidStaging("installed pulse-agent version is unavailable")
+ }
+ if utils.CompareVersions(utils.NormalizeVersion(request.Version), utils.NormalizeVersion(strings.TrimSpace(currentVersion))) <= 0 {
+ return removeInvalidStaging("signed artifact does not advance the installed pulse-agent version")
+ }
return UpdateStageResult{Action: "staged", ArtifactID: request.ArtifactID, SHA256: actual, DurableAt: u.now().UTC()}, nil
}
+func validArtifactVersion(version string) bool {
+ return version != "" && version != "dev" && len(version) <= 128 && !strings.ContainsAny(version, "\x00\r\n")
+}
+
func (u *updateActivator) Activate(ctx context.Context, request UpdateActivateRequest) (UpdateResult, error) {
u.mu.Lock()
defer u.mu.Unlock()
- if !validArtifactID(request.ArtifactID) || !validSHA256(request.SHA256) {
+ request.Version = strings.TrimSpace(request.Version)
+ if !validArtifactID(request.ArtifactID) || !validSHA256(request.SHA256) || !validArtifactVersion(request.Version) {
return UpdateResult{}, invalidArtifact("artifact identity or digest is invalid")
}
if err := u.validateDirectory(u.stagingDir); err != nil {
@@ -222,6 +252,10 @@ func (u *updateActivator) Activate(ctx context.Context, request UpdateActivateRe
if err := u.verifySignature(artifact, strings.TrimSpace(string(signatureBytes))); err != nil {
return UpdateResult{}, invalidArtifact("staged artifact signature is invalid")
}
+ candidateVersion, err := u.inspectVersion(ctx, filepath.Join(artifactDir, "pulse-agent"))
+ if err != nil || strings.TrimSpace(candidateVersion) != request.Version {
+ return UpdateResult{}, invalidArtifact("staged artifact is not the requested pulse-agent version")
+ }
activationID := request.ArtifactID + ":" + actual[:16]
if state, err := u.readState(); err == nil {
if state.Action == "preparing" || state.Action == "pending" {
@@ -256,11 +290,17 @@ func (u *updateActivator) Activate(ctx context.Context, request UpdateActivateRe
if err != nil {
return UpdateResult{}, &ProviderError{Code: ErrorStateConflict, Message: "installed agent binary is unavailable or unsafe"}
}
+ currentVersion, err := u.inspectVersion(ctx, u.targetPath)
+ if err != nil || !validArtifactVersion(strings.TrimSpace(currentVersion)) ||
+ utils.CompareVersions(utils.NormalizeVersion(request.Version), utils.NormalizeVersion(strings.TrimSpace(currentVersion))) <= 0 {
+ return UpdateResult{}, invalidArtifact("staged artifact does not advance the installed pulse-agent version")
+ }
rollbackDigest := sha256Hex(current)
deadline := u.now().UTC().Add(u.rollbackWindow)
+ peer, _ := PeerFromContext(ctx)
preparing := durableUpdateState{
Action: "preparing", ActivationID: activationID, ActiveSHA256: actual,
- RollbackSHA256: rollbackDigest, RollbackDeadline: deadline, UpdatedAt: u.now().UTC(),
+ RollbackSHA256: rollbackDigest, RollbackDeadline: deadline, UpdatedAt: u.now().UTC(), ActivatorPID: peer.PID,
}
if err := u.writeDurableState(preparing); err != nil {
return UpdateResult{}, &ProviderError{Code: ErrorInternal, Message: "persist activation intent"}
@@ -272,7 +312,7 @@ func (u *updateActivator) Activate(ctx context.Context, request UpdateActivateRe
pending := durableUpdateState{
Action: "pending", ActivationID: activationID,
ActiveSHA256: actual, RollbackSHA256: rollbackDigest,
- RollbackDeadline: deadline, UpdatedAt: u.now().UTC(),
+ RollbackDeadline: deadline, UpdatedAt: u.now().UTC(), ActivatorPID: peer.PID,
}
if err := u.writeDurableState(pending); err != nil {
if recoveryErr := u.recoverStateLocked(preparing); recoveryErr != nil {
@@ -309,6 +349,12 @@ func (u *updateActivator) Commit(ctx context.Context, request UpdateCommitReques
if err := ctx.Err(); err != nil {
return UpdateResult{}, &ProviderError{Code: ErrorDeadlineExceeded, Message: "update commit deadline exceeded", Retryable: true}
}
+ if peer, ok := PeerFromContext(ctx); state.ActivatorPID > 0 && (!ok || peer.PID != state.ActivatorPID) {
+ return UpdateResult{}, &ProviderError{Code: ErrorStateConflict, Message: "commit must come from the activated collector process"}
+ }
+ if err := u.validateCommitter(ctx, state.ActiveSHA256); err != nil {
+ return UpdateResult{}, &ProviderError{Code: ErrorStateConflict, Message: "commit caller is not the activated collector binary"}
+ }
if err := u.validateInstalledState(state); err != nil {
return UpdateResult{}, err
}
@@ -570,7 +616,9 @@ func (u *updateActivator) installStagedArtifact(destination string, artifact, si
if err := os.Chmod(tempDir, 0o700); err != nil {
return err
}
- binaryTemp, err := writeSyncedTemp(tempDir, ".pulse-agent-*", artifact, 0o600)
+ // Root-owned staging is executable only so the helper can perform the fixed
+ // pulse-agent identity/version probe. The collector cannot modify this tree.
+ binaryTemp, err := writeSyncedTemp(tempDir, ".pulse-agent-*", artifact, 0o700)
if err != nil {
return err
}
diff --git a/internal/agenthelper/update_activation_test.go b/internal/agenthelper/update_activation_test.go
index 5889c4412a..b2dd7bc168 100644
--- a/internal/agenthelper/update_activation_test.go
+++ b/internal/agenthelper/update_activation_test.go
@@ -28,7 +28,18 @@ func testUpdateActivator(t *testing.T, verifier func([]byte, string) error) (Upd
}
provider, err := NewUpdateActivator(UpdateActivatorConfig{
QuarantineDir: quarantine, StagingDir: staging, TargetPath: target, StatePath: filepath.Join(stateDir, "activation.json"),
- VerifySignature: verifier,
+ VerifySignature: verifier,
+ InspectVersion: func(_ context.Context, path string) (string, error) {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return "", err
+ }
+ if strings.Contains(string(data), "old-signed-binary") {
+ return "1.0.0", nil
+ }
+ return "1.1.0", nil
+ },
+ ValidateCommitter: func(context.Context, string) error { return nil },
ValidateOwner: func(*os.File) error { return nil },
ValidateQuarantineOwner: func(*os.File) error { return nil },
Now: func() time.Time { return time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC) },
@@ -61,7 +72,7 @@ func stageUpdate(t *testing.T, staging, identity string, binary []byte) string {
func promoteUpdate(t *testing.T, provider UpdateProvider, artifactID, digest string) {
t.Helper()
- result, err := provider.Stage(context.Background(), UpdateStageRequest{ArtifactID: artifactID, SHA256: digest})
+ result, err := provider.Stage(context.Background(), UpdateStageRequest{ArtifactID: artifactID, SHA256: digest, Version: "1.1.0"})
if err != nil {
t.Fatalf("Stage: %v", err)
}
@@ -80,7 +91,7 @@ func TestUpdateActivationAndIdentityBoundRollbackAreDurable(t *testing.T) {
newDigest := stageUpdate(t, staging, "release-1", testELF("new-signed-binary"))
promoteUpdate(t, provider, "release-1", newDigest)
oldDigest := sha256Hex(testELF("old-signed-binary"))
- activated, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-1", SHA256: newDigest})
+ activated, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-1", SHA256: newDigest, Version: "1.1.0"})
if err != nil {
t.Fatalf("Activate: %v", err)
}
@@ -96,7 +107,7 @@ func TestUpdateActivationAndIdentityBoundRollbackAreDurable(t *testing.T) {
if info, err := os.Stat(state); err != nil || info.Mode().Perm() != 0o600 {
t.Fatalf("durable state mode=%v err=%v", info, err)
}
- retried, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-1", SHA256: newDigest})
+ retried, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-1", SHA256: newDigest, Version: "1.1.0"})
if err != nil || retried != activated {
t.Fatalf("idempotent activation retry = %#v err=%v, want %#v", retried, err, activated)
}
@@ -123,7 +134,7 @@ func TestUpdateCommitClosesRollbackWindowAndCleansStaging(t *testing.T) {
provider, quarantine, target, _ := testUpdateActivator(t, func([]byte, string) error { return nil })
digest := stageUpdate(t, quarantine, "release-commit", testELF("committed"))
promoteUpdate(t, provider, "release-commit", digest)
- activation, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-commit", SHA256: digest})
+ activation, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-commit", SHA256: digest, Version: "1.1.0"})
if err != nil {
t.Fatal(err)
}
@@ -155,11 +166,33 @@ func TestUpdateCommitClosesRollbackWindowAndCleansStaging(t *testing.T) {
}
}
+func TestUpdateCommitRequiresActivatingProcessAfterExecTransition(t *testing.T) {
+ provider, quarantine, _, _ := testUpdateActivator(t, func([]byte, string) error { return nil })
+ digest := stageUpdate(t, quarantine, "process-bound", testELF("new-signed-binary"))
+ promoteUpdate(t, provider, "process-bound", digest)
+ activating := context.WithValue(context.Background(), peerContextKey{}, Peer{UID: 1000, PID: 4321})
+ activation, err := provider.Activate(activating, UpdateActivateRequest{ArtifactID: "process-bound", SHA256: digest, Version: "1.1.0"})
+ if err != nil {
+ t.Fatalf("Activate: %v", err)
+ }
+ otherProcess := context.WithValue(context.Background(), peerContextKey{}, Peer{UID: 1000, PID: 4322})
+ if _, err := provider.Commit(otherProcess, UpdateCommitRequest{
+ ActivationID: activation.ActivationID, CurrentSHA256: activation.ActiveSHA256,
+ }); err == nil || !strings.Contains(err.Error(), "activated collector process") {
+ t.Fatalf("different process committed pending activation: %v", err)
+ }
+ if _, err := provider.Commit(activating, UpdateCommitRequest{
+ ActivationID: activation.ActivationID, CurrentSHA256: activation.ActiveSHA256,
+ }); err != nil {
+ t.Fatalf("activating process could not commit after validation: %v", err)
+ }
+}
+
func TestUpdateActivatorRestartRollsBackUncommittedActivation(t *testing.T) {
provider, quarantine, target, state := testUpdateActivator(t, func([]byte, string) error { return nil })
digest := stageUpdate(t, quarantine, "release-restart", testELF("uncommitted"))
promoteUpdate(t, provider, "release-restart", digest)
- activation, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-restart", SHA256: digest})
+ activation, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-restart", SHA256: digest, Version: "1.1.0"})
if err != nil {
t.Fatal(err)
}
@@ -172,6 +205,17 @@ func TestUpdateActivatorRestartRollsBackUncommittedActivation(t *testing.T) {
VerifySignature: func([]byte, string) error {
return nil
},
+ InspectVersion: func(_ context.Context, path string) (string, error) {
+ data, readErr := os.ReadFile(path)
+ if readErr != nil {
+ return "", readErr
+ }
+ if strings.Contains(string(data), "old-signed-binary") {
+ return "1.0.0", nil
+ }
+ return "1.1.0", nil
+ },
+ ValidateCommitter: func(context.Context, string) error { return nil },
ValidateOwner: func(*os.File) error { return nil },
ValidateQuarantineOwner: func(*os.File) error { return nil },
Now: func() time.Time { return activation.RollbackDeadline.Add(-time.Second) },
@@ -191,6 +235,23 @@ func TestUpdateActivatorRestartRollsBackUncommittedActivation(t *testing.T) {
}
}
+func TestUpdateStagingRejectsWrongArtifactVersionAndDowngrade(t *testing.T) {
+ provider, quarantine, _, _ := testUpdateActivator(t, func([]byte, string) error { return nil })
+ digest := stageUpdate(t, quarantine, "wrong-role", testELF("signed-other-component"))
+ if _, err := provider.Stage(context.Background(), UpdateStageRequest{
+ ArtifactID: "wrong-role", SHA256: digest, Version: "9.9.9",
+ }); err == nil || !strings.Contains(err.Error(), "requested pulse-agent version") {
+ t.Fatalf("wrong signed artifact role/version accepted: %v", err)
+ }
+
+ digest = stageUpdate(t, quarantine, "downgrade", testELF("old-signed-binary"))
+ if _, err := provider.Stage(context.Background(), UpdateStageRequest{
+ ArtifactID: "downgrade", SHA256: digest, Version: "1.0.0",
+ }); err == nil || !strings.Contains(err.Error(), "does not advance") {
+ t.Fatalf("signed downgrade accepted: %v", err)
+ }
+}
+
func TestUpdateRollbackWatchdogRestoresUncommittedActivation(t *testing.T) {
provider, quarantine, target, _ := testUpdateActivator(t, func([]byte, string) error { return nil })
activator := provider.(*updateActivator)
@@ -201,7 +262,7 @@ func TestUpdateRollbackWatchdogRestoresUncommittedActivation(t *testing.T) {
}
digest := stageUpdate(t, quarantine, "release-watchdog", testELF("uncommitted"))
promoteUpdate(t, provider, "release-watchdog", digest)
- activation, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-watchdog", SHA256: digest})
+ activation, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-watchdog", SHA256: digest, Version: "1.1.0"})
if err != nil || watchdog == nil {
t.Fatalf("Activate = %#v, %v; watchdog=%v", activation, err, watchdog != nil)
}
@@ -260,14 +321,14 @@ func TestUpdateActivationRejectsTraversalSymlinksAndDigestMismatch(t *testing.T)
if _, err := provider.Stage(context.Background(), UpdateStageRequest{ArtifactID: "symlink-release", SHA256: sha256Hex([]byte("attacker"))}); err == nil {
t.Fatal("symlink artifact accepted")
}
+ promoteUpdate(t, provider, "release-1", validDigest)
if err := os.Remove(target); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outside, target); err != nil {
t.Fatal(err)
}
- promoteUpdate(t, provider, "release-1", validDigest)
- if _, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-1", SHA256: validDigest}); err == nil {
+ if _, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-1", SHA256: validDigest, Version: "1.1.0"}); err == nil {
t.Fatal("symlink install target accepted")
}
}
@@ -290,7 +351,7 @@ func TestUpdateActivationUsesOpenedBytesAcrossStagingSwap(t *testing.T) {
digest := stageUpdate(t, staging, "release-swap", testELF("verified-bytes"))
stagingBinary = filepath.Join(staging, "release-swap", "pulse-agent")
promoteUpdate(t, provider, "release-swap", digest)
- if _, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-swap", SHA256: digest}); err != nil {
+ if _, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-swap", SHA256: digest, Version: "1.1.0"}); err != nil {
t.Fatalf("Activate: %v", err)
}
if installed, _ := os.ReadFile(target); string(installed) != string(testELF("verified-bytes")) {
@@ -302,7 +363,7 @@ func TestUpdateRollbackRejectsWrongIdentityAndChangedBinary(t *testing.T) {
provider, staging, target, _ := testUpdateActivator(t, func([]byte, string) error { return nil })
digest := stageUpdate(t, staging, "release-1", testELF("new"))
promoteUpdate(t, provider, "release-1", digest)
- result, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-1", SHA256: digest})
+ result, err := provider.Activate(context.Background(), UpdateActivateRequest{ArtifactID: "release-1", SHA256: digest, Version: "1.1.0"})
if err != nil {
t.Fatal(err)
}
diff --git a/internal/agentupdate/coverage_test.go b/internal/agentupdate/coverage_test.go
index 169ed7e604..593c3f8d08 100644
--- a/internal/agentupdate/coverage_test.go
+++ b/internal/agentupdate/coverage_test.go
@@ -47,7 +47,7 @@ func TestPrivilegedUpdateRollbackFailurePreservesPendingHandoff(t *testing.T) {
u := New(Config{PrivilegedUpdate: helper, Disabled: true, StateDir: helper.root, CurrentVersion: "1.0.0"})
u.selfTestFn = func(context.Context, string) error { return nil }
- err := u.performPrivilegedUpdate(context.Background(), "/usr/local/bin/pulse-agent", bytes.NewReader(binary), int64(len(binary)), digest, "signed-update")
+ err := u.performPrivilegedUpdate(context.Background(), "/usr/local/bin/pulse-agent", bytes.NewReader(binary), int64(len(binary)), digest, "signed-update", "1.1.0")
if err == nil || !strings.Contains(err.Error(), "typed helper rollback failed") {
t.Fatalf("performPrivilegedUpdate error = %v", err)
}
diff --git a/internal/agentupdate/privileged_update.go b/internal/agentupdate/privileged_update.go
index f1aee4f247..7d4b810779 100644
--- a/internal/agentupdate/privileged_update.go
+++ b/internal/agentupdate/privileged_update.go
@@ -25,8 +25,8 @@ const pendingPrivilegedUpdateFile = ".pulse-agent-update-pending.json"
type PrivilegedUpdate interface {
CreateQuarantinedArtifact() (artifactID string, file *os.File, cleanup func() error, err error)
WriteQuarantinedSignature(artifactID, signature string) error
- Stage(context.Context, string, string) (agenthelper.UpdateStageResult, error)
- Activate(context.Context, string, string) (agenthelper.UpdateResult, error)
+ Stage(context.Context, string, string, string) (agenthelper.UpdateStageResult, error)
+ Activate(context.Context, string, string, string) (agenthelper.UpdateResult, error)
Commit(context.Context, agenthelper.UpdateResult) (agenthelper.UpdateResult, error)
Rollback(context.Context, agenthelper.UpdateResult) (agenthelper.UpdateResult, error)
}
@@ -112,15 +112,15 @@ func (p *privilegeHelperUpdate) WriteQuarantinedSignature(artifactID, signature
return syncUpdateDirectory(filepath.Dir(path))
}
-func (p *privilegeHelperUpdate) Stage(ctx context.Context, artifactID, digest string) (agenthelper.UpdateStageResult, error) {
+func (p *privilegeHelperUpdate) Stage(ctx context.Context, artifactID, digest, version string) (agenthelper.UpdateStageResult, error) {
var result agenthelper.UpdateStageResult
- _, err := p.client.Call(ctx, agenthelper.OperationAgentUpdateStage, agenthelper.OperationVersion1, 30*time.Second, agenthelper.UpdateStageRequest{ArtifactID: artifactID, SHA256: digest}, &result)
+ _, err := p.client.Call(ctx, agenthelper.OperationAgentUpdateStage, agenthelper.OperationVersion1, 30*time.Second, agenthelper.UpdateStageRequest{ArtifactID: artifactID, SHA256: digest, Version: version}, &result)
return result, err
}
-func (p *privilegeHelperUpdate) Activate(ctx context.Context, artifactID, digest string) (agenthelper.UpdateResult, error) {
+func (p *privilegeHelperUpdate) Activate(ctx context.Context, artifactID, digest, version string) (agenthelper.UpdateResult, error) {
var result agenthelper.UpdateResult
- _, err := p.client.Call(ctx, agenthelper.OperationAgentUpdateActivate, agenthelper.OperationVersion1, 30*time.Second, agenthelper.UpdateActivateRequest{ArtifactID: artifactID, SHA256: digest}, &result)
+ _, err := p.client.Call(ctx, agenthelper.OperationAgentUpdateActivate, agenthelper.OperationVersion1, 30*time.Second, agenthelper.UpdateActivateRequest{ArtifactID: artifactID, SHA256: digest, Version: version}, &result)
return result, err
}
diff --git a/internal/agentupdate/privileged_update_test.go b/internal/agentupdate/privileged_update_test.go
index efd5731d1c..5fb03c27d9 100644
--- a/internal/agentupdate/privileged_update_test.go
+++ b/internal/agentupdate/privileged_update_test.go
@@ -42,12 +42,12 @@ func (f *fakePrivilegedUpdate) WriteQuarantinedSignature(_ string, signature str
return nil
}
-func (f *fakePrivilegedUpdate) Stage(_ context.Context, artifactID, digest string) (agenthelper.UpdateStageResult, error) {
+func (f *fakePrivilegedUpdate) Stage(_ context.Context, artifactID, digest, _ string) (agenthelper.UpdateStageResult, error) {
f.events = append(f.events, "stage")
return agenthelper.UpdateStageResult{Action: "staged", ArtifactID: artifactID, SHA256: digest, DurableAt: time.Now()}, nil
}
-func (f *fakePrivilegedUpdate) Activate(_ context.Context, _ string, digest string) (agenthelper.UpdateResult, error) {
+func (f *fakePrivilegedUpdate) Activate(_ context.Context, _ string, digest, _ string) (agenthelper.UpdateResult, error) {
f.events = append(f.events, "activate")
f.activation = agenthelper.UpdateResult{Action: "pending", ActivationID: "pulse-agent-0123456789abcdef0123456789abcdef:0123456789abcdef", ActiveSHA256: digest, RollbackSHA256: strings.Repeat("a", 64), RollbackDeadline: time.Now().Add(time.Minute)}
return f.activation, nil
@@ -96,7 +96,7 @@ func TestPrivilegedUpdateStagesActivatesAndRollsBackRestartFailure(t *testing.T)
return nil
}
- err := u.performPrivilegedUpdate(context.Background(), "/usr/local/bin/pulse-agent", bytes.NewReader(binary), int64(len(binary)), digest, "signed-update")
+ err := u.performPrivilegedUpdate(context.Background(), "/usr/local/bin/pulse-agent", bytes.NewReader(binary), int64(len(binary)), digest, "signed-update", "1.1.0")
if err == nil || !strings.Contains(err.Error(), "update rolled back") {
t.Fatalf("performPrivilegedUpdate error = %v", err)
}
@@ -118,7 +118,7 @@ func TestPrivilegedUpdateFailsClosedBeforeActivation(t *testing.T) {
u := New(Config{PrivilegedUpdate: helper, Disabled: true, StateDir: helper.root, CurrentVersion: "1.0.0"})
u.selfTestFn = func(context.Context, string) error { return nil }
- err := u.performPrivilegedUpdate(context.Background(), "/usr/local/bin/pulse-agent", bytes.NewReader(binary), int64(len(binary)), strings.Repeat("0", 64), "signed-update")
+ err := u.performPrivilegedUpdate(context.Background(), "/usr/local/bin/pulse-agent", bytes.NewReader(binary), int64(len(binary)), strings.Repeat("0", 64), "signed-update", "1.1.0")
if err == nil || !strings.Contains(err.Error(), "checksum mismatch") {
t.Fatalf("performPrivilegedUpdate error = %v", err)
}
diff --git a/internal/agentupdate/update.go b/internal/agentupdate/update.go
index fc2659fa64..dc301eec0c 100644
--- a/internal/agentupdate/update.go
+++ b/internal/agentupdate/update.go
@@ -942,7 +942,7 @@ func (u *Updater) performUpdateWithExecPathForVersion(ctx context.Context, execP
checksumHeader := strings.TrimSpace(resp.Header.Get(checksumSHA256Header))
signatureHeaderValue := strings.TrimSpace(resp.Header.Get(signatureHeader))
if u.cfg.PrivilegedUpdate != nil {
- return u.performPrivilegedUpdate(ctx, execPath, resp.Body, resp.ContentLength, checksumHeader, signatureHeaderValue)
+ return u.performPrivilegedUpdate(ctx, execPath, resp.Body, resp.ContentLength, checksumHeader, signatureHeaderValue, targetVersion)
}
// Resolve symlinks to get the real path for atomic rename
@@ -1075,7 +1075,7 @@ func (u *Updater) performUpdateWithExecPathForVersion(ctx context.Context, execP
return restartProcessFn(execPath)
}
-func (u *Updater) performPrivilegedUpdate(ctx context.Context, execPath string, body io.Reader, contentLength int64, checksumHeader, signature string) error {
+func (u *Updater) performPrivilegedUpdate(ctx context.Context, execPath string, body io.Reader, contentLength int64, checksumHeader, signature, targetVersion string) error {
if runtimeGOOS != goOSLinux {
return errors.New("typed privilege-helper updates are supported only on Linux")
}
@@ -1143,14 +1143,14 @@ func (u *Updater) performPrivilegedUpdate(ctx context.Context, execPath string,
if err := u.cfg.PrivilegedUpdate.WriteQuarantinedSignature(artifactID, signature); err != nil {
return err
}
- staged, err := u.cfg.PrivilegedUpdate.Stage(ctx, artifactID, digest)
+ staged, err := u.cfg.PrivilegedUpdate.Stage(ctx, artifactID, digest, targetVersion)
if err != nil {
return fmt.Errorf("stage signed update through typed helper: %w", err)
}
if staged.Action != "staged" || staged.ArtifactID != artifactID || !strings.EqualFold(staged.SHA256, digest) {
return errors.New("typed helper returned an invalid staging result")
}
- activation, err := u.cfg.PrivilegedUpdate.Activate(ctx, artifactID, digest)
+ activation, err := u.cfg.PrivilegedUpdate.Activate(ctx, artifactID, digest, targetVersion)
if err != nil {
return fmt.Errorf("activate signed update through typed helper: %w", err)
}
diff --git a/internal/api/agent_install_command_shared.go b/internal/api/agent_install_command_shared.go
index 9f7d68ced9..43faed3d1f 100644
--- a/internal/api/agent_install_command_shared.go
+++ b/internal/api/agent_install_command_shared.go
@@ -106,7 +106,6 @@ func containerRuntimeAgentScopes(enableHost bool) []string {
scopes = append(scopes,
config.ScopeAgentReport,
config.ScopeAgentConfigRead,
- config.ScopeAgentManage,
)
}
return scopes
diff --git a/internal/api/agent_install_command_shared_test.go b/internal/api/agent_install_command_shared_test.go
index be34766235..ef8db24130 100644
--- a/internal/api/agent_install_command_shared_test.go
+++ b/internal/api/agent_install_command_shared_test.go
@@ -235,7 +235,6 @@ func TestContainerRuntimeAgentScopesFollowHostMode(t *testing.T) {
config.ScopeDockerReport,
config.ScopeAgentReport,
config.ScopeAgentConfigRead,
- config.ScopeAgentManage,
}, dualMode)
require.Equal(t, []string{config.ScopeDockerReport}, containerRuntimeAgentScopes(false))
diff --git a/internal/api/agenttokens/install.go b/internal/api/agenttokens/install.go
index 0059c5ce71..753bc4c1fc 100644
--- a/internal/api/agenttokens/install.go
+++ b/internal/api/agenttokens/install.go
@@ -69,7 +69,6 @@ func ProxmoxScopes(enableCommands bool) []string {
scopes := []string{
config.ScopeAgentReport,
config.ScopeAgentConfigRead,
- config.ScopeAgentManage,
}
if enableCommands {
scopes = append(scopes, config.ScopeAgentExec)
@@ -81,7 +80,6 @@ func HostScopes(enableCommands bool) []string {
scopes := []string{
config.ScopeAgentReport,
config.ScopeAgentConfigRead,
- config.ScopeAgentManage,
config.ScopeDockerReport,
config.ScopeKubernetesReport,
}
diff --git a/internal/api/agenttokens/install_test.go b/internal/api/agenttokens/install_test.go
index bfc7a9b86a..a691ddc7f7 100644
--- a/internal/api/agenttokens/install_test.go
+++ b/internal/api/agenttokens/install_test.go
@@ -194,11 +194,17 @@ func TestProxmoxScopesRequireExplicitCommandAuthority(t *testing.T) {
if (&config.APITokenRecord{Scopes: monitoringScopes}).HasScope(config.ScopeAgentExec) {
t.Fatalf("monitoring-only Proxmox scopes include %s: %v", config.ScopeAgentExec, monitoringScopes)
}
+ if (&config.APITokenRecord{Scopes: monitoringScopes}).HasScope(config.ScopeAgentManage) {
+ t.Fatalf("monitoring-only Proxmox scopes include cross-host management: %v", monitoringScopes)
+ }
commandScopes := ProxmoxScopes(true)
if !(&config.APITokenRecord{Scopes: commandScopes}).HasScope(config.ScopeAgentExec) {
t.Fatalf("explicit command profile is missing %s: %v", config.ScopeAgentExec, commandScopes)
}
+ if (&config.APITokenRecord{Scopes: commandScopes}).HasScope(config.ScopeAgentManage) {
+ t.Fatalf("collector command profile includes cross-host management: %v", commandScopes)
+ }
}
func TestIssueAndPersistDefaultsToMonitoringOnlyScopes(t *testing.T) {
diff --git a/internal/api/collector_authority.go b/internal/api/collector_authority.go
new file mode 100644
index 0000000000..cfa0fcd48a
--- /dev/null
+++ b/internal/api/collector_authority.go
@@ -0,0 +1,135 @@
+package api
+
+import (
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rcourtman/pulse-go-rewrite/internal/api/agenttokens"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+const maxCollectorAuthorityRequestBytes int64 = 16 << 10
+
+type collectorAuthorityReductionRequest struct {
+ AgentID string `json:"agentId"`
+ Hostname string `json:"hostname"`
+}
+
+// handleReduceCollectorAuthority is an irreversible, self-service reduction.
+// A host credential may remove its own execution and management scopes during
+// safe-profile migration, but this route can never add a scope or target
+// another token.
+func (r *Router) handleReduceCollectorAuthority(w http.ResponseWriter, req *http.Request) {
+ if req.Method != http.MethodPost {
+ w.Header().Set("Allow", http.MethodPost)
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ caller := getAPITokenRecordFromRequest(req)
+ if caller == nil || !caller.HasScope(config.ScopeAgentReport) {
+ http.Error(w, "Agent bearer credential required", http.StatusForbidden)
+ return
+ }
+ decoder := json.NewDecoder(io.LimitReader(req.Body, maxCollectorAuthorityRequestBytes+1))
+ decoder.DisallowUnknownFields()
+ var payload collectorAuthorityReductionRequest
+ if err := decoder.Decode(&payload); err != nil {
+ http.Error(w, "Invalid request body", http.StatusBadRequest)
+ return
+ }
+ if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
+ http.Error(w, "Invalid request body", http.StatusBadRequest)
+ return
+ }
+ payload.AgentID = strings.TrimSpace(payload.AgentID)
+ payload.Hostname = strings.TrimSpace(payload.Hostname)
+ if payload.AgentID == "" || payload.Hostname == "" {
+ http.Error(w, "Canonical agent identity required", http.StatusBadRequest)
+ return
+ }
+ if r.persistence == nil {
+ http.Error(w, "Collector authority persistence is unavailable", http.StatusServiceUnavailable)
+ return
+ }
+
+ organizationID := strings.TrimSpace(GetOrgID(req.Context()))
+ config.Mu.Lock()
+ previous := make([]config.APITokenRecord, len(r.config.APITokens))
+ for previousIndex := range r.config.APITokens {
+ previous[previousIndex] = r.config.APITokens[previousIndex].Clone()
+ }
+ index := -1
+ var prior config.APITokenRecord
+ for candidateIndex := range r.config.APITokens {
+ candidate := &r.config.APITokens[candidateIndex]
+ if candidate.ID != caller.ID {
+ continue
+ }
+ orgs := candidate.GetBoundOrgs()
+ boundAgentID := strings.TrimSpace(candidate.Metadata["bound_agent_id"])
+ boundHostname := strings.TrimSpace(candidate.Metadata["bound_hostname"])
+ if len(orgs) != 1 || strings.TrimSpace(orgs[0]) != organizationID ||
+ boundAgentID == "" || boundAgentID != payload.AgentID ||
+ boundHostname == "" || !strings.EqualFold(boundHostname, payload.Hostname) {
+ config.Mu.Unlock()
+ http.Error(w, "Collector credential binding mismatch", http.StatusForbidden)
+ return
+ }
+ index = candidateIndex
+ prior = candidate.Clone()
+ break
+ }
+ if index < 0 {
+ config.Mu.Unlock()
+ http.Error(w, "Collector credential not found", http.StatusUnauthorized)
+ return
+ }
+ record := &r.config.APITokens[index]
+ nextScopes := make([]string, 0, len(record.Scopes))
+ for _, scope := range record.Scopes {
+ if scope == config.ScopeWildcard {
+ config.Mu.Unlock()
+ http.Error(w, "Wildcard credentials cannot be reduced through the collector route", http.StatusForbidden)
+ return
+ }
+ if scope != config.ScopeAgentExec && scope != config.ScopeAgentManage {
+ nextScopes = append(nextScopes, scope)
+ }
+ }
+ record.Scopes = nextScopes
+ if record.HasScope(config.ScopeAgentExec) || !record.HasScope(config.ScopeAgentReport) {
+ r.config.APITokens = previous
+ config.Mu.Unlock()
+ http.Error(w, "Collector credential scopes cannot be reduced safely", http.StatusForbidden)
+ return
+ }
+ if record.Metadata == nil {
+ record.Metadata = make(map[string]string)
+ }
+ record.Metadata[agenttokens.CredentialKindMetadataKey] = agenttokens.CredentialKindMonitoringCollector
+ record.Metadata[agenttokens.CommandPolicyIntentMetadataKey] = agenttokens.CommandPolicyIntentDisabled
+ if err := r.persistence.SaveAPITokens(r.config.APITokens); err != nil {
+ r.config.APITokens = previous
+ r.config.SortAPITokens()
+ config.Mu.Unlock()
+ http.Error(w, "Failed to persist collector authority reduction", http.StatusInternalServerError)
+ return
+ }
+ config.Mu.Unlock()
+
+ if r.agentExecServer != nil && prior.HasScope(config.ScopeAgentExec) {
+ r.agentExecServer.InvalidateAgentSession(agentexec.AgentAdmission{
+ OrganizationID: organizationID,
+ TokenID: prior.ID,
+ AgentID: payload.AgentID,
+ Hostname: payload.Hostname,
+ RuntimeRole: agentexec.RuntimeRoleLegacyFullTrust,
+ })
+ }
+ LogAuditEventForTenant(organizationID, "collector_authority_reduced", caller.Name, GetClientIP(req), req.URL.Path, true, "Removed execution and cross-host management scopes from collector credential")
+ w.WriteHeader(http.StatusNoContent)
+}
diff --git a/internal/api/collector_authority_test.go b/internal/api/collector_authority_test.go
new file mode 100644
index 0000000000..4c55e190ac
--- /dev/null
+++ b/internal/api/collector_authority_test.go
@@ -0,0 +1,129 @@
+package api
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/api/agenttokens"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+func TestReduceCollectorAuthorityRemovesExecutionScopeIrreversibly(t *testing.T) {
+ raw := "collector-authority-test.12345678"
+ record, err := config.NewAPITokenRecord(raw, "legacy collector", []string{
+ config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeAgentManage, config.ScopeAgentExec,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ record.OrgID = "org-a"
+ record.Metadata = map[string]string{
+ "bound_agent_id": "agent-a", "bound_hostname": "node.example",
+ agenttokens.RuntimeRoleMetadataKey: agenttokens.CredentialKindLegacyFullTrust,
+ }
+ cfg := &config.Config{APITokens: []config.APITokenRecord{*record}}
+ router := &Router{config: cfg, persistence: config.NewConfigPersistence(t.TempDir())}
+ body, _ := json.Marshal(collectorAuthorityReductionRequest{AgentID: "agent-a", Hostname: "node.example"})
+ req := httptest.NewRequest(http.MethodPost, "/api/agents/collector/reduce-authority", bytes.NewReader(body))
+ req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-a"))
+ attachAPITokenRecord(req, record)
+ response := httptest.NewRecorder()
+ router.handleReduceCollectorAuthority(response, req)
+ if response.Code != http.StatusNoContent {
+ t.Fatalf("status = %d, body=%s", response.Code, response.Body.String())
+ }
+ if len(cfg.APITokens) != 1 || cfg.APITokens[0].HasScope(config.ScopeAgentExec) {
+ t.Fatalf("reduced scopes = %v", cfg.APITokens)
+ }
+ if cfg.APITokens[0].HasScope(config.ScopeAgentManage) {
+ t.Fatalf("reduced collector retained cross-host management scope: %v", cfg.APITokens[0].Scopes)
+ }
+ if got := cfg.APITokens[0].Metadata[agenttokens.RuntimeRoleMetadataKey]; got != agenttokens.CredentialKindMonitoringCollector {
+ t.Fatalf("runtime role = %q", got)
+ }
+ if got := cfg.APITokens[0].Metadata[agenttokens.CommandPolicyIntentMetadataKey]; got != agenttokens.CommandPolicyIntentDisabled {
+ t.Fatalf("command policy = %q", got)
+ }
+}
+
+func TestReduceCollectorAuthorityRejectsCrossHostBinding(t *testing.T) {
+ record := &config.APITokenRecord{ID: "token-a", OrgID: "org-a", Scopes: []string{config.ScopeAgentReport, config.ScopeAgentExec}, Metadata: map[string]string{
+ "bound_agent_id": "agent-a", "bound_hostname": "node.example",
+ }}
+ cfg := &config.Config{APITokens: []config.APITokenRecord{*record}}
+ router := &Router{config: cfg, persistence: config.NewConfigPersistence(t.TempDir())}
+ body, _ := json.Marshal(collectorAuthorityReductionRequest{AgentID: "agent-b", Hostname: "other.example"})
+ req := httptest.NewRequest(http.MethodPost, "/api/agents/collector/reduce-authority", bytes.NewReader(body))
+ req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-a"))
+ attachAPITokenRecord(req, record)
+ response := httptest.NewRecorder()
+ router.handleReduceCollectorAuthority(response, req)
+ if response.Code != http.StatusForbidden || !cfg.APITokens[0].HasScope(config.ScopeAgentExec) {
+ t.Fatalf("status=%d scopes=%v", response.Code, cfg.APITokens[0].Scopes)
+ }
+}
+
+func TestReduceCollectorAuthorityRejectsUnboundCredential(t *testing.T) {
+ record := &config.APITokenRecord{ID: "token-a", OrgID: "org-a", Scopes: []string{config.ScopeAgentReport, config.ScopeAgentExec}}
+ cfg := &config.Config{APITokens: []config.APITokenRecord{*record}}
+ router := &Router{config: cfg, persistence: config.NewConfigPersistence(t.TempDir())}
+ body, _ := json.Marshal(collectorAuthorityReductionRequest{AgentID: "agent-a", Hostname: "node.example"})
+ req := httptest.NewRequest(http.MethodPost, "/api/agents/collector/reduce-authority", bytes.NewReader(body))
+ req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-a"))
+ attachAPITokenRecord(req, record)
+ response := httptest.NewRecorder()
+ router.handleReduceCollectorAuthority(response, req)
+ if response.Code != http.StatusForbidden || !cfg.APITokens[0].HasScope(config.ScopeAgentExec) {
+ t.Fatalf("status=%d scopes=%v", response.Code, cfg.APITokens[0].Scopes)
+ }
+}
+
+func TestReduceCollectorAuthorityRollsBackMemoryWhenPersistenceFails(t *testing.T) {
+ raw := "collector-authority-persistence.12345678"
+ record, err := config.NewAPITokenRecord(raw, "legacy collector", []string{config.ScopeAgentReport, config.ScopeAgentExec})
+ if err != nil {
+ t.Fatal(err)
+ }
+ record.OrgID = "org-a"
+ record.Metadata = map[string]string{
+ "bound_agent_id": "agent-a", "bound_hostname": "node.example",
+ agenttokens.RuntimeRoleMetadataKey: agenttokens.CredentialKindLegacyFullTrust,
+ }
+ cfg := &config.Config{APITokens: []config.APITokenRecord{*record}}
+ persistence := config.NewConfigPersistence(t.TempDir())
+ persistence.SetFileSystem(actionRunnerFailingPersistenceFS{})
+ router := &Router{config: cfg, persistence: persistence}
+ body, _ := json.Marshal(collectorAuthorityReductionRequest{AgentID: "agent-a", Hostname: "node.example"})
+ req := httptest.NewRequest(http.MethodPost, "/api/agents/collector/reduce-authority", bytes.NewReader(body))
+ req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-a"))
+ attachAPITokenRecord(req, record)
+ response := httptest.NewRecorder()
+ router.handleReduceCollectorAuthority(response, req)
+ if response.Code != http.StatusInternalServerError {
+ t.Fatalf("status = %d, body=%s", response.Code, response.Body.String())
+ }
+ if !cfg.APITokens[0].HasScope(config.ScopeAgentExec) || cfg.APITokens[0].Metadata[agenttokens.RuntimeRoleMetadataKey] != agenttokens.CredentialKindLegacyFullTrust {
+ t.Fatalf("failed persistence changed live authority: %#v", cfg.APITokens[0])
+ }
+}
+
+func TestReduceCollectorAuthorityRejectsWildcardCredential(t *testing.T) {
+ record := &config.APITokenRecord{ID: "wildcard", OrgID: "org-a", Scopes: []string{config.ScopeWildcard}, Metadata: map[string]string{
+ "bound_agent_id": "agent-a", "bound_hostname": "node.example",
+ }}
+ cfg := &config.Config{APITokens: []config.APITokenRecord{*record}}
+ router := &Router{config: cfg, persistence: config.NewConfigPersistence(t.TempDir())}
+ body, _ := json.Marshal(collectorAuthorityReductionRequest{AgentID: "agent-a", Hostname: "node.example"})
+ req := httptest.NewRequest(http.MethodPost, "/api/agents/collector/reduce-authority", bytes.NewReader(body))
+ req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-a"))
+ attachAPITokenRecord(req, record)
+ response := httptest.NewRecorder()
+ router.handleReduceCollectorAuthority(response, req)
+ if response.Code != http.StatusForbidden || !cfg.APITokens[0].HasScope(config.ScopeAgentExec) {
+ t.Fatalf("wildcard reduction status=%d scopes=%v", response.Code, cfg.APITokens[0].Scopes)
+ }
+}
diff --git a/internal/api/deploy_handlers.go b/internal/api/deploy_handlers.go
index e39dea15fc..5004e93c50 100644
--- a/internal/api/deploy_handlers.go
+++ b/internal/api/deploy_handlers.go
@@ -877,7 +877,7 @@ func (h *DeployHandlers) HandleEnroll(w http.ResponseWriter, r *http.Request) {
return
}
runtimeScopes := []string{
- config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeAgentManage,
+ config.ScopeAgentReport, config.ScopeAgentConfigRead,
config.ScopeDockerReport, config.ScopeKubernetesReport,
}
if req.CommandsEnabled {
diff --git a/internal/api/deploy_handlers_test.go b/internal/api/deploy_handlers_test.go
index 78e888cd4b..a79461f8a6 100644
--- a/internal/api/deploy_handlers_test.go
+++ b/internal/api/deploy_handlers_test.go
@@ -1014,8 +1014,8 @@ func TestHandleEnroll_CommandsEnabledAddsAgentExecScope(t *testing.T) {
if !hasExec {
t.Errorf("expected runtime token to have %s scope, got scopes: %v", config.ScopeAgentExec, found.Scopes)
}
- if !hasManage {
- t.Errorf("expected runtime token to have %s scope, got scopes: %v", config.ScopeAgentManage, found.Scopes)
+ if hasManage {
+ t.Errorf("runtime collector token must not have %s scope, got scopes: %v", config.ScopeAgentManage, found.Scopes)
}
if got := found.Metadata["bound_agent_id"]; got != "agent-cmd-host" {
t.Errorf("runtime token bound_agent_id = %q, want %q", got, "agent-cmd-host")
@@ -1058,22 +1058,22 @@ func TestHandleEnroll_CommandsDisabledNoAgentExecScope(t *testing.T) {
t.Fatal("runtime token not found in config")
}
- // Should have report, config:read, and manage — but NOT agent:exec.
+ // Should have report and config:read — but no management or execution scope.
for _, s := range found.Scopes {
if s == config.ScopeAgentExec {
t.Errorf("runtime token should NOT have %s scope when commandsEnabled is false", config.ScopeAgentExec)
}
}
- // Should still have manage.
+ // Collector credentials must not manage other agent configurations.
hasManage := false
for _, s := range found.Scopes {
if s == config.ScopeAgentManage {
hasManage = true
}
}
- if !hasManage {
- t.Errorf("expected runtime token to have %s scope", config.ScopeAgentManage)
+ if hasManage {
+ t.Errorf("runtime collector token must not have %s scope", config.ScopeAgentManage)
}
}
diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.go
index da5c878ed6..76b8e4ead1 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -380,6 +380,7 @@ var allRouteAllowlist = []string{
"/api/agents/docker/report",
"/api/agents/kubernetes/report",
"/api/agents/action-runner/credential",
+ "/api/agents/collector/reduce-authority",
"/api/agents/agent/report",
"/api/agents/host/report",
"/api/agents/agent/lookup",
diff --git a/internal/api/router_low_coverage_additional_test.go b/internal/api/router_low_coverage_additional_test.go
index 4b4def0615..a264481de7 100644
--- a/internal/api/router_low_coverage_additional_test.go
+++ b/internal/api/router_low_coverage_additional_test.go
@@ -193,11 +193,14 @@ func TestHandleDiagnosticsDockerPrepareToken_Success(t *testing.T) {
t.Fatalf("expected API token to be recorded")
}
token := router.config.APITokens[0]
- for _, scope := range []string{config.ScopeDockerReport, config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeAgentManage} {
+ for _, scope := range []string{config.ScopeDockerReport, config.ScopeAgentReport, config.ScopeAgentConfigRead} {
if !token.HasScope(scope) {
t.Fatalf("expected default migration token to include %q, got %#v", scope, token.Scopes)
}
}
+ if token.HasScope(config.ScopeAgentManage) {
+ t.Fatalf("default migration token retained cross-host management scope: %#v", token.Scopes)
+ }
}
func TestHandleDiagnosticsDockerPrepareToken_RollsBackWhenPersistenceFails(t *testing.T) {
diff --git a/internal/api/router_routes_registration.go b/internal/api/router_routes_registration.go
index 96a9f28c91..e474a537ac 100644
--- a/internal/api/router_routes_registration.go
+++ b/internal/api/router_routes_registration.go
@@ -56,6 +56,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {
r.mux.HandleFunc("/api/agents/kubernetes/report", RequireAuth(r.config, RequireScope(config.ScopeKubernetesReport, r.kubernetesAgentHandlers.HandleReport)))
r.mux.HandleFunc("/api/agents/agent/report", RequireAuth(r.config, RequireScope(config.ScopeAgentReport, r.unifiedAgentHandlers.HandleReport)))
r.mux.HandleFunc("/api/agents/action-runner/credential", RequireAuth(r.config, actionRunnerCredentialRoute(r.config, r.handleIssueActionRunnerCredential, r.handleSelfRevokeActionRunnerCredential)))
+ r.mux.HandleFunc("/api/agents/collector/reduce-authority", RequireAuth(r.config, RequireScope(config.ScopeAgentReport, r.handleReduceCollectorAuthority)))
r.mux.HandleFunc("/api/agents/host/report", wrapLegacyHostAlias("/api/agents/host/report", RequireAuth(r.config, RequireScope(config.ScopeAgentReport, r.unifiedAgentHandlers.HandleReport))))
r.mux.HandleFunc("/api/agents/agent/lookup", RequireAuth(r.config, RequireScope(config.ScopeAgentReport, r.unifiedAgentHandlers.HandleLookup)))
r.mux.HandleFunc("/api/agents/host/lookup", wrapLegacyHostAlias("/api/agents/host/lookup", RequireAuth(r.config, RequireScope(config.ScopeAgentReport, r.unifiedAgentHandlers.HandleLookup))))
diff --git a/internal/config/api_tokens.go b/internal/config/api_tokens.go
index a8fbd23fed..27dc454330 100644
--- a/internal/config/api_tokens.go
+++ b/internal/config/api_tokens.go
@@ -111,6 +111,7 @@ func (r *APITokenRecord) IsExpired() bool {
// Clone returns a copy of the record with duplicated pointer fields.
func (r *APITokenRecord) Clone() APITokenRecord {
clone := *r
+ clone.Scopes = append([]string(nil), r.Scopes...)
if r.LastUsedAt != nil {
t := *r.LastUsedAt
clone.LastUsedAt = &t
@@ -126,6 +127,12 @@ func (r *APITokenRecord) Clone() APITokenRecord {
clone.OrgIDs = make([]string, len(r.OrgIDs))
copy(clone.OrgIDs, r.OrgIDs)
}
+ if r.Metadata != nil {
+ clone.Metadata = make(map[string]string, len(r.Metadata))
+ for key, value := range r.Metadata {
+ clone.Metadata[key] = value
+ }
+ }
clone.ensureID()
return clone
diff --git a/scripts/install.sh b/scripts/install.sh
index fe2345be4d..4b8de971cc 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -1008,6 +1008,45 @@ revoke_action_runner_credential() {
return 1
}
+reduce_safe_profile_collector_authority() {
+ local active_token_file="${STATE_DIR%/}/runtime.token"
+ local active_token=""
+ local curl_config=""
+ local payload=""
+ local -a reduce_args
+
+ if [[ ! -s "$active_token_file" || -L "$active_token_file" ]]; then
+ active_token_file=""
+ active_token="$PULSE_TOKEN"
+ else
+ active_token=$(head -1 "$active_token_file" 2>/dev/null || true)
+ fi
+ [[ -n "$active_token" && "$active_token" != *$'\r'* && "$active_token" != *$'\n'* ]] || return 1
+ [[ -n "$AGENT_ID" && ${#AGENT_ID} -le 256 && "$AGENT_ID" =~ ^[A-Za-z0-9._:-]+$ ]] || return 1
+ [[ -n "$HOSTNAME_OVERRIDE" && ${#HOSTNAME_OVERRIDE} -le 253 && "$HOSTNAME_OVERRIDE" =~ ^[A-Za-z0-9._:-]+$ ]] || return 1
+ [[ "$PULSE_URL" =~ ^https?://[^[:space:]]+$ ]] || return 1
+
+ curl_config=$(mktemp)
+ chmod 0600 "$curl_config"
+ printf 'header = "Authorization: Bearer %s"\nheader = "Content-Type: application/json"\n' \
+ "$active_token" > "$curl_config"
+ active_token=""
+ payload="{\"agentId\":\"${AGENT_ID}\",\"hostname\":\"${HOSTNAME_OVERRIDE}\"}"
+ reduce_args=(--config "$curl_config" -fsS --connect-timeout 5 --max-time 15 -X POST --data-binary "$payload")
+ if [[ "$INSECURE" == "true" ]]; then
+ reduce_args+=(-k)
+ elif [[ -n "$CURL_CA_BUNDLE" ]]; then
+ reduce_args+=(--cacert "$CURL_CA_BUNDLE")
+ fi
+ if curl "${reduce_args[@]}" "${PULSE_URL%/}/api/agents/collector/reduce-authority" >/dev/null 2>&1; then
+ rm -f "$curl_config"
+ log_info "Durably removed execution and cross-host management scopes from the collector credential before migration."
+ return 0
+ fi
+ rm -f "$curl_config"
+ return 1
+}
+
teardown_action_runner_service() {
local had_runner_config="false"
if [[ -f "$ACTION_RUNNER_ENV_FILE" || -f "$ACTION_RUNNER_TOKEN_FILE" ]]; then
@@ -1277,7 +1316,7 @@ RestartSec=5s
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
-ProtectSystem=strict
+ProtectSystem=false
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
@@ -1647,34 +1686,19 @@ safe_profile_manifest_value() {
safe_profile_snapshot_state_metadata() {
local metadata_file="${SAFE_PROFILE_TRANSACTION_DIR}/state-metadata.bin"
- local path=""
- local relative_path=""
- local entry_type="file"
local uid="" gid="" mode=""
[[ -d "$STATE_DIR" && ! -L "$STATE_DIR" ]] ||
fail "Refusing unsafe safe-profile state directory: ${STATE_DIR}" "$EXIT_GENERAL"
: > "$metadata_file"
chmod 0600 "$metadata_file"
- while IFS= read -r -d '' path; do
- if [[ "$path" == "$STATE_DIR" ]]; then
- relative_path="."
- else
- relative_path="${path#${STATE_DIR%/}/}"
- fi
- entry_type="file"
- [[ -d "$path" && ! -L "$path" ]] && entry_type="directory"
- [[ -L "$path" ]] && entry_type="symlink"
- uid=$(stat -c '%u' "$path") || return 1
- gid=$(stat -c '%g' "$path") || return 1
- mode=$(stat -c '%a' "$path") || return 1
- printf '%s\0%s\0%s\0%s\0%s\0' \
- "$relative_path" \
- "$uid" \
- "$gid" \
- "$mode" \
- "$entry_type" >> "$metadata_file"
- done < <(find "$STATE_DIR" -xdev -print0)
+ # Only the state root is installer-owned metadata. Descendants become
+ # collector-writable during the safe profile and therefore must never be
+ # replayed later as root-owned pathname operations.
+ uid=$(stat -c '%u' "$STATE_DIR") || return 1
+ gid=$(stat -c '%g' "$STATE_DIR") || return 1
+ mode=$(stat -c '%a' "$STATE_DIR") || return 1
+ printf '.\0%s\0%s\0%s\0directory\0' "$uid" "$gid" "$mode" > "$metadata_file"
}
safe_profile_restore_state_metadata() {
@@ -1689,22 +1713,15 @@ safe_profile_restore_state_metadata() {
IFS= read -r -d '' gid &&
IFS= read -r -d '' mode &&
IFS= read -r -d '' entry_type; do
- if [[ "$relative_path" == "." ]]; then
- destination="$snapshot_state_dir"
- else
- [[ -n "$relative_path" && "$relative_path" != /* &&
- "/${relative_path}/" != *"/../"* ]] || return 1
- destination="${snapshot_state_dir%/}/${relative_path}"
- fi
- # Runtime-owned state such as SQLite WAL/SHM files can legitimately
- # disappear while the collector is stopped. Restore the identity of
- # every surviving pre-migration entry without turning a vanished
- # transient file into a rollback failure.
- [[ -e "$destination" || -L "$destination" ]] || continue
- chown -h "${uid}:${gid}" "$destination" || return 1
- if [[ "$entry_type" != "symlink" ]]; then
- chmod "$mode" "$destination" || return 1
- fi
+ # Format-v2 snapshots created before the hardened rollback recorded the
+ # complete mutable tree. Ignore those descendant records: replaying
+ # collector-controlled pathnames as root is unsafe. The state root
+ # cannot be replaced by the service account because its parent is root.
+ [[ "$relative_path" == "." ]] || continue
+ destination="$snapshot_state_dir"
+ [[ -d "$destination" && ! -L "$destination" && "$entry_type" == "directory" ]] || return 1
+ chown "${uid}:${gid}" "$destination" || return 1
+ chmod "$mode" "$destination" || return 1
done < "$metadata_file"
}
@@ -1797,6 +1814,27 @@ safe_profile_restore_entry() {
fi
}
+safe_profile_remove_collector_command_authority() {
+ local unit_path="$1"
+ local rewritten=""
+
+ [[ -f "$unit_path" && ! -L "$unit_path" ]] || return 1
+ rewritten=$(mktemp)
+ chmod 0600 "$rewritten"
+ if ! sed -E 's/(^|[[:space:]])--enable-commands([[:space:]]|$)/\1\2/g' "$unit_path" > "$rewritten"; then
+ rm -f "$rewritten"
+ return 1
+ fi
+ # Preserve the restored unit's root-controlled inode metadata while making
+ # the irreversible server-side scope reduction explicit in local config.
+ if ! cat "$rewritten" > "$unit_path"; then
+ rm -f "$rewritten"
+ return 1
+ fi
+ rm -f "$rewritten"
+ ! grep -Eq -- '(^|[[:space:]])--enable-commands([[:space:]]|$)' "$unit_path"
+}
+
safe_profile_restore_transaction() {
local transaction_dir="$1"
local reason="${2:-explicit}"
@@ -1824,6 +1862,10 @@ safe_profile_restore_transaction() {
systemctl stop "${PRIVILEGED_HELPER_NAME}.service" 2>/dev/null || true
safe_profile_restore_entry "$transaction_dir" collector-binary "${INSTALL_DIR}/${BINARY_NAME}" COLLECTOR_BINARY
safe_profile_restore_entry "$transaction_dir" collector-unit "$SAFE_PROFILE_COLLECTOR_UNIT" COLLECTOR_UNIT
+ # The server-side execution-scope reduction deliberately survives both
+ # explicit and automatic local rollback. Never recreate a command-capable
+ # collector configuration around that monitoring-only credential.
+ safe_profile_remove_collector_command_authority "$SAFE_PROFILE_COLLECTOR_UNIT" || return 1
safe_profile_restore_entry "$transaction_dir" helper-binary "$PRIVILEGED_HELPER_BINARY_PATH" HELPER_BINARY
safe_profile_restore_entry "$transaction_dir" helper-service-unit "$PRIVILEGED_HELPER_SERVICE_UNIT" HELPER_SERVICE_UNIT
safe_profile_restore_entry "$transaction_dir" helper-socket-unit "$PRIVILEGED_HELPER_SOCKET_UNIT" HELPER_SOCKET_UNIT
@@ -4769,6 +4811,8 @@ if [[ "$SAFE_PROFILE_ACTION" == "apply" ]]; then
safe_profile_platform_supported ||
fail "Safe-profile migration is supported only on standard Linux systemd hosts; no broader-privilege fallback was applied" "$EXIT_MISSING_ARGS"
safe_profile_begin_transaction
+ reduce_safe_profile_collector_authority ||
+ fail "Safe-profile migration could not durably remove command and cross-host management authority from the existing collector credential; no privilege change was retained" "$EXIT_AUTH_REJECTED"
fi
# Create the dedicated service account for the least-privilege profile and
diff --git a/scripts/installtests/install_sh_test.go b/scripts/installtests/install_sh_test.go
index 167184f5d9..243bd1ac70 100644
--- a/scripts/installtests/install_sh_test.go
+++ b/scripts/installtests/install_sh_test.go
@@ -5887,6 +5887,53 @@ printf 'revoked\n'
}
}
+func TestInstallSHSafeProfileDurablyReducesCollectorAuthority(t *testing.T) {
+ const token = "collector-secret-that-must-not-appear-in-output"
+ var gotAuthorization string
+ var gotMethod string
+ var gotBody map[string]string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotAuthorization = r.Header.Get("Authorization")
+ gotMethod = r.Method
+ if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil {
+ t.Errorf("decode authority reduction body: %v", err)
+ http.Error(w, "bad request", http.StatusBadRequest)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ defer server.Close()
+
+ stateDir := t.TempDir()
+ mustWrite(t, filepath.Join(stateDir, "runtime.token"), token+"\n")
+ script := `
+set -euo pipefail
+STATE_DIR="` + stateDir + `"
+PULSE_TOKEN=""
+AGENT_ID="agent-secure-runtime"
+HOSTNAME_OVERRIDE="secure-runtime.lab"
+PULSE_URL="` + server.URL + `"
+INSECURE="false"
+CURL_CA_BUNDLE=""
+log_info() { printf '%s\n' "$*"; }
+` + extractInstallShellFunction(t, "reduce_safe_profile_collector_authority") + `
+reduce_safe_profile_collector_authority
+`
+ out, err := exec.Command("bash", "-c", script).CombinedOutput()
+ if err != nil {
+ t.Fatalf("collector authority reduction: %v\n%s", err, out)
+ }
+ if strings.Contains(string(out), token) {
+ t.Fatalf("collector credential leaked in output: %s", out)
+ }
+ if gotMethod != http.MethodPost || gotAuthorization != "Bearer "+token {
+ t.Fatalf("authority reduction transport: method=%q authorization=%q", gotMethod, gotAuthorization)
+ }
+ if gotBody["agentId"] != "agent-secure-runtime" || gotBody["hostname"] != "secure-runtime.lab" {
+ t.Fatalf("authority reduction body = %#v", gotBody)
+ }
+}
+
func TestInstallSHRendersHardenedActionRunnerUnit(t *testing.T) {
root := t.TempDir()
unitPath := filepath.Join(root, "pulse-agent-runner.service")
@@ -5912,7 +5959,7 @@ func TestInstallSHRendersHardenedActionRunnerUnit(t *testing.T) {
"Group=root",
"NoNewPrivileges=true",
"ProtectHome=true",
- "ProtectSystem=strict",
+ "ProtectSystem=false",
"ProtectKernelTunables=true",
"ProtectKernelModules=true",
"ProtectControlGroups=true",
@@ -5926,6 +5973,9 @@ func TestInstallSHRendersHardenedActionRunnerUnit(t *testing.T) {
if strings.Contains(unit, "PrivateNetwork=true") {
t.Fatalf("networked action runner cannot use the helper's private-network sandbox:\n%s", unit)
}
+ if strings.Contains(unit, "ProtectSystem=strict") {
+ t.Fatalf("host-mutating action runner cannot make the host filesystem read-only:\n%s", unit)
+ }
}
func TestInstallSHTypedPrivilegedHelperProtectsCredentialsAfterStateChown(t *testing.T) {
diff --git a/scripts/installtests/safe_profile_migration_test.go b/scripts/installtests/safe_profile_migration_test.go
index 97f1770656..a0f72bbe39 100644
--- a/scripts/installtests/safe_profile_migration_test.go
+++ b/scripts/installtests/safe_profile_migration_test.go
@@ -31,6 +31,7 @@ func safeProfileTransactionFunctions(t *testing.T) string {
extractInstallShellFunction(t, "safe_profile_restore_state_metadata") + "\n" +
extractInstallShellFunction(t, "safe_profile_begin_transaction") + "\n" +
extractInstallShellFunction(t, "safe_profile_restore_entry") + "\n" +
+ extractInstallShellFunction(t, "safe_profile_remove_collector_command_authority") + "\n" +
extractInstallShellFunction(t, "safe_profile_restore_transaction") + "\n" +
extractInstallShellFunction(t, "safe_profile_commit_transaction")
}
@@ -131,12 +132,17 @@ rm -f "$STATE_DIR/proxmox-pve-registration-blocked" "$STATE_DIR/proxmox-pbs-regi
printf 'changed-agent-id\n' > "$STATE_DIR/agent-id"
printf 'changed-connection\n' > "$STATE_DIR/connection.env"
chmod 0777 "$STATE_DIR" "$STATE_DIR/cache" "$STATE_DIR/cache/sample"
+printf 'outside-state\n' > "$EXPECTED_DIR/outside-target"
+chmod 0600 "$EXPECTED_DIR/outside-target"
+rm -f "$STATE_DIR/cache/sample"
+ln -s "$EXPECTED_DIR/outside-target" "$STATE_DIR/cache/sample"
mkdir -p "$PRIVILEGED_HELPER_CREDENTIAL_DIR"
printf 'moved-monitoring-token\n' > "$PRIVILEGED_HELPER_CREDENTIAL_DIR/token"
printf 'runner-still-independent\n' > "$ACTION_RUNNER_SENTINEL"
safe_profile_restore_transaction "$transaction" automatic-failure
cmp "$INSTALL_DIR/$BINARY_NAME" "$EXPECTED_DIR/collector-binary"
-cmp "$SAFE_PROFILE_COLLECTOR_UNIT" "$EXPECTED_DIR/collector-unit"
+grep -q '^User=root$' "$SAFE_PROFILE_COLLECTOR_UNIT"
+! grep -Eq -- '(^|[[:space:]])--enable-commands([[:space:]]|$)' "$SAFE_PROFILE_COLLECTOR_UNIT"
cmp "$STATE_DIR/token" "$EXPECTED_DIR/state-token"
cmp "$STATE_DIR/runtime.token" "$EXPECTED_DIR/runtime-token"
cmp "$STATE_DIR/agent-id" "$EXPECTED_DIR/agent-id"
@@ -148,8 +154,9 @@ grep -q '^legacy-pve-blocked$' "$STATE_DIR/proxmox-pve-registration-blocked"
grep -q '^legacy-pbs-blocked$' "$STATE_DIR/proxmox-pbs-registration-blocked"
grep -q '^pve,pbs$' "$STATE_DIR/proxmox-detected-types"
test "$(stat -c '%a' "$STATE_DIR")" = 750
-test "$(stat -c '%a' "$STATE_DIR/cache")" = 710
-test "$(stat -c '%a' "$STATE_DIR/cache/sample")" = 640
+test "$(stat -c '%a' "$STATE_DIR/cache")" = 777
+test -L "$STATE_DIR/cache/sample"
+test "$(stat -c '%a' "$EXPECTED_DIR/outside-target")" = 600
test ! -e "$STATE_DIR/cache/runtime.db-wal"
test ! -e "$PRIVILEGED_HELPER_BINARY_PATH"
test ! -e "$PRIVILEGED_HELPER_SERVICE_UNIT"
diff --git a/scripts/installtests/secure_runtime_systemd_lab_test.go b/scripts/installtests/secure_runtime_systemd_lab_test.go
index 9442b1bc7b..88b030cec0 100644
--- a/scripts/installtests/secure_runtime_systemd_lab_test.go
+++ b/scripts/installtests/secure_runtime_systemd_lab_test.go
@@ -42,6 +42,7 @@ import (
"errors"
"fmt"
"io"
+ "io/fs"
"net"
"net/http"
"net/http/httptest"
@@ -103,21 +104,22 @@ type secureRuntimeLabReport struct {
}
type secureRuntimeLabFixture struct {
- mu sync.Mutex
- collector []byte
- helper []byte
- runner []byte
- serverVersion string
- reports []secureRuntimeLabReport
- lastSeen time.Time
- freezeLastSeen bool
- authFailures int
- requestFailures []string
- actionServer *agentexec.Server
- actionSecret string
- actionBindingID string
- actionRevoked bool
- actionRevokes int
+ mu sync.Mutex
+ collector []byte
+ helper []byte
+ runner []byte
+ serverVersion string
+ reports []secureRuntimeLabReport
+ lastSeen time.Time
+ freezeLastSeen bool
+ authFailures int
+ requestFailures []string
+ actionServer *agentexec.Server
+ actionSecret string
+ actionBindingID string
+ actionRevoked bool
+ actionRevokes int
+ authorityReductions int
}
func newSecureRuntimeLabFixture(collector, helper, runner []byte, version string) *secureRuntimeLabFixture {
@@ -168,6 +170,12 @@ func (f *secureRuntimeLabFixture) actionSnapshot() (agentexec.AgentAdmission, bo
return f.actionAdmissionLocked(), f.actionRevoked, f.actionRevokes
}
+func (f *secureRuntimeLabFixture) authorityReductionCount() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.authorityReductions
+}
+
func (f *secureRuntimeLabFixture) setCollector(artifact []byte) {
f.mu.Lock()
defer f.mu.Unlock()
@@ -209,6 +217,8 @@ func (f *secureRuntimeLabFixture) ServeHTTP(w http.ResponseWriter, r *http.Reque
f.actionServer.HandleWebSocket(w, r)
case r.URL.Path == "/api/agents/action-runner/credential":
f.handleActionRunnerSelfRevoke(w, r)
+ case r.URL.Path == "/api/agents/collector/reduce-authority":
+ f.handleCollectorAuthorityReduction(w, r)
case r.URL.Path == "/api/health":
writeSecureRuntimeJSON(w, http.StatusOK, map[string]any{"status": "ok"})
case r.URL.Path == "/api/agents/agent/report":
@@ -236,6 +246,32 @@ func (f *secureRuntimeLabFixture) ServeHTTP(w http.ResponseWriter, r *http.Reque
}
}
+func (f *secureRuntimeLabFixture) handleCollectorAuthorityReduction(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ var request struct {
+ AgentID string `json:"agentId"`
+ Hostname string `json:"hostname"`
+ }
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&request); err != nil {
+ http.Error(w, "invalid request", http.StatusBadRequest)
+ return
+ }
+ valid := strings.TrimSpace(r.Header.Get("Authorization")) == "Bearer "+secureRuntimeLabToken &&
+ strings.TrimSpace(request.AgentID) == secureRuntimeLabAgentID &&
+ strings.EqualFold(strings.TrimSpace(request.Hostname), secureRuntimeLabHostname)
+ if !valid {
+ http.Error(w, "forbidden", http.StatusForbidden)
+ return
+ }
+ f.mu.Lock()
+ f.authorityReductions++
+ f.mu.Unlock()
+ w.WriteHeader(http.StatusNoContent)
+}
+
func (f *secureRuntimeLabFixture) authorized(r *http.Request) bool {
bearer := r.Header.Get("Authorization")
valid := r.Header.Get("X-API-Token") == secureRuntimeLabToken &&
@@ -454,6 +490,43 @@ func secureRuntimeStableSnapshot(t *testing.T) secureRuntimeStableIdentity {
return result
}
+func secureRuntimeSeedAPTPackageCache(t *testing.T) (string, string) {
+ t.Helper()
+ const cacheDir = "/var/cache/apt/archives"
+ path := filepath.Join(cacheDir, "pulse-secure-runtime-qualification.deb")
+ content := bytes.Repeat([]byte("pulse-secure-runtime\n"), 4096)
+ if err := os.WriteFile(path, content, 0o600); err != nil {
+ t.Fatalf("seed disposable apt package cache: %v", err)
+ }
+ t.Cleanup(func() { _ = os.Remove(path) })
+ hasher := sha256.New()
+ err := filepath.WalkDir(cacheDir, func(entryPath string, entry fs.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ return walkErr
+ }
+ if entry.IsDir() || !strings.HasSuffix(strings.ToLower(entry.Name()), ".deb") {
+ return nil
+ }
+ info, infoErr := entry.Info()
+ if infoErr != nil {
+ return infoErr
+ }
+ if !info.Mode().IsRegular() {
+ return nil
+ }
+ relative, relativeErr := filepath.Rel(cacheDir, entryPath)
+ if relativeErr != nil {
+ return relativeErr
+ }
+ _, _ = fmt.Fprintf(hasher, "%s\x00%d\x00%d\n", filepath.ToSlash(relative), info.Size(), info.ModTime().UnixNano())
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("fingerprint disposable apt package cache: %v", err)
+ }
+ return path, "sha256:" + hex.EncodeToString(hasher.Sum(nil))
+}
+
type secureRuntimeScenarioResult struct {
Name string `json:"name"`
Passed bool `json:"passed"`
@@ -461,30 +534,34 @@ type secureRuntimeScenarioResult struct {
}
type secureRuntimeLabReceipt struct {
- SchemaVersion int `json:"schema_version"`
- CompletedAt string `json:"completed_at"`
- SourceHashes map[string]string `json:"source_hashes"`
- ArtifactHashes map[string]string `json:"artifact_hashes"`
- OSRelease string `json:"os_release"`
- Kernel string `json:"kernel"`
- SystemdVersion string `json:"systemd_version"`
- Architecture string `json:"architecture"`
- CollectorServiceUser string `json:"collector_service_user"`
- CollectorProcessUID int `json:"collector_process_uid"`
- CollectorAuthority string `json:"collector_authority"`
- AmbientCapabilitiesNone bool `json:"ambient_capabilities_none"`
- HelperProtocolHealthy bool `json:"helper_protocol_healthy"`
- StateIdentityPreserved bool `json:"state_identity_preserved"`
- DockerDegraded bool `json:"docker_degraded"`
- ActionRunnerQualified bool `json:"action_runner_qualified"`
- ActionReceiptKind string `json:"action_receipt_kind,omitempty"`
- CredentialRotated bool `json:"credential_rotated"`
- SelfRevokeObserved bool `json:"self_revoke_observed"`
- CollectorContinuity bool `json:"collector_continuity"`
- ReportCount int `json:"report_count"`
- FirstReportAt string `json:"first_report_at"`
- LastReportAt string `json:"last_report_at"`
- Scenarios []secureRuntimeScenarioResult `json:"scenarios"`
+ SchemaVersion int `json:"schema_version"`
+ CompletedAt string `json:"completed_at"`
+ SourceHashes map[string]string `json:"source_hashes"`
+ ArtifactHashes map[string]string `json:"artifact_hashes"`
+ ArtifactVersions map[string]string `json:"artifact_versions"`
+ DisposableVMGuardHash string `json:"disposable_vm_guard_sha256"`
+ OSRelease string `json:"os_release"`
+ Kernel string `json:"kernel"`
+ SystemdVersion string `json:"systemd_version"`
+ Architecture string `json:"architecture"`
+ CollectorServiceUser string `json:"collector_service_user"`
+ CollectorProcessUID int `json:"collector_process_uid"`
+ CollectorAuthority string `json:"collector_authority"`
+ AmbientCapabilitiesNone bool `json:"ambient_capabilities_none"`
+ HelperProtocolHealthy bool `json:"helper_protocol_healthy"`
+ StateIdentityPreserved bool `json:"state_identity_preserved"`
+ DockerDegraded bool `json:"docker_degraded"`
+ ActionRunnerQualified bool `json:"action_runner_qualified"`
+ ActionMutationVerified bool `json:"action_mutation_verified"`
+ CollectorAuthorityReductionRequestObserved bool `json:"collector_authority_reduction_request_observed"`
+ ActionReceiptKind string `json:"action_receipt_kind,omitempty"`
+ CredentialRotated bool `json:"credential_rotated"`
+ SelfRevokeObserved bool `json:"self_revoke_observed"`
+ CollectorContinuity bool `json:"collector_continuity"`
+ ReportCount int `json:"report_count"`
+ FirstReportAt string `json:"first_report_at"`
+ LastReportAt string `json:"last_report_at"`
+ Scenarios []secureRuntimeScenarioResult `json:"scenarios"`
}
func TestSecureRuntimeSystemdLab(t *testing.T) {
@@ -514,13 +591,36 @@ func TestSecureRuntimeSystemdLab(t *testing.T) {
defer server.Close()
receipt := secureRuntimeLabReceipt{
- SchemaVersion: 2,
+ SchemaVersion: 3,
SourceHashes: map[string]string{
"scripts/install.sh": secureRuntimeHash(installer),
"scripts/installtests/secure_runtime_systemd_lab_test.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("scripts", "installtests", "secure_runtime_systemd_lab_test.go"))),
+ "scripts/release_control/secure_runtime_attestation.py": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("scripts", "release_control", "secure_runtime_attestation.py"))),
+ "internal/agenthelper/update_activation.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "agenthelper", "update_activation.go"))),
+ "internal/agenthelper/server.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "agenthelper", "server.go"))),
+ "internal/agentexec/server.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "agentexec", "server.go"))),
+ "internal/agentexec/types.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "agentexec", "types.go"))),
+ "internal/agentexec/verifier_postconditions.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "agentexec", "verifier_postconditions.go"))),
+ "internal/api/collector_authority.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "api", "collector_authority.go"))),
+ "internal/api/action_runner_credentials.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "api", "action_runner_credentials.go"))),
+ "internal/api/agenttokens/install.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "api", "agenttokens", "install.go"))),
+ "internal/api/agent_exec_token_binding.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "api", "agent_exec_token_binding.go"))),
+ "internal/actionrunner/runner.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "actionrunner", "runner.go"))),
+ "internal/actionrunner/types.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "actionrunner", "types.go"))),
+ "internal/actionrunner/transport.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "actionrunner", "transport.go"))),
+ "internal/hostagent/storage_cleanup.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "hostagent", "storage_cleanup.go"))),
+ "internal/operationreceipt/store.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "operationreceipt", "store.go"))),
+ "internal/operationreceipt/types.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "operationreceipt", "types.go"))),
+ "internal/agentupdate/update.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "agentupdate", "update.go"))),
+ "internal/agentupdate/privileged_update.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("internal", "agentupdate", "privileged_update.go"))),
+ "cmd/pulse-agent/main.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("cmd", "pulse-agent", "main.go"))),
+ "cmd/pulse-agent-helper/main.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("cmd", "pulse-agent-helper", "main.go"))),
+ "cmd/pulse-agent-runner/main.go": secureRuntimeHash(secureRuntimeReadFile(t, repoFile("cmd", "pulse-agent-runner", "main.go"))),
},
- ArtifactHashes: map[string]string{"collector_v1": secureRuntimeHash(collectorV1), "collector_v2": secureRuntimeHash(collectorV2), "helper": secureRuntimeHash(helper), "runner": secureRuntimeHash(runner)},
- Architecture: runtime.GOARCH,
+ ArtifactHashes: map[string]string{"collector_v1": secureRuntimeHash(collectorV1), "collector_v2": secureRuntimeHash(collectorV2), "helper": secureRuntimeHash(helper), "runner": secureRuntimeHash(runner)},
+ ArtifactVersions: map[string]string{"collector_v1": collectorV1Version, "collector_v2": collectorV2Version},
+ DisposableVMGuardHash: secureRuntimeHash([]byte(secureRuntimeLabMarkerValue + "\n")),
+ Architecture: runtime.GOARCH,
}
receipt.OSRelease = strings.TrimSpace(string(secureRuntimeReadFile(t, "/etc/os-release")))
receipt.Kernel = secureRuntimeCommand(t, 10*time.Second, "uname", "-srvmo")
@@ -598,6 +698,9 @@ func TestSecureRuntimeSystemdLab(t *testing.T) {
}
secureRuntimeAssertSafeProfile(t)
secureRuntimeAssertHelperProtocol(t)
+ if fixture.authorityReductionCount() < 1 {
+ t.Fatal("safe apply did not durably reduce the collector credential authority")
+ }
dockerDegraded := dockerInitiallyEnabled && !secureRuntimeCollectorHasArgument("--enable-docker")
if dockerInitiallyEnabled && !secureRuntimeCollectorOwnedRootlessAvailable(t) {
if !dockerDegraded || !strings.Contains(applyOutput, "disabled rootful Docker monitoring") {
@@ -609,9 +712,9 @@ func TestSecureRuntimeSystemdLab(t *testing.T) {
reportsBeforeRollback, _, _, _ := fixture.snapshot()
secureRuntimeRunInstaller(t, installerPath, server.URL, "--safe-profile-rollback")
secureRuntimeWaitForReports(t, fixture, len(reportsBeforeRollback)+1, 45*time.Second)
- secureRuntimeAssertRootCommandProfile(t)
- secureRuntimeWaitForStableIdentity(t, legacyBaseline, 10*time.Second, "explicit rollback")
- pass("explicit_safe_profile_rollback", "legacy binary, unit, authority, and service identity restored")
+ secureRuntimeAssertRootMonitoringProfile(t)
+ secureRuntimeWaitForStableIdentity(t, secureRuntimeWithoutCollectorUnit(legacyBaseline), 10*time.Second, "explicit rollback")
+ pass("explicit_safe_profile_rollback", "legacy binary and service identity restored without resurrecting collector command authority")
automaticRollbackBaseline := secureRuntimeStableSnapshot(t)
fixture.setFrozen(true)
@@ -620,19 +723,19 @@ func TestSecureRuntimeSystemdLab(t *testing.T) {
if failedErr == nil || !strings.Contains(failedOutput, "restoring the previous profile") {
t.Fatalf("stale lastSeen safe apply unexpectedly succeeded: err=%v\n%s", failedErr, failedOutput)
}
- secureRuntimeWaitForStableIdentity(t, automaticRollbackBaseline, 10*time.Second, "automatic failure rollback")
- secureRuntimeAssertRootCommandProfile(t)
- pass("automatic_failure_rollback", "frozen lastSeen prevented commit and restored binary/unit/state identity")
+ secureRuntimeWaitForStableIdentity(t, secureRuntimeWithoutCollectorUnit(automaticRollbackBaseline), 10*time.Second, "automatic failure rollback")
+ secureRuntimeAssertRootMonitoringProfile(t)
+ pass("automatic_failure_rollback", "frozen lastSeen prevented commit and restored binary/state identity without command authority")
fixture.setCollector(collectorV2)
reportsBeforeUpdate, _, _, _ := fixture.snapshot()
secureRuntimeRunInstaller(t, installerPath, server.URL, "--update")
secureRuntimeWaitForReports(t, fixture, len(reportsBeforeUpdate)+1, 45*time.Second)
- secureRuntimeAssertRootCommandProfile(t)
+ secureRuntimeAssertRootMonitoringProfile(t)
if got := secureRuntimeHash(secureRuntimeReadFile(t, "/usr/local/bin/pulse-agent")); got != secureRuntimeHash(collectorV2) {
t.Fatalf("ordinary update collector hash = %s, want v2 hash", got)
}
- pass("ordinary_update_non_migration", "binary updated while root command-capable profile remained unchanged")
+ pass("ordinary_update_non_migration", "binary updated while the downgraded root monitoring profile remained unchanged")
fixture.setServerVersion(collectorV2Version)
reportsBeforeFinalApply, preFinalLastSeen, _, _ := fixture.snapshot()
@@ -661,10 +764,11 @@ func TestSecureRuntimeSystemdLab(t *testing.T) {
actionContext, cancelAction := context.WithTimeout(agentexec.WithOrganizationID(context.Background(), secureRuntimeLabOrgID), 30*time.Second)
defer cancelAction()
+ cachePath, cacheFingerprint := secureRuntimeSeedAPTPackageCache(t)
cleanupRequest := agentexec.HostStorageCleanupPayload{
RequestID: "secure-runtime.receipt.1", ActionID: "secure-runtime-receipt",
Operation: agentexec.HostStorageCleanupOperationPackageCache,
- ExpectedFingerprint: "sha256:" + strings.Repeat("f", 64), Timeout: 15,
+ ExpectedFingerprint: cacheFingerprint, Timeout: 15,
}
if err := agentexec.BindHostStorageCleanupPayload(&cleanupRequest); err != nil {
t.Fatalf("bind typed receipt qualification request: %v", err)
@@ -673,20 +777,36 @@ func TestSecureRuntimeSystemdLab(t *testing.T) {
if err != nil {
t.Fatalf("execute typed receipt qualification request: %v", err)
}
- if cleanupResult == nil || cleanupResult.MutationStarted {
- t.Fatalf("typed receipt qualification unexpectedly mutated the host: %+v", cleanupResult)
+ if cleanupResult == nil || !cleanupResult.Success || !cleanupResult.MutationStarted ||
+ cleanupResult.Verification != agentexec.HostStorageCleanupVerificationVerified || cleanupResult.ReclaimedBytes <= 0 {
+ t.Fatalf("typed receipt qualification did not complete a verified host mutation: %+v", cleanupResult)
+ }
+ if _, err := os.Stat(cachePath); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("typed package-cache cleanup did not remove seeded archive: %v", err)
}
receiptIdentity := agentexec.HostStorageCleanupOperationIdentity(secureRuntimeLabAgentID, cleanupRequest)
query, err := fixture.actionServer.QueryAgentOperation(actionContext, secureRuntimeLabAgentID, receiptIdentity)
if err != nil || query.Status != operationreceipt.QueryFoundTerminal || query.Record == nil || query.Record.ResultKind != agentexec.HostStorageCleanupReceiptKind {
t.Fatalf("durable typed receipt query = %+v, err=%v", query, err)
}
+ refusalRequest := agentexec.HostStorageCleanupPayload{
+ RequestID: "secure-runtime.receipt.2", ActionID: "secure-runtime-refusal",
+ Operation: agentexec.HostStorageCleanupOperationPackageCache,
+ ExpectedFingerprint: "sha256:" + strings.Repeat("f", 64), Timeout: 15,
+ }
+ if err := agentexec.BindHostStorageCleanupPayload(&refusalRequest); err != nil {
+ t.Fatalf("bind typed refusal qualification request: %v", err)
+ }
+ refusalResult, err := fixture.actionServer.ExecuteHostStorageCleanup(actionContext, secureRuntimeLabAgentID, refusalRequest)
+ if err != nil || refusalResult == nil || refusalResult.MutationStarted {
+ t.Fatalf("typed refusal request was not rejected before mutation: result=%+v err=%v", refusalResult, err)
+ }
if _, err := fixture.actionServer.ExecuteCommand(actionContext, secureRuntimeLabAgentID, agentexec.ExecuteCommandPayload{
RequestID: "secure-runtime-shell-denial", Command: "true", TargetType: "agent", Trusted: true,
}); err == nil || !strings.Contains(err.Error(), "typed action-runner") {
t.Fatalf("action runner did not reject generic command dispatch: %v", err)
}
- pass("typed_action_receipt", "closed storage-cleanup request refused before mutation and replayed as a durable terminal receipt; generic command dispatch denied")
+ pass("typed_action_receipt", "verified apt cache mutation and durable terminal receipt; stale fingerprint refused before mutation; generic command dispatch denied")
currentAdmission, _, _ := fixture.actionSnapshot()
wrongAdmission := currentAdmission
@@ -750,6 +870,8 @@ func TestSecureRuntimeSystemdLab(t *testing.T) {
receipt.StateIdentityPreserved = true
receipt.DockerDegraded = dockerDegraded
receipt.ActionRunnerQualified = true
+ receipt.ActionMutationVerified = true
+ receipt.CollectorAuthorityReductionRequestObserved = fixture.authorityReductionCount() > 0
receipt.ActionReceiptKind = agentexec.HostStorageCleanupReceiptKind
receipt.CredentialRotated = true
receipt.SelfRevokeObserved = true
@@ -1067,6 +1189,20 @@ func secureRuntimeAssertRootCommandProfile(t *testing.T) {
secureRuntimeCommand(t, 10*time.Second, "systemctl", "is-active", "pulse-agent.service")
}
+func secureRuntimeAssertRootMonitoringProfile(t *testing.T) {
+ t.Helper()
+ if user := secureRuntimeSystemdProperty(t, "User"); user != "root" && user != "" {
+ t.Fatalf("rolled-back collector systemd User = %q, want root", user)
+ }
+ if secureRuntimeCollectorHasArgument("--enable-commands") {
+ t.Fatal("rolled-back collector resurrected --enable-commands after irreversible credential downgrade")
+ }
+ if uid := secureRuntimeCollectorProcessUID(t); uid != 0 {
+ t.Fatalf("rolled-back collector process UID = %d, want 0", uid)
+ }
+ secureRuntimeCommand(t, 10*time.Second, "systemctl", "is-active", "pulse-agent.service")
+}
+
func secureRuntimeAssertSafeProfile(t *testing.T) {
t.Helper()
if user := secureRuntimeSystemdProperty(t, "User"); user != "pulse-agent" {
@@ -1196,12 +1332,25 @@ func secureRuntimeIdentitiesEqual(left, right secureRuntimeStableIdentity) bool
return true
}
+func secureRuntimeWithoutCollectorUnit(identity secureRuntimeStableIdentity) secureRuntimeStableIdentity {
+ result := make(secureRuntimeStableIdentity, len(identity)-1)
+ for path, value := range identity {
+ if path != "/etc/systemd/system/pulse-agent.service" {
+ result[path] = value
+ }
+ }
+ return result
+}
+
func secureRuntimeWaitForStableIdentity(t *testing.T, want secureRuntimeStableIdentity, timeout time.Duration, scenario string) {
t.Helper()
deadline := time.Now().Add(timeout)
var got secureRuntimeStableIdentity
for time.Now().Before(deadline) {
got = secureRuntimeStableSnapshot(t)
+ if _, compareUnit := want["/etc/systemd/system/pulse-agent.service"]; !compareUnit {
+ delete(got, "/etc/systemd/system/pulse-agent.service")
+ }
if secureRuntimeIdentitiesEqual(want, got) {
return
}
diff --git a/scripts/release_control/secure_runtime_attestation.py b/scripts/release_control/secure_runtime_attestation.py
index c6ef6d8cb1..cccafab6dc 100644
--- a/scripts/release_control/secure_runtime_attestation.py
+++ b/scripts/release_control/secure_runtime_attestation.py
@@ -36,6 +36,40 @@ ARTIFACT_ARGUMENTS = {
"helper": "helper",
"runner": "runner",
}
+EXPECTED_ARTIFACT_PACKAGES = {
+ "collector_v1": "github.com/rcourtman/pulse-go-rewrite/cmd/pulse-agent",
+ "collector_v2": "github.com/rcourtman/pulse-go-rewrite/cmd/pulse-agent",
+ "helper": "github.com/rcourtman/pulse-go-rewrite/cmd/pulse-agent-helper",
+ "runner": "github.com/rcourtman/pulse-go-rewrite/cmd/pulse-agent-runner",
+}
+REQUIRED_SOURCE_PATHS = {
+ "scripts/install.sh",
+ "scripts/installtests/secure_runtime_systemd_lab_test.go",
+ "scripts/release_control/secure_runtime_attestation.py",
+ "internal/agenthelper/update_activation.go",
+ "internal/agenthelper/server.go",
+ "internal/agentexec/server.go",
+ "internal/agentexec/types.go",
+ "internal/agentexec/verifier_postconditions.go",
+ "internal/api/collector_authority.go",
+ "internal/api/action_runner_credentials.go",
+ "internal/api/agenttokens/install.go",
+ "internal/api/agent_exec_token_binding.go",
+ "internal/actionrunner/runner.go",
+ "internal/actionrunner/types.go",
+ "internal/actionrunner/transport.go",
+ "internal/hostagent/storage_cleanup.go",
+ "internal/operationreceipt/store.go",
+ "internal/operationreceipt/types.go",
+ "internal/agentupdate/update.go",
+ "internal/agentupdate/privileged_update.go",
+ "cmd/pulse-agent/main.go",
+ "cmd/pulse-agent-helper/main.go",
+ "cmd/pulse-agent-runner/main.go",
+}
+DISPOSABLE_VM_GUARD_SHA256 = hashlib.sha256(
+ b"PULSE_SECURE_RUNTIME_SYSTEMD_LAB=disposable-v1\n"
+).hexdigest()
FORBIDDEN_RECEIPT_KEYS = {
"api_key",
"authorization",
@@ -143,8 +177,8 @@ def load_receipt(path: Path) -> tuple[dict[str, Any], bytes]:
receipt = json.loads(raw)
except (OSError, json.JSONDecodeError) as exc:
raise AttestationError(f"unable to load receipt {path}: {exc}") from exc
- if not isinstance(receipt, dict) or receipt.get("schema_version") != 2:
- raise AttestationError("receipt must be a schema_version 2 object")
+ if not isinstance(receipt, dict) or receipt.get("schema_version") != 3:
+ raise AttestationError("receipt must be a schema_version 3 object")
reject_sensitive_keys(receipt)
return receipt, raw
@@ -164,10 +198,38 @@ def verify_scenarios(receipt: dict[str, Any]) -> None:
raise AttestationError("receipt scenario set or order does not match the canonical 12-scenario qualification")
+def verify_runtime_claims(receipt: dict[str, Any]) -> None:
+ required_true = (
+ "ambient_capabilities_none",
+ "helper_protocol_healthy",
+ "state_identity_preserved",
+ "action_runner_qualified",
+ "action_mutation_verified",
+ "collector_authority_reduction_request_observed",
+ "credential_rotated",
+ "self_revoke_observed",
+ "collector_continuity",
+ )
+ for key in required_true:
+ if receipt.get(key) is not True:
+ raise AttestationError(f"receipt does not prove required runtime claim {key}")
+ if receipt.get("collector_service_user") != "pulse-agent":
+ raise AttestationError("receipt collector service user is not pulse-agent")
+ if not isinstance(receipt.get("collector_process_uid"), int) or receipt["collector_process_uid"] <= 0:
+ raise AttestationError("receipt collector process UID is not non-root")
+ if receipt.get("collector_authority") != "monitoring-only":
+ raise AttestationError("receipt collector authority is not monitoring-only")
+ if receipt.get("disposable_vm_guard_sha256") != DISPOSABLE_VM_GUARD_SHA256:
+ raise AttestationError("receipt disposable-VM guard claim is missing or invalid")
+
+
def verify_source_hashes(checkout: Path, commit: str, receipt: dict[str, Any]) -> dict[str, str]:
source_hashes = receipt.get("source_hashes")
if not isinstance(source_hashes, dict) or not source_hashes:
raise AttestationError("receipt source_hashes must be a non-empty object")
+ missing = REQUIRED_SOURCE_PATHS.difference(source_hashes)
+ if missing:
+ raise AttestationError(f"receipt source_hashes omit required boundary sources: {sorted(missing)}")
verified: dict[str, str] = {}
for source_path in sorted(source_hashes):
digest = source_hashes[source_path]
@@ -200,6 +262,51 @@ def verify_artifacts(receipt: dict[str, Any], artifacts: dict[str, Path]) -> dic
return verified
+def verify_artifact_build_identity(
+ receipt: dict[str, Any], artifacts: dict[str, Path], qualified_commit: str
+) -> dict[str, dict[str, str]]:
+ versions = receipt.get("artifact_versions")
+ if not isinstance(versions, dict) or set(versions) != {"collector_v1", "collector_v2"}:
+ raise AttestationError("receipt artifact_versions must identify both collector artifacts")
+ if any(not isinstance(value, str) or not value.strip() for value in versions.values()):
+ raise AttestationError("receipt collector artifact version is invalid")
+ if versions["collector_v1"] == versions["collector_v2"]:
+ raise AttestationError("collector qualification artifacts must have distinct versions")
+
+ verified: dict[str, dict[str, str]] = {}
+ for name, artifact in artifacts.items():
+ try:
+ result = subprocess.run(
+ ["go", "version", "-m", str(artifact)],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ except (OSError, subprocess.CalledProcessError) as exc:
+ raise AttestationError(f"unable to inspect Go build identity for {name}") from exc
+ package = ""
+ settings: dict[str, str] = {}
+ for line in result.stdout.splitlines():
+ fields = line.strip().split("\t")
+ if len(fields) >= 2 and fields[0] == "path":
+ package = fields[1]
+ elif len(fields) >= 2 and fields[0] == "build" and "=" in fields[1]:
+ key, value = fields[1].split("=", 1)
+ settings[key] = value
+ if package != EXPECTED_ARTIFACT_PACKAGES[name]:
+ raise AttestationError(f"artifact {name} is not the expected Go command package")
+ if settings.get("vcs") != "git" or settings.get("vcs.revision") != qualified_commit:
+ raise AttestationError(f"artifact {name} is not build-stamped from the qualified commit")
+ if settings.get("vcs.modified") != "false":
+ raise AttestationError(f"artifact {name} was built from a modified checkout")
+ verified[name] = {
+ "package": package,
+ "vcs_revision": settings["vcs.revision"],
+ "vcs_modified": settings["vcs.modified"],
+ }
+ return verified
+
+
def create_attestation(
*,
checkout: Path,
@@ -224,8 +331,13 @@ def create_attestation(
receipt, receipt_bytes = load_receipt(receipt_path)
verify_scenarios(receipt)
+ verify_runtime_claims(receipt)
source_hashes = verify_source_hashes(checkout, qualified_commit, receipt)
+ attestation_tool_hash = sha256_file(Path(__file__))
+ if source_hashes["scripts/release_control/secure_runtime_attestation.py"] != attestation_tool_hash:
+ raise AttestationError("executing attestation tool does not match the qualified commit")
artifact_hashes = verify_artifacts(receipt, artifacts)
+ artifact_build_identity = verify_artifact_build_identity(receipt, artifacts, qualified_commit)
record_path = PurePosixPath(receipt_record_path)
if (
record_path.is_absolute()
@@ -240,11 +352,11 @@ def create_attestation(
):
raise AttestationError("elapsed seconds must be positive")
- classification = "exact-release-candidate" if release_candidate_ref else "exact-committed-main"
+ classification = "release-candidate-artifact-bound-self-attested-systemd" if release_candidate_ref else "committed-main-artifact-bound-self-attested-systemd"
return {
- "schema_version": 2,
+ "schema_version": 3,
"attestation_tool": "scripts/release_control/secure_runtime_attestation.py",
- "attestation_tool_sha256": sha256_file(Path(__file__)),
+ "attestation_tool_sha256": attestation_tool_hash,
"proof_classification": classification,
"qualified_commit": qualified_commit,
"qualified_ref_at_run": release_candidate_ref or qualified_commit,
@@ -253,13 +365,15 @@ def create_attestation(
"qualified_commit_reachable_from_main": True,
"build_checkout": "detached-worktree",
"build_checkout_clean_except_lab_artifacts": True,
- "disposable_vm_guard_verified": True,
+ "disposable_vm_guard_receipt_claim_validated": True,
+ "execution_receipt_authentication": "none-secret-free-self-attestation",
"receipt_path": receipt_record_path,
"receipt_sha256": sha256_bytes(receipt_bytes),
"source_hashes_match_commit": True,
"source_hashes": source_hashes,
"artifact_hashes_match_receipt": True,
"artifact_hashes": artifact_hashes,
+ "artifact_build_identity": artifact_build_identity,
"host": {
"os": _os_name(receipt.get("os_release")),
"kernel": receipt.get("kernel"),
diff --git a/scripts/release_control/secure_runtime_attestation_test.py b/scripts/release_control/secure_runtime_attestation_test.py
index e7bf598b80..d891d12429 100644
--- a/scripts/release_control/secure_runtime_attestation_test.py
+++ b/scripts/release_control/secure_runtime_attestation_test.py
@@ -4,6 +4,7 @@ import subprocess
import sys
import tempfile
import unittest
+from unittest import mock
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
@@ -11,9 +12,13 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
from secure_runtime_attestation import (
ARTIFACT_ARGUMENTS,
AttestationError,
+ DISPOSABLE_VM_GUARD_SHA256,
+ EXPECTED_ARTIFACT_PACKAGES,
REQUIRED_SCENARIOS,
+ REQUIRED_SOURCE_PATHS,
create_attestation,
sha256_bytes,
+ verify_artifact_build_identity,
)
from repo_file_io import strip_local_git_env
@@ -28,10 +33,11 @@ class SecureRuntimeAttestationTest(unittest.TestCase):
self.git("config", "user.name", "Pulse Test")
self.git("config", "user.email", "[email protected]")
self.source_hashes = {}
- for relative, value in {
- "scripts/install.sh": b"installer\n",
- "scripts/installtests/secure_runtime_systemd_lab_test.go": b"lab\n",
- }.items():
+ for relative in sorted(REQUIRED_SOURCE_PATHS):
+ if relative == "scripts/release_control/secure_runtime_attestation.py":
+ value = Path(__file__).with_name("secure_runtime_attestation.py").read_bytes()
+ else:
+ value = f"fixture:{relative}\n".encode()
path = self.repo / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(value)
@@ -54,13 +60,27 @@ class SecureRuntimeAttestationTest(unittest.TestCase):
self.receipt.write_text(
json.dumps(
{
- "schema_version": 2,
+ "schema_version": 3,
"source_hashes": self.source_hashes,
"artifact_hashes": artifact_hashes,
+ "artifact_versions": {"collector_v1": "1.0.0", "collector_v2": "1.1.0"},
+ "disposable_vm_guard_sha256": DISPOSABLE_VM_GUARD_SHA256,
"os_release": 'PRETTY_NAME="Fixture Linux"',
"kernel": "Linux fixture",
"systemd_version": "systemd 255",
"architecture": "arm64",
+ "collector_service_user": "pulse-agent",
+ "collector_process_uid": 1000,
+ "collector_authority": "monitoring-only",
+ "ambient_capabilities_none": True,
+ "helper_protocol_healthy": True,
+ "state_identity_preserved": True,
+ "action_runner_qualified": True,
+ "action_mutation_verified": True,
+ "collector_authority_reduction_request_observed": True,
+ "credential_rotated": True,
+ "self_revoke_observed": True,
+ "collector_continuity": True,
"scenarios": [
{"name": name, "passed": True, "detail": "passed"}
for name in REQUIRED_SCENARIOS
@@ -71,8 +91,17 @@ class SecureRuntimeAttestationTest(unittest.TestCase):
+ "\n",
encoding="utf-8",
)
+ self.build_identity = mock.patch(
+ "secure_runtime_attestation.verify_artifact_build_identity",
+ return_value={
+ name: {"package": package, "vcs_revision": self.commit, "vcs_modified": "false"}
+ for name, package in EXPECTED_ARTIFACT_PACKAGES.items()
+ },
+ )
+ self.build_identity.start()
def tearDown(self) -> None:
+ self.build_identity.stop()
self.temporary.cleanup()
def git(self, *args: str) -> str:
@@ -100,7 +129,7 @@ class SecureRuntimeAttestationTest(unittest.TestCase):
def test_accepts_exact_committed_main_evidence(self) -> None:
result = self.attest()
- self.assertEqual(result["proof_classification"], "exact-committed-main")
+ self.assertEqual(result["proof_classification"], "committed-main-artifact-bound-self-attested-systemd")
self.assertEqual(result["qualified_commit"], self.commit)
self.assertTrue(result["source_hashes_match_commit"])
self.assertTrue(result["artifact_hashes_match_receipt"])
@@ -110,7 +139,7 @@ class SecureRuntimeAttestationTest(unittest.TestCase):
def test_accepts_exact_release_candidate_ref(self) -> None:
self.git("tag", "v9.0.0-rc.1", self.commit)
result = self.attest(release_candidate_ref="v9.0.0-rc.1")
- self.assertEqual(result["proof_classification"], "exact-release-candidate")
+ self.assertEqual(result["proof_classification"], "release-candidate-artifact-bound-self-attested-systemd")
self.assertNotIn("exact-release-candidate", result["residual_proof"])
def test_rejects_attached_checkout(self) -> None:
@@ -140,6 +169,30 @@ class SecureRuntimeAttestationTest(unittest.TestCase):
with self.assertRaisesRegex(AttestationError, "artifact digest mismatch"):
self.attest()
+ def test_rejects_wrong_go_command_package(self) -> None:
+ output = (
+ "fixture: go1.25\n"
+ "\tpath\tgithub.com/rcourtman/pulse-go-rewrite/cmd/not-pulse-agent\n"
+ f"\tbuild\tvcs=git\n\tbuild\tvcs.revision={self.commit}\n\tbuild\tvcs.modified=false\n"
+ )
+ with mock.patch("secure_runtime_attestation.subprocess.run", return_value=subprocess.CompletedProcess([], 0, output, "")):
+ with self.assertRaisesRegex(AttestationError, "expected Go command package"):
+ verify_artifact_build_identity(self.receipt_dict(), self.artifacts, self.commit)
+
+ def test_rejects_modified_go_build_identity(self) -> None:
+ def inspect(command, **_kwargs):
+ name = Path(command[-1]).name
+ output = (
+ "fixture: go1.25\n"
+ f"\tpath\t{EXPECTED_ARTIFACT_PACKAGES[name]}\n"
+ f"\tbuild\tvcs=git\n\tbuild\tvcs.revision={self.commit}\n\tbuild\tvcs.modified=true\n"
+ )
+ return subprocess.CompletedProcess(command, 0, output, "")
+
+ with mock.patch("secure_runtime_attestation.subprocess.run", side_effect=inspect):
+ with self.assertRaisesRegex(AttestationError, "modified checkout"):
+ verify_artifact_build_identity(self.receipt_dict(), self.artifacts, self.commit)
+
def test_rejects_failed_scenario(self) -> None:
receipt = json.loads(self.receipt.read_text(encoding="utf-8"))
receipt["scenarios"][-1]["passed"] = False
@@ -147,6 +200,20 @@ class SecureRuntimeAttestationTest(unittest.TestCase):
with self.assertRaisesRegex(AttestationError, "did not pass"):
self.attest()
+ def test_rejects_receipt_without_verified_mutation(self) -> None:
+ receipt = json.loads(self.receipt.read_text(encoding="utf-8"))
+ receipt["action_mutation_verified"] = False
+ self.receipt.write_text(json.dumps(receipt), encoding="utf-8")
+ with self.assertRaisesRegex(AttestationError, "action_mutation_verified"):
+ self.attest()
+
+ def test_rejects_legacy_receipt_schema(self) -> None:
+ receipt = json.loads(self.receipt.read_text(encoding="utf-8"))
+ receipt["schema_version"] = 2
+ self.receipt.write_text(json.dumps(receipt), encoding="utf-8")
+ with self.assertRaisesRegex(AttestationError, "schema_version 3"):
+ self.attest()
+
def test_rejects_missing_scenario(self) -> None:
receipt = json.loads(self.receipt.read_text(encoding="utf-8"))
receipt["scenarios"].pop()
@@ -190,6 +257,9 @@ class SecureRuntimeAttestationTest(unittest.TestCase):
with self.assertRaisesRegex(AttestationError, "must be positive"):
self.attest(elapsed_seconds=float("nan"))
+ def receipt_dict(self):
+ return json.loads(self.receipt.read_text(encoding="utf-8"))
+
if __name__ == "__main__":
unittest.main()