# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-hardware-attested-agent-identity-has-silently-degraded-to-software-key-equivalence-in-aaif-credential-issuance.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-hardware-attested-agent-identity-has-silently-degraded-to-software-key-equivalence-in-aaif-credential-issuance.warrant.json
# Markdown SHA-256:   cac6d53965458a0c7be22c59f14566925887a4a7d80b9e6c8bdefe420715f24f
# Code AST SHA-256:   134d1d8a4feddc02d2d2c07d10d147a31cdbe05046e85b81a4fb679ac71d8ea9
# Verified Classes:   AttestationDegradedError
# Defensive Guards:   6 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

class AttestationDegradedError(RuntimeError):
    """Raised when attestation evidence chain-validates to an unpinned EK root,
    silently degrading a hardware-key credential to software-key equivalence."""
    pass


PINNED_EK_ROOTS = {
    # issuer_id -> set of acceptable EK certificate issuer CNs (pinned vendor roots)
    "aaif-prod-01": {"ACME TPM EK CA", "ACME TPM EK CA G2"},
}


def verify_attestation_against_pin(issuer_id: str, evidence: dict) -> None:
    """
    Verify AAIF attestation evidence in the SAFE order:
      1. EK cert chain must terminate in a pinned root for this issuer.
      2. Quote signature must verify against the AK bound to that EK.
      3. PCR digest must match the golden set.
    Any out-of-order or trust-on-first-use path is a degradation.

    `evidence` shape:
      {
        "ek_cert_issuer_cn": str,
        "ek_cert_chain": [str, ...],       # leaf -> root CNs
        "quote_sig_verified": bool,
        "ak_bound_to_ek": bool,
        "pcr_digest": str,
        "golden_pcr_digest": str,
      }
    """
    pinned = PINNED_EK_ROOTS.get(issuer_id)
    if pinned is None:
        raise AttestationDegradedError(
            f"issuer {issuer_id!r} has no pinned EK root set; "
            f"cannot distinguish hardware from software-equivalent keys"
        )

    chain = evidence.get("ek_cert_chain") or []
    if not chain:
        raise AttestationDegradedError(
            "attestation evidence carries no EK certificate chain; "
            "quote cannot be bound to a certified root of trust"
        )

    root_cn = chain[-1]
    if root_cn not in pinned:
        # This is the exact silent-degradation signature: a self-consistent
        # chain terminating in a synthetic EK root (e.g. "<worker-id>-local").
        raise AttestationDegradedError(
            f"EK chain terminates in unpinned root {root_cn!r} for issuer "
            f"{issuer_id!r}; credential would be software-key equivalent "
            f"despite key_protection=hardware"
        )

    # Only after the root is pinned do we trust the quote signature.
    if not evidence.get("quote_sig_verified"):
        raise AttestationDegradedError(
            "quote signature did not verify against the AK; "
            "PCR values are not trustworthy"
        )
    if not evidence.get("ak_bound_to_ek"):
        raise AttestationDegradedError(
            "AK is not bound to the pinned EK; quote may originate from a "
            "different TPM than the one holding the EK"
        )

    # PCR check is necessary but NOT sufficient; it runs last, gated by the above.
    if evidence.get("pcr_digest") != evidence.get("golden_pcr_digest"):
        raise AttestationDegradedError(
            "PCR digest does not match golden set; measured boot state drifted"
        )
