# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bind-the-did-document-s-verification-method-to-the-mtls-leaf-san-during-short-lived-workload-rotation-and-why-rotation-in-fligh.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bind-the-did-document-s-verification-method-to-the-mtls-leaf-san-during-short-lived-workload-rotation-and-why-rotation-in-fligh.warrant.json
# Markdown SHA-256:   625d5f921a9d925606413627494453bb469e058995654600f1f700ebeb35865d
# Code AST SHA-256:   e481c0e125ec7e53ce8bdf7be8392dccfe68bc46e845f9830b485c4ce1d4d00e
# Verified Classes:   DidBindingError, Leaf, DidDocument
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class DidBindingError(RuntimeError):
    """Raised when the mTLS leaf cannot be bound to the claimed DID's verification method."""
    pass


@dataclass(frozen=True)
class Leaf:
    did_san: str
    public_key: str
    not_before: float
    not_after: float


@dataclass(frozen=True)
class DidDocument:
    did: str
    verification_methods: tuple  # public keys
    resolved_at: float


def verify_peer(
    claimed_did: str,
    leaf: Leaf,
    cached_doc: DidDocument,
    resolver,
    rotation_interval: float,
    max_skew: float,
    now: float | None = None,
    allow_one_forced_resolution: bool = True,
) -> DidDocument:
    now = now if now is not None else time.time()

    if not (leaf.not_before <= now <= leaf.not_after):
        raise DidBindingError(
            f"leaf for {claimed_did} outside validity window "
            f"[{leaf.not_before}, {leaf.not_after}] at {now}"
        )

    if leaf.did_san != claimed_did:
        raise DidBindingError(
            f"SAN/DID mismatch: leaf asserts {leaf.did_san!r}, peer claims {claimed_did!r}"
        )

    ttl = now - cached_doc.resolved_at
    safe_ttl = rotation_interval - 2 * max_skew
    if ttl > safe_ttl:
        # Cache is provably too old to be trusted against this rotation cadence.
        if not allow_one_forced_resolution:
            raise DidBindingError(
                f"cached DID document for {claimed_did} is stale "
                f"(age={ttl:.1f}s, safe_ttl={safe_ttl:.1f}s) and forced resolution disabled"
            )
        cached_doc = resolver(claimed_did)

    if leaf.public_key in cached_doc.verification_methods:
        return cached_doc

    # Key mismatch: one forced re-resolution to cover rotation-in-flight.
    if not allow_one_forced_resolution:
        raise DidBindingError(
            f"leaf key for {claimed_did} not in cached DID document and re-resolution disabled"
        )
    fresh = resolver(claimed_did)
    if leaf.public_key not in fresh.verification_methods:
        raise DidBindingError(
            f"leaf key for {claimed_did} not authorized by DID document after re-resolution"
        )
    return fresh
