# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-aaif-credential-whose-scope-chain-has-been-silently-widened-by-a-re-issuance-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-aaif-credential-whose-scope-chain-has-been-silently-widened-by-a-re-issuance-hop.warrant.json
# Markdown SHA-256:   879dba0ce38944159c93a8961466b93e09bb0baa0ee541b20d1273b6dc8c52ab
# Code AST SHA-256:   2a55765ed6654684dd9fb4733aa38bc3c6be764196f18a9cfe48ba0cd23b4051
# Verified Classes:   ScopeWideningError, Credential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ScopeWideningError(RuntimeError):
    """Raised when a delegated AAIF credential's effective scope exceeds the
    composed intersection of its delegation chain."""


@dataclass
class Credential:
    issuer: str
    subject: str
    scope: frozenset[str]
    constraints: dict = field(default_factory=dict)
    parent: Optional["Credential"] = None
    signature_valid: bool = True


def _refine(scope: frozenset[str], constraints: dict) -> frozenset[str]:
    """Fold constraints into scope. A scope string unsatisfiable under the
    credential's own constraints is dropped; if any string is dropped, the
    credential is malformed and the caller must reject."""
    prefix = constraints.get("path_prefix")
    if prefix is None:
        return scope
    refined = set()
    for s in scope:
        # scope strings of form "fs:read:<path>" must lie under prefix
        parts = s.split(":", 2)
        if len(parts) == 3 and parts[0] == "fs" and parts[1] == "read":
            if parts[2].startswith(prefix):
                refined.add(s)
            # else: silently dropped -> caller detects via set difference
        else:
            refined.add(s)
    return frozenset(refined)


def validate_chain(leaf: Credential) -> frozenset[str]:
    """Return the effective scope the leaf may honor, or raise."""
    chain: list[Credential] = []
    node: Optional[Credential] = leaf
    while node is not None:
        chain.append(node)
        node = node.parent
    chain.reverse()  # root first

    for cred in chain:
        if not cred.signature_valid:
            raise ScopeWideningError(
                f"invalid signature at issuer={cred.issuer} subject={cred.subject}"
            )

    # Link integrity: each child's parent must be issued by the child's issuer.
    for parent, child in zip(chain, chain[1:]):
        if child.issuer != parent.subject:
            raise ScopeWideningError(
                f"broken chain link: {child.issuer} != {parent.subject}"
            )

    # Constraint refinement: reject if constraints drop any declared scope string.
    for cred in chain:
        refined = _refine(cred.scope, cred.constraints)
        if refined != cred.scope:
            raise ScopeWideningError(
                f"scope unsatisfiable under own constraints at issuer={cred.issuer}: "
                f"declared={sorted(cred.scope)} admitted={sorted(refined)}"
            )

    # Composed intersection.
    composed = chain[0].scope
    for cred in chain[1:]:
        composed = composed & cred.scope

    # The leaf's declared scope must equal the composed intersection.
    if leaf.scope != composed:
        widened = leaf.scope - composed
        raise ScopeWideningError(
            f"scope widened: leaf={leaf.subject} declared={sorted(leaf.scope)} "
            f"composed={sorted(composed)} unauthorized={sorted(widened)}"
        )

    return composed


def authorize(leaf: Credential, capability: str) -> None:
    effective = validate_chain(leaf)
    if capability not in effective:
        raise ScopeWideningError(
            f"capability {capability!r} not in effective scope {sorted(effective)}"
        )
