# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-handle-holder-binding-breakage-when-a-federated-verifiable-credential-is-verified-offline-against-a-stale-issuer-key-set.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-handle-holder-binding-breakage-when-a-federated-verifiable-credential-is-verified-offline-against-a-stale-issuer-key-set.warrant.json
# Markdown SHA-256:   2b4942501e0bf65e9978cf07c9799a4f602303c8ab148012058fb5bbed798082
# Code AST SHA-256:   f099d122c99411992ae08a683bf764a7eb55a4bb38fd77f35c83444811218de4
# Verified Classes:   StaleAuthorityError, KeySet, Credential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleAuthorityError(RuntimeError):
    """Raised when a credential's validity interval is not contained within the
    freshness window of the cached issuer key set under which it was verified."""


@dataclass(frozen=True)
class KeySet:
    version: str
    fetched_at: float          # epoch seconds
    revoked_keys: frozenset    # key ids revoked as of fetched_at


@dataclass(frozen=True)
class Credential:
    issuer_key_id: str
    not_before: float
    not_after: float
    cnf_key_id: str            # holder-bound key


def admit_offline(
    cred: Credential,
    keyset: KeySet,
    now: float,
    max_staleness: float,
    revocation_sla: float,
) -> str:
    if now < cred.not_before or now > cred.not_after:
        raise StaleAuthorityError(
            f"credential outside its own validity window at t={now}"
        )

    authority_until = keyset.fetched_at + max_staleness
    if now >= authority_until:
        raise StaleAuthorityError(
            f"cached key set v={keyset.version} expired at {authority_until}, now={now}"
        )

    # The critical invariant: the credential must not outlive the authority window
    # by more than the issuer's revocation-propagation SLA.
    if cred.not_after > authority_until + revocation_sla:
        raise StaleAuthorityError(
            f"credential valid until {cred.not_after} exceeds authority window "
            f"{authority_until} + SLA {revocation_sla}; holder binding does not "
            f"extend issuer authority"
        )

    if cred.issuer_key_id in keyset.revoked_keys:
        raise StaleAuthorityError(
            f"issuer key {cred.issuer_key_id} revoked as of v={keyset.version}"
        )

    # Possession proof MUST be bound to keyset.version (checked by caller's
    # transcript construction); we assert the binding key is present.
    if not cred.cnf_key_id:
        raise StaleAuthorityError("credential lacks holder-binding key")

    return f"admitted under authority epoch v={keyset.version}"
