Skip to content

fix: correct keyring fallback logic in try_decrypt_data#70

Open
yahao333 wants to merge 1 commit into
WecomTeam:mainfrom
yahao333:fix/try-decrypt-data-keyring-fallback
Open

fix: correct keyring fallback logic in try_decrypt_data#70
yahao333 wants to merge 1 commit into
WecomTeam:mainfrom
yahao333:fix/try-decrypt-data-keyring-fallback

Conversation

@yahao333

Copy link
Copy Markdown

改动

修复 try_decrypt_data 函数的密钥回退逻辑错误

src/crypto/keystore.rs 中,try_decrypt_data 函数存在致命 bug:第1步和第2步都调用 load_key_from_file(),导致完全相同的密钥被尝试两次,而 keyring 中的密钥从未被尝试。当使用系统 keyring 存储加密密钥时,加密的数据将无法被解密。

问题分析

修复前:

pub fn try_decrypt_data<T: serde::de::DeserializeOwned>(data: &[u8]) -> Result<T> {
    // 1. Try cached key (covers both keyring and file sources)
    if let Some(key) = load_key_from_file() {
        if let Ok(result) = decrypt_data::<T>(data, &key) {
            return Ok(result);
        }
        tracing::debug!("Cached key failed to decrypt, trying file key directly…");
    }

    // 2. Fall back to file key (in case cache holds a stale keyring key)
    let key = load_key_from_file().ok_or(...)?;
    decrypt_data(data, &key)
}

问题:

  • 第1步和第2步都使用 load_key_from_file()
  • 日志信息 "trying file key directly" 是误导性的
  • keyring 中的密钥从未被尝试

修复后:

pub fn try_decrypt_data<T: serde::de::DeserializeOwned>(data: &[u8]) -> Result<T> {
    // 1. Try file key first
    if let Some(key) = load_key_from_file() {
        if let Ok(result) = decrypt_data::<T>(data, &key) {
            return Ok(result);
        }
        tracing::debug!("File key failed to decrypt, trying keyring key…");
    }

    // 2. Fall back to keyring key (in case file key is stale or unavailable)
    if let Some(key) = load_key_from_keyring() {
        if let Ok(result) = decrypt_data::<T>(data, &key) {
            return Ok(result);
        }
        tracing::debug!("Keyring key also failed to decrypt");
    }

    Err(anyhow::anyhow!("解密数据失败(未找到有效密钥)"))
}

影响范围

此 bug 影响以下加密数据的解密:

  • bot.enc - 企业微信机器人凭证
  • mcp_config.enc - MCP 配置缓存

关联 Issue: #

检查项

  • 代码已自测通过
  • 无调试代码残留
  • 文档已同步更新(如有需要)

The try_decrypt_data function had a critical bug where both step 1 and
step 2 called load_key_from_file(), causing the same key to be tried
twice while the keyring key was never attempted. This prevented
successful decryption of data encrypted with the keyring key.

Now the function:
1. First tries the file key
2. On failure, falls back to the keyring key

Fixes data decryption failures for bot.enc and mcp_config.enc files
when the encryption key is stored in the system keyring.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant