agentmux_srv_core/backend/vault/
generate.rs1use ring::rand::{SecureRandom, SystemRandom};
13use zeroize::Zeroizing;
14
15const LOWER: &str = "abcdefghijkmnopqrstuvwxyz";
16const UPPER: &str = "ABCDEFGHJKLMNPQRSTUVWXYZ";
17const DIGIT: &str = "23456789";
18const SPECIAL: &str = "-_.!@#%^*";
20const LOOK_ALIKES: &str = "0O1lI";
22
23pub const DEFAULT_LENGTH: usize = 20;
24pub const MIN_LENGTH: usize = 8;
25pub const MAX_LENGTH: usize = 128;
26pub const MIN_BITS: f64 = 80.0;
28pub const DEFAULT_WORDS: usize = 6;
29const MAX_WORDS: usize = 12;
30const TRIES: usize = 200;
33
34#[derive(Debug, Clone, PartialEq)]
36pub enum Style {
37 Chars,
39 Words(usize),
42}
43
44#[derive(Debug, Clone, PartialEq)]
45pub struct Rules {
46 pub style: Style,
47 pub length: usize,
48 pub required: Vec<String>,
50 pub allowed: String,
52 pub max_consecutive: Option<usize>,
53}
54
55impl Default for Rules {
56 fn default() -> Self {
57 let required = vec![LOWER.to_string(), UPPER.to_string(), DIGIT.to_string(), SPECIAL.to_string()];
58 Rules { style: Style::Chars, length: DEFAULT_LENGTH, allowed: required.concat(), required, max_consecutive: None }
59 }
60}
61
62#[derive(Debug, Clone, Default, serde::Deserialize)]
64pub struct RulesRequest {
65 #[serde(default)]
66 pub passwordrules: Option<String>,
67 #[serde(default)]
68 pub length: Option<usize>,
69 #[serde(default)]
70 pub words: Option<usize>,
71 #[serde(default)]
73 pub maxlength: Option<usize>,
74}
75
76fn class(name: &str) -> Option<&'static str> {
77 match name {
78 "lower" => Some(LOWER),
79 "upper" => Some(UPPER),
80 "digit" => Some(DIGIT),
81 "special" => Some(SPECIAL),
82 _ => None,
83 }
84}
85
86fn custom_set(set: &str) -> Result<String, String> {
88 let inner = set.strip_prefix('[').and_then(|s| s.strip_suffix(']')).ok_or_else(|| format!("{set:?} isn't a class or a [set]"))?;
89 let mut out = String::new();
90 for c in inner.chars() {
91 if c.is_ascii_graphic() && !LOOK_ALIKES.contains(c) && !out.contains(c) {
92 out.push(c);
93 }
94 }
95 if out.is_empty() {
96 return Err(format!("the set {set:?} holds no usable character"));
97 }
98 Ok(out)
99}
100
101fn sets(value: &str) -> Result<Vec<String>, String> {
103 let mut out = Vec::new();
104 for item in value.split(',').map(str::trim).filter(|s| !s.is_empty()) {
105 match class(item) {
106 Some(c) => out.push(c.to_string()),
107 None if item == "ascii-printable" || item == "unicode" => out.push([LOWER, UPPER, DIGIT, SPECIAL].concat()),
108 None => out.push(custom_set(item)?),
109 }
110 }
111 Ok(out)
112}
113
114fn merge(into: &mut String, set: &str) {
115 for c in set.chars() {
116 if !into.contains(c) {
117 into.push(c);
118 }
119 }
120}
121
122struct SiteRules {
125 min: usize,
126 max: usize,
127 max_consecutive: Option<usize>,
128 required: Vec<String>,
129 allowed: String,
130}
131
132fn parse(text: &str) -> Result<SiteRules, String> {
134 if text.len() > 1000 {
135 return Err("passwordrules is longer than 1000 characters".into());
136 }
137 let mut site = SiteRules { min: 0, max: usize::MAX, max_consecutive: None, required: Vec::new(), allowed: String::new() };
138 for rule in text.split(';').map(str::trim).filter(|s| !s.is_empty()) {
139 let (name, value) = rule.split_once(':').ok_or_else(|| format!("{rule:?} isn't name: value"))?;
140 let (name, value) = (name.trim().to_ascii_lowercase(), value.trim());
141 let number = || value.parse::<usize>().map_err(|_| format!("{name} needs a number, not {value:?}"));
142 match name.as_str() {
143 "minlength" => site.min = site.min.max(number()?),
144 "maxlength" => site.max = site.max.min(number()?),
145 "max-consecutive" => site.max_consecutive = Some(number()?.max(1)),
146 "required" => {
147 let union = sets(value)?.concat();
149 merge(&mut site.allowed, &union);
150 site.required.push(union);
151 }
152 "allowed" => {
153 for s in sets(value)? {
154 merge(&mut site.allowed, &s);
155 }
156 }
157 _ => {}
159 }
160 }
161 Ok(site)
162}
163
164pub fn readable(passwordrules: &str) -> bool {
168 parse(passwordrules.trim()).is_ok()
169}
170
171pub fn rules(req: &RulesRequest) -> Result<Rules, String> {
174 if let Some(n) = req.words {
175 if !(DEFAULT_WORDS..=MAX_WORDS).contains(&n) {
176 return Err(format!("words is {DEFAULT_WORDS} to {MAX_WORDS}"));
177 }
178 if req.passwordrules.as_deref().is_some_and(|t| !t.trim().is_empty()) {
179 return Err("words can't follow a site's passwordrules: leave out words for a character value".into());
180 }
181 let longest = n * super::wordlist::WORDS.iter().map(|w| w.len()).max().unwrap_or(0) + n - 1;
183 if let Some(m) = req.maxlength.filter(|m| *m > 0 && *m < longest) {
184 return Err(format!(
185 "{n} words can run to {longest} characters, more than the field's maxlength of {m}: leave out words for a character value"
186 ));
187 }
188 return Ok(Rules { style: Style::Words(n), length: 0, required: Vec::new(), allowed: String::new(), max_consecutive: None });
189 }
190 let mut r = Rules::default();
191 let (mut min, mut max) = (MIN_LENGTH, MAX_LENGTH);
192 if let Some(text) = req.passwordrules.as_deref().map(str::trim).filter(|t| !t.is_empty()) {
193 let site = parse(text)?;
194 min = min.max(site.min);
195 max = max.min(site.max);
196 if site.max_consecutive.is_some() {
197 r.max_consecutive = site.max_consecutive;
198 }
199 if !site.allowed.is_empty() {
200 r.allowed = site.allowed;
201 r.required = site.required;
202 }
203 }
204 if let Some(m) = req.maxlength.filter(|m| *m > 0) {
205 max = max.min(m);
206 }
207 if min > max {
208 return Err(format!("the rules ask for at least {min} and at most {max} characters"));
209 }
210 r.length = req.length.unwrap_or(DEFAULT_LENGTH).clamp(min, max);
211 if r.required.len() > r.length {
212 return Err(format!("{} required classes don't fit in {} characters", r.required.len(), r.length));
213 }
214 let bits = bits(&r);
215 if bits < MIN_BITS {
216 return Err(format!(
217 "these rules leave {bits:.0} bits ({} characters from {} choices); at least {MIN_BITS:.0} are needed: allow a longer value or more characters",
218 r.length,
219 r.allowed.chars().count()
220 ));
221 }
222 Ok(r)
223}
224
225pub fn bits(r: &Rules) -> f64 {
227 match r.style {
228 Style::Words(n) => n as f64 * (super::wordlist::WORDS.len() as f64).log2(),
229 Style::Chars => r.length as f64 * (r.allowed.chars().count().max(1) as f64).log2(),
230 }
231}
232
233fn index(rng: &SystemRandom, n: usize) -> Result<usize, String> {
235 debug_assert!(n > 0 && n <= 256);
236 let limit = 256 - (256 % n);
237 loop {
238 let mut b = [0u8; 1];
239 rng.fill(&mut b).map_err(|_| "the system random generator failed".to_string())?;
240 if (b[0] as usize) < limit {
241 return Ok(b[0] as usize % n);
242 }
243 }
244}
245
246fn meets(value: &[char], r: &Rules) -> bool {
247 if !r.required.iter().all(|set| value.iter().any(|c| set.contains(*c))) {
248 return false;
249 }
250 if let Some(max) = r.max_consecutive {
251 let mut run = 1;
252 for w in value.windows(2) {
253 run = if w[0] == w[1] { run + 1 } else { 1 };
254 if run > max {
255 return false;
256 }
257 }
258 }
259 true
260}
261
262pub fn generate(r: &Rules) -> Result<Zeroizing<String>, String> {
264 let rng = SystemRandom::new();
265 if let Style::Words(n) = r.style {
266 let words = super::wordlist::WORDS;
267 let mut out = Zeroizing::new(String::new());
268 for i in 0..n {
269 if i > 0 {
270 out.push('-');
271 }
272 out.push_str(words[index(&rng, words.len())?]);
273 }
274 return Ok(out);
275 }
276 let alphabet: Vec<char> = r.allowed.chars().collect();
277 if alphabet.is_empty() || alphabet.len() > 256 {
278 return Err("the rules allow no characters".into());
279 }
280 for _ in 0..TRIES {
281 let mut chars = Zeroizing::new(Vec::with_capacity(r.length));
282 for _ in 0..r.length {
283 chars.push(alphabet[index(&rng, alphabet.len())?]);
284 }
285 if meets(&chars, r) {
286 return Ok(Zeroizing::new(chars.iter().collect()));
287 }
288 }
289 Err("couldn't make a value that meets every rule: they may contradict each other".into())
290}
291
292pub fn describe(r: &Rules) -> String {
294 match r.style {
295 Style::Words(n) => format!("{n} words, {:.0} bits", bits(r)),
296 Style::Chars => format!("{} characters from {} choices, {:.0} bits", r.length, r.allowed.chars().count(), bits(r)),
297 }
298}
299
300#[cfg(test)]
301#[path = "generate_tests.rs"]
302mod tests;