github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/pkg/x509util/x509util.go (about)

     1  package x509util
     2  
     3  import (
     4  	"crypto/x509"
     5  	"errors"
     6  	"io/fs"
     7  	"os"
     8  )
     9  
    10  // CustomCertPool creates a x509.CertPool from a filepath string.
    11  //
    12  // If the path is a directory, it walks the directory and adds all files to the
    13  // pool.
    14  func CustomCertPool(caPath string) (*x509.CertPool, error) {
    15  	fi, err := os.Stat(caPath)
    16  	if err != nil {
    17  		return nil, err
    18  	}
    19  
    20  	var caFiles [][]byte
    21  	if fi.IsDir() {
    22  		caFiles, err = dirContents(caPath)
    23  		if err != nil {
    24  			return nil, err
    25  		}
    26  	} else {
    27  		contents, err := os.ReadFile(caPath)
    28  		if err != nil {
    29  			return nil, err
    30  		}
    31  		caFiles = append(caFiles, contents)
    32  	}
    33  
    34  	certPool := x509.NewCertPool()
    35  	for _, caBytes := range caFiles {
    36  		if ok := certPool.AppendCertsFromPEM(caBytes); !ok {
    37  			return nil, errors.New("failed to append certs from CA PEM")
    38  		}
    39  	}
    40  
    41  	return certPool, nil
    42  }
    43  
    44  func dirContents(dirPath string) ([][]byte, error) {
    45  	var allContents [][]byte
    46  	dirFS := os.DirFS(dirPath)
    47  	if err := fs.WalkDir(dirFS, ".", func(path string, d fs.DirEntry, err error) error {
    48  		if !d.IsDir() {
    49  			contents, err := fs.ReadFile(dirFS, d.Name())
    50  			if err != nil {
    51  				return err
    52  			}
    53  			allContents = append(allContents, contents)
    54  		}
    55  		return nil
    56  	}); err != nil {
    57  		return nil, err
    58  	}
    59  
    60  	return allContents, nil
    61  }