# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-honor-a-delegated-capability-whose-scope-was-attenuated-by-a-peer-but-whose-provenance-chain-was-not.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-honor-a-delegated-capability-whose-scope-was-attenuated-by-a-peer-but-whose-provenance-chain-was-not.warrant.json
# Markdown SHA-256:   bf82b573fe47892e3ea38b60d1e952efc9492fcfa753b6dc1f37d6d5ad135eec
# Code AST SHA-256:   a9f2f654a5b7a32d6d3dc1ce584c7fe00efb3a2e861bbbfa174daffe73f76f1d
# Verified Classes:   UnattestedAttenuationError, Scope, Provenance, DelegationEnvelope
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnattestedAttenuationError(RuntimeError):
    """Raised when a delegation narrows scope without re-attesting the narrowing."""


@dataclass(frozen=True)
class Scope:
    verb: str
    resource_prefix: str
    budget: int
    ttl: int

    def is_semantic_subset_of(self, other: "Scope") -> bool:
        verb_ok = self.verb in _VERB_LATTICE.get(other.verb, set())
        resource_ok = self.resource_prefix.startswith(other.resource_prefix)
        return (
            verb_ok
            and resource_ok
            and self.budget <= other.budget
            and self.ttl <= other.ttl
        )


_VERB_LATTICE = {
    "write": {"write", "read"},
    "read": {"read"},
    "admin": {"admin", "write", "read"},
}


@dataclass(frozen=True)
class Provenance:
    attested_scope: Scope
    signer: str
    signature: bytes
    # signature covers attested_scope only; it does NOT cover any narrowed scope


@dataclass(frozen=True)
class DelegationEnvelope:
    effective_scope: Scope
    provenance: Provenance
    narrow_signature: Optional[bytes]  # signature over effective_scope, chained to provenance


def verify_delegation(env: DelegationEnvelope, trusted_signers: set[str]) -> Scope:
    prov = env.provenance
    if prov.signer not in trusted_signers:
        raise UnattestedAttenuationError(
            f"provenance signer {prov.signer!r} not trusted"
        )
    if not prov.signature:
        raise UnattestedAttenuationError("provenance artifact is unsigned")

    attested = prov.attested_scope
    effective = env.effective_scope

    if effective == attested:
        return effective

    if not effective.is_semantic_subset_of(attested):
        raise UnattestedAttenuationError(
            f"effective scope {effective} is not a subset of attested {attested}; "
            "possible scope escalation"
        )

    # Narrowing occurred. It MUST be attested by a chained signature over the
    # effective scope, or the chain does not bind the narrowing and a sibling
    # hop can present the same attested scope with a different effective scope.
    if env.narrow_signature is None:
        raise UnattestedAttenuationError(
            f"scope narrowed from {attested} to {effective} but narrowing is "
            "unattested; refusing to execute against a decoupled capability"
        )

    return effective


def handle_handoff(env: DelegationEnvelope, trusted_signers: set[str]) -> Scope:
    try:
        return verify_delegation(env, trusted_signers)
    except UnattestedAttenuationError:
        # Propagate as hard failure so the delegator learns its envelope is
        # malformed; do not downgrade to a warning.
        raise
