# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-a-federated-capability-grant-has-silently-outlived-its-delegating-principal-s-authority.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-a-federated-capability-grant-has-silently-outlived-its-delegating-principal-s-authority.warrant.json
# Markdown SHA-256:   756bed644ab1a0859ea7a9b56e355e3ebea014ecf130ef83150d1c35f5c689e3
# Code AST SHA-256:   1f813ca185e2dc2ac5b155ce3ceb8f69d4f3527f3cee64a6454a369512f1a5bc
# Verified Classes:   AuthorityDecayUndetected, DelegatedGrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AuthorityDecayUndetected(RuntimeError):
    """Raised when a delegated grant is signature-valid but its delegating
    principal's live authority could not be re-anchored within the staleness
    bound. Signature validity is NOT authority validity across a trust hop."""


@dataclass
class DelegatedGrant:
    grant_id: str
    delegator: str            # e.g. "analyst@orgA"
    scope: str                # e.g. "billing:read"
    minted_at: float
    expires_at: float
    revalidated_at: float     # last successful re-anchor against delegator's authority
    signature_chain_valid: bool


def assert_authority_live(
    grant: DelegatedGrant,
    authority_service,          # callable(delegator, scope) -> bool, may raise on partition
    max_staleness_s: float,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    # Cheap local checks first: these are necessary, never sufficient.
    if not grant.signature_chain_valid:
        raise AuthorityDecayUndetected(
            f"grant {grant.grant_id}: signature chain broken"
        )
    if now >= grant.expires_at:
        raise AuthorityDecayUndetected(
            f"grant {grant.grant_id}: TTL expired at {grant.expires_at}"
        )

    # The boundary: signature + TTL say nothing about whether the delegator
    # still holds the authority it delegated. Re-anchor or fail closed.
    staleness = now - grant.revalidated_at
    if staleness > max_staleness_s:
        try:
            still_holds = authority_service(grant.delegator, grant.scope)
        except Exception as exc:  # partition, timeout, 5xx from authority
            # Fail closed: inability to revalidate is not permission to proceed.
            raise AuthorityDecayUndetected(
                f"grant {grant.grant_id}: re-anchor failed for "
                f"{grant.delegator}/{grant.scope} after {staleness:.1f}s "
                f"staleness ({exc!r}); refusing call"
            ) from exc

        if not still_holds:
            # The exact failure this article is about: token live, authority dead.
            raise AuthorityDecayUndetected(
                f"grant {grant.grant_id}: authority decayed — "
                f"{grant.delegator} no longer holds {grant.scope} "
                f"({staleness:.1f}s since last re-anchor)"
            )
        grant.revalidated_at = now


def execute_federated_call(grant, authority_service, max_staleness_s, call):
    assert_authority_live(grant, authority_service, max_staleness_s)
    return call()
