# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-attest-after-a-mid-chain-credential-refresh-and-why-the-aaif-attested-until-watermark-must-be-monotonic-per-hop-rather-than.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-attest-after-a-mid-chain-credential-refresh-and-why-the-aaif-attested-until-watermark-must-be-monotonic-per-hop-rather-than.warrant.json
# Markdown SHA-256:   cc38f5755eb01130a069bc916b1203f0ced9c8cc5454aa9aa8e79a8c09ae3f26
# Code AST SHA-256:   6b59a9abdc0455d4a5fb8058a1892d3bf511f74c63b5ebef05d37bdc0f3658bb
# Verified Classes:   AttestationLineageError, Attestation, WarrantProvenance, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class AttestationLineageError(RuntimeError):
    """Raised when a warrant's provenance digest does not descend from the
    attestation presented at the same hop, or when the lineage cannot be
    proven and the verifier is configured to fail closed."""
    pass


@dataclass
class Attestation:
    hop_id: str
    digest: str
    issuer_nonce: str
    attested_until: float
    predecessors: list[str] = field(default_factory=list)  # signed refresh edges


@dataclass
class WarrantProvenance:
    hop_id: str
    parent_attestation_digest: str
    parent_issuer_nonce: str


@dataclass
class Warrant:
    warrant_id: str
    provenance: list[WarrantProvenance]


def verify_digest_lineage(
    warrant: Warrant,
    presented: dict[str, Attestation],
    transparency_log_available: bool,
    fail_closed: bool = True,
) -> None:
    """Enforce per-hop monotonic attestation lineage for an in-flight warrant.

    A hop's presented attestation digest must equal the warrant's recorded
    parent digest, OR be a documented descendant of it (refresh edge present
    in the transparency log). If the log is unavailable, behavior is governed
    by fail_closed.
    """
    for prov in warrant.provenance:
        att = presented.get(prov.hop_id)
        if att is None:
            raise AttestationLineageError(
                f"hop {prov.hop_id}: no attestation presented for warrant "
                f"{warrant.warrant_id}"
            )

        if att.digest == prov.parent_attestation_digest:
            continue  # exact match: no refresh occurred mid-chain

        # Digest mismatch: a refresh happened. We must prove descent.
        if not transparency_log_available:
            if fail_closed:
                raise AttestationLineageError(
                    f"hop {prov.hop_id}: digest {att.digest} != warrant parent "
                    f"{prov.parent_attestation_digest}, and transparency log "
                    f"unavailable; failing closed (warrant {warrant.warrant_id})"
                )
            # fail-open path is the original bug; explicitly refuse to pretend
            # we verified anything.
            raise AttestationLineageError(
                f"hop {prov.hop_id}: cannot verify lineage; fail-open is "
                f"prohibited for attestation continuity"
            )

        if prov.parent_attestation_digest not in att.predecessors:
            raise AttestationLineageError(
                f"hop {prov.hop_id}: presented digest {att.digest} does not "
                f"descend from warrant parent {prov.parent_attestation_digest}; "
                f"substitution, not refresh (warrant {warrant.warrant_id})"
            )

        # Monotonic watermark check: the refreshed attestation must not have
        # an earlier attested_until than the epoch it replaces (guards against
        # replay of an older, longer-lived credential).
        if att.attested_until <= 0.0:
            raise AttestationLineageError(
                f"hop {prov.hop_id}: non-positive attested_until watermark"
            )


def digest_of(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()
