# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-proof-of-possession-key-substitution-from-silently-widening-delegated-authority-in-agent-to-agent-oauth-2-1-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-proof-of-possession-key-substitution-from-silently-widening-delegated-authority-in-agent-to-agent-oauth-2-1-chains.warrant.json
# Markdown SHA-256:   7e82feb55f95adb2161d605f7d5b54b590f5d8f2edbd6bef4cf4b813cbcaa188
# Code AST SHA-256:   cb2ee982c8ef024c33f719822c1f91f56dc36158d10480708463f40fccf77308
# Verified Classes:   AuthorityWideningError, BoundToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class AuthorityWideningError(RuntimeError):
    """Raised when a delegated token's resource or scope set exceeds its parent's."""
    pass


@dataclass(frozen=True)
class BoundToken:
    subject: str
    cnf_jkt: str
    resource: FrozenSet[str]
    scope: FrozenSet[str]


def validate_delegation(parent: BoundToken, child: BoundToken) -> None:
    # PoP binding must move to the child presenter, not stay on the parent.
    if child.cnf_jkt == parent.cnf_jkt:
        raise AuthorityWideningError(
            f"child token retains parent PoP key {parent.cnf_jkt!r}; "
            "delegation requires re-binding to the worker's key"
        )

    widened_resources = child.resource - parent.resource
    if widened_resources:
        raise AuthorityWideningError(
            f"resource widening across delegation: child grants "
            f"{sorted(widened_resources)} not present in parent {sorted(parent.resource)}"
        )

    widened_scopes = child.scope - parent.scope
    if widened_scopes:
        raise AuthorityWideningError(
            f"scope widening across delegation: child grants "
            f"{sorted(widened_scopes)} not present in parent {sorted(parent.scope)}"
        )


def mint_child_token(
    parent: BoundToken,
    worker_jkt: str,
    requested_resource: FrozenSet[str] | None,
    requested_scope: FrozenSet[str],
) -> BoundToken:
    # Absence of `resource` must mean inherit, never "server default audience".
    effective_resource = parent.resource if requested_resource is None else requested_resource
    child = BoundToken(
        subject=f"{parent.subject}/delegate",
        cnf_jkt=worker_jkt,
        resource=frozenset(effective_resource),
        scope=frozenset(requested_scope),
    )
    validate_delegation(parent, child)
    return child
