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
//! `#[secured]` proc macro implementation.
//!
//! Generates an authentication/authorization guard that runs as a
//! `FromRequestParts` gate — a hidden, handler-unique parameter inserted
//! ahead of the handler's own parameters — instead of a statement inside the
//! handler body (issue #1668). Axum resolves every `FromRequestParts`
//! extractor, left to right, *before* it ever reaches a `FromRequest` body
//! extractor (`Json` / `Form` / `Multipart`) and short-circuits on the first
//! rejection, so an unauthenticated/unauthorized request is rejected with
//! `401`/`403` before the request body is parsed, rather than after.
//!
//! ## Forms
//!
//! - `#[secured]` -- require authenticated session (session key exists)
//! - `#[secured("admin")]` -- require a specific role
//! - `#[secured("admin", "editor")]` -- require any of the listed roles
//! - `#[secured(scopes = ["posts:write"])]` -- require a scoped API token that
//!   grants every listed scope. **No session is required** for a scopes-only
//!   gate, so a pure service token (no logged-in user) authorizes on scopes
//!   alone. Default-deny: a token lacking a required scope gets `403`.
//! - `#[secured("admin", scopes = ["posts:write"])]` -- require **both** the
//!   role (via the session) **and** the scope (AND semantics).

use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::parse::Parser as _;
use syn::{Expr, ExprLit, Lit, LitStr, Meta, Token};

use crate::idempotency_guard::should_own_replay;

/// Parsed `#[secured(...)]` arguments: positional role literals plus an
/// optional `scopes = [...]` list of token abilities.
#[derive(Default)]
struct SecuredArgs {
    roles: Vec<String>,
    scopes: Vec<String>,
}

/// Parse the `#[secured(...)]` attribute arguments.
///
/// Grammar: zero or more leading bare string literals (roles), optionally
/// followed by `scopes = ["a", "b"]`. Examples that must parse:
/// `#[secured]`, `#[secured("admin")]`, `#[secured("a", "b")]`,
/// `#[secured(scopes = ["x"])]`, `#[secured("admin", scopes = ["x"])]`.
fn parse_secured_args(attr: TokenStream) -> syn::Result<SecuredArgs> {
    use proc_macro2::TokenTree;

    if attr.is_empty() {
        return Ok(SecuredArgs::default());
    }

    // Peel off leading bare string literals as roles; bare literals are not
    // valid `Meta`, so they must be consumed before the keyword-style parse.
    let mut iter = attr.into_iter().peekable();
    let mut roles = Vec::new();
    while let Some(TokenTree::Literal(lit)) = iter.peek() {
        let s: LitStr = syn::parse2(quote! { #lit })?;
        roles.push(s.value());
        iter.next();
        if let Some(TokenTree::Punct(p)) = iter.peek()
            && p.as_char() == ','
        {
            iter.next();
        } else {
            break;
        }
    }

    let rest: TokenStream = iter.collect();
    let mut scopes = Vec::new();
    if !rest.is_empty() {
        let metas =
            syn::punctuated::Punctuated::<Meta, Token![,]>::parse_terminated.parse2(rest)?;
        for meta in metas {
            match meta {
                Meta::NameValue(nv) if nv.path.is_ident("scopes") => {
                    scopes = parse_scope_array(&nv.value)?;
                }
                other => {
                    return Err(syn::Error::new_spanned(
                        other,
                        "expected role string literals and/or `scopes = [\"...\"]`",
                    ));
                }
            }
        }
    }

    Ok(SecuredArgs { roles, scopes })
}

/// Parse `["a", "b"]` into a vec of strings, erroring on non-string elements.
fn parse_scope_array(expr: &Expr) -> syn::Result<Vec<String>> {
    let Expr::Array(arr) = expr else {
        return Err(syn::Error::new_spanned(
            expr,
            "`scopes` must be an array of string literals, e.g. scopes = [\"posts:write\"]",
        ));
    };
    arr.elems
        .iter()
        .map(|el| match el {
            Expr::Lit(ExprLit {
                lit: Lit::Str(s), ..
            }) => Ok(s.value()),
            other => Err(syn::Error::new_spanned(
                other,
                "scope entries must be string literals",
            )),
        })
        .collect()
}

#[allow(clippy::too_many_lines)]
// `item` is only ever borrowed via
// `param_helpers::split_leading_items_and_reject_incompatible` now, but
// keeps the owned `TokenStream` signature every macro entry point in this
// crate shares (and the proc-macro boundary in `lib.rs` requires).
#[allow(clippy::needless_pass_by_value)]
pub fn secured_macro(attr: TokenStream, item: TokenStream) -> TokenStream {
    let SecuredArgs { roles, scopes } = match parse_secured_args(attr) {
        Ok(r) => r,
        Err(err) => return err.to_compile_error(),
    };

    let (leading_items, mut input_fn) =
        match crate::param_helpers::split_leading_items_and_reject_incompatible(&item, "secured") {
            Ok(v) => v,
            Err(err) => return err,
        };

    // An attribute sharing #[authorize]'s argument grammar under a different
    // name is refused rather than guessed at — see
    // `authorize::reject_if_ambiguous_authorize_shape`'s doc comment.
    if let Some(err) = crate::authorize::reject_if_ambiguous_authorize_shape(&input_fn) {
        return err;
    }

    // The session/role check is emitted for the classic forms (`#[secured]`,
    // `#[secured("admin")]`) and whenever a role is required. It is OMITTED for
    // a scopes-ONLY gate so a pure service token with no session authorizes on
    // its scopes alone (extracting a real `Session` would otherwise require a
    // `SessionLayer` and reject token-only requests).
    let emit_session_check = !roles.is_empty() || scopes.is_empty();
    let emit_scope_check = !scopes.is_empty();

    let role_literals = roles.iter().map(|role| quote! { #role });
    let scope_literals = scopes.iter().map(|scope| quote! { #scope });
    // A single `TokenStream` (cheaply `Clone`) so the role/scope consts can be
    // emitted twice — once in the handler body for OpenAPI extraction (where
    // nothing in the body reads them any more, hence `allow(dead_code)`), once
    // inside the gate for the actual runtime check — without moving the
    // (single-use) role/scope literal iterators twice.
    let role_scope_consts = quote! {
        #[allow(dead_code)]
        const __AUTUMN_SECURED_ROLES: &[&str] = &[#(#role_literals),*];
        #[allow(dead_code)]
        const __AUTUMN_SECURED_SCOPES: &[&str] = &[#(#scope_literals),*];
    };
    let fn_name = input_fn.sig.ident.clone();
    let gate_ident = format_ident!("__AutumnSecuredGate_{}", fn_name);

    let session_check = if emit_session_check {
        quote! {
            // A real `Session` extraction (not a raw extensions lookup) so a
            // missing `SessionLayer` still fails loudly, exactly as the
            // hidden `__autumn_session: Session` handler parameter this
            // replaces did.
            let __autumn_session: ::autumn_web::session::Session = match
                <::autumn_web::session::Session as ::autumn_web::reexports::axum::extract::FromRequestParts<::autumn_web::AppState>>
                    ::from_request_parts(parts, state).await
            {
                ::core::result::Result::Ok(__session) => __session,
                ::core::result::Result::Err(__never) => match __never {},
            };
            if let ::core::result::Result::Err(__autumn_error) = ::autumn_web::auth::__check_secured_with_key(
                &__autumn_session,
                state.auth_session_key(),
                __AUTUMN_SECURED_ROLES,
            ).await {
                if __autumn_error.status() == ::autumn_web::reexports::http::StatusCode::UNAUTHORIZED {
                    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_finalized_session_response(&__autumn_idempotency_replay)
                    {
                        return ::core::result::Result::Err(__autumn_response);
                    }
                }
                return ::core::result::Result::Err(
                    ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_error),
                );
            }
        }
    } else {
        quote! {}
    };

    let scope_check = if emit_scope_check {
        quote! {
            let __autumn_token_scopes = parts
                .extensions
                .get::<::autumn_web::auth::ApiTokenScopes>()
                .cloned();
            if let ::core::result::Result::Err(__autumn_error) = ::autumn_web::auth::__check_secured_scopes(
                __autumn_token_scopes.as_ref(),
                __AUTUMN_SECURED_SCOPES,
            ).await {
                return ::core::result::Result::Err(
                    ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_error),
                );
            }
        }
    } else {
        quote! {}
    };

    // Whether THIS gate should also serve a cached idempotency replay: see
    // `should_own_replay` for the full ordering rationale (issue #1668's
    // pre-body gates and `#[authorize]`'s in-body check must never both skip
    // replay-ownership, nor both claim it).
    let owns_replay = should_own_replay(&input_fn);
    let replay_check = if owns_replay {
        crate::idempotency_guard::owned_replay_check_tokens()
    } else {
        quote! {}
    };

    // The marker consts stay in the handler body (not just the gate below) so
    // `api_doc::extract_secured_info` can still recover the role/scope values
    // for OpenAPI when `#[secured]` expands before the route macro.
    let markers = role_scope_consts.clone();

    // Both checks — and any replay lookup this gate owns — run inside a
    // `FromRequestParts` gate: a hidden parameter inserted ahead of the
    // handler's own parameters, rather than as a statement inside the handler
    // body. Axum resolves every `FromRequestParts` extractor before it ever
    // reaches a `FromRequest` body extractor (`Json` / `Form` / `Multipart`)
    // and short-circuits on the first rejection, so an unauthenticated /
    // unauthorized / replayed request never causes the body to be parsed.
    let gate_item = crate::request_gate::wrap_gate(
        &gate_ident,
        &quote! {
            #role_scope_consts
            #session_check
            #scope_check
            #replay_check
        },
    );

    let original_response =
        crate::param_helpers::build_original_response(&input_fn.block, &input_fn.sig.output);

    // Insert the gate as the FIRST parameter — ahead of every other
    // extractor, including any earlier-inserted guard gate (which then
    // correctly runs AFTER this one; see `should_own_replay`'s doc comment).
    crate::request_gate::insert_gate_param(&mut input_fn, &gate_ident);

    input_fn.block = syn::parse_quote! {
        {
            #markers
            #original_response
        }
    };

    quote! {
        #leading_items
        #gate_item
        #input_fn
    }
}

#[cfg(test)]
mod tests {
    use quote::quote;

    use super::{parse_secured_args, secured_macro};
    use crate::static_route::static_get_macro;

    /// Characterization test (Echo refactor, clone class: the
    /// `FromRequestParts` gate skeleton shared with `step_up`/`throttle`):
    /// pins `#[secured("admin", scopes = ["posts:write"])]`'s exact expansion
    /// — exercising the role check, the scope check, and (as the only guard
    /// on this handler) the replay lookup all at once — so that factoring the
    /// gate's struct+impl skeleton into `request_gate::wrap_gate` cannot
    /// silently change a single token of it.
    #[test]
    fn secured_macro_expansion_is_unchanged_by_the_gate_skeleton_refactor() {
        let generated = secured_macro(
            quote! { "admin", scopes = ["posts:write"] },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert_eq!(
            generated,
            include_str!("../testdata/secured_golden.txt").trim_end()
        );
    }

    /// Characterization test (Echo refactor, clone class: the
    /// `split_leading_items_and_fn` + asyncness-check + marker-check preamble
    /// shared byte-for-byte with `step_up`/`throttle`/`authorize`): pins the
    /// exact async-required message so factoring the preamble into
    /// `param_helpers` cannot silently change it or misattribute it to the
    /// wrong attribute name.
    #[test]
    fn secured_rejects_sync_functions_with_the_attribute_named_in_the_message() {
        let generated = secured_macro(
            quote! { "admin" },
            quote! {
                fn sync_handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("#[secured] can only be applied to async functions"),
            "should emit the exact async-required message naming #[secured]:\n{generated}"
        );
    }

    #[test]
    fn secured_rejects_when_invoked_on_a_static_route_handler_via_an_alias() {
        // Simulates real source using `use ::autumn_web::secured as auth;`:
        //   #[static_get("/private")]
        //   #[auth("admin")]
        //   async fn private() -> &'static str { "private" }
        // `static_get_macro` cannot recognize `auth` by name (Codex review on
        // #2513, tenth finding) and must accept the combination rather than
        // reject it, leaving the incompatibility for the guard's own macro to
        // catch via the marker it left behind. The compiler invokes the SAME
        // `secured_macro` function regardless of what alias the source used
        // to name it — aliasing changes only the surface spelling, never
        // which function actually runs — so calling `secured_macro` directly
        // here is exactly what real, aliased source code produces.
        let accepted = static_get_macro(
            quote! { "/private" },
            quote! {
                #[auth("admin")]
                async fn private() -> &'static str { "private" }
            },
        );
        assert!(
            !accepted.to_string().contains("compile_error"),
            "static_get_macro cannot recognize an aliased guard attribute by name, so it must \
             accept (not reject) at this point, deferring to the guard's own marker check: \
             {accepted}"
        );

        let accepted_fn = crate::param_helpers::extract_fn_item(accepted, "private");
        let generated = secured_macro(quote! { "admin" }, quote! { #accepted_fn }).to_string();

        assert!(
            generated.contains("compile_error"),
            "secured_macro must reject a handler already marked as a #[static_get] route, \
             regardless of what alias attribute name the source used to invoke it: {generated}"
        );
    }

    #[test]
    fn secured_rejects_when_a_marker_is_buried_inside_a_cached_wrapper() {
        // Simulates real source using `use ::autumn_web::secured as auth;`:
        //   #[static_get("/private")]
        //   #[cached]
        //   #[auth("admin")]
        //   async fn private() -> &'static str { "private" }
        // `#[static_get]` injects `STATIC_ROUTE_HANDLER_MARKER` into the top
        // of the original body, but `#[cached]` — the next attribute to
        // expand — re-homes that ENTIRE body (marker included) one level
        // deeper, inside its own `(|| async move { ... })().await` closure
        // IIFE (`cached_macro`'s `compute`). A marker scan that only looks at
        // the function's top-level statements would miss it entirely,
        // reopening the exact cache-bypass hole this whole rejection exists
        // to close (Codex review on #2513, eleventh finding).
        let marked = static_get_macro(
            quote! { "/private" },
            quote! {
                #[cached]
                #[auth("admin")]
                async fn private() -> &'static str { "private" }
            },
        );
        assert!(
            !marked.to_string().contains("compile_error"),
            "static_get_macro cannot recognize #[cached] or the aliased guard by name, so it \
             must accept at this point: {marked}"
        );

        let marked_fn = crate::param_helpers::extract_fn_item(marked, "private");
        let cached = crate::cached::cached_macro(quote! {}, quote! { #marked_fn });
        assert!(
            !cached.to_string().contains("compile_error"),
            "#[cached] knows nothing about route guards and must accept unconditionally: {cached}"
        );

        let cached_fn = crate::param_helpers::extract_fn_item(cached, "private");
        let generated = secured_macro(quote! { "admin" }, quote! { #cached_fn }).to_string();

        assert!(
            generated.contains("compile_error"),
            "secured_macro must still find the #[static_get] marker even after #[cached] buried \
             it inside a closure IIFE: {generated}"
        );
    }

    #[test]
    fn secured_string_literal_replay_guard_still_injects_replay_stop() {
        let generated = secured_macro(
            quote! {},
            quote! {
                async fn guarded() -> &'static str {
                    let _ = "__AUTUMN_IDEMPOTENCY_REPLAY_GUARD";
                    "ok"
                }
            },
        )
        .to_string();

        assert!(
            generated.contains("__replay_response"),
            "plain handler text must not suppress the generated replay stop: {generated}"
        );
    }

    // ── Parser (#1158) ───────────────────────────────────────────────────────

    #[test]
    fn parses_empty() {
        let a = parse_secured_args(quote! {}).unwrap();
        assert_eq!(a.roles, [] as [String; 0]);
        assert_eq!(a.scopes, [] as [String; 0]);
    }

    #[test]
    fn parses_roles_only() {
        let a = parse_secured_args(quote! { "admin", "editor" }).unwrap();
        assert_eq!(a.roles, vec!["admin", "editor"]);
        assert_eq!(a.scopes, [] as [String; 0]);
    }

    #[test]
    fn parses_scopes_only() {
        let a = parse_secured_args(quote! { scopes = ["posts:read", "posts:write"] }).unwrap();
        assert_eq!(a.roles, [] as [String; 0]);
        assert_eq!(a.scopes, vec!["posts:read", "posts:write"]);
    }

    #[test]
    fn parses_roles_and_scopes() {
        let a = parse_secured_args(quote! { "admin", scopes = ["posts:write"] }).unwrap();
        assert_eq!(a.roles, vec!["admin"]);
        assert_eq!(a.scopes, vec!["posts:write"]);
    }

    #[test]
    fn rejects_unknown_key() {
        assert!(parse_secured_args(quote! { foo = ["x"] }).is_err());
    }

    /// `#[secured(policy = "…")]` is not a form this macro has ever accepted,
    /// but it read like one: five doc sites (two of them `ignore`d rustdoc
    /// fences, which are never compiled) told readers to write it. The grammar
    /// is bare role literals and/or `scopes = [...]`; a `policy` key lands on
    /// the catch-all arm and fails the build. Pinned so the spelling cannot
    /// come back looking supported.
    #[test]
    fn rejects_policy_key() {
        assert!(parse_secured_args(quote! { policy = "reports.read" }).is_err());
    }

    #[test]
    fn rejects_non_string_scope_entries() {
        assert!(parse_secured_args(quote! { scopes = [1, 2] }).is_err());
    }

    // ── Codegen (#1158) ──────────────────────────────────────────────────────

    #[test]
    fn scopes_only_emits_scope_check_and_no_session_check() {
        let generated = secured_macro(
            quote! { scopes = ["posts:write"] },
            quote! { async fn h() -> &'static str { "ok" } },
        )
        .to_string();
        assert!(generated.contains("__check_secured_scopes"));
        assert!(
            !generated.contains("__check_secured_with_key"),
            "a scopes-only gate must not emit the session/role check: {generated}"
        );
        assert!(generated.contains("__AUTUMN_SECURED_SCOPES"));
        // No Session extractor is injected for a token-only route.
        assert!(!generated.contains("__autumn_session"));
    }

    #[test]
    fn roles_and_scopes_emits_both_checks() {
        let generated = secured_macro(
            quote! { "admin", scopes = ["posts:write"] },
            quote! { async fn h() -> &'static str { "ok" } },
        )
        .to_string();
        assert!(generated.contains("__check_secured_with_key"));
        assert!(generated.contains("__check_secured_scopes"));
        assert!(generated.contains("__autumn_session"));
    }

    #[test]
    fn roles_only_preserves_three_arg_session_check_and_marker() {
        let generated = secured_macro(
            quote! { "admin" },
            quote! { async fn h() -> &'static str { "ok" } },
        )
        .to_string();
        assert!(generated.contains("__check_secured_with_key"));
        assert!(!generated.contains("__check_secured_scopes"));
        // Both markers always emitted for OpenAPI extraction.
        assert!(generated.contains("__AUTUMN_SECURED_ROLES"));
        assert!(generated.contains("__AUTUMN_SECURED_SCOPES"));
    }

    // ── Pre-body FromRequestParts gate (#1668) ──────────────────────────────

    #[test]
    fn check_runs_in_a_from_request_parts_gate() {
        let generated = secured_macro(
            quote! { "admin" },
            quote! { async fn h() -> &'static str { "ok" } },
        )
        .to_string();
        assert!(
            generated.contains("FromRequestParts"),
            "the check must run in a FromRequestParts gate, not a body statement:\n{generated}"
        );
        assert!(
            generated.contains("struct __AutumnSecuredGate_h"),
            "should emit a handler-unique gate marker struct:\n{generated}"
        );
    }

    #[test]
    fn inserts_gate_as_first_parameter() {
        let generated_fn = {
            let generated = secured_macro(
                quote! { "admin" },
                quote! {
                    async fn h(::autumn_web::reexports::axum::extract::Json(_body): ::autumn_web::reexports::axum::extract::Json<String>) -> &'static str { "ok" }
                },
            );
            let items: syn::File = syn::parse2(generated).expect("generated tokens must parse");
            items
                .items
                .into_iter()
                .find_map(|item| match item {
                    syn::Item::Fn(f) if f.sig.ident == "h" => Some(f),
                    _ => None,
                })
                .expect("handler fn must be present in the expansion")
        };
        let first_param = generated_fn
            .sig
            .inputs
            .first()
            .expect("handler must have at least the gate parameter");
        let syn::FnArg::Typed(pat_type) = first_param else {
            panic!("first parameter must be a typed gate parameter");
        };
        let syn::Type::Path(type_path) = pat_type.ty.as_ref() else {
            panic!("gate parameter must be a named type");
        };
        assert_eq!(
            type_path.path.segments.last().unwrap().ident,
            "__AutumnSecuredGate_h",
            "the gate must be the FIRST parameter — ahead of the body extractor — so Axum \
             resolves (and can reject on) it before ever reaching the body"
        );
    }

    #[test]
    fn handler_body_no_longer_contains_the_session_check() {
        let generated_fn = {
            let generated = secured_macro(
                quote! { "admin" },
                quote! { async fn h() -> &'static str { "ok" } },
            );
            let items: syn::File = syn::parse2(generated).expect("generated tokens must parse");
            items
                .items
                .into_iter()
                .find_map(|item| match item {
                    syn::Item::Fn(f) if f.sig.ident == "h" => Some(f),
                    _ => None,
                })
                .expect("handler fn must be present in the expansion")
        };
        let body = quote! { #generated_fn }.to_string();
        assert!(
            !body.contains("__check_secured_with_key"),
            "the handler body must not call the runtime check directly:\n{body}"
        );
    }

    #[test]
    fn defers_replay_to_an_earlier_gate_when_stacked() {
        let generated = secured_macro(
            quote! { "admin" },
            quote! {
                async fn h(_g: __AutumnThrottleGate_h) -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            !generated.contains("__replay_response"),
            "must defer replay-ownership to the earlier-inserted gate:\n{generated}"
        );
    }

    #[test]
    fn defers_replay_when_authorize_still_pending() {
        let generated = secured_macro(
            quote! { "admin" },
            quote! {
                #[authorize("update", resource = Post)]
                async fn h() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            !generated.contains("__replay_response"),
            "must defer replay-ownership while #[authorize] is still pending:\n{generated}"
        );
    }

    /// Echo clone-class regression (missed-fix half): `step_up_macro` and
    /// `throttle_macro` both guard their `original_response` match with a
    /// recursive `type_contains_impl_trait` check (see their own
    /// `*_handles_nested_impl_trait_return_type` tests) specifically because
    /// Rust rejects `impl Trait` in local variable type annotations (E0562)
    /// even when it's nested, e.g. `Result<impl IntoResponse, _>`.
    /// `secured_macro` never received that fix — it still guards with a
    /// shallow `matches!(ty.as_ref(), syn::Type::ImplTrait(_))` that only
    /// catches a *top-level* `impl Trait` return type, so it emits
    /// `let __autumn_inner: Result<impl IntoResponse, _> = …`, which fails to
    /// compile for any real handler shaped like this.
    #[test]
    fn secured_handles_nested_impl_trait_return_type() {
        let generated = secured_macro(
            quote! { "admin" },
            quote! {
                async fn handler() -> Result<impl IntoResponse, String> {
                    Ok("ok")
                }
            },
        )
        .to_string();
        assert!(
            !generated.contains("__autumn_inner :"),
            "should not emit an explicit local annotation for nested impl Trait: {generated}"
        );
    }
}