# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-attested-identity-when-a-delegation-chain-crosses-an-issuer-boundary-mid-run.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-attested-identity-when-a-delegation-chain-crosses-an-issuer-boundary-mid-run.warrant.json
# Markdown SHA-256:   70a8ec2a4b0de35763a3407c5113987e8fd2b05ae8dee7257f5702a8bbfe2798
# Code AST SHA-256:   e72be67cc03c02635f16d9fe8a30d8664b22f2581d6647039cf69e45d3f47bc0
# Verified Classes:   WorkloadBindingLost, Credential, Chain
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class WorkloadBindingLost(RuntimeError):
    """Raised when a credential in a delegation chain no longer denotes the attested workload."""
    pass


@dataclass
class Credential:
    iss: str
    sub: str
    scope: list
    wl_binding: Optional[str] = None      # origin workload measurement, if preserved
    sensitive: bool = False


@dataclass
class Chain:
    hops: list = field(default_factory=list)

    def terminal(self) -> Credential:
        return self.hops[-1]


def cross_issuer_mint(origin: Credential, new_iss: str, logical_sub: str,
                      scope: list, sensitive: bool) -> Credential:
    """Mint a delegated credential at an issuer boundary.

    Correct behavior: propagate origin.wl_binding so the terminal verifier can
    re-check it. The bug being guarded against is dropping it here.
    """
    return Credential(
        iss=new_iss,
        sub=logical_sub,
        scope=scope,
        wl_binding=origin.wl_binding,   # MUST propagate; dropping this is the failure
        sensitive=sensitive,
    )


def verify_at_point_of_use(chain: Chain, live_measurement: str) -> None:
    """Verify the terminal credential against the live process measurement.

    A verifier that only checks signatures/scopes returns here without error even
    when the binding was laundered away. This one refuses that.
    """
    term = chain.terminal()
    if term.sensitive and term.wl_binding is None:
        raise WorkloadBindingLost(
            f"credential from {term.iss} carries sensitive scope {term.scope} "
            f"but no workload binding; cannot prove executing workload was attested"
        )
    if term.wl_binding is not None and term.wl_binding != live_measurement:
        raise WorkloadBindingLost(
            f"workload rebinding: credential bound to {term.wl_binding!r} "
            f"presented by live measurement {live_measurement!r} (reschedule?)"
        )


def run_across_boundary(origin: Credential, live_measurement: str,
                        sensitive: bool) -> None:
    # Boundary hop: issuer B mints without propagating binding (the observed bug).
    hop = cross_issuer_mint(origin, new_iss="B", logical_sub="agent-7f3a",
                            scope=["call:toolX"], sensitive=sensitive)
    hop.wl_binding = None  # simulate the laundering observed in the field
    chain = Chain(hops=[origin, hop])
    verify_at_point_of_use(chain, live_measurement)


if __name__ == "__main__":
    m = hashlib.sha256(b"image||config").hexdigest()
    origin = Credential(iss="A", sub=m, scope=["read:kb"], wl_binding=m)
    try:
        run_across_boundary(origin, live_measurement=m, sensitive=True)
    except WorkloadBindingLost as e:
        print("BLOCKED:", e)   # binding lost at issuer boundary -> hard stop
