github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/pkg/rego/store.go (about)

     1  package rego
     2  
     3  import (
     4  	"fmt"
     5  	"io/fs"
     6  	"os"
     7  	"path/filepath"
     8  	"strings"
     9  
    10  	"github.com/open-policy-agent/opa/loader"
    11  	"github.com/open-policy-agent/opa/storage"
    12  )
    13  
    14  // initialise a store populated with OPA data files found in dataPaths
    15  func initStore(dataFS fs.FS, dataPaths, namespaces []string) (storage.Store, error) {
    16  	// FilteredPaths will recursively find all file paths that contain a valid document
    17  	// extension from the given list of data paths.
    18  	allDocumentPaths, _ := loader.FilteredPathsFS(dataFS, dataPaths, func(abspath string, info os.FileInfo, depth int) bool {
    19  		if info.IsDir() {
    20  			return false // filter in, include
    21  		}
    22  		ext := strings.ToLower(filepath.Ext(info.Name()))
    23  		for _, filter := range []string{
    24  			".yaml",
    25  			".yml",
    26  			".json",
    27  		} {
    28  			if filter == ext {
    29  				return false // filter in, include
    30  			}
    31  		}
    32  		return true // filter out, exclude
    33  	})
    34  
    35  	documents, err := loader.NewFileLoader().WithFS(dataFS).All(allDocumentPaths)
    36  	if err != nil {
    37  		return nil, fmt.Errorf("load documents: %w", err)
    38  	}
    39  
    40  	// pass all namespaces so that rego rule can refer to namespaces as data.namespaces
    41  	documents.Documents["namespaces"] = namespaces
    42  
    43  	store, err := documents.Store()
    44  	if err != nil {
    45  		return nil, fmt.Errorf("get documents store: %w", err)
    46  	}
    47  	return store, nil
    48  }