//! The rule a new password is made by: its length and its classes, as data. //! //! ```text //! PasswordRule::shipped() the rule Cotton Keys offers (password_rule.json) //! PasswordRule::from_value(json) a rule the caller hands over, checked //! rule.generate() a password from the OS random source //! rule.generate_with(rng) the same from a given source (the vectors) //! ``` //! //! A rule is a length and a list of classes, each its characters and how many //! of them a password holds at least. A password takes `at_least` characters //! from each class, fills the rest from every class's characters together, //! and is shuffled; every draw is uniform (`gen_range`, never a modulo). The //! shipped rule leaves out characters read for one another (`0`/`O`, `1`/`l`/`I`). //! //! **Pure** but for the OS random source in [`PasswordRule::generate`]. use rand::seq::SliceRandom; use rand::Rng; use serde::{Deserialize, Serialize}; use zeroize::Zeroizing; /// The rule Cotton Keys offers, as data. pub const SHIPPED: &str = include_str!("password_rule.json"); /// The longest password a rule makes. pub const LENGTH_MAX: usize = 128; /// One class of characters a password draws from. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct CharClass { /// A name for the class (`lower`, `digits`), unique in its rule. pub id: String, /// The characters, each once. pub chars: String, /// How many of these a password holds at least. #[serde(default)] pub at_least: usize, } /// How a new password is made. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct PasswordRule { pub length: usize, pub classes: Vec, } /// Why a rule was refused, in words. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum RuleError { #[error("the rule does not read: {0}")] DoesNotRead(String), #[error("a password is 1 to {LENGTH_MAX} characters, not {0}")] BadLength(usize), #[error("the rule names no class of characters")] NoClasses, #[error("the class {0:?} has no characters")] EmptyClass(String), #[error("the class {0:?} names a character twice")] RepeatedChar(String), #[error("two classes are called {0:?}")] RepeatedClass(String), #[error("the classes ask for {asked} characters at least, more than the length {length}")] TooManyAsked { asked: usize, length: usize }, } impl PasswordRule { /// The rule Cotton Keys ships. pub fn shipped() -> PasswordRule { PasswordRule::from_value(&serde_json::from_str(SHIPPED).expect("the shipped rule is JSON")) .expect("the shipped rule holds") } /// A rule handed over as JSON, checked. pub fn from_value(value: &serde_json::Value) -> Result { let rule: PasswordRule = serde_json::from_value(value.clone()).map_err(|error| RuleError::DoesNotRead(error.to_string()))?; rule.check()?; Ok(rule) } /// Whether the rule can make a password. pub fn check(&self) -> Result<(), RuleError> { if self.length == 0 || self.length > LENGTH_MAX { return Err(RuleError::BadLength(self.length)); } if self.classes.is_empty() { return Err(RuleError::NoClasses); } let mut ids = std::collections::HashSet::new(); let mut seen = std::collections::HashSet::new(); for class in &self.classes { if !ids.insert(class.id.as_str()) { return Err(RuleError::RepeatedClass(class.id.clone())); } if class.chars.is_empty() { return Err(RuleError::EmptyClass(class.id.clone())); } for ch in class.chars.chars() { if !seen.insert(ch) { return Err(RuleError::RepeatedChar(class.id.clone())); } } } let asked: usize = self.classes.iter().map(|class| class.at_least).sum(); if asked > self.length { return Err(RuleError::TooManyAsked { asked, length: self.length }); } Ok(()) } /// A password by this rule, from the OS random source. pub fn generate(&self) -> Result, RuleError> { self.generate_with(&mut rand::rngs::OsRng) } /// A password by this rule, from `rng`. pub fn generate_with(&self, rng: &mut R) -> Result, RuleError> { self.check()?; let every: Vec = self.classes.iter().flat_map(|class| class.chars.chars()).collect(); let mut out: Zeroizing> = Zeroizing::new(Vec::with_capacity(self.length)); for class in &self.classes { let chars: Vec = class.chars.chars().collect(); for _ in 0..class.at_least { out.push(chars[rng.gen_range(0..chars.len())]); } } while out.len() < self.length { out.push(every[rng.gen_range(0..every.len())]); } out.shuffle(rng); Ok(Zeroizing::new(out.iter().collect())) } } #[cfg(test)] #[path = "password_rule_tests.rs"] mod tests;