# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-asserted-capability-grant-as-untrusted-until-re-attested-under-its-own-trust-root.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-asserted-capability-grant-as-untrusted-until-re-attested-under-its-own-trust-root.warrant.json
# Markdown SHA-256:   aec5c4804efe7c75bdf70cfb43a35b865d0202b56a737d2a376766b22a7195b6
# Code AST SHA-256:   db0f55ccf3b30e1a898b9a9b7220dd72441c350d19f839f083bda2a1fe5842b2
# Verified Classes:   CapabilityCeilingViolation, FederationAgreement, DelegationToken, FederatedVerifier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class CapabilityCeilingViolation(RuntimeError):
    """Raised when a peer-issued, signature-valid grant requests a capability
    class outside the ceiling this receiver delegated to the peer's policy root,
    or names a scope that cannot be mapped into the receiver's taxonomy."""


@dataclass
class FederationAgreement:
    peer_root: str
    # receiver-local capability classes this peer root may exercise
    ceiling: Set[str]
    # peer scope-string -> receiver capability class (None = unmappable)
    scope_map: Dict[str, str] = field(default_factory=dict)


@dataclass
class DelegationToken:
    sub: str
    act: str
    scope: str          # peer's scope string, peer semantics
    resource: str       # peer's logical resource name
    signing_root: str


class FederatedVerifier:
    def __init__(self, agreements: Dict[str, FederationAgreement]):
        self._agreements = agreements

    def _resolve_local_resource(self, peer_root: str, peer_resource: str) -> str:
        # Receiver-local binding; never index peer names directly.
        return f"local::{peer_root}::{peer_resource}"

    def attest(self, token: DelegationToken) -> str:
        agreement = self._agreements.get(token.signing_root)
        if agreement is None:
            raise CapabilityCeilingViolation(
                f"no federation agreement for root {token.signing_root!r}"
            )
        # Signature already verified upstream; that is NOT sufficient.
        local_class = agreement.scope_map.get(token.scope)
        if local_class is None:
            raise CapabilityCeilingViolation(
                f"peer scope {token.scope!r} is unmappable into local taxonomy "
                f"for root {token.signing_root!r}; refusing transitive trust"
            )
        if local_class not in agreement.ceiling:
            raise CapabilityCeilingViolation(
                f"capability {local_class!r} is outside the ceiling delegated to "
                f"root {token.signing_root!r} (ceiling={sorted(agreement.ceiling)})"
            )
        return self._resolve_local_resource(token.signing_root, token.resource)


# Reproduction of the observed failure:
agreements = {
    "org-b-root": FederationAgreement(
        peer_root="org-b-root",
        ceiling={"dataset:read"},                 # onboarded read-only
        scope_map={"dataset:read": "dataset:read"},  # write intentionally absent
    )
}
verifier = FederatedVerifier(agreements)
bad_token = DelegationToken(
    sub="plan-b", act="orch-a",
    scope="dataset:write", resource="shared-dataset",
    signing_root="org-b-root",
)
try:
    verifier.attest(bad_token)
except CapabilityCeilingViolation as e:
    print("BLOCKED:", e)
    # -> capability 'dataset:write' outside ceiling; write never reaches resource layer
