# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-skill-loader-accept-an-attested-manifest-yet-still-execute-injected-code-after-sandbox-rehydration.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-skill-loader-accept-an-attested-manifest-yet-still-execute-injected-code-after-sandbox-rehydration.warrant.json
# Markdown SHA-256:   1ff5a4e9dc08f605e8b76828ef1f48b445299a50c7326f85679d546cc70b5d7c
# Code AST SHA-256:   01ceed0b66a9ba659d9666875599e4d6b6cbf3d1c1f655a7a07fd60d95f7fb90
# Verified Classes:   AttestationRehydrationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import pickle
import subprocess


class AttestationRehydrationError(RuntimeError):
    """Raised when a manifest is attested but rehydration escapes the declared capability set."""
    pass


ALLOWED_SYSCALLS = {"read", "write", "open", "close", "stat", "mmap", "brk"}


def verify_manifest(manifest: dict, publisher_key: bytes) -> bool:
    body = manifest["body"].encode()
    expected = hashlib.sha256(body + publisher_key).hexdigest()
    return expected == manifest["digest"]


def rehydrate_confined(artifact: bytes, declared_caps: set[str]) -> object:
    """
    Materialize the artifact in a child process under a syscall filter seeded
    from declared_caps. Reject on any syscall outside the declared set.
    Never call pickle.load / yaml.load / torch.load in the loader's own space.
    """
    # Non-evaluating path is the only in-process-safe path.
    if artifact[:1] == b"{":
        import json
        return json.loads(artifact.decode())

    # Evaluating format: must be confined. Simulate the child result here.
    observed_syscalls = _run_confined_child(artifact)
    undeclared = observed_syscalls - declared_caps - ALLOWED_SYSCALLS
    if undeclared:
        raise AttestationRehydrationError(
            f"rehydration issued undeclared syscalls {sorted(undeclared)}; "
            f"declared={sorted(declared_caps)}"
        )
    return _load_nonedata(artifact)


def _run_confined_child(artifact: bytes) -> set[str]:
    # Placeholder: real implementation forks, applies seccomp, and traces syscalls.
    # A pickle __reduce__ payload would surface 'execve' or 'socket' here.
    return {"read", "write", "open", "execve"}


def _load_nonedata(artifact: bytes) -> object:
    return pickle.loads(artifact)


def load_skill(manifest: dict, artifact: bytes, publisher_key: bytes) -> object:
    if not verify_manifest(manifest, publisher_key):
        raise AttestationRehydrationError("manifest digest does not match publisher key")
    declared = set(manifest.get("capabilities", []))
    return rehydrate_confined(artifact, declared)
