Debian Codegraph @

packageurl_test.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 package packageurl_test
23
24 import (
25 "encoding/json"
26 "fmt"
27 "os"
28 "path/filepath"
29 "reflect"
30 "regexp"
31 "sort"
32 "strings"
33 "testing"
34
35 "github.com/package-url/packageurl-go"
36 )
37
38 // OrderedMap is used to store the TestFixture.QualifierMap, to ensure that the
39 // declaration order of qualifiers is preserved.
40 type OrderedMap struct {
41 OrderedKeys []string
42 Map map[string]string
43 }
44
45 // qualifiersMapPattern is used to parse the TestFixture "qualifiers" field to
46 // ensure that it's a json object.
47 var qualifiersMapPattern = regexp.MustCompile(`(?ms)^\{.*\}$`)
48
49 // UnmarshalJSON unmarshals the qualifiers field for a TestFixture. The
50 // qualifiers field is given as a json object such as:
51 //
52 // "qualifiers": {"arch": "i386", "distro": "fedora-25"}
53 //
54 // This function performs in-order parsing of these values into an OrderedMap to
55 // preserve items in order of declaration. Note that parsing as a
56 // map[string]string won't preserve element order.
57 func (m *OrderedMap) UnmarshalJSON(bytes []byte) error {
58 data := string(bytes)
59 switch data {
60 case "null":
61 m.OrderedKeys = []string{}
62 m.Map = make(map[string]string)
63 return nil
64 default:
65 // ensure that the data is a json object "{...}"
66 if !qualifiersMapPattern.MatchString(data) {
67 return fmt.Errorf("qualifiers parse error: not a json object: %s", data)
68 }
69
70 // find out the order in which map keys occur
71 dec := json.NewDecoder(strings.NewReader(data))
72 // consume opening '{'
73 _, _ = dec.Token()
74 for dec.More() {
75 t, _ := dec.Token()
76 switch token := t.(type) {
77 case json.Delim:
78 if token != '}' {
79 return fmt.Errorf("qualifiers parse error: expected delimiter '}', got: %v", token)
80 }
81 // closed json object -> we're done
82 case string:
83 // this token is a dictionary key
84 m.OrderedKeys = append(m.OrderedKeys, token)
85 // consume the value (the token following the colon after the key)
86 _, _ = dec.Token()
87 }
88 }
89
90 // now that we know the key order, just fill the OrderedMap.Map field
91 if err := json.Unmarshal(bytes, &m.Map); err != nil {
92 return err
93 }
94 return nil
95 }
96 }
97
98 type ComponentData struct {
99 PackageType string `json:"type"`
100 Namespace string `json:"namespace"`
101 Name string `json:"name"`
102 Version string `json:"version"`
103 QualifierMap OrderedMap `json:"qualifiers"`
104 Subpath string `json:"subpath"`
105 }
106
107 // Qualifiers converts the ComponentData.QualifierMap field to an object of type
108 // packageurl.Qualifiers.
109 func (t ComponentData) Qualifiers() packageurl.Qualifiers {
110 q := packageurl.Qualifiers{}
111
112 for _, key := range t.QualifierMap.OrderedKeys {
113 q = append(q, packageurl.Qualifier{Key: key, Value: t.QualifierMap.Map[key]})
114 }
115
116 return q
117 }
118
119 type ComponentsOrPurl struct {
120 Purl *string
121 PurlComponent *ComponentData
122 }
123
124 func (cop *ComponentsOrPurl) UnmarshalJSON(data []byte) error {
125 // Try string first
126 var s string
127 if err := json.Unmarshal(data, &s); err == nil {
128 cop.Purl = &s
129 return nil
130 }
131
132 var comp ComponentData
133 if err := json.Unmarshal(data, &comp); err == nil {
134 cop.PurlComponent = &comp
135 return nil
136 }
137
138 return fmt.Errorf("ComponentsOrPurl: data is neither a string nor PURL component")
139 }
140
141 type TestFixture struct {
142 Description string `json:"description"`
143 TestGroup string `json:"test_group"`
144 TestType string `json:"test_type"`
145 Input ComponentsOrPurl `json:"input"`
146 ExpectedFailure bool `json:"expected_failure"`
147 ExpectedOutput ComponentsOrPurl `json:"expected_output"`
148 ExpectedFailureReason *string `json:"expected_failure_reason"`
149 }
150
151 type TestSuite struct {
152 Schema string `json:"$schema"`
153 Tests []TestFixture `json:"tests"`
154 }
155
156 type jsonFile struct {
157 name string
158 content []byte
159 }
160
161 func readJSONFilesFromDir(dirPath string) ([]jsonFile, error) {
162 var result []jsonFile
163
164 entries, err := os.ReadDir(dirPath)
165 if err != nil {
166 return nil, fmt.Errorf("reading dir %s: %w", dirPath, err)
167 }
168
169 for _, entry := range entries {
170 if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {
171 continue
172 }
173
174 fullPath := filepath.Join(dirPath, entry.Name())
175 data, err := os.ReadFile(fullPath)
176 if err != nil {
177 return nil, fmt.Errorf("reading file %s: %w", fullPath, err)
178 }
179
180 result = append(result, jsonFile{name: entry.Name(), content: data})
181 }
182
183 return result, nil
184 }
185
186 func roundTripTest(tc TestFixture, t *testing.T) {
187 p, err := packageurl.FromString(*tc.Input.Purl)
188 if tc.ExpectedFailure == false {
189 if err != nil {
190 t.Logf("%s failed: %s", tc.Description, err)
191 t.Fail()
192 }
193
194 if tc.ExpectedOutput.Purl != nil {
195 if *tc.ExpectedOutput.Purl != p.String() {
196 t.Logf("%s: '%s' test failed: wanted: '%s', got '%s'", tc.Description, tc.TestType, *tc.ExpectedOutput.Purl, p.String())
197 t.Fail()
198 }
199 } else {
200 t.Logf("%s: expected output nil: '%s'", tc.Description, *tc.ExpectedOutput.Purl)
201 t.Fail()
202 }
203
204 } else {
205 if err == nil {
206 t.Logf("%s did not fail and returned %#v", tc.Description, p)
207 t.Fail()
208 }
209
210 }
211 }
212
213 func parseTest(tc TestFixture, t *testing.T) {
214 p, err := packageurl.FromString(*tc.Input.Purl)
215 if tc.ExpectedFailure == false {
216 if err != nil {
217 t.Logf("%s failed: %s", tc.Description, err)
218 t.Fail()
219 }
220 // verify parsing
221 expected := tc.ExpectedOutput.PurlComponent
222 if p.Type != expected.PackageType {
223 t.Logf("%s: incorrect package type: wanted: '%s', got '%s'", tc.Description, expected.PackageType, p.Type)
224 t.Fail()
225 }
226 if p.Namespace != expected.Namespace {
227 t.Logf("%s: incorrect namespace: wanted: '%s', got '%s'", tc.Description, expected.Namespace, p.Namespace)
228 t.Fail()
229 }
230 if p.Name != expected.Name {
231 t.Logf("%s: incorrect name: wanted: '%s', got '%s'", tc.Description, expected.Name, p.Name)
232 t.Fail()
233 }
234 if p.Version != expected.Version {
235 t.Logf("%s: incorrect version: wanted: '%s', got '%s'", tc.Description, expected.Version, p.Version)
236 t.Fail()
237 }
238 want := expected.Qualifiers()
239 sort.Slice(want, func(i, j int) bool {
240 return want[i].Key < want[j].Key
241 })
242 got := p.Qualifiers
243 sort.Slice(got, func(i, j int) bool {
244 return got[i].Key < got[j].Key
245 })
246 if !reflect.DeepEqual(want, got) {
247 t.Logf("%s: incorrect qualifiers: wanted: '%#v', got '%#v'", tc.Description, want, p.Qualifiers)
248 t.Fail()
249 }
250
251 if p.Subpath != expected.Subpath {
252 t.Logf("%s: incorrect subpath: wanted: '%s', got '%s'", tc.Description, expected.Subpath, p.Subpath)
253 t.Fail()
254 }
255 } else {
256 // Invalid cases
257 if err == nil {
258 t.Logf("%s did not fail and returned %#v", tc.Description, p)
259 t.Fail()
260 }
261 }
262
263 }
264
265 func buildTest(tc TestFixture, t *testing.T) {
266 input := tc.Input.PurlComponent
267 instance := packageurl.NewPackageURL(
268 input.PackageType, input.Namespace, input.Name, input.Version,
269 // Use QualifiersFromMap so that the qualifiers have a defined order, which is needed for string comparisons
270 packageurl.QualifiersFromMap(input.Qualifiers().Map()), input.Subpath)
271 result := instance.ToString()
272 canonicalExpectedPurl := tc.ExpectedOutput.Purl
273
274 if tc.ExpectedFailure {
275 // String()/ToString() signature won't error so the only reasonable thing is to check this here.
276 err := instance.Normalize()
277 if err == nil {
278 t.Logf("'%s' did not fail for %#v", tc.Description, instance)
279 t.Fail()
280 }
281 } else {
282 if result != *canonicalExpectedPurl {
283 t.Logf("%s: '%s' test failed: wanted: '%s', got '%s'", tc.Description, tc.TestType, *canonicalExpectedPurl, result)
284 t.Fail()
285 }
286 }
287
288 }
289
290 func TestPurlSpecFixtures(t *testing.T) {
291 testFiles, err := readJSONFilesFromDir("testdata/purl-spec/tests/types/")
292 if err != nil {
293 t.Fatal(err)
294 }
295
296 for _, file := range testFiles {
297 var suite TestSuite
298 err := json.Unmarshal(file.content, &suite)
299 if err != nil {
300 t.Fatal(err)
301 }
302
303 for idx, tc := range suite.Tests {
304 testName := fmt.Sprintf("%s[%d]%s", file.name, (idx + 1), tc.TestType)
305 t.Run(testName, func(t *testing.T) {
306 testType := tc.TestType
307
308 switch testType {
309 case "roundtrip":
310 roundTripTest(tc, t)
311 case "parse":
312 parseTest(tc, t)
313 case "build":
314 buildTest(tc, t)
315 default:
316 t.Fatalf("Unsupported test type: %s", testType)
317 }
318
319 })
320
321 }
322 }
323 }
324
325 // Verify correct conversion of Qualifiers to a string map and vice versa.
326 func TestQualifiersMapConversion(t *testing.T) {
327 tests := []struct {
328 kvMap map[string]string
329 qualifiers packageurl.Qualifiers
330 }{
331 {
332 kvMap: map[string]string{},
333 qualifiers: packageurl.Qualifiers{},
334 },
335 {
336 kvMap: map[string]string{"arch": "amd64"},
337 qualifiers: packageurl.Qualifiers{
338 packageurl.Qualifier{Key: "arch", Value: "amd64"},
339 },
340 },
341 {
342 kvMap: map[string]string{"arch": "amd64", "os": "linux"},
343 qualifiers: packageurl.Qualifiers{
344 packageurl.Qualifier{Key: "arch", Value: "amd64"},
345 packageurl.Qualifier{Key: "os", Value: "linux"},
346 },
347 },
348 }
349
350 for _, test := range tests {
351 // map -> Qualifiers
352 got := packageurl.QualifiersFromMap(test.kvMap)
353 if !reflect.DeepEqual(got, test.qualifiers) {
354 t.Logf("map -> qualifiers conversion failed: got: %#v, wanted: %#v", got, test.qualifiers)
355 t.Fail()
356 }
357
358 // Qualifiers -> map
359 mp := test.qualifiers.Map()
360 if !reflect.DeepEqual(mp, test.kvMap) {
361 t.Logf("qualifiers -> map conversion failed: got: %#v, wanted: %#v", mp, test.kvMap)
362 t.Fail()
363 }
364 }
365 }
366
367 func TestNameEscaping(t *testing.T) {
368 testCases := map[string]string{
369 "abc": "pkg:deb/abc",
370 "ab/c": "pkg:deb/ab%2Fc",
371 }
372 for name, output := range testCases {
373 t.Run(name, func(t *testing.T) {
374 p := &packageurl.PackageURL{Type: "deb", Name: name}
375 if s := p.ToString(); s != output {
376 t.Fatalf("wrong escape. expected=%q, got=%q", output, s)
377 }
378 })
379 }
380
381 }
382
383 func TestQualifierMissingEqual(t *testing.T) {
384 input := "pkg:npm/test-pkg?key"
385 want := packageurl.PackageURL{
386 Type: "npm",
387 Name: "test-pkg",
388 Qualifiers: packageurl.Qualifiers{},
389 }
390 got, err := packageurl.FromString(input)
391 if err != nil {
392 t.Fatalf("FromString(%s): unexpected error: %v", input, err)
393 }
394 if !reflect.DeepEqual(want, got) {
395 t.Fatalf("FromString(%s): want %q got %q", input, want, got)
396 }
397 }
398
399 // The plain "foo/../bar" form has always been rejected by Normalize. The percent-encoded form
400 // used to get through, because Subpath still held %2E%2E when that check ran.
401 func TestEncodedDotDotSubpathIsRejected(t *testing.T) {
402 for _, input := range []string{
403 "pkg:generic/[email protected]#foo/../bar",
404 "pkg:generic/[email protected]#foo/%2E%2E/bar",
405 } {
406 if _, err := packageurl.FromString(input); err == nil {
407 t.Errorf("FromString(%s): expected an error, got none", input)
408 }
409 }
410 }
411
412 func TestNormalize(t *testing.T) {
413 testCases := []struct {
414 name string
415 input packageurl.PackageURL
416 want packageurl.PackageURL
417 wantErr bool
418 }{{
419 name: "type is case insensitive",
420 input: packageurl.PackageURL{
421 Type: "NpM",
422 Name: "pkg",
423 },
424 want: packageurl.PackageURL{
425 Type: "npm",
426 Name: "pkg",
427 Qualifiers: packageurl.Qualifiers{},
428 },
429 }, {
430 name: "type is manditory",
431 input: packageurl.PackageURL{
432 Name: "pkg",
433 },
434 wantErr: true,
435 }, {
436 name: "leading and traling / on namespace are trimmed",
437 input: packageurl.PackageURL{
438 Type: "npm",
439 Namespace: "/namespace/org/",
440 Name: "pkg",
441 },
442 want: packageurl.PackageURL{
443 Type: "npm",
444 Namespace: "namespace/org",
445 Name: "pkg",
446 Qualifiers: packageurl.Qualifiers{},
447 },
448 }, {
449 name: "qualifiers with empty values are removed",
450 input: packageurl.PackageURL{
451 Type: "npm",
452 Name: "pkg",
453 Qualifiers: packageurl.Qualifiers{{
454 Key: "k1", Value: "v1",
455 }, {
456 Key: "k2", Value: "",
457 }, {
458 Key: "k3", Value: "v3",
459 }},
460 },
461 want: packageurl.PackageURL{
462 Type: "npm",
463 Name: "pkg",
464 Qualifiers: packageurl.Qualifiers{{
465 Key: "k1", Value: "v1",
466 }, {
467 Key: "k3", Value: "v3",
468 }},
469 },
470 }, {
471 name: "qualifiers are sorted by key",
472 input: packageurl.PackageURL{
473 Type: "npm",
474 Name: "pkg",
475 Qualifiers: packageurl.Qualifiers{{
476 Key: "k3", Value: "v3",
477 }, {
478 Key: "k2", Value: "v2",
479 }, {
480 Key: "k1", Value: "v1",
481 }},
482 },
483 want: packageurl.PackageURL{
484 Type: "npm",
485 Name: "pkg",
486 Qualifiers: packageurl.Qualifiers{{
487 Key: "k1", Value: "v1",
488 }, {
489 Key: "k2", Value: "v2",
490 }, {
491 Key: "k3", Value: "v3",
492 }},
493 },
494 }, {
495 name: "duplicate keys are invalid",
496 input: packageurl.PackageURL{
497 Type: "npm",
498 Name: "pkg",
499 Qualifiers: packageurl.Qualifiers{{
500 Key: "k1", Value: "v1",
501 }, {
502 Key: "k1", Value: "v2",
503 }},
504 },
505 wantErr: true,
506 }, {
507 name: "keys are made lower case",
508 input: packageurl.PackageURL{
509 Type: "npm",
510 Name: "pkg",
511 Qualifiers: packageurl.Qualifiers{{
512 Key: "KeY", Value: "v1",
513 }},
514 },
515 want: packageurl.PackageURL{
516 Type: "npm",
517 Name: "pkg",
518 Qualifiers: packageurl.Qualifiers{{
519 Key: "key", Value: "v1",
520 }},
521 },
522 }, {
523 name: "name is required",
524 input: packageurl.PackageURL{
525 Type: "npm",
526 },
527 wantErr: true,
528 }, {
529 name: "leading and traling / on subpath are trimmed",
530 input: packageurl.PackageURL{
531 Type: "npm",
532 Name: "pkg",
533 Subpath: "/sub/path/",
534 },
535 want: packageurl.PackageURL{
536 Type: "npm",
537 Name: "pkg",
538 Qualifiers: packageurl.Qualifiers{},
539 Subpath: "sub/path",
540 },
541 }, {
542 name: "'.' is an invalid subpath segment",
543 input: packageurl.PackageURL{
544 Type: "npm",
545 Name: "pkg",
546 Subpath: "/sub/./path/",
547 },
548 wantErr: true,
549 }, {
550 name: "'..' is an invalid subpath segment",
551 input: packageurl.PackageURL{
552 Type: "npm",
553 Name: "pkg",
554 Subpath: "/sub/../path/",
555 },
556 wantErr: true,
557 }, {
558 name: "'./' is a valid subpath prefix",
559 input: packageurl.PackageURL{
560 Type: "npm",
561 Name: "pkg",
562 Subpath: "./sub/path",
563 },
564 want: packageurl.PackageURL{
565 Type: "npm",
566 Name: "pkg",
567 Qualifiers: packageurl.Qualifiers{},
568 Subpath: "./sub/path",
569 },
570 }, {
571 name: "'../' is a valid subpath prefix",
572 input: packageurl.PackageURL{
573 Type: "npm",
574 Name: "pkg",
575 Subpath: "../sub/path",
576 },
577 want: packageurl.PackageURL{
578 Type: "npm",
579 Name: "pkg",
580 Qualifiers: packageurl.Qualifiers{},
581 Subpath: "../sub/path",
582 },
583 }, {
584 name: "known type namespace adjustments",
585 input: packageurl.PackageURL{
586 Type: "apk",
587 Namespace: "NaMeSpAcE",
588 Name: "pkg",
589 },
590 want: packageurl.PackageURL{
591 Type: "apk",
592 Namespace: "namespace",
593 Name: "pkg",
594 Qualifiers: packageurl.Qualifiers{},
595 },
596 }, {
597 name: "known type name adjustments",
598 input: packageurl.PackageURL{
599 Type: "alpm",
600 Name: "nAmE",
601 },
602 want: packageurl.PackageURL{
603 Type: "alpm",
604 Name: "name",
605 Qualifiers: packageurl.Qualifiers{},
606 },
607 }, {
608 name: "known type version adjustments",
609 input: packageurl.PackageURL{
610 Type: "huggingface",
611 Name: "name",
612 Version: "VeRsIoN",
613 },
614 want: packageurl.PackageURL{
615 Type: "huggingface",
616 Name: "name",
617 Version: "version",
618 Qualifiers: packageurl.Qualifiers{},
619 },
620 }}
621
622 for _, testCase := range testCases {
623 t.Run(testCase.name, func(t *testing.T) {
624 got := testCase.input
625 err := got.Normalize()
626 if err != nil && testCase.wantErr {
627 return
628 }
629 if err != nil && !testCase.wantErr {
630 t.Fatalf("Normalize(%s): unexpected error: %v", testCase.name, err)
631 }
632 if testCase.wantErr {
633 t.Fatalf("Normalize(%s): want error, got none", testCase.name)
634 }
635 if !reflect.DeepEqual(testCase.want, got) {
636 t.Fatalf("Normalize(%s):\nwant %#v\ngot %#v", testCase.name, testCase.want, got)
637 }
638 })
639 }
640 }
641
642 // purlExpectation represents an expected canonical purl and destructured [packageurl.PackageURL]
643 // for a given input string.
644 type purlExpectation struct {
645 // input represents a user-supplied purl input string to be parsed.
646 input string
647
648 // canonical is the expected canonical string represenation for input.
649 canonical string
650 // purl is the expected [packageurl.PackageURL] for input.
651 purl packageurl.PackageURL
652 }
653
654 // TestRoundtrip is intended to cover some tricky purl parsing/canonicalization that is not covered
655 // by the purl-spec tests (yet).
656 func TestRoundtrip(t *testing.T) {
657 tests := []struct {
658 name string
659 expectation purlExpectation
660 }{
661 {
662 name: "input version with unescaped slashes",
663 expectation: purlExpectation{
664 input: "pkg:github/golang/mod@refs/tags/v0.30.0",
665 canonical: "pkg:github/golang/mod@refs%2Ftags%2Fv0.30.0",
666 purl: packageurl.PackageURL{
667 Type: packageurl.TypeGithub,
668 Namespace: "golang",
669 Name: "mod",
670 Version: "refs/tags/v0.30.0",
671 Qualifiers: packageurl.Qualifiers{}}},
672 },
673
674 {
675 name: "go modules can have vanity urls without namespace",
676 expectation: purlExpectation{
677 input: "pkg:golang/[email protected]",
678 canonical: "pkg:golang/[email protected]",
679 purl: packageurl.PackageURL{
680 Type: packageurl.TypeGolang,
681 Name: "go.opencensus.io",
682 Version: "v0.20.1",
683 Qualifiers: packageurl.Qualifiers{}}},
684 },
685
686 {
687 name: "version with unescaped plus characters, qualifiers and subpath",
688 expectation: purlExpectation{
689 input: "pkg:deb/debian/[email protected]+md510+dhx1-1.1?distro=stretch&repository_url=http://deb.debian.org&arch=amd64#subpath/to/file",
690 canonical: "pkg:deb/debian/[email protected]%2Bmd510%2Bdhx1-1.1?arch=amd64&distro=stretch&repository_url=http:%2F%2Fdeb.debian.org#subpath/to/file",
691 purl: packageurl.PackageURL{
692 Type: packageurl.TypeDebian,
693 Namespace: "debian",
694 Name: "nuget",
695 Version: "2.8.7+md510+dhx1-1.1",
696 Qualifiers: packageurl.Qualifiers{
697 {Key: "arch", Value: "amd64"},
698 {Key: "distro", Value: "stretch"},
699 {Key: "repository_url", Value: "http://deb.debian.org"},
700 },
701 Subpath: "subpath/to/file"}},
702 },
703
704 {
705 name: "npm package with unescaped @ in scope and no version",
706 expectation: purlExpectation{
707 input: "pkg:npm/@opentelemetry/sdk-trace-node",
708 canonical: "pkg:npm/%40opentelemetry/sdk-trace-node",
709 purl: packageurl.PackageURL{
710 Type: packageurl.TypeNPM,
711 Namespace: "@opentelemetry",
712 Name: "sdk-trace-node",
713 Qualifiers: packageurl.Qualifiers{}}},
714 },
715
716 {
717 name: "npm package with unescaped @ in scope and version",
718 expectation: purlExpectation{
719 input: "pkg:npm/@opentelemetry/[email protected]",
720 canonical: "pkg:npm/%40opentelemetry/[email protected]",
721 purl: packageurl.PackageURL{
722 Type: packageurl.TypeNPM,
723 Namespace: "@opentelemetry",
724 Name: "sdk-trace-node",
725 Version: "2.2.0",
726 Qualifiers: packageurl.Qualifiers{}}},
727 },
728
729 {
730 name: "percent-encoded subpath is decoded on parse",
731 expectation: purlExpectation{
732 input: "pkg:cocoapods/[email protected]#NSData%2Bzlib",
733 canonical: "pkg:cocoapods/[email protected]#NSData%2Bzlib",
734 purl: packageurl.PackageURL{
735 Type: packageurl.TypeCocoapods,
736 Name: "GoogleUtilities",
737 Version: "7.5.2",
738 Qualifiers: packageurl.Qualifiers{},
739 Subpath: "NSData+zlib"}},
740 },
741
742 // Per the purl spec character-encoding section, only alphanumerics, '-', '.',
743 // '_', '~', and ':' may appear unencoded in name/version/subpath segments.
744 // All other characters — including RFC 3986 sub-delimiters such as '(', ')',
745 // '!', '$', '&', "'", '*', ',', ';', '=' — must be percent-encoded.
746 {
747 name: "name and version with sub-delimiters are percent-encoded",
748 expectation: purlExpectation{
749 input: "pkg:generic/Microsoft%20Visual%20C%2B%2B%20%28x86%[email protected]%2A",
750 canonical: "pkg:generic/Microsoft%20Visual%20C%2B%2B%20%28x86%[email protected]%2A",
751 purl: packageurl.PackageURL{
752 Type: packageurl.TypeGeneric,
753 Name: "Microsoft Visual C++ (x86)",
754 Version: "14.28.29913*",
755 Qualifiers: packageurl.Qualifiers{}}},
756 },
757
758 // See https://github.com/package-url/purl-spec/discussions/814#discussioncomment-15837007
759 {
760 name: "interpret + character in qualifier as literal plus (not space)",
761 expectation: purlExpectation{
762 input: "pkg:generic/[email protected]?checksum=sha256:18a348109d3f92772bee72a55eabb9d318596add6a70b92adb6ff8e789d587a8&download_url=https://dl.grafana.com/enterprise/release/grafana-enterprise-12.0.1+security-01.linux-amd64.tar.gz",
763 canonical: "pkg:generic/[email protected]?checksum=sha256:18a348109d3f92772bee72a55eabb9d318596add6a70b92adb6ff8e789d587a8&download_url=https:%2F%2Fdl.grafana.com%2Fenterprise%2Frelease%2Fgrafana-enterprise-12.0.1%2Bsecurity-01.linux-amd64.tar.gz",
764 purl: packageurl.PackageURL{
765 Type: packageurl.TypeGeneric,
766 Name: "grafana",
767 Version: "12.0.1",
768 Qualifiers: packageurl.Qualifiers{
769 {Key: "checksum", Value: "sha256:18a348109d3f92772bee72a55eabb9d318596add6a70b92adb6ff8e789d587a8"},
770 {Key: "download_url", Value: "https://dl.grafana.com/enterprise/release/grafana-enterprise-12.0.1+security-01.linux-amd64.tar.gz"},
771 }}},
772 },
773 }
774
775 for _, tc := range tests {
776 t.Run(tc.name, func(t *testing.T) {
777 got, err := packageurl.FromString(tc.expectation.input)
778 if err != nil {
779 t.Fatalf("FromString(%s) unexpectedly failed: %v", tc.expectation.input, err)
780 }
781 if !reflect.DeepEqual(tc.expectation.purl, got) {
782 t.Fatalf("FromString(%s):\nwanted: %#v\ngot: %#v", tc.expectation.input, tc.expectation.purl, got)
783 }
784
785 if got.String() != tc.expectation.canonical {
786 t.Fatalf("String(%s):\nwanted: %s\ngot: %s", tc.expectation.input, tc.expectation.canonical, got.String())
787 }
788 })
789 }
790 }
791
792 // TestNpmScopeWithoutName guards the regression reported in
793 // https://github.com/package-url/packageurl-go/issues/91. An npm purl whose
794 // remainder is a bare scope with no name (a leading '@' and no '/') must return
795 // "purl is missing name", while valid scoped and unscoped npm purls keep
796 // parsing.
797 func TestNpmScopeWithoutName(t *testing.T) {
798 tests := []struct {
799 name string
800 input string
801 wantErr bool
802 wantName string
803 wantNS string
804 wantVer string
805 }{
806 {
807 name: "bare scope without name returns error",
808 input: "pkg:npm/@4.17.21",
809 wantErr: true,
810 },
811 {
812 name: "bare scope without name or version returns error",
813 input: "pkg:npm/@babel",
814 wantErr: true,
815 },
816 {
817 name: "scoped package with name and version parses",
818 input: "pkg:npm/@opentelemetry/[email protected]",
819 wantName: "sdk-trace-node",
820 wantNS: "@opentelemetry",
821 wantVer: "2.2.0",
822 },
823 {
824 name: "scoped package with name and no version parses",
825 input: "pkg:npm/@opentelemetry/sdk-trace-node",
826 wantName: "sdk-trace-node",
827 wantNS: "@opentelemetry",
828 },
829 {
830 name: "unscoped package with version parses",
831 input: "pkg:npm/[email protected]",
832 wantName: "lodash",
833 wantVer: "4.17.21",
834 },
835 }
836
837 for _, tc := range tests {
838 t.Run(tc.name, func(t *testing.T) {
839 got, err := packageurl.FromString(tc.input)
840 if tc.wantErr {
841 if err == nil {
842 t.Fatalf("FromString(%s): expected error, got nil (parsed as %#v)", tc.input, got)
843 }
844 return
845 }
846 if err != nil {
847 t.Fatalf("FromString(%s) unexpectedly failed: %v", tc.input, err)
848 }
849 if got.Name != tc.wantName {
850 t.Errorf("FromString(%s): name = %q, want %q", tc.input, got.Name, tc.wantName)
851 }
852 if got.Namespace != tc.wantNS {
853 t.Errorf("FromString(%s): namespace = %q, want %q", tc.input, got.Namespace, tc.wantNS)
854 }
855 if got.Version != tc.wantVer {
856 t.Errorf("FromString(%s): version = %q, want %q", tc.input, got.Version, tc.wantVer)
857 }
858 })
859 }
860 }