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//! The rules ECMA-427 gives for every type are always 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. On top of those, the
17//! components a purl-spec type definition marks case-insensitive are
18//! lowercased ([`PurlRules::CaseInsensitive`]), and `pypi` names follow
19//! PEP 503 ([`PurlRules::Pypi`]). Rules the definitions give only in prose
20//! (for example `hackage`'s "kebab-case", `pub`'s underscores or `cpan`'s
21//! uppercase author) are not applied, so two spellings that a type-aware tool
22//! would treat as the same package may still compare unequal.
23//! [`CanonicalPurl::rules`] says which rules applied.
24//!
25//! [`Purl::check_type`] checks the requirements the definitions give as data:
26//! a required or prohibited namespace, required qualifiers, and the
27//! permitted characters of a name or version. [`Purl::parse`] does not apply
28//! them, so a PURL its type does not allow still parses.
29//!
30//! See `docs/design/purl.md` and the test-suite data under `spec/purl/`.
31
32use std::collections::BTreeMap;
33use std::fmt;
34
35use thiserror::Error;
36
37/// Inputs longer than this, or whose canonical form would be, are rejected
38/// with [`PurlError::TooLong`].
39pub const MAX_PURL_BYTES: usize = 4096;
40
41/// Why a string is not a Package URL.
42///
43/// **Experimental:** may change in a 0.x minor release.
44#[derive(Debug, Clone, PartialEq, Eq, Error)]
45#[non_exhaustive]
46pub enum PurlError {
47    /// The text, or its canonical form, is longer than [`MAX_PURL_BYTES`].
48    #[error("Package URL is longer than {MAX_PURL_BYTES} bytes")]
49    TooLong,
50    /// The scheme is missing or is not `pkg`.
51    #[error("Package URL must start with `pkg:`")]
52    Scheme,
53    /// The type is missing, does not start with a letter, or has characters
54    /// other than ASCII letters, digits, `.` and `-`.
55    #[error("Package URL type is missing or invalid")]
56    Type,
57    /// The name is missing.
58    #[error("Package URL name is missing")]
59    Name,
60    /// A namespace segment decodes to text containing `/`.
61    #[error("Package URL namespace segment contains a slash")]
62    Namespace,
63    /// A qualifier key is empty, has characters other than ASCII letters,
64    /// digits, `.`, `-` and `_`, or does not start with a letter.
65    #[error("Package URL qualifier key is invalid")]
66    QualifierKey,
67    /// A qualifier key appears twice.
68    #[error("Package URL qualifier key appears more than once")]
69    DuplicateQualifier,
70    /// A subpath segment decodes to text containing `/`.
71    #[error("Package URL subpath segment contains a slash")]
72    Subpath,
73    /// A `%` not followed by two hex digits, or decoded bytes that are not UTF-8.
74    #[error("Package URL has an invalid percent-encoding")]
75    Encoding,
76    /// The identifier of a `purl` TEI is not unpadded Base64URL of UTF-8 text.
77    #[error("TEI purl identifier is not unpadded Base64URL of UTF-8 text")]
78    TeiIdentifier,
79}
80
81/// Which canonicalization rules produced a [`CanonicalPurl`].
82///
83/// **Experimental:** may change in a 0.x minor release. A type that gains
84/// rules gets a new variant, so its canonical form changes in that release.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
86#[non_exhaustive]
87pub enum PurlRules {
88    /// The rules ECMA-427 gives for every type, and nothing type-specific.
89    Generic,
90    /// The generic rules, plus those of the purl-spec `pypi` type definition:
91    /// the name is lowercased and each run of `-`, `_` and `.` becomes one
92    /// `-` (PEP 503), and the version, which the definition marks
93    /// case-insensitive, is lowercased. Only ASCII letters are lowercased;
94    /// valid PyPI names and versions are ASCII.
95    Pypi,
96    /// The generic rules, plus lowercasing every component (namespace, name,
97    /// version or subpath) that the purl-spec type definition marks
98    /// `"case_sensitive": false`, for example the namespace and name of
99    /// `github`, `deb` and `composer` PURLs. Only ASCII letters are lowercased.
100    CaseInsensitive,
101}
102
103impl PurlRules {
104    /// The rules for a lowercased type.
105    fn for_type(package_type: &str) -> Self {
106        match (package_type, type_rule(package_type)) {
107            ("pypi", _) => Self::Pypi,
108            (_, Some(rule)) if rule.lowercase != 0 => Self::CaseInsensitive,
109            _ => Self::Generic,
110        }
111    }
112}
113
114/// Why a PURL breaks a rule of its purl-spec type definition
115/// ([`Purl::check_type`]).
116///
117/// **Experimental:** may change in a 0.x minor release.
118#[derive(Debug, Clone, PartialEq, Eq, Error)]
119#[non_exhaustive]
120pub enum PurlTypeError {
121    /// The type requires a namespace and there is none.
122    #[error("this Package URL type requires a namespace")]
123    NamespaceRequired,
124    /// The type has no namespace and one is given.
125    #[error("this Package URL type does not allow a namespace")]
126    NamespaceProhibited,
127    /// A qualifier the type requires is missing.
128    #[error("this Package URL type requires the qualifier `{0}`")]
129    QualifierRequired(&'static str),
130    /// The name has characters the type does not permit.
131    #[error("the Package URL name has characters this type does not permit")]
132    NameCharacters,
133    /// The version has characters the type does not permit.
134    #[error("the Package URL version has characters this type does not permit")]
135    VersionCharacters,
136}
137
138const NAMESPACE: u8 = 1;
139const NAME: u8 = 2;
140const VERSION: u8 = 4;
141const SUBPATH: u8 = 8;
142
143#[derive(Clone, Copy)]
144enum Requirement {
145    Required,
146    Prohibited,
147    Optional,
148}
149
150/// What a purl-spec type definition (`spec/purl/types/`) gives as data,
151/// except `permitted_characters` (see [`check_characters`]). Sorted by type.
152/// `tests/purl_spec_suite.rs` checks it against the vendored definitions.
153struct TypeRule {
154    package_type: &'static str,
155    /// The components marked `"case_sensitive": false`.
156    lowercase: u8,
157    namespace: Requirement,
158    required_qualifiers: &'static [&'static str],
159}
160
161#[rustfmt::skip]
162const TYPE_RULES: &[TypeRule] = &[
163    TypeRule { package_type: "alpm", lowercase: NAMESPACE | NAME, namespace: Requirement::Required, required_qualifiers: &[] },
164    TypeRule { package_type: "apk", lowercase: NAMESPACE | NAME, namespace: Requirement::Required, required_qualifiers: &[] },
165    TypeRule { package_type: "bazel", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
166    TypeRule { package_type: "bitbucket", lowercase: NAMESPACE | NAME, namespace: Requirement::Required, required_qualifiers: &[] },
167    TypeRule { package_type: "bitnami", lowercase: NAME, namespace: Requirement::Prohibited, required_qualifiers: &[] },
168    TypeRule { package_type: "brew", lowercase: NAMESPACE | NAME, namespace: Requirement::Optional, required_qualifiers: &[] },
169    TypeRule { package_type: "cargo", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
170    TypeRule { package_type: "chrome-extension", lowercase: NAME, namespace: Requirement::Prohibited, required_qualifiers: &[] },
171    TypeRule { package_type: "cocoapods", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
172    TypeRule { package_type: "composer", lowercase: NAMESPACE | NAME, namespace: Requirement::Required, required_qualifiers: &[] },
173    TypeRule { package_type: "conan", lowercase: 0, namespace: Requirement::Optional, required_qualifiers: &[] },
174    TypeRule { package_type: "conda", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
175    TypeRule { package_type: "cpan", lowercase: 0, namespace: Requirement::Optional, required_qualifiers: &[] },
176    TypeRule { package_type: "cran", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
177    TypeRule { package_type: "deb", lowercase: NAMESPACE | NAME, namespace: Requirement::Required, required_qualifiers: &[] },
178    TypeRule { package_type: "docker", lowercase: 0, namespace: Requirement::Optional, required_qualifiers: &[] },
179    TypeRule { package_type: "gem", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
180    TypeRule { package_type: "generic", lowercase: 0, namespace: Requirement::Optional, required_qualifiers: &[] },
181    TypeRule { package_type: "git", lowercase: 0, namespace: Requirement::Required, required_qualifiers: &[] },
182    TypeRule { package_type: "github", lowercase: NAMESPACE | NAME, namespace: Requirement::Required, required_qualifiers: &[] },
183    TypeRule { package_type: "golang", lowercase: 0, namespace: Requirement::Required, required_qualifiers: &[] },
184    TypeRule { package_type: "hackage", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
185    TypeRule { package_type: "hex", lowercase: NAMESPACE | NAME, namespace: Requirement::Optional, required_qualifiers: &[] },
186    TypeRule { package_type: "huggingface", lowercase: VERSION, namespace: Requirement::Required, required_qualifiers: &[] },
187    TypeRule { package_type: "julia", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &["uuid"] },
188    TypeRule { package_type: "luarocks", lowercase: NAMESPACE | NAME, namespace: Requirement::Optional, required_qualifiers: &[] },
189    TypeRule { package_type: "maven", lowercase: 0, namespace: Requirement::Required, required_qualifiers: &[] },
190    TypeRule { package_type: "mlflow", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
191    TypeRule { package_type: "npm", lowercase: 0, namespace: Requirement::Optional, required_qualifiers: &[] },
192    TypeRule { package_type: "nuget", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
193    TypeRule { package_type: "oci", lowercase: NAME | VERSION, namespace: Requirement::Prohibited, required_qualifiers: &[] },
194    TypeRule { package_type: "opam", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
195    TypeRule { package_type: "otp", lowercase: NAME | SUBPATH, namespace: Requirement::Prohibited, required_qualifiers: &[] },
196    TypeRule { package_type: "pub", lowercase: NAME, namespace: Requirement::Prohibited, required_qualifiers: &[] },
197    TypeRule { package_type: "pypi", lowercase: NAME | VERSION, namespace: Requirement::Prohibited, required_qualifiers: &[] },
198    TypeRule { package_type: "qpkg", lowercase: NAMESPACE, namespace: Requirement::Required, required_qualifiers: &[] },
199    TypeRule { package_type: "rpm", lowercase: NAMESPACE, namespace: Requirement::Required, required_qualifiers: &[] },
200    TypeRule { package_type: "swid", lowercase: 0, namespace: Requirement::Optional, required_qualifiers: &["tag_id"] },
201    TypeRule { package_type: "swift", lowercase: 0, namespace: Requirement::Required, required_qualifiers: &[] },
202    TypeRule { package_type: "vcpkg", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
203    TypeRule { package_type: "vscode-extension", lowercase: NAMESPACE | NAME | VERSION, namespace: Requirement::Required, required_qualifiers: &[] },
204    TypeRule { package_type: "yocto", lowercase: NAMESPACE, namespace: Requirement::Optional, required_qualifiers: &[] },
205];
206
207fn type_rule(package_type: &str) -> Option<&'static TypeRule> {
208    TYPE_RULES
209        .binary_search_by(|rule| rule.package_type.cmp(package_type))
210        .ok()
211        .map(|index| &TYPE_RULES[index])
212}
213
214/// The `permitted_characters` patterns of the definitions, written out:
215/// `chrome-extension` name `^[a-p]{32}$` and version `^\d+(\.\d+){0,3}$`, and
216/// `pub` name `^[a-z0-9_]` (as written, it constrains the first character
217/// only). The name is checked after case folding, as the definitions mark both
218/// names case-insensitive.
219fn check_characters(
220    package_type: &str,
221    name: &str,
222    version: Option<&str>,
223) -> Result<(), PurlTypeError> {
224    let name = name.to_ascii_lowercase();
225    let name_ok = match package_type {
226        "chrome-extension" => name.len() == 32 && name.bytes().all(|b| (b'a'..=b'p').contains(&b)),
227        "pub" => name
228            .bytes()
229            .next()
230            .is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'),
231        _ => true,
232    };
233    if !name_ok {
234        return Err(PurlTypeError::NameCharacters);
235    }
236    let version_ok = match (package_type, version) {
237        ("chrome-extension", Some(version)) => {
238            let parts: Vec<_> = version.split('.').collect();
239            parts.len() <= 4
240                && parts
241                    .iter()
242                    .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()))
243        }
244        _ => true,
245    };
246    if !version_ok {
247        return Err(PurlTypeError::VersionCharacters);
248    }
249    Ok(())
250}
251
252/// A parsed Package URL. Holds the original text and never rewrites it.
253///
254/// **Experimental:** may change in a 0.x minor release.
255///
256/// Equality compares the original text and components exactly. To ask
257/// whether two spellings name the same package, compare
258/// [`Purl::canonical`] values or use [`same_package_url`].
259///
260/// ```
261/// use libtea_core::purl::{same_package_url, Purl};
262///
263/// let a = Purl::parse("PKG:Maven/org.apache/commons-io@2.11.0?Type=jar&classifier=").unwrap();
264/// let b = Purl::parse("pkg:maven/org.apache/commons-io@2.11.0?type=jar").unwrap();
265/// assert_eq!(a.as_str(), "PKG:Maven/org.apache/commons-io@2.11.0?Type=jar&classifier=");
266/// assert_eq!(a.canonical().as_str(), "pkg:maven/org.apache/commons-io@2.11.0?type=jar");
267/// assert!(same_package_url(&a, &b));
268/// ```
269#[derive(Debug, Clone, PartialEq, Eq, Hash)]
270pub struct Purl {
271    original: String,
272    package_type: String,
273    namespace: Vec<String>,
274    name: String,
275    version: Option<String>,
276    qualifiers: BTreeMap<String, String>,
277    subpath: Vec<String>,
278}
279
280/// A PURL in canonical form under [`Self::rules`]. Comparable and hashable.
281///
282/// **Experimental:** may change in a 0.x minor release.
283///
284/// It is computed from a [`Purl`] and cannot be turned back into one without
285/// parsing, so it cannot be sent by mistake where the original was meant.
286///
287/// Equality, hashing and ordering compare the text. The rules follow from the
288/// type in it, so equal texts always have equal rules.
289#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
290pub struct CanonicalPurl {
291    text: String,
292    rules: PurlRules,
293}
294
295impl CanonicalPurl {
296    /// The canonical text.
297    #[must_use]
298    pub fn as_str(&self) -> &str {
299        &self.text
300    }
301
302    /// The rules that were applied: [`PurlRules::Generic`], or the
303    /// type-specific variant for a type that has one.
304    #[must_use]
305    pub fn rules(&self) -> PurlRules {
306        self.rules
307    }
308}
309
310impl fmt::Display for CanonicalPurl {
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        f.write_str(&self.text)
313    }
314}
315
316/// Whether two PURLs have the same canonical form ([`Purl::canonical`]).
317#[must_use]
318pub fn same_package_url(a: &Purl, b: &Purl) -> bool {
319    a.canonical() == b.canonical()
320}
321
322impl Purl {
323    /// Parse a Package URL as ECMA-427 describes, right to left.
324    ///
325    /// Accepts what the specification says a parser should accept, such as
326    /// `pkg://` and redundant slashes, and keeps `text` unchanged for
327    /// [`Self::as_str`].
328    ///
329    /// # Errors
330    ///
331    /// Returns [`PurlError`] when a required component is missing, a type or
332    /// qualifier key has characters ECMA-427 does not allow, a qualifier key
333    /// repeats, a decoded namespace or subpath segment contains `/`, the
334    /// percent-encoding is invalid, or the text or its canonical form is
335    /// longer than [`MAX_PURL_BYTES`].
336    pub fn parse(text: &str) -> Result<Self, PurlError> {
337        if text.len() > MAX_PURL_BYTES {
338            return Err(PurlError::TooLong);
339        }
340        let (remainder, subpath) = match text.rsplit_once('#') {
341            Some((left, right)) => (left, parse_subpath(right)?),
342            None => (text, Vec::new()),
343        };
344        let (remainder, qualifiers) = match remainder.rsplit_once('?') {
345            Some((left, right)) => (left, parse_qualifiers(right)?),
346            None => (remainder, BTreeMap::new()),
347        };
348        let (scheme, remainder) = remainder.split_once(':').ok_or(PurlError::Scheme)?;
349        if !scheme.eq_ignore_ascii_case("pkg") {
350            return Err(PurlError::Scheme);
351        }
352        let remainder = remainder.trim_start_matches('/');
353        let (package_type, remainder) = remainder.split_once('/').ok_or(PurlError::Name)?;
354        let package_type = package_type.to_ascii_lowercase();
355        if !valid_type(&package_type) {
356            return Err(PurlError::Type);
357        }
358        // The version separator is the last '@' of the last path segment, so an
359        // unencoded '@' that starts a namespace segment (`pkg:npm/@babel/core`)
360        // is not taken for one. A version's own '/' is percent-encoded.
361        let last_segment = remainder.rfind('/').map_or(0, |index| index + 1);
362        let (remainder, version) = match remainder[last_segment..].rfind('@') {
363            Some(at) => {
364                let at = last_segment + at;
365                let version = percent_decode(&remainder[at + 1..])?;
366                (&remainder[..at], (!version.is_empty()).then_some(version))
367            }
368            None => (remainder, None),
369        };
370        let remainder = remainder.trim_end_matches('/');
371        let (remainder, name) = match remainder.rsplit_once('/') {
372            Some((left, right)) => (left, right),
373            None => ("", remainder),
374        };
375        let name = percent_decode(name)?;
376        if name.is_empty() {
377            return Err(PurlError::Name);
378        }
379        let mut namespace = Vec::new();
380        for segment in remainder.split('/').filter(|segment| !segment.is_empty()) {
381            let segment = percent_decode(segment)?;
382            if segment.contains('/') {
383                return Err(PurlError::Namespace);
384            }
385            namespace.push(segment);
386        }
387        let purl = Self {
388            original: text.to_owned(),
389            package_type,
390            namespace,
391            name,
392            version,
393            qualifiers,
394            subpath,
395        };
396        // Percent-encoding can triple a component's length. Refusing here keeps
397        // the promise that every canonical form parses again.
398        if purl.canonical().text.len() > MAX_PURL_BYTES {
399            return Err(PurlError::TooLong);
400        }
401        Ok(purl)
402    }
403
404    /// Exactly the text that was parsed.
405    #[must_use]
406    pub fn as_str(&self) -> &str {
407        &self.original
408    }
409
410    /// The type, lowercased.
411    #[must_use]
412    pub fn package_type(&self) -> &str {
413        &self.package_type
414    }
415
416    /// The decoded namespace segments joined with `/`, or `None` when there
417    /// are none. No type-specific normalization is applied (see
418    /// [`Self::canonical`]).
419    #[must_use]
420    pub fn namespace(&self) -> Option<String> {
421        (!self.namespace.is_empty()).then(|| self.namespace.join("/"))
422    }
423
424    /// The decoded name, as written. No type-specific normalization is
425    /// applied (see [`Self::canonical`]).
426    #[must_use]
427    pub fn name(&self) -> &str {
428        &self.name
429    }
430
431    /// The decoded version, as written, or `None` when absent or empty.
432    #[must_use]
433    pub fn version(&self) -> Option<&str> {
434        self.version.as_deref()
435    }
436
437    /// Decoded qualifiers with non-empty values, keys lowercased, in key order.
438    pub fn qualifiers(&self) -> impl Iterator<Item = (&str, &str)> {
439        self.qualifiers
440            .iter()
441            .map(|(key, value)| (key.as_str(), value.as_str()))
442    }
443
444    /// The decoded value of one qualifier; `key` is matched in lowercase.
445    #[must_use]
446    pub fn qualifier(&self, key: &str) -> Option<&str> {
447        self.qualifiers
448            .get(&key.to_ascii_lowercase())
449            .map(String::as_str)
450    }
451
452    /// The decoded subpath segments joined with `/`, without empty, `.` and
453    /// `..` segments, or `None` when none remain.
454    #[must_use]
455    pub fn subpath(&self) -> Option<String> {
456        (!self.subpath.is_empty()).then(|| self.subpath.join("/"))
457    }
458
459    /// The canonical form: the generic rules, plus the type's own rules when
460    /// [`PurlRules`] has them ([`CanonicalPurl::rules`] says which).
461    ///
462    /// ```
463    /// use libtea_core::purl::{Purl, PurlRules};
464    ///
465    /// let purl = Purl::parse("pkg:PyPI/Django_Allauth@0.61.1RC1").unwrap();
466    /// assert_eq!(purl.name(), "Django_Allauth");
467    /// let canonical = purl.canonical();
468    /// assert_eq!(canonical.as_str(), "pkg:pypi/django-allauth@0.61.1rc1");
469    /// assert_eq!(canonical.rules(), PurlRules::Pypi);
470    /// ```
471    #[must_use]
472    pub fn canonical(&self) -> CanonicalPurl {
473        let rules = PurlRules::for_type(&self.package_type);
474        let lowercase = type_rule(&self.package_type).map_or(0, |rule| rule.lowercase);
475        let fold = |text: &str, component: u8, out: &mut String| {
476            if lowercase & component == 0 {
477                percent_encode_into(text, out);
478            } else {
479                percent_encode_into(&text.to_ascii_lowercase(), out);
480            }
481        };
482        let mut out = String::with_capacity(self.original.len());
483        out.push_str("pkg:");
484        out.push_str(&self.package_type);
485        out.push('/');
486        for segment in &self.namespace {
487            fold(segment, NAMESPACE, &mut out);
488            out.push('/');
489        }
490        if rules == PurlRules::Pypi {
491            percent_encode_into(&pypi_name(&self.name), &mut out);
492        } else {
493            fold(&self.name, NAME, &mut out);
494        }
495        if let Some(version) = &self.version {
496            out.push('@');
497            fold(version, VERSION, &mut out);
498        }
499        for (index, (key, value)) in self.qualifiers.iter().enumerate() {
500            out.push(if index == 0 { '?' } else { '&' });
501            out.push_str(key);
502            out.push('=');
503            percent_encode_into(value, &mut out);
504        }
505        for (index, segment) in self.subpath.iter().enumerate() {
506            out.push(if index == 0 { '#' } else { '/' });
507            fold(segment, SUBPATH, &mut out);
508        }
509        CanonicalPurl { text: out, rules }
510    }
511
512    /// Check the rules the purl-spec type definition gives as data: whether a
513    /// namespace is required or prohibited, which qualifiers are required, and
514    /// the permitted characters of the name and version. A type without a
515    /// definition passes. Rules given only in prose are not checked.
516    ///
517    /// ```
518    /// use libtea_core::purl::{Purl, PurlTypeError};
519    ///
520    /// assert_eq!(Purl::parse("pkg:github/package-url/purl-spec").unwrap().check_type(), Ok(()));
521    /// let purl = Purl::parse("pkg:github/purl-spec").unwrap();
522    /// assert_eq!(purl.check_type(), Err(PurlTypeError::NamespaceRequired));
523    /// let purl = Purl::parse("pkg:julia/Dates").unwrap();
524    /// assert_eq!(purl.check_type(), Err(PurlTypeError::QualifierRequired("uuid")));
525    /// ```
526    ///
527    /// # Errors
528    ///
529    /// The first rule the PURL breaks, as a [`PurlTypeError`].
530    pub fn check_type(&self) -> Result<(), PurlTypeError> {
531        let Some(rule) = type_rule(&self.package_type) else {
532            return Ok(());
533        };
534        match (rule.namespace, self.namespace.is_empty()) {
535            (Requirement::Required, true) => return Err(PurlTypeError::NamespaceRequired),
536            (Requirement::Prohibited, false) => return Err(PurlTypeError::NamespaceProhibited),
537            _ => {}
538        }
539        if let Some(key) = rule
540            .required_qualifiers
541            .iter()
542            .find(|key| !self.qualifiers.contains_key(**key))
543        {
544            return Err(PurlTypeError::QualifierRequired(key));
545        }
546        check_characters(&self.package_type, &self.name, self.version.as_deref())
547    }
548}
549
550/// PEP 503: lowercase, and each run of `-`, `_` and `.` becomes one `-`.
551fn pypi_name(name: &str) -> String {
552    let mut out = String::with_capacity(name.len());
553    let mut in_run = false;
554    for c in name.chars() {
555        if matches!(c, '-' | '_' | '.') {
556            if !in_run {
557                out.push('-');
558            }
559            in_run = true;
560        } else {
561            out.push(c.to_ascii_lowercase());
562            in_run = false;
563        }
564    }
565    out
566}
567
568/// ECMA-427 5.6.2: ASCII letters, digits, `.` and `-`, starting with a letter.
569fn valid_type(package_type: &str) -> bool {
570    let mut chars = package_type.chars();
571    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
572        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-'))
573}
574
575/// ECMA-427 5.6.6, keys already lowercased: letters, digits, `.`, `-` and `_`,
576/// starting with a letter.
577fn valid_qualifier_key(key: &str) -> bool {
578    let mut chars = key.chars();
579    chars.next().is_some_and(|c| c.is_ascii_lowercase())
580        && chars
581            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '-' | '_'))
582}
583
584fn parse_qualifiers(text: &str) -> Result<BTreeMap<String, String>, PurlError> {
585    let mut qualifiers = BTreeMap::new();
586    for pair in text.split('&').filter(|pair| !pair.is_empty()) {
587        let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
588        let key = key.to_ascii_lowercase();
589        if !valid_qualifier_key(&key) {
590            return Err(PurlError::QualifierKey);
591        }
592        let value = percent_decode(value)?;
593        if value.is_empty() {
594            continue;
595        }
596        if qualifiers.insert(key, value).is_some() {
597            return Err(PurlError::DuplicateQualifier);
598        }
599    }
600    Ok(qualifiers)
601}
602
603fn parse_subpath(text: &str) -> Result<Vec<String>, PurlError> {
604    let mut segments = Vec::new();
605    for segment in text.split('/') {
606        let segment = percent_decode(segment)?;
607        if segment.is_empty() || segment == "." || segment == ".." {
608            continue;
609        }
610        if segment.contains('/') {
611            return Err(PurlError::Subpath);
612        }
613        segments.push(segment);
614    }
615    Ok(segments)
616}
617
618fn percent_decode(text: &str) -> Result<String, PurlError> {
619    if !text.contains('%') {
620        return Ok(text.to_owned());
621    }
622    let bytes = text.as_bytes();
623    let mut out = Vec::with_capacity(bytes.len());
624    let mut index = 0;
625    while index < bytes.len() {
626        if bytes[index] == b'%' {
627            let high = bytes.get(index + 1).and_then(|b| hex_value(*b));
628            let low = bytes.get(index + 2).and_then(|b| hex_value(*b));
629            let (Some(high), Some(low)) = (high, low) else {
630                return Err(PurlError::Encoding);
631            };
632            out.push(high << 4 | low);
633            index += 3;
634        } else {
635            out.push(bytes[index]);
636            index += 1;
637        }
638    }
639    String::from_utf8(out).map_err(|_| PurlError::Encoding)
640}
641
642fn hex_value(byte: u8) -> Option<u8> {
643    match byte {
644        b'0'..=b'9' => Some(byte - b'0'),
645        b'a'..=b'f' => Some(byte - b'a' + 10),
646        b'A'..=b'F' => Some(byte - b'A' + 10),
647        _ => None,
648    }
649}
650
651/// ECMA-427 5.4: alphanumerics, `.-_~` and `:` stay; every other UTF-8 octet
652/// becomes `%XX` with uppercase hex.
653fn percent_encode_into(text: &str, out: &mut String) {
654    const HEX: &[u8; 16] = b"0123456789ABCDEF";
655    for &byte in text.as_bytes() {
656        if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_' | b'~' | b':') {
657            out.push(char::from(byte));
658        } else {
659            out.push('%');
660            out.push(char::from(HEX[usize::from(byte >> 4)]));
661            out.push(char::from(HEX[usize::from(byte & 0x0f)]));
662        }
663    }
664}
665
666#[cfg(test)]
667mod tests {
668    use super::*;
669
670    #[test]
671    fn original_text_is_kept_and_canonical_is_separate() {
672        let text = "pkg://NPM//%40angular/animation@12.3.1?B=2&a=1#/x/./y/";
673        let purl = Purl::parse(text).unwrap();
674        assert_eq!(purl.as_str(), text);
675        assert_eq!(purl.package_type(), "npm");
676        assert_eq!(purl.namespace().as_deref(), Some("@angular"));
677        assert_eq!(purl.name(), "animation");
678        assert_eq!(purl.version(), Some("12.3.1"));
679        assert_eq!(purl.qualifier("A"), Some("1"));
680        assert_eq!(purl.subpath().as_deref(), Some("x/y"));
681        assert_eq!(
682            purl.canonical().as_str(),
683            "pkg:npm/%40angular/animation@12.3.1?a=1&b=2#x/y"
684        );
685        assert_eq!(purl.canonical().rules(), PurlRules::Generic);
686    }
687
688    #[test]
689    fn an_unencoded_scope_is_not_a_version() {
690        let purl = Purl::parse("pkg:npm/@babel/core#lib").unwrap();
691        assert_eq!(purl.namespace().as_deref(), Some("@babel"));
692        assert_eq!(purl.name(), "core");
693        assert_eq!(purl.version(), None);
694        assert_eq!(purl.canonical().as_str(), "pkg:npm/%40babel/core#lib");
695        let versioned = Purl::parse("pkg:npm/@babel/core@7.0.0").unwrap();
696        assert_eq!(versioned.version(), Some("7.0.0"));
697    }
698
699    #[test]
700    fn canonical_is_idempotent_on_its_own_output() {
701        for text in [
702            "pkg:generic/a%20b@1.0%2B2?checksum=sha1:ab,sha256:cd",
703            "pkg:deb/debian/curl@7.50.3-1?arch=i386&distro=jessie",
704            "pkg:golang/github.com/gorilla/context@234fd47e07d1004f0aed9c#api",
705            "pkg:generic/%E2%82%AC@%C3%A9",
706        ] {
707            let once = Purl::parse(text).unwrap().canonical();
708            let twice = Purl::parse(once.as_str()).unwrap().canonical();
709            assert_eq!(once, twice, "{text}");
710        }
711    }
712
713    #[test]
714    fn rejected_inputs() {
715        let cases: &[(&str, PurlError)] = &[
716            ("EnterpriseLibrary.Common@6.0.1304", PurlError::Scheme),
717            ("http:npm/a", PurlError::Scheme),
718            ("pkg:npm", PurlError::Name),
719            ("pkg:npm/", PurlError::Name),
720            ("pkg:npm/@1.0", PurlError::Name),
721            ("pkg:/a", PurlError::Name),
722            ("pkg:9pm/a", PurlError::Type),
723            ("pkg:n+m/a", PurlError::Type),
724            ("pkg:n%70m/a", PurlError::Type),
725            ("pkg:npm/a?1key=v", PurlError::QualifierKey),
726            ("pkg:npm/a?k%65y=v", PurlError::QualifierKey),
727            ("pkg:npm/a?=v", PurlError::QualifierKey),
728            ("pkg:npm/a?k=1&K=2", PurlError::DuplicateQualifier),
729            ("pkg:npm/a%2Fb/c", PurlError::Namespace),
730            ("pkg:npm/a#b%2Fc", PurlError::Subpath),
731            ("pkg:npm/a%zz", PurlError::Encoding),
732            ("pkg:npm/a%c3", PurlError::Encoding),
733            ("pkg:npm/a@1%", PurlError::Encoding),
734        ];
735        for (text, error) in cases {
736            assert_eq!(Purl::parse(text).as_ref().err(), Some(error), "{text}");
737        }
738        let long = format!("pkg:generic/{}", "a".repeat(MAX_PURL_BYTES));
739        assert_eq!(Purl::parse(&long), Err(PurlError::TooLong));
740        // Short enough as text, too long once each space becomes `%20`.
741        let spaces = format!("pkg:generic/{}", " ".repeat(2000));
742        assert!(spaces.len() <= MAX_PURL_BYTES);
743        assert_eq!(Purl::parse(&spaces), Err(PurlError::TooLong));
744    }
745
746    #[test]
747    fn empty_qualifier_values_are_dropped_and_empty_version_is_none() {
748        let purl = Purl::parse("pkg:generic/a@?x=&y").unwrap();
749        assert_eq!(purl.version(), None);
750        assert_eq!(purl.qualifiers().count(), 0);
751        assert_eq!(purl.canonical().as_str(), "pkg:generic/a");
752    }
753
754    #[test]
755    fn names_are_not_case_folded_without_a_type_rule() {
756        // npm and maven names are case-sensitive in their type definitions.
757        for (a, b) in [
758            ("pkg:npm/Lodash@4.0.0", "pkg:npm/lodash@4.0.0"),
759            (
760                "pkg:maven/org.Apache/Commons@1",
761                "pkg:maven/org.apache/commons@1",
762            ),
763            ("pkg:generic/a_b@1", "pkg:generic/a-b@1"),
764        ] {
765            let (a, b) = (Purl::parse(a).unwrap(), Purl::parse(b).unwrap());
766            assert!(!same_package_url(&a, &b));
767            assert_eq!(a.canonical().rules(), PurlRules::Generic);
768        }
769    }
770
771    #[test]
772    fn pypi_names_and_versions_follow_the_type_definition() {
773        for (input, canonical) in [
774            ("pkg:pypi/Django@1.11.1", "pkg:pypi/django@1.11.1"),
775            ("pkg:pypi/friendly.bard@1.0", "pkg:pypi/friendly-bard@1.0"),
776            ("pkg:pypi/friendly--bard", "pkg:pypi/friendly-bard"),
777            (
778                "pkg:pypi/My.PyPI_.--._Package@1.11.1.DEV1",
779                "pkg:pypi/my-pypi-package@1.11.1.dev1",
780            ),
781            ("pkg:pypi/-a_", "pkg:pypi/-a-"),
782            ("pkg:pypi/a%2Eb", "pkg:pypi/a-b"),
783            // Qualifier values and the subpath keep their case.
784            (
785                "pkg:pypi/Django@1.0?file_name=Django-1.0.tar.gz#Docs",
786                "pkg:pypi/django@1.0?file_name=Django-1.0.tar.gz#Docs",
787            ),
788        ] {
789            let purl = Purl::parse(input).unwrap();
790            assert_eq!(purl.as_str(), input);
791            assert_eq!(purl.canonical().as_str(), canonical, "{input}");
792            assert_eq!(purl.canonical().rules(), PurlRules::Pypi);
793            let again = Purl::parse(canonical).unwrap().canonical();
794            assert_eq!(again.as_str(), canonical, "idempotent: {input}");
795        }
796        let a = Purl::parse("pkg:pypi/Zope.Interface@5.0").unwrap();
797        let b = Purl::parse("pkg:pypi/zope-interface@5.0").unwrap();
798        assert!(same_package_url(&a, &b));
799        // The accessors keep what was written.
800        assert_eq!(a.name(), "Zope.Interface");
801    }
802
803    #[test]
804    fn case_insensitive_components_follow_the_type_definition() {
805        for (input, canonical) in [
806            (
807                "pkg:github/Package-URL/Purl-Spec@244FD47",
808                "pkg:github/package-url/purl-spec@244FD47",
809            ),
810            (
811                "pkg:deb/Debian/CURL@7.50.3-1?Arch=I386",
812                "pkg:deb/debian/curl@7.50.3-1?arch=I386",
813            ),
814            ("pkg:rpm/Fedora/Curl@7.50", "pkg:rpm/fedora/Curl@7.50"),
815            ("pkg:oci/Debian@SHA256%3AABC", "pkg:oci/debian@sha256:abc"),
816            (
817                "pkg:otp/Hex@2.1.1#Src/Hex.erl",
818                "pkg:otp/hex@2.1.1#src/hex.erl",
819            ),
820            (
821                "pkg:huggingface/EleutherAI/GPT@797ABC",
822                "pkg:huggingface/EleutherAI/GPT@797abc",
823            ),
824        ] {
825            let purl = Purl::parse(input).unwrap();
826            assert_eq!(purl.as_str(), input);
827            assert_eq!(purl.canonical().as_str(), canonical, "{input}");
828            assert_eq!(purl.canonical().rules(), PurlRules::CaseInsensitive);
829            let again = Purl::parse(canonical).unwrap().canonical();
830            assert_eq!(again.as_str(), canonical, "idempotent: {input}");
831        }
832        // golang and swift are case-sensitive in their definitions.
833        for input in [
834            "pkg:golang/GitHub.com/Sirupsen/Logrus",
835            "pkg:swift/github.com/Alamofire/Alamofire",
836        ] {
837            let purl = Purl::parse(input).unwrap();
838            assert_eq!(purl.canonical().as_str(), input);
839            assert_eq!(purl.canonical().rules(), PurlRules::Generic);
840        }
841        let a = Purl::parse("pkg:github/Package-url/purl-Spec").unwrap();
842        let b = Purl::parse("pkg:github/package-url/purl-spec").unwrap();
843        assert!(same_package_url(&a, &b));
844        assert_eq!(a.namespace().as_deref(), Some("Package-url"));
845    }
846
847    #[test]
848    fn check_type_applies_the_definition_requirements() {
849        let check = |text: &str| Purl::parse(text).unwrap().check_type();
850        assert_eq!(check("pkg:maven/org.apache/commons-io@2.11.0"), Ok(()));
851        assert_eq!(
852            check("pkg:maven/commons-io"),
853            Err(PurlTypeError::NamespaceRequired)
854        );
855        assert_eq!(
856            check("pkg:cargo/rust-lang/serde"),
857            Err(PurlTypeError::NamespaceProhibited)
858        );
859        assert_eq!(check("pkg:npm/left-pad"), Ok(()));
860        assert_eq!(check("pkg:npm/%40babel/core"), Ok(()));
861        assert_eq!(
862            check("pkg:julia/Dates"),
863            Err(PurlTypeError::QualifierRequired("uuid"))
864        );
865        assert_eq!(
866            check("pkg:julia/Dates?uuid=ade2ca70-3891-5945-98fb-dc099432e06a"),
867            Ok(())
868        );
869        assert_eq!(
870            check("pkg:swid/Acme/example.com/Enterprise+Server@1.0.0"),
871            Err(PurlTypeError::QualifierRequired("tag_id"))
872        );
873        // A type without a definition, or one the parser lowercased, is checked by its type.
874        assert_eq!(check("pkg:notatype/a/b"), Ok(()));
875        assert_eq!(
876            check("pkg:GitHub/purl-spec"),
877            Err(PurlTypeError::NamespaceRequired)
878        );
879    }
880}