import json import os import subprocess import sys import urllib.error import urllib.parse import urllib.request def emit(key: str, value) -> None: print(f"{key}: {json.dumps(value)}") def require_env(name: str) -> str: value = os.environ.get(name) if not value: print(f"Error: {name} environment variable is not set.", file=sys.stderr) sys.exit(1) return value def main() -> None: host = require_env("HOST") port = require_env("PORT") url = f"http://{host}:{port}/cluster-agent/e2e-ns/api/v1/clusters/test:executeCommand?token=secret123" payload = json.dumps({"command": "echo hello"}).encode() req = urllib.request.Request(url, data=payload, method="POST") req.add_header("Content-Type", "application/json") try: with urllib.request.urlopen(req, timeout=10) as resp: resp.read() except urllib.error.HTTPError: pass pod = subprocess.check_output( [ "kubectl", "-n", "cluster-agent-e2e", "get", "pods", "-l", "app=cluster-agent", "-o", "jsonpath={.items[0].metadata.name}", ], text=True, ).strip() audit_log = subprocess.check_output( [ "kubectl", "-n", "cluster-agent-e2e", "exec", pod, "--", "cat", "/tmp/audit.log", ], text=True, ).strip() target = None for line in audit_log.splitlines(): line = line.strip() if not line: continue try: entry = json.loads(line) except json.JSONDecodeError: continue if entry.get("request_method") != "POST": continue uri = entry.get("request_uri", "") if "executeCommand" in uri: target = entry if not target: emit("error", "audit entry not found") sys.exit(1) params = urllib.parse.parse_qs( target.get("request_params", ""), keep_blank_values=True ) token = params.get("token", [None])[0] body_raw = target.get("request_body", "") try: body = json.loads(body_raw) if body_raw else {} except Exception: body = {} emit("method", target.get("request_method")) emit("uri", target.get("request_uri")) emit("status", target.get("response_status")) emit("token", token) emit("command", body.get("command")) if __name__ == "__main__": main()