# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-capability-token-whose-attestation-chain-re-binds-after-mid-task-key-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-capability-token-whose-attestation-chain-re-binds-after-mid-task-key-rotation.warrant.json
# Markdown SHA-256:   0af3da5a178bc305c3ec2a619a43b9eec39fd6e2af96639387cbed0d72430536
# Code AST SHA-256:   a6c8edc3efe77e72e02259537d01e210ce9e4a79ffdb2e0500b8b0135af979ba
# Verified Classes:   AttestationRebindError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class AttestationRebindError(RuntimeError):
    """Raised when a delegated capability token's attestation chain re-binds
    to a new key without a matching grant re-issuance."""
    pass


def validate_delegated_capability(
    token: dict,
    cache: dict,  # subject_id -> {"key_fingerprint", "attestation_epoch", "grant_nonce"}
) -> dict:
    subject = token["subject_id"]
    key_fp = token["attested_key_fingerprint"]
    epoch = token["attestation_epoch"]
    nonce = token["grant_nonce"]
    rotation_stmt = token.get("rotation_statement")

    # 1. Signature validity is assumed checked upstream; this function enforces
    #    identity continuity, which signatures alone cannot guarantee.
    prior = cache.get(subject)
    if prior is None:
        cache[subject] = {
            "key_fingerprint": key_fp,
            "attestation_epoch": epoch,
            "grant_nonce": nonce,
        }
        return token

    key_changed = prior["key_fingerprint"] != key_fp
    nonce_changed = prior["grant_nonce"] != nonce
    epoch_advanced = epoch > prior["attestation_epoch"]

    # 2. No rotation but different key: key substitution or subject collision.
    if key_changed and not epoch_advanced:
        raise AttestationRebindError(
            f"subject {subject}: key changed {prior['key_fingerprint']} -> {key_fp} "
            f"without epoch advance (prior epoch {prior['attestation_epoch']}, got {epoch})"
        )

    # 3. Epoch went backwards: replay of an older attestation.
    if epoch < prior["attestation_epoch"]:
        raise AttestationRebindError(
            f"subject {subject}: attestation_epoch regressed "
            f"{prior['attestation_epoch']} -> {epoch}"
        )

    # 4. Key rotated but grant was not re-issued: the re-binding hazard.
    if key_changed and not nonce_changed:
        if rotation_stmt is None:
            raise AttestationRebindError(
                f"subject {subject}: key rotated to {key_fp} under unchanged "
                f"grant nonce {nonce} with no rotation statement"
            )
        if rotation_stmt.get("previous_fingerprint") != prior["key_fingerprint"]:
            raise AttestationRebindError(
                f"subject {subject}: rotation statement previous_fingerprint "
                f"{rotation_stmt.get('previous_fingerprint')} does not match "
                f"cached {prior['key_fingerprint']}"
            )
        # Rotation is legitimate but the grant still authorizes the old key.
        # Refuse and force re-delegation rather than silently re-scoping.
        raise AttestationRebindError(
            f"subject {subject}: attestation re-bound to {key_fp} but grant "
            f"nonce {nonce} was issued for {prior['key_fingerprint']}; "
            f"re-delegation required"
        )

    # 5. Coherent update: rotation with fresh grant, or no change.
    cache[subject] = {
        "key_fingerprint": key_fp,
        "attestation_epoch": epoch,
        "grant_nonce": nonce,
    }
    return token
