Skip to content

policy

policy

The unified +/- policy line format — one grammar for every tier.

A policy file is one entry per line::

+pypi.org                          # allow a domain
+*.pythonhosted.org                # allow every subdomain
+192.168.1.50:8080                 # allow one host:port
+localhost:8000                    # reach a service on the host's localhost
-telemetry.vendor.com              # deny
+api.anthropic.com  %reason=harness-test %expires=2026-06-09T12:00Z

The leading + (allow) or - (deny) is mandatory. %key=value markers carry optional metadata (reason, expires, from, first/last, hits); # starts a free-text comment that the parser ignores entirely. Blank and comment-only lines are skipped.

The reserved target localhost is a host-service grant: +localhost:PORT opens the host machine's own localhost:PORT to the container (the loader routes it to the backend host-loopback address, accepted above the deny tiers). It requires an explicit port and the + action.

This module is the single parser for shipped, generated, and authored policy alike. Stdlib-only, so it is cheap to audit and safe to import from anywhere.

Action = Literal['+', '-'] module-attribute

A policy verdict prefix: "+" (allow) or "-" (deny).

LOCALHOST = 'localhost' module-attribute

Reserved target: +localhost:PORT grants the container access to the host's localhost.

__all__ = ['LOCALHOST', 'Action', 'PolicyEntry', 'domain_targets', 'ip_targets', 'is_ip', 'localhost_ports', 'parse_policy', 'render_policy'] module-attribute

PolicyEntry(action, target, port=None, meta=dict()) dataclass

One parsed policy line.

Attributes:

Name Type Description
action Action

"+" (allow) or "-" (deny).

target str

a domain (optionally *.-prefixed), an IP literal, or a CIDR.

port int | None

the optional :port (None when unspecified).

meta dict[str, str]

the %key=value markers parsed off the line (empty when none).

action instance-attribute

target instance-attribute

port = None class-attribute instance-attribute

meta = field(default_factory=dict) class-attribute instance-attribute

parse_policy(text)

Parse policy text into entries, failing fast on a malformed line.

Raises:

Type Description
ValueError

on a missing +/- prefix, an empty or invalid target, an out-of-range port, or a malformed %key=value marker — annotated with the line number.

Source code in src/terok_shield/policy.py
def parse_policy(text: str) -> list[PolicyEntry]:
    """Parse policy text into entries, failing fast on a malformed line.

    Raises:
        ValueError: on a missing ``+``/``-`` prefix, an empty or invalid
            target, an out-of-range port, or a malformed ``%key=value``
            marker — annotated with the line number.
    """
    entries: list[PolicyEntry] = []
    for lineno, raw in enumerate(text.splitlines(), start=1):
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        body, _, _comment = line.partition("#")  # comments bear zero load
        try:
            entries.append(_parse_line(body.strip()))
        except ValueError as exc:
            raise ValueError(f"line {lineno}: {exc} ({raw!r})") from exc
    return entries

render_policy(entries)

Render entries back to canonical text (round-trips parse_policy).

Source code in src/terok_shield/policy.py
def render_policy(entries: list[PolicyEntry]) -> str:
    """Render entries back to canonical text (round-trips [`parse_policy`][terok_shield.policy.parse_policy])."""
    lines = []
    for e in entries:
        # An IPv6 literal carrying a port must be bracketed, else ``addr:port``
        # is indistinguishable from a longer IPv6 address on re-parse.
        host = f"[{e.target}]" if (e.port is not None and ":" in e.target) else e.target
        line = f"{e.action}{host}" + (f":{e.port}" if e.port is not None else "")
        line += "".join(f" %{key}={value}" for key, value in sorted(e.meta.items()))
        lines.append(line)
    return "\n".join(lines) + "\n" if lines else ""

localhost_ports(entries)

Ports from the +localhost:PORT host-service grants, fed to the builder's loopback_ports.

Only admitting (+) entries grant a port — a programmatically built -localhost entry (which parse_policy would reject) is never a grant.

Source code in src/terok_shield/policy.py
def localhost_ports(entries: list[PolicyEntry]) -> tuple[int, ...]:
    """Ports from the ``+localhost:PORT`` host-service grants, fed to the builder's ``loopback_ports``.

    Only admitting (``+``) entries grant a port — a programmatically built
    ``-localhost`` entry (which ``parse_policy`` would reject) is never a grant.
    """
    return tuple(
        e.port for e in entries if e.action == "+" and e.target == LOCALHOST and e.port is not None
    )

is_ip(target)

True when target is an IP literal or CIDR (a domain or localhost is False).

Source code in src/terok_shield/policy.py
def is_ip(target: str) -> bool:
    """True when *target* is an IP literal or CIDR (a domain or ``localhost`` is False)."""
    try:
        ipaddress.ip_network(target, strict=False)
    except ValueError:
        return False
    return True

ip_targets(entries)

The IP/CIDR targets among entries (domains and localhost excluded), order-preserving.

Source code in src/terok_shield/policy.py
def ip_targets(entries: list[PolicyEntry]) -> list[str]:
    """The IP/CIDR targets among *entries* (domains and ``localhost`` excluded), order-preserving."""
    return [e.target for e in entries if is_ip(e.target)]

domain_targets(entries)

The domain targets among entries (IPs and localhost excluded), order-preserving.

Source code in src/terok_shield/policy.py
def domain_targets(entries: list[PolicyEntry]) -> list[str]:
    """The domain targets among *entries* (IPs and ``localhost`` excluded), order-preserving."""
    return [e.target for e in entries if e.target != LOCALHOST and not is_ip(e.target)]