nodedb 0.2.1

Local-first, real-time, edge-to-cloud hybrid database for multi-modal workloads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
// SPDX-License-Identifier: BUSL-1.1

//! HashiCorp Vault transit-engine key provider.
//!
//! ## Flow
//!
//! At startup NodeDB reads the wrapped DEK ciphertext blob from
//! `ciphertext_blob_path`, then calls:
//!
//! ```text
//! POST {addr}/v1/{mount}/decrypt/{key_name}
//! Body: { "ciphertext": "<vault:v1:...>" }
//! Header: X-Vault-Token: <token>
//! ```
//!
//! The `plaintext` field in the JSON response is base64-encoded 32 bytes.
//!
//! Key rotation calls `rewrap/{key_name}` with the old ciphertext blob and
//! persists the new ciphertext blob to disk before returning the new key.
//!
//! # Security checks
//!
//! Both `token_path` and `ciphertext_blob_path` are passed through
//! [`check_key_file`] before being read. Symlinks, world/group-readable
//! files, and files owned by a different UID are rejected.

use std::path::PathBuf;

use base64::Engine as _;
use tracing::info;
use zeroize::Zeroizing;

use crate::Result;

use super::KeyProvider;
use super::key_file_security::check_key_file;

/// Vault transit-engine key provider.
pub struct VaultKeyProvider {
    pub(super) addr: String,
    pub(super) token_path: PathBuf,
    pub(super) key_name: String,
    pub(super) mount: String,
    pub(super) ciphertext_blob_path: PathBuf,
    client: reqwest::Client,
}

impl VaultKeyProvider {
    pub(super) fn new(
        addr: String,
        token_path: PathBuf,
        key_name: String,
        mount: String,
        ciphertext_blob_path: PathBuf,
    ) -> Self {
        Self {
            addr,
            token_path,
            key_name,
            mount,
            ciphertext_blob_path,
            client: reqwest::Client::new(),
        }
    }

    fn read_token(&self) -> Result<String> {
        check_key_file(&self.token_path)?;
        std::fs::read_to_string(&self.token_path)
            .map(|s| s.trim().to_owned())
            .map_err(|e| crate::Error::Encryption {
                detail: format!(
                    "failed to read Vault token from {}: {e}",
                    self.token_path.display()
                ),
            })
    }

    fn read_ciphertext_blob(&self) -> Result<String> {
        check_key_file(&self.ciphertext_blob_path)?;
        std::fs::read_to_string(&self.ciphertext_blob_path)
            .map(|s| s.trim().to_owned())
            .map_err(|e| crate::Error::Encryption {
                detail: format!(
                    "failed to read Vault ciphertext blob from {}: {e}",
                    self.ciphertext_blob_path.display()
                ),
            })
    }

    fn write_ciphertext_blob(&self, ciphertext: &str) -> Result<()> {
        std::fs::write(&self.ciphertext_blob_path, ciphertext).map_err(|e| {
            crate::Error::Encryption {
                detail: format!(
                    "failed to write Vault ciphertext blob to {}: {e}",
                    self.ciphertext_blob_path.display()
                ),
            }
        })
    }

    async fn decrypt_with_vault(&self, ciphertext: &str) -> Result<Zeroizing<[u8; 32]>> {
        let token = self.read_token()?;
        let url = format!(
            "{}/v1/{}/decrypt/{}",
            self.addr.trim_end_matches('/'),
            self.mount,
            self.key_name
        );

        let resp = self
            .client
            .post(&url)
            .header("X-Vault-Token", &token)
            .json(&serde_json::json!({ "ciphertext": ciphertext }))
            .send()
            .await
            .map_err(|e| crate::Error::Encryption {
                detail: format!("Vault HTTP request failed: {e}"),
            })?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(crate::Error::Encryption {
                detail: format!("Vault decrypt returned {status}: {body}"),
            });
        }

        let body: serde_json::Value = resp.json().await.map_err(|e| crate::Error::Encryption {
            detail: format!("Vault response JSON parse failed: {e}"),
        })?;

        let plaintext_b64 = body
            .pointer("/data/plaintext")
            .and_then(|v| v.as_str())
            .ok_or_else(|| crate::Error::Encryption {
                detail: "Vault response missing /data/plaintext field".into(),
            })?;

        decode_32_byte_b64(plaintext_b64)
    }

    async fn rewrap_with_vault(&self, old_ciphertext: &str) -> Result<String> {
        let token = self.read_token()?;
        let url = format!(
            "{}/v1/{}/rewrap/{}",
            self.addr.trim_end_matches('/'),
            self.mount,
            self.key_name
        );

        let resp = self
            .client
            .post(&url)
            .header("X-Vault-Token", &token)
            .json(&serde_json::json!({ "ciphertext": old_ciphertext }))
            .send()
            .await
            .map_err(|e| crate::Error::Encryption {
                detail: format!("Vault rewrap HTTP request failed: {e}"),
            })?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(crate::Error::Encryption {
                detail: format!("Vault rewrap returned {status}: {body}"),
            });
        }

        let body: serde_json::Value = resp.json().await.map_err(|e| crate::Error::Encryption {
            detail: format!("Vault rewrap response JSON parse failed: {e}"),
        })?;

        body.pointer("/data/ciphertext")
            .and_then(|v| v.as_str())
            .map(|s| s.to_owned())
            .ok_or_else(|| crate::Error::Encryption {
                detail: "Vault rewrap response missing /data/ciphertext field".into(),
            })
    }
}

#[async_trait::async_trait]
impl KeyProvider for VaultKeyProvider {
    async fn unwrap_key(&self) -> Result<Zeroizing<[u8; 32]>> {
        let ciphertext = self.read_ciphertext_blob()?;
        let key = self.decrypt_with_vault(&ciphertext).await?;
        info!(
            mount = %self.mount,
            key_name = %self.key_name,
            "Vault transit key unwrapped successfully"
        );
        Ok(key)
    }

    async fn rotate(&self) -> Result<Zeroizing<[u8; 32]>> {
        let old_ciphertext = self.read_ciphertext_blob()?;

        // Rewrap with Vault (no plaintext leaves Vault during rewrap).
        let new_ciphertext = self.rewrap_with_vault(&old_ciphertext).await?;
        self.write_ciphertext_blob(&new_ciphertext)?;

        // Decrypt the new ciphertext to get the new plaintext key.
        let key = self.decrypt_with_vault(&new_ciphertext).await?;
        info!(
            mount = %self.mount,
            key_name = %self.key_name,
            "Vault transit key rotated successfully"
        );
        Ok(key)
    }
}

fn decode_32_byte_b64(b64: &str) -> Result<Zeroizing<[u8; 32]>> {
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(b64)
        .map_err(|e| crate::Error::Encryption {
            detail: format!("Vault plaintext base64 decode failed: {e}"),
        })?;
    if bytes.len() != 32 {
        return Err(crate::Error::Encryption {
            detail: format!(
                "Vault plaintext must be 32 bytes after base64 decode, got {}",
                bytes.len()
            ),
        });
    }
    let mut key = Zeroizing::new([0u8; 32]);
    key.copy_from_slice(&bytes);
    Ok(key)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt as _;

    /// Minimal mock HTTP server using `axum`.
    ///
    /// The mock responds to:
    ///   POST /v1/transit/decrypt/mykey  → 200 with plaintext
    ///   POST /v1/transit/decrypt/badkey → 403
    fn spawn_mock_vault(port: u16) -> tokio::task::JoinHandle<()> {
        use axum::{Router, routing::post};

        tokio::spawn(async move {
            let app = Router::new()
                .route(
                    "/v1/transit/decrypt/mykey",
                    post(|| async {
                        // 32 bytes of 0x42 base64-encoded.
                        let plaintext =
                            base64::engine::general_purpose::STANDARD.encode([0x42u8; 32]);
                        axum::Json(serde_json::json!({
                            "data": { "plaintext": plaintext }
                        }))
                    }),
                )
                .route(
                    "/v1/transit/decrypt/badkey",
                    post(|| async {
                        (
                            axum::http::StatusCode::FORBIDDEN,
                            axum::Json(serde_json::json!({
                                "errors": ["permission denied"]
                            })),
                        )
                    }),
                )
                .route(
                    "/v1/transit/rewrap/mykey",
                    post(|| async {
                        axum::Json(serde_json::json!({
                            "data": { "ciphertext": "vault:v1:newwrapped==" }
                        }))
                    }),
                );

            let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{port}"))
                .await
                .unwrap();
            axum::serve(listener, app).await.unwrap();
        })
    }

    /// Write a file with secure Unix permissions (0o600) for use in tests.
    #[cfg(unix)]
    fn write_secure(path: &std::path::Path, content: &[u8]) {
        use std::io::Write as _;
        let mut f = std::fs::File::create(path).unwrap();
        f.write_all(content).unwrap();
        drop(f);
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap();
    }

    #[tokio::test]
    #[cfg(unix)]
    async fn vault_unwrap_happy_path() {
        let port = 18201u16;
        let _srv = spawn_mock_vault(port);
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let dir = tempfile::tempdir().unwrap();
        let token_path = dir.path().join("token");
        let blob_path = dir.path().join("blob");
        write_secure(&token_path, b"fake-token");
        write_secure(&blob_path, b"vault:v1:someciphertext==");

        let provider = VaultKeyProvider::new(
            format!("http://127.0.0.1:{port}"),
            token_path,
            "mykey".into(),
            "transit".into(),
            blob_path,
        );

        let key = provider.unwrap_key().await.unwrap();
        assert_eq!(*key, [0x42u8; 32]);
    }

    #[tokio::test]
    #[cfg(unix)]
    async fn vault_auth_error_path() {
        let port = 18202u16;
        let _srv = spawn_mock_vault(port);
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let dir = tempfile::tempdir().unwrap();
        let token_path = dir.path().join("token");
        let blob_path = dir.path().join("blob");
        write_secure(&token_path, b"bad-token");
        write_secure(&blob_path, b"vault:v1:cipher==");

        let provider = VaultKeyProvider::new(
            format!("http://127.0.0.1:{port}"),
            token_path,
            "badkey".into(),
            "transit".into(),
            blob_path,
        );

        let err = provider.unwrap_key().await.unwrap_err();
        let detail = format!("{err:?}");
        assert!(
            detail.contains("403") || detail.contains("permission"),
            "expected auth error, got: {detail}"
        );
    }

    #[tokio::test]
    #[cfg(unix)]
    async fn vault_rotate_updates_blob() {
        let port = 18203u16;
        let _srv = spawn_mock_vault(port);
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let dir = tempfile::tempdir().unwrap();
        let token_path = dir.path().join("token");
        let blob_path = dir.path().join("blob");
        write_secure(&token_path, b"fake-token");
        write_secure(&blob_path, b"vault:v1:original==");

        let provider = VaultKeyProvider::new(
            format!("http://127.0.0.1:{port}"),
            token_path,
            "mykey".into(),
            "transit".into(),
            blob_path.clone(),
        );

        let key = provider.rotate().await.unwrap();
        assert_eq!(*key, [0x42u8; 32]);

        // Blob on disk should have been updated to the new ciphertext.
        let new_blob = std::fs::read_to_string(&blob_path).unwrap();
        assert_eq!(new_blob.trim(), "vault:v1:newwrapped==");
    }

    #[tokio::test]
    #[cfg(unix)]
    async fn vault_insecure_token_file_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let token_path = dir.path().join("token");
        let blob_path = dir.path().join("blob");

        use std::io::Write as _;
        // Token file with insecure permissions (0o644).
        let mut f = std::fs::File::create(&token_path).unwrap();
        f.write_all(b"some-token").unwrap();
        drop(f);
        std::fs::set_permissions(&token_path, std::fs::Permissions::from_mode(0o644)).unwrap();
        write_secure(&blob_path, b"vault:v1:cipher==");

        let provider = VaultKeyProvider::new(
            "http://127.0.0.1:1".into(), // unreachable — error before HTTP
            token_path,
            "mykey".into(),
            "transit".into(),
            blob_path,
        );

        let err = provider.unwrap_key().await.unwrap_err();
        let detail = format!("{err:?}");
        assert!(
            detail.contains("insecure") || detail.contains("644"),
            "expected insecure-permissions error on token file, got: {detail}"
        );
    }
}