@finalai/final-agent-provider 0.4.1 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/sandboxes/egress-bootstrap.ts"],
4
- "sourcesContent": ["// The same controller runs in ordinary Linux provider namespaces; no VM platform API is used.\nexport const workspaceEgressBootstrap = String.raw`import collections, errno, fcntl, hashlib, ipaddress, json, os, pathlib, platform, re, shutil, signal, shlex, socket, stat, struct, subprocess, sys, tempfile, threading, time, urllib.parse, uuid\n\nROOT = pathlib.Path('/run/final-workspace-egress')\nPERSISTENT = pathlib.Path('/var/lib/final-workspace-egress')\nRESOLVER = pathlib.Path('/etc/resolv.conf')\nHOSTS = pathlib.Path('/etc/hosts')\nCHAIN = 'FINAL-EGRESS'\nREPLY = 'FINAL-EGRESS-REPLY'\nFORWARD = 'FINAL-EGRESS-FWD'\nNAT = 'FINAL-EGRESS-NAT'\nMARK = '0x80000/0xff0000'\nos.environ['PATH'] = '/usr/sbin:/usr/bin:/sbin:/bin'\nos.environ.pop('SSL_CERT_FILE', None)\nos.environ.pop('SSL_CERT_DIR', None)\n# Prime autoload before choosing families; later kernel enablement requires reinitialization.\ntry: socket.socket(socket.AF_INET6, socket.SOCK_DGRAM).close()\nexcept OSError as failure:\n if failure.errno not in (errno.EAFNOSUPPORT, errno.EPROTONOSUPPORT, errno.EPERM, errno.EACCES): raise\nFAMILIES = ('iptables', 'ip6tables') if pathlib.Path('/proc/net/if_inet6').exists() else ('iptables',)\n\nclass WorkspaceConflictError(RuntimeError):\n pass\n\nclass PrerequisiteError(RuntimeError):\n pass\n\nclass DenialUnavailableError(RuntimeError):\n pass\n\nclass EnrollmentLostError(RuntimeError):\n pass\n\n\ndef command(*args, check=True, timeout=25):\n if args[0] in ('iptables', 'ip6tables') and '--version' not in args: args = (args[0], '-w', '5', *args[1:])\n result = subprocess.run(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)\n if check and result.returncode != 0:\n raise RuntimeError('Workspace networking command failed: ' + ' '.join(args[:4]))\n return result\n\ndef atomic(path, value, binary=False, mode=0o600):\n staged = None\n try:\n with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as out:\n staged = pathlib.Path(out.name)\n out.write(value if binary else json.dumps(value).encode())\n out.flush(); os.fsync(out.fileno())\n os.chmod(staged, mode)\n os.replace(staged, path)\n directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)\n try: os.fsync(directory)\n finally: os.close(directory)\n finally:\n if staged is not None: staged.unlink(missing_ok=True)\n\ndef managed_text(path, content):\n data = content.encode()\n try: atomic(path, data, binary=True, mode=0o644)\n except OSError as failure:\n if failure.errno != errno.EBUSY: raise\n # Docker bind-mounted files cannot be replaced; never follow a raced-in symlink.\n pending = PERSISTENT / 'resolver-write-pending.json' if path == RESOLVER else None\n if pending is not None: atomic(pending, True)\n fd = os.open(path, os.O_WRONLY | os.O_NOFOLLOW | os.O_NONBLOCK)\n with os.fdopen(fd, 'wb') as out:\n if not stat.S_ISREG(os.fstat(out.fileno()).st_mode): raise RuntimeError('Managed network file must be regular')\n os.ftruncate(out.fileno(), 0)\n out.write(data); out.flush(); os.fsync(out.fileno())\n if pending is not None: pending.unlink(missing_ok=True)\n\ndef load(path, default=None):\n try:\n return json.loads(path.read_text())\n except FileNotFoundError:\n return default\n\ndef prerequisite(action):\n if sys.version_info < (3, 8):\n raise PrerequisiteError('Device egress requires Python 3.8 or newer')\n if sys.platform != 'linux' or os.geteuid() != 0:\n raise PrerequisiteError('Device egress requires an isolated Linux workspace with privileged networking access')\n ROOT.mkdir(mode=0o700, exist_ok=True)\n if ROOT.is_symlink() or ROOT.stat().st_uid != 0:\n raise RuntimeError('Workspace egress state must be a root-owned directory')\n ROOT.chmod(0o700)\n direct = not load(ROOT / 'config.json') or (load(ROOT / 'config.json', {}).get('mode') == 'direct' and load(ROOT / 'status.json', {}).get('mode') == 'direct')\n if action in ('status', 'artifact', 'claim', 'unlock') or (action == 'disable' and (direct or load(ROOT / 'config.json', {}).get('noNetworkChanges') is True)): return\n if action in ('configure', 'renew') and not pathlib.Path('/dev/net/tun').exists():\n raise PrerequisiteError('This sandbox provider does not expose /dev/net/tun')\n command('ip', '-V')\n for family in FAMILIES:\n command(family, '--version'); command(family + '-restore', '--version')\n\nBOOT_ID = pathlib.Path('/proc/sys/kernel/random/boot_id').read_text().strip()\n\ndef existing_control_replies():\n saved = load(ROOT / 'control-replies.json')\n sockets = []\n for table in ('tcp', 'tcp6'):\n def address(value):\n host, port = value.split(':')\n raw = bytes.fromhex(host)\n raw = b''.join(raw[i:i+4][::-1] for i in range(0, len(raw), 4))\n ip = ipaddress.ip_address(raw)\n if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None: ip = ip.ipv4_mapped\n return str(ip), int(port, 16)\n source = pathlib.Path('/proc/net/' + table)\n if not source.exists(): continue\n for line in source.read_text().splitlines()[1:]:\n columns = line.split()\n if columns[3] in ('01', '0A'): sockets.append((address(columns[1]), address(columns[2]), columns[3], int(columns[7])))\n addresses = json.loads(command('ip', '-j', 'addr', 'show').stdout)\n local_addresses = {ipaddress.ip_address(address['local']) for interface in addresses for address in interface.get('addr_info', [])}\n bridge_networks = [ipaddress.ip_network(network) for _, network in local_bridges()]\n listeners = [local for local, remote, state, uid in sockets if state == '0A' and not ipaddress.ip_address(local[0]).is_loopback]\n replies = []\n for local, remote, state, uid in sockets:\n # Only privileged provider sockets may use the pre-conntrack compatibility exception.\n remote_ip = ipaddress.ip_address(remote[0])\n if uid != 0 or state != '01' or remote_ip.is_loopback or remote_ip in local_addresses: continue\n if any(remote_ip.version == network.version and remote_ip in network for network in bridge_networks): continue\n if any(port == local[1] and (ipaddress.ip_address(host).is_unspecified or host == local[0]) for host, port in listeners):\n replies.append({'source': local[0], 'sourcePort': local[1], 'destination': remote[0], 'destinationPort': remote[1], 'uid': 0})\n if saved is not None and any(reply.get('uid') != 0 for reply in saved): saved = None\n capture_overflow = saved is None and len(replies) > 128\n if saved is not None: replies = saved\n server_ports = [{'source': host, 'sourcePort': port} for host, port in listeners]\n for prior in load(ROOT / 'control-listeners.json', []):\n if any(local[1] == prior['sourcePort'] and state == '01' for local, remote, state, uid in sockets): server_ports.append(prior)\n # A dual-stack listener appears in tcp6 even when the accepted transport uses IPv4.\n server_ports += [{'source': reply['source'], 'sourcePort': reply['sourcePort']} for reply in replies]\n server_ports = [dict(source=host, sourcePort=port) for host, port in sorted({(item['source'], item['sourcePort']) for item in server_ports})]\n prior = load(ROOT / 'control-listeners.json', [])\n privileged = {local for local, remote, state, uid in sockets if state == '0A' and uid == 0}\n server_ports.sort(key=lambda item: (item not in prior, (item['source'], item['sourcePort']) not in privileged))\n atomic(ROOT / 'control-listeners.json', server_ports[:256])\n if len(server_ports) > 256:\n atomic(ROOT / 'listener-limit.json', {'limit': 256, 'observed': len(server_ports)})\n else: (ROOT / 'listener-limit.json').unlink(missing_ok=True)\n if capture_overflow: raise RuntimeError('Too many existing inbound control connections')\n atomic(ROOT / 'control-replies.json', replies)\n return replies\n\ndef local_bridges():\n result = []\n # Minimal VM kernels can reject a type-filtered dump; ordinary link dumps remain portable.\n links = json.loads(command('ip', '-j', '-d', 'link', 'show').stdout)\n by_name = {link['ifname']: link for link in links}\n uplinks = set()\n for route in json.loads(command('ip', '-j', '-4', 'route', 'show', 'table', 'all').stdout):\n if route.get('dst') == 'default' or route.get('gateway') is not None or route.get('nexthops'):\n uplinks.add(route.get('dev'))\n uplinks.update(hop.get('dev') for hop in route.get('nexthops', []))\n for link in links:\n if link.get('linkinfo', {}).get('info_kind') != 'bridge': continue\n try: members = list((pathlib.Path('/sys/class/net') / link['ifname'] / 'brif').iterdir())\n except FileNotFoundError: continue\n if link['ifname'] in uplinks or any(member.name in uplinks or by_name.get(member.name, {}).get('linkinfo', {}).get('info_kind') != 'veth' for member in members): continue\n name = link['ifname']\n if not re.fullmatch(r'[A-Za-z0-9_.-]{1,15}', name): raise RuntimeError('Unsupported local bridge name')\n for interface in json.loads(command('ip', '-j', '-4', 'addr', 'show', 'dev', name).stdout):\n for address in interface.get('addr_info', []):\n if address.get('family') == 'inet': result.append((name, str(ipaddress.ip_network(address['local'] + '/' + str(address['prefixlen']), strict=False))))\n return sorted(result)\n\ndef install_guard(allow_tunnel=False, closed=False):\n if closed: allow_tunnel = False\n replies = [reply for reply in load(ROOT / 'control-replies.json', []) if reply.get('uid') == 0] if closed else existing_control_replies()\n bridges = [] if closed else local_bridges()\n try: listeners = load(ROOT / 'control-listeners.json', [])\n except Exception:\n if not closed: raise\n listeners = []\n if closed: tunnel_addresses = load(ROOT / 'tunnel-addresses.json', [])\n else:\n tunnel = command('ip', '-j', 'addr', 'show', 'dev', 'final-egress0', check=False)\n tunnel_addresses = [str(ipaddress.ip_address(address['local'])) for interface in json.loads(tunnel.stdout or b'[]') for address in interface.get('addr_info', [])]\n atomic(ROOT / 'tunnel-addresses.json', tunnel_addresses)\n for family in FAMILIES:\n rules = ['*filter', ':' + CHAIN + ' - [0:0]', '-F ' + CHAIN]\n # Block namespace-local DNS stubs that would otherwise resolve on the provider's network.\n for proto in ('tcp', 'udp'):\n rules.append('-A ' + CHAIN + ' -o lo -p ' + proto + ' --dport 53 -j REJECT')\n if family == 'iptables':\n rules.append('-A ' + CHAIN + ' -d 127.0.0.11 -j REJECT')\n rules.append('-A ' + CHAIN + ' -d 100.100.100.100 -j REJECT')\n rules += ['-A ' + CHAIN + ' -o lo -j ACCEPT', '-A ' + CHAIN + ' -m mark --mark ' + MARK + ' -m owner --uid-owner 0 -j ACCEPT', '-A ' + CHAIN + ' -m mark --mark ' + MARK + ' -m conntrack --ctdir REPLY -j ACCEPT']\n if family == 'ip6tables':\n for kind in (133, 134, 135, 136):\n rules += ['-A ' + CHAIN + ' -p ipv6-icmp --icmpv6-type ' + str(kind) + ' -m owner --uid-owner 1-4294967294 -j REJECT',\n '-A ' + CHAIN + ' -p ipv6-icmp --icmpv6-type ' + str(kind) + ' -j ACCEPT']\n if family == 'iptables':\n for name, network in bridges: rules.append('-A ' + CHAIN + ' -o ' + name + ' -d ' + network + ' -j ACCEPT')\n if family == 'iptables' and allow_tunnel:\n rules.append('-A ' + CHAIN + ' -o final-egress0 -j ACCEPT')\n if closed:\n for reply in replies:\n if (':' in reply['source']) != (family == 'ip6tables'): continue\n rules.append('-A ' + CHAIN + ' -p tcp -s ' + reply['source'] + ' --sport ' + str(reply['sourcePort']) + ' -d ' + reply['destination'] + ' --dport ' + str(reply['destinationPort']) + ' --tcp-flags SYN,RST,ACK ACK -j ACCEPT')\n rules += ['-A ' + CHAIN + ' -j REJECT', 'COMMIT', '*mangle', ':' + REPLY + ' - [0:0]', '-F ' + REPLY,\n # Docker rewrites its DNS stub's port in nat/OUTPUT; block before that translation.\n '-A ' + REPLY + ' -o lo -p tcp --dport 53 -j DROP',\n '-A ' + REPLY + ' -o lo -p udp --dport 53 -j DROP',\n ]\n if family == 'iptables': rules.append('-A ' + REPLY + ' -d 127.0.0.11 -j DROP')\n # mangle/OUTPUT sees the initial exit route even for physical provider replies.\n # Exclude only the actual tunnel source addresses before marking server replies.\n for address in tunnel_addresses:\n if (':' in address) == (family == 'ip6tables'):\n rules.append('-A ' + REPLY + ' -s ' + address + ' -j RETURN')\n # Minimal provider kernels omit connmark. Reserve the existing server ports for TCP replies;\n # an untracked outgoing client's ephemeral port cannot obtain this exception.\n for listener in listeners:\n host = listener['source']\n address = ipaddress.ip_address(host)\n if (':' in host) != (family == 'ip6tables') and not (family == 'iptables' and address.version == 6 and address.is_unspecified): continue\n source = '' if ipaddress.ip_address(host).is_unspecified else ' -s ' + host\n rules.append('-A ' + REPLY + ' -p tcp' + source + ' --sport ' + str(listener['sourcePort']) +\n ' -m conntrack --ctdir REPLY --ctorigdstport ' + str(listener['sourcePort']) + ' -j MARK --set-xmark ' + MARK)\n # Conntrack can load after a provider's long-lived inbound RPC already opened (E2B envd).\n # Preserve only ACKs on those accepted server sockets, never a new outbound SYN.\n for reply in replies:\n if (':' in reply['source']) != (family == 'ip6tables'): continue\n rules.append('-A ' + REPLY + ' -p tcp -s ' + reply['source'] + ' --sport ' + str(reply['sourcePort']) +\n ' -d ' + reply['destination'] + ' --dport ' + str(reply['destinationPort']) +\n ' --tcp-flags SYN,RST,ACK ACK -j MARK --set-xmark ' + MARK)\n rules.append('COMMIT')\n # Docker can prepend filter/FORWARD accepts; mangle runs before that table.\n rules += ['*mangle', ':' + FORWARD + ' - [0:0]', '-F ' + FORWARD]\n if family == 'iptables': rules.append('-A ' + FORWARD + ' -d 100.100.100.100 -j DROP')\n if family == 'iptables':\n for name, network in bridges:\n for ingress, _ in bridges: rules.append('-A ' + FORWARD + ' -i ' + ingress + ' -o ' + name + ' -d ' + network + ' -j RETURN')\n if family == 'iptables' and allow_tunnel:\n for name, network in bridges:\n rules += ['-A ' + FORWARD + ' -i ' + name + ' -s ' + network + ' -o final-egress0 -j RETURN',\n '-A ' + FORWARD + ' -i final-egress0 -o ' + name + ' -d ' + network + ' -m conntrack --ctstate ESTABLISHED,RELATED -j RETURN']\n rules += ['-A ' + FORWARD + ' -j DROP', 'COMMIT']\n rules += ['*filter', ':' + FORWARD + ' - [0:0]', '-F ' + FORWARD]\n if family == 'iptables': rules.append('-A ' + FORWARD + ' -d 100.100.100.100 -j DROP')\n if family == 'iptables':\n for name, network in bridges:\n for ingress, _ in bridges: rules.append('-A ' + FORWARD + ' -i ' + ingress + ' -o ' + name + ' -d ' + network + ' -j RETURN')\n if family == 'iptables' and allow_tunnel:\n for name, network in bridges:\n rules += ['-A ' + FORWARD + ' -i ' + name + ' -s ' + network + ' -o final-egress0 -j ACCEPT',\n '-A ' + FORWARD + ' -i final-egress0 -o ' + name + ' -d ' + network + ' -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT']\n rules += ['-A ' + FORWARD + ' -j REJECT', 'COMMIT']\n if family == 'iptables':\n rules += ['*nat', ':' + NAT + ' - [0:0]', '-F ' + NAT]\n for name, network in bridges:\n rules.append('-A ' + NAT + ' -s ' + network + ' -o final-egress0 -j MASQUERADE')\n rules.append('COMMIT')\n installed = subprocess.run([family + '-restore', '-w', '5', '--noflush'], timeout=25, input=('\\n'.join(rules) + '\\n').encode(), stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)\n if installed.returncode: raise RuntimeError(family + ' firewall installation failed: ' + installed.stderr.decode(errors='replace')[:800])\n hooks = [('mangle', 'OUTPUT', REPLY), ('mangle', 'FORWARD', FORWARD), ('filter', 'OUTPUT', CHAIN), ('filter', 'FORWARD', FORWARD)]\n if family == 'iptables': hooks.append(('nat', 'POSTROUTING', NAT))\n for table, hook, chain in hooks:\n if command(family, '-t', table, '-C', hook, '-j', chain, check=False).returncode != 0:\n command(family, '-t', table, '-I', hook, '1', '-j', chain)\n # Reverse-NAT replies from TUN must return to a nested bridge rather than the exit default route.\n if allow_tunnel:\n while command('ip', '-4', 'rule', 'del', 'pref', '5210', 'iif', 'final-egress0', 'lookup', 'main', 'protocol', '242', check=False).returncode == 0: pass\n existing = command('ip', '-4', 'rule', 'show').stdout.decode()\n for name, network in bridges:\n if not any('to ' + value + ' iif final-egress0 lookup main' in existing for value in (network, network[:-3] if network.endswith('/32') else network)):\n command('ip', '-4', 'rule', 'add', 'pref', '5210', 'iif', 'final-egress0', 'to', network, 'lookup', 'main', 'protocol', '242')\n existing_rules = command('ip', '-4', 'rule', 'show').stdout.decode() if bridges else ''\n for name, network in bridges:\n if not any('to ' + value + ' lookup main' in existing_rules for value in (network, network[:-3] if network.endswith('/32') else network)):\n command('ip', '-4', 'rule', 'add', 'pref', '5210', 'to', network, 'lookup', 'main', 'protocol', '242')\n\ndef chain_hooked(family, table, hook, chain):\n result = command(family, '-t', table, '-S', check=False)\n if result.returncode != 0:\n if table != 'filter' and result.returncode == 3 and b'Table does not exist' in result.stderr: return False\n raise RuntimeError('Cannot inspect namespace firewall hooks')\n return ('-A ' + hook + ' -j ' + chain) in result.stdout.decode().splitlines()\n\ndef denial_present():\n for family in FAMILIES:\n for hook, chain in [('OUTPUT', CHAIN), ('FORWARD', FORWARD)]:\n if not chain_hooked(family, 'filter', hook, chain): return False\n rules = command(family, '-t', 'filter', '-S', chain, check=False)\n if rules.returncode or not any(shlex.split(line)[:4] in (['-A', chain, '-j', 'DROP'], ['-A', chain, '-j', 'REJECT']) for line in rules.stdout.decode().splitlines()): return False\n return True\n\ndef restoration_pending():\n if load(ROOT / 'config.json', {}).get('mode') == 'error' or load(ROOT / 'status.json', {}).get('mode') == 'error': return True\n if (PERSISTENT / 'hosts.original').exists() or (PERSISTENT / 'resolver.original').exists() or (not HOSTS.is_symlink() and HOSTS.exists() and '# final-workspace-egress' in HOSTS.read_text()): return True\n if RESOLVER.exists() and RESOLVER.read_bytes().startswith(b'# Final workspace egress\\n'): return True\n if not all(shutil.which(family) for family in FAMILIES):\n return (PERSISTENT / 'identity.json').exists() or load(ROOT / 'config.json', {}).get('mode', 'direct') != 'direct'\n try:\n return any(chain_hooked(family, table, hook, chain)\n for family in FAMILIES\n for table, hook, chain in [('filter', 'OUTPUT', CHAIN), ('filter', 'FORWARD', FORWARD), ('mangle', 'OUTPUT', REPLY), ('mangle', 'FORWARD', FORWARD)] + ([('nat', 'POSTROUTING', NAT)] if family == 'iptables' else []))\n except RuntimeError:\n # Never-managed images need no repair when their provider denies firewall inspection.\n if not (PERSISTENT / 'identity.json').exists() and load(ROOT / 'config.json', {}).get('mode', 'direct') == 'direct': return False\n raise\n\ndef restore():\n transport_hosts({})\n original = PERSISTENT / 'resolver.original'\n if not original.exists() and (load(PERSISTENT / 'resolver-write-pending.json', False) or (RESOLVER.exists() and RESOLVER.read_bytes().startswith(b'# Final workspace egress\\n'))):\n raise RuntimeError('Original workspace resolver backup is missing; repair the provider resolver before Disable')\n if original.exists():\n current = RESOLVER\n if load(PERSISTENT / 'resolver-write-pending.json', False) or not current.exists() or current.read_text().startswith('# Final workspace egress\\n'):\n link = load(PERSISTENT / 'resolver-link.json')\n if link is None:\n if load(PERSISTENT / 'resolver-absent.json', False): current.unlink(missing_ok=True)\n else:\n if current.is_symlink(): current.unlink()\n managed_text(current, original.read_text())\n else:\n staged = current.parent / ('.final-egress-resolver-' + uuid.uuid4().hex)\n try:\n os.symlink(link['target'], staged); os.replace(staged, current)\n finally: staged.unlink(missing_ok=True)\n (PERSISTENT / 'resolver-write-pending.json').unlink(missing_ok=True)\n original.unlink()\n (PERSISTENT / 'resolver-link.json').unlink(missing_ok=True)\n (PERSISTENT / 'resolver-absent.json').unlink(missing_ok=True)\n for family in FAMILIES:\n hooks = [('filter', 'OUTPUT', CHAIN), ('mangle', 'OUTPUT', REPLY), ('mangle', 'FORWARD', FORWARD), ('filter', 'FORWARD', FORWARD)]\n if family == 'iptables': hooks.append(('nat', 'POSTROUTING', NAT))\n for table, hook, chain in hooks:\n while chain_hooked(family, table, hook, chain):\n command(family, '-t', table, '-D', hook, '-j', chain)\n command(family, '-t', table, '-F', chain, check=False)\n command(family, '-t', table, '-X', chain, check=False)\n while command('ip', '-4', 'rule', 'del', 'pref', '5210', 'protocol', '242', 'lookup', 'main', check=False).returncode == 0: pass\n for saved in ('control-replies.json', 'control-listeners.json', 'listener-limit.json', 'tunnel-addresses.json'):\n (ROOT / saved).unlink(missing_ok=True)\n (PERSISTENT / 'identity.json').unlink(missing_ok=True)\n (PERSISTENT / 'intent.json').unlink(missing_ok=True)\n\ndef validated_resolvers(addresses):\n if not isinstance(addresses, list) or not addresses or len(addresses) > 3:\n raise RuntimeError('One to three IPv4 DNS resolvers are required')\n addresses = [str(ipaddress.IPv4Address(address)) for address in addresses]\n if len(set(addresses)) != len(addresses) or any(int(address.split('.')[0]) in (0, 127) or int(address.split('.')[0]) >= 224 or address == '100.100.100.100' for address in addresses):\n raise RuntimeError('Device DNS resolvers must be unique reachable unicast addresses')\n return addresses\n\ndef resolver(addresses):\n addresses = validated_resolvers(addresses)\n source = RESOLVER\n if not (PERSISTENT / 'resolver.original').exists():\n if source.exists() and source.read_bytes().startswith(b'# Final workspace egress\\n'):\n raise RuntimeError('Original workspace resolver backup is missing; repair the provider resolver')\n absent = not source.exists() and not source.is_symlink()\n try: original = source.read_bytes()\n except FileNotFoundError: original = b''\n atomic(PERSISTENT / 'resolver-absent.json', absent)\n if source.is_symlink(): atomic(PERSISTENT / 'resolver-link.json', {'target': os.readlink(source)})\n else: (PERSISTENT / 'resolver-link.json').unlink(missing_ok=True)\n atomic(PERSISTENT / 'resolver.original', original, binary=True)\n content = '# Final workspace egress\\n' + ''.join('nameserver ' + address + '\\n' for address in addresses) + 'options timeout:2 attempts:2\\n'\n if not source.is_symlink() and source.exists() and source.read_bytes() == content.encode(): return\n managed_text(source, content)\n\ndef transport_hosts(hosts):\n original = PERSISTENT / 'hosts.original'\n absent = PERSISTENT / 'hosts-absent.json'\n if HOSTS.is_symlink():\n if hosts: raise PrerequisiteError('Workspace egress requires a regular /etc/hosts file')\n if original.exists():\n if load(absent, False): HOSTS.unlink()\n else: atomic(HOSTS, original.read_bytes(), binary=True, mode=0o644)\n original.unlink(); absent.unlink(missing_ok=True)\n return\n if hosts and not original.exists():\n atomic(absent, not HOSTS.exists())\n atomic(original, HOSTS.read_bytes() if HOSTS.exists() else b'', binary=True)\n if not HOSTS.exists() and not hosts:\n if original.exists() and not load(absent, False): atomic(HOSTS, original.read_bytes(), binary=True, mode=0o644)\n original.unlink(missing_ok=True); absent.unlink(missing_ok=True)\n return\n lines = HOSTS.read_text().splitlines() if HOSTS.exists() else []\n lines = [line for line in lines if not line.endswith('# final-workspace-egress')]\n for host, address in hosts.items():\n if not host or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-' for c in host):\n raise RuntimeError('Invalid egress transport hostname')\n lines.append(str(ipaddress.IPv4Address(address)) + ' ' + host + ' # final-workspace-egress')\n content = '\\n'.join(lines) + '\\n'\n if not hosts and load(absent, False) and not lines: HOSTS.unlink(missing_ok=True)\n elif not HOSTS.exists() or HOSTS.read_text() != content: managed_text(HOSTS, content)\n if not hosts:\n original.unlink(missing_ok=True); absent.unlink(missing_ok=True)\n\ndef status(mode, config, **extra):\n try: policy_routing = command('ip', '-4', 'rule', 'show', check=False).returncode == 0\n except FileNotFoundError: policy_routing = False\n result = {'mode': mode, 'leaseId': config.get('leaseId'), 'ownerUserId': config.get('ownerUserId'),\n 'workspaceId': config.get('workspaceId'), 'architecture': platform.machine(), 'policyRouting': policy_routing, 'expiresAtMs': config.get('expiresAtMs'), 'deviceId': None, 'path': None, **extra}\n atomic(ROOT / 'status.json', result)\n return result\n\ndef controller_status(mode, config, **extra):\n # A writer may await daemon shutdown while holding this lock; skip stale/busy publication.\n with open(ROOT / 'request.lock', 'a') as requests:\n try: fcntl.flock(requests, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except BlockingIOError: return\n saved = load(ROOT / 'config.json', {})\n fields = ('mode', 'revision', 'leaseId', 'workspaceId', 'ownerUserId', 'expiresAtMs', 'state')\n if any(saved.get(field) != config.get(field) for field in fields): return\n return status(mode, config, **extra)\n\ndef lease_id(value):\n if not isinstance(value, str) or not value: raise RuntimeError('Missing workspace lease identifier')\n return value\n\ndef lease_state_name(value):\n value = lease_id(value)\n try: return str(uuid.UUID(value))\n except ValueError: return 'opaque-' + hashlib.sha256(value.encode()).hexdigest()\n\ndef helper_environment():\n env = {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin'}\n env.update(FINAL_TAILSCALE_MANAGED='1', FINAL_DEVICE_PARENT_PID=str(os.getpid()), TS_NO_LOGS_NO_SUPPORT='true', TS_DEBUG_ENV_FILE='/dev/null', TS_LOGS_DIR=str(ROOT / 'logs'))\n return env\n\ndef cli(helper, sock, *args):\n # CLI operations are managed children as well: closing their pipe stops them on controller death.\n env = helper_environment()\n errors = os.open(ROOT / 'last-control-error.log', os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)\n try:\n proc = subprocess.Popen([str(helper), 'final-cli', '--socket=' + str(sock), *args], stdin=subprocess.PIPE,\n stdout=subprocess.PIPE, stderr=errors, env=env)\n finally: os.close(errors)\n try:\n proc.stdin.write(b'final-device-start\\n'); proc.stdin.flush()\n deadline = time.monotonic() + 20\n output = bytearray()\n os.set_blocking(proc.stdout.fileno(), False)\n while proc.poll() is None:\n chunk = proc.stdout.read(65536)\n if chunk: output.extend(chunk)\n if len(output) > 1024 * 1024 or time.monotonic() > deadline:\n raise RuntimeError('Workspace egress control operation exceeded its limit: ' + args[0])\n time.sleep(.01)\n output.extend(proc.stdout.read() or b'')\n if proc.returncode != 0:\n detail = ': ' + bytes(output).decode(errors='replace')[:1000] if args[0] == 'ping' else ''\n raise RuntimeError('Workspace egress control operation failed (' + args[0] + ')' + detail)\n return bytes(output)\n finally:\n try: proc.stdin.close()\n except BrokenPipeError: pass\n if proc.poll() is None: proc.kill()\n proc.wait()\n\ndef stop(proc):\n if proc is not None:\n try: proc.stdin.close()\n except BrokenPipeError: pass\n try: proc.wait(timeout=2)\n except subprocess.TimeoutExpired: proc.kill(); proc.wait()\n\ndef minimal_guard():\n failures = []\n # Cached accepted sockets permit recovery even without conntrack or mangle.\n try: replies = [reply for reply in load(ROOT / 'control-replies.json', []) if reply.get('uid') == 0]\n except Exception: replies = []\n for family in FAMILIES:\n try:\n for hook, chain in [('OUTPUT', CHAIN), ('FORWARD', FORWARD)]:\n existing = command(family, '-t', 'filter', '-S', chain, check=False)\n hooked = command(family, '-t', 'filter', '-C', hook, '-j', chain, check=False)\n # Retain a successfully installed closed family and its control exceptions.\n if existing.returncode == 0 and hooked.returncode == 0 and b'-o final-egress0' not in existing.stdout and any(shlex.split(line)[:4] in (['-A', chain, '-j', 'DROP'], ['-A', chain, '-j', 'REJECT']) for line in existing.stdout.decode().splitlines()): continue\n rules = ['*filter', ':' + chain + ' - [0:0]', '-F ' + chain]\n if hook == 'OUTPUT':\n for proto in ('tcp', 'udp'):\n rules.append('-A ' + chain + ' -o lo -p ' + proto + ' --dport 53 -j DROP')\n if family == 'iptables':\n rules += ['-A ' + chain + ' -d 127.0.0.11 -j DROP', '-A ' + chain + ' -d 100.100.100.100 -j DROP']\n rules.append('-A ' + chain + ' -o lo -j ACCEPT')\n if family == 'ip6tables':\n for kind in (133, 134, 135, 136):\n rules += ['-A ' + chain + ' -p ipv6-icmp --icmpv6-type ' + str(kind) + ' -m owner --uid-owner 1-4294967294 -j REJECT',\n '-A ' + chain + ' -p ipv6-icmp --icmpv6-type ' + str(kind) + ' -j ACCEPT']\n for reply in replies:\n if (':' in reply['source']) != (family == 'ip6tables'): continue\n rules.append('-A ' + chain + ' -p tcp -s ' + reply['source'] + ' --sport ' + str(reply['sourcePort']) +\n ' -d ' + reply['destination'] + ' --dport ' + str(reply['destinationPort']) +\n ' --tcp-flags SYN,RST,ACK ACK -j ACCEPT')\n rules += ['-A ' + chain + ' -j DROP', 'COMMIT']\n result = subprocess.run([family + '-restore', '-w', '5', '--noflush'], input=('\\n'.join(rules) + '\\n').encode(), capture_output=True, timeout=25)\n if result.returncode and family == 'ip6tables':\n # Without owner matching, deny IPv6 neighbor traffic too rather than leaving the family open.\n fallback = [rule for rule in rules if '-p ipv6-icmp ' not in rule]\n result = subprocess.run([family + '-restore', '-w', '5', '--noflush'], input=('\\n'.join(fallback) + '\\n').encode(), capture_output=True, timeout=25)\n if result.returncode: raise RuntimeError('Atomic emergency denial failed for ' + family)\n if hooked.returncode != 0: command(family, '-t', 'filter', '-I', hook, '1', '-j', chain)\n except Exception as cause: failures.append(str(cause))\n if failures: raise RuntimeError('Cannot install minimal namespace denial: ' + '; '.join(failures))\n\ndef guard(allow_tunnel=False):\n try: install_guard(allow_tunnel)\n except Exception:\n try: install_guard(closed=True)\n except Exception:\n try: minimal_guard()\n except Exception as failure:\n raise DenialUnavailableError('Workspace network denial could not be installed') from failure\n raise\n\ndef clear_identity():\n for path in ROOT.glob('state-*'):\n if path.is_file(): path.unlink()\n (ROOT / 'enrollment.key').unlink(missing_ok=True)\n\ndef stop_controller():\n with open(ROOT / 'daemon.lock', 'a') as lock:\n deadline = time.monotonic() + 5\n signaled = None\n while True:\n pid = load(ROOT / 'controller.pid')\n if isinstance(pid, int) and pid != signaled:\n try:\n args = pathlib.Path('/proc/' + str(pid) + '/cmdline').read_bytes().split(bytes([0]))\n if str(ROOT / 'controller.py').encode() in args and b'run' in args:\n os.kill(pid, signal.SIGTERM); signaled = pid\n except ProcessLookupError: pass\n except FileNotFoundError: pass\n try:\n fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)\n clear_identity()\n return\n except BlockingIOError:\n if time.monotonic() >= deadline: raise RuntimeError('Workspace egress controller did not stop')\n time.sleep(.05)\n\ndef capture_errors(proc):\n tail = collections.deque(maxlen=128)\n while True:\n chunk = proc.stderr.read1(4096)\n if not chunk: return\n tail.append(chunk)\n atomic(ROOT / 'daemon.log', b''.join(tail), binary=True)\n\ndef select_exit(config, peers, selected, health_misses, helper, sock):\n candidates = sorted(config.get('devices', []), key=lambda item: item.get('tailscaleIp') != selected)\n for item in candidates:\n ip = item.get('tailscaleIp')\n if ip not in peers or not peers[ip].get('Online') or peers[ip].get('Expired'): continue\n try:\n # TSMP tests the encrypted peer path without opening a destination connection.\n cli(helper, sock, 'ping', '--tsmp', '--c=1', '--timeout=2s', str(ipaddress.IPv4Address(ip)))\n health_misses[ip] = 0\n return item\n except (RuntimeError, ValueError) as cause:\n atomic(ROOT / 'last-peer-error.json', {'deviceId': item['deviceId'], 'error': str(cause), 'atMs': int(time.time() * 1000)})\n health_misses[ip] = health_misses.get(ip, 0) + 1\n if ip == selected and health_misses[ip] < 3: break\n continue\n return None\n\ndef run():\n with open(ROOT / 'daemon.lock', 'a') as lock:\n deadline = time.monotonic() + 5\n while True:\n try:\n fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)\n break\n except BlockingIOError:\n pid = load(ROOT / 'controller.pid')\n alive = False\n try:\n alive = isinstance(pid, int) and str(ROOT / 'controller.py').encode() in pathlib.Path('/proc/' + str(pid) + '/cmdline').read_bytes().split(bytes([0]))\n except FileNotFoundError: pass\n if time.monotonic() >= deadline:\n if alive: return\n raise RuntimeError('Workspace controller startup lock is busy')\n time.sleep(.01)\n atomic(ROOT / 'controller.pid', os.getpid())\n proc = None\n current = None\n selected = None\n health_misses = {}\n bridges = None\n revision = None\n def terminate(signum, frame):\n raise SystemExit(0)\n signal.signal(signal.SIGTERM, terminate)\n signal.signal(signal.SIGINT, terminate)\n try:\n while True:\n config = load(ROOT / 'config.json', {})\n mode = config.get('mode', 'blocked')\n if mode != 'device' or config.get('bootId') != BOOT_ID or config.get('expiresAtMs', 0) <= time.time() * 1000 or config.get('deadlineMonotonic', 0) <= time.monotonic():\n # Coordinate relinquishing the daemon lock with writers so a renewal cannot lose its controller.\n with open(ROOT / 'request.lock', 'a') as requests:\n fcntl.flock(requests, fcntl.LOCK_EX)\n if load(ROOT / 'config.json', {}) != config: continue\n stop(proc); proc = None; current = None; selected = None\n clear_identity()\n if mode == 'direct':\n restore(); status('direct', config)\n else:\n guard(); status('blocked', config)\n fcntl.flock(lock, fcntl.LOCK_UN)\n return\n helper = ROOT / 'helper'\n sock = ROOT / 'control.sock'\n revision = config.get('revision', config['leaseId'])\n if revision != current or proc is None or proc.poll() is not None:\n stop(proc); proc = None\n with open(ROOT / 'request.lock', 'a') as requests:\n fcntl.flock(requests, fcntl.LOCK_EX)\n if load(ROOT / 'config.json', {}).get('revision', load(ROOT / 'config.json', {}).get('leaseId')) != revision: continue\n guard(); transport_hosts(config['transportHosts'])\n sock.unlink(missing_ok=True)\n state = ROOT / ('state-' + lease_state_name(config['leaseId']))\n for old in ROOT.glob('state-*'):\n if old != state and old.is_file(): old.unlink()\n env = helper_environment()\n proc = subprocess.Popen([str(helper), '--tun=final-egress0', '--port=0', '--socket=' + str(sock), '--state=' + str(state)],\n stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=env)\n threading.Thread(target=capture_errors, args=(proc,), daemon=True).start()\n proc.stdin.write(b'final-device-start\\n'); proc.stdin.flush()\n deadline = time.monotonic() + 5\n while not sock.exists():\n if proc.poll() is not None or time.monotonic() > deadline:\n raise RuntimeError('Workspace egress daemon did not become ready')\n time.sleep(.05)\n args = ['up', '--reset', '--login-server=' + config['controlUrl'], '--hostname=workspace-' + lease_state_name(config['leaseId'])[:40],\n '--accept-dns=false', '--accept-routes=false', '--shields-up', '--netfilter-mode=off']\n if config.get('authKey'):\n atomic(ROOT / 'enrollment.key', config['authKey'].encode(), binary=True)\n args.append('--auth-key=file:' + str(ROOT / 'enrollment.key'))\n args.append('--force-reauth')\n try: cli(helper, sock, *args)\n finally:\n (ROOT / 'enrollment.key').unlink(missing_ok=True)\n with open(ROOT / 'request.lock', 'a') as requests:\n # A writer may hold request.lock while awaiting our daemon.lock.\n try: fcntl.flock(requests, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except BlockingIOError: pass\n else:\n pending = load(ROOT / 'config.json', {})\n if pending.get('revision', pending.get('leaseId')) == revision:\n pending.pop('authKey', None); atomic(ROOT / 'config.json', pending)\n with open(ROOT / 'request.lock', 'a') as requests:\n fcntl.flock(requests, fcntl.LOCK_EX)\n saved = load(ROOT / 'config.json', {})\n if saved.get('mode') != 'device' or saved.get('leaseId') != config.get('leaseId') or saved.get('revision', saved.get('leaseId')) != revision:\n stop(proc); proc = None; current = None; selected = None\n continue\n resolver(saved.get('dnsResolvers', ['1.1.1.1', '9.9.9.9']))\n saved.pop('authKey', None); atomic(ROOT / 'config.json', saved)\n current = revision; selected = None\n guard(allow_tunnel=True)\n if config.get('state') == 'provisioning':\n controller_status('enrolled', config)\n time.sleep(.2)\n continue\n actual_bridges = local_bridges()\n with open(ROOT / 'request.lock', 'a') as requests:\n fcntl.flock(requests, fcntl.LOCK_EX)\n latest = load(ROOT / 'config.json', {})\n if latest.get('mode') != 'device' or latest.get('revision', latest.get('leaseId')) != revision: continue\n resolver(latest.get('dnsResolvers', ['1.1.1.1', '9.9.9.9']))\n previous_listeners = load(ROOT / 'control-listeners.json', [])\n existing_control_replies()\n actual_tunnel = command('ip', '-j', 'addr', 'show', 'dev', 'final-egress0', check=False)\n actual_addresses = [str(ipaddress.ip_address(address['local'])) for interface in json.loads(actual_tunnel.stdout or b'[]') for address in interface.get('addr_info', [])]\n if bridges != actual_bridges or previous_listeners != load(ROOT / 'control-listeners.json', []) or actual_addresses != load(ROOT / 'tunnel-addresses.json', []):\n guard(allow_tunnel=True); bridges = actual_bridges\n try:\n raw = json.loads(cli(helper, sock, 'status', '--json'))\n peers = {ip: peer for peer in (raw.get('Peer') or {}).values() for ip in (peer.get('TailscaleIPs') or [])}\n candidates = config.get('devices', [])\n candidate = select_exit(config, peers, selected, health_misses, helper, sock)\n if candidate is None:\n last = next((item for item in candidates if item.get('tailscaleIp') == selected), None)\n # A health miss must not tear down an authorized route during control outage/rekey.\n # Keeping it can only use the approved exit; the namespace guard still forbids direct fallback.\n if last is not None and selected in peers and not peers[selected].get('Expired'):\n peer = peers[selected]\n controller_status('reconnecting', config, deviceId=last['deviceId'], path='direct' if peer.get('CurAddr') else 'relay')\n else:\n if selected is not None: cli(helper, sock, 'set', '--exit-node=')\n selected = None\n controller_status('blocked', config)\n else:\n ip = str(ipaddress.IPv4Address(candidate['tailscaleIp']))\n if selected != ip:\n cli(helper, sock, 'set', '--exit-node=' + ip, '--exit-node-allow-lan-access=false')\n selected = ip\n route = command('ip', '-4', 'route', 'get', '192.0.2.254').stdout\n if b'dev final-egress0' not in route:\n controller_status('configuring', config)\n time.sleep(.1)\n continue\n peer = peers[ip]\n controller_status('device', config, deviceId=candidate['deviceId'], path='direct' if peer.get('CurAddr') else 'relay')\n time.sleep(1)\n except (RuntimeError, subprocess.TimeoutExpired, json.JSONDecodeError) as failure:\n atomic(ROOT / 'last-peer-error.json', {'error': str(failure)[:1000], 'atMs': int(time.time() * 1000)})\n controller_status('reconnecting', config)\n time.sleep(1)\n except Exception as cause:\n atomic(ROOT / 'last-error.json', {'error': str(cause), 'atMs': int(time.time() * 1000)})\n controller_status('error', load(ROOT / 'config.json', {}), error='Workspace egress stopped; inspect the controller error')\n raise\n finally:\n stop(proc)\n if load(ROOT / 'controller.pid') == os.getpid(): (ROOT / 'controller.pid').unlink(missing_ok=True)\n # Writers can await daemon.lock while holding request.lock; finish secret cleanup after releasing it.\n fcntl.flock(lock, fcntl.LOCK_UN)\n with open(ROOT / 'request.lock', 'a') as requests:\n fcntl.flock(requests, fcntl.LOCK_EX)\n pending = load(ROOT / 'config.json', {})\n if revision is not None and pending.get('revision', pending.get('leaseId')) == revision and 'authKey' in pending:\n pending.pop('authKey', None); atomic(ROOT / 'config.json', pending)\n\ndef apply(request):\n prerequisite(request['action'])\n with open(ROOT / 'request.lock', 'a') as lock:\n fcntl.flock(lock, fcntl.LOCK_EX)\n action = request['action']\n source = pathlib.Path(__file__).read_bytes() if '__file__' in globals() else sys.argv[1].encode()\n cached_source = ROOT / 'controller.py'\n if not cached_source.exists() or cached_source.read_bytes() != source: atomic(cached_source, source, binary=True)\n existing = load(ROOT / 'config.json', {})\n capabilities = [int(line.split()[1], 16) for line in pathlib.Path('/proc/self/status').read_text().splitlines() if line.startswith(('CapInh:', 'CapPrm:', 'CapEff:', 'CapBnd:', 'CapAmb:'))]\n # A prior choice with lost volatile state is not proof of an untouched namespace.\n network_pristine = (existing.get('noNetworkChanges') is True or ((not existing or existing.get('mode') == 'direct') and not (PERSISTENT / 'intent.json').exists())) and bool(capabilities) and not any(mask & (1 << 12) for mask in capabilities) and not (PERSISTENT / 'resolver.original').exists() and not (PERSISTENT / 'hosts.original').exists() and not (ROOT / 'controller.pid').exists()\n workspace_id = request.get('workspaceId')\n if action != 'status' and existing.get('workspaceId') is not None and existing['workspaceId'] != workspace_id:\n raise RuntimeError('This network namespace belongs to a different workspace')\n operation = load(ROOT / 'operation.json', {})\n operation_live = operation.get('bootId') == BOOT_ID and operation.get('deadline', 0) > time.monotonic()\n token = str(uuid.UUID(request['configurationToken'])) if request.get('configurationToken') is not None else None\n if action == 'claim':\n if (request.get('refresh') or request.get('verifyOnly')) and (not operation_live or operation.get('token') != token):\n raise WorkspaceConflictError('Workspace configuration claim was superseded')\n if operation_live and operation.get('token') != token:\n return {**load(ROOT / 'status.json', {'mode': 'blocked', 'leaseId': None, 'expiresAtMs': None, 'deviceId': None, 'path': None}), 'busy': True}\n token = str(uuid.UUID(token))\n if not request.get('verifyOnly'):\n atomic(ROOT / 'operation.json', {'token': token, 'deadline': time.monotonic() + 300, 'bootId': BOOT_ID})\n return {**load(ROOT / 'status.json', {'mode': 'blocked', 'leaseId': None, 'expiresAtMs': None, 'deviceId': None, 'path': None}), 'busy': False}\n if action == 'unlock':\n if operation.get('token') == token: (ROOT / 'operation.json').unlink(missing_ok=True)\n return load(ROOT / 'status.json', {'mode': 'blocked', 'leaseId': None, 'expiresAtMs': None, 'deviceId': None, 'path': None})\n if action not in ('status', 'artifact'):\n if token is not None and (not operation_live or operation.get('token') != token):\n raise WorkspaceConflictError('Workspace egress configuration was superseded')\n if operation_live and token != operation.get('token'):\n raise WorkspaceConflictError('Another binding is configuring workspace egress')\n expected = lease_id(request['expectedLeaseId']) if request.get('expectedLeaseId') is not None else None\n if token is None and expected is not None and existing.get('leaseId') != expected:\n if action == 'block' and existing.get('leaseId') is None and existing.get('mode') == 'direct':\n return load(ROOT / 'status.json', {'mode': 'direct', 'leaseId': None, 'expiresAtMs': None, 'deviceId': None, 'path': None})\n if action == 'block' and existing.get('leaseId') is None and existing.get('mode') == 'blocked':\n try: guard()\n except Exception as failure:\n status('error' if isinstance(failure, DenialUnavailableError) else 'blocked', existing)\n raise\n return status('blocked', existing)\n if not (action == 'block' and existing.get('leaseId') is None and (not existing or existing.get('mode') == 'blocked')):\n raise WorkspaceConflictError('Workspace egress lease changed before cleanup')\n if action not in ('status', 'artifact'):\n PERSISTENT.mkdir(mode=0o700, exist_ok=True)\n if PERSISTENT.is_symlink() or PERSISTENT.stat().st_uid != 0:\n raise RuntimeError('Persistent workspace egress state must be root-owned')\n PERSISTENT.chmod(0o700)\n identity = load(PERSISTENT / 'identity.json', {})\n if identity.get('workspaceId') is not None and identity['workspaceId'] != workspace_id:\n raise RuntimeError('Persistent egress state belongs to a different workspace')\n if action != 'disable': atomic(PERSISTENT / 'identity.json', {'workspaceId': workspace_id})\n if action == 'block': atomic(PERSISTENT / 'intent.json', {'requiresChoice': not request.get('restoreDirect', False)})\n if action == 'disable' and existing.get('noNetworkChanges') is True:\n if (PERSISTENT / 'resolver.original').exists() or (PERSISTENT / 'hosts.original').exists() or (ROOT / 'controller.pid').exists():\n raise RuntimeError('Workspace contains restoration artifacts; privileged repair is required')\n (PERSISTENT / 'identity.json').unlink(missing_ok=True)\n (PERSISTENT / 'intent.json').unlink(missing_ok=True)\n config = {'mode': 'direct', 'workspaceId': workspace_id, 'ownerUserId': None}\n atomic(ROOT / 'config.json', config)\n return status('direct', config)\n if action == 'disable' and (not existing or (existing.get('mode') == 'direct' and load(ROOT / 'status.json', {}).get('mode') == 'direct')):\n if restoration_pending(): restore()\n (PERSISTENT / 'identity.json').unlink(missing_ok=True)\n (PERSISTENT / 'intent.json').unlink(missing_ok=True)\n config = {'mode': 'direct', 'workspaceId': workspace_id, 'ownerUserId': None}\n atomic(ROOT / 'config.json', config)\n return status('direct', config)\n if action == 'artifact':\n ready = False\n try: fd = os.open(ROOT / 'helper', os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)\n except FileNotFoundError: pass\n else:\n with os.fdopen(fd, 'rb') as source:\n info = os.fstat(source.fileno())\n if stat.S_ISREG(info.st_mode) and info.st_size <= 128 * 1024 * 1024:\n ready = hashlib.sha256(source.read(128 * 1024 * 1024 + 1)).hexdigest() == request['sha256']\n return {**load(ROOT / 'status.json', {'mode': 'blocked', 'leaseId': None, 'expiresAtMs': None, 'deviceId': None, 'path': None}), 'helperReady': ready}\n if action == 'status':\n result = load(ROOT / 'status.json', {'mode': 'direct', 'leaseId': None, 'expiresAtMs': None, 'deviceId': None, 'path': None, 'architecture': platform.machine()})\n alive = False\n with open(ROOT / 'daemon.lock', 'a') as daemon_lock:\n try:\n fcntl.flock(daemon_lock, fcntl.LOCK_EX | fcntl.LOCK_NB)\n if result.get('mode') != 'error' and existing.get('mode') not in ('direct', 'error') and existing:\n result = {**result, 'mode': 'blocked' if denial_present() else 'error', 'deviceId': None, 'path': None}\n except BlockingIOError: alive = True\n return {**result, 'networkPristine': existing.get('noNetworkChanges', False), 'controllerAlive': alive, 'configuring': operation_live, 'restorePending': restoration_pending(), 'choicePending': load(PERSISTENT / 'intent.json', {}).get('requiresChoice', existing.get('mode') == 'blocked')}\n if action in ('block', 'configure'):\n try: guard()\n except Exception as failure:\n mode = 'error' if isinstance(failure, DenialUnavailableError) else 'blocked'\n failed = {'mode': mode, 'workspaceId': workspace_id, 'ownerUserId': request.get('ownerUserId'), 'noNetworkChanges': network_pristine}\n atomic(ROOT / 'config.json', failed); status(mode, failed)\n raise\n if action == 'configure':\n # Validation failure must not leave an old direct/device status after guard installation.\n pending = {'mode': 'blocked', 'workspaceId': workspace_id, 'ownerUserId': request.get('ownerUserId')}\n atomic(ROOT / 'config.json', pending); status('blocked', pending)\n if request.get('config', {}).get('workspaceId') != workspace_id: raise RuntimeError('Enrollment belongs to a different workspace')\n if command('ip', '-4', 'rule', 'show', check=False).returncode != 0:\n raise PrerequisiteError('This workspace kernel does not support Linux policy routing')\n config = request['config']\n config['dnsResolvers'] = validated_resolvers(config.get('dnsResolvers', ['1.1.1.1', '9.9.9.9']))\n control = urllib.parse.urlsplit(config['controlUrl'])\n if control.scheme != 'https' or not control.hostname or control.username is not None or control.password is not None or control.query or control.fragment:\n raise RuntimeError('Workspace control URL must use HTTPS without credentials, query or fragment')\n config['leaseId'] = lease_id(config['leaseId'])\n remaining = config['expiresAtMs'] - time.time() * 1000\n if not 0 < remaining <= 16 * 60 * 1000:\n raise RuntimeError('Workspace egress lease is expired or exceeds fifteen minutes')\n config['bootId'] = BOOT_ID\n config['deadlineMonotonic'] = time.monotonic() + min(remaining, 15 * 60 * 1000) / 1000\n staged = pathlib.Path(request['helperPath'])\n try: fd = os.open(staged, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)\n except FileNotFoundError as failure:\n raise RuntimeError('Staged networking helper is missing; transfer the approved artifact again') from failure\n with os.fdopen(fd, 'rb') as source:\n if not stat.S_ISREG(os.fstat(source.fileno()).st_mode):\n raise RuntimeError('Workspace networking helper must be a regular file')\n content = source.read(128 * 1024 * 1024 + 1)\n if len(content) > 128 * 1024 * 1024 or hashlib.sha256(content).hexdigest() != config['helper']['sha256']:\n raise RuntimeError('Workspace networking helper failed integrity verification')\n machine = {'x86_64': 62, 'aarch64': 183}.get(platform.machine())\n if content[:6] != b'\\x7fELF\\x02\\x01' or len(content) < 20 or struct.unpack('<H', content[18:20])[0] != machine:\n raise RuntimeError('The pinned networking helper does not match this Linux workspace architecture')\n atomic(ROOT / 'helper', content, binary=True, mode=0o700)\n config = dict(config, mode='device')\n elif action == 'renew':\n request['lease']['leaseId'] = lease_id(request['lease']['leaseId'])\n if request.get('lease', {}).get('workspaceId') != workspace_id: raise RuntimeError('Renewal belongs to a different workspace')\n config = load(ROOT / 'config.json')\n if config is None or config.get('leaseId') != request['lease']['leaseId']:\n raise WorkspaceConflictError('Workspace egress lease changed')\n if config.get('bootId') != BOOT_ID or config.get('deadlineMonotonic', 0) <= time.monotonic() or config.get('expiresAtMs', 0) <= time.time() * 1000:\n raise EnrollmentLostError('Workspace enrollment expired locally; authorized reenrollment is required')\n lease = request['lease']\n lease['leaseId'] = lease_id(lease['leaseId'])\n remaining = lease['expiresAtMs'] - time.time() * 1000\n if not 0 < remaining <= 16 * 60 * 1000:\n raise RuntimeError('Workspace egress renewal is invalid')\n config.update(bootId=BOOT_ID, expiresAtMs=lease['expiresAtMs'], devices=lease['devices'], state=lease['state'], deadlineMonotonic=time.monotonic() + min(remaining, 15 * 60 * 1000) / 1000)\n elif action in ('block', 'disable'):\n config = {'mode': 'direct' if action == 'disable' else 'blocked', 'workspaceId': workspace_id, 'ownerUserId': None if action == 'disable' else request.get('ownerUserId')}\n else:\n raise RuntimeError('Unknown workspace egress action')\n atomic(ROOT / 'config.json', config)\n if action in ('block', 'disable'): stop_controller()\n if action == 'renew':\n with open(ROOT / 'daemon.lock', 'a') as daemon_lock:\n try: fcntl.flock(daemon_lock, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except BlockingIOError:\n prior = load(ROOT / 'status.json', {})\n return {**prior, 'expiresAtMs': config['expiresAtMs']}\n # The controller uses a root-owned copy after this caller's temporary files are removed.\n source = pathlib.Path(__file__).read_bytes() if '__file__' in globals() else sys.argv[1].encode()\n atomic(ROOT / 'controller.py', source, binary=True)\n subprocess.Popen([sys.executable, '-I', str(ROOT / 'controller.py'), 'run'], stdin=subprocess.DEVNULL,\n stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)\n if action == 'block': return status('blocked', config)\n return status('configuring', config)\n\nif __name__ == '__main__':\n try:\n if len(sys.argv) > 1 and sys.argv[1] == 'run': run()\n else: print(json.dumps(apply(json.load(sys.stdin))))\n except Exception as cause:\n try:\n if ROOT.exists() and not ROOT.is_symlink() and ROOT.stat().st_uid == 0:\n atomic(ROOT / 'last-error.json', {'error': str(cause)[:1000], 'atMs': int(time.time() * 1000)})\n except OSError: pass\n code = 'egress_enrollment_lost' if isinstance(cause, EnrollmentLostError) else 'prerequisite' if isinstance(cause, (FileNotFoundError, PrerequisiteError)) else 'conflict' if isinstance(cause, WorkspaceConflictError) else 'configuration'\n print(json.dumps({'errorCode': code}))\n sys.exit(1)\n`;\n\n// Verify the owned source before executing it; a cache miss requests the full bootstrap once.\nexport const cachedWorkspaceEgressBootstrap = (sha256: string): string => {\n if (!/^[a-f0-9]{64}$/.test(sha256)) throw new Error('Invalid workspace controller SHA256');\n return String.raw`import hashlib, os, pathlib, stat\npath = pathlib.Path('/run/final-workspace-egress/controller.py')\ntry:\n fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)\n with os.fdopen(fd, 'rb') as file:\n info = os.fstat(file.fileno())\n source = file.read(128 * 1024 + 1)\n valid = stat.S_ISREG(info.st_mode) and info.st_uid == 0 and not info.st_mode & 0o022 and len(source) <= 128 * 1024 and hashlib.sha256(source).hexdigest() == '${sha256}'\nexcept OSError: valid = False\nif valid: exec(compile(source, str(path), 'exec'), {'__name__': '__main__', '__file__': str(path)})\nelse: print('{\"needsBootstrap\":true}')\n`;\n};\n\n// Keep provider command arguments small; credentials and trusted source travel on stdin.\nexport const workspaceEgressLauncher = String.raw`import io,json,sys\nrequest=json.load(sys.stdin)\nsource=request['source']\nsys.argv=['-c',source]\nsys.stdin=io.StringIO(request['input'])\nexec(compile(source,'<final-workspace-egress>','exec'),{'__name__':'__main__'})\n`;\n"],
5
- "mappings": "AACO,MAAM,2BAA2B,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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;AAK1K;AAGO,MAAM,0BAA0B,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;",
4
+ "sourcesContent": ["// The same controller runs in ordinary Linux provider namespaces; no VM platform API is used.\nexport const workspaceEgressBootstrap = String.raw`import collections, errno, fcntl, hashlib, ipaddress, json, os, pathlib, platform, re, shutil, signal, shlex, socket, stat, struct, subprocess, sys, tempfile, threading, time, urllib.parse, uuid\n\nROOT = pathlib.Path('/run/final-workspace-egress')\nPERSISTENT = pathlib.Path('/var/lib/final-workspace-egress')\nRESOLVER = pathlib.Path('/etc/resolv.conf')\nHOSTS = pathlib.Path('/etc/hosts')\nCHAIN = 'FINAL-EGRESS'\nREPLY = 'FINAL-EGRESS-REPLY'\nFORWARD = 'FINAL-EGRESS-FWD'\nNAT = 'FINAL-EGRESS-NAT'\nMARK = '0x80000/0xff0000'\nos.environ['PATH'] = '/usr/sbin:/usr/bin:/sbin:/bin'\nos.environ.pop('SSL_CERT_FILE', None)\nos.environ.pop('SSL_CERT_DIR', None)\n# Prime autoload before choosing families; later kernel enablement requires reinitialization.\ntry: socket.socket(socket.AF_INET6, socket.SOCK_DGRAM).close()\nexcept OSError as failure:\n if failure.errno not in (errno.EAFNOSUPPORT, errno.EPROTONOSUPPORT, errno.EPERM, errno.EACCES): raise\nFAMILIES = ('iptables', 'ip6tables') if pathlib.Path('/proc/net/if_inet6').exists() else ('iptables',)\n\nclass WorkspaceConflictError(RuntimeError):\n pass\n\nclass PrerequisiteError(RuntimeError):\n pass\n\nclass DenialUnavailableError(RuntimeError):\n pass\n\nclass EnrollmentLostError(RuntimeError):\n pass\n\n\ndef command(*args, check=True, timeout=25):\n if args[0] in ('iptables', 'ip6tables') and '--version' not in args: args = (args[0], '-w', '5', *args[1:])\n result = subprocess.run(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)\n if check and result.returncode != 0:\n raise RuntimeError('Workspace networking command failed: ' + ' '.join(args[:4]))\n return result\n\ndef atomic(path, value, binary=False, mode=0o600):\n staged = None\n try:\n with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as out:\n staged = pathlib.Path(out.name)\n out.write(value if binary else json.dumps(value).encode())\n out.flush(); os.fsync(out.fileno())\n os.chmod(staged, mode)\n os.replace(staged, path)\n directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)\n try: os.fsync(directory)\n finally: os.close(directory)\n finally:\n if staged is not None: staged.unlink(missing_ok=True)\n\ndef managed_text(path, content):\n data = content.encode()\n try: atomic(path, data, binary=True, mode=0o644)\n except OSError as failure:\n if failure.errno != errno.EBUSY: raise\n # Docker bind-mounted files cannot be replaced; never follow a raced-in symlink.\n pending = PERSISTENT / 'resolver-write-pending.json' if path == RESOLVER else None\n if pending is not None: atomic(pending, True)\n fd = os.open(path, os.O_WRONLY | os.O_NOFOLLOW | os.O_NONBLOCK)\n with os.fdopen(fd, 'wb') as out:\n if not stat.S_ISREG(os.fstat(out.fileno()).st_mode): raise RuntimeError('Managed network file must be regular')\n os.ftruncate(out.fileno(), 0)\n out.write(data); out.flush(); os.fsync(out.fileno())\n if pending is not None: pending.unlink(missing_ok=True)\n\ndef load(path, default=None):\n try:\n return json.loads(path.read_text())\n except FileNotFoundError:\n return default\n\ndef prerequisite(action):\n if sys.version_info < (3, 8):\n raise PrerequisiteError('Device egress requires Python 3.8 or newer')\n if sys.platform != 'linux' or os.geteuid() != 0:\n raise PrerequisiteError('Device egress requires an isolated Linux workspace with privileged networking access')\n ROOT.mkdir(mode=0o700, exist_ok=True)\n if ROOT.is_symlink() or ROOT.stat().st_uid != 0:\n raise RuntimeError('Workspace egress state must be a root-owned directory')\n ROOT.chmod(0o700)\n direct = not load(ROOT / 'config.json') or (load(ROOT / 'config.json', {}).get('mode') == 'direct' and load(ROOT / 'status.json', {}).get('mode') == 'direct')\n if action in ('status', 'artifact', 'claim', 'unlock') or (action == 'disable' and (direct or load(ROOT / 'config.json', {}).get('noNetworkChanges') is True)): return\n if action in ('configure', 'renew') and not pathlib.Path('/dev/net/tun').exists():\n raise PrerequisiteError('This sandbox provider does not expose /dev/net/tun')\n command('ip', '-V')\n for family in FAMILIES:\n command(family, '--version'); command(family + '-restore', '--version')\n\nBOOT_ID = pathlib.Path('/proc/sys/kernel/random/boot_id').read_text().strip()\n\ndef existing_control_replies():\n saved = load(ROOT / 'control-replies.json')\n sockets = []\n for table in ('tcp', 'tcp6'):\n def address(value):\n host, port = value.split(':')\n raw = bytes.fromhex(host)\n raw = b''.join(raw[i:i+4][::-1] for i in range(0, len(raw), 4))\n ip = ipaddress.ip_address(raw)\n if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None: ip = ip.ipv4_mapped\n return str(ip), int(port, 16)\n source = pathlib.Path('/proc/net/' + table)\n if not source.exists(): continue\n for line in source.read_text().splitlines()[1:]:\n columns = line.split()\n if columns[3] in ('01', '0A'): sockets.append((address(columns[1]), address(columns[2]), columns[3], int(columns[7])))\n addresses = json.loads(command('ip', '-j', 'addr', 'show').stdout)\n local_addresses = {ipaddress.ip_address(address['local']) for interface in addresses for address in interface.get('addr_info', [])}\n bridge_networks = [ipaddress.ip_network(network) for _, network in local_bridges()]\n listeners = [local for local, remote, state, uid in sockets if state == '0A' and not ipaddress.ip_address(local[0]).is_loopback]\n replies = []\n for local, remote, state, uid in sockets:\n # Only privileged provider sockets may use the pre-conntrack compatibility exception.\n remote_ip = ipaddress.ip_address(remote[0])\n if uid != 0 or state != '01' or remote_ip.is_loopback or remote_ip in local_addresses: continue\n if any(remote_ip.version == network.version and remote_ip in network for network in bridge_networks): continue\n if any(port == local[1] and (ipaddress.ip_address(host).is_unspecified or host == local[0]) for host, port in listeners):\n replies.append({'source': local[0], 'sourcePort': local[1], 'destination': remote[0], 'destinationPort': remote[1], 'uid': 0})\n if saved is not None and any(reply.get('uid') != 0 for reply in saved): saved = None\n capture_overflow = saved is None and len(replies) > 128\n if saved is not None: replies = saved\n server_ports = [{'source': host, 'sourcePort': port} for host, port in listeners]\n for prior in load(ROOT / 'control-listeners.json', []):\n if any(local[1] == prior['sourcePort'] and state == '01' for local, remote, state, uid in sockets): server_ports.append(prior)\n # A dual-stack listener appears in tcp6 even when the accepted transport uses IPv4.\n server_ports += [{'source': reply['source'], 'sourcePort': reply['sourcePort']} for reply in replies]\n server_ports = [dict(source=host, sourcePort=port) for host, port in sorted({(item['source'], item['sourcePort']) for item in server_ports})]\n prior = load(ROOT / 'control-listeners.json', [])\n privileged = {local for local, remote, state, uid in sockets if state == '0A' and uid == 0}\n server_ports.sort(key=lambda item: (item not in prior, (item['source'], item['sourcePort']) not in privileged))\n atomic(ROOT / 'control-listeners.json', server_ports[:256])\n if len(server_ports) > 256:\n atomic(ROOT / 'listener-limit.json', {'limit': 256, 'observed': len(server_ports)})\n else: (ROOT / 'listener-limit.json').unlink(missing_ok=True)\n if capture_overflow: raise RuntimeError('Too many existing inbound control connections')\n atomic(ROOT / 'control-replies.json', replies)\n return replies\n\ndef local_bridges():\n result = []\n # Minimal VM kernels can reject a type-filtered dump; ordinary link dumps remain portable.\n links = json.loads(command('ip', '-j', '-d', 'link', 'show').stdout)\n by_name = {link['ifname']: link for link in links}\n uplinks = set()\n for route in json.loads(command('ip', '-j', '-4', 'route', 'show', 'table', 'all').stdout):\n if route.get('dst') == 'default' or route.get('gateway') is not None or route.get('nexthops'):\n uplinks.add(route.get('dev'))\n uplinks.update(hop.get('dev') for hop in route.get('nexthops', []))\n for link in links:\n if link.get('linkinfo', {}).get('info_kind') != 'bridge': continue\n try: members = list((pathlib.Path('/sys/class/net') / link['ifname'] / 'brif').iterdir())\n except FileNotFoundError: continue\n if link['ifname'] in uplinks or any(member.name in uplinks or by_name.get(member.name, {}).get('linkinfo', {}).get('info_kind') != 'veth' for member in members): continue\n name = link['ifname']\n if not re.fullmatch(r'[A-Za-z0-9_.-]{1,15}', name): raise RuntimeError('Unsupported local bridge name')\n for interface in json.loads(command('ip', '-j', '-4', 'addr', 'show', 'dev', name).stdout):\n for address in interface.get('addr_info', []):\n if address.get('family') == 'inet': result.append((name, str(ipaddress.ip_network(address['local'] + '/' + str(address['prefixlen']), strict=False))))\n return sorted(result)\n\ndef install_guard(allow_tunnel=False, closed=False):\n if closed: allow_tunnel = False\n replies = [reply for reply in load(ROOT / 'control-replies.json', []) if reply.get('uid') == 0] if closed else existing_control_replies()\n bridges = [] if closed else local_bridges()\n try: listeners = load(ROOT / 'control-listeners.json', [])\n except Exception:\n if not closed: raise\n listeners = []\n if closed: tunnel_addresses = load(ROOT / 'tunnel-addresses.json', [])\n else:\n tunnel = command('ip', '-j', 'addr', 'show', 'dev', 'final-egress0', check=False)\n tunnel_addresses = [str(ipaddress.ip_address(address['local'])) for interface in json.loads(tunnel.stdout or b'[]') for address in interface.get('addr_info', [])]\n atomic(ROOT / 'tunnel-addresses.json', tunnel_addresses)\n for family in FAMILIES:\n rules = ['*filter', ':' + CHAIN + ' - [0:0]', '-F ' + CHAIN]\n # Block namespace-local DNS stubs that would otherwise resolve on the provider's network.\n for proto in ('tcp', 'udp'):\n rules.append('-A ' + CHAIN + ' -o lo -p ' + proto + ' --dport 53 -j REJECT')\n if family == 'iptables':\n rules.append('-A ' + CHAIN + ' -d 127.0.0.11 -j REJECT')\n rules.append('-A ' + CHAIN + ' -d 100.100.100.100 -j REJECT')\n rules += ['-A ' + CHAIN + ' -o lo -j ACCEPT', '-A ' + CHAIN + ' -m mark --mark ' + MARK + ' -m owner --uid-owner 0 -j ACCEPT', '-A ' + CHAIN + ' -m mark --mark ' + MARK + ' -m conntrack --ctdir REPLY -j ACCEPT']\n if family == 'ip6tables':\n for kind in (133, 134, 135, 136):\n rules += ['-A ' + CHAIN + ' -p ipv6-icmp --icmpv6-type ' + str(kind) + ' -m owner --uid-owner 1-4294967294 -j REJECT',\n '-A ' + CHAIN + ' -p ipv6-icmp --icmpv6-type ' + str(kind) + ' -j ACCEPT']\n if family == 'iptables':\n for name, network in bridges: rules.append('-A ' + CHAIN + ' -o ' + name + ' -d ' + network + ' -j ACCEPT')\n if family == 'iptables' and allow_tunnel:\n rules.append('-A ' + CHAIN + ' -o final-egress0 -j ACCEPT')\n if closed:\n for reply in replies:\n if (':' in reply['source']) != (family == 'ip6tables'): continue\n rules.append('-A ' + CHAIN + ' -p tcp -s ' + reply['source'] + ' --sport ' + str(reply['sourcePort']) + ' -d ' + reply['destination'] + ' --dport ' + str(reply['destinationPort']) + ' --tcp-flags SYN,RST,ACK ACK -j ACCEPT')\n rules += ['-A ' + CHAIN + ' -j REJECT', 'COMMIT', '*mangle', ':' + REPLY + ' - [0:0]', '-F ' + REPLY,\n # Docker rewrites its DNS stub's port in nat/OUTPUT; block before that translation.\n '-A ' + REPLY + ' -o lo -p tcp --dport 53 -j DROP',\n '-A ' + REPLY + ' -o lo -p udp --dport 53 -j DROP',\n ]\n if family == 'iptables': rules.append('-A ' + REPLY + ' -d 127.0.0.11 -j DROP')\n # mangle/OUTPUT sees the initial exit route even for physical provider replies.\n # Exclude only the actual tunnel source addresses before marking server replies.\n for address in tunnel_addresses:\n if (':' in address) == (family == 'ip6tables'):\n rules.append('-A ' + REPLY + ' -s ' + address + ' -j RETURN')\n # Minimal provider kernels omit connmark. Reserve the existing server ports for TCP replies;\n # an untracked outgoing client's ephemeral port cannot obtain this exception.\n for listener in listeners:\n host = listener['source']\n address = ipaddress.ip_address(host)\n if (':' in host) != (family == 'ip6tables') and not (family == 'iptables' and address.version == 6 and address.is_unspecified): continue\n source = '' if ipaddress.ip_address(host).is_unspecified else ' -s ' + host\n rules.append('-A ' + REPLY + ' -p tcp' + source + ' --sport ' + str(listener['sourcePort']) +\n ' -m conntrack --ctdir REPLY --ctorigdstport ' + str(listener['sourcePort']) + ' -j MARK --set-xmark ' + MARK)\n # Conntrack can load after a provider's long-lived inbound RPC already opened (E2B envd).\n # Preserve only ACKs on those accepted server sockets, never a new outbound SYN.\n for reply in replies:\n if (':' in reply['source']) != (family == 'ip6tables'): continue\n rules.append('-A ' + REPLY + ' -p tcp -s ' + reply['source'] + ' --sport ' + str(reply['sourcePort']) +\n ' -d ' + reply['destination'] + ' --dport ' + str(reply['destinationPort']) +\n ' --tcp-flags SYN,RST,ACK ACK -j MARK --set-xmark ' + MARK)\n rules.append('COMMIT')\n # Docker can prepend filter/FORWARD accepts; mangle runs before that table.\n rules += ['*mangle', ':' + FORWARD + ' - [0:0]', '-F ' + FORWARD]\n if family == 'iptables': rules.append('-A ' + FORWARD + ' -d 100.100.100.100 -j DROP')\n if family == 'iptables':\n for name, network in bridges:\n for ingress, _ in bridges: rules.append('-A ' + FORWARD + ' -i ' + ingress + ' -o ' + name + ' -d ' + network + ' -j RETURN')\n if family == 'iptables' and allow_tunnel:\n for name, network in bridges:\n rules += ['-A ' + FORWARD + ' -i ' + name + ' -s ' + network + ' -o final-egress0 -j RETURN',\n '-A ' + FORWARD + ' -i final-egress0 -o ' + name + ' -d ' + network + ' -m conntrack --ctstate ESTABLISHED,RELATED -j RETURN']\n rules += ['-A ' + FORWARD + ' -j DROP', 'COMMIT']\n rules += ['*filter', ':' + FORWARD + ' - [0:0]', '-F ' + FORWARD]\n if family == 'iptables': rules.append('-A ' + FORWARD + ' -d 100.100.100.100 -j DROP')\n if family == 'iptables':\n for name, network in bridges:\n for ingress, _ in bridges: rules.append('-A ' + FORWARD + ' -i ' + ingress + ' -o ' + name + ' -d ' + network + ' -j RETURN')\n if family == 'iptables' and allow_tunnel:\n for name, network in bridges:\n rules += ['-A ' + FORWARD + ' -i ' + name + ' -s ' + network + ' -o final-egress0 -j ACCEPT',\n '-A ' + FORWARD + ' -i final-egress0 -o ' + name + ' -d ' + network + ' -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT']\n rules += ['-A ' + FORWARD + ' -j REJECT', 'COMMIT']\n if family == 'iptables':\n rules += ['*nat', ':' + NAT + ' - [0:0]', '-F ' + NAT]\n for name, network in bridges:\n rules.append('-A ' + NAT + ' -s ' + network + ' -o final-egress0 -j MASQUERADE')\n rules.append('COMMIT')\n installed = subprocess.run([family + '-restore', '-w', '5', '--noflush'], timeout=25, input=('\\n'.join(rules) + '\\n').encode(), stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)\n if installed.returncode: raise RuntimeError(family + ' firewall installation failed: ' + installed.stderr.decode(errors='replace')[:800])\n hooks = [('mangle', 'OUTPUT', REPLY), ('mangle', 'FORWARD', FORWARD), ('filter', 'OUTPUT', CHAIN), ('filter', 'FORWARD', FORWARD)]\n if family == 'iptables': hooks.append(('nat', 'POSTROUTING', NAT))\n for table, hook, chain in hooks:\n if command(family, '-t', table, '-C', hook, '-j', chain, check=False).returncode != 0:\n command(family, '-t', table, '-I', hook, '1', '-j', chain)\n # Reverse-NAT replies from TUN must return to a nested bridge rather than the exit default route.\n if allow_tunnel:\n while command('ip', '-4', 'rule', 'del', 'pref', '5210', 'iif', 'final-egress0', 'lookup', 'main', 'protocol', '242', check=False).returncode == 0: pass\n existing = command('ip', '-4', 'rule', 'show').stdout.decode()\n for name, network in bridges:\n if not any('to ' + value + ' iif final-egress0 lookup main' in existing for value in (network, network[:-3] if network.endswith('/32') else network)):\n command('ip', '-4', 'rule', 'add', 'pref', '5210', 'iif', 'final-egress0', 'to', network, 'lookup', 'main', 'protocol', '242')\n existing_rules = command('ip', '-4', 'rule', 'show').stdout.decode() if bridges else ''\n for name, network in bridges:\n if not any('to ' + value + ' lookup main' in existing_rules for value in (network, network[:-3] if network.endswith('/32') else network)):\n command('ip', '-4', 'rule', 'add', 'pref', '5210', 'to', network, 'lookup', 'main', 'protocol', '242')\n\ndef chain_hooked(family, table, hook, chain):\n result = command(family, '-t', table, '-S', check=False)\n if result.returncode != 0:\n if table != 'filter' and result.returncode == 3 and b'Table does not exist' in result.stderr: return False\n raise RuntimeError('Cannot inspect namespace firewall hooks')\n return ('-A ' + hook + ' -j ' + chain) in result.stdout.decode().splitlines()\n\ndef denial_present():\n for family in FAMILIES:\n for hook, chain in [('OUTPUT', CHAIN), ('FORWARD', FORWARD)]:\n if not chain_hooked(family, 'filter', hook, chain): return False\n rules = command(family, '-t', 'filter', '-S', chain, check=False)\n if rules.returncode or not any(shlex.split(line)[:4] in (['-A', chain, '-j', 'DROP'], ['-A', chain, '-j', 'REJECT']) for line in rules.stdout.decode().splitlines()): return False\n return True\n\ndef restoration_pending():\n if load(ROOT / 'config.json', {}).get('mode') == 'error' or load(ROOT / 'status.json', {}).get('mode') == 'error': return True\n if (PERSISTENT / 'hosts.original').exists() or (PERSISTENT / 'resolver.original').exists() or (not HOSTS.is_symlink() and HOSTS.exists() and '# final-workspace-egress' in HOSTS.read_text()): return True\n if RESOLVER.exists() and RESOLVER.read_bytes().startswith(b'# Final workspace egress\\n'): return True\n if not all(shutil.which(family) for family in FAMILIES):\n return (PERSISTENT / 'identity.json').exists() or load(ROOT / 'config.json', {}).get('mode', 'direct') != 'direct'\n try:\n return any(chain_hooked(family, table, hook, chain)\n for family in FAMILIES\n for table, hook, chain in [('filter', 'OUTPUT', CHAIN), ('filter', 'FORWARD', FORWARD), ('mangle', 'OUTPUT', REPLY), ('mangle', 'FORWARD', FORWARD)] + ([('nat', 'POSTROUTING', NAT)] if family == 'iptables' else []))\n except RuntimeError:\n # Never-managed images need no repair when their provider denies firewall inspection.\n if not (PERSISTENT / 'identity.json').exists() and load(ROOT / 'config.json', {}).get('mode', 'direct') == 'direct': return False\n raise\n\ndef restore():\n transport_hosts({})\n original = PERSISTENT / 'resolver.original'\n if not original.exists() and (load(PERSISTENT / 'resolver-write-pending.json', False) or (RESOLVER.exists() and RESOLVER.read_bytes().startswith(b'# Final workspace egress\\n'))):\n raise RuntimeError('Original workspace resolver backup is missing; repair the provider resolver before Disable')\n if original.exists():\n current = RESOLVER\n if load(PERSISTENT / 'resolver-write-pending.json', False) or not current.exists() or current.read_text().startswith('# Final workspace egress\\n'):\n link = load(PERSISTENT / 'resolver-link.json')\n if link is None:\n if load(PERSISTENT / 'resolver-absent.json', False): current.unlink(missing_ok=True)\n else:\n if current.is_symlink(): current.unlink()\n managed_text(current, original.read_text())\n else:\n staged = current.parent / ('.final-egress-resolver-' + uuid.uuid4().hex)\n try:\n os.symlink(link['target'], staged); os.replace(staged, current)\n finally: staged.unlink(missing_ok=True)\n (PERSISTENT / 'resolver-write-pending.json').unlink(missing_ok=True)\n original.unlink()\n (PERSISTENT / 'resolver-link.json').unlink(missing_ok=True)\n (PERSISTENT / 'resolver-absent.json').unlink(missing_ok=True)\n for family in FAMILIES:\n hooks = [('filter', 'OUTPUT', CHAIN), ('mangle', 'OUTPUT', REPLY), ('mangle', 'FORWARD', FORWARD), ('filter', 'FORWARD', FORWARD)]\n if family == 'iptables': hooks.append(('nat', 'POSTROUTING', NAT))\n for table, hook, chain in hooks:\n while chain_hooked(family, table, hook, chain):\n command(family, '-t', table, '-D', hook, '-j', chain)\n command(family, '-t', table, '-F', chain, check=False)\n command(family, '-t', table, '-X', chain, check=False)\n while command('ip', '-4', 'rule', 'del', 'pref', '5210', 'protocol', '242', 'lookup', 'main', check=False).returncode == 0: pass\n for saved in ('control-replies.json', 'control-listeners.json', 'listener-limit.json', 'tunnel-addresses.json'):\n (ROOT / saved).unlink(missing_ok=True)\n (PERSISTENT / 'identity.json').unlink(missing_ok=True)\n (PERSISTENT / 'intent.json').unlink(missing_ok=True)\n\ndef validated_resolvers(addresses):\n if not isinstance(addresses, list) or not addresses or len(addresses) > 3:\n raise RuntimeError('One to three IPv4 DNS resolvers are required')\n addresses = [str(ipaddress.IPv4Address(address)) for address in addresses]\n if len(set(addresses)) != len(addresses) or any(int(address.split('.')[0]) in (0, 127) or int(address.split('.')[0]) >= 224 or address == '100.100.100.100' for address in addresses):\n raise RuntimeError('Device DNS resolvers must be unique reachable unicast addresses')\n return addresses\n\ndef resolver(addresses):\n addresses = validated_resolvers(addresses)\n source = RESOLVER\n if not (PERSISTENT / 'resolver.original').exists():\n if source.exists() and source.read_bytes().startswith(b'# Final workspace egress\\n'):\n raise RuntimeError('Original workspace resolver backup is missing; repair the provider resolver')\n absent = not source.exists() and not source.is_symlink()\n try: original = source.read_bytes()\n except FileNotFoundError: original = b''\n atomic(PERSISTENT / 'resolver-absent.json', absent)\n if source.is_symlink(): atomic(PERSISTENT / 'resolver-link.json', {'target': os.readlink(source)})\n else: (PERSISTENT / 'resolver-link.json').unlink(missing_ok=True)\n atomic(PERSISTENT / 'resolver.original', original, binary=True)\n content = '# Final workspace egress\\n' + ''.join('nameserver ' + address + '\\n' for address in addresses) + 'options timeout:2 attempts:2\\n'\n if not source.is_symlink() and source.exists() and source.read_bytes() == content.encode(): return\n managed_text(source, content)\n\ndef transport_hosts(hosts):\n original = PERSISTENT / 'hosts.original'\n absent = PERSISTENT / 'hosts-absent.json'\n if HOSTS.is_symlink():\n if hosts: raise PrerequisiteError('Workspace egress requires a regular /etc/hosts file')\n if original.exists():\n if load(absent, False): HOSTS.unlink()\n else: atomic(HOSTS, original.read_bytes(), binary=True, mode=0o644)\n original.unlink(); absent.unlink(missing_ok=True)\n return\n if hosts and not original.exists():\n atomic(absent, not HOSTS.exists())\n atomic(original, HOSTS.read_bytes() if HOSTS.exists() else b'', binary=True)\n if not HOSTS.exists() and not hosts:\n if original.exists() and not load(absent, False): atomic(HOSTS, original.read_bytes(), binary=True, mode=0o644)\n original.unlink(missing_ok=True); absent.unlink(missing_ok=True)\n return\n lines = HOSTS.read_text().splitlines() if HOSTS.exists() else []\n lines = [line for line in lines if not line.endswith('# final-workspace-egress')]\n for host, address in hosts.items():\n if not host or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-' for c in host):\n raise RuntimeError('Invalid egress transport hostname')\n lines.append(str(ipaddress.IPv4Address(address)) + ' ' + host + ' # final-workspace-egress')\n content = '\\n'.join(lines) + '\\n'\n if not hosts and load(absent, False) and not lines: HOSTS.unlink(missing_ok=True)\n elif not HOSTS.exists() or HOSTS.read_text() != content: managed_text(HOSTS, content)\n if not hosts:\n original.unlink(missing_ok=True); absent.unlink(missing_ok=True)\n\ndef status(mode, config, **extra):\n try: policy_routing = command('ip', '-4', 'rule', 'show', check=False).returncode == 0\n except FileNotFoundError: policy_routing = False\n result = {'mode': mode, 'leaseId': config.get('leaseId'), 'ownerUserId': config.get('ownerUserId'),\n 'workspaceId': config.get('workspaceId'), 'architecture': platform.machine(), 'policyRouting': policy_routing, 'expiresAtMs': config.get('expiresAtMs'), 'deviceId': None, 'path': None, **extra}\n atomic(ROOT / 'status.json', result)\n return result\n\ndef controller_status(mode, config, **extra):\n # A writer may await daemon shutdown while holding this lock; skip stale/busy publication.\n with open(ROOT / 'request.lock', 'a') as requests:\n try: fcntl.flock(requests, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except BlockingIOError: return\n saved = load(ROOT / 'config.json', {})\n fields = ('mode', 'revision', 'leaseId', 'workspaceId', 'ownerUserId', 'expiresAtMs', 'state')\n if any(saved.get(field) != config.get(field) for field in fields): return\n return status(mode, config, **extra)\n\ndef lease_id(value):\n if not isinstance(value, str) or not value: raise RuntimeError('Missing workspace lease identifier')\n return value\n\ndef lease_state_name(value):\n value = lease_id(value)\n try: return str(uuid.UUID(value))\n except ValueError: return 'opaque-' + hashlib.sha256(value.encode()).hexdigest()\n\ndef helper_environment():\n env = {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin'}\n env.update(FINAL_TAILSCALE_MANAGED='1', FINAL_DEVICE_PARENT_PID=str(os.getpid()), TS_NO_LOGS_NO_SUPPORT='true', TS_DEBUG_ENV_FILE='/dev/null', TS_LOGS_DIR=str(ROOT / 'logs'))\n return env\n\ndef cli(helper, sock, *args):\n # CLI operations are managed children as well: closing their pipe stops them on controller death.\n env = helper_environment()\n errors = os.open(ROOT / 'last-control-error.log', os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)\n try:\n proc = subprocess.Popen([str(helper), 'final-cli', '--socket=' + str(sock), *args], stdin=subprocess.PIPE,\n stdout=subprocess.PIPE, stderr=errors, env=env)\n finally: os.close(errors)\n try:\n proc.stdin.write(b'final-device-start\\n'); proc.stdin.flush()\n deadline = time.monotonic() + 20\n output = bytearray()\n os.set_blocking(proc.stdout.fileno(), False)\n while proc.poll() is None:\n chunk = proc.stdout.read(65536)\n if chunk: output.extend(chunk)\n if len(output) > 1024 * 1024 or time.monotonic() > deadline:\n raise RuntimeError('Workspace egress control operation exceeded its limit: ' + args[0])\n time.sleep(.01)\n output.extend(proc.stdout.read() or b'')\n if proc.returncode != 0:\n detail = ': ' + bytes(output).decode(errors='replace')[:1000] if args[0] == 'ping' else ''\n raise RuntimeError('Workspace egress control operation failed (' + args[0] + ')' + detail)\n return bytes(output)\n finally:\n try: proc.stdin.close()\n except BrokenPipeError: pass\n if proc.poll() is None: proc.kill()\n proc.wait()\n\ndef stop(proc):\n if proc is not None:\n try: proc.stdin.close()\n except BrokenPipeError: pass\n try: proc.wait(timeout=2)\n except subprocess.TimeoutExpired: proc.kill(); proc.wait()\n\ndef minimal_guard():\n failures = []\n # Cached accepted sockets permit recovery even without conntrack or mangle.\n try: replies = [reply for reply in load(ROOT / 'control-replies.json', []) if reply.get('uid') == 0]\n except Exception: replies = []\n for family in FAMILIES:\n try:\n for hook, chain in [('OUTPUT', CHAIN), ('FORWARD', FORWARD)]:\n existing = command(family, '-t', 'filter', '-S', chain, check=False)\n hooked = command(family, '-t', 'filter', '-C', hook, '-j', chain, check=False)\n # Retain a successfully installed closed family and its control exceptions.\n if existing.returncode == 0 and hooked.returncode == 0 and b'-o final-egress0' not in existing.stdout and any(shlex.split(line)[:4] in (['-A', chain, '-j', 'DROP'], ['-A', chain, '-j', 'REJECT']) for line in existing.stdout.decode().splitlines()): continue\n rules = ['*filter', ':' + chain + ' - [0:0]', '-F ' + chain]\n if hook == 'OUTPUT':\n for proto in ('tcp', 'udp'):\n rules.append('-A ' + chain + ' -o lo -p ' + proto + ' --dport 53 -j DROP')\n if family == 'iptables':\n rules += ['-A ' + chain + ' -d 127.0.0.11 -j DROP', '-A ' + chain + ' -d 100.100.100.100 -j DROP']\n rules.append('-A ' + chain + ' -o lo -j ACCEPT')\n if family == 'ip6tables':\n for kind in (133, 134, 135, 136):\n rules += ['-A ' + chain + ' -p ipv6-icmp --icmpv6-type ' + str(kind) + ' -m owner --uid-owner 1-4294967294 -j REJECT',\n '-A ' + chain + ' -p ipv6-icmp --icmpv6-type ' + str(kind) + ' -j ACCEPT']\n for reply in replies:\n if (':' in reply['source']) != (family == 'ip6tables'): continue\n rules.append('-A ' + chain + ' -p tcp -s ' + reply['source'] + ' --sport ' + str(reply['sourcePort']) +\n ' -d ' + reply['destination'] + ' --dport ' + str(reply['destinationPort']) +\n ' --tcp-flags SYN,RST,ACK ACK -j ACCEPT')\n rules += ['-A ' + chain + ' -j DROP', 'COMMIT']\n result = subprocess.run([family + '-restore', '-w', '5', '--noflush'], input=('\\n'.join(rules) + '\\n').encode(), capture_output=True, timeout=25)\n if result.returncode and family == 'ip6tables':\n # Without owner matching, deny IPv6 neighbor traffic too rather than leaving the family open.\n fallback = [rule for rule in rules if '-p ipv6-icmp ' not in rule]\n result = subprocess.run([family + '-restore', '-w', '5', '--noflush'], input=('\\n'.join(fallback) + '\\n').encode(), capture_output=True, timeout=25)\n if result.returncode: raise RuntimeError('Atomic emergency denial failed for ' + family)\n if hooked.returncode != 0: command(family, '-t', 'filter', '-I', hook, '1', '-j', chain)\n except Exception as cause: failures.append(str(cause))\n if failures: raise RuntimeError('Cannot install minimal namespace denial: ' + '; '.join(failures))\n\ndef guard(allow_tunnel=False):\n try: install_guard(allow_tunnel)\n except Exception:\n try: install_guard(closed=True)\n except Exception:\n try: minimal_guard()\n except Exception as failure:\n raise DenialUnavailableError('Workspace network denial could not be installed') from failure\n raise\n\ndef clear_identity():\n for path in ROOT.glob('state-*'):\n if path.is_file(): path.unlink()\n (ROOT / 'enrollment.key').unlink(missing_ok=True)\n\ndef stop_controller():\n with open(ROOT / 'daemon.lock', 'a') as lock:\n deadline = time.monotonic() + 5\n signaled = None\n while True:\n pid = load(ROOT / 'controller.pid')\n if isinstance(pid, int) and pid != signaled:\n try:\n args = pathlib.Path('/proc/' + str(pid) + '/cmdline').read_bytes().split(bytes([0]))\n if str(ROOT / 'controller.py').encode() in args and b'run' in args:\n os.kill(pid, signal.SIGTERM); signaled = pid\n except ProcessLookupError: pass\n except FileNotFoundError: pass\n try:\n fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)\n clear_identity()\n return\n except BlockingIOError:\n if time.monotonic() >= deadline: raise RuntimeError('Workspace egress controller did not stop')\n time.sleep(.05)\n\ndef capture_errors(proc):\n tail = collections.deque(maxlen=128)\n while True:\n chunk = proc.stderr.read1(4096)\n if not chunk: return\n tail.append(chunk)\n atomic(ROOT / 'daemon.log', b''.join(tail), binary=True)\n\ndef select_exit(config, peers, selected, health_misses, helper, sock):\n candidates = sorted(config.get('devices', []), key=lambda item: item.get('tailscaleIp') != selected)\n for item in candidates:\n ip = item.get('tailscaleIp')\n if ip not in peers or not peers[ip].get('Online') or peers[ip].get('Expired'): continue\n try:\n # TSMP tests the encrypted peer path without opening a destination connection.\n cli(helper, sock, 'ping', '--tsmp', '--c=1', '--timeout=2s', str(ipaddress.IPv4Address(ip)))\n health_misses[ip] = 0\n return item\n except (RuntimeError, ValueError) as cause:\n atomic(ROOT / 'last-peer-error.json', {'deviceId': item['deviceId'], 'error': str(cause), 'atMs': int(time.time() * 1000)})\n health_misses[ip] = health_misses.get(ip, 0) + 1\n if ip == selected and health_misses[ip] < 3: break\n continue\n return None\n\ndef run():\n with open(ROOT / 'daemon.lock', 'a') as lock:\n deadline = time.monotonic() + 5\n while True:\n try:\n fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)\n break\n except BlockingIOError:\n pid = load(ROOT / 'controller.pid')\n alive = False\n try:\n alive = isinstance(pid, int) and str(ROOT / 'controller.py').encode() in pathlib.Path('/proc/' + str(pid) + '/cmdline').read_bytes().split(bytes([0]))\n except FileNotFoundError: pass\n if time.monotonic() >= deadline:\n if alive: return\n raise RuntimeError('Workspace controller startup lock is busy')\n time.sleep(.01)\n atomic(ROOT / 'controller.pid', os.getpid())\n proc = None\n current = None\n selected = None\n health_misses = {}\n bridges = None\n revision = None\n def terminate(signum, frame):\n raise SystemExit(0)\n signal.signal(signal.SIGTERM, terminate)\n signal.signal(signal.SIGINT, terminate)\n try:\n while True:\n config = load(ROOT / 'config.json', {})\n mode = config.get('mode', 'blocked')\n if mode != 'device' or config.get('bootId') != BOOT_ID or config.get('expiresAtMs', 0) <= time.time() * 1000 or config.get('deadlineMonotonic', 0) <= time.monotonic():\n # Coordinate relinquishing the daemon lock with writers so a renewal cannot lose its controller.\n with open(ROOT / 'request.lock', 'a') as requests:\n fcntl.flock(requests, fcntl.LOCK_EX)\n if load(ROOT / 'config.json', {}) != config: continue\n stop(proc); proc = None; current = None; selected = None\n clear_identity()\n if mode == 'direct':\n restore(); status('direct', config)\n else:\n guard(); status('blocked', config)\n fcntl.flock(lock, fcntl.LOCK_UN)\n return\n helper = ROOT / 'helper'\n sock = ROOT / 'control.sock'\n revision = config.get('revision', config['leaseId'])\n if revision != current or proc is None or proc.poll() is not None:\n stop(proc); proc = None\n with open(ROOT / 'request.lock', 'a') as requests:\n fcntl.flock(requests, fcntl.LOCK_EX)\n if load(ROOT / 'config.json', {}).get('revision', load(ROOT / 'config.json', {}).get('leaseId')) != revision: continue\n guard(); transport_hosts(config['transportHosts'])\n sock.unlink(missing_ok=True)\n state = ROOT / ('state-' + lease_state_name(config['leaseId']))\n for old in ROOT.glob('state-*'):\n if old != state and old.is_file(): old.unlink()\n env = helper_environment()\n proc = subprocess.Popen([str(helper), '--tun=final-egress0', '--port=0', '--socket=' + str(sock), '--state=' + str(state)],\n stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=env)\n threading.Thread(target=capture_errors, args=(proc,), daemon=True).start()\n proc.stdin.write(b'final-device-start\\n'); proc.stdin.flush()\n deadline = time.monotonic() + 5\n while not sock.exists():\n if proc.poll() is not None or time.monotonic() > deadline:\n raise RuntimeError('Workspace egress daemon did not become ready')\n time.sleep(.05)\n args = ['up', '--reset', '--login-server=' + config['controlUrl'], '--hostname=workspace-' + lease_state_name(config['leaseId'])[:40],\n '--accept-dns=false', '--accept-routes=false', '--shields-up', '--netfilter-mode=off']\n if config.get('authKey'):\n atomic(ROOT / 'enrollment.key', config['authKey'].encode(), binary=True)\n args.append('--auth-key=file:' + str(ROOT / 'enrollment.key'))\n args.append('--force-reauth')\n try: cli(helper, sock, *args)\n finally:\n (ROOT / 'enrollment.key').unlink(missing_ok=True)\n with open(ROOT / 'request.lock', 'a') as requests:\n # A writer may hold request.lock while awaiting our daemon.lock.\n try: fcntl.flock(requests, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except BlockingIOError: pass\n else:\n pending = load(ROOT / 'config.json', {})\n if pending.get('revision', pending.get('leaseId')) == revision:\n pending.pop('authKey', None); atomic(ROOT / 'config.json', pending)\n with open(ROOT / 'request.lock', 'a') as requests:\n fcntl.flock(requests, fcntl.LOCK_EX)\n saved = load(ROOT / 'config.json', {})\n if saved.get('mode') != 'device' or saved.get('leaseId') != config.get('leaseId') or saved.get('revision', saved.get('leaseId')) != revision:\n stop(proc); proc = None; current = None; selected = None\n continue\n resolver(saved.get('dnsResolvers', ['1.1.1.1', '9.9.9.9']))\n saved.pop('authKey', None); atomic(ROOT / 'config.json', saved)\n current = revision; selected = None\n guard(allow_tunnel=True)\n if config.get('state') == 'provisioning':\n controller_status('enrolled', config)\n time.sleep(.2)\n continue\n actual_bridges = local_bridges()\n with open(ROOT / 'request.lock', 'a') as requests:\n fcntl.flock(requests, fcntl.LOCK_EX)\n latest = load(ROOT / 'config.json', {})\n if latest.get('mode') != 'device' or latest.get('revision', latest.get('leaseId')) != revision: continue\n resolver(latest.get('dnsResolvers', ['1.1.1.1', '9.9.9.9']))\n previous_listeners = load(ROOT / 'control-listeners.json', [])\n existing_control_replies()\n actual_tunnel = command('ip', '-j', 'addr', 'show', 'dev', 'final-egress0', check=False)\n actual_addresses = [str(ipaddress.ip_address(address['local'])) for interface in json.loads(actual_tunnel.stdout or b'[]') for address in interface.get('addr_info', [])]\n if bridges != actual_bridges or previous_listeners != load(ROOT / 'control-listeners.json', []) or actual_addresses != load(ROOT / 'tunnel-addresses.json', []):\n guard(allow_tunnel=True); bridges = actual_bridges\n try:\n raw = json.loads(cli(helper, sock, 'status', '--json'))\n peers = {ip: peer for peer in (raw.get('Peer') or {}).values() for ip in (peer.get('TailscaleIPs') or [])}\n candidates = config.get('devices', [])\n candidate = select_exit(config, peers, selected, health_misses, helper, sock)\n if candidate is None:\n last = next((item for item in candidates if item.get('tailscaleIp') == selected), None)\n # A health miss must not tear down an authorized route during control outage/rekey.\n # Keeping it can only use the approved exit; the namespace guard still forbids direct fallback.\n if last is not None and selected in peers and not peers[selected].get('Expired'):\n peer = peers[selected]\n controller_status('reconnecting', config, deviceId=last['deviceId'], path='direct' if peer.get('CurAddr') else 'relay')\n else:\n if selected is not None: cli(helper, sock, 'set', '--exit-node=')\n selected = None\n controller_status('blocked', config)\n else:\n ip = str(ipaddress.IPv4Address(candidate['tailscaleIp']))\n if selected != ip:\n cli(helper, sock, 'set', '--exit-node=' + ip, '--exit-node-allow-lan-access=false')\n selected = ip\n route = command('ip', '-4', 'route', 'get', '192.0.2.254').stdout\n if b'dev final-egress0' not in route:\n controller_status('configuring', config)\n time.sleep(.1)\n continue\n peer = peers[ip]\n controller_status('device', config, deviceId=candidate['deviceId'], path='direct' if peer.get('CurAddr') else 'relay')\n time.sleep(1)\n except (RuntimeError, subprocess.TimeoutExpired, json.JSONDecodeError) as failure:\n atomic(ROOT / 'last-peer-error.json', {'error': str(failure)[:1000], 'atMs': int(time.time() * 1000)})\n controller_status('reconnecting', config)\n time.sleep(1)\n except Exception as cause:\n atomic(ROOT / 'last-error.json', {'error': str(cause), 'atMs': int(time.time() * 1000)})\n controller_status('error', load(ROOT / 'config.json', {}), error='Workspace egress stopped; inspect the controller error')\n raise\n finally:\n stop(proc)\n if load(ROOT / 'controller.pid') == os.getpid(): (ROOT / 'controller.pid').unlink(missing_ok=True)\n # Writers can await daemon.lock while holding request.lock; finish secret cleanup after releasing it.\n fcntl.flock(lock, fcntl.LOCK_UN)\n with open(ROOT / 'request.lock', 'a') as requests:\n fcntl.flock(requests, fcntl.LOCK_EX)\n pending = load(ROOT / 'config.json', {})\n if revision is not None and pending.get('revision', pending.get('leaseId')) == revision and 'authKey' in pending:\n pending.pop('authKey', None); atomic(ROOT / 'config.json', pending)\n\ndef apply(request):\n prerequisite(request['action'])\n with open(ROOT / 'request.lock', 'a') as lock:\n fcntl.flock(lock, fcntl.LOCK_EX)\n action = request['action']\n source = pathlib.Path(__file__).read_bytes() if '__file__' in globals() else sys.argv[1].encode()\n cached_source = ROOT / 'controller.py'\n if not cached_source.exists() or cached_source.read_bytes() != source: atomic(cached_source, source, binary=True)\n existing = load(ROOT / 'config.json', {})\n capabilities = [int(line.split()[1], 16) for line in pathlib.Path('/proc/self/status').read_text().splitlines() if line.startswith(('CapInh:', 'CapPrm:', 'CapEff:', 'CapBnd:', 'CapAmb:'))]\n # A prior choice with lost volatile state is not proof of an untouched namespace.\n network_pristine = (existing.get('noNetworkChanges') is True or ((not existing or existing.get('mode') == 'direct') and not (PERSISTENT / 'intent.json').exists())) and bool(capabilities) and not any(mask & (1 << 12) for mask in capabilities) and not (PERSISTENT / 'resolver.original').exists() and not (PERSISTENT / 'hosts.original').exists() and not (ROOT / 'controller.pid').exists()\n workspace_id = request.get('workspaceId')\n if action != 'status' and existing.get('workspaceId') is not None and existing['workspaceId'] != workspace_id:\n raise RuntimeError('This network namespace belongs to a different workspace')\n operation = load(ROOT / 'operation.json', {})\n operation_live = operation.get('bootId') == BOOT_ID and operation.get('deadline', 0) > time.monotonic()\n token = str(uuid.UUID(request['configurationToken'])) if request.get('configurationToken') is not None else None\n if action == 'claim':\n if (request.get('refresh') or request.get('verifyOnly')) and (not operation_live or operation.get('token') != token):\n raise WorkspaceConflictError('Workspace configuration claim was superseded')\n if operation_live and operation.get('token') != token:\n return {**load(ROOT / 'status.json', {'mode': 'blocked', 'leaseId': None, 'expiresAtMs': None, 'deviceId': None, 'path': None}), 'busy': True}\n token = str(uuid.UUID(token))\n if not request.get('verifyOnly'):\n atomic(ROOT / 'operation.json', {'token': token, 'deadline': time.monotonic() + 300, 'bootId': BOOT_ID})\n return {**load(ROOT / 'status.json', {'mode': 'blocked', 'leaseId': None, 'expiresAtMs': None, 'deviceId': None, 'path': None}), 'busy': False}\n if action == 'unlock':\n if operation.get('token') == token: (ROOT / 'operation.json').unlink(missing_ok=True)\n return load(ROOT / 'status.json', {'mode': 'blocked', 'leaseId': None, 'expiresAtMs': None, 'deviceId': None, 'path': None})\n if action not in ('status', 'artifact'):\n if token is not None and (not operation_live or operation.get('token') != token):\n raise WorkspaceConflictError('Workspace egress configuration was superseded')\n if operation_live and token != operation.get('token'):\n raise WorkspaceConflictError('Another binding is configuring workspace egress')\n expected = lease_id(request['expectedLeaseId']) if request.get('expectedLeaseId') is not None else None\n if token is None and expected is not None and existing.get('leaseId') != expected:\n if action == 'block' and existing.get('leaseId') is None and existing.get('mode') == 'direct':\n return load(ROOT / 'status.json', {'mode': 'direct', 'leaseId': None, 'expiresAtMs': None, 'deviceId': None, 'path': None})\n if action == 'block' and existing.get('leaseId') is None and existing.get('mode') == 'blocked':\n try: guard()\n except Exception as failure:\n status('error' if isinstance(failure, DenialUnavailableError) else 'blocked', existing)\n raise\n return status('blocked', existing)\n if not (action == 'block' and existing.get('leaseId') is None and (not existing or existing.get('mode') == 'blocked')):\n raise WorkspaceConflictError('Workspace egress lease changed before cleanup')\n if action not in ('status', 'artifact'):\n PERSISTENT.mkdir(mode=0o700, exist_ok=True)\n if PERSISTENT.is_symlink() or PERSISTENT.stat().st_uid != 0:\n raise RuntimeError('Persistent workspace egress state must be root-owned')\n PERSISTENT.chmod(0o700)\n identity = load(PERSISTENT / 'identity.json', {})\n if identity.get('workspaceId') is not None and identity['workspaceId'] != workspace_id:\n raise RuntimeError('Persistent egress state belongs to a different workspace')\n if action != 'disable': atomic(PERSISTENT / 'identity.json', {'workspaceId': workspace_id})\n if action == 'block': atomic(PERSISTENT / 'intent.json', {'requiresChoice': not request.get('restoreDirect', False)})\n if action == 'disable' and existing.get('noNetworkChanges') is True:\n if (PERSISTENT / 'resolver.original').exists() or (PERSISTENT / 'hosts.original').exists() or (ROOT / 'controller.pid').exists():\n raise RuntimeError('Workspace contains restoration artifacts; privileged repair is required')\n (PERSISTENT / 'identity.json').unlink(missing_ok=True)\n (PERSISTENT / 'intent.json').unlink(missing_ok=True)\n config = {'mode': 'direct', 'workspaceId': workspace_id, 'ownerUserId': None}\n atomic(ROOT / 'config.json', config)\n return status('direct', config)\n if action == 'disable' and (not existing or (existing.get('mode') == 'direct' and load(ROOT / 'status.json', {}).get('mode') == 'direct')):\n if restoration_pending(): restore()\n (PERSISTENT / 'identity.json').unlink(missing_ok=True)\n (PERSISTENT / 'intent.json').unlink(missing_ok=True)\n config = {'mode': 'direct', 'workspaceId': workspace_id, 'ownerUserId': None}\n atomic(ROOT / 'config.json', config)\n return status('direct', config)\n if action == 'artifact':\n ready = False\n try: fd = os.open(ROOT / 'helper', os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)\n except FileNotFoundError: pass\n else:\n with os.fdopen(fd, 'rb') as source:\n info = os.fstat(source.fileno())\n if stat.S_ISREG(info.st_mode) and info.st_size <= 128 * 1024 * 1024:\n ready = hashlib.sha256(source.read(128 * 1024 * 1024 + 1)).hexdigest() == request['sha256']\n return {**load(ROOT / 'status.json', {'mode': 'blocked', 'leaseId': None, 'expiresAtMs': None, 'deviceId': None, 'path': None}), 'helperReady': ready}\n if action == 'status':\n result = load(ROOT / 'status.json', {'mode': 'direct', 'leaseId': None, 'expiresAtMs': None, 'deviceId': None, 'path': None, 'architecture': platform.machine()})\n alive = False\n with open(ROOT / 'daemon.lock', 'a') as daemon_lock:\n try:\n fcntl.flock(daemon_lock, fcntl.LOCK_EX | fcntl.LOCK_NB)\n if result.get('mode') != 'error' and existing.get('mode') not in ('direct', 'error') and existing:\n result = {**result, 'mode': 'blocked' if denial_present() else 'error', 'deviceId': None, 'path': None}\n except BlockingIOError: alive = True\n return {**result, 'networkPristine': existing.get('noNetworkChanges', False), 'controllerAlive': alive, 'configuring': operation_live, 'restorePending': restoration_pending(), 'choicePending': load(PERSISTENT / 'intent.json', {}).get('requiresChoice', existing.get('mode') == 'blocked')}\n if action in ('block', 'configure'):\n try: guard()\n except Exception as failure:\n mode = 'error' if isinstance(failure, DenialUnavailableError) else 'blocked'\n failed = {'mode': mode, 'workspaceId': workspace_id, 'ownerUserId': request.get('ownerUserId'), 'noNetworkChanges': network_pristine}\n atomic(ROOT / 'config.json', failed); status(mode, failed)\n raise\n if action == 'configure':\n # Validation failure must not leave an old direct/device status after guard installation.\n pending = {'mode': 'blocked', 'workspaceId': workspace_id, 'ownerUserId': request.get('ownerUserId')}\n atomic(ROOT / 'config.json', pending); status('blocked', pending)\n if request.get('config', {}).get('workspaceId') != workspace_id: raise RuntimeError('Enrollment belongs to a different workspace')\n if command('ip', '-4', 'rule', 'show', check=False).returncode != 0:\n raise PrerequisiteError('This workspace kernel does not support Linux policy routing')\n config = request['config']\n config['dnsResolvers'] = validated_resolvers(config.get('dnsResolvers', ['1.1.1.1', '9.9.9.9']))\n control = urllib.parse.urlsplit(config['controlUrl'])\n if control.scheme != 'https' or not control.hostname or control.username is not None or control.password is not None or control.query or control.fragment:\n raise RuntimeError('Workspace control URL must use HTTPS without credentials, query or fragment')\n config['leaseId'] = lease_id(config['leaseId'])\n remaining = config['expiresAtMs'] - time.time() * 1000\n if not 0 < remaining <= 16 * 60 * 1000:\n raise RuntimeError('Workspace egress lease is expired or exceeds fifteen minutes')\n config['bootId'] = BOOT_ID\n config['deadlineMonotonic'] = time.monotonic() + min(remaining, 15 * 60 * 1000) / 1000\n # The sandbox user can replace staging files; validate and install the same bytes.\n staged = pathlib.Path(request['helperPath'])\n try: fd = os.open(staged, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)\n except FileNotFoundError as failure:\n raise RuntimeError('Staged networking helper is missing; transfer the approved artifact again') from failure\n with os.fdopen(fd, 'rb') as source:\n if not stat.S_ISREG(os.fstat(source.fileno()).st_mode):\n raise RuntimeError('Workspace networking helper must be a regular file')\n content = source.read(128 * 1024 * 1024 + 1)\n if len(content) > 128 * 1024 * 1024 or hashlib.sha256(content).hexdigest() != config['helper']['sha256']:\n raise RuntimeError('Workspace networking helper failed integrity verification')\n machine = {'x86_64': 62, 'aarch64': 183}.get(platform.machine())\n if content[:6] != b'\\x7fELF\\x02\\x01' or len(content) < 20 or struct.unpack('<H', content[18:20])[0] != machine:\n raise RuntimeError('The pinned networking helper does not match this Linux workspace architecture')\n atomic(ROOT / 'helper', content, binary=True, mode=0o700)\n config = dict(config, mode='device')\n elif action == 'renew':\n request['lease']['leaseId'] = lease_id(request['lease']['leaseId'])\n if request.get('lease', {}).get('workspaceId') != workspace_id: raise RuntimeError('Renewal belongs to a different workspace')\n config = load(ROOT / 'config.json')\n if config is None or config.get('leaseId') != request['lease']['leaseId']:\n raise WorkspaceConflictError('Workspace egress lease changed')\n if config.get('bootId') != BOOT_ID or config.get('deadlineMonotonic', 0) <= time.monotonic() or config.get('expiresAtMs', 0) <= time.time() * 1000:\n raise EnrollmentLostError('Workspace enrollment expired locally; authorized reenrollment is required')\n lease = request['lease']\n lease['leaseId'] = lease_id(lease['leaseId'])\n remaining = lease['expiresAtMs'] - time.time() * 1000\n if not 0 < remaining <= 16 * 60 * 1000:\n raise RuntimeError('Workspace egress renewal is invalid')\n config.update(bootId=BOOT_ID, expiresAtMs=lease['expiresAtMs'], devices=lease['devices'], state=lease['state'], deadlineMonotonic=time.monotonic() + min(remaining, 15 * 60 * 1000) / 1000)\n elif action in ('block', 'disable'):\n config = {'mode': 'direct' if action == 'disable' else 'blocked', 'workspaceId': workspace_id, 'ownerUserId': None if action == 'disable' else request.get('ownerUserId')}\n else:\n raise RuntimeError('Unknown workspace egress action')\n atomic(ROOT / 'config.json', config)\n if action in ('block', 'disable'): stop_controller()\n if action == 'renew':\n with open(ROOT / 'daemon.lock', 'a') as daemon_lock:\n try: fcntl.flock(daemon_lock, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except BlockingIOError:\n prior = load(ROOT / 'status.json', {})\n return {**prior, 'expiresAtMs': config['expiresAtMs']}\n # The controller uses a root-owned copy after this caller's temporary files are removed.\n source = pathlib.Path(__file__).read_bytes() if '__file__' in globals() else sys.argv[1].encode()\n atomic(ROOT / 'controller.py', source, binary=True)\n subprocess.Popen([sys.executable, '-I', str(ROOT / 'controller.py'), 'run'], stdin=subprocess.DEVNULL,\n stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)\n if action == 'block': return status('blocked', config)\n return status('configuring', config)\n\nif __name__ == '__main__':\n try:\n if len(sys.argv) > 1 and sys.argv[1] == 'run': run()\n else: print(json.dumps(apply(json.load(sys.stdin))))\n except Exception as cause:\n try:\n if ROOT.exists() and not ROOT.is_symlink() and ROOT.stat().st_uid == 0:\n atomic(ROOT / 'last-error.json', {'error': str(cause)[:1000], 'atMs': int(time.time() * 1000)})\n except OSError: pass\n code = 'egress_enrollment_lost' if isinstance(cause, EnrollmentLostError) else 'prerequisite' if isinstance(cause, (FileNotFoundError, PrerequisiteError)) else 'conflict' if isinstance(cause, WorkspaceConflictError) else 'configuration'\n print(json.dumps({'errorCode': code}))\n sys.exit(1)\n`;\n\n// Verify the owned source before executing it; a cache miss requests the full bootstrap once.\nexport const cachedWorkspaceEgressBootstrap = (sha256: string): string => {\n if (!/^[a-f0-9]{64}$/.test(sha256)) throw new Error('Invalid workspace controller SHA256');\n return String.raw`import hashlib, os, pathlib, stat\npath = pathlib.Path('/run/final-workspace-egress/controller.py')\ntry:\n fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)\n with os.fdopen(fd, 'rb') as file:\n info = os.fstat(file.fileno())\n source = file.read(128 * 1024 + 1)\n valid = stat.S_ISREG(info.st_mode) and info.st_uid == 0 and not info.st_mode & 0o022 and len(source) <= 128 * 1024 and hashlib.sha256(source).hexdigest() == '${sha256}'\nexcept OSError: valid = False\nif valid: exec(compile(source, str(path), 'exec'), {'__name__': '__main__', '__file__': str(path)})\nelse: print('{\"needsBootstrap\":true}')\n`;\n};\n\n// Keep provider command arguments small; credentials and trusted source travel on stdin.\nexport const workspaceEgressLauncher = String.raw`import io,json,sys\nrequest=json.load(sys.stdin)\nsource=request['source']\nsys.argv=['-c',source]\nsys.stdin=io.StringIO(request['input'])\nexec(compile(source,'<final-workspace-egress>','exec'),{'__name__':'__main__'})\n`;\n"],
5
+ "mappings": "AACO,MAAM,2BAA2B,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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  }
@@ -486,7 +486,8 @@ const createWorkspaceEgressManager = (options) => {
486
486
  bytes = downloaded;
487
487
  }
488
488
  const hash = helper.sha256;
489
- const helperPath = bytes == null ? "/run/final-workspace-egress/helper" : `/tmp/final-egress-${crypto.randomUUID()}`;
489
+ const stagingDirectory = bytes == null ? null : `/tmp/final-egress-${crypto.randomUUID()}`;
490
+ const helperPath = stagingDirectory == null ? "/run/final-workspace-egress/helper" : `${stagingDirectory}/helper`;
490
491
  let leaseId = null;
491
492
  const outcome = { result: null, failures: [] };
492
493
  try {
@@ -550,8 +551,14 @@ const createWorkspaceEgressManager = (options) => {
550
551
  }
551
552
  }
552
553
  try {
553
- if (bytes != null) await options.sandbox.removePath({ path: helperPath, force: true });
554
+ if (stagingDirectory != null)
555
+ await options.sandbox.removePath({
556
+ path: stagingDirectory,
557
+ recursive: true,
558
+ force: true
559
+ });
554
560
  } catch (cleanup) {
561
+ reportFailure("artifact-cleanup", cleanup);
555
562
  outcome.failures.push(cleanup);
556
563
  }
557
564
  if (outcome.failures.length > 0 && outcome.result != null) {