# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-token-whose-consent-chain-is-cryptographically-valid-but-semantically-expired.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-token-whose-consent-chain-is-cryptographically-valid-but-semantically-expired.warrant.json
# Markdown SHA-256:   450feb10f26984453b7c35c988bfbf9696534f9334bd09521d6c81c996a6008f
# Code AST SHA-256:   7d0d41da155143a5832550ffb9b206907bce3d7460dcf7e9320d7dc4d044d41c
# Verified Classes:   StaleInteriorConsentError, Grant
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class StaleInteriorConsentError(RuntimeError):
    """Raised when a delegated capability chain is cryptographically valid
    but an interior grant has lapsed, or the recomposed scope exceeds the
    intersection of all live ancestor scopes, at the time of use."""


@dataclass(frozen=True)
class Grant:
    grantor: str
    grantee: str
    action: str
    resource_prefix: str          # e.g. "project/phoenix/docs/public/"
    window_start: float
    window_end: float
    signature_valid: bool = True  # set by the crypto layer; never trusted alone


def verify_chain_at_use(
    chain: Sequence[Grant],
    use_time: float,
    requested_action: str,
    requested_resource: str,
) -> Grant:
    """Re-walk the full chain at use time. Do NOT cache the verdict across
    a window boundary. Returns the leaf grant if and only if every interior
    link is live and the recomposed scope authorizes the request."""

    if not chain:
        raise StaleInteriorConsentError("empty capability chain")

    # (1) Every link must be cryptographically valid *and* live at use_time.
    #     The naive verifier checks only chain[0] and chain[-1]; that is the bug.
    for i, g in enumerate(chain):
        if not g.signature_valid:
            raise StaleInteriorConsentError(
                f"link {i} ({g.grantor}->{g.grantee}) signature invalid"
            )
        if not (g.window_start <= use_time <= g.window_end):
            raise StaleInteriorConsentError(
                f"link {i} ({g.grantor}->{g.grantee}) window "
                f"[{g.window_start},{g.window_end}] does not contain "
                f"use_time={use_time}; chain is cryptographically valid but "
                f"interior consent has lapsed"
            )

    # (2) Effective scope is the INTERSECTION of all links, not the leaf's
    #     declared scope. A leaf that exceeds its ancestors is unauthorized
    #     even with a valid signature.
    effective_prefix = chain[0].resource_prefix
    effective_action = chain[0].action
    for g in chain[1:]:
        # longest-common-prefix narrowing; a widening is a hard refusal
        if not g.resource_prefix.startswith(effective_prefix):
            raise StaleInteriorConsentError(
                f"scope recomposition widening at {g.grantor}: "
                f"{g.resource_prefix!r} is not within {effective_prefix!r}"
            )
        effective_prefix = g.resource_prefix
        if g.action != effective_action and g.action != "delegate":
            raise StaleInteriorConsentError(
                f"action mismatch at {g.grantor}: {g.action!r} vs "
                f"{effective_action!r}"
            )

    if not requested_resource.startswith(effective_prefix):
        raise StaleInteriorConsentError(
            f"requested resource {requested_resource!r} outside recomposed "
            f"scope {effective_prefix!r}"
        )
    if requested_action not in (effective_action, "delegate"):
        raise StaleInteriorConsentError(
            f"requested action {requested_action!r} outside recomposed "
            f"scope {effective_action!r}"
        )

    return chain[-1]
