cufflink-cli 0.11.2

CLI for the Cufflink CRUD microservice platform — deploy, init, and manage services
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
use crate::config::CliConfig;
use crate::project_config::ProjectConfig;
use std::collections::HashMap;
use std::process::Command;

/// Get the service ID by extracting manifest name and looking up via API
async fn get_service_id(config: &CliConfig) -> eyre::Result<String> {
    // Check if this is a web project first (use Cufflink.toml)
    let project = ProjectConfig::find_and_load()?;
    let mode = project
        .as_ref()
        .and_then(|p| p.service.mode.as_deref())
        .unwrap_or("rust");

    let service_name = if mode == "web" {
        project
            .as_ref()
            .and_then(|p| p.service.name.as_deref())
            .ok_or_else(|| eyre::eyre!("Web mode requires [service].name in Cufflink.toml"))?
            .to_string()
    } else {
        let output = Command::new("cargo")
            .args(["run", "--", "--emit-manifest"])
            .output()?;

        if !output.status.success() {
            eyre::bail!("Failed to build service. Run from a cufflink service directory.");
        }

        let stdout = String::from_utf8(output.stdout)?;
        let manifest: serde_json::Value = serde_json::from_str(stdout.trim())?;
        manifest["name"]
            .as_str()
            .ok_or_else(|| eyre::eyre!("No service name in manifest"))?
            .to_string()
    };
    let service_name = &service_name;

    let client = config.http_client();
    let resp = config
        .auth_request(
            &client,
            reqwest::Method::GET,
            &format!("{}/api/services", config.api_url),
        )
        .send()
        .await?;

    let services: serde_json::Value = resp.json().await?;
    let service = services["services"]
        .as_array()
        .and_then(|arr| {
            arr.iter()
                .find(|s| s["name"].as_str() == Some(service_name))
        })
        .ok_or_else(|| eyre::eyre!("Service '{}' not found on platform", service_name))?;

    Ok(service["id"]
        .as_str()
        .ok_or_else(|| eyre::eyre!("Service has no ID"))?
        .to_string())
}

/// List all config values for the current service
pub async fn list(env: Option<&str>) -> eyre::Result<()> {
    let config = CliConfig::load_with_env(env)?;

    if let Some(ref name) = config.env_name {
        println!("Environment: {}", name);
    }

    let service_id = get_service_id(&config).await?;

    let client = config.http_client();
    let resp = config
        .auth_request(
            &client,
            reqwest::Method::GET,
            &format!("{}/api/services/{}/config", config.api_url, service_id),
        )
        .send()
        .await?;

    if resp.status().is_success() {
        let body: serde_json::Value = resp.json().await?;
        if let Some(configs) = body["configs"].as_array() {
            if configs.is_empty() {
                println!("No configuration values set.");
            } else {
                use comfy_table::{presets::NOTHING, Table, TableComponent};

                let mut table = Table::new();
                table.load_preset(NOTHING);
                table.set_style(TableComponent::HeaderLines, '-');
                table.set_style(TableComponent::MiddleHeaderIntersections, ' ');
                table.set_header(vec!["KEY", "VALUE", "SECRET"]);

                for c in configs {
                    let secret = if c["is_secret"].as_bool() == Some(true) {
                        "yes"
                    } else {
                        "no"
                    };
                    table.add_row(vec![
                        c["key"].as_str().unwrap_or(""),
                        c["value"].as_str().unwrap_or(""),
                        secret,
                    ]);
                }

                println!("{table}");
            }
        }
    } else {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        eyre::bail!("Failed to list config ({}): {}", status, body);
    }

    Ok(())
}

/// Set a config value
pub async fn set(key: &str, value: &str, is_secret: bool, env: Option<&str>) -> eyre::Result<()> {
    let config = CliConfig::load_with_env(env)?;

    if let Some(ref name) = config.env_name {
        println!("Environment: {}", name);
    }

    let service_id = get_service_id(&config).await?;

    let payload = serde_json::json!({
        "key": key,
        "value": value,
        "is_secret": is_secret,
    });

    let client = config.http_client();
    let resp = config
        .auth_request(
            &client,
            reqwest::Method::PUT,
            &format!("{}/api/services/{}/config", config.api_url, service_id),
        )
        .json(&payload)
        .send()
        .await?;

    if resp.status().is_success() {
        println!("Config '{}' set successfully", key);
    } else {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        eyre::bail!("Failed to set config ({}): {}", status, body);
    }

    Ok(())
}

/// Delete a config value
pub async fn delete(key: &str, env: Option<&str>) -> eyre::Result<()> {
    let config = CliConfig::load_with_env(env)?;

    if let Some(ref name) = config.env_name {
        println!("Environment: {}", name);
    }

    let service_id = get_service_id(&config).await?;

    let client = config.http_client();
    let resp = config
        .auth_request(
            &client,
            reqwest::Method::DELETE,
            &format!(
                "{}/api/services/{}/config/{}",
                config.api_url, service_id, key
            ),
        )
        .send()
        .await?;

    if resp.status().is_success() {
        println!("Config '{}' deleted", key);
    } else {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        eyre::bail!("Failed to delete config ({}): {}", status, body);
    }

    Ok(())
}

/// Sync configs and secrets from Cufflink.toml to the platform
pub async fn sync(env: Option<&str>) -> eyre::Result<()> {
    let config = CliConfig::load_with_env(env)?;

    if let Some(ref name) = config.env_name {
        println!("Environment: {}", name);
    }

    let service_id = get_service_id(&config).await?;

    let project =
        ProjectConfig::find_and_load()?.ok_or_else(|| eyre::eyre!("No Cufflink.toml found"))?;

    let env_name = env
        .map(|s| s.to_string())
        .or_else(|| project.service.default_env.clone())
        .ok_or_else(|| eyre::eyre!("No environment specified"))?;

    let env_config = project.get_env(&env_name)?;

    sync_to_platform(
        &config,
        &service_id,
        &env_config.config,
        &env_config.secrets,
        &project,
        &env_name,
    )
    .await
}

/// Sync configs and secrets to the platform. Used by both `config sync` and `deploy`.
pub async fn sync_to_platform(
    cli_config: &CliConfig,
    service_id: &str,
    configs: &HashMap<String, String>,
    secrets: &HashMap<String, String>,
    project: &ProjectConfig,
    env_name: &str,
) -> eyre::Result<()> {
    let client = cli_config.http_client();
    let config_url = format!("{}/api/services/{}/config", cli_config.api_url, service_id);

    // Sync plaintext configs
    let mut synced = 0;
    for (key, value) in configs {
        let payload = serde_json::json!({
            "key": key,
            "value": value,
            "is_secret": false,
        });

        let resp = cli_config
            .auth_request(&client, reqwest::Method::PUT, &config_url)
            .json(&payload)
            .send()
            .await?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            eyre::bail!("Failed to sync config '{}' ({}): {}", key, status, body);
        }
        synced += 1;
    }

    // Sync secrets from securestore
    let resolved_secrets = resolve_secret_refs(project, env_name, secrets)?;
    let mut secrets_synced = 0;
    for (config_key, value) in &resolved_secrets {
        let payload = serde_json::json!({
            "key": config_key,
            "value": value,
            "is_secret": true,
        });

        let resp = cli_config
            .auth_request(&client, reqwest::Method::PUT, &config_url)
            .json(&payload)
            .send()
            .await?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            eyre::bail!(
                "Failed to sync secret '{}' ({}): {}",
                config_key,
                status,
                body
            );
        }
        secrets_synced += 1;
    }

    if synced > 0 || secrets_synced > 0 {
        println!(
            "  Synced {} config(s) and {} secret(s)",
            synced, secrets_synced
        );
    }

    Ok(())
}

/// Resolve `secret_refs` (mapping `config_key → "group:name"`) against the
/// local securestore vault for the given environment. Returns a flat
/// `config_key → resolved_value` map.
fn resolve_secret_refs(
    project: &ProjectConfig,
    env_name: &str,
    secret_refs: &HashMap<String, String>,
) -> eyre::Result<HashMap<String, String>> {
    if secret_refs.is_empty() {
        return Ok(HashMap::new());
    }
    let store = super::secrets_cmd::load_store(project, env_name)?;
    let mut out = HashMap::with_capacity(secret_refs.len());
    for (config_key, store_name) in secret_refs {
        let value: String = store.get(store_name).map_err(|e| {
            eyre::eyre!(
                "Secret '{}' not found in securestore for '{}': {}",
                store_name,
                env_name,
                e
            )
        })?;
        out.insert(config_key.clone(), value);
    }
    Ok(out)
}

/// Resolve a service's declared `[config]` + `[secrets]` for an environment
/// into a flat env-var map. Plain config values pass through unchanged;
/// secret references like `"google_maps:api_key"` are resolved against the
/// local securestore vault.
///
/// This is the canonical "what env vars does this service declare for this
/// environment?" lookup. Use it anywhere you need ground-truth env values
/// (build-time injection, doctor commands, dry-run output, etc.) — the
/// platform's `GET /config` masks `is_secret=true` values and is unsuitable
/// for paths that need actual values.
pub fn resolve_local_envs(
    project: &ProjectConfig,
    env_name: &str,
) -> eyre::Result<HashMap<String, String>> {
    let env = project.get_env(env_name)?;
    let mut out = env.config.clone();
    out.extend(resolve_secret_refs(project, env_name, &env.secrets)?);
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::project_config::EnvironmentConfig;
    use securestore::{KeySource, SecretsManager};
    use tempfile::TempDir;

    fn make_project_with_vault(env_name: &str) -> (TempDir, ProjectConfig) {
        let tmp = tempfile::tempdir().unwrap();
        let project_dir = tmp.path().to_path_buf();
        let secrets_dir = project_dir.join("secrets");
        std::fs::create_dir_all(&secrets_dir).unwrap();

        // Mirrors `secrets init`: generate a fresh key, export it, then
        // build the vault against that key path so subsequent `load_store`
        // can decrypt without `CUFFLINK_SECRETS_KEY` being set.
        let key_path = secrets_dir.join(format!("{}.key", env_name));
        let vault_path = secrets_dir.join(format!("{}.json", env_name));
        let store_for_key = SecretsManager::new(KeySource::Csprng).unwrap();
        store_for_key.export_key(&key_path).unwrap();

        let mut store = SecretsManager::new(KeySource::Path(&key_path)).unwrap();
        store.set("google_maps:api_key", "AIzaSyTEST");
        store.set("postmark:api_key", "pm-test-token");
        store.save_as(&vault_path).unwrap();

        let project = ProjectConfig {
            service: Default::default(),
            environments: HashMap::new(),
            project_dir,
        };
        (tmp, project)
    }

    fn env_with(config: &[(&str, &str)], secrets: &[(&str, &str)]) -> EnvironmentConfig {
        EnvironmentConfig {
            api_url: "http://localhost:8080".to_string(),
            tenant: "default".to_string(),
            api_key_env: None,
            api_key: None,
            keycloak_url: None,
            keycloak_realm: None,
            keycloak_client_id: None,
            config: config
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            secrets: secrets
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
        }
    }

    #[test]
    fn resolves_config_only_passes_values_through() {
        let (_tmp, mut project) = make_project_with_vault("staging");
        project.environments.insert(
            "staging".to_string(),
            env_with(&[("NEXT_PUBLIC_API_URL", "https://api.example")], &[]),
        );

        let envs = resolve_local_envs(&project, "staging").unwrap();
        assert_eq!(
            envs.get("NEXT_PUBLIC_API_URL").map(String::as_str),
            Some("https://api.example")
        );
    }

    #[test]
    fn resolves_secrets_against_local_vault() {
        let (_tmp, mut project) = make_project_with_vault("staging");
        project.environments.insert(
            "staging".to_string(),
            env_with(
                &[],
                &[("NEXT_PUBLIC_GOOGLE_MAPS_API_KEY", "google_maps:api_key")],
            ),
        );

        let envs = resolve_local_envs(&project, "staging").unwrap();
        assert_eq!(
            envs.get("NEXT_PUBLIC_GOOGLE_MAPS_API_KEY")
                .map(String::as_str),
            Some("AIzaSyTEST")
        );
    }

    #[test]
    fn resolves_mixed_config_and_secrets() {
        let (_tmp, mut project) = make_project_with_vault("staging");
        project.environments.insert(
            "staging".to_string(),
            env_with(
                &[("NEXT_PUBLIC_API_URL", "https://api.example")],
                &[
                    ("NEXT_PUBLIC_GOOGLE_MAPS_API_KEY", "google_maps:api_key"),
                    ("POSTMARK_API_KEY", "postmark:api_key"),
                ],
            ),
        );

        let envs = resolve_local_envs(&project, "staging").unwrap();
        assert_eq!(envs.len(), 3);
        assert_eq!(envs["NEXT_PUBLIC_API_URL"], "https://api.example");
        assert_eq!(envs["NEXT_PUBLIC_GOOGLE_MAPS_API_KEY"], "AIzaSyTEST");
        assert_eq!(envs["POSTMARK_API_KEY"], "pm-test-token");
    }

    #[test]
    fn errors_when_referenced_secret_missing_from_vault() {
        let (_tmp, mut project) = make_project_with_vault("staging");
        project.environments.insert(
            "staging".to_string(),
            env_with(&[], &[("MISSING_VAR", "missing:secret")]),
        );

        let err = resolve_local_envs(&project, "staging").unwrap_err();
        assert!(err.to_string().contains("missing:secret"));
        assert!(err.to_string().contains("staging"));
    }

    #[test]
    fn errors_for_unknown_environment() {
        let (_tmp, project) = make_project_with_vault("staging");

        let err = resolve_local_envs(&project, "nope").unwrap_err();
        assert!(err.to_string().contains("nope"));
    }
}