# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-aaif-audience-binding-when-the-delegating-org-s-key-material-rotates-mid-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-aaif-audience-binding-when-the-delegating-org-s-key-material-rotates-mid-federation.warrant.json
# Markdown SHA-256:   558154533db30b448c58ac0c43a9caeda779d6dae835de497248ca25807c6b0b
# Code AST SHA-256:   5a6d75d7d516697fa6b2f22843e49618aac735155e0c429fa5cd8eedc26c28ef
# Verified Classes:   AAIFRegistryGenerationMismatch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AAIFRegistryGenerationMismatch(RuntimeError):
    """Raised when a delegated AAIF token's registry_gen does not match the
    currently published audience-scope registry generation.

    This is deliberately distinct from a signature failure: the signature may
    be valid against an overlapping key while the audience scope has moved.
    Operators must re-publish scopes, not rotate keys.
    """
    pass


def validate_delegated_aaif(token: dict, current_registry_gen: str) -> None:
    # Signature validation is assumed to have passed upstream against the
    # overlapping JWKS window. That is necessary but not sufficient.
    if "registry_gen" not in token:
        # A token minted before registry_gen was required cannot be
        # validated under reading (2). Refuse rather than guess.
        raise AAIFRegistryGenerationMismatch(
            "delegated token carries no registry_gen; audience scope is "
            "unverifiable during delegating-org rotation"
        )

    token_gen = token["registry_gen"]
    if token_gen != current_registry_gen:
        raise AAIFRegistryGenerationMismatch(
            f"token registry_gen={token_gen!r} does not match current "
            f"registry generation={current_registry_gen!r}; audience scope "
            f"may have narrowed since mint. Rejecting to prevent silent "
            f"authorization widening."
        )

    # Only now is it safe to resolve aud against the current scope registry.
    aud = token.get("aud", [])
    if not isinstance(aud, list) or not aud:
        raise AAIFRegistryGenerationMismatch(
            "delegated token has empty or malformed aud; cannot bind to "
            "AAIF subject membership"
        )
