File: certpool.go

package info (click to toggle)
golang-github-smallstep-crypto 0.63.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,800 kB
  • sloc: sh: 66; makefile: 50
file content (53 lines) | stat: -rw-r--r-- 1,186 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package x509util

import (
	"crypto/x509"
	"os"
	"path/filepath"
	"strings"

	"github.com/pkg/errors"
)

// ReadCertPool loads a certificate pool from disk. The given path can be a
// file, a directory, or a comma-separated list of files.
func ReadCertPool(path string) (*x509.CertPool, error) {
	info, err := os.Stat(path)
	if err != nil && !os.IsNotExist(err) {
		return nil, errors.Wrap(err, "error reading cert pool")
	}

	var (
		files []string
		pool  = x509.NewCertPool()
	)
	if info != nil && info.IsDir() {
		finfos, err := os.ReadDir(path)
		if err != nil {
			return nil, errors.Wrap(err, "error reading cert pool")
		}
		for _, finfo := range finfos {
			files = append(files, filepath.Join(path, finfo.Name()))
		}
	} else {
		files = strings.Split(path, ",")
		for i := range files {
			files[i] = strings.TrimSpace(files[i])
		}
	}

	var found bool
	for _, f := range files {
		bytes, err := os.ReadFile(f)
		if err != nil {
			return nil, errors.Wrap(err, "error reading cert pool")
		}
		if ok := pool.AppendCertsFromPEM(bytes); ok {
			found = true
		}
	}
	if !found {
		return nil, errors.New("error reading cert pool: not certificates found")
	}
	return pool, nil
}