rustploy 0.1.72

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
//! Validação dos **vínculos** de um spec que vai ser gravado (`ServiceSpec::links`).
//! Ver `docs/plano-recursos-e-vinculos.md`.
//!
//! Regras:
//! - o alvo existe, não é o próprio serviço e não aparece duas vezes;
//! - o prefixo, se escrito, é um nome de variável válido;
//! - do **mesmo projeto**, qualquer serviço; de **outro projeto**, só um banco compartilhado, e só se a
//!   trava dele (`shared.accept_links`) aceitar — a trava vale para vínculos **novos**: um que já
//!   existia continua mesmo com ela desligada;
//! - nenhum ciclo, contando `depends_on`, os vínculos de todos e os acessos ao banco compartilhado.

use crate::domain::{
    ResourceKind, Service, ServiceSpec, is_valid_env_prefix, is_valid_resource_name, resource_kind,
};
use crate::protocol::Response as RpResponse;
use crate::store::Db;
use std::collections::BTreeSet;

/// O que a gravação precisa fazer além de salvar: os servidores compartilhados (de outros projetos)
/// que este projeto passa a usar e ainda não tem acesso.
#[derive(Debug, Default, PartialEq)]
pub struct LinkPlan {
    pub grant_servers: Vec<String>,
}

pub(crate) async fn check(
    db: &Db,
    spec: &ServiceSpec,
    self_id: Option<&str>,
) -> Result<LinkPlan, RpResponse> {
    if spec.links.is_empty() {
        return Ok(LinkPlan::default());
    }
    let all = crate::store::services::list_all(db)
        .await
        .map_err(|e| RpResponse::err("DatabaseError", e.to_string()))?;
    let access = crate::store::shared_access::all(db)
        .await
        .unwrap_or_default();
    let stored_links: BTreeSet<String> = self_id
        .and_then(|id| all.iter().find(|s| s.id == id))
        .map(|s| s.spec.links.iter().map(|l| l.service_id.clone()).collect())
        .unwrap_or_default();

    let plan = plan_links(spec, self_id, &all, &access, &stored_links)?;

    // Ciclo: o grafo inteiro com os vínculos NOVOS deste serviço no lugar dos gravados.
    if let Some(id) = self_id {
        let others: Vec<Service> = all.iter().filter(|s| s.id != id).cloned().collect();
        let mut implicit = crate::features::deploy::autostart::implicit_edges(&access, &others);
        for link in &spec.links {
            implicit.push((id.to_string(), link.service_id.clone()));
        }
        // As arestas implícitas de `shared_access` também partem deste serviço (ele é do projeto).
        for (server, project) in &access {
            if *project == spec.project_id && server != id {
                implicit.push((id.to_string(), server.clone()));
            }
        }
        let tuples: Vec<(String, String, Vec<String>)> = all
            .iter()
            .map(|s| (s.id.clone(), s.spec.name.clone(), s.spec.depends_on.clone()))
            .collect();
        crate::features::deploy::deps::shared_cycle(&tuples, &implicit, self_id, &spec.depends_on)
            .map_err(|nomes| {
                RpResponse::err(
                    "DependencyCycle",
                    format!(
                        "esse vínculo cria um ciclo (um serviço acabaria esperando a si mesmo): {}",
                        nomes.join(", ")
                    ),
                )
            })?;
    }
    Ok(plan)
}

/// As regras que não precisam de grafo (separadas para teste).
pub(crate) fn plan_links(
    spec: &ServiceSpec,
    self_id: Option<&str>,
    all: &[Service],
    access: &[(String, String)],
    stored_links: &BTreeSet<String>,
) -> Result<LinkPlan, RpResponse> {
    let mut seen = BTreeSet::new();
    let mut plan = LinkPlan::default();
    for link in &spec.links {
        if self_id == Some(link.service_id.as_str()) {
            return Err(RpResponse::err(
                "InvalidInput",
                "um serviço não pode se vincular a si mesmo",
            ));
        }
        if !seen.insert(link.service_id.as_str()) {
            return Err(RpResponse::err(
                "InvalidInput",
                "o mesmo serviço aparece duas vezes nos vínculos",
            ));
        }
        if let Some(prefix) = &link.env_prefix
            && !is_valid_env_prefix(prefix)
        {
            return Err(RpResponse::err(
                "InvalidInput",
                format!(
                    "prefixo de variável inválido: \"{prefix}\" (use só A-Z, 0-9 e _, sem começar por dígito)"
                ),
            ));
        }
        let Some(target) = all.iter().find(|s| s.id == link.service_id) else {
            return Err(RpResponse::err(
                "NotFound",
                format!("o serviço vinculado {} não existe", link.service_id),
            ));
        };
        if let Some(resource) = &link.resource {
            if target.spec.project_id != spec.project_id {
                return Err(RpResponse::err(
                    "InvalidInput",
                    format!(
                        "recurso só em serviço do mesmo projeto; num banco compartilhado de outro \
                         projeto (\"{}\"), use um database gerenciado",
                        target.spec.name
                    ),
                ));
            }
            let Some(kind) = resource_kind(target.spec.product.as_deref()) else {
                return Err(RpResponse::err(
                    "InvalidInput",
                    format!(
                        "\"{}\" não oferece recursos (só S3 — RustFS, MinIO — e Postgres, MySQL, MariaDB)",
                        target.spec.name
                    ),
                ));
            };
            if !is_valid_resource_name(kind, &resource.name) {
                let rule = match kind {
                    ResourceKind::Bucket => {
                        "bucket: 3 a 63 caracteres, minúsculas, dígitos, ponto e hífen, começando e \
                         terminando com letra ou dígito"
                    }
                    ResourceKind::Database => {
                        "database: até 32 caracteres, minúsculas, dígitos e _, começando com letra"
                    }
                };
                return Err(RpResponse::err(
                    "InvalidInput",
                    format!("nome de recurso inválido \"{}\" ({rule})", resource.name),
                ));
            }
            if resource.public_read && kind != ResourceKind::Bucket {
                return Err(RpResponse::err(
                    "InvalidInput",
                    "leitura pública só vale para bucket",
                ));
            }
        }
        if target.spec.project_id == spec.project_id {
            continue;
        }
        let Some(shared) = &target.spec.shared else {
            return Err(RpResponse::err(
                "LinkNotAllowed",
                format!(
                    "\"{}\" é de outro projeto: só dá para vincular a um serviço de outro projeto se ele \
                     for um banco compartilhado",
                    target.spec.name
                ),
            ));
        };
        let is_new = !stored_links.contains(&link.service_id);
        if is_new && !shared.accept_links {
            return Err(RpResponse::err(
                "LinkRefused",
                format!(
                    "o banco compartilhado \"{}\" está com a trava ligada: não aceita vínculos novos de \
                     outros projetos",
                    target.spec.name
                ),
            ));
        }
        let granted = access
            .iter()
            .any(|(server, project)| server == &target.id && project == &spec.project_id);
        if !granted {
            plan.grant_servers.push(target.id.clone());
        }
    }
    Ok(plan)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::{ServiceLink, SharedServerConfig};

    fn service(id: &str, project: &str, shared: Option<bool>) -> Service {
        let mut spec = crate::features::wizard::app_spec(id.into(), project.into());
        spec.name = id.into();
        spec.shared = shared.map(|accept_links| SharedServerConfig { accept_links });
        Service {
            id: id.into(),
            spec,
            status: crate::domain::ServiceStatus::Stopped,
            live_container_id: None,
            compose_project: None,
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
        }
    }

    fn with_links(project: &str, targets: &[&str]) -> ServiceSpec {
        let mut spec = crate::features::wizard::app_spec("api".into(), project.into());
        spec.links = targets
            .iter()
            .map(|t| ServiceLink {
                service_id: (*t).into(),
                env_prefix: None,
                resource: None,
            })
            .collect();
        spec
    }

    fn code(r: Result<LinkPlan, RpResponse>) -> String {
        match r {
            Err(RpResponse::Err { code, .. }) => code,
            other => format!("{other:?}"),
        }
    }

    #[test]
    fn regras_dos_vinculos() {
        let all = vec![
            service("db", "p1", None),
            service("outro_app", "p2", None),
            service("pg_aberto", "p2", Some(true)),
            service("pg_trancado", "p2", Some(false)),
        ];
        let none = BTreeSet::new();
        // mesmo projeto: livre, sem acesso a conceder
        assert_eq!(
            plan_links(&with_links("p1", &["db"]), Some("api"), &all, &[], &none).unwrap(),
            LinkPlan::default()
        );
        // a si mesmo, repetido, inexistente
        assert_eq!(
            code(plan_links(
                &with_links("p1", &["api"]),
                Some("api"),
                &all,
                &[],
                &none
            )),
            "InvalidInput"
        );
        assert_eq!(
            code(plan_links(
                &with_links("p1", &["db", "db"]),
                Some("api"),
                &all,
                &[],
                &none
            )),
            "InvalidInput"
        );
        assert_eq!(
            code(plan_links(
                &with_links("p1", &["sumiu"]),
                Some("api"),
                &all,
                &[],
                &none
            )),
            "NotFound"
        );
        // outro projeto: só banco compartilhado
        assert_eq!(
            code(plan_links(
                &with_links("p1", &["outro_app"]),
                Some("api"),
                &all,
                &[],
                &none
            )),
            "LinkNotAllowed"
        );
        // compartilhado aceitando, sem acesso ainda: concede
        assert_eq!(
            plan_links(
                &with_links("p1", &["pg_aberto"]),
                Some("api"),
                &all,
                &[],
                &none
            )
            .unwrap(),
            LinkPlan {
                grant_servers: vec!["pg_aberto".into()]
            }
        );
        // já com acesso: nada a conceder
        let access = vec![("pg_aberto".to_string(), "p1".to_string())];
        assert_eq!(
            plan_links(
                &with_links("p1", &["pg_aberto"]),
                Some("api"),
                &all,
                &access,
                &none
            )
            .unwrap(),
            LinkPlan::default()
        );
        // trava ligada: recusa o vínculo novo, mas mantém o que já existia
        assert_eq!(
            code(plan_links(
                &with_links("p1", &["pg_trancado"]),
                Some("api"),
                &all,
                &[],
                &none
            )),
            "LinkRefused"
        );
        let stored: BTreeSet<String> = ["pg_trancado".to_string()].into();
        assert!(
            plan_links(
                &with_links("p1", &["pg_trancado"]),
                Some("api"),
                &all,
                &access,
                &stored
            )
            .is_ok()
        );
        // prefixo inválido
        let mut spec = with_links("p1", &["db"]);
        spec.links[0].env_prefix = Some("1abc".into());
        assert_eq!(
            code(plan_links(&spec, Some("api"), &all, &[], &none)),
            "InvalidInput"
        );
    }

    /// Fase 2: recurso só no mesmo projeto, só em provedor que oferece, com nome válido; leitura
    /// pública só para bucket.
    #[test]
    fn regras_do_recurso() {
        use crate::domain::LinkResource;
        let mut s3 = service("s3", "p1", None);
        s3.spec.product = Some("rustfs".into());
        let mut pg = service("pg", "p1", None);
        pg.spec.product = Some("postgres".into());
        let mut pg_fora = service("pg_fora", "p2", Some(true));
        pg_fora.spec.product = Some("postgres".into());
        let all = vec![s3, pg, pg_fora, service("app", "p1", None)];
        let none = BTreeSet::new();
        let with = |target: &str, name: &str, public_read: bool| {
            let mut spec = with_links("p1", &[target]);
            spec.links[0].resource = Some(LinkResource {
                name: name.into(),
                public_read,
            });
            spec
        };
        assert!(
            plan_links(
                &with("s3", "chickie-uploads", true),
                Some("api"),
                &all,
                &[],
                &none
            )
            .is_ok()
        );
        assert!(plan_links(&with("pg", "loja", false), Some("api"), &all, &[], &none).is_ok());
        assert_eq!(
            code(plan_links(
                &with("pg", "loja", true),
                Some("api"),
                &all,
                &[],
                &none
            )),
            "InvalidInput"
        );
        assert_eq!(
            code(plan_links(
                &with("s3", "Maiuscula", false),
                Some("api"),
                &all,
                &[],
                &none
            )),
            "InvalidInput"
        );
        assert_eq!(
            code(plan_links(
                &with("pg", "1abc", false),
                Some("api"),
                &all,
                &[],
                &none
            )),
            "InvalidInput"
        );
        assert_eq!(
            code(plan_links(
                &with("app", "x123", false),
                Some("api"),
                &all,
                &[],
                &none
            )),
            "InvalidInput"
        );
        let access = vec![("pg_fora".to_string(), "p1".to_string())];
        assert_eq!(
            code(plan_links(
                &with("pg_fora", "loja", false),
                Some("api"),
                &all,
                &access,
                &none
            )),
            "InvalidInput"
        );
    }

    #[test]
    fn nomes_de_recurso() {
        use crate::domain::{ResourceKind::*, is_valid_resource_name as ok};
        assert!(ok(Bucket, "chickie-uploads"));
        assert!(ok(Bucket, "a.b-c"));
        assert!(!ok(Bucket, "ab"));
        assert!(!ok(Bucket, "-ab"));
        assert!(!ok(Bucket, "a..b"));
        assert!(!ok(Bucket, "ABC"));
        assert!(ok(Database, "loja_2"));
        assert!(!ok(Database, "loja-2"));
        assert!(!ok(Database, "\"; DROP"));
        assert!(!ok(Database, &"a".repeat(33)));
    }

    #[test]
    fn prefixo_padrao_e_validacao() {
        use crate::domain::{is_valid_env_prefix, link_env_prefix};
        assert_eq!(link_env_prefix("s3"), "S3");
        assert_eq!(link_env_prefix("pg-central"), "PG_CENTRAL");
        assert_eq!(link_env_prefix("landing page"), "LANDING_PAGE");
        assert_eq!(link_env_prefix("2fa"), "_2FA");
        assert!(is_valid_env_prefix("DB_MAIN"));
        assert!(!is_valid_env_prefix("db"));
        assert!(!is_valid_env_prefix("1DB"));
        assert!(!is_valid_env_prefix(""));
    }

    /// O vínculo vira aresta de dependência (a ordem do deploy em árvore e do boot).
    #[test]
    fn vinculo_vira_aresta() {
        let mut api = service("api", "p1", None);
        api.spec.links = vec![ServiceLink {
            service_id: "db".into(),
            env_prefix: None,
            resource: None,
        }];
        let all = vec![service("db", "p1", None), api];
        let edges = crate::features::deploy::autostart::implicit_edges(&[], &all);
        assert_eq!(edges, vec![("api".to_string(), "db".to_string())]);
    }
}