# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-allowlist-drift-when-a-tool-call-s-semantic-class-diverges-from-its-transport-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-allowlist-drift-when-a-tool-call-s-semantic-class-diverges-from-its-transport-identity.warrant.json
# Markdown SHA-256:   0e96d84c0334864fa02e4e65676949e2e10ea4dd4c6a649a87259b6d66a64196
# Code AST SHA-256:   3632a49fd2707327afc0ee4d463a312eb03a5d15ced1107c8186bb4357d86721
# Verified Classes:   CapabilityDriftError, AllowlistGrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CapabilityDriftError(RuntimeError):
    """Raised when a call's effective capability exceeds its allowlist grant."""
    pass


class AllowlistGrant:
    def __init__(self, tool_name: str, granted_caps: frozenset[str], pinned_digest: str):
        self.tool_name = tool_name
        self.granted_caps = granted_caps
        self.pinned_digest = pinned_digest


def _attested_footprint(digest: str) -> frozenset[str]:
    # In production this reads a signed attestation produced at build time
    # (static analysis + syscall trace). Stubbed here for illustration.
    return frozenset({"network:read", "network:connect"})


def _effective_capability(tool_name: str, args: dict, footprint: frozenset[str]) -> frozenset[str]:
    caps = set(footprint)
    if "redirect" in args and args["redirect"]:
        # Following a redirect opens a second egress path the proxy won't see.
        caps.add("network:connect")
    if "include" in args and args["include"]:
        caps.add("filesystem:read:arbitrary")
    return frozenset(caps)


def enforce(grants: dict[str, AllowlistGrant], tool_name: str, args: dict) -> None:
    grant = grants.get(tool_name)
    if grant is None:
        raise CapabilityDriftError(f"tool {tool_name!r} is not in the allowlist")

    footprint = _attested_footprint(grant.pinned_digest)
    effective = _effective_capability(tool_name, args, footprint)

    excess = effective - grant.granted_caps
    if excess:
        raise CapabilityDriftError(
            f"tool {tool_name!r} (digest {grant.pinned_digest}) would exercise "
            f"{sorted(excess)} beyond grant {sorted(grant.granted_caps)}"
        )


if __name__ == "__main__":
    grants = {
        "fetch_url": AllowlistGrant(
            tool_name="fetch_url",
            granted_caps=frozenset({"network:read"}),
            pinned_digest="sha256:aa11...",
        )
    }
    try:
        enforce(grants, "fetch_url", {"url": "https://approved.example", "redirect": "http://evil.example"})
    except CapabilityDriftError as e:
        print(f"refused before execution: {e}")
