# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-transitive-trust-escalation-when-a-federated-agent-re-delegates-a-brokered-capability-across-an-organizational-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-transitive-trust-escalation-when-a-federated-agent-re-delegates-a-brokered-capability-across-an-organizational-boundary.warrant.json
# Markdown SHA-256:   457af7c516ab2c99b7df6d684d55cc8bfbd46ecda47c17c9b3d3a7bc834b74ae
# Code AST SHA-256:   7f2ad0d93b0e40a90fbe03ed1f871372a1ce912f010f5c03d56265821612605f
# Verified Classes:   NonDelegableCapabilityError, DelegationDepthExceededError, GranteeBindingViolation, CapabilityGrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class NonDelegableCapabilityError(RuntimeError):
    """Raised when a holder attempts to re-delegate a terminal capability grant."""
    pass


class DelegationDepthExceededError(RuntimeError):
    """Raised when a delegable grant's depth budget is exhausted."""
    pass


class GranteeBindingViolation(RuntimeError):
    """Raised when the presenter is not the recorded grantee of the capability."""
    pass


@dataclass
class CapabilityGrant:
    grantee_org: str
    resource: str
    policy: str
    exp: float
    delegable: bool = False
    max_depth: int = 0
    audience: tuple = field(default_factory=tuple)
    depth_used: int = 0


def exchange_capability(
    grant: CapabilityGrant,
    presenter_org: str,
    requested_audience: str,
    now: Optional[float] = None,
) -> CapabilityGrant:
    """
    Broker-side token exchange. Enforces the non-transitivity invariant:
    a grant may only produce a derived grant if it is explicitly delegable,
    the presenter is the recorded grantee, depth remains, and the requested
    audience is within the grant's declared audience set.
    """
    now = time.time() if now is None else now

    if now >= grant.exp:
        raise NonDelegableCapabilityError(
            f"grant for {grant.resource} expired at {grant.exp}; "
            f"cannot exchange an expired parent"
        )

    # Grantee-binding: possession of the token is not sufficient.
    if presenter_org != grant.grantee_org:
        raise GranteeBindingViolation(
            f"presenter {presenter_org} is not grantee {grant.grantee_org}; "
            f"token forwarding or confused-deputy attempt"
        )

    # The core invariant: absent an explicit delegable flag, terminal.
    if not grant.delegable:
        raise NonDelegableCapabilityError(
            f"grant for {grant.resource} is non-delegable; "
            f"org {presenter_org} attempted to relay to {requested_audience}"
        )

    if grant.depth_used >= grant.max_depth:
        raise DelegationDepthExceededError(
            f"depth {grant.depth_used}/{grant.max_depth} exhausted for "
            f"{grant.resource}; cannot mint grant for {requested_audience}"
        )

    if requested_audience not in grant.audience:
        raise NonDelegableCapabilityError(
            f"audience {requested_audience} not in declared set "
            f"{grant.audience} for {grant.resource}"
        )

    # Derived grant inherits parent policy and cannot outlive it.
    return CapabilityGrant(
        grantee_org=requested_audience,
        resource=grant.resource,
        policy=grant.policy,
        exp=min(grant.exp, now + 600.0),
        delegable=grant.delegable,
        max_depth=grant.max_depth,
        audience=grant.audience,
        depth_used=grant.depth_used + 1,
    )
