scp-node 0.1.0-beta.1

Application node composing relay, identity, and HTTP server for SCP
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
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
//! Dev API handlers for local development and diagnostics.
//!
//! Provides the `/scp/dev/v1` endpoint family: health, identity, relay
//! status, and context management. All requests require bearer token
//! authentication (spec section 18.10.2). The token is validated using
//! constant-time comparison to prevent timing side-channel attacks.
//!
//! ## Endpoints
//!
//! | Method | Path | Handler |
//! |--------|------|---------|
//! | GET | `/scp/dev/v1/health` | [`health_handler`] |
//! | GET | `/scp/dev/v1/identity` | [`identity_handler`] |
//! | GET | `/scp/dev/v1/relay/status` | [`relay_status_handler`] |
//! | GET | `/scp/dev/v1/contexts` | [`list_contexts_handler`] |
//! | GET | `/scp/dev/v1/contexts/{id}` | [`get_context_handler`] |
//! | POST | `/scp/dev/v1/contexts` | [`create_context_handler`] |
//! | DELETE | `/scp/dev/v1/contexts/{id}` | [`delete_context_handler`] |
//!
//! See spec section 18.10 for the full dev API specification.

use std::sync::Arc;

use axum::Json;
use axum::body::Body;
use axum::extract::rejection::JsonRejection;
use axum::extract::{Path, State};
use axum::http::{Request, StatusCode, header};
use axum::middleware::Next;
use axum::response::IntoResponse;
use serde::{Deserialize, Serialize};
use subtle::ConstantTimeEq;

use crate::error::ApiError;
use crate::http::NodeState;

// ---------------------------------------------------------------------------
// Bearer auth middleware
// ---------------------------------------------------------------------------

/// Axum middleware that validates bearer token authentication.
///
/// Extracts the `Authorization: Bearer <token>` header from incoming requests
/// and validates it against `expected_token` using constant-time comparison
/// (via [`subtle::ConstantTimeEq`]) to prevent timing side-channel attacks.
///
/// Returns HTTP 401 with a JSON error body if:
/// - The `Authorization` header is missing
/// - The header value is not in `Bearer <token>` format
/// - The provided token does not match the expected token
///
/// See spec section 18.10.2.
pub async fn bearer_auth_middleware(
    req: Request<Body>,
    next: Next,
    expected_token: String,
) -> impl IntoResponse {
    let auth_header = req
        .headers()
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok());

    match auth_header {
        // RFC 7235 §2.1: auth-scheme tokens are case-insensitive.
        Some(value) if value.len() > 7 && value[..7].eq_ignore_ascii_case("bearer ") => {
            let provided = &value[7..];
            if bool::from(provided.as_bytes().ct_eq(expected_token.as_bytes())) {
                next.run(req).await.into_response()
            } else {
                ApiError::unauthorized().into_response()
            }
        }
        _ => ApiError::unauthorized().into_response(),
    }
}

// ---------------------------------------------------------------------------
// Host header validation (DNS rebinding protection)
// ---------------------------------------------------------------------------

/// Allowed Host header values for the dev API.
///
/// The dev API is intended for localhost access only (spec section 18.10.1).
/// This middleware rejects requests whose `Host` header does not match a
/// localhost pattern, preventing DNS rebinding attacks where a malicious
/// website resolves to 127.0.0.1 and accesses the dev API through the browser.
const ALLOWED_HOSTS: &[&str] = &["localhost", "127.0.0.1", "[::1]"];

/// Returns true if the `Host` header value is a localhost address,
/// optionally followed by a port (e.g., `localhost:8080`, `127.0.0.1:3000`,
/// `[::1]:8080`).
///
/// Handles RFC 3986 bracket notation for IPv6 addresses — `[::1]:8080`
/// is correctly parsed as hostname `[::1]`, not split on internal colons.
fn is_localhost_host(host: &str) -> bool {
    // IPv6 bracket notation: [::1] or [::1]:port
    let hostname = if host.starts_with('[') {
        // Find the closing bracket; everything up to and including it is the host.
        host.find(']').map_or(host, |end| &host[..=end])
    } else {
        // IPv4 or hostname: split on first ':' to strip port.
        host.split(':').next().unwrap_or(host)
    };
    ALLOWED_HOSTS
        .iter()
        .any(|h| hostname.eq_ignore_ascii_case(h))
}

/// Axum middleware that rejects requests with non-localhost Host headers.
///
/// Prevents DNS rebinding attacks against the dev API (spec section 18.10.1).
/// Returns HTTP 403 if the Host header is missing or does not match a
/// localhost address.
pub async fn localhost_host_middleware(req: Request<Body>, next: Next) -> impl IntoResponse {
    let host = req
        .headers()
        .get(header::HOST)
        .and_then(|v| v.to_str().ok());

    match host {
        Some(h) if is_localhost_host(h) => next.run(req).await.into_response(),
        _ => {
            // No Host header or non-localhost Host — reject.
            ApiError::forbidden("forbidden: dev API only accessible via localhost").into_response()
        }
    }
}

// ---------------------------------------------------------------------------
// Security response headers
// ---------------------------------------------------------------------------

/// Axum middleware that sets security response headers on every dev API response.
///
/// Headers applied:
/// - `X-Content-Type-Options: nosniff` — prevents MIME sniffing
/// - `Cache-Control: no-store` — prevents caching of sensitive diagnostics
/// - `X-Frame-Options: DENY` — prevents clickjacking via iframe embedding
///
/// Also rejects CORS preflight (OPTIONS) requests with 403 Forbidden.
/// The dev API is localhost-only and must not be accessible cross-origin.
pub async fn security_headers_middleware(req: Request<Body>, next: Next) -> impl IntoResponse {
    // Reject CORS preflight requests explicitly.
    if req.method() == axum::http::Method::OPTIONS {
        return ApiError::forbidden("forbidden: CORS requests not allowed on dev API")
            .into_response();
    }

    let mut response = next.run(req).await;
    let headers = response.headers_mut();
    headers.insert(
        axum::http::header::X_CONTENT_TYPE_OPTIONS,
        axum::http::HeaderValue::from_static("nosniff"),
    );
    headers.insert(
        axum::http::header::CACHE_CONTROL,
        axum::http::HeaderValue::from_static("no-store"),
    );
    headers.insert(
        axum::http::header::X_FRAME_OPTIONS,
        axum::http::HeaderValue::from_static("DENY"),
    );
    response
}

// ---------------------------------------------------------------------------
// Response types
// ---------------------------------------------------------------------------

/// Response body for `GET /scp/dev/v1/health`.
///
/// Reports basic health metrics for the running node.
///
/// See spec section 18.10.3.
#[derive(Debug, Clone, Serialize)]
pub struct HealthResponse {
    /// Seconds since the node was started.
    pub uptime_seconds: u64,
    /// Total number of active relay connections across all IPs.
    pub relay_connections: u64,
    /// Storage subsystem status. Currently always `"ok"`.
    pub storage_status: String,
}

/// Response body for `GET /scp/dev/v1/identity`.
///
/// Returns the node operator's DID string and full DID document.
///
/// See spec section 18.10.3.
#[derive(Debug, Clone, Serialize)]
pub struct IdentityResponse {
    /// The operator's DID string (e.g., `did:dht:...`).
    pub did: String,
    /// The operator's full DID document, serialized as a JSON object.
    pub document: serde_json::Value,
}

/// Response body for `GET /scp/dev/v1/relay/status`.
///
/// Reports relay server status with real-time metrics from the
/// connection tracker and blob storage backend.
///
/// See spec section 18.10.3.
#[derive(Debug, Clone, Serialize)]
pub struct RelayStatusResponse {
    /// The address the relay server is bound to (e.g., `127.0.0.1:9000`).
    pub bound_addr: String,
    /// Total number of active connections across all IPs.
    pub active_connections: u64,
    /// Number of blobs currently stored in the blob storage backend.
    pub blob_count: u64,
}

/// Response body for context endpoints (`GET /scp/dev/v1/contexts` and
/// `GET /scp/dev/v1/contexts/{id}`).
///
/// Represents a registered broadcast context with its metadata. The `mode`
/// field is always `"broadcast"` in the current implementation.
///
/// See spec section 18.10.3.
#[derive(Debug, Clone, Serialize)]
pub struct ContextResponse {
    /// Context ID (hex-encoded).
    pub id: String,
    /// Human-readable context name (advisory, may be absent).
    pub name: Option<String>,
    /// Context mode. Currently always `"broadcast"`.
    pub mode: String,
    /// Number of active subscribers for this context's routing ID.
    pub subscriber_count: u64,
}

/// Request body for `POST /scp/dev/v1/contexts`.
///
/// Registers a new broadcast context. The `id` field is required; `name` is
/// an optional human-readable label.
///
/// See spec section 18.10.3.
#[derive(Debug, Clone, Deserialize)]
pub struct CreateContextRequest {
    /// Context ID (hex-encoded).
    pub id: String,
    /// Human-readable context name (advisory).
    pub name: Option<String>,
}

// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------

/// Handler for `GET /scp/dev/v1/health`.
///
/// Returns a [`HealthResponse`] with the node's uptime (computed from
/// [`NodeState::start_time`]), relay connection count, and storage status.
///
/// See spec section 18.10.3.
pub async fn health_handler(State(state): State<Arc<NodeState>>) -> impl IntoResponse {
    let uptime = state.start_time.elapsed().as_secs();
    let relay_connections = {
        let tracker = state.connection_tracker.read().await;
        tracker.values().sum::<usize>() as u64
    };

    (
        StatusCode::OK,
        Json(HealthResponse {
            uptime_seconds: uptime,
            relay_connections,
            storage_status: "ok".to_owned(),
        }),
    )
}

/// Handler for `GET /scp/dev/v1/identity`.
///
/// Returns an [`IdentityResponse`] with the node operator's DID string and
/// full DID document.
///
/// See spec section 18.10.3.
pub async fn identity_handler(State(state): State<Arc<NodeState>>) -> impl IntoResponse {
    let document = serde_json::to_value(&state.did_document)
        .unwrap_or_else(|_| serde_json::Value::String(state.did.clone()));

    (
        StatusCode::OK,
        Json(IdentityResponse {
            did: state.did.clone(),
            document,
        }),
    )
}

/// Handler for `GET /scp/dev/v1/relay/status`.
///
/// Returns a [`RelayStatusResponse`] with the relay's bound address, active
/// connection count from the shared connection tracker, and blob count
/// from the blob storage backend.
///
/// See spec section 18.10.3.
pub async fn relay_status_handler(State(state): State<Arc<NodeState>>) -> impl IntoResponse {
    use scp_transport::native::storage::BlobStorage as _;

    let active_connections = {
        let tracker = state.connection_tracker.read().await;
        tracker.values().sum::<usize>() as u64
    };
    let blob_count = state.blob_storage.count().await.unwrap_or(0) as u64;

    (
        StatusCode::OK,
        Json(RelayStatusResponse {
            bound_addr: state.relay_addr.to_string(),
            active_connections,
            blob_count,
        }),
    )
}

/// Returns the subscriber count for a hex-encoded context/routing ID.
///
/// Parses the hex string into a `[u8; 32]` routing ID and looks up the
/// number of subscriber entries in the subscription registry. Returns 0
/// if the hex is invalid or the routing ID has no subscribers.
async fn subscriber_count_for_context(state: &NodeState, hex_id: &str) -> u64 {
    let Ok(bytes) = hex::decode(hex_id) else {
        return 0;
    };
    let Ok(routing_id) = <[u8; 32]>::try_from(bytes) else {
        return 0;
    };
    let registry = state.subscription_registry.read().await;
    registry
        .get(&routing_id)
        .map_or(0, |entries| entries.len() as u64)
}

/// Handler for `GET /scp/dev/v1/contexts`.
///
/// Returns a JSON array of all registered broadcast contexts as
/// [`ContextResponse`] values. Returns an empty array when no contexts
/// are registered.
///
/// See spec section 18.10.3.
pub async fn list_contexts_handler(State(state): State<Arc<NodeState>>) -> impl IntoResponse {
    let snapshot: Vec<(String, Option<String>)> = {
        let contexts = state.broadcast_contexts.read().await;
        contexts
            .values()
            .map(|ctx| (ctx.id.clone(), ctx.name.clone()))
            .collect()
    };

    let mut responses = Vec::with_capacity(snapshot.len());
    for (id, name) in snapshot {
        let subscriber_count = subscriber_count_for_context(&state, &id).await;
        responses.push(ContextResponse {
            id,
            name,
            mode: "broadcast".to_owned(),
            subscriber_count,
        });
    }

    (StatusCode::OK, Json(responses))
}

/// Handler for `GET /scp/dev/v1/contexts/{id}`.
///
/// Returns the [`ContextResponse`] for the context matching the given `id`
/// path parameter. Returns HTTP 404 if no context with that ID is
/// registered.
///
/// See spec section 18.10.3.
pub async fn get_context_handler(
    State(state): State<Arc<NodeState>>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    let id = id.to_ascii_lowercase();
    let ctx_data = {
        let contexts = state.broadcast_contexts.read().await;
        contexts
            .get(&id)
            .map(|ctx| (ctx.id.clone(), ctx.name.clone()))
    };

    match ctx_data {
        None => ApiError::not_found(format!("context {id} not found")).into_response(),
        Some((ctx_id, ctx_name)) => {
            let subscriber_count = subscriber_count_for_context(&state, &ctx_id).await;
            (
                StatusCode::OK,
                Json(ContextResponse {
                    id: ctx_id,
                    name: ctx_name,
                    mode: "broadcast".to_owned(),
                    subscriber_count,
                }),
            )
                .into_response()
        }
    }
}

/// Maximum allowed length for a context ID (hex-encoded, so 64 chars for 32 bytes).
const MAX_CONTEXT_ID_LEN: usize = 64;
/// Maximum allowed length for a context name.
const MAX_CONTEXT_NAME_LEN: usize = 256;

/// Handler for `POST /scp/dev/v1/contexts`.
///
/// Parses a [`CreateContextRequest`] JSON body and registers a new
/// broadcast context. Returns HTTP 201 Created with the newly created
/// [`ContextResponse`].
///
/// Validates:
/// - `id` is non-empty, ASCII hex only, max 64 chars (32 bytes hex-encoded)
/// - `name` (if present) is max 256 chars, no control characters
/// - No duplicate context ID already registered
///
/// See spec section 18.10.3.
pub async fn create_context_handler(
    State(state): State<Arc<NodeState>>,
    body: Result<Json<CreateContextRequest>, JsonRejection>,
) -> impl IntoResponse {
    // Unwrap JSON body, mapping extraction failures to ApiError (spec §18.10.4).
    let Ok(Json(body)) = body else {
        return ApiError::bad_request("invalid JSON body").into_response();
    };

    // Validate context ID: non-empty, hex-only, bounded length.
    if body.id.is_empty() || body.id.len() > MAX_CONTEXT_ID_LEN {
        return ApiError::bad_request(format!(
            "context id must be 1-{MAX_CONTEXT_ID_LEN} characters"
        ))
        .into_response();
    }
    if !body.id.bytes().all(|b| b.is_ascii_hexdigit()) {
        return ApiError::bad_request("context id must contain only hex characters")
            .into_response();
    }

    // Normalize to lowercase so mixed-case hex values are not treated as distinct.
    let id = body.id.to_ascii_lowercase();

    // Validate context name if present: bounded length, no control chars.
    // Use chars().count() for correct Unicode character counting.
    if let Some(ref name) = body.name {
        if name.chars().count() > MAX_CONTEXT_NAME_LEN {
            return ApiError::bad_request(format!(
                "context name must be at most {MAX_CONTEXT_NAME_LEN} characters"
            ))
            .into_response();
        }
        if name.chars().any(char::is_control) {
            return ApiError::bad_request("context name must not contain control characters")
                .into_response();
        }
    }

    let mut contexts = state.broadcast_contexts.write().await;

    // Reject duplicate context IDs (compared against normalized lowercase).
    if contexts.contains_key(&id) {
        return ApiError::conflict(format!("context {id} already exists")).into_response();
    }

    // Enforce broadcast context limit (mirrors MAX_PROJECTED_CONTEXTS).
    if contexts.len() >= crate::MAX_BROADCAST_CONTEXTS {
        return ApiError::bad_request(format!(
            "broadcast context limit ({}) reached",
            crate::MAX_BROADCAST_CONTEXTS
        ))
        .into_response();
    }

    let ctx = crate::http::BroadcastContext {
        id: id.clone(),
        name: body.name,
    };
    // Newly created context starts with 0 subscribers.
    let response = ContextResponse {
        id: ctx.id.clone(),
        name: ctx.name.clone(),
        mode: "broadcast".to_owned(),
        subscriber_count: 0,
    };
    contexts.insert(id.clone(), ctx);
    drop(contexts);

    // Include Location header per HTTP semantics for 201 Created.
    let location = format!("/scp/dev/v1/contexts/{id}");
    let mut headers = axum::http::HeaderMap::new();
    if let Ok(val) = axum::http::HeaderValue::from_str(&location) {
        headers.insert(axum::http::header::LOCATION, val);
    }

    (StatusCode::CREATED, headers, Json(response)).into_response()
}

/// Handler for `DELETE /scp/dev/v1/contexts/{id}`.
///
/// Removes the broadcast context matching the given `id` path parameter.
/// Returns HTTP 204 No Content on success, or HTTP 404 if no context with
/// that ID is registered.
///
/// See spec section 18.10.3.
pub async fn delete_context_handler(
    State(state): State<Arc<NodeState>>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    let id = id.to_ascii_lowercase();
    let mut contexts = state.broadcast_contexts.write().await;

    if contexts.remove(&id).is_some() {
        StatusCode::NO_CONTENT.into_response()
    } else {
        ApiError::not_found(format!("context {id} not found")).into_response()
    }
}

// ---------------------------------------------------------------------------
// Router constructor
// ---------------------------------------------------------------------------

/// Returns an axum [`Router`] serving the dev API endpoints under
/// `/scp/dev/v1`.
///
/// All routes are protected by bearer token authentication. The `token`
/// parameter is the expected bearer token (format:
/// `scp_local_token_<32 hex chars>`). Requests without a valid
/// `Authorization: Bearer <token>` header receive HTTP 401.
///
/// See spec section 18.10.2.
/// Maximum request body size for the dev API (64 KiB).
/// Prevents unbounded memory allocation from oversized POST bodies.
const DEV_API_MAX_BODY_SIZE: usize = 64 * 1024;

pub fn dev_router(state: Arc<NodeState>, token: String) -> axum::Router {
    use axum::middleware;
    use axum::routing::get;

    let expected = token;
    axum::Router::new()
        .route("/scp/dev/v1/health", get(health_handler))
        .route("/scp/dev/v1/identity", get(identity_handler))
        .route("/scp/dev/v1/relay/status", get(relay_status_handler))
        .route(
            "/scp/dev/v1/contexts",
            get(list_contexts_handler).post(create_context_handler),
        )
        .route(
            "/scp/dev/v1/contexts/{id}",
            get(get_context_handler).delete(delete_context_handler),
        )
        .layer(axum::extract::DefaultBodyLimit::max(DEV_API_MAX_BODY_SIZE))
        // Axum layers are LIFO: last added = outermost = runs first.
        //
        // Execution order (outermost → innermost):
        //   1. Security headers — sets X-Content-Type-Options, Cache-Control,
        //      X-Frame-Options on ALL responses (including auth/host rejections),
        //      and rejects CORS preflight requests.
        //   2. Host check — cheapest rejection, prevents DNS rebinding.
        //   3. Bearer auth — validates token, rejects unauthorized requests.
        //   4. Body limit — enforces 64 KiB max on POST bodies.
        //   5. Route handlers.
        .layer(middleware::from_fn(move |req, next| {
            bearer_auth_middleware(req, next, expected.clone())
        }))
        .layer(middleware::from_fn(localhost_host_middleware))
        .layer(middleware::from_fn(security_headers_middleware))
        .with_state(state)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use std::collections::HashMap;
    use std::net::SocketAddr;
    use std::sync::Arc;
    use std::time::Instant;

    use axum::body::Body;
    use axum::http::{Request, StatusCode, header};
    use http_body_util::BodyExt;
    use scp_transport::native::storage::BlobStorageBackend;
    use tokio::sync::RwLock;
    use tower::ServiceExt;

    use crate::http::NodeState;

    use super::*;

    /// Valid bearer token used across all dev API tests.
    const TEST_TOKEN: &str = "scp_local_token_abcdef1234567890abcdef1234567890";

    /// Helper: creates an HTTP request builder with `Host: localhost` pre-set.
    /// All dev API test requests must include a localhost Host header for the
    /// DNS-rebinding protection middleware.
    fn localhost_request() -> axum::http::request::Builder {
        Request::builder().header(header::HOST, "localhost")
    }

    /// Creates a test `NodeState` with the given dev token.
    fn test_state(token: &str) -> Arc<NodeState> {
        Arc::new(NodeState {
            did: "did:dht:test123".to_owned(),
            relay_url: "wss://localhost/scp/v1".to_owned(),
            broadcast_contexts: RwLock::new(HashMap::new()),
            relay_addr: "127.0.0.1:9000".parse::<SocketAddr>().unwrap(),
            bridge_secret: zeroize::Zeroizing::new([0u8; 32]),
            dev_token: Some(token.to_owned()),
            dev_bind_addr: Some("127.0.0.1:9100".parse::<SocketAddr>().unwrap()),
            projected_contexts: RwLock::new(HashMap::new()),
            blob_storage: Arc::new(BlobStorageBackend::default()),
            relay_config: scp_transport::native::server::RelayConfig::default(),
            start_time: Instant::now(),
            http_bind_addr: SocketAddr::from(([0, 0, 0, 0], 8443)),
            shutdown_token: tokio_util::sync::CancellationToken::new(),
            cors_origins: None,
            projection_rate_limiter: scp_transport::relay::rate_limit::PublishRateLimiter::new(
                1000,
            ),
            tls_config: None,
            cert_resolver: None,
            did_document: scp_identity::document::DidDocument {
                context: vec!["https://www.w3.org/ns/did/v1".to_owned()],
                id: "did:dht:test123".to_owned(),
                verification_method: vec![],
                authentication: vec![],
                assertion_method: vec![],
                also_known_as: vec![],
                service: vec![],
            },
            connection_tracker: scp_transport::relay::rate_limit::new_connection_tracker(),
            subscription_registry: scp_transport::relay::subscription::new_registry(),
            acme_challenges: None,
            bridge_state: Arc::new(crate::bridge_handlers::BridgeState::new()),
        })
    }

    #[tokio::test]
    async fn valid_token_passes_middleware() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .uri("/scp/dev/v1/health")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert!(json.get("uptime_seconds").is_some());
        assert!(json.get("relay_connections").is_some());
        assert!(json.get("storage_status").is_some());
    }

    #[tokio::test]
    async fn invalid_token_returns_401() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .uri("/scp/dev/v1/health")
            .header(header::AUTHORIZATION, "Bearer wrong_token")
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"], "unauthorized");
        assert_eq!(json["code"], "UNAUTHORIZED");
    }

    #[tokio::test]
    async fn non_localhost_host_returns_403() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        // DNS rebinding: request with external Host header should be rejected.
        let req = Request::builder()
            .uri("/scp/dev/v1/health")
            .header(header::HOST, "evil.example.com")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "FORBIDDEN");
    }

    #[tokio::test]
    async fn ipv6_localhost_host_accepted() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        // [::1]:8080 is valid localhost — must not be rejected.
        let req = Request::builder()
            .uri("/scp/dev/v1/health")
            .header(header::HOST, "[::1]:8080")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn ipv6_localhost_host_without_port_accepted() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        // [::1] without port is also valid localhost.
        let req = Request::builder()
            .uri("/scp/dev/v1/health")
            .header(header::HOST, "[::1]")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn missing_header_returns_401() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .uri("/scp/dev/v1/health")
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"], "unauthorized");
        assert_eq!(json["code"], "UNAUTHORIZED");
    }

    #[tokio::test]
    async fn identity_handler_returns_did() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .uri("/scp/dev/v1/identity")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["did"], "did:dht:test123");
        assert!(json.get("document").is_some());
    }

    #[tokio::test]
    async fn relay_status_handler_returns_addr() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .uri("/scp/dev/v1/relay/status")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["bound_addr"], "127.0.0.1:9000");
        assert_eq!(json["active_connections"], 0);
        assert_eq!(json["blob_count"], 0);
    }

    #[tokio::test]
    async fn all_responses_are_json_content_type() {
        let token = TEST_TOKEN;
        let state = test_state(token);

        let paths = [
            "/scp/dev/v1/health",
            "/scp/dev/v1/identity",
            "/scp/dev/v1/relay/status",
        ];

        for path in paths {
            let router = dev_router(Arc::clone(&state), token.to_owned());
            let req = localhost_request()
                .uri(path)
                .header(header::AUTHORIZATION, format!("Bearer {token}"))
                .body(Body::empty())
                .unwrap();

            let resp = router.oneshot(req).await.unwrap();
            assert_eq!(resp.status(), StatusCode::OK, "path: {path}");

            let content_type = resp
                .headers()
                .get(header::CONTENT_TYPE)
                .expect("missing Content-Type header")
                .to_str()
                .unwrap();
            assert!(
                content_type.contains("application/json"),
                "path {path} has Content-Type: {content_type}"
            );
        }
    }

    // -- Context management endpoint tests --

    #[tokio::test]
    async fn list_contexts_returns_empty_array() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .uri("/scp/dev/v1/contexts")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json, serde_json::json!([]));
    }

    #[tokio::test]
    async fn list_contexts_returns_registered_contexts() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        state.broadcast_contexts.write().await.insert(
            "aa11bb22".to_owned(),
            crate::http::BroadcastContext {
                id: "aa11bb22".to_owned(),
                name: Some("Test Context".to_owned()),
            },
        );
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .uri("/scp/dev/v1/contexts")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let arr = json.as_array().unwrap();
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["id"], "aa11bb22");
        assert_eq!(arr[0]["name"], "Test Context");
        assert_eq!(arr[0]["mode"], "broadcast");
        assert_eq!(arr[0]["subscriber_count"], 0);
    }

    #[tokio::test]
    async fn get_context_returns_found() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        state.broadcast_contexts.write().await.insert(
            "abcdef01".to_owned(),
            crate::http::BroadcastContext {
                id: "abcdef01".to_owned(),
                name: Some("My Context".to_owned()),
            },
        );
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .uri("/scp/dev/v1/contexts/abcdef01")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["id"], "abcdef01");
        assert_eq!(json["name"], "My Context");
        assert_eq!(json["mode"], "broadcast");
        assert_eq!(json["subscriber_count"], 0);
    }

    #[tokio::test]
    async fn get_context_returns_404_for_unknown() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .uri("/scp/dev/v1/contexts/nonexistent")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "NOT_FOUND");
    }

    #[tokio::test]
    async fn create_context_returns_201() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(Arc::clone(&state), token.to_owned());

        let req = localhost_request()
            .method("POST")
            .uri("/scp/dev/v1/contexts")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(
                serde_json::to_string(&serde_json::json!({
                    "id": "cc33dd44",
                    "name": "New Context"
                }))
                .unwrap(),
            ))
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::CREATED);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["id"], "cc33dd44");
        assert_eq!(json["name"], "New Context");
        assert_eq!(json["mode"], "broadcast");
        assert_eq!(json["subscriber_count"], 0);

        // Verify context was actually stored
        let contexts = state.broadcast_contexts.read().await;
        assert_eq!(contexts.len(), 1);
        assert!(contexts.contains_key("cc33dd44"));
        drop(contexts);
    }

    #[tokio::test]
    async fn create_context_without_name() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .method("POST")
            .uri("/scp/dev/v1/contexts")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(r#"{"id":"ee55ff66"}"#))
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::CREATED);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["id"], "ee55ff66");
        assert!(json["name"].is_null());
    }

    #[tokio::test]
    async fn delete_context_returns_204() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        state.broadcast_contexts.write().await.insert(
            "d00aed".to_owned(),
            crate::http::BroadcastContext {
                id: "d00aed".to_owned(),
                name: None,
            },
        );
        let router = dev_router(Arc::clone(&state), token.to_owned());

        let req = localhost_request()
            .method("DELETE")
            .uri("/scp/dev/v1/contexts/d00aed")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::NO_CONTENT);

        // Verify context was removed
        assert!(state.broadcast_contexts.read().await.is_empty());
    }

    #[tokio::test]
    async fn delete_context_returns_404_for_unknown() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .method("DELETE")
            .uri("/scp/dev/v1/contexts/nonexistent")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "NOT_FOUND");
    }

    #[tokio::test]
    async fn context_endpoints_require_auth() {
        let token = TEST_TOKEN;
        let state = test_state(token);

        // Test all context endpoints without auth
        let uris_and_methods: Vec<(&str, &str)> = vec![
            ("GET", "/scp/dev/v1/contexts"),
            ("GET", "/scp/dev/v1/contexts/any-id"),
            ("DELETE", "/scp/dev/v1/contexts/any-id"),
        ];

        for (method, uri) in uris_and_methods {
            let router = dev_router(Arc::clone(&state), token.to_owned());
            let req = localhost_request()
                .method(method)
                .uri(uri)
                .body(Body::empty())
                .unwrap();

            let resp = router.oneshot(req).await.unwrap();
            assert_eq!(
                resp.status(),
                StatusCode::UNAUTHORIZED,
                "{method} {uri} should require auth"
            );
        }

        // POST with body but no auth
        let router = dev_router(Arc::clone(&state), token.to_owned());
        let req = localhost_request()
            .method("POST")
            .uri("/scp/dev/v1/contexts")
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(r#"{"id":"aabb0011"}"#))
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn create_context_rejects_non_hex_id() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .method("POST")
            .uri("/scp/dev/v1/contexts")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(r#"{"id":"not-valid-hex!"}"#))
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "BAD_REQUEST");
    }

    #[tokio::test]
    async fn create_context_rejects_empty_id() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .method("POST")
            .uri("/scp/dev/v1/contexts")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(r#"{"id":""}"#))
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn create_context_rejects_duplicate_id() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        state.broadcast_contexts.write().await.insert(
            "aabb0011".to_owned(),
            crate::http::BroadcastContext {
                id: "aabb0011".to_owned(),
                name: None,
            },
        );
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .method("POST")
            .uri("/scp/dev/v1/contexts")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(r#"{"id":"aabb0011"}"#))
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::CONFLICT);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "CONFLICT");
    }

    // -- Tests A-I: additional coverage for confirmed findings --

    /// Test A: Wrong bearer token returns 401 with correct error shape.
    #[tokio::test]
    async fn wrong_bearer_token_returns_401_with_error_shape() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .uri("/scp/dev/v1/health")
            .header(header::AUTHORIZATION, "Bearer wrong_token_here")
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

        let content_type = resp
            .headers()
            .get(header::CONTENT_TYPE)
            .expect("missing Content-Type on 401")
            .to_str()
            .unwrap();
        assert!(
            content_type.contains("application/json"),
            "401 response should be JSON, got: {content_type}"
        );

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["error"], "unauthorized");
        assert_eq!(json["code"], "UNAUTHORIZED");
    }

    /// Test B: Case-insensitive bearer scheme (RFC 7235 §2.1).
    #[tokio::test]
    async fn bearer_scheme_case_insensitive() {
        let token = TEST_TOKEN;
        let state = test_state(token);

        // lowercase "bearer"
        let router = dev_router(Arc::clone(&state), token.to_owned());
        let req = localhost_request()
            .uri("/scp/dev/v1/health")
            .header(header::AUTHORIZATION, format!("bearer {token}"))
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "lowercase 'bearer' should pass"
        );

        // uppercase "BEARER"
        let router = dev_router(Arc::clone(&state), token.to_owned());
        let req = localhost_request()
            .uri("/scp/dev/v1/health")
            .header(header::AUTHORIZATION, format!("BEARER {token}"))
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "uppercase 'BEARER' should pass"
        );

        // mixed case "BeArEr"
        let router = dev_router(Arc::clone(&state), token.to_owned());
        let req = localhost_request()
            .uri("/scp/dev/v1/health")
            .header(header::AUTHORIZATION, format!("BeArEr {token}"))
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "mixed case 'BeArEr' should pass"
        );
    }

    /// Test C: Non-bearer auth scheme returns 401.
    #[tokio::test]
    async fn non_bearer_auth_scheme_returns_401() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .uri("/scp/dev/v1/health")
            .header(header::AUTHORIZATION, "Basic dXNlcjpwYXNz")
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "UNAUTHORIZED");
    }

    /// Test D: Context ID exceeding `MAX_CONTEXT_ID_LEN` returns 400.
    #[tokio::test]
    async fn create_context_rejects_oversized_id() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let oversized_id = "a".repeat(MAX_CONTEXT_ID_LEN + 1);
        let body_json = serde_json::json!({ "id": oversized_id });

        let req = localhost_request()
            .method("POST")
            .uri("/scp/dev/v1/contexts")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(serde_json::to_string(&body_json).unwrap()))
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "BAD_REQUEST");
        assert!(
            json["error"]
                .as_str()
                .unwrap()
                .contains(&MAX_CONTEXT_ID_LEN.to_string()),
            "error message should mention the max length"
        );
    }

    /// Test E: Context name exceeding `MAX_CONTEXT_NAME_LEN` returns 400.
    #[tokio::test]
    async fn create_context_rejects_oversized_name() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let oversized_name = "a".repeat(MAX_CONTEXT_NAME_LEN + 1);
        let body_json = serde_json::json!({ "id": "aabb", "name": oversized_name });

        let req = localhost_request()
            .method("POST")
            .uri("/scp/dev/v1/contexts")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(serde_json::to_string(&body_json).unwrap()))
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "BAD_REQUEST");
        assert!(
            json["error"]
                .as_str()
                .unwrap()
                .contains(&MAX_CONTEXT_NAME_LEN.to_string()),
            "error message should mention the max length"
        );
    }

    /// Test F: Context name with control characters returns 400.
    #[tokio::test]
    async fn create_context_rejects_control_chars_in_name() {
        let token = TEST_TOKEN;
        let state = test_state(token);

        let names_with_control = [
            "name\x00with_null",
            "name\x1fwith_unit_sep",
            "\ttabbed",
            "new\nline",
        ];

        for bad_name in names_with_control {
            let router = dev_router(Arc::clone(&state), token.to_owned());
            let body_json = serde_json::json!({ "id": "aabb", "name": bad_name });

            let req = localhost_request()
                .method("POST")
                .uri("/scp/dev/v1/contexts")
                .header(header::AUTHORIZATION, format!("Bearer {token}"))
                .header(header::CONTENT_TYPE, "application/json")
                .body(Body::from(serde_json::to_string(&body_json).unwrap()))
                .unwrap();

            let resp = router.oneshot(req).await.unwrap();
            assert_eq!(
                resp.status(),
                StatusCode::BAD_REQUEST,
                "name with control char should be rejected: {bad_name:?}"
            );

            let body = resp.into_body().collect().await.unwrap().to_bytes();
            let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
            assert_eq!(json["code"], "BAD_REQUEST");
        }
    }

    /// Test G: Malformed JSON body returns 400 with JSON error (not plain text).
    #[tokio::test]
    async fn malformed_json_returns_400_with_json_body() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        // Send {"id": 42} -- number instead of string
        let req = localhost_request()
            .method("POST")
            .uri("/scp/dev/v1/contexts")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(r#"{"id": 42}"#))
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);

        let content_type = resp
            .headers()
            .get(header::CONTENT_TYPE)
            .expect("missing Content-Type on malformed JSON 400")
            .to_str()
            .unwrap();
        assert!(
            content_type.contains("application/json"),
            "malformed JSON error should be JSON, got: {content_type}"
        );

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "BAD_REQUEST");
        assert!(
            json.get("error").is_some(),
            "error response must include 'error' field"
        );
    }

    /// Test G (cont.): Completely invalid JSON returns 400 with JSON body.
    #[tokio::test]
    async fn invalid_json_syntax_returns_400_with_json_body() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .method("POST")
            .uri("/scp/dev/v1/contexts")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from("not json at all"))
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);

        let content_type = resp
            .headers()
            .get(header::CONTENT_TYPE)
            .expect("missing Content-Type")
            .to_str()
            .unwrap();
        assert!(
            content_type.contains("application/json"),
            "invalid JSON syntax error should be JSON, got: {content_type}"
        );

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "BAD_REQUEST");
    }

    /// Test H: Mixed-case hex context IDs are normalized to lowercase.
    #[tokio::test]
    async fn context_id_normalized_to_lowercase() {
        let token = TEST_TOKEN;
        let state = test_state(token);

        // Create context with uppercase ID.
        let router = dev_router(Arc::clone(&state), token.to_owned());
        let req = localhost_request()
            .method("POST")
            .uri("/scp/dev/v1/contexts")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(r#"{"id":"AABB","name":"Upper"}"#))
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::CREATED);

        // Response should contain normalized lowercase ID.
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(
            json["id"], "aabb",
            "created ID should be normalized to lowercase"
        );

        // GET /contexts/aabb should find it.
        let router = dev_router(Arc::clone(&state), token.to_owned());
        let req = localhost_request()
            .uri("/scp/dev/v1/contexts/aabb")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "lowercase lookup should find it"
        );

        // GET /contexts/AABB should also find it (lookup is normalized).
        let router = dev_router(Arc::clone(&state), token.to_owned());
        let req = localhost_request()
            .uri("/scp/dev/v1/contexts/AABB")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "uppercase lookup should also find it (normalized)"
        );

        // Creating with "aabb" should be rejected as duplicate.
        let router = dev_router(Arc::clone(&state), token.to_owned());
        let req = localhost_request()
            .method("POST")
            .uri("/scp/dev/v1/contexts")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(r#"{"id":"aabb"}"#))
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::CONFLICT,
            "lowercase duplicate of uppercase should conflict"
        );

        // DELETE /contexts/AaBb should work (normalized).
        let router = dev_router(Arc::clone(&state), token.to_owned());
        let req = localhost_request()
            .method("DELETE")
            .uri("/scp/dev/v1/contexts/AaBb")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::NO_CONTENT,
            "mixed-case delete should find the normalized ID"
        );
    }

    /// Sends a request and asserts the response has the expected status and
    /// `application/json` Content-Type (skipped for 204 No Content).
    async fn assert_json_content_type(
        state: &Arc<NodeState>,
        token: &str,
        method: &str,
        path: &str,
        body: Option<&str>,
        expected_status: StatusCode,
        desc: &str,
    ) {
        let router = dev_router(Arc::clone(state), token.to_owned());
        let mut builder = localhost_request()
            .method(method)
            .uri(path)
            .header(header::AUTHORIZATION, format!("Bearer {token}"));
        if body.is_some() {
            builder = builder.header(header::CONTENT_TYPE, "application/json");
        }
        let req = builder
            .body(body.map_or_else(Body::empty, |b| Body::from(b.to_owned())))
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), expected_status, "{desc}: wrong status");

        if expected_status != StatusCode::NO_CONTENT {
            let content_type = resp
                .headers()
                .get(header::CONTENT_TYPE)
                .unwrap_or_else(|| panic!("{desc}: missing Content-Type header"))
                .to_str()
                .unwrap();
            assert!(
                content_type.contains("application/json"),
                "{desc}: Content-Type should be JSON, got: {content_type}"
            );
        }
    }

    /// Test I (part 1): Success and error endpoints return JSON Content-Type.
    #[tokio::test]
    async fn success_endpoints_return_json_content_type() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        state.broadcast_contexts.write().await.insert(
            "deadbeef".to_owned(),
            crate::http::BroadcastContext {
                id: "deadbeef".to_owned(),
                name: Some("Test".to_owned()),
            },
        );

        let cases: &[(&str, &str, Option<&str>, StatusCode, &str)] = &[
            (
                "GET",
                "/scp/dev/v1/health",
                None,
                StatusCode::OK,
                "health 200",
            ),
            (
                "GET",
                "/scp/dev/v1/identity",
                None,
                StatusCode::OK,
                "identity 200",
            ),
            (
                "GET",
                "/scp/dev/v1/relay/status",
                None,
                StatusCode::OK,
                "relay status 200",
            ),
            (
                "GET",
                "/scp/dev/v1/contexts",
                None,
                StatusCode::OK,
                "list contexts 200",
            ),
            (
                "GET",
                "/scp/dev/v1/contexts/deadbeef",
                None,
                StatusCode::OK,
                "get context 200",
            ),
        ];

        for &(method, path, body, expected_status, desc) in cases {
            assert_json_content_type(&state, token, method, path, body, expected_status, desc)
                .await;
        }
    }

    /// Test I (part 2): Error responses and create/auth return JSON Content-Type.
    #[tokio::test]
    async fn error_and_create_endpoints_return_json_content_type() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        state.broadcast_contexts.write().await.insert(
            "deadbeef".to_owned(),
            crate::http::BroadcastContext {
                id: "deadbeef".to_owned(),
                name: Some("Test".to_owned()),
            },
        );

        let error_cases: &[(&str, &str, Option<&str>, StatusCode, &str)] = &[
            (
                "GET",
                "/scp/dev/v1/contexts/nonexistent",
                None,
                StatusCode::NOT_FOUND,
                "get 404",
            ),
            (
                "DELETE",
                "/scp/dev/v1/contexts/nonexistent",
                None,
                StatusCode::NOT_FOUND,
                "del 404",
            ),
            (
                "POST",
                "/scp/dev/v1/contexts",
                Some(r#"{"id":""}"#),
                StatusCode::BAD_REQUEST,
                "empty 400",
            ),
            (
                "POST",
                "/scp/dev/v1/contexts",
                Some(r#"{"id":"deadbeef"}"#),
                StatusCode::CONFLICT,
                "dup 409",
            ),
        ];

        for &(method, path, body, expected_status, desc) in error_cases {
            assert_json_content_type(&state, token, method, path, body, expected_status, desc)
                .await;
        }

        // POST 201 (create) -- separate because it changes state.
        assert_json_content_type(
            &state,
            token,
            "POST",
            "/scp/dev/v1/contexts",
            Some(r#"{"id":"cafe0001","name":"Test I"}"#),
            StatusCode::CREATED,
            "create 201",
        )
        .await;

        // Unauthenticated 401.
        let router = dev_router(Arc::clone(&state), token.to_owned());
        let req = localhost_request()
            .uri("/scp/dev/v1/health")
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED, "unauth 401");
        let content_type = resp
            .headers()
            .get(header::CONTENT_TYPE)
            .expect("unauth 401: missing Content-Type")
            .to_str()
            .unwrap();
        assert!(
            content_type.contains("application/json"),
            "unauth 401: Content-Type should be JSON, got: {content_type}"
        );
    }

    // -----------------------------------------------------------------------
    // Security headers
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn responses_include_security_headers() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = localhost_request()
            .uri("/scp/dev/v1/health")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        assert_eq!(
            resp.headers().get(header::X_CONTENT_TYPE_OPTIONS).unwrap(),
            "nosniff"
        );
        assert_eq!(
            resp.headers().get(header::CACHE_CONTROL).unwrap(),
            "no-store"
        );
        assert_eq!(resp.headers().get(header::X_FRAME_OPTIONS).unwrap(), "DENY");
    }

    #[tokio::test]
    async fn security_headers_on_error_responses() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        // 401 response should also have security headers.
        let req = localhost_request()
            .uri("/scp/dev/v1/health")
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(
            resp.headers().get(header::X_CONTENT_TYPE_OPTIONS).unwrap(),
            "nosniff"
        );
    }

    #[tokio::test]
    async fn cors_preflight_rejected() {
        let token = TEST_TOKEN;
        let state = test_state(token);
        let router = dev_router(state, token.to_owned());

        let req = Request::builder()
            .method(axum::http::Method::OPTIONS)
            .uri("/scp/dev/v1/health")
            .header(header::HOST, "localhost")
            .body(Body::empty())
            .unwrap();

        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "FORBIDDEN");
    }
}