# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bind-its-aaif-subject-key-before-first-credential-use-the-pre-attestation-key-substitution-window.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bind-its-aaif-subject-key-before-first-credential-use-the-pre-attestation-key-substitution-window.warrant.json
# Markdown SHA-256:   602ae263011f2d31f01155fec98fae58c09934c5b162e3d8fc0deae7fce38f9d
# Code AST SHA-256:   1bfbb81ad1c9b530109a308580a1b6c69a355513ed6ccd9395e7f095b8fc122e
# Verified Classes:   IdentityBindingError, Credential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hmac
from dataclasses import dataclass


class IdentityBindingError(RuntimeError):
    """Raised when a received AAIF credential is not bound to the instance's subject key."""
    pass


@dataclass(frozen=True)
class Credential:
    subject_pubkey: bytes
    issuer_id: str
    capabilities: frozenset
    not_before: float
    not_after: float
    issuer_signature: bytes


def activate_credential(
    credential: Credential,
    local_public_key: bytes,
    local_private_key,
    issuer_nonce: bytes,
    now: float,
) -> Credential:
    # Signature and temporal validity are necessary but not sufficient.
    if not verify_issuer_signature(credential):
        raise IdentityBindingError("issuer signature invalid")
    if not (credential.not_before <= now <= credential.not_after):
        raise IdentityBindingError("credential outside validity window")

    # The binding invariant: subject key must be byte-identical to ours.
    if not hmac.compare_digest(credential.subject_pubkey, local_public_key):
        raise IdentityBindingError(
            "credential subject_pubkey does not match local subject key; "
            "possible response substitution — refusing to activate"
        )

    # Proof of possession: sign the issuer's nonce with our private key.
    # The issuer must have echoed this nonce in its attestation response.
    proof = sign(local_private_key, issuer_nonce)
    if not verify_signature(credential.subject_pubkey, issuer_nonce, proof):
        raise IdentityBindingError("proof-of-possession over issuer nonce failed")

    return credential  # only now may this transition to ACTIVE
