pasejo 2026.5.31

passage re-implementation in Rust for teams
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// SPDX-FileCopyrightText: The pasejo Authors
// SPDX-License-Identifier: 0BSD

use std::time::Duration;

use zeroize::Zeroizing;

use crate::cli::{clipboard, i18n, prompts};
use crate::commands::store_op::{StoreMutation, with_store, with_store_then};
use crate::models::cli::{Cli, OtpCommands};
use crate::models::configuration::Configuration;
use crate::models::password_store::{OneTimePassword, OneTimePasswordType, PasswordStore};
use crate::secrets;

pub fn dispatch(
    command: &OtpCommands,
    cli: &Cli,
    configuration: &Configuration,
) -> anyhow::Result<()> {
    match command {
        OtpCommands::Add(args) => add(
            configuration,
            args.store_selection.store.as_ref(),
            &args.password_path,
            &args.parse_password()?,
            args.force,
            cli.offline,
        ),
        OtpCommands::Copy(args) => copy(
            configuration,
            args.store_selection.store.as_ref(),
            args.force,
            &args.source_path,
            &args.target_path,
            cli.offline,
        ),
        OtpCommands::List(args) => list(
            configuration,
            args.store_selection.store.as_ref(),
            args.tree,
            cli.offline,
        ),
        OtpCommands::Move(args) => mv(
            configuration,
            args.store_selection.store.as_ref(),
            args.force,
            &args.current_path,
            &args.new_path,
            cli.offline,
        ),
        OtpCommands::Remove(args) => remove(
            configuration,
            args.store_selection.store.as_ref(),
            args.force,
            &args.password_path,
            cli.offline,
        ),
        OtpCommands::Show(args) => show(
            configuration,
            args.store_selection.store.as_ref(),
            &args.password_path,
            args.clip,
            cli.offline,
        ),
    }
}

fn add(
    configuration: &Configuration,
    store_name: Option<&String>,
    password_path: &str,
    password: &OneTimePassword,
    force: bool,
    offline: bool,
) -> anyhow::Result<()> {
    with_store(configuration, store_name, offline, |_, store| {
        let allow_overwrite = !store.otp.contains_key(password_path)
            || force
            || prompts::get_confirmation_from_user(&i18n::prompt_overwrite_one_time_password())?;
        let mutation = insert_one_time_password(store, password_path, password, allow_overwrite)?;
        i18n::one_time_password_added(password_path);
        Ok(((), mutation))
    })
}

fn remove(
    configuration: &Configuration,
    store_name: Option<&String>,
    force: bool,
    password_path: &str,
    offline: bool,
) -> anyhow::Result<()> {
    with_store(configuration, store_name, offline, |_, store| {
        let allow_remove = !store.otp.contains_key(password_path)
            || force
            || prompts::get_confirmation_from_user(&i18n::prompt_remove_one_time_password())?;
        let mutation = remove_one_time_password(store, password_path, allow_remove)?;
        i18n::one_time_password_removed(password_path);
        Ok(((), mutation))
    })
}

fn list(
    configuration: &Configuration,
    store_name: Option<&String>,
    tree: bool,
    offline: bool,
) -> anyhow::Result<()> {
    with_store(configuration, store_name, offline, |_, store| {
        if tree {
            print!(
                "{}",
                secrets::format_as_tree("", &store.otp_names_as_list())
            );
        } else {
            for secret in store.otp_names_as_list() {
                println!("{secret}");
            }
        }
        Ok(((), StoreMutation::Unchanged))
    })
}

fn show(
    configuration: &Configuration,
    store_name: Option<&String>,
    password_path: &str,
    clip: bool,
    offline: bool,
) -> anyhow::Result<()> {
    with_store_then(
        configuration,
        store_name,
        offline,
        |_, store| {
            let Some(password) = store.otp.get_mut(password_path) else {
                anyhow::bail!(i18n::error_no_one_time_password_found(password_path))
            };
            let is_hotp = password.otp_type == OneTimePasswordType::Hotp;
            let code = password.generate()?;
            let formatted = format_code(code, password.digits);
            let mutation = if is_hotp {
                StoreMutation::Modified
            } else {
                StoreMutation::Unchanged
            };
            Ok((formatted, mutation))
        },
        |code: &Zeroizing<String>| {
            if clip {
                let duration = Duration::from_secs(configuration.clipboard_timeout.unwrap_or(45));
                let notify = configuration.clipboard_notify.unwrap_or(true);
                i18n::one_time_password_copy_into_clipboard(password_path, &duration);
                clipboard::copy_text_to_clipboard(code.as_str(), duration, notify)?;
            } else {
                i18n::one_time_password_show(password_path);
                println!("{}", code.as_str());
            }
            Ok(())
        },
    )?;
    Ok(())
}

fn mv(
    configuration: &Configuration,
    store_name: Option<&String>,
    force: bool,
    current_path: &str,
    new_path: &str,
    offline: bool,
) -> anyhow::Result<()> {
    with_store(configuration, store_name, offline, |_, store| {
        let allow_overwrite = !store.otp.contains_key(new_path)
            || force
            || prompts::get_confirmation_from_user(&i18n::prompt_overwrite_one_time_password())?;
        let mutation = move_one_time_password(store, current_path, new_path, allow_overwrite)?;
        i18n::one_time_password_moved(current_path, new_path);
        Ok(((), mutation))
    })
}

fn copy(
    configuration: &Configuration,
    store_name: Option<&String>,
    force: bool,
    source_path: &str,
    target_path: &str,
    offline: bool,
) -> anyhow::Result<()> {
    with_store(configuration, store_name, offline, |_, store| {
        let allow_overwrite = !store.otp.contains_key(target_path)
            || force
            || prompts::get_confirmation_from_user(&i18n::prompt_overwrite_one_time_password())?;
        let mutation = copy_one_time_password(store, source_path, target_path, allow_overwrite)?;
        i18n::one_time_password_copied(source_path, target_path);
        Ok(((), mutation))
    })
}

/// Insert `password` at `password_path`. Bails when a password already
/// exists there and `allow_overwrite` is `false`. The handler computes
/// `allow_overwrite` from `--force` and the interactive prompt; the
/// helper itself is pure so the data-mutation path can be tested without
/// stdin or a real store.
fn insert_one_time_password(
    store: &mut PasswordStore,
    password_path: &str,
    password: &OneTimePassword,
    allow_overwrite: bool,
) -> anyhow::Result<StoreMutation> {
    if store.otp.contains_key(password_path) && !allow_overwrite {
        anyhow::bail!(i18n::error_one_time_password_already_exists(password_path));
    }
    store.otp.insert(password_path.to_owned(), password.clone());
    Ok(StoreMutation::Modified)
}

/// Remove the password at `password_path`. Bails when the entry doesn't
/// exist *or* when it does but `allow_remove` is `false` (the user
/// declined the overwrite prompt). The not-found message is preferred
/// over the not-allowed message when both apply.
fn remove_one_time_password(
    store: &mut PasswordStore,
    password_path: &str,
    allow_remove: bool,
) -> anyhow::Result<StoreMutation> {
    if !store.otp.contains_key(password_path) {
        anyhow::bail!(i18n::error_no_one_time_password_found(password_path));
    }
    if !allow_remove {
        anyhow::bail!(i18n::error_not_allowed_to_remove_one_time_password(
            password_path
        ));
    }
    store.otp.remove(password_path);
    Ok(StoreMutation::Modified)
}

/// Move `current_path` to `new_path`. Bails when the destination is
/// occupied and `allow_overwrite` is `false`, or when the source is
/// missing. The destination check runs first so a forbidden overwrite
/// never disturbs the source entry.
fn move_one_time_password(
    store: &mut PasswordStore,
    current_path: &str,
    new_path: &str,
    allow_overwrite: bool,
) -> anyhow::Result<StoreMutation> {
    if store.otp.contains_key(new_path) && !allow_overwrite {
        anyhow::bail!(i18n::error_one_time_password_already_exists(new_path));
    }
    let Some(password) = store.otp.remove(current_path) else {
        anyhow::bail!(i18n::error_no_one_time_password_found(current_path));
    };
    store.otp.insert(new_path.to_owned(), password);
    Ok(StoreMutation::Modified)
}

/// Copy the password at `source_path` to `target_path`, leaving the
/// source intact. Same overwrite/missing semantics as
/// [`move_one_time_password`].
fn copy_one_time_password(
    store: &mut PasswordStore,
    source_path: &str,
    target_path: &str,
    allow_overwrite: bool,
) -> anyhow::Result<StoreMutation> {
    if store.otp.contains_key(target_path) && !allow_overwrite {
        anyhow::bail!(i18n::error_one_time_password_already_exists(target_path));
    }
    let Some(password) = store.otp.get(source_path) else {
        anyhow::bail!(i18n::error_no_one_time_password_found(source_path));
    };
    let copy = password.clone();
    store.otp.insert(target_path.to_owned(), copy);
    Ok(StoreMutation::Modified)
}

/// Zero-pad an OTP code to the declared digit width.
///
/// `OneTimePassword::generate` returns the raw integer, so a 6-digit code
/// of `54321` would render without its leading zero and be rejected by
/// the verifying server. This pads with `0`s up to `digits`. The caller
/// owns wiping the buffer; we wrap it in `Zeroizing` since the formatted
/// digits are themselves sensitive material.
fn format_code(code: u32, digits: u8) -> Zeroizing<String> {
    Zeroizing::new(format!("{code:0width$}", width = usize::from(digits)))
}

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

    #[test]
    fn pads_with_leading_zeros_for_six_digits() {
        let formatted = format_code(54321, 6);
        assert_eq!(formatted.as_str(), "054321");
    }

    #[test]
    fn pads_zero_to_full_width() {
        let formatted = format_code(0, 6);
        assert_eq!(formatted.as_str(), "000000");
    }

    #[test]
    fn does_not_pad_when_value_already_fills_width() {
        let formatted = format_code(999_999, 6);
        assert_eq!(formatted.as_str(), "999999");
    }

    #[test]
    fn pads_to_eight_digits_for_eight_digit_otps() {
        let formatted = format_code(12_345, 8);
        assert_eq!(formatted.as_str(), "00012345");
    }

    #[test]
    fn pads_to_four_digits_for_four_digit_otps() {
        let formatted = format_code(7, 4);
        assert_eq!(formatted.as_str(), "0007");
    }

    #[test]
    fn output_length_always_matches_digit_count() {
        // 9 is the largest digit count whose `max_in_range` still fits in
        // a u32; in practice OTPs cap at 8 digits, so this is plenty of
        // headroom. Pushing to 10 would overflow `10u32.pow(10)`.
        for digits in 4..=9u8 {
            let max_in_range = 10u32.pow(u32::from(digits)) - 1;
            for code in [0, 7, max_in_range] {
                let formatted = format_code(code, digits);
                assert_eq!(
                    formatted.len(),
                    usize::from(digits),
                    "code={code}, digits={digits}, formatted={formatted:?}",
                );
            }
        }
    }

    /// Build a distinguishable `OneTimePassword` per period. Tests use
    /// the `period` field as a discriminator so they can assert *which*
    /// password ended up at a given path after a mutation. We build by
    /// mutation rather than `..Default::default()` because
    /// `OneTimePassword` implements `ZeroizeOnDrop`, which forbids moves
    /// out of any of its non-`Copy` fields.
    fn otp_with_period(period: u64) -> OneTimePassword {
        let mut otp = OneTimePassword::default();
        otp.period = period;
        otp
    }

    fn store_with(entries: &[(&str, OneTimePassword)]) -> PasswordStore {
        let mut store = PasswordStore::default();
        for (path, otp) in entries {
            store.otp.insert((*path).to_owned(), otp.clone());
        }
        store
    }

    // ---- insert_one_time_password ---------------------------------------

    #[test]
    fn insert_writes_a_new_entry_into_an_empty_path() {
        let mut store = PasswordStore::default();
        let password = otp_with_period(30);

        let mutation = insert_one_time_password(&mut store, "github", &password, false).unwrap();

        assert!(matches!(mutation, StoreMutation::Modified));
        assert_eq!(store.otp.get("github"), Some(&password));
    }

    #[test]
    fn insert_overwrites_existing_entry_when_allowed() {
        let mut store = store_with(&[("github", otp_with_period(30))]);
        let replacement = otp_with_period(60);

        let mutation = insert_one_time_password(&mut store, "github", &replacement, true).unwrap();

        assert!(matches!(mutation, StoreMutation::Modified));
        assert_eq!(store.otp.get("github"), Some(&replacement));
    }

    #[test]
    fn insert_bails_on_existing_entry_when_overwrite_not_allowed() {
        let original = otp_with_period(30);
        let mut store = store_with(&[("github", original.clone())]);
        let replacement = otp_with_period(60);

        let result = insert_one_time_password(&mut store, "github", &replacement, false);

        assert!(result.is_err());
        // Original entry must be untouched on the bail path.
        assert_eq!(store.otp.get("github"), Some(&original));
    }

    // ---- remove_one_time_password ---------------------------------------

    #[test]
    fn remove_drops_the_entry_when_allowed() {
        let mut store = store_with(&[("github", otp_with_period(30))]);

        let mutation = remove_one_time_password(&mut store, "github", true).unwrap();

        assert!(matches!(mutation, StoreMutation::Modified));
        assert!(!store.otp.contains_key("github"));
    }

    #[test]
    fn remove_bails_when_user_declined_and_keeps_entry() {
        let original = otp_with_period(30);
        let mut store = store_with(&[("github", original.clone())]);

        let result = remove_one_time_password(&mut store, "github", false);

        assert!(result.is_err());
        assert_eq!(store.otp.get("github"), Some(&original));
    }

    #[test]
    fn remove_bails_when_entry_does_not_exist() {
        i18n::init_for_tests();
        let mut store = PasswordStore::default();

        let result = remove_one_time_password(&mut store, "missing", true);

        assert!(result.is_err());
        let message = result.unwrap_err().to_string();
        assert!(
            message.contains("No one-time password found"),
            "expected not-found message, got: {message}"
        );
    }

    // ---- move_one_time_password -----------------------------------------

    #[test]
    fn move_relocates_entry_when_destination_is_empty() {
        let original = otp_with_period(30);
        let mut store = store_with(&[("old", original.clone())]);

        let mutation = move_one_time_password(&mut store, "old", "new", false).unwrap();

        assert!(matches!(mutation, StoreMutation::Modified));
        assert!(!store.otp.contains_key("old"));
        assert_eq!(store.otp.get("new"), Some(&original));
    }

    #[test]
    fn move_overwrites_destination_when_allowed() {
        let source = otp_with_period(30);
        let target = otp_with_period(60);
        let mut store = store_with(&[("old", source.clone()), ("new", target)]);

        let mutation = move_one_time_password(&mut store, "old", "new", true).unwrap();

        assert!(matches!(mutation, StoreMutation::Modified));
        assert!(!store.otp.contains_key("old"));
        // Destination now holds the source's value, not the original target.
        assert_eq!(store.otp.get("new"), Some(&source));
    }

    #[test]
    fn move_bails_when_destination_exists_and_overwrite_not_allowed() {
        let source = otp_with_period(30);
        let target = otp_with_period(60);
        let mut store = store_with(&[("old", source.clone()), ("new", target.clone())]);

        let result = move_one_time_password(&mut store, "old", "new", false);

        assert!(result.is_err());
        // Both entries untouched when the overwrite is rejected.
        assert_eq!(store.otp.get("old"), Some(&source));
        assert_eq!(store.otp.get("new"), Some(&target));
    }

    #[test]
    fn move_bails_when_source_is_missing() {
        i18n::init_for_tests();
        let mut store = PasswordStore::default();

        let result = move_one_time_password(&mut store, "missing", "new", true);

        assert!(result.is_err());
        let message = result.unwrap_err().to_string();
        assert!(
            message.contains("No one-time password found"),
            "expected not-found message, got: {message}"
        );
    }

    #[test]
    fn move_to_same_path_is_a_noop_when_overwrite_allowed() {
        let original = otp_with_period(30);
        let mut store = store_with(&[("github", original.clone())]);

        let mutation = move_one_time_password(&mut store, "github", "github", true).unwrap();

        assert!(matches!(mutation, StoreMutation::Modified));
        assert_eq!(store.otp.get("github"), Some(&original));
    }

    // ---- copy_one_time_password -----------------------------------------

    #[test]
    fn copy_duplicates_entry_to_new_path() {
        let original = otp_with_period(30);
        let mut store = store_with(&[("source", original.clone())]);

        let mutation = copy_one_time_password(&mut store, "source", "target", false).unwrap();

        assert!(matches!(mutation, StoreMutation::Modified));
        // Both source and target now hold equal values.
        assert_eq!(store.otp.get("source"), Some(&original));
        assert_eq!(store.otp.get("target"), Some(&original));
    }

    #[test]
    fn copy_overwrites_destination_when_allowed() {
        let source = otp_with_period(30);
        let target = otp_with_period(60);
        let mut store = store_with(&[("source", source.clone()), ("target", target)]);

        let mutation = copy_one_time_password(&mut store, "source", "target", true).unwrap();

        assert!(matches!(mutation, StoreMutation::Modified));
        // Source still present, target now mirrors source.
        assert_eq!(store.otp.get("source"), Some(&source));
        assert_eq!(store.otp.get("target"), Some(&source));
    }

    #[test]
    fn copy_bails_when_destination_exists_and_overwrite_not_allowed() {
        let source = otp_with_period(30);
        let target = otp_with_period(60);
        let mut store = store_with(&[("source", source.clone()), ("target", target.clone())]);

        let result = copy_one_time_password(&mut store, "source", "target", false);

        assert!(result.is_err());
        // Both entries untouched on the bail path.
        assert_eq!(store.otp.get("source"), Some(&source));
        assert_eq!(store.otp.get("target"), Some(&target));
    }

    #[test]
    fn copy_bails_when_source_is_missing() {
        i18n::init_for_tests();
        let mut store = PasswordStore::default();

        let result = copy_one_time_password(&mut store, "missing", "target", true);

        assert!(result.is_err());
        let message = result.unwrap_err().to_string();
        assert!(
            message.contains("No one-time password found"),
            "expected not-found message, got: {message}"
        );
    }
}