Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Keep integration safety fixtures aligned with reviewed source

pulse-triage[bot]ce1a28f64d94
diff --git a/scripts/installtests/agent_systemd_teardown.py b/scripts/installtests/agent_systemd_teardown.py
index 8e0c80a8c0..01272af2f5 100644
--- a/scripts/installtests/agent_systemd_teardown.py
+++ b/scripts/installtests/agent_systemd_teardown.py
@@ -9,10 +9,13 @@ controls establish refusal and ordering, not native systemd or installed use.
import os
from pathlib import Path
import shlex
+import shutil
+import signal
import subprocess
import tempfile
import time
import unittest
+from unittest import mock
ROOT = Path(__file__).resolve().parents[2]
SOURCE = Path(os.environ.get("PULSE_AGENT_TEARDOWN_SOURCE", ROOT / "scripts/install.sh"))
@@ -23,6 +26,17 @@ def function(source, name):
return marker + source.split(marker, 1)[1].split("\n}\n", 1)[0] + "\n}\n"
+def bounded_read_environment(root, child_id):
+ # macOS CI prepares GNU timeout outside /usr/bin and /bin. Keep the
+ # private systemctl double first without discarding that real prerequisite
+ # or replacing it with a simulated timeout. Missing preparation is a fail.
+ timeout = shutil.which("timeout")
+ if timeout is None:
+ raise RuntimeError("GNU timeout missing from the prepared test PATH")
+ (root / "timeout").symlink_to(Path(timeout).resolve())
+ return dict(os.environ, PATH=str(root) + ":/usr/bin:/bin", CHILD_ID=str(child_id))
+
+
DOUBLE = r'''
set -euo pipefail
EXIT_GENERAL=1 AGENT_NAME=pulse-agent
@@ -244,17 +258,49 @@ class AgentSystemdTeardown(unittest.TestCase):
child_id = root / "child-id"
executable.write_text("#!/bin/bash\nprintf '%s\\n' \"$$\" > \"$CHILD_ID\"\nexec sleep 60\n")
executable.chmod(0o700)
- env = dict(os.environ, PATH=str(root) + ":/usr/bin:/bin", CHILD_ID=str(child_id))
+ env = bounded_read_environment(root, child_id)
started = time.monotonic()
- result = subprocess.run(["bash", "-c", function(self.source, "read_agent_removal_unit_state") +
- "\nread_agent_removal_unit_state pulse-agent.service\n"],
- env=env, capture_output=True, text=True, timeout=8)
- self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)
- self.assertLess(time.monotonic() - started, 7)
- self.assertEqual(result.stdout, "")
- self.assertTrue(child_id.exists(), "the bounded read never started")
- with self.assertRaises(ProcessLookupError):
- os.kill(int(child_id.read_text()), 0)
+ try:
+ result = subprocess.run(["bash", "-c", function(self.source, "read_agent_removal_unit_state") +
+ "\nread_agent_removal_unit_state pulse-agent.service\n"],
+ env=env, capture_output=True, text=True, timeout=8)
+ self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertLess(time.monotonic() - started, 7)
+ self.assertEqual(result.stdout, "")
+ self.assertTrue(child_id.exists(), "the bounded read never started")
+ with self.assertRaises(ProcessLookupError):
+ os.kill(int(child_id.read_text()), 0)
+ finally:
+ # An adverse result must fail above, not leave our own hanging
+ # fixture behind. This does not turn failed cleanup into a pass.
+ if child_id.exists():
+ try:
+ os.kill(int(child_id.read_text()), signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+
+ def test_timeout_probe_keeps_prepared_tool_and_refuses_missing_preparation(self):
+ timeout = shutil.which("timeout")
+ self.assertIsNotNone(timeout, "native CI must supply GNU timeout")
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ prepared = root / "prepared"
+ prepared.mkdir()
+ (prepared / "timeout").symlink_to(Path(timeout).resolve())
+ probe = root / "probe"
+ probe.mkdir()
+ # A tool prepared in an otherwise empty, non-system PATH must be
+ # carried into the isolated probe. Never fall back to a host unit.
+ with mock.patch.dict(os.environ, PATH=str(prepared)):
+ env = bounded_read_environment(probe, probe / "child-id")
+ self.assertEqual((probe / "timeout").resolve(), Path(timeout).resolve())
+ version = subprocess.run([str(probe / "timeout"), "--version"], env=env,
+ capture_output=True, text=True, timeout=3)
+ self.assertEqual(version.returncode, 0, version.stdout + version.stderr)
+ self.assertIn("GNU coreutils", version.stdout)
+ with mock.patch.dict(os.environ, PATH=str(root / "absent")):
+ with self.assertRaisesRegex(RuntimeError, "missing from the prepared test PATH"):
+ bounded_read_environment(root, root / "child-id")
if __name__ == "__main__":
diff --git a/scripts/installtests/helm_openshift_docs_contract_test.go b/scripts/installtests/helm_openshift_docs_contract_test.go
index 7d24eaf717..2e42ba4cc9 100644
--- a/scripts/installtests/helm_openshift_docs_contract_test.go
+++ b/scripts/installtests/helm_openshift_docs_contract_test.go
@@ -42,8 +42,33 @@ func openShiftDocsIssues(docs string) []string {
require(commands[1][1], "--set openShift.kubernetesAgent.clusterID=")
require(commands[1][1], "--set agent.secretEnv.name=pulse-agent-env")
require(commands[1][1], "--set 'agent.secretEnv.keys[0]=PULSE_TOKEN'")
- require(docs, "create secret generic pulse-agent-env")
- require(docs, `--from-file=PULSE_TOKEN="$HOME/.config/pulse/kubernetes-agent-token"`)
+ // The guide now validates the owner/private-file path before either
+ // provisioning pipeline. Bind the input to that same command block, not a
+ // literal HOME path or a precaution elsewhere in the document.
+ var secretCommands []string
+ for _, command := range regexp.MustCompile("(?s)```bash\n(.*?)```").FindAllStringSubmatch(docs, -1) {
+ if strings.Contains(command[1], "create secret generic pulse-agent-env") {
+ secretCommands = append(secretCommands, command[1])
+ }
+ }
+ if len(secretCommands) != 1 {
+ issues = append(issues, "need one validated private-file Secret creation block")
+ } else {
+ for _, value := range []string{
+ `set -euo pipefail`,
+ `config_dir="$HOME/.config/pulse"`,
+ `token_file="$config_dir/kubernetes-agent-token"`,
+ `[ -L "$token_file" ]`,
+ `[ ! -f "$token_file" ]`,
+ `[ ! -O "$token_file" ]`,
+ `[ ! -r "$token_file" ]`,
+ `[ ! -s "$token_file" ]`,
+ `chmod 600 "$token_file"`,
+ `--from-file=PULSE_TOKEN="$token_file"`,
+ } {
+ require(secretCommands[0], value)
+ }
+ }
// Inspect shell blocks only: prose warns against these unsafe arguments.
unsafe := regexp.MustCompile(`--from-literal=(?:PULSE_TOKEN|API_TOKENS?)=|--set(?:-string)?\s+(?:agent|server)\.secretEnv\.data\.`)
for _, command := range regexp.MustCompile("(?s)```bash\n(.*?)```").FindAllStringSubmatch(docs, -1) {
@@ -73,7 +98,16 @@ func TestOpenShiftDocsKeepBootstrapAndPrivateSecret(t *testing.T) {
{"secret creation", "create secret generic pulse-agent-env", "create secret generic wrong-agent-env"},
{"secret reference", "agent.secretEnv.name=pulse-agent-env", "agent.secretEnv.name=wrong-agent-env"},
{"secret key", "agent.secretEnv.keys[0]=PULSE_TOKEN", "agent.secretEnv.keys[0]=WRONG_TOKEN"},
- {"private-file input", `--from-file=PULSE_TOKEN="$HOME/.config/pulse/kubernetes-agent-token"`, "--from-literal=PULSE_TOKEN=synthetic-not-a-secret"},
+ {"private-file input", `--from-file=PULSE_TOKEN="$token_file"`, "--from-literal=PULSE_TOKEN=synthetic-not-a-secret"},
+ {"private directory", `config_dir="$HOME/.config/pulse"`, `config_dir="/tmp/shared"`},
+ {"bound private file", `token_file="$config_dir/kubernetes-agent-token"`, `token_file="/tmp/shared-token"`},
+ {"linked token", `[ -L "$token_file" ]`, `[ -L "$unrelated" ]`},
+ {"regular token", `[ ! -f "$token_file" ]`, `[ ! -f "$unrelated" ]`},
+ {"owned token", `[ ! -O "$token_file" ]`, `[ ! -O "$unrelated" ]`},
+ {"readable token", `[ ! -r "$token_file" ]`, `[ ! -r "$unrelated" ]`},
+ {"empty token", `[ ! -s "$token_file" ]`, `[ ! -s "$unrelated" ]`},
+ {"private mode", `chmod 600 "$token_file"`, `chmod 644 "$token_file"`},
+ {"pipeline failure", `set -euo pipefail`, `set -eu`},
{"Helm token value", "--set agent.secretEnv.name=pulse-agent-env", "--set-string agent.secretEnv.data.PULSE_TOKEN=synthetic-not-a-secret"},
} {
t.Run(change.name, func(t *testing.T) {
diff --git a/scripts/installtests/install_sh_test.go b/scripts/installtests/install_sh_test.go
index 9b49b16c56..1539f7e75e 100644
--- a/scripts/installtests/install_sh_test.go
+++ b/scripts/installtests/install_sh_test.go
@@ -8353,12 +8353,13 @@ func TestInstallSHSystemdTeardownRequiresObservedQuiescence(t *testing.T) {
"test_failed_revocation_retains_stopped_runner_recovery_material",
"test_full_batch_reconciles_earlier_activation_sources",
"test_real_read_timeout_stops_its_owned_child",
+ "test_timeout_probe_keeps_prepared_tool_and_refuses_missing_preparation",
} {
if !strings.Contains(string(output), name+" (__main__.AgentSystemdTeardown."+name+") ... ok") {
t.Fatalf("systemd teardown control %s did not pass:\n%s", name, output)
}
}
- if !strings.Contains(string(output), "\nRan 7 tests in ") || !strings.Contains(string(output), "\nOK\n") {
+ if !strings.Contains(string(output), "\nRan 8 tests in ") || !strings.Contains(string(output), "\nOK\n") {
t.Fatalf("incomplete systemd teardown verdict:\n%s", output)
}
entry, err := os.ReadFile(repoFile("scripts", "install.sh"))
diff --git a/scripts/installtests/native_helper_workflow_test.go b/scripts/installtests/native_helper_workflow_test.go
index 154b6874f5..9ca02ab58d 100644
--- a/scripts/installtests/native_helper_workflow_test.go
+++ b/scripts/installtests/native_helper_workflow_test.go
@@ -120,7 +120,11 @@ func TestNativeHelperWorkflowCoversChangedSourceAndLinuxBoundaries(t *testing.T)
for _, scenario := range []struct{ name, old, new string }{
{"missing x64", "runner: ubuntu-24.04\n", "runner: macos-15\n"},
{"missing arm64", "runner: ubuntu-24.04-arm\n", "runner: macos-15\n"},
- {"not both Linux jobs", "if: runner.os == 'Linux'", "if: matrix.runner == 'ubuntu-24.04'"},
+ // Scope the mutation to the owned helper step. The workflow also has
+ // earlier Linux-only removal checks, which are not this validator's
+ // subject and must not accidentally absorb the negative control.
+ {"not both Linux jobs", "name: Test native Linux helper boundaries\n if: runner.os == 'Linux'", "name: Test native Linux helper boundaries\n if: matrix.runner == 'ubuntu-24.04'"},
+ {"not both Linux build jobs", "name: Build native Linux helper\n if: runner.os == 'Linux'", "name: Build native Linux helper\n if: matrix.runner == 'ubuntu-24.04'"},
{"tolerated helper failure", "name: Test native Linux helper boundaries", "name: Test native Linux helper boundaries\n continue-on-error: true"},
{"missing helper command tests", " ./cmd/pulse-agent-helper\n", ""},
{"missing protocol tests", " ./internal/agenthelper\n", ""},
diff --git a/scripts/release_control/release_promotion_policy_test.py b/scripts/release_control/release_promotion_policy_test.py
index ba474e14f7..98ee5dcc49 100644
--- a/scripts/release_control/release_promotion_policy_test.py
+++ b/scripts/release_control/release_promotion_policy_test.py
@@ -45,6 +45,29 @@ def normalize_ws(text: str) -> str:
return " ".join(text.split())
+def expandable_intake_context(form: dict, field_id: str, heading: str) -> str:
+ """Read the conditional guidance at its report field, not arbitrary prose.
+
+ The forms keep optional context in expandable Markdown immediately before
+ the relevant textarea. A matching sentence elsewhere must not conceal a
+ removed, misplaced or malformed section.
+ """
+ fields = [index for index, field in enumerate(form["body"]) if field.get("id") == field_id]
+ if len(fields) != 1 or fields[0] == 0:
+ raise ValueError("missing or repeated report field")
+ block = form["body"][fields[0] - 1]
+ if block.get("type") != "markdown":
+ raise ValueError("conditional context must precede its report field as Markdown")
+ text = block.get("attributes", {}).get("value", "")
+ sections = re.findall(r"<details>\s*<summary>([^<]+)</summary>(.*?)</details>", text, re.DOTALL)
+ if text.count("<details>") != len(sections) or text.count("</details>") != len(sections):
+ raise ValueError("malformed conditional context")
+ matches = [context for title, context in sections if title == heading]
+ if len(matches) != 1:
+ raise ValueError("missing, malformed or repeated conditional context")
+ return normalize_ws(matches[0])
+
+
def release_notes_have_exact_title(notes: str, version: str) -> bool:
"""Match the first title, as the reader-facing Go notes contract does.
@@ -1925,11 +1948,12 @@ class ReleasePromotionPolicyTest(unittest.TestCase):
self.assertEqual(evidence["type"], "textarea")
self.assertFalse(evidence.get("validations", {}).get("required", False))
self.assertNotIn("render", evidence["attributes"])
- # Keep the distinctions at the optional attachment point, not
- # hidden in an introduction, link or new required field.
- description = evidence["attributes"]["description"]
- context = normalize_ws(description.split("For notification reports,", 1)[1]
- .split("For CPU, memory or disk-write reports", 1)[0])
+ # Keep every distinction at the optional attachment point. The
+ # accepted form expands it there instead of overloading the
+ # field's short description or adding a required questionnaire.
+ context = expandable_intake_context(
+ form, evidence_id, "Notification delivery: Test versus ordinary alerts",
+ )
for distinction in (
"already-observed **Test** result", "ordinary alert delivery",
"single, grouped/digest or resolved", "destination type",
@@ -1945,6 +1969,40 @@ class ReleasePromotionPolicyTest(unittest.TestCase):
self.assertIn(distinction, context)
self.assertTrue(fields["pulse_version"]["validations"]["required"])
+ def test_expandable_intake_context_cannot_be_hidden_or_detached(self) -> None:
+ for name, summary_id, evidence_id in (
+ ("bug_report.yml", "bug_description", "logs"),
+ ("v6_rc_feedback.yml", "summary", "evidence"),
+ ):
+ for field_id, heading in (
+ (summary_id, "Several hosts or clusters: preserve which names and IDs repeat"),
+ (evidence_id, "Notification delivery: Test versus ordinary alerts"),
+ ):
+ with self.subTest(form=name, field=field_id):
+ form = yaml.load(read(f".github/ISSUE_TEMPLATE/{name}"), Loader=UniqueKeyLoader)
+ context = expandable_intake_context(form, field_id, heading)
+ self.assertTrue(context)
+ index = next(i for i, field in enumerate(form["body"]) if field.get("id") == field_id)
+ original = form["body"][index - 1]
+ value = original["attributes"]["value"]
+ for change in (
+ {"type": "textarea", "attributes": {"description": value}},
+ {"type": "markdown", "attributes": {"value": value.replace("<details>", "", 1)}},
+ {"type": "markdown", "attributes": {"value": value.replace("</details>", "", 1)}},
+ {"type": "markdown", "attributes": {"value": value.replace(heading, "Other context", 1)}},
+ {"type": "markdown", "attributes": {"value": value + "\n" + value}},
+ {"type": "markdown", "attributes": {"value": "See the introduction."}},
+ ):
+ # Keep the original elsewhere: a whole-form substring
+ # search would wrongly accept this detached context.
+ form["body"][index - 1] = change
+ form["body"].append(original)
+ with self.assertRaises(ValueError):
+ expandable_intake_context(form, field_id, heading)
+ form["body"].pop()
+ form["body"][index - 1] = original
+ self.assertEqual(expandable_intake_context(form, field_id, heading), context)
+
def test_notification_triage_separates_evaluation_delivery_and_identity(self) -> None:
documents = ("docs/ISSUE_TRIAGE.md", "frontend-modern/public/docs/ISSUE_TRIAGE.md")
self.assertEqual(read(documents[0]), read(documents[1]))
@@ -2026,7 +2084,9 @@ class ReleasePromotionPolicyTest(unittest.TestCase):
self.assertEqual(summary["type"], "textarea")
self.assertTrue(summary["validations"]["required"])
self.assertNotIn("render", summary["attributes"])
- prose = normalize_ws(summary["attributes"]["description"])
+ prose = expandable_intake_context(
+ form, summary_id, "Several hosts or clusters: preserve which names and IDs repeat",
+ )
for distinction in (
"For reports involving several hosts or clusters",
"which nodes share a cluster", "independent installations",
diff --git a/scripts/tests/test_telemetry_adoption_report.py b/scripts/tests/test_telemetry_adoption_report.py
index e42cad53d7..589b6e2181 100644
--- a/scripts/tests/test_telemetry_adoption_report.py
+++ b/scripts/tests/test_telemetry_adoption_report.py
@@ -887,13 +887,40 @@ class TelemetryAdoptionReportTest(unittest.TestCase):
REPO_ROOT / "frontend-modern/public/docs/SECURITY.md",
)
+ self.assertEqual(security_docs[0].read_bytes(), security_docs[1].read_bytes())
+
+ def check(content):
+ self.assertIn("Settings → Infrastructure → Install on a host", content)
+ self.assertNotIn("Settings → Agents → Installation commands", content)
+ self.assertNotIn("Settings -> Agents -> Installation commands", content)
+ # The current guide uses the safe host-install surface and
+ # instance-served manual route, not the old alternate page label.
+ # Retain each safety distinction in that actual migration section.
+ migration = " ".join(content.split("Preferred option (no SSH keys, no proxy wiring):", 1)[1]
+ .split("Legacy sensor proxy (removed):", 1)[0].split())
+ for boundary in (
+ "separately revealed credential out of the copied command",
+ "silent prompt on that host", "private token-file route",
+ "agent installer served by your Pulse instance",
+ "verified HTTPS address", "`--token-file` and `--enable-proxmox`",
+ "installs the server, not the agent",
+ "Do not pipe an unchecked HTTP response into a privileged shell",
+ "or disable certificate verification",
+ ):
+ self.assertIn(boundary, migration)
+
for path in security_docs:
with self.subTest(path=path.relative_to(REPO_ROOT)):
content = path.read_text(encoding="utf-8")
- self.assertIn("Settings → Infrastructure → Install on a host", content)
- self.assertIn("Proxmox or Machines page", content)
- self.assertNotIn("Settings → Agents → Installation commands", content)
- self.assertNotIn("Settings -> Agents -> Installation commands", content)
+ check(content)
+ for boundary in ("Settings → Infrastructure → Install on a host",
+ "agent installer served by your", "verified HTTPS address",
+ "`--token-file`", "separately", "Do not pipe an unchecked HTTP response"):
+ with self.subTest(removed=boundary):
+ changed = content.replace(boundary, "removed safety boundary")
+ self.assertNotEqual(changed, content)
+ with self.assertRaises(AssertionError):
+ check(changed)
def test_summarize_rows_uses_latest_install_state_and_splits_release_validation(self) -> None:
now = datetime.now(timezone.utc).replace(microsecond=0)