Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add Rust password generator sanity checks (#776)
Leendert de Borst86c3a1db7193
diff --git a/core/rust/src/password_generator/basic.rs b/core/rust/src/password_generator/basic.rsindex 2e4cc3294..e16fd63ab 100644--- a/core/rust/src/password_generator/basic.rs+++ b/core/rust/src/password_generator/basic.rs@@ -1,8 +1,8 @@//! Basic character-set password generator.//!-//! Builds a character set from the enabled options, generates an initial password using an-//! unbiased CSPRNG, and then ensures at least one character from every enabled set is-//! present (as some websites require this).+//! Builds a character set from the enabled options and constructs the password so that it+//! is guaranteed to contain at least one character from every enabled set (as some websites+//! require this).use rand::RngCore;@@ -19,9 +19,27 @@ const AMBIGUOUS_CHARS: &str = "Il1O0oZzSsBbGg2568|[]{}()<>;:,.`'\"_-";/// Generate a basic password based on the supplied settings.pub fn generate<R: RngCore + ?Sized>(settings: &PasswordSettings, rng: &mut R) -> String {let chars = build_character_set(settings);+ let length = settings.length as usize;++ // Reserve one mandatory character per enabled class so the result is guaranteed to+ // contain at least one of each.+ let mut mandatory = mandatory_characters(settings, rng);++ // If the requested length cannot fit every mandatory character (e.g. length 2 with four+ // enabled classes), shuffle and truncate so we never exceed the requested length. Which+ // classes "win" is then random rather than always favouring the same ones.+ if mandatory.len() > length {+ shuffle(&mut mandatory, rng);+ mandatory.truncate(length);+ }- let mut password = generate_initial_password(&chars, settings.length as usize, rng);- ensure_requirements(&mut password, settings, rng);+ // Fill the remaining positions from the full character set, then shuffle so the mandatory+ // characters are not clustered at the front.+ let mut password = mandatory;+ while password.len() < length {+ password.push(chars[unbiased_index(rng, chars.len())]);+ }+ shuffle(&mut password, rng);password.into_iter().collect()}@@ -67,34 +85,38 @@ fn remove_ambiguous_characters(chars: &[char]) -> Vec<char> {.collect()}-/// Generate the initial random password from the character set.-fn generate_initial_password<R: RngCore + ?Sized>(- chars: &[char],- length: usize,+/// Collect one mandatory character per enabled class, so the constructed password is+/// guaranteed to contain at least one character from each.+fn mandatory_characters<R: RngCore + ?Sized>(+ settings: &PasswordSettings,rng: &mut R,) -> Vec<char> {- (0..length)- .map(|_| chars[unbiased_index(rng, chars.len())])- .collect()+ let mut mandatory = Vec::new();+ if settings.use_lowercase {+ push_one(&mut mandatory, LOWERCASE_CHARS, settings, rng);+ }+ if settings.use_uppercase {+ push_one(&mut mandatory, UPPERCASE_CHARS, settings, rng);+ }+ if settings.use_numbers {+ push_one(&mut mandatory, NUMBER_CHARS, settings, rng);+ }+ if settings.use_special_chars {+ push_one(&mut mandatory, SPECIAL_CHARS, settings, rng);+ }+ mandatory}-/// Ensure the generated password contains at least one character from each enabled set.-fn ensure_requirements<R: RngCore + ?Sized>(- password: &mut Vec<char>,+/// Pick one random character from the (ambiguity-filtered) class set and push it onto `out`.+fn push_one<R: RngCore + ?Sized>(+ out: &mut Vec<char>,+ char_set: &str,settings: &PasswordSettings,rng: &mut R,) {- if settings.use_lowercase && !password.iter().any(|c| c.is_ascii_lowercase()) {- add_character_from_set(password, &safe_character_set(LOWERCASE_CHARS, settings), rng);- }- if settings.use_uppercase && !password.iter().any(|c| c.is_ascii_uppercase()) {- add_character_from_set(password, &safe_character_set(UPPERCASE_CHARS, settings), rng);- }- if settings.use_numbers && !password.iter().any(|c| c.is_ascii_digit()) {- add_character_from_set(password, &safe_character_set(NUMBER_CHARS, settings), rng);- }- if settings.use_special_chars && !password.iter().any(|c| SPECIAL_CHARS.contains(*c)) {- add_character_from_set(password, &safe_character_set(SPECIAL_CHARS, settings), rng);+ let safe = safe_character_set(char_set, settings);+ if !safe.is_empty() {+ out.push(safe[unbiased_index(rng, safe.len())]);}}@@ -107,15 +129,11 @@ fn safe_character_set(char_set: &str, settings: &PasswordSettings) -> Vec<char>remove_ambiguous_characters(&chars)}-/// Replace a random position in the password with a character from the given set.-fn add_character_from_set<R: RngCore + ?Sized>(- password: &mut [char],- char_set: &[char],- rng: &mut R,-) {- if password.is_empty() || char_set.is_empty() {- return;+/// Shuffle a slice in place with an unbiased Fisher–Yates shuffle, reusing [`unbiased_index`]+/// so the result stays deterministic under a fixed seed.+fn shuffle<R: RngCore + ?Sized>(items: &mut [char], rng: &mut R) {+ for i in (1..items.len()).rev() {+ let j = unbiased_index(rng, i + 1);+ items.swap(i, j);}- let pos = unbiased_index(rng, password.len());- password[pos] = char_set[unbiased_index(rng, char_set.len())];}diff --git a/core/rust/src/password_generator/mod.rs b/core/rust/src/password_generator/mod.rsindex 61d2bdce1..1012b8565 100644--- a/core/rust/src/password_generator/mod.rs+++ b/core/rust/src/password_generator/mod.rs@@ -147,9 +147,17 @@ fn default_length() -> u32 {}fn default_word_count() -> u32 {- 4+ 5}+/// Maximum values for the password and passphrase length. The apps cap passwords at 256+/// characters and passphrases at 10 words; the core enforces the same so we prevent any+/// excess length or word count to avoid potential issues.+const MIN_PASSWORD_LENGTH: u32 = 1;+const MAX_PASSWORD_LENGTH: u32 = 256;+const MIN_WORD_COUNT: u32 = 1;+const MAX_WORD_COUNT: u32 = 10;+fn default_true() -> bool {true}@@ -177,9 +185,17 @@ pub fn generate_password(settings_json: &str) -> Result<String, VaultError> {/// Generate a password or passphrase from already-parsed settings.pub fn generate_from_settings(settings: &PasswordSettings) -> String {let mut rng = make_rng(settings.seed.as_deref());++ // Limit the maximum values for the password and passphrase length.+ let mut settings = settings.clone();+ settings.length = settings+ .length+ .clamp(MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH);+ settings.word_count = settings.word_count.clamp(MIN_WORD_COUNT, MAX_WORD_COUNT);+match settings.generator_type {- GeneratorType::Basic => basic::generate(settings, &mut rng),- GeneratorType::Diceware => diceware::generate(settings, &mut rng),+ GeneratorType::Basic => basic::generate(&settings, &mut rng),+ GeneratorType::Diceware => diceware::generate(&settings, &mut rng),}}diff --git a/core/rust/src/password_generator/tests.rs b/core/rust/src/password_generator/tests.rsindex 3d9a96f6d..31811156c 100644--- a/core/rust/src/password_generator/tests.rs+++ b/core/rust/src/password_generator/tests.rs@@ -14,7 +14,7 @@ fn empty_json_uses_defaults() {assert_eq!(s.length, 18);assert!(s.use_lowercase && s.use_uppercase && s.use_numbers && s.use_special_chars);assert!(!s.use_non_ambiguous_chars);- assert_eq!(s.word_count, 4);+ assert_eq!(s.word_count, 5);assert_eq!(s.language, "English");assert_eq!(s.capitalization, Capitalization::Lowercase);assert_eq!(s.separator, Separator::Dash);@@ -56,6 +56,47 @@ fn basic_only_numbers_yields_only_digits() {assert!(pw.chars().all(|c| c.is_ascii_digit()));}+#[test]+fn basic_short_password_keeps_every_class() {+ // With all four classes enabled and a short length, the constructed password must still contain one of each class on every run.+ let json = r#"{"Type":"basic","Length":4,"UseLowercase":true,"UseUppercase":true,"UseNumbers":true,"UseSpecialChars":true}"#;+ for _ in 0..500 {+ let pw = generate_password(json).unwrap();+ assert_eq!(pw.chars().count(), 4);+ assert!(pw.chars().any(|c| c.is_ascii_lowercase()), "no lowercase in {pw}");+ assert!(pw.chars().any(|c| c.is_ascii_uppercase()), "no uppercase in {pw}");+ assert!(pw.chars().any(|c| c.is_ascii_digit()), "no digit in {pw}");+ assert!(+ pw.chars().any(|c| "!@#$%^&*()_+-=[]{}|;:,.<>?".contains(c)),+ "no special char in {pw}"+ );+ }+}++#[test]+fn basic_length_clamped_to_max() {+ // Out-of-range lengths are clamped to the supported maximum (256) rather than honoured.+ let json = r#"{"Type":"basic","Length":100000}"#;+ let pw = generate_password(json).unwrap();+ assert_eq!(pw.chars().count(), 256);+}++#[test]+fn basic_zero_length_clamped_to_min() {+ // Length 0 must not yield an empty password; it is clamped up to the minimum of 1.+ let json = r#"{"Type":"basic","Length":0}"#;+ let pw = generate_password(json).unwrap();+ assert_eq!(pw.chars().count(), 1);+}++#[test]+fn diceware_word_count_clamped_to_max() {+ // More than the supported 10 words is clamped down to 10.+ let json = r#"{"Type":"diceware","WordCount":50,"Separator":"Dash","Salt":"None"}"#;+ let pw = generate_password(json).unwrap();+ assert_eq!(pw.split('-').count(), 10);+}+#[test]fn basic_no_classes_falls_back_to_lowercase() {let json = r#"{"Type":"basic","Length":20,"UseLowercase":false,"UseUppercase":false,"UseNumbers":false,"UseSpecialChars":false}"#;