railiance-platform/scripts/telemetry_grafana_custody.py
codex 92a0f5ed59
All checks were successful
CI Smoke / host-smoke (push) Successful in 0s
CI Smoke / container-smoke (push) Successful in 1s
Establish attended telemetry Grafana custody and record private activation
Assistant: codex
Assistant-Model: gpt-6-astra
Assistant-Session: 01a06ecb-456a-71c2-b41e-0755d336e883
2026-09-06 22:36:09 +02:00

93 lines
5.5 KiB
Python

#!/usr/bin/env python3
"""Silent attended bootstrap of an exact Grafana-admin ESO lane."""
import argparse
import base64
import json
import os
import re
import secrets
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from state_hub_preflight_lane import bao, command, data, assert_cluster, LaneError, capabilities, revoke
from repair_eso_kubernetes_auth import role_payload, check_role, verify_login
k = ['kubectl', '--kubeconfig', '/home/worsch/.kube/config-railiance01']
lane = dict(service_account='telemetry-grafana-eso', namespace='telemetry', role='telemetry-grafana-eso', policy='telemetry-grafana-admin-eso', kv_path='platform/data/workloads/telemetry/grafana-admin')
policy = 'path "' + lane['kv_path'] + '" { capabilities = ["read"] }\npath "auth/token/lookup-self" { capabilities = ["read"] }\npath "auth/token/revoke-self" { capabilities = ["update"] }\n'
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--receipt', required=True)
args = parser.parse_args()
fd = os.open(args.receipt, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
receipt = {'schema': 'rapp-telemetry.custody.v1', 'status': 'failed'}
def absent(r):
return b'404' in r.stderr or b'No value found' in r.stderr
try:
assert_cluster(k)
identity = data(bao(['token', 'lookup', '-format=json']))['data']['policies']
if 'platform-admin' not in identity or 'root' in identity:
raise LaneError('wrong_identity')
boundary_path = 'sys/policies/acl/agent-high-risk-boundary'
current = data(bao(['read', '-format=json', boundary_path]))['data']['policy']
overlay = ''
for path in [lane['kv_path'], lane['kv_path'].replace('/data/', '/metadata/', 1)]:
stanza = 'path "' + path + '" { capabilities = ["deny"] }\n'
if '"' + path + '"' not in current:
overlay += stanza
elif not re.search(r'path\s+"' + re.escape(path) + r'"\s*\{\s*capabilities\s*=\s*\["deny"\]\s*\}', current):
raise LaneError('boundary_path_drift')
if overlay:
if data(bao(['read', '-format=json', boundary_path]))['data']['policy'] != current:
raise LaneError('boundary_drift')
bao(['write', boundary_path, '-'], payload={'policy': current + '\n' + overlay})
if data(bao(['read', '-format=json', boundary_path]))['data']['policy'] != current + '\n' + overlay:
raise LaneError('boundary_readback_failed')
r = bao(['read', '-format=json', lane['kv_path']], allow_failure=True)
if r.returncode:
if not absent(r):
raise LaneError('custody_absence_unproven')
bao(['write', lane['kv_path'], '-'], payload={'options': {'cas': 0}, 'data': {'ADMIN_USERNAME': 'admin', 'ADMIN_PASSWORD': secrets.token_urlsafe(48)}})
native = data(bao(['read', '-format=json', lane['kv_path']]))['data']
if set(native['data']) != {'ADMIN_USERNAME', 'ADMIN_PASSWORD'} or native['data']['ADMIN_USERNAME'] != 'admin' or len(native['data']['ADMIN_PASSWORD']) < 40:
raise LaneError('custody_drift')
for path, payload, checker in [('sys/policies/acl/' + lane['policy'], {'policy': policy}, lambda a: a['policy'] == policy), ('auth/kubernetes/role/' + lane['role'], role_payload(lane), None)]:
old = bao(['read', '-format=json', path], allow_failure=True)
if old.returncode:
if not absent(old):
raise LaneError('object_absence_unproven')
bao(['write', path, '-'], payload=payload)
elif checker:
if not checker(data(old)['data']):
raise LaneError('policy_drift')
else:
check_role(data(old)['data'], lane)
child = data(bao(['token', 'create', '-format=json', '-policy=' + lane['policy'], '-policy=agent-high-risk-boundary', '-no-default-policy', '-ttl=60s']))['auth']['client_token']
try:
paths = [lane['kv_path'], lane['kv_path'].replace('/data/', '/metadata/', 1)]
caps = capabilities(child, paths)
if any((caps[p] != ['deny'] for p in paths)):
raise LaneError('coding_agent_boundary_failed')
receipt['coding_agent_deny_wins'] = True
finally:
revoke(child)
verify_login(k, lane, receipt)
command(k + ['apply', '-f', '/home/worsch/rapp-telemetry/manifests/custody.yaml'])
command(k + ['wait', '--for=condition=Ready', 'clustersecretstore/openbao-telemetry-grafana', '--timeout=45s'])
command(k + ['-n', 'telemetry', 'wait', '--for=condition=Ready', 'externalsecret/telemetry-grafana-admin', '--timeout=45s'])
live = data(command(k + ['-n', 'telemetry', 'get', 'secret', 'telemetry-grafana-admin', '-o', 'json']))['data']
if base64.b64decode(live['admin-user']).decode() != native['data']['ADMIN_USERNAME'] or base64.b64decode(live['admin-password']).decode() != native['data']['ADMIN_PASSWORD']:
raise LaneError('delivery_mismatch')
receipt.update(status='verified', kv_version=native['metadata']['version'], custody='platform/workloads/telemetry/grafana-admin', delivery_matches=True)
except Exception:
receipt['error'] = 'custody_bootstrap_failed'
finally:
with os.fdopen(fd, 'w') as f:
json.dump(receipt, f, indent=2)
sys.exit(0 if receipt['status'] == 'verified' else 1)
if __name__ == "__main__":
main()