|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import argparse |
| 4 | +import http.client |
| 5 | +import json |
| 6 | +import sys |
| 7 | +from pathlib import Path |
| 8 | +from urllib.parse import urlsplit |
| 9 | + |
| 10 | +from predicate_authority.policy_source import PolicyFileSource |
| 11 | + |
| 12 | + |
| 13 | +def _request_json( |
| 14 | + method: str, url: str, payload: dict[str, str] | None = None |
| 15 | +) -> tuple[int, dict[str, object]]: |
| 16 | + parsed = urlsplit(url) |
| 17 | + if parsed.scheme not in {"http", "https"}: |
| 18 | + raise RuntimeError(f"Unsupported URL scheme: {parsed.scheme}") |
| 19 | + if parsed.netloc == "": |
| 20 | + raise RuntimeError("URL must include host:port.") |
| 21 | + path = parsed.path or "/" |
| 22 | + if parsed.query: |
| 23 | + path = f"{path}?{parsed.query}" |
| 24 | + body = None |
| 25 | + headers: dict[str, str] = {} |
| 26 | + if payload is not None: |
| 27 | + body = json.dumps(payload) |
| 28 | + headers["Content-Type"] = "application/json" |
| 29 | + connection_cls = ( |
| 30 | + http.client.HTTPSConnection if parsed.scheme == "https" else http.client.HTTPConnection |
| 31 | + ) |
| 32 | + connection = connection_cls(parsed.netloc, timeout=5.0) |
| 33 | + try: |
| 34 | + connection.request(method.upper(), path, body=body, headers=headers) |
| 35 | + response = connection.getresponse() |
| 36 | + raw = response.read().decode("utf-8") |
| 37 | + finally: |
| 38 | + connection.close() |
| 39 | + if raw.strip() == "": |
| 40 | + return int(response.status), {} |
| 41 | + loaded = json.loads(raw) |
| 42 | + if not isinstance(loaded, dict): |
| 43 | + raise RuntimeError("Expected JSON object response.") |
| 44 | + return int(response.status), loaded |
| 45 | + |
| 46 | + |
| 47 | +def _base_url(host: str, port: int) -> str: |
| 48 | + return f"http://{host}:{port}" |
| 49 | + |
| 50 | + |
| 51 | +def _print_json(payload: dict[str, object]) -> None: |
| 52 | + print(json.dumps(payload, indent=2, sort_keys=True)) |
| 53 | + |
| 54 | + |
| 55 | +def _cmd_sidecar_health(args: argparse.Namespace) -> int: |
| 56 | + status, payload = _request_json("GET", f"{_base_url(args.host, args.port)}/health") |
| 57 | + _print_json(payload) |
| 58 | + return 0 if status < 400 else 1 |
| 59 | + |
| 60 | + |
| 61 | +def _cmd_sidecar_status(args: argparse.Namespace) -> int: |
| 62 | + status, payload = _request_json("GET", f"{_base_url(args.host, args.port)}/status") |
| 63 | + _print_json(payload) |
| 64 | + return 0 if status < 400 else 1 |
| 65 | + |
| 66 | + |
| 67 | +def _cmd_policy_validate(args: argparse.Namespace) -> int: |
| 68 | + path = Path(args.file) |
| 69 | + if not path.exists(): |
| 70 | + print(f"Policy file not found: {path}", file=sys.stderr) |
| 71 | + return 1 |
| 72 | + try: |
| 73 | + rules = PolicyFileSource(str(path)).load_rules() |
| 74 | + except Exception as exc: # noqa: BLE001 |
| 75 | + print(f"Policy validation failed: {exc}", file=sys.stderr) |
| 76 | + return 1 |
| 77 | + _print_json({"valid": True, "rule_count": len(rules), "file": str(path)}) |
| 78 | + return 0 |
| 79 | + |
| 80 | + |
| 81 | +def _cmd_policy_reload(args: argparse.Namespace) -> int: |
| 82 | + status, payload = _request_json("POST", f"{_base_url(args.host, args.port)}/policy/reload") |
| 83 | + _print_json(payload) |
| 84 | + return 0 if status < 400 else 1 |
| 85 | + |
| 86 | + |
| 87 | +def _cmd_revoke_principal(args: argparse.Namespace) -> int: |
| 88 | + status, payload = _request_json( |
| 89 | + "POST", |
| 90 | + f"{_base_url(args.host, args.port)}/revoke/principal", |
| 91 | + payload={"principal_id": args.id}, |
| 92 | + ) |
| 93 | + _print_json(payload) |
| 94 | + return 0 if status < 400 else 1 |
| 95 | + |
| 96 | + |
| 97 | +def _cmd_revoke_intent(args: argparse.Namespace) -> int: |
| 98 | + status, payload = _request_json( |
| 99 | + "POST", |
| 100 | + f"{_base_url(args.host, args.port)}/revoke/intent", |
| 101 | + payload={"intent_hash": args.hash}, |
| 102 | + ) |
| 103 | + _print_json(payload) |
| 104 | + return 0 if status < 400 else 1 |
| 105 | + |
| 106 | + |
| 107 | +def _add_host_port_args(parser: argparse.ArgumentParser) -> None: |
| 108 | + parser.add_argument("--host", default="127.0.0.1") |
| 109 | + parser.add_argument("--port", type=int, default=8787) |
| 110 | + |
| 111 | + |
| 112 | +def build_parser() -> argparse.ArgumentParser: |
| 113 | + parser = argparse.ArgumentParser(description="predicate-authority operational CLI") |
| 114 | + subparsers = parser.add_subparsers(dest="command", required=True) |
| 115 | + |
| 116 | + sidecar_parser = subparsers.add_parser("sidecar", help="Sidecar inspection commands") |
| 117 | + sidecar_sub = sidecar_parser.add_subparsers(dest="sidecar_command", required=True) |
| 118 | + |
| 119 | + sidecar_health = sidecar_sub.add_parser("health", help="Query sidecar /health") |
| 120 | + _add_host_port_args(sidecar_health) |
| 121 | + sidecar_health.set_defaults(func=_cmd_sidecar_health) |
| 122 | + |
| 123 | + sidecar_status = sidecar_sub.add_parser("status", help="Query sidecar /status") |
| 124 | + _add_host_port_args(sidecar_status) |
| 125 | + sidecar_status.set_defaults(func=_cmd_sidecar_status) |
| 126 | + |
| 127 | + policy_parser = subparsers.add_parser("policy", help="Policy utility commands") |
| 128 | + policy_sub = policy_parser.add_subparsers(dest="policy_command", required=True) |
| 129 | + |
| 130 | + policy_validate = policy_sub.add_parser("validate", help="Validate policy file") |
| 131 | + policy_validate.add_argument("--file", required=True) |
| 132 | + policy_validate.set_defaults(func=_cmd_policy_validate) |
| 133 | + |
| 134 | + policy_reload = policy_sub.add_parser("reload", help="Request sidecar policy reload") |
| 135 | + _add_host_port_args(policy_reload) |
| 136 | + policy_reload.set_defaults(func=_cmd_policy_reload) |
| 137 | + |
| 138 | + revoke_parser = subparsers.add_parser("revoke", help="Revocation commands") |
| 139 | + revoke_sub = revoke_parser.add_subparsers(dest="revoke_command", required=True) |
| 140 | + |
| 141 | + revoke_principal = revoke_sub.add_parser("principal", help="Revoke by principal_id") |
| 142 | + _add_host_port_args(revoke_principal) |
| 143 | + revoke_principal.add_argument("--id", required=True) |
| 144 | + revoke_principal.set_defaults(func=_cmd_revoke_principal) |
| 145 | + |
| 146 | + revoke_intent = revoke_sub.add_parser("intent", help="Revoke by intent hash") |
| 147 | + _add_host_port_args(revoke_intent) |
| 148 | + revoke_intent.add_argument("--hash", required=True) |
| 149 | + revoke_intent.set_defaults(func=_cmd_revoke_intent) |
| 150 | + |
| 151 | + return parser |
| 152 | + |
| 153 | + |
| 154 | +def main() -> None: |
| 155 | + parser = build_parser() |
| 156 | + args = parser.parse_args() |
| 157 | + exit_code = args.func(args) |
| 158 | + raise SystemExit(exit_code) |
| 159 | + |
| 160 | + |
| 161 | +if __name__ == "__main__": |
| 162 | + main() |
0 commit comments