auths-cli 0.1.2

Command-line interface for Auths decentralized identity system
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
//! Comprehensive health check command for Auths.

use crate::adapters::doctor_fixes::GitSigningConfigFix;
use crate::adapters::system_diagnostic::PosixDiagnosticAdapter;
use crate::ux::format::{JsonResponse, Output, is_json_mode};
use anyhow::Result;
use auths_sdk::keychain;
use auths_sdk::ports::diagnostics::{
    CheckCategory, CheckResult, ConfigIssue, DiagnosticFix, FixApplied,
};
use auths_sdk::workflows::diagnostics::DiagnosticsWorkflow;
use chrono::{DateTime, Utc};
use clap::Parser;
use serde::Serialize;
use std::io::IsTerminal;

/// Health check command.
#[derive(Parser, Debug, Clone)]
#[command(
    name = "doctor",
    about = "Run comprehensive health checks",
    after_help = "Examples:
  auths doctor              # Check all health aspects
  auths doctor --fix        # Auto-fix identified issues
  auths doctor --json       # JSON output

Exit Codes:
  0 — All checks pass
  1 — Critical check failed (Auths is non-functional)
  2 — Critical checks pass, advisory checks fail (environment could be better)

Related:
  auths status  — Show identity and device status
  auths init    — Initialize a new identity"
)]
pub struct DoctorCommand {
    /// Auto-fix issues where possible
    #[clap(long)]
    pub fix: bool,
}

/// A single health check.
#[derive(Debug, Serialize)]
pub struct Check {
    name: String,
    passed: bool,
    detail: String,
    suggestion: Option<String>,
    #[serde(skip_serializing_if = "is_advisory")]
    category: CheckCategory,
}

fn is_advisory(cat: &CheckCategory) -> bool {
    *cat == CheckCategory::Advisory
}

/// Overall doctor report.
#[derive(Debug, Serialize)]
pub struct DoctorReport {
    pub version: String,
    pub checks: Vec<Check>,
    pub all_pass: bool,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub fixes_applied: Vec<FixApplied>,
}

/// Handle the doctor command.
pub fn handle_doctor(cmd: DoctorCommand) -> Result<()> {
    let checks = run_checks();
    let all_pass = checks.iter().all(|c| c.passed);

    let (final_checks, fixes_applied) = if cmd.fix && !all_pass {
        let out = if !is_json_mode() {
            Some(Output::new())
        } else {
            None
        };
        let fixes = apply_fixes(&checks, out.as_ref());
        if !fixes.is_empty() {
            let rechecked = run_checks();
            (rechecked, fixes)
        } else {
            (checks, fixes)
        }
    } else {
        (checks, Vec::new())
    };

    let all_pass = final_checks.iter().all(|c| c.passed);

    // Compute exit code based on check categories
    let exit_code = compute_exit_code(&final_checks);

    let report = DoctorReport {
        version: env!("CARGO_PKG_VERSION").to_string(),
        checks: final_checks,
        all_pass,
        fixes_applied,
    };

    if is_json_mode() {
        JsonResponse {
            success: all_pass,
            command: "doctor".to_string(),
            data: Some(report),
            error: if !all_pass {
                Some("some health checks failed".to_string())
            } else {
                None
            },
        }
        .print()?;
    } else {
        print_report(&report);
    }

    if exit_code != 0 {
        std::process::exit(exit_code);
    }

    Ok(())
}

/// Compute exit code based on check categories.
///
/// Returns:
/// * 0 — all checks pass
/// * 1 — at least one Critical check fails (Auths is non-functional)
/// * 2 — all Critical checks pass, at least one Advisory check fails
fn compute_exit_code(checks: &[Check]) -> i32 {
    let critical_failures = checks
        .iter()
        .any(|c| !c.passed && c.category == CheckCategory::Critical);

    if critical_failures {
        return 1;
    }

    let advisory_failures = checks
        .iter()
        .any(|c| !c.passed && c.category == CheckCategory::Advisory);

    if advisory_failures {
        return 2;
    }

    0
}

/// Run all prerequisite checks.
#[allow(clippy::disallowed_methods)] // CLI boundary: Utc::now() injected here
fn run_checks() -> Vec<Check> {
    let now = Utc::now();
    let adapter = PosixDiagnosticAdapter;
    let workflow = DiagnosticsWorkflow::new(&adapter, &adapter);

    let mut checks = Vec::new();

    if let Ok(report) = workflow.run() {
        for cr in report.checks {
            let suggestion = if cr.passed {
                None
            } else {
                suggestion_for_check(&cr.name)
            };
            checks.push(Check {
                name: cr.name.clone(),
                passed: cr.passed,
                detail: format_check_detail(&cr),
                suggestion,
                category: cr.category,
            });
        }
    }

    // Domain checks are all Critical
    checks.push(check_keychain_accessible());
    checks.push(check_auths_repo());
    checks.push(check_identity_valid(now));

    // Advisory: network connectivity
    checks.push(check_registry_connectivity());

    checks
}

fn apply_fixes(checks: &[Check], out: Option<&Output>) -> Vec<FixApplied> {
    let failed: Vec<CheckResult> = checks
        .iter()
        .filter(|c| !c.passed)
        .map(|c| CheckResult {
            name: c.name.clone(),
            passed: c.passed,
            message: Some(c.detail.clone()),
            config_issues: Vec::new(),
            category: c.category,
        })
        .collect();

    let fixes = build_available_fixes();
    let interactive = std::io::stdin().is_terminal();
    let mut applied = Vec::new();

    for fix in &fixes {
        let applicable: Vec<&CheckResult> = failed.iter().filter(|c| fix.can_fix(c)).collect();
        if applicable.is_empty() {
            continue;
        }

        if !fix.is_safe() && !interactive {
            if let Some(o) = out {
                o.print_warn(&format!(
                    "Skipping unsafe fix '{}' (non-interactive mode)",
                    fix.name()
                ));
            }
            continue;
        }

        if !fix.is_safe() && interactive {
            let confirm = dialoguer::Confirm::new()
                .with_prompt(format!(
                    "Apply fix '{}'? (may overwrite existing git config)",
                    fix.name()
                ))
                .default(true)
                .interact()
                .unwrap_or(false);
            if !confirm {
                continue;
            }
        }

        match fix.apply() {
            Ok(message) => {
                if let Some(o) = out {
                    o.print_success(&format!("Fixed: {}", message));
                }
                applied.push(FixApplied {
                    name: fix.name().to_string(),
                    message,
                });
            }
            Err(e) => {
                if let Some(o) = out {
                    o.print_error(&format!("Fix '{}' failed: {}", fix.name(), e));
                }
            }
        }
    }

    applied
}

fn build_available_fixes() -> Vec<Box<dyn DiagnosticFix>> {
    let mut fixes: Vec<Box<dyn DiagnosticFix>> = Vec::new();

    if let Ok(sign_path) = which::which("auths-sign") {
        let key_alias = resolve_key_alias().unwrap_or_else(|| "main".to_string());
        fixes.push(Box::new(GitSigningConfigFix::new(sign_path, key_alias)));
    }

    fixes
}

fn resolve_key_alias() -> Option<String> {
    let keychain = keychain::get_platform_keychain().ok()?;
    let aliases = keychain.list_aliases().ok()?;
    aliases
        .into_iter()
        .find(|a| !a.to_string().contains("--next-"))
        .map(|a| a.to_string())
}

fn format_check_detail(cr: &CheckResult) -> String {
    if !cr.config_issues.is_empty() {
        let parts: Vec<String> = cr
            .config_issues
            .iter()
            .map(|issue| match issue {
                ConfigIssue::Mismatch {
                    key,
                    expected,
                    actual,
                } => {
                    format!("{key} (is '{actual}', expected '{expected}')")
                }
                ConfigIssue::Absent(key) => format!("{key} (not set)"),
            })
            .collect();
        return format!("Missing or wrong: {}", parts.join(", "));
    }
    cr.message.clone().unwrap_or_default()
}

fn suggestion_for_check(name: &str) -> Option<String> {
    match name {
        "Git installed" => {
            Some("Install Git for your platform (see: https://git-scm.com/downloads)".to_string())
        }
        "Git version" => Some(
            "Upgrade Git to 2.34.0+ for SSH signing: https://git-scm.com/downloads".to_string(),
        ),
        "Git user identity" => Some(
            "Run: git config --global user.name \"Your Name\" && git config --global user.email \"you@example.com\"".to_string(),
        ),
        "ssh-keygen installed" => {
            let hint = if cfg!(target_os = "macos") {
                "ssh-keygen is normally pre-installed on macOS. Check your PATH."
            } else if cfg!(target_os = "windows") {
                "Install OpenSSH via Settings > Apps > Optional features, or `winget install Microsoft.OpenSSH.Client`."
            } else {
                "Install OpenSSH: `sudo apt install openssh-client` (Debian/Ubuntu) or `sudo dnf install openssh-clients` (Fedora/RHEL)."
            };
            Some(hint.to_string())
        }
        "SSH version" => Some(
            "Upgrade OpenSSH to 8.2+ for -Y find-principals support. Check with: ssh -V".to_string(),
        ),
        "Git signing config" => Some("Run: auths doctor --fix".to_string()),
        "Auths directory" => Some("Run: auths init --profile developer".to_string()),
        "Allowed signers file" => Some("Run: auths doctor --fix".to_string()),
        "Registry connectivity" => {
            Some("Check your internet connection or try again later.".to_string())
        }
        _ => None,
    }
}

fn check_keychain_accessible() -> Check {
    let (passed, detail, suggestion) = match keychain::get_platform_keychain() {
        Ok(keychain) => (
            true,
            format!("{} (accessible)", keychain.backend_name()),
            None,
        ),
        Err(e) => (
            false,
            format!("inaccessible: {e}"),
            Some("Run: auths init --profile developer".to_string()),
        ),
    };
    Check {
        name: "System keychain".to_string(),
        passed,
        detail,
        suggestion,
        category: CheckCategory::Critical,
    }
}

fn check_auths_repo() -> Check {
    let (passed, detail, suggestion) = match auths_sdk::paths::auths_home() {
        Ok(path) => {
            if !path.exists() {
                (
                    false,
                    format!("{} (not found)", path.display()),
                    Some("Run: auths init --profile developer".to_string()),
                )
            } else {
                match crate::factories::storage::open_git_repo(&path) {
                    Ok(_) => (
                        true,
                        format!("{} (valid git repository)", path.display()),
                        None,
                    ),
                    Err(_) => (
                        false,
                        format!("{} (exists but not a valid git repo)", path.display()),
                        Some("Run: auths init --profile developer".to_string()),
                    ),
                }
            }
        }
        Err(e) => (
            false,
            format!("Cannot resolve path: {e}"),
            Some("Run: auths init --profile developer".to_string()),
        ),
    };
    Check {
        name: "Auths directory".to_string(),
        passed,
        detail,
        suggestion,
        category: CheckCategory::Critical,
    }
}

fn check_identity_valid(now: DateTime<Utc>) -> Check {
    let (passed, detail, suggestion) = match keychain::get_platform_keychain() {
        Ok(keychain) => match keychain.list_aliases() {
            Ok(aliases) if aliases.is_empty() => (
                false,
                "No keys found in keychain".to_string(),
                Some("Run: auths init --profile developer  (or: auths id create)".to_string()),
            ),
            Ok(aliases) => {
                let key_count = aliases.len();
                let expiry_info = check_attestation_expiry(now);
                match expiry_info {
                    ExpiryStatus::AllExpired(msg) => (
                        false,
                        format!("{key_count} key(s) found, but {msg}"),
                        Some("Run: auths device extend".to_string()),
                    ),
                    ExpiryStatus::ExpiringSoon(msg) => {
                        (true, format!("{key_count} key(s) found ({msg})"), None)
                    }
                    ExpiryStatus::Ok | ExpiryStatus::NoAttestations => {
                        (true, format!("{key_count} key(s) found"), None)
                    }
                }
            }
            Err(e) => (
                false,
                format!("Failed to list keys: {e}"),
                Some("Run: auths doctor  (check keychain is accessible first)".to_string()),
            ),
        },
        Err(_) => (
            false,
            "Keychain not accessible".to_string(),
            Some("Run: auths init --profile developer".to_string()),
        ),
    };
    Check {
        name: "Auths identity".to_string(),
        passed,
        detail,
        suggestion,
        category: CheckCategory::Critical,
    }
}

enum ExpiryStatus {
    Ok,
    NoAttestations,
    ExpiringSoon(String),
    AllExpired(String),
}

fn check_attestation_expiry(now: DateTime<Utc>) -> ExpiryStatus {
    use auths_sdk::storage::RegistryAttestationStorage;

    let repo_path = match auths_sdk::paths::auths_home() {
        Ok(p) if p.exists() => p,
        _ => return ExpiryStatus::NoAttestations,
    };

    let storage = RegistryAttestationStorage::new(&repo_path);
    let attestations = match storage
        .load_all_enriched()
        .map(|v| v.into_iter().map(|e| e.attestation).collect::<Vec<_>>())
    {
        Ok(a) => a,
        Err(_) => return ExpiryStatus::NoAttestations,
    };

    if attestations.is_empty() {
        return ExpiryStatus::NoAttestations;
    }

    let active: Vec<_> = attestations
        .iter()
        .filter(|a| a.revoked_at.is_none())
        .collect();

    if active.is_empty() {
        return ExpiryStatus::AllExpired("all attestations revoked".to_string());
    }

    let with_expiry: Vec<_> = active.iter().filter(|a| a.expires_at.is_some()).collect();

    if with_expiry.is_empty() {
        return ExpiryStatus::Ok;
    }

    let all_expired = with_expiry
        .iter()
        .all(|a| a.expires_at.is_some_and(|exp| exp < now));

    if all_expired {
        return ExpiryStatus::AllExpired("all attestations expired".to_string());
    }

    let warn_threshold = now + chrono::Duration::days(7);
    let expiring_soon = with_expiry
        .iter()
        .any(|a| a.expires_at.is_some_and(|exp| exp < warn_threshold));

    if expiring_soon {
        return ExpiryStatus::ExpiringSoon("some attestations expiring within 7 days".to_string());
    }

    ExpiryStatus::Ok
}

fn check_registry_connectivity() -> Check {
    use auths_sdk::registration::DEFAULT_REGISTRY_URL;

    let url = format!("{DEFAULT_REGISTRY_URL}/health");
    let client = reqwest::blocking::Client::builder()
        .timeout(std::time::Duration::from_secs(5))
        .build();

    let (passed, detail) = match client {
        Ok(client) => match client.get(&url).send() {
            Ok(resp) if resp.status().is_success() => {
                (true, format!("{DEFAULT_REGISTRY_URL} (reachable)"))
            }
            Ok(resp) => (
                false,
                format!("{DEFAULT_REGISTRY_URL} (HTTP {})", resp.status()),
            ),
            Err(e) => (false, format!("unreachable: {e}")),
        },
        Err(e) => (false, format!("HTTP client error: {e}")),
    };

    Check {
        name: "Registry connectivity".to_string(),
        passed,
        detail,
        suggestion: if passed {
            None
        } else {
            suggestion_for_check("Registry connectivity")
        },
        category: CheckCategory::Advisory,
    }
}

/// Print the report in human-readable format.
fn print_report(report: &DoctorReport) {
    let out = Output::new();

    out.print_heading(&format!("Auths Doctor (v{})", report.version));
    out.println("--------------------------");
    out.newline();

    for check in &report.checks {
        let (icon, name_styled) = if check.passed {
            (out.success(""), out.bold(&check.name))
        } else {
            (out.error(""), out.error(&check.name))
        };

        out.println(&format!("[{icon}] {name_styled}: {}", check.detail));

        if let Some(ref suggestion) = check.suggestion {
            out.println(&format!("      -> {}", out.dim(suggestion)));
        }
    }

    if !report.fixes_applied.is_empty() {
        out.newline();
        out.print_heading("Fixes applied:");
        for fix in &report.fixes_applied {
            out.println(&format!("  {}{}", out.success(&fix.name), fix.message));
        }
    }

    out.newline();

    let passed_count = report.checks.iter().filter(|c| c.passed).count();
    let failed_count = report.checks.len() - passed_count;

    let summary = format!(
        "Summary: {} passed, {} failed",
        out.success(&passed_count.to_string()),
        out.error(&failed_count.to_string())
    );
    out.println(&summary);
    out.newline();

    if report.all_pass {
        out.print_success("All checks passed! Your system is ready.");
    } else {
        out.print_error("Some checks failed. Please review the suggestions above.");
    }
}

impl crate::commands::executable::ExecutableCommand for DoctorCommand {
    fn execute(&self, _ctx: &crate::config::CliConfig) -> anyhow::Result<()> {
        handle_doctor(self.clone())
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_keychain_check_suggestion_is_exact_command() {
        let suggestion = "Run: auths init --profile developer";
        assert!(
            suggestion.starts_with("Run:"),
            "suggestion must start with 'Run:'"
        );
    }

    #[test]
    fn test_workflow_includes_version_and_user_checks() {
        use super::*;
        let adapter = PosixDiagnosticAdapter;
        let workflow = DiagnosticsWorkflow::new(&adapter, &adapter);
        let report = workflow.run().unwrap();

        let check_names: Vec<&str> = report.checks.iter().map(|c| c.name.as_str()).collect();
        assert!(
            check_names.contains(&"Git signing config"),
            "signing config check must exist"
        );
        assert!(
            check_names.contains(&"Git version"),
            "git version check must exist"
        );
        assert!(
            check_names.contains(&"Git user identity"),
            "git user identity check must exist"
        );
    }

    #[test]
    fn test_all_failed_checks_have_exact_runnable_suggestions() {
        let suggestions: Vec<Option<String>> = vec![
            Some("Run: auths init --profile developer".to_string()),
            Some("Run: auths id init".to_string()),
            Some("Run: git config --global gpg.format ssh".to_string()),
            Some("Run: auths init --profile developer".to_string()),
        ];
        for text in suggestions.into_iter().flatten() {
            assert!(text.starts_with("Run:"), "bad suggestion: {}", text);
        }
    }

    #[test]
    fn test_suggestion_for_all_new_checks() {
        use super::suggestion_for_check;
        assert!(suggestion_for_check("Git version").is_some());
        assert!(suggestion_for_check("Git user identity").is_some());
        assert!(suggestion_for_check("Auths directory").is_some());
        assert!(suggestion_for_check("Registry connectivity").is_some());
    }
}