Skip to main content

bitwarden_generators/
passphrase.rs

1use bitwarden_crypto::EFF_LONG_WORD_LIST;
2use bitwarden_error::bitwarden_error;
3use rand::{Rng, RngExt, seq::IndexedRandom};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use thiserror::Error;
7#[cfg(feature = "wasm")]
8use tsify::Tsify;
9
10use crate::util::capitalize_first_letter;
11
12#[allow(missing_docs)]
13#[bitwarden_error(full)]
14#[derive(Debug, Error)]
15pub enum PassphraseError {
16    #[error("'num_words' must be between {} and {}", minimum, maximum)]
17    InvalidNumWords { minimum: u8, maximum: u8 },
18}
19
20/// Passphrase generator request options.
21#[derive(Serialize, Deserialize, Debug, JsonSchema)]
22#[serde(rename_all = "camelCase", deny_unknown_fields)]
23#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
24#[cfg_attr(feature = "wasm", derive(Tsify), tsify(into_wasm_abi, from_wasm_abi))]
25pub struct PassphraseGeneratorRequest {
26    /// Number of words in the generated passphrase.
27    /// This value must be between 3 and 20.
28    pub num_words: u8,
29    /// Character separator between words in the generated passphrase. The value cannot be empty.
30    pub word_separator: String,
31    /// When set to true, capitalize the first letter of each word in the generated passphrase.
32    pub capitalize: bool,
33    /// When set to true, include a number at the end of one of the words in the generated
34    /// passphrase.
35    pub include_number: bool,
36}
37
38impl Default for PassphraseGeneratorRequest {
39    fn default() -> Self {
40        Self {
41            num_words: 3,
42            word_separator: ' '.to_string(),
43            capitalize: false,
44            include_number: false,
45        }
46    }
47}
48
49/// Minimum number of words allowed in a generated passphrase.
50pub const MINIMUM_PASSPHRASE_NUM_WORDS: u8 = 3;
51/// Maximum number of words allowed in a generated passphrase.
52pub const MAXIMUM_PASSPHRASE_NUM_WORDS: u8 = 20;
53
54/// Represents a set of valid options to generate a passhprase with.
55/// To get an instance of it, use
56/// [`PassphraseGeneratorRequest::validate_options`](PassphraseGeneratorRequest::validate_options)
57struct ValidPassphraseGeneratorOptions {
58    pub(super) num_words: u8,
59    pub(super) word_separator: String,
60    pub(super) capitalize: bool,
61    pub(super) include_number: bool,
62}
63
64impl PassphraseGeneratorRequest {
65    /// Validates the request and returns an immutable struct with valid options to use with the
66    /// passphrase generator.
67    fn validate_options(self) -> Result<ValidPassphraseGeneratorOptions, PassphraseError> {
68        // TODO: Add password generator policy checks
69
70        if !(MINIMUM_PASSPHRASE_NUM_WORDS..=MAXIMUM_PASSPHRASE_NUM_WORDS).contains(&self.num_words)
71        {
72            return Err(PassphraseError::InvalidNumWords {
73                minimum: MINIMUM_PASSPHRASE_NUM_WORDS,
74                maximum: MAXIMUM_PASSPHRASE_NUM_WORDS,
75            });
76        }
77
78        Ok(ValidPassphraseGeneratorOptions {
79            num_words: self.num_words,
80            word_separator: self.word_separator,
81            capitalize: self.capitalize,
82            include_number: self.include_number,
83        })
84    }
85}
86
87/// Implementation of the random passphrase generator.
88pub(crate) fn passphrase(request: PassphraseGeneratorRequest) -> Result<String, PassphraseError> {
89    let options = request.validate_options()?;
90    Ok(passphrase_with_rng(rand::rng(), options))
91}
92
93fn passphrase_with_rng(mut rng: impl Rng, options: ValidPassphraseGeneratorOptions) -> String {
94    let mut passphrase_words = gen_words(&mut rng, options.num_words);
95    if options.include_number {
96        include_number_in_words(&mut rng, &mut passphrase_words);
97    }
98    if options.capitalize {
99        capitalize_words(&mut passphrase_words);
100    }
101    passphrase_words.join(&options.word_separator)
102}
103
104fn gen_words(mut rng: impl Rng, num_words: u8) -> Vec<String> {
105    (0..num_words)
106        .map(|_| {
107            EFF_LONG_WORD_LIST
108                .choose(&mut rng)
109                .expect("slice is not empty")
110                .to_string()
111        })
112        .collect()
113}
114
115fn include_number_in_words(mut rng: impl Rng, words: &mut [String]) {
116    let number_idx = rng.random_range(0..words.len());
117    words[number_idx].push_str(&rng.random_range(0..=9).to_string());
118}
119
120fn capitalize_words(words: &mut [String]) {
121    words
122        .iter_mut()
123        .for_each(|w| *w = capitalize_first_letter(w));
124}
125
126#[cfg(test)]
127mod tests {
128    use rand::SeedableRng;
129
130    use super::*;
131
132    #[test]
133    fn test_gen_words() {
134        let mut rng = rand_chacha::ChaCha8Rng::from_seed([0u8; 32]);
135        assert_eq!(
136            &gen_words(&mut rng, 4),
137            &["crust", "subsystem", "undertook", "protector"]
138        );
139        assert_eq!(&gen_words(&mut rng, 1), &["silenced"]);
140        assert_eq!(&gen_words(&mut rng, 2), &["dinginess", "numbing"]);
141    }
142
143    #[test]
144    fn test_capitalize() {
145        assert_eq!(capitalize_first_letter("hello"), "Hello");
146        assert_eq!(capitalize_first_letter("1ello"), "1ello");
147        assert_eq!(capitalize_first_letter("Hello"), "Hello");
148        assert_eq!(capitalize_first_letter("h"), "H");
149        assert_eq!(capitalize_first_letter(""), "");
150
151        // Also supports non-ascii, though the EFF list doesn't have any
152        assert_eq!(capitalize_first_letter("áéíóú"), "Áéíóú");
153    }
154
155    #[test]
156    fn test_capitalize_words() {
157        let mut words = vec!["hello".into(), "world".into()];
158        capitalize_words(&mut words);
159        assert_eq!(words, &["Hello", "World"]);
160    }
161
162    #[test]
163    fn test_include_number() {
164        let mut rng = rand_chacha::ChaCha8Rng::from_seed([0u8; 32]);
165
166        let mut words = vec!["hello".into(), "world".into()];
167        include_number_in_words(&mut rng, &mut words);
168        assert_eq!(words, &["hello8", "world"]);
169
170        let mut words = vec!["This".into(), "is".into(), "a".into(), "test".into()];
171        include_number_in_words(&mut rng, &mut words);
172        assert_eq!(words, &["This", "is", "a", "test6"]);
173    }
174
175    #[test]
176    fn test_separator() {
177        let mut rng = rand_chacha::ChaCha8Rng::from_seed([0u8; 32]);
178
179        let input = PassphraseGeneratorRequest {
180            num_words: 4,
181            // This emoji is 35 bytes long, but represented as a single character
182            word_separator: "👨🏻‍❤️‍💋‍👨🏻".into(),
183            capitalize: false,
184            include_number: true,
185        }
186        .validate_options()
187        .unwrap();
188        assert_eq!(
189            passphrase_with_rng(&mut rng, input),
190            "crust👨🏻‍❤️‍💋‍👨🏻subsystem👨🏻‍❤️‍💋‍👨🏻undertook👨🏻‍❤️‍💋‍👨🏻protector2"
191        );
192    }
193
194    #[test]
195    fn test_passphrase() {
196        let mut rng = rand_chacha::ChaCha8Rng::from_seed([0u8; 32]);
197
198        let input = PassphraseGeneratorRequest {
199            num_words: 4,
200            word_separator: "-".into(),
201            capitalize: true,
202            include_number: true,
203        }
204        .validate_options()
205        .unwrap();
206        assert_eq!(
207            passphrase_with_rng(&mut rng, input),
208            "Crust-Subsystem-Undertook-Protector2"
209        );
210
211        let input = PassphraseGeneratorRequest {
212            num_words: 3,
213            word_separator: " ".into(),
214            capitalize: false,
215            include_number: true,
216        }
217        .validate_options()
218        .unwrap();
219        assert_eq!(
220            passphrase_with_rng(&mut rng, input),
221            "numbing4 catnip jokester"
222        );
223
224        let input = PassphraseGeneratorRequest {
225            num_words: 5,
226            word_separator: ";".into(),
227            capitalize: false,
228            include_number: false,
229        }
230        .validate_options()
231        .unwrap();
232        assert_eq!(
233            passphrase_with_rng(&mut rng, input),
234            "cabana;pungent;acts;sarcasm;duller"
235        );
236    }
237}