# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-skill-injection-attack-surfaces-in-dynamically-loaded-agent-skills-and-plugin-registries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-skill-injection-attack-surfaces-in-dynamically-loaded-agent-skills-and-plugin-registries.warrant.json
# Markdown SHA-256:   7b5400a04616bd3d48c06135c191b4e3ca2f84759d6ae1bf8fb143551fec354c
# Code AST SHA-256:   11ad2daf14fdb2147a105c6d09183dac35998e19a411ecd4e986a6d6c022224f
# Verified Classes:   SkillBindingError, Authorization, ResolvedSkill
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SkillBindingError(RuntimeError):
    """Raised when the resolved skill does not match the authorized identity.

    Covers: tag repointed to new content, capability ambiguity, trust root
    co-located with the mutable registry, and generation-counter mismatch.
    Every case is a violation of the invariant that the executed content
    digest equals the digest authorized at decision time.
    """


@dataclass(frozen=True)
class Authorization:
    name: str
    digest: str          # content digest captured at authorization time
    provenance_root: str  # trust root, must live outside the registry domain
    generation: int


@dataclass(frozen=True)
class ResolvedSkill:
    name: str
    content: bytes
    provenance_root: str
    generation: int
    registry_domain: str  # the domain that can mutate this registry


def _digest(content: bytes) -> str:
    return "sha256:" + hashlib.sha256(content).hexdigest()


def verify_binding(auth: Authorization, resolved: ResolvedSkill) -> None:
    # 1. Name must match; a name mismatch is a routing bug, not injection,
    #    but it must still fail closed.
    if auth.name != resolved.name:
        raise SkillBindingError(
            f"name mismatch: authorized {auth.name!r}, resolved {resolved.name!r}"
        )

    # 2. Trust root must not be writable by the registry principal. A chain
    #    that roots in the mutable store is self-referential and worthless.
    if resolved.provenance_root == resolved.registry_domain:
        raise SkillBindingError(
            f"trust root {resolved.provenance_root!r} is co-located with mutable "
            f"registry domain {resolved.registry_domain!r}; signature is self-referential"
        )

    # 3. Generation counter must match, closing the refresh interleaving window
    #    where policy reads generation N and execution reads N+1.
    if auth.generation != resolved.generation:
        raise SkillBindingError(
            f"generation drift: authorized gen {auth.generation}, "
            f"resolved gen {resolved.generation}; refusing to execute under stale authorization"
        )

    # 4. The core invariant: content digest must equal the authorized digest.
    #    This is the check that mutable tags and capability collisions defeat.
    actual = _digest(resolved.content)
    if actual != auth.digest:
        raise SkillBindingError(
            f"digest divergence for {auth.name!r}: authorized {auth.digest}, "
            f"resolved {actual}; tag was repointed or content substituted"
        )


def resolve_capability(candidates: list[ResolvedSkill], tag: str) -> ResolvedSkill:
    """Fail closed on capability ambiguity rather than taking first match."""
    if not candidates:
        raise SkillBindingError(f"no provider registered for capability {tag!r}")
    if len(candidates) > 1:
        providers = ", ".join(c.name for c in candidates)
        raise SkillBindingError(
            f"capability {tag!r} claimed by multiple providers ({providers}); "
            f"first-match resolution is the dependency-confusion primitive"
        )
    return candidates[0]
