vgi-bridge 0.16.0

The per-community VGI bridge: holds the community's forge credentials, takes git-ns/bridge jobs from its VTC over TSP or DIDComm, runs the forge adapters, reports results, events and drift, and posts the commit-trust check where no forge feature can be trusted to.
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
//! The bridge's own DID and keys.
//!
//! The bridge is a companion service with its own DID (design §5.1): the VTC
//! records, per namespace, which bridge DID serves it, and refuses results
//! and events from any other. Two shapes, per the VTI house rules:
//!
//! - **`did:webvh`, provisioned by the community's VTA** (recommended). The
//!   operator provisions a DID for the bridge from the VTA the same way the
//!   VTC's is (a DID template), and imports the resulting secrets bundle with
//!   `vgi-bridge identity import`. The VTA mints; the bridge only holds.
//! - **`did:peer:2`**, minted locally by `vgi-bridge init`. Nothing to host:
//!   the identifier carries the keys *and* a `TSPTransport` and a
//!   `DIDCommMessaging` service naming the mediator the bridge listens at,
//!   which is how the VTC finds where to send jobs (it picks a transport from
//!   the services the bridge's DID document advertises — TSP first — and a
//!   `did:key` advertises none). Because the
//!   mediator is part of the identifier, moving the bridge to another
//!   mediator means a new DID, registered again at the VTC.
//! - **`did:key`**: still loaded from a store that holds one (earlier
//!   releases minted it), but a VTC cannot send it jobs; `run` says so.
//!
//! In VTA mode ([`crate::vta`]) the identity is the `did:webvh` of the
//! bridge's own context in the VTC's VTA: its keys are fetched into memory at
//! start-up and never stored here, and a rotation in the VTA replaces them at
//! run time ([`crate::Bridge::replace_identity`]).
//!
//! Otherwise the private keys are held only in the sealed store, and the
//! same keys serve TSP, DIDComm (authcrypt) and the Data Integrity proofs on
//! every Trust Task document the bridge sends.

use std::fmt;

use affinidi_tdk::affinidi_crypto::KeyType;
use affinidi_tdk::secrets_resolver::secrets::Secret;
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use trust_tasks_proof::affinidi::{SignOptions, sign_trust_task};
use vta_sdk::did_secrets::DidSecretsBundle;
use zeroize::Zeroizing;

use crate::store::Store;

/// The sealed secret the identity is stored under.
pub const IDENTITY_SECRET: &str = "identity";

/// The longest DID the bridge mints. Every `DIDCacheClient` refuses to parse
/// a longer one (`max_did_size_in_bytes`, default 1000), and neither end of a
/// DIDComm session says that is why it failed: the connect times out. A
/// `did:peer:2` carries its service inside the identifier, so a mediator with
/// a long DID (a `did:peer` of its own) can push it past this.
pub const MAX_DID_BYTES: usize = 1000;

/// The DID-document service `type` of a DIDComm v2 endpoint (W3C) — one of
/// the services the VTC selects a bridge's transport by.
pub const DIDCOMM_SERVICE_TYPE: &str = "DIDCommMessaging";

/// The DID-document service `type` of a TSP endpoint, whose
/// `serviceEndpoint` is the mediator's DID — the service the VTC prefers.
pub const TSP_SERVICE_TYPE: &str = "TSPTransport";

/// What the sealed identity secret holds.
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "type")]
enum StoredIdentity {
    /// A locally minted `did:key`: its 32-byte Ed25519 seed, hex.
    DidKey { did: String, seed: String },
    /// A VTA-provisioned DID: its secrets bundle.
    Bundle { bundle: DidSecretsBundle },
}

/// The bridge's DID and the secrets behind it.
#[derive(Clone)]
pub struct BridgeIdentity {
    did: String,
    signing: Secret,
    secrets: Vec<Secret>,
}

impl fmt::Debug for BridgeIdentity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BridgeIdentity")
            .field("did", &self.did)
            .field("secrets", &self.secrets.len())
            .finish()
    }
}

impl BridgeIdentity {
    /// A new `did:key` from a fresh Ed25519 seed. Returns the identity and
    /// the seed to seal.
    pub fn generate_did_key() -> Result<(Self, Zeroizing<[u8; 32]>)> {
        let mut seed = Zeroizing::new([0u8; 32]);
        aws_lc_rs::rand::fill(seed.as_mut())
            .map_err(|_| anyhow::anyhow!("system RNG unavailable"))?;
        let identity = Self::from_seed(&seed)?;
        Ok((identity, seed))
    }

    /// The `did:key` for an Ed25519 seed.
    pub fn from_seed(seed: &[u8; 32]) -> Result<Self> {
        let public = ed25519_dalek::SigningKey::from_bytes(seed)
            .verifying_key()
            .to_bytes();
        let did = format!(
            "did:key:{}",
            vta_sdk::did_key::ed25519_multibase_pubkey(&public)
        );
        let s = vta_sdk::did_key::secrets_from_did_key(&did, seed)
            .map_err(|e| anyhow::anyhow!("did:key secrets: {e}"))?;
        Ok(BridgeIdentity {
            did,
            signing: s.signing.clone(),
            secrets: vec![s.signing, s.key_agreement],
        })
    }

    /// An identity from a VTA-provisioned secrets bundle. Its first Ed25519
    /// key signs; every key goes to DIDComm.
    pub fn from_bundle(bundle: &DidSecretsBundle) -> Result<Self> {
        let secrets = vta_sdk::did_key::secrets_from_bundle(bundle)
            .map_err(|e| anyhow::anyhow!("DID secrets bundle: {e}"))?;
        for s in &secrets {
            if !s.id.starts_with(&format!("{}#", bundle.did)) {
                bail!(
                    "bundle key `{}` does not belong to `{}`: refusing a bundle for another DID",
                    s.id,
                    bundle.did
                );
            }
        }
        let signing = secrets
            .iter()
            .find(|s| s.get_key_type() == KeyType::Ed25519)
            .cloned()
            .context("the bundle has no Ed25519 key to sign documents with")?;
        if !secrets.iter().any(|s| s.get_key_type() == KeyType::X25519) {
            bail!("the bundle has no X25519 key-agreement key; DIDComm needs one");
        }
        Ok(BridgeIdentity {
            did: bundle.did.clone(),
            signing,
            secrets,
        })
    }

    /// A new `did:peer:2` whose document advertises TSP and DIDComm through
    /// `mediator_did`: an Ed25519 key that signs (and authenticates), an
    /// X25519 key for key agreement (and TSP's encryption), a `#tsp`
    /// `TSPTransport` service and a `DIDCommMessaging` service. The returned
    /// bundle is what to seal ([`Self::store_bundle`]).
    pub fn generate_did_peer(mediator_did: &str) -> Result<(Self, DidSecretsBundle)> {
        use affinidi_tdk::dids::{
            DID, OneOrMany, PeerKeyRole, PeerService, PeerServiceEndpoint, PeerServiceEndpointLong,
        };
        if mediator_did.trim().is_empty() || !mediator_did.starts_with("did:") {
            bail!("`{mediator_did}` is not a mediator DID");
        }
        let didcomm = PeerService {
            type_: DIDCOMM_SERVICE_TYPE.into(),
            endpoint: PeerServiceEndpoint::Long(OneOrMany::One(PeerServiceEndpointLong {
                uri: mediator_did.to_string(),
                accept: vec!["didcomm/v2".into()],
                routing_keys: vec![],
            })),
            id: None,
        };
        // The shape the TSP stack reads a peer's mediator from: the bare
        // mediator DID, no DIDComm `accept` (that would claim something
        // untrue of TSP).
        let tsp = PeerService {
            type_: TSP_SERVICE_TYPE.into(),
            endpoint: PeerServiceEndpoint::Uri(mediator_did.to_string()),
            id: Some("#tsp".into()),
        };
        let mint = |services: Vec<PeerService>| {
            DID::generate_did_peer_with_services(
                vec![
                    (
                        PeerKeyRole::Verification,
                        affinidi_tdk::dids::KeyType::Ed25519,
                    ),
                    (PeerKeyRole::Encryption, affinidi_tdk::dids::KeyType::X25519),
                ],
                Some(services),
            )
            .map_err(|e| anyhow::anyhow!("minting a did:peer: {e}"))
        };
        // Both services carry the mediator DID, so a mediator with a long DID
        // (a did:peer of its own) can push the pair past the limit. Then the
        // DIDComm service alone — the VTC still reaches the bridge, over
        // DIDComm — rather than no bridge at all.
        let (mut did, mut secrets) = mint(vec![didcomm.clone(), tsp])?;
        let mut with_tsp = true;
        if did.len() > MAX_DID_BYTES {
            (did, secrets) = mint(vec![didcomm])?;
            with_tsp = false;
            if did.len() <= MAX_DID_BYTES {
                tracing::warn!(
                    mediator = %mediator_did,
                    "the mediator's DID is too long to advertise both TSP and DIDComm in a \
                     did:peer; minted one advertising DIDComm only (the VTC reaches it over \
                     DIDComm). For TSP, use a mediator with a short DID or a did:webvh bridge DID"
                );
            }
        }
        if did.len() > MAX_DID_BYTES {
            bail!(
                "the did:peer this would mint is {} bytes, past the {MAX_DID_BYTES}-byte limit \
                 every DID resolver enforces, so the VTC could not resolve it. A did:peer \
                 carries its mediator inside the identifier: use a mediator with a short DID \
                 (a did:web or did:webvh), or provision a did:webvh for the bridge instead",
                did.len()
            );
        }
        let bundle = bundle_of(&did, &secrets)?;
        let identity = Self::from_bundle(&bundle)?;
        let mut minted = vec![("DIDComm", advertised_mediator(&did)?)];
        if with_tsp {
            minted.push(("TSP", advertised_tsp_mediator(&did)?));
        }
        for (kind, advertised) in minted {
            match advertised {
                Some(m) if m == mediator_did => {}
                other => bail!(
                    "the minted did:peer advertises {kind} at {other:?}, not `{mediator_did}`: \
                     refusing it"
                ),
            }
        }
        Ok((identity, bundle))
    }

    /// The identity as a secrets bundle — the format `identity import`
    /// reads, so an export is restored by importing it. Key material.
    pub fn to_bundle(&self) -> Result<DidSecretsBundle> {
        bundle_of(&self.did, &self.secrets)
    }

    /// The sealed identity as a secrets bundle, for export: an imported or
    /// minted bundle exactly as stored — every key it carries, whatever its
    /// type — and a `did:key` seed as the bundle of its two keys. `None`
    /// before `init` / `identity import`.
    pub fn stored_bundle(store: &Store) -> Result<Option<DidSecretsBundle>> {
        let Some(bytes) = store.get_secret(IDENTITY_SECRET)? else {
            return Ok(None);
        };
        let stored: StoredIdentity =
            serde_json::from_slice(&bytes).context("decoding the sealed identity")?;
        match stored {
            StoredIdentity::Bundle { bundle } => Ok(Some(bundle)),
            StoredIdentity::DidKey { .. } => {
                Self::load(store)?.map(|id| id.to_bundle()).transpose()
            }
        }
    }

    /// Seal a `did:key` seed as the bridge's identity.
    pub fn store_did_key(store: &Store, seed: &[u8; 32]) -> Result<Self> {
        let identity = Self::from_seed(seed)?;
        let stored = StoredIdentity::DidKey {
            did: identity.did.clone(),
            seed: hex::encode(seed),
        };
        let json = Zeroizing::new(serde_json::to_vec(&stored)?);
        store.put_secret(IDENTITY_SECRET, &json)?;
        Ok(identity)
    }

    /// Seal a VTA-provisioned bundle as the bridge's identity.
    pub fn store_bundle(store: &Store, bundle: DidSecretsBundle) -> Result<Self> {
        let identity = Self::from_bundle(&bundle)?;
        let json = Zeroizing::new(serde_json::to_vec(&StoredIdentity::Bundle { bundle })?);
        store.put_secret(IDENTITY_SECRET, &json)?;
        Ok(identity)
    }

    /// Load the sealed identity. `None` before `init` / `identity import`.
    pub fn load(store: &Store) -> Result<Option<Self>> {
        let Some(bytes) = store.get_secret(IDENTITY_SECRET)? else {
            return Ok(None);
        };
        let stored: StoredIdentity =
            serde_json::from_slice(&bytes).context("decoding the sealed identity")?;
        Ok(Some(match stored {
            StoredIdentity::DidKey { did, seed } => {
                let raw = Zeroizing::new(hex::decode(seed).context("identity seed")?);
                let seed: [u8; 32] = raw
                    .as_slice()
                    .try_into()
                    .map_err(|_| anyhow::anyhow!("identity seed is not 32 bytes"))?;
                let id = Self::from_seed(&seed)?;
                if id.did != did {
                    bail!("the sealed seed does not derive the sealed DID `{did}`");
                }
                id
            }
            StoredIdentity::Bundle { bundle } => Self::from_bundle(&bundle)?,
        }))
    }

    /// The bridge's DID.
    pub fn did(&self) -> &str {
        &self.did
    }

    /// An identity from secrets already checked against the DID's current
    /// document (VTA mode, [`crate::vta`]): `signing` signs, every secret
    /// goes to DIDComm (all the key-agreement keys the document lists, so a
    /// message encrypted to any of them — during a rotation's overlap —
    /// still opens).
    pub fn from_secrets(did: &str, signing: Secret, secrets: Vec<Secret>) -> Result<Self> {
        for s in &secrets {
            if !s.id.starts_with(&format!("{did}#")) {
                bail!("key `{}` does not belong to `{did}`", s.id);
            }
        }
        if signing.get_key_type() != KeyType::Ed25519 || !secrets.iter().any(|s| s.id == signing.id)
        {
            bail!(
                "the signing key `{}` is not an Ed25519 key of the set",
                signing.id
            );
        }
        Ok(BridgeIdentity {
            did: did.to_string(),
            signing,
            secrets,
        })
    }

    /// The verification method that signs.
    pub fn signing_key_id(&self) -> &str {
        &self.signing.id
    }

    /// Every secret held.
    pub(crate) fn secrets(&self) -> &[Secret] {
        &self.secrets
    }

    /// Whether `other` holds the same keys (ids and public halves).
    pub fn same_keys(&self, other: &BridgeIdentity) -> bool {
        let keys = |i: &BridgeIdentity| {
            let mut v: Vec<(String, Vec<u8>)> = i
                .secrets
                .iter()
                .map(|s| (s.id.clone(), s.get_public_bytes().to_vec()))
                .collect();
            v.sort();
            v
        };
        self.did == other.did && self.signing.id == other.signing.id && keys(self) == keys(other)
    }

    /// Every secret DIDComm needs (signing and key agreement).
    pub fn messaging_secrets(&self) -> Vec<Secret> {
        self.secrets.clone()
    }

    /// Sign a Trust Task document (`eddsa-jcs-2022`, `authentication`).
    /// `doc.issuer` must already be this DID.
    ///
    /// `authentication` is passed explicitly — it is also
    /// `sign_trust_task`'s own default — because this is the purpose SPEC.md
    /// asks a producer to sign with (proving the bridge controls its
    /// identifier), and the one `wire::DocChecker::check` requires on every
    /// inbound document: `git-ns/bridge/result` and `git-ns/bridge/event`
    /// define no attestation, so `assertionMethod` is never right for them.
    pub async fn sign(&self, doc: &Value) -> Result<Value> {
        sign_trust_task(
            doc,
            &self.signing,
            SignOptions::new().with_proof_purpose("authentication"),
        )
        .await
        .map_err(|e| anyhow::anyhow!("signing a document: {e}"))
    }
}

/// A secrets bundle for `did` from its secrets.
fn bundle_of(did: &str, secrets: &[Secret]) -> Result<DidSecretsBundle> {
    use vta_sdk::did_secrets::SecretEntry;
    use vta_sdk::keys::KeyType as BundleKeyType;
    let secrets = secrets
        .iter()
        .map(|s| {
            let key_type = match s.get_key_type() {
                KeyType::Ed25519 => BundleKeyType::Ed25519,
                KeyType::X25519 => BundleKeyType::X25519,
                other => bail!("key `{}` is {other:?}, which a bundle does not carry", s.id),
            };
            Ok(SecretEntry {
                key_id: s.id.clone(),
                key_type,
                private_key_multibase: s
                    .get_private_keymultibase()
                    .map_err(|e| anyhow::anyhow!("encoding key `{}`: {e}", s.id))?,
            })
        })
        .collect::<Result<Vec<_>>>()?;
    Ok(DidSecretsBundle {
        did: did.to_string(),
        secrets,
    })
}

/// Where a DID resolvable without the network (`did:key`, `did:peer`) says
/// it takes DIDComm: the `serviceEndpoint` URI of its `DIDCommMessaging`
/// service — for a mediated party, the mediator's DID. `Ok(None)`: the
/// document advertises no DIDComm service, as a `did:key`'s never does.
/// `Err` for a DID that needs the network to resolve (`did:webvh`,
/// `did:web`): its document is its host's to publish, not the bridge's to
/// second-guess.
pub fn advertised_mediator(did: &str) -> Result<Option<String>> {
    advertised_endpoint(did, DIDCOMM_SERVICE_TYPE)
}

/// Where a DID resolvable without the network says it takes TSP: the
/// mediator DID its `TSPTransport` service names. `Ok(None)`: it advertises
/// no TSP (a `did:key`, or a `did:peer` minted before the bridge spoke TSP).
/// `Err` as for [`advertised_mediator`].
pub fn advertised_tsp_mediator(did: &str) -> Result<Option<String>> {
    advertised_endpoint(did, TSP_SERVICE_TYPE)
}

fn advertised_endpoint(did: &str, service_type: &str) -> Result<Option<String>> {
    if !(did.starts_with("did:key:") || did.starts_with("did:peer:")) {
        bail!("`{did}` is not resolvable without the network");
    }
    let parsed: affinidi_tdk::did_common::DID = did
        .parse()
        .map_err(|e| anyhow::anyhow!("`{did}` is not a DID: {e}"))?;
    let doc = parsed
        .resolve()
        .map_err(|e| anyhow::anyhow!("resolving `{did}`: {e}"))?;
    let doc = serde_json::to_value(&doc)?;
    let Some(services) = doc.get("service").and_then(Value::as_array) else {
        return Ok(None);
    };
    Ok(services.iter().find_map(|svc| {
        let typed = match svc.get("type") {
            Some(Value::String(t)) => t == service_type,
            Some(Value::Array(ts)) => ts.iter().any(|t| t == service_type),
            _ => false,
        };
        typed
            .then(|| svc.get("serviceEndpoint").and_then(endpoint_uri))
            .flatten()
    }))
}

fn endpoint_uri(endpoint: &Value) -> Option<String> {
    match endpoint {
        Value::String(s) => Some(s.clone()),
        Value::Object(map) => map.get("uri")?.as_str().map(str::to_string),
        Value::Array(arr) => arr.iter().find_map(endpoint_uri),
        _ => None,
    }
}

/// Whether the VTC can reach `did` through `mediator_did` — the check `run`
/// and `identity import` make before a bridge goes into service.
///
/// - `Ok(None)`: yes, or it cannot be told locally (a `did:webvh` publishes
///   its own document; the VTC resolves it).
/// - `Ok(Some(warning))`: the DID advertises no TSP or DIDComm service (a
///   `did:key`), so no VTC can send it jobs. The bridge still runs — results
///   and events still go out — but the operator must know.
/// - `Err`: the DID names another mediator. A `did:peer` names its mediator
///   forever; served from a different one, the VTC would deliver jobs where
///   the bridge no longer listens, and nothing would say why.
pub fn check_reachable(did: &str, mediator_did: &str) -> Result<Option<String>> {
    if !(did.starts_with("did:key:") || did.starts_with("did:peer:")) {
        return Ok(None);
    }
    // A did:peer minted before the bridge spoke TSP advertises DIDComm only:
    // still served (the VTC reaches it over DIDComm). One whose TSP or DIDComm
    // service names another mediator is refused.
    let tsp = advertised_tsp_mediator(did)?;
    let didcomm = advertised_mediator(did)?;
    if let Some(m) = [&tsp, &didcomm]
        .into_iter()
        .flatten()
        .find(|m| m.as_str() != mediator_did)
    {
        bail!(
            "the bridge's DID `{did}` advertises the mediator `{m}`, but the config names \
             `{mediator_did}`. A did:peer names its mediator in its identifier, so the VTC \
             would send jobs to `{m}`, where this bridge would not be listening.\n\
             Fix (recommended, and the only one that keeps bound namespaces working): set \
             `mediator_did = \"{m}\"` back in the config.\n\
             Only for a bridge that serves no bound namespace: mint a new identity \
             (`vgi-bridge identity mint --replace --backup <file>`) and register the new DID \
             at the VTC — see `identity mint --help` for what a new DID breaks"
        );
    }
    match didcomm {
        Some(_) => Ok(None),
        // TSP only: reachable (checked above).
        None if tsp.is_some() => Ok(None),
        None => Ok(Some(format!(
            "the bridge's DID `{did}` advertises no TSP or DIDComm service, so no VTC can send it \
             jobs (they fail with `noMatchingProtocol`). Mint a did:peer that names the \
             mediator (`vgi-bridge identity mint --replace --backup <file>`) and register \
             the new DID at the VTC"
        ))),
    }
}

/// The key the bridge signs git commits with (the Dependabot re-sign): its
/// DID's Ed25519 signing key, and the verification method that names it.
/// The key is wiped when this is dropped.
pub struct GitSigningKey {
    /// The verification method id (`<did>#<fragment>`), for the
    /// `Signed-by-DID:` trailer.
    pub verification_method: String,
    /// The key.
    pub key: ed25519_dalek::SigningKey,
}

impl fmt::Debug for GitSigningKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GitSigningKey")
            .field("verification_method", &self.verification_method)
            .finish_non_exhaustive()
    }
}

impl BridgeIdentity {
    /// The key the bridge signs git commits with: the same Ed25519 key that
    /// signs its Trust Task documents, which its DID document publishes as a
    /// verification method (a `did:peer` or `did:key` always does; a VTA-provisioned
    /// `did:webvh` does for the key in its bundle). verify-trust resolves the
    /// DID and accepts a commit signature only from a key the document
    /// publishes. The sshsig `git` namespace keeps a commit signature from
    /// ever being mistaken for a document proof, and the other way round.
    pub fn git_signing_key(&self) -> Result<GitSigningKey> {
        let private = self.signing.get_private_bytes();
        let seed: Zeroizing<[u8; 32]> = Zeroizing::new(
            private
                .get(..32)
                .and_then(|s| <[u8; 32]>::try_from(s).ok())
                .context("the signing key is not an Ed25519 seed")?,
        );
        let key = ed25519_dalek::SigningKey::from_bytes(&seed);
        if key.verifying_key().as_bytes().as_slice() != self.signing.get_public_bytes() {
            bail!("the signing key's public half does not match the identity");
        }
        if !self.signing.id.starts_with(&format!("{}#", self.did)) {
            bail!(
                "the signing key `{}` is not a verification method of `{}`",
                self.signing.id,
                self.did
            );
        }
        Ok(GitSigningKey {
            verification_method: self.signing.id.clone(),
            key,
        })
    }

    /// Sign with a chosen `proofPurpose` — for tests of the purpose check
    /// only; every document the bridge sends is an `authentication` proof.
    #[doc(hidden)]
    pub async fn sign_with_purpose(&self, doc: &Value, purpose: &str) -> Result<Value> {
        sign_trust_task(
            doc,
            &self.signing,
            SignOptions::new().with_proof_purpose(purpose),
        )
        .await
        .map_err(|e| anyhow::anyhow!("signing a document: {e}"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::seal::MasterKey;
    use trust_tasks_proof::affinidi::Verifier;

    #[tokio::test]
    async fn a_did_key_signs_what_a_did_key_verifier_accepts() {
        let (id, seed) = BridgeIdentity::generate_did_key().unwrap();
        assert!(id.did().starts_with("did:key:z6Mk"));
        let doc = serde_json::json!({
            "id": "urn:uuid:1",
            "type": "https://trusttasks.org/spec/git-ns/bridge/result/0.1",
            "issuer": id.did(),
            "payload": { "jobId": "j", "outcome": "succeeded" },
        });
        let signed = id.sign(&doc).await.unwrap();
        Verifier::for_did_key().verify_raw(&signed).await.unwrap();

        let store = Store::in_memory(MasterKey::generate().unwrap()).unwrap();
        BridgeIdentity::store_did_key(&store, &seed).unwrap();
        let back = BridgeIdentity::load(&store).unwrap().unwrap();
        assert_eq!(back.did(), id.did());
        assert_eq!(back.messaging_secrets().len(), 2);
        assert!(!format!("{back:?}").contains(&hex::encode(*seed)));
    }

    #[test]
    fn the_git_signing_key_is_the_did_key() {
        let id = BridgeIdentity::from_seed(&[5u8; 32]).unwrap();
        let k = id.git_signing_key().unwrap();
        assert_eq!(k.key.to_bytes(), [5u8; 32]);
        let mb = id.did().strip_prefix("did:key:").unwrap();
        assert_eq!(k.verification_method, format!("{}#{mb}", id.did()));
        assert!(
            format!("{k:?}").ends_with(", .. }"),
            "no key material in Debug"
        );
    }

    const MEDIATOR: &str = "did:web:mediator.acme-vtc.example";

    #[tokio::test]
    async fn a_did_peer_advertises_tsp_and_didcomm_through_its_mediator() {
        let (id, bundle) = BridgeIdentity::generate_did_peer(MEDIATOR).unwrap();
        assert!(id.did().starts_with("did:peer:2."), "{}", id.did());
        assert!(id.did().len() <= MAX_DID_BYTES);
        // A bare DID by the Trust Task `Did` syntax, and one a commit
        // trailer's `#`/`?`/`/` split leaves whole (the Dependabot re-sign):
        // base64url, no padding.
        assert!(
            id.did()
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || ":.-_".contains(c)),
            "{}",
            id.did()
        );
        // What the VTC selects a transport by: a `TSPTransport` and a
        // `DIDCommMessaging` service naming the mediator, found in the
        // document the DID resolves to.
        assert_eq!(
            advertised_mediator(id.did()).unwrap().as_deref(),
            Some(MEDIATOR)
        );
        assert_eq!(
            advertised_tsp_mediator(id.did()).unwrap().as_deref(),
            Some(MEDIATOR)
        );
        assert_eq!(check_reachable(id.did(), MEDIATOR).unwrap(), None);
        // The ids DIDComm looks secrets up by are the ones the document
        // names: `#key-1` signs and authenticates, `#key-2` agrees keys.
        let doc: affinidi_tdk::did_common::DID = id.did().parse().unwrap();
        let doc = serde_json::to_value(doc.resolve().unwrap()).unwrap();
        let x25519 = id
            .messaging_secrets()
            .into_iter()
            .find(|s| s.get_key_type() == KeyType::X25519)
            .unwrap();
        assert_eq!(x25519.id, format!("{}#key-2", id.did()));
        assert_eq!(doc["keyAgreement"], serde_json::json!([x25519.id]));
        assert_eq!(
            doc["assertionMethod"],
            serde_json::json!([format!("{}#key-1", id.did())])
        );
        // Served from another mediator, the DID would send the VTC to the
        // wrong place: refused.
        let err = check_reachable(id.did(), "did:web:elsewhere.example")
            .unwrap_err()
            .to_string();
        // Setting the mediator back is the first fix offered: it is the one
        // that keeps bound namespaces working.
        let first_fix = err
            .find(&format!("`mediator_did = \"{MEDIATOR}\"`"))
            .unwrap();
        assert!(first_fix < err.find("mint").unwrap(), "{err}");

        // It signs what the production verifier accepts ([`crate::proof_checker`]
        // is the same resolver-backed one the VTC's side is): a did:peer
        // resolves without the network.
        let doc = serde_json::json!({
            "id": "urn:uuid:1",
            "type": "https://trusttasks.org/spec/git-ns/bridge/result/0.1",
            "issuer": id.did(),
            "payload": { "jobId": "j", "outcome": "succeeded" },
        });
        let signed = id.sign(&doc).await.unwrap();
        crate::proof_checker()
            .await
            .unwrap()
            .verify_raw(&signed)
            .await
            .unwrap();
        let k = id.git_signing_key().unwrap();
        assert_eq!(k.verification_method, format!("{}#key-1", id.did()));

        // Sealed as a bundle, loaded back the same.
        let store = Store::in_memory(MasterKey::generate().unwrap()).unwrap();
        BridgeIdentity::store_bundle(&store, bundle).unwrap();
        let back = BridgeIdentity::load(&store).unwrap().unwrap();
        assert_eq!(back.did(), id.did());
        assert_eq!(back.messaging_secrets().len(), 2);
    }

    /// The VTC's own selection (`vtc-service` `git_ns::bridge`): resolve the
    /// bridge's DID with the DID cache client, read its services by type,
    /// and intersect with what the VTC speaks. A did:key fails exactly here
    /// (`noMatchingProtocol`); a did:peer minted by `init` picks TSP through
    /// its mediator, and DIDComm from a VTC that speaks no TSP.
    #[tokio::test]
    async fn the_vtc_selects_tsp_for_a_did_peer_and_nothing_for_a_did_key() {
        use affinidi_tdk::did_resolver::DIDCacheClient;
        use affinidi_tdk::did_resolver::config::DIDCacheConfigBuilder;
        use vta_sdk::protocol::matching::{Protocol, ServiceCapabilities, select_protocol};
        let resolver = DIDCacheClient::new(DIDCacheConfigBuilder::default().build())
            .await
            .unwrap();
        let (peer, _) = BridgeIdentity::generate_did_peer(MEDIATOR).unwrap();
        let key = BridgeIdentity::from_seed(&[5u8; 32]).unwrap();
        for (id, want) in [(&peer, Some(Protocol::Tsp)), (&key, None)] {
            let resolved = resolver.resolve(id.did()).await.unwrap();
            let doc = serde_json::to_value(&resolved.doc).unwrap();
            let theirs = ServiceCapabilities::from_did_document(&doc);
            let ours = ServiceCapabilities {
                tsp: Some(id.did().to_string()),
                didcomm: Some(id.did().to_string()),
                rest: None,
            };
            let got = select_protocol(&ours, &theirs, id.did())
                .ok()
                .map(|m| m.protocol);
            assert_eq!(got, want, "{}", id.did());
            if want.is_some() {
                assert_eq!(theirs.didcomm.as_deref(), Some(MEDIATOR));
                assert_eq!(theirs.tsp.as_deref(), Some(MEDIATOR));
                // A VTC built without TSP still reaches it over DIDComm.
                let didcomm_only = ServiceCapabilities {
                    tsp: None,
                    ..ours.clone()
                };
                assert_eq!(
                    select_protocol(&didcomm_only, &theirs, id.did())
                        .unwrap()
                        .protocol,
                    Protocol::Didcomm
                );
                // verify-trust finds the key the bridge re-signs Dependabot
                // commits with in the same document.
                let signing = id.git_signing_key().unwrap().key.verifying_key().to_bytes();
                assert!(vgi_core::ed25519_signing_keys_from_doc(&doc).contains(&signing));
            }
        }
    }

    #[test]
    fn a_did_key_is_reachable_by_no_vtc() {
        let id = BridgeIdentity::from_seed(&[5u8; 32]).unwrap();
        assert_eq!(advertised_mediator(id.did()).unwrap(), None);
        let warning = check_reachable(id.did(), MEDIATOR).unwrap().unwrap();
        assert!(warning.contains("noMatchingProtocol"), "{warning}");
        // A DID with a published document is not second-guessed.
        assert_eq!(
            check_reachable("did:webvh:QmScid:bridge.example", MEDIATOR).unwrap(),
            None
        );
    }

    #[test]
    fn a_mediator_with_a_long_did_is_refused_at_mint() {
        let long = format!("did:web:{}.example", "m".repeat(900));
        let err = BridgeIdentity::generate_did_peer(&long).unwrap_err();
        assert!(err.to_string().contains("1000-byte"), "{err}");
        assert!(BridgeIdentity::generate_did_peer("not-a-did").is_err());
    }

    /// A mediator whose DID is too long to carry twice still gets a bridge:
    /// one advertising DIDComm only, which the VTC reaches over DIDComm.
    #[test]
    fn a_mediator_too_long_for_both_services_gets_a_didcomm_only_did_peer() {
        let short = BridgeIdentity::generate_did_peer(MEDIATOR).unwrap().0;
        assert!(advertised_tsp_mediator(short.did()).unwrap().is_some());
        // Somewhere between "both fit" and "nothing fits" lies the case
        // under test; find it rather than hard-code the encoding's sizes.
        let (mediator, id) = (100..900)
            .step_by(10)
            .map(|n| format!("did:web:{}.example", "m".repeat(n)))
            .find_map(|m| {
                let (id, _) = BridgeIdentity::generate_did_peer(&m).ok()?;
                advertised_tsp_mediator(id.did())
                    .unwrap()
                    .is_none()
                    .then_some((m, id))
            })
            .expect("a mediator DID too long for both services but not for one");
        assert!(id.did().len() <= MAX_DID_BYTES);
        assert_eq!(
            advertised_mediator(id.did()).unwrap().as_deref(),
            Some(mediator.as_str())
        );
        assert_eq!(check_reachable(id.did(), &mediator).unwrap(), None);
    }

    #[test]
    fn an_exported_identity_imports_as_the_same_did_and_keys() {
        for id in [
            BridgeIdentity::generate_did_peer(MEDIATOR).unwrap().0,
            BridgeIdentity::from_seed(&[7u8; 32]).unwrap(),
        ] {
            let text = serde_json::to_string(&id.to_bundle().unwrap()).unwrap();
            let store = Store::in_memory(MasterKey::generate().unwrap()).unwrap();
            let back =
                BridgeIdentity::store_bundle(&store, serde_json::from_str(&text).unwrap()).unwrap();
            assert_eq!(back.did(), id.did());
            assert_eq!(
                back.git_signing_key().unwrap().key.to_bytes(),
                id.git_signing_key().unwrap().key.to_bytes()
            );
            let reloaded = BridgeIdentity::load(&store).unwrap().unwrap();
            assert_eq!(reloaded.did(), id.did());
        }
    }

    #[tokio::test]
    async fn signing_for_another_issuer_is_refused() {
        let (id, _) = BridgeIdentity::generate_did_key().unwrap();
        let doc = serde_json::json!({ "id": "x", "issuer": "did:key:z6MkOther", "payload": {} });
        assert!(id.sign(&doc).await.is_err());
    }
}