auberge 0.14.2

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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
use crate::ansible_assets::AnsibleAssets;
use crate::config::Config;
use crate::playbook_meta::PlaybookMeta;
use cloudflare::endpoints::dns::dns::{
    CreateDnsRecord, CreateDnsRecordParams, DeleteDnsRecord, DnsContent, DnsRecord, ListDnsRecords,
    UpdateDnsRecord, UpdateDnsRecordParams,
};
use cloudflare::endpoints::zones::zone::{ListZones, ListZonesParams};
use cloudflare::framework::Environment;
use cloudflare::framework::auth::Credentials;
use cloudflare::framework::client::ClientConfig;
use cloudflare::framework::client::async_api::Client;
use eyre::Result;
use std::collections::HashMap;

pub struct MigrationResult {
    pub subdomain: String,
    pub old_ip: String,
    pub new_ip: String,
    pub success: bool,
}

pub struct DnsStatus {
    pub domain: String,
    pub configured_subdomains: Vec<String>,
    pub active_records: Vec<DnsRecord>,
    pub missing_subdomains: Vec<String>,
}

pub struct DnsService {
    client: Client,
    domain: String,
    default_ttl: u32,
    zone_id: String,
}

#[derive(Debug)]
pub struct SubdomainEntry {
    pub subdomain: String,
    pub ip_override: Option<String>,
}

#[derive(Default)]
pub struct DiscoveredSubdomains {
    pub public: HashMap<String, SubdomainEntry>,
    pub tailnet_only: HashMap<String, SubdomainEntry>,
}

/// Walks the playbooks directory once and returns App subdomains partitioned
/// by ADR-0003 publication channel:
/// - `public`     — Cloudflare A records (subject to per-app `_tailscale_ip` override)
/// - `tailnet_only` — Blocky `customDNS` map (no Cloudflare A record ever)
///
/// Metas with an empty/missing `subdomain` are silently dropped; the integrity
/// test in this module (`test_every_app_meta_has_subdomain_unless_tailnet_only_or_excluded`)
/// enforces that App metas declare a non-empty `subdomain`, so the silent drop
/// is unreachable for in-tree metas.
pub fn discover_all_subdomains() -> DiscoveredSubdomains {
    let assets = match AnsibleAssets::prepare() {
        Ok(a) => a,
        Err(_) => return DiscoveredSubdomains::default(),
    };
    let entries = match std::fs::read_dir(assets.playbooks_dir()) {
        Ok(e) => e,
        Err(_) => return DiscoveredSubdomains::default(),
    };

    let config = Config::load().ok();
    let mut public: HashMap<String, SubdomainEntry> = HashMap::new();
    let mut tailnet_only: HashMap<String, SubdomainEntry> = HashMap::new();

    for entry in entries.flatten() {
        let path = entry.path();
        let Some(file_name) = path.file_name().and_then(|s| s.to_str()) else {
            continue;
        };
        let Some(app) = file_name.strip_suffix(".meta.yml") else {
            continue;
        };
        let Ok(meta) = PlaybookMeta::load(&path) else {
            continue;
        };
        let config_override = config.as_ref().and_then(|c| {
            let key = format!("{}_subdomain", app);
            c.get(&key).filter(|v| !v.is_empty())
        });
        let Some(subdomain) =
            config_override.or_else(|| meta.subdomain.clone().filter(|s| !s.is_empty()))
        else {
            continue;
        };

        if meta.tailnet_only {
            tailnet_only.insert(
                app.to_string(),
                SubdomainEntry {
                    subdomain,
                    ip_override: None,
                },
            );
        } else {
            let ip_override = config.as_ref().and_then(|c| {
                let key = format!("{}_tailscale_ip", app);
                c.get(&key).filter(|v| !v.is_empty())
            });
            public.insert(
                app.to_string(),
                SubdomainEntry {
                    subdomain,
                    ip_override,
                },
            );
        }
    }

    DiscoveredSubdomains {
        public,
        tailnet_only,
    }
}

/// Public-App subdomains only. Thin wrapper for callers that don't need the
/// tailnet-only half (status, interactive subdomain pickers, etc.).
pub fn discover_subdomains() -> HashMap<String, SubdomainEntry> {
    discover_all_subdomains().public
}

/// Returns `true` if `ip` is in the Tailscale CGNAT range (100.64.0.0/10).
pub fn is_tailscale_ip(ip: &str) -> bool {
    let Ok(addr) = ip.parse::<std::net::Ipv4Addr>() else {
        return false;
    };
    let octets = addr.octets();
    octets[0] == 100 && (64..=127).contains(&octets[1])
}

impl DnsService {
    pub async fn new_with_production(_production_override: Option<bool>) -> Result<Self> {
        let config = Config::load()?;

        let api_token = config
            .get_resolved("cloudflare_dns_api_token")?
            .filter(|v| !v.is_empty())
            .ok_or_else(|| eyre::eyre!("cloudflare_dns_api_token not set in config"))?;

        let credentials = Credentials::UserAuthToken { token: api_token };

        let client = Client::new(
            credentials,
            ClientConfig::default(),
            Environment::Production,
        )?;

        let domain = config.domain();
        let default_ttl = config.ttl();
        let zone_id = Self::discover_zone_id(&client, &domain).await?;

        Ok(Self {
            client,
            domain,
            default_ttl,
            zone_id,
        })
    }

    async fn discover_zone_id(client: &Client, zone_name: &str) -> Result<String> {
        let zones = client
            .request(&ListZones {
                params: ListZonesParams {
                    name: Some(zone_name.to_string()),
                    ..Default::default()
                },
            })
            .await
            .map_err(|e| eyre::eyre!("Failed to list zones: {}", e))?;

        let mut results = zones.result;
        match results.len() {
            0 => eyre::bail!("Zone not found: {}", zone_name),
            1 => Ok(results.remove(0).id),
            _ => {
                let ids: Vec<String> = results.iter().map(|z| z.id.clone()).collect();
                eyre::bail!(
                    "Multiple zones found for '{}': {:?}. Scope your API token to a single zone.",
                    zone_name,
                    ids
                )
            }
        }
    }

    pub fn domain(&self) -> &str {
        &self.domain
    }

    pub async fn list_records(&self) -> Result<Vec<DnsRecord>> {
        let response = self
            .client
            .request(&ListDnsRecords {
                zone_identifier: &self.zone_id,
                params: Default::default(),
            })
            .await
            .map_err(|e| eyre::eyre!("Failed to list DNS records: {}", e))?;

        Ok(response.result)
    }

    async fn find_record(&self, subdomain: &str) -> Result<Option<DnsRecord>> {
        let records = self.list_records().await?;
        let full_name = format!("{}.{}", subdomain, self.domain);

        Ok(records
            .into_iter()
            .find(|r| r.name == full_name && matches!(r.content, DnsContent::A { .. })))
    }

    pub async fn set_a_record(&self, subdomain: &str, ip: &str) -> Result<()> {
        let existing = self.find_record(subdomain).await?;
        let full_name = format!("{}.{}", subdomain, self.domain);
        let ip_addr = ip
            .parse()
            .map_err(|e| eyre::eyre!("Invalid IP address: {}", e))?;

        if let Some(record) = existing {
            self.client
                .request(&UpdateDnsRecord {
                    zone_identifier: &self.zone_id,
                    identifier: &record.id,
                    params: UpdateDnsRecordParams {
                        name: &full_name,
                        content: DnsContent::A { content: ip_addr },
                        ttl: Some(self.default_ttl),
                        proxied: Some(false),
                    },
                })
                .await
                .map_err(|e| eyre::eyre!("Failed to update DNS record: {}", e))?;
        } else {
            self.client
                .request(&CreateDnsRecord {
                    zone_identifier: &self.zone_id,
                    params: CreateDnsRecordParams {
                        name: &full_name,
                        content: DnsContent::A { content: ip_addr },
                        ttl: Some(self.default_ttl),
                        proxied: Some(false),
                        priority: None,
                    },
                })
                .await
                .map_err(|e| eyre::eyre!("Failed to create DNS record: {}", e))?;
        }

        Ok(())
    }

    /// Deletes the A record for `subdomain`.  Returns `true` when the record
    /// was found and deleted, `false` when it was already absent (idempotent).
    pub async fn delete_a_record(&self, subdomain: &str) -> Result<bool> {
        let existing = self.find_record(subdomain).await?;
        match existing {
            None => Ok(false),
            Some(record) => {
                self.client
                    .request(&DeleteDnsRecord {
                        zone_identifier: &self.zone_id,
                        identifier: &record.id,
                    })
                    .await
                    .map_err(|e| eyre::eyre!("Failed to delete DNS record: {}", e))?;
                Ok(true)
            }
        }
    }

    pub async fn migrate_all(&self, new_ip: &str, dry_run: bool) -> Result<Vec<MigrationResult>> {
        let existing = self.list_records().await?;
        let mut results = Vec::new();

        let domain_suffix = format!(".{}", self.domain);
        let a_records: Vec<&DnsRecord> = existing
            .iter()
            .filter(|r| matches!(r.content, DnsContent::A { .. }))
            .filter(|r| r.name.ends_with(&domain_suffix) && r.name != self.domain)
            .collect();

        if dry_run {
            for record in a_records {
                if let DnsContent::A { content: old_ip } = record.content {
                    if is_tailscale_ip(&old_ip.to_string()) {
                        eprintln!("Skipping tailnet-only record: {}", record.name);
                        continue;
                    }
                    let subdomain = record
                        .name
                        .strip_suffix(&domain_suffix)
                        .expect("pre-filtered to end with domain suffix")
                        .to_string();

                    results.push(MigrationResult {
                        subdomain,
                        old_ip: old_ip.to_string(),
                        new_ip: new_ip.to_string(),
                        success: true,
                    });
                }
            }
            return Ok(results);
        }

        for record in a_records {
            if let DnsContent::A { content: old_ip } = record.content {
                if is_tailscale_ip(&old_ip.to_string()) {
                    eprintln!("Skipping tailnet-only record: {}", record.name);
                    continue;
                }
                let subdomain = record
                    .name
                    .strip_suffix(&domain_suffix)
                    .expect("pre-filtered to end with domain suffix");

                let success = self.set_a_record(subdomain, new_ip).await.is_ok();

                results.push(MigrationResult {
                    subdomain: subdomain.to_string(),
                    old_ip: old_ip.to_string(),
                    new_ip: new_ip.to_string(),
                    success,
                });
            }
        }

        Ok(results)
    }

    pub async fn status(&self) -> Result<DnsStatus> {
        let active_records = self.list_records().await?;

        let discovered = discover_subdomains();
        let configured_subdomains: Vec<String> =
            discovered.values().map(|e| e.subdomain.clone()).collect();

        let domain_suffix = format!(".{}", self.domain);
        let active_names: std::collections::HashSet<String> = active_records
            .iter()
            .filter(|r| matches!(r.content, DnsContent::A { .. }))
            .map(|r| {
                r.name
                    .strip_suffix(&domain_suffix)
                    .unwrap_or(&r.name)
                    .to_string()
            })
            .collect();

        let missing_subdomains: Vec<String> = configured_subdomains
            .iter()
            .filter(|s| !active_names.contains(*s))
            .cloned()
            .collect();

        Ok(DnsStatus {
            domain: self.domain.clone(),
            configured_subdomains,
            active_records,
            missing_subdomains,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeSet;
    use std::path::PathBuf;

    #[test]
    fn test_is_tailscale_ip_true() {
        assert!(is_tailscale_ip("100.64.0.1"));
        assert!(is_tailscale_ip("100.100.200.1"));
        assert!(is_tailscale_ip("100.127.255.255"));
    }

    #[test]
    fn test_is_tailscale_ip_false() {
        assert!(!is_tailscale_ip("100.128.0.1"));
        assert!(!is_tailscale_ip("192.168.1.1"));
        assert!(!is_tailscale_ip("203.0.113.10"));
        assert!(!is_tailscale_ip("not-an-ip"));
    }

    fn playbooks_dir() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("ansible")
            .join("playbooks")
    }

    // Metas for orchestrating/infrastructure playbooks that don't represent
    // an App with DNS publication. Anything else must declare `subdomain`.
    const NON_APP_PLAYBOOK_METAS: &[&str] = &[
        "apps",
        "bootstrap",
        "calibre",
        "hardening",
        "hermes",
        "infrastructure",
        "remove-radicale",
        "vibecoder",
    ];

    #[test]
    fn test_every_app_meta_has_subdomain_unless_tailnet_only_or_excluded() {
        let dir = playbooks_dir();
        let read = std::fs::read_dir(&dir).expect("playbooks dir");
        for entry in read.flatten() {
            let path = entry.path();
            let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
                continue;
            };
            let Some(stem) = name.strip_suffix(".meta.yml") else {
                continue;
            };
            let meta =
                PlaybookMeta::load(&path).unwrap_or_else(|e| panic!("failed to parse {name}: {e}"));

            if meta.tailnet_only {
                assert!(
                    meta.subdomain.as_deref().is_some_and(|s| !s.is_empty()),
                    "{name}: tailnet_only metas must declare subdomain"
                );
                continue;
            }

            if NON_APP_PLAYBOOK_METAS.contains(&stem) {
                continue;
            }

            assert!(
                meta.subdomain.as_deref().is_some_and(|s| !s.is_empty()),
                "{name}: non-tailnet-only App meta must declare subdomain. \
                 If this Playbook Meta does not represent an App, add its stem \
                 to NON_APP_PLAYBOOK_METAS in src/services/dns.rs tests."
            );
        }
    }

    #[test]
    fn test_discover_subdomains_returns_expected_public_apps() {
        // discover_subdomains -> Config::load() reads XDG_CONFIG_HOME, which
        // other tests in this binary mutate. Hold TEST_LOCK to serialize.
        let _guard = crate::output::TEST_LOCK.lock().unwrap();
        let discovered = discover_subdomains();
        let got: BTreeSet<String> = discovered.keys().cloned().collect();
        let expected: BTreeSet<String> = [
            "baikal",
            "blocky",
            "colporteur",
            "freshrss",
            "gokapi",
            "grimmory",
            "headscale",
            "navidrome",
            "yourls",
        ]
        .iter()
        .map(|s| (*s).to_string())
        .collect();
        assert_eq!(got, expected);
    }

    #[test]
    fn test_discover_subdomains_excludes_tailnet_only_apps() {
        let _guard = crate::output::TEST_LOCK.lock().unwrap();
        let discovered = discover_subdomains();
        for tailnet_only in ["bichon", "cockpit", "paperless"] {
            assert!(
                !discovered.contains_key(tailnet_only),
                "tailnet-only app {tailnet_only} must not appear in Public-App discovery"
            );
        }
    }

    #[test]
    fn test_discover_subdomains_uses_meta_subdomain_value() {
        use crate::output::EnvVarGuard;
        let _guard = crate::output::TEST_LOCK.lock().unwrap();
        // Pin XDG_CONFIG_HOME at an empty dir so no <app>_subdomain
        // override exists and meta defaults are the sole signal.
        let dir = tempfile::tempdir().unwrap();
        let _xdg = EnvVarGuard::set("XDG_CONFIG_HOME", dir.path());
        let discovered = discover_subdomains();
        assert_eq!(discovered["headscale"].subdomain, "hs");
        assert_eq!(discovered["freshrss"].subdomain, "freshrss");
    }

    #[test]
    fn test_discover_subdomains_honors_app_subdomain_config_override() {
        use crate::output::EnvVarGuard;
        let _guard = crate::output::TEST_LOCK.lock().unwrap();

        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("auberge/config.toml");
        std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();
        std::fs::write(
            &config_path,
            "domain = \"example.com\"\nfreshrss_subdomain = \"news\"\n",
        )
        .unwrap();
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&config_path, std::fs::Permissions::from_mode(0o600)).unwrap();

        let _xdg = EnvVarGuard::set("XDG_CONFIG_HOME", dir.path());

        let discovered = discover_subdomains();
        assert_eq!(
            discovered["freshrss"].subdomain, "news",
            "freshrss_subdomain in config must override meta default"
        );
        assert_eq!(
            discovered["baikal"].subdomain, "baikal",
            "apps without a config override keep their meta default"
        );
    }
}