Skip to content

Commit

Permalink
Rename TrivyOpts to ScannerOpts and refactor error handling
Browse files Browse the repository at this point in the history
Renamed the `TrivyOpts` struct to `ScannerOpts` to better reflect its purpose. Added an explicit channel parameter `ch` for error handling throughout the functions to improve code clarity and maintainability. Added new test cases to cover scenarios with digest-referenced Docker images.

Signed-off-by: Miaha Cybersec <[email protected]>
  • Loading branch information
Miaha Cybersec authored and Miaha Cybersec committed Aug 14, 2024
1 parent 3941bcc commit 6f4a12a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 21 deletions.
40 changes: 19 additions & 21 deletions pkg/patch/patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,8 @@ const (
defaultTag = "latest"
)

type TrivyOpts struct {
type ScannerOpts struct {
Image string
Ch chan error
ReportFile string
WorkingFolder string
Updates *unversioned.UpdateManifest
Expand Down Expand Up @@ -193,15 +192,14 @@ func patchWithContext(ctx context.Context, ch chan error, image, reportFile, use
eg.Go(func() error {
err = buildkitBuild(
BuildContext{ctx},
&TrivyOpts{
image, ch,
reportFile, workingFolder, updates, ignoreError,
&ScannerOpts{
image, reportFile, workingFolder, updates, ignoreError,
output, dockerNormalizedImageName, patchedImageName, format,
},
BkClient{
bkClient, &solveOpt,
},
BuildStatus{buildChannel})
BuildStatus{buildChannel}, ch)

Check warning on line 202 in pkg/patch/patch.go

View check run for this annotation

Codecov / codecov/patch

pkg/patch/patch.go#L193-L202

Added lines #L193 - L202 were not covered by tests
return err
})

Expand Down Expand Up @@ -232,24 +230,24 @@ func patchWithContext(ctx context.Context, ch chan error, image, reportFile, use
}

// buildkitBuild submits a build request to BuildKit with the given information.
func buildkitBuild(buildContext BuildContext, trivyOpts *TrivyOpts, bkClient BkClient, buildStatus BuildStatus) error {
func buildkitBuild(buildContext BuildContext, trivyOpts *ScannerOpts, bkClient BkClient, buildStatus BuildStatus, ch chan error) error {
_, err := bkClient.BkClient.Build(buildContext.Ctx, *bkClient.SolveOpt, copaProduct, func(ctx context.Context, c gwclient.Client) (*gwclient.Result, error) {
bkConfig, err := buildkit.InitializeBuildkitConfig(ctx, c, trivyOpts.DockerNormalizedImageName.String())
if err != nil {
return handleError(trivyOpts.Ch, err)
return handleError(ch, err)

Check warning on line 237 in pkg/patch/patch.go

View check run for this annotation

Codecov / codecov/patch

pkg/patch/patch.go#L233-L237

Added lines #L233 - L237 were not covered by tests
}

manager, err := resolvePackageManager(buildContext, trivyOpts, c, bkConfig)
if err != nil {
return handleError(trivyOpts.Ch, err)
return handleError(ch, err)

Check warning on line 242 in pkg/patch/patch.go

View check run for this annotation

Codecov / codecov/patch

pkg/patch/patch.go#L240-L242

Added lines #L240 - L242 were not covered by tests
}

return buildReport(buildContext, trivyOpts, bkConfig, manager)
return buildReport(buildContext, trivyOpts, bkConfig, manager, ch)

Check warning on line 245 in pkg/patch/patch.go

View check run for this annotation

Codecov / codecov/patch

pkg/patch/patch.go#L245

Added line #L245 was not covered by tests
}, buildStatus.BuildChannel)
return err

Check warning on line 247 in pkg/patch/patch.go

View check run for this annotation

Codecov / codecov/patch

pkg/patch/patch.go#L247

Added line #L247 was not covered by tests
}

func resolvePackageManager(buildContext BuildContext, trivyOpts *TrivyOpts, client gwclient.Client, config *buildkit.Config) (pkgmgr.PackageManager, error) {
func resolvePackageManager(buildContext BuildContext, trivyOpts *ScannerOpts, client gwclient.Client, config *buildkit.Config) (pkgmgr.PackageManager, error) {
var manager pkgmgr.PackageManager
if trivyOpts.ReportFile == "" {
fileBytes, err := buildkit.ExtractFileFromState(buildContext.Ctx, client, &config.ImageState, "/etc/os-release")
Expand Down Expand Up @@ -289,25 +287,25 @@ func handleError(ch chan error, err error) (*gwclient.Result, error) {
}

// buildReport is an extracted method containing logic to manage the updates and build report.
func buildReport(buildContext BuildContext, trivyOpts *TrivyOpts, config *buildkit.Config, manager pkgmgr.PackageManager) (*gwclient.Result, error) {
func buildReport(buildContext BuildContext, trivyOpts *ScannerOpts, config *buildkit.Config, manager pkgmgr.PackageManager, ch chan error) (*gwclient.Result, error) {
patchedImageState, errPkgs, err := manager.InstallUpdates(buildContext.Ctx, trivyOpts.Updates, trivyOpts.IgnoreError)
if err != nil {
return handleError(trivyOpts.Ch, err)
return handleError(ch, err)

Check warning on line 293 in pkg/patch/patch.go

View check run for this annotation

Codecov / codecov/patch

pkg/patch/patch.go#L290-L293

Added lines #L290 - L293 were not covered by tests
}
platform := platforms.Normalize(platforms.DefaultSpec())
if platform.OS != "linux" {
platform.OS = "linux"

Check warning on line 297 in pkg/patch/patch.go

View check run for this annotation

Codecov / codecov/patch

pkg/patch/patch.go#L295-L297

Added lines #L295 - L297 were not covered by tests
}
def, err := patchedImageState.Marshal(buildContext.Ctx, llb.Platform(platform))
if err != nil {
return handleError(trivyOpts.Ch, fmt.Errorf("unable to get platform from ImageState %w", err))
return handleError(ch, fmt.Errorf("unable to get platform from ImageState %w", err))

Check warning on line 301 in pkg/patch/patch.go

View check run for this annotation

Codecov / codecov/patch

pkg/patch/patch.go#L299-L301

Added lines #L299 - L301 were not covered by tests
}
res, err := config.Client.Solve(buildContext.Ctx, gwclient.SolveRequest{
Definition: def.ToPB(),
Evaluate: true,
})
if err != nil {
return handleError(trivyOpts.Ch, err)
return handleError(ch, err)

Check warning on line 308 in pkg/patch/patch.go

View check run for this annotation

Codecov / codecov/patch

pkg/patch/patch.go#L303-L308

Added lines #L303 - L308 were not covered by tests
}
res.AddMeta(exptypes.ExporterImageConfigKey, config.ConfigData)

Check warning on line 310 in pkg/patch/patch.go

View check run for this annotation

Codecov / codecov/patch

pkg/patch/patch.go#L310

Added line #L310 was not covered by tests
// Currently can only validate updates if updating via scanner
Expand All @@ -317,7 +315,7 @@ func buildReport(buildContext BuildContext, trivyOpts *TrivyOpts, config *buildk
if trivyOpts.Output != "" && len(validatedManifest.Updates) > 0 {
err = vex.TryOutputVexDocument(validatedManifest, manager, trivyOpts.PatchedImageName, trivyOpts.Format, trivyOpts.Output)
if err != nil {
return handleError(trivyOpts.Ch, err)
return handleError(ch, err)

Check warning on line 318 in pkg/patch/patch.go

View check run for this annotation

Codecov / codecov/patch

pkg/patch/patch.go#L315-L318

Added lines #L315 - L318 were not covered by tests
}
}
}
Expand Down Expand Up @@ -347,28 +345,28 @@ func updateManifest(updates *unversioned.UpdateManifest, errPkgs []string) *unve
}

func generatePatchedTag(dockerNormalizedImageName reference.Named, userSuppliedPatchTag string) string {
// officialTag is typically the versioning tag of the image as published in a container registry
var officialTag string
// currentTag is typically the versioning tag of the image as published in a container registry
var currentTag string
var copaTag string

taggedName, ok := dockerNormalizedImageName.(reference.Tagged)

if ok {
officialTag = taggedName.Tag()
currentTag = taggedName.Tag()
} else {
log.Warnf("Image name has no tag")
}

if userSuppliedPatchTag != "" {
copaTag = userSuppliedPatchTag
return copaTag
} else if officialTag == "" {
} else if currentTag == "" {
log.Warnf("No output tag specified for digest-referenced image, defaulting to `%s`", defaultPatchedTagSuffix)
copaTag = defaultPatchedTagSuffix
return copaTag
}

copaTag = fmt.Sprintf("%s-%s", officialTag, defaultPatchedTagSuffix)
copaTag = fmt.Sprintf("%s-%s", currentTag, defaultPatchedTagSuffix)
return copaTag
}

Expand Down
12 changes: 12 additions & 0 deletions pkg/patch/patch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,18 @@ func TestGeneratePatchedTag(t *testing.T) {
userSuppliedPatchTag: "20231004-custom-tag",
expectedPatchedTag: "20231004-custom-tag",
},
{
name: "NoTag_WithDigest_NoUserSupplied",
dockerImageName: "docker.io/library/debian@sha256:540ebf19fb0bbc243e1314edac26b9fe7445e9c203357f27968711a45ea9f1d4",
userSuppliedPatchTag: "",
expectedPatchedTag: defaultPatchedTagSuffix,
},
{
name: "NoTag_WithDigest_UserSupplied",
dockerImageName: "docker.io/library/debian@sha256:540ebf19fb0bbc243e1314edac26b9fe7445e9c203357f27968711a45ea9f1d4",
userSuppliedPatchTag: "stable-patched",
expectedPatchedTag: "stable-patched",
},
}

for _, tc := range testCases {
Expand Down

0 comments on commit 6f4a12a

Please sign in to comment.