Skip to main content

ryra_core/config/
schema.rs

1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Serialize};
4
5use crate::capability::Capability;
6use crate::registry::service_def::AuthKind;
7
8/// Top-level preferences.toml configuration.
9#[derive(Debug, Clone, Default, Serialize, Deserialize)]
10pub struct Config {
11    /// Ryra version that last wrote this config. Written on every save,
12    /// checked on load to reject configs from newer versions.
13    #[serde(default, skip_serializing_if = "Option::is_none")]
14    pub version: Option<String>,
15    /// Legacy — reads old configs with [host], never written back.
16    #[serde(default, skip_serializing)]
17    pub host: HostConfig,
18    /// Admin email used as the default for services that need an admin account.
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub admin_email: Option<String>,
21    pub smtp: Option<SmtpCredentials>,
22    pub auth: Option<AuthCredentials>,
23    /// Tailscale auth credential + cached tailnet metadata. Set on first
24    /// `--tailscale` install; reused for every subsequent service so the
25    /// user only ever pastes their key once.
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub tailscale: Option<TailscaleConfig>,
28    #[serde(default, skip_serializing_if = "Vec::is_empty")]
29    pub registries: Vec<RegistryEntry>,
30    /// Backup repository + encryption password. Set by
31    /// `ryra backup configure`; consumed by every `ryra backup run`,
32    /// `ryra backup restore`, and `ryra backup list` invocation.
33    /// `None` means the user hasn't configured backups yet — every
34    /// backup command refuses with [`Error::BackupRepoNotConfigured`].
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub backup: Option<BackupSettings>,
37}
38
39impl Config {
40    /// True iff this config carries credentials/tokens that must be
41    /// protected from casual disclosure: SMTP user/password, Tailscale
42    /// admin API token, and anything similar added in the future.
43    /// Callers use this to fire a one-time warning the first time
44    /// preferences.toml acquires sensitive content.
45    pub fn has_secrets(&self) -> bool {
46        self.smtp.is_some() || self.tailscale.is_some() || self.backup.is_some()
47    }
48}
49
50// --- Backup ---
51
52/// Top-level backup repository configuration. Persisted in
53/// preferences.toml under `[backup]`. Storing the password here (vs.
54/// requiring it on every invocation) is the only ergonomic way to run
55/// `ryra backup run` from a systemd timer — but the file is already
56/// 0600 and contains comparably-sensitive SMTP and Tailscale tokens,
57/// so the threat model doesn't change.
58///
59/// Losing this password = losing access to every snapshot. Surfaced
60/// once by `ryra backup configure` with a print-and-confirm step.
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct BackupSettings {
63    /// The restic encryption password. Forms the only key that can
64    /// decrypt the repo's content.
65    pub password: String,
66    /// Storage backend the snapshots are pushed to. Typed enum
67    /// (instead of a raw restic URL string + opaque env map) so
68    /// invalid combinations of credentials are unrepresentable and
69    /// the CLI can prompt for the right fields per backend.
70    pub backend: BackupBackend,
71}
72
73/// Storage backend for the backup repository. The variants map to
74/// restic's supported backends; each carries exactly the fields restic
75/// needs to authenticate, no more.
76#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
77#[serde(tag = "kind", rename_all = "lowercase")]
78pub enum BackupBackend {
79    /// Any S3-compatible object store: MinIO, AWS S3, Backblaze B2 via
80    /// S3 API, Cloudflare R2, Wasabi. The `endpoint` is the full URL
81    /// to the API (e.g. `http://127.0.0.1:9000` for a local MinIO,
82    /// `https://s3.us-east-1.amazonaws.com` for AWS).
83    S3 {
84        endpoint: String,
85        bucket: String,
86        access_key_id: String,
87        secret_access_key: String,
88        /// Optional path prefix inside the bucket. Lets one bucket
89        /// host multiple ryra installs (one per host or per user) by
90        /// scoping each to a sub-prefix.
91        #[serde(default, skip_serializing_if = "Option::is_none")]
92        prefix: Option<String>,
93    },
94    /// A local filesystem path. Primarily a testing affordance — point
95    /// at a tempdir and round-trip backup/restore without spinning up
96    /// MinIO. Production users should prefer the S3 variant pointed at
97    /// off-machine storage; a "local" backup gives no protection from
98    /// disk failure.
99    Local { path: std::path::PathBuf },
100}
101
102impl BackupBackend {
103    /// The `--repo` argument passed to the restic binary. restic uses
104    /// a single colon-prefixed string to identify the backend ("s3:",
105    /// "rest:", a raw path for local). This builder centralises the
106    /// formatting so callers never hand-construct it.
107    pub fn restic_repo(&self) -> String {
108        match self {
109            BackupBackend::S3 {
110                endpoint,
111                bucket,
112                prefix,
113                ..
114            } => {
115                let stripped = endpoint
116                    .trim_end_matches('/')
117                    .trim_start_matches("http://")
118                    .trim_start_matches("https://");
119                // Keep the scheme: restic distinguishes
120                // s3:http://… (plain HTTP) from s3:https://….
121                let scheme = if endpoint.starts_with("http://") {
122                    "http://"
123                } else {
124                    "https://"
125                };
126                let base = format!("s3:{scheme}{stripped}/{bucket}");
127                match prefix.as_deref().map(|p| p.trim_matches('/')) {
128                    Some(p) if !p.is_empty() => format!("{base}/{p}"),
129                    _ => base,
130                }
131            }
132            BackupBackend::Local { path } => path.display().to_string(),
133        }
134    }
135
136    /// Environment variables restic needs to authenticate to this
137    /// backend. Returned as a vec of `(key, value)` pairs so the
138    /// caller can decide whether to set them on a `Command` or via
139    /// `std::env::set_var` (the former is preferred — keeps the
140    /// process env clean and per-invocation).
141    pub fn env(&self) -> Vec<(&'static str, String)> {
142        match self {
143            BackupBackend::S3 {
144                access_key_id,
145                secret_access_key,
146                ..
147            } => vec![
148                ("AWS_ACCESS_KEY_ID", access_key_id.clone()),
149                ("AWS_SECRET_ACCESS_KEY", secret_access_key.clone()),
150            ],
151            BackupBackend::Local { .. } => vec![],
152        }
153    }
154}
155
156#[derive(Debug, Clone, Default, Serialize, Deserialize)]
157pub struct HostConfig {
158    #[serde(default)]
159    pub domain: Option<String>,
160}
161
162// --- SMTP ---
163
164#[derive(Debug, Clone, Serialize, Deserialize)]
165pub struct SmtpCredentials {
166    pub host: String,
167    pub port: u16,
168    pub username: String,
169    pub password: String,
170    pub from: String,
171    #[serde(default)]
172    pub security: SmtpSecurity,
173}
174
175/// SMTP transport security mode.
176#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
177#[serde(rename_all = "snake_case")]
178pub enum SmtpSecurity {
179    #[default]
180    Starttls,
181    ForceTls,
182    Off,
183}
184
185impl SmtpSecurity {
186    pub fn as_str(&self) -> &'static str {
187        match self {
188            SmtpSecurity::Starttls => "starttls",
189            SmtpSecurity::ForceTls => "force_tls",
190            SmtpSecurity::Off => "off",
191        }
192    }
193}
194
195// --- Auth ---
196
197#[derive(Debug, Clone, Serialize, Deserialize)]
198#[serde(tag = "provider", rename_all = "lowercase")]
199pub enum AuthCredentials {
200    /// Managed Authelia instance installed via ryra.
201    Authelia { url: String, port: u16 },
202    /// External OIDC provider managed by the user.
203    External { url: String },
204}
205
206impl AuthCredentials {
207    pub fn url(&self) -> &str {
208        match self {
209            AuthCredentials::Authelia { url, .. } => url,
210            AuthCredentials::External { url } => url,
211        }
212    }
213
214    pub fn provider_name(&self) -> &str {
215        match self {
216            AuthCredentials::Authelia { .. } => "authelia",
217            AuthCredentials::External { .. } => "external",
218        }
219    }
220
221    pub fn port(&self) -> Option<u16> {
222        match self {
223            AuthCredentials::Authelia { port, .. } => Some(*port),
224            AuthCredentials::External { .. } => None,
225        }
226    }
227}
228
229// --- Caddy local domain ---
230
231/// Hardcoded Caddy domain. Caddy in ryra exists for local HTTPS during
232/// development and OIDC testing — services are reachable at
233/// `<service>.internal:<caddy_https_port>` from the host. There's no
234/// global "TLS provider" config; the URL on each `InstalledService`
235/// is the source of truth for how that service is reached, and ryra
236/// inspects URL hostnames (`*.internal` → Caddy local) when behavior
237/// has to dispatch on it (auth bridge, /etc/hosts writes).
238pub const CADDY_LOCAL_DOMAIN: &str = "internal";
239
240// --- Tailscale ---
241
242/// Tag ryra applies to the host advertising services. Required by
243/// Tailscale Services (service hosts must be tagged), declared in the
244/// tailnet ACL by `ensure_setup`. Single per-tailnet tag — every ryra
245/// host shares it.
246pub const HOST_TAG: &str = "tag:ryra-host";
247
248/// Tag ryra applies to defined services. Used by autoApprovers in the
249/// ACL so every ryra-defined service auto-approves its host without
250/// manual admin clicks.
251pub const SERVICE_TAG: &str = "tag:ryra-service";
252
253/// Admin API token + cached tailnet metadata for Tailscale Services.
254/// Stored in preferences.toml under `[tailscale]` so the user pastes the
255/// admin token once and every subsequent `--tailscale` install reuses
256/// it for service definition + ACL setup. Same file mode (0600) as
257/// SMTP/auth credentials.
258#[derive(Debug, Clone, Serialize, Deserialize)]
259pub struct TailscaleConfig {
260    /// Admin API token (`tskey-api-…`). Used to manage Tailscale
261    /// Services: define services, update ACL with auto-approval, tag
262    /// the host. Stored locally because every `--tailscale` install
263    /// (and every `--tailscale` removal) calls the API.
264    pub admin_api_key: String,
265    /// Cached tailnet suffix (e.g. `cobbler-tuna.ts.net`). Resolved
266    /// lazily from `tailscale status --json` and remembered so we don't
267    /// re-shell out on every install.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub tailnet: Option<String>,
270}
271
272// --- Registry entry ---
273
274#[derive(Debug, Clone, Serialize, Deserialize)]
275pub struct RegistryEntry {
276    pub name: String,
277    pub url: String,
278}
279
280// --- Installed service record ---
281
282/// In-memory view of a single installed service. Reconstructed by
283/// `ryra_core::list_installed()` from the quadlet directory's
284/// `# Service-*` headers + the per-service `.env` file. No longer
285/// persisted to `preferences.toml` — the on-disk artifacts are the
286/// source of truth.
287#[derive(Debug, Clone)]
288pub struct InstalledService {
289    pub name: String,
290    pub version: String,
291    pub repo: String,
292    /// All allocated host ports by name (e.g., "http" → 8080, "tcp" → 5432).
293    pub ports: BTreeMap<String, u16>,
294    /// The auth kind the user chose when installing this service, if any.
295    pub auth_kind: Option<AuthKind>,
296    /// How this service is reachable.
297    pub exposure: crate::Exposure,
298    /// Capabilities this service provides — the persisted snapshot of
299    /// `service.toml`'s `[capabilities] provides` taken at install time.
300    /// Empty for services whose service.toml didn't declare any (i.e.
301    /// most application services, all of which are pure consumers).
302    pub provides: Vec<Capability>,
303    /// Whether the service was fully installed. Always `true` when
304    /// reconstructed from the quadlet scan (a marker'd `.container`
305    /// only exists for completed installs).
306    pub installed: bool,
307}
308
309impl Config {
310    /// Validate structural invariants after deserialization.
311    pub fn validate(&self) -> Result<(), String> {
312        // Future invariants land here. Per-service uniqueness is no
313        // longer a Config concern: the source of truth for installed
314        // services is the quadlet directory, where each service has a
315        // single `.container` by definition.
316        let _ = self;
317        Ok(())
318    }
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324
325    #[test]
326    fn tailscale_config_round_trip() {
327        let cfg = Config {
328            tailscale: Some(TailscaleConfig {
329                admin_api_key: "tskey-api-XXXX".into(),
330                tailnet: Some("cobbler-tuna.ts.net".into()),
331            }),
332            ..Config::default()
333        };
334        let serialized = toml::to_string(&cfg).unwrap();
335        assert!(serialized.contains("[tailscale]"));
336        assert!(serialized.contains("admin_api_key = \"tskey-api-XXXX\""));
337        assert!(serialized.contains("tailnet = \"cobbler-tuna.ts.net\""));
338        let parsed: Config = toml::from_str(&serialized).unwrap();
339        let ts = parsed.tailscale.expect("[tailscale] should round-trip");
340        assert_eq!(ts.admin_api_key, "tskey-api-XXXX");
341        assert_eq!(ts.tailnet.as_deref(), Some("cobbler-tuna.ts.net"));
342    }
343
344    #[test]
345    fn tailscale_config_tailnet_optional() {
346        // Cached tailnet should be skipped on serialize when None — the
347        // first install resolves it lazily and writes it back; serialize
348        // shouldn't emit `tailnet = ""` for fresh configs.
349        let cfg = Config {
350            tailscale: Some(TailscaleConfig {
351                admin_api_key: "tskey-api-YYY".into(),
352                tailnet: None,
353            }),
354            ..Config::default()
355        };
356        let s = toml::to_string(&cfg).unwrap();
357        assert!(!s.contains("tailnet"));
358    }
359
360    #[test]
361    fn backup_s3_repo_string_is_restic_compatible() {
362        let backend = BackupBackend::S3 {
363            endpoint: "http://127.0.0.1:9000".into(),
364            bucket: "ryra-backups".into(),
365            access_key_id: "minio".into(),
366            secret_access_key: "minio123".into(),
367            prefix: None,
368        };
369        assert_eq!(
370            backend.restic_repo(),
371            "s3:http://127.0.0.1:9000/ryra-backups"
372        );
373    }
374
375    #[test]
376    fn backup_s3_repo_with_prefix() {
377        let backend = BackupBackend::S3 {
378            endpoint: "https://s3.eu-west-1.amazonaws.com".into(),
379            bucket: "shared-bucket".into(),
380            access_key_id: "k".into(),
381            secret_access_key: "s".into(),
382            prefix: Some("hosts/laptop".into()),
383        };
384        assert_eq!(
385            backend.restic_repo(),
386            "s3:https://s3.eu-west-1.amazonaws.com/shared-bucket/hosts/laptop"
387        );
388    }
389
390    #[test]
391    fn backup_s3_trims_trailing_endpoint_slashes() {
392        // Sloppy user input shouldn't double-slash the resulting URL —
393        // restic accepts both but the canonical form is cleaner.
394        let backend = BackupBackend::S3 {
395            endpoint: "http://127.0.0.1:9000/".into(),
396            bucket: "b".into(),
397            access_key_id: "k".into(),
398            secret_access_key: "s".into(),
399            prefix: None,
400        };
401        assert_eq!(backend.restic_repo(), "s3:http://127.0.0.1:9000/b");
402    }
403
404    #[test]
405    fn backup_local_repo_is_path_string() {
406        let backend = BackupBackend::Local {
407            path: "/tmp/ryra-test-repo".into(),
408        };
409        assert_eq!(backend.restic_repo(), "/tmp/ryra-test-repo");
410    }
411
412    #[test]
413    fn backup_s3_env_carries_aws_credentials() {
414        let backend = BackupBackend::S3 {
415            endpoint: "http://127.0.0.1:9000".into(),
416            bucket: "b".into(),
417            access_key_id: "the_id".into(),
418            secret_access_key: "the_secret".into(),
419            prefix: None,
420        };
421        let env: std::collections::HashMap<_, _> = backend.env().into_iter().collect();
422        assert_eq!(env.get("AWS_ACCESS_KEY_ID"), Some(&"the_id".to_string()));
423        assert_eq!(
424            env.get("AWS_SECRET_ACCESS_KEY"),
425            Some(&"the_secret".to_string())
426        );
427    }
428
429    #[test]
430    fn backup_local_env_is_empty() {
431        let backend = BackupBackend::Local {
432            path: "/tmp/x".into(),
433        };
434        assert!(backend.env().is_empty());
435    }
436
437    #[test]
438    fn backup_settings_round_trip() {
439        let cfg = Config {
440            backup: Some(BackupSettings {
441                password: "the-key".into(),
442                backend: BackupBackend::S3 {
443                    endpoint: "http://127.0.0.1:9000".into(),
444                    bucket: "ryra".into(),
445                    access_key_id: "minio".into(),
446                    secret_access_key: "minio123".into(),
447                    prefix: None,
448                },
449            }),
450            ..Config::default()
451        };
452        let text = toml::to_string(&cfg).unwrap();
453        assert!(text.contains("[backup]"), "expected [backup] table: {text}");
454        assert!(text.contains("password = \"the-key\""), "{text}");
455        assert!(text.contains("kind = \"s3\""), "{text}");
456        let parsed: Config = toml::from_str(&text).unwrap();
457        let b = parsed.backup.expect("backup round-trips");
458        assert_eq!(b.password, "the-key");
459        match b.backend {
460            BackupBackend::S3 { bucket, .. } => assert_eq!(bucket, "ryra"),
461            other => panic!("unexpected backend: {other:?}"),
462        }
463    }
464
465    #[test]
466    fn backup_settings_counted_in_has_secrets() {
467        // Triggers the "first time secrets are saved" warning the same
468        // way SMTP / Tailscale do.
469        let cfg = Config {
470            backup: Some(BackupSettings {
471                password: "x".into(),
472                backend: BackupBackend::Local {
473                    path: "/tmp/r".into(),
474                },
475            }),
476            ..Config::default()
477        };
478        assert!(cfg.has_secrets());
479    }
480}