magi-rs 0.9.0

Magi Agent: a terminal AI assistant in Rust with sandboxed tool execution, OAuth login, and encrypted local memory (authenticated encryption with error-correcting FEC via the cryptovault crate).
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
// Author: Julian Bolivar
// Version: 1.0.0
// Date: 2026-07-17
//! Master passphrase resolution and strength enforcement (MS2, zero-knowledge).
//!
//! The passphrase is the ONLY key: there is no keyring, no recovery, no backdoor
//! (REQ-V23). It resolves with a deterministic precedence (`-p`, then
//! `MAGI_PASSPHRASE`, then interactive prompt) and is used only to derive the KEK,
//! then zeroized (the caller holds it in [`Zeroizing`]). Because a moved `.db`
//! can be brute-forced offline with no rate-limiting, creation and rotation
//! enforce a **hard** strength floor (`zxcvbn` score ≥ 3, ≥ 12 chars) with
//! **no override** (REQ-V18).

use std::io::IsTerminal;

use zeroize::Zeroizing;
use zxcvbn::zxcvbn;

use crate::vault::VaultError;

/// Environment variable that supplies the master passphrase in headless/CI use.
pub const PASSPHRASE_ENV: &str = "MAGI_PASSPHRASE";

/// Absolute minimum passphrase length (chars, not bytes). 12 is the floor below
/// which even a high-`zxcvbn` estimate is untrustworthy for offline brute-force.
pub const MIN_PASSPHRASE_CHARS: usize = 12;

/// Minimum `zxcvbn` score to accept (0–4). 3 = "safely unguessable: moderate
/// protection from an offline slow-hash scenario" — the correct floor for a
/// portable `.db` attacked offline without rate-limiting (REQ-V18).
const MIN_ZXCVBN_SCORE: u8 = 3;

/// Injectable interactive input (R-V07: tests never touch a real TTY).
pub trait PassphrasePrompt {
    /// Whether stdin is an interactive terminal (`IsTerminal`, D-V08).
    fn is_interactive(&self) -> bool;

    /// Reads one passphrase. `show=false` ⇒ hidden (no echo); `show=true` ⇒ live
    /// echo (REQ-V21, for `passwd --show`). `show` is ignored without a TTY.
    ///
    /// # Errors
    /// [`VaultError::Io`] if the terminal read fails.
    fn read_passphrase(&mut self, msg: &str, show: bool) -> Result<Zeroizing<String>, VaultError>;
}

/// Production [`PassphrasePrompt`] over the real stdin/stderr.
pub struct TtyPrompt;

impl PassphrasePrompt for TtyPrompt {
    fn is_interactive(&self) -> bool {
        std::io::stdin().is_terminal()
    }

    fn read_passphrase(&mut self, msg: &str, show: bool) -> Result<Zeroizing<String>, VaultError> {
        if show {
            eprint!("{msg}");
            use std::io::Write;
            std::io::stderr().flush().ok();
            let mut line = String::new();
            std::io::stdin()
                .read_line(&mut line)
                .map_err(|e| VaultError::Io(e.to_string()))?;
            Ok(strip_trailing_newline(Zeroizing::new(line)))
        } else {
            rpassword::prompt_password(msg)
                .map(Zeroizing::new)
                .map_err(|e| VaultError::Io(e.to_string()))
        }
    }
}

/// Removes at most ONE trailing `\n` or `\r\n` (never other whitespace).
///
/// A submitted line's newline is never part of an intended passphrase, so
/// stripping it aligns `-p`/env with the interactive prompt and prevents the
/// silent lockout of `MAGI_PASSPHRASE=$(cat f)` (trailing `\n`). Inner or
/// deliberate trailing spaces/tabs are preserved (REQ-V18 / MAGI run 10).
///
/// Takes and returns [`Zeroizing`] so the passphrase never lands in a plain
/// `String` that outlives the call (REQ-V41 — keep sensitive material masked
/// end-to-end, never a bare copy).
///
/// Exposed so first-run creation (`main::resolve_master_passphrase`) normalizes
/// `-p`/env EXACTLY as unlock does — otherwise a passphrase created with a
/// trailing newline could never be reproduced on unlock (lockout).
pub fn strip_trailing_newline(s: Zeroizing<String>) -> Zeroizing<String> {
    if let Some(stripped) = s.strip_suffix("\r\n") {
        Zeroizing::new(stripped.to_string())
    } else if let Some(stripped) = s.strip_suffix('\n') {
        Zeroizing::new(stripped.to_string())
    } else {
        s
    }
}

/// Resolves the master passphrase: `-p` > `MAGI_PASSPHRASE` > interactive prompt.
///
/// A trailing newline is stripped from `-p`/env. An empty `MAGI_PASSPHRASE`
/// counts as absent. **Without a TTY and without `-p`/env, fails closed with
/// [`VaultError::PassphraseUnavailable`] and NEVER reads stdin** (REQ-V40:
/// stdin is reserved for the secret value). An empty prompt entry aborts the
/// same way (user cancelled).
///
/// # Errors
/// [`VaultError::PassphraseUnavailable`] as described; [`VaultError::Io`] on a
/// terminal read failure.
pub fn resolve_passphrase(
    flag: Option<Zeroizing<String>>,
    prompt: &mut dyn PassphrasePrompt,
) -> Result<Zeroizing<String>, VaultError> {
    if let Some(p) = flag {
        // `p` is already `Zeroizing`; strip in place with no bare-`String` copy.
        return Ok(strip_trailing_newline(p));
    }
    if let Ok(env) = std::env::var(PASSPHRASE_ENV) {
        if !env.is_empty() {
            return Ok(strip_trailing_newline(Zeroizing::new(env)));
        }
    }
    if !prompt.is_interactive() {
        return Err(VaultError::PassphraseUnavailable);
    }
    let entered = prompt.read_passphrase("Passphrase: ", false)?;
    if entered.is_empty() {
        return Err(VaultError::PassphraseUnavailable);
    }
    Ok(entered)
}

/// Enforces the hard strength floor (REQ-V18): `< MIN_PASSPHRASE_CHARS` chars or
/// `zxcvbn` score `< MIN_ZXCVBN_SCORE` ⇒ rejected. No override, no composition
/// rules. Runs only on create/rotate, never on unlock.
///
/// # Errors
/// [`VaultError::WeakPassphrase`] with the reasons + tips (never the passphrase).
pub fn check_strength(passphrase: &str) -> Result<(), VaultError> {
    if passphrase.chars().count() < MIN_PASSPHRASE_CHARS {
        return Err(VaultError::WeakPassphrase(format!(
            "too short (need at least {MIN_PASSPHRASE_CHARS} characters); \
             a passphrase of 4+ random words is strong and easy to recall"
        )));
    }
    let estimate = zxcvbn(passphrase, &[]);
    if u8::from(estimate.score()) < MIN_ZXCVBN_SCORE {
        let mut reason = String::from("too easy to guess");
        if let Some(feedback) = estimate.feedback() {
            if let Some(warning) = feedback.warning() {
                reason = format!("{reason}: {warning}");
            }
            let tips: Vec<String> = feedback
                .suggestions()
                .iter()
                .map(std::string::ToString::to_string)
                .collect();
            if !tips.is_empty() {
                reason = format!("{reason} ({})", tips.join("; "));
            }
        }
        return Err(VaultError::WeakPassphrase(format!(
            "{reason}. Try 4+ random words; length matters more than symbols"
        )));
    }
    Ok(())
}

/// The verbatim zero-knowledge warning shown on first-run and `passwd` (REQ-V23).
const ZK_WARNING: &str =
    "no recovery: if you forget the passphrase, the data is lost. There is no backdoor.";

/// First-run (REQ-V17) and `passwd`: double entry + [`check_strength`] + the
/// zero-knowledge no-recovery warning. `show` (REQ-V21) is threaded to both reads.
///
/// A mismatch re-prompts; an empty entry aborts. The strength floor is enforced
/// before acceptance — with no override.
///
/// # Errors
/// [`VaultError::PassphraseUnavailable`] if the user aborts (empty entry);
/// [`VaultError::WeakPassphrase`] if the floor is not met; [`VaultError::Io`] on
/// a terminal read failure.
pub fn create_passphrase(
    prompt: &mut dyn PassphrasePrompt,
    show: bool,
) -> Result<Zeroizing<String>, VaultError> {
    loop {
        let first = prompt.read_passphrase(&format!("New passphrase ({ZK_WARNING}): "), show)?;
        if first.is_empty() {
            return Err(VaultError::PassphraseUnavailable);
        }
        check_strength(first.as_str())?;
        let second = prompt.read_passphrase("Confirm passphrase: ", show)?;
        if first.as_str() == second.as_str() {
            return Ok(first);
        }
        // Mismatch: loop and re-prompt (a transient user error, not a failure).
    }
}

/// Fuzz entrypoint (`fuzz_passphrase_input`, Task 8 / REQ-V39).
///
/// Feeds ARBITRARY bytes as a passphrase (via `from_utf8_lossy`, since input is a
/// `&str`) through [`check_strength`] and a KEK derivation, **discarding** the
/// results. Invariant: no input — empty, huge, non-UTF8 — ever panics; a weak one
/// returns [`VaultError::WeakPassphrase`]. Tests raw-byte coverage via lossy
/// conversion, not UTF-8 rejection (that path does not exist — input is `String`).
#[doc(hidden)]
pub fn fuzz_passphrase_entrypoint(data: &[u8]) {
    let s = String::from_utf8_lossy(data);
    let _ = check_strength(&s);
    // Deriving a KEK must also never panic on arbitrary input.
    let vault = cryptovault::CryptoVault::default();
    if let Ok(salt) = cryptovault::generate_salt() {
        let _ = vault.derive_key(&s, &salt);
    }
}

#[cfg(test)]
mod tests {
    use super::{
        check_strength, create_passphrase, resolve_passphrase, PassphrasePrompt, PASSPHRASE_ENV,
    };
    use crate::vault::VaultError;
    use zeroize::Zeroizing;

    /// Fake prompt: scripted answers in order; records `show` and `msg` per read.
    struct FakePrompt {
        interactive: bool,
        answers: Vec<String>,
        reads: usize,
        shows: Vec<bool>,
        msgs: Vec<String>,
    }
    impl PassphrasePrompt for FakePrompt {
        fn is_interactive(&self) -> bool {
            self.interactive
        }
        fn read_passphrase(
            &mut self,
            msg: &str,
            show: bool,
        ) -> Result<Zeroizing<String>, VaultError> {
            let i = self.reads;
            self.reads += 1;
            self.shows.push(show);
            self.msgs.push(msg.to_string());
            Ok(Zeroizing::new(
                self.answers.get(i).cloned().unwrap_or_default(),
            ))
        }
    }
    fn fp(interactive: bool, answers: Vec<&str>) -> FakePrompt {
        FakePrompt {
            interactive,
            answers: answers.into_iter().map(Into::into).collect(),
            reads: 0,
            shows: vec![],
            msgs: vec![],
        }
    }

    /// RAII env guard (no `temp_env` dep); restores the prior value on drop.
    fn with_var<R>(key: &str, val: Option<&str>, f: impl FnOnce() -> R) -> R {
        struct Guard {
            key: String,
            prev: Option<String>,
        }
        impl Drop for Guard {
            fn drop(&mut self) {
                match &self.prev {
                    Some(v) => std::env::set_var(&self.key, v),
                    None => std::env::remove_var(&self.key),
                }
            }
        }
        let _g = Guard {
            key: key.to_string(),
            prev: std::env::var(key).ok(),
        };
        match val {
            Some(v) => std::env::set_var(key, v),
            None => std::env::remove_var(key),
        }
        f()
    }

    #[test]
    #[serial_test::serial]
    fn test_flag_takes_precedence_over_env_and_prompt() {
        let mut p = fp(true, vec!["from-prompt"]);
        with_var(PASSPHRASE_ENV, Some("from-env"), || {
            let r =
                resolve_passphrase(Some(Zeroizing::new("from-flag".into())), &mut p).expect("ok");
            assert_eq!(r.as_str(), "from-flag");
            assert_eq!(p.reads, 0);
        });
    }

    #[test]
    #[serial_test::serial]
    fn test_env_takes_precedence_over_prompt_and_empty_env_counts_as_absent() {
        let mut p = fp(true, vec!["from-prompt"]);
        with_var(PASSPHRASE_ENV, Some("from-env"), || {
            assert_eq!(
                resolve_passphrase(None, &mut p).expect("ok").as_str(),
                "from-env"
            );
        });
        with_var(PASSPHRASE_ENV, Some(""), || {
            assert_eq!(
                resolve_passphrase(None, &mut p).expect("ok").as_str(),
                "from-prompt"
            );
        });
    }

    #[test]
    #[serial_test::serial]
    fn test_no_tty_without_flag_or_env_fails_closed_without_reading_stdin() {
        let mut p = fp(false, vec!["pipe-data"]);
        with_var(PASSPHRASE_ENV, None, || {
            let e = resolve_passphrase(None, &mut p).expect_err("fail-closed");
            assert!(matches!(e, VaultError::PassphraseUnavailable));
            assert_eq!(p.reads, 0);
        });
    }

    #[test]
    #[serial_test::serial]
    fn test_trailing_newline_stripped_from_flag_and_env_but_not_inner_whitespace() {
        let mut p = fp(true, vec!["x"]);
        let r =
            resolve_passphrase(Some(Zeroizing::new("pass phrase\n".into())), &mut p).expect("ok");
        assert_eq!(r.as_str(), "pass phrase");
        with_var(PASSPHRASE_ENV, Some("secret \r\n"), || {
            let e = resolve_passphrase(None, &mut p).expect("ok");
            assert_eq!(e.as_str(), "secret ");
        });
    }

    #[test]
    fn test_short_or_low_score_passphrases_are_hard_rejected_without_override() {
        for weak in ["short", "password123!", "qwertyuiop12"] {
            assert!(
                matches!(check_strength(weak), Err(VaultError::WeakPassphrase(_))),
                "should reject: {weak}"
            );
        }
    }

    #[test]
    fn test_diceware_lowercase_words_are_accepted_without_composition_rules() {
        // Verified empirically with zxcvbn 3.1.1: score 4 (>= floor 3).
        check_strength("correct horse battery staple").expect("diceware >= 3");
    }

    #[test]
    fn test_weak_passphrase_message_never_contains_the_passphrase() {
        let probe = "hunter2hunter2";
        if let Err(VaultError::WeakPassphrase(msg)) = check_strength(probe) {
            assert!(!msg.contains(probe));
        }
    }

    #[test]
    fn test_create_passphrase_requires_matching_double_entry() {
        let mut p = fp(
            true,
            vec![
                "correct horse battery staple",
                "MISMATCH-XYZ",
                "correct horse battery staple",
                "correct horse battery staple",
            ],
        );
        let r = create_passphrase(&mut p, false).expect("ok");
        assert_eq!(r.as_str(), "correct horse battery staple");
        assert_eq!(p.reads, 4);
    }

    #[test]
    fn test_create_passphrase_threads_show_flag_to_both_reads() {
        let mut p = fp(true, vec!["correct horse battery staple"; 2]);
        create_passphrase(&mut p, true).expect("ok");
        assert_eq!(p.shows, vec![true, true]);
    }

    #[test]
    fn test_create_passphrase_emits_zero_knowledge_no_recovery_warning() {
        let mut p = fp(true, vec!["correct horse battery staple"; 2]);
        create_passphrase(&mut p, false).expect("ok");
        assert!(p
            .msgs
            .iter()
            .any(|m| m.to_lowercase().contains("no recovery")
                || m.to_lowercase().contains("data is lost")));
    }

    #[test]
    fn test_fuzz_passphrase_entrypoint_never_panics_on_arbitrary_input() {
        for data in [
            &b""[..],
            &b"\x00"[..],
            &b"\xff\xfe\x80"[..], // invalid UTF-8
            &[0x41u8; 100_000],   // huge
        ] {
            super::fuzz_passphrase_entrypoint(data);
        }
    }
}