# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-hardware-attested-agent-credential-has-silently-outlived-its-bound-workload.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-hardware-attested-agent-credential-has-silently-outlived-its-bound-workload.warrant.json
# Markdown SHA-256:   efc824ac06e5c4e5cc4888083175ee3094d023044716a5465106d36aefc4ef26
# Code AST SHA-256:   2a93d608946a54ff542a3ece99886952ee0bf210a06bd668009685de7dfbb8d4
# Verified Classes:   AttestationBindingError, AttestationDoc, WorkloadClaim
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
import hashlib
from dataclasses import dataclass


class AttestationBindingError(RuntimeError):
    """Raised when a hardware-attested credential is not bound to the live workload."""
    pass


@dataclass
class AttestationDoc:
    sub: str
    pcr_set: frozenset            # measurements the document attests to
    user_data: bytes              # binding field (nonce or static enrollment value)
    minted_at: float              # unix seconds
    credential_exp: float


@dataclass
class WorkloadClaim:
    sub: str
    process_start_time: float
    declared_pcr_set: frozenset


def admit_peer(
    doc: AttestationDoc,
    claim: WorkloadClaim,
    challenge_nonce: bytes,
    seal_policy_pcrs: frozenset,
    verify_policy_pcrs: frozenset,
    nonce_ledger: dict,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    # 1. Freshness: document must bind the per-handshake nonce, not a static value.
    if doc.user_data != hashlib.sha256(challenge_nonce).digest():
        raise AttestationBindingError(
            f"binding field is not the live challenge nonce for {doc.sub}: "
            f"likely a replayed sealed-cache attestation"
        )

    # 2. Temporal binding: document must postdate the claimed process start.
    if doc.minted_at < claim.process_start_time:
        raise AttestationBindingError(
            f"attestation for {doc.sub} minted {claim.process_start_time - doc.minted_at:.1f}s "
            f"before the claimed process start; predecessor artifact reused"
        )

    # 3. Measurement completeness: seal policy must cover everything the verifier checks.
    if not verify_policy_pcrs.issubset(seal_policy_pcrs):
        missing = verify_policy_pcrs - seal_policy_pcrs
        raise AttestationBindingError(
            f"seal policy omits PCRs {sorted(missing)} that the verifier requires; "
            f"restart with altered code would pass"
        )

    # 4. Nonce single-use: reject replay of a nonce already consumed for this sub.
    key = (doc.sub, hashlib.sha256(challenge_nonce).digest())
    if key in nonce_ledger:
        raise AttestationBindingError(
            f"nonce replay detected for {doc.sub} at {nonce_ledger[key]:.0f}"
        )
    nonce_ledger[key] = now

    # 5. Expiry and subject match.
    if doc.credential_exp <= now:
        raise AttestationBindingError(f"credential for {doc.sub} expired")
    if doc.sub != claim.sub:
        raise AttestationBindingError(
            f"subject mismatch: doc={doc.sub} claim={claim.sub}"
        )
