rise-deploy 0.16.4

A simple and powerful CLI for deploying containerized applications
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
use anyhow::{Context, Result};
use comfy_table::{modifiers::UTF8_ROUND_CORNERS, presets::UTF8_FULL, Attribute, Cell, Table};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

#[derive(Debug, Deserialize)]
struct EnvVarResponse {
    key: String,
    value: String, // Will be masked ("••••••••") for protected secrets
    is_secret: bool,
    is_protected: bool,
}

#[derive(Debug, Deserialize)]
struct EnvVarsResponse {
    env_vars: Vec<EnvVarResponse>,
}

#[derive(Debug, Serialize)]
struct SetEnvVarRequest {
    value: String,
    #[serde(default)]
    is_secret: bool,
    #[serde(default)]
    is_protected: bool,
}

/// Fetch environment variables from a project (internal helper)
async fn fetch_env_vars_response(
    http_client: &Client,
    backend_url: &str,
    token: &str,
    project: &str,
) -> Result<EnvVarsResponse> {
    let url = format!("{}/api/v1/projects/{}/env", backend_url, project);

    let response = http_client
        .get(&url)
        .header("Authorization", format!("Bearer {}", token))
        .send()
        .await
        .context("Failed to fetch environment variables")?;

    if !response.status().is_success() {
        let status = response.status();
        let error_text = response
            .text()
            .await
            .unwrap_or_else(|_| "Unknown error".to_string());
        anyhow::bail!(
            "Failed to fetch environment variables (status {}): {}",
            status,
            error_text
        );
    }

    let env_vars_response: EnvVarsResponse = response
        .json()
        .await
        .context("Failed to parse environment variables response")?;

    Ok(env_vars_response)
}

/// Fetch preview environment variables — the full set a deployment would receive.
///
/// Returns:
/// - Loadable vars (non-secret + unprotected secrets, with decrypted values)
/// - Protected keys (value masked, cannot be loaded locally)
pub async fn fetch_preview_env_vars(
    http_client: &Client,
    backend_url: &str,
    token: &str,
    project: &str,
    deployment_group: &str,
) -> Result<(Vec<(String, String)>, Vec<String>)> {
    let url = format!(
        "{}/api/v1/projects/{}/env/preview?deployment_group={}",
        backend_url, project, deployment_group
    );

    let response = http_client
        .get(&url)
        .header("Authorization", format!("Bearer {}", token))
        .send()
        .await
        .context("Failed to fetch preview environment variables")?;

    if !response.status().is_success() {
        let status = response.status();
        let error_text = response
            .text()
            .await
            .unwrap_or_else(|_| "Unknown error".to_string());
        anyhow::bail!(
            "Failed to fetch preview environment variables (status {}): {}",
            status,
            error_text
        );
    }

    let env_response: EnvVarsResponse = response
        .json()
        .await
        .context("Failed to parse preview environment variables response")?;

    let mut loadable_vars = Vec::new();
    let mut protected_keys = Vec::new();

    for var in env_response.env_vars {
        if var.is_protected {
            protected_keys.push(var.key);
        } else {
            loadable_vars.push((var.key, var.value));
        }
    }

    Ok((loadable_vars, protected_keys))
}

/// Set an environment variable for a project
#[allow(clippy::too_many_arguments)]
pub async fn set_env(
    http_client: &Client,
    backend_url: &str,
    token: &str,
    project: &str,
    key: &str,
    value: &str,
    is_secret: bool,
    is_protected: bool,
) -> Result<()> {
    let url = format!("{}/api/v1/projects/{}/env/{}", backend_url, project, key);

    let payload = SetEnvVarRequest {
        value: value.to_string(),
        is_secret,
        is_protected,
    };

    let response = http_client
        .put(&url)
        .header("Authorization", format!("Bearer {}", token))
        .json(&payload)
        .send()
        .await
        .context("Failed to set environment variable")?;

    if !response.status().is_success() {
        let status = response.status();
        let error_text = response
            .text()
            .await
            .unwrap_or_else(|_| "Unknown error".to_string());
        anyhow::bail!(
            "Failed to set environment variable (status {}): {}",
            status,
            error_text
        );
    }

    let var_type = if is_secret {
        if is_protected {
            "protected secret"
        } else {
            "unprotected secret"
        }
    } else {
        "plain text"
    };
    println!(
        "✓ Set {} variable '{}' for project '{}'",
        var_type, key, project
    );

    Ok(())
}

/// List environment variables for a project
pub async fn list_env(
    http_client: &Client,
    backend_url: &str,
    token: &str,
    project: &str,
) -> Result<()> {
    let env_vars_response =
        fetch_env_vars_response(http_client, backend_url, token, project).await?;

    if env_vars_response.env_vars.is_empty() {
        println!(
            "No environment variables configured for project '{}'",
            project
        );
        return Ok(());
    }

    let mut table = Table::new();
    table
        .load_preset(UTF8_FULL)
        .apply_modifier(UTF8_ROUND_CORNERS)
        .set_header(vec![
            Cell::new("KEY").add_attribute(Attribute::Bold),
            Cell::new("VALUE").add_attribute(Attribute::Bold),
            Cell::new("TYPE").add_attribute(Attribute::Bold),
            Cell::new("PROTECTED").add_attribute(Attribute::Bold),
        ]);

    for var in env_vars_response.env_vars {
        let var_type = if var.is_secret { "secret" } else { "plain" };
        let protected = if var.is_secret {
            if var.is_protected {
                "yes"
            } else {
                "no"
            }
        } else {
            "-"
        };
        table.add_row(vec![
            Cell::new(&var.key),
            Cell::new(&var.value),
            Cell::new(var_type),
            Cell::new(protected),
        ]);
    }

    println!("{}", table);
    println!("\nProject: {}", project);
    println!("Note: Secret values are always masked for security");

    Ok(())
}

/// Get the value of a specific environment variable
pub async fn get_env(
    http_client: &Client,
    backend_url: &str,
    token: &str,
    project: &str,
    key: &str,
) -> Result<()> {
    // First, fetch the variable to check if it exists and get its metadata
    let env_vars_response =
        fetch_env_vars_response(http_client, backend_url, token, project).await?;

    let env_var = env_vars_response
        .env_vars
        .into_iter()
        .find(|v| v.key == key)
        .ok_or_else(|| anyhow::anyhow!("Environment variable '{}' not found", key))?;

    // If it's a secret and protected, we can't get the value
    if env_var.is_secret && env_var.is_protected {
        anyhow::bail!(
            "Cannot retrieve value: '{}' is a protected secret.\n\
             To make it unprotected, update it with: rise env set {} <value> --secret --protected=false",
            key, key
        );
    }

    // If it's an unprotected secret, fetch the decrypted value
    if env_var.is_secret && !env_var.is_protected {
        let url = format!(
            "{}/api/v1/projects/{}/env/{}/value",
            backend_url, project, key
        );

        let response = http_client
            .get(&url)
            .header("Authorization", format!("Bearer {}", token))
            .send()
            .await
            .context("Failed to get environment variable value")?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            anyhow::bail!(
                "Failed to get environment variable value (status {}): {}",
                status,
                error_text
            );
        }

        #[derive(Debug, serde::Deserialize)]
        struct EnvVarValueResponse {
            value: String,
        }

        let value_response: EnvVarValueResponse = response
            .json()
            .await
            .context("Failed to parse environment variable value response")?;

        // Print just the value (useful for scripting)
        println!("{}", value_response.value);
    } else {
        // For non-secret variables, the value is already in the response
        println!("{}", env_var.value);
    }

    Ok(())
}

/// Delete an environment variable from a project
pub async fn unset_env(
    http_client: &Client,
    backend_url: &str,
    token: &str,
    project: &str,
    key: &str,
) -> Result<()> {
    let url = format!("{}/api/v1/projects/{}/env/{}", backend_url, project, key);

    let response = http_client
        .delete(&url)
        .header("Authorization", format!("Bearer {}", token))
        .send()
        .await
        .context("Failed to delete environment variable")?;

    if !response.status().is_success() {
        let status = response.status();
        let error_text = response
            .text()
            .await
            .unwrap_or_else(|_| "Unknown error".to_string());
        anyhow::bail!(
            "Failed to delete environment variable (status {}): {}",
            status,
            error_text
        );
    }

    println!("✓ Deleted variable '{}' from project '{}'", key, project);

    Ok(())
}

/// Import environment variables from a file
///
/// File format:
/// - Lines starting with # are comments
/// - Empty lines are ignored
/// - Format: KEY=value (plain text) or KEY=secret:value (secret)
/// - Example:
///   ```
///   # Database configuration
///   DB_HOST=localhost
///   DB_PASSWORD=secret:my-secret-password
///   ```
pub async fn import_env(
    http_client: &Client,
    backend_url: &str,
    token: &str,
    project: &str,
    file_path: &PathBuf,
) -> Result<()> {
    let contents = std::fs::read_to_string(file_path)
        .with_context(|| format!("Failed to read file: {}", file_path.display()))?;

    let mut success_count = 0;
    let mut error_count = 0;

    for (line_num, line) in contents.lines().enumerate() {
        let line = line.trim();

        // Skip comments and empty lines
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        // Parse KEY=value
        let parts: Vec<&str> = line.splitn(2, '=').collect();
        if parts.len() != 2 {
            eprintln!(
                "Warning: Line {} has invalid format (expected KEY=value): {}",
                line_num + 1,
                line
            );
            error_count += 1;
            continue;
        }

        let key = parts[0].trim();
        let value_part = parts[1];

        // Check if value is secret
        let (value, is_secret) = if let Some(stripped) = value_part.strip_prefix("secret:") {
            (stripped, true)
        } else {
            (value_part, false)
        };

        // Validate key name (alphanumeric and underscore only)
        if !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
            eprintln!(
                "Warning: Line {} has invalid key name '{}' (must be alphanumeric with underscores)",
                line_num + 1,
                key
            );
            error_count += 1;
            continue;
        }

        // Set the variable
        // Protected defaults to true for secrets, false for non-secrets
        let is_protected = is_secret;
        match set_env(
            http_client,
            backend_url,
            token,
            project,
            key,
            value,
            is_secret,
            is_protected,
        )
        .await
        {
            Ok(_) => success_count += 1,
            Err(e) => {
                eprintln!(
                    "Warning: Failed to set variable '{}' from line {}: {}",
                    key,
                    line_num + 1,
                    e
                );
                error_count += 1;
            }
        }
    }

    println!(
        "\n✓ Import complete: {} variables set, {} errors",
        success_count, error_count
    );

    if error_count > 0 {
        anyhow::bail!("Import completed with {} errors", error_count);
    }

    Ok(())
}

/// List environment variables for a deployment (read-only)
pub async fn list_deployment_env(
    http_client: &Client,
    backend_url: &str,
    token: &str,
    project: &str,
    deployment_id: &str,
) -> Result<()> {
    let url = format!(
        "{}/api/v1/projects/{}/deployments/{}/env",
        backend_url, project, deployment_id
    );

    let response = http_client
        .get(&url)
        .header("Authorization", format!("Bearer {}", token))
        .send()
        .await
        .context("Failed to list deployment environment variables")?;

    if !response.status().is_success() {
        let status = response.status();
        let error_text = response
            .text()
            .await
            .unwrap_or_else(|_| "Unknown error".to_string());
        anyhow::bail!(
            "Failed to list deployment environment variables (status {}): {}",
            status,
            error_text
        );
    }

    let env_vars_response: EnvVarsResponse = response
        .json()
        .await
        .context("Failed to parse environment variables response")?;

    if env_vars_response.env_vars.is_empty() {
        println!(
            "No environment variables configured for deployment '{}' in project '{}'",
            deployment_id, project
        );
        return Ok(());
    }

    let mut table = Table::new();
    table
        .load_preset(UTF8_FULL)
        .apply_modifier(UTF8_ROUND_CORNERS)
        .set_header(vec![
            Cell::new("KEY").add_attribute(Attribute::Bold),
            Cell::new("VALUE").add_attribute(Attribute::Bold),
            Cell::new("TYPE").add_attribute(Attribute::Bold),
        ]);

    for var in env_vars_response.env_vars {
        let var_type = if var.is_secret { "secret" } else { "plain" };
        table.add_row(vec![
            Cell::new(&var.key),
            Cell::new(&var.value),
            Cell::new(var_type),
        ]);
    }

    println!("{}", table);
    println!("\nProject: {}", project);
    println!("Deployment: {}", deployment_id);
    println!("Note: Secret values are always masked for security");
    println!("Note: Deployment environment variables are read-only snapshots");

    Ok(())
}