Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PM-3435] Passphrase generator #262

Merged
merged 18 commits into from
Dec 4, 2023
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/bitwarden/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,6 @@ bitwarden-api-identity = { path = "../bitwarden-api-identity", version = "=0.2.1
bitwarden-api-api = { path = "../bitwarden-api-api", version = "=0.2.1" }

[dev-dependencies]
rand_chacha = "0.3.1"
tokio = { version = "1.28.2", features = ["rt", "macros"] }
wiremock = "0.5.18"
5 changes: 2 additions & 3 deletions crates/bitwarden/src/tool/generators/client_generator.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use crate::{
error::Result,
tool::generators::password::{
passphrase, password, PassphraseGeneratorRequest, PasswordGeneratorRequest,
},
tool::generators::passphrase::{passphrase, PassphraseGeneratorRequest},
tool::generators::password::{password, PasswordGeneratorRequest},
Client,
};

Expand Down
4 changes: 3 additions & 1 deletion crates/bitwarden/src/tool/generators/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
mod client_generator;
mod passphrase;
mod password;

pub use password::{PassphraseGeneratorRequest, PasswordGeneratorRequest};
pub use passphrase::PassphraseGeneratorRequest;
pub use password::PasswordGeneratorRequest;
190 changes: 190 additions & 0 deletions crates/bitwarden/src/tool/generators/passphrase.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
use crate::{
error::{Error, Result},
wordlist::EFF_LONG_WORD_LIST,
};
use rand::{seq::SliceRandom, Rng, RngCore};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Passphrase generator request.
///
/// The default separator is `-` and default number of words is 3.
#[derive(Serialize, Deserialize, Debug, JsonSchema, Default)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[cfg_attr(feature = "mobile", derive(uniffi::Record))]
pub struct PassphraseGeneratorRequest {
audreyality marked this conversation as resolved.
Show resolved Hide resolved
/// Number of words in the generated passphrase.
/// This value must be between 3 and 20.
/// The default value when unset is 3
pub num_words: Option<u8>,
/// Character separator between words in the generated passphrase.
/// If the value is set, it cannot be empty.
/// The default value when unset is `-`
pub word_separator: Option<String>,
/// When set to true, capitalize the first letter of each word in the generated passphrase.
/// The default value when unset is `false`
pub capitalize: Option<bool>,
/// When set to true, include a number at the end of one of the words in the generated passphrase.
/// The default value when unset is `false`
pub include_number: Option<bool>,
}

const DEFAULT_PASSPHRASE_NUM_WORDS: u8 = 3;
const DEFAULT_PASSPHRASE_SEPARATOR: &str = " ";

const MINIMUM_PASSPHRASE_NUM_WORDS: u8 = 3;
const MAXIMUM_PASSPHRASE_NUM_WORDS: u8 = 20;

pub(super) fn passphrase(input: PassphraseGeneratorRequest) -> Result<String> {
passphrase_with_rng(rand::thread_rng(), input)
}

fn passphrase_with_rng(mut rng: impl RngCore, input: PassphraseGeneratorRequest) -> Result<String> {
dani-garcia marked this conversation as resolved.
Show resolved Hide resolved
let capitalize = input.capitalize.unwrap_or(false);
let include_number = input.include_number.unwrap_or(false);

let num_words = input.num_words.unwrap_or(DEFAULT_PASSPHRASE_NUM_WORDS);
if !(MINIMUM_PASSPHRASE_NUM_WORDS..=MAXIMUM_PASSPHRASE_NUM_WORDS).contains(&num_words) {
return Err(Error::Internal("'num_words' must be between 3 and 20"));
Hinton marked this conversation as resolved.
Show resolved Hide resolved
}

let Some(separator) = input
.word_separator
.as_deref()
.unwrap_or(DEFAULT_PASSPHRASE_SEPARATOR)
.chars()
.next()
else {
return Err(Error::Internal("'word_separator' cannot be empty"));
};

let mut passphrase_words = gen_words(&mut rng, num_words);
if include_number {
include_number_in_words(&mut rng, &mut passphrase_words);
}
if capitalize {
capitalize_words(&mut passphrase_words);
}
Ok(passphrase_words.join(&separator.to_string()))
}

fn gen_words(mut rng: impl RngCore, num_words: u8) -> Vec<String> {
(0..num_words)
.map(|_| {
EFF_LONG_WORD_LIST
.choose(&mut rng)
.expect("slice is not empty")
.to_string()
})
.collect()
}
dani-garcia marked this conversation as resolved.
Show resolved Hide resolved

fn include_number_in_words(mut rng: impl RngCore, words: &mut [String]) {
let number_idx = rng.gen_range(0..words.len());
words[number_idx].push_str(&rng.gen_range(0..=9).to_string());
}

fn capitalize_words(words: &mut [String]) {
words
.iter_mut()
.for_each(|w| *w = capitalize_first_letter(w));
}

fn capitalize_first_letter(s: &str) -> String {
// Unicode case conversion can change the length of the string, so we can't capitalize in place.
// Instead we extract the first character and convert it to uppercase. This returns
// an iterator which we collect into a string, and then append the rest of the input.
audreyality marked this conversation as resolved.
Show resolved Hide resolved
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
audreyality marked this conversation as resolved.
Show resolved Hide resolved
}

#[cfg(test)]
mod tests {
use rand::SeedableRng;

use super::*;

#[test]
fn test_gen_words() {
let mut rng = rand_chacha::ChaCha8Rng::from_seed([0u8; 32]);
assert_eq!(
&gen_words(&mut rng, 4),
&["subsystem", "undertook", "silenced", "dinginess"]
);
assert_eq!(&gen_words(&mut rng, 1), &["numbing"]);
assert_eq!(&gen_words(&mut rng, 2), &["catnip", "jokester"]);
}

#[test]
fn test_capitalize() {
assert_eq!(capitalize_first_letter("hello"), "Hello");
assert_eq!(capitalize_first_letter("1ello"), "1ello");
assert_eq!(capitalize_first_letter("Hello"), "Hello");
assert_eq!(capitalize_first_letter("h"), "H");
assert_eq!(capitalize_first_letter(""), "");

// Also supports non-ascii, though the EFF list doesn't have any
assert_eq!(capitalize_first_letter("áéíóú"), "Áéíóú");
}

#[test]
fn test_capitalize_words() {
let mut words = vec!["hello".into(), "world".into()];
capitalize_words(&mut words);
assert_eq!(words, &["Hello", "World"]);
}

#[test]
fn test_include_number() {
let mut rng = rand_chacha::ChaCha8Rng::from_seed([0u8; 32]);

let mut words = vec!["hello".into(), "world".into()];
include_number_in_words(&mut rng, &mut words);
assert_eq!(words, &["hello", "world7"]);

let mut words = vec!["This".into(), "is".into(), "a".into(), "test".into()];
include_number_in_words(&mut rng, &mut words);
assert_eq!(words, &["This", "is", "a1", "test"]);
}

#[test]
fn test_passphrase() {
let mut rng = rand_chacha::ChaCha8Rng::from_seed([0u8; 32]);

let input = PassphraseGeneratorRequest {
num_words: Some(4),
word_separator: Some("-".into()),
capitalize: Some(true),
include_number: Some(true),
};
assert_eq!(
passphrase_with_rng(&mut rng, input).unwrap(),
"Subsystem4-Undertook-Silenced-Dinginess"
);

let input = PassphraseGeneratorRequest {
num_words: Some(3),
word_separator: Some(" ".into()),
capitalize: Some(false),
include_number: Some(true),
};
assert_eq!(
passphrase_with_rng(&mut rng, input).unwrap(),
"drew7 hankering cabana"
);

let input = PassphraseGeneratorRequest {
num_words: Some(5),
word_separator: Some(";".into()),
capitalize: None,
include_number: None,
};
assert_eq!(
passphrase_with_rng(&mut rng, input).unwrap(),
"duller;backlight;factual;husked;remover"
);
}
}
17 changes: 0 additions & 17 deletions crates/bitwarden/src/tool/generators/password.rs
dani-garcia marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,6 @@ pub struct PasswordGeneratorRequest {
pub min_special: Option<bool>,
}

/// Passphrase generator request.
///
/// The default separator is `-` and default number of words is 3.
#[derive(Serialize, Deserialize, Debug, JsonSchema, Default)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[cfg_attr(feature = "mobile", derive(uniffi::Record))]
pub struct PassphraseGeneratorRequest {
pub num_words: Option<u8>,
pub word_separator: Option<String>,
pub capitalize: Option<bool>,
pub include_number: Option<bool>,
}

pub(super) fn password(_input: PasswordGeneratorRequest) -> Result<String> {
Ok("pa11w0rd".to_string())
}

pub(super) fn passphrase(_input: PassphraseGeneratorRequest) -> Result<String> {
Ok("correct-horse-battery-staple".to_string())
}
32 changes: 29 additions & 3 deletions crates/bw/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use bitwarden::{
auth::RegisterRequest, client::client_settings::ClientSettings, tool::PasswordGeneratorRequest,
auth::RegisterRequest,
client::client_settings::ClientSettings,
tool::{PassphraseGeneratorRequest, PasswordGeneratorRequest},
};
use bitwarden_cli::{install_color_eyre, text_prompt_when_none, Color};
use clap::{command, Args, CommandFactory, Parser, Subcommand};
Expand Down Expand Up @@ -87,7 +89,7 @@ enum ItemCommands {
#[derive(Subcommand, Clone)]
enum GeneratorCommands {
Password(PasswordGeneratorArgs),
Passphrase {},
Passphrase(PassphraseGeneratorArgs),
}

#[derive(Args, Clone)]
Expand All @@ -113,6 +115,18 @@ struct PasswordGeneratorArgs {
length: u8,
}

#[derive(Args, Clone)]
struct PassphraseGeneratorArgs {
#[arg(long, default_value = "3", help = "Number of words in the passphrase")]
words: u8,
#[arg(long, default_value = " ", help = "Separator between words")]
separator: char,
#[arg(long, action, help = "Capitalize the first letter of each word")]
capitalize: bool,
#[arg(long, action, help = "Include a number in one of the words")]
include_number: bool,
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
Expand Down Expand Up @@ -206,7 +220,19 @@ async fn process_commands() -> Result<()> {

println!("{}", password);
}
GeneratorCommands::Passphrase {} => todo!(),
GeneratorCommands::Passphrase(args) => {
let passphrase = client
.generator()
.passphrase(PassphraseGeneratorRequest {
num_words: Some(args.words),
word_separator: Some(args.separator.to_string()),
capitalize: Some(args.capitalize),
include_number: Some(args.include_number),
})
.await?;

println!("{}", passphrase);
}
},
};

Expand Down