aptu-core 0.10.12

Core library for Aptu - OSS issue triage with AI assistance
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
// SPDX-License-Identifier: Apache-2.0

//! Global ignore list for security findings.
//!
//! Allows users to configure patterns and paths to skip before LLM validation,
//! reducing API costs and noise from known false positives.

use std::fs;
use std::path::{Component, Path, PathBuf};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

use super::Finding;

fn path_matches_prefix(file_path: &str, prefix: &str) -> bool {
    let file_components: Vec<Component<'_>> = Path::new(file_path)
        .components()
        .filter(|component| !matches!(component, Component::CurDir))
        .collect();
    let prefix_components: Vec<Component<'_>> = Path::new(prefix).components().collect();

    if prefix_components.is_empty() || file_components.is_empty() {
        return false;
    }

    // Relative paths must start with the prefix.
    if file_components.len() >= prefix_components.len()
        && file_components[..prefix_components.len()]
            .iter()
            .zip(&prefix_components)
            .all(|(file_component, prefix_component)| file_component == prefix_component)
    {
        return true;
    }

    // Absolute paths may contain the prefix at any depth.
    matches!(file_components.first(), Some(Component::RootDir))
        && file_components
            .windows(prefix_components.len())
            .any(|window| {
                window
                    .iter()
                    .zip(&prefix_components)
                    .all(|(file_component, prefix_component)| file_component == prefix_component)
            })
}

/// Security configuration for ignore rules.
///
/// Loaded from `~/.config/aptu/security.toml` with fallback to defaults.
///
/// By default, includes sensible ignore paths for common test and vendor directories.
/// Use `SecurityConfig::empty()` for a configuration with no ignore rules.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    /// Pattern IDs to ignore (e.g., `["hardcoded-secret", "sql-injection"]`).
    #[serde(default)]
    pub ignore_patterns: Vec<String>,

    /// File path prefixes to ignore (e.g., `["test/", "vendor/"]`).
    #[serde(default)]
    pub ignore_paths: Vec<String>,
}

impl Default for SecurityConfig {
    /// Returns configuration with sensible default ignore paths.
    ///
    /// Includes common test and vendor directories that typically contain
    /// test fixtures or third-party code that should not be scanned.
    fn default() -> Self {
        Self {
            ignore_patterns: vec![],
            ignore_paths: vec![
                "tests/".to_string(),
                "test/".to_string(),
                "benches/".to_string(),
                "fixtures/".to_string(),
                "vendor/".to_string(),
                "generated/".to_string(),
                "docs/".to_string(),
                "build/".to_string(),
                "target/".to_string(),
                "dist/".to_string(),
                "out/".to_string(),
                ".next/".to_string(),
            ],
        }
    }
}

impl SecurityConfig {
    /// Create configuration with sensible default ignore paths.
    ///
    /// This is an alias for `Default::default()`.
    #[must_use]
    #[deprecated(since = "0.6.0", note = "Use `SecurityConfig::default()` instead")]
    pub fn with_defaults() -> Self {
        Self::default()
    }

    /// Create an empty configuration with no ignore rules.
    ///
    /// Use this when you want to scan all files without any filtering.
    #[must_use]
    pub fn empty() -> Self {
        Self {
            ignore_patterns: vec![],
            ignore_paths: vec![],
        }
    }

    /// Check if a file path should be ignored based on configuration.
    ///
    /// This is a fast check that can be used before scanning to avoid
    /// running expensive regex patterns on files in ignored directories.
    ///
    /// # Arguments
    ///
    /// * `file_path` - The file path to check
    ///
    /// # Returns
    ///
    /// `true` if the path should be ignored, `false` otherwise.
    #[must_use]
    pub fn should_ignore_path(&self, file_path: &str) -> bool {
        self.ignore_paths
            .iter()
            .any(|prefix| path_matches_prefix(file_path, prefix))
    }

    /// Load configuration from `~/.config/aptu/security.toml`.
    ///
    /// Returns default configuration if file doesn't exist or parse fails.
    ///
    /// # Returns
    ///
    /// Loaded configuration or default on error.
    #[must_use]
    pub fn load() -> Self {
        if let Some(path) = Self::config_path() {
            match Self::load_from_path(&path) {
                Ok(config) => config,
                Err(e) => {
                    tracing::warn!("Failed to load security config: {:#}", e);
                    Self::default()
                }
            }
        } else {
            tracing::warn!("Config directory not available, using default security config");
            Self::default()
        }
    }

    /// Get the configuration file path.
    ///
    /// Returns `~/.config/aptu/security.toml` or `None` if config directory cannot be determined.
    #[must_use]
    pub fn config_path() -> Option<PathBuf> {
        dirs::config_dir().map(|dir| dir.join("aptu").join("security.toml"))
    }

    /// Load configuration from a specific path.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to configuration file
    ///
    /// # Returns
    ///
    /// Loaded configuration or error if file exists but is invalid.
    fn load_from_path(path: &PathBuf) -> Result<Self> {
        if !path.exists() {
            return Ok(Self::default());
        }

        let contents = fs::read_to_string(path)
            .with_context(|| format!("Failed to read config file: {}", path.display()))?;

        toml::from_str(&contents)
            .with_context(|| format!("Failed to parse config file: {}", path.display()))
    }

    /// Check if a finding should be ignored based on configuration.
    ///
    /// A finding is ignored if:
    /// - Its pattern ID matches any entry in `ignore_patterns`
    /// - Its file path starts with any entry in `ignore_paths`
    ///
    /// # Arguments
    ///
    /// * `finding` - The finding to check
    ///
    /// # Returns
    ///
    /// `true` if the finding should be ignored, `false` otherwise.
    #[must_use]
    pub fn should_ignore(&self, finding: &Finding) -> bool {
        // Check pattern ID
        if self.ignore_patterns.contains(&finding.pattern_id) {
            return true;
        }

        // Check file path prefixes
        for prefix in &self.ignore_paths {
            if path_matches_prefix(&finding.file_path, prefix) {
                return true;
            }
        }

        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::security::{Confidence, Severity};

    #[test]
    fn test_security_config_default_has_sensible_paths() {
        let config = SecurityConfig::default();
        assert!(config.ignore_patterns.is_empty());
        assert_eq!(config.ignore_paths.len(), 12);
        assert!(config.ignore_paths.contains(&"tests/".to_string()));
        assert!(config.ignore_paths.contains(&"test/".to_string()));
        assert!(config.ignore_paths.contains(&"benches/".to_string()));
        assert!(config.ignore_paths.contains(&"fixtures/".to_string()));
        assert!(config.ignore_paths.contains(&"vendor/".to_string()));
        for prefix in [
            "generated/",
            "docs/",
            "build/",
            "target/",
            "dist/",
            "out/",
            ".next/",
        ] {
            assert!(config.should_ignore_path(&format!("./{prefix}file.rs")));
        }
    }

    #[test]
    fn test_empty_config() {
        let config = SecurityConfig::empty();
        assert!(config.ignore_patterns.is_empty());
        assert!(config.ignore_paths.is_empty());
    }

    #[test]
    #[allow(deprecated)]
    fn test_with_defaults_deprecated() {
        // with_defaults is deprecated but should still work
        let config = SecurityConfig::with_defaults();
        assert!(config.ignore_patterns.is_empty());
        assert_eq!(config.ignore_paths.len(), 12);
    }

    #[test]
    fn test_should_ignore_path_method() {
        let config = SecurityConfig::default();

        // Should ignore test paths
        assert!(config.should_ignore_path("tests/unit/test.rs"));
        assert!(config.should_ignore_path("test/fixtures/data.rs"));
        assert!(config.should_ignore_path("vendor/lib.rs"));

        // Should not ignore src paths
        assert!(!config.should_ignore_path("src/main.rs"));
        assert!(!config.should_ignore_path("src/test.rs"));
    }

    #[test]
    fn test_should_ignore_pattern() {
        let config = SecurityConfig {
            ignore_patterns: vec!["test-pattern".to_string(), "another-pattern".to_string()],
            ignore_paths: vec![],
        };

        let finding = Finding {
            pattern_id: "test-pattern".to_string(),
            description: "Test".to_string(),
            severity: Severity::Low,
            confidence: Confidence::Low,
            file_path: "src/main.rs".to_string(),
            line_number: 1,
            matched_text: "test".to_string(),
            cwe: None,
        };

        assert!(config.should_ignore(&finding));
    }

    #[test]
    fn test_should_ignore_path() {
        let config = SecurityConfig {
            ignore_patterns: vec![],
            ignore_paths: vec!["test/".to_string(), "vendor/".to_string()],
        };

        let finding = Finding {
            pattern_id: "pattern".to_string(),
            description: "Test".to_string(),
            severity: Severity::Low,
            confidence: Confidence::Low,
            file_path: "test/fixtures/data.rs".to_string(),
            line_number: 1,
            matched_text: "test".to_string(),
            cwe: None,
        };

        assert!(config.should_ignore(&finding));
    }

    #[test]
    fn test_should_not_ignore() {
        let config = SecurityConfig {
            ignore_patterns: vec!["other-pattern".to_string()],
            ignore_paths: vec!["vendor/".to_string()],
        };

        let finding = Finding {
            pattern_id: "real-pattern".to_string(),
            description: "Test".to_string(),
            severity: Severity::High,
            confidence: Confidence::High,
            file_path: "src/main.rs".to_string(),
            line_number: 42,
            matched_text: "code".to_string(),
            cwe: Some("CWE-123".to_string()),
        };

        assert!(!config.should_ignore(&finding));
    }

    #[test]
    fn test_should_ignore_path_prefix() {
        let config = SecurityConfig {
            ignore_patterns: vec![],
            ignore_paths: vec!["test/".to_string()],
        };

        // Should match prefix
        let finding1 = Finding {
            pattern_id: "pattern".to_string(),
            description: "Test".to_string(),
            severity: Severity::Low,
            confidence: Confidence::Low,
            file_path: "test/unit/test.rs".to_string(),
            line_number: 1,
            matched_text: "test".to_string(),
            cwe: None,
        };
        assert!(config.should_ignore(&finding1));

        // Should not match if not a prefix
        let finding2 = Finding {
            pattern_id: "pattern".to_string(),
            description: "Test".to_string(),
            severity: Severity::Low,
            confidence: Confidence::Low,
            file_path: "src/test.rs".to_string(),
            line_number: 1,
            matched_text: "test".to_string(),
            cwe: None,
        };
        assert!(!config.should_ignore(&finding2));
    }

    #[test]
    fn test_path_matches_prefix_component_matching() {
        // ./ prefix is normalized away (CurDir component skipped)
        assert!(path_matches_prefix("./tests/foo.rs", "tests/"));
        // Direct component match
        assert!(path_matches_prefix("tests/foo.rs", "tests/"));
        // Absolute path matches prefix at any depth
        assert!(path_matches_prefix("/absolute/path/tests/foo.rs", "tests/"));
        // Different first component must not match
        assert!(!path_matches_prefix("src/main.rs", "tests/"));
        // Path deeper than prefix still matches
        assert!(path_matches_prefix("generated/sub/deep.rs", "generated/"));
        // Nested same-name component in a relative path must not match
        assert!(!path_matches_prefix("src/tests/foo.rs", "tests/"));
    }

    #[test]
    fn test_config_serialization() {
        let config = SecurityConfig {
            ignore_patterns: vec!["pattern1".to_string(), "pattern2".to_string()],
            ignore_paths: vec!["test/".to_string(), "vendor/".to_string()],
        };

        let toml = toml::to_string(&config).expect("serialize");
        let deserialized: SecurityConfig = toml::from_str(&toml).expect("deserialize");

        assert_eq!(config.ignore_patterns, deserialized.ignore_patterns);
        assert_eq!(config.ignore_paths, deserialized.ignore_paths);
    }

    #[test]
    fn test_load_nonexistent_file_returns_defaults() {
        let path = PathBuf::from("/nonexistent/path/security.toml");
        let config = SecurityConfig::load_from_path(&path).expect("load default");
        // When file doesn't exist, should return sensible defaults
        assert!(config.ignore_patterns.is_empty());
        assert_eq!(config.ignore_paths.len(), 12);
    }

    #[test]
    fn test_config_path() {
        if let Some(path) = SecurityConfig::config_path() {
            assert!(path.ends_with("aptu/security.toml"));
        }
        // If None, test passes (config dir not available in environment)
    }
}