jmap-base-client 0.1.2

RFC 8620 JMAP base client — auth-agnostic, session fetch, blob, SSE, WebSocket
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
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
// Integration tests for JmapClient core methods.
// Oracle: RFC 8620 §2 (Session), §3.3 (making requests), §6 (blobs), §7 (push)
// Fixtures: tests/fixtures/jmap/*.json (hand-written from RFC 8620 examples)

use jmap_base_client::auth::NoneAuth;
use jmap_base_client::client::JmapClient;
use jmap_base_client::error::ClientError;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn session_fixture() -> serde_json::Value {
    let text = std::fs::read_to_string(
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/jmap/session.json"),
    )
    .expect("cannot read session.json fixture");
    serde_json::from_str(&text).expect("session.json must be valid JSON")
}

fn call_response_fixture() -> serde_json::Value {
    let text = std::fs::read_to_string(
        std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/jmap/call_response.json"),
    )
    .expect("cannot read call_response.json fixture");
    serde_json::from_str(&text).expect("call_response.json must be valid JSON")
}

fn minimal_request() -> jmap_types::JmapRequest {
    jmap_types::JmapRequest::new(
        vec!["urn:ietf:params:jmap:core".to_owned()],
        vec![(
            "Mailbox/get".to_owned(),
            serde_json::json!({"accountId": "A13824", "ids": null}),
            "r1".to_owned(),
        )],
        None,
    )
}

// ---------------------------------------------------------------------------
// Constructor validation (these do not need a mock server)
// ---------------------------------------------------------------------------

/// Oracle: base_url validation — empty string must be rejected.
#[test]
fn test_new_rejects_empty_url() {
    let result = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        "",
        jmap_base_client::client::ClientConfig::default(),
    )
    .map(|_| ());
    assert!(
        matches!(result, Err(ClientError::InvalidArgument(_))),
        "empty base_url must return InvalidArgument, got {result:?}"
    );
}

/// Oracle: base_url validation — ftp:// scheme must be rejected.
#[test]
fn test_new_rejects_ftp_scheme() {
    let result = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        "ftp://example.com",
        jmap_base_client::client::ClientConfig::default(),
    )
    .map(|_| ());
    assert!(
        matches!(result, Err(ClientError::InvalidArgument(_))),
        "ftp scheme must return InvalidArgument, got {result:?}"
    );
}

/// Oracle: base_url validation — URL with a path component must be rejected.
#[test]
fn test_new_rejects_url_with_path() {
    let result = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        "https://example.com/jmap",
        jmap_base_client::client::ClientConfig::default(),
    )
    .map(|_| ());
    assert!(
        matches!(result, Err(ClientError::InvalidArgument(_))),
        "base_url with path must return InvalidArgument, got {result:?}"
    );
}

/// Oracle: bd:JMAP-6r7c.58 — base_url with RFC 3986 user-info
/// (`https://user:password@host/`) must be rejected. url::Url::Display
/// echoes user-info verbatim (RFC 3986 §7.5 explicitly warns against
/// this), so an unrejected user-info value would leak through every
/// downstream error message that carries the URL. JMAP authenticates via
/// the Authorization header (AuthProvider) — the user-info component has
/// no legitimate use here.
#[test]
fn test_new_rejects_url_with_userinfo_password() {
    let canary_password = "redaction-canary-pw-PSt8SiPS";
    let url = format!("https://alice:{canary_password}@example.com");
    let result = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &url,
        jmap_base_client::client::ClientConfig::default(),
    )
    .map(|_| ());
    let err = result.expect_err("user-info in base_url must be rejected");
    let rendered = format!("{err}");
    assert!(
        matches!(err, ClientError::InvalidArgument(_)),
        "expected InvalidArgument, got {err:?}"
    );
    assert!(
        !rendered.contains(canary_password),
        "rejection error message must not echo the password back into the \
         error chain; rendered: {rendered}"
    );
    assert!(
        !rendered.contains("alice"),
        "rejection error message must not echo the username back either; \
         rendered: {rendered}"
    );
    assert!(
        rendered.contains("user-info"),
        "rejection error message must surface the actual reason for diagnostics; \
         rendered: {rendered}"
    );
}

/// Oracle: bd:JMAP-6r7c.58 — base_url with username only (no password)
/// must also be rejected. url::Url::Display includes the username even
/// when no password is present, so the same leak class applies.
#[test]
fn test_new_rejects_url_with_userinfo_username_only() {
    let result = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        "https://alice@example.com",
        jmap_base_client::client::ClientConfig::default(),
    )
    .map(|_| ());
    assert!(
        matches!(result, Err(ClientError::InvalidArgument(_))),
        "username-only user-info must be rejected, got {result:?}"
    );
}

/// Oracle: base_url validation — a bare https origin must be accepted.
#[test]
fn test_new_accepts_https_origin() {
    let result = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        "https://example.com",
        jmap_base_client::client::ClientConfig::default(),
    )
    .map(|_| ());
    assert!(result.is_ok(), "valid https origin must be accepted");
}

/// Oracle: bd:JMAP-6r7c.27 — `new_with_shared_auth` accepts a pre-built
/// `Arc<dyn AuthProvider>` and shares it across multiple `JmapClient`
/// instances. The strong-count assertions document the sharing contract.
#[test]
fn test_new_with_shared_auth_shares_the_arc() {
    use std::sync::Arc;
    let auth: Arc<dyn jmap_base_client::auth::AuthProvider> = Arc::new(NoneAuth);
    assert_eq!(Arc::strong_count(&auth), 1, "fresh Arc starts at 1");

    let client_a = JmapClient::new_with_shared_auth(
        jmap_base_client::auth::DefaultTransport,
        Arc::clone(&auth),
        "https://a.example.com",
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("valid https origin must be accepted");
    assert_eq!(
        Arc::strong_count(&auth),
        2,
        "client A must hold the second strong reference"
    );

    let client_b = JmapClient::new_with_shared_auth(
        jmap_base_client::auth::DefaultTransport,
        Arc::clone(&auth),
        "https://b.example.com",
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("valid https origin must be accepted");
    assert_eq!(
        Arc::strong_count(&auth),
        3,
        "client B must hold the third strong reference"
    );

    // Drop the test's local Arc; the two clients still share the remaining 2.
    drop(auth);
    drop(client_a);
    drop(client_b);
}

/// Oracle: config validation — request_timeout == Duration::ZERO must be rejected.
/// Duration::ZERO is version-dependent in reqwest: some versions treat it as "no timeout",
/// others as "instant timeout". Reject explicitly to eliminate this footgun.
#[test]
fn test_new_rejects_zero_request_timeout() {
    let mut config = jmap_base_client::client::ClientConfig::default();
    config.request_timeout = std::time::Duration::ZERO;
    let result = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        "https://example.com",
        config,
    )
    .map(|_| ());
    assert!(
        matches!(result, Err(ClientError::InvalidArgument(_))),
        "request_timeout == Duration::ZERO must return InvalidArgument, got {result:?}"
    );
}

/// Oracle: config validation — max_call_body == 0 must be rejected with InvalidArgument.
#[test]
fn test_new_rejects_zero_max_call_body() {
    let mut config = jmap_base_client::client::ClientConfig::default();
    config.max_call_body = 0;
    let result = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        "https://example.com",
        config,
    )
    .map(|_| ());
    assert!(
        matches!(result, Err(ClientError::InvalidArgument(_))),
        "max_call_body == 0 must return InvalidArgument, got {result:?}"
    );
}

/// Oracle: config validation — max_ws_message == 0 must be rejected with
/// InvalidArgument. tungstenite would otherwise treat `Some(0)` as "no
/// message of any size is acceptable" which is a misconfiguration trap.
/// JMAP-6lsm.5 added this field; test pins the validation contract.
#[test]
fn test_new_rejects_zero_max_ws_message() {
    let mut config = jmap_base_client::client::ClientConfig::default();
    config.max_ws_message = 0;
    let result = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        "https://example.com",
        config,
    )
    .map(|_| ());
    assert!(
        matches!(result, Err(ClientError::InvalidArgument(_))),
        "max_ws_message == 0 must return InvalidArgument, got {result:?}"
    );
}

/// Oracle: ClientConfig::default has max_ws_message = 1 MiB (parallel to
/// max_sse_frame). Default values are part of the public contract; if a
/// future change retunes the default this test breaks loudly so the
/// change is deliberate.
#[test]
fn test_default_max_ws_message_is_1mib() {
    let cfg = jmap_base_client::client::ClientConfig::default();
    assert_eq!(cfg.max_ws_message, 1024 * 1024);
    assert_eq!(cfg.max_sse_frame, 1024 * 1024);
}

/// Oracle: connect_ws_with_limit must reject max_message_bytes == 0 with
/// InvalidArgument BEFORE attempting any I/O. Mirrors the ClientConfig
/// validation; JMAP-6lsm.5.
#[tokio::test]
async fn test_connect_ws_with_limit_rejects_zero_max_message() {
    let result = jmap_base_client::ws::connect_ws_with_limit("ws://localhost/", None, 0).await;
    match result {
        Err(jmap_base_client::ClientError::InvalidArgument(msg)) => {
            assert!(
                msg.contains("max_message_bytes"),
                "error message must mention 'max_message_bytes': {msg}"
            );
        }
        other => panic!("expected InvalidArgument(\"...max_message_bytes...\"), got {other:?}"),
    }
}

// ---------------------------------------------------------------------------
// fetch_session
// ---------------------------------------------------------------------------

/// Oracle: RFC 8620 §2 — fetch_session returns a correctly parsed Session
/// with the apiUrl, uploadUrl, downloadUrl, eventSourceUrl, state, and username
/// from the hand-written RFC 8620 fixture.
#[tokio::test]
async fn test_fetch_session_returns_session() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/.well-known/jmap"))
        .respond_with(ResponseTemplate::new(200).set_body_json(session_fixture()))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let session = client
        .fetch_session()
        .await
        .expect("fetch_session must succeed");

    // Oracle: RFC 8620 §2.1 — values from fixture, not from code under test
    assert_eq!(session.username, "john@example.com");
    assert_eq!(session.api_url, "https://jmap.example.com/api/");
    assert_eq!(
        session.upload_url,
        "https://jmap.example.com/upload/{accountId}/"
    );
    assert_eq!(
        session.download_url,
        "https://jmap.example.com/download/{accountId}/{blobId}/{name}?accept={type}"
    );
    assert_eq!(
        session.event_source_url,
        "https://jmap.example.com/eventsource/?types={types}&closeafter={closeafter}&ping={ping}"
    );
    assert_eq!(session.state, "75128aab4b1b");
    assert!(
        session.accounts.contains_key("A13824"),
        "accounts must contain A13824"
    );
}

/// Oracle: security requirement — fetch_session response body capped at 1 MiB.
/// A response body of 1 MiB + 1 byte must return ClientError::ResponseTooLarge.
#[tokio::test]
async fn test_fetch_session_size_cap() {
    let oversized_body = "x".repeat(1024 * 1024 + 1);
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/.well-known/jmap"))
        .respond_with(ResponseTemplate::new(200).set_body_string(oversized_body))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let err = client
        .fetch_session()
        .await
        .expect_err("oversized response must fail");
    assert!(
        matches!(err, ClientError::ResponseTooLarge { .. }),
        "expected ResponseTooLarge, got {err:?}"
    );
}

/// Oracle: RFC 8620 §2 — HTTP 401 from session endpoint must surface as
/// ClientError::AuthFailed(401).
#[tokio::test]
async fn test_fetch_session_401_returns_auth_failed() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/.well-known/jmap"))
        .respond_with(ResponseTemplate::new(401))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let err = client.fetch_session().await.expect_err("401 must fail");
    assert!(
        matches!(err, ClientError::AuthFailed(401)),
        "expected AuthFailed(401), got {err:?}"
    );
}

/// Oracle: session URL validation — a Session whose apiUrl has a non-http
/// scheme must return ClientError::InvalidArgument.
#[tokio::test]
async fn test_fetch_session_rejects_non_http_api_url() {
    let server = MockServer::start().await;

    let mut body = session_fixture();
    body["apiUrl"] = serde_json::Value::String("ftp://example.com/api/".to_owned());

    Mock::given(method("GET"))
        .and(path("/.well-known/jmap"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let err = client
        .fetch_session()
        .await
        .expect_err("ftp apiUrl must fail");
    assert!(
        matches!(err, ClientError::InvalidSession(_)),
        "expected InvalidSession for ftp apiUrl, got {err:?}"
    );
}

/// Oracle: session URL validation — each of uploadUrl, downloadUrl, and
/// eventSourceUrl with a non-http scheme must return ClientError::InvalidArgument.
#[tokio::test]
async fn test_fetch_session_rejects_non_http_other_urls() {
    // A fresh MockServer per iteration ensures each request receives exactly
    // the intended body with one field set to ftp://, regardless of wiremock
    // mock-matching order when multiple mocks are registered on the same path.
    for field in &["uploadUrl", "downloadUrl", "eventSourceUrl"] {
        let server = MockServer::start().await;
        let mut body = session_fixture();
        body[*field] = serde_json::Value::String("ftp://example.com/bad".to_owned());

        Mock::given(method("GET"))
            .and(path("/.well-known/jmap"))
            .respond_with(ResponseTemplate::new(200).set_body_json(body))
            .mount(&server)
            .await;

        let client = JmapClient::new(
            jmap_base_client::auth::DefaultTransport,
            NoneAuth,
            &server.uri(),
            jmap_base_client::client::ClientConfig::default(),
        )
        .expect("client construction must succeed");

        let err = client
            .fetch_session()
            .await
            .expect_err(&format!("ftp {field} must fail"));
        assert!(
            matches!(err, ClientError::InvalidSession(_)),
            "expected InvalidSession for ftp {field}, got {err:?}"
        );
    }
}

// ---------------------------------------------------------------------------
// call
// ---------------------------------------------------------------------------

/// Oracle: RFC 8620 §3.3/§3.4 — a successful POST to apiUrl returns a
/// JmapResponse parsed from the hand-written call_response.json fixture.
#[tokio::test]
async fn test_call_round_trip() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/api/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(call_response_fixture()))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let api_url = format!("{}/api/", server.uri());
    let resp = client
        .call(&api_url, &minimal_request())
        .await
        .expect("call must succeed");

    // Oracle: values from call_response.json fixture
    assert_eq!(resp.session_state, "sess1");
    assert_eq!(resp.method_responses.len(), 1);
    assert_eq!(resp.method_responses[0].0, "Mailbox/get");
    assert_eq!(resp.method_responses[0].2, "r1");

    // Tighten the args check (bd:JMAP-6r7c.7): inspect the args payload so a
    // regression that zeroed or stripped it cannot pass this test silently.
    // The fixture sets accountId="A13824", state="m-state-1", list=[],
    // notFound=[]; all four are checked.
    let args = resp.method_responses[0]
        .1
        .as_object()
        .expect("method-response args must be a JSON object");
    assert_eq!(
        args.get("accountId").and_then(|v| v.as_str()),
        Some("A13824"),
        "args.accountId must match call_response.json fixture"
    );
    assert_eq!(
        args.get("state").and_then(|v| v.as_str()),
        Some("m-state-1"),
        "args.state must match call_response.json fixture"
    );
    assert!(
        args.get("list")
            .and_then(|v| v.as_array())
            .is_some_and(Vec::is_empty),
        "args.list must be an empty array"
    );
    assert!(
        args.get("notFound")
            .and_then(|v| v.as_array())
            .is_some_and(Vec::is_empty),
        "args.notFound must be an empty array"
    );
}

/// Oracle: bd:JMAP-6r7c.39 — `call_session` POSTs to `session.api_url`,
/// not to `session.upload_url` or any other session URL field.
///
/// The mock server is configured so that GETting `/api/` would return
/// 500 (which would fail the test), and POSTing `/api/` returns the
/// canned call_response fixture. We construct a Session whose api_url
/// points at the mock's `/api/` and upload_url points at a different
/// path that is unmocked (so any accidental route would 404). If a
/// future refactor accidentally routed `call_session` to (say)
/// `session.upload_url`, the test would fail because the mock would
/// not match the wrong path.
#[tokio::test]
async fn test_call_session_routes_to_session_api_url() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/api/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(call_response_fixture()))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    // Construct a Session by deserializing a minimal JSON payload so the
    // URL points at the mock server, not at the example.com placeholder
    // from the on-disk fixture. The upload_url / download_url /
    // event_source_url fields point at an unmocked path so any
    // wrong-routing regression surfaces as a connection error or 404,
    // not as a silent success.  Session is `#[non_exhaustive]`, so a
    // struct-literal constructor is not available from outside the
    // crate; the JSON path is the public construction API.
    let api_url = format!("{}/api/", server.uri());
    let unmocked_url = format!("{}/UNMOCKED-must-not-be-hit", server.uri());
    let session: jmap_base_client::request::Session = serde_json::from_value(serde_json::json!({
        "capabilities": {},
        "accounts": {},
        "primaryAccounts": {},
        "username": "",
        "apiUrl": api_url,
        "downloadUrl": unmocked_url,
        "uploadUrl": unmocked_url,
        "eventSourceUrl": unmocked_url,
        "state": "",
    }))
    .expect("hand-rolled Session JSON must deserialize");

    let resp = client
        .call_session(&session, &minimal_request())
        .await
        .expect("call_session must succeed against session.api_url");

    // Oracle from call_response.json fixture: same as test_call_round_trip.
    assert_eq!(resp.session_state, "sess1");
    assert_eq!(resp.method_responses.len(), 1);
    assert_eq!(resp.method_responses[0].0, "Mailbox/get");
}

/// Oracle: bd:JMAP-6r7c.64 — `upload_blob_session` reads
/// `session.upload_url` internally and refuses to route to any other
/// session URL field. The mock server responds at `/upload/<account>/`;
/// the other Session URL fields point at unmocked paths so a wrong-
/// routing regression surfaces as a 404 or connection error rather
/// than a silent success.
#[tokio::test]
async fn test_upload_blob_session_routes_to_session_upload_url() {
    use wiremock::matchers::header;

    let payload: &[u8] = b"upload-session-bytes";
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/upload/account1/"))
        .and(header("Content-Type", "application/octet-stream"))
        .respond_with(ResponseTemplate::new(200).set_body_string(
            r#"{"accountId":"account1","blobId":"B-session-1","type":"application/octet-stream","size":20}"#,
        ))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let upload_url = format!("{}/upload/{{accountId}}/", server.uri());
    let unmocked = format!("{}/UNMOCKED-must-not-be-hit", server.uri());
    let session: jmap_base_client::request::Session = serde_json::from_value(serde_json::json!({
        "capabilities": {},
        "accounts": {},
        "primaryAccounts": {},
        "username": "",
        "apiUrl": unmocked,
        "downloadUrl": unmocked,
        "uploadUrl": upload_url,
        "eventSourceUrl": unmocked,
        "state": "",
    }))
    .expect("hand-rolled Session JSON must deserialize");

    let resp = client
        .upload_blob_session(
            &session,
            jmap_base_client::UploadBlobSessionParams {
                account_id: "account1",
                content_type: "application/octet-stream",
                data: bytes::Bytes::copy_from_slice(payload),
            },
        )
        .await
        .expect("upload_blob_session must route via session.upload_url");

    assert_eq!(resp.account_id, "account1");
    assert_eq!(resp.blob_id, "B-session-1");
    assert_eq!(resp.size, payload.len() as u64);
}

/// Oracle: bd:JMAP-6r7c.64 — `download_blob_session` reads
/// `session.download_url` internally. Same routing-discriminator
/// pattern as the upload variant.
#[tokio::test]
async fn test_download_blob_session_routes_to_session_download_url() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/download/account1/blob-abc/file.bin"))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(b"download-session-bytes".to_vec()))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let download_url = format!(
        "{}/download/{{accountId}}/{{blobId}}/{{name}}",
        server.uri()
    );
    let unmocked = format!("{}/UNMOCKED-must-not-be-hit", server.uri());
    let session: jmap_base_client::request::Session = serde_json::from_value(serde_json::json!({
        "capabilities": {},
        "accounts": {},
        "primaryAccounts": {},
        "username": "",
        "apiUrl": unmocked,
        "downloadUrl": download_url,
        "uploadUrl": unmocked,
        "eventSourceUrl": unmocked,
        "state": "",
    }))
    .expect("hand-rolled Session JSON must deserialize");

    let bytes = client
        .download_blob_session(
            &session,
            jmap_base_client::DownloadBlobSessionParams {
                account_id: "account1",
                blob_id: "blob-abc",
                name: "file.bin",
                accept_type: None,
                expected_sha256: None,
            },
        )
        .await
        .expect("download_blob_session must route via session.download_url");

    assert_eq!(bytes.as_ref(), b"download-session-bytes");
}

/// Oracle: bd:JMAP-6r7c.64 — `subscribe_events_session` expands
/// `session.event_source_url` with the caller-supplied
/// SubscribeEventsSessionParams template variables. Mock server
/// responds at the expanded path so a wrong-routing regression
/// surfaces as a 404.
#[tokio::test]
async fn test_subscribe_events_session_routes_to_session_event_source_url() {
    use futures::StreamExt as _;

    let sse_body = "event: state\ndata: {\"changed\":{\"acc1\":{\"Email\":\"s1\"}}}\n\n";
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/events/"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "text/event-stream")
                .set_body_bytes(sse_body.as_bytes().to_vec()),
        )
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    // Template with the three RFC 8620 §7.3 variables. With params=None,
    // each expands to "" producing `/events/?types=&closeafter=&ping=`.
    // The mock matches the path `/events/` (path matcher ignores query
    // string), so the routing is correct iff the expansion uses
    // session.event_source_url.
    let event_source_url = format!(
        "{}/events/?types={{types}}&closeafter={{closeafter}}&ping={{ping}}",
        server.uri()
    );
    let unmocked = format!("{}/UNMOCKED-must-not-be-hit", server.uri());
    let session: jmap_base_client::request::Session = serde_json::from_value(serde_json::json!({
        "capabilities": {},
        "accounts": {},
        "primaryAccounts": {},
        "username": "",
        "apiUrl": unmocked,
        "downloadUrl": unmocked,
        "uploadUrl": unmocked,
        "eventSourceUrl": event_source_url,
        "state": "",
    }))
    .expect("hand-rolled Session JSON must deserialize");

    let mut stream = client
        .subscribe_events_session(
            &session,
            jmap_base_client::SubscribeEventsSessionParams::default(),
        )
        .await
        .expect("subscribe_events_session must route via session.event_source_url");

    let frame = stream
        .next()
        .await
        .expect("must receive at least one frame")
        .expect("frame must parse");
    match frame.event {
        jmap_base_client::sse::SseEvent::StateChange(sc) => {
            let acct = sc
                .changed
                .get("acc1")
                .expect("server StateChange must carry acc1");
            assert_eq!(acct.get("Email").map(|s| s.as_ref()), Some("s1"));
        }
        other => panic!("expected StateChange, got {other:?}"),
    }
}

/// Oracle: security requirement — call response body capped at 8 MiB.
/// A response body of 8 MiB + 1 byte must return ClientError::ResponseTooLarge.
#[tokio::test]
async fn test_call_size_cap() {
    let oversized_body = "x".repeat(8 * 1024 * 1024 + 1);
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/api/"))
        .respond_with(ResponseTemplate::new(200).set_body_string(oversized_body))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let api_url = format!("{}/api/", server.uri());
    let err = client
        .call(&api_url, &minimal_request())
        .await
        .expect_err("oversized response must fail");
    assert!(
        matches!(err, ClientError::ResponseTooLarge { .. }),
        "expected ResponseTooLarge, got {err:?}"
    );
}

/// Oracle: RFC 8620 §3.3 — HTTP 401 from apiUrl must surface as
/// ClientError::AuthFailed(401).
#[tokio::test]
async fn test_call_401_returns_auth_failed() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/api/"))
        .respond_with(ResponseTemplate::new(401))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let api_url = format!("{}/api/", server.uri());
    let err = client
        .call(&api_url, &minimal_request())
        .await
        .expect_err("401 must fail");
    assert!(
        matches!(err, ClientError::AuthFailed(401)),
        "expected AuthFailed(401), got {err:?}"
    );
}

// ---------------------------------------------------------------------------
// upload_blob
// ---------------------------------------------------------------------------

/// Oracle: bd:JMAP-6r7c.50 — `upload_blob` accepts a typed `UploadBlobParams`
/// struct literal (not four positional `&str`-ish args). The wire request
/// reaches the server at `Session.upload_url` with `{accountId}` expanded,
/// carries the supplied `Content-Type` header, and posts the supplied bytes.
/// On the matched expected response, the client returns a parsed
/// `BlobUploadResponse` carrying the same account id, blob id, content
/// type, and size — independent oracle for the round-trip.
#[tokio::test]
async fn test_upload_blob_typed_params_round_trip() {
    use wiremock::matchers::{body_bytes, header};

    let payload: &[u8] = b"hello world";
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/upload/account1/"))
        .and(header("Content-Type", "application/octet-stream"))
        .and(body_bytes(payload.to_vec()))
        .respond_with(ResponseTemplate::new(200).set_body_string(
            r#"{"accountId":"account1","blobId":"B-typed-1","type":"application/octet-stream","size":11}"#,
        ))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let template =
        jmap_base_client::JmapUrlTemplate::new(format!("{}/upload/{{accountId}}/", server.uri()));
    let resp = client
        .upload_blob(jmap_base_client::UploadBlobParams {
            upload_url_template: &template,
            account_id: "account1",
            content_type: "application/octet-stream",
            data: bytes::Bytes::copy_from_slice(payload),
        })
        .await
        .expect("typed upload must succeed");

    assert_eq!(resp.account_id, "account1");
    assert_eq!(resp.blob_id, "B-typed-1");
    assert_eq!(resp.content_type, "application/octet-stream");
    assert_eq!(resp.size, payload.len() as u64);
}

/// Oracle: security requirement — upload_blob response body capped at 1 MiB.
/// A server returning an oversized upload response must yield ResponseTooLarge.
#[tokio::test]
async fn test_upload_blob_response_size_cap() {
    let oversized_body = "x".repeat(1024 * 1024 + 1);
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/upload/account1/"))
        .respond_with(ResponseTemplate::new(200).set_body_string(oversized_body))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let template =
        jmap_base_client::JmapUrlTemplate::new(format!("{}/upload/{{accountId}}/", server.uri()));
    let err = client
        .upload_blob(jmap_base_client::UploadBlobParams {
            upload_url_template: &template,
            account_id: "account1",
            content_type: "application/octet-stream",
            data: bytes::Bytes::from(b"hello".to_vec()),
        })
        .await
        .expect_err("oversized upload response must fail");
    assert!(
        matches!(err, ClientError::ResponseTooLarge { .. }),
        "expected ResponseTooLarge, got {err:?}"
    );
}

/// Oracle: regression for bd:JMAP-6lsm.8 — when the server's reply
/// `BlobUploadResponse.size` disagrees with the actual bytes uploaded,
/// upload_blob MUST surface UnexpectedResponse rather than silently
/// accept the buggy server's reported size. Independent oracle: a
/// hand-crafted server response declaring size=0 for a 5-byte upload.
#[tokio::test]
async fn test_upload_blob_rejects_size_mismatch() {
    let server = MockServer::start().await;

    // Server returns a JSON BlobUploadResponse with size=0 even though
    // the client uploads 5 bytes. No sha256 (most servers don't supply
    // one), so size is the only integrity signal.
    let buggy_resp =
        r#"{"accountId":"account1","blobId":"B1","type":"application/octet-stream","size":0}"#;
    Mock::given(method("POST"))
        .and(path("/upload/account1/"))
        .respond_with(ResponseTemplate::new(200).set_body_string(buggy_resp))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let template =
        jmap_base_client::JmapUrlTemplate::new(format!("{}/upload/{{accountId}}/", server.uri()));
    let err = client
        .upload_blob(jmap_base_client::UploadBlobParams {
            upload_url_template: &template,
            account_id: "account1",
            content_type: "application/octet-stream",
            data: bytes::Bytes::from(b"hello".to_vec()), // 5 bytes
        })
        .await
        .expect_err("size mismatch must surface as an error");
    match err {
        ClientError::UnexpectedResponse(msg) => {
            assert!(
                msg.contains("size mismatch"),
                "error must mention 'size mismatch': {msg}"
            );
            assert!(msg.contains("5"), "error must mention client size 5: {msg}");
            assert!(msg.contains("0"), "error must mention server size 0: {msg}");
        }
        other => panic!("expected UnexpectedResponse, got {other:?}"),
    }
}

// ---------------------------------------------------------------------------
// download_blob
// ---------------------------------------------------------------------------

/// Oracle: security requirement — download_blob response body capped at 64 MiB.
/// A response body of 64 MiB + 1 byte must return ClientError::ResponseTooLarge.
#[tokio::test]
async fn test_download_blob_size_cap() {
    let oversized_body = vec![b'x'; 64 * 1024 * 1024 + 1];
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/download/account1/blob-abc/file.bin"))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(oversized_body))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let template = jmap_base_client::JmapUrlTemplate::new(format!(
        "{}/download/{{accountId}}/{{blobId}}/{{name}}",
        server.uri()
    ));
    let err = client
        .download_blob(jmap_base_client::DownloadBlobParams {
            download_url_template: &template,
            account_id: "account1",
            blob_id: "blob-abc",
            name: "file.bin",
            accept_type: None,
            expected_sha256: None,
        })
        .await
        .expect_err("oversized download must fail");
    assert!(
        matches!(err, ClientError::ResponseTooLarge { .. }),
        "expected ResponseTooLarge, got {err:?}"
    );
}

// ---------------------------------------------------------------------------
// subscribe_events — SSE line-ending normalization
// ---------------------------------------------------------------------------

/// Oracle: RFC 8895 §9 — SSE lines terminated with CRLF must parse
/// identically to LF-terminated lines.
///
/// A server sending HTTP/1.1 CRLF-terminated SSE is realistic; the client
/// must normalize \r\n → \n before handing the block to parse_sse_block.
#[tokio::test]
async fn test_subscribe_events_crlf_line_endings() {
    use futures::StreamExt as _;
    use jmap_base_client::sse::SseEvent;

    // CRLF-terminated SSE block ending in the double-CRLF frame delimiter.
    let crlf_body = "event: state\r\ndata: {\"changed\":{}}\r\n\r\n";

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/events"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "text/event-stream")
                .set_body_bytes(crlf_body.as_bytes().to_vec()),
        )
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let event_url = format!("{}/events", server.uri());
    let mut stream = client
        .subscribe_events(&event_url, None)
        .await
        .expect("subscribe_events must succeed");

    let frame = stream
        .next()
        .await
        .expect("stream must yield at least one frame")
        .expect("frame must not be an error");

    // Oracle: the "state" event type must be recognized after CRLF normalization.
    assert!(
        matches!(frame.event, SseEvent::StateChange(_)),
        "CRLF-terminated state event must parse as StateChange, got {:?}",
        frame.event
    );
}

/// Oracle: RFC 8895 §9 — SSE frame terminated by LF + CRLF blank line (\n\r\n)
/// must parse correctly. This combination is not detected by \n\n (LFs are
/// separated by \r) and must be caught by the explicit \n\r\n search.
#[tokio::test]
async fn test_subscribe_events_lf_crlf_frame_delimiter() {
    use futures::StreamExt as _;
    use jmap_base_client::sse::SseEvent;

    // LF-terminated field lines, CRLF-terminated blank line: \n\r\n delimiter.
    let body = "event: state\ndata: {\"changed\":{}}\n\r\n";

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/events"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "text/event-stream")
                .set_body_bytes(body.as_bytes().to_vec()),
        )
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let event_url = format!("{}/events", server.uri());
    let mut stream = client
        .subscribe_events(&event_url, None)
        .await
        .expect("subscribe_events must succeed");

    let frame = stream
        .next()
        .await
        .expect("stream must yield at least one frame")
        .expect("frame must not be an error");

    // Oracle: state event must be recognized after \n\r\n delimiter.
    assert!(
        matches!(frame.event, SseEvent::StateChange(_)),
        "LF+CRLF-terminated state event must parse as StateChange, got {:?}",
        frame.event
    );
}

/// Oracle: RFC 8895 §9 — SSE lines terminated with bare CR must parse
/// identically to LF-terminated lines (CR-only is a valid line terminator).
#[tokio::test]
async fn test_subscribe_events_cr_line_endings() {
    use futures::StreamExt as _;
    use jmap_base_client::sse::SseEvent;

    // CR-only-terminated SSE block ending in the double-CR frame delimiter.
    let cr_body = "event: state\rdata: {\"changed\":{}}\r\r";

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/events"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "text/event-stream")
                .set_body_bytes(cr_body.as_bytes().to_vec()),
        )
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let event_url = format!("{}/events", server.uri());
    let mut stream = client
        .subscribe_events(&event_url, None)
        .await
        .expect("subscribe_events must succeed");

    let frame = stream
        .next()
        .await
        .expect("stream must yield at least one frame")
        .expect("frame must not be an error");

    // Oracle: the "state" event type must be recognized after CR normalization.
    assert!(
        matches!(frame.event, SseEvent::StateChange(_)),
        "CR-terminated state event must parse as StateChange, got {:?}",
        frame.event
    );
}

/// Oracle: security requirement — subscribe_events must reject a 200 response
/// whose Content-Type is not text/event-stream. A misconfigured server returning
/// application/json would silently produce no events; return UnexpectedResponse instead.
#[tokio::test]
async fn test_subscribe_events_rejects_wrong_content_type() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/events"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "application/json")
                .set_body_bytes(b"{}".to_vec()),
        )
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let event_url = format!("{}/events", server.uri());
    // BoxStream is not Debug, so expect_err is unavailable; use match.
    let result = client.subscribe_events(&event_url, None).await;
    match result {
        Ok(_) => panic!("wrong Content-Type must fail before streaming starts"),
        Err(ref e) => assert!(
            matches!(e, ClientError::UnexpectedResponse(_)),
            "expected UnexpectedResponse for wrong Content-Type, got {e:?}"
        ),
    }
}

/// Oracle: regression for bd:JMAP-6lsm.2 — RFC 7231 §3.1.1.1 / RFC 9110 §8.3
/// say the media-type essence is bounded by ';', SP, HTAB, or end-of-string.
/// A naive `starts_with("text/event-stream")` accepts "text/event-streamish",
/// silently produces no events, and the caller sees an apparently-quiet
/// stream. The fix must reject the suffix-extension case before streaming
/// starts. The independent oracle is the spec; the test feeds a hand-written
/// invalid Content-Type that *would* have passed the old prefix check.
#[tokio::test]
async fn test_subscribe_events_rejects_event_stream_suffix() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/events"))
        .respond_with(
            ResponseTemplate::new(200)
                // Trailing "ish" makes the subtype "event-streamish", not
                // "event-stream". Pre-fix code would accept this.
                .insert_header("Content-Type", "text/event-streamish")
                .set_body_bytes(b"data: hi\n\n".to_vec()),
        )
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let event_url = format!("{}/events", server.uri());
    let result = client.subscribe_events(&event_url, None).await;
    match result {
        Ok(_) => panic!("text/event-streamish must be rejected, not silently accepted"),
        Err(ref e) => assert!(
            matches!(e, ClientError::UnexpectedResponse(_)),
            "expected UnexpectedResponse for streamish suffix, got {e:?}"
        ),
    }
}

/// Oracle: positive case for bd:JMAP-6lsm.2 — Content-Type with a parameter
/// like `text/event-stream; charset=utf-8` MUST be accepted (RFC 7231
/// §3.1.1.1 allows parameters after ';'). The bugfix splits on ';' or
/// whitespace and compares the essence; without that split, a parameterised
/// header would still pass the (now stricter) check, but pinning this case
/// keeps the boundary explicit so a future "tighten further" mistake doesn't
/// silently break parameterised media types.
#[tokio::test]
async fn test_subscribe_events_accepts_charset_parameter() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/events"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("Content-Type", "text/event-stream; charset=utf-8")
                // Single complete event so the stream returns Some(Ok(_)).
                .set_body_bytes(b"data: hi\n\n".to_vec()),
        )
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let event_url = format!("{}/events", server.uri());
    // Should construct the stream successfully even with the charset param.
    let _stream = client
        .subscribe_events(&event_url, None)
        .await
        .expect("subscribe_events must accept text/event-stream; charset=utf-8");
}

// ---------------------------------------------------------------------------
// extract_response
// ---------------------------------------------------------------------------

/// Oracle: RFC 8620 §3.4 — extract_response finds the matching invocation
/// by call_id and deserializes its arguments.
///
/// The assertion inspects the returned Value (bd:JMAP-6r7c.7), not just
/// the Result variant — a regression that returned Ok(Value::Null) or
/// stripped fields from the args payload would otherwise pass with the
/// weaker is_ok()-only check.
#[test]
fn test_extract_response_success() {
    let resp = jmap_types::JmapResponse::new(
        vec![(
            "Mailbox/get".to_owned(),
            serde_json::json!({"accountId": "A13824", "state": "s1", "list": [], "notFound": []}),
            "r1".to_owned(),
        )],
        "sess1".into(),
        None,
    );

    let val: serde_json::Value = jmap_base_client::client::extract_response(&resp, "r1")
        .expect("extract_response must succeed");
    let args = val
        .as_object()
        .expect("extract_response must return the args object verbatim");
    assert_eq!(
        args.get("accountId").and_then(|v| v.as_str()),
        Some("A13824"),
        "extract_response must preserve args.accountId from the invocation"
    );
    assert_eq!(
        args.get("state").and_then(|v| v.as_str()),
        Some("s1"),
        "extract_response must preserve args.state from the invocation"
    );
    assert!(
        args.contains_key("list"),
        "extract_response must preserve args.list (even when empty)"
    );
    assert!(
        args.contains_key("notFound"),
        "extract_response must preserve args.notFound (even when empty)"
    );
}

/// Oracle: RFC 8620 §3.4 — extract_response returns ClientError::MethodNotFound
/// when no invocation with the given call_id exists.
#[test]
fn test_extract_response_not_found() {
    let resp = jmap_types::JmapResponse::new(
        vec![(
            "Mailbox/get".to_owned(),
            serde_json::json!({}),
            "r1".to_owned(),
        )],
        "sess1".into(),
        None,
    );

    let err = jmap_base_client::client::extract_response::<serde_json::Value>(&resp, "r99")
        .expect_err("wrong call_id must fail");
    assert!(
        matches!(err, ClientError::MethodNotFound(_)),
        "expected MethodNotFound, got {err:?}"
    );
}

/// Oracle: RFC 8620 §3.6.1 — when an invocation has method name "error",
/// extract_response returns ClientError::MethodError with type and description.
#[test]
fn test_extract_response_method_error() {
    let resp = jmap_types::JmapResponse::new(
        vec![(
            "error".to_owned(),
            serde_json::json!({"type": "serverFail", "description": "oops"}),
            "r1".to_owned(),
        )],
        "sess1".into(),
        None,
    );

    let err = jmap_base_client::client::extract_response::<serde_json::Value>(&resp, "r1")
        .expect_err("error invocation must fail");
    assert!(
        matches!(
            &err,
            ClientError::MethodError { error_type, description }
                if error_type == "serverFail" && description.as_deref() == Some("oops")
        ),
        "expected MethodError{{serverFail, Some(\"oops\")}}, got {err:?}"
    );
}

/// Oracle: RFC 8620 §3.2 + §3.6.1 — when a server emits both a success
/// invocation and an "error" invocation under the same call_id, the error
/// MUST take precedence. Returning the success would silently lose the
/// failure indication. Independent oracle: hand-built JmapResponse with
/// the documented multi-invocation pattern from RFC 8620 §3.2 line 876–880.
#[test]
fn test_extract_response_error_after_success_takes_precedence() {
    let resp = jmap_types::JmapResponse::new(
        vec![
            (
                "Mailbox/get".to_owned(),
                serde_json::json!({
                    "accountId": "A1",
                    "state": "s1",
                    "list": [],
                    "notFound": []
                }),
                "r1".to_owned(),
            ),
            (
                "error".to_owned(),
                serde_json::json!({"type": "serverFail", "description": "implicit op failed"}),
                "r1".to_owned(),
            ),
        ],
        "sess1".into(),
        None,
    );

    let err = jmap_base_client::client::extract_response::<serde_json::Value>(&resp, "r1")
        .expect_err("error sibling must surface even with a success present");
    assert!(
        matches!(
            &err,
            ClientError::MethodError { error_type, .. } if error_type == "serverFail"
        ),
        "expected MethodError{{serverFail}}, got {err:?}"
    );
}

/// Oracle: RFC 8620 §5.8 example (lines 3158–3180) — a `Foo/copy` with
/// `onSuccessDestroyOriginal: true` produces both the primary `Foo/copy`
/// response and an implicit `Foo/set` response, both with the same call_id.
/// When all matching invocations are successes, extract_response returns
/// the FIRST one (the primary response). Independent oracle: spec example
/// JSON shape, hand-built here.
#[test]
fn test_extract_response_first_success_when_no_error() {
    let resp = jmap_types::JmapResponse::new(
        vec![
            (
                "Todo/copy".to_owned(),
                serde_json::json!({
                    "fromAccountId": "x",
                    "accountId": "y",
                    "created": {"k5122": {"id": "DAf97"}},
                    "oldState": "c1d64ecb038c",
                    "newState": "33844835152b"
                }),
                "0".to_owned(),
            ),
            (
                "Todo/set".to_owned(),
                serde_json::json!({
                    "accountId": "x",
                    "oldState": "871903",
                    "newState": "871909",
                    "destroyed": ["a"]
                }),
                "0".to_owned(),
            ),
        ],
        "sess1".into(),
        None,
    );

    let v = jmap_base_client::client::extract_response::<serde_json::Value>(&resp, "0")
        .expect("must succeed when all matches are successes");
    assert_eq!(
        v["fromAccountId"], "x",
        "primary (first) response must be the Todo/copy result, got {v}"
    );
    assert!(
        v.get("destroyed").is_none(),
        "must NOT be the Todo/set result (which has 'destroyed' but no 'fromAccountId')"
    );
}

/// Oracle: extension of the §3.2 multi-response rule — error precedence
/// applies even when the error appears after several successful matches.
/// Catches a regression where the implementation might short-circuit on
/// the first match.
#[test]
fn test_extract_response_error_after_multiple_successes() {
    let resp = jmap_types::JmapResponse::new(
        vec![
            (
                "Todo/copy".to_owned(),
                serde_json::json!({"fromAccountId": "x"}),
                "r1".to_owned(),
            ),
            (
                "Todo/set".to_owned(),
                serde_json::json!({"accountId": "x"}),
                "r1".to_owned(),
            ),
            (
                "error".to_owned(),
                serde_json::json!({"type": "rateLimit"}),
                "r1".to_owned(),
            ),
        ],
        "sess1".into(),
        None,
    );

    let err = jmap_base_client::client::extract_response::<serde_json::Value>(&resp, "r1")
        .expect_err("trailing error must take precedence over earlier successes");
    assert!(
        matches!(
            &err,
            ClientError::MethodError { error_type, .. } if error_type == "rateLimit"
        ),
        "expected MethodError{{rateLimit}}, got {err:?}"
    );
}

// ---------------------------------------------------------------------------
// download_blob — typed expected_sha256 integrity contract (bd:JMAP-6r7c.48)
// ---------------------------------------------------------------------------

/// Oracle: NIST FIPS 180-4 Appendix A, example 1 — SHA-256("abc") =
/// ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad.
/// The hex digest is hand-typed from the NIST publication; the test
/// server returns the literal three bytes "abc", and the typed
/// `jmap_cid_types::Sha256` is the caller-supplied integrity expectation.
/// A successful match means `download_blob` returns the bytes verbatim.
#[tokio::test]
async fn download_blob_with_typed_sha256_matches_succeeds() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/download/account1/blob-abc/file.bin"))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(b"abc".to_vec()))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    let expected = jmap_cid_types::Sha256::from_hex(
        "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
    )
    .expect("NIST oracle digest must parse as canonical Sha256");

    let template = jmap_base_client::JmapUrlTemplate::new(format!(
        "{}/download/{{accountId}}/{{blobId}}/{{name}}",
        server.uri()
    ));
    let bytes = client
        .download_blob(jmap_base_client::DownloadBlobParams {
            download_url_template: &template,
            account_id: "account1",
            blob_id: "blob-abc",
            name: "file.bin",
            accept_type: None,
            expected_sha256: Some(&expected),
        })
        .await
        .expect("integrity-matched download must succeed");
    assert_eq!(bytes.as_ref(), b"abc");
}

/// Oracle: a server returning bytes "abc" with a caller-supplied
/// `expected_sha256` that is canonical SHA-256("") — the empty-string
/// digest `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`
/// (RFC 6234, NIST CAVS) — must return
/// `ClientError::BlobIntegrityMismatch` with `expected` carrying the
/// caller's typed-canonical digest unchanged. The pre-bd:JMAP-6r7c.48
/// `&str` path applied `to_ascii_lowercase` before populating `expected`;
/// the typed path does not (the wrapper already enforces canonical
/// lowercase at construction). Asserting on the exact wire string locks
/// in the new contract.
#[tokio::test]
async fn download_blob_with_typed_sha256_mismatch_returns_integrity_error() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/download/account1/blob-abc/file.bin"))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(b"abc".to_vec()))
        .mount(&server)
        .await;

    let client = JmapClient::new(
        jmap_base_client::auth::DefaultTransport,
        NoneAuth,
        &server.uri(),
        jmap_base_client::client::ClientConfig::default(),
    )
    .expect("client construction must succeed");

    // SHA-256("") canonical — does not match SHA-256("abc").
    let empty_sha256_hex = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
    let expected = jmap_cid_types::Sha256::from_hex(empty_sha256_hex)
        .expect("RFC 6234 oracle digest must parse as canonical Sha256");

    let template = jmap_base_client::JmapUrlTemplate::new(format!(
        "{}/download/{{accountId}}/{{blobId}}/{{name}}",
        server.uri()
    ));
    let err = client
        .download_blob(jmap_base_client::DownloadBlobParams {
            download_url_template: &template,
            account_id: "account1",
            blob_id: "blob-abc",
            name: "file.bin",
            accept_type: None,
            expected_sha256: Some(&expected),
        })
        .await
        .expect_err("mismatched integrity check must fail");

    match err {
        ClientError::BlobIntegrityMismatch { expected, actual } => {
            assert_eq!(
                expected, empty_sha256_hex,
                "expected must carry the typed caller-supplied digest verbatim"
            );
            assert_eq!(
                actual, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
                "actual must be SHA-256(\"abc\") per NIST FIPS 180-4 Appendix A"
            );
        }
        other => panic!("expected BlobIntegrityMismatch, got {other:?}"),
    }
}