mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-11-28 16:58:31 +01:00
Bind the timeout and saved-expiry examples independently to the private read-only transport. Bound timeout prose checks to their own section and preserve exact recipe multiplicity, missing/extra-call rejection and both examples' real-curl safety controls. Contract-Neutral: Documentation fixture inventory and section-boundary repair only; no runtime, authority, transport policy or rendered guide change. Change-source: pulse-maintainer
592 lines
34 KiB
Python
592 lines
34 KiB
Python
#!/usr/bin/env python3
|
||
"""Exercise the API guide's credential-file commands with synthetic secrets.
|
||
|
||
The HTTP tests need guest-local loopback; run via pulse-worker-source-proof.
|
||
No real Pulse instance, credentials or external network is used.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from contextlib import contextmanager
|
||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||
import json
|
||
import os
|
||
from pathlib import Path
|
||
import re
|
||
import shlex
|
||
import shutil
|
||
import stat
|
||
import subprocess
|
||
import tempfile
|
||
import threading
|
||
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:
|
||
return DOC.read_text(encoding="utf-8").split("## 🔐 Authentication\n", 1)[1].split("\n## ", 1)[0]
|
||
|
||
|
||
def commands() -> tuple[str, str]:
|
||
blocks = re.findall(r"```bash\n(.*?)```", auth_section(), re.DOTALL)
|
||
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 block.startswith("pulse_api ") and path in block]
|
||
if len(matches) != 1:
|
||
raise AssertionError(f"expected one executable recipe for {path}")
|
||
# 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
|
||
# ensures the fixture tests what readers copy, not a second hand-written client.
|
||
FLEET_ACTION_REQUESTS = (
|
||
("GET", "/api/connections", None),
|
||
("GET", "/api/agent/resource-capabilities/vm%3A42", None),
|
||
("POST", "/api/actions/plan", {
|
||
"requestId": "manual-recovery-123", "resourceId": "vm:42",
|
||
"capabilityName": "restart", "params": {"mode": "graceful"},
|
||
"reason": "Recover after confirmed outage",
|
||
}),
|
||
("POST", "/api/actions/act_.../decision", {
|
||
"outcome": "approved", "reason": "Inside maintenance window", "planHash": "sha256:...",
|
||
}),
|
||
("POST", "/api/actions/act_.../execute", {
|
||
"reason": "Execute approved recovery", "planHash": "sha256:...",
|
||
}),
|
||
("GET", "/api/audit/actions?resourceId=vm%3A42&limit=10", None),
|
||
("GET", "/api/audit/actions/act_.../events", None),
|
||
)
|
||
|
||
|
||
@contextmanager
|
||
def recording_server(status: int = 200, partial: bool = False, response: bytes = b'{"fixture":true}\n'):
|
||
requests = []
|
||
|
||
class Handler(BaseHTTPRequestHandler):
|
||
def record_request(self):
|
||
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(response)
|
||
|
||
do_GET = record_request
|
||
do_POST = record_request
|
||
do_PUT = record_request
|
||
do_PATCH = record_request
|
||
do_DELETE = record_request
|
||
|
||
def log_message(self, *_args):
|
||
pass
|
||
|
||
server = HTTPServer(("127.0.0.1", 0), Handler)
|
||
# Poll only the fixture server more often so teardown need not wait 500 ms.
|
||
# This does not shorten any copied request, reader or cleanup deadline.
|
||
thread = threading.Thread(target=server.serve_forever,
|
||
kwargs={"poll_interval": 0.05}, daemon=True)
|
||
thread.start()
|
||
try:
|
||
yield server.server_address[1], requests
|
||
finally:
|
||
server.shutdown()
|
||
server.server_close()
|
||
thread.join(timeout=5)
|
||
|
||
|
||
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, proxy_port: int | None = None):
|
||
"""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(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"
|
||
tools.mkdir(exist_ok=True)
|
||
recorder = tools / "curl"
|
||
recorder.write_text(
|
||
"#!/usr/bin/env python3\nimport json, os, sys\n"
|
||
"from pathlib import Path\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\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),
|
||
REAL_CURL=real_curl, ARGV_RECEIPT=str(receipt))
|
||
for key in list(env):
|
||
if key.lower().endswith("_proxy"):
|
||
del env[key]
|
||
if proxy_port is not None:
|
||
# A guest-local recording proxy witnesses whether a copied loopback
|
||
# recipe can disclose its credential through inherited proxy settings.
|
||
proxy = f"http://127.0.0.1:{proxy_port}"
|
||
env.update(http_proxy=proxy, HTTPS_PROXY=proxy, ALL_PROXY=proxy,
|
||
no_proxy="", NO_PROXY="")
|
||
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)
|
||
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)
|
||
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
|
||
|
||
|
||
class APIAuthDocsTest(unittest.TestCase):
|
||
def test_base_url_guidance_limits_plain_http_to_the_pulse_host(self):
|
||
introduction = DOC.read_text().split("## 🔐 Authentication\n", 1)[0]
|
||
self.assertIn("configured HTTPS origin", introduction)
|
||
self.assertEqual(re.findall(r"http://[^\s`]+", introduction),
|
||
["http://127.0.0.1:7655/api"])
|
||
self.assertRegex(" ".join(introduction.split()),
|
||
r"on the Pulse host only: `http://127\.0\.0\.1:7655/api`")
|
||
# The lead must agree with the executable helper, not replace the
|
||
# existing private-header and certificate-verifying remote recipe.
|
||
self.assertIn("http://127.0.0.1:7655$api_path", request_helper())
|
||
self.assertIn("--proto '=https'", auth_section())
|
||
self.assertIn("never `--insecure`", auth_section())
|
||
|
||
def test_credentials_are_not_documented_as_command_arguments(self):
|
||
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 "@$auth_file"', request_helper())
|
||
self.assertIn("HTTPS", section)
|
||
self.assertIn("does not verify authentication", section)
|
||
self.assertIn("monitoring:read", section)
|
||
self.assertIn("Do not paste tokens", section)
|
||
|
||
def test_all_shell_recipes_keep_credentials_out_of_arguments_and_defaults(self):
|
||
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)")
|
||
blocks = re.findall(r"```bash\n(.*?)```", DOC.read_text(), re.DOTALL)
|
||
requests = [block for block in blocks if block.startswith("pulse_api ")]
|
||
expected_requests = [
|
||
("GET", "/api/state/summary"),
|
||
*((method, path) for method, path, _ in FLEET_ACTION_REQUESTS),
|
||
("POST", "/api/config/nodes"),
|
||
# Independent recovery and saved-expiry examples both use the list.
|
||
("GET", "/api/security/tokens"),
|
||
("GET", "/api/security/tokens"),
|
||
]
|
||
self.assertEqual([tuple(shlex.split(block.splitlines()[0])[1:3]) for block in requests],
|
||
expected_requests, "every copied operation needs an explicit expected route")
|
||
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:
|
||
if request.startswith("pulse_api POST "):
|
||
self.assertIn("--data-binary @-", request_helper())
|
||
if request.startswith("pulse_api POST /api/config/nodes "):
|
||
self.assertEqual(request.strip(), 'pulse_api POST /api/config/nodes < "$node_request_file"')
|
||
else:
|
||
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",
|
||
"actions:execute", "audit:read"):
|
||
self.assertIn(scope, guide)
|
||
for boundary in ("steps separately", "bound to an authorised user", "licensed audit logging",
|
||
"separation of duties", "step-up", "losing the connection",
|
||
"terminal result", "planHash", "URL-encode"):
|
||
self.assertIn(boundary, guide)
|
||
|
||
def test_shipped_copy_is_identical(self):
|
||
self.assertEqual(DOC.read_bytes(), (ROOT / "frontend-modern/public/docs/API.md").read_bytes())
|
||
|
||
def test_preparation_protects_new_and_existing_header_files(self):
|
||
preparation, _ = commands()
|
||
with tempfile.TemporaryDirectory() as temporary:
|
||
home = Path(temporary)
|
||
tools = home / "tools"
|
||
tools.mkdir()
|
||
# The editor must be interactive in the real recipe; this fixture
|
||
# verifies its filename without putting a synthetic token in argv.
|
||
editor = tools / "vi"
|
||
editor.write_text('#!/bin/sh\n[ "$#" = 1 ] && [ "$1" = "$HOME/.config/pulse/api-header" ]\n')
|
||
editor.chmod(0o700)
|
||
env = dict(os.environ, HOME=str(home), PATH=f"{tools}:{os.environ['PATH']}")
|
||
header = home / ".config/pulse/api-header"
|
||
for existing in (False, True):
|
||
if existing:
|
||
header.write_text(f"X-API-Token: {TEST_TOKEN}\n")
|
||
header.chmod(0o644)
|
||
subprocess.run(["bash", "-eu", "-c", preparation], env=env, check=True)
|
||
self.assertEqual(stat.S_IMODE(header.stat().st_mode), 0o600)
|
||
self.assertEqual(stat.S_IMODE(header.parent.stat().st_mode), 0o700)
|
||
self.assertEqual(header.read_text(), f"X-API-Token: {TEST_TOKEN}\n" if existing else "")
|
||
|
||
def test_preparation_rejects_symlinked_paths_without_editing_or_chmodding_targets(self):
|
||
preparation, _request = commands()
|
||
for component in (".config", ".config/pulse", ".config/pulse/api-header"):
|
||
with self.subTest(component=component), tempfile.TemporaryDirectory() as temporary:
|
||
home = Path(temporary) / "home"
|
||
home.mkdir()
|
||
target = Path(temporary) / "target"
|
||
if component.endswith("api-header"):
|
||
target.write_text("preserve target\n")
|
||
target.chmod(0o644)
|
||
else:
|
||
target.mkdir()
|
||
target.chmod(0o755)
|
||
link = home / component
|
||
link.parent.mkdir(parents=True, exist_ok=True)
|
||
link.symlink_to(target)
|
||
tools = home / "tools"
|
||
tools.mkdir()
|
||
editor = tools / "vi"
|
||
editor.write_text('#!/bin/sh\ntouch "$HOME/editor-called"\n')
|
||
editor.chmod(0o700)
|
||
before = stat.S_IMODE(target.stat().st_mode)
|
||
env = dict(os.environ, HOME=str(home), PATH=f"{tools}:{os.environ['PATH']}")
|
||
result = subprocess.run(["bash", "-c", preparation], env=env, capture_output=True, timeout=10)
|
||
self.assertNotEqual(result.returncode, 0)
|
||
self.assertFalse((home / "editor-called").exists())
|
||
self.assertEqual(stat.S_IMODE(target.stat().st_mode), before)
|
||
if target.is_file():
|
||
self.assertEqual(target.read_text(), "preserve target\n")
|
||
else:
|
||
self.assertEqual(list(target.iterdir()), [])
|
||
|
||
def test_preparation_failure_stops_before_editor_in_an_ordinary_shell(self):
|
||
preparation, _request = commands()
|
||
for failing_command in ("mkdir", "touch", "chmod"):
|
||
with self.subTest(command=failing_command), tempfile.TemporaryDirectory() as temporary:
|
||
home = Path(temporary)
|
||
tools = home / "tools"
|
||
tools.mkdir()
|
||
failure = tools / failing_command
|
||
failure.write_text("#!/bin/sh\nexit 73\n")
|
||
failure.chmod(0o700)
|
||
editor = tools / "vi"
|
||
editor.write_text('#!/bin/sh\n: > "$HOME/editor-called"\n')
|
||
editor.chmod(0o700)
|
||
env = dict(os.environ, HOME=str(home), PATH=f"{tools}:{os.environ['PATH']}")
|
||
result = subprocess.run(["bash", "-c", preparation], env=env, capture_output=True, timeout=10)
|
||
self.assertEqual(result.returncode, 73)
|
||
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],
|
||
private_response=True)
|
||
|
||
def test_header_file_sends_each_supported_header_without_exposing_argv(self):
|
||
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)
|
||
self.assertEqual(result.returncode, 0, result.stderr.decode())
|
||
self.assertEqual(requests[-1][0], "/api/state/summary")
|
||
self.assertEqual(requests[-1][1][key], value)
|
||
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, 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):
|
||
before = len(requests)
|
||
result = self.run_documented_request(Path(temporary), f"{key}: {value}", port,
|
||
recipe(path))
|
||
self.assertEqual(result.returncode, 0, result.stderr.decode())
|
||
self.assertEqual(len(requests), before + 1, "each step sends only its own request")
|
||
sent_path, headers, sent_method, sent_body = requests[-1]
|
||
self.assertEqual((sent_method, sent_path), (method, path))
|
||
self.assertEqual(headers[key], value)
|
||
other_key = "Authorization" if key == "X-API-Token" else "X-API-Token"
|
||
self.assertNotIn(other_key, headers)
|
||
self.assertNotIn("X-Curlrc-Injected", headers)
|
||
if body is None:
|
||
self.assertEqual(sent_body, b"")
|
||
else:
|
||
self.assertEqual(headers["Content-Type"], "application/json")
|
||
self.assertEqual(json.loads(sent_body), body)
|
||
|
||
def test_each_fleet_action_recipe_surfaces_auth_errors_without_following_steps(self):
|
||
for status in (401, 403):
|
||
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.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 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.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_shared_helper_preserves_method_and_body_for_existing_admin_operations(self):
|
||
with private_recording_server() as (port, requests), tempfile.TemporaryDirectory() as temporary:
|
||
for method in ("GET", "POST", "PUT", "DELETE"):
|
||
with self.subTest(method=method):
|
||
call = f"pulse_api {method} /api/admin/roles <<'JSON'\n{{\"fixture\":true}}\nJSON\n"
|
||
result = self.run_documented_request(Path(temporary), "X-API-Token: " + TEST_TOKEN,
|
||
port, request_helper() + "\n" + call)
|
||
self.assertEqual(result.returncode, 0, result.stderr.decode())
|
||
path, headers, sent_method, body = requests[-1]
|
||
self.assertEqual((sent_method, path), (method, "/api/admin/roles"))
|
||
if method in ("POST", "PUT"):
|
||
self.assertEqual(headers["Content-Type"], "application/json")
|
||
self.assertEqual(json.loads(body), {"fixture": True})
|
||
else:
|
||
self.assertEqual(body, b"")
|
||
self.assertNotIn("Content-Type", headers)
|
||
self.assertEqual(len(requests), 4)
|
||
|
||
def test_token_edit_patch_uses_private_stdin_without_redirect_or_retry(self):
|
||
# PATCH is the existing token-edit method. Exercise the exact copied
|
||
# helper against a recording HTTP server, not a hand-written curl call.
|
||
# This witnesses transport/privacy, not backend permission decisions.
|
||
payload = {"name": "private-fixture-token-name", "scopes": ["monitoring:read"]}
|
||
for status, partial, expected_exit in ((200, False, 0), (400, False, 22),
|
||
(401, False, 22), (403, False, 22),
|
||
(302, False, 1), (200, True, 18)):
|
||
for key, value in (("X-API-Token", TEST_TOKEN), ("Authorization", "Bearer " + TEST_TOKEN)):
|
||
with self.subTest(status=status, partial=partial, header=key), \
|
||
tempfile.TemporaryDirectory() as temporary, \
|
||
private_recording_server(status, partial) as (port, requests), \
|
||
recording_server() as (proxy_port, proxy_requests):
|
||
home = Path(temporary)
|
||
body_file = home / "private-token-edit.json"
|
||
body_file.write_text(json.dumps(payload) + "\n")
|
||
body_file.chmod(0o600)
|
||
call = 'pulse_api PATCH /api/security/tokens/doc-fixture < "$HOME/private-token-edit.json"'
|
||
result = exercise_curl(self, home, f"{key}: {value}", port,
|
||
request_helper() + "\n" + call,
|
||
private_response=True, proxy_port=proxy_port)
|
||
self.assertEqual(result.returncode, expected_exit, result.stderr.decode())
|
||
self.assertEqual(len(requests), 1, "token edit must not retry or follow a redirect")
|
||
self.assertEqual(proxy_requests, [], "loopback token edit must bypass inherited proxies")
|
||
path, headers, method, body = requests[0]
|
||
self.assertEqual((method, path), ("PATCH", "/api/security/tokens/doc-fixture"))
|
||
self.assertEqual(headers[key], value)
|
||
other_key = "Authorization" if key == "X-API-Token" else "X-API-Token"
|
||
self.assertNotIn(other_key, headers)
|
||
self.assertNotIn("X-Curlrc-Injected", headers)
|
||
self.assertEqual(headers["Content-Type"], "application/json")
|
||
self.assertEqual(json.loads(body), payload)
|
||
self.assertEqual(json.loads(body_file.read_text()), payload)
|
||
self.assertEqual(stat.S_IMODE(body_file.stat().st_mode), 0o600)
|
||
self.assertNotIn(payload["name"].encode(), result.stdout + result.stderr)
|
||
self.assertNotIn(payload["name"], (home / "argv.json").read_text())
|
||
|
||
def test_shared_helper_keeps_glob_shaped_paths_and_queries_literal(self):
|
||
# One curl process can still send multiple HTTP requests: shell quoting
|
||
# and an argv-count assertion do not prevent curl's own URL expansion.
|
||
paths = (
|
||
"/api/admin/roles/{review,ops}",
|
||
"/api/admin/roles/team[1-3]",
|
||
"/api/audit/actions?resourceId=host[1-3]&limit=10",
|
||
"/api/audit/actions?filter[resource]=host{a,b}",
|
||
)
|
||
self.assert_literal_requests(paths)
|
||
|
||
def test_shared_helper_preserves_percent_encoded_identifiers(self):
|
||
self.assert_literal_requests((
|
||
"/api/admin/roles/%7Breview%2Cops%7D%5B1-3%5D",
|
||
"/api/audit/actions?resourceId=host%5B1-3%5D&limit=10",
|
||
))
|
||
|
||
def assert_literal_requests(self, paths):
|
||
with private_recording_server() as (port, requests), tempfile.TemporaryDirectory() as temporary:
|
||
for key, value in (("X-API-Token", TEST_TOKEN), ("Authorization", "Bearer " + TEST_TOKEN)):
|
||
for method in ("GET", "POST", "PUT", "PATCH", "DELETE"):
|
||
for path in paths:
|
||
with self.subTest(header=key, method=method, path=path):
|
||
before = len(requests)
|
||
call = f"pulse_api {method} '{path}' <<'JSON'\n{{\"fixture\":true}}\nJSON\n"
|
||
result = self.run_documented_request(Path(temporary), f"{key}: {value}", port,
|
||
request_helper() + "\n" + call)
|
||
self.assertEqual(len(requests), before + 1,
|
||
"one supplied URL must not expand into multiple requests")
|
||
sent_path, headers, sent_method, body = requests[-1]
|
||
self.assertEqual((sent_method, sent_path), (method, path))
|
||
self.assertEqual(result.returncode, 0, result.stderr.decode())
|
||
self.assertEqual(headers[key], value)
|
||
other_key = "Authorization" if key == "X-API-Token" else "X-API-Token"
|
||
self.assertNotIn(other_key, headers)
|
||
self.assertNotIn("X-Curlrc-Injected", headers)
|
||
if method in ("POST", "PUT", "PATCH"):
|
||
self.assertEqual(headers["Content-Type"], "application/json")
|
||
self.assertEqual(json.loads(body), {"fixture": True})
|
||
else:
|
||
self.assertEqual(body, b"")
|
||
self.assertNotIn("Content-Type", headers)
|
||
|
||
def test_glob_shaped_write_fails_privately_without_additional_requests(self):
|
||
for status, partial, expected_exit in ((401, False, 22), (302, False, 1), (200, True, 18)):
|
||
with private_recording_server(status, partial) as (port, requests):
|
||
for method in ("POST", "PATCH", "DELETE"):
|
||
for key, value in (("X-API-Token", TEST_TOKEN), ("Authorization", "Bearer " + TEST_TOKEN)):
|
||
with self.subTest(status=status, method=method, header=key), tempfile.TemporaryDirectory() as temporary:
|
||
before = len(requests)
|
||
path = "/api/admin/roles/{review,ops}"
|
||
call = f"pulse_api {method} '{path}' <<'JSON'\n{{\"fixture\":true}}\nJSON\n"
|
||
result = self.run_documented_request(Path(temporary), f"{key}: {value}", port,
|
||
request_helper() + "\n" + call)
|
||
self.assertEqual(result.returncode, expected_exit, result.stderr.decode())
|
||
self.assertEqual(len(requests), before + 1,
|
||
"failure must not submit another target or retry the write")
|
||
self.assertEqual((requests[-1][2], requests[-1][0]), (method, path))
|
||
|
||
def test_shared_helper_refuses_unsupported_methods_urls_and_missing_auth_before_transport(self):
|
||
with recording_server() as (port, requests), tempfile.TemporaryDirectory() as temporary:
|
||
env = dict(os.environ, HOME=temporary)
|
||
for call, expected_exit in (("pulse_api OPTIONS /api/admin/roles", 2),
|
||
("pulse_api GET https://example.invalid/api/admin/roles", 2),
|
||
("pulse_api DELETE", 2),
|
||
("pulse_api DELETE /api/admin/roles/unused", 1)):
|
||
with self.subTest(call=call):
|
||
command = (request_helper() + "\n" + call).replace("http://127.0.0.1:7655", f"http://127.0.0.1:{port}")
|
||
result = subprocess.run(["bash", "-eu", "-c", command], env=env,
|
||
capture_output=True, timeout=10)
|
||
self.assertEqual(result.returncode, expected_exit, result.stderr.decode())
|
||
self.assertEqual(requests, [])
|
||
self.assertFalse((Path(temporary) / ".config").exists())
|
||
|
||
def test_uncertain_token_change_keeps_identity_and_secret_limits_explicit(self):
|
||
source = DOC.read_text()
|
||
heading = "## When a token change times out\n"
|
||
self.assertEqual(source.count(heading), 1, "missing token-change recovery guidance")
|
||
section = " ".join(source.split(heading, 1)[1].split("\n## ", 1)[0].split())
|
||
for boundary in (
|
||
"Do not repeat the change", "independent administrator session",
|
||
"metadata only", "Names are not unique", "exact record IDs",
|
||
"404 can mean absent or hidden from this caller",
|
||
"snapshot does not prove an earlier request cannot still finish",
|
||
"Do not rotate or recreate the token to resolve an unconfirmed edit",
|
||
"GET cannot recover the raw secret", "exact successor",
|
||
"settle the original attempt", "separate, intentional rotation",
|
||
"preserves its existing scopes, bindings, metadata and expiry",
|
||
"rather than guess, grant full access or re-enrol agents",
|
||
):
|
||
with self.subTest(boundary=boundary):
|
||
self.assertIn(boundary, section)
|
||
self.assertIn("[shown once](#when-a-token-change-times-out)", source)
|
||
self.assertIn("do not replay a POST, PUT, PATCH or DELETE after a lost response", source)
|
||
self.assertEqual(DOC.read_bytes(), (ROOT / "frontend-modern/public/docs/API.md").read_bytes())
|
||
|
||
def test_token_recovery_and_expiry_each_copy_one_private_metadata_read(self):
|
||
source = DOC.read_text()
|
||
for heading in ("## When a token change times out\n", "## Checking a saved token’s expiry\n"):
|
||
self.assertEqual(source.count(heading), 1, "missing or duplicate private-read section")
|
||
section = source.split(heading, 1)[1].split("\n## ", 1)[0]
|
||
blocks = re.findall(r"```bash\n(.*?)```", section, re.DOTALL)
|
||
self.assertEqual(blocks, ["pulse_api GET /api/security/tokens\n"],
|
||
"each section must copy one read, never a write or metadata output")
|
||
for status, partial, expected_exit in ((200, False, 0), (401, False, 22),
|
||
(403, False, 22), (404, False, 22),
|
||
(500, False, 22), (302, False, 1),
|
||
(200, True, 18)):
|
||
for key, value in (("X-API-Token", TEST_TOKEN), ("Authorization", "Bearer " + TEST_TOKEN)):
|
||
with self.subTest(section=heading, status=status, partial=partial, header=key), \
|
||
private_recording_server(status, partial) as (port, requests), \
|
||
tempfile.TemporaryDirectory() as temporary:
|
||
home = Path(temporary)
|
||
result = exercise_curl(self, home, f"{key}: {value}", port,
|
||
request_helper() + "\n" + blocks[0], private_response=True)
|
||
self.assertEqual(result.returncode, expected_exit, result.stderr.decode())
|
||
self.assertEqual(len(requests), 1, "never replay a write, redirect or retry")
|
||
sent_path, headers, method, body = requests[0]
|
||
self.assertEqual((method, sent_path, body), ("GET", "/api/security/tokens", b""))
|
||
self.assertEqual(headers[key], value)
|
||
|
||
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__":
|
||
unittest.main()
|