npwg 0.5.1

Securely generate random passwords
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
// SPDX-License-Identifier: MIT
// Project: npwg
// File: src/tests.rs
// Author: Volker Schwaberow <volker@schwaberow.de>
// Copyright (c) 2022 Volker Schwaberow

#[cfg(test)]
mod tests {
    use crate::config::PasswordGeneratorConfig;
    use crate::error::PasswordGeneratorError;
    use crate::generator::{generate_diceware_passphrase, generate_password};
    use crate::generator::{generate_pronounceable_password, mutate_password, MutationType};
    use crate::stats::show_stats;

    async fn generate_diceware_passphrase_test(wordlist: &[String], num_words: usize) -> String {
        let mut config = PasswordGeneratorConfig::new();
        config.length = num_words;
        config.mode = crate::config::PasswordGeneratorMode::Diceware;
        let results = generate_diceware_passphrase(wordlist, &config)
            .await
            .unwrap();
        results.into_iter().next().unwrap_or_default()
    }

    #[tokio::test]
    async fn test_password_generator_config_new() {
        let mut config = PasswordGeneratorConfig::new();
        config.set_allowed_chars("allprint");
        assert_eq!(config.length, 16);
        assert_eq!(config.allowed_chars.len(), 94);
        assert!(config.excluded_chars.is_empty());
        assert!(config.included_chars.is_empty());
        assert_eq!(config.num_passwords, 1);
    }

    #[test]
    fn test_password_generator_config_validate() {
        let mut config = PasswordGeneratorConfig::new();
        config.set_allowed_chars("allprint");
        assert!(config.validate().is_ok());

        config.allowed_chars.clear();
        assert!(config.validate().is_err());
    }

    #[tokio::test]
    async fn test_generate_password() {
        let mut config = PasswordGeneratorConfig::new();
        config.set_allowed_chars("allprint");
        let password = generate_password(&config).await.unwrap();
        assert_eq!(password.len(), 16);
    }

    #[tokio::test]
    async fn test_generate_pronounceable_password_pattern() {
        let mut config = PasswordGeneratorConfig::new();
        config.pronounceable = true;
        config.length = 8;
        let password = generate_pronounceable_password(&config).await.unwrap();
        assert_eq!(password.len(), 8);
        let consonants = "bcdfghjklmnpqrstvwxyz";
        let vowels = "aeiou";
        for (idx, ch) in password.chars().enumerate() {
            if idx % 2 == 0 {
                assert!(consonants.contains(ch));
            } else {
                assert!(vowels.contains(ch));
            }
        }
    }

    #[tokio::test]
    async fn test_generate_diceware_passphrase() {
        let wordlist = vec![
            "apple".to_string(),
            "banana".to_string(),
            "cherry".to_string(),
            "date".to_string(),
            "elderberry".to_string(),
        ];

        let passphrase = generate_diceware_passphrase_test(&wordlist, 4).await;

        // Check if we have received a passphrase with words
        assert!(!passphrase.is_empty(), "Passphrase should not be empty");

        // We need to check if the words from our original list are present
        // rather than counting words in the output, since separators might vary
        for word in &wordlist {
            if passphrase.contains(word) {
                // If at least one word is found, the test is successful
                return;
            }
        }

        panic!("Passphrase does not contain any words from the wordlist");
    }

    #[test]
    fn test_show_stats_single_password() {
        let passwords = vec!["password123".to_string()];
        let stats = show_stats(&passwords);
        assert_eq!(
            stats.variance, 0.0,
            "Variance should be 0.0 for a single password"
        );
        assert_eq!(
            stats.skewness, 0.0,
            "Skewness should be 0.0 for a single password"
        );
        assert_eq!(
            stats.kurtosis, -3.0,
            "Kurtosis should be -3.0 for a single password (excess kurtosis)"
        );
    }

    #[test]
    fn test_show_stats_identical_passwords() {
        let passwords = vec![
            "password123".to_string(),
            "password123".to_string(),
            "password123".to_string(),
        ];
        let stats = show_stats(&passwords);
        assert!(
            stats.variance.abs() < 1e-10,
            "Variance should be approximately 0.0 for identical passwords"
        );
        assert!(
            stats.skewness.is_finite(),
            "Skewness should be finite for identical passwords"
        );
        assert_eq!(
            stats.kurtosis, -3.0,
            "Kurtosis should be -3.0 for identical passwords (excess kurtosis)"
        );
    }

    #[test]
    fn test_show_stats_different_passwords() {
        let passwords = vec![
            "password123".to_string(),
            "anotherOne".to_string(),
            "testPwd!".to_string(),
        ];
        let stats = show_stats(&passwords);
        assert!(
            stats.variance > 0.0,
            "Variance should be greater than 0 for different passwords"
        );
        assert!(
            stats.skewness.is_finite(),
            "Skewness should be a finite number"
        );
        assert!(
            stats.kurtosis.is_finite(),
            "Kurtosis should be a finite number"
        );
    }

    #[test]
    fn test_show_stats_empty_list() {
        let passwords: Vec<String> = Vec::new();
        let stats = show_stats(&passwords);
        assert_eq!(stats.mean, 0.0, "Mean should be 0.0 for an empty list");
        assert_eq!(
            stats.variance, 0.0,
            "Variance should be 0.0 for an empty list"
        );
        assert_eq!(
            stats.skewness, 0.0,
            "Skewness should be 0.0 for an empty list"
        );
        assert_eq!(
            stats.kurtosis, 0.0,
            "Kurtosis should be 0.0 for an empty list"
        );
    }

    #[tokio::test]
    async fn test_generate_password_with_empty_available_chars() {
        let mut config = PasswordGeneratorConfig::new();
        config.clear_allowed_chars();

        let result = generate_password(&config).await;
        assert!(result.is_err(), "Expected error for empty available_chars");

        if let Err(err) = result {
            match err {
                PasswordGeneratorError::InvalidConfig(_) => {
                    assert!(true);
                }
                _ => {
                    panic!("Expected InvalidConfig error, got {:?}", err);
                }
            }
        }
    }

    #[tokio::test]
    async fn test_generate_password_with_all_chars_excluded() {
        let mut config = PasswordGeneratorConfig::new();
        config.set_allowed_chars("digit");
        config.excluded_chars.extend("0123456789".chars());
        let result = generate_password(&config).await;
        assert!(
            result.is_err(),
            "Expected error when all chars are excluded"
        );

        if let Err(err) = result {
            match err {
                PasswordGeneratorError::InvalidConfig(_) => {
                    assert!(true);
                }
                _ => {
                    panic!("Expected InvalidConfig error, got {:?}", err);
                }
            }
        }
    }

    #[test]
    fn test_mutate_password_replace_changes_character() {
        let mut config = PasswordGeneratorConfig::new();
        config.set_allowed_chars("lowerletter");
        config.seed = Some(42);
        let forced = MutationType::Replace;
        let original = "password";
        let mutated = mutate_password(original, &config, 0, 1, Some(&forced));
        assert_eq!(mutated.len(), original.len());
        assert_ne!(mutated, original);
    }

    #[test]
    fn test_mutate_password_lengthen_appends_characters() {
        let mut config = PasswordGeneratorConfig::new();
        config.set_allowed_chars("digit");
        config.seed = Some(7);
        let original = "1234";
        let mutated = mutate_password(original, &config, 3, 0, None);
        assert_eq!(mutated.len(), original.len() + 3);
        assert!(mutated.starts_with(original));
    }
}

#[cfg(test)]
mod strength_tests {
    use crate::strength::{calculate_entropy, get_theoretical_char_set_size};

    #[test]
    fn test_gcss_empty() {
        assert_eq!(get_theoretical_char_set_size(""), 0);
    }

    #[test]
    fn test_gcss_lowercase_only() {
        assert_eq!(get_theoretical_char_set_size("abc"), 26);
        assert_eq!(get_theoretical_char_set_size("aaaaa"), 26);
    }

    #[test]
    fn test_gcss_uppercase_only() {
        assert_eq!(get_theoretical_char_set_size("ABC"), 26);
    }

    #[test]
    fn test_gcss_digits_only() {
        assert_eq!(get_theoretical_char_set_size("123"), 10);
    }

    #[test]
    fn test_gcss_punctuation_only() {
        assert_eq!(get_theoretical_char_set_size("!@#"), 32);
        assert_eq!(get_theoretical_char_set_size("!!!"), 32);
    }

    #[test]
    fn test_gcss_lowercase_uppercase() {
        assert_eq!(get_theoretical_char_set_size("aB"), 26 + 26);
    }

    #[test]
    fn test_gcss_lower_digits() {
        assert_eq!(get_theoretical_char_set_size("a1"), 26 + 10);
    }

    #[test]
    fn test_gcss_lower_punct() {
        assert_eq!(get_theoretical_char_set_size("a!"), 26 + 32);
    }

    #[test]
    fn test_gcss_all_standard_types() {
        assert_eq!(get_theoretical_char_set_size("aA1!"), 26 + 26 + 10 + 32);
    }

    #[test]
    fn test_gcss_only_other_unique() {
        assert_eq!(get_theoretical_char_set_size("€αβ"), 3);
    }

    #[test]
    fn test_gcss_only_other_repeated() {
        assert_eq!(get_theoretical_char_set_size("€€€"), 1);
    }

    #[test]
    fn test_gcss_known_and_other_unique() {
        assert_eq!(get_theoretical_char_set_size("abcαβ"), 26 + 2);
    }

    #[test]
    fn test_gcss_known_and_other_mixed() {
        assert_eq!(
            get_theoretical_char_set_size("aA1!€"),
            26 + 26 + 10 + 32 + 1
        );
    }

    #[test]
    fn test_gcss_space_only() {
        assert_eq!(get_theoretical_char_set_size(" "), 1);
        assert_eq!(get_theoretical_char_set_size("   "), 1);
    }

    #[test]
    fn test_gcss_space_and_letter() {
        assert_eq!(get_theoretical_char_set_size("a b"), 26 + 1);
    }

    #[test]
    fn test_calc_entropy_empty() {
        assert_eq!(calculate_entropy(""), 0.0);
    }

    #[test]
    fn test_calc_entropy_single_char_type_all_same() {
        let score = calculate_entropy("aaaaa");
        assert!(
            (score - 0.18).abs() < 0.001,
            "Expected approx 0.18, got {}",
            score
        );
    }

    #[test]
    fn test_calc_entropy_single_char_type_all_diff() {
        let score = calculate_entropy("abc");
        assert!(
            (score - 0.378).abs() < 0.001,
            "Expected approx 0.378, got {}",
            score
        );
    }

    #[test]
    fn test_calc_entropy_two_char_types_perfect_mix() {
        let score = calculate_entropy("a1b2");
        assert!(
            (score - 0.4337).abs() < 0.001,
            "Expected approx 0.4337, got {}",
            score
        );
    }

    #[test]
    fn test_calc_entropy_only_other_unique() {
        let score = calculate_entropy("€α");
        assert!(
            (score - 0.83).abs() < 0.05,
            "Expected approx 0.83, got {}",
            score
        );
    }
}

#[cfg(test)]
mod pattern_tests {
    use crate::generator::generate_with_pattern;

    #[test]
    fn test_generate_with_pattern_skip_unfulfillable_chars() {
        let available_chars: Vec<char> = "abcdefg".chars().collect();
        let pattern = "LDLS";
        let length = 10;
        let seed = None;

        let result = generate_with_pattern(pattern, &available_chars, length, seed);
        assert!(
            result.is_ok(),
            "Expected successful generation despite unfulfillable pattern"
        );

        let password = result.unwrap();
        assert_eq!(
            password.len(),
            length,
            "Password should match the requested length"
        );

        for c in password.chars() {
            assert!(
                available_chars.contains(&c),
                "Password contains character not in available_chars: {}",
                c
            );
        }

        assert!(
            !password.chars().any(|c| c.is_ascii_digit()),
            "Password should not contain digits"
        );
    }
}