# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-capability-token-whose-attenuation-chain-silently-widens-at-the-expiry-rebinding-seam.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-capability-token-whose-attenuation-chain-silently-widens-at-the-expiry-rebinding-seam.warrant.json
# Markdown SHA-256:   16776a8f27de3ea8aa97bfb977703871af12964cd988fbc016821873f6531503
# Code AST SHA-256:   ac9dfcc82a92b4f89f7e01e77a8cbe1ffcc6144d9fe8355d14f6137ee8fa90b8
# Verified Classes:   AttenuationWideningError, Token
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional

TEMPORAL_CLAIMS = frozenset({"iat", "exp", "nbf", "sig"})


class AttenuationWideningError(RuntimeError):
    """Raised when a token's effective scope exceeds its parent's evaluated scope,
    or when a rebind mutates non-temporal claims (re-parenting / ambient merge)."""
    pass


@dataclass
class Token:
    claims: dict
    parent_hash: Optional[str]
    issuer: str
    holder: str
    digest: str = field(init=False)

    def __post_init__(self) -> None:
        body = repr(sorted(self.claims.items())) + str(self.parent_hash) + self.issuer + self.holder
        self.digest = hashlib.sha256(body.encode()).hexdigest()


def _scope_subset(child: dict, parent: dict) -> bool:
    # tools must be a subset; budget must be <= parent's
    if not set(child.get("tools", [])) <= set(parent.get("tools", [])):
        return False
    if child.get("budget", 0) > parent.get("budget", 0):
        return False
    return True


def verify_rebind(prior: Token, candidate: Token, parent: Token, *, is_refresh_claim: bool) -> None:
    """Enforce the rebind-seam invariant.

    is_refresh_claim: the caller asserts this is a pure refresh (same issuer/holder/parent).
    If True, only temporal claims may differ. If False, full attenuation is re-checked
    against the *evaluated* parent scope, and re-parenting must be authorized.
    """
    if is_refresh_claim:
        if candidate.parent_hash != prior.parent_hash:
            raise AttenuationWideningError(
                f"refresh re-parented token: {prior.parent_hash} -> {candidate.parent_hash}"
            )
        if candidate.issuer != prior.issuer or candidate.holder != prior.holder:
            raise AttenuationWideningError("refresh changed issuer/holder identity")
        changed = {
            k for k in set(prior.claims) | set(candidate.claims)
            if prior.claims.get(k) != candidate.claims.get(k)
        }
        non_temporal = changed - TEMPORAL_CLAIMS
        if non_temporal:
            raise AttenuationWideningError(
                f"refresh mutated non-temporal claims: {sorted(non_temporal)}"
            )
        return

    # Issuance path: candidate must be a genuine attenuation of the *evaluated* parent.
    if candidate.parent_hash != parent.digest:
        raise AttenuationWideningError(
            "issuance parent_hash does not match the evaluated parent token"
        )
    if not _scope_subset(candidate.claims, parent.claims):
        raise AttenuationWideningError(
            f"effective scope widened: child={candidate.claims} parent={parent.claims}"
        )


def replay_against_issuance_scope(chain: list[Token], leaf: Token) -> None:
    """Independent auditor path: walk the chain and confirm monotone attenuation
    at every link, using each link's claims as-issued (not as-runtime-merged)."""
    by_digest = {t.digest: t for t in chain}
    cur = leaf
    while cur.parent_hash is not None:
        parent = by_digest.get(cur.parent_hash)
        if parent is None:
            raise AttenuationWideningError(
                f"broken chain: parent {cur.parent_hash} not in replay set"
            )
        if not _scope_subset(cur.claims, parent.claims):
            raise AttenuationWideningError(
                f"replay found widening at link {cur.digest[:8]} -> {parent.digest[:8]}"
            )
        cur = parent
