tvc 0.13.1

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
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
//! Deploy provisioning-details command.

use crate::outcome::Outcome;
use crate::output::StdCtx;
use crate::provisioning::{
    ProvisionBundle, extract_ephemeral_public_key_bytes, fetch_provisioning_details,
    verify_provisioning_details,
};
use crate::util::write_file;
use anyhow::Context;
use clap::Args as ClapArgs;
use qos_core::protocol::services::boot::{Approval, VersionedManifestEnvelope};
use qos_nsm::types::NsmDigest;
use serde::Serialize;
use std::fmt::Write;
use std::fmt::{self, Display, Formatter};
use std::path::{Path, PathBuf};
use uuid::Uuid;

/// Get provisioning details for a deployment.
#[derive(Debug, ClapArgs)]
#[command(about, long_about = None)]
pub struct Args {
    /// ID of the deployment.
    #[arg(short = 'd', long, env = "TVC_DEPLOY_ID")]
    pub deploy_id: Uuid,

    /// Never use for sensitive applications! Skip attestation, PCR, and approval verification.
    #[arg(long, env = "TVC_DANGEROUS_SKIP_VERIFICATION")]
    pub dangerous_skip_verification: bool,

    /// Write provisioning details to a local json bundle usable during re-encryption.
    #[arg(long, value_name = "PATH", env = "TVC_PROVISION_BUNDLE_OUT")]
    pub provision_bundle_out: Option<PathBuf>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct ApprovalSummary {
    alias: String,
    public_key: Vec<u8>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct AttestationSummary {
    ephemeral_key: Vec<u8>,
    module_id: String,
    digest: NsmDigest,
    timestamp_ms: u64,
    user_data: Option<Vec<u8>>,
    nonce: Option<Vec<u8>>,
    pcrs: Vec<(usize, Vec<u8>)>,
    certificate_len: usize,
    ca_bundle_cert_count: usize,
    manifest_set_threshold: u32,
    manifest_set_approvals: Vec<ApprovalSummary>,
    share_set_approvals: Vec<ApprovalSummary>,
}

const SUMMARY_PCR_MAX_INDEX: usize = 17;

/// Run the deploy provisioning-details command.
pub async fn run(_ctx: &mut StdCtx, args: Args) -> anyhow::Result<Outcome> {
    let auth = crate::client::build_client().await?;
    let details = fetch_provisioning_details(&auth, &args.deploy_id).await?;

    let summary = build_summary_with_optional_verify(
        details.attestation_document(),
        details.manifest_envelope(),
        args.dangerous_skip_verification,
        None,
    )?;
    let (deployment_id, attestation_document, manifest_envelope, fetched_at_unix_ms) =
        details.into_parts();

    let bundle_path = match args.provision_bundle_out.as_ref() {
        Some(path) => {
            let bundle = ProvisionBundle::new(
                deployment_id.to_string(),
                &attestation_document,
                manifest_envelope,
                fetched_at_unix_ms,
                &summary.ephemeral_key,
            );
            write_provision_bundle(path, &bundle).await?;
            Some(path.display().to_string())
        }
        None => None,
    };

    let verification_status = if args.dangerous_skip_verification {
        "skipped attestation, PCR, and approval verification (--dangerous-skip-verification)"
    } else {
        "verified (attestation + approvals)"
    };

    Ok(Outcome::DeployProvisioningDetails(
        ProvisioningDetails::from_summary(
            deployment_id.to_string(),
            verification_status,
            bundle_path,
            &summary,
        ),
    ))
}

async fn write_provision_bundle(path: &Path, bundle: &ProvisionBundle) -> anyhow::Result<()> {
    let contents =
        serde_json::to_vec_pretty(bundle).context("failed to serialize provision bundle")?;
    write_file(path, &contents).await?;
    Ok(())
}

fn build_summary_with_optional_verify(
    cose_sign1_der: &[u8],
    manifest_envelope: &VersionedManifestEnvelope,
    dangerous_skip_verification: bool,
    validation_time_override: Option<u64>,
) -> anyhow::Result<AttestationSummary> {
    let mut attestation_doc = if dangerous_skip_verification {
        qos_nsm::nitro::unsafe_attestation_doc_from_der(cose_sign1_der)
            .context("failed to parse attestation document")?
    } else {
        verify_provisioning_details(cose_sign1_der, manifest_envelope, validation_time_override)?
    };

    let manifest = manifest_envelope.clone().manifest();

    Ok(AttestationSummary {
        ephemeral_key: extract_ephemeral_public_key_bytes(
            attestation_doc
                .public_key
                .as_ref()
                .map(|public_key| public_key.as_ref()),
        )?,
        user_data: attestation_doc
            .user_data
            .take()
            .map(|user_data| user_data.into_vec()),
        nonce: attestation_doc.nonce.take().map(|nonce| nonce.into_vec()),
        pcrs: std::mem::take(&mut attestation_doc.pcrs)
            .into_iter()
            .filter(|(index, _)| *index <= SUMMARY_PCR_MAX_INDEX)
            .map(|(index, pcr)| (index, pcr.into_vec()))
            .collect(),
        certificate_len: attestation_doc.certificate.len(),
        ca_bundle_cert_count: attestation_doc.cabundle.len(),
        manifest_set_threshold: manifest.manifest_set().threshold,
        manifest_set_approvals: approval_summaries(manifest_envelope.manifest_set_approvals()),
        share_set_approvals: approval_summaries(manifest_envelope.share_set_approvals()),
        module_id: attestation_doc.module_id,
        digest: attestation_doc.digest.into(),
        timestamp_ms: attestation_doc.timestamp,
    })
}

fn approval_summaries(approvals: &[Approval]) -> Vec<ApprovalSummary> {
    approvals
        .iter()
        .map(|approval| ApprovalSummary {
            alias: approval.member.alias.clone(),
            public_key: approval.member.pub_key.clone(),
        })
        .collect()
}

/// Wide terminal outcome for `deploy provisioning-details`. Byte fields are
/// hex-encoded; `digest` carries the Debug rendering of the NSM digest so the
/// same string serves both the payload and the human line.
#[derive(Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProvisioningDetails {
    deployment_id: String,
    verification: String,
    ephemeral_key: String,
    module_id: String,
    digest: String,
    timestamp_ms: u64,
    user_data: Option<String>,
    nonce: Option<String>,
    pcrs: Vec<PcrEntry>,
    certificate_length: usize,
    ca_bundle_certificates: usize,
    manifest_set_threshold: u32,
    manifest_set_approvals: Vec<ApprovalEntry>,
    share_set_approvals: Vec<ApprovalEntry>,
    /// Present when `--provision-bundle-out` wrote a bundle file.
    #[serde(skip_serializing_if = "Option::is_none")]
    bundle_path: Option<String>,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct PcrEntry {
    index: usize,
    value: String,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ApprovalEntry {
    alias: String,
    public_key: String,
}

impl ProvisioningDetails {
    fn from_summary(
        deployment_id: String,
        verification: &str,
        bundle_path: Option<String>,
        summary: &AttestationSummary,
    ) -> Self {
        Self {
            deployment_id,
            verification: verification.to_string(),
            ephemeral_key: hex::encode(&summary.ephemeral_key),
            module_id: summary.module_id.clone(),
            digest: format!("{:?}", summary.digest),
            timestamp_ms: summary.timestamp_ms,
            user_data: summary.user_data.as_ref().map(hex::encode),
            nonce: summary.nonce.as_ref().map(hex::encode),
            pcrs: summary
                .pcrs
                .iter()
                .map(|(index, pcr)| PcrEntry {
                    index: *index,
                    value: hex::encode(pcr),
                })
                .collect(),
            certificate_length: summary.certificate_len,
            ca_bundle_certificates: summary.ca_bundle_cert_count,
            manifest_set_threshold: summary.manifest_set_threshold,
            manifest_set_approvals: approval_entries(&summary.manifest_set_approvals),
            share_set_approvals: approval_entries(&summary.share_set_approvals),
            bundle_path,
        }
    }
}

fn approval_entries(approvals: &[ApprovalSummary]) -> Vec<ApprovalEntry> {
    approvals
        .iter()
        .map(|approval| ApprovalEntry {
            alias: approval.alias.clone(),
            public_key: hex::encode(&approval.public_key),
        })
        .collect()
}

impl Display for ProvisioningDetails {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let mut message = String::new();

        if let Some(path) = &self.bundle_path {
            let _ = write!(message, "Provision bundle written to: {path}\n\n");
        }

        // Fixed attestation summary; `PCRs:` deliberately has no trailing
        // newline so the PCR loop below appends its own leading-newline lines
        // (and the section reads correctly even when there are no PCRs).
        let _ = write!(
            message,
            r#"Deployment: {}
Verification: {}
Ephemeral Key: {}
Module ID: {}
Digest: {}
Timestamp (ms): {}
User Data: {}
Nonce: {}
PCRs:"#,
            self.deployment_id,
            self.verification,
            self.ephemeral_key,
            self.module_id,
            self.digest,
            self.timestamp_ms,
            self.user_data.as_deref().unwrap_or("(none)"),
            self.nonce.as_deref().unwrap_or("(none)"),
        );

        for pcr in &self.pcrs {
            let label = match pcr.index {
                16 => " (setup manifest/key commitment)",
                17 => " (live manifest/key commitment)",
                _ => "",
            };
            let _ = write!(message, "\n  PCR{}{label}: {}", pcr.index, pcr.value);
        }

        let _ = write!(
            message,
            r#"
Certificate Length: {} bytes
CA Bundle Certificates: {}
Manifest Set Approvals: {}/{}"#,
            self.certificate_length,
            self.ca_bundle_certificates,
            self.manifest_set_approvals.len(),
            self.manifest_set_threshold,
        );
        write_approval_entries(&mut message, &self.manifest_set_approvals);

        if self.share_set_approvals.is_empty() {
            let _ = write!(message, "\nShare Set Approvals: (none)");
        } else {
            let _ = write!(
                message,
                "\nShare Set Approvals: {}",
                self.share_set_approvals.len()
            );
            write_approval_entries(&mut message, &self.share_set_approvals);
        }

        f.write_str(&message)
    }
}

fn write_approval_entries(message: &mut String, approvals: &[ApprovalEntry]) {
    for approval in approvals {
        let _ = write!(message, "\n  {}: {}", approval.alias, approval.public_key);
    }
}

#[cfg(test)]
mod tests {
    use super::build_summary_with_optional_verify;
    use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
    use qos_core::protocol::services::boot::VersionedManifestEnvelope;
    use serde::Deserialize;

    #[derive(Debug, Deserialize)]
    struct ValidProvisioningDetailsFixture {
        validation_time_secs: u64,
        attestation_document_cose_sign1_base64: String,
        manifest_envelope: VersionedManifestEnvelope,
    }

    fn valid_provisioning_details_fixture() -> ValidProvisioningDetailsFixture {
        serde_json::from_str(include_str!(
            "../../../fixtures/valid_provisioning_details.json"
        ))
        .unwrap()
    }

    #[test]
    fn build_summary_accepts_real_fixture() {
        let fixture = valid_provisioning_details_fixture();
        let attestation_document = BASE64_STANDARD
            .decode(&fixture.attestation_document_cose_sign1_base64)
            .unwrap();

        let summary = build_summary_with_optional_verify(
            &attestation_document,
            &fixture.manifest_envelope,
            false,
            Some(fixture.validation_time_secs),
        )
        .unwrap();

        let manifest = fixture.manifest_envelope.clone().manifest();
        assert!(!summary.ephemeral_key.is_empty());
        assert_eq!(
            summary.manifest_set_threshold,
            manifest.manifest_set().threshold
        );
        assert_eq!(
            summary.manifest_set_approvals.len(),
            fixture.manifest_envelope.manifest_set_approvals().len()
        );
    }

    #[test]
    fn build_summary_rejects_real_fixture_with_missing_manifest_approval() {
        let fixture = valid_provisioning_details_fixture();
        let attestation_document = BASE64_STANDARD
            .decode(&fixture.attestation_document_cose_sign1_base64)
            .unwrap();
        let mut manifest_envelope = fixture.manifest_envelope;
        match &mut manifest_envelope {
            VersionedManifestEnvelope::V2(envelope) => envelope.manifest_set_approvals.clear(),
            VersionedManifestEnvelope::V1(envelope) => envelope.manifest_set_approvals.clear(),
            VersionedManifestEnvelope::V0(envelope) => envelope.manifest_set_approvals.clear(),
        }

        assert!(
            build_summary_with_optional_verify(
                &attestation_document,
                &manifest_envelope,
                false,
                Some(fixture.validation_time_secs),
            )
            .is_err()
        );
    }

    use super::{ApprovalEntry, PcrEntry, ProvisioningDetails};

    fn full_details() -> ProvisioningDetails {
        ProvisioningDetails {
            deployment_id: "dep_123".to_string(),
            verification: "verified".to_string(),
            ephemeral_key: "abcd".to_string(),
            module_id: "mod-1".to_string(),
            digest: "SHA384".to_string(),
            timestamp_ms: 1_700_000_000_000,
            user_data: Some("aa".to_string()),
            nonce: Some("bb".to_string()),
            pcrs: vec![
                PcrEntry {
                    index: 0,
                    value: "00".to_string(),
                },
                PcrEntry {
                    index: 16,
                    value: "1616".to_string(),
                },
                PcrEntry {
                    index: 17,
                    value: "1717".to_string(),
                },
            ],
            certificate_length: 1234,
            ca_bundle_certificates: 3,
            manifest_set_threshold: 2,
            manifest_set_approvals: vec![
                ApprovalEntry {
                    alias: "alice".to_string(),
                    public_key: "aaaa".to_string(),
                },
                ApprovalEntry {
                    alias: "bob".to_string(),
                    public_key: "bbbb".to_string(),
                },
            ],
            share_set_approvals: vec![ApprovalEntry {
                alias: "carol".to_string(),
                public_key: "cccc".to_string(),
            }],
            bundle_path: Some("/tmp/bundle.json".to_string()),
        }
    }

    #[test]
    fn human_message_full_golden() {
        assert_eq!(
            full_details().to_string(),
            r#"Provision bundle written to: /tmp/bundle.json

Deployment: dep_123
Verification: verified
Ephemeral Key: abcd
Module ID: mod-1
Digest: SHA384
Timestamp (ms): 1700000000000
User Data: aa
Nonce: bb
PCRs:
  PCR0: 00
  PCR16 (setup manifest/key commitment): 1616
  PCR17 (live manifest/key commitment): 1717
Certificate Length: 1234 bytes
CA Bundle Certificates: 3
Manifest Set Approvals: 2/2
  alice: aaaa
  bob: bbbb
Share Set Approvals: 1
  carol: cccc"#
        );
    }

    #[test]
    fn human_message_minimal_golden() {
        let details = ProvisioningDetails::default();
        // NOTE: the first five lines have empty values, so they end in a
        // significant trailing space — do not strip trailing whitespace here.
        assert_eq!(
            details.to_string(),
            r#"Deployment: 
Verification: 
Ephemeral Key: 
Module ID: 
Digest: 
Timestamp (ms): 0
User Data: (none)
Nonce: (none)
PCRs:
Certificate Length: 0 bytes
CA Bundle Certificates: 0
Manifest Set Approvals: 0/0
Share Set Approvals: (none)"#
        );
    }
}