# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-delegated-capability-token-silently-outlive-its-attestation-chain-when-crossing-a-vendor-trust-root-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-delegated-capability-token-silently-outlive-its-attestation-chain-when-crossing-a-vendor-trust-root-boundary.warrant.json
# Markdown SHA-256:   07c1daee7a3ab865e98ac60bca46421128b3b9e16bf2b9bcd2d0de09d4560b82
# Code AST SHA-256:   933b6e1d809fe9b7bfcdf5c4ce78a0b71108c83748155d23717fb7363fb628e8
# Verified Classes:   OrphanedDelegationError, Manifest, DelegatedCapabilityToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta


class OrphanedDelegationError(RuntimeError):
    """Raised when a delegated capability token's validity outlives the
    attestation chain that authorized it, under the relying party's policy."""


@dataclass
class Manifest:
    subject: str
    issued_at: datetime
    attestation_ttl: timedelta
    revoked: bool = False

    def is_live(self, now: datetime) -> bool:
        return (not self.revoked) and (now <= self.issued_at + self.attestation_ttl)


@dataclass
class DelegatedCapabilityToken:
    subject: str
    scope: str
    not_after: datetime
    chain: list[Manifest]  # leaf -> ... -> root


def verify_dct(
    dct: DelegatedCapabilityToken,
    now: datetime,
    policy: str,  # "T" (terminating) or "V" (validating)
    trusted_roots: set[str],
) -> None:
    if now > dct.not_after:
        raise OrphanedDelegationError(
            f"DCT for {dct.subject} expired at {dct.not_after.isoformat()}"
        )

    root = dct.chain[-1]
    if root.subject not in trusted_roots:
        raise OrphanedDelegationError(
            f"chain root {root.subject!r} not in relying-party trust store"
        )

    if policy == "T":
        # Path-terminating: only require the chain to reach a trusted root.
        # Freshness of intermediate manifests is NOT checked.
        return

    if policy == "V":
        # Path-validating: every link must be currently live and unrevoked.
        for link in dct.chain:
            if not link.is_live(now):
                raise OrphanedDelegationError(
                    f"attestation link {link.subject!r} is stale or revoked at "
                    f"{now.isoformat()}; DCT authority is orphaned"
                )
        return

    raise OrphanedDelegationError(f"unknown trust policy {policy!r}")


# Demonstration: DCT outlives its 24h manifest but is honored under Policy T.
t0 = datetime(2025, 6, 13, 12, 0, 0)
leaf = Manifest("vendor-a.example/instance-7", issued_at=t0, attestation_ttl=timedelta(hours=24))
root = Manifest("vendor-a.example/root", issued_at=t0, attestation_ttl=timedelta(days=365))
dct = DelegatedCapabilityToken(
    subject="vendor-a.example/instance-7",
    scope="read:ledger",
    not_after=t0 + timedelta(days=7),
    chain=[leaf, root],
)

verify_dct(dct, now=t0 + timedelta(hours=72), policy="T", trusted_roots={"vendor-a.example/root"})  # passes: orphaned
verify_dct(dct, now=t0 + timedelta(hours=72), policy="V", trusted_roots={"vendor-a.example/root"})  # raises
