# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-aaif-token-whose-capability-scope-was-silently-widened-by-a-re-attesting-intermediary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-aaif-token-whose-capability-scope-was-silently-widened-by-a-re-attesting-intermediary.warrant.json
# Markdown SHA-256:   af4328f9672fc22ef23387432cf0754ed984d0ab585bd033ea9fd81f9fcbc829
# Code AST SHA-256:   3270bda83e6529057fcc74256347d5854ceb7a124c8d5ed8fc06d4124d0bc0bf
# Verified Classes:   ScopeWideningError, DelegationToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ScopeWideningError(RuntimeError):
    """Raised when a delegated token's scope is not a subset of its parent's."""


@dataclass(frozen=True)
class DelegationToken:
    token_id: str
    issuer: str                 # key id of the signer
    parent_hash: str | None     # sha256 of parent token's canonical bytes, None for root
    scope: frozenset[str]
    signature: str              # opaque; assumed verified upstream

    def canonical_bytes(self) -> bytes:
        return (
            f"{self.token_id}|{self.issuer}|{self.parent_hash}|"
            f"{','.join(sorted(self.scope))}"
        ).encode()


def token_hash(tok: DelegationToken) -> str:
    return hashlib.sha256(tok.canonical_bytes()).hexdigest()


def verify_delegation_edge(
    child: DelegationToken,
    parent_lookup: dict[str, DelegationToken],
    notary_keys: frozenset[str],
) -> None:
    """
    Enforce the containment invariant at the receiving instance.

    For a notary-issued child, child.scope must be a subset of parent.scope.
    A notary may narrow or re-encode; it may not extend. Extension requires a
    fresh root-signed grant, which never references a parent.
    """
    if child.parent_hash is None:
        # Root grant; no containment to check. Root issuance is the principal's authority.
        return

    parent = parent_lookup.get(child.parent_hash)
    if parent is None:
        raise ScopeWideningError(
            f"token {child.token_id}: parent {child.parent_hash} not resolvable; "
            f"cannot verify containment"
        )

    # Recompute parent hash to ensure the referenced parent is the one we hold.
    if token_hash(parent) != child.parent_hash:
        raise ScopeWideningError(
            f"token {child.token_id}: parent hash mismatch — "
            f"referenced {child.parent_hash}, actual {token_hash(parent)}"
        )

    if child.issuer in notary_keys:
        widened = child.scope - parent.scope
        if widened:
            raise ScopeWideningError(
                f"token {child.token_id}: notary {child.issuer} widened scope "
                f"by {sorted(widened)}; parent scope was {sorted(parent.scope)}. "
                f"Extension requires a fresh root grant."
            )
    # Non-notary issuers are checked by the grantor path elsewhere; a non-notary
    # child that references a parent is itself a protocol violation.
    else:
        raise ScopeWideningError(
            f"token {child.token_id}: issuer {child.issuer} is not a registered "
            f"notary but emitted a child token; only notaries may re-attest"
        )


def admit_token(
    child: DelegationToken,
    parent_lookup: dict[str, DelegationToken],
    notary_keys: frozenset[str],
) -> frozenset[str]:
    """Return the effective scope the instance may execute under, or raise."""
    verify_delegation_edge(child, parent_lookup, notary_keys)
    return child.scope
