-
Notifications
You must be signed in to change notification settings - Fork 48
/
packageurl.go
673 lines (613 loc) · 18.3 KB
/
packageurl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
/*
Copyright (c) the purl authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Package packageurl implements the package-url spec
package packageurl
import (
"errors"
"fmt"
"net/url"
"path"
"regexp"
"sort"
"strings"
)
var (
// QualifierKeyPattern describes a valid qualifier key:
//
// - The key must be composed only of ASCII letters and numbers, '.',
// '-' and '_' (period, dash and underscore).
// - A key cannot start with a number.
QualifierKeyPattern = regexp.MustCompile(`^[A-Za-z\.\-_][0-9A-Za-z\.\-_]*$`)
// TypePattern describes a valid type:
//
// - The type must be composed only of ASCII letters and numbers, '.',
// '+' and '-' (period, plus and dash).
// - A type cannot start with a number.
TypePattern = regexp.MustCompile(`^[A-Za-z\.\-\+][0-9A-Za-z\.\-\+]*$`)
)
// These are the known purl types as defined in the spec. Some of these require
// special treatment during parsing.
// https://github.com/package-url/purl-spec#known-purl-types
var (
// TypeAlpm is a pkg:alpm purl.
TypeAlpm = "alpm"
// TypeApk is a pkg:apk purl.
TypeApk = "apk"
// TypeBitbucket is a pkg:bitbucket purl.
TypeBitbucket = "bitbucket"
// TypeBitnami is a pkg:bitnami purl.
TypeBitnami = "bitnami"
// TypeCargo is a pkg:cargo purl.
TypeCargo = "cargo"
// TypeCocoapods is a pkg:cocoapods purl.
TypeCocoapods = "cocoapods"
// TypeComposer is a pkg:composer purl.
TypeComposer = "composer"
// TypeConan is a pkg:conan purl.
TypeConan = "conan"
// TypeConda is a pkg:conda purl.
TypeConda = "conda"
// TypeCran is a pkg:cran purl.
TypeCran = "cran"
// TypeDebian is a pkg:deb purl.
TypeDebian = "deb"
// TypeDocker is a pkg:docker purl.
TypeDocker = "docker"
// TypeGem is a pkg:gem purl.
TypeGem = "gem"
// TypeGeneric is a pkg:generic purl.
TypeGeneric = "generic"
// TypeGithub is a pkg:github purl.
TypeGithub = "github"
// TypeGolang is a pkg:golang purl.
TypeGolang = "golang"
// TypeHackage is a pkg:hackage purl.
TypeHackage = "hackage"
// TypeHex is a pkg:hex purl.
TypeHex = "hex"
// TypeHuggingface is pkg:huggingface purl.
TypeHuggingface = "huggingface"
// TypeMLflow is pkg:mlflow purl.
TypeMLFlow = "mlflow"
// TypeMaven is a pkg:maven purl.
TypeMaven = "maven"
// TypeNPM is a pkg:npm purl.
TypeNPM = "npm"
// TypeNuget is a pkg:nuget purl.
TypeNuget = "nuget"
// TypeOCI is a pkg:oci purl
TypeOCI = "oci"
// TypePub is a pkg:pub purl.
TypePub = "pub"
// TypePyPi is a pkg:pypi purl.
TypePyPi = "pypi"
// TypeQPKG is a pkg:qpkg purl.
TypeQpkg = "qpkg"
// TypeRPM is a pkg:rpm purl.
TypeRPM = "rpm"
// TypeSWID is pkg:swid purl
TypeSWID = "swid"
// TypeSwift is pkg:swift purl
TypeSwift = "swift"
// KnownTypes is a map of types that are officially supported by the spec.
// See https://github.com/package-url/purl-spec/blob/master/PURL-TYPES.rst#known-purl-types
KnownTypes = map[string]struct{}{
TypeAlpm: {},
TypeApk: {},
TypeBitbucket: {},
TypeBitnami: {},
TypeCargo: {},
TypeCocoapods: {},
TypeComposer: {},
TypeConan: {},
TypeConda: {},
TypeCran: {},
TypeDebian: {},
TypeDocker: {},
TypeGem: {},
TypeGeneric: {},
TypeGithub: {},
TypeGolang: {},
TypeHackage: {},
TypeHex: {},
TypeHuggingface: {},
TypeMaven: {},
TypeMLFlow: {},
TypeNPM: {},
TypeNuget: {},
TypeOCI: {},
TypePub: {},
TypePyPi: {},
TypeQpkg: {},
TypeRPM: {},
TypeSWID: {},
TypeSwift: {},
}
TypeApache = "apache"
TypeAndroid = "android"
TypeAtom = "atom"
TypeBower = "bower"
TypeBrew = "brew"
TypeBuildroot = "buildroot"
TypeCarthage = "carthage"
TypeChef = "chef"
TypeChocolatey = "chocolatey"
TypeClojars = "clojars"
TypeCoreos = "coreos"
TypeCpan = "cpan"
TypeCtan = "ctan"
TypeCrystal = "crystal"
TypeDrupal = "drupal"
TypeDtype = "dtype"
TypeDub = "dub"
TypeElm = "elm"
TypeEclipse = "eclipse"
TypeGitea = "gitea"
TypeGitlab = "gitlab"
TypeGradle = "gradle"
TypeGuix = "guix"
TypeHaxe = "haxe"
TypeHelm = "helm"
TypeJulia = "julia"
TypeLua = "lua"
TypeMelpa = "melpa"
TypeMeteor = "meteor"
TypeNim = "nim"
TypeNix = "nix"
TypeOpam = "opam"
TypeOpenwrt = "openwrt"
TypeOsgi = "osgi"
TypeP2 = "p2"
TypePear = "pear"
TypePecl = "pecl"
TypePERL6 = "perl6"
TypePlatformio = "platformio"
TypeEbuild = "ebuild"
TypePuppet = "puppet"
TypeSourceforge = "sourceforge"
TypeSublime = "sublime"
TypeTerraform = "terraform"
TypeVagrant = "vagrant"
TypeVim = "vim"
TypeWORDPRESS = "wordpress"
TypeYocto = "yocto"
// CandidateTypes is a map of types that are not yet officially supported by the spec,
// but are being considered for inclusion.
// See https://github.com/package-url/purl-spec/blob/master/PURL-TYPES.rst#other-candidate-types-to-define
CandidateTypes = map[string]struct{}{
TypeApache: {},
TypeAndroid: {},
TypeAtom: {},
TypeBower: {},
TypeBrew: {},
TypeBuildroot: {},
TypeCarthage: {},
TypeChef: {},
TypeChocolatey: {},
TypeClojars: {},
TypeCoreos: {},
TypeCpan: {},
TypeCtan: {},
TypeCrystal: {},
TypeDrupal: {},
TypeDtype: {},
TypeDub: {},
TypeElm: {},
TypeEclipse: {},
TypeGitea: {},
TypeGitlab: {},
TypeGradle: {},
TypeGuix: {},
TypeHaxe: {},
TypeHelm: {},
TypeJulia: {},
TypeLua: {},
TypeMelpa: {},
TypeMeteor: {},
TypeNim: {},
TypeNix: {},
TypeOpam: {},
TypeOpenwrt: {},
TypeOsgi: {},
TypeP2: {},
TypePear: {},
TypePecl: {},
TypePERL6: {},
TypePlatformio: {},
TypeEbuild: {},
TypePuppet: {},
TypeSourceforge: {},
TypeSublime: {},
TypeTerraform: {},
TypeVagrant: {},
TypeVim: {},
TypeWORDPRESS: {},
TypeYocto: {},
}
)
// Qualifier represents a single key=value qualifier in the package url
type Qualifier struct {
Key string
Value string
}
func (q Qualifier) String() string {
// A value must be a percent-encoded string
return fmt.Sprintf("%s=%s", q.Key, url.PathEscape(q.Value))
}
// Qualifiers is a slice of key=value pairs, with order preserved as it appears
// in the package URL.
type Qualifiers []Qualifier
// urlQuery returns a raw URL query with all the qualifiers as keys + values.
func (q Qualifiers) urlQuery() (rawQuery string) {
v := make(url.Values)
for _, qq := range q {
v.Add(qq.Key, qq.Value)
}
return v.Encode()
}
// QualifiersFromMap constructs a Qualifiers slice from a string map. To get a
// deterministic qualifier order (despite maps not providing any iteration order
// guarantees) the returned Qualifiers are sorted in increasing order of key.
func QualifiersFromMap(mm map[string]string) Qualifiers {
q := Qualifiers{}
for k, v := range mm {
q = append(q, Qualifier{Key: k, Value: v})
}
// sort for deterministic qualifier order
sort.Slice(q, func(i int, j int) bool { return q[i].Key < q[j].Key })
return q
}
// Map converts a Qualifiers struct to a string map.
func (qq Qualifiers) Map() map[string]string {
m := make(map[string]string)
for i := 0; i < len(qq); i++ {
k := qq[i].Key
v := qq[i].Value
m[k] = v
}
return m
}
func (qq Qualifiers) String() string {
var kvPairs []string
for _, q := range qq {
kvPairs = append(kvPairs, q.String())
}
return strings.Join(kvPairs, "&")
}
func (qq *Qualifiers) Normalize() error {
qs := *qq
normedQQ := make(Qualifiers, 0, len(qs))
for _, q := range qs {
if q.Key == "" {
return fmt.Errorf("key is missing from qualifier: %v", q)
}
if q.Value == "" {
// Empty values are equivalent to the key being omitted from the PackageURL.
continue
}
key := strings.ToLower(q.Key)
if !validQualifierKey(key) {
return fmt.Errorf("invalid qualifier key: %q", key)
}
normedQQ = append(normedQQ, Qualifier{key, q.Value})
}
sort.Slice(normedQQ, func(i, j int) bool { return normedQQ[i].Key < normedQQ[j].Key })
for i := 1; i < len(normedQQ); i++ {
if normedQQ[i-1].Key == normedQQ[i].Key {
return fmt.Errorf("duplicate qualifier key: %q", normedQQ[i].Key)
}
}
*qq = normedQQ
return nil
}
// PackageURL is the struct representation of the parts that make a package url
type PackageURL struct {
Type string
Namespace string
Name string
Version string
Qualifiers Qualifiers
Subpath string
}
// NewPackageURL creates a new PackageURL struct instance based on input
func NewPackageURL(purlType, namespace, name, version string,
qualifiers Qualifiers, subpath string) *PackageURL {
return &PackageURL{
Type: purlType,
Namespace: namespace,
Name: name,
Version: version,
Qualifiers: qualifiers,
Subpath: subpath,
}
}
// ToString returns the human-readable instance of the PackageURL structure.
// This is the literal purl as defined by the spec.
func (p *PackageURL) ToString() string {
u := &url.URL{
Scheme: "pkg",
RawQuery: p.Qualifiers.urlQuery(),
Fragment: p.Subpath,
}
paths := []string{p.Type}
// we need to escape each segment by itself, so that we don't escape "/" in the namespace.
for _, segment := range strings.Split(p.Namespace, "/") {
if segment == "" {
continue
}
paths = append(paths, escape(segment))
}
nameWithVersion := escape(p.Name)
if p.Version != "" {
nameWithVersion += "@" + escape(p.Version)
}
paths = append(paths, nameWithVersion)
u.Opaque = strings.Join(paths, "/")
return u.String()
}
func (p PackageURL) String() string {
return p.ToString()
}
// FromString parses a valid package url string into a PackageURL structure
func FromString(purl string) (PackageURL, error) {
u, err := url.Parse(purl)
if err != nil {
return PackageURL{}, fmt.Errorf("failed to parse as URL: %w", err)
}
if u.Scheme != "pkg" {
return PackageURL{}, fmt.Errorf("purl scheme is not \"pkg\": %q", u.Scheme)
}
p := u.Opaque
// if a purl starts with pkg:/ or even pkg://, we need to fall back to host + path.
if p == "" {
p = strings.TrimPrefix(path.Join(u.Host, u.Path), "/")
}
typ, p, ok := strings.Cut(p, "/")
if !ok {
return PackageURL{}, fmt.Errorf("purl is missing type or name")
}
typ = strings.ToLower(typ)
qualifiers, err := parseQualifiers(u.RawQuery)
if err != nil {
return PackageURL{}, fmt.Errorf("invalid qualifiers: %w", err)
}
namespace, name, version, err := separateNamespaceNameVersion(p)
if err != nil {
return PackageURL{}, err
}
pURL := PackageURL{
Qualifiers: qualifiers,
Type: typ,
Namespace: namespace,
Name: name,
Version: version,
Subpath: u.Fragment,
}
err = pURL.Normalize()
return pURL, err
}
// Normalize converts p to its canonical form, returning an error if p is invalid.
func (p *PackageURL) Normalize() error {
typ := strings.ToLower(p.Type)
if !validType(typ) {
return fmt.Errorf("invalid type %q", typ)
}
namespace := strings.Trim(p.Namespace, "/")
if err := p.Qualifiers.Normalize(); err != nil {
return fmt.Errorf("invalid qualifiers: %v", err)
}
if p.Name == "" {
return errors.New("purl is missing name")
}
subpath := strings.Trim(p.Subpath, "/")
segs := strings.Split(p.Subpath, "/")
for i, s := range segs {
if (s == "." || s == "..") && i != 0 {
return fmt.Errorf("invalid Package URL subpath: %q", p.Subpath)
}
}
*p = PackageURL{
Type: typ,
Namespace: typeAdjustNamespace(typ, namespace),
Name: typeAdjustName(typ, p.Name, p.Qualifiers),
Version: typeAdjustVersion(typ, p.Version),
Qualifiers: p.Qualifiers,
Subpath: subpath,
}
return validCustomRules(*p)
}
// escape the given string in a purl-compatible way.
func escape(s string) string {
// for compatibility with other implementations and the purl-spec, we want to escape all
// characters, which is what "QueryEscape" does. The issue with QueryEscape is that it encodes
// " " (space) as "+", which is valid in a query, but invalid in a path (see
// https://stackoverflow.com/questions/2678551/when-should-space-be-encoded-to-plus-or-20) for
// context).
// To work around that, we replace the "+" signs with the path-compatible "%20".
return strings.ReplaceAll(url.QueryEscape(s), "+", "%20")
}
func separateNamespaceNameVersion(path string) (ns, name, version string, err error) {
name = path
if namespaceSep := strings.LastIndex(name, "/"); namespaceSep != -1 {
ns, name = name[:namespaceSep], name[namespaceSep+1:]
ns, err = url.PathUnescape(ns)
if err != nil {
return "", "", "", fmt.Errorf("error unescaping namespace: %w", err)
}
}
if versionSep := strings.LastIndex(name, "@"); versionSep != -1 {
name, version = name[:versionSep], name[versionSep+1:]
version, err = url.PathUnescape(version)
if err != nil {
return "", "", "", fmt.Errorf("error unescaping version: %w", err)
}
}
name, err = url.PathUnescape(name)
if err != nil {
return "", "", "", fmt.Errorf("error unescaping name: %w", err)
}
if name == "" {
return "", "", "", fmt.Errorf("purl is missing name")
}
return ns, name, version, nil
}
func parseQualifiers(rawQuery string) (Qualifiers, error) {
// we need to parse the qualifiers ourselves and cannot rely on the `url.Query` type because
// that uses a map, meaning it's unordered. We want to keep the order of the qualifiers, so this
// function re-implements the `url.parseQuery` function based on our `Qualifier` type. Most of
// the code here is taken from `url.parseQuery`.
q := Qualifiers{}
for rawQuery != "" {
var key string
key, rawQuery, _ = strings.Cut(rawQuery, "&")
if strings.Contains(key, ";") {
return nil, fmt.Errorf("invalid semicolon separator in query")
}
if key == "" {
continue
}
key, value, _ := strings.Cut(key, "=")
key, err := url.QueryUnescape(key)
if err != nil {
return nil, fmt.Errorf("error unescaping qualifier key %q", key)
}
if !validQualifierKey(key) {
return nil, fmt.Errorf("invalid qualifier key: '%s'", key)
}
value, err = url.QueryUnescape(value)
if err != nil {
return nil, fmt.Errorf("error unescaping qualifier value %q", value)
}
q = append(q, Qualifier{
Key: strings.ToLower(key),
Value: value,
})
}
return q, nil
}
// Make any purl type-specific adjustments to the parsed namespace.
// See https://github.com/package-url/purl-spec#known-purl-types
func typeAdjustNamespace(purlType, ns string) string {
switch purlType {
case TypeAlpm,
TypeApk,
TypeBitbucket,
TypeComposer,
TypeDebian,
TypeGithub,
TypeGolang,
TypeNPM,
TypeRPM,
TypeQpkg:
return strings.ToLower(ns)
}
return ns
}
// Make any purl type-specific adjustments to the parsed name.
// See https://github.com/package-url/purl-spec#known-purl-types
func typeAdjustName(purlType, name string, qualifiers Qualifiers) string {
quals := qualifiers.Map()
switch purlType {
case TypeAlpm,
TypeApk,
TypeBitbucket,
TypeBitnami,
TypeComposer,
TypeDebian,
TypeGithub,
TypeGolang,
TypeNPM:
return strings.ToLower(name)
case TypePyPi:
return strings.ToLower(strings.ReplaceAll(name, "_", "-"))
case TypeMLFlow:
return adjustMlflowName(name, quals)
}
return name
}
// Make any purl type-specific adjustments to the parsed version.
// See https://github.com/package-url/purl-spec#known-purl-types
func typeAdjustVersion(purlType, version string) string {
switch purlType {
case TypeHuggingface:
return strings.ToLower(version)
}
return version
}
// https://github.com/package-url/purl-spec/blob/master/PURL-TYPES.rst#mlflow
func adjustMlflowName(name string, qualifiers map[string]string) string {
if repo, ok := qualifiers["repository_url"]; ok {
if strings.Contains(repo, "azureml") {
// Azure ML is case-sensitive and must be kept as-is
return name
} else if strings.Contains(repo, "databricks") {
// Databricks is case-insensitive and must be lowercased
return strings.ToLower(name)
} else {
// Unknown repository type, keep as-is
return name
}
} else {
// No repository qualifier given, keep as-is
return name
}
}
// validQualifierKey validates a qualifierKey against our QualifierKeyPattern.
func validQualifierKey(key string) bool {
return QualifierKeyPattern.MatchString(key)
}
// validType validates a type against our TypePattern.
func validType(typ string) bool {
return TypePattern.MatchString(typ)
}
// validCustomRules evaluates additional rules for each package url type, as specified in the package-url specification.
// On success, it returns nil. On failure, a descriptive error will be returned.
func validCustomRules(p PackageURL) error {
q := p.Qualifiers.Map()
switch p.Type {
case TypeConan:
if p.Namespace != "" {
if val, ok := q["channel"]; ok {
if val == "" {
return errors.New("the qualifier channel must be not empty if namespace is present")
}
} else {
return errors.New("channel qualifier does not exist")
}
} else {
if val, ok := q["channel"]; ok {
if val != "" {
return errors.New("namespace is required if channel is non empty")
}
}
}
case TypeSwift:
if p.Namespace == "" {
return errors.New("namespace is required")
}
if p.Version == "" {
return errors.New("version is required")
}
case TypeCran:
if p.Version == "" {
return errors.New("version is required")
}
}
return nil
}