# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-aaif-credential-binding-after-a-delegated-re-sign-and-how-does-the-audience-mismatch-invariant-fail-open.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-aaif-credential-binding-after-a-delegated-re-sign-and-how-does-the-audience-mismatch-invariant-fail-open.warrant.json
# Markdown SHA-256:   4d3f491b309169a41b0cfa221b71f4e2d4c08d930315c7a4f1e8e4f303d05003
# Code AST SHA-256:   403cab00dc6ef4a904c879992dbd81bafdf843b6a03134b2584a25b57349953f
# Verified Classes:   CredentialBindingError, AAIFCredential
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CredentialBindingError(RuntimeError):
    """Raised when an AAIF delegated credential violates the monotonic-authority invariant."""


@dataclass(frozen=True)
class AAIFCredential:
    subject: str
    audience: str          # the VERIFIER, not the presenter
    scope: FrozenSet[str]
    expires_at: float
    actor_chain: tuple = field(default=())   # signed hops, root-first
    signed: bool = True


def verify_delegation(cred: AAIFCredential, verifier: str, now: float,
                      parent: AAIFCredential | None = None) -> None:
    if not cred.signed:
        raise CredentialBindingError("actor chain not covered by signature")
    if cred.audience != verifier:
        # audience must name the verifier; aud==self tautology is the failure mode
        raise CredentialBindingError(
            f"audience mismatch: cred.aud={cred.audience!r} verifier={verifier!r}"
        )
    if cred.expires_at <= now:
        raise CredentialBindingError("credential expired")
    if parent is not None:
        if not cred.scope.issubset(parent.scope):
            raise CredentialBindingError(
                f"scope escalation: child={sorted(cred.scope)} parent={sorted(parent.scope)}"
            )
        if cred.expires_at > parent.expires_at:
            raise CredentialBindingError("child outlives parent warrant")
        if not cred.actor_chain or cred.actor_chain[-1] != parent.subject:
            raise CredentialBindingError("broken actor chain: last hop != parent subject")
