# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-spiffe-svid-outlives-the-delegating-principal-s-authorization-window.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-spiffe-svid-outlives-the-delegating-principal-s-authorization-window.warrant.json
# Markdown SHA-256:   857b654dd349978cea5ed08523cfed4a3ca8baf68750df01d4359c1a9ad3985f
# Code AST SHA-256:   4c7a81c5990f93484ea3b11aa3473e69ef93aac4ebbf05883f40bcc2d954f938
# Verified Classes:   DelegationChainError, Grant, DelegationToken
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class DelegationChainError(RuntimeError):
    """Raised when a delegated token's authority cannot be proven live."""
    pass


@dataclass
class Grant:
    grant_id: str
    principal: str
    expires_at: float
    revoked: bool = False


@dataclass
class DelegationToken:
    subject_svid: str
    act_principal: str
    grant_id: str          # must reference the terminal parent grant
    expires_at: float      # must be <= parent grant.expires_at
    signature_valid: bool


def mint_child_token(parent: Grant, subject_svid: str, now: float) -> DelegationToken:
    """Clamp child lifetime to the parent grant, never to the SVID TTL."""
    if parent.revoked or parent.expires_at <= now:
        raise DelegationChainError(
            f"cannot delegate from dead grant {parent.grant_id}"
        )
    # The invariant: child exp is bounded by the authorization clock.
    child_exp = min(parent.expires_at, now + 60.0)
    return DelegationToken(
        subject_svid=subject_svid,
        act_principal=parent.principal,
        grant_id=parent.grant_id,
        expires_at=child_exp,
        signature_valid=True,
    )


def verify_delegated_call(
    token: DelegationToken,
    grant_lookup,
    now: float,
    max_stateless_ttl: float = 300.0,
) -> None:
    """Reject ghost tokens: valid SVID + valid signature is not enough."""
    if not token.signature_valid:
        raise DelegationChainError("bad signature")
    if token.grant_id is None:
        raise DelegationChainError(
            "token carries no grant_id; cannot prove authority is live"
        )
    grant = grant_lookup(token.grant_id)
    if grant is None:
        raise DelegationChainError(f"unknown grant {token.grant_id}")
    if grant.revoked:
        raise DelegationChainError(f"grant {grant.grant_id} revoked")
    if grant.expires_at <= now:
        raise DelegationChainError(
            f"grant {grant.grant_id} expired at {grant.expires_at}, now {now}"
        )
    if token.expires_at > grant.expires_at:
        # The exact failure from the incident: exp copied from SVID, not grant.
        raise DelegationChainError(
            f"token exp {token.expires_at} exceeds grant exp {grant.expires_at}"
        )
    if token.expires_at - now > max_stateless_ttl:
        raise DelegationChainError(
            "token claims lifetime beyond stateless trust window; "
            "requires online re-check"
        )
