/
backend.go
323 lines (291 loc) · 7.57 KB
/
backend.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
//
// 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 keyvalue
import (
"context"
"errors"
"fmt"
"hash/fnv"
"math"
"reflect"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/guacsec/guac/pkg/assembler/backends"
"github.com/guacsec/guac/pkg/assembler/graphql/model"
"github.com/guacsec/guac/pkg/assembler/kv"
"github.com/guacsec/guac/pkg/assembler/kv/memmap"
)
func init() {
backends.Register("keyvalue", getBackend)
}
// node is the common interface of all backend nodes.
type node interface {
// ID provides global IDs for all nodes that can be referenced from
// other places in GUAC.
//
// Since we always ingest data and never remove,
// we can keep this global and increment it as needed.
//
// For fast retrieval, we also keep a map from ID from nodes that have
// it.
//
// IDs are stored as string in graphql even though we ask for integers
// See https://github.com/99designs/gqlgen/issues/2561
ID() string
// Neighbors allows retrieving neighbors of a node using the backlinks.
//
// This is useful for path related queries where the type of the node
// is not as relevant as its connections.
//
// The allowedEdges argument allows filtering the set of neighbors to
// only include certain GUAC verbs.
Neighbors(allowedEdges edgeMap) []string
// BuildModelNode builds a GraphQL return type for a backend node,
BuildModelNode(ctx context.Context, c *demoClient) (model.Node, error)
// Key is used to store the node in the key value store.
Key() string
}
var errNotFound = errors.New("not found")
var errTypeNotMatch = errors.New("Stored type does not match")
// Scorecard scores are in range of 1-10, so a single step at 100 should be
// plenty big
var epsilon = math.Nextafter(100, 100.1) - 100
const (
// Collection names must not have ":" in them
indexCol = "index"
artCol = "artifacts"
occCol = "isOccurrences"
pkgTypeCol = "pkgTypes"
pkgNSCol = "pkgNamespaces"
pkgNameCol = "pkgNames"
pkgVerCol = "pkgVersions"
isDepCol = "isDependencies"
hasMDCol = "hasMetadatas"
hasSBOMCol = "hasSBOMs"
srcTypeCol = "srcTypes"
srcNSCol = "srcNamespaces"
srcNameCol = "srcNames"
cgCol = "certifyGoods"
cbCol = "certifyBads"
builderCol = "builders"
licenseCol = "licenses"
clCol = "certifyLegals"
cscCol = "certifyScorecards"
slsaCol = "hasSLSAs"
hsaCol = "hasSourceAts"
hashEqCol = "hashEquals"
pkgEqCol = "pkgEquals"
pocCol = "pointOfContacts"
vulnTypeCol = "vulnTypes"
vulnIDCol = "vulnIDs"
vulnEqCol = "vulnEquals"
vulnMDCol = "vulnMetadatas"
cVEXCol = "certifyVEXs"
cVulnCol = "certifyVulns"
)
func typeColMap(col string) node {
switch col {
case artCol:
return &artStruct{}
case occCol:
return &isOccurrenceStruct{}
case pkgTypeCol:
return &pkgType{}
case pkgNSCol:
return &pkgNamespace{}
case pkgNameCol:
return &pkgName{}
case pkgVerCol:
return &pkgVersion{}
case isDepCol:
return &isDependencyLink{}
case hasMDCol:
return &hasMetadataLink{}
case hasSBOMCol:
return &hasSBOMStruct{}
case srcTypeCol:
return &srcType{}
case srcNSCol:
return &srcNamespace{}
case srcNameCol:
return &srcNameNode{}
case cgCol:
return &goodLink{}
case cbCol:
return &badLink{}
case builderCol:
return &builderStruct{}
case licenseCol:
return &licStruct{}
case clCol:
return &certifyLegalStruct{}
case cscCol:
return &scorecardLink{}
case slsaCol:
return &hasSLSAStruct{}
case hsaCol:
return &srcMapLink{}
case hashEqCol:
return &hashEqualStruct{}
case pkgEqCol:
return &pkgEqualStruct{}
case pocCol:
return &pointOfContactLink{}
case vulnTypeCol:
return &vulnTypeStruct{}
case vulnIDCol:
return &vulnIDNode{}
case vulnEqCol:
return &vulnerabilityEqualLink{}
case vulnMDCol:
return &vulnerabilityMetadataLink{}
case cVEXCol:
return &vexLink{}
case cVulnCol:
return &certifyVulnerabilityLink{}
}
return &artStruct{}
}
// atomic add to ensure ID is not duplicated
func (c *demoClient) getNextID() string {
atomic.AddUint32(&c.id, 1)
return fmt.Sprintf("%d", c.id)
}
type demoClient struct {
id uint32
m sync.RWMutex
kv kv.Store
}
func getBackend(ctx context.Context, opts backends.BackendArgs) (backends.Backend, error) {
store, ok := opts.(kv.Store)
if !ok {
store = memmap.GetStore()
}
return &demoClient{kv: store}, nil
}
func noMatch(filter *string, value string) bool {
if filter != nil {
return value != *filter
}
return false
}
func nilToEmpty(input *string) string {
if input == nil {
return ""
}
return *input
}
func toLower(filter *string) *string {
if filter != nil {
lower := strings.ToLower(*filter)
return &lower
}
return nil
}
func noMatchFloat(filter *float64, value float64) bool {
if filter != nil {
return math.Abs(*filter-value) > epsilon
}
return false
}
func byIDkv[E node](ctx context.Context, id string, c *demoClient) (E, error) {
var nl E
var k string
if err := c.kv.Get(ctx, indexCol, id, &k); err != nil {
return nl, fmt.Errorf("%w : id not found in index %q", err, id)
}
sub := strings.SplitN(k, ":", 2)
if len(sub) != 2 {
return nl, fmt.Errorf("Bad value was stored in index map: %v", k)
}
return byKeykv[E](ctx, sub[0], sub[1], c)
}
func byKeykv[E node](ctx context.Context, coll string, k string, c *demoClient) (E, error) {
var nl E
if err := validateType(nl, coll); err != nil {
return nl, err
}
err := c.kv.Get(ctx, coll, k, &nl)
return nl, err
}
func setkv(ctx context.Context, coll string, n node, c *demoClient) error {
// validate type?
return c.kv.Set(ctx, coll, n.Key(), n)
}
func (c *demoClient) addToIndex(ctx context.Context, coll string, n node) error {
if err := validateType(n, coll); err != nil {
return err
}
val := strings.Join([]string{coll, n.Key()}, ":")
return c.kv.Set(ctx, indexCol, n.ID(), val)
}
func validateType[E node](n E, c string) error {
if reflect.TypeOf(typeColMap(c)) == reflect.TypeOf(n) {
return nil
}
return fmt.Errorf("%w : found: %q want: %q", errTypeNotMatch,
reflect.TypeOf(typeColMap(c)), reflect.TypeOf(n))
}
func lock(m *sync.RWMutex, readOnly bool) {
if readOnly {
m.RLock()
} else {
m.Lock()
}
}
func unlock(m *sync.RWMutex, readOnly bool) {
if readOnly {
m.RUnlock()
} else {
m.Unlock()
}
}
func timeKey(t time.Time) string {
return fmt.Sprint(t.Unix())
}
func (c *demoClient) getPackageVersionAndArtifacts(ctx context.Context, pkgOrArt []string) ([]string, []string, error) {
var pkgs []string
var arts []string
for _, id := range pkgOrArt {
found := false
if _, err := byIDkv[*pkgVersion](ctx, id, c); err == nil {
pkgs = append(pkgs, id)
found = true
}
if _, err := byIDkv[*artStruct](ctx, id, c); err == nil {
arts = append(arts, id)
found = true
}
if !found {
return nil, nil, fmt.Errorf("unexpected type in package or artifact list")
}
}
return pkgs, arts, nil
}
func hashKey(in string) string {
h := fnv.New128a()
h.Write([]byte(in))
bts := h.Sum(nil)
return fmtBytes(bts)
}
func fmtBytes(s []byte) string {
strs := make([]string, len(s))
for i, v := range s {
strs[i] = fmt.Sprintf("%x", v)
}
return strings.Join(strs, "")
}