vta-sdk 0.11.0

SDK 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
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
//! Wire types for the runtime REST service-management surface.
//!
//! Spec: `docs/05-design-notes/runtime-service-management.md` §4.
//!
//! These cover the four REST operations exposed under
//! `pnm services rest {enable,update,disable,rollback}` plus the
//! shared response shape (`ServiceMutationResponse`) used by every
//! mutation across both REST and DIDComm kinds.
//!
//! DIDComm-side wire types live in [`super`] — `EnableDidcommRequest`,
//! `DisableDidcommRequest`, and (renamed in T2.3) `UpdateDidcommRequest`.
//! Keep the two surfaces in sync as they evolve.
//!
//! ## URL field convention
//!
//! `url: String` is intentional — the field stays a string here so
//! the SDK matches the existing protocol-management types
//! (`mediator_did: String`, etc.) and the operation layer applies a
//! single validation pass via [`crate::protocol::validate_service_url`]
//! (T1.2). Operators see one consistent error shape regardless of
//! whether validation runs client-side, server-side, or both.

use serde::{Deserialize, Serialize};

use crate::error::VtaError;

/// Validate a service-endpoint URL.
///
/// Spec §3.4: must be `https://`, parsable by `url::Url`, no
/// fragment, no userinfo. Returns the parsed [`url::Url`] on
/// success so callers don't re-parse, or [`VtaError::Validation`]
/// with a specific message on failure.
///
/// Centralized so both REST handlers and DIDComm transport
/// handlers (and any client-side pre-flight) use the same rule.
/// The CLI surfaces the rejection through `VtaError`'s
/// `suggested_fix` path; reasons are kept short and operator-
/// readable rather than full stack-trace text.
///
/// `localhost` and IP literals are accepted — the operator may
/// genuinely want to advertise a private deployment. TLS is still
/// required there (operator can run a private CA / mkcert); the
/// invariant is that clients see a TLS-protected URL in the DID
/// document, not that the cert chains to a public root.
pub fn validate_service_url(url: &str) -> Result<url::Url, VtaError> {
    let trimmed = url.trim();
    if trimmed.is_empty() {
        return Err(VtaError::Validation("service URL is empty".into()));
    }

    let parsed = url::Url::parse(trimmed)
        .map_err(|e| VtaError::Validation(format!("service URL is unparseable: {e}")))?;

    if parsed.scheme() != "https" {
        return Err(VtaError::Validation(format!(
            "service URL must use https:// (got {})",
            parsed.scheme()
        )));
    }

    if parsed.fragment().is_some() {
        return Err(VtaError::Validation(
            "service URL must not contain a `#fragment`".into(),
        ));
    }

    // userinfo = the `user:password@` part. `url::Url` exposes
    // username() (always returns "" when absent) and password()
    // (Option<&str>). A non-empty username OR a password being
    // present means userinfo is set.
    if !parsed.username().is_empty() || parsed.password().is_some() {
        return Err(VtaError::Validation(
            "service URL must not contain userinfo (user:password@)".into(),
        ));
    }

    if parsed.host().is_none() {
        return Err(VtaError::Validation("service URL must have a host".into()));
    }

    Ok(parsed)
}

/// Request body for `POST /services/rest/enable`.
///
/// Adds a `#vta-rest` service entry to the VTA's DID document
/// pointing at `url`. Refused with `ServiceAlreadyEnabled` if REST
/// is already advertised. The wire shape rendered into the DID
/// document — `id: "{DID}#vta-rest"`, `type: "VTARest"` — is
/// preserved by the operation layer (P1.3) for SDK-resolution
/// compatibility (`vta-sdk/src/session.rs:1100`).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[must_use]
pub struct EnableRestRequest {
    pub url: String,
}

impl EnableRestRequest {
    pub fn new(url: impl Into<String>) -> Self {
        Self { url: url.into() }
    }
}

/// Request body for `POST /services/rest/update`.
///
/// Replaces the URL on the existing `#vta-rest` entry. Refused
/// with `ServiceNotPresent` if REST is not currently advertised.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[must_use]
pub struct UpdateRestRequest {
    pub url: String,
}

impl UpdateRestRequest {
    pub fn new(url: impl Into<String>) -> Self {
        Self { url: url.into() }
    }
}

/// Request body for `POST /services/rest/disable`.
///
/// Removes the `#vta-rest` entry. Refused with
/// `LastServiceRefused` when DIDComm is also disabled (spec §3.2)
/// and with `ServiceNotPresent` if REST isn't currently advertised.
///
/// No fields today — the body exists so the wire surface stays
/// uniform (every mutation is a `POST` with a JSON body) and so
/// the type can grow optional fields later without a breaking
/// change. Serializes as `{}`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[must_use]
pub struct DisableRestRequest {}

/// Request body for `POST /services/rest/rollback`.
///
/// Fail-forwards the most recent REST mutation (spec §3.5a) by
/// reading the snapshot store and dispatching to the equivalent
/// forward operation. Refused with `NoPriorMutation` when no
/// snapshot is recorded, and with `LastServiceRefused` if the
/// rollback would brick the VTA. Like [`DisableRestRequest`],
/// no fields today — serializes as `{}`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[must_use]
pub struct RollbackRestRequest {}

/// Request body for `POST /services/webauthn/enable`.
///
/// Adds a `#vta-webauthn` service entry to the VTA's DID document
/// pointing at `url`. Refused with `ServiceAlreadyEnabled` if the
/// WebAuthn-RP surface is already advertised. The wire shape
/// rendered into the DID document — `id: "{DID}#vta-webauthn"`,
/// `type: "WebAuthnRP"` — is preserved by the operation layer.
///
/// Distinct from `EnableRestRequest` because the WebAuthn-RP
/// surface has different availability semantics: it can be
/// toggled independently of the general REST API and is the entry
/// point browsers discover for the auth portal.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[must_use]
pub struct EnableWebauthnRequest {
    pub url: String,
}

impl EnableWebauthnRequest {
    pub fn new(url: impl Into<String>) -> Self {
        Self { url: url.into() }
    }
}

/// Request body for `POST /services/webauthn/update`.
///
/// Replaces the URL on the existing `#vta-webauthn` entry. Refused
/// with `ServiceNotPresent` if the WebAuthn surface is not currently
/// advertised.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[must_use]
pub struct UpdateWebauthnRequest {
    pub url: String,
}

impl UpdateWebauthnRequest {
    pub fn new(url: impl Into<String>) -> Self {
        Self { url: url.into() }
    }
}

/// Request body for `POST /services/webauthn/disable`.
///
/// Removes the `#vta-webauthn` entry **and** any passkey
/// verificationMethods published on the VTA's DID document — the
/// operator chose hard-disable semantics so a disabled WebAuthn-RP
/// surface doesn't leave dangling VMs claiming to authenticate
/// against an unreachable RP.
///
/// Refused with `LastServiceRefused` when removing WebAuthn would
/// leave no transport advertised at all (spec §3.2; WebAuthn counts
/// as a transport for this invariant).
///
/// No fields today — serializes as `{}`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[must_use]
pub struct DisableWebauthnRequest {}

/// Request body for `POST /services/webauthn/rollback`. Symmetric
/// with [`RollbackRestRequest`].
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[must_use]
pub struct RollbackWebauthnRequest {}

/// Request body for `POST /services/didcomm/rollback`.
///
/// Threads `drain_ttl_secs` through to the dispatched forward op
/// for the disable / update arms. Server applies the spec §3.6
/// default (24h) when omitted.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[must_use]
pub struct RollbackDidcommRequest {
    /// Drain window for the previously-active mediator (seconds).
    /// Server default is 24h when omitted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub drain_ttl_secs: Option<u64>,
}

impl RollbackDidcommRequest {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn drain_ttl_secs(mut self, secs: u64) -> Self {
        self.drain_ttl_secs = Some(secs);
        self
    }
}

/// Response body for `GET /services/didcomm/drain` — the list of
/// mediators currently in drain state. Empty list is normal.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DrainListResponse {
    pub entries: Vec<DrainEntry>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DrainEntry {
    pub mediator_did: String,
    pub endpoint: String,
    /// Drain deadline (RFC 3339).
    pub drains_until: String,
}

/// Response body for the rollback handlers. Wider than
/// [`ServiceMutationResponse`] — adds `kind` and
/// `draining_mediator` fields that downstream consumers need to
/// distinguish the dispatched arm.
///
/// `log_entry_version_id` is the empty string when the rollback
/// was a no-op (snapshot ≡ current state).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RollbackResponse {
    pub log_entry_version_id: String,
    pub effective_at: String,
    /// One of: `disabled`, `enabled`, `updated`, `no_op`.
    pub kind: String,
    /// `Some(rfc3339)` when the rollback scheduled a drain.
    /// `None` for REST and DIDComm enable / no-op arms.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub drain_until: Option<String>,
    /// Mediator DID currently being drained by this rollback.
    /// `None` for REST and DIDComm enable / no-op arms.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub draining_mediator: Option<String>,
    /// The VTA's own DID — the subject of the LogEntry this
    /// rollback wrote. Carried so the CLI can print follow-up
    /// commands like `pnm webvh did-log <vta_did>` for serverless
    /// deployments without forcing the operator to look it up.
    /// Empty string in `no_op` responses where no LogEntry was
    /// written. Serialized as `vta_did` on the wire; elided when
    /// empty for compactness.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub vta_did: String,
    /// True when the VTA's DID is self-hosted (`server_id =
    /// "serverless"`). The rollback's new LogEntry is persisted
    /// locally but NOT pushed to any webvh host — the operator
    /// must fetch the updated `did.jsonl` and redeploy.
    /// `#[serde(default)]` for back-compat — older servers don't
    /// emit the field and old clients treat absent → false.
    #[serde(default)]
    pub serverless: bool,
}

/// Response body for `GET /services` — the operator-facing read
/// surface for inspecting the VTA's current advertised transport
/// services. Spec §10 (resolved): minimal shape — one entry per
/// kind, `enabled` flag, kind-specific config when enabled.
///
/// Order is canonical: DIDComm before REST when both are
/// advertised, matching the spec §3.3 ordering invariant
/// enforced in `protocol::document::sort_services_canonical`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ServicesListResponse {
    pub services: Vec<ServiceState>,
}

/// State of a single transport kind. The `kind` discriminator is
/// `"rest"`, `"didcomm"`, or `"webauthn"` on the wire (kebab-case to
/// align with the rest of the runtime service-management surface).
/// When `enabled` is `false`, the kind-specific config fields are
/// absent.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum ServiceState {
    Rest {
        enabled: bool,
        /// Currently-published REST URL. `None` when REST is
        /// disabled.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        url: Option<String>,
    },
    Didcomm {
        enabled: bool,
        /// Currently-active mediator DID. `None` when DIDComm is
        /// disabled.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        mediator_did: Option<String>,
        /// Routing keys for the active mediator. Empty when
        /// DIDComm is disabled or when the mediator entry doesn't
        /// carry routing-keys today (the workspace's `#vta-didcomm`
        /// service entry currently doesn't).
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        routing_keys: Vec<String>,
    },
    Webauthn {
        enabled: bool,
        /// Currently-published WebAuthn-RP URL — typically the
        /// operator-facing auth portal. `None` when the WebAuthn
        /// service is disabled.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        url: Option<String>,
    },
}

/// Shared response body for every successful service-mutation
/// operation (REST + DIDComm enable/update/disable/rollback).
///
/// `drain_until` is `Some(rfc3339)` only for DIDComm operations
/// that scheduled a drain (`update_didcomm`, `disable_didcomm`,
/// or a `rollback_didcomm` whose fail-forward target was a drain
/// transition). REST mutations always set it to `None`.
///
/// All timestamps are RFC 3339 strings to match the existing wire
/// convention from `DisableDidcommResponse::drains_until`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ServiceMutationResponse {
    /// Version-id of the new WebVH LogEntry produced by the
    /// mutation. Joins telemetry events to chain history.
    pub log_entry_version_id: String,
    /// RFC 3339 timestamp when the mutation took effect — the
    /// same instant stamped on the new LogEntry.
    pub effective_at: String,
    /// `Some(rfc3339)` when the mutation scheduled a DIDComm
    /// drain; `None` otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub drain_until: Option<String>,
    /// The VTA's own DID — subject of the LogEntry this mutation
    /// wrote. Carried so the CLI can print follow-up commands like
    /// `pnm webvh did-log <vta_did>` for serverless deployments
    /// without forcing the operator to look it up.
    /// `#[serde(default)]` + `skip_serializing_if = "String::is_empty"`
    /// keep the wire compact and back-compat with older servers.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub vta_did: String,
    /// True when the VTA's DID is self-hosted (`server_id =
    /// "serverless"`). The new LogEntry is persisted locally but
    /// NOT pushed to any webvh host — the operator must fetch the
    /// updated `did.jsonl` and redeploy. `#[serde(default)]` for
    /// back-compat — older servers don't emit the field; old
    /// clients treat absent → false (no spurious hint).
    #[serde(default)]
    pub serverless: bool,
}

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

    /// Round-trip every request type — both directions, across the
    /// wire forms used by REST handlers (raw JSON body) and DIDComm
    /// transport (JSON-tagged in the message attachment).
    #[test]
    fn rest_request_types_round_trip_through_json() {
        let req = EnableRestRequest::new("https://vta.example.com");
        let json = serde_json::to_string(&req).unwrap();
        let restored: EnableRestRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(restored, req);

        let req = UpdateRestRequest::new("https://vta-new.example.com");
        let json = serde_json::to_string(&req).unwrap();
        let restored: UpdateRestRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(restored, req);

        let req = DisableRestRequest::default();
        let json = serde_json::to_string(&req).unwrap();
        let restored: DisableRestRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(restored, req);

        let req = RollbackRestRequest::default();
        let json = serde_json::to_string(&req).unwrap();
        let restored: RollbackRestRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(restored, req);
    }

    /// The empty request bodies must serialize as `{}`, not `null`,
    /// `[]`, or a string. REST clients that send `null` would
    /// fail strict-deserialize servers; pin the wire form.
    #[test]
    fn empty_request_bodies_serialize_as_empty_object() {
        assert_eq!(
            serde_json::to_string(&DisableRestRequest::default()).unwrap(),
            "{}"
        );
        assert_eq!(
            serde_json::to_string(&RollbackRestRequest::default()).unwrap(),
            "{}"
        );
    }

    /// The empty request bodies must also accept an empty object
    /// `{}` (and `null`, via `Default`) on the deserialize side, so
    /// callers that send no body don't trip up the server.
    #[test]
    fn empty_request_bodies_accept_empty_object() {
        let _: DisableRestRequest = serde_json::from_str("{}").unwrap();
        let _: RollbackRestRequest = serde_json::from_str("{}").unwrap();
    }

    /// `url` field name must stay literal `url` on the wire —
    /// renaming it would break every caller. Pin via JSON shape
    /// rather than relying solely on the `#[derive(Serialize)]`
    /// default.
    #[test]
    fn rest_url_field_is_literal_url_on_wire() {
        let json = serde_json::to_value(EnableRestRequest::new("https://x.example")).unwrap();
        assert_eq!(json["url"], "https://x.example");
        assert!(json.get("uri").is_none(), "must not rename url to uri");

        let json = serde_json::to_value(UpdateRestRequest::new("https://y.example")).unwrap();
        assert_eq!(json["url"], "https://y.example");
    }

    /// `ServiceMutationResponse` round-trips with and without
    /// `drain_until`. The `None` case omits the field on the wire
    /// (per `skip_serializing_if`); the `Some` case includes the
    /// RFC 3339 timestamp.
    #[test]
    fn service_mutation_response_round_trips_both_drain_states() {
        let rest_response = ServiceMutationResponse {
            log_entry_version_id: "1-zQm...A".into(),
            effective_at: "2026-05-06T13:00:00Z".into(),
            drain_until: None,
            vta_did: "did:webvh:scid:host:vta".into(),
            serverless: false,
        };
        let json = serde_json::to_value(&rest_response).unwrap();
        assert_eq!(json["log_entry_version_id"], "1-zQm...A");
        assert_eq!(json["effective_at"], "2026-05-06T13:00:00Z");
        assert!(
            json.get("drain_until").is_none(),
            "drain_until must be omitted when None — wire bandwidth + reader convention",
        );
        let restored: ServiceMutationResponse = serde_json::from_value(json).unwrap();
        assert_eq!(restored, rest_response);

        let didcomm_response = ServiceMutationResponse {
            log_entry_version_id: "2-zQm...B".into(),
            effective_at: "2026-05-06T13:00:00Z".into(),
            drain_until: Some("2026-05-07T13:00:00Z".into()),
            vta_did: "did:webvh:scid:host:vta".into(),
            serverless: true,
        };
        let json = serde_json::to_value(&didcomm_response).unwrap();
        assert_eq!(json["drain_until"], "2026-05-07T13:00:00Z");
        assert_eq!(json["vta_did"], "did:webvh:scid:host:vta");
        assert_eq!(json["serverless"], true);
        let restored: ServiceMutationResponse = serde_json::from_value(json).unwrap();
        assert_eq!(restored, didcomm_response);
    }

    /// Back-compat: older servers don't emit `vta_did` /
    /// `serverless`. Absent on the wire → string default ("") +
    /// bool default (false). Pins what `#[serde(default)]` buys.
    #[test]
    fn service_mutation_response_decodes_legacy_payload() {
        let legacy = r#"{
            "log_entry_version_id": "1-zQm...A",
            "effective_at": "2026-05-06T13:00:00Z"
        }"#;
        let r: ServiceMutationResponse = serde_json::from_str(legacy).unwrap();
        assert_eq!(r.vta_did, "");
        assert!(!r.serverless);
    }

    // ── validate_service_url ──────────────────────────────────────

    #[test]
    fn validate_service_url_accepts_https() {
        assert!(validate_service_url("https://vta.example.com").is_ok());
        assert!(validate_service_url("https://vta.example.com/").is_ok());
        assert!(validate_service_url("https://vta.example.com:8443").is_ok());
        assert!(validate_service_url("https://vta.example.com/path/sub").is_ok());
    }

    #[test]
    fn validate_service_url_accepts_localhost_and_ip_literals() {
        // Private/dev deployments are valid — operators may run
        // mkcert or a private CA; TLS-protected is what matters,
        // not whether the cert chains to a public root.
        assert!(validate_service_url("https://localhost:8443").is_ok());
        assert!(validate_service_url("https://127.0.0.1:8443").is_ok());
        assert!(validate_service_url("https://[::1]:8443").is_ok());
    }

    #[test]
    fn validate_service_url_rejects_http() {
        let err = validate_service_url("http://vta.example.com").unwrap_err();
        match err {
            VtaError::Validation(msg) => assert!(
                msg.contains("https"),
                "expected scheme-related rejection, got: {msg}",
            ),
            other => panic!("expected Validation, got {other:?}"),
        }
    }

    #[test]
    fn validate_service_url_rejects_other_schemes() {
        for bad in [
            "ws://vta.example.com",
            "ftp://x.example",
            "file:///etc/passwd",
        ] {
            assert!(
                matches!(validate_service_url(bad), Err(VtaError::Validation(_))),
                "expected rejection for {bad}",
            );
        }
    }

    #[test]
    fn validate_service_url_rejects_fragment() {
        let err = validate_service_url("https://vta.example.com/api#section").unwrap_err();
        match err {
            VtaError::Validation(msg) => {
                assert!(
                    msg.contains("fragment"),
                    "expected fragment rejection, got: {msg}"
                )
            }
            other => panic!("expected Validation, got {other:?}"),
        }
    }

    #[test]
    fn validate_service_url_rejects_userinfo() {
        for bad in [
            "https://user@vta.example.com",
            "https://user:pass@vta.example.com",
            "https://:pass@vta.example.com",
        ] {
            let err = validate_service_url(bad).unwrap_err();
            match err {
                VtaError::Validation(msg) => assert!(
                    msg.contains("userinfo"),
                    "expected userinfo rejection for {bad}, got: {msg}",
                ),
                other => panic!("expected Validation for {bad}, got {other:?}"),
            }
        }
    }

    #[test]
    fn validate_service_url_rejects_unparseable() {
        for bad in ["not a url at all", "://no-scheme", "https://", "🦀"] {
            assert!(
                matches!(validate_service_url(bad), Err(VtaError::Validation(_))),
                "expected rejection for {bad:?}",
            );
        }
    }

    #[test]
    fn validate_service_url_rejects_empty_and_whitespace() {
        for bad in ["", "   ", "\t\n"] {
            let err = validate_service_url(bad).unwrap_err();
            match err {
                VtaError::Validation(msg) => assert!(
                    msg.contains("empty"),
                    "expected empty-URL rejection for {bad:?}, got: {msg}",
                ),
                other => panic!("expected Validation for {bad:?}, got {other:?}"),
            }
        }
    }

    /// On success, the parsed `url::Url` is returned so callers
    /// don't re-parse. Spot-check a couple of properties.
    #[test]
    fn validate_service_url_returns_parsed_url() {
        let parsed = validate_service_url("https://vta.example.com:8443/api").unwrap();
        assert_eq!(parsed.scheme(), "https");
        assert_eq!(parsed.host_str(), Some("vta.example.com"));
        assert_eq!(parsed.port(), Some(8443));
        assert_eq!(parsed.path(), "/api");
    }

    // ── ServicesListResponse / ServiceState wire shape ──────────

    #[test]
    fn services_list_response_round_trips_both_kinds() {
        let response = ServicesListResponse {
            services: vec![
                ServiceState::Didcomm {
                    enabled: true,
                    mediator_did: Some("did:peer:2.M".into()),
                    routing_keys: vec!["did:peer:2.K".into()],
                },
                ServiceState::Rest {
                    enabled: true,
                    url: Some("https://vta.example.com".into()),
                },
            ],
        };
        let json = serde_json::to_string(&response).unwrap();
        let restored: ServicesListResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(restored, response);
    }

    /// Disabled state on either kind has the kind-specific config
    /// fields elided from the wire form (per `skip_serializing_if`).
    #[test]
    fn service_state_disabled_omits_config_fields() {
        let rest_off = ServiceState::Rest {
            enabled: false,
            url: None,
        };
        let json = serde_json::to_value(&rest_off).unwrap();
        assert_eq!(json["kind"], "rest");
        assert_eq!(json["enabled"], false);
        assert!(
            json.get("url").is_none(),
            "url must be elided when None to keep the wire form clean",
        );

        let didcomm_off = ServiceState::Didcomm {
            enabled: false,
            mediator_did: None,
            routing_keys: vec![],
        };
        let json = serde_json::to_value(&didcomm_off).unwrap();
        assert_eq!(json["kind"], "didcomm");
        assert_eq!(json["enabled"], false);
        assert!(json.get("mediator_did").is_none());
        assert!(json.get("routing_keys").is_none());
    }

    /// Discriminator field is literal `kind` with kebab-case
    /// (`rest` / `didcomm`) values — pin the wire contract so a
    /// `serde(rename)` tweak fails loudly.
    #[test]
    fn service_state_discriminator_is_literal_kind() {
        let json = serde_json::to_value(ServiceState::Rest {
            enabled: true,
            url: Some("https://x.example".into()),
        })
        .unwrap();
        assert_eq!(json["kind"], "rest");

        let json = serde_json::to_value(ServiceState::Didcomm {
            enabled: true,
            mediator_did: Some("did:peer:2.M".into()),
            routing_keys: vec![],
        })
        .unwrap();
        assert_eq!(json["kind"], "didcomm");
    }

    /// `ServiceMutationResponse` deserializes both forms — explicit
    /// `null` for drain_until (some encoders emit it) and the
    /// elided form (preferred).
    #[test]
    fn service_mutation_response_accepts_explicit_null_drain_until() {
        let with_null = r#"{
            "log_entry_version_id": "1-zQm...A",
            "effective_at": "2026-05-06T13:00:00Z",
            "drain_until": null
        }"#;
        let r: ServiceMutationResponse = serde_json::from_str(with_null).unwrap();
        assert_eq!(r.drain_until, None);

        let elided = r#"{
            "log_entry_version_id": "1-zQm...A",
            "effective_at": "2026-05-06T13:00:00Z"
        }"#;
        let r: ServiceMutationResponse = serde_json::from_str(elided).unwrap();
        assert_eq!(r.drain_until, None);
    }
}