autumn-macros 0.9.0

Proc macros for the Autumn web framework
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
use syn::{Block, Expr, ExprIf, Item, Pat, Stmt, Type};

const REPLAY_GUARD_IDENT: &str = "__AUTUMN_IDEMPOTENCY_REPLAY_GUARD";

pub fn block_has_replay_guard(block: &Block) -> bool {
    block_has_generated_replay_guard(block)
}

/// Whether a pre-body `FromRequestParts` gate macro (`#[secured]`,
/// `#[step_up]`, `#[throttle]` — issue #1668) about to attach its own gate to
/// `input_fn` should also make that gate responsible for serving a cached
/// idempotency replay.
///
/// Exactly one guard may own replay-serving, and it must be the one every
/// OTHER stacked guard's check is already guaranteed to have passed by the
/// time it runs. That is never true when:
///
/// - another guard's gate parameter is already present — [`has_any_guard_gate_param`];
/// - an earlier-expanded in-body guard (`#[authorize]`, or a gate that
///   deferred for one of these same reasons) already owns replay —
///   [`block_has_replay_guard`];
/// - `#[authorize]` is still an unexpanded attribute and will run AFTER this
///   gate: its policy check lives inside the handler body, which only runs
///   once every extractor — including this gate — has already succeeded, so
///   a gate that served a cached replay itself would return before
///   `#[authorize]`'s check ever ran.
pub fn should_own_replay(input_fn: &syn::ItemFn) -> bool {
    !crate::param_helpers::has_any_guard_gate_param(input_fn)
        && !block_has_replay_guard(&input_fn.block)
        && !has_pending_authorize_attr(input_fn)
}

/// The gate body for a guard that [`should_own_replay`]: look up a cached
/// `IdempotencyReplayResponse` and return it immediately when present.
///
/// Callers splice this into their own gate assembly wherever their ordering
/// requires it — `#[secured]` and `#[throttle]` place it after their own
/// check, `#[step_up]` before — so it takes no ordering flag; the identical
/// token stream (issue #1668) is the only thing shared between them.
pub fn owned_replay_check_tokens() -> proc_macro2::TokenStream {
    quote::quote! {
        let __autumn_idempotency_replay = parts
            .extensions
            .get::<::autumn_web::idempotency::IdempotencyReplayResponse>()
            .cloned()
            .map(::autumn_web::reexports::axum::extract::Extension);
        if let ::core::option::Option::Some(__autumn_response) =
            ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
        {
            return ::core::result::Result::Err(__autumn_response);
        }
    }
}

fn has_pending_authorize_attr(input_fn: &syn::ItemFn) -> bool {
    input_fn
        .attrs
        .iter()
        .any(|attr| crate::authorize::attr_is_authorize_shaped(attr, input_fn))
}

fn block_has_generated_replay_guard(block: &Block) -> bool {
    let mut index = 0;
    while let Some(stmt) = block.stmts.get(index) {
        if stmt_is_replay_guard_marker(stmt)
            && block
                .stmts
                .get(index + 1)
                .is_some_and(stmt_is_generated_replay_guard)
        {
            return true;
        }

        if stmt_is_generated_auth_prologue(stmt)
            || stmt_is_generated_throttle_prologue(stmt)
            || stmt_is_generated_sunset_check_prologue(stmt)
        {
            index += 1;
            continue;
        }

        if let Some(nested) = generated_nested_response_body(block, index) {
            return block_has_generated_replay_guard(nested);
        }

        return false;
    }

    false
}

fn stmt_is_replay_guard_marker(stmt: &Stmt) -> bool {
    matches!(
        stmt,
        Stmt::Item(Item::Const(item)) if item.ident == REPLAY_GUARD_IDENT
    )
}

fn stmt_is_generated_replay_guard(stmt: &Stmt) -> bool {
    let Stmt::Expr(Expr::If(expr_if), _) = stmt else {
        return false;
    };

    if_let_replays_and_returns(expr_if)
}

fn stmt_is_generated_auth_prologue(stmt: &Stmt) -> bool {
    // Marker consts the auth guards prepend ahead of their check. They carry no
    // behaviour, so the scan must step over them: a prologue statement that is
    // not recognized stops the walk, the replay guard behind it reads as absent,
    // and an enclosing guard emits a second one *ahead* of the auth check —
    // serving a cached response before authentication/authorization runs.
    if matches!(
        stmt,
        Stmt::Item(Item::Const(item))
            if item.ident == "__AUTUMN_SECURED_ROLES"
                || item.ident == "__AUTUMN_SECURED_SCOPES"
                || item.ident == "__AUTUMN_AUTHORIZE_BINDINGS"
    ) {
        return true;
    }

    let Stmt::Expr(Expr::If(expr_if), _) = stmt else {
        return false;
    };

    if_let_generated_check_returns_error(expr_if)
}

/// Skips the two statements the `#[throttle]` macro prepends ahead of the
/// idempotency-replay guard when it expands BEFORE the route macro (i.e.
/// `#[throttle]` written above `#[get]`/`#[post]`): the
/// `const __AUTUMN_THROTTLE_ROUTE_ID` bucket-namespace constant and the
/// `if let Err(__autumn_throttle_response) = …__check_throttle(…).await { return … }`
/// guard. Recognizing them lets the body scan reach the generated replay guard
/// that follows, so the route macro suppresses the outer
/// `IdempotencyReplayLayer` under this attribute ordering exactly as it already
/// does for `#[secured]`/`#[authorize]` (which expand the same way when written
/// above the route attribute).
fn stmt_is_generated_throttle_prologue(stmt: &Stmt) -> bool {
    if matches!(
        stmt,
        Stmt::Item(Item::Const(item)) if item.ident == "__AUTUMN_THROTTLE_ROUTE_ID"
    ) {
        return true;
    }

    let Stmt::Expr(Expr::If(expr_if), _) = stmt else {
        return false;
    };

    if_let_throttle_check_returns(expr_if)
}

/// Skips the version-sunset check `#[authorize]` emits between its policy
/// check and its replay stop:
/// `if let Some(Extension(meta)) = &__autumn_route_version { if let
/// Some(resp) = check_sunset(&state, meta) { return resp; } }`. It carries
/// real behaviour (an old route version can still reject a request), but
/// nothing downstream of it depends on that outcome the way replay-serving
/// does, so the scan must step over it to reach the replay guard that
/// follows: an unrecognized statement here stops the walk, the replay guard
/// reads as absent, and a gate macro stacked above `#[authorize]` would then
/// claim replay ownership for a `FromRequestParts` extractor that runs
/// BEFORE authorize's policy re-check ever does.
fn stmt_is_generated_sunset_check_prologue(stmt: &Stmt) -> bool {
    let Stmt::Expr(Expr::If(expr_if), _) = stmt else {
        return false;
    };

    if_let_sunset_check(expr_if)
}

fn if_let_sunset_check(expr_if: &ExprIf) -> bool {
    let Expr::Let(expr_let) = expr_if.cond.as_ref() else {
        return false;
    };

    expr_if.else_branch.is_none()
        && pat_is_some_route_version_extension(&expr_let.pat)
        && expr_is_ref_to_ident(&expr_let.expr, "__autumn_route_version")
        && block_is_sunset_check_body(&expr_if.then_branch)
}

fn pat_is_some_route_version_extension(pat: &Pat) -> bool {
    let Pat::TupleStruct(tuple) = pat else {
        return false;
    };

    path_matches(&tuple.path, &["core", "option", "Option", "Some"])
        && tuple.elems.len() == 1
        && pat_is_extension_binding(&tuple.elems[0], "__autumn_meta")
}

fn pat_is_extension_binding(pat: &Pat, expected: &str) -> bool {
    let Pat::TupleStruct(tuple) = pat else {
        return false;
    };

    path_ends_with(&tuple.path, "Extension")
        && tuple.elems.len() == 1
        && pat_binds_ident(&tuple.elems[0], expected)
}

fn block_is_sunset_check_body(block: &Block) -> bool {
    match block.stmts.as_slice() {
        [Stmt::Expr(Expr::If(inner_if), _)] => if_let_sunset_response_returns(inner_if),
        _ => false,
    }
}

fn if_let_sunset_response_returns(expr_if: &ExprIf) -> bool {
    let Expr::Let(expr_let) = expr_if.cond.as_ref() else {
        return false;
    };

    expr_if.else_branch.is_none()
        && pat_is_some_replay_response(&expr_let.pat)
        && expr_is_check_sunset_call(&expr_let.expr)
        && block_returns_ident(&expr_if.then_branch, "__autumn_response")
}

fn expr_is_check_sunset_call(expr: &Expr) -> bool {
    match expr {
        Expr::Call(call) => {
            path_expr_matches(&call.func, &["autumn_web", "__private", "check_sunset"])
        }
        Expr::Group(group) => expr_is_check_sunset_call(&group.expr),
        Expr::Paren(paren) => expr_is_check_sunset_call(&paren.expr),
        _ => false,
    }
}

fn if_let_throttle_check_returns(expr_if: &ExprIf) -> bool {
    let Expr::Let(expr_let) = expr_if.cond.as_ref() else {
        return false;
    };

    pat_is_err_throttle_response(&expr_let.pat)
        && expr_is_generated_throttle_check_call(&expr_let.expr)
        && block_returns_ident(&expr_if.then_branch, "__autumn_throttle_response")
}

fn pat_is_err_throttle_response(pat: &Pat) -> bool {
    match pat {
        Pat::TupleStruct(tuple) => {
            path_matches(&tuple.path, &["core", "result", "Result", "Err"])
                && tuple.elems.len() == 1
                && pat_binds_ident(&tuple.elems[0], "__autumn_throttle_response")
        }
        _ => false,
    }
}

fn expr_is_generated_throttle_check_call(expr: &Expr) -> bool {
    match expr {
        Expr::Await(await_expr) => expr_is_generated_throttle_check_call(&await_expr.base),
        Expr::Call(call) => {
            path_expr_matches(&call.func, &["autumn_web", "security", "__check_throttle"])
                && call
                    .args
                    .first()
                    .is_some_and(|arg| expr_is_ref_to_ident(arg, "__autumn_state"))
        }
        Expr::Group(group) => expr_is_generated_throttle_check_call(&group.expr),
        Expr::Paren(paren) => expr_is_generated_throttle_check_call(&paren.expr),
        _ => false,
    }
}

fn if_let_replays_and_returns(expr_if: &ExprIf) -> bool {
    let Expr::Let(expr_let) = expr_if.cond.as_ref() else {
        return false;
    };

    pat_is_some_replay_response(&expr_let.pat)
        && expr_is_replay_response_call(&expr_let.expr)
        && block_returns_ident(&expr_if.then_branch, "__autumn_response")
}

fn if_let_generated_check_returns_error(expr_if: &ExprIf) -> bool {
    let Expr::Let(expr_let) = expr_if.cond.as_ref() else {
        return false;
    };

    pat_is_err_autumn_error(&expr_let.pat)
        && expr_is_generated_auth_check_call(&expr_let.expr)
        && block_is_generated_auth_failure_response(&expr_if.then_branch)
}

fn pat_is_some_replay_response(pat: &Pat) -> bool {
    match pat {
        Pat::TupleStruct(tuple) => {
            path_matches(&tuple.path, &["core", "option", "Option", "Some"])
                && tuple.elems.len() == 1
                && pat_binds_ident(&tuple.elems[0], "__autumn_response")
        }
        _ => false,
    }
}

fn pat_is_err_autumn_error(pat: &Pat) -> bool {
    match pat {
        Pat::TupleStruct(tuple) => {
            path_matches(&tuple.path, &["core", "result", "Result", "Err"])
                && tuple.elems.len() == 1
                && pat_binds_ident(&tuple.elems[0], "__autumn_error")
        }
        _ => false,
    }
}

fn pat_binds_ident(pat: &Pat, expected: &str) -> bool {
    matches!(pat, Pat::Ident(ident) if ident.ident == expected)
}

fn expr_is_replay_response_call(expr: &Expr) -> bool {
    match expr {
        Expr::Call(call) => path_expr_matches(
            &call.func,
            &["autumn_web", "idempotency", "__replay_response"],
        ),
        Expr::Group(group) => expr_is_replay_response_call(&group.expr),
        Expr::Paren(paren) => expr_is_replay_response_call(&paren.expr),
        _ => false,
    }
}

fn expr_is_generated_auth_check_call(expr: &Expr) -> bool {
    match expr {
        Expr::Await(await_expr) => expr_is_generated_auth_check_call(&await_expr.base),
        Expr::Call(call)
            if path_expr_matches(
                &call.func,
                &["autumn_web", "auth", "__check_secured_with_key"],
            ) =>
        {
            call.args.len() == 3
                && call
                    .args
                    .first()
                    .is_some_and(|arg| expr_is_ref_to_ident(arg, "__autumn_session"))
                && call
                    .args
                    .iter()
                    .nth(1)
                    .is_some_and(expr_is_auth_session_key_call)
                && call
                    .args
                    .iter()
                    .nth(2)
                    .is_some_and(|arg| path_expr_ends_with(arg, "__AUTUMN_SECURED_ROLES"))
        }
        Expr::Call(call)
            if path_expr_matches(
                &call.func,
                &["autumn_web", "auth", "__check_secured_scopes"],
            ) =>
        {
            // __check_secured_scopes(__autumn_token_scopes…, __AUTUMN_SECURED_SCOPES)
            call.args.len() == 2
                && call
                    .args
                    .iter()
                    .nth(1)
                    .is_some_and(|arg| path_expr_ends_with(arg, "__AUTUMN_SECURED_SCOPES"))
        }
        Expr::Call(call)
            if path_expr_matches(
                &call.func,
                &["autumn_web", "authorization", "__check_policy"],
            ) =>
        {
            call.args.len() == 4
                && call
                    .args
                    .first()
                    .is_some_and(|arg| expr_is_ref_to_ident(arg, "__autumn_state"))
                && call
                    .args
                    .iter()
                    .nth(1)
                    .is_some_and(|arg| expr_is_ref_to_ident(arg, "__autumn_session"))
                && call.args.iter().nth(2).is_some_and(expr_is_string_literal)
                && call.args.iter().nth(3).is_some_and(expr_is_ref_to_path)
        }
        Expr::Call(call)
            if path_expr_matches(
                &call.func,
                &["autumn_web", "authorization", "__check_policy_scoped"],
            ) =>
        {
            // __check_policy_scoped(&state, &session, scopes_map, "action", &resource)
            call.args.len() == 5
                && call
                    .args
                    .first()
                    .is_some_and(|arg| expr_is_ref_to_ident(arg, "__autumn_state"))
                && call
                    .args
                    .iter()
                    .nth(1)
                    .is_some_and(|arg| expr_is_ref_to_ident(arg, "__autumn_session"))
                && call.args.iter().nth(2).is_some_and(expr_is_scopes_map_arg)
                && call.args.iter().nth(3).is_some_and(expr_is_string_literal)
                && call.args.iter().nth(4).is_some_and(expr_is_ref_to_path)
        }
        Expr::Group(group) => expr_is_generated_auth_check_call(&group.expr),
        Expr::Paren(paren) => expr_is_generated_auth_check_call(&paren.expr),
        _ => false,
    }
}

/// Recognizes `__autumn_token_scopes.as_ref().map(|__e| &__e.0)` — the
/// generated scopes argument emitted by `#[authorize]` for `__check_policy_scoped`.
fn expr_is_scopes_map_arg(expr: &Expr) -> bool {
    let Expr::MethodCall(outer) = expr else {
        return false;
    };
    if outer.method != "map" {
        return false;
    }
    let Expr::MethodCall(inner) = outer.receiver.as_ref() else {
        return false;
    };
    inner.method == "as_ref" && path_expr_ends_with(&inner.receiver, "__autumn_token_scopes")
}

fn block_returns_ident(block: &Block, expected: &str) -> bool {
    block.stmts.iter().any(|stmt| match stmt {
        Stmt::Expr(Expr::Return(ret), _) => ret
            .expr
            .as_ref()
            .is_some_and(|expr| path_expr_ends_with(expr, expected)),
        _ => false,
    })
}

fn block_is_generated_auth_failure_response(block: &Block) -> bool {
    match block.stmts.as_slice() {
        [Stmt::Expr(Expr::Return(ret), _)] => ret
            .expr
            .as_ref()
            .is_some_and(|expr| expr_is_autumn_error_response(expr)),
        [
            Stmt::Expr(Expr::If(replay_if), _),
            Stmt::Expr(Expr::Return(ret), _),
        ] => {
            if_let_replays_finalized_session_response(replay_if)
                && ret
                    .expr
                    .as_ref()
                    .is_some_and(|expr| expr_is_autumn_error_response(expr))
        }
        _ => false,
    }
}

fn expr_is_autumn_error_response(expr: &Expr) -> bool {
    match expr {
        Expr::Call(call) => {
            path_expr_matches(
                &call.func,
                &[
                    "autumn_web",
                    "reexports",
                    "axum",
                    "response",
                    "IntoResponse",
                    "into_response",
                ],
            ) && call.args.len() == 1
                && call
                    .args
                    .first()
                    .is_some_and(|arg| path_expr_ends_with(arg, "__autumn_error"))
        }
        Expr::Group(group) => expr_is_autumn_error_response(&group.expr),
        Expr::Paren(paren) => expr_is_autumn_error_response(&paren.expr),
        _ => false,
    }
}

fn if_let_replays_finalized_session_response(expr_if: &ExprIf) -> bool {
    let Expr::Let(expr_let) = expr_if.cond.as_ref() else {
        return false;
    };

    pat_is_some_replay_response(&expr_let.pat)
        && expr_is_finalized_session_replay_call(&expr_let.expr)
        && block_returns_ident(&expr_if.then_branch, "__autumn_response")
}

fn expr_is_finalized_session_replay_call(expr: &Expr) -> bool {
    match expr {
        Expr::Await(await_expr) => expr_is_finalized_session_replay_call(&await_expr.base),
        Expr::Call(call)
            if path_expr_matches(
                &call.func,
                &[
                    "autumn_web",
                    "idempotency",
                    "__replay_finalized_session_response",
                ],
            ) =>
        {
            call.args.len() == 1
                && call
                    .args
                    .first()
                    .is_some_and(|arg| expr_is_ref_to_ident(arg, "__autumn_idempotency_replay"))
        }
        Expr::Call(call)
            if path_expr_matches(
                &call.func,
                &[
                    "autumn_web",
                    "idempotency",
                    "__replay_finalized_session_response_for_anonymous",
                ],
            ) =>
        {
            call.args.len() == 3
                && call
                    .args
                    .first()
                    .is_some_and(|arg| expr_is_ref_to_ident(arg, "__autumn_session"))
                && call
                    .args
                    .iter()
                    .nth(1)
                    .is_some_and(expr_is_auth_session_key_call)
                && call
                    .args
                    .iter()
                    .nth(2)
                    .is_some_and(|arg| expr_is_ref_to_ident(arg, "__autumn_idempotency_replay"))
        }
        Expr::Group(group) => expr_is_finalized_session_replay_call(&group.expr),
        Expr::Paren(paren) => expr_is_finalized_session_replay_call(&paren.expr),
        _ => false,
    }
}

fn expr_is_ref_to_ident(expr: &Expr, expected: &str) -> bool {
    let Expr::Reference(reference) = expr else {
        return false;
    };

    path_expr_ends_with(&reference.expr, expected)
}

fn expr_is_ref_to_path(expr: &Expr) -> bool {
    matches!(expr, Expr::Reference(reference) if matches!(reference.expr.as_ref(), Expr::Path(_)))
}

fn expr_is_auth_session_key_call(expr: &Expr) -> bool {
    let Expr::MethodCall(call) = expr else {
        return false;
    };

    call.method == "auth_session_key"
        && call.args.is_empty()
        && path_expr_ends_with(&call.receiver, "__autumn_state")
}

const fn expr_is_string_literal(expr: &Expr) -> bool {
    matches!(
        expr,
        Expr::Lit(syn::ExprLit {
            lit: syn::Lit::Str(_),
            ..
        })
    )
}

fn generated_nested_response_body(block: &Block, index: usize) -> Option<&Block> {
    let stmt = block.stmts.get(index)?;
    match stmt {
        Stmt::Local(local) if pat_binds_inner_response(&local.pat) => local
            .init
            .as_ref()
            .and_then(|init| expr_nested_async_body(&init.expr))
            .filter(|_| {
                index + 2 == block.stmts.len()
                    && block
                        .stmts
                        .get(index + 1)
                        .is_some_and(stmt_is_inner_response_tail)
            }),
        Stmt::Expr(expr, None) if index + 1 == block.stmts.len() => expr_nested_async_body(expr),
        _ => None,
    }
}

fn pat_binds_inner_response(pat: &Pat) -> bool {
    match pat {
        Pat::Ident(ident) => ident.ident == "__autumn_inner",
        Pat::Type(typed) => pat_binds_inner_response(&typed.pat),
        _ => false,
    }
}

/// Unwrap the `(async move { … }).await` wrapper the body guards (`#[secured]`,
/// `#[authorize]`, `#[throttle]`, …) put a handler's original body inside —
/// including the `IntoResponse::into_response(…)` call, parens, and invisible
/// groups they may sit behind — and yield the inner block.
///
/// Also unwraps the unrelated `(|| async move { … })().await` closure-IIFE
/// wrapper `#[cached]` puts a handler's original body inside
/// (`cached_macro`'s `compute`): a marker injected by an earlier-expanding
/// attribute (e.g. `#[static_get]`'s `STATIC_ROUTE_HANDLER_MARKER`) ends up
/// buried one level deeper than usual when `#[cached]` sits between it and
/// the guard that needs to see it, same as the guard-generated wrapper above
/// (Codex review on #2513, eleventh finding).
///
/// Shared with `api_doc`'s marker walks: each guard or wrapper that expands
/// *before* another buries the earlier one's marker consts one wrapper level
/// deeper, so a walk that does not descend through this shape silently loses
/// them.
pub fn expr_nested_async_body(expr: &Expr) -> Option<&Block> {
    match expr {
        Expr::Async(expr_async) => Some(&expr_async.block),
        Expr::Await(await_expr) => expr_nested_async_body(&await_expr.base),
        Expr::Call(call)
            if path_expr_matches(
                &call.func,
                &[
                    "autumn_web",
                    "reexports",
                    "axum",
                    "response",
                    "IntoResponse",
                    "into_response",
                ],
            ) && call.args.len() == 1 =>
        {
            call.args.first().and_then(expr_nested_async_body)
        }
        // `(|| async move { … })()` / `(|| async move { … })().await` — a
        // zero-argument call of an inline closure, the `#[cached]` IIFE
        // shape. The closure itself is never `async`; its body is the async
        // block being wrapped.
        Expr::Call(call) if call.args.is_empty() => match unwrap_group_paren(&call.func) {
            Expr::Closure(closure) => expr_nested_async_body(&closure.body),
            _ => None,
        },
        Expr::Group(group) => expr_nested_async_body(&group.expr),
        Expr::Paren(paren) => expr_nested_async_body(&paren.expr),
        _ => None,
    }
}

/// Strip any invisible `Group`/`Paren` wrapper down to the expression they
/// enclose, without following any other wrapper shape (unlike
/// [`expr_nested_async_body`], which only unwraps a specific known set of
/// *async* wrappers and returns the inner `Block` rather than the `Expr`
/// itself).
fn unwrap_group_paren(expr: &Expr) -> &Expr {
    match expr {
        Expr::Group(group) => unwrap_group_paren(&group.expr),
        Expr::Paren(paren) => unwrap_group_paren(&paren.expr),
        other => other,
    }
}

/// Marker consts a body guard (`#[secured]`, `#[step_up]`, `#[authorize]`,
/// `#[throttle]`) unconditionally emits into the same block as its
/// `__autumn_inner` binding whenever it rewrites a handler's return type —
/// see `secured_macro`'s `check_call`, `step_up_macro`'s `build_check_call`,
/// `authorize_macro`'s block prologue, and `throttle_macro`'s `check_call`.
/// One of these always precedes the binding in real guard output, so its
/// presence is what [`generated_inner_response_binding`] uses to tell a real
/// guard's generated wrapper apart from a block that merely has the same
/// `let __autumn_inner: T = (async move { … }).await; IntoResponse::into_response(__autumn_inner)`
/// shape by coincidence.
const RESPONSE_REWRITING_GUARD_MARKERS: &[&str] = &[
    "__AUTUMN_SECURED_ROLES",
    "__AUTUMN_STEP_UP_MAX_AGE",
    "__AUTUMN_THROTTLE_ROUTE_ID",
    "__AUTUMN_AUTHORIZE_BINDINGS",
];

/// Whether any statement in `stmts` is a marker const from
/// [`RESPONSE_REWRITING_GUARD_MARKERS`].
fn stmts_have_response_rewriting_guard_marker(stmts: &[Stmt]) -> bool {
    stmts.iter().any(|stmt| {
        matches!(
            stmt,
            Stmt::Item(Item::Const(item))
                if RESPONSE_REWRITING_GUARD_MARKERS.contains(&item.ident.to_string().as_str())
        )
    })
}

/// The exact shape a body guard (`#[secured]`, `#[step_up]`, `#[authorize]`,
/// `#[throttle]`) emits when it rewrites a non-unit, non-`impl Trait` return
/// type: a `let __autumn_inner: T = <init>;` binding sitting exactly one
/// statement before the end of `block`, immediately followed by the
/// generated `IntoResponse::into_response(__autumn_inner)` tail, with one of
/// [`RESPONSE_REWRITING_GUARD_MARKERS`] present earlier in the same block, or
/// `markerless_gate_budget` above zero (issue #1677's
/// `api_doc::infer_response_body` recovery relies on this).
///
/// `markerless_gate_budget` covers `#[step_up]`/`#[throttle]`: their marker
/// consts moved out of the body and into their gate's own impl block
/// (#1668), so they can never appear in `block` for this scan to find. The
/// caller counts it once, from the enclosing function's signature — one unit
/// per such gate parameter present — and this function returns the balance
/// left after spending one unit to accept the *current* level, so a caller
/// recursing into a deeper, nested block cannot spend the same real guard's
/// unit a second time on an unrelated coincidental match there (a marker-const
/// acceptance spends nothing, since a real marker is level-local proof on its
/// own).
///
/// Deliberately structural rather than a bare name-and-type scan. Matching
/// the required *position* (second-to-last, with that exact tail following)
/// alone rules out a handler that happens to declare its own unrelated local
/// named `__autumn_inner` elsewhere in the body. But the guard's own
/// generated wrapper contains the *user's original body* verbatim one level
/// deeper (`(async move { #original_body }).await`) — so if that original
/// body itself independently ends in the same two-statement shape, position
/// and tail alone cannot tell a real guard's own binding apart from the
/// user's body coincidentally mimicking it. Requiring a marker const (or an
/// unspent budget unit) to also be present closes that gap: no guard ever
/// emits the `__autumn_inner` binding without one, a handler's own code has
/// no reason to declare an identifier the framework treats as reserved, and
/// the budget cap means a coincidence *beyond* the real guards' own levels
/// still has nothing left to spend.
///
/// Returns the local's declared type, its initializer expression, and the
/// remaining budget, so a caller can read the type, recurse into a deeper
/// nested guard via [`expr_nested_async_body`], and thread the correct
/// balance through that recursion.
pub fn generated_inner_response_binding(
    block: &Block,
    markerless_gate_budget: usize,
) -> Option<(&Type, &Expr, usize)> {
    let len = block.stmts.len();
    if len < 2 {
        return None;
    }
    let index = len - 2;
    let Stmt::Local(local) = &block.stmts[index] else {
        return None;
    };
    if !pat_binds_inner_response(&local.pat) {
        return None;
    }
    let Pat::Type(pat_type) = &local.pat else {
        return None;
    };
    if !stmt_is_inner_response_tail(&block.stmts[index + 1]) {
        return None;
    }
    let remaining_budget = if stmts_have_response_rewriting_guard_marker(&block.stmts[..index]) {
        markerless_gate_budget
    } else if markerless_gate_budget > 0 {
        markerless_gate_budget - 1
    } else {
        return None;
    };
    let init_expr = &local.init.as_ref()?.expr;
    Some((&pat_type.ty, init_expr, remaining_budget))
}

fn stmt_is_inner_response_tail(stmt: &Stmt) -> bool {
    let Stmt::Expr(Expr::Call(call), None) = stmt else {
        return false;
    };

    path_expr_matches(
        &call.func,
        &[
            "autumn_web",
            "reexports",
            "axum",
            "response",
            "IntoResponse",
            "into_response",
        ],
    ) && call.args.len() == 1
        && call
            .args
            .first()
            .is_some_and(|arg| path_expr_ends_with(arg, "__autumn_inner"))
}

fn path_expr_ends_with(expr: &Expr, expected: &str) -> bool {
    let Expr::Path(path) = expr else {
        return false;
    };

    path_ends_with(&path.path, expected)
}

fn path_expr_matches(expr: &Expr, expected: &[&str]) -> bool {
    let Expr::Path(path) = expr else {
        return false;
    };

    path_matches(&path.path, expected)
}

fn path_matches(path: &syn::Path, expected: &[&str]) -> bool {
    if path.segments.len() != expected.len() {
        return false;
    }
    // Only an `expected` path actually rooted at the framework crate (some
    // call sites match a `core::...`/`std::...` path instead, e.g. the
    // `Option`/`Result` patterns above) needs its leading segment compared
    // against the actively resolved name rather than the literal
    // `"autumn_web"` — once a rename or `crate = "..."` override (#1828) is
    // in effect, that's what an earlier-expanded stacked macro's own
    // (already-finalized) output is rooted at instead (Codex review, #2552).
    let root_matches = if expected.first() == Some(&"autumn_web") {
        path.segments.first().is_some_and(|segment| {
            segment.ident == autumn_macros_support::crate_path::current_target_path_segment()
        })
    } else {
        path.segments
            .first()
            .zip(expected.first())
            .is_some_and(|(segment, expected)| segment.ident == *expected)
    };
    root_matches
        && path
            .segments
            .iter()
            .skip(1)
            .zip(&expected[1..])
            .all(|(segment, expected)| segment.ident == *expected)
}

fn path_ends_with(path: &syn::Path, expected: &str) -> bool {
    path.segments
        .last()
        .is_some_and(|segment| segment.ident == expected)
}

#[cfg(test)]
mod tests {
    use super::{block_has_replay_guard, should_own_replay};

    #[test]
    fn string_literal_does_not_count_as_replay_guard() {
        let block: syn::Block = syn::parse_quote!({
            let _ = "__AUTUMN_IDEMPOTENCY_REPLAY_GUARD";
        });

        assert!(!block_has_replay_guard(&block));
    }

    #[test]
    fn marker_const_without_replay_call_does_not_count_as_replay_guard() {
        let block: syn::Block = syn::parse_quote!({
            const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
            let _ = "plain user const";
        });

        assert!(!block_has_replay_guard(&block));
    }

    #[test]
    fn marker_const_and_non_returned_replay_call_do_not_count_as_replay_guard() {
        let block: syn::Block = syn::parse_quote!({
            const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
            let _ignored =
                ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay);
        });

        assert!(!block_has_replay_guard(&block));
    }

    #[test]
    fn generated_shape_after_user_statement_does_not_count_as_replay_guard() {
        let block: syn::Block = syn::parse_quote!({
            mutate_before_replay_stop();
            const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
            if let ::core::option::Option::Some(__autumn_response) =
                ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
            {
                return __autumn_response;
            }
        });

        assert!(!block_has_replay_guard(&block));
    }

    #[test]
    fn nested_generated_shape_with_semicolon_does_not_count_as_replay_guard() {
        let block: syn::Block = syn::parse_quote!({
            ::autumn_web::reexports::axum::response::IntoResponse::into_response(
                (async move {
                    const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
                    if let ::core::option::Option::Some(__autumn_response) =
                        ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
                    {
                        return __autumn_response;
                    }
                })
                .await,
            );
            mutate_after_dropped_replay_response();
        });

        assert!(!block_has_replay_guard(&block));
    }

    #[test]
    fn nested_generated_shape_without_tail_response_does_not_count_as_replay_guard() {
        let block: syn::Block = syn::parse_quote!({
            let __autumn_inner: ::autumn_web::reexports::axum::response::Response = (async move {
                const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
                if let ::core::option::Option::Some(__autumn_response) =
                    ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
                {
                    return __autumn_response;
                }
            })
            .await;
            mutate_after_nested_replay_response();
        });

        assert!(!block_has_replay_guard(&block));
    }

    #[test]
    fn nested_guard_in_non_autumn_into_response_does_not_count() {
        let block: syn::Block = syn::parse_quote!({
            evil::IntoResponse::into_response(
                (async move {
                    const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
                    if let ::core::option::Option::Some(__autumn_response) =
                        ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
                    {
                        return __autumn_response;
                    }
                })
                .await,
            )
        });

        assert!(!block_has_replay_guard(&block));
    }

    #[test]
    fn nested_guard_in_extra_into_response_argument_does_not_count() {
        let block: syn::Block = syn::parse_quote!({
            ::autumn_web::reexports::axum::response::IntoResponse::into_response(
                side_effect_before_replay_stop(),
                (async move {
                    const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
                    if let ::core::option::Option::Some(__autumn_response) =
                        ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
                    {
                        return __autumn_response;
                    }
                })
                .await,
            )
        });

        assert!(!block_has_replay_guard(&block));
    }

    #[test]
    fn secured_prologue_with_side_effect_argument_does_not_count() {
        let block: syn::Block = syn::parse_quote!({
            const __AUTUMN_SECURED_ROLES: &[&str] = &["admin"];
            if let ::core::result::Result::Err(__autumn_error) =
                ::autumn_web::auth::__check_secured_with_key(
                    side_effect_before_replay_stop(),
                    __autumn_state.auth_session_key(),
                    __AUTUMN_SECURED_ROLES,
                )
                .await
            {
                return ::autumn_web::reexports::axum::response::IntoResponse::into_response(
                    __autumn_error,
                );
            }
            const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
            if let ::core::option::Option::Some(__autumn_response) =
                ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
            {
                return __autumn_response;
            }
        });

        assert!(!block_has_replay_guard(&block));
    }

    #[test]
    fn authorize_prologue_with_side_effect_argument_does_not_count() {
        let block: syn::Block = syn::parse_quote!({
            if let ::core::result::Result::Err(__autumn_error) =
                ::autumn_web::authorization::__check_policy::<Post>(
                    &__autumn_state,
                    &__autumn_session,
                    side_effect_before_replay_stop(),
                    &post,
                )
                .await
            {
                return ::autumn_web::reexports::axum::response::IntoResponse::into_response(
                    __autumn_error,
                );
            }
            const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
            if let ::core::option::Option::Some(__autumn_response) =
                ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
            {
                return __autumn_response;
            }
        });

        assert!(!block_has_replay_guard(&block));
    }

    #[test]
    fn generated_const_and_replay_call_count_as_replay_guard() {
        let block: syn::Block = syn::parse_quote!({
            const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
            if let ::core::option::Option::Some(__autumn_response) =
                ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
            {
                return __autumn_response;
            }
        });

        assert!(block_has_replay_guard(&block));
    }

    #[test]
    fn generated_throttle_prologue_before_replay_guard_counts() {
        // `#[throttle]` written above `#[post]` expands first: it prepends the
        // route-id const and the throttle check, then the replay guard. The scan
        // must skip the throttle prologue and still recognize the replay guard so
        // the route macro suppresses the outer IdempotencyReplayLayer.
        let block: syn::Block = syn::parse_quote!({
            const __AUTUMN_THROTTLE_ROUTE_ID: &str =
                ::core::concat!(::core::module_path!(), "::", "handler");
            if let ::core::result::Result::Err(__autumn_throttle_response) =
                ::autumn_web::security::__check_throttle(
                    &__autumn_state,
                    __AUTUMN_THROTTLE_ROUTE_ID,
                    ::autumn_web::security::ThrottleSpec::Inline {
                        limit: 1,
                        per_secs: 60,
                        key: ::core::option::Option::None,
                    },
                    &__autumn_throttle_headers,
                    __autumn_throttle_peer.as_ref().map(|ext| ext.0.0),
                    __autumn_throttle_principal.as_ref().map(|e| &e.0),
                    __autumn_throttle_session.as_ref().map(|e| &e.0),
                    __autumn_throttle_exempt.is_some(),
                )
                .await
            {
                return __autumn_throttle_response;
            }
            const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
            if let ::core::option::Option::Some(__autumn_response) =
                ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
            {
                return __autumn_response;
            }
        });

        assert!(block_has_replay_guard(&block));
    }

    #[test]
    fn throttle_prologue_with_side_effect_argument_does_not_count() {
        // A throttle-shaped prologue whose check call takes a side-effecting first
        // argument (not `&__autumn_state`) must NOT be skipped, so a hand-written
        // look-alike cannot trick the route macro into dropping the replay layer.
        let block: syn::Block = syn::parse_quote!({
            const __AUTUMN_THROTTLE_ROUTE_ID: &str = "handler";
            if let ::core::result::Result::Err(__autumn_throttle_response) =
                ::autumn_web::security::__check_throttle(
                    side_effect_before_replay_stop(),
                    __AUTUMN_THROTTLE_ROUTE_ID,
                )
                .await
            {
                return __autumn_throttle_response;
            }
            const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
            if let ::core::option::Option::Some(__autumn_response) =
                ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
            {
                return __autumn_response;
            }
        });

        assert!(!block_has_replay_guard(&block));
    }

    #[test]
    fn generated_secured_prologue_before_replay_guard_counts() {
        let block: syn::Block = syn::parse_quote!({
            const __AUTUMN_SECURED_ROLES: &[&str] = &["admin"];
            if let ::core::result::Result::Err(__autumn_error) =
                ::autumn_web::auth::__check_secured_with_key(
                    &__autumn_session,
                    __autumn_state.auth_session_key(),
                    __AUTUMN_SECURED_ROLES,
                )
                .await
            {
                return ::autumn_web::reexports::axum::response::IntoResponse::into_response(
                    __autumn_error,
                );
            }
            const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
            if let ::core::option::Option::Some(__autumn_response) =
                ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
            {
                return __autumn_response;
            }
        });

        assert!(block_has_replay_guard(&block));
    }

    #[test]
    fn generated_authorize_prologue_with_anonymous_session_replay_counts() {
        let block: syn::Block = syn::parse_quote!({
            if let ::core::result::Result::Err(__autumn_error) =
                ::autumn_web::authorization::__check_policy::<Post>(
                    &__autumn_state,
                    &__autumn_session,
                    "update",
                    &post,
                )
                .await
            {
                if let ::core::option::Option::Some(__autumn_response) =
                    ::autumn_web::idempotency::__replay_finalized_session_response_for_anonymous(
                        &__autumn_session,
                        __autumn_state.auth_session_key(),
                        &__autumn_idempotency_replay,
                    )
                    .await
                {
                    return __autumn_response;
                }
                return ::autumn_web::reexports::axum::response::IntoResponse::into_response(
                    __autumn_error,
                );
            }
            const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
            if let ::core::option::Option::Some(__autumn_response) =
                ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
            {
                return __autumn_response;
            }
        });

        assert!(block_has_replay_guard(&block));
    }

    #[test]
    fn generated_authorize_scoped_prologue_before_replay_guard_counts() {
        let block: syn::Block = syn::parse_quote!({
            if let ::core::result::Result::Err(__autumn_error) =
                ::autumn_web::authorization::__check_policy_scoped::<Post>(
                    &__autumn_state,
                    &__autumn_session,
                    __autumn_token_scopes.as_ref().map(|__e| &__e.0),
                    "update",
                    &post,
                )
                .await
            {
                return ::autumn_web::reexports::axum::response::IntoResponse::into_response(
                    __autumn_error,
                );
            }
            const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
            if let ::core::option::Option::Some(__autumn_response) =
                ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
            {
                return __autumn_response;
            }
        });

        assert!(block_has_replay_guard(&block));
    }

    #[test]
    fn generated_authorize_wrapper_can_find_nested_secured_replay_guard() {
        let block: syn::Block = syn::parse_quote!({
            if let ::core::result::Result::Err(__autumn_error) =
                ::autumn_web::authorization::__check_policy::<Post>(
                    &__autumn_state,
                    &__autumn_session,
                    "update",
                    &post,
                )
                .await
            {
                return ::autumn_web::reexports::axum::response::IntoResponse::into_response(
                    __autumn_error,
                );
            }
            let __autumn_inner: ::autumn_web::reexports::axum::response::Response = (async move {
                const __AUTUMN_SECURED_ROLES: &[&str] = &["admin"];
                if let ::core::result::Result::Err(__autumn_error) =
                    ::autumn_web::auth::__check_secured_with_key(
                        &__autumn_session,
                        __autumn_state.auth_session_key(),
                        __AUTUMN_SECURED_ROLES,
                    )
                    .await
                {
                    return ::autumn_web::reexports::axum::response::IntoResponse::into_response(
                        __autumn_error,
                    );
                }
                const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
                if let ::core::option::Option::Some(__autumn_response) =
                    ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
                {
                    return __autumn_response;
                }
            })
            .await;
            ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
        });

        assert!(block_has_replay_guard(&block));
    }

    #[test]
    fn generated_authorize_bindings_marker_does_not_hide_replay_guard() {
        // `#[authorize]` prepends a binding marker const ahead of its policy
        // check (#1627). Like the `#[secured]` role/scope markers, it must be
        // transparent to this scan: a prologue statement that is not skipped
        // stops the walk, so the replay guard behind it would look absent and
        // the enclosing guard would emit a second one ahead of the policy
        // check — serving a cached response before authorization runs.
        //
        // Scope of this test: it pins the SKIP-LIST behavior on the
        // marker-plus-policy-check prologue prefix, via a reduced hand-written
        // block that stops short of the sunset-check statement `#[authorize]`
        // emits next. `should_own_replay_defers_to_authorize_across_the_sunset_check`
        // below exercises the real full expansion, sunset check included.
        let generated = crate::authorize::authorize_macro(
            quote::quote! { "update", resource = Post },
            quote::quote! {
                async fn update_post(post: Post) -> &'static str { "ok" }
            },
        );
        let generated_fn: syn::ItemFn =
            syn::parse2(generated).expect("#[authorize] must emit a parseable function");
        assert!(
            matches!(
                generated_fn.block.stmts.first(),
                Some(syn::Stmt::Item(syn::Item::Const(item)))
                    if item.ident == "__AUTUMN_AUTHORIZE_BINDINGS"
            ),
            "the reduced block's FIRST statement must keep matching what #[authorize] emits \
             (the rest of the real expansion is deliberately not walked here — see above)"
        );

        let block: syn::Block = syn::parse_quote!({
            const __AUTUMN_AUTHORIZE_BINDINGS: &[(&str, &str)] = &[("update", "Post")];
            if let ::core::result::Result::Err(__autumn_error) =
                ::autumn_web::authorization::__check_policy_scoped::<Post>(
                    &__autumn_state,
                    &__autumn_session,
                    __autumn_token_scopes.as_ref().map(|__e| &__e.0),
                    "update",
                    &post,
                )
                .await
            {
                return ::autumn_web::reexports::axum::response::IntoResponse::into_response(
                    __autumn_error,
                );
            }
            const __AUTUMN_IDEMPOTENCY_REPLAY_GUARD: () = ();
            if let ::core::option::Option::Some(__autumn_response) =
                ::autumn_web::idempotency::__replay_response(&__autumn_idempotency_replay)
            {
                return __autumn_response;
            }
        });

        assert!(block_has_replay_guard(&block));
    }

    /// Counts real `__AUTUMN_IDEMPOTENCY_REPLAY_GUARD` markers left in the
    /// final program after a `#[secured("admin")]` + `#[authorize(...)]`
    /// stack fully expands, in the given attribute order. `#[secured]`
    /// keeps its own checks in a sibling `FromRequestParts` gate item (issue
    /// #1668), never in `input_fn`'s own block, so the count must total the
    /// LAST stage's output plus any earlier gate item verbatim -- the
    /// earlier stage's function item is superseded, not additive.
    fn final_replay_marker_count(gate_item: &str, final_fn: &proc_macro2::TokenStream) -> usize {
        format!("{gate_item} {final_fn}")
            .matches("__AUTUMN_IDEMPOTENCY_REPLAY_GUARD")
            .count()
    }

    #[test]
    fn secured_above_authorize_emits_exactly_one_replay_guard() {
        // Issue #2233: `#[secured("admin")]` above `#[authorize(...)]` above
        // the route macro. Secured is topmost, so it expands FIRST -- with
        // `#[authorize]` still a pending attribute, `should_own_replay` must
        // defer (`has_pending_authorize_attr`) and leave its gate free of any
        // replay check. Authorize expands SECOND, on secured's already
        // gate-wrapped output, and must be the one guard that owns replay.
        //
        // This composition is already safe on trunk: #[secured] moved its
        // checks into a sibling `FromRequestParts` gate item (issue #1668),
        // never into `input_fn`'s own block, so the duplicate-guard risk the
        // issue describes cannot reach this stacking order any more. This
        // test is the end-to-end proof the issue's suggested fix direction
        // asked for, run against real macro output in both stacking orders.
        let secured_input = quote::quote! {
            #[authorize("update", resource = Note)]
            async fn update_note(note: Note) -> &'static str { "ok" }
        };
        let after_secured = crate::secured::secured_macro(quote::quote! { "admin" }, secured_input);
        let mut fn_after_secured: syn::ItemFn =
            crate::param_helpers::extract_fn_item(after_secured.clone(), "update_note");
        // Rustc strips a live attribute from the item before invoking its
        // macro; `extract_fn_item` alone does not, so mirror that here.
        fn_after_secured
            .attrs
            .retain(|a| !a.path().is_ident("authorize"));
        let after_authorize = crate::authorize::authorize_macro(
            quote::quote! { "update", resource = Note },
            quote::quote! { #fn_after_secured },
        );
        let gate_item = after_secured
            .to_string()
            .split("async fn update_note")
            .next()
            .expect("the gate struct+impl precedes the fn in secured's output")
            .to_string();

        assert_eq!(
            final_replay_marker_count(&gate_item, &after_authorize),
            1,
            "exactly one guard must own replay-serving end to end: \
             gate:\n{gate_item}\n\nfinal fn:\n{after_authorize}"
        );
    }

    #[test]
    fn authorize_above_secured_emits_exactly_one_replay_guard() {
        // Issue #2233, the other stacking order: `#[authorize(...)]` above
        // `#[secured("admin")]`. Authorize is topmost and expands FIRST,
        // claiming replay ownership in its own in-body check (nothing else
        // has claimed it yet). Secured expands SECOND, on authorize's
        // already-expanded body, and must recognize authorize's replay
        // guard there (past its policy-check failure branch and sunset
        // check) so its own gate stays free of a second one.
        let authorize_input = quote::quote! {
            #[secured("admin")]
            async fn update_note(note: Note) -> &'static str { "ok" }
        };
        let after_authorize = crate::authorize::authorize_macro(
            quote::quote! { "update", resource = Note },
            authorize_input,
        );
        let mut fn_after_authorize: syn::ItemFn =
            crate::param_helpers::extract_fn_item(after_authorize, "update_note");
        fn_after_authorize
            .attrs
            .retain(|a| !a.path().is_ident("secured"));
        let after_secured = crate::secured::secured_macro(
            quote::quote! { "admin" },
            quote::quote! { #fn_after_authorize },
        );

        assert_eq!(
            after_secured
                .to_string()
                .matches("__AUTUMN_IDEMPOTENCY_REPLAY_GUARD")
                .count(),
            1,
            "exactly one guard must own replay-serving end to end: {after_secured}"
        );
    }

    #[test]
    fn should_own_replay_defers_to_authorize_across_the_sunset_check() {
        // Real stacking order `#[authorize("update", resource = Post)]` above
        // `#[secured]`/`#[step_up]`/`#[throttle]`: authorize expands FIRST
        // (it's topmost) and already owns replay-serving via its own in-body
        // check. Between that check and its replay stop it also emits a
        // sunset-version check — a statement the scan must see past, or it
        // stops early, reports no replay guard, and lets the about-to-attach
        // gate claim replay ownership for itself.
        //
        // That would no longer be the harmless redundancy it was pre-#1668:
        // the gate is a `FromRequestParts` extractor that runs BEFORE the
        // handler body — i.e. before `#[authorize]`'s policy re-check, which
        // lives entirely inside the body. A gate that wrongly owns replay
        // would serve a cached success response for a retried mutation
        // without ever re-running that policy check, even after the
        // requester's authorization has since been revoked.
        let generated = crate::authorize::authorize_macro(
            quote::quote! { "update", resource = Post },
            quote::quote! {
                async fn update_post(post: Post) -> &'static str { "ok" }
            },
        );
        let generated_fn: syn::ItemFn =
            syn::parse2(generated).expect("#[authorize] must emit a parseable function");

        assert!(
            block_has_replay_guard(&generated_fn.block),
            "the real #[authorize] expansion already owns replay-serving; the scan must \
             see past the sunset-check statement to find it"
        );
        assert!(
            !should_own_replay(&generated_fn),
            "a gate macro stacking on top of real #[authorize] output must defer replay \
             ownership to authorize, not claim it for a pre-body gate"
        );
    }
}