# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-did-anchored-mtls-token-whose-subject-key-was-rotated-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-did-anchored-mtls-token-whose-subject-key-was-rotated-mid-session.warrant.json
# Markdown SHA-256:   18041c2ce350d726f706a01dc7a3ee1af272816fc432c51ad43b5dcc28a90219
# Code AST SHA-256:   3363476044f63dd45bd46fbbff3d3414fc7d64d68a7d9099fe8622454747cb2f
# Verified Classes:   StaleIdentityWarrantError, DidDocument, Token
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class StaleIdentityWarrantError(RuntimeError):
    """Raised when a token's bound key is no longer authorized for authentication."""
    pass


@dataclass
class DidDocument:
    did: str
    version_id: str
    updated: float
    authentication: list[str]          # verification method ids authorized for authn
    verification_methods: dict[str, dict]  # id -> {"publicKeyJwk": {...}, ...}


@dataclass
class Token:
    sub: str
    cnf_jkt: str          # SPKI thumbprint bound at issuance
    iat: float
    exp: float
    did_version: Optional[str] = None  # optional pin


def spki_thumbprint(cert_der: bytes) -> str:
    return "sha-256:" + hashlib.sha256(cert_der).hexdigest()


def verify_cross_org_call(
    token: Token,
    peer_cert_der: bytes,
    resolver,                       # callable(did) -> DidDocument
    cache: dict[str, DidDocument],
    now: Optional[float] = None,
    honor_version_pin: bool = False,
) -> DidDocument:
    now = time.time() if now is None else now

    if not (token.iat <= now < token.exp):
        raise StaleIdentityWarrantError(
            f"token outside validity window: iat={token.iat} exp={token.exp} now={now}"
        )

    presented_jkt = spki_thumbprint(peer_cert_der)
    if presented_jkt != token.cnf_jkt:
        raise StaleIdentityWarrantError(
            f"cnf mismatch: token bound to {token.cnf_jkt}, cert presents {presented_jkt}"
        )

    cached = cache.get(token.sub)
    needs_refresh = cached is None or cached.updated >= token.iat
    if cached is not None and token.did_version and honor_version_pin:
        needs_refresh = cached.version_id != token.did_version

    doc = resolver(token.sub) if needs_refresh else cached
    cache[token.sub] = doc

    # The boundary invariant: the key must be under `authentication`, not merely
    # present in verificationMethod, and not merely under assertionMethod.
    authorized_ids = set(doc.authentication)
    matching_ids = [
        vid for vid, vm in doc.verification_methods.items()
        if _jwk_thumbprint(vm.get("publicKeyJwk", {})) == presented_jkt
    ]

    if not matching_ids:
        raise StaleIdentityWarrantError(
            f"key {presented_jkt} absent from DID document {doc.did}@{doc.version_id}"
        )

    if not any(vid in authorized_ids for vid in matching_ids):
        # This is the demoted-key case: key exists (likely under assertionMethod)
        # but is no longer authorized to authenticate a live session.
        raise StaleIdentityWarrantError(
            f"key {presented_jkt} present in {doc.did}@{doc.version_id} but not "
            f"authorized for authentication; matched ids={matching_ids}, "
            f"authn set={sorted(authorized_ids)}"
        )

    return doc


def _jwk_thumbprint(jwk: dict) -> str:
    # RFC 7638 canonical thumbprint; simplified for illustration.
    import json
    canon = json.dumps(
        {k: jwk[k] for k in ("crv", "kty", "x", "y") if k in jwk},
        separators=(",", ":"), sort_keys=True,
    )
    return "sha-256:" + hashlib.sha256(canon.encode()).hexdigest()
