# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-federated-credential-mid-handoff-when-the-issuer-s-revocation-list-has-already-been-garbage-collected.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-federated-credential-mid-handoff-when-the-issuer-s-revocation-list-has-already-been-garbage-collected.warrant.json
# Markdown SHA-256:   100e04d65bd2e5fd640a1e3c6fb3cc10403dab44b2428dc438460cc6ad0f5312
# Code AST SHA-256:   56ce11463c5101c8b32390521598d12a12ac495909751ced7a1272e1f69daebc
# Verified Classes:   RevocationAttributionError, StatusList, Credential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationAttributionError(RuntimeError):
    """Raised when a status-list bit cannot be attributed to the credential being validated."""


@dataclass(frozen=True)
class StatusList:
    url: str
    epoch: int
    issued_at: float          # signed by issuer; when this list document was minted
    bits: bytes               # decoded bitstring

    def bit(self, index: int) -> int:
        byte, off = divmod(index, 8)
        return (self.bits[byte] >> (7 - off)) & 1


@dataclass(frozen=True)
class Credential:
    subject: str
    valid_from: float
    valid_until: float
    status_index: int
    status_list_url: str
    derived_ttl: float | None = None   # TTL of any child token minted from this one


def validate_provenance(cred: Credential, status: StatusList, now: float) -> bool:
    if status.url != cred.status_list_url:
        raise RevocationAttributionError(
            f"status list URL mismatch: cred points at {cred.status_list_url}, got {status.url}"
        )

    # The invariant: a bit is only attributable if the list predates the credential's lifetime.
    # If the list was re-issued after valid_from, the index may have been recycled and the
    # bit at status_index describes a *different* credential.
    if status.issued_at > cred.valid_from:
        raise RevocationAttributionError(
            f"status list epoch {status.epoch} issued at {status.issued_at} "
            f"postdates credential valid_from {cred.valid_from}; "
            f"index {cred.status_index} is not attributable (possible GC recycling)"
        )

    # Derived-token TTL must not outlive the parent's status-list retention horizon.
    if cred.derived_ttl is not None and cred.valid_from + cred.derived_ttl > status.issued_at:
        # In production this is a hard reject: a child token outliving the list epoch
        # is a revocation-laundering primitive.
        raise RevocationAttributionError(
            f"derived TTL {cred.derived_ttl}s exceeds status-list retention horizon; "
            f"child token would outlive attributable revocation window"
        )

    if status.bit(cred.status_index) == 1:
        return False  # affirmatively revoked

    # Provenance mode: parent may be expired, but only if a fresh child token is present.
    # We do not silently accept expired parents without a child; that is the bug we are bounding.
    if now > cred.valid_until and cred.derived_ttl is None:
        return False

    return True


def handoff_check(cred: Credential, status: StatusList, now: float) -> str:
    try:
        ok = validate_provenance(cred, status, now)
    except RevocationAttributionError as e:
        return f"REJECT (fail-closed): {e}"
    return "ACCEPT" if ok else "REJECT (revoked or expired)"
