mrapids 0.1.31

Your OpenAPI, but executable
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
#![allow(dead_code)]

use crate::core::api::ApiError;
use crate::models::auth::{
    CredentialSource, CredentialStatus, SchemeType, SecurityRequirement, SelectedAuth,
    SelectionReason, ValidationStatus,
};
use anyhow::{Context, Result};
use std::collections::{HashMap, HashSet};
use std::env;
use std::path::PathBuf;

/// Manages runtime authentication selection based on requirements and available credentials
pub struct AuthSelector {
    /// Available authentication schemes and their status
    available_credentials: HashMap<String, CredentialStatus>,
    /// Security requirement for the current operation
    operation_requirements: Option<SecurityRequirement>,
    /// Global security requirements (fallback)
    global_requirements: Option<SecurityRequirement>,
    /// User preference for auth scheme
    preferred_scheme: Option<String>,
}

impl AuthSelector {
    /// Create a new auth selector
    pub fn new() -> Self {
        Self {
            available_credentials: HashMap::new(),
            operation_requirements: None,
            global_requirements: None,
            preferred_scheme: None,
        }
    }

    /// Set operation-specific requirements
    pub fn with_operation_requirements(mut self, req: SecurityRequirement) -> Self {
        self.operation_requirements = Some(req);
        self
    }

    /// Set global requirements (used as fallback)
    pub fn with_global_requirements(mut self, req: SecurityRequirement) -> Self {
        self.global_requirements = Some(req);
        self
    }

    /// Set user's preferred scheme (--auth parameter)
    pub fn with_preferred_scheme(mut self, scheme: String) -> Self {
        self.preferred_scheme = Some(scheme);
        self
    }

    /// Discover available credentials from environment and config
    pub fn discover_credentials(
        &mut self,
        schemes: &HashMap<String, crate::models::auth::SecuritySchemeDetails>,
    ) -> Result<()> {
        for (name, details) in schemes {
            let status = self.check_credential_status(name, details)?;
            self.available_credentials.insert(name.clone(), status);
        }
        Ok(())
    }

    /// Check if credentials are available for a scheme
    fn check_credential_status(
        &self,
        name: &str,
        details: &crate::models::auth::SecuritySchemeDetails,
    ) -> Result<CredentialStatus> {
        let (is_configured, source) = match details.scheme_type {
            SchemeType::ApiKey => self.check_api_key(name),
            SchemeType::Http => self.check_http_auth(name, details),
            SchemeType::OAuth2 => self.check_oauth2(name),
            SchemeType::OpenIdConnect => self.check_oidc(name),
            SchemeType::MutualTls => self.check_mtls(name),
        };

        Ok(CredentialStatus {
            scheme_name: name.to_string(),
            is_configured,
            source,
            validation_status: ValidationStatus::NotValidated,
            last_used: None,
        })
    }

    /// Check for API key in environment or config
    fn check_api_key(&self, name: &str) -> (bool, CredentialSource) {
        // Check environment variables (common patterns)
        let env_vars = vec![
            format!("{}_API_KEY", name.to_uppercase()),
            format!("API_KEY"),
            format!("{}_KEY", name.to_uppercase()),
        ];

        for var in env_vars {
            if env::var(&var).is_ok() {
                return (true, CredentialSource::Environment(var));
            }
        }

        // Check config file
        let config_path = self.get_auth_config_path(name);
        if config_path.exists() {
            return (
                true,
                CredentialSource::ConfigFile(config_path.to_string_lossy().to_string()),
            );
        }

        (false, CredentialSource::NotConfigured)
    }

    /// Check for HTTP auth (Bearer/Basic)
    fn check_http_auth(
        &self,
        name: &str,
        details: &crate::models::auth::SecuritySchemeDetails,
    ) -> (bool, CredentialSource) {
        let is_bearer = details.bearer_format.is_some();

        let env_vars = if is_bearer {
            vec![
                format!("{}_TOKEN", name.to_uppercase()),
                format!("BEARER_TOKEN"),
                format!("ACCESS_TOKEN"),
                format!("AUTH_TOKEN"),
            ]
        } else {
            vec![
                format!("{}_USERNAME", name.to_uppercase()),
                format!("{}_PASSWORD", name.to_uppercase()),
                format!("BASIC_AUTH"),
            ]
        };

        for var in &env_vars {
            if env::var(var).is_ok() {
                return (true, CredentialSource::Environment(var.clone()));
            }
        }

        // Check for auth profile
        let profile_path = self.get_auth_profile_path(name);
        if profile_path.exists() {
            return (true, CredentialSource::Profile(name.to_string()));
        }

        (false, CredentialSource::NotConfigured)
    }

    /// Check for OAuth2 credentials
    fn check_oauth2(&self, name: &str) -> (bool, CredentialSource) {
        // Check for token file in ~/.mrapids/auth/tokens/
        let token_path = dirs::home_dir()
            .map(|d| {
                d.join(".mrapids")
                    .join("auth")
                    .join("tokens")
                    .join(format!("{}.json", name))
            })
            .unwrap_or_default();

        if token_path.exists() {
            return (true, CredentialSource::Profile(name.to_string()));
        }

        // Check for client credentials in environment
        let client_id = format!("{}_CLIENT_ID", name.to_uppercase());
        let client_secret = format!("{}_CLIENT_SECRET", name.to_uppercase());

        if env::var(&client_id).is_ok() && env::var(&client_secret).is_ok() {
            return (
                true,
                CredentialSource::Environment(format!("{}, {}", client_id, client_secret)),
            );
        }

        (false, CredentialSource::NotConfigured)
    }

    /// Check for OpenID Connect configuration
    fn check_oidc(&self, name: &str) -> (bool, CredentialSource) {
        // Similar to OAuth2, check for tokens
        self.check_oauth2(name)
    }

    /// Check for mTLS certificates
    fn check_mtls(&self, name: &str) -> (bool, CredentialSource) {
        let cert_vars = vec![
            format!("{}_CLIENT_CERT", name.to_uppercase()),
            format!("{}_CLIENT_KEY", name.to_uppercase()),
            format!("CLIENT_CERT_PATH"),
            format!("CLIENT_KEY_PATH"),
        ];

        for var in &cert_vars {
            if let Ok(path) = env::var(var) {
                if PathBuf::from(&path).exists() {
                    return (true, CredentialSource::Environment(var.clone()));
                }
            }
        }

        (false, CredentialSource::NotConfigured)
    }

    /// Select the best available authentication scheme
    pub fn select_best_scheme(&self) -> Result<SelectedAuth> {
        // 1. If user specified a preference, try to use it
        if let Some(preferred) = &self.preferred_scheme {
            if let Some(cred) = self.available_credentials.get(preferred) {
                if cred.is_configured {
                    return self
                        .create_selected_auth(preferred, SelectionReason::ExplicitSelection);
                } else {
                    return Err(ApiError::AuthError(format!(
                        "Preferred auth scheme '{}' is not configured",
                        preferred
                    ))
                    .into());
                }
            } else {
                return Err(
                    ApiError::AuthError(format!("Unknown auth scheme: {}", preferred)).into(),
                );
            }
        }

        // 2. Get the active requirements (operation overrides global)
        let requirements = self
            .operation_requirements
            .as_ref()
            .or(self.global_requirements.as_ref());

        if let Some(req) = requirements {
            // 3. Check if no auth is required
            if req.is_optional() {
                return self.create_selected_auth("none", SelectionReason::OnlyOption);
            }

            // 4. Find the simplest valid option
            if let Some(option) = req.simplest_option() {
                // Check if all required schemes are available
                let mut all_available = true;
                let mut first_scheme = None;

                for scheme_req in &option.schemes {
                    if first_scheme.is_none() {
                        first_scheme = Some(&scheme_req.name);
                    }

                    if let Some(cred) = self.available_credentials.get(&scheme_req.name) {
                        if !cred.is_configured {
                            all_available = false;
                            break;
                        }
                    } else {
                        all_available = false;
                        break;
                    }
                }

                if all_available {
                    if let Some(scheme_name) = first_scheme {
                        return self.create_selected_auth(
                            scheme_name,
                            SelectionReason::BestAvailable("Simplest valid option".to_string()),
                        );
                    }
                }
            }

            // 5. Try any available option
            for option in &req.options {
                let mut all_available = true;
                let mut schemes_needed = Vec::new();

                for scheme_req in &option.schemes {
                    schemes_needed.push(scheme_req.name.clone());
                    if let Some(cred) = self.available_credentials.get(&scheme_req.name) {
                        if !cred.is_configured {
                            all_available = false;
                            break;
                        }
                    } else {
                        all_available = false;
                        break;
                    }
                }

                if all_available && !schemes_needed.is_empty() {
                    return self.create_selected_auth(
                        &schemes_needed[0],
                        SelectionReason::BestAvailable(format!(
                            "First available option with {} scheme(s)",
                            schemes_needed.len()
                        )),
                    );
                }
            }

            return Err(ApiError::AuthError(
                "No valid authentication credentials available for this operation".to_string(),
            )
            .into());
        }

        // 6. No requirements, check for any configured scheme
        for (name, cred) in &self.available_credentials {
            if cred.is_configured {
                return self.create_selected_auth(name, SelectionReason::Default);
            }
        }

        // 7. No auth required or available
        self.create_selected_auth("none", SelectionReason::OnlyOption)
    }

    /// Create a SelectedAuth result
    fn create_selected_auth(
        &self,
        scheme_name: &str,
        reason: SelectionReason,
    ) -> Result<SelectedAuth> {
        let cred = self
            .available_credentials
            .get(scheme_name)
            .context("Auth scheme not found")?;

        // Note: We don't include actual credential values for security
        let credentials = HashMap::new(); // Redacted

        Ok(SelectedAuth {
            scheme_name: scheme_name.to_string(),
            scheme_type: SchemeType::Http, // Would need scheme details to set correctly
            credentials,
            source: cred.source.clone(),
            reason,
        })
    }

    /// Validate that a specific scheme can be used
    pub fn validate_selection(&self, scheme: &str) -> Result<()> {
        let requirements = self
            .operation_requirements
            .as_ref()
            .or(self.global_requirements.as_ref());

        if let Some(req) = requirements {
            // Check if the scheme satisfies any option
            for option in &req.options {
                let schemes_in_option: HashSet<String> =
                    option.schemes.iter().map(|s| s.name.clone()).collect();

                if schemes_in_option.contains(scheme) {
                    // Check if all schemes in this option are available
                    let mut all_available = true;
                    for required_scheme in &schemes_in_option {
                        if let Some(cred) = self.available_credentials.get(required_scheme) {
                            if !cred.is_configured {
                                all_available = false;
                                break;
                            }
                        } else {
                            all_available = false;
                            break;
                        }
                    }

                    if all_available {
                        return Ok(());
                    } else {
                        return Err(ApiError::AuthError(format!(
                            "Auth scheme '{}' requires additional schemes to be configured",
                            scheme
                        ))
                        .into());
                    }
                }
            }

            return Err(ApiError::AuthError(format!(
                "Auth scheme '{}' does not satisfy the security requirements",
                scheme
            ))
            .into());
        }

        // No requirements, any configured scheme is valid
        if let Some(cred) = self.available_credentials.get(scheme) {
            if cred.is_configured {
                Ok(())
            } else {
                Err(
                    ApiError::AuthError(format!("Auth scheme '{}' is not configured", scheme))
                        .into(),
                )
            }
        } else {
            Err(ApiError::AuthError(format!("Unknown auth scheme: {}", scheme)).into())
        }
    }

    /// Get path to auth config file
    fn get_auth_config_path(&self, name: &str) -> PathBuf {
        // Auth is now stored in user's home directory, not project config
        dirs::home_dir()
            .map(|d| {
                d.join(".mrapids")
                    .join("auth")
                    .join(format!("{}.yaml", name))
            })
            .unwrap_or_else(|| {
                PathBuf::from(".mrapids")
                    .join("auth")
                    .join(format!("{}.yaml", name))
            })
    }

    /// Get path to auth profile
    fn get_auth_profile_path(&self, name: &str) -> PathBuf {
        PathBuf::from(".mrapids")
            .join("auth")
            .join(format!("{}.toml", name))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::auth::{RequirementOption, SchemeRequirement};

    #[test]
    fn test_select_with_preference() {
        let mut selector = AuthSelector::new().with_preferred_scheme("api_key".to_string());

        selector.available_credentials.insert(
            "api_key".to_string(),
            CredentialStatus {
                scheme_name: "api_key".to_string(),
                is_configured: true,
                source: CredentialSource::Environment("API_KEY".to_string()),
                validation_status: ValidationStatus::NotValidated,
                last_used: None,
            },
        );

        let selected = selector.select_best_scheme().unwrap();
        assert_eq!(selected.scheme_name, "api_key");
        matches!(selected.reason, SelectionReason::ExplicitSelection);
    }

    #[test]
    fn test_select_simplest_option() {
        let mut selector = AuthSelector::new();

        // Add a requirement with two options
        let mut req = SecurityRequirement::default();

        // Option 1: Just API key
        req.options.push(RequirementOption {
            schemes: vec![SchemeRequirement {
                name: "api_key".to_string(),
                scopes: vec![],
            }],
        });

        // Option 2: OAuth2 + Basic (more complex)
        req.options.push(RequirementOption {
            schemes: vec![
                SchemeRequirement {
                    name: "oauth2".to_string(),
                    scopes: vec!["read".to_string()],
                },
                SchemeRequirement {
                    name: "basic".to_string(),
                    scopes: vec![],
                },
            ],
        });

        selector = selector.with_operation_requirements(req);

        // Only API key is configured
        selector.available_credentials.insert(
            "api_key".to_string(),
            CredentialStatus {
                scheme_name: "api_key".to_string(),
                is_configured: true,
                source: CredentialSource::Environment("API_KEY".to_string()),
                validation_status: ValidationStatus::NotValidated,
                last_used: None,
            },
        );

        let selected = selector.select_best_scheme().unwrap();
        assert_eq!(selected.scheme_name, "api_key");
    }
}