moshpit-agent 0.8.16

moshpit agent — holds identity keys in memory and serves them over a Unix socket
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
413
414
415
416
417
418
419
420
421
422
423
424
425
// Copyright (c) 2025 moshpit developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! Encrypted vault for storing key paths and their passphrases.
//!
//! The vault file uses the same crypto stack as moshpit private keys:
//! Argon2id → HKDF-SHA512 → AES-256-GCM-SIV.
//!
//! On-disk format:
//! ```text
//! b"moshpit-vault-v1"   (16 bytes, magic header)
//! [u32 len][cipher]     "aes-256-gcm-siv" or "none"
//! [u32 len][kdf]        argon2id PHC hash string or "none"
//! [u32 len][salt]       64 bytes of random salt
//! [u32 len][nonce]      12 bytes of random nonce
//! [u32 len][ciphertext] AES-256-GCM-SIV encrypted bincode-next payload
//! ```
//!
//! The plaintext payload is a bincode-next-serialised `Vec<VaultEntry>`.

use std::{
    fs::{File, OpenOptions},
    io::{Read as _, Write as _},
    path::{Path, PathBuf},
};

#[cfg(target_family = "unix")]
use std::os::unix::fs::OpenOptionsExt as _;

use anyhow::{Result, anyhow};
use argon2::{
    Argon2, PasswordHash, PasswordHasher as _, PasswordVerifier as _,
    password_hash::phc::SaltString,
};
use aws_lc_rs::{
    aead::{AES_256_GCM_SIV, Aad, Nonce, RandomizedNonceKey},
    hkdf::{HKDF_SHA512, Salt},
    rand::fill,
};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use bincode_next::{Decode, Encode, config::standard, decode_from_slice, encode_to_vec};
use bytes::{Buf as _, BytesMut};
use zeroize::{Zeroize, ZeroizeOnDrop};

const VAULT_HEADER: &[u8] = b"moshpit-vault-v1";
const VAULT_CIPHER: &str = "aes-256-gcm-siv";
const VAULT_NONE_CIPHER: &str = "none";
const VAULT_NONE_KDF: &str = "none";
const HKDF_INFO: &[u8] = b"moshpit-vault HKDF";

/// A single entry in the vault: a key path and its passphrase.
#[derive(Clone, Debug, Decode, Encode, Zeroize, ZeroizeOnDrop)]
pub(crate) struct VaultEntry {
    /// Absolute path to the private key file.
    pub(crate) key_path: String,
    /// Passphrase used to decrypt the key; empty string for unencrypted keys.
    pub(crate) passphrase: String,
}

/// The in-memory representation of the decrypted vault.
#[derive(Clone, Debug, Default)]
pub(crate) struct Vault {
    entries: Vec<VaultEntry>,
}

impl Drop for Vault {
    fn drop(&mut self) {
        self.zeroize();
    }
}

impl Vault {
    fn zeroize(&mut self) {
        for entry in &mut self.entries {
            entry.zeroize();
        }
        self.entries.clear();
    }

    /// Create an empty vault.
    #[must_use]
    pub(crate) fn new() -> Self {
        Self::default()
    }

    #[cfg(test)]
    fn remove(&mut self, key_path: &str) {
        self.entries.retain(|e| e.key_path != key_path);
    }

    /// Add or update an entry.
    pub(crate) fn upsert(&mut self, key_path: String, passphrase: String) {
        if let Some(e) = self.entries.iter_mut().find(|e| e.key_path == key_path) {
            e.passphrase.zeroize();
            e.passphrase = passphrase;
        } else {
            self.entries.push(VaultEntry {
                key_path,
                passphrase,
            });
        }
    }

    /// Return a reference to all entries.
    #[must_use]
    pub(crate) fn entries(&self) -> &[VaultEntry] {
        &self.entries
    }

    /// Encrypt and write this vault to `path` using `passphrase` as the master key.
    pub(crate) fn save_encrypted(&self, path: &Path, passphrase: &str) -> Result<()> {
        let payload = encode_to_vec(&self.entries, standard())?;

        // Derive master key: Argon2id hash → HKDF-SHA512 → 32 bytes for AES-256-GCM-SIV
        let mut salt_bytes = [0u8; 64];
        fill(&mut salt_bytes)?;
        let argon2_salt = SaltString::generate();
        let argon2 = Argon2::default();
        let hash = argon2
            .hash_password_with_salt(passphrase.as_bytes(), argon2_salt.as_bytes())
            .map_err(|e| anyhow!("argon2 hashing: {e}"))?
            .to_string();

        let prk = Salt::new(HKDF_SHA512, &salt_bytes).extract(passphrase.as_bytes());
        let mut key_bytes = [0u8; 32];
        prk.expand(&[HKDF_INFO], &AES_256_GCM_SIV)?
            .fill(&mut key_bytes)?;

        let nonce_key = RandomizedNonceKey::new(&AES_256_GCM_SIV, &key_bytes)?;
        let mut nonce_bytes = [0u8; 12];
        let ciphertext = {
            let mut in_out = payload.clone();
            let nonce = nonce_key.seal_in_place_append_tag(Aad::empty(), &mut in_out)?;
            nonce_bytes.copy_from_slice(nonce.as_ref());
            in_out
        };

        let mut out = VAULT_HEADER.to_vec();
        write_lv(&mut out, VAULT_CIPHER.as_bytes())?;
        write_lv(&mut out, hash.as_bytes())?;
        write_lv(&mut out, &salt_bytes)?;
        write_lv(&mut out, &nonce_bytes)?;
        write_lv(&mut out, &ciphertext)?;

        let encoded = STANDARD.encode(&out);

        let mut file = {
            #[cfg(target_family = "unix")]
            {
                OpenOptions::new()
                    .write(true)
                    .create(true)
                    .truncate(true)
                    .mode(0o600)
                    .open(path)?
            }
            #[cfg(not(target_family = "unix"))]
            {
                OpenOptions::new()
                    .write(true)
                    .create(true)
                    .truncate(true)
                    .open(path)?
            }
        };
        file.write_all(encoded.as_bytes())?;
        Ok(())
    }

    /// Load and decrypt a vault from `path` using `passphrase`.
    pub(crate) fn load_encrypted(path: &Path, passphrase: &str) -> Result<Self> {
        let mut file = File::open(path)?;
        let mut encoded = String::new();
        let _n = file.read_to_string(&mut encoded)?;

        let raw = STANDARD.decode(encoded.trim())?;
        let mut buf = BytesMut::from(&raw[..]);

        let header = buf.split_to(VAULT_HEADER.len());
        if header.as_ref() != VAULT_HEADER {
            return Err(anyhow!("invalid vault header"));
        }

        let cipher = read_lv(&mut buf)?;
        let cipher_str =
            std::str::from_utf8(&cipher).map_err(|_| anyhow!("invalid vault cipher"))?;
        let kdf = read_lv(&mut buf)?;
        let kdf_str = std::str::from_utf8(&kdf).map_err(|_| anyhow!("invalid vault kdf"))?;

        if cipher_str == VAULT_NONE_CIPHER && kdf_str == VAULT_NONE_KDF {
            let payload = read_lv(&mut buf)?;
            let (entries, _) = decode_from_slice::<Vec<VaultEntry>, _>(&payload, standard())?;
            return Ok(Self { entries });
        }

        if cipher_str != VAULT_CIPHER {
            return Err(anyhow!("unsupported vault cipher: {cipher_str}"));
        }

        // Verify passphrase via Argon2
        let hash_str = std::str::from_utf8(&kdf).map_err(|_| anyhow!("invalid kdf string"))?;
        let parsed =
            PasswordHash::new(hash_str).map_err(|e| anyhow!("invalid argon2 hash: {e}"))?;
        Argon2::default()
            .verify_password(passphrase.as_bytes(), &parsed)
            .map_err(|_| anyhow!("incorrect master passphrase"))?;

        let salt_bytes = read_lv(&mut buf)?;
        let nonce_bytes = read_lv(&mut buf)?;
        let mut ciphertext = read_lv(&mut buf)?.to_vec();

        let prk = Salt::new(HKDF_SHA512, &salt_bytes).extract(passphrase.as_bytes());
        let mut key_bytes = [0u8; 32];
        prk.expand(&[HKDF_INFO], &AES_256_GCM_SIV)?
            .fill(&mut key_bytes)?;
        let nonce = Nonce::try_assume_unique_for_key(&nonce_bytes)?;
        let unbound = aws_lc_rs::aead::UnboundKey::new(&AES_256_GCM_SIV, &key_bytes)?;
        let key = aws_lc_rs::aead::LessSafeKey::new(unbound);
        let plaintext = key
            .open_in_place(nonce, Aad::empty(), &mut ciphertext)
            .map_err(|_| anyhow!("vault decryption failed"))?;

        let (entries, _) = decode_from_slice::<Vec<VaultEntry>, _>(plaintext, standard())?;
        Ok(Self { entries })
    }

    /// Write a vault without encryption (for unencrypted agent setups).
    pub(crate) fn save_plaintext(&self, path: &Path) -> Result<()> {
        let payload = encode_to_vec(&self.entries, standard())?;
        let mut out = VAULT_HEADER.to_vec();
        write_lv(&mut out, VAULT_NONE_CIPHER.as_bytes())?;
        write_lv(&mut out, VAULT_NONE_KDF.as_bytes())?;
        write_lv(&mut out, &payload)?;
        let encoded = STANDARD.encode(&out);

        let mut file = {
            #[cfg(target_family = "unix")]
            {
                OpenOptions::new()
                    .write(true)
                    .create(true)
                    .truncate(true)
                    .mode(0o600)
                    .open(path)?
            }
            #[cfg(not(target_family = "unix"))]
            {
                OpenOptions::new()
                    .write(true)
                    .create(true)
                    .truncate(true)
                    .open(path)?
            }
        };
        file.write_all(encoded.as_bytes())?;
        Ok(())
    }
}

fn write_lv(out: &mut Vec<u8>, data: &[u8]) -> Result<()> {
    let len = u32::try_from(data.len()).map_err(|_| anyhow!("vault field exceeds 4 GiB limit"))?;
    out.extend_from_slice(&len.to_be_bytes());
    out.extend_from_slice(data);
    Ok(())
}

fn read_lv(buf: &mut BytesMut) -> Result<BytesMut> {
    if buf.remaining() < 4 {
        return Err(anyhow!("vault truncated reading length"));
    }
    let len = usize::try_from(buf.get_u32())?;
    if buf.remaining() < len {
        return Err(anyhow!("vault truncated reading value"));
    }
    Ok(buf.split_to(len))
}

/// Default vault path: `~/.mp/agent-vault`.
pub(crate) fn default_vault_path() -> Option<PathBuf> {
    dirs2::home_dir().map(|h| h.join(".mp").join("agent-vault"))
}

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

    #[test]
    fn vault_upsert_and_entries() {
        let mut v = Vault::new();
        v.upsert("/tmp/key1".into(), "pass1".into());
        v.upsert("/tmp/key2".into(), "pass2".into());
        assert_eq!(v.entries().len(), 2);
        v.upsert("/tmp/key1".into(), "newpass".into());
        assert_eq!(v.entries().len(), 2);
        assert_eq!(v.entries()[0].passphrase, "newpass");
    }

    #[test]
    fn vault_remove() {
        let mut v = Vault::new();
        v.upsert("/tmp/key1".into(), "pass1".into());
        v.upsert("/tmp/key2".into(), "pass2".into());
        v.remove("/tmp/key1");
        assert_eq!(v.entries().len(), 1);
        assert_eq!(v.entries()[0].key_path, "/tmp/key2");
    }

    #[test]
    fn vault_roundtrip_encrypted() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("vault");

        let mut v = Vault::new();
        v.upsert("/tmp/key".into(), "secret".into());
        v.save_encrypted(&path, "master").expect("save encrypted");

        let loaded = Vault::load_encrypted(&path, "master").expect("load encrypted");
        assert_eq!(loaded.entries().len(), 1);
        assert_eq!(loaded.entries()[0].key_path, "/tmp/key");
        assert_eq!(loaded.entries()[0].passphrase, "secret");
    }

    #[test]
    fn vault_wrong_passphrase() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("vault");

        let mut v = Vault::new();
        v.upsert("/tmp/key".into(), "secret".into());
        v.save_encrypted(&path, "master").expect("save encrypted");

        let result = Vault::load_encrypted(&path, "wrong");
        assert!(result.is_err());
    }

    #[test]
    fn vault_roundtrip_plaintext() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("vault");

        let mut v = Vault::new();
        v.upsert("/tmp/k".into(), "pp".into());
        v.save_plaintext(&path).expect("save plaintext");

        let loaded = Vault::load_encrypted(&path, "ignored").expect("load plaintext");
        assert_eq!(loaded.entries()[0].key_path, "/tmp/k");
    }

    #[test]
    fn vault_default_path_is_some() {
        assert!(default_vault_path().is_some());
    }

    #[test]
    fn vault_load_invalid_header() {
        use base64::Engine as _;
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("vault");
        let garbage = STANDARD.encode(b"not-a-valid-vault");
        std::fs::write(&path, garbage.as_bytes()).expect("write test file");
        let result = Vault::load_encrypted(&path, "any");
        assert!(
            result
                .expect_err("expected load error on invalid header")
                .to_string()
                .contains("invalid vault header")
        );
    }

    #[test]
    fn vault_load_unsupported_cipher() -> Result<()> {
        use base64::Engine as _;
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("vault");
        let mut out = VAULT_HEADER.to_vec();
        write_lv(&mut out, b"unknown-cipher")?;
        write_lv(&mut out, b"none")?;
        let encoded = STANDARD.encode(&out);
        std::fs::write(&path, encoded.as_bytes()).expect("write test file");
        let result = Vault::load_encrypted(&path, "any");
        assert!(
            result
                .expect_err("expected load error on unknown cipher")
                .to_string()
                .contains("unsupported vault cipher")
        );
        Ok(())
    }

    #[test]
    fn read_lv_truncated_length_field() {
        // Buffer with only 2 bytes — too short to read a u32 length
        let mut buf = BytesMut::from(&[0x00u8, 0x01][..]);
        let result = read_lv(&mut buf);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("truncated reading length")
        );
    }

    #[test]
    fn read_lv_truncated_value_field() {
        // Buffer says value is 100 bytes but only has 2 bytes after the length
        let mut out = Vec::new();
        out.extend_from_slice(&100u32.to_be_bytes());
        out.extend_from_slice(&[0xAAu8, 0xBB]);
        let mut buf = BytesMut::from(&out[..]);
        let result = read_lv(&mut buf);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("truncated reading value")
        );
    }
}