# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-federated-agent-identity-when-short-lived-credentials-outlive-the-revocation-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-federated-agent-identity-when-short-lived-credentials-outlive-the-revocation-window.warrant.json
# Markdown SHA-256:   9f7b8082c8376335f3e5a5d9160f2c616cd919a0a0824e37da6e88823b4f20fe
# Code AST SHA-256:   44a514dad1cd7adc95a36919b741f31d8e1a4bcfc40bc88a36434a9abc84c486
# Verified Classes:   RevocationWatermarkError, Credential, VerifierState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationWatermarkError(RuntimeError):
    """Raised when a credential's issuance time is newer than the verifier's
    last successful revocation sync, meaning the issuance path may have
    bypassed revocation."""
    pass


@dataclass
class Credential:
    identity: str
    issued_at: float      # epoch seconds
    expires_at: float     # epoch seconds
    serial: str


@dataclass
class VerifierState:
    last_sync_at: float          # epoch seconds of last successful revocation sync
    revoked_serials: set[str]
    max_clock_skew: float = 2.0  # seconds


def verify_credential(cred: Credential, state: VerifierState, now: float | None = None) -> bool:
    now = time.time() if now is None else now

    if now > cred.expires_at:
        return False  # expired; not our concern

    if cred.serial in state.revoked_serials:
        return False  # explicitly revoked

    # Boundary check: was this credential minted after our last revocation sync?
    # If so, we cannot prove the issuance path was revocation-scoped.
    if cred.issued_at > state.last_sync_at + state.max_clock_skew:
        raise RevocationWatermarkError(
            f"credential {cred.serial} for {cred.identity} issued at "
            f"{cred.issued_at:.0f} is newer than last sync {state.last_sync_at:.0f}; "
            f"issuance path may bypass revocation. Refusing until resync."
        )

    return True


def admission_gate(cred: Credential, state: VerifierState, resync_fn) -> bool:
    """Attempt verification; on watermark violation, force a resync and retry once."""
    try:
        return verify_credential(cred, state)
    except RevocationWatermarkError:
        new_sync = resync_fn()
        state.last_sync_at = new_sync
        # Retry only if the resync actually advanced past the issuance time.
        if cred.issued_at > state.last_sync_at + state.max_clock_skew:
            raise RevocationWatermarkError(
                f"resync at {new_sync:.0f} still precedes issuance "
                f"{cred.issued_at:.0f} for {cred.serial}; revocation scope incomplete"
            )
        return verify_credential(cred, state)
