# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-manifest-signature-re-binding-when-a-federated-peer-rotates-its-signing-key-mid-delegation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-manifest-signature-re-binding-when-a-federated-peer-rotates-its-signing-key-mid-delegation-chain.warrant.json
# Markdown SHA-256:   1e7b33624b7b570f6f1297255a5311ffbf2eb97358b894a3f6f21a169a2a5090
# Code AST SHA-256:   c6c454bb5e856885aeecba6a575e234752f63307dcb97fcbcb847a9c7a0ac14f
# Verified Classes:   ManifestRebindingError, Manifest, DelegationCredential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ManifestRebindingError(RuntimeError):
    """Raised when a manifest reference resolves to a document whose hash
    differs from the reference named in the delegation credential.

    This is the split-state signal: the peer rotated its signing key and
    re-published a manifest, but the upstream delegation credential still
    authorizes the prior artifact. Accepting the re-fetched manifest would
    launder unauthorized capability changes through a valid signature.
    """


@dataclass(frozen=True)
class Manifest:
    issuer_did: str
    key_id: str
    capabilities: frozenset
    raw: bytes

    def content_hash(self) -> str:
        return hashlib.sha256(self.raw).hexdigest()


@dataclass(frozen=True)
class DelegationCredential:
    issuer_did: str          # the org that granted the delegation (A)
    subject_did: str         # the delegate (B)
    manifest_ref: str        # SHA-256 of the manifest A authorized
    authorized_caps: frozenset


def verify_delegation(
    credential: DelegationCredential,
    presented_manifest: Manifest,
    signature_valid: bool,
    rotation_log_key_ids: frozenset,
) -> None:
    """Authorize a delegated agent. Raises on any boundary violation.

    Authentication (signature) and authorization (hash equality) are kept
    strictly separate. No fallback re-resolution is permitted.
    """
    if not signature_valid:
        raise ManifestRebindingError(
            f"signature invalid for {presented_manifest.issuer_did}"
        )

    # Rotation log must have announced this key; unannounced keys are
    # indistinguishable from attacker-controlled keys.
    if presented_manifest.key_id not in rotation_log_key_ids:
        raise ManifestRebindingError(
            f"key_id {presented_manifest.key_id} not in rotation log for "
            f"{presented_manifest.issuer_did}; cannot distinguish rotation "
            f"from key substitution"
        )

    actual_hash = presented_manifest.content_hash()

    # The decisive check. If the presented manifest is not byte-identical
    # to the artifact the credential authorizes, the delegation is void.
    # Do NOT resolve manifest_ref to "the current manifest."
    if actual_hash != credential.manifest_ref:
        raise ManifestRebindingError(
            f"manifest re-binding detected: credential authorizes "
            f"{credential.manifest_ref}, peer presented {actual_hash} "
            f"(key_id={presented_manifest.key_id}). Rotation requires "
            f"re-issuance of the delegation credential by "
            f"{credential.issuer_did}; refusing to authorize."
        )

    # Even with hash equality, capabilities must not exceed the grant.
    if not presented_manifest.capabilities.issubset(credential.authorized_caps):
        raise ManifestRebindingError(
            f"capability escalation: manifest declares "
            f"{sorted(presented_manifest.capabilities)} but credential "
            f"authorizes {sorted(credential.authorized_caps)}"
        )
