# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-was-silently-widened-by-a-re-issuing-parent.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-was-silently-widened-by-a-re-issuing-parent.warrant.json
# Markdown SHA-256:   6858e14ad47ca8a88a24d46365eebff5e5100e2c7349af266dba11231ada3945
# Code AST SHA-256:   e274c46066a544f881b02ef3c84fe82e1571ce17c951697e769803e8972df726
# Verified Classes:   DelegationUnverifiable, Credential
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationUnverifiable(RuntimeError):
    """Raised when a delegated credential cannot be grounded in the issuer's ledger."""
    pass


@dataclass(frozen=True)
class Credential:
    credential_id: str
    parent_credential_id: Optional[str]
    scope: frozenset[str]
    nbf: float
    exp: float
    issued_by_authority: bool  # True iff resolvable in issuance ledger


def validate_delegation(
    child: Credential,
    chain: dict[str, Credential],
    revoked: frozenset[str],
    now: float,
    scope_subset,
    mutating: bool,
) -> None:
    """Enforce the delegated-credential invariant before any side-effecting action.

    scope_subset(child_scope, parent_scope) -> bool must implement the deployment's
    semantic scope algebra; lexical subset is insufficient.
    """
    cursor: Optional[Credential] = child
    while cursor is not None:
        if not cursor.issued_by_authority:
            raise DelegationUnverifiable(
                f"credential {cursor.credential_id!r} is a re-issued token "
                f"not resolvable in the issuance ledger; scope-subset cannot be grounded"
            )
        if cursor.credential_id in revoked:
            raise DelegationUnverifiable(
                f"credential {cursor.credential_id!r} is revoked at evaluation time"
            )
        if not (cursor.nbf <= now <= cursor.exp):
            raise DelegationUnverifiable(
                f"credential {cursor.credential_id!r} outside validity window at {now}"
            )

        parent_id = cursor.parent_credential_id
        if parent_id is None:
            return  # reached a root-issued credential; chain grounded

        parent = chain.get(parent_id)
        if parent is None:
            if mutating:
                raise DelegationUnverifiable(
                    f"parent {parent_id!r} of {cursor.credential_id!r} unresolvable; "
                    f"refusing mutating action with unverifiable delegation chain"
                )
            return  # non-mutating: log and proceed under caller's policy

        if not scope_subset(cursor.scope, parent.scope):
            raise DelegationUnverifiable(
                f"scope of {cursor.credential_id!r} is not a semantic subset of "
                f"parent {parent_id!r}; delegation widened beyond grant"
            )
        if cursor.exp > parent.exp or cursor.nbf < parent.nbf:
            raise DelegationUnverifiable(
                f"validity window of {cursor.credential_id!r} exceeds parent {parent_id!r}"
            )
        cursor = parent
