1use proc_macro2::TokenStream;
5use quote::{ToTokens, quote};
6use syn::{FnArg, ImplItemFn, LitStr, Pat, ReturnType, Type, parse_quote};
7
8#[proc_macro_attribute]
22pub fn requiere_rol(
23 attr: proc_macro::TokenStream,
24 item: proc_macro::TokenStream,
25) -> proc_macro::TokenStream {
26 expand(attr.into(), item.into()).into()
27}
28
29fn expand(attr: TokenStream, item: TokenStream) -> TokenStream {
30 let mut handler: ImplItemFn = match syn::parse2(item.clone()) {
31 Ok(handler) => handler,
32 Err(err) => return err.to_compile_error(),
33 };
34 match role_check(attr, &handler) {
35 Ok(check) => {
36 let body = &handler.block;
37 handler.block = parse_quote!({ #check #body });
38 handler.into_token_stream()
39 }
40 Err(err) => {
43 let err = err.to_compile_error();
44 quote!(#err #handler)
45 }
46 }
47}
48
49fn role_check(attr: TokenStream, handler: &ImplItemFn) -> syn::Result<TokenStream> {
51 let role: LitStr = syn::parse2(attr).map_err(|err| {
52 syn::Error::new(
53 err.span(),
54 "#[requiere_rol] takes one role name: #[requiere_rol(\"admin\")]",
55 )
56 })?;
57 if !is_role_name(&role.value()) {
58 return Err(syn::Error::new_spanned(
59 &role,
60 "#[requiere_rol]: a role name is lowercase letters, digits, `_`, `:` or `-`, starting with a letter",
61 ));
62 }
63 let auth = bearer_auth_param(handler)?;
64 let ret = match &handler.sig.output {
65 ReturnType::Type(_, ty) => ty,
66 ReturnType::Default => {
67 return Err(syn::Error::new_spanned(
68 &handler.sig,
69 "#[requiere_rol] needs a handler returning a response enum with `from_status`",
70 ));
71 }
72 };
73 Ok(quote! {
74 if !#auth.0.tiene_rol(#role) {
75 let (status, error) = ::puerto_web::auth::prohibido();
76 return <#ret>::from_status(status, error);
77 }
78 })
79}
80
81fn bearer_auth_param(handler: &ImplItemFn) -> syn::Result<&syn::Ident> {
83 for input in &handler.sig.inputs {
84 let FnArg::Typed(param) = input else {
85 continue;
86 };
87 if !is_bearer_auth(¶m.ty) {
88 continue;
89 }
90 return match &*param.pat {
91 Pat::Ident(binding) => Ok(&binding.ident),
92 other => Err(syn::Error::new_spanned(
93 other,
94 "#[requiere_rol]: bind the `BearerAuth` parameter to a name: `auth: BearerAuth`",
95 )),
96 };
97 }
98 Err(syn::Error::new_spanned(
99 &handler.sig,
100 "#[requiere_rol] needs the handler to take `auth: BearerAuth`: a role is checked on an authenticated caller",
101 ))
102}
103
104fn is_bearer_auth(ty: &Type) -> bool {
105 match ty {
106 Type::Path(path) => path
107 .path
108 .segments
109 .last()
110 .is_some_and(|segment| segment.ident == "BearerAuth"),
111 _ => false,
112 }
113}
114
115fn is_role_name(role: &str) -> bool {
117 let mut chars = role.chars();
118 chars.next().is_some_and(|first| first.is_ascii_lowercase())
119 && chars
120 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | ':' | '-'))
121}
122
123#[cfg(test)]
124mod tests {
125 use super::*;
126
127 fn expanded(attr: TokenStream, item: TokenStream) -> String {
128 expand(attr, item).to_string()
129 }
130
131 #[test]
132 fn should_check_the_role_before_the_body_when_the_handler_takes_bearer_auth() {
133 let output = expanded(
135 quote!("admin"),
136 quote! {
137 async fn delete(&self, auth: BearerAuth) -> DeleteResponse {
138 DeleteResponse::NoContent
139 }
140 },
141 );
142
143 let expected = quote! {
145 async fn delete(&self, auth: BearerAuth) -> DeleteResponse {
146 if !auth.0.tiene_rol("admin") {
147 let (status, error) = ::puerto_web::auth::prohibido();
148 return <DeleteResponse>::from_status(status, error);
149 }
150 {
151 DeleteResponse::NoContent
152 }
153 }
154 };
155 assert_eq!(output, expected.to_string());
156 }
157
158 #[test]
159 fn should_find_bearer_auth_by_its_last_segment_when_the_path_is_qualified() {
160 let output = expanded(
162 quote!("admin"),
163 quote! {
164 async fn delete(&self, id: Path<Uuid>, caller: puerto_web::auth::BearerAuth) -> R { R::Ok }
165 },
166 );
167
168 assert!(output.contains("caller . 0 . tiene_rol"), "{output}");
170 assert!(!output.contains("compile_error"), "{output}");
171 }
172
173 #[test]
174 fn should_fail_naming_the_attribute_when_the_handler_takes_no_bearer_auth() {
175 let output = expanded(
177 quote!("admin"),
178 quote! { async fn delete(&self, id: Path<Uuid>) -> R { R::Ok } },
179 );
180
181 assert!(output.contains("compile_error"), "{output}");
183 assert!(
184 output.contains("needs the handler to take `auth: BearerAuth`"),
185 "{output}"
186 );
187 }
188
189 #[test]
190 fn should_still_emit_the_method_when_the_attribute_is_wrong() {
191 let output = expanded(
193 quote!("admin"),
194 quote! { async fn delete(&self) -> R { R::Ok } },
195 );
196
197 assert!(output.contains("async fn delete"), "{output}");
199 assert!(!output.contains("tiene_rol"), "{output}");
200 }
201
202 #[test]
203 fn should_fail_when_the_role_is_not_a_role_name() {
204 for attr in [
205 quote!("Admin"),
206 quote!(""),
207 quote!("1admin"),
208 quote!("ad min"),
209 ] {
210 let output = expanded(
212 attr.clone(),
213 quote! { async fn delete(&self, auth: BearerAuth) -> R { R::Ok } },
214 );
215
216 assert!(
218 output.contains("a role name is lowercase"),
219 "{attr}: {output}"
220 );
221 }
222 }
223
224 #[test]
225 fn should_fail_when_the_attribute_is_not_one_string() {
226 for attr in [quote!(), quote!(admin), quote!("admin", "editor")] {
227 let output = expanded(
229 attr.clone(),
230 quote! { async fn delete(&self, auth: BearerAuth) -> R { R::Ok } },
231 );
232
233 assert!(output.contains("takes one role name"), "{attr}: {output}");
235 }
236 }
237
238 #[test]
239 fn should_fail_when_bearer_auth_is_destructured() {
240 let output = expanded(
242 quote!("admin"),
243 quote! { async fn delete(&self, BearerAuth(p): BearerAuth) -> R { R::Ok } },
244 );
245
246 assert!(
248 output.contains("bind the `BearerAuth` parameter to a name"),
249 "{output}"
250 );
251 }
252
253 #[test]
254 fn should_fail_when_the_handler_returns_nothing() {
255 let output = expanded(
257 quote!("admin"),
258 quote! { async fn delete(&self, auth: BearerAuth) {} },
259 );
260
261 assert!(output.contains("needs a handler returning"), "{output}");
263 }
264
265 #[test]
266 fn should_accept_role_names_with_digits_and_separators() {
267 for role in ["admin", "a", "billing:read", "team-lead", "level_2"] {
268 assert!(is_role_name(role), "{role}");
269 }
270 }
271}