# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-validate-an-mcp-oauth-token-audience-after-a-tool-result-driven-redirect-and-why-does-the-confused-deputy-window-reopen-mid-s.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-validate-an-mcp-oauth-token-audience-after-a-tool-result-driven-redirect-and-why-does-the-confused-deputy-window-reopen-mid-s.warrant.json
# Markdown SHA-256:   3a1d269dccb786f50e054c69b6fdeeedacff0e363d57c0dc12e57ce203ccbd58
# Code AST SHA-256:   910a956291e5375913bb1f21d8240c055c95ec6412f7abbdfff4260aaeb1a2dc
# Verified Classes:   AudienceBindingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class AudienceBindingError(RuntimeError):
    """Raised when an egress hop would reuse a token not bound to the target resource."""
    pass


def authorize_egress(target_url: str, session_token: dict, allowlist: set[str]) -> dict:
    """
    Re-derive audience for a single egress hop. Never inherit the session token
    across an origin boundary. Returns a token bound to target_url's origin, or raises.
    """
    target_origin = origin_of(target_url)  # scheme://host[:port]

    if target_origin not in allowlist:
        raise AudienceBindingError(
            f"egress to {target_origin} not in session allowlist; "
            f"tool-result URL is untrusted input"
        )

    token_origin = session_token.get("resource_origin")
    token_aud = set(session_token.get("aud", []))

    # Same-origin egress with an exactly-scoped token: reuse is legitimate.
    if target_origin == token_origin and token_aud == {target_origin}:
        return session_token

    # Cross-origin or over-broad aud: must re-derive via token exchange.
    if target_origin in token_aud and len(token_aud) > 1:
        # Overlapping aud is an AS misconfiguration; refuse rather than gamble.
        raise AudienceBindingError(
            f"token aud {sorted(token_aud)} overlaps target {target_origin}; "
            f"audience check would be a no-op — refusing egress"
        )

    exchanged = exchange_token_for_resource(session_token, resource=target_origin)
    if exchanged.get("resource_origin") != target_origin:
        raise AudienceBindingError(
            f"token exchange returned token bound to {exchanged.get('resource_origin')}, "
            f"expected {target_origin}"
        )
    return exchanged


def fetch_followup(target_url: str, session_token: dict, allowlist: set[str]) -> bytes:
    """Follow a URL that appeared in a tool result. Re-validate before attaching credentials."""
    try:
        bound = authorize_egress(target_url, session_token, allowlist)
    except AudienceBindingError:
        # Do not fall back to session token; do not silently drop. Surface to agent loop.
        raise
    return http_get(target_url, headers={"Authorization": f"Bearer {bound['access_token']}"})
