tvc 0.14.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
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
//! Approve deploy command - cryptographically approve a QOS manifest.

use crate::{
    approvals::{ApprovalVerdict, OperatorApproval, ValidatedManifest},
    client::build_client,
    commands::Run,
    config::turnkey::Config,
    errors::MissingResource,
    local_operator_key::LocalOperatorSeedSource,
    operator::{OperatorCtx, ResolvedOperator, resolve_operator},
    outcome::Outcome,
    output::StdCtx,
    pair::HexSeed,
    prompts::{self, bail_required_in_non_interactive, stdin_can_prompt},
    shell_print, shell_println,
    util::{read_file_to_string, write_file},
};
use anyhow::{Context, bail};
use clap::{ArgGroup, Args as ClapArgs};
use displaydoc::Display;
use qos_core::protocol::services::boot::{
    Approval, ManifestSet, Namespace, NitroConfig, QuorumMember, ShareSet, VersionedManifest,
};
use serde::Serialize;
use std::fmt::{self, Formatter, Write};
use std::time::{SystemTime, UNIX_EPOCH};
use std::{
    ops::Deref,
    path::{Path, PathBuf},
};
use tracing::{debug, instrument};
use turnkey_client::generated::{
    CreateTvcManifestApprovalsIntent, GetTvcDeploymentRequest, TvcManifestApproval,
};
use uuid::Uuid;

const QUORUM_REACHED_MESSAGE: &str =
    "Manifest approval quorum reached. Your deployment will be available soon.";

/// Cryptographically approve a QOS manifest for a deployment with your operator's manifest set key.
#[derive(Debug, ClapArgs)]
#[command(about, long_about = None)]
#[command(group(ArgGroup::new("manifest-source").args(["manifest", "deploy_id"])))]
pub struct Args {
    /// Path to QOS manifest file.
    #[arg(
        short,
        long,
        value_name = "PATH",
        env = "TVC_MANIFEST",
        help_heading = "Manifest source (pick one)"
    )]
    pub manifest: Option<PathBuf>,

    /// ID of the deployment the manifest belongs to.
    #[arg(
        short,
        long,
        env = "TVC_DEPLOY_ID",
        help_heading = "Manifest source (pick one)"
    )]
    pub deploy_id: Option<Uuid>,

    /// Turnkey manifest ID (UUID) for the manifest being approved.
    /// Required when posting approval to the API.
    #[arg(long, env = "TVC_MANIFEST_ID")]
    pub manifest_id: Option<Uuid>,

    /// Turnkey operator UUID for the approving operator. When posting without
    /// this flag, TVC selects from the last manifest's saved operator IDs. A
    /// configured hosted operator is selected by its UUID.
    #[arg(long, env = "TVC_OPERATOR_ID")]
    pub operator_id: Option<Uuid>,

    /// Hex-encoded 32-byte master seed for the operator key.
    /// If no seed flag is provided, uses the operator key from the logged-in org config.
    #[arg(
        long,
        value_name = "HEX_SEED",
        env = "TVC_OPERATOR_SEED",
        help_heading = "Operator seed (pick one)"
    )]
    pub operator_seed: Option<HexSeed>,

    /// Path to a file containing the hex-encoded master seed for the operator key.
    #[arg(
        long,
        value_name = "PATH",
        env = "TVC_OPERATOR_SEED_PATH",
        help_heading = "Operator seed (pick one)"
    )]
    pub operator_seed_path: Option<PathBuf>,

    /// Walk through manifest approval prompts but do not generate an approval.
    #[arg(long, env = "TVC_DRY_RUN")]
    pub dry_run: bool,

    /// DANGEROUS: skip interactive prompts for approving each aspect of manifest.
    #[arg(long, env = "TVC_DANGEROUS_SKIP_INTERACTIVE")]
    pub dangerous_skip_interactive: bool,

    /// Write approval to file instead of stdout.
    #[arg(short = 'o', long, value_name = "PATH", env = "TVC_APPROVAL_OUT")]
    pub approval_out: Option<PathBuf>,

    /// Generate a local-operator approval without posting it to the API. This
    /// supports offline signing and cannot be used with a hosted operator.
    #[arg(long, env = "TVC_SKIP_POST")]
    pub skip_post: bool,
}

impl Run for Args {
    type Outcome = ApproveOutcome;

    async fn run(self, ctx: &mut StdCtx) -> anyhow::Result<Self::Outcome> {
        let args = ArgsWithResolvedOperatorSeedSource::try_from(self)?;

        // Manifest review prompts are required unless explicitly skipped;
        // bail before fetching anything if nobody can answer them.
        if !args.dangerous_skip_interactive && (ctx.is_non_interactive() || !stdin_can_prompt()) {
            bail_required_in_non_interactive("--dangerous-skip-interactive")?;
        }

        let (manifest, fetched) = load_manifest(ctx, &args).await?;
        let manifest = ValidatedManifest::try_from(&manifest)?;

        if !args.dangerous_skip_interactive {
            interactive_approve(ctx, &manifest)?;
        }

        let (post_target, operator_id) = build_post_target(
            BuildPostTargetArgs::from(&args),
            fetched.as_ref().map(|(id, _)| *id),
            ctx.is_non_interactive(),
        )
        .await?;

        let inputs = ResolvedApproveInputs {
            manifest,
            operator_seed_source: args.operator_seed_source,
            operator_id,
            approval_out: args.approval_out,
            dry_run: args.dry_run,
            skip_post: args.skip_post,
            post_target,
            posted_approvals: fetched.map(|(_, approvals)| approvals).unwrap_or_default(),
        };

        run_with_resolved_inputs(ctx, inputs).await
    }
}

// TODO: this file is a bit of a mess
// and is almost 1k lines before the tests mod
// it should probably be split up into submodules

struct PostApprovalPlan<'a> {
    manifest_id: Uuid,
    operator_id: &'a Uuid,
    deploy_id: Option<&'a Uuid>,
}

/// What `post_approval_to_api` learned from the API: the created approval IDs
/// and whether the manifest approval quorum is now reached (`None` when the
/// post-check deployment fetch failed or was not attempted).
struct PostedApproval {
    approval_ids: Vec<String>,
    quorum_reached: Option<bool>,
}

/// Terminal shapes for `deploy approve` (reasons share the `manifest_approval_*` prefix).
pub enum ApproveOutcome {
    /// Approval generated and posted to the API.
    Posted(ApprovalPosted),
    /// Approval generated but not posted (`--skip-post`).
    NotPosted(ApprovalGenerated),
    /// The operator already has an approval on this manifest; nothing posted.
    AlreadyPosted(ApprovalAlreadyPosted),
    /// `--dry-run`: manifest review completed, no approval generated.
    DryRun(ApprovalDryRun),
}

impl From<ApproveOutcome> for Outcome {
    fn from(outcome: ApproveOutcome) -> Self {
        match outcome {
            ApproveOutcome::Posted(msg) => Outcome::ManifestApprovalPosted(msg),
            ApproveOutcome::NotPosted(msg) => Outcome::ManifestApprovalGenerated(msg),
            ApproveOutcome::AlreadyPosted(msg) => Outcome::ManifestApprovalAlreadyPosted(msg),
            ApproveOutcome::DryRun(msg) => Outcome::ManifestApprovalDryRun(msg),
        }
    }
}

/// The approval payload as an outcome reports it: inline when it went to
/// stdout, the file path when `--approval-out` wrote it.
#[derive(Display, Serialize)]
#[serde(rename_all = "camelCase")]
enum ApprovalOutput {
    /// Approval written to: {0}
    WrittenTo(PathBuf),
    /// {0}
    Approval(JsonPretty<Approval>),
}

#[derive(Serialize)]
struct JsonPretty<T>(T);

impl<T: Serialize> std::fmt::Display for JsonPretty<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let json = serde_json::to_string_pretty(self).map_err(|_| fmt::Error)?;
        f.write_str(&json)
    }
}

impl<T> Deref for JsonPretty<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> From<T> for JsonPretty<T> {
    fn from(value: T) -> Self {
        Self(value)
    }
}

impl ApprovalOutput {
    fn new(approval: Approval, approval_out: Option<PathBuf>) -> Self {
        match approval_out {
            Some(path) => Self::WrittenTo(path),
            None => Self::Approval(approval.into()),
        }
    }
}

// `#[default]` only applies to unit variants, so the registry-fixture Default
// is a manual, test-only impl.
#[cfg(test)]
impl Default for ApprovalOutput {
    fn default() -> Self {
        Self::WrittenTo(Default::default())
    }
}

#[derive(Serialize)]
#[cfg_attr(test, derive(Default))]
#[serde(rename_all = "camelCase")]
pub struct ApprovalPosted {
    #[serde(flatten)]
    approval_or_path: ApprovalOutput,
    manifest_id: String,
    operator_id: String,
    approval_ids: Vec<String>,
    /// `None` when the post-check deployment fetch failed or was not
    /// attempted (no `--deploy-id`), so quorum state is unknown.
    quorum_reached: Option<bool>,
}

impl fmt::Display for ApprovalPosted {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            r#"{}
Approval posted successfully!

Approval IDs: {:?}
Manifest ID: {}
Operator ID: {}"#,
            self.approval_or_path, self.approval_ids, self.manifest_id, self.operator_id
        )?;

        if let Some(reached) = self.quorum_reached {
            let quorum_line = if reached {
                QUORUM_REACHED_MESSAGE
            } else {
                "Your approval has been posted. Deployment requires additional manifest approvals before it can be deployed on TVC."
            };

            write!(f, "\n\n{quorum_line}")?;
        }

        Ok(())
    }
}

#[derive(Display, Serialize)]
#[cfg_attr(test, derive(Default))]
/// {0}
pub struct ApprovalGenerated(ApprovalOutput);

#[derive(Display, Default, Serialize)]
#[serde(rename_all = "camelCase")]
/// Operator {operator_id} has already approved this manifest (approval ID: {approval_id}). Nothing to post.
pub struct ApprovalAlreadyPosted {
    operator_id: String,
    approval_id: String,
}

#[derive(Default, Display, Serialize)]
/// Dry run complete. No approval generated.
pub struct ApprovalDryRun;

struct PostTarget {
    manifest_id: Uuid,
    deploy_id: Option<Uuid>,
}

/// Approve inputs that cannot be resolved into a postable approval; carries
/// the user-facing remediation and converts into `anyhow` at the `?` site.
#[derive(Debug, thiserror::Error)]
enum ApproveInputError {
    #[error(
        "--manifest-id is required to post approval to API (or use --deploy-id). \
         Use --skip-post to only generate the approval locally."
    )]
    MissingManifestId,
}

/// The slice of [`ArgsWithResolvedOperatorSeedSource`] that
/// [`build_post_target`] observes.
struct BuildPostTargetArgs {
    manifest_id: Option<Uuid>,
    operator_id: Option<Uuid>,
    deploy_id: Option<Uuid>,
    dry_run: bool,
    skip_post: bool,
}

impl From<&ArgsWithResolvedOperatorSeedSource> for BuildPostTargetArgs {
    fn from(args: &ArgsWithResolvedOperatorSeedSource) -> Self {
        Self {
            manifest_id: args.manifest_id,
            operator_id: args.operator_id,
            deploy_id: args.deploy_id,
            dry_run: args.dry_run,
            skip_post: args.skip_post,
        }
    }
}

struct ResolvedApproveInputs<'a> {
    manifest: ValidatedManifest<'a>,
    operator_seed_source: Option<LocalOperatorSeedSource>,
    operator_id: Option<Uuid>,
    approval_out: Option<PathBuf>,
    dry_run: bool,
    skip_post: bool,
    post_target: Option<PostTarget>,
    /// Present only when the manifest came from a deployment fetch: the
    /// already-posted approvals, parsed at that boundary, for validation and
    /// duplicate checks.
    posted_approvals: Vec<OperatorApproval>,
}

/// [`Args`] with the mutually-exclusive seed flags already parsed into a
/// seed source, so input resolution can no longer observe the raw flags.
struct ArgsWithResolvedOperatorSeedSource {
    manifest: Option<PathBuf>,
    deploy_id: Option<Uuid>,
    manifest_id: Option<Uuid>,
    operator_id: Option<Uuid>,
    operator_seed_source: Option<LocalOperatorSeedSource>,
    dry_run: bool,
    dangerous_skip_interactive: bool,
    approval_out: Option<PathBuf>,
    skip_post: bool,
}

impl TryFrom<Args> for ArgsWithResolvedOperatorSeedSource {
    type Error = anyhow::Error;

    fn try_from(args: Args) -> anyhow::Result<Self> {
        let Args {
            operator_seed,
            operator_seed_path,
            manifest,
            deploy_id,
            manifest_id,
            operator_id,
            dry_run,
            dangerous_skip_interactive,
            approval_out,
            skip_post,
        } = args;

        let operator_seed_source =
            LocalOperatorSeedSource::from_args(operator_seed, operator_seed_path)?;

        Ok(Self {
            manifest,
            deploy_id,
            manifest_id,
            operator_id,
            operator_seed_source,
            dry_run,
            dangerous_skip_interactive,
            approval_out,
            skip_post,
        })
    }
}

/// Resolve where to post and which operator approves. No post target is
/// built for `--dry-run` or `--skip-post`; without `--operator-id`, a lone
/// saved operator ID is used and multiple prompt for a choice when possible.
async fn build_post_target(
    args: BuildPostTargetArgs,
    fetched_manifest_id: Option<Uuid>,
    non_interactive: bool,
) -> anyhow::Result<(Option<PostTarget>, Option<Uuid>)> {
    if args.dry_run || args.skip_post {
        return Ok((None, args.operator_id));
    }

    let manifest_id = fetched_manifest_id
        .or(args.manifest_id)
        .ok_or(ApproveInputError::MissingManifestId)?;

    let operator_id = if let Some(operator_id) = args.operator_id {
        operator_id
    } else {
        let config = Config::load().await?;

        let saved_ids = config
            .get_last_operator_ids()
            .unwrap_or_default()
            .into_iter()
            .map(|id| {
                Uuid::parse_str(&id)
                    .with_context(|| format!("saved operator ID '{id}' is not a UUID"))
            })
            .collect::<anyhow::Result<Vec<_>>>()?;

        match saved_ids.len() {
            0 => bail!(
                "--operator-id is required to post approval to API. \
                 No saved operator IDs found. \
                 Use --skip-post to only generate the approval locally."
            ),
            1 => saved_ids[0],
            _ if non_interactive || !stdin_can_prompt() => bail!(
                "--operator-id is required to post approval to API when multiple saved operator IDs are available"
            ),
            _ => prompts::select("Select approving operator", saved_ids)?,
        }
    };

    let post_target = PostTarget {
        manifest_id,
        deploy_id: args.deploy_id,
    };

    Ok((post_target.into(), operator_id.into()))
}

async fn run_with_resolved_inputs(
    ctx: &mut StdCtx,
    inputs: ResolvedApproveInputs<'_>,
) -> anyhow::Result<ApproveOutcome> {
    if inputs.dry_run {
        return Ok(ApproveOutcome::DryRun(ApprovalDryRun));
    }

    let validation = inputs.manifest.validate(inputs.posted_approvals);

    validation
        .approvals
        .iter()
        .filter(|validated| validated.verdict != ApprovalVerdict::Valid)
        .for_each(|validated| {
            let message = format!(
                "existing approval from {} is {}; enclave will reject this approval and fail to start",
                validated.approval, validated.verdict
            );

            if let Err(error) = ctx.shell().human().warn(message) {
                debug!(%error, "failed to write approval warning");
            }
        });

    let operator = resolve_operator(inputs.operator_seed_source, inputs.operator_id).await?;
    if inputs.skip_post && operator.is_hosted() {
        bail!("--skip-post is only supported for local operators");
    }
    let auth = if operator.is_hosted() {
        Some(build_client().await?)
    } else {
        None
    };
    let approval = sign_and_write_approval(
        &operator,
        &OperatorCtx {
            auth: auth.as_ref(),
        },
        inputs.approval_out.as_deref(),
        &inputs.manifest,
    )
    .await?;

    match inputs.post_target {
        Some(target) => {
            let operator_id = operator
                .id()
                .context("resolved operator ID required to post approval")?;

            // An approval already posted by this operator, matched by
            // operator ID or by the manifest set member public key.
            let existing = validation.approvals.iter().find(|validated| {
                validated.approval.operator_id == operator_id
                    || validated.approval.public_key.to_bytes() == approval.member.pub_key
            });

            if let Some(existing) = existing {
                return Ok(ApproveOutcome::AlreadyPosted(ApprovalAlreadyPosted {
                    operator_id: operator_id.to_string(),
                    approval_id: existing.approval.id.to_string(),
                }));
            }

            let plan = PostApprovalPlan {
                manifest_id: target.manifest_id,
                operator_id: &operator_id,
                deploy_id: target.deploy_id.as_ref(),
            };
            let posted = post_approval_to_api(ctx, plan, &approval, &inputs.manifest).await?;

            Ok(ApproveOutcome::Posted(ApprovalPosted {
                approval_or_path: ApprovalOutput::new(approval, inputs.approval_out),
                manifest_id: target.manifest_id.to_string(),
                operator_id: operator_id.to_string(),
                approval_ids: posted.approval_ids,
                quorum_reached: posted.quorum_reached,
            }))
        }
        None => Ok(ApproveOutcome::NotPosted(ApprovalGenerated(
            ApprovalOutput::new(approval, inputs.approval_out),
        ))),
    }
}

async fn load_manifest(
    ctx: &mut StdCtx,
    args: &ArgsWithResolvedOperatorSeedSource,
) -> anyhow::Result<(VersionedManifest, Option<(Uuid, Vec<OperatorApproval>)>)> {
    match (&args.manifest, &args.deploy_id) {
        (Some(path), _) => Ok((read_manifest_from_path(path).await?, None)),
        (_, Some(deploy_id)) => {
            let (manifest, manifest_id, approvals) =
                fetch_manifest_from_deploy(ctx, &deploy_id.to_string()).await?;
            Ok((manifest, Some((manifest_id, approvals))))
        }
        (None, None) => bail!("a manifest source is required"),
    }
}

/// Sign the manifest and, when `--approval-out` is set, write the approval to
/// that file. Reporting the approval (inline payload or file path) is the
/// terminal outcome's job.
async fn sign_and_write_approval(
    operator: &ResolvedOperator,
    operator_ctx: &OperatorCtx<'_>,
    approval_out: Option<&Path>,
    manifest: &ValidatedManifest<'_>,
) -> anyhow::Result<Approval> {
    let approval = operator.approve_manifest(operator_ctx, manifest).await?;

    if let Some(path) = approval_out {
        let json = serde_json::to_string_pretty(&approval)?;
        write_file(path, &json).await?;
    }

    Ok(approval)
}

#[instrument(skip_all, fields(manifest_id = %plan.manifest_id, operator_id = %plan.operator_id, deploy_id = ?plan.deploy_id))]
async fn post_approval_to_api(
    ctx: &mut StdCtx,
    plan: PostApprovalPlan<'_>,
    approval: &Approval,
    manifest: &ValidatedManifest<'_>,
) -> anyhow::Result<PostedApproval> {
    shell_println!(ctx)?;
    shell_println!(ctx, "Posting approval to Turnkey...")?;

    let auth = crate::client::build_client().await?;

    let tvc_approval = TvcManifestApproval {
        operator_id: plan.operator_id.to_string(),
        signature: hex::encode(&approval.signature),
    };

    let intent = CreateTvcManifestApprovalsIntent {
        manifest_id: plan.manifest_id.to_string(),
        approvals: vec![tvc_approval],
    };

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

    let result = auth
        .client
        .create_tvc_manifest_approvals(auth.org_id.clone(), timestamp_ms, intent)
        .await
        .context("failed to post manifest approval")?;

    let quorum_reached = match plan.deploy_id {
        Some(deploy_id) => {
            let request = GetTvcDeploymentRequest {
                organization_id: auth.org_id.clone(),
                deployment_id: deploy_id.to_string(),
            };

            match auth.client.get_tvc_deployment(request).await {
                Ok(response) => match response.tvc_deployment {
                    Some(deployment) => {
                        let approvals = deployment
                            .manifest_approvals
                            .into_iter()
                            .map(OperatorApproval::try_from)
                            .collect::<Result<Vec<_>, _>>()?;

                        Some(manifest.validate(approvals).quorum_reached())
                    }
                    None => Some(false),
                },
                Err(error) => {
                    debug!(
                        %deploy_id,
                        %error,
                        "failed to fetch deployment after posting manifest approval"
                    );
                    None
                }
            }
        }
        None => None,
    };

    Ok(PostedApproval {
        approval_ids: result.result.approval_ids,
        quorum_reached,
    })
}

/// Walk the user through each section of the manifest for approval.
fn interactive_approve(ctx: &mut StdCtx, manifest: &VersionedManifest) -> anyhow::Result<()> {
    shell_println!(ctx, "\n========================================")?;
    shell_println!(ctx, "         MANIFEST APPROVAL")?;
    shell_println!(ctx, "========================================\n")?;

    review_namespace(ctx, manifest.namespace())?;
    review_enclave(ctx, manifest.enclave())?;
    review_pivot(ctx, manifest)?;
    review_manifest_set(ctx, manifest.manifest_set())?;
    review_share_set(ctx, manifest.share_set())?;

    shell_println!(ctx, "\n========================================")?;
    shell_println!(ctx, "    ALL SECTIONS APPROVED")?;
    shell_println!(ctx, "========================================\n")?;

    Ok(())
}

fn render_namespace(namespace: &Namespace) -> String {
    let mut s = String::new();
    let _ = writeln!(s, "NAMESPACE");
    let _ = writeln!(s, "─────────────────────────────────────");
    let _ = writeln!(s, "  Name:       {}", namespace.name);
    let _ = writeln!(s, "  Nonce:      {}", namespace.nonce);
    let _ = writeln!(s, "  Quorum Key: {}", hex::encode(&namespace.quorum_key));
    let _ = writeln!(s);
    s
}

fn review_namespace(ctx: &mut StdCtx, namespace: &Namespace) -> anyhow::Result<()> {
    shell_print!(ctx, "{}", render_namespace(namespace))?;
    prompts::confirm_or_bail("Approve namespace?", "approval")
}

fn render_enclave(enclave: &NitroConfig) -> String {
    let mut s = String::new();
    let _ = writeln!(s, "ENCLAVE (AWS Nitro)");
    let _ = writeln!(s, "─────────────────────────────────────");
    let _ = writeln!(s, "  PCR0 (image):     {}", hex::encode(&enclave.pcr0));
    let _ = writeln!(s, "  PCR1 (kernel):    {}", hex::encode(&enclave.pcr1));
    let _ = writeln!(s, "  PCR2 (app):       {}", hex::encode(&enclave.pcr2));
    let _ = writeln!(s, "  PCR3 (IAM role):  {}", hex::encode(&enclave.pcr3));
    // Skip the QOS commit since it's not cryptographically linked
    let _ = writeln!(s);
    s
}

fn review_enclave(ctx: &mut StdCtx, enclave: &NitroConfig) -> anyhow::Result<()> {
    shell_print!(ctx, "{}", render_enclave(enclave))?;
    prompts::confirm_or_bail("Approve enclave configuration?", "approval")
}

fn render_pivot(manifest: &VersionedManifest) -> String {
    let mut s = String::new();
    let _ = writeln!(s, "PIVOT BINARY");
    let _ = writeln!(s, "─────────────────────────────────────");
    let _ = writeln!(
        s,
        "  Pivot Binary Hash: {}",
        hex::encode(manifest.pivot_hash())
    );
    if manifest.args().is_empty() {
        let _ = writeln!(s, "  CLI Args: (none)");
    } else {
        let _ = writeln!(s, "  CLI Args:\n   {}", manifest.args().join("\n   "));
    }
    let _ = writeln!(s);
    s
}

fn review_pivot(ctx: &mut StdCtx, manifest: &VersionedManifest) -> anyhow::Result<()> {
    shell_print!(ctx, "{}", render_pivot(manifest))?;
    prompts::confirm_or_bail("Approve pivot binary?", "approval")
}

fn render_quorum_members(members: &[QuorumMember]) -> String {
    let mut s = String::new();
    for member in members.iter() {
        let _ = writeln!(s, "    {} ({})", member.alias, hex::encode(&member.pub_key));
    }
    s
}

fn render_manifest_set(set: &ManifestSet) -> String {
    let mut s = String::new();
    let _ = writeln!(s, "MANIFEST SET");
    let _ = writeln!(s, "─────────────────────────────────────");
    let _ = writeln!(s, "  Threshold: {} of {}", set.threshold, set.members.len());
    let _ = writeln!(s, "  Members:");
    s.push_str(&render_quorum_members(&set.members));
    let _ = writeln!(s);
    s
}

fn review_manifest_set(ctx: &mut StdCtx, set: &ManifestSet) -> anyhow::Result<()> {
    shell_print!(ctx, "{}", render_manifest_set(set))?;
    prompts::confirm_or_bail("Approve manifest set?", "approval")
}

fn render_share_set(set: &ShareSet) -> String {
    let mut s = String::new();
    let _ = writeln!(s, "SHARE SET");
    let _ = writeln!(s, "─────────────────────────────────────");
    let _ = writeln!(s, "  Threshold: {} of {}", set.threshold, set.members.len());
    let _ = writeln!(s, "  Members:");
    s.push_str(&render_quorum_members(&set.members));
    let _ = writeln!(s);
    s
}

fn review_share_set(ctx: &mut StdCtx, set: &ShareSet) -> anyhow::Result<()> {
    shell_print!(ctx, "{}", render_share_set(set))?;
    prompts::confirm_or_bail("Approve share set?", "approval")
}

async fn read_manifest_from_path(path: &Path) -> anyhow::Result<VersionedManifest> {
    let content = read_file_to_string(path).await?;
    let manifest = VersionedManifest::try_from_slice_compat(content.as_bytes())
        .with_context(|| format!("failed to parse manifest JSON from: {}", path.display()))?;
    Ok(manifest)
}

/// Fetch manifest from Turnkey using GetTvcDeployment API.
/// Returns the manifest, its Turnkey manifest_id, and the deployment itself.
#[instrument(skip(ctx))]
async fn fetch_manifest_from_deploy(
    ctx: &mut StdCtx,
    deploy_id: &str,
) -> anyhow::Result<(VersionedManifest, Uuid, Vec<OperatorApproval>)> {
    shell_println!(ctx, "Fetching deployment {deploy_id}...")?;

    let auth = build_client().await?;

    let request = GetTvcDeploymentRequest {
        organization_id: auth.org_id.clone(),
        deployment_id: deploy_id.to_string(),
    };

    let response = auth
        .client
        .get_tvc_deployment(request)
        .await
        .with_context(|| format!("failed to fetch deployment {deploy_id}"))?;

    let deployment = response
        .tvc_deployment
        .ok_or_else(|| MissingResource::new("deployment", deploy_id.to_string()))?;

    let tvc_manifest = deployment
        .manifest
        .as_ref()
        .ok_or_else(|| MissingResource::new("manifest", format!("deployment {deploy_id}")))?;

    let manifest = VersionedManifest::try_from_slice_compat(&tvc_manifest.manifest)
        .context("failed to parse manifest from deployment")?;

    let manifest_id = tvc_manifest
        .id
        .parse::<Uuid>()
        .with_context(|| format!("manifest ID '{}' is not a UUID", tvc_manifest.id))?;

    let approvals = deployment
        .manifest_approvals
        .into_iter()
        .map(OperatorApproval::try_from)
        .collect::<Result<Vec<_>, _>>()?;

    shell_println!(ctx, "✓ Manifest loaded (manifest_id: {manifest_id})")?;

    Ok((manifest, manifest_id, approvals))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn fixture_manifest() -> VersionedManifest {
        VersionedManifest::try_from_slice_compat(include_bytes!("../../../fixtures/manifest.json"))
            .expect("fixture manifest should parse")
    }

    #[test]
    fn render_namespace_includes_name_nonce_and_quorum_key() {
        let manifest = fixture_manifest();
        let rendered = render_namespace(manifest.namespace());
        assert!(rendered.contains("NAMESPACE"));
        assert!(rendered.contains("turnkey-prod"));
        assert!(rendered.contains("Nonce:"));
        assert!(rendered.contains("Quorum Key:"));
    }

    #[test]
    fn render_enclave_includes_all_four_pcrs() {
        let manifest = fixture_manifest();
        let rendered = render_enclave(manifest.enclave());
        assert!(rendered.contains("ENCLAVE (AWS Nitro)"));
        assert!(rendered.contains("PCR0"));
        assert!(rendered.contains("PCR1"));
        assert!(rendered.contains("PCR2"));
        assert!(rendered.contains("PCR3"));
    }

    #[test]
    fn render_pivot_includes_header_and_args() {
        let manifest = fixture_manifest();
        let rendered = render_pivot(&manifest);
        assert!(rendered.contains("PIVOT BINARY"));
        assert!(rendered.contains("Pivot Binary Hash:"));
        assert!(rendered.contains("--flag"));
        assert!(rendered.contains("positional"));
    }

    #[test]
    fn render_manifest_set_includes_threshold_and_each_member() {
        let manifest = fixture_manifest();
        let rendered = render_manifest_set(manifest.manifest_set());
        assert!(rendered.contains("MANIFEST SET"));
        assert!(rendered.contains("Threshold: 2 of 3"));
        assert!(rendered.contains("operator-alice"));
        assert!(rendered.contains("operator-bob"));
        assert!(rendered.contains("operator-charlie"));
    }

    fn posted_to_file() -> ApprovalPosted {
        ApprovalPosted {
            approval_or_path: ApprovalOutput::WrittenTo("approval.json".into()),
            manifest_id: "manifest-123".to_string(),
            operator_id: "operator-456".to_string(),
            approval_ids: vec!["approval-1".to_string()],
            quorum_reached: Some(true),
        }
    }

    #[test]
    fn approval_posted_serializes_expected_json() {
        let value =
            serde_json::to_value(Outcome::from(ApproveOutcome::Posted(posted_to_file()))).unwrap();

        assert_eq!(
            value,
            serde_json::json!({
                "reason": "manifest_approval_posted",
                "writtenTo": "approval.json",
                "manifestId": "manifest-123",
                "operatorId": "operator-456",
                "approvalIds": ["approval-1"],
                "quorumReached": true,
            })
        );
    }

    #[test]
    fn approval_generated_serializes_expected_json() {
        let generated = ApprovalGenerated(ApprovalOutput::Approval(
            Approval {
                signature: vec![0xde, 0xad],
                member: QuorumMember {
                    alias: "operator-alice".to_string(),
                    pub_key: vec![0xaa],
                },
            }
            .into(),
        ));

        let value =
            serde_json::to_value(Outcome::from(ApproveOutcome::NotPosted(generated))).unwrap();

        assert_eq!(
            value,
            serde_json::json!({
                "reason": "manifest_approval_generated",
                "approval": {
                    "signature": "dead",
                    "member": {
                        "alias": "operator-alice",
                        "pubKey": "aa",
                    },
                },
                "reason": "manifest_approval_generated"
            })
        );
    }

    #[test]
    fn approval_already_posted_serializes_expected_json() {
        let already_posted = ApprovalAlreadyPosted {
            operator_id: "operator-456".to_string(),
            approval_id: "approval-1".to_string(),
        };

        let value =
            serde_json::to_value(Outcome::from(ApproveOutcome::AlreadyPosted(already_posted)))
                .unwrap();

        assert_eq!(
            value,
            serde_json::json!({
                "reason": "manifest_approval_already_posted",
                "operatorId": "operator-456",
                "approvalId": "approval-1",
            })
        );
    }

    #[test]
    fn approval_dry_run_serializes_reason_only() {
        let value =
            serde_json::to_value(Outcome::from(ApproveOutcome::DryRun(ApprovalDryRun))).unwrap();

        assert_eq!(
            value,
            serde_json::json!({ "reason": "manifest_approval_dry_run" })
        );
    }

    /// The quorum line is branch-dependent: present with the reached/pending
    /// sentence when the post-check fetch succeeded, absent when quorum state
    /// is unknown (matching the pre-outcome behavior of a silent failed
    /// fetch).
    #[test]
    fn approval_posted_human_message_includes_quorum_line_only_when_known() {
        let mut posted = posted_to_file();

        posted.quorum_reached = Some(true);
        assert!(
            posted
                .to_string()
                .contains("Manifest approval quorum reached.")
        );

        posted.quorum_reached = Some(false);
        assert!(
            posted
                .to_string()
                .contains("requires additional manifest approvals")
        );

        posted.quorum_reached = None;
        let human = posted.to_string();
        assert!(!human.contains("quorum"));
        assert!(human.ends_with("Operator ID: operator-456"));
    }
}