File: scanner_test.go

package info (click to toggle)
gitlab-agent 16.1.3-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 6,324 kB
  • sloc: makefile: 175; sh: 52; ruby: 3
file content (687 lines) | stat: -rw-r--r-- 21,367 bytes parent folder | download
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
package agent

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"sync"
	"testing"
	"time"

	"github.com/golang/mock/gomock"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/modagent"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/testing/mock_modagent"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/pkg/agentcfg"
	"go.uber.org/zap/zaptest"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/kubernetes/fake"
	clienttesting "k8s.io/client-go/testing"
)

const (
	namespace1                = "namespace1"
	namespace2                = "namespace2"
	gitlabAgentNamespace      = "gitlab-agent"
	gitlabAgentServiceAccount = "gitlab-agent"
	podName                   = "Pod name"
)

func TestScan(t *testing.T) {
	ctrl := gomock.NewController(t)
	ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
	defer cancel()

	kubeClientset := fake.NewSimpleClientset()
	logParser := &CustomLogParser{}
	api := mock_modagent.NewMockApi(ctrl)
	s := scanJob{
		log:                       zaptest.NewLogger(t),
		api:                       api,
		kubeClientset:             kubeClientset,
		gitlabAgentNamespace:      gitlabAgentNamespace,
		gitlabAgentServiceAccount: gitlabAgentServiceAccount,
		agentID:                   5000000000,
		targetNamespaces:          []string{namespace1, namespace2},
		logParser:                 logParser,
		resourceRequirements:      &defaultResourceRequirements,
	}

	// Each namespace scan will return 1 vulnerability based on the response from ParsePodLogsToReport. As there are 2 namespaces this will result in 2 vulnerabilities to be transmitted to Gitlab.
	api.EXPECT().MakeGitLabRequest(gomock.Any(), "/",
		gomock.Any(),
		gomock.Any(),
	).Times(2).
		DoAndReturn(mockVulnerabilityCreate)

	api.EXPECT().MakeGitLabRequest(gomock.Any(), "/scan_result",
		gomock.Any(),
		gomock.Any(),
	).Times(1).
		DoAndReturn(func(ctx context.Context, path string, opts ...modagent.GitLabRequestOption) (*modagent.GitLabResponse, error) {
			uuids, err := getUuidsFromOptions(opts)
			require.NoError(t, err)

			// There are 2 vulnerabilities detected in total.
			// As we want to send single request for all workloads,
			// we need to check if this single request contains all returned vulnerabilities.
			expectedVulnerabiltiyIds := []string{
				"2b19bdf999f6fdd149344caf0b0ff2c9fb96fa2c7eb1eb25907b48c32980397a",
				"2b19bdf999f6fdd149344caf0b0ff2c9fb96fa2c7eb1eb25907b48c32980397a",
			}

			assert.ElementsMatch(t, expectedVulnerabiltiyIds, uuids)

			return &modagent.GitLabResponse{
				StatusCode: 200,
			}, nil
		})

	// s.Run starts a Watcher for each Trivy Pod that it creates and waits for the Pod status to change to Succeeded before processing it's logs.
	// As the Watcher is created within the scanJob.startPodScanForNamespace, I opted to use a fake watch interface to stub the Pod status change events.
	wg := startCustomWatcher(t, ctx, kubeClientset, 2, corev1.PodSucceeded)

	s.Run(ctx)
	podList, err := kubeClientset.CoreV1().Pods(gitlabAgentNamespace).List(ctx, metav1.ListOptions{})
	assert.NoError(t, err)
	// Trivy Pods should be deleted after the scan is complete
	assert.Equal(t, 0, len(podList.Items))

	wg.Wait()
}

func TestScanPodFailed(t *testing.T) {
	ctrl := gomock.NewController(t)
	ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
	defer cancel()

	kubeClientset := fake.NewSimpleClientset()

	logParser := &CustomLogParser{}
	api := mock_modagent.NewMockApi(ctrl)
	s := scanJob{
		log:                       zaptest.NewLogger(t),
		api:                       api,
		kubeClientset:             kubeClientset,
		gitlabAgentNamespace:      gitlabAgentNamespace,
		gitlabAgentServiceAccount: gitlabAgentServiceAccount,
		agentID:                   5000000000,
		targetNamespaces:          []string{namespace1},
		logParser:                 logParser,
		resourceRequirements:      &defaultResourceRequirements,
	}

	api.EXPECT().MakeGitLabRequest(gomock.Any(), "/",
		gomock.Any(),
		gomock.Any(),
	).Times(0)

	api.EXPECT().MakeGitLabRequest(gomock.Any(), "/scan_result",
		gomock.Any(),
		gomock.Any(),
	).Times(0)

	wg := startCustomWatcher(t, ctx, kubeClientset, 1, corev1.PodFailed)

	s.Run(ctx)
	podList, err := kubeClientset.CoreV1().Pods(gitlabAgentNamespace).List(ctx, metav1.ListOptions{})
	assert.NoError(t, err)
	// Failed Trivy Pods should be deleted
	assert.Equal(t, 0, len(podList.Items))

	wg.Wait()
}

func TestScanEmptyNamespace(t *testing.T) {
	ctrl := gomock.NewController(t)
	ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
	defer cancel()

	kubeClientset := fake.NewSimpleClientset()
	// Ensure that no Trivy Pods are created when there are no namespaces to be scanned
	kubeClientset.PrependReactor("create", "*", func(action clienttesting.Action) (bool, runtime.Object, error) {
		t.Errorf("Create should not be called")
		return true, nil, nil
	})

	logParser := &CustomLogParser{}
	api := mock_modagent.NewMockApi(ctrl)
	s := scanJob{
		log:                       zaptest.NewLogger(t),
		api:                       api,
		kubeClientset:             kubeClientset,
		gitlabAgentNamespace:      gitlabAgentNamespace,
		gitlabAgentServiceAccount: gitlabAgentServiceAccount,
		agentID:                   5000000000,
		targetNamespaces:          []string{}, //No namespace targetted
		logParser:                 logParser,
		resourceRequirements:      &defaultResourceRequirements,
	}

	api.EXPECT().MakeGitLabRequest(gomock.Any(), "/",
		gomock.Any(),
		gomock.Any(),
	).Times(0)

	api.EXPECT().MakeGitLabRequest(gomock.Any(), "/scan_result",
		gomock.Any(),
		gomock.Any(),
	).Times(0)

	wg := startCustomWatcher(t, ctx, kubeClientset, 1, corev1.PodSucceeded)

	s.Run(ctx)

	wg.Wait()
}

// Actual logs taken from output of Trivy k8s
var podLogsWithReport = []byte(`{
	"ClusterName": "",
	"Findings": [
	  {
	  "Namespace": "default",
	  "Kind": "Pod",
	  "Name": "nginx-unaccessible-6dfd584649-twqzw",
	  "Error": "scan error: unable to initialize a scanner: unable to initialize a docker scanner: 4 errors occurred:\\n\\t* unable to inspect the image (localhost:1234/nginx:latest): Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?\\n\\t* unable to initialize Podman client: no podman socket found: stat podman/podman.sock: no such file or directory\\n\\t* containerd socket not found: /run/containerd/containerd.sock\\n\\t* Get \"https://localhost:1234/v2/\": dial tcp [::1]:1234: connect: connection refused; Get \"http://localhost:1234/v2/\": dial tcp [::1]:1234: connect: connection refused\\n\\n"
	  }
	]
	}`)

// Actual logs with error taken from output of Trivy k8s
var podLogsWithErrorAndReport = []byte(fmt.Sprintf(`text2 2023-04-18T06:51:05.356Z	ERROR	Error during vulnerabilities scan: scan error: unable to initialize a scanner: unable to initialize a docker scanner: 4 errors occurred:
	  * unable to inspect the image (localhost:1234/nginx:latest): Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
	  * unable to initialize Podman client: no podman socket found: stat podman/podman.sock: no such file or directory
	  * containerd socket not found: /run/containerd/containerd.sock
	  * Get "https://localhost:1234/v2/": dial tcp [::1]:1234: connect: connection refused; Get "http://localhost:1234/v2/": dial tcp [::1]:1234: connect: connection refused


  %s`, string(podLogsWithReport)))

func TestParsePodLogsToReportWithNoError(t *testing.T) {
	logParser := &logParserImpl{}
	consolidatedReport, err := logParser.ParsePodLogsToReport(podLogsWithReport)
	assert.NoError(t, err)

	var referenceConsolidatedReport ConsolidatedReport
	err = json.Unmarshal(podLogsWithReport, &referenceConsolidatedReport)
	assert.NoError(t, err)

	assert.Equal(t, referenceConsolidatedReport, consolidatedReport)
}

func TestParsePodLogsToReportWithError(t *testing.T) {
	logParser := &logParserImpl{}
	consolidatedReport, err := logParser.ParsePodLogsToReport(podLogsWithErrorAndReport)
	assert.NoError(t, err)

	var referenceConsolidatedReport ConsolidatedReport
	err = json.Unmarshal(podLogsWithReport, &referenceConsolidatedReport)
	assert.NoError(t, err)

	assert.Equal(t, referenceConsolidatedReport, consolidatedReport)
}

var publishedDate = time.Date(2020, time.December, 10, 0, 0, 0, 0, time.UTC)
var lastModifiedDate = time.Date(2022, time.October, 29, 0, 0, 0, 0, time.UTC)
var sampleResult = []Result{
	{
		Target: "nginx:1.16 (debian 10.3)",
		Class:  "os-pkgs",
		Type:   "alpine",
		Vulnerabilities: []DetectedVulnerability{
			{
				VulnerabilityID:  "CVE-2020-27350",
				PkgName:          "apt",
				InstalledVersion: "1.8.2",
				FixedVersion:     "1.8.2.2",
				PrimaryURL:       "https://avd.aquasec.com/nvd/cve-2020-27350",
				Vulnerability: Vulnerability{
					Title:       "apt: integer overflows and underflows while parsing .deb packages",
					Description: "APT had several integer overflows and underflows while parsing .deb packages, aka GHSL-2020-168 GHSL-2020-169, in files apt-pkg/contrib/extracttar.cc, apt-pkg/deb/debfile.cc, and apt-pkg/contrib/arfile.cc. This issue affects: apt 1.2.32ubuntu0 versions prior to 1.2.32ubuntu0.2; 1.6.12ubuntu0 versions prior to 1.6.12ubuntu0.2; 2.0.2ubuntu0 versions prior to 2.0.2ubuntu0.2; 2.1.10ubuntu0 versions prior to 2.1.10ubuntu0.1;",
					Severity:    "MEDIUM",
					References: []string{
						"https://access.redhat.com/security/cve/CVE-2020-27350",
						"https://bugs.launchpad.net/bugs/1899193",
					},
					PublishedDate:    &publishedDate,
					LastModifiedDate: &lastModifiedDate,
				},
			},
		},
	},
}

func setOwnerFindings(ownerKind string) Resource {
	return Resource{
		Namespace: namespace1,
		Kind:      ownerKind,
		Name:      "Owner name",
		Results:   sampleResult,
	}
}

func TestExcludeControlledPodWorkloads(t *testing.T) {
	ctrl := gomock.NewController(t)
	ctx := context.Background()

	kubeClientset := fake.NewSimpleClientset()
	logParser := &CustomLogParser{}
	api := mock_modagent.NewMockApi(ctrl)
	s := scanJob{
		log:                       zaptest.NewLogger(t),
		api:                       api,
		kubeClientset:             kubeClientset,
		gitlabAgentNamespace:      gitlabAgentNamespace,
		gitlabAgentServiceAccount: gitlabAgentServiceAccount,
		agentID:                   5000000000,
		targetNamespaces:          []string{namespace1},
		logParser:                 logParser,
	}

	// Pod spec with OwnerReference to simulate a controlled Pod
	isController := true
	podSpec := &corev1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:            podName,
			Namespace:       namespace1,
			OwnerReferences: []metav1.OwnerReference{},
		},
		Spec: corev1.PodSpec{
			Containers: []corev1.Container{
				{
					Name:  "nginx-container",
					Image: "nginx:1.16",
				},
			},
		},
	}

	podFindings := Resource{
		Namespace: namespace1,
		Kind:      "Pod",
		Name:      podName,
		Results:   sampleResult,
	}

	testCases := []struct {
		hasOwner                  bool
		ownerGroupVersion         string
		ownerKind                 string
		consolidatedReport        ConsolidatedReport
		expectedQualifiedFindings []Resource
	}{
		{
			hasOwner:          true,
			ownerGroupVersion: "v1",
			ownerKind:         "ReplicationController",
			consolidatedReport: ConsolidatedReport{
				Findings: []Resource{
					setOwnerFindings("ReplicationController"),
				},
			},
			expectedQualifiedFindings: []Resource{
				setOwnerFindings("ReplicationController"),
			},
		},
		{
			hasOwner:          true,
			ownerGroupVersion: "apps/v1",
			ownerKind:         "ReplicaSet",
			consolidatedReport: ConsolidatedReport{
				Findings: []Resource{
					setOwnerFindings("ReplicaSet"),
				},
			},
			expectedQualifiedFindings: []Resource{
				setOwnerFindings("ReplicaSet"),
			},
		},
		{
			hasOwner:          true,
			ownerGroupVersion: "apps/v1",
			ownerKind:         "StatefulSet",
			consolidatedReport: ConsolidatedReport{
				Findings: []Resource{
					setOwnerFindings("StatefulSet"),
				},
			},
			expectedQualifiedFindings: []Resource{
				setOwnerFindings("StatefulSet"),
			},
		},
		{
			hasOwner:          true,
			ownerGroupVersion: "apps/v1",
			ownerKind:         "DaemonSet",
			consolidatedReport: ConsolidatedReport{
				Findings: []Resource{
					setOwnerFindings("DaemonSet"),
				},
			},
			expectedQualifiedFindings: []Resource{
				setOwnerFindings("DaemonSet"),
			},
		},
		{
			hasOwner:          true,
			ownerGroupVersion: "batch/v1",
			ownerKind:         "Job",
			consolidatedReport: ConsolidatedReport{
				Findings: []Resource{
					setOwnerFindings("Job"),
				},
			},
			expectedQualifiedFindings: []Resource{
				setOwnerFindings("Job"),
			},
		},
		{
			hasOwner:          true,
			ownerGroupVersion: "custom/v1",
			ownerKind:         "custom",
			consolidatedReport: ConsolidatedReport{
				Findings: []Resource{
					setOwnerFindings("custom"),
					podFindings,
				},
			},
			expectedQualifiedFindings: []Resource{
				setOwnerFindings("custom"),
				podFindings,
			},
		},
		{
			hasOwner:          false,
			ownerGroupVersion: "",
			ownerKind:         "",
			consolidatedReport: ConsolidatedReport{
				Findings: []Resource{
					podFindings,
				},
			},
			expectedQualifiedFindings: []Resource{
				podFindings,
			},
		},
	}

	for _, tc := range testCases {
		t.Run(tc.ownerKind, func(t *testing.T) {
			if tc.hasOwner {
				podSpec.ObjectMeta.OwnerReferences = []metav1.OwnerReference{
					{
						APIVersion: tc.ownerGroupVersion,
						Kind:       tc.ownerKind,
						Name:       "Owner name",
						Controller: &isController,
					},
				}
			}

			// Create Pod
			_, err := kubeClientset.CoreV1().Pods(namespace1).Create(ctx, podSpec, metav1.CreateOptions{})
			assert.NoError(t, err)

			qualifiedFindings := s.excludeControlledPodWorkloads(ctx, s.log, &tc.consolidatedReport, namespace1)

			assert.Equal(t, tc.expectedQualifiedFindings, qualifiedFindings)

			// Delete pod
			err = s.kubeClientset.CoreV1().Pods(namespace1).Delete(ctx, podName, metav1.DeleteOptions{})
			assert.NoError(t, err)
		})
	}
}

func getUuidsFromOptions(opts []modagent.GitLabRequestOption) ([]string, error) {
	body, err := getBodyFromOptions(opts)
	if err != nil {
		return nil, err
	}

	payload := new(reqBody)
	if err := json.Unmarshal(body, payload); err != nil {
		return nil, err
	}

	return payload.UUIDs, nil
}

func getBodyFromOptions(opts []modagent.GitLabRequestOption) ([]byte, error) {
	config, err := modagent.ApplyRequestOptions(opts)
	if err != nil {
		return nil, err
	}

	return io.ReadAll(config.Body)
}

func mockVulnerabilityCreate(ctx context.Context, path string, opts ...modagent.GitLabRequestOption) (*modagent.GitLabResponse, error) {
	body, err := getBodyFromOptions(opts)
	if err != nil {
		return nil, err
	}

	payload := new(Payload)
	if err = json.Unmarshal(body, payload); err != nil {
		return nil, err
	}

	response := &uuidResponse{
		// Technically not a UUID, but for testing
		// purposes it works as a suitible replacement.
		UUID: payload.Vulnerability.ID(),
	}

	var responseBytes []byte
	responseBytes, err = json.Marshal(response)
	if err != nil {
		return nil, err
	}

	return &modagent.GitLabResponse{
		StatusCode: http.StatusOK,
		Body:       io.NopCloser(bytes.NewReader(responseBytes)),
	}, nil
}

type CustomLogParser struct {
	err error
}

// ParsePodLogsToReport stubs the report that is parsed from a Trivy Pod's logs
func (m *CustomLogParser) ParsePodLogsToReport(logs []byte) (ConsolidatedReport, error) {
	report := ConsolidatedReport{
		Findings: []Resource{
			{
				Namespace: "some-namespace",
				Kind:      "Deployment",
				Name:      "nginx",
				Results:   sampleResult,
			},
		},
	}
	return report, m.err
}

// customWatcher is used to stub the Pod's watch interface
type customWatcher struct {
	eventChan chan watch.Event
}

func (cw *customWatcher) Stop() {}

func (cw *customWatcher) ResultChan() <-chan watch.Event {
	return cw.eventChan

}

// startCustomWatcher creates a custom watcher and waits for the specified number of Pods to be created before changing the Pod status to the desired status.
// This will ensure that the watcher in scanJob.startPodScanForNamespace does not wait forever and can continue processing.
// As we are using kubernetes fake.Clientset, Status.Phase would be "" instead of PodPending.
// Status.Phase would not change even after the Pod status has been updated since the customWatcher doesn't update the kubernetes object.
// As such, the moment the status has been updated, this function will exit.
func startCustomWatcher(t *testing.T, ctx context.Context, kubeClientset *fake.Clientset, podsToCreate int, desiredPodStatus corev1.PodPhase) *sync.WaitGroup {
	customWatcher := &customWatcher{
		eventChan: make(chan watch.Event),
	}
	kubeClientset.PrependWatchReactor("pods", func(action clienttesting.Action) (handled bool, ret watch.Interface, err error) {
		return true, customWatcher, nil
	})

	// Use WaitGroup to wait for Pod status to change before exiting the test function
	var wg sync.WaitGroup
	wg.Add(1)
	go func(wg *sync.WaitGroup) {
		defer wg.Done()

		for {
			select {
			case <-time.After(10 * time.Millisecond):
				podList, err := kubeClientset.CoreV1().Pods(gitlabAgentNamespace).List(ctx, metav1.ListOptions{})
				assert.NoError(t, err)

				// Only process if number of expected Pods have been created
				if len(podList.Items) == podsToCreate {
					for i := range podList.Items {
						createdPod := &podList.Items[i]
						updatedPod := createdPod.DeepCopy()
						updatedPod.Status.Phase = desiredPodStatus
						customWatcher.eventChan <- watch.Event{Type: watch.Modified, Object: updatedPod}
					}
					close(customWatcher.eventChan)
					return
				}
			case <-ctx.Done():
				return
			}
		}
	}(&wg)

	return &wg
}

func TestGetPodSpec(t *testing.T) {
	s := &scanJob{
		gitlabAgentNamespace:      gitlabAgentNamespace,
		gitlabAgentServiceAccount: gitlabAgentServiceAccount,
		resourceRequirements:      &defaultResourceRequirements,
	}
	workloadsToScan := "Pod,ReplicaSet,ReplicationController,StatefulSet,DaemonSet,CronJob,Job"

	expectedPodSpec := &corev1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      podName,
			Namespace: s.gitlabAgentNamespace,
		},
		Spec: corev1.PodSpec{
			ServiceAccountName: s.gitlabAgentServiceAccount,
			Containers: []corev1.Container{
				{
					Name: "trivy",
					Resources: corev1.ResourceRequirements{
						Limits: corev1.ResourceList{
							corev1.ResourceMemory: resource.MustParse(defaultTrivyResourceLimitsMemory),
							corev1.ResourceCPU:    resource.MustParse(defaultTrivyResourceLimitsCpu),
						},
						Requests: corev1.ResourceList{
							corev1.ResourceMemory: resource.MustParse(defaultTrivyResourceRequestsMemory),
							corev1.ResourceCPU:    resource.MustParse(defaultTrivyResourceRequestsCpu),
						},
					},
					Image: trivyImageRef,
					Command: []string{
						"trivy",
						"k8s",
						workloadsToScan,
						"-n",
						namespace1,
						"--no-progress",
						"--quiet",
						"--report=summary",
						"--scanners=vuln",
						"--db-repository",
						"registry.gitlab.com/gitlab-org/security-products/dependencies/trivy-db-glad",
						"--format",
						"json",
					},
				},
			},
			RestartPolicy: corev1.RestartPolicyNever,
		},
	}

	actualPodSpec, err := s.getPodSpecForTrivyScanner(podName, namespace1)
	if assert.NoError(t, err) {
		assert.Equal(t, expectedPodSpec, actualPodSpec)
	}
}

func TestGetPodSpecWithValidationError(t *testing.T) {
	testCases := []struct {
		description         string
		inputLimitsCpu      string
		inputLimitsMemory   string
		inputRequestsCpu    string
		inputRequestsMemory string
	}{
		{
			description:         "invalid limits cpu",
			inputLimitsCpu:      "a",
			inputLimitsMemory:   "",
			inputRequestsCpu:    "",
			inputRequestsMemory: "",
		},
		{
			description:         "invalid limits memory",
			inputLimitsCpu:      "",
			inputLimitsMemory:   "a",
			inputRequestsCpu:    "",
			inputRequestsMemory: "",
		},
		{
			description:         "invalid requests cpu",
			inputLimitsCpu:      "",
			inputLimitsMemory:   "",
			inputRequestsCpu:    "a",
			inputRequestsMemory: "",
		},
		{
			description:         "invalid requests memory",
			inputLimitsCpu:      "",
			inputLimitsMemory:   "",
			inputRequestsCpu:    "",
			inputRequestsMemory: "a",
		},
	}
	for _, tc := range testCases {
		t.Run(tc.description, func(t *testing.T) {
			s := &scanJob{
				gitlabAgentNamespace:      gitlabAgentNamespace,
				gitlabAgentServiceAccount: gitlabAgentServiceAccount,
				resourceRequirements: &agentcfg.ResourceRequirements{
					Limits: &agentcfg.Resource{
						Cpu:    tc.inputLimitsCpu,
						Memory: tc.inputLimitsMemory,
					},
					Requests: &agentcfg.Resource{
						Cpu:    tc.inputRequestsCpu,
						Memory: tc.inputRequestsMemory,
					},
				},
			}

			_, err := s.getPodSpecForTrivyScanner(podName, namespace1)
			assert.ErrorIs(t, err, resource.ErrFormatWrong)
		})
	}
}