# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-skill-whose-signature-verifies-but-whose-bound-executable-has-been-swapped-between-attestation-and-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-skill-whose-signature-verifies-but-whose-bound-executable-has-been-swapped-between-attestation-and-invocation.warrant.json
# Markdown SHA-256:   5281a2b1a65d1ec09f5416bcd0411134196429653cdc6182748e77f93aeb71d7
# Code AST SHA-256:   3834942dcb08b8e83b560d6b4abeacec256c459bbd355ea3bf2981acc346a0cd
# Verified Classes:   SkillIntegrityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import os


class SkillIntegrityError(RuntimeError):
    """Raised when the artifact bound for execution is not the artifact that was verified."""
    pass


def verify_and_bind(manifest: dict, open_artifact) -> int:
    """
    Verify a signed skill manifest and return an *open file descriptor* to the
    exact bytes that were digest-checked. Callers MUST execute via this fd
    (e.g. /proc/self/fd/N) and MUST NOT re-resolve manifest['artifact_path'].

    open_artifact: callable(path) -> (fd, path_used)
    """
    if not manifest.get("signature_valid"):
        raise SkillIntegrityError("manifest signature invalid; refusing to bind")

    fd, path_used = open_artifact(manifest["artifact_path"])
    try:
        h = hashlib.sha256()
        while chunk := os.read(fd, 65536):
            h.update(chunk)
        os.lseek(fd, 0, os.SEEK_SET)
        actual = "sha256:" + h.hexdigest()
    except Exception:
        os.close(fd)
        raise

    if actual != manifest["artifact_digest"]:
        os.close(fd)
        raise SkillIntegrityError(
            f"artifact digest mismatch: expected {manifest['artifact_digest']}, "
            f"got {actual} from {path_used}"
        )

    # Invariant: the fd returned here is the only legitimate execution handle.
    # Any code path that instead re-opens manifest['artifact_path'] re-introduces
    # TOCTOU drift and must be rejected by the caller.
    if not manifest.get("content_addressed", False):
        # Name-derived path: safe only because we hold the fd, but flag it so the
        # executor never falls back to path re-resolution.
        manifest["_binding"] = "descriptor_only"
    return fd


def invoke_skill(manifest: dict, open_artifact, executor) -> None:
    fd = verify_and_bind(manifest, open_artifact)
    try:
        # executor receives the fd; it must not receive the path string.
        executor(fd=fd, argv=manifest.get("argv", []))
    finally:
        os.close(fd)
