# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revoked-credential-still-satisfies-a-cached-capability-warrant-cross-org-revocation-lag-and-the-byzantine-reputatio.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revoked-credential-still-satisfies-a-cached-capability-warrant-cross-org-revocation-lag-and-the-byzantine-reputatio.warrant.json
# Markdown SHA-256:   4c5d47a249b83f828b5ae75fcab87953f587f87e68a3427e08f4d7aff6e95e4a
# Code AST SHA-256:   ca89d4aa51317fd246095766d1cca336ce96058cac9916b2ff18c670dd26d45c
# Verified Classes:   RevocationBypassError, RevocationView, Warrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class RevocationBypassError(RuntimeError):
    """Raised when authorization would proceed on a stale or absent revocation view."""
    pass


@dataclass
class RevocationView:
    issuer: str
    revoked: frozenset
    as_of: float          # wall-clock when this view was fetched


@dataclass
class Warrant:
    subject: str
    issuer: str
    capability: str
    exp: float
    signature_valid: bool


MAX_REV_STALENESS = 30.0        # seconds; must be << warrant_TTL
REPUTATION_FLOOR = 0.80


def authorize(
    subject: str,
    capability: str,
    now: float,
    warrant: Warrant,
    rev_view: Optional[RevocationView],
    reputation: float,
    fetch_revocation,            # callable(issuer) -> Optional[RevocationView]
) -> bool:
    if not warrant.signature_valid:
        return False
    if now >= warrant.exp:
        return False

    # --- the boundary: freshness of revocation view is a hard precondition ---
    if rev_view is None or (now - rev_view.as_of) > MAX_REV_STALENESS:
        rev_view = fetch_revocation(warrant.issuer)
        if rev_view is None:
            # fail closed. Do NOT fall back to a stale view.
            raise RevocationBypassError(
                f"revocation view for issuer={warrant.issuer} unavailable or "
                f"staler than {MAX_REV_STALENESS}s at t={now}; refusing to "
                f"authorize subject={subject} on cached state"
            )
        if (now - rev_view.as_of) > MAX_REV_STALENESS:
            raise RevocationBypassError(
                f"fetched revocation view for issuer={warrant.issuer} still "
                f"stale ({now - rev_view.as_of:.1f}s > {MAX_REV_STALENESS}s)"
            )

    if subject in rev_view.revoked:
        return False

    # reputation gate is orthogonal: it filters valid credentials, it does not
    # substitute for revocation freshness.
    if reputation < REPUTATION_FLOOR:
        return False

    return True
