From cff2ed2caa89753641690c3a084e9805ea5b8ba2 Mon Sep 17 00:00:00 2001 From: mrl5 <31549762+mrl5@users.noreply.github.com> Date: Sat, 23 Jul 2022 18:06:57 +0200 Subject: [PATCH] fix(cpe-tag): errors when package version "0" or "9999" [#54] closes #54 --- crates/cpe-tag/src/searchers.rs | 37 ++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/crates/cpe-tag/src/searchers.rs b/crates/cpe-tag/src/searchers.rs index 435b82a..2ab2cbd 100644 --- a/crates/cpe-tag/src/searchers.rs +++ b/crates/cpe-tag/src/searchers.rs @@ -17,6 +17,10 @@ use std::error::Error; use std::path::Path; pub fn grep(pattern: String, feed: &Path) -> Result, Box> { + if pattern.is_empty() { + return Ok(HashSet::new()); + } + let matcher = RegexMatcher::new_line_matcher(&pattern)?; let mut matches: Vec = vec![]; @@ -41,13 +45,7 @@ pub fn match_cpes<'a>( re_pattern: &str, ) -> HashMap<&'a Package, HashSet> { let mut cpes = HashMap::new(); - let re = Regex::new(re_pattern).unwrap(); - let matches = feed - .iter() - .filter(|feed_entry| re.is_match(feed_entry)) - .map(|x| x.to_string()) - .collect(); - cpes.insert(pkg, matches); + cpes.insert(pkg, get_matches(re_pattern, feed)); cpes } @@ -60,6 +58,18 @@ pub fn contains_cpe_json_key(line: &str) -> bool { line.contains(CPE_KEYWORD_IN_FEED_LINE) } +fn get_matches(re_pattern: &str, feed: &[Box]) -> HashSet { + if re_pattern.is_empty() { + return HashSet::new(); + } + + let re = Regex::new(re_pattern).unwrap(); + feed.iter() + .filter(|feed_entry| re.is_match(feed_entry)) + .map(|x| x.to_string()) + .collect() +} + fn get_uniq_values(matches: Vec) -> HashSet { let values: HashSet = matches.iter().map(|m| scrap_cpe(m)).collect(); values @@ -76,6 +86,19 @@ mod tests { "cpe:2.3:a:xmlsoft:libxml2:2.9.10:*:*:*:*:*:*:*" ); } + #[test] + fn it_should_ignore_empty_string_as_a_pattern() { + let test_matches = [ + Box::from( + " \"cpe23Uri\" : \"cpe:2.3:a:busybox:busybox:1.29.3:*:*:*:*:*:*:*\"\r\n", + ), + Box::from( + " \"cpe23Uri\" : \"cpe:2.3:a:xmlsoft:libxml2:2.9.10:*:*:*:*:*:*:*\"\r\n", + ), + ]; + + assert_eq!(get_matches("", &test_matches).len(), 0); + } #[test] fn it_should_return_unique_values() {