# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-revoked-did-delegation-is-still-being-honored-mid-chain-in-cross-org-agent-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-revoked-did-delegation-is-still-being-honored-mid-chain-in-cross-org-agent-attestation.warrant.json
# Markdown SHA-256:   5af8418c75406d7bfd6d6eff7faab4e6e67cef1107ebc1fa0c873884728cf718
# Code AST SHA-256:   e98c51e109d54ca77833db8edee6a7935b51da3634e7e28ff5082ad43630b0c8
# Verified Classes:   ChainRevocationBypass, Link, Chain, DelegationVerifier
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ChainRevocationBypass(RuntimeError):
    """Raised when a multi-hop delegation chain is admitted without recursive status verification."""
    pass


@dataclass
class Link:
    vc_id: str
    issuer_did: str
    subject_did: str
    status_list_version: int
    revoked: bool = False


@dataclass
class Chain:
    links: list[Link] = field(default_factory=list)

    @property
    def depth(self) -> int:
        return len(self.links)

    def version_vector_key(self) -> str:
        # Sound cache key: incorporate every ancestor status-list version,
        # not just the leaf. A version advance on any link invalidates.
        h = hashlib.sha256()
        for link in self.links:
            h.update(f"{link.vc_id}:{link.status_list_version}".encode())
        return h.hexdigest()


class DelegationVerifier:
    def __init__(self, max_cache_ttl_s: int = 600, status_publish_interval_s: int = 30):
        self._cache: dict[str, bool] = {}
        self.max_cache_ttl_s = max_cache_ttl_s
        self.status_publish_interval_s = status_publish_interval_s

    def admit(self, chain: Chain) -> bool:
        if chain.depth == 0:
            raise ChainRevocationBypass("empty chain: no root delegation to anchor on")

        # Invariant: every link's status must be evaluated. A verifier that
        # checks only the leaf silently honors severed mid-chain warrants.
        status_checks = 0
        for i, link in enumerate(chain.links):
            status_checks += 1
            if link.revoked:
                # Revocation at any link severs the tail. The leaf VC is
                # byte-identical, so only this recursive walk catches it.
                raise ChainRevocationBypass(
                    f"revoked link at depth {i} (vc={link.vc_id}, issuer={link.issuer_did}); "
                    f"tail authority severed but leaf unrevoked"
                )

        if status_checks < chain.depth:
            # Structural guard: if the walk short-circuited, refuse rather
            # than fall back to leaf-only admission.
            raise ChainRevocationBypass(
                f"status_checks={status_checks} < chain_depth={chain.depth}: "
                f"leaf-only admission is unsound for multi-hop delegation"
            )

        # Cache is keyed on the version vector; an ancestor revocation advances
        # a version and forces a miss, closing the propagation window.
        key = chain.version_vector_key()
        if key in self._cache:
            return self._cache[key]

        if self.max_cache_ttl_s > self.status_publish_interval_s:
            # Static misconfiguration: the cache outlives the publish cadence,
            # guaranteeing a leak window of (ttl - interval) seconds.
            raise ChainRevocationBypass(
                f"cache_ttl={self.max_cache_ttl_s}s > publish_interval="
                f"{self.status_publish_interval_s}s: bounded leak window not closed"
            )

        self._cache[key] = True
        return True


def handle_request(chain: Chain) -> str:
    verifier = DelegationVerifier(max_cache_ttl_s=600, status_publish_interval_s=30)
    try:
        verifier.admit(chain)
    except ChainRevocationBypass as e:
        return f"REJECT: {e}"
    return "ADMIT"


# Demonstrates the 540s-style leak: mid-chain revoked, leaf live.
leaky_chain = Chain(links=[
    Link("vc_A_to_B", "did:web:orgA", "did:web:orgB", status_list_version=1, revoked=True),
    Link("vc_B_to_C", "did:web:orgB", "did:web:orgC", status_list_version=1, revoked=False),
])
print(handle_request(leaky_chain))
