# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-identity-spoofing-from-surviving-continuous-authorization-re-evaluation-under-aaif.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-identity-spoofing-from-surviving-continuous-authorization-re-evaluation-under-aaif.warrant.json
# Markdown SHA-256:   bf7279147a6240e28fc8f3cf037ef5aa3383a1c1130186181548c5909272081c
# Code AST SHA-256:   4bfbe67f35a7f85ee7b3199ca8c84930da158ccb2b1cace6b2e1a4d25718adc0
# Verified Classes:   SubjectContinuityViolation, Assertion, ExecutingContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SubjectContinuityViolation(RuntimeError):
    """Raised when a valid AAIF assertion is presented by a non-matching executing context."""
    pass


@dataclass(frozen=True)
class Assertion:
    subject: str
    task_id: str
    resource_handle: str
    delegation_depth: int
    ctx_fingerprint: str  # committed at mint time


@dataclass(frozen=True)
class ExecutingContext:
    subject: str
    task_id: str
    resource_handle: str
    delegation_depth: int
    process_id: str


def compute_fingerprint(task_id: str, resource_handle: str, depth: int, process_id: str) -> str:
    payload = f"{task_id}|{resource_handle}|{depth}|{process_id}".encode()
    return hashlib.sha256(payload).hexdigest()


def re_evaluate(assertion: Assertion, ctx: ExecutingContext) -> bool:
    # Subject-continuity join: assertion subject must equal executing subject.
    if assertion.subject != ctx.subject:
        raise SubjectContinuityViolation(
            f"assertion subject {assertion.subject!r} != executing subject {ctx.subject!r}"
        )
    # Context binding: the fingerprint committed in the assertion must match
    # the live execution context, not merely the session key.
    live = compute_fingerprint(ctx.task_id, ctx.resource_handle, ctx.delegation_depth, ctx.process_id)
    if assertion.ctx_fingerprint != live:
        raise SubjectContinuityViolation(
            f"context fingerprint mismatch for subject {ctx.subject!r}: "
            f"asserted={assertion.ctx_fingerprint[:12]} live={live[:12]}"
        )
    return True


def authorize_tool_call(assertion: Assertion, ctx: ExecutingContext, capability: str) -> bool:
    # Fail closed on any continuity violation; never fall back to signature-only.
    try:
        re_evaluate(assertion, ctx)
    except SubjectContinuityViolation as exc:
        raise SubjectContinuityViolation(
            f"denied {capability!r} for {ctx.subject!r}: {exc}"
        ) from exc
    return True
