-
Notifications
You must be signed in to change notification settings - Fork 11
/
common.go
61 lines (54 loc) · 1.79 KB
/
common.go
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
54
55
56
57
58
59
60
61
/* Copyright (c) 2019 Snowflake Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package mtls
import (
"crypto/x509"
"fmt"
"os"
"path/filepath"
)
// LoadRootOfTrust will load an CA root of trust(s) from the given
// file and return a CertPool to use in validating certificates.
// All CA's to validate against must be presented together in the PEM
// file.
// If the file is a directory, LoadRootOfTrust will load all files
// in that directory.
func LoadRootOfTrust(path string) (*x509.CertPool, error) {
fi, err := os.Stat(path)
if err != nil {
return nil, fmt.Errorf("could not stat CA cert path %q: %w", path, err)
}
var certfiles []string
if fi.IsDir() {
files, err := os.ReadDir(path)
if err != nil {
return nil, fmt.Errorf("could not read CA cert directory %q: %w", path, err)
}
for _, f := range files {
certfiles = append(certfiles, filepath.Join(path, f.Name()))
}
} else {
certfiles = []string{path}
}
capool := x509.NewCertPool()
for _, filename := range certfiles {
ca, err := os.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("could not read %q: %w", filename, err)
}
if !capool.AppendCertsFromPEM(ca) {
return nil, fmt.Errorf("could not add CA cert from %q to pool: %w", filename, err)
}
}
return capool, nil
}