# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trust-broker-replay-from-silently-widening-delegated-authority-across-org-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trust-broker-replay-from-silently-widening-delegated-authority-across-org-boundaries.warrant.json
# Markdown SHA-256:   4607b96b3cf89e76934387ad32f52b146ce146286876ee55c3c96ba63bab6e87
# Code AST SHA-256:   d14da56413f10b6496c8bc25ff05f1cda3e2da970c39e72b100f9d300a58c990
# Verified Classes:   FederationScopeWideningError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class FederationScopeWideningError(RuntimeError):
    """Raised when a re-minted warrant expands scope beyond its parent,
    or when a hop's local policy does not cover the warrant's claimed scope."""
    pass


def admit_warrant(warrant: dict, parent: dict | None, local_policy: dict) -> dict:
    # 1. Signature proves issuance, not authorization.
    if not warrant.get("sig_valid"):
        raise FederationScopeWideningError(f"warrant {warrant['id']} signature invalid")

    # 2. Re-mint on retry must be monotonic narrowing.
    if parent is not None:
        if not _is_subscope(warrant["scope"], parent["scope"]):
            raise FederationScopeWideningError(
                f"warrant {warrant['id']} widens scope beyond parent {parent['id']}: "
                f"{warrant['scope']} ⊄ {parent['scope']} — retry must be new request-id"
            )

    # 3. Every audience must be covered by local policy; no silent clamping.
    for aud in warrant["aud"]:
        if aud not in local_policy:
            raise FederationScopeWideningError(
                f"warrant {warrant['id']} targets audience {aud} with no local policy"
            )
        if not _scope_covered(warrant["scope"], local_policy[aud]):
            raise FederationScopeWideningError(
                f"warrant {warrant['id']} scope {warrant['scope']} not covered by "
                f"policy for {aud}; refusing rather than clamping"
            )

    # 4. Audit record carries the chain, not just the leaf.
    return {
        "request_id": warrant["request_id"],
        "chain": (parent["chain"] if parent else []) + [warrant["id"]],
        "admitted_scope": warrant["scope"],
    }


def _is_subscope(child: dict, parent: dict) -> bool:
    return all(parent.get(k) is not None and child.get(k, 0) <= parent[k]
               for k in parent if k.startswith("max_"))


def _scope_covered(scope: dict, policy: dict) -> bool:
    return all(k in policy and scope.get(k, 0) <= policy[k]
               for k in scope if k.startswith("max_"))
