Skip to content

Quickly sandbox your AI agent.

Python

feat(dns): host DNS proxy + patched libslirp for macOS VPN/split-DNS

Tyler Paynec3bd6264e4ee
diff --git a/packages/quicksand-core/pyproject.toml b/packages/quicksand-core/pyproject.toml
index f894f2d..6bd5b19 100644
--- a/packages/quicksand-core/pyproject.toml
+++ b/packages/quicksand-core/pyproject.toml
@@ -5,7 +5,13 @@ description = "Core sandbox functionality for the quicksand VM harness."
readme = "README.md"
requires-python = ">=3.11"
license = "MIT"
-dependencies = ["httpx>=0.27,<1.0", "pydantic>=2.0", "quicksand-smb>=0.4.9,<0.5.0"]
+dependencies = [
+ "httpx>=0.27,<1.0",
+ "pydantic>=2.0",
+ "quicksand-smb>=0.4.9,<0.5.0",
+ # Host-side DNS proxy for macOS VPN/split-DNS resolution (see host/dns_proxy.py).
+ "dnslib>=0.9.24; sys_platform == 'darwin'",
+]
[build-system]
requires = ["hatchling"]
diff --git a/packages/quicksand-core/quicksand_core/_types.py b/packages/quicksand-core/quicksand_core/_types.py
index d609538..4082231 100644
--- a/packages/quicksand-core/quicksand_core/_types.py
+++ b/packages/quicksand-core/quicksand_core/_types.py
@@ -367,6 +367,11 @@ class EnvironmentVariables:
QEMU_MODULE_DIR = "QEMU_MODULE_DIR"
+ # Read by the bundled (patched) libslirp on macOS: when set to a port
+ # number, guest DNS forwarded to 10.0.2.3 is redirected to 127.0.0.1:<port>
+ # where the host DNS proxy answers via the OS resolver. See host/dns_proxy.py.
+ DNS_PROXY = "QUICKSAND_DNS_PROXY"
+
# =============================================================================
# Guest Commands
@@ -587,6 +592,11 @@ class SandboxConfig(BaseModel):
accel: Accelerator | Literal["auto"] | None = "auto"
disk_size: str | None = None
enable_display: bool = False
+ host_dns_proxy: bool | None = None
+ """Route guest DNS through a host-side proxy that resolves via the OS
+ resolver. Fixes macOS VPN/split-DNS failures (see host/dns_proxy.py).
+ ``None`` (default) auto-enables on macOS hosts with ``network_mode=FULL``;
+ ``True``/``False`` force it on/off. No effect on Linux/Windows hosts."""
@field_validator("memory")
@classmethod
@@ -623,6 +633,7 @@ class SandboxConfigParams(TypedDict, total=False):
accel: Accelerator | Literal["auto"] | None
disk_size: str | None
enable_display: bool
+ host_dns_proxy: bool | None
_td_keys = set(SandboxConfigParams.__annotations__) | {"image"}
diff --git a/packages/quicksand-core/quicksand_core/host/dns_proxy.py b/packages/quicksand-core/quicksand_core/host/dns_proxy.py
new file mode 100644
index 0000000..b9b247e
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/host/dns_proxy.py
@@ -0,0 +1,117 @@
+"""Host-side DNS proxy for macOS VPN/split-DNS resolution.
+
+On macOS, libslirp discovers a single upstream nameserver via libresolv and
+forwards all guest DNS to it from an unbound socket. It does not honor the
+system's scoped resolvers (``scutil --dns``), so when a VPN is active the
+guest's DNS fails — often entirely — because the chosen resolver is reachable
+only through the VPN interface, or the wrong scope is picked. Toggling the VPN
+just reshuffles which resolver gets picked, which is the intermittent symptom
+users hit.
+
+The bundled libslirp is patched so that, when ``$QUICKSAND_DNS_PROXY`` names a
+port, it redirects the DNS it forwards (guest -> 10.0.2.3) to
+``127.0.0.1:<port>``. This module is the host-side endpoint of that redirect: a
+tiny DNS server that answers A/AAAA via :func:`socket.getaddrinfo`, the same OS
+resolver every working macOS app uses — so it honors scoped/VPN/split-DNS
+automatically.
+
+The guest's slirp network is IPv4-only, so AAAA answers are intentionally left
+empty (macOS returns v4-mapped addresses for AAAA, which are not real IPv6);
+clients fall back to A.
+"""
+
+from __future__ import annotations
+
+import logging
+import socket
+from typing import TYPE_CHECKING
+
+from ..utils import find_free_port
+
+if TYPE_CHECKING:
+ from dnslib import DNSRecord
+ from dnslib.server import DNSHandler
+
+logger = logging.getLogger("quicksand.dns_proxy")
+
+
+class _GetAddrInfoResolver:
+ """dnslib resolver that answers A/AAAA via the host's system resolver."""
+
+ def resolve(self, request: DNSRecord, handler: DNSHandler) -> DNSRecord:
+ from dnslib import AAAA, QTYPE, RR, A
+
+ reply = request.reply()
+ qtype = QTYPE[request.q.qtype]
+ name = str(request.q.qname).rstrip(".")
+
+ # Only A/AAAA are answered via getaddrinfo. Other types get an empty
+ # NOERROR so the guest's resolver falls back cleanly instead of hanging.
+ if qtype not in ("A", "AAAA"):
+ return reply
+
+ family = socket.AF_INET if qtype == "A" else socket.AF_INET6
+ try:
+ infos = socket.getaddrinfo(name, None, family, socket.SOCK_STREAM)
+ except socket.gaierror:
+ return reply # name does not resolve — empty answer
+
+ seen: set[str] = set()
+ for info in infos:
+ fam = info[0]
+ ip = str(info[4][0]).split("%")[0] # strip any IPv6 scope id
+ if ip in seen:
+ continue
+ try:
+ if qtype == "A" and fam == socket.AF_INET:
+ rdata = A(ip)
+ elif qtype == "AAAA" and fam == socket.AF_INET6:
+ # macOS returns v4-mapped (::ffff:1.2.3.4) for AAAA; those
+ # are not real IPv6 and the guest network is IPv4-only.
+ if ip.startswith("::ffff:") or "." in ip:
+ continue
+ rdata = AAAA(ip)
+ else:
+ continue
+ except Exception:
+ logger.debug("Skipping unparseable address %s for %s", ip, name)
+ continue
+ seen.add(ip)
+ reply.add_answer(RR(request.q.qname, request.q.qtype, rdata=rdata, ttl=60))
+
+ return reply
+
+
+class HostDnsProxy:
+ """A loopback DNS server that resolves via the host OS resolver.
+
+ Lifecycle mirrors :class:`~quicksand_core.host.smb.SMBServer`: construct,
+ :meth:`start`, then :meth:`stop`. The chosen :attr:`port` is passed to the
+ patched libslirp via the ``QUICKSAND_DNS_PROXY`` environment variable.
+ """
+
+ def __init__(self) -> None:
+ self._port = find_free_port()
+ self._servers: list = []
+
+ @property
+ def port(self) -> int:
+ return self._port
+
+ def start(self) -> None:
+ from dnslib.server import DNSServer
+
+ resolver = _GetAddrInfoResolver()
+ for tcp in (False, True):
+ server = DNSServer(resolver, port=self._port, address="127.0.0.1", tcp=tcp)
+ server.start_thread()
+ self._servers.append(server)
+ logger.info("Host DNS proxy listening on 127.0.0.1:%d (udp+tcp)", self._port)
+
+ def stop(self) -> None:
+ for server in self._servers:
+ try:
+ server.stop()
+ except Exception:
+ logger.debug("Error stopping DNS proxy server", exc_info=True)
+ self._servers = []
diff --git a/packages/quicksand-core/quicksand_core/sandbox/_lifecycle.py b/packages/quicksand-core/quicksand_core/sandbox/_lifecycle.py
index 504c7f2..2148139 100644
--- a/packages/quicksand-core/quicksand_core/sandbox/_lifecycle.py
+++ b/packages/quicksand-core/quicksand_core/sandbox/_lifecycle.py
@@ -7,6 +7,7 @@ import logging
import os
import secrets
import shutil
+import sys
import tempfile
import warnings
from collections.abc import Callable
@@ -147,6 +148,12 @@ class _LifecycleMixin(_SandboxProtocol):
if self.config.network_mode in (NetworkMode.MOUNTS_ONLY, NetworkMode.FULL):
self._ensure_smb_server()
+ # Start the host DNS proxy (macOS + FULL networking). The bundled
+ # libslirp is patched to redirect guest DNS to QUICKSAND_DNS_PROXY,
+ # which this proxy answers via the OS resolver — fixing VPN/split-DNS
+ # failures that the stock libslirp hits on macOS.
+ self._maybe_start_dns_proxy()
+
cmd = self._build_vm_command()
logger.debug(
"Starting VM: port=%s, image=%s",
@@ -163,10 +170,37 @@ class _LifecycleMixin(_SandboxProtocol):
):
env[EnvironmentVariables.QEMU_MODULE_DIR] = str(self._runtime_info.module_dir)
+ if self._dns_proxy is not None:
+ env[EnvironmentVariables.DNS_PROXY] = str(self._dns_proxy.port)
+
assert self._temp_dir is not None
console_log_path = self._temp_dir / FilePatterns.CONSOLE_LOG
self._process_manager.start(cmd, env, console_log_path)
+ def _maybe_start_dns_proxy(self) -> None:
+ """Start the host DNS proxy when appropriate.
+
+ Auto-enabled on macOS hosts with ``network_mode=FULL`` (the only mode
+ where the guest reaches the internet). ``config.host_dns_proxy`` forces
+ it on or off. The proxy is the host-side endpoint of the patched
+ libslirp's DNS redirect; see :mod:`quicksand_core.host.dns_proxy`.
+ """
+ override = self.config.host_dns_proxy
+ if override is False:
+ return
+ if sys.platform != "darwin":
+ if override is True:
+ logger.warning("host_dns_proxy is only supported on macOS hosts; ignoring")
+ return
+ if override is None and self.config.network_mode is not NetworkMode.FULL:
+ return
+
+ from ..host.dns_proxy import HostDnsProxy
+
+ proxy = HostDnsProxy()
+ proxy.start()
+ self._dns_proxy = proxy
+
async def _connect_to_guest_agent(self) -> None:
"""Wait for the guest agent; clean up and re-raise on failure."""
try:
@@ -360,6 +394,14 @@ class _LifecycleMixin(_SandboxProtocol):
cleanup_errors.extend(await self._cleanup_mounts())
+ if self._dns_proxy is not None:
+ try:
+ self._dns_proxy.stop()
+ except Exception as e:
+ cleanup_errors.append(("DNS proxy", e))
+ logger.warning("Failed to stop DNS proxy: %s", e)
+ self._dns_proxy = None
+
if self._agent_client:
try:
await self._agent_client.close()
diff --git a/packages/quicksand-core/quicksand_core/sandbox/_protocol.py b/packages/quicksand-core/quicksand_core/sandbox/_protocol.py
index cfd6733..0ad665e 100644
--- a/packages/quicksand-core/quicksand_core/sandbox/_protocol.py
+++ b/packages/quicksand-core/quicksand_core/sandbox/_protocol.py
@@ -16,6 +16,7 @@ from .._types import (
SaveManifest,
Timeouts,
)
+from ..host.dns_proxy import HostDnsProxy
from ..host.smb import SMBServer
from ..qemu import OverlayManager, VMProcessManager
from ..qemu.platform import RuntimeInfo
@@ -43,6 +44,7 @@ class _SandboxProtocol(Protocol):
_temp_dir: Path | None
_process_manager: VMProcessManager
_smb_server: SMBServer | None
+ _dns_proxy: HostDnsProxy | None
_dynamic_mounts: list[MountHandle]
_progress_callback: Callable[[str, int, int], None] | None
_overlay_manager: OverlayManager | None
diff --git a/packages/quicksand-core/quicksand_core/sandbox/_sandbox.py b/packages/quicksand-core/quicksand_core/sandbox/_sandbox.py
index 513def0..375b001 100644
--- a/packages/quicksand-core/quicksand_core/sandbox/_sandbox.py
+++ b/packages/quicksand-core/quicksand_core/sandbox/_sandbox.py
@@ -93,6 +93,7 @@ class Sandbox(
self._temp_dir: Path | None = None
self._process_manager = VMProcessManager()
self._smb_server: Any = None
+ self._dns_proxy: Any = None
self._dynamic_mounts: list = []
self._agent_client: AgentClient | None = None
self._agent_port: int | None = None
diff --git a/packages/quicksand-qemu/hatch_build.py b/packages/quicksand-qemu/hatch_build.py
index 2f43fd5..3cac89b 100644
--- a/packages/quicksand-qemu/hatch_build.py
+++ b/packages/quicksand-qemu/hatch_build.py
@@ -990,6 +990,134 @@ class RuntimeBuildHook(BuildHookInterface):
"The installer may have failed silently."
)
+ def _ensure_libslirp_build_tools(self) -> None:
+ """Install meson/ninja (needed to build patched libslirp) if missing."""
+ missing = [t for t in ("meson", "ninja") if not shutil.which(t)]
+ if not missing:
+ return
+ if not shutil.which("brew"):
+ raise RuntimeError(
+ "Building patched libslirp requires meson and ninja, but they are "
+ "missing and Homebrew is not available to install them."
+ )
+ subprocess.run(["brew", "install", *missing], check=True)
+ self.app.display_info(f"Installed build tools via Homebrew: {', '.join(missing)}")
+
+ def _patch_libslirp_macos(self, bin_dir: Path) -> None:
+ """Rebuild the bundled libslirp with the quicksand DNS-redirect patch.
+
+ Stock macOS libslirp forwards guest DNS to a single libresolv-picked
+ resolver and ignores the system's scoped/VPN/split-DNS resolvers, so
+ guest DNS fails (often entirely) under a VPN. The patch makes libslirp
+ honor ``$QUICKSAND_DNS_PROXY`` and redirect guest DNS to a host-side
+ proxy (``quicksand_core.host.dns_proxy``) that resolves via the OS
+ resolver. We rebuild the *same* libslirp version Homebrew's QEMU links
+ (ABI-compatible, same SONAME) and swap the dylib into ``bin/lib/``.
+ """
+ import tarfile
+ import tempfile
+ import urllib.request
+
+ lib_dir = bin_dir / "lib"
+ target = lib_dir / "libslirp.0.dylib"
+ if not target.exists():
+ raise RuntimeError(
+ f"Expected bundled libslirp at {target}, but it is missing — "
+ "cannot apply the quicksand DNS patch."
+ )
+
+ patch_file = Path(self.root) / "patches" / "libslirp-dns-proxy.patch"
+ if not patch_file.exists():
+ raise RuntimeError(f"libslirp patch not found: {patch_file}")
+
+ # Guard: we only patch libslirp.0 (SONAME). If QEMU ever links a
+ # different SONAME (e.g. a future libslirp.1), swapping libslirp.0
+ # would silently ship an unpatched QEMU — fail loudly instead.
+ qemu_bin = next(bin_dir.glob("qemu-system-*"), None)
+ if qemu_bin is not None:
+ linked = subprocess.run(
+ ["otool", "-L", str(qemu_bin)], capture_output=True, text=True
+ ).stdout
+ if "libslirp.0.dylib" not in linked:
+ raise RuntimeError(
+ "Bundled QEMU does not link libslirp.0.dylib — the pinned "
+ "libslirp patch version is stale. Update LIBSLIRP_VERSION and "
+ "patches/libslirp-dns-proxy.patch to match QEMU's libslirp."
+ )
+
+ # Pinned: the patch in patches/ is cut against this exact version, and
+ # it is ABI-compatible (same SONAME) with the libslirp QEMU links.
+ # Bump together with the patch when QEMU moves to a newer libslirp.
+ LIBSLIRP_VERSION = "4.9.3"
+ source_url = (
+ f"https://gitlab.freedesktop.org/slirp/libslirp/-/archive/"
+ f"v{LIBSLIRP_VERSION}/libslirp-v{LIBSLIRP_VERSION}.tar.gz"
+ )
+ version = LIBSLIRP_VERSION
+
+ self._ensure_libslirp_build_tools()
+
+ # Build env: ensure Homebrew's bin (meson/ninja/pkg-config) is on PATH.
+ env = dict(os.environ)
+ brew = shutil.which("brew")
+ if brew:
+ brew_bin = str(Path(brew).resolve().parent)
+ if brew_bin not in env.get("PATH", ""):
+ env["PATH"] = f"{brew_bin}:{env.get('PATH', '')}"
+
+ with tempfile.TemporaryDirectory(prefix="quicksand-libslirp-") as tmp_str:
+ tmp = Path(tmp_str)
+ tarball = tmp / "libslirp-src.tar.gz"
+ self.app.display_info(f"Downloading libslirp {version} source from {source_url}")
+ urllib.request.urlretrieve(source_url, tarball)
+ with tarfile.open(tarball) as tf:
+ tf.extractall(tmp)
+
+ src = next(p for p in tmp.iterdir() if p.is_dir() and (p / "meson.build").exists())
+
+ # Apply the patch (paths are a/src/... b/src/... -> -p1, relative to src).
+ with patch_file.open() as pf:
+ subprocess.run(["patch", "-p1"], cwd=src, stdin=pf, check=True)
+
+ build = src / "build"
+ subprocess.run(
+ ["meson", "setup", str(build), "--buildtype=release"],
+ cwd=src,
+ check=True,
+ env=env,
+ )
+ subprocess.run(["ninja", "-C", str(build)], check=True, env=env)
+
+ built = build / "libslirp.0.dylib"
+ if not built.exists():
+ raise RuntimeError(f"libslirp build did not produce {built}")
+
+ # Match the bundle layout: self-id and @loader_path sibling deps.
+ subprocess.run(
+ ["install_name_tool", "-id", "@loader_path/libslirp.0.dylib", str(built)],
+ check=True,
+ )
+ otool = subprocess.run(
+ ["otool", "-L", str(built)], capture_output=True, text=True, check=True
+ )
+ for line in otool.stdout.splitlines()[1:]:
+ dep = line.strip().split(" ")[0]
+ if not dep or dep.startswith("@"):
+ continue
+ base = Path(dep).name
+ if base == "libslirp.0.dylib" or not (lib_dir / base).exists():
+ continue
+ subprocess.run(
+ ["install_name_tool", "-change", dep, f"@loader_path/{base}", str(built)],
+ check=True,
+ )
+
+ shutil.copy(built, target)
+
+ # Re-sign ad-hoc (install_name_tool invalidated any signature).
+ subprocess.run(["codesign", "--force", "--sign", "-", str(target)], check=True)
+ self.app.display_info(f"Bundled patched libslirp {version} (QUICKSAND_DNS_PROXY redirect)")
+
def initialize(self, version: str, build_data: dict) -> None:
"""Bundle QEMU binaries into the package."""
if self.target_name != "wheel" or version == "editable":
@@ -1034,6 +1162,9 @@ class RuntimeBuildHook(BuildHookInterface):
if system == "darwin":
bundler.bundle_macos_dylibs(dest_qemu, bin_dir, entitlements_plist=MACOS_ENTITLEMENTS)
bundler.bundle_macos_dylibs(dest_img, bin_dir)
+ # Replace the bundled libslirp with a patched build that honors
+ # $QUICKSAND_DNS_PROXY (fixes macOS VPN/split-DNS guest DNS).
+ self._patch_libslirp_macos(bin_dir)
elif system == "linux":
bundler.bundle_linux_libs(dest_qemu, bin_dir)
bundler.bundle_linux_libs(dest_img, bin_dir)
diff --git a/packages/quicksand-qemu/patches/libslirp-dns-proxy.patch b/packages/quicksand-qemu/patches/libslirp-dns-proxy.patch
new file mode 100644
index 0000000..c70aad2
--- /dev/null
+++ b/packages/quicksand-qemu/patches/libslirp-dns-proxy.patch
@@ -0,0 +1,57 @@
+diff --git a/src/socket.c b/src/socket.c
+index c491d0f..6d18a53 100644
+--- a/src/socket.c
++++ b/src/socket.c
+@@ -725,6 +725,19 @@ void sorecvfrom(struct socket *so)
+ saddr = addr;
+ sotranslate_in(so, &saddr);
+
++ /*
++ * Quicksand: when DNS forwarding is redirected to a host proxy on
++ * a non-53 port ($QUICKSAND_DNS_PROXY), the reply arrives from that
++ * port; restore the source port the guest queried (so_fport, i.e.
++ * 53) so the guest's resolver accepts the reply. No-op in the normal
++ * case, where the real resolver already answers from :53.
++ */
++ if (so->so_ffamily == AF_INET && !so->slirp->disable_dns &&
++ so->so_faddr.s_addr == so->slirp->vnameserver_addr.s_addr &&
++ so->so_fport == htons(53)) {
++ ((struct sockaddr_in *)&saddr)->sin_port = so->so_fport;
++ }
++
+ /* Perform lazy guest IP address resolution if needed. */
+ if (so->so_state & SS_HOSTFWD) {
+ if (soassign_guest_addr_if_needed(so) < 0) {
+@@ -976,8 +989,30 @@ void sofwdrain(struct socket *so)
+ static bool sotranslate_out4(Slirp *s, struct socket *so, struct sockaddr_in *sin)
+ {
+ if (!s->disable_dns && so->so_faddr.s_addr == s->vnameserver_addr.s_addr) {
+- return (so->so_fport == htons(53) &&
+- get_dns_addr(&sin->sin_addr, &sin->sin_port) >= 0);
++ if (so->so_fport != htons(53)) {
++ return false;
++ }
++ /*
++ * Quicksand: when $QUICKSAND_DNS_PROXY is set to a port number,
++ * redirect the upstream DNS that slirp forwards (guest -> 10.0.2.3)
++ * to a host-side proxy on 127.0.0.1:<port>. This bypasses the macOS
++ * libresolv path (get_dns_addr) that picks a single primary resolver
++ * and ignores VPN/split-DNS scoping. Unset => unchanged behavior.
++ */
++ {
++ static int qs_dns_port = -1; /* -1 = unparsed, 0 = disabled */
++ if (qs_dns_port == -1) {
++ const char *e = getenv("QUICKSAND_DNS_PROXY");
++ int p = (e && *e) ? atoi(e) : 0;
++ qs_dns_port = (p > 0 && p <= 65535) ? p : 0;
++ }
++ if (qs_dns_port > 0) {
++ sin->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
++ sin->sin_port = htons((uint16_t)qs_dns_port);
++ return true;
++ }
++ }
++ return get_dns_addr(&sin->sin_addr, &sin->sin_port) >= 0;
+ }
+
+ if (so->so_faddr.s_addr == s->vhost_addr.s_addr ||
diff --git a/tests/unit/test_dns_proxy.py b/tests/unit/test_dns_proxy.py
new file mode 100644
index 0000000..7a7a4cd
--- /dev/null
+++ b/tests/unit/test_dns_proxy.py
@@ -0,0 +1,89 @@
+"""Unit tests for the macOS host DNS proxy (host/dns_proxy.py) and its config.
+
+The proxy is macOS-only (dnslib is a macOS-only dependency and the patched
+libslirp that drives it is only bundled on macOS), so the functional tests
+skip elsewhere. The config/env-name tests run everywhere.
+"""
+
+from __future__ import annotations
+
+import socket
+import sys
+
+import pytest
+from quicksand_core import SandboxConfig
+from quicksand_core._types import EnvironmentVariables
+
+darwin_only = pytest.mark.skipif(sys.platform != "darwin", reason="host DNS proxy is macOS-only")
+
+
+def _query(port: int, name: str, qtype: str = "A"):
+ from dnslib import DNSRecord
+
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ sock.settimeout(3)
+ try:
+ sock.sendto(DNSRecord.question(name, qtype).pack(), ("127.0.0.1", port))
+ data, _ = sock.recvfrom(4096)
+ finally:
+ sock.close()
+ return DNSRecord.parse(data)
+
+
+@darwin_only
+def test_proxy_resolves_localhost():
+ """A records come back via getaddrinfo (no network needed for localhost)."""
+ from quicksand_core.host.dns_proxy import HostDnsProxy
+
+ proxy = HostDnsProxy()
+ proxy.start()
+ try:
+ reply = _query(proxy.port, "localhost", "A")
+ answers = [str(rr.rdata) for rr in reply.rr]
+ assert "127.0.0.1" in answers
+ finally:
+ proxy.stop()
+
+
+@darwin_only
+def test_proxy_empty_for_unresolvable():
+ """Unresolvable names yield an empty NOERROR reply, never a crash/hang."""
+ from quicksand_core.host.dns_proxy import HostDnsProxy
+
+ proxy = HostDnsProxy()
+ proxy.start()
+ try:
+ reply = _query(proxy.port, "quicksand-nope.invalid", "A")
+ assert len(reply.rr) == 0
+ finally:
+ proxy.stop()
+
+
+@darwin_only
+def test_proxy_aaaa_does_not_return_v4mapped():
+ """macOS getaddrinfo returns v4-mapped AAAA; the proxy must drop them
+ (guest slirp network is IPv4-only) and never emit a malformed record."""
+ from quicksand_core.host.dns_proxy import HostDnsProxy
+
+ proxy = HostDnsProxy()
+ proxy.start()
+ try:
+ reply = _query(proxy.port, "localhost", "AAAA")
+ for rr in reply.rr:
+ assert "." not in str(rr.rdata) # no v4-mapped leak
+ finally:
+ proxy.stop()
+
+
+def test_config_field_default_is_auto():
+ assert SandboxConfig(image="alpine").host_dns_proxy is None
+
+
+def test_config_field_override():
+ assert SandboxConfig(image="alpine", host_dns_proxy=True).host_dns_proxy is True
+ assert SandboxConfig(image="alpine", host_dns_proxy=False).host_dns_proxy is False
+
+
+def test_dns_proxy_env_var_name():
+ # The bundled patched libslirp reads exactly this variable.
+ assert EnvironmentVariables.DNS_PROXY == "QUICKSAND_DNS_PROXY"
diff --git a/uv.lock b/uv.lock
index b02104f..92aacd4 100644
--- a/uv.lock
+++ b/uv.lock
@@ -375,6 +375,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/33/6b/e0547afaf41bf2c42e52430072fa5658766e3d65bd4b03a563d1b6336f57/distlib-0.4.0-py2.py3-none-any.whl", hash = "sha256:9659f7d87e46584a30b5780e43ac7a2143098441670ff0a49d5f9034c54a6c16", size = 469047, upload-time = "2025-07-17T16:51:58.613Z" },
]
+[[package]]
+name = "dnslib"
+version = "0.9.26"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a2/71/269f74ef9bc8ca453af2e1768d4f4c8e7ef5f894d058d27fd1b69c754d7f/dnslib-0.9.26.tar.gz", hash = "sha256:be56857534390b2fbd02935270019bacc5e6b411d156cb3921ac55a7fb51f1a8", size = 82901, upload-time = "2025-03-03T09:17:32.606Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/16/93/167364f10194e374119b211e475ed8763d7591ae4f7001b304282dde5825/dnslib-0.9.26-py3-none-any.whl", hash = "sha256:e68719e633d761747c7e91bd241019ef5a2b61a63f56025939e144c841a70e0d", size = 64161, upload-time = "2025-03-03T09:17:31.47Z" },
+]
+
[[package]]
name = "filelock"
version = "3.29.0"
@@ -1075,6 +1084,7 @@ name = "quicksand-core"
version = "0.11.14.dev0"
source = { editable = "packages/quicksand-core" }
dependencies = [
+ { name = "dnslib", marker = "sys_platform == 'darwin'" },
{ name = "httpx" },
{ name = "pydantic" },
{ name = "quicksand-smb" },
@@ -1082,6 +1092,7 @@ dependencies = [
[package.metadata]
requires-dist = [
+ { name = "dnslib", marker = "sys_platform == 'darwin'", specifier = ">=0.9.24" },
{ name = "httpx", specifier = ">=0.27,<1.0" },
{ name = "pydantic", specifier = ">=2.0" },
{ name = "quicksand-smb", editable = "packages/quicksand-smb" },