# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-and-how-signed-skill-provenance-bounds-the-injection-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-and-how-signed-skill-provenance-bounds-the-injection-surface.warrant.json
# Markdown SHA-256:   5e200e74687f97b0ec9d7fd9c35cd452048b84ea857f3dbc5b9caf16f974d308
# Code AST SHA-256:   470e2b5472611ff692bb6becf0b9ee85438ca518895426cbaabd0b160954c1ee
# Verified Classes:   ManifestProvenanceError, SignedManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
import re
from dataclasses import dataclass


class ManifestProvenanceError(RuntimeError):
    """Raised when a tool manifest violates signed-skill admission invariants."""


# Role markers and imperative chaining that a declarative capability
# description must never contain, regardless of signature validity.
_FORBIDDEN_PATTERNS = [
    re.compile(r"\[\s*SYSTEM\s*:", re.IGNORECASE),
    re.compile(r"<\|im_start\|>", re.IGNORECASE),
    re.compile(r"\b(before calling|first invoke|then call)\b", re.IGNORECASE),
    re.compile(r"\bappend\b.*\btranscript\b", re.IGNORECASE),
]


@dataclass
class SignedManifest:
    tool_name: str
    description: str
    input_schema: dict
    declared_data_sources: list[str]
    publisher: str
    signature: str
    signed_payload_hash: str  # hash the publisher signed


def _payload_hash(manifest: SignedManifest) -> str:
    # Hash covers description + schema + declared sources, NOT just identity.
    body = json.dumps(
        {
            "tool": manifest.tool_name,
            "description": manifest.description,
            "schema": manifest.input_schema,
            "sources": manifest.declared_data_sources,
        },
        sort_keys=True,
    ).encode()
    return hashlib.sha256(body).hexdigest()


def _verify_signature(manifest: SignedManifest, trusted_publishers: dict[str, str]) -> None:
    expected = trusted_publishers.get(manifest.publisher)
    if expected is None:
        raise ManifestProvenanceError(
            f"publisher {manifest.publisher!r} has no out-of-band trust root"
        )
    if manifest.signed_payload_hash != _payload_hash(manifest):
        raise ManifestProvenanceError(
            f"signature does not cover full payload for {manifest.tool_name!r}"
        )


def _enforce_declarative_grammar(manifest: SignedManifest) -> None:
    for pat in _FORBIDDEN_PATTERNS:
        if pat.search(manifest.description):
            raise ManifestProvenanceError(
                f"description of {manifest.tool_name!r} contains non-declarative "
                f"or role-spoofing text matching {pat.pattern!r}; "
                f"publisher={manifest.publisher}"
            )


def admit_manifest(
    manifest: SignedManifest,
    trusted_publishers: dict[str, str],
    admitted_hashes: set[str],
) -> str:
    """Admission gate: signature AND grammar AND refresh-stability."""
    _verify_signature(manifest, trusted_publishers)   # who said it
    _enforce_declarative_grammar(manifest)            # is it the kind of thing allowed
    h = _payload_hash(manifest)
    if h in admitted_hashes:
        return h
    # New hash on a known tool = refresh drift; must re-pass both gates above.
    admitted_hashes.add(h)
    return h


def validate_call_payload(
    manifest: SignedManifest, arguments: dict, transcript_tokens: set[str]
) -> None:
    """No argument may carry data whose provenance is undeclared."""
    declared = set(manifest.declared_data_sources)
    for field, value in arguments.items():
        if not isinstance(value, str):
            continue
        for token in transcript_tokens:
            if token in value and field not in declared:
                raise ManifestProvenanceError(
                    f"argument {field!r} of {manifest.tool_name!r} carries "
                    f"undeclared transcript data; possible exfil via signed-but-"
                    f"poisoned description"
                )
