1use std::collections::HashMap;
22use std::fmt;
23use std::sync::Mutex;
24
25use hmac::{Hmac, Mac};
26use sha2::Sha256;
27
28pub const TYPED_FROM_VAULT: &str = "[typed from the Vault: hidden]";
30
31pub const WINDOW_FROM: usize = 6;
33const MAX_PER_DOC: usize = 64;
35const P: u64 = (1 << 61) - 1;
37
38type Mac256 = Hmac<Sha256>;
39
40struct Typed {
41 chars: usize,
42 fingerprint: u64,
43 mac: [u8; 32],
44}
45
46struct Doc {
47 id: Option<String>,
49 typed: Vec<Typed>,
50}
51
52impl Doc {
53 fn is_document(&mut self, doc: Option<&str>) -> bool {
56 match (&self.id, doc) {
57 (_, None) => true,
58 (None, Some(id)) => {
59 self.id = Some(id.to_string());
60 true
61 }
62 (Some(have), Some(id)) => have == id,
63 }
64 }
65}
66
67fn of_document<'a>(docs: &'a mut HashMap<String, Doc>, block: &str, doc: Option<&str>) -> Option<&'a Doc> {
70 if !docs.get_mut(block)?.is_document(doc) {
71 docs.remove(block);
72 return None;
73 }
74 docs.get(block)
75}
76
77pub struct TypedSecrets {
79 key: [u8; 32],
80 base: u64,
81 docs: Mutex<HashMap<String, Doc>>,
82}
83
84impl fmt::Debug for TypedSecrets {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 f.debug_struct("TypedSecrets").finish_non_exhaustive()
87 }
88}
89
90fn mul_mod(a: u64, b: u64) -> u64 {
91 ((a as u128 * b as u128) % P as u128) as u64
92}
93
94impl TypedSecrets {
95 pub fn new(key: [u8; 32]) -> Self {
97 let mut mac = Mac256::new_from_slice(&key).expect("an HMAC takes a key of any length");
98 mac.update(b"fingerprint base");
99 let bytes = mac.finalize().into_bytes();
100 let base = u64::from_be_bytes(bytes[..8].try_into().expect("eight bytes")) % (P - 1000) + 500;
101 Self { key, base, docs: Mutex::new(HashMap::new()) }
102 }
103
104 fn fingerprint(&self, text: &[char]) -> u64 {
105 text.iter().fold(0u64, |h, c| (mul_mod(h, self.base) + *c as u64 + 1) % P)
106 }
107
108 fn mac(&self, text: &str) -> [u8; 32] {
109 let mut mac = Mac256::new_from_slice(&self.key).expect("an HMAC takes a key of any length");
110 mac.update(text.as_bytes());
111 mac.finalize().into_bytes().into()
112 }
113
114 pub fn note<'a>(&self, block: &str, doc: impl Into<Option<&'a str>>, value: &str) {
118 let doc: Option<&str> = doc.into();
119 let text: Vec<char> = value.chars().collect();
120 if text.is_empty() {
121 return;
122 }
123 let typed = Typed { chars: text.len(), fingerprint: self.fingerprint(&text), mac: self.mac(value) };
124 let mut docs = self.docs.lock().unwrap_or_else(|p| p.into_inner());
125 let entry = docs.entry(block.to_string()).or_insert_with(|| Doc { id: doc.map(str::to_string), typed: Vec::new() });
126 if !entry.is_document(doc) {
127 *entry = Doc { id: doc.map(str::to_string), typed: Vec::new() };
128 }
129 if entry.typed.iter().any(|t| t.mac == typed.mac) {
130 return;
131 }
132 if entry.typed.len() >= MAX_PER_DOC {
133 entry.typed.remove(0);
134 }
135 entry.typed.push(typed);
136 }
137
138 pub fn forget(&self, block: &str) {
140 self.docs.lock().unwrap_or_else(|p| p.into_inner()).remove(block);
141 }
142
143 pub fn typed_into(&self, block: &str, doc: Option<&str>) -> bool {
146 let mut docs = self.docs.lock().unwrap_or_else(|p| p.into_inner());
147 of_document(&mut docs, block, doc).is_some_and(|d| !d.typed.is_empty())
148 }
149
150 pub fn withhold(&self, block: &str, doc: Option<&str>, text: &str) -> Option<String> {
153 let typed: Vec<(usize, u64, [u8; 32])> = {
154 let mut docs = self.docs.lock().unwrap_or_else(|p| p.into_inner());
155 let Some(d) = of_document(&mut docs, block, doc) else { return None };
156 d.typed.iter().map(|t| (t.chars, t.fingerprint, t.mac)).collect()
157 };
158 if typed.is_empty() || text.is_empty() {
159 return None;
160 }
161 let chars: Vec<char> = text.chars().collect();
162 let mut hidden = vec![false; chars.len()];
163 let mut any = false;
164 let mut lengths: Vec<usize> = typed.iter().map(|t| t.0).collect();
165 lengths.sort_unstable();
166 lengths.dedup();
167 for len in lengths {
168 let wanted: Vec<&(usize, u64, [u8; 32])> = typed.iter().filter(|t| t.0 == len).collect();
169 if len < WINDOW_FROM {
170 let (start, end) = trimmed_range(&chars);
172 if end - start == len && self.confirm(&chars[start..end], &wanted) {
173 hidden[start..end].fill(true);
174 any = true;
175 }
176 continue;
177 }
178 if chars.len() < len {
179 continue;
180 }
181 let pow = (1..len).fold(1u64, |p, _| mul_mod(p, self.base));
183 let mut h = self.fingerprint(&chars[..len]);
184 let mut i = 0;
185 loop {
186 if wanted.iter().any(|t| t.1 == h) && self.confirm(&chars[i..i + len], &wanted) {
187 hidden[i..i + len].fill(true);
188 any = true;
189 }
190 if i + len >= chars.len() {
191 break;
192 }
193 let out = mul_mod((chars[i] as u64 + 1) % P, pow);
194 h = (mul_mod((h + P - out) % P, self.base) + chars[i + len] as u64 + 1) % P;
195 i += 1;
196 }
197 }
198 if !any {
199 return None;
200 }
201 let mut out = String::with_capacity(text.len());
202 let mut in_run = false;
203 for (c, h) in chars.iter().zip(&hidden) {
204 if *h {
205 if !in_run {
206 out.push_str(TYPED_FROM_VAULT);
207 in_run = true;
208 }
209 } else {
210 in_run = false;
211 out.push(*c);
212 }
213 }
214 Some(out)
215 }
216
217 pub fn withhold_json(&self, block: &str, doc: Option<&str>, value: &mut serde_json::Value) -> usize {
220 use serde_json::Value;
221 match value {
222 Value::String(s) => match self.withhold(block, doc, s) {
223 Some(shown) => {
224 *s = shown;
225 1
226 }
227 None => 0,
228 },
229 Value::Array(items) => items.iter_mut().map(|v| self.withhold_json(block, doc, v)).sum(),
230 Value::Object(fields) => fields.values_mut().map(|v| self.withhold_json(block, doc, v)).sum(),
231 _ => 0,
232 }
233 }
234
235 fn confirm(&self, window: &[char], wanted: &[&(usize, u64, [u8; 32])]) -> bool {
236 let text: String = window.iter().collect();
237 let mac = self.mac(&text);
238 wanted.iter().any(|t| crate::secret_eq::secret_eq(&t.2, &mac))
239 }
240}
241
242fn trimmed_range(chars: &[char]) -> (usize, usize) {
244 let start = chars.iter().position(|c| !c.is_whitespace()).unwrap_or(chars.len());
245 let end = chars.iter().rposition(|c| !c.is_whitespace()).map_or(start, |e| e + 1);
246 (start, end)
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252
253 const PASSWORD: &str = "Tr0ub4dor&3-sentinel";
254
255 fn secrets() -> TypedSecrets {
256 TypedSecrets::new([7u8; 32])
257 }
258
259 #[test]
260 fn a_typed_value_is_hidden_wherever_it_sits_in_a_text() {
261 let s = secrets();
262 s.note("pane-1", "doc-1", PASSWORD);
263 assert_eq!(s.withhold("pane-1", Some("doc-1"), PASSWORD).as_deref(), Some(TYPED_FROM_VAULT));
264 let said = s.withhold("pane-1", Some("doc-1"), &format!("your password is {PASSWORD}, keep it")).unwrap();
265 assert_eq!(said, format!("your password is {TYPED_FROM_VAULT}, keep it"));
266 assert_eq!(s.withhold("pane-1", Some("doc-1"), &format!("{PASSWORD} ")).unwrap(), format!("{TYPED_FROM_VAULT} "));
268 assert_eq!(s.withhold("pane-1", Some("doc-1"), &format!("{PASSWORD}/{PASSWORD}")).unwrap(), format!("{TYPED_FROM_VAULT}/{TYPED_FROM_VAULT}"));
269 assert_eq!(s.withhold("pane-1", Some("doc-1"), &format!("a{PASSWORD}")).unwrap(), format!("a{TYPED_FROM_VAULT}"));
270 }
271
272 #[test]
273 fn text_that_is_not_the_value_is_left_alone() {
274 let s = secrets();
275 s.note("pane-1", "doc-1", PASSWORD);
276 for text in ["", "hello", "Tr0ub4dor&3-sentinel".trim_end_matches('l'), "tr0ub4dor&3-sentinel", "Welcome back, alex"] {
277 assert_eq!(s.withhold("pane-1", Some("doc-1"), text), None, "{text:?}");
278 }
279 }
280
281 #[test]
282 fn a_short_value_is_matched_as_a_whole_text_only() {
283 let s = secrets();
284 s.note("pane-1", "doc-1", "4821");
285 assert_eq!(s.withhold("pane-1", Some("doc-1"), "4821").as_deref(), Some(TYPED_FROM_VAULT));
286 assert_eq!(s.withhold("pane-1", Some("doc-1"), " 4821 ").as_deref(), Some(format!(" {TYPED_FROM_VAULT} ").as_str()));
287 assert_eq!(s.withhold("pane-1", Some("doc-1"), "order 4821 shipped"), None, "inside a longer text a short value is not matched");
288 assert_eq!(s.withhold("pane-1", Some("doc-1"), "48210"), None);
289 s.note("pane-1", "doc-1", "5");
290 assert_eq!(s.withhold("pane-1", Some("doc-1"), "5").as_deref(), Some(TYPED_FROM_VAULT), "a one-digit code box");
291 assert_eq!(s.withhold("pane-1", Some("doc-1"), "5 items in the cart"), None);
292 }
293
294 #[test]
295 fn a_value_with_other_letters_and_languages_is_matched_by_its_characters() {
296 let s = secrets();
297 s.note("pane-1", "doc-1", "pässwörd-日本語-🔑");
298 assert_eq!(s.withhold("pane-1", Some("doc-1"), "x pässwörd-日本語-🔑 y").unwrap(), format!("x {TYPED_FROM_VAULT} y"));
299 assert_eq!(s.withhold("pane-1", Some("doc-1"), "x passwörd-日本語-🔑 y"), None);
300 }
301
302 #[test]
303 fn two_values_and_two_panes_are_kept_apart() {
304 let s = secrets();
305 s.note("pane-1", "doc-1", PASSWORD);
306 s.note("pane-1", "doc-1", "another-typed-value");
307 s.note("pane-2", "doc-9", "pane-two-value-77");
308 let both = s.withhold("pane-1", Some("doc-1"), &format!("{PASSWORD} and another-typed-value")).unwrap();
309 assert_eq!(both, format!("{TYPED_FROM_VAULT} and {TYPED_FROM_VAULT}"));
310 assert_eq!(s.withhold("pane-1", Some("doc-1"), "pane-two-value-77"), None, "another pane's value is not this pane's");
311 assert!(s.withhold("pane-2", Some("doc-9"), "pane-two-value-77").is_some());
312 }
313
314 #[test]
315 fn a_new_document_is_a_page_with_nothing_typed_in_it() {
316 let s = secrets();
317 s.note("pane-1", "doc-1", PASSWORD);
318 assert!(s.typed_into("pane-1", Some("doc-1")));
319 assert!(s.typed_into("pane-1", None), "a read that can't tell which document it is counts as the one typed in");
320 assert!(!s.typed_into("pane-1", Some("doc-2")));
322 assert_eq!(s.withhold("pane-1", Some("doc-2"), PASSWORD), None);
323 assert!(!s.typed_into("pane-1", Some("doc-1")), "and they do not come back");
324 s.note("pane-1", "doc-2", "second-document-value");
326 assert!(s.withhold("pane-1", Some("doc-2"), "second-document-value").is_some());
327 s.note("pane-1", "doc-3", "third-document-value");
328 assert_eq!(s.withhold("pane-1", Some("doc-3"), "second-document-value"), None);
329 s.forget("pane-1");
330 assert!(!s.typed_into("pane-1", None), "a closed pane keeps nothing");
331 }
332
333 #[test]
334 fn a_value_typed_while_the_document_could_not_be_read_is_kept_for_the_first_one_a_read_names() {
335 let s = secrets();
336 s.note("pane-1", None, PASSWORD);
337 assert!(s.typed_into("pane-1", None), "eval stays refused");
338 assert!(s.withhold("pane-1", None, PASSWORD).is_some());
339 assert!(s.typed_into("pane-1", Some("doc-1")));
341 assert!(s.withhold("pane-1", Some("doc-1"), PASSWORD).is_some());
342 assert!(!s.typed_into("pane-1", Some("doc-2")));
343 assert_eq!(s.withhold("pane-1", Some("doc-2"), PASSWORD), None);
344 }
345
346 #[test]
347 fn what_is_kept_is_a_keyed_digest_and_not_the_value() {
348 let one = TypedSecrets::new([1u8; 32]);
349 let other = TypedSecrets::new([2u8; 32]);
350 one.note("pane-1", "doc-1", PASSWORD);
351 other.note("pane-1", "doc-1", PASSWORD);
352 assert!(!format!("{one:?}").contains(PASSWORD) && !format!("{one:?}").contains("sentinel"));
353 let digest = |s: &TypedSecrets| s.docs.lock().unwrap().get("pane-1").unwrap().typed.iter().map(|t| (t.fingerprint, t.mac)).collect::<Vec<_>>();
354 assert_ne!(digest(&one), digest(&other), "another key gives another digest, so a short value can't be guessed without it");
355 let kept = one.docs.lock().unwrap();
356 let t = &kept.get("pane-1").unwrap().typed[0];
357 assert_eq!(t.chars, PASSWORD.chars().count(), "the length is kept beside it");
358 assert!(!t.mac.windows(8).any(|w| PASSWORD.as_bytes().windows(8).any(|v| v == w)));
359 }
360
361 #[test]
362 fn typing_the_same_value_again_keeps_one_digest_and_the_most_per_document_is_bounded() {
363 let s = secrets();
364 for _ in 0..3 {
365 s.note("pane-1", "doc-1", PASSWORD);
366 }
367 assert_eq!(s.docs.lock().unwrap().get("pane-1").unwrap().typed.len(), 1);
368 for n in 0..(MAX_PER_DOC + 10) {
369 s.note("pane-1", "doc-1", &format!("value-number-{n:04}"));
370 }
371 assert_eq!(s.docs.lock().unwrap().get("pane-1").unwrap().typed.len(), MAX_PER_DOC);
372 assert!(s.withhold("pane-1", Some("doc-1"), &format!("value-number-{:04}", MAX_PER_DOC + 9)).is_some(), "the newest are kept");
373 }
374
375 #[test]
376 fn the_rolling_fingerprint_agrees_with_the_one_made_whole_on_a_long_text() {
377 let s = secrets();
378 s.note("pane-1", "doc-1", "needle-in-a-haystack");
379 let text = format!("{}needle-in-a-haystack{}", "hay ".repeat(5000), " straw".repeat(3000));
380 let said = s.withhold("pane-1", Some("doc-1"), &text).unwrap();
381 assert_eq!(said.matches(TYPED_FROM_VAULT).count(), 1);
382 assert!(!said.contains("needle"));
383 assert_eq!(said.len(), text.len() - "needle-in-a-haystack".len() + TYPED_FROM_VAULT.len());
384 }
385
386 struct FakePage {
389 fields: Vec<(String, String, String)>, marked: Vec<String>,
391 }
392
393 impl FakePage {
394 fn type_into(&mut self, secrets: &TypedSecrets, name: &str, value: &str) {
395 let field = self.fields.iter_mut().find(|f| f.0 == name).unwrap();
396 field.2 = value.to_string();
397 self.marked.push(name.to_string());
398 secrets.note("pane-1", "doc-1", value);
399 }
400
401 fn page_script_runs(&mut self) {
404 self.marked.clear();
405 for f in self.fields.iter_mut() {
406 f.1 = "text".to_string();
407 }
408 let shown = self.fields.iter().find(|f| f.0 == "password").unwrap().2.clone();
409 self.fields.push(("heading".into(), "text".into(), format!("Welcome, your password is {shown}")));
410 self.fields.push(("status".into(), "text".into(), shown));
411 }
412
413 fn reads(&self) -> serde_json::Value {
415 let list = |_: &str| -> Vec<serde_json::Value> {
416 self.fields
417 .iter()
418 .map(|(name, kind, value)| {
419 let hidden = self.marked.contains(name);
420 serde_json::json!({ "name": name, "type": kind, "marked": hidden, "value": if hidden { "[hidden]" } else { value.as_str() } })
421 })
422 .collect()
423 };
424 serde_json::json!({ "snapshot": list("snapshot"), "find": { "matches": list("find") }, "readBack": { "after": { "value": self.fields[0].2 } } })
425 }
426 }
427
428 #[test]
429 fn g4_web_no_agent_script_runs_and_no_call_returns_the_field_value_even_after_a_type_switch() {
430 let s = secrets();
431 let mut page = FakePage {
432 fields: vec![("user".into(), "text".into(), String::new()), ("password".into(), "password".into(), String::new())],
433 marked: Vec::new(),
434 };
435 page.type_into(&s, "password", PASSWORD);
436 assert!(s.typed_into("pane-1", Some("doc-1")), "eval is refused while a Vault value was typed into the document");
438 page.page_script_runs();
439 assert!(page.marked.is_empty(), "the page took the mark off");
440 assert!(s.typed_into("pane-1", Some("doc-1")), "and the refusal does not depend on it");
441 let mut answer = page.reads();
442 assert!(answer.to_string().contains(PASSWORD), "the page's own copy is in what it would read back");
443 let changed = s.withhold_json("pane-1", Some("doc-1"), &mut answer);
444 assert!(changed >= 4, "the field, the heading, the status and the read-back: {changed}");
445 assert!(!answer.to_string().contains(PASSWORD) && !answer.to_string().contains("sentinel"), "{answer}");
446 assert!(answer.to_string().contains(TYPED_FROM_VAULT));
447 assert_eq!(answer["snapshot"][0]["name"], "user", "what is not the value is read as it was");
448 assert!(!s.typed_into("pane-1", Some("doc-2")));
450 }
451}