tvc 0.7.0

CLI for Turnkey Verifiable Cloud
Documentation
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
//! Deploy create command - creates a deployment from a config file or CLI flags.

use crate::client::build_client;
use crate::config::deploy::DeployConfig;
use crate::pull_secret::encrypt_pivot_pull_secret;
use anyhow::{bail, Context, Result};
use clap::Args as ClapArgs;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use turnkey_client::generated::{CreateTvcDeploymentIntent, ValidateTvcImageRequest};

pub(crate) const LONG_ABOUT: &str = "\
Create a new TVC deployment.

Use --config-file, flags, env vars, or a mix of them. Command-line flags
override env vars; env vars override config file values. If --config-file is
omitted, all required deployment fields must be provided by flags or env vars.

Required deployment fields:
  --app-id / TVC_APP_ID
  --qos-version / TVC_QOS_VERSION
  --pivot-image-url / TVC_PIVOT_IMAGE_URL
  --pivot-path / TVC_PIVOT_PATH
  --expected-pivot-digest / TVC_EXPECTED_PIVOT_DIGEST

Special rules:
  --pivot-args replaces the config file's list entirely (does not append).
  --debug-mode can enable debug mode but cannot disable a true config value.
  --pivot-pull-secret reads an unencrypted pull secret file, encrypts it for the
  active org's API environment, and overrides the encrypted secret in the config.

Examples:
  tvc deploy create --config-file deploy.json

  # OR

  TVC_ORG_ID=... \\
  TVC_API_KEY_PUBLIC=... \\
  TVC_API_KEY_PRIVATE=... \\
  TVC_APP_ID=... \\
  TVC_QOS_VERSION=... \\
  TVC_PIVOT_PATH=... \\
  TVC_PIVOT_IMAGE_URL=... \\
  TVC_EXPECTED_PIVOT_DIGEST=... \\
    tvc deploy create";

/// Create a new TVC deployment from a config file or CLI flags.
#[derive(Debug, ClapArgs)]
#[command(about, long_about = None)]
pub struct Args {
    /// Path to the deployment configuration file (JSON).
    /// Optional when all required fields are provided via flags or env.
    #[arg(short = 'c', long, value_name = "PATH", env = "TVC_DEPLOY_CONFIG")]
    pub config_file: Option<PathBuf>,

    /// Override the appId field.
    #[arg(long, env = "TVC_APP_ID")]
    pub app_id: Option<String>,

    /// Override the qosVersion field.
    #[arg(long, env = "TVC_QOS_VERSION")]
    pub qos_version: Option<String>,

    /// Override the pivotContainerImageUrl field.
    #[arg(long, env = "TVC_PIVOT_IMAGE_URL")]
    pub pivot_image_url: Option<String>,

    /// Override the expectedPivotDigest field.
    #[arg(long, env = "TVC_EXPECTED_PIVOT_DIGEST")]
    pub expected_pivot_digest: Option<String>,

    /// Override the pivotPath field.
    #[arg(long, env = "TVC_PIVOT_PATH")]
    pub pivot_path: Option<String>,

    /// Override pivotArgs (replaces the file's list entirely; not appended).
    #[arg(
        long,
        value_name = "ARG",
        value_delimiter = ',',
        env = "TVC_PIVOT_ARGS"
    )]
    pub pivot_args: Vec<String>,

    /// Enable debug mode. One-way: cannot disable a `true` set earlier via the file.
    #[arg(long, env = "TVC_DEBUG_MODE")]
    pub debug_mode: bool,

    /// Override the healthCheckPort field.
    #[arg(long, env = "TVC_HEALTH_CHECK_PORT")]
    pub health_check_port: Option<u16>,

    /// Override the publicIngressPort field.
    #[arg(long, env = "TVC_PUBLIC_INGRESS_PORT")]
    pub public_ingress_port: Option<u16>,

    /// Path to an unencrypted pivot container pull secret file.
    ///
    /// The content will be encrypted based on the active org's API environment and
    /// override `pivotContainerEncryptedPullSecret` from the config file.
    #[arg(long, value_name = "PATH", env = "TVC_PIVOT_PULL_SECRET")]
    pub pivot_pull_secret: Option<PathBuf>,
}

fn build_validate_image_request(
    organization_id: &str,
    image_url: &str,
    pivot_container_encrypted_pull_secret: Option<String>,
) -> ValidateTvcImageRequest {
    ValidateTvcImageRequest {
        organization_id: organization_id.to_string(),
        pivot_container_image_url: image_url.to_string(),
        pivot_container_encrypted_pull_secret,
    }
}

fn build_create_intent(
    deploy_config: &DeployConfig,
    pivot_container_image_url: String,
    pivot_container_encrypted_pull_secret: Option<String>,
) -> CreateTvcDeploymentIntent {
    CreateTvcDeploymentIntent {
        app_id: deploy_config.app_id.clone(),
        qos_version: deploy_config.qos_version.clone(),
        pivot_container_image_url,
        pivot_path: deploy_config.pivot_path.clone(),
        pivot_args: deploy_config.pivot_args.clone(),
        expected_pivot_digest: deploy_config.expected_pivot_digest.clone(),
        pivot_container_encrypted_pull_secret,
        debug_mode: deploy_config.debug_mode,
        nonce: None,
        health_check_type: deploy_config.health_check_type,
        health_check_port: deploy_config.health_check_port as u32,
        public_ingress_port: deploy_config.public_ingress_port as u32,
    }
}

fn pin_image_url(image_url: &str, resolved_digest: &str) -> String {
    if image_url.contains("@") {
        image_url.to_string()
    } else {
        format!("{image_url}@{resolved_digest}") // works for docker pull even if image_url included a :tag
    }
}

fn apply_overrides(config: &mut DeployConfig, args: &Args) {
    if let Some(v) = &args.app_id {
        config.app_id = v.clone();
    }
    if let Some(v) = &args.qos_version {
        config.qos_version = v.clone();
    }
    if let Some(v) = &args.pivot_image_url {
        config.pivot_container_image_url = v.clone();
    }
    if let Some(v) = &args.expected_pivot_digest {
        config.expected_pivot_digest = v.clone();
    }
    if let Some(v) = &args.pivot_path {
        config.pivot_path = v.clone();
    }
    if !args.pivot_args.is_empty() {
        config.pivot_args = args.pivot_args.clone();
    }
    // One-way: only ever flips false -> true.
    if args.debug_mode {
        config.debug_mode = Some(true);
    }
    if let Some(v) = args.health_check_port {
        config.health_check_port = v;
    }
    if let Some(v) = args.public_ingress_port {
        config.public_ingress_port = v;
    }
}

fn resolve_deploy_config(args: &Args) -> Result<DeployConfig> {
    let mut config = match &args.config_file {
        Some(path) => {
            let content = std::fs::read_to_string(path)
                .with_context(|| format!("failed to read config file: {}", path.display()))?;
            serde_json::from_str(&content)
                .with_context(|| format!("failed to parse config file: {}", path.display()))?
        }
        None => {
            let mut t = DeployConfig::template(None);
            // Strip the template's "<REMOVE_ME...>" hint so flag-only mode
            // doesn't ship it to the API for public images.
            t.pivot_container_encrypted_pull_secret = None;
            t
        }
    };

    apply_overrides(&mut config, args);

    let missing = config.missing_required_fields();
    if !missing.is_empty() {
        let suggestion = if args.config_file.is_some() {
            "Edit the config file or override via flag/TVC_* env."
        } else {
            "Provide via flag, TVC_* env, or --config-file."
        };
        bail!(
            "missing required values: {}. {suggestion}",
            missing.join(", ")
        );
    }

    Ok(config)
}

/// Run the deploy create command.
pub async fn run(args: Args) -> Result<()> {
    let deploy_config = resolve_deploy_config(&args)?;

    println!("Creating deployment for app '{}'...", deploy_config.app_id);

    // Build authenticated client
    let auth = build_client().await?;

    let pivot_container_encrypted_pull_secret = match args.pivot_pull_secret.as_ref() {
        Some(path) => {
            let pull_secret = std::fs::read_to_string(path).with_context(|| {
                format!("failed to read pivot pull secret file: {}", path.display())
            })?;

            if pull_secret.trim().is_empty() {
                bail!(
                    "pivot pull secret file is empty after trimming whitespace: {}",
                    path.display()
                );
            }

            Some(encrypt_pivot_pull_secret(&pull_secret, &auth.api_base_url)?)
        }
        None => deploy_config.pivot_container_encrypted_pull_secret.clone(),
    };

    let validate_image_request = build_validate_image_request(
        &auth.org_id,
        &deploy_config.pivot_container_image_url,
        pivot_container_encrypted_pull_secret.clone(),
    );

    let validate_image_response = auth
        .client
        .validate_tvc_image(validate_image_request)
        .await
        .context("failed to validate TVC image")?;

    let pinned_image_url = pin_image_url(
        &deploy_config.pivot_container_image_url,
        &validate_image_response.resolved_image_digest,
    );

    if pinned_image_url != deploy_config.pivot_container_image_url {
        println!("Using pinned image reference for deployment request: {pinned_image_url}");
    }

    let intent = build_create_intent(
        &deploy_config,
        pinned_image_url,
        pivot_container_encrypted_pull_secret,
    );

    // Get timestamp
    let timestamp_ms = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .context("system time before unix epoch")?
        .as_millis();

    // Create the deployment
    let result = auth
        .client
        .create_tvc_deployment(auth.org_id, timestamp_ms, intent)
        .await
        .context("failed to create TVC deployment")?;

    println!();
    println!("Deployment created successfully!");
    println!();
    println!("Deployment ID: {}", result.result.deployment_id);
    println!("App ID: {}", deploy_config.app_id);
    if let Some(path) = &args.config_file {
        println!("Config: {}", path.display());
    }
    println!();
    println!("Next steps:");
    println!(
        "  - Run `WIP: tvc deploy status {}` to check deployment status",
        result.result.deployment_id
    );
    println!(
        "  - Run `tvc deploy approve --deploy-id {}` to approve the manifest",
        result.result.deployment_id
    );

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn pin_image_url_appends_digest_to_tagged_reference() {
        let pinned = pin_image_url("ghcr.io/team/app:latest", "sha256:abc123");
        assert_eq!(pinned, "ghcr.io/team/app:latest@sha256:abc123");
    }

    #[test]
    fn pin_image_url_appends_digest_to_untagged_reference() {
        let pinned = pin_image_url("ghcr.io/team/app", "sha256:abc123");
        assert_eq!(pinned, "ghcr.io/team/app@sha256:abc123");
    }

    fn empty_args() -> Args {
        Args {
            config_file: None,
            app_id: None,
            qos_version: None,
            pivot_image_url: None,
            expected_pivot_digest: None,
            pivot_path: None,
            pivot_args: vec![],
            debug_mode: false,
            health_check_port: None,
            public_ingress_port: None,
            pivot_pull_secret: None,
        }
    }

    fn all_required_flags() -> Args {
        Args {
            app_id: Some("flag-app-id".into()),
            qos_version: Some("flag-qos".into()),
            pivot_image_url: Some("flag-image".into()),
            expected_pivot_digest: Some("flag-digest".into()),
            pivot_path: Some("flag-path".into()),
            ..empty_args()
        }
    }

    fn file_config() -> DeployConfig {
        let mut c = DeployConfig::template(None);
        c.app_id = "file-app-id".into();
        c.qos_version = "file-qos".into();
        c.pivot_container_image_url = "file-image".into();
        c.pivot_path = "file-path".into();
        c.pivot_args = vec!["a".into(), "b".into()];
        c.expected_pivot_digest = "file-digest".into();
        c.debug_mode = Some(false);
        c.pivot_container_encrypted_pull_secret = None;
        c.health_check_port = 4000;
        c.public_ingress_port = 5000;
        c
    }

    fn write_config(config: &DeployConfig) -> NamedTempFile {
        let mut f = NamedTempFile::new().unwrap();
        f.write_all(serde_json::to_string(config).unwrap().as_bytes())
            .unwrap();
        f
    }

    #[test]
    fn flag_overrides_file_value() {
        let file = write_config(&file_config());
        let args = Args {
            config_file: Some(file.path().to_path_buf()),
            app_id: Some("flag-app-id".into()),
            ..empty_args()
        };
        let resolved = resolve_deploy_config(&args).unwrap();
        assert_eq!(resolved.app_id, "flag-app-id");
        // Untouched fields keep their file values.
        assert_eq!(resolved.qos_version, "file-qos");
        assert_eq!(resolved.health_check_port, 4000);
    }

    #[test]
    fn file_value_used_when_flag_absent() {
        let file = write_config(&file_config());
        let args = Args {
            config_file: Some(file.path().to_path_buf()),
            ..empty_args()
        };
        let resolved = resolve_deploy_config(&args).unwrap();
        assert_eq!(resolved.app_id, "file-app-id");
        assert_eq!(resolved.qos_version, "file-qos");
        assert_eq!(resolved.health_check_port, 4000);
    }

    #[test]
    fn no_file_uses_flag_only_with_template_defaults() {
        let resolved = resolve_deploy_config(&all_required_flags()).unwrap();
        // Required fields come from flags.
        assert_eq!(resolved.app_id, "flag-app-id");
        assert_eq!(resolved.qos_version, "flag-qos");
        assert_eq!(resolved.pivot_container_image_url, "flag-image");
        assert_eq!(resolved.pivot_path, "flag-path");
        assert_eq!(resolved.expected_pivot_digest, "flag-digest");
        // Optional fields fall back to template defaults.
        assert_eq!(resolved.health_check_port, 3000);
        assert_eq!(resolved.public_ingress_port, 3000);
        assert_eq!(resolved.debug_mode, Some(false));
        assert!(resolved.pivot_args.is_empty());
        // Pull-secret placeholder cleared in flag-only mode.
        assert_eq!(resolved.pivot_container_encrypted_pull_secret, None);
    }

    #[test]
    fn no_file_no_required_flags_bails_naming_each_flag() {
        let err = resolve_deploy_config(&empty_args()).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("--app-id"), "{msg}");
        assert!(msg.contains("--qos-version"), "{msg}");
        assert!(msg.contains("--pivot-image-url"), "{msg}");
        assert!(msg.contains("--pivot-path"), "{msg}");
        assert!(msg.contains("--expected-pivot-digest"), "{msg}");
    }

    #[test]
    fn pivot_args_flag_replaces_file_list() {
        let file = write_config(&file_config()); // file has ["a", "b"]
        let args = Args {
            config_file: Some(file.path().to_path_buf()),
            pivot_args: vec!["c".into()],
            ..empty_args()
        };
        let resolved = resolve_deploy_config(&args).unwrap();
        assert_eq!(resolved.pivot_args, vec!["c"]);
    }
}