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.

Restore documentation fixtures for private API and PBS recipes

pulse-triage[bot]5082c60d27d4
diff --git a/scripts/tests/test_agent_docs.py b/scripts/tests/test_agent_docs.py
index 08d402e28e..1aff2a541a 100644
--- a/scripts/tests/test_agent_docs.py
+++ b/scripts/tests/test_agent_docs.py
@@ -66,7 +66,9 @@ class AgentDocsTest(unittest.TestCase):
shell = "\n".join(blocks(name))
self.assertNotRegex(shell, r"--token(?:\s|=)|PULSE_TOKEN=|curl[^\n]*http://")
self.assertNotRegex(shell, r"curl[^`]*\|\s*(?:sudo\s+)?bash")
- self.assertIn("Stop if the download fails", doc.decode())
+ boundary = ("Stop if the download fails" if name == "UNIFIED_AGENT.md"
+ else "Stop if preparation or download fails")
+ self.assertIn(boundary, doc.decode())
windows = "\n".join(blocks(NAMES[0], "powershell"))
self.assertNotRegex(windows, r"(?i)\biex\b|\birm\b|Invoke-Expression|http://|\$env:PULSE_TOKEN\s*=")
@@ -134,7 +136,10 @@ class AgentDocsTest(unittest.TestCase):
command = command.replace("https://pulse.example.com", f"https://{hostname}:{port}")
command = command.replace("https://raw.githubusercontent.com", f"https://{hostname}:{port}")
if ca is not None:
- command = command.replace("curl ", f'curl --cacert "{ca}" ', 1)
+ if "curl --disable " in command:
+ command = command.replace("curl --disable ", f'curl --disable --cacert "{ca}" ', 1)
+ else:
+ command = command.replace("curl ", f'curl --cacert "{ca}" ', 1)
result = subprocess.run(["bash", "-eu", "-c", command], env=env, capture_output=True, timeout=20)
argv = json.loads((home / "curl-argv.json").read_text())
self.assertNotIn(TOKEN, " ".join(argv))
@@ -143,12 +148,14 @@ class AgentDocsTest(unittest.TestCase):
self.assertIn(argument, argv)
self.assertNotIn("--insecure", argv)
self.assertNotIn("-k", argv)
+ if "sensor-cleanup-download.XXXXXX" in command:
+ self.assertEqual(argv[0], "--disable")
return result
def test_downloads_require_verified_tls_and_success(self):
for name, path, needle, output in (
(NAMES[0], "/install.sh", '--output "$HOME/.config/pulse/agent-install.sh"', "agent-install.sh"),
- (NAMES[1], CLEANUP_PATH, '--output "$HOME/.config/pulse/sensor-proxy-uninstall.sh"', "sensor-proxy-uninstall.sh"),
+ (NAMES[1], CLEANUP_PATH, 'helper_file="$config_dir/sensor-proxy-uninstall.sh"', "sensor-proxy-uninstall.sh"),
):
for status, ca, hostname, expected in (
(200, self.cert, "localhost", 0),
diff --git a/scripts/tests/test_api_auth_docs.py b/scripts/tests/test_api_auth_docs.py
index 6ec083d45d..5ebda96876 100644
--- a/scripts/tests/test_api_auth_docs.py
+++ b/scripts/tests/test_api_auth_docs.py
@@ -24,6 +24,9 @@ import unittest
ROOT = Path(__file__).resolve().parents[2]
DOC = ROOT / "docs/API.md"
TEST_TOKEN = "synthetic-doc-test-token"
+PRIVATE_RESPONSE = json.dumps({
+ "fixture": True, "token": TEST_TOKEN, "resource": "private-fixture-resource",
+}).encode() + b"\n"
def auth_section() -> str:
@@ -32,17 +35,26 @@ def auth_section() -> str:
def commands() -> tuple[str, str]:
blocks = re.findall(r"```bash\n(.*?)```", auth_section(), re.DOTALL)
- preparation = next(block for block in blocks if "umask 077" in block)
- request = next(block for block in blocks if block.startswith("curl "))
- return preparation, request
+ preparation = next(block for block in blocks if 'vi "$auth_file"' in block)
+ return preparation, recipe("/api/state/summary")
+
+
+def request_helper() -> str:
+ matches = [block for block in re.findall(r"```bash\n(.*?)```", auth_section(), re.DOTALL)
+ if block.startswith("pulse_api() (")]
+ if len(matches) != 1:
+ raise AssertionError("expected one private-response helper")
+ return matches[0]
def recipe(path: str) -> str:
matches = [block for block in re.findall(r"```bash\n(.*?)```", DOC.read_text(), re.DOTALL)
- if path in block]
+ if block.startswith("pulse_api ") and path in block]
if len(matches) != 1:
raise AssertionError(f"expected one executable recipe for {path}")
- return matches[0]
+ # A copied call is meaningful only after defining the actual guide helper
+ # in that shell, not a second, hand-written curl implementation.
+ return request_helper() + "\n" + matches[0]
# Independently expected HTTP operations: extracting the shell from the guide
@@ -67,7 +79,7 @@ FLEET_ACTION_REQUESTS = (
@contextmanager
-def recording_server(status: int = 200):
+def recording_server(status: int = 200, partial: bool = False, response: bytes = b'{"fixture":true}\n'):
requests = []
class Handler(BaseHTTPRequestHandler):
@@ -75,8 +87,12 @@ def recording_server(status: int = 200):
body = self.rfile.read(int(self.headers.get("Content-Length", "0")))
requests.append((self.path, dict(self.headers), self.command, body))
self.send_response(status)
+ if status == 302:
+ self.send_header("Location", "/api/should-not-receive-credentials")
+ if partial:
+ self.send_header("Content-Length", str(len(response) + 100))
self.end_headers()
- self.wfile.write(b'{"fixture":true}\n')
+ self.wfile.write(response)
do_GET = record_request
do_POST = record_request
@@ -98,12 +114,25 @@ def recording_server(status: int = 200):
thread.join(timeout=5)
-def exercise_curl(case: unittest.TestCase, home: Path, header_text: str, port: int, request: str):
+def private_recording_server(status: int = 200, partial: bool = False):
+ return recording_server(status, partial, response=PRIVATE_RESPONSE)
+
+
+def exercise_curl(case: unittest.TestCase, home: Path, header_text: str, port: int, request: str,
+ *, private_response: bool = False):
"""Execute the exact copied recipe; capture argv and hostile curl defaults."""
header = home / ".config/pulse/api-header"
header.parent.mkdir(parents=True, exist_ok=True)
header.write_text(header_text + "\n")
- header.chmod(0o600)
+ header.chmod(0o644 if private_response else 0o600)
+ # Other guides import this fixture for credential transport alone. Keep
+ # that contract separate from API.md's response-file/helper contract.
+ if private_response:
+ retained = header.parent / "api-response.retained"
+ if not retained.exists():
+ retained.write_bytes(b"previous private response\n")
+ retained.chmod(0o600)
+ previous = {file: file.read_bytes() for file in header.parent.glob("api-response.*")}
real_curl = shutil.which("curl")
case.assertIsNotNone(real_curl, "curl is required to exercise the documented command")
tools = home / "tools"
@@ -112,16 +141,17 @@ def exercise_curl(case: unittest.TestCase, home: Path, header_text: str, port: i
recorder.write_text(
"#!/usr/bin/env python3\nimport json, os, sys\n"
"from pathlib import Path\n"
- "Path(os.environ['ARGV_RECEIPT']).write_text(json.dumps(sys.argv[1:]))\n"
+ "with Path(os.environ['ARGV_RECEIPT']).open('a') as f: f.write(json.dumps(sys.argv[1:]) + '\\n')\n"
"os.execv(os.environ['REAL_CURL'], [os.environ['REAL_CURL'], *sys.argv[1:]])\n"
)
recorder.chmod(0o700)
receipt = home / "argv.json"
+ receipt.write_text("")
trace = home / "curl-trace.txt"
# An existing curl configuration must not turn safe argv into a trace
# containing the header file's credential, or inject another header.
(home / ".curlrc").write_text(
- f'header = "X-Curlrc-Injected: yes"\nverbose\ntrace-ascii = "{trace}"\n'
+ f'header = "X-Curlrc-Injected: yes"\nverbose\ninsecure\nlocation\ntrace-ascii = "{trace}"\n'
)
env = dict(os.environ, HOME=str(home), PATH=f"{tools}:{os.environ['PATH']}",
CURL_HOME=str(home), XDG_CONFIG_HOME=str(home / ".config"), TMPDIR=str(home),
@@ -131,12 +161,28 @@ def exercise_curl(case: unittest.TestCase, home: Path, header_text: str, port: i
del env[key]
request = request.replace("http://127.0.0.1:7655", f"http://127.0.0.1:{port}")
result = subprocess.run(["bash", "-eu", "-c", request], env=env, capture_output=True, timeout=10)
- argv = json.loads(receipt.read_text())
+ calls = [json.loads(line) for line in receipt.read_text().splitlines()]
+ case.assertEqual(len(calls), 1, "a copied step must invoke curl once, even on failure")
+ argv = calls[0]
case.assertEqual(argv[0], "--disable", "curl defaults must be disabled by the first option")
case.assertNotIn(TEST_TOKEN, " ".join(argv))
case.assertIn("@" + str(header), argv)
- case.assertNotIn(b"synthetic-doc-test-token", result.stdout + result.stderr)
+ for marker in (TEST_TOKEN, "private-fixture-resource"):
+ case.assertNotIn(marker.encode(), result.stdout + result.stderr, "private response leaked")
case.assertFalse(trace.exists(), "local curl configuration must not create a credential trace")
+ if private_response:
+ for option, value in (("--connect-timeout", "5"), ("--max-time", "20")):
+ case.assertIn(option, argv)
+ case.assertEqual(argv[argv.index(option) + 1], value)
+ responses = set(header.parent.glob("api-response.*")) - previous.keys()
+ case.assertEqual(len(responses), 1, "each request must retain a new response file")
+ response = responses.pop()
+ case.assertIn(str(response).encode(), result.stdout)
+ case.assertEqual(response.read_bytes(), PRIVATE_RESPONSE)
+ for path, mode in ((header.parent, 0o700), (header, 0o600), (response, 0o600)):
+ case.assertEqual(stat.S_IMODE(path.stat().st_mode), mode)
+ for path, content in previous.items():
+ case.assertEqual(path.read_bytes(), content, "an earlier response was overwritten")
return result
@@ -145,7 +191,7 @@ class APIAuthDocsTest(unittest.TestCase):
section = auth_section()
bash = "\n".join(re.findall(r"```bash\n(.*?)```", section, re.DOTALL))
self.assertNotRegex(bash, r"(?:X-API-Token:|Authorization:|Bearer\s)")
- self.assertIn('--header "@$HOME/.config/pulse/api-header"', bash)
+ self.assertIn('--header "@$auth_file"', request_helper())
self.assertIn("HTTPS", section)
self.assertIn("does not verify authentication", section)
self.assertIn("monitoring:read", section)
@@ -155,16 +201,22 @@ class APIAuthDocsTest(unittest.TestCase):
bash = "\n".join(re.findall(r"```bash\n(.*?)```", DOC.read_text(), re.DOTALL))
self.assertNotRegex(bash, r"(?:\b\w*TOKEN=|X-API-Token:|Authorization:|Bearer\s)")
self.assertNotRegex(bash, r"(?:--insecure|--verbose|--trace\S*|--location|\s-k\b)")
- requests = [block for block in re.findall(r"```bash\n(.*?)```", DOC.read_text(), re.DOTALL)
- if block.startswith("curl ")]
+ blocks = re.findall(r"```bash\n(.*?)```", DOC.read_text(), re.DOTALL)
+ requests = [block for block in blocks if block.startswith("pulse_api ")]
self.assertEqual(len(requests), 8)
+ self.assertEqual([block for block in blocks if "curl " in block], [request_helper()],
+ "an example must not bypass the private-response helper")
+ self.assertIn("curl --disable --fail-with-body ", request_helper())
for request in requests:
- self.assertTrue(request.startswith("curl --disable --fail-with-body "))
- self.assertIn('--header "@$HOME/.config/pulse/api-header"', request)
- if "--request POST" in request:
- self.assertIn("--data-binary @-", request)
+ if request.startswith("pulse_api POST "):
+ self.assertIn("--data-binary @-", request_helper())
self.assertIn("<<'JSON'", request)
+ def test_every_documented_shell_recipe_parses(self):
+ for block in re.findall(r"```bash\n(.*?)```", DOC.read_text(), re.DOTALL):
+ with self.subTest(block=block):
+ subprocess.run(["bash", "-n", "-c", block], check=True, capture_output=True)
+
def test_action_guidance_preserves_scope_and_review_boundaries(self):
guide = DOC.read_text()
for scope in ("monitoring:read", "settings:read", "actions:plan", "actions:approve",
@@ -251,10 +303,11 @@ class APIAuthDocsTest(unittest.TestCase):
self.assertFalse((home / "editor-called").exists())
def run_documented_request(self, home: Path, header_text: str, port: int, request=None):
- return exercise_curl(self, home, header_text, port, request if request is not None else commands()[1])
+ return exercise_curl(self, home, header_text, port, request if request is not None else commands()[1],
+ private_response=True)
def test_header_file_sends_each_supported_header_without_exposing_argv(self):
- with tempfile.TemporaryDirectory() as temporary, recording_server() as (port, requests):
+ with tempfile.TemporaryDirectory() as temporary, private_recording_server() as (port, requests):
for key, value in (("X-API-Token", TEST_TOKEN), ("Authorization", "Bearer " + TEST_TOKEN)):
with self.subTest(header=key):
result = self.run_documented_request(Path(temporary), f"{key}: {value}", port)
@@ -264,7 +317,7 @@ class APIAuthDocsTest(unittest.TestCase):
self.assertNotIn("X-Curlrc-Injected", requests[-1][1])
def test_fleet_action_recipes_send_expected_methods_paths_and_json(self):
- with tempfile.TemporaryDirectory() as temporary, recording_server() as (port, requests):
+ with tempfile.TemporaryDirectory() as temporary, private_recording_server() as (port, requests):
for key, value in (("X-API-Token", TEST_TOKEN), ("Authorization", "Bearer " + TEST_TOKEN)):
for method, path, body in FLEET_ACTION_REQUESTS:
with self.subTest(header=key, method=method, path=path):
@@ -287,23 +340,40 @@ class APIAuthDocsTest(unittest.TestCase):
def test_each_fleet_action_recipe_surfaces_auth_errors_without_following_steps(self):
for status in (401, 403):
- with tempfile.TemporaryDirectory() as temporary, recording_server(status) as (port, requests):
+ with tempfile.TemporaryDirectory() as temporary, private_recording_server(status) as (port, requests):
for _method, path, _body in FLEET_ACTION_REQUESTS:
with self.subTest(status=status, path=path):
before = len(requests)
result = self.run_documented_request(Path(temporary), "X-API-Token: " + TEST_TOKEN,
port, recipe(path))
self.assertEqual(result.returncode, 22, result.stderr.decode())
- self.assertIn(b'{"fixture":true}', result.stdout)
self.assertEqual(len(requests), before + 1)
def test_http_auth_errors_fail_instead_of_looking_successful(self):
for status in (401, 403):
with self.subTest(status=status), tempfile.TemporaryDirectory() as temporary:
- with recording_server(status) as (port, _):
+ with private_recording_server(status) as (port, requests):
result = self.run_documented_request(Path(temporary), "X-API-Token: " + TEST_TOKEN, port)
self.assertEqual(result.returncode, 22, result.stderr.decode())
- self.assertIn(b'{"fixture":true}', result.stdout)
+ self.assertEqual(len(requests), 1)
+
+ def test_redirect_and_partial_post_fail_privately_without_retry(self):
+ for status, partial, exitcode in ((302, False, 1), (200, True, 18)):
+ with self.subTest(status=status, partial=partial), tempfile.TemporaryDirectory() as temporary:
+ with private_recording_server(status, partial) as (port, requests):
+ result = self.run_documented_request(Path(temporary), "X-API-Token: " + TEST_TOKEN,
+ port, recipe("/api/actions/act_.../execute"))
+ self.assertEqual(result.returncode, exitcode, result.stderr.decode())
+ self.assertEqual(len(requests), 1, "uncertain POST must not be repeated or redirected")
+
+ def test_private_response_assertion_rejects_console_output_regression(self):
+ request = commands()[1]
+ self.assertEqual(request.count('--output "$result_file" '), 1)
+ unsafe = request.replace('--output "$result_file" ', "")
+ with tempfile.TemporaryDirectory() as temporary, private_recording_server() as (port, requests):
+ with self.assertRaisesRegex(AssertionError, "private response leaked"):
+ self.run_documented_request(Path(temporary), "X-API-Token: " + TEST_TOKEN, port, unsafe)
+ self.assertEqual(len(requests), 1)
if __name__ == "__main__":
diff --git a/scripts/tests/test_pbs_docs.py b/scripts/tests/test_pbs_docs.py
index 3e9f104fcb..18314ad5c7 100644
--- a/scripts/tests/test_pbs_docs.py
+++ b/scripts/tests/test_pbs_docs.py
@@ -25,6 +25,10 @@ DOC = ROOT / "docs/PBS.md"
PBS_TOKEN = "synthetic-pbs-secret"
AGENT_TOKEN = "synthetic-agent-secret"
AUTH_HEADER = f"PBSAPIToken=pulse-monitor@pbs!pulse-token:{PBS_TOKEN}"
+PRIVATE_RESPONSE = json.dumps({
+ "data": [], "token": PBS_TOKEN, "resource": "private-fixture-datastore",
+}).encode() + b"\n"
+DOWNLOAD_SELECTOR = 'installer_file="$config_dir/pbs-agent-install.sh"'
def blocks():
@@ -34,8 +38,8 @@ def blocks():
return re.findall(r"```bash\n(.*?)```", text, re.DOTALL)
-def recipe(needle):
- matches = [block for block in blocks() if needle in block]
+def recipe(needle, *, also=None):
+ matches = [block for block in blocks() if needle in block and (also is None or also in block)]
if len(matches) != 1:
raise AssertionError(f"expected one recipe containing {needle!r}")
return matches[0]
@@ -70,15 +74,17 @@ def server_context(cert, key):
@contextmanager
-def server(cert, key, status=200, installer=None, installer_path="/install.sh"):
+def server(cert, key, status=200, installer=None, installer_path="/install.sh", response=b'{"data":[]}\n'):
requests = []
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
requests.append((self.path, dict(self.headers)))
self.send_response(status)
+ if status == 302:
+ self.send_header("Location", "/should-not-receive-credentials")
self.end_headers()
- body = installer if self.path == installer_path else b'{"data":[]}\n'
+ body = installer if self.path == installer_path else response
self.wfile.write(body or b"fixture error\n")
def log_message(self, *_args):
@@ -97,6 +103,12 @@ def server(cert, key, status=200, installer=None, installer_path="/install.sh"):
thread.join(timeout=5)
+def private_server(cert, key, status=200, installer=None, installer_path="/install.sh"):
+ # The agent guide imports the shared TLS fixture. Only PBS diagnostic
+ # checks use the credential-bearing synthetic response sensitivity marker.
+ return server(cert, key, status, installer, installer_path, response=PRIVATE_RESPONSE)
+
+
class PBSDocsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
@@ -169,7 +181,8 @@ class PBSDocsTest(unittest.TestCase):
def test_private_preparation_preserves_existing_content(self):
for name in ("pbs-agent-token", "pbs-header"):
- command = recipe(f'vi "$HOME/.config/pulse/{name}"')
+ command = recipe(f'credential_file="$config_dir/{name}"', also='vi "$credential_file"')
+ self.assertIn('vi "$credential_file"', command)
with self.subTest(name=name), tempfile.TemporaryDirectory() as temporary:
home = Path(temporary)
tools = home / "tools"
@@ -192,10 +205,13 @@ class PBSDocsTest(unittest.TestCase):
def run_curl(self, home, command, port, ca=None, hostname="localhost"):
private = home / ".config/pulse"
- private.mkdir(parents=True, exist_ok=True, mode=0o700)
+ private.mkdir(parents=True, exist_ok=True, mode=0o755)
header = private / "pbs-header"
header.write_text(f"Authorization: {AUTH_HEADER}\n")
- header.chmod(0o600)
+ header.chmod(0o644)
+ earlier = private / "earlier-pbs-response"
+ earlier.write_bytes(b"earlier private result\n")
+ earlier.chmod(0o600)
real_curl = shutil.which("curl")
self.assertIsNotNone(real_curl)
tools = home / "tools"
@@ -203,30 +219,52 @@ class PBSDocsTest(unittest.TestCase):
recorder = tools / "curl"
recorder.write_text(
"#!/usr/bin/env python3\nimport json, os, sys\nfrom pathlib import Path\n"
- "Path(os.environ['ARGV_RECEIPT']).write_text(json.dumps(sys.argv[1:]))\n"
+ "with Path(os.environ['ARGV_RECEIPT']).open('a') as f: f.write(json.dumps(sys.argv[1:]) + '\\n')\n"
"os.execv(os.environ['REAL_CURL'], [os.environ['REAL_CURL'], *sys.argv[1:]])\n"
)
recorder.chmod(0o700)
receipt = home / "argv.json"
+ receipt.write_text("")
+ trace = home / "curl-trace.txt"
+ (home / ".curlrc").write_text(
+ f'header = "X-Curlrc-Injected: yes"\nverbose\ninsecure\nlocation\ntrace-ascii = "{trace}"\n'
+ )
env = fixture_environment(home)
- env.update(PATH=f"{tools}:{os.environ['PATH']}", REAL_CURL=real_curl, ARGV_RECEIPT=str(receipt))
+ env.update(PATH=f"{tools}:{os.environ['PATH']}", REAL_CURL=real_curl, ARGV_RECEIPT=str(receipt),
+ CURL_HOME=str(home), XDG_CONFIG_HOME=str(home / ".config"))
command = command.replace("https://pbs.example.com:8007", f"https://{hostname}:{port}")
command = command.replace("https://pulse.example.com", f"https://{hostname}:{port}")
if ca is not None:
shutil.copyfile(ca, private / "pbs-ca.pem")
# This is the guide's optional, independently verified CA-file form.
- command = command.replace("curl ", 'curl --cacert "$HOME/.config/pulse/pbs-ca.pem" ', 1)
+ self.assertEqual(command.count("curl --disable "), 1)
+ command = command.replace("curl --disable ", 'curl --disable --cacert "$HOME/.config/pulse/pbs-ca.pem" ', 1)
result = subprocess.run(["bash", "-eu", "-c", command], env=env, capture_output=True, timeout=20)
- argv = json.loads(receipt.read_text())
- for secret in (PBS_TOKEN, AGENT_TOKEN):
+ calls = [json.loads(line) for line in receipt.read_text().splitlines()]
+ self.assertEqual(len(calls), 1, "a copied recipe must invoke curl only once")
+ argv = calls[0]
+ self.assertEqual(argv[0], "--disable", "ignore local curl settings before other options")
+ for secret in (PBS_TOKEN, AGENT_TOKEN, "private-fixture-datastore"):
self.assertNotIn(secret, " ".join(argv))
- self.assertNotIn(secret.encode(), result.stdout + result.stderr)
+ self.assertNotIn(secret.encode(), result.stdout + result.stderr, "private response leaked")
self.assertNotIn("--insecure", argv)
self.assertNotIn("-k", argv)
+ self.assertFalse(trace.exists(), "curl defaults must not enable credential-bearing traces")
+ self.assertEqual(earlier.read_bytes(), b"earlier private result\n")
return result, argv
+ def assert_private_response(self, home, result, expected=PRIVATE_RESPONSE):
+ private = home / ".config/pulse"
+ responses = list(private.glob("pbs-response.*"))
+ self.assertEqual(len(responses), 1)
+ response = responses[0]
+ self.assertIn(str(response).encode(), result.stdout)
+ self.assertEqual(response.read_bytes(), expected)
+ for path, mode in ((private, 0o700), (private / "pbs-header", 0o600), (response, 0o600)):
+ self.assertEqual(stat.S_IMODE(path.stat().st_mode), mode)
+
def test_datastore_request_transmits_auth_only_in_header(self):
- with tempfile.TemporaryDirectory() as temporary, server(self.cert, self.key) as (port, requests):
+ with tempfile.TemporaryDirectory() as temporary, private_server(self.cert, self.key) as (port, requests):
result, argv = self.run_curl(Path(temporary), recipe("--fail-with-body"), port, self.cert)
self.assertEqual(result.returncode, 0, result.stderr.decode())
self.assertIn("--max-time", argv)
@@ -235,25 +273,34 @@ class PBSDocsTest(unittest.TestCase):
self.assertEqual(requests, [("/api2/json/admin/datastore", {
**requests[0][1], "Authorization": AUTH_HEADER,
})])
- self.assertEqual(result.stdout, b'{"data":[]}\n')
+ self.assertNotIn("X-Curlrc-Injected", requests[0][1])
+ self.assert_private_response(Path(temporary), result)
def test_auth_errors_retain_body_and_fail(self):
for status in (401, 403):
with self.subTest(status=status), tempfile.TemporaryDirectory() as temporary:
- with server(self.cert, self.key, status) as (port, requests):
+ with private_server(self.cert, self.key, status) as (port, requests):
result, _ = self.run_curl(Path(temporary), recipe("--fail-with-body"), port, self.cert)
self.assertEqual(result.returncode, 22, result.stderr.decode())
self.assertEqual(len(requests), 1)
- self.assertEqual(result.stdout, b'{"data":[]}\n')
+ self.assert_private_response(Path(temporary), result)
+
+ def test_redirect_is_not_followed_or_successful(self):
+ with tempfile.TemporaryDirectory() as temporary, private_server(self.cert, self.key, 302) as (port, requests):
+ result, _ = self.run_curl(Path(temporary), recipe("--fail-with-body"), port, self.cert)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual(len(requests), 1)
+ self.assert_private_response(Path(temporary), result)
def test_tls_rejects_untrusted_wrong_certificate_and_wrong_hostname(self):
for ca, hostname in ((None, "localhost"), (self.other_cert, "localhost"), (self.cert, "127.0.0.1")):
with self.subTest(ca=ca, hostname=hostname), tempfile.TemporaryDirectory() as temporary:
- with server(self.cert, self.key) as (port, requests):
+ with private_server(self.cert, self.key) as (port, requests):
result, _ = self.run_curl(Path(temporary), recipe("--fail-with-body"), port, ca, hostname)
self.assertEqual(result.returncode, 60, result.stderr.decode())
# Authentication is never sent over an unverified channel.
self.assertEqual(requests, [])
+ self.assert_private_response(Path(temporary), result, b"")
def test_download_and_agent_file_handoff(self):
# The downloaded fixture deliberately cannot install or change a
@@ -270,12 +317,19 @@ assert os.environ['EXPECTED_AGENT_TOKEN'] not in ' '.join(args)
Path(os.environ['AGENT_RECEIPT']).write_text(json.dumps(args))
PY
'''
- with tempfile.TemporaryDirectory() as temporary, server(self.cert, self.key, installer=installer) as (port, requests):
+ with tempfile.TemporaryDirectory() as temporary, private_server(self.cert, self.key, installer=installer) as (port, requests):
home = Path(temporary)
- result, _ = self.run_curl(home, recipe('--output "$HOME/.config/pulse/pbs-agent-install.sh"'), port, self.cert)
+ result, argv = self.run_curl(home, recipe(DOWNLOAD_SELECTOR), port, self.cert)
self.assertEqual(result.returncode, 0, result.stderr.decode())
+ self.assertEqual(len(requests), 1)
self.assertEqual(requests[0][0], "/install.sh")
self.assertNotIn("Authorization", requests[0][1])
+ self.assertNotIn("X-Curlrc-Injected", requests[0][1])
+ self.assertNotIn("--header", argv)
+ saved = home / ".config/pulse/pbs-agent-install.sh"
+ self.assertEqual(saved.read_bytes(), installer)
+ self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o600)
+ self.assertEqual(list(saved.parent.glob("pbs-agent-download.*")), [])
token = home / ".config/pulse/pbs-agent-token"
token.write_text(AGENT_TOKEN + "\n")
token.chmod(0o600)
@@ -294,11 +348,23 @@ PY
self.assertIn('read_collector_token_file_safely "$TOKEN_FILE_PATH" true', actual)
def test_failed_installer_download_is_nonzero(self):
- with tempfile.TemporaryDirectory() as temporary, server(self.cert, self.key, 403) as (port, _requests):
- home = Path(temporary)
- result, _ = self.run_curl(home, recipe('--output "$HOME/.config/pulse/pbs-agent-install.sh"'), port, self.cert)
- self.assertEqual(result.returncode, 22, result.stderr.decode())
- self.assertFalse((home / ".config/pulse/pbs-agent-install.sh").exists())
+ for status, exitcode in ((403, 22), (302, 1), (204, 1)):
+ with self.subTest(status=status), tempfile.TemporaryDirectory() as temporary:
+ with private_server(self.cert, self.key, status) as (port, requests):
+ home = Path(temporary)
+ result, _ = self.run_curl(home, recipe(DOWNLOAD_SELECTOR), port, self.cert)
+ self.assertEqual(result.returncode, exitcode, result.stderr.decode())
+ self.assertEqual(len(requests), 1)
+ self.assertFalse((home / ".config/pulse/pbs-agent-install.sh").exists())
+
+ def test_private_response_assertion_rejects_console_output_regression(self):
+ command = recipe("--fail-with-body")
+ self.assertEqual(command.count('--output "$result_file" '), 1)
+ unsafe = command.replace('--output "$result_file" ', "")
+ with tempfile.TemporaryDirectory() as temporary, private_server(self.cert, self.key) as (port, requests):
+ with self.assertRaisesRegex(AssertionError, "private response leaked"):
+ self.run_curl(Path(temporary), unsafe, port, self.cert)
+ self.assertEqual(len(requests), 1)
if __name__ == "__main__":