oth_rvault 0.4.0

Partial Ansible Vault encoder and decoder
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use std::sync::{Arc, Mutex};
use std::time::Duration;

use inquire::{InquireError, Select, ui::RenderConfig};

const BOLD: &str = "\x1b[1m";
const BOLD_CYAN: &str = "\x1b[1;36m";
const RESET: &str = "\x1b[0m";

use crate::{
    typedetect::{detect_format, FileFormat},
    types::TypedValue,
    vaultfunc,
};

const SUBNODE_PREFIX: &str = "__subnode__\n";

struct Entry {
    /// "/" separated path shown in the fuzzy UI
    display: String,
    /// raw vault-encrypted string value
    vault_str: String,
}

struct ClipSession {
    clipboard: arboard::Clipboard,
    /// Monotonically increasing copy counter; timer threads compare against this
    /// to avoid clearing a value that was already overwritten by a later copy.
    generation: Arc<Mutex<u64>>,
    timeout_secs: u64,
    password: String,
    format: FileFormat,
    /// Set to true when the user selects [ Quit ] at any level.
    quit: bool,
    color: bool,
}

/// Interactive clipboard picker over all vault-encrypted values in `input`.
///
/// - Fuzzy-searches all encrypted paths (displayed as `/`-separated)
/// - Selecting a sub-node blob opens a second fuzzy picker over its fields
/// - Esc at any level goes up; Esc at top level exits and clears the clipboard
/// - Each copy starts a background timer that clears the clipboard after
///   `timeout_secs` seconds (0 = no automatic clearing)
pub fn clip(
    input: &str,
    password: &str,
    timeout_secs: u64,
    color: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    if !color {
        inquire::set_global_render_config(RenderConfig::empty());
    }
    let format = detect_format(input)?;
    if format == FileFormat::Vault {
        return Err("cannot clip from a raw vault-encrypted file (level-0)".into());
    }
    let content = std::fs::read_to_string(input)
        .map_err(|e| format!("error reading '{}': {}", input, e))?;

    let mut entries = Vec::new();
    match format {
        FileFormat::Json => {
            let root: serde_json::Value = serde_json::from_str(&content)
                .map_err(|e| format!("error parsing JSON from '{}': {}", input, e))?;
            collect_json(&root, "", &mut entries);
        }
        FileFormat::Yaml => {
            let root: serde_yaml::Value = serde_yaml::from_str(&content)
                .map_err(|e| format!("error parsing YAML from '{}': {}", input, e))?;
            collect_yaml(&root, "", &mut entries);
        }
        FileFormat::Vault => unreachable!(),
    }
    entries.sort_by(|a, b| a.display.cmp(&b.display));

    if entries.is_empty() {
        println!("No encrypted values found in '{}'.", input);
        return Ok(());
    }

    let clipboard = arboard::Clipboard::new()
        .map_err(|e| format!("failed to open clipboard: {}", e))?;

    let mut session = ClipSession {
        clipboard,
        generation: Arc::new(Mutex::new(0)),
        timeout_secs,
        password: password.to_string(),
        format,
        quit: false,
        color,
    };

    session.run(&entries)?;
    session.clear();
    println!("  Clipboard cleared.");
    Ok(())
}

impl ClipSession {
    fn run(&mut self, entries: &[Entry]) -> Result<(), Box<dyn std::error::Error>> {
        const QUIT: &str = "[ Quit ]";
        let mut options: Vec<String> = entries.iter().map(|e| e.display.clone()).collect();
        options.insert(0, QUIT.to_string());

        loop {
            let selected = match Select::new("Select entry (Esc or 'q' to quit):", options.clone()).prompt() {
                Ok(s) => s,
                Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => break,
                Err(e) => return Err(e.into()),
            };

            if selected == QUIT {
                break;
            }

            let entry = entries.iter().find(|e| e.display == selected).unwrap();

            // Strip any leading whitespace before the vault prefix (YAML block scalars)
            let vault_str = match entry.vault_str.find("$ANSIBLE_VAULT;") {
                Some(idx) => &entry.vault_str[idx..],
                None => entry.vault_str.as_str(),
            };

            let decrypted = match vaultfunc::decrypt(vault_str, &self.password) {
                Ok((TypedValue::String(s), _)) => s,
                Ok((typed, _)) => typed_to_string(&typed),
                Err(e) => {
                    eprintln!("decryption failed for '{}': {}", selected, e);
                    continue;
                }
            };

            if let Some(inner) = decrypted.strip_prefix(SUBNODE_PREFIX) {
                match self.format {
                    FileFormat::Json => match serde_json::from_str::<serde_json::Value>(inner) {
                        Ok(val) => self.field_loop_json(&val)?,
                        Err(e) => eprintln!("failed to parse sub-node '{}': {}", selected, e),
                    },
                    FileFormat::Yaml => match serde_yaml::from_str::<serde_yaml::Value>(inner) {
                        Ok(val) => self.field_loop_yaml(&val)?,
                        Err(e) => eprintln!("failed to parse sub-node '{}': {}", selected, e),
                    },
                    FileFormat::Vault => unreachable!(),
                }
            } else {
                self.copy(&decrypted, &selected)?;
            }
            if self.quit {
                break;
            }
        }
        Ok(())
    }

    fn field_loop_json(
        &mut self,
        val: &serde_json::Value,
    ) -> Result<(), Box<dyn std::error::Error>> {
        const QUIT: &str = "[ Quit ]";
        let map = match val.as_object() {
            Some(m) => m,
            None => return Ok(()),
        };
        let mut fields: Vec<String> = map.keys().cloned().collect();
        if fields.is_empty() {
            return Ok(());
        }
        fields.insert(0, QUIT.to_string());

        loop {
            let selected = match Select::new("Select field (Esc to go back):", fields.clone()).prompt() {
                Ok(f) => f,
                Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => {
                    return Ok(())
                }
                Err(e) => return Err(e.into()),
            };

            if selected == QUIT {
                self.quit = true;
                return Ok(());
            }

            let child = &val[&selected];
            if child.is_object() {
                self.field_loop_json(child)?;
            } else {
                let copy_val = self.json_value_to_string(child);
                self.copy(&copy_val, &selected)?;
            }
            if self.quit {
                return Ok(());
            }
        }
    }

    fn field_loop_yaml(
        &mut self,
        val: &serde_yaml::Value,
    ) -> Result<(), Box<dyn std::error::Error>> {
        const QUIT: &str = "[ Quit ]";
        let map = match val.as_mapping() {
            Some(m) => m,
            None => return Ok(()),
        };

        let mut fields: Vec<String> = map
            .keys()
            .filter_map(|k| match k {
                serde_yaml::Value::String(s) => Some(s.clone()),
                serde_yaml::Value::Number(n) => Some(n.to_string()),
                serde_yaml::Value::Bool(b) => Some(b.to_string()),
                _ => None,
            })
            .collect();
        if fields.is_empty() {
            return Ok(());
        }
        fields.insert(0, QUIT.to_string());

        loop {
            let selected = match Select::new("Select field (Esc to go back):", fields.clone()).prompt() {
                Ok(f) => f,
                Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => {
                    return Ok(())
                }
                Err(e) => return Err(e.into()),
            };

            if selected == QUIT {
                self.quit = true;
                return Ok(());
            }

            // Find the value by matching the display name back to the YAML key
            let child = map.iter().find(|(k, _)| match k {
                serde_yaml::Value::String(s) => s == &selected,
                serde_yaml::Value::Number(n) => n.to_string() == selected,
                serde_yaml::Value::Bool(b) => b.to_string() == selected,
                _ => false,
            });

            match child {
                None => eprintln!("field '{}' not found", selected),
                Some((_, v)) if v.is_mapping() => self.field_loop_yaml(v)?,
                Some((_, v)) => {
                    let copy_val = self.yaml_value_to_string(v);
                    self.copy(&copy_val, &selected)?;
                }
            }
            if self.quit {
                return Ok(());
            }
        }
    }

    /// Convert a JSON value to a string suitable for the clipboard.
    /// Vault-encrypted strings within the value are decrypted transparently.
    fn json_value_to_string(&self, val: &serde_json::Value) -> String {
        match val {
            serde_json::Value::String(s) => {
                if let Some(idx) = s.find("$ANSIBLE_VAULT;") {
                    if let Ok((typed, _)) = vaultfunc::decrypt(&s[idx..], &self.password) {
                        return typed_to_string(&typed);
                    }
                }
                s.clone()
            }
            serde_json::Value::Bool(b) => b.to_string(),
            serde_json::Value::Number(n) => n.to_string(),
            serde_json::Value::Null => String::new(),
            other => serde_json::to_string(other).unwrap_or_default(),
        }
    }

    /// Convert a YAML value to a string suitable for the clipboard.
    /// Vault-encrypted strings within the value are decrypted transparently.
    fn yaml_value_to_string(&self, val: &serde_yaml::Value) -> String {
        match val {
            serde_yaml::Value::String(s) => {
                if let Some(idx) = s.find("$ANSIBLE_VAULT;") {
                    if let Ok((typed, _)) = vaultfunc::decrypt(&s[idx..], &self.password) {
                        return typed_to_string(&typed);
                    }
                }
                s.clone()
            }
            serde_yaml::Value::Bool(b) => b.to_string(),
            serde_yaml::Value::Number(n) => n.to_string(),
            serde_yaml::Value::Null => String::new(),
            serde_yaml::Value::Tagged(t) => self.yaml_value_to_string(&t.value),
            other => serde_yaml::to_string(other).unwrap_or_default(),
        }
    }

    fn copy(&mut self, value: &str, label: &str) -> Result<(), Box<dyn std::error::Error>> {
        self.clipboard
            .set_text(value)
            .map_err(|e| format!("clipboard error: {}", e))?;

        if self.timeout_secs > 0 {
            // Increment generation so any earlier timer thread knows not to clear.
            let current_gen = {
                let mut g = self.generation.lock().unwrap();
                *g += 1;
                *g
            };
            let gen_arc = self.generation.clone();
            let secs = self.timeout_secs;
            std::thread::spawn(move || {
                std::thread::sleep(Duration::from_secs(secs));
                let g = gen_arc.lock().unwrap();
                if *g == current_gen {
                    drop(g); // release lock before creating a new Clipboard
                    if let Ok(mut cb) = arboard::Clipboard::new() {
                        let _ = cb.set_text("");
                        // Give X11 time to serve the empty content before the
                        // selection server thread is stopped on drop.
                        std::thread::sleep(Duration::from_millis(150));
                    }
                }
            });
            let emph = if self.color { BOLD_CYAN } else { BOLD };
            println!("\n  {emph}✓  Copied '{label}' to clipboard.{RESET}  (clears in {secs}s)\n");
        } else {
            let emph = if self.color { BOLD_CYAN } else { BOLD };
            println!("\n  {emph}✓  Copied '{label}' to clipboard.{RESET}\n");
        }
        Ok(())
    }

    fn clear(&mut self) {
        // Invalidate any pending timer
        *self.generation.lock().unwrap() = u64::MAX;
        let _ = self.clipboard.set_text("");
        // Give X11 time to serve the empty content before the Clipboard is dropped.
        std::thread::sleep(Duration::from_millis(150));
    }
}

fn typed_to_string(typed: &TypedValue) -> String {
    match typed {
        TypedValue::String(s) => s.clone(),
        TypedValue::Integer(i) => i.to_string(),
        TypedValue::Bool(b) => b.to_string(),
        TypedValue::Number(f) => f.to_string(),
        TypedValue::Null => String::new(),
    }
}

fn collect_json(val: &serde_json::Value, path: &str, out: &mut Vec<Entry>) {
    match val {
        serde_json::Value::String(s) if s.contains("$ANSIBLE_VAULT;") => {
            out.push(Entry {
                display: path.replace('.', "/"),
                vault_str: s.clone(),
            });
        }
        serde_json::Value::Object(map) => {
            for (key, child) in map {
                let new_path = if path.is_empty() {
                    key.clone()
                } else {
                    format!("{}.{}", path, key)
                };
                collect_json(child, &new_path, out);
            }
        }
        serde_json::Value::Array(arr) => {
            for item in arr {
                collect_json(item, path, out);
            }
        }
        _ => {}
    }
}

fn collect_yaml(val: &serde_yaml::Value, path: &str, out: &mut Vec<Entry>) {
    match val {
        serde_yaml::Value::String(s) if s.contains("$ANSIBLE_VAULT;") => {
            out.push(Entry {
                display: path.replace('.', "/"),
                vault_str: s.clone(),
            });
        }
        serde_yaml::Value::Tagged(tagged) => {
            if let serde_yaml::Value::String(s) = &tagged.value {
                if s.contains("$ANSIBLE_VAULT;") {
                    out.push(Entry {
                        display: path.replace('.', "/"),
                        vault_str: s.clone(),
                    });
                }
            }
        }
        serde_yaml::Value::Mapping(map) => {
            for (key, child) in map {
                let key_str = match key {
                    serde_yaml::Value::String(s) => s.clone(),
                    serde_yaml::Value::Number(n) => n.to_string(),
                    serde_yaml::Value::Bool(b) => b.to_string(),
                    _ => continue,
                };
                let new_path = if path.is_empty() {
                    key_str
                } else {
                    format!("{}.{}", path, key_str)
                };
                collect_yaml(child, &new_path, out);
            }
        }
        serde_yaml::Value::Sequence(seq) => {
            for item in seq {
                collect_yaml(item, path, out);
            }
        }
        _ => {}
    }
}