blob: e48e013b8918601adfcb648dbdd2df1a1d3b7b37 [file] [log] [blame]
Serge Bazanskif3312ef2020-08-01 17:15:52 +02001package pki
2
3import (
4 "fmt"
5 "io/ioutil"
6 "os"
7
8 "github.com/golang/glog"
9)
10
11// DeveloperCredentialsLocation returns the path containing HSPKI credentials
12// on developer machines. These are provisioned by //cluster/prodaccess, and
13// are used if available.
14func DeveloperCredentialsLocation() (string, error) {
15 cfgDir, err := os.UserConfigDir()
16 if err != nil {
17 glog.Exitf("UserConfigDir: %w", err)
18 }
19
20 return fmt.Sprintf("%s/hspki", cfgDir), nil
21}
22
23type creds struct {
24 ca []byte
25 cert []byte
26 key []byte
27}
28
29func loadDeveloperCredentials() (*creds, error) {
30 path, err := DeveloperCredentialsLocation()
31 if err != nil {
32 return nil, fmt.Errorf("DeveloperCredentialsLocation: %w")
33 }
34
35 c := creds{}
36 for _, el := range []struct {
37 target *[]byte
38 path string
39 }{
40 {&c.ca, path + "/" + "ca.crt"},
41 {&c.cert, path + "/" + "tls.crt"},
42 {&c.key, path + "/" + "tls.key"},
43 } {
44 data, err := ioutil.ReadFile(el.path)
45 if err != nil {
46 return nil, fmt.Errorf("ReadFile(%q): %w", el.path, err)
47 }
48 *el.target = data
49 }
50
51 return &c, nil
52}
53
54func loadFlagCredentials() (*creds, error) {
55 c := creds{}
56 for _, el := range []struct {
57 target *[]byte
58 path string
59 }{
60 {&c.ca, flagCAPath},
61 {&c.cert, flagCertificatePath},
62 {&c.key, flagKeyPath},
63 } {
64 data, err := ioutil.ReadFile(el.path)
65 if err != nil {
66 return nil, fmt.Errorf("ReadFile(%q): %w", el.path, err)
67 }
68 *el.target = data
69 }
70
71 return &c, nil
72}
73
74func loadCredentials() (*creds, error) {
75 dev, err := loadDeveloperCredentials()
76 if err == nil {
77 return dev, nil
78 }
79 glog.Warningf("Could not load developer PKI credentials: %v", err)
80
81 fl, err := loadFlagCredentials()
82 if err == nil {
83 return fl, err
84 }
85 glog.Warningf("Could not load flag-defined PKI credentials: %v", err)
86
87 return nil, fmt.Errorf("could not load any credentials")
88}