Skip to main content

axiam_sdk_macros/
lib.rs

1//! Proc-macro Actix-Web authorization attributes for the AXIAM Rust SDK.
2//!
3//! This crate is an implementation detail of [`axiam-sdk`]; do not depend on
4//! it directly. The three attribute macros it exports are re-exported from
5//! `axiam-sdk` behind its `macros` feature, so consumers write
6//! `use axiam_sdk::require_access;` and never name this crate.
7//!
8//! The macros implement the CONTRACT.md §11 *declarative authorization
9//! helpers* on top of the §10 `AxiamUser` route-guard extractor. They are
10//! deliberately **thin**: each one expands to a small wrapper that delegates
11//! to the runtime helpers in [`axiam_sdk::middleware`] (`RequireAccess`,
12//! `resource_from_path`, `require_role_check`, …), so the enforcement logic
13//! lives in ordinary, unit-testable library code rather than inside macro
14//! expansion.
15//!
16//! - [`macro@require_auth`] — require an authenticated AXIAM identity (401 on
17//!   failure).
18//! - [`macro@require_access`] — require the authenticated caller to pass an
19//!   AXIAM authorization check for an `action` on a request-resolved resource
20//!   (401 unauthenticated, 403 denied, 400 unresolvable resource, 503 authz
21//!   transport failure — fail closed).
22//! - [`macro@require_role`] — require one of a set of roles, checked locally
23//!   against the verified token's claims (403 on failure).
24//!
25//! [`axiam-sdk`]: https://docs.rs/axiam-sdk
26//! [`axiam_sdk::middleware`]: https://docs.rs/axiam-sdk/latest/axiam_sdk/middleware/
27
28use proc_macro::TokenStream;
29use quote::{format_ident, quote};
30use syn::punctuated::Punctuated;
31use syn::{Expr, ExprLit, ExprPath, ItemFn, Lit, Meta, Pat, Token, parse_macro_input};
32
33/// Require an authenticated AXIAM identity on an Actix-Web handler
34/// (CONTRACT.md §11 `require_auth`).
35///
36/// Pure sugar over the §10 [`AxiamUser`] extractor: the attribute injects an
37/// `AxiamUser` extractor parameter into the handler, so Actix rejects the
38/// request with `401 authentication_failed` before the handler body runs if
39/// no verified identity is present. The handler's own signature, parameters
40/// and return type are otherwise unchanged.
41///
42/// ```ignore
43/// use axiam_sdk::require_auth;
44///
45/// #[require_auth]
46/// async fn whoami() -> &'static str {
47///     "you are authenticated"
48/// }
49/// ```
50///
51/// The handler may still declare its own `AxiamUser` parameter if it needs
52/// the identity in its body — the injected extractor is independent of it.
53///
54/// [`AxiamUser`]: https://docs.rs/axiam-sdk/latest/axiam_sdk/middleware/struct.AxiamUser.html
55#[proc_macro_attribute]
56pub fn require_auth(args: TokenStream, item: TokenStream) -> TokenStream {
57    if !args.is_empty() {
58        return compile_error(
59            proc_macro2::TokenStream::from(args),
60            "require_auth takes no arguments",
61        );
62    }
63    let mut func = parse_macro_input!(item as ItemFn);
64    if func.sig.asyncness.is_none() {
65        return compile_error_spanned(func.sig.fn_token, "require_auth requires an `async fn`");
66    }
67
68    // Inject a leading `AxiamUser` extractor parameter. Named with a leading
69    // underscore so it does not trip `unused_variables` when the body ignores
70    // it — Actix still runs the extractor (and its §10 401 path) regardless.
71    let injected: syn::FnArg = syn::parse_quote! {
72        _axiam_require_auth_user: ::axiam_sdk::middleware::AxiamUser
73    };
74    func.sig.inputs.insert(0, injected);
75
76    quote!(#func).into()
77}
78
79/// Require the authenticated caller to pass an AXIAM authorization check on an
80/// Actix-Web handler (CONTRACT.md §11 `require_access`).
81///
82/// Runs strictly *after* §10 authentication and consumes the identity it
83/// injected — it never re-implements token extraction/verification. The check
84/// is issued for the **request's** authenticated user (its `user_id` is sent
85/// as `subject_id`), not for the application's own `AxiamClient` session.
86///
87/// # Arguments
88///
89/// - `action` (**required**) — the permission action string, e.g.
90///   `action = "read"`.
91/// - Exactly one resource selector:
92///   - `resource_param = "id"` — the name of a path parameter whose value is
93///     parsed as the resource `Uuid`;
94///   - `resource_id = "<uuid>"` — a static UUID literal, for singleton
95///     resources;
96///   - `resolver = path::to::fn` — a function
97///     `fn(&actix_web::HttpRequest) -> Result<uuid::Uuid, axiam_sdk::middleware::AuthzGuardError>`
98///     for anything else (body fields, headers, composite lookups).
99/// - `scope = "…"` (optional) — passed through to `check_access` verbatim.
100///
101/// # Requirements on the annotated handler
102///
103/// - It must be an `async fn`.
104/// - The application must register `web::Data<AxiamClient>` (used to issue the
105///   check) and `web::Data<JwksVerifier>` (used by the §10 extractor) as app
106///   data.
107/// - Any handler parameters must be simple identifiers (so they can be
108///   forwarded to the original body).
109///
110/// # Error mapping (CONTRACT.md §11.5)
111///
112/// | Condition | Status | `error` code |
113/// |-----------|--------|--------------|
114/// | no verified identity | 401 | `authentication_failed` |
115/// | check returns `allowed = false` / server 403 | 403 | `authorization_denied` |
116/// | resource id missing or not a UUID | 400 | `invalid_request` |
117/// | transport failure reaching authz (fail closed) | 503 | `authz_unavailable` |
118///
119/// ```ignore
120/// use axiam_sdk::{require_access, middleware::AxiamUser};
121///
122/// #[require_access(action = "read", resource_param = "id")]
123/// async fn get_document(user: AxiamUser) -> String {
124///     format!("user {} may read this document", user.user_id)
125/// }
126/// ```
127#[proc_macro_attribute]
128pub fn require_access(args: TokenStream, item: TokenStream) -> TokenStream {
129    let metas = parse_macro_input!(args with Punctuated::<Meta, Token![,]>::parse_terminated);
130    let func = parse_macro_input!(item as ItemFn);
131
132    let mut action: Option<String> = None;
133    let mut resource_param: Option<String> = None;
134    let mut resource_id: Option<String> = None;
135    let mut resolver: Option<ExprPath> = None;
136    let mut scope: Option<String> = None;
137
138    for meta in metas {
139        let nv = match meta {
140            Meta::NameValue(nv) => nv,
141            other => {
142                return compile_error_spanned(
143                    &other,
144                    "require_access arguments must be `name = value` pairs",
145                );
146            }
147        };
148        if nv.path.is_ident("action") {
149            match lit_string(&nv.value) {
150                Some(s) => action = Some(s),
151                None => {
152                    return compile_error_spanned(&nv.value, "`action` must be a string literal");
153                }
154            }
155        } else if nv.path.is_ident("resource_param") {
156            match lit_string(&nv.value) {
157                Some(s) => resource_param = Some(s),
158                None => {
159                    return compile_error_spanned(
160                        &nv.value,
161                        "`resource_param` must be a string literal",
162                    );
163                }
164            }
165        } else if nv.path.is_ident("resource_id") {
166            match lit_string(&nv.value) {
167                Some(s) => resource_id = Some(s),
168                None => {
169                    return compile_error_spanned(
170                        &nv.value,
171                        "`resource_id` must be a string literal (a UUID)",
172                    );
173                }
174            }
175        } else if nv.path.is_ident("scope") {
176            match lit_string(&nv.value) {
177                Some(s) => scope = Some(s),
178                None => {
179                    return compile_error_spanned(&nv.value, "`scope` must be a string literal");
180                }
181            }
182        } else if nv.path.is_ident("resolver") {
183            match &nv.value {
184                Expr::Path(p) => resolver = Some(p.clone()),
185                other => {
186                    return compile_error_spanned(other, "`resolver` must be a path to a function");
187                }
188            }
189        } else {
190            return compile_error_spanned(
191                &nv.path,
192                "unknown argument (expected one of: action, resource_param, resource_id, resolver, scope)",
193            );
194        }
195    }
196
197    let action = match action {
198        Some(a) => a,
199        None => {
200            return compile_error_spanned(
201                &func.sig,
202                "require_access requires an `action`, e.g. #[require_access(action = \"read\", resource_param = \"id\")]",
203            );
204        }
205    };
206
207    let selector_count =
208        resource_param.is_some() as u8 + resource_id.is_some() as u8 + resolver.is_some() as u8;
209    if selector_count == 0 {
210        return compile_error_spanned(
211            &func.sig,
212            "require_access requires exactly one resource selector: `resource_param`, `resource_id`, or `resolver`",
213        );
214    }
215    if selector_count > 1 {
216        return compile_error_spanned(
217            &func.sig,
218            "require_access accepts only one resource selector: specify exactly one of `resource_param`, `resource_id`, or `resolver`",
219        );
220    }
221
222    if func.sig.asyncness.is_none() {
223        return compile_error_spanned(func.sig.fn_token, "require_access requires an `async fn`");
224    }
225
226    // How to resolve the resource `Uuid` from the request, per selector.
227    let resolve_expr = if let Some(param) = resource_param {
228        quote! { ::axiam_sdk::middleware::resource_from_path(&__axiam_req, #param) }
229    } else if let Some(id) = resource_id {
230        quote! { ::axiam_sdk::middleware::resource_from_static(#id) }
231    } else {
232        let resolver = resolver.expect("selector_count guarantees a resolver here");
233        quote! { #resolver(&__axiam_req) }
234    };
235
236    let scope_call = match scope {
237        Some(s) => quote! { .scope(#s) },
238        None => quote! {},
239    };
240
241    let guard = quote! {
242        // Type is inferred as `uuid::Uuid` from the resolver's return type, so
243        // the expansion does not require the consumer crate to name `uuid`.
244        let __axiam_resource_id = match #resolve_expr {
245            ::core::result::Result::Ok(id) => id,
246            ::core::result::Result::Err(err) => {
247                return ::actix_web::ResponseError::error_response(&err);
248            }
249        };
250        if let ::core::result::Result::Err(err) = ::axiam_sdk::middleware::RequireAccess::new(#action)
251            #scope_call
252            .check(&__axiam_client, &__axiam_require_access_user, __axiam_resource_id)
253            .await
254        {
255            return ::actix_web::ResponseError::error_response(&err);
256        }
257    };
258
259    let extra_inputs = quote! {
260        __axiam_req: ::actix_web::HttpRequest,
261        __axiam_require_access_user: ::axiam_sdk::middleware::AxiamUser,
262        __axiam_client: ::actix_web::web::Data<::axiam_sdk::client::AxiamClient>,
263    };
264
265    expand_wrapper(func, extra_inputs, guard)
266}
267
268/// Require one of a set of roles on an Actix-Web handler (CONTRACT.md §11
269/// `require_role`).
270///
271/// A **local** check against the verified token's `roles` claim — it performs
272/// no server round-trip, so it is cheaper but coarser than
273/// [`macro@require_access`]. Role names are tenant-defined; `require_access`
274/// remains the authoritative, resource-level check. Passes if the caller
275/// holds **at least one** of the listed roles, otherwise responds
276/// `403 authorization_denied`. An unauthenticated request is rejected with
277/// `401 authentication_failed` by the injected §10 extractor first.
278///
279/// ```ignore
280/// use axiam_sdk::require_role;
281///
282/// #[require_role("admin", "superadmin")]
283/// async fn admin_panel() -> &'static str {
284///     "welcome, admin"
285/// }
286/// ```
287#[proc_macro_attribute]
288pub fn require_role(args: TokenStream, item: TokenStream) -> TokenStream {
289    let roles = parse_macro_input!(args with Punctuated::<Expr, Token![,]>::parse_terminated);
290    let func = parse_macro_input!(item as ItemFn);
291
292    let mut role_lits: Vec<String> = Vec::new();
293    for expr in &roles {
294        match lit_string(expr) {
295            Some(s) => role_lits.push(s),
296            None => {
297                return compile_error_spanned(
298                    expr,
299                    "require_role arguments must be string literals",
300                );
301            }
302        }
303    }
304    if role_lits.is_empty() {
305        return compile_error_spanned(
306            &func.sig,
307            "require_role requires at least one role, e.g. #[require_role(\"admin\")]",
308        );
309    }
310
311    if func.sig.asyncness.is_none() {
312        return compile_error_spanned(func.sig.fn_token, "require_role requires an `async fn`");
313    }
314
315    let guard = quote! {
316        if let ::core::result::Result::Err(err) = ::axiam_sdk::middleware::require_role_check(
317            &__axiam_require_role_user,
318            &[#(#role_lits),*],
319        ) {
320            return ::actix_web::ResponseError::error_response(&err);
321        }
322    };
323
324    let extra_inputs = quote! {
325        __axiam_req: ::actix_web::HttpRequest,
326        __axiam_require_role_user: ::axiam_sdk::middleware::AxiamUser,
327    };
328
329    expand_wrapper(func, extra_inputs, guard)
330}
331
332/// Build the wrapper handler shared by `require_access` and `require_role`.
333///
334/// The original handler is nested (renamed) inside a generated wrapper that
335/// declares the injected extractor parameters (`extra_inputs`) alongside the
336/// original ones, runs `guard`, then — on success — calls the original body
337/// and adapts its return value with `Responder::respond_to`. This keeps the
338/// wrapper compatible with any handler whose return type implements
339/// `Responder` (including `Result<T, actix_web::Error>`).
340fn expand_wrapper(
341    func: ItemFn,
342    extra_inputs: proc_macro2::TokenStream,
343    guard: proc_macro2::TokenStream,
344) -> TokenStream {
345    let attrs = &func.attrs;
346    let vis = &func.vis;
347    let sig = &func.sig;
348    let name = &sig.ident;
349    let orig_inputs = &sig.inputs;
350
351    // Collect the original parameter identifiers to forward to the nested
352    // implementation. Only simple `ident: Type` parameters are supported.
353    let mut forward = Vec::new();
354    for input in orig_inputs.iter() {
355        match input {
356            syn::FnArg::Receiver(recv) => {
357                return compile_error_spanned(
358                    recv,
359                    "require_* macros cannot be applied to methods with a `self` receiver",
360                );
361            }
362            syn::FnArg::Typed(pat_type) => match &*pat_type.pat {
363                Pat::Ident(pat_ident) => forward.push(pat_ident.ident.clone()),
364                other => {
365                    return compile_error_spanned(
366                        other,
367                        "require_* handler parameters must be simple identifiers",
368                    );
369                }
370            },
371        }
372    }
373
374    let inner_name = format_ident!("__axiam_impl_{}", name);
375    let inner_sig = {
376        let mut s = sig.clone();
377        s.ident = inner_name.clone();
378        s
379    };
380    let inner_block = &func.block;
381
382    let comma = if orig_inputs.is_empty() {
383        quote! {}
384    } else {
385        quote! {,}
386    };
387
388    let expanded = quote! {
389        #(#attrs)*
390        #vis async fn #name(
391            #extra_inputs
392            #orig_inputs #comma
393        ) -> ::actix_web::HttpResponse {
394            // The original handler, nested so it does not leak into the
395            // surrounding namespace.
396            #inner_sig #inner_block
397
398            #guard
399
400            let __axiam_inner_result = #inner_name(#(#forward),*).await;
401            ::actix_web::Responder::respond_to(__axiam_inner_result, &__axiam_req)
402                .map_into_boxed_body()
403        }
404    };
405    expanded.into()
406}
407
408/// Extract a `String` from a string-literal expression, if that is what it is.
409fn lit_string(expr: &Expr) -> Option<String> {
410    match expr {
411        Expr::Lit(ExprLit {
412            lit: Lit::Str(s), ..
413        }) => Some(s.value()),
414        _ => None,
415    }
416}
417
418/// Emit a `compile_error!` at the call site (no useful span available).
419fn compile_error(tokens: proc_macro2::TokenStream, message: &str) -> TokenStream {
420    syn::Error::new_spanned(tokens, message)
421        .to_compile_error()
422        .into()
423}
424
425/// Emit a `compile_error!` spanned at `tokens` with `message`.
426fn compile_error_spanned<T: quote::ToTokens>(tokens: T, message: &str) -> TokenStream {
427    syn::Error::new_spanned(tokens, message)
428        .to_compile_error()
429        .into()
430}
431
432// ---------------------------------------------------------------------------
433// §22.14 — declarative reactor handler binding
434// ---------------------------------------------------------------------------
435
436/// The §22.5 hookable events, for compile-time validation of
437/// [`macro@reactor_handler`]'s argument.
438///
439/// A copy of `axiam_sdk::amqp::reactor::registry::EVENT_REGISTRY`'s names, and
440/// necessarily a copy: a proc-macro crate is compiled for the HOST and cannot
441/// depend on the library it expands into. `tests/reactor_macro_test.rs` in the
442/// parent crate asserts the two lists agree, so an event added to the registry
443/// and not to this list fails a test rather than silently becoming unbindable.
444///
445/// Note what is **not** here and never will be: a list of the three hot-path
446/// operations §22.7 excludes. They are refused because they are absent from
447/// *this* list, not because they appear on another one — §22.13 requires them
448/// to be absent from every event constant the SDK exposes, and §22.14 rule 2
449/// restates that for exactly this temptation (a nicer error message).
450const HOOKABLE_EVENTS: &[&str] = &[
451    "token.pre_issue",
452    "login.post_auth",
453    "user.pre_create",
454    "user.pre_update",
455    "grant.pre_assign",
456];
457
458/// Bind an `async fn` to one reactor hook event (CONTRACT.md §22.14).
459///
460/// The event name lives next to the function that handles it, and is checked
461/// **at compile time** against the §22.5 registry — so a typo is a build
462/// failure rather than an event that silently never fires.
463///
464/// ```ignore
465/// use axiam_sdk::amqp::reactor::{ReactorDecision, ReactorEvent, ReactorRouter};
466/// use axiam_sdk::reactor_handler;
467///
468/// #[reactor_handler("token.pre_issue")]
469/// async fn enrich_token(event: ReactorEvent) -> ReactorDecision {
470///     ReactorDecision::mutate([("ext.department", "engineering")])
471/// }
472///
473/// let handler = ReactorRouter::new().on::<enrich_token>().build()?;
474/// ```
475///
476/// # What it expands to
477///
478/// The function is emitted **unchanged**, so it stays directly callable and
479/// directly unit-testable. Alongside it the macro emits a braced marker struct
480/// of the same name — braced, so it occupies only the *type* namespace and does
481/// not collide with the function in the value namespace — carrying an
482/// `impl ReactorHandlerFn` whose `EVENT` associated constant is the validated
483/// literal. `ReactorRouter::on::<T>()` reads it from there.
484///
485/// # What it deliberately does not do
486///
487/// It adds no dispatch, no error handling and no answer of its own. §22.14's
488/// rules — an unbound event abstains, a handler's own panic propagates, a patch
489/// is never filtered — are enforced by [`ReactorRouter`], one place, whichever
490/// way a handler was bound.
491///
492/// [`ReactorRouter`]: https://docs.rs/axiam-sdk/latest/axiam_sdk/amqp/reactor/struct.ReactorRouter.html
493#[proc_macro_attribute]
494pub fn reactor_handler(args: TokenStream, item: TokenStream) -> TokenStream {
495    let args2 = proc_macro2::TokenStream::from(args.clone());
496    let parsed = match syn::parse::<ExprLit>(args) {
497        Ok(lit) => lit,
498        Err(_) => {
499            return compile_error(
500                args2,
501                "reactor_handler takes one string literal: the §22.5 event name, \
502                 e.g. #[reactor_handler(\"token.pre_issue\")]",
503            );
504        }
505    };
506    let Some(event) = lit_string(&Expr::Lit(parsed.clone())) else {
507        return compile_error(
508            args2,
509            "reactor_handler's argument must be a string literal event name",
510        );
511    };
512
513    if !HOOKABLE_EVENTS.contains(&event.as_str()) {
514        return compile_error_spanned(
515            &parsed,
516            &format!(
517                "{event} is not a hookable reactor event; the registry is [{}]",
518                HOOKABLE_EVENTS.join(", ")
519            ),
520        );
521    }
522
523    let func = parse_macro_input!(item as ItemFn);
524    if func.sig.asyncness.is_none() {
525        return compile_error_spanned(
526            func.sig.fn_token,
527            "reactor_handler requires an `async fn` — a handler resolves to a ReactorDecision",
528        );
529    }
530
531    let name = &func.sig.ident;
532    let vis = &func.vis;
533    let doc = format!("Marker type binding [`{name}`] to `{event}` (CONTRACT.md §22.14).");
534
535    quote! {
536        #func
537
538        #[doc = #doc]
539        #[allow(non_camel_case_types)]
540        #vis struct #name {}
541
542        impl ::axiam_sdk::amqp::reactor::ReactorHandlerFn for #name {
543            const EVENT: &'static str = #event;
544
545            fn call(
546                event: ::axiam_sdk::amqp::reactor::ReactorEvent,
547            ) -> ::axiam_sdk::amqp::reactor::BoxedReactorFuture {
548                ::std::boxed::Box::pin(#name(event))
549            }
550        }
551    }
552    .into()
553}