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
#![warn(
    clippy::all,
    // clippy::restriction,
    clippy::pedantic,
    clippy::nursery,
    // clippy::cargo
)]
#![recursion_limit = "256"]
extern crate proc_macro;
extern crate syn;
#[macro_use]
extern crate quote;
#[macro_use]
extern crate darling;
use darling::ast;
use darling::FromDeriveInput;
use proc_macro2::TokenStream;
use quote::ToTokens;
use syn::DeriveInput;
#[derive(Debug, FromDeriveInput)]
// This line says that we want to process all attributes declared with `my_trait`,
// and that darling should panic if this receiver is given an enum.
#[darling(attributes(authorized))]
struct AuthorizedOpts {
    /// The struct ident.
    ident: syn::Ident,

    /// The type's generics. You'll need these any time your trait is expected
    /// to work with types that declare generics.
    generics: syn::Generics,

    /// Receives the body of the struct or enum. We don't care about
    /// struct fields because we previously told darling we only accept structs.
    data: ast::Data<(), AuthorizedField>,

    /// The Input Receiver demands a volume, so use `Volume::Normal` if the
    /// caller doesn't provide one.
    // #[darling(default)]
    scope: String,
}

#[derive(Debug, FromField)]
#[darling(attributes(authorized))]
struct AuthorizedField {
    /// Get the ident of the field. For fields in tuple or newtype structs or
    /// enum bodies, this can be `None`.
    ident: Option<syn::Ident>,

    /// This magic field name pulls the type from the input.
    ty: syn::Type,

    attrs: Vec<syn::Attribute>,
    /// We declare this as an `Option` so that during tokenization we can write
    /// `field.volume.unwrap_or(derive_input.volume)` to facilitate field-level
    /// overrides of struct-level settings.
    #[darling(default)]
    scope: Option<String>,

    #[darling(default)]
    default: Option<String>,
}

impl ToTokens for AuthorizedOpts {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let struct_name = &self.ident;

        let fields = self
            .data
            .as_ref()
            .take_struct()
            .expect("Should never be enum")
            .fields;

        let authorized_trait = generate_authorized_trait(struct_name, &fields);
        let authorizable_trait = generate_authorizable_trait(struct_name, &self.scope, &fields);

        tokens.extend(quote! {
            #authorized_trait
            #authorizable_trait
        })
    }
}

fn generate_authorized_trait(
    struct_name: &syn::Ident,
    fields: &[&AuthorizedField],
) -> proc_macro2::TokenStream {
    let serialize_fields = fields
        .iter()
        .enumerate()
        .map(|(_i, f)| {
            let ident = if let Some(ref ident) = f.ident {
                ident.clone()
            } else {
                panic!("");
            };

            let unauthorized = match &f.default {
                None => quote! { Default::default() },
                Some(def) => match syn::parse_str::<syn::Path>(def) {
                    Ok(path) => quote! { #path() },
                    _ => panic!("Cannot parse default path"),
                },
            };

            let name = format!("{}", ident);
            let var_name = syn::Ident::new(&format!("arg_{}", name), ident.span());

            quote! {
                let #var_name = if !unauthorized_fields.contains(&#name) {
                    self.#ident.clone()
                } else {
                    #unauthorized
                };
            }
        })
        .collect::<Vec<_>>();

    let assign_field = fields
        .iter()
        .enumerate()
        .map(|(_i, f)| {
            let ident = if let Some(ref ident) = f.ident {
                ident.clone()
            } else {
                panic!("");
            };

            let name = format!("{}", ident);
            let var_name = syn::Ident::new(&format!("arg_{}", name), ident.span());

            quote! {
                #ident: #var_name
            }
        })
        .collect::<Vec<_>>();

    quote! {
        impl authorized::Authorized for #struct_name {
            type Source = #struct_name;

            fn build_serialize_struct<E>(&self,unauthorized_fields: &[&str]) -> Result<Self, E>
            {
                #(#serialize_fields)*

                Ok(Self {
                    #(#assign_field,)*
                })
            }
        }
    }
}

fn generate_authorizable_trait(
    struct_name: &syn::Ident,
    global_scope: &str,
    fields: &[&AuthorizedField],
) -> proc_macro2::TokenStream {
    let filtering_fields = fields
        .iter()
        .enumerate()
        .map(|(_i, f)| {
            let ident = if let Some(ref ident) = f.ident {
                ident.clone()
            } else {
                panic!("");
            };

            let name = format!("{}", ident);
            if let Some(ref scope) = f.scope {
                quote! {
                    if !#scope.parse::<authorized::scope::Scope>().unwrap().allow_access(scope) {
                        unauthorized_fields.push(#name);
                    }
                }
            } else {
                quote! {}
            }
        })
        .collect::<Vec<_>>();

    quote! {
        impl Authorizable for #struct_name {
            type Authorized = #struct_name;

            fn filter_unauthorized_fields<'a>(&'a self, scope: &authorized::scope::Scope) -> UnAuthorizedFields<'a>
            {
                let mut unauthorized_fields = vec![];

                #(
                    #filtering_fields
                )*

                    unauthorized_fields
            }

            fn authorize<'a>(&'a self, input_scope: &authorized::scope::Scope) -> Result<AuthorizedResult<'a, Self::Authorized>, AuthorizedError> {
                let global_scopes = vec!(#global_scope.parse::<Scope>()?);
                let unauthorized_fields = self.filter_unauthorized_fields(input_scope);

                let status = if global_scopes.iter().map(|scope| scope.allow_access(&input_scope)).any(|access| access) {
                    AuthorizationStatus::Authorized
                } else {
                    AuthorizationStatus::UnAuthorized
                };
                let inner = self.build_serialize_struct::<AuthorizedError>(&unauthorized_fields)?;
                Ok(AuthorizedResult {
                    input_scope: input_scope.clone(),
                    inner,
                    status,
                    unauthorized_fields
                })
            }
        }

    }
}

#[proc_macro_derive(Authorized, attributes(authorized))]
pub fn derive_authorized(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input: DeriveInput = syn::parse(input).unwrap();
    let res = AuthorizedOpts::from_derive_input(&input).unwrap();

    proc_macro::TokenStream::from(quote!(#res))
}