# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-delegated-capability-token-whose-audience-field-names-a-sibling-instance-rather-than-itself.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-delegated-capability-token-whose-audience-field-names-a-sibling-instance-rather-than-itself.warrant.json
# Markdown SHA-256:   116d8509fd5c67ccc226561e7ca104d1bbb68c26567fe75d4060b8a9d1b03793
# Code AST SHA-256:   30a05979fc8ab82db695538047f6c4e6ce748f2236a123441389ad6cf99c8776
# Verified Classes:   AudienceScopeMismatch, DelegationWarrantMissing, CapabilityToken
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Optional


class AudienceScopeMismatch(RuntimeError):
    """Raised when a capability token's audience does not name the verifying instance
    and the instance holds no delegation warrant covering the requested scope."""
    pass


class DelegationWarrantMissing(RuntimeError):
    """Raised when a forwarded token lacks a may_delegate claim or the forwarder's
    delegation chain to this instance is broken."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    jti: str
    iss: str
    aud: str
    scope: FrozenSet[str]
    may_delegate: bool = False
    parent_jti: Optional[str] = None


def authorize_execution(
    token: CapabilityToken,
    self_id: str,
    requested_scope: FrozenSet[str],
    held_warrants: FrozenSet[str],
    signature_ok: bool,
    not_expired: bool,
    received_via_forward: bool = False,
) -> None:
    if not signature_ok:
        raise AudienceScopeMismatch(f"signature invalid for token {token.jti}")
    if not not_expired:
        raise AudienceScopeMismatch(f"token {token.jti} expired")

    # The check that makes the others meaningful.
    if token.aud != self_id:
        if not (token.scope & held_warrants):
            raise AudienceScopeMismatch(
                f"token {token.jti} audience={token.aud!r} != self={self_id!r}; "
                f"requested scope {sorted(requested_scope)} not covered by held warrants "
                f"{sorted(held_warrants)}; refusing to treat foreign audience as bearer"
            )
        # A warrant exists, but it does not authorize *using* the foreign token.
        # The caller must re-mint with aud=self_id and parent_jti=token.jti.
        raise AudienceScopeMismatch(
            f"token {token.jti} audience={token.aud!r} != self={self_id!r}; "
            f"warrant present — re-mint required, do not execute foreign token"
        )

    if received_via_forward and not token.may_delegate:
        raise DelegationWarrantMissing(
            f"token {token.jti} forwarded to {self_id!r} but carries no may_delegate claim; "
            f"forwarder {token.iss!r} had no authority to re-delegate"
        )

    if not requested_scope.issubset(token.scope):
        raise AudienceScopeMismatch(
            f"requested scope {sorted(requested_scope)} not subset of "
            f"token scope {sorted(token.scope)}"
        )
