rustploy 0.1.36

Rustploy PaaS daemon — lightweight self-hosted deployment platform
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! Configuração do daemon (`config.toml`): structs de cada seção com defaults e
//! o singleton `CONFIG`.

#![allow(dead_code)] // API de quando o módulo vivia no `shared`; parte dela só os testes usam.

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

/// Process-wide configuration singleton. Loaded once (files + env vars) on first
/// access and shared everywhere via [`RustployConfig::global`].
static CONFIG: OnceLock<RustployConfig> = OnceLock::new();
static CONFIG_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvBackupConfig {
    /// Directório onde os snapshots são gravados.
    /// Padrão: <db_path>/env_backups/
    pub dir: Option<String>,
    /// Intervalo entre backups em segundos. Padrão: 60.
    #[serde(default = "default_env_backup_interval")]
    pub interval_secs: u64,
}

/// `Default` à mão, não derivado: o `#[serde(default)]` da seção inteira em
/// `RustployConfig` cai AQUI quando o `config.toml` não tem `[env_backup]` (o
/// caso do packaging), e um `u64` derivado seria 0 — o que fazia
/// `tokio::time::interval(0)` panicar no boot e matar o loop de backup.
impl Default for EnvBackupConfig {
    fn default() -> Self {
        Self {
            dir: None,
            interval_secs: default_env_backup_interval(),
        }
    }
}

fn default_env_backup_interval() -> u64 {
    60
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RustployConfig {
    pub daemon: DaemonConfig,
    pub ingress: IngressConfig,
    pub docker: DockerConfig,
    pub deploy: DeployConfig,
    pub metrics: MetricsConfig,
    pub secrets: SecretsConfig,
    #[serde(default)]
    pub api: ApiConfig,
    #[serde(default)]
    pub env_backup: EnvBackupConfig,
    #[serde(default)]
    pub external_ports: ExternalPortsConfig,
    #[serde(default)]
    pub registry: RegistryConfig,
    #[serde(default)]
    pub update: UpdateConfig,
    #[serde(default)]
    pub state_git: StateGitConfig,
    #[serde(default)]
    pub logs: LogsConfig,
}

/// `[logs]`: persistência do log de runtime dos containers (`platform::log_store`). Plano:
/// `docs/plano-log-de-runtime-persistido.md`. Todos os campos têm padrão.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogsConfig {
    /// Liga a gravação. Desligada, o log segue só ao vivo (como antes).
    #[serde(default = "default_logs_enabled")]
    pub enabled: bool,
    /// Apaga segmentos mais velhos que isso.
    #[serde(default = "default_logs_retention_days")]
    pub retention_days: u32,
    /// Teto de disco por serviço (bytes); o segmento mais velho sai primeiro.
    #[serde(default = "default_logs_max_bytes")]
    pub max_bytes_per_service: u64,
}

fn default_logs_enabled() -> bool {
    true
}

fn default_logs_retention_days() -> u32 {
    14
}

fn default_logs_max_bytes() -> u64 {
    50 * 1024 * 1024
}

/// `Default` à mão (e não derivado) pelo mesmo motivo do `[env_backup]`: a seção ausente cai aqui e
/// um `bool`/número derivado seria `false`/`0`.
impl Default for LogsConfig {
    fn default() -> Self {
        Self {
            enabled: default_logs_enabled(),
            retention_days: default_logs_retention_days(),
            max_bytes_per_service: default_logs_max_bytes(),
        }
    }
}

/// `[state_git]`: só o ritmo do `fetch`. Modo, repositório e provider são configurados pela UI e
/// ficam no banco (ver `features::state_git`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateGitConfig {
    /// De quanto em quanto tempo o daemon consulta o remoto por commits novos (mínimo efetivo: 10 s).
    #[serde(default = "default_fetch_interval_secs")]
    pub fetch_interval_secs: u64,
}

fn default_fetch_interval_secs() -> u64 {
    60
}

impl Default for StateGitConfig {
    fn default() -> Self {
        Self {
            fetch_interval_secs: default_fetch_interval_secs(),
        }
    }
}

/// Verificação de versão nova (`Command::CheckUpdate`). Só consulta; instalar é
/// outra etapa (ver `docs/plano-updaters-daemon-e-gui.md`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateConfig {
    /// `false`: o daemon nem consulta o GitHub (VPS sem saída para a internet).
    #[serde(default = "default_update_enabled")]
    pub enabled: bool,
    /// Repositório `dono/nome` cujas releases são consultadas. Fixo na config:
    /// a UI não escolhe de onde vem uma atualização.
    #[serde(default = "default_update_repo")]
    pub repo: String,
    /// Por quantas horas o resultado vale. O GitHub limita a API anônima a 60
    /// consultas/h por IP, e o cache evita estourar isso com a UI aberta.
    #[serde(default = "default_update_cache_hours")]
    pub cache_hours: u64,
    /// De quantas em quantas horas o daemon consulta sozinho, para o selo de versão nova
    /// acender nas UIs abertas sem ninguém clicar em "Verificar". `0`: só quando pedem.
    #[serde(default = "default_update_check_interval_hours")]
    pub check_interval_hours: u64,
    /// `false` (padrão): o agente MCP não pode pedir `ApplyUpdate`/`UpdateRollback`. Atualizar
    /// derruba a API e troca o binário; isso é decisão de uma pessoa, na UI.
    #[serde(default)]
    pub allow_agent_apply: bool,
}

fn default_update_enabled() -> bool {
    true
}
fn default_update_repo() -> String {
    "antoniofernandodj/rustploy".into()
}
fn default_update_cache_hours() -> u64 {
    6
}
fn default_update_check_interval_hours() -> u64 {
    6
}

impl Default for UpdateConfig {
    fn default() -> Self {
        Self {
            enabled: default_update_enabled(),
            repo: default_update_repo(),
            cache_hours: default_update_cache_hours(),
            check_interval_hours: default_update_check_interval_hours(),
            allow_agent_apply: false,
        }
    }
}

/// Faixa de portas de host que o rustploy pode alocar automaticamente para
/// exposição externa de serviços TCP (`ServiceSpec.host_port`). Também é a
/// única faixa que o helper privilegiado de firewall (`rustployd-fw`) aceita
/// liberar/bloquear — portas fora dela são recusadas por construção.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExternalPortsConfig {
    #[serde(default = "default_external_range_start")]
    pub range_start: u16,
    #[serde(default = "default_external_range_end")]
    pub range_end: u16,
}

fn default_external_range_start() -> u16 {
    20000
}
fn default_external_range_end() -> u16 {
    20999
}

impl Default for ExternalPortsConfig {
    fn default() -> Self {
        Self {
            range_start: default_external_range_start(),
            range_end: default_external_range_end(),
        }
    }
}

impl ExternalPortsConfig {
    pub fn contains(&self, port: u16) -> bool {
        port >= self.range_start && port <= self.range_end
    }
}

/// Configuration for the HTTP/JSON + SSE control API — o canal administrativo remoto.
/// Binds to loopback by default and is meant to sit behind the ingress proxy,
/// which terminates TLS for `rustploy.domain.com` and forwards to it.
/// Binding to a non-loopback address requires a token.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiConfig {
    #[serde(default = "default_api_enabled")]
    pub enabled: bool,
    #[serde(default = "default_api_bind")]
    pub bind_address: String,
    #[serde(default = "default_api_port")]
    pub port: u16,
    #[serde(default)]
    pub token: Option<String>,
    /// Domínio público da própria API. Quando definido (não vazio), o listener
    /// da API termina TLS **nesta mesma porta** com um certificado Let's Encrypt
    /// provisionado automaticamente via ACME (requer ACME habilitado + porta 80
    /// acessível pela internet para o desafio HTTP-01). Vazio/`None` = HTTP puro,
    /// para uso local ou atrás de um proxy externo.
    #[serde(default)]
    pub domain: Option<String>,
    #[serde(default = "default_api_max_connections")]
    pub max_connections: usize,
}

fn default_api_enabled() -> bool {
    true
}
fn default_api_bind() -> String {
    "127.0.0.1".into()
}
fn default_api_port() -> u16 {
    9797
}
fn default_api_max_connections() -> usize {
    32
}

impl Default for ApiConfig {
    fn default() -> Self {
        Self {
            enabled: default_api_enabled(),
            bind_address: default_api_bind(),
            port: default_api_port(),
            token: None,
            domain: None,
            max_connections: default_api_max_connections(),
        }
    }
}

impl ApiConfig {
    /// True when the configured bind address is not a loopback address.
    pub fn is_public_bind(&self) -> bool {
        match self.bind_address.parse::<std::net::IpAddr>() {
            Ok(ip) => !ip.is_loopback(),
            Err(_) => self.bind_address != "localhost",
        }
    }

    /// URL pública desta API, sem barra final — a base das URLs de webhook
    /// (`{base}/webhook/{service_id}/{token}`) e do callback OAuth
    /// (`{base}/oauth/gitea/callback`), que são servidos pelo **mesmo** listener
    /// da API desde a unificação (ver `docs/plano-unificacao-webhook-api.md`).
    ///
    /// Com `domain` definido o listener termina TLS na própria porta, então o
    /// esquema é `https` e a porta só aparece quando não é a 443. Sem domínio,
    /// usa `fallback_host` (o chamador passa o IP de saída da máquina) sobre
    /// HTTP puro.
    pub fn public_base_url(&self, fallback_host: &str) -> String {
        match self
            .domain
            .as_deref()
            .map(str::trim)
            .filter(|d| !d.is_empty())
        {
            Some(domain) if self.port == 443 => format!("https://{domain}"),
            Some(domain) => format!("https://{domain}:{}", self.port),
            None => format!("http://{fallback_host}:{}", self.port),
        }
    }
}

/// Registry Docker OCI (Distribution API v2) embutido no daemon. O listener
/// sempre escuta em loopback (Basic auth obrigatória, ver `registry::auth`);
/// quando `domain` está definido (aqui ou em `daemon_settings`, que tem
/// precedência — mesmo padrão do e-mail ACME), o daemon registra uma rota no
/// ingress + certificado ACME pra expor publicamente.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistryConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default = "default_registry_port")]
    pub port: u16,
    #[serde(default)]
    pub domain: Option<String>,
    /// Diretório do CAS. Padrão: `<db_path>/registry/`.
    #[serde(default)]
    pub storage_dir: Option<String>,
}

fn default_registry_port() -> u16 {
    5100
}

impl Default for RegistryConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            port: default_registry_port(),
            domain: None,
            storage_dir: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DaemonConfig {
    pub db_path: String,
    pub log_level: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IngressConfig {
    pub http_port: u16,
    pub https_port: u16,
    pub bind_address: String,
    pub acme: AcmeConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AcmeConfig {
    pub enabled: bool,
    pub email: Option<String>,
    pub directory: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DockerConfig {
    pub socket_path: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeployConfig {
    pub drain_secs: u64,
    pub image_cache: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricsConfig {
    pub interval_secs: u64,
    pub history_points: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretsConfig {
    /// Arquivo da identidade `age` privada do servidor (`AGE-SECRET-KEY-1…`, 0600). Só é lido se
    /// `age_identity` não estiver no `config.toml`. Ausente → `/etc/rustploy/age.key`.
    #[serde(default)]
    pub age_key_path: Option<String>,
    /// Identidade `age` (X25519, `AGE-SECRET-KEY-1…`) que cifra e decifra os segredos
    /// (`ENC[age:…]`). Ausente → o daemon gera uma na primeira subida e a grava aqui.
    /// **Perder esta chave sem ter `recovery_recipient` = perder todos os segredos.**
    #[serde(default)]
    pub age_identity: Option<String>,
    /// Chave **pública** (`age1…`) de recuperação: todo segredo novo também fica legível por quem
    /// tem a chave privada correspondente (guardada fora do servidor).
    #[serde(default)]
    pub recovery_recipient: Option<String>,
}

impl Default for RustployConfig {
    fn default() -> Self {
        Self {
            daemon: DaemonConfig {
                db_path: "/var/lib/rustploy/db".into(),
                log_level: "info".into(),
            },
            ingress: IngressConfig {
                http_port: 8080,
                https_port: 443,
                bind_address: "0.0.0.0".into(),
                acme: AcmeConfig {
                    enabled: true,
                    email: None,
                    directory: "https://acme-v02.api.letsencrypt.org/directory".into(),
                },
            },
            docker: DockerConfig {
                socket_path: "/var/run/docker.sock".into(),
            },
            deploy: DeployConfig {
                drain_secs: 10,
                image_cache: 2,
            },
            metrics: MetricsConfig {
                interval_secs: 2,
                history_points: 60,
            },
            secrets: SecretsConfig {
                age_key_path: Some("/etc/rustploy/age.key".into()),
                age_identity: None,
                recovery_recipient: None,
            },
            api: ApiConfig::default(),
            env_backup: EnvBackupConfig::default(),
            external_ports: ExternalPortsConfig::default(),
            registry: RegistryConfig::default(),
            update: UpdateConfig::default(),
            state_git: StateGitConfig::default(),
            logs: LogsConfig::default(),
        }
    }
}

impl RustployConfig {
    /// Returns the process-wide config, loading it on first call.
    ///
    /// This is the single entry point every binary should use so that all
    /// `RUSTPLOY_*` environment variables are read in exactly one place.
    pub fn global() -> &'static RustployConfig {
        CONFIG.get_or_init(|| {
            let (cfg, path) = Self::load_with_path();
            let _ = CONFIG_PATH.set(path);
            cfg
        })
    }

    /// Arquivo de onde `global()` leu a config (`None` = defaults).
    pub fn global_path() -> Option<&'static Path> {
        Self::global();
        CONFIG_PATH.get().and_then(|p| p.as_deref())
    }

    pub fn load() -> Self {
        Self::load_with_path().0
    }

    /// Como [`load`](Self::load), devolvendo também o arquivo de onde a config saiu (`None` = veio
    /// dos defaults). O daemon precisa dele para gravar a identidade `age` gerada na primeira subida.
    pub fn load_with_path() -> (Self, Option<std::path::PathBuf>) {
        let paths = [
            std::env::var("RUSTPLOY_CONFIG")
                .ok()
                .map(std::path::PathBuf::from),
            Some(std::path::PathBuf::from("/etc/rustploy/config.toml")),
            dirs_config_path(),
        ];

        for path in paths.into_iter().flatten() {
            if let Ok(contents) = std::fs::read_to_string(&path)
                && let Ok(cfg) = toml::from_str(&contents)
            {
                return (Self::apply_env_overrides(cfg), Some(path));
            }
        }

        (Self::apply_env_overrides(Self::default()), None)
    }

    fn apply_env_overrides(mut cfg: Self) -> Self {
        if let Ok(v) = std::env::var("RUSTPLOY_DB_PATH") {
            cfg.daemon.db_path = v;
        }
        if let Ok(v) = std::env::var("RUSTPLOY_LOG_LEVEL") {
            cfg.daemon.log_level = v;
        }
        if let Ok(v) = std::env::var("RUSTPLOY_HTTP_PORT")
            && let Ok(p) = v.parse()
        {
            cfg.ingress.http_port = p;
        }
        // HTTP/JSON + SSE control API.
        if let Ok(v) = std::env::var("RUSTPLOY_API_ENABLED") {
            cfg.api.enabled = matches!(v.as_str(), "1" | "true" | "yes" | "on");
        }
        if let Ok(v) = std::env::var("RUSTPLOY_API_BIND") {
            cfg.api.bind_address = v;
        }
        if let Ok(v) = std::env::var("RUSTPLOY_API_PORT")
            && let Ok(p) = v.parse()
        {
            cfg.api.port = p;
        }
        if let Ok(v) = std::env::var("RUSTPLOY_API_TOKEN") {
            cfg.api.token = Some(v).filter(|s| !s.is_empty());
        }
        if let Ok(v) = std::env::var("RUSTPLOY_API_DOMAIN") {
            cfg.api.domain = Some(v).filter(|s| !s.is_empty());
        }
        // Registry OCI embutido.
        if let Ok(v) = std::env::var("RUSTPLOY_REGISTRY_ENABLED") {
            cfg.registry.enabled = matches!(v.as_str(), "1" | "true" | "yes" | "on");
        }
        if let Ok(v) = std::env::var("RUSTPLOY_REGISTRY_PORT")
            && let Ok(p) = v.parse()
        {
            cfg.registry.port = p;
        }
        if let Ok(v) = std::env::var("RUSTPLOY_REGISTRY_DOMAIN") {
            cfg.registry.domain = Some(v).filter(|s| !s.is_empty());
        }
        if let Ok(v) = std::env::var("RUSTPLOY_REGISTRY_STORAGE_DIR") {
            cfg.registry.storage_dir = Some(v).filter(|s| !s.is_empty());
        }
        cfg
    }
}

/// The single place the process reads `$HOME`.
pub fn user_home() -> Option<String> {
    std::env::var("HOME").ok().filter(|s| !s.is_empty())
}

/// `~/.local/share/rustploy`, falling back to `/tmp` when `$HOME` is unset.
pub fn fallback_data_dir() -> PathBuf {
    let home = user_home().unwrap_or_else(|| "/tmp".into());
    PathBuf::from(home)
        .join(".local")
        .join("share")
        .join("rustploy")
}

fn dirs_config_path() -> Option<PathBuf> {
    user_home().map(|home| {
        PathBuf::from(home)
            .join(".config")
            .join("rustploy")
            .join("config.toml")
    })
}

/// Detecta o IP de saída da máquina conectando um socket UDP em 8.8.8.8:80
/// (sem enviar dados) e lendo o endereço local escolhido pelo kernel. Usado só
/// como host de fallback quando `api.domain` não está configurado.
pub fn outbound_ip() -> String {
    use std::net::UdpSocket;
    UdpSocket::bind("0.0.0.0:0")
        .and_then(|s| {
            s.connect("8.8.8.8:80")?;
            s.local_addr()
        })
        .map(|addr| addr.ip().to_string())
        .unwrap_or_else(|_| "localhost".to_string())
}

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

    /// A partial `[api]` block (only the fields the installer/admin cares about)
    /// must parse, with the remaining fields falling back to their defaults.
    #[test]
    fn partial_api_block_uses_field_defaults() {
        let toml_str = r#"
[api]
token = "abc123"
"#;
        let cfg: ApiConfig = toml::from_str(toml_str)
            .map(|w: WrapApi| w.api)
            .expect("partial [api] must parse");
        assert_eq!(cfg.token.as_deref(), Some("abc123"));
        assert_eq!(cfg.port, 9797);
        assert_eq!(cfg.bind_address, "127.0.0.1");
        assert_eq!(cfg.max_connections, 32);
    }

    #[derive(Deserialize)]
    struct WrapApi {
        api: ApiConfig,
    }

    /// Idem para `[registry]`: `enabled = true` sozinho deve bastar, com
    /// `port`/`domain`/`storage_dir` caindo nos defaults.
    #[test]
    fn partial_registry_block_uses_field_defaults() {
        let toml_str = r#"
[registry]
enabled = true
"#;
        let cfg: RegistryConfig = toml::from_str(toml_str)
            .map(|w: WrapRegistry| w.registry)
            .expect("partial [registry] must parse");
        assert!(cfg.enabled);
        assert_eq!(cfg.port, 5100);
        assert_eq!(cfg.domain, None);
        assert_eq!(cfg.storage_dir, None);
    }

    #[derive(Deserialize)]
    struct WrapRegistry {
        registry: RegistryConfig,
    }

    /// Sem `[update]` na config (todo `config.toml` existente) vale o padrão; e um
    /// bloco parcial só sobrescreve o que foi escrito.
    #[test]
    fn update_block_is_optional_and_partial() {
        assert!(UpdateConfig::default().enabled);
        assert_eq!(UpdateConfig::default().cache_hours, 6);
        assert_eq!(UpdateConfig::default().check_interval_hours, 6);

        let cfg: UpdateConfig = toml::from_str("enabled = false").unwrap();
        assert!(!cfg.enabled);
        assert_eq!(cfg.repo, "antoniofernandodj/rustploy");
        // O agente MCP não aplica atualização, a menos que a config diga.
        assert!(!cfg.allow_agent_apply);
        let cfg: UpdateConfig = toml::from_str("allow_agent_apply = true").unwrap();
        assert!(cfg.allow_agent_apply);
    }
}