Skip to content

Commit a2d738c

Browse files
authored
fix: miscellaneous fixes for ai-reported suggestions (#4101)
* test(cli): replace panic with t.Fatalf in deprecated config tests Signed-off-by: Ramkumar Chinchani <rchincha.dev@gmail.com> * fix(trivy): keep sbom generation failures non-fatal in runTrivy Signed-off-by: Ramkumar Chinchani <rchincha.dev@gmail.com> * docs(meta): fix typos in hooks comments Signed-off-by: Ramkumar Chinchani <rchincha.dev@gmail.com> * refactor(requestcontext): align package name and godoc comments Signed-off-by: Ramkumar Chinchani <rchincha.dev@gmail.com> * test(gc): factor metrics setup helper and fix typo Signed-off-by: Ramkumar Chinchani <rchincha.dev@gmail.com> * test(trivy): cover non-fatal SBOM generation failures - add runTrivy test ensuring scan succeeds when SBOM generation fails - inject artifact runner constructor for deterministic internal testing - fix matchesRepo doc comment to be action-agnostic Signed-off-by: Ramkumar Chinchani <rchincha.dev@gmail.com> --------- Signed-off-by: Ramkumar Chinchani <rchincha.dev@gmail.com>
1 parent 4e4d00a commit a2d738c

7 files changed

Lines changed: 91 additions & 35 deletions

File tree

pkg/cli/client/config_cmd_deprecated_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ func TestConfigCmdDeprecatedMain(t *testing.T) {
8282

8383
actual, err := os.ReadFile(configPath)
8484
if err != nil {
85-
panic(err)
85+
t.Fatalf("failed to read config file %s: %v", configPath, err)
8686
}
8787
actualStr := string(actual)
8888
So(actualStr, ShouldContainSubstring, "configtest1")
@@ -405,7 +405,7 @@ func TestConfigCmdDeprecatedMain(t *testing.T) {
405405

406406
actual, err := os.ReadFile(configPath)
407407
if err != nil {
408-
panic(err)
408+
t.Fatalf("failed to read config file %s: %v", configPath, err)
409409
}
410410
actualStr := string(actual)
411411
So(actualStr, ShouldContainSubstring, "https://test-url.com")
@@ -450,7 +450,7 @@ func TestConfigCmdDeprecatedMain(t *testing.T) {
450450

451451
actual, err := os.ReadFile(configPath)
452452
if err != nil {
453-
panic(err)
453+
t.Fatalf("failed to read config file %s: %v", configPath, err)
454454
}
455455
actualStr := string(actual)
456456
So(actualStr, ShouldContainSubstring, `https://new-url.com`)
@@ -477,7 +477,7 @@ func TestConfigCmdDeprecatedMain(t *testing.T) {
477477

478478
actual, err := os.ReadFile(configPath)
479479
if err != nil {
480-
panic(err)
480+
t.Fatalf("failed to read config file %s: %v", configPath, err)
481481
}
482482
actualStr := string(actual)
483483
So(actualStr, ShouldNotContainSubstring, "showspinner")

pkg/extensions/search/cve/trivy/scanner.go

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ const (
5757

5858
var errImageStoreNotFound = errors.New("image store not found")
5959

60+
var newArtifactRunner = artifact.NewRunner //nolint:gochecknoglobals // test seam for deterministic runner injection
61+
6062
// getNewScanOptions sets trivy configuration values for our scans and returns them as
6163
// a trivy Options structure.
6264
func getNewScanOptions(dir string, dbRepositoryRef, javaDBRepositoryRef name.Reference,
@@ -330,7 +332,7 @@ func (scanner Scanner) runTrivy(ctx context.Context, opts flag.Options) (types.R
330332
var sbom *generatedSBOM
331333

332334
err = scanner.withTempDir(func() error {
333-
runner, err := artifact.NewRunner(ctx, opts, artifact.TargetContainerImage)
335+
runner, err := newArtifactRunner(ctx, opts, artifact.TargetContainerImage)
334336
if err != nil {
335337
return err
336338
}
@@ -347,13 +349,14 @@ func (scanner Scanner) runTrivy(ctx context.Context, opts flag.Options) (types.R
347349
}
348350

349351
if scanner.sbomOptions.enabled {
350-
sbom, err = scanner.generateSBOM(ctx, runner, opts, report)
351-
if err != nil {
352-
scanner.log.Warn().Err(err).Str("image", opts.ImageOptions.Input).Msg("failed to generate sbom")
352+
var sbomErr error
353+
sbom, sbomErr = scanner.generateSBOM(ctx, runner, opts, report)
354+
if sbomErr != nil {
355+
scanner.log.Warn().Err(sbomErr).Str("image", opts.ImageOptions.Input).Msg("failed to generate sbom")
353356
}
354357
}
355358

356-
return err
359+
return nil
357360
})
358361

359362
return report, sbom, err

pkg/extensions/search/cve/trivy/scanner_internal_test.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,13 @@ package trivy
55
import (
66
"context"
77
"encoding/json"
8+
"errors"
89
"os"
910
"path"
1011
"testing"
1112
"time"
1213

14+
"github.com/aquasecurity/trivy-db/pkg/metadata"
1315
dbTypes "github.com/aquasecurity/trivy-db/pkg/types"
1416
"github.com/aquasecurity/trivy/pkg/commands/artifact"
1517
"github.com/aquasecurity/trivy/pkg/flag"
@@ -132,6 +134,54 @@ func TestGenerateSBOM(t *testing.T) {
132134
})
133135
}
134136

137+
func TestRunTrivySBOMGenerationFailureIsNonFatal(t *testing.T) {
138+
Convey("runTrivy should return report and nil error when SBOM generation fails", t, func() {
139+
logger := log.NewTestLogger()
140+
rootDir := t.TempDir()
141+
142+
dbDir := path.Join(rootDir, "_trivy", "db")
143+
err := os.MkdirAll(dbDir, 0o755)
144+
So(err, ShouldBeNil)
145+
err = os.WriteFile(metadata.Path(dbDir), []byte(`{"Version":2}`), 0o600)
146+
So(err, ShouldBeNil)
147+
148+
store := local.NewImageStore(rootDir, false, false, logger, monitoring.NewMetricsServer(false, logger), nil, nil, nil, nil)
149+
storeController := storage.StoreController{DefaultStore: store}
150+
151+
scanner := Scanner{
152+
log: logger,
153+
storeController: storeController,
154+
sbomOptions: sbomOptions{
155+
enabled: true,
156+
reportFormat: trivyTypes.FormatSPDXJSON,
157+
},
158+
}
159+
160+
sbomErr := errors.New("sbom generation failed")
161+
oldNewArtifactRunner := newArtifactRunner
162+
newArtifactRunner = func(ctx context.Context, opts flag.Options, target artifact.TargetKind,
163+
runnerOpts ...artifact.RunnerOption,
164+
) (artifact.Runner, error) {
165+
return fakeArtifactRunner{
166+
reportFn: func(ctx context.Context, opts flag.Options, report trivyTypes.Report) error {
167+
return sbomErr
168+
},
169+
}, nil
170+
}
171+
defer func() {
172+
newArtifactRunner = oldNewArtifactRunner
173+
}()
174+
175+
report, generated, err := scanner.runTrivy(context.Background(), flag.Options{
176+
ImageOptions: flag.ImageOptions{Input: "repo:tag"},
177+
})
178+
179+
So(err, ShouldBeNil)
180+
So(report, ShouldResemble, trivyTypes.Report{})
181+
So(generated, ShouldBeNil)
182+
})
183+
}
184+
135185
func TestMultipleStoragePath(t *testing.T) {
136186
Convey("Test multiple storage path", t, func() {
137187
// Create temporary directory

pkg/meta/hooks.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ func rollbackDigestManifestTags(ctx context.Context, repo string, tags, appliedM
143143
}
144144

145145
// OnUpdateManifest is called when a new manifest is added. It updates metadb according to the type
146-
// of image pushed(normal images, signatues, etc.). In care of any errors, it makes sure to keep
146+
// of image pushed(normal images, signatures, etc.). In case of any errors, it makes sure to keep
147147
// consistency between metadb and the image store.
148148
func OnUpdateManifest(ctx context.Context, repo, reference, mediaType string, digest godigest.Digest, body []byte,
149149
storeController storage.StoreController, metaDB mTypes.MetaDB, log log.Logger,
@@ -213,7 +213,7 @@ func OnUpdateManifestDigestTags(ctx context.Context, repo string, tags []string,
213213
}
214214

215215
// OnDeleteManifest is called when a manifest is deleted. It updates metadb according to the type
216-
// of image pushed(normal images, signatues, etc.). In care of any errors, it makes sure to keep
216+
// of image pushed(normal images, signatures, etc.). In case of any errors, it makes sure to keep
217217
// consistency between metadb and the image store.
218218
func OnDeleteManifest(repo, reference, mediaType string, digest godigest.Digest, manifestBlob []byte,
219219
storeController storage.StoreController, metaDB mTypes.MetaDB, log log.Logger,
@@ -271,7 +271,7 @@ func OnDeleteManifest(repo, reference, mediaType string, digest godigest.Digest,
271271
return nil
272272
}
273273

274-
// OnGetManifest is called when a manifest is downloaded. It increments the download couter on that manifest.
274+
// OnGetManifest is called when a manifest is downloaded. It increments the download counter on that manifest.
275275
func OnGetManifest(name, reference, mediaType string, body []byte,
276276
storeController storage.StoreController, metaDB mTypes.MetaDB, log log.Logger,
277277
) error {

pkg/requestcontext/authn.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package uac
1+
package requestcontext
22

33
import (
44
"context"

pkg/requestcontext/user_access_control.go

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package uac
1+
package requestcontext
22

33
import (
44
"context"
@@ -167,9 +167,8 @@ func (uac *UserAccessControl) SetGlobPatterns(action string, patterns map[string
167167
uac.authzInfo.globPatterns[action] = patterns
168168
}
169169

170-
/*
171-
Can returns whether or not the user/anonymous who made the request has 'action' permission on 'repository'.
172-
*/
170+
// Can returns whether or not the user/anonymous who made the request has
171+
// action permission on repository.
173172
func (uac *UserAccessControl) Can(action, repository string) bool {
174173
var defaultRet bool
175174
if uac.isBehaviourAction(action) {
@@ -205,10 +204,8 @@ func (uac *UserAccessControl) areGlobPatternsSet() bool {
205204
return !notSet
206205
}
207206

208-
/*
209-
returns whether or not 'repository' can be found in the list of patterns
210-
on which the user who made the request has read permission on.
211-
*/
207+
// matchesRepo returns whether repository matches the provided action's glob patterns
208+
// and is allowed by the longest matching pattern.
212209
func (uac *UserAccessControl) matchesRepo(globPatterns map[string]bool, repository string) bool {
213210
var longestMatchedPattern string
214211

pkg/storage/gc/gc_test.go

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -58,12 +58,20 @@ var testCases = []struct {
5858
},
5959
}
6060

61+
func newTestMetricsServer(t *testing.T, log zlog.Logger) monitoring.MetricServer {
62+
t.Helper()
63+
64+
metrics := monitoring.NewMetricsServer(false, log)
65+
t.Cleanup(metrics.Stop)
66+
67+
return metrics
68+
}
69+
6170
func TestGarbageCollectAndRetentionMetaDB(t *testing.T) {
6271
log := zlog.NewTestLogger()
6372
audit := zlog.NewAuditLogger("debug", "/dev/null")
6473

65-
metrics := monitoring.NewMetricsServer(false, log)
66-
defer metrics.Stop() // Clean up metrics server to prevent resource leaks
74+
metrics := newTestMetricsServer(t, log)
6775

6876
trueVal := true
6977

@@ -1242,7 +1250,7 @@ func TestGarbageCollectAndRetentionMetaDB(t *testing.T) {
12421250
So(err, ShouldBeNil)
12431251

12441252
if testcase.testCaseName == s3TestName {
1245-
// Remote sorage is written to only after the blob upload is finished,
1253+
// Remote storage is written to only after the blob upload is finished,
12461254
// there should be no space used by blob uploads
12471255
So(uploads, ShouldEqual, []string{})
12481256
} else {
@@ -1253,7 +1261,7 @@ func TestGarbageCollectAndRetentionMetaDB(t *testing.T) {
12531261
isPresent, _, _, err := imgStore.StatBlobUpload(repoName, blobUploadID)
12541262

12551263
if testcase.testCaseName == s3TestName {
1256-
// Remote sorage is written to only after the blob upload is finished,
1264+
// Remote storage is written to only after the blob upload is finished,
12571265
// there should be no space used by blob uploads
12581266
So(err, ShouldNotBeNil)
12591267
So(isPresent, ShouldBeFalse)
@@ -1271,7 +1279,7 @@ func TestGarbageCollectAndRetentionMetaDB(t *testing.T) {
12711279
So(err, ShouldBeNil)
12721280

12731281
if testcase.testCaseName == s3TestName {
1274-
// Remote sorage is written to only after the blob upload is finished,
1282+
// Remote storage is written to only after the blob upload is finished,
12751283
// there should be no space used by blob uploads
12761284
So(uploads, ShouldEqual, []string{})
12771285
} else {
@@ -1282,7 +1290,7 @@ func TestGarbageCollectAndRetentionMetaDB(t *testing.T) {
12821290
isPresent, _, _, err = imgStore.StatBlobUpload(repoName, blobUploadID)
12831291

12841292
if testcase.testCaseName == s3TestName {
1285-
// Remote sorage is written to only after the blob upload is finished,
1293+
// Remote storage is written to only after the blob upload is finished,
12861294
// there should be no space used by blob uploads
12871295
So(err, ShouldNotBeNil)
12881296
So(isPresent, ShouldBeFalse)
@@ -1316,8 +1324,7 @@ func TestGarbageCollectDeletion(t *testing.T) {
13161324
log := zlog.NewTestLogger()
13171325
audit := zlog.NewAuditLogger("debug", "/dev/null")
13181326

1319-
metrics := monitoring.NewMetricsServer(false, log)
1320-
defer metrics.Stop() // Clean up metrics server to prevent resource leaks
1327+
metrics := newTestMetricsServer(t, log)
13211328

13221329
trueVal := true
13231330
falseVal := false
@@ -1755,8 +1762,7 @@ func TestGarbageCollectAndRetentionNoMetaDB(t *testing.T) {
17551762
log := zlog.NewTestLogger()
17561763
audit := zlog.NewAuditLogger("debug", "/dev/null")
17571764

1758-
metrics := monitoring.NewMetricsServer(false, log)
1759-
defer metrics.Stop() // Clean up metrics server to prevent resource leaks
1765+
metrics := newTestMetricsServer(t, log)
17601766

17611767
trueVal := true
17621768

@@ -2566,7 +2572,7 @@ func TestGarbageCollectAndRetentionNoMetaDB(t *testing.T) {
25662572
So(err, ShouldBeNil)
25672573

25682574
if testcase.testCaseName == s3TestName {
2569-
// Remote sorage is written to only after the blob upload is finished,
2575+
// Remote storage is written to only after the blob upload is finished,
25702576
// there should be no space used by blob uploads
25712577
So(uploads, ShouldEqual, []string{})
25722578
} else {
@@ -2577,7 +2583,7 @@ func TestGarbageCollectAndRetentionNoMetaDB(t *testing.T) {
25772583
isPresent, _, _, err := imgStore.StatBlobUpload(repoName, blobUploadID)
25782584

25792585
if testcase.testCaseName == s3TestName {
2580-
// Remote sorage is written to only after the blob upload is finished,
2586+
// Remote storage is written to only after the blob upload is finished,
25812587
// there should be no space used by blob uploads
25822588
So(err, ShouldNotBeNil)
25832589
So(isPresent, ShouldBeFalse)
@@ -2595,7 +2601,7 @@ func TestGarbageCollectAndRetentionNoMetaDB(t *testing.T) {
25952601
So(err, ShouldBeNil)
25962602

25972603
if testcase.testCaseName == s3TestName {
2598-
// Remote sorage is written to only after the blob upload is finished,
2604+
// Remote storage is written to only after the blob upload is finished,
25992605
// there should be no space used by blob uploads
26002606
So(uploads, ShouldEqual, []string{})
26012607
} else {
@@ -2606,7 +2612,7 @@ func TestGarbageCollectAndRetentionNoMetaDB(t *testing.T) {
26062612
isPresent, _, _, err = imgStore.StatBlobUpload(repoName, blobUploadID)
26072613

26082614
if testcase.testCaseName == s3TestName {
2609-
// Remote sorage is written to only after the blob upload is finished,
2615+
// Remote storage is written to only after the blob upload is finished,
26102616
// there should be no space used by blob uploads
26112617
So(err, ShouldNotBeNil)
26122618
So(isPresent, ShouldBeFalse)

0 commit comments

Comments
 (0)