# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-manifest-declared-tool-capabilities-from-silently-exceeding-the-signed-skill-envelope-during-runtime-skill-injection.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-manifest-declared-tool-capabilities-from-silently-exceeding-the-signed-skill-envelope-during-runtime-skill-injection.warrant.json
# Markdown SHA-256:   bb35fcd392f0a861459330e798674a706345e7ebe90f601114b19b1cb6685fb8
# Code AST SHA-256:   8c54b2e40687cc6e72cc86a9c363a89eebecac4d6d62841e44bea8df100ae347
# Verified Classes:   CapabilityEnvelopeViolation, SignedEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import os
from urllib.parse import urlparse, urljoin


class CapabilityEnvelopeViolation(RuntimeError):
    """Raised when a tool invocation's realized effect escapes its signed capability envelope."""
    pass


class SignedEnvelope:
    def __init__(self, allowed_origins, allowed_roots):
        # Signed at load time; these are the domains the signature attests to.
        self.allowed_origins = frozenset(allowed_origins)
        self.allowed_roots = tuple(os.path.realpath(r) for r in allowed_roots)

    def check_http(self, resolved_url):
        origin = urlparse(resolved_url).netloc
        if origin not in self.allowed_origins:
            raise CapabilityEnvelopeViolation(
                f"http.get escaped signed origin scope: {origin!r} not in {sorted(self.allowed_origins)}"
            )

    def check_fs(self, resolved_path):
        real = os.path.realpath(resolved_path)
        if not any(real == root or real.startswith(root + os.sep) for root in self.allowed_roots):
            raise CapabilityEnvelopeViolation(
                f"filesystem.read escaped signed root scope: {real!r} not under {self.allowed_roots}"
            )


def invoke_http_get(envelope, url, follow_redirects, redirect_target=None):
    # Pre-apply every effect transform the handler is capable of, then validate.
    final_url = url
    if follow_redirects and redirect_target is not None:
        final_url = urljoin(url, redirect_target)
    envelope.check_http(final_url)  # validate the resolved, post-redirect URL
    return final_url


def invoke_fs_read(envelope, path):
    # Canonicalize before validating so lexical prefix tricks cannot pass.
    resolved = os.path.realpath(path)
    envelope.check_fs(resolved)
    with open(resolved, "rb") as fh:
        return fh.read()


def guarded_dispatch(envelope, capability, args):
    if capability == "http.get":
        return invoke_http_get(
            envelope,
            args["url"],
            args.get("follow_redirects", False),
            args.get("redirect_target"),
        )
    if capability == "filesystem.read":
        return invoke_fs_read(envelope, args["path"])
    raise CapabilityEnvelopeViolation(f"capability {capability!r} not present in signed envelope")


if __name__ == "__main__":
    env = SignedEnvelope(
        allowed_origins=["api.example.com"],
        allowed_roots=["/data/inputs"],
    )
    # Trace 1: redirect escape — rejected because the post-redirect origin is checked.
    try:
        guarded_dispatch(
            env,
            "http.get",
            {"url": "https://api.example.com/x", "follow_redirects": True,
             "redirect_target": "https://attacker.example/steal"},
        )
    except CapabilityEnvelopeViolation as e:
        print("caught:", e)
    # Trace 2: path traversal — rejected because realpath is checked, not the raw string.
    try:
        guarded_dispatch(env, "filesystem.read",
                         {"path": "/data/inputs/../../etc/agent/secrets"})
    except CapabilityEnvelopeViolation as e:
        print("caught:", e)
