# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-agent-manifest-whose-did-resolves-but-whose-signing-key-has-rotated-mid-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-agent-manifest-whose-did-resolves-but-whose-signing-key-has-rotated-mid-handshake.warrant.json
# Markdown SHA-256:   3599718218db24be4725547e443e20d77c27995bd0c0128058301a5374fccbb7
# Code AST SHA-256:   29871f3e8726b4b6d1137486d86f1609949388566d69ab88ca8975547bd1a1cf
# Verified Classes:   StaleKeyAuthorizationError, DidDocument, SignedManifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleKeyAuthorizationError(RuntimeError):
    """Raised when a manifest's signing key is not provably authorized at verification time."""
    pass


@dataclass
class DidDocument:
    updated: float
    active_keys: set[str]
    revoked: dict[str, float]  # key_id -> revocation_time (epoch seconds)


@dataclass
class SignedManifest:
    signing_key_id: str
    issued_at: float
    not_after: float
    payload: bytes
    signature: bytes


def verify_federated_manifest(
    manifest: SignedManifest,
    resolved_doc: DidDocument,
    resolved_at: float,
    verification_time: float,
    max_resolution_age: float,
    revocation_channel_reachable: bool,
) -> bool:
    # 1. Resolution freshness
    if verification_time - resolved_at > max_resolution_age:
        raise StaleKeyAuthorizationError(
            f"resolution stale: age={verification_time - resolved_at:.1f}s "
            f"> max={max_resolution_age:.1f}s; re-resolve before deciding"
        )

    # 2. Revocation exclusion over [issued_at, verification_time]
    rev_time: Optional[float] = resolved_doc.revoked.get(manifest.signing_key_id)
    if rev_time is not None and rev_time <= verification_time:
        raise StaleKeyAuthorizationError(
            f"signing key {manifest.signing_key_id} revoked at {rev_time:.0f} "
            f"<= verification_time {verification_time:.0f}; "
            f"signature valid at issuance but unauthorized at verification"
        )

    # 3. Key must be currently active (not silently retired)
    if manifest.signing_key_id not in resolved_doc.active_keys:
        raise StaleKeyAuthorizationError(
            f"signing key {manifest.signing_key_id} absent from current DID document "
            f"(updated {resolved_doc.updated:.0f}); treat as revocation-equivalent"
        )

    # 4. Interval containment
    if not (manifest.issued_at <= verification_time <= manifest.not_after):
        raise StaleKeyAuthorizationError(
            f"verification_time {verification_time:.0f} outside manifest interval "
            f"[{manifest.issued_at:.0f}, {manifest.not_after:.0f}]"
        )

    # 5. Revocation channel must be reachable for provable-unrevoked assertion
    if not revocation_channel_reachable:
        raise StaleKeyAuthorizationError(
            "revocation channel unreachable; cannot assert key unrevoked at "
            f"{verification_time:.0f}; defer, do not accept"
        )

    # Signature verification (necessary, not sufficient) happens here in production.
    return True
