# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-federated-agent-trust-anchor-silently-accept-tokens-minted-under-a-superseded-signing-key-during-cross-org-authorization.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-federated-agent-trust-anchor-silently-accept-tokens-minted-under-a-superseded-signing-key-during-cross-org-authorization.warrant.json
# Markdown SHA-256:   6cb0f9742886d491353328307001107eaec587966a67fd2003e48b50d52ede5c
# Code AST SHA-256:   0010b3a59eaf7aab966393098b85f1d244a231274a072a05ca94bc551ad95d02
# Verified Classes:   StaleIssuanceAuthorityError, TrustedKey, Token
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass
from typing import Mapping, Optional


class StaleIssuanceAuthorityError(RuntimeError):
    """Raised when a token's iat exceeds the signing key's issuance-authorization bound.

    The signature may be valid and the kid may be present in the trust anchor;
    this error means the key was retained for verification of in-flight tokens
    but was not authorized to mint tokens at the token's iat.
    """


@dataclass(frozen=True)
class TrustedKey:
    kid: str
    signing_not_before: Optional[int] = None  # epoch seconds; None = unbounded past
    signing_not_after: Optional[int] = None   # epoch seconds; None = unbounded future


@dataclass(frozen=True)
class Token:
    kid: str
    iss: str
    sub: str
    iat: int
    exp: int
    signature_valid: bool


def verify_federated_token(
    token: Token,
    anchor: Mapping[str, TrustedKey],
    now: Optional[int] = None,
) -> None:
    """Verify a cross-org agent authorization token against a trust anchor.

    Enforces both cryptographic validity and issuance authorization. The
    issuance-authorization check is the non-obvious one: a key present in the
    anchor may still be unauthorized to sign tokens at `token.iat`.
    """
    now = int(time.time()) if now is None else now

    if not token.signature_valid:
        raise StaleIssuanceAuthorityError(
            f"signature invalid for kid={token.kid!r}"
        )

    key = anchor.get(token.kid)
    if key is None:
        raise StaleIssuanceAuthorityError(
            f"kid={token.kid!r} not present in trust anchor"
        )

    # Cryptographic validity is necessary but not sufficient. The key must
    # have been authorized to *mint* at token.iat, not merely trusted to
    # *verify* now. Without this bound, a grace-window key is a standing
    # authorization and a compromised issuer can mint post-rotation tokens.
    if key.signing_not_before is not None and token.iat < key.signing_not_before:
        raise StaleIssuanceAuthorityError(
            f"token iat={token.iat} precedes key {key.kid!r} "
            f"signing_not_before={key.signing_not_before}"
        )
    if key.signing_not_after is not None and token.iat > key.signing_not_after:
        raise StaleIssuanceAuthorityError(
            f"token iat={token.iat} exceeds key {key.kid!r} "
            f"signing_not_after={key.signing_not_after}; key retained for "
            f"in-flight verification only"
        )

    if now > token.exp:
        raise StaleIssuanceAuthorityError(
            f"token expired: exp={token.exp} now={now}"
        )

    # Caller proceeds: token is cryptographically valid AND was minted under
    # a key authorized to issue at token.iat.
