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 6 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;
121 changes: 121 additions & 0 deletions crates/bitwarden/src/tool/generators/passphrase.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
use crate::{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
pub num_words: Option<u8>,
pub word_separator: Option<String>,
pub capitalize: Option<bool>,
pub include_number: Option<bool>,
}
dani-garcia marked this conversation as resolved.
Show resolved Hide resolved

const DEFAULT_PASSPHRASE_NUM_WORDS: u8 = 3;
const DEFAULT_PASSPHRASE_SEPARATOR: char = ' ';

pub(super) fn passphrase(input: PassphraseGeneratorRequest) -> Result<String> {
let num_words = input.num_words.unwrap_or(DEFAULT_PASSPHRASE_NUM_WORDS);
let separator = input
.word_separator
.and_then(|s| s.chars().next())
.unwrap_or(DEFAULT_PASSPHRASE_SEPARATOR);
let capitalize = input.capitalize.unwrap_or(false);
let include_number = input.include_number.unwrap_or(false);

let mut rand = rand::thread_rng();

let mut passphrase_words = gen_words(&mut rand, num_words);
if include_number {
include_number_in_words(&mut rand, &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 {
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"]);
}
}
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