-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathpurl.go
More file actions
302 lines (265 loc) · 9.21 KB
/
purl.go
File metadata and controls
302 lines (265 loc) · 9.21 KB
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
//
// Copyright 2023 The GUAC Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helpers
import (
"fmt"
"net/url"
"path/filepath"
"sort"
"strings"
"github.com/guacsec/guac/internal/testing/ptrfrom"
model "github.com/guacsec/guac/pkg/assembler/clients/generated"
purl "github.com/package-url/packageurl-go"
)
const (
PurlTypeGuac = "guac"
PurlFilesGuac = "pkg:guac/files/"
PurlPkgGuac = "pkg:guac/pkg/"
)
// PurlToPkg converts a purl URI string into a graphql package node
func PurlToPkg(purlUri string) (*model.PkgInputSpec, error) {
p, err := purl.FromString(purlUri)
if err != nil {
return nil, fmt.Errorf("unable to parse purl %s: %v", purlUri, err)
}
return purlConvert(p)
}
// PurlToPkgFilter converts a purl URI string into a graphql package filter spec.
// The result will only match the input purl, and no other packages. The filter
// is created with Guac's purl special casing.
func PurlToPkgFilter(purl string) (model.PkgSpec, error) {
inputSpec, err := PurlToPkg(purl)
if err != nil {
return model.PkgSpec{}, err
}
var qualifiers []model.PackageQualifierSpec
for _, q := range inputSpec.Qualifiers {
q := q
qualifiers = append(qualifiers, model.PackageQualifierSpec{
Key: q.Key,
Value: &q.Value,
})
}
return model.PkgSpec{
Type: &inputSpec.Type,
Namespace: ptrfrom.String(nilToEmpty(inputSpec.Namespace)),
Name: &inputSpec.Name,
Version: ptrfrom.String(nilToEmpty(inputSpec.Version)),
Qualifiers: qualifiers,
Subpath: ptrfrom.String(nilToEmpty(inputSpec.Subpath)),
MatchOnlyEmptyQualifiers: ptrfrom.Bool(len(qualifiers) == 0),
}, nil
}
// AllPkgTreeToPurl takes one package trie evaluation and converts it into a PURL
// it will only do this for one PURL, and will ignore other pkg tries in the fragment
func AllPkgTreeToPurl(v *model.AllPkgTree) string {
ns := v.Namespaces[0]
nsStr := ns.Namespace
name := ns.Names[0]
nameStr := name.Name
versionStr := ""
subpathStr := ""
qualifierStrs := []string{}
if len(name.Versions) > 0 {
version := v.Namespaces[0].Names[0].Versions[0]
versionStr = version.Version
subpathStr = version.Subpath
for _, v := range version.Qualifiers {
qualifierStrs = append(qualifierStrs, v.GetKey())
qualifierStrs = append(qualifierStrs, v.GetValue())
}
}
purl := PkgToPurl(v.Type, nsStr, nameStr, versionStr, subpathStr, qualifierStrs)
return purl
}
func PkgInputSpecToPurl(currentPkg *model.PkgInputSpec) string {
qualifiersMap := map[string]string{}
keys := []string{}
for _, kv := range currentPkg.Qualifiers {
qualifiersMap[kv.Key] = kv.Value
keys = append(keys, kv.Key)
}
sort.Strings(keys)
qualifiers := []string{}
for _, k := range keys {
qualifiers = append(qualifiers, k, qualifiersMap[k])
}
var ns, ver, subpath string
if currentPkg.Namespace != nil {
ns = *currentPkg.Namespace
}
if currentPkg.Version != nil {
ver = *currentPkg.Version
}
if currentPkg.Subpath != nil {
subpath = *currentPkg.Subpath
}
return PkgToPurl(currentPkg.Type, ns, currentPkg.Name, ver, subpath, qualifiers)
}
func PkgToPurl(purlType, namespace, name, version, subpath string, qualifiersList []string) string {
collectedQualifiers := purl.Qualifiers{}
for i := range qualifiersList {
if i%2 == 0 {
qualifier := purl.Qualifier{
Key: qualifiersList[i],
Value: qualifiersList[i+1],
}
collectedQualifiers = append(collectedQualifiers, qualifier)
}
}
if purlType == purl.TypeOCI || purlType == purl.TypeDocker {
if namespace != "" {
collectedQualifiers = append(collectedQualifiers, purl.Qualifier{Key: "repository_url", Value: namespace})
namespace = ""
}
}
pkg := purl.NewPackageURL(purlType, namespace, name, version, collectedQualifiers, subpath)
return pkg.ToString()
}
func purlConvert(p purl.PackageURL) (*model.PkgInputSpec, error) {
switch p.Type {
// Enumeration of https://github.com/package-url/purl-spec#known-purl-types
// TODO(lumjjb): each PURL definition usually comes with a default repository
// we should consider addition of default repository to the prefix of the namespace
// so that they can be referenced with higher specificity in GUAC
//
// PURL types not defined in purl library handled generically
case "alpine", "githubactions", PurlTypeGuac:
fallthrough
// PURL types defined in purl library handled generically
case purl.TypeBitbucket, purl.TypeCocoapods, purl.TypeCargo,
purl.TypeComposer, purl.TypeConan, purl.TypeConda, purl.TypeCran,
purl.TypeDebian, purl.TypeGem, purl.TypeGithub,
purl.TypeGolang, purl.TypeHackage, purl.TypeHex, purl.TypeMaven,
purl.TypeNPM, purl.TypeNuget, purl.TypePyPi, purl.TypeRPM, purl.TypeSwift,
purl.TypeGeneric, purl.TypeYocto, purl.TypeCpan,
purl.TypeAlpm, purl.TypeApk, purl.TypeBitnami, purl.TypeHuggingface,
purl.TypeMLFlow, purl.TypePub, purl.TypeQpkg, purl.TypeSWID:
r := pkg(p.Type, p.Namespace, p.Name, p.Version, p.Subpath, p.Qualifiers.Map())
return r, nil
// Special cases handled separately
case purl.TypeOCI:
// For OCI, the namespace is not used and respository_url may contain a namespace
// as part of the physical location of the package. Therefore, in order to use it
// in the graphQL model consistently with other types, we special case OCI to take
// the respository_url and encode it as the Package namespace.
//
// Ref: https://github.com/package-url/purl-spec/blob/master/PURL-TYPES.rst#oci
qs := p.Qualifiers.Map()
// Not technically part of the spec but some PURLs still include the namespace
// as part of the PURL
var ns string = p.Namespace
for k, v := range qs {
if k == "repository_url" {
ns = v
}
}
delete(qs, "repository_url")
ns = strings.TrimSuffix(ns, "/"+p.Name)
r := pkg(p.Type, ns, p.Name, p.Version, p.Subpath, qs)
return r, nil
case purl.TypeDocker:
// Similar to the case of OCI as above, but difference is that the namespace can be
// used to specify registry/user/organization if present.
//
// It states
// - The default repository is https://hub.docker.com.
// - The namespace is the registry/user/organization if present.
// - The version should be the image id sha256 or a tag. Since tags can
// be moved, a sha256 image id is preferred. as part of the physical
// location of the package.. However, this is not enforced, and examples use tags
//
// Ref: https://github.com/package-url/purl-spec/blob/master/PURL-TYPES.rst#docker
qs := p.Qualifiers.Map()
var repUrl string
for k, v := range qs {
if k == "repository_url" {
repUrl = v
}
}
delete(qs, "repository_url")
ns := filepath.Join(repUrl, p.Namespace)
ns = strings.Trim(ns, "/")
r := pkg(p.Type, ns, p.Name, p.Version, p.Subpath, qs)
return r, nil
default:
if _, ok := purl.KnownTypes[p.Type]; ok {
return nil, fmt.Errorf("unhandled known PURL type: %q. Please report at https://github.com/guacsec/guac/issues/new", p.Type)
}
if _, ok := purl.CandidateTypes[p.Type]; ok {
return nil, fmt.Errorf("unhandled candidate PURL type: %q. Please report at https://github.com/guacsec/guac/issues/new", p.Type)
}
return nil, fmt.Errorf("unsupported PURL type: %q", p.Type)
}
}
func pkg(typ, namespace, name, version, subpath string, qualifiers map[string]string) *model.PkgInputSpec {
var pQualifiers []model.PackageQualifierInputSpec
for k, v := range qualifiers {
pQualifiers = append(pQualifiers, model.PackageQualifierInputSpec{
Key: k,
Value: v,
})
}
p := &model.PkgInputSpec{
Type: typ,
Namespace: &namespace,
Name: name,
Version: &version,
Subpath: &subpath,
Qualifiers: pQualifiers,
}
return p
}
func SanitizeString(s string) string {
escapedName := ""
if strings.Contains(s, "/") {
var ns []string
for _, item := range strings.Split(s, "/") {
ns = append(ns, url.QueryEscape(item))
}
escapedName = strings.Join(ns, "/")
} else {
escapedName = url.QueryEscape(s)
}
return escapedName
}
func GuacPkgPurl(pkgName string, pkgVersion *string) string {
escapedName := SanitizeString(pkgName)
if pkgVersion == nil {
return fmt.Sprintf(PurlPkgGuac+"%s", escapedName)
}
return fmt.Sprintf(PurlPkgGuac+"%s@%s", escapedName, *pkgVersion)
}
func GuacFilePurl(alg string, digest string, filename *string) string {
s := fmt.Sprintf(PurlFilesGuac+"%s:%s", strings.ToLower(alg), digest)
if filename != nil {
s += fmt.Sprintf("?filename=%s", SanitizeString(*filename))
}
return s
}
func GuacGenericPurl(s string) string {
sanitizedString := SanitizeString(s)
if strings.HasPrefix(sanitizedString, "/") {
return fmt.Sprintf("pkg:guac/generic%s", sanitizedString)
} else {
return fmt.Sprintf("pkg:guac/generic/%s", sanitizedString)
}
}
func nilToEmpty(s *string) string {
if s == nil {
return ""
}
return *s
}