Skip to main content

libtea_core/
purl.rs

1//! Package URL (ECMA-427) parsing and canonical form, for comparison only.
2//!
3//! **Experimental:** may change in a 0.x minor release.
4//!
5//! TEA asks a client to use a TEI "exactly as received" and to send the `purl`
6//! query parameter as the caller's "logical PURL string". So nothing in this
7//! SDK rewrites a PURL it sends, stores, locks or prints as the server's. This
8//! module exists so a caller can ask whether two PURLs name the same package:
9//! [`Purl`] keeps the text it was parsed from ([`Purl::as_str`]), and the
10//! canonical form is a separate type, [`CanonicalPurl`], that cannot be passed
11//! where a `Purl` is expected.
12//!
13//! Only the rules ECMA-427 gives for every type are applied
14//! ([`PurlRules::Generic`]): lowercase scheme, type and qualifier keys;
15//! percent-encoding normalized; empty qualifier values dropped and keys sorted;
16//! empty, `.` and `..` subpath segments dropped. Type-specific rules (such as
17//! PyPI lowercasing names) are **not** applied, so two spellings that a
18//! type-aware tool would treat as the same package may compare unequal.
19//!
20//! See `docs/design/purl.md` and the test-suite data under `spec/purl/`.
21
22use std::collections::BTreeMap;
23use std::fmt;
24
25use thiserror::Error;
26
27/// Inputs longer than this, or whose canonical form would be, are rejected
28/// with [`PurlError::TooLong`].
29pub const MAX_PURL_BYTES: usize = 4096;
30
31/// Why a string is not a Package URL.
32///
33/// **Experimental:** may change in a 0.x minor release.
34#[derive(Debug, Clone, PartialEq, Eq, Error)]
35#[non_exhaustive]
36pub enum PurlError {
37    /// The text, or its canonical form, is longer than [`MAX_PURL_BYTES`].
38    #[error("Package URL is longer than {MAX_PURL_BYTES} bytes")]
39    TooLong,
40    /// The scheme is missing or is not `pkg`.
41    #[error("Package URL must start with `pkg:`")]
42    Scheme,
43    /// The type is missing, does not start with a letter, or has characters
44    /// other than ASCII letters, digits, `.` and `-`.
45    #[error("Package URL type is missing or invalid")]
46    Type,
47    /// The name is missing.
48    #[error("Package URL name is missing")]
49    Name,
50    /// A namespace segment decodes to text containing `/`.
51    #[error("Package URL namespace segment contains a slash")]
52    Namespace,
53    /// A qualifier key is empty, has characters other than ASCII letters,
54    /// digits, `.`, `-` and `_`, or does not start with a letter.
55    #[error("Package URL qualifier key is invalid")]
56    QualifierKey,
57    /// A qualifier key appears twice.
58    #[error("Package URL qualifier key appears more than once")]
59    DuplicateQualifier,
60    /// A subpath segment decodes to text containing `/`.
61    #[error("Package URL subpath segment contains a slash")]
62    Subpath,
63    /// A `%` not followed by two hex digits, or decoded bytes that are not UTF-8.
64    #[error("Package URL has an invalid percent-encoding")]
65    Encoding,
66    /// The identifier of a `purl` TEI is not unpadded Base64URL of UTF-8 text.
67    #[error("TEI purl identifier is not unpadded Base64URL of UTF-8 text")]
68    TeiIdentifier,
69}
70
71/// Which canonicalization rules produced a [`CanonicalPurl`].
72///
73/// **Experimental:** may change in a 0.x minor release.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
75#[non_exhaustive]
76pub enum PurlRules {
77    /// The rules ECMA-427 gives for every type, and nothing type-specific.
78    Generic,
79}
80
81/// A parsed Package URL. Holds the original text and never rewrites it.
82///
83/// **Experimental:** may change in a 0.x minor release.
84///
85/// Equality compares the original text and components exactly. To ask
86/// whether two spellings name the same package, compare
87/// [`Purl::canonical`] values or use [`same_package_url`].
88///
89/// ```
90/// use libtea_core::purl::{same_package_url, Purl};
91///
92/// let a = Purl::parse("PKG:Maven/org.apache/commons-io@2.11.0?Type=jar&classifier=").unwrap();
93/// let b = Purl::parse("pkg:maven/org.apache/commons-io@2.11.0?type=jar").unwrap();
94/// assert_eq!(a.as_str(), "PKG:Maven/org.apache/commons-io@2.11.0?Type=jar&classifier=");
95/// assert_eq!(a.canonical().as_str(), "pkg:maven/org.apache/commons-io@2.11.0?type=jar");
96/// assert!(same_package_url(&a, &b));
97/// ```
98#[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/// A PURL in canonical form under [`Self::rules`]. Comparable and hashable.
110///
111/// **Experimental:** may change in a 0.x minor release.
112///
113/// It is computed from a [`Purl`] and cannot be turned back into one without
114/// parsing, so it cannot be sent by mistake where the original was meant.
115#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
116pub struct CanonicalPurl(String);
117
118impl CanonicalPurl {
119    /// The canonical text.
120    #[must_use]
121    pub fn as_str(&self) -> &str {
122        &self.0
123    }
124
125    /// The rules that were applied. Always [`PurlRules::Generic`] for now.
126    #[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/// Whether two PURLs have the same canonical form under the generic rules.
139#[must_use]
140pub fn same_package_url(a: &Purl, b: &Purl) -> bool {
141    a.canonical() == b.canonical()
142}
143
144impl Purl {
145    /// Parse a Package URL as ECMA-427 describes, right to left.
146    ///
147    /// Accepts what the specification says a parser should accept, such as
148    /// `pkg://` and redundant slashes, and keeps `text` unchanged for
149    /// [`Self::as_str`].
150    ///
151    /// # Errors
152    ///
153    /// Returns [`PurlError`] when a required component is missing, a type or
154    /// qualifier key has characters ECMA-427 does not allow, a qualifier key
155    /// repeats, a decoded namespace or subpath segment contains `/`, the
156    /// percent-encoding is invalid, or the text or its canonical form is
157    /// longer than [`MAX_PURL_BYTES`].
158    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        // The version separator is the last '@' of the last path segment, so an
181        // unencoded '@' that starts a namespace segment (`pkg:npm/@babel/core`)
182        // is not taken for one. A version's own '/' is percent-encoded.
183        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        // Percent-encoding can triple a component's length. Refusing here keeps
219        // the promise that every canonical form parses again.
220        if purl.canonical().0.len() > MAX_PURL_BYTES {
221            return Err(PurlError::TooLong);
222        }
223        Ok(purl)
224    }
225
226    /// Exactly the text that was parsed.
227    #[must_use]
228    pub fn as_str(&self) -> &str {
229        &self.original
230    }
231
232    /// The type, lowercased.
233    #[must_use]
234    pub fn package_type(&self) -> &str {
235        &self.package_type
236    }
237
238    /// The decoded namespace segments joined with `/`, or `None` when there
239    /// are none. No type-specific normalization is applied.
240    #[must_use]
241    pub fn namespace(&self) -> Option<String> {
242        (!self.namespace.is_empty()).then(|| self.namespace.join("/"))
243    }
244
245    /// The decoded name. No type-specific normalization is applied.
246    #[must_use]
247    pub fn name(&self) -> &str {
248        &self.name
249    }
250
251    /// The decoded version, or `None` when absent or empty.
252    #[must_use]
253    pub fn version(&self) -> Option<&str> {
254        self.version.as_deref()
255    }
256
257    /// Decoded qualifiers with non-empty values, keys lowercased, in key order.
258    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    /// The decoded value of one qualifier; `key` is matched in lowercase.
265    #[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    /// The decoded subpath segments joined with `/`, without empty, `.` and
273    /// `..` segments, or `None` when none remain.
274    #[must_use]
275    pub fn subpath(&self) -> Option<String> {
276        (!self.subpath.is_empty()).then(|| self.subpath.join("/"))
277    }
278
279    /// The canonical form under [`PurlRules::Generic`].
280    #[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
309/// ECMA-427 5.6.2: ASCII letters, digits, `.` and `-`, starting with a letter.
310fn 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
316/// ECMA-427 5.6.6, keys already lowercased: letters, digits, `.`, `-` and `_`,
317/// starting with a letter.
318fn 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
392/// ECMA-427 5.4: alphanumerics, `.-_~` and `:` stay; every other UTF-8 octet
393/// becomes `%XX` with uppercase hex.
394fn 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        // Short enough as text, too long once each space becomes `%20`.
482        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        // PyPI names are case-insensitive, but that is a type-specific rule.
500        assert!(!same_package_url(&a, &b));
501    }
502}