# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-stale-revoked-warrants-from-being-honored-after-a-credential-rotation-race-in-federated-agent-meshes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-stale-revoked-warrants-from-being-honored-after-a-credential-rotation-race-in-federated-agent-meshes.warrant.json
# Markdown SHA-256:   07ad5524cd621314c66e24d27b47ebfe5ef20a4627288c18cdcd78a9ed2e966e
# Code AST SHA-256:   c5d8d9dd6da191bb7334e4a74727d56c95b6e0e6e6729eb862a20c1dd909dca9
# Verified Classes:   StaleWatermarkError, RetiredWarrantError, Warrant, Watermark
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleWatermarkError(RuntimeError):
    """Raised when a verifier cannot establish watermark freshness for a warrant's issuer."""
    pass


class RetiredWarrantError(RuntimeError):
    """Raised when a presented warrant's epoch is below the issuer's revocation watermark."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer_id: str
    agent_id: str
    epoch: int
    scope: str          # "read" | "write" | "delegate"
    signature_valid: bool


@dataclass(frozen=True)
class Watermark:
    issuer_id: str
    agent_id: str
    epoch: int
    fetched_at: float
    signed: bool


FRESHNESS_WINDOW_S = 30.0
SAFE_SCOPES = {"read"}  # accept-on-stale permitted only here


def authorize(
    warrant: Warrant,
    watermark: Optional[Watermark],
    now: float,
    *,
    can_fetch_issuer: bool,
) -> bool:
    if not warrant.signature_valid:
        raise RetiredWarrantError(
            f"warrant {warrant.agent_id}@{warrant.epoch} signature invalid"
        )

    if watermark is None or watermark.issuer_id != warrant.issuer_id \
            or watermark.agent_id != warrant.agent_id:
        if not can_fetch_issuer:
            raise StaleWatermarkError(
                f"no watermark for {warrant.issuer_id}/{warrant.agent_id}; "
                f"cannot authorize {warrant.scope} scope"
            )
        raise StaleWatermarkError(
            f"watermark missing for {warrant.agent_id}; fetch required before authorize"
        )

    stale = (now - watermark.fetched_at) > FRESHNESS_WINDOW_S
    if stale:
        if warrant.scope in SAFE_SCOPES:
            # bounded exposure: accept only read-scope under stale watermark
            pass
        else:
            raise StaleWatermarkError(
                f"watermark for {warrant.agent_id} stale by "
                f"{now - watermark.fetched_at:.1f}s; refusing {warrant.scope} scope"
            )

    if not watermark.signed:
        raise StaleWatermarkError(
            f"watermark for {warrant.agent_id} unsigned; not a trust anchor"
        )

    if warrant.epoch < watermark.epoch:
        raise RetiredWarrantError(
            f"warrant {warrant.agent_id}@{warrant.epoch} below watermark "
            f"{watermark.epoch}; replay of retired credential"
        )

    return True
