# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-did-resolution-staleness-as-a-warrant-revocation-failure-in-cross-org-a2a-trust-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-did-resolution-staleness-as-a-warrant-revocation-failure-in-cross-org-a2a-trust-federation.warrant.json
# Markdown SHA-256:   6b30a8f5b1212f29f311e94e1b46de7742ab29f4ee80123008bcc297caabace5
# Code AST SHA-256:   8a3af2f472eb008f1abe017b61a870167b06a69dbd135cd4d0a9fa5b56bc89cd
# Verified Classes:   WarrantStalenessError, ResolutionMonotonicityError, ResolvedDocument, PinnedWarrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class WarrantStalenessError(RuntimeError):
    """Raised when a cached DID resolution is too old to authorize a capability,
    or when a re-resolution cannot be performed (fail-closed)."""
    pass


class ResolutionMonotonicityError(RuntimeError):
    """Raised when a resolved DID document appears to go backwards in version,
    indicating a stale replica rather than a fresh read."""
    pass


@dataclass(frozen=True)
class ResolvedDocument:
    did: str
    updated: int          # monotonic version/timestamp published by the DID method
    keys: frozenset       # authorized verification key ids
    resolved_at: float    # local wall-clock of the resolution


@dataclass(frozen=True)
class PinnedWarrant:
    agent_id: str
    did: str
    signing_key: str
    capabilities: frozenset
    resolved_at: float
    document_updated: int


# Capabilities that mutate federated state and therefore require fresh resolution.
MUTATING_CAPABILITIES = frozenset({"artifact.write", "task.execute"})


def authorize_envelope(
    warrant: PinnedWarrant,
    envelope_signing_key: str,
    requested_capability: str,
    issuer_revocation_bound_s: float,
    resolver,  # callable(did) -> ResolvedDocument | None
    now: Optional[float] = None,
) -> bool:
    now = time.time() if now is None else now

    # 1. Signature key must match the pinned warrant's key.
    if envelope_signing_key != warrant.signing_key:
        raise WarrantStalenessError(
            f"envelope key {envelope_signing_key} != pinned key {warrant.signing_key}"
        )

    # 2. Capability must be within the pinned set.
    if requested_capability not in warrant.capabilities:
        raise WarrantStalenessError(
            f"capability {requested_capability} not in warrant {warrant.capabilities}"
        )

    # 3. Freshness gate: mutating capabilities require resolution within the
    #    issuer's revocation propagation bound, measured from the *pinned*
    #    resolution, not from envelope receipt.
    age = now - warrant.resolved_at
    if requested_capability in MUTATING_CAPABILITIES and age > issuer_revocation_bound_s:
        # Must re-resolve before proceeding. Fail closed if resolver unavailable.
        fresh = resolver(warrant.did)
        if fresh is None:
            raise WarrantStalenessError(
                f"resolution unavailable for {warrant.did}; refusing mutating "
                f"capability {requested_capability} on stale warrant (age={age:.1f}s)"
            )

        # 4. Monotonicity: a document that went backwards is a stale replica.
        if fresh.updated < warrant.document_updated:
            raise ResolutionMonotonicityError(
                f"{warrant.did} resolved updated={fresh.updated} < pinned "
                f"updated={warrant.document_updated}; stale replica suspected"
            )

        # 5. The signing key must still be present in the fresh document.
        if warrant.signing_key not in fresh.keys:
            raise WarrantStalenessError(
                f"key {warrant.signing_key} revoked in fresh resolution of "
                f"{warrant.did}; warrant is dead"
            )

        # 6. The fresh document must itself be within the bound.
        if now - fresh.resolved_at > issuer_revocation_bound_s:
            raise WarrantStalenessError(
                f"fresh resolution of {warrant.did} is itself stale "
                f"(age={now - fresh.resolved_at:.1f}s > bound={issuer_revocation_bound_s}s)"
            )

    return True
