Agent Zero AI framework
Harden Tailscale Funnel remote control
Alessandrobb6004c77fb3
diff --git a/helpers/cli_tunnel.py b/helpers/cli_tunnel.pyindex 05f702fc9..a37344c8c 100644--- a/helpers/cli_tunnel.py+++ b/helpers/cli_tunnel.py@@ -148,6 +148,7 @@ class CliTunnelHelper(TunnelHelper):notify=None,binary_resolver=None,preflight=None,+ output_handler=None,):super().__init__(port, notify=notify)self.label = label@@ -162,6 +163,7 @@ class CliTunnelHelper(TunnelHelper):self.binary_resolver = binary_resolverself.preflight = preflightself.command_prefix = []+ self.output_handler = output_handlerdef _extract_url(self, line):match = self.url_pattern.search(line)@@ -216,6 +218,11 @@ class CliTunnelHelper(TunnelHelper):cleaned_line = line.strip()if cleaned_line:recent_output.append(cleaned_line)+ if callable(self.output_handler):+ try:+ self.output_handler(cleaned_line, self._notify)+ except Exception:+ passurl = self._extract_url(cleaned_line)if url:self.tunnel_url = urldiff --git a/helpers/tailscale_tunnel.py b/helpers/tailscale_tunnel.pyindex 25e13361e..87325ca13 100644--- a/helpers/tailscale_tunnel.py+++ b/helpers/tailscale_tunnel.py@@ -21,6 +21,8 @@ TAILSCALE_URL_RE = re.compile(r"https://[a-zA-Z0-9.-]+\.ts\.net[^\s\"']*")TAILSCALE_LOGIN_URL_RE = re.compile(r"https://login\.tailscale\.com/[^\s\"']+")TAILSCALE_STABLE_PACKAGES_URL = "https://pkgs.tailscale.com/stable/?v=latest"TAILSCALE_UP_TIMEOUT = 180+TAILSCALE_FUNNEL_TIMEOUT = 300+TAILSCALE_FUNNEL_HTTPS_PORT = "443"TAILSCALE_DAEMON_START_TIMEOUT = 12TAILSCALE_RUNTIME_DIR = Path(files.get_abs_path("tmp", "tailscale"))TAILSCALE_STATE_DIR = Path(files.get_abs_path("usr", "tailscale"))@@ -102,6 +104,16 @@ def tailscale_status(binary_path, socket_path=None):)+def tailscale_funnel_help(binary_path, socket_path=None):+ return subprocess.run(+ tailscale_command(binary_path, ["funnel", "--help"], socket_path),+ check=False,+ text=True,+ capture_output=True,+ timeout=12,+ )++def compact_output(lines):return " ".join(line.strip() for line in lines if line and line.strip())@@ -355,6 +367,21 @@ def run_tailscale_up()+def ensure_tailscale_funnel_command(binary_path, socket_path=None):+ completed = tailscale_funnel_help(binary_path, socket_path=socket_path)+ output = compact_output([completed.stderr, completed.stdout])+ if completed.returncode == 0 and "tailscale funnel" in output.lower():+ return++ details = f" Details: {output}" if output else ""+ raise RuntimeError(+ "Agent Zero prepared Tailscale, but this Tailscale binary does not "+ "support `tailscale funnel`. Tailscale Remote Control needs Tailscale "+ "v1.38.3 or newer with Funnel support enabled for your tailnet."+ f"{details}"+ )++def ensure_tailscale_ready(binary_path, notify=None):socket_path = Nonecompleted = tailscale_status(binary_path)@@ -381,7 +408,8 @@ def ensure_tailscale_ready(binary_path, notify=None):try:payload = json.loads(completed.stdout or "{}")except json.JSONDecodeError:- return+ ensure_tailscale_funnel_command(binary_path, socket_path=socket_path)+ return {"command_prefix": tailscale_socket_args(socket_path)}backend_state = str(payload.get("BackendState") or "").lower()if backend_state and backend_state != "running":@@ -390,6 +418,7 @@ def ensure_tailscale_ready(binary_path, notify=None):try:payload = json.loads(completed.stdout or "{}")except json.JSONDecodeError:+ ensure_tailscale_funnel_command(binary_path, socket_path=socket_path)return {"command_prefix": tailscale_socket_args(socket_path)}backend_state = str(payload.get("BackendState") or "").lower()if backend_state and backend_state != "running":@@ -400,31 +429,63 @@ def ensure_tailscale_ready(binary_path, notify=None):"approval, then try again.")+ ensure_tailscale_funnel_command(binary_path, socket_path=socket_path)return {"command_prefix": tailscale_socket_args(socket_path)}class TailscaleTunnel(CliTunnelHelper):def __init__(self, port, notify=None):target = f"http://127.0.0.1:{port}"+ self._announced_login_urls = set()super().__init__(label="Tailscale Funnel",binary="tailscale",port=port,- command=["tailscale", "funnel", "--yes", target],+ command=[+ "tailscale",+ "funnel",+ "--yes",+ f"--https={TAILSCALE_FUNNEL_HTTPS_PORT}",+ target,+ ],url_pattern=TAILSCALE_URL_RE,missing_binary_message=("Tailscale could not be prepared in this environment. Install ""Tailscale, make sure the `tailscaled` service is available to ""this container, enable Funnel for the tailnet, then try again."),- shutdown_command=["tailscale", "funnel", "--yes", target, "off"],+ shutdown_command=[+ "tailscale",+ "funnel",+ "--yes",+ f"--https={TAILSCALE_FUNNEL_HTTPS_PORT}",+ target,+ "off",+ ],+ timeout=TAILSCALE_FUNNEL_TIMEOUT,binary_resolver=lambda notify_callback: install_tailscale(notify=notify_callback),preflight=ensure_tailscale_ready,+ output_handler=self._handle_tailscale_output,notify=notify,)+ def _handle_tailscale_output(self, line, notify=None):+ login_match = TAILSCALE_LOGIN_URL_RE.search(line)+ if not login_match:+ return+ login_url = login_match.group(0).rstrip(".,)")+ if login_url in self._announced_login_urls:+ return+ self._announced_login_urls.add(login_url)+ notify_info(+ notify,+ "Open the Tailscale approval link to finish sign-in or enable Funnel. "+ "Agent Zero will continue when Tailscale reports the public URL.",+ {"provider": "tailscale", "url": login_url},+ )+def stop(self):try:return super().stop()diff --git a/tests/test_tunnel_remote_link.py b/tests/test_tunnel_remote_link.pyindex 0e8fdbdf4..5027fc29f 100644--- a/tests/test_tunnel_remote_link.py+++ b/tests/test_tunnel_remote_link.py@@ -146,7 +146,8 @@ def test_remote_link_provider_options_match_supported_remote_link_providers():assert '<option value="serveo">Serveo</option>' in htmlassert '<option value="cloudflared">Cloudflare</option>' not in htmlassert "Cloudflare Tunnel is the quickest shareable URL" in html- assert "Agent Zero will start its sign-in flow" in html+ assert "Tailscale Funnel creates a public HTTPS URL" in html+ assert "approve sign-in or Funnel access" in htmldef test_tunnel_provider_normalization_preserves_aliases(tunnel_manager_module):@@ -162,6 +163,7 @@ def test_tunnel_provider_normalization_preserves_aliases(tunnel_manager_module):def test_tailscale_cli_commands_are_wired(tunnel_manager_module):manager = tunnel_manager_module.TunnelManager()+ modules = remote_link_modules()tailscale = manager._create_tunnel(50001, "tailscale")@@ -169,15 +171,18 @@ def test_tailscale_cli_commands_are_wired(tunnel_manager_module):"tailscale","funnel","--yes",+ "--https=443","http://127.0.0.1:50001",]assert tailscale.shutdown_command == ["tailscale","funnel","--yes",+ "--https=443","http://127.0.0.1:50001","off",]+ assert tailscale.timeout == modules.tailscale.TAILSCALE_FUNNEL_TIMEOUTdef test_remote_link_providers_have_dedicated_helper_modules():@@ -523,6 +528,15 @@ def test_tailscale_preflight_starts_managed_daemon_then_runs_up_with_socket(return next(status_results)monkeypatch.setattr(modules.tailscale, "tailscale_status", fake_status)+ monkeypatch.setattr(+ modules.tailscale,+ "tailscale_funnel_help",+ lambda binary_path, socket_path=None: types.SimpleNamespace(+ returncode=0,+ stdout="USAGE\n tailscale funnel <target>",+ stderr="",+ ),+ )popen_commands = []class FakeProcess:@@ -651,6 +665,15 @@ def test_tailscale_preflight_runs_up_then_accepts_running_status("tailscale_status",lambda binary_path, socket_path=None: next(status_results),)+ monkeypatch.setattr(+ modules.tailscale,+ "tailscale_funnel_help",+ lambda binary_path, socket_path=None: types.SimpleNamespace(+ returncode=0,+ stdout="USAGE\n tailscale funnel <target>",+ stderr="",+ ),+ )class FakeProcess:stdout = iter(["Success.\n"])@@ -681,6 +704,110 @@ def test_tailscale_preflight_runs_up_then_accepts_running_status(}+def test_tailscale_preflight_rejects_clients_without_funnel(+ tunnel_manager_module,+ monkeypatch,+):+ modules = remote_link_modules()+ monkeypatch.setattr(+ modules.tailscale,+ "tailscale_status",+ lambda binary_path, socket_path=None: types.SimpleNamespace(+ returncode=0,+ stdout='{"BackendState": "Running"}',+ stderr="",+ ),+ )+ monkeypatch.setattr(+ modules.tailscale,+ "tailscale_funnel_help",+ lambda binary_path, socket_path=None: types.SimpleNamespace(+ returncode=1,+ stdout="",+ stderr="unknown command: funnel",+ ),+ )++ with pytest.raises(RuntimeError, match="does not support `tailscale funnel`"):+ modules.tailscale.ensure_tailscale_ready("/tmp/tailscale")+++def test_tailscale_funnel_command_surfaces_approval_url(+ tunnel_manager_module,+ monkeypatch,+):+ modules = remote_link_modules()+ popen_commands = []+ notifications = []+ monkeypatch.setattr(+ modules.tailscale,+ "install_tailscale",+ lambda notify=None: "/tmp/tailscale",+ )+ monkeypatch.setattr(+ modules.tailscale,+ "ensure_tailscale_ready",+ lambda binary_path, notify=None: {+ "command_prefix": ["--socket", "/tmp/tailscaled.sock"]+ },+ )++ class FakeProcess:+ def __init__(self, command, **kwargs):+ popen_commands.append(command)+ self.stdout = iter([+ "Visit https://login.tailscale.com/a/funnel-approval to enable Funnel\n",+ "Available on the internet:\n",+ "https://agent-zero.example.ts.net\n",+ ])++ def poll(self):+ return None++ def wait(self, timeout=None):+ return 0++ monkeypatch.setattr(modules.cli.subprocess, "Popen", FakeProcess)++ tunnel = modules.tailscale.TailscaleTunnel(+ 50001,+ notify=lambda event, message, data=None: notifications.append({+ "event": event.value,+ "message": message,+ "data": data,+ }),+ )++ assert tunnel.start() == "https://agent-zero.example.ts.net"+ assert popen_commands == [+ [+ "/tmp/tailscale",+ "--socket",+ "/tmp/tailscaled.sock",+ "funnel",+ "--yes",+ "--https=443",+ "http://127.0.0.1:50001",+ ]+ ]+ assert {+ "event": "info",+ "message": (+ "Open the Tailscale approval link to finish sign-in or enable Funnel. "+ "Agent Zero will continue when Tailscale reports the public URL."+ ),+ "data": {+ "provider": "tailscale",+ "url": "https://login.tailscale.com/a/funnel-approval",+ },+ } in notifications+ assert notifications[-1] == {+ "event": "tunnel_url",+ "message": "Tailscale Funnel URL is ready",+ "data": {"url": "https://agent-zero.example.ts.net"},+ }++def test_cli_tunnel_preflight_prefix_is_used_for_start_and_shutdown(tunnel_manager_module,monkeypatch,diff --git a/webui/components/settings/tunnel/tunnel-section.html b/webui/components/settings/tunnel/tunnel-section.htmlindex 6dc0b3e5f..806060c17 100644--- a/webui/components/settings/tunnel/tunnel-section.html+++ b/webui/components/settings/tunnel/tunnel-section.html@@ -36,7 +36,7 @@<div class="field-label"><div class="field-title">Link provider</div><div class="field-description">- Cloudflare Tunnel is the quickest shareable URL. Tailscale is private to your tailnet and Agent Zero will start its sign-in flow when needed. Microsoft Dev Tunnels may ask you to approve a GitHub device login.+ Cloudflare Tunnel is the quickest shareable URL. Tailscale Funnel creates a public HTTPS URL after this container joins your tailnet and may ask you to approve sign-in or Funnel access. Microsoft Dev Tunnels may ask you to approve a GitHub device login.</div></div><div class="field-control">diff --git a/webui/components/settings/tunnel/tunnel-store.js b/webui/components/settings/tunnel/tunnel-store.jsindex 5e93d137a..25bd2dc0a 100644--- a/webui/components/settings/tunnel/tunnel-store.js+++ b/webui/components/settings/tunnel/tunnel-store.js@@ -47,7 +47,7 @@ const model = {get loginActionCopy() {if (this.loginProvider === "tailscale") {- return "Open the Tailscale login link and approve this container. Agent Zero will continue when Tailscale finishes setup.";+ return "Open the Tailscale link to approve this container or enable Funnel. Agent Zero will continue when Tailscale reports the public URL.";}return "Approve the tunnel request, then Agent Zero will finish enabling Remote Control.";},@@ -103,7 +103,7 @@ const model = {this.microsoftLoginCode = n.data.code || "";this.microsoftLoginUrl = n.data.url || "";this.loadingText = this.loginProvider === "tailscale"- ? "Waiting for Tailscale login..."+ ? "Waiting for Tailscale approval...": "Waiting for Microsoft login...";} else {this.loadingText = n.message;