//! 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.pubconst SHIPPED: &str = include_str!("password_rule.json");/// The longest password a rule makes.pubconst LENGTH_MAX: usize = 128;/// One class of characters a password draws from.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pubstructCharClass {/// 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)]pubstructPasswordRule {pub length: usize,pub classes: Vec<CharClass>,}/// Why a rule was refused, in words.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pubenumRuleError { #[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 },}implPasswordRule {/// The rule Cotton Keys ships.pubfn 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.pubfn from_value(value: &serde_json::Value) -> Result<PasswordRule, RuleError> {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.pubfn check(&self) -> Result<(), RuleError> {ifself.length == 0 || self.length > LENGTH_MAX {returnErr(RuleError::BadLength(self.length)); }ifself.classes.is_empty() {returnErr(RuleError::NoClasses); }letmut ids = std::collections::HashSet::new();letmut seen = std::collections::HashSet::new();for class in &self.classes {if !ids.insert(class.id.as_str()) {returnErr(RuleError::RepeatedClass(class.id.clone())); }if class.chars.is_empty() {returnErr(RuleError::EmptyClass(class.id.clone())); }for ch in class.chars.chars() {if !seen.insert(ch) {returnErr(RuleError::RepeatedChar(class.id.clone())); } } }let asked: usize = self.classes.iter().map(|class| class.at_least).sum();if asked > self.length {returnErr(RuleError::TooManyAsked { asked, length: self.length }); }Ok(()) }/// A password by this rule, from the OS random source.pubfn generate(&self) -> Result<Zeroizing<String>, RuleError> {self.generate_with(&mut rand::rngs::OsRng) }/// A password by this rule, from `rng`.pubfn generate_with<R: Rng + ?Sized>(&self, rng: &mut R) -> Result<Zeroizing<String>, RuleError> {self.check()?;let every: Vec<char> = self.classes.iter().flat_map(|class| class.chars.chars()).collect();letmut out: Zeroizing<Vec<char>> = Zeroizing::new(Vec::with_capacity(self.length));for class in &self.classes {let chars: Vec<char> = class.chars.chars().collect();for _ in0..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;