assay-engine 0.5.4

Standalone workflow + auth + dashboard HTTP server on PostgreSQL 18 + SQLite. Embeddable as a library, or run as a binary.
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
//! Phase-3 integration test.
//!
//! Spawns the `assay-engine` binary against a temp SQLite DB on a random
//! free port, polls `/api/v1/engine/workflow/health` until ready, then exercises the key
//! endpoints: health, version, namespaces, dashboard index. Confirms
//! shape of the responses.
//!
//! This test proves the whole binary wires together correctly — config
//! parsing → backend connect → migrations → axum compose → router
//! serving → both workflow API and dashboard paths answering.

use std::io::Write;
use std::net::TcpListener;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

/// Find a free TCP port by binding to 127.0.0.1:0, reading the assigned
/// port, and dropping the listener. Race-prone in theory; fine for tests
/// that spawn immediately.
fn free_port() -> u16 {
    let l = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral");
    l.local_addr().unwrap().port()
}

fn engine_binary() -> PathBuf {
    // cargo test sets CARGO_BIN_EXE_<name> for integration tests.
    env!("CARGO_BIN_EXE_assay-engine").into()
}

struct EngineProcess {
    child: Child,
    port: u16,
    _tmpdir: tempfile::TempDir,
}

impl EngineProcess {
    fn spawn() -> Self {
        let port = free_port();
        let tmp = tempfile::tempdir().expect("tempdir");
        let db_path = tmp.path().join("engine.db");
        let cfg_path = tmp.path().join("engine.toml");

        let cfg = format!(
            r#"
[server]
bind_addr = "127.0.0.1:{port}"

[backend]
type = "sqlite"
path = "{db}"

[auth]
admin_api_keys = ["engine-smoke-test-key"]

[logging]
level = "error"
format = "pretty"
"#,
            db = db_path.display()
        );
        std::fs::write(&cfg_path, cfg).expect("write cfg");

        let child = Command::new(engine_binary())
            .arg("serve")
            .arg("--config")
            .arg(&cfg_path)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .expect("spawn engine");

        Self {
            child,
            port,
            _tmpdir: tmp,
        }
    }

    fn url(&self, path: &str) -> String {
        format!("http://127.0.0.1:{}{}", self.port, path)
    }

    async fn wait_ready(&self, client: &reqwest::Client) {
        let deadline = Instant::now() + Duration::from_secs(15);
        loop {
            if let Ok(r) = client
                .get(self.url("/api/v1/engine/workflow/health"))
                .send()
                .await
                && r.status().is_success()
            {
                return;
            }
            if Instant::now() >= deadline {
                panic!("engine did not become ready on port {}", self.port);
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
    }
}

impl Drop for EngineProcess {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn engine_smoke_sqlite() {
    // Log to stderr so test output shows the port if anything fails.
    let _ = writeln!(std::io::stderr(), "engine_smoke_sqlite starting");

    let engine = EngineProcess::spawn();
    let client = reqwest::Client::builder()
        // 30s — generous: Argon2id (m=64 MiB, t=3, p=4) on a slow CI
        // runner can take 2-3s per hash; the BW register/verify path
        // does multiple. 5s is too tight on ubuntu-latest 4-vCPU.
        .timeout(Duration::from_secs(30))
        .build()
        .unwrap();

    engine.wait_ready(&client).await;

    // ── /api/v1/engine/workflow/health ────────────────────────────────────────────────
    let r = client
        .get(engine.url("/api/v1/engine/workflow/health"))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200, "health should return 200");
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["service"], "assay-workflow");
    assert_eq!(body["status"], "ok");

    // ── /api/v1/engine/workflow/version ───────────────────────────────────────────────
    let r = client
        .get(engine.url("/api/v1/engine/workflow/version"))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let body: serde_json::Value = r.json().await.unwrap();
    assert!(
        body.get("version").is_some(),
        "version response should have `version` field"
    );

    // ── /api/v1/engine/workflow/namespaces ────────────────────────────────────────────
    // Gated by the engine's auth layer — admin api-key
    // break-glass authenticates the request.
    let r = client
        .get(engine.url("/api/v1/engine/workflow/namespaces"))
        .header("Authorization", "Bearer engine-smoke-test-key")
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let body: serde_json::Value = r.json().await.unwrap();
    let arr = body.as_array().expect("namespaces should be a JSON array");
    assert!(
        arr.iter().any(|n| n["name"] == "main"),
        "`main` namespace should be auto-seeded on first connect"
    );

    // ── /workflow/ (dashboard index) ──────────────────────────────────
    let r = client.get(engine.url("/workflow/")).send().await.unwrap();
    assert_eq!(r.status(), 200);
    let ct = r
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .to_string();
    assert!(
        ct.starts_with("text/html"),
        "dashboard should return text/html, got {ct}"
    );
    let body = r.text().await.unwrap();
    assert!(
        body.contains("<html") || body.contains("<!DOCTYPE") || body.contains("<!doctype"),
        "dashboard body should contain HTML doctype"
    );

    // ── / (root → redirect to /workflow/) ─────────────────────────────
    let r = client.get(engine.url("/")).send().await.unwrap();
    assert!(
        r.status().is_success() || r.status().is_redirection(),
        "root should be 2xx or 3xx (redirect), got {}",
        r.status()
    );

    // ── /api/v1/vault/kv/* ────────────────────────────────────────────
    // Plan 17 / v0.3.0 vault module. Admin-key gated for Phase 1.
    let admin_bearer = "Bearer engine-smoke-test-key";

    // Unauthenticated: 401.
    let r = client
        .put(engine.url("/api/v1/vault/kv/api/stripe"))
        .json(&serde_json::json!({ "data": "sk_live_xxx" }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 401, "vault must reject missing bearer");

    // PUT with admin key.
    let r = client
        .put(engine.url("/api/v1/vault/kv/api/stripe"))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({ "data": "sk_live_xxx" }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 201, "vault PUT should return 201; body: ?");
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["version"], 1);

    // GET round-trip.
    let r = client
        .get(engine.url("/api/v1/vault/kv/api/stripe"))
        .header("Authorization", admin_bearer)
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["data"], "sk_live_xxx");
    assert_eq!(body["version"], 1);

    // PUT another version, confirm GET returns the newer one.
    let r = client
        .put(engine.url("/api/v1/vault/kv/api/stripe"))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({ "data": "sk_live_yyy" }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 201);
    let r = client
        .get(engine.url("/api/v1/vault/kv/api/stripe"))
        .header("Authorization", admin_bearer)
        .send()
        .await
        .unwrap();
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["data"], "sk_live_yyy");
    assert_eq!(body["version"], 2);

    // ── /api/v1/vault/transit/* ───────────────────────────────────────
    let r = client
        .post(engine.url("/api/v1/vault/transit/keys/logs"))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({}))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 201, "transit create should return 201");

    // Encrypt + decrypt round-trip.
    use base64::Engine;
    use base64::engine::general_purpose::STANDARD as B64;
    let plaintext = b"hello-from-engine-smoke";
    let r = client
        .post(engine.url("/api/v1/vault/transit/encrypt/logs"))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({
            "plaintext_b64": B64.encode(plaintext),
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let ct: serde_json::Value = r.json().await.unwrap();
    let ciphertext = ct["ciphertext"].as_str().unwrap();
    assert!(ciphertext.starts_with("vault:v1:"));

    let r = client
        .post(engine.url("/api/v1/vault/transit/decrypt/logs"))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({ "ciphertext": ciphertext }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let body: serde_json::Value = r.json().await.unwrap();
    let decoded = B64
        .decode(body["plaintext_b64"].as_str().unwrap().as_bytes())
        .unwrap();
    assert_eq!(decoded, plaintext);

    // ── /api/v1/vault/sys/seal-status ─────────────────────────────────
    // Phase 2 sealing: status reflects unsealed (plaintext-method,
    // first-boot path), `sealed = false`.
    let r = client
        .get(engine.url("/api/v1/vault/sys/seal-status"))
        .header("Authorization", admin_bearer)
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["sealed"], false);
    assert_eq!(body["method"], "plaintext");

    // ── /api/v1/vault/sys/seal — fail-closed semantics ────────────────
    let r = client
        .post(engine.url("/api/v1/vault/sys/seal"))
        .header("Authorization", admin_bearer)
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 204, "seal should return 204");

    // After sealing, KV + transit ops must surface 503 / Sealed.
    let r = client
        .put(engine.url("/api/v1/vault/kv/api/post-seal"))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({ "data": "should-be-rejected" }))
        .send()
        .await
        .unwrap();
    assert_eq!(
        r.status(),
        503,
        "PUT after seal must fail-closed with 503; got {}",
        r.status()
    );
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["error"], "sealed");

    let r = client
        .post(engine.url("/api/v1/vault/transit/encrypt/logs"))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({ "plaintext_b64": "Zm9v" }))
        .send()
        .await
        .unwrap();
    assert_eq!(
        r.status(),
        503,
        "transit encrypt after seal must fail-closed; got {}",
        r.status()
    );

    // Status should now report sealed = true.
    let r = client
        .get(engine.url("/api/v1/vault/sys/seal-status"))
        .header("Authorization", admin_bearer)
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["sealed"], true);

    // ── Spawn a second engine for collection / personal vault flow ────
    // (the prior instance is sealed for the rest of this test). The
    // flow is admin-key gated; this proves the Phase-3 routes exist and
    // round-trip through the full PG/SQLite path.
    drop(engine);
    let engine2 = EngineProcess::spawn();
    let client2 = reqwest::Client::builder()
        // 30s — generous: Argon2id (m=64 MiB, t=3, p=4) on a slow CI
        // runner can take 2-3s per hash; the BW register/verify path
        // does multiple. 5s is too tight on ubuntu-latest 4-vCPU.
        .timeout(Duration::from_secs(30))
        .build()
        .unwrap();
    engine2.wait_ready(&client2).await;

    // Personal vault: ensure for user "alice" with a 32-byte X25519
    // pubkey (placeholder — real value comes from the auth crate).
    let pubkey_b64 = B64.encode([7u8; 32]);
    let r = client2
        .post(engine2.url("/api/v1/vault/me/alice"))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({ "public_key_b64": pubkey_b64 }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["owner_user"], "alice");

    // Idempotent ensure — second call returns the same row.
    let r = client2
        .post(engine2.url("/api/v1/vault/me/alice"))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({ "public_key_b64": pubkey_b64 }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let again: serde_json::Value = r.json().await.unwrap();
    assert_eq!(again["id"], body["id"], "ensure_vault must be idempotent");

    // Personal item — pre-encrypted bytes (the server is just a blob
    // store at this layer).
    let r = client2
        .post(engine2.url("/api/v1/vault/me/alice/items"))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({
            "item_type": "login",
            "name": "github",
            "ciphertext_b64": B64.encode(b"encrypted-payload"),
            "nonce_b64": B64.encode([1u8; 12]),
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 201);
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["item_type"], "login");
    assert_eq!(body["name"], "github");

    // List personal items — should include the one we just created.
    let r = client2
        .get(engine2.url("/api/v1/vault/me/alice/items"))
        .header("Authorization", admin_bearer)
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["items"].as_array().unwrap().len(), 1);

    // Collection — create + add member + add item + list.
    let r = client2
        .post(engine2.url("/api/v1/vault/collections"))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({
            "org_id": "org-acme",
            "name": "Engineering",
            "created_by": "alice",
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 201);
    let col: serde_json::Value = r.json().await.unwrap();
    let col_id = col["id"].as_str().unwrap().to_string();

    // Add member with wrapped collection key.
    let r = client2
        .post(engine2.url(&format!("/api/v1/vault/collections/{col_id}/members")))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({
            "user_id": "alice",
            "wrapped_key_b64": B64.encode(b"wrapped-collection-key-32-bytes-here"),
            "role": "admin",
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 204);

    // List members.
    let r = client2
        .get(engine2.url(&format!("/api/v1/vault/collections/{col_id}/members")))
        .header("Authorization", admin_bearer)
        .send()
        .await
        .unwrap();
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["members"].as_array().unwrap().len(), 1);
    assert_eq!(body["members"][0]["user_id"], "alice");
    assert_eq!(body["members"][0]["role"], "admin");

    // Add item to the collection.
    let r = client2
        .post(engine2.url(&format!("/api/v1/vault/collections/{col_id}/items")))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({
            "item_type": "login",
            "name": "shared-aws-root",
            "ciphertext_b64": B64.encode(b"shared-encrypted"),
            "nonce_b64": B64.encode([2u8; 12]),
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 201);

    // List collection items.
    let r = client2
        .get(engine2.url(&format!("/api/v1/vault/collections/{col_id}/items")))
        .header("Authorization", admin_bearer)
        .send()
        .await
        .unwrap();
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["items"].as_array().unwrap().len(), 1);
    assert_eq!(body["items"][0]["name"], "shared-aws-root");

    // ── /api/v1/vault/share — biscuit share links (Phase 4) ──────────
    let r = client2
        .post(engine2.url("/api/v1/vault/share"))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({
            "target_kind": "collection",
            "target_id": col_id,
            "ttl_secs": 60,
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 201);
    let mint: serde_json::Value = r.json().await.unwrap();
    let token = mint["token"].as_str().unwrap().to_string();
    let revocation_id = mint["revocation_ids"][0].as_str().unwrap().to_string();
    assert!(!token.is_empty());

    // Redeem — public surface, no admin gate.
    let r = client2
        .get(engine2.url(&format!("/api/v1/vault/share/{token}")))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let grant: serde_json::Value = r.json().await.unwrap();
    assert_eq!(grant["target_kind"], "collection");
    assert_eq!(grant["target_id"], col_id);

    // Revoke and re-redeem — should now 403.
    let r = client2
        .post(engine2.url("/api/v1/vault/share/revoke"))
        .header("Authorization", admin_bearer)
        .json(&serde_json::json!({
            "revocation_id": revocation_id,
            "reason": "test-revoke",
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 204);
    let r = client2
        .get(engine2.url(&format!("/api/v1/vault/share/{token}")))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 403, "redeeming a revoked token must 403");

    // ── BW-compat shim (Phase 7) ─────────────────────────────────────
    // Discovery endpoints are public + unauthenticated.
    let r = client2.get(engine2.url("/api/alive")).send().await.unwrap();
    assert_eq!(r.status(), 200);
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["service"], "assay-vault");

    let r = client2
        .get(engine2.url("/api/version"))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);

    let r = client2
        .get(engine2.url("/api/config"))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["server"]["name"], "assay-vault");

    // ── BW prelogin → register → connect/token → sync round-trip ─────
    // Plan §S6: stock BW client flow. Drives the same routes `bw
    // login` would call.
    let bw_email = "bw-smoke@example.com";
    let bw_password = "0123456789abcdef0123456789abcdef"; // simulated KDF-derived hash

    // 1. Prelogin returns Argon2id KDF posture for the email.
    let r = client2
        .post(engine2.url("/api/accounts/prelogin"))
        .json(&serde_json::json!({ "email": bw_email }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["Kdf"], 1);
    assert_eq!(body["KdfIterations"], 3);
    assert_eq!(body["KdfMemory"], 64);

    // 2. Register the user.
    let r = client2
        .post(engine2.url("/api/accounts/register"))
        .json(&serde_json::json!({
            "Email": bw_email,
            "Name": "Smoke User",
            "MasterPasswordHash": bw_password,
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);

    // 3. Re-register the same email → 400.
    let r = client2
        .post(engine2.url("/api/accounts/register"))
        .json(&serde_json::json!({
            "Email": bw_email,
            "MasterPasswordHash": bw_password,
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 400, "duplicate register should 400");

    // 4. /identity/connect/token — password grant returns a JWT.
    let r = client2
        .post(engine2.url("/identity/connect/token"))
        .form(&[
            ("grant_type", "password"),
            ("username", bw_email),
            ("password", bw_password),
            ("scope", "api offline_access"),
        ])
        .send()
        .await
        .unwrap();
    assert_eq!(
        r.status(),
        200,
        "BW token grant should succeed for seeded user"
    );
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["Kdf"], 1, "issued JWT response carries Argon2id KDF");
    assert!(body["access_token"].as_str().unwrap_or("").len() > 20);
    let bw_jwt = body["access_token"].as_str().unwrap().to_string();

    // 5. Wrong password → 400 invalid_grant.
    let r = client2
        .post(engine2.url("/identity/connect/token"))
        .form(&[
            ("grant_type", "password"),
            ("username", bw_email),
            ("password", "definitely-wrong"),
        ])
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 400);
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["error"], "invalid_grant");

    // 6. /api/sync with the JWT returns BW shape (auto-create vault row).
    let r = client2
        .get(engine2.url("/api/sync"))
        .bearer_auth(&bw_jwt)
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let body: serde_json::Value = r.json().await.unwrap();
    assert_eq!(body["Object"], "sync");
    assert_eq!(body["Profile"]["Email"], bw_email);

    // 7. Create a passkey-bearing cipher (plan §S6 — passkey-as-cipher).
    let cipher_body = serde_json::json!({
        "Type": 1,
        "Name": "github",
        "Notes": "encrypted-notes-blob",
        "Login": {
            "Username": "alice@example.com",
            "Password": "encrypted-password-blob",
            "Uri": "https://github.com",
            "Fido2Credentials": [
                {
                    "CredentialId": "encrypted-credential-id",
                    "KeyType": "encrypted-key-type",
                    "KeyAlgorithm": "encrypted-alg",
                    "RpId": "encrypted-rpid",
                    "UserName": "encrypted-user",
                    "Counter": "encrypted-counter"
                }
            ]
        }
    });
    let r = client2
        .post(engine2.url("/api/ciphers"))
        .bearer_auth(&bw_jwt)
        .json(&cipher_body)
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 201);
    let body: serde_json::Value = r.json().await.unwrap();
    let cipher_id = body["Id"].as_str().unwrap().to_string();
    assert_eq!(body["Type"], 1);
    assert!(body["Login"]["Fido2Credentials"].is_array());

    // 8. Sync now returns the cipher with passkey credentials intact.
    let r = client2
        .get(engine2.url("/api/sync"))
        .bearer_auth(&bw_jwt)
        .send()
        .await
        .unwrap();
    let body: serde_json::Value = r.json().await.unwrap();
    let ciphers = body["Ciphers"].as_array().unwrap();
    assert_eq!(ciphers.len(), 1);
    assert_eq!(
        ciphers[0]["Login"]["Fido2Credentials"][0]["CredentialId"],
        "encrypted-credential-id"
    );

    // 9. Delete the cipher.
    let r = client2
        .delete(engine2.url(&format!("/api/ciphers/{cipher_id}")))
        .bearer_auth(&bw_jwt)
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 204);

    // ── /vault/console — Phase-7 dashboard pane ──────────────────────
    let r = client2
        .get(engine2.url("/vault/console"))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let ct = r
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .to_string();
    assert!(
        ct.starts_with("text/html"),
        "vault console should return text/html, got {ct}"
    );
    let body = r.text().await.unwrap();
    assert!(body.contains("Assay Vault"));
    // Pane controllers reference the documented endpoints.
    let r = client2
        .get(engine2.url("/vault/app.js"))
        .send()
        .await
        .unwrap();
    assert_eq!(r.status(), 200);
    let body = r.text().await.unwrap();
    assert!(body.contains("/sys/seal-status"));
    assert!(body.contains("/transit/keys"));
    assert!(body.contains("/dynamic/leases"));
    // Plan §S10 — My vault + Collections panes (A7).
    assert!(body.contains("/me/"));
    assert!(body.contains("/collections"));
}