# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-transitive-trust-escalation-across-federated-agent-brokers-when-capability-grants-are-re-signed-at-each-administrative-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-transitive-trust-escalation-across-federated-agent-brokers-when-capability-grants-are-re-signed-at-each-administrative-hop.warrant.json
# Markdown SHA-256:   e22c6c24576af03ca7ddfd6de629692bd301dad30c7ec35ae16afe25af66becb
# Code AST SHA-256:   c858e1150544c809da7a8af67efb984e1de9d08cd36387bef11d25a57fc5955f
# Verified Classes:   TransitiveTrustEscalation, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TransitiveTrustEscalation(RuntimeError):
    """Raised when a re-signed federated warrant cannot be proven a subset of its parent grant."""
    pass


@dataclass(frozen=True)
class Warrant:
    subject: str
    capability: str          # e.g. "read:dataset/telemetry" or "read:dataset/*"
    expires_at: int
    issuer: str
    parent_hash: Optional[str]   # hash of the upstream warrant this attenuates
    revocation_ptr: Optional[str]


def _is_subset(child_cap: str, parent_cap: str) -> bool:
    # A wildcard is a superset, never a subset, of a specific grant.
    if child_cap == parent_cap:
        return True
    if child_cap.endswith("/*"):
        return False
    if parent_cap.endswith("/*"):
        return child_cap.startswith(parent_cap[:-1])
    return False


def verify_federated_warrant(
    presented: Warrant,
    chain: list[Warrant],
    now: int,
) -> None:
    """
    Verify a warrant re-signed across administrative hops.
    `chain` is ordered originator -> ... -> presented issuer.
    Raises TransitiveTrustEscalation on any monotonicity violation.
    """
    if not chain:
        raise TransitiveTrustEscalation("empty attenuation chain: cannot verify subset invariant")

    origin = chain[0]
    if presented.expires_at > origin.expires_at:
        raise TransitiveTrustEscalation(
            f"expiry widened: presented {presented.expires_at} > origin {origin.expires_at}"
        )
    if presented.revocation_ptr != origin.revocation_ptr:
        raise TransitiveTrustEscalation(
            "revocation pointer does not transitively reference originator; "
            "originator revocation will not propagate"
        )

    prev = origin
    for hop in chain[1:] + [presented]:
        if not _is_subset(hop.capability, prev.capability):
            raise TransitiveTrustEscalation(
                f"capability widened at hop issued by {hop.issuer}: "
                f"{hop.capability!r} is not a subset of {prev.capability!r}"
            )
        if hop.expires_at > prev.expires_at:
            raise TransitiveTrustEscalation(
                f"expiry widened at hop issued by {hop.issuer}"
            )
        prev = hop

    if presented.expires_at <= now:
        raise TransitiveTrustEscalation("presented warrant already expired")


# Reproduces the observed trace: A grants telemetry, B re-signs a wildcard.
w_a = Warrant("alpha", "read:dataset/telemetry", 1000, "org-a", None, "rev://org-a/42")
w_b = Warrant("alpha", "read:dataset/*", 2000, "org-b", "hash(w_a)", "rev://org-a/42")

verify_federated_warrant(w_b, [w_a], now=500)
# -> TransitiveTrustEscalation: capability widened at hop issued by org-b:
#    'read:dataset/*' is not a subset of 'read:dataset/telemetry'
