railiance-platform/tests/test_operator_matrix_lane.py
codex 857be4695f
All checks were successful
CI Smoke / host-smoke (push) Successful in 0s
CI Smoke / container-smoke (push) Successful in 1s
RPF-WP-0054-T04: create-only broker grant keycape/client-secret-generate
- New CCR request type custody-generate-grant (scripts/broker_grant_lane.py):
  grant policy (create on keycape/+ data, read on metadata, deny on reserved
  entries, revoke-self; no update, data read, metadata write, list or
  delete), broker issuer policy and a 5m orphan non-renewable token role,
  with readback. Binds no identity, so the apply is inert until T01.
- CCR-2026-0040 (proposed), catalog grant (pilot, approval-required,
  exec-env only), generated policies, tests.
- T03 drops custom_metadata: a metadata write would also allow changing
  other entries' version settings.
- test_operator_matrix_lane follows CCR-2026-0039 now being applied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Assistant: claude-code
Assistant-Model: opus
Assistant-Process: 469992@bnt-lap001
Assistant-Session: e4b8e420-df0a-441d-83ae-7f19130594d9
2026-10-09 19:08:25 +02:00

179 lines
8 KiB
Python

"""RPF-WP-0035-T03: workload-kv-operator-matrix lane (CCR-2026-0039)."""
from __future__ import annotations
import copy
import importlib.util
import json
import os
import stat
import sys
import tempfile
import unittest
from pathlib import Path
import yaml
ROOT = Path(__file__).resolve().parents[1]
CCR_PATH = ROOT / "credential-change-requests/CCR-2026-0039-fluid-telegram-hall-of-helix-operator-matrix.yaml"
CAMPAIGN = "platform/data/workloads/coulomb/fluid-telegram/hall-of-helix"
def load(name: str, rel: str):
spec = importlib.util.spec_from_file_location(name, ROOT / rel)
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
return module
lane = load("operator_matrix_lane", "scripts/operator_matrix_lane.py")
cc = load("credential_change_cli_matrix", "scripts/credential-change.py")
def ccr() -> dict:
return yaml.safe_load(CCR_PATH.read_text())
# Stateful fake: policy/role writes are stored and read back; every call is logged.
FAKE_BAO = r'''#!/usr/bin/env python3
import json, os, sys
path = os.environ["FAKE_BAO_STATE"]
state = json.load(open(path))
open(os.environ["FAKE_BAO_LOG"], "a").write(json.dumps(sys.argv[1:]) + "\n")
args = [a for a in sys.argv[1:] if a != "-format=json"]
if args[:2] == ["auth", "list"]:
print(json.dumps({k: {"type": v} for k, v in state["mounts"].items()}))
elif args[:2] == ["policy", "read"]:
if args[2] not in state["policies"]:
sys.exit(2)
print(state["policies"][args[2]])
elif args[:2] == ["policy", "write"]:
state["policies"][args[2]] = open(args[3]).read()
elif args[0] == "write":
state["roles"][args[1]] = json.load(open(args[2][1:]))
elif args[0] == "read":
print(json.dumps({"data": state["roles"][args[1]]}))
json.dump(state, open(path, "w"))
'''
LIVE_BOUNDARY = 'path "platform/data/workloads/forgejo/forgejo-admin" {\n capabilities = ["deny"]\n}\n'
class OperatorMatrixLaneTests(unittest.TestCase):
def test_ccr_validates_and_records_the_delegated_apply(self):
_ccr, errors, _w = cc.validate_ccr(CCR_PATH)
self.assertEqual(errors, [])
self.assertEqual(_ccr["status"], "applied")
self.assertEqual(cc.applier_readiness_blockers(_ccr), [])
self.assertTrue(any(e["kind"] == "delegated_metadata_apply" and e["result"] == "passed"
for e in _ccr["verification"]["evidence"]))
def test_unconfirmed_binding_blocks_the_applier(self):
c = ccr()
c["openbao"]["auth"]["bound_claims_confirmed"] = False
self.assertIn("applier requires confirmed OpenBao auth binding",
cc.applier_readiness_blockers(c))
def test_policy_is_the_exact_matrix_and_nothing_else(self):
policy = (ROOT / ccr()["openbao"]["policy_file"]).read_text()
self.assertNotIn("metadata", policy.split("\n", 1)[1])
self.assertNotIn("*", policy)
for word in ("delete", "list", "patch", "sudo"):
self.assertNotIn(f'"{word}"', policy)
self.assertIn(f'path "{CAMPAIGN}/redaction-salt" {{\n capabilities = ["create", "read"]', policy)
self.assertIn(f'path "{CAMPAIGN}/operator-app" {{\n capabilities = ["read"]', policy)
def test_repo_boundary_carries_all_eight_agent_denies(self):
text = (ROOT / lane.BOUNDARY_FILE).read_text()
self.assertEqual(lane.boundary_presence(ccr(), text), (8, 8))
def test_validator_rejects_widening(self):
cases = [
("wildcard entry", lambda c: c["openbao"]["matrix"][0].update(entry="*")),
("unknown capability", lambda c: c["openbao"]["matrix"][0]["capabilities"].append("delete")),
("no read", lambda c: c["openbao"]["matrix"][3].update(capabilities=["create"])),
("duplicate entry", lambda c: c["openbao"]["matrix"].append(copy.deepcopy(c["openbao"]["matrix"][0]))),
("campaign wildcard", lambda c: c["openbao"].update(campaign_path="platform/workloads/coulomb/fluid-telegram/*")),
("other auth mount", lambda c: c["openbao"]["auth"].update(mount="kubernetes")),
]
for label, mutate in cases:
with self.subTest(label):
c = ccr()
mutate(c)
self.assertNotEqual(lane.validate(c, ROOT), [], label)
def test_validator_rejects_bad_role_file(self):
good = json.loads((ROOT / ccr()["openbao"]["auth"]["role_file"]).read_text())
cases = [
("public callback", {"allowed_redirect_uris": ["https://bao.coulomb.social/ui/vault/auth/netkingdom/oidc/callback"]}),
("no aal2", {"bound_claims": {"groups": ["fluid-telegram-operators"]}}),
("two groups", {"bound_claims": {"groups": ["a", "b"], "/assurance/level": "aal2"}}),
("default policy", {"token_no_default_policy": False}),
("long ttl", {"token_ttl": "60m"}),
("long max", {"token_explicit_max_ttl": "2h"}),
("extra key", {"token_period": "15m"}),
]
for label, change in cases:
with self.subTest(label):
with tempfile.TemporaryDirectory(dir=ROOT / "openbao/auth") as tmp:
role_file = Path(tmp) / "role.json"
role_file.write_text(json.dumps({**good, **change}))
c = ccr()
c["openbao"]["auth"]["role_file"] = str(role_file.relative_to(ROOT))
self.assertNotEqual(lane.validate(c, ROOT), [], label)
def _apply(self, boundary: str, mounts: dict | None = None):
tmp = Path(tempfile.mkdtemp())
state = {"mounts": mounts if mounts is not None else {"netkingdom/": "oidc"},
"policies": {lane.BOUNDARY_POLICY: boundary}, "roles": {}}
(tmp / "state.json").write_text(json.dumps(state))
bao = tmp / "bao"
bao.write_text(FAKE_BAO)
bao.chmod(bao.stat().st_mode | stat.S_IEXEC)
os.environ["FAKE_BAO_STATE"] = str(tmp / "state.json")
os.environ["FAKE_BAO_LOG"] = str(tmp / "log")
(tmp / "log").write_text("")
error = None
try:
lane.run_apply(ccr(), ROOT, str(bao), quiet=True)
except lane.BaoError as exc:
error = exc
state = json.loads((tmp / "state.json").read_text())
writes = [json.loads(l) for l in (tmp / "log").read_text().splitlines()
if json.loads(l)[0] == "write" or json.loads(l)[:2] == ["policy", "write"]]
return error, state, writes
def test_apply_appends_denies_preserving_live_boundary_and_reads_back(self):
error, state, writes = self._apply(LIVE_BOUNDARY)
self.assertIsNone(error)
boundary = state["policies"][lane.BOUNDARY_POLICY]
self.assertTrue(boundary.startswith(LIVE_BOUNDARY.rstrip("\n")))
self.assertEqual(lane.boundary_presence(ccr(), boundary), (8, 8))
self.assertEqual([w[:3] for w in writes][:2], [
["policy", "write", lane.BOUNDARY_POLICY],
["policy", "write", "workload-kv-fluid-telegram-hall-of-helix-operator"],
])
self.assertIn("auth/netkingdom/role/fluid-telegram-hall-of-helix-workload-kv", state["roles"])
def test_apply_skips_boundary_when_denies_already_live(self):
overlay = (ROOT / ccr()["openbao"]["boundary_overlay_file"]).read_text()
error, state, writes = self._apply(LIVE_BOUNDARY + overlay)
self.assertIsNone(error)
self.assertNotIn(["policy", "write", lane.BOUNDARY_POLICY], [w[:3] for w in writes])
def test_apply_refuses_partial_boundary_before_any_write(self):
partial = LIVE_BOUNDARY + lane.boundary_stanzas(ccr())[0] + "\n"
error, _state, writes = self._apply(partial)
self.assertIsNotNone(error)
self.assertEqual(writes, [])
def test_apply_refuses_missing_or_foreign_oidc_mount_before_any_write(self):
for mounts in ({}, {"netkingdom/": "jwt"}):
with self.subTest(mounts=mounts):
error, _state, writes = self._apply(LIVE_BOUNDARY, mounts)
self.assertIsNotNone(error)
self.assertEqual(writes, [])
if __name__ == "__main__":
unittest.main()