# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-aaif-credential-it-was-issued-authorizes-a-capability-the-issuer-no-longer-holds.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-aaif-credential-it-was-issued-authorizes-a-capability-the-issuer-no-longer-holds.warrant.json
# Markdown SHA-256:   d0ff655c57a04929875266a9f8c2ff0d6711fd416e0d43303783d49353a73827
# Code AST SHA-256:   2da7df3e27e90f82bfb77916bec7e1aa3fca1d925a51127e85cddab1aa885543
# Verified Classes:   StaleDelegationError, AaifCredential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StaleDelegationError(RuntimeError):
    """Raised when a delegated AAIF credential's issuer no longer holds the delegated scope."""
    pass


class AaifCredential:
    def __init__(self, subject, issuer, scope, not_after, max_staleness_s):
        self.subject = subject
        self.issuer = issuer
        self.scope = scope
        self.not_after = not_after
        self.max_staleness_s = max_staleness_s


def assert_credential_sound(cred, now, issuer_live_scope, last_chain_check_ts):
    """
    Enforce the delegation-depth invariant:
      effective_lifetime = min(not_after, issuer_grant_lifetime, revocation_poll_interval)
    Fails closed if chain state is unreachable or stale beyond the declared ceiling.
    """
    if now >= cred.not_after:
        raise StaleDelegationError(
            f"credential for {cred.subject} expired at {cred.not_after}"
        )

    if issuer_live_scope is None:
        # Chain unreachable: fail closed, never assume validity.
        raise StaleDelegationError(
            f"cannot verify issuer {cred.issuer} grant state; failing closed"
        )

    if (now - last_chain_check_ts) > cred.max_staleness_s:
        raise StaleDelegationError(
            f"chain check for {cred.issuer} is {(now - last_chain_check_ts)}s old, "
            f"exceeds max_staleness {cred.max_staleness_s}s"
        )

    if cred.scope not in issuer_live_scope:
        raise StaleDelegationError(
            f"issuer {cred.issuer} no longer holds scope {cred.scope}; "
            f"delegated credential to {cred.subject} is stale"
        )

    return True
