# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-least-privilege-tool-grant-was-silently-widened-by-a-mid-session-policy-refresh-the-grant-rehydration-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-least-privilege-tool-grant-was-silently-widened-by-a-mid-session-policy-refresh-the-grant-rehydration-failure.warrant.json
# Markdown SHA-256:   b65bcadb24c208c58ae401abc7cf71b92931b42be5f7e3e3f64ae9589c5cd228
# Code AST SHA-256:   5ebe8b35bbfa6d61083e084ef98a9249d28aabb125c52c6356afae94042abfd0
# Verified Classes:   StaleGrantError, ToolHandle, EffectiveGrant, PolicyDecisionPoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleGrantError(RuntimeError):
    """Raised when a tool handle's grant epoch diverges from the live policy epoch."""


@dataclass(frozen=True)
class ToolHandle:
    tool: str
    grant_epoch: str          # epoch under which this handle was minted
    capability_token: str


@dataclass(frozen=True)
class EffectiveGrant:
    epoch: str
    allowed_tools: frozenset
    allowed_paths: tuple


class PolicyDecisionPoint:
    """Live PDP whose grant is a function of mutable identity attributes."""

    def __init__(self, identity: str, grant: EffectiveGrant):
        self.identity = identity
        self._grant = grant

    def current_epoch(self) -> str:
        return self._grant.epoch

    def effective_grant(self) -> EffectiveGrant:
        return self._grant

    def refresh(self, new_grant: EffectiveGrant) -> None:
        # Attribute-driven refresh: grant changes, live handles do NOT re-mint.
        self._grant = new_grant

    def authorize(self, handle: ToolHandle, path: str) -> bool:
        # Enforcement keys on identity against the CURRENT grant, ignoring handle epoch.
        g = self._grant
        return handle.tool in g.allowed_tools and any(
            path.startswith(p) for p in g.allowed_paths
        )


def dispatch(pdp: PolicyDecisionPoint, handle: ToolHandle, path: str) -> str:
    """Grant-epoch fence: refuse to dispatch on a stale handle before authorizing."""
    live_epoch = pdp.current_epoch()
    if handle.grant_epoch != live_epoch:
        raise StaleGrantError(
            f"handle for tool={handle.tool!r} minted under epoch "
            f"{handle.grant_epoch!r} but live policy epoch is {live_epoch!r}; "
            f"re-mint handles and re-validate cached path assumptions before retrying"
        )
    if not pdp.authorize(handle, path):
        raise PermissionError(f"denied: {handle.tool} -> {path}")
    return f"read {path}"


# --- trace of the observed failure ---
pdp = PolicyDecisionPoint(
    identity="svc-researcher@run-8821",
    grant=EffectiveGrant(
        epoch="G0",
        allowed_tools=frozenset({"read_file"}),
        allowed_paths=("docs/",),
    ),
)

handle = ToolHandle(tool="read_file", grant_epoch="G0", capability_token="tok-G0")

# Mid-session attribute-driven refresh silently widens the grant.
pdp.refresh(
    EffectiveGrant(
        epoch="G1",
        allowed_tools=frozenset({"read_file", "http_fetch"}),
        allowed_paths=("docs/", "infra/"),
    )
)

# Without the fence this call succeeds (PDP authorizes under G1) and the
# reasoning layer never learns its scope moved.
try:
    dispatch(pdp, handle, "infra/secrets/terraform.tfstate")
except StaleGrantError as e:
    print(f"fence caught silent widening: {e}")
    # Correct recovery: re-mint under G1, re-read effective grant, re-plan.
    handle = ToolHandle(tool="read_file", grant_epoch=pdp.current_epoch(), capability_token="tok-G1")
    print(dispatch(pdp, handle, "infra/secrets/terraform.tfstate"))
