# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-delegated-authorization-token-exchange-has-silently-downgraded-scope-in-aaif-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-delegated-authorization-token-exchange-has-silently-downgraded-scope-in-aaif-agent-handoffs.warrant.json
# Markdown SHA-256:   49db98b522b978d2f2b2c02e7ad2841f3b4685a3fbc91296994efc31c886c2d4
# Code AST SHA-256:   080cf80dcc0122afad25473fb84b867ac98ca6f335c1f6ccabc28c53a7327e39
# Verified Classes:   DelegationScopeInflation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DelegationScopeInflation(RuntimeError):
    """Raised when a derived AAIF token carries scopes absent from its ancestor grant."""
    pass


def verify_derived_token(derived_token, ancestor_token, require_origin_map=True):
    """
    Enforce containment: scopes(derived) must be a subset of scopes(ancestor).
    Signature validity is assumed already checked upstream; this is the
    containment check that signatures cannot provide.
    """
    derived_scopes = set(derived_token.scopes)
    ancestor_scopes = set(ancestor_token.scopes)

    inflated = derived_scopes - ancestor_scopes
    if inflated:
        raise DelegationScopeInflation(
            f"derived token {derived_token.id} (minted by {derived_token.issuer}) "
            f"carries scopes {sorted(inflated)} not present in ancestor grant "
            f"{ancestor_token.id} held by {ancestor_token.subject}. "
            f"Derivation hop {derived_token.derivation_depth} widened authority silently."
        )

    if require_origin_map:
        origin = getattr(derived_token, "scope_origin", None)
        if origin is None:
            raise DelegationScopeInflation(
                f"derived token {derived_token.id} missing required scope_origin map; "
                f"containment cannot be attributed to a specific hop."
            )
        for scope in derived_scopes:
            hop = origin.get(scope)
            if hop is None:
                raise DelegationScopeInflation(
                    f"scope {scope!r} in token {derived_token.id} has no recorded origin hop."
                )
            if scope not in ancestor_scopes and hop != ancestor_token.subject:
                raise DelegationScopeInflation(
                    f"scope {scope!r} origin {hop!r} does not match ancestor subject "
                    f"{ancestor_token.subject!r}; token was widened at derivation."
                )

    return True
