# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-credential-subject-divergence-when-a-federated-verifier-silently-rewrites-the-sub-claim-during-vc-normalization.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-credential-subject-divergence-when-a-federated-verifier-silently-rewrites-the-sub-claim-during-vc-normalization.warrant.json
# Markdown SHA-256:   dd7d84f82212dca61d705de96b48c5cfcbff4f6890fe48b1410cea4c570ee654
# Code AST SHA-256:   98fbbd5ba0c2b7ce9350f9b066bb6a4ba3b7cdad3bd479026c227dcbfddf3022
# Verified Classes:   SubjectBindingError, VerifiedEnvelope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SubjectBindingError(RuntimeError):
    """Raised when the emitted credential subject diverges from the signed subject
    without a signed alias chain covering the difference."""
    pass


@dataclass
class VerifiedEnvelope:
    signed_payload: dict          # canonicalized bytes that the proof actually covered
    emitted_subject: str          # subject after verifier normalization
    proof_verified: bool
    signed_aliases: list[str]     # alsoKnownAs entries asserted *inside* the signed payload


def extract_signed_subject(signed_payload: dict) -> str:
    # The subject as it existed in the bytes the signature covered.
    return signed_payload["credentialSubject"]["id"]


def assert_subject_binding(env: VerifiedEnvelope, requested_scope: str) -> str:
    if not env.proof_verified:
        raise SubjectBindingError("proof not verified; cannot bind subject")

    signed = extract_signed_subject(env.signed_payload)
    emitted = env.emitted_subject

    if emitted == signed:
        return signed

    # Divergence is only tolerable if the emitted subject is a signed alias.
    if emitted in env.signed_aliases:
        return emitted

    # Otherwise the verifier rewrote the subject outside the signed envelope:
    # this is the capability-escalation path. Fail closed.
    raise SubjectBindingError(
        f"subject divergence: signed={signed!r} emitted={emitted!r} "
        f"scope={requested_scope!r} — normalization occurred after proof "
        f"verification and is not covered by a signed alias chain"
    )


def authorize(env: VerifiedEnvelope, requested_scope: str) -> str:
    bound_subject = assert_subject_binding(env, requested_scope)
    # Authorization scope is derived from the *bound* (signed) subject only.
    return f"grant:{hashlib.sha256(bound_subject.encode()).hexdigest()[:16]}:{requested_scope}"
