# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-oauth-2-1-resource-indicator-scoping-with-per-tool-consent-when-a-downscoped-token-silently-widens-at-the-tool-bounda.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-oauth-2-1-resource-indicator-scoping-with-per-tool-consent-when-a-downscoped-token-silently-widens-at-the-tool-bounda.warrant.json
# Markdown SHA-256:   2f82c9d08d183405ee4fcb7e10df5dc0e40c3de32d7f3f44378cc89888cc1ce4
# Code AST SHA-256:   a65f7202be8e8fffa1aa402736b1010847a5df02b91f5300a1b3256bbb9d0ac4
# Verified Classes:   ConsentWideningError, Token, ConsentRecord, InvocationWarrant, Runtime
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ConsentWideningError(RuntimeError):
    """Raised when a tool invocation would reuse a credential issued for a
    different tool's consent decision (cache-key collapse on (resource, scope))."""
    pass


@dataclass(frozen=True)
class Token:
    jti: str
    resource: str          # RFC 8707 resource indicator
    scope: frozenset       # granted scope string, split
    exp: float


@dataclass(frozen=True)
class ConsentRecord:
    consent_id: str
    tool_id: str
    granted_scope: frozenset
    allow_once: bool
    task_id: str


@dataclass
class InvocationWarrant:
    tool_id: str
    consent_id: str
    task_id: str
    jti: str
    exp: float
    used: bool = False


@dataclass
class Runtime:
    # BUG: keyed on (resource, scope) -> collapses distinct consent decisions
    credential_cache: dict = field(default_factory=dict)
    # FIX: keyed on (tool_id, consent_id) and gated by a warrant
    warrant_store: dict = field(default_factory=dict)
    consent_ledger: dict = field(default_factory=dict)


def issue_downscoped_token(parent: Token, resource: str, scope: frozenset,
                           jti_factory) -> Token:
    # AS mints a token whose only distinguishing fields are (resource, scope).
    return Token(jti=jti_factory(), resource=resource, scope=scope,
                 exp=time.time() + 3600)


def invoke_tool_buggy(rt: Runtime, tool_id: str, required: frozenset,
                      consent: ConsentRecord, resource: str,
                      jti_factory) -> Token:
    key = (resource, required)  # <-- collapse point
    if key in rt.credential_cache:
        tok = rt.credential_cache[key]
        # gate passes because scope matches, but the token was issued for
        # a different tool's consent decision
        if not required <= tok.scope:
            raise ConsentWideningError("cached token lacks required scope")
        return tok
    tok = issue_downscoped_token(parent=Token("p", resource, required, 0),
                                 resource=resource, scope=required,
                                 jti_factory=jti_factory)
    rt.credential_cache[key] = tok
    return tok


def invoke_tool(rt: Runtime, tool_id: str, required: frozenset,
                consent: ConsentRecord, resource: str,
                jti_factory) -> Token:
    # 1. Consent gate is evaluated against the ledger, never the token.
    rec = rt.consent_ledger.get(consent.consent_id)
    if rec is None or rec.tool_id != tool_id or rec.task_id != consent.task_id:
        raise ConsentWideningError(
            f"no matching consent for tool {tool_id!r} "
            f"(consent {consent.consent_id!r} bound to {rec.tool_id if rec else None!r})"
        )
    if not required <= rec.granted_scope:
        raise ConsentWideningError(
            f"tool {tool_id!r} requires {sorted(required)}, "
            f"consent granted {sorted(rec.granted_scope)}"
        )

    # 2. Warrant binds tool_id -> consent_id -> jti; cache is keyed on warrant.
    wkey = (tool_id, consent.consent_id, consent.task_id)
    warrant = rt.warrant_store.get(wkey)
    if warrant is None:
        tok = issue_downscoped_token(parent=Token("p", resource, required, 0),
                                     resource=resource, scope=required,
                                     jti_factory=jti_factory)
        warrant = InvocationWarrant(tool_id=tool_id,
                                    consent_id=consent.consent_id,
                                    task_id=consent.task_id,
                                    jti=tok.jti, exp=tok.exp)
        rt.warrant_store[wkey] = warrant
        rt.credential_cache[(resource, tok.jti)] = tok
    else:
        tok = rt.credential_cache[(resource, warrant.jti)]

    # 3. allow_once is enforced at the warrant, not at the token.
    if rec.allow_once and warrant.used:
        raise ConsentWideningError(
            f"allow_once consent {consent.consent_id!r} already consumed "
            f"by a prior invocation of {tool_id!r}"
        )
    if warrant.exp <= time.time():
        raise ConsentWideningError(f"warrant for {tool_id!r} expired")
    warrant.used = True
    return tok


def _demo() -> None:
    jti = iter(["j1", "j2"]).__next__
    rt = Runtime()
    rt.consent_ledger["c-search"] = ConsentRecord(
        consent_id="c-search", tool_id="search_docs",
        granted_scope=frozenset({"docs:read"}), allow_once=True, task_id="t1")
    rt.consent_ledger["c-export"] = ConsentRecord(
        consent_id="c-export", tool_id="export_corpus",
        granted_scope=frozenset({"docs:read"}), allow_once=False, task_id="t1")

    # Buggy path: export_corpus reuses search_docs' cached token.
    invoke_tool_buggy(rt, "search_docs", frozenset({"docs:read"}),
                      rt.consent_ledger["c-search"], "https://mcp.example.com", jti)
    invoke_tool_buggy(rt, "export_corpus", frozenset({"docs:read"}),
                      rt.consent_ledger["c-export"], "https://mcp.example.com", jti)
    # -> no exception; consent widened silently.

    # Fixed path: try to run export_corpus under search_docs' consent.
    invoke_tool(rt, "search_docs", frozenset({"docs:read"}),
                rt.consent_ledger["c-search"], "https://mcp.example.com", jti)
    try:
        invoke_tool(rt, "export_corpus", frozenset({"docs:read"}),
                    rt.consent_ledger["c-search"], "https://mcp.example.com", jti)
    except ConsentWideningError as e:
        print("blocked:", e)

    # allow_once replay on resume:
    try:
        invoke_tool(rt, "search_docs", frozenset({"docs:read"}),
                    rt.consent_ledger["c-search"], "https://mcp.example.com", jti)
    except ConsentWideningError as e:
        print("blocked on replay:", e)


if __name__ == "__main__":
    _demo()
