Skip to content

terok_shield

terok_shield

terok-shield: nftables-based egress firewalling for Podman containers.

Public API facade. The Shield class coordinates collaborators:

  • HookMode (hooks.mode) — per-container nft ruleset lifecycle
  • DnsResolver (dns.resolver) — domain resolution and caching
  • ProfileLoader (profiles) — allowlist profile composition
  • RulesetBuilder (nft.rules) — nftables ruleset generation
  • AuditLogger (audit) — per-container JSONL audit trail
  • CommandRunner (run) — subprocess execution boundary

Core and support modules are imported lazily — from terok_shield import ShieldConfig does not pull in nft, dnsmasq, or subprocess helpers. Heavy imports are deferred until Shield is instantiated.

HOOK_ENTRYPOINT_NAME = 'terok-shield-hook' module-attribute

Canonical filename of the shield OCI hook entrypoint script.

Used (a) under ~/.local/share/containers/oci/hooks.d/ for user-wide installation and (b) under each per-container state_dir after Shield.pre_start() materialises it. Keeping both sites consuming the same constant means renaming the entrypoint is a single edit.

COMMANDS = CommandTree((_lazy('status', 'Show shield configuration overview', 'observe:STATUS'), _lazy('prepare', 'Prepare shield and print podman flags', 'launch:PREPARE'), _lazy('run', 'Launch a shielded container via podman', 'launch:RUN'), _lazy('resolve', 'Resolve DNS profiles and cache IPs', 'launch:RESOLVE'), _lazy('allow', 'Allow a domain or IP for a container (live, or at its next start when stopped)', 'control:ALLOW'), _lazy('deny', 'Live-deny a domain or IP for a container', 'control:DENY'), _lazy('override', 'Open a break-glass override above the security tier until a date, or revoke it', 'control:OVERRIDE'), _lazy('down', 'Switch container to the DOWN posture (accept + log)', 'control:DOWN'), _lazy('up', 'Restore deny-all mode for a container', 'control:UP'), _lazy('bypass', 'Open, close or show the timed allow-all window for a container', 'control:BYPASS'), _lazy('reset', 'Forget DNS-learned allow state (back to authored policy seeds)', 'control:RESET'), _lazy('quarantine', 'Total network blackout (drop all, log dropped traffic)', 'control:QUARANTINE'), _lazy('rules', 'Show current nft rules for a container', 'control:RULES'), _lazy('harvest', 'Show what a container reached for (refusals, window and DOWN accepts)', 'observe:HARVEST'), _lazy('watch', 'Stream shield events — audit log, NFLOG packets, and DNS blocks on the dnsmasq tiers', 'stream:WATCH'), _lazy('simple-clearance', 'Terminal clearance fallback — prompts operator for each blocked connection (no D-Bus)', 'stream:SIMPLE_CLEARANCE'), _lazy('logs', 'Show audit log entries', 'observe:LOGS'), _lazy('profiles', 'List available shield profiles', 'observe:PROFILES'), _lazy('setup', 'Install global OCI hooks for restart persistence', 'launch:SETUP'), _lazy('check-environment', 'Check podman environment for compatibility issues', 'observe:CHECK_ENVIRONMENT'), _lazy('preview', 'Show ruleset that would be applied', 'control:PREVIEW'))) module-attribute

logger = logging.getLogger(__name__) module-attribute

__version__ = _meta_version('terok-shield') module-attribute

__all__ = ['AllowResult', 'ArgDef', 'COMMANDS', 'CommandDef', 'DnsTier', 'EnvironmentCheck', 'ExecError', 'HOOK_ENTRYPOINT_NAME', 'HarvestEntry', 'HarvestReport', 'HooksInstaller', 'OverrideRevocation', 'RotationRisk', 'SecurityTierRefusal', 'Shield', 'ShieldConfig', 'ShieldMode', 'ShieldReading', 'ShieldRuntime', 'ShieldState', 'ensure_user_hooks_dir_configured', 'recorded_container_id', 'recorded_dns_tier', 'recorded_rotation_risk', 'user_hooks_dir_configured', 'validate_target'] module-attribute

DnsTier

Bases: Enum

How domain allowlists reach the nft allow sets.

dnsmasq with --nftset adds every answered address to the

allow sets before the reply reaches the workload. Follows IP rotation, covers subdomains, accepts wildcard entries, names blocked domains.

DNSMASQ_STATIC: a dnsmasq built without nftset support. The allow sets are resolved once at launch; the query log still names blocked domains. LOOKUP: no dnsmasq. The allow sets are resolved once at launch with dig or drill. GETENT: no dnsmasq and no lookup tool. The allow sets are resolved once at launch with getent hosts.

DNSMASQ_LIVE = 'dnsmasq-live' class-attribute instance-attribute

DNSMASQ_STATIC = 'dnsmasq-static' class-attribute instance-attribute

LOOKUP = 'lookup' class-attribute instance-attribute

GETENT = 'getent' class-attribute instance-attribute

live property

True when the allow sets follow DNS answers as they arrive.

runs_dnsmasq property

True when a per-container dnsmasq serves the container's DNS.

hint property

What a degraded tier lacks and what restores the live one; empty for the live tier.

parse(recorded) classmethod

The tier a recorded name means; None for a name that is not a tier.

A retired name reads as the tier it named, so a container recorded under it restarts instead of being recreated.

Source code in src/terok_shield/config.py
@classmethod
def parse(cls, recorded: str) -> DnsTier | None:
    """The tier a recorded name means; ``None`` for a name that is not a tier.

    A retired name reads as the tier it named, so a container recorded under
    it restarts instead of being recreated.
    """
    try:
        return cls(_RETIRED_TIER_NAMES.get(recorded, recorded))
    except ValueError:
        return None

OverrideRevocation(target, closed=(), kept=(), live=True) dataclass

What revoking a break-glass override closed, and when the revoke takes hold.

Returned by Shield.revoke_override. An operator told that a break-glass ended needs two things a bare success would hide. A running container drops the override at once, while a stopped one only stops opening it at its next start. And an address the override held can stay reachable above the security tier through another override that covers it — a range, say — which a revoke of this one leaves alone. So the addresses are split into the ones closed and the ones still open.

Attributes:

Name Type Description
target str

The domain, IP or CIDR whose override ended, as its tier entry recorded it.

closed tuple[str, ...]

The addresses the override held that no t10 element admits any more.

kept tuple[str, ...]

The addresses the override held that another override still in force admits above the security tier, because it covers them.

live bool

True when the container was running, so its ruleset no longer holds the override now; False when podman said no process runs for it — it is stopped, or gone — so the revoke applies from its next start.

target instance-attribute

closed = () class-attribute instance-attribute

kept = () class-attribute instance-attribute

live = True class-attribute instance-attribute

ShieldConfig(state_dir, mode=ShieldMode.HOOK, default_profiles=(), loopback_ports=(), audit_enabled=True, profiles_dir=None, runtime=ShieldRuntime.DEFAULT, dns_cache_dir=None, bypass_duration='5m', dnsmasq_path=None) dataclass

Per-container shield configuration.

The library is a pure function of its inputs. Given a ShieldConfig with state_dir, it writes to that directory and nowhere else. No env-var reading, no config-file parsing.

state_dir instance-attribute

mode = ShieldMode.HOOK class-attribute instance-attribute

default_profiles = () class-attribute instance-attribute

Profiles to compose when a call's profiles argument is None; empty composes no profile.

loopback_ports = () class-attribute instance-attribute

audit_enabled = True class-attribute instance-attribute

profiles_dir = None class-attribute instance-attribute

runtime = ShieldRuntime.DEFAULT class-attribute instance-attribute

dns_cache_dir = None class-attribute instance-attribute

Resolved-allowlist cache shared across containers.

The one deliberate exception to the state_dir-only rule: many tasks with the same allowlist share one resolve. None selects dns_cache_dir under the shield state root. Only the tiers that resolve at launch use it.

bypass_duration = '5m' class-attribute instance-attribute

How long the timed allow-all window stays open when a caller names no duration.

An nft timeout (30s, 5m, 2h). The kernel closes the window when the element expires, so nothing outlives the timeout it was opened with.

dnsmasq_path = None class-attribute instance-attribute

The dnsmasq binary to run; None finds one on the current host PATH.

Set it for a dnsmasq built outside the distro package, for example one built with nftset support in the operator's home.

ShieldMode

Bases: Enum

Operating mode for the shield firewall.

Currently only HOOK is supported. Future modes (e.g. bridge) will add members here.

HOOK = 'hook' class-attribute instance-attribute

ShieldReading(state, bypass_remaining=None) dataclass

One reading of a container's live ruleset: its posture and its timed window.

Both come out of a single nft -T list table — the listing that classifies the posture already holds the window set — so a caller that shows both (a status line, a task pane) pays for one netns entry, not two, and never pairs a posture with a window read a moment apart.

Attributes:

Name Type Description
state ShieldState

The posture the listing classifies as.

bypass_remaining int | None

Whole seconds left on the timed allow-all window (0 in its last second), or None when none is open. Only the UP chain reads the window set, so any other posture reads None.

state instance-attribute

bypass_remaining = None class-attribute instance-attribute

ShieldRuntime

Bases: Enum

Container runtime category — drives DNS-reachability assumptions.

crun / runc / youki. The container shares the netns,

so dnsmasq on 127.0.0.1 is reachable directly.

KRUN: libkrun microVM. The guest has its own loopback isolated from the netns, so dnsmasq must bind to a link-local address on netns lo that the guest can reach via passt.

DEFAULT = 'default' class-attribute instance-attribute

KRUN = 'krun' class-attribute instance-attribute

from_runtime_name(name) classmethod

Map a podman --runtime <name> string (or None) to the enum.

Centralises the wire-format vocabulary so callers don't repeat "krun" → KRUN mappings inline. Anything other than "krun" (including None and unknown runtime names) maps to DEFAULT — the loopback-shared-with-netns assumption holds for every runtime shield has been tested against besides krun.

Source code in src/terok_shield/config.py
@classmethod
def from_runtime_name(cls, name: str | None) -> ShieldRuntime:
    """Map a podman ``--runtime <name>`` string (or ``None``) to the enum.

    Centralises the wire-format vocabulary so callers don't repeat
    ``"krun" → KRUN`` mappings inline.  Anything other than
    ``"krun"`` (including ``None`` and unknown runtime names) maps
    to ``DEFAULT`` — the loopback-shared-with-netns assumption holds
    for every runtime shield has been tested against besides krun.
    """
    return cls.KRUN if name == "krun" else cls.DEFAULT

ShieldState

Bases: Enum

Per-container shield state, derived from the live nft ruleset.

QUARANTINE: Total network blackout — all traffic dropped, dropped traffic logged. UP: Normal enforcing mode (deny-all with allowlists). DOWN: Accept-by-default posture, private-range protection retained (RFC 1918 + RFC 4193). DISENGAGED: Accept-everything posture — no deny set, no private-range or hard-deny reject. OFFLINE: No ruleset found (container stopped or unshielded). ERROR: Ruleset present but unrecognised.

confirmed_posture, which a live allow and a revoke route on, keeps OFFLINE for a container podman says runs no process — stopped, or gone. A running container whose ruleset could not be read, or that carries none (unshielded), is ERROR there.

QUARANTINE = 'quarantine' class-attribute instance-attribute

UP = 'up' class-attribute instance-attribute

DOWN = 'down' class-attribute instance-attribute

DISENGAGED = 'disengaged' class-attribute instance-attribute

OFFLINE = 'offline' class-attribute instance-attribute

ERROR = 'error' class-attribute instance-attribute

RotationRisk(tier, allow=(), deny=(), override=()) dataclass

Policy names the container's DNS tier pins to the addresses they resolved to.

A name the shield resolves itself — once at launch, again at most hourly on a posture change — is enforced by those addresses only, and the provider behind it can move to another at any time. What that costs depends on the name's tier and on the posture, so the value keeps the three kinds apart and words them per posture (lines).

Computed on read from the bundle — the recorded DNS tier and the authored policy (recorded_rotation_risk) — so it never disagrees with what the container runs. IP and CIDR entries cannot rotate and stable local names (STABLE_LOCAL_NAMES) never do, so neither is ever listed.

Attributes:

Name Type Description
tier DnsTier

The DNS tier the container launched with.

allow tuple[str, ...]

Allowlisted names (t30, t40, runtime +) on a tier that resolves them once — every tier but dnsmasq-live. While the shield is UP, an address they rotate to is refused.

deny tuple[str, ...]

Denied names (t20, runtime -) on a tier that runs no dnsmasq (lookup, getent), where nothing sinkholes them: the deny holds their resolved addresses only, and an address a vault host rotates to escapes it. A security gap, worded louder.

override tuple[str, ...]

Break-glass names (t10), resolved once on every tier — the live tier included, since dnsmasq never populates the override set. An address they rotate to is not reached.

tier instance-attribute

allow = () class-attribute instance-attribute

deny = () class-attribute instance-attribute

override = () class-attribute instance-attribute

lines(posture=None)

The warning lines that matter in posture, worded for it.

posture None means a launch or restart: the container boots UP and may be lowered afterwards, so every line counts and the deny line names both ways out. In UP every line counts; in DOWN only the deny line — accept-by-default makes a pinned allow moot, while the security tier is still meant to hold; DISENGAGED enforces nothing, so nothing is worth a word.

Source code in src/terok_shield/state.py
def lines(self, posture: ShieldState | None = None) -> list[str]:
    """The warning lines that matter in *posture*, worded for it.

    *posture* ``None`` means a launch or restart: the container boots UP
    and may be lowered afterwards, so every line counts and the deny line
    names both ways out.  In UP every line counts; in DOWN only the deny
    line — accept-by-default makes a pinned allow moot, while the security
    tier is still meant to hold; DISENGAGED enforces nothing, so nothing
    is worth a word.
    """
    if posture is ShieldState.DOWN:
        wanted = [self._deny_line(posture)]
    elif posture in (None, ShieldState.UP):
        wanted = [self._allow_line(), self._override_line(), self._deny_line(posture)]
    else:
        wanted = []
    return [line for line in wanted if line]

SecurityTierRefusal(target, *, entry, address='')

Bases: RuntimeError

A grant the t20 security tier refuses: only a break-glass override reaches the target.

The security tier (policy/20-security-deny) holds what the orchestrator denies direct egress to — the vault-relayed provider hosts, above all. A live allow may lift the operator's own runtime deny, never this tier: the one way past it is the t10 override, authored with a reason and an expiry and sitting above the deny. Raised before anything changes, so a refused allow leaves the ruleset and the bundle as they were.

Attributes:

Name Type Description
target

The domain or IP the caller asked to allow.

entry

The security-tier name, address or range that refuses it.

address

The address the target shares with the tier, when the refusal is by address; empty when the name itself is refused.

Record what was refused and by which entry; the message names a shared address.

Source code in src/terok_shield/state.py
def __init__(self, target: str, *, entry: str, address: str = "") -> None:
    """Record what was refused and by which entry; the message names a shared address."""
    self.target = target
    self.entry = entry
    self.address = address
    super().__init__(f"{self.cause} — break-glass only")

target = target instance-attribute

entry = entry instance-attribute

address = address instance-attribute

cause property

One clause saying why the security tier refuses the target.

HarvestEntry(action, target, count, first_seen, last_seen, ports, addresses, tier=TIER_ALLOWLIST, remedies=(REMEDY_TASK, REMEDY_PROJECT, REMEDY_SET)) dataclass

One destination a task reached for, what the shield did, and what could change it.

action instance-attribute

What the shield did, as the reader recorded it: blocked — refused by the terminal rule; bypass — let through by the timed allow-all window; down — accepted only because the shield was down; security_deny — refused by the t20 deny set; private_range — refused by a range floor.

target instance-attribute

The domain the reader recovered, or the address when it had none.

This is what a promotion would name, which is why it is the grouping key: an allowlist entry for a rotating CDN is worth nothing as an IP.

count instance-attribute

Audit lines seen for this target.

A floor on attempts, not a connection count: the reader records one line per target per 30 s, so a tight retry loop and a single request can both land as one.

first_seen instance-attribute

last_seen instance-attribute

ports instance-attribute

Destination ports, ascending — a promotion candidate on 443 and one on 25 deserve different scrutiny.

addresses instance-attribute

Addresses seen behind target, in first-seen order; empty when the target is itself an address.

tier = TIER_ALLOWLIST class-attribute instance-attribute

The tier that stands between the task and the target: t40 when no refusing tier claims it (the allowlist just does not name it), t20_operator for the operator's own runtime deny, t20_security for the security tier (vault-relayed hosts above all), t20_private for a private range, t00 for the hard-deny floor. Read from the destination against the container's bundle, so a down line from a DISENGAGED shield lands in the tier that would refuse it once the shield is back up. Defaults to the ordinary t40 case.

remedies = (REMEDY_TASK, REMEDY_PROJECT, REMEDY_SET) class-attribute instance-attribute

What could let the task reach the target, in preference order: task / project (an allow), set (a curated or user set), override (break-glass, with a reason and an expiry), host_port (a +localhost:PORT grant for the host's own loopback — pasta's map or the slirp4netns gateway, both refused in t00, above every override). Empty for the rest of the hard-deny floor, which nothing reaches. Defaults to the remedies of the ordinary t40 case.

HarvestReport(entries=(), audit_enabled=True) dataclass

What harvest found, and whether it could find anything.

An empty harvest means two different things depending on audit_enabled: with audit on, the task reached for nothing it could not have; with audit off, the reader recorded nothing to begin with, so the emptiness says nothing about the task. A caller shows the second as such rather than as an all-clear.

Iterating the report yields its entries, and its length is theirs, so a caller that only ever listed the entries reads it unchanged.

entries = () class-attribute instance-attribute

The harvested entries, in review order.

audit_enabled = True class-attribute instance-attribute

Whether audit was on when the container was created — the flag its NFLOG reader honoured.

__iter__()

Yield the entries, in review order.

Source code in src/terok_shield/harvest.py
def __iter__(self) -> Iterator[HarvestEntry]:
    """Yield the entries, in review order."""
    return iter(self.entries)

__len__()

Return how many entries were harvested.

Source code in src/terok_shield/harvest.py
def __len__(self) -> int:
    """Return how many entries were harvested."""
    return len(self.entries)

HooksInstaller(target_dir=_default_target_dir()) dataclass

Persistent installation of terok-shield's OCI hook pair.

The createRuntime/poststop hook pair must persist across container restarts: podman ≥ 5.x drops per-container --hooks-dir on stop/start (containers/podman#17935), so global hooks are the only reliable activation path until that upstream regression is fixed.

Scripts, ballast, and JSON descriptors all land in target_dir (default: namespace_state_dir("shield") / "hooks"). containers.conf is patched to register that path so podman discovers the descriptors on the next container start.

Symmetric lifecycle: install writes, uninstall removes. Both are idempotent.

target_dir = field(default_factory=_default_target_dir) class-attribute instance-attribute

Directory the hook scripts, ballast, and JSON descriptors all live in.

check_setup(*, live=False)

Check Shield's receipt and hooks, optionally probing launch prerequisites.

Source code in src/terok_shield/hooks/install.py
def check_setup(self, *, live: bool = False) -> tuple[SetupCheck, ...]:
    """Check Shield's receipt and hooks, optionally probing launch prerequisites."""
    checks = [self._receipt().check(), *self._check_artifacts()]
    if live:
        checks.extend(self._check_tools())
    return tuple(checks)

install()

Install global standalone hooks after preflight; certify only verified work.

Source code in src/terok_shield/hooks/install.py
@setup_lock()
def install(self) -> None:
    """Install global standalone hooks after preflight; certify only verified work."""
    require_no_downgrade(self.check_setup())
    require_setup(self._check_tools())
    receipt = self._receipt()
    receipt.clear()
    install_reader_resource()
    self.target_dir.mkdir(parents=True, exist_ok=True)
    _write_role_files(self.target_dir)
    ensure_user_hooks_dir_configured(self.target_dir)
    require_setup(self._check_artifacts())
    receipt.write()

uninstall()

Remove every hook file install would write.

Idempotent — missing files are tolerated. containers.conf is left untouched: other terok packages may still register their own hooks_dir entries the operator wants to keep.

Source code in src/terok_shield/hooks/install.py
@setup_lock()
def uninstall(self) -> None:
    """Remove every hook file [`install`][terok_shield.hooks.install.HooksInstaller.install] would write.

    Idempotent — missing files are tolerated.  ``containers.conf``
    is left untouched: other terok packages may still register
    their own ``hooks_dir`` entries the operator wants to keep.
    """
    self._receipt().clear()
    for name in (*_SCRIPT_FILES, *_DESCRIPTOR_FILES):
        (self.target_dir / name).unlink(missing_ok=True)

is_installed()

True when target_dir carries the canonical createRuntime hook JSON.

Use check_setup for receipt, interpreter, and artifact validation.

Source code in src/terok_shield/hooks/install.py
def is_installed(self) -> bool:
    """True when ``target_dir`` carries the canonical createRuntime hook JSON.

    Use ``check_setup`` for receipt, interpreter, and artifact validation.
    """
    return (self.target_dir / _nft_hook_json("createRuntime")).is_file()

ExecError(cmd, rc, stderr)

Bases: Exception

Raised when a subprocess fails.

Store command details and format the error message.

Source code in src/terok_shield/run.py
def __init__(self, cmd: list[str], rc: int, stderr: str) -> None:
    """Store command details and format the error message."""
    self.cmd = cmd
    self.rc = rc
    self.stderr = stderr
    super().__init__(f"{cmd!r} failed (rc={rc}): {stderr.strip()}")

cmd = cmd instance-attribute

rc = rc instance-attribute

stderr = stderr instance-attribute

EnvironmentCheck(dns_tier='', ok=True, podman_version=(0,), hooks='not-installed', health='ok', issues=list(), needs_setup=False, setup_hint='') dataclass

Result of Shield.check_environment.

Machine-readable fields for programmatic consumers (terok TUI, scripts). Human-readable issues and setup_hint for CLI display.

Attributes:

Name Type Description
ok bool

True if no issues found.

podman_version tuple[int, ...]

Detected podman version tuple.

hooks str

Hook installation type (per-container, global, not-installed).

health str

Environment health (ok, setup-needed, stale-hooks).

dns_tier str

Active DNS resolution tier, a DnsTier value.

issues list[str]

List of human-readable issue descriptions.

needs_setup bool

True if one-time setup is required.

setup_hint str

Setup instructions (empty if not needed).

dns_tier = '' class-attribute instance-attribute

ok = True class-attribute instance-attribute

podman_version = (0,) class-attribute instance-attribute

hooks = 'not-installed' class-attribute instance-attribute

health = 'ok' class-attribute instance-attribute

issues = field(default_factory=list) class-attribute instance-attribute

needs_setup = False class-attribute instance-attribute

setup_hint = '' class-attribute instance-attribute

AllowResult(target, ips=(), live=True) dataclass

What Shield.allow granted, and when it takes effect.

A grant lands one of two ways, and a caller reporting it to an operator has to say which: a running container takes it live, a stopped one only at its next start.

Attributes:

Name Type Description
target str

The domain or IP the caller asked to allow.

ips tuple[str, ...]

The addresses the running ruleset admits now. Empty when the grant waits for the next start — or when every live attempt failed, which a caller should treat as nothing allowed.

live bool

True when the grant went to the container's running ruleset; False when podman said no process runs for the container — it is stopped, or gone — so the grant sits in its runtime overlay and applies at its next start.

target instance-attribute

ips = () class-attribute instance-attribute

live = True class-attribute instance-attribute

Shield(config, *, runner=None, audit=None, dns=None, profiles=None, ruleset=None, hub_events=None)

Public API facade — coordinates collaborators per container.

Delegates to HookMode for netns/nft operations, DnsResolver for name resolution, ProfileLoader for allowlists, RulesetBuilder for ruleset generation, and AuditLogger for the audit trail. All collaborators are injectable for testing.

Create the shield facade.

Parameters:

Name Type Description Default
config ShieldConfig

Shield configuration (must include state_dir).

required
runner CommandRunner | None

Command runner (default: SubprocessRunner).

None
audit AuditLogger | None

Audit logger (default: from config.state_dir).

None
dns DnsResolver | None

DNS resolver (default: from runner).

None
profiles ProfileLoader | None

Profile loader (default: from config.profiles_dir).

None
ruleset RulesetBuilder | None

Ruleset builder (default: from config loopback_ports).

None
hub_events HubEventEmitter | None

Best-effort emitter for shield_up / shield_down events bound for the terok-clearance hub (default: a fresh HubEventEmitter). The emitter routes each event to the supervisor's per-container socket using the container_id supplied on every up / down call. Pass a no-op stub in tests that should not touch the socket.

None
Source code in src/terok_shield/__init__.py
def __init__(
    self,
    config: ShieldConfig,
    *,
    runner: "CommandRunner | None" = None,
    audit: "AuditLogger | None" = None,
    dns: "DnsResolver | None" = None,
    profiles: "ProfileLoader | None" = None,
    ruleset: "RulesetBuilder | None" = None,
    hub_events: "HubEventEmitter | None" = None,
) -> None:
    """Create the shield facade.

    Args:
        config: Shield configuration (must include state_dir).
        runner: Command runner (default: ``SubprocessRunner``).
        audit: Audit logger (default: from config.state_dir).
        dns: DNS resolver (default: from runner).
        profiles: Profile loader (default: from config.profiles_dir).
        ruleset: Ruleset builder (default: from config loopback_ports).
        hub_events: Best-effort emitter for ``shield_up`` / ``shield_down``
            events bound for the terok-clearance hub (default: a fresh
            [`HubEventEmitter`][terok_shield._hub_events.HubEventEmitter]).  The
            emitter routes each event to the supervisor's
            per-container socket using the ``container_id`` supplied
            on every [`up`][terok_shield.Shield.up] /
            [`down`][terok_shield.Shield.down] call.  Pass a no-op
            stub in tests that should not touch the socket.
    """
    from ._hub_events import HubEventEmitter
    from .audit import AuditLogger
    from .dns.resolver import DnsResolver
    from .nft.rules import RulesetBuilder
    from .profiles import ProfileLoader
    from .run import SubprocessRunner

    self.config = config
    self.runner = runner or SubprocessRunner()
    self.audit = audit or AuditLogger(
        audit_path=StateBundle(config.state_dir).audit,
        enabled=config.audit_enabled,
    )
    self.dns = dns or DnsResolver(runner=self.runner, host_cache_dir=config.dns_cache_dir)
    self.profiles = profiles or ProfileLoader(
        user_dir=config.profiles_dir or Path("/nonexistent"),
    )
    self.ruleset = ruleset or RulesetBuilder(loopback_ports=config.loopback_ports)
    self.hub_events = hub_events or HubEventEmitter()
    self._mode = self._create_mode(config.mode)

config = config instance-attribute

runner = runner or SubprocessRunner() instance-attribute

audit = audit or AuditLogger(audit_path=StateBundle(config.state_dir).audit, enabled=config.audit_enabled) instance-attribute

dns = dns or DnsResolver(runner=self.runner, host_cache_dir=config.dns_cache_dir) instance-attribute

profiles = profiles or ProfileLoader(user_dir=config.profiles_dir or Path('/nonexistent')) instance-attribute

ruleset = ruleset or RulesetBuilder(loopback_ports=config.loopback_ports) instance-attribute

hub_events = hub_events or HubEventEmitter() instance-attribute

check_environment()

Check the podman environment for compatibility issues.

Proactive check for API consumers (e.g. terok). Returns an EnvironmentCheck with detected issues and setup hints. Does not raise — the caller decides how to handle issues.

Source code in src/terok_shield/__init__.py
def check_environment(self) -> EnvironmentCheck:
    """Check the podman environment for compatibility issues.

    Proactive check for API consumers (e.g. terok).  Returns an
    [`EnvironmentCheck`][terok_shield.EnvironmentCheck] with detected issues and setup hints.
    Does not raise — the caller decides how to handle issues.
    """
    from terok_util import SetupStatus

    from .dns import apparmor, dnsmasq
    from .hooks.install import HooksInstaller
    from .podman_info import parse_podman_info
    from .run import ShieldNeedsSetup

    output = self.runner.run(["podman", "info", "-f", "json"], check=False)
    info = parse_podman_info(output)
    issues: list[str] = []
    needs_setup = False
    setup_hint = ""
    health = "ok"

    try:
        dnsmasq_bin = dnsmasq.locate(self.config.dnsmasq_path, self.runner)
    except ShieldNeedsSetup as exc:
        issues.append(str(exc))
        dnsmasq_bin = ""
    tier, apparmor_blocked = apparmor.detect_dns_tier_under_apparmor(
        self.runner, self.config.state_dir, dnsmasq_bin
    )
    dns_tier = tier.value
    if apparmor_blocked:
        issues.append(
            f"AppArmor confines {dnsmasq_bin} from the shield state directory. "
            "Install the terok AppArmor profile addendum (docs/apparmor.md)."
        )
    if not tier.live:
        issues.append(f"DNS tier {tier.value}: {tier.hint}")

    checks = HooksInstaller().check_setup()
    failed = [check for check in checks if check.status != SetupStatus.READY]
    hooks = "global" if not failed else "not-installed"
    if failed:
        health = "setup-needed"
        needs_setup = True
        setup_hint = "Run 'terok-shield setup' to refresh global hooks."
        issues.extend(check.diagnostic for check in failed)

    return EnvironmentCheck(
        ok=not issues,
        podman_version=info.version,
        hooks=hooks,
        health=health,
        dns_tier=dns_tier,
        issues=issues,
        needs_setup=needs_setup,
        setup_hint=setup_hint,
    )

status()

Return current shield status information.

Source code in src/terok_shield/__init__.py
def status(self) -> dict:
    """Return current shield status information."""
    return {
        "mode": self.config.mode.value,
        "profiles": self.profiles.list_profiles(),
        "audit_enabled": self.config.audit_enabled,
    }

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

Prepare shield for container start. Returns extra podman args.

The four tier arguments are the orchestrator-generated policy tiers, which shield writes into the bundle so callers pass data and never touch the layout: security_deny → t20 (vault hosts denied direct), provider_allow → t30 (provider egress), project_allow → t40 (git remote + custom, merged with the composed profiles), override → t10 (break-glass allow above the deny; a CIDR is accepted but logged as a warning).

Source code in src/terok_shield/__init__.py
def pre_start(
    self,
    container: str,
    profiles: list[str] | None = None,
    *,
    security_deny: Sequence[str] = (),
    provider_allow: Sequence[str] = (),
    project_allow: Sequence[str] = (),
    override: Sequence[str] = (),
) -> list[str]:
    """Prepare shield for container start.  Returns extra podman args.

    The four tier arguments are the orchestrator-generated policy tiers,
    which shield writes into the bundle so callers pass data and never touch
    the layout: *security_deny* → t20 (vault hosts denied direct),
    *provider_allow* → t30 (provider egress), *project_allow* → t40 (git
    remote + custom, merged with the composed profiles), *override* → t10
    (break-glass allow above the deny; a CIDR is accepted but logged as a warning).
    """
    if profiles is None:
        profiles = list(self.config.default_profiles)
    result = self._mode.pre_start(
        container,
        profiles,
        security_deny=security_deny,
        provider_allow=provider_allow,
        project_allow=project_allow,
        override=override,
    )
    self.audit.log_event(container, "setup", detail=f"profiles={','.join(profiles)}")
    return result

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

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

Same tier arguments as pre_start, but for a container that already exists: rewrites the tiers and static-resolution caches and regenerates the pre-applied artifacts (ruleset.nft, dnsmasq config), so the next podman start enforces current policy instead of the bundle frozen at creation. Returns nothing — the container keeps its launch-time podman args.

Source code in src/terok_shield/__init__.py
def refresh(
    self,
    container: str,
    profiles: list[str] | None = None,
    *,
    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.

    Same tier arguments as [`pre_start`][terok_shield.Shield.pre_start],
    but for a container that already exists: rewrites the tiers and
    static-resolution caches and regenerates the pre-applied artifacts
    (``ruleset.nft``, dnsmasq config), so the next ``podman start``
    enforces *current* policy instead of the bundle frozen at creation.
    Returns nothing — the container keeps its launch-time podman args.
    """
    if profiles is None:
        profiles = list(self.config.default_profiles)
    self._mode.refresh(
        container,
        profiles,
        security_deny=security_deny,
        provider_allow=provider_allow,
        project_allow=project_allow,
        override=override,
    )
    self.audit.log_event(container, "refresh", detail=f"profiles={','.join(profiles)}")

allow(container, target)

Allow a domain or IP for container: live when it runs, from its next start when not.

Tier authority is settled before anything changes. A target the t20 security tier refuses — that very host, a name under one of its domains, or anything that resolves to one of its addresses — raises SecurityTierRefusal and nothing is granted, not even the addresses that were not shared: a security-tier host is reachable through a break-glass override only. The refusal lands in the audit trail as allow_refused.

A running container takes the grant live, address by address — an nft failure is logged and skipped — and a domain also joins its dnsmasq config, so the addresses the name rotates to follow. A stopped container gets the target recorded in its runtime overlay instead, for its next start to apply. The AllowResult says which of the two happened. A container counts as stopped only when podman says it has no process — or has no such container, which a recreate under the same name starts from the same bundle — never because its ruleset could not be read: a running one whose listing failed, or that carries no ruleset, takes the live path, where a failure is reported.

Raises:

Type Description
SecurityTierRefusal

When the security tier refuses the target.

ShieldNeedsSetup

A *. target on a tier that resolves names once.

RuntimeError

When neither the ruleset nor podman says whether the container runs — with nothing changed — or a stopped container's bundle was never prepared by a launch. Also, on a running container with the addresses already added, when its dnsmasq cannot reload to follow the name.

Source code in src/terok_shield/__init__.py
def allow(self, container: str, target: str) -> AllowResult:
    """Allow a domain or IP for *container*: live when it runs, from its next start when not.

    Tier authority is settled before anything changes.  A target the t20
    security tier refuses — that very host, a name under one of its
    domains, or anything that resolves to one of its addresses — raises
    [`SecurityTierRefusal`][terok_shield.state.SecurityTierRefusal] and
    nothing is granted, not even the addresses that were not shared: a
    security-tier host is reachable through a break-glass override only.
    The refusal lands in the audit trail as ``allow_refused``.

    A running container takes the grant live, address by address — an nft
    failure is logged and skipped — and a domain also joins its dnsmasq
    config, so the addresses the name rotates to follow.  A stopped
    container gets the target recorded in its runtime overlay instead, for
    its next start to apply.  The
    [`AllowResult`][terok_shield.AllowResult] says which of the two happened.
    A container counts as stopped only when podman says it has no process
    — or has no such container, which a recreate under the same name
    starts from the same bundle — never because its ruleset could not be
    read: a running one whose listing failed, or that carries no ruleset,
    takes the live path, where a failure is reported.

    Raises:
        SecurityTierRefusal: When the security tier refuses the target.
        ShieldNeedsSetup: A ``*.`` target on a tier that resolves names once.
        RuntimeError: When neither the ruleset nor podman says whether the
            container runs — with nothing changed — or a stopped
            container's bundle was never prepared by a launch.  Also, on
            a running container with the addresses already added, when
            its dnsmasq cannot reload to follow the name.
    """
    from .run import ExecError

    self._refuse_static_wildcard(target)
    is_domain = not _is_ip(target)
    ips = [target] if not is_domain else self.dns.resolve_domains([target])
    try:
        self._mode.check_security_tier(target, ips)
    except SecurityTierRefusal as refusal:
        self.audit.log_event(
            container, "allow_refused", dest=refusal.address or target, detail=str(refusal)
        )
        raise
    if self._mode.confirmed_posture(container) is ShieldState.OFFLINE:
        self._mode.allow_offline(target)
        self.audit.log_event(container, "allowed", dest=target, detail="at next start")
        return AllowResult(target=target, live=False)
    allowed: list[str] = []
    for ip in ips:
        try:
            self._mode.allow_ip(container, ip)
        except (ExecError, OSError) as exc:
            logger.warning("allow_ip failed for %s on %s: %s", ip, container, exc)
            continue
        allowed.append(ip)
        self.audit.log_event(container, "allowed", dest=ip, detail=f"target={target}")
    # Update dnsmasq config for domain targets (so future IP rotations are captured)
    if is_domain and allowed:
        self._mode.allow_domain(container, target)
    return AllowResult(target=target, ips=tuple(allowed))

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

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

The one way past the security tier on a live task — direct reach to a vault-relayed provider host, a LAN service in a private range — and deliberately narrow: target joins the t10 override set with a kernel timeout, so the kernel itself ends it when expires runs out (a date holds through that day, host local time). Agents keep using the vault for key relaying; the override only adds the direct route. The hard-deny floor (link-local, cloud metadata) is never overridden, nor is the host's own loopback, which a +localhost:PORT grant reaches.

A break-glass needs both a reason and an expiry, and the shield enforces both: an empty reason is refused like a passed expires. The reason is recorded on the tier entry and in the audit trail (override), which takes the grant the moment the kernel does — before the dnsmasq reload a domain needs, so a failed reload never leaves a grant that holds without a record. The tier entry is written only after that: the swap is computed from the tier as the grant will leave it, held in memory, so the tier never records a grant the kernel did not take. A grant and a revoke_override never interleave: each holds the container's t10 lock from its read of the tier through its swap, and a grant resolves its names before taking it, so a revoke never waits on a resolver.

The grant survives shield down/up, re-timed at each rebuild, until it expires or the next restart re-derives the tier from the orchestrator's policy — persist it there (shield.override) for it to outlive the task's run.

Returns:

Type Description
list[str]

The addresses opened: the target itself for an IP or a CIDR.

Raises:

Type Description
ValueError

For a target no override can carry, an expires that is no date or already passed, or an empty reason.

RuntimeError

When container has no running ruleset to take it, or the target resolves to no address — or, with the grant already holding in the kernel, when the tier or the override cache cannot record it (the message says what the next rebuild seeds in its place) or dnsmasq cannot reload to open the name.

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

    The one way past the security tier on a live task — direct reach to a
    vault-relayed provider host, a LAN service in a private range — and
    deliberately narrow: *target* joins the t10 override set with a kernel
    timeout, so the kernel itself ends it when *expires* runs out (a date
    holds through that day, host local time).  Agents keep using the
    vault for key relaying; the override only adds the direct route.  The
    hard-deny floor (link-local, cloud metadata) is never overridden, nor
    is the host's own loopback, which a ``+localhost:PORT`` grant reaches.

    A break-glass needs both a reason and an expiry, and the shield
    enforces both: an empty *reason* is refused like a passed *expires*.
    The reason is recorded on the tier entry and in the audit trail
    (``override``), which takes the grant the moment the kernel does —
    before the dnsmasq reload a domain needs, so a failed reload never
    leaves a grant that holds without a record.  The tier entry is
    written only after that: the swap is computed from the tier as the
    grant will leave it, held in memory, so the tier never records a
    grant the kernel did not take.  A grant and a
    [`revoke_override`][terok_shield.Shield.revoke_override] never
    interleave: each holds the container's t10 lock from its read of the
    tier through its swap, and a grant resolves its names before taking
    it, so a revoke never waits on a resolver.

    The grant survives ``shield down``/``up``, re-timed at each rebuild,
    until it expires or the next restart re-derives the tier from the
    orchestrator's policy — persist it there (``shield.override``) for it
    to outlive the task's run.

    Returns:
        The addresses opened: the target itself for an IP or a CIDR.

    Raises:
        ValueError: For a target no override can carry, an *expires*
            that is no date or already passed, or an empty *reason*.
        RuntimeError: When *container* has no running ruleset to take it,
            or the target resolves to no address — or, with the grant
            already holding in the kernel, when the tier or the override
            cache cannot record it (the message says what the next
            rebuild seeds in its place) or dnsmasq cannot reload to open
            the name.
    """
    when = expires.isoformat() if isinstance(expires, date) else expires
    return self._mode.override(container, target, when, reason=reason)

revoke_override(container, target)

End target's break-glass on container now, before its expiry runs out.

The way to close a door override opened, or one the orchestrator authored as shield.override. Only an override still in force can be revoked: a target with none, or one whose expiry already passed, raises instead of passing for a success.

The revoke is ordered to fail closed. The tier entry goes first, so no shield down/up re-opens the override, and the files a plain podman start replays are rewritten without it. Only then is it dropped from the running ruleset's t10 set, in one nft transaction that keeps every other override. A name's dnsmasq sinkhole punch-through closes too. The revoke is audited as override_revoked once nothing running holds the override. A stopped container's bundle is rewritten for its next start — and a container counts as stopped only when podman says it has no process, or has no such container, never because its ruleset could not be read.

A revoke stops new connections; connections already open keep running until they close, as they do when the override expires. It holds until the next restart re-derives the tier from the orchestrator's policy: an override authored there comes back unless it is removed there too.

Returns:

Type Description
OverrideRevocation
OverrideRevocation

naming the addresses closed, those another override still holds

OverrideRevocation

open, and whether the container was running.

Raises:

Type Description
ValueError

For text that is no domain, IP or CIDR, and for localhost, whose +localhost:PORT grants are no override.

RuntimeError

When target has no override in force, or neither the ruleset nor podman says whether the container runs — with nothing changed, in both cases. Also, with the record already gone, when nft cannot drop it from the running ruleset, or no dnsmasq reloads to sinkhole its name again — the message says which.

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

    The way to close a door [`override`][terok_shield.Shield.override]
    opened, or one the orchestrator authored as ``shield.override``.  Only
    an override still in force can be revoked: a target with none, or
    one whose expiry already passed, raises instead of passing for a
    success.

    The revoke is ordered to fail closed.  The tier entry goes first, so
    no ``shield down``/``up`` re-opens the override, and the files a
    plain ``podman start`` replays are rewritten without it.  Only then
    is it dropped from the running ruleset's t10 set, in one nft
    transaction that keeps every other override.  A name's dnsmasq
    sinkhole punch-through closes too.  The revoke is audited as
    ``override_revoked`` once nothing running holds the override.  A
    stopped container's bundle is rewritten for its next start — and a
    container counts as stopped only when podman says it has no process,
    or has no such container, never because its ruleset could not be read.

    A revoke stops new connections; connections already open keep running
    until they close, as they do when the override expires.  It holds
    until the next restart re-derives the tier from the orchestrator's
    policy: an override authored there comes back unless it is removed
    there too.

    Returns:
        An [`OverrideRevocation`][terok_shield.config.OverrideRevocation]
        naming the addresses closed, those 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``, whose ``+localhost:PORT`` grants are no override.
        RuntimeError: When *target* has no override in force, or neither
            the ruleset nor podman says whether the container runs —
            with nothing changed, in both cases.  Also, with the record
            already gone, when nft cannot drop it from the running
            ruleset, or no dnsmasq reloads to sinkhole its name again —
            the message says which.
    """
    return self._mode.revoke_override(container, target)

deny(container, target)

Live-deny a domain or IP for a running container.

Source code in src/terok_shield/__init__.py
def deny(self, container: str, target: str) -> list[str]:
    """Live-deny a domain or IP for a running container."""
    from .run import ExecError

    self._refuse_static_wildcard(target)
    is_domain = not _is_ip(target)
    ips = [target] if not is_domain else self.dns.resolve_domains([target])
    denied: list[str] = []
    for ip in ips:
        try:
            self._mode.deny_ip(container, ip)
        except (ExecError, OSError) as exc:
            logger.warning("deny_ip failed for %s on %s: %s", ip, container, exc)
            continue
        denied.append(ip)
        self.audit.log_event(container, "denied", dest=ip, detail=f"target={target}")
    # Remove domain from dnsmasq config (stops future auto-population)
    if is_domain and denied:
        self._mode.deny_domain(container, target)
    return denied

rules(container)

Return current nft rules for a container.

Source code in src/terok_shield/__init__.py
def rules(self, container: str) -> str:
    """Return current nft rules for a container."""
    return self._mode.list_rules(container)

down(container, container_id, *, disengaged=False)

Switch a running container to the DOWN posture.

container is the operator-facing podman name (audit log key); container_id is the full podman UUID — the routing key for the per-container hub socket the supervisor listens on. The caller knows both at every emit site, so neither carries a default.

With disengaged, the container takes the DISENGAGED posture instead: nothing is enforced — no deny set, no private-range or hard-deny reject — and every new connection is only logged.

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

    *container* is the operator-facing podman name (audit log key);
    *container_id* is the full podman UUID — the routing key for
    the per-container hub socket the supervisor listens on.  The
    caller knows both at every emit site, so neither carries a
    default.

    With *disengaged*, the container takes the DISENGAGED posture
    instead: nothing is enforced — no deny set, no private-range or
    hard-deny reject — and every new connection is only logged.
    """
    self._mode.shield_down(container, disengaged=disengaged)
    self.audit.log_event(
        container,
        "shield_down",
        detail="disengaged=True" if disengaged else None,
    )
    self.hub_events.shield_down(
        container,
        container_id,
        disengaged=disengaged,
        dossier=self._read_dossier(),
    )

quarantine(container)

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

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

up(container, container_id)

Restore normal deny-all mode for a running container.

container / container_id — see down.

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

    *container* / *container_id* — see
    [`down`][terok_shield.Shield.down].
    """
    self._mode.shield_up(container)
    self.audit.log_event(container, "shield_up")
    self.hub_events.shield_up(container, container_id, dossier=self._read_dossier())

harvest()

Summarise what this container reached for, from its audit log.

A read, not a policy change: the entries say what was refused, what the timed window let through and what the DOWN posture accepted only because the shield was down — each with the tier that stands in the way and the remedies that could lift it — and promoting any of them stays an explicit act elsewhere. The report also says whether audit was on for this container at all: with it off, the reader recorded nothing, and an empty harvest is no all-clear.

Raises:

Type Description
RuntimeError

The audit log exists but cannot be read.

Source code in src/terok_shield/__init__.py
def harvest(self) -> "HarvestReport":
    """Summarise what this container reached for, from its audit log.

    A read, not a policy change: the entries say what was refused, what
    the timed window let through and what the DOWN posture accepted only
    because the shield was down — each with the tier that stands in the
    way and the remedies that could lift it — and promoting any of them
    stays an explicit act elsewhere.  The report also says whether audit
    was on for this container at all: with it off, the reader recorded
    nothing, and an empty harvest is no all-clear.

    Raises:
        RuntimeError: The audit log exists but cannot be read.
    """
    from .harvest import harvest

    return harvest(self.config.state_dir)

bypass(container, duration=None)

Open the timed allow-all window and return the duration granted.

duration is an nft timeout; None takes bypass_duration from the config. The window lives in the kernel: it closes when the element expires, a rebuild or a restart closes it sooner, and nothing renews it. It accepts what the allowlist would refuse — never the security tier, the private ranges or the hard-deny floor, which all sit above it in the chain — and it opens in the UP posture only, the one chain that reads it.

Raises:

Type Description
RuntimeError

When the container's posture is not UP.

ValueError

When duration is not an nft timeout.

Source code in src/terok_shield/__init__.py
def bypass(self, container: str, duration: str | None = None) -> str:
    """Open the timed allow-all window and return the duration granted.

    *duration* is an nft timeout; ``None`` takes
    [`bypass_duration`][terok_shield.ShieldConfig.bypass_duration] from the
    config.  The window lives in the kernel: it closes when the element
    expires, a rebuild or a restart closes it sooner, and nothing renews it.
    It accepts what the allowlist would refuse — never the security tier,
    the private ranges or the hard-deny floor, which all sit above it in
    the chain — and it opens in the UP posture only, the one chain that
    reads it.

    Raises:
        RuntimeError: When the container's posture is not UP.
        ValueError: When *duration* is not an nft timeout.
    """
    duration = duration or self.config.bypass_duration
    self._mode.arm_window(container, duration)
    self.audit.log_event(container, "bypass_armed", detail=f"duration={duration}")
    return duration

bypass_off(container)

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

Source code in src/terok_shield/__init__.py
def bypass_off(self, container: str) -> None:
    """Close the timed allow-all window before its timeout runs out."""
    self._mode.disarm_window(container)
    self.audit.log_event(container, "bypass_disarmed")

bypass_remaining(container)

Whole seconds left on the timed allow-all window, or None when none is open.

The window half of inspect; a caller that also shows the posture reads both from that one listing instead.

Source code in src/terok_shield/__init__.py
def bypass_remaining(self, container: str) -> int | None:
    """Whole seconds left on the timed allow-all window, or ``None`` when none is open.

    The window half of [`inspect`][terok_shield.Shield.inspect]; a caller
    that also shows the posture reads both from that one listing instead.
    """
    return self.inspect(container).bypass_remaining

inspect(container)

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

One nft -T list table inside the container's netns answers both, so a surface showing both — a status line, a task pane — pays for one listing, and the two are never read a moment apart. The countdown is the kernel's own, in whole seconds, and reported only for UP: the one posture whose chain reads the window set.

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

    One ``nft -T list table`` inside the container's netns answers both, so
    a surface showing both — a status line, a task pane — pays for one
    listing, and the two are never read a moment apart.  The countdown is
    the kernel's own, in whole seconds, and reported only for UP: the one
    posture whose chain reads the window set.
    """
    return self._mode.inspect(container)

reset(container)

Forget DNS-learned allow state, keeping the authored policy seeds.

The live tier accumulates every IP the workload legitimately resolved; reset returns the allow sets to their just-launched contents (policy literals only) without touching the deny tier or the operator's runtime overlay.

Source code in src/terok_shield/__init__.py
def reset(self, container: str) -> None:
    """Forget DNS-learned allow state, keeping the authored policy seeds.

    The live tier accumulates every IP the workload legitimately
    resolved; ``reset`` returns the allow sets to their just-launched
    contents (policy literals only) without touching the deny tier or
    the operator's runtime overlay.
    """
    self._mode.shield_reset(container)
    self.audit.log_event(container, "shield_reset")

state(container)

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

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

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

Generate the ruleset that would be applied to a container.

profiles compose into the preview exactly as they would into a launch (None means the config's default_profiles, as in pre_start): their host-service grants join the preamble and their literal IPs seed the allow set. See HookMode.preview.

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

    *profiles* compose into the preview exactly as they would into a
    launch (``None`` means the config's ``default_profiles``, as in
    [`pre_start`][terok_shield.Shield.pre_start]): their host-service
    grants join the preamble and their literal IPs seed the allow set.
    See [`HookMode.preview`][terok_shield.hooks.mode.HookMode.preview].
    """
    if profiles is None:
        profiles = list(self.config.default_profiles)
    return self._mode.preview(down=down, disengaged=disengaged, profiles=profiles)

resolve(*, force=False)

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

Refreshes the caches pre_start and refresh fill — the allow cache on the tiers without DNS interception, the t10 override cache and the two t20 deny caches (the security tier's, the runtime overlay's) — without rewriting any tier. force re-resolves even when a cache is fresh. Returns the resolved allow IPs; the dnsmasq-live tier resolves per query, so it returns none.

Raises:

Type Description
RuntimeError

When pre_start never completed for this state dir.

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

    Refreshes the caches [`pre_start`][terok_shield.Shield.pre_start] and
    [`refresh`][terok_shield.Shield.refresh] fill — the allow cache on the
    tiers without DNS interception, the t10 override cache and the two t20
    deny caches (the security tier's, the runtime overlay's) — without
    rewriting any tier.  *force* re-resolves even
    when a cache is fresh.  Returns the resolved allow IPs; the
    ``dnsmasq-live`` tier resolves per query, so it returns none.

    Raises:
        RuntimeError: When pre_start never completed for this state dir.
    """
    return self._mode.resolve(force=force)

profiles_list()

List available profile names.

Source code in src/terok_shield/__init__.py
def profiles_list(self) -> list[str]:
    """List available profile names."""
    return self.profiles.list_profiles()

tail_log(n=50)

Yield the last n audit events.

Source code in src/terok_shield/__init__.py
def tail_log(self, n: int = 50) -> Iterator[dict]:
    """Yield the last *n* audit events."""
    return self.audit.tail_log(n)

compose_profiles(names)

Load and merge multiple profiles.

Source code in src/terok_shield/__init__.py
def compose_profiles(self, names: list[str]) -> list[str]:
    """Load and merge multiple profiles."""
    return self.profiles.compose_profiles(names)

validate_target(target)

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

The target grammar every policy line obeys, on its own: no action prefix, no :port, no %markers. Public so a caller that keeps host lists of its own (an orchestrator's named egress sets, a promotion target) validates them by the same rule the shield will apply, instead of a copy of the pattern that drifts. A caller that wants a narrower grammar — no wildcards, no CIDRs — layers its own check on top.

Raises:

Type Description
ValueError

When target is neither a domain, an IP literal, nor a CIDR.

Source code in src/terok_shield/policy.py
def validate_target(target: str) -> None:
    """Accept a domain (optionally ``*.``-prefixed), an IP literal, or a CIDR.

    The target grammar every policy line obeys, on its own: no action prefix,
    no ``:port``, no ``%markers``.  Public so a caller that keeps host lists
    of its own (an orchestrator's named egress sets, a promotion target)
    validates them by the same rule the shield will apply, instead of a copy
    of the pattern that drifts.  A caller that wants a narrower grammar — no
    wildcards, no CIDRs — layers its own check on top.

    Raises:
        ValueError: When *target* is neither a domain, an IP literal, nor a CIDR.
    """
    try:
        ipaddress.ip_network(target, strict=False)
        return
    except ValueError:
        pass
    if not _DOMAIN.fullmatch(target):
        raise ValueError(f"invalid target: {target!r}")

recorded_container_id(state_dir)

The short id of the container shielded from state_dir, as its OCI hook recorded it.

The 12-character short id is the one key every per-container surface shares: the NFLOG reader stamps it on each event, and the clearance hub keys its socket and its mute by it. A caller that holds only the state dir — a task's orchestrator — names the container exactly as those surfaces do, instead of by a podman name they have never seen. Thin public wrapper over StateBundle.read_container_id, like recorded_dns_tier; None until the container's first start.

Source code in src/terok_shield/state.py
def recorded_container_id(state_dir: Path) -> str | None:
    """The short id of the container shielded from *state_dir*, as its OCI hook recorded it.

    The 12-character short id is the one key every per-container surface
    shares: the NFLOG reader stamps it on each event, and the clearance hub
    keys its socket and its mute by it.  A caller that holds only the state
    dir — a task's orchestrator — names the container exactly as those
    surfaces do, instead of by a podman name they have never seen.  Thin
    public wrapper over
    [`StateBundle.read_container_id`][terok_shield.state.StateBundle.read_container_id],
    like [`recorded_dns_tier`][terok_shield.state.recorded_dns_tier];
    ``None`` until the container's first start.
    """
    return StateBundle(state_dir).read_container_id()

recorded_dns_tier(state_dir)

The DNS tier a shielded container launched with, read from state_dir.

Thin public wrapper over StateBundle.read_dns_tier so callers that only want the tier need not know the bundle layout.

Source code in src/terok_shield/state.py
def recorded_dns_tier(state_dir: Path) -> DnsTier | None:
    """The DNS tier a shielded container launched with, read from *state_dir*.

    Thin public wrapper over
    [`StateBundle.read_dns_tier`][terok_shield.state.StateBundle.read_dns_tier]
    so callers that only want the tier need not know the bundle layout.
    """
    return StateBundle(state_dir).read_dns_tier()

recorded_rotation_risk(state_dir)

What the DNS tier of the container shielded from state_dir pins to resolved addresses.

A file read — the recorded tier and the authored policy — computed on read, so an orchestrator shows the same warning the shield logs without a Shield or a container to ask: at launch, in a task pane, after a posture change. Thin public wrapper over StateBundle.read_rotation_risk, like recorded_dns_tier; None when nothing is at risk or nothing was recorded.

Source code in src/terok_shield/state.py
def recorded_rotation_risk(state_dir: Path) -> RotationRisk | None:
    """What the DNS tier of the container shielded from *state_dir* pins to resolved addresses.

    A file read — the recorded tier and the authored policy — computed on
    read, so an orchestrator shows the same warning the shield logs without
    a ``Shield`` or a container to ask: at launch, in a task pane, after a
    posture change.  Thin public wrapper over
    [`StateBundle.read_rotation_risk`][terok_shield.state.StateBundle.read_rotation_risk],
    like [`recorded_dns_tier`][terok_shield.state.recorded_dns_tier]; ``None``
    when nothing is at risk or nothing was recorded.
    """
    return StateBundle(state_dir).read_rotation_risk()

ensure_user_hooks_dir_configured(hooks_dir=None)

Ensure ~/.config/containers/containers.conf lists hooks_dir.

The canonical SSOT for the rootless OCI hooks directory across every terok package: shield calls it at setup time; other installers (e.g. terok-sandbox's per-container supervisor) call it before dropping their own descriptors so they don't have to re-implement the containers.conf patcher. Idempotent.

hooks_dir defaults to namespace_state_dir("shield") / "hooks" — shield's canonical install location under paths.root.

Creates the conf file if absent. Inserts hooks_dir into the existing [engine] section or appends a new section if none exists. Skips silently when hooks_dir is already listed. When a different hooks_dir is configured, appends ours to the list rather than failing — the operator owns containers.conf and may have intentionally pinned other locations.

Pure line-based editing — comments and formatting are preserved.

Source code in src/terok_shield/hooks/install.py
@setup_lock()
def ensure_user_hooks_dir_configured(hooks_dir: Path | None = None) -> None:
    """Ensure ``~/.config/containers/containers.conf`` lists *hooks_dir*.

    The canonical SSOT for the rootless OCI hooks directory across
    every terok package: shield calls it at ``setup`` time; other
    installers (e.g. terok-sandbox's per-container supervisor) call
    it before dropping their own descriptors so they don't have to
    re-implement the containers.conf patcher.  Idempotent.

    *hooks_dir* defaults to ``namespace_state_dir("shield") / "hooks"``
    — shield's canonical install location under ``paths.root``.

    Creates the conf file if absent.  Inserts ``hooks_dir`` into the
    existing ``[engine]`` section or appends a new section if none
    exists.  Skips silently when *hooks_dir* is already listed.  When
    a different ``hooks_dir`` is configured, appends ours to the list
    rather than failing — the operator owns containers.conf and may
    have intentionally pinned other locations.

    Pure line-based editing — comments and formatting are preserved.
    """
    if hooks_dir is None:
        hooks_dir = _default_target_dir()
    conf_path = _user_containers_conf()
    hooks_str = str(hooks_dir)
    hooks_line = f'hooks_dir = ["{hooks_str}"]'

    if not conf_path.is_file():
        conf_path.parent.mkdir(parents=True, exist_ok=True)
        conf_path.write_text(f"[engine]\n{hooks_line}\n")
        return

    existing = _parse_hooks_dir_from_conf(conf_path)
    if not existing:
        _insert_hooks_line(conf_path, hooks_line)
        return

    if hooks_str in existing or str(hooks_dir.expanduser()) in existing:
        return  # already configured
    _append_to_hooks_dir(conf_path, hooks_str)

user_hooks_dir_configured(hooks_dir)

Whether the user's containers.conf registers this package-owned hook directory.

Source code in src/terok_shield/hooks/install.py
def user_hooks_dir_configured(hooks_dir: Path) -> bool:
    """Whether the user's containers.conf registers this package-owned hook directory."""
    return str(hooks_dir.expanduser()) in {
        str(Path(entry).expanduser())
        for entry in _parse_hooks_dir_from_conf(_user_containers_conf())
    }

__getattr__(name)

Lazy import for re-exported core/support layer names.

Source code in src/terok_shield/__init__.py
def __getattr__(name: str) -> object:
    """Lazy import for re-exported core/support layer names."""
    if name in _LAZY_IMPORTS:
        mod_path, attr = _LAZY_IMPORTS[name]
        mod = _importlib.import_module(mod_path)
        value = getattr(mod, attr)
        globals()[name] = value  # cache for subsequent access
        return value
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")