-
Notifications
You must be signed in to change notification settings - Fork 6
/
parser.go
409 lines (356 loc) · 10.7 KB
/
parser.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
/*
Copyright 2021 Adevinta
*/
package cdc
import (
"context"
"encoding/json"
errs "errors"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/adevinta/errors"
"github.com/adevinta/vulcan-api/pkg/api"
"github.com/adevinta/vulcan-api/pkg/asyncapi"
vulndb "github.com/adevinta/vulcan-api/pkg/vulnerabilitydb"
)
const (
// supported operations
opDeleteTeam = "DeleteTeam"
opCreateAsset = "CreateAsset"
opDeleteAsset = "DeleteAsset"
opUpdateAsset = "UpdateAsset"
opDeleteAllAssets = "DeleteAllAssets"
opFindingOverwrite = "FindingOverwrite"
opMergeDiscoveredAssets = "MergeDiscoveredAssets"
)
var (
errInvalidData = errs.New("invalid data")
errUnsupportedAction = errs.New("unsupported action")
errTargetNotUnique = errs.New("target is not unique")
errUnavailabeJobsRunner = errs.New("unavailable jobs runner")
)
// Parser defines a CDC log parser.
type Parser interface {
// Parse should parse the log events secuentially from the beginning
// of the slice and return the number of events that have been processed
// correctly. So if one event processing is errored, parser should stop
// processing and return current parsed events count.
Parse(log []Event) (nParsed uint)
}
// AsyncTxParser implements a CDC log parser to handle distributed transactions
// for VulnDB and other API asynchronous jobs.
type AsyncTxParser struct {
VulnDBClient vulndb.Client
JobsRunner *api.JobsRunner
logger log.Logger
asyncAPI AsyncAPI
}
// AsyncAPI defines the methods of Vulcan Async API needed by the AyncTxParser.
type AsyncAPI interface {
PushAsset(asset asyncapi.AssetPayload) error
DeleteAsset(asset asyncapi.AssetPayload) error
}
// NewAsyncTxParser builds a new CDC log parser to handle distributed
// transactions for VulnDB and other API asynchronous jobs.
func NewAsyncTxParser(vulnDBClient vulndb.Client, jobsRunner *api.JobsRunner, asyncAPI AsyncAPI, logger log.Logger) *AsyncTxParser {
return &AsyncTxParser{
VulnDBClient: vulnDBClient,
JobsRunner: jobsRunner,
logger: logger,
asyncAPI: asyncAPI,
}
}
// Parse parses the log sequentially processing each event based on its action
// and returns the number of events that have been processed correctly.
// If an error happens during processing of one event, and it is not a permanent
// error, log processing is stopped.
// If a permanent error happens during processing of one event or event has reached
// max processing attempts, that event is discarded counting as if it was processed.
func (p *AsyncTxParser) Parse(log []Event) (nParsed uint) {
var processFunc func([]byte) error
for _, event := range log {
switch event.Action() {
case opDeleteTeam:
processFunc = p.processDeleteTeam
case opCreateAsset:
processFunc = p.processCreateAsset
case opDeleteAsset:
processFunc = p.processDeleteAsset
case opUpdateAsset:
processFunc = p.processUpdateAsset
case opDeleteAllAssets:
processFunc = p.processDeleteAllAssets
case opFindingOverwrite:
processFunc = p.processFindingOverwrite
case opMergeDiscoveredAssets:
processFunc = p.processMergeDiscoveredAssets
default:
// If action is not supported
// log err and stop processing
p.logErr(event, errUnsupportedAction)
return
}
// Process Event
err := processFunc(event.Data())
if err != nil {
// If processing is errored
// log err and stop processing
p.logErr(event, err)
return
}
nParsed++
}
return
}
func (p *AsyncTxParser) processDeleteTeam(data []byte) error {
var dto OpDeleteTeamDTO
err := json.Unmarshal(data, &dto)
if err != nil {
return errInvalidData
}
err = p.VulnDBClient.DeleteTeam(context.Background(), dto.Team.ID, dto.Team.ID)
if err != nil {
if errors.IsKind(err, errors.ErrNotFound) {
return nil
}
return err
}
return nil
}
func (p *AsyncTxParser) processCreateAsset(data []byte) error {
var dto OpCreateAssetDTO
err := json.Unmarshal(data, &dto)
if err != nil {
return errInvalidData
}
asyncAsset := assetToAsyncAsset(dto.Asset)
err = p.asyncAPI.PushAsset(asyncAsset)
if err != nil {
return err
}
payload := api.CreateTarget{
Identifier: dto.Asset.Identifier,
Teams: []string{dto.Asset.Team.ID},
}
_, err = p.VulnDBClient.CreateTarget(context.Background(), payload)
return err
}
func (p *AsyncTxParser) processDeleteAsset(data []byte) error {
var dto OpDeleteAssetDTO
ctx := context.Background()
err := json.Unmarshal(data, &dto)
if err != nil {
return errInvalidData
}
asyncAsset := assetToAsyncAsset(dto.Asset)
err = p.asyncAPI.DeleteAsset(asyncAsset)
if err != nil {
return err
}
// The assets deleted in a "delete all assets" operation only need to be
// published as a delete event through the Vulcan Async API, but not to the
// VulnDB.
if dto.DeleteAllAssetsOp {
return nil
}
if dto.DupAssets > 0 {
// If there are more assets with the same
// identifier and for the same team, do not
// execute tag deletion from VulnDB.
return nil
}
// Retrieve target from VulnDB so we
// can use its ID in delete tag request
params := api.TargetsParams{
Identifier: dto.Asset.Identifier,
// Set match to true so we look for
// targets matching identifier completely
IdentifierMatch: true,
}
ttList, err := p.VulnDBClient.Targets(ctx, params, api.Pagination{})
if err != nil {
return err
}
if len(ttList.Targets) > 1 {
// This should never happen
// with current VunlnDB schema
return errTargetNotUnique
}
if len(ttList.Targets) == 0 {
// If target is not present in
// VulnDB, nothing to do
return nil
}
target := ttList.Targets[0]
teamID := dto.Asset.Team.ID
err = p.VulnDBClient.DeleteTargetTeam(ctx, teamID, target.ID, teamID)
if err != nil {
// If target is not found or if we get a 403 HTTP response status,
// which means that the team is no longer associated with the target,
// there is nothing to do, so return no error.
if errors.IsKind(err, errors.ErrNotFound) || errors.IsKind(err, errors.ErrForbidden) {
return nil
}
return err
}
return nil
}
func (p *AsyncTxParser) processUpdateAsset(data []byte) error {
// For an update operation we only need to publish an event to the Vulcan
// Async API, because the Vulnerability DB is only interested in
// modifications in the identifier of an asset which is currently not
// allowed.
var dto OpUpdateAssetDTO
err := json.Unmarshal(data, &dto)
if err != nil {
return errInvalidData
}
asyncAsset := assetToAsyncAsset(dto.NewAsset)
err = p.asyncAPI.PushAsset(asyncAsset)
if err != nil {
return err
}
return nil
}
func (p *AsyncTxParser) processDeleteAllAssets(data []byte) error {
var dto OpDeleteAllAssetsDTO
err := json.Unmarshal(data, &dto)
if err != nil {
return errInvalidData
}
err = p.VulnDBClient.DeleteTeam(context.Background(), dto.Team.ID, dto.Team.ID)
if err != nil {
if errors.IsKind(err, errors.ErrNotFound) {
return nil
}
return err
}
return nil
}
func (p *AsyncTxParser) processFindingOverwrite(data []byte) error {
var dto OpFindingOverwriteDTO
err := json.Unmarshal(data, &dto)
if err != nil {
return errInvalidData
}
_, err = p.VulnDBClient.UpdateFinding(
context.Background(),
dto.FindingOverwrite.FindingID,
&api.UpdateFinding{
Status: &dto.FindingOverwrite.Status,
},
dto.FindingOverwrite.TeamID)
if err != nil {
if errors.IsKind(err, errors.ErrNotFound) {
return nil
}
return err
}
return nil
}
// processMergeDiscoveredAssets performs the following actions:
// - Marks the Job as RUNNING
// - Calls the MergeDiscoveredAssets operation
// - Marks the Job as DONE
// In the case that the MergeDiscoveredAssets operation fails, the error is
// added to the JobResult.
// Errors are not returned from the function to avoid this operation to be
// retried. They are logged instead.
// NOTE: this operation could be time consuming, and therefore affect
// consistency introduced by latency executing the other distributed
// transactions.
func (p *AsyncTxParser) processMergeDiscoveredAssets(data []byte) error {
var dto OpMergeDiscoveredAssetsDTO
err := json.Unmarshal(data, &dto)
if err != nil {
_ = level.Error(p.logger).Log(
"component", CDCLogTag, "error", err, "action", opMergeDiscoveredAssets,
)
return nil
}
if p.JobsRunner == nil || p.JobsRunner.Client == nil {
_ = level.Error(p.logger).Log(
"component", CDCLogTag, "error", errUnavailabeJobsRunner, "action", opMergeDiscoveredAssets,
)
return nil
}
// Set the status of the Job to RUNNING so the user can track its progress.
job := api.Job{
ID: dto.JobID,
Status: api.JobStatusRunning,
Operation: opMergeDiscoveredAssets,
}
if err := p.updateJob(job); err != nil {
return nil
}
// Execute the merge of the discovered assets.
if err := p.JobsRunner.Client.MergeDiscoveredAssets(context.Background(), dto.TeamID, dto.Assets, dto.GroupName); err != nil {
_ = level.Error(p.logger).Log(
"component", CDCLogTag, "error", err, "job_id", dto.JobID, "action", opMergeDiscoveredAssets,
)
job.Result = &api.JobResult{
Error: err.Error(),
}
}
// Mark the job as DONE.
job.Status = api.JobStatusDone
_, err = p.JobsRunner.Client.UpdateJob(context.Background(), job)
if err := p.updateJob(job); err != nil {
return nil
}
return nil
}
func (p *AsyncTxParser) updateJob(job api.Job) error {
_, err := p.JobsRunner.Client.UpdateJob(context.Background(), job)
if err != nil {
_ = level.Error(p.logger).Log(
"component", CDCLogTag, "error", err, "job_id", job.ID, "action", opMergeDiscoveredAssets,
)
}
return err
}
func (p *AsyncTxParser) logErr(e Event, err error) {
_ = level.Error(p.logger).Log(
"component", CDCLogTag, "error", err, "id", e.ID(), "action", e.Action(), "retries", e.ReadCount()+1,
)
}
// TODO: This function is duplicated here: cmd/vulcan-asset-bumper/main.go, we
// should find a proper package to move it so we have only one function doing
// the same thing.
func assetToAsyncAsset(a api.Asset) asyncapi.AssetPayload {
var annotations []*asyncapi.Annotation
for _, asset := range a.AssetAnnotations {
annotations = append(annotations, &asyncapi.Annotation{
Key: asset.Key,
Value: asset.Value,
})
}
ROLFP := ""
if a.ROLFP != nil {
ROLFP = a.ROLFP.String()
}
scannable := false
if a.Scannable != nil {
scannable = *a.Scannable
}
assetType := ""
if a.AssetType != nil {
assetType = a.AssetType.Name
}
asyncAsset := asyncapi.AssetPayload{
Id: a.ID,
Team: &asyncapi.Team{
Id: a.Team.ID,
Name: a.Team.Name,
Description: a.Team.Description,
Tag: a.Team.Tag,
},
Alias: a.Alias,
Rolfp: ROLFP,
Scannable: scannable,
AssetType: (*asyncapi.AssetType)(&assetType),
Identifier: a.Identifier,
Annotations: annotations,
}
return asyncAsset
}