Skip to content

mode

mode

Hook mode: OCI hooks + per-container netns.

Uses OCI hooks to apply per-container nftables rules inside each container's network namespace. No root required — only podman and nft.

Orchestrates collaborators per lifecycle phase:

  • RulesetBuilder (nft.rules) — generates and verifies nft rulesets
  • DnsResolver (dns.resolver) — pre-start domain resolution
  • ProfileLoader (profiles) — allowlist profile composition
  • AuditLogger (audit) — event logging
  • CommandRunner (run) — subprocess execution (nft, nsenter)
  • dnsmasq (dns.dnsmasq) — runtime DNS with nftset auto-population
  • hook_install (hooks.install) — OCI hook file generation
  • state (state) — per-container state bundle I/O

logger = logging.getLogger(__name__) module-attribute

WINDOW_NEEDS_UP = 'The bypass window opens only in the UP posture, and {container} is {posture}: outside UP the window set is unreferenced, so an open window would grant nothing. Raise the shield first.' module-attribute

Refusal for arming the timed window outside UP, where nothing would read it.

OVERRIDE_NEEDS_RULESET = "{container} is {posture}: a live override goes into a running ruleset's t10 set, and there is none to take it. An authored shield.override applies from the next start." module-attribute

Refusal for a live override on a container with no override set to add to.

HookMode(*, config, runner, audit, dns, profiles, ruleset)

Hook-mode shield backend (Strategy, implements ShieldModeBackend).

Coordinates the full lifecycle of OCI-hook-based container firewalling. Delegates to RulesetBuilder for nft generation, DnsResolver for name resolution, ProfileLoader for allowlists, dnsmasq for runtime DNS, and state for per-container persistence.

Create a hook mode backend with all collaborators.

Parameters:

Name Type Description Default
config ShieldConfig

Shield configuration (provides state_dir).

required
runner CommandRunner

Command runner for subprocess calls.

required
audit AuditLogger

Audit logger for event logging.

required
dns DnsResolver

DNS resolver for domain resolution and caching.

required
profiles ProfileLoader

Profile loader for allowlist profiles.

required
ruleset RulesetBuilder

Ruleset builder for nft generation and verification.

required
Source code in src/terok_shield/hooks/mode.py
def __init__(
    self,
    *,
    config: ShieldConfig,
    runner: "CommandRunner",
    audit: "AuditLogger",
    dns: "DnsResolver",
    profiles: "ProfileLoader",
    ruleset: RulesetBuilder,
) -> None:
    """Create a hook mode backend with all collaborators.

    Args:
        config: Shield configuration (provides state_dir).
        runner: Command runner for subprocess calls.
        audit: Audit logger for event logging.
        dns: DNS resolver for domain resolution and caching.
        profiles: Profile loader for allowlist profiles.
        ruleset: Ruleset builder for nft generation and verification.
    """
    self._config = config
    self._runner = runner
    self._audit = audit
    self._dns = dns
    self._profiles = profiles
    self._ruleset = ruleset
    self._podman_info: PodmanInfo | None = None
    self._gateways: tuple[str, str] | None = None

pre_start(container, profiles, *, security_deny=(), provider_allow=(), project_allow=(), override=())

Prepare for container start in hook mode.

Verifies setup, composes profiles, resolves DNS, writes allowlist, detects DNS tier, sets annotations, and returns the podman CLI arguments needed for shield protection.

Parameters:

Name Type Description Default
security_deny Sequence[str]

Hosts/IPs an upstream layer (executor's roster projection, carried by sandbox) generates for the t20 security-deny tier — vault hosts denied direct egress.

()
provider_allow Sequence[str]

Hosts/IPs generated for the t30 provider-allow tier — agent/provider egress endpoints.

()
project_allow Sequence[str]

Hosts/IPs authored by the orchestrator for the t40 project-allow tier (git remote, custom domains) — merged with the composed profiles.

()
override Sequence[str]

Hosts/IPs/CIDRs authored for the t10 break-glass override tier, which sits above the security-deny; statically resolved and seeded into a separate nft set. A CIDR opens a whole subnet above the deny — accepted, but logged as a warning and an override_range audit event. Shield owns writing every tier, so callers pass data, never touch the bundle.

()

Raises:

Type Description
SetupRequiredError

When global hooks are not installed or need refreshing.

Source code in src/terok_shield/hooks/mode.py
def pre_start(
    self,
    container: str,
    profiles: list[str],
    *,
    security_deny: Sequence[str] = (),
    provider_allow: Sequence[str] = (),
    project_allow: Sequence[str] = (),
    override: Sequence[str] = (),
) -> list[str]:
    """Prepare for container start in hook mode.

    Verifies setup, composes profiles, resolves DNS, writes
    allowlist, detects DNS tier, sets annotations, and returns
    the podman CLI arguments needed for shield protection.

    Args:
        security_deny: Hosts/IPs an upstream layer (executor's roster
            projection, carried by sandbox) generates for the t20
            security-deny tier — vault hosts denied direct egress.
        provider_allow: Hosts/IPs generated for the t30 provider-allow
            tier — agent/provider egress endpoints.
        project_allow: Hosts/IPs authored by the orchestrator for the t40
            project-allow tier (git remote, custom domains) — merged with
            the composed profiles.
        override: Hosts/IPs/CIDRs authored for the t10 break-glass override
            tier, which sits *above* the security-deny; statically resolved
            and seeded into a separate nft set.  A CIDR opens a whole
            subnet above the deny — accepted, but logged as a warning and
            an ``override_range`` audit event.  Shield owns writing every
            tier, so callers pass data, never touch the bundle.

    Raises:
        terok_util.SetupRequiredError: When global hooks are not installed
            or need refreshing.
    """
    sd = self._config.state_dir.resolve()
    require_setup(HooksInstaller().check_setup(live=True))
    info = self._get_podman_info()
    StateBundle(sd).ensure_dirs()

    # Detect DNS tier, upstream DNS, and gateway addresses
    dnsmasq_bin = dnsmasq.locate(self._config.dnsmasq_path, self._runner)
    tier = self._detect_dns_tier(container, sd, dnsmasq_bin)
    mode = info.network_mode or "pasta"
    upstream_dns = _upstream_dns_for_mode(mode)
    gw_v4, gw_v6 = self._gateways = _gateways_for_mode(mode)

    # Persist the launch-detected facts first: they are what ``refresh``
    # reuses instead of re-detecting, and ``_write_ruleset`` reads the
    # ports back out of the bundle (SSOT) rather than off the config, so
    # later up/down rebuilds share one source.
    bundle = StateBundle(sd)
    bundle.upstream_dns.write_text(f"{upstream_dns}\n")
    bundle.dns_tier.write_text(f"{tier.value}\n")
    bundle.dnsmasq_command.write_text(f"{dnsmasq_bin}\n")
    bundle.network_mode.write_text(f"{mode}\n")
    bundle.record_gateways(gw_v4, gw_v6)
    bundle.loopback_ports.write_text("".join(f"{p}\n" for p in self._config.loopback_ports))
    # The NFLOG reader reads no config, so the creation-time audit choice
    # reaches it — and a later harvest — through the bundle.
    audit_flag = str(self._config.audit_enabled).lower()
    bundle.audit_flag.write_text(f"{audit_flag}\n")
    self._author_policy(
        container,
        sd,
        profiles,
        tier,
        upstream_dns,
        (gw_v4, gw_v6),
        security_deny=security_deny,
        provider_allow=provider_allow,
        project_allow=project_allow,
        override=override,
    )

    # Build podman args
    args = self._build_network_args(mode, gw_v4)

    # WORKAROUND(pasta-dns-bind): bind-mount shield's own resolv.conf over
    # the container's on every tier instead of using podman --dns. --dns
    # makes pasta bind host port 53, which fails for a rootless container.
    # Podman's default resolv.conf lists the host's own nameservers; on an
    # AppArmor host one of those is a blocked LAN router, so the container
    # resolves nothing (#1246). Drop this when rootless podman/pasta can
    # set the container's resolvers without binding host port 53.
    args += ["--volume", f"{StateBundle(sd).resolv_conf}:/etc/resolv.conf:ro,Z"]

    # Annotations: profiles, name, state_dir, version, dns.  loopback_ports
    # lives in the state bundle (per-container, written above), not as an
    # annotation — annotations are write-only on shield's side.
    args += [
        "--annotation",
        f"{ANNOTATION_KEY}={ANNOTATION_LIST_SEP.join(profiles)}",
        "--annotation",
        f"{ANNOTATION_NAME_KEY}={container}",
        "--annotation",
        f"{ANNOTATION_STATE_DIR_KEY}={sd}",
        "--annotation",
        f"{ANNOTATION_VERSION_KEY}={state.BUNDLE_VERSION}",
        "--annotation",
        f"{ANNOTATION_AUDIT_ENABLED_KEY}={audit_flag}",
        "--annotation",
        f"{ANNOTATION_UPSTREAM_DNS_KEY}={upstream_dns}",
        "--annotation",
        f"{ANNOTATION_DNS_TIER_KEY}={tier.value}",
    ]

    self._audit.log_event(container, "setup", detail="using setup-installed global hooks")

    args += [
        "--cap-drop",
        "NET_ADMIN",
        "--cap-drop",
        "NET_RAW",
    ]
    return args

refresh(container, profiles, *, security_deny=(), provider_allow=(), project_allow=(), override=())

Recompute an existing container's policy bundle before a plain restart.

The policy-authoring half of pre_start without the launch half: rewrites every tier from the caller's current data, refreshes the static-resolution caches, and regenerates ruleset.nft + the dnsmasq config — so the OCI hook applies current policy at the next podman start instead of replaying the bundle frozen at creation. Reuses every launch-detected fact the bundle persisted — DNS tier, upstream DNS, network mode, loopback ports — rather than re-detecting: the container's mounts and annotations were built for those, a fresh detection could disagree with them, and a restart stays free of podman info.

Raises:

Type Description
RuntimeError

When the bundle carries no persisted DNS tier / upstream DNS / network mode (pre_start never ran for this state dir).

Source code in src/terok_shield/hooks/mode.py
def refresh(
    self,
    container: str,
    profiles: list[str],
    *,
    security_deny: Sequence[str] = (),
    provider_allow: Sequence[str] = (),
    project_allow: Sequence[str] = (),
    override: Sequence[str] = (),
) -> None:
    """Recompute an existing container's policy bundle before a plain restart.

    The policy-authoring half of
    [`pre_start`][terok_shield.hooks.mode.HookMode.pre_start] without the
    launch half: rewrites every tier from the caller's current data,
    refreshes the static-resolution caches, and regenerates
    ``ruleset.nft`` + the dnsmasq config — so the OCI hook applies
    *current* policy at the next ``podman start`` instead of replaying
    the bundle frozen at creation.  Reuses every launch-detected fact the
    bundle persisted — DNS tier, upstream DNS, network mode, loopback
    ports — rather than re-detecting: the container's mounts and
    annotations were built for those, a fresh detection could disagree
    with them, and a restart stays free of ``podman info``.

    Raises:
        RuntimeError: When the bundle carries no persisted DNS tier /
            upstream DNS / network mode (``pre_start`` never ran for this
            state dir).
    """
    sd = self._config.state_dir.resolve()
    bundle = StateBundle(sd)
    tier = bundle.read_dns_tier()
    mode = bundle.read_network_mode()
    upstream_dns = self._read_upstream_dns()
    if tier is None or not upstream_dns or not mode:
        raise RuntimeError(
            "shield bundle has no persisted DNS tier / upstream DNS / network mode — "
            "pre_start never completed for this container; re-create the task"
        )
    self._gateways = bundle.read_gateways()
    self._author_policy(
        container,
        sd,
        profiles,
        tier,
        upstream_dns,
        self._gateways,
        security_deny=security_deny,
        provider_allow=provider_allow,
        project_allow=project_allow,
        override=override,
    )

resolve(*, force=False)

Re-resolve the authored policy into its static-resolution caches.

The resolution step of refresh on its own: every cache the bundle's policy feeds is refreshed, and no tier, ruleset or dnsmasq config is rewritten — the project-allow tier keeps every host its caller authored. force re-resolves even when a cache is fresh. Returns the resolved allow IPs, which stay empty on the live tier, where dnsmasq resolves per query.

Raises:

Type Description
RuntimeError

When the bundle carries no persisted DNS tier (pre_start never ran for this state dir).

Source code in src/terok_shield/hooks/mode.py
def resolve(self, *, force: bool = False) -> list[str]:
    """Re-resolve the authored policy into its static-resolution caches.

    The resolution step of [`refresh`][terok_shield.hooks.mode.HookMode.refresh]
    on its own: every cache the bundle's policy feeds is refreshed, and no
    tier, ruleset or dnsmasq config is rewritten — the project-allow tier
    keeps every host its caller authored.  *force* re-resolves even when a
    cache is fresh.  Returns the resolved allow IPs, which stay empty on
    the live tier, where dnsmasq resolves per query.

    Raises:
        RuntimeError: When the bundle carries no persisted DNS tier
            (``pre_start`` never ran for this state dir).
    """
    sd = self._config.state_dir.resolve()
    tier = StateBundle(sd).read_dns_tier()
    if tier is None:
        raise RuntimeError(
            "shield bundle has no persisted DNS tier — "
            "pre_start never completed for this container"
        )
    return self._resolve_policy(sd, tier, force=force)

allow_domain(container, domain)

Record +domain in the runtime overlay and reload dnsmasq.

The overlay (policy/live) flips any prior deny of domain and survives reloads; the dnsmasq restart picks up the new nftset= line so future IP rotations of domain are auto-populated. The IP-level allow (nft set update) is handled separately by allow_ip().

No-op when the container runs no dnsmasq (the static IP-level allow already happened via allow_ip()).

Source code in src/terok_shield/hooks/mode.py
def allow_domain(self, container: str, domain: str) -> None:
    """Record ``+domain`` in the runtime overlay and reload dnsmasq.

    The overlay (``policy/live``) flips any prior deny of *domain* and
    survives reloads; the dnsmasq restart picks up the new ``nftset=``
    line so future IP rotations of *domain* are auto-populated.  The
    IP-level allow (nft set update) is handled separately by ``allow_ip()``.

    No-op when the container runs no dnsmasq (the static IP-level allow
    already happened via ``allow_ip()``).
    """
    sd = self._config.state_dir.resolve()
    if not _runs_dnsmasq(sd):
        return
    StateBundle(sd).overlay_set("+", domain)
    self._reload_dnsmasq(container, sd)

deny_domain(container, domain)

Record -domain in the runtime overlay and reload dnsmasq.

Counterpart of allow_domain(): the dnsmasq restart picks up the local= sinkhole, so domain stops resolving (NXDOMAIN) and the deny fails fast in the DNS plane instead of timing out against the filter.

No-op when the container runs no dnsmasq.

Source code in src/terok_shield/hooks/mode.py
def deny_domain(self, container: str, domain: str) -> None:
    """Record ``-domain`` in the runtime overlay and reload dnsmasq.

    Counterpart of ``allow_domain()``: the dnsmasq restart picks up the
    ``local=`` sinkhole, so *domain* stops resolving (NXDOMAIN) and the
    deny fails fast in the DNS plane instead of timing out against the
    filter.

    No-op when the container runs no dnsmasq.
    """
    sd = self._config.state_dir.resolve()
    if not _runs_dnsmasq(sd):
        return
    StateBundle(sd).overlay_set("-", domain)
    self._reload_dnsmasq(container, sd)

security_tier(*, refresh=False)

The t20 security tier this container's bundle records, as a matcher.

With refresh, on a DNS tier that runs no dnsmasq, the tier's names are resolved afresh and their current addresses join the cached ones. Nothing sinkholes a vault host's name on those tiers, so the container can reach an address the launch-time resolution never saw — and that address arrives as an unattributed refusal an operator may be asked to allow. The dnsmasq tiers sinkhole the names, so the cache stands.

Source code in src/terok_shield/hooks/mode.py
def security_tier(self, *, refresh: bool = False) -> SecurityTier:
    """The t20 security tier this container's bundle records, as a matcher.

    With *refresh*, on a DNS tier that runs no dnsmasq, the tier's names
    are resolved afresh and their current addresses join the cached ones.
    Nothing sinkholes a vault host's name on those tiers, so the container
    can reach an address the launch-time resolution never saw — and that
    address arrives as an unattributed refusal an operator may be asked
    to allow.  The dnsmasq tiers sinkhole the names, so the cache stands.
    """
    bundle = StateBundle(self._config.state_dir.resolve())
    fresh: list[str] = []
    tier = bundle.read_dns_tier()
    if refresh and tier is not None and not tier.runs_dnsmasq:
        names = [
            target
            for target in bundle.read_effective().security_deny_targets()
            if not is_ip(target) and not target.startswith("*.")
        ]
        fresh = self._dns.resolve_domains(names, quiet=True) if names else []
    return bundle.read_security_tier(extra_addresses=fresh)

check_security_tier(target, ips)

Refuse target when the t20 security tier refuses it — by name, suffix, or any of ips.

Meant to run once per grant, before anything changes, with every address the target resolved to: a refusal is all or nothing, never a grant of some addresses and a refusal of the rest. The tiers without dnsmasq re-resolve the security names first (security_tier).

Raises:

Type Description
SecurityTierRefusal

Naming the security-tier entry, and the shared address when that is the cause.

Source code in src/terok_shield/hooks/mode.py
def check_security_tier(self, target: str, ips: Sequence[str]) -> None:
    """Refuse *target* when the t20 security tier refuses it — by name, suffix, or any of *ips*.

    Meant to run once per grant, before anything changes, with every
    address the target resolved to: a refusal is all or nothing, never a
    grant of some addresses and a refusal of the rest.  The tiers without
    dnsmasq re-resolve the security names first
    ([`security_tier`][terok_shield.hooks.mode.HookMode.security_tier]).

    Raises:
        SecurityTierRefusal: Naming the security-tier entry, and the
            shared address when that is the cause.
    """
    if (refusal := self.security_tier(refresh=True).refusal(target, ips)) is not None:
        raise refusal

allow_ip(container, ip)

Live-allow an IP for a running container via nsenter.

Tier authority holds at this API itself, whoever calls it. An address in the t20 security tier is refused — never deleted from the deny set, where it would stay lifted until the next rebuild. Only the operator's own runtime deny (a - entry of policy/live, or an address one of its denied names resolved to) is lifted before the address joins the t40 allow set. The check reads the bundle as it stands; check_security_tier is the caller's place to add a fresh resolution.

Raises:

Type Description
SecurityTierRefusal

When ip falls in the security tier.

Source code in src/terok_shield/hooks/mode.py
def allow_ip(self, container: str, ip: str) -> None:
    """Live-allow an IP for a running container via nsenter.

    Tier authority holds at this API itself, whoever calls it.  An address
    in the t20 security tier is refused — never deleted from the deny set,
    where it would stay lifted until the next rebuild.  Only the
    operator's own runtime deny (a ``-`` entry of ``policy/live``, or an
    address one of its denied names resolved to) is lifted before the
    address joins the t40 allow set.  The check reads the bundle as it
    stands; [`check_security_tier`][terok_shield.hooks.mode.HookMode.check_security_tier]
    is the caller's place to add a fresh resolution.

    Raises:
        SecurityTierRefusal: When *ip* falls in the security tier.
    """
    ip = safe_ip(ip)
    sd = self._config.state_dir.resolve()
    bundle = StateBundle(sd)
    if (refusal := bundle.read_security_tier().refusal(ip)) is not None:
        raise refusal

    # Un-deny: lift the operator's own runtime deny of this address.
    if ip in bundle.read_live_denied_ips():
        nft_cmd = delete_deny_elements_dual([ip])
        if nft_cmd:
            self._nft_apply_best_effort(container, nft_cmd)

    # When the live set has a default timeout (30 m), permanent IPs must use
    # 'timeout 0s' so they are never evicted by the set's per-element expiry clock.
    tier = bundle.read_dns_tier()
    element = f"{{ {ip} timeout 0s }}" if tier is not None and tier.live else f"{{ {ip} }}"

    self._runner.nft_via_nsenter(
        container,
        "add",
        "element",
        "inet",
        "terok_shield",
        self._set_for_ip(ip),
        element,
    )
    # Persist to the runtime overlay (flips any prior deny of this IP).
    bundle.overlay_set("+", ip)

allow_offline(target)

Record +target for a container that is not running: no nft, nothing live.

A stopped container has no ruleset to take a live grant, so the grant goes where every runtime allow persists — the policy/live overlay, flipping any earlier deny of the same target — and the files the OCI hook applies at the next start are re-derived from the bundle at once. The hook replays ruleset.nft and starts dnsmasq from dnsmasq.conf as they stand, re-deriving nothing, so without that a plain podman start would come up without the grant; terok's restart path, which runs refresh before podman start, carries it either way. A domain is recorded as the name, so its own DNS tier resolves it — at once on a tier that pins names, per query on dnsmasq-live.

Raises:

Type Description
SecurityTierRefusal

When the bundle's security tier refuses target by name, suffix or address.

RuntimeError

When no launch ever prepared this bundle — no start would read the overlay, so recording into it would only look like success (a mistyped container, say).

Source code in src/terok_shield/hooks/mode.py
def allow_offline(self, target: str) -> None:
    """Record ``+target`` for a container that is not running: no nft, nothing live.

    A stopped container has no ruleset to take a live grant, so the grant
    goes where every runtime allow persists — the ``policy/live`` overlay,
    flipping any earlier deny of the same target — and the files the OCI
    hook applies at the next start are re-derived from the bundle at
    once.  The hook replays ``ruleset.nft`` and starts dnsmasq from
    ``dnsmasq.conf`` as they stand, re-deriving nothing, so without that
    a plain ``podman start`` would come up without the grant; terok's
    restart path, which runs [`refresh`][terok_shield.hooks.mode.HookMode.refresh]
    before ``podman start``, carries it either way.  A domain is recorded
    as the name, so its own DNS tier resolves it — at once on a tier that
    pins names, per query on ``dnsmasq-live``.

    Raises:
        SecurityTierRefusal: When the bundle's security tier refuses
            *target* by name, suffix or address.
        RuntimeError: When no launch ever prepared this bundle — no start
            would read the overlay, so recording into it would only look
            like success (a mistyped container, say).
    """
    if is_ip(target):
        target = safe_ip(target)
    sd = self._config.state_dir.resolve()
    bundle = StateBundle(sd)
    tier = bundle.read_dns_tier()
    upstream_dns = self._read_upstream_dns()
    mode = bundle.read_network_mode()
    if tier is None or not upstream_dns or not mode:
        raise RuntimeError(
            f"no shield bundle was prepared in {sd} — pre_start never completed there, "
            "so no start would apply the allow"
        )
    if (refusal := bundle.read_security_tier().refusal(target)) is not None:
        raise refusal
    bundle.overlay_set("+", target)
    self._rederive_start_artifacts(sd, tier, upstream_dns)

override(container, target, expires, *, reason)

Break glass for target on a running container, valid through expires, for reason.

The live counterpart of an authored shield.override: target joins the t10 set — above the security tier and the private ranges — with a kernel timeout that runs out at the end of the expires day, host local time (or at the instant, for a full timestamp). The kernel ends the break-glass on time with nothing in userspace keeping the clock, as it closes the bypass window. Agents keep reaching a vault-relayed provider through the vault; the override only adds the direct route.

The grant is recorded in the t10 tier with its %expires and its %reason, so every shield down/up rebuild re-seeds it, timed afresh. The tier stays the orchestrator's: the next restart re-derives it from the orchestrator's own policy, which is where an override that should outlive the task belongs. The whole t10 set is swapped in one nft transaction — flushed and re-seeded — so every element takes its current timeout and nothing overlaps. A domain also opens in the dnsmasq sinkhole, so the workload can resolve it.

The tier follows the kernel, never the other way round. The override names resolve first, held in memory (_resolve_grant). The rest holds the t10 lock (override_change), so no revoke or other grant interleaves: the swap is computed from the tier as it stands then — whatever a revoke or a grant changed while the names resolved — with this grant in place of any earlier entry for target. The tier records the grant only once the kernel has taken that swap, and the override cache takes the answers the swap was seeded from after the tier, so it post-dates the tier it answers for. A refusal or a failed swap leaves both as they were, and at no moment does the tier hold a grant the kernel never took. The grant is audited as override — with its expiry and reason — the moment the transaction commits, before the tier records it and before the dnsmasq reload: once the kernel holds it, the audit trail must too, whatever happens next.

The hard-deny floor (link-local, cloud metadata) sits above t10 and is never overridden: a target that is, or resolves into, a hard-deny range is refused, and so is a name that resolves to nothing. So is anything that takes in the host's own loopback — the address host.containers.internal names under the recorded network mode — which only a +localhost:PORT grant reaches, one port at a time. An IP or CIDR is judged before anything else, so it is refused with the same message in every posture, a stopped container's included. A name is resolved once, so the addresses checked are the addresses seeded. That resolution covers every other override name as well, and none of their answers is checked here: the seed itself leaves out whatever no override may open, and the grant notes it. Under slirp4netns the ruleset refuses the gateway above t10 regardless. An expires that runs out while the names resolve is refused like one that had passed already: the grant would never reach the kernel.

Returns:

Type Description
list[str]

The addresses target opened (itself, for an IP or a CIDR).

Raises:

Type Description
ValueError

For a target no override can carry (localhost, the host alias or its address, a wildcard, the hard-deny floor, or text that is no target), an expires that is no date or has passed, or an empty reason.

RuntimeError

When the container has no running ruleset with an override set (stopped, quarantined, unrecognised), or the target resolves to no address — and, once the kernel holds the grant, when the tier or the override cache cannot record it or dnsmasq cannot reload to open the name.

Source code in src/terok_shield/hooks/mode.py
def override(self, container: str, target: str, expires: str, *, reason: str) -> list[str]:
    """Break glass for *target* on a running container, valid through *expires*, for *reason*.

    The live counterpart of an authored ``shield.override``: *target*
    joins the t10 set — above the security tier and the private ranges —
    with a kernel timeout that runs out at the end of the *expires* day,
    host local time (or at the instant, for a full timestamp).  The kernel
    ends the break-glass on time with nothing in userspace keeping the
    clock, as it closes the bypass window.  Agents keep reaching a
    vault-relayed provider through the vault; the override only adds the
    direct route.

    The grant is recorded in the t10 tier with its ``%expires`` and its
    ``%reason``, so every ``shield down``/``up`` rebuild re-seeds it,
    timed afresh.  The tier stays the orchestrator's: the next restart
    re-derives it from the orchestrator's own policy, which is where an
    override that should outlive the task belongs.  The whole t10 set is
    swapped in one nft transaction — flushed and re-seeded — so every
    element takes its current timeout and nothing overlaps.  A domain
    also opens in the dnsmasq sinkhole, so the workload can resolve it.

    The tier follows the kernel, never the other way round.  The override
    names resolve first, held in memory (``_resolve_grant``).  The rest
    holds the t10 lock
    ([`override_change`][terok_shield.state.StateBundle.override_change]),
    so no revoke or other grant interleaves: the swap is computed from
    the tier as it stands then — whatever a revoke or a grant changed
    while the names resolved — with this grant in place of any earlier
    entry for *target*.  The tier records the grant only once the kernel
    has taken that swap, and the override cache takes the answers the
    swap was seeded from after the tier, so it post-dates the tier it
    answers for.  A refusal or a failed swap leaves both as they were,
    and at no moment does the tier hold a grant the kernel never took.
    The grant is audited as ``override`` — with its expiry and reason —
    the moment the transaction commits, before the tier records it and
    before the dnsmasq reload: once the kernel holds it, the audit trail
    must too, whatever happens next.

    The hard-deny floor (link-local, cloud metadata) sits above t10 and is
    never overridden: a target that is, or resolves into, a hard-deny
    range is refused, and so is a name that resolves to nothing.  So is
    anything that takes in the host's own loopback — the address
    ``host.containers.internal`` names under the recorded network mode —
    which only a ``+localhost:PORT`` grant reaches, one port at a time.  An
    IP or CIDR is judged before anything else, so it is refused with the
    same message in every posture, a stopped container's included.  A
    name is resolved once, so the addresses checked are the addresses
    seeded.  That resolution covers every other override name as well,
    and none of their answers is checked here: the seed itself leaves out
    whatever no override may open, and the grant notes it.  Under
    slirp4netns the ruleset refuses the gateway above t10 regardless.
    An *expires* that runs out while the names resolve is refused like
    one that had passed already: the grant would never reach the kernel.

    Returns:
        The addresses *target* opened (itself, for an IP or a CIDR).

    Raises:
        ValueError: For a target no override can carry (``localhost``,
            the host alias or its address, a wildcard, the hard-deny
            floor, or text that is no target), an *expires* that is no
            date or has passed, or an empty *reason*.
        RuntimeError: When the container has no running ruleset with an
            override set (stopped, quarantined, unrecognised), or the
            target resolves to no address — and, once the kernel holds
            the grant, when the tier or the override cache cannot record
            it or dnsmasq cannot reload to open the name.
    """
    target = _override_target(target)
    if is_ip(target):
        # An address is judged without resolving it, so the floor and the
        # host's loopback refuse it in any posture, ahead of every other check.
        host = StateBundle(self._config.state_dir.resolve()).host_loopback()
        _check_override_addresses(target, [target], host=host)
    if not (reason := reason.strip()):
        raise ValueError(
            f"an override of {target} needs a reason: a break-glass says why it exists"
        )
    if expiry_deadline(expires).timestamp() <= time.time():
        raise ValueError(
            f"expires={expires} has already passed — an override must hold through today "
            "at least"
        )
    posture = self.shield_state(container)
    if posture not in _OVERRIDE_POSTURES:
        raise RuntimeError(
            OVERRIDE_NEEDS_RULESET.format(container=container, posture=posture.value)
        )
    sd = self._config.state_dir.resolve()
    bundle = StateBundle(sd)
    entry = override_entry(target, expires, reason=reason)
    answers = self._resolve_grant(bundle, entry)
    with bundle.override_change():
        # The tier as it stands now, with the grant in it: a revoke that
        # landed while the names resolved stays revoked, a grant stays granted.
        recorded = bundle.read_effective()
        planned = recorded.with_override(entry)
        cached = read_name_resolution(bundle.override_resolved) or {}
        resolution = cached if answers is None else {**cached, **answers}
        addresses = [target] if is_ip(target) else resolution.get(target, [])
        host = bundle.host_loopback()
        _check_override_addresses(target, addresses, host=host)
        moment = time.time()
        if expiry_deadline(expires).timestamp() <= moment:
            raise ValueError(
                f"expires={expires} ran out while the override names resolved — "
                "nothing was granted"
            )
        # What a rebuild still seeds for the target should the tier fail to record the grant.
        spelled = bundle.override_entries(target)
        earlier = [prior for prior in recorded.active_override(moment) if prior in spelled]
        seeds = bundle.read_override_seeds(moment, policy=planned, resolution=resolution)
        self._runner.nft_via_nsenter(
            container, stdin=flush_override_sets() + _override_elements(seeds, moment)
        )
        self._audit.log_event(
            container, "override", dest=target, detail=f"expires={expires}; reason={reason}"
        )
        # Only now that the kernel holds the grant does the tier record it.
        unrecorded = _record_grant(container, bundle, target, expires, reason, earlier)
        if unrecorded is None and answers is not None:
            unrecorded = _cache_grant_answers(container, bundle, planned, resolution, target)
    self._note_override_refusals(container, sd)
    self._open_granted_name(container, sd, target, unrecorded)
    return addresses

revoke_override(container, target)

End target's break-glass on container now, ahead of its expiry.

The counterpart of override. It ends a live grant and an authored shield.override alike, since the t10 tier records both the same way. Only an override still in force can be revoked. A target with no t10 entry, or one whose %expires already ran out, is refused, so a typo never passes for a door that was closed.

Closing must not depend on a step that can fail open, so the order matters. The tier entry goes first: every rebuild re-seeds t10 from the tier, so from then on no shield up/down re-opens the override, whatever fails next. Next, ruleset.nft and override.expiry are re-derived from the bundle, because the OCI hook replays them at every start, so a plain podman start does not re-open it either. A rewrite that fails stops nothing after it: the swap, the audit and the dnsmasq reload still run, and its error is raised last — otherwise the running ruleset would keep admitting the target, and a retry would find no override left to revoke. Last, the running ruleset's t10 set is swapped in one nft transaction, flushed and re-seeded with the overrides still in force. The target's elements go, and every other element stays, timed to its own deadline. No DNS lookup takes part: a revoke must not wait on, or fail with, a resolver. From the read of the tier through the swap it holds the t10 lock (override_change), so a grant whose names resolved meanwhile swaps from the tier as the revoke left it and never re-opens the target. A grant resolves before it takes the lock, so the wait is never on a resolver.

The revoke is audited as override_revoked once nothing running holds the override: when that transaction commits, or at once when the ruleset carries no t10 set (a stopped or quarantined container). For a name, dnsmasq is then reloaded if its config still punches the name through the sinkhole, so the name stops resolving again. A stopped container's dnsmasq config is rewritten on disk instead, for its next start.

"Stopped" is podman's word, never an unreadable ruleset's: a listing that fails reads as OFFLINE too, so before a revoke treats the container as stopped, podman must confirm it has no process, or has no such container (confirmed_posture). A running container whose ruleset could not be read gets the swap, and its failure is raised.

Connections already established keep running: the ruleset accepts established traffic ahead of every tier, so a revoke stops new connections, as the override's own expiry does.

Returns:

Type Description
OverrideRevocation

The addresses closed, the ones another override still holds open,

OverrideRevocation

and whether the container was running.

Raises:

Type Description
ValueError

For text that is no domain, IP or CIDR, and for localhost: a +localhost:PORT grant opens a preamble port, which no t10 swap takes back.

RuntimeError

When target has no override in force on the container (or it has no state bundle at all), or when neither the ruleset nor podman says whether the container runs — both before anything changes. Also, with the record already gone, when nft cannot drop the elements from the running ruleset, dnsmasq cannot reload to sinkhole the name again, or the files a plain start replays cannot be rewritten — each message saying what still holds.

Source code in src/terok_shield/hooks/mode.py
def revoke_override(self, container: str, target: str) -> OverrideRevocation:
    """End *target*'s break-glass on *container* now, ahead of its expiry.

    The counterpart of [`override`][terok_shield.hooks.mode.HookMode.override].
    It ends a live grant and an authored ``shield.override`` alike, since
    the t10 tier records both the same way.  Only an override still in
    force can be revoked.  A target with no t10 entry, or one whose
    ``%expires`` already ran out, is refused, so a typo never passes for
    a door that was closed.

    Closing must not depend on a step that can fail open, so the order
    matters.  The tier entry goes first: every rebuild re-seeds t10 from
    the tier, so from then on no ``shield up``/``down`` re-opens the
    override, whatever fails next.  Next, ``ruleset.nft`` and
    ``override.expiry`` are re-derived from the bundle, because the OCI
    hook replays them at every start, so a plain ``podman start`` does
    not re-open it either.  A rewrite that fails stops nothing after it:
    the swap, the audit and the dnsmasq reload still run, and its error
    is raised last — otherwise the running ruleset would keep admitting
    the target, and a retry would find no override left to revoke.  Last,
    the running ruleset's t10 set is swapped in one nft transaction,
    flushed and re-seeded with the overrides still in force.  The target's elements go, and every other
    element stays, timed to its own deadline.  No DNS lookup takes part:
    a revoke must not wait on, or fail with, a resolver.  From the read of
    the tier through the swap it holds the t10 lock
    ([`override_change`][terok_shield.state.StateBundle.override_change]),
    so a grant whose names resolved meanwhile swaps from the tier as the
    revoke left it and never re-opens the target.  A grant resolves
    before it takes the lock, so the wait is never on a resolver.

    The revoke is audited as ``override_revoked`` once nothing running
    holds the override: when that transaction commits, or at once when
    the ruleset carries no t10 set (a stopped or quarantined container).
    For a name, dnsmasq is then reloaded if its config still punches the
    name through the sinkhole, so the name stops resolving again.  A
    stopped container's dnsmasq config is rewritten on disk instead, for
    its next start.

    "Stopped" is podman's word, never an unreadable ruleset's: a listing
    that fails reads as OFFLINE too, so before a revoke treats the
    container as stopped, podman must confirm it has no process, or has
    no such container
    ([`confirmed_posture`][terok_shield.hooks.mode.HookMode.confirmed_posture]).
    A running container whose ruleset could not be read gets the swap,
    and its failure is raised.

    Connections already established keep running: the ruleset accepts
    established traffic ahead of every tier, so a revoke stops new
    connections, as the override's own expiry does.

    Returns:
        The addresses closed, the ones another override still holds open,
        and whether the container was running.

    Raises:
        ValueError: For text that is no domain, IP or CIDR, and for
            ``localhost``: a ``+localhost:PORT`` grant opens a preamble
            port, which no t10 swap takes back.
        RuntimeError: When *target* has no override in force on the
            container (or it has no state bundle at all), or when
            neither the ruleset nor podman says whether the container
            runs — both before anything changes.
            Also, with the record already gone, when nft cannot drop the
            elements from the running ruleset, dnsmasq cannot reload to
            sinkhole the name again, or the files a plain start replays
            cannot be rewritten — each message saying what still holds.
    """
    target = _revoke_target(target)
    sd = self._config.state_dir.resolve()
    bundle = StateBundle(sd)
    # From the read of the tier through the swap, no grant interleaves:
    # one that resolved its names meanwhile swaps from the tier as this leaves it.
    with bundle.override_change():
        in_force = _overrides_in_force(container, bundle, target, time.time())
        shown = in_force[0].target
        posture = self.confirmed_posture(container)
        held = _held_addresses(bundle, in_force)
        bundle.remove_override(target)
        stale = self._replay_left_stale(sd, shown, dnsmasq_conf=posture is ShieldState.OFFLINE)
        moment = time.time()
        seeds = bundle.read_override_seeds(moment)
        if posture not in (ShieldState.OFFLINE, ShieldState.QUARANTINE):
            self._swap_out_of_t10(container, shown, seeds, moment, stale=stale)
    kept = tuple(address for address in held if _covered_by_seed(address, seeds))
    closed = tuple(address for address in held if address not in kept)
    live = posture is not ShieldState.OFFLINE
    self._audit.log_event(
        container,
        "override_revoked",
        dest=shown,
        detail=_revocation_detail(in_force[0], live=live),
    )
    self._close_revoked_name(container, sd, shown, live=live, stale=stale)
    return OverrideRevocation(target=shown, closed=closed, kept=kept, live=live)

deny_ip(container, ip)

Live-deny an IP for a running container via nsenter.

Removes from the nft allow set (best-effort), adds to the nft deny set, and records -ip in policy/live so the deny sticks across shield up / restart and flips any prior allow.

Source code in src/terok_shield/hooks/mode.py
def deny_ip(self, container: str, ip: str) -> None:
    """Live-deny an IP for a running container via nsenter.

    Removes from the nft allow set (best-effort), adds to the nft deny set,
    and records ``-ip`` in ``policy/live`` so the deny sticks across
    ``shield up`` / restart and flips any prior allow.
    """
    ip = safe_ip(ip)
    sd = self._config.state_dir.resolve()
    bundle = StateBundle(sd)

    with bundle.override_change():
        # Best-effort nft delete (IP may not be in the set)
        try:
            self._runner.nft_via_nsenter(
                container,
                "delete",
                "element",
                "inet",
                "terok_shield",
                self._set_for_ip(ip),
                f"{{ {ip} }}",
            )
        except ExecError as e:
            stderr = str(e).lower()
            if not any(
                pat in stderr
                for pat in ("no such file", "element does not exist", "not in set")
            ):
                logger.warning("nft delete element failed for %s: %s", ip, e)

        # Add to nft deny set (prevents dnsmasq from re-allowing)
        nft_cmd = add_deny_elements_dual([ip])
        if nft_cmd:
            self._nft_apply_best_effort(container, nft_cmd)

        # Persist before any rebuild can snapshot the policy.
        bundle.overlay_set("-", ip)

shield_down(container, *, disengaged=False)

Switch a running container to the DOWN posture (DISENGAGED when disengaged).

Plain DOWN accepts by default but keeps the deny set and both range floors; DISENGAGED enforces nothing, so its deny sets are left empty — the next shield up repopulates them from the composed policy. Both postures re-seed the t10 override set: it tags break-glass traffic ALLOWED ahead of the DOWN catch-all in DISENGAGED too, so that traffic is never recorded as accepted only because the shield is down.

On a tier that pins names, caches older than an hour are re-resolved first (_refresh_pinned_names), so the deny set the down posture keeps enforcing holds the vault hosts' current addresses; and plain DOWN notes the denied names a rotation would carry past it.

Source code in src/terok_shield/hooks/mode.py
def shield_down(self, container: str, *, disengaged: bool = False) -> None:
    """Switch a running container to the DOWN posture (DISENGAGED when *disengaged*).

    Plain DOWN accepts by default but keeps the deny set and both range
    floors; DISENGAGED enforces nothing, so its deny sets are left empty —
    the next ``shield up`` repopulates them from the composed policy.
    Both postures re-seed the t10 override set: it tags break-glass
    traffic ``ALLOWED`` ahead of the ``DOWN`` catch-all in DISENGAGED
    too, so that traffic is never recorded as accepted only because the
    shield is down.

    On a tier that pins names, caches older than an hour are re-resolved
    first (``_refresh_pinned_names``), so the deny set the down posture keeps enforcing holds the vault
    hosts' current addresses; and plain DOWN notes the denied names a
    rotation would carry past it.
    """
    sd = self._config.state_dir.resolve()
    self._refresh_pinned_names(sd)
    ruleset = self._container_ruleset(container)
    rs = ruleset.build_down(disengaged=disengaged)
    current = self.shield_state(container)
    if current == ShieldState.OFFLINE:
        stdin = rs
    else:
        stdin = f"delete table {NFT_TABLE}\n{rs}"
    snapshot = [] if current == ShieldState.OFFLINE else self._snapshot_allow_sets(container)
    # Publish the accepting table and its mandatory deny entries together.
    # A later seed would leave a window in which a denied connection could
    # become established and survive the restored deny policy.
    bundle = StateBundle(sd)
    with bundle.override_change():
        seeds = "" if disengaged else add_deny_elements_dual(sorted(bundle.read_denied_ips()))
        seeds += _override_elements(bundle.read_override_seeds(), time.time())
        if seeds:
            stdin += f"\n{seeds}"
        self._runner.nft_via_nsenter(container, stdin=stdin)

        # Carry learned IPs across the rebuild before a live deny can remove one.
        # DOWN does not evaluate them, but a later UP snapshots this table.
        self._restore_allow_sets(container, snapshot, skip=())

    # The nft plane is already complete. Synchronize its DNS companion
    # without reopening the transaction or duplicating interval elements.
    self._note_override_refusals(container, sd)
    self._sync_dns_plane(container, sd)

    output = self._runner.nft_via_nsenter(
        container,
        "list",
        "table",
        "inet",
        NFT_TABLE_NAME,
    )
    errors = ruleset.verify_down(output, disengaged=disengaged)
    if errors:
        raise RuntimeError(f"Shield-down ruleset verification failed: {'; '.join(errors)}")
    if not disengaged:
        self._note_rotation_risk(container, sd, posture=ShieldState.DOWN)

shield_quarantine(container)

Total network blackout — drop all traffic, log dropped traffic.

Reads no settings — no DNS, no allowlists, no loopback ports, no gateway probe, no profile lookup. build_quarantine / verify_quarantine are static; the only inputs are the container name and the live ruleset state (table-or-no-table). Any config-conditional branch added here is a bug.

Source code in src/terok_shield/hooks/mode.py
def shield_quarantine(self, container: str) -> None:
    """Total network blackout — drop all traffic, log dropped traffic.

    Reads no settings — no DNS, no allowlists, no loopback ports,
    no gateway probe, no profile lookup.  ``build_quarantine`` /
    ``verify_quarantine`` are static; the only inputs are the
    container name and the live ruleset state (table-or-no-table).
    Any config-conditional branch added here is a bug.
    """
    rs = RulesetBuilder.build_quarantine()
    current = self.shield_state(container)
    stdin = rs if current == ShieldState.OFFLINE else f"delete table {NFT_TABLE}\n{rs}"
    self._runner.nft_via_nsenter(container, stdin=stdin)
    output = self._runner.nft_via_nsenter(
        container,
        "list",
        "table",
        "inet",
        NFT_TABLE_NAME,
    )
    errors = RulesetBuilder.verify_quarantine(output)
    if errors:
        raise RuntimeError(f"Quarantine ruleset verification failed: {'; '.join(errors)}")

shield_up(container)

Restore normal deny-all mode for a running container.

The rebuild is delete table + re-apply, which would forget every dnsmasq-learned allow-set element — a container coming out of the down posture would suddenly lose IPs its workload already resolved (clients cache answers, so they do not necessarily re-query). The allow sets are therefore snapshotted before the rebuild and restored after it.

On a tier that pins names, caches older than an hour are re-resolved before anything changes (_refresh_pinned_names): a container raised after hours down would otherwise come up seeded with its launch-time addresses. The names the tier still pins are noted once the posture holds.

Source code in src/terok_shield/hooks/mode.py
def shield_up(self, container: str) -> None:
    """Restore normal deny-all mode for a running container.

    The rebuild is ``delete table`` + re-apply, which would forget every
    dnsmasq-learned allow-set element — a container coming out of the down
    posture would suddenly lose IPs its workload already resolved (clients
    cache answers, so they do not necessarily re-query).  The allow sets
    are therefore snapshotted before the rebuild and restored after it.

    On a tier that pins names, caches older than an hour are re-resolved
    before anything changes (``_refresh_pinned_names``): a container raised after hours down would otherwise come up seeded
    with its launch-time addresses.  The names the tier still pins are
    noted once the posture holds.
    """
    sd = self._config.state_dir.resolve()
    self._refresh_pinned_names(sd)

    ruleset = self._container_ruleset(container)
    rs = ruleset.build_up()
    current = self.shield_state(container)
    if current == ShieldState.OFFLINE:
        stdin = rs
    else:
        stdin = f"delete table {NFT_TABLE}\n{rs}"
    snapshot = [] if current == ShieldState.OFFLINE else self._snapshot_allow_sets(container)
    with StateBundle(sd).override_change():
        self._runner.nft_via_nsenter(container, stdin=stdin)

        # Re-add effective IPs (allowed minus denied)
        unique_ips = StateBundle(sd).read_effective_ips()
        if unique_ips:
            elements_cmd = ruleset.add_elements_dual(unique_ips)
            if elements_cmd:
                self._runner.nft_via_nsenter(container, stdin=elements_cmd)

        # Repopulate the deny sets and the t10 override set from the bundle
        denied_ips = self._reseed_deny_and_override(container, sd)

        # Restore the snapshot, minus everything the rebuild already re-added
        # (a duplicate/overlapping element would abort the nft transaction)
        # and minus denied entries (deny_ip() removed them from the allow set
        # deliberately — a down/up round trip must not resurrect them).
        self._restore_allow_sets(container, snapshot, skip=[*unique_ips, *denied_ips])

    # Gateway addresses are baked into the ruleset — no repopulation needed.
    self._note_override_refusals(container, sd)
    self._sync_dns_plane(container, sd)

    output = self._runner.nft_via_nsenter(
        container,
        "list",
        "table",
        "inet",
        NFT_TABLE_NAME,
    )
    errors = ruleset.verify_up(output)
    if errors:
        raise RuntimeError(f"Ruleset verification failed: {'; '.join(errors)}")
    self._note_rotation_risk(container, sd, posture=ShieldState.UP)

shield_reset(container)

Forget learned allow-set state — back to the just-launched contents.

Flushes both tier-40 project-allow sets and re-seeds them from the effective policy in a single nft transaction, so authored literals never blink out. dnsmasq-learned IPs vanish until the workload resolves the corresponding names again; the operator overlay (policy/live) and the deny tier are untouched.

Source code in src/terok_shield/hooks/mode.py
def shield_reset(self, container: str) -> None:
    """Forget learned allow-set state — back to the just-launched contents.

    Flushes both tier-40 project-allow sets and re-seeds them from the
    effective policy in a single nft transaction, so authored literals
    never blink out.  dnsmasq-learned IPs vanish until the workload
    resolves the corresponding names again; the operator overlay
    (``policy/live``) and the deny tier are untouched.
    """
    sd = self._config.state_dir.resolve()
    ruleset = self._container_ruleset(container)
    stdin = (
        f"flush set {NFT_TABLE} {TIER_PROJECT_ALLOW}_v4\n"
        f"flush set {NFT_TABLE} {TIER_PROJECT_ALLOW}_v6\n"
    )
    stdin += ruleset.add_elements_dual(StateBundle(sd).read_effective_ips())
    self._runner.nft_via_nsenter(container, stdin=stdin)

arm_window(container, timeout)

Open the timed allow-all window for timeout — in the UP posture only.

The element carries a kernel timeout, so the window closes itself even if nothing ever calls disarm_window — and any disruption (a rebuild, a restart, a crashed host process) only closes it sooner.

Only the UP chain references the window set. Armed in any other posture the element would grant nothing — DOWN accepts by default already, quarantine drops everything — while the caller would be told a window is open, so arming there is refused instead.

Raises:

Type Description
ValueError

When timeout is not an nft timeout.

RuntimeError

When the container's posture is not UP.

Source code in src/terok_shield/hooks/mode.py
def arm_window(self, container: str, timeout: str) -> None:
    """Open the timed allow-all window for *timeout* — in the UP posture only.

    The element carries a kernel timeout, so the window closes itself even
    if nothing ever calls [`disarm_window`][terok_shield.hooks.mode.HookMode.disarm_window]
    — and any disruption (a rebuild, a restart, a crashed host process)
    only closes it sooner.

    Only the UP chain references the window set.  Armed in any other
    posture the element would grant nothing — DOWN accepts by default
    already, quarantine drops everything — while the caller would be told
    a window is open, so arming there is refused instead.

    Raises:
        ValueError: When *timeout* is not an nft timeout.
        RuntimeError: When the container's posture is not UP.
    """
    stdin = arm_bypass_window(timeout)
    if (posture := self.shield_state(container)) is not ShieldState.UP:
        raise RuntimeError(WINDOW_NEEDS_UP.format(container=container, posture=posture.value))
    self._runner.nft_via_nsenter(container, stdin=stdin)

disarm_window(container)

Close the timed allow-all window now, before its timeout runs out.

Source code in src/terok_shield/hooks/mode.py
def disarm_window(self, container: str) -> None:
    """Close the timed allow-all window now, before its timeout runs out."""
    self._runner.nft_via_nsenter(container, stdin=disarm_bypass_window())

inspect(container)

Read the container's posture and its timed window from one ruleset listing.

One nft -T list table serves both: the posture comes from the verifiers, the window's countdown from its own set block, in whole seconds — -T prints them so, where a plain listing would print 4m59s693ms. The window keeps no host-side deadline, so the kernel's clock is the only record and a stale answer is impossible by construction. Only the UP chain reads the window set, so the countdown is reported for UP alone.

Source code in src/terok_shield/hooks/mode.py
def inspect(self, container: str) -> ShieldReading:
    """Read the container's posture and its timed window from one ruleset listing.

    One ``nft -T list table`` serves both: the posture comes from the
    verifiers, the window's countdown from its own set block, in whole
    seconds — ``-T`` prints them so, where a plain listing would print
    ``4m59s693ms``.  The window keeps no host-side deadline, so the
    kernel's clock is the only record and a stale answer is impossible by
    construction.  Only the UP chain reads the window set, so the
    countdown is reported for UP alone.
    """
    output = self._list_table(container, numeric_time=True)
    state = self._classify(output)
    remaining = parse_window_expiry(output) if state is ShieldState.UP else None
    return ShieldReading(state=state, bypass_remaining=remaining)

shield_state(container)

Query the live nft ruleset to determine the container's shield state.

Source code in src/terok_shield/hooks/mode.py
def shield_state(self, container: str) -> ShieldState:
    """Query the live nft ruleset to determine the container's shield state."""
    return self.inspect(container).state

confirmed_posture(container)

The posture allow and revoke route on: OFFLINE only when podman says no process runs.

An empty listing reads as OFFLINE, and so does one that failed: _list_table swallows a podman inspect, nsenter or nft error, because a status poll must not crash on one. A change must not take that for a stopped container. It would skip the kernel, as an allow recorded only in the overlay or a revoke with no t10 swap, and report the change as waiting for the next start while the running ruleset stays as it was. It would also rewrite the dnsmasq config on disk, which a running dnsmasq never reads, and after which no reconcile finds anything left to reload. So an OFFLINE reading is checked against podman's own record. No process (pid 0) is a stopped container, and so is one podman has no record of at all: removed, it runs nothing, and an orchestrator that recreates it under the same name starts it from the same bundle. A process means a running container whose ruleset could not be read, or that carries none at all: that reads as ERROR, so the live path is tried and its failure reported.

Raises:

Type Description
RuntimeError

When podman cannot say whether the container runs either — before the caller changes anything, so the change can simply be tried again.

Source code in src/terok_shield/hooks/mode.py
def confirmed_posture(self, container: str) -> ShieldState:
    """The posture allow and revoke route on: OFFLINE only when podman says no process runs.

    An empty listing reads as OFFLINE, and so does one that failed:
    ``_list_table`` swallows a ``podman inspect``, ``nsenter`` or ``nft``
    error, because a status poll must not crash on one.  A change must not
    take that for a stopped container.  It would skip the kernel, as an
    allow recorded only in the overlay or a revoke with no t10 swap, and
    report the change as waiting for the next start while the running
    ruleset stays as it was.  It would also rewrite the dnsmasq config on
    disk, which a running dnsmasq never reads, and after which no
    reconcile finds anything left to reload.  So an OFFLINE reading is
    checked against podman's own record.  No process (pid 0) is a stopped
    container, and so is one podman has no record of at all: removed, it
    runs nothing, and an orchestrator that recreates it under the same
    name starts it from the same bundle.  A process means a running
    container whose ruleset could not be read, or that carries none at
    all: that reads as ERROR, so the live path is tried and its failure
    reported.

    Raises:
        RuntimeError: When podman cannot say whether the container runs
            either — before the caller changes anything, so the change
            can simply be tried again.
    """
    posture = self.shield_state(container)
    if posture is not ShieldState.OFFLINE:
        return posture
    try:
        pid = self._runner.podman_inspect(container, "{{.State.Pid}}")
    except (ExecError, OSError) as exc:
        if self._podman_has_no_such_container(container):
            return ShieldState.OFFLINE
        raise RuntimeError(
            f"{container}'s ruleset could not be read, and podman cannot say whether it "
            f"is running ({exc}): nothing was changed, so try again"
        ) from exc
    return ShieldState.OFFLINE if pid.strip() in ("", "0") else ShieldState.ERROR

list_rules(container)

List current nft rules for a running container.

Source code in src/terok_shield/hooks/mode.py
def list_rules(self, container: str) -> str:
    """List current nft rules for a running container."""
    return self._list_table(container)

preview(*, down=False, disengaged=False, profiles=())

Generate the ruleset that would be applied to a container.

With profiles, the ruleset the hook applies on the live tier at createRuntime: their +localhost:PORT grants join the preamble and their literal IPs seed the t40 project-allow set. Domains are left out on purpose — the live tier never resolves them at apply time (dnsmasq learns them per query), so nothing is approximated. Touches no setup, podman, DNS or state dir, which makes it the generator for applying a ruleset by hand.

Source code in src/terok_shield/hooks/mode.py
def preview(
    self, *, down: bool = False, disengaged: bool = False, profiles: Sequence[str] = ()
) -> str:
    """Generate the ruleset that would be applied to a container.

    With *profiles*, the ruleset the hook applies on the live tier at
    ``createRuntime``: their ``+localhost:PORT`` grants join the
    preamble and their literal IPs seed the t40 project-allow set.
    Domains are left out on purpose — the live tier never resolves
    them at apply time (dnsmasq learns them per query), so nothing is
    approximated.  Touches no setup, podman, DNS or state dir, which
    makes it the generator for applying a ruleset by hand.
    """
    entries = parse_policy(
        "".join(f"+{e}\n" for e in self._profiles.compose_profiles(list(profiles)))
    )
    builder = self._ruleset
    if grants := localhost_ports(entries):
        ports = (*self._config.loopback_ports, *grants)
        builder = RulesetBuilder(loopback_ports=tuple(dict.fromkeys(ports)))
    ruleset = builder.build_down(disengaged=disengaged) if down else builder.build_up()
    return ruleset + add_elements_dual(ip_targets(entries))