# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-signed-skill-manifest-has-been-bypassed-by-capability-aliasing-at-the-sandbox-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-signed-skill-manifest-has-been-bypassed-by-capability-aliasing-at-the-sandbox-boundary.warrant.json
# Markdown SHA-256:   013920cb444bd0ca8d6032da0ea1b7f8c8ca7d17c600ec5f27b927d522005596
# Code AST SHA-256:   56fe448e55113f37e2a283a40e92d16a26e4ed1674f04c364e89b3d2eace2a02
# Verified Classes:   CapabilityAliasEscape, SignedManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class CapabilityAliasEscape(RuntimeError):
    """Raised when a skill's resolved canonical capability is not a member
    of its signed capability set — i.e. the manifest signature was bypassed
    via name aliasing rather than forged."""


@dataclass(frozen=True)
class SignedManifest:
    skill_id: str
    version: str
    capabilities: frozenset[str]  # canonical capabilities, as signed


# Alias table is part of the trusted computing base (condition C3).
# In production this must be signed and pinned per-execution; here it is
# the specific historical mislabel that caused the incident.
ALIAS_TABLE: dict[str, str] = {
    "fs.read": "fs.read",
    "fs.read.legacy": "fs.write",   # historical mislabel, never corrected
    "net.egress": "net.egress",
}


def resolve_canonical(requested_name: str) -> str:
    try:
        return ALIAS_TABLE[requested_name]
    except KeyError as exc:
        # Unresolvable names are denied, never prefix-matched.
        raise CapabilityAliasEscape(
            f"unresolvable capability name {requested_name!r}; "
            "no prefix fallback is permitted on the enforcement path"
        ) from exc


def enforce_scope(manifest: SignedManifest, requested_name: str) -> str:
    """Resolve-then-check (condition C1). Returns the canonical capability
    only if it is a member of the signed set; otherwise raises."""
    canonical = resolve_canonical(requested_name)

    if canonical not in manifest.capabilities:
        # This is the exact trace of the observed incident: a validly signed
        # read-only skill reaching write authority through an alias.
        raise CapabilityAliasEscape(
            f"skill {manifest.skill_id}@{manifest.version} requested "
            f"{requested_name!r} -> canonical {canonical!r}, which is not in "
            f"its signed capability set {sorted(manifest.capabilities)}; "
            "signature bypassed via alias resolution"
        )

    return canonical


def admit_and_dispatch(manifest: SignedManifest, requested_name: str) -> str:
    # Signature verification is assumed to have passed at admission.
    canonical = enforce_scope(manifest, requested_name)
    # Emit BOTH names to the audit log so divergence is reconstructable.
    return canonical


if __name__ == "__main__":
    pdf_annotate = SignedManifest(
        skill_id="pdf-annotate",
        version="1.4.0",
        capabilities=frozenset({"fs.read", "net.egress"}),
    )

    # Legitimate call: passes.
    assert admit_and_dispatch(pdf_annotate, "fs.read") == "fs.read"

    # The incident: validly signed read-only skill, aliased to write.
    try:
        admit_and_dispatch(pdf_annotate, "fs.read.legacy")
    except CapabilityAliasEscape as err:
        print(f"BLOCKED: {err}")
    else:
        raise AssertionError("alias escape was not caught")
