# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-warrant-signed-by-a-trust-root-it-can-resolve-but-cannot-verify-against-its-own-residency-pinned-ke.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-warrant-signed-by-a-trust-root-it-can-resolve-but-cannot-verify-against-its-own-residency-pinned-ke.warrant.json
# Markdown SHA-256:   53ff0038ac434e570c533808c98c961c7212ad54b190cdd2b6a1d2e2fc0ba688
# Code AST SHA-256:   40d7a5a26a4f460694b71de5afc5cb0ce71ae3a8180d985271dcf972d3cc0bff
# Verified Classes:   UnpinnedTrustRootError, Warrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class UnpinnedTrustRootError(RuntimeError):
    """Raised when a warrant's signing key resolves and verifies but is not
    pinned in the residency keyring for the payload's data classification."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    root_fingerprint: str      # sha256 of the actual signing key, post-resolution
    capability: str
    dest_region: str
    payload_class: str


def fingerprint_of(jwk: dict) -> str:
    raw = jwk["n"].encode() + jwk["e"].encode()
    return "sha256:" + hashlib.sha256(raw).hexdigest()


def admit(
    warrant: Warrant,
    request_op: str,
    resolved_jwk: dict,
    pinned_keyring: dict[str, set[str]],   # payload_class -> set of pinned fingerprints
    region_policy: dict[str, set[str]],    # payload_class -> admitted dest regions
) -> bool:
    # 1. chain validity against the resolved (possibly unpinned) root
    actual_fp = fingerprint_of(resolved_jwk)
    if actual_fp != warrant.root_fingerprint:
        raise UnpinnedTrustRootError(
            f"resolved key fingerprint {actual_fp} != warrant claim "
            f"{warrant.root_fingerprint}; chain cannot be trusted"
        )

    # 2. capability scope
    if warrant.capability != request_op:
        return False

    # 3. residency pinning — the invariant that is commonly dropped.
    #    Must join on FINGERPRINT and on the PAYLOAD's class, not the issuer name.
    pinned = pinned_keyring.get(warrant.payload_class, set())
    if actual_fp not in pinned:
        raise UnpinnedTrustRootError(
            f"trust root {actual_fp} (issuer={warrant.issuer}) is resolvable and "
            f"chain-valid but NOT pinned for payload class "
            f"{warrant.payload_class!r}; refusing admission"
        )

    # 4. destination-region routing for the payload class
    if warrant.dest_region not in region_policy.get(warrant.payload_class, set()):
        return False

    return True
