|
| 1 | +"""Authenticated loopback bridge for browser runtime command execution.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +import secrets |
| 7 | +import subprocess |
| 8 | +import threading |
| 9 | +from collections.abc import Callable |
| 10 | +from dataclasses import dataclass |
| 11 | +from http import HTTPStatus |
| 12 | +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 13 | +from urllib.error import HTTPError, URLError |
| 14 | +from urllib.request import Request, urlopen |
| 15 | + |
| 16 | +from ash.sandbox.executor import ExecutionResult |
| 17 | + |
| 18 | +BridgeExecutor = Callable[[str, int, dict[str, str]], ExecutionResult] |
| 19 | + |
| 20 | + |
| 21 | +@dataclass(slots=True) |
| 22 | +class BrowserExecBridge: |
| 23 | + """Loopback HTTP bridge with bearer-token auth.""" |
| 24 | + |
| 25 | + token: str |
| 26 | + base_url: str |
| 27 | + _server: ThreadingHTTPServer |
| 28 | + _thread: threading.Thread |
| 29 | + |
| 30 | + @classmethod |
| 31 | + def start( |
| 32 | + cls, |
| 33 | + *, |
| 34 | + executor: BridgeExecutor, |
| 35 | + host: str = "127.0.0.1", |
| 36 | + token: str | None = None, |
| 37 | + ) -> BrowserExecBridge: |
| 38 | + if host not in {"127.0.0.1", "localhost"}: |
| 39 | + raise ValueError(f"bridge_loopback_required:{host}") |
| 40 | + |
| 41 | + bridge_token = (token or secrets.token_hex(24)).strip() |
| 42 | + if not bridge_token: |
| 43 | + raise ValueError("bridge_token_required") |
| 44 | + |
| 45 | + class _BridgeServer(ThreadingHTTPServer): |
| 46 | + daemon_threads = True |
| 47 | + allow_reuse_address = True |
| 48 | + |
| 49 | + def __init__(self) -> None: |
| 50 | + super().__init__((host, 0), _BridgeHandler) |
| 51 | + self.bridge_token = bridge_token |
| 52 | + self.bridge_executor = executor |
| 53 | + |
| 54 | + class _BridgeHandler(BaseHTTPRequestHandler): |
| 55 | + server: _BridgeServer |
| 56 | + |
| 57 | + def do_POST(self) -> None: # noqa: N802 |
| 58 | + if self.path != "/exec": |
| 59 | + self._write_json( |
| 60 | + HTTPStatus.NOT_FOUND, {"error": "bridge_route_not_found"} |
| 61 | + ) |
| 62 | + return |
| 63 | + expected = f"Bearer {self.server.bridge_token}" |
| 64 | + if (self.headers.get("Authorization") or "") != expected: |
| 65 | + self._write_json( |
| 66 | + HTTPStatus.UNAUTHORIZED, {"error": "bridge_unauthorized"} |
| 67 | + ) |
| 68 | + return |
| 69 | + try: |
| 70 | + content_length = int(self.headers.get("Content-Length") or "0") |
| 71 | + except ValueError: |
| 72 | + self._write_json( |
| 73 | + HTTPStatus.BAD_REQUEST, |
| 74 | + {"error": "bridge_invalid_content_length"}, |
| 75 | + ) |
| 76 | + return |
| 77 | + body = self.rfile.read(max(0, content_length)) |
| 78 | + try: |
| 79 | + payload = json.loads(body.decode("utf-8", errors="replace")) |
| 80 | + except json.JSONDecodeError: |
| 81 | + self._write_json( |
| 82 | + HTTPStatus.BAD_REQUEST, {"error": "bridge_invalid_json"} |
| 83 | + ) |
| 84 | + return |
| 85 | + command = payload.get("command") |
| 86 | + timeout_seconds = payload.get("timeout_seconds") |
| 87 | + environment = payload.get("environment") or {} |
| 88 | + if not isinstance(command, str) or not command.strip(): |
| 89 | + self._write_json( |
| 90 | + HTTPStatus.BAD_REQUEST, {"error": "bridge_invalid_command"} |
| 91 | + ) |
| 92 | + return |
| 93 | + if not isinstance(timeout_seconds, int) or timeout_seconds <= 0: |
| 94 | + self._write_json( |
| 95 | + HTTPStatus.BAD_REQUEST, {"error": "bridge_invalid_timeout"} |
| 96 | + ) |
| 97 | + return |
| 98 | + if not isinstance(environment, dict) or not all( |
| 99 | + isinstance(k, str) and isinstance(v, str) |
| 100 | + for k, v in environment.items() |
| 101 | + ): |
| 102 | + self._write_json( |
| 103 | + HTTPStatus.BAD_REQUEST, {"error": "bridge_invalid_environment"} |
| 104 | + ) |
| 105 | + return |
| 106 | + try: |
| 107 | + result = self.server.bridge_executor( |
| 108 | + command, timeout_seconds, environment |
| 109 | + ) |
| 110 | + except Exception as e: |
| 111 | + self._write_json( |
| 112 | + HTTPStatus.INTERNAL_SERVER_ERROR, |
| 113 | + {"error": f"bridge_executor_failed:{e}"}, |
| 114 | + ) |
| 115 | + return |
| 116 | + self._write_json( |
| 117 | + HTTPStatus.OK, |
| 118 | + { |
| 119 | + "exit_code": result.exit_code, |
| 120 | + "stdout": result.stdout, |
| 121 | + "stderr": result.stderr, |
| 122 | + "timed_out": result.timed_out, |
| 123 | + }, |
| 124 | + ) |
| 125 | + |
| 126 | + def _write_json( |
| 127 | + self, status: HTTPStatus, payload: dict[str, object] |
| 128 | + ) -> None: |
| 129 | + body = json.dumps(payload, ensure_ascii=True).encode("utf-8") |
| 130 | + self.send_response(int(status)) |
| 131 | + self.send_header("Content-Type", "application/json") |
| 132 | + self.send_header("Content-Length", str(len(body))) |
| 133 | + self.end_headers() |
| 134 | + self.wfile.write(body) |
| 135 | + |
| 136 | + def log_message(self, format: str, *args: object) -> None: |
| 137 | + _ = (format, args) |
| 138 | + return |
| 139 | + |
| 140 | + server = _BridgeServer() |
| 141 | + thread = threading.Thread( |
| 142 | + target=server.serve_forever, |
| 143 | + name="ash-browser-bridge", |
| 144 | + daemon=True, |
| 145 | + ) |
| 146 | + thread.start() |
| 147 | + port = int(server.server_address[1]) |
| 148 | + return cls( |
| 149 | + token=bridge_token, |
| 150 | + base_url=f"http://127.0.0.1:{port}", |
| 151 | + _server=server, |
| 152 | + _thread=thread, |
| 153 | + ) |
| 154 | + |
| 155 | + def stop(self) -> None: |
| 156 | + self._server.shutdown() |
| 157 | + self._server.server_close() |
| 158 | + self._thread.join(timeout=2.0) |
| 159 | + |
| 160 | + |
| 161 | +def request_bridge_exec( |
| 162 | + *, |
| 163 | + base_url: str, |
| 164 | + token: str, |
| 165 | + command: str, |
| 166 | + timeout_seconds: int, |
| 167 | + environment: dict[str, str] | None = None, |
| 168 | +) -> ExecutionResult: |
| 169 | + payload = json.dumps( |
| 170 | + { |
| 171 | + "command": command, |
| 172 | + "timeout_seconds": timeout_seconds, |
| 173 | + "environment": environment or {}, |
| 174 | + }, |
| 175 | + ensure_ascii=True, |
| 176 | + ).encode("utf-8") |
| 177 | + request = Request( # noqa: S310 |
| 178 | + f"{base_url.rstrip('/')}/exec", |
| 179 | + method="POST", |
| 180 | + data=payload, |
| 181 | + headers={ |
| 182 | + "Content-Type": "application/json", |
| 183 | + "Authorization": f"Bearer {token}", |
| 184 | + }, |
| 185 | + ) |
| 186 | + try: |
| 187 | + with urlopen(request, timeout=max(5, timeout_seconds + 10)) as response: # noqa: S310 |
| 188 | + body = response.read().decode("utf-8", errors="replace") |
| 189 | + except HTTPError as e: |
| 190 | + if e.code == int(HTTPStatus.UNAUTHORIZED): |
| 191 | + raise ValueError("bridge_unauthorized") from None |
| 192 | + raise ValueError(f"bridge_http_error:{e.code}") from None |
| 193 | + except URLError as e: |
| 194 | + raise ValueError(f"bridge_unreachable:{e}") from e |
| 195 | + parsed = json.loads(body) |
| 196 | + return ExecutionResult( |
| 197 | + exit_code=int(parsed.get("exit_code", 1)), |
| 198 | + stdout=str(parsed.get("stdout") or ""), |
| 199 | + stderr=str(parsed.get("stderr") or ""), |
| 200 | + timed_out=bool(parsed.get("timed_out")), |
| 201 | + ) |
| 202 | + |
| 203 | + |
| 204 | +def make_docker_exec_bridge_executor(*, container_name: str) -> BridgeExecutor: |
| 205 | + def _execute( |
| 206 | + command: str, timeout_seconds: int, environment: dict[str, str] |
| 207 | + ) -> ExecutionResult: |
| 208 | + env_args: list[str] = [] |
| 209 | + for key, value in environment.items(): |
| 210 | + env_args.extend(["-e", f"{key}={value}"]) |
| 211 | + args = [ |
| 212 | + "docker", |
| 213 | + "exec", |
| 214 | + *env_args, |
| 215 | + container_name, |
| 216 | + "bash", |
| 217 | + "-lc", |
| 218 | + command, |
| 219 | + ] |
| 220 | + try: |
| 221 | + proc = subprocess.run( # noqa: S603 |
| 222 | + args, |
| 223 | + capture_output=True, |
| 224 | + text=True, |
| 225 | + timeout=max(5, timeout_seconds + 10), |
| 226 | + check=False, |
| 227 | + ) |
| 228 | + except subprocess.TimeoutExpired: |
| 229 | + return ExecutionResult( |
| 230 | + exit_code=-1, |
| 231 | + stdout="", |
| 232 | + stderr="bridge_command_timed_out", |
| 233 | + timed_out=True, |
| 234 | + ) |
| 235 | + return ExecutionResult( |
| 236 | + exit_code=int(proc.returncode), |
| 237 | + stdout=proc.stdout or "", |
| 238 | + stderr=proc.stderr or "", |
| 239 | + ) |
| 240 | + |
| 241 | + return _execute |
0 commit comments