# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-delegated-capability-whose-trust-anchor-rotated-mid-delegation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-delegated-capability-whose-trust-anchor-rotated-mid-delegation-chain.warrant.json
# Markdown SHA-256:   aacdeed7ea70bdf8ba813077a8ce4ed5c7f0542e22cab64dd67973b4c3b3fe32
# Code AST SHA-256:   3ff627dac0a116f1513104d0500d366b5a8e29f5abdcbb286d328a89c55354fb
# Verified Classes:   AnchorFreshnessViolation, AnchorDoc, Capability
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AnchorFreshnessViolation(RuntimeError):
    """Raised when a delegated capability is evaluated against anchor documents
    older than the issuer's warranted freshness bound."""
    pass


@dataclass
class AnchorDoc:
    domain: str
    keys_active: set
    keys_retired: dict  # key_id -> retired_at epoch
    rotation_period: float
    fetched_at: float


@dataclass
class Capability:
    root_domain: str
    signing_key_id: str
    min_anchor_freshness: float  # issuer-warranted max anchor age, seconds
    expiry: float


def verify_delegated_capability(
    cap: Capability,
    anchor: AnchorDoc,
    now: float,
    clock_skew: float = 2.0,
) -> bool:
    # 1. Expiry is necessary but not sufficient.
    if now >= cap.expiry:
        return False

    # 2. Anchor must be for the root domain.
    if anchor.domain != cap.root_domain:
        raise AnchorFreshnessViolation(
            f"anchor domain {anchor.domain} != capability root {cap.root_domain}"
        )

    # 3. THE BOUNDARY: anchor age must respect BOTH the issuer's warranty
    #    and the domain's own rotation period. A cache TTL longer than either
    #    creates a use-after-revocation window.
    anchor_age = now - anchor.fetched_at
    effective_bound = min(
        cap.min_anchor_freshness,
        anchor.rotation_period - clock_skew,
    )
    if effective_bound <= 0:
        raise AnchorFreshnessViolation(
            f"unsatisfiable freshness: rotation_period={anchor.rotation_period}s "
            f"<= clock_skew={clock_skew}s"
        )
    if anchor_age > effective_bound:
        raise AnchorFreshnessViolation(
            f"anchor age {anchor_age:.1f}s exceeds bound {effective_bound:.1f}s "
            f"(warranted={cap.min_anchor_freshness}s, "
            f"rotation_period={anchor.rotation_period}s); "
            f"refusing to honor capability under possibly-retired key"
        )

    # 4. Key must be currently active, not merely present in a retention cache.
    if cap.signing_key_id in anchor.keys_retired:
        raise AnchorFreshnessViolation(
            f"signing key {cap.signing_key_id} retired at "
            f"{anchor.keys_retired[cap.signing_key_id]}; capability minted under "
            f"a revoked key"
        )
    if cap.signing_key_id not in anchor.keys_active:
        raise AnchorFreshnessViolation(
            f"signing key {cap.signing_key_id} not in active set for {anchor.domain}"
        )

    return True


if __name__ == "__main__":
    now = time.time()
    # Reproduces the observed incident: 10-min cache, 5-min rotation.
    stale_anchor = AnchorDoc(
        domain="org-a",
        keys_active={"K_A1"},
        keys_retired={},
        rotation_period=300.0,
        fetched_at=now - 220.0,  # cached 220s ago, past rotation
    )
    cap = Capability(
        root_domain="org-a",
        signing_key_id="K_A1",
        min_anchor_freshness=180.0,
        expiry=now + 3600.0,
    )
    try:
        verify_delegated_capability(cap, stale_anchor, now)
    except AnchorFreshnessViolation as e:
        print(f"REJECTED (correct): {e}")
