# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-policy-attestation-replay-across-federated-trust-brokers-when-attestation-timestamps-are-peer-local.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-policy-attestation-replay-across-federated-trust-brokers-when-attestation-timestamps-are-peer-local.warrant.json
# Markdown SHA-256:   4cbdd3aaf8cb664cc6338249c8c5b823c953c6735526311f671bd6f95918657e
# Code AST SHA-256:   422ec86f33e3200c99ac4589bc527d2a5eab43994d24465ade79606309f22374
# Verified Classes:   AttestationReplayError, MissingUniquenessTokenError, Attestation, FederatedAttestationVerifier
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Dict, Tuple


class AttestationReplayError(RuntimeError):
    """Raised when a policy attestation is re-presented for an overlapping request context."""
    pass


class MissingUniquenessTokenError(RuntimeError):
    """Raised when a federated attestation carries no verifier-checkable uniqueness token."""
    pass


@dataclass(frozen=True)
class Attestation:
    attestation_id: str
    issuer: str
    subject: str
    caller_id: str
    issued_at: int          # peer-local epoch seconds
    expires_at: int
    sequence: int | None    # broker-signed monotonic seq, or None if absent
    request_hash: str | None


class FederatedAttestationVerifier:
    def __init__(self, skew_tolerance: int = 300) -> None:
        self.skew_tolerance = skew_tolerance
        # digest -> (caller_id, issued_at) of the first consumption
        self._consumed: Dict[str, Tuple[str, int]] = {}
        # (issuer, subject) -> highest sequence accepted
        self._seq_high_water: Dict[Tuple[str, str], int] = {}

    def _digest(self, a: Attestation) -> str:
        h = hashlib.sha256()
        h.update(a.attestation_id.encode())
        h.update(a.issuer.encode())
        h.update(a.subject.encode())
        return h.hexdigest()

    def verify_and_consume(self, a: Attestation, now: int, request_hash: str) -> None:
        # 1. Structural: federated grants MUST carry a uniqueness token.
        if a.sequence is None and a.request_hash is None:
            raise MissingUniquenessTokenError(
                f"attestation {a.attestation_id} from {a.issuer} has no sequence "
                f"or request binding; cannot establish federation-global uniqueness"
            )

        # 2. Request binding: if present, replay against a different context fails here.
        if a.request_hash is not None and a.request_hash != request_hash:
            raise AttestationReplayError(
                f"attestation {a.attestation_id} bound to request {a.request_hash}, "
                f"presented for {request_hash}"
            )

        # 3. Content-addressed replay guard, independent of caller identity.
        digest = self._digest(a)
        prior = self._consumed.get(digest)
        if prior is not None:
            prior_caller, prior_issued = prior
            # Non-advancing peer clock under re-presentation is the skew/replay signature.
            if a.issued_at <= prior_issued:
                raise AttestationReplayError(
                    f"attestation {a.attestation_id} re-presented (caller {prior_caller} -> "
                    f"{a.caller_id}) with non-advancing issued_at {prior_issued} -> {a.issued_at}"
                )
            raise AttestationReplayError(
                f"attestation {a.attestation_id} already consumed by caller {prior_caller}"
            )

        # 4. Monotonic sequence check per (issuer, subject).
        if a.sequence is not None:
            key = (a.issuer, a.subject)
            high = self._seq_high_water.get(key, -1)
            if a.sequence <= high:
                raise AttestationReplayError(
                    f"attestation {a.attestation_id} sequence {a.sequence} not greater than "
                    f"high-water {high} for {key}"
                )

        # 5. Freshness check AFTER uniqueness — tolerance governs skew, not reuse.
        if a.issued_at - self.skew_tolerance > now:
            raise AttestationReplayError(
                f"attestation {a.attestation_id} issued_at {a.issued_at} exceeds skew tolerance"
            )
        if a.expires_at < now:
            raise AttestationReplayError(
                f"attestation {a.attestation_id} expired at {a.expires_at}"
            )

        # Commit consumption only after all checks pass.
        self._consumed[digest] = (a.caller_id, a.issued_at)
        if a.sequence is not None:
            self._seq_high_water[(a.issuer, a.subject)] = a.sequence
