pnm-cli 0.17.2

CLI Tool for managing a personal Verifiable Trust Agent
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
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
//! `pnm bootstrap` — sealed-transfer consumer commands.
//!
//! Thin pnm-side wrapper over `vta_cli_common::sealed_consumer`. The shared
//! crate owns the seed-file conventions (`<config_dir>/bootstrap-secrets/<bundle_id>.key`,
//! 0600 on Unix, owner-only DACL on Windows), the armor-decode/HPKE-open
//! pipeline, and the `--no-verify-digest` warning text. This module only
//! adds pnm-specific glue: payload pretty-printing for `bootstrap open`,
//! the online TEE attest/connect flow, and the authed REST bridge for
//! `provision-integration`.
//!
//! Offline opening requires `--expect-digest` or an explicit warning-bearing
//! `--no-verify-digest`. Online connect also accepts `--expect-pcr0` as its
//! anchor: the fresh server-generated digest cannot be known before the call.

use std::fs;
use std::io::Write;
use std::path::PathBuf;

use serde::Deserialize;
use vta_sdk::attestation::verify_nitro_assertion;
use vta_sdk::sealed_transfer::{
    BootstrapRequest, SealedPayloadV1, armor, bundle_digest, ed25519_seed_to_x25519_secret,
    generate_ed25519_keypair, open_bundle,
};

use crate::auth;
use crate::config;

use vta_sdk::hex::lower as hex_lower;

/// `pnm bootstrap request --out <PATH> [--label <NAME>]`
pub async fn run_request(
    out: PathBuf,
    label: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config_dir = config::config_dir()?;
    let created = vta_cli_common::sealed_consumer::create_bootstrap_request(&config_dir, label)?;
    let json = serde_json::to_string_pretty(&created.request)?;
    fs::write(&out, json.as_bytes())?;

    println!("Bootstrap request written to {}", out.display());
    println!();
    println!("  Bundle-Id:  {}", created.bundle_id_hex);
    println!("  Client DID: {}", created.request.client_did);
    println!("  Seed saved: {}", created.secret_path.display());
    println!();
    println!("Hand the request to the producer. They will return an armored bundle.");
    println!("Verify the SHA-256 digest they print to you out-of-band, then run:");
    println!("  pnm bootstrap open --bundle <file> --expect-digest <hex>");
    Ok(())
}

/// `pnm bootstrap provision-request` — consumer-side. Generate a
/// VP-framed `BootstrapRequest` for the provision-integration flow.
///
/// Mints an ephemeral Ed25519 keypair, persists the seed under
/// `~/.config/pnm/bootstrap-secrets/<bundle_id>.key`, and writes a
/// signed VP naming the target DID template + variables. Hand the JSON
/// to the VTA operator's `vta bootstrap provision-integration` or
/// `pnm bootstrap provision-integration` (authed bridge) and decrypt
/// the returned bundle with `pnm bootstrap open`.
#[allow(clippy::too_many_arguments)]
pub async fn run_provision_request(
    template: String,
    vars: Vec<String>,
    context_hint: Option<String>,
    admin_template: Option<String>,
    validity_hours: f64,
    label: Option<String>,
    out: PathBuf,
) -> Result<(), Box<dyn std::error::Error>> {
    use vta_sdk::provision_integration::ProvisionRequestBuilder;

    if !validity_hours.is_finite() || validity_hours <= 0.0 {
        return Err(format!(
            "--validity-hours must be a positive finite number, got {validity_hours}"
        )
        .into());
    }
    let validity = chrono::Duration::seconds((validity_hours * 3600.0) as i64);

    let mut builder = ProvisionRequestBuilder::new(template).validity(validity);
    for raw in &vars {
        let (k, v) = parse_var(raw)?;
        builder = builder.var(k, v);
    }
    if let Some(ctx) = context_hint {
        builder = builder.context_hint(ctx);
    }
    if let Some(admin) = admin_template {
        builder = builder.admin_template(admin);
    }
    if let Some(l) = label {
        builder = builder.label(l);
    }

    let config_dir = config::config_dir()?;
    let created =
        vta_cli_common::sealed_consumer::create_provision_request(&config_dir, builder).await?;

    let json = serde_json::to_string_pretty(&created.request)?;
    fs::write(&out, json.as_bytes())?;

    println!("Provision bootstrap request written to {}", out.display());
    println!();
    println!("  Bundle-Id:  {}", created.bundle_id_hex);
    println!("  Client DID: {}", created.client_did);
    println!("  Seed saved: {}", created.secret_path.display());
    println!();
    println!("Hand the request to the VTA operator. They will run:");
    println!("  vta bootstrap provision-integration --request <file> --out <bundle>");
    println!("(or `pnm bootstrap provision-integration` over REST against a live VTA).");
    println!();
    println!("Verify the returned digest out-of-band, then:");
    println!("  pnm bootstrap open --bundle <file> --expect-digest <hex>");
    Ok(())
}

/// Parse a single `--var KEY=VALUE` argument. Value is tried as JSON
/// first; falls back to a plain string for unquoted values.
fn parse_var(raw: &str) -> Result<(String, serde_json::Value), Box<dyn std::error::Error>> {
    let (key, value) = raw
        .split_once('=')
        .ok_or_else(|| format!("invalid --var '{raw}': expected KEY=VALUE"))?;
    if key.is_empty() {
        return Err(format!("invalid --var '{raw}': empty key").into());
    }
    let parsed = serde_json::from_str::<serde_json::Value>(value)
        .unwrap_or_else(|_| serde_json::Value::String(value.to_string()));
    Ok((key.to_string(), parsed))
}

/// `pnm bootstrap open --bundle <PATH> [--expect-digest <HEX>] [--no-verify-digest]`
pub async fn run_open(
    bundle_path: PathBuf,
    out: Option<PathBuf>,
    expect_digest: Option<String>,
    no_verify_digest: bool,
    expect_vta_did: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config_dir = config::config_dir()?;
    let opened = vta_cli_common::sealed_consumer::open_armored_bundle(
        &bundle_path,
        &config_dir,
        expect_digest.as_deref(),
        no_verify_digest,
    )?;

    println!("Sealed bundle opened.");
    println!();
    println!("  Bundle-Id:       {}", opened.bundle_id_hex);
    println!("  Digest (sha256): {}", opened.digest);
    println!("  Producer DID:    {}", opened.producer.producer_did);
    println!("  Producer proof:  {:?}", opened.producer.proof);
    println!();
    match &opened.payload {
        SealedPayloadV1::AdminCredential(c) => {
            println!("Payload: AdminCredential");
            println!("  DID:     {}", c.did);
            println!("  VTA DID: {}", c.vta_did);
            if let Some(ref u) = c.vta_url {
                println!("  VTA URL: {u}");
            }
            if out.is_none() {
                println!();
                println!("Nothing was written. To install this credential either:");
                println!("  - re-open with --out <path> for a file-based consumer, or");
                println!(
                    "  - use the online flow: pnm bootstrap connect --vta-did <did> \
                     --expect-pcr0 <hex> [--expect-pcr8 <hex>]"
                );
                println!(
                    "    (--vta-url <url> is the fallback when the DID log is not yet \
                     resolvable; it does not pin the VTA's identity)"
                );
            }
        }
        SealedPayloadV1::ContextProvision(p) => {
            println!("Payload: ContextProvision");
            println!("  Context:   {} ({})", p.context_id, p.context_name);
            println!("  Admin DID: {}", p.admin_did);
            if out.is_none() {
                println!();
                println!(
                    "Nothing was written — this payload carries an admin credential. \
                     Re-open with --out <path> to write it as JSON."
                );
            }
        }
        SealedPayloadV1::DidSecrets(s) => {
            println!("Payload: DidSecrets");
            println!("  DID:     {}", s.did);
            println!("  Secrets: {}", s.secrets.len());
        }
        SealedPayloadV1::AdminKeySet(keys) => {
            println!("Payload: AdminKeySet ({} keys)", keys.len());
            for k in keys {
                println!("  - {}", k.label);
            }
        }
        SealedPayloadV1::RawPrivateKey(k) => {
            println!("Payload: RawPrivateKey ({})", k.key_type);
        }
        SealedPayloadV1::TemplateBootstrap(p) => {
            println!("Payload: TemplateBootstrap");
            println!("  Template:     {}", p.config.template_name);
            println!("  Kind:         {}", p.config.template_kind);
            println!("  Secrets for:  {} DID(s)", p.secrets.len());
            println!("  Outputs:      {}", p.config.outputs.len());
            if let Some(ref u) = p.config.vta_url {
                println!("  VTA URL:      {u}");
            }
            match expect_vta_did.as_deref() {
                Some(pinned) => {
                    use vta_sdk::provision_integration::template_verify::verify_template_bootstrap;
                    verify_template_bootstrap((**p).clone(), pinned, chrono::Duration::minutes(5))?;
                    println!();
                    println!("  \x1b[1;32m✓ VC verified against pinned VTA DID\x1b[0m");
                }
                None => {
                    println!();
                    println!("  \x1b[1;33m⚠ VC NOT verified — digest-only trust anchor.\x1b[0m");
                    println!(
                        "    Re-run with --expect-vta-did <did> to verify the authorization VC."
                    );
                }
            }
            println!();
            println!("Install via the provision-integration flow on the integration host.");
        }
        SealedPayloadV1::AdminRotation(p) => {
            println!("Payload: AdminRotation");
            println!("  Admin DID:    {}", p.admin.did);
            println!("  VTA DID:      {}", p.vta_trust.vta_did);
            if let Some(ref u) = p.vta_url {
                println!("  VTA URL:      {u}");
            }
            // VC verification for AdminRotation parallels the
            // TemplateBootstrap path but isn't yet plumbed through —
            // digest pinning remains the trust anchor for now.
            println!();
            println!(
                "  \x1b[1;33m⚠ VC verification not yet wired for AdminRotation — digest-only.\x1b[0m"
            );
            println!();
            println!("Install via the provision-integration flow on the integration host.");
        }
        SealedPayloadV1::IssuedCredential(c) => {
            println!("Payload: IssuedCredential");
            println!("  Issuer DID: {}", c.issuer_did);
            if let Some(ref label) = c.label {
                println!("  Label:      {label}");
            }
            let kind = if c.credential.is_string() {
                "SD-JWT-VC (compact)"
            } else {
                "W3C Data-Integrity VC"
            };
            println!("  Format:     {kind}");
            println!();
            println!(
                "Receive this credential into the holder vault via the credential-exchange flow."
            );
        }
        SealedPayloadV1::MessagingBridgeCredentials(b) => {
            println!("Payload: MessagingBridgeCredentials");
            println!("  Platform:   {}", b.platform);
            println!("  Fields:     {}", b.fields.len());
            println!();
            println!(
                "Load these platform secrets into the messaging-bridge connector's secret store."
            );
        }
    }

    if let Some(path) = out {
        // Writing the credential out installs it for a file-based consumer, so
        // the bundle must be anchored first: the out-of-band digest, or a
        // signature by `--expect-vta-did` (see `verify_admin_bundle`). This
        // also rejects any payload variant that isn't an admin identity, with
        // a per-variant message. The bundle is already spent by this point,
        // so failing here still costs the operator a fresh request cycle —
        // hence the up-front warning in the `--out` help text.
        let bundle = vta_cli_common::sealed_consumer::verify_admin_bundle(
            opened,
            expect_digest.as_deref(),
            expect_vta_did.as_deref(),
        )?;
        write_credential_bundle(&path, &bundle)?;
        println!();
        println!("Credential written to {} (0600).", path.display());
    }

    Ok(())
}

/// Serialize a [`CredentialBundle`] to `path`, owner-readable only.
///
/// Field names come from the type's serde renames (`privateKeyMultibase`,
/// `vtaDid`, `vtaUrl`), so the output is exactly the shape file-based
/// consumers expect — e.g. the trust registry's `TR_VTA_CREDENTIAL`.
fn write_credential_bundle(
    path: &std::path::Path,
    bundle: &vta_sdk::credentials::CredentialBundle,
) -> Result<(), Box<dyn std::error::Error>> {
    let json = serde_json::to_vec_pretty(bundle)?;

    let mut opts = fs::OpenOptions::new();
    opts.create(true).write(true).truncate(true);
    // Open at 0600 so the private key is never briefly world-readable
    // between create and chmod — same rationale as `write_secret` in
    // vta-cli-common's sealed_consumer.
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.mode(0o600);
    }
    let mut file = opts.open(path)?;
    file.write_all(&json)?;
    file.write_all(b"\n")?;
    drop(file);

    if let Err(e) = vta_cli_common::secure_file::restrict_file_to_owner(path) {
        eprintln!(
            "warning: could not restrict {} to owner ({e}) — the private key may be \
             readable by other local users",
            path.display()
        );
    }
    Ok(())
}

// ── online flow (Mode B — TEE first-boot attestation) ──────────────────

#[derive(Debug, Deserialize)]
struct BootstrapResponseWire {
    bundle: String,
    digest: String,
}

/// Resolve without the session helper's URL-guessing fallback. Bootstrap must
/// fail closed on an invalid WebVH log, not silently trust the DID's DNS host.
/// Use a local resolver so SCID/log verification happens on the operator's
/// machine rather than trusting a remote resolver's returned document.
async fn resolve_connect_url(
    vta_did: &str,
    resolver: &affinidi_did_resolver_cache_sdk::DIDCacheClient,
) -> Result<String, Box<dyn std::error::Error>> {
    resolve_connect_url_with_policy(
        vta_did,
        resolver,
        vta_sdk::http::EndpointPolicy::process_default(),
    )
    .await
}

/// Deliberately ignores `PNM_RESOLVER_URL` / `[resolver_url]`, which every
/// other `DIDCacheClient` in PNM honours (see `main.rs`). The document
/// resolved here selects the endpoint that mints a super-admin credential,
/// and the VTA's first-boot carve-out is single-use — a remote resolver
/// returning a document of its choosing would pick that endpoint on the
/// operator's behalf, once, irreversibly. Local mode verifies the SCID and
/// the signed log chain on this machine instead. The resolution error names
/// the exception, because an operator whose egress only reaches a resolver
/// sidecar would otherwise be told to wait for a DID log that is already
/// published.
async fn resolve_connect_url_with_policy(
    vta_did: &str,
    resolver: &affinidi_did_resolver_cache_sdk::DIDCacheClient,
    policy: vta_sdk::http::EndpointPolicy,
) -> Result<String, Box<dyn std::error::Error>> {
    let url = async {
        let resolved = resolver.resolve(vta_did).await?;
        let doc = serde_json::to_value(&resolved.doc)?;
        if doc["id"].as_str() != Some(vta_did) {
            return Err("resolved DID document does not match requested VTA DID".into());
        }
        vta_sdk::protocol::matching::ServiceCapabilities::from_did_document(&doc)
            .rest
            .ok_or_else(|| "VTA DID document does not advertise a REST endpoint".into())
    }
    .await
    .map_err(|e: Box<dyn std::error::Error>| {
        format!(
            "Could not resolve bootstrap endpoint for VTA DID {vta_did}: {e}. \
             Resolution is always local here — a configured PNM_RESOLVER_URL / \
             [resolver_url] is not used for bootstrap, so a reachable resolver \
             sidecar does not satisfy this. Retry once its DID log is published \
             and reachable from this machine, or explicitly use --vta-url <URL> \
             instead of --vta-did (without DID identity pinning)."
        )
    })?;
    // An authentic DID document can still advertise an unsafe destination. The
    // guard's own message carries the remedy (`--allow-private-endpoints` /
    // `VTA_ALLOW_PRIVATE_ENDPOINTS`); do NOT append a `--vta-url` suggestion
    // to it. That flag is not guarded, so offering it as the fix for a guard
    // failure teaches operators to route around the control instead of making
    // a decision about it.
    vta_sdk::http::guard_vta_endpoint(&url, policy).map_err(|e| {
        format!("VTA DID {vta_did} advertises a REST endpoint that is not safe to call: {e}")
    })?;
    Ok(url.trim_end_matches('/').to_string())
}

fn check_connect_vta_did(
    expected: Option<&str>,
    actual: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    if let Some(expected) = expected
        && expected != actual
    {
        return Err(format!(
            "bootstrap credential VTA DID {actual} does not match requested VTA DID {expected}; \
             refusing to install credentials"
        )
        .into());
    }
    Ok(())
}

/// The online digest is generated during connect; a pre-computable PCR0 pin
/// also satisfies its anchor requirement. PCR8 alone is not an image pin.
///
/// Every pin is syntax-checked here, before any network I/O, because
/// `/bootstrap/request` closes `BOOTSTRAP_CARVEOUT_CLOSED_KEY` server-side
/// *before* it returns the bundle (`routes/bootstrap.rs`). A pin that is only
/// rejected later, at `VerifiedAttestation::check_pcrs`, is rejected after
/// the VTA's one-shot first boot has already been spent — so a typo in
/// `--expect-pcr8` would leave the operator with no way to bootstrap that VTA
/// at all. Malformed in, nothing sent.
fn validate_connect_anchor(
    expect_digest: Option<&str>,
    no_verify_digest: bool,
    expect_pcr0: Option<&str>,
    expect_pcr8: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    if let Some(pcr0) = expect_pcr0 {
        vta_sdk::attestation::validate_expected_pcr(0, pcr0)?;
    }
    if let Some(pcr8) = expect_pcr8 {
        vta_sdk::attestation::validate_expected_pcr(8, pcr8)?;
    }
    if expect_digest.is_some() || no_verify_digest {
        // Preserve the shared conflict error and explicit opt-out warning.
        return vta_cli_common::sealed_consumer::validate_digest_flags(
            expect_digest,
            no_verify_digest,
        );
    }
    if expect_pcr0.is_some() {
        return Ok(());
    }
    Err(
        "connect requires --expect-pcr0 <hex>, --expect-digest <hex>, or \
         --no-verify-digest (explicit opt-out with a warning). The connect digest is \
         generated server-side during this call and cannot be pre-shared; pin \
         --expect-pcr0 to the expected enclave image measurement."
            .into(),
    )
}

/// `pnm bootstrap connect --vta-did <DID> [--expect-digest <HEX>]
///   [--expect-pcr0 <HEX>] [--expect-pcr8 <HEX>]`
///
/// Online TEE first-boot bootstrap. Generates an ephemeral Ed25519 keypair,
/// POSTs the `did:key` as `client_did` to `/bootstrap/request`, verifies
/// the attestation quote (optionally pinning the enclave PCR0/PCR8 — P3.4),
/// installs the minted admin credential, and
/// registers the VTA under a slug in `pnm` config. Only the first successful
/// call against a fresh TEE VTA succeeds — the carve-out closes on success.
///
/// For non-TEE VTAs use `pnm setup` (temp did:key + admin grant via
/// `vta acl create` + auto-rotate on first authenticated connect).
#[allow(clippy::too_many_arguments)]
pub async fn run_connect(
    vta_did: Option<String>,
    vta_url: Option<String>,
    expect_digest: Option<String>,
    no_verify_digest: bool,
    expect_pcr0: Option<String>,
    expect_pcr8: Option<String>,
    vta_slug: Option<String>,
    pnm_config: &mut crate::config::PnmConfig,
) -> Result<(), Box<dyn std::error::Error>> {
    validate_connect_anchor(
        expect_digest.as_deref(),
        no_verify_digest,
        expect_pcr0.as_deref(),
        expect_pcr8.as_deref(),
    )?;

    let vta_url = match (vta_did.as_deref(), vta_url) {
        (Some(did), None) => {
            let resolver = affinidi_did_resolver_cache_sdk::DIDCacheClient::new(
                vta_sdk::resolver::build_did_cache_config(None),
            )
            .await?;
            resolve_connect_url(did, &resolver).await?
        }
        (None, Some(url)) => url,
        _ => return Err("provide exactly one of --vta-did or --vta-url".into()),
    };

    let (ed_seed, ed_pub) = generate_ed25519_keypair();
    let nonce: [u8; 16] = rand::random();
    let bundle_id_hex = hex_lower(&nonce);

    // Reuse the SDK's canonical wire type so pnm speaks the same shape the
    // server `BootstrapRequestBody` deserializes. Emits `client_did` as a
    // `did:key:z6Mk…` string.
    let body = BootstrapRequest::new(ed_pub, nonce, None);

    // Largest bootstrap response read into memory: one armored bundle plus an
    // attestation document, a few KiB in practice.
    const MAX_BOOTSTRAP_RESPONSE_BYTES: usize = 1024 * 1024;

    let url = format!("{}/bootstrap/request", vta_url.trim_end_matches('/'));
    // The SDK client: finite timeouts, and no redirect off the VTA's origin.
    let client = vta_sdk::http::rest_client();
    let resp = client.post(&url).json(&body).send().await?;
    let status = resp.status();
    // Capture the headers before the body consumes the response: a 429 from the
    // VTA's unauth limiter carries `x-rate-limit-source` / `retry-after`, which
    // `rate_limited_from_http` reads to attribute the refusal.
    let headers = resp.headers().clone();
    let bytes = vta_sdk::http::read_body_capped(resp, MAX_BOOTSTRAP_RESPONSE_BYTES)
        .await
        .map_err(|e| format!("bootstrap request ({status}): {e}"))?;
    if !status.is_success() {
        let body = String::from_utf8_lossy(&bytes);
        // A rate limit must stay typed, or its message reads as a bootstrap
        // failure and sends the operator to check the enclave. The limiter runs
        // *before* the carve-out is touched, so the one-shot first boot is not
        // spent — retrying after the wait is safe.
        if let Some(rl) =
            vta_sdk::error::VtaError::rate_limited_from_http(status, &headers, &body, &url)
        {
            eprintln!(
                "The rate limit rejected this request before the enclave minted anything, \
                 so the one-time bootstrap is not spent — retry after the wait."
            );
            return Err(rl.into());
        }
        return Err(format!("bootstrap request failed ({status}): {body}").into());
    }
    let wire: BootstrapResponseWire = serde_json::from_slice(&bytes)?;

    // Optional client-side digest verification. Attestation + TLS give the
    // primary integrity anchor; this is a belt-and-suspenders check the
    // operator can opt into by communicating the digest out-of-band.
    if let Some(expected) = &expect_digest
        && !expected.eq_ignore_ascii_case(&wire.digest)
    {
        return Err(format!(
            "server-reported digest {} does not match expected {}",
            wire.digest, expected
        )
        .into());
    }

    let bundles = armor::decode(&wire.bundle)?;
    if bundles.len() != 1 {
        return Err(format!(
            "expected exactly one armored bundle from server, got {}",
            bundles.len()
        )
        .into());
    }
    let bundle = &bundles[0];
    if hex_lower(&bundle.bundle_id) != bundle_id_hex {
        return Err("server-returned bundle_id does not match our nonce".into());
    }

    // HPKE decryption uses the X25519 secret derived from our Ed25519 seed.
    let x_secret = ed25519_seed_to_x25519_secret(&ed_seed);
    let opened = open_bundle(&x_secret, bundle, expect_digest.as_deref())?;

    // The attestation quote binds the did:key-visible bytes end-to-end:
    //   SHA256(client_ed25519 || bundle_id || producer_ed25519)
    // so we pass the raw Ed25519 pubkey we generated (the same bytes the
    // server decoded from `client_did`) rather than any X25519 derivative.
    let attest = verify_nitro_assertion(&opened.producer, &ed_pub, &nonce)?;
    // Client-side PCR pinning (P3.4): refuse a genuine-but-WRONG enclave image
    // / signing cert. No-op unless the operator passed --expect-pcr0/8.
    attest
        .check_pcrs(expect_pcr0.as_deref(), expect_pcr8.as_deref())
        .map_err(|e| {
            format!(
                "{e}. The attestation is cryptographically valid but the enclave does not \
                 match the pinned measurement — refusing to bootstrap. Confirm the expected \
                 PCR against the deployed EIF / KMS key policy."
            )
        })?;
    println!("TEE attestation verified.");
    println!("  Enclave module: {}", attest.module_id);
    if !attest.pcr0_hex.is_empty() {
        let pinned = if expect_pcr0.is_some() {
            " (pinned ✓)"
        } else {
            ""
        };
        println!("  PCR0:           {}{pinned}", attest.pcr0_hex);
    }
    if !attest.pcr8_hex.is_empty() {
        let pinned = if expect_pcr8.is_some() {
            " (pinned ✓)"
        } else {
            ""
        };
        println!("  PCR8:           {}{pinned}", attest.pcr8_hex);
    }

    let credential = match opened.payload {
        SealedPayloadV1::AdminCredential(c) => c,
        other => {
            return Err(format!(
                "expected AdminCredential payload from online bootstrap, got {}",
                variant_name(&other)
            )
            .into());
        }
    };

    check_connect_vta_did(vta_did.as_deref(), &credential.vta_did)?;

    let slug = vta_slug.unwrap_or_else(|| default_slug(&credential.vta_did));
    pnm_config.vtas.insert(
        slug.clone(),
        crate::config::VtaConfig {
            name: slug.clone(),
            vta_did: Some(credential.vta_did.clone()),
            url: None,
            mediator_did: None,
        },
    );
    if pnm_config.default_vta.is_none() {
        pnm_config.default_vta = Some(slug.clone());
    }
    crate::config::save_config(pnm_config)?;

    // The bootstrap URL is only needed for the immediate `auth::ensure_authenticated`
    // call below — every subsequent command resolves the REST endpoint
    // from the VTA DID document at runtime.
    let keyring_key = crate::config::vta_keyring_key(&slug);
    auth::store_session(
        &keyring_key,
        &credential.did,
        &credential.private_key_multibase,
        &credential.vta_did,
    )?;
    // Verify the credential works end-to-end before declaring success.
    auth::ensure_authenticated(&vta_url, &keyring_key).await?;

    println!();
    println!("Bootstrap complete.");
    println!("  VTA slug:   {slug}");
    println!("  Client DID: {}", credential.did);
    println!("  VTA DID:    {}", credential.vta_did);
    println!("  Digest:     {}", bundle_digest(bundle));
    Ok(())
}

/// `pnm bootstrap provision-integration` — bridge a VP-framed
/// BootstrapRequest to the VTA over whichever transport the client
/// is currently using (REST or DIDComm), writing the returned
/// armored bundle to disk.
///
/// The VTA runs the same shared library fn for both transports and
/// the offline `vta bootstrap provision-integration` CLI; the only
/// difference between paths is the wire form of the request /
/// response. `VtaClient::provision_integration` dispatches:
/// - REST → `POST /bootstrap/provision-integration` with the
///   bearer token from the open session.
/// - DIDComm → `provision-integration/1.0` message over the open
///   authcrypt session. The VTA enforces that the DIDComm sender
///   DID matches the VP holder before issuing the bundle
///   (privilege-laundering guard).
#[allow(clippy::too_many_arguments)]
pub async fn run_provision_integration(
    client: &vta_sdk::client::VtaClient,
    request: PathBuf,
    context: Option<String>,
    assertion: String,
    vc_validity_seconds: Option<i64>,
    out: PathBuf,
    create_context: bool,
    admin_scope: String,
) -> Result<(), Box<dyn std::error::Error>> {
    use vta_sdk::provision_integration::http::{
        AdminScope, AssertionMode as WireAssertionMode, ProvisionIntegrationRequest,
    };

    // 1. Parse the integration's VP (but don't verify locally — the
    //    server does the authoritative verification).
    //
    //    Two views of the same document, deliberately. `vp_raw` is what
    //    goes on the wire: this VP was signed by the integration, not by
    //    us, so relaying the typed struct would re-render it in the SDK's
    //    casing and the maintainer would verify bytes the holder never
    //    signed. `vp` is a local read-only view, used only to resolve the
    //    context hint below.
    let request_json =
        fs::read_to_string(&request).map_err(|e| format!("read {}: {e}", request.display()))?;
    let vp_raw: serde_json::Value = serde_json::from_str(&request_json)
        .map_err(|e| format!("parse BootstrapRequest (VP): {e}"))?;
    let vp: vta_sdk::provision_integration::BootstrapRequest =
        serde_json::from_value(vp_raw.clone())
            .map_err(|e| format!("parse BootstrapRequest (VP): {e}"))?;

    // 2. Resolve context: explicit > hint > fail. If both present they
    //    must agree.
    let target_context = resolve_target_context_wire(&vp, context)?;

    // 3. Map assertion flag.
    let assertion_mode = match assertion.as_str() {
        "did-signed" | "didsigned" | "did_signed" => WireAssertionMode::DidSigned,
        "pinned-only" | "pinnedonly" | "pinned_only" | "pinned" => WireAssertionMode::PinnedOnly,
        other => {
            return Err(format!(
                "invalid --assertion value '{other}' — use 'did-signed' or 'pinned-only'"
            )
            .into());
        }
    };

    // 3b. Map the admin-scope flag. Clap's `value_parser` already rejects
    //     anything outside the pair, so the fallthrough is a wiring bug rather
    //     than operator input — say so instead of inventing a default, which
    //     would silently narrow a grant someone asked to widen.
    let admin_scope = match admin_scope.as_str() {
        "context" => AdminScope::Context,
        "unrestricted" => AdminScope::Unrestricted,
        other => {
            return Err(format!(
                "invalid --admin-scope value '{other}' — use 'context' or 'unrestricted'"
            )
            .into());
        }
    };

    // 4. Submit.
    let resp = client
        .provision_integration(ProvisionIntegrationRequest {
            request: vp_raw,
            // `--context` is required on the pnm-cli surface today, so
            // we always pass a concrete value. The wire field is
            // `Option<String>` per the canonical spec; future flag
            // changes can pass `None` to opt into VTA-side inference.
            context: Some(target_context.clone()),
            assertion: Some(assertion_mode),
            vc_validity_seconds,
            create_context,
            admin_scope,
        })
        .await?;

    // 5. Write bundle + print summary.
    fs::write(&out, resp.bundle.as_bytes()).map_err(|e| format!("write {}: {e}", out.display()))?;

    eprintln!(
        "Integration provisioned via {} — sealed bundle written to {}",
        client.endpoint_label(),
        out.display()
    );
    eprintln!();
    eprintln!("  Bundle-Id:       {}", resp.summary.bundle_id_hex);
    if resp.summary.context_created {
        eprintln!("  Context:         {target_context} (created inline via --create-context)");
    } else if create_context {
        eprintln!(
            "  Context:         {target_context} (already existed; --create-context was a no-op)"
        );
    } else {
        eprintln!("  Context:         {target_context}");
    }
    eprintln!("  Client DID:      {}", resp.summary.client_did);
    if resp.summary.admin_rolled_over {
        eprintln!(
            "  Admin DID:       {} (VTA-minted, rolled over from client)",
            resp.summary.admin_did
        );
        if let Some(ref admin_tpl) = resp.summary.admin_template_name {
            eprintln!("  Admin template:  {admin_tpl}");
        }
    } else {
        eprintln!("  Admin DID:       {} (== client)", resp.summary.admin_did);
    }
    if let Some(ref integration_did) = resp.summary.integration_did {
        eprintln!("  Integration DID: {integration_did}");
    } else {
        eprintln!("  Integration DID: (none — admin-rotation only)");
    }
    if let (Some(name), Some(kind)) = (
        resp.summary.template_name.as_deref(),
        resp.summary.template_kind.as_deref(),
    ) {
        eprintln!("  Template:        {name} ({kind})");
    }
    eprintln!("  Secrets:         {}", resp.summary.secret_count);
    eprintln!("  Outputs:         {}", resp.summary.output_count);
    // Printed as hex, because that is what `--expect-digest` takes and what an
    // operator reads out loud. The wire carries a multibase multihash as of
    // `provision/integration/0.3`; the two are the same digest in two
    // encodings, and the human-facing one should not change under an operator
    // mid-migration.
    let digest_hex = resp
        .digest_multibase
        .as_deref()
        .map(vta_sdk::sealed_transfer::multibase_digest_to_hex)
        .transpose()
        .unwrap_or(None);
    match digest_hex {
        Some(hex) => {
            eprintln!("  SHA-256 digest:  {hex}");
            eprintln!();
            eprintln!(
                "Communicate the digest to the integration's operator out-of-band so they can\n  \
                 verify the bundle on first boot:\n  \
                 pnm bootstrap open --bundle <file> --expect-digest {hex}",
            );
        }
        // The member is OPTIONAL from 0.3 on. Say so rather than print an empty
        // line an operator might read as a digest of nothing.
        None => {
            eprintln!("  SHA-256 digest:  (not supplied by this VTA)");
            eprintln!();
        }
    }
    Ok(())
}

fn resolve_target_context_wire(
    request: &vta_sdk::provision_integration::BootstrapRequest,
    explicit: Option<String>,
) -> Result<String, Box<dyn std::error::Error>> {
    use vta_sdk::provision_integration::BootstrapAsk;
    let hint = match &request.ask {
        BootstrapAsk::TemplateBootstrap(ask) => ask.context_hint.clone(),
        BootstrapAsk::AdminRotation(ask) => ask.context_hint.clone(),
    };
    match (explicit, hint) {
        (Some(explicit), Some(hint)) if explicit != hint => Err(format!(
            "--context '{explicit}' does not match request contextHint '{hint}' — \
             operator and integration must agree on the context before provisioning"
        )
        .into()),
        (Some(explicit), _) => Ok(explicit),
        (None, Some(hint)) => Ok(hint),
        (None, None) => Err(
            "no context specified — pass --context <id> or have the integration's \
             BootstrapRequest include a contextHint"
                .into(),
        ),
    }
}

fn variant_name(p: &SealedPayloadV1) -> &'static str {
    match p {
        SealedPayloadV1::AdminCredential(_) => "AdminCredential",
        SealedPayloadV1::ContextProvision(_) => "ContextProvision",
        SealedPayloadV1::DidSecrets(_) => "DidSecrets",
        SealedPayloadV1::AdminKeySet(_) => "AdminKeySet",
        SealedPayloadV1::RawPrivateKey(_) => "RawPrivateKey",
        SealedPayloadV1::TemplateBootstrap(_) => "TemplateBootstrap",
        SealedPayloadV1::AdminRotation(_) => "AdminRotation",
        SealedPayloadV1::IssuedCredential(_) => "IssuedCredential",
        SealedPayloadV1::MessagingBridgeCredentials(_) => "MessagingBridgeCredentials",
    }
}

fn default_slug(vta_did: &str) -> String {
    vta_did.rsplit(':').next().unwrap_or("vta").to_string()
}

#[cfg(test)]
mod tests {
    use super::parse_var;
    use serde_json::Value;

    const VTA_DID: &str =
        "did:webvh:Qmd1FCL9Vj2vJ433UDfC9MBstK6W6QWSQvYyeNn8va2fai:identity.example.com";

    async fn fixture_resolver(doc: Value) -> affinidi_did_resolver_cache_sdk::DIDCacheClient {
        let mut resolver = affinidi_did_resolver_cache_sdk::DIDCacheClient::new(
            vta_sdk::resolver::build_did_cache_config(None),
        )
        .await
        .unwrap();
        // These fixtures exercise endpoint selection, not log verification.
        resolver
            .add_did_document(VTA_DID, serde_json::from_value(doc).unwrap())
            .await;
        resolver
    }

    #[tokio::test]
    async fn connect_resolves_advertised_rest_host_port_and_path() {
        let resolver = fixture_resolver(serde_json::json!({
            "id": VTA_DID,
            "service": [
                {"id": format!("{VTA_DID}#tsp"), "type": "TSPTransport", "serviceEndpoint": "did:example:mediator"},
                {"id": format!("{VTA_DID}#custom-rest"), "type": "VTARest", "serviceEndpoint": "https://api.example.com:8443/vta/"}
            ]
        })).await;
        assert_eq!(
            super::resolve_connect_url(VTA_DID, &resolver)
                .await
                .unwrap(),
            "https://api.example.com:8443/vta"
        );
    }

    #[tokio::test]
    async fn connect_guards_did_advertised_rest_endpoints() {
        use vta_sdk::http::EndpointPolicy;

        for (url, public_allowed, private_allowed) in [
            ("https://api.example.com:8443/vta/", true, true),
            ("http://localhost:8100/vta/", true, true),
            ("http://127.0.0.1:8100/", true, true),
            ("http://[::1]:8100/", true, true),
            ("http://api.example.com/", false, false),
            ("http://10.0.0.5/", false, false),
            ("https://169.254.169.254/latest/meta-data/", false, false),
            ("https://[fe80::1]/", false, false),
            ("https://[fd00:ec2::254]/", false, false),
            ("https://metadata.google.internal/", false, false),
            (
                "https://operator:fixture-secret@api.example.com/",
                false,
                false,
            ),
            ("https://[::ffff:10.0.0.5]/", false, false),
            ("https://[::ffff:169.254.169.254]/", false, false),
            ("https://0.0.0.0/", false, false),
            ("https://192.0.2.1/", false, false),
            ("https://10.0.0.5:8443/vta/", false, true),
            ("https://192.168.1.10/", false, true),
            ("https://[fd00::1]/", false, true),
            ("https://100.64.0.1/", false, true),
            ("https://vta.internal/", false, true),
            ("file:///tmp/vta", false, false),
        ] {
            let resolver = fixture_resolver(serde_json::json!({
                "id": VTA_DID,
                "service": [{
                    "id": format!("{VTA_DID}#custom-rest"),
                    "type": "VTARest",
                    "serviceEndpoint": url,
                }],
            }))
            .await;
            for (policy, allowed) in [
                (EndpointPolicy::public_only(), public_allowed),
                (EndpointPolicy::private_allowed(), private_allowed),
            ] {
                let result =
                    super::resolve_connect_url_with_policy(VTA_DID, &resolver, policy).await;
                if allowed {
                    assert_eq!(result.unwrap(), url.trim_end_matches('/'));
                } else {
                    let error = result
                        .expect_err("unsafe DID endpoint must not fall back to its host")
                        .to_string();
                    assert!(error.contains(VTA_DID), "{error}");
                    assert!(!error.contains("fixture-secret"), "{error}");
                    // A guard rejection must not advertise --vta-url as its
                    // remedy: that flag skips this guard entirely, so
                    // suggesting it here would teach operators to route
                    // around the control rather than decide about it.
                    assert!(!error.contains("--vta-url"), "{error}");
                    if private_allowed {
                        assert!(error.contains("VTA_ALLOW_PRIVATE_ENDPOINTS"), "{error}");
                        assert!(error.contains("--allow-private-endpoints"), "{error}");
                    }
                }
            }
        }
    }

    #[tokio::test]
    async fn connect_refuses_missing_rest_or_wrong_document_instead_of_guessing_url() {
        for doc in [
            serde_json::json!({"id": VTA_DID}),
            serde_json::json!({"id": "did:web:other.example.com", "service": [
                {"id": "did:web:other.example.com#rest", "type": "VTARest", "serviceEndpoint": "https://api.example.com"}
            ]}),
        ] {
            let resolver = fixture_resolver(doc).await;
            let error = super::resolve_connect_url(VTA_DID, &resolver)
                .await
                .unwrap_err()
                .to_string();
            assert!(error.contains(VTA_DID));
            // Bootstrap resolution is local-only by design; say so, or an
            // operator whose egress reaches only a resolver sidecar reads
            // this as "the DID log is not published yet".
            assert!(error.contains("PNM_RESOLVER_URL"), "{error}");
            assert!(error.contains("--vta-url"));
        }
    }

    #[tokio::test]
    async fn connect_resolution_failure_names_did_and_explicit_fallback() {
        let resolver = fixture_resolver(serde_json::json!({"id": VTA_DID})).await;
        let did = "did:unsupported:bootstrap-target";
        let error = super::resolve_connect_url(did, &resolver)
            .await
            .unwrap_err()
            .to_string();
        assert!(error.contains(did));
        assert!(error.contains("--vta-url"));
    }

    #[test]
    fn connect_pins_credential_identity_but_preserves_url_fallback() {
        assert!(super::check_connect_vta_did(Some(VTA_DID), VTA_DID).is_ok());
        assert!(super::check_connect_vta_did(None, VTA_DID).is_ok());
        assert!(super::check_connect_vta_did(Some(VTA_DID), "did:web:other.example.com").is_err());
    }

    #[test]
    fn connect_anchor_flag_matrix() {
        let valid = "ab12".repeat(24);
        for digest in [None, Some("digest")] {
            for opt_out in [false, true] {
                for pcr0 in [None, Some(valid.as_str())] {
                    // PCR8 is an additional pin, never an anchor on its own:
                    // it measures the signing certificate, not the image.
                    for pcr8 in [None, Some(valid.as_str())] {
                        let expected = !(digest.is_some() && opt_out)
                            && (digest.is_some() || opt_out || pcr0.is_some());
                        assert_eq!(
                            super::validate_connect_anchor(digest, opt_out, pcr0, pcr8).is_ok(),
                            expected,
                            "digest={digest:?}, opt_out={opt_out}, pcr0={pcr0:?}, pcr8={pcr8:?}",
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn connect_accepts_valid_normalized_pcr0_as_sole_anchor() {
        let pcr0 = "ab12".repeat(24);
        for value in [
            pcr0.clone(),
            pcr0.to_uppercase(),
            format!("0x{pcr0}"),
            format!(" \t0X{}\n ", "AB12 \t".repeat(24)),
        ] {
            super::validate_connect_anchor(None, false, Some(&value), None).unwrap();
            super::validate_connect_anchor(None, false, Some(&value), Some(&value)).unwrap();
        }
    }

    /// Both pins, not just PCR0. `/bootstrap/request` closes the first-boot
    /// carve-out server-side before it returns the bundle, so a pin rejected
    /// only at `check_pcrs` — after the POST — is rejected once the VTA's
    /// one-shot bootstrap has already been spent. A typo'd `--expect-pcr8`
    /// must therefore fail here, with nothing sent.
    #[tokio::test]
    async fn connect_rejects_malformed_pcrs_before_resolving_or_posting() {
        let valid = "ab12".repeat(24);
        for value in [
            "".to_string(),
            " ".to_string(),
            "0x".to_string(),
            " \t0X\n".to_string(),
            "abcd".to_string(),
            "a".repeat(95),
            "a".repeat(97),
            format!("{}g", "a".repeat(95)),
        ] {
            // `which` names the malformed pin; the other is well-formed, so a
            // failure can only come from the one under test.
            for (which, pcr0, pcr8) in [
                (0u8, Some(value.clone()), None),
                (0, Some(value.clone()), Some(valid.clone())),
                (8, Some(valid.clone()), Some(value.clone())),
                // A malformed PCR8 alongside another valid anchor still fails:
                // the pin is checked, not merely consulted when it is load-bearing.
                (8, None, Some(value.clone())),
            ] {
                for (digest, opt_out) in [(None, false), (Some("digest"), false), (None, true)] {
                    for by_did in [true, false] {
                        let mut config = crate::config::PnmConfig::default();
                        // Invalid targets fail differently if preflight is skipped.
                        // Neither target can contact an external service in a regression.
                        let error = super::run_connect(
                            by_did.then(|| "did:unsupported:bootstrap-target".into()),
                            (!by_did).then(|| "not-a-url".into()),
                            digest.map(str::to_string),
                            opt_out,
                            pcr0.clone(),
                            pcr8.clone(),
                            None,
                            &mut config,
                        )
                        .await
                        .unwrap_err();
                        assert!(
                            matches!(
                                error.downcast_ref::<vta_sdk::attestation::ConfigAttestationVerifyError>(),
                                Some(vta_sdk::attestation::ConfigAttestationVerifyError::InvalidExpectedPcr { which: actual, .. })
                                    if *actual == which
                            ),
                            "which={which}, value={value:?}, error={error}"
                        );
                        assert!(config.vtas.is_empty());
                        assert!(config.default_vta.is_none());
                    }
                }
            }
        }
    }

    #[test]
    fn connect_missing_anchor_explains_all_routes() {
        // PCR8 alone leaves the image unpinned, so it must land on the same
        // error rather than reading as a satisfied anchor.
        for pcr8 in [None, Some("ab12".repeat(24))] {
            let error = super::validate_connect_anchor(None, false, None, pcr8.as_deref())
                .unwrap_err()
                .to_string();
            for route in ["--expect-pcr0", "--expect-digest", "--no-verify-digest"] {
                assert!(error.contains(route), "{error}");
            }
            assert!(error.contains("generated server-side"), "{error}");
        }
        assert!(vta_cli_common::sealed_consumer::validate_digest_flags(None, false).is_err());
    }

    #[test]
    fn parse_var_plain_string() {
        let (k, v) = parse_var("URL=https://mediator.example.com").unwrap();
        assert_eq!(k, "URL");
        assert_eq!(v, Value::String("https://mediator.example.com".into()));
    }

    #[test]
    fn parse_var_json_types_round_trip() {
        assert_eq!(parse_var("N=42").unwrap().1, Value::Number(42.into()));
        assert_eq!(parse_var("B=true").unwrap().1, Value::Bool(true));
        assert!(parse_var(r#"A=[1,2]"#).unwrap().1.is_array());
    }

    #[test]
    fn parse_var_value_may_contain_equals() {
        let (_, v) = parse_var("URL=https://m.example.com?x=1").unwrap();
        assert_eq!(v.as_str(), Some("https://m.example.com?x=1"));
    }

    #[test]
    fn parse_var_missing_equals_errors() {
        assert!(parse_var("LONELY").is_err());
    }

    #[test]
    fn parse_var_empty_key_errors() {
        assert!(parse_var("=value").is_err());
    }

    fn scratch_path(name: &str) -> std::path::PathBuf {
        let mut p = std::env::temp_dir();
        p.push(format!("pnm-open-out-{name}-{}.json", std::process::id()));
        p
    }

    fn sample_bundle() -> vta_sdk::credentials::CredentialBundle {
        vta_sdk::credentials::CredentialBundle {
            did: "did:key:z6MkTest".into(),
            private_key_multibase: "z3SecretTest".into(),
            vta_did: "did:webvh:QmTest:vta.example.com:vta".into(),
            vta_url: Some("https://vta.example.com".into()),
        }
    }

    /// The on-disk field names are the contract with file-based consumers
    /// (the trust registry's `TR_VTA_CREDENTIAL` parses exactly these), so
    /// assert the serde renames rather than the Rust field names.
    #[test]
    fn written_credential_uses_wire_field_names() {
        let path = scratch_path("fields");
        super::write_credential_bundle(&path, &sample_bundle()).unwrap();

        let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
        assert_eq!(v["did"], "did:key:z6MkTest");
        assert_eq!(v["privateKeyMultibase"], "z3SecretTest");
        assert_eq!(v["vtaDid"], "did:webvh:QmTest:vta.example.com:vta");
        assert_eq!(v["vtaUrl"], "https://vta.example.com");

        std::fs::remove_file(&path).ok();
    }

    /// `vtaUrl` is `skip_serializing_if = "Option::is_none"`, so an absent
    /// URL must omit the key entirely rather than emit `null` — the
    /// registry's loader treats an explicit null as a parse error.
    #[test]
    fn written_credential_omits_absent_vta_url() {
        let path = scratch_path("nourl");
        let mut bundle = sample_bundle();
        bundle.vta_url = None;
        super::write_credential_bundle(&path, &bundle).unwrap();

        let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
        assert!(v.get("vtaUrl").is_none());

        std::fs::remove_file(&path).ok();
    }

    #[cfg(unix)]
    #[test]
    fn written_credential_is_owner_only() {
        use std::os::unix::fs::PermissionsExt;

        let path = scratch_path("perms");
        super::write_credential_bundle(&path, &sample_bundle()).unwrap();

        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
        assert_eq!(
            mode & 0o777,
            0o600,
            "credential file must not be group/world readable"
        );

        std::fs::remove_file(&path).ok();
    }

    /// Writing must overwrite, not append — re-running against an existing
    /// path would otherwise produce trailing garbage after valid JSON.
    #[cfg(unix)]
    #[test]
    fn written_credential_truncates_existing_file() {
        let path = scratch_path("truncate");
        std::fs::write(&path, vec![b'x'; 4096]).unwrap();
        super::write_credential_bundle(&path, &sample_bundle()).unwrap();

        // Parses cleanly => no leftover bytes from the longer previous file.
        let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
        assert_eq!(v["did"], "did:key:z6MkTest");

        std::fs::remove_file(&path).ok();
    }
}