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
503
504
505
506
#![allow(dead_code)]

use crate::core::api::ApiError;
use anyhow::{Context, Result};
use colored::*;
use reqwest::StatusCode;
use std::collections::HashMap;

use crate::models::auth::{CredentialSource, SchemeType, SecuritySchemeDetails};

#[derive(Debug, Clone)]
pub struct AuthDiagnostic {
    pub error_type: AuthErrorType,
    pub scheme_name: String,
    pub details: String,
    pub suggestions: Vec<String>,
    pub help_commands: Vec<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum AuthErrorType {
    MissingCredentials,
    InvalidCredentials,
    ExpiredToken,
    InsufficientScopes,
    NetworkError,
    ConfigurationError,
    UnsupportedScheme,
}

pub struct AuthDiagnostics {
    scheme_details: HashMap<String, SecuritySchemeDetails>,
}

impl AuthDiagnostics {
    pub fn new(scheme_details: HashMap<String, SecuritySchemeDetails>) -> Self {
        Self { scheme_details }
    }

    /// Diagnose authentication error based on HTTP response
    pub fn diagnose_from_response(
        &self,
        status: StatusCode,
        headers: &reqwest::header::HeaderMap,
        body: &str,
        scheme_name: &str,
    ) -> AuthDiagnostic {
        let scheme = self.scheme_details.get(scheme_name);

        match status {
            StatusCode::UNAUTHORIZED => self.diagnose_401(headers, body, scheme_name, scheme),
            StatusCode::FORBIDDEN => self.diagnose_403(headers, body, scheme_name, scheme),
            StatusCode::TOO_MANY_REQUESTS => self.diagnose_429(headers, body, scheme_name, scheme),
            _ => self.diagnose_generic(status, body, scheme_name, scheme),
        }
    }

    /// Diagnose 401 Unauthorized errors
    fn diagnose_401(
        &self,
        headers: &reqwest::header::HeaderMap,
        body: &str,
        scheme_name: &str,
        scheme: Option<&SecuritySchemeDetails>,
    ) -> AuthDiagnostic {
        let mut suggestions = Vec::new();
        let mut help_commands = Vec::new();
        let mut error_type = AuthErrorType::InvalidCredentials;
        let mut details = String::new();

        // Check WWW-Authenticate header for hints
        if let Some(www_auth) = headers.get("www-authenticate") {
            if let Ok(www_auth_str) = www_auth.to_str() {
                details = format!("Server requires: {}", www_auth_str);

                if www_auth_str.contains("Bearer") {
                    if www_auth_str.contains("error=\"invalid_token\"") {
                        error_type = AuthErrorType::InvalidCredentials;
                        suggestions.push(
                            "Your access token appears to be invalid or malformed".to_string(),
                        );
                        suggestions.push(
                            "The token may have been revoked or incorrectly copied".to_string(),
                        );
                    } else if www_auth_str.contains("error=\"expired_token\"") {
                        error_type = AuthErrorType::ExpiredToken;
                        suggestions.push("Your access token has expired".to_string());
                        suggestions
                            .push("You need to refresh or regenerate your token".to_string());
                    }
                }
            }
        }

        // Analyze response body for common patterns
        let body_lower = body.to_lowercase();
        if body_lower.contains("expired") || body_lower.contains("expir") {
            error_type = AuthErrorType::ExpiredToken;
            suggestions.push("Token or credentials have expired".to_string());
        } else if body_lower.contains("invalid") || body_lower.contains("incorrect") {
            suggestions.push("Credentials appear to be invalid".to_string());
        } else if body_lower.contains("missing") || body_lower.contains("required") {
            error_type = AuthErrorType::MissingCredentials;
            suggestions.push("Required authentication credentials are missing".to_string());
        }

        // Provide scheme-specific suggestions
        if let Some(scheme_detail) = scheme {
            match scheme_detail.scheme_type {
                SchemeType::ApiKey => {
                    suggestions.push("Check that your API key is correct and active".to_string());
                    suggestions.push(format!(
                        "Verify the key is being sent in the {} as '{}'",
                        scheme_detail
                            .location
                            .as_ref()
                            .map(|l| format!("{:?}", l).to_lowercase())
                            .unwrap_or_else(|| "header".to_string()),
                        scheme_detail
                            .name
                            .as_ref()
                            .unwrap_or(&"X-API-Key".to_string())
                    ));
                    help_commands.push(format!(
                        "mrapids auth connect {} --auth-type api-key",
                        scheme_name
                    ));
                }
                SchemeType::Http => {
                    if scheme_detail.bearer_format.is_some() {
                        suggestions.push(
                            "Ensure your Bearer token is valid and properly formatted".to_string(),
                        );
                        suggestions.push(
                            "Token should be sent as 'Authorization: Bearer <token>'".to_string(),
                        );
                        help_commands.push(format!(
                            "mrapids auth connect {} --auth-type bearer",
                            scheme_name
                        ));
                    } else {
                        suggestions.push("Check your Basic auth username and password".to_string());
                        suggestions.push("Credentials should be base64 encoded".to_string());
                        help_commands.push(format!(
                            "mrapids auth connect {} --auth-type basic",
                            scheme_name
                        ));
                    }
                }
                SchemeType::OAuth2 => {
                    suggestions.push("Your OAuth2 token may need to be refreshed".to_string());
                    suggestions.push("Check that the token has the required scopes".to_string());
                    help_commands.push(format!(
                        "mrapids auth connect {} --auth-type oauth2 --flow client-credentials",
                        scheme_name
                    ));
                    help_commands.push(format!("mrapids auth refresh {}", scheme_name));
                }
                _ => {}
            }
        }

        // Add general troubleshooting steps
        help_commands.push(format!("mrapids auth validate --scheme {}", scheme_name));
        help_commands.push("mrapids auth detect --operations".to_string());

        AuthDiagnostic {
            error_type,
            scheme_name: scheme_name.to_string(),
            details,
            suggestions,
            help_commands,
        }
    }

    /// Diagnose 403 Forbidden errors
    fn diagnose_403(
        &self,
        _headers: &reqwest::header::HeaderMap,
        body: &str,
        scheme_name: &str,
        scheme: Option<&SecuritySchemeDetails>,
    ) -> AuthDiagnostic {
        let mut suggestions = Vec::new();
        let mut help_commands = Vec::new();
        let error_type = AuthErrorType::InsufficientScopes;

        let body_lower = body.to_lowercase();
        let details = if body_lower.contains("scope") || body_lower.contains("permission") {
            "You don't have the required permissions or scopes for this operation".to_string()
        } else if body_lower.contains("rate") || body_lower.contains("limit") {
            "You may have hit a rate limit or quota restriction".to_string()
        } else {
            "Access to this resource is forbidden with your current credentials".to_string()
        };

        // Check for OAuth2 scope issues
        if let Some(scheme_detail) = scheme {
            if scheme_detail.scheme_type == SchemeType::OAuth2 {
                suggestions.push("Your token may be missing required scopes".to_string());
                suggestions
                    .push("Check the API documentation for required permissions".to_string());

                // Try to extract required scopes from error
                if body.contains("scope") {
                    if let Some(scope_match) = extract_scopes_from_error(body) {
                        suggestions.push(format!("Required scopes: {}", scope_match));
                        help_commands.push(format!(
                            "mrapids auth connect {} --scopes \"{}\"",
                            scheme_name, scope_match
                        ));
                    }
                }
            }
        }

        suggestions.push("Your credentials are valid but lack necessary permissions".to_string());
        suggestions.push("Contact the API administrator if you need additional access".to_string());

        help_commands.push(format!(
            "mrapids auth validate --scheme {} --verbose",
            scheme_name
        ));
        help_commands.push("mrapids auth detect --operations".to_string());

        AuthDiagnostic {
            error_type,
            scheme_name: scheme_name.to_string(),
            details,
            suggestions,
            help_commands,
        }
    }

    /// Diagnose 429 Too Many Requests errors
    fn diagnose_429(
        &self,
        headers: &reqwest::header::HeaderMap,
        _body: &str,
        scheme_name: &str,
        _scheme: Option<&SecuritySchemeDetails>,
    ) -> AuthDiagnostic {
        let mut suggestions = Vec::new();
        let mut help_commands = Vec::new();
        let mut details = "Rate limit exceeded".to_string();

        // Check for Retry-After header
        if let Some(retry_after) = headers.get("retry-after") {
            if let Ok(retry_str) = retry_after.to_str() {
                details = format!("Rate limit exceeded. Retry after: {} seconds", retry_str);
                suggestions.push(format!("Wait {} seconds before retrying", retry_str));
            }
        }

        // Check for rate limit headers
        if let Some(limit) = headers.get("x-ratelimit-limit") {
            if let Ok(limit_str) = limit.to_str() {
                suggestions.push(format!("Rate limit: {} requests per period", limit_str));
            }
        }

        if let Some(remaining) = headers.get("x-ratelimit-remaining") {
            if let Ok(remaining_str) = remaining.to_str() {
                suggestions.push(format!("Remaining requests: {}", remaining_str));
            }
        }

        suggestions.push("Consider implementing exponential backoff".to_string());
        suggestions.push("Reduce the frequency of your API requests".to_string());

        help_commands.push("mrapids config set --rate-limit 10".to_string());
        help_commands.push("mrapids config set --retry-delay 1000".to_string());

        AuthDiagnostic {
            error_type: AuthErrorType::NetworkError,
            scheme_name: scheme_name.to_string(),
            details,
            suggestions,
            help_commands,
        }
    }

    /// Diagnose generic errors
    fn diagnose_generic(
        &self,
        status: StatusCode,
        body: &str,
        scheme_name: &str,
        _scheme: Option<&SecuritySchemeDetails>,
    ) -> AuthDiagnostic {
        let mut suggestions = Vec::new();
        let mut help_commands = Vec::new();

        let details = format!(
            "HTTP {} error: {}",
            status.as_u16(),
            if body.len() > 100 {
                format!("{}...", &body[..100])
            } else {
                body.to_string()
            }
        );

        match status.as_u16() {
            400..=499 => {
                suggestions.push("Client error - check your request configuration".to_string());
                suggestions.push("Verify the API endpoint and parameters".to_string());
            }
            500..=599 => {
                suggestions
                    .push("Server error - the API service may be experiencing issues".to_string());
                suggestions.push("Try again later or contact the API provider".to_string());
            }
            _ => {
                suggestions.push("Unexpected error occurred".to_string());
            }
        }

        help_commands.push(format!(
            "mrapids auth validate --scheme {} --debug",
            scheme_name
        ));
        help_commands.push("mrapids config show".to_string());

        AuthDiagnostic {
            error_type: AuthErrorType::NetworkError,
            scheme_name: scheme_name.to_string(),
            details,
            suggestions,
            help_commands,
        }
    }

    /// Display diagnostic information to the user
    pub fn display(&self, diagnostic: &AuthDiagnostic) {
        println!(
            "\n{} {}",
            "".red().bold(),
            "Authentication Error".red().bold()
        );
        println!("{}", "".repeat(60).red());

        // Error details
        println!("\n{}: {}", "Scheme".yellow(), diagnostic.scheme_name.bold());
        println!("{}: {:?}", "Type".yellow(), diagnostic.error_type);
        println!("{}: {}", "Details".yellow(), diagnostic.details);

        // Suggestions
        if !diagnostic.suggestions.is_empty() {
            println!("\n{}", "Troubleshooting Suggestions:".cyan().bold());
            for (i, suggestion) in diagnostic.suggestions.iter().enumerate() {
                println!("  {}. {}", i + 1, suggestion);
            }
        }

        // Help commands
        if !diagnostic.help_commands.is_empty() {
            println!("\n{}", "Try these commands:".green().bold());
            for cmd in &diagnostic.help_commands {
                println!("  $ {}", cmd.bright_white());
            }
        }

        println!("\n{}", "".repeat(60).dimmed());
    }

    /// Validate credentials before making API calls
    pub fn prevalidate_credentials(
        &self,
        scheme_name: &str,
        source: &CredentialSource,
    ) -> Result<()> {
        let _scheme = self
            .scheme_details
            .get(scheme_name)
            .context("Unknown authentication scheme")?;

        match source {
            CredentialSource::NotConfigured => {
                return Err(ApiError::AuthError(format!(
                    "No credentials configured for '{}'. Run:\n  {}",
                    scheme_name,
                    format!("mrapids auth connect {}", scheme_name).green()
                ))
                .into());
            }
            CredentialSource::Environment(var) => {
                if std::env::var(var).is_err() {
                    return Err(ApiError::AuthError(format!(
                        "Environment variable '{}' is not set. Set it with:\n  {}",
                        var,
                        format!("export {}=<your-credential>", var).green()
                    ))
                    .into());
                }
            }
            CredentialSource::ConfigFile(path) => {
                if !std::path::Path::new(path).exists() {
                    return Err(ApiError::AuthError(format!(
                        "Configuration file '{}' not found. Create it with:\n  {}",
                        path,
                        format!("mrapids auth connect {}", scheme_name).green()
                    ))
                    .into());
                }
            }
            _ => {}
        }

        Ok(())
    }
}

/// Extract scope requirements from error message
fn extract_scopes_from_error(body: &str) -> Option<String> {
    // Common patterns for scope errors
    let patterns = [
        r"required.*scopes?:?\s*([a-zA-Z0-9:_\s,]+)",
        r"missing.*scopes?:?\s*([a-zA-Z0-9:_\s,]+)",
        r"scopes?.*required:?\s*([a-zA-Z0-9:_\s,]+)",
    ];

    for pattern in patterns {
        if let Ok(re) = regex::Regex::new(pattern) {
            if let Some(captures) = re.captures(body) {
                if let Some(scopes) = captures.get(1) {
                    return Some(scopes.as_str().trim().to_string());
                }
            }
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::auth::AuthLocation;
    use reqwest::header::HeaderMap;

    #[test]
    fn test_diagnose_401_bearer() {
        let mut schemes = HashMap::new();
        schemes.insert(
            "bearer_auth".to_string(),
            SecuritySchemeDetails {
                scheme_type: SchemeType::Http,
                location: Some(AuthLocation::Header),
                name: Some("Authorization".to_string()),
                bearer_format: Some("JWT".to_string()),
                flows: None,
                openid_connect_url: None,
                description: None,
            },
        );

        let diagnostics = AuthDiagnostics::new(schemes);
        let mut headers = HeaderMap::new();
        headers.insert(
            "www-authenticate",
            "Bearer error=\"invalid_token\"".parse().unwrap(),
        );

        let diagnostic = diagnostics.diagnose_from_response(
            StatusCode::UNAUTHORIZED,
            &headers,
            "Invalid token",
            "bearer_auth",
        );

        assert_eq!(diagnostic.error_type, AuthErrorType::InvalidCredentials);
        assert!(diagnostic
            .suggestions
            .iter()
            .any(|s| s.contains("invalid or malformed")));
        assert!(diagnostic
            .help_commands
            .iter()
            .any(|c| c.contains("auth connect")));
    }

    #[test]
    fn test_diagnose_403_scopes() {
        let schemes = HashMap::new();
        let diagnostics = AuthDiagnostics::new(schemes);
        let headers = HeaderMap::new();

        let diagnostic = diagnostics.diagnose_from_response(
            StatusCode::FORBIDDEN,
            &headers,
            "Missing required scope: read:users",
            "oauth2",
        );

        assert_eq!(diagnostic.error_type, AuthErrorType::InsufficientScopes);
        assert!(diagnostic.details.contains("permissions"));
    }

    #[test]
    fn test_extract_scopes() {
        let error = "Error: Missing required scopes: read:users write:posts";
        let scopes = extract_scopes_from_error(error);
        assert_eq!(scopes, Some("read:users write:posts".to_string()));
    }
}