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
//! `#[step_up]` proc macro implementation.
//!
//! Generates a step-up authentication 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 a stale/missing step-up session is rejected before the
//! request body is parsed, rather than after.
//!
//! ## Forms
//!
//! - `#[step_up]` -- require fresh auth with the default max-age (5 minutes)
//! - `#[step_up(max_age = "5m")]` -- require fresh auth within 5 minutes
//! - `#[step_up(max_age = "1h")]` -- require fresh auth within 1 hour
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::LitStr;
use crate::idempotency_guard::should_own_replay;
/// Parse the `#[step_up(max_age = "…")]` attribute arguments.
///
/// Returns `Some(seconds)` when `max_age` is specified, `None` for bare
/// `#[step_up]`.
fn parse_step_up_args(attr: TokenStream) -> syn::Result<Option<u64>> {
if attr.is_empty() {
return Ok(None);
}
let meta: syn::MetaNameValue = syn::parse2(attr)?;
let key = meta.path.get_ident().map(std::string::ToString::to_string);
if key.as_deref() != Some("max_age") {
return Err(syn::Error::new_spanned(
&meta.path,
"#[step_up] only accepts a `max_age` argument (e.g. #[step_up(max_age = \"5m\")])",
));
}
let value_str: LitStr = match &meta.value {
syn::Expr::Lit(expr_lit) => match &expr_lit.lit {
syn::Lit::Str(s) => s.clone(),
_ => {
return Err(syn::Error::new_spanned(
&meta.value,
"max_age must be a string literal, e.g. \"5m\"",
));
}
},
_ => {
return Err(syn::Error::new_spanned(
&meta.value,
"max_age must be a string literal, e.g. \"5m\"",
));
}
};
let secs = parse_max_age_str_at_compile_time(&value_str)
.map_err(|msg| syn::Error::new_spanned(&value_str, msg))?;
Ok(Some(secs))
}
/// Parse a duration string at macro-expansion time.
fn parse_max_age_str_at_compile_time(lit: &LitStr) -> Result<u64, String> {
let s = lit.value();
if let Some(mins) = s.strip_suffix('m') {
return mins
.parse::<u64>()
.map(|m| m * 60)
.map_err(|_| format!("invalid max_age: '{s}' (expected e.g. \"5m\")"));
}
if let Some(hours) = s.strip_suffix('h') {
return hours
.parse::<u64>()
.map(|h| h * 3600)
.map_err(|_| format!("invalid max_age: '{s}' (expected e.g. \"1h\")"));
}
if let Some(secs) = s.strip_suffix('s') {
return secs
.parse::<u64>()
.map_err(|_| format!("invalid max_age: '{s}' (expected e.g. \"30s\")"));
}
s.parse::<u64>()
.map_err(|_| format!("invalid max_age: '{s}' (expected seconds or e.g. \"5m\")"))
}
/// Build the runtime freshness-check token stream that runs inside the gate's
/// `from_request_parts`, after the extractor prelude has bound `state`,
/// `__autumn_session`, `__autumn_step_up_headers`, `__autumn_step_up_uri`,
/// `__autumn_step_up_method`, and `__autumn_idempotency_replay`.
fn build_check_call(max_age_tokens: &TokenStream) -> TokenStream {
quote! {
const __AUTUMN_STEP_UP_MAX_AGE: ::core::option::Option<u64> = #max_age_tokens;
// Resolve max_age before the check so the response can advertise the
// exact value actually enforced (not the compile-time default).
let __max_age_secs: u64 =
::autumn_web::step_up::__resolve_step_up_max_age(state, __AUTUMN_STEP_UP_MAX_AGE);
if let ::core::result::Result::Err(__autumn_step_up_error) =
::autumn_web::step_up::__check_step_up_with_config(
&__autumn_session,
state,
__AUTUMN_STEP_UP_MAX_AGE,
).await
{
if let ::core::option::Option::Some(__autumn_response) =
::autumn_web::idempotency::__replay_finalized_session_response_for_anonymous(
&__autumn_session,
state.auth_session_key(),
&__autumn_idempotency_replay,
)
.await
{
return ::core::result::Result::Err(__autumn_response);
}
let __wants_json: bool = __autumn_step_up_headers
.get(::autumn_web::reexports::axum::http::header::ACCEPT)
.and_then(|v| v.to_str().ok())
.map(|s| s.contains("application/json") || s.contains("+json"))
.unwrap_or(false);
if __wants_json {
return ::core::result::Result::Err(
::autumn_web::step_up::__step_up_json_response(__max_age_secs),
);
} else {
// For non-GET requests: prefer Referer so the user returns to
// the page with the form after reauth rather than a POST/DELETE
// endpoint that has no GET handler.
// For GET requests: use the current URI so the user is sent
// directly back to the page they were trying to open.
let __is_mutating = __autumn_step_up_method != ::autumn_web::reexports::axum::http::Method::GET;
let __return_to: ::std::string::String = if __is_mutating {
let __referer_path = __autumn_step_up_headers
.get(::autumn_web::reexports::axum::http::header::REFERER)
.and_then(|v| v.to_str().ok())
.and_then(::autumn_web::step_up::referer_path);
let __path = __referer_path.as_deref().unwrap_or_else(|| {
__autumn_step_up_uri
.path_and_query()
.map(|pq| pq.as_str())
.unwrap_or_else(|| __autumn_step_up_uri.path())
});
::autumn_web::step_up::encode_return_to(__path)
} else {
::autumn_web::step_up::encode_return_to(
__autumn_step_up_uri
.path_and_query()
.map(|pq| pq.as_str())
.unwrap_or_else(|| __autumn_step_up_uri.path()),
)
};
return ::core::result::Result::Err(
::autumn_web::reexports::axum::response::IntoResponse::into_response(
::autumn_web::reexports::axum::response::Redirect::to(
&::std::format!("/reauth?return_to={__return_to}")
)
),
);
}
}
}
}
/// Expand the `#[step_up]` / `#[step_up(max_age = "Nm")]` attribute.
#[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 step_up_macro(attr: TokenStream, item: TokenStream) -> TokenStream {
let max_age_opt = match parse_step_up_args(attr) {
Ok(v) => v,
Err(err) => return err.to_compile_error(),
};
let (leading_items, mut input_fn) =
match crate::param_helpers::split_leading_items_and_reject_incompatible(&item, "step_up") {
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;
}
let max_age_tokens = max_age_opt.map_or_else(
|| quote! { ::core::option::Option::None },
|n| {
let lit = proc_macro2::Literal::u64_suffixed(n);
quote! { ::core::option::Option::Some(#lit) }
},
);
let check_call = build_check_call(&max_age_tokens);
// Inert copy of `check_call`'s own `__AUTUMN_STEP_UP_MAX_AGE` const,
// spliced into the handler body below (mirroring `secured_macro`'s
// `role_scope_consts`/`markers` split): #1668 moved the step-up check
// itself into the gate below, so `check_call`'s copy of this const never
// reaches the handler's own body any more, but
// `api_doc::infer_response_body`'s guard recovery
// (`RESPONSE_REWRITING_GUARD_MARKERS`) requires exactly this const IN the
// body to tell a real guard's `__autumn_inner` wrapper apart from
// unrelated code with the same shape (issue #2516), so
// `api_doc::recover_guarded_return_type` can still recover the
// pre-rewrite return type for OpenAPI when #[step_up] expands before the
// route macro (#1677).
let max_age_marker = quote! {
#[allow(dead_code)]
const __AUTUMN_STEP_UP_MAX_AGE: ::core::option::Option<u64> = #max_age_tokens;
};
let fn_name = input_fn.sig.ident.clone();
let gate_ident = format_ident!("__AutumnStepUpGate_{}", fn_name);
// 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). Replay is checked BEFORE the
// step-up freshness check (unchanged from before this gate existed): a
// cached response for an already-completed mutation needs no fresh
// step-up to replay, since replaying serves the exact stored bytes rather
// than re-executing the handler.
let owns_replay = should_own_replay(&input_fn);
let replay_check = if owns_replay {
crate::idempotency_guard::owned_replay_check_tokens()
} else {
quote! {
let __autumn_idempotency_replay = parts
.extensions
.get::<::autumn_web::idempotency::IdempotencyReplayResponse>()
.cloned()
.map(::autumn_web::reexports::axum::extract::Extension);
}
};
// Both the freshness check and the replay lookup 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 a stale/missing step-up
// session never causes the body to be parsed.
let gate_item = crate::request_gate::wrap_gate(
&gate_ident,
"e! {
// 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 {},
};
let __autumn_step_up_headers = parts.headers.clone();
let __autumn_step_up_uri = parts.uri.clone();
let __autumn_step_up_method = parts.method.clone();
#replay_check
#check_call
},
);
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! {
{
#max_age_marker
#original_response
}
};
quote! {
#leading_items
#gate_item
#input_fn
}
}
// ── Tests ────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use quote::quote;
use super::step_up_macro;
use crate::static_route::static_get_macro;
/// Characterization test (Echo refactor, clone class: the
/// `FromRequestParts` gate skeleton shared with `secured`/`throttle`):
/// pins `#[step_up(max_age = "5m")]`'s exact expansion — exercising the
/// session extraction, the freshness 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 step_up_macro_expansion_is_unchanged_by_the_gate_skeleton_refactor() {
let generated = step_up_macro(
quote! { max_age = "5m" },
quote! {
async fn handler() -> &'static str { "ok" }
},
)
.to_string();
assert_eq!(
generated,
include_str!("../testdata/step_up_golden.txt").trim_end()
);
}
#[test]
fn step_up_rejects_when_invoked_on_a_static_route_handler_via_an_alias() {
// See `secured::tests::secured_rejects_when_invoked_on_a_static_route_handler_via_an_alias`
// for the full rationale (Codex review on #2513, tenth finding).
let accepted = static_get_macro(
quote! { "/private" },
quote! {
#[auth]
async fn private() -> &'static str { "private" }
},
);
assert!(
!accepted.to_string().contains("compile_error"),
"static_get_macro cannot recognize an aliased guard attribute by name: {accepted}"
);
let accepted_fn = crate::param_helpers::extract_fn_item(accepted, "private");
let generated = step_up_macro(quote! {}, quote! { #accepted_fn }).to_string();
assert!(
generated.contains("compile_error"),
"step_up_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 step_up_bare_generates_check_call() {
let generated = step_up_macro(
quote! {},
quote! {
async fn delete_account() -> &'static str {
"deleted"
}
},
)
.to_string();
assert!(
generated.contains("__check_step_up_with_config"),
"bare #[step_up] should generate a step-up check:\n{generated}"
);
}
#[test]
fn step_up_with_max_age_minutes_emits_seconds() {
let generated = step_up_macro(
quote! { max_age = "5m" },
quote! {
async fn delete_account() -> &'static str {
"deleted"
}
},
)
.to_string();
assert!(
generated.contains("__check_step_up_with_config"),
"should contain step-up check:\n{generated}"
);
assert!(
generated.contains("300u64"),
"5m should expand to 300u64:\n{generated}"
);
}
#[test]
fn step_up_with_max_age_hours() {
let generated = step_up_macro(
quote! { max_age = "1h" },
quote! {
async fn handler() -> &'static str { "ok" }
},
)
.to_string();
assert!(
generated.contains("3600u64"),
"1h should expand to 3600u64:\n{generated}"
);
}
#[test]
fn step_up_with_max_age_seconds() {
let generated = step_up_macro(
quote! { max_age = "30s" },
quote! {
async fn handler() -> &'static str { "ok" }
},
)
.to_string();
assert!(
generated.contains("30u64"),
"30s should expand to 30u64:\n{generated}"
);
}
#[test]
fn step_up_injects_session_parameter() {
let generated = step_up_macro(
quote! {},
quote! {
async fn handler() -> &'static str { "ok" }
},
)
.to_string();
assert!(
generated.contains("__autumn_session"),
"should inject session parameter:\n{generated}"
);
}
#[test]
fn check_runs_in_a_from_request_parts_gate() {
let generated = step_up_macro(
quote! {},
quote! {
async fn handler() -> &'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 __AutumnStepUpGate_handler"),
"should emit a handler-unique gate marker struct:\n{generated}"
);
assert!(
!generated.contains("__autumn_state"),
"the old hidden State<AppState> handler parameter should be gone — the gate reads \
state from its own `from_request_parts` argument instead:\n{generated}"
);
}
#[test]
fn step_up_injects_headers_parameter() {
let generated = step_up_macro(
quote! {},
quote! {
async fn handler() -> &'static str { "ok" }
},
)
.to_string();
assert!(
generated.contains("__autumn_step_up_headers"),
"should inject headers parameter:\n{generated}"
);
}
#[test]
fn step_up_injects_uri_parameter() {
let generated = step_up_macro(
quote! {},
quote! {
async fn handler() -> &'static str { "ok" }
},
)
.to_string();
assert!(
generated.contains("__autumn_step_up_uri"),
"should inject URI parameter:\n{generated}"
);
}
#[test]
fn step_up_rejects_sync_functions() {
let generated = step_up_macro(
quote! {},
quote! {
fn sync_handler() -> &'static str { "ok" }
},
)
.to_string();
assert!(
generated.contains("compile_error"),
"should emit compile_error for non-async functions:\n{generated}"
);
}
#[test]
fn step_up_rejects_unknown_attribute_key() {
let generated = step_up_macro(
quote! { unknown_arg = "value" },
quote! {
async fn handler() -> &'static str { "ok" }
},
)
.to_string();
assert!(
generated.contains("compile_error"),
"should emit compile_error for unknown attribute key:\n{generated}"
);
}
#[test]
fn step_up_generates_redirect_for_html_client() {
let generated = step_up_macro(
quote! {},
quote! {
async fn handler() -> &'static str { "ok" }
},
)
.to_string();
// Should redirect to /reauth?return_to=… for non-JSON clients
assert!(
generated.contains("/reauth"),
"should redirect to /reauth for HTML clients:\n{generated}"
);
}
#[test]
fn step_up_generates_json_response_branch() {
let generated = step_up_macro(
quote! {},
quote! {
async fn handler() -> &'static str { "ok" }
},
)
.to_string();
// Should call __step_up_json_response for JSON clients
assert!(
generated.contains("__step_up_json_response"),
"should call JSON response helper for API clients:\n{generated}"
);
}
#[test]
fn inserts_gate_as_first_parameter_when_stacked_with_secured() {
// Simulate `#[secured]` having already expanded and inserted its own
// gate parameter ahead of `#[step_up]`'s. Each gate is now an
// independent `FromRequestParts` parameter (issue #1668) rather than a
// shared hidden `Session`/`State` pair, so there is no more
// duplicate-parameter risk to guard against — but `#[step_up]`'s own
// gate must still land as the new FIRST parameter, ahead of
// `#[secured]`'s (which then correctly runs second; see
// `should_own_replay`'s doc comment).
let generated_fn = {
let generated = step_up_macro(
quote! {},
quote! {
async fn handler(_g: __AutumnSecuredGate_handler) -> &'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 == "handler" => 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,
"__AutumnStepUpGate_handler",
"the newly-inserted gate must be the FIRST parameter"
);
}
#[test]
fn defers_replay_when_authorize_still_pending() {
let generated = step_up_macro(
quote! {},
quote! {
#[authorize("update", resource = Post)]
async fn handler() -> &'static str { "ok" }
},
)
.to_string();
assert!(
!generated.contains("__replay_response"),
"must defer replay-ownership while #[authorize] is still pending:\n{generated}"
);
}
#[test]
fn owns_replay_when_unguarded() {
let generated = step_up_macro(
quote! {},
quote! {
async fn handler() -> &'static str { "ok" }
},
)
.to_string();
assert!(
generated.contains("__replay_response"),
"an otherwise-unguarded step-up handler's gate must own replay-serving:\n{generated}"
);
}
#[test]
fn defers_replay_to_an_earlier_gate_when_stacked() {
// Simulate `#[secured]` having already expanded and inserted its own
// gate parameter ahead of `#[step_up]`'s.
let generated = step_up_macro(
quote! {},
quote! {
async fn handler(_g: __AutumnSecuredGate_handler) -> &'static str { "ok" }
},
)
.to_string();
assert!(
!generated.contains("__replay_response"),
"must defer replay-ownership to the earlier-inserted gate:\n{generated}"
);
}
#[test]
fn step_up_injects_method_parameter() {
let generated = step_up_macro(
quote! {},
quote! {
async fn handler() -> &'static str { "ok" }
},
)
.to_string();
assert!(
generated.contains("__autumn_step_up_method"),
"should inject method parameter for GET/POST distinction:\n{generated}"
);
}
#[test]
fn step_up_uses_resolve_max_age_for_json_response() {
let generated = step_up_macro(
quote! {},
quote! {
async fn handler() -> &'static str { "ok" }
},
)
.to_string();
assert!(
generated.contains("__resolve_step_up_max_age"),
"should call __resolve_step_up_max_age so WWW-Authenticate max-age \
reflects the actual configured value:\n{generated}"
);
}
#[test]
fn step_up_handles_nested_impl_trait_return_type() {
// Rust rejects `impl Trait` in local variable type annotations.
// A handler returning `Result<impl IntoResponse, _>` or
// `AutumnResult<impl IntoResponse>` must not produce
// `let __autumn_inner: Result<impl IntoResponse, _> = …`.
let generated = step_up_macro(
quote! {},
quote! {
async fn handler() -> Result<impl IntoResponse, String> {
Ok("ok")
}
},
)
.to_string();
// The generated code must NOT contain the explicit local-type annotation
// when the return type contains impl Trait.
assert!(
!generated.contains("__autumn_inner :"),
"should not emit an explicit local annotation for nested impl Trait: {generated}"
);
}
}