OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

[Feature]: 加密能力下沉到 RAGFS 设计

Open baojun-zhang opened this issue 5 months ago • 0 comments

加密逻辑从 Python → Rust 迁移方案

一、当前架构与问题

1.1 当前数据流

Python (viking_fs.py)
  ├── read/write/grep/mv/write_file/read_file/write_file_bytes/
  │   read_file_bytes/append_file/write_context/_read_relation_table/
  │   _write_relation_table/_read_abstract_file/overview
  │   → 每个方法都手动调用 _encrypt_content / _decrypt_content
  │
  ├── FileEncryptor (Python, async)
  │   ├── encrypt(account_id, plaintext) → AES-GCM + Envelope 格式
  │   └── decrypt(account_id, ciphertext) → 解析 Envelope → AES-GCM 解密
  │
  └── RootKeyProvider → KMS / Vault / Local 密钥管理

        ↓ RAGFSBindingClient (PyO3 FFI)

Rust (ragfs)
  └── FileSystem trait → 纯字节读写,无加密感知
      └── MountableFS → 路由到各 plugin(每个 mount 内部已套 StatsWrappedFS)

1.2 当前问题

问题 严重度 说明
加密分支散落 18+ 个方法 高 每个读写方法都要手动判断 if self._encryptor:,代码重复且易遗漏
grep 性能退化 高 加密文件 grep 必须回退到 Python 层逐文件解密后匹配,无法在 Rust 侧整链完成
加密语义不一致 中 部分方法(如 _read_abstract_file、overview)直接调 self._encryptor.decrypt(),而 read 走 _decrypt_content wrapper
新操作无加密 中 未来新增文件操作需手动添加加密分支,容易遗漏
无法 pipeline 优化 低 Python GIL 限制,无法在 Rust 侧做批量解密/流式处理

1.3 当前涉及加密的方法清单

方法 加密/解密 位置
read 解密 → 切片 viking_fs.py:L388-L416
write 加密 → 写入 viking_fs.py:L427-L431
_grep_encrypted 解密后逐文件匹配 viking_fs.py:L870-L921
_read_abstract_file 解密 viking_fs.py:L1307-L1309
overview 解密 viking_fs.py:L1381-L1383
write_file 加密 viking_fs.py:L2286-L2287
read_file 解密 viking_fs.py:L2329-L2330
read_file_bytes 解密 viking_fs.py:L2361
write_file_bytes 加密 viking_fs.py:L2377-L2378
append_file 先解密 → 拼接 → 再加密 viking_fs.py:L2393-L2406
move_file 解密再加密(cp+rm) viking_fs.py:L2540-L2542
_recursive_copy_dir_with_encryption 逐文件 move viking_fs.py:L678-L708
mv temp 路径判断跳过加密 viking_fs.py:L636-L651
_read_relation_table 解密 viking_fs.py:L2214
_write_relation_table 加密 viking_fs.py:L2248-L2249
write_context 通过 write_file 间接加密 viking_fs.py:L2629-L2666

二、目标架构

2.1 设计原则

本方案围绕以下统一约束原则展开,后续每一节都是对它们的落地:

原则 含义
加密下沉 Rust 三层信封的全部计算(HKDF/AES-GCM/信封 build-parse)在 Rust 完成;Python 仅负责把 root_key 注入 Rust
不改 FileSystem trait 签名 加密是横向 wrapper,trait 方法签名零改动,所有 plugin 不动
增加 FsContext 通用旁路上下文(不可变) 上下文经 tokio::task_local! 旁路传递,不可变;当前仅承载 account_id(租户);加密只是其消费者之一。
是否加密在构造期决定,与 ctx 无关 root_key 是 binding 构造配置;仅当配置了 root_key 才套 EncryptionWrappedFS 层,否则栈里没有加密层(明文零额外开销)。
Stats 必须在最外层 端到端耗时(内含多种组合测绿-如:加密)必须被统计;wrapper 组装顺序为 Stats(xxxWrappedFS(Mountable))
account_id 与路径同源 加解密用的 account_id 必须与 _uri_to_path 解析路径用的是同一个 ctx,杜绝 KeyMismatch
存量兼容 HKDF 参数、Envelope 二进制布局与 Python 现状一致,存量加密文件必须能解开

2.2 整体分层与 wrapper 组装

加密能力作为横向 wrapper 插入到既有栈中。关键:Stats 在最外层,这样统计的耗时涵盖加解密;加密层在中间且仅在配置了 root_key 时才存在;MountableFS 负责路由,其每个 mount 内部还各有一层 per-mount Stats(现状已存在,见 mountable.rs)。

加密开启(配置含 root_key):              加密关闭(配置无 root_key):
┌────────────────────────────────┐      ┌────────────────────────────────┐
│ StatsWrappedFS (顶层/端到端)     │      │ StatsWrappedFS (顶层/端到端)     │
│   └ EncryptionWrappedFS         │      │   └ MountableFS  ← 无 Encryption │
│       └ MountableFS             │      │       └ 每 mount: Stats(plugin) │
│           └ 每 mount: Stats(...) │      │           └ LocalFS/S3FS/...     │
│               └ LocalFS/S3FS/... │      └────────────────────────────────┘
└────────────────────────────────┘

是否套 EncryptionWrappedFS 在 binding 构造期由"配置是否含 root_key"静态决定(§2.4);非加密场景的数据路径里根本没有加密层,无额外一跳。

两层 Stats 各司其职、互不替代:

  • 顶层 Stats:端到端口径,一次 read 的总时长(含解密),喂给"整体性能"观测。
  • per-mount Stats:每个后端的纯 I/O 口径,喂给现有 get_mount_stats / get_all_stats,用于定位是哪个后端慢。

为何加密不是 plugin、而是 wrapper:plugin 是纵向存储后端(localfs/s3fs/...),加密是横向切面。若在每个 plugin 内实现加密 = 7 份重复代码、7 处 bug 面、新增 plugin 必须记得加密。wrapper 模式一处实现、对所有后端透明。

2.3 通用上下文 FsContext —— 旁路传递

2.3.1 为什么用 task_local 旁路,而不是 trait 形参

上下文(account_id 等)不能进 FileSystem trait 方法签名(会污染核心 trait、逼所有 plugin 改),也不应让每个 wrapper 去读全局 thread/contextvar。采用 tokio::task_local!:

// crates/ragfs/src/core/context.rs

/// 文件系统上下文(不可变快照,定义见 §2.3.3)。当前仅承载 account_id(租户)。
pub type FsContext = std::sync::Arc<FsContextInner>;

tokio::task_local! {
    /// 当前 task(future)绑定的 FS 上下文。
    pub static FS_CTX: FsContext;
}

为什么是 task_local! 而不是 thread_local!:binding 内部用多线程 tokio runtime。一个 future 在 .await 让出后可能被调度到另一个 worker 线程继续 poll。thread_local 的值绑定线程,跨 worker 迁移后读不到;task_local 的值绑定 future,随 future 迁移、跨 .await 不丢、并发 task 间天然隔离。

2.3.2 无竞态证明

binding.read(ctx_a, ...) → FS_CTX.scope(ctx_a, async { top.read().await })
   即使 .await 让出、迁移到其他 worker 线程,wrapper 内 FS_CTX.try_with(...) 仍读到 ctx_a ✓
binding.read(ctx_b, ...) → FS_CTX.scope(ctx_b, async { ... })   ← ctx_b 绑定到另一个 future,完全隔离

2.3.3 访问 helper:FsContextView 统一收敛

避免每个 wrapper 重复写 FS_CTX.try_with(...).ok().flatten() 和散落的魔法字符串:

// crates/ragfs/src/core/context.rs

/// FsContext 是不可变快照:构造后不再被任何操作修改。
/// 进入 FS_CTX.scope 的值是一份 clone,wrapper 只读不写。
pub type FsContext = std::sync::Arc<FsContextInner>;

/// 上下文内容(不可变)。字段只增不改:构造时一次性填好,之后只读。
#[derive(Clone)]
pub struct FsContextInner {
    account_id: String,            // 租户标识(account_id 即租户)
    // 后续如需新增只读字段在此扩展,并保持"构造后不可变"
}

impl FsContextInner {
    pub fn new(account_id: impl Into<String>) -> Self {
        Self { account_id: account_id.into() }
    }
    pub fn account_id(&self) -> &str { &self.account_id }
}

/// 只读视图:统一封装"从 task_local 取当前 ctx",未设置时返回空视图(不 panic)。
pub struct FsContextView { inner: Option<FsContext> }

impl FsContextView {
    pub fn current() -> Self {
        Self { inner: FS_CTX.try_with(|c| c.clone()).ok() }
    }
    /// 租户标识;未设置 ctx 时返回 None。
    pub fn account_id(&self) -> Option<&str> {
        self.inner.as_ref().map(|c| c.account_id())
    }
}

FsContext 设计为不可变对象:用 Arc<FsContextInner> 承载、字段私有只读、无任何 setter,进入 FS_CTX.scope 的值是 clone。任何 wrapper 都只能读,杜绝某个操作中途篡改 ctx 影响后续 wrapper 或并发 task。Arc 使跨 .await/跨 worker 线程克隆为零拷贝(仅引用计数)。

2.3.4 ctx 防护机制(必须,防止空 ctx 引发系统异常)

fs_ctx 是"每次与 ragfs 交互都应存在"的通用对象,但 Rust 侧绝不能假定它一定存在或一定含某个 key。统一防护规则:

场景 wrapper 行为 理由
FS_CTX 未设置(try_with 返回 Err) FsContextView::current() 返回空视图,所有 get() 返回 None,不 panic task_local 未进 scope 时(如某些直接单测)不能崩
ctx 存在但缺 account_id(加密层存在)且读到密文 返回 Error::internal("account_id missing"),不静默返回密文 静默返回密文 = 把密文当明文给上层,数据错误
ctx 存在但缺 account_id,读到明文 直接透传 明文无需 account_id

要点:"ctx 是否为空"只影响"能否取到某个 key",绝不直接等价于"是否加密"。是否加密永远由"栈中是否套了 EncryptionWrappedFS 这层"在构造期决定(§2.4),与 ctx 内容无关。

2.3.5 ctx 字段约定

字段 说明
account_id 租户标识(account_id 即租户,无单独 tenant_id)。用于 HKDF 派生 Account Key,也是路径隔离的依据

当前只承载 account_id 一个字段。未来确有需要时,作为只读字段扩展 FsContextInner(保持不可变)即可,无需改 FileSystem trait。

2.4 加密的开关:构造期决定,root_key 与上下文无关

root_key 是 binding 构造期配置项,不是运行时上下文。它在创建 RAGFSBindingClient 时一次性传入,全程不可变,与每次请求的 fs_ctx 完全无关。account_id 来自 ctx(每请求不同),root_key 来自构造配置(进程内恒定)——二者职责分明。

仅当配置里 root_key 有值,才构造 EncryptionWrappedFS;否则根本不套这层(你的要求 #3)。这样非加密场景的数据路径是 Stats(Mountable),不会每次多走一跳 EncryptionWrappedFS:

加密开启(配置含 root_key):   Stats( Encryption( Mountable ) )
加密关闭(配置无 root_key):   Stats(            Mountable   )   ← 无 Encryption 层

细节:

  1. RAGFSBindingClient 实例化发生在 create_agfs_client()(agfs_utils.py:L164),不是模块导入期(__init__.py 仅拿类引用)。
  2. 其调用方 _init_storage(core.py:L250)与 bootstrap_encryption(core.py:L263)同处一个 async 方法,可以重排。把"取 root_key"提前到构造 binding 之前(详见 §2.6.2),即可在构造期把 root_key 作为配置传入。

2.5 三层信封模式与迁移边界

┌─────────────────────────────────────────────────────────────┐
│ L1: Root Key (32 bytes)  来源: KMS / Vault / 本地文件           │
│     → VikingFS 初始化时 Python 获取,作为构造配置传入 binding(§2.6) │
├─────────────────────────────────────────────────────────────┤
│ L2: Account Key  派生: HKDF-SHA256(salt, ikm=RootKey, info)   │
│       salt = b"openviking-kek-salt-v1"                        │
│       info = b"openviking:kek:v1:" + account_id               │
│     → Rust 侧懒加载缓存 HashMap<account_id,[u8;32]> + RwLock    │
├─────────────────────────────────────────────────────────────┤
│ L3: File Key + Data IV   File Key/IV = rand::random()         │
│     File Key 加解密: AES-256-GCM(AccountKey, FileKey)          │
│     数据加解密:      AES-256-GCM(FileKey, DataIV, Content)     │
│     → 全部 Rust                                                │
└─────────────────────────────────────────────────────────────┘

2.5.1 加密常量直接固化进 Rust(不走配置)

以下都是编译期常量,必须在 crates/ragfs/src/crypto/mod.rs 中硬编码,与 Python 现状逐字节一致,不通过 configure() 配置项传递(配置传递会引入"配置漂移→存量全解不开"的风险):

项 现状值(逐字节复刻 Python) Python 来源
HKDF salt b"openviking-kek-salt-v1" providers.py:L47
HKDF info 前缀 b"openviking:kek:v1:",info = 前缀 + account_id providers.py:L48
HKDF 算法 HKDF(SHA256, length=32),ikm=root_key providers.py:L100-L106
MAGIC / VERSION b"OVE1" / 0x01 encryptor.py:L32-L36
provider 常量 LOCAL=0x01 / VAULT=0x02 / VOLCENGINE=0x03 encryptor.py:L38-L40
信封头布局 struct.pack("!4sBBHHH", MAGIC, VERSION, provider_type, efk_len, kiv_len, div_len) —— 大端,固定 12 字节头 encryptor.py:L238-L250
字段顺序 header ‖ encrypted_file_key ‖ key_iv ‖ data_iv ‖ encrypted_content 同上
长度字段 efk/kiv/div 各 2 字节大端 u16;content 长度不入头部(取剩余) 同上

只有 root_key + provider_type 是运行时值(root_key 来自 KMS/Vault 网络 I/O),作为构造配置传入 binding(§2.6.2)。其余全是常量。

2.5.2 各层归属

层 操作 位置
L1 获取 Root Key(KMS/Vault/文件) Python:VikingFS 初始化时 await provider.get_root_key()
L1 Root Key 传入 Rust binding 构造期作为配置项传入(非运行时 ctx)
L2 HKDF 派生 + 缓存 Rust(hkdf+sha2,HashMap+RwLock)
L3 File Key/IV 生成、AES-GCM 加解密、信封 build/parse Rust

2.6 栈构造、配置注入与上下文传递(binding 单一接入)

接入方式范围:OpenViking 生产链路仅通过 PyO3 binding 使用 ragfs(create_agfs_client 无条件构造 binding)。

2.6.1 统一栈构造(消除 binding 内部重复,修复插件注册)

把"注册全部内建 plugin + 组装 wrapper 栈"收敛到一个 builder。构造入参是一个分段配置对象 RagfsConfig(对齐 ov.conf 的分段组织:encryption 是其中一段,未来新增能力只加新段、不改构造签名)。是否套加密层由 config.encryption 是否存在静态决定:

// crates/ragfs/src/core/builder.rs(新增)

/// binding 的分段配置——对齐 ov.conf 的分段组织。
/// 新增能力(如 cache/quota)只在此追加字段,不改 build_default_stack 签名。
#[derive(Default)]
pub struct RagfsConfig {
    pub encryption: Option<EncryptionConfig>,  // None → 明文;Some → 套加密层
    // 预留:未来其它段(如 pub cache: Option<CacheConfig>)
}

/// encryption 段:root_key 构造期固定、不可变。
pub struct EncryptionConfig { pub root_key: [u8; 32], pub provider_type: u8 }

/// 构建标准 ragfs 栈。config.encryption 为 None → 不套加密层(明文);Some → 套 EncryptionWrappedFS。
/// 无论是否加密,顶层都套 StatsWrappedFS(端到端统计,§4.3)。
pub async fn build_default_stack(config: RagfsConfig) -> RagfsStack {
    let mountable = Arc::new(MountableFS::new());
    register_builtin_plugins(&mountable).await;   // 唯一的内建插件注册点

    // 数据路径基底;encryption 段存在时在中间插入 EncryptionWrappedFS(不可变 root_key)。
    let data_fs: Arc<dyn FileSystem> = match config.encryption {
        Some(enc) => Arc::new(EncryptionWrappedFS::new(
            mountable.clone() as Arc<dyn FileSystem>,
            enc.root_key,        // [u8; 32],构造期固定、不可变
            enc.provider_type,   // u8
        )),
        None => mountable.clone() as Arc<dyn FileSystem>,  // 明文:不套加密层
    };
    let top = Arc::new(StatsWrappedFS::with_arc(data_fs));  // 顶层 stats 恒在
    RagfsStack { mountable, top }   // mountable 管挂载;top 走数据
}

/// 唯一内建插件注册序列(消除散落的 register_plugin 序列漂移)。
pub async fn register_builtin_plugins(fs: &MountableFS) {
    fs.register_plugin(MemFSPlugin).await;
    fs.register_plugin(KVFSPlugin).await;
    fs.register_plugin(QueueFSPlugin::new()).await;
    fs.register_plugin(SQLFSPlugin::new()).await;
    fs.register_plugin(LocalFSPlugin::new()).await;
    fs.register_plugin(ServerInfoFSPlugin::new()).await;
    #[cfg(feature = "s3")]
    fs.register_plugin(S3FSPlugin::new()).await;
}

StatsWrappedFS 现状构造签名是 new(Box<dyn FileSystem>)(stats_wrapper.rs:L22),需补 with_arc(inner: Arc<dyn FileSystem>) 构造(保留既有 new(Box<...>) 不动)。

2.6.2 配置注入(分段 config,encryption 为其中一段)—— 构造期一次性传入

binding 构造函数收一个分段配置 dict(对齐 ov.conf 的分段组织),encryption 只是其中一段,内含 root_key(32 字节密钥材料)+ provider_type(u8 信封头标识)。未来新增能力只追加新段,不改构造签名。配置构造完即固定不可变:

# openviking/service/core.py — initialize()(调整顺序:先取 root_key,再构造 binding)
#
# 现状顺序:_init_storage(内含 create_agfs_client) → bootstrap_encryption
# 调整为:  先 bootstrap_encryption 拿 encryptor、await 取 root_key
#           → 再 create_agfs_client(传入分段 config) 构造 binding
#
# 两步本就在同一 async 方法内,重排不影响其它逻辑。

self._encryptor = await bootstrap_encryption(full_config)  # FileEncryptor(provider),不触网
ragfs_cfg = {}  # binding 分段配置;未来新增段在此追加
if self._encryptor is not None:
    # get_root_key() 是 RootKeyProvider 的 async 方法(KMS/Vault 可能触网),此处可 await。
    root_key = await self._encryptor.provider.get_root_key()  # bytes(32)
    ragfs_cfg["encryption"] = {  # encryption 段
        "root_key": root_key,
        "provider_type": self._encryptor.provider_type,  # u8(新增只读 property)
    }

# create_agfs_client 透传分段 config 给 binding 构造函数
self._agfs_client = create_agfs_client(binding_config)
# openviking/utils/agfs_utils.py
def create_agfs_client(agfs_config, ragfs_config: dict | None = None):
    RAGFSBindingClient, _ = get_binding_client()
    # 构造期传入分段 config:无 encryption 段 → 明文栈;含 encryption 段 → 加密栈(§2.6.1)
    client = RAGFSBindingClient(config=ragfs_config or {})
    mount_agfs_backend(client, agfs_config)
    return client
// crates/ragfs-python/src/lib.rs — 构造期决定是否加密
#[pymethods]
impl RAGFSBindingClient {
    #[new]
    #[pyo3(signature = (config=None))]
    fn new(py: Python<'_>, config: Option<HashMap<String, PyObject>>) -> PyResult<Self> {
        let rt = tokio::runtime::Runtime::new()?;
        // 阶段 A(持 GIL):把分段 config 解析为 owned 强类型 RagfsConfig
        let cfg = config.unwrap_or_default();
        let mut ragfs_cfg = RagfsConfig::default();
        // 仅解析 encryption 段;其余段缺省。未来新增段在此追加分支。
        if let Some(enc_obj) = cfg.get("encryption") {
            let enc: HashMap<String, PyObject> = enc_obj.extract(py)?;
            let rk: Vec<u8> = enc.get("root_key")
                .ok_or_else(|| PyValueError::new_err("encryption.root_key required"))?
                .extract(py)?;
            let root_key: [u8; 32] = rk.as_slice().try_into()
                .map_err(|_| PyValueError::new_err("root_key must be 32 bytes"))?;
            let provider_type: u8 = enc.get("provider_type")
                .ok_or_else(|| PyValueError::new_err("encryption.provider_type required"))?
                .extract(py)?;
            ragfs_cfg.encryption = Some(EncryptionConfig { root_key, provider_type });
        }
        // 阶段 B:构造栈(无 encryption 段时无加密层)
        let stack = rt.block_on(build_default_stack(ragfs_cfg));
        Ok(Self { mountable: stack.mountable, top: stack.top, rt })
    }
    // 不再有 configure() 方法。
}

幂等性不再是问题:root_key 构造期一次性传入,没有"重复 configure"的场景。

为什么密钥材料只需 root_key(即便 provider 是 Vault/KMS)

三种 provider(Local / Vault / Volcengine KMS)的差异只在 get_root_key() 内部——即如何拿到那 32 字节明文 root_key:Local 读本地文件、Vault 经 transit 引擎解密、KMS 经 Decrypt 接口解密。一旦明文 root_key 到手,下游 derive_account_key(HKDF)与 encrypt_file_key/decrypt_file_key(AES-GCM)都落在 BaseProvider,对三种 provider 完全一致、纯本地计算,运行时再也不碰 Vault/KMS。因此职责边界天然清晰:

启动 bootstrap(Python 侧,一次性)            运行时(Rust 侧,每次 IO)
┌──────────────────────────────┐          ┌───────────────────────────┐
│ Vault/KMS 解密 → 明文 root_key │          │ HKDF(root_key, account_id) │
│ (addr/token/key_id/ak/sk/     │ 只传 32B │   → account_key            │
│  region/endpoint 全在此消耗)  │─────────▶│ AES-256-GCM 加解密 file_key │
└──────────────────────────────┘ root_key │ (与 provider 类型无关)     │
                                           └───────────────────────────┘
  • addr/token/key_id/access_key/secret_key/region/endpoint 等 provider 配置全部在 Python bootstrap 阶段被消费,唯一产物就是明文 root_key。把它们透传进 Rust 没有意义——运行时不会再发起任何 Vault/KMS 调用。
  • provider_type(u8)仍要传,但仅作信封头标识字节(!4sBBHHH 的 provider 字段),不参与解密:account_key 只由 root_key + account_id 派生,与 provider 无关。它是元数据,不是密钥材料。

已知限制(与 Python 现状对齐,非本方案引入的退化)

  1. 不支持进程内热轮换 root_key:root_key 构造期固化、不可变,轮换需重启进程重新 bootstrap。现状 Python 的 _root_key 进程级缓存(providers.py:L196)同样只在启动取一次,无差异。
  2. 不支持多 root_key 版本共存(旧文件旧 key / 新文件新 key):现信封头只有 VERSION 字节、无 root_key 版本 ID,现有实现也只缓存单个 _root_key,同样不支持。未来若需要,正确演进方向是把 root_key 扩展为 keyring(root_key_id → key 映射),而非往构造函数堆砌 KMS 参数。属独立演进项,不在本次范围。

2.6.3 上下文传递(fs_ctx)

VikingFS 数据方法用 _ctx_or_default(ctx) 解析(与 _uri_to_path 同源),构造 fs_ctx dict 经 binding 数据方法的 ctx 形参下传;binding read/write/grep 方法内用 FS_CTX.scope(fs_ctx, ...) 包裹对 self.top 的调用。下游 wrapper 一律通过 FsContextView::current() 读取(含空视图防护,§2.3.4)。

2.7 EncryptionWrappedFS 结构与读写实现

// crates/ragfs/src/core/encryption_wrapper.rs

/// 加密包装器 — 横向切面,可包装任意 FileSystem。与 StatsWrappedFS 同属 core/。
/// 仅当配置了 root_key 时才会被 builder 套上(§2.4):这层一旦存在,就一定加密。
/// root_key 构造期传入、不可变;account_id 每请求从 FsContext 读取。
pub struct EncryptionWrappedFS {
    inner: Arc<dyn FileSystem>,                      // 通常是 MountableFS
    root_key: [u8; 32],                              // 构造期固定、不可变(不再是 Option)
    provider_type: u8,                               // 写信封时记录的 provider 标识,不可变
    account_keys: RwLock<HashMap<String, [u8; 32]>>, // Account Key 懒加载缓存(按 account_id)
}

impl EncryptionWrappedFS {
    /// 由 builder 在"配置含 root_key"时构造。
    pub fn new(inner: Arc<dyn FileSystem>, root_key: [u8; 32], provider_type: u8) -> Self {
        Self { inner, root_key, provider_type, account_keys: RwLock::new(HashMap::new()) }
    }

    /// HKDF 派生 Account Key(懒加载缓存);salt/info 与 providers.py 逐字节一致。
    fn get_account_key(&self, account_id: &str) -> [u8; 32] {
        if let Some(k) = self.account_keys.read().unwrap().get(account_id) { return *k; }
        let k = crate::crypto::hkdf_sha256(&self.root_key, account_id.as_bytes());
        self.account_keys.write().unwrap().insert(account_id.to_string(), k);
        k
    }

    /// 从 ctx 取 account_id;缺失则报错(避免用错租户密钥,§2.3.4)。
    fn require_account_id(&self) -> Result<String> {
        FsContextView::current().account_id().map(str::to_string)
            .ok_or_else(|| Error::internal("account_id missing in FsContext"))
    }
}

#[async_trait]
impl FileSystem for EncryptionWrappedFS {
    async fn read(&self, path: &str, offset: u64, size: u64) -> Result<Vec<u8>> {
        // 单形态由启动期探针保证(§2.10):加密模式下落盘必为密文,运行时不再做形态判定。
        // 直接整读解析信封解密;若极端情况下读到非信封字节,parse_envelope 自然报错。
        let data = self.inner.read(path, 0, 0).await?;
        let account_id = self.require_account_id()?;
        let account_key = self.get_account_key(&account_id);
        let (_p, enc_key, key_iv, data_iv, ct) = crate::crypto::parse_envelope(&data)?;
        let file_key = crate::crypto::aes_gcm_decrypt(&account_key, &key_iv, &enc_key)?;
        let plaintext = crate::crypto::aes_gcm_decrypt(&file_key, &data_iv, &ct)?;
        Ok(slice(plaintext, offset, size))               // 解密后明文切片,语义同现状
    }

    async fn write(&self, path: &str, data: &[u8], offset: u64, flags: WriteFlag) -> Result<u64> {
        // 信封是不可分割整体:offset>0 的部分写会在密文中间插碎片 → 损坏文件,显式拒绝。
        // 与现状一致:binding write 恒为 offset=0/Create(见 lib.rs::write)。
        if offset != 0 {
            return Err(Error::internal("encrypted write only supports whole-file write (offset must be 0)"));
        }
        let account_id = self.require_account_id()?;
        let account_key = self.get_account_key(&account_id);
        let file_key: [u8; 32] = rand::random();
        let data_iv: [u8; 12] = rand::random();
        let ct = crate::crypto::aes_gcm_encrypt(&file_key, &data_iv, data)?;
        let key_iv: [u8; 12] = rand::random();
        let enc_key = crate::crypto::aes_gcm_encrypt(&account_key, &key_iv, &file_key)?;
        let envelope = crate::crypto::build_envelope(self.provider_type, &enc_key, &key_iv, &data_iv, &ct);
        self.inner.write(path, &envelope, 0, flags).await
    }

    // grep / 其余方法见 §2.8、§2.9
}

2.8 grep 的真实边界(加密层恒走解密遍历)

rg 的加速来自对磁盘明文字节做全文扫描;加密文件落盘是密文,rg 无法直接匹配。因此加密路径 grep 本质仍是"逐文件读→解密→明文匹配",与现状 _grep_encrypted 复杂度相同。迁移的真实收益是去掉 Python 逐文件 FFI 往返 + GIL,整链在 Rust 完成、可并行解密,而非"rg 直扫密文"。

grep/grep_internal/grep_file 是 trait 默认方法,且 LocalFS/S3FS 各自重写了 grep 直扫底层字节(s3fs、localfs)。

明文场景由构造期决定(栈中无 EncryptionWrappedFS 这层),grep 直接落到 plugin 重写版,保留原生 rg / 并发加速、零退化——无需本 wrapper 介入。EncryptionWrappedFS::grep 这层一旦存在就必然加密,因此恒走 trait 默认遍历 self.grep_internal(...),其内部 grep_file 调用的是 self.read(= 本 wrapper 的解密 read),对密文正确解密匹配、对明文透传。

致命退化警示:加密层的 grep 绝不能委托 self.inner.grep()——inner 路由到 plugin 重写版会直接对磁盘密文字节跑正则,加密文件全部漏匹配(静默的数据可见性丢失)。必须经 self.grep_internal → grep_file → self.read 解密后匹配。

复用 setup(消除复制粘贴):调 grep_internal 前需复刻 trait 默认 grep 的两步 setup(filesystem.rs:L250-L287):正则编译((?i) 前缀 + Regex::new)和 normalize_prefix_path。把正则编译抽成自由函数 pub(crate) fn compile_grep_regex(pattern, case_insensitive) -> Result<Regex>,默认 grep 与加密层共用(normalize_prefix_path 已是现成自由函数),不改任何 trait 签名:

// EncryptionWrappedFS::grep —— 这层只在加密时存在,故恒走解密遍历(无 root_key 分支)
async fn grep(&self, path, pattern, recursive, case_insensitive,
              node_limit, exclude_path, level_limit) -> Result<GrepResult> {
    let re = compile_grep_regex(pattern, case_insensitive)?;
    let base = normalize_prefix_path(path);
    let excl = exclude_path.map(normalize_prefix_path);
    let mut result = GrepResult::new();
    // trait 默认遍历:grep_file → self.read 自动解密
    self.grep_internal(&base, &base, &re, recursive, node_limit,
                       excl.as_deref(), level_limit, &mut result).await?;
    Ok(result)
}

2.9 完整 trait 方法处理清单(防语义退化)

EncryptionWrappedFS 实现 FileSystem 时,只有 read/write/grep 含加密逻辑,其余方法逐一显式委托 self.inner.xxx().await。实现前以 filesystem.rs 当前 trait 定义为准逐个核对(参照 StatsWrappedFS 已有的完整委托清单)。

默认方法陷阱:grep/grep_internal/grep_file/tree_directory/truncate/exists 都是 trait 默认方法,编译器不会因未覆写而报错,必须人工核对。

方法 处理 理由
read / write 普通文件内容加解密改写(§2.7);/queue、/serverinfo 虚拟控制路径透传 /queue/*/enqueue/dequeue/size 与 /serverinfo/* 返回的是插件协议/运行时信息,不是持久化文件内容,不能按信封解析或写成信封
grep 普通文件内容恒走默认遍历 self.grep_internal(§2.8);虚拟控制路径透传 普通文件经 grep_file→self.read 解密匹配,绝不委托 inner.grep;控制型插件不承载加密文件内容,透传保留插件语义
tree_directory 显式委托 self.inner.tree_directory() 不读内容、无需解密;保留 S3FS 原生 tree 优化
truncate(默认方法) 不覆写,继承 trait 默认 默认实现 self.read→resize→self.write 经本 wrapper 自动得到"解密整文→截断→重新整写整加密";无 plugin 覆写 truncate,无原生优化可丢
exists(默认方法) 不覆写,继承 trait 默认 默认 self.stat(...).is_ok(),与加解密无关
create 普通文件写入空内容的合法信封(等价 self.write(path, b"", 0, Create));虚拟控制路径透传 空文件也是文件内容形态的一部分;加密模式下若透传到底层会产生裸 0 字节文件,后续 read 按信封解析失败并破坏单形态不变量
list/stat/mkdir/remove/remove_all/rename/read_dir/chmod/ensure_parent_dirs/ 其余 显式 self.inner.xxx().await 透传 不碰内容;显式委托保留 plugin 行为

trait 无 append:现状 append_file 是上层"读旧→拼接→写回"组合(非单 trait 方法)。迁移后 read 自动解密、write 自动整加密,正确性自动获得。原子性沿用现状上层语义:① 优先底层原子 rename(写临时文件再 rename);② 不支持时对同一 path 加写锁串行化。禁止就地按 offset 改写密文。

关于 mv:FileSystem trait 无 mv 方法,binding 的 mv 对应 trait 的 rename(old, new)(见 lib.rs::mv → fs.rename),已包含在上表"透传"行。rename 只移动/改名、不读写文件内容——密文 blob 原样跟随路径移动,且同租户内 account_id 不变,故透传即正确,无需解密重加密。另需区分两条易混路径:

  • binding mv / trait rename:纯路径操作 → 透传(本表)。
  • Python viking_fs.move_file:是上层"读旧→写新→删旧"组合(viking_fs.py:L2529-L2542),其 read/write 各自经加密层自动解密/加密,正确性自动获得(与 append 同理);而 cp/persist_temp 的目录级整体搬运走 raw 字节通道(§3.4.2),不经加密层。
  • 跨 account 限制:raw 字节搬运与 trait rename 只能用于同一加密 account 域(/local/{account_id} 使用路径内 account,非 local 控制路径使用 _system)。跨域复制/移动会把源 account 的密文信封放到目标 account 路径下,目标 account key 无法解密,必须 fail-fast 或走上层"源 ctx 解密→目标 ctx 重加密"业务路径。

校验:实现后 cargo 编译可暴露"无默认实现方法"的遗漏;对默认方法(grep 系列/tree_directory/truncate/exists)必须按上表逐一人工核对。新增 trait 方法时,须同步在所有 wrapper 补委托。

2.10 单形态不变量与启动期形态探针

目标:系统中的文件只允许一种形态——要么全明文、要么全密文。任何与当前模式不符的存量数据,启动即失败(fail-fast),绝不进入"混合容忍"状态。这避免了"明文模式静默读出密文乱码""加密模式把存量明文当数据"等隐患。

单一防线——启动期探针:单形态由启动期一次性自检保证,运行时不做任何形态判定(加密层 read 直接解密,§2.7)。探针锚点是系统账户文件 /local/_system/accounts.json。选它的依据:

  • 它是系统首次启动即创建、且每次启动 LegacyAPIKeyManager.load() 必读的文件(legacy.py:L74-82)。
  • 它走业务加解密通道(_read_json/_write_json 经 _async_agfs.read / encrypt_bytes,legacy.py:L637/L664,注释明确 "rely on file-level AES encryption")。因此它的磁盘字节头直接反映系统形态:加密模式下带 OVE1 信封,明文模式下是裸 JSON。

探针逻辑(在 binding 构造完、load() 之前,用 raw 通道读原始字节、不经加密层,仅看文件头):

probe_storage_form(mode):                    # mode = 当前配置:Plaintext | Encrypted
    raw = read_raw("/local/_system/accounts.json")   # 走 self.mountable,拿磁盘原始字节
    if raw is NotFound:
        return                               # 全新系统:无存量数据,任何模式都合法,放行
    on_disk = Encrypted if has_magic(raw, "OVE1") else Plaintext
    if on_disk != mode:
        panic(f"storage form mismatch: on-disk={on_disk}, configured={mode}. "
              f"refusing to start to avoid corrupting/misreading existing data")

判定矩阵:

accounts.json 状态 当前配置 结论
文件不存在 明文 / 加密 全新系统,放行(首次写入即确立形态)
裸 JSON(无 MAGIC) 明文 一致,放行
裸 JSON(无 MAGIC) 加密 panic:存量明文 + 配置加密
有 OVE1 信封 加密 一致,放行
有 OVE1 信封 明文 panic:存量密文 + 配置明文

要点:

  • fail-fast:形态不符在启动期就 panic 拒绝服务,不等到运行时读到具体文件才暴露,杜绝"跑一半才发现数据读不了"。
  • 零运行时开销:探针仅启动一次;明文模式运行时仍无任何 wrapper,符合 §2.4 原则。
  • 用 raw 字节判定:探针走 read_raw(§3.4.2),只读文件头看 MAGIC,不触发解密、不需要 account_id,明文/加密两种模式下都能安全执行。
  • 本期不做自动迁移:探针只做"一致性校验 + 拒绝启动",不负责把明文批量转密文(或反向)。形态转换是独立的运维/迁移工具职责,不在本方案范围。

三、关键设计决策

3.1 为什么不在 trait 加参数 / 不在每个 plugin 实现加密?

  • trait 加参数:污染核心 I/O 抽象、所有 plugin 都要改、无法运行时开关。
  • 每个 plugin 各自实现:7 份重复代码、7 处 bug 面、新增 plugin 易遗漏。
  • wrapper 模式:一处实现、对所有后端透明、运行时由 root_key 开关。

3.2 为什么 FsContext 不可变、用 task_local 旁路

  • 不可变:Arc<FsContextInner> 承载、字段私有只读、无 setter(§2.3.3)。任何操作中途都改不了 ctx,避免被某次调用篡改污染后续 wrapper 或并发 task。当前只含 account_id(租户)。
  • task_local 而非 trait 形参:不改 trait、不改 plugin;而非 thread_local:多线程 runtime 下 future 跨 worker 迁移,thread_local 读不到(§2.3.1)。
  • 与 Python dict 天然对应,binding 入口一次性转成不可变 FsContext,无需额外序列化(§2.6.3)。

3.3 为什么 Stats 在最外层

一次操作的端到端耗时必须涵盖加解密(加解密本身是 CPU 开销,是性能观测的重点)。故 Stats(Encryption(Mountable))(加密关闭时为 Stats(Mountable)):顶层 Stats 量端到端、含 crypto;底层 per-mount Stats 量各后端纯 I/O。两层口径互补,缺一不可。

3.4 为什么是否加密由"加密层是否存在"决定,而非 ctx

fs_ctx 是通用上下文(account_id 供加密,未来可供审计/统计),"有没有 ctx""ctx 里有没有某 key"都不该等价于"要不要加密"。加密开关是构造期确定的系统配置:配置含 root_key 就套 EncryptionWrappedFS,否则不套(§2.4)。这样 fs_ctx 与加密彻底解耦、可被任意 wrapper 复用;非加密场景也没有多余的加密层一跳。

3.5 为什么 Root/Account Key 可迁 Rust

仅 L1 root_key 获取涉及网络 I/O,且只在启动执行一次(由 Python await provider.get_root_key(),作为 binding 构造配置传入)。传入后是 32 字节常量。L2 HKDF、L3 AES-GCM 均纯本地确定性计算。迁移后 Rust 成为加密唯一活跃实现;Python RootKeyProvider.get_root_key() 接口保留,BaseProvider.encrypt_file_key/decrypt_file_key/derive_account_key 与 FileEncryptor.encrypt/decrypt 标记 deprecated,待回归验证后清理。

3.6 兼容性

  • 存量加密文件:HKDF 参数与 Envelope 布局逐字节固化(§2.5.1),Rust 解析与 Python 完全兼容。
  • 明文文件:is_encrypted() 经 MAGIC 检测,透传。
  • 加密开关:未配置 root_key 时栈里没有加密层(明文模式)。
  • 空/异常 ctx:Rust 侧防护(§2.3.4),不 panic;加密层读到密文却无 account_id 报错而非静默返回密文。

四、风险评估

风险 概率 影响 缓解
AES-GCM / HKDF 与 Python 不一致 低 高 标准 crate + 与 cryptography 交叉验证;salt/info 逐字节固化(§2.5.1)
Envelope 二进制布局与存量不一致 低 高 头部 !4sBBHHH(大端)/字段序/provider 常量逐字节复刻;双向字节级互通单测(§2.5.1)
account_id 与路径错配 → KeyMismatch/数据损坏 高 高 _fs_ctx 与 _uri_to_path 同源(同一 _ctx_or_default(ctx));单测覆盖"显式 ctx≠bound ctx"(§3.4.1)
空/异常 ctx 致 Rust panic 中 高 FsContextView 空视图防护;缺 key 降级不崩;读密文缺 account_id 报错而非静默返回密文(§2.3.4)
wrapper 默认方法(grep/tree/truncate/exists)未覆写致退化 中 高 编译器不报缺失,按 §2.9 逐一人工核对
grep 加密文件漏匹配 中 高 加密模式走 self.grep_internal(经解密 read),禁止委托 inner.grep;单测覆盖加密 grep 命中(§2.8)
cp/persist 误触解密 中 高 cp 走密文整体搬运、不附 account_id;加密层只服务业务逐文件读写(§3.4.2)
binding 构造时序:root_key 获取 中 高 RAGFSBindingClient 非模块导入期构造;initialize() 内重排为"先 await get_root_key → 再构造 binding(crypto)",root_key 构造期传入、不可变(§2.4/§2.6.2)
KMS/Vault 参数是否需下沉 Rust — — 不需要:provider 配置(addr/token/key_id/ak/sk…)仅在 Python bootstrap 消费产出明文 root_key;运行时只用 root_key+provider_type,不再触网(§2.6.2)
root_key 热轮换 / 多版本共存 低 中 本方案不支持,与 Python 现状(单 _root_key 进程缓存、信封无版本 ID)一致;未来经 keyring 扩展,非本次范围(§2.6.2)
存量数据与配置模式形态不符(明文↔加密切换) 中 高 单形态不变量:启动期以 accounts.json 头 MAGIC 探测,形态不符 fail-fast panic(§2.10);运行时不做额外形态判定,仅由信封解析自然报错;本期不做自动迁移
task_local 跨线程读不到 ctx 低 高 tokio::task_local! + FS_CTX.scope(),值绑 future(§2.3)
加密 write 部分写(offset>0)损坏信封 低 高 显式拒绝 offset≠0,与现状整写语义对齐(§2.7)
append/truncate 加密原子性 中 中 trait 无 append(上层组合);truncate 继承默认经 self.read/write 整加密;原子性沿用上层 rename/写锁,禁止就地改写密文(§2.9)

附录 A:RAGFS 架构分层

crates/ragfs/src/
├── core/
│   ├── filesystem.rs        ← FileSystem trait(+ compile_grep_regex 自由函数)
│   ├── mountable.rs         ← MountableFS(路由;每 mount 内 StatsWrappedFS)
│   ├── stats_wrapper.rs     ← StatsWrappedFS(+ with_arc 构造)
│   ├── context.rs           ← FsContext + task_local + FsContextView   ← 新增
│   ├── encryption_wrapper.rs← EncryptionWrappedFS                       ← 新增
│   ├── builder.rs           ← build_default_stack / register_builtin_plugins ← 新增
│   └── ...
├── crypto/mod.rs            ← Envelope + AES-GCM + HKDF(常量固化)       ← 新增
├── plugins/                 ← 存储后端(不涉及)
├── server/                  ← HTTP API   ← 整目录删除(HTTP 模式移除)
└── lib.rs

附录 B:binding 数据流

viking_fs.read(uri, ctx)
  path   = _uri_to_path(ctx)          ← _ctx_or_default(ctx)
  fs_ctx = _fs_ctx(ctx)   ── 同源 ──   ← 同一 ctx → 同一 account_id
  async_client.read(path, fs_ctx=..)
  binding.read(path, ctx=fs_ctx)
        │
        ▼
  FS_CTX.scope(ctx, async {
      top.read(path, offset, size)     ← StatsWrappedFS(顶层, 含加解密耗时)
        └─ EncryptionWrappedFS.read    ← 仅加密配置下存在此层;明文模式直连 MountableFS
             └─ MountableFS.read       ← 路由 + per-mount Stats
                  └─ LocalFS/S3FS/...   ← 纯字节
  }).await

baojun-zhang avatar Jun 03 '26 10:06 baojun-zhang