vta-service 0.10.0

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
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
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
use serde::Deserialize;
use std::time::{SystemTime, UNIX_EPOCH};
use tracing::{debug, info, warn};
use url::{Host, Url};

use crate::error::AppError;
use crate::webvh_auth::{
    ChallengeContext, VtaSigningIdentity, build_authenticate_message, build_refresh_message,
};

pub struct WebvhClient {
    http: reqwest::Client,
    server_url: String,
    /// The daemon's DID. Bound at construction so the auth flow can
    /// populate the DIDComm `to:` field for audience-binding, and so
    /// the operator-facing error messages can name *which* daemon
    /// the failure came from.
    server_did: String,
    access_token: Option<String>,
}

/// Decide whether a host is a loopback address we're willing to dial
/// over plaintext `http://` in dev. We accept:
///
/// - the literal domain `localhost` (and only that — `localhost.evil`
///   resolves to attacker-controlled IPs),
/// - any IPv4 in `127.0.0.0/8` (covers `127.0.0.1` and dev shims like
///   `127.0.0.2`),
/// - the IPv6 loopback `::1` (and only that — `::ffff:8.8.8.8` IPv4-
///   mapped IPv6 is *not* a loopback even though it sometimes parses
///   as one in laxer stacks).
///
/// We deliberately exclude `0.0.0.0` (a listen-on-all-interfaces
/// sentinel an operator should rarely *dial*) and
/// `host.docker.internal` (resolution depends on the container
/// runtime). Operators who need plain HTTP from outside loopback
/// should terminate TLS at a reverse proxy and advertise its
/// `https://` URL in the daemon DID's service entry.
fn is_loopback_host(host: &Host<&str>) -> bool {
    match host {
        Host::Domain(d) => *d == "localhost",
        Host::Ipv4(ip) => ip.is_loopback(),
        Host::Ipv6(ip) => ip.is_loopback(),
    }
}

/// Reject schemes other than `https://` (always) or `http://` to a
/// loopback host (dev only). Bearer tokens, the VTA-signed
/// authenticate JWS, and refresh tokens must never travel over
/// plaintext. The check happens at client construction so every
/// REST entrypoint inherits it — there is no "skip the check"
/// path for individual requests.
fn enforce_transport_security(parsed: &Url, raw: &str) -> Result<(), AppError> {
    let scheme = parsed.scheme();
    if scheme == "https" {
        return Ok(());
    }
    if scheme == "http" {
        if parsed.host().map(|h| is_loopback_host(&h)).unwrap_or(false) {
            return Ok(());
        }
        return Err(AppError::Validation(format!(
            "refusing to dial webvh-server `{raw}` over plaintext `http://`: \
             bearer tokens and the VTA's signed authenticate payload must not be sent \
             over plaintext. Only `http://` to a loopback host \
             (localhost, 127/8, ::1) is permitted; advertise an `https://` endpoint in \
             the server DID's service entry instead.",
        )));
    }
    Err(AppError::Validation(format!(
        "webvh-server URL `{raw}` uses unsupported scheme `{scheme}://`; \
         only `https://` (recommended) or `http://` to a loopback host are accepted.",
    )))
}

#[derive(Debug, Deserialize)]
pub struct RequestUriResponse {
    pub did_url: String,
    pub mnemonic: String,
}

#[derive(Debug, Deserialize)]
pub struct CheckPathResponse {
    pub available: bool,
}

/// Tokens returned by the daemon's `/api/auth/` and `/api/auth/refresh`
/// endpoints. Field names match the daemon's
/// `affinidi_webvh_common::AuthenticateData` / `RefreshData` (camelCase
/// on the wire). The daemon **always rotates the refresh token** on
/// use, so a `TokenData` returned from `refresh()` carries a
/// different `refresh_token` from the one supplied as input —
/// callers must persist the new value.
///
/// Hygiene:
/// - `ZeroizeOnDrop` overwrites the token bytes when the instance
///   falls out of scope.
/// - `Debug` is manually implemented to redact the token strings —
///   accidental `tracing::error!(?tokens, ...)` then logs
///   `<redacted>` instead of the secret.
#[derive(Clone, Deserialize, zeroize::ZeroizeOnDrop)]
#[serde(rename_all = "camelCase")]
pub struct TokenData {
    pub access_token: String,
    pub access_expires_at: u64,
    pub refresh_token: String,
    pub refresh_expires_at: u64,
}

impl std::fmt::Debug for TokenData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TokenData")
            .field("access_token", &"<redacted>")
            .field("access_expires_at", &self.access_expires_at)
            .field("refresh_token", &"<redacted>")
            .field("refresh_expires_at", &self.refresh_expires_at)
            .finish()
    }
}

/// Wire shape of `/api/auth/` and `/api/auth/refresh` responses.
/// Wrapped in `{session_id, data}` per the daemon's
/// `AuthenticateResponse` / `RefreshResponse` types.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TokenResponseWire {
    #[allow(dead_code)] // accepted for shape match; client doesn't need the value
    session_id: String,
    data: TokenData,
}

/// Wire shape of `/api/auth/challenge` response. Daemon emits
/// camelCase (`sessionId`); we accept both forms via `alias` to
/// stay compatible with any deployment that hasn't redeployed yet
/// (the daemon's older builds emitted snake_case before the
/// `#[serde(rename_all = "camelCase")]` annotation was added).
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ChallengeResponseWire {
    #[serde(alias = "session_id")]
    session_id: String,
    data: ChallengeData,
}

#[derive(Debug, Deserialize)]
struct ChallengeData {
    challenge: String,
}

fn unix_now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

impl WebvhClient {
    /// Construct a client for a daemon REST URL. Rejects URLs whose
    /// scheme would send the bearer token / authenticate JWS over
    /// plaintext to a non-loopback host. See
    /// [`enforce_transport_security`] for the policy.
    ///
    /// `server_did` is the daemon's DID. The auth flow uses it for
    /// the DIDComm `to:` field (audience binding) and operator-facing
    /// error messages name it explicitly.
    pub fn new(server_url: &str, server_did: &str) -> Result<Self, AppError> {
        let parsed = Url::parse(server_url).map_err(|e| {
            AppError::Validation(format!("invalid webvh-server URL `{server_url}`: {e}"))
        })?;
        enforce_transport_security(&parsed, server_url)?;
        Ok(Self {
            http: reqwest::Client::new(),
            server_url: server_url.trim_end_matches('/').to_string(),
            server_did: server_did.to_string(),
            access_token: None,
        })
    }

    pub fn set_access_token(&mut self, token: String) {
        self.access_token = Some(token);
    }

    /// Run the full challenge → JWS-authenticate flow against the
    /// daemon, returning a fresh token pair. Does not mutate
    /// `self.access_token`; the caller chooses what to do with the
    /// returned tokens (typically persist via `webvh_store`).
    ///
    /// Errors map to typed `AppError` variants so the route /
    /// operation layer can surface the right hint to the operator:
    ///
    /// - daemon 401 → `Authentication` (signature / session /
    ///   challenge invalid; likely clock skew or kid mismatch),
    /// - daemon 403 → `Forbidden` (signature valid, VTA DID not in
    ///   daemon ACL — corrective action is daemon-side),
    /// - daemon 4xx other → `Validation`,
    /// - daemon 5xx → `Internal`,
    /// - network/parse failures → `Internal`.
    pub async fn authenticate(
        &self,
        identity: &VtaSigningIdentity<'_>,
    ) -> Result<TokenData, AppError> {
        let challenge = self.fetch_challenge(identity.vta_did).await?;

        let jws = build_authenticate_message(
            identity,
            &ChallengeContext {
                session_id: &challenge.session_id,
                challenge: &challenge.data.challenge,
                server_did: &self.server_did,
            },
            unix_now_secs(),
        )?;

        let url = format!("{}/api/auth/", self.server_url);
        info!(method = "POST", %url, "webvh: authenticating");
        let resp = self
            .http
            .post(&url)
            .header("Content-Type", "application/json")
            .body(jws)
            .send()
            .await
            .map_err(|e| AppError::Internal(format!("webvh authenticate request failed: {e}")))?;

        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        if !status.is_success() {
            return Err(self.map_auth_failure(status, &body, identity.vta_did));
        }
        let parsed: TokenResponseWire = serde_json::from_str(&body).map_err(|e| {
            AppError::Internal(format!(
                "webvh authenticate response parse error: {e} (body: {body})"
            ))
        })?;
        Ok(parsed.data)
    }

    /// Redeem a refresh token against the daemon. Returns the rotated
    /// token pair. The daemon always rotates refresh tokens on use, so
    /// the returned `refresh_token` differs from the input — callers
    /// must persist the new one immediately.
    pub async fn refresh(
        &self,
        identity: &VtaSigningIdentity<'_>,
        refresh_token: &str,
    ) -> Result<TokenData, AppError> {
        let jws =
            build_refresh_message(identity, &self.server_did, refresh_token, unix_now_secs())?;
        let url = format!("{}/api/auth/refresh", self.server_url);
        info!(method = "POST", %url, "webvh: refreshing token");
        let resp = self
            .http
            .post(&url)
            .header("Content-Type", "application/json")
            .body(jws)
            .send()
            .await
            .map_err(|e| AppError::Internal(format!("webvh refresh request failed: {e}")))?;
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        if !status.is_success() {
            // Refresh failure is normal at end-of-lifetime — return
            // a typed `Authentication` so the caller can fall back to
            // a full re-authenticate instead of bubbling a 500.
            warn!(
                status = %status,
                vta_did = %identity.vta_did,
                "webvh refresh rejected by daemon",
            );
            return Err(AppError::Authentication(format!(
                "webvh-server {} rejected refresh token (status {status}): {body}",
                self.server_did,
            )));
        }
        let parsed: TokenResponseWire = serde_json::from_str(&body).map_err(|e| {
            AppError::Internal(format!(
                "webvh refresh response parse error: {e} (body: {body})"
            ))
        })?;
        Ok(parsed.data)
    }

    async fn fetch_challenge(&self, vta_did: &str) -> Result<ChallengeResponseWire, AppError> {
        let url = format!("{}/api/auth/challenge", self.server_url);
        debug!(method = "POST", %url, "webvh: fetching challenge");
        let resp = self
            .http
            .post(&url)
            .json(&serde_json::json!({ "did": vta_did }))
            .send()
            .await
            .map_err(|e| AppError::Internal(format!("webvh challenge request failed: {e}")))?;
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        if !status.is_success() {
            return Err(AppError::Internal(format!(
                "webvh-server {} POST /api/auth/challenge failed (status {status}): {body}",
                self.server_did,
            )));
        }
        serde_json::from_str(&body).map_err(|e| {
            AppError::Internal(format!(
                "webvh challenge response parse error: {e} (body: {body})"
            ))
        })
    }

    /// Map a non-2xx response from `/api/auth/` to a typed `AppError`.
    ///
    /// The daemon distinguishes:
    ///
    /// - **401 Unauthorized** — signature / session / challenge
    ///   verification failed. Common causes: clock skew between VTA
    ///   and daemon (daemon accepts a ±5min window), the challenge
    ///   expired before redemption, or the signing-key fragment on
    ///   the VTA doesn't match a verification method in its DID
    ///   document.
    /// - **403 Forbidden** — signature was valid, but the VTA's
    ///   DID is not in the daemon's ACL. Corrective action is on
    ///   the daemon side.
    ///
    /// Two distinct hints so the CLI can guide the operator to the
    /// *actually* broken thing. (Earlier on this branch the ACL hint
    /// was attached to the 401 arm — caught by the audit.)
    fn map_auth_failure(&self, status: reqwest::StatusCode, body: &str, vta_did: &str) -> AppError {
        if status == reqwest::StatusCode::UNAUTHORIZED {
            return AppError::Authentication(format!(
                "webvh-server {server_did} rejected authentication signature for VTA DID `{vta_did}`. \
                 Likely causes: clock skew between VTA and daemon (daemon accepts a ±5min window), \
                 expired challenge, or a signing-key fragment that doesn't match a verification method \
                 in the VTA's DID document. Daemon response: {body}",
                server_did = self.server_did,
            ));
        }
        if status == reqwest::StatusCode::FORBIDDEN {
            return AppError::Forbidden(format!(
                "webvh-server {server_did} accepted the signature for VTA DID `{vta_did}` but the \
                 DID is not in the daemon's ACL. The corrective action is daemon-side: grant the \
                 VTA's DID access on the daemon. Daemon response: {body}",
                server_did = self.server_did,
            ));
        }
        if status.is_client_error() {
            return AppError::Validation(format!(
                "webvh-server {} rejected authentication (status {status}): {body}",
                self.server_did,
            ));
        }
        AppError::Internal(format!(
            "webvh-server {} authentication failed (status {status}): {body}",
            self.server_did,
        ))
    }

    /// Apply authorization header (if set) to a request builder.
    fn with_auth(&self, mut req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        if let Some(ref token) = self.access_token {
            req = req.header("Authorization", format!("Bearer {token}"));
        }
        req
    }

    /// Send a request and map non-2xx HTTP statuses to typed
    /// `AppError` variants so the operation layer can switch on them:
    ///
    /// - 401 → `Unauthorized` (token rejected; caller should
    ///   invalidate cache and re-authenticate),
    /// - 403 → `Forbidden` (daemon ACL miss),
    /// - 4xx other → `Validation` (request-shape rejection),
    /// - 5xx → `Internal` (daemon-side fault),
    /// - network failure → `Internal`.
    ///
    /// The error message names the daemon DID so operator-facing
    /// errors don't need to thread the server identity separately.
    async fn send(
        &self,
        req: reqwest::RequestBuilder,
        context: &str,
    ) -> Result<reqwest::Response, AppError> {
        let resp = req
            .send()
            .await
            .map_err(|e| AppError::Internal(format!("webvh-server request failed: {e}")))?;
        let status = resp.status();
        if !status.is_success() {
            let text = resp.text().await.unwrap_or_default();
            let msg = format!(
                "webvh-server {server} {context} failed ({status}): {text}",
                server = self.server_did,
            );
            return Err(match status {
                reqwest::StatusCode::UNAUTHORIZED => AppError::Unauthorized(msg),
                reqwest::StatusCode::FORBIDDEN => AppError::Forbidden(msg),
                // A taken path (e.g. `POST /api/dids` on an already-reserved
                // slot) is a clean conflict, not a malformed request — keep
                // it a 409 to the caller rather than collapsing to a 400.
                reqwest::StatusCode::CONFLICT => AppError::Conflict(msg),
                s if s.is_client_error() => AppError::Validation(msg),
                _ => AppError::Internal(msg),
            });
        }
        debug!(
            status = status.as_u16(),
            context, "webvh: received via rest"
        );
        Ok(resp)
    }

    /// POST /api/dids — reserve a path on the remote.
    ///
    /// `domain` is the optional hosting domain to target. When the
    /// remote serves multiple tenant domains, the operator (via pnm
    /// CLI `--domain`) supplies the target; otherwise the remote
    /// resolves through caller's ACL default → system default. An
    /// unknown domain on the remote is rejected as
    /// `did-management:unknown_domain`.
    pub async fn request_uri(
        &self,
        path: Option<&str>,
        domain: Option<&str>,
    ) -> Result<RequestUriResponse, AppError> {
        let url = format!("{}/api/dids", self.server_url);
        info!(method = "POST", %url, "webvh: sending via rest");
        let mut body = serde_json::Map::new();
        if let Some(p) = path {
            body.insert("path".to_string(), serde_json::Value::String(p.to_string()));
        }
        if let Some(d) = domain {
            body.insert(
                "domain".to_string(),
                serde_json::Value::String(d.to_string()),
            );
        }
        let req = self
            .with_auth(self.http.post(&url))
            .json(&serde_json::Value::Object(body));
        let resp = self.send(req, "POST /api/dids").await?;
        resp.json()
            .await
            .map_err(|e| AppError::Internal(format!("webvh-server response parse error: {e}")))
    }

    /// POST /api/dids/register — atomic claim-and-publish.
    ///
    /// Single round-trip equivalent to `request_uri(path)` +
    /// `publish_did(mnemonic, log_content)` but committed in one fjall
    /// batch on the server, so resolvers never see the slot empty
    /// between allocation and content upload. The relevant flow for
    /// promoting an existing serverless DID to a host without a
    /// resolvability gap.
    ///
    /// `force` is honoured only when the caller is an admin replacing a
    /// slot owned by a different DID. The owner re-registering their
    /// own slot is idempotent and needs no force.
    ///
    /// `domain` follows the same resolution chain as `request_uri`.
    pub async fn register_did_atomic(
        &self,
        path: &str,
        did_log: &str,
        force: bool,
        domain: Option<&str>,
    ) -> Result<RequestUriResponse, AppError> {
        let url = format!("{}/api/dids/register", self.server_url);
        info!(method = "POST", %url, "webvh: sending via rest");
        let mut body = serde_json::Map::new();
        body.insert(
            "path".to_string(),
            serde_json::Value::String(path.to_string()),
        );
        // Send the canonical `didData` + `method` shape introduced by
        // the v0.1 did-management spec. The remote accepts the legacy
        // `did_log` shape too (T26 normalisation), but emitting the
        // canonical form keeps this client off the deprecation path.
        body.insert(
            "method".to_string(),
            serde_json::Value::String("webvh".to_string()),
        );
        body.insert(
            "didData".to_string(),
            serde_json::Value::String(did_log.to_string()),
        );
        body.insert("force".to_string(), serde_json::Value::Bool(force));
        if let Some(d) = domain {
            body.insert(
                "domain".to_string(),
                serde_json::Value::String(d.to_string()),
            );
        }
        let req = self
            .with_auth(self.http.post(&url))
            .json(&serde_json::Value::Object(body));
        let resp = self.send(req, "POST /api/dids/register").await?;
        resp.json()
            .await
            .map_err(|e| AppError::Internal(format!("webvh-server response parse error: {e}")))
    }

    /// PUT /api/dids/{mnemonic} — publish DID log.
    ///
    /// The `domain` argument is accepted for disambiguation on hosts
    /// that run per-domain mnemonic namespaces. Hosts with a flat
    /// namespace ignore it on lookup; a mismatched explicit domain is
    /// surfaced as `did-management:unknown_domain`.
    pub async fn publish_did(
        &self,
        mnemonic: &str,
        log_content: &str,
        domain: Option<&str>,
    ) -> Result<(), AppError> {
        let url = if let Some(d) = domain {
            format!(
                "{}/api/dids/{mnemonic}?domain={}",
                self.server_url,
                url::form_urlencoded::byte_serialize(d.as_bytes()).collect::<String>()
            )
        } else {
            format!("{}/api/dids/{mnemonic}", self.server_url)
        };
        info!(method = "PUT", %url, "webvh: sending via rest");
        let req = self
            .with_auth(self.http.put(&url))
            .header("Content-Type", "application/jsonl")
            .body(log_content.to_string());
        self.send(req, &format!("PUT /api/dids/{mnemonic}")).await?;
        Ok(())
    }

    /// DELETE /api/dids/{mnemonic}.
    pub async fn delete_did(&self, mnemonic: &str, domain: Option<&str>) -> Result<(), AppError> {
        let url = if let Some(d) = domain {
            format!(
                "{}/api/dids/{mnemonic}?domain={}",
                self.server_url,
                url::form_urlencoded::byte_serialize(d.as_bytes()).collect::<String>()
            )
        } else {
            format!("{}/api/dids/{mnemonic}", self.server_url)
        };
        info!(method = "DELETE", %url, "webvh: sending via rest");
        let req = self.with_auth(self.http.delete(&url));
        self.send(req, &format!("DELETE /api/dids/{mnemonic}"))
            .await?;
        Ok(())
    }

    /// POST /api/dids/check — check whether a path is available, with
    /// optional atomic reservation (v0.1 `did-management/did/check-name/0.1`
    /// `reserve` flag).
    pub async fn check_path(
        &self,
        path: &str,
        reserve: bool,
        domain: Option<&str>,
    ) -> Result<CheckPathResponse, AppError> {
        let url = format!("{}/api/dids/check", self.server_url);
        let mut body = serde_json::Map::new();
        body.insert(
            "path".to_string(),
            serde_json::Value::String(path.to_string()),
        );
        if reserve {
            body.insert("reserve".to_string(), serde_json::Value::Bool(true));
        }
        if let Some(d) = domain {
            body.insert(
                "domain".to_string(),
                serde_json::Value::String(d.to_string()),
            );
        }
        let req = self
            .with_auth(self.http.post(&url))
            .json(&serde_json::Value::Object(body));
        let resp = self.send(req, "POST /api/dids/check").await?;
        resp.json()
            .await
            .map_err(|e| AppError::Internal(format!("webvh-server response parse error: {e}")))
    }

    /// GET /api/me/domains — list the hosting domains the caller's
    /// ACL scope permits on this server. Read-only; used by the pnm
    /// CLI to discover legitimate `--domain` values before creating
    /// a DID.
    pub async fn list_my_domains(&self) -> Result<MyDomainsResponse, AppError> {
        let url = format!("{}/api/me/domains", self.server_url);
        info!(method = "GET", %url, "webvh: sending via rest");
        let req = self.with_auth(self.http.get(&url));
        let resp = self.send(req, "GET /api/me/domains").await?;
        resp.json()
            .await
            .map_err(|e| AppError::Internal(format!("webvh-server response parse error: {e}")))
    }
}

#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MyDomainsResponse {
    pub domains: Vec<MyDomainEntry>,
    pub default: Option<String>,
}

#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MyDomainEntry {
    pub name: String,
    #[serde(default)]
    pub default_domain: bool,
    #[serde(default)]
    pub status: String,
    #[serde(default)]
    pub label: Option<String>,
}

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

    fn assert_validation_err(result: Result<WebvhClient, AppError>, needle: &str) {
        match result {
            Err(AppError::Validation(msg)) => assert!(
                msg.contains(needle),
                "expected validation error to contain `{needle}`, got: {msg}"
            ),
            Err(other) => panic!("expected Validation error, got {other:?}"),
            Ok(_) => panic!("expected Validation error, got Ok"),
        }
    }

    #[test]
    fn https_url_is_accepted() {
        // Standard production case — DID advertises an https endpoint.
        let c = WebvhClient::new("https://daemon.example", "did:web:daemon.example")
            .expect("https must be accepted");
        assert_eq!(c.server_url, "https://daemon.example");
    }

    #[test]
    fn https_url_trailing_slash_is_normalised() {
        // Match the existing trim_end_matches('/') behaviour so callers
        // can format paths with a leading slash without producing `//`.
        let c = WebvhClient::new("https://daemon.example/", "did:web:daemon.example").unwrap();
        assert_eq!(c.server_url, "https://daemon.example");
    }

    #[test]
    fn http_to_non_loopback_is_rejected() {
        // The core invariant: bearer tokens and the signed JWS must
        // not be sent over plaintext to a network-reachable host.
        assert_validation_err(
            WebvhClient::new("http://daemon.example", "did:web:daemon.example"),
            "refusing to dial webvh-server",
        );
    }

    #[test]
    fn http_to_localhost_is_accepted_for_dev() {
        // Local-dev escape hatch — operator's daemon on the same host.
        let c = WebvhClient::new("http://localhost:8530", "did:web:daemon.example").unwrap();
        assert_eq!(c.server_url, "http://localhost:8530");
    }

    #[test]
    fn http_to_127_0_0_1_is_accepted() {
        let c = WebvhClient::new("http://127.0.0.1:8530", "did:web:daemon.example").unwrap();
        assert_eq!(c.server_url, "http://127.0.0.1:8530");
    }

    #[test]
    fn http_to_127_0_0_x_subnet_is_accepted() {
        // We use the IPv4 `is_loopback()` predicate, which covers all
        // of `127.0.0.0/8` — including dev shims like 127.0.0.2 that
        // operators use to bind multiple local services.
        let c = WebvhClient::new("http://127.0.0.5:8530", "did:web:daemon.example").unwrap();
        assert_eq!(c.server_url, "http://127.0.0.5:8530");
    }

    #[test]
    fn http_to_ipv6_loopback_is_accepted() {
        let c = WebvhClient::new("http://[::1]:8530", "did:web:daemon.example").unwrap();
        // The url crate normalises bracketed IPv6 in display form.
        assert!(c.server_url.contains("::1"));
    }

    #[test]
    fn http_to_0_0_0_0_is_rejected() {
        // 0.0.0.0 is a listen-on-all address. An operator dialing it
        // from the VTA host is technically loopback-equivalent, but
        // it's also the kind of typo that a misconfigured daemon DID
        // can introduce — fail loud rather than silently allow it.
        assert_validation_err(
            WebvhClient::new("http://0.0.0.0:8530", "did:web:daemon.example"),
            "refusing to dial webvh-server",
        );
    }

    #[test]
    fn ftp_scheme_is_rejected() {
        assert_validation_err(
            WebvhClient::new("ftp://daemon.example/", "did:web:daemon.example"),
            "unsupported scheme",
        );
    }

    #[test]
    fn ws_scheme_is_rejected() {
        // WebSocket isn't a wire we serve daemon REST over —
        // a daemon DID advertising ws:// is a misconfiguration.
        assert_validation_err(
            WebvhClient::new("ws://daemon.example/", "did:web:daemon.example"),
            "unsupported scheme",
        );
    }

    #[test]
    fn malformed_url_is_rejected() {
        assert_validation_err(
            WebvhClient::new("not-a-url", "did:web:daemon.example"),
            "invalid webvh-server URL",
        );
    }

    #[test]
    fn empty_url_is_rejected() {
        assert_validation_err(
            WebvhClient::new("", "did:web:daemon.example"),
            "invalid webvh-server URL",
        );
    }

    #[test]
    fn https_to_loopback_is_also_accepted() {
        // Operators running a TLS-terminating proxy locally
        // (mkcert + nginx, mitmproxy) should still work.
        let c = WebvhClient::new("https://localhost:8443", "did:web:daemon.example").unwrap();
        assert_eq!(c.server_url, "https://localhost:8443");
    }

    #[test]
    fn http_to_hostname_resembling_localhost_is_rejected() {
        // `localhost.evil.com` resolves wherever the attacker wants —
        // accept only the literal `localhost`, not anything ending in it.
        assert_validation_err(
            WebvhClient::new("http://localhost.evil.example", "did:web:daemon.example"),
            "refusing to dial webvh-server",
        );
    }

    // ── HTTP-flow tests against a wiremock daemon ──────────────────
    //
    // wiremock spins up a real local server bound to 127.0.0.1:<random>;
    // our HTTPS policy admits loopback HTTP so no insecure-test knob is
    // needed. Each test scopes its `MockServer` so the port is freed
    // between tests.

    use crate::webvh_auth::VtaSigningIdentity;
    use ed25519_dalek::SigningKey;
    use serde_json::json;
    use wiremock::matchers::{header, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn signing_identity() -> ([u8; 32], String, String) {
        let seed = [9u8; 32];
        let sk = SigningKey::from_bytes(&seed);
        let vta_did = "did:webvh:test:vta".to_string();
        let kid = format!("{vta_did}#key-0");
        (sk.to_bytes(), vta_did, kid)
    }

    fn token_response_json() -> serde_json::Value {
        // Daemon's wire shape (camelCase): wrapped in {sessionId, data}.
        json!({
            "sessionId": "auth-session-1",
            "data": {
                "accessToken": "access-token-A",
                "accessExpiresAt": 9_999_999_999u64,
                "refreshToken": "refresh-token-A",
                "refreshExpiresAt": 9_999_999_999u64,
            }
        })
    }

    fn challenge_response_json() -> serde_json::Value {
        json!({
            "sessionId": "chal-session-1",
            "data": { "challenge": "deadbeef" },
        })
    }

    #[tokio::test]
    async fn authenticate_round_trips_against_mock_daemon() {
        // Happy path: challenge → JWS authenticate → tokens.
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/auth/challenge"))
            .respond_with(ResponseTemplate::new(200).set_body_json(challenge_response_json()))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/auth/"))
            .and(header("Content-Type", "application/json"))
            // The JWS payload is base64url-encoded; we can't match on
            // its inner content here. The wire-shape correctness of
            // the JWS is verified by the unit tests in `webvh_auth`.
            .respond_with(ResponseTemplate::new(200).set_body_json(token_response_json()))
            .expect(1)
            .mount(&server)
            .await;

        let (private, vta_did, kid) = signing_identity();
        let client = WebvhClient::new(&server.uri(), "did:web:daemon-mock.example").unwrap();
        let identity = VtaSigningIdentity {
            vta_did: &vta_did,
            signing_kid: &kid,
            private_key: &private,
        };

        let tokens = client
            .authenticate(&identity)
            .await
            .expect("authenticate must succeed");
        assert_eq!(tokens.access_token, "access-token-A");
        assert_eq!(tokens.refresh_token, "refresh-token-A");
        assert_eq!(tokens.access_expires_at, 9_999_999_999);
    }

    #[tokio::test]
    async fn authenticate_401_surfaces_signature_freshness_hint() {
        // 401 from the daemon means signature/session/challenge
        // verification failed — typically clock skew, expired
        // challenge, or a kid that doesn't match a verification
        // method. The hint must NOT misdirect the operator toward
        // ACL edits (that's the 403 case below).
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/auth/challenge"))
            .respond_with(ResponseTemplate::new(200).set_body_json(challenge_response_json()))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/auth/"))
            .respond_with(ResponseTemplate::new(401).set_body_string("invalid signature"))
            .mount(&server)
            .await;

        let (private, vta_did, kid) = signing_identity();
        let client = WebvhClient::new(&server.uri(), "did:web:daemon-mock.example").unwrap();
        let identity = VtaSigningIdentity {
            vta_did: &vta_did,
            signing_kid: &kid,
            private_key: &private,
        };

        let err = client.authenticate(&identity).await.unwrap_err();
        match err {
            AppError::Authentication(msg) => {
                assert!(
                    msg.contains("clock skew") || msg.contains("expired challenge"),
                    "401 must hint at signature/freshness failures, not ACL: {msg}"
                );
                assert!(
                    !msg.contains("not in the daemon's ACL"),
                    "401 must NOT suggest ACL change (that's the 403 case): {msg}"
                );
            }
            other => panic!("expected Authentication, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn authenticate_403_surfaces_acl_hint() {
        // 403 from the daemon means signature was valid but the VTA
        // DID is not in the ACL. The CLI must direct the operator
        // toward the daemon-side fix (grant ACL access), not toward
        // re-checking signatures.
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/auth/challenge"))
            .respond_with(ResponseTemplate::new(200).set_body_json(challenge_response_json()))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/auth/"))
            .respond_with(ResponseTemplate::new(403).set_body_string("DID not in ACL"))
            .mount(&server)
            .await;

        let (private, vta_did, kid) = signing_identity();
        let client = WebvhClient::new(&server.uri(), "did:web:daemon-mock.example").unwrap();
        let identity = VtaSigningIdentity {
            vta_did: &vta_did,
            signing_kid: &kid,
            private_key: &private,
        };

        let err = client.authenticate(&identity).await.unwrap_err();
        match err {
            AppError::Forbidden(msg) => {
                assert!(
                    msg.contains("not in the daemon's ACL"),
                    "403 must surface the ACL hint: {msg}"
                );
                assert!(msg.contains(&vta_did), "should name the VTA DID: {msg}");
                assert!(
                    msg.contains("daemon-side"),
                    "should point at the daemon as the fix location: {msg}"
                );
            }
            other => panic!("expected Forbidden, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn authenticate_500_yields_internal_not_auth_error() {
        // A 5xx is a daemon-side problem, not an auth problem — must
        // not look like "ACL needs updating."
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/auth/challenge"))
            .respond_with(ResponseTemplate::new(200).set_body_json(challenge_response_json()))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/auth/"))
            .respond_with(ResponseTemplate::new(503).set_body_string("upstream down"))
            .mount(&server)
            .await;

        let (private, vta_did, kid) = signing_identity();
        let client = WebvhClient::new(&server.uri(), "did:web:daemon-mock.example").unwrap();
        let identity = VtaSigningIdentity {
            vta_did: &vta_did,
            signing_kid: &kid,
            private_key: &private,
        };

        let err = client.authenticate(&identity).await.unwrap_err();
        assert!(
            matches!(err, AppError::Internal(_)),
            "5xx should map to Internal, got: {err:?}"
        );
    }

    #[tokio::test]
    async fn refresh_returns_rotated_tokens() {
        // The daemon rotates the refresh token on use. The returned
        // refresh_token must be the daemon's new value, not echoed
        // from the input.
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/auth/refresh"))
            .and(header("Content-Type", "application/json"))
            // The old refresh token rides inside the JWS body; we
            // can't match on encoded contents from a wiremock matcher.
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "sessionId": "refreshed-session",
                "data": {
                    "accessToken": "new-access",
                    "accessExpiresAt": 1_900_000_000u64,
                    "refreshToken": "rotated-refresh",
                    "refreshExpiresAt": 1_900_999_999u64,
                }
            })))
            .expect(1)
            .mount(&server)
            .await;

        let (private, vta_did, kid) = signing_identity();
        let client = WebvhClient::new(&server.uri(), "did:web:daemon-mock.example").unwrap();
        let identity = VtaSigningIdentity {
            vta_did: &vta_did,
            signing_kid: &kid,
            private_key: &private,
        };

        let tokens = client
            .refresh(&identity, "old-refresh")
            .await
            .expect("refresh must succeed");
        assert_eq!(tokens.access_token, "new-access");
        assert_eq!(
            tokens.refresh_token, "rotated-refresh",
            "refresh must return rotated token, not echo input"
        );
    }

    #[tokio::test]
    async fn refresh_failure_yields_typed_authentication_error() {
        // End-of-lifetime case: refresh token expired or replayed.
        // Callers fall back to full re-auth; the typed variant tells
        // them to.
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/auth/refresh"))
            .respond_with(ResponseTemplate::new(401).set_body_string("invalid refresh token"))
            .mount(&server)
            .await;

        let (private, vta_did, kid) = signing_identity();
        let client = WebvhClient::new(&server.uri(), "did:web:daemon-mock.example").unwrap();
        let identity = VtaSigningIdentity {
            vta_did: &vta_did,
            signing_kid: &kid,
            private_key: &private,
        };
        let err = client
            .refresh(&identity, "stale-refresh")
            .await
            .unwrap_err();
        assert!(
            matches!(err, AppError::Authentication(_)),
            "expired refresh must map to Authentication, got: {err:?}"
        );
    }

    #[test]
    fn token_data_debug_redacts_secret_fields() {
        // Same protection as `WebvhServerAuthRecord` — accidental
        // `tracing::error!(?tokens)` must not log the access or
        // refresh token bytes. Expiry timestamps stay visible (not
        // secret, useful for freshness diagnostics).
        let td = TokenData {
            access_token: "should-not-appear-XXXX".into(),
            access_expires_at: 1234,
            refresh_token: "also-secret-YYYY".into(),
            refresh_expires_at: 5678,
        };
        let dbg = format!("{td:?}");
        assert!(!dbg.contains("XXXX"), "access_token must not leak: {dbg}");
        assert!(!dbg.contains("YYYY"), "refresh_token must not leak: {dbg}");
        assert!(dbg.contains("<redacted>"));
        assert!(dbg.contains("1234"));
        assert!(dbg.contains("5678"));
    }

    #[tokio::test]
    async fn authenticate_uses_camelcase_sessionid_from_daemon() {
        // The daemon's `ChallengeResponse` has
        // `#[serde(rename_all = "camelCase")]` so the wire field is
        // `sessionId`. Regression guard: a future tweak that switched
        // our deserializer to snake_case-only would silently break
        // the auth handshake.
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/auth/challenge"))
            // Note: explicit camelCase `sessionId`, not snake_case.
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "sessionId": "camel-id",
                "data": { "challenge": "cafebabe" }
            })))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/auth/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(token_response_json()))
            .mount(&server)
            .await;

        let (private, vta_did, kid) = signing_identity();
        let client = WebvhClient::new(&server.uri(), "did:web:daemon-mock.example").unwrap();
        let identity = VtaSigningIdentity {
            vta_did: &vta_did,
            signing_kid: &kid,
            private_key: &private,
        };
        let _ = client
            .authenticate(&identity)
            .await
            .expect("must accept camelCase sessionId");
    }
}