# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-oauth-resource-binding-when-an-mcp-server-reuses-a-cached-token-across-tool-scopes.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-oauth-resource-binding-when-an-mcp-server-reuses-a-cached-token-across-tool-scopes.warrant.json
# Markdown SHA-256:   c2e48091c7b5d7162471b5cff2b5a208491780304e04bbc0fa1917bbb8d9a983
# Code AST SHA-256:   e21e1359d4a51e32d9c76f88d96fad46e69140685f0c7c6262cef9896b651add
# Verified Classes:   AudienceMismatch, ScopeInsufficient
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AudienceMismatch(RuntimeError):
    """Raised when a token's audience does not match the tool's declared resource."""
    pass


class ScopeInsufficient(RuntimeError):
    """Raised when a token lacks the scope required by the tool."""
    pass


def authorize_tool(token, tool, cache):
    # 1. Audience check MUST precede scope check and cache lookup.
    if token.aud != tool.resource:
        raise AudienceMismatch(
            f"token aud={token.aud!r} does not match tool resource={tool.resource!r}"
        )

    # 2. Cache key includes resource and scope set — never (client_id, subject) alone.
    key = (token.client_id, token.subject, tool.resource, frozenset(tool.required_scopes))
    cached = cache.get(key)
    if cached is not None and cached.is_valid():
        return cached

    # 3. Scope check.
    if not tool.required_scopes.issubset(token.scope):
        raise ScopeInsufficient(
            f"token scope={sorted(token.scope)} missing {sorted(tool.required_scopes - token.scope)}"
        )

    # 4. Any exchange must re-assert resource; reject unbound results.
    exchanged = token.exchange(resource=tool.resource, scope=tool.required_scopes)
    if exchanged.aud != tool.resource:
        raise AudienceMismatch(
            f"exchange returned aud={exchanged.aud!r}, expected {tool.resource!r}"
        )

    cache.put(key, exchanged)
    return exchanged
