# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-a-tool-manifest-s-declared-schema-and-its-declared-capabilities-when-the-manifest-is-attacker-controlled.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-a-tool-manifest-s-declared-schema-and-its-declared-capabilities-when-the-manifest-is-attacker-controlled.warrant.json
# Markdown SHA-256:   e79a7016518c413ac8a757c6e6c1a316ef42f2d74f20a064dd90d2dc08697862
# Code AST SHA-256:   9b013e319656cdb45138345699d5e7a1be9a2269be9d5e558d95970169441569
# Verified Classes:   CapabilityPoisoningError, Manifest
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class CapabilityPoisoningError(RuntimeError):
    """Raised when a manifest's declared capabilities exceed or diverge from
    the least-privilege set derived from its registered purpose."""


@dataclass(frozen=True)
class Manifest:
    name: str
    version: str
    schema_hash: str
    declared_capabilities: frozenset[str] = field(default_factory=frozenset)


# Purpose -> least-privilege capability set. This table is owned by the
# registry operator, NOT by the manifest author. It is the trust anchor.
PURPOSE_CAPABILITY_POLICY: dict[str, frozenset[str]] = {
    "url_summarizer": frozenset({"network:fetch"}),
    "file_reader": frozenset({"fs:read"}),
    "build_tool": frozenset({"fs:read", "fs:write", "subprocess"}),
}

# Capability combinations that are individually fine but jointly form an
# exfiltration primitive. Rejected regardless of purpose.
FORBIDDEN_COMBINATIONS: tuple[frozenset[str], ...] = (
    frozenset({"fs:read", "network:fetch"}),
    frozenset({"env:read", "network:fetch"}),
    frozenset({"fs:read", "subprocess"}),
)


def admit_manifest(manifest: Manifest, registered_purpose: str) -> None:
    """Admission gate. Raises CapabilityPoisoningError on any violation.

    The invariant: the manifest's declared capabilities must be a subset of
    the purpose-derived policy, must be non-empty-by-declaration (fail-closed),
    and must not form a forbidden combination.
    """
    if registered_purpose not in PURPOSE_CAPABILITY_POLICY:
        raise CapabilityPoisoningError(
            f"unknown purpose {registered_purpose!r}; cannot derive policy"
        )

    allowed = PURPOSE_CAPABILITY_POLICY[registered_purpose]
    declared = manifest.declared_capabilities

    # Fail-closed: absent declaration is not a grant.
    if not declared:
        # An empty set is acceptable only if the purpose requires nothing.
        if allowed:
            raise CapabilityPoisoningError(
                f"{manifest.name}@{manifest.version} declares no capabilities "
                f"but purpose {registered_purpose!r} requires {sorted(allowed)}; "
                f"fail-closed default rejects"
            )
        return

    # Wildcards are never admissible from an untrusted manifest.
    for cap in declared:
        if cap.endswith(":*") or cap == "*":
            raise CapabilityPoisoningError(
                f"{manifest.name}@{manifest.version} declares wildcard "
                f"capability {cap!r}; wildcards must be resolved by the policy, "
                f"not the manifest"
            )

    # Subset check: declared must be within purpose-derived least privilege.
    excess = declared - allowed
    if excess:
        raise CapabilityPoisoningError(
            f"{manifest.name}@{manifest.version} declares capabilities "
            f"{sorted(excess)} outside purpose {registered_purpose!r} "
            f"(allowed: {sorted(allowed)})"
        )

    # Joint combination check: the whole set, not individual members.
    for combo in FORBIDDEN_COMBINATIONS:
        if combo <= declared:
            raise CapabilityPoisoningError(
                f"{manifest.name}@{manifest.version} declares forbidden "
                f"capability combination {sorted(combo)}; this is an "
                f"exfiltration primitive regardless of declared purpose"
            )


def admit_on_upgrade(
    previous: Manifest, incoming: Manifest, registered_purpose: str
) -> None:
    """Re-evaluate capabilities on version bump even if schema is unchanged.

    Schema-hash caching must not short-circuit capability re-evaluation.
    """
    if incoming.schema_hash == previous.schema_hash and (
        incoming.declared_capabilities != previous.declared_capabilities
    ):
        raise CapabilityPoisoningError(
            f"{incoming.name} {previous.version}->{incoming.version}: schema "
            f"unchanged but capability set changed "
            f"{sorted(previous.declared_capabilities)} -> "
            f"{sorted(incoming.declared_capabilities)}; re-admission required"
        )
    admit_manifest(incoming, registered_purpose)


if __name__ == "__main__":
    # The observed attack: tidy schema, poisoned capability list.
    poisoned = Manifest(
        name="summarize_url",
        version="1.2.0",
        schema_hash="sha256:aaaa",
        declared_capabilities=frozenset({"network:fetch", "fs:read", "env:read"}),
    )
    try:
        admit_manifest(poisoned, registered_purpose="url_summarizer")
    except CapabilityPoisoningError as e:
        print(f"rejected: {e}")
