vgi-bridge 0.19.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
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
//! Trust Task documents on the VTC ↔ bridge link.
//!
//! The payload types are the ones generated from the normative
//! `git-ns/bridge/*` specifications (`trust_tasks_rs::specs::git_ns`); this
//! module adds only behaviour: checking an inbound document before anything
//! reads its payload, the rules JSON Schema cannot state (which members each
//! job `kind` carries), and building signed outbound documents.
//!
//! **An inbound document is checked in this order**, each step before the
//! next reads anything the previous one has not vouched for:
//!
//! 1. the envelope parses (framework members only — the payload is still
//!    opaque JSON);
//! 2. `issuer` is the one VTC this bridge serves — anything else is
//!    `permissionDenied`, whatever its proof (spec: *Authorization*). Checked
//!    before the proof so that a stranger's document never makes the bridge
//!    resolve a DID the stranger chose;
//! 3. the transport's authenticated sender, when there is one, is that same
//!    DID (`identityMismatch`);
//! 4. `recipient` is this bridge (`wrongRecipient`);
//! 5. `issuedAt` is present and fresh (a stale job replayed after later ones
//!    would push the forge back to an old state);
//! 6. the Data Integrity proof verifies, over the document exactly as it
//!    arrived, under a verification method the issuer controls;
//! 7. only then is the payload parsed into its generated type.

use std::sync::Arc;

use anyhow::Result;
use async_trait::async_trait;
use chrono::{TimeDelta, Utc};
use serde::Serialize;
use serde_json::Value;
use trust_tasks_rs::{
    ErrorPayload, FreshnessPolicy, RejectReason, StandardCode, TrustTask, TypeUri,
    VerificationError,
};

use crate::identity::BridgeIdentity;

use trust_tasks_rs::Payload as GitNsPayload;

/// `git-ns/bridge/event` 0.1, still sent to a VTC configured for it.
pub use trust_tasks_rs::specs::git_ns::bridge::event::v0_1 as event_v0_1;
/// `git-ns/bridge/event` 0.2, still sent to a VTC configured for it.
pub use trust_tasks_rs::specs::git_ns::bridge::event::v0_2 as event_v0_2;
/// `git-ns/bridge/event` 0.3, still sent to a VTC configured for it.
pub use trust_tasks_rs::specs::git_ns::bridge::event::v0_3 as event_v0_3;
/// `git-ns/bridge/event` 0.4, the type every event is built as. Each version
/// is wire-identical for every event the older ones carry (0.2 changes only
/// what the VTC does with a transfer, a reused name, and a resource outside
/// the namespace; 0.3 only adds `roleMapReported`; 0.4 only adds
/// `pullRequestOpened`), so an event for a VTC configured for an older one
/// is the same payload under the older type URI: see [`event_type_uri`].
/// `roleMapReported` is never sent under 0.1 or 0.2, and
/// `pullRequestOpened` never under anything before 0.4.
pub use trust_tasks_rs::specs::git_ns::bridge::event::v0_4 as event;
/// `git-ns/bridge/job` 0.4, still taken (job 0.5: a bridge that takes 0.5
/// SHOULD go on accepting 0.4).
pub use trust_tasks_rs::specs::git_ns::bridge::job::v0_4 as job_v0_4;
/// The payload types of `git-ns/bridge/job` 0.5, which every job is read
/// as: a 0.4 job is a valid 0.5 job with the same meaning (0.5 only adds
/// `closePullRequest`, which a 0.4 job cannot carry — [`job_kind_allowed`]).
/// It adds rules the schema does not state, checked in
/// [`check_kind_members`]: a namespace admin with no right of their own on
/// a repository is listed at `git.ns.admin` and gets no role; there is no
/// namespace-level `projectRoles`; each account appears once.
pub use trust_tasks_rs::specs::git_ns::bridge::job::v0_5 as job;
pub use trust_tasks_rs::specs::git_ns::bridge::result::v0_1 as result;

/// `git-ns/bridge/job/0.5`'s type URI.
pub const JOB_TYPE: &str = <job::Payload as GitNsPayload>::TYPE_URI;
/// `git-ns/bridge/job/0.4`'s type URI.
pub const JOB_TYPE_V0_4: &str = <job_v0_4::Payload as GitNsPayload>::TYPE_URI;
/// The job versions this bridge takes, newest first — what it lists in
/// answer to `trust-task-discovery`.
pub const JOB_TYPES: [&str; 2] = [JOB_TYPE, JOB_TYPE_V0_4];

/// `trust-task-discovery/0.2`, which a VTC asks before it sends 0.4 or 0.5
/// jobs (`git-ns/bridge/job` 0.4 and 0.5 each forbid sending that version to
/// a bridge that has not shown it takes it).
pub const DISCOVERY_TYPE: &str = "https://trusttasks.org/spec/trust-task-discovery/0.2";

/// Whether `type_uri` (bare) is a job this bridge takes: `git-ns/bridge/job`
/// 0.5 or 0.4.
pub fn is_job_type(type_uri: &str) -> bool {
    JOB_TYPES.contains(&type_uri)
}

/// Whether `type_uri` (bare) is another version of `git-ns/bridge/job`,
/// which this bridge refuses with `unsupportedVersion`: before 0.4 a
/// namespace admin was sent as an owner, and nothing here reads that.
pub fn is_other_job_version(type_uri: &str) -> bool {
    !is_job_type(type_uri) && type_uri.starts_with("https://trusttasks.org/spec/git-ns/bridge/job/")
}

/// Whether a job of `kind` may arrive under `type_uri` (one
/// [`is_job_type`] accepts): `closePullRequest` exists only from 0.5, so a
/// 0.4 job naming it is malformed — 0.4's schema has no such kind, and the
/// 0.5 types every job is read with would otherwise let it through.
pub fn job_kind_allowed(type_uri: &str, kind: job::PayloadKind) -> bool {
    type_uri == JOB_TYPE || kind != job::PayloadKind::ClosePullRequest
}

/// The `trust-task-discovery` answer: the job types this bridge takes, if
/// any of `patterns` (SPEC §10.2 grammar; empty means `*`) selects their
/// slug.
pub fn discovery_answer(patterns: &[String]) -> Value {
    const SLUG: &str = "git-ns/bridge/job";
    let selects = |p: &str| {
        p == "*"
            || p == SLUG
            || p.strip_suffix("/*")
                .is_some_and(|prefix| SLUG.starts_with(&format!("{prefix}/")))
    };
    let listed = patterns.is_empty() || patterns.iter().any(|p| selects(p));
    let types: Vec<&str> = if listed {
        JOB_TYPES.to_vec()
    } else {
        Vec::new()
    };
    serde_json::json!({ "supportedTypes": types })
}

/// An error response carrying a code a git-ns specification declares (the
/// generated `error_codes`), with the retryability it declares. Built from
/// the code's wire form because the declaration comes from
/// `trust_tasks_rs` and the error payload from `trust_tasks_rs`; when the
/// two are one crate again this is `ErrorPayload::from(code)`.
pub fn declared_error(code: trust_tasks_rs::DeclaredErrorCode) -> ErrorPayload {
    let parsed: trust_tasks_rs::TrustTaskCode = code
        .code
        .parse()
        .expect("a generated error code is a valid extended code");
    ErrorPayload::new(parsed).with_retryable(code.retryable)
}

/// The type URI an event is sent under, for the version the VTC takes.
pub fn event_type_uri(version: crate::config::EventVersion) -> &'static str {
    use crate::config::EventVersion;
    match version {
        EventVersion::V0_1 => event_v0_1::Payload::TYPE_URI,
        EventVersion::V0_2 => event_v0_2::Payload::TYPE_URI,
        EventVersion::V0_3 => event_v0_3::Payload::TYPE_URI,
        _ => event::Payload::TYPE_URI,
    }
}

/// Whether `type_uri` (bare) is the VTC's acknowledgement of an event, of
/// any version (a VTC acknowledges an event in the version it was sent,
/// and the configured version may have changed since).
pub fn is_event_response_type(type_uri: &str) -> bool {
    type_uri == event::Response::TYPE_URI
        || type_uri == event_v0_3::Response::TYPE_URI
        || type_uri == event_v0_2::Response::TYPE_URI
        || type_uri == event_v0_1::Response::TYPE_URI
}

/// Parse a `git-ns/bridge/job` 0.4 or 0.5 payload (as 0.5).
pub fn parse_job(payload: &Value) -> std::result::Result<job::Payload, String> {
    serde_json::from_value(payload.clone()).map_err(|e| format!("job payload: {e}"))
}

/// The DIDComm message type that carries a Trust Task document as its body
/// (the Trust Tasks DIDComm binding; the same constant vtc-service routes on).
pub const ENVELOPE_TYPE: &str = "https://trusttasks.org/binding/didcomm/0.1/envelope";

/// Checks a document's Data Integrity proof. A seam so tests can verify
/// `did:key` proofs offline; production resolves `did:webvh` too.
#[async_trait]
pub trait ProofCheck: Send + Sync {
    /// Verify `doc`'s proof as received, bound to its in-band `issuer`.
    async fn verify_raw(&self, doc: &Value) -> Result<(), VerificationError>;
}

#[async_trait]
impl ProofCheck for trust_tasks_proof::affinidi::Verifier {
    async fn verify_raw(&self, doc: &Value) -> Result<(), VerificationError> {
        trust_tasks_proof::affinidi::Verifier::verify_raw(self, doc).await
    }
}

/// Drops a DID's cached document, so the next resolution fetches it again.
#[async_trait]
pub trait Evict: Send + Sync {
    /// Forget `did`'s cached document.
    async fn evict(&self, did: &str);
}

#[async_trait]
impl Evict for affinidi_tdk::did_resolver::DIDCacheClient {
    async fn evict(&self, did: &str) {
        let _ = self.remove(did).await;
    }
}

/// A [`ProofCheck`] that tries a failed proof once more against a fresh
/// resolution of the issuer's DID: a document cached from before the
/// issuer rotated its key would otherwise refuse the new key until it
/// expired. Fails closed after the second try, and a document that verified
/// is never re-checked — a key rotated *out* is trusted at most for the
/// cache's lifetime.
pub struct ReResolving {
    inner: Arc<dyn ProofCheck>,
    cache: Arc<dyn Evict>,
    /// When each DID was last resolved again: at most once per
    /// [`RE_RESOLVE_EVERY`], so a stream of bad proofs cannot make the bridge
    /// hammer (or be steered into flooding) the DID's host.
    last: std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>>,
}

/// The least time between two fresh resolutions of one DID on a failure.
pub const RE_RESOLVE_EVERY: std::time::Duration = std::time::Duration::from_secs(30);

impl ReResolving {
    /// Over `inner`, evicting from `cache`.
    pub fn new(inner: Arc<dyn ProofCheck>, cache: Arc<dyn Evict>) -> Self {
        ReResolving {
            inner,
            cache,
            last: Default::default(),
        }
    }

    /// Whether `did` may be resolved again now (and note that it is).
    fn may_re_resolve(&self, did: &str) -> bool {
        let mut last = self.last.lock().expect("lock");
        let now = std::time::Instant::now();
        if last
            .get(did)
            .is_some_and(|t| now.duration_since(*t) < RE_RESOLVE_EVERY)
        {
            return false;
        }
        if last.len() > 1024 {
            last.retain(|_, t| now.duration_since(*t) < RE_RESOLVE_EVERY);
        }
        last.insert(did.to_string(), now);
        true
    }
}

#[async_trait]
impl ProofCheck for ReResolving {
    async fn verify_raw(&self, doc: &Value) -> Result<(), VerificationError> {
        match self.inner.verify_raw(doc).await {
            Ok(()) => Ok(()),
            Err(first) => {
                let Some(issuer) = doc.get("issuer").and_then(Value::as_str) else {
                    return Err(first);
                };
                // Only a network-resolved DID can have changed.
                if issuer.starts_with("did:key:")
                    || issuer.starts_with("did:peer:")
                    || !self.may_re_resolve(issuer)
                {
                    return Err(first);
                }
                tracing::info!(%issuer, "a proof failed against the cached DID document; resolving it again");
                self.cache.evict(issuer).await;
                self.inner.verify_raw(doc).await
            }
        }
    }
}

/// A document that passed steps 1–6: from the VTC, to this bridge, fresh,
/// and signed. Only [`DocChecker::check`] makes one.
#[derive(Debug, Clone)]
pub struct VerifiedDoc {
    /// The envelope, payload still untyped.
    pub doc: TrustTask<Value>,
}

impl VerifiedDoc {
    /// The bare type URI (`…/git-ns/bridge/job/0.4`, `…#response`).
    pub fn type_uri(&self) -> String {
        self.doc.type_uri.to_string()
    }
}

/// Why an inbound document was refused, as the error response carries it.
#[derive(Debug)]
pub struct Refusal {
    /// The error payload to send back.
    pub payload: ErrorPayload,
    /// The envelope, when it parsed far enough to answer.
    pub doc: Option<TrustTask<Value>>,
}

impl Refusal {
    fn standard(
        code: StandardCode,
        message: impl Into<String>,
        doc: Option<TrustTask<Value>>,
    ) -> Box<Self> {
        Box::new(Refusal {
            payload: ErrorPayload::new(code).with_message(message),
            doc,
        })
    }
}

/// Steps 1–6 of the module docs.
pub struct DocChecker {
    vtc_did: String,
    bridge_did: String,
    freshness: FreshnessPolicy,
    proof: Arc<dyn ProofCheck>,
}

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

impl DocChecker {
    /// A checker for documents from `vtc_did` to `bridge_did`, no older than
    /// `max_age_secs`.
    pub fn new(
        vtc_did: impl Into<String>,
        bridge_did: impl Into<String>,
        max_age_secs: u64,
        proof: Arc<dyn ProofCheck>,
    ) -> Self {
        DocChecker {
            vtc_did: vtc_did.into(),
            bridge_did: bridge_did.into(),
            freshness: FreshnessPolicy::consequential()
                .with_max_age(TimeDelta::seconds(max_age_secs as i64)),
            proof,
        }
    }

    /// The VTC this bridge serves.
    pub fn vtc_did(&self) -> &str {
        &self.vtc_did
    }

    /// Check `raw`, which arrived from `authenticated_sender` when the
    /// transport proved one.
    pub async fn check(
        &self,
        raw: &Value,
        authenticated_sender: Option<&str>,
    ) -> Result<VerifiedDoc, Box<Refusal>> {
        // 1. The envelope.
        let doc: TrustTask<Value> = serde_json::from_value(raw.clone()).map_err(|e| {
            Refusal::standard(
                StandardCode::MalformedRequest,
                format!("not a Trust Task document: {e}"),
                None,
            )
        })?;
        // 2. Only our VTC.
        if doc.issuer.as_deref() != Some(self.vtc_did.as_str()) {
            return Err(Refusal::standard(
                StandardCode::PermissionDenied,
                "this bridge serves one VTC, and this document is not from it",
                Some(doc),
            ));
        }
        // 3. The transport agrees.
        if let Some(sender) = authenticated_sender
            && sender != self.vtc_did
        {
            return Err(Refusal::standard(
                StandardCode::IdentityMismatch,
                "the transport-authenticated sender is not the document's issuer",
                Some(doc),
            ));
        }
        // 4. Addressed to us.
        if doc.recipient.as_deref() != Some(self.bridge_did.as_str()) {
            return Err(Refusal::standard(
                StandardCode::WrongRecipient,
                "the document is not addressed to this bridge",
                Some(doc),
            ));
        }
        // 5. Fresh.
        if let Err(reason) = doc.validate_freshness(Utc::now(), &self.freshness) {
            let payload: ErrorPayload = reason.into();
            return Err(Box::new(Refusal {
                payload,
                doc: Some(doc),
            }));
        }
        // 6. Signed by the issuer.
        if raw.get("proof").is_none() {
            return Err(Refusal::standard(
                StandardCode::ProofRequired,
                "a proof is required on every document from the VTC",
                Some(doc),
            ));
        }
        // SPEC.md "Which purpose a producer signs with": a producer signs a
        // Trust Task document under `authentication` — proving the issuer
        // controls the identifier — and SHOULD NOT use `assertionMethod`
        // unless the task's own spec defines the proof as an attestation.
        // Neither `git-ns/bridge/job` nor `git-ns/bridge/result` does, so
        // every other purpose is refused here: `assertionMethod` (the VTC
        // would be attesting the job as if it were a credential, which no
        // git-ns/bridge spec asks for), `keyAgreement` (never authorises a
        // signature), and anything else. Checked here, before the
        // signature, and bound by it (the purpose is signed).
        if raw.pointer("/proof/proofPurpose").and_then(Value::as_str) != Some("authentication") {
            return Err(Refusal::standard(
                StandardCode::ProofInvalid,
                "the proof's purpose must be authentication",
                Some(doc),
            ));
        }
        if let Err(e) = self.proof.verify_raw(raw).await {
            tracing::warn!(error = %e, id = %doc.id, "refusing a document whose proof does not verify");
            let payload: ErrorPayload = RejectReason::ProofInvalid {
                reason: e.to_string(),
            }
            .into();
            return Err(Box::new(Refusal {
                payload,
                doc: Some(doc),
            }));
        }
        Ok(VerifiedDoc { doc })
    }
}

/// A fresh `urn:uuid` document id.
pub fn new_id() -> String {
    let mut b = [0u8; 16];
    aws_lc_rs::rand::fill(&mut b).expect("system RNG");
    // RFC 4122 version 4, variant 1.
    b[6] = (b[6] & 0x0f) | 0x40;
    b[8] = (b[8] & 0x3f) | 0x80;
    let h = hex::encode(b);
    format!(
        "urn:uuid:{}-{}-{}-{}-{}",
        &h[0..8],
        &h[8..12],
        &h[12..16],
        &h[16..20],
        &h[20..32]
    )
}

/// Build and sign a new request document (`result`, `event`) from the bridge
/// to the VTC, of type `type_uri`, carrying `payload`. Returns its id and the
/// signed document.
pub async fn signed_request(
    identity: &BridgeIdentity,
    vtc_did: &str,
    type_uri: &str,
    payload: Value,
) -> Result<(String, Value)> {
    let id = new_id();
    let type_uri: TypeUri = type_uri
        .parse()
        .map_err(|e| anyhow::anyhow!("type URI `{type_uri}`: {e}"))?;
    let mut doc = TrustTask::new(id.clone(), type_uri, payload);
    doc.thread_id = Some(id.clone());
    doc.issuer = Some(identity.did().to_string());
    doc.recipient = Some(vtc_did.to_string());
    doc.issued_at = Some(Utc::now());
    let signed = identity.sign(&serde_json::to_value(&doc)?).await?;
    Ok((id, signed))
}

/// Build and sign the response to `request`.
pub async fn signed_response<R: Serialize>(
    identity: &BridgeIdentity,
    request: &TrustTask<Value>,
    payload: R,
) -> Result<Value> {
    let resp = request.respond_with(new_id(), payload);
    identity.sign(&serde_json::to_value(&resp)?).await
}

/// Build and sign an error response to `request`.
pub async fn signed_error(
    identity: &BridgeIdentity,
    request: &TrustTask<Value>,
    payload: ErrorPayload,
) -> Result<Value> {
    let mut resp = request.reject_with(new_id(), payload);
    // Addressed from this bridge even when the request named someone else.
    resp.issuer = Some(identity.did().to_string());
    identity.sign(&serde_json::to_value(&resp)?).await
}

/// Check that a job carries exactly the members its `kind` uses (the
/// specification's kind table, which the schema cannot express).
pub fn check_kind_members(p: &job::Payload) -> std::result::Result<(), String> {
    use job::PayloadKind as K;
    let has = |present: bool, name: &str, allowed: bool, required: bool| {
        if required && !present {
            Err(format!("`{}` requires `{name}`", p.kind))
        } else if present && !allowed {
            Err(format!("`{}` does not use `{name}`", p.kind))
        } else {
            Ok(())
        }
    };
    // (repo, spec, desiredRoles, steps, target, subject, number, message):
    // (allowed, required)
    const NO: (bool, bool) = (false, false);
    const MAY: (bool, bool) = (true, false);
    const MUST: (bool, bool) = (true, true);
    let rules: [(bool, bool); 8] = match p.kind {
        // 0.4: no namespace-level `projectRoles`.
        K::ProjectRoles => [MUST, NO, MUST, NO, NO, NO, NO, NO],
        K::CreateRepo => [MUST, MUST, MAY, NO, NO, NO, NO, NO],
        K::Bootstrap => [MUST, NO, NO, MAY, NO, NO, NO, NO],
        K::Archive => [MUST, NO, NO, NO, NO, NO, NO, NO],
        K::Inspect => [MAY, NO, NO, NO, NO, NO, NO, NO],
        K::BeginBind => [NO, NO, NO, NO, MUST, NO, NO, NO],
        K::BeginAccountLink => [NO, NO, NO, NO, NO, MUST, NO, NO],
        // 0.5: `repo`, `number` and `message` together.
        K::ClosePullRequest => [MUST, NO, NO, NO, NO, NO, MUST, MUST],
        _ => return Err(format!("unknown job kind `{}`", p.kind)),
    };
    let present = [
        p.repo.is_some(),
        p.spec.is_some(),
        p.desired_roles.is_some(),
        p.steps.is_some(),
        p.target.is_some(),
        p.subject.is_some(),
        p.number.is_some(),
        p.message.is_some(),
    ];
    let names = [
        "repo",
        "spec",
        "desiredRoles",
        "steps",
        "target",
        "subject",
        "number",
        "message",
    ];
    for i in 0..names.len() {
        has(present[i], names[i], rules[i].0, rules[i].1)?;
    }
    if let Some(steps) = &p.steps {
        let mut seen = std::collections::BTreeSet::new();
        if steps.is_empty() || !steps.iter().all(|s| seen.insert(s.to_string())) {
            return Err("`steps` must be a non-empty list of distinct names".into());
        }
    }
    if let Some(roles) = &p.desired_roles {
        let mut seen = std::collections::BTreeSet::new();
        if !roles
            .iter()
            .all(|r| seen.insert((r.account.forge.to_string(), r.account.id.to_string())))
        {
            return Err("`desiredRoles` names one account twice".into());
        }
    }
    check_remove_accounts(p)
}

/// `removeAccounts`: `projectRoles` only, at least one account, none twice,
/// and none also in `desiredRoles` except at `git.ns.admin` (job 0.4: that
/// entry asks for no role, as the removal does) — an account is matched by
/// `forge` and `id`, never by its display `login`.
/// Whether each account is on the namespace's forge is checked once the
/// namespace is known (the bridge's admission).
fn check_remove_accounts(p: &job::Payload) -> std::result::Result<(), String> {
    let Some(remove) = &p.remove_accounts else {
        return Ok(());
    };
    if p.kind != job::PayloadKind::ProjectRoles {
        return Err(format!("`{}` does not use `removeAccounts`", p.kind));
    }
    if remove.is_empty() {
        return Err("`removeAccounts` must name at least one account".into());
    }
    let key = |a: &job::ForgeAccount| (a.forge.to_string(), a.id.to_string());
    let mut seen = std::collections::BTreeSet::new();
    if !remove.iter().all(|a| seen.insert(key(a))) {
        return Err("`removeAccounts` names one account twice".into());
    }
    if let Some(overlap) = p
        .desired_roles
        .iter()
        .flatten()
        .find(|r| seen.contains(&key(&r.account)) && r.right != job::Right::GitNsAdmin)
    {
        return Err(format!(
            "account {} on `{}` is in both `desiredRoles` and `removeAccounts`",
            *overlap.account.id, *overlap.account.forge
        ));
    }
    Ok(())
}

/// Truncate `s` to at most `max` bytes on a character boundary (the result
/// schema bounds `detail` and `message` at 1024).
pub fn clip(s: &str, max: usize) -> String {
    if s.len() <= max {
        return s.to_string();
    }
    let mut end = max.saturating_sub(1);
    while !s.is_char_boundary(end) {
        end -= 1;
    }
    format!("{}…", &s[..end.saturating_sub(2)])
}

/// Whether `v` is one of this module's request types, by bare type URI.
pub fn is_type<P: GitNsPayload>(v: &VerifiedDoc) -> bool {
    v.doc.type_uri.to_string() == P::TYPE_URI
}

#[cfg(test)]
mod tests {
    /// Fails until the cache is evicted once — a document cached from
    /// before the issuer rotated its key.
    struct Stale {
        evicted: std::sync::atomic::AtomicBool,
        checks: std::sync::atomic::AtomicU32,
        fresh_passes: bool,
    }

    #[async_trait]
    impl ProofCheck for Stale {
        async fn verify_raw(&self, _doc: &Value) -> Result<(), VerificationError> {
            use std::sync::atomic::Ordering::SeqCst;
            self.checks.fetch_add(1, SeqCst);
            if self.evicted.load(SeqCst) && self.fresh_passes {
                Ok(())
            } else {
                Err(VerificationError::UnsupportedCryptosuite("stale".into()))
            }
        }
    }

    #[async_trait]
    impl Evict for Stale {
        async fn evict(&self, _did: &str) {
            self.evicted
                .store(true, std::sync::atomic::Ordering::SeqCst);
        }
    }

    #[tokio::test]
    async fn a_failed_proof_is_checked_once_more_against_a_fresh_document() {
        use std::sync::atomic::Ordering::SeqCst;
        let doc = serde_json::json!({ "issuer": "did:webvh:QmVtc:acme-vtc.example" });
        for fresh_passes in [true, false] {
            let s = Arc::new(Stale {
                evicted: false.into(),
                checks: 0.into(),
                fresh_passes,
            });
            let r = ReResolving::new(s.clone(), s.clone());
            assert_eq!(r.verify_raw(&doc).await.is_ok(), fresh_passes);
            assert_eq!(
                s.checks.load(SeqCst),
                2,
                "once more, never again (fails closed)"
            );
            assert!(s.evicted.load(SeqCst));
        }
        // Once per DID per interval: a second failure soon after is refused
        // without resolving again.
        let s = Arc::new(Stale {
            evicted: false.into(),
            checks: 0.into(),
            fresh_passes: false,
        });
        let r = ReResolving::new(s.clone(), s.clone());
        assert!(r.verify_raw(&doc).await.is_err());
        assert!(r.verify_raw(&doc).await.is_err());
        assert_eq!(
            s.checks.load(SeqCst),
            3,
            "the second failure is not re-resolved"
        );
        // A did:key cannot have changed: no second try.
        let s = Arc::new(Stale {
            evicted: false.into(),
            checks: 0.into(),
            fresh_passes: true,
        });
        let r = ReResolving::new(s.clone(), s.clone());
        assert!(
            r.verify_raw(&serde_json::json!({ "issuer": "did:key:z6Mk" }))
                .await
                .is_err()
        );
        assert_eq!(s.checks.load(SeqCst), 1);
    }

    use super::*;
    use serde_json::json;
    use trust_tasks_proof::affinidi::Verifier;

    fn checker(vtc: &BridgeIdentity, bridge: &str) -> DocChecker {
        DocChecker::new(vtc.did(), bridge, 300, Arc::new(Verifier::for_did_key()))
    }

    async fn job_doc(vtc: &BridgeIdentity, bridge: &str, payload: Value) -> Value {
        let doc = json!({
            "id": new_id(),
            "type": JOB_TYPE,
            "issuer": vtc.did(),
            "recipient": bridge,
            "issuedAt": Utc::now().to_rfc3339(),
            "payload": payload,
        });
        vtc.sign(&doc).await.unwrap()
    }

    #[tokio::test]
    async fn a_signed_fresh_job_from_the_vtc_passes() {
        let (vtc, _) = BridgeIdentity::generate_did_key().unwrap();
        let (bridge, _) = BridgeIdentity::generate_did_key().unwrap();
        let raw = job_doc(
            &vtc,
            bridge.did(),
            json!({"jobId": "j1", "namespace": "ns", "kind": "inspect"}),
        )
        .await;
        let v = checker(&vtc, bridge.did())
            .check(&raw, Some(vtc.did()))
            .await
            .unwrap();
        assert!(is_job_type(&v.type_uri()));
        let p: job::Payload = serde_json::from_value(v.doc.payload).unwrap();
        check_kind_members(&p).unwrap();
    }

    #[tokio::test]
    async fn every_step_refuses_what_it_should() {
        let (vtc, _) = BridgeIdentity::generate_did_key().unwrap();
        let (other, _) = BridgeIdentity::generate_did_key().unwrap();
        let (bridge, _) = BridgeIdentity::generate_did_key().unwrap();
        let c = checker(&vtc, bridge.did());
        let payload = json!({"jobId": "j1", "namespace": "ns", "kind": "inspect"});
        let code = |r: Box<Refusal>| r.payload.code.to_string();

        // Another DID, validly signed: permission denied, before any proof work.
        let raw = job_doc(&other, bridge.did(), payload.clone()).await;
        assert_eq!(
            code(c.check(&raw, None).await.unwrap_err()),
            "permissionDenied"
        );

        // Right issuer, wrong transport sender.
        let raw = job_doc(&vtc, bridge.did(), payload.clone()).await;
        assert_eq!(
            code(c.check(&raw, Some(other.did())).await.unwrap_err()),
            "identityMismatch"
        );

        // Addressed elsewhere.
        let raw = job_doc(&vtc, other.did(), payload.clone()).await;
        assert_eq!(
            code(c.check(&raw, None).await.unwrap_err()),
            "wrongRecipient"
        );

        // Tampered after signing.
        let mut raw = job_doc(&vtc, bridge.did(), payload.clone()).await;
        raw["payload"]["kind"] = json!("archive");
        assert_eq!(code(c.check(&raw, None).await.unwrap_err()), "proofInvalid");

        // Claiming the VTC as issuer but signed by someone else.
        let mut forged = json!({
            "id": new_id(), "type": JOB_TYPE, "issuer": other.did(),
            "recipient": bridge.did(), "issuedAt": Utc::now().to_rfc3339(), "payload": payload,
        });
        forged = other.sign(&forged).await.unwrap();
        forged["issuer"] = json!(vtc.did());
        assert_eq!(
            code(c.check(&forged, None).await.unwrap_err()),
            "proofInvalid"
        );

        // No proof at all.
        let mut raw = job_doc(
            &vtc,
            bridge.did(),
            json!({"jobId": "j", "namespace": "n", "kind": "inspect"}),
        )
        .await;
        raw.as_object_mut().unwrap().remove("proof");
        assert_eq!(
            code(c.check(&raw, None).await.unwrap_err()),
            "proofRequired"
        );

        // Signed as an assertion rather than for authentication: the
        // specification reserves `assertionMethod` for a task whose spec
        // defines the proof as an attestation, which `git-ns/bridge/job`
        // does not.
        let assertion = vtc
            .sign_with_purpose(
                &json!({
                    "id": new_id(), "type": JOB_TYPE, "issuer": vtc.did(),
                    "recipient": bridge.did(), "issuedAt": Utc::now().to_rfc3339(),
                    "payload": {"jobId": "j", "namespace": "n", "kind": "inspect"},
                }),
                "assertionMethod",
            )
            .await
            .unwrap();
        let r = c.check(&assertion, None).await.unwrap_err();
        assert_eq!(r.payload.code.to_string(), "proofInvalid");
        assert!(
            r.payload
                .message
                .unwrap_or_default()
                .contains("authentication")
        );

        // `keyAgreement` never authorises a signature, so the framework
        // itself refuses to mint a proof under it (`sign_with_purpose`
        // would error before producing one) — forge the field directly to
        // confirm the purpose gate still catches it, before any signature
        // check.
        let mut forged_ka = job_doc(&vtc, bridge.did(), payload.clone()).await;
        forged_ka["proof"]["proofPurpose"] = json!("keyAgreement");
        assert_eq!(
            code(c.check(&forged_ka, None).await.unwrap_err()),
            "proofInvalid"
        );

        // Stale.
        let old = json!({
            "id": new_id(), "type": JOB_TYPE, "issuer": vtc.did(),
            "recipient": bridge.did(), "issuedAt": "2020-01-01T00:00:00Z",
            "payload": {"jobId": "j", "namespace": "n", "kind": "inspect"},
        });
        let old = vtc.sign(&old).await.unwrap();
        assert_eq!(code(c.check(&old, None).await.unwrap_err()), "expired");
    }

    /// A resolver modelling a DID document where the signing key is listed
    /// under `assertionMethod` only — never `authentication`. A proof that
    /// *names* `authentication` and verifies cryptographically must still be
    /// refused, because the issuer never authorised that key for it: the
    /// purpose named on the wire has to be checked against the real
    /// verification relationship, not just trusted at face value.
    struct AssertionMethodOnly(std::collections::BTreeMap<String, Vec<u8>>);

    #[async_trait]
    impl trust_tasks_proof::affinidi::ProofPurposeResolver for AssertionMethodOnly {
        async fn resolve_vm_for_purpose(
            &self,
            vm: &str,
            purpose: trust_tasks_proof::affinidi::ProofPurpose,
        ) -> std::result::Result<
            affinidi_data_integrity::did_vm::ResolvedKey,
            affinidi_data_integrity::DataIntegrityError,
        > {
            if purpose != trust_tasks_proof::affinidi::ProofPurpose::AssertionMethod {
                return Err(affinidi_data_integrity::DataIntegrityError::Resolver(
                    format!("{vm} is not listed under {purpose} in its DID document"),
                ));
            }
            self.0
                .get(vm)
                .map(|k| {
                    affinidi_data_integrity::did_vm::ResolvedKey::new(
                        affinidi_tdk::affinidi_crypto::KeyType::Ed25519,
                        k.clone(),
                    )
                })
                .ok_or_else(|| {
                    affinidi_data_integrity::DataIntegrityError::Resolver(format!(
                        "{vm} is not published"
                    ))
                })
        }
    }

    #[tokio::test]
    async fn an_authentication_proof_whose_key_is_listed_only_under_assertion_method_is_refused() {
        let (vtc, _) = BridgeIdentity::generate_did_key().unwrap();
        let (bridge, _) = BridgeIdentity::generate_did_key().unwrap();
        let k = vtc.git_signing_key().unwrap();
        let map = [(
            k.verification_method.clone(),
            k.key.verifying_key().to_bytes().to_vec(),
        )]
        .into_iter()
        .collect();
        let verifier = trust_tasks_proof::affinidi::Verifier::with_resolver(Arc::new(
            AssertionMethodOnly(map),
        ));
        let c = DocChecker::new(vtc.did(), bridge.did(), 300, Arc::new(verifier));
        let raw = job_doc(
            &vtc,
            bridge.did(),
            json!({"jobId": "j", "namespace": "n", "kind": "inspect"}),
        )
        .await;
        // `job_doc` signs with the default purpose (`authentication`), so
        // this passes the wire-level purpose gate and reaches the proof
        // check, where the resolver above refuses the key for it.
        assert_eq!(raw["proof"]["proofPurpose"], "authentication");
        let r = c.check(&raw, None).await.unwrap_err();
        assert_eq!(r.payload.code.to_string(), "proofInvalid");
    }

    #[test]
    fn kinds_carry_exactly_their_members() {
        let parse = |v: Value| serde_json::from_value::<job::Payload>(v).unwrap();
        let ok = [
            json!({"jobId":"j","namespace":"n","kind":"archive","repo":"github.com/a/b"}),
            json!({"jobId":"j","namespace":"n","kind":"inspect"}),
            json!({"jobId":"j","namespace":"n","kind":"projectRoles","repo":"github.com/a/b","desiredRoles":[]}),
            json!({"jobId":"j","namespace":"n","kind":"beginBind","target":{"forge":"github.com","owner":"acme"}}),
            // An account listed at `git.ns.admin` (no role) may also be removed.
            json!({"jobId":"j","namespace":"n","kind":"projectRoles","repo":"github.com/a/b",
                "desiredRoles":[{"subject":"did:key:z6MkAdmin","account":{"forge":"github.com","id":"7","login":"a"},"right":"git.ns.admin"}],
                "removeAccounts":[{"forge":"github.com","id":"7","login":"a"}]}),
        ];
        for v in ok {
            check_kind_members(&parse(v.clone())).unwrap_or_else(|e| panic!("{v}: {e}"));
        }
        let bad = [
            json!({"jobId":"j","namespace":"n","kind":"archive"}),
            json!({"jobId":"j","namespace":"n","kind":"inspect","subject":"did:key:z6Mk"}),
            json!({"jobId":"j","namespace":"n","kind":"createRepo","repo":"github.com/a/b"}),
            json!({"jobId":"j","namespace":"n","kind":"beginAccountLink"}),
            // 0.4: there is no namespace-level `projectRoles`.
            json!({"jobId":"j","namespace":"n","kind":"projectRoles","desiredRoles":[]}),
            // One account, twice.
            json!({"jobId":"j","namespace":"n","kind":"projectRoles","repo":"github.com/a/b","desiredRoles":[
                {"subject":"did:key:z6MkOne","account":{"forge":"github.com","id":"7","login":"a"},"right":"git.repo.own"},
                {"subject":"did:key:z6MkTwo","account":{"forge":"github.com","id":"7","login":"b"},"right":"git.ns.admin"}]}),
            // An account listed at a right that maps to a role is not also removed.
            json!({"jobId":"j","namespace":"n","kind":"projectRoles","repo":"github.com/a/b",
                "desiredRoles":[{"subject":"did:key:z6MkOwner","account":{"forge":"github.com","id":"7","login":"a"},"right":"git.repo.own"}],
                "removeAccounts":[{"forge":"github.com","id":"7","login":"a"}]}),
        ];
        for v in bad {
            assert!(check_kind_members(&parse(v.clone())).is_err(), "{v}");
        }
        // Credentials have no member to ride in on.
        assert!(
            serde_json::from_value::<job::Payload>(
                json!({"jobId":"j","namespace":"n","kind":"archive","repo":"github.com/a/b","token":"ghs_x"})
            )
            .is_err()
        );
    }

    #[test]
    fn job_0_4_and_0_5_are_taken() {
        assert!(is_job_type(JOB_TYPE));
        assert!(is_job_type(JOB_TYPE_V0_4));
        assert!(JOB_TYPE.ends_with("/git-ns/bridge/job/0.5"));
        assert!(JOB_TYPE_V0_4.ends_with("/git-ns/bridge/job/0.4"));
        for v in ["0.1", "0.2", "0.3", "0.6"] {
            let t = format!("https://trusttasks.org/spec/git-ns/bridge/job/{v}");
            assert!(!is_job_type(&t));
            assert!(is_other_job_version(&t));
        }
        assert!(!is_other_job_version(JOB_TYPE));
        assert!(!is_other_job_version(JOB_TYPE_V0_4));
        // `closePullRequest` is a 0.5 kind: refused under 0.4, taken under
        // 0.5; every other kind under either.
        use job::PayloadKind as K;
        assert!(job_kind_allowed(JOB_TYPE, K::ClosePullRequest));
        assert!(!job_kind_allowed(JOB_TYPE_V0_4, K::ClosePullRequest));
        assert!(job_kind_allowed(JOB_TYPE_V0_4, K::ProjectRoles));
        assert!(job_kind_allowed(JOB_TYPE, K::ProjectRoles));
    }

    #[test]
    fn discovery_lists_job_0_5_and_0_4_for_a_pattern_that_selects_them() {
        for p in [
            vec![],
            vec!["*".to_string()],
            vec!["git-ns/*".into()],
            vec!["git-ns/bridge/job".into()],
        ] {
            assert_eq!(
                discovery_answer(&p)["supportedTypes"],
                json!([
                    "https://trusttasks.org/spec/git-ns/bridge/job/0.5",
                    "https://trusttasks.org/spec/git-ns/bridge/job/0.4"
                ]),
                "{p:?}"
            );
        }
        for p in [
            vec!["acl/*".to_string()],
            vec!["git-ns/bridge".into()],
            vec!["git-ns/bridge/job/0.4".into()],
        ] {
            assert_eq!(discovery_answer(&p)["supportedTypes"], json!([]), "{p:?}");
        }
    }

    #[test]
    fn close_pull_request_carries_repo_number_and_message() {
        let parse = |v: Value| serde_json::from_value::<job::Payload>(v).unwrap();
        let base = || {
            json!({"jobId":"j","namespace":"n","kind":"closePullRequest",
                "repo":"github.com/a/b","number":42,"message":"Not open to you."})
        };
        check_kind_members(&parse(base())).unwrap();
        for missing in ["repo", "number", "message"] {
            let mut v = base();
            v.as_object_mut().unwrap().remove(missing);
            assert!(check_kind_members(&parse(v)).is_err(), "without {missing}");
        }
        // Nothing another kind uses.
        let mut v = base();
        v["steps"] = json!(["workflow"]);
        assert!(check_kind_members(&parse(v)).is_err());
        // And no other kind carries `number` or `message`.
        let v = json!({"jobId":"j","namespace":"n","kind":"archive","repo":"github.com/a/b","number":1});
        assert!(check_kind_members(&parse(v)).is_err());
        let v = json!({"jobId":"j","namespace":"n","kind":"inspect","message":"x"});
        assert!(check_kind_members(&parse(v)).is_err());
        // The schema's bounds: a pull request number is at least 1, and the
        // message at most 16384 characters.
        for bad in [
            json!({"jobId":"j","namespace":"n","kind":"closePullRequest",
                "repo":"github.com/a/b","number":0,"message":"m"}),
            json!({"jobId":"j","namespace":"n","kind":"closePullRequest",
                "repo":"github.com/a/b","number":1,"message":"x".repeat(16_385)}),
        ] {
            assert!(serde_json::from_value::<job::Payload>(bad).is_err());
        }
    }

    #[test]
    fn clip_keeps_char_boundaries() {
        let s = "é".repeat(1000);
        let c = clip(&s, 1024);
        assert!(c.len() <= 1024);
        assert_eq!(clip("short", 1024), "short");
    }
}