OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

[Bug]: VolcengineKMSProvider caches an unpersisted ephemeral root key after a persist failure

Open Tong-bit-art opened this issue 2 months ago • 2 comments

Issue Origin

Observed or reproduced in a real environment

Bug Description

VolcengineKMSProvider caches the freshly generated root key in self._root_key before it is encrypted and written to disk. If that persist step fails, the provider raises ConfigError but leaves the never-persisted key in the instance cache.

get_root_key() starts with a fast path:

if self._root_key is not None:
    return self._root_key

so the next call returns that unpersisted key with no error at all. Every account key derived afterwards, and therefore every file key encrypted with it, becomes permanently undecryptable once the process restarts and a new root key is minted.

This is the same defect class that #3423 fixed for VaultProvider. That change left VolcengineKMSProvider untouched, although it has the identical structure and the identical guard message.

Steps to Reproduce

  1. Configure encryption.provider = "volcengine_kms" on a fresh install (no existing key_file).
  2. Cause a transient failure on the first persist attempt — a KMS 5xx, a read-only or full filesystem, or ~/.openviking not writable.
  3. Call get_root_key(). It raises ConfigError — correct so far.
  4. Call get_root_key() again (the ordinary operational retry, or simply the next request).

Expected Behavior

The retry should keep failing with ConfigError until the key can actually be persisted, exactly as VaultProvider does. No data should ever be encrypted under a key that was not durably stored.

Actual Behavior

The second call succeeds silently and returns a 32-byte root key that exists only in memory. The key file is still absent.

Minimal Reproducible Example

import tempfile
from pathlib import Path
from unittest.mock import AsyncMock

from openviking.crypto.providers import VolcengineKMSProvider

key_file = Path(tempfile.mkdtemp()) / "openviking-volcengine-root-key.enc"

p = VolcengineKMSProvider(
    region="cn-beijing",
    access_key_id="ak",
    secret_access_key="sk",
    key_id="kid",
    key_file=str(key_file),
)
p._encrypt_with_kms = AsyncMock(side_effect=RuntimeError("KMS 503"))

try:
    await p.get_root_key()   # ConfigError: ... refusing to start with ephemeral key
except Exception as e:
    print("attempt 1:", type(e).__name__)

key = await p.get_root_key()  # returns silently - no exception
print("attempt 2: got", len(key), "bytes; persisted?", key_file.exists())
# attempt 2: got 32 bytes; persisted? False

Error Logs

None. The second call raises nothing at all, which is the core of the problem — the guard message says "Refusing to start with ephemeral key (data loss risk)", but the retry does precisely that.

OpenViking Version

main @ df32bf6e50a40843438f9491a26069ca4bd08f1f

Python Version

3.11.9

Operating System

Windows

Model Backend

Other

Additional Context

openviking/crypto/providers.py:722-740 (current main):

self._root_key = secrets.token_bytes(32)

# Encrypt and store root key
try:
    encrypted_root_key = await self._encrypt_with_kms(self._root_key)
    self.key_file.parent.mkdir(parents=True, exist_ok=True)
    with open(self.key_file, "wb") as f:
        f.write(encrypted_root_key)
except Exception as e:
    raise ConfigError(
        f"Failed to persist root key to file. "
        f"Refusing to start with ephemeral key (data loss risk): {e}"
    )

Compare VaultProvider at the same file, lines 440-475, which #3423 gave both the explanatory comment and the self._root_key = None reset before raising.

The reset only ever clears a key generated inside this block: reaching line 725 requires self._root_key to still be None (checked at line 706), and the only other assignment is the early-returning load path at line 714. So the fix is scoped to the failure case.

TestVolcengineKMSProviderMock currently has one happy-path test and no equivalent of Vault's test_persist_failure_clears_cache_and_retries, which is why this survived.

I am not proposing a fix here — per CONTRIBUTING this touches encrypted file behavior, so I would like to confirm the boundary first. Happy to send a minimal PR that mirrors the Vault guard if that is the preferred shape.

Tong-bit-art avatar Oct 02 '26 09:10 Tong-bit-art

Fixed by #5561, merged into main (merge commit f20d9a77).

The change is the one-line guard VaultProvider already had, plus the contract test this provider was missing:

except Exception as e:
    self._root_key = None
    raise ConfigError(
        f"Failed to persist root key to file. "
        f"Refusing to start with ephemeral key (data loss risk): {e}"
    )

test_persist_failure_clears_cache_and_retries now exists on both providers and mirrors #3423's Vault test. Verified against merged main at d9352f2a8:

tests/unit/crypto          39 passed
-k persist_failure          2 passed   (Vault + Volcengine KMS)

Closing this — the reproducer in the issue no longer returns a key on the second get_root_key() call; it keeps raising ConfigError until the key is durably stored.

Tong-bit-art avatar Oct 05 '26 15:10 Tong-bit-art

Fixed by #5561 (merge commit \ 20d9a77) and verified against merged \main\ at \d9352f2a8: \ ests/unit/crypto\ 39 passed, including the new \ est_persist_failure_clears_cache_and_retries\ on both providers.

Tong-bit-art avatar Oct 06 '26 05:10 Tong-bit-art