# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tee-attestation-quote-as-non-transferable-across-a-delegated-sub-agent-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tee-attestation-quote-as-non-transferable-across-a-delegated-sub-agent-handoff.warrant.json
# Markdown SHA-256:   2b741e6d132f3bed449a4edbbcf8c1678e356de56e235b96a76fcd134ea42aaf
# Code AST SHA-256:   e0e496433a12bf9bf9eff3276253d9c86944b9587c20dceb47d1c84191d5d8b4
# Verified Classes:   AttestationBindingError, Quote, ActingPrincipal
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class AttestationBindingError(RuntimeError):
    """Raised when a presented TEE quote does not bind to the acting principal."""


@dataclass(frozen=True)
class Quote:
    measurement: str          # hex digest of the measured runtime image
    nonce: str                # verifier-issued challenge this quote answers
    issued_to: str            # logical principal the nonce was issued to
    issued_at: float
    ttl_s: float
    posture_session: str      # continuous posture channel bound to this quote

    def is_expired(self, now: Optional[float] = None) -> bool:
        return (now if now is not None else time.time()) > self.issued_at + self.ttl_s


@dataclass(frozen=True)
class ActingPrincipal:
    identity: str             # logical agent id (e.g., "executor-B1")
    measurement: str          # actual runtime measurement of the executing process
    posture_session: str      # posture channel this process is actually on
    delegated_from: Optional[str] = None


def admit_action(
    principal: ActingPrincipal,
    presented: Quote,
    verifier_nonce: str,
    allowlist: frozenset[str],
    now: Optional[float] = None,
) -> None:
    """
    Verify that the presented quote attests the acting principal, not an ancestor.
    Raises AttestationBindingError on any binding failure.
    """
    now = now if now is not None else time.time()

    if presented.is_expired(now):
        raise AttestationBindingError(
            f"quote expired for {principal.identity}; ttl={presented.ttl_s}s"
        )

    # Nonce must be the one the verifier issued for THIS hop, not the parent's.
    if presented.nonce != verifier_nonce:
        raise AttestationBindingError(
            f"nonce mismatch for {principal.identity}: quote answers "
            f"{presented.nonce!r}, verifier issued {verifier_nonce!r}"
        )

    # The nonce must have been issued to the acting principal, not its delegator.
    if presented.issued_to != principal.identity:
        raise AttestationBindingError(
            f"quote was issued to {presented.issued_to!r} but presented by "
            f"{principal.identity!r}; delegation does not transfer attestation"
        )

    # The measured image in the quote must equal the acting process's image.
    if presented.measurement != principal.measurement:
        raise AttestationBindingError(
            f"measurement inheritance detected: quote attests "
            f"{presented.measurement[:16]}..., acting process is "
            f"{principal.measurement[:16]}..."
        )

    # Continuous posture must be bound to the same subject as the quote.
    if presented.posture_session != principal.posture_session:
        raise AttestationBindingError(
            f"posture channel {presented.posture_session!r} is not bound to "
            f"acting principal {principal.identity!r} "
            f"(actual channel {principal.posture_session!r})"
        )

    # Only after binding holds do we consult the allowlist.
    if presented.measurement not in allowlist:
        raise AttestationBindingError(
            f"measurement {presented.measurement[:16]}... not on allowlist"
        )


def handle_handoff(parent_quote: Quote, child: ActingPrincipal, verifier_nonce: str) -> None:
    """
    Simulate the observed failure: parent forwards its own quote to the child.
    """
    allowlist = frozenset({parent_quote.measurement})
    admit_action(
        principal=child,
        presented=parent_quote,   # <-- the bug: parent's quote, child's action
        verifier_nonce=verifier_nonce,
        allowlist=allowlist,
    )


if __name__ == "__main__":
    q = Quote(
        measurement=hashlib.sha256(b"planner-image").hexdigest(),
        nonce="n-parent",
        issued_to="planner-A",
        issued_at=time.time(),
        ttl_s=300.0,
        posture_session="ps-A",
    )
    b1 = ActingPrincipal(
        identity="executor-B1",
        measurement=hashlib.sha256(b"executor-image+unreviewed-adapter").hexdigest(),
        posture_session="ps-A",   # inherited channel: also wrong
        delegated_from="planner-A",
    )
    try:
        handle_handoff(q, b1, verifier_nonce="n-child")
    except AttestationBindingError as e:
        print(f"REJECTED: {e}")
