clawspec-core 0.4.4

Core library for generating OpenAPI specifications from tests
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
//! OpenAPI Security Scheme support for clawspec.
//!
//! This module provides types for defining and configuring OpenAPI security schemes
//! that are included in the generated specification. Security schemes describe
//! the authentication methods available for your API.
//!
//! # Overview
//!
//! Security in OpenAPI consists of two parts:
//! 1. **Security Schemes**: Definitions of authentication methods (Bearer, Basic, API Key, etc.)
//! 2. **Security Requirements**: References to schemes that must be satisfied for an operation
//!
//! # Example
//!
//! ```rust
//! use clawspec_core::{ApiClient, SecurityScheme, SecurityRequirement, ApiKeyLocation};
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let client = ApiClient::builder()
//!     .with_security_scheme("bearerAuth", SecurityScheme::bearer())
//!     .with_security_scheme("apiKey", SecurityScheme::api_key("X-API-Key", ApiKeyLocation::Header))
//!     .with_default_security(SecurityRequirement::new("bearerAuth"))
//!     .build()?;
//! # Ok(())
//! # }
//! ```
//!
//! # Generated OpenAPI
//!
//! The security schemes are output in the `components.securitySchemes` section:
//!
//! ```yaml
//! components:
//!   securitySchemes:
//!     bearerAuth:
//!       type: http
//!       scheme: bearer
//!     apiKey:
//!       type: apiKey
//!       name: X-API-Key
//!       in: header
//! security:
//!   - bearerAuth: []
//! ```

use indexmap::IndexMap;
use utoipa::openapi::security::{
    ApiKey as UtoipaApiKey, ApiKeyValue, AuthorizationCode, ClientCredentials, Flow, Http,
    HttpAuthScheme, Implicit, OAuth2 as UtoipaOAuth2, OpenIdConnect as UtoipaOpenIdConnect,
    Password, Scopes, SecurityScheme as UtoipaSecurityScheme,
};

/// OpenAPI security scheme configuration.
///
/// This enum represents the different types of security schemes supported by OpenAPI.
/// Each variant maps directly to an OpenAPI security scheme type.
///
/// # Supported Schemes
///
/// - **Bearer**: HTTP Bearer token authentication (RFC 6750)
/// - **Basic**: HTTP Basic authentication (RFC 7617)
/// - **ApiKey**: API key passed in header, query, or cookie
/// - **OAuth2**: OAuth 2.0 authentication flows
/// - **OpenIdConnect**: OpenID Connect Discovery
///
/// # Example
///
/// ```rust
/// use clawspec_core::{SecurityScheme, ApiKeyLocation};
///
/// // Simple bearer token
/// let bearer = SecurityScheme::bearer();
///
/// // Bearer with JWT format hint
/// let jwt = SecurityScheme::bearer_with_format("JWT");
///
/// // API key in header
/// let api_key = SecurityScheme::api_key("X-API-Key", ApiKeyLocation::Header);
///
/// // Basic auth
/// let basic = SecurityScheme::basic();
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum SecurityScheme {
    /// HTTP Bearer authentication (RFC 6750).
    ///
    /// Used for token-based authentication where the client sends
    /// an `Authorization: Bearer <token>` header.
    Bearer {
        /// Optional format hint (e.g., "JWT" for JSON Web Tokens)
        format: Option<String>,
        /// Description for documentation
        description: Option<String>,
    },

    /// HTTP Basic authentication (RFC 7617).
    ///
    /// Uses `Authorization: Basic <base64(username:password)>` header.
    Basic {
        /// Description for documentation
        description: Option<String>,
    },

    /// API Key authentication.
    ///
    /// The API key can be passed in a header, query parameter, or cookie.
    ApiKey {
        /// Name of the header, query parameter, or cookie
        name: String,
        /// Where the API key is passed
        location: ApiKeyLocation,
        /// Description for documentation
        description: Option<String>,
    },

    /// OAuth 2.0 authentication.
    ///
    /// Supports multiple OAuth2 flows: authorization code, client credentials,
    /// implicit, and password.
    OAuth2 {
        /// OAuth2 flows configuration (boxed to reduce enum size)
        flows: Box<OAuth2Flows>,
        /// Description for documentation
        description: Option<String>,
    },

    /// OpenID Connect Discovery.
    ///
    /// Uses OpenID Connect for authentication with automatic discovery
    /// of the provider's configuration.
    OpenIdConnect {
        /// OpenID Connect discovery URL
        open_id_connect_url: String,
        /// Description for documentation
        description: Option<String>,
    },
}

impl SecurityScheme {
    /// Creates a simple HTTP Bearer authentication scheme.
    ///
    /// # Example
    ///
    /// ```rust
    /// use clawspec_core::SecurityScheme;
    ///
    /// let scheme = SecurityScheme::bearer();
    /// ```
    pub fn bearer() -> Self {
        Self::Bearer {
            format: None,
            description: None,
        }
    }

    /// Creates an HTTP Bearer authentication scheme with a format hint.
    ///
    /// # Arguments
    ///
    /// * `format` - Format hint (e.g., "JWT" for JSON Web Tokens)
    ///
    /// # Example
    ///
    /// ```rust
    /// use clawspec_core::SecurityScheme;
    ///
    /// let scheme = SecurityScheme::bearer_with_format("JWT");
    /// ```
    pub fn bearer_with_format(format: impl Into<String>) -> Self {
        Self::Bearer {
            format: Some(format.into()),
            description: None,
        }
    }

    /// Creates an HTTP Basic authentication scheme.
    ///
    /// # Example
    ///
    /// ```rust
    /// use clawspec_core::SecurityScheme;
    ///
    /// let scheme = SecurityScheme::basic();
    /// ```
    pub fn basic() -> Self {
        Self::Basic { description: None }
    }

    /// Creates an API Key authentication scheme.
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the header, query parameter, or cookie
    /// * `location` - Where the API key is passed
    ///
    /// # Example
    ///
    /// ```rust
    /// use clawspec_core::{SecurityScheme, ApiKeyLocation};
    ///
    /// let scheme = SecurityScheme::api_key("X-API-Key", ApiKeyLocation::Header);
    /// ```
    pub fn api_key(name: impl Into<String>, location: ApiKeyLocation) -> Self {
        Self::ApiKey {
            name: name.into(),
            location,
            description: None,
        }
    }

    /// Creates an OpenID Connect authentication scheme.
    ///
    /// # Arguments
    ///
    /// * `url` - OpenID Connect discovery URL
    ///
    /// # Example
    ///
    /// ```rust
    /// use clawspec_core::SecurityScheme;
    ///
    /// let scheme = SecurityScheme::openid_connect("https://auth.example.com/.well-known/openid-configuration");
    /// ```
    pub fn openid_connect(url: impl Into<String>) -> Self {
        Self::OpenIdConnect {
            open_id_connect_url: url.into(),
            description: None,
        }
    }

    /// Adds a description to the security scheme.
    ///
    /// # Example
    ///
    /// ```rust
    /// use clawspec_core::SecurityScheme;
    ///
    /// let scheme = SecurityScheme::bearer()
    ///     .with_description("JWT token obtained from /auth/login");
    /// ```
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        match &mut self {
            SecurityScheme::Bearer {
                description: desc, ..
            } => *desc = Some(description.into()),
            SecurityScheme::Basic { description: desc } => *desc = Some(description.into()),
            SecurityScheme::ApiKey {
                description: desc, ..
            } => *desc = Some(description.into()),
            SecurityScheme::OAuth2 {
                description: desc, ..
            } => *desc = Some(description.into()),
            SecurityScheme::OpenIdConnect {
                description: desc, ..
            } => *desc = Some(description.into()),
        }
        self
    }

    /// Converts this security scheme to a utoipa SecurityScheme.
    pub(crate) fn to_utoipa(&self) -> UtoipaSecurityScheme {
        match self {
            SecurityScheme::Bearer {
                format,
                description,
            } => {
                let mut http = Http::new(HttpAuthScheme::Bearer);
                if let Some(fmt) = format {
                    http.bearer_format = Some(fmt.clone());
                }
                if let Some(desc) = description {
                    http.description = Some(desc.clone());
                }
                UtoipaSecurityScheme::Http(http)
            }
            SecurityScheme::Basic { description } => {
                let mut http = Http::new(HttpAuthScheme::Basic);
                if let Some(desc) = description {
                    http.description = Some(desc.clone());
                }
                UtoipaSecurityScheme::Http(http)
            }
            SecurityScheme::ApiKey {
                name,
                location,
                description,
            } => {
                let api_key_value = if let Some(desc) = description {
                    ApiKeyValue::with_description(name, desc)
                } else {
                    ApiKeyValue::new(name)
                };
                let api_key = match location {
                    ApiKeyLocation::Header => UtoipaApiKey::Header(api_key_value),
                    ApiKeyLocation::Query => UtoipaApiKey::Query(api_key_value),
                    ApiKeyLocation::Cookie => UtoipaApiKey::Cookie(api_key_value),
                };
                UtoipaSecurityScheme::ApiKey(api_key)
            }
            SecurityScheme::OAuth2 { flows, description } => {
                let mut oauth2 = flows.to_utoipa();
                if let Some(desc) = description {
                    oauth2.description = Some(desc.clone());
                }
                UtoipaSecurityScheme::OAuth2(oauth2)
            }
            SecurityScheme::OpenIdConnect {
                open_id_connect_url,
                description,
            } => {
                let mut oidc = UtoipaOpenIdConnect::new(open_id_connect_url);
                if let Some(desc) = description {
                    oidc.description = Some(desc.clone());
                }
                UtoipaSecurityScheme::OpenIdConnect(oidc)
            }
        }
    }
}

/// Location where an API key is passed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ApiKeyLocation {
    /// API key in HTTP header
    Header,
    /// API key in query parameter
    Query,
    /// API key in cookie
    Cookie,
}

/// OAuth2 flow configurations.
///
/// Represents the different OAuth2 flows supported by OpenAPI.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct OAuth2Flows {
    /// Authorization Code flow
    pub authorization_code: Option<OAuth2Flow>,
    /// Client Credentials flow
    pub client_credentials: Option<OAuth2Flow>,
    /// Implicit flow (deprecated in OAuth 2.1)
    pub implicit: Option<OAuth2ImplicitFlow>,
    /// Password flow (deprecated in OAuth 2.1)
    pub password: Option<OAuth2Flow>,
}

impl OAuth2Flows {
    /// Creates a new OAuth2Flows with authorization code flow.
    pub fn authorization_code(
        authorization_url: impl Into<String>,
        token_url: impl Into<String>,
        scopes: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        Self {
            authorization_code: Some(OAuth2Flow {
                authorization_url: Some(authorization_url.into()),
                token_url: token_url.into(),
                refresh_url: None,
                scopes: scopes
                    .into_iter()
                    .map(|(k, v)| (k.into(), v.into()))
                    .collect(),
            }),
            ..Default::default()
        }
    }

    /// Creates a new OAuth2Flows with client credentials flow.
    pub fn client_credentials(
        token_url: impl Into<String>,
        scopes: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        Self {
            client_credentials: Some(OAuth2Flow {
                authorization_url: None,
                token_url: token_url.into(),
                refresh_url: None,
                scopes: scopes
                    .into_iter()
                    .map(|(k, v)| (k.into(), v.into()))
                    .collect(),
            }),
            ..Default::default()
        }
    }

    fn to_utoipa(&self) -> UtoipaOAuth2 {
        let mut flows: Vec<Flow> = Vec::new();

        if let Some(flow) = &self.authorization_code {
            let scopes = Scopes::from_iter(flow.scopes.clone());
            let auth_code = if let Some(ref refresh) = flow.refresh_url {
                AuthorizationCode::with_refresh_url(
                    flow.authorization_url.as_deref().unwrap_or_default(),
                    &flow.token_url,
                    scopes,
                    refresh,
                )
            } else {
                AuthorizationCode::new(
                    flow.authorization_url.as_deref().unwrap_or_default(),
                    &flow.token_url,
                    scopes,
                )
            };
            flows.push(Flow::AuthorizationCode(auth_code));
        }

        if let Some(flow) = &self.client_credentials {
            let scopes = Scopes::from_iter(flow.scopes.clone());
            let client_creds = if let Some(ref refresh) = flow.refresh_url {
                ClientCredentials::with_refresh_url(&flow.token_url, scopes, refresh)
            } else {
                ClientCredentials::new(&flow.token_url, scopes)
            };
            flows.push(Flow::ClientCredentials(client_creds));
        }

        if let Some(flow) = &self.implicit {
            let scopes = Scopes::from_iter(flow.scopes.clone());
            let implicit = if let Some(ref refresh) = flow.refresh_url {
                Implicit::with_refresh_url(&flow.authorization_url, scopes, refresh)
            } else {
                Implicit::new(&flow.authorization_url, scopes)
            };
            flows.push(Flow::Implicit(implicit));
        }

        if let Some(flow) = &self.password {
            let scopes = Scopes::from_iter(flow.scopes.clone());
            let password = if let Some(ref refresh) = flow.refresh_url {
                Password::with_refresh_url(&flow.token_url, scopes, refresh)
            } else {
                Password::new(&flow.token_url, scopes)
            };
            flows.push(Flow::Password(password));
        }

        UtoipaOAuth2::new(flows)
    }
}

/// OAuth2 flow configuration (for flows with token URL).
#[derive(Debug, Clone, PartialEq)]
pub struct OAuth2Flow {
    /// Authorization URL (required for authorization_code, not for client_credentials)
    pub authorization_url: Option<String>,
    /// Token URL
    pub token_url: String,
    /// Refresh URL (optional)
    pub refresh_url: Option<String>,
    /// Available scopes
    pub scopes: IndexMap<String, String>,
}

/// OAuth2 implicit flow configuration.
#[derive(Debug, Clone, PartialEq)]
pub struct OAuth2ImplicitFlow {
    /// Authorization URL
    pub authorization_url: String,
    /// Refresh URL (optional)
    pub refresh_url: Option<String>,
    /// Available scopes
    pub scopes: IndexMap<String, String>,
}

/// Security requirement specifying which scheme and scopes are needed.
///
/// A security requirement references a security scheme by name and optionally
/// specifies required scopes (for OAuth2 schemes).
///
/// # Example
///
/// ```rust
/// use clawspec_core::SecurityRequirement;
///
/// // Simple requirement (no scopes)
/// let bearer_req = SecurityRequirement::new("bearerAuth");
///
/// // OAuth2 with required scopes
/// let oauth_req = SecurityRequirement::with_scopes("oauth2", ["read:users", "write:users"]);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SecurityRequirement {
    /// Name of the security scheme (must match a registered scheme)
    pub name: String,
    /// Required scopes (empty for non-OAuth schemes)
    pub scopes: Vec<String>,
}

impl SecurityRequirement {
    /// Creates a new security requirement without scopes.
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the security scheme
    ///
    /// # Example
    ///
    /// ```rust
    /// use clawspec_core::SecurityRequirement;
    ///
    /// let req = SecurityRequirement::new("bearerAuth");
    /// ```
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            scopes: Vec::new(),
        }
    }

    /// Creates a new security requirement with scopes.
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the security scheme
    /// * `scopes` - Required OAuth2 scopes
    ///
    /// # Example
    ///
    /// ```rust
    /// use clawspec_core::SecurityRequirement;
    ///
    /// let req = SecurityRequirement::with_scopes("oauth2", ["read:users", "write:users"]);
    /// ```
    pub fn with_scopes(
        name: impl Into<String>,
        scopes: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            name: name.into(),
            scopes: scopes.into_iter().map(Into::into).collect(),
        }
    }

    /// Converts to utoipa SecurityRequirement.
    pub(crate) fn to_utoipa(&self) -> utoipa::openapi::security::SecurityRequirement {
        utoipa::openapi::security::SecurityRequirement::new(
            &self.name,
            self.scopes.iter().map(String::as_str),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_bearer_scheme_creation() {
        let scheme = SecurityScheme::bearer();
        assert!(matches!(
            scheme,
            SecurityScheme::Bearer {
                format: None,
                description: None
            }
        ));
    }

    #[test]
    fn test_bearer_with_format() {
        let scheme = SecurityScheme::bearer_with_format("JWT");
        assert!(matches!(
            scheme,
            SecurityScheme::Bearer {
                format: Some(ref f),
                description: None
            } if f == "JWT"
        ));
    }

    #[test]
    fn test_basic_scheme_creation() {
        let scheme = SecurityScheme::basic();
        assert!(matches!(
            scheme,
            SecurityScheme::Basic { description: None }
        ));
    }

    #[test]
    fn test_api_key_scheme_creation() {
        let scheme = SecurityScheme::api_key("X-API-Key", ApiKeyLocation::Header);
        assert!(matches!(
            scheme,
            SecurityScheme::ApiKey {
                ref name,
                location: ApiKeyLocation::Header,
                description: None
            } if name == "X-API-Key"
        ));
    }

    #[test]
    fn test_with_description() {
        let scheme = SecurityScheme::bearer().with_description("JWT Bearer token");
        assert!(matches!(
            scheme,
            SecurityScheme::Bearer {
                format: None,
                description: Some(ref d)
            } if d == "JWT Bearer token"
        ));
    }

    #[test]
    fn test_security_requirement_new() {
        let req = SecurityRequirement::new("bearerAuth");
        assert_eq!(req.name, "bearerAuth");
        assert!(req.scopes.is_empty());
    }

    #[test]
    fn test_security_requirement_with_scopes() {
        let req = SecurityRequirement::with_scopes("oauth2", ["read:users", "write:users"]);
        assert_eq!(req.name, "oauth2");
        assert_eq!(req.scopes, vec!["read:users", "write:users"]);
    }

    #[test]
    fn test_bearer_to_utoipa() {
        let scheme = SecurityScheme::bearer_with_format("JWT").with_description("JWT token");
        let utoipa_scheme = scheme.to_utoipa();

        assert!(matches!(utoipa_scheme, UtoipaSecurityScheme::Http(_)));
    }

    #[test]
    fn test_basic_to_utoipa() {
        let scheme = SecurityScheme::basic();
        let utoipa_scheme = scheme.to_utoipa();

        assert!(matches!(utoipa_scheme, UtoipaSecurityScheme::Http(_)));
    }

    #[test]
    fn test_api_key_to_utoipa() {
        let scheme = SecurityScheme::api_key("X-API-Key", ApiKeyLocation::Header);
        let utoipa_scheme = scheme.to_utoipa();

        assert!(matches!(utoipa_scheme, UtoipaSecurityScheme::ApiKey(_)));
    }

    #[test]
    fn test_openid_connect_to_utoipa() {
        let scheme = SecurityScheme::openid_connect("https://auth.example.com/.well-known/openid");
        let utoipa_scheme = scheme.to_utoipa();

        assert!(matches!(
            utoipa_scheme,
            UtoipaSecurityScheme::OpenIdConnect(_)
        ));
    }

    #[test]
    fn test_oauth2_authorization_code_flows() {
        let flows = OAuth2Flows::authorization_code(
            "https://auth.example.com/authorize",
            "https://auth.example.com/token",
            [("read:users", "Read user data")],
        );

        assert!(flows.authorization_code.is_some());
        assert!(flows.client_credentials.is_none());
    }

    #[test]
    fn test_oauth2_client_credentials_flows() {
        let flows = OAuth2Flows::client_credentials(
            "https://auth.example.com/token",
            [("api:access", "API access")],
        );

        assert!(flows.client_credentials.is_some());
        assert!(flows.authorization_code.is_none());
    }

    #[test]
    fn test_security_requirement_to_utoipa() {
        let req = SecurityRequirement::with_scopes("oauth2", ["read:users"]);
        let utoipa_req = req.to_utoipa();

        // Verify the requirement was created (internal structure)
        assert!(format!("{utoipa_req:?}").contains("oauth2"));
    }
}