Skip to content

Commit

Permalink
Fix missing credentials for java-db from private registry (#2353)
Browse files Browse the repository at this point in the history
  • Loading branch information
tom1299 authored Jan 9, 2025
1 parent ee37bbb commit 35e0c4d
Show file tree
Hide file tree
Showing 3 changed files with 167 additions and 2 deletions.
8 changes: 8 additions & 0 deletions pkg/plugins/trivy/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,14 @@ func (c Config) GetSkipJavaDBUpdate() bool {
return boolVal
}

func (c Config) GetJavaDBRepository() string {
val, ok := c.Data[keyTrivyJavaDBRepository]
if !ok {
return ""
}
return val
}

func (c Config) TrivyDBRepositoryCredentialsSet() bool {
_, userOk := c.SecretData[keyTrivyDBRepositoryUsername]
_, passOk := c.SecretData[keyTrivyDBRepositoryPassword]
Expand Down
31 changes: 29 additions & 2 deletions pkg/plugins/trivy/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,10 @@ func GetPodSpecForStandaloneMode(ctx trivyoperator.PluginContext,
volumes = append(volumes, *volume)
volumeMounts = append(volumeMounts, *volumeMount)
}
initContainer := corev1.Container{

initContainers := []corev1.Container{}

initContainers = append(initContainers, corev1.Container{
Name: p.idGenerator.GenerateID(),
Image: trivyImageRef,
ImagePullPolicy: corev1.PullPolicy(config.GetImagePullPolicy()),
Expand All @@ -140,6 +143,30 @@ func GetPodSpecForStandaloneMode(ctx trivyoperator.PluginContext,
Resources: requirements,
SecurityContext: securityContext,
VolumeMounts: volumeMounts,
})

if !config.GetSkipJavaDBUpdate() && config.TrivyDBRepositoryCredentialsSet() {
initContainers = append(initContainers, corev1.Container{
Name: p.idGenerator.GenerateID(),
Image: trivyImageRef,
ImagePullPolicy: corev1.PullPolicy(config.GetImagePullPolicy()),
TerminationMessagePolicy: corev1.TerminationMessageFallbackToLogsOnError,
Env: initContainerEnvVar(trivyConfigName, config),
Command: []string{
"trivy",
},
Args: []string{
"--cache-dir",
cacheDir,
"image",
"--download-java-db-only",
"--java-db-repository",
config.GetJavaDBRepository(),
},
Resources: requirements,
SecurityContext: securityContext,
VolumeMounts: volumeMounts,
})
}

var containers []corev1.Container
Expand Down Expand Up @@ -293,7 +320,7 @@ func GetPodSpecForStandaloneMode(ctx trivyoperator.PluginContext,
ServiceAccountName: ctx.GetServiceAccountName(),
AutomountServiceAccountToken: ptr.To[bool](getAutomountServiceAccountToken(ctx)),
Volumes: volumes,
InitContainers: []corev1.Container{initContainer},
InitContainers: initContainers,
Containers: containers,
SecurityContext: &corev1.PodSecurityContext{},
}, secrets, nil
Expand Down
130 changes: 130 additions & 0 deletions pkg/plugins/trivy/plugin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7039,6 +7039,136 @@ func TestGetContainers(t *testing.T) {
}
}

func TestGetInitContainers(t *testing.T) {
workloadSpec := &appsv1.ReplicaSet{
Spec: appsv1.ReplicaSetSpec{
Template: corev1.PodTemplateSpec{

Spec: corev1.PodSpec{
Containers: []corev1.Container{
{Name: "container1", Image: "busybox:1.34.1"},
},
},
},
},
}

testCases := []struct {
name string
configData map[string]string
}{
{
name: "Standalone mode with image command java-db from private registry",
configData: map[string]string{
"trivy.dbRepository": trivy.DefaultDBRepository,
"trivy.javaDbRepository": "my-private-registry.io/aquasec/trivy-java-db",
"trivy.skipJavaDBUpdate": "false",
"trivy.repository": "gcr.io/aquasec/trivy",
"trivy.tag": "0.35.0",
"trivy.mode": string(trivy.Standalone),
"trivy.command": string(trivy.Image),
},
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
fakeclient := fake.NewClientBuilder().WithObjects(
&corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "trivy-operator-trivy-config",
Namespace: "trivyoperator-ns",
},
Data: tc.configData,
},
&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "trivy-operator-trivy-config",
Namespace: "trivyoperator-ns",
},
Data: map[string][]byte{
"trivy.dbRepositoryUsername": []byte("my-username"),
"trivy.dbRepositoryPassword": []byte("my-password"),
},
},
).Build()

pluginContext := trivyoperator.NewPluginContext().
WithName(trivy.Plugin).
WithNamespace("trivyoperator-ns").
WithServiceAccountName("trivyoperator-sa").
WithClient(fakeclient).
Get()

config, err := pluginContext.GetConfig()
if err != nil {
t.Fatalf("failed to get config: %v", err)
}
config.SecretData = map[string][]byte{
"my-username": []byte("my-username"),
"my-password": []byte("my-password"),
}

resolver := kube.NewObjectResolver(fakeclient, &kube.CompatibleObjectMapper{})
instance := trivy.NewPlugin(fixedClock, ext.NewSimpleIDGenerator(), &resolver)
jobSpec, _, err := instance.GetScanJobSpec(pluginContext, workloadSpec, nil, nil, map[string]v1alpha1.SbomReportData{})
assert.NoError(t, err)

assert.Len(t, jobSpec.InitContainers, 2)
// Assert first init container to download trivy-db from private registry
trivyDbInitContainer := jobSpec.InitContainers[0]

containsDownloadDBOnly := false
for _, arg := range trivyDbInitContainer.Args {
if arg == "--download-db-only" {
containsDownloadDBOnly = true
break
}
}
assert.True(t, containsDownloadDBOnly, "Expected first init container to only download try-db")

hasTrivyUsername := false
hasTrivyPassword := false
for _, envVar := range trivyDbInitContainer.Env {
if envVar.Name == "TRIVY_USERNAME" {
hasTrivyUsername = true
}
if envVar.Name == "TRIVY_PASSWORD" {
hasTrivyPassword = true
}
}
assert.True(t, hasTrivyUsername, "Expected init container to have username env var for private trivy-db registry")
assert.True(t, hasTrivyPassword, "Expected init container to have password env var for private trivy-db registry")

// Assert second init container to download java-db from private registry
javaDbInitContainer := jobSpec.InitContainers[1]

containsDownloadJavaDBOnly := false
for _, arg := range javaDbInitContainer.Args {
if arg == "--download-java-db-only" {
containsDownloadJavaDBOnly = true
break
}
}
assert.True(t, containsDownloadJavaDBOnly, "Expected second init container to only download java-db")

hasTrivyUsername = false
hasTrivyPassword = false
for _, envVar := range javaDbInitContainer.Env {
if envVar.Name == "TRIVY_USERNAME" {
hasTrivyUsername = true
}
if envVar.Name == "TRIVY_PASSWORD" {
hasTrivyPassword = true
}
}
assert.True(t, hasTrivyUsername, "Expected init container to have username env var for private java-db registry")
assert.True(t, hasTrivyPassword, "Expected init container to have password env var for private java-db registry")

})
}
}

func getReportAsString(fixture string) string {
f, err := os.Open("./testdata/fixture/" + fixture)
if err != nil {
Expand Down

0 comments on commit 35e0c4d

Please sign in to comment.