1use std::collections::BTreeMap;
24use std::fmt;
25
26use thiserror::Error;
27
28pub const MAX_PURL_BYTES: usize = 4096;
31
32#[derive(Debug, Clone, PartialEq, Eq, Error)]
36#[non_exhaustive]
37pub enum PurlError {
38 #[error("Package URL is longer than {MAX_PURL_BYTES} bytes")]
40 TooLong,
41 #[error("Package URL must start with `pkg:`")]
43 Scheme,
44 #[error("Package URL type is missing or invalid")]
47 Type,
48 #[error("Package URL name is missing")]
50 Name,
51 #[error("Package URL namespace segment contains a slash")]
53 Namespace,
54 #[error("Package URL qualifier key is invalid")]
57 QualifierKey,
58 #[error("Package URL qualifier key appears more than once")]
60 DuplicateQualifier,
61 #[error("Package URL subpath segment contains a slash")]
63 Subpath,
64 #[error("Package URL has an invalid percent-encoding")]
66 Encoding,
67 #[error("TEI purl identifier is not unpadded Base64URL of UTF-8 text")]
69 TeiIdentifier,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
77#[non_exhaustive]
78pub enum PurlRules {
79 Generic,
81 Pypi,
87}
88
89impl PurlRules {
90 fn for_type(package_type: &str) -> Self {
92 match package_type {
93 "pypi" => Self::Pypi,
94 _ => Self::Generic,
95 }
96 }
97}
98
99#[derive(Debug, Clone, PartialEq, Eq, Hash)]
117pub struct Purl {
118 original: String,
119 package_type: String,
120 namespace: Vec<String>,
121 name: String,
122 version: Option<String>,
123 qualifiers: BTreeMap<String, String>,
124 subpath: Vec<String>,
125}
126
127#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
137pub struct CanonicalPurl {
138 text: String,
139 rules: PurlRules,
140}
141
142impl CanonicalPurl {
143 #[must_use]
145 pub fn as_str(&self) -> &str {
146 &self.text
147 }
148
149 #[must_use]
152 pub fn rules(&self) -> PurlRules {
153 self.rules
154 }
155}
156
157impl fmt::Display for CanonicalPurl {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 f.write_str(&self.text)
160 }
161}
162
163#[must_use]
165pub fn same_package_url(a: &Purl, b: &Purl) -> bool {
166 a.canonical() == b.canonical()
167}
168
169impl Purl {
170 pub fn parse(text: &str) -> Result<Self, PurlError> {
184 if text.len() > MAX_PURL_BYTES {
185 return Err(PurlError::TooLong);
186 }
187 let (remainder, subpath) = match text.rsplit_once('#') {
188 Some((left, right)) => (left, parse_subpath(right)?),
189 None => (text, Vec::new()),
190 };
191 let (remainder, qualifiers) = match remainder.rsplit_once('?') {
192 Some((left, right)) => (left, parse_qualifiers(right)?),
193 None => (remainder, BTreeMap::new()),
194 };
195 let (scheme, remainder) = remainder.split_once(':').ok_or(PurlError::Scheme)?;
196 if !scheme.eq_ignore_ascii_case("pkg") {
197 return Err(PurlError::Scheme);
198 }
199 let remainder = remainder.trim_start_matches('/');
200 let (package_type, remainder) = remainder.split_once('/').ok_or(PurlError::Name)?;
201 let package_type = package_type.to_ascii_lowercase();
202 if !valid_type(&package_type) {
203 return Err(PurlError::Type);
204 }
205 let last_segment = remainder.rfind('/').map_or(0, |index| index + 1);
209 let (remainder, version) = match remainder[last_segment..].rfind('@') {
210 Some(at) => {
211 let at = last_segment + at;
212 let version = percent_decode(&remainder[at + 1..])?;
213 (&remainder[..at], (!version.is_empty()).then_some(version))
214 }
215 None => (remainder, None),
216 };
217 let remainder = remainder.trim_end_matches('/');
218 let (remainder, name) = match remainder.rsplit_once('/') {
219 Some((left, right)) => (left, right),
220 None => ("", remainder),
221 };
222 let name = percent_decode(name)?;
223 if name.is_empty() {
224 return Err(PurlError::Name);
225 }
226 let mut namespace = Vec::new();
227 for segment in remainder.split('/').filter(|segment| !segment.is_empty()) {
228 let segment = percent_decode(segment)?;
229 if segment.contains('/') {
230 return Err(PurlError::Namespace);
231 }
232 namespace.push(segment);
233 }
234 let purl = Self {
235 original: text.to_owned(),
236 package_type,
237 namespace,
238 name,
239 version,
240 qualifiers,
241 subpath,
242 };
243 if purl.canonical().text.len() > MAX_PURL_BYTES {
246 return Err(PurlError::TooLong);
247 }
248 Ok(purl)
249 }
250
251 #[must_use]
253 pub fn as_str(&self) -> &str {
254 &self.original
255 }
256
257 #[must_use]
259 pub fn package_type(&self) -> &str {
260 &self.package_type
261 }
262
263 #[must_use]
267 pub fn namespace(&self) -> Option<String> {
268 (!self.namespace.is_empty()).then(|| self.namespace.join("/"))
269 }
270
271 #[must_use]
274 pub fn name(&self) -> &str {
275 &self.name
276 }
277
278 #[must_use]
280 pub fn version(&self) -> Option<&str> {
281 self.version.as_deref()
282 }
283
284 pub fn qualifiers(&self) -> impl Iterator<Item = (&str, &str)> {
286 self.qualifiers
287 .iter()
288 .map(|(key, value)| (key.as_str(), value.as_str()))
289 }
290
291 #[must_use]
293 pub fn qualifier(&self, key: &str) -> Option<&str> {
294 self.qualifiers
295 .get(&key.to_ascii_lowercase())
296 .map(String::as_str)
297 }
298
299 #[must_use]
302 pub fn subpath(&self) -> Option<String> {
303 (!self.subpath.is_empty()).then(|| self.subpath.join("/"))
304 }
305
306 #[must_use]
319 pub fn canonical(&self) -> CanonicalPurl {
320 let rules = PurlRules::for_type(&self.package_type);
321 let mut out = String::with_capacity(self.original.len());
322 out.push_str("pkg:");
323 out.push_str(&self.package_type);
324 out.push('/');
325 for segment in &self.namespace {
326 percent_encode_into(segment, &mut out);
327 out.push('/');
328 }
329 match rules {
330 PurlRules::Pypi => percent_encode_into(&pypi_name(&self.name), &mut out),
331 PurlRules::Generic => percent_encode_into(&self.name, &mut out),
332 }
333 if let Some(version) = &self.version {
334 out.push('@');
335 match rules {
336 PurlRules::Pypi => percent_encode_into(&version.to_ascii_lowercase(), &mut out),
337 PurlRules::Generic => percent_encode_into(version, &mut out),
338 }
339 }
340 for (index, (key, value)) in self.qualifiers.iter().enumerate() {
341 out.push(if index == 0 { '?' } else { '&' });
342 out.push_str(key);
343 out.push('=');
344 percent_encode_into(value, &mut out);
345 }
346 for (index, segment) in self.subpath.iter().enumerate() {
347 out.push(if index == 0 { '#' } else { '/' });
348 percent_encode_into(segment, &mut out);
349 }
350 CanonicalPurl { text: out, rules }
351 }
352}
353
354fn pypi_name(name: &str) -> String {
356 let mut out = String::with_capacity(name.len());
357 let mut in_run = false;
358 for c in name.chars() {
359 if matches!(c, '-' | '_' | '.') {
360 if !in_run {
361 out.push('-');
362 }
363 in_run = true;
364 } else {
365 out.push(c.to_ascii_lowercase());
366 in_run = false;
367 }
368 }
369 out
370}
371
372fn valid_type(package_type: &str) -> bool {
374 let mut chars = package_type.chars();
375 chars.next().is_some_and(|c| c.is_ascii_alphabetic())
376 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-'))
377}
378
379fn valid_qualifier_key(key: &str) -> bool {
382 let mut chars = key.chars();
383 chars.next().is_some_and(|c| c.is_ascii_lowercase())
384 && chars
385 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '-' | '_'))
386}
387
388fn parse_qualifiers(text: &str) -> Result<BTreeMap<String, String>, PurlError> {
389 let mut qualifiers = BTreeMap::new();
390 for pair in text.split('&').filter(|pair| !pair.is_empty()) {
391 let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
392 let key = key.to_ascii_lowercase();
393 if !valid_qualifier_key(&key) {
394 return Err(PurlError::QualifierKey);
395 }
396 let value = percent_decode(value)?;
397 if value.is_empty() {
398 continue;
399 }
400 if qualifiers.insert(key, value).is_some() {
401 return Err(PurlError::DuplicateQualifier);
402 }
403 }
404 Ok(qualifiers)
405}
406
407fn parse_subpath(text: &str) -> Result<Vec<String>, PurlError> {
408 let mut segments = Vec::new();
409 for segment in text.split('/') {
410 let segment = percent_decode(segment)?;
411 if segment.is_empty() || segment == "." || segment == ".." {
412 continue;
413 }
414 if segment.contains('/') {
415 return Err(PurlError::Subpath);
416 }
417 segments.push(segment);
418 }
419 Ok(segments)
420}
421
422fn percent_decode(text: &str) -> Result<String, PurlError> {
423 if !text.contains('%') {
424 return Ok(text.to_owned());
425 }
426 let bytes = text.as_bytes();
427 let mut out = Vec::with_capacity(bytes.len());
428 let mut index = 0;
429 while index < bytes.len() {
430 if bytes[index] == b'%' {
431 let high = bytes.get(index + 1).and_then(|b| hex_value(*b));
432 let low = bytes.get(index + 2).and_then(|b| hex_value(*b));
433 let (Some(high), Some(low)) = (high, low) else {
434 return Err(PurlError::Encoding);
435 };
436 out.push(high << 4 | low);
437 index += 3;
438 } else {
439 out.push(bytes[index]);
440 index += 1;
441 }
442 }
443 String::from_utf8(out).map_err(|_| PurlError::Encoding)
444}
445
446fn hex_value(byte: u8) -> Option<u8> {
447 match byte {
448 b'0'..=b'9' => Some(byte - b'0'),
449 b'a'..=b'f' => Some(byte - b'a' + 10),
450 b'A'..=b'F' => Some(byte - b'A' + 10),
451 _ => None,
452 }
453}
454
455fn percent_encode_into(text: &str, out: &mut String) {
458 const HEX: &[u8; 16] = b"0123456789ABCDEF";
459 for &byte in text.as_bytes() {
460 if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_' | b'~' | b':') {
461 out.push(char::from(byte));
462 } else {
463 out.push('%');
464 out.push(char::from(HEX[usize::from(byte >> 4)]));
465 out.push(char::from(HEX[usize::from(byte & 0x0f)]));
466 }
467 }
468}
469
470#[cfg(test)]
471mod tests {
472 use super::*;
473
474 #[test]
475 fn original_text_is_kept_and_canonical_is_separate() {
476 let text = "pkg://NPM//%40angular/animation@12.3.1?B=2&a=1#/x/./y/";
477 let purl = Purl::parse(text).unwrap();
478 assert_eq!(purl.as_str(), text);
479 assert_eq!(purl.package_type(), "npm");
480 assert_eq!(purl.namespace().as_deref(), Some("@angular"));
481 assert_eq!(purl.name(), "animation");
482 assert_eq!(purl.version(), Some("12.3.1"));
483 assert_eq!(purl.qualifier("A"), Some("1"));
484 assert_eq!(purl.subpath().as_deref(), Some("x/y"));
485 assert_eq!(
486 purl.canonical().as_str(),
487 "pkg:npm/%40angular/animation@12.3.1?a=1&b=2#x/y"
488 );
489 assert_eq!(purl.canonical().rules(), PurlRules::Generic);
490 }
491
492 #[test]
493 fn an_unencoded_scope_is_not_a_version() {
494 let purl = Purl::parse("pkg:npm/@babel/core#lib").unwrap();
495 assert_eq!(purl.namespace().as_deref(), Some("@babel"));
496 assert_eq!(purl.name(), "core");
497 assert_eq!(purl.version(), None);
498 assert_eq!(purl.canonical().as_str(), "pkg:npm/%40babel/core#lib");
499 let versioned = Purl::parse("pkg:npm/@babel/core@7.0.0").unwrap();
500 assert_eq!(versioned.version(), Some("7.0.0"));
501 }
502
503 #[test]
504 fn canonical_is_idempotent_on_its_own_output() {
505 for text in [
506 "pkg:generic/a%20b@1.0%2B2?checksum=sha1:ab,sha256:cd",
507 "pkg:deb/debian/curl@7.50.3-1?arch=i386&distro=jessie",
508 "pkg:golang/github.com/gorilla/context@234fd47e07d1004f0aed9c#api",
509 "pkg:generic/%E2%82%AC@%C3%A9",
510 ] {
511 let once = Purl::parse(text).unwrap().canonical();
512 let twice = Purl::parse(once.as_str()).unwrap().canonical();
513 assert_eq!(once, twice, "{text}");
514 }
515 }
516
517 #[test]
518 fn rejected_inputs() {
519 let cases: &[(&str, PurlError)] = &[
520 ("EnterpriseLibrary.Common@6.0.1304", PurlError::Scheme),
521 ("http:npm/a", PurlError::Scheme),
522 ("pkg:npm", PurlError::Name),
523 ("pkg:npm/", PurlError::Name),
524 ("pkg:npm/@1.0", PurlError::Name),
525 ("pkg:/a", PurlError::Name),
526 ("pkg:9pm/a", PurlError::Type),
527 ("pkg:n+m/a", PurlError::Type),
528 ("pkg:n%70m/a", PurlError::Type),
529 ("pkg:npm/a?1key=v", PurlError::QualifierKey),
530 ("pkg:npm/a?k%65y=v", PurlError::QualifierKey),
531 ("pkg:npm/a?=v", PurlError::QualifierKey),
532 ("pkg:npm/a?k=1&K=2", PurlError::DuplicateQualifier),
533 ("pkg:npm/a%2Fb/c", PurlError::Namespace),
534 ("pkg:npm/a#b%2Fc", PurlError::Subpath),
535 ("pkg:npm/a%zz", PurlError::Encoding),
536 ("pkg:npm/a%c3", PurlError::Encoding),
537 ("pkg:npm/a@1%", PurlError::Encoding),
538 ];
539 for (text, error) in cases {
540 assert_eq!(Purl::parse(text).as_ref().err(), Some(error), "{text}");
541 }
542 let long = format!("pkg:generic/{}", "a".repeat(MAX_PURL_BYTES));
543 assert_eq!(Purl::parse(&long), Err(PurlError::TooLong));
544 let spaces = format!("pkg:generic/{}", " ".repeat(2000));
546 assert!(spaces.len() <= MAX_PURL_BYTES);
547 assert_eq!(Purl::parse(&spaces), Err(PurlError::TooLong));
548 }
549
550 #[test]
551 fn empty_qualifier_values_are_dropped_and_empty_version_is_none() {
552 let purl = Purl::parse("pkg:generic/a@?x=&y").unwrap();
553 assert_eq!(purl.version(), None);
554 assert_eq!(purl.qualifiers().count(), 0);
555 assert_eq!(purl.canonical().as_str(), "pkg:generic/a");
556 }
557
558 #[test]
559 fn names_are_not_case_folded_without_a_type_rule() {
560 for (a, b) in [
562 ("pkg:npm/Lodash@4.0.0", "pkg:npm/lodash@4.0.0"),
563 (
564 "pkg:maven/org.Apache/Commons@1",
565 "pkg:maven/org.apache/commons@1",
566 ),
567 ("pkg:generic/a_b@1", "pkg:generic/a-b@1"),
568 ] {
569 let (a, b) = (Purl::parse(a).unwrap(), Purl::parse(b).unwrap());
570 assert!(!same_package_url(&a, &b));
571 assert_eq!(a.canonical().rules(), PurlRules::Generic);
572 }
573 }
574
575 #[test]
576 fn pypi_names_and_versions_follow_the_type_definition() {
577 for (input, canonical) in [
578 ("pkg:pypi/Django@1.11.1", "pkg:pypi/django@1.11.1"),
579 ("pkg:pypi/friendly.bard@1.0", "pkg:pypi/friendly-bard@1.0"),
580 ("pkg:pypi/friendly--bard", "pkg:pypi/friendly-bard"),
581 (
582 "pkg:pypi/My.PyPI_.--._Package@1.11.1.DEV1",
583 "pkg:pypi/my-pypi-package@1.11.1.dev1",
584 ),
585 ("pkg:pypi/-a_", "pkg:pypi/-a-"),
586 ("pkg:pypi/a%2Eb", "pkg:pypi/a-b"),
587 (
589 "pkg:pypi/Django@1.0?file_name=Django-1.0.tar.gz#Docs",
590 "pkg:pypi/django@1.0?file_name=Django-1.0.tar.gz#Docs",
591 ),
592 ] {
593 let purl = Purl::parse(input).unwrap();
594 assert_eq!(purl.as_str(), input);
595 assert_eq!(purl.canonical().as_str(), canonical, "{input}");
596 assert_eq!(purl.canonical().rules(), PurlRules::Pypi);
597 let again = Purl::parse(canonical).unwrap().canonical();
598 assert_eq!(again.as_str(), canonical, "idempotent: {input}");
599 }
600 let a = Purl::parse("pkg:pypi/Zope.Interface@5.0").unwrap();
601 let b = Purl::parse("pkg:pypi/zope-interface@5.0").unwrap();
602 assert!(same_package_url(&a, &b));
603 assert_eq!(a.name(), "Zope.Interface");
605 }
606}