# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-attestation-chain-when-a-delegated-agent-refreshes-its-short-lived-credential-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-attestation-chain-when-a-delegated-agent-refreshes-its-short-lived-credential-mid-handoff.warrant.json
# Markdown SHA-256:   628e07c2a41c87d958abf7863fef6eae54484f0cbd6a19ceb2c65ac4ec158cc5
# Code AST SHA-256:   50656b37c9fc10a42b29babc43c581ef9af1e6f566342e7cd720f43baea84196
# Verified Classes:   AttestationChainError, Link
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationChainError(RuntimeError):
    """Raised when a delegated agent's credential breaks issuer continuity."""
    pass


@dataclass(frozen=True)
class Link:
    subject: str      # delegate identity
    issuer: str       # who signed this link
    scope: str
    chain_hash: str   # hash binding the full chain up to this link


def verify_chain(chain: list[Link], leaf: Link, *, allow_re_root: bool = False) -> None:
    """
    Enforce issuer continuity: every link's issuer must equal the prior
    link's subject, and the leaf's issuer must equal the terminal subject.
    """
    if not chain:
        raise AttestationChainError("empty attestation chain")

    # Link-by-link continuity.
    for i in range(1, len(chain)):
        if chain[i].issuer != chain[i - 1].subject:
            raise AttestationChainError(
                f"broken chain at hop {i}: issuer {chain[i].issuer!r} "
                f"!= prior subject {chain[i - 1].subject!r}"
            )

    terminal = chain[-1].subject

    # Leaf must terminate the chain, unless explicitly re-rooted under policy.
    if leaf.issuer != terminal:
        if not allow_re_root:
            raise AttestationChainError(
                f"leaf issuer {leaf.issuer!r} does not terminate chain "
                f"(terminal subject {terminal!r}); refresh re-rooted the chain"
            )
        # Re-root path: the leaf must bind the same chain hash it claims to extend.
        expected = hashlib.sha256(
            (chain[-1].chain_hash + terminal).encode()
        ).hexdigest()
        if leaf.chain_hash != expected:
            raise AttestationChainError(
                "re-rooted leaf does not bind the presented chain hash; "
                "refusing to authorize under a foreign trust anchor"
            )


def refresh_leaf(chain: list[Link], leaf: Link, new_ttl_ok: bool) -> Link:
    """
    Simulate the refresh path. If the IdP mints a leaf whose issuer is not the
    terminal delegator, we must either reject or mark it as an explicit re-root.
    """
    if not new_ttl_ok:
        raise AttestationChainError("refresh rejected: TTL policy violation")

    terminal = chain[-1].subject
    refreshed = Link(
        subject=leaf.subject,
        issuer="idp-root",            # <- re-roots silently
        scope=leaf.scope,
        chain_hash=leaf.chain_hash,
    )
    if refreshed.issuer != terminal:
        # Caller must decide: re-delegate, or accept an explicit re-root.
        raise AttestationChainError(
            f"refresh would re-root chain: leaf issuer {refreshed.issuer!r} "
            f"!= terminal delegator {terminal!r}; re-delegate instead"
        )
    return refreshed
