pars-core 0.2.4

Pars(a zx2c4-pass compatible passwords manager) core library
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
use std::fs;
use std::io::{BufRead, Read, Write};
use std::path::Path;

use anyhow::{anyhow, Result};
use passwords::PasswordGenerator;
use secrecy::{ExposeSecret, SecretString};

use crate::pgp::PGPClient;
use crate::util::fs_util;
use crate::util::fs_util::{
    backup_encrypted_file, create_or_overwrite, get_dir_gpg_id_content, path_attack_check,
    path_to_str, restore_backup_file,
};

pub struct IOStreams<'a, I, O, E>
where
    I: Read + BufRead,
    O: Write,
    E: Write,
{
    pub in_s: &'a mut I,
    pub out_s: &'a mut O,
    pub err_s: &'a mut E,
}

pub struct PasswdGenerateConfig {
    pub no_symbols: bool,
    pub in_place: bool,
    pub force: bool,
    pub pass_length: usize,
    pub extension: String,
    pub pgp_executable: String,
}

pub fn generate_io<I, O, E>(
    root: &Path,
    pass_name: &str,
    gen_cfg: &PasswdGenerateConfig,
    io_streams: &mut IOStreams<I, O, E>,
) -> Result<SecretString>
where
    I: Read + BufRead,
    O: Write,
    E: Write,
{
    let pass_path = root.join(format!("{}.{}", pass_name, gen_cfg.extension));

    path_attack_check(root, &pass_path)?;

    if gen_cfg.in_place && gen_cfg.force {
        let err_msg = "Cannot use both [--in-place] and [--force]";
        writeln!(io_streams.err_s, "{err_msg}")?;
        return Err(anyhow!(err_msg));
    }

    if pass_path.exists()
        && !gen_cfg.force
        && !gen_cfg.in_place
        && !fs_util::prompt_overwrite(io_streams.in_s, io_streams.err_s, pass_name)?
    {
        writeln!(io_streams.out_s, "Operation cancelled.")?;
        return Ok(SecretString::new("".to_string().into()));
    }

    let pg = PasswordGenerator::new()
        .length(gen_cfg.pass_length)
        .numbers(true)
        .lowercase_letters(true)
        .uppercase_letters(true)
        .symbols(!gen_cfg.no_symbols)
        .spaces(false)
        .exclude_similar_characters(true)
        .strict(true);

    let password = SecretString::new(pg.generate_one().map_err(|e| anyhow!(e))?.into());

    // Get the appropriate key fingerprints for this path
    let keys_fpr = get_dir_gpg_id_content(root, &pass_path)?;
    let client = PGPClient::new(&gen_cfg.pgp_executable, &keys_fpr)?;

    if gen_cfg.in_place && pass_path.exists() {
        let existing = client.decrypt_stdin(root, path_to_str(&pass_path)?)?;
        let mut content = existing.expose_secret().lines().collect::<Vec<_>>();

        if !content.is_empty() {
            content[0] = password.expose_secret();

            let backup = backup_encrypted_file(&pass_path)?;
            match client.encrypt(&content.join("\n"), path_to_str(&pass_path)?) {
                Ok(_) => {
                    fs::remove_file(&backup)?;
                }
                Err(e) => {
                    restore_backup_file(&backup)?;
                    return Err(e);
                }
            }
        }
    } else {
        if let Some(parent) = pass_path.parent() {
            fs::create_dir_all(parent)?;
        }

        create_or_overwrite(&client, &pass_path, &password)?;
    }

    writeln!(io_streams.out_s, "Generated password for '{pass_name}' saved")?;

    Ok(password)
}

#[cfg(test)]
mod tests {

    use std::io::{stderr, stdout, BufReader};
    use std::thread;

    use os_pipe::pipe;
    use pretty_assertions::assert_eq;
    use serial_test::serial;

    use super::*;
    use crate::pgp::key_management::key_gen_batch;
    use crate::util::defer::cleanup;
    use crate::util::test_util::*;

    fn setup_test_client(root: &Path) -> PGPClient {
        key_gen_batch(&get_test_executable(), &gpg_key_gen_example_batch()).unwrap();
        let test_client = PGPClient::new(get_test_executable(), &[&get_test_email()]).unwrap();
        test_client.key_edit_batch(&gpg_key_edit_example_batch()).unwrap();
        write_gpg_id(root, &test_client.get_keys_fpr());
        test_client
    }

    #[test]
    #[serial]
    #[ignore = "need run interactively"]
    fn basic_password_generation() {
        let executable = get_test_executable();
        let email = get_test_email();
        let (_tmp_dir, root) = gen_unique_temp_dir();

        cleanup!(
            {
                let (stdin, stdin_w) = pipe().unwrap();
                let mut stdin = BufReader::new(stdin);
                let mut stdout = stdout().lock();
                let mut stderr = stderr().lock();
                let test_client = setup_test_client(&root);

                let mut config = PasswdGenerateConfig {
                    no_symbols: false,
                    in_place: false,
                    force: false,
                    pass_length: 16,
                    extension: "gpg".to_string(),
                    pgp_executable: executable.clone(),
                };

                let mut io_streams =
                    IOStreams { in_s: &mut stdin, out_s: &mut stdout, err_s: &mut stderr };

                let password = generate_io(&root, "test1", &config, &mut io_streams).unwrap();

                assert_eq!(password.expose_secret().len(), 16);
                assert!(root.join("test1.gpg").exists());
                let secret = test_client.decrypt_stdin(&root, "test1.gpg").unwrap();
                assert_eq!(secret.expose_secret(), password.expose_secret());

                // Now test interactive overwrite
                config.pass_length = 114;
                thread::spawn(move || {
                    let mut stdin = stdin_w;
                    stdin.write_all(b"n").unwrap();
                });
                let original_passwd = password;
                let password = generate_io(&root, "test1", &config, &mut io_streams).unwrap();
                let secret = test_client.decrypt_stdin(&root, "test1.gpg").unwrap();
                assert_eq!(password.expose_secret(), "");
                assert_eq!(secret.expose_secret(), original_passwd.expose_secret());

                let (stdin, stdin_w) = pipe().unwrap();
                let mut stdin = BufReader::new(stdin);
                let mut io_streams =
                    IOStreams { in_s: &mut stdin, out_s: &mut stdout, err_s: &mut stderr };
                thread::spawn(move || {
                    let mut stdin = stdin_w;
                    stdin.write_all(b"y").unwrap();
                });
                let password = generate_io(&root, "test1", &config, &mut io_streams).unwrap();
                let secret = test_client.decrypt_stdin(&root, "test1.gpg").unwrap();
                assert_eq!(secret.expose_secret(), password.expose_secret());
                assert_eq!(password.expose_secret().len(), 114);
            },
            {
                clean_up_test_key(&executable, &[&email]).unwrap();
            }
        );
    }

    #[test]
    #[serial]
    #[ignore = "need run interactively"]
    fn inplace_generation() {
        let executable = get_test_executable();
        let email = get_test_email();
        let (_tmp_dir, root) = gen_unique_temp_dir();

        cleanup!(
            {
                let (stdin, _) = pipe().unwrap();
                let mut stdin = BufReader::new(stdin);
                let mut stdout = stdout().lock();
                let mut stderr = stderr().lock();

                let test_client = setup_test_client(&root);
                test_client
                    .encrypt(
                        "existing\npassword\nfor super earth",
                        path_to_str(&root.join("test2.gpg")).unwrap(),
                    )
                    .unwrap();

                let config = PasswdGenerateConfig {
                    no_symbols: false,
                    in_place: true,
                    force: false,
                    pass_length: 12,
                    extension: "gpg".to_string(),
                    pgp_executable: executable.clone(),
                };

                let mut io_streams =
                    IOStreams { in_s: &mut stdin, out_s: &mut stdout, err_s: &mut stderr };

                let password = generate_io(&root, "test2", &config, &mut io_streams).unwrap();

                let content = test_client.decrypt_stdin(&root, "test2.gpg").unwrap();
                let lines: Vec<&str> = content.expose_secret().lines().collect();
                assert_eq!(lines[0], password.expose_secret());
                assert_eq!(password.expose_secret().len(), 12);
                assert_eq!(lines[1], "password");
                assert_eq!(lines[2], "for super earth");
            },
            {
                clean_up_test_key(&executable, &[&email]).unwrap();
            }
        );
    }

    #[test]
    #[serial]
    #[ignore = "need run interactively"]
    fn force_overwrite() {
        let executable = get_test_executable();
        let email = get_test_email();
        let (_tmp_dir, root) = gen_unique_temp_dir();

        cleanup!(
            {
                let (stdin, _) = pipe().unwrap();
                let mut stdin = BufReader::new(stdin);
                let mut stdout = stdout().lock();
                let mut stderr = stderr().lock();

                let test_client = setup_test_client(&root);
                test_client
                    .encrypt("old_password", path_to_str(&root.join("test3.gpg")).unwrap())
                    .unwrap();

                let config = PasswdGenerateConfig {
                    no_symbols: false,
                    in_place: false,
                    force: true,
                    pass_length: 8,
                    extension: "gpg".to_string(),
                    pgp_executable: executable.clone(),
                };

                let mut io_streams =
                    IOStreams { in_s: &mut stdin, out_s: &mut stdout, err_s: &mut stderr };

                let password = generate_io(&root, "test3", &config, &mut io_streams).unwrap();

                assert_eq!(password.expose_secret().len(), 8);
                let content = test_client.decrypt_stdin(&root, "test3.gpg").unwrap();
                assert_eq!(content.expose_secret(), password.expose_secret());
            },
            {
                clean_up_test_key(&executable, &[&email]).unwrap();
            }
        );
    }

    #[test]
    #[serial]
    #[ignore = "need run interactively"]
    fn no_symbols() {
        let executable = get_test_executable();
        let email = get_test_email();
        let (_tmp_dir, root) = gen_unique_temp_dir();

        cleanup!(
            {
                let (stdin, _) = pipe().unwrap();
                let mut stdin = BufReader::new(stdin);
                let mut stdout = stdout().lock();
                let mut stderr = stderr().lock();
                let test_client = setup_test_client(&root);

                let config = PasswdGenerateConfig {
                    no_symbols: true,
                    in_place: false,
                    force: false,
                    pass_length: 10,
                    extension: "gpg".to_string(),
                    pgp_executable: executable.clone(),
                };

                let mut io_streams =
                    IOStreams { in_s: &mut stdin, out_s: &mut stdout, err_s: &mut stderr };

                let password = generate_io(&root, "test4", &config, &mut io_streams).unwrap();

                assert!(!password.expose_secret().contains(|c: char| !c.is_alphanumeric()));
                let content = test_client.decrypt_stdin(&root, "test4.gpg").unwrap();
                assert_eq!(content.expose_secret(), password.expose_secret());
            },
            {
                clean_up_test_key(&executable, &[&email]).unwrap();
            }
        );
    }

    #[test]
    #[serial]
    #[ignore = "need run interactively"]
    fn invalid_path() {
        let executable = get_test_executable();
        let email = get_test_email();
        let (_tmp_dir, root) = gen_unique_temp_dir();

        cleanup!(
            {
                let (stdin, _) = pipe().unwrap();
                let mut stdin = BufReader::new(stdin);
                let mut stdout = stdout().lock();
                let mut stderr = stderr().lock();

                let config = PasswdGenerateConfig {
                    no_symbols: false,
                    in_place: false,
                    force: false,
                    pass_length: 16,
                    extension: "gpg".to_string(),
                    pgp_executable: executable.clone(),
                };

                let mut io_streams =
                    IOStreams { in_s: &mut stdin, out_s: &mut stdout, err_s: &mut stderr };

                let result = generate_io(&root, "../outside", &config, &mut io_streams);

                assert!(result.is_err());
            },
            {
                clean_up_test_key(&executable, &[&email]).unwrap();
            }
        );
    }

    #[test]
    #[serial]
    #[ignore = "need run interactively"]
    fn invalid_flag() {
        let executable = get_test_executable();
        let email = get_test_email();
        let (_tmp_dir, root) = gen_unique_temp_dir();

        cleanup!(
            {
                let (stdin, _) = pipe().unwrap();
                let mut stdin = BufReader::new(stdin);
                let mut stdout = stdout().lock();
                let mut stderr = stderr().lock();

                let config = PasswdGenerateConfig {
                    no_symbols: false,
                    in_place: true,
                    force: true,
                    pass_length: 16,
                    extension: "gpg".to_string(),
                    pgp_executable: executable.clone(),
                };

                let mut io_streams =
                    IOStreams { in_s: &mut stdin, out_s: &mut stdout, err_s: &mut stderr };

                let result = generate_io(&root, "test5", &config, &mut io_streams);

                assert!(result.is_err());
            },
            {
                clean_up_test_key(&executable, &[&email]).unwrap();
            }
        );
    }
}