github.com/devseccon/trivy@v0.47.1-0.20231123133102-bd902a0bd996/pkg/fanal/analyzer/config/config.go (about)

     1  package config
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"golang.org/x/xerrors"
     9  	"k8s.io/utils/strings/slices"
    10  
    11  	"github.com/devseccon/trivy/pkg/fanal/analyzer"
    12  	"github.com/devseccon/trivy/pkg/misconf"
    13  )
    14  
    15  var (
    16  	_ analyzer.PostAnalyzer = (*Analyzer)(nil)
    17  
    18  	requiredExts = []string{".json", ".yaml", ".yml", ".tfvars"}
    19  )
    20  
    21  // Analyzer represents an analyzer for config files,
    22  // which is embedded into each config analyzer such as Kubernetes.
    23  type Analyzer struct {
    24  	typ     analyzer.Type
    25  	version int
    26  	scanner *misconf.Scanner
    27  }
    28  
    29  type NewScanner func([]string, misconf.ScannerOption) (*misconf.Scanner, error)
    30  
    31  func NewAnalyzer(t analyzer.Type, version int, newScanner NewScanner, opts analyzer.AnalyzerOptions) (*Analyzer, error) {
    32  	s, err := newScanner(opts.FilePatterns, opts.MisconfScannerOption)
    33  	if err != nil {
    34  		return nil, xerrors.Errorf("%s scanner init error: %w", t, err)
    35  	}
    36  	return &Analyzer{
    37  		typ:     t,
    38  		version: version,
    39  		scanner: s,
    40  	}, nil
    41  }
    42  
    43  // PostAnalyze performs configuration analysis on the input filesystem and detect misconfigurations.
    44  func (a *Analyzer) PostAnalyze(ctx context.Context, input analyzer.PostAnalysisInput) (*analyzer.AnalysisResult, error) {
    45  	misconfs, err := a.scanner.Scan(ctx, input.FS)
    46  	if err != nil {
    47  		return nil, xerrors.Errorf("%s scan error: %w", a.typ, err)
    48  	}
    49  	return &analyzer.AnalysisResult{Misconfigurations: misconfs}, nil
    50  }
    51  
    52  // Required checks if the given file path has one of the required file extensions.
    53  func (a *Analyzer) Required(filePath string, _ os.FileInfo) bool {
    54  	return slices.Contains(requiredExts, filepath.Ext(filePath))
    55  }
    56  
    57  // Type returns the analyzer type of the current Analyzer instance.
    58  func (a *Analyzer) Type() analyzer.Type {
    59  	return a.typ
    60  }
    61  
    62  // Version returns the version of the current Analyzer instance.
    63  func (a *Analyzer) Version() int {
    64  	return a.version
    65  }