# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-deny-a-tool-invocation-that-is-authorized-by-its-static-capability-grant-but-violates-the-runtime-policy-s-effe.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-deny-a-tool-invocation-that-is-authorized-by-its-static-capability-grant-but-violates-the-runtime-policy-s-effe.warrant.json
# Markdown SHA-256:   4e25ffbdf14025face4985f8414bb96d23152c08748be9056dc405e5be048dda
# Code AST SHA-256:   1277bd031c1a8f46b850ca4aa5af23c26df0d94e185eee7c9de95036f55319d6
# Verified Classes:   PolicyBypassError, Invocation, CanonicalInvocation, _Grant, _Policy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import ipaddress
import posixpath
from dataclasses import dataclass
from typing import Optional


class PolicyBypassError(RuntimeError):
    """Raised when an invocation would execute without a full policy evaluation."""
    pass


@dataclass(frozen=True)
class Invocation:
    principal: str
    verb: str
    resource: str          # raw, as declared by the agent
    port: Optional[int] = None


@dataclass(frozen=True)
class CanonicalInvocation:
    principal: str
    verb: str
    resource: str          # canonicalized: symlinks collapsed, host resolved, identifiers qualified
    port: Optional[int]
    resolved_addr: Optional[ipaddress.IPv4Address] = None


def canonicalize(inv: Invocation, resolver) -> CanonicalInvocation:
    """Resolve the invocation into the domain both grant and policy must agree on."""
    if inv.verb.startswith("fs."):
        canon = posixpath.normpath(inv.resource)  # collapses .. and .
        return CanonicalInvocation(inv.principal, inv.verb, canon, inv.port)
    if inv.verb == "net.fetch":
        addr = resolver(inv.resource)
        return CanonicalInvocation(inv.principal, inv.verb, inv.resource, inv.port, addr)
    return CanonicalInvocation(inv.principal, inv.verb, inv.resource, inv.port)


def enforce(inv: Invocation, grant, policy, resolver) -> CanonicalInvocation:
    canon = canonicalize(inv, resolver)

    # Grant is necessary.
    if not grant.admits(canon.principal, canon.verb, canon.resource):
        raise PolicyBypassError(f"grant does not admit {canon.verb} on {canon.resource}")

    # Policy is necessary and MUST be evaluated even when the grant admits.
    # Skipping this on a grant hit is the boundary defect.
    decision = policy.evaluate(canon)
    if decision != "PERMIT":
        raise PolicyBypassError(
            f"grant admitted but policy denied: {canon.verb} {canon.resource} "
            f"(resolved={canon.resolved_addr})"
        )

    # Execute against the canonical value, never the raw one.
    return canon


def _demo():
    class _Grant:
        def admits(self, principal, verb, resource):
            return verb == "net.fetch" and resource.endswith(".internal.example")

    class _Policy:
        def evaluate(self, canon):
            addr = canon.resolved_addr
            if addr is not None and not addr.is_private:
                return "DENY"   # link-local 169.254.169.254 is not private
            return "PERMIT"

    inv = Invocation("agent-7", "net.fetch", "metadata.internal.example", 80)
    resolver = lambda host: ipaddress.IPv4Address("169.254.169.254")

    # Grant admits the host, so a naive fast-path would execute. Enforce denies.
    try:
        enforce(inv, _Grant(), _Policy(), resolver)
    except PolicyBypassError as e:
        print(f"correctly blocked: {e}")
        return
    raise PolicyBypassError("invocation executed despite policy denial — boundary violated")


if __name__ == "__main__":
    _demo()
