# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-capability-grant-whose-scope-was-widened-by-a-peer-s-local-re-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-capability-grant-whose-scope-was-widened-by-a-peer-s-local-re-delegation.warrant.json
# Markdown SHA-256:   85a12033179744fce47e10348d0d36bb052677740da52d63c8763f18d0c741df
# Code AST SHA-256:   4746779016d58cf1bd06f80399023af7c6ccc01563d5c53f9260e7b77876b9d8
# Verified Classes:   FederatedScopeWideningError, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class FederatedScopeWideningError(RuntimeError):
    """Raised when a re-delegated warrant's effective scope cannot be proven
    a subset of the root grant under the root issuer's canonicalizer."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scope: str
    canonicalizer_id: str  # content-addressed id of the root's normalizer
    parent_scope: Optional[str]
    depth: int
    signature_valid: bool


def canonicalize(scope: str, canonicalizer_id: str) -> str:
    """Root-issuer canonical form. In production this dispatches to a pinned,
    versioned normalizer. Here we model git-ref normalization as the example."""
    if canonicalizer_id == "gitref-v1":
        s = scope.strip()
        if s.startswith("branch/"):
            s = "refs/heads/" + s[len("branch/"):]
        # resolve .. segments deterministically
        parts = []
        for seg in s.split("/"):
            if seg == "..":
                if parts:
                    parts.pop()
            elif seg and seg != ".":
                parts.append(seg)
        return "/".join(parts)
    raise FederatedScopeWideningError(f"unknown canonicalizer {canonicalizer_id!r}")


def is_subset(leaf: str, root: str, canonicalizer_id: str) -> bool:
    """Subset test performed in the ROOT's vocabulary, not the caller's."""
    leaf_c = canonicalize(leaf, canonicalizer_id)
    root_c = canonicalize(root, canonicalizer_id)
    if not root_c.endswith("*"):
        return leaf_c == root_c
    prefix = root_c[:-1]
    return leaf_c.startswith(prefix) and "/.." not in leaf_c


def accept_redelegated_warrant(
    leaf: Warrant, root: Warrant, root_canonicalizer_id: str
) -> None:
    if not leaf.signature_valid or not root.signature_valid:
        raise FederatedScopeWideningError("signature invalid somewhere in chain")
    if leaf.depth < 0:
        raise FederatedScopeWideningError("depth exhausted")
    if leaf.canonicalizer_id != root_canonicalizer_id:
        raise FederatedScopeWideningError(
            f"canonicalizer mismatch: leaf uses {leaf.canonicalizer_id!r}, "
            f"root requires {root_canonicalizer_id!r}; cannot prove subset-ness"
        )
    if not is_subset(leaf.scope, root.scope, root_canonicalizer_id):
        raise FederatedScopeWideningError(
            f"effective scope {leaf.scope!r} is not a subset of root "
            f"{root.scope!r} under {root_canonicalizer_id!r}"
        )


def execute_write(warrant: Warrant, target: str, root: Warrant) -> str:
    # Resolution MUST precede authorization and the resolved form MUST be executed.
    resolved = canonicalize(target, warrant.canonicalizer_id)
    accept_redelegated_warrant(warrant, root, root.canonicalizer_id)
    if not is_subset(resolved, root.scope, root.canonicalizer_id):
        raise FederatedScopeWideningError(
            f"resolved target {resolved!r} escapes root scope {root.scope!r}"
        )
    return resolved


# Reproduction of the observed escalation:
root = Warrant("orgA", "orgB", "branch/feature-*", "gitref-v1", None, 2, True)
leaf = Warrant("orgB", "orgC", "refs/heads/feature-*", "gitref-v1", root.scope, 1, True)

# This passes the naive chain check (signatures ok, depth ok, prefix ok)...
# ...but the resolved target escapes:
try:
    execute_write(leaf, "refs/heads/feature-x/../../../main", root)
except FederatedScopeWideningError as e:
    print("BLOCKED:", e)  # BLOCKED: resolved target 'refs/heads/main' escapes...
