# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-valid-but-revoked-peer-credential-as-live-during-cross-org-trust-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-valid-but-revoked-peer-credential-as-live-during-cross-org-trust-federation.warrant.json
# Markdown SHA-256:   1f9eadd2dff349540aa83f2d6a56d0bbf77cac64595854592ecdc4784c88da52
# Code AST SHA-256:   71f70e472a2b04c102c236c15e61381657069276776d2de33fcb3686e1e801f3
# Verified Classes:   StaleRevocationState, RevocationRollback, StatusList, Credential
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleRevocationState(RuntimeError):
    """Raised when an authorization decision would rest on revocation state
    whose age cannot be proven to be within the issuer's declared bound."""
    pass


class RevocationRollback(StaleRevocationState):
    """Raised when a status list epoch regresses below the last seen epoch."""
    pass


@dataclass
class StatusList:
    epoch: int
    issuer_issued_at: float      # signed by issuer
    max_staleness: float         # signed by issuer; seconds
    fetched_at_monotonic: float  # local monotonic clock at fetch
    revoked_indices: set


@dataclass
class Credential:
    subject: str
    capability: str
    not_after: float
    status_list_index: int
    signature_valid: bool


def authorize(cred: Credential, status: StatusList, last_seen_epoch: int,
              now_monotonic: float) -> bool:
    if not cred.signature_valid:
        return False
    if now_monotonic >= cred.not_after:
        return False

    # Rollback protection: a status list older than one we've already seen
    # cannot be trusted to reflect current revocations.
    if status.epoch < last_seen_epoch:
        raise RevocationRollback(
            f"status list epoch {status.epoch} < last seen {last_seen_epoch}; "
            f"possible replay of pre-revocation state"
        )

    # Freshness bound: age measured on the local monotonic clock against
    # the issuer's signed max_staleness. We do NOT trust the replica's own
    # wall-clock timestamp.
    age = now_monotonic - status.fetched_at_monotonic
    if status.max_staleness <= 0 or age > status.max_staleness:
        raise StaleRevocationState(
            f"revocation state age {age:.1f}s exceeds issuer bound "
            f"{status.max_staleness:.1f}s (epoch {status.epoch}); "
            f"refusing to authorize {cred.subject} for {cred.capability}"
        )

    if cred.status_list_index in status.revoked_indices:
        return False

    # High-blast-radius capabilities must be re-checked per action by the
    # caller; this function returns True only for *this* decision instant.
    return True
