ryra-core 0.7.2

Core library for ryra: config, registry, and service generation logic
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
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! Auth bridge: artifacts that let an auth-enabled service talk to Caddy+Authelia.
//!
//! Services with `--auth` need to reach Authelia for OIDC. When Caddy is
//! handling HTTPS with a self-signed cert, the service container must trust
//! that cert and be able to resolve the auth provider's hostname to Caddy's
//! (dynamic) container IP.
//!
//! This module is a pure builder: it reads probe files under `/etc/ssl/certs`
//! and constructs [`Step::WriteFile`] entries for the caller to execute. It
//! performs no writes itself, so planning remains side-effect-free and
//! respects `--dry-run`.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use crate::Step;
use crate::capability::{Capability, find_installed_provider};
use crate::config::schema::Config;
use crate::error::{Error, Result};
use crate::generate::GeneratedFile;

/// System CA bundle locations probed in order. First hit wins.
const SYSTEM_CA_PATHS: &[&str] = &[
    "/etc/ssl/certs/ca-certificates.crt",
    "/etc/pki/tls/certs/ca-bundle.crt",
];

/// Quadlet + filesystem artifacts a caller should merge into the service's
/// generated unit and execute as part of the install plan.
pub struct AuthBridge {
    /// Extra `Volume=` entries for the service's `.container` unit.
    pub volumes: Vec<String>,
    /// Extra env vars for the service's `.env` file (CA trust for Python/Node).
    pub env: BTreeMap<String, String>,
    /// Extra `ExecStartPre=` entries for the service's `.container` unit.
    pub exec_start_pre: Vec<String>,
    /// Files to write before the service starts (CA bundle + helper scripts).
    pub steps: Vec<Step>,
}

/// Inputs to [`build`].
pub struct AuthBridgeParams<'a> {
    pub service_name: &'a str,
    /// Capabilities declared by the currently-installing service. The
    /// bridge skips itself when the caller is the OIDC provider or the
    /// reverse proxy — those services don't consume themselves.
    pub service_provides: &'a [Capability],
    pub enable_auth: bool,
    pub config: &'a Config,
    /// Snapshot of installed services. Production callers pass
    /// [`crate::list_installed`]; tests construct synthetic data so
    /// they can drive the function without writing real quadlet files.
    pub installed: &'a [crate::config::schema::InstalledService],
    /// Absolute path to the service's data dir (`~/.local/share/services/<name>`).
    pub service_data: &'a Path,
}

/// Build auth-bridge artifacts for a service. Returns `Ok(None)` when the
/// bridge does not apply — the caller isn't using auth, the service is
/// authelia/caddy itself, authelia/Caddy aren't yet installed, or
/// authelia's URL isn't a Caddy-local hostname (`*.internal`).
///
/// Dispatch is driven by authelia's URL: when the hostname is `*.internal`,
/// Caddy is the internal TLS terminator and we build the existing bridge
/// (CA bundle, alias-to-Caddy, host-resolve script). Other URLs (Tailscale
/// FQDNs, public domains) imply the user is running their own internal
/// trust path, which ryra doesn't construct yet — bridge returns None and
/// runtime OIDC across containers is the user's responsibility for now.
pub fn build(params: &AuthBridgeParams<'_>) -> Result<Option<AuthBridge>> {
    if !params.enable_auth {
        return Ok(None);
    }
    // The bridge wires consumers to providers — providers themselves
    // (the OIDC IdP, the reverse proxy) don't need it.
    if params.service_provides.contains(&Capability::OidcProvider)
        || params.service_provides.contains(&Capability::ReverseProxy)
    {
        return Ok(None);
    }
    let Some(authelia) = find_installed_provider(params.installed, Capability::OidcProvider) else {
        return Ok(None);
    };
    // Bridge applies only when the OIDC provider is reachable via a
    // Caddy-fronted *.internal hostname. Other exposures (Tailscale serve,
    // user's external proxy on a public domain) mean another trust path
    // is in play and ryra doesn't have matching client-side plumbing yet.
    if !matches!(authelia.exposure, crate::Exposure::Internal { .. }) {
        return Ok(None);
    }
    if find_installed_provider(params.installed, Capability::ReverseProxy).is_none() {
        return Ok(None);
    }

    let ryra_dir: PathBuf = params
        .service_data
        .parent()
        .ok_or_else(|| Error::Bundle("service data dir has no parent directory".into()))?
        .to_path_buf();

    let merged_bundle = params.service_data.join("ca-bundle.crt");
    let refresh_ca_script = params.service_data.join("refresh-ca-bundle.sh");
    let auth_host_script = params.service_data.join("resolve-auth-host.sh");
    let auth_hosts = params.service_data.join("auth-hosts.txt");

    let mut volumes = Vec::new();
    let mut env = BTreeMap::new();
    let mut exec_start_pre = Vec::new();
    let mut steps = Vec::new();

    // --- CA bundle: system CAs + caddy's self-signed CA (if already present) ---
    //
    // Reading from /etc/ssl/certs is a read-only probe. If no system bundle is
    // found, we start with an empty string — the refresh-ca-bundle.sh hook
    // rebuilds it each start. If caddy's CA isn't on disk yet (caddy is being
    // installed alongside), refresh-ca-bundle.sh will pick it up at first
    // start. Either way, the placeholder is safe.
    let ca_cert_host = ryra_dir.join("caddy-root-ca.crt");
    let mut bundle = String::new();
    for sys_path in SYSTEM_CA_PATHS {
        if let Ok(content) = std::fs::read_to_string(sys_path) {
            bundle = content;
            break;
        }
    }
    if let Ok(caddy_ca) = std::fs::read_to_string(&ca_cert_host) {
        bundle.push_str("\n# services-caddy-ca\n");
        bundle.push_str(&caddy_ca);
    }
    steps.push(Step::WriteFile(GeneratedFile {
        path: merged_bundle.clone(),
        content: bundle,
    }));
    volumes.push(format!(
        "{}:/etc/ssl/certs/ca-certificates.crt:ro,z",
        merged_bundle.display()
    ));
    // Python (requests/certifi) and Node don't honour the system CA store —
    // they need explicit env vars.
    for var in ["REQUESTS_CA_BUNDLE", "SSL_CERT_FILE", "NODE_EXTRA_CA_CERTS"] {
        env.insert(var.into(), "/etc/ssl/certs/ca-certificates.crt".into());
    }

    // --- refresh-ca-bundle.sh: rebuild bundle at each service start ---
    let refresh_script = render_refresh_ca_script(&ryra_dir, params.service_data);
    steps.push(Step::WriteFile(GeneratedFile {
        path: refresh_ca_script.clone(),
        content: refresh_script,
    }));
    exec_start_pre.push(format!("-/bin/bash {}", refresh_ca_script.display()));

    // --- resolve-auth-host.sh: dynamic /etc/hosts for auth domain ---
    //
    // The auth provider's hostname (typically an ICANN `.internal` address)
    // isn't resolvable via normal DNS, so we write a small hosts file at
    // service-start time mapping it to caddy's current container IP and
    // bind-mount that over /etc/hosts.
    if let Some(auth_url) = authelia.exposure.url()
        && let Ok(parsed) = url::Url::parse(auth_url)
        && let Some(host) = parsed.host_str()
    {
        let resolve_script = render_resolve_auth_host_script(params.service_data, host);
        steps.push(Step::WriteFile(GeneratedFile {
            path: auth_host_script.clone(),
            content: resolve_script,
        }));
        steps.push(Step::WriteFile(GeneratedFile {
            path: auth_hosts.clone(),
            content: format!("127.0.0.1 {host}\n"),
        }));
        exec_start_pre.push(format!("-/bin/bash {}", auth_host_script.display()));
        volumes.push(format!("{}:/etc/hosts:z", auth_hosts.display()));
    }

    Ok(Some(AuthBridge {
        volumes,
        env,
        exec_start_pre,
        steps,
    }))
}

fn render_refresh_ca_script(ryra_dir: &Path, service_data: &Path) -> String {
    format!(
        "#!/bin/bash\n\
         CADDY_CA=\"{ryra_dir}/caddy-root-ca.crt\"\n\
         MERGED=\"{service_data}/ca-bundle.crt\"\n\
         [ -f \"$CADDY_CA\" ] || exit 0\n\
         for f in /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt; do\n\
           if [ -f \"$f\" ]; then cp \"$f\" \"$MERGED\"; break; fi\n\
         done\n\
         cat \"$CADDY_CA\" >> \"$MERGED\" 2>/dev/null || true\n\
         exit 0\n",
        ryra_dir = ryra_dir.display(),
        service_data = service_data.display(),
    )
}

fn render_resolve_auth_host_script(service_data: &Path, host: &str) -> String {
    // `timeout 5` guards against a wedged podman socket: this runs in
    // ExecStartPre, and without the guard a hung podman blocks service
    // startup indefinitely. On timeout we fall through to 127.0.0.1 —
    // OIDC won't work, but the service comes up instead of hanging.
    format!(
        "#!/bin/bash\n\
         # Resolve caddy's current IP for the auth domain\n\
         HOSTS=\"{service_data}/auth-hosts.txt\"\n\
         CADDY_IP=$(timeout 5 podman inspect caddy --format '{{{{range .NetworkSettings.Networks}}}}{{{{.IPAddress}}}} {{{{end}}}}' 2>/dev/null | awk '{{print $1}}')\n\
         if [ -n \"$CADDY_IP\" ]; then\n\
           echo \"$CADDY_IP {host}\" > \"$HOSTS\"\n\
         else\n\
           echo \"127.0.0.1 {host}\" > \"$HOSTS\"\n\
         fi\n\
         exit 0\n",
        service_data = service_data.display(),
        host = host,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::schema::{AuthCredentials, InstalledService};
    use std::collections::BTreeMap;

    type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;

    /// Capability list a known-by-name service in these tests provides.
    /// Used to populate both `InstalledService::provides` and
    /// `AuthBridgeParams::service_provides` without depending on the
    /// default registry being cloned in tempdirs.
    fn provides_for(name: &str) -> &'static [Capability] {
        match name {
            "authelia" => &[Capability::OidcProvider, Capability::ForwardAuthProvider],
            "caddy" => &[Capability::ReverseProxy],
            _ => &[],
        }
    }

    fn installed(name: &str, url: Option<&str>) -> InstalledService {
        let exposure = match url {
            Some(u) => crate::Exposure::from_url(u),
            None => crate::Exposure::Loopback,
        };
        InstalledService {
            name: name.into(),
            version: "0.1.0".into(),
            repo: "default".into(),
            ports: BTreeMap::new(),
            auth_kind: None,
            exposure,
            provides: provides_for(name).to_vec(),
            installed: true,
        }
    }

    /// Build a (Config, installed-list) pair so tests can drive `build()`
    /// without writing real quadlet files. The `services` list is now
    /// passed alongside `config`, not embedded in it.
    fn fixture(
        services: Vec<InstalledService>,
        auth: Option<AuthCredentials>,
    ) -> (Config, Vec<InstalledService>) {
        let cfg = Config {
            auth,
            ..Config::default()
        };
        (cfg, services)
    }

    fn write_paths(bridge: &AuthBridge) -> Vec<&Path> {
        bridge
            .steps
            .iter()
            .filter_map(|s| match s {
                Step::WriteFile(f) => Some(f.path.as_path()),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn returns_none_when_auth_disabled() -> TestResult {
        let tmp = tempfile::tempdir()?;
        let (cfg, installed) = fixture(
            vec![installed("authelia", Some("https://auth.internal"))],
            None,
        );
        let out = build(&AuthBridgeParams {
            service_name: "forgejo",
            service_provides: provides_for("forgejo"),
            enable_auth: false,
            config: &cfg,
            installed: &installed,
            service_data: tmp.path(),
        })?;
        assert!(out.is_none());
        Ok(())
    }

    #[test]
    fn returns_none_when_authelia_not_installed() -> TestResult {
        let tmp = tempfile::tempdir()?;
        let (cfg, installed) = fixture(vec![installed("caddy", None)], None);
        let out = build(&AuthBridgeParams {
            service_name: "forgejo",
            service_provides: provides_for("forgejo"),
            enable_auth: true,
            config: &cfg,
            installed: &installed,
            service_data: tmp.path(),
        })?;
        assert!(out.is_none());
        Ok(())
    }

    #[test]
    fn returns_none_when_caddy_not_installed() -> TestResult {
        let tmp = tempfile::tempdir()?;
        let (cfg, installed) = fixture(
            vec![installed("authelia", Some("https://auth.internal"))],
            None,
        );
        let out = build(&AuthBridgeParams {
            service_name: "forgejo",
            service_provides: provides_for("forgejo"),
            enable_auth: true,
            config: &cfg,
            installed: &installed,
            service_data: tmp.path(),
        })?;
        assert!(out.is_none());
        Ok(())
    }

    #[test]
    fn returns_none_for_authelia_itself() -> TestResult {
        let tmp = tempfile::tempdir()?;
        let (cfg, installed) = fixture(
            vec![
                installed("authelia", Some("https://auth.internal")),
                installed("caddy", None),
            ],
            None,
        );
        let out = build(&AuthBridgeParams {
            service_name: "authelia",
            service_provides: provides_for("authelia"),
            enable_auth: true,
            config: &cfg,
            installed: &installed,
            service_data: tmp.path(),
        })?;
        assert!(out.is_none());
        Ok(())
    }

    #[test]
    fn returns_none_for_non_internal_authelia_url() -> TestResult {
        // Authelia at a non-`*.internal` URL means another trust path is
        // in play (Tailscale serve, user's external proxy). ryra doesn't
        // construct that bridge — runtime OIDC across containers is the
        // user's responsibility for non-Caddy deployments.
        let tmp = tempfile::tempdir()?;
        let (cfg, installed) = fixture(
            vec![
                installed("authelia", Some("https://auth.test.local")),
                installed("caddy", None),
            ],
            None,
        );
        let out = build(&AuthBridgeParams {
            service_name: "forgejo",
            service_provides: provides_for("forgejo"),
            enable_auth: true,
            config: &cfg,
            installed: &installed,
            service_data: tmp.path(),
        })?;
        assert!(out.is_none());
        Ok(())
    }

    #[test]
    fn returns_none_for_authelia_url_without_host() -> TestResult {
        // Defensive: a URL that fails to parse or lacks a host shouldn't
        // crash the builder — it should bail cleanly.
        let tmp = tempfile::tempdir()?;
        let (cfg, installed) = fixture(
            vec![
                installed("authelia", Some("not-a-url")),
                installed("caddy", None),
            ],
            None,
        );
        let out = build(&AuthBridgeParams {
            service_name: "forgejo",
            service_provides: provides_for("forgejo"),
            enable_auth: true,
            config: &cfg,
            installed: &installed,
            service_data: tmp.path(),
        })?;
        assert!(out.is_none());
        Ok(())
    }

    #[test]
    fn returns_none_for_caddy_itself() -> TestResult {
        let tmp = tempfile::tempdir()?;
        let (cfg, installed) = fixture(
            vec![
                installed("authelia", Some("https://auth.internal")),
                installed("caddy", None),
            ],
            None,
        );
        let out = build(&AuthBridgeParams {
            service_name: "caddy",
            service_provides: provides_for("caddy"),
            enable_auth: true,
            config: &cfg,
            installed: &installed,
            service_data: tmp.path(),
        })?;
        assert!(out.is_none());
        Ok(())
    }

    #[test]
    fn build_does_not_write_to_service_data() -> TestResult {
        // The whole point of this refactor: a pure planning call must not
        // touch the service's data dir.
        let tmp = tempfile::tempdir()?;
        let service_data = tmp.path().join("forgejo");
        std::fs::create_dir_all(&service_data)?;

        let (cfg, installed) = fixture(
            vec![
                installed("authelia", Some("https://auth.internal")),
                installed("caddy", None),
            ],
            None,
        );
        let out = build(&AuthBridgeParams {
            service_name: "forgejo",
            service_provides: provides_for("forgejo"),
            enable_auth: true,
            config: &cfg,
            installed: &installed,
            service_data: &service_data,
        })?;
        assert!(out.is_some());

        let entries: Vec<_> = std::fs::read_dir(&service_data)?.collect();
        assert!(
            entries.is_empty(),
            "build() must not write to service_data, found: {entries:?}"
        );
        Ok(())
    }

    fn build_forgejo_bridge(service_data: &Path, authelia_url: Option<&str>) -> Result<AuthBridge> {
        let (cfg, installed) = fixture(
            vec![
                installed("authelia", authelia_url),
                installed("caddy", None),
            ],
            None,
        );
        build(&AuthBridgeParams {
            service_name: "forgejo",
            service_provides: provides_for("forgejo"),
            enable_auth: true,
            config: &cfg,
            installed: &installed,
            service_data,
        })?
        .ok_or_else(|| {
            Error::Bundle(
                "auth bridge unexpectedly returned None for forgejo + authelia + caddy".into(),
            )
        })
    }

    #[test]
    fn emits_expected_write_file_steps() -> TestResult {
        let tmp = tempfile::tempdir()?;
        let service_data = tmp.path().join("forgejo");
        let bridge = build_forgejo_bridge(&service_data, Some("https://auth.internal"))?;

        let paths = write_paths(&bridge);
        assert!(paths.contains(&service_data.join("ca-bundle.crt").as_path()));
        assert!(paths.contains(&service_data.join("refresh-ca-bundle.sh").as_path()));
        assert!(paths.contains(&service_data.join("resolve-auth-host.sh").as_path()));
        assert!(paths.contains(&service_data.join("auth-hosts.txt").as_path()));
        Ok(())
    }

    #[test]
    fn returns_none_when_authelia_has_no_url() -> TestResult {
        // Bridge dispatch reads authelia's URL hostname; without one, ryra
        // can't tell if the deployment is Caddy-local or something else, so
        // it bails rather than guessing.
        let tmp = tempfile::tempdir()?;
        let (cfg, installed) = fixture(
            vec![installed("authelia", None), installed("caddy", None)],
            None,
        );
        let out = build(&AuthBridgeParams {
            service_name: "forgejo",
            service_provides: provides_for("forgejo"),
            enable_auth: true,
            config: &cfg,
            installed: &installed,
            service_data: tmp.path(),
        })?;
        assert!(out.is_none());
        Ok(())
    }

    #[test]
    fn emits_ca_trust_volume_and_env() -> TestResult {
        let tmp = tempfile::tempdir()?;
        let service_data = tmp.path().join("forgejo");
        let bridge = build_forgejo_bridge(&service_data, Some("https://auth.internal"))?;

        let bundle_mount = format!(
            "{}:/etc/ssl/certs/ca-certificates.crt:ro,z",
            service_data.join("ca-bundle.crt").display()
        );
        assert!(bridge.volumes.contains(&bundle_mount));
        assert_eq!(
            bridge.env.get("REQUESTS_CA_BUNDLE").map(String::as_str),
            Some("/etc/ssl/certs/ca-certificates.crt")
        );
        assert_eq!(
            bridge.env.get("SSL_CERT_FILE").map(String::as_str),
            Some("/etc/ssl/certs/ca-certificates.crt")
        );
        assert_eq!(
            bridge.env.get("NODE_EXTRA_CA_CERTS").map(String::as_str),
            Some("/etc/ssl/certs/ca-certificates.crt")
        );
        Ok(())
    }

    #[test]
    fn auth_hosts_contains_authelia_hostname() -> TestResult {
        let tmp = tempfile::tempdir()?;
        let service_data = tmp.path().join("forgejo");
        // *.internal is the bridge's domain — non-internal URLs fall
        // outside Caddy-local dispatch and don't get a bridge.
        let bridge = build_forgejo_bridge(&service_data, Some("https://auth.internal"))?;

        let hosts_step = bridge
            .steps
            .iter()
            .find_map(|s| match s {
                Step::WriteFile(f) if f.path == service_data.join("auth-hosts.txt") => Some(f),
                _ => None,
            })
            .ok_or("auth-hosts.txt step missing")?;
        assert_eq!(hosts_step.content, "127.0.0.1 auth.internal\n");
        Ok(())
    }

    #[test]
    fn exec_start_pre_references_emitted_scripts() -> TestResult {
        let tmp = tempfile::tempdir()?;
        let service_data = tmp.path().join("forgejo");
        let bridge = build_forgejo_bridge(&service_data, Some("https://auth.internal"))?;

        let refresh = format!(
            "-/bin/bash {}",
            service_data.join("refresh-ca-bundle.sh").display()
        );
        let resolve = format!(
            "-/bin/bash {}",
            service_data.join("resolve-auth-host.sh").display()
        );
        assert!(bridge.exec_start_pre.contains(&refresh));
        assert!(bridge.exec_start_pre.contains(&resolve));
        Ok(())
    }
}