From 4568f32181ac08a3a423eb546f836f9c6835eaa4 Mon Sep 17 00:00:00 2001 From: Mario Leyva Date: Tue, 25 Feb 2025 09:40:04 -0800 Subject: [PATCH] Fix bug where SCABLIR temporary directory wasn't deleted after RPM extraction. PiperOrigin-RevId: 730920555 --- extractor/filesystem/os/rpm/rpm_linux.go | 4 +-- extractor/filesystem/os/rpm/rpm_test.go | 31 ++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/extractor/filesystem/os/rpm/rpm_linux.go b/extractor/filesystem/os/rpm/rpm_linux.go index 4642a6d2..04891a98 100644 --- a/extractor/filesystem/os/rpm/rpm_linux.go +++ b/extractor/filesystem/os/rpm/rpm_linux.go @@ -168,9 +168,9 @@ func (e Extractor) extractFromInput(ctx context.Context, input *filesystem.ScanI if input.Root == "" { // The file got copied to a temporary dir, remove it at the end. defer func() { - dir := filepath.Base(absPath) + dir := filepath.Dir(absPath) if err := os.RemoveAll(dir); err != nil { - log.Errorf("os.RemoveAll(%q%): %w", dir, err) + log.Errorf("os.RemoveAll(%q): %w", dir, err) } }() } diff --git a/extractor/filesystem/os/rpm/rpm_test.go b/extractor/filesystem/os/rpm/rpm_test.go index 043fcb2f..539b15d2 100644 --- a/extractor/filesystem/os/rpm/rpm_test.go +++ b/extractor/filesystem/os/rpm/rpm_test.go @@ -24,6 +24,7 @@ import ( "runtime" "slices" "sort" + "strings" "testing" "time" @@ -790,6 +791,10 @@ func TestExtract_VirtualFilesystem(t *testing.T) { d := t.TempDir() createOsRelease(t, d, tt.osrelease) + // Need to record scalibr files found in /tmp before the rpm extractor runs, as it may create + // some. This is needed to compare the files found after the extractor runs. + filesInTmpWant := scalibrFilesInTmp(t) + r, err := os.Open(tt.path) defer func() { if err = r.Close(); err != nil { @@ -823,6 +828,13 @@ func TestExtract_VirtualFilesystem(t *testing.T) { if len(got) != tt.wantResults { t.Errorf("Extract(%s): got %d results, want %d\n", tt.path, len(got), tt.wantResults) } + + // Check that no scalibr files remain in /tmp. + filesInTmpGot := scalibrFilesInTmp(t) + less := func(a, b string) bool { return a < b } + if diff := cmp.Diff(filesInTmpWant, filesInTmpGot, cmpopts.SortSlices(less)); diff != "" { + t.Errorf("returned unexpected diff (-want +got):\n%s", diff) + } }) } } @@ -996,3 +1008,22 @@ func createOsRelease(t *testing.T, root string, content string) { t.Fatalf("write to %s: %v\n", filepath.Join(root, "etc/os-release"), err) } } + +// scalibrFilesInTmp returns the list of filenames in /tmp that start with "scalibr-". +func scalibrFilesInTmp(t *testing.T) []string { + t.Helper() + + filenames := []string{} + files, err := os.ReadDir(os.TempDir()) + if err != nil { + t.Fatalf("os.ReadDir('%q') error: %v", os.TempDir(), err) + } + + for _, f := range files { + name := f.Name() + if strings.HasPrefix(name, "scalibr-") { + filenames = append(filenames, f.Name()) + } + } + return filenames +}