# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-credential-whose-scope-graph-is-acyclic-but-whose-attestation-chain-is-not.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-credential-whose-scope-graph-is-acyclic-but-whose-attestation-chain-is-not.warrant.json
# Markdown SHA-256:   c24b0a5800d691e5bf68685f20b79255de0b2eade06a671f7dadb7eefa4bb4c5
# Code AST SHA-256:   eb194a089e2769b5fa4881f37573823ca2d97230871d708148bc28b87b0fce4b
# Verified Classes:   AttestationChainError, Link, KeyAuthorizationTable
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AttestationChainError(RuntimeError):
    """Raised when an AAIF attestation chain is invalid even though the
    delegated credential's scope-subgraph check passed."""


@dataclass
class Link:
    issuer: str
    subject: str
    scope: str
    issued_at: int
    signature_valid: bool


@dataclass
class KeyAuthorizationTable:
    # key_id -> list of (authorized_from, authorized_until) intervals
    intervals: dict = field(default_factory=dict)
    revoked: set = field(default_factory=set)

    def authorized_at(self, key_id: str, ts: int) -> bool:
        if key_id in self.revoked:
            return False
        for start, end in self.intervals.get(key_id, []):
            if start <= ts <= end:
                return True
        return False


def verify_delegated_credential(
    chain: list[Link],
    scope_check_passed: bool,
    key_table: KeyAuthorizationTable,
) -> None:
    if not scope_check_passed:
        raise AttestationChainError("scope-subgraph narrowing check failed")

    seen_issuers: set[str] = set()
    for hop, link in enumerate(chain):
        if not link.signature_valid:
            raise AttestationChainError(
                f"hop {hop}: signature invalid for {link.issuer}->{link.subject}"
            )
        if link.issuer in seen_issuers:
            # Scope graph is acyclic; the attestation chain need not be.
            # A repeated issuer means a fork or loop that the scope check
            # cannot observe.
            raise AttestationChainError(
                f"hop {hop}: attestation chain revisits issuer {link.issuer!r}; "
                f"chain is forked or looped — re-walk from root"
            )
        seen_issuers.add(link.issuer)
        if not key_table.authorized_at(link.issuer, link.issued_at):
            raise AttestationChainError(
                f"hop {hop}: issuer key {link.issuer!r} not authorized at "
                f"issued_at={link.issued_at}; cryptographic validity is not authority"
            )


# --- demonstration of the silent-acceptance boundary ---
if __name__ == "__main__":
    key_table = KeyAuthorizationTable(
        intervals={
            "P":  [(0, 10_000)],
            "A1": [(100, 5_000)],
            "A2": [(200, 900)],
        },
        revoked={"A2"},  # revocation written to key table, not scope store
    )
    chain = [
        Link("P",  "A1", "read:db/orders",              100, True),
        Link("A1", "A2", "read:db/orders/row",          200, True),
        Link("A2", "A3", "read:db/orders/row/status",   800, True),
    ]
    # Scope check passes: each hop narrows correctly.
    # A naive verifier returns here and grants access.
    try:
        verify_delegated_credential(chain, scope_check_passed=True, key_table=key_table)
    except AttestationChainError as exc:
        print(f"REJECTED: {exc}")
