# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-federated-identity-token-whose-embedded-policy-epoch-is-older-than-the-relying-party-s-revocation-floor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-federated-identity-token-whose-embedded-policy-epoch-is-older-than-the-relying-party-s-revocation-floor.warrant.json
# Markdown SHA-256:   331b1d501194ad563cc3fc6c9e6d34794c3a83f8836a56bed9ae936da887e4aa
# Code AST SHA-256:   1803bbd5c4f65017bea8140b4e8c4dc41a3364bb14b0ad03ca034647bba4ca78
# Verified Classes:   StaleFederatedPolicyEpoch, IndeterminateFederationState, FederatedAssertion, RPPolicyState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleFederatedPolicyEpoch(RuntimeError):
    """Token identity is valid but its embedded policy epoch predates the RP's revocation floor."""
    pass


class IndeterminateFederationState(RuntimeError):
    """RP cannot confirm its revocation floor is current; must fail closed."""
    pass


@dataclass(frozen=True)
class FederatedAssertion:
    subject: str
    issuer: str
    exp: float                 # unix seconds
    policy_epoch: Optional[int]  # None if claim absent from signed body
    signature_valid: bool


@dataclass(frozen=True)
class RPPolicyState:
    revocation_floor: int
    floor_replication_lag_s: float
    max_tolerable_lag_s: float = 2.0


def admit_federated_peer(
    assertion: FederatedAssertion,
    rp: RPPolicyState,
    now: float,
) -> None:
    # 1. Cryptographic + temporal validity.
    if not assertion.signature_valid:
        raise IndeterminateFederationState("signature invalid; cannot trust any claim")
    if assertion.exp <= now:
        raise StaleFederatedPolicyEpoch("token expired; peer must re-authenticate")

    # 2. Fail closed if the RP's own floor is not trustworthy.
    if rp.floor_replication_lag_s > rp.max_tolerable_lag_s:
        raise IndeterminateFederationState(
            f"revocation floor replication lag {rp.floor_replication_lag_s}s "
            f"exceeds {rp.max_tolerable_lag_s}s; refusing federated admission"
        )

    # 3. Epoch gate: absent epoch is NOT defaulted to current.
    if assertion.policy_epoch is None:
        raise IndeterminateFederationState(
            "token carries no signed policy_epoch; cannot bound authorization freshness"
        )
    if assertion.policy_epoch < rp.revocation_floor:
        raise StaleFederatedPolicyEpoch(
            f"policy_epoch {assertion.policy_epoch} < revocation_floor "
            f"{rp.revocation_floor}; peer must re-issue with fresh epoch"
        )

    # Admitted: identity fresh AND policy fresh against this RP's floor.
    return None
