# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-skill-attestation-identity-binding-when-a-marketplace-re-signs-third-party-skills-under-a-rotating-issuer-key.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-skill-attestation-identity-binding-when-a-marketplace-re-signs-third-party-skills-under-a-rotating-issuer-key.warrant.json
# Markdown SHA-256:   fba0a4cbbd58f2c8049ef60c6bf9e2c0b7c08d3966943df50e2effc4c8e515b9
# Code AST SHA-256:   01f615ef670ae679d23c3828389d644740c3b77260e6fc1ae8c4290605c339f7
# Verified Classes:   AttestationBindingError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import hmac


class AttestationBindingError(RuntimeError):
    """Raised when a re-signed skill attestation does not bind the presented
    capability manifest to the issuer identity the runtime is trusting."""
    pass


def verify_skill_attestation(
    envelope: dict,
    presented_manifest: dict,
    trusted_issuer_keys: dict,
    marketplace_key: bytes,
) -> None:
    """
    Posture B verification. The signed payload MUST cover:
      subject_hash, manifest_hash, issuer_id, issuer_key_id.
    The marketplace signature is evidence of observation, not a grant.
    """
    signed = envelope["signed"]
    sig = envelope["marketplace_sig"]

    # 1. Recompute the manifest hash from what we are about to load.
    manifest_bytes = _canonical_json(presented_manifest)
    presented_hash = hashlib.sha256(manifest_bytes).hexdigest()

    # 2. The signed predicate must actually cover the manifest hash.
    if "manifest_hash" not in signed:
        raise AttestationBindingError(
            "signed payload omits manifest_hash; capability manifest is unsigned "
            "(attestation laundering exposure)"
        )
    if not hmac.compare_digest(signed["manifest_hash"], presented_hash):
        raise AttestationBindingError(
            f"manifest hash mismatch: signed={signed['manifest_hash']} "
            f"presented={presented_hash}"
        )

    # 3. Issuer identity must be inside the signature, not advisory.
    issuer_id = signed.get("issuer_id")
    issuer_key_id = signed.get("issuer_key_id")
    if not issuer_id or not issuer_key_id:
        raise AttestationBindingError(
            "issuer_id/issuer_key_id not covered by signature"
        )
    if issuer_id not in trusted_issuer_keys:
        raise AttestationBindingError(f"issuer {issuer_id} not trusted")
    if issuer_key_id not in trusted_issuer_keys[issuer_id]:
        raise AttestationBindingError(
            f"issuer key {issuer_key_id} not trusted for {issuer_id}"
        )

    # 4. Verify marketplace signature over the full signed tuple.
    payload = _canonical_json(signed)
    expected = hmac.new(marketplace_key, payload, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, sig):
        raise AttestationBindingError("marketplace signature invalid")

    # 5. Subject hash must match the bundle we are loading.
    if signed["subject_hash"] != envelope["bundle_hash"]:
        raise AttestationBindingError("subject hash does not match bundle")


def _canonical_json(obj: dict) -> bytes:
    import json
    return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()
