-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathreprocessor_unit_test.go
More file actions
738 lines (671 loc) · 32.7 KB
/
reprocessor_unit_test.go
File metadata and controls
738 lines (671 loc) · 32.7 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
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
package reprocessor
import (
"context"
"fmt"
"testing"
"time"
"github.com/pkg/errors"
mockDeploymentDataStore "github.com/stackrox/rox/central/deployment/datastore/mocks"
"github.com/stackrox/rox/central/deployment/views"
mockImageDataStore "github.com/stackrox/rox/central/image/datastore/mocks"
mockImageV2DataStore "github.com/stackrox/rox/central/imagev2/datastore/mocks"
nodeDatastoreMocks "github.com/stackrox/rox/central/node/datastore/mocks"
riskManagerMocks "github.com/stackrox/rox/central/risk/manager/mocks"
"github.com/stackrox/rox/central/sensor/service/connection"
connectionMocks "github.com/stackrox/rox/central/sensor/service/connection/mocks"
"github.com/stackrox/rox/generated/internalapi/central"
"github.com/stackrox/rox/generated/storage"
"github.com/stackrox/rox/pkg/concurrency"
"github.com/stackrox/rox/pkg/features"
imageEnricher "github.com/stackrox/rox/pkg/images/enricher"
"github.com/stackrox/rox/pkg/images/enricher/mocks"
nodesEnricherMocks "github.com/stackrox/rox/pkg/nodes/enricher/mocks"
"github.com/stackrox/rox/pkg/protocompat"
"github.com/stackrox/rox/pkg/sac"
"github.com/stackrox/rox/pkg/sac/resources"
"github.com/stackrox/rox/pkg/search"
"github.com/stackrox/rox/pkg/sensor/event"
"github.com/stackrox/rox/pkg/testutils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
"google.golang.org/protobuf/proto"
)
func Test_loopImpl_reprocessNode(t *testing.T) {
type args struct {
id string
}
type mocks struct {
nodes *nodeDatastoreMocks.MockDataStore
risk *riskManagerMocks.MockManager
nodeEnricher *nodesEnricherMocks.MockNodeEnricher
}
tests := []struct {
name string
args args
node *storage.Node
want bool
setUpMocks func(t *testing.T, a *args, m *mocks)
}{
{
name: "when node is RHCOS then nothing is done",
setUpMocks: func(t *testing.T, a *args, m *mocks) {
node := &storage.Node{
OsImage: "Red Hat Enterprise Linux CoreOS 412.86.202302091419-0 (Ootpa)",
}
m.nodes.EXPECT().GetNode(gomock.Any(), a.id).Return(node, true, nil)
},
},
{
name: "when node is not RHCOS then scanner is called and node is upserted",
setUpMocks: func(t *testing.T, a *args, m *mocks) {
node := &storage.Node{
OsImage: "Something that is not RHCOS",
LastUpdated: protocompat.TimestampNow(),
}
gomock.InOrder(
m.nodes.EXPECT().GetNode(gomock.Any(), gomock.Eq(a.id)).Times(1).Return(node, true, nil),
m.nodeEnricher.EXPECT().EnrichNode(node).Times(1).Return(nil),
m.risk.EXPECT().CalculateRiskAndUpsertNode(gomock.Any()).Return(nil).Times(1),
)
},
want: true,
},
{
name: "when node storage returns err then returns false",
setUpMocks: func(t *testing.T, a *args, m *mocks) {
m.nodes.EXPECT().GetNode(gomock.Any(), a.id).Times(1).Return(nil, false, errors.New("foobar"))
},
want: false,
},
{
name: "when node storage is successful but node is not found then returns false",
setUpMocks: func(t *testing.T, a *args, m *mocks) {
m.nodes.EXPECT().GetNode(gomock.Any(), a.id).Times(1).Return(nil, false, nil)
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
m := mocks{
nodes: nodeDatastoreMocks.NewMockDataStore(ctrl),
risk: riskManagerMocks.NewMockManager(ctrl),
nodeEnricher: nodesEnricherMocks.NewMockNodeEnricher(ctrl),
}
tt.setUpMocks(t, &tt.args, &m)
l := &loopImpl{
nodes: m.nodes,
risk: m.risk,
nodeEnricher: m.nodeEnricher,
}
if got := l.reprocessNode(tt.args.id); got != tt.want {
t.Errorf("reprocessNode() = %v, want %v", got, tt.want)
}
})
}
}
func TestReprocessWatchedImageDelegation(t *testing.T) {
testutils.MustUpdateFeature(t, features.FlattenImageData, false)
t.Run("delegation disabled", func(t *testing.T) {
testutils.MustUpdateFeature(t, features.DelegateWatchedImageReprocessing, false)
enrichmentCtx := gomock.Cond(func(ctxRaw any) bool {
// Ensure that the enrichment isn't delegable.
ectx := ctxRaw.(imageEnricher.EnrichmentContext)
return !ectx.Delegable
})
ctrl := gomock.NewController(t)
enricher := mocks.NewMockImageEnricher(ctrl)
enricher.EXPECT().EnrichImage(emptyCtx, enrichmentCtx, gomock.Any())
loop := &loopImpl{imageEnricher: enricher}
loop.reprocessWatchedImage("example.com/repo/path:tag")
})
t.Run("delegation enabled", func(t *testing.T) {
testutils.MustUpdateFeature(t, features.DelegateWatchedImageReprocessing, true)
ctx := gomock.Cond(func(ctxRaw any) bool {
// Delegation will fail if context does not have image read access.
ctx := ctxRaw.(context.Context)
scopeChecker := sac.GlobalAccessScopeChecker(ctx).
AccessMode(storage.Access_READ_ACCESS).
Resource(resources.Image)
return scopeChecker.IsAllowed()
})
enrichmentCtx := gomock.Cond(func(ctxRaw any) bool {
// The enrichment must be delegable.
ectx := ctxRaw.(imageEnricher.EnrichmentContext)
return ectx.Delegable
})
ctrl := gomock.NewController(t)
enricher := mocks.NewMockImageEnricher(ctrl)
enricher.EXPECT().EnrichImage(ctx, enrichmentCtx, gomock.Any())
loop := &loopImpl{imageEnricher: enricher}
loop.reprocessWatchedImage("example.com/repo/path:tag")
})
}
func TestReprocessWatchedImageV2Delegation(t *testing.T) {
testutils.MustUpdateFeature(t, features.FlattenImageData, true)
t.Run("delegation disabled", func(t *testing.T) {
testutils.MustUpdateFeature(t, features.DelegateWatchedImageReprocessing, false)
enrichmentCtx := gomock.Cond(func(ctxRaw any) bool {
// Ensure that the enrichment isn't delegable.
ectx := ctxRaw.(imageEnricher.EnrichmentContext)
return !ectx.Delegable
})
ctrl := gomock.NewController(t)
enricher := mocks.NewMockImageEnricherV2(ctrl)
enricher.EXPECT().EnrichImage(emptyCtx, enrichmentCtx, gomock.Any())
loop := &loopImpl{imageEnricherV2: enricher}
loop.reprocessWatchedImageV2("example.com/repo/path:tag")
})
t.Run("delegation enabled", func(t *testing.T) {
testutils.MustUpdateFeature(t, features.DelegateWatchedImageReprocessing, true)
ctx := gomock.Cond(func(ctxRaw any) bool {
// Delegation will fail if context does not have image read access.
ctx := ctxRaw.(context.Context)
scopeChecker := sac.GlobalAccessScopeChecker(ctx).
AccessMode(storage.Access_READ_ACCESS).
Resource(resources.Image)
return scopeChecker.IsAllowed()
})
enrichmentCtx := gomock.Cond(func(ctxRaw any) bool {
// The enrichment must be delegable.
ectx := ctxRaw.(imageEnricher.EnrichmentContext)
return ectx.Delegable
})
ctrl := gomock.NewController(t)
enricher := mocks.NewMockImageEnricherV2(ctrl)
enricher.EXPECT().EnrichImage(ctx, enrichmentCtx, gomock.Any())
loop := &loopImpl{imageEnricherV2: enricher}
loop.reprocessWatchedImageV2("example.com/repo/path:tag")
})
}
func TestReprocessImage(t *testing.T) {
testutils.MustUpdateFeature(t, features.FlattenImageData, false)
newTestLoop := func(tt *testing.T) (*loopImpl, *mockImageDataStore.MockDataStore, *riskManagerMocks.MockManager) {
ctrl := gomock.NewController(t)
imageDS := mockImageDataStore.NewMockDataStore(ctrl)
riskManager := riskManagerMocks.NewMockManager(ctrl)
testLoop := &loopImpl{
images: imageDS,
risk: riskManager,
}
return testLoop, imageDS, riskManager
}
reprocessFuncError := func(_ context.Context, _ imageEnricher.EnrichmentContext, _ *storage.Image) (imageEnricher.EnrichmentResult, error) {
return imageEnricher.EnrichmentResult{}, errors.New("some error")
}
reprocessFuncUpdate := func(_ context.Context, _ imageEnricher.EnrichmentContext, _ *storage.Image) (imageEnricher.EnrichmentResult, error) {
return imageEnricher.EnrichmentResult{ImageUpdated: true}, nil
}
reprocessFuncNoUpdate := func(_ context.Context, _ imageEnricher.EnrichmentContext, _ *storage.Image) (imageEnricher.EnrichmentResult, error) {
return imageEnricher.EnrichmentResult{ImageUpdated: false}, nil
}
imageID := "id"
t.Run("error retrieving the image", func(tt *testing.T) {
testLoop, imageDS, _ := newTestLoop(tt)
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(nil, false, errors.New("some error"))
image, reprocessed := testLoop.reprocessImage(imageID, imageEnricher.UseCachesIfPossible, nil)
assert.Nil(tt, image)
assert.False(tt, reprocessed)
})
t.Run("image does not exist", func(tt *testing.T) {
testLoop, imageDS, _ := newTestLoop(tt)
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(nil, false, nil)
image, reprocessed := testLoop.reprocessImage(imageID, imageEnricher.UseCachesIfPossible, nil)
assert.Nil(tt, image)
assert.False(tt, reprocessed)
})
t.Run("image is not pullable", func(tt *testing.T) {
testLoop, imageDS, _ := newTestLoop(tt)
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(&storage.Image{NotPullable: true}, true, nil)
image, reprocessed := testLoop.reprocessImage(imageID, imageEnricher.UseCachesIfPossible, nil)
assert.Nil(tt, image)
assert.False(tt, reprocessed)
})
t.Run("image is cluster local", func(tt *testing.T) {
testLoop, imageDS, _ := newTestLoop(tt)
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(&storage.Image{IsClusterLocal: true}, true, nil)
image, reprocessed := testLoop.reprocessImage(imageID, imageEnricher.UseCachesIfPossible, nil)
assert.Nil(tt, image)
assert.False(tt, reprocessed)
})
t.Run("reprocessingFunc error", func(tt *testing.T) {
testLoop, imageDS, _ := newTestLoop(tt)
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(&storage.Image{}, true, nil)
image, reprocessed := testLoop.reprocessImage(imageID, imageEnricher.UseCachesIfPossible, reprocessFuncError)
assert.Nil(tt, image)
assert.False(tt, reprocessed)
})
t.Run("reprocessingFunc update calculate risk and upsert error", func(tt *testing.T) {
testLoop, imageDS, riskManager := newTestLoop(tt)
image := &storage.Image{}
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(image, true, nil)
riskManager.EXPECT().CalculateRiskAndUpsertImage(gomock.Eq(image)).Times(1).Return(errors.New("some error"))
retImage, reprocessed := testLoop.reprocessImage(imageID, imageEnricher.UseCachesIfPossible, reprocessFuncUpdate)
assert.Nil(tt, retImage)
assert.False(tt, reprocessed)
})
t.Run("re-fetch error", func(tt *testing.T) {
testLoop, imageDS, riskManager := newTestLoop(tt)
image := &storage.Image{}
gomock.InOrder(
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(image, true, nil),
riskManager.EXPECT().CalculateRiskAndUpsertImage(gomock.Eq(image)).Times(1).Return(nil),
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(nil, false, errors.New("some error")),
)
retImage, reprocessed := testLoop.reprocessImage(imageID, imageEnricher.UseCachesIfPossible, reprocessFuncUpdate)
assert.Nil(tt, retImage)
assert.False(tt, reprocessed)
})
t.Run("re-fetch not found", func(tt *testing.T) {
testLoop, imageDS, riskManager := newTestLoop(tt)
image := &storage.Image{}
gomock.InOrder(
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(image, true, nil),
riskManager.EXPECT().CalculateRiskAndUpsertImage(gomock.Eq(image)).Times(1).Return(nil),
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(nil, false, nil),
)
retImage, reprocessed := testLoop.reprocessImage(imageID, imageEnricher.UseCachesIfPossible, reprocessFuncUpdate)
assert.Nil(tt, retImage)
assert.False(tt, reprocessed)
})
t.Run("re-fetch image", func(tt *testing.T) {
testLoop, imageDS, riskManager := newTestLoop(tt)
initialImage := &storage.Image{}
secondImage := &storage.Image{Scan: &storage.ImageScan{}}
gomock.InOrder(
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(initialImage, true, nil),
riskManager.EXPECT().CalculateRiskAndUpsertImage(gomock.Eq(initialImage)).Times(1).Return(nil),
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(secondImage, true, nil),
)
retImage, reprocessed := testLoop.reprocessImage(imageID, imageEnricher.UseCachesIfPossible, reprocessFuncUpdate)
assert.NotNil(tt, retImage)
assert.False(tt, proto.Equal(initialImage, retImage))
assert.True(tt, proto.Equal(secondImage, retImage))
assert.True(tt, reprocessed)
})
t.Run("reprocessingFunc no scan update", func(tt *testing.T) {
testLoop, imageDS, _ := newTestLoop(tt)
image := &storage.Image{}
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(image, true, nil)
retImage, reprocessed := testLoop.reprocessImage(imageID, imageEnricher.UseCachesIfPossible, reprocessFuncNoUpdate)
assert.NotNil(tt, retImage)
assert.True(tt, proto.Equal(image, retImage))
assert.True(tt, reprocessed)
})
}
func TestReprocessImageV2(t *testing.T) {
testutils.MustUpdateFeature(t, features.FlattenImageData, true)
newTestLoop := func(tt *testing.T) (*loopImpl, *mockImageV2DataStore.MockDataStore, *mockImageDataStore.MockDataStore, *riskManagerMocks.MockManager) {
ctrl := gomock.NewController(t)
imageDS := mockImageV2DataStore.NewMockDataStore(ctrl)
legacyImageDS := mockImageDataStore.NewMockDataStore(ctrl)
riskManager := riskManagerMocks.NewMockManager(ctrl)
testLoop := &loopImpl{
imagesV2: imageDS,
images: legacyImageDS,
risk: riskManager,
}
return testLoop, imageDS, legacyImageDS, riskManager
}
reprocessFuncError := func(_ context.Context, _ imageEnricher.EnrichmentContext, _ *storage.ImageV2) (imageEnricher.EnrichmentResult, error) {
return imageEnricher.EnrichmentResult{}, errors.New("some error")
}
reprocessFuncUpdate := func(_ context.Context, _ imageEnricher.EnrichmentContext, _ *storage.ImageV2) (imageEnricher.EnrichmentResult, error) {
return imageEnricher.EnrichmentResult{ImageUpdated: true}, nil
}
reprocessFuncNoUpdate := func(_ context.Context, _ imageEnricher.EnrichmentContext, _ *storage.ImageV2) (imageEnricher.EnrichmentResult, error) {
return imageEnricher.EnrichmentResult{ImageUpdated: false}, nil
}
imageID := "id"
imageDigest := "sha256:test"
t.Run("error retrieving the image", func(tt *testing.T) {
testLoop, imageDS, _, _ := newTestLoop(tt)
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(nil, false, errors.New("some error"))
image, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, nil)
assert.Nil(tt, image)
assert.False(tt, reprocessed)
})
t.Run("image does not exist in V2 or legacy store", func(tt *testing.T) {
testLoop, imageDS, legacyImageDS, _ := newTestLoop(tt)
gomock.InOrder(
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(nil, false, nil),
legacyImageDS.EXPECT().GetImageMetadata(gomock.Any(), gomock.Eq(imageDigest)).Times(1).Return(nil, false, nil),
)
image, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, nil)
assert.Nil(tt, image)
assert.False(tt, reprocessed)
})
t.Run("image does not exist in V2 and error fetching from legacy store", func(tt *testing.T) {
testLoop, imageDS, legacyImageDS, _ := newTestLoop(tt)
gomock.InOrder(
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(nil, false, nil),
legacyImageDS.EXPECT().GetImageMetadata(gomock.Any(), gomock.Eq(imageDigest)).Times(1).Return(nil, false, errors.New("some error")),
)
image, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, nil)
assert.Nil(tt, image)
assert.False(tt, reprocessed)
})
t.Run("image is not pullable", func(tt *testing.T) {
testLoop, imageDS, _, _ := newTestLoop(tt)
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(&storage.ImageV2{NotPullable: true}, true, nil)
image, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, nil)
assert.Nil(tt, image)
assert.False(tt, reprocessed)
})
t.Run("image is cluster local", func(tt *testing.T) {
testLoop, imageDS, _, _ := newTestLoop(tt)
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(&storage.ImageV2{IsClusterLocal: true}, true, nil)
image, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, nil)
assert.Nil(tt, image)
assert.False(tt, reprocessed)
})
t.Run("legacy image not pullable triggers migration", func(tt *testing.T) {
testLoop, imageDS, legacyImageDS, _ := newTestLoop(tt)
legacyImage := &storage.Image{Id: imageDigest, NotPullable: true}
gomock.InOrder(
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(nil, false, nil),
legacyImageDS.EXPECT().GetImageMetadata(gomock.Any(), gomock.Eq(imageDigest)).Times(1).Return(legacyImage, true, nil),
imageDS.EXPECT().UpsertImage(gomock.Any(), gomock.Any()).Times(1).Return(nil),
)
image, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, nil)
assert.Nil(tt, image)
assert.False(tt, reprocessed)
})
t.Run("legacy image cluster local triggers migration", func(tt *testing.T) {
testLoop, imageDS, legacyImageDS, _ := newTestLoop(tt)
legacyImage := &storage.Image{Id: imageDigest, IsClusterLocal: true}
gomock.InOrder(
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(nil, false, nil),
legacyImageDS.EXPECT().GetImageMetadata(gomock.Any(), gomock.Eq(imageDigest)).Times(1).Return(legacyImage, true, nil),
imageDS.EXPECT().UpsertImage(gomock.Any(), gomock.Any()).Times(1).Return(nil),
)
image, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, nil)
assert.Nil(tt, image)
assert.False(tt, reprocessed)
})
t.Run("legacy image migration upsert error", func(tt *testing.T) {
testLoop, imageDS, legacyImageDS, _ := newTestLoop(tt)
legacyImage := &storage.Image{Id: imageDigest, NotPullable: true}
gomock.InOrder(
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(nil, false, nil),
legacyImageDS.EXPECT().GetImageMetadata(gomock.Any(), gomock.Eq(imageDigest)).Times(1).Return(legacyImage, true, nil),
imageDS.EXPECT().UpsertImage(gomock.Any(), gomock.Any()).Times(1).Return(errors.New("upsert error")),
)
image, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, nil)
assert.Nil(tt, image)
assert.False(tt, reprocessed)
})
t.Run("reprocessingFunc error", func(tt *testing.T) {
testLoop, imageDS, _, _ := newTestLoop(tt)
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(&storage.ImageV2{}, true, nil)
image, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, reprocessFuncError)
assert.Nil(tt, image)
assert.False(tt, reprocessed)
})
t.Run("reprocessingFunc update calculate risk and upsert error", func(tt *testing.T) {
testLoop, imageDS, _, riskManager := newTestLoop(tt)
image := &storage.ImageV2{}
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(image, true, nil)
riskManager.EXPECT().CalculateRiskAndUpsertImageV2(gomock.Eq(image)).Times(1).Return(errors.New("some error"))
retImage, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, reprocessFuncUpdate)
assert.Nil(tt, retImage)
assert.False(tt, reprocessed)
})
t.Run("re-fetch error", func(tt *testing.T) {
testLoop, imageDS, _, riskManager := newTestLoop(tt)
image := &storage.ImageV2{}
gomock.InOrder(
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(image, true, nil),
riskManager.EXPECT().CalculateRiskAndUpsertImageV2(gomock.Eq(image)).Times(1).Return(nil),
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(nil, false, errors.New("some error")),
)
retImage, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, reprocessFuncUpdate)
assert.Nil(tt, retImage)
assert.False(tt, reprocessed)
})
t.Run("re-fetch not found", func(tt *testing.T) {
testLoop, imageDS, _, riskManager := newTestLoop(tt)
image := &storage.ImageV2{}
gomock.InOrder(
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(image, true, nil),
riskManager.EXPECT().CalculateRiskAndUpsertImageV2(gomock.Eq(image)).Times(1).Return(nil),
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(nil, false, nil),
)
retImage, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, reprocessFuncUpdate)
assert.Nil(tt, retImage)
assert.False(tt, reprocessed)
})
t.Run("re-fetch image", func(tt *testing.T) {
testLoop, imageDS, _, riskManager := newTestLoop(tt)
initialImage := &storage.ImageV2{}
secondImage := &storage.ImageV2{Scan: &storage.ImageScan{}}
gomock.InOrder(
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(initialImage, true, nil),
riskManager.EXPECT().CalculateRiskAndUpsertImageV2(gomock.Eq(initialImage)).Times(1).Return(nil),
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(secondImage, true, nil),
)
retImage, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, reprocessFuncUpdate)
assert.NotNil(tt, retImage)
assert.False(tt, proto.Equal(initialImage, retImage))
assert.True(tt, proto.Equal(secondImage, retImage))
assert.True(tt, reprocessed)
})
t.Run("reprocessingFunc no scan update", func(tt *testing.T) {
testLoop, imageDS, _, _ := newTestLoop(tt)
image := &storage.ImageV2{}
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(image, true, nil)
retImage, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, reprocessFuncNoUpdate)
assert.NotNil(tt, retImage)
assert.True(tt, proto.Equal(image, retImage))
assert.True(tt, reprocessed)
})
t.Run("legacy image found and successfully reprocessed", func(tt *testing.T) {
testLoop, imageDS, legacyImageDS, riskManager := newTestLoop(tt)
legacyImage := &storage.Image{Id: imageDigest}
secondImage := &storage.ImageV2{Id: imageID, Scan: &storage.ImageScan{}}
gomock.InOrder(
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(nil, false, nil),
legacyImageDS.EXPECT().GetImageMetadata(gomock.Any(), gomock.Eq(imageDigest)).Times(1).Return(legacyImage, true, nil),
riskManager.EXPECT().CalculateRiskAndUpsertImageV2(gomock.Any()).Times(1).Return(nil),
imageDS.EXPECT().GetImage(gomock.Any(), gomock.Eq(imageID)).Times(1).Return(secondImage, true, nil),
)
retImage, reprocessed := testLoop.reprocessImageV2(imageID, imageDigest, imageEnricher.UseCachesIfPossible, reprocessFuncUpdate)
assert.NotNil(tt, retImage)
assert.True(tt, proto.Equal(secondImage, retImage))
assert.True(tt, reprocessed)
})
}
func TestReprocessImagesAndResyncDeployments_SkipBrokenSensor(t *testing.T) {
testutils.MustUpdateFeature(t, features.FlattenImageData, false)
imgs := []*storage.Image{}
for _, cluster := range []string{"a", "b"} { // two clusters
// Create at least one more image than max semaphore size to ensure skip logic is executed.
for i := range imageReprocessorSemaphoreSize + 1 {
imgs = append(imgs, &storage.Image{Id: fmt.Sprintf("img%d-%s", i, cluster)})
}
}
results := []search.Result{}
for _, img := range imgs {
results = append(results, search.Result{
ID: img.GetId(),
Matches: map[string][]string{
// Last character of image ID is the cluster.
imageClusterIDFieldPath: {img.GetId()[len(img.GetId())-1:]},
}},
)
}
newReprocessorLoop := func(t *testing.T) (*loopImpl, *connectionMocks.MockSensorConnection, *connectionMocks.MockSensorConnection) {
ctrl := gomock.NewController(t)
connA := connectionMocks.NewMockSensorConnection(ctrl)
connB := connectionMocks.NewMockSensorConnection(ctrl)
connManager := connectionMocks.NewMockManager(ctrl)
imageDS := mockImageDataStore.NewMockDataStore(ctrl)
riskManager := riskManagerMocks.NewMockManager(ctrl)
connA.EXPECT().ClusterID().AnyTimes().Return("a")
connB.EXPECT().ClusterID().AnyTimes().Return("b")
connManager.EXPECT().GetConnection("a").AnyTimes().Return(connA)
connManager.EXPECT().GetConnection("b").AnyTimes().Return(connB)
connManager.EXPECT().GetActiveConnections().Return([]connection.SensorConnection{connA, connB})
imageDS.EXPECT().Search(gomock.Any(), gomock.Any()).AnyTimes().Return(results, nil)
for _, img := range imgs {
imageDS.EXPECT().GetImage(gomock.Any(), img.GetId()).AnyTimes().Return(img, true, nil)
}
riskManager.EXPECT().CalculateRiskAndUpsertImage(gomock.Any()).AnyTimes().Return(nil)
testLoop := &loopImpl{
images: imageDS,
risk: riskManager,
connManager: connManager,
stopSig: concurrency.NewSignal(),
}
return testLoop, connA, connB
}
reprocessFuncUpdate := func(_ context.Context, _ imageEnricher.EnrichmentContext, _ *storage.Image) (imageEnricher.EnrichmentResult, error) {
return imageEnricher.EnrichmentResult{ImageUpdated: true}, nil
}
updatedImageTypeCond := gomock.Cond(func(msg *central.MsgToSensor) bool {
return event.GetEventTypeWithoutPrefix(msg.GetMsg()) == "UpdatedImage"
})
reprocessDeploymentsTypeCond := gomock.Cond(func(msg *central.MsgToSensor) bool {
return event.GetEventTypeWithoutPrefix(msg.GetMsg()) == "ReprocessDeployments"
})
t.Run("send all messages when clusters are healthy", func(t *testing.T) {
testLoop, connA, connB := newReprocessorLoop(t)
// Expect every updated image to be sent.
connA.EXPECT().InjectMessage(gomock.Any(), updatedImageTypeCond).Times(len(imgs) / 2).Return(nil)
connB.EXPECT().InjectMessage(gomock.Any(), updatedImageTypeCond).Times(len(imgs) / 2).Return(nil)
// Expect each cluster to be sent a reprocess deployments message.
connA.EXPECT().InjectMessage(gomock.Any(), reprocessDeploymentsTypeCond).Times(1).Return(nil)
connB.EXPECT().InjectMessage(gomock.Any(), reprocessDeploymentsTypeCond).Times(1).Return(nil)
testLoop.reprocessImagesAndResyncDeployments(0, reprocessFuncUpdate, nil)
})
t.Run("skip some messages when are broken clusters", func(t *testing.T) {
testLoop, connA, connB := newReprocessorLoop(t)
// Cluster "a" is healthy, expect all applicable images to be sent.
connA.EXPECT().InjectMessage(gomock.Any(), updatedImageTypeCond).Times(len(imgs) / 2).Return(nil)
// Cluster "b" is not healthy, expect at MOST imageReprocessorSemaphoreSize attempted messages.
connB.EXPECT().InjectMessage(gomock.Any(), updatedImageTypeCond).MaxTimes(int(imageReprocessorSemaphoreSize)).Return(errors.New("broken"))
connA.EXPECT().InjectMessage(gomock.Any(), reprocessDeploymentsTypeCond).Times(1).Return(nil)
// No reprocess deployments message is sent due to previous failures.
connB.EXPECT().InjectMessage(gomock.Any(), reprocessDeploymentsTypeCond).Times(0).Return(nil)
testLoop.reprocessImagesAndResyncDeployments(0, reprocessFuncUpdate, nil)
})
}
func TestReprocessImagesV2AndResyncDeployments_SkipBrokenSensor(t *testing.T) {
testutils.MustUpdateFeature(t, features.FlattenImageData, true)
imgs := []*storage.ImageV2{}
for _, cluster := range []string{"a", "b"} { // two clusters
// Create at least one more image than max semaphore size to ensure skip logic is executed.
for i := range imageReprocessorSemaphoreSize + 1 {
imgs = append(imgs, &storage.ImageV2{Id: fmt.Sprintf("img%d-%s", i, cluster)})
}
}
containerImageViews := []*views.ContainerImageView{}
for _, img := range imgs {
containerImageViews = append(containerImageViews, &views.ContainerImageView{
ImageIDV2: img.GetId(),
// Last character of image ID is the cluster.
ClusterIDs: []string{img.GetId()[len(img.GetId())-1:]},
})
}
newReprocessorLoop := func(t *testing.T) (*loopImpl, *connectionMocks.MockSensorConnection, *connectionMocks.MockSensorConnection) {
ctrl := gomock.NewController(t)
connA := connectionMocks.NewMockSensorConnection(ctrl)
connB := connectionMocks.NewMockSensorConnection(ctrl)
connManager := connectionMocks.NewMockManager(ctrl)
deploymentDS := mockDeploymentDataStore.NewMockDataStore(ctrl)
imageDS := mockImageV2DataStore.NewMockDataStore(ctrl)
riskManager := riskManagerMocks.NewMockManager(ctrl)
connA.EXPECT().ClusterID().AnyTimes().Return("a")
connB.EXPECT().ClusterID().AnyTimes().Return("b")
connManager.EXPECT().GetConnection("a").AnyTimes().Return(connA)
connManager.EXPECT().GetConnection("b").AnyTimes().Return(connB)
connManager.EXPECT().GetActiveConnections().Return([]connection.SensorConnection{connA, connB})
connManager.EXPECT().AllSensorsHaveCapability(gomock.Any()).AnyTimes().Return(false)
deploymentDS.EXPECT().GetContainerImageViews(gomock.Any(), gomock.Any()).AnyTimes().Return(containerImageViews, nil)
for _, img := range imgs {
imageDS.EXPECT().GetImage(gomock.Any(), img.GetId()).AnyTimes().Return(img, true, nil)
imageDS.EXPECT().GetImageNames(gomock.Any(), img.GetDigest()).
AnyTimes().
Return([]*storage.ImageName{img.GetName()}, nil)
}
riskManager.EXPECT().CalculateRiskAndUpsertImageV2(gomock.Any()).AnyTimes().Return(nil)
testLoop := &loopImpl{
deployments: deploymentDS,
imagesV2: imageDS,
risk: riskManager,
connManager: connManager,
stopSig: concurrency.NewSignal(),
}
return testLoop, connA, connB
}
reprocessFuncUpdate := func(_ context.Context, _ imageEnricher.EnrichmentContext, _ *storage.ImageV2) (imageEnricher.EnrichmentResult, error) {
return imageEnricher.EnrichmentResult{ImageUpdated: true}, nil
}
updatedImageTypeCond := gomock.Cond(func(msg *central.MsgToSensor) bool {
return event.GetEventTypeWithoutPrefix(msg.GetMsg()) == "UpdatedImage"
})
reprocessDeploymentsTypeCond := gomock.Cond(func(msg *central.MsgToSensor) bool {
return event.GetEventTypeWithoutPrefix(msg.GetMsg()) == "ReprocessDeployments"
})
t.Run("send all messages when clusters are healthy", func(t *testing.T) {
testLoop, connA, connB := newReprocessorLoop(t)
// Expect every updated image to be sent.
connA.EXPECT().InjectMessage(gomock.Any(), updatedImageTypeCond).Times(len(imgs) / 2).Return(nil)
connB.EXPECT().InjectMessage(gomock.Any(), updatedImageTypeCond).Times(len(imgs) / 2).Return(nil)
// Expect each cluster to be sent a reprocess deployments message.
connA.EXPECT().InjectMessage(gomock.Any(), reprocessDeploymentsTypeCond).Times(1).Return(nil)
connB.EXPECT().InjectMessage(gomock.Any(), reprocessDeploymentsTypeCond).Times(1).Return(nil)
testLoop.reprocessImagesV2AndResyncDeployments(0, reprocessFuncUpdate, search.EmptyQuery())
})
t.Run("skip some messages when are broken clusters", func(t *testing.T) {
testLoop, connA, connB := newReprocessorLoop(t)
// Cluster "a" is healthy, expect all applicable images to be sent.
connA.EXPECT().InjectMessage(gomock.Any(), updatedImageTypeCond).Times(len(imgs) / 2).Return(nil)
// Cluster "b" is not healthy, expect at MOST imageReprocessorSemaphoreSize attempted messages.
connB.EXPECT().InjectMessage(gomock.Any(), updatedImageTypeCond).MaxTimes(int(imageReprocessorSemaphoreSize)).Return(errors.New("broken"))
connA.EXPECT().InjectMessage(gomock.Any(), reprocessDeploymentsTypeCond).Times(1).Return(nil)
// No reprocess deployments message is sent due to previous failures.
connB.EXPECT().InjectMessage(gomock.Any(), reprocessDeploymentsTypeCond).Times(0).Return(nil)
testLoop.reprocessImagesV2AndResyncDeployments(0, reprocessFuncUpdate, search.EmptyQuery())
})
}
func TestInjectMessage(t *testing.T) {
ctx := context.Background()
msg := ¢ral.MsgToSensor{
Msg: ¢ral.MsgToSensor_ReprocessDeployments{
ReprocessDeployments: ¢ral.ReprocessDeployments{},
},
}
contextWithTimeout := gomock.Cond(func(ctx context.Context) bool {
_, hasTimeout := ctx.Deadline()
return hasTimeout
})
contextWithoutTimeout := gomock.Cond(func(ctx context.Context) bool {
_, hasTimeout := ctx.Deadline()
return !hasTimeout
})
t.Run("use timeout when duration set", func(t *testing.T) {
testLoop := &loopImpl{
injectMessageTimeoutDur: 1 * time.Millisecond, // Can be anything non-zero
}
ctrl := gomock.NewController(t)
conn := connectionMocks.NewMockSensorConnection(ctrl)
// Validate created context has a timeout.
conn.EXPECT().InjectMessage(contextWithTimeout, gomock.Any()).Return(nil)
err := testLoop.injectMessage(ctx, conn, msg)
require.NoError(t, err)
})
t.Run("no timeout when duration zero", func(t *testing.T) {
testLoop := &loopImpl{
injectMessageTimeoutDur: 0,
}
ctrl := gomock.NewController(t)
conn := connectionMocks.NewMockSensorConnection(ctrl)
// Validate created context DOES NOT have a timeout.
conn.EXPECT().InjectMessage(contextWithoutTimeout, gomock.Any()).Return(nil)
err := testLoop.injectMessage(ctx, conn, msg)
require.NoError(t, err)
})
}