# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-federated-attribute-assertions-as-lease-bound-rather-than-identity-bound-when-crossing-organizational-trust-b.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-federated-attribute-assertions-as-lease-bound-rather-than-identity-bound-when-crossing-organizational-trust-b.warrant.json
# Markdown SHA-256:   557d9cb9aac83a0036480b7c7a9aec9382c06fc3bf545979c8169589b8829211
# Code AST SHA-256:   35bdcb62ca5d00be593b651f0db21634fb47620d07d27625fc8910419746ccda
# Verified Classes:   StaleCapabilityError, DerivedClaimRejectedError, CapabilityLease
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleCapabilityError(RuntimeError):
    """Raised when an agent attempts to act on a capability lease that has
    exceeded its staleness budget or whose revocation state cannot be confirmed."""
    pass


class DerivedClaimRejectedError(RuntimeError):
    """Raised when an agent receives a derived claim without the underlying
    verifiable credential and a fresh revocation probe."""
    pass


@dataclass
class CapabilityLease:
    vc_blob: bytes
    subject: str
    scope: str
    issued_at: float
    expires_at: float
    last_revocation_check: Optional[float] = None
    revocation_probe_ttl: float = 60.0  # S: staleness budget in seconds

    def is_stale(self, now: Optional[float] = None) -> bool:
        now = now if now is not None else time.time()
        if self.last_revocation_check is None:
            return True
        return (now - self.last_revocation_check) > self.revocation_probe_ttl

    def is_expired(self, now: Optional[float] = None) -> bool:
        now = now if now is not None else time.time()
        return now >= self.expires_at


def authorize_action(
    lease: CapabilityLease,
    requested_scope: str,
    blast_radius_high: bool,
    revocation_probe,
    now: Optional[float] = None,
) -> bool:
    """Authorize an action against a lease-bound capability.

    revocation_probe: callable(subject) -> bool (True if still valid).
    Raises StaleCapabilityError if the lease cannot be confirmed current.
    """
    now = now if now is not None else time.time()

    if lease.is_expired(now):
        raise StaleCapabilityError(
            f"lease for {lease.subject} expired at {lease.expires_at}"
        )

    # High blast-radius actions always re-probe, regardless of staleness.
    if blast_radius_high or lease.is_stale(now):
        try:
            still_valid = revocation_probe(lease.subject)
        except Exception as exc:
            # Fail closed: cannot confirm revocation state.
            raise StaleCapabilityError(
                f"revocation probe failed for {lease.subject}: {exc}"
            ) from exc
        if not still_valid:
            raise StaleCapabilityError(
                f"capability for {lease.subject} revoked by issuer"
            )
        lease.last_revocation_check = now

    if requested_scope != lease.scope:
        # Scope change requires full re-verification, not lease reuse.
        raise StaleCapabilityError(
            f"scope mismatch: lease grants {lease.scope!r}, "
            f"action requests {requested_scope!r}"
        )

    return True


def accept_handoff_claim(claim: dict, original_vc: Optional[bytes]) -> None:
    """Reject derived claims forwarded between agents without the source VC."""
    if original_vc is None or "derived_from" not in claim:
        raise DerivedClaimRejectedError(
            "handoff carried a derived claim without the source verifiable "
            "credential; the receiving agent cannot re-verify revocation state"
        )
