Skip to main content

secretscout/
error.rs

1//! Error types for SecretScout
2//!
3//! This module defines a comprehensive error hierarchy using thiserror,
4//! with WASM-compatible serialization and proper severity levels.
5
6#[cfg(feature = "wasm")]
7use serde::{Deserialize, Serialize};
8
9/// Error severity levels for proper error handling
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11#[cfg_attr(feature = "wasm", derive(Serialize, Deserialize))]
12pub enum ErrorSeverity {
13    /// Fatal errors that should cause immediate exit with code 1
14    Fatal,
15    /// Non-fatal errors that should be logged as warnings and allow continuation
16    NonFatal,
17    /// Expected errors that represent normal flow control (e.g., no commits to scan)
18    Expected,
19}
20
21/// Root error type for the entire application
22#[derive(thiserror::Error, Debug)]
23#[cfg_attr(feature = "wasm", derive(Serialize, Deserialize))]
24pub enum Error {
25    #[error("Configuration error: {0}")]
26    Config(#[from] ConfigError),
27
28    #[error("Event processing error: {0}")]
29    Event(#[from] EventError),
30
31    #[error("Binary management error: {0}")]
32    Binary(#[from] BinaryError),
33
34    #[error("SARIF processing error: {0}")]
35    Sarif(#[from] SarifError),
36
37    #[error("GitHub API error: {0}")]
38    GitHub(#[from] GitHubError),
39
40    #[error("I/O error: {0}")]
41    Io(String),
42
43    #[error("JSON error: {0}")]
44    Json(String),
45
46    #[error("HTTP error: {0}")]
47    Http(String),
48
49    #[error("License validation error: {0}")]
50    License(String),
51
52    #[error("Unknown error: {0}")]
53    Unknown(String),
54}
55
56/// Configuration-related errors
57#[derive(thiserror::Error, Debug)]
58#[cfg_attr(feature = "wasm", derive(Serialize, Deserialize))]
59pub enum ConfigError {
60    #[error("Missing required environment variable: {0}")]
61    MissingEnvVar(String),
62
63    #[error("Invalid environment variable value for {key}: {value}")]
64    InvalidEnvVar { key: String, value: String },
65
66    #[error("Invalid boolean value: {0} (expected 'true', 'false', '0', or '1')")]
67    InvalidBoolean(String),
68
69    #[error("Invalid git reference: {0}")]
70    InvalidGitRef(String),
71
72    #[error("Invalid file path: {0}")]
73    InvalidPath(String),
74
75    #[error("File not found: {0}")]
76    FileNotFound(String),
77
78    #[error("Path traversal detected: {0}")]
79    PathTraversal(String),
80
81    #[error("Path outside workspace: {0}")]
82    OutsideWorkspace(String),
83
84    #[error("Invalid repository format: {0} (expected 'owner/repo')")]
85    InvalidRepository(String),
86}
87
88/// Event processing errors
89#[derive(thiserror::Error, Debug)]
90#[cfg_attr(feature = "wasm", derive(Serialize, Deserialize))]
91pub enum EventError {
92    #[error("Unsupported event type: {0}")]
93    UnsupportedEvent(String),
94
95    #[error("Invalid event JSON: {0}")]
96    InvalidEventJson(String),
97
98    #[error("Missing required field in event: {0}")]
99    MissingField(String),
100
101    #[error("No commits found in event")]
102    NoCommits,
103
104    #[error("Failed to fetch PR commits: {0}")]
105    FetchPRCommits(String),
106
107    #[error("Invalid PR number: {0}")]
108    InvalidPRNumber(i64),
109}
110
111/// Binary management errors
112#[derive(thiserror::Error, Debug)]
113#[cfg_attr(feature = "wasm", derive(Serialize, Deserialize))]
114pub enum BinaryError {
115    #[error("Unsupported platform: {0}")]
116    UnsupportedPlatform(String),
117
118    #[error("Unsupported architecture: {0}")]
119    UnsupportedArchitecture(String),
120
121    #[error("Failed to download binary: {0}")]
122    DownloadFailed(String),
123
124    #[error("Failed to extract archive: {0}")]
125    ExtractionFailed(String),
126
127    #[error("Binary not found in archive")]
128    BinaryNotFound,
129
130    #[error("Failed to execute gitleaks: {0}")]
131    ExecutionFailed(String),
132
133    #[error("Gitleaks exited with error code {code}: {stderr}")]
134    GitleaksError { code: i32, stderr: String },
135
136    #[error("Failed to make binary executable: {0}")]
137    ChmodFailed(String),
138
139    #[error("Cache error: {0}")]
140    CacheError(String),
141
142    #[error("Failed to resolve latest version: {0}")]
143    VersionResolution(String),
144}
145
146/// SARIF processing errors
147#[derive(thiserror::Error, Debug)]
148#[cfg_attr(feature = "wasm", derive(Serialize, Deserialize))]
149pub enum SarifError {
150    #[error("SARIF file not found: {0}")]
151    FileNotFound(String),
152
153    #[error("Failed to parse SARIF JSON: {0}")]
154    ParseError(String),
155
156    #[error("Invalid SARIF structure: {0}")]
157    InvalidStructure(String),
158
159    #[error("Missing required field: {0}")]
160    MissingField(String),
161
162    #[error("No results found in SARIF report")]
163    NoResults,
164}
165
166/// GitHub API errors
167#[derive(thiserror::Error, Debug)]
168#[cfg_attr(feature = "wasm", derive(Serialize, Deserialize))]
169pub enum GitHubError {
170    #[error("API request failed with status {status}: {message}")]
171    RequestFailed { status: u16, message: String },
172
173    #[error("Authentication failed: {0}")]
174    AuthenticationFailed(String),
175
176    #[error("Rate limit exceeded")]
177    RateLimitExceeded,
178
179    #[error("Resource not found: {0}")]
180    NotFound(String),
181
182    #[error("Failed to parse API response: {0}")]
183    ParseError(String),
184
185    #[error("Network error: {0}")]
186    NetworkError(String),
187
188    #[error("Timeout: {0}")]
189    Timeout(String),
190
191    #[error("Cannot comment on line (diff too large or file not in PR)")]
192    DiffTooLarge,
193
194    #[error("Max retries exceeded")]
195    MaxRetriesExceeded,
196}
197
198impl Error {
199    /// Returns the severity level of this error
200    pub fn severity(&self) -> ErrorSeverity {
201        match self {
202            // Fatal errors
203            Error::Config(ConfigError::MissingEnvVar(_)) => ErrorSeverity::Fatal,
204            Error::Config(ConfigError::InvalidEnvVar { .. }) => ErrorSeverity::Fatal,
205            Error::Config(ConfigError::PathTraversal(_)) => ErrorSeverity::Fatal,
206            Error::Config(ConfigError::OutsideWorkspace(_)) => ErrorSeverity::Fatal,
207            Error::Event(EventError::UnsupportedEvent(_)) => ErrorSeverity::Fatal,
208            Error::Event(EventError::NoCommits) => ErrorSeverity::Expected,
209            Error::Binary(BinaryError::UnsupportedPlatform(_)) => ErrorSeverity::Fatal,
210            Error::Binary(BinaryError::UnsupportedArchitecture(_)) => ErrorSeverity::Fatal,
211            Error::Binary(BinaryError::DownloadFailed(_)) => ErrorSeverity::Fatal,
212            Error::Binary(BinaryError::GitleaksError { .. }) => ErrorSeverity::Fatal,
213            Error::Sarif(SarifError::FileNotFound(_)) => ErrorSeverity::Fatal,
214            Error::Sarif(SarifError::ParseError(_)) => ErrorSeverity::Fatal,
215            Error::GitHub(GitHubError::AuthenticationFailed(_)) => ErrorSeverity::Fatal,
216            Error::License(_) => ErrorSeverity::Fatal,
217
218            // Non-fatal errors (warnings)
219            Error::Binary(BinaryError::CacheError(_)) => ErrorSeverity::NonFatal,
220            Error::Binary(BinaryError::VersionResolution(_)) => ErrorSeverity::NonFatal,
221            Error::GitHub(GitHubError::DiffTooLarge) => ErrorSeverity::NonFatal,
222            Error::GitHub(GitHubError::NotFound(_)) => ErrorSeverity::NonFatal,
223            Error::GitHub(GitHubError::RateLimitExceeded) => ErrorSeverity::NonFatal,
224
225            // Default to fatal for safety
226            _ => ErrorSeverity::Fatal,
227        }
228    }
229
230    /// Masks sensitive information in error messages
231    pub fn sanitized(&self) -> String {
232        let message = self.to_string();
233        // Replace any potential tokens or secrets with ***
234        message
235            .replace(
236                |c: char| c.is_ascii_alphanumeric() && message.contains("token"),
237                "***",
238            )
239            .replace(
240                |c: char| c.is_ascii_alphanumeric() && message.contains("key"),
241                "***",
242            )
243    }
244}
245
246impl ConfigError {
247    /// Create a missing environment variable error
248    pub fn missing_env(key: impl Into<String>) -> Self {
249        ConfigError::MissingEnvVar(key.into())
250    }
251
252    /// Create an invalid environment variable error
253    pub fn invalid_env(key: impl Into<String>, value: impl Into<String>) -> Self {
254        ConfigError::InvalidEnvVar {
255            key: key.into(),
256            value: value.into(),
257        }
258    }
259}
260
261impl EventError {
262    /// Create an unsupported event error
263    pub fn unsupported(event: impl Into<String>) -> Self {
264        EventError::UnsupportedEvent(event.into())
265    }
266}
267
268impl From<std::io::Error> for Error {
269    fn from(err: std::io::Error) -> Self {
270        Error::Io(err.to_string())
271    }
272}
273
274impl From<serde_json::Error> for Error {
275    fn from(err: serde_json::Error) -> Self {
276        Error::Json(err.to_string())
277    }
278}
279
280#[cfg(feature = "native")]
281impl From<reqwest::Error> for Error {
282    fn from(err: reqwest::Error) -> Self {
283        Error::Http(err.to_string())
284    }
285}
286
287#[cfg(feature = "native")]
288impl From<octocrab::Error> for Error {
289    fn from(err: octocrab::Error) -> Self {
290        Error::GitHub(GitHubError::NetworkError(err.to_string()))
291    }
292}
293
294/// Result type alias for SecretScout operations
295pub type Result<T> = std::result::Result<T, Error>;
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300
301    #[test]
302    fn test_error_severity() {
303        let err = Error::Config(ConfigError::MissingEnvVar("TEST".into()));
304        assert_eq!(err.severity(), ErrorSeverity::Fatal);
305
306        let err = Error::Event(EventError::NoCommits);
307        assert_eq!(err.severity(), ErrorSeverity::Expected);
308
309        let err = Error::Binary(BinaryError::CacheError("test".into()));
310        assert_eq!(err.severity(), ErrorSeverity::NonFatal);
311    }
312
313    #[test]
314    fn test_config_error_constructors() {
315        let err = ConfigError::missing_env("TEST_VAR");
316        assert!(matches!(err, ConfigError::MissingEnvVar(_)));
317
318        let err = ConfigError::invalid_env("KEY", "value");
319        assert!(matches!(err, ConfigError::InvalidEnvVar { .. }));
320    }
321
322    #[test]
323    fn test_error_display() {
324        let err = Error::Config(ConfigError::MissingEnvVar("GITHUB_TOKEN".into()));
325        let msg = err.to_string();
326        assert!(msg.contains("GITHUB_TOKEN"));
327        assert!(msg.contains("Configuration error"));
328    }
329}