# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fail-aaif-scoped-credential-exchange-when-delegated-capability-tokens-outlive-their-warrant-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fail-aaif-scoped-credential-exchange-when-delegated-capability-tokens-outlive-their-warrant-chain.warrant.json
# Markdown SHA-256:   c8294d029a1f510147bff5f0b1df3a0150e7aeb037d65040250317ab80647a45
# Code AST SHA-256:   e4b8ee47d7bc9fa5c2facefe4d5336132f5e61582c9f86f3b894e2fd1b6422f1
# Verified Classes:   WarrantChainBroken, StaleChainResolution, Warrant, CapabilityToken, WarrantRegistry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class WarrantChainBroken(RuntimeError):
    """Raised when a capability token's grounding warrant is no longer the
    registry head at redemption time. The token is cryptographically valid
    but no longer authorized; the caller must fail closed."""


class StaleChainResolution(RuntimeError):
    """Raised when the redeeming instance has not re-resolved the warrant
    chain within the amendment-propagation bound and cannot prove freshness."""


@dataclass
class Warrant:
    warrant_id: str
    version: int
    claims: dict
    revoked: bool = False

    def digest(self) -> str:
        payload = f"{self.warrant_id}:{self.version}:{sorted(self.claims.items())}"
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class CapabilityToken:
    token_id: str
    warrant_id: str
    warrant_version_at_mint: int
    warrant_digest_at_mint: str
    scope: str
    resource: str
    mint_time: float
    ttl: float


@dataclass
class WarrantRegistry:
    heads: dict = field(default_factory=dict)  # warrant_id -> current Warrant

    def head(self, warrant_id: str) -> Warrant:
        return self.heads[warrant_id]

    def amend(self, warrant_id: str, new_claims: dict) -> None:
        old = self.heads[warrant_id]
        self.heads[warrant_id] = Warrant(
            warrant_id=warrant_id,
            version=old.version + 1,
            claims=new_claims,
        )


AMENDMENT_PROPAGATION_BOUND = 45.0  # seconds, p99 registry replication + skew


def redeem(
    token: CapabilityToken,
    requested_scope: str,
    requested_resource: str,
    registry: WarrantRegistry,
    last_chain_resolution: float,
    now: float | None = None,
) -> bool:
    now = now if now is not None else time.time()

    # TTL is necessary but never sufficient.
    if now > token.mint_time + token.ttl:
        raise WarrantChainBroken(
            f"token {token.token_id} expired at {token.mint_time + token.ttl:.0f}"
        )

    # Scope match is necessary but never sufficient.
    if token.scope != requested_scope or token.resource != requested_resource:
        raise WarrantChainBroken(
            f"token {token.token_id} scope {token.scope}:{token.resource} "
            f"does not cover {requested_scope}:{requested_resource}"
        )

    # Freshness gate: refuse to trust a chain we have not re-resolved recently.
    if now - last_chain_resolution > AMENDMENT_PROPAGATION_BOUND:
        raise StaleChainResolution(
            f"chain last resolved {now - last_chain_resolution:.0f}s ago, "
            f"bound is {AMENDMENT_PROPAGATION_BOUND:.0f}s; fail closed"
        )

    head = registry.head(token.warrant_id)

    # The load-bearing check: digest against LIVE HEAD, not mint-time snapshot.
    if head.digest() != token.warrant_digest_at_mint:
        raise WarrantChainBroken(
            f"token {token.token_id} grounded in {token.warrant_id} v"
            f"{token.warrant_version_at_mint} (digest {token.warrant_digest_at_mint[:12]}), "
            f"but registry head is v{head.version} (digest {head.digest()[:12]}); "
            f"warrant chain diverged — token is valid but unauthorized"
        )

    if head.revoked:
        raise WarrantChainBroken(
            f"warrant {token.warrant_id} v{head.version} is revoked"
        )

    return True


def demo() -> None:
    reg = WarrantRegistry()
    w1 = Warrant("W1", 1, {"scope": "remediate:restart_service", "service": "payments-*"})
    reg.heads["W1"] = w1

    mint = time.time()
    tok = CapabilityToken(
        token_id="T1",
        warrant_id="W1",
        warrant_version_at_mint=1,
        warrant_digest_at_mint=w1.digest(),
        scope="remediate:restart_service",
        resource="payments-api",
        mint_time=mint,
        ttl=1500.0,
    )

    # Principal narrows the warrant at t+360s.
    reg.amend("W1", {"scope": "remediate:restart_service", "service": "payments-api-readonly"})

    # A2 redeems at t+540s with a fresh chain resolution. Must fail closed.
    redeem(
        tok,
        requested_scope="remediate:restart_service",
        requested_resource="payments-api",
        registry=reg,
        last_chain_resolution=mint + 540.0,
        now=mint + 540.0,
    )


if __name__ == "__main__":
    demo()
