# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-attestation-replay-across-federation-trust-brokers-from-silently-widening-delegated-capability-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-attestation-replay-across-federation-trust-brokers-from-silently-widening-delegated-capability-scope.warrant.json
# Markdown SHA-256:   e156d7a0ff127f6fe1e7bba94f858bd2ca5f1f37e9ffb9470b9d7f1f134fc81a
# Code AST SHA-256:   7791bd76a329e13d922eb401bd8e87a9860b45787272d41777994ecfbae49f1e
# Verified Classes:   ScopeMonotonicityViolation, Attestation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeMonotonicityViolation(RuntimeError):
    """Raised when a consumer's effective scope exceeds the issuer's intended scope,
    or when a delegation hop's freshness outlives its root attestation."""


@dataclass(frozen=True)
class Attestation:
    issuer: str
    intended_scope: FrozenSet[str]  # canonical, issuer-signed leaves
    grammar_id: str
    aud: str
    exp: float
    nonce: str
    chain: tuple = ()  # parent attestations, root-first


def validate_delegation(
    presented: Attestation,
    consumer_grammar_id: str,
    consumer_effective_scope: FrozenSet[str],
    now: float,
) -> None:
    # 1. Grammar must match exactly; consumers may not translate-and-widen.
    if presented.grammar_id != consumer_grammar_id:
        raise ScopeMonotonicityViolation(
            f"grammar mismatch: issuer={presented.grammar_id!r} "
            f"consumer={consumer_grammar_id!r}; fail closed, do not translate"
        )

    # 2. Full chain must be present and re-validated, not just the leaf token.
    if not presented.chain:
        raise ScopeMonotonicityViolation(
            "delegation chain absent; cannot verify transitive freshness"
        )

    # 3. Freshness is transitive: no hop may outlive its root.
    root = presented.chain[0]
    for hop in (*presented.chain, presented):
        if hop.exp > root.exp:
            raise ScopeMonotonicityViolation(
                f"hop exp {hop.exp} exceeds root exp {root.exp}; "
                "replayed token can survive root revocation"
            )
        if hop.exp < now:
            raise ScopeMonotonicityViolation(f"expired hop from {hop.issuer}")

    # 4. Effective scope must be a subset of issuer-intended scope.
    widened = consumer_effective_scope - presented.intended_scope
    if widened:
        raise ScopeMonotonicityViolation(
            f"scope widening at {presented.aud}: {sorted(widened)} "
            f"not in issuer intent {sorted(presented.intended_scope)}"
        )
