# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-scope-escalation-through-credential-re-delegation-in-aaif-when-the-attenuation-check-passes-but-the-audience-chain-is-forg.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-scope-escalation-through-credential-re-delegation-in-aaif-when-the-attenuation-check-passes-but-the-audience-chain-is-forg.warrant.json
# Markdown SHA-256:   2595a6c09a8bd22fc605a426e1958a775cfb1107cf39757de367bd8b7ed835d9
# Code AST SHA-256:   79b0eb015679bd301fb6917bc0a1824ad39ab0f26d7aa40a15a30a1895467b97
# Verified Classes:   LineageSpliceError, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class LineageSpliceError(RuntimeError):
    """Raised when a delegated warrant's audience lineage is not a single ancestor chain."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    audience: str
    scope: frozenset[str]
    expiry: int
    parent: Optional["Warrant"] = None
    federation_hop: bool = False


def validate_delegation(child: Warrant, now: int) -> None:
    if now >= child.expiry:
        raise LineageSpliceError(f"warrant expired at {child.expiry}, now={now}")

    parent = child.parent
    if parent is None:
        return  # root warrant, no lineage to check

    if not child.scope.issubset(parent.scope):
        raise LineageSpliceError(
            f"scope escalation: {sorted(child.scope)} not subset of {sorted(parent.scope)}"
        )
    if child.expiry > parent.expiry:
        raise LineageSpliceError(
            f"expiry escalation: child {child.expiry} > parent {parent.expiry}"
        )

    # The invariant most validators skip: issuer must equal the parent's audience,
    # unless this hop is an explicit federation boundary.
    if not child.federation_hop and child.issuer != parent.audience:
        raise LineageSpliceError(
            f"sibling splice: child.issuer={child.issuer!r} != parent.audience={parent.audience!r}"
        )

    # Two-hop check: the parent must itself be a legitimate child of the grandparent.
    grandparent = parent.parent
    if grandparent is not None and not parent.federation_hop:
        if parent.issuer != grandparent.audience:
            raise LineageSpliceError(
                "grandparent splice: parent.issuer="
                f"{parent.issuer!r} != grandparent.audience={grandparent.audience!r}"
            )


def demo() -> None:
    root = Warrant("principal", "orchestrator", frozenset({"read:repo", "write:repo"}), 1000)
    # Legitimate attenuation: orchestrator -> worker, scope shrinks.
    legit = Warrant("orchestrator", "worker", frozenset({"read:repo"}), 900, parent=root)
    validate_delegation(legit, now=500)

    # Forged splice: attacker claims orchestrator issued it, but parent.audience is "worker".
    forged = Warrant("orchestrator", "attacker", frozenset({"read:repo"}), 900, parent=legit)
    try:
        validate_delegation(forged, now=500)
    except LineageSpliceError as exc:
        print(f"rejected: {exc}")


if __name__ == "__main__":
    demo()
