Skip to content

Network and policy

Every connection a sandbox opens goes through a proxy that applies the network policy of the daemon: rules that allow or deny hosts, or HTTP methods and paths, for every sandbox or for one. This page covers the rules of one sandbox, the changes of the policy, the global rules, and how a program checks the policy and reads what the sandboxes reached.

The global policy

The global policy of sbx may allow every host, under its Open preset, and the rules of a sandbox add to it: an allow rule then restricts nothing. Deny what unattended code, agents above all, must not reach, check the global policy (sbx policy ls), and read the activity log while the sandbox exists. See the network model.

The rules of one sandbox

A sandbox handle changes the rules of that sandbox only, and they go with it when it is deleted. They apply from the moment they are added, to a sandbox that exists already, so they do not cover the install commands of its kits: rules that do are a mixin of the kit, given by a sandbox spec or a mixin written in Python.

docs_src/client/network.py
import fastsandbox
from fastsandbox.models import NetworkCheck, RuleChange


async def main() -> None:
    client = await fastsandbox.connect()
    async with client.create("docs-network", kit="shell") as sandbox, sandbox.running():
        # Rules of this sandbox only: they go with it.
        await sandbox.allow_hosts("pypi.org", "files.pythonhosted.org")
        denied = await sandbox.deny_hosts("example.org")
        print(f"applied: {denied.is_applied}")

        # An HTTP rule, narrowed to a method and a path, for this sandbox.
        await client.policy.apply_all(
            RuleChange.deny_http("api.example.com")
            .with_methods("POST")
            .with_path("/admin/**")
            .for_sandbox(sandbox.name)
        )
        for rule in await sandbox.network_rules():
            print(f"{rule.decision} {', '.join(rule.resources)}")

        # What the policy decides for a host, and what the sandbox reached.
        check = await client.policy.check(NetworkCheck.host("api.anthropic.com:443"))
        print(f"api.anthropic.com allowed: {check.allowed}")
        log = (await client.policy.log()).for_sandbox(sandbox.name)
        for host in log.blocked_hosts:
            print(f"blocked: {host.host} ({host.count_since} times)")


if __name__ == "__main__":
    fastsandbox.run(main())
Call What it does
allow_hosts(*hosts) allows TCP connections to the hosts or patterns (*.githubusercontent.com)
deny_hosts(*hosts) denies TCP and UDP connections to them
remove_hosts(*hosts) removes the rules added for them
remove_network_rule(id) removes one rule of the sandbox, by identifier
network_rules() the rules scoped to the sandbox, as NetworkRule

Each change returns a RuleChangeResult, whose created list holds the new rules, as CreatedRule: their rule_id, the resource they cover and their protocols; a change the daemon refuses raises OperationFailedError. From inside the sandbox, a denied host is answered by the proxy, with HTTP 403, in place of the host.

Changing the policy

client.policy applies any change, built with the class methods of RuleChange:

Change Rule
RuleChange.allow(*hosts) allow TCP
RuleChange.deny(*hosts) deny TCP and UDP
RuleChange.allow_http(*hosts), RuleChange.deny_http(*hosts) allow or deny HTTP requests, on every path (/**) until with_path() narrows it
RuleChange.remove(*hosts) remove the rules added for the hosts
RuleChange.remove_rule(id) remove a rule by identifier

and narrowed with with_protocols(), with_methods("POST"), with_path("/admin/**") for HTTP rules, and for_sandbox(name), which scopes the change to one sandbox.

The hosts a rule names

The hosts of a rule are checked as the sbx CLI checks them, before anything is sent. A host is one of these forms:

  • an exact domain, example.com, with globs inside its labels: ? for one character, [12] or [!1] for a class;
  • leading wildcard labels, *.example.com for one label, **.example.com for any number, and ** alone for every host;
  • an IPv4 address, or a CIDR prefix, 10.0.0.0/8 or 2001:db8::1/128;
  • any of those with a port, example.com:443; an IPv6 address takes its port in brackets, [2001:db8::1]:443.

Any other host raises InvalidRequestError with the reason, and the daemon receives nothing: a URL (https://api.example.com), a host with a path (api.example.com/v1, which an HTTP rule takes apart with with_path()), a bare *, a bare IPv6 address. The daemon would store a URL or a path as the resource of a rule and never apply it, leaving reachable the host it seems to name. The check covers every change: apply(), apply_all() and the rules of a sandbox handle. A removal is not checked, so that a rule stored otherwise can still go. The rules of a sandbox spec, and so those of a task, are checked the same way, and raise InvalidSpecError.

A program that takes hosts from its users checks them before it writes a rule, with the same check: HostPattern(text) is the text itself, a str that goes wherever a host does, and raises InvalidHostPatternError, a ValueError whose pattern and reason say what is wrong, without the daemon.

from fastsandbox import InvalidHostPatternError
from fastsandbox.models import HostPattern

try:
    host = HostPattern(user_input)
except InvalidHostPatternError as error:
    print(f"{error.pattern}: {error.reason}")  # "https://…: a host, not a URL: leave the scheme out"

The daemon answers a batch of changes with HTTP 200 and reports the changes that failed inside it: apply(*changes) returns a result per change, each with is_applied and check(); apply_all(*changes) raises OperationFailedError on the first that failed.

Global rules

A change without for_sandbox() is global: it applies to every sandbox of the user, now and later. A program that adds one removes it when it is done, by the identifier returned at its creation, with policy.remove_rule(id).

results = await client.policy.apply_all(RuleChange.deny("tracker.example"))
rule_ids = [rule.rule_id for result in results for rule in result.created]
try:
    ...
finally:
    for rule_id in rule_ids:
        await client.policy.remove_rule(rule_id)

A rule scoped to a sandbox is not found by the global removal: remove it through the sandbox, with remove_network_rule().

Checking and watching

Call Gives
policy.rules() every rule, global and scoped, as NetworkRules, with whether an organization policy governs them
policy.check(check) what the global policy decides for NetworkCheck.host("host:443") or NetworkCheck.http("GET", url): a CheckResult with allowed and the deciding rule. The rules of a sandbox and of its kits are not taken into account
policy.log() the hosts the sandboxes reached or were refused, as a NetworkLog; for_sandbox(name) keeps one sandbox
policy.profiles() the governance profiles
policy.setup_needed() whether the policy still needs its initial setup, done with the sbx CLI
policy.refresh() reloads the policy

In a FastSandbox task

A task declares its rules with Network, scoped to its sandbox as those of a spec are: its host rules from the creation of the sandbox, and its HTTP rules from its start. See Network rules.