feat(image): support tar.gz image (fanal#40)

This commit is contained in:
Teppei Fukuda
2019-10-15 11:48:52 +03:00
committed by GitHub
parent 83f0e2b08b
commit 9e8f0bb4f0
9 changed files with 57 additions and 2 deletions

View File

@@ -1,10 +1,14 @@
package analyzer
import (
"compress/gzip"
"context"
"io"
"os"
"time"
"github.com/aquasecurity/fanal/utils"
"github.com/aquasecurity/fanal/types"
"golang.org/x/xerrors"
@@ -136,7 +140,15 @@ func Analyze(ctx context.Context, imageName string, opts ...types.DockerOption)
return fileMap, nil
}
func AnalyzeFromFile(ctx context.Context, r io.ReadCloser) (fileMap extractor.FileMap, err error) {
func AnalyzeFile(ctx context.Context, f *os.File) (fileMap extractor.FileMap, err error) {
var r io.Reader
r = f
if utils.IsGzip(f) {
r, err = gzip.NewReader(f)
if err != nil {
return nil, xerrors.Errorf("failed to open gzip: %w", err)
}
}
e := docker.NewDockerExtractor(types.DockerOption{})
fileMap, err = e.ExtractFromFile(ctx, r, RequiredFilenames())
if err != nil {

View File

@@ -64,7 +64,7 @@ func run() (err error) {
return err
}
files, err = analyzer.AnalyzeFromFile(ctx, rc)
files, err = analyzer.AnalyzeFile(ctx, rc)
if err != nil {
return err
}

BIN
utils/testdata/aqua.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

BIN
utils/testdata/test.tar.gz vendored Normal file

Binary file not shown.

BIN
utils/testdata/test.txt vendored Normal file

Binary file not shown.

BIN
utils/testdata/test.txt.gz vendored Normal file

Binary file not shown.

BIN
utils/testdata/test.txt.zst vendored Normal file

Binary file not shown.

View File

@@ -2,6 +2,7 @@ package utils
import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
@@ -37,3 +38,13 @@ func IsCommandAvailable(name string) bool {
}
return true
}
func IsGzip(f *os.File) bool {
buf := make([]byte, 3)
n, _ := f.Read(buf)
defer f.Seek(0, io.SeekStart)
if n < 3 {
return false
}
return buf[0] == 0x1F && buf[1] == 0x8B && buf[2] == 0x8
}

32
utils/utils_test.go Normal file
View File

@@ -0,0 +1,32 @@
package utils
import (
"os"
"testing"
)
func TestIsGzip(t *testing.T) {
var tests = []struct {
in string
want bool
}{
{"testdata/test.txt.gz", true},
{"testdata/test.tar.gz", true},
{"testdata/test.txt", false},
{"testdata/test.txt.zst", false},
{"testdata/aqua.png", false},
}
for _, tt := range tests {
t.Run(tt.in, func(t *testing.T) {
f, err := os.Open(tt.in)
if err != nil {
t.Fatalf("unknown error: %s", err)
}
got := IsGzip(f)
if got != tt.want {
t.Errorf("got %t, want %t", got, tt.want)
}
})
}
}