# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-a2a-task-under-an-agent-card-whose-signing-key-rotated-mid-handoff-and-then-fail-authorization-at-the-first-to.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-a2a-task-under-an-agent-card-whose-signing-key-rotated-mid-handoff-and-then-fail-authorization-at-the-first-to.warrant.json
# Markdown SHA-256:   3cae49930a2047e9255bacb4a4fafbfa9a6970a5a8757fbbdbbb2028bd95ce89
# Code AST SHA-256:   ee942fe48ea6ed4b430ed730d34b75289ad38255766406cbe13630f2c672b0ad
# Verified Classes:   AgentCardEpochMismatch, CapabilityAssertion, TaskRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class AgentCardEpochMismatch(RuntimeError):
    """Raised when a downstream authorization check resolves a caller's
    Agent Card key against a JWKS epoch different from the one that
    admitted the task. This is the signature of an admission/authorization
    split caused by mid-task key rotation."""
    pass


@dataclass
class CapabilityAssertion:
    """Task-scoped, callee-signed binding of the admission decision.
    Every downstream privileged step validates THIS, not the caller's JWKS."""
    caller_id: str
    card_digest: str          # hash of the exact card admitted
    resolved_scopes: tuple
    task_id: str
    exp: float                # == task deadline
    callee_sig: Optional[str] = None


@dataclass
class TaskRecord:
    task_id: str
    assertion: CapabilityAssertion
    admitted_at: float = field(default_factory=time.time)


def admit_task(caller_id: str, card_jws: str, card_body: dict,
               task_id: str, task_deadline: float) -> TaskRecord:
    """Admission: verify card signature ONCE, pin the decision."""
    # (JWS verification against current JWKS omitted for brevity)
    digest = hashlib.sha256(card_jws.encode()).hexdigest()
    assertion = CapabilityAssertion(
        caller_id=caller_id,
        card_digest=digest,
        resolved_scopes=tuple(card_body["scopes"]),
        task_id=task_id,
        exp=task_deadline,
    )
    # callee signs the assertion here (omitted); it never re-derives from JWKS.
    assertion.callee_sig = "callee-signed-assertion"
    return TaskRecord(task_id=task_id, assertion=assertion)


def authorize_step(record: TaskRecord, required_scope: str,
                   current_jwks_kids: set, caller_card_kid: str,
                   now: Optional[float] = None) -> None:
    """Downstream privileged step. Validates the PINNED assertion.

    If an implementation instead re-resolves caller_card_kid against
    current_jwks_kids, a rotation between admission and this call
    produces a silent split. We detect and refuse it explicitly."""
    now = now if now is not None else time.time()

    # Guardrail 1: assertion must not be expired.
    if now > record.assertion.exp:
        raise AgentCardEpochMismatch(
            f"task {record.task_id}: capability assertion expired at "
            f"{record.assertion.exp}, now {now}"
        )

    # Guardrail 2: the key that admitted the task must still be the key
    # the assertion was pinned to. If the caller's active kid has moved
    # AND the pinned kid is gone from JWKS, this is an epoch split, not
    # a scope denial -- surface it as such.
    if caller_card_kid not in current_jwks_kids:
        raise AgentCardEpochMismatch(
            f"task {record.task_id}: caller key {caller_card_kid} admitted "
            f"the task but is absent from current JWKS; authority was "
            f"re-derived from a moved trust root (epoch split)"
        )

    # Guardrail 3: scope must be a subset of the admission-time decision.
    if required_scope not in record.assertion.resolved_scopes:
        raise AgentCardEpochMismatch(
            f"task {record.task_id}: scope {required_scope} not in "
            f"admission-time scopes {record.assertion.resolved_scopes}"
        )
    # ... proceed with the privileged operation
