vta-service 0.3.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
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
//! Integration tests for the VTA REST API.
//!
//! Spins up the axum router with a temp fjall store and tests endpoints
//! with real HTTP requests. JWT tokens are created programmatically and
//! sessions are pre-inserted to bypass the DIDComm challenge-response flow.

use std::sync::Arc;

use axum::body::Body;
use axum::http::{Request, StatusCode};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64;
use http_body_util::BodyExt;
use serde_json::{Value, json};
use tokio::sync::{RwLock, watch};
use tower::ServiceExt;

use vti_common::acl::Role;
use vti_common::auth::jwt::JwtKeys;
use vti_common::auth::session::{Session, SessionState, store_session};
use vti_common::config::StoreConfig;
use vti_common::store::Store;

use vta_service::config::AppConfig;
use vta_service::routes;
use vta_service::server::AppState;
use vta_service::store::KeyspaceHandle;

// ── Test harness ───────────────────────────────────────────────────

struct TestApp {
    router: axum::Router,
}

impl TestApp {
    async fn new() -> (Self, TestContext) {
        let dir = tempfile::tempdir().expect("temp dir");
        let store_config = StoreConfig {
            data_dir: dir.path().to_path_buf(),
        };
        let store = Store::open(&store_config).expect("open store");

        let keys_ks = store.keyspace("keys").unwrap();
        let sessions_ks = store.keyspace("sessions").unwrap();
        let acl_ks = store.keyspace("acl").unwrap();
        let contexts_ks = store.keyspace("contexts").unwrap();
        let audit_ks = store.keyspace("audit").unwrap();
        let cache_ks = store.keyspace("cache").unwrap();
        #[cfg(feature = "webvh")]
        let webvh_ks = store.keyspace("webvh").unwrap();

        let jwt_seed = [0x42u8; 32];
        let jwt_keys = Arc::new(JwtKeys::from_ed25519_bytes(&jwt_seed, "VTA").expect("jwt keys"));

        let seed_store: Arc<dyn vta_service::keys::seed_store::SeedStore> =
            Arc::new(TestSeedStore(vec![0xABu8; 32]));

        let mut config: AppConfig = toml::from_str(&format!(
            r#"
            vta_did = "did:key:z6MkTestVTA"
            [store]
            data_dir = "{}"
            [auth]
            jwt_signing_key = "{}"
            "#,
            dir.path().display(),
            BASE64.encode(&jwt_seed),
        ))
        .expect("parse config");
        // Set config_path to a writable location so update_config can persist
        config.config_path = dir.path().join("config.toml");

        let (restart_tx, _rx) = watch::channel(false);

        let imported_ks = store.keyspace("imported_secrets").unwrap();
        let state = AppState {
            keys_ks: keys_ks.clone(),
            sessions_ks: sessions_ks.clone(),
            acl_ks: acl_ks.clone(),
            contexts_ks,
            audit_ks: audit_ks.clone(),
            imported_ks,
            cache_ks,
            #[cfg(feature = "webvh")]
            webvh_ks,
            wrapping_cache: vta_service::keys::wrapping::WrappingKeyCache::new(),
            config: Arc::new(RwLock::new(config)),
            seed_store,
            did_resolver: None,
            secrets_resolver: None,
            #[cfg(feature = "didcomm")]
            didcomm_bridge: Arc::new(tokio::sync::RwLock::new(None)),
            jwt_keys: Some(jwt_keys.clone()),
            atm: None,
            tee: None,
            restart_tx,
            metrics_handle: None,
        };

        let router = routes::router()
            .with_state(state.clone())
            .merge(routes::health_router().with_state(state));

        let ctx = TestContext {
            jwt_keys,
            sessions_ks,
            acl_ks,
            _dir: dir,
        };

        (Self { router }, ctx)
    }

    async fn request(&self, req: Request<Body>) -> (StatusCode, Value) {
        let resp = self
            .router
            .clone()
            .oneshot(req)
            .await
            .expect("request failed");
        let status = resp.status();
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: Value = serde_json::from_slice(&body)
            .unwrap_or_else(|_| json!({"raw": String::from_utf8_lossy(&body).to_string()}));
        (status, json)
    }
}

struct TestContext {
    jwt_keys: Arc<JwtKeys>,
    sessions_ks: KeyspaceHandle,
    acl_ks: KeyspaceHandle,
    _dir: tempfile::TempDir,
}

impl TestContext {
    /// Create an authenticated session and return a Bearer token.
    async fn auth_token(&self, did: &str, role: &str, contexts: Vec<String>) -> String {
        let session_id = format!("sess-{}", uuid::Uuid::new_v4());
        let session = Session {
            session_id: session_id.clone(),
            did: did.to_string(),
            challenge: String::new(),
            state: SessionState::Authenticated,
            created_at: now_epoch(),
            refresh_token: None,
            refresh_expires_at: None,
        };
        store_session(&self.sessions_ks, &session)
            .await
            .expect("store session");

        let claims = self.jwt_keys.new_claims(
            did.to_string(),
            session_id,
            role.to_string(),
            contexts,
            900,
            false,
        );
        self.jwt_keys.encode(&claims).expect("encode jwt")
    }

    /// Create an ACL entry for a DID.
    async fn create_acl(&self, did: &str, role: Role, contexts: Vec<String>) {
        let entry = vti_common::acl::AclEntry {
            did: did.to_string(),
            role,
            label: None,
            allowed_contexts: contexts,
            created_at: now_epoch(),
            created_by: "test".to_string(),
        };
        self.acl_ks
            .insert(format!("acl:{did}"), &entry)
            .await
            .expect("insert acl");
    }
}

/// Minimal seed store for tests.
struct TestSeedStore(Vec<u8>);

impl vta_service::keys::seed_store::SeedStore for TestSeedStore {
    fn get(
        &self,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<Output = Result<Option<Vec<u8>>, vti_common::error::AppError>>
                + Send
                + '_,
        >,
    > {
        let seed = self.0.clone();
        Box::pin(async move { Ok(Some(seed)) })
    }
    fn set(
        &self,
        _seed: &[u8],
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = Result<(), vti_common::error::AppError>> + Send + '_>,
    > {
        Box::pin(async { Ok(()) })
    }
}

fn now_epoch() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
}

fn get(uri: &str) -> Request<Body> {
    Request::builder()
        .method("GET")
        .uri(uri)
        .body(Body::empty())
        .unwrap()
}

fn get_auth(uri: &str, token: &str) -> Request<Body> {
    Request::builder()
        .method("GET")
        .uri(uri)
        .header("Authorization", format!("Bearer {token}"))
        .body(Body::empty())
        .unwrap()
}

fn post_auth(uri: &str, token: &str, body: Value) -> Request<Body> {
    Request::builder()
        .method("POST")
        .uri(uri)
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/json")
        .body(Body::from(serde_json::to_vec(&body).unwrap()))
        .unwrap()
}

fn patch_auth(uri: &str, token: &str, body: Value) -> Request<Body> {
    Request::builder()
        .method("PATCH")
        .uri(uri)
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/json")
        .body(Body::from(serde_json::to_vec(&body).unwrap()))
        .unwrap()
}

fn put_auth(uri: &str, token: &str, body: Value) -> Request<Body> {
    Request::builder()
        .method("PUT")
        .uri(uri)
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/json")
        .body(Body::from(serde_json::to_vec(&body).unwrap()))
        .unwrap()
}

fn delete_auth(uri: &str, token: &str) -> Request<Body> {
    Request::builder()
        .method("DELETE")
        .uri(uri)
        .header("Authorization", format!("Bearer {token}"))
        .body(Body::empty())
        .unwrap()
}

// ── Health ─────────────────────────────────────────────────────────

#[tokio::test]
async fn health_returns_ok_without_auth() {
    let (app, _ctx) = TestApp::new().await;
    let (status, body) = app.request(get("/health")).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["status"], "ok");
}

#[tokio::test]
async fn health_details_requires_auth() {
    let (app, _ctx) = TestApp::new().await;
    let (status, _) = app.request(get("/health/details")).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn health_details_returns_version_with_auth() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkTest", "admin", vec![]).await;
    let (status, body) = app.request(get_auth("/health/details", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["status"], "ok");
    assert!(body["version"].is_string());
}

// ── Auth: missing/invalid token ────────────────────────────────────

#[tokio::test]
async fn missing_token_returns_401() {
    let (app, _ctx) = TestApp::new().await;
    let (status, _) = app.request(get("/config")).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn invalid_token_returns_401() {
    let (app, _ctx) = TestApp::new().await;
    let (status, _) = app.request(get_auth("/config", "not-a-jwt")).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn expired_session_returns_401() {
    let (app, ctx) = TestApp::new().await;
    // Create a token with a valid JWT but no session in the store
    let claims = ctx.jwt_keys.new_claims(
        "did:key:z6MkGhost".into(),
        "nonexistent-session".into(),
        "admin".into(),
        vec![],
        900,
        false,
    );
    let token = ctx.jwt_keys.encode(&claims).unwrap();
    let (status, _) = app.request(get_auth("/config", &token)).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

// ── Role enforcement ───────────────────────────────────────────────

#[tokio::test]
async fn application_role_cannot_access_admin_endpoints() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx
        .auth_token("did:key:z6MkApp", "application", vec!["ctx1".into()])
        .await;
    // POST /keys requires admin
    let (status, _) = app
        .request(post_auth(
            "/keys",
            &token,
            json!({"key_type": "ed25519", "context_id": "ctx1"}),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn initiator_cannot_access_super_admin_endpoints() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx
        .auth_token("did:key:z6MkInit", "initiator", vec![])
        .await;
    // PATCH /config requires super admin
    let (status, _) = app
        .request(patch_auth("/config", &token, json!({"vta_name": "hacked"})))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn admin_can_read_config() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;
    let (status, body) = app.request(get_auth("/config", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["vta_did"], "did:key:z6MkTestVTA");
}

#[tokio::test]
async fn super_admin_can_update_config() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    let (status, body) = app
        .request(patch_auth(
            "/config",
            &token,
            json!({"vta_name": "Updated Name"}),
        ))
        .await;
    assert!(status.is_success(), "update config: {status} {body}");
    assert_eq!(body["vta_name"], "Updated Name");
}

#[tokio::test]
async fn scoped_admin_cannot_update_config() {
    let (app, ctx) = TestApp::new().await;
    // Admin with allowed_contexts is NOT super admin
    let token = ctx
        .auth_token("did:key:z6MkScoped", "admin", vec!["ctx1".into()])
        .await;
    let (status, _) = app
        .request(patch_auth("/config", &token, json!({"vta_name": "nope"})))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ── ACL CRUD ───────────────────────────────────────────────────────

#[tokio::test]
async fn acl_create_and_list() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // Create
    let (status, body) = app
        .request(post_auth(
            "/acl",
            &token,
            json!({
                "did": "did:key:z6MkNew",
                "role": "application",
                "label": "test app",
                "allowed_contexts": ["ctx1"]
            }),
        ))
        .await;
    assert!(status.is_success(), "create: {body}");

    // List
    let (status, body) = app.request(get_auth("/acl", &token)).await;
    assert_eq!(status, StatusCode::OK);
    let entries = body["entries"].as_array().expect("entries array");
    assert!(
        entries.iter().any(|e| e["did"] == "did:key:z6MkNew"),
        "new entry should be in list"
    );
}

#[tokio::test]
async fn acl_application_cannot_manage() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx
        .auth_token("did:key:z6MkApp", "application", vec!["ctx1".into()])
        .await;
    let (status, _) = app.request(get_auth("/acl", &token)).await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ── Context CRUD ───────────────────────────────────────────────────

#[tokio::test]
async fn context_create_requires_super_admin() {
    let (app, ctx) = TestApp::new().await;

    // Scoped admin → forbidden
    let token = ctx
        .auth_token("did:key:z6MkScoped", "admin", vec!["ctx1".into()])
        .await;
    let (status, _) = app
        .request(post_auth(
            "/contexts",
            &token,
            json!({"id": "new-ctx", "name": "New Context"}),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);

    // Super admin → OK
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    let (status, body) = app
        .request(post_auth(
            "/contexts",
            &token,
            json!({"id": "new-ctx", "name": "New Context"}),
        ))
        .await;
    assert!(status.is_success(), "create: {body}");
}

// ── Key management ─────────────────────────────────────────────────

#[tokio::test]
async fn key_create_and_list() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // Create a context first (needed for key creation)
    let (status, _) = app
        .request(post_auth(
            "/contexts",
            &token,
            json!({"id": "test", "name": "Test Context"}),
        ))
        .await;
    assert!(status.is_success());

    // Create key
    let (status, body) = app
        .request(post_auth(
            "/keys",
            &token,
            json!({"key_type": "ed25519", "context_id": "test"}),
        ))
        .await;
    assert!(status.is_success(), "create key: {body}");
    assert!(body["key_id"].is_string());
    assert_eq!(body["key_type"], "ed25519");

    // List keys
    let (status, body) = app.request(get_auth("/keys", &token)).await;
    assert_eq!(status, StatusCode::OK);
    let keys = body["keys"].as_array().expect("keys array");
    assert!(!keys.is_empty(), "should have at least one key");
}

// ── Restart requires super admin ───────────────────────────────────

#[tokio::test]
async fn restart_requires_super_admin() {
    let (app, ctx) = TestApp::new().await;

    // Regular admin with contexts → forbidden
    let token = ctx
        .auth_token("did:key:z6MkScoped", "admin", vec!["ctx1".into()])
        .await;
    let (status, _) = app
        .request(post_auth("/vta/restart", &token, json!({})))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);

    // Initiator → forbidden
    let token = ctx
        .auth_token("did:key:z6MkInit", "initiator", vec![])
        .await;
    let (status, _) = app
        .request(post_auth("/vta/restart", &token, json!({})))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ── Backup requires super admin ────────────────────────────────────

#[tokio::test]
async fn backup_export_requires_super_admin() {
    let (app, ctx) = TestApp::new().await;

    // Scoped admin → forbidden
    let token = ctx
        .auth_token("did:key:z6MkScoped", "admin", vec!["ctx1".into()])
        .await;
    let (status, _) = app
        .request(post_auth(
            "/backup/export",
            &token,
            json!({"password": "test-password-12!!", "include_audit": false}),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn backup_export_rejects_short_password() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    let (status, body) = app
        .request(post_auth(
            "/backup/export",
            &token,
            json!({"password": "short", "include_audit": false}),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::BAD_REQUEST,
        "should reject short password: {body}"
    );
}

#[tokio::test]
async fn backup_export_and_import_preview() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    // Export
    let (status, envelope) = app
        .request(post_auth(
            "/backup/export",
            &token,
            json!({"password": "test-password-12!!", "include_audit": false}),
        ))
        .await;
    assert_eq!(status, StatusCode::OK, "export: {envelope}");
    assert_eq!(envelope["format"], "vta-backup-v1");

    // Import preview (confirm=false)
    let (status, preview) = app
        .request(post_auth(
            "/backup/import",
            &token,
            json!({
                "backup": envelope,
                "password": "test-password-12!!",
                "confirm": false
            }),
        ))
        .await;
    assert_eq!(status, StatusCode::OK, "preview: {preview}");
    assert_eq!(preview["status"], "preview");
}

// ── Cache ──────────────────────────────────────────────────────────

#[tokio::test]
async fn cache_put_get_delete() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // PUT
    let req = Request::builder()
        .method("PUT")
        .uri("/cache/test-key")
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/json")
        .body(Body::from(r#"{"value":"hello","ttl_secs":60}"#))
        .unwrap();
    let (status, _) = app.request(req).await;
    assert!(status.is_success(), "PUT cache: {status}");

    // GET
    let (status, body) = app.request(get_auth("/cache/test-key", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["value"], "hello");

    // DELETE
    let (status, _) = app.request(delete_auth("/cache/test-key", &token)).await;
    assert!(status.is_success(), "DELETE cache: {status}");

    // GET again → 404
    let (status, _) = app.request(get_auth("/cache/test-key", &token)).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

// ── Audit ──────────────────────────────────────────────────────────

#[tokio::test]
async fn audit_list_requires_admin() {
    let (app, ctx) = TestApp::new().await;

    // Application → forbidden
    let token = ctx
        .auth_token("did:key:z6MkApp", "application", vec!["ctx1".into()])
        .await;
    let (status, _) = app.request(get_auth("/audit/logs", &token)).await;
    assert_eq!(status, StatusCode::FORBIDDEN);

    // Admin → OK
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;
    let (status, body) = app.request(get_auth("/audit/logs", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert!(body["entries"].is_array());
}

// ── Context scoping ────────────────────────────────────────────────

#[tokio::test]
async fn scoped_admin_can_only_access_own_context_keys() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    // Create two contexts
    app.request(post_auth(
        "/contexts",
        &super_token,
        json!({"id": "ctx-a", "name": "A"}),
    ))
    .await;
    app.request(post_auth(
        "/contexts",
        &super_token,
        json!({"id": "ctx-b", "name": "B"}),
    ))
    .await;

    // Create a key in ctx-a
    let (status, key_body) = app
        .request(post_auth(
            "/keys",
            &super_token,
            json!({"key_type": "ed25519", "context_id": "ctx-a"}),
        ))
        .await;
    assert!(status.is_success());
    let key_id = key_body["key_id"].as_str().unwrap();

    // Scoped admin for ctx-b cannot get the key in ctx-a (returns 403 or 404 — both are valid)
    let encoded_id = urlencoding::encode(key_id);
    let scoped_b_token = ctx
        .auth_token("did:key:z6MkB", "admin", vec!["ctx-b".into()])
        .await;
    let (status, _) = app
        .request(get_auth(&format!("/keys/{encoded_id}"), &scoped_b_token))
        .await;
    assert!(
        status == StatusCode::FORBIDDEN || status == StatusCode::NOT_FOUND,
        "scoped admin should not access other context's key, got {status}"
    );

    // Scoped admin for ctx-a CAN get the key
    let scoped_a_token = ctx
        .auth_token("did:key:z6MkA", "admin", vec!["ctx-a".into()])
        .await;
    let (status, body) = app
        .request(get_auth(&format!("/keys/{encoded_id}"), &scoped_a_token))
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["key_id"], key_id);
}

// ── Key lifecycle ──────────────────────────────────────────────────

#[tokio::test]
async fn key_create_revoke_list_lifecycle() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // Create context + key
    app.request(post_auth(
        "/contexts",
        &token,
        json!({"id": "lc", "name": "Lifecycle"}),
    ))
    .await;
    let (_, key_body) = app
        .request(post_auth(
            "/keys",
            &token,
            json!({"key_type": "ed25519", "context_id": "lc"}),
        ))
        .await;
    let key_id = key_body["key_id"].as_str().unwrap();
    assert_eq!(key_body["status"], "active");

    // Revoke the key (key_id may contain slashes from derivation path, URL-encode it)
    let encoded_id = urlencoding::encode(key_id);
    let (status, body) = app
        .request(delete_auth(&format!("/keys/{encoded_id}"), &token))
        .await;
    assert!(status.is_success(), "revoke: {status} {body}");

    // Get key — should show revoked status
    let (status, body) = app
        .request(get_auth(&format!("/keys/{encoded_id}"), &token))
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["status"], "revoked");
}

#[tokio::test]
async fn key_rename() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    app.request(post_auth(
        "/contexts",
        &token,
        json!({"id": "rn", "name": "Rename"}),
    ))
    .await;
    let (_, key_body) = app
        .request(post_auth(
            "/keys",
            &token,
            json!({"key_type": "ed25519", "context_id": "rn", "label": "original"}),
        ))
        .await;
    let key_id = key_body["key_id"].as_str().unwrap();

    // Rename the key (PATCH expects new key_id in body)
    let encoded_id = urlencoding::encode(key_id);
    let (status, body) = app
        .request(patch_auth(
            &format!("/keys/{encoded_id}"),
            &token,
            json!({"key_id": "renamed-key"}),
        ))
        .await;
    assert!(status.is_success(), "rename: {status} {body}");
    assert_eq!(body["key_id"], "renamed-key");
}

// ── Seed management ────────────────────────────────────────────────

#[tokio::test]
async fn seed_list_returns_seeds() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;
    let (status, body) = app.request(get_auth("/keys/seeds", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert!(body["seeds"].is_array());
}

// ── Audit entries created by operations ────────────────────────────

#[tokio::test]
async fn operations_create_audit_entries() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // Perform some operations that create audit entries
    app.request(post_auth(
        "/contexts",
        &token,
        json!({"id": "aud", "name": "Audit Test"}),
    ))
    .await;
    app.request(post_auth(
        "/keys",
        &token,
        json!({"key_type": "ed25519", "context_id": "aud"}),
    ))
    .await;

    // Check audit logs contain entries
    let (status, body) = app.request(get_auth("/audit/logs", &token)).await;
    assert_eq!(status, StatusCode::OK);
    let entries = body["entries"].as_array().expect("entries");
    assert!(
        !entries.is_empty(),
        "should have at least 1 audit entry, got {}",
        entries.len()
    );

    // Verify audit entries have expected fields
    let entry = &entries[0];
    assert!(entry["id"].is_string());
    assert!(entry["timestamp"].is_number());
    assert!(entry["action"].is_string());
    assert!(entry["actor"].is_string());
}

// ── Audit retention ────────────────────────────────────────────────

#[tokio::test]
async fn audit_retention_get_and_update() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // Get current retention
    let (status, body) = app.request(get_auth("/audit/retention", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert!(body["retention_days"].is_number());

    // Update retention
    let (status, body) = app
        .request(patch_auth(
            "/audit/retention",
            &token,
            json!({"retention_days": 90}),
        ))
        .await;
    assert!(status.is_success(), "update retention: {status} {body}");
}

// ── Backup wrong password ──────────────────────────────────────────

#[tokio::test]
async fn backup_import_wrong_password_returns_auth_error() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    // Export with one password
    let (status, envelope) = app
        .request(post_auth(
            "/backup/export",
            &token,
            json!({"password": "correct-password!!", "include_audit": false}),
        ))
        .await;
    assert_eq!(status, StatusCode::OK);

    // Import with wrong password
    let (status, body) = app
        .request(post_auth(
            "/backup/import",
            &token,
            json!({"backup": envelope, "password": "wrong-password!!!", "confirm": false}),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::UNAUTHORIZED,
        "wrong password should → 401: {body}"
    );
}

// ── ACL CRUD full lifecycle ────────────────────────────────────────

#[tokio::test]
async fn acl_get_update_delete_lifecycle() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // Create
    app.request(post_auth(
        "/acl",
        &token,
        json!({
            "did": "did:key:z6MkTarget",
            "role": "application",
            "label": "test",
            "allowed_contexts": ["ctx1"]
        }),
    ))
    .await;

    // Get
    let (status, body) = app
        .request(get_auth("/acl/did:key:z6MkTarget", &token))
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["role"], "application");

    // Update
    let (status, body) = app
        .request(patch_auth(
            "/acl/did:key:z6MkTarget",
            &token,
            json!({"role": "initiator", "label": "updated"}),
        ))
        .await;
    assert!(status.is_success(), "update: {status} {body}");
    assert_eq!(body["role"], "initiator");

    // Delete
    let (status, _) = app
        .request(delete_auth("/acl/did:key:z6MkTarget", &token))
        .await;
    assert!(status.is_success());

    // Verify deleted
    let (status, _) = app
        .request(get_auth("/acl/did:key:z6MkTarget", &token))
        .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

// ── Context lifecycle ──────────────────────────────────────────────

#[tokio::test]
async fn context_create_get_update_delete() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    // Create
    let (status, _) = app
        .request(post_auth(
            "/contexts",
            &token,
            json!({"id": "lifecycle", "name": "Test", "description": "A test context"}),
        ))
        .await;
    assert!(status.is_success());

    // Get
    let (status, body) = app.request(get_auth("/contexts/lifecycle", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["name"], "Test");
    assert_eq!(body["description"], "A test context");

    // Update
    let (status, body) = app
        .request(patch_auth(
            "/contexts/lifecycle",
            &token,
            json!({"name": "Updated"}),
        ))
        .await;
    assert!(status.is_success(), "update: {status} {body}");
    assert_eq!(body["name"], "Updated");

    // List
    let (status, body) = app.request(get_auth("/contexts", &token)).await;
    assert_eq!(status, StatusCode::OK);
    let contexts = body["contexts"].as_array().expect("contexts");
    assert!(contexts.iter().any(|c| c["id"] == "lifecycle"));

    // Delete
    let (status, _) = app
        .request(delete_auth("/contexts/lifecycle", &token))
        .await;
    assert!(status.is_success());
}

// ── Multiple key types ─────────────────────────────────────────────

#[tokio::test]
async fn create_p256_key() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    app.request(post_auth(
        "/contexts",
        &token,
        json!({"id": "p256", "name": "P256 Test"}),
    ))
    .await;

    let (status, body) = app
        .request(post_auth(
            "/keys",
            &token,
            json!({"key_type": "p256", "context_id": "p256"}),
        ))
        .await;
    assert!(status.is_success(), "create p256: {status} {body}");
    assert_eq!(body["key_type"], "p256");
    assert!(body["public_key"].is_string());
}

// ── Context DID update (context admin) ────────────────────────────

#[tokio::test]
async fn context_admin_can_update_own_context_did() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // Create a context as super admin
    let (status, _) = app
        .request(post_auth(
            "/contexts",
            &super_token,
            json!({"id": "myctx", "name": "My Context"}),
        ))
        .await;
    assert!(status.is_success());

    // Context-scoped admin can update DID on their own context
    let scoped_token = ctx
        .auth_token("did:key:z6MkScoped", "admin", vec!["myctx".into()])
        .await;
    let (status, body) = app
        .request(put_auth(
            "/contexts/myctx/did",
            &scoped_token,
            json!({"did": "did:webvh:abc:example.com"}),
        ))
        .await;
    assert!(status.is_success(), "update did: {status} {body}");
    assert_eq!(body["did"], "did:webvh:abc:example.com");
}

#[tokio::test]
async fn context_admin_cannot_update_other_context_did() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // Create two contexts
    app.request(post_auth(
        "/contexts",
        &super_token,
        json!({"id": "ctx-a", "name": "A"}),
    ))
    .await;
    app.request(post_auth(
        "/contexts",
        &super_token,
        json!({"id": "ctx-b", "name": "B"}),
    ))
    .await;

    // Admin scoped to ctx-a cannot update ctx-b's DID
    let scoped_token = ctx
        .auth_token("did:key:z6MkScopedA", "admin", vec!["ctx-a".into()])
        .await;
    let (status, _) = app
        .request(put_auth(
            "/contexts/ctx-b/did",
            &scoped_token,
            json!({"did": "did:webvh:nope:example.com"}),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn super_admin_can_update_any_context_did() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    app.request(post_auth(
        "/contexts",
        &token,
        json!({"id": "anyctx", "name": "Any"}),
    ))
    .await;

    let (status, body) = app
        .request(put_auth(
            "/contexts/anyctx/did",
            &token,
            json!({"did": "did:webvh:xyz:example.com"}),
        ))
        .await;
    assert!(
        status.is_success(),
        "super admin update did: {status} {body}"
    );
    assert_eq!(body["did"], "did:webvh:xyz:example.com");
}

#[tokio::test]
async fn non_admin_cannot_update_context_did() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    app.request(post_auth(
        "/contexts",
        &super_token,
        json!({"id": "restricted", "name": "R"}),
    ))
    .await;

    // Application role cannot update DID
    let app_token = ctx
        .auth_token("did:key:z6MkApp", "application", vec!["restricted".into()])
        .await;
    let (status, _) = app
        .request(put_auth(
            "/contexts/restricted/did",
            &app_token,
            json!({"did": "did:webvh:bad:example.com"}),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ── Reader role tests ──────────────────────────────────────────────

#[tokio::test]
async fn reader_can_list_keys() {
    let (app, ctx) = TestApp::new().await;
    let reader_token = ctx
        .auth_token("did:key:z6MkReader", "reader", vec!["test-ctx".into()])
        .await;

    let (status, _) = app
        .request(get_auth("/keys?context_id=test-ctx", &reader_token))
        .await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn reader_cannot_sign() {
    let (app, ctx) = TestApp::new().await;
    let reader_token = ctx
        .auth_token("did:key:z6MkReader", "reader", vec!["test-ctx".into()])
        .await;

    let (status, _) = app
        .request(post_auth(
            "/keys/test-key/sign",
            &reader_token,
            json!({"payload": "aGVsbG8", "algorithm": "EdDSA"}),
        ))
        .await;
    assert!(
        status == StatusCode::FORBIDDEN || status == StatusCode::UNPROCESSABLE_ENTITY,
        "expected 403 or 422, got {status}"
    );
}

#[tokio::test]
async fn reader_cannot_create_key() {
    let (app, ctx) = TestApp::new().await;
    let reader_token = ctx
        .auth_token("did:key:z6MkReader", "reader", vec!["test-ctx".into()])
        .await;

    let (status, _) = app
        .request(post_auth(
            "/keys",
            &reader_token,
            json!({"key_type": "Ed25519", "context_id": "test-ctx"}),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}