secrets-vault 2.4.1

AES-256-GCM encrypted key-value vault with PBKDF2 key derivation. Store API keys and tokens securely instead of plaintext dotfiles.
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Session-unlock broker v2 — a KEY SERVER, not a passphrase dispenser
//! (QVLT2_SPEC.md §6). ONE presence check starts a short-lived daemon; callers
//! ask for individual values (`GET <project> <key>`) and the broker enforces the
//! grant registry per request, server-side. The passphrase is read from the
//! child's stdin pipe, used once to derive the master secret, and zeroized —
//! it never crosses the transport in any form, and neither does the master
//! secret. What crosses is at most ONE decrypted value per authorized request.
//!
//! Security boundary, stated as two requirements the transport must meet:
//!
//!   R1. **Only the owning user may connect.** Unix: the socket lives at
//!       `~/.secrets/session.sock` with 0600 perms inside the 0700 secrets dir
//!       (the guarantee ssh-agent relies on). Windows: the named pipe carries a
//!       protected owner-only DACL, and the client verifies the pipe's OWNER
//!       before trusting it (see `session_win.rs` — the pipe namespace is
//!       machine-global, so R1 needs a check the filesystem gives Unix for free).
//!   R2. **Caller identity comes from the kernel, never from the caller.**
//!       Unix: the `LOCAL_PEERTOKEN` audit token (pid + pidversion — closes the
//!       pid-reuse race `LOCAL_PEEREPID` would leave). Windows:
//!       `GetNamedPipeClientProcessId`, with the pid pinned by a live process
//!       handle so it cannot be recycled underneath us.
//!
//! Both then run the SAME process-ancestry agent resolution `exec` uses, on the
//! PEER's pid. The caller's own claims are never consulted. Residual risk
//! (spec §3.1): ancestry is same-user-spoofable — the broker narrows blast
//! radius and leaves an audit line; the user boundary remains the OS trust line.
//!
//! Protocol (spec §6.1):
//!   `GET <project> <key>\n` → `OK <len>\n<len bytes>` | `ERR denied\n` |
//!                             `ERR unknown-key\n` | `ERR scheme\n`
//!   `END\n`                 → connection closed, broker exits
//!   bare `GET\n` (legacy v1 client) → EMPTY response + close, so old clients
//!   fall through to their presence path instead of misparsing an error
//!   string as a passphrase.
//! Error ordering is normative: a caller without a grant gets `ERR denied`
//! for EVERY key, existing or not — the broker is not an existence oracle.
//!
//! STRUCTURE: the enforcement pipeline below (`handle_get`, `Verdict`, `audit`)
//! is platform-INDEPENDENT and is the only copy. A transport's whole job is to
//! satisfy R1/R2 and hand up a `Peer`; it never decides anything. That split is
//! deliberate — two copies of a normative deny-ordering is exactly the kind of
//! thing that drifts between platforms and quietly stops matching the spec.

use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use zeroize::Zeroizing;

use secrets_vault::{is_valid_key, is_valid_project, MasterSecret, VaultError, VaultReader};

use crate::registry;

/// Rendezvous address for the broker.
///
/// Unix: a socket file inside the (0700) secrets dir. Windows: a named pipe,
/// whose name is derived in `session_win.rs` (the pipe namespace is global, so
/// the name has to carry the user SID + a digest of the secrets dir).
#[cfg(unix)]
pub fn socket_path(secrets_dir: &Path) -> PathBuf {
    secrets_dir.join("session.sock")
}

#[cfg(windows)]
pub fn socket_path(secrets_dir: &Path) -> PathBuf {
    PathBuf::from(crate::session_win::pipe_name(secrets_dir))
}

fn log_path(secrets_dir: &Path) -> PathBuf {
    secrets_dir.join("session.log")
}

/// What is listening at the rendezvous address?
pub enum Probe {
    /// A broker that is ours.
    Live,
    /// Nothing there (the normal "no session" state).
    Absent,
    /// Something IS listening, but it is not ours. Only reachable on Windows,
    /// where the pipe namespace is machine-global; on Unix the 0700 directory
    /// makes this unrepresentable.
    Foreign(String),
}

/// Probe the rendezvous address.
///
/// This exists because the broker binds in the CHILD process while the success
/// message is printed by the PARENT — without a check, the parent announces a
/// key server that never came up. "Is something listening" is NOT a sufficient
/// check for that: if another process is squatting the address, the probe sees
/// a perfectly healthy endpoint that is not ours, and the parent would report
/// success while our broker died. So the Windows probe verifies ownership, and
/// `Foreign` is reported rather than smoothed into `Absent`.
#[cfg(unix)]
pub fn probe(secrets_dir: &Path) -> Probe {
    // On Unix the address is a file inside a 0700 directory: nobody else can
    // create it, so presence implies ours.
    if socket_path(secrets_dir).exists() {
        Probe::Live
    } else {
        Probe::Absent
    }
}

#[cfg(windows)]
pub fn probe(secrets_dir: &Path) -> Probe {
    crate::session_win::probe(secrets_dir)
}

/// Kernel-attested identity of a connected peer. Built by the transport, which
/// is responsible for making every field trustworthy; the pipeline below simply
/// believes it.
pub(crate) struct Peer {
    /// The peer's process id, pinned by the transport for as long as this
    /// struct lives (Unix: pidversion in the token; Windows: an open process
    /// handle) so the ancestry walk cannot be aimed at a recycled pid.
    pub pid: i32,
    /// Whether the peer runs as the same user as this broker. The transport
    /// establishes this from the kernel (Unix: euid from the audit token;
    /// Windows: the peer token's user SID), never from anything the peer said.
    pub same_user: bool,
    /// Transport-specific identity detail for the audit line (e.g. pidversion).
    pub detail: String,
}

/// Best-effort append to the audit log (names and verdicts only — NEVER values).
pub(crate) fn audit(secrets_dir: &Path, line: &str) {
    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let path = log_path(secrets_dir);
    #[cfg(unix)]
    let file = {
        use std::os::unix::fs::OpenOptionsExt;
        std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .mode(0o600)
            .open(&path)
    };
    // Windows: the secrets dir carries an owner-only DACL that this file
    // inherits (see winacl.rs), which is the 0600 equivalent.
    #[cfg(not(unix))]
    let file = std::fs::OpenOptions::new().create(true).append(true).open(&path);
    if let Ok(mut f) = file {
        use std::io::Write as _;
        let _ = writeln!(f, "{ts} {line}");
    }
}

pub(crate) enum Verdict {
    Ok(Zeroizing<Vec<u8>>),
    Denied,
    UnknownKey,
    Scheme,
}

/// The per-request enforcement pipeline (spec §6.2, normative order):
/// kernel peer identity → same-user gate → ancestry agent resolution on the
/// PEER's pid → registry grant → declared-key manifest → single-record decrypt.
///
/// THE ONLY COPY. Every transport funnels through here, so the deny ordering —
/// and the no-existence-oracle property that depends on it — is identical on
/// every platform by construction.
#[allow(clippy::too_many_arguments)]
pub(crate) fn handle_get(
    secrets_dir: &Path,
    vault_path: &Path,
    master: &MasterSecret,
    registry_key: &[u8; 32],
    peer: Option<Peer>,
    project: &str,
    key: &str,
) -> Verdict {
    if !is_valid_project(project) || !is_valid_key(key) {
        return Verdict::Denied;
    }
    let Some(peer) = peer else {
        return Verdict::Denied;
    };
    if !peer.same_user {
        return Verdict::Denied;
    }
    let Some(agent) = registry::resolve_agent_from(peer.pid) else {
        audit(
            secrets_dir,
            &format!(
                "DENY pid={} {} (no agent) {project}/{key}",
                peer.pid, peer.detail
            ),
        );
        return Verdict::Denied;
    };
    let reg = match registry::Registry::load_raw(secrets_dir, registry_key) {
        Ok(r) => r,
        Err(_) => return Verdict::Denied,
    };
    if reg.grant_for(&agent, project, registry::now()).is_none() {
        audit(secrets_dir, &format!("DENY agent={agent} (no grant) {project}/{key}"));
        return Verdict::Denied;
    }
    // Declared-key manifest: when the registry records the project's key set,
    // requests outside it are denied (NOT unknown-key — no namespace oracle).
    if let Some(meta) = reg.projects.get(project) {
        if !meta.keys.is_empty() && !meta.keys.iter().any(|k| k == key) {
            audit(
                secrets_dir,
                &format!("DENY agent={agent} (outside manifest) {project}/{key}"),
            );
            return Verdict::Denied;
        }
    }

    // Re-read the vault per request — a `set` during the session window is
    // picked up naturally (the salt is stable across saves, spec §5.1).
    let data = match std::fs::read(vault_path) {
        Ok(d) => d,
        Err(_) => return Verdict::Denied,
    };
    let reader = match VaultReader::open(data, master) {
        Ok(r) => r,
        Err(_) => return Verdict::Denied,
    };
    // Scoped override first, bare shared entry second — the same resolution
    // order exec/lease/get use. The grant and declared-key manifest checks
    // above already bounded WHICH names may be requested, so the fallback
    // widens where a granted name's value is stored, never what is served.
    let storage = format!("{project}/{key}");
    let looked_up = match reader.decrypt_one(master, &storage) {
        Err(VaultError::NotFound) => reader.decrypt_one(master, key),
        other => other,
    };
    match looked_up {
        Ok(value) => {
            audit(secrets_dir, &format!("SERVE agent={agent} {project}/{key}"));
            Verdict::Ok(value)
        }
        Err(VaultError::NotFound) => {
            audit(secrets_dir, &format!("UNKNOWN agent={agent} {project}/{key}"));
            Verdict::UnknownKey
        }
        Err(VaultError::UnknownScheme(_)) => Verdict::Scheme,
        Err(_) => Verdict::Denied,
    }
}

/// Parse one request line and dispatch. Shared so both transports agree on the
/// grammar, including the legacy bare-`GET` case.
pub(crate) enum Request<'a> {
    Get { project: &'a str, key: &'a str },
    End,
    /// Legacy v1 client expecting the passphrase — answer with an EMPTY close.
    LegacyGet,
    Malformed,
}

pub(crate) fn parse_request(line: &str) -> Request<'_> {
    let mut parts = line.split_whitespace();
    match (parts.next(), parts.next(), parts.next(), parts.next()) {
        (Some("END"), None, None, None) => Request::End,
        (Some("GET"), Some(project), Some(key), None) => Request::Get { project, key },
        (Some("GET"), None, None, None) => Request::LegacyGet,
        _ => Request::Malformed,
    }
}

/// Serialize a verdict into the wire response.
pub(crate) fn encode_verdict(v: Verdict) -> Zeroizing<Vec<u8>> {
    match v {
        Verdict::Ok(value) => {
            let mut out = Zeroizing::new(Vec::with_capacity(16 + value.len()));
            out.extend_from_slice(format!("OK {}\n", value.len()).as_bytes());
            out.extend_from_slice(&value);
            out
        }
        Verdict::Denied => Zeroizing::new(b"ERR denied\n".to_vec()),
        Verdict::UnknownKey => Zeroizing::new(b"ERR unknown-key\n".to_vec()),
        Verdict::Scheme => Zeroizing::new(b"ERR scheme\n".to_vec()),
    }
}

/// Parse a broker response into the value, or None for anything else.
/// Shared by both clients so the framing can't diverge.
pub(crate) fn decode_response(buf: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
    let nl = buf.iter().position(|&b| b == b'\n')?;
    let header = std::str::from_utf8(&buf[..nl]).ok()?;
    let len: usize = header.strip_prefix("OK ")?.parse().ok()?;
    let body = &buf[nl + 1..];
    if body.len() != len {
        return None;
    }
    Some(Zeroizing::new(body.to_vec()))
}

// ── Unix transport ──

#[cfg(unix)]
mod imp {
    use std::io::{Read, Write};
    use std::os::unix::fs::PermissionsExt;
    use std::os::unix::net::{UnixListener, UnixStream};
    use std::path::Path;
    use std::time::{Duration, Instant};

    use zeroize::Zeroizing;

    use secrets_vault::{v2_salt, MasterSecret, VaultReader};

    use super::{
        audit, decode_response, encode_verdict, handle_get, parse_request, socket_path, Peer,
        Request,
    };

    /// CLIENT: ask a running broker for one value. Returns the plaintext value if
    /// the broker exists AND the grant checks pass server-side, else None (caller
    /// falls back to the presence path). Any error is a silent None — a
    /// missing/expired/denying broker is a normal case, never fatal.
    pub fn request_value(
        secrets_dir: &Path,
        project: &str,
        key: &str,
    ) -> Option<Zeroizing<Vec<u8>>> {
        let path = socket_path(secrets_dir);
        let mut stream = UnixStream::connect(&path).ok()?;
        stream.set_read_timeout(Some(Duration::from_secs(5))).ok()?;
        stream
            .write_all(format!("GET {project} {key}\n").as_bytes())
            .ok()?;
        let mut buf = Zeroizing::new(Vec::new());
        stream.read_to_end(&mut buf).ok()?;
        decode_response(&buf)
    }

    /// CLIENT: ask a running broker to shut down NOW (used by `secrets lock` and
    /// `secrets rekey`). Best-effort; also unlinks the socket so a wedged daemon
    /// can't be reached.
    pub fn end(secrets_dir: &Path) {
        let path = socket_path(secrets_dir);
        if let Ok(mut s) = UnixStream::connect(&path) {
            let _ = s.write_all(b"END\n");
        }
        let _ = std::fs::remove_file(&path);
    }

    /// R2 on Unix: the kernel's audit token, captured at connect time.
    #[cfg(target_os = "macos")]
    fn peer_identity(stream: &UnixStream) -> Option<Peer> {
        use std::os::unix::io::AsRawFd;

        // audit_token_t (mach): 8 u32s. Read via getsockopt(SOL_LOCAL,
        // LOCAL_PEERTOKEN) — captured by the kernel at connect time — and field-
        // extracted with libbsm's PUBLIC accessors (never hand-indexed).
        #[repr(C)]
        #[derive(Clone, Copy)]
        struct AuditToken {
            val: [u32; 8],
        }
        const SOL_LOCAL: libc::c_int = 0; // sys/un.h
        const LOCAL_PEERTOKEN: libc::c_int = 0x006; // sys/un.h

        #[link(name = "bsm")]
        unsafe extern "C" {
            fn audit_token_to_pid(t: AuditToken) -> libc::pid_t;
            fn audit_token_to_pidversion(t: AuditToken) -> libc::c_int;
            fn audit_token_to_euid(t: AuditToken) -> libc::uid_t;
        }

        let mut token = AuditToken { val: [0; 8] };
        let mut len = std::mem::size_of::<AuditToken>() as libc::socklen_t;
        let rc = unsafe {
            libc::getsockopt(
                stream.as_raw_fd(),
                SOL_LOCAL,
                LOCAL_PEERTOKEN,
                &mut token as *mut _ as *mut libc::c_void,
                &mut len,
            )
        };
        if rc != 0 || len as usize != std::mem::size_of::<AuditToken>() {
            return None;
        }
        unsafe {
            let pid = audit_token_to_pid(token);
            let pidversion = audit_token_to_pidversion(token);
            let euid = audit_token_to_euid(token);
            Some(Peer {
                pid,
                same_user: euid == libc::geteuid(),
                detail: format!("pidv={pidversion}"),
            })
        }
    }

    #[cfg(not(target_os = "macos"))]
    fn peer_identity(_stream: &UnixStream) -> Option<Peer> {
        // No kernel peer attestation wired on this platform yet → every GET is
        // denied (fail closed). The 0600 socket still gates by uid.
        None
    }

    /// DAEMON: derive keys, zeroize the passphrase, then answer per-key requests
    /// until the lifetime expires or an `END` arrives. Called ONLY by the hidden
    /// `__session-serve` subcommand in the detached child; `pass` was read from
    /// the child's stdin (pipe), never argv/env. Blocks until exit, then removes
    /// the socket.
    pub fn serve(secrets_dir: &Path, minutes: u64, pass: Zeroizing<String>) -> Result<(), String> {
        let vault_path = secrets_dir.join("vault.qvlt");

        // Fail closed on anything but a healthy v2 vault — a v1 vault must never
        // revive the passphrase-dispenser behavior (spec §8).
        let data = std::fs::read(&vault_path).map_err(|e| format!("read vault: {e}"))?;
        let salt = v2_salt(&data).map_err(|e| format!("not a v2 vault: {e}"))?;
        let master = MasterSecret::derive(&pass, &salt);
        drop(pass); // Zeroizing: the passphrase's lifetime ends HERE (G4).
        let registry_key_z = master.registry_key();
        let registry_key: &[u8; 32] = &registry_key_z;
        // Prove the derivation before serving anything (wrong passphrase → exit).
        VaultReader::open(data, &master).map_err(|e| format!("vault open: {e}"))?;

        let path = socket_path(secrets_dir);
        // Fresh socket: unlink a stale one first (a prior daemon that died hard).
        let _ = std::fs::remove_file(&path);
        let listener =
            UnixListener::bind(&path).map_err(|e| format!("bind {}: {e}", path.display()))?;
        // R1: 0600 BEFORE we accept anything — owner-only is the whole model.
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
            .map_err(|e| format!("chmod socket: {e}"))?;

        audit(secrets_dir, &format!("START lifetime={minutes}m"));
        let deadline = Instant::now() + Duration::from_secs(minutes.saturating_mul(60));
        listener
            .set_nonblocking(true)
            .map_err(|e| format!("nonblocking: {e}"))?;

        'outer: loop {
            if Instant::now() >= deadline {
                break;
            }
            match listener.accept() {
                Ok((mut stream, _)) => {
                    // Capture the kernel-attested identity FIRST — before reading
                    // anything the peer controls.
                    let peer = peer_identity(&stream);
                    let _ = stream.set_nonblocking(false);
                    let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));

                    // One bounded request line ("GET " + 256 + 1 + 256 + "\n").
                    let mut req = Vec::with_capacity(64);
                    let mut byte = [0u8; 1];
                    while req.len() < 1024 {
                        match stream.read(&mut byte) {
                            Ok(1) if byte[0] == b'\n' => break,
                            Ok(1) => req.push(byte[0]),
                            _ => break,
                        }
                    }
                    let line = String::from_utf8_lossy(&req);
                    match parse_request(&line) {
                        Request::End => {
                            audit(secrets_dir, "END (requested)");
                            break 'outer;
                        }
                        Request::Get { project, key } => {
                            let verdict = handle_get(
                                secrets_dir,
                                &vault_path,
                                &master,
                                registry_key,
                                peer,
                                project,
                                key,
                            );
                            let _ = stream.write_all(&encode_verdict(verdict));
                        }
                        Request::LegacyGet => {
                            audit(secrets_dir, "LEGACY-GET (empty close)");
                        }
                        Request::Malformed => {
                            let _ = stream.write_all(b"ERR denied\n");
                        }
                    }
                    // stream drops → close.
                }
                Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    std::thread::sleep(Duration::from_millis(200));
                }
                Err(_) => std::thread::sleep(Duration::from_millis(200)),
            }
        }
        audit(secrets_dir, "STOP");
        let _ = std::fs::remove_file(&path);
        Ok(())
    }

    /// Detach from the controlling terminal so the broker outlives the shell that
    /// started it (the drain may run long after the launching command returns).
    /// `setsid` makes us a new session leader with no controlling tty.
    pub fn detach() {
        unsafe {
            libc::setsid();
        }
    }
}

// ── Windows transport ──

#[cfg(windows)]
mod imp {
    pub use crate::session_win::{detach, end, request_value, serve};
}

pub use imp::{detach, end, request_value, serve};