# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-chain-has-silently-widened.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-chain-has-silently-widened.warrant.json
# Markdown SHA-256:   63c0ac37844def4671568d9458b9154b9bb3b036fb116ea36a90c828ab4baf70
# Code AST SHA-256:   bb3fa078d68e7407ccdf77acd916f7c6c5f9aee6ba8ab90cb02fe1416c9be623
# Verified Classes:   ResolverDisagreement, ScopePin, DelegatedToken, Verifier
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import unicodedata
from dataclasses import dataclass
from typing import FrozenSet


class ResolverDisagreement(RuntimeError):
    """Raised when a delegated token's scope cannot be bounded at the leaf verifier."""
    pass


@dataclass(frozen=True)
class ScopePin:
    grammar_id: str
    normalization: str          # e.g. "nfc", "nfd", "none"
    audience: FrozenSet[str]


@dataclass(frozen=True)
class DelegatedToken:
    scope_atom: str
    pin: ScopePin
    ttl_seconds: int


@dataclass(frozen=True)
class Verifier:
    grammar_id: str
    normalization: str
    tenant_namespace: str

    def normalize(self, path: str) -> str:
        # Collapse ".." segments and apply Unicode normalization.
        parts = []
        for seg in path.split("/"):
            if seg == "..":
                if parts:
                    parts.pop()
            elif seg and seg != ".":
                parts.append(seg)
        joined = "/" + "/".join(parts)
        if self.normalization == "nfc":
            return unicodedata.normalize("NFC", joined)
        if self.normalization == "nfd":
            return unicodedata.normalize("NFD", joined)
        return joined


def safe_to_present(token: DelegatedToken, verifier: Verifier, candidate_path: str) -> bool:
    if token.ttl_seconds <= 0:
        return False
    if verifier.grammar_id != token.pin.grammar_id:
        return False
    if verifier.normalization != token.pin.normalization:
        return False
    if verifier.tenant_namespace not in token.pin.audience:
        return False
    # The leaf's candidate must be a fixed point of the verifier's normalizer.
    if verifier.normalize(candidate_path) != candidate_path:
        return False
    return True


def present_credential(token: DelegatedToken, verifier: Verifier, candidate_path: str) -> str:
    if not safe_to_present(token, verifier, candidate_path):
        raise ResolverDisagreement(
            f"refusing to present token scope={token.scope_atom!r} to verifier "
            f"grammar={verifier.grammar_id!r} norm={verifier.normalization!r} "
            f"for path={candidate_path!r}: resolver identity not pinned or path "
            f"not a fixed point of verifier normalizer"
        )
    return verifier.normalize(candidate_path)


# Observed failure reproduction:
tok = DelegatedToken(
    scope_atom="fs:read:/tenant/acme/*",
    pin=ScopePin(grammar_id="aaif-glob-v2", normalization="nfc", audience=frozenset({"storage"})),
    ttl_seconds=300,
)
ver = Verifier(grammar_id="aaif-glob-v2", normalization="nfc", tenant_namespace="storage")

# This call refuses instead of silently crossing the tenant boundary.
present_credential(tok, ver, "/tenant/acme/../beta/secrets")
