From e6d7f01d79e40f825deef76581246d1be5e4908b Mon Sep 17 00:00:00 2001 From: Evan Gibler <20933572+egibs@users.noreply.github.com> Date: Tue, 17 Dec 2024 16:43:35 -0600 Subject: [PATCH] Improve extracted archive file clean up (#714) * Improve extracted archive file clean up Signed-off-by: egibs <20933572+egibs@users.noreply.github.com> * Wrap tmpRoot removal in a defer instead Signed-off-by: egibs <20933572+egibs@users.noreply.github.com> * Only remove if tmpRoot is created successfully Signed-off-by: egibs <20933572+egibs@users.noreply.github.com> --------- Signed-off-by: egibs <20933572+egibs@users.noreply.github.com> --- pkg/action/scan.go | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/pkg/action/scan.go b/pkg/action/scan.go index 096e3ffa0..9aab19ab4 100644 --- a/pkg/action/scan.go +++ b/pkg/action/scan.go @@ -497,6 +497,14 @@ func processArchive(ctx context.Context, c malcontent.Config, rfs []fs.FS, archi if err != nil { return nil, fmt.Errorf("extract to temp: %w", err) } + // Ensure that tmpRoot is removed before returning if created successfully + if tmpRoot != "" { + defer func() { + if err := os.RemoveAll(tmpRoot); err != nil { + logger.Errorf("remove %s: %v", tmpRoot, err) + } + }() + } // macOS will prefix temporary directories with `/private` // update tmpRoot with this prefix to allow strings.TrimPrefix to work if runtime.GOOS == "darwin" { @@ -515,13 +523,10 @@ func processArchive(ctx context.Context, c malcontent.Config, rfs []fs.FS, archi } if fr != nil { // Store a clean reprepsentation of the archive's scanned file to match single file scanning behavior - extractedFilePath = strings.TrimPrefix(extractedFilePath, tmpRoot) - frs.Store(extractedFilePath, fr) + clean := strings.TrimPrefix(extractedFilePath, tmpRoot) + frs.Store(clean, fr) } } - if err := os.RemoveAll(tmpRoot); err != nil { - logger.Errorf("remove %s: %v", tmpRoot, err) - } return &frs, nil }