a3s-boot-macros 0.1.2

Attribute macros for a3s-boot
Documentation
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
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::{bracketed, Attribute, Ident, LitStr, Result, Token};

#[derive(Clone, Default)]
pub(crate) struct ApiSecurityArgs {
    name: Option<LitStr>,
    scopes: Vec<LitStr>,
}

impl ApiSecurityArgs {
    pub(crate) fn tokens(&self) -> proc_macro2::TokenStream {
        let name = self.name.as_ref().expect("checked during parsing");
        let scopes = self
            .scopes
            .iter()
            .map(|scope| quote!(#scope.to_string()))
            .collect::<Vec<_>>();

        quote!(with_api_security(#name, vec![#(#scopes),*]))
    }
}

impl Parse for ApiSecurityArgs {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let mut args = Self::default();

        if input.peek(LitStr) {
            args.name = Some(input.parse::<LitStr>()?);
            crate::parse_optional_comma(input)?;
        }

        while !input.is_empty() {
            let ident = input.parse::<Ident>()?;
            input.parse::<Token![=]>()?;

            if ident == "name" || ident == "scheme" {
                crate::set_once(&mut args.name, input.parse::<LitStr>()?, ident)?;
            } else if ident == "scopes" {
                if !args.scopes.is_empty() {
                    return Err(syn::Error::new_spanned(ident, "duplicate `scopes` option"));
                }
                args.scopes = parse_string_array(input)?;
            } else {
                return Err(syn::Error::new_spanned(
                    ident,
                    "expected `name`, `scheme`, or `scopes`",
                ));
            }

            crate::parse_optional_comma(input)?;
        }

        if args.name.is_none() {
            return Err(input.error("missing required security scheme name"));
        }

        Ok(args)
    }
}

#[derive(Clone, Default)]
pub(crate) struct BearerAuthArgs {
    name: Option<LitStr>,
}

impl BearerAuthArgs {
    pub(crate) fn tokens(&self) -> proc_macro2::TokenStream {
        match &self.name {
            Some(name) => quote!(with_bearer_auth_named(#name)),
            None => quote!(with_bearer_auth()),
        }
    }
}

impl Parse for BearerAuthArgs {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let mut args = Self::default();

        if input.peek(LitStr) {
            args.name = Some(input.parse::<LitStr>()?);
            crate::parse_optional_comma(input)?;
        }

        while !input.is_empty() {
            let ident = input.parse::<Ident>()?;
            input.parse::<Token![=]>()?;

            if ident == "name" || ident == "scheme" {
                crate::set_once(&mut args.name, input.parse::<LitStr>()?, ident)?;
            } else {
                return Err(syn::Error::new_spanned(
                    ident,
                    "expected `name` or `scheme`",
                ));
            }

            crate::parse_optional_comma(input)?;
        }

        Ok(args)
    }
}

#[derive(Clone, Default)]
pub(crate) struct ApiCookieAuthArgs {
    name: Option<LitStr>,
    scheme: Option<LitStr>,
    description: Option<LitStr>,
}

impl ApiCookieAuthArgs {
    pub(crate) fn tokens(&self) -> Result<proc_macro2::TokenStream> {
        let name = self
            .name
            .clone()
            .unwrap_or_else(|| LitStr::new("sid", proc_macro2::Span::call_site()));
        let scheme = self
            .scheme
            .clone()
            .unwrap_or_else(|| LitStr::new("cookieAuth", proc_macro2::Span::call_site()));
        Ok(api_key_auth_tokens(
            &scheme,
            quote!(::a3s_boot::OpenApiApiKeyLocation::Cookie),
            &name,
            self.description.as_ref(),
        ))
    }
}

impl Parse for ApiCookieAuthArgs {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let mut args = Self::default();

        if input.peek(LitStr) {
            args.name = Some(input.parse::<LitStr>()?);
            crate::parse_optional_comma(input)?;
        }

        while !input.is_empty() {
            let ident = input.parse::<Ident>()?;
            input.parse::<Token![=]>()?;

            if ident == "name" || ident == "cookie" {
                crate::set_once(&mut args.name, input.parse::<LitStr>()?, ident)?;
            } else if ident == "scheme" {
                crate::set_once(&mut args.scheme, input.parse::<LitStr>()?, ident)?;
            } else if ident == "description" {
                crate::set_once(&mut args.description, input.parse::<LitStr>()?, ident)?;
            } else {
                return Err(syn::Error::new_spanned(
                    ident,
                    "expected `name`, `cookie`, `scheme`, or `description`",
                ));
            }

            crate::parse_optional_comma(input)?;
        }

        Ok(args)
    }
}

#[derive(Clone, Default)]
pub(crate) struct ApiKeyAuthArgs {
    name: Option<LitStr>,
    scheme: Option<LitStr>,
    location: Option<LitStr>,
    description: Option<LitStr>,
}

impl ApiKeyAuthArgs {
    pub(crate) fn tokens(&self) -> Result<proc_macro2::TokenStream> {
        let name = self
            .name
            .clone()
            .unwrap_or_else(|| LitStr::new("x-api-key", proc_macro2::Span::call_site()));
        let scheme = self
            .scheme
            .clone()
            .unwrap_or_else(|| LitStr::new("apiKeyAuth", proc_macro2::Span::call_site()));
        let location = match self.location.as_ref().map(LitStr::value).as_deref() {
            None | Some("header") => quote!(::a3s_boot::OpenApiApiKeyLocation::Header),
            Some("query") => quote!(::a3s_boot::OpenApiApiKeyLocation::Query),
            Some("cookie") => quote!(::a3s_boot::OpenApiApiKeyLocation::Cookie),
            Some(_) => {
                return Err(syn::Error::new_spanned(
                    self.location.as_ref().expect("checked above"),
                    "expected `header`, `query`, or `cookie`",
                ));
            }
        };

        Ok(api_key_auth_tokens(
            &scheme,
            location,
            &name,
            self.description.as_ref(),
        ))
    }
}

impl Parse for ApiKeyAuthArgs {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let mut args = Self::default();

        if input.peek(LitStr) {
            args.name = Some(input.parse::<LitStr>()?);
            crate::parse_optional_comma(input)?;
        }

        while !input.is_empty() {
            let ident = input.parse::<Ident>()?;
            input.parse::<Token![=]>()?;

            if ident == "name" || ident == "key" {
                crate::set_once(&mut args.name, input.parse::<LitStr>()?, ident)?;
            } else if ident == "scheme" {
                crate::set_once(&mut args.scheme, input.parse::<LitStr>()?, ident)?;
            } else if ident == "location" || ident == "in" {
                crate::set_once(&mut args.location, input.parse::<LitStr>()?, ident)?;
            } else if ident == "description" {
                crate::set_once(&mut args.description, input.parse::<LitStr>()?, ident)?;
            } else {
                return Err(syn::Error::new_spanned(
                    ident,
                    "expected `name`, `key`, `scheme`, `location`, `in`, or `description`",
                ));
            }

            crate::parse_optional_comma(input)?;
        }

        Ok(args)
    }
}

#[derive(Clone)]
pub(crate) struct OAuth2AuthArgs {
    scheme: LitStr,
    flow: OAuth2FlowKind,
    authorization_url: Option<LitStr>,
    token_url: Option<LitStr>,
    refresh_url: Option<LitStr>,
    scopes: Vec<LitStr>,
    description: Option<LitStr>,
}

impl OAuth2AuthArgs {
    pub(crate) fn tokens(&self) -> Result<proc_macro2::TokenStream> {
        let scheme = &self.scheme;
        let scopes = self
            .scopes
            .iter()
            .map(|scope| quote!(#scope.to_string()))
            .collect::<Vec<_>>();
        let flow_scopes = self
            .scopes
            .iter()
            .map(|scope| quote!((#scope, "")))
            .collect::<Vec<_>>();
        let flow = self.flow.tokens(
            self.authorization_url.as_ref(),
            self.token_url.as_ref(),
            self.refresh_url.as_ref(),
            &flow_scopes,
        )?;
        let mut security_scheme = quote!(::a3s_boot::OpenApiSecurityScheme::oauth2(#flow));

        if let Some(description) = &self.description {
            security_scheme = quote!((#security_scheme).with_description(#description));
        }

        Ok(quote! {
            with_security_scheme(#scheme, #security_scheme)
                .with_api_security(#scheme, vec![#(#scopes),*])
        })
    }
}

impl Parse for OAuth2AuthArgs {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let mut scheme = if input.peek(LitStr) {
            let scheme = Some(input.parse::<LitStr>()?);
            crate::parse_optional_comma(input)?;
            scheme
        } else {
            None
        };
        let mut flow = None;
        let mut authorization_url = None;
        let mut token_url = None;
        let mut refresh_url = None;
        let mut scopes = Vec::new();
        let mut description = None;

        while !input.is_empty() {
            let ident = input.parse::<Ident>()?;
            input.parse::<Token![=]>()?;

            if ident == "name" || ident == "scheme" {
                crate::set_once(&mut scheme, input.parse::<LitStr>()?, ident)?;
            } else if ident == "flow" {
                crate::set_once(&mut flow, OAuth2FlowKind::parse(input)?, ident)?;
            } else if ident == "authorization_url" || ident == "authorizationUrl" {
                crate::set_once(&mut authorization_url, input.parse::<LitStr>()?, ident)?;
            } else if ident == "token_url" || ident == "tokenUrl" {
                crate::set_once(&mut token_url, input.parse::<LitStr>()?, ident)?;
            } else if ident == "refresh_url" || ident == "refreshUrl" {
                crate::set_once(&mut refresh_url, input.parse::<LitStr>()?, ident)?;
            } else if ident == "scopes" {
                if !scopes.is_empty() {
                    return Err(syn::Error::new_spanned(ident, "duplicate `scopes` option"));
                }
                scopes = parse_string_array(input)?;
            } else if ident == "description" {
                crate::set_once(&mut description, input.parse::<LitStr>()?, ident)?;
            } else {
                return Err(syn::Error::new_spanned(
                    ident,
                    "expected `name`, `scheme`, `flow`, `authorization_url`, `token_url`, `refresh_url`, `scopes`, or `description`",
                ));
            }

            crate::parse_optional_comma(input)?;
        }

        let scheme =
            scheme.unwrap_or_else(|| LitStr::new("oauth2", proc_macro2::Span::call_site()));
        let flow = flow.unwrap_or(OAuth2FlowKind::AuthorizationCode);
        flow.validate(authorization_url.as_ref(), token_url.as_ref())?;

        Ok(Self {
            scheme,
            flow,
            authorization_url,
            token_url,
            refresh_url,
            scopes,
            description,
        })
    }
}

#[derive(Clone, Copy)]
enum OAuth2FlowKind {
    Implicit,
    Password,
    ClientCredentials,
    AuthorizationCode,
}

impl OAuth2FlowKind {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let value = input.parse::<LitStr>()?;
        match value.value().as_str() {
            "implicit" => Ok(Self::Implicit),
            "password" => Ok(Self::Password),
            "client_credentials" | "clientCredentials" => Ok(Self::ClientCredentials),
            "authorization_code" | "authorizationCode" => Ok(Self::AuthorizationCode),
            _ => Err(syn::Error::new_spanned(
                value,
                "expected `implicit`, `password`, `client_credentials`, or `authorization_code`",
            )),
        }
    }

    fn validate(
        self,
        authorization_url: Option<&LitStr>,
        token_url: Option<&LitStr>,
    ) -> Result<()> {
        match self {
            Self::Implicit if authorization_url.is_none() => Err(syn::Error::new(
                proc_macro2::Span::call_site(),
                "`implicit` OAuth2 flow requires `authorization_url`",
            )),
            Self::Password | Self::ClientCredentials if token_url.is_none() => {
                Err(syn::Error::new(
                    proc_macro2::Span::call_site(),
                    "this OAuth2 flow requires `token_url`",
                ))
            }
            Self::AuthorizationCode if authorization_url.is_none() || token_url.is_none() => {
                Err(syn::Error::new(
                    proc_macro2::Span::call_site(),
                    "`authorization_code` OAuth2 flow requires `authorization_url` and `token_url`",
                ))
            }
            _ => Ok(()),
        }
    }

    fn tokens(
        self,
        authorization_url: Option<&LitStr>,
        token_url: Option<&LitStr>,
        refresh_url: Option<&LitStr>,
        scopes: &[proc_macro2::TokenStream],
    ) -> Result<proc_macro2::TokenStream> {
        fn with_refresh_url(
            flow: proc_macro2::TokenStream,
            refresh_url: Option<&LitStr>,
        ) -> proc_macro2::TokenStream {
            match refresh_url {
                Some(refresh_url) => quote!((#flow).with_refresh_url(#refresh_url)),
                None => flow,
            }
        }

        Ok(match self {
            Self::Implicit => {
                let authorization_url = authorization_url.expect("validated during parsing");
                let flow = with_refresh_url(
                    quote! {
                        ::a3s_boot::OpenApiOAuthFlow::implicit(#authorization_url, [#(#scopes),*])
                    },
                    refresh_url,
                );
                quote! {
                    ::a3s_boot::OpenApiOAuthFlows::new().with_implicit(#flow)
                }
            }
            Self::Password => {
                let token_url = token_url.expect("validated during parsing");
                let flow = with_refresh_url(
                    quote! {
                        ::a3s_boot::OpenApiOAuthFlow::password(#token_url, [#(#scopes),*])
                    },
                    refresh_url,
                );
                quote! {
                    ::a3s_boot::OpenApiOAuthFlows::new().with_password(#flow)
                }
            }
            Self::ClientCredentials => {
                let token_url = token_url.expect("validated during parsing");
                let flow = with_refresh_url(
                    quote! {
                        ::a3s_boot::OpenApiOAuthFlow::client_credentials(#token_url, [#(#scopes),*])
                    },
                    refresh_url,
                );
                quote! {
                    ::a3s_boot::OpenApiOAuthFlows::new().with_client_credentials(#flow)
                }
            }
            Self::AuthorizationCode => {
                let authorization_url = authorization_url.expect("validated during parsing");
                let token_url = token_url.expect("validated during parsing");
                let flow = with_refresh_url(
                    quote! {
                        ::a3s_boot::OpenApiOAuthFlow::authorization_code(
                            #authorization_url,
                            #token_url,
                            [#(#scopes),*],
                        )
                    },
                    refresh_url,
                );
                quote! {
                    ::a3s_boot::OpenApiOAuthFlows::new().with_authorization_code(#flow)
                }
            }
        })
    }
}

#[derive(Clone)]
pub(crate) struct OpenIdConnectAuthArgs {
    scheme: LitStr,
    url: LitStr,
    scopes: Vec<LitStr>,
    description: Option<LitStr>,
}

impl OpenIdConnectAuthArgs {
    pub(crate) fn tokens(&self) -> proc_macro2::TokenStream {
        let scheme = &self.scheme;
        let url = &self.url;
        let scopes = self
            .scopes
            .iter()
            .map(|scope| quote!(#scope.to_string()))
            .collect::<Vec<_>>();
        let mut security_scheme = quote!(::a3s_boot::OpenApiSecurityScheme::open_id_connect(#url));

        if let Some(description) = &self.description {
            security_scheme = quote!((#security_scheme).with_description(#description));
        }

        quote! {
            with_security_scheme(#scheme, #security_scheme)
                .with_api_security(#scheme, vec![#(#scopes),*])
        }
    }
}

impl Parse for OpenIdConnectAuthArgs {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let mut scheme = if input.peek(LitStr) {
            let scheme = Some(input.parse::<LitStr>()?);
            crate::parse_optional_comma(input)?;
            scheme
        } else {
            None
        };
        let mut url = None;
        let mut scopes = Vec::new();
        let mut description = None;

        while !input.is_empty() {
            let ident = input.parse::<Ident>()?;
            input.parse::<Token![=]>()?;

            if ident == "name" || ident == "scheme" {
                crate::set_once(&mut scheme, input.parse::<LitStr>()?, ident)?;
            } else if ident == "url"
                || ident == "open_id_connect_url"
                || ident == "openIdConnectUrl"
            {
                crate::set_once(&mut url, input.parse::<LitStr>()?, ident)?;
            } else if ident == "scopes" {
                if !scopes.is_empty() {
                    return Err(syn::Error::new_spanned(ident, "duplicate `scopes` option"));
                }
                scopes = parse_string_array(input)?;
            } else if ident == "description" {
                crate::set_once(&mut description, input.parse::<LitStr>()?, ident)?;
            } else {
                return Err(syn::Error::new_spanned(
                    ident,
                    "expected `name`, `scheme`, `url`, `open_id_connect_url`, `scopes`, or `description`",
                ));
            }

            crate::parse_optional_comma(input)?;
        }

        let scheme =
            scheme.unwrap_or_else(|| LitStr::new("openId", proc_macro2::Span::call_site()));
        let Some(url) = url else {
            return Err(input.error("missing required `url` option"));
        };

        Ok(Self {
            scheme,
            url,
            scopes,
            description,
        })
    }
}

pub(crate) fn parse_args_or_default<T>(attr: &Attribute) -> Result<T>
where
    T: Parse + Default,
{
    if matches!(attr.meta, syn::Meta::Path(_)) {
        Ok(T::default())
    } else {
        attr.parse_args::<T>()
    }
}

fn parse_string_array(input: ParseStream<'_>) -> Result<Vec<LitStr>> {
    let content;
    bracketed!(content in input);

    let mut items = Vec::new();
    while !content.is_empty() {
        items.push(content.parse::<LitStr>()?);
        crate::parse_optional_comma(&content)?;
    }

    Ok(items)
}

fn api_key_auth_tokens(
    scheme: &LitStr,
    location: proc_macro2::TokenStream,
    name: &LitStr,
    description: Option<&LitStr>,
) -> proc_macro2::TokenStream {
    let mut security_scheme = quote! {
        ::a3s_boot::OpenApiSecurityScheme::api_key(#location, #name)
    };

    if let Some(description) = description {
        security_scheme = quote! {
            (#security_scheme).with_description(#description)
        };
    }

    quote! {
        with_security_scheme(#scheme, #security_scheme)
            .with_api_security(#scheme, ::std::vec::Vec::<::std::string::String>::new())
    }
}