# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-federate-capability-attestation-drift-across-brokered-trust-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-federate-capability-attestation-drift-across-brokered-trust-chains.warrant.json
# Markdown SHA-256:   4deee8e0bb1dd6071241e533bfb252fed7bbdf7dbbae7c759804120b63ba3e90
# Code AST SHA-256:   af7abc997efdbcd9a7173b9f7ef64990c7c6dad84b3d0e961aa916506108c240
# Verified Classes:   FederationAttestationError, Attestation, BrokerPresentation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class FederationAttestationError(RuntimeError):
    """Raised when a brokered attestation cannot soundly authorize a decision."""
    pass


@dataclass(frozen=True)
class Attestation:
    attestation_id: str
    issuer: str
    subject_agent: str
    bound_scope: str
    not_before: float
    not_after: float
    signature_valid: bool


@dataclass(frozen=True)
class BrokerPresentation:
    attestation: Attestation
    broker_id: str
    broker_verified_at: float
    broker_presentation_at: float
    broker_holds_reissuance_delegation: bool
    negotiated_scope: str


def authorize_via_broker(
    presentation: BrokerPresentation,
    relying_party_clock: float,
    max_clock_skew: float = 5.0,
) -> str:
    att = presentation.attestation

    if not att.signature_valid:
        raise FederationAttestationError(
            f"attestation {att.attestation_id} signature invalid at broker "
            f"{presentation.broker_id}"
        )

    # Relying party must evaluate expiry against its OWN clock, not the
    # broker's presentation timestamp.
    if relying_party_clock > att.not_after + max_clock_skew:
        raise FederationAttestationError(
            f"attestation {att.attestation_id} expired at relying party: "
            f"not_after={att.not_after} decision_clock={relying_party_clock} "
            f"broker_presented_at={presentation.broker_presentation_at}"
        )

    if relying_party_clock < att.not_before - max_clock_skew:
        raise FederationAttestationError(
            f"attestation {att.attestation_id} not yet valid at relying party"
        )

    # Scope binding must match the negotiated scope. A broker that re-scopes
    # without a delegation is asserting authority it does not hold.
    if att.bound_scope != presentation.negotiated_scope:
        if not presentation.broker_holds_reissuance_delegation:
            raise FederationAttestationError(
                f"scope-binding mismatch for {att.attestation_id}: "
                f"attestation bound to {att.bound_scope!r}, negotiated "
                f"{presentation.negotiated_scope!r}, broker "
                f"{presentation.broker_id} holds no reissuance delegation"
            )
        raise FederationAttestationError(
            f"scope-binding mismatch for {att.attestation_id} requires "
            f"delegation-chain walk; not performed in this path"
        )

    # Broker cache TTL must not exceed attestation lifetime for relayed grants.
    broker_lag = presentation.broker_presentation_at - presentation.broker_verified_at
    attestation_lifetime = att.not_after - att.not_before
    if broker_lag > attestation_lifetime:
        raise FederationAttestationError(
            f"broker {presentation.broker_id} relayed {att.attestation_id} "
            f"after {broker_lag:.1f}s, exceeding attestation lifetime "
            f"{attestation_lifetime:.1f}s"
        )

    return presentation.negotiated_scope


if __name__ == "__main__":
    att = Attestation(
        attestation_id="att-7f3a",
        issuer="org-c-issuer",
        subject_agent="agent-c",
        bound_scope="S1",
        not_before=1000.0,
        not_after=1300.0,
        signature_valid=True,
    )
    pres = BrokerPresentation(
        attestation=att,
        broker_id="broker-b",
        broker_verified_at=1010.0,
        broker_presentation_at=1340.0,
        broker_holds_reissuance_delegation=False,
        negotiated_scope="S1",
    )
    try:
        authorize_via_broker(pres, relying_party_clock=1341.0)
    except FederationAttestationError as exc:
        print(f"REFUSED: {exc}")
