# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-capability-across-a-federation-boundary-and-the-policy-oracle-answers-permit-for-a-schema-it-cannot-actuall.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-capability-across-a-federation-boundary-and-the-policy-oracle-answers-permit-for-a-schema-it-cannot-actuall.warrant.json
# Markdown SHA-256:   86651c63337824fb34b8282c4c495d31e9b1a9971847c1a2ede0fa34e97fb4f6
# Code AST SHA-256:   adc5b762faed9627769b2c781ba3fea7c2be1cc9fa2fb6ce342fe74221f34ab3
# Verified Classes:   PermitWithoutRouteError, CapabilityGrant, CapabilityRequest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class PermitWithoutRouteError(RuntimeError):
    """Raised when a capability grant authorizes an invocation but no
    routable, schema-compatible endpoint exists behind the boundary.

    This is a *negotiation* failure, not a routing failure: it must not
    enter the retry loop and must not trigger a default-route fallback.
    """


@dataclass(frozen=True)
class CapabilityGrant:
    capability_id: str
    schema_digest: str          # digest the gateway claims is live
    warrant_scope_digest: str   # digest the PDP bound the warrant to
    warrant_cache_age_s: float  # how stale the PDP attribute was


@dataclass(frozen=True)
class CapabilityRequest:
    capability_id: str
    required_schema_digest: str
    explicit_fallback: Optional[str] = None  # caller-named fallback digest, or None


def verify_grant(
    req: CapabilityRequest,
    grant: CapabilityGrant,
    registry_live_digest: str,
    max_warrant_age_s: float = 5.0,
) -> None:
    """Enforce the permit-without-route boundary at grant receipt.

    Dispatch is permitted only if all three independent checks pass:
      1. warrant scope matches the requested schema digest (not just the name)
      2. the grant's schema digest matches the live registry digest
      3. the grant's schema digest equals the request's required digest

    Any mismatch raises PermitWithoutRouteError and MUST NOT be retried
    or routed to a default handler.
    """
    if grant.capability_id != req.capability_id:
        raise PermitWithoutRouteError(
            f"grant capability {grant.capability_id!r} does not match "
            f"request {req.capability_id!r}"
        )

    # Check 1: warrant must be scoped to the schema digest, not just the name.
    if grant.warrant_scope_digest != req.required_schema_digest:
        raise PermitWithoutRouteError(
            f"stale_warrant_schema: warrant scoped to "
            f"{grant.warrant_scope_digest[:12]} but request requires "
            f"{req.required_schema_digest[:12]}"
        )

    # Check 2: the grant's schema must match what the registry actually serves.
    if grant.schema_digest != registry_live_digest:
        raise PermitWithoutRouteError(
            f"schema_digest_mismatch: grant claims "
            f"{grant.schema_digest[:12]} but registry serves "
            f"{registry_live_digest[:12]}"
        )

    # Check 3: digest equality only -- no superset heuristics across orgs.
    if grant.schema_digest != req.required_schema_digest:
        raise PermitWithoutRouteError(
            f"schema_digest_mismatch: grant {grant.schema_digest[:12]} != "
            f"required {req.required_schema_digest[:12]}"
        )

    # Guard against a PDP cache that outlived the registry roll window.
    if grant.warrant_cache_age_s > max_warrant_age_s:
        raise PermitWithoutRouteError(
            f"stale_warrant_schema: warrant cache age "
            f"{grant.warrant_cache_age_s:.1f}s exceeds "
            f"{max_warrant_age_s:.1f}s roll window"
        )


def digest_schema(schema: str) -> str:
    return hashlib.sha256(schema.encode("utf-8")).hexdigest()
