Skip to content

Quickly sandbox your AI agent.

Python

Add bidirectional port forwards with Forward(Host, Guest)

Tyler Paynea38fa65c7c8d
diff --git a/README.md b/README.md
index ad797ee..501de99 100644
--- a/README.md
+++ b/README.md
@@ -64,13 +64,16 @@ await sb.unmount(handle)
### Configure networking
-Sandboxes are network-isolated by default. Opt in to internet access and port forwarding with `NetworkMode.FULL`.
+Sandboxes are network-isolated by default. Opt in to internet access with `NetworkMode.FULL`. Port forwards work in either direction: `Forward(Host(...), Guest(...))` exposes a guest port on the host, and `Forward(Guest(...), Host(...))` exposes a host service inside the guest, even when the sandbox is otherwise offline.
```python
async with Sandbox(
image="ubuntu",
network_mode=NetworkMode.FULL,
- port_forwards=[PortForward(host=8080, guest=80)],
+ port_forwards=[
+ Forward(Host(8080), Guest(80)), # host:8080 -> guest:80
+ Forward(Guest(3128), Host(8080)), # guest 10.0.2.101:3128 -> host:8080
+ ],
) as sb:
...
```
@@ -128,8 +131,8 @@ Sandbox(
mounts=[Mount("/host", "/guest")],
# NONE, MOUNTS_ONLY (default), or FULL internet access
network_mode=NetworkMode.FULL,
- # Forward host TCP ports into the guest
- port_forwards=[PortForward(host=8080, guest=80)],
+ # Forward TCP ports in either direction (host -> guest, guest -> host)
+ port_forwards=[Forward(Host(8080), Guest(80)), Forward(Guest(3128), Host(8080))],
# Expand the guest filesystem on boot
disk_size="10G",
# Attach virtual GPU, keyboard, and mouse for screenshot/type_text/mouse control
diff --git a/docs/under-the-hood/07-network-and-isolation.md b/docs/under-the-hood/07-network-and-isolation.md
index c9a4986..8ff1e99 100644
--- a/docs/under-the-hood/07-network-and-isolation.md
+++ b/docs/under-the-hood/07-network-and-isolation.md
@@ -51,17 +51,34 @@ QEMU's SLIRP networking gives the guest a virtual NAT. The guest sees:
Sandbox(
image="ubuntu",
network_mode=NetworkMode.FULL,
- port_forwards=[PortForward(host=8080, guest=80), PortForward(host=8443, guest=443)],
+ port_forwards=[Forward(Host(8080), Guest(80)), Forward(Host("0.0.0.0", 8443), Guest(443))],
)
```
```bash
--netdev user,id=net0,hostfwd=tcp:127.0.0.1:{agent_port}-:{agent_port},hostfwd=tcp:127.0.0.1:8080-:80,hostfwd=tcp:127.0.0.1:8443-:443,...
+-netdev user,id=net0,hostfwd=tcp:127.0.0.1:{agent_port}-:{agent_port},hostfwd=tcp:127.0.0.1:8080-:80,hostfwd=tcp:0.0.0.0:8443-:443,...
```
-Each `PortForward(host, guest)` pair becomes a `hostfwd` rule. The agent port's `hostfwd` is always present (it's how `execute()` reaches the guest) and uses a dynamically allocated port.
+Each `Forward(Host, Guest)` becomes a `hostfwd` rule of the form `hostfwd=tcp:{host.address}:{host.port}-{guest.address}:{guest.port}`. The host address is the interface QEMU listens on and defaults to `127.0.0.1`. The guest address is left empty by default, which QEMU resolves to the guest's own IP (`10.0.2.15`). The agent port's `hostfwd` is always present (it's how `execute()` reaches the guest) and uses a dynamically allocated port.
-All forwards bind to `127.0.0.1`. They are only accessible from the host, not from the network.
+## Guest forwarding
+
+```python
+Sandbox(
+ image="ubuntu",
+ port_forwards=[Forward(Guest(3128), Host(8080))],
+)
+```
+
+```bash
+-netdev user,id=net0,restrict=on,...,guestfwd=tcp:10.0.2.101:3128-cmd:/path/to/python /path/to/_tcp_relay.py 127.0.0.1 8080
+```
+
+Each `Forward(Guest, Host)` becomes a `guestfwd` rule on the same virtual network the SMB mount tunnel uses. When the guest connects to `10.0.2.101:3128`, QEMU spawns one `_tcp_relay.py` process for that connection and pipes the guest's TCP stream through the relay's stdin/stdout to a fresh host-side connection to `127.0.0.1:8080`. When either side closes, the relay exits. This is the same `cmd:` relay that carries CIFS traffic to the in-process SMB server on Windows. Because the relay does an ordinary `connect()`, the host endpoint may be a hostname or an address on another machine.
+
+QEMU also accepts a chardev target (`guestfwd=tcp:10.0.2.101:3128-tcp:127.0.0.1:8080`), which avoids the per-connection process. Quicksand does not use it because a chardev is a single stream: every guest connection to that address is multiplexed onto one host connection. In testing, eight concurrent requests through a chardev target produced a duplicated response and a dropped one, and the stream was left unusable afterwards. The per-connection relay costs one short-lived Python process per guest connection and in exchange gives ordinary TCP semantics.
+
+`restrict=on` does not affect `guestfwd`, so guest-to-host forwards work in `MOUNTS_ONLY` mode. The guest address is validated to sit inside `10.0.2.0/24` and away from the addresses slirp reserves (`10.0.2.2`, `10.0.2.3`, `10.0.2.15`) and the SMB tunnel (`10.0.2.100:445`).
## Virtio network device
diff --git a/docs/under-the-hood/index.md b/docs/under-the-hood/index.md
index 6aabe92..36d133d 100644
--- a/docs/under-the-hood/index.md
+++ b/docs/under-the-hood/index.md
@@ -158,7 +158,7 @@ All configuration is passed as keyword arguments to `Sandbox(...)`:
| `memory` | Memory allocation (e.g., `"512M"`, `"2G"`) |
| `cpus` | Number of virtual CPUs |
| `mounts` | List of `Mount` for boot-time host directory sharing |
-| `port_forwards` | List of `PortForward(host=..., guest=...)` objects |
+| `port_forwards` | List of `Forward(src, dst)` objects. `Forward(Host(port), Guest(port))` exposes a guest port on the host; `Forward(Guest(port), Host(port))` exposes a host service inside the guest. `PortForward(host, guest)` is a deprecated alias for the first form. |
| `save` | Auto-save name on stop (on `Sandbox.__init__`, not `SandboxConfig`) |
| `network_mode` | `NetworkMode` enum: `NONE`, `MOUNTS_ONLY` (default), `FULL` |
| `extra_qemu_args` | Additional QEMU command line arguments |
diff --git a/docs/user-guide/02-sandbox-lifecycle.md b/docs/user-guide/02-sandbox-lifecycle.md
index 68653a4..73c6547 100644
--- a/docs/user-guide/02-sandbox-lifecycle.md
+++ b/docs/user-guide/02-sandbox-lifecycle.md
@@ -5,7 +5,7 @@
## Quick start
```python
-from quicksand import Sandbox, Mount, NetworkMode, PortForward
+from quicksand import Sandbox, Mount, NetworkMode, Forward, Host, Guest
async with Sandbox(image="ubuntu") as sb:
result = await sb.execute("uname -a")
@@ -26,7 +26,10 @@ sb = Sandbox(
cpus=4, # CPU cores (default: 1)
enable_display=True, # Enable GUI for screenshots/input (default: False)
network_mode=NetworkMode.FULL, # Internet access (default: MOUNTS_ONLY)
- port_forwards=[PortForward(host=8080, guest=80)],
+ port_forwards=[ # Either direction, one list
+ Forward(Host(8080), Guest(80)), # guest:80 reachable at host:8080
+ Forward(Guest(3128), Host(8080)), # host:8080 reachable at 10.0.2.101:3128
+ ],
mounts=[ # Share host directories into the VM
Mount("/host/code", "/mnt/code"),
],
diff --git a/docs/user-guide/07-network-and-isolation.md b/docs/user-guide/07-network-and-isolation.md
index e9bf1db..1cb81ea 100644
--- a/docs/user-guide/07-network-and-isolation.md
+++ b/docs/user-guide/07-network-and-isolation.md
@@ -4,7 +4,7 @@
All examples below assume:
```python
-from quicksand import Sandbox, NetworkMode, PortForward
+from quicksand import Sandbox, NetworkMode, Forward, Host, Guest
```
## Default: isolated
@@ -38,28 +38,71 @@ async with Sandbox(image="ubuntu", network_mode=NetworkMode.FULL) as sb:
## Port forwarding
-Expose a service running inside the VM to the host:
+`port_forwards` is a list of `Forward(src, dst)` objects. Each one connects a `Host` endpoint to a `Guest` endpoint, and the order decides the direction. An endpoint is a port with an optional address, written whichever way reads best:
+
+```python
+Host(8080) # port only, address defaults to 127.0.0.1
+Host("0.0.0.0", 8080) # address and port
+Host("0.0.0.0:8080") # the same, as one string
+Host(port=8080, address="0.0.0.0")
+```
+
+`Guest` takes the same forms. Its address is optional too and defaults to the right value for its side of the forward.
+
+> `PortForward(host=..., guest=...)` is a deprecated alias for `Forward(Host(...), Guest(...))`. It still works but emits a `DeprecationWarning`.
+
+### Host to guest: reach the guest from the host
+
+Expose a service running inside the VM on a host port:
```python
async with Sandbox(
image="ubuntu",
network_mode=NetworkMode.FULL,
- port_forwards=[PortForward(host=8080, guest=80)],
+ port_forwards=[Forward(Host(8080), Guest(80))],
) as sb:
await sb.execute("apt install -y nginx && nginx")
# Now accessible at http://localhost:8080 on the host
```
-Multiple port forwards are supported:
+Multiple forwards are supported:
+
+```python
+port_forwards=[
+ Forward(Host(8080), Guest(80)), # HTTP
+ Forward(Host(8443), Guest(443)), # HTTPS
+ Forward(Host(5432), Guest(5432)), # PostgreSQL
+]
+```
+
+By default the host side binds `127.0.0.1`, so the port is reachable only from the host itself. Set `Host("0.0.0.0", 8080)` to make it reachable from other machines on your network. The guest address almost never needs setting, since the VM has a single IP that QEMU fills in.
+
+### Guest to host: reach the host from the guest
+
+Expose a service running on the host to code inside the VM. This works even in the default `MOUNTS_ONLY` mode, where every other outbound connection is blocked, so it is the way to offer a sandbox a carefully chosen slice of the outside world such as an HTTP proxy or one of your own APIs:
+
+```python
+async with Sandbox(
+ image="ubuntu", # MOUNTS_ONLY by default: no internet
+ port_forwards=[Forward(Guest(3128), Host(8080))],
+) as sb:
+ # Inside the VM, 10.0.2.101:3128 is the host's 127.0.0.1:8080
+ await sb.execute("curl -x http://10.0.2.101:3128 https://example.com")
+```
+
+The guest dials `Guest.address:Guest.port`. The address defaults to `10.0.2.101`, a virtual address on the VM's private network. The host side defaults to `127.0.0.1` and may be any address or hostname the host can reach, which turns the forward into a pinhole from an offline sandbox to exactly one remote service:
```python
port_forwards=[
- PortForward(host=8080, guest=80), # HTTP
- PortForward(host=8443, guest=443), # HTTPS
- PortForward(host=5432, guest=5432), # PostgreSQL
+ Forward(Guest(3128), Host(8080)), # proxy on the host
+ Forward(Guest(80), Host(5000)), # your API
+ Forward(Guest("10.0.2.102", 80), Host(5001)), # a second API on guest port 80
+ Forward(Guest(5432), Host("db.internal", 5432)), # relayed onward to one remote host
]
```
+Each guest connection becomes its own connection on the host, so concurrent requests and keep-alive sessions behave normally. When the guest is the source its address must be inside `10.0.2.0/24` and may not be the gateway (`10.0.2.2`), the DNS forwarder (`10.0.2.3`), the guest itself (`10.0.2.15`), or the mount tunnel (`10.0.2.100:445`). Guest-to-host forwards need a network device, so they are rejected with `NetworkMode.NONE`.
+
## Security boundary
The VM provides strong isolation:
@@ -86,12 +129,23 @@ async with Sandbox(image="with-deps") as sb:
await sb.execute("cd /mnt/code && python3 main.py")
```
+**Allow internet access only through a proxy you control:**
+```python
+# Run an HTTP proxy on the host (127.0.0.1:8080) that enforces an allowlist,
+# then hand the offline sandbox just that proxy.
+async with Sandbox(
+ image="ubuntu",
+ port_forwards=[Forward(Guest(3128), Host(8080))],
+) as sb:
+ await sb.execute("export https_proxy=http://10.0.2.101:3128; pip install requests")
+```
+
**Run a web server and test it:**
```python
async with Sandbox(
image="ubuntu",
network_mode=NetworkMode.FULL,
- port_forwards=[PortForward(host=3000, guest=3000)],
+ port_forwards=[Forward(Host(3000), Guest(3000))],
) as sb:
await sb.execute("cd /app && node server.js &")
# Test from host: requests.get("http://localhost:3000")
diff --git a/examples/custom_config.py b/examples/custom_config.py
index 9c45ffc..23283d8 100644
--- a/examples/custom_config.py
+++ b/examples/custom_config.py
@@ -5,7 +5,7 @@ Example with custom configuration using UbuntuSandbox.
import asyncio
-from quicksand import Mount, NetworkMode, PortForward, UbuntuSandbox
+from quicksand import Forward, Guest, Host, Mount, NetworkMode, UbuntuSandbox
async def main():
@@ -17,7 +17,7 @@ async def main():
Mount("/tmp/host-data", "/mnt/data", readonly=True),
],
# Forward ports from guest to host
- port_forwards=[PortForward(host=8080, guest=80)],
+ port_forwards=[Forward(Host(8080), Guest(80))],
# Block internet access (recommended for untrusted code)
network_mode=NetworkMode.MOUNTS_ONLY,
# Boot timeout
diff --git a/packages/quicksand-core/quicksand_core/__init__.py b/packages/quicksand-core/quicksand_core/__init__.py
index f265cf4..fa3dd72 100644
--- a/packages/quicksand-core/quicksand_core/__init__.py
+++ b/packages/quicksand-core/quicksand_core/__init__.py
@@ -12,6 +12,9 @@ from . import _types as types
from ._types import (
BaseImageInfo,
BootTiming,
+ Forward,
+ Guest,
+ Host,
ImageProvider,
Key,
Mount,
@@ -64,6 +67,9 @@ __all__ = [ # noqa: RUF022
"Mount",
"MountHandle",
"MountType",
+ "Forward",
+ "Host",
+ "Guest",
"PortForward",
"ExecuteResult",
# Boot timing
diff --git a/packages/quicksand-core/quicksand_core/_types.py b/packages/quicksand-core/quicksand_core/_types.py
index 0624b71..3a073bd 100644
--- a/packages/quicksand-core/quicksand_core/_types.py
+++ b/packages/quicksand-core/quicksand_core/_types.py
@@ -12,14 +12,16 @@ Platform and Architecture enums are in platform.py.
from __future__ import annotations
+import ipaddress
import subprocess
import sys
-from dataclasses import dataclass
+import warnings
+from dataclasses import dataclass, field
from enum import StrEnum
from pathlib import Path
-from typing import Literal, Protocol, TypedDict, runtime_checkable
+from typing import Annotated, Literal, Protocol, TypedDict, overload, runtime_checkable
-from pydantic import BaseModel, ConfigDict, field_validator
+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from .host import Accelerator
@@ -89,12 +91,266 @@ class NetworkMode(StrEnum):
# =============================================================================
+# Virtual IP inside the slirp network that guest-to-host forwards listen on by
+# default. Kept separate from the SMB tunnel IP (10.0.2.100) so the two never
+# collide. Mirrored as ``NetworkConstants.GUESTFWD_DEFAULT_IP``.
+_GUESTFWD_DEFAULT_IP = "10.0.2.101"
+_LOOPBACK = "127.0.0.1"
+
+
+def _endpoint_args(
+ owner: str, args: tuple[int | str | None, ...], port: int | None, address: str | None
+) -> tuple[int, str | None]:
+ """Normalise the flexible endpoint constructor forms to ``(port, address)``.
+
+ Accepted: ``(port)``, ``("addr", port)``, ``(port, "addr")``,
+ ``("addr:port")``, and the keywords ``port=``/``address=``. A positional
+ ``None`` address is ignored so callers can pass an optional address through.
+ """
+ if len(args) > 2:
+ raise TypeError(f"{owner}() takes at most 2 positional arguments ({len(args)} given)")
+ for arg in args:
+ if arg is None:
+ continue
+ if isinstance(arg, bool) or not isinstance(arg, int | str):
+ raise TypeError(
+ f"{owner}() positional arguments must be an int port or a str address, "
+ f"got {type(arg).__name__}"
+ )
+ if isinstance(arg, int):
+ if port is not None:
+ raise TypeError(f"{owner}() got multiple values for port")
+ port = arg
+ continue
+ if address is not None:
+ raise TypeError(f"{owner}() got multiple values for address")
+ if ":" in arg:
+ addr, _, port_str = arg.rpartition(":")
+ if port is not None:
+ raise TypeError(f"{owner}() got multiple values for port")
+ if not addr or not port_str.isdigit():
+ raise ValueError(f"{owner}: expected 'address:port', got {arg!r}")
+ port = int(port_str)
+ address = addr
+ else:
+ address = arg
+ if port is None:
+ raise TypeError(
+ f"{owner}() missing a port; use {owner}(port), {owner}('addr', port), "
+ f"{owner}('addr:port') or {owner}(port=...)"
+ )
+ return port, address
+
+
+@dataclass(init=False)
+class Host:
+ """A TCP endpoint on the host machine.
+
+ Construct with any of::
+
+ Host(8080) # 127.0.0.1:8080
+ Host("0.0.0.0", 8080)
+ Host("0.0.0.0:8080")
+ Host(port=8080, address="0.0.0.0")
+
+ As the source of a :class:`Forward`, ``address`` is the interface QEMU
+ listens on. The default ``127.0.0.1`` keeps the port reachable only from
+ the host itself; ``0.0.0.0`` exposes it to the network. As the destination,
+ ``address`` is where the tunnel connects and may be a hostname.
+ """
+
+ port: int
+ address: str = _LOOPBACK
+ kind: Literal["host"] = field(default="host", repr=False, compare=False)
+ """Discriminator for dict/JSON input. Not meant to be set by callers."""
+
+ @overload
+ def __init__(self, port: int, /, address: str = ...) -> None: ...
+ @overload
+ def __init__(self, address: str, port: int, /) -> None: ...
+ @overload
+ def __init__(self, address_and_port: str, /) -> None: ...
+ @overload
+ def __init__(self, address: str, /, *, port: int) -> None: ...
+ @overload
+ def __init__(self, *, port: int, address: str = ...) -> None: ...
+
+ def __init__(
+ self, *args: int | str | None, port: int | None = None, address: str | None = None
+ ) -> None:
+ self.port, addr = _endpoint_args("Host", args, port, address)
+ self.address = addr if addr is not None else _LOOPBACK
+ self.kind = "host"
+ self.__post_init__()
+
+ def __post_init__(self) -> None:
+ _check_port("Host", self.port)
+
+
+@dataclass(init=False)
+class Guest:
+ """A TCP endpoint inside the guest VM.
+
+ Construct with any of::
+
+ Guest(80) # address chosen by the Forward direction
+ Guest("10.0.2.102", 80)
+ Guest("10.0.2.102:80")
+ Guest(port=80, address="10.0.2.102")
+
+ As the destination of a :class:`Forward`, ``address`` defaults to the
+ guest's own IP (left to QEMU) and rarely needs setting. As the source, it
+ is a virtual address on the slirp network (``10.0.2.0/24``) that the guest
+ dials to reach the host; the default ``10.0.2.101`` is filled in by
+ :class:`Forward`. Pick a different address only to run several forwards on
+ the same guest port.
+ """
+
+ port: int
+ address: str | None = None
+ kind: Literal["guest"] = field(default="guest", repr=False, compare=False)
+ """Discriminator for dict/JSON input. Not meant to be set by callers."""
+
+ @overload
+ def __init__(self, port: int, /, address: str | None = ...) -> None: ...
+ @overload
+ def __init__(self, address: str, port: int, /) -> None: ...
+ @overload
+ def __init__(self, address_and_port: str, /) -> None: ...
+ @overload
+ def __init__(self, address: str, /, *, port: int) -> None: ...
+ @overload
+ def __init__(self, *, port: int, address: str | None = ...) -> None: ...
+
+ def __init__(
+ self, *args: int | str | None, port: int | None = None, address: str | None = None
+ ) -> None:
+ self.port, self.address = _endpoint_args("Guest", args, port, address)
+ self.kind = "guest"
+ self.__post_init__()
+
+ def __post_init__(self) -> None:
+ _check_port("Guest", self.port)
+
+
+Endpoint = Annotated[Host | Guest, Field(discriminator="kind")]
+"""Either end of a :class:`Forward`."""
+
+
@dataclass
-class PortForward:
- """Forward a TCP port from the host into the guest."""
+class Forward:
+ """Forward TCP connections between the host and the guest, in either direction.
+
+ ``src`` is where connections are accepted and ``dst`` is where they are
+ delivered. One end must be a :class:`Host` and the other a :class:`Guest`.
+
+ Host to guest (QEMU ``hostfwd``) exposes a service running in the VM on a
+ host port::
+
+ Forward(Host(8080), Guest(80)) # host:8080 -> guest:80
+ Forward(Host("0.0.0.0:8080"), Guest(80)) # also reachable from the LAN
+
+ Guest to host (QEMU ``guestfwd``) exposes a host service inside the VM. It
+ works in every network mode that has a NIC, including ``MOUNTS_ONLY`` where
+ all other outbound traffic is blocked, so a host-side HTTP proxy or API can
+ be offered to an otherwise offline sandbox::
+
+ Forward(Guest(3128), Host(8080)) # guest 10.0.2.101:3128 -> host:8080
+ Forward(Guest("10.0.2.102:80"), Host(5001)) # a second service on guest port 80
+ Forward(Guest(5432), Host("db.internal", 5432)) # pinhole to one remote service
+ """
+
+ src: Endpoint
+ dst: Endpoint
+
+ def __post_init__(self) -> None:
+ if isinstance(self.src, Host) and isinstance(self.dst, Guest):
+ self._validate_host_to_guest(self.src, self.dst)
+ elif isinstance(self.src, Guest) and isinstance(self.dst, Host):
+ if self.src.address is None:
+ self.src = Guest(self.src.port, _GUESTFWD_DEFAULT_IP)
+ self._validate_guest_to_host(self.src, self.dst)
+ else:
+ raise ValueError(
+ "Forward must connect a Host endpoint to a Guest endpoint, got "
+ f"src={type(self.src).__name__} and dst={type(self.dst).__name__}"
+ )
+
+ @property
+ def host(self) -> Host:
+ """The :class:`Host` end, whichever side it is on."""
+ end = self.src if isinstance(self.src, Host) else self.dst
+ assert isinstance(end, Host) # guaranteed by __post_init__
+ return end
+
+ @property
+ def guest(self) -> Guest:
+ """The :class:`Guest` end, whichever side it is on."""
+ end = self.src if isinstance(self.src, Guest) else self.dst
+ assert isinstance(end, Guest) # guaranteed by __post_init__
+ return end
+
+ @property
+ def host_to_guest(self) -> bool:
+ """True for ``Forward(Host, Guest)``, False for ``Forward(Guest, Host)``."""
+ return isinstance(self.src, Host)
+
+ @staticmethod
+ def _validate_host_to_guest(src: Host, dst: Guest) -> None:
+ _check_ipv4("Host.address", src.address, "when the host is the source (bind address)")
+ if dst.address is not None:
+ _check_ipv4("Guest.address", dst.address, "when the guest is the destination")
+
+ @staticmethod
+ def _validate_guest_to_host(src: Guest, dst: Host) -> None:
+ assert src.address is not None
+ addr = _check_ipv4("Guest.address", src.address, "when the guest is the source")
+
+ network = ipaddress.IPv4Network(
+ f"{NetworkConstants.QEMU_SLIRP_GATEWAY}/{NetworkConstants.QEMU_SLIRP_NETMASK}",
+ strict=False,
+ )
+ if addr not in network:
+ raise ValueError(
+ f"Guest.address must be inside the slirp network {network} when the guest "
+ f"is the source, got {src.address}"
+ )
+
+ reserved = {
+ NetworkConstants.QEMU_SLIRP_GATEWAY: "the slirp gateway",
+ NetworkConstants.QEMU_SLIRP_DNS: "the slirp DNS forwarder",
+ NetworkConstants.QEMU_SLIRP_GUEST_IP: "the guest itself",
+ }
+ if src.address in reserved:
+ raise ValueError(f"Guest.address {src.address} is reserved for {reserved[src.address]}")
+ del dst # any host address or hostname is fine as a connect target
+
+
+def _check_port(owner: str, port: int) -> None:
+ if not 1 <= port <= 65535:
+ raise ValueError(f"{owner}.port must be in 1..65535, got {port}")
- host: int
- guest: int
+
+def _check_ipv4(name: str, value: str, context: str) -> ipaddress.IPv4Address:
+ try:
+ return ipaddress.IPv4Address(value)
+ except ValueError as e:
+ raise ValueError(f"{name} must be an IPv4 address {context}, got {value!r}") from e
+
+
+def PortForward(host: int, guest: int) -> Forward:
+ """Deprecated. Use ``Forward(Host(host), Guest(guest))``.
+
+ Kept so existing ``PortForward(host=..., guest=...)`` calls keep working.
+ Emits a :class:`DeprecationWarning`.
+ """
+ warnings.warn(
+ "PortForward is deprecated and will be removed in a future release; "
+ "use Forward(Host(port), Guest(port)) instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return Forward(Host(host), Guest(guest))
# =============================================================================
@@ -294,6 +550,7 @@ class NetworkConstants:
GUEST_SMB_PORT = 445 # Standard SMB port for CIFS mounts
GUESTFWD_SMB_IP = "10.0.2.100" # Virtual IP for guestfwd SMB tunnel (MOUNTS_ONLY mode)
GUESTFWD_SMB_PORT = 445 # SMB port on the guestfwd virtual IP
+ GUESTFWD_DEFAULT_IP = _GUESTFWD_DEFAULT_IP # Default Guest source address in Forward
# =============================================================================
@@ -599,7 +856,10 @@ class SandboxConfig(BaseModel):
memory: str = "512M"
cpus: int = 1
mounts: list[Mount] = []
- port_forwards: list[PortForward] = []
+ port_forwards: list[Forward] = []
+ """TCP forwards in either direction. ``Forward(Host(...), Guest(...))``
+ exposes a guest port on the host; ``Forward(Guest(...), Host(...))`` exposes
+ a host service inside the guest."""
network_mode: NetworkMode = NetworkMode.MOUNTS_ONLY
extra_qemu_args: list[str] = []
boot_timeout: float = Timeouts.BOOT_DEFAULT
@@ -620,6 +880,59 @@ class SandboxConfig(BaseModel):
parse_memory_size(v)
return v
+ @property
+ def host_forwards(self) -> list[Forward]:
+ """The host-to-guest entries of :attr:`port_forwards` (QEMU ``hostfwd``)."""
+ return [f for f in self.port_forwards if f.host_to_guest]
+
+ @property
+ def guest_forwards(self) -> list[Forward]:
+ """The guest-to-host entries of :attr:`port_forwards` (QEMU ``guestfwd``)."""
+ return [f for f in self.port_forwards if not f.host_to_guest]
+
+ @model_validator(mode="after")
+ def _validate_port_forwards(self) -> SandboxConfig:
+ if not self.port_forwards:
+ return self
+
+ host_binds: set[tuple[str, int]] = set()
+ for f in self.host_forwards:
+ key = (f.host.address, f.host.port)
+ if key in host_binds:
+ raise ValueError(
+ f"Duplicate host-to-guest Forward listening on {f.host.address}:"
+ f"{f.host.port}; each host address/port may be forwarded only once."
+ )
+ host_binds.add(key)
+
+ guest_forwards = self.guest_forwards
+ if not guest_forwards:
+ return self
+
+ if self.network_mode is NetworkMode.NONE:
+ raise ValueError(
+ "Forward(Guest, Host) requires network_mode=FULL or MOUNTS_ONLY; "
+ "NetworkMode.NONE has no network device to tunnel through."
+ )
+
+ smb_tunnel = (NetworkConstants.GUESTFWD_SMB_IP, NetworkConstants.GUESTFWD_SMB_PORT)
+ seen: set[tuple[str, int]] = set()
+ for f in guest_forwards:
+ assert f.guest.address is not None # filled in by Forward.__post_init__
+ key = (f.guest.address, f.guest.port)
+ if key == smb_tunnel:
+ raise ValueError(
+ f"Forward from Guest {f.guest.address}:{f.guest.port} collides with the "
+ "CIFS mount tunnel; choose another guest address or port."
+ )
+ if key in seen:
+ raise ValueError(
+ f"Duplicate guest-to-host Forward from {f.guest.address}:{f.guest.port}; "
+ "each guest address/port may be forwarded only once."
+ )
+ seen.add(key)
+ return self
+
@property
def memory_bytes(self) -> int:
"""Configured guest RAM in bytes."""
@@ -640,7 +953,7 @@ class SandboxConfigParams(TypedDict, total=False):
memory: str
cpus: int
mounts: list[Mount]
- port_forwards: list[PortForward]
+ port_forwards: list[Forward]
network_mode: NetworkMode
extra_qemu_args: list[str]
boot_timeout: float
diff --git a/packages/quicksand-core/quicksand_core/qemu/platform.py b/packages/quicksand-core/quicksand_core/qemu/platform.py
index dab7bac..3c32488 100644
--- a/packages/quicksand-core/quicksand_core/qemu/platform.py
+++ b/packages/quicksand-core/quicksand_core/qemu/platform.py
@@ -361,8 +361,9 @@ class PlatformConfig:
hostfwd = f"hostfwd=tcp:127.0.0.1:{agent_port}-:{agent_port}"
- for pf in config.port_forwards:
- hostfwd += f",hostfwd=tcp:127.0.0.1:{pf.host}-:{pf.guest}"
+ for f in config.host_forwards:
+ guest_addr = f.guest.address or "" # empty = the guest's own IP
+ hostfwd += f",hostfwd=tcp:{f.host.address}:{f.host.port}-{guest_addr}:{f.guest.port}"
restrict = "off" if config.network_mode is NetworkMode.FULL else "on"
@@ -377,13 +378,18 @@ class PlatformConfig:
if guestfwd_cmd is not None:
guestfwd = f",guestfwd=tcp:{guestfwd_ip}:{guestfwd_port}-cmd:{guestfwd_cmd}"
elif config.network_mode is NetworkMode.MOUNTS_ONLY and smb_port is not None:
- import sys
+ guestfwd = self._relay_guestfwd(
+ guestfwd_ip, guestfwd_port, NetworkConstants.LOCALHOST, smb_port
+ )
- relay_script = str(Path(__file__).resolve().parent.parent / "_tcp_relay.py")
- guestfwd = (
- f",guestfwd=tcp:{guestfwd_ip}:{guestfwd_port}-"
- f"cmd:{sys.executable} {relay_script} "
- f"{NetworkConstants.LOCALHOST} {smb_port}"
+ # User-requested guest forwards: host services exposed inside the guest.
+ # Each uses the same per-connection TCP relay as the SMB tunnel above
+ # rather than a ``-tcp:host:port`` chardev target, because a chardev
+ # target multiplexes every guest connection onto one host connection.
+ for f in config.guest_forwards:
+ assert f.guest.address is not None # filled in by Forward.__post_init__
+ guestfwd += self._relay_guestfwd(
+ f.guest.address, f.guest.port, f.host.address, f.host.port
)
netdev_opts = f"user,id=net0,restrict={restrict},{hostfwd}{guestfwd}"
@@ -396,6 +402,22 @@ class PlatformConfig:
f"{virtio_net},netdev=net0",
]
+ @staticmethod
+ def _relay_guestfwd(guest_ip: str, guest_port: int, host: str, host_port: int) -> str:
+ """Build a ``,guestfwd=...`` netdev option that relays to a host TCP port.
+
+ QEMU spawns one ``_tcp_relay.py`` process per guest connection
+ (inetd-style), so concurrent guest connections each get their own
+ host-side TCP connection and close independently.
+ """
+ import sys
+
+ relay_script = str(Path(__file__).resolve().parent.parent / "_tcp_relay.py")
+ return (
+ f",guestfwd=tcp:{guest_ip}:{guest_port}-"
+ f"cmd:{sys.executable} {relay_script} {host} {host_port}"
+ )
+
@lru_cache(maxsize=1)
def get_platform_config() -> PlatformConfig:
diff --git a/packages/quicksand/README.md b/packages/quicksand/README.md
index ad797ee..501de99 100644
--- a/packages/quicksand/README.md
+++ b/packages/quicksand/README.md
@@ -64,13 +64,16 @@ await sb.unmount(handle)
### Configure networking
-Sandboxes are network-isolated by default. Opt in to internet access and port forwarding with `NetworkMode.FULL`.
+Sandboxes are network-isolated by default. Opt in to internet access with `NetworkMode.FULL`. Port forwards work in either direction: `Forward(Host(...), Guest(...))` exposes a guest port on the host, and `Forward(Guest(...), Host(...))` exposes a host service inside the guest, even when the sandbox is otherwise offline.
```python
async with Sandbox(
image="ubuntu",
network_mode=NetworkMode.FULL,
- port_forwards=[PortForward(host=8080, guest=80)],
+ port_forwards=[
+ Forward(Host(8080), Guest(80)), # host:8080 -> guest:80
+ Forward(Guest(3128), Host(8080)), # guest 10.0.2.101:3128 -> host:8080
+ ],
) as sb:
...
```
@@ -128,8 +131,8 @@ Sandbox(
mounts=[Mount("/host", "/guest")],
# NONE, MOUNTS_ONLY (default), or FULL internet access
network_mode=NetworkMode.FULL,
- # Forward host TCP ports into the guest
- port_forwards=[PortForward(host=8080, guest=80)],
+ # Forward TCP ports in either direction (host -> guest, guest -> host)
+ port_forwards=[Forward(Host(8080), Guest(80)), Forward(Guest(3128), Host(8080))],
# Expand the guest filesystem on boot
disk_size="10G",
# Attach virtual GPU, keyboard, and mouse for screenshot/type_text/mouse control
diff --git a/packages/quicksand/quicksand/__init__.py b/packages/quicksand/quicksand/__init__.py
index 0461b9f..77a2a6d 100644
--- a/packages/quicksand/quicksand/__init__.py
+++ b/packages/quicksand/quicksand/__init__.py
@@ -41,6 +41,9 @@ from quicksand_core import (
Architecture,
BootTiming,
ExecuteResult,
+ Forward,
+ Guest,
+ Host,
Key,
MachineType,
Mount,
@@ -111,6 +114,9 @@ __all__ = [ # noqa: RUF022
"SandboxConfigParams",
"Mount",
"MountType",
+ "Forward",
+ "Host",
+ "Guest",
"PortForward",
"ExecuteResult",
# Boot timing
diff --git a/packages/quicksand/quicksand/cli/run.py b/packages/quicksand/quicksand/cli/run.py
index c3c9c1a..bf308cf 100644
--- a/packages/quicksand/quicksand/cli/run.py
+++ b/packages/quicksand/quicksand/cli/run.py
@@ -7,6 +7,10 @@ import asyncio
import contextlib
import sys
from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from quicksand_core._types import Forward
GLOBAL_SAVES_DIR = Path.home() / ".quicksand" / "sandboxes"
@@ -67,8 +71,18 @@ def _add_arguments(parser: argparse.ArgumentParser) -> None:
"-p",
"--port",
action="append",
- metavar="HOST:GUEST",
- help="Forward host port to guest port (can be repeated)",
+ metavar="[HOST_ADDR:]HOST_PORT:[GUEST_ADDR:]GUEST_PORT",
+ help="Expose guest port GUEST_PORT on the host at HOST_ADDR:HOST_PORT "
+ "(default HOST_ADDR 127.0.0.1; can be repeated)",
+ )
+ parser.add_argument(
+ "-g",
+ "--guest-port",
+ action="append",
+ metavar="[GUEST_ADDR:]GUEST_PORT:[HOST_ADDR:]HOST_PORT",
+ help="Expose host port HOST_PORT inside the guest at GUEST_ADDR:GUEST_PORT "
+ "(default GUEST_ADDR 10.0.2.101, HOST_ADDR 127.0.0.1; can be repeated). "
+ "Works without internet access.",
)
parser.add_argument(
"--boot-timeout",
@@ -144,6 +158,41 @@ def _save_output_path(name: str) -> Path:
return GLOBAL_SAVES_DIR / name
+def _parse_forward(spec: str, *, guest_to_host: bool) -> Forward:
+ """Parse a ``-p`` or ``-g`` spec into a :class:`Forward`.
+
+ Both flags share one shape, ``[SRC_ADDR:]SRC_PORT:[DST_ADDR:]DST_PORT``.
+ ``-p`` reads it as host then guest, ``-g`` as guest then host. Omitted
+ addresses take the endpoint defaults.
+
+ Raises ``ValueError`` with a user-facing message on malformed input.
+ """
+ from quicksand_core._types import Forward, Guest, Host
+
+ parts = spec.split(":")
+ try:
+ if len(parts) == 2:
+ src_addr, src_port, dst_addr, dst_port = None, parts[0], None, parts[1]
+ elif len(parts) == 3 and parts[0].isdigit():
+ src_addr, src_port, dst_addr, dst_port = None, parts[0], parts[1], parts[2]
+ elif len(parts) == 3:
+ src_addr, src_port, dst_addr, dst_port = parts[0], parts[1], None, parts[2]
+ elif len(parts) == 4:
+ src_addr, src_port, dst_addr, dst_port = parts
+ else:
+ raise ValueError("wrong number of fields")
+
+ if guest_to_host:
+ src = Guest(src_addr, int(src_port)) if src_addr else Guest(int(src_port))
+ dst = Host(dst_addr, int(dst_port)) if dst_addr else Host(int(dst_port))
+ else:
+ src = Host(src_addr, int(src_port)) if src_addr else Host(int(src_port))
+ dst = Guest(dst_addr, int(dst_port)) if dst_addr else Guest(int(dst_port))
+ return Forward(src, dst)
+ except ValueError as e:
+ raise ValueError(f"{spec} ({e}; expected [SRC_ADDR:]SRC_PORT:[DST_ADDR:]DST_PORT)") from e
+
+
def cmd(args: argparse.Namespace) -> int:
"""Run an interactive shell in a sandbox."""
return asyncio.run(_cmd_async(args))
@@ -171,23 +220,15 @@ async def _cmd_async(args: argparse.Namespace) -> int:
host_path, guest_path = mount_str.split(":", 1)
mounts.append(Mount(host=host_path, guest=guest_path))
- # Parse port forwards
- from quicksand_core._types import PortForward
-
- port_forwards: list[PortForward] = []
- if args.port:
- for pf_str in args.port:
- if ":" not in pf_str:
- print(
- f"Invalid port-forward format: {pf_str} (expected HOST:GUEST)",
- file=sys.stderr,
- )
- return 1
- host_port, guest_port = pf_str.split(":", 1)
+ # Parse port forwards (both directions share one list)
+
+ port_forwards: list[Forward] = []
+ for flag, specs in (("-p", args.port or []), ("-g", args.guest_port or [])):
+ for spec in specs:
try:
- port_forwards.append(PortForward(host=int(host_port), guest=int(guest_port)))
- except ValueError:
- print(f"Invalid port numbers: {pf_str}", file=sys.stderr)
+ port_forwards.append(_parse_forward(spec, guest_to_host=(flag == "-g")))
+ except ValueError as e:
+ print(f"Invalid {flag} forward: {e}", file=sys.stderr)
return 1
# Resolve network mode
diff --git a/pyproject.toml b/pyproject.toml
index 72b546b..47e7ad5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -91,6 +91,7 @@ fix = ["fix:format", "fix:code"]
"test:integration-mounts-readwrite" = "pytest tests/integration/mounts/readwrite -v --timeout=300"
"test:integration-mounts-multiple" = "pytest tests/integration/mounts/multiple -v --timeout=300"
"test:integration-network-unrestricted" = "pytest tests/integration/network/unrestricted -v --timeout=300"
+"test:integration-network-guest-forward" = "pytest tests/integration/network/guest_forward -v --timeout=300"
"test:integration-checkpoint" = "pytest tests/integration/checkpoint -v --timeout=300"
"test:integration-dev" = "pytest tests/integration/dev -v --timeout=600 -m docker"
"test:no-docker" = "pytest tests/ -x -v --timeout=120 -k 'not docker'"
diff --git a/tests/integration/network/guest_forward/__init__.py b/tests/integration/network/guest_forward/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/integration/network/guest_forward/conftest.py b/tests/integration/network/guest_forward/conftest.py
new file mode 100644
index 0000000..603feaa
--- /dev/null
+++ b/tests/integration/network/guest_forward/conftest.py
@@ -0,0 +1,80 @@
+"""Fixtures for guest-forward tests: a host HTTP server exposed inside an offline sandbox."""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from typing import Any
+
+import pytest
+import pytest_asyncio
+from quicksand import Forward, Guest, Host, NetworkMode, Sandbox
+
+from tests.conftest import has_qemu
+from tests.integration.conftest import get_vm_type
+
+GUEST_PORT = 8080
+
+
+class _EchoPathHandler(BaseHTTPRequestHandler):
+ """Answers every GET with ``path=<request path>`` so callers can tell responses apart."""
+
+ def do_GET(self):
+ body = f"path={self.path}\n".encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "text/plain")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, format: str, *args: Any) -> None:
+ pass
+
+
[email protected](scope="module")
+def host_http_server():
+ """Loopback-only HTTP server on a random port, served on a background thread."""
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _EchoPathHandler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ yield server
+ server.shutdown()
+ server.server_close()
+
+
+@pytest_asyncio.fixture(scope="module")
+async def shared_sandbox(real_image, real_kernel, host_http_server):
+ """Module-scoped MOUNTS_ONLY sandbox with the host HTTP server forwarded in."""
+ if not has_qemu():
+ pytest.skip("QEMU not installed")
+
+ sandbox = Sandbox(
+ image=get_vm_type(),
+ network_mode=NetworkMode.MOUNTS_ONLY,
+ port_forwards=[
+ Forward(Guest(GUEST_PORT), Host(host_http_server.server_port)),
+ ],
+ )
+ await sandbox.start()
+ await _wait_for_network(sandbox)
+ yield sandbox
+ await sandbox.stop()
+
+
+async def _wait_for_network(sandbox: Sandbox, timeout: float = 15.0) -> None:
+ """Wait until the guest has a default route.
+
+ The agent channel comes up over virtio-serial before guest networking
+ does, so the first TCP connection can otherwise race DHCP. Reads
+ ``/proc/net/route`` rather than ``ip``, which minimal images may lack.
+ """
+ for _ in range(int(timeout / 0.5)):
+ result = await sandbox.execute(
+ "awk '$2 == \"00000000\" { found = 1 } END { exit !found }' /proc/net/route",
+ timeout=5.0,
+ )
+ if result.exit_code == 0:
+ return
+ await asyncio.sleep(0.5)
+ raise RuntimeError("guest network did not come up")
diff --git a/tests/integration/network/guest_forward/test_guest_forward.py b/tests/integration/network/guest_forward/test_guest_forward.py
new file mode 100644
index 0000000..32c0fae
--- /dev/null
+++ b/tests/integration/network/guest_forward/test_guest_forward.py
@@ -0,0 +1,61 @@
+"""Tests for Forward(Guest, Host): host services reachable from an offline guest."""
+
+from __future__ import annotations
+
+import pytest
+from quicksand_core._types import NetworkConstants
+
+from .conftest import GUEST_PORT
+
+_URL = f"http://{NetworkConstants.GUESTFWD_DEFAULT_IP}:{GUEST_PORT}"
+
+# Ubuntu images ship curl; Alpine images only have BusyBox wget. ``fetch``
+# is a shell function that writes the response body to stdout either way.
+_FETCH = (
+ 'fetch() { if command -v curl >/dev/null 2>&1; then curl -sS --max-time 10 "$1"; '
+ 'else wget -qO- -T 10 "$1"; fi; }; '
+)
+
+
+class TestGuestToHostForward:
+ """Guest-forward tests using a shared MOUNTS_ONLY sandbox."""
+
+ @pytest.mark.asyncio
+ async def test_guest_reaches_host_server(self, shared_sandbox):
+ """A plain GET through the tunnel returns the host server's response."""
+ result = await shared_sandbox.execute(f"{_FETCH} fetch {_URL}/hello", timeout=15.0)
+ assert result.exit_code == 0, f"fetch failed: {result.stderr}"
+ assert result.stdout.strip() == "path=/hello"
+
+ @pytest.mark.asyncio
+ async def test_concurrent_connections_are_independent(self, shared_sandbox):
+ """Parallel guest connections each get their own host connection.
+
+ This is the property the per-connection relay buys over a chardev
+ target, which would interleave all guest connections on one stream.
+ """
+ n = 8
+ script = _FETCH + " ".join(f"fetch {_URL}/req{i} > /tmp/gf_{i} &" for i in range(n))
+ script += " wait; cat " + " ".join(f"/tmp/gf_{i}" for i in range(n))
+ result = await shared_sandbox.execute(script, timeout=30.0)
+ assert result.exit_code == 0, f"fetch failed: {result.stderr}"
+ lines = sorted(result.stdout.split())
+ assert lines == sorted(f"path=/req{i}" for i in range(n))
+
+ @pytest.mark.asyncio
+ async def test_sequential_connections_reopen_cleanly(self, shared_sandbox):
+ """Each request opens and closes its own tunnel connection."""
+ for i in range(3):
+ result = await shared_sandbox.execute(f"{_FETCH} fetch {_URL}/seq{i}", timeout=15.0)
+ assert result.exit_code == 0, f"fetch failed: {result.stderr}"
+ assert result.stdout.strip() == f"path=/seq{i}"
+
+ @pytest.mark.asyncio
+ async def test_internet_still_blocked(self, shared_sandbox):
+ """The tunnel does not loosen MOUNTS_ONLY isolation."""
+ result = await shared_sandbox.execute(
+ f"{_FETCH} fetch http://1.1.1.1/ >/dev/null", timeout=20.0
+ )
+ assert result.exit_code != 0
diff --git a/tests/unit/test_cli_run_forwards.py b/tests/unit/test_cli_run_forwards.py
new file mode 100644
index 0000000..eb65518
--- /dev/null
+++ b/tests/unit/test_cli_run_forwards.py
@@ -0,0 +1,48 @@
+"""Unit tests for ``quicksand run`` port-forward argument parsing."""
+
+from __future__ import annotations
+
+import pytest
+from quicksand.cli.run import _parse_forward
+from quicksand_core import Forward, Guest, Host
+
+
+ ("spec", "expected"),
+ [
+ ("8080:80", Forward(Host(8080), Guest(80))),
+ ("0.0.0.0:8080:80", Forward(Host(8080, "0.0.0.0"), Guest(80))),
+ ("8080:10.0.2.15:80", Forward(Host(8080), Guest(80, "10.0.2.15"))),
+ ("0.0.0.0:8080:10.0.2.15:80", Forward(Host(8080, "0.0.0.0"), Guest(80, "10.0.2.15"))),
+ ],
+)
+def test_parse_host_to_guest(spec, expected):
+ assert _parse_forward(spec, guest_to_host=False) == expected
+
+
+ ("spec", "expected"),
+ [
+ ("3128:8080", Forward(Guest(3128), Host(8080))),
+ ("10.0.2.102:3128:8080", Forward(Guest(3128, "10.0.2.102"), Host(8080))),
+ ("3128:localhost:8080", Forward(Guest(3128), Host(8080, "localhost"))),
+ (
+ "10.0.2.102:3128:localhost:8080",
+ Forward(Guest(3128, "10.0.2.102"), Host(8080, "localhost")),
+ ),
+ ],
+)
+def test_parse_guest_to_host(spec, expected):
+ assert _parse_forward(spec, guest_to_host=True) == expected
+
+
[email protected]("spec", ["3128", "a:b", "1:2:3:4:5", "3128:0", "10.0.2.2:80:8080"])
+def test_parse_guest_to_host_rejects(spec):
+ with pytest.raises(ValueError):
+ _parse_forward(spec, guest_to_host=True)
+
+
[email protected]("spec", ["80", "localhost:8080:80", "8080:guest.local:80"])
+def test_parse_host_to_guest_rejects(spec):
+ with pytest.raises(ValueError):
+ _parse_forward(spec, guest_to_host=False)
diff --git a/tests/unit/test_core_config.py b/tests/unit/test_core_config.py
index b87f642..d74714f 100644
--- a/tests/unit/test_core_config.py
+++ b/tests/unit/test_core_config.py
@@ -4,8 +4,8 @@ from __future__ import annotations
import pytest
from pydantic import ValidationError
-from quicksand_core import Mount, PortForward, SandboxConfig
-from quicksand_core._types import NetworkMode
+from quicksand_core import Forward, Guest, Host, Mount, SandboxConfig
+from quicksand_core._types import NetworkConstants, NetworkMode
class TestMount:
@@ -56,7 +56,7 @@ class TestSandboxConfig:
memory="2G",
cpus=4,
mounts=mounts,
- port_forwards=[PortForward(host=8080, guest=80)],
+ port_forwards=[Forward(Host(8080), Guest(80))],
network_mode=NetworkMode.FULL,
extra_qemu_args=["-cpu", "host"],
boot_timeout=120.0,
@@ -66,7 +66,7 @@ class TestSandboxConfig:
assert config.memory == "2G"
assert config.cpus == 4
assert len(config.mounts) == 1
- assert config.port_forwards == [PortForward(host=8080, guest=80)]
+ assert config.port_forwards == [Forward(Host(8080), Guest(80))]
assert config.network_mode is NetworkMode.FULL
assert config.extra_qemu_args == ["-cpu", "host"]
assert config.boot_timeout == 120.0
@@ -107,3 +107,203 @@ class TestExecuteResult:
result = ExecuteResult(stdout="", stderr="error message", exit_code=1)
assert result.exit_code == 1
assert result.stderr == "error message"
+
+
+class TestForwardTypes:
+ """Tests for Forward/Host/Guest and the deprecated PortForward alias."""
+
+ def test_port_forward_is_deprecated_alias(self):
+ """PortForward still builds a host-to-guest Forward but warns."""
+ from quicksand_core import PortForward
+
+ with pytest.warns(DeprecationWarning, match="Forward"):
+ pf = PortForward(host=8080, guest=80)
+ assert pf == Forward(Host(8080), Guest(80))
+
+ def test_host_to_guest_defaults(self):
+ f = Forward(Host(8080), Guest(80))
+ assert f.host_to_guest
+ assert f.host == Host(8080, "127.0.0.1")
+ assert f.guest == Guest(80)
+ assert f.guest.address is None # left to QEMU: the guest's own IP
+
+ def test_guest_to_host_defaults(self):
+ f = Forward(Guest(3128), Host(8080))
+ assert not f.host_to_guest
+ assert f.guest == Guest(3128, NetworkConstants.GUESTFWD_DEFAULT_IP)
+ assert f.host == Host(8080, "127.0.0.1")
+
+ def test_explicit_addresses_are_kept(self):
+ f = Forward(Guest(80, "10.0.2.102"), Host(5001, "db.internal"))
+ assert f.guest.address == "10.0.2.102"
+ assert f.host.address == "db.internal"
+ g = Forward(Host(8080, "0.0.0.0"), Guest(80, "10.0.2.15"))
+ assert g.host.address == "0.0.0.0"
+ assert g.guest.address == "10.0.2.15"
+
+ @pytest.mark.parametrize(
+ "make",
+ [
+ lambda: Host(8080, "0.0.0.0"),
+ lambda: Host("0.0.0.0", 8080),
+ lambda: Host("0.0.0.0:8080"),
+ lambda: Host(port=8080, address="0.0.0.0"),
+ lambda: Host("0.0.0.0", port=8080),
+ ],
+ )
+ def test_host_constructor_forms_are_equivalent(self, make):
+ assert make() == Host(8080, "0.0.0.0")
+ assert (make().port, make().address) == (8080, "0.0.0.0")
+
+ @pytest.mark.parametrize(
+ "make",
+ [
+ lambda: Guest(80, "10.0.2.102"),
+ lambda: Guest("10.0.2.102", 80),
+ lambda: Guest("10.0.2.102:80"),
+ lambda: Guest(port=80, address="10.0.2.102"),
+ ],
+ )
+ def test_guest_constructor_forms_are_equivalent(self, make):
+ assert make() == Guest(80, "10.0.2.102")
+
+ def test_port_only_forms(self):
+ assert Host(8080).address == "127.0.0.1"
+ assert Host(port=8080).address == "127.0.0.1"
+ assert Guest(80).address is None
+ assert Host("db.internal", 5432) == Host("db.internal:5432")
+
+ @pytest.mark.parametrize(
+ ("make", "exc", "match"),
+ [
+ (lambda: Host(), TypeError, "missing a port"), # ty: ignore[no-matching-overload]
+ (lambda: Host("0.0.0.0"), TypeError, "missing a port"),
+ (lambda: Host("a:b"), ValueError, "expected 'address:port'"),
+ (lambda: Host(":80"), ValueError, "expected 'address:port'"),
+ (lambda: Host(1, 2), TypeError, "multiple values for port"), # ty: ignore[no-matching-overload]
+ (lambda: Host("a", "b"), TypeError, "multiple values for address"), # ty: ignore[no-matching-overload]
+ (lambda: Host("a:1", 2), TypeError, "multiple values for port"),
+ (lambda: Host(1, "a", "b"), TypeError, "at most 2 positional"), # ty: ignore[no-matching-overload]
+ (lambda: Host(True), TypeError, "int port or a str address"),
+ (lambda: Host(1.5), TypeError, "int port or a str address"), # ty: ignore[no-matching-overload]
+ (lambda: Host("x:0"), ValueError, "Host.port"),
+ ],
+ )
+ def test_endpoint_constructor_rejects(self, make, exc, match):
+ with pytest.raises(exc, match=match):
+ make()
+
+ def test_kind_is_not_part_of_repr_or_equality(self):
+ assert "kind" not in repr(Host(1))
+ assert Host(1) == Host(1, "127.0.0.1")
+
+ @pytest.mark.parametrize(
+ ("endpoint", "match"),
+ [
+ (lambda: Host(0), "Host.port"),
+ (lambda: Guest(70000), "Guest.port"),
+ ],
+ )
+ def test_endpoint_rejects_bad_port(self, endpoint, match):
+ with pytest.raises(ValueError, match=match):
+ endpoint()
+
+ @pytest.mark.parametrize(
+ ("src", "dst", "match"),
+ [
+ (Host(1), Host(2), "Host endpoint to a Guest endpoint"),
+ (Guest(1), Guest(2), "Host endpoint to a Guest endpoint"),
+ (Host(1, "localhost"), Guest(2), "Host.address must be an IPv4"),
+ (Host(1), Guest(2, "guest.local"), "Guest.address must be an IPv4"),
+ (Guest(1, "not-an-ip"), Host(2), "Guest.address must be an IPv4"),
+ (Guest(1, "192.168.1.1"), Host(2), "slirp network"),
+ (Guest(1, "10.0.2.2"), Host(2), "gateway"),
+ (Guest(1, "10.0.2.3"), Host(2), "DNS"),
+ (Guest(1, "10.0.2.15"), Host(2), "guest itself"),
+ ],
+ )
+ def test_forward_rejects_bad_combinations(self, src, dst, match):
+ with pytest.raises(ValueError, match=match):
+ Forward(src, dst)
+
+ def test_host_destination_may_be_hostname(self):
+ f = Forward(Guest(5432), Host(5432, "db.internal"))
+ assert f.host.address == "db.internal"
+
+ def test_config_splits_forward_directions(self):
+ h2g = Forward(Host(8080), Guest(80))
+ g2h = Forward(Guest(3128), Host(8080))
+ config = SandboxConfig(image="ubuntu", port_forwards=[h2g, g2h])
+ assert config.port_forwards == [h2g, g2h]
+ assert config.host_forwards == [h2g]
+ assert config.guest_forwards == [g2h]
+
+ def test_config_accepts_forward_dicts(self):
+ """Dict input is discriminated by the endpoint ``kind`` tag."""
+ config = SandboxConfig.model_validate(
+ {
+ "image": "ubuntu",
+ "port_forwards": [
+ {"src": {"kind": "host", "port": 8080}, "dst": {"kind": "guest", "port": 80}},
+ {"src": {"kind": "guest", "port": 3128}, "dst": {"kind": "host", "port": 8080}},
+ ],
+ }
+ )
+ assert config.host_forwards == [Forward(Host(8080), Guest(80))]
+ assert config.guest_forwards == [Forward(Guest(3128), Host(8080))]
+
+ def test_guest_to_host_requires_nic(self):
+ with pytest.raises(ValidationError, match=r"NetworkMode\.NONE"):
+ SandboxConfig(
+ image="ubuntu",
+ network_mode=NetworkMode.NONE,
+ port_forwards=[Forward(Guest(3128), Host(8080))],
+ )
+
+ def test_host_to_guest_allowed_with_network_none(self):
+ """Only guest-to-host forwards need a NIC at config time."""
+ config = SandboxConfig(
+ image="ubuntu",
+ network_mode=NetworkMode.NONE,
+ port_forwards=[Forward(Host(8080), Guest(80))],
+ )
+ assert config.host_forwards == [Forward(Host(8080), Guest(80))]
+
+ def test_guest_to_host_rejects_smb_tunnel_collision(self):
+ with pytest.raises(ValidationError, match="CIFS mount tunnel"):
+ SandboxConfig(
+ image="ubuntu",
+ port_forwards=[
+ Forward(
+ Guest(NetworkConstants.GUESTFWD_SMB_PORT, NetworkConstants.GUESTFWD_SMB_IP),
+ Host(8080),
+ )
+ ],
+ )
+
+ def test_guest_to_host_rejects_duplicate_source(self):
+ with pytest.raises(ValidationError, match="Duplicate guest-to-host"):
+ SandboxConfig(
+ image="ubuntu",
+ port_forwards=[Forward(Guest(3128), Host(8080)), Forward(Guest(3128), Host(9090))],
+ )
+
+ def test_host_to_guest_rejects_duplicate_bind(self):
+ with pytest.raises(ValidationError, match="Duplicate host-to-guest"):
+ SandboxConfig(
+ image="ubuntu",
+ port_forwards=[Forward(Host(8080), Guest(80)), Forward(Host(8080), Guest(81))],
+ )
+
+ def test_same_port_different_address_ok(self):
+ config = SandboxConfig(
+ image="ubuntu",
+ port_forwards=[
+ Forward(Guest(3128), Host(8080)),
+ Forward(Guest(3128, "10.0.2.102"), Host(9090)),
+ Forward(Host(8080), Guest(80)),
+ Forward(Host(8080, "0.0.0.0"), Guest(81)),
+ ],
+ )
+ assert len(config.guest_forwards) == 2
+ assert len(config.host_forwards) == 2
diff --git a/tests/unit/test_core_sandbox.py b/tests/unit/test_core_sandbox.py
index 127024e..23c4498 100644
--- a/tests/unit/test_core_sandbox.py
+++ b/tests/unit/test_core_sandbox.py
@@ -7,7 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import pytest
-from quicksand_core import PortForward, Sandbox, SandboxConfig
+from quicksand_core import Forward, Guest, Host, Sandbox, SandboxConfig
from quicksand_core._types import NetworkMode
from quicksand_core.host import Accelerator, LinuxConfig
from quicksand_core.host.quicksand_guest_agent_client import _retry_on_transient_error
@@ -163,7 +163,7 @@ class TestSandboxNetworkArgs:
"""Test port forwarding configuration."""
config = SandboxConfig(
image="ubuntu",
- port_forwards=[PortForward(host=8080, guest=80), PortForward(host=8443, guest=443)],
+ port_forwards=[Forward(Host(8080), Guest(80)), Forward(Host(8443), Guest(443))],
)
platform_config = _create_test_platform_config()
@@ -171,6 +171,54 @@ class TestSandboxNetworkArgs:
assert "hostfwd=tcp:127.0.0.1:8080-:80" in args[1]
assert "hostfwd=tcp:127.0.0.1:8443-:443" in args[1]
+ def test_host_to_guest_addresses(self, fake_qcow2):
+ """Explicit Host bind address and Guest destination address reach hostfwd."""
+ config = SandboxConfig(
+ image="ubuntu",
+ port_forwards=[Forward(Host(8080, "0.0.0.0"), Guest(80, "10.0.2.15"))],
+ )
+ platform_config = _create_test_platform_config()
+
+ args = platform_config._build_network_args(config, 12345)
+ assert "hostfwd=tcp:0.0.0.0:8080-10.0.2.15:80" in args[1]
+
+ def test_guest_to_host_forwards(self, fake_qcow2):
+ """Guest-to-host Forwards become per-connection guestfwd relay tunnels."""
+ config = SandboxConfig(
+ image="ubuntu",
+ network_mode=NetworkMode.MOUNTS_ONLY,
+ port_forwards=[
+ Forward(Host(8080), Guest(80)),
+ Forward(Guest(3128), Host(9090)),
+ Forward(Guest(5000, "10.0.2.102"), Host(5001, "localhost")),
+ ],
+ )
+ platform_config = _create_test_platform_config()
+
+ args = platform_config._build_network_args(config, 12345)
+ netdev = args[1]
+ assert "restrict=on" in netdev
+ assert "hostfwd=tcp:127.0.0.1:8080-:80" in netdev
+ assert "guestfwd=tcp:10.0.2.101:3128-cmd:" in netdev
+ assert "guestfwd=tcp:10.0.2.102:5000-cmd:" in netdev
+ assert "_tcp_relay.py 127.0.0.1 9090" in netdev
+ assert "_tcp_relay.py localhost 5001" in netdev
+ # Never the single-connection chardev form.
+ assert "-tcp:" not in netdev
+
+ def test_guest_to_host_coexists_with_smb_tunnel(self, fake_qcow2):
+ """A guest-to-host Forward does not displace the SMB mount tunnel."""
+ config = SandboxConfig(
+ image="ubuntu",
+ network_mode=NetworkMode.MOUNTS_ONLY,
+ port_forwards=[Forward(Guest(3128), Host(9090))],
+ )
+ platform_config = _create_test_platform_config()
+
+ args = platform_config._build_network_args(config, 12345, smb_port=4450)
+ assert "guestfwd=tcp:10.0.2.100:445-cmd:" in args[1]
+ assert "guestfwd=tcp:10.0.2.101:3128-cmd:" in args[1]
+
class TestSandboxMountConfig:
"""Tests for mount configuration validation."""