# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-aaif-token-that-re-binds-the-subject-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-aaif-token-that-re-binds-the-subject-mid-chain.warrant.json
# Markdown SHA-256:   daa8478d67b1ffe7eebcfac974963bc68cc74c3cbcbdf22f103b30f6de9f15eb
# Code AST SHA-256:   335b0178fc9ede122fe40c757919ec59ae68d994372d0129ad481826034143e2
# Verified Classes:   SubjectRebindingError, ActClaim, DelegatedToken
# Defensive Guards:   7 fail-closed invariants (zero external deps)

# aaif_delegation.py
# Guardrail: reject AAIF delegated tokens whose subject was re-bound mid-chain.

from dataclasses import dataclass
from typing import Optional


class SubjectRebindingError(RuntimeError):
    """Raised when a delegated token's sub does not match the out-of-band expected subject,
    or when the act chain is non-contiguous (a hop promoted itself into sub)."""


@dataclass(frozen=True)
class ActClaim:
    sub: str
    aud: str
    may_act: Optional[str] = None


@dataclass(frozen=True)
class DelegatedToken:
    sub: str
    aud: str
    scope: frozenset
    act_chain: tuple  # ordered outermost -> innermost, each an ActClaim


def verify_delegation(
    token: DelegatedToken,
    expected_subject: Optional[str],
    expected_audience: str,
    expected_scope: frozenset,
    max_chain_depth: int = 8,
) -> None:
    # 1. Out-of-band subject must be present. Without it we cannot distinguish
    #    delegation from re-binding, so we refuse rather than guess.
    if expected_subject is None:
        raise SubjectRebindingError(
            "task envelope carries no task_binding.subject; "
            "cannot verify delegation provenance"
        )

    # 2. Audience and scope are necessary but NOT sufficient. Checked first only
    #    so that cheaper failures report before the expensive chain walk.
    if token.aud != expected_audience:
        raise SubjectRebindingError(
            f"audience mismatch: token.aud={token.aud!r} expected={expected_audience!r}"
        )
    if not token.scope <= expected_scope:
        raise SubjectRebindingError(
            f"scope escalation: token.scope={sorted(token.scope)} "
            f"exceeds expected={sorted(expected_scope)}"
        )

    # 3. The decisive check: sub must equal the out-of-band expected subject.
    #    A re-bound token passes every check above and fails here.
    if token.sub != expected_subject:
        raise SubjectRebindingError(
            f"subject re-binding detected: token.sub={token.sub!r} "
            f"expected original subject={expected_subject!r}; "
            f"refusing to act on a token whose principal was rewritten mid-chain"
        )

    # 4. Chain contiguity: each hop's actor must be the previous hop's audience,
    #    and the innermost link must terminate at the expected subject.
    if len(token.act_chain) > max_chain_depth:
        raise SubjectRebindingError(
            f"act chain depth {len(token.act_chain)} exceeds policy max {max_chain_depth}"
        )
    if not token.act_chain:
        # A token with no act chain claiming a human sub is a first-hop token,
        # not a delegation; accept only if sub itself is the expected subject
        # (already checked). Nothing more to walk.
        return

    prev_aud = token.sub
    for hop in reversed(token.act_chain):
        if hop.aud != prev_aud:
            raise SubjectRebindingError(
                f"non-contiguous act chain: hop.aud={hop.aud!r} "
                f"does not match previous subject/audience={prev_aud!r}"
            )
        prev_aud = hop.sub

    if prev_aud != expected_subject:
        raise SubjectRebindingError(
            f"act chain terminates at {prev_aud!r}, "
            f"not at expected subject {expected_subject!r}; "
            f"delegation provenance is broken"
        )
