# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-bootstraps-federation-trust-from-an-attestation-that-was-valid-under-a-policy-digest-the-peer-has-since-rotated.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-bootstraps-federation-trust-from-an-attestation-that-was-valid-under-a-policy-digest-the-peer-has-since-rotated.warrant.json
# Markdown SHA-256:   fe819e61e54395cd7754857e219cb3b00a9460531e6ad9bc4b4505a0bf02ae51
# Code AST SHA-256:   746effefd8cd5bf53bb03ae7c26719ca480eb1b7baf7498d5f5afbe5915808fb
# Verified Classes:   FederationTrustError, PinnedTrust, Attestation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class FederationTrustError(RuntimeError):
    """Raised when a federated attestation cannot be safely bound to local trust state."""


@dataclass(frozen=True)
class PinnedTrust:
    issuer: str
    root_key_id: str
    policy_digest: str
    policy_epoch: int
    capabilities: frozenset[str]


@dataclass(frozen=True)
class Attestation:
    issuer: str
    root_key_id: str
    policy_digest: str
    policy_epoch: int
    capabilities: frozenset[str]
    signature_valid: bool  # set by upstream signature verification


def authorize_federated_call(
    pinned: PinnedTrust,
    att: Attestation,
    requested: frozenset[str],
) -> PinnedTrust:
    """
    Decide whether an inbound federated call is authorized under the peer's
    *current* policy, and return the (possibly re-pinned) trust tuple.

    Invariant: freshness is decided by policy_epoch, never by policy_digest
    alone. Digest proves *what* the policy is; epoch proves *whether it is
    current*. A missing or non-monotonic epoch is a conformance failure and
    MUST NOT be routed to any pinned-digest fallback.
    """
    if not att.signature_valid:
        raise FederationTrustError(
            f"attestation from {att.issuer} failed signature verification"
        )
    if att.issuer != pinned.issuer or att.root_key_id != pinned.root_key_id:
        raise FederationTrustError(
            f"issuer/root mismatch: pinned=({pinned.issuer},{pinned.root_key_id}) "
            f"att=({att.issuer},{att.root_key_id})"
        )
    if att.policy_epoch < 0:
        raise FederationTrustError(
            f"attestation from {att.issuer} carries no valid policy_epoch "
            f"(got {att.policy_epoch}); refusing pinned-digest fallback"
        )

    # Superseded attestation: replay of an old epoch. Reject, never fall back.
    if att.policy_epoch < pinned.policy_epoch:
        raise FederationTrustError(
            f"stale attestation from {att.issuer}: epoch {att.policy_epoch} "
            f"< pinned epoch {pinned.policy_epoch}"
        )

    # Same epoch, different digest => issuer equivocation / split-brain policy.
    if att.policy_epoch == pinned.policy_epoch and att.policy_digest != pinned.policy_digest:
        raise FederationTrustError(
            f"issuer equivocation from {att.issuer} at epoch {att.policy_epoch}: "
            f"pinned digest {pinned.policy_digest} != attested {att.policy_digest}"
        )

    # Newer epoch: re-pin atomically to the attested policy, then authorize
    # against the *new* capability set (never the old one).
    if att.policy_epoch > pinned.policy_epoch:
        pinned = PinnedTrust(
            issuer=att.issuer,
            root_key_id=att.root_key_id,
            policy_digest=att.policy_digest,
            policy_epoch=att.policy_epoch,
            capabilities=att.capabilities,
        )

    # Authorize strictly against the current (post-re-pin) capability set.
    missing = requested - pinned.capabilities
    if missing:
        raise FederationTrustError(
            f"capability not granted by {pinned.issuer} at epoch "
            f"{pinned.policy_epoch} (digest {pinned.policy_digest}): "
            f"missing={sorted(missing)}"
        )
    return pinned
