nblm_core/doctor/
checks.rs

1use colored::Colorize;
2use std::env;
3
4use crate::auth::{ensure_drive_scope, EnvTokenProvider};
5use crate::error::Error;
6
7/// Status of a diagnostic check
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum CheckStatus {
10    Pass,
11    Warning,
12    Error,
13}
14
15impl CheckStatus {
16    /// Convert status to exit code contribution
17    pub fn exit_code(&self) -> i32 {
18        match self {
19            CheckStatus::Pass => 0,
20            CheckStatus::Warning => 1,
21            CheckStatus::Error => 2,
22        }
23    }
24
25    /// Convert status to ASCII marker with aligned label
26    pub fn as_marker(&self) -> String {
27        let label = match self {
28            CheckStatus::Pass => "ok",
29            CheckStatus::Warning => "warn",
30            CheckStatus::Error => "error",
31        };
32        let total_width = "error".len() + 2; // include brackets
33        format!("{:>width$}", format!("[{}]", label), width = total_width)
34    }
35
36    /// Convert status to colored marker using the colored crate
37    pub fn as_marker_colored(&self) -> String {
38        let marker = self.as_marker();
39        match self {
40            CheckStatus::Pass => marker.green(),
41            CheckStatus::Warning => marker.yellow(),
42            CheckStatus::Error => marker.red(),
43        }
44        .to_string()
45    }
46}
47
48/// Result of a single diagnostic check
49#[derive(Debug, Clone)]
50pub struct CheckResult {
51    pub name: String,
52    pub status: CheckStatus,
53    pub message: String,
54    pub suggestion: Option<String>,
55}
56
57impl CheckResult {
58    pub fn new(name: impl Into<String>, status: CheckStatus, message: impl Into<String>) -> Self {
59        Self {
60            name: name.into(),
61            status,
62            message: message.into(),
63            suggestion: None,
64        }
65    }
66
67    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
68        self.suggestion = Some(suggestion.into());
69        self
70    }
71
72    /// Format check result for display
73    pub fn format(&self) -> String {
74        self.format_with_marker(self.status.as_marker())
75    }
76
77    /// Format check result for display with colored markers
78    pub fn format_colored(&self) -> String {
79        self.format_with_marker(self.status.as_marker_colored())
80    }
81
82    fn format_with_marker(&self, marker: String) -> String {
83        let mut output = format!("{} {}", marker, self.message);
84        if let Some(suggestion) = &self.suggestion {
85            output.push_str(&format!("\n       Suggestion: {}", suggestion));
86        }
87        output
88    }
89}
90
91/// Summary of all diagnostic checks
92#[derive(Debug)]
93pub struct DiagnosticsSummary {
94    pub checks: Vec<CheckResult>,
95}
96
97impl DiagnosticsSummary {
98    pub fn new(checks: Vec<CheckResult>) -> Self {
99        Self { checks }
100    }
101
102    /// Calculate the overall exit code
103    pub fn exit_code(&self) -> i32 {
104        self.checks
105            .iter()
106            .map(|check| check.status.exit_code())
107            .max()
108            .unwrap_or(0)
109    }
110
111    /// Count checks by status
112    pub fn count_by_status(&self, status: CheckStatus) -> usize {
113        self.checks
114            .iter()
115            .filter(|check| check.status == status)
116            .count()
117    }
118
119    /// Format summary for display
120    pub fn format_summary(&self) -> String {
121        let total = self.checks.len();
122        let failed =
123            self.count_by_status(CheckStatus::Error) + self.count_by_status(CheckStatus::Warning);
124
125        if failed == 0 {
126            format!("\nSummary: All {} checks passed.", total)
127        } else {
128            format!(
129                "\nSummary: {} checks failing out of {}. See above for details.",
130                failed, total
131            )
132        }
133    }
134
135    /// Format summary for display with color
136    pub fn format_summary_colored(&self) -> String {
137        let total = self.checks.len();
138        let failed =
139            self.count_by_status(CheckStatus::Error) + self.count_by_status(CheckStatus::Warning);
140
141        if failed == 0 {
142            format!(
143                "\n{}",
144                format!("Summary: All {} checks passed.", total).green()
145            )
146        } else {
147            format!(
148                "\n{}",
149                format!(
150                    "Summary: {} checks failing out of {}. See above for details.",
151                    failed, total
152                )
153                .yellow()
154            )
155        }
156    }
157}
158
159/// Configuration for an environment variable check
160pub struct EnvVarCheck {
161    pub name: &'static str,
162    pub required: bool,
163    pub suggestion: &'static str,
164    pub show_value: bool,
165}
166
167/// Static configuration table for environment variable checks
168const ENV_VAR_CHECKS: &[EnvVarCheck] = &[
169    EnvVarCheck {
170        name: "NBLM_PROJECT_NUMBER",
171        required: true,
172        suggestion: "export NBLM_PROJECT_NUMBER=<your-project-number>",
173        show_value: true,
174    },
175    EnvVarCheck {
176        name: "NBLM_ENDPOINT_LOCATION",
177        required: false,
178        suggestion: "export NBLM_ENDPOINT_LOCATION=us-central1",
179        show_value: true,
180    },
181    EnvVarCheck {
182        name: "NBLM_LOCATION",
183        required: false,
184        suggestion: "export NBLM_LOCATION=us-central1",
185        show_value: true,
186    },
187    EnvVarCheck {
188        name: "NBLM_ACCESS_TOKEN",
189        required: false,
190        suggestion: "export NBLM_ACCESS_TOKEN=$(gcloud auth print-access-token)",
191        show_value: false,
192    },
193];
194
195/// Check a single environment variable
196fn check_env_var(config: &EnvVarCheck) -> CheckResult {
197    match env::var(config.name) {
198        Ok(value) if !value.is_empty() => {
199            let message = if config.show_value {
200                format!("{}={}", config.name, value)
201            } else {
202                format!("{} set (value hidden)", config.name)
203            };
204            CheckResult::new(
205                format!("env_var_{}", config.name.to_lowercase()),
206                CheckStatus::Pass,
207                message,
208            )
209        }
210        Ok(_) | Err(env::VarError::NotPresent) => {
211            let status = if config.required {
212                CheckStatus::Error
213            } else {
214                CheckStatus::Warning
215            };
216            CheckResult::new(
217                format!("env_var_{}", config.name.to_lowercase()),
218                status,
219                format!("{} missing", config.name),
220            )
221            .with_suggestion(config.suggestion)
222        }
223        Err(env::VarError::NotUnicode(_)) => CheckResult::new(
224            format!("env_var_{}", config.name.to_lowercase()),
225            CheckStatus::Error,
226            format!("{} contains invalid UTF-8", config.name),
227        ),
228    }
229}
230
231/// Run all environment variable checks
232pub fn check_environment_variables() -> Vec<CheckResult> {
233    ENV_VAR_CHECKS.iter().map(check_env_var).collect()
234}
235
236/// Configuration for a command availability check
237pub struct CommandCheck {
238    pub name: &'static str,
239    pub command: &'static str,
240    pub required: bool,
241    pub suggestion: &'static str,
242}
243
244/// Static configuration table for command checks
245const COMMAND_CHECKS: &[CommandCheck] = &[CommandCheck {
246    name: "gcloud",
247    command: "gcloud",
248    required: false,
249    suggestion: "Install Google Cloud CLI: https://cloud.google.com/sdk/docs/install",
250}];
251
252/// Check if a command is available in PATH
253fn check_command(config: &CommandCheck) -> CheckResult {
254    let status = std::process::Command::new(config.command)
255        .arg("--version")
256        .output();
257
258    match status {
259        Ok(output) if output.status.success() => {
260            let version = String::from_utf8_lossy(&output.stdout);
261            let version_line = version.lines().next().unwrap_or("").trim();
262            CheckResult::new(
263                format!("command_{}", config.name),
264                CheckStatus::Pass,
265                format!("{} is installed ({})", config.name, version_line),
266            )
267        }
268        _ => {
269            let status = if config.required {
270                CheckStatus::Error
271            } else {
272                CheckStatus::Warning
273            };
274            CheckResult::new(
275                format!("command_{}", config.name),
276                status,
277                format!("{} command not found", config.name),
278            )
279            .with_suggestion(config.suggestion)
280        }
281    }
282}
283
284/// Run all command availability checks
285pub fn check_commands() -> Vec<CheckResult> {
286    COMMAND_CHECKS.iter().map(check_command).collect()
287}
288
289/// Validate that `NBLM_ACCESS_TOKEN`, when present, grants Google Drive access.
290pub async fn check_drive_access_token() -> Vec<CheckResult> {
291    match env::var("NBLM_ACCESS_TOKEN") {
292        Ok(value) if !value.trim().is_empty() => {
293            let provider = EnvTokenProvider::new("NBLM_ACCESS_TOKEN");
294            match ensure_drive_scope(&provider).await {
295                Ok(_) => vec![CheckResult::new(
296                    "drive_scope_nblm_access_token",
297                    CheckStatus::Pass,
298                    "NBLM_ACCESS_TOKEN grants Google Drive access",
299                )],
300                Err(Error::TokenProvider(message)) => {
301                    if message.contains("missing the required drive.file scope") {
302                        vec![CheckResult::new(
303                            "drive_scope_nblm_access_token",
304                            CheckStatus::Warning,
305                            "NBLM_ACCESS_TOKEN lacks Google Drive scope",
306                        )
307                        .with_suggestion(
308                            "Run `gcloud auth login --enable-gdrive-access` and refresh NBLM_ACCESS_TOKEN",
309                        )]
310                    } else {
311                        vec![CheckResult::new(
312                            "drive_scope_nblm_access_token",
313                            CheckStatus::Warning,
314                            format!(
315                                "Could not confirm Google Drive scope for NBLM_ACCESS_TOKEN: {}",
316                                message
317                            ),
318                        )]
319                    }
320                }
321                Err(err) => vec![CheckResult::new(
322                    "drive_scope_nblm_access_token",
323                    CheckStatus::Warning,
324                    format!(
325                        "Could not confirm Google Drive scope for NBLM_ACCESS_TOKEN: {}",
326                        err
327                    ),
328                )],
329            }
330        }
331        _ => Vec::new(),
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338    use serial_test::serial;
339    use wiremock::matchers::{method, path, query_param};
340    use wiremock::{Mock, MockServer, ResponseTemplate};
341
342    struct EnvGuard {
343        key: &'static str,
344        original: Option<String>,
345    }
346
347    impl EnvGuard {
348        fn new(key: &'static str) -> Self {
349            let original = env::var(key).ok();
350            Self { key, original }
351        }
352    }
353
354    impl Drop for EnvGuard {
355        fn drop(&mut self) {
356            if let Some(value) = &self.original {
357                env::set_var(self.key, value);
358            } else {
359                env::remove_var(self.key);
360            }
361        }
362    }
363
364    #[test]
365    fn test_check_status_markers() {
366        assert_eq!(CheckStatus::Pass.as_marker(), "   [ok]");
367        assert_eq!(CheckStatus::Warning.as_marker(), " [warn]");
368        assert_eq!(CheckStatus::Error.as_marker(), "[error]");
369    }
370
371    #[test]
372    fn test_check_status_colored_markers() {
373        // Force colored output in tests (OK if target ignores it)
374        colored::control::set_override(true);
375
376        // Verify colored markers still include status labels
377        let ok = CheckStatus::Pass.as_marker_colored();
378        assert!(ok.contains("[ok]"));
379
380        let warn = CheckStatus::Warning.as_marker_colored();
381        assert!(warn.contains("[warn]"));
382
383        let err = CheckStatus::Error.as_marker_colored();
384        assert!(err.contains("[error]"));
385
386        // Reset override
387        colored::control::unset_override();
388    }
389
390    #[test]
391    fn test_check_status_exit_codes() {
392        assert_eq!(CheckStatus::Pass.exit_code(), 0);
393        assert_eq!(CheckStatus::Warning.exit_code(), 1);
394        assert_eq!(CheckStatus::Error.exit_code(), 2);
395    }
396
397    #[test]
398    fn test_check_result_format() {
399        let result = CheckResult::new("test", CheckStatus::Pass, "Test passed");
400        assert_eq!(result.format(), "   [ok] Test passed");
401
402        let result_with_suggestion = CheckResult::new("test", CheckStatus::Warning, "Test warning")
403            .with_suggestion("Try this fix");
404        assert!(result_with_suggestion.format().contains("Suggestion:"));
405    }
406
407    #[test]
408    fn test_check_result_format_colored() {
409        // Force colored output in tests
410        colored::control::set_override(true);
411
412        let result = CheckResult::new("test", CheckStatus::Pass, "Test passed");
413        let colored = result.format_colored();
414        assert!(colored.contains("\x1b["));
415        assert!(colored.contains("Test passed"));
416        assert!(colored.ends_with("Test passed"));
417
418        // Reset override
419        colored::control::unset_override();
420    }
421
422    #[test]
423    fn test_diagnostics_summary_exit_code() {
424        let summary = DiagnosticsSummary::new(vec![
425            CheckResult::new("test1", CheckStatus::Pass, "Pass"),
426            CheckResult::new("test2", CheckStatus::Pass, "Pass"),
427        ]);
428        assert_eq!(summary.exit_code(), 0);
429
430        let summary = DiagnosticsSummary::new(vec![
431            CheckResult::new("test1", CheckStatus::Pass, "Pass"),
432            CheckResult::new("test2", CheckStatus::Warning, "Warning"),
433        ]);
434        assert_eq!(summary.exit_code(), 1);
435
436        let summary = DiagnosticsSummary::new(vec![
437            CheckResult::new("test1", CheckStatus::Pass, "Pass"),
438            CheckResult::new("test2", CheckStatus::Error, "Error"),
439        ]);
440        assert_eq!(summary.exit_code(), 2);
441    }
442
443    #[test]
444    fn test_check_env_var_present() {
445        env::set_var("TEST_VAR", "test_value");
446        let config = EnvVarCheck {
447            name: "TEST_VAR",
448            required: true,
449            suggestion: "export TEST_VAR=value",
450            show_value: true,
451        };
452        let result = check_env_var(&config);
453        assert_eq!(result.status, CheckStatus::Pass);
454        assert!(result.message.contains("test_value"));
455        env::remove_var("TEST_VAR");
456    }
457
458    #[test]
459    fn test_check_env_var_missing_required() {
460        env::remove_var("MISSING_VAR");
461        let config = EnvVarCheck {
462            name: "MISSING_VAR",
463            required: true,
464            suggestion: "export MISSING_VAR=value",
465            show_value: true,
466        };
467        let result = check_env_var(&config);
468        assert_eq!(result.status, CheckStatus::Error);
469        assert!(result.message.contains("missing"));
470        assert!(result.suggestion.is_some());
471    }
472
473    #[test]
474    fn test_check_env_var_missing_optional() {
475        env::remove_var("OPTIONAL_VAR");
476        let config = EnvVarCheck {
477            name: "OPTIONAL_VAR",
478            required: false,
479            suggestion: "export OPTIONAL_VAR=value",
480            show_value: true,
481        };
482        let result = check_env_var(&config);
483        assert_eq!(result.status, CheckStatus::Warning);
484        assert!(result.message.contains("missing"));
485    }
486
487    #[test]
488    fn test_check_command_not_found() {
489        let config = CommandCheck {
490            name: "nonexistent_command_xyz",
491            command: "nonexistent_command_xyz",
492            required: false,
493            suggestion: "Install the command",
494        };
495        let result = check_command(&config);
496        assert_eq!(result.status, CheckStatus::Warning);
497        assert!(result.message.contains("not found"));
498        assert!(result.suggestion.is_some());
499    }
500
501    #[test]
502    fn test_check_command_required_not_found() {
503        let config = CommandCheck {
504            name: "nonexistent_required",
505            command: "nonexistent_required",
506            required: true,
507            suggestion: "Install the command",
508        };
509        let result = check_command(&config);
510        assert_eq!(result.status, CheckStatus::Error);
511        assert!(result.message.contains("not found"));
512    }
513
514    #[tokio::test]
515    #[serial]
516    async fn test_drive_access_check_passes_with_valid_scope() {
517        let token_guard = EnvGuard::new("NBLM_ACCESS_TOKEN");
518        let endpoint_guard = EnvGuard::new("NBLM_TOKENINFO_ENDPOINT");
519
520        env::set_var("NBLM_ACCESS_TOKEN", "test-token");
521
522        let server = MockServer::start().await;
523        let tokeninfo_url = format!("{}/tokeninfo", server.uri());
524        env::set_var("NBLM_TOKENINFO_ENDPOINT", &tokeninfo_url);
525
526        Mock::given(method("GET"))
527            .and(path("/tokeninfo"))
528            .and(query_param("access_token", "test-token"))
529            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
530                "scope": "https://www.googleapis.com/auth/drive.file"
531            })))
532            .expect(1)
533            .mount(&server)
534            .await;
535
536        let results = check_drive_access_token().await;
537        assert_eq!(results.len(), 1);
538        assert_eq!(results[0].status, CheckStatus::Pass);
539        assert!(results[0].message.contains("grants Google Drive access"));
540
541        drop(token_guard);
542        drop(endpoint_guard);
543    }
544
545    #[tokio::test]
546    #[serial]
547    async fn test_drive_access_check_reports_missing_scope() {
548        let token_guard = EnvGuard::new("NBLM_ACCESS_TOKEN");
549        let endpoint_guard = EnvGuard::new("NBLM_TOKENINFO_ENDPOINT");
550
551        env::set_var("NBLM_ACCESS_TOKEN", "test-token");
552
553        let server = MockServer::start().await;
554        let tokeninfo_url = format!("{}/tokeninfo", server.uri());
555        env::set_var("NBLM_TOKENINFO_ENDPOINT", &tokeninfo_url);
556
557        Mock::given(method("GET"))
558            .and(path("/tokeninfo"))
559            .and(query_param("access_token", "test-token"))
560            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
561                "scope": "https://www.googleapis.com/auth/cloud-platform"
562            })))
563            .expect(1)
564            .mount(&server)
565            .await;
566
567        let results = check_drive_access_token().await;
568        assert_eq!(results.len(), 1);
569        assert_eq!(results[0].status, CheckStatus::Warning);
570        assert!(results[0].message.contains("lacks Google Drive scope"));
571
572        drop(token_guard);
573        drop(endpoint_guard);
574    }
575}