|
| 1 | +"""Shared transport-security validation for gateway connections (AAASM-3685/3725). |
| 2 | +
|
| 3 | +The SDK reaches the governance gateway over two transports that both carry |
| 4 | +sensitive material: |
| 5 | +
|
| 6 | +* the op-control gRPC stream (``op_control.py``), which carries the agent |
| 7 | + identity triple and operator pause / terminate signals; |
| 8 | +* the control-plane HTTP API (``client/gateway.py``), which sends the API key |
| 9 | + as an ``Authorization: Bearer`` header. |
| 10 | +
|
| 11 | +Neither must travel unencrypted to a **non-loopback** host without an explicit |
| 12 | +opt-in. A loopback target is the local dev-mode gateway, where plaintext is the |
| 13 | +documented default; anything else is presumed remote and must be encrypted. |
| 14 | +
|
| 15 | +This module centralises the loopback decision and the two enforcement helpers |
| 16 | +so the gRPC and HTTP paths agree on what "secure" means (mirrors node-sdk |
| 17 | +AAASM-3123). |
| 18 | +""" |
| 19 | + |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +import warnings |
| 23 | +from urllib.parse import urlsplit |
| 24 | + |
| 25 | +__all__ = [ |
| 26 | + "LOOPBACK_HOSTS", |
| 27 | + "gateway_host_of", |
| 28 | + "is_loopback_target", |
| 29 | + "require_secure_grpc_target", |
| 30 | + "require_secure_http_url", |
| 31 | + "warn_if_insecure_http_url", |
| 32 | +] |
| 33 | + |
| 34 | +# Hosts treated as loopback for the secure-by-default transport decision. |
| 35 | +# A loopback gateway is the local dev-mode CP, where plaintext is the documented |
| 36 | +# default; anything else is presumed remote and must be encrypted. |
| 37 | +LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1", "[::1]"}) |
| 38 | + |
| 39 | + |
| 40 | +def gateway_host_of(gateway_url: str) -> str: |
| 41 | + """Extract the bare host from a gateway target. |
| 42 | +
|
| 43 | + Accepts a gRPC ``host:port`` target, a bare host, or a full URL with a |
| 44 | + scheme (``http://host:port/path``). IPv6 bracket form (``[::1]:7391``) is |
| 45 | + preserved with its brackets so it can be matched against |
| 46 | + :data:`LOOPBACK_HOSTS`. The result is lower-cased for case-insensitive |
| 47 | + comparison. |
| 48 | + """ |
| 49 | + target = gateway_url.strip() |
| 50 | + |
| 51 | + # Full URL with a scheme — let urlsplit pull out the host:port authority. |
| 52 | + if "://" in target: |
| 53 | + target = urlsplit(target).netloc |
| 54 | + |
| 55 | + # Strip any userinfo (``user:pass@host``) — only the host matters here. |
| 56 | + if "@" in target: |
| 57 | + target = target.rsplit("@", 1)[1] |
| 58 | + |
| 59 | + # Bracketed IPv6 (``[::1]`` or ``[::1]:7391``): keep the brackets, drop the |
| 60 | + # trailing ``:port`` that sits *outside* the closing bracket. |
| 61 | + if target.startswith("["): |
| 62 | + closing = target.find("]") |
| 63 | + if closing != -1: |
| 64 | + return target[: closing + 1].lower() |
| 65 | + return target.lower() |
| 66 | + |
| 67 | + # Bare IPv6 without brackets (more than one colon) — no port to strip. |
| 68 | + if target.count(":") > 1: |
| 69 | + return target.lower() |
| 70 | + |
| 71 | + # host or host:port — drop the port. |
| 72 | + return target.rsplit(":", 1)[0].lower() if ":" in target else target.lower() |
| 73 | + |
| 74 | + |
| 75 | +def is_loopback_target(gateway_url: str) -> bool: |
| 76 | + """Return True iff ``gateway_url`` points at a loopback host.""" |
| 77 | + return gateway_host_of(gateway_url) in LOOPBACK_HOSTS |
| 78 | + |
| 79 | + |
| 80 | +def require_secure_grpc_target(gateway_url: str, *, allow_insecure: bool) -> None: |
| 81 | + """Validate that a plaintext gRPC channel to ``gateway_url`` is permitted. |
| 82 | +
|
| 83 | + A loopback target is always allowed (local dev gateway). A non-loopback |
| 84 | + target requires the caller to set ``allow_insecure`` — otherwise raise |
| 85 | + :class:`ValueError`, because the op-control stream carries the agent |
| 86 | + identity and operator control signals. |
| 87 | + """ |
| 88 | + if is_loopback_target(gateway_url) or allow_insecure: |
| 89 | + return |
| 90 | + raise ValueError( |
| 91 | + f"Refusing to open an insecure (plaintext) gRPC channel to non-loopback " |
| 92 | + f"gateway {gateway_url!r}. Use a TLS channel via channel_factory, or pass " |
| 93 | + f"allow_insecure=True to explicitly opt in (loopback dev only)." |
| 94 | + ) |
| 95 | + |
| 96 | + |
| 97 | +def require_secure_http_url(gateway_url: str, *, has_api_key: bool, allow_insecure: bool) -> None: |
| 98 | + """Validate that an ``http://`` control-plane URL is permitted. |
| 99 | +
|
| 100 | + When an API key is set it is sent as a Bearer header, so a plaintext |
| 101 | + ``http://`` URL to a non-loopback host would leak the credential. Refuse |
| 102 | + unless the target is loopback or ``allow_insecure`` is set. ``https://`` |
| 103 | + URLs (and non-http schemes) always pass. |
| 104 | + """ |
| 105 | + scheme = urlsplit(gateway_url.strip()).scheme.lower() |
| 106 | + if scheme != "http": |
| 107 | + return |
| 108 | + if not has_api_key: |
| 109 | + return |
| 110 | + if is_loopback_target(gateway_url) or allow_insecure: |
| 111 | + return |
| 112 | + raise ValueError( |
| 113 | + f"Refusing to send an Authorization: Bearer credential over a plaintext " |
| 114 | + f"(non-TLS) connection to non-loopback gateway {gateway_url!r}. Use an " |
| 115 | + f"https:// endpoint, or pass allow_insecure=True to explicitly opt in " |
| 116 | + f"(loopback dev only)." |
| 117 | + ) |
| 118 | + |
| 119 | + |
| 120 | +def warn_if_insecure_http_url(gateway_url: str, *, has_api_key: bool) -> None: |
| 121 | + """Emit a warning when a non-loopback ``http://`` gateway carries a key. |
| 122 | +
|
| 123 | + Resolution-time advisory counterpart to :func:`require_secure_http_url`: |
| 124 | + the resolver knows the URL and whether a key is set before any request is |
| 125 | + issued, so it warns early. The hard refusal still happens later in |
| 126 | + ``GatewayClient`` (AAASM-3725). ``https://`` and loopback targets are silent. |
| 127 | + """ |
| 128 | + scheme = urlsplit(gateway_url.strip()).scheme.lower() |
| 129 | + if scheme != "http" or not has_api_key or is_loopback_target(gateway_url): |
| 130 | + return |
| 131 | + warnings.warn( |
| 132 | + f"Gateway {gateway_url!r} uses plaintext http:// while an API key is set; " |
| 133 | + f"the Authorization: Bearer credential would travel unencrypted. Use " |
| 134 | + f"https:// for non-loopback gateways.", |
| 135 | + stacklevel=3, |
| 136 | + ) |
0 commit comments