Debian Codegraph @

packageurl.go

raw symbols SCIP
1 /*
2 Copyright (c) the purl authors
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy
5 of this software and associated documentation files (the "Software"), to deal
6 in the Software without restriction, including without limitation the rights
7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 copies of the Software, and to permit persons to whom the Software is
9 furnished to do so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 // Package packageurl implements the package-url spec
24 package packageurl
25
26 import (
27 "errors"
28 "fmt"
29 "net/url"
30 "regexp"
31 "slices"
32 "strings"
33 )
34
35 var (
36 // QualifierKeyPattern describes a valid qualifier key:
37 //
38 // - The key must be composed only of ASCII letters and numbers, '.',
39 // '-' and '_' (period, dash and underscore).
40 // - A key cannot start with a number.
41 QualifierKeyPattern = regexp.MustCompile(`^[A-Za-z\.\-_][0-9A-Za-z\.\-_]*$`)
42 // TypePattern describes a valid type:
43 //
44 // - The type must be composed only of ASCII letters and numbers, '.',
45 // '+' and '-' (period, plus and dash).
46 // - A type cannot start with a number.
47 TypePattern = regexp.MustCompile(`^[A-Za-z\.\-\+][0-9A-Za-z\.\-\+]*$`)
48 )
49
50 // These are the known purl types as defined in the spec. Some of these require
51 // special treatment during parsing.
52 // https://github.com/package-url/purl-spec#known-purl-types
53 var (
54 // TypeAlpm is a pkg:alpm purl.
55 TypeAlpm = "alpm"
56 // TypeApk is a pkg:apk purl.
57 TypeApk = "apk"
58 // TypeBitbucket is a pkg:bitbucket purl.
59 TypeBitbucket = "bitbucket"
60 // TypeBitnami is a pkg:bitnami purl.
61 TypeBitnami = "bitnami"
62 // TypeCargo is a pkg:cargo purl.
63 TypeCargo = "cargo"
64 // TypeChromeExtension is a pkg:chrome-extension purl.
65 TypeChromeExtension = "chrome-extension"
66 // TypeCocoapods is a pkg:cocoapods purl.
67 TypeCocoapods = "cocoapods"
68 // TypeComposer is a pkg:composer purl.
69 TypeComposer = "composer"
70 // TypeConan is a pkg:conan purl.
71 TypeConan = "conan"
72 // TypeConda is a pkg:conda purl.
73 TypeConda = "conda"
74 // TypeCran is a pkg:cran purl.
75 TypeCran = "cran"
76 // TypeDebian is a pkg:deb purl.
77 TypeDebian = "deb"
78 // TypeDocker is a pkg:docker purl.
79 TypeDocker = "docker"
80 // TypeGem is a pkg:gem purl.
81 TypeGem = "gem"
82 // TypeGeneric is a pkg:generic purl.
83 TypeGeneric = "generic"
84 // TypeGithub is a pkg:github purl.
85 TypeGithub = "github"
86 // TypeGolang is a pkg:golang purl.
87 TypeGolang = "golang"
88 // TypeHackage is a pkg:hackage purl.
89 TypeHackage = "hackage"
90 // TypeHex is a pkg:hex purl.
91 TypeHex = "hex"
92 // TypeHuggingface is pkg:huggingface purl.
93 TypeHuggingface = "huggingface"
94 // TypeMLflow is pkg:mlflow purl.
95 TypeMLFlow = "mlflow"
96 // TypeMaven is a pkg:maven purl.
97 TypeMaven = "maven"
98 // TypeNPM is a pkg:npm purl.
99 TypeNPM = "npm"
100 // TypeNuget is a pkg:nuget purl.
101 TypeNuget = "nuget"
102 // TypeOCI is a pkg:oci purl.
103 TypeOCI = "oci"
104 // TypeOTP is a pkg:otp purl.
105 TypeOTP = "otp"
106 // TypePub is a pkg:pub purl.
107 TypePub = "pub"
108 // TypePyPi is a pkg:pypi purl.
109 TypePyPi = "pypi"
110 // TypeQPKG is a pkg:qpkg purl.
111 TypeQpkg = "qpkg"
112 // TypeRPM is a pkg:rpm purl.
113 TypeRPM = "rpm"
114 // TypeSWID is a pkg:swid purl.
115 TypeSWID = "swid"
116 // TypeSwift is a pkg:swift purl.
117 TypeSwift = "swift"
118 // TypeVcpkg is a pkg:vcpkg purl.
119 TypeVcpkg = "vcpkg"
120 // TypeVSCodeExtension is a pkg:vscode-extension purl.
121 TypeVSCodeExtension = "vscode-extension"
122 // TypeYocto is a pkg:yocto purl.
123 TypeYocto = "yocto"
124
125 // KnownTypes is a map of types that are officially supported by the spec.
126 // See https://github.com/package-url/purl-spec/blob/master/PURL-TYPES.rst#known-purl-types
127 KnownTypes = map[string]struct{}{
128 TypeAlpm: {},
129 TypeApk: {},
130 TypeBitbucket: {},
131 TypeBitnami: {},
132 TypeCargo: {},
133 TypeChromeExtension: {},
134 TypeCocoapods: {},
135 TypeComposer: {},
136 TypeConan: {},
137 TypeConda: {},
138 TypeCpan: {},
139 TypeCran: {},
140 TypeDebian: {},
141 TypeDocker: {},
142 TypeGem: {},
143 TypeGeneric: {},
144 TypeGithub: {},
145 TypeGolang: {},
146 TypeHackage: {},
147 TypeHex: {},
148 TypeHuggingface: {},
149 TypeMaven: {},
150 TypeMLFlow: {},
151 TypeNPM: {},
152 TypeNuget: {},
153 TypeOCI: {},
154 TypeOTP: {},
155 TypePub: {},
156 TypePyPi: {},
157 TypeQpkg: {},
158 TypeRPM: {},
159 TypeSWID: {},
160 TypeSwift: {},
161 TypeVcpkg: {},
162 TypeVSCodeExtension: {},
163 TypeYocto: {},
164 }
165
166 TypeApache = "apache"
167 TypeAndroid = "android"
168 TypeAtom = "atom"
169 TypeBower = "bower"
170 TypeBrew = "brew"
171 TypeBuildroot = "buildroot"
172 TypeCarthage = "carthage"
173 TypeChef = "chef"
174 TypeChocolatey = "chocolatey"
175 TypeClojars = "clojars"
176 TypeCoreos = "coreos"
177 TypeCpan = "cpan"
178 TypeCtan = "ctan"
179 TypeCrystal = "crystal"
180 TypeDrupal = "drupal"
181 TypeDtype = "dtype"
182 TypeDub = "dub"
183 TypeElm = "elm"
184 TypeEclipse = "eclipse"
185 TypeGitea = "gitea"
186 TypeGitlab = "gitlab"
187 TypeGradle = "gradle"
188 TypeGuix = "guix"
189 TypeHaxe = "haxe"
190 TypeHelm = "helm"
191 TypeJulia = "julia"
192 TypeLua = "lua"
193 TypeMelpa = "melpa"
194 TypeMeteor = "meteor"
195 TypeNim = "nim"
196 TypeNix = "nix"
197 TypeOpam = "opam"
198 TypeOpenwrt = "openwrt"
199 TypeOsgi = "osgi"
200 TypeP2 = "p2"
201 TypePear = "pear"
202 TypePecl = "pecl"
203 TypePERL6 = "perl6"
204 TypePlatformio = "platformio"
205 TypeEbuild = "ebuild"
206 TypePuppet = "puppet"
207 TypeSourceforge = "sourceforge"
208 TypeSublime = "sublime"
209 TypeTerraform = "terraform"
210 TypeVagrant = "vagrant"
211 TypeVim = "vim"
212 TypeWORDPRESS = "wordpress"
213
214 // CandidateTypes is a map of types that are not yet officially supported by the spec,
215 // but are being considered for inclusion.
216 // See https://github.com/package-url/purl-spec/blob/master/PURL-TYPES.rst#other-candidate-types-to-define
217 CandidateTypes = map[string]struct{}{
218 TypeApache: {},
219 TypeAndroid: {},
220 TypeAtom: {},
221 TypeBower: {},
222 TypeBrew: {},
223 TypeBuildroot: {},
224 TypeCarthage: {},
225 TypeChef: {},
226 TypeChocolatey: {},
227 TypeClojars: {},
228 TypeCoreos: {},
229 TypeCtan: {},
230 TypeCrystal: {},
231 TypeDrupal: {},
232 TypeDtype: {},
233 TypeDub: {},
234 TypeElm: {},
235 TypeEclipse: {},
236 TypeGitea: {},
237 TypeGitlab: {},
238 TypeGradle: {},
239 TypeGuix: {},
240 TypeHaxe: {},
241 TypeHelm: {},
242 TypeJulia: {},
243 TypeLua: {},
244 TypeMelpa: {},
245 TypeMeteor: {},
246 TypeNim: {},
247 TypeNix: {},
248 TypeOpam: {},
249 TypeOpenwrt: {},
250 TypeOsgi: {},
251 TypeP2: {},
252 TypePear: {},
253 TypePecl: {},
254 TypePERL6: {},
255 TypePlatformio: {},
256 TypeEbuild: {},
257 TypePuppet: {},
258 TypeSourceforge: {},
259 TypeSublime: {},
260 TypeTerraform: {},
261 TypeVagrant: {},
262 TypeVim: {},
263 TypeWORDPRESS: {},
264 TypeYocto: {},
265 }
266 )
267
268 // Qualifier represents a single key=value qualifier in the package url
269 type Qualifier struct {
270 Key string
271 Value string
272 }
273
274 // String returns a canonical string representation of the qualifier according to [SPEC].
275 //
276 // [SPEC] https://github.com/package-url/purl-spec/blob/main/PURL-SPECIFICATION.rst#rules-for-each-purl-component
277 func (q Qualifier) String() string {
278 // A value must be a percent-encoded string
279 var b strings.Builder
280 escapeQualifier(&b, q.Key)
281 b.WriteByte('=')
282 escapeQualifier(&b, q.Value)
283 return b.String()
284 }
285
286 // Qualifiers is a slice of key=value pairs, with order preserved as it appears
287 // in the package URL.
288 type Qualifiers []Qualifier
289
290 // String returns a canonical string representation of the qualifiers as keys + values.
291 // Canonical form requires qualifier keys to be lexicographically ordered.
292 // The leading `?` qualifier component delimiter is excluded.
293 func (q Qualifiers) String() string {
294 if len(q) == 0 {
295 return ""
296 }
297 slices.SortFunc(q, func(a, b Qualifier) int { return strings.Compare(a.Key, b.Key) })
298 var b strings.Builder
299 // Estimate capacity: each qualifier needs key + "=" + value + "&"
300 b.Grow(len(q) * 32)
301 for i, qq := range q {
302 if i > 0 {
303 b.WriteByte('&')
304 }
305 escapeQualifier(&b, qq.Key)
306 b.WriteByte('=')
307 escapeQualifier(&b, qq.Value)
308 }
309 return b.String()
310 }
311
312 // escapeQualifier escapes a qualifier key or value for use in the query string.
313 // Per purl spec, ':' is NOT encoded but most other special characters are.
314 func escapeQualifier(b *strings.Builder, s string) {
315 for i := 0; i < len(s); i++ {
316 c := s[i]
317 if isQualifierSafe(c) {
318 b.WriteByte(c)
319 } else {
320 writePercentEncodedByte(b, c)
321 }
322 }
323 }
324
325 // isQualifierSafe reports whether c can appear unencoded in a purl qualifier.
326 // Per purl spec, ':' is allowed unencoded in qualifier values.
327 func isQualifierSafe(c byte) bool {
328 // Standard unreserved characters plus ':'
329 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
330 c == '-' || c == '.' || c == '_' || c == '~' || c == ':'
331 }
332
333 // QualifiersFromMap constructs a Qualifiers slice from a string map. To get a
334 // deterministic qualifier order (despite maps not providing any iteration order
335 // guarantees) the returned Qualifiers are sorted in increasing order of key.
336 func QualifiersFromMap(mm map[string]string) Qualifiers {
337 q := make(Qualifiers, 0, len(mm))
338
339 for k, v := range mm {
340 q = append(q, Qualifier{Key: k, Value: v})
341 }
342
343 // sort for deterministic qualifier order
344 slices.SortFunc(q, func(a, b Qualifier) int { return strings.Compare(a.Key, b.Key) })
345
346 return q
347 }
348
349 // Map converts a Qualifiers struct to a string map.
350 func (qq Qualifiers) Map() map[string]string {
351 m := make(map[string]string)
352
353 for i := 0; i < len(qq); i++ {
354 k := qq[i].Key
355 v := qq[i].Value
356 m[k] = v
357 }
358
359 return m
360 }
361
362 func (qq *Qualifiers) Normalize() error {
363 qs := *qq
364 normedQQ := make(Qualifiers, 0, len(qs))
365 for _, q := range qs {
366 if q.Key == "" {
367 return fmt.Errorf("key is missing from qualifier: %v", q)
368 }
369 if q.Value == "" {
370 // Empty values are equivalent to the key being omitted from the PackageURL.
371 continue
372 }
373 key := toLowerASCII(q.Key)
374 if !validQualifierKey(key) {
375 return fmt.Errorf("invalid qualifier key: %q", key)
376 }
377 normedQQ = append(normedQQ, Qualifier{key, q.Value})
378 }
379 slices.SortFunc(normedQQ, func(a, b Qualifier) int { return strings.Compare(a.Key, b.Key) })
380 for i := 1; i < len(normedQQ); i++ {
381 if normedQQ[i-1].Key == normedQQ[i].Key {
382 return fmt.Errorf("duplicate qualifier key: %q", normedQQ[i].Key)
383 }
384 }
385 *qq = normedQQ
386 return nil
387 }
388
389 // toLowerASCII returns s with all ASCII uppercase letters converted to lowercase.
390 // It avoids allocation if s is already lowercase.
391 func toLowerASCII(s string) string {
392 needsConvert := -1
393 for i := 0; i < len(s); i++ {
394 if c := s[i]; c >= 'A' && c <= 'Z' {
395 needsConvert = i
396 break
397 }
398 }
399 if needsConvert < 0 {
400 return s
401 }
402
403 b := make([]byte, len(s))
404 copy(b, s[:needsConvert])
405 for i := needsConvert; i < len(s); i++ {
406 c := s[i]
407 if c >= 'A' && c <= 'Z' {
408 c += 32
409 }
410 b[i] = c
411 }
412 return string(b)
413 }
414
415 // PackageURL is the struct representation of the parts that make a package url
416 type PackageURL struct {
417 Type string
418 Namespace string
419 Name string
420 Version string
421 Qualifiers Qualifiers
422 Subpath string
423 }
424
425 // NewPackageURL creates a new PackageURL struct instance based on input
426 func NewPackageURL(purlType, namespace, name, version string,
427 qualifiers Qualifiers, subpath string) *PackageURL {
428
429 return &PackageURL{
430 Type: purlType,
431 Namespace: namespace,
432 Name: name,
433 Version: version,
434 Qualifiers: qualifiers,
435 Subpath: subpath,
436 }
437 }
438
439 // ToString returns a canonical string representation of the qualifier according to [SPEC].
440 //
441 // [SPEC] https://github.com/package-url/purl-spec/blob/main/PURL-SPECIFICATION.rst#rules-for-each-purl-component
442 func (p *PackageURL) ToString() string {
443 var b strings.Builder
444 // Estimate capacity for typical purl, including component delimiters.
445 b.Grow(4 + len(p.Type) + 1 + len(p.Namespace) + 1 + len(p.Name) + 1 + len(p.Version) + len(p.Subpath) + 32)
446
447 b.WriteString("pkg:")
448 b.WriteString(p.Type)
449
450 // Each namespace segment shall be a percent-encoded string.
451 if p.Namespace != "" {
452 start := 0
453 for i := 0; i <= len(p.Namespace); i++ {
454 if i == len(p.Namespace) || p.Namespace[i] == '/' {
455 if i > start {
456 b.WriteByte('/')
457 writePercentEncodedString(&b, p.Namespace[start:i])
458 }
459 start = i + 1
460 }
461 }
462 }
463
464 // A name shall be a percent-encoded string.
465 b.WriteByte('/')
466 writePercentEncodedString(&b, p.Name)
467
468 if p.Version != "" {
469 // A version shall be a percent-encoded string.
470 b.WriteByte('@')
471 writePercentEncodedString(&b, p.Version)
472 }
473
474 if len(p.Qualifiers) > 0 {
475 b.WriteByte('?')
476 b.WriteString(p.Qualifiers.String())
477 }
478
479 // Each subpath segment shall be a percent-encoded string.
480 if p.Subpath != "" {
481 b.WriteByte('#')
482 escapeSubpath(&b, p.Subpath)
483 }
484
485 return b.String()
486 }
487
488 func (p PackageURL) String() string {
489 return p.ToString()
490 }
491
492 // FromString parses a valid package url string into a [PackageURL].
493 func FromString(purl string) (PackageURL, error) {
494 // Check scheme
495 if len(purl) < 4 || toLowerASCII(purl[:4]) != "pkg:" {
496 return PackageURL{}, fmt.Errorf("purl scheme is not \"pkg\": %q", purl)
497 }
498
499 remainder := purl[4:]
500
501 // Handle pkg:/ and pkg:// formats by stripping leading slashes
502 for len(remainder) > 0 && remainder[0] == '/' {
503 remainder = remainder[1:]
504 }
505
506 // Extract fragment (subpath)
507 var subpath string
508 if idx := strings.IndexByte(remainder, '#'); idx != -1 {
509 // A subpath is a percent-encoded string and must be decoded like the
510 // other components (namespace, name, version).
511 decoded, err := percentDecodeSubpath(remainder[idx+1:])
512 if err != nil {
513 return PackageURL{}, fmt.Errorf("error unescaping subpath: %w", err)
514 }
515 subpath = decoded
516 remainder = remainder[:idx]
517 }
518
519 // Extract query string (qualifiers)
520 var rawQuery string
521 if idx := strings.IndexByte(remainder, '?'); idx != -1 {
522 rawQuery = remainder[idx+1:]
523 remainder = remainder[:idx]
524 }
525
526 // Extract type
527 typ, remainder, ok := strings.Cut(remainder, "/")
528 if !ok {
529 return PackageURL{}, fmt.Errorf("purl is missing type or name")
530 }
531 typ = toLowerASCII(typ)
532
533 // Parse qualifiers
534 qualifiers, err := parseQualifiers(rawQuery)
535 if err != nil {
536 return PackageURL{}, fmt.Errorf("invalid qualifiers: %w", err)
537 }
538
539 // Parse namespace, name, version
540 namespace, name, version, err := separateNamespaceNameVersion(typ, remainder)
541 if err != nil {
542 return PackageURL{}, err
543 }
544
545 pURL := PackageURL{
546 Qualifiers: qualifiers,
547 Type: typ,
548 Namespace: namespace,
549 Name: name,
550 Version: version,
551 Subpath: subpath,
552 }
553
554 err = pURL.Normalize()
555 return pURL, err
556 }
557
558 // Normalize converts p to its canonical form, returning an error if p is invalid.
559 func (p *PackageURL) Normalize() error {
560 typ := strings.ToLower(p.Type)
561 if !validType(typ) {
562 return fmt.Errorf("invalid type %q", typ)
563 }
564 namespace := strings.Trim(p.Namespace, "/")
565 if err := p.Qualifiers.Normalize(); err != nil {
566 return fmt.Errorf("invalid qualifiers: %v", err)
567 }
568 if p.Name == "" {
569 return errors.New("purl is missing name")
570 }
571 subpath := strings.Trim(p.Subpath, "/")
572 segs := strings.Split(p.Subpath, "/")
573 for i, s := range segs {
574 if (s == "." || s == "..") && i != 0 {
575 return fmt.Errorf("invalid Package URL subpath: %q", p.Subpath)
576 }
577 }
578 *p = PackageURL{
579 Type: typ,
580 Namespace: typeAdjustNamespace(typ, namespace),
581 Name: typeAdjustName(typ, p.Name, p.Qualifiers),
582 Version: typeAdjustVersion(typ, p.Version),
583 Qualifiers: p.Qualifiers,
584 Subpath: subpath,
585 }
586 return validCustomRules(*p)
587 }
588
589 // percentDecode percent-decodes a purl component according to [Encoding].
590 //
591 // [Encoding] https://github.com/package-url/purl-spec/blob/main/PURL-SPECIFICATION.rst#character-encoding
592 func percentDecode(s string) (string, error) {
593 // Note: uses [url.PathUnescape] instead of [url.QueryUnescape] to treat '+' characters
594 // literally (not as space).
595 return url.PathUnescape(s)
596 }
597
598 // percentDecodeSubpath percent-decodes a subpath by decoding each '/'-separated
599 // segment on its own, so an encoded slash inside a segment is not treated as a
600 // segment separator. This mirrors the per-segment decoding done for the namespace.
601 func percentDecodeSubpath(s string) (string, error) {
602 if !strings.Contains(s, "%") {
603 return s, nil
604 }
605 segments := strings.Split(s, "/")
606 for i, segment := range segments {
607 decoded, err := percentDecode(segment)
608 if err != nil {
609 return "", err
610 }
611 segments[i] = decoded
612 }
613 return strings.Join(segments, "/"), nil
614 }
615
616 // writePercentEncodedString percent-encodes s as a purl path segment and writes it to the builder.
617 func writePercentEncodedString(b *strings.Builder, s string) {
618 // Check if we need to escape at all
619 needsEscape := false
620 for i := 0; i < len(s); i++ {
621 if !isPathSegmentSafe(s[i]) {
622 needsEscape = true
623 break
624 }
625 }
626 if !needsEscape {
627 b.WriteString(s)
628 return
629 }
630
631 // Need to escape - process character by character
632 for i := 0; i < len(s); i++ {
633 c := s[i]
634 if isPathSegmentSafe(c) {
635 b.WriteByte(c)
636 } else {
637 writePercentEncodedByte(b, c)
638 }
639 }
640 }
641
642 // writePercentEncodedByte percent-encodes the given byte as per [RFC-3986] and writes the result to
643 // the supplied [strings.Builder].
644 //
645 // [RFC-3986]: https://datatracker.ietf.org/doc/html/rfc3986#page-12
646 func writePercentEncodedByte(b *strings.Builder, c byte) {
647 b.WriteByte('%')
648 b.WriteByte(hexUpper[c>>4])
649 b.WriteByte(hexUpper[c&0x0f])
650 }
651
652 // isPathSegmentSafe reports whether c can appear unencoded in a purl path segment.
653 // Per the purl spec, the only characters that must NOT be percent-encoded are:
654 // alphanumerics, the unreserved punctuation '-', '.', '_', '~', and ':'.
655 // All other characters — including RFC 3986 sub-delimiters such as '(', ')', '!',
656 // '$', '&', "'", '*', ',', ';', '=' — must be percent-encoded.
657 //
658 // See https://ecma-tc54.github.io/ECMA-427/#sec-purl-specification-character-encoding
659 func isPathSegmentSafe(c byte) bool {
660 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
661 c == '-' || c == '.' || c == '_' || c == '~' || c == ':'
662 }
663
664 // escapeSubpath escapes a subpath, handling segments separated by '/'.
665 func escapeSubpath(b *strings.Builder, s string) {
666 for i := 0; i < len(s); i++ {
667 c := s[i]
668 if c == '/' {
669 b.WriteByte('/')
670 } else if isPathSegmentSafe(c) {
671 b.WriteByte(c)
672 } else {
673 writePercentEncodedByte(b, c)
674 }
675 }
676 }
677
678 const hexUpper = "0123456789ABCDEF"
679
680 // separateNamespaceNameVersion parses the <namespace>/<name>@<version> part of a purl (the
681 // remainder parameter) into its constituent components. It aims to follow the [HOW-TO-PARSE]
682 // procedure.
683 //
684 // [HOW-TO-PARSE]: https://github.com/package-url/purl-spec/blob/main/docs/how-to-parse.md
685 func separateNamespaceNameVersion(purlType string, remainder string) (ns, name, version string, err error) {
686 // NPM purls can have a namespace ("scope") that starts with an '@' character.
687 // For example, "pkg:npm/@babel/core".
688 // For any other purl type this indicates malformed purl input.
689 if purlType != TypeNPM && strings.HasPrefix(remainder, "@") {
690 return "", "", "", fmt.Errorf("purl is missing name")
691 }
692 // A leading '@' is only valid for npm when it introduces a scope, which
693 // requires a '/' to separate the scope from the name (for example,
694 // "pkg:npm/@babel/core"). A remainder like "@4.17.21" has no '/', so it is a
695 // bare scope with no name and must be rejected the same way as v0.1.3 did.
696 if purlType == TypeNPM && strings.HasPrefix(remainder, "@") && !strings.Contains(remainder, "/") {
697 return "", "", "", fmt.Errorf("purl is missing name")
698 }
699
700 // Split the remainder once from right on '@'.
701 // The left side is the remainder.
702 if strings.LastIndex(remainder, "@") > 0 {
703 remainder, version = rightmostSplit(remainder, "@")
704 // Percent-decode the right side. This is the version.
705 version, err = percentDecode(version)
706 if err != nil {
707 return "", "", "", fmt.Errorf("error unescaping version: %w", err)
708 }
709 }
710
711 // Split this once from right on '/'.
712 // The left side is the remainder.
713 remainder, name = rightmostSplit(remainder, "/")
714 // Percent-decode the right side. This is the name.
715 name, err = percentDecode(name)
716 if err != nil {
717 return "", "", "", fmt.Errorf("error unescaping name: %w", err)
718 }
719
720 // Split the remainder on '/'.
721 segments := strings.Split(remainder, "/")
722 nsSegments := []string{}
723 for _, segment := range segments {
724 // Discard any empty segment from that split.
725 if segment == "" {
726 continue
727 }
728 // Percent-decode each segment.
729 nsSegment, err := percentDecode(segment)
730 if err != nil {
731 return "", "", "", fmt.Errorf("error unescaping namespace: %w", err)
732 }
733 nsSegments = append(nsSegments, nsSegment)
734 }
735 // Join segments back with a '/'.
736 ns = strings.Join(nsSegments, "/")
737
738 if name == "" {
739 return "", "", "", fmt.Errorf("purl is missing name")
740 }
741
742 return ns, name, version, nil
743 }
744
745 // rightmostSplit splits the input path on a given delimiter such that the lhs returns the string to
746 // the left of the right-most delimiter and rhs return the string to the right of the right-most
747 // delimiter. For example, given path "github.com/package-url/packageurl-go" and delimiter "/" the
748 // lhs will be "github.com/package-url" and rhs will be "packageurl-go".
749 func rightmostSplit(path string, delim string) (lhs, rhs string) {
750 lastSepIdx := strings.LastIndex(path, delim)
751 rhs = path[lastSepIdx+1:]
752 if lastSepIdx >= 0 {
753 lhs = path[:lastSepIdx]
754 }
755 return lhs, rhs
756 }
757
758 func parseQualifiers(rawQuery string) (Qualifiers, error) {
759 // we need to parse the qualifiers ourselves and cannot rely on the `url.Query` type because
760 // that uses a map, meaning it's unordered. We want to keep the order of the qualifiers, so this
761 // function re-implements the `url.parseQuery` function based on our `Qualifier` type. Most of
762 // the code here is taken from `url.parseQuery`.
763 q := Qualifiers{}
764 for rawQuery != "" {
765 var key string
766 key, rawQuery, _ = strings.Cut(rawQuery, "&")
767 if strings.Contains(key, ";") {
768 return nil, fmt.Errorf("invalid semicolon separator in query")
769 }
770 if key == "" {
771 continue
772 }
773 // The key is the lowercase left side.
774 key, value, _ := strings.Cut(key, "=")
775 key = strings.ToLower(key)
776
777 if !validQualifierKey(key) {
778 return nil, fmt.Errorf("invalid qualifier key: '%s'", key)
779 }
780
781 // The value is the percent-decoded right side.
782 value, err := percentDecode(value)
783 if err != nil {
784 return nil, fmt.Errorf("error unescaping qualifier value %q", value)
785 }
786
787 q = append(q, Qualifier{Key: key, Value: value})
788 }
789 return q, nil
790 }
791
792 // Make any purl type-specific adjustments to the parsed namespace.
793 // See https://github.com/package-url/purl-spec#known-purl-types
794 func typeAdjustNamespace(purlType, ns string) string {
795 switch purlType {
796 case TypeAlpm,
797 TypeApk,
798 TypeBitbucket,
799 TypeBrew,
800 TypeComposer,
801 TypeDebian,
802 TypeGithub,
803 TypeGolang,
804 TypeRPM,
805 TypeQpkg:
806 return strings.ToLower(ns)
807 }
808 return ns
809 }
810
811 // Make any purl type-specific adjustments to the parsed name.
812 // See https://github.com/package-url/purl-spec#known-purl-types
813 func typeAdjustName(purlType, name string, qualifiers Qualifiers) string {
814 quals := qualifiers.Map()
815 switch purlType {
816 case TypeAlpm,
817 TypeApk,
818 TypeBitbucket,
819 TypeBitnami,
820 TypeBrew,
821 TypeChromeExtension,
822 TypeComposer,
823 TypeDebian,
824 TypeGithub,
825 TypeGolang:
826 return strings.ToLower(name)
827 case TypePyPi:
828 return strings.ToLower(strings.ReplaceAll(name, "_", "-"))
829 case TypeMLFlow:
830 return adjustMlflowName(name, quals)
831 }
832 return name
833 }
834
835 // Make any purl type-specific adjustments to the parsed version.
836 // See https://github.com/package-url/purl-spec#known-purl-types
837 func typeAdjustVersion(purlType, version string) string {
838 switch purlType {
839 case TypeHuggingface:
840 return strings.ToLower(version)
841 }
842 return version
843 }
844
845 // https://github.com/package-url/purl-spec/blob/master/PURL-TYPES.rst#mlflow
846 func adjustMlflowName(name string, qualifiers map[string]string) string {
847 if repo, ok := qualifiers["repository_url"]; ok {
848 if strings.Contains(repo, "databricks") {
849 // Databricks is case-insensitive and must be lowercased
850 return strings.ToLower(name)
851 }
852
853 // Azure ML is case-sensitive and must be kept as-is
854 // Unknown repository type, keep as-is
855 return name
856
857 } else {
858 // No repository qualifier given, keep as-is
859 return name
860 }
861 }
862
863 // validQualifierKey validates a qualifierKey against our QualifierKeyPattern.
864 // The key must be composed only of ASCII letters and numbers, '.', '-' and '_'.
865 // A key cannot start with a number.
866 // See https://ecma-tc54.github.io/ECMA-427/#sec-purl-specification-rules-qualifiers.
867 func validQualifierKey(key string) bool {
868 if len(key) == 0 {
869 return false
870 }
871 // First character: must be a-z, A-Z, '.', '-', or '_'
872 c := key[0]
873 if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '.' || c == '-' || c == '_') {
874 return false
875 }
876 // Remaining characters: a-z, A-Z, 0-9, '.', '-', or '_'
877 for i := 1; i < len(key); i++ {
878 c = key[i]
879 if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_') {
880 return false
881 }
882 }
883 return true
884 }
885
886 // validType validates a type against our TypePattern.
887 // The type must be composed only of ASCII letters and numbers, '.', '+' and '-'.
888 // A type cannot start with a number.
889 // See https://ecma-tc54.github.io/ECMA-427/#sec-purl-specification-rules-type.
890 func validType(typ string) bool {
891 if len(typ) == 0 {
892 return false
893 }
894 // First character: must be a-z, A-Z, '.', '-', or '+'
895 c := typ[0]
896 if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '.' || c == '-' || c == '+') {
897 return false
898 }
899 // Remaining characters: a-z, A-Z, 0-9, '.', '-', or '+'
900 for i := 1; i < len(typ); i++ {
901 c = typ[i]
902 if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+') {
903 return false
904 }
905 }
906 return true
907 }
908
909 // validChromeExtensionName checks the name against ^[a-z]{32}$.
910 func validChromeExtensionName(name string) bool {
911 if len(name) != 32 {
912 return false
913 }
914 for i := 0; i < len(name); i++ {
915 if c := name[i]; c < 'a' || c > 'z' {
916 return false
917 }
918 }
919 return true
920 }
921
922 // validChromeExtensionVersion checks the version against ^\d+(\.\d+){0,3}$.
923 func validChromeExtensionVersion(version string) bool {
924 segments := 1
925 digitsInSegment := 0
926 for i := 0; i < len(version); i++ {
927 c := version[i]
928 if c >= '0' && c <= '9' {
929 digitsInSegment++
930 continue
931 }
932 if c == '.' {
933 if digitsInSegment == 0 {
934 return false
935 }
936 segments++
937 digitsInSegment = 0
938 continue
939 }
940 return false
941 }
942 return digitsInSegment > 0 && segments <= 4
943 }
944
945 // validCustomRules evaluates additional rules for each package url type, as specified in the package-url specification.
946 // On success, it returns nil. On failure, a descriptive error will be returned.
947 func validCustomRules(p PackageURL) error {
948 switch p.Type {
949 case TypeChromeExtension:
950 if p.Namespace != "" {
951 return errors.New("a chrome-extension purl must not have a namespace")
952 }
953 if !validChromeExtensionName(p.Name) {
954 return errors.New("a chrome-extension name must be 32 lowercase ASCII letters")
955 }
956 if p.Version != "" && !validChromeExtensionVersion(p.Version) {
957 return errors.New("a chrome-extension version must be 1 to 4 dot-separated integers")
958 }
959 case TypeCpan:
960 // It MUST be written uppercase.
961 if strings.ToUpper(p.Namespace) != p.Namespace {
962 return errors.New("a cpan purl namespace must use uppercase characters")
963 }
964
965 // A distribution name MUST NOT contain the string '::'.
966 distName := p.Name
967 if strings.Contains(distName, "::") {
968 return errors.New("a cpan distribution name must not contain '::'")
969 }
970 case TypeJulia:
971 // The spec prohibits a namespace.
972 if p.Namespace != "" {
973 return errors.New("a julia purl must not have a namespace")
974 }
975 // The spec requires the presence of a uuid qualifier.
976 if _, ok := p.Qualifiers.Map()["uuid"]; !ok {
977 return errors.New("a julia purl must have a uuid qualifier")
978 }
979 case TypeOTP:
980 // The spec prohibits a namespace.
981 if p.Namespace != "" {
982 return errors.New("an otp purl must not have a namespace")
983 }
984 case TypeSwift:
985 if p.Namespace == "" {
986 return errors.New("namespace is required")
987 }
988 case TypeVcpkg:
989 if p.Namespace != "" {
990 return errors.New("a vcpkg purl must not have a namespace")
991 }
992 case TypeVSCodeExtension:
993 if p.Namespace == "" {
994 return errors.New("namespace is required")
995 }
996 }
997 return nil
998 }