# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-delegated-aaif-credential-s-scope-as-narrower-than-its-issuer-s-runtime-authorization-and-never-wider.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-delegated-aaif-credential-s-scope-as-narrower-than-its-issuer-s-runtime-authorization-and-never-wider.warrant.json
# Markdown SHA-256:   7efc607fdb803df93d619020e2fa4fb212951aab6fb70b9636b2498fa0ef01ab
# Code AST SHA-256:   0ff43f82faa480b5afe4fa0424be4b97dcc0278c909a0ff61a17b255f7864526
# Verified Classes:   ScopeInflationError, AmbiguousScopeGrammarError, DelegatedCredential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeInflationError(RuntimeError):
    """Raised when a delegate attempts an action outside its encoded credential scope."""
    pass


class AmbiguousScopeGrammarError(RuntimeError):
    """Raised when the credential scope uses prefix/glob semantics that cannot be safely bounded."""
    pass


@dataclass(frozen=True)
class DelegatedCredential:
    issuer: str
    # Closed enumeration of exact resource identifiers. No prefixes, no globs.
    encoded_scope: FrozenSet[str] = field(default_factory=frozenset)
    grammar: str = "exact"

    def grants(self, resource_id: str) -> bool:
        if self.grammar != "exact":
            # Fail-closed: ambiguous grammar cannot bound the intersection.
            raise AmbiguousScopeGrammarError(
                f"credential from {self.issuer} uses grammar={self.grammar!r}; "
                "cannot evaluate membership safely"
            )
        return resource_id in self.encoded_scope


def authorize_action(
    credential: DelegatedCredential,
    resource_id: str,
    issuer_runtime_authority: FrozenSet[str],
) -> None:
    """
    Enforce the intersection bound. The issuer's runtime authority is accepted
    only to *document* the gap on failure; it must never widen the decision.
    """
    if not credential.grants(resource_id):
        # Note: issuer_runtime_authority is deliberately NOT consulted as a grant.
        issuer_could = resource_id in issuer_runtime_authority
        raise ScopeInflationError(
            f"resource {resource_id!r} not in encoded scope of credential "
            f"issued by {credential.issuer}; "
            f"issuer_runtime_authority_covers_it={issuer_could} "
            f"(issuer authority does not propagate to delegate)"
        )
    # authorized: resource_id is a literal member of the encoded scope


def guarded_retry(
    credential: DelegatedCredential,
    resource_id: str,
    issuer_runtime_authority: FrozenSet[str],
    rederive_from_issuer_manifest: bool,
) -> None:
    """
    Retry path. Re-deriving scope from the issuer manifest is the inflation vector;
    reject it explicitly rather than silently widening.
    """
    if rederive_from_issuer_manifest:
        raise ScopeInflationError(
            "retry attempted to re-derive scope from issuer manifest; "
            "delegate scope must be read only from the credential"
        )
    authorize_action(credential, resource_id, issuer_runtime_authority)
