vta-service 0.12.13

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Pure transport-resolution logic for WebVH hosting servers.
//!
//! Walks a server DID's service array and decides whether the VTA
//! should talk to it via DIDComm or REST, 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`.
//!
//! ## Accepted service types
//!
//! - `DIDCommMessaging` — preferred when present, regardless of
//!   position in the service array.
//! - `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.
//!
//! ## DIDComm precedence
//!
//! Workspace-wide invariant: when a DID advertises both transports,
//! Service[] is canonically ordered DIDComm-first (see
//! `protocol::document::sort_services_canonical`). We don't rely on
//! that ordering for *reading* foreign DIDs though — any DIDComm
//! entry, wherever it sits, wins over every REST entry. This keeps
//! third-party DIDs that emit non-canonical orderings working
//! without surprising the operator.

/// Service-type string emitted on DIDComm endpoints (per DIDComm v2).
pub(crate) const SVC_DIDCOMM: &str = "DIDCommMessaging";

/// 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>;
    /// The `hostingPath` the endpoint advertises, if any.
    ///
    /// A hosting server may serve its control plane under a prefix rather than
    /// at the origin root — `webvh.storm.ws` advertises `/webvh`. The DID
    /// templates have emitted this field all along, and nothing read it, so
    /// every REST request was built against the bare origin and 404'd on any
    /// server that uses one.
    fn hosting_path(&self) -> Option<String> {
        None
    }
}

/// Join an advertised origin and its optional hosting path into a base URL.
///
/// Both halves arrive from a DID document, so neither's punctuation can be
/// assumed: the origin may carry a trailing slash and the path may or may not
/// lead with one.
fn join_base(uri: &str, hosting_path: Option<&str>) -> String {
    let base = uri.trim_matches('"').trim_end_matches('/');
    match hosting_path.map(|p| p.trim_matches('"').trim_matches('/')) {
        Some(p) if !p.is_empty() => format!("{base}/{p}"),
        _ => base.to_string(),
    }
}

/// Outcome of walking a server's service array.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ResolvedTransport {
    DIDComm,
    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_didcomm)) {
        return Some(ResolvedTransport::DIDComm);
    }
    for svc in services {
        if svc.types().iter().any(is_webvh_rest)
            && let Some(raw) = svc.endpoint_uri()
        {
            let url = join_base(&raw, svc.hosting_path().as_deref());
            if url.is_empty() {
                continue;
            }
            return Some(ResolvedTransport::Rest { url });
        }
    }
    None
}

#[inline]
fn is_didcomm(t: &String) -> bool {
    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 =
    "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()
    }
    fn hosting_path(&self) -> Option<String> {
        // `Endpoint` models only `uri`; `hostingPath` sits beside it in the
        // same object, reachable through the untyped map form.
        use affinidi_tdk::did_common::service::Endpoint;
        let Endpoint::Map(value) = &self.service_endpoint else {
            return None;
        };
        let obj = match value {
            serde_json::Value::Array(a) => a.first()?,
            other => other,
        };
        obj.get("hostingPath")
            .and_then(|v| v.as_str())
            .map(str::to_string)
    }
}

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

    // ── hostingPath ─────────────────────────────────────────────────

    /// The live failure this fixes: `webvh.storm.ws` advertises
    /// `{"uri":"https://webvh.storm.ws","hostingPath":"/webvh"}`, and every
    /// REST request was built against the bare origin — so the control plane at
    /// `/webvh/api/...` answered 404.
    #[test]
    fn rest_base_includes_the_advertised_hosting_path() {
        let services = vec![TestService::with_hosting_path(
            &["WebVHHosting"],
            Some("https://webvh.storm.ws"),
            Some("/webvh"),
        )];
        assert_eq!(
            resolve_server_transport(&services),
            Some(ResolvedTransport::Rest {
                url: "https://webvh.storm.ws/webvh".to_string()
            })
        );
    }

    /// Neither half's punctuation can be assumed — both come from a document.
    #[test]
    fn rest_base_join_is_slash_tolerant() {
        for (uri, path) in [
            ("https://h.example/", "/webvh"),
            ("https://h.example", "webvh"),
            ("https://h.example/", "webvh/"),
        ] {
            let services = vec![TestService::with_hosting_path(
                &["WebVHHosting"],
                Some(uri),
                Some(path),
            )];
            assert_eq!(
                resolve_server_transport(&services),
                Some(ResolvedTransport::Rest {
                    url: "https://h.example/webvh".to_string()
                }),
                "uri={uri} path={path}"
            );
        }
    }

    /// A server serving at the origin root is unchanged — no empty segment.
    #[test]
    fn rest_base_is_unchanged_without_a_hosting_path() {
        for path in [None, Some(""), Some("/")] {
            let services = vec![TestService::with_hosting_path(
                &["WebVHHosting"],
                Some("https://h.example"),
                path,
            )];
            assert_eq!(
                resolve_server_transport(&services),
                Some(ResolvedTransport::Rest {
                    url: "https://h.example".to_string()
                }),
                "path={path:?}"
            );
        }
    }

    // ── resolve_rest_endpoint ───────────────────────────────────────

    struct TestService {
        types: Vec<String>,
        uri: Option<String>,
        hosting_path: 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),
                hosting_path: None,
            }
        }
        fn with_hosting_path(types: &[&str], uri: Option<&str>, path: Option<&str>) -> Self {
            Self {
                hosting_path: path.map(String::from),
                ..Self::new(types, uri)
            }
        }
    }
    impl ServiceEntry for TestService {
        fn types(&self) -> &[String] {
            &self.types
        }
        fn hosting_path(&self) -> Option<String> {
            self.hosting_path.clone()
        }
        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);
    }

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

    #[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 didcomm_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::DIDComm)
        );
    }

    #[test]
    fn didcomm_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::DIDComm)
        );
    }

    #[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()
            })
        );
    }
}