# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-dpop-binding-when-an-oidc-token-is-refreshed-mid-handoff-and-how-do-we-bound-the-attestation-window.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-dpop-binding-when-an-oidc-token-is-refreshed-mid-handoff-and-how-do-we-bound-the-attestation-window.warrant.json
# Markdown SHA-256:   fc669f001fe70100051089a0672ab2df8e33d406db2c96754068e07b6fdc93c9
# Code AST SHA-256:   40fafc6546ca1f24cb5da8090579e2355fb5c545efbcefdb89486dcbf3632ccc
# Verified Classes:   DpopBindingDiscontinuity
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class DpopBindingDiscontinuity(RuntimeError):
    """Raised when a live session's DPoP thumbprint rotates without a valid re-binding attestation."""
    pass


def verify_session_continuity(
    session: dict,
    presented_jkt: str,
    token_claims: dict,
    rebind_attestation: dict | None,
    refresh_grace_s: float = 30.0,
) -> str:
    """
    Returns one of: "continue", "migrate", "suspend", "terminate".
    Raises DpopBindingDiscontinuity when the mismatch is unattributable and
    the caller would otherwise fall through to full re-auth (state loss).
    """
    cached_jkt = session["jkt"]
    if presented_jkt == cached_jkt:
        return "continue"

    # A key change during a live session is not a refresh — it is a binding event.
    if rebind_attestation is not None:
        if rebind_attestation.get("old_jkt") != cached_jkt or rebind_attestation.get("new_jkt") != presented_jkt:
            raise DpopBindingDiscontinuity(
                f"re-bind attestation does not cover {cached_jkt} -> {presented_jkt}"
            )
        if not rebind_attestation.get("old_key_signature_valid"):
            raise DpopBindingDiscontinuity("re-bind attestation signature invalid")
        return "migrate"

    identity_stable = (
        token_claims.get("sub") == session["subject"]
        and token_claims.get("iss") == session["iss"]
        and token_claims.get("aud") == session["aud"]
    )
    within_grace = (token_claims.get("iat", 0) - session["opened_at"]) <= refresh_grace_s

    if identity_stable and within_grace:
        # Rotation-under-refresh: preserve state, require explicit resume.
        return "suspend"

    # Unattributable mismatch: MUST NOT be routed to the retry layer as a
    # plain 401, because that path discards session state and re-executes.
    raise DpopBindingDiscontinuity(
        f"jkt mismatch {cached_jkt} -> {presented_jkt} with no attestation "
        f"and no grace window; session={session.get('session_id')}"
    )
