# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-push-notification-webhook-binding-as-invalid-at-the-moment-the-remote-agent-card-s-signing-key-rotates-mid.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-push-notification-webhook-binding-as-invalid-at-the-moment-the-remote-agent-card-s-signing-key-rotates-mid.warrant.json
# Markdown SHA-256:   f01762312836ea2eca62f993fdb86bc372e2f5a043f18589ee729b33d079ead9
# Code AST SHA-256:   aff6f8ae66154bcc306c64d7933d59cb873fedefc61dd329f20cd3eb71357393
# Verified Classes:   WebhookBindingInvalidated, CardBinding
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class WebhookBindingInvalidated(RuntimeError):
    """Raised when a push notification cannot be verified against the
    card version that authorized the task's webhook binding, and the
    new card's security posture differs from the bound one."""


@dataclass(frozen=True)
class CardBinding:
    agent_id: str
    card_version: str
    security_schemes_hash: str
    push_endpoint_host: str


def schemes_hash(schemes: dict) -> str:
    canon = repr(sorted(schemes.items())).encode()
    return hashlib.sha256(canon).hexdigest()


def verify_push_notification(
    binding: CardBinding,
    incoming_kid: str,
    cached_kids: set[str],
    current_card: dict,
) -> str:
    """Return the kid to verify with, or raise if the binding is invalid.

    Safe path: kid is in the cached set -> verify as-is.
    Rotation path: kid missing, but current card's security posture is
    identical to the bound one -> adopt the new kid for verification
    WITHOUT re-binding the webhook.
    Invalid path: posture changed -> raise; do not silently re-bind.
    """
    if incoming_kid in cached_kids:
        return incoming_kid

    new_schemes_hash = schemes_hash(current_card.get("securitySchemes", {}))
    new_host = current_card.get("pushNotification", {}).get("endpointHost", "")

    if new_schemes_hash != binding.security_schemes_hash:
        raise WebhookBindingInvalidated(
            f"agent {binding.agent_id} rotated key to {incoming_kid} but "
            f"securitySchemes changed since binding (task bound under "
            f"card {binding.card_version}); task must re-enter "
            f"input-required(reauth) rather than accept the notification"
        )
    if new_host and new_host != binding.push_endpoint_host:
        raise WebhookBindingInvalidated(
            f"agent {binding.agent_id} push endpoint host moved from "
            f"{binding.push_endpoint_host} to {new_host} mid-task; "
            f"binding is no longer the one the operator approved"
        )
    return incoming_kid
