net-kingdom/tools/contract-tests/tests/test_agent_status_grant.py
tegwick 9c73a5fa09
All checks were successful
Bounded-execution contracts / contracts (push) Successful in 1m20s
CI Smoke / host-smoke (push) Successful in 0s
CI Smoke / container-smoke (push) Successful in 3s
NK-WP-0058-T05: proposal for a read-only agent status grant (not applied), with guard tests
Dedicated ServiceAccount sso/nk-agent-status (SI-14), read-only Jobs/pods/Deployments/ExternalSecrets in
sso, one named ConfigMap in informed-decision and one Argo Application; no Secrets, logs or exec. Options
A-D for the founder decision; tests keep the grant narrow and sso workloads free of literal secrets.

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

Assistant: claude-code
Assistant-Model: opus
Assistant-Process: 943911@bnt-lap001
Assistant-Session: fc322940-1c8e-4bed-ab39-86cec99f23a0
2026-11-06 00:52:35 +01:00

75 lines
3.8 KiB
Python

"""NK-WP-0058-T05: the proposed agent status grant stays read-only and narrow, and what it can read holds no secret.
The grant (docs/proposals/2026-11-06-nk58-t05-agent-status-grant/rbac.yaml) is source only until decided. These
checks keep it from widening by accident, and keep the sso workloads it can read free of literal secret values:
`get` on a pod or Deployment returns its env, so a secret written there would become readable.
"""
from pathlib import Path
import yaml
REPO = Path(__file__).resolve().parents[3]
GRANT = REPO / 'docs/proposals/2026-11-06-nk58-t05-agent-status-grant/rbac.yaml'
READ = {'get', 'list', 'watch'}
NEVER = {'secrets', 'pods/log', 'pods/exec', 'pods/attach', 'pods/portforward', 'serviceaccounts/token'}
ALLOWED = {('sso', 'batch', 'jobs'), ('sso', '', 'pods'), ('sso', 'apps', 'deployments'),
('sso', 'external-secrets.io', 'externalsecrets'), ('informed-decision', '', 'configmaps'),
('argocd', 'argoproj.io', 'applications')}
SECRET_WORDS = {'PASS', 'PASSWORD', 'SECRET', 'TOKEN', 'KEY', 'SEED', 'CREDENTIAL', 'CREDENTIALS'}
NOT_A_VALUE = {'URL', 'URLS', 'ORIGINS', 'SECONDS', 'RETURNS', 'FILE', 'PATH', 'ENABLED'} # what the value is
def secret_named(name):
parts = name.upper().split('_')
return bool(SECRET_WORDS & set(parts)) and parts[-1] not in NOT_A_VALUE
def docs():
return [d for d in yaml.safe_load_all(GRANT.read_text()) if d]
def test_only_namespaced_read_rules_on_the_listed_resources():
kinds = {d['kind'] for d in docs()}
assert kinds == {'ServiceAccount', 'Role', 'RoleBinding'} # nothing cluster-wide
for role in (d for d in docs() if d['kind'] == 'Role'):
ns = role['metadata']['namespace']
for rule in role['rules']:
assert set(rule['verbs']) <= READ, rule
for group in rule['apiGroups']:
for resource in rule['resources']:
assert resource not in NEVER and '*' not in (group, resource)
assert (ns, group, resource) in ALLOWED, (ns, group, resource)
if ns != 'sso':
assert rule.get('resourceNames'), f'{ns}: outside sso the grant names its objects'
def test_bound_only_to_the_dedicated_identity():
sa = next(d for d in docs() if d['kind'] == 'ServiceAccount')
assert sa['metadata'] == {**sa['metadata'], 'name': 'nk-agent-status', 'namespace': 'sso'}
assert sa['automountServiceAccountToken'] is False
for binding in (d for d in docs() if d['kind'] == 'RoleBinding'):
assert binding['subjects'] == [{'kind': 'ServiceAccount', 'name': 'nk-agent-status', 'namespace': 'sso'}]
assert binding['roleRef']['kind'] == 'Role'
def test_sso_workloads_carry_no_literal_secret_values():
"""Values of secret-named env vars in sso workloads are references or file paths, never the secret itself."""
found = []
for path in sorted((REPO / 'sso-mfa/k8s').glob('*/*.yaml')):
for doc in yaml.safe_load_all(path.read_text()):
if not isinstance(doc, dict) or doc.get('metadata', {}).get('namespace') != 'sso':
continue
spec = doc.get('spec') or {}
pod = (spec.get('template') or {}).get('spec') or {}
for container in (pod.get('containers') or []) + (pod.get('initContainers') or []):
for env in container.get('env') or []:
value = env.get('value')
if value is not None and secret_named(env['name']) and not str(value).startswith('/'):
found.append(f"{path.relative_to(REPO)}:{env['name']}")
assert found == [], found
def test_secret_named():
assert secret_named('USER_ENGINE_TENANT_MANAGEMENT_TOKEN') and secret_named('SMTP_PASSWORD')
assert not secret_named('KEYCAPE_ACCOUNT_PORTAL_URL') and not secret_named('PASSWORD_SETUP_TTL_SECONDS')
assert not secret_named('AUTHELIA_JWT_SECRET_FILE')