# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-scope-escalation-leakage-when-an-aaif-delegated-credential-is-re-minted-across-a-sub-agent-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-scope-escalation-leakage-when-an-aaif-delegated-credential-is-re-minted-across-a-sub-agent-hop.warrant.json
# Markdown SHA-256:   13e6e4bbc591d67ea184b420b4faac4565e9377ab6bb08d65960af9b1f32c8fd
# Code AST SHA-256:   1397f11f3dc8948d87b892d77ee70a68c9183a8053fc7c3b5402dc16f8ca5278
# Verified Classes:   ScopeEscalationError, Credential
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ScopeEscalationError(RuntimeError):
    """Raised when a delegated credential's effective surface exceeds its parent's."""


@dataclass(frozen=True)
class Credential:
    cid: str
    parent: Optional[str]
    scope: frozenset
    resource: str                 # glob pattern, verifier-semantics
    constraints: dict = field(default_factory=dict)
    may_redelegate: bool = False
    revoked: bool = False


def effective_surface(cred: Credential, chain: dict) -> dict:
    """Compute the meet of a credential's surface with every ancestor's, under verifier semantics."""
    surface = {
        "scope": set(cred.scope),
        "resource": cred.resource,
        "constraints": dict(cred.constraints),
        "may_redelegate": cred.may_redelegate,
    }
    cur = cred
    seen = set()
    while cur.parent is not None:
        if cur.cid in seen:
            raise ScopeEscalationError(f"cycle in delegation chain at {cur.cid}")
        seen.add(cur.cid)
        parent = chain.get(cur.parent)
        if parent is None:
            raise ScopeEscalationError(
                f"unresolvable ancestor {cur.parent} for {cur.cid}; fail-closed"
            )
        if parent.revoked:
            raise ScopeEscalationError(f"ancestor {parent.cid} revoked; deny {cred.cid}")
        # scope: set intersection
        surface["scope"] &= set(parent.scope)
        # resource: must narrow under the verifier's matcher, not nominal glob algebra
        if not _resource_narrows(surface["resource"], parent.resource):
            raise ScopeEscalationError(
                f"resource {surface['resource']!r} does not narrow parent {parent.resource!r}"
            )
        # constraints: conjunction — child may tighten, never drop or loosen
        for k, v in parent.constraints.items():
            if k not in surface["constraints"]:
                raise ScopeEscalationError(f"constraint {k!r} dropped from ancestor")
        # delegation flag: cannot be widened
        if surface["may_redelegate"] and not parent.may_redelegate:
            raise ScopeEscalationError("may_redelegate widened relative to ancestor")
        cur = parent
    return surface


def _resource_narrows(child: str, parent: str) -> bool:
    """Verifier-authoritative check: every path matching child must match parent."""
    # In production: delegate to the same matcher the resource server uses.
    # Here: conservative prefix check — reject anything not provably narrower.
    if child == parent:
        return True
    if child.startswith(parent.rstrip("*").rstrip("/") + "/") and "*" not in child:
        return True
    return False


def authorize(cred: Credential, chain: dict, requested_path: str) -> bool:
    surface = effective_surface(cred, chain)
    if not _resource_narrows(requested_path, surface["resource"]):
        raise ScopeEscalationError(
            f"path {requested_path!r} outside effective surface {surface['resource']!r}"
        )
    return True
