Skip to main content

agentmux_srv_core/backend/vault/
generate.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Strong values the Vault makes itself, so no person types them and no agent
5//! sees them (docs/specs/SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md ยง4.1).
6//!
7//! Characters are drawn from the OS generator (`ring`'s `SystemRandom`) with
8//! rejection sampling, so every allowed character is equally likely. The rules
9//! take the `passwordrules` format sites declare on their fields
10//! (`minlength: 12; maxlength: 32; required: lower; required: digit; allowed: [-_]`).
11
12use ring::rand::{SecureRandom, SystemRandom};
13use zeroize::Zeroizing;
14
15const LOWER: &str = "abcdefghijkmnopqrstuvwxyz";
16const UPPER: &str = "ABCDEFGHJKLMNPQRSTUVWXYZ";
17const DIGIT: &str = "23456789";
18/// The symbols most sites accept.
19const SPECIAL: &str = "-_.!@#%^*";
20/// Look-alikes left out of every class, so a person can read a value if they ever must.
21const LOOK_ALIKES: &str = "0O1lI";
22
23pub const DEFAULT_LENGTH: usize = 20;
24pub const MIN_LENGTH: usize = 8;
25pub const MAX_LENGTH: usize = 128;
26/// Below this a character value is refused: the rules leave too few choices.
27pub const MIN_BITS: f64 = 80.0;
28pub const DEFAULT_WORDS: usize = 6;
29const MAX_WORDS: usize = 12;
30/// Tries at drawing a value that meets every `required` class and
31/// `max-consecutive`; with any rules that leave 80 bits, a few are enough.
32const TRIES: usize = 200;
33
34/// How a value is built.
35#[derive(Debug, Clone, PartialEq)]
36pub enum Style {
37    /// Characters from the classes the rules allow.
38    Chars,
39    /// Words from the Vault's word list, joined by `-`: for a value a person
40    /// must type on a TV or a phone.
41    Words(usize),
42}
43
44#[derive(Debug, Clone, PartialEq)]
45pub struct Rules {
46    pub style: Style,
47    pub length: usize,
48    /// Each set must give the value at least one character.
49    pub required: Vec<String>,
50    /// Every character the value may hold (the required sets included).
51    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/// What a caller asks for: a site's `passwordrules`, a length, or words.
63#[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    /// A field's `maxlength`, which caps the length whatever else says.
72    #[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
86/// The characters of a `[...]` set, minus look-alikes, or an error naming it.
87fn 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
101/// A value list in `passwordrules` (`lower, upper, [-_]`) as character sets.
102fn 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
122/// What a site's `passwordrules` says, read but not yet weighed: its lengths,
123/// its character sets, and its longest run of one character.
124struct SiteRules {
125    min: usize,
126    max: usize,
127    max_consecutive: Option<usize>,
128    required: Vec<String>,
129    allowed: String,
130}
131
132/// Reads a site's `passwordrules`.
133fn 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                // `required: lower, upper` means one character from either.
148                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            // Unknown rules are ignored, as browsers do.
158            _ => {}
159        }
160    }
161    Ok(site)
162}
163
164/// Whether a site's `passwordrules` can be read at all. Rules that can be read
165/// are the site's word on what it accepts, even when they leave no strong
166/// password; rules that can't say nothing a caller can follow.
167pub fn readable(passwordrules: &str) -> bool {
168    parse(passwordrules.trim()).is_ok()
169}
170
171/// Builds the rules from what was asked. A site's `passwordrules` replaces the
172/// default classes; `length` picks a length within its bounds.
173pub 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        // A field that can't hold the longest value it might get would cut it on use.
182        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
225/// How many bits of choice a value under these rules carries.
226pub 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
233/// A uniform index below `n` (at most 256), by rejection sampling.
234fn 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
262/// A new value under the rules. It lives only in the returned buffer.
263pub 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
292/// What the rules were, in a line an agent or the pane can show.
293pub 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;