# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-cached-a2a-agent-card-before-honoring-a-push-notification-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-cached-a2a-agent-card-before-honoring-a-push-notification-binding.warrant.json
# Markdown SHA-256:   704485f316cccd40af35e12dd234fcac184b6e7ea26166e3716a11be921681c0
# Code AST SHA-256:   07e8124febd2f98b9a6640379a0a829e143e91dfeeda7e4bc5d9ded7a568aa96
# Verified Classes:   CardBindingSkewError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CardBindingSkewError(RuntimeError):
    """Raised when a push notification's auth material does not match the cached Agent Card generation."""
    pass


def validate_notification_against_card(notification, cached_card, refetch_card):
    """
    Enforce the card-generation predicate for A2A v1.0 push bindings.
    Returns the (possibly refreshed) card that authorizes this notification,
    or raises if the notification cannot be attributed to any card generation.
    """
    scheme = cached_card["securitySchemes"]["pushAuth"]
    expected_key_id = scheme.get("keyId")
    presented_key_id = notification.headers.get("X-A2A-Key-Id")

    if presented_key_id == expected_key_id:
        if not verify_signature(notification, scheme):
            raise CardBindingSkewError(
                f"Signature invalid under current key {expected_key_id}; "
                "possible tampering, not skew."
            )
        return cached_card

    # Key-id mismatch: the cached card is stale. Re-fetch before deciding.
    fresh_card = refetch_card()
    fresh_scheme = fresh_card["securitySchemes"]["pushAuth"]
    if fresh_scheme.get("keyId") != presented_key_id:
        raise CardBindingSkewError(
            f"Notification key {presented_key_id} matches neither cached "
            f"{expected_key_id} nor refreshed {fresh_scheme.get('keyId')}; "
            "cannot attribute notification to any card generation."
        )
    if not verify_signature(notification, fresh_scheme):
        raise CardBindingSkewError(
            f"Signature invalid under refreshed key {presented_key_id}."
        )
    # Binding is valid under the refreshed generation; caller must re-issue
    # tasks/pushNotificationConfig/set to migrate the registration.
    return fresh_card


def verify_signature(notification, scheme):
    # Placeholder for HMAC/bearer verification against scheme material.
    return True
