# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-transitive-trust-escalation-across-federated-policy-exchange-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-transitive-trust-escalation-across-federated-policy-exchange-boundaries.warrant.json
# Markdown SHA-256:   27058843d5288d32fcf5779f8e7e6e4f39ca103b1f6a37f16d6ffe11e2a15490
# Code AST SHA-256:   4e3bfe1ef61b7960174975adec070208bf1520f89470a7d779921c11125650ab
# Verified Classes:   TrustEscalationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TrustEscalationError(RuntimeError):
    """Raised when a delegation would grant more than the origin intended
    because a referenced policy has not been resolved locally."""
    pass


def authorize_delegation(
    capability: str,
    policy_ref: str,
    local_policy_cache: dict,
    max_resolution_window_s: float,
    revocation_window_s: float,
) -> dict:
    """Fail-closed authorization for a brokered delegation.

    Returns the effective constraint set. Raises if the policy reference
    is unresolved and cannot be safely treated as restrictive.
    """
    if max_resolution_window_s >= revocation_window_s:
        # The policy channel is slower than the revocation channel:
        # an upstream revocation could be honored before its narrowing
        # policy arrives. This is an unbounded escalation window.
        raise TrustEscalationError(
            f"policy resolution window ({max_resolution_window_s}s) "
            f">= revocation window ({revocation_window_s}s); "
            f"escalation window is unbounded"
        )

    resolved = local_policy_cache.get(policy_ref)
    if resolved is None:
        # Unresolved reference: grant only the minimum constraint set.
        # Do NOT pass the capability through unconstrained.
        return {
            "capability": capability,
            "constraints": {"scope": "minimum", "policy_resolved": False},
            "escalation_risk": "bounded",
        }

    return {
        "capability": capability,
        "constraints": resolved,
        "policy_resolved": True,
        "escalation_risk": "none",
    }


def broker_redelegate(
    capability: str,
    policy_ref: str,
    local_policy_cache: dict,
    downstream_org: str,
) -> dict:
    """A broker must not re-delegate a reference it cannot resolve."""
    if policy_ref not in local_policy_cache:
        raise TrustEscalationError(
            f"broker cannot re-delegate unresolved policy {policy_ref!r} "
            f"to {downstream_org}; resolve locally first"
        )
    return {
        "capability": capability,
        "policy_ref": policy_ref,
        "constraints": local_policy_cache[policy_ref],
    }
