auberge 0.15.16

CLI tool for managing self-hosted infrastructure with Ansible
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use crate::ansible_assets::AnsibleAssets;
use crate::config::Config;
use crate::key_registry::KeyRegistry;
use crate::output;
use crate::playbook_meta::PlaybookMeta;
use crate::prompt::{Choice, select_item};
use clap::{Args, Subcommand};
use dialoguer::{Input, theme::ColorfulTheme};
use eyre::{Result, WrapErr};
use std::collections::HashSet;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

#[derive(Subcommand)]
pub enum ConfigCommands {
    #[command(
        visible_alias = "i",
        about = "Print a config.toml scaffold derived from the Key Registry"
    )]
    Init(InitArgs),
    #[command(visible_alias = "s", about = "Set a config value")]
    Set {
        #[arg(help = "Key name (e.g. admin_user_name)")]
        key: Option<String>,
        #[arg(help = "Value to set")]
        value: Option<String>,
    },
    #[command(visible_alias = "g", about = "Get a config value")]
    Get {
        #[arg(help = "Key name")]
        key: Option<String>,
        #[arg(
            long,
            help = "Execute !-prefixed command references and print the resolved value (may print secrets)"
        )]
        resolved: bool,
    },
    #[command(
        visible_alias = "l",
        about = "List all config keys (sensitive values redacted)"
    )]
    List,
    #[command(visible_alias = "rm", about = "Remove a key from config")]
    Remove {
        #[arg(help = "Key name")]
        key: Option<String>,
    },
    #[command(visible_alias = "e", about = "Open config in $EDITOR")]
    Edit,
    #[command(visible_alias = "p", about = "Print config file path")]
    Path,
}

#[derive(Args)]
pub struct InitArgs {
    #[arg(
        long,
        value_delimiter = ',',
        help = "Comma-separated playbook names; emit only their union of required keys"
    )]
    pub playbooks: Vec<String>,
    #[arg(
        short = 'o',
        long,
        help = "Write scaffold to FILE (refuses to overwrite without --force)"
    )]
    pub output: Option<PathBuf>,
    #[arg(short = 'f', long, help = "Overwrite the output file if it exists")]
    pub force: bool,
}

fn key_choice(prompt: &str) -> Choice {
    Choice::new("config key")
        .with_prompt(prompt)
        .resolved_by("the key as an argument")
}

fn select_key(config: &Config, prompt: &str) -> Result<String> {
    let keys = config.keys();
    if keys.is_empty() {
        eyre::bail!("No config keys found");
    }
    select_item(&keys, |s: &String| s.clone(), key_choice(prompt))
}

fn select_registry_key(registry: &KeyRegistry, prompt: &str) -> Result<String> {
    let keys = sorted_registry_keys(registry);
    if keys.is_empty() {
        eyre::bail!("Key Registry is empty");
    }
    let display = |k: &String| match registry.get(k) {
        Some(entry) if entry.secret => format!("{k} [secret]"),
        _ => k.clone(),
    };
    select_item(&keys, display, key_choice(prompt))
}

fn sorted_registry_keys(registry: &KeyRegistry) -> Vec<String> {
    let mut keys: Vec<String> = registry.iter().map(|(k, _)| k.clone()).collect();
    keys.sort();
    keys
}

fn resolve_key(key: Option<String>, config: &Config, prompt: &str) -> Result<String> {
    match key {
        Some(k) => Ok(k),
        None => select_key(config, prompt),
    }
}

pub fn run_config_init(args: InitArgs) -> Result<()> {
    let assets = AnsibleAssets::prepare()?;
    let registry = KeyRegistry::load(&assets.ansible_dir().join("keys.yml"))?;
    let scaffold = build_scaffold(&registry, &args.playbooks, &assets.playbooks_dir())?;

    match args.output {
        None => {
            print!("{scaffold}");
            Ok(())
        }
        Some(path) => write_scaffold(&path, &scaffold, args.force),
    }
}

fn build_scaffold(
    registry: &KeyRegistry,
    playbooks: &[String],
    playbooks_dir: &Path,
) -> Result<String> {
    if playbooks.is_empty() {
        return Ok(registry.scaffold());
    }
    let mut keys: HashSet<String> = HashSet::new();
    for playbook in playbooks {
        let meta_path = playbooks_dir.join(format!("{playbook}.meta.yml"));
        let meta = PlaybookMeta::load(&meta_path)
            .wrap_err_with(|| format!("Unknown playbook '{playbook}'"))?;
        keys.extend(meta.required_keys);
    }
    Ok(registry.scaffold_filtered(&keys))
}

fn write_scaffold(path: &Path, scaffold: &str, force: bool) -> Result<()> {
    if path.exists() && !force {
        eyre::bail!(
            "Refusing to overwrite {}; pass --force to override",
            path.display()
        );
    }
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
    {
        fs::create_dir_all(parent)
            .wrap_err_with(|| format!("Failed to create {}", parent.display()))?;
    }
    fs::write(path, scaffold).wrap_err_with(|| format!("Failed to write {}", path.display()))?;
    fs::set_permissions(path, fs::Permissions::from_mode(0o600))
        .wrap_err_with(|| format!("Failed to set permissions on {}", path.display()))?;
    output::success(&format!("Wrote scaffold to {}", path.display()));
    Ok(())
}

pub fn run_config_set(key: Option<String>, value: Option<String>) -> Result<()> {
    let mut config = Config::load()?;
    let key = match key {
        Some(k) => k,
        None => {
            let assets = AnsibleAssets::prepare()?;
            let registry = KeyRegistry::load(&assets.ansible_dir().join("keys.yml"))?;
            select_registry_key(&registry, "Select key to set")?
        }
    };
    let value = match value {
        Some(v) => v,
        None => {
            let current = config.get(&key).unwrap_or_default();
            Input::<String>::with_theme(&ColorfulTheme::default())
                .with_prompt(format!("Value for '{}'", key))
                .default(current)
                .allow_empty(true)
                .interact_text()?
        }
    };
    config.set(&key, &value)?;
    output::success(&format!("{} = {}", key, value));
    Ok(())
}

pub fn run_config_get(key: Option<String>, resolved: bool) -> Result<()> {
    let config = Config::load()?;
    let key = resolve_key(key, &config, "Select key to get")?;
    println!("{}", get_value(&config, &key, resolved)?);
    Ok(())
}

fn get_value(config: &Config, key: &str, resolved: bool) -> Result<String> {
    let value = if resolved {
        config.get_resolved(key)?
    } else {
        config.get(key)
    };
    value.ok_or_else(|| eyre::eyre!("Key '{}' not found", key))
}

pub fn run_config_list() -> Result<()> {
    let config = Config::load()?;
    for (key, value) in config.keys_redacted() {
        println!("{} = {}", key, value);
    }
    Ok(())
}

pub fn run_config_remove(key: Option<String>) -> Result<()> {
    let mut config = Config::load()?;
    let key = resolve_key(key, &config, "Select key to remove")?;
    if config.remove(&key)? {
        output::success(&format!("Removed '{}'", key));
    } else {
        eyre::bail!("Key '{}' not found", key);
    }
    Ok(())
}

pub fn run_config_edit() -> Result<()> {
    let path = Config::path()?;
    if !path.exists() {
        eyre::bail!(
            "Config not found at {}. Run `auberge config init --output {}` first.",
            path.display(),
            path.display()
        );
    }
    let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vi".to_string());
    std::process::Command::new(&editor)
        .arg(&path)
        .status()
        .map_err(|e| eyre::eyre!("Failed to open editor '{}': {}", editor, e))?;
    Ok(())
}

pub fn run_config_path() -> Result<()> {
    println!("{}", Config::path()?.display());
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn fixture_registry() -> (tempfile::TempDir, KeyRegistry) {
        let yaml = r#"
keys:
  admin_user_name:
    secret: false
    doc: "Admin username"
  domain:
    secret: false
    doc: "Primary domain"
  tailscale_authkey:
    secret: true
    doc: "Tailscale auth key"
  paperless_admin_password:
    secret: true
    doc: "Paperless admin password"
"#;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("keys.yml");
        fs::write(&path, yaml).unwrap();
        let registry = KeyRegistry::load(&path).unwrap();
        (dir, registry)
    }

    fn fixture_playbooks_dir(metas: &[(&str, &str)]) -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        for (name, body) in metas {
            fs::write(dir.path().join(format!("{name}.meta.yml")), body).unwrap();
        }
        dir
    }

    #[test]
    fn test_build_scaffold_without_playbooks_includes_all_keys() {
        let (_keys_dir, registry) = fixture_registry();
        let dir = fixture_playbooks_dir(&[]);
        let scaffold = build_scaffold(&registry, &[], dir.path()).unwrap();
        assert!(scaffold.contains("admin_user_name"));
        assert!(scaffold.contains("domain"));
        assert!(scaffold.contains("tailscale_authkey"));
        assert!(scaffold.contains("paperless_admin_password"));
    }

    #[test]
    fn test_build_scaffold_with_playbooks_emits_union_of_required_keys() {
        let (_keys_dir, registry) = fixture_registry();
        let dir = fixture_playbooks_dir(&[
            (
                "infra",
                "required_keys: [admin_user_name, tailscale_authkey]\n",
            ),
            ("apps", "required_keys: [admin_user_name, domain]\n"),
        ]);
        let scaffold = build_scaffold(
            &registry,
            &["infra".to_string(), "apps".to_string()],
            dir.path(),
        )
        .unwrap();
        assert!(scaffold.contains("admin_user_name"));
        assert!(scaffold.contains("domain"));
        assert!(scaffold.contains("tailscale_authkey"));
        assert!(!scaffold.contains("paperless_admin_password"));
    }

    #[test]
    fn test_build_scaffold_with_unknown_playbook_errors() {
        let (_keys_dir, registry) = fixture_registry();
        let dir = fixture_playbooks_dir(&[]);
        let err = build_scaffold(&registry, &["nope".to_string()], dir.path()).unwrap_err();
        assert!(err.to_string().contains("Unknown playbook 'nope'"));
    }

    #[test]
    fn test_build_scaffold_with_playbook_having_empty_required_keys_emits_empty() {
        let (_keys_dir, registry) = fixture_registry();
        let dir = fixture_playbooks_dir(&[("solo", "required_keys: []\n")]);
        let scaffold = build_scaffold(&registry, &["solo".to_string()], dir.path()).unwrap();
        assert!(scaffold.is_empty());
    }

    #[test]
    fn test_write_scaffold_creates_file_with_0600_permissions() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        write_scaffold(&path, "domain = \"\"\n", false).unwrap();
        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600);
    }

    #[test]
    fn test_write_scaffold_refuses_to_overwrite_without_force() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        fs::write(&path, "existing content").unwrap();
        let err = write_scaffold(&path, "new content", false).unwrap_err();
        assert!(err.to_string().contains("Refusing to overwrite"));
        assert_eq!(fs::read_to_string(&path).unwrap(), "existing content");
    }

    #[test]
    fn test_write_scaffold_overwrites_with_force() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        fs::write(&path, "existing").unwrap();
        write_scaffold(&path, "fresh", true).unwrap();
        assert_eq!(fs::read_to_string(&path).unwrap(), "fresh");
    }

    #[test]
    fn test_sorted_registry_keys_returns_all_keys_alphabetically() {
        let (_keys_dir, registry) = fixture_registry();
        let keys = sorted_registry_keys(&registry);
        assert_eq!(
            keys,
            vec![
                "admin_user_name",
                "domain",
                "paperless_admin_password",
                "tailscale_authkey",
            ]
        );
    }

    fn ref_config() -> Config {
        Config::from_toml_str(
            r#"
            domain = "example.com"
            restic_password = "!echo resolved_secret"
            padded = "!printf '  trimmed  '"
            escaped = "!!pa foo"
            broken = "!false"
            silent = "!true"
        "#,
        )
        .unwrap()
    }

    #[test]
    fn test_get_value_raw_literal() {
        assert_eq!(
            get_value(&ref_config(), "domain", false).unwrap(),
            "example.com"
        );
    }

    #[test]
    fn test_get_value_raw_ref_stays_raw() {
        assert_eq!(
            get_value(&ref_config(), "restic_password", false).unwrap(),
            "!echo resolved_secret"
        );
    }

    #[test]
    fn test_get_value_resolved_literal_is_identity() {
        assert_eq!(
            get_value(&ref_config(), "domain", true).unwrap(),
            "example.com"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_get_value_resolved_ref_runs_command() {
        assert_eq!(
            get_value(&ref_config(), "restic_password", true).unwrap(),
            "resolved_secret"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_get_value_resolved_trims_whitespace() {
        assert_eq!(get_value(&ref_config(), "padded", true).unwrap(), "trimmed");
    }

    #[cfg(unix)]
    #[test]
    fn test_get_value_resolved_escaped_bang_is_literal() {
        assert_eq!(
            get_value(&ref_config(), "escaped", true).unwrap(),
            "!pa foo"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_get_value_resolved_failing_command_errors() {
        let err = get_value(&ref_config(), "broken", true).unwrap_err();
        let chain = format!("{err:#}");
        assert!(chain.contains("Failed to resolve config key 'broken'"));
        assert!(chain.contains("Shell command failed"));
    }

    #[cfg(unix)]
    #[test]
    fn test_get_value_resolved_empty_output_errors() {
        let err = get_value(&ref_config(), "silent", true).unwrap_err();
        let chain = format!("{err:#}");
        assert!(chain.contains("Failed to resolve config key 'silent'"));
        assert!(chain.contains("empty output"));
    }

    #[test]
    fn test_get_value_missing_key_errors_in_both_modes() {
        for resolved in [false, true] {
            let err = get_value(&ref_config(), "nope", resolved).unwrap_err();
            assert!(err.to_string().contains("Key 'nope' not found"));
        }
    }

    #[test]
    fn test_write_scaffold_creates_parent_dirs() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("nested/sub/config.toml");
        write_scaffold(&path, "domain = \"\"\n", false).unwrap();
        assert!(path.exists());
    }
}