# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-peer-s-trust-anchor-re-issuance-after-policy-mediation-rewrites-its-capability-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-peer-s-trust-anchor-re-issuance-after-policy-mediation-rewrites-its-capability-scope.warrant.json
# Markdown SHA-256:   9762c85391b18c7b15c7de70415c6beb7a7bfc4dde1039c5edda62c5fc39cf5c
# Code AST SHA-256:   e0ac27f733562dbe23944972de038a5b42c159e9dc9ec52655a048d81abc41c0
# Verified Classes:   FederatedWarrantRejected, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class FederatedWarrantRejected(RuntimeError):
    """Raised when a re-issued trust anchor cannot prove scope-narrowing provenance."""
    pass


@dataclass(frozen=True)
class Warrant:
    subject: str
    issuer: str
    audience: str
    signed_caps: frozenset
    derived_from: str | None  # hash of the presented warrant, None for root warrants


def _hash(w: Warrant) -> str:
    payload = f"{w.subject}|{w.issuer}|{w.audience}|{sorted(w.signed_caps)}"
    return hashlib.sha256(payload.encode()).hexdigest()


def admit_federated_peer(
    presented: Warrant,
    reissued: Warrant,
    mediated_caps: frozenset,
    trusted_root: str,
) -> None:
    """
    Enforce the narrowing + provenance invariants before honoring a peer.
    mediated_caps is what the policy engine *decided*; signed_caps is what
    the gateway *asserted*. They must agree, and the chain must link.
    """
    if reissued.issuer != trusted_root:
        raise FederatedWarrantRejected(
            f"re-issued warrant issuer {reissued.issuer!r} != trusted root {trusted_root!r}"
        )

    if reissued.derived_from is None:
        raise FederatedWarrantRejected(
            "re-issued warrant carries no derived_from provenance; "
            "cannot distinguish mediation from arbitrary root-signed grant"
        )

    if reissued.derived_from != _hash(presented):
        raise FederatedWarrantRejected(
            "derived_from does not match presented warrant hash; "
            "chain linkage broken or warrant substituted"
        )

    # Narrowing invariant: the signed assertion must not exceed the mediated decision.
    if not reissued.signed_caps.issubset(mediated_caps):
        widened = reissued.signed_caps - mediated_caps
        raise FederatedWarrantRejected(
            f"scope widening across mediation: signed caps {sorted(widened)} "
            f"exceed mediated caps {sorted(mediated_caps)}"
        )

    # A derived warrant may not carry more authority than the peer proved.
    if not reissued.signed_caps.issubset(presented.signed_caps):
        raise FederatedWarrantRejected(
            "re-issued warrant asserts capabilities the peer never presented"
        )
