mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-11-29 17:21:13 +01:00
Correct org-bound API token refusal, instance-admin boundaries, license tiers, and missing registered routes across docs/WEBHOOKS.md, docs/AUDIT_LOGGING.md, and docs/TRUENAS.md (and their frontend-modern/public/docs/ mirrors) to match internal/api/router_routes_monitoring.go, router_routes_licensing.go, router_routes_registration.go, platform_connection_shared.go, security_setup_fix.go, and pkg/licensing/features.go, and add router-anchored doc contract assertions in scripts/tests/test_admin_docs.py and scripts/tests/test_truenas_docs.py. Contract-Neutral: Documentation and router-anchored doc tests only; aligns shipped Help guides with existing runtime authorization, license tier, and route contracts without changing runtime behavior. Change-source: pulse-maintainer
734 lines
43 KiB
Python
734 lines
43 KiB
Python
#!/usr/bin/env python3
|
|
"""Execute the administration guides with synthetic credentials and loopback.
|
|
|
|
Run with pulse-worker-source-proof; these fixtures do not perform real role,
|
|
tenant or audit operations. The Go documentation tests check the actual handlers.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import tempfile
|
|
import unittest
|
|
|
|
from test_api_auth_docs import (ROOT, TEST_TOKEN, exercise_curl, recording_server,
|
|
private_recording_server, request_helper)
|
|
|
|
|
|
DOCS = ROOT / "docs"
|
|
GUIDES = ("RBAC", "AUDIT_LOGGING", "MULTI_TENANT")
|
|
EXPECTED = {
|
|
"RBAC": (
|
|
("POST", "/api/admin/roles", {
|
|
"id": "alert-manager", "name": "Alert Manager",
|
|
"description": "Can view and manage alerts",
|
|
"permissions": [{"action": "read", "resource": "alerts"},
|
|
{"action": "write", "resource": "alerts"},
|
|
{"action": "read", "resource": "nodes"}],
|
|
}),
|
|
("GET", "/api/admin/roles", None),
|
|
("PUT", "/api/admin/roles/alert-manager", {
|
|
"name": "Alert Manager", "description": "Updated description",
|
|
"permissions": [{"action": "read", "resource": "alerts"},
|
|
{"action": "write", "resource": "alerts"},
|
|
{"action": "read", "resource": "nodes"},
|
|
{"action": "read", "resource": "ai"}],
|
|
}),
|
|
("DELETE", "/api/admin/roles/alert-manager", None),
|
|
("GET", "/api/admin/users", None),
|
|
("PUT", "/api/admin/users/jane/roles", {"roleIds": ["alert-manager", "viewer"]}),
|
|
("PUT", "/api/admin/users/jane/roles", {"roleIds": []}),
|
|
("DELETE", "/api/admin/users/jane", None),
|
|
),
|
|
"AUDIT_LOGGING": (
|
|
("GET", "/api/audit?limit=50", None),
|
|
("GET", "/api/audit?limit=50&event=login&startTime=2026-01-01T00:00:00Z&endTime=2026-01-31T23:59:59Z&success=false", None),
|
|
("GET", "/api/audit/summary", None),
|
|
("GET", "/api/audit/export?event=login&startTime=2026-01-01T00:00:00Z&endTime=2026-01-31T23:59:59Z", None),
|
|
("GET", "/api/audit/6b3c9c3c-9a2f-4b3c-9a3b-3d0e8c5c5d45/verify", None),
|
|
),
|
|
"MULTI_TENANT": (
|
|
("GET", "/api/orgs/production-datacenter/members", None),
|
|
("GET", "/api/orgs/production-datacenter/shares/incoming", None),
|
|
),
|
|
}
|
|
|
|
|
|
def recipes(name: str) -> list[str]:
|
|
requests = []
|
|
for block in re.findall(r"```bash\n(.*?)```", (DOCS / f"{name}.md").read_text(), re.DOTALL):
|
|
# The audit read examples share a fence but are independent operations.
|
|
for step in re.split(r"\n(?=# )", block):
|
|
if "curl " in step or "pulse_api " in step:
|
|
requests.append(step)
|
|
return requests
|
|
|
|
|
|
def executable_recipe(name: str, step: str) -> str:
|
|
# Use the actual shared helper, not a test-only safe client. Legacy curl
|
|
# snippets remain executable so the parent control can expose their leak.
|
|
if "pulse_api " in step:
|
|
return request_helper() + "\n" + step
|
|
return step
|
|
|
|
|
|
class AdminDocsTest(unittest.TestCase):
|
|
def test_shell_recipes_never_expose_credentials_or_override_tls(self):
|
|
for name in GUIDES:
|
|
with self.subTest(guide=name):
|
|
steps = recipes(name)
|
|
self.assertEqual(len(steps), len(EXPECTED[name]))
|
|
for step in steps:
|
|
self.assertNotRegex(step, r"(?:\b\w*TOKEN=|Authorization:|X-API-Token:|Bearer\s|--cookie\b)")
|
|
self.assertNotRegex(step, r"(?:--insecure|--verbose|--trace\S*|--location|\s-k\b)")
|
|
self.assertIn("pulse_api ", step)
|
|
self.assertNotIn("curl ", step)
|
|
if re.search(r"(?:--request|pulse_api) (POST|PUT)", step):
|
|
self.assertIn("--data-binary @-", request_helper() if "pulse_api " in step else step)
|
|
self.assertIn("<<'JSON'", step)
|
|
|
|
def test_guides_explain_authority_and_sensitive_output(self):
|
|
for name in GUIDES:
|
|
guide = (DOCS / f"{name}.md").read_text()
|
|
with self.subTest(guide=name):
|
|
self.assertIn("API.md#-authentication", guide)
|
|
self.assertIn("HTTPS", guide)
|
|
self.assertIn("certificate verification", guide)
|
|
rbac = (DOCS / "RBAC.md").read_text()
|
|
for boundary in ("full-access (`*`)", "bound to an authorised administrator", "cannot be modified or deleted", "self-escalation", "complete list", "URL-encode"):
|
|
self.assertIn(boundary, rbac)
|
|
audit = (DOCS / "AUDIT_LOGGING.md").read_text()
|
|
for boundary in ("audit:read", "audit_logging", "private directory", "redacted excerpt", "does not reuse filters",
|
|
"in the same Bash session", "not an installed Pulse command", "not list pagination",
|
|
"reject malformed or empty supplied", "before reading events", "not `success` or list", "partial file", "does not follow redirects or retry"):
|
|
self.assertIn(boundary, audit)
|
|
for boundary in ("10,000 matching events", "export_too_large", "not a partial download",
|
|
"truncated summary", "not a byte-size", "query-duration guarantee"):
|
|
self.assertIn(boundary, audit)
|
|
org = (DOCS / "MULTI_TENANT.md").read_text()
|
|
for boundary in ("session-based user authentication", "403 session_required", "CSRF", "settings:read", "organization binding", "pending invitation", "accept the share", "accessRole"):
|
|
self.assertIn(boundary, org)
|
|
self.assertNotRegex(org, r"\| `PATCH` \|")
|
|
|
|
def test_shipped_copies_are_identical(self):
|
|
for name in (*GUIDES, "API"):
|
|
with self.subTest(guide=name):
|
|
self.assertEqual((DOCS / f"{name}.md").read_bytes(),
|
|
(ROOT / "frontend-modern/public/docs" / f"{name}.md").read_bytes())
|
|
|
|
def test_api_reference_uses_its_custom_role_and_links_full_policy_guidance(self):
|
|
reference = (DOCS / "API.md").read_text()
|
|
|
|
def section(heading):
|
|
return reference.split(f"### {heading}\n", 1)[1].split("\n### ", 1)[0]
|
|
|
|
create = json.loads(re.search(r"```json\n(.*?)```", section("Create Role"), re.S)[1])
|
|
assignment = json.loads(re.search(r"```json\n(.*?)```", section("Set User Roles"), re.S)[1])
|
|
self.assertEqual(create["id"], EXPECTED["RBAC"][0][2]["id"])
|
|
self.assertNotIn(create["id"], ("admin", "operator", "viewer", "auditor"))
|
|
self.assertEqual(assignment["roleIds"], [create["id"], "viewer"])
|
|
self.assertEqual(create["permissions"], [
|
|
{"action": "read", "resource": "alerts"},
|
|
{"action": "write", "resource": "alerts"},
|
|
])
|
|
update = section("Update Role")
|
|
self.assertIn("Full policy replacement.", update)
|
|
self.assertIn("[Preserve saved fields](RBAC.md#before-using-the-api)", update)
|
|
self.assertNotIn("name, description, or permissions", update)
|
|
|
|
def test_rbac_setup_guidance_matches_navigation_and_failure_states(self):
|
|
guide = (DOCS / "RBAC.md").read_text()
|
|
readable = " ".join(guide.replace("**", "").split())
|
|
frontend = ROOT / "frontend-modern/src"
|
|
navigation = (frontend / "components/Settings/settingsNavCatalog.ts").read_text()
|
|
for panel in ("roles", "users"):
|
|
with self.subTest(panel=panel):
|
|
entry = re.search(
|
|
rf"id: 'security-{panel}',(.*?)(?=\n\s+id:|\Z)",
|
|
navigation, re.DOTALL,
|
|
).group(1)
|
|
self.assertIn("features: ['rbac']", entry)
|
|
self.assertIn("hideWhenUnavailable: true", entry)
|
|
self.assertIn(f"requiredCapability: '{panel}'", entry)
|
|
for label, source in (
|
|
("Pro runtime missing", "utils/licensePresentation.ts"),
|
|
("Open Pulse Pro downloads", "utils/licensePresentation.ts"),
|
|
("Roles are unavailable for this session", "components/Settings/RolesPanel.tsx"),
|
|
("User access is unavailable for this session", "components/Settings/UserAssignmentsPanel.tsx"),
|
|
("Failed to load roles", "utils/rbacPresentation.ts"),
|
|
("Failed to load user assignments", "utils/rbacPresentation.ts"),
|
|
):
|
|
with self.subTest(label=label):
|
|
self.assertIn(label, readable)
|
|
self.assertIn(label, " ".join((frontend / source).read_text().split()))
|
|
for boundary in (
|
|
"active licence is not an administrator grant",
|
|
"licence and runtime status",
|
|
"do not buy a second licence or reset the data directory",
|
|
"independent administrator recovery path",
|
|
"next sign-in replaces manually assigned roles",
|
|
"#automatic-role-assignment-via-oidc",
|
|
"runtime's `rbac` capability and this session's permission",
|
|
"missing menu entry alone does not tell you which check failed",
|
|
"do not remove proxy role gating or widen an agent's token",
|
|
"not proof that no roles or users exist",
|
|
"Do not create or delete access records to test it",
|
|
):
|
|
with self.subTest(boundary=boundary):
|
|
self.assertIn(boundary, readable)
|
|
|
|
def test_rbac_unconfirmed_change_guidance_uses_existing_read_controls(self):
|
|
guide = (DOCS / "RBAC.md").read_text()
|
|
section = guide.split("### A role or user change could not be confirmed\n", 1)[1].split("\n---", 1)[0]
|
|
readable = " ".join(section.replace("**", "").split())
|
|
frontend = ROOT / "frontend-modern/src/components/Settings"
|
|
for label, panel in (
|
|
("Check saved roles", "RolesPanel.tsx"),
|
|
("Check saved access", "UserAssignmentsPanel.tsx"),
|
|
):
|
|
with self.subTest(label=label):
|
|
self.assertIn(label, readable)
|
|
source = (frontend / panel).read_text()
|
|
# Match the documented control, not inline callback syntax.
|
|
# The panels' transport tests exercise the read and no-replay
|
|
# boundary, including named keyboard-recovery handlers.
|
|
self.assertRegex(source, rf"actionLabel=\{{[^}}]*'{re.escape(label)}'\}}")
|
|
for boundary in (
|
|
"after Pulse has saved a role or removed access",
|
|
"Do not repeat the Save or Delete",
|
|
"working administrator session open",
|
|
"identity and complete role list",
|
|
"do not repeat the change",
|
|
"access remains unknown, not empty or unchanged",
|
|
"Do not grant broader roles, widen a token or disable authentication",
|
|
"not that the intended user's access works",
|
|
"#automatic-role-assignment-via-oidc",
|
|
"does not disable the upstream identity-provider account",
|
|
"tokens, cookies and full responses private",
|
|
):
|
|
with self.subTest(boundary=boundary):
|
|
self.assertIn(boundary, readable)
|
|
self.assertIn("#a-role-or-user-change-could-not-be-confirmed", guide)
|
|
self.assertNotIn("```", section, "recovery must not introduce a mutation recipe")
|
|
|
|
def test_all_recipes_send_exact_methods_paths_and_bodies_with_each_header(self):
|
|
with recording_server() as (port, requests):
|
|
for name, operations in EXPECTED.items():
|
|
steps = recipes(name)
|
|
self.assertEqual(len(steps), len(operations))
|
|
for key, value in (("X-API-Token", TEST_TOKEN), ("Authorization", "Bearer " + TEST_TOKEN)):
|
|
for step, (method, path, body) in zip(steps, operations):
|
|
with self.subTest(guide=name, method=method, path=path, header=key), tempfile.TemporaryDirectory(prefix="admin docs ") as temporary:
|
|
before = len(requests)
|
|
result = exercise_curl(self, Path(temporary), f"{key}: {value}", port, executable_recipe(name, step))
|
|
self.assertEqual(result.returncode, 0, result.stderr.decode())
|
|
self.assertEqual(len(requests), before + 1, "a copied step sends exactly one request")
|
|
sent_path, headers, sent_method, sent_body = requests[-1]
|
|
self.assertEqual((sent_method, sent_path), (method, path))
|
|
self.assertEqual(headers[key], value)
|
|
self.assertNotIn("X-Curlrc-Injected", headers)
|
|
self.assertNotIn("Authorization" if key == "X-API-Token" else "X-API-Token", 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_every_recipe_surfaces_auth_and_license_errors_without_next_steps(self):
|
|
for status in (401, 402, 403):
|
|
with recording_server(status) as (port, requests):
|
|
for name in GUIDES:
|
|
for step in recipes(name):
|
|
with self.subTest(status=status, guide=name), tempfile.TemporaryDirectory() as temporary:
|
|
before = len(requests)
|
|
result = exercise_curl(self, Path(temporary), f"X-API-Token: {TEST_TOKEN}", port, executable_recipe(name, step))
|
|
self.assertEqual(result.returncode, 22, result.stderr.decode())
|
|
self.assertEqual(len(requests), before + 1)
|
|
self.assertNotIn(b"Saved private export", result.stdout)
|
|
# Every guide preserves the error in a private response file.
|
|
responses = list((Path(temporary) / ".config/pulse").glob("api-response.*"))
|
|
self.assertEqual(len(responses), 1)
|
|
output = responses[0].read_bytes()
|
|
self.assertNotIn(b'{"fixture":true}', result.stdout)
|
|
self.assertIn(b'{"fixture":true}', output)
|
|
|
|
def test_audit_reads_keep_private_success_bodies_in_new_owner_only_files(self):
|
|
self.assertEqual(len(recipes("AUDIT_LOGGING")), len(EXPECTED["AUDIT_LOGGING"]))
|
|
with private_recording_server() as (port, requests), tempfile.TemporaryDirectory() as temporary:
|
|
home = Path(temporary)
|
|
for header in (f"X-API-Token: {TEST_TOKEN}", f"Authorization: Bearer {TEST_TOKEN}"):
|
|
for step, (method, path, _) in zip(recipes("AUDIT_LOGGING"), EXPECTED["AUDIT_LOGGING"]):
|
|
with self.subTest(path=path, header=header.split(":")[0]):
|
|
before = len(requests)
|
|
result = exercise_curl(self, home, header, port,
|
|
executable_recipe("AUDIT_LOGGING", step), private_response=True)
|
|
self.assertEqual(result.returncode, 0, result.stderr.decode())
|
|
self.assertEqual(len(requests), before + 1)
|
|
self.assertEqual((requests[-1][2], requests[-1][0]), (method, path))
|
|
self.assertIn(b"HTTP 200", result.stdout)
|
|
# One already-retained response plus ten distinct new responses.
|
|
self.assertEqual(len(list((home / ".config/pulse").glob("api-response.*"))), 11)
|
|
|
|
def test_audit_reads_keep_private_http_error_bodies_and_fail(self):
|
|
self.assertEqual(len(recipes("AUDIT_LOGGING")), len(EXPECTED["AUDIT_LOGGING"]))
|
|
for status in (400, 401, 402, 403, 500, 503):
|
|
with private_recording_server(status) as (port, requests):
|
|
for step in recipes("AUDIT_LOGGING"):
|
|
with self.subTest(status=status, step=step), tempfile.TemporaryDirectory() as temporary:
|
|
before = len(requests)
|
|
result = exercise_curl(self, Path(temporary), f"X-API-Token: {TEST_TOKEN}", port,
|
|
executable_recipe("AUDIT_LOGGING", step), private_response=True)
|
|
self.assertEqual(result.returncode, 22, result.stderr.decode())
|
|
self.assertEqual(len(requests), before + 1)
|
|
self.assertIn(f"HTTP {status}".encode(), result.stdout)
|
|
|
|
def test_audit_reads_refuse_redirect_success_and_incomplete_transfers(self):
|
|
self.assertEqual(len(recipes("AUDIT_LOGGING")), len(EXPECTED["AUDIT_LOGGING"]))
|
|
for status, partial, expected_exit in ((302, False, 1), (200, True, 18)):
|
|
with private_recording_server(status, partial) as (port, requests):
|
|
for step in recipes("AUDIT_LOGGING"):
|
|
with self.subTest(status=status, partial=partial, step=step), tempfile.TemporaryDirectory() as temporary:
|
|
before = len(requests)
|
|
result = exercise_curl(self, Path(temporary), f"X-API-Token: {TEST_TOKEN}", port,
|
|
executable_recipe("AUDIT_LOGGING", step), private_response=True)
|
|
self.assertEqual(result.returncode, expected_exit, result.stderr.decode())
|
|
self.assertEqual(len(requests), before + 1, "must not follow redirects or retry partial reads")
|
|
|
|
def test_rbac_guidance_preserves_private_and_uncertain_change_boundaries(self):
|
|
guide = (DOCS / "RBAC.md").read_text()
|
|
before_api = guide.split("### Before Using the API", 1)[1].split("\n### ", 1)[0]
|
|
readable = " ".join(before_api.replace("**", "").split())
|
|
for boundary in ("in the same Bash session", "not an installed Pulse command",
|
|
"owner-only file", "redacted", "five-second", "twenty-second"):
|
|
self.assertIn(boundary, readable)
|
|
caution = next(p for p in before_api.split("\n\n") if p.startswith("**Run one operation"))
|
|
readable = " ".join(caution.replace("**", "").split())
|
|
for boundary in (
|
|
"Run one operation at a time.", "Keep admin recovery access.",
|
|
"Role deletion can remove grants or lift deny rules.",
|
|
"Check assignments in Users first.",
|
|
"Removing a user or clearing their role list clears assignments.",
|
|
"won't follow redirects or retry",
|
|
"A timeout or partial reply can follow a saved change.",
|
|
"Check saved roles and intended access before another write.",
|
|
"HTTP success neither proves access nor disables IdP accounts.",
|
|
):
|
|
with self.subTest(boundary=boundary):
|
|
self.assertIn(boundary, readable)
|
|
|
|
def test_role_replacement_guidance_preserves_the_current_policy(self):
|
|
guide = (DOCS / "RBAC.md").read_text()
|
|
readable = " ".join(guide.replace("**", "").split())
|
|
for boundary in (
|
|
"Role PUT replaces the complete policy",
|
|
"existing role from `GET /api/admin/roles`",
|
|
"exact ID, `parentId`, `priority`",
|
|
"each permission's `effect` and `conditions`",
|
|
"Missing `effect` means `allow`, not “keep deny”",
|
|
"lowercase `allow` or `deny`",
|
|
"Stop on failed reads or missing/null `permissions`",
|
|
"Coordinate writers",
|
|
"Re-read the list after saving, not just the write response",
|
|
"examples use the new `alert-manager`",
|
|
):
|
|
with self.subTest(boundary=boundary):
|
|
self.assertIn(boundary, readable)
|
|
update = guide.split("### Updating a Role\n", 1)[1].split("### Deleting a Role\n", 1)[0]
|
|
self.assertIn("**Full replacement.** [Preserve saved fields](#before-using-the-api).", update)
|
|
|
|
# The live tenant store, not the legacy file manager, owns this policy.
|
|
provider = (ROOT / "internal/api/access_tenant_provider.go").read_text()
|
|
self.assertIn("auth.NewSQLiteManager(auth.SQLiteManagerConfig{", provider)
|
|
handler = (ROOT / "internal/api/access_control_handlers.go").read_text()
|
|
put = handler.split("case http.MethodPut:", 1)[1].split("case http.MethodDelete:", 1)[0]
|
|
self.assertIn("var role auth.Role", put)
|
|
self.assertIn("role.ID = roleID", put)
|
|
self.assertIn("manager.SaveRole(role)", put)
|
|
store = (ROOT / "pkg/auth/sqlite_manager.go").read_text()
|
|
save = store.split("func (m *SQLiteManager) SaveRoleWithContext(", 1)[1].split("func (m *SQLiteManager) getRoleUnsafe(", 1)[0]
|
|
for field in ("name", "description", "parent_id", "priority"):
|
|
self.assertIn(f"{field} = excluded.{field}", save)
|
|
self.assertIn('DELETE FROM rbac_permissions WHERE role_id = ?', save)
|
|
self.assertIn("effect := perm.GetEffect()", save)
|
|
self.assertIn("json.Marshal(perm.Conditions)", save)
|
|
role = (ROOT / "pkg/auth/rbac.go").read_text()
|
|
self.assertIn('if p.Effect == "" {\n\t\treturn EffectAllow', role)
|
|
evaluator = (ROOT / "pkg/auth/policy_evaluator.go").read_text()
|
|
self.assertIn("if len(perm.Conditions) == 0 {\n\t\treturn true", evaluator)
|
|
|
|
def test_rbac_operations_keep_private_success_bodies_in_new_owner_only_files(self):
|
|
steps = recipes("RBAC")
|
|
self.assertEqual(len(steps), len(EXPECTED["RBAC"]))
|
|
with private_recording_server() as (port, requests), tempfile.TemporaryDirectory(prefix="rbac docs ") as temporary:
|
|
home = Path(temporary)
|
|
for header in (f"X-API-Token: {TEST_TOKEN}", f"Authorization: Bearer {TEST_TOKEN}"):
|
|
for step, (method, path, _) in zip(steps, EXPECTED["RBAC"]):
|
|
with self.subTest(method=method, path=path, header=header.split(":")[0]):
|
|
before = len(requests)
|
|
result = exercise_curl(self, home, header, port,
|
|
executable_recipe("RBAC", step), private_response=True)
|
|
self.assertEqual(result.returncode, 0, result.stderr.decode())
|
|
self.assertEqual(len(requests), before + 1)
|
|
self.assertEqual((requests[-1][2], requests[-1][0]), (method, path))
|
|
self.assertIn(b"HTTP 200", result.stdout)
|
|
self.assertEqual(len(list((home / ".config/pulse").glob("api-response.*"))), 17)
|
|
|
|
def test_rbac_operations_keep_private_http_errors_and_fail_without_retry(self):
|
|
for status in (400, 401, 402, 403, 500, 503):
|
|
with private_recording_server(status) as (port, requests):
|
|
for step in recipes("RBAC"):
|
|
with self.subTest(status=status, step=step), tempfile.TemporaryDirectory() as temporary:
|
|
before = len(requests)
|
|
result = exercise_curl(self, Path(temporary), f"X-API-Token: {TEST_TOKEN}", port,
|
|
executable_recipe("RBAC", step), private_response=True)
|
|
self.assertEqual(result.returncode, 22, result.stderr.decode())
|
|
self.assertEqual(len(requests), before + 1)
|
|
self.assertIn(f"HTTP {status}".encode(), result.stdout)
|
|
|
|
def test_rbac_operations_refuse_redirect_success_and_uncertain_transfer_retry(self):
|
|
for status, partial, expected_exit in ((302, False, 1), (200, True, 18)):
|
|
with private_recording_server(status, partial) as (port, requests):
|
|
for step in recipes("RBAC"):
|
|
with self.subTest(status=status, partial=partial, step=step), tempfile.TemporaryDirectory() as temporary:
|
|
before = len(requests)
|
|
result = exercise_curl(self, Path(temporary), f"X-API-Token: {TEST_TOKEN}", port,
|
|
executable_recipe("RBAC", step), private_response=True)
|
|
self.assertEqual(result.returncode, expected_exit, result.stderr.decode())
|
|
self.assertEqual(len(requests), before + 1, "an uncertain mutation must not be repeated or redirected")
|
|
|
|
def test_org_feature_flag_setup_uses_the_installed_deployment(self):
|
|
guide = (DOCS / "MULTI_TENANT.md").read_text()
|
|
quick_start = guide.split("## Quick Start\n", 1)[1].split("## Concepts", 1)[0]
|
|
flag_error = guide.split('### "Multi-tenant functionality', 1)[1].split("\n### ", 1)[0]
|
|
for entry in (quick_start, flag_error):
|
|
self.assertIn("#applying-the-feature-flag", entry)
|
|
self.assertNotIn("in your environment and restart Pulse", entry)
|
|
setup = guide.split("## Applying the feature flag\n", 1)[1].split("\n## ", 1)[0]
|
|
readable = " ".join(setup.replace("**", "").split())
|
|
for boundary in (
|
|
"existing deployment's environment configuration", "Docker or Compose",
|
|
"A restart alone does not apply a changed container environment.",
|
|
"same pinned image, persistent data mount, credentials and other settings",
|
|
"systemd", "unit or drop-in changed", "Kubernetes", "existing workload controller",
|
|
"not its agents", "monitoring and alerts are unavailable",
|
|
"working administrator recovery path", "not a licence or membership grant",
|
|
):
|
|
with self.subTest(boundary=boundary):
|
|
self.assertIn(boundary, readable)
|
|
self.assertIn("DEPLOYMENT_MODELS.md#updates-by-model", setup)
|
|
self.assertIn("CONFIGURATION.md#common-overrides-environment-variables", setup)
|
|
self.assertNotIn("```", setup, "do not add an unqualified deployment mutation command")
|
|
|
|
def test_org_guidance_preserves_private_bounded_reads_and_session_mutations(self):
|
|
guide = (DOCS / "MULTI_TENANT.md").read_text()
|
|
for boundary in ("in the same Bash session", "not an installed Pulse command",
|
|
"five-second", "twenty-second", "does not follow redirects or retry",
|
|
"owner-only file", "redacted", "partial file", "not a complete list",
|
|
"HTTP 401/402/403", "do not", "widen a token",
|
|
"mutations token-authenticated", "signed-in UI", "CSRF"):
|
|
self.assertIn(boundary, guide)
|
|
for step in recipes("MULTI_TENANT"):
|
|
self.assertRegex(step, r"^pulse_api GET /api/orgs/")
|
|
self.assertNotIn("curl ", step)
|
|
|
|
def test_org_reads_keep_private_success_bodies_in_new_owner_only_files(self):
|
|
steps = recipes("MULTI_TENANT")
|
|
self.assertEqual(len(steps), len(EXPECTED["MULTI_TENANT"]))
|
|
with private_recording_server() as (port, requests), tempfile.TemporaryDirectory(prefix="org docs ") as temporary:
|
|
home = Path(temporary)
|
|
for header in (f"X-API-Token: {TEST_TOKEN}", f"Authorization: Bearer {TEST_TOKEN}"):
|
|
for step, (method, path, _) in zip(steps, EXPECTED["MULTI_TENANT"]):
|
|
with self.subTest(path=path, header=header.split(":")[0]):
|
|
before = len(requests)
|
|
result = exercise_curl(self, home, header, port,
|
|
executable_recipe("MULTI_TENANT", step), private_response=True)
|
|
self.assertEqual(result.returncode, 0, result.stderr.decode())
|
|
self.assertEqual(len(requests), before + 1)
|
|
self.assertEqual((requests[-1][2], requests[-1][0]), (method, path))
|
|
self.assertEqual(requests[-1][3], b"", "organization reads send no mutation body")
|
|
self.assertIn(b"HTTP 200", result.stdout)
|
|
# Four reads retain four new files without overwriting the old response.
|
|
self.assertEqual(len(list((home / ".config/pulse").glob("api-response.*"))), 5)
|
|
|
|
def test_org_reads_keep_private_http_errors_and_fail_without_retry(self):
|
|
for status in (400, 401, 402, 403, 500, 503):
|
|
with private_recording_server(status) as (port, requests):
|
|
for step in recipes("MULTI_TENANT"):
|
|
with self.subTest(status=status, step=step), tempfile.TemporaryDirectory() as temporary:
|
|
before = len(requests)
|
|
result = exercise_curl(self, Path(temporary), f"X-API-Token: {TEST_TOKEN}", port,
|
|
executable_recipe("MULTI_TENANT", step), private_response=True)
|
|
self.assertEqual(result.returncode, 22, result.stderr.decode())
|
|
self.assertEqual(len(requests), before + 1)
|
|
self.assertIn(f"HTTP {status}".encode(), result.stdout)
|
|
|
|
def test_org_reads_refuse_redirect_success_and_incomplete_transfer_retry(self):
|
|
for status, partial, expected_exit in ((302, False, 1), (200, True, 18)):
|
|
with private_recording_server(status, partial) as (port, requests):
|
|
for step in recipes("MULTI_TENANT"):
|
|
with self.subTest(status=status, partial=partial, step=step), tempfile.TemporaryDirectory() as temporary:
|
|
before = len(requests)
|
|
result = exercise_curl(self, Path(temporary), f"X-API-Token: {TEST_TOKEN}", port,
|
|
executable_recipe("MULTI_TENANT", step), private_response=True)
|
|
self.assertEqual(result.returncode, expected_exit, result.stderr.decode())
|
|
self.assertEqual(len(requests), before + 1, "do not follow redirects or retry partial reads")
|
|
|
|
|
|
def test_plans_and_rbac_editor_permissions_match_shipped_settings_ui(self):
|
|
nav = (ROOT / "frontend-modern/src/components/Settings/settingsNavCatalog.ts").read_text()
|
|
system_group = nav.split("id: 'system',", 1)[1].split("id: 'support',", 1)[0]
|
|
self.assertIn("id: 'system-billing'", system_group)
|
|
messages = (ROOT / "frontend-modern/src/i18n/messages.ts").read_text()
|
|
self.assertIn("'settings.nav.group.system': 'System'", messages)
|
|
self.assertIn("'settings.nav.item.plans': 'Plans & Billing'", messages)
|
|
for name in ("RBAC.md", "MULTI_TENANT.md"):
|
|
with self.subTest(guide=name):
|
|
guide = (DOCS / name).read_text()
|
|
self.assertIn("**Settings → System → Plans & Billing**", guide)
|
|
self.assertNotIn("**Settings → Plans & Billing**", guide)
|
|
|
|
rbac_perms = (ROOT / "frontend-modern/src/utils/rbacPermissions.ts").read_text()
|
|
actions = re.findall(r"'([^']+)'", rbac_perms.split("RBAC_PERMISSION_ACTIONS = [", 1)[1].split("]", 1)[0])
|
|
resources = re.findall(r"'([^']+)'", rbac_perms.split("RBAC_PERMISSION_RESOURCES = [", 1)[1].split("]", 1)[0])
|
|
self.assertGreaterEqual(len(actions), 5)
|
|
self.assertGreaterEqual(len(resources), 6)
|
|
rbac = (DOCS / "RBAC.md").read_text()
|
|
for action in actions:
|
|
with self.subTest(action=action):
|
|
self.assertIn(f"`{action}`", rbac)
|
|
for resource in resources:
|
|
with self.subTest(resource=resource):
|
|
self.assertIn(f"`{resource}`", rbac)
|
|
|
|
def test_multi_tenant_help_documents_org_deletion_token_revocation_and_cold_monitor_isolation(self):
|
|
org_doc = " ".join((DOCS / "MULTI_TENANT.md").read_text(encoding="utf-8").split())
|
|
for phrase in (
|
|
"Deleting an organization revokes API tokens bound to that organization ID before removing its data.",
|
|
"Creating an organization also clears any stale credentials left bound to that ID, so old tokens cannot carry over if an ID is reused.",
|
|
"A request without an explicit API token does not resolve or start a cold non-default organization monitor merely by sending `X-Pulse-Org-ID` or a session cookie.",
|
|
):
|
|
with self.subTest(phrase=phrase):
|
|
self.assertIn(phrase, org_doc)
|
|
|
|
org_handlers = (ROOT / "internal/api/org_handlers.go").read_text(encoding="utf-8")
|
|
self.assertIn("func (h *OrgHandlers) SetCredentialRevoker(callback func(orgID string) error)", org_handlers)
|
|
self.assertIn("if err := h.revokeCredentials(req.ID); err != nil {", org_handlers)
|
|
self.assertIn("if err := h.revokeCredentials(orgID); err != nil {", org_handlers)
|
|
auth_go = (ROOT / "internal/api/auth.go").read_text(encoding="utf-8")
|
|
self.assertIn("if mtm != nil && explicitTokenProvided {", auth_go)
|
|
|
|
def test_multi_tenant_audit_and_webhooks_help_match_tenant_context_and_default_org_policy(self):
|
|
org_doc = " ".join((DOCS / "MULTI_TENANT.md").read_text(encoding="utf-8").split())
|
|
audit_doc = " ".join((DOCS / "AUDIT_LOGGING.md").read_text(encoding="utf-8").split())
|
|
webhooks_doc = " ".join((DOCS / "WEBHOOKS.md").read_text(encoding="utf-8").split())
|
|
|
|
for phrase in (
|
|
"Default-organization membership:",
|
|
"POST /api/orgs/default/members",
|
|
"DELETE /api/orgs/default/members/{userId}",
|
|
"assigns only the `viewer` organization role",
|
|
"HTTP `400` (`invalid_role`)",
|
|
"`default-org-access-migration.json`",
|
|
"`migration:default-org-access`",
|
|
"Proxy-authenticated users have no stored RBAC assignment to migrate from",
|
|
"Active WebSocket and SSE streams re-check organization access every 10 seconds",
|
|
"`GET` | `/api/orgs/{id}/invitations`",
|
|
"`DELETE` | `/api/orgs/{id}/invitations/{userId}`",
|
|
"`GET` | `/api/org-invitations`",
|
|
"`DELETE` | `/api/org-invitations/{id}`",
|
|
"`DELETE` | `/api/orgs/{id}/shares/incoming/{shareId}`",
|
|
"`pulse_org_id` browser cookie",
|
|
"Single-organization-bound API token",
|
|
"Signed-in user's landing organization",
|
|
"`default_org_access_denied`",
|
|
"Organization-neutral bootstrap routes",
|
|
"`/api/security/status`, `/api/logout`, `/api/health`, `GET /api/orgs`, `/api/org-invitations`, `/api/org-invitations/*`",
|
|
"excluding `/ws`, `/simple-stats`, and `/debug`",
|
|
):
|
|
with self.subTest(doc="MULTI_TENANT.md", phrase=phrase):
|
|
self.assertIn(phrase, org_doc)
|
|
self.assertNotIn("Default-organization members cannot be managed here.", org_doc)
|
|
|
|
for phrase in (
|
|
"the `pulse_org_id` browser cookie",
|
|
"a single-organization-bound API token",
|
|
"a signed-in user's landing organization before falling back to `default`",
|
|
"Selection never overrides membership or a token's organization binding.",
|
|
):
|
|
with self.subTest(doc="AUDIT_LOGGING.md", phrase=phrase):
|
|
self.assertIn(phrase, audit_doc)
|
|
|
|
self.assertIn("`403 default_org_access_denied`", webhooks_doc)
|
|
|
|
for name in ("MULTI_TENANT.md", "AUDIT_LOGGING.md", "WEBHOOKS.md"):
|
|
with self.subTest(mirror=name):
|
|
self.assertEqual(
|
|
(DOCS / name).read_bytes(),
|
|
(ROOT / "frontend-modern/public/docs" / name).read_bytes(),
|
|
)
|
|
|
|
tenant_mw = (ROOT / "internal/api/middleware_tenant.go").read_text(encoding="utf-8")
|
|
for marker in (
|
|
'orgID = strings.TrimSpace(r.Header.Get("X-Pulse-Org-ID"))',
|
|
"if cookie, err := r.Cookie(CookieNameOrgID); err == nil {",
|
|
"else if len(t.OrgIDs) == 1 && strings.TrimSpace(t.OrgIDs[0]) != \"\" {",
|
|
"if landing := policy.LandingOrgID(r.Context(), userID); landing != \"\" {",
|
|
'code = "default_org_access_denied"',
|
|
"if !result.Allowed && policy != nil && orgID == \"default\" && token == nil && orgNeutralBootstrapRequest(r) {",
|
|
):
|
|
self.assertIn(marker, tenant_mw)
|
|
|
|
org_policy = (ROOT / "internal/api/org_access_policy.go").read_text(encoding="utf-8")
|
|
for marker in (
|
|
"var orgAccessRecheckInterval = 10 * time.Second",
|
|
'case "/api/security/status", "/api/logout", "/api/health":',
|
|
'case "/ws", "/simple-stats":',
|
|
'const defaultOrgAccessMigrationFile = "default-org-access-migration.json"',
|
|
'const defaultOrgAccessMigrationActor = "migration:default-org-access"',
|
|
):
|
|
self.assertIn(marker, org_policy)
|
|
|
|
org_handlers = (ROOT / "internal/api/org_handlers.go").read_text(encoding="utf-8")
|
|
for marker in (
|
|
"func (h *OrgHandlers) handleAddDefaultOrgMember(",
|
|
"func (h *OrgHandlers) handleRemoveDefaultOrgMember(",
|
|
'writeErrorResponse(w, http.StatusBadRequest, "invalid_role", "Default organization members are viewers; instance roles control what they can do", nil)',
|
|
):
|
|
self.assertIn(marker, org_handlers)
|
|
|
|
routes = (ROOT / "internal/api/router_routes_licensing.go").read_text(encoding="utf-8")
|
|
for marker in (
|
|
'r.mux.HandleFunc("GET /api/orgs/{id}/invitations"',
|
|
'r.mux.HandleFunc("DELETE /api/orgs/{id}/invitations/{userId}"',
|
|
'r.mux.HandleFunc("GET /api/org-invitations"',
|
|
'r.mux.HandleFunc("DELETE /api/org-invitations/{id}"',
|
|
'r.mux.HandleFunc("DELETE /api/orgs/{id}/shares/incoming/{shareId}"',
|
|
):
|
|
self.assertIn(marker, routes)
|
|
|
|
def test_api_doc_security_status_rbac_and_org_contracts_match_source(self):
|
|
api_doc = " ".join((DOCS / "API.md").read_text(encoding="utf-8").split())
|
|
for phrase in (
|
|
"three tiered `detailLevel` views",
|
|
"`public` (unauthenticated)",
|
|
"`Authorization: Bearer` and query-string tokens are intentionally ignored here",
|
|
"`authenticated` (signed-in non-admin",
|
|
"`privileged` (admin with `settings:read`)",
|
|
"`GET /api/security/tokens/<id>` (admin, `settings:read`)",
|
|
"`POST /api/security/apply-restart`",
|
|
"requires a valid bootstrap token in `X-Setup-Token`",
|
|
"full-access (`*`) scope not bound to a non-default organization",
|
|
"`GET /api/admin/rbac/integrity`",
|
|
"`POST /api/admin/rbac/reset-admin`",
|
|
"OIDC and SAML group-to-role mapping",
|
|
"`POST /api/orgs/default/members`",
|
|
"assigns only the `viewer` organization role",
|
|
"`DELETE /api/orgs/default/members/{userId}`",
|
|
"`GET /api/orgs/{id}/invitations`",
|
|
"`DELETE /api/orgs/{id}/invitations/{userId}`",
|
|
"`GET /api/org-invitations`",
|
|
"`POST /api/org-invitations/{id}/accept`",
|
|
"`DELETE /api/org-invitations/{id}`",
|
|
"`POST /api/orgs/{id}/shares/incoming/{shareId}/accept`",
|
|
"`DELETE /api/orgs/{id}/shares/incoming/{shareId}`",
|
|
):
|
|
with self.subTest(doc="API.md", phrase=phrase):
|
|
self.assertIn(phrase, api_doc)
|
|
self.assertNotIn("Default org members cannot be managed.", api_doc)
|
|
self.assertEqual(
|
|
(DOCS / "API.md").read_bytes(),
|
|
(ROOT / "frontend-modern/public/docs/API.md").read_bytes(),
|
|
)
|
|
|
|
auth_routes = (ROOT / "internal/api/router_routes_auth_security.go").read_text(encoding="utf-8")
|
|
for marker in (
|
|
'securityStatusDetailPublic = "public"',
|
|
'securityStatusDetailAuthenticated = "authenticated"',
|
|
'securityStatusDetailPrivileged = "privileged"',
|
|
"Bearer and query-string tokens are intentionally not accepted here",
|
|
"r.handleGetAPIToken(w, req)",
|
|
"func (r *Router) authorizeSecurityRestart(",
|
|
"bootstrapTokenHeader",
|
|
):
|
|
self.assertIn(marker, auth_routes)
|
|
|
|
licensing_routes = (ROOT / "internal/api/router_routes_licensing.go").read_text(encoding="utf-8")
|
|
for marker in (
|
|
'r.mux.HandleFunc("GET /api/admin/rbac/integrity"',
|
|
'r.mux.HandleFunc("POST /api/admin/rbac/reset-admin"',
|
|
"RequireScope(config.ScopeWildcard, rbacHandlers.HandleRoles)",
|
|
"RequireScope(config.ScopeWildcard, rbacHandlers.HandleGetUsers)",
|
|
"RequireScope(config.ScopeWildcard, rbacHandlers.HandleUserRoleActions)",
|
|
"RequireScope(config.ScopeWildcard, rbacAdminEndpoints.HandleIntegrityCheck)",
|
|
"RequireScope(config.ScopeWildcard, rbacAdminEndpoints.HandleAdminReset)",
|
|
):
|
|
self.assertIn(marker, licensing_routes)
|
|
|
|
def test_webhooks_and_audit_docs_match_org_bound_token_refusal_and_routes(self):
|
|
webhooks_doc = " ".join((DOCS / "WEBHOOKS.md").read_text(encoding="utf-8").split())
|
|
audit_doc = " ".join((DOCS / "AUDIT_LOGGING.md").read_text(encoding="utf-8").split())
|
|
|
|
for phrase in (
|
|
"Pro, legacy Pro+, Cloud, MSP, and Enterprise/custom licenses",
|
|
"Sign in as an instance administrator (not a non-instance organization owner or admin)",
|
|
"API tokens bound to a non-default organisation are refused with HTTP `403`",
|
|
"`/api/notifications/*` refuses API tokens bound to a non-default organisation with HTTP `403`",
|
|
"**instance-wide** (non-org-bound) token with `settings:write` paired with `X-Pulse-Org-ID: <orgID>`",
|
|
"non-default org-bound tokens receive `403`",
|
|
"instance-wide token with `settings:read` or `settings:write`",
|
|
):
|
|
with self.subTest(doc="WEBHOOKS.md", phrase=phrase):
|
|
self.assertIn(phrase, webhooks_doc)
|
|
self.assertNotIn(
|
|
"Programmatic creation needs an organisation-bound token with `settings:write`",
|
|
webhooks_doc,
|
|
)
|
|
|
|
for phrase in (
|
|
"Pro, legacy Pro+, Cloud, MSP, or Enterprise/custom license with the `audit_logging` capability",
|
|
"Use an **instance-wide** (non-org-bound) API token with `audit:read`",
|
|
"Every `/api/audit*` endpoint enforces instance-administrator authority and refuses API tokens bound to a non-default organization with HTTP `403`",
|
|
"`GET /api/audit/actions`",
|
|
"`GET /api/audit/actions/{id}/events`",
|
|
"`GET /api/audit/exports`",
|
|
"Pro / legacy Pro+ / Cloud / MSP / Enterprise",
|
|
):
|
|
with self.subTest(doc="AUDIT_LOGGING.md", phrase=phrase):
|
|
self.assertIn(phrase, audit_doc)
|
|
|
|
for name in ("WEBHOOKS.md", "AUDIT_LOGGING.md"):
|
|
with self.subTest(mirror=name):
|
|
self.assertEqual(
|
|
(DOCS / name).read_bytes(),
|
|
(ROOT / "frontend-modern/public/docs" / name).read_bytes(),
|
|
)
|
|
|
|
monitoring_routes = (ROOT / "internal/api/router_routes_monitoring.go").read_text(encoding="utf-8")
|
|
self.assertIn(
|
|
'r.mux.HandleFunc("/api/notifications/", RequireOrgManager(r.config, r.notificationHandlers.HandleNotifications))',
|
|
monitoring_routes,
|
|
)
|
|
security_fix = (ROOT / "internal/api/security_setup_fix.go").read_text(encoding="utf-8")
|
|
for marker in (
|
|
"func ensureOrgManagerSession(",
|
|
"func ensureAdminSession(",
|
|
"refuseOrgBoundToken(w, req, record)",
|
|
):
|
|
self.assertIn(marker, security_fix)
|
|
|
|
licensing_routes = (ROOT / "internal/api/router_routes_licensing.go").read_text(encoding="utf-8")
|
|
for marker in (
|
|
'r.mux.HandleFunc("GET /api/audit/actions"',
|
|
'r.mux.HandleFunc("GET /api/audit/actions/{id}/events"',
|
|
'r.mux.HandleFunc("GET /api/audit/exports"',
|
|
'r.mux.HandleFunc("/api/admin/webhooks/audit"',
|
|
"if !ensureAdminSession(r.config, w, req) {",
|
|
):
|
|
self.assertIn(marker, licensing_routes)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|