Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Add rootless runtime qualification harness
rcourtman11aadbfb1b3a
diff --git a/.gitignore b/.gitignoreindex bc5d7772dc..75864cd199 100644--- a/.gitignore+++ b/.gitignore@@ -271,6 +271,9 @@ scripts/release_control/*!scripts/release_control/secure_runtime_attestation_v6_test.py!scripts/release_control/secure_runtime_attestation_v7.py!scripts/release_control/secure_runtime_attestation_v7_test.py+!scripts/release_control/secure_runtime_rootless_attestation_v1.py+!scripts/release_control/secure_runtime_rootless_attestation_v1_test.py+!scripts/release_control/secure_runtime_rootless_source_manifest_v1.json!scripts/release_control/secure_runtime_source_manifest_v6.json!scripts/release_control/secure_runtime_source_manifest_v7.json!scripts/release_control/staged_commit_shape_guard.pydiff --git a/docs/AGENT_SECURITY.md b/docs/AGENT_SECURITY.mdindex b19040f88b..0fecba77e0 100644--- a/docs/AGENT_SECURITY.md+++ b/docs/AGENT_SECURITY.md@@ -257,7 +257,7 @@ or generic command path.| Linux SMART telemetry | `smart.snapshot` through the no-network helper; no caller-selected device or arguments | Implemented, unqualified on representative physical disks. Helper failure omits/degrades SMART only; the collector does not retry as root | Does not yet justify SMART parity or a default change | `agent-lifecycle`: record live SATA, SAS/controller, USB bridge, and NVMe evidence, including standby, permission failure, timeout, and partial-data cases || Proxmox node-local LXC filesystem telemetry | `proxmox.lxc_filesystems` through the no-network helper using fixed bounded `pct` operations | Implemented, unqualified on a representative PVE node. Helper failure omits/degrades this snapshot only | Does not yet justify Proxmox host-agent parity or a default change | `agent-lifecycle`: record live running/stopped LXC, mount, timeout, output-bound, and helper-loss behavior on supported PVE versions || Rootful Docker or Podman inventory | No direct collector access to a root-equivalent daemon socket | Implemented as a typed-helper summary-only fallback. Migration preserves container ID/name/image/state/status/creation inventory and marks the report `typed-helper-summary`; stats, secondary inventories, update checks, and actions remain unavailable | Unit and installer regressions cover the boundary, but no representative live Docker/Podman qualification exists. Full rootful parity remains an explicit default blocker; the legacy/root profile is not safe-profile evidence | `agent-lifecycle`: record fresh install, migration, restart, helper loss/recovery, bounds, and summary parity on representative rootful Docker and Podman; decide explicitly whether reduced telemetry is sufficient |-| Collector-owned rootless Docker or Podman | Direct access only to one usable runtime socket owned by the `pulse-agent` UID whose daemon also attests rootless mode | Implemented, unqualified live. Discovery is deferred until the collector account exists and accepts exactly one readable/writable, non-symlink socket owned by that UID across Docker and Podman. Cross-user, root-owned, remote, unreadable, non-rootless-daemon, or ambiguous endpoints are rejected. An installer-owned exact pin survives daemon loss and update; the running collector can move between direct rootless monitoring and rootful typed-helper summary without regaining action authority | Does not yet justify container-runtime parity or a default change | `deployment-installability`: record fresh install, migration, restart, socket-loss, ambiguity, helper/direct recovery, and telemetry parity on both rootless Docker and rootless Podman |+| Collector-owned rootless Docker or Podman | Direct access only to one usable runtime socket owned by the `pulse-agent` UID whose daemon also attests rootless mode | Implemented, unqualified live. Discovery is deferred until the collector account exists and accepts exactly one readable/writable, non-symlink socket owned by that UID across Docker and Podman. Cross-user, root-owned, remote, unreadable, non-rootless-daemon, or ambiguous endpoints are rejected. An installer-owned exact pin survives daemon loss and update; the running collector can move between direct rootless monitoring and rootful typed-helper summary without regaining action authority | A separate opt-in `secure-runtime-rootless-v1` harness and fail-closed receipt validator define disposable nested Ubuntu/systemd Docker and Podman proof without changing immutable schema v7. No complete retained receipt exists yet, so this does not justify container-runtime parity or a default change | `deployment-installability`: run and retain the exact source/artifact-bound fresh-install, migration, restart, socket-loss, ambiguity, helper/direct recovery, cleanup, and telemetry-parity packet for both rootless Docker and rootless Podman || Separate runner package update and package-cache cleanup | Root-owned `pulse-agent-runner`, host-bound action credential, typed request, postcondition, and durable receipt | The schema-v6 committed-main systemd receipt records a real verified apt-cache mutation, stale-fingerprint refusal, replay, nonce-bound readiness, effective-unit override rejection, exact credential rotation, bodyless self-revocation, and collector/helper continuity. A separate production Router regression exercises HTTPS issuance, WSS admission, encrypted token persistence, failed-rotation rollback, exact socket invalidation, two server restarts, old-secret rejection, and durable self-revoke | Qualified for the exercised systemd fixture paths and focused production Router lifecycle. Focused installer tests also cover atomic pending cancellation and fail-closed credential retention. The evidence does not cover every runner operation, representative providers, or an exact release candidate | `agent-lifecycle` and `api-contracts`: reproduce the combined systemd and production Router path from trusted RC artifacts with representative package-update success/failure/cancellation evidence || Separate runner Proxmox guest and container lifecycle/update actions | Root-owned runner with closed typed protocols; never the monitoring collector | Implemented, unqualified on representative PVE and container-runtime targets. Focused protocol tests prove expired requests are not dispatched, timeout/caller abandonment sends one request-bound cancellation across every typed mutation family, and a canceled Proxmox mutation persists an indeterminate terminal receipt that survives runner reconnect and replays without a second mutation | This is local protocol/durability proof only: it makes no live-provider action-parity claim and does not change the default | `agent-lifecycle`: record target-bound success, stale-state refusal, provider-handoff cancellation, reconnect/replay, and independent postconditions on disposable real targets || Appliance, non-systemd, Windows, and macOS host-agent profiles | Platform API where sufficient; otherwise an explicitly named legacy/full-trust profile | **Unavailable for safe-profile apply.** The installer fails closed instead of silently installing a root-equivalent profile | Excluded from the Linux safe-profile claim | `deployment-installability`: land a platform-specific service, filesystem, update, helper, migration, rollback, and live-proof contract before marking that platform supported |diff --git a/docs/release-control/v6/internal/AGENT_PRIVILEGE_BOUNDARY_PLAN.md b/docs/release-control/v6/internal/AGENT_PRIVILEGE_BOUNDARY_PLAN.mdindex 959681429b..7b1a43c823 100644--- a/docs/release-control/v6/internal/AGENT_PRIVILEGE_BOUNDARY_PLAN.md+++ b/docs/release-control/v6/internal/AGENT_PRIVILEGE_BOUNDARY_PLAN.md@@ -269,6 +269,17 @@ profile is configured. This is implementation proof only; the live fresh-installambiguity, loss, bidirectional recovery, and telemetry-parity matrix remainsthe qualification residual.+The standalone `secure-runtime-rootless-v1` packet now owns that residual+without changing the immutable schema-v7 systemd contract. Its opt-in wrapper+runs only inside disposable nested Ubuntu/systemd hosts and requires real+collector-owned rootless Docker and Podman daemons, separate same-family+rootful helper baselines, exact installer pins, runtime loss and recovery, and+cleanup before its independent validator can emit a local artifact-bound+self-attestation. A checked-in harness or locally passing ordinary tests are+not qualification. Until a complete secret-free receipt and attestation are+retained, the matrix row remains implemented-but-unqualified and the safe+profile remains opt-in.+## Target Architecture### 1. API-Only Monitoringdiff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex b5bf57a3dc..d47f75910c 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -1751,6 +1751,8 @@ lifecycle conditions, but compact empty-state spacing, icon treatment, and texthierarchy must compose frontend-primitives' `EmptyState` `variant="panel"`instead of lifecycle-local centered icon/text shells.+32. `scripts/run-secure-runtime-rootless-qualification.sh` shared with `deployment-installability`: the rootless runtime qualification wrapper is both an agent lifecycle provider-boundary proof entry point and a deployment installability proof harness.+## Extension PointsSafe-profile installation and migration invoke the private lifecycle commands@@ -7237,6 +7239,29 @@ qualify migration and failure rollback, typed-helper update activation,provider parity and documented degradation, and separately credentialed liveaction sessions. Unsupported platforms continue to fail closed on migration.+### Rootless container qualification is a separate immutable packet++`scripts/run-secure-runtime-rootless-qualification.sh` is the opt-in entrypoint+for collector-owned rootless Docker and Podman proof. It does not extend or+reinterpret the schema-v7 systemd receipt. The wrapper confines destructive+runtime setup to disposable nested Ubuntu/systemd hosts with no mounted host+daemon socket, exercises each runtime in an isolated state root, and emits the+standalone `secure-runtime-rootless-v1` receipt only after exact socket+ownership, daemon rootless attestation, installer pinning, direct telemetry,+same-family typed-helper fallback, recovery without collector restart,+ambiguity refusal, authority isolation, and cleanup are recorded.++`scripts/release_control/secure_runtime_rootless_attestation_v1.py` validates+the secret-free receipt against the governed rootless source manifest and the+exact qualification artifact. It treats rootless and rootful helper+inventories as separate daemon identities, requires direct recovery to restore+the original rootless identity and rich telemetry, and understands that a+collector restart creates a new report stream while daemon restart preserves+the durable daemon identity. Its classification is local, opt-in,+artifact-bound self-attestation only. No receipt exists merely because the+harness is checked in, so rootless Docker and Podman remain live-unqualified+and cannot change the product default.+### Command and durable typed dispatch are context-honest and canceled when abandonedThe agent command transport now refuses to dispatch work its caller hasdiff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.mdindex 99de4b03bd..a4d1879058 100644--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md@@ -254,6 +254,20 @@ commands and autonomous cleanup/update work remain disabled in the safecollector even while direct rootless monitoring is active. Legacy/root discovery retainsits separate rootful-Docker-first behavior for compatibility.+Live collector-owned rootless-runtime proof is deliberately separated from+the immutable schema-v7 systemd packet. The opt-in+`scripts/run-secure-runtime-rootless-qualification.sh` wrapper creates fresh,+network-isolated Ubuntu/systemd hosts for real rootless Docker and Podman,+never mounts a host daemon socket, and records each host identity separately.+Its standalone `secure-runtime-rootless-v1` receipt must bind the exact+qualification, collector, helper, installer, source-manifest, socket,+fresh-install, legacy-migration, restart, fallback, recovery, ambiguity,+authority, and cleanup evidence before the independent validator can emit a+local artifact-bound self-attestation. Checking in the harness or passing its+ordinary contract tests is not live qualification. Until a complete+secret-free receipt and attestation are retained, this surface remains+implemented-but-unqualified and cannot change the opt-in safe-profile default.+Release builds and archives carry both helper and runner binaries for the fiveLinux targets (`amd64`, `arm64`, `armv7`, `armv6`, and `386`) with checksum,Ed25519, and SSH signature sidecars. Exact archive/container-context validation@@ -821,6 +835,8 @@ artifact-selection behaviour.`NoNewPrivileges=false` exception above: it restores only the privilege`lxc-attach` needs and leaves the rest of the sandbox intact.+9. `scripts/run-secure-runtime-rootless-qualification.sh` shared with `agent-lifecycle`: the rootless runtime qualification wrapper is both an agent lifecycle provider-boundary proof entry point and a deployment installability proof harness.+## Extension Points1. Add or change deployment-type detection, update planning, or apply behavior through `internal/updates/`diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex 71c1d71b2a..5e2e2da33b 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -1286,6 +1286,14 @@"agent-lifecycle","deployment-installability"]+ },+ {+ "path": "scripts/run-secure-runtime-rootless-qualification.sh",+ "rationale": "the rootless runtime qualification wrapper is both an agent lifecycle provider-boundary proof entry point and a deployment installability proof harness",+ "subsystems": [+ "agent-lifecycle",+ "deployment-installability"+ ]}],"subsystems": [@@ -1389,6 +1397,7 @@"scripts/installtests/windows_agent_lifecycle.ps1","scripts/installtests/windowslifecycleserver/main.go","scripts/run-native-pve-action-qualification.sh",+ "scripts/run-secure-runtime-rootless-qualification.sh","tests/integration/tests/84-docker-restart-real-lab-artifact.spec.ts"],"verification": {@@ -1472,6 +1481,20 @@"scripts/installtests/native_pve_action_qualification_test.go"]},+ {+ "id": "rootless-container-runtime-qualification",+ "label": "disposable rootless Docker and Podman lifecycle qualification proof",+ "match_prefixes": [],+ "match_files": [+ "scripts/run-secure-runtime-rootless-qualification.sh"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "scripts/installtests/secure_runtime_rootless_qualification_test.go",+ "scripts/release_control/secure_runtime_rootless_attestation_v1_test.py"+ ]+ },{"id": "patrol-autonomy-colima-real-lab","label": "RG-06 server-owned limited-unattended-autonomy Colima proof",@@ -4490,6 +4513,8 @@"scripts/release_control/resolve_release_promotion.py","scripts/release_control/secure_runtime_attestation_v6.py","scripts/release_control/secure_runtime_attestation_v7.py",+ "scripts/release_control/secure_runtime_rootless_attestation_v1.py",+ "scripts/release_control/secure_runtime_rootless_source_manifest_v1.json","scripts/release_control/secure_runtime_source_manifest_v6.json","scripts/release_control/secure_runtime_source_manifest_v7.json","scripts/release_control/validate_artifact_release_line.py",@@ -4497,6 +4522,7 @@"scripts/release_update_key.go","scripts/run-release-backend-tests.sh","scripts/run-release-preflight.sh",+ "scripts/run-secure-runtime-rootless-qualification.sh","scripts/run_cloud_public_signup_smoke.sh","scripts/run_demo_public_browser_smoke.sh","scripts/run_hosted_staging_smoke.sh",@@ -4693,8 +4719,8 @@"scripts/release_control/release_candidate_manifest_test.py"]},- {- "id": "release-build-metadata-runtime",+ {+ "id": "release-build-metadata-runtime","label": "release build metadata proof","match_prefixes": [],"match_files": [@@ -4731,6 +4757,22 @@"scripts/release_control/secure_runtime_attestation_v7_test.py"]},+ {+ "id": "rootless-runtime-qualification-tooling",+ "label": "standalone rootless Docker and Podman qualification packet proof",+ "match_prefixes": [],+ "match_files": [+ "scripts/release_control/secure_runtime_rootless_attestation_v1.py",+ "scripts/release_control/secure_runtime_rootless_source_manifest_v1.json",+ "scripts/run-secure-runtime-rootless-qualification.sh"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "scripts/installtests/secure_runtime_rootless_qualification_test.go",+ "scripts/release_control/secure_runtime_rootless_attestation_v1_test.py"+ ]+ },{"id": "pulse-mcp-installer-release-runtime","label": "Pulse MCP installer release proof",diff --git a/frontend-modern/public/docs/AGENT_SECURITY.md b/frontend-modern/public/docs/AGENT_SECURITY.mdindex b19040f88b..0fecba77e0 100644--- a/frontend-modern/public/docs/AGENT_SECURITY.md+++ b/frontend-modern/public/docs/AGENT_SECURITY.md@@ -257,7 +257,7 @@ or generic command path.| Linux SMART telemetry | `smart.snapshot` through the no-network helper; no caller-selected device or arguments | Implemented, unqualified on representative physical disks. Helper failure omits/degrades SMART only; the collector does not retry as root | Does not yet justify SMART parity or a default change | `agent-lifecycle`: record live SATA, SAS/controller, USB bridge, and NVMe evidence, including standby, permission failure, timeout, and partial-data cases || Proxmox node-local LXC filesystem telemetry | `proxmox.lxc_filesystems` through the no-network helper using fixed bounded `pct` operations | Implemented, unqualified on a representative PVE node. Helper failure omits/degrades this snapshot only | Does not yet justify Proxmox host-agent parity or a default change | `agent-lifecycle`: record live running/stopped LXC, mount, timeout, output-bound, and helper-loss behavior on supported PVE versions || Rootful Docker or Podman inventory | No direct collector access to a root-equivalent daemon socket | Implemented as a typed-helper summary-only fallback. Migration preserves container ID/name/image/state/status/creation inventory and marks the report `typed-helper-summary`; stats, secondary inventories, update checks, and actions remain unavailable | Unit and installer regressions cover the boundary, but no representative live Docker/Podman qualification exists. Full rootful parity remains an explicit default blocker; the legacy/root profile is not safe-profile evidence | `agent-lifecycle`: record fresh install, migration, restart, helper loss/recovery, bounds, and summary parity on representative rootful Docker and Podman; decide explicitly whether reduced telemetry is sufficient |-| Collector-owned rootless Docker or Podman | Direct access only to one usable runtime socket owned by the `pulse-agent` UID whose daemon also attests rootless mode | Implemented, unqualified live. Discovery is deferred until the collector account exists and accepts exactly one readable/writable, non-symlink socket owned by that UID across Docker and Podman. Cross-user, root-owned, remote, unreadable, non-rootless-daemon, or ambiguous endpoints are rejected. An installer-owned exact pin survives daemon loss and update; the running collector can move between direct rootless monitoring and rootful typed-helper summary without regaining action authority | Does not yet justify container-runtime parity or a default change | `deployment-installability`: record fresh install, migration, restart, socket-loss, ambiguity, helper/direct recovery, and telemetry parity on both rootless Docker and rootless Podman |+| Collector-owned rootless Docker or Podman | Direct access only to one usable runtime socket owned by the `pulse-agent` UID whose daemon also attests rootless mode | Implemented, unqualified live. Discovery is deferred until the collector account exists and accepts exactly one readable/writable, non-symlink socket owned by that UID across Docker and Podman. Cross-user, root-owned, remote, unreadable, non-rootless-daemon, or ambiguous endpoints are rejected. An installer-owned exact pin survives daemon loss and update; the running collector can move between direct rootless monitoring and rootful typed-helper summary without regaining action authority | A separate opt-in `secure-runtime-rootless-v1` harness and fail-closed receipt validator define disposable nested Ubuntu/systemd Docker and Podman proof without changing immutable schema v7. No complete retained receipt exists yet, so this does not justify container-runtime parity or a default change | `deployment-installability`: run and retain the exact source/artifact-bound fresh-install, migration, restart, socket-loss, ambiguity, helper/direct recovery, cleanup, and telemetry-parity packet for both rootless Docker and rootless Podman || Separate runner package update and package-cache cleanup | Root-owned `pulse-agent-runner`, host-bound action credential, typed request, postcondition, and durable receipt | The schema-v6 committed-main systemd receipt records a real verified apt-cache mutation, stale-fingerprint refusal, replay, nonce-bound readiness, effective-unit override rejection, exact credential rotation, bodyless self-revocation, and collector/helper continuity. A separate production Router regression exercises HTTPS issuance, WSS admission, encrypted token persistence, failed-rotation rollback, exact socket invalidation, two server restarts, old-secret rejection, and durable self-revoke | Qualified for the exercised systemd fixture paths and focused production Router lifecycle. Focused installer tests also cover atomic pending cancellation and fail-closed credential retention. The evidence does not cover every runner operation, representative providers, or an exact release candidate | `agent-lifecycle` and `api-contracts`: reproduce the combined systemd and production Router path from trusted RC artifacts with representative package-update success/failure/cancellation evidence || Separate runner Proxmox guest and container lifecycle/update actions | Root-owned runner with closed typed protocols; never the monitoring collector | Implemented, unqualified on representative PVE and container-runtime targets. Focused protocol tests prove expired requests are not dispatched, timeout/caller abandonment sends one request-bound cancellation across every typed mutation family, and a canceled Proxmox mutation persists an indeterminate terminal receipt that survives runner reconnect and replays without a second mutation | This is local protocol/durability proof only: it makes no live-provider action-parity claim and does not change the default | `agent-lifecycle`: record target-bound success, stale-state refusal, provider-handoff cancellation, reconnect/replay, and independent postconditions on disposable real targets || Appliance, non-systemd, Windows, and macOS host-agent profiles | Platform API where sufficient; otherwise an explicitly named legacy/full-trust profile | **Unavailable for safe-profile apply.** The installer fails closed instead of silently installing a root-equivalent profile | Excluded from the Linux safe-profile claim | `deployment-installability`: land a platform-specific service, filesystem, update, helper, migration, rollback, and live-proof contract before marking that platform supported |diff --git a/scripts/installtests/secure_runtime_rootless_qualification_test.go b/scripts/installtests/secure_runtime_rootless_qualification_test.gonew file mode 100644index 0000000000..a1a4089d8d--- /dev/null+++ b/scripts/installtests/secure_runtime_rootless_qualification_test.go@@ -0,0 +1,1581 @@+//go:build !windows++package installtests++// This file is a deliberately separate qualification packet. The live test is+// never part of ordinary `go test`: it mutates users, systemd units, and local+// container-runtime state and therefore requires an exact disposable-host+// marker plus an explicit opt-in. The host-side wrapper creates the isolated+// Ubuntu 24.04 systemd containers and never mounts the host runtime socket.++import (+ "context"+ "crypto/sha256"+ "debug/buildinfo"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "sort"+ "strconv"+ "strings"+ "syscall"+ "testing"+ "time"++ agentsdocker "github.com/rcourtman/pulse-go-rewrite/pkg/agents/docker"+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"+)++const (+ rootlessQualOptIn = "PULSE_SECURE_RUNTIME_ROOTLESS_QUALIFICATION"+ rootlessQualOptInValue = "disposable-v1"+ rootlessQualMarker = "/etc/pulse-secure-runtime-rootless-qualification"+ rootlessQualFixture = "pulse-rootless-qualification-fixture:v1"+ rootlessQualRunningName = "pulse-rootless-running"+ rootlessQualExitedName = "pulse-rootless-exited"+)++var rootlessQualScenarioOrder = []string{+ "fresh_install",+ "legacy_migration",+ "collector_restart",+ "daemon_restart",+ "socket_loss_helper_fallback",+ "direct_recovery",+ "dual_socket_ambiguity_refusal",+ "exact_pin_recovery",+ "telemetry_parity",+ "authority_isolation",+ "cleanup",+}++type rootlessQualReceipt struct {+ SchemaVersion int `json:"schema_version"`+ Kind string `json:"kind"`+ Result string `json:"result"`+ SourceCommit string `json:"source_commit"`+ StartedAt string `json:"started_at"`+ CompletedAt string `json:"completed_at"`+ SourceHashes map[string]string `json:"source_hashes"`+ Artifacts rootlessQualArtifacts `json:"artifacts"`+ Runs []rootlessQualRun `json:"runs"`+}++type rootlessQualHost struct {+ MachineID string `json:"machine_id"`+ Architecture string `json:"architecture"`+ Kernel string `json:"kernel"`+ SystemdVersion string `json:"systemd_version"`+}++type rootlessQualArtifact struct {+ PathBasename string `json:"path_basename"`+ SHA256 string `json:"sha256"`+ Package string `json:"package"`+ GoVersion string `json:"go_version"`+ VCSRevision string `json:"vcs_revision"`+ VCSModified bool `json:"vcs_modified"`+}++type rootlessQualInstallerArtifact struct {+ PathBasename string `json:"path_basename"`+ SHA256 string `json:"sha256"`+}++type rootlessQualArtifacts struct {+ QualificationTest rootlessQualArtifact `json:"qualification_test"`+ Collector rootlessQualArtifact `json:"collector"`+ Helper rootlessQualArtifact `json:"helper"`+ Installer rootlessQualInstallerArtifact `json:"installer"`+}++type rootlessQualRun struct {+ Host rootlessQualHost `json:"host"`+ Runtime rootlessQualRuntime `json:"runtime"`+ Scenarios []rootlessQualScenario `json:"scenarios"`+}++type rootlessQualRuntime struct {+ Runtime string `json:"runtime"`+ RuntimeVersion string `json:"runtime_version"`+ DaemonID string `json:"daemon_id"`+ CollectorUID int `json:"collector_uid"`+ SocketPath string `json:"socket_path"`+ SocketUID int `json:"socket_uid"`+ SocketGID int `json:"socket_gid"`+ SocketMode string `json:"socket_mode"`+ DaemonRootless bool `json:"daemon_rootless"`+ SocketType string `json:"socket_type"`+ SocketSymlink bool `json:"socket_symlink"`+}++type rootlessQualScenario struct {+ Name string `json:"name"`+ Result string `json:"result"`+ StartedAt string `json:"started_at"`+ CompletedAt string `json:"completed_at"`+ ReportSequence *uint64 `json:"report_sequence"`+ ReportStreamID *string `json:"report_stream_id"`+ Evidence map[string]any `json:"evidence"`+}++type rootlessQualDaemon struct {+ runtime string+ rootlessUnit string+ rootfulUnit string+ rootlessSock string+ rootfulSock string+ uid int+ home string+}++func TestSecureRuntimeRootlessQualification(t *testing.T) {+ if os.Getenv(rootlessQualOptIn) != rootlessQualOptInValue {+ t.Skip("run through scripts/run-secure-runtime-rootless-qualification.sh inside its disposable systemd container")+ }+ runtimeKind := strings.TrimSpace(os.Getenv("PULSE_ROOTLESS_RUNTIME"))+ receiptPath := strings.TrimSpace(os.Getenv("PULSE_ROOTLESS_RECEIPT"))+ rootlessQualRequireDisposableHost(t, runtimeKind, receiptPath)++ collector := secureRuntimeReadArtifact(t, "PULSE_SECURE_RUNTIME_COLLECTOR")+ collectorSignature := secureRuntimeReadSignature(t, "PULSE_SECURE_RUNTIME_COLLECTOR_SIGNATURE")+ helper := secureRuntimeReadArtifact(t, "PULSE_SECURE_RUNTIME_HELPER")+ collectorVersion := secureRuntimeArtifactVersion(t, "PULSE_SECURE_RUNTIME_COLLECTOR")+ installerPath := strings.TrimSpace(os.Getenv("PULSE_SECURE_RUNTIME_INSTALLER"))+ if !filepath.IsAbs(installerPath) {+ t.Fatalf("PULSE_SECURE_RUNTIME_INSTALLER must be absolute: %q", installerPath)+ }++ started := time.Now().UTC()+ fixture := newSecureRuntimeLabFixture(collector, collectorSignature, helper, nil, collectorVersion)+ defer fixture.actionServer.Shutdown()+ server := httptest.NewServer(fixture)+ defer server.Close()++ daemon := rootlessQualPrepareDaemons(t, runtimeKind)+ defer rootlessQualBestEffortStop(daemon.rootlessUnit, daemon.rootfulUnit, rootlessQualOtherUnit(runtimeKind))+ rootlessQualStartRootful(t, daemon)+ rootlessQualStartRootless(t, daemon)+ identity := rootlessQualReadIdentityRecord(t, daemon)+ if err := os.Remove(daemon.rootlessSock + ".qualification-identity"); err != nil {+ t.Fatalf("remove transient runtime identity sidecar: %v", err)+ }+ rootlessQualCreateFixture(t, daemon, false)+ rootlessQualCreateFixture(t, daemon, true)+ daemonRootlessObserved := rootlessQualDaemonRootless(t, daemon)+ if !daemonRootlessObserved {+ t.Fatalf("%s daemon did not independently report rootless operation", runtimeKind)+ }+ rootfulBaseline := rootlessQualRuntimeBaseline(t, daemon, false)+ rootlessBaseline := rootlessQualRuntimeBaseline(t, daemon, true)+ if rootfulBaseline.SemanticDigest != rootlessBaseline.SemanticDigest || rootfulBaseline.Count != 2 {+ t.Fatalf("separate same-family baselines differ: rootful=%+v rootless=%+v", rootfulBaseline, rootlessBaseline)+ }++ var scenarios []rootlessQualScenario+ appendScenario := func(name string, began time.Time, report *agentsdocker.Report, evidence map[string]any) {+ scenario := rootlessQualScenario{Name: name, Result: "passed", StartedAt: began.Format(time.RFC3339Nano), CompletedAt: time.Now().UTC().Format(time.RFC3339Nano), Evidence: evidence}+ if report != nil {+ stream, sequence, ok := agentshost.ParseReportSequenceID(report.SequenceID)+ if !ok {+ t.Fatalf("scenario %s received invalid sequence ID %q", name, report.SequenceID)+ }+ scenario.ReportSequence = &sequence+ scenario.ReportStreamID = &stream+ }+ scenarios = append(scenarios, scenario)+ }++ // Prove a fresh safe-profile install first, then remove it before creating+ // the legacy root profile. Both paths therefore begin without installed+ // Pulse files; the surrounding outer container itself is also fresh.+ freshStarted := time.Now().UTC()+ secureRuntimeRunInstaller(t, installerPath, server.URL,+ "--least-privilege", "--enable-privileged-helper", "--enable-docker")+ freshReport := rootlessQualWaitDirect(t, fixture, freshStarted, runtimeKind, 75*time.Second)+ secureRuntimeAssertSafeProfile(t)+ secureRuntimeAssertHelperProtocol(t)+ freshDigest := rootlessQualDigestReport(freshReport.Report)+ freshPID := secureRuntimeCollectorMainPID(t)+ daemonIDBefore := rootlessQualDaemonID(t, daemon, true)+ appendScenario("fresh_install", freshStarted, &freshReport.Report,+ rootlessQualDirectEvidence(daemon, identity, freshPID, daemonIDBefore, daemonRootlessObserved, freshDigest))+ rootlessQualUninstallPulse(t, installerPath, server.URL)+ rootlessQualAssertPulseRemoved(t)++ migrationStarted := time.Now().UTC()+ secureRuntimeRunInstaller(t, installerPath, server.URL,+ "--enable-commands", "--command-authority", "command-capable", "--enable-docker")+ legacyReport := rootlessQualWaitReport(t, fixture, migrationStarted, 75*time.Second, func(report agentsdocker.Report) bool {+ return rootlessQualComplete(report) && report.Host.CollectionMode == "" && report.Host.Runtime == runtimeKind+ })+ secureRuntimeAssertRootCommandProfile(t)+ legacyPID := secureRuntimeCollectorMainPID(t)+ legacyDigest := rootlessQualSemanticDigest(legacyReport.Report)+ if legacyDigest != rootfulBaseline.SemanticDigest {+ t.Fatalf("legacy root report differs from the separate rootful runtime baseline: report=%s baseline=%s", legacyDigest, rootfulBaseline.SemanticDigest)+ }+ applyStarted := time.Now().UTC()+ secureRuntimeRunInstaller(t, installerPath, server.URL, "--safe-profile-apply")+ migratedReport := rootlessQualWaitDirect(t, fixture, applyStarted, runtimeKind, 75*time.Second)+ secureRuntimeAssertSafeProfile(t)+ secureRuntimeAssertHelperProtocol(t)+ migratedDigest := rootlessQualDigestReport(migratedReport.Report)+ if freshDigest.SemanticDigest != rootlessBaseline.SemanticDigest || migratedDigest.SemanticDigest != rootlessBaseline.SemanticDigest {+ t.Fatalf("direct report semantic parity failed: baseline=%s fresh=%s migration=%s", rootlessBaseline.SemanticDigest, freshDigest.SemanticDigest, migratedDigest.SemanticDigest)+ }+ migratedPID := secureRuntimeCollectorMainPID(t)+ if migratedPID == legacyPID {+ t.Fatalf("safe-profile migration did not replace legacy collector PID %d", legacyPID)+ }+ migrationEvidence := rootlessQualDirectEvidence(daemon, identity, migratedPID, daemonIDBefore, daemonRootlessObserved, migratedDigest)+ migrationEvidence["legacy_profile"] = "root-command-capable"+ migrationEvidence["target_profile"] = "typed-helper-monitoring-only"+ migrationEvidence["authority_reduced"] = true+ migrationEvidence["legacy_collector_pid"] = legacyPID+ appendScenario("legacy_migration", migrationStarted, &migratedReport.Report, migrationEvidence)++ restartStarted := time.Now().UTC()+ collectorPIDBefore := migratedPID+ streamBefore, _, _ := agentshost.ParseReportSequenceID(migratedReport.Report.SequenceID)+ secureRuntimeCommand(t, 20*time.Second, "systemctl", "restart", "pulse-agent.service")+ collectorPIDAfter := secureRuntimeCollectorMainPID(t)+ restartedCollectorReport := rootlessQualWaitDirect(t, fixture, restartStarted, runtimeKind, 75*time.Second)+ streamAfter, _, _ := agentshost.ParseReportSequenceID(restartedCollectorReport.Report.SequenceID)+ restartedCollectorDigest := rootlessQualDigestReport(restartedCollectorReport.Report)+ if collectorPIDAfter == collectorPIDBefore || streamAfter == streamBefore || restartedCollectorDigest.SemanticDigest != rootlessBaseline.SemanticDigest {+ t.Fatalf("collector restart did not replace process/stream with parity: pid=%d/%d stream=%s/%s", collectorPIDBefore, collectorPIDAfter, streamBefore, streamAfter)+ }+ restartEvidence := rootlessQualDirectEvidence(daemon, identity, collectorPIDAfter, daemonIDBefore, daemonRootlessObserved, restartedCollectorDigest)+ restartEvidence["previous_collector_pid"] = collectorPIDBefore+ restartEvidence["previous_report_stream_id"] = streamBefore+ appendScenario("collector_restart", restartStarted, &restartedCollectorReport.Report, restartEvidence)++ daemonRestartStarted := time.Now().UTC()+ daemonPIDBefore, invocationBefore := rootlessQualUnitIdentity(t, daemon.rootlessUnit)+ rootlessQualStopUnit(t, daemon.rootlessUnit)+ rootlessQualStartRootless(t, daemon)+ daemonPIDAfter, invocationAfter := rootlessQualUnitIdentity(t, daemon.rootlessUnit)+ daemonIDAfter := rootlessQualDaemonID(t, daemon, true)+ daemonRootlessAfterRestart := rootlessQualDaemonRootless(t, daemon)+ daemonRestartReport := rootlessQualWaitDirect(t, fixture, daemonRestartStarted, runtimeKind, 75*time.Second)+ daemonRestartDigest := rootlessQualDigestReport(daemonRestartReport.Report)+ if daemonPIDBefore == daemonPIDAfter || invocationBefore == invocationAfter || daemonIDBefore != daemonIDAfter || daemonRestartDigest.SemanticDigest != rootlessBaseline.SemanticDigest {+ t.Fatalf("daemon restart identity/parity mismatch: pid=%d/%d invocation=%s/%s daemon=%s/%s", daemonPIDBefore, daemonPIDAfter, invocationBefore, invocationAfter, daemonIDBefore, daemonIDAfter)+ }+ daemonEvidence := rootlessQualDirectEvidence(daemon, identity, collectorPIDAfter, daemonIDAfter, daemonRootlessAfterRestart, daemonRestartDigest)+ daemonEvidence["previous_daemon_pid"] = daemonPIDBefore+ daemonEvidence["daemon_pid"] = daemonPIDAfter+ daemonEvidence["previous_daemon_invocation_id"] = invocationBefore+ daemonEvidence["daemon_invocation_id"] = invocationAfter+ appendScenario("daemon_restart", daemonRestartStarted, &daemonRestartReport.Report, daemonEvidence)++ lossStarted := time.Now().UTC()+ rootlessQualStopUnit(t, daemon.rootlessUnit)+ helperReport := rootlessQualWaitReport(t, fixture, lossStarted, 90*time.Second, func(report agentsdocker.Report) bool {+ return rootlessQualComplete(report) && report.Host.CollectionMode == agentsdocker.CollectionModeTypedHelperSummary && report.Host.Runtime == runtimeKind+ })+ rootlessQualAssertHelperSummaryOnly(t, helperReport.Report, runtimeKind)+ helperDigest := rootlessQualDigestReport(helperReport.Report)+ if helperDigest.SemanticDigest != rootfulBaseline.SemanticDigest || secureRuntimeCollectorMainPID(t) != collectorPIDAfter {+ t.Fatalf("typed-helper fallback did not preserve rootful semantic baseline/collector PID")+ }+ appendScenario("socket_loss_helper_fallback", lossStarted, &helperReport.Report, map[string]any{+ "collector_pid": collectorPIDAfter, "collection_mode": agentsdocker.CollectionModeTypedHelperSummary,+ "direct_runtime_available": false, "helper_fallback": true, "inventory_complete": true,+ "inventory_count": helperDigest.Count, "rootful_baseline_inventory_count": rootfulBaseline.Count,+ "semantic_sha256": helperDigest.SemanticDigest, "rootful_baseline_semantic_sha256": rootfulBaseline.SemanticDigest,+ "full_fields_present": false, "stats_present": false, "secondary_structure_sha256": "",+ "container_actions_enabled": false, "container_updates_enabled": false, "collector_restart_count": 0,+ })++ recoveryStarted := time.Now().UTC()+ rootlessQualStartRootless(t, daemon)+ recoveryReport := rootlessQualWaitDirect(t, fixture, recoveryStarted, runtimeKind, 90*time.Second)+ recoveryDigest := rootlessQualDigestReport(recoveryReport.Report)+ daemonRootlessAfterRecovery := rootlessQualDaemonRootless(t, daemon)+ if !rootlessQualStableDigestEqual(recoveryDigest, daemonRestartDigest) || secureRuntimeCollectorMainPID(t) != collectorPIDAfter || rootlessQualDaemonID(t, daemon, true) != daemonIDBefore {+ t.Fatalf("direct recovery did not restore the exact prior rootless telemetry/identity")+ }+ appendScenario("direct_recovery", recoveryStarted, &recoveryReport.Report,+ rootlessQualDirectEvidence(daemon, identity, collectorPIDAfter, daemonIDBefore, daemonRootlessAfterRecovery, recoveryDigest))++ ambiguityStarted := time.Now().UTC()+ otherUnit, otherSocket := rootlessQualStartOtherRootless(t, daemon)+ defer rootlessQualBestEffortStop(otherUnit)+ if _, err := os.Lstat(otherSocket); err != nil {+ t.Fatalf("second live rootless socket missing: %v", err)+ }+ ambiguityOutput := rootlessQualRunUnpinnedCollector(t, server.URL, 6*time.Second)+ if !strings.Contains(strings.ToLower(ambiguityOutput), "ambiguous collector-owned rootless runtime endpoints") {+ t.Fatalf("unpinned collector did not fail closed on dual sockets:\n%s", ambiguityOutput)+ }+ appendScenario("dual_socket_ambiguity_refusal", ambiguityStarted, nil, map[string]any{+ "protected_collector_pid": collectorPIDAfter,+ "live_sockets": rootlessQualDualSocketEvidence(t, daemon.uid),+ "probe_kind": "separate-unpinned-collector",+ "admission_refused": true, "fail_closed": true, "daemon_probe_count": 0,+ "container_actions_enabled": false, "collector_restart_count": 0,+ })+ rootlessQualStopUnit(t, otherUnit)++ pinStarted := time.Now().UTC()+ rootlessQualStopUnit(t, daemon.rootlessUnit)+ unitBefore := rootlessQualServicePin(t, runtimeKind)+ pinFallback := rootlessQualWaitReport(t, fixture, pinStarted, 90*time.Second, func(report agentsdocker.Report) bool {+ return rootlessQualComplete(report) && report.Host.CollectionMode == agentsdocker.CollectionModeTypedHelperSummary && report.Host.Runtime == runtimeKind+ })+ previousUpdateStream, _, _ := agentshost.ParseReportSequenceID(pinFallback.Report.SequenceID)+ updateStarted := time.Now().UTC()+ secureRuntimeRunInstaller(t, installerPath, server.URL, "--update")+ unitWhileAbsent := rootlessQualServicePin(t, runtimeKind)+ if unitBefore != daemon.rootlessSock || unitWhileAbsent != unitBefore {+ t.Fatalf("offline update lost exact rootless pin: before=%q after=%q", unitBefore, unitWhileAbsent)+ }+ collectorPIDAfterUpdate := secureRuntimeCollectorMainPID(t)+ postUpdateFallback := rootlessQualWaitReport(t, fixture, updateStarted, 90*time.Second, func(report agentsdocker.Report) bool {+ stream, _, ok := agentshost.ParseReportSequenceID(report.SequenceID)+ return ok && stream != previousUpdateStream && rootlessQualComplete(report) && report.Host.CollectionMode == agentsdocker.CollectionModeTypedHelperSummary && report.Host.Runtime == runtimeKind+ })+ rootlessQualStartRootless(t, daemon)+ pinReport := rootlessQualWaitDirect(t, fixture, postUpdateFallback.ReceivedAt, runtimeKind, 90*time.Second)+ pinDigest := rootlessQualDigestReport(pinReport.Report)+ daemonRootlessAfterPinRecovery := rootlessQualDaemonRootless(t, daemon)+ if !rootlessQualStableDigestEqual(pinDigest, recoveryDigest) || rootlessQualServicePin(t, runtimeKind) != daemon.rootlessSock {+ t.Fatalf("exact pin recovery did not return to the same endpoint and telemetry")+ }+ pinEvidence := rootlessQualDirectEvidence(daemon, identity, collectorPIDAfterUpdate, daemonIDBefore, daemonRootlessAfterPinRecovery, pinDigest)+ _, pinFallbackSequence, _ := agentshost.ParseReportSequenceID(postUpdateFallback.Report.SequenceID)+ _, pinRecoverySequence, _ := agentshost.ParseReportSequenceID(pinReport.Report.SequenceID)+ pinEvidence["previous_collector_pid"] = collectorPIDAfter+ pinEvidence["previous_report_stream_id"] = previousUpdateStream+ pinEvidence["pin_source"] = "root-owned-systemd-unit"+ pinEvidence["pinned_socket_path"] = unitBefore+ pinEvidence["socket_absent_observed"] = true+ pinEvidence["fallback_report_sequence"] = pinFallbackSequence+ pinEvidence["recovery_report_sequence"] = pinRecoverySequence+ pinEvidence["recovered_socket_path"] = daemon.rootlessSock+ pinEvidence["selected_socket_path"] = rootlessQualServicePin(t, runtimeKind)+ pinEvidence["recovered_socket_uid"] = identity.SocketUID+ pinEvidence["recovered_socket_gid"] = identity.SocketGID+ pinEvidence["recovered_socket_mode"] = identity.SocketMode+ pinEvidence["recovered_socket_type"] = "unix"+ pinEvidence["recovered_socket_symlink"] = false+ pinEvidence["candidate_count"] = 1+ pinEvidence["daemon_probe_count"] = 1+ pinEvidence["collector_restart_count"] = 1+ appendScenario("exact_pin_recovery", pinStarted, &pinReport.Report, pinEvidence)++ parityStarted := time.Now().UTC()+ parityReport := rootlessQualWaitDirect(t, fixture, parityStarted, runtimeKind, 75*time.Second)+ parityDigest := rootlessQualDigestReport(parityReport.Report)+ appendScenario("telemetry_parity", parityStarted, &parityReport.Report, map[string]any{+ "collector_pid": collectorPIDAfterUpdate, "baseline_kind": "root-client-same-rootless-daemon",+ "baseline_inventory_count": rootlessBaseline.Count, "collector_inventory_count": parityDigest.Count,+ "baseline_semantic_sha256": rootlessBaseline.SemanticDigest, "collector_semantic_sha256": parityDigest.SemanticDigest,+ "collector_full_fields_present": parityDigest.FullFieldsPresent, "collector_stats_present": parityDigest.StatsPresent,+ "collector_secondary_inventory_present": parityDigest.SecondaryInventoryPresent,+ })++ authorityStarted := time.Now().UTC()+ collectorUID := rootlessQualUID(t, "pulse-agent")+ rootfulDenied := rootlessQualRootfulAccessDenied(t, daemon)+ groups := strings.Fields(rootlessQualCommand(t, 10*time.Second, "id", "-nG", "pulse-agent"))+ for _, group := range groups {+ if group == "docker" || group == "podman" {+ t.Fatalf("collector retained daemon group %q", group)+ }+ }+ if !rootfulDenied || secureRuntimeCollectorProcessUID(t) != collectorUID || secureRuntimeCollectorHasArgument("--enable-commands") {+ t.Fatal("authority isolation did not remain exact")+ }+ helperNetworkDenied := rootlessQualAssertHelperNetworkDenied(t)+ commandSessionPresent := fixture.actionServer.IsAgentConnectedForOrganization(secureRuntimeLabOrgID, secureRuntimeLabAgentID)+ if !helperNetworkDenied || commandSessionPresent || fixture.authorityReductionCount() < 1 {+ t.Fatalf("authority evidence mismatch: helper_network_denied=%t command_session=%t reductions=%d", helperNetworkDenied, commandSessionPresent, fixture.authorityReductionCount())+ }+ appendScenario("authority_isolation", authorityStarted, nil, map[string]any{+ "collector_pid": collectorPIDAfterUpdate, "collector_uid": collectorUID, "effective_uid": collectorUID,+ "effective_root": false, "safe_profile_enabled": true, "commands_enabled": false,+ "privileged_helper_enabled": true, "reduction_request_observed": true,+ "collector_command_transport_present": false, "collector_command_session_present": false,+ "container_actions_enabled": false, "container_updates_enabled": false,+ "rootful_socket_access": false, "helper_network_access": false,+ })++ cleanupStarted := time.Now().UTC()+ rootlessQualUninstallPulse(t, installerPath, server.URL)+ rootlessQualStopUnit(t, daemon.rootlessUnit)+ rootlessQualStopUnit(t, daemon.rootfulUnit)+ rootlessQualRemoveRuntimeState(t, daemon)+ rootlessQualAssertPulseRemoved(t)+ for _, socket := range []string{daemon.rootlessSock, daemon.rootfulSock} {+ if _, err := os.Lstat(socket); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("cleanup left socket %s: %v", socket, err)+ }+ }+ userStateClean := rootlessQualUserStateClean(daemon)+ if !userStateClean {+ t.Fatal("cleanup left dedicated rootless runtime state")+ }+ appendScenario("cleanup", cleanupStarted, nil, map[string]any{+ "runtime_stopped": true, "socket_absent": true, "fixtures_removed": true, "user_state_clean": userStateClean,+ })++ artifacts := rootlessQualArtifactIdentities(t, installerPath)+ sourceHashes := rootlessQualSourceHashes(t)+ receipt := rootlessQualReceipt{+ SchemaVersion: 1, Kind: "pulse-secure-runtime-rootless-qualification", Result: "passed",+ SourceCommit: strings.TrimSpace(os.Getenv("PULSE_ROOTLESS_SOURCE_COMMIT")),+ StartedAt: started.Format(time.RFC3339Nano), CompletedAt: time.Now().UTC().Format(time.RFC3339Nano),+ SourceHashes: sourceHashes, Artifacts: artifacts,+ Runs: []rootlessQualRun{{+ Host: rootlessQualHost{+ MachineID: strings.TrimSpace(string(rootlessQualReadFile(t, "/etc/machine-id"))), Architecture: runtime.GOARCH,+ Kernel: rootlessQualCommand(t, 10*time.Second, "uname", "-srvmo"),+ SystemdVersion: strings.SplitN(rootlessQualCommand(t, 10*time.Second, "systemctl", "--version"), "\n", 2)[0],+ },+ Runtime: rootlessQualRuntime{+ Runtime: runtimeKind, RuntimeVersion: identity.RuntimeVersion, DaemonID: daemonIDBefore,+ CollectorUID: daemon.uid, SocketPath: daemon.rootlessSock, SocketUID: identity.SocketUID,+ SocketGID: identity.SocketGID, SocketMode: identity.SocketMode, DaemonRootless: daemonRootlessObserved,+ SocketType: "unix", SocketSymlink: false,+ },+ Scenarios: scenarios,+ }},+ }+ if err := rootlessQualValidateReceipt(receipt, 1); err != nil {+ t.Fatalf("generated receipt failed validation: %v", err)+ }+ rootlessQualWriteJSON(t, receiptPath, receipt)+}++type rootlessQualBaseline struct {+ Count int+ SemanticDigest string+}++type rootlessQualReportDigest struct {+ Count int+ InventoryDigest string+ SemanticDigest string+ StatsDigest string+ StatsPresent bool+ FullFieldsPresent bool+ SecondaryDigest string+ SecondaryInventoryPresent bool+}++type rootlessQualIdentity struct {+ RuntimeVersion string `json:"runtime_version"`+ SocketUID int `json:"socket_uid"`+ SocketGID int `json:"socket_gid"`+ SocketMode string `json:"socket_mode"`+}++func rootlessQualDirectEvidence(d rootlessQualDaemon, identity rootlessQualIdentity, collectorPID int, daemonID string, daemonRootless bool, digest rootlessQualReportDigest) map[string]any {+ return map[string]any{+ "collector_pid": collectorPID, "service_pid": collectorPID,+ "collection_path": "collector-owned-rootless-socket", "inventory_complete": true, "inventory_count": digest.Count,+ "semantic_sha256": digest.SemanticDigest, "full_fields_present": digest.FullFieldsPresent,+ "stats_present": digest.StatsPresent, "secondary_structure_sha256": digest.SecondaryDigest,+ "daemon_id": daemonID, "daemon_rootless": daemonRootless,+ "socket_path": d.rootlessSock, "socket_uid": identity.SocketUID, "socket_gid": identity.SocketGID,+ "socket_mode": identity.SocketMode, "socket_type": "unix", "socket_symlink": false,+ }+}++func rootlessQualRequireDisposableHost(t *testing.T, runtimeKind, receiptPath string) {+ t.Helper()+ if os.Geteuid() != 0 || (runtimeKind != "docker" && runtimeKind != "podman") {+ t.Fatalf("qualification requires root and PULSE_ROOTLESS_RUNTIME=docker|podman")+ }+ marker, err := os.ReadFile(rootlessQualMarker)+ if err != nil || strings.TrimSpace(string(marker)) != rootlessQualOptInValue {+ t.Fatalf("disposable marker is absent or invalid: %v", err)+ }+ if !filepath.IsAbs(receiptPath) || filepath.Clean(receiptPath) != receiptPath {+ t.Fatalf("PULSE_ROOTLESS_RECEIPT must be an exact absolute path: %q", receiptPath)+ }+ osRelease := string(rootlessQualReadFile(t, "/etc/os-release"))+ if !strings.Contains(osRelease, "VERSION_ID=\"24.04\"") && !strings.Contains(osRelease, "VERSION_ID=24.04") {+ t.Fatal("qualification host is not Ubuntu 24.04")+ }+ if _, err := os.Stat("/run/systemd/system"); err != nil {+ t.Fatalf("qualification host is not booted under systemd: %v", err)+ }+ if routes := string(rootlessQualReadFile(t, "/proc/net/route")); rootlessQualHasDefaultRoute(routes) {+ t.Fatal("qualification workload must run with outer-container networking disabled")+ }+}++func rootlessQualHasDefaultRoute(routes string) bool {+ for _, line := range strings.Split(routes, "\n") {+ fields := strings.Fields(line)+ if len(fields) >= 2 && fields[1] == "00000000" {+ return true+ }+ }+ return false+}++func rootlessQualPrepareDaemons(t *testing.T, runtimeKind string) rootlessQualDaemon {+ t.Helper()+ if _, err := exec.Command("id", "-u", "pulse-agent").Output(); err != nil {+ rootlessQualCommand(t, 10*time.Second, "useradd", "--system", "--create-home", "--home-dir", "/var/lib/pulse-rootless", "--shell", "/usr/sbin/nologin", "pulse-agent")+ }+ uid := rootlessQualUID(t, "pulse-agent")+ home := "/var/lib/pulse-rootless"+ rootlessQualWriteSubID(t, "/etc/subuid", "pulse-agent:100000:65536")+ rootlessQualWriteSubID(t, "/etc/subgid", "pulse-agent:100000:65536")+ paths := []string{filepath.Join("/run/user", strconv.Itoa(uid)), filepath.Join(home, "fixture"), filepath.Join(home, "docker"), filepath.Join(home, "podman")}+ for _, path := range paths {+ rootlessQualCommand(t, 10*time.Second, "install", "-d", "-o", "pulse-agent", "-g", "pulse-agent", "-m", "0700", path)+ }+ containerfile := "FROM scratch\nCOPY busybox /busybox\nENTRYPOINT [\"/busybox\"]\n"+ if err := os.WriteFile(filepath.Join(home, "fixture", "Containerfile"), []byte(containerfile), 0o600); err != nil {+ t.Fatal(err)+ }+ busybox, err := os.ReadFile("/bin/busybox")+ if err != nil {+ t.Fatalf("read offline busybox fixture: %v", err)+ }+ if err := os.WriteFile(filepath.Join(home, "fixture", "busybox"), busybox, 0o755); err != nil {+ t.Fatal(err)+ }+ rootlessQualCommand(t, 10*time.Second, "chown", "-R", "pulse-agent:pulse-agent", home)+ d := rootlessQualDaemon{runtime: runtimeKind, uid: uid, home: home, rootlessUnit: "pulse-rootless-" + runtimeKind, rootfulUnit: "pulse-rootful-" + runtimeKind}+ if runtimeKind == "docker" {+ d.rootlessSock = filepath.Join("/run/user", strconv.Itoa(uid), "docker.sock")+ d.rootfulSock = "/var/run/docker.sock"+ } else {+ d.rootlessSock = filepath.Join("/run/user", strconv.Itoa(uid), "podman", "podman.sock")+ d.rootfulSock = "/run/podman/podman.sock"+ }+ return d+}++func rootlessQualStartRootless(t *testing.T, d rootlessQualDaemon) {+ t.Helper()+ rootlessQualBestEffortStop(d.rootlessUnit)+ if d.runtime == "docker" {+ args := []string{"--quiet", "--collect", "--unit", d.rootlessUnit, "--property=Type=exec", "--property=User=pulse-agent", "--property=Group=pulse-agent", "--",+ "/usr/bin/env", "HOME=" + d.home, "XDG_RUNTIME_DIR=" + filepath.Dir(d.rootlessSock), "DOCKERD_ROOTLESS_ROOTLESSKIT_NET=host", "DOCKERD_ROOTLESS_ROOTLESSKIT_PORT_DRIVER=none",+ "/usr/bin/dockerd-rootless.sh", "--host=unix://" + d.rootlessSock, "--data-root=" + filepath.Join(d.home, "docker", "data"), "--exec-root=" + filepath.Join(d.home, "docker", "exec"), "--pidfile=" + filepath.Join(d.home, "docker", "dockerd.pid"), "--storage-driver=vfs", "--iptables=false", "--bridge=none"}+ rootlessQualCommand(t, 20*time.Second, "systemd-run", args...)+ } else {+ rootlessQualCommand(t, 20*time.Second, "install", "-d", "-o", "pulse-agent", "-g", "pulse-agent", "-m", "0700", filepath.Dir(d.rootlessSock))+ rootlessQualCommand(t, 20*time.Second, "systemd-run", "--quiet", "--collect", "--unit", d.rootlessUnit, "--property=Type=exec", "--property=User=pulse-agent", "--property=Group=pulse-agent", "--",+ "/usr/bin/env", "HOME="+d.home, "XDG_RUNTIME_DIR="+filepath.Join("/run/user", strconv.Itoa(d.uid)),+ "/usr/bin/podman", "system", "service", "--time=0", "unix://"+d.rootlessSock)+ }+ rootlessQualWaitSocket(t, d.rootlessSock)+ rootlessQualRuntimePing(t, d, true)+ rootlessQualCaptureIdentity(t, d)+}++func rootlessQualStartRootful(t *testing.T, d rootlessQualDaemon) {+ t.Helper()+ rootlessQualBestEffortStop(d.rootfulUnit)+ rootlessQualCommand(t, 10*time.Second, "install", "-d", "-o", "root", "-g", "root", "-m", "0755", filepath.Dir(d.rootfulSock))+ if d.runtime == "docker" {+ rootlessQualCommand(t, 20*time.Second, "systemd-run", "--quiet", "--collect", "--unit", d.rootfulUnit, "--property=Type=exec", "--",+ "/usr/bin/dockerd", "--host=unix://"+d.rootfulSock, "--data-root=/var/lib/pulse-rootful-docker", "--exec-root=/run/pulse-rootful-docker", "--pidfile=/run/pulse-rootful-docker.pid", "--storage-driver=vfs", "--iptables=false", "--bridge=none")+ } else {+ rootlessQualCommand(t, 20*time.Second, "systemd-run", "--quiet", "--collect", "--unit", d.rootfulUnit, "--property=Type=exec", "--",+ "/usr/bin/podman", "system", "service", "--time=0", "unix://"+d.rootfulSock)+ }+ rootlessQualWaitSocket(t, d.rootfulSock)+ rootlessQualCommand(t, 10*time.Second, "chmod", "0660", d.rootfulSock)+ rootlessQualRuntimePing(t, d, false)+}++func rootlessQualStartOtherRootless(t *testing.T, d rootlessQualDaemon) (string, string) {+ t.Helper()+ other := d+ if d.runtime == "docker" {+ other.runtime, other.rootlessUnit = "podman", "pulse-rootless-podman-ambiguity"+ other.rootlessSock = filepath.Join("/run/user", strconv.Itoa(d.uid), "podman", "podman.sock")+ } else {+ other.runtime, other.rootlessUnit = "docker", "pulse-rootless-docker-ambiguity"+ other.rootlessSock = filepath.Join("/run/user", strconv.Itoa(d.uid), "docker.sock")+ }+ rootlessQualStartRootless(t, other)+ return other.rootlessUnit, other.rootlessSock+}++func rootlessQualOtherUnit(runtimeKind string) string {+ if runtimeKind == "docker" {+ return "pulse-rootless-podman-ambiguity"+ }+ return "pulse-rootless-docker-ambiguity"+}++func rootlessQualCreateFixture(t *testing.T, d rootlessQualDaemon, rootless bool) {+ t.Helper()+ cli := rootlessQualCLI(d, rootless)+ rootlessQualCommand(t, 2*time.Minute, cli[0], append(cli[1:], "build", "--network=none", "-t", rootlessQualFixture, "-f", filepath.Join(d.home, "fixture", "Containerfile"), filepath.Join(d.home, "fixture"))...)+ rootlessQualCommand(t, 30*time.Second, cli[0], append(cli[1:], "run", "-d", "--name", rootlessQualRunningName, rootlessQualFixture, "sleep", "3600")...)+ if out, err := rootlessQualCommandError(30*time.Second, cli[0], append(cli[1:], "run", "--name", rootlessQualExitedName, rootlessQualFixture, "true")...); err != nil {+ t.Fatalf("create exited fixture: %v\n%s", err, out)+ }+}++func rootlessQualCLI(d rootlessQualDaemon, rootless bool) []string {+ if d.runtime == "docker" {+ host := d.rootfulSock+ if rootless {+ host = d.rootlessSock+ return []string{"runuser", "-u", "pulse-agent", "--", "env", "HOME=" + d.home, "XDG_RUNTIME_DIR=" + filepath.Dir(host), "DOCKER_HOST=unix://" + host, "docker"}+ }+ return []string{"docker", "--host", "unix://" + host}+ }+ host := d.rootfulSock+ if rootless {+ host = d.rootlessSock+ return []string{"runuser", "-u", "pulse-agent", "--", "env", "HOME=" + d.home, "XDG_RUNTIME_DIR=" + filepath.Join("/run/user", strconv.Itoa(d.uid)), "podman", "--url", "unix://" + host}+ }+ return []string{"podman", "--url", "unix://" + host}+}++func rootlessQualRuntimePing(t *testing.T, d rootlessQualDaemon, rootless bool) {+ t.Helper()+ cli := rootlessQualCLI(d, rootless)+ rootlessQualCommand(t, 30*time.Second, cli[0], append(cli[1:], "info")...)+}++func rootlessQualRuntimeBaseline(t *testing.T, d rootlessQualDaemon, rootless bool) rootlessQualBaseline {+ t.Helper()+ cli := rootlessQualCLI(d, rootless)+ format := "{{.Names}}|{{.Image}}|{{.State}}"+ out := rootlessQualCommand(t, 30*time.Second, cli[0], append(cli[1:], "ps", "-a", "--format", format)...)+ lines := strings.Split(strings.TrimSpace(out), "\n")+ var normalized []string+ for _, line := range lines {+ line = strings.TrimSpace(strings.TrimPrefix(line, "/"))+ if line != "" {+ normalized = append(normalized, line)+ }+ }+ sort.Strings(normalized)+ return rootlessQualBaseline{Count: len(normalized), SemanticDigest: rootlessQualHashJSON(normalized)}+}++func rootlessQualWaitDirect(t *testing.T, fixture *secureRuntimeLabFixture, after time.Time, runtimeKind string, timeout time.Duration) secureRuntimeDockerReport {+ t.Helper()+ return rootlessQualWaitReport(t, fixture, after, timeout, func(report agentsdocker.Report) bool {+ return rootlessQualComplete(report) && report.Host.CollectionMode != agentsdocker.CollectionModeTypedHelperSummary && report.Host.Runtime == runtimeKind && len(report.Containers) == 2+ })+}++func rootlessQualWaitReport(t *testing.T, fixture *secureRuntimeLabFixture, after time.Time, timeout time.Duration, predicate func(agentsdocker.Report) bool) secureRuntimeDockerReport {+ t.Helper()+ deadline := time.Now().Add(timeout)+ for time.Now().Before(deadline) {+ for _, candidate := range fixture.dockerSnapshot() {+ if candidate.ReceivedAt.After(after) && predicate(candidate.Report) {+ return candidate+ }+ }+ time.Sleep(200 * time.Millisecond)+ }+ t.Fatalf("timed out waiting for container report after %s", after.Format(time.RFC3339Nano))+ return secureRuntimeDockerReport{}+}++func rootlessQualComplete(report agentsdocker.Report) bool {+ return report.InventoryComplete == nil || *report.InventoryComplete+}++func rootlessQualAssertHelperSummaryOnly(t *testing.T, report agentsdocker.Report, runtimeKind string) {+ t.Helper()+ if report.InventoryComplete == nil || !*report.InventoryComplete {+ t.Fatal("typed-helper runtime summary did not declare complete inventory")+ }+ if report.Host.Runtime != runtimeKind || report.Host.CollectionMode != agentsdocker.CollectionModeTypedHelperSummary {+ t.Fatalf("typed-helper collection posture = runtime:%q mode:%q", report.Host.Runtime, report.Host.CollectionMode)+ }+ if len(report.Images) != 0 || len(report.Volumes) != 0 || len(report.Networks) != 0 || len(report.Services) != 0 || len(report.Tasks) != 0 || len(report.Nodes) != 0 || len(report.Secrets) != 0 || len(report.Configs) != 0 || report.StorageUsage != nil {+ t.Fatal("typed-helper runtime summary fabricated unsupported secondary inventories")+ }+ for _, container := range report.Containers {+ if container.ImageDigest != "" || container.Health != "" || len(container.HealthcheckTargets) != 0 || container.CPUPercent != 0 || container.MemoryUsageBytes != 0 || container.MemoryLimitBytes != 0 || container.MemoryPercent != 0 || container.UptimeSeconds != 0 || container.RestartCount != 0 || container.ExitCode != 0 || container.OOMKilled != nil || container.StartedAt != nil || container.FinishedAt != nil || len(container.Ports) != 0 || len(container.Labels) != 0 || len(container.Env) != 0 || len(container.Networks) != 0 || container.NetworkRXBytes != 0 || container.NetworkTXBytes != 0 || container.WritableLayerBytes != 0 || container.RootFilesystemBytes != 0 || container.BlockIO != nil || len(container.Mounts) != 0 || container.Podman != nil || container.UpdateStatus != nil {+ t.Fatalf("typed-helper container %q escaped the summary-only boundary: %+v", container.ID, container)+ }+ }+}++func rootlessQualDigestReport(report agentsdocker.Report) rootlessQualReportDigest {+ type semantic struct{ Name, Image, State string }+ type stats struct {+ Name string+ MemoryLimited bool+ OOMKnown bool+ RuntimeDetails bool+ }+ semanticRows := make([]semantic, 0, len(report.Containers))+ statsRows := make([]stats, 0, len(report.Containers))+ fullFieldsPresent := len(report.Containers) > 0+ runningStatsPresent := false+ for _, item := range report.Containers {+ semanticRows = append(semanticRows, semantic{Name: item.Name, Image: item.Image, State: item.State})+ statsRows = append(statsRows, stats{Name: item.Name, MemoryLimited: item.MemoryLimitBytes > 0, OOMKnown: item.OOMKilled != nil, RuntimeDetails: item.StartedAt != nil || item.FinishedAt != nil})+ if item.CreatedAt.IsZero() || item.Status == "" || item.OOMKilled == nil || (item.StartedAt == nil && item.FinishedAt == nil) {+ fullFieldsPresent = false+ }+ if strings.EqualFold(item.State, "running") && (item.MemoryUsageBytes > 0 || item.MemoryLimitBytes > 0 || item.CPUPercent != 0 || item.NetworkRXBytes > 0 || item.NetworkTXBytes > 0 || item.BlockIO != nil) {+ runningStatsPresent = true+ }+ }+ sort.Slice(semanticRows, func(i, j int) bool { return semanticRows[i].Name < semanticRows[j].Name })+ sort.Slice(statsRows, func(i, j int) bool { return statsRows[i].Name < statsRows[j].Name })+ imageNames := make([]string, 0, len(report.Images))+ for _, image := range report.Images {+ imageNames = append(imageNames, strings.Join(image.RepoTags, ","))+ }+ volumeNames := make([]string, 0, len(report.Volumes))+ for _, volume := range report.Volumes {+ volumeNames = append(volumeNames, volume.Name)+ }+ networkNames := make([]string, 0, len(report.Networks))+ for _, network := range report.Networks {+ networkNames = append(networkNames, network.Name)+ }+ sort.Strings(imageNames)+ sort.Strings(volumeNames)+ sort.Strings(networkNames)+ secondary := map[string]any{"images": imageNames, "volumes": volumeNames, "networks": networkNames}+ inventory := map[string]any{"containers": semanticRows, "runtime": report.Host.Runtime, "mode": report.Host.CollectionMode}+ return rootlessQualReportDigest{+ Count: len(report.Containers), InventoryDigest: rootlessQualHashJSON(inventory), SemanticDigest: rootlessQualHashJSON(semanticRows),+ StatsDigest: rootlessQualHashJSON(statsRows), StatsPresent: runningStatsPresent,+ FullFieldsPresent: fullFieldsPresent, SecondaryDigest: rootlessQualHashJSON(secondary),+ SecondaryInventoryPresent: len(report.Images) > 0 && len(report.Networks) > 0,+ }+}++func rootlessQualSemanticDigest(report agentsdocker.Report) string {+ return rootlessQualDigestReport(report).SemanticDigest+}++func rootlessQualStableDigestEqual(left, right rootlessQualReportDigest) bool {+ return left.Count == right.Count && left.InventoryDigest == right.InventoryDigest &&+ left.SemanticDigest == right.SemanticDigest && left.SecondaryDigest == right.SecondaryDigest &&+ left.StatsPresent && right.StatsPresent+}++func rootlessQualHashJSON(value any) string {+ raw, err := json.Marshal(value)+ if err != nil {+ panic(err)+ }+ sum := sha256.Sum256(raw)+ return hex.EncodeToString(sum[:])+}++func rootlessQualDaemonID(t *testing.T, d rootlessQualDaemon, rootless bool) string {+ t.Helper()+ cli := rootlessQualCLI(d, rootless)+ if d.runtime == "docker" {+ return rootlessQualCommand(t, 30*time.Second, cli[0], append(cli[1:], "info", "--format", "{{.ID}}")...)+ }+ info := rootlessQualCommand(t, 30*time.Second, cli[0], append(cli[1:], "info", "--format", "json")...)+ var decoded map[string]any+ if err := json.Unmarshal([]byte(info), &decoded); err != nil {+ t.Fatalf("decode podman info: %v", err)+ }+ store, _ := decoded["store"].(map[string]any)+ identity := map[string]any{"graphRoot": store["graphRoot"], "runRoot": store["runRoot"], "runtime": d.runtime}+ return rootlessQualHashJSON(identity)+}++func rootlessQualDaemonRootless(t *testing.T, d rootlessQualDaemon) bool {+ t.Helper()+ cli := rootlessQualCLI(d, true)+ if d.runtime == "docker" {+ securityOptions := rootlessQualCommand(t, 30*time.Second, cli[0], append(cli[1:], "info", "--format", "{{json .SecurityOptions}}")...)+ return strings.Contains(strings.ToLower(securityOptions), "rootless")+ }+ rootless := rootlessQualCommand(t, 30*time.Second, cli[0], append(cli[1:], "info", "--format", "{{.Host.Security.Rootless}}")...)+ return strings.EqualFold(strings.TrimSpace(rootless), "true")+}++func rootlessQualUnitIdentity(t *testing.T, unit string) (int, string) {+ t.Helper()+ pidText := rootlessQualCommand(t, 10*time.Second, "systemctl", "show", unit, "--property=MainPID", "--value")+ pid, err := strconv.Atoi(pidText)+ if err != nil || pid <= 1 {+ t.Fatalf("unit %s returned invalid MainPID %q", unit, pidText)+ }+ invocation := rootlessQualCommand(t, 10*time.Second, "systemctl", "show", unit, "--property=InvocationID", "--value")+ if len(invocation) != 32 {+ t.Fatalf("unit %s returned invalid InvocationID %q", unit, invocation)+ }+ return pid, invocation+}++func rootlessQualRunUnpinnedCollector(t *testing.T, serverURL string, duration time.Duration) string {+ t.Helper()+ protectedPID := secureRuntimeCollectorMainPID(t)+ stateDir, err := os.MkdirTemp("/tmp", "pulse-unpinned-probe-")+ if err != nil {+ t.Fatal(err)+ }+ defer os.RemoveAll(stateDir)+ collectorUID := rootlessQualUID(t, "pulse-agent")+ collectorGID := rootlessQualGID(t, "pulse-agent")+ if err := os.Chown(stateDir, collectorUID, collectorGID); err != nil {+ t.Fatalf("chown ambiguity probe state: %v", err)+ }+ if err := os.Chmod(stateDir, 0o700); err != nil {+ t.Fatalf("chmod ambiguity probe state: %v", err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), duration)+ defer cancel()+ cmd := exec.CommandContext(ctx, "runuser", "-u", "pulse-agent", "--", "env", "-u", "DOCKER_HOST", "-u", "PODMAN_HOST", "-u", "CONTAINER_HOST",+ "PULSE_URL="+serverURL, "PULSE_TOKEN="+secureRuntimeLabToken, "PULSE_INTERVAL=1s", "PULSE_AGENT_ID="+secureRuntimeLabAgentID,+ "PULSE_HOSTNAME="+secureRuntimeLabHostname, "PULSE_ENABLE_HOST=false", "PULSE_ENABLE_DOCKER=true", "PULSE_ENABLE_COMMANDS=false",+ "PULSE_AGENT_ALLOW_PLAINTEXT_HTTP=true", "/usr/local/bin/pulse-agent", "--state-dir", stateDir, "--health-addr", "")+ out, err := cmd.CombinedOutput()+ if err == nil || !errors.Is(ctx.Err(), context.DeadlineExceeded) {+ t.Fatalf("unpinned ambiguity probe did not remain alive until bounded cancellation: err=%v\n%s", err, out)+ }+ if afterPID := secureRuntimeCollectorMainPID(t); afterPID != protectedPID {+ t.Fatalf("separate ambiguity probe disturbed protected collector: before=%d after=%d", protectedPID, afterPID)+ }+ return string(out)+}++func rootlessQualServicePin(t *testing.T, runtimeKind string) string {+ t.Helper()+ environment := secureRuntimeSystemdProperty(t, "Environment")+ key := "DOCKER_HOST=unix://"+ if runtimeKind == "podman" {+ key = "CONTAINER_HOST=unix://"+ }+ for _, field := range strings.Fields(environment) {+ field = strings.Trim(field, `"`)+ if strings.HasPrefix(field, key) {+ return strings.TrimPrefix(field, key)+ }+ }+ t.Fatalf("collector unit lacks %s pin: %s", key, environment)+ return ""+}++func rootlessQualRootfulAccessDenied(t *testing.T, d rootlessQualDaemon) bool {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, "runuser", "-u", "pulse-agent", "--", "curl", "-fsS", "--max-time", "2", "--unix-socket", d.rootfulSock, "http://runtime/_ping")+ return cmd.Run() != nil+}++func rootlessQualDualSocketEvidence(t *testing.T, uid int) []map[string]any {+ t.Helper()+ result := make([]map[string]any, 0, 2)+ for _, item := range []struct{ runtime, path string }{+ {"docker", filepath.Join("/run/user", strconv.Itoa(uid), "docker.sock")},+ {"podman", filepath.Join("/run/user", strconv.Itoa(uid), "podman", "podman.sock")},+ } {+ socketUID, socketGID, mode := rootlessQualSocketIdentity(t, item.path)+ result = append(result, map[string]any{+ "runtime": item.runtime, "path": item.path, "uid": socketUID, "gid": socketGID,+ "mode": mode, "type": "unix", "symlink": false,+ })+ _ = os.Remove(item.path + ".qualification-identity")+ }+ return result+}++func rootlessQualAssertHelperNetworkDenied(t *testing.T) bool {+ t.Helper()+ rootlessQualCommand(t, 10*time.Second, "ip", "link", "add", "pulse-rootless-canary", "type", "dummy")+ t.Cleanup(func() { _ = exec.Command("ip", "link", "del", "pulse-rootless-canary").Run() })+ rootlessQualCommand(t, 10*time.Second, "ip", "address", "add", "192.0.2.1/32", "dev", "pulse-rootless-canary")+ rootlessQualCommand(t, 10*time.Second, "ip", "link", "set", "pulse-rootless-canary", "up")+ observations := secureRuntimeAssertHelperOutboundNetworkDenied(t)+ return observations["helper_namespace_connection"] == "denied" && observations["host_canary_reachable"] == true+}++func rootlessQualCaptureIdentity(t *testing.T, d rootlessQualDaemon) {+ t.Helper()+ uid, gid, mode := rootlessQualSocketIdentity(t, d.rootlessSock)+ cli := rootlessQualCLI(d, true)+ version := rootlessQualCommand(t, 30*time.Second, cli[0], append(cli[1:], "version", "--format", "{{.Server.Version}}")...)+ if d.runtime == "podman" {+ version = rootlessQualCommand(t, 30*time.Second, cli[0], append(cli[1:], "version", "--format", "{{.Server.Version}}")...)+ }+ rootlessQualWriteJSON(t, d.rootlessSock+".qualification-identity", rootlessQualIdentity{RuntimeVersion: version, SocketUID: uid, SocketGID: gid, SocketMode: mode})+}++func rootlessQualReadIdentityRecord(t *testing.T, d rootlessQualDaemon) rootlessQualIdentity {+ t.Helper()+ path := d.rootlessSock + ".qualification-identity"+ raw := rootlessQualReadFile(t, path)+ var identity rootlessQualIdentity+ if err := json.Unmarshal(raw, &identity); err != nil {+ t.Fatalf("decode runtime identity: %v", err)+ }+ return identity+}++func rootlessQualSocketIdentity(t *testing.T, path string) (int, int, string) {+ t.Helper()+ info, err := os.Lstat(path)+ if err != nil {+ t.Fatalf("inspect socket identity %s: %v", path, err)+ }+ if info.Mode()&os.ModeSocket == 0 || info.Mode()&os.ModeSymlink != 0 || info.Mode().Perm()&0o600 != 0o600 || info.Mode().Perm()&0o006 != 0 {+ t.Fatalf("unsafe rootless socket mode at %s: %s", path, info.Mode())+ }+ stat, ok := info.Sys().(*syscall.Stat_t)+ if !ok {+ t.Fatalf("socket %s lacks Unix stat identity", path)+ }+ return int(stat.Uid), int(stat.Gid), fmt.Sprintf("%04o", info.Mode().Perm())+}++func rootlessQualArtifactIdentities(t *testing.T, installerPath string) rootlessQualArtifacts {+ t.Helper()+ executable, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ collectorPath := strings.TrimSpace(os.Getenv("PULSE_SECURE_RUNTIME_COLLECTOR"))+ helperPath := strings.TrimSpace(os.Getenv("PULSE_SECURE_RUNTIME_HELPER"))+ return rootlessQualArtifacts{+ QualificationTest: rootlessQualGoArtifact(t, executable, "dockeragent.test"),+ Collector: rootlessQualGoArtifact(t, collectorPath, "pulse-agent"),+ Helper: rootlessQualGoArtifact(t, helperPath, "pulse-agent-helper"),+ Installer: rootlessQualInstallerArtifact{+ PathBasename: filepath.Base(installerPath), SHA256: secureRuntimeHash(rootlessQualReadFile(t, installerPath)),+ },+ }+}++func rootlessQualGoArtifact(t *testing.T, path, basename string) rootlessQualArtifact {+ t.Helper()+ info, err := buildinfo.ReadFile(path)+ if err != nil {+ t.Fatalf("read Go build metadata for %s: %v", path, err)+ }+ artifact := rootlessQualArtifact{+ PathBasename: filepath.Base(path), SHA256: secureRuntimeHash(rootlessQualReadFile(t, path)),+ Package: info.Path, GoVersion: info.GoVersion,+ }+ for _, setting := range info.Settings {+ switch setting.Key {+ case "vcs.revision":+ artifact.VCSRevision = setting.Value+ case "vcs.modified":+ artifact.VCSModified = setting.Value == "true"+ }+ }+ wantCommit := strings.TrimSpace(os.Getenv("PULSE_ROOTLESS_SOURCE_COMMIT"))+ if artifact.PathBasename != basename || artifact.Package == "" || artifact.VCSRevision != wantCommit || artifact.VCSModified {+ t.Fatalf("qualification artifact is not an exact clean source build: %+v", artifact)+ }+ return artifact+}++func rootlessQualSourceHashes(t *testing.T) map[string]string {+ t.Helper()+ path := strings.TrimSpace(os.Getenv("PULSE_ROOTLESS_SOURCE_HASHES"))+ if !filepath.IsAbs(path) {+ t.Fatalf("PULSE_ROOTLESS_SOURCE_HASHES must be absolute: %q", path)+ }+ var hashes map[string]string+ if err := json.Unmarshal(rootlessQualReadFile(t, path), &hashes); err != nil {+ t.Fatalf("decode source hashes: %v", err)+ }+ if len(hashes) == 0 {+ t.Fatal("source hash map is empty")+ }+ return hashes+}++func rootlessQualUninstallPulse(t *testing.T, installerPath, serverURL string) {+ t.Helper()+ secureRuntimeRunInstaller(t, installerPath, serverURL, "--uninstall")+}++func rootlessQualAssertPulseRemoved(t *testing.T) {+ t.Helper()+ for _, path := range secureRuntimeInstalledPaths {+ if _, err := os.Lstat(path); err == nil {+ t.Fatalf("Pulse cleanup left %s", path)+ } else if !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("inspect cleanup path %s: %v", path, err)+ }+ }+}++func rootlessQualRemoveRuntimeState(t *testing.T, d rootlessQualDaemon) {+ t.Helper()+ for _, path := range []string{d.home, filepath.Join("/run/user", strconv.Itoa(d.uid)), "/var/lib/pulse-rootful-docker", "/var/lib/containers/storage"} {+ if err := os.RemoveAll(path); err != nil {+ t.Fatalf("remove runtime state %s: %v", path, err)+ }+ }+}++func rootlessQualUserStateClean(d rootlessQualDaemon) bool {+ for _, path := range []string{d.home, filepath.Join("/run/user", strconv.Itoa(d.uid)), "/var/lib/pulse-rootful-docker", "/var/lib/containers/storage"} {+ if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) {+ return false+ }+ }+ return true+}++func rootlessQualStopUnit(t *testing.T, unit string) {+ t.Helper()+ rootlessQualCommand(t, 30*time.Second, "systemctl", "stop", unit)+ rootlessQualCommand(t, 30*time.Second, "systemctl", "reset-failed", unit)+}++func rootlessQualBestEffortStop(units ...string) {+ for _, unit := range units {+ if unit != "" {+ _ = exec.Command("systemctl", "stop", unit).Run()+ _ = exec.Command("systemctl", "reset-failed", unit).Run()+ }+ }+}++func rootlessQualWaitSocket(t *testing.T, path string) {+ t.Helper()+ deadline := time.Now().Add(45 * time.Second)+ for time.Now().Before(deadline) {+ if info, err := os.Lstat(path); err == nil && info.Mode()&os.ModeSocket != 0 && info.Mode()&os.ModeSymlink == 0 {+ return+ }+ time.Sleep(200 * time.Millisecond)+ }+ t.Fatalf("runtime socket did not appear: %s", path)+}++func rootlessQualUID(t *testing.T, user string) int {+ t.Helper()+ uidText := rootlessQualCommand(t, 10*time.Second, "id", "-u", user)+ uid, err := strconv.Atoi(uidText)+ if err != nil {+ t.Fatalf("parse UID %q: %v", uidText, err)+ }+ return uid+}++func rootlessQualGID(t *testing.T, user string) int {+ t.Helper()+ gidText := rootlessQualCommand(t, 10*time.Second, "id", "-g", user)+ gid, err := strconv.Atoi(gidText)+ if err != nil {+ t.Fatalf("parse GID %q: %v", gidText, err)+ }+ return gid+}++func rootlessQualWriteSubID(t *testing.T, path, line string) {+ t.Helper()+ raw, err := os.ReadFile(path)+ if err != nil && !errors.Is(err, os.ErrNotExist) {+ t.Fatal(err)+ }+ if strings.Contains(string(raw), strings.SplitN(line, ":", 2)[0]+":") {+ return+ }+ f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)+ if err != nil {+ t.Fatal(err)+ }+ defer f.Close()+ if _, err := fmt.Fprintln(f, line); err != nil {+ t.Fatal(err)+ }+}++func rootlessQualCommand(t *testing.T, timeout time.Duration, name string, args ...string) string {+ t.Helper()+ out, err := rootlessQualCommandError(timeout, name, args...)+ if err != nil {+ t.Fatalf("%s %s: %v\n%s", name, strings.Join(args, " "), err, out)+ }+ return strings.TrimSpace(out)+}++func rootlessQualCommandError(timeout time.Duration, name string, args ...string) (string, error) {+ ctx, cancel := context.WithTimeout(context.Background(), timeout)+ defer cancel()+ out, err := exec.CommandContext(ctx, name, args...).CombinedOutput()+ if ctx.Err() != nil {+ return string(out), fmt.Errorf("command timed out: %w", ctx.Err())+ }+ return string(out), err+}++func rootlessQualReadFile(t *testing.T, path string) []byte {+ t.Helper()+ f, err := os.Open(path)+ if err != nil {+ t.Fatal(err)+ }+ defer f.Close()+ raw, err := io.ReadAll(io.LimitReader(f, 64<<20))+ if err != nil {+ t.Fatal(err)+ }+ return raw+}++func rootlessQualWriteJSON(t *testing.T, path string, value any) {+ t.Helper()+ raw, err := json.MarshalIndent(value, "", " ")+ if err != nil {+ t.Fatal(err)+ }+ tmp := path + ".tmp"+ if err := os.WriteFile(tmp, append(raw, '\n'), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.Rename(tmp, path); err != nil {+ t.Fatal(err)+ }+}++func rootlessQualValidateReceipt(receipt rootlessQualReceipt, wantRuns int) error {+ if receipt.SchemaVersion != 1 || receipt.Kind != "pulse-secure-runtime-rootless-qualification" || receipt.Result != "passed" {+ return errors.New("invalid top-level qualification identity")+ }+ if len(receipt.SourceCommit) != 40 || len(receipt.Runs) != wantRuns || receipt.Artifacts.QualificationTest.PathBasename != "dockeragent.test" || receipt.Artifacts.QualificationTest.VCSModified || len(receipt.SourceHashes) == 0 {+ return errors.New("invalid source, artifact, or runtime binding")+ }+ seen := map[string]bool{}+ for _, run := range receipt.Runs {+ rt := run.Runtime+ if seen[rt.Runtime] || (rt.Runtime != "docker" && rt.Runtime != "podman") || !rt.DaemonRootless || rt.CollectorUID <= 0 || rt.SocketUID != rt.CollectorUID || rt.SocketPath == "" || rt.DaemonID == "" || rt.SocketType != "unix" || rt.SocketSymlink {+ return fmt.Errorf("invalid runtime identity for %q", rt.Runtime)+ }+ seen[rt.Runtime] = true+ if rt.SocketMode != "0600" && rt.SocketMode != "0660" {+ return fmt.Errorf("runtime %s socket mode is not owner-private", rt.Runtime)+ }+ if len(run.Scenarios) != len(rootlessQualScenarioOrder) {+ return fmt.Errorf("runtime %s scenario count = %d", rt.Runtime, len(run.Scenarios))+ }+ for i, scenario := range run.Scenarios {+ if scenario.Name != rootlessQualScenarioOrder[i] || scenario.Result != "passed" || scenario.StartedAt == "" || scenario.CompletedAt == "" || len(scenario.Evidence) == 0 {+ return fmt.Errorf("runtime %s scenario %d is invalid", rt.Runtime, i)+ }+ reportExpected := scenario.Name != "dual_socket_ambiguity_refusal" && scenario.Name != "authority_isolation" && scenario.Name != "cleanup"+ if reportExpected != (scenario.ReportSequence != nil && scenario.ReportStreamID != nil && *scenario.ReportStreamID != "") {+ return fmt.Errorf("runtime %s scenario %s report binding is invalid", rt.Runtime, scenario.Name)+ }+ }+ }+ return nil+}++func TestRootlessQualificationReceiptContract(t *testing.T) {+ now := time.Now().UTC().Format(time.RFC3339Nano)+ sequence := uint64(1)+ scenarios := make([]rootlessQualScenario, 0, len(rootlessQualScenarioOrder))+ for _, name := range rootlessQualScenarioOrder {+ scenario := rootlessQualScenario{Name: name, Result: "passed", StartedAt: now, CompletedAt: now, Evidence: map[string]any{"observed": true}}+ if name != "dual_socket_ambiguity_refusal" && name != "authority_isolation" && name != "cleanup" {+ scenario.ReportSequence = &sequence+ stream := "stream"+ scenario.ReportStreamID = &stream+ }+ scenarios = append(scenarios, scenario)+ }+ receipt := rootlessQualReceipt{+ SchemaVersion: 1, Kind: "pulse-secure-runtime-rootless-qualification", Result: "passed", SourceCommit: strings.Repeat("a", 40),+ SourceHashes: map[string]string{"source.go": strings.Repeat("b", 64)},+ Artifacts: rootlessQualArtifacts{QualificationTest: rootlessQualArtifact{PathBasename: "dockeragent.test", VCSRevision: strings.Repeat("a", 40)}},+ Runs: []rootlessQualRun{{Runtime: rootlessQualRuntime{Runtime: "docker", DaemonID: "daemon", CollectorUID: 1000, SocketUID: 1000, SocketMode: "0600", SocketPath: "/run/user/1000/docker.sock", SocketType: "unix", DaemonRootless: true}, Scenarios: scenarios}},+ }+ if err := rootlessQualValidateReceipt(receipt, 1); err != nil {+ t.Fatal(err)+ }+ receipt.Runs[0].Scenarios[3].ReportSequence = nil+ if err := rootlessQualValidateReceipt(receipt, 1); err == nil {+ t.Fatal("receipt validator accepted a report-producing scenario without a sequence")+ }+}++func TestRootlessQualificationGoSchemaPassesPythonValidator(t *testing.T) {+ commit := strings.Repeat("a", 40)+ digest := strings.Repeat("b", 64)+ started := time.Date(2026, 9, 1, 10, 0, 0, 0, time.UTC)+ receipt := rootlessQualReceipt{+ SchemaVersion: 1, Kind: "pulse-secure-runtime-rootless-qualification", Result: "passed",+ SourceCommit: commit, StartedAt: started.Format(time.RFC3339Nano),+ CompletedAt: started.Add(2 * time.Minute).Format(time.RFC3339Nano),+ SourceHashes: map[string]string{"internal/dockeragent/agent.go": digest, "scripts/install.sh": digest},+ Artifacts: rootlessQualArtifacts{+ QualificationTest: rootlessQualArtifact{PathBasename: "dockeragent.test", SHA256: digest, Package: "github.com/rcourtman/pulse-go-rewrite/scripts/installtests.test", GoVersion: "go1.25.0", VCSRevision: commit},+ Collector: rootlessQualArtifact{PathBasename: "pulse-agent", SHA256: digest, Package: "github.com/rcourtman/pulse-go-rewrite/cmd/pulse-agent", GoVersion: "go1.25.0", VCSRevision: commit},+ Helper: rootlessQualArtifact{PathBasename: "pulse-agent-helper", SHA256: digest, Package: "github.com/rcourtman/pulse-go-rewrite/cmd/pulse-agent-helper", GoVersion: "go1.25.0", VCSRevision: commit},+ Installer: rootlessQualInstallerArtifact{PathBasename: "install.sh", SHA256: digest},+ },+ }+ for index, runtimeKind := range []string{"docker", "podman"} {+ receipt.Runs = append(receipt.Runs, rootlessQualValidatorFixtureRun(runtimeKind, 1000, index, started.Add(time.Duration(index)*time.Minute), digest))+ }+ path := filepath.Join(t.TempDir(), "receipt.json")+ rootlessQualWriteJSON(t, path, receipt)+ validator := repoFile("scripts", "release_control", "secure_runtime_rootless_attestation_v1.py")+ program := `import importlib.util, pathlib, sys+spec=importlib.util.spec_from_file_location("validator", pathlib.Path(sys.argv[1]))+module=importlib.util.module_from_spec(spec); spec.loader.exec_module(module)+module.parse_receipt_bytes(pathlib.Path(sys.argv[2]).read_bytes())+`+ cmd := exec.Command("python3", "-I", "-c", program, validator, path)+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("Go receipt schema failed the real Python validator: %v\n%s", err, output)+ }+}++func rootlessQualValidatorFixtureRun(runtimeKind string, uid, index int, began time.Time, digest string) rootlessQualRun {+ socketPath := filepath.Join("/run/user", strconv.Itoa(uid), "docker.sock")+ if runtimeKind == "podman" {+ socketPath = filepath.Join("/run/user", strconv.Itoa(uid), "podman", "podman.sock")+ }+ daemonID := runtimeKind + "-daemon"+ direct := func(pid int) map[string]any {+ return map[string]any{+ "collector_pid": pid, "service_pid": pid, "collection_path": "collector-owned-rootless-socket",+ "inventory_complete": true, "inventory_count": 2, "semantic_sha256": digest,+ "full_fields_present": true, "stats_present": true, "secondary_structure_sha256": digest,+ "daemon_id": daemonID, "daemon_rootless": true, "socket_path": socketPath,+ "socket_uid": uid, "socket_gid": uid, "socket_mode": "0600", "socket_type": "unix", "socket_symlink": false,+ }+ }+ stream := func(value string) *string { return &value }+ sequence := func(value uint64) *uint64 { return &value }+ makeScenario := func(offset int, name string, streamID *string, seq *uint64, evidence map[string]any) rootlessQualScenario {+ start := began.Add(time.Duration(offset) * time.Second)+ return rootlessQualScenario{Name: name, Result: "passed", StartedAt: start.Format(time.RFC3339Nano), CompletedAt: start.Add(time.Second).Format(time.RFC3339Nano), ReportStreamID: streamID, ReportSequence: seq, Evidence: evidence}+ }+ fresh := direct(100 + index*10)+ migration := direct(101 + index*10)+ migration["legacy_profile"] = "root-command-capable"+ migration["target_profile"] = "typed-helper-monitoring-only"+ migration["authority_reduced"] = true+ migration["legacy_collector_pid"] = 150 + index*10+ restart := direct(102 + index*10)+ restart["previous_collector_pid"] = 101 + index*10+ restart["previous_report_stream_id"] = fmt.Sprintf("%s-migration-%d", runtimeKind, index)+ daemon := direct(102 + index*10)+ daemon["previous_daemon_pid"] = 200 + index*10+ daemon["daemon_pid"] = 201 + index*10+ daemon["previous_daemon_invocation_id"] = fmt.Sprintf("%s-old-invocation", runtimeKind)+ daemon["daemon_invocation_id"] = fmt.Sprintf("%s-new-invocation", runtimeKind)+ fallback := map[string]any{+ "collector_pid": 102 + index*10, "collection_mode": "typed-helper-summary", "direct_runtime_available": false,+ "helper_fallback": true, "inventory_complete": true, "inventory_count": 2, "rootful_baseline_inventory_count": 2,+ "semantic_sha256": digest, "rootful_baseline_semantic_sha256": digest, "full_fields_present": false,+ "stats_present": false, "secondary_structure_sha256": "", "container_actions_enabled": false,+ "container_updates_enabled": false, "collector_restart_count": 0,+ }+ liveSockets := []map[string]any{+ {"runtime": "docker", "path": filepath.Join("/run/user", strconv.Itoa(uid), "docker.sock"), "uid": uid, "gid": uid, "mode": "0600", "type": "unix", "symlink": false},+ {"runtime": "podman", "path": filepath.Join("/run/user", strconv.Itoa(uid), "podman", "podman.sock"), "uid": uid, "gid": uid, "mode": "0600", "type": "unix", "symlink": false},+ }+ ambiguity := map[string]any{+ "protected_collector_pid": 102 + index*10, "live_sockets": liveSockets,+ "probe_kind": "separate-unpinned-collector", "admission_refused": true, "fail_closed": true,+ "daemon_probe_count": 0, "container_actions_enabled": false, "collector_restart_count": 0,+ }+ pin := direct(103 + index*10)+ pin["previous_collector_pid"] = 102 + index*10+ pin["previous_report_stream_id"] = fmt.Sprintf("%s-restart-%d", runtimeKind, index)+ pin["pin_source"] = "root-owned-systemd-unit"+ pin["pinned_socket_path"] = socketPath+ pin["socket_absent_observed"] = true+ pin["fallback_report_sequence"] = 1+ pin["recovery_report_sequence"] = 2+ pin["recovered_socket_path"] = socketPath+ pin["selected_socket_path"] = socketPath+ pin["recovered_socket_uid"] = uid+ pin["recovered_socket_gid"] = uid+ pin["recovered_socket_mode"] = "0600"+ pin["recovered_socket_type"] = "unix"+ pin["recovered_socket_symlink"] = false+ pin["candidate_count"] = 1+ pin["daemon_probe_count"] = 1+ pin["collector_restart_count"] = 1+ parity := map[string]any{+ "collector_pid": 103 + index*10, "baseline_kind": "root-client-same-rootless-daemon",+ "baseline_inventory_count": 2, "collector_inventory_count": 2,+ "baseline_semantic_sha256": digest, "collector_semantic_sha256": digest,+ "collector_full_fields_present": true, "collector_stats_present": true,+ "collector_secondary_inventory_present": true,+ }+ authority := map[string]any{+ "collector_pid": 103 + index*10, "collector_uid": uid, "effective_uid": uid, "effective_root": false,+ "safe_profile_enabled": true, "commands_enabled": false, "privileged_helper_enabled": true,+ "reduction_request_observed": true, "collector_command_transport_present": false,+ "collector_command_session_present": false, "container_actions_enabled": false, "container_updates_enabled": false,+ "rootful_socket_access": false, "helper_network_access": false,+ }+ run := rootlessQualRun{+ Host: rootlessQualHost{MachineID: fmt.Sprintf("machine-%s", runtimeKind), Architecture: "amd64", Kernel: "Linux fixture", SystemdVersion: "systemd 255"},+ Runtime: rootlessQualRuntime{Runtime: runtimeKind, RuntimeVersion: "1.0.0", DaemonID: daemonID, CollectorUID: uid, SocketPath: socketPath, SocketUID: uid, SocketGID: uid, SocketMode: "0600", SocketType: "unix", DaemonRootless: true},+ }+ run.Scenarios = []rootlessQualScenario{+ makeScenario(0, "fresh_install", stream(fmt.Sprintf("%s-fresh-%d", runtimeKind, index)), sequence(1), fresh),+ makeScenario(2, "legacy_migration", stream(fmt.Sprintf("%s-migration-%d", runtimeKind, index)), sequence(1), migration),+ makeScenario(4, "collector_restart", stream(fmt.Sprintf("%s-restart-%d", runtimeKind, index)), sequence(1), restart),+ makeScenario(6, "daemon_restart", stream(fmt.Sprintf("%s-restart-%d", runtimeKind, index)), sequence(2), daemon),+ makeScenario(8, "socket_loss_helper_fallback", stream(fmt.Sprintf("%s-restart-%d", runtimeKind, index)), sequence(3), fallback),+ makeScenario(10, "direct_recovery", stream(fmt.Sprintf("%s-restart-%d", runtimeKind, index)), sequence(4), direct(102+index*10)),+ makeScenario(12, "dual_socket_ambiguity_refusal", nil, nil, ambiguity),+ makeScenario(14, "exact_pin_recovery", stream(fmt.Sprintf("%s-update-%d", runtimeKind, index)), sequence(2), pin),+ makeScenario(16, "telemetry_parity", stream(fmt.Sprintf("%s-update-%d", runtimeKind, index)), sequence(3), parity),+ makeScenario(18, "authority_isolation", nil, nil, authority),+ makeScenario(20, "cleanup", nil, nil, map[string]any{"runtime_stopped": true, "socket_absent": true, "fixtures_removed": true, "user_state_clean": true}),+ }+ return run+}++func TestRootlessQualificationGuardAndWrapperInvariants(t *testing.T) {+ if rootlessQualHasDefaultRoute("Iface Destination Gateway\neth0 00000000 0100007F") != true || rootlessQualHasDefaultRoute("Iface Destination Gateway\nlo 0000007F 00000000") {+ t.Fatal("default-route refusal parser drifted")+ }+ raw, err := os.ReadFile(repoFile("scripts", "run-secure-runtime-rootless-qualification.sh"))+ if err != nil {+ t.Fatal(err)+ }+ script := string(raw)+ for _, required := range []string{+ `PULSE_ROOTLESS_UBUNTU_IMAGE`, `^ubuntu@sha256:`, `--network none`, `--tmpfs /run`,+ `PULSE_SECURE_RUNTIME_ROOTLESS_QUALIFICATION=disposable-v1`, `dockeragent.test`,+ `run_runtime docker`, `run_runtime podman`, `PULSE_ROOTLESS_RUNTIME=${runtime_name}`, `--privileged`,+ `pulse-secure-runtime-rootless-qualification`, `qualification result != \"passed\"`,+ `openssl pkeyutl -sign -rawin -inkey`, `qualification output directory must have exact mode 0700`,+ `302a300506032b6570032100`, `len(spki) != len(prefix) + 32`,+ } {+ if !strings.Contains(script, required) {+ t.Fatalf("rootless qualification wrapper missing %q", required)+ }+ }+ for _, forbidden := range []string{"/var/run/docker.sock:", "/run/podman/podman.sock:", "-v $", "--volume"} {+ if strings.Contains(script, forbidden) {+ t.Fatalf("rootless qualification wrapper contains forbidden host-runtime mount marker %q", forbidden)+ }+ }+ if strings.Contains(script, "--private-key") || strings.Contains(script, "update_seed=") {+ t.Fatal("rootless wrapper must not put its ephemeral signing key in a process argument")+ }+ createIndex := strings.Index(script, `container_id="$(docker create`)+ trackIndex := strings.Index(script, `CONTAINER_IDS+=("${container_id}")`)+ if createIndex < 0 || trackIndex < 0 || trackIndex < createIndex {+ t.Fatal("rootless wrapper must track the exact container ID only after docker create succeeds")+ }+}++func runRootlessQualificationWithFakeDocker(t *testing.T, mode string) (string, string, error) {+ t.Helper()+ if _, err := exec.LookPath("python3"); err != nil {+ t.Skip("python3 is required for the wrapper ownership regression")+ }+ temporary := t.TempDir()+ fakeBin := filepath.Join(temporary, "bin")+ outputDir := filepath.Join(temporary, "output")+ if err := os.MkdirAll(fakeBin, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.Mkdir(outputDir, 0o700); err != nil {+ t.Fatal(err)+ }+ writeExecutable := func(name, body string) {+ t.Helper()+ if err := os.WriteFile(filepath.Join(fakeBin, name), []byte(body), 0o755); err != nil {+ t.Fatalf("write fake %s: %v", name, err)+ }+ }+ writeExecutable("git", `#!/bin/sh+case " $* " in+ *" branch --show-current "*) printf '%s\n' main ;;+ *" status --porcelain "*) : ;;+ *" rev-parse HEAD "*) printf '%040d\n' 0 | tr 0 a ;;+ *) printf 'unexpected fake git invocation: %s\n' "$*" >&2; exit 64 ;;+esac+`)+ writeExecutable("go", `#!/bin/sh+if [ "${1:-}" = env ] && [ "${2:-}" = GOARCH ]; then+ printf '%s\n' amd64+ exit 0+fi+output=''+while [ "$#" -gt 0 ]; do+ if [ "$1" = -o ]; then+ output="$2"+ break+ fi+ shift+done+[ -n "$output" ] || exit 65+printf '%s\n' fake-go-artifact >"$output"+chmod 0700 "$output"+`)+ writeExecutable("openssl", `#!/bin/sh+command_name="${1:-}"+shift || true+case "$command_name" in+ rand)+ printf '%032d\n' 0 | tr 0 a+ ;;+ genpkey)+ while [ "$#" -gt 0 ]; do+ if [ "$1" = -out ]; then printf '%s\n' fake-private-key >"$2"; exit 0; fi+ shift+ done+ exit 66+ ;;+ pkey)+ while [ "$#" -gt 0 ]; do+ if [ "$1" = -out ]; then+ python3 - "$2" <<'PY'+from pathlib import Path+import sys+Path(sys.argv[1]).write_bytes(bytes.fromhex("302a300506032b6570032100") + bytes(32))+PY+ exit 0+ fi+ shift+ done+ exit 67+ ;;+ pkeyutl)+ printf '%s' fake-signature+ ;;+ base64)+ python3 -c 'import base64,sys; sys.stdout.write(base64.b64encode(sys.stdin.buffer.read()).decode())'+ ;;+ *)+ exit 68+ ;;+esac+`)+ dockerLog := filepath.Join(temporary, "docker.log")+ dockerState := filepath.Join(temporary, "docker.state")+ dockerLabel := filepath.Join(temporary, "docker.label")+ writeExecutable("docker", `#!/bin/sh+printf '%s\n' "$*" >>"$PULSE_FAKE_DOCKER_LOG"+container_id='cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc'+case "${1:-}" in+ info) exit 0 ;;+ build) printf '%s\n' fake-build ; exit 0 ;;+ image) printf '%s\n' '[{}]' ; exit 0 ;;+ create)+ if [ "$PULSE_FAKE_DOCKER_MODE" = name-conflict ]; then+ printf '%s\n' 'Conflict. The container name is already in use.' >&2+ exit 125+ fi+ previous=''+ for argument in "$@"; do+ if [ "$previous" = --label ]; then+ printf '%s\n' "${argument#*=}" >"$PULSE_FAKE_DOCKER_LABEL"+ fi+ previous="$argument"+ done+ : >"$PULSE_FAKE_DOCKER_STATE"+ printf '%s\n' "$container_id"+ ;;+ cp)+ case "${2:-}" in+ *:*) printf '%s\n' '{}' >"$3" ;;+ esac+ ;;+ start) exit 0 ;;+ exec)+ case " $* " in+ *" ip route "*) exit 1 ;;+ *) exit 0 ;;+ esac+ ;;+ inspect)+ case " $* " in+ *".Mounts"*) exit 0 ;;+ *".Config.Labels"*)+ [ "$PULSE_FAKE_DOCKER_MODE" != inspect-failure ] || exit 1+ cat "$PULSE_FAKE_DOCKER_LABEL"+ ;;+ *) exit 70 ;;+ esac+ ;;+ rm)+ [ "$PULSE_FAKE_DOCKER_MODE" != rm-failure ] || exit 1+ rm -f "$PULSE_FAKE_DOCKER_STATE"+ ;;+ ps)+ [ ! -f "$PULSE_FAKE_DOCKER_STATE" ] || printf '%s\n' "$container_id"+ ;;+ logs) exit 0 ;;+ *) printf 'unexpected fake docker invocation: %s\n' "$*" >&2; exit 69 ;;+esac+`)+ commit := strings.Repeat("a", 40)+ command := exec.Command("bash", repoFile("scripts", "run-secure-runtime-rootless-qualification.sh"))+ command.Env = append(os.Environ(),+ "PATH="+fakeBin+string(os.PathListSeparator)+os.Getenv("PATH"),+ "PULSE_FAKE_DOCKER_LOG="+dockerLog,+ "PULSE_FAKE_DOCKER_STATE="+dockerState,+ "PULSE_FAKE_DOCKER_LABEL="+dockerLabel,+ "PULSE_FAKE_DOCKER_MODE="+mode,+ "PULSE_ROOTLESS_UBUNTU_IMAGE=ubuntu@sha256:"+strings.Repeat("b", 64),+ "PULSE_ROOTLESS_QUALIFICATION_OUTPUT_DIR="+outputDir,+ "PULSE_ROOTLESS_QUALIFICATION_CONFIRM=I_HAVE_VERIFIED_THESE_ARE_DISPOSABLE_ROOTLESS_SYSTEMD_CONTAINERS_COMMIT_"+commit,+ )+ output, err := command.CombinedOutput()+ logBytes, readErr := os.ReadFile(dockerLog)+ if readErr != nil {+ t.Fatal(readErr)+ }+ return string(output), string(logBytes), err+}++func TestRootlessQualificationNameConflictDoesNotRemoveContainer(t *testing.T) {+ output, logText, err := runRootlessQualificationWithFakeDocker(t, "name-conflict")+ if err == nil {+ t.Fatalf("wrapper unexpectedly succeeded after Docker name conflict: %s", output)+ }+ if !strings.Contains(logText, "create --name pulse-rootless-qual-docker-") {+ t.Fatalf("fake Docker did not reach the name-conflict create; docker log=%s wrapper output=%s", logText, output)+ }+ for _, line := range strings.Split(logText, "\n") {+ if strings.HasPrefix(line, "rm ") {+ t.Fatalf("name-conflict cleanup attempted to remove an unowned container: %s", logText)+ }+ }+}++func TestRootlessQualificationCleanupFailureCannotEmitPassingPacket(t *testing.T) {+ for _, mode := range []string{"inspect-failure", "rm-failure"} {+ t.Run(mode, func(t *testing.T) {+ output, logText, err := runRootlessQualificationWithFakeDocker(t, mode)+ if err == nil {+ t.Fatalf("wrapper unexpectedly succeeded after %s: %s", mode, output)+ }+ if strings.Contains(output, "Rootless qualification passed:") {+ t.Fatalf("wrapper emitted a passing packet after %s: %s", mode, output)+ }+ if !strings.Contains(logText, ".Config.Labels") {+ t.Fatalf("wrapper did not reach strict ownership verification after %s: %s", mode, logText)+ }+ if mode == "rm-failure" && !strings.Contains(logText, "rm -f cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc") {+ t.Fatalf("wrapper did not exercise strict removal failure: %s", logText)+ }+ })+ }+}diff --git a/scripts/release_control/secure_runtime_rootless_attestation_v1.py b/scripts/release_control/secure_runtime_rootless_attestation_v1.pynew file mode 100644index 0000000000..c0f8eabc3e--- /dev/null+++ b/scripts/release_control/secure_runtime_rootless_attestation_v1.py@@ -0,0 +1,900 @@+#!/usr/bin/env python3+"""Validate the secret-free opt-in rootless runtime qualification receipt.++This validator deliberately makes no claim about published release artifacts or+whether the safe collector profile is suitable as a default. It validates one+local, artifact-bound qualification receipt for both Docker and Podman.+"""++from __future__ import annotations++import argparse+import contextlib+import hashlib+import json+import math+import os+import re+import stat+import subprocess+import sys+import tempfile+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, NoReturn+++RECEIPT_SCHEMA_VERSION = 1+ATTESTATION_SCHEMA_VERSION = 1+RECEIPT_KIND = "pulse-secure-runtime-rootless-qualification"+ATTESTATION_KIND = "pulse-secure-runtime-rootless-receipt-attestation"+CLASSIFICATION = "local-opt-in-rootless-runtime-artifact-bound-self-attestation"+MAX_RECEIPT_BYTES = 2 * 1024 * 1024+MAX_ARTIFACT_BYTES = 256 * 1024 * 1024+SOURCE_MANIFEST_SCHEMA_VERSION = 1+SOURCE_MANIFEST_ID = "secure-runtime-rootless-v1"+SOURCE_MANIFEST_PATH = "scripts/release_control/secure_runtime_rootless_source_manifest_v1.json"+SHA256_RE = re.compile(r"^[0-9a-f]{64}$")+COMMIT_RE = re.compile(r"^[0-9a-f]{40}$")+GO_VERSION_RE = re.compile(r"^go1\.[0-9]+(?:\.[0-9]+)?$")+IDENTITY_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:@+-]{0,255}$")+VERSION_RE = re.compile(r"^v?[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$")+TIMESTAMP_RE = re.compile(+ r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,9})?Z$"+)+SENSITIVE_KEY_PARTS = frozenset(+ {+ "authorization",+ "bearer",+ "cookie",+ "credential",+ "credentials",+ "password",+ "passwd",+ "privatekey",+ "secret",+ "secrets",+ "token",+ "tokens",+ }+)+SENSITIVE_VALUE_PATTERNS = (+ re.compile(r"-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----"),+ re.compile(r"(?i)(?:^|\s)(?:bearer|basic)\s+[A-Za-z0-9+/=_-]{8,}"),+ re.compile(r"^[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}$"),+ re.compile(r"^[a-z][a-z0-9+.-]*://[^/@\s:]+:[^/@\s]+@", re.IGNORECASE),+)++REQUIRED_RUNTIMES = ("docker", "podman")+REQUIRED_SCENARIOS = (+ "fresh_install",+ "legacy_migration",+ "collector_restart",+ "daemon_restart",+ "socket_loss_helper_fallback",+ "direct_recovery",+ "dual_socket_ambiguity_refusal",+ "exact_pin_recovery",+ "telemetry_parity",+ "authority_isolation",+ "cleanup",+)+++class ValidationError(ValueError):+ """The receipt is malformed or does not prove the required contract."""+++def fail(message: str) -> NoReturn:+ raise ValidationError(message)+++def require(condition: bool, message: str) -> None:+ if not condition:+ fail(message)+++def require_object(value: Any, label: str, keys: set[str]) -> dict[str, Any]:+ require(isinstance(value, dict), f"{label} must be an object")+ actual = set(value)+ require(actual == keys, f"{label} fields differ: missing={sorted(keys - actual)} extra={sorted(actual - keys)}")+ return value+++def require_bool(value: Any, expected: bool, label: str) -> None:+ require(type(value) is bool and value is expected, f"{label} must be {str(expected).lower()}")+++def require_int(value: Any, label: str, *, minimum: int = 0) -> int:+ require(type(value) is int and value >= minimum, f"{label} must be an integer >= {minimum}")+ return value+++def require_text(+ value: Any,+ label: str,+ *,+ pattern: re.Pattern[str] | None = None,+ maximum: int = 256,+) -> str:+ require(isinstance(value, str) and 0 < len(value) <= maximum, f"{label} must be non-empty text <= {maximum} bytes")+ require("\x00" not in value and "\n" not in value and "\r" not in value, f"{label} contains control text")+ if pattern is not None:+ require(pattern.fullmatch(value) is not None, f"{label} has an invalid format")+ return value+++def require_digest(value: Any, label: str, *, allow_empty: bool = False) -> str:+ if allow_empty and value == "":+ return ""+ return require_text(value, label, pattern=SHA256_RE, maximum=64)+++def parse_timestamp(value: Any, label: str) -> datetime:+ text = require_text(value, label, pattern=TIMESTAMP_RE, maximum=40)+ try:+ parsed = datetime.fromisoformat(text[:-1] + "+00:00")+ except ValueError as exc:+ raise ValidationError(f"{label} is not a valid UTC timestamp") from exc+ require(parsed.tzinfo == timezone.utc, f"{label} must be UTC")+ return parsed+++def reject_sensitive_evidence(value: Any, path: str = "receipt") -> None:+ if isinstance(value, dict):+ for key, child in value.items():+ require(isinstance(key, str), f"{path} contains a non-string key")+ if path != "receipt.source_hashes":+ normalized = re.sub(r"[^a-z0-9]", "", key.lower())+ segmented = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", key)+ parts = {part.lower() for part in re.split(r"[^A-Za-z0-9]+", segmented) if part}+ require(+ normalized not in SENSITIVE_KEY_PARTS and not parts.intersection(SENSITIVE_KEY_PARTS),+ f"{path}.{key} is a forbidden sensitive key",+ )+ reject_sensitive_evidence(child, f"{path}.{key}")+ elif isinstance(value, list):+ for index, child in enumerate(value):+ reject_sensitive_evidence(child, f"{path}[{index}]")+ elif isinstance(value, str):+ for pattern in SENSITIVE_VALUE_PATTERNS:+ require(pattern.search(value) is None, f"{path} contains secret-like evidence")+ elif isinstance(value, float):+ require(math.isfinite(value), f"{path} contains a non-finite number")+++def expected_socket_path(runtime: str, uid: int) -> str:+ if runtime == "docker":+ return f"/run/user/{uid}/docker.sock"+ return f"/run/user/{uid}/podman/podman.sock"+++DIRECT_KEYS = {+ "collector_pid",+ "service_pid",+ "collection_path",+ "inventory_complete",+ "inventory_count",+ "semantic_sha256",+ "full_fields_present",+ "stats_present",+ "secondary_structure_sha256",+ "daemon_id",+ "daemon_rootless",+ "socket_path",+ "socket_uid",+ "socket_gid",+ "socket_mode",+ "socket_type",+ "socket_symlink",+}+++def validate_socket_mode(value: Any, label: str) -> str:+ mode = require_text(value, label, pattern=re.compile(r"^0[0-7]{3}$"), maximum=4)+ numeric_mode = int(mode, 8)+ require(numeric_mode & 0o600 == 0o600, f"{label} must grant owner read and write")+ require(numeric_mode & 0o006 == 0, f"{label} must not grant world read or write")+ return mode+++def validate_socket_identity(value: Any, label: str, runtime: str, uid: int) -> dict[str, Any]:+ socket = require_object(+ value,+ label,+ {"runtime", "path", "uid", "gid", "mode", "type", "symlink"},+ )+ require(socket["runtime"] == runtime, f"{label}.runtime must be {runtime}")+ require(socket["path"] == expected_socket_path(runtime, uid), f"{label}.path is not the exact rootless path")+ require(socket["uid"] == uid, f"{label}.uid must match the collector")+ require_int(socket["gid"], f"{label}.gid", minimum=1)+ validate_socket_mode(socket["mode"], f"{label}.mode")+ require(socket["type"] == "unix", f"{label}.type must be unix")+ require_bool(socket["symlink"], False, f"{label}.symlink")+ return socket+++def validate_direct_evidence(+ evidence: Any,+ label: str,+ runtime_result: dict[str, Any],+ *,+ expected_collector_pid: int | None = None,+ expected_daemon_id: str | None = None,+) -> dict[str, Any]:+ item = require_object(evidence, label, DIRECT_KEYS)+ collector_pid = require_int(item["collector_pid"], f"{label}.collector_pid", minimum=2)+ require_int(item["service_pid"], f"{label}.service_pid", minimum=2)+ require(item["service_pid"] == collector_pid, f"{label} collector and service PID must match")+ if expected_collector_pid is not None:+ require(collector_pid == expected_collector_pid, f"{label} unexpectedly restarted the collector")+ require(item["collection_path"] == "collector-owned-rootless-socket", f"{label}.collection_path differs")+ require_bool(item["inventory_complete"], True, f"{label}.inventory_complete")+ require_int(item["inventory_count"], f"{label}.inventory_count", minimum=1)+ for name in ("semantic_sha256", "secondary_structure_sha256"):+ require_digest(item[name], f"{label}.{name}")+ require_bool(item["full_fields_present"], True, f"{label}.full_fields_present")+ require_bool(item["stats_present"], True, f"{label}.stats_present")+ daemon_id = require_text(item["daemon_id"], f"{label}.daemon_id", pattern=IDENTITY_RE)+ if expected_daemon_id is not None:+ require(daemon_id == expected_daemon_id, f"{label} has the wrong daemon identity")+ require_bool(item["daemon_rootless"], True, f"{label}.daemon_rootless")+ require(item["socket_path"] == runtime_result["socket_path"], f"{label} used a different socket path")+ require(item["socket_uid"] == runtime_result["socket_uid"], f"{label} used a different socket owner")+ require(item["socket_gid"] == runtime_result["socket_gid"], f"{label} used a different socket group")+ require(item["socket_mode"] == runtime_result["socket_mode"], f"{label} used a different socket mode")+ require(item["socket_type"] == "unix", f"{label}.socket_type must be unix")+ require_bool(item["socket_symlink"], False, f"{label}.socket_symlink")+ return item+++def validate_scenario(+ scenario: Any,+ expected_name: str,+ label: str,+ receipt_start: datetime,+ receipt_end: datetime,+) -> tuple[dict[str, Any], datetime, datetime]:+ item = require_object(+ scenario,+ label,+ {"name", "result", "started_at", "completed_at", "report_stream_id", "report_sequence", "evidence"},+ )+ require(item["name"] == expected_name, f"{label}.name must be {expected_name}")+ require(item["result"] == "passed", f"{label}.result must be passed")+ started = parse_timestamp(item["started_at"], f"{label}.started_at")+ completed = parse_timestamp(item["completed_at"], f"{label}.completed_at")+ require(receipt_start <= started < completed <= receipt_end, f"{label} chronology is outside the receipt window")+ non_reporting = expected_name in {"dual_socket_ambiguity_refusal", "authority_isolation", "cleanup"}+ if non_reporting:+ require(item["report_stream_id"] is None, f"{label}.report_stream_id must be null")+ require(item["report_sequence"] is None, f"{label}.report_sequence must be null")+ else:+ require_text(item["report_stream_id"], f"{label}.report_stream_id", pattern=IDENTITY_RE)+ require_int(item["report_sequence"], f"{label}.report_sequence", minimum=1)+ return item, started, completed+++def stable_direct_parity(left: dict[str, Any], right: dict[str, Any], label: str) -> None:+ for name in ("inventory_count", "semantic_sha256", "secondary_structure_sha256"):+ require(left[name] == right[name], f"{label} did not retain {name} parity")+ require_bool(right["full_fields_present"], True, f"{label}.full_fields_present")+ require_bool(right["stats_present"], True, f"{label}.stats_present")+++def validate_run(run: Any, expected_runtime: str, run_index: int, receipt_start: datetime, receipt_end: datetime) -> dict[str, Any]:+ label = f"runs[{run_index}]"+ run = require_object(run, label, {"host", "runtime", "scenarios"})+ host = require_object(run["host"], f"{label}.host", {"machine_id", "architecture", "kernel", "systemd_version"})+ require_text(host["machine_id"], f"{label}.host.machine_id", pattern=IDENTITY_RE)+ require(host["architecture"] in {"amd64", "arm64"}, f"{label}.host.architecture is unsupported")+ require_text(host["kernel"], f"{label}.host.kernel", maximum=128)+ require_text(host["systemd_version"], f"{label}.host.systemd_version", maximum=128)++ runtime = require_object(+ run["runtime"], f"{label}.runtime",+ {"runtime", "runtime_version", "daemon_id", "collector_uid", "socket_path", "socket_uid", "socket_gid", "socket_mode", "socket_type", "socket_symlink", "daemon_rootless"},+ )+ require(runtime["runtime"] == expected_runtime, f"{label}.runtime.runtime must be {expected_runtime}")+ require_text(runtime["runtime_version"], f"{label}.runtime.runtime_version", pattern=VERSION_RE, maximum=128)+ require_text(runtime["daemon_id"], f"{label}.runtime.daemon_id", pattern=IDENTITY_RE)+ uid = require_int(runtime["collector_uid"], f"{label}.runtime.collector_uid", minimum=1)+ socket_path = expected_socket_path(expected_runtime, uid)+ require(runtime["socket_path"] == socket_path, f"{label}.runtime.socket_path must be {socket_path}")+ require(runtime["socket_uid"] == uid, f"{label}.runtime.socket_uid must match collector_uid")+ require_int(runtime["socket_gid"], f"{label}.runtime.socket_gid", minimum=1)+ validate_socket_mode(runtime["socket_mode"], f"{label}.runtime.socket_mode")+ require(runtime["socket_type"] == "unix", f"{label}.runtime.socket_type must be unix")+ require_bool(runtime["socket_symlink"], False, f"{label}.runtime.socket_symlink")+ require_bool(runtime["daemon_rootless"], True, f"{label}.runtime.daemon_rootless")++ scenarios = run["scenarios"]+ require(isinstance(scenarios, list) and len(scenarios) == len(REQUIRED_SCENARIOS), f"{label}.scenarios must contain exactly eleven scenarios")+ parsed: dict[str, dict[str, Any]] = {}+ previous_completed: datetime | None = None+ for index, name in enumerate(REQUIRED_SCENARIOS):+ scenario, started, completed = validate_scenario(scenarios[index], name, f"{label}.scenarios[{index}]", receipt_start, receipt_end)+ if previous_completed is not None:+ require(previous_completed <= started, f"{label}.scenarios are not chronological")+ previous_completed = completed+ parsed[name] = scenario++ fresh = validate_direct_evidence(parsed["fresh_install"]["evidence"], f"{label}.fresh_install", runtime)+ migration_raw = require_object(+ parsed["legacy_migration"]["evidence"], f"{label}.legacy_migration",+ DIRECT_KEYS | {"legacy_profile", "target_profile", "authority_reduced", "legacy_collector_pid"},+ )+ require(migration_raw["legacy_profile"] == "root-command-capable", f"{label}.legacy_migration legacy profile differs")+ require(migration_raw["target_profile"] == "typed-helper-monitoring-only", f"{label}.legacy_migration target profile differs")+ require_bool(migration_raw["authority_reduced"], True, f"{label}.legacy_migration.authority_reduced")+ legacy_collector_pid = require_int(migration_raw["legacy_collector_pid"], f"{label}.legacy_migration.legacy_collector_pid", minimum=2)+ migration = validate_direct_evidence({key: migration_raw[key] for key in DIRECT_KEYS}, f"{label}.legacy_migration.direct", runtime)+ require(migration["collector_pid"] != legacy_collector_pid, f"{label}.legacy_migration did not replace the legacy collector")+ stable_direct_parity(fresh, migration, f"{label}.legacy_migration")++ restart_raw = require_object(+ parsed["collector_restart"]["evidence"], f"{label}.collector_restart",+ DIRECT_KEYS | {"previous_collector_pid", "previous_report_stream_id"},+ )+ require(restart_raw["previous_collector_pid"] == migration["collector_pid"], f"{label}.collector_restart predecessor differs")+ require(restart_raw["previous_report_stream_id"] == parsed["legacy_migration"]["report_stream_id"], f"{label}.collector_restart predecessor stream differs")+ restart = validate_direct_evidence({key: restart_raw[key] for key in DIRECT_KEYS}, f"{label}.collector_restart.direct", runtime)+ require(restart["collector_pid"] != migration["collector_pid"], f"{label}.collector_restart did not change PID")+ stable_direct_parity(fresh, restart, f"{label}.collector_restart")++ fresh_stream = parsed["fresh_install"]["report_stream_id"]+ migration_stream = parsed["legacy_migration"]["report_stream_id"]+ restart_stream = parsed["collector_restart"]["report_stream_id"]+ require(len({fresh_stream, migration_stream, restart_stream}) == 3, f"{label} install/migration/restart streams are not distinct")+ require(parsed["fresh_install"]["report_sequence"] >= 1, f"{label}.fresh_install sequence is invalid")+ require(parsed["legacy_migration"]["report_sequence"] >= 1, f"{label}.legacy_migration sequence is invalid")++ daemon_raw = require_object(+ parsed["daemon_restart"]["evidence"], f"{label}.daemon_restart",+ DIRECT_KEYS | {"previous_daemon_pid", "daemon_pid", "previous_daemon_invocation_id", "daemon_invocation_id"},+ )+ daemon = validate_direct_evidence({key: daemon_raw[key] for key in DIRECT_KEYS}, f"{label}.daemon_restart.direct", runtime, expected_collector_pid=restart["collector_pid"], expected_daemon_id=runtime["daemon_id"])+ previous_daemon_pid = require_int(daemon_raw["previous_daemon_pid"], f"{label}.daemon_restart.previous_daemon_pid", minimum=2)+ daemon_pid = require_int(daemon_raw["daemon_pid"], f"{label}.daemon_restart.daemon_pid", minimum=2)+ require(previous_daemon_pid != daemon_pid, f"{label}.daemon_restart did not change daemon PID")+ previous_invocation = require_text(daemon_raw["previous_daemon_invocation_id"], f"{label}.daemon_restart.previous_daemon_invocation_id", pattern=IDENTITY_RE)+ invocation = require_text(daemon_raw["daemon_invocation_id"], f"{label}.daemon_restart.daemon_invocation_id", pattern=IDENTITY_RE)+ require(previous_invocation != invocation, f"{label}.daemon_restart did not change InvocationID")+ stable_direct_parity(fresh, daemon, f"{label}.daemon_restart")++ fallback_label = f"{label}.socket_loss_helper_fallback"+ fallback = require_object(+ parsed["socket_loss_helper_fallback"]["evidence"], fallback_label,+ {"collector_pid", "collection_mode", "direct_runtime_available", "helper_fallback", "inventory_complete", "inventory_count", "rootful_baseline_inventory_count", "semantic_sha256", "rootful_baseline_semantic_sha256", "full_fields_present", "stats_present", "secondary_structure_sha256", "container_actions_enabled", "container_updates_enabled", "collector_restart_count"},+ )+ require(fallback["collector_pid"] == restart["collector_pid"], f"{fallback_label} restarted collector")+ require(fallback["collection_mode"] == "typed-helper-summary", f"{fallback_label} did not use helper summary")+ require_bool(fallback["direct_runtime_available"], False, f"{fallback_label}.direct_runtime_available")+ require_bool(fallback["helper_fallback"], True, f"{fallback_label}.helper_fallback")+ require_bool(fallback["inventory_complete"], True, f"{fallback_label}.inventory_complete")+ require_int(fallback["inventory_count"], f"{fallback_label}.inventory_count", minimum=1)+ require(fallback["inventory_count"] == fallback["rootful_baseline_inventory_count"], f"{fallback_label} rootful count parity differs")+ require_digest(fallback["semantic_sha256"], f"{fallback_label}.semantic_sha256")+ require(fallback["semantic_sha256"] == fallback["rootful_baseline_semantic_sha256"], f"{fallback_label} semantic parity differs")+ require_bool(fallback["full_fields_present"], False, f"{fallback_label}.full_fields_present")+ require(fallback["secondary_structure_sha256"] == "", f"{fallback_label}.secondary_structure_sha256 must be empty")+ require_bool(fallback["stats_present"], False, f"{fallback_label}.stats_present")+ for name in ("container_actions_enabled", "container_updates_enabled"):+ require_bool(fallback[name], False, f"{fallback_label}.{name}")+ require(fallback["collector_restart_count"] == 0, f"{fallback_label} restarted collector")++ recovery = validate_direct_evidence(parsed["direct_recovery"]["evidence"], f"{label}.direct_recovery", runtime, expected_collector_pid=restart["collector_pid"], expected_daemon_id=runtime["daemon_id"])+ stable_direct_parity(fresh, recovery, f"{label}.direct_recovery")++ for name in ("collector_restart", "daemon_restart", "socket_loss_helper_fallback", "direct_recovery"):+ require(parsed[name]["report_stream_id"] == restart_stream, f"{label}.{name} changed report stream")+ sequences = [parsed[name]["report_sequence"] for name in ("collector_restart", "daemon_restart", "socket_loss_helper_fallback", "direct_recovery")]+ require(all(left < right for left, right in zip(sequences, sequences[1:])), f"{label} post-restart report sequence is not monotonic")++ ambiguity_label = f"{label}.dual_socket_ambiguity_refusal"+ ambiguity = require_object(+ parsed["dual_socket_ambiguity_refusal"]["evidence"], ambiguity_label,+ {"protected_collector_pid", "live_sockets", "probe_kind", "admission_refused", "fail_closed", "daemon_probe_count", "container_actions_enabled", "collector_restart_count"},+ )+ require(ambiguity["protected_collector_pid"] == restart["collector_pid"], f"{ambiguity_label} changed protected collector PID")+ require(ambiguity["probe_kind"] == "separate-unpinned-collector", f"{ambiguity_label}.probe_kind differs")+ live_sockets = ambiguity["live_sockets"]+ require(isinstance(live_sockets, list) and len(live_sockets) == 2, f"{ambiguity_label}.live_sockets must contain two sockets")+ for index, runtime_name in enumerate(REQUIRED_RUNTIMES):+ validate_socket_identity(live_sockets[index], f"{ambiguity_label}.live_sockets[{index}]", runtime_name, uid)+ require_bool(ambiguity["admission_refused"], True, f"{ambiguity_label}.admission_refused")+ require_bool(ambiguity["fail_closed"], True, f"{ambiguity_label}.fail_closed")+ require(ambiguity["daemon_probe_count"] == 0, f"{ambiguity_label} probed daemon")+ require_bool(ambiguity["container_actions_enabled"], False, f"{ambiguity_label}.container_actions_enabled")+ require(ambiguity["collector_restart_count"] == 0, f"{ambiguity_label} restarted collector")++ pin_label = f"{label}.exact_pin_recovery"+ pin_raw = require_object(+ parsed["exact_pin_recovery"]["evidence"], pin_label,+ DIRECT_KEYS | {"previous_collector_pid", "previous_report_stream_id", "pin_source", "pinned_socket_path", "socket_absent_observed", "fallback_report_sequence", "recovery_report_sequence", "recovered_socket_path", "selected_socket_path", "recovered_socket_uid", "recovered_socket_gid", "recovered_socket_mode", "recovered_socket_type", "recovered_socket_symlink", "candidate_count", "daemon_probe_count", "collector_restart_count"},+ )+ require(pin_raw["previous_collector_pid"] == restart["collector_pid"], f"{pin_label} predecessor PID differs")+ require(pin_raw["previous_report_stream_id"] == restart_stream, f"{pin_label} predecessor stream differs")+ pin = validate_direct_evidence({key: pin_raw[key] for key in DIRECT_KEYS}, f"{pin_label}.direct", runtime, expected_daemon_id=runtime["daemon_id"])+ require(pin["collector_pid"] != restart["collector_pid"], f"{pin_label} update did not restart collector")+ pin_stream = parsed["exact_pin_recovery"]["report_stream_id"]+ require(pin_stream != restart_stream, f"{pin_label} did not create a new report stream")+ require(pin_raw["pin_source"] == "root-owned-systemd-unit", f"{pin_label} pin source differs")+ for name in ("pinned_socket_path", "recovered_socket_path", "selected_socket_path"):+ require(pin_raw[name] == socket_path, f"{pin_label}.{name} differs")+ require_bool(pin_raw["socket_absent_observed"], True, f"{pin_label}.socket_absent_observed")+ require(pin_raw["recovered_socket_uid"] == uid and pin_raw["recovered_socket_gid"] == runtime["socket_gid"], f"{pin_label} recovered owner differs")+ require(pin_raw["recovered_socket_mode"] == runtime["socket_mode"], f"{pin_label} recovered mode differs")+ require(pin_raw["recovered_socket_type"] == "unix", f"{pin_label}.recovered_socket_type must be unix")+ require_bool(pin_raw["recovered_socket_symlink"], False, f"{pin_label}.recovered_socket_symlink")+ fallback_sequence = require_int(pin_raw["fallback_report_sequence"], f"{pin_label}.fallback_report_sequence", minimum=1)+ recovery_sequence = require_int(pin_raw["recovery_report_sequence"], f"{pin_label}.recovery_report_sequence", minimum=1)+ require(fallback_sequence < recovery_sequence <= parsed["exact_pin_recovery"]["report_sequence"], f"{pin_label} sequence causality differs")+ require(pin_raw["candidate_count"] == 1 and pin_raw["daemon_probe_count"] == 1, f"{pin_label} did not select/probe exactly one endpoint")+ require(pin_raw["collector_restart_count"] == 1, f"{pin_label} must record exactly one update restart")+ stable_direct_parity(fresh, pin, pin_label)++ parity_label = f"{label}.telemetry_parity"+ parity = require_object(+ parsed["telemetry_parity"]["evidence"], parity_label,+ {"collector_pid", "baseline_kind", "baseline_inventory_count", "collector_inventory_count", "baseline_semantic_sha256", "collector_semantic_sha256", "collector_full_fields_present", "collector_stats_present", "collector_secondary_inventory_present"},+ )+ require(parity["collector_pid"] == pin["collector_pid"], f"{parity_label} changed collector PID")+ require(parity["baseline_kind"] == "root-client-same-rootless-daemon", f"{parity_label} baseline differs")+ baseline_count = require_int(parity["baseline_inventory_count"], f"{parity_label}.baseline_inventory_count", minimum=1)+ collector_count = require_int(parity["collector_inventory_count"], f"{parity_label}.collector_inventory_count", minimum=1)+ require(baseline_count == collector_count == fresh["inventory_count"], f"{parity_label} count differs")+ baseline_semantic = require_digest(parity["baseline_semantic_sha256"], f"{parity_label}.baseline_semantic_sha256")+ collector_semantic = require_digest(parity["collector_semantic_sha256"], f"{parity_label}.collector_semantic_sha256")+ require(baseline_semantic == collector_semantic == fresh["semantic_sha256"], f"{parity_label} semantic inventory differs")+ for name in ("collector_full_fields_present", "collector_stats_present", "collector_secondary_inventory_present"):+ require_bool(parity[name], True, f"{parity_label}.{name}")+ require(parsed["telemetry_parity"]["report_stream_id"] == pin_stream, f"{parity_label} changed updated stream")+ require(parsed["telemetry_parity"]["report_sequence"] > parsed["exact_pin_recovery"]["report_sequence"], f"{parity_label} sequence is not monotonic")++ authority_label = f"{label}.authority_isolation"+ authority = require_object(+ parsed["authority_isolation"]["evidence"], authority_label,+ {"collector_pid", "collector_uid", "effective_uid", "effective_root", "safe_profile_enabled", "commands_enabled", "privileged_helper_enabled", "reduction_request_observed", "collector_command_transport_present", "collector_command_session_present", "container_actions_enabled", "container_updates_enabled", "rootful_socket_access", "helper_network_access"},+ )+ require(authority["collector_pid"] == pin["collector_pid"], f"{authority_label} changed collector PID")+ require(authority["collector_uid"] == uid == authority["effective_uid"], f"{authority_label} UID binding differs")+ require_bool(authority["effective_root"], False, f"{authority_label}.effective_root")+ for name in ("safe_profile_enabled", "privileged_helper_enabled", "reduction_request_observed"):+ require_bool(authority[name], True, f"{authority_label}.{name}")+ for name in ("commands_enabled", "collector_command_transport_present", "collector_command_session_present", "container_actions_enabled", "container_updates_enabled", "rootful_socket_access", "helper_network_access"):+ require_bool(authority[name], False, f"{authority_label}.{name}")++ cleanup = require_object(parsed["cleanup"]["evidence"], f"{label}.cleanup", {"runtime_stopped", "socket_absent", "fixtures_removed", "user_state_clean"})+ for name in cleanup:+ require_bool(cleanup[name], True, f"{label}.cleanup.{name}")+ return run+++def validate_receipt(receipt: Any) -> dict[str, Any]:+ reject_sensitive_evidence(receipt)+ root = require_object(+ receipt,+ "receipt",+ {+ "schema_version",+ "kind",+ "result",+ "source_commit",+ "started_at",+ "completed_at",+ "artifacts",+ "runs",+ "source_hashes",+ },+ )+ require(root["schema_version"] == RECEIPT_SCHEMA_VERSION, "receipt.schema_version must be 1")+ require(root["kind"] == RECEIPT_KIND, f"receipt.kind must be {RECEIPT_KIND}")+ require(root["result"] == "passed", "receipt.result must be passed")+ source_commit = require_text(root["source_commit"], "receipt.source_commit", pattern=COMMIT_RE, maximum=40)+ started = parse_timestamp(root["started_at"], "receipt.started_at")+ completed = parse_timestamp(root["completed_at"], "receipt.completed_at")+ require(started < completed, "receipt chronology is invalid")++ artifacts = require_object(root["artifacts"], "receipt.artifacts", {"qualification_test", "collector", "helper", "installer"})+ expected_basenames = {"qualification_test": "dockeragent.test", "collector": "pulse-agent", "helper": "pulse-agent-helper"}+ expected_packages = {+ "qualification_test": "github.com/rcourtman/pulse-go-rewrite/scripts/installtests.test",+ "collector": "github.com/rcourtman/pulse-go-rewrite/cmd/pulse-agent",+ "helper": "github.com/rcourtman/pulse-go-rewrite/cmd/pulse-agent-helper",+ }+ for name, basename in expected_basenames.items():+ artifact = require_object(artifacts[name], f"receipt.artifacts.{name}", {"path_basename", "sha256", "package", "go_version", "vcs_revision", "vcs_modified"})+ require(artifact["path_basename"] == basename, f"receipt.artifacts.{name}.path_basename differs")+ require_digest(artifact["sha256"], f"receipt.artifacts.{name}.sha256")+ require(artifact["package"] == expected_packages[name], f"receipt.artifacts.{name}.package differs")+ require_text(artifact["go_version"], f"receipt.artifacts.{name}.go_version", pattern=GO_VERSION_RE, maximum=32)+ require(artifact["vcs_revision"] == source_commit, f"receipt.artifacts.{name}.vcs_revision differs from source_commit")+ require_bool(artifact["vcs_modified"], False, f"receipt.artifacts.{name}.vcs_modified")+ installer = require_object(artifacts["installer"], "receipt.artifacts.installer", {"path_basename", "sha256"})+ require(installer["path_basename"] == "install.sh", "receipt.artifacts.installer.path_basename differs")+ require_digest(installer["sha256"], "receipt.artifacts.installer.sha256")++ source_hashes = root["source_hashes"]+ require(isinstance(source_hashes, dict) and source_hashes, "receipt.source_hashes must be a non-empty object")+ for source_path, digest in source_hashes.items():+ require_text(source_path, "receipt.source_hashes path", maximum=512)+ require(+ source_path == Path(source_path).as_posix()+ and not source_path.startswith("/")+ and ".." not in Path(source_path).parts,+ "receipt.source_hashes contains a non-canonical path",+ )+ require_digest(digest, f"receipt.source_hashes[{source_path}]")+ require(source_hashes.get("scripts/install.sh") == installer["sha256"], "installer digest must equal governed scripts/install.sh")++ runs = root["runs"]+ require(isinstance(runs, list) and len(runs) == 2, "receipt.runs must contain two disposable hosts")+ validated = [validate_run(runs[index], runtime, index, started, completed) for index, runtime in enumerate(REQUIRED_RUNTIMES)]+ require(validated[0]["host"]["machine_id"] != validated[1]["host"]["machine_id"], "Docker and Podman runs must use distinct hosts")+ require(validated[0]["runtime"]["daemon_id"] != validated[1]["runtime"]["daemon_id"], "Docker and Podman daemon identities must differ")+ docker_stream = validated[0]["scenarios"][REQUIRED_SCENARIOS.index("collector_restart")]["report_stream_id"]+ podman_stream = validated[1]["scenarios"][REQUIRED_SCENARIOS.index("collector_restart")]["report_stream_id"]+ require(docker_stream != podman_stream, "Docker and Podman report streams must differ")+ for current in validated:+ uid = current["runtime"]["collector_uid"]+ expected_live_sockets = [+ {"runtime": runtime, "path": expected_socket_path(runtime, uid), "uid": uid, "gid": current["runtime"]["socket_gid"], "mode": current["runtime"]["socket_mode"], "type": "unix", "symlink": False}+ for runtime in REQUIRED_RUNTIMES+ ]+ ambiguity = current["scenarios"][REQUIRED_SCENARIOS.index("dual_socket_ambiguity_refusal")]["evidence"]+ require(ambiguity["live_sockets"] == expected_live_sockets, "dual-socket evidence differs from run-local socket identities")+ return root+++def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:+ result: dict[str, Any] = {}+ for key, value in pairs:+ if key in result:+ fail(f"receipt contains duplicate JSON key {key!r}")+ result[key] = value+ return result+++def parse_receipt_bytes(data: bytes) -> dict[str, Any]:+ require(len(data) <= MAX_RECEIPT_BYTES, "receipt exceeds the maximum size")+ try:+ text = data.decode("utf-8")+ except UnicodeDecodeError as exc:+ raise ValidationError("receipt is not UTF-8") from exc+ try:+ parsed = json.loads(+ text,+ object_pairs_hook=_reject_duplicate_keys,+ parse_constant=lambda value: fail(f"receipt contains invalid number {value}"),+ )+ except json.JSONDecodeError as exc:+ raise ValidationError(f"receipt is not valid JSON: {exc}") from exc+ validate_receipt(parsed)+ return parsed+++def read_immutable_receipt(path: Path) -> bytes:+ flags = os.O_RDONLY+ if hasattr(os, "O_CLOEXEC"):+ flags |= os.O_CLOEXEC+ if hasattr(os, "O_NOFOLLOW"):+ flags |= os.O_NOFOLLOW+ if hasattr(os, "O_NONBLOCK"):+ flags |= os.O_NONBLOCK+ try:+ descriptor = os.open(path, flags)+ except OSError as exc:+ raise ValidationError(f"unable to open receipt: {exc}") from exc+ try:+ before = os.fstat(descriptor)+ require(stat.S_ISREG(before.st_mode), "receipt must be a regular file")+ require(before.st_size <= MAX_RECEIPT_BYTES, "receipt exceeds the maximum size")+ chunks: list[bytes] = []+ remaining = MAX_RECEIPT_BYTES + 1+ while remaining:+ chunk = os.read(descriptor, min(1024 * 1024, remaining))+ if not chunk:+ break+ chunks.append(chunk)+ remaining -= len(chunk)+ data = b"".join(chunks)+ require(len(data) <= MAX_RECEIPT_BYTES, "receipt exceeds the maximum size")+ after = os.fstat(descriptor)+ require(+ (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns)+ == (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns),+ "receipt changed while it was being read",+ )+ require(len(data) == before.st_size, "receipt read was incomplete")+ return data+ finally:+ os.close(descriptor)+++def _canonical_relative_path(value: Any, label: str) -> str:+ text = require_text(value, label, maximum=512)+ candidate = Path(text)+ require(+ not candidate.is_absolute()+ and candidate.as_posix() == text+ and text not in {"", "."}+ and ".." not in candidate.parts,+ f"{label} is not a canonical repository-relative path",+ )+ return text+++def load_source_manifest(checkout: Path, manifest_path: Path) -> tuple[bytes, dict[str, str]]:+ manifest_bytes = read_immutable_receipt(manifest_path)+ try:+ manifest = json.loads(manifest_bytes.decode("utf-8"), object_pairs_hook=_reject_duplicate_keys)+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise ValidationError(f"source manifest is invalid JSON: {exc}") from exc+ manifest = require_object(+ manifest,+ "source manifest",+ {"schema_version", "manifest_id", "target_os", "description", "exact_paths", "recursive_roots", "include_suffixes", "exclude_suffixes"},+ )+ require(manifest["schema_version"] == SOURCE_MANIFEST_SCHEMA_VERSION, "source manifest schema differs")+ require(manifest["manifest_id"] == SOURCE_MANIFEST_ID, "source manifest ID differs")+ require(manifest["target_os"] == "linux", "source manifest target_os must be linux")+ require_text(manifest["description"], "source manifest description", maximum=1024)+ for field in ("exact_paths", "recursive_roots", "include_suffixes", "exclude_suffixes"):+ require(isinstance(manifest[field], list) and all(isinstance(item, str) for item in manifest[field]), f"source manifest {field} must be a text array")+ require(len(manifest[field]) == len(set(manifest[field])), f"source manifest {field} contains duplicates")+ require(manifest["exact_paths"], "source manifest exact_paths must not be empty")+ include_suffixes = tuple(manifest["include_suffixes"])+ exclude_suffixes = tuple(manifest["exclude_suffixes"])+ require(include_suffixes and all(suffix.startswith(".") for suffix in include_suffixes), "source manifest include_suffixes are invalid")+ require(all(suffix.startswith("_") or suffix.startswith(".") for suffix in exclude_suffixes), "source manifest exclude_suffixes are invalid")++ paths: set[str] = set()+ for raw_path in manifest["exact_paths"]:+ paths.add(_canonical_relative_path(raw_path, "source manifest exact path"))+ for raw_root in manifest["recursive_roots"]:+ root_text = _canonical_relative_path(raw_root, "source manifest recursive root")+ root = checkout / root_text+ require(root.is_dir() and not root.is_symlink(), f"source manifest recursive root is not a regular directory: {root_text}")+ for candidate in root.rglob("*"):+ if candidate.is_dir():+ continue+ relative = candidate.relative_to(checkout).as_posix()+ if candidate.name.endswith(exclude_suffixes):+ continue+ if not candidate.name.endswith(include_suffixes):+ continue+ paths.add(relative)+ hashes: dict[str, str] = {}+ checkout_resolved = checkout.resolve(strict=True)+ for relative in sorted(paths):+ candidate = checkout / relative+ try:+ metadata = candidate.lstat()+ except OSError as exc:+ raise ValidationError(f"unable to inspect governed source {relative}: {exc}") from exc+ require(stat.S_ISREG(metadata.st_mode), f"governed source is not a regular file: {relative}")+ require(not stat.S_ISLNK(metadata.st_mode), f"governed source is a symlink: {relative}")+ resolved = candidate.resolve(strict=True)+ require(resolved.is_relative_to(checkout_resolved), f"governed source escapes checkout: {relative}")+ source_bytes = read_immutable_receipt(candidate)+ hashes[relative] = hashlib.sha256(source_bytes).hexdigest()+ require(hashes, "source manifest expands to no source files")+ return manifest_bytes, hashes+++def verify_source_commit(checkout: Path, source_commit: str, source_hashes: dict[str, str]) -> None:+ def git(*arguments: str) -> bytes:+ try:+ result = subprocess.run(+ ["git", *arguments],+ cwd=checkout,+ check=True,+ capture_output=True,+ )+ except (OSError, subprocess.CalledProcessError) as exc:+ detail = exc.stderr.decode("utf-8", errors="replace").strip() if isinstance(exc, subprocess.CalledProcessError) else str(exc)+ raise ValidationError(f"unable to verify receipt source commit: {detail}") from exc+ return result.stdout++ top_level = Path(git("rev-parse", "--show-toplevel").decode("utf-8").strip()).resolve(strict=True)+ require(top_level == checkout, "source checkout is not the requested repository root")+ resolved = git("rev-parse", "--verify", f"{source_commit}^{{commit}}").decode("ascii").strip()+ require(resolved == source_commit, "receipt source_commit is not an exact commit")+ for relative, expected_digest in source_hashes.items():+ source_bytes = git("show", f"{source_commit}:{relative}")+ require(+ hashlib.sha256(source_bytes).hexdigest() == expected_digest,+ f"governed source {relative} does not match receipt source_commit",+ )+++def immutable_artifact_snapshot(path: Path, expected_basename: str, *, executable: bool) -> Any:+ require(path.name == expected_basename, f"artifact path basename must be {expected_basename}")+ flags = os.O_RDONLY+ if hasattr(os, "O_CLOEXEC"):+ flags |= os.O_CLOEXEC+ if hasattr(os, "O_NOFOLLOW"):+ flags |= os.O_NOFOLLOW+ if hasattr(os, "O_NONBLOCK"):+ flags |= os.O_NONBLOCK+ try:+ descriptor = os.open(path, flags)+ except OSError as exc:+ raise ValidationError(f"unable to open artifact {expected_basename}: {exc}") from exc+ try:+ before = os.fstat(descriptor)+ require(stat.S_ISREG(before.st_mode), f"artifact {expected_basename} must be a regular file")+ require(0 < before.st_size <= MAX_ARTIFACT_BYTES, f"artifact {expected_basename} size is invalid")+ if executable:+ require(before.st_mode & 0o111 != 0, f"artifact {expected_basename} is not executable")+ with tempfile.TemporaryDirectory(prefix="pulse-rootless-artifact-") as temporary:+ snapshot = Path(temporary) / expected_basename+ target = os.open(snapshot, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o700 if executable else 0o600)+ digest = hashlib.sha256()+ copied = 0+ try:+ while True:+ chunk = os.read(descriptor, 1024 * 1024)+ if not chunk:+ break+ copied += len(chunk)+ require(copied <= MAX_ARTIFACT_BYTES, f"artifact {expected_basename} exceeds the maximum size")+ digest.update(chunk)+ offset = 0+ while offset < len(chunk):+ offset += os.write(target, chunk[offset:])+ os.fsync(target)+ finally:+ os.close(target)+ after = os.fstat(descriptor)+ require(+ (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns)+ == (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns),+ f"artifact {expected_basename} changed while being snapshotted",+ )+ require(copied == before.st_size, f"artifact {expected_basename} snapshot is incomplete")+ yield snapshot, digest.hexdigest()+ finally:+ os.close(descriptor)+++def inspect_go_build_identity(artifact: Path) -> dict[str, Any]:+ try:+ result = subprocess.run(+ ["go", "version", "-m", str(artifact)],+ check=True,+ capture_output=True,+ timeout=15,+ )+ except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:+ detail = ""+ if isinstance(exc, subprocess.CalledProcessError):+ detail = exc.stderr.decode("utf-8", errors="replace").strip()+ raise ValidationError(f"unable to inspect Go artifact build identity: {detail or exc}") from exc+ require(len(result.stdout) <= 256 * 1024, "Go artifact metadata is unexpectedly large")+ try:+ lines = result.stdout.decode("utf-8").splitlines()+ except UnicodeDecodeError as exc:+ raise ValidationError("Go artifact metadata is not UTF-8") from exc+ require(lines and ": " in lines[0], "Go artifact metadata header is malformed")+ go_version = lines[0].rsplit(": ", 1)[1]+ require_text(go_version, "Go artifact go_version", pattern=GO_VERSION_RE, maximum=32)+ settings: dict[str, str] = {}+ package = ""+ for line in lines[1:]:+ fields = line.strip().split("\t")+ if len(fields) == 2 and fields[0] == "path":+ require(not package, "Go artifact metadata contains duplicate package path")+ package = fields[1]+ continue+ if len(fields) != 2 or fields[0] != "build" or "=" not in fields[1]:+ continue+ key, value = fields[1].split("=", 1)+ require(key not in settings, f"Go artifact metadata contains duplicate build setting {key}")+ settings[key] = value+ require(settings.get("vcs") == "git", "Go artifact is not git VCS stamped")+ require_text(package, "Go artifact package", maximum=256)+ revision = require_text(settings.get("vcs.revision"), "Go artifact vcs.revision", pattern=COMMIT_RE, maximum=40)+ require(settings.get("vcs.modified") == "false", "Go artifact is modified or lacks vcs.modified=false")+ return {"package": package, "go_version": go_version, "vcs_revision": revision, "vcs_modified": False}+++def create_attestation(+ receipt_path: Path,+ qualification_test_path: Path,+ collector_path: Path,+ helper_path: Path,+ installer_path: Path,+ *,+ checkout: Path | None = None,+ manifest_path: Path | None = None,+ verify_git_commit: bool = True,+) -> dict[str, Any]:+ data = read_immutable_receipt(receipt_path)+ receipt = parse_receipt_bytes(data)+ checkout = (checkout or Path(__file__).resolve().parents[2]).resolve(strict=True)+ manifest_path = manifest_path or checkout / SOURCE_MANIFEST_PATH+ manifest_bytes, source_hashes = load_source_manifest(checkout, manifest_path)+ require(receipt["source_hashes"] == source_hashes, "receipt source_hashes do not match the canonical source manifest")+ if verify_git_commit:+ verify_source_commit(checkout, receipt["source_commit"], source_hashes)+ supplied_artifacts = {+ "qualification_test": (qualification_test_path, "dockeragent.test", True),+ "collector": (collector_path, "pulse-agent", True),+ "helper": (helper_path, "pulse-agent-helper", True),+ "installer": (installer_path, "install.sh", False),+ }+ artifact_bindings: dict[str, dict[str, Any]] = {}+ with contextlib.ExitStack() as stack:+ snapshots: dict[str, Path] = {}+ for name, (path, basename, executable) in supplied_artifacts.items():+ snapshot, artifact_digest = stack.enter_context(+ immutable_artifact_snapshot(path, basename, executable=executable)+ )+ require(artifact_digest == receipt["artifacts"][name]["sha256"], f"{name} bytes do not match receipt SHA-256")+ snapshots[name] = snapshot+ artifact_bindings[name] = {"path_basename": basename, "sha256": artifact_digest}+ for name in ("qualification_test", "collector", "helper"):+ build = inspect_go_build_identity(snapshots[name])+ claimed = receipt["artifacts"][name]+ require(build["package"] == claimed["package"], f"{name} Go package differs from receipt")+ require(build["go_version"] == claimed["go_version"], f"{name} Go version differs from receipt")+ require(build["vcs_revision"] == claimed["vcs_revision"] == receipt["source_commit"], f"{name} VCS revision differs")+ require_bool(build["vcs_modified"], False, f"{name} vcs.modified")+ artifact_bindings[name].update(build)+ validator_path = Path(__file__).absolute()+ validator_bytes = read_immutable_receipt(validator_path)+ return {+ "schema_version": ATTESTATION_SCHEMA_VERSION,+ "kind": ATTESTATION_KIND,+ "classification": CLASSIFICATION,+ "receipt_sha256": hashlib.sha256(data).hexdigest(),+ "validator_source_sha256": hashlib.sha256(validator_bytes).hexdigest(),+ "source_manifest_schema_version": SOURCE_MANIFEST_SCHEMA_VERSION,+ "source_manifest_id": SOURCE_MANIFEST_ID,+ "source_manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(),+ "source_hash_count": len(source_hashes),+ "source_commit": receipt["source_commit"],+ "source_commit_verified": verify_git_commit,+ "artifact_bindings": artifact_bindings,+ "validated_runtimes": list(REQUIRED_RUNTIMES),+ "limitations": [+ "not-published-release-provenance",+ "not-default-profile-authorization",+ "not-independent-security-review",+ "production-exact-scope-proof-is-external-prior",+ ],+ }+++def parse_args(argv: list[str] | None = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("receipt", type=Path, help="schema-v1 rootless qualification receipt")+ parser.add_argument("--qualification-test", required=True, type=Path, help="exact dockeragent.test qualification binary")+ parser.add_argument("--collector", required=True, type=Path, help="exact pulse-agent binary")+ parser.add_argument("--helper", required=True, type=Path, help="exact pulse-agent-helper binary")+ parser.add_argument("--installer", required=True, type=Path, help="exact install.sh blob")+ return parser.parse_args(argv)+++def main(argv: list[str] | None = None) -> int:+ arguments = parse_args(argv)+ try:+ attestation = create_attestation(+ arguments.receipt,+ arguments.qualification_test,+ arguments.collector,+ arguments.helper,+ arguments.installer,+ )+ except ValidationError as exc:+ print(f"rootless receipt validation failed: {exc}", file=sys.stderr)+ return 1+ print(json.dumps(attestation, sort_keys=True, separators=(",", ":")))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/release_control/secure_runtime_rootless_attestation_v1_test.py b/scripts/release_control/secure_runtime_rootless_attestation_v1_test.pynew file mode 100644index 0000000000..2044f63301--- /dev/null+++ b/scripts/release_control/secure_runtime_rootless_attestation_v1_test.py@@ -0,0 +1,392 @@+#!/usr/bin/env python3+"""Adversarial tests for the schema-v1 rootless qualification validator."""++from __future__ import annotations++import copy+import hashlib+import json+import os+import subprocess+import sys+import tempfile+import unittest+from datetime import datetime, timedelta, timezone+from pathlib import Path+from unittest import mock++sys.path.insert(0, str(Path(__file__).resolve().parent))+import secure_runtime_rootless_attestation_v1 as attester+++def sha(value: str | bytes) -> str:+ return hashlib.sha256(value if isinstance(value, bytes) else value.encode()).hexdigest()+++class RootlessAttestationV1Test(unittest.TestCase):+ def setUp(self) -> None:+ self.temp = tempfile.TemporaryDirectory()+ self.root = Path(self.temp.name)+ self.commit = "a" * 40+ self.artifacts = {}+ for key, basename in {+ "qualification_test": "dockeragent.test",+ "collector": "pulse-agent",+ "helper": "pulse-agent-helper",+ "installer": "install.sh",+ }.items():+ path = self.root / basename+ path.write_bytes(f"{key}-bytes".encode())+ path.chmod(0o700 if key != "installer" else 0o600)+ self.artifacts[key] = path+ self.sources = {+ "runtime.go": b"package runtime\n",+ "internal/api/api_tokens.go": b"package api\n",+ "scripts/install.sh": self.artifacts["installer"].read_bytes(),+ }+ for relative, data in self.sources.items():+ target = self.root / relative+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(data)+ self.manifest = self.root / "manifest.json"+ self.manifest.write_text(json.dumps({+ "schema_version": 1, "manifest_id": attester.SOURCE_MANIFEST_ID,+ "target_os": "linux", "description": "test boundary",+ "exact_paths": sorted(self.sources), "recursive_roots": [],+ "include_suffixes": [".go"], "exclude_suffixes": ["_test.go"],+ }), encoding="utf-8")+ self.receipt = self.make_receipt()++ def tearDown(self) -> None:+ self.temp.cleanup()++ @staticmethod+ def ts(index: int) -> str:+ value = datetime(2026, 9, 1, 10, tzinfo=timezone.utc) + timedelta(minutes=index)+ return value.isoformat().replace("+00:00", "Z")++ @staticmethod+ def socket(runtime: str, uid: int, gid: int, mode: str) -> dict:+ return {"runtime": runtime, "path": attester.expected_socket_path(runtime, uid), "uid": uid,+ "gid": gid, "mode": mode, "type": "unix", "symlink": False}++ def direct(self, runtime: str, pid: int, daemon: str, uid: int, gid: int, mode: str) -> dict:+ return {+ "collector_pid": pid, "service_pid": pid, "collection_path": "collector-owned-rootless-socket",+ "inventory_complete": True, "inventory_count": 2,+ "semantic_sha256": sha(runtime + "-semantic"),+ "full_fields_present": True, "stats_present": True,+ "secondary_structure_sha256": sha(runtime + "-secondary"),+ "daemon_id": daemon, "daemon_rootless": True,+ "socket_path": attester.expected_socket_path(runtime, uid), "socket_uid": uid,+ "socket_gid": gid, "socket_mode": mode, "socket_type": "unix", "socket_symlink": False,+ }++ def make_run(self, runtime: str, index: int) -> dict:+ uid = 1200 + index * 100+ gid, mode = uid, "0600" if runtime == "docker" else "0660"+ daemon = runtime + "-durable-daemon"+ fresh = self.direct(runtime, 4100 + index * 100, daemon, uid, gid, mode)+ migration = {**self.direct(runtime, fresh["collector_pid"] + 1, daemon, uid, gid, mode),+ "legacy_profile": "root-command-capable", "target_profile": "typed-helper-monitoring-only",+ "authority_reduced": True, "legacy_collector_pid": fresh["collector_pid"] + 50}+ restart = {**self.direct(runtime, fresh["collector_pid"] + 2, daemon, uid, gid, mode),+ "previous_collector_pid": migration["collector_pid"],+ "previous_report_stream_id": runtime + "-migration-stream"}+ daemon_restart = {**self.direct(runtime, restart["collector_pid"], daemon, uid, gid, mode),+ "previous_daemon_pid": 5100 + index * 100, "daemon_pid": 5101 + index * 100,+ "previous_daemon_invocation_id": runtime + "-invocation-before",+ "daemon_invocation_id": runtime + "-invocation-after"}+ rootful_semantic = sha(runtime + "-rootful-semantic")+ fallback = {+ "collector_pid": restart["collector_pid"], "collection_mode": "typed-helper-summary",+ "direct_runtime_available": False, "helper_fallback": True, "inventory_complete": True,+ "inventory_count": 3, "rootful_baseline_inventory_count": 3,+ "semantic_sha256": rootful_semantic, "rootful_baseline_semantic_sha256": rootful_semantic,+ "full_fields_present": False, "stats_present": False, "secondary_structure_sha256": "",+ "container_actions_enabled": False, "container_updates_enabled": False, "collector_restart_count": 0,+ }+ recovery = self.direct(runtime, restart["collector_pid"], daemon, uid, gid, mode)+ ambiguity = {+ "protected_collector_pid": restart["collector_pid"], "probe_kind": "separate-unpinned-collector",+ "live_sockets": [self.socket(name, uid, gid, mode) for name in attester.REQUIRED_RUNTIMES],+ "admission_refused": True, "fail_closed": True, "daemon_probe_count": 0,+ "container_actions_enabled": False, "collector_restart_count": 0,+ }+ pin = {**self.direct(runtime, fresh["collector_pid"] + 3, daemon, uid, gid, mode),+ "previous_collector_pid": restart["collector_pid"],+ "previous_report_stream_id": runtime + "-restart-stream",+ "pin_source": "root-owned-systemd-unit", "pinned_socket_path": attester.expected_socket_path(runtime, uid),+ "socket_absent_observed": True, "fallback_report_sequence": 10, "recovery_report_sequence": 19,+ "recovered_socket_path": attester.expected_socket_path(runtime, uid),+ "selected_socket_path": attester.expected_socket_path(runtime, uid),+ "recovered_socket_uid": uid, "recovered_socket_gid": gid, "recovered_socket_mode": mode,+ "recovered_socket_type": "unix", "recovered_socket_symlink": False,+ "candidate_count": 1, "daemon_probe_count": 1, "collector_restart_count": 1}+ parity = {+ "collector_pid": pin["collector_pid"], "baseline_kind": "root-client-same-rootless-daemon",+ "baseline_inventory_count": 2, "collector_inventory_count": 2,+ "baseline_semantic_sha256": fresh["semantic_sha256"],+ "collector_semantic_sha256": fresh["semantic_sha256"],+ "collector_full_fields_present": True, "collector_stats_present": True,+ "collector_secondary_inventory_present": True,+ }+ authority = {+ "collector_pid": pin["collector_pid"], "collector_uid": uid, "effective_uid": uid,+ "effective_root": False, "safe_profile_enabled": True, "commands_enabled": False,+ "privileged_helper_enabled": True, "reduction_request_observed": True,+ "collector_command_transport_present": False, "collector_command_session_present": False,+ "container_actions_enabled": False, "container_updates_enabled": False,+ "rootful_socket_access": False, "helper_network_access": False,+ }+ evidence = [fresh, migration, restart, daemon_restart, fallback, recovery, ambiguity, pin, parity, authority,+ {"runtime_stopped": True, "socket_absent": True, "fixtures_removed": True, "user_state_clean": True}]+ reports = {+ "fresh_install": (runtime + "-fresh-stream", 1),+ "legacy_migration": (runtime + "-migration-stream", 1),+ "collector_restart": (runtime + "-restart-stream", 1),+ "daemon_restart": (runtime + "-restart-stream", 2),+ "socket_loss_helper_fallback": (runtime + "-restart-stream", 3),+ "direct_recovery": (runtime + "-restart-stream", 4),+ "exact_pin_recovery": (runtime + "-update-stream", 20),+ "telemetry_parity": (runtime + "-update-stream", 21),+ }+ scenarios = []+ for scenario_index, name in enumerate(attester.REQUIRED_SCENARIOS):+ stream, sequence = reports.get(name, (None, None))+ scenarios.append({"name": name, "result": "passed",+ "started_at": self.ts(index * 30 + scenario_index * 2 + 1),+ "completed_at": self.ts(index * 30 + scenario_index * 2 + 2),+ "report_stream_id": stream, "report_sequence": sequence,+ "evidence": evidence[scenario_index]})+ return {+ "host": {"machine_id": f"{index + 1:032x}", "architecture": "amd64",+ "kernel": "6.12.0-test", "systemd_version": "systemd-257"},+ "runtime": {"runtime": runtime, "runtime_version": "27.3.1" if runtime == "docker" else "5.2.2",+ "daemon_id": daemon, "collector_uid": uid,+ "socket_path": attester.expected_socket_path(runtime, uid), "socket_uid": uid,+ "socket_gid": gid, "socket_mode": mode, "socket_type": "unix",+ "socket_symlink": False, "daemon_rootless": True},+ "scenarios": scenarios,+ }++ def make_receipt(self) -> dict:+ packages = {+ "qualification_test": "github.com/rcourtman/pulse-go-rewrite/scripts/installtests.test",+ "collector": "github.com/rcourtman/pulse-go-rewrite/cmd/pulse-agent",+ "helper": "github.com/rcourtman/pulse-go-rewrite/cmd/pulse-agent-helper",+ }+ artifacts = {"installer": {"path_basename": "install.sh", "sha256": sha(self.artifacts["installer"].read_bytes())}}+ for name, package in packages.items():+ artifacts[name] = {"path_basename": self.artifacts[name].name,+ "sha256": sha(self.artifacts[name].read_bytes()), "package": package,+ "go_version": "go1.25.1", "vcs_revision": self.commit, "vcs_modified": False}+ return {+ "schema_version": 1, "kind": attester.RECEIPT_KIND, "result": "passed",+ "source_commit": self.commit, "started_at": self.ts(0), "completed_at": self.ts(60),+ "source_hashes": {name: sha(data) for name, data in self.sources.items()},+ "artifacts": artifacts, "runs": [self.make_run("docker", 0), self.make_run("podman", 1)],+ }++ def scenario(self, receipt: dict, run: int, name: str) -> dict:+ return receipt["runs"][run]["scenarios"][attester.REQUIRED_SCENARIOS.index(name)]++ def invalid(self, mutation) -> None:+ receipt = copy.deepcopy(self.receipt)+ mutation(receipt)+ with self.assertRaises(attester.ValidationError):+ attester.validate_receipt(receipt)++ def write_receipt(self, receipt: dict | None = None) -> Path:+ path = self.root / "receipt.json"+ path.write_text(json.dumps(receipt or self.receipt, sort_keys=True), encoding="utf-8")+ return path++ def valid_build(self, package: str) -> dict:+ return {"package": package, "go_version": "go1.25.1", "vcs_revision": self.commit, "vcs_modified": False}++ def attest(self, receipt: dict | None = None) -> dict:+ packages = {name: self.receipt["artifacts"][name]["package"] for name in ("qualification_test", "collector", "helper")}+ with mock.patch.object(attester, "inspect_go_build_identity", side_effect=lambda path: self.valid_build(packages[{v.name: k for k, v in self.artifacts.items()}[path.name]])):+ return attester.create_attestation(+ self.write_receipt(receipt), self.artifacts["qualification_test"], self.artifacts["collector"],+ self.artifacts["helper"], self.artifacts["installer"], checkout=self.root,+ manifest_path=self.manifest, verify_git_commit=False)++ def test_valid_two_disposable_host_receipt_and_artifacts(self) -> None:+ attester.validate_receipt(self.receipt)+ result = self.attest()+ self.assertEqual(result["validated_runtimes"], ["docker", "podman"])+ self.assertEqual(set(result["artifact_bindings"]), set(self.artifacts))+ self.assertIn("not-default-profile-authorization", result["limitations"])++ def test_topology_runtime_and_source_fail_closed(self) -> None:+ mutations = [+ lambda r: r["runs"].pop(),+ lambda r: r["runs"][1]["host"].update(machine_id=r["runs"][0]["host"]["machine_id"]),+ lambda r: r["runs"].reverse(),+ lambda r: r["runs"][0]["runtime"].update(daemon_rootless=False),+ lambda r: r["runs"][0]["runtime"].update(socket_path="/var/run/docker.sock"),+ lambda r: r["runs"][0]["runtime"].update(socket_mode="0666"),+ lambda r: r["source_hashes"].update({"scripts/install.sh": sha("wrong")}),+ ]+ for mutation in mutations:+ with self.subTest(mutation=mutation): self.invalid(mutation)++ def test_migration_restart_stream_and_daemon_causality(self) -> None:+ mutations = [+ lambda r: r["runs"][0]["scenarios"].reverse(),+ lambda r: self.scenario(r, 0, "legacy_migration")["evidence"].update(authority_reduced=False),+ lambda r: self.scenario(r, 0, "legacy_migration").update(report_stream_id="docker-fresh-stream"),+ lambda r: self.scenario(r, 0, "collector_restart")["evidence"].update(previous_collector_pid=9999),+ lambda r: self.scenario(r, 0, "daemon_restart")["evidence"].update(daemon_id="recreated"),+ lambda r: self.scenario(r, 0, "daemon_restart")["evidence"].update(previous_daemon_pid=5101),+ lambda r: self.scenario(r, 0, "daemon_restart")["evidence"].update(previous_daemon_invocation_id="docker-invocation-after"),+ lambda r: self.scenario(r, 0, "direct_recovery").update(report_sequence=2),+ ]+ for mutation in mutations:+ with self.subTest(mutation=mutation): self.invalid(mutation)++ def test_complete_fallback_reduction_ambiguity_and_structural_parity(self) -> None:+ fallback = self.scenario(self.receipt, 0, "socket_loss_helper_fallback")["evidence"]+ self.assertTrue(fallback["inventory_complete"])+ self.assertFalse(fallback["stats_present"])+ self.assertNotIn("stats_sha256", self.scenario(self.receipt, 0, "fresh_install")["evidence"])+ mutations = [+ lambda r: self.scenario(r, 0, "socket_loss_helper_fallback")["evidence"].update(inventory_complete=False),+ lambda r: self.scenario(r, 0, "socket_loss_helper_fallback")["evidence"].update(stats_present=True),+ lambda r: self.scenario(r, 0, "socket_loss_helper_fallback")["evidence"].update(container_actions_enabled=True),+ lambda r: self.scenario(r, 0, "dual_socket_ambiguity_refusal")["evidence"].update(daemon_probe_count=1),+ lambda r: self.scenario(r, 0, "dual_socket_ambiguity_refusal")["evidence"]["live_sockets"][0].update(path="/tmp/socket"),+ lambda r: self.scenario(r, 0, "daemon_restart")["evidence"].update(full_fields_present=False),+ ]+ for mutation in mutations:+ with self.subTest(mutation=mutation): self.invalid(mutation)++ def test_exact_pin_update_authority_and_cleanup_are_observable(self) -> None:+ mutations = [+ lambda r: self.scenario(r, 0, "exact_pin_recovery")["evidence"].update(collector_pid=4102, service_pid=4102),+ lambda r: self.scenario(r, 0, "exact_pin_recovery").update(report_stream_id="docker-restart-stream"),+ lambda r: self.scenario(r, 0, "exact_pin_recovery")["evidence"].update(fallback_report_sequence=20),+ lambda r: self.scenario(r, 0, "telemetry_parity")["evidence"].update(collector_semantic_sha256=sha("wrong")),+ lambda r: self.scenario(r, 0, "authority_isolation")["evidence"].update(api_scopes=["agent:report"]),+ lambda r: self.scenario(r, 0, "authority_isolation")["evidence"].update(reduction_request_observed=False),+ lambda r: self.scenario(r, 0, "authority_isolation")["evidence"].update(collector_command_session_present=True),+ lambda r: self.scenario(r, 0, "authority_isolation")["evidence"].update(helper_network_access=True),+ lambda r: self.scenario(r, 0, "cleanup")["evidence"].update(user_state_clean=False),+ ]+ for mutation in mutations:+ with self.subTest(mutation=mutation): self.invalid(mutation)++ def test_token_named_governed_source_is_allowed_but_secret_evidence_is_not(self) -> None:+ attester.validate_receipt(self.receipt)+ self.invalid(lambda r: r["runs"][0]["host"].update(kernel="Bearer abcdefghijklmnop"))+ with self.assertRaises(attester.ValidationError): attester.reject_sensitive_evidence({"api_token": "redacted"})++ def test_artifact_bytes_symlinks_metadata_and_package_substitution_fail(self) -> None:+ self.artifacts["collector"].write_bytes(b"different")+ self.artifacts["collector"].chmod(0o700)+ with self.assertRaises(attester.ValidationError): self.attest()+ self.artifacts["collector"].write_bytes(b"collector-bytes")+ self.artifacts["collector"].chmod(0o700)+ helper_path = self.artifacts["helper"]+ real = self.root / "helper-real"+ helper_path.rename(real)+ helper_path.symlink_to(real)+ with self.assertRaises(attester.ValidationError): self.attest()+ helper_path.unlink()+ real.rename(helper_path)+ wrong = self.valid_build("github.com/rcourtman/pulse-go-rewrite/cmd/pulse-agent")+ with mock.patch.object(attester, "inspect_go_build_identity", return_value=wrong):+ with self.assertRaises(attester.ValidationError):+ attester.create_attestation(self.write_receipt(), *self.artifacts.values(), checkout=self.root,+ manifest_path=self.manifest, verify_git_commit=False)+ packages = [self.receipt["artifacts"][name]["package"] for name in ("qualification_test", "collector", "helper")]+ identities = [self.valid_build(package) for package in packages]+ identities[1]["vcs_revision"] = "b" * 40+ with mock.patch.object(attester, "inspect_go_build_identity", side_effect=identities):+ with self.assertRaises(attester.ValidationError):+ attester.create_attestation(self.write_receipt(), *self.artifacts.values(), checkout=self.root,+ manifest_path=self.manifest, verify_git_commit=False)++ @unittest.skipUnless(hasattr(os, "mkfifo"), "FIFO validation requires Unix mkfifo")+ def test_fifo_receipt_and_artifact_paths_are_rejected_without_blocking(self) -> None:+ module_dir = Path(attester.__file__).resolve().parent+ receipt_fifo = self.root / "receipt.fifo"+ os.mkfifo(receipt_fifo, 0o600)+ receipt_probe = (+ "import sys; from pathlib import Path; "+ "sys.path.insert(0, sys.argv[1]); "+ "import secure_runtime_rootless_attestation_v1 as a; "+ "a.read_immutable_receipt(Path(sys.argv[2]))"+ )+ result = subprocess.run(+ [sys.executable, "-I", "-c", receipt_probe, str(module_dir), str(receipt_fifo)],+ capture_output=True,+ timeout=2,+ )+ self.assertNotEqual(result.returncode, 0)+ self.assertIn(b"receipt must be a regular file", result.stderr)++ artifact_dir = self.root / "fifo-artifact"+ artifact_dir.mkdir()+ artifact_fifo = artifact_dir / "pulse-agent"+ os.mkfifo(artifact_fifo, 0o700)+ artifact_probe = (+ "import sys; from pathlib import Path; "+ "sys.path.insert(0, sys.argv[1]); "+ "import secure_runtime_rootless_attestation_v1 as a; "+ "ctx=a.immutable_artifact_snapshot(Path(sys.argv[2]), 'pulse-agent', executable=True); "+ "ctx.__enter__()"+ )+ result = subprocess.run(+ [sys.executable, "-I", "-c", artifact_probe, str(module_dir), str(artifact_fifo)],+ capture_output=True,+ timeout=2,+ )+ self.assertNotEqual(result.returncode, 0)+ self.assertIn(b"artifact pulse-agent must be a regular file", result.stderr)++ def test_go_metadata_parser_rejects_modified_and_mismatched_vcs(self) -> None:+ package = "github.com/rcourtman/pulse-go-rewrite/cmd/pulse-agent"+ output = (f"/tmp/pulse-agent: go1.25.1\n\tpath\t{package}\n\tbuild\tvcs=git\n"+ f"\tbuild\tvcs.revision={self.commit}\n\tbuild\tvcs.modified=false\n").encode()+ with mock.patch.object(attester.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, output, b"")):+ self.assertEqual(attester.inspect_go_build_identity(self.artifacts["collector"])["package"], package)+ for bad in (output.replace(b"vcs.modified=false", b"vcs.modified=true"),+ output.replace(b"vcs=git", b"vcs=hg")):+ with mock.patch.object(attester.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, bad, b"")):+ with self.assertRaises(attester.ValidationError): attester.inspect_go_build_identity(self.artifacts["collector"])++ def test_duplicate_json_source_manifest_and_cli_contract(self) -> None:+ with self.assertRaises(attester.ValidationError):+ attester.parse_receipt_bytes(b'{"schema_version":1,"schema_version":1}')+ bad = copy.deepcopy(self.receipt)+ bad["source_hashes"]["runtime.go"] = sha("wrong")+ with self.assertRaises(attester.ValidationError): self.attest(bad)+ args = attester.parse_args(["receipt.json", "--qualification-test", "dockeragent.test",+ "--collector", "pulse-agent", "--helper", "pulse-agent-helper",+ "--installer", "install.sh"])+ self.assertEqual(args.qualification_test.name, "dockeragent.test")++ def test_canonical_manifest_expands_the_executed_boundary(self) -> None:+ checkout = Path(__file__).resolve().parents[2]+ _, hashes = attester.load_source_manifest(+ checkout, checkout / attester.SOURCE_MANIFEST_PATH+ )+ required = {+ "scripts/install.sh",+ "scripts/release_ldflags.sh",+ "scripts/installtests/secure_runtime_rootless_qualification_test.go",+ "scripts/installtests/secure_runtime_systemd_lab_test.go",+ "scripts/release_control/secure_runtime_rootless_attestation_v1.py",+ "scripts/release_control/secure_runtime_rootless_source_manifest_v1.json",+ "scripts/run-secure-runtime-rootless-qualification.sh",+ "internal/api/api_token_identity.go",+ "pkg/auth/token.go",+ }+ self.assertTrue(required.issubset(hashes), sorted(required - set(hashes)))+++if __name__ == "__main__":+ unittest.main()diff --git a/scripts/release_control/secure_runtime_rootless_source_manifest_v1.json b/scripts/release_control/secure_runtime_rootless_source_manifest_v1.jsonnew file mode 100644index 0000000000..247f377e8e--- /dev/null+++ b/scripts/release_control/secure_runtime_rootless_source_manifest_v1.json@@ -0,0 +1,49 @@+{+ "schema_version": 1,+ "manifest_id": "secure-runtime-rootless-v1",+ "target_os": "linux",+ "description": "Production source boundary for collector-owned rootless Docker and Podman discovery, direct collection, typed-helper fallback, recovery, installer pinning, and the standalone rootless qualification packet.",+ "exact_paths": [+ "VERSION",+ "go.mod",+ "go.sum",+ "pkg/agents/docker/report.go",+ "pkg/agents/docker/report_limits.go",+ "scripts/install.sh",+ "scripts/release_ldflags.sh",+ "scripts/installtests/secure_runtime_rootless_qualification_test.go",+ "scripts/installtests/secure_runtime_systemd_lab_test.go",+ "scripts/installtests/testdata/secure_runtime_docker_fixture.go",+ "scripts/release_control/secure_runtime_rootless_attestation_v1.py",+ "scripts/release_control/secure_runtime_rootless_source_manifest_v1.json",+ "scripts/run-secure-runtime-rootless-qualification.sh"+ ],+ "recursive_roots": [+ "cmd/pulse-agent",+ "cmd/pulse-agent-helper",+ "internal/actionrunner",+ "internal/agentexec",+ "internal/agenthelper",+ "internal/agenttls",+ "internal/agentupdate",+ "internal/api",+ "internal/collectorlifecycle",+ "internal/config",+ "internal/dockeragent",+ "internal/hostagent",+ "internal/operationreceipt",+ "internal/securityutil",+ "internal/updatesignature",+ "pkg/auth",+ "pkg/agents/host",+ "pkg/securityutil",+ "pkg/tlsutil"+ ],+ "include_suffixes": [+ ".go",+ ".tmpl"+ ],+ "exclude_suffixes": [+ "_test.go"+ ]+}diff --git a/scripts/run-secure-runtime-rootless-qualification.sh b/scripts/run-secure-runtime-rootless-qualification.shnew file mode 100755index 0000000000..df56ba8f81--- /dev/null+++ b/scripts/run-secure-runtime-rootless-qualification.sh@@ -0,0 +1,308 @@+#!/usr/bin/env bash+set -euo pipefail++readonly REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+readonly UBUNTU_IMAGE="${PULSE_ROOTLESS_UBUNTU_IMAGE:?set PULSE_ROOTLESS_UBUNTU_IMAGE to an immutable ubuntu@sha256:... Ubuntu 24.04 image}"+readonly OUTPUT_PARENT="${PULSE_ROOTLESS_QUALIFICATION_OUTPUT_DIR:?set PULSE_ROOTLESS_QUALIFICATION_OUTPUT_DIR to an existing absolute private directory}"+readonly CONFIRM="${PULSE_ROOTLESS_QUALIFICATION_CONFIRM:-}"++if [[ ! "${UBUNTU_IMAGE}" =~ ^ubuntu@sha256:[0-9a-f]{64}$ ]]; then+ echo "ERROR: PULSE_ROOTLESS_UBUNTU_IMAGE must be an exact ubuntu@sha256 digest" >&2+ exit 2+fi+if [[ "${OUTPUT_PARENT}" != /* || ! -d "${OUTPUT_PARENT}" || -L "${OUTPUT_PARENT}" ]]; then+ echo "ERROR: PULSE_ROOTLESS_QUALIFICATION_OUTPUT_DIR must be an existing absolute non-symlink directory" >&2+ exit 2+fi+if [[ "$(stat -c '%a' "${OUTPUT_PARENT}" 2>/dev/null || stat -f '%Lp' "${OUTPUT_PARENT}")" != "700" ]]; then+ echo "ERROR: qualification output directory must have exact mode 0700" >&2+ exit 2+fi+if ! command -v docker >/dev/null 2>&1 || ! docker info >/dev/null 2>&1; then+ echo "ERROR: a working Docker CLI/daemon is required to create disposable qualification containers" >&2+ exit 2+fi+if [[ "$(git -C "${REPO_ROOT}" branch --show-current)" != "main" ]]; then+ echo "ERROR: qualification builds are allowed only from main" >&2+ exit 2+fi+if [[ -n "$(git -C "${REPO_ROOT}" status --porcelain)" ]]; then+ echo "ERROR: qualification requires a clean exact source checkout" >&2+ exit 2+fi++readonly SOURCE_COMMIT="$(git -C "${REPO_ROOT}" rev-parse HEAD)"+readonly EXPECTED_CONFIRM="I_HAVE_VERIFIED_THESE_ARE_DISPOSABLE_ROOTLESS_SYSTEMD_CONTAINERS_COMMIT_${SOURCE_COMMIT}"+if [[ "${CONFIRM}" != "${EXPECTED_CONFIRM}" ]]; then+ echo "ERROR: exact destructive opt-in required:" >&2+ echo "export PULSE_ROOTLESS_QUALIFICATION_CONFIRM=${EXPECTED_CONFIRM}" >&2+ exit 2+fi++readonly RUN_STAMP="$(date -u +%Y%m%dT%H%M%SZ)"+readonly OUTPUT_DIR="${OUTPUT_PARENT}/${RUN_STAMP}-${SOURCE_COMMIT:0:12}"+readonly IMAGE_TAG="pulse-rootless-qualification:${SOURCE_COMMIT:0:12}"+readonly CONTAINER_RUN_LABEL="org.pulse.rootless-qualification.run"+readonly CONTAINER_RUN_NONCE="$(openssl rand -hex 16)"+PACKET_DIR="$(mktemp -d /tmp/pulse-rootless-packet.XXXXXX)"+CONTAINER_IDS=()++inspect_qualification_container_nonce() {+ local container_id="$1"+ docker inspect --format '{{ index .Config.Labels "org.pulse.rootless-qualification.run" }}' "${container_id}"+}++remove_qualification_container_strict() {+ local container_id="$1"+ local observed_nonce+ local remaining+ if ! observed_nonce="$(inspect_qualification_container_nonce "${container_id}")"; then+ echo "ERROR: unable to verify ownership label for qualification container ${container_id}" >&2+ return 1+ fi+ if [[ "${observed_nonce}" != "${CONTAINER_RUN_NONCE}" ]]; then+ echo "ERROR: qualification container ${container_id} ownership label changed" >&2+ return 1+ fi+ if ! docker rm -f "${container_id}" >/dev/null; then+ echo "ERROR: failed to remove qualification container ${container_id}" >&2+ return 1+ fi+ if ! remaining="$(docker ps -aq --no-trunc --filter "id=${container_id}")"; then+ echo "ERROR: unable to verify removal of qualification container ${container_id}" >&2+ return 1+ fi+ if printf '%s\n' "${remaining}" | grep -Fxq "${container_id}"; then+ echo "ERROR: qualification container ${container_id} remains after removal" >&2+ return 1+ fi+}++remove_qualification_container_best_effort() {+ local container_id="$1"+ local observed_nonce+ if ! observed_nonce="$(inspect_qualification_container_nonce "${container_id}" 2>/dev/null)"; then+ echo "WARNING: unable to inspect qualification container ${container_id}; manual cleanup may be required" >&2+ return+ fi+ if [[ "${observed_nonce}" != "${CONTAINER_RUN_NONCE}" ]]; then+ echo "WARNING: refusing to remove qualification container ${container_id} after ownership label mismatch" >&2+ return+ fi+ if ! docker rm -f "${container_id}" >/dev/null 2>&1; then+ echo "WARNING: failed to remove qualification container ${container_id}; manual cleanup is required" >&2+ fi+}++cleanup() {+ local container_id+ local discovered+ local discovered_ids=""+ if ! discovered_ids="$(docker ps -aq --no-trunc --filter "label=${CONTAINER_RUN_LABEL}=${CONTAINER_RUN_NONCE}" 2>/dev/null)"; then+ echo "WARNING: unable to discover qualification containers for final cleanup" >&2+ fi+ for container_id in "${CONTAINER_IDS[@]}"; do+ remove_qualification_container_best_effort "${container_id}"+ done+ while IFS= read -r discovered; do+ [[ -n "${discovered}" ]] || continue+ if [[ " ${CONTAINER_IDS[*]} " != *" ${discovered} "* ]]; then+ remove_qualification_container_best_effort "${discovered}"+ fi+ done <<<"${discovered_ids}"+ if [[ "${PACKET_DIR}" == /tmp/pulse-rootless-packet.* && -d "${PACKET_DIR}" ]]; then+ find "${PACKET_DIR}" -type f -exec chmod u+w {} + 2>/dev/null || true+ rm -rf -- "${PACKET_DIR}"+ fi+}+trap cleanup EXIT INT TERM++sha256_files() {+ if command -v sha256sum >/dev/null 2>&1; then+ sha256sum "$@"+ else+ shasum -a 256 "$@"+ fi+}++mkdir "${OUTPUT_DIR}"+chmod 0700 "${OUTPUT_DIR}"++openssl genpkey -algorithm ED25519 -out "${PACKET_DIR}/update-private.pem"+chmod 0600 "${PACKET_DIR}/update-private.pem"+openssl pkey -in "${PACKET_DIR}/update-private.pem" -pubout -outform DER -out "${PACKET_DIR}/update-public.der"+chmod 0600 "${PACKET_DIR}/update-public.der"+update_public_key="$(python3 -I - "${PACKET_DIR}/update-public.der" <<'PY'+import base64+import pathlib+import sys++# Ed25519 SubjectPublicKeyInfo is an exact 12-byte algorithm/bit-string prefix+# followed by the raw 32-byte public key required by the release ldflags.+spki = pathlib.Path(sys.argv[1]).read_bytes()+prefix = bytes.fromhex("302a300506032b6570032100")+if len(spki) != len(prefix) + 32 or not spki.startswith(prefix):+ raise SystemExit("unexpected Ed25519 SubjectPublicKeyInfo encoding")+print(base64.b64encode(spki[len(prefix):]).decode("ascii"), end="")+PY+)"+qualification_version="rootless-v1.${SOURCE_COMMIT:0:12}"+agent_ldflags="$(cd "${REPO_ROOT}" && ./scripts/release_ldflags.sh agent --version "${qualification_version}" --update-public-keys "${update_public_key}")"+helper_ldflags="$(cd "${REPO_ROOT}" && ./scripts/release_ldflags.sh agent --version "${qualification_version}" --update-public-keys "${update_public_key}")"++(+ cd "${REPO_ROOT}"+ CGO_ENABLED=0 GOOS=linux GOARCH="$(go env GOARCH)" GOFLAGS= GOWORK=off go build -trimpath -ldflags "${agent_ldflags}" -o "${PACKET_DIR}/pulse-agent" ./cmd/pulse-agent+ CGO_ENABLED=0 GOOS=linux GOARCH="$(go env GOARCH)" GOFLAGS= GOWORK=off go build -trimpath -ldflags "${helper_ldflags}" -o "${PACKET_DIR}/pulse-agent-helper" ./cmd/pulse-agent-helper+ CGO_ENABLED=0 GOOS=linux GOARCH="$(go env GOARCH)" GOFLAGS= GOWORK=off go test -c -trimpath -o "${PACKET_DIR}/dockeragent.test" ./scripts/installtests+)+openssl pkeyutl -sign -rawin -inkey "${PACKET_DIR}/update-private.pem" -in "${PACKET_DIR}/pulse-agent" | openssl base64 -A >"${PACKET_DIR}/pulse-agent.sig"+printf '\n' >>"${PACKET_DIR}/pulse-agent.sig"+rm -f "${PACKET_DIR}/update-private.pem" "${PACKET_DIR}/update-public.der"+unset update_public_key agent_ldflags helper_ldflags+install -m 0700 "${REPO_ROOT}/scripts/install.sh" "${PACKET_DIR}/install.sh"++python3 -I - "${REPO_ROOT}" "${PACKET_DIR}/source-hashes.json" <<'PY'+import importlib.util+import json+import pathlib+import sys++checkout = pathlib.Path(sys.argv[1]).resolve(strict=True)+destination = pathlib.Path(sys.argv[2])+validator_path = checkout / "scripts/release_control/secure_runtime_rootless_attestation_v1.py"+spec = importlib.util.spec_from_file_location("rootless_validator", validator_path)+if spec is None or spec.loader is None:+ raise SystemExit("unable to load rootless receipt validator")+module = importlib.util.module_from_spec(spec)+spec.loader.exec_module(module)+_, hashes = module.load_source_manifest(checkout, checkout / module.SOURCE_MANIFEST_PATH)+destination.write_text(json.dumps(hashes, sort_keys=True, separators=(",", ":")) + "\n")+PY+chmod 0600 "${PACKET_DIR}/source-hashes.json"++cat >"${PACKET_DIR}/Dockerfile" <<EOF+FROM ${UBUNTU_IMAGE}+ENV container=docker DEBIAN_FRONTEND=noninteractive+RUN apt-get update && apt-get install -y --no-install-recommends \+ bash busybox-static ca-certificates curl dbus-user-session gnupg iproute2 jq kmod \+ libpam-systemd openssl passwd procps slirp4netns software-properties-common \+ systemd systemd-sysv uidmap fuse-overlayfs podman && \+ install -d -m 0755 /etc/apt/keyrings && \+ curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc && \+ chmod 0644 /etc/apt/keyrings/docker.asc && \+ printf 'deb [arch=%s signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu noble stable\n' "\$(dpkg --print-architecture)" >/etc/apt/sources.list.d/docker.list && \+ apt-get update && apt-get install -y --no-install-recommends docker-ce docker-ce-cli docker-ce-rootless-extras containerd.io && \+ apt-get clean && rm -rf /var/lib/apt/lists/* && \+ ln -sf /dev/null /etc/systemd/system/docker.service && \+ ln -sf /dev/null /etc/systemd/system/docker.socket && \+ ln -sf /dev/null /etc/systemd/system/podman.service && \+ ln -sf /dev/null /etc/systemd/system/podman.socket && \+ printf '%s\n' disposable-v1 >/etc/pulse-secure-runtime-rootless-qualification && \+ rm -f /etc/machine-id && touch /etc/machine-id && \+ systemctl set-default multi-user.target+STOPSIGNAL SIGRTMIN+3+CMD ["/sbin/init"]+EOF++docker build --pull --no-cache --network default -t "${IMAGE_TAG}" -f "${PACKET_DIR}/Dockerfile" "${PACKET_DIR}" | tee "${OUTPUT_DIR}/image-build.log"+docker image inspect "${IMAGE_TAG}" >"${OUTPUT_DIR}/qualification-image-inspect.json"++run_runtime() {+ local runtime_name="$1"+ local container_name="pulse-rootless-qual-${runtime_name}-${SOURCE_COMMIT:0:8}-$$"+ local container_id+ local local_receipt="${OUTPUT_DIR}/${runtime_name}-receipt.json"++ container_id="$(docker create --name "${container_name}" --hostname "pulse-rootless-${runtime_name}" \+ --label "${CONTAINER_RUN_LABEL}=${CONTAINER_RUN_NONCE}" \+ --privileged --network none --cgroupns=host \+ --tmpfs /run:rw,nosuid,nodev,mode=755 --tmpfs /run/lock:rw,nosuid,nodev,mode=755 \+ -v /sys/fs/cgroup:/sys/fs/cgroup:rw "${IMAGE_TAG}")"+ CONTAINER_IDS+=("${container_id}")+ docker cp "${PACKET_DIR}/." "${container_id}:/opt/pulse/packet"+ docker start "${container_id}" >/dev/null++ local deadline=$((SECONDS + 60))+ until docker exec "${container_id}" systemctl is-system-running --wait >/dev/null 2>&1; do+ if (( SECONDS >= deadline )); then+ docker logs "${container_id}" >"${OUTPUT_DIR}/${runtime_name}-container.log" 2>&1 || true+ echo "ERROR: ${runtime_name} disposable systemd container did not become ready" >&2+ return 1+ fi+ sleep 1+ done+ if docker exec "${container_id}" sh -c 'ip route | grep -q "^default "'; then+ echo "ERROR: ${runtime_name} qualification container unexpectedly has an external default route" >&2+ return 1+ fi+ if docker inspect "${container_id}" --format '{{range .Mounts}}{{println .Source "->" .Destination}}{{end}}' | grep -E '/(var/)?run/(docker|podman)(\.sock)?'; then+ echo "ERROR: host runtime socket was mounted into ${runtime_name} qualification container" >&2+ return 1+ fi++ docker exec \+ -e PULSE_SECURE_RUNTIME_ROOTLESS_QUALIFICATION=disposable-v1 \+ -e "PULSE_ROOTLESS_RUNTIME=${runtime_name}" \+ -e PULSE_ROOTLESS_RECEIPT=/run/rootless-receipt.json \+ -e PULSE_ROOTLESS_SOURCE_HASHES=/opt/pulse/packet/source-hashes.json \+ -e "PULSE_ROOTLESS_SOURCE_COMMIT=${SOURCE_COMMIT}" \+ -e PULSE_SECURE_RUNTIME_COLLECTOR=/opt/pulse/packet/pulse-agent \+ -e PULSE_SECURE_RUNTIME_COLLECTOR_SIGNATURE=/opt/pulse/packet/pulse-agent.sig \+ -e PULSE_SECURE_RUNTIME_HELPER=/opt/pulse/packet/pulse-agent-helper \+ -e PULSE_SECURE_RUNTIME_INSTALLER=/opt/pulse/packet/install.sh \+ "${container_id}" /opt/pulse/packet/dockeragent.test \+ -test.run '^TestSecureRuntimeRootlessQualification$' -test.count=1 -test.v -test.timeout=45m \+ | tee "${OUTPUT_DIR}/${runtime_name}-test.log"++ docker cp "${container_id}:/run/rootless-receipt.json" "${local_receipt}"+ docker logs "${container_id}" >"${OUTPUT_DIR}/${runtime_name}-container.log" 2>&1 || true+ chmod 0600 "${local_receipt}" "${OUTPUT_DIR}/${runtime_name}-test.log" "${OUTPUT_DIR}/${runtime_name}-container.log"+ remove_qualification_container_strict "${container_id}"+}++run_runtime docker+run_runtime podman++python3 -I - "${OUTPUT_DIR}/docker-receipt.json" "${OUTPUT_DIR}/podman-receipt.json" "${OUTPUT_DIR}/receipt.json" <<'PY'+import json+import pathlib+import sys++docker_path, podman_path, output_path = map(pathlib.Path, sys.argv[1:])+docker = json.loads(docker_path.read_text())+podman = json.loads(podman_path.read_text())+if docker.get("result") != "passed" or podman.get("result") != "passed":+ raise SystemExit("per-runtime qualification result != \"passed\"")+for field in ("schema_version", "kind", "source_commit", "source_hashes", "artifacts"):+ if docker.get(field) != podman.get(field):+ raise SystemExit(f"per-runtime qualification field differs: {field}")+if [run.get("runtime", {}).get("runtime") for run in docker.get("runs", []) + podman.get("runs", [])] != ["docker", "podman"]:+ raise SystemExit("per-runtime receipts are not exact Docker then Podman runs")+combined = {+ "schema_version": docker["schema_version"],+ "kind": docker["kind"],+ "result": "passed",+ "source_commit": docker["source_commit"],+ "started_at": min(docker["started_at"], podman["started_at"]),+ "completed_at": max(docker["completed_at"], podman["completed_at"]),+ "source_hashes": docker["source_hashes"],+ "artifacts": docker["artifacts"],+ "runs": docker["runs"] + podman["runs"],+}+output_path.write_text(json.dumps(combined, indent=2, sort_keys=True) + "\n")+PY+chmod 0600 "${OUTPUT_DIR}/receipt.json"++python3 -I "${REPO_ROOT}/scripts/release_control/secure_runtime_rootless_attestation_v1.py" \+ "${OUTPUT_DIR}/receipt.json" \+ --qualification-test "${PACKET_DIR}/dockeragent.test" \+ --collector "${PACKET_DIR}/pulse-agent" \+ --helper "${PACKET_DIR}/pulse-agent-helper" \+ --installer "${PACKET_DIR}/install.sh" \+ >"${OUTPUT_DIR}/attestation.json"+chmod 0600 "${OUTPUT_DIR}/attestation.json"++sha256_files "${OUTPUT_DIR}/receipt.json" "${OUTPUT_DIR}/attestation.json" >"${OUTPUT_DIR}/sha256.txt"+chmod 0600 "${OUTPUT_DIR}/sha256.txt"+echo "Rootless qualification passed: ${OUTPUT_DIR}"