aperture-cli 0.1.9

Dynamic CLI generator for OpenAPI specifications
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
// These lints are overly pedantic for test code
#![allow(clippy::default_trait_access)]
#![allow(clippy::field_reassign_with_default)]
#![allow(clippy::too_many_lines)]
#![allow(clippy::missing_panics_doc)]
#![allow(clippy::option_if_let_else)]
#![allow(clippy::significant_drop_tightening)]

use aperture_cli::config::context_name::ApiContextName;
use aperture_cli::config::manager::ConfigManager;
use aperture_cli::error::{Error, ErrorKind as ApertureErrorKind};

/// Helper to create a validated `ApiContextName` from a string literal in tests
fn name(s: &str) -> ApiContextName {
    ApiContextName::new(s).expect("test name should be valid")
}
use aperture_cli::fs::FileSystem;
use std::collections::HashMap;
use std::io::{self, ErrorKind};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

// Mock FileSystem implementation for testing
#[derive(Clone)]
pub struct MockFileSystem {
    files: Arc<Mutex<HashMap<PathBuf, Vec<u8>>>>,
    dirs: Arc<Mutex<HashMap<PathBuf, bool>>>,
}

impl Default for MockFileSystem {
    fn default() -> Self {
        Self::new()
    }
}

impl MockFileSystem {
    #[must_use]
    pub fn new() -> Self {
        Self {
            files: Arc::new(Mutex::new(HashMap::new())),
            dirs: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    pub fn add_file(&self, path: &Path, content: &str) {
        self.files
            .lock()
            .unwrap()
            .insert(path.to_path_buf(), content.as_bytes().to_vec());
        self.dirs
            .lock()
            .unwrap()
            .insert(path.parent().unwrap().to_path_buf(), true);
    }

    pub fn add_dir(&self, path: &Path) {
        self.dirs.lock().unwrap().insert(path.to_path_buf(), true);
    }
}

impl FileSystem for MockFileSystem {
    fn read_to_string(&self, path: &Path) -> io::Result<String> {
        let files = self.files.lock().unwrap();
        if let Some(content) = files.get(path) {
            String::from_utf8(content.clone())
                .map_err(|_| io::Error::new(ErrorKind::InvalidData, "Invalid UTF-8 in file"))
        } else {
            Err(io::Error::new(ErrorKind::NotFound, "File not found"))
        }
    }

    fn write_all(&self, path: &Path, contents: &[u8]) -> io::Result<()> {
        self.files
            .lock()
            .unwrap()
            .insert(path.to_path_buf(), contents.to_vec());
        Ok(())
    }

    fn create_dir_all(&self, path: &Path) -> io::Result<()> {
        self.dirs.lock().unwrap().insert(path.to_path_buf(), true);
        Ok(())
    }

    fn exists(&self, path: &Path) -> bool {
        let files = self.files.lock().unwrap();
        let dirs = self.dirs.lock().unwrap();
        files.contains_key(path) || dirs.contains_key(path)
    }

    fn remove_file(&self, path: &Path) -> io::Result<()> {
        let mut files = self.files.lock().unwrap();
        if files.remove(path).is_some() {
            Ok(())
        } else {
            Err(io::Error::new(ErrorKind::NotFound, "File not found"))
        }
    }

    fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
        let files = self.files.lock().unwrap();
        let entries: Vec<PathBuf> = files
            .keys()
            .filter(|p| p.parent() == Some(path))
            .cloned()
            .collect();
        Ok(entries)
    }

    fn is_file(&self, path: &Path) -> bool {
        self.files.lock().unwrap().contains_key(path)
    }

    fn remove_dir_all(&self, path: &Path) -> io::Result<()> {
        self.dirs.lock().unwrap().remove(path);
        Ok(())
    }

    fn is_dir(&self, path: &Path) -> bool {
        self.dirs.lock().unwrap().contains_key(path)
    }

    fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
        Ok(path.to_path_buf())
    }

    fn atomic_write(&self, path: &Path, contents: &[u8]) -> io::Result<()> {
        self.write_all(path, contents)
    }
}

fn setup_manager() -> (ConfigManager<MockFileSystem>, MockFileSystem) {
    let fs = MockFileSystem::new();
    let config_dir = PathBuf::from("/test/config");
    fs.add_dir(&config_dir);
    let manager = ConfigManager::with_fs(fs.clone(), config_dir);
    (manager, fs)
}

fn setup_dir(fs: &MockFileSystem) -> PathBuf {
    let dir = PathBuf::from("/test/specs");
    fs.add_dir(&dir);
    dir
}

#[test]
fn test_add_spec_with_custom_http_scheme_token() {
    let (manager, fs) = setup_manager();

    // Create a spec with Token HTTP scheme (common alternative to Bearer)
    let spec_content = r"
openapi: 3.0.0
info:
  title: Token Auth API
  version: 1.0.0
servers:
  - url: https://api.example.com
components:
  securitySchemes:
    tokenAuth:
      type: http
      scheme: Token
      x-aperture-secret:
        source: env
        name: API_TOKEN
paths:
  /users:
    get:
      operationId: getUsers
      security:
        - tokenAuth: []
      responses:
        '200':
          description: Success
";

    let spec_path = setup_dir(&fs).join("token-api.yaml");
    fs.write_all(&spec_path, spec_content.as_bytes())
        .expect("Failed to write spec");

    // Should succeed - Token scheme is now supported
    let result = manager.add_spec(&name("token-api"), &spec_path, false, false);
    assert!(result.is_ok(), "Token HTTP scheme should be supported");

    // Verify the spec was added
    let specs = manager.list_specs().expect("Failed to list specs");
    assert!(specs.contains(&"token-api".to_string()));
}

#[test]
fn test_add_spec_with_custom_http_scheme_apikey() {
    let (manager, fs) = setup_manager();

    // Create a spec with ApiKey HTTP scheme (note: different from apiKey type)
    let spec_content = r"
openapi: 3.0.0
info:
  title: ApiKey Scheme API
  version: 1.0.0
servers:
  - url: https://api.example.com
components:
  securitySchemes:
    customAuth:
      type: http
      scheme: ApiKey
      x-aperture-secret:
        source: env
        name: CUSTOM_API_KEY
paths:
  /data:
    get:
      operationId: getData
      security:
        - customAuth: []
      responses:
        '200':
          description: Success
";

    let spec_path = setup_dir(&fs).join("apikey-scheme.yaml");
    fs.write_all(&spec_path, spec_content.as_bytes())
        .expect("Failed to write spec");

    // Should succeed - ApiKey HTTP scheme is now supported
    let result = manager.add_spec(&name("apikey-scheme"), &spec_path, false, false);
    assert!(result.is_ok(), "ApiKey HTTP scheme should be supported");
}

#[test]
fn test_add_spec_with_dsn_scheme() {
    let (manager, fs) = setup_manager();

    // Create a spec with DSN HTTP scheme (Sentry-style)
    let spec_content = r"
openapi: 3.0.0
info:
  title: Sentry-style API
  version: 1.0.0
servers:
  - url: https://api.example.com
components:
  securitySchemes:
    dsnAuth:
      type: http
      scheme: DSN
      x-aperture-secret:
        source: env
        name: SENTRY_DSN
paths:
  /events:
    post:
      operationId: sendEvent
      security:
        - dsnAuth: []
      responses:
        '200':
          description: Success
";

    let spec_path = setup_dir(&fs).join("dsn-api.yaml");
    fs.write_all(&spec_path, spec_content.as_bytes())
        .expect("Failed to write spec");

    // Should succeed - DSN scheme is now supported
    let result = manager.add_spec(&name("dsn-api"), &spec_path, false, false);
    assert!(result.is_ok(), "DSN HTTP scheme should be supported");
}

#[test]
fn test_rejected_complex_auth_schemes() {
    let (manager, fs) = setup_manager();

    // Test OAuth scheme (should be rejected)
    let oauth_spec = r"
openapi: 3.0.0
info:
  title: OAuth API
  version: 1.0.0
servers:
  - url: https://api.example.com
components:
  securitySchemes:
    oauthScheme:
      type: http
      scheme: oauth
      x-aperture-secret:
        source: env
        name: OAUTH_TOKEN
paths:
  /users:
    get:
      operationId: getUsers
      security:
        - oauthScheme: []
      responses:
        '200':
          description: Success
";

    let spec_path = setup_dir(&fs).join("oauth-api.yaml");
    fs.write_all(&spec_path, oauth_spec.as_bytes())
        .expect("Failed to write spec");

    // Should fail in strict mode
    let result = manager.add_spec(&name("oauth-api"), &spec_path, false, true);
    assert!(
        result.is_err(),
        "OAuth HTTP scheme should be rejected in strict mode"
    );

    // Test Negotiate scheme (should be rejected)
    let negotiate_spec = r"
openapi: 3.0.0
info:
  title: Negotiate API
  version: 1.0.0
servers:
  - url: https://api.example.com
components:
  securitySchemes:
    negotiateAuth:
      type: http
      scheme: negotiate
paths:
  /users:
    get:
      operationId: getUsers
      security:
        - negotiateAuth: []
      responses:
        '200':
          description: Success
";

    let spec_path = setup_dir(&fs).join("negotiate-api.yaml");
    fs.write_all(&spec_path, negotiate_spec.as_bytes())
        .expect("Failed to write spec");

    // Should fail in strict mode
    let result = manager.add_spec(&name("negotiate-api"), &spec_path, false, true);
    assert!(
        result.is_err(),
        "Negotiate HTTP scheme should be rejected in strict mode"
    );
}

#[test]
fn test_add_spec_with_proprietary_http_scheme() {
    let (manager, fs) = setup_manager();

    // Create a spec with a completely custom/proprietary HTTP scheme
    let spec_content = r"
openapi: 3.0.0
info:
  title: Proprietary Auth API
  version: 1.0.0
servers:
  - url: https://api.example.com
components:
  securitySchemes:
    customScheme:
      type: http
      scheme: X-CompanyAuth-V2
      x-aperture-secret:
        source: env
        name: COMPANY_AUTH_TOKEN
paths:
  /protected:
    get:
      operationId: getProtected
      security:
        - customScheme: []
      responses:
        '200':
          description: Success
";

    let spec_path = setup_dir(&fs).join("proprietary-api.yaml");
    fs.write_all(&spec_path, spec_content.as_bytes())
        .expect("Failed to write spec");

    // Should succeed - any custom scheme name is now supported
    let result = manager.add_spec(&name("proprietary-api"), &spec_path, false, false);
    assert!(
        result.is_ok(),
        "Custom proprietary HTTP schemes should be supported"
    );
}

#[test]
fn test_reject_oauth_http_scheme() {
    let (manager, fs) = setup_manager();

    // Create a spec with 'oauth' as HTTP scheme (should be rejected)
    let spec_content = r"
openapi: 3.0.0
info:
  title: OAuth HTTP Scheme API
  version: 1.0.0
servers:
  - url: https://api.example.com
components:
  securitySchemes:
    oauthScheme:
      type: http
      scheme: oauth
paths:
  /users:
    get:
      operationId: getUsers
      responses:
        '200':
          description: Success
";

    let spec_path = setup_dir(&fs).join("oauth-http.yaml");
    fs.write_all(&spec_path, spec_content.as_bytes())
        .expect("Failed to write spec");

    // Should fail - 'oauth' as HTTP scheme suggests complex flows
    let result = manager.add_spec(&name("oauth-http"), &spec_path, false, true); // Use strict mode
    assert!(result.is_err());
    if let Err(Error::Internal {
        kind: ApertureErrorKind::Validation,
        message: msg,
        ..
    }) = result
    {
        assert!(
            msg.contains("requires complex authentication flows"),
            "Expected complex auth flow error, got: {msg}"
        );
    } else {
        panic!("Expected Validation error for oauth HTTP scheme");
    }
}

#[test]
fn test_reject_negotiate_http_scheme() {
    let (manager, fs) = setup_manager();

    // Create a spec with 'negotiate' HTTP scheme (Kerberos/NTLM)
    let spec_content = r"
openapi: 3.0.0
info:
  title: Negotiate Auth API
  version: 1.0.0
servers:
  - url: https://api.example.com
components:
  securitySchemes:
    negotiateAuth:
      type: http
      scheme: Negotiate
paths:
  /secure:
    get:
      operationId: getSecure
      responses:
        '200':
          description: Success
";

    let spec_path = setup_dir(&fs).join("negotiate-api.yaml");
    fs.write_all(&spec_path, spec_content.as_bytes())
        .expect("Failed to write spec");

    // Should fail - Negotiate requires complex Kerberos/NTLM flows
    let result = manager.add_spec(&name("negotiate-api"), &spec_path, false, true); // Use strict mode
    assert!(result.is_err());
    if let Err(Error::Internal {
        kind: ApertureErrorKind::Validation,
        message: msg,
        ..
    }) = result
    {
        assert!(
            msg.contains("requires complex authentication flows"),
            "Expected complex auth flow error, got: {msg}"
        );
    } else {
        panic!("Expected Validation error for Negotiate scheme");
    }
}