Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions pkgs/fleet/laptop-agent-broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,8 @@ def broker_tunnel_socket(port, timeout_s=None):
"""Broker-local CONNECT tunnel establishment (#9611 acceptance 2).

Same wire behaviour as la.tunnel_socket (credential read from the
HTTPS_PROXY env and sent only inside the CONNECT request), but
seat's recorded tailnet proxy when one exists, else the HTTPS_PROXY
env, and sent only inside the CONNECT request), but
with a hard bounded timeout and ordinary exceptions: the client's
tunnel_socket can block up to 60 s waiting for the CONNECT response
and raises SystemExit on a closed proxy — inside a broker thread
Expand All @@ -143,7 +144,14 @@ def broker_tunnel_socket(port, timeout_s=None):
surfaces as a fast, logged OSError instead."""
import base64
import urllib.parse
raw = os.environ.get("HTTPS_PROXY")
# The recorded tailnet proxy beats the ambient env (#12426): a
# broker auto-started from a sandbox shell otherwise inherits the
# platform egress proxy and every tunnel fails while it looks
# alive. la is the deployed client; an older copy without the
# resolver leaves the ambient env in charge.
resolver = getattr(la, "tailnet_https_proxy", None)
raw = (resolver() if resolver is not None else None) \
or os.environ.get("HTTPS_PROXY")
if not raw:
raise OSError("HTTPS_PROXY must be set")
u = urllib.parse.urlparse(raw)
Expand Down
102 changes: 99 additions & 3 deletions pkgs/fleet/laptop-agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
(`cloudflare.access-laptop-agent`, Bitwarden-backed; migrated from the
0600 file 2026-11-16, Drew-approved). Fallback transport: the
VM's tailnet tunnel proxy (HTTP CONNECT, same construction as
laptop-proxy-connect.py; the proxy credential is read from HTTPS_PROXY
and sent only inside the CONNECT request), used automatically when the
laptop-proxy-connect.py; the proxy credential is read from the seat's
recorded tailnet proxy (fleet-proxy.env) when one exists, else from
HTTPS_PROXY, and sent only inside the CONNECT request), used automatically when the
Cloudflare path fails and directly for /exec calls whose budget exceeds
the Cloudflare edge's ~100 s response cap. The agent token lives in
~/tools/laptop-agent-token (mode 600) and is sent as a header — never
Expand Down Expand Up @@ -250,11 +251,106 @@ def _log_trip(trip, path, total_ms, status, t_sent_ms=None,
pass


# --- recorded tailnet proxy (code#12426, mirroring #12645) -------------
# In userspace mode the seat bootstrap writes the tailnet proxy URL to
# fleet-proxy.env beside tailscaled's node state. Tailnet CONNECTs use
# that recorded proxy in place of the ambient HTTPS_PROXY: a process
# started from a sandbox shell carries the platform egress proxy there,
# and tailnet tunnels through it fail while the process looks healthy.
# The Cloudflare leg keeps the ambient proxy by design (it is the
# internet egress). A kernel-mode seat has no file (the bootstrap
# removes it), so the ambient env stays in charge there. The candidate
# order, slug rule and parse rule mirror fleet-config's
# tailnet_https_proxy (pkgs/fleet/crates/fleet-config/src/lib.rs).

TAILNET_PROXY_ENV_FILE = "fleet-proxy.env"


def _agent_slug(agent):
"""The bootstrap's agent slug: lower-cased, every character outside
[a-z0-9-] replaced by '-', leading and trailing dashes trimmed, cut
to 55 characters, then one 'muse-' prefix dropped. None when
nothing is left, as the bootstrap refuses such a name."""
mapped = "".join(
c if ("a" <= c <= "z" or "0" <= c <= "9" or c == "-") else "-"
for c in agent.lower()
)
slug = mapped.strip("-")[:55]
if slug.startswith("muse-"):
slug = slug[len("muse-"):]
return slug or None


def _tailnet_proxy_env_candidates(home, fleet_agent, explicit):
"""Where to look for the recorded tailnet proxy env, most specific
first: an explicit $FLEET_PROXY_ENV path, then the named agent's
isolated node state (~/.local/state/tailscale/agents/<slug>), then
the legacy shared node state (~/.local/state/tailscale). Pure over
its inputs so the order is testable."""
out = []
if explicit:
p = Path(explicit)
out.append(p if p.is_absolute() else home / p)
state = home / ".local" / "state" / "tailscale"
if fleet_agent:
slug = _agent_slug(fleet_agent)
if slug:
out.append(state / "agents" / slug / TAILNET_PROXY_ENV_FILE)
out.append(state / TAILNET_PROXY_ENV_FILE)
return out


def _parse_tailnet_proxy_env(text):
"""The HTTPS_PROXY value an env file sets, from a line of the form
[export ]HTTPS_PROXY=value (the value optionally in matching single
or double quotes). The last such line with a value wins, as it
would when the file is sourced."""
value = None
for line in text.splitlines():
line = line.strip()
if line.startswith("export "):
line = line[len("export "):].lstrip()
if not line.startswith("HTTPS_PROXY="):
continue
v = line[len("HTTPS_PROXY="):].strip()
if len(v) >= 2 and v[0] == v[-1] and v[0] in "\"'":
v = v[1:-1]
if v:
value = v
return value


def tailnet_https_proxy():
"""The seat's recorded tailnet proxy: the first readable
fleet-proxy.env among the candidates that sets HTTPS_PROXY.
None (no file, as on a kernel-mode seat) leaves the ambient env
in charge."""
for path in _tailnet_proxy_env_candidates(
Path.home(),
os.environ.get("FLEET_AGENT"),
os.environ.get("FLEET_PROXY_ENV"),
):
try:
text = path.read_text()
except OSError:
continue
value = _parse_tailnet_proxy_env(text)
if value:
return value
return None


def tailnet_proxy_url():
"""The proxy URL for a tailnet CONNECT: the recorded tailnet proxy
when the seat has one, else the ambient HTTPS_PROXY."""
return tailnet_https_proxy() or os.environ.get("HTTPS_PROXY")


def tunnel_socket(port=None):
import base64
import urllib.parse
port = port or TARGET_PORT
raw = os.environ.get("HTTPS_PROXY")
raw = tailnet_proxy_url()
if not raw:
sys.exit("laptop-agent: HTTPS_PROXY must be set")
u = urllib.parse.urlparse(raw)
Expand Down
206 changes: 206 additions & 0 deletions pkgs/fleet/tests/test_tailnet_proxy_env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
#!/usr/bin/env python3
"""Tests for laptop-agent.py's recorded tailnet proxy resolution
(code#12426 — the Python mirror of fleet-config's #12645 rule: the
seat's recorded fleet-proxy.env beats the ambient HTTPS_PROXY for
tailnet CONNECTs).

Run with: python3 -m unittest discover -s pkgs/fleet/tests
"""

import importlib.util
import os
import socket
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch

CLIENT = Path(__file__).resolve().parents[1] / "laptop-agent.py"


def _load_client():
spec = importlib.util.spec_from_file_location("laptop_agent_client", CLIENT)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod


la = _load_client()


class AgentSlugTest(unittest.TestCase):
"""Same cases as fleet-config's agent_slug_matches_the_bootstrap_rule."""

def test_cases(self):
self.assertEqual(la._agent_slug("felix"), "felix")
self.assertEqual(la._agent_slug("Muse Felix"), "felix")
self.assertEqual(la._agent_slug("muse-archer"), "archer")
self.assertEqual(la._agent_slug("-a_b-"), "a-b")
self.assertEqual(la._agent_slug("muse-"), "muse")
self.assertIsNone(la._agent_slug(""))
self.assertEqual(len(la._agent_slug("x" * 80)), 55)


class CandidatesTest(unittest.TestCase):
"""Same order as fleet-config's
tailnet_proxy_env_candidates_follow_the_bootstrap_layout."""

def test_order(self):
home = Path("/home/a")
state = home / ".local/state/tailscale"
self.assertEqual(
la._tailnet_proxy_env_candidates(home, None, None),
[state / "fleet-proxy.env"],
)
self.assertEqual(
la._tailnet_proxy_env_candidates(home, "Muse-Felix", "x/p.env"),
[
home / "x/p.env",
state / "agents/felix/fleet-proxy.env",
state / "fleet-proxy.env",
],
)
# A name with nothing usable gets no agent path.
self.assertEqual(
la._tailnet_proxy_env_candidates(home, "--", None),
[state / "fleet-proxy.env"],
)


class ParseTest(unittest.TestCase):
"""Same cases as fleet-config's
parse_tailnet_proxy_env_reads_the_bootstrap_line."""

def test_cases(self):
self.assertEqual(
la._parse_tailnet_proxy_env("export HTTPS_PROXY=http://127.0.0.1:3130\n"),
"http://127.0.0.1:3130",
)
self.assertEqual(
la._parse_tailnet_proxy_env(
"# c\nHTTPS_PROXY='http://a:1'\nexport HTTPS_PROXY=\"http://b:2\"\n"
),
"http://b:2",
)
self.assertIsNone(la._parse_tailnet_proxy_env("HTTPS_PROXY=\n"))
self.assertIsNone(la._parse_tailnet_proxy_env("OTHER=1\n"))


class ResolveTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.home = Path(self.tmp.name)
self.state = self.home / ".local/state/tailscale"
self.state.mkdir(parents=True)
env = {"HOME": str(self.home)}
self.env_patch = patch.dict(os.environ, env, clear=False)
self.env_patch.start()
for key in ("FLEET_AGENT", "FLEET_PROXY_ENV"):
os.environ.pop(key, None)

def tearDown(self):
self.env_patch.stop()
self.tmp.cleanup()

def _write(self, path, text):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)

def test_no_file_leaves_ambient_in_charge(self):
self.assertIsNone(la.tailnet_https_proxy())

def test_shared_file(self):
self._write(
self.state / "fleet-proxy.env",
"export HTTPS_PROXY=http://127.0.0.1:3130\n",
)
self.assertEqual(la.tailnet_https_proxy(), "http://127.0.0.1:3130")

def test_agent_file_beats_shared(self):
self._write(
self.state / "fleet-proxy.env",
"export HTTPS_PROXY=http://127.0.0.1:3130\n",
)
self._write(
self.state / "agents/felix/fleet-proxy.env",
"export HTTPS_PROXY=http://127.0.0.1:9999\n",
)
with patch.dict(os.environ, {"FLEET_AGENT": "Muse Felix"}):
self.assertEqual(la.tailnet_https_proxy(), "http://127.0.0.1:9999")

def test_explicit_path_beats_both(self):
self._write(
self.state / "fleet-proxy.env",
"export HTTPS_PROXY=http://127.0.0.1:3130\n",
)
explicit = self.home / "elsewhere.env"
self._write(explicit, "export HTTPS_PROXY=http://127.0.0.1:7777\n")
with patch.dict(os.environ, {"FLEET_PROXY_ENV": str(explicit)}):
self.assertEqual(la.tailnet_https_proxy(), "http://127.0.0.1:7777")


class _FakeSocket:
def __init__(self):
self._resp = b"HTTP/1.1 200 OK\r\n\r\n"
self.sent = b""

def sendall(self, data):
self.sent += data

def recv(self, _n):
if not self._resp:
return b""
out, self._resp = self._resp[:1], self._resp[1:]
return out

def settimeout(self, _t):
pass


class TunnelSocketPreferenceTest(unittest.TestCase):
"""The tailnet CONNECT goes to the recorded proxy when one exists,
and to the ambient proxy's host otherwise."""

def _run(self, env):
fake = _FakeSocket()
calls = []

def fake_create_connection(addr, timeout=None):
calls.append(addr)
return fake

with patch.dict(os.environ, env, clear=False):
for key in ("FLEET_AGENT", "FLEET_PROXY_ENV"):
if key not in env:
os.environ.pop(key, None)
with patch.object(socket, "create_connection", fake_create_connection):
la.tunnel_socket()
return calls

def test_recorded_proxy_wins_over_ambient_egress(self):
with tempfile.TemporaryDirectory() as td:
home = Path(td)
env_file = home / "fleet-proxy.env"
env_file.write_text("export HTTPS_PROXY=http://127.0.0.1:3130\n")
calls = self._run(
{
"HOME": str(home),
"FLEET_PROXY_ENV": str(env_file),
"HTTPS_PROXY": "http://broker:broker@hatch-egress-proxy:3128",
}
)
self.assertEqual(calls, [("127.0.0.1", 3130)])

def test_ambient_used_when_no_recorded_proxy(self):
with tempfile.TemporaryDirectory() as td:
calls = self._run(
{
"HOME": str(Path(td)),
"HTTPS_PROXY": "http://broker:broker@127.0.0.1:3130",
}
)
self.assertEqual(calls, [("127.0.0.1", 3130)])


if __name__ == "__main__":
unittest.main()