# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-delegated-capability-attenuation-breach-when-a-federated-peer-re-signs-a-warrant-with-widened-scope-during-cross-org-tru.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-delegated-capability-attenuation-breach-when-a-federated-peer-re-signs-a-warrant-with-widened-scope-during-cross-org-tru.warrant.json
# Markdown SHA-256:   e53f02ac6438350a5f90bb936a436ef8618eb66fe4140f242ff33558977aac77
# Code AST SHA-256:   41f438ee69df514cacdddf2eb917bb399b86e1f016ce750f2e41cbbfc5f3499c
# Verified Classes:   ScopeAttenuationBreach
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ScopeAttenuationBreach(RuntimeError):
    """Raised when a derived warrant's scope is not a literal subset of its
    signature-verified parent scope. Indicates either a widening transform
    (glob->literal) applied during re-signing, or a subset check run against
    a non-authoritative scope source (manifest, cache, negotiation message)."""
    pass


def issue_derived_warrant(parent_token, child_scope, verifier):
    # 1. Anchor: re-verify the parent token and read scope from signed claims,
    #    NOT from any session cache or negotiation manifest.
    parent_claims = verifier.verify_and_decode(parent_token)
    parent_scope = frozenset(parent_claims["scope"])  # signed literals only

    # 2. Closed scope algebra: every child element must be a literal present
    #    in the signed parent scope. No glob expansion, no role mapping here.
    for element in child_scope:
        if not is_literal_scope_element(element):
            raise ScopeAttenuationBreach(
                f"non-literal scope element {element!r} cannot be attenuated; "
                f"patterns must be expanded and signed by the issuer, not the consumer"
            )
        if element not in parent_scope:
            raise ScopeAttenuationBreach(
                f"scope element {element!r} is not a subset of signed parent scope "
                f"{sorted(parent_scope)}; refusing to issue derived warrant "
                f"(possible glob-widening during negotiation)"
            )

    # 3. Monotone derivation: depth decrements, scope only shrinks.
    if parent_claims["depth"] <= 0:
        raise ScopeAttenuationBreach(
            "delegation depth budget exhausted; cannot derive further warrants"
        )

    return sign_child(
        issuer=parent_claims["audience"],
        scope=frozenset(child_scope),
        depth=parent_claims["depth"] - 1,
        parent_digest=verifier.digest(parent_token),
    )


def is_literal_scope_element(element):
    # Reject wildcard/glob/pattern forms outright at the derivation boundary.
    return not any(ch in element for ch in "*?[]")
