ic-asset-router 0.1.1

File-based HTTP routing with IC response certification for Internet Computer canisters
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
//! Build full-stack web applications on the Internet Computer with file-based
//! routing conventions familiar from Next.js and SvelteKit — but in Rust,
//! compiled to a single canister. Drop a handler file into `src/routes/`,
//! deploy, and your endpoint is live with automatic response certification,
//! typed parameters, scoped middleware, and configurable security headers.
//!
//! # Features
//!
//! - **File-based routing** — `src/routes/` maps directly to URL paths.
//!   Dynamic segments (`_postId/`), catch-all wildcards (`all.rs`), dotted
//!   filenames (`og.png.rs` → `/og.png`), and nested directories all work
//!   out of the box. See [`build::generate_routes`].
//! - **IC response certification** — responses are automatically certified so
//!   boundary nodes can verify them. Choose from three certification modes
//!   (Skip, ResponseOnly, Full) per route or per asset. See
//!   [Certification Modes](#certification-modes) below.
//! - **Typed route context** — handlers receive a [`RouteContext`] with typed
//!   path params, typed search params, headers, body, and the full URL.
//! - **Scoped middleware** — place a `middleware.rs` in any directory to wrap
//!   all handlers below it. Middleware composes from root to leaf.
//!   See [`middleware::MiddlewareFn`].
//! - **Catch-all wildcards** — name a file `all.rs` to capture the remaining
//!   path. The matched tail is available as `ctx.wildcard`.
//! - **Custom 404 handler** — place a `not_found.rs` at the routes root to
//!   serve a styled error page instead of the default plain-text 404.
//! - **Security headers** — choose from [`SecurityHeaders::strict`],
//!   [`SecurityHeaders::permissive`], or [`SecurityHeaders::none`] presets,
//!   or configure individual headers.
//! - **Cache control & TTL** — set `Cache-Control` per asset type, configure
//!   TTL-based expiry via [`CacheConfig`], and invalidate cached responses
//!   with [`invalidate_path`], [`invalidate_prefix`], or
//!   [`invalidate_all_dynamic`].
//!
//! # Quick Start
//!
//! **1. Build script** — scans `src/routes/` and generates the route tree:
//!
//! ```rust,ignore
//! // build.rs
//! fn main() {
//!     ic_asset_router::build::generate_routes();
//! }
//! ```
//!
//! **2. Route handler** — a file in `src/routes/` with public `get`, `post`,
//! etc. functions:
//!
//! ```rust,ignore
//! // src/routes/index.rs
//! use ic_asset_router::{HttpResponse, RouteContext, StatusCode};
//! use std::borrow::Cow;
//!
//! pub fn get(_ctx: RouteContext<()>) -> HttpResponse<'static> {
//!     HttpResponse::builder()
//!         .with_status_code(StatusCode::OK)
//!         .with_headers(vec![(
//!             "content-type".to_string(),
//!             "text/html; charset=utf-8".to_string(),
//!         )])
//!         .with_body(Cow::<[u8]>::Owned(b"<h1>Hello from the IC!</h1>".to_vec()))
//!         .build()
//! }
//! ```
//!
//! **3. Canister wiring** — include the generated route tree and expose the
//! HTTP interface:
//!
//! ```rust,ignore
//! // src/lib.rs
//! mod route_tree {
//!     include!(concat!(env!("OUT_DIR"), "/__route_tree.rs"));
//! }
//!
//! fn setup() {
//!     route_tree::ROUTES.with(|routes| {
//!         ic_asset_router::setup(routes).build();
//!     });
//! }
//! ```
//!
//! See the [`examples/`](https://github.com/kristoferlund/ic-asset-router/tree/main/examples)
//! directory for complete, deployable canister projects including a
//! [React SPA](https://github.com/kristoferlund/ic-asset-router/tree/main/examples/react-app)
//! with TanStack Router/Query and per-route SEO meta tags.
//!
//! # Route Handlers
//!
//! Each `.rs` file in `src/routes/` is a route handler. Export one or more
//! public functions named after HTTP methods and the build script wires them
//! to the matching URL path automatically.
//!
//! ## Supported Methods
//!
//! Export any combination of `get`, `post`, `put`, `patch`, `delete`, `head`,
//! or `options` as `pub fn` from a single file. Private functions are ignored.
//! A file with no recognized public method function causes a build error.
//!
//! ## Handler Signature
//!
//! Every handler receives a [`RouteContext`] and returns an
//! [`HttpResponse<'static>`](HttpResponse). All types are re-exported from
//! `ic_asset_router` — no need to depend on `ic_http_certification` directly:
//!
//! ```rust,ignore
//! use ic_asset_router::{HttpResponse, RouteContext, StatusCode};
//! use std::borrow::Cow;
//!
//! pub fn get(_ctx: RouteContext<()>) -> HttpResponse<'static> {
//!     HttpResponse::builder()
//!         .with_status_code(StatusCode::OK)
//!         .with_headers(vec![("content-type".into(), "text/plain".into())])
//!         .with_body(Cow::<[u8]>::Owned(b"Hello!".to_vec()))
//!         .build()
//! }
//! ```
//!
//! The type parameter `P` in `RouteContext<P>` is the typed params struct
//! generated by the build script for routes with dynamic segments. Use `()`
//! for routes without dynamic segments.
//!
//! ## Multiple Methods in One File
//!
//! A single file can handle several HTTP methods. The library returns
//! `405 Method Not Allowed` with a correct `Allow` header for methods
//! that exist at the same path but weren't requested:
//!
//! ```rust,ignore
//! // src/routes/items/_itemId/index.rs
//! use ic_asset_router::{HttpResponse, RouteContext, StatusCode};
//!
//! pub fn get(ctx: RouteContext<Params>) -> HttpResponse<'static> {
//!     // GET /items/:itemId — retrieve
//!     # todo!()
//! }
//!
//! pub fn put(ctx: RouteContext<Params>) -> HttpResponse<'static> {
//!     // PUT /items/:itemId — update
//!     # todo!()
//! }
//!
//! pub fn delete(ctx: RouteContext<Params>) -> HttpResponse<'static> {
//!     // DELETE /items/:itemId — delete
//!     # todo!()
//! }
//!
//! use super::Params; // generated: pub struct Params { pub item_id: String }
//! ```
//!
//! ## What RouteContext Provides
//!
//! Handlers receive all request data through the context object:
//!
//! - `ctx.params` — typed path parameters (e.g. `ctx.params.post_id`)
//! - `ctx.search` — typed search (query string) params (default `()`)
//! - `ctx.query` — untyped query params (`HashMap<String, String>`)
//! - `ctx.method` — HTTP method
//! - `ctx.headers` — request headers
//! - `ctx.body` — raw request body bytes
//! - `ctx.url` — full request URL
//! - `ctx.wildcard` — catch-all wildcard tail (`Option<String>`)
//!
//! Convenience methods: [`ctx.header()`](RouteContext::header),
//! [`ctx.body_to_str()`](RouteContext::body_to_str),
//! [`ctx.json::<T>()`](RouteContext::json),
//! [`ctx.form::<T>()`](RouteContext::form),
//! [`ctx.form_data()`](RouteContext::form_data).
//!
//! See the [`json-api`](https://github.com/kristoferlund/ic-asset-router/tree/main/examples/json-api)
//! example for a complete REST API with GET, POST, PUT, and DELETE.
//!
//! # Middleware
//!
//! Place a `middleware.rs` file in any directory under `src/routes/` and it
//! wraps every handler in that directory and all subdirectories below it.
//! The file must export a `pub fn middleware` with the
//! [`MiddlewareFn`](middleware::MiddlewareFn) signature:
//!
//! ```rust,ignore
//! use ic_asset_router::{HttpRequest, HttpResponse, RouteParams};
//!
//! pub fn middleware(
//!     req: HttpRequest,
//!     params: &RouteParams,
//!     next: &dyn Fn(HttpRequest, &RouteParams) -> HttpResponse<'static>,
//! ) -> HttpResponse<'static> {
//!     // Before: inspect or modify the request
//!     let response = next(req, params);
//!     // After: inspect or modify the response
//!     response
//! }
//! ```
//!
//! Middleware can:
//!
//! - **Modify the request** — `req` is owned; construct or alter it before
//!   passing to `next`.
//! - **Modify the response** — capture the return value of `next` and
//!   transform headers, body, or status before returning.
//! - **Short-circuit** — return a response without calling `next` at all
//!   (e.g. return 401 for unauthorized requests). The handler never executes.
//!
//! ## Composition Order
//!
//! Middleware at different directory levels composes automatically in
//! root-to-leaf order. For a request to `/api/v2/data`:
//!
//! ```text
//! root middleware → /api middleware → /api/v2 middleware → handler
//! ```
//!
//! On the way back, responses unwind in reverse (onion model). Only one
//! middleware per directory is allowed. Middleware also wraps the custom
//! 404 handler — root-level middleware runs before `not_found.rs`.
//!
//! ## Example: CORS Middleware
//!
//! ```rust,ignore
//! use ic_asset_router::{HttpRequest, HttpResponse, RouteParams, StatusCode};
//!
//! pub fn middleware(
//!     req: HttpRequest,
//!     params: &RouteParams,
//!     next: &dyn Fn(HttpRequest, &RouteParams) -> HttpResponse<'static>,
//! ) -> HttpResponse<'static> {
//!     let cors_headers = vec![
//!         ("access-control-allow-origin".into(), "*".into()),
//!         ("access-control-allow-methods".into(), "GET, POST, PUT, DELETE, OPTIONS".into()),
//!         ("access-control-allow-headers".into(), "content-type".into()),
//!     ];
//!
//!     // Short-circuit: respond to OPTIONS preflight without running the handler
//!     if req.method().as_str() == "OPTIONS" {
//!         return HttpResponse::builder()
//!             .with_status_code(StatusCode::NO_CONTENT)
//!             .with_headers(cors_headers)
//!             .build();
//!     }
//!
//!     let response = next(req, params);
//!
//!     // Append CORS headers to the response
//!     let mut headers = response.headers().to_vec();
//!     headers.extend(cors_headers);
//!     HttpResponse::builder()
//!         .with_status_code(response.status_code())
//!         .with_headers(headers)
//!         .with_body(response.body().to_vec())
//!         .build()
//! }
//! ```
//!
//! See the [`json-api`](https://github.com/kristoferlund/ic-asset-router/tree/main/examples/json-api)
//! example for a working CORS middleware.
//!
//! # Certification Modes
//!
//! Every response served by an IC canister can be cryptographically certified
//! so that boundary nodes can verify it was not tampered with. This library
//! supports three certification modes, configurable per-route or per-asset:
//!
//! ## Choosing a Mode
//!
//! **Start with Response-Only (the default).** It is correct for 90% of
//! routes and requires zero configuration.
//!
//! | Mode | When to use | Example routes |
//! |------|-------------|----------------|
//! | **Response-only** | Same URL always returns same content | Static pages, blog posts, docs |
//! | **Skip** | Tampering has no security impact | Health checks, `/ping` |
//! | **Skip + handler auth** | Fast auth-gated API (query-path perf) | `/api/customers`, `/api/me` |
//! | **Authenticated** | Response depends on caller identity, must be tamper-proof | User profiles, dashboards |
//! | **Custom (Full)** | Response depends on specific headers/params | Content negotiation, pagination |
//!
//! ## Response-Only (Default)
//!
//! No attribute needed — just write your handler:
//!
//! ```rust,ignore
//! pub fn get(_ctx: RouteContext<()>) -> HttpResponse<'static> {
//!     // Automatically uses ResponseOnly certification
//!     HttpResponse::builder()
//!         .with_status_code(StatusCode::OK)
//!         .with_body(b"Hello!" as &[u8])
//!         .build()
//! }
//! ```
//!
//! The response body, status code, and headers are certified. The request
//! details are not included in the hash. This is sufficient when the
//! response depends only on the URL path and canister state.
//!
//! ## Skip Certification
//!
//! ```rust,ignore
//! #[route(certification = "skip")]
//! pub fn get(_ctx: RouteContext<()>) -> HttpResponse<'static> {
//!     // Handler runs on every query call — like a candid query
//!     HttpResponse::builder()
//!         .with_body(b"{\"status\":\"ok\"}" as &[u8])
//!         .build()
//! }
//! ```
//!
//! **Handler execution:** Skip-mode routes run the handler on every query
//! call, just like candid `query` calls. This makes them ideal for
//! auth-gated API endpoints — combine with handler-level auth (JWT
//! validation, `ic_cdk::caller()` checks) for fast (~200ms) authenticated
//! queries without waiting for consensus (~2s update calls).
//!
//! **Security note:** Skip certification provides the same trust level as
//! candid query calls — both trust the responding replica without
//! cryptographic verification by the boundary node. If candid queries are
//! acceptable for your application, skip certification is equally
//! acceptable.
//!
//! ### Skip + Handler Auth Pattern
//!
//! ```rust,ignore
//! #[route(certification = "skip")]
//! pub fn get(ctx: RouteContext<()>) -> HttpResponse<'static> {
//!     let caller = ic_cdk::caller();
//!     if caller == Principal::anonymous() {
//!         return HttpResponse::builder()
//!             .with_status_code(StatusCode::UNAUTHORIZED)
//!             .with_body(b"unauthorized" as &[u8])
//!             .build();
//!     }
//!     // Return caller-specific data
//!     HttpResponse::builder()
//!         .with_body(format!("hello {caller}").into_bytes())
//!         .build()
//! }
//! ```
//!
//! See the [`api-authentication`](https://github.com/kristoferlund/ic-asset-router/tree/main/examples/api-authentication)
//! example for a complete demonstration of both patterns.
//!
//! ## Authenticated (Full Certification Preset)
//!
//! ```rust,ignore
//! #[route(certification = "authenticated")]
//! pub fn get(_ctx: RouteContext<()>) -> HttpResponse<'static> {
//!     // Authorization header is included in certification
//!     // User A cannot receive User B's cached response
//!     HttpResponse::builder()
//!         .with_body(b"{\"name\":\"Alice\"}" as &[u8])
//!         .build()
//! }
//! ```
//!
//! The `authenticated` preset is a preconfigured Full mode that includes
//! the `Authorization` request header and `Content-Type` response header.
//!
//! ## Custom Full Certification
//!
//! ```rust,ignore
//! #[route(certification = custom(
//!     request_headers = ["accept"],
//!     query_params = ["page", "limit"]
//! ))]
//! pub fn get(_ctx: RouteContext<()>) -> HttpResponse<'static> {
//!     // Each combination of Accept + page + limit is independently certified
//!     HttpResponse::builder()
//!         .with_body(b"page content" as &[u8])
//!         .build()
//! }
//! ```
//!
//! ## Setup with Static Assets
//!
//! Configure and certify assets in a single builder chain during
//! `init`/`post_upgrade`:
//!
//! ```rust,ignore
//! use ic_asset_router::CertificationMode;
//!
//! route_tree::ROUTES.with(|routes| {
//!     ic_asset_router::setup(routes)
//!         .with_assets(&STATIC_DIR)                                   // response-only (default)
//!         .with_assets_certified(&PUBLIC_DIR, CertificationMode::skip()) // skip
//!         .build();
//! });
//! ```
//!
//! ## Performance Comparison
//!
//! | Mode | Relative cost | Witness size |
//! |------|---------------|--------------|
//! | Skip | ~0 | Minimal |
//! | Response-only | Low | ~200 bytes |
//! | Full (authenticated) | Medium | ~300 bytes |
//! | Full (custom) | Medium–High | ~300–500 bytes |
//!
//! ## Security Model: Certification vs Candid Calls
//!
//! IC canisters support two HTTP interfaces and two candid call types, each
//! with different trust assumptions:
//!
//! | Mechanism | Consensus | Boundary node verifies? | Trust model |
//! |-----------|-----------|------------------------|-------------|
//! | Candid **update** call | Yes (2s) | N/A | Consensus — response reflects agreed-upon state |
//! | Candid **query** call | No (200ms) | No | Trust the replica |
//! | HTTP + **ResponseOnly/Full** cert | Yes (2s) | Yes | Consensus — boundary node verifies the certificate |
//! | HTTP + **Skip** cert | No (200ms) | No | Trust the replica |
//!
//! **Key insight:** Skip certification and candid query calls have the same
//! trust model. Both execute on a single replica without consensus, and
//! neither response is cryptographically verified. If your application
//! already uses candid queries (as most IC apps do), skip certification
//! is equally acceptable for equivalent operations.
//!
//! ## Common Mistakes
//!
//! - **Over-certifying:** Certifying `User-Agent` causes cache
//!   fragmentation (every browser version gets a separate certificate).
//!   Only certify headers that affect the response content.
//! - **Under-certifying:** Using response-only for authenticated endpoints
//!   means a malicious replica can serve any cached response to any user.
//!   Use `#[route(certification = "authenticated")]` instead.
//! - **Certifying non-deterministic data:** If the response body changes
//!   every call (e.g., timestamps), the certificate is immediately stale.
//!   Use `skip` or add a TTL.

/// Debug logging macro gated behind the `debug-logging` feature flag.
/// When enabled, expands to `ic_cdk::println!`; otherwise compiles to nothing.
#[cfg(feature = "debug-logging")]
macro_rules! debug_log {
    ($($arg:tt)*) => { ic_cdk::println!($($arg)*) };
}

#[cfg(not(feature = "debug-logging"))]
macro_rules! debug_log {
    ($($arg:tt)*) => {};
}

use std::{borrow::Cow, cell::RefCell, rc::Rc};

use assets::get_asset_headers;
use ic_cdk::api::{certified_data_set, data_certificate};
use ic_http_certification::{
    utils::add_v2_certificate_header, DefaultCelBuilder, HttpCertification, HttpCertificationPath,
    HttpCertificationTree, HttpCertificationTreeEntry, CERTIFICATE_EXPRESSION_HEADER_NAME,
};
use router::{RouteNode, RouteResult};

/// Canonical path used to cache the single certified 404 response.
///
/// All not-found responses are certified and cached under this one path
/// instead of per-request-path, preventing memory growth from bot scans.
const NOT_FOUND_CANONICAL_PATH: &str = "/__not_found";

/// Extract the `content-type` header value from an HTTP response.
///
/// Performs a case-insensitive search for the `content-type` header.
/// Returns `"application/octet-stream"` if no content-type header is present.
fn extract_content_type(response: &HttpResponse) -> String {
    response
        .headers()
        .iter()
        .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
        .map(|(_, v)| v.clone())
        .unwrap_or_else(|| "application/octet-stream".to_string())
}

/// Build a 405 Method Not Allowed response with an `Allow` header listing the
/// permitted methods for the requested path.
fn method_not_allowed(allowed: &[Method]) -> HttpResponse<'static> {
    let allow = allowed
        .iter()
        .map(|m| m.as_str())
        .collect::<Vec<_>>()
        .join(", ");
    HttpResponse::builder()
        .with_status_code(StatusCode::METHOD_NOT_ALLOWED)
        .with_headers(vec![
            ("allow".to_string(), allow),
            ("content-type".to_string(), "text/plain".to_string()),
        ])
        .with_body(Cow::<[u8]>::Owned(b"Method Not Allowed".to_vec()))
        .build()
}

/// Build a plain-text error response for the given HTTP status code and message.
///
/// This avoids canister traps by returning a well-formed HTTP response instead
/// of panicking on malformed input or missing internal state.
fn error_response(status: u16, message: &str) -> HttpResponse<'static> {
    HttpResponse::builder()
        .with_status_code(StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR))
        .with_headers(vec![("content-type".to_string(), "text/plain".to_string())])
        .with_body(Cow::<[u8]>::Owned(message.as_bytes().to_vec()))
        .build()
}

/// Check whether a dynamic asset is expired, considering both the asset's own
/// TTL and the global [`CacheConfig`] fallback.
///
/// Returns `false` for static assets (they never expire) or when no TTL
/// applies.
fn is_asset_expired(asset: &asset_router::CertifiedAsset, path: &str, now_ns: u64) -> bool {
    if !asset.is_dynamic() {
        return false;
    }
    if asset.ttl.is_some() {
        return asset.is_expired(now_ns);
    }
    // Fall back to global config TTL.
    let effective_ttl = ROUTER_CONFIG.with(|c| c.borrow().cache_config.effective_ttl(path));
    match effective_ttl {
        Some(ttl) => {
            let expiry_ns = asset.certified_at.saturating_add(ttl.as_nanos() as u64);
            now_ns >= expiry_ns
        }
        None => false,
    }
}

/// Custom asset router with per-asset certification modes.
pub mod asset_router;
/// Static and dynamic asset certification, invalidation, and serving helpers.
pub mod assets;
/// Build-script utilities for file-based route generation.
pub mod build;
/// Certification mode configuration types.
pub mod certification;
/// Global configuration types: security headers, cache control, TTL settings.
pub mod config;
/// Request context types passed to route handlers.
pub mod context;
/// Middleware type definition.
pub mod middleware;
/// MIME type detection from file extensions.
pub mod mime;
/// Per-route configuration types (certification mode, TTL, headers).
pub mod route_config;
/// Route trie, handler types, and dispatch logic.
pub mod router;

pub use assets::{
    delete_assets, invalidate_all_dynamic, invalidate_path, invalidate_prefix, last_certified_at,
};
pub use certification::{CertificationMode, FullConfig, FullConfigBuilder, ResponseOnlyConfig};
pub use config::{AssetConfig, CacheConfig, CacheControl, SecurityHeaders};
pub use context::{
    deserialize_search_params, parse_form_body, parse_query, url_decode, FormBodyError,
    JsonBodyError, QueryParams, RouteContext,
};
pub use ic_asset_router_macros::route;
pub use ic_http_certification::{HttpRequest, HttpResponse, Method, StatusCode};
pub use route_config::RouteConfig;
pub use router::{HandlerResult, RouteParams};

thread_local! {
    static HTTP_TREE: Rc<RefCell<HttpCertificationTree>> = Default::default();
    static ASSET_ROUTER: RefCell<asset_router::AssetRouter> = RefCell::new(asset_router::AssetRouter::with_tree(HTTP_TREE.with(|tree| tree.clone())));
    static ROUTER_CONFIG: RefCell<AssetConfig> = RefCell::new(AssetConfig::default());
}

/// Set the global router configuration.
fn set_asset_config(config: AssetConfig) {
    ROUTER_CONFIG.with(|c| {
        *c.borrow_mut() = config;
    });
}

/// Register skip-certification tree entries for all routes configured with
/// [`CertificationMode::Skip`].
fn register_skip_routes(root_route_node: &router::RouteNode) {
    let skip_paths = root_route_node.skip_certified_paths();
    if skip_paths.is_empty() {
        return;
    }

    // Insert skip certification tree entries directly into the shared tree
    // WITHOUT storing a CertifiedAsset. This ensures the skip handler runs
    // on every query call instead of serving a cached empty response.
    HTTP_TREE.with(|tree| {
        let mut tree = tree.borrow_mut();
        for path in &skip_paths {
            let tree_path = HttpCertificationPath::exact(path.to_string());
            let certification = HttpCertification::skip();
            let tree_entry = HttpCertificationTreeEntry::new(tree_path, certification);
            tree.insert(&tree_entry);
        }
    });

    // Update the root hash to include the new skip entries.
    ASSET_ROUTER.with_borrow(|asset_router| {
        certified_data_set(asset_router.root_hash());
    });

    debug_log!("registered {} skip certification entries", skip_paths.len());
}

// ---------------------------------------------------------------------------
// Setup builder
// ---------------------------------------------------------------------------

/// Entry point for canister initialization. Returns a [`SetupBuilder`] that
/// configures the asset router, certifies assets, and registers skip routes
/// in a single fluent chain.
///
/// Call this during `init` and `post_upgrade`:
///
/// ```rust,ignore
/// use include_dir::{include_dir, Dir};
///
/// mod route_tree {
///     include!(concat!(env!("OUT_DIR"), "/__route_tree.rs"));
/// }
///
/// static ASSET_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/assets");
///
/// fn setup() {
///     route_tree::ROUTES.with(|routes| {
///         ic_asset_router::setup(routes)
///             .with_assets(&ASSET_DIR)
///             .build();
///     });
/// }
/// ```
pub fn setup(routes: &router::RouteNode) -> SetupBuilder<'_> {
    SetupBuilder {
        routes,
        config: None,
        asset_dirs: Vec::new(),
        delete_paths: Vec::new(),
    }
}

/// Builder for canister initialization. Created by [`setup()`].
///
/// Calling [`.build()`](SetupBuilder::build) executes the following steps
/// in order:
///
/// 1. Sets the global [`AssetConfig`] (or uses the default).
/// 2. Certifies each registered asset directory.
/// 3. Deletes any paths registered via [`delete_assets`](SetupBuilder::delete_assets).
/// 4. Registers skip-certification tree entries for all skip-mode routes.
/// 5. Calls `certified_data_set` with the final root hash.
pub struct SetupBuilder<'r> {
    routes: &'r router::RouteNode,
    config: Option<AssetConfig>,
    asset_dirs: Vec<(
        &'static include_dir::Dir<'static>,
        certification::CertificationMode,
    )>,
    delete_paths: Vec<&'static str>,
}

impl<'r> SetupBuilder<'r> {
    /// Override the default [`AssetConfig`].
    ///
    /// If not called, [`AssetConfig::default()`] is used.
    pub fn with_config(mut self, config: AssetConfig) -> Self {
        self.config = Some(config);
        self
    }

    /// Certify all files in `dir` with the default certification mode
    /// (response-only).
    pub fn with_assets(mut self, dir: &'static include_dir::Dir<'static>) -> Self {
        self.asset_dirs
            .push((dir, certification::CertificationMode::response_only()));
        self
    }

    /// Certify all files in `dir` with a specific [`CertificationMode`].
    pub fn with_assets_certified(
        mut self,
        dir: &'static include_dir::Dir<'static>,
        mode: certification::CertificationMode,
    ) -> Self {
        self.asset_dirs.push((dir, mode));
        self
    }

    /// Delete previously certified assets at the given paths.
    ///
    /// Useful when static assets (e.g. a SPA's `index.html`) should be
    /// replaced by dynamically generated responses with route-specific
    /// content (e.g. SEO meta tags).
    pub fn delete_assets(mut self, paths: Vec<&'static str>) -> Self {
        self.delete_paths.extend(paths);
        self
    }

    /// Execute the setup: apply config, certify assets, register skip
    /// routes, and commit the certification tree root hash.
    pub fn build(self) {
        // 1. Set config.
        set_asset_config(self.config.unwrap_or_default());

        // 2. Certify asset directories.
        for (dir, mode) in &self.asset_dirs {
            assets::certify_assets_with_mode(dir, mode.clone());
        }

        // 3. Delete specified asset paths.
        if !self.delete_paths.is_empty() {
            assets::delete_assets(self.delete_paths);
        }

        // 4. Register skip routes.
        register_skip_routes(self.routes);
    }
}

/// Options controlling the behavior of [`http_request`].
pub struct HttpRequestOptions {
    /// Whether to attempt serving a certified response from the asset router.
    ///
    /// When `true` (the default), the library checks the asset router for a
    /// previously certified response and returns it directly if available.
    /// When `false`, the handler runs on every request and the response is
    /// served with a skip-certification proof.
    pub certify: bool,
}

impl Default for HttpRequestOptions {
    fn default() -> Self {
        HttpRequestOptions { certify: true }
    }
}

/// Attach a skip-certification proof to a response.
///
/// Adds the CEL skip expression header, borrows the shared HTTP
/// certification tree, obtains the data certificate, constructs a
/// witness, and appends the v2 certificate header. On success the
/// response is modified in place. On failure (missing certificate or
/// witness error) an appropriate error response is returned in the
/// `Err` variant.
fn attach_skip_certification(
    path: &str,
    response: &mut HttpResponse<'static>,
) -> Result<(), HttpResponse<'static>> {
    response.add_header((
        CERTIFICATE_EXPRESSION_HEADER_NAME.to_string(),
        DefaultCelBuilder::skip_certification().to_string(),
    ));

    HTTP_TREE.with(|tree| {
        let tree = tree.borrow();

        let cert = data_certificate().ok_or_else(|| {
            error_response(500, "Internal Server Error: no data certificate available")
        })?;

        let tree_path = HttpCertificationPath::exact(path);
        let certification = HttpCertification::skip();
        let tree_entry = HttpCertificationTreeEntry::new(&tree_path, certification);

        let witness = tree.witness(&tree_entry, path).map_err(|_| {
            error_response(
                500,
                "Internal Server Error: failed to create certification witness",
            )
        })?;

        add_v2_certificate_header(&cert, response, &witness, &tree_path.to_expr_path());

        Ok(())
    })
}

/// Handle the `NotFound` branch of `http_request`.
///
/// When certification is enabled, checks the canonical `/__not_found` cache
/// entry: serves from cache if valid, upgrades if expired or missing. Also
/// tries serving a static asset for the original path before upgrading.
/// When certification is disabled, runs the not-found handler directly.
fn handle_not_found_query(
    req: HttpRequest,
    path: &str,
    root: &RouteNode,
    certify: bool,
) -> HttpResponse<'static> {
    if certify {
        // Check the unified AssetRouter for the canonical /__not_found entry.
        let canonical_state = ASSET_ROUTER.with_borrow(|asset_router| {
            asset_router
                .get_asset(NOT_FOUND_CANONICAL_PATH)
                .map(|asset| is_asset_expired(asset, NOT_FOUND_CANONICAL_PATH, ic_cdk::api::time()))
        });

        match canonical_state {
            Some(true) => {
                debug_log!("upgrading not-found (TTL expired for canonical path)");
                return HttpResponse::builder().with_upgrade(true).build();
            }
            Some(false) => {
                return ASSET_ROUTER.with_borrow(|asset_router| {
                    let cert = match data_certificate() {
                        Some(c) => c,
                        None => {
                            debug_log!("upgrading not-found (no data certificate)");
                            return HttpResponse::builder().with_upgrade(true).build();
                        }
                    };
                    if let Some((mut response, witness, expr_path)) = asset_router.serve_asset(&req)
                    {
                        add_v2_certificate_header(&cert, &mut response, &witness, &expr_path);
                        debug_log!("serving cached not-found for {}", path);
                        response
                    } else {
                        debug_log!("upgrading not-found (serve_asset failed for canonical path)");
                        HttpResponse::builder().with_upgrade(true).build()
                    }
                });
            }
            None => {
                // Try serving a static asset for the original path.
                let maybe_response = ASSET_ROUTER.with_borrow(|asset_router| {
                    let cert = data_certificate()?;
                    let (mut response, witness, expr_path) = asset_router.serve_asset(&req)?;
                    add_v2_certificate_header(&cert, &mut response, &witness, &expr_path);
                    Some(response)
                });
                if let Some(response) = maybe_response {
                    debug_log!("serving static asset for {}", path);
                    return response;
                }

                debug_log!("upgrading not-found (no cached entry for {})", path);
                return HttpResponse::builder().with_upgrade(true).build();
            }
        }
    }

    // Non-certified mode: execute the not-found handler directly.
    if let Some(response) = root.execute_not_found_with_middleware(path, req) {
        response
    } else {
        HttpResponse::not_found(
            b"Not Found",
            vec![("Content-Type".into(), "text/plain".into())],
        )
        .build()
    }
}

/// Serve from the asset router cache, or upgrade to an update call.
///
/// Checks the asset router for a cached certified response at `path`.
/// Returns the certified response if the asset exists and is not expired,
/// or an upgrade response (`upgrade: true`) if the asset is missing,
/// expired, or the data certificate is unavailable.
fn serve_from_cache_or_upgrade(req: &HttpRequest, path: &str) -> HttpResponse<'static> {
    enum CacheState {
        Missing,
        Expired,
        Valid,
    }

    let cache_state = ASSET_ROUTER.with_borrow(|asset_router| match asset_router.get_asset(path) {
        Some(asset) => {
            if is_asset_expired(asset, path, ic_cdk::api::time()) {
                CacheState::Expired
            } else {
                CacheState::Valid
            }
        }
        None => CacheState::Missing,
    });

    match cache_state {
        CacheState::Missing => {
            debug_log!("upgrading (no asset: {})", path);
            HttpResponse::builder().with_upgrade(true).build()
        }
        CacheState::Expired => {
            debug_log!("upgrading (TTL expired for {})", path);
            HttpResponse::builder().with_upgrade(true).build()
        }
        CacheState::Valid => ASSET_ROUTER.with_borrow(|asset_router| {
            let cert = match data_certificate() {
                Some(c) => c,
                None => {
                    debug_log!("upgrading (no data certificate)");
                    return HttpResponse::builder().with_upgrade(true).build();
                }
            };
            if let Some((mut response, witness, expr_path)) = asset_router.serve_asset(req) {
                add_v2_certificate_header(&cert, &mut response, &witness, &expr_path);
                debug_log!("serving directly");
                response
            } else {
                debug_log!("upgrading");
                HttpResponse::builder().with_upgrade(true).build()
            }
        }),
    }
}

/// Run the handler through the middleware chain and attach a
/// skip-certification proof to the response.
///
/// Used both when the caller opts out of certification globally
/// (`opts.certify == false`) and when a route is configured with
/// [`CertificationMode::Skip`].
fn serve_without_certification(
    root: &RouteNode,
    path: &str,
    handler: router::HandlerFn,
    req: HttpRequest,
    params: router::RouteParams,
) -> HttpResponse<'static> {
    debug_log!("serving {} without certification", path);
    let mut response = root.execute_with_middleware(path, handler, req, params);
    match attach_skip_certification(path, &mut response) {
        Ok(()) => response,
        Err(err_resp) => err_resp,
    }
}

/// Handle an HTTP query-path request.
///
/// This is the IC `http_request` entry point. It resolves the incoming
/// request against the route tree and either:
///
/// 1. Serves a previously certified response from the asset router, or
/// 2. Upgrades the request to an update call (returns `upgrade: true`) so
///    that the handler can run in `http_request_update` and certify a new
///    response.
///
/// Non-GET/HEAD requests are always upgraded. GET requests for dynamic
/// routes with expired TTLs are also upgraded.
pub fn http_request(
    req: HttpRequest,
    root_route_node: &RouteNode,
    opts: HttpRequestOptions,
) -> HttpResponse<'static> {
    debug_log!("http_request: {:?}", req.url());

    let path = match req.get_path() {
        Ok(p) => p,
        Err(_) => return error_response(400, "Bad Request: malformed URL"),
    };

    let method = req.method().clone();

    // Non-GET requests arriving at the query endpoint must be upgraded to an
    // update call so that state-mutating handlers execute in the update path.
    if method != Method::GET && method != Method::HEAD {
        debug_log!(
            "upgrading non-GET request ({}) to update call",
            method.as_str()
        );
        return HttpResponse::builder().with_upgrade(true).build();
    }

    match root_route_node.resolve(&path, &method) {
        RouteResult::Found(handler, params, _result_handler, pattern) => match opts.certify {
            false => serve_without_certification(root_route_node, &path, handler, req, params),
            true => {
                let route_config = root_route_node.get_route_config(&pattern);
                let cert_mode = route_config.map(|rc| &rc.certification);

                // Full mode binds proof to request headers — always upgrade.
                if matches!(cert_mode, Some(certification::CertificationMode::Full(_))) {
                    debug_log!("upgrading (full certification mode: {})", path);
                    return HttpResponse::builder().with_upgrade(true).build();
                }

                if matches!(cert_mode, Some(certification::CertificationMode::Skip)) {
                    return serve_without_certification(
                        root_route_node,
                        &path,
                        handler,
                        req,
                        params,
                    );
                }

                serve_from_cache_or_upgrade(&req, &path)
            }
        },
        RouteResult::MethodNotAllowed(allowed) => method_not_allowed(&allowed),
        RouteResult::NotFound => handle_not_found_query(req, &path, root_route_node, opts.certify),
    }
}

/// Certify a dynamically generated response and store it for future query-path
/// serving.
///
/// The response body is stored in the `AssetRouter` via `certify_asset()`,
/// which lets the query path use `serve_asset()`. All responses — including
/// not-found handler output — go through this single path. The not-found
/// Certify a dynamically generated response and store it for future query-path
/// serving.
///
/// The response body is stored in the `AssetRouter` via `certify_asset()`,
/// which lets the query path use `serve_asset()`. All responses — including
/// not-found handler output — go through this single path. The not-found
/// handler's response is certified at the canonical `/__not_found` path so
/// that only one cache entry exists for all 404s.
///
/// When `fallback_for` is `Some`, the asset is registered as a fallback
/// for the given scope. This is used by the not-found handler to certify
/// a single `/__not_found` asset that serves as a fallback for all paths.
///
/// The `mode` parameter controls how the response is certified:
/// - `Skip` / `ResponseOnly` — uses `certify_asset()` (no request needed).
/// - `Full` — uses `certify_dynamic_asset()` with the original request.
///
/// The `request` parameter is required for `Full` mode and ignored otherwise.
fn certify_dynamic_response_with_ttl(
    response: HttpResponse<'static>,
    path: &str,
    fallback_for: Option<String>,
    mode: certification::CertificationMode,
    request: Option<&HttpRequest>,
    ttl_override: Option<std::time::Duration>,
) -> HttpResponse<'static> {
    let content_type = extract_content_type(&response);
    let effective_ttl = ttl_override
        .or_else(|| ROUTER_CONFIG.with(|c| c.borrow().cache_config.effective_ttl(path)));

    let dynamic_cache_control =
        ROUTER_CONFIG.with(|c| c.borrow().cache_control.dynamic_assets.clone());

    let config = asset_router::AssetCertificationConfig {
        mode: mode.clone(),
        content_type: Some(content_type),
        status_code: response.status_code(),
        headers: get_asset_headers(vec![("cache-control".to_string(), dynamic_cache_control)]),
        encodings: vec![],
        fallback_for,
        aliases: vec![],
        certified_at: ic_cdk::api::time(),
        ttl: effective_ttl,
        dynamic: true,
    };

    let certified = ASSET_ROUTER.with_borrow_mut(|asset_router| {
        // Delete any existing asset at this path before re-certifying.
        asset_router.delete_asset(path);

        match &mode {
            certification::CertificationMode::Full(_) => {
                // Full mode requires the original request for certification.
                let req = match request {
                    Some(r) => r,
                    None => {
                        debug_log!(
                            "certify_dynamic_response_with_ttl: Full certification mode \
                             requires the original request, but none was provided for path '{}'. \
                             Returning uncertified response.",
                            path
                        );
                        return false;
                    }
                };
                if let Err(_err) = asset_router.certify_dynamic_asset(path, req, &response, config)
                {
                    debug_log!(
                        "certify_dynamic_response_with_ttl: failed to certify dynamic asset \
                         (full) for path '{}': {}. Returning uncertified response.",
                        path,
                        _err
                    );
                    return false;
                }
            }
            _ => {
                // Skip and ResponseOnly modes use certify_asset.
                if let Err(_err) =
                    asset_router.certify_asset(path, response.body().to_vec(), config)
                {
                    debug_log!(
                        "certify_dynamic_response_with_ttl: failed to certify dynamic asset \
                         for path '{}': {}. Returning uncertified response.",
                        path,
                        _err
                    );
                    return false;
                }
            }
        }

        certified_data_set(asset_router.root_hash());
        true
    });

    if !certified {
        debug_log!(
            "certify_dynamic_response_with_ttl: certification failed for path '{}', \
             serving uncertified response",
            path
        );
    }

    response
}

/// Handle the `NotFound` branch of `http_request_update`.
///
/// Checks the canonical `/__not_found` cache entry. If a valid (non-expired)
/// cached 404 exists, serves it directly. Otherwise, executes the not-found
/// handler through the middleware chain, certifies the response at the
/// canonical path as a fallback, and caches it.
fn handle_not_found_update(
    req: HttpRequest,
    path: &str,
    root: &RouteNode,
) -> HttpResponse<'static> {
    let cached_valid = ASSET_ROUTER.with_borrow(|asset_router| {
        match asset_router.get_asset(NOT_FOUND_CANONICAL_PATH) {
            Some(asset) => !is_asset_expired(asset, NOT_FOUND_CANONICAL_PATH, ic_cdk::api::time()),
            None => false,
        }
    });

    if cached_valid {
        debug_log!("not-found canonical entry still valid, serving from cache");
        return ASSET_ROUTER.with_borrow(|asset_router| {
            let canonical_req = HttpRequest::get(NOT_FOUND_CANONICAL_PATH.to_string()).build();
            match asset_router.serve_asset(&canonical_req) {
                Some((resp, _witness, _expr_path)) => resp,
                None => error_response(
                    500,
                    "Internal Server Error: cached not-found entry missing from asset router",
                ),
            }
        });
    }

    // Execute the not-found handler and certify at the canonical path.
    let response = if let Some(response) = root.execute_not_found_with_middleware(path, req) {
        response
    } else {
        HttpResponse::not_found(
            b"Not Found",
            vec![("Content-Type".into(), "text/plain".into())],
        )
        .build()
    };
    certify_dynamic_response_with_ttl(
        response,
        NOT_FOUND_CANONICAL_PATH,
        Some("/".to_string()),
        certification::CertificationMode::response_only(),
        None,
        None,
    )
}

/// Handle a `HandlerResult::NotModified` result in the update path.
///
/// Resets the TTL timer on the cached asset (if TTL-based caching is active),
/// then serves the existing cached response from the asset router.
fn handle_not_modified(req: &HttpRequest, path: &str) -> HttpResponse<'static> {
    debug_log!("handler returned NotModified for {}", path);

    // Reset the certified_at timestamp so the TTL timer restarts.
    ASSET_ROUTER.with_borrow_mut(|asset_router| {
        if let Some(asset) = asset_router.get_asset_mut(path) {
            if asset.ttl.is_some() {
                asset.certified_at = ic_cdk::api::time();
            }
        }
    });

    // Serve the existing cached response from the asset router.
    ASSET_ROUTER.with_borrow(|asset_router| match asset_router.serve_asset(req) {
        Some((mut resp, witness, expr_path)) => {
            if let Some(cert) = data_certificate() {
                add_v2_certificate_header(&cert, &mut resp, &witness, &expr_path);
            }
            resp
        }
        None => error_response(
            500,
            "Internal Server Error: NotModified but no cached asset found",
        ),
    })
}

/// Handle an HTTP update-path request.
///
/// This is the IC `http_request_update` entry point. It runs the matched
/// route handler (through the middleware chain), certifies the response in
/// the asset router, and caches it for future query-path serving.
///
/// If a [`HandlerResultFn`](router::HandlerResultFn) is registered for the
/// route, it is called first to check for [`HandlerResult::NotModified`].
/// A `NotModified` result preserves the existing cached response and resets
/// the TTL timer (if TTL-based caching is active).
pub fn http_request_update(req: HttpRequest, root_route_node: &RouteNode) -> HttpResponse<'static> {
    debug_log!("http_request_update: {:?}", req.url());

    let path = match req.get_path() {
        Ok(p) => p,
        Err(_) => return error_response(400, "Bad Request: malformed URL"),
    };

    let method = req.method().clone();

    match root_route_node.resolve(&path, &method) {
        RouteResult::Found(handler, params, result_handler, pattern) => {
            let route_config = root_route_node.get_route_config(&pattern);
            let cert_mode = route_config
                .map(|rc| rc.certification.clone())
                .unwrap_or_else(certification::CertificationMode::response_only);
            let route_ttl = route_config.and_then(|rc| rc.ttl);

            // Skip-mode routes are handled on the query path; if one arrives
            // here (stale upgrade), just run the handler without re-certifying.
            if matches!(&cert_mode, certification::CertificationMode::Skip) {
                debug_log!("skip mode in update path (unexpected): {}", path);
                return root_route_node.execute_with_middleware(&path, handler, req, params);
            }

            // Check for NotModified before running the full pipeline.
            if let Some(result_fn) = result_handler {
                match result_fn(req.clone(), params.clone()) {
                    router::HandlerResult::NotModified => {
                        return handle_not_modified(&req, &path);
                    }
                    router::HandlerResult::Response(response) => {
                        return certify_dynamic_response_with_ttl(
                            response,
                            &path,
                            None,
                            cert_mode,
                            Some(&req),
                            route_ttl,
                        );
                    }
                }
            }

            // Standard path: call handler through middleware, then certify.
            let response =
                root_route_node.execute_with_middleware(&path, handler, req.clone(), params);
            certify_dynamic_response_with_ttl(
                response,
                &path,
                None,
                cert_mode,
                Some(&req),
                route_ttl,
            )
        }
        RouteResult::MethodNotAllowed(allowed) => method_not_allowed(&allowed),
        RouteResult::NotFound => handle_not_found_update(req, &path, root_route_node),
    }
}

// Test coverage audit (Session 7, Spec 5.5):
//
// Covered:
//   - Malformed URL → 400 response (both http_request and http_request_update)
//   - Handler without content-type doesn't panic
//   - extract_content_type: JSON, HTML, missing (fallback to octet-stream), case-insensitive
//
// No significant gaps for unit-testable code. IC runtime-dependent paths
// (certification, asset serving, TTL upgrade, NotModified flow) require PocketIC
// E2E tests (spec 5.7).
#[cfg(test)]
mod tests {
    use super::*;
    use ic_http_certification::Method;
    use router::{NodeType, RouteNode, RouteParams};
    use std::time::Duration;

    fn noop_handler(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
        HttpResponse::builder()
            .with_status_code(StatusCode::OK)
            .with_body(b"ok" as &[u8])
            .build()
    }

    fn setup_router() -> RouteNode {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/", Method::GET, noop_handler);
        root.insert("/*", Method::GET, noop_handler);
        root
    }

    // ---- 1.3.5: malformed URL returns 400 (not a trap) ----

    #[test]
    fn http_request_malformed_url_returns_400() {
        let root = setup_router();
        // Construct a request with a URL that will fail `get_path()` parsing.
        // A bare NUL byte in the URL makes the URI parser fail.
        let req = HttpRequest::builder()
            .with_method(Method::GET)
            .with_url("http://[::bad")
            .build();
        let opts = HttpRequestOptions { certify: false };
        let response = http_request(req, &root, opts);
        assert_eq!(response.status_code(), StatusCode::BAD_REQUEST);
        assert!(std::str::from_utf8(response.body())
            .unwrap()
            .contains("malformed URL"));
    }

    #[test]
    fn http_request_update_malformed_url_returns_400() {
        let root = setup_router();
        let req = HttpRequest::builder()
            .with_method(Method::GET)
            .with_url("http://[::bad")
            .build();
        let response = http_request_update(req, &root);
        assert_eq!(response.status_code(), StatusCode::BAD_REQUEST);
        assert!(std::str::from_utf8(response.body())
            .unwrap()
            .contains("malformed URL"));
    }

    // ---- 1.3.6: missing content-type in handler response doesn't trap ----

    fn handler_no_content_type(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
        // Response with no content-type header — should not cause the library to trap.
        HttpResponse::builder()
            .with_status_code(StatusCode::OK)
            .with_body(b"no content-type" as &[u8])
            .build()
    }

    #[test]
    fn handler_without_content_type_does_not_trap() {
        // This test verifies that a handler returning a response without a
        // content-type header does not cause a panic. The http_request_update
        // function calls IC runtime APIs (certify_assets, certified_data_set)
        // that are unavailable in unit tests, so we test the handler directly
        // and verify the router dispatch path up to the handler call.
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/no-ct", Method::GET, handler_no_content_type);

        // Verify the route matches and the handler runs without panic.
        let req = HttpRequest::builder()
            .with_method(Method::GET)
            .with_url("/no-ct")
            .build();
        match root.resolve("/no-ct", &Method::GET) {
            RouteResult::Found(handler, params, _, _) => {
                let response = handler(req, params);
                assert_eq!(response.status_code(), StatusCode::OK);
                assert_eq!(response.body(), b"no content-type");
                // No content-type header present — and no panic occurred.
                assert!(response
                    .headers()
                    .iter()
                    .all(|(name, _): &(String, String)| name.to_lowercase() != "content-type"));
            }
            _ => panic!("expected Found for GET /no-ct"),
        }
    }

    // ---- 1.2: handler-controlled response metadata ----

    #[test]
    fn extract_content_type_json() {
        let response = HttpResponse::builder()
            .with_status_code(StatusCode::OK)
            .with_headers(vec![(
                "content-type".to_string(),
                "application/json".to_string(),
            )])
            .with_body(b"{}" as &[u8])
            .build();
        assert_eq!(extract_content_type(&response), "application/json");
    }

    #[test]
    fn extract_content_type_html() {
        let response = HttpResponse::builder()
            .with_status_code(StatusCode::OK)
            .with_headers(vec![("Content-Type".to_string(), "text/html".to_string())])
            .with_body(b"<h1>hi</h1>" as &[u8])
            .build();
        assert_eq!(extract_content_type(&response), "text/html");
    }

    #[test]
    fn extract_content_type_missing_falls_back() {
        let response = HttpResponse::builder()
            .with_status_code(StatusCode::OK)
            .with_body(b"raw bytes" as &[u8])
            .build();
        assert_eq!(extract_content_type(&response), "application/octet-stream");
    }

    #[test]
    fn extract_content_type_case_insensitive() {
        let response = HttpResponse::builder()
            .with_status_code(StatusCode::OK)
            .with_headers(vec![("CONTENT-TYPE".to_string(), "text/plain".to_string())])
            .with_body(b"hello" as &[u8])
            .build();
        assert_eq!(extract_content_type(&response), "text/plain");
    }

    // ---- 8.6.5: is_asset_expired unit tests ----

    fn make_asset_router() -> asset_router::AssetRouter {
        let tree = std::rc::Rc::new(std::cell::RefCell::new(
            ic_http_certification::HttpCertificationTree::default(),
        ));
        asset_router::AssetRouter::with_tree(tree)
    }

    /// Dynamic asset with own TTL — not expired when now < certified_at + TTL.
    #[test]
    fn asset_with_own_ttl_not_expired() {
        let mut router = make_asset_router();
        let config = asset_router::AssetCertificationConfig {
            certified_at: 1_000_000,
            ttl: Some(Duration::from_secs(3600)),
            dynamic: true,
            ..Default::default()
        };
        router
            .certify_asset("/page", b"content".to_vec(), config)
            .unwrap();
        let asset = router.get_asset("/page").unwrap();

        let one_hour_ns: u64 = 3_600_000_000_000;
        assert!(!is_asset_expired(
            asset,
            "/page",
            1_000_000 + one_hour_ns - 1
        ));
    }

    /// Dynamic asset with own TTL — expired when now >= certified_at + TTL.
    #[test]
    fn asset_with_own_ttl_expired() {
        let mut router = make_asset_router();
        let config = asset_router::AssetCertificationConfig {
            certified_at: 1_000_000,
            ttl: Some(Duration::from_secs(3600)),
            dynamic: true,
            ..Default::default()
        };
        router
            .certify_asset("/page", b"content".to_vec(), config)
            .unwrap();
        let asset = router.get_asset("/page").unwrap();

        let one_hour_ns: u64 = 3_600_000_000_000;
        // At expiry boundary.
        assert!(is_asset_expired(asset, "/page", 1_000_000 + one_hour_ns));
        // After expiry.
        assert!(is_asset_expired(
            asset,
            "/page",
            1_000_000 + one_hour_ns + 1
        ));
    }

    /// Dynamic asset without own TTL falls back to global config.
    #[test]
    fn asset_without_ttl_uses_global_config() {
        let mut router = make_asset_router();
        let config = asset_router::AssetCertificationConfig {
            certified_at: 1_000_000,
            ttl: None,
            dynamic: true,
            ..Default::default()
        };
        router
            .certify_asset("/page", b"content".to_vec(), config)
            .unwrap();
        let asset = router.get_asset("/page").unwrap();

        // Set global config with a 1-hour default TTL.
        ROUTER_CONFIG.with(|c| {
            c.borrow_mut().cache_config.default_ttl = Some(Duration::from_secs(3600));
        });

        let one_hour_ns: u64 = 3_600_000_000_000;
        // Before expiry.
        assert!(!is_asset_expired(
            asset,
            "/page",
            1_000_000 + one_hour_ns - 1
        ));
        // At expiry.
        assert!(is_asset_expired(asset, "/page", 1_000_000 + one_hour_ns));

        // Clean up thread-local.
        ROUTER_CONFIG.with(|c| {
            c.borrow_mut().cache_config.default_ttl = None;
        });
    }

    /// Dynamic asset without own TTL and no global config → never expires.
    #[test]
    fn asset_without_ttl_no_global_config_never_expires() {
        let mut router = make_asset_router();
        let config = asset_router::AssetCertificationConfig {
            certified_at: 1_000_000,
            ttl: None,
            dynamic: true,
            ..Default::default()
        };
        router
            .certify_asset("/page", b"content".to_vec(), config)
            .unwrap();
        let asset = router.get_asset("/page").unwrap();

        // Ensure global config has no TTL.
        ROUTER_CONFIG.with(|c| {
            c.borrow_mut().cache_config.default_ttl = None;
        });

        // Even at u64::MAX, should not be expired.
        assert!(!is_asset_expired(asset, "/page", u64::MAX));
    }

    /// Static asset (dynamic=false) never expires regardless of TTL settings.
    #[test]
    fn static_asset_never_expires() {
        let mut router = make_asset_router();
        // A static asset with a TTL — but is_asset_expired should still return false.
        let config = asset_router::AssetCertificationConfig {
            certified_at: 1_000_000,
            ttl: Some(Duration::from_secs(1)),
            dynamic: false,
            ..Default::default()
        };
        router
            .certify_asset("/page", b"content".to_vec(), config)
            .unwrap();
        let asset = router.get_asset("/page").unwrap();

        // Way past the TTL, but static assets never expire.
        assert!(!is_asset_expired(asset, "/page", u64::MAX));
    }
}