-
Notifications
You must be signed in to change notification settings - Fork 232
/
settings.go
275 lines (220 loc) · 6.35 KB
/
settings.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package settings
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/CircleCI-Public/circleci-cli/data"
yaml "gopkg.in/yaml.v3"
)
// Config is used to represent the current state of a CLI instance.
type Config struct {
Host string `yaml:"host"`
Endpoint string `yaml:"endpoint"`
Token string `yaml:"token"`
RestEndpoint string `yaml:"rest_endpoint"`
TLSCert string `yaml:"tls_cert"`
TLSInsecure bool `yaml:"tls_insecure"`
HTTPClient *http.Client `yaml:"-"`
Data *data.DataBag `yaml:"-"`
Debug bool `yaml:"-"`
Address string `yaml:"-"`
FileUsed string `yaml:"-"`
GitHubAPI string `yaml:"-"`
SkipUpdateCheck bool `yaml:"-"`
OrbPublishing OrbPublishingInfo `yaml:"orb_publishing"`
}
type OrbPublishingInfo struct {
DefaultNamespace string `yaml:"default_namespace"`
DefaultVcsProvider string `yaml:"default_vcs_provider"`
DefaultOwner string `yaml:"default_owner"`
}
// UpdateCheck is used to represent settings for checking for updates of the CLI.
type UpdateCheck struct {
LastUpdateCheck time.Time `yaml:"last_update_check"`
FileUsed string `yaml:"-"`
}
// Load will read the update check settings from the user's disk and then deserialize it into the current instance.
func (upd *UpdateCheck) Load() error {
path := filepath.Join(SettingsPath(), updateCheckFilename())
if err := ensureSettingsFileExists(path); err != nil {
return err
}
upd.FileUsed = path
content, err := ioutil.ReadFile(path) // #nosec
if err != nil {
return err
}
err = yaml.Unmarshal(content, &upd)
return err
}
// WriteToDisk will write the last update check to disk by serializing the YAML
func (upd *UpdateCheck) WriteToDisk() error {
enc, err := yaml.Marshal(&upd)
if err != nil {
return err
}
err = ioutil.WriteFile(upd.FileUsed, enc, 0600)
return err
}
// Load will read the config from the user's disk and then evaluate possible configuration from the environment.
func (cfg *Config) Load() error {
if err := cfg.LoadFromDisk(); err != nil {
return err
}
cfg.LoadFromEnv("circleci_cli")
return nil
}
// LoadFromDisk is used to read config from the user's disk and deserialize the YAML into our runtime config.
func (cfg *Config) LoadFromDisk() error {
path := filepath.Join(SettingsPath(), configFilename())
if err := ensureSettingsFileExists(path); err != nil {
return err
}
cfg.FileUsed = path
content, err := ioutil.ReadFile(path) // #nosec
if err != nil {
return err
}
err = yaml.Unmarshal(content, &cfg)
if err != nil {
return nil
}
return cfg.WithHTTPClient()
}
// WriteToDisk will write the runtime config instance to disk by serializing the YAML
func (cfg *Config) WriteToDisk() error {
enc, err := yaml.Marshal(&cfg)
if err != nil {
return err
}
err = ioutil.WriteFile(cfg.FileUsed, enc, 0600)
return err
}
// LoadFromEnv will read from environment variables of the given prefix for host, endpoint, and token specifically.
func (cfg *Config) LoadFromEnv(prefix string) {
if host := ReadFromEnv(prefix, "host"); host != "" {
cfg.Host = host
}
if restEndpoint := ReadFromEnv(prefix, "rest_endpoint"); restEndpoint != "" {
cfg.RestEndpoint = restEndpoint
}
if endpoint := ReadFromEnv(prefix, "endpoint"); endpoint != "" {
cfg.Endpoint = endpoint
}
if token := ReadFromEnv(prefix, "token"); token != "" {
cfg.Token = token
}
}
// ReadFromEnv takes a prefix and field to search the environment for after capitalizing and joining them with an underscore.
func ReadFromEnv(prefix, field string) string {
name := strings.Join([]string{prefix, field}, "_")
return os.Getenv(strings.ToUpper(name))
}
// updateCheckFilename returns the name of the cli update checks file
func updateCheckFilename() string {
return "update_check.yml"
}
// configFilename returns the name of the cli config file
func configFilename() string {
// TODO: Make this configurable
return "cli.yml"
}
// settingsPath returns the path of the CLI settings directory
func SettingsPath() string {
// TODO: Make this configurable
home, _ := os.UserHomeDir()
return path.Join(home, ".circleci")
}
// ensureSettingsFileExists does just that.
func ensureSettingsFileExists(path string) error {
// TODO - handle invalid YAML config files.
_, err := os.Stat(path)
if err == nil {
return nil
}
if !os.IsNotExist(err) {
// Filesystem error
return err
}
dir := filepath.Dir(path)
// Create folder
if err = os.MkdirAll(dir, 0700); err != nil {
return err
}
_, err = os.Create(path)
if err != nil {
return err
}
err = os.Chmod(path, 0600)
return err
}
func (cfg *Config) WithHTTPClient() error {
tlsConfig := &tls.Config{
InsecureSkipVerify: cfg.TLSInsecure,
}
if cfg.TLSCert != "" {
err := validateTLSCertPath(cfg.TLSCert)
if err != nil {
return fmt.Errorf("invalid tls cert provided: %s", err.Error())
}
pemData, err := ioutil.ReadFile(cfg.TLSCert)
if err != nil {
return fmt.Errorf("unable to read tls cert: %s", err.Error())
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(pemData) {
return errors.New("unable to parse certificates")
}
tlsConfig.RootCAs = pool
}
cfg.HTTPClient = &http.Client{
Timeout: 60 * time.Second,
Transport: &http.Transport{
ExpectContinueTimeout: 1 * time.Second,
IdleConnTimeout: 90 * time.Second,
MaxIdleConns: 10,
TLSHandshakeTimeout: 10 * time.Second,
TLSClientConfig: tlsConfig,
},
}
return nil
}
func validateTLSCertPath(path string) error {
info, err := os.Stat(path)
if err != nil {
return err
}
if info.IsDir() {
return errors.New("provided TLSCert path must be a file")
}
if runtime.GOOS == "windows" {
return nil
}
for path != "." && path != "/" {
info, err := os.Stat(path)
if err != nil {
return err
}
if isWorldWritable(info) {
return fmt.Errorf("%s cannot be world-writable", path)
}
path = filepath.Dir(path)
}
return nil
}
func isWorldWritable(info os.FileInfo) bool {
mode := fmt.Sprint(info.Mode())
// Parse the system level permissions from the octal mode.
// Example: '-rwxrwx-w-' -> '-w-'
sysPerms := mode[len(mode)-3:]
return strings.Contains(sysPerms, "w")
}