vta-service 0.38.0

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
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
//! Pure transport-resolution logic for WebVH hosting servers.
//!
//! Walks a server DID's service array and decides whether the VTA can
//! reach it through the **outbound Trust-Task seam** or must fall back
//! to the legacy WebVH REST API — and, for REST, which URL to dial.
//! Kept pure (no resolver, no async, no I/O) so it can be unit-tested
//! with stub service entries instead of a live `DIDCacheClient`.
//!
//! ## This decides *whether* the seam applies, never *which* transport
//!
//! There used to be two transport selectors in this service, and this
//! was the second one: it answered "DIDComm or REST" from its own copy
//! of the service-type constants, in its own precedence order, with no
//! knowledge of TSP. So a did-host advertising TSP was answered over
//! DIDComm — the seam's `PREFERENCE_ORDER` (TSP > DIDComm > REST) never
//! got to speak, because the choice had already been made here.
//!
//! Now this answers one narrower question: *can the seam carry a Trust
//! Task to this server at all?* If the server advertises any transport
//! the seam can use, the answer is [`ResolvedTransport::TrustTask`] and
//! `operations::outbound` picks between them. Only a server advertising
//! none of them falls back to the legacy REST client.
//!
//! The service-type constants come from `vta_sdk::protocol::matching`,
//! the same module the seam reads, so the two cannot drift apart again.
//!
//! ## Accepted service types
//!
//! - `TSPTransport`, `DIDCommMessaging` — either one means the seam can
//!   reach this server; it decides which to use.
//! - `WebVHHosting` — the canonical type emitted by current
//!   `did-hosting-daemon` / `did-hosting-server` builds.
//! - `WebVHHostingService` — legacy alias accepted on **read only**.
//!   We never emit it; existing daemon DIDs stamped before the
//!   unification keep working.
//!
//! ## Seam precedence
//!
//! Workspace-wide invariant: when a DID advertises several transports,
//! Service[] is canonically ordered (see
//! `protocol::document::sort_services_canonical`). We don't rely on
//! that ordering for *reading* foreign DIDs though — a seam-capable
//! entry, wherever it sits, wins over every legacy-REST entry. This
//! keeps third-party DIDs that emit non-canonical orderings working
//! without surprising the operator.
//!
//! Note what this does **not** cover: `TrustTaskHTTPS`. A server
//! advertising only that is reachable by the seam over its REST
//! binding, but routing there would swap the legacy WebVH REST API for
//! the Trust-Task one on the publish path — a live-data change this
//! selector has no business making on its own. It stays on the legacy
//! client until that retirement is taken deliberately.
//!
//! ## `hostingPath` is not the REST base
//!
//! The `did-host-http*` templates used to stamp a `hostingPath` beside
//! `uri` in the `WebVHHosting` endpoint. It described nothing: no
//! caller ever set the `HOSTING_PATH` var, so every document carried
//! the template's own default (`/webvh`), and no server in the
//! ecosystem ever read the field back. #756 mistook it for a
//! control-plane prefix and joined it onto the base; the live
//! deployment says otherwise —
//!
//! ```text
//! GET https://webvh.storm.ws/api/health        -> 200 {"status":"ok"}
//! GET https://webvh.storm.ws/webvh/api/health  -> 404
//! ```
//!
//! — and the hosting service nests its whole API at `/api` off the
//! origin root, with no prefix setting to configure. The REST base is
//! `serviceEndpoint.uri` alone. `hostingPath` is ignored on read, and
//! the templates no longer emit it (#759).

/// Service types that mean "the outbound seam can carry a Trust Task here".
///
/// Re-exported from `vta_sdk::protocol::matching` rather than spelled again:
/// a local copy is how this module came to not know about TSP in the first
/// place, and the seam reads that module to decide what it can actually send.
pub(crate) const SVC_TSP: &str = vta_sdk::protocol::matching::TSP_SERVICE_TYPE;

/// Service-type string emitted on DIDComm endpoints (per DIDComm v2).
pub(crate) const SVC_DIDCOMM: &str = vta_sdk::protocol::matching::DIDCOMM_SERVICE_TYPE;

/// Service-type string emitted on current WebVH-host endpoints.
pub(crate) const SVC_WEBVH_HOSTING: &str = "WebVHHosting";

/// Legacy alias for [`SVC_WEBVH_HOSTING`]. Accepted on read; never
/// emitted by this workspace.
pub(crate) const SVC_WEBVH_HOSTING_LEGACY: &str = "WebVHHostingService";

/// Minimal abstraction over a DID-document service entry, sufficient
/// for transport resolution. Implemented for
/// `affinidi_did_common::Service` in `mod.rs`; tests construct stub
/// values.
pub(crate) trait ServiceEntry {
    fn types(&self) -> &[String];
    fn endpoint_uri(&self) -> Option<String>;
}

/// Outcome of walking a server's service array.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ResolvedTransport {
    /// Reachable through `operations::outbound`, which picks the actual
    /// transport from the peer's advertisement (TSP > DIDComm > REST).
    TrustTask,
    /// Legacy WebVH REST API — not the Trust-Task HTTPS binding.
    Rest { url: String },
}

/// Walk `services` and decide how the VTA should talk to this server.
///
/// Returns `None` if no usable service is advertised; the caller
/// surfaces an `AppError::Validation` so the operator sees the
/// specific server DID.
///
/// REST URLs returned here are stripped of:
/// - surrounding double-quotes — some JSON-LD serialisers emit
///   `"https://host"` (quotes included) for `serviceEndpoint`,
/// - one trailing `/` — to keep the per-route `format!("{base}/api/…")`
///   helpers from producing double slashes.
pub(crate) fn resolve_server_transport<S: ServiceEntry>(
    services: &[S],
) -> Option<ResolvedTransport> {
    if services
        .iter()
        .any(|s| s.types().iter().any(is_seam_capable))
    {
        return Some(ResolvedTransport::TrustTask);
    }
    for svc in services {
        if svc.types().iter().any(is_webvh_rest)
            && let Some(raw) = svc.endpoint_uri()
        {
            let url = raw.trim_matches('"').trim_end_matches('/').to_string();
            if url.is_empty() {
                continue;
            }
            return Some(ResolvedTransport::Rest { url });
        }
    }
    None
}

#[inline]
fn is_seam_capable(t: &String) -> bool {
    t == SVC_TSP || t == SVC_DIDCOMM
}

#[inline]
fn is_webvh_rest(t: &String) -> bool {
    t == SVC_WEBVH_HOSTING || t == SVC_WEBVH_HOSTING_LEGACY
}

/// Human-readable description of accepted service types. Used in
/// the `validate_server_did` failure message so operators see the
/// full accepted set at the point of rejection.
pub(crate) const SUPPORTED_TYPES_HUMAN: &str =
    "TSPTransport, DIDCommMessaging, WebVHHosting, or WebVHHostingService (legacy)";

// ── ServiceEntry impl for the resolver's concrete Service type ─────
//
// Lets `resolve_server_transport(&doc.service)` work without an
// adaptor at the call site. We reach the type through the
// `affinidi_tdk` umbrella — that's the path the workspace already
// uses for adjacent resolver types, and it spares us from adding
// `affinidi-did-common` as a direct dependency just for this impl.
impl ServiceEntry for affinidi_tdk::did_common::service::Service {
    fn types(&self) -> &[String] {
        &self.type_
    }
    fn endpoint_uri(&self) -> Option<String> {
        self.service_endpoint.get_uri()
    }
}

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

    // ── hostingPath is not the REST base ────────────────────────────

    /// Regression guard for #756/#759, pinned against the live document.
    ///
    /// This is the verbatim `WebVHHosting` entry `webvh.storm.ws` publishes,
    /// parsed by the same concrete `Service` type the resolver hands us. #756
    /// read the `hostingPath` beside `uri` as a control-plane prefix and
    /// dialled `https://webvh.storm.ws/webvh/api/...`; that server answers
    /// `/api/health` with 200 and `/webvh/api/health` with 404, so the base is
    /// the origin alone. Anyone tempted to join the two halves again should
    /// re-probe a live server first.
    #[test]
    fn advertised_hosting_path_is_ignored_on_the_live_document() {
        let svc: affinidi_tdk::did_common::service::Service = serde_json::from_str(
            r#"{
                "id": "did:webvh:QmUcyd...:webvh.storm.ws#webvh-hosting",
                "type": "WebVHHosting",
                "serviceEndpoint": {
                    "hostingPath": "/webvh",
                    "uri": "https://webvh.storm.ws"
                }
            }"#,
        )
        .expect("the live WebVHHosting entry parses");
        assert_eq!(
            resolve_server_transport(std::slice::from_ref(&svc)),
            Some(ResolvedTransport::Rest {
                url: "https://webvh.storm.ws".to_string()
            })
        );
    }

    struct TestService {
        types: Vec<String>,
        uri: Option<String>,
    }
    impl TestService {
        fn new(types: &[&str], uri: Option<&str>) -> Self {
            Self {
                types: types.iter().map(|s| s.to_string()).collect(),
                uri: uri.map(String::from),
            }
        }
    }
    impl ServiceEntry for TestService {
        fn types(&self) -> &[String] {
            &self.types
        }
        fn endpoint_uri(&self) -> Option<String> {
            self.uri.clone()
        }
    }

    #[test]
    fn empty_service_list_yields_none() {
        let services: Vec<TestService> = vec![];
        assert_eq!(resolve_server_transport(&services), None);
    }

    #[test]
    fn unsupported_service_type_yields_none() {
        // A DID with services but none we can talk to — operator
        // sees a "no supported service" error upstream.
        let services = vec![TestService::new(&["LinkedDomains"], Some("https://x"))];
        assert_eq!(resolve_server_transport(&services), None);
    }

    /// **The regression this change exists to end.** A did-host advertising
    /// TSP — and nothing else the seam can use — used to fall through to the
    /// legacy REST client, because this selector had never heard of TSP. The
    /// host was reachable over its highest-preference transport the whole time
    /// and the VTA dialled its REST API instead.
    #[test]
    fn tsp_only_reaches_the_seam() {
        let services = vec![TestService::new(&[SVC_TSP], None)];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::TrustTask)
        );
    }

    /// TSP beside legacy REST: the seam is chosen, and `operations::outbound`
    /// decides from there. This selector deliberately does **not** rank TSP
    /// against DIDComm — that is `PREFERENCE_ORDER`'s job, and having two
    /// rankings is what put a TSP host on DIDComm.
    #[test]
    fn tsp_beside_legacy_rest_still_reaches_the_seam() {
        let services = vec![
            TestService::new(&[SVC_WEBVH_HOSTING], Some("https://host.example")),
            TestService::new(&[SVC_TSP], None),
        ];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::TrustTask)
        );
    }

    /// Both seam transports advertised: one answer, not a choice made here.
    #[test]
    fn tsp_and_didcomm_together_yield_one_answer() {
        let services = vec![
            TestService::new(&[SVC_DIDCOMM], None),
            TestService::new(&[SVC_TSP], None),
        ];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::TrustTask)
        );
    }

    /// `TrustTaskHTTPS` is deliberately **not** a seam trigger here — see the
    /// module header. A host advertising only it stays on the legacy WebVH
    /// REST client, because routing it through the seam would swap the publish
    /// path's API on live data.
    #[test]
    fn trust_task_https_alone_does_not_divert_the_publish_path() {
        let services = vec![
            TestService::new(
                &[vta_sdk::protocol::matching::TRUST_TASK_HTTPS_SERVICE_TYPE],
                Some("https://host.example/api"),
            ),
            TestService::new(&[SVC_WEBVH_HOSTING], Some("https://host.example")),
        ];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::Rest {
                url: "https://host.example".to_string()
            })
        );
    }

    /// The constants are the SDK's, not a second copy. A local copy is how this
    /// module came to not know about TSP, so the equality is asserted rather
    /// than trusted to review.
    #[test]
    fn the_service_types_are_the_sdk_ones() {
        assert_eq!(SVC_TSP, vta_sdk::protocol::matching::TSP_SERVICE_TYPE);
        assert_eq!(
            SVC_DIDCOMM,
            vta_sdk::protocol::matching::DIDCOMM_SERVICE_TYPE
        );
    }

    #[test]
    fn didcomm_only_reaches_the_seam() {
        let services = vec![TestService::new(&[SVC_DIDCOMM], None)];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::TrustTask)
        );
    }

    #[test]
    fn webvh_hosting_canonical_resolves_to_rest() {
        // The canonical type emitted by current daemon builds.
        let services = vec![TestService::new(
            &[SVC_WEBVH_HOSTING],
            Some("https://daemon.example"),
        )];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::Rest {
                url: "https://daemon.example".into()
            })
        );
    }

    #[test]
    fn webvh_hosting_service_legacy_alias_accepted() {
        // Older daemon deployments emit WebVHHostingService. We
        // never emit it ourselves but tolerate it on read so
        // pre-unification DIDs keep working.
        let services = vec![TestService::new(
            &[SVC_WEBVH_HOSTING_LEGACY],
            Some("https://legacy.example"),
        )];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::Rest {
                url: "https://legacy.example".into()
            })
        );
    }

    #[test]
    fn a_seam_transport_wins_when_listed_first() {
        let services = vec![
            TestService::new(&[SVC_DIDCOMM], None),
            TestService::new(&[SVC_WEBVH_HOSTING], Some("https://x")),
        ];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::TrustTask)
        );
    }

    #[test]
    fn a_seam_transport_wins_when_listed_after_rest() {
        // The canonical ordering puts DIDComm first, but third-party
        // DIDs may not honour that. Walk the array twice rather than
        // trust the order.
        let services = vec![
            TestService::new(&[SVC_WEBVH_HOSTING], Some("https://x")),
            TestService::new(&[SVC_DIDCOMM], None),
        ];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::TrustTask)
        );
    }

    #[test]
    fn rest_url_strips_surrounding_quotes() {
        let services = vec![TestService::new(
            &[SVC_WEBVH_HOSTING],
            Some("\"https://daemon.example\""),
        )];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::Rest {
                url: "https://daemon.example".into()
            })
        );
    }

    #[test]
    fn rest_url_strips_trailing_slash() {
        let services = vec![TestService::new(
            &[SVC_WEBVH_HOSTING],
            Some("https://daemon.example/"),
        )];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::Rest {
                url: "https://daemon.example".into()
            })
        );
    }

    #[test]
    fn rest_url_strips_quotes_and_trailing_slash_together() {
        let services = vec![TestService::new(
            &[SVC_WEBVH_HOSTING],
            Some("\"https://daemon.example/\""),
        )];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::Rest {
                url: "https://daemon.example".into()
            })
        );
    }

    #[test]
    fn rest_entry_without_endpoint_falls_through() {
        // A WebVHHosting entry with no URI shouldn't short-circuit —
        // a later valid entry should still win.
        let services = vec![
            TestService::new(&[SVC_WEBVH_HOSTING], None),
            TestService::new(&[SVC_WEBVH_HOSTING], Some("https://second.example")),
        ];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::Rest {
                url: "https://second.example".into()
            })
        );
    }

    #[test]
    fn rest_entry_with_empty_uri_after_trim_is_skipped() {
        // "/" → trims to empty → not usable. Caller should treat as
        // no REST service, fall through to a later entry or None.
        let services = vec![TestService::new(&[SVC_WEBVH_HOSTING], Some("/"))];
        assert_eq!(resolve_server_transport(&services), None);
    }

    #[test]
    fn multi_typed_service_entry_matches_any_type() {
        // A service entry can carry multiple types in `type` (rare
        // but valid per DID-Core). Match if any one of them is a
        // supported type.
        let services = vec![TestService::new(
            &["LinkedDomains", SVC_WEBVH_HOSTING],
            Some("https://multi.example"),
        )];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::Rest {
                url: "https://multi.example".into()
            })
        );
    }
}