# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-revoked-did-delegation-during-a-cross-org-a2a-handoff-after-a-credential-status-list-cache-miss.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-revoked-did-delegation-during-a-cross-org-a2a-handoff-after-a-credential-status-list-cache-miss.warrant.json
# Markdown SHA-256:   0b9a4cb3527c82be50083851ff8539d9f38ea8b717f866720a5e318bbca05c97
# Code AST SHA-256:   62bcb485c7335136da20205b073d342521d6b482fe535e904ebb779162f754a7
# Verified Classes:   RevocationPropagationGap, StatusListCache, Delegation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationPropagationGap(RuntimeError):
    """Raised when a verifier grants scope it cannot justify against a fresh revocation source."""
    pass


@dataclass
class StatusListCache:
    fetched_at: float
    ttl: float
    revoked_bits: set
    issuer_did: str

    def age(self, now: float) -> float:
        return now - self.fetched_at

    def is_revoked(self, index: int) -> bool:
        return index in self.revoked_bits


@dataclass
class Delegation:
    subject_did: str
    status_list_index: int
    valid_until: float


def verify_handoff(
    delegation: Delegation,
    cache: StatusListCache,
    now: float,
    session_lifetime: float,
) -> bool:
    # Clamp TTL by the credential's own remaining validity, not just config.
    effective_ttl = min(cache.ttl, delegation.valid_until - now)
    if effective_ttl <= 0:
        raise RevocationPropagationGap(
            f"delegation for {delegation.subject_did} expired before verification"
        )

    if cache.age(now) > effective_ttl:
        raise RevocationPropagationGap(
            f"status list age {cache.age(now):.0f}s exceeds clamped ttl "
            f"{effective_ttl:.0f}s for {delegation.subject_did}"
        )

    if cache.is_revoked(delegation.status_list_index):
        return False

    # Session must not outlive the next mandatory revalidation point.
    next_revalidate = cache.fetched_at + effective_ttl
    if now + session_lifetime > next_revalidate:
        raise RevocationPropagationGap(
            f"session for {delegation.subject_did} would outlive status-list "
            f"revalidation by {now + session_lifetime - next_revalidate:.0f}s"
        )

    return True


def on_post_handoff_refetch(
    delegation: Delegation,
    fresh_cache: StatusListCache,
    session_active: bool,
) -> None:
    if session_active and fresh_cache.is_revoked(delegation.status_list_index):
        # Retroactive invalidation: a live session is running on revoked authority.
        raise RevocationPropagationGap(
            f"revoked authority in use: {delegation.subject_did} holds live session "
            f"under revoked delegation index {delegation.status_list_index}"
        )
