1use std::collections::BTreeMap;
23use std::fmt;
24
25use thiserror::Error;
26
27pub const MAX_PURL_BYTES: usize = 4096;
30
31#[derive(Debug, Clone, PartialEq, Eq, Error)]
35#[non_exhaustive]
36pub enum PurlError {
37 #[error("Package URL is longer than {MAX_PURL_BYTES} bytes")]
39 TooLong,
40 #[error("Package URL must start with `pkg:`")]
42 Scheme,
43 #[error("Package URL type is missing or invalid")]
46 Type,
47 #[error("Package URL name is missing")]
49 Name,
50 #[error("Package URL namespace segment contains a slash")]
52 Namespace,
53 #[error("Package URL qualifier key is invalid")]
56 QualifierKey,
57 #[error("Package URL qualifier key appears more than once")]
59 DuplicateQualifier,
60 #[error("Package URL subpath segment contains a slash")]
62 Subpath,
63 #[error("Package URL has an invalid percent-encoding")]
65 Encoding,
66 #[error("TEI purl identifier is not unpadded Base64URL of UTF-8 text")]
68 TeiIdentifier,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
75#[non_exhaustive]
76pub enum PurlRules {
77 Generic,
79}
80
81#[derive(Debug, Clone, PartialEq, Eq, Hash)]
99pub struct Purl {
100 original: String,
101 package_type: String,
102 namespace: Vec<String>,
103 name: String,
104 version: Option<String>,
105 qualifiers: BTreeMap<String, String>,
106 subpath: Vec<String>,
107}
108
109#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
116pub struct CanonicalPurl(String);
117
118impl CanonicalPurl {
119 #[must_use]
121 pub fn as_str(&self) -> &str {
122 &self.0
123 }
124
125 #[must_use]
127 pub fn rules(&self) -> PurlRules {
128 PurlRules::Generic
129 }
130}
131
132impl fmt::Display for CanonicalPurl {
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 f.write_str(&self.0)
135 }
136}
137
138#[must_use]
140pub fn same_package_url(a: &Purl, b: &Purl) -> bool {
141 a.canonical() == b.canonical()
142}
143
144impl Purl {
145 pub fn parse(text: &str) -> Result<Self, PurlError> {
159 if text.len() > MAX_PURL_BYTES {
160 return Err(PurlError::TooLong);
161 }
162 let (remainder, subpath) = match text.rsplit_once('#') {
163 Some((left, right)) => (left, parse_subpath(right)?),
164 None => (text, Vec::new()),
165 };
166 let (remainder, qualifiers) = match remainder.rsplit_once('?') {
167 Some((left, right)) => (left, parse_qualifiers(right)?),
168 None => (remainder, BTreeMap::new()),
169 };
170 let (scheme, remainder) = remainder.split_once(':').ok_or(PurlError::Scheme)?;
171 if !scheme.eq_ignore_ascii_case("pkg") {
172 return Err(PurlError::Scheme);
173 }
174 let remainder = remainder.trim_start_matches('/');
175 let (package_type, remainder) = remainder.split_once('/').ok_or(PurlError::Name)?;
176 let package_type = package_type.to_ascii_lowercase();
177 if !valid_type(&package_type) {
178 return Err(PurlError::Type);
179 }
180 let last_segment = remainder.rfind('/').map_or(0, |index| index + 1);
184 let (remainder, version) = match remainder[last_segment..].rfind('@') {
185 Some(at) => {
186 let at = last_segment + at;
187 let version = percent_decode(&remainder[at + 1..])?;
188 (&remainder[..at], (!version.is_empty()).then_some(version))
189 }
190 None => (remainder, None),
191 };
192 let remainder = remainder.trim_end_matches('/');
193 let (remainder, name) = match remainder.rsplit_once('/') {
194 Some((left, right)) => (left, right),
195 None => ("", remainder),
196 };
197 let name = percent_decode(name)?;
198 if name.is_empty() {
199 return Err(PurlError::Name);
200 }
201 let mut namespace = Vec::new();
202 for segment in remainder.split('/').filter(|segment| !segment.is_empty()) {
203 let segment = percent_decode(segment)?;
204 if segment.contains('/') {
205 return Err(PurlError::Namespace);
206 }
207 namespace.push(segment);
208 }
209 let purl = Self {
210 original: text.to_owned(),
211 package_type,
212 namespace,
213 name,
214 version,
215 qualifiers,
216 subpath,
217 };
218 if purl.canonical().0.len() > MAX_PURL_BYTES {
221 return Err(PurlError::TooLong);
222 }
223 Ok(purl)
224 }
225
226 #[must_use]
228 pub fn as_str(&self) -> &str {
229 &self.original
230 }
231
232 #[must_use]
234 pub fn package_type(&self) -> &str {
235 &self.package_type
236 }
237
238 #[must_use]
241 pub fn namespace(&self) -> Option<String> {
242 (!self.namespace.is_empty()).then(|| self.namespace.join("/"))
243 }
244
245 #[must_use]
247 pub fn name(&self) -> &str {
248 &self.name
249 }
250
251 #[must_use]
253 pub fn version(&self) -> Option<&str> {
254 self.version.as_deref()
255 }
256
257 pub fn qualifiers(&self) -> impl Iterator<Item = (&str, &str)> {
259 self.qualifiers
260 .iter()
261 .map(|(key, value)| (key.as_str(), value.as_str()))
262 }
263
264 #[must_use]
266 pub fn qualifier(&self, key: &str) -> Option<&str> {
267 self.qualifiers
268 .get(&key.to_ascii_lowercase())
269 .map(String::as_str)
270 }
271
272 #[must_use]
275 pub fn subpath(&self) -> Option<String> {
276 (!self.subpath.is_empty()).then(|| self.subpath.join("/"))
277 }
278
279 #[must_use]
281 pub fn canonical(&self) -> CanonicalPurl {
282 let mut out = String::with_capacity(self.original.len());
283 out.push_str("pkg:");
284 out.push_str(&self.package_type);
285 out.push('/');
286 for segment in &self.namespace {
287 percent_encode_into(segment, &mut out);
288 out.push('/');
289 }
290 percent_encode_into(&self.name, &mut out);
291 if let Some(version) = &self.version {
292 out.push('@');
293 percent_encode_into(version, &mut out);
294 }
295 for (index, (key, value)) in self.qualifiers.iter().enumerate() {
296 out.push(if index == 0 { '?' } else { '&' });
297 out.push_str(key);
298 out.push('=');
299 percent_encode_into(value, &mut out);
300 }
301 for (index, segment) in self.subpath.iter().enumerate() {
302 out.push(if index == 0 { '#' } else { '/' });
303 percent_encode_into(segment, &mut out);
304 }
305 CanonicalPurl(out)
306 }
307}
308
309fn valid_type(package_type: &str) -> bool {
311 let mut chars = package_type.chars();
312 chars.next().is_some_and(|c| c.is_ascii_alphabetic())
313 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-'))
314}
315
316fn valid_qualifier_key(key: &str) -> bool {
319 let mut chars = key.chars();
320 chars.next().is_some_and(|c| c.is_ascii_lowercase())
321 && chars
322 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '-' | '_'))
323}
324
325fn parse_qualifiers(text: &str) -> Result<BTreeMap<String, String>, PurlError> {
326 let mut qualifiers = BTreeMap::new();
327 for pair in text.split('&').filter(|pair| !pair.is_empty()) {
328 let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
329 let key = key.to_ascii_lowercase();
330 if !valid_qualifier_key(&key) {
331 return Err(PurlError::QualifierKey);
332 }
333 let value = percent_decode(value)?;
334 if value.is_empty() {
335 continue;
336 }
337 if qualifiers.insert(key, value).is_some() {
338 return Err(PurlError::DuplicateQualifier);
339 }
340 }
341 Ok(qualifiers)
342}
343
344fn parse_subpath(text: &str) -> Result<Vec<String>, PurlError> {
345 let mut segments = Vec::new();
346 for segment in text.split('/') {
347 let segment = percent_decode(segment)?;
348 if segment.is_empty() || segment == "." || segment == ".." {
349 continue;
350 }
351 if segment.contains('/') {
352 return Err(PurlError::Subpath);
353 }
354 segments.push(segment);
355 }
356 Ok(segments)
357}
358
359fn percent_decode(text: &str) -> Result<String, PurlError> {
360 if !text.contains('%') {
361 return Ok(text.to_owned());
362 }
363 let bytes = text.as_bytes();
364 let mut out = Vec::with_capacity(bytes.len());
365 let mut index = 0;
366 while index < bytes.len() {
367 if bytes[index] == b'%' {
368 let high = bytes.get(index + 1).and_then(|b| hex_value(*b));
369 let low = bytes.get(index + 2).and_then(|b| hex_value(*b));
370 let (Some(high), Some(low)) = (high, low) else {
371 return Err(PurlError::Encoding);
372 };
373 out.push(high << 4 | low);
374 index += 3;
375 } else {
376 out.push(bytes[index]);
377 index += 1;
378 }
379 }
380 String::from_utf8(out).map_err(|_| PurlError::Encoding)
381}
382
383fn hex_value(byte: u8) -> Option<u8> {
384 match byte {
385 b'0'..=b'9' => Some(byte - b'0'),
386 b'a'..=b'f' => Some(byte - b'a' + 10),
387 b'A'..=b'F' => Some(byte - b'A' + 10),
388 _ => None,
389 }
390}
391
392fn percent_encode_into(text: &str, out: &mut String) {
395 const HEX: &[u8; 16] = b"0123456789ABCDEF";
396 for &byte in text.as_bytes() {
397 if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_' | b'~' | b':') {
398 out.push(char::from(byte));
399 } else {
400 out.push('%');
401 out.push(char::from(HEX[usize::from(byte >> 4)]));
402 out.push(char::from(HEX[usize::from(byte & 0x0f)]));
403 }
404 }
405}
406
407#[cfg(test)]
408mod tests {
409 use super::*;
410
411 #[test]
412 fn original_text_is_kept_and_canonical_is_separate() {
413 let text = "pkg://NPM//%40angular/animation@12.3.1?B=2&a=1#/x/./y/";
414 let purl = Purl::parse(text).unwrap();
415 assert_eq!(purl.as_str(), text);
416 assert_eq!(purl.package_type(), "npm");
417 assert_eq!(purl.namespace().as_deref(), Some("@angular"));
418 assert_eq!(purl.name(), "animation");
419 assert_eq!(purl.version(), Some("12.3.1"));
420 assert_eq!(purl.qualifier("A"), Some("1"));
421 assert_eq!(purl.subpath().as_deref(), Some("x/y"));
422 assert_eq!(
423 purl.canonical().as_str(),
424 "pkg:npm/%40angular/animation@12.3.1?a=1&b=2#x/y"
425 );
426 assert_eq!(purl.canonical().rules(), PurlRules::Generic);
427 }
428
429 #[test]
430 fn an_unencoded_scope_is_not_a_version() {
431 let purl = Purl::parse("pkg:npm/@babel/core#lib").unwrap();
432 assert_eq!(purl.namespace().as_deref(), Some("@babel"));
433 assert_eq!(purl.name(), "core");
434 assert_eq!(purl.version(), None);
435 assert_eq!(purl.canonical().as_str(), "pkg:npm/%40babel/core#lib");
436 let versioned = Purl::parse("pkg:npm/@babel/core@7.0.0").unwrap();
437 assert_eq!(versioned.version(), Some("7.0.0"));
438 }
439
440 #[test]
441 fn canonical_is_idempotent_on_its_own_output() {
442 for text in [
443 "pkg:generic/a%20b@1.0%2B2?checksum=sha1:ab,sha256:cd",
444 "pkg:deb/debian/curl@7.50.3-1?arch=i386&distro=jessie",
445 "pkg:golang/github.com/gorilla/context@234fd47e07d1004f0aed9c#api",
446 "pkg:generic/%E2%82%AC@%C3%A9",
447 ] {
448 let once = Purl::parse(text).unwrap().canonical();
449 let twice = Purl::parse(once.as_str()).unwrap().canonical();
450 assert_eq!(once, twice, "{text}");
451 }
452 }
453
454 #[test]
455 fn rejected_inputs() {
456 let cases: &[(&str, PurlError)] = &[
457 ("EnterpriseLibrary.Common@6.0.1304", PurlError::Scheme),
458 ("http:npm/a", PurlError::Scheme),
459 ("pkg:npm", PurlError::Name),
460 ("pkg:npm/", PurlError::Name),
461 ("pkg:npm/@1.0", PurlError::Name),
462 ("pkg:/a", PurlError::Name),
463 ("pkg:9pm/a", PurlError::Type),
464 ("pkg:n+m/a", PurlError::Type),
465 ("pkg:n%70m/a", PurlError::Type),
466 ("pkg:npm/a?1key=v", PurlError::QualifierKey),
467 ("pkg:npm/a?k%65y=v", PurlError::QualifierKey),
468 ("pkg:npm/a?=v", PurlError::QualifierKey),
469 ("pkg:npm/a?k=1&K=2", PurlError::DuplicateQualifier),
470 ("pkg:npm/a%2Fb/c", PurlError::Namespace),
471 ("pkg:npm/a#b%2Fc", PurlError::Subpath),
472 ("pkg:npm/a%zz", PurlError::Encoding),
473 ("pkg:npm/a%c3", PurlError::Encoding),
474 ("pkg:npm/a@1%", PurlError::Encoding),
475 ];
476 for (text, error) in cases {
477 assert_eq!(Purl::parse(text).as_ref().err(), Some(error), "{text}");
478 }
479 let long = format!("pkg:generic/{}", "a".repeat(MAX_PURL_BYTES));
480 assert_eq!(Purl::parse(&long), Err(PurlError::TooLong));
481 let spaces = format!("pkg:generic/{}", " ".repeat(2000));
483 assert!(spaces.len() <= MAX_PURL_BYTES);
484 assert_eq!(Purl::parse(&spaces), Err(PurlError::TooLong));
485 }
486
487 #[test]
488 fn empty_qualifier_values_are_dropped_and_empty_version_is_none() {
489 let purl = Purl::parse("pkg:generic/a@?x=&y").unwrap();
490 assert_eq!(purl.version(), None);
491 assert_eq!(purl.qualifiers().count(), 0);
492 assert_eq!(purl.canonical().as_str(), "pkg:generic/a");
493 }
494
495 #[test]
496 fn names_are_not_case_folded() {
497 let a = Purl::parse("pkg:pypi/Django@1.11.1").unwrap();
498 let b = Purl::parse("pkg:pypi/django@1.11.1").unwrap();
499 assert!(!same_package_url(&a, &b));
501 }
502}