# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-skill-injection-via-signed-tool-manifests-from-failing-at-the-capability-binding-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-skill-injection-via-signed-tool-manifests-from-failing-at-the-capability-binding-boundary.warrant.json
# Markdown SHA-256:   58fd3cb0ef84c29c413661f2d2a2aa5cb77fbd7f5775905ba9b41150d673b5ec
# Code AST SHA-256:   32eb03ae1405f2de690057d21e061cb094ec1f759e13fe9d695b50d2e5b5d1a3
# Verified Classes:   CapabilityBindingError, SignedManifestEntry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityBindingError(RuntimeError):
    """Raised when a signed tool manifest verifies but the invocation
    escapes the capability envelope the signer authorized."""
    pass


@dataclass(frozen=True)
class SignedManifestEntry:
    name: str
    schema: dict
    description: str
    endpoint: str
    capability_envelope: dict  # e.g. {"url": {"host_allowlist": ["api.internal"]}}
    signature: str

    @property
    def tool_hash(self) -> str:
        body = json.dumps(
            {"name": self.name, "schema": self.schema,
             "endpoint": self.endpoint,
             "capability_envelope": self.capability_envelope},
            sort_keys=True,
        ).encode()
        return hashlib.sha256(body).hexdigest()


def attest_invocation(
    entry: SignedManifestEntry,
    planned_tool_hash: str,
    arguments: dict,
    agent_warrant_tools: set[str],
    verify_signature,
    seen_arg_digests: set[str],
) -> str:
    # 1. signature must verify (necessary, never sufficient)
    if not verify_signature(entry):
        raise CapabilityBindingError("manifest signature invalid")

    # 2. content-addressed identity: plan must reference this exact tool
    if entry.tool_hash != planned_tool_hash:
        raise CapabilityBindingError(
            f"tool identity mismatch: planned {planned_tool_hash[:12]} "
            f"!= loaded {entry.tool_hash[:12]} (name shadowing?)"
        )

    # 3. warrant coverage
    if entry.name not in agent_warrant_tools:
        raise CapabilityBindingError(
            f"agent warrant does not cover tool {entry.name!r}"
        )

    # 4. capability envelope: schema-valid is not capability-valid
    for param, constraints in entry.capability_envelope.items():
        value = arguments.get(param)
        if "host_allowlist" in constraints:
            host = _extract_host(value)
            if host not in constraints["host_allowlist"]:
                raise CapabilityBindingError(
                    f"param {param!r} host {host!r} outside signed "
                    f"allowlist {constraints['host_allowlist']}"
                )

    # 5. replay / repeat-exfil guard on argument digest
    arg_digest = hashlib.sha256(
        json.dumps(arguments, sort_keys=True).encode()
    ).hexdigest()
    if arg_digest in seen_arg_digests:
        raise CapabilityBindingError(
            f"argument digest {arg_digest[:12]} already denied once; "
            "refusing retry loop"
        )

    return arg_digest


def _extract_host(url: str) -> str:
    from urllib.parse import urlparse
    return urlparse(url).hostname or ""
