Agent Zero AI framework
Fix Tailscale Remote Control CSRF origins
Alessandroca4efe6e6ac2
diff --git a/api/csrf_token.py b/api/csrf_token.pyindex 5f4ba13d5..6cbd355c0 100644--- a/api/csrf_token.py+++ b/api/csrf_token.py@@ -1,5 +1,4 @@import secrets-from urllib.parse import urlparsefrom helpers.api import (ApiHandler,Input,@@ -9,6 +8,7 @@ from helpers.api import (session,)from helpers import runtime, dotenv, login+from helpers.tunnel_origins import origin_from_urlimport fnmatchALLOWED_ORIGINS_KEY = "ALLOWED_ORIGINS"@@ -82,11 +82,7 @@ class GetCsrfToken(ApiHandler):)if not r:return None- # parse and normalize- p = urlparse(r)- if not p.scheme or not p.hostname:- return None- return f"{p.scheme}://{p.hostname}" + (f":{p.port}" if p.port else "")+ return origin_from_url(r)async def get_allowed_origins(self) -> list[str]:# get the allowed origins from the environment@@ -107,8 +103,10 @@ class GetCsrfToken(ApiHandler):from api.tunnel_proxy import process as tunnel_api_processtunnel = await tunnel_api_process({"action": "get"})- if tunnel and isinstance(tunnel, dict) and tunnel["success"]:- allowed_origins.append(tunnel["tunnel_url"])+ if tunnel and isinstance(tunnel, dict) and tunnel.get("success"):+ tunnel_origin = origin_from_url(tunnel.get("tunnel_url"))+ if tunnel_origin:+ allowed_origins.append(tunnel_origin)except Exception:passdiff --git a/helpers/tunnel_origins.py b/helpers/tunnel_origins.pynew file mode 100644index 000000000..c24d8e997--- /dev/null+++ b/helpers/tunnel_origins.py@@ -0,0 +1,107 @@+import json+import urllib.request+from urllib.parse import urlparse+++_DEFAULT_PORTS = {+ "http": 80,+ "https": 443,+ "ws": 80,+ "wss": 443,+}+++def origin_from_url(value):+ """Normalize a URL or Origin header to scheme://host[:port]."""+ if not isinstance(value, str) or not value.strip():+ return None+ parsed = urlparse(value.strip())+ if not parsed.scheme or not parsed.hostname:+ return None++ scheme = parsed.scheme.lower()+ host = parsed.hostname.lower()+ try:+ port = parsed.port+ except ValueError:+ return None++ origin = f"{scheme}://{host}"+ if port and port != _DEFAULT_PORTS.get(scheme):+ origin += f":{port}"+ return origin+++def origin_key(value):+ """Return a comparable same-origin tuple including default ports."""+ origin = origin_from_url(value)+ if not origin:+ return None+ parsed = urlparse(origin)+ try:+ port = parsed.port or _DEFAULT_PORTS.get(parsed.scheme)+ except ValueError:+ return None+ if not parsed.scheme or not parsed.hostname or port is None:+ return None+ return parsed.scheme, parsed.hostname.lower(), int(port)+++def get_active_tunnel_origins():+ """Return normalized origins for currently active Remote Control URLs."""+ origins = []++ try:+ from helpers.tunnel_manager import TunnelManager++ tunnel_url = TunnelManager.get_instance().get_tunnel_url()+ _append_origin(origins, tunnel_url)+ except Exception:+ pass++ try:+ _append_origin(origins, _get_tunnel_service_url())+ except Exception:+ pass++ return origins+++def _append_origin(origins, url):+ origin = origin_from_url(url)+ if origin and origin not in origins:+ origins.append(origin)+++def _get_tunnel_service_url():+ try:+ from helpers import dotenv, runtime++ should_query_service = bool(+ runtime.is_dockerized()+ or runtime.get_arg("tunnel_api_port")+ or dotenv.get_dotenv_value("TUNNEL_API_PORT")+ )+ if not should_query_service:+ return None++ port = runtime.get_tunnel_api_port()+ except Exception:+ return None++ body = json.dumps({"action": "get"}).encode("utf-8")+ request = urllib.request.Request(+ f"http://localhost:{port}/",+ data=body,+ headers={"Content-Type": "application/json"},+ method="POST",+ )+ try:+ with urllib.request.urlopen(request, timeout=0.35) as response:+ payload = json.loads(response.read().decode("utf-8", errors="replace"))+ except Exception:+ return None++ if isinstance(payload, dict) and payload.get("success"):+ return payload.get("tunnel_url")+ return Nonediff --git a/helpers/ws.py b/helpers/ws.pyindex 1150aa8dc..5ca1cc79c 100644--- a/helpers/ws.py+++ b/helpers/ws.py@@ -13,6 +13,7 @@ from flask import Flask, session, requestfrom helpers import files, cachefrom helpers.print_style import PrintStylefrom helpers.errors import format_error+from helpers.tunnel_origins import get_active_tunnel_origins, origin_keyif TYPE_CHECKING:from helpers.ws_manager import WsManager@@ -148,6 +149,11 @@ def validate_ws_origin(environ: dict[str, Any]) -> tuple[bool, str | None]:if origin_host == host and origin_port == port:return True, None+ request_origin_key = (origin_parsed.scheme, origin_host, int(origin_port))+ for active_origin in get_active_tunnel_origins():+ if origin_key(active_origin) == request_origin_key:+ return True, None+if origin_host not in {host for host, _ in candidates}:return False, "origin_host_mismatch"return False, "origin_port_mismatch"@@ -648,4 +654,4 @@ def _error_response(code: str, message: str,"ok": False,"error": {"code": code, "error": message},}],- }\ No newline at end of file+ }diff --git a/run_ui.py b/run_ui.pyindex 4edf94b8b..8346d1b47 100644--- a/run_ui.py+++ b/run_ui.py@@ -1,5 +1,6 @@import initializefrom helpers import dotenv, extension, runtime+from helpers.api import csrf_protect, requires_authfrom helpers.print_style import PrintStylefrom helpers.server_startup import run_uvicorn_with_retriesfrom helpers.ui_server import UiServerRuntime, configure_process_environmentdiff --git a/tests/test_csrf_tunnel_origins.py b/tests/test_csrf_tunnel_origins.pynew file mode 100644index 000000000..b2c0af92d--- /dev/null+++ b/tests/test_csrf_tunnel_origins.py@@ -0,0 +1,153 @@+from __future__ import annotations++import json+from types import SimpleNamespace++import pytest+from flask import Flask+++async def test_csrf_token_allows_normalized_active_tailscale_origin(monkeypatch):+ import api.csrf_token as csrf_module+ import api.tunnel_proxy as tunnel_proxy++ handler = csrf_module.GetCsrfToken(Flask("test_csrf_tunnel_origins"), None)+ request = SimpleNamespace(+ headers={"Origin": "https://agent-zero.tailabc.ts.net"},+ environ={},+ referrer=None,+ )++ monkeypatch.setattr(csrf_module.login, "is_login_required", lambda: False)+ monkeypatch.setattr(+ csrf_module.dotenv,+ "get_dotenv_value",+ lambda key: "http://localhost:32080"+ if key == csrf_module.ALLOWED_ORIGINS_KEY+ else "",+ )++ async def fake_tunnel_process(input_data):+ return {+ "success": True,+ "tunnel_url": "https://agent-zero.tailabc.ts.net/funnel-ready/",+ "is_running": True,+ }++ monkeypatch.setattr(tunnel_proxy, "process", fake_tunnel_process)++ origin_check = await handler.check_allowed_origin(request)++ assert origin_check["ok"] is True+ assert "https://agent-zero.tailabc.ts.net" in origin_check["allowed_origins"]+++async def test_csrf_token_rejects_unrelated_origin_with_active_tunnel(monkeypatch):+ import api.csrf_token as csrf_module+ import api.tunnel_proxy as tunnel_proxy++ handler = csrf_module.GetCsrfToken(Flask("test_csrf_tunnel_origins"), None)+ request = SimpleNamespace(+ headers={"Origin": "https://evil.example"},+ environ={},+ referrer=None,+ )++ monkeypatch.setattr(csrf_module.login, "is_login_required", lambda: False)+ monkeypatch.setattr(+ csrf_module.dotenv,+ "get_dotenv_value",+ lambda key: "http://localhost:32080"+ if key == csrf_module.ALLOWED_ORIGINS_KEY+ else "",+ )++ async def fake_tunnel_process(input_data):+ return {+ "success": True,+ "tunnel_url": "https://agent-zero.tailabc.ts.net/funnel-ready/",+ "is_running": True,+ }++ monkeypatch.setattr(tunnel_proxy, "process", fake_tunnel_process)++ origin_check = await handler.check_allowed_origin(request)++ assert origin_check["ok"] is False+++def test_active_tunnel_origins_include_docker_tunnel_service_url(monkeypatch):+ import helpers.tunnel_origins as tunnel_origins++ monkeypatch.setattr(+ tunnel_origins,+ "_get_tunnel_service_url",+ lambda: "https://agent-zero.tailabc.ts.net/funnel-ready/",+ )++ assert (+ "https://agent-zero.tailabc.ts.net"+ in tunnel_origins.get_active_tunnel_origins()+ )+++def test_tunnel_service_url_uses_short_local_get_request(monkeypatch):+ from helpers import dotenv, runtime+ import helpers.tunnel_origins as tunnel_origins++ captured = {}++ class FakeResponse:+ def __enter__(self):+ return self++ def __exit__(self, exc_type, exc, tb):+ return None++ def read(self):+ return json.dumps({+ "success": True,+ "tunnel_url": "https://agent-zero.tailabc.ts.net/funnel-ready/",+ }).encode("utf-8")++ def fake_urlopen(request, timeout):+ captured["url"] = request.full_url+ captured["body"] = request.data+ captured["method"] = request.get_method()+ captured["timeout"] = timeout+ return FakeResponse()++ monkeypatch.setattr(+ runtime,+ "is_dockerized",+ lambda: True,+ )+ monkeypatch.setattr(+ runtime,+ "get_arg",+ lambda name: None,+ )+ monkeypatch.setattr(+ runtime,+ "get_tunnel_api_port",+ lambda: 55520,+ )+ monkeypatch.setattr(+ dotenv,+ "get_dotenv_value",+ lambda key: "",+ )+ monkeypatch.setattr(tunnel_origins.urllib.request, "urlopen", fake_urlopen)++ assert (+ tunnel_origins._get_tunnel_service_url()+ == "https://agent-zero.tailabc.ts.net/funnel-ready/"+ )+ assert captured == {+ "url": "http://localhost:55520/",+ "body": b'{"action": "get"}',+ "method": "POST",+ "timeout": 0.35,+ }diff --git a/tests/test_ws_csrf.py b/tests/test_ws_csrf.pyindex 48e7e8230..a5fb7ba70 100644--- a/tests/test_ws_csrf.py+++ b/tests/test_ws_csrf.py@@ -49,3 +49,49 @@ def test_validate_ws_origin_rejects_cross_origin():)assert ok is Falseassert reason == "origin_host_mismatch"+++def test_validate_ws_origin_allows_active_tunnel_origin_with_local_upstream_host(+ monkeypatch,+):+ import helpers.ws as ws++ monkeypatch.setattr(+ ws,+ "get_active_tunnel_origins",+ lambda: ["https://agent-zero.tailabc.ts.net"],+ raising=False,+ )++ ok, reason = validate_ws_origin(+ {+ "HTTP_ORIGIN": "https://agent-zero.tailabc.ts.net",+ "HTTP_HOST": "127.0.0.1:80",+ }+ )++ assert ok is True+ assert reason is None+++def test_validate_ws_origin_rejects_unrelated_origin_with_active_tunnel(+ monkeypatch,+):+ import helpers.ws as ws++ monkeypatch.setattr(+ ws,+ "get_active_tunnel_origins",+ lambda: ["https://agent-zero.tailabc.ts.net"],+ raising=False,+ )++ ok, reason = validate_ws_origin(+ {+ "HTTP_ORIGIN": "https://evil.example",+ "HTTP_HOST": "127.0.0.1:80",+ }+ )++ assert ok is False+ assert reason == "origin_host_mismatch"