# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-capability-token-has-outlived-its-originating-grant-in-aaif-trust-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-capability-token-has-outlived-its-originating-grant-in-aaif-trust-chains.warrant.json
# Markdown SHA-256:   9cb8f9f6c184471428a042f911a314de6f7b7237ad50a6b0d93be85530311722
# Code AST SHA-256:   81c2d5c4e4560ebff3f5285c209a3885a519d601d532005b77209e531a4f2fa3
# Verified Classes:   OrphanedCapabilityError, GrantStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class OrphanedCapabilityError(RuntimeError):
    """Raised when a delegated SCT's parent grant cannot be resolved to a live, non-revoked record."""
    pass


class GrantStore:
    def __init__(self):
        # grant_id -> {"revoked": bool, "exp": float}
        self._grants = {}

    def tombstone(self, grant_id, now):
        rec = self._grants.get(grant_id)
        if rec is None:
            # Absence is NOT permission. Record an explicit dead grant.
            self._grants[grant_id] = {"revoked": True, "exp": now}
        else:
            rec["revoked"] = True
            rec["exp"] = now

    def resolve(self, grant_id):
        # Returns the record or None. Callers MUST treat None as denial.
        return self._grants.get(grant_id)


def authorize_delegated_token(token, store, now):
    """
    Validate a delegated capability token by walking its parent_grant chain
    to the root. Fails closed on any unresolvable or revoked ancestor.
    """
    parent_id = token.get("parent_grant")
    if parent_id is None:
        # Root-level grant; caller must have validated root separately.
        return True

    seen = set()
    current = parent_id
    while current is not None:
        if current in seen:
            raise OrphanedCapabilityError(
                f"cycle detected in grant chain at {current!r}"
            )
        seen.add(current)

        rec = store.resolve(current)
        if rec is None:
            # THE INVARIANT: missing parent grant is a denial, not a pass.
            raise OrphanedCapabilityError(
                f"parent grant {current!r} not found in store; "
                f"refusing to honor descendant token (fail-closed)"
            )
        if rec["revoked"]:
            raise OrphanedCapabilityError(
                f"parent grant {current!r} is revoked; descendant token is orphaned"
            )
        if rec["exp"] <= now:
            raise OrphanedCapabilityError(
                f"parent grant {current!r} expired at {rec['exp']}; descendant token is orphaned"
            )

        # Walk one more level up if the record carries its own parent.
        current = rec.get("parent_grant")

    return True
