Skip to main content

auths_cli/errors/
renderer.rs

1use anyhow::Error;
2use auths_sdk::domains::signing::service::{ArtifactSigningError, SigningError};
3use auths_sdk::error::CoreTrustError;
4use auths_sdk::error::IdDriverStorageError;
5use auths_sdk::error::IdStorageError;
6use auths_sdk::error::PairingError;
7use auths_sdk::error::{AgentError, AuthsErrorInfo};
8use auths_sdk::error::{
9    ApprovalError, DeviceError, DeviceExtensionError, McpAuthError, OrgError, RegistrationError,
10    RotationError, SdkStorageError, SetupError, TrustError,
11};
12use auths_sdk::error::{FreezeError, InitError};
13use auths_sdk::workflows::auth::AuthChallengeError;
14use auths_verifier::{AttestationError, CommitVerificationError};
15use colored::Colorize;
16
17use crate::errors::cli_error::CliError;
18use crate::ux::format::Output;
19
20const DOCS_BASE_URL: &str = "https://docs.auths.dev";
21
22/// Render an error to stderr in either text or JSON format.
23///
24/// Args:
25/// * `err`: The error to render.
26/// * `json_mode`: If `true`, output structured JSON; otherwise styled text.
27pub fn render_error(err: &Error, json_mode: bool) {
28    if json_mode {
29        render_json(err);
30    } else {
31        render_text(err);
32    }
33}
34
35/// Try to extract `AuthsErrorInfo` from an `anyhow::Error` by downcasting
36/// through all known error types. Walks the full error chain so that
37/// `.with_context()` wrapping doesn't hide typed errors.
38fn extract_error_info(err: &Error) -> Option<(&str, &str, Option<&str>)> {
39    macro_rules! try_downcast {
40        ($source:expr, $($ty:ty),+ $(,)?) => {
41            $(
42                if let Some(e) = $source.downcast_ref::<$ty>() {
43                    let code = AuthsErrorInfo::error_code(e);
44                    let msg = format!("{e}");
45                    // SAFETY: we leak the String to get a &'static str because
46                    // the caller consumes it immediately in the same scope.
47                    // This is bounded to a single error render per invocation.
48                    let msg: &str = Box::leak(msg.into_boxed_str());
49                    return Some((code, msg, AuthsErrorInfo::suggestion(e)));
50                }
51            )+
52        };
53    }
54
55    for cause in err.chain() {
56        try_downcast!(
57            cause,
58            AgentError,
59            AttestationError,
60            SetupError,
61            DeviceError,
62            DeviceExtensionError,
63            RotationError,
64            RegistrationError,
65            McpAuthError,
66            OrgError,
67            ApprovalError,
68            ArtifactSigningError,
69            SigningError,
70            SdkStorageError,
71            TrustError,
72            AuthChallengeError,
73            CommitVerificationError,
74            PairingError,
75            FreezeError,
76            InitError,
77            CoreTrustError,
78            IdStorageError,
79            IdDriverStorageError,
80        );
81    }
82
83    None
84}
85
86fn render_text(err: &Error) {
87    let out = Output::new();
88
89    if let Some(cli_err) = err.downcast_ref::<CliError>() {
90        eprintln!("\n{} {}", "Error:".red().bold(), cli_err);
91        eprintln!("\n{}", cli_err.suggestion());
92        if let Some(url) = cli_err.docs_url() {
93            eprintln!("Docs: {}", url);
94        }
95        eprintln!();
96        return;
97    }
98
99    if let Some((code, message, suggestion)) = extract_error_info(err) {
100        let prefix = format!("[{code}]").yellow();
101        out.print_error(&format!("{prefix} {}", out.bold(message)));
102        eprintln!();
103        if let Some(suggestion) = suggestion {
104            eprintln!("  fix:  {}", suggestion.blue());
105        }
106        if let Some(url) = docs_url(code) {
107            eprintln!("  docs: {url}");
108        }
109        return;
110    }
111
112    // Fallback for generic anyhow::Error
113    let msg = err.to_string();
114    let suggestion = match msg.as_str() {
115        s if s.contains("No identity found") => Some(format!(
116            "Run `auths init` to create one, or `auths key import` to restore from a backup.\n     See: {DOCS_BASE_URL}/getting-started/quickstart/"
117        )),
118        s if s.contains("keychain") || s.contains("Secret Service") => Some(format!(
119            "Cannot access system keychain.\n\n     If running headless (CI/Docker), set:\n       export AUTHS_KEYCHAIN_BACKEND=file\n       export AUTHS_PASSPHRASE=<your-passphrase>\n\n     See: {DOCS_BASE_URL}/cli/troubleshooting/"
120        )),
121        s if s.contains("ssh-keygen") && s.contains("not found") => Some(
122            "ssh-keygen not found on PATH.\n\n     Install OpenSSH:\n       Ubuntu: sudo apt install openssh-client\n       macOS:  ssh-keygen is pre-installed\n       Windows: Install OpenSSH via Settings > Apps > Optional features".to_string()
123        ),
124        s if s.contains("not a git repository") => Some(
125            "This command must be run inside a Git repository.\nRun `git init` first, or navigate to an existing repo.".to_string()
126        ),
127        s if s.contains("permission denied") || s.contains("Permission denied") => Some(format!(
128            "Permission denied. Check file permissions on the relevant path.\n     Run `auths doctor` for a full health check.\n     See: {DOCS_BASE_URL}/cli/troubleshooting/"
129        )),
130        s if s.contains("connection refused") || s.contains("timed out") || s.contains("timeout") => Some(
131            "Network connection failed. Check your internet connection and try again.\nIf using a registry, verify the URL with `auths config show`.".to_string()
132        ),
133        _ => None,
134    };
135
136    if let Some(suggestion) = suggestion {
137        out.print_error(&msg);
138        eprintln!("\n{suggestion}");
139    } else {
140        out.print_error(&format!("{err}"));
141        for cause in err.chain().skip(1) {
142            eprintln!("  caused by: {cause}");
143        }
144        eprintln!(
145            "\nhint: Run 'auths doctor' to check your setup, or 'auths error list' to browse known issues."
146        );
147    }
148}
149
150fn render_json(err: &Error) {
151    let json = if let Some(cli_err) = err.downcast_ref::<CliError>() {
152        build_json(
153            None,
154            &format!("{cli_err}"),
155            Some(cli_err.suggestion()),
156            cli_err.docs_url().map(|s| s.to_string()),
157        )
158    } else if let Some((code, message, suggestion)) = extract_error_info(err) {
159        build_json(Some(code), message, suggestion, docs_url(code))
160    } else {
161        build_json(None, &format!("{err}"), None, None)
162    };
163
164    eprintln!("{json}");
165}
166
167fn build_json(
168    code: Option<&str>,
169    message: &str,
170    suggestion: Option<&str>,
171    docs: Option<String>,
172) -> String {
173    let mut map = serde_json::Map::new();
174    if let Some(c) = code {
175        map.insert("code".into(), serde_json::Value::String(c.into()));
176    }
177    map.insert("message".into(), serde_json::Value::String(message.into()));
178    if let Some(s) = suggestion {
179        map.insert("suggestion".into(), serde_json::Value::String(s.into()));
180    }
181    if let Some(d) = docs {
182        map.insert("docs".into(), serde_json::Value::String(d));
183    }
184
185    let wrapper = serde_json::json!({ "error": map });
186    serde_json::to_string_pretty(&wrapper)
187        .unwrap_or_else(|_| format!("{{\"error\":{{\"message\":\"{message}\"}}}}"))
188}
189
190fn docs_url(code: &str) -> Option<String> {
191    if code.starts_with("AUTHS-E") {
192        Some(format!("{DOCS_BASE_URL}/errors/#{code}"))
193    } else {
194        None
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    #[test]
203    fn docs_url_returns_some_for_known_codes() {
204        let url = docs_url("AUTHS-E3001");
205        assert_eq!(url, Some(format!("{DOCS_BASE_URL}/errors/#AUTHS-E3001")));
206    }
207
208    #[test]
209    fn docs_url_returns_none_for_unknown_codes() {
210        assert!(docs_url("UNKNOWN").is_none());
211        assert!(docs_url("SOME_OTHER").is_none());
212    }
213
214    #[test]
215    fn build_json_with_all_fields() {
216        let json = build_json(
217            Some("AUTHS-E3001"),
218            "Key not found",
219            Some("Run `auths key list`"),
220            Some(format!("{DOCS_BASE_URL}/errors/#AUTHS-E3001")),
221        );
222        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
223        assert_eq!(parsed["error"]["code"], "AUTHS-E3001");
224        assert_eq!(parsed["error"]["message"], "Key not found");
225        assert_eq!(parsed["error"]["suggestion"], "Run `auths key list`");
226        assert!(
227            parsed["error"]["docs"]
228                .as_str()
229                .unwrap()
230                .contains("AUTHS-E3001")
231        );
232    }
233
234    #[test]
235    fn build_json_without_optional_fields() {
236        let json = build_json(None, "Something went wrong", None, None);
237        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
238        assert_eq!(parsed["error"]["message"], "Something went wrong");
239        assert!(parsed["error"].get("code").is_none());
240        assert!(parsed["error"].get("suggestion").is_none());
241        assert!(parsed["error"].get("docs").is_none());
242    }
243
244    #[test]
245    fn render_error_agent_error_text() {
246        let err = Error::new(AgentError::KeyNotFound);
247        render_error(&err, false);
248    }
249
250    #[test]
251    fn render_error_agent_error_json() {
252        let err = Error::new(AgentError::KeyNotFound);
253        render_error(&err, true);
254    }
255
256    #[test]
257    fn render_error_attestation_error_text() {
258        let err = Error::new(AttestationError::IssuerSignatureFailed("bad sig".into()));
259        render_error(&err, false);
260    }
261
262    #[test]
263    fn render_error_unknown_error_text() {
264        let err = anyhow::anyhow!("something unexpected");
265        render_error(&err, false);
266    }
267
268    #[test]
269    fn render_error_unknown_error_json() {
270        let err = anyhow::anyhow!("something unexpected");
271        render_error(&err, true);
272    }
273
274    #[test]
275    fn extract_error_info_returns_code_for_agent_error() {
276        let err = Error::new(AgentError::KeyNotFound);
277        let (code, _, suggestion) = extract_error_info(&err).unwrap();
278        assert_eq!(code, "AUTHS-E3001");
279        assert!(suggestion.is_some());
280    }
281
282    #[test]
283    fn extract_error_info_walks_chain_through_context() {
284        let err: Error = Error::new(AgentError::KeyNotFound).context("operation failed");
285        let (code, _, _) = extract_error_info(&err).unwrap();
286        assert_eq!(code, "AUTHS-E3001");
287    }
288
289    #[test]
290    fn setup_error_storage_delegates_to_inner_code() {
291        let inner = IdStorageError::NotFound("test".into());
292        let sdk_err = auths_sdk::error::SdkStorageError::Identity(inner);
293        let setup_err = SetupError::StorageError(sdk_err);
294        let err = Error::new(setup_err);
295        let (code, _, suggestion) = extract_error_info(&err).unwrap();
296        assert_eq!(code, "AUTHS-E4104");
297        assert!(suggestion.is_some());
298    }
299
300    #[test]
301    fn setup_error_registration_delegates_to_inner_code() {
302        let reg_err = RegistrationError::AlreadyRegistered;
303        let setup_err = SetupError::RegistrationFailed(reg_err);
304        let err = Error::new(setup_err);
305        let (code, _, suggestion) = extract_error_info(&err).unwrap();
306        assert_eq!(code, "AUTHS-E5401");
307        assert!(suggestion.is_some());
308    }
309}