# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-peer-agent-card-whose-securityschemes-reference-a-signing-key-that-rotates-between-discovery-and-webhook-delivery.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-peer-agent-card-whose-securityschemes-reference-a-signing-key-that-rotates-between-discovery-and-webhook-delivery.warrant.json
# Markdown SHA-256:   5b4dd1f72042fe5fd33206fe567cece28fc4c9131ddcdac5c77167b896611aca
# Code AST SHA-256:   171461167c5e15193e1bca9c4ebfe90472d8b05eea9d5c1751dedad07701920b
# Verified Classes:   SigningKeyLineageError, CardVersion, TaskBinding
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class SigningKeyLineageError(RuntimeError):
    """Raised when a webhook's signing key cannot be traced to an
    authenticated card version valid at the task's current state."""


@dataclass(frozen=True)
class CardVersion:
    peer_id: str
    version: int
    kid: str
    authenticated: bool


@dataclass(frozen=True)
class TaskBinding:
    task_id: str
    peer_id: str
    card_version: int
    kid: str
    state: str


def verify_webhook(
    binding: TaskBinding,
    webhook_kid: str,
    webhook_payload: bytes,
    webhook_sig: bytes,
    cached_card: CardVersion,
    refetched_card: Optional[CardVersion],
    verifier,
) -> bool:
    # Fast path: kid matches the binding established at last transition.
    if webhook_kid == binding.kid:
        if not verifier(webhook_payload, webhook_sig, binding.kid):
            raise SigningKeyLineageError(
                f"kid {binding.kid} matches binding but signature invalid; "
                f"treat as forgery, not rotation"
            )
        return True

    # kid mismatch is a lineage question, not a retry.
    if refetched_card is None:
        raise SigningKeyLineageError(
            f"webhook kid {webhook_kid} unknown to binding {binding.kid}; "
            f"no authenticated re-fetch available, rejecting"
        )
    if not refetched_card.authenticated:
        raise SigningKeyLineageError(
            f"re-fetched card for {refetched_card.peer_id} is unauthenticated; "
            f"refusing to trust kid {webhook_kid}"
        )
    if refetched_card.version <= cached_card.version:
        raise SigningKeyLineageError(
            f"card version moved backward or stalled "
            f"({cached_card.version} -> {refetched_card.version}); quarantine task"
        )
    if refetched_card.kid != webhook_kid:
        raise SigningKeyLineageError(
            f"webhook kid {webhook_kid} not present in authenticated card "
            f"v{refetched_card.version} (has {refetched_card.kid})"
        )
    if not verifier(webhook_payload, webhook_sig, webhook_kid):
        raise SigningKeyLineageError(
            f"signature invalid against rotated kid {webhook_kid}"
        )
    # Caller must now re-bind the task to refetched_card.version before
    # advancing the state machine.
    return True
