Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 31 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ include = [

[dependencies]
fst = "0.4.7"
memmap2 = "0.9.9"
packageurl = "0.6.0"
once_cell = "1.21"

[build-dependencies]
Expand Down
28 changes: 25 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,34 @@ Add `purl-validator` to your Rust dependency
cargo add purl-validator
```

Use it in your code like this
Use it in your code like this:

```rust
use purl_validator::validate;

let result: bool = validate("pkg:nuget/FluentValidation");
fn main() {
let result: bool = validate("pkg:nuget/FluentValidation")
.expect("only fails if PURL is invalid or contains version, qualifier, or subpath");
}
```

Examples and errors:

```rust
fn example() {
// This will return: Ok(true)
validate("pkg:nuget/FluentValidation");

// This will return: Ok(false)
validate("pkg:nuget/non-existent-foo-bar");


// This will return an error: Err(UnsupportedPurl("only base PURL is supported (no version, qualifiers, or subpath)"))
validate("pkg:nuget/FluentValidation@10.2.3");

// This will return an error: Err(InvalidPurl(""))
validate("nuget/FluentValidation");
}
```

## Contribution
Expand Down Expand Up @@ -90,4 +112,4 @@ limitations under the License.
```

[^1]: MineCode continuously collects package metadata from various package ecosystems to maintain an up-to-date catalog of known packages.
[^2]: A Base Package URL is a Package URL without a version or subpath.
[^2]: A Base Package URL is a Package URL without a version, qualifiers or subpath.
34 changes: 27 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,35 +24,55 @@ See https://aboutcode.org for more information about nexB OSS projects.
//! ```
//! use purl_validator::validate;
//!
//! let result: bool = validate("pkg:nuget/FluentValidation");
//! let result: bool = validate("pkg:nuget/FluentValidation")
//! .expect("only fails if PURL is invalid or contains version, qualifier, or subpath");
//! ```
//!

use fst::Set;

use once_cell::sync::Lazy;
use packageurl::PackageUrl;
use std::env;
use std::str::FromStr;

static FST_DATA: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/purls.fst"));

static VALIDATOR: Lazy<Set<&'static [u8]>> =
Lazy::new(|| Set::new(FST_DATA).expect("Failed to load FST from embedded bytes"));

fn strip_and_check_purl(packageurl: &str, fst_map: &Set<&[u8]>) -> bool {
fn strip_and_check_purl(packageurl: &str, fst_map: &Set<&[u8]>) -> Result<bool, ValidateError> {
let purl = PackageUrl::from_str(packageurl).map_err(ValidateError::InvalidPurl)?;
if purl.version().is_some() || !purl.qualifiers().is_empty() || purl.subpath().is_some() {
return Err(ValidateError::UnsupportedPurl(
"only base PURL is supported (no version, qualifiers, or subpath)",
));
}

let trimmed_packageurl = packageurl.trim_end_matches("/");
fst_map.contains(trimmed_packageurl)
Ok(fst_map.contains(trimmed_packageurl))
}

/// Validate a Package URL (PURL)
///
/// Returns `true` if the given base PURL represents an existing package,
/// otherwise returns `false`.
/// Return `Ok(true)` if given **base PURL** represents an existing package,
/// `Ok(false)` if it does not, or `Err` if the PURL is invalid or contains
/// unsupported fields (version, qualifiers, or subpath).
///
/// A **base PURL** is a PURL without a version, qualifiers, or subpath.
/// PURLs containing a version, qualifiers, or subpath are **not supported**
/// and will cause the validator to return an error.
///
/// Use pre-built FST (Finite State Transducer) to perform lookups and confirm whether
/// the **base PURL** exists.
pub fn validate(packageurl: &str) -> bool {
pub fn validate(packageurl: &str) -> Result<bool, ValidateError> {
strip_and_check_purl(packageurl, &VALIDATOR)
}

#[derive(Debug)]
pub enum ValidateError {
InvalidPurl(packageurl::Error),
UnsupportedPurl(&'static str),
}

#[cfg(test)]
mod validate_tests;
39 changes: 30 additions & 9 deletions src/validate_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ fn test_validate_with_custom_file() {
let data: Vec<u8> = fs::read(test_path).unwrap();
let data_slice: &[u8] = &data;
let validator = Set::new(data_slice).unwrap();
assert!(strip_and_check_purl(
"pkg:nuget/FluentUtils.EnumExtensions",
&validator
));
assert!(!strip_and_check_purl("pkg:example/nonexistent", &validator));

let result = strip_and_check_purl("pkg:nuget/FluentUtils.EnumExtensions", &validator).unwrap();
assert!(result);

let result = strip_and_check_purl("pkg:example/nonexistent", &validator).unwrap();
assert!(!result);
}

#[test]
Expand All @@ -35,8 +36,28 @@ fn test_validate_with_packageurl_trailing_slash() {
let validator = Set::new(data_slice).unwrap();

assert!(validator.contains("pkg:nuget/FluentUtils.EnumExtensions"));
assert!(strip_and_check_purl(
"pkg:nuget/FluentUtils.EnumExtensions/",
&validator
));
let result = strip_and_check_purl("pkg:nuget/FluentUtils.EnumExtensions/", &validator).unwrap();
assert!(result);
}

#[test]
fn test_validate_with_packageurl_invalid_purl() {
let test_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/test_purls.fst");
let data: Vec<u8> = fs::read(test_path).unwrap();
let data_slice: &[u8] = &data;
let validator = Set::new(data_slice).unwrap();

let result = strip_and_check_purl("nuget/foobar", &validator);
assert!(matches!(result, Err(ValidateError::InvalidPurl(_))));
}

#[test]
fn test_validate_with_packageurl_unsupported_purl() {
let test_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/test_purls.fst");
let data: Vec<u8> = fs::read(test_path).unwrap();
let data_slice: &[u8] = &data;
let validator = Set::new(data_slice).unwrap();

let result = strip_and_check_purl("pkg:nuget/FluentUtils.EnumExtensions@1.0.0", &validator);
assert!(matches!(result, Err(ValidateError::UnsupportedPurl(_))));
}