Skip to main content

ch_auth_macros/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4
5use proc_macro::TokenStream;
6
7use proc_macro_crate::{FoundCrate, crate_name};
8use quote::quote;
9use syn::parse::Parser;
10use syn::punctuated::Punctuated;
11use syn::spanned::Spanned;
12use syn::{Expr, FnArg, Ident, ItemFn, Meta, Pat, Path, ReturnType, Token, Type};
13
14/// Protects an asynchronous Axum handler with an account role check.
15///
16/// See the [crate documentation](crate) for role syntax, arguments, the
17/// session binding convention, and return contracts.
18#[proc_macro_attribute]
19pub fn auth(args: TokenStream, input: TokenStream) -> TokenStream {
20    auth_inner(args, input).unwrap_or_else(|error| error.into_compile_error().into())
21}
22
23#[derive(Clone, Copy)]
24enum FailureMode {
25    Result,
26    Response,
27    IntoResponse,
28}
29
30impl FailureMode {
31    fn parse(expr: Expr) -> syn::Result<Self> {
32        let ident = expr_ident(expr, "failure")?;
33        match ident.to_string().as_str() {
34            "result" => Ok(Self::Result),
35            "response" => Ok(Self::Response),
36            "into_response" => Ok(Self::IntoResponse),
37            _ => Err(syn::Error::new(
38                ident.span(),
39                "failure must be result, response, or into_response",
40            )),
41        }
42    }
43
44    fn infer(function: &ItemFn) -> syn::Result<Self> {
45        let ReturnType::Type(_, ty) = &function.sig.output else {
46            return Err(syn::Error::new(
47                function.sig.span(),
48                "#[auth] handlers must return Response, Result, or impl IntoResponse",
49            ));
50        };
51
52        if matches!(ty.as_ref(), Type::ImplTrait(_)) {
53            return Ok(Self::IntoResponse);
54        }
55        if is_result_type(ty) {
56            return Ok(Self::Result);
57        }
58        if matches!(ty.as_ref(), Type::Tuple(tuple) if tuple.elems.is_empty()) {
59            return Err(syn::Error::new(
60                ty.span(),
61                "#[auth] handlers must return Response, Result, or impl IntoResponse",
62            ));
63        }
64
65        Ok(Self::Response)
66    }
67}
68
69struct AuthArgs {
70    role: Expr,
71    session_ident: Option<Ident>,
72    failure_mode: Option<FailureMode>,
73}
74
75impl AuthArgs {
76    fn parse(args: Punctuated<Meta, Token![,]>) -> syn::Result<Self> {
77        let mut role = None;
78        let mut session_ident = None;
79        let mut failure_mode = None;
80
81        for meta in args {
82            match meta {
83                Meta::Path(path) => {
84                    if role.is_some() {
85                        return Err(syn::Error::new(
86                            path.span(),
87                            "auth role specified multiple times",
88                        ));
89                    }
90                    role = Some(role_expression(path)?);
91                }
92                Meta::NameValue(name_value) if name_value.path.is_ident("session") => {
93                    if session_ident.is_some() {
94                        return Err(syn::Error::new(
95                            name_value.path.span(),
96                            "session specified multiple times",
97                        ));
98                    }
99                    session_ident = Some(expr_ident(name_value.value, "session")?);
100                }
101                Meta::NameValue(name_value) if name_value.path.is_ident("failure") => {
102                    if failure_mode.is_some() {
103                        return Err(syn::Error::new(
104                            name_value.path.span(),
105                            "failure specified multiple times",
106                        ));
107                    }
108                    failure_mode = Some(FailureMode::parse(name_value.value)?);
109                }
110                Meta::NameValue(name_value) => {
111                    return Err(syn::Error::new(
112                        name_value.path.span(),
113                        "unknown auth argument; expected session or failure",
114                    ));
115                }
116                Meta::List(list) => {
117                    return Err(syn::Error::new(list.span(), "unsupported auth argument"));
118                }
119            }
120        }
121
122        Ok(Self {
123            role: role.ok_or_else(|| {
124                syn::Error::new(proc_macro2::Span::call_site(), "missing auth role")
125            })?,
126            session_ident,
127            failure_mode,
128        })
129    }
130}
131
132fn auth_inner(args: TokenStream, input: TokenStream) -> syn::Result<TokenStream> {
133    let parser = Punctuated::<Meta, Token![,]>::parse_terminated;
134    let args = AuthArgs::parse(Parser::parse(parser, args)?)?;
135    let mut function: ItemFn = syn::parse(input)?;
136
137    if function.sig.asyncness.is_none() {
138        return Err(syn::Error::new(
139            function.sig.fn_token.span(),
140            "#[auth] handlers must be async",
141        ));
142    }
143
144    let session_ident = resolve_session_ident(&function, args.session_ident)?;
145    let current_user_ident = Ident::new("current_user", function.sig.ident.span());
146    if session_ident == current_user_ident {
147        return Err(syn::Error::new(
148            session_ident.span(),
149            "the auth session and generated current_user binding must use different names",
150        ));
151    }
152    reject_current_user_argument(&function, &current_user_ident)?;
153
154    let failure_mode = match args.failure_mode {
155        Some(mode) => mode,
156        None => FailureMode::infer(&function)?,
157    };
158    let account_session = account_session_path()?;
159    let original_block = *function.block;
160    let expansion = AuthorizationExpansion {
161        session: &session_ident,
162        current_user: &current_user_ident,
163        account_session: &account_session,
164        role: &args.role,
165        original: &original_block,
166    };
167
168    function.block = match failure_mode {
169        FailureMode::Result => syn::parse2(expansion.result_body())?,
170        FailureMode::Response => {
171            let axum = dependency_path("axum")?;
172            syn::parse2(expansion.response_body(&axum))?
173        }
174        FailureMode::IntoResponse => {
175            let axum = dependency_path("axum")?;
176            syn::parse2(expansion.opaque_response_body(&axum))?
177        }
178    };
179
180    Ok(quote!(#function).into())
181}
182
183struct AuthorizationExpansion<'a> {
184    session: &'a Ident,
185    current_user: &'a Ident,
186    account_session: &'a Path,
187    role: &'a Expr,
188    original: &'a syn::Block,
189}
190
191impl AuthorizationExpansion<'_> {
192    fn result_body(&self) -> proc_macro2::TokenStream {
193        let authorization = self.authorization_binding(quote! {
194            return ::core::result::Result::Err(::core::convert::Into::into(error));
195        });
196        let original = self.original;
197        quote!({
198            #authorization
199            #original
200        })
201    }
202
203    fn response_body(&self, axum: &Path) -> proc_macro2::TokenStream {
204        let authorization = self.authorization_binding(quote! {
205            return #axum::response::IntoResponse::into_response(error);
206        });
207        let original = self.original;
208        quote!({
209            #authorization
210            #original
211        })
212    }
213
214    fn opaque_response_body(&self, axum: &Path) -> proc_macro2::TokenStream {
215        let authorization = self.authorization_binding(quote! {
216            return #axum::response::IntoResponse::into_response(error);
217        });
218        let original = self.original;
219        quote!({
220            #authorization
221            #axum::response::IntoResponse::into_response((async move #original).await)
222        })
223    }
224
225    fn authorization_binding(
226        &self,
227        on_error: proc_macro2::TokenStream,
228    ) -> proc_macro2::TokenStream {
229        let Self {
230            session,
231            current_user,
232            account_session,
233            role,
234            ..
235        } = self;
236
237        quote! {
238            let #current_user = match #account_session::authorize(&#session, #role) {
239                ::core::result::Result::Ok(user) => ::core::clone::Clone::clone(user),
240                ::core::result::Result::Err(error) => {
241                    #on_error
242                }
243            };
244            let _ = &#current_user;
245        }
246    }
247}
248
249fn account_session_path() -> syn::Result<Path> {
250    let ch_auth = dependency_path("ch-auth")?;
251    syn::parse2(quote!(#ch_auth::authorization::AccountSession))
252}
253
254fn role_expression(path: Path) -> syn::Result<Expr> {
255    let Some(role) = path.get_ident() else {
256        return syn::parse2(quote!(#path));
257    };
258    let role_name = role.to_string();
259    let parts = role_name.split('_').collect::<Vec<_>>();
260    if parts.iter().any(|part| part.is_empty())
261        || !role_name
262            .bytes()
263            .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_')
264    {
265        return Err(syn::Error::new(
266            role.span(),
267            "short auth roles must use SCREAMING_SNAKE_CASE; use a qualified role path otherwise",
268        ));
269    }
270
271    let variant = parts
272        .into_iter()
273        .map(|part| {
274            let mut bytes = part.bytes();
275            let first = bytes.next().expect("validated role segment");
276            let mut segment = String::with_capacity(part.len());
277            segment.push(char::from(first));
278            segment.extend(bytes.map(|byte| char::from(byte.to_ascii_lowercase())));
279            segment
280        })
281        .collect::<String>();
282    let variant = Ident::new(&variant, role.span());
283    syn::parse2(quote!(crate::AuthRole::#variant))
284}
285
286fn dependency_path(package: &str) -> syn::Result<Path> {
287    match crate_name(package) {
288        Ok(FoundCrate::Itself) => Ok(syn::parse_quote!(crate)),
289        Ok(FoundCrate::Name(name)) => {
290            let ident = Ident::new(&name.replace('-', "_"), proc_macro2::Span::call_site());
291            Ok(syn::parse_quote!(::#ident))
292        }
293        Err(error) => Err(syn::Error::new(
294            proc_macro2::Span::call_site(),
295            format!("#[auth] requires a direct `{package}` dependency: {error}"),
296        )),
297    }
298}
299
300fn resolve_session_ident(function: &ItemFn, explicit: Option<Ident>) -> syn::Result<Ident> {
301    if let Some(session) = explicit {
302        if function
303            .sig
304            .inputs
305            .iter()
306            .any(|input| argument_ident(input) == Some(&session))
307        {
308            return Ok(session);
309        }
310        return Err(syn::Error::new(
311            session.span(),
312            format!("session binding `{session}` is not a plain handler argument"),
313        ));
314    }
315
316    let candidates = function
317        .sig
318        .inputs
319        .iter()
320        .filter_map(argument_ident)
321        .filter(|ident| *ident == "auth_session" || *ident == "auth")
322        .cloned()
323        .collect::<Vec<_>>();
324
325    match candidates.as_slice() {
326        [session] => Ok(session.clone()),
327        [] => Err(syn::Error::new(
328            function.sig.inputs.span(),
329            "missing auth session binding; name it `auth_session` or pass `session = ...`",
330        )),
331        [_, _, ..] => Err(syn::Error::new(
332            function.sig.inputs.span(),
333            "ambiguous auth session binding; pass `session = ...`",
334        )),
335    }
336}
337
338fn reject_current_user_argument(function: &ItemFn, generated: &Ident) -> syn::Result<()> {
339    if let Some(input) = function
340        .sig
341        .inputs
342        .iter()
343        .find(|input| argument_ident(input) == Some(generated))
344    {
345        return Err(syn::Error::new(
346            input.span(),
347            "remove the `current_user` argument; #[auth] creates that local binding after authorization",
348        ));
349    }
350    Ok(())
351}
352
353fn argument_ident(input: &FnArg) -> Option<&Ident> {
354    let FnArg::Typed(pat_type) = input else {
355        return None;
356    };
357    let Pat::Ident(pat_ident) = pat_type.pat.as_ref() else {
358        return None;
359    };
360    Some(&pat_ident.ident)
361}
362
363fn is_result_type(ty: &Type) -> bool {
364    let Type::Path(type_path) = ty else {
365        return false;
366    };
367    type_path
368        .path
369        .segments
370        .last()
371        .is_some_and(|segment| segment.ident == "Result")
372}
373
374fn expr_ident(expr: Expr, field: &str) -> syn::Result<Ident> {
375    let Expr::Path(expr_path) = expr else {
376        return Err(syn::Error::new(
377            expr.span(),
378            format!("{field} must be an identifier"),
379        ));
380    };
381    expr_path
382        .path
383        .get_ident()
384        .cloned()
385        .ok_or_else(|| syn::Error::new(expr_path.span(), format!("{field} must be an identifier")))
386}