# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-authenticate-as-itself-but-authorize-as-its-predecessor-after-an-aaif-credential-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-authenticate-as-itself-but-authorize-as-its-predecessor-after-an-aaif-credential-rotation.warrant.json
# Markdown SHA-256:   8e8692b739de40d79d684dbb99c1fe070ecd7f2cfcc7a06d3b26f190e03c4d5a
# Code AST SHA-256:   5f09735b264b36e3535babac9e8a5396507d48bd84799eac4187edbd7fb9352d
# Verified Classes:   WarrantSubjectMismatchError, Warrant, AuthContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class WarrantSubjectMismatchError(RuntimeError):
    """Raised when the authenticated instance is not the warrant subject
    and no valid re-delegation edge bridges them."""
    pass


@dataclass(frozen=True)
class Warrant:
    subject: str                      # instance id the warrant names
    scope: frozenset[str]
    expires_at: float
    delegation_depth_remaining: int
    redelegated_from: Optional[str] = None  # set if this edge was signed by subject


@dataclass(frozen=True)
class AuthContext:
    instance_id: str                  # who is presenting right now
    signature_valid: bool
    nonce_fresh: bool


def authorize(ctx: AuthContext, warrant: Warrant, now: float,
              revoked_subjects: frozenset[str]) -> None:
    # --- authentication sub-check ---
    if not (ctx.signature_valid and ctx.nonce_fresh):
        raise WarrantSubjectMismatchError(
            f"auth failed for {ctx.instance_id}: signature/nonce invalid"
        )

    # --- warrant sub-check ---
    if warrant.expires_at <= now:
        raise WarrantSubjectMismatchError(f"warrant expired at {warrant.expires_at}")
    if warrant.subject in revoked_subjects:
        raise WarrantSubjectMismatchError(
            f"warrant subject {warrant.subject} is revoked; warrant orphaned"
        )

    # --- composition invariant: the two identity assertions must agree ---
    if ctx.instance_id == warrant.subject:
        return  # inside boundary

    # successor path: require a signed re-delegation edge with remaining depth
    if warrant.redelegated_from == warrant.subject and warrant.delegation_depth_remaining > 0:
        return  # inside boundary via re-delegation

    # outside boundary: valid signature + unexpired warrant is NOT sufficient
    raise WarrantSubjectMismatchError(
        f"instance {ctx.instance_id} authenticated as itself but warrant "
        f"subject is {warrant.subject} with depth_remaining="
        f"{warrant.delegation_depth_remaining}; no signed re-delegation edge. "
        f"Rotation incomplete: re-delegate or re-issue before first tool call."
    )


def resume_after_rotation(checkpoint: dict, successor: AuthContext,
                          now: float) -> None:
    """Resume path: must re-establish subject continuity before any tool call."""
    warrant = Warrant(
        subject=checkpoint["warrant_subject"],
        scope=frozenset(checkpoint["warrant_scope"]),
        expires_at=checkpoint["warrant_expires_at"],
        delegation_depth_remaining=checkpoint["delegation_depth_remaining"],
        redelegated_from=checkpoint.get("redelegated_from"),
    )
    authorize(successor, warrant, now, frozenset(checkpoint.get("revoked", [])))
