# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-spiffe-spire-workload-attested-agent-identity-from-silently-degrading-into-a-bearer-token-handoff-at-the-cross-org-broker-bou.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-spiffe-spire-workload-attested-agent-identity-from-silently-degrading-into-a-bearer-token-handoff-at-the-cross-org-broker-bou.warrant.json
# Markdown SHA-256:   cfd2c23fabed5a5ea61b3f36c9d11da147b0c4f1973546bc418c43d728045f47
# Code AST SHA-256:   99fc718b699db4887a8df996665c86c50abb766d8776d197c618913f49592df0
# Verified Classes:   WarrantIntentMismatch, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class WarrantIntentMismatch(RuntimeError):
    """Raised when a call's intent binding does not match the warrant's session/argument commitment."""


@dataclass(frozen=True)
class Warrant:
    spiffe_id: str
    tool: str
    session_nonce: str
    arg_hash: str


def canonical_arg_hash(tool: str, arguments: dict) -> str:
    payload = json.dumps({"tool": tool, "args": arguments}, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def authorize_call(
    warrant: Warrant,
    presented_spiffe_id: str,
    tool: str,
    arguments: dict,
    session_nonce: str,
) -> None:
    if presented_spiffe_id != warrant.spiffe_id:
        raise WarrantIntentMismatch(
            f"SVID {presented_spiffe_id} does not match warrant identity {warrant.spiffe_id}"
        )
    if session_nonce != warrant.session_nonce:
        # Checkpoint-resume or sub-agent spawn minted a new session; the old
        # warrant's intent commitment is void even though the SVID is unchanged.
        raise WarrantIntentMismatch(
            f"session nonce {session_nonce!r} != warrant nonce {warrant.session_nonce!r}; "
            "intent continuity broken by resume/rotation"
        )
    actual_hash = canonical_arg_hash(tool, arguments)
    if actual_hash != warrant.arg_hash:
        # The agent varied a resource-selecting argument (e.g. tenant) while
        # holding a valid SVID. Identity continuity is intact; intent is not.
        raise WarrantIntentMismatch(
            f"argument hash {actual_hash[:12]} != warrant arg hash {warrant.arg_hash[:12]}; "
            "resource scope drifted from attested intent"
        )


def handle_brokered_call(warrant, presented_spiffe_id, tool, arguments, session_nonce):
    try:
        authorize_call(warrant, presented_spiffe_id, tool, arguments, session_nonce)
    except WarrantIntentMismatch as exc:
        # Convert silent cross-tenant read into an explicit, auditable rejection.
        return {"status": "rejected", "reason": str(exc), "audit": "intent_drift"}
    return {"status": "authorized", "tool": tool}
