Repository navigation
Expand file tree
/
Copy pathconfig.go
More file actions
349 lines (317 loc) · 10.3 KB
/
Copy pathconfig.go
File metadata and controls
349 lines (317 loc) · 10.3 KB
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
)
// gConfig is the loaded config, read once at startup by init.
var gConfig Config
// Config is everything the CLI remembers between runs.
//
// Sessions are named credentials rather than one token, so a machine that talks
// to more than one organization, or to more than one deployment of the API,
// does not have to re-authenticate to switch. Exactly one is active at a time.
type Config struct {
// Version of this file's shape, so a future change can migrate rather than
// guess.
Version int `json:"version"`
// Active names the session in use. Empty means unauthenticated, which is a
// working state: the API answers a lookup with no key at all.
Active string `json:"active"`
// Sessions are the stored credentials, keyed by name.
Sessions map[string]*Session `json:"sessions"`
// CacheEnabled controls the on-disk lookup cache.
CacheEnabled bool `json:"cache_enabled"`
// CacheTTL is how long a cached answer stays good, as a duration string.
CacheTTL string `json:"cache_ttl"`
// Format is the default output format for a single lookup.
Format string `json:"format"`
// Concurrency and Retries default what the client is built with.
Concurrency int `json:"concurrency"`
Retries int `json:"retries"`
}
// Session is one stored credential.
type Session struct {
// Key is the API key. Stored in plain text in a 0600 file, the same way
// every CLI credential on a developer machine is; the alternative is a
// keyring this would have to carry per platform.
Key string `json:"key"`
// BaseURL overrides the API this session talks to, which is what lets a
// session on another deployment sit beside a production one.
BaseURL string `json:"base_url,omitempty"`
Created time.Time `json:"created"`
LastUsed time.Time `json:"last_used,omitempty"`
// RefreshToken is present only for a session created by `login` in a
// browser. It is NOT used for lookups - the API key above is - and exists
// so `logout` can revoke server-side instead of only deleting this file,
// which is the difference between signing out and forgetting.
RefreshToken string `json:"refresh_token,omitempty"`
// APIKeyID names which key this session holds, so the console's key list
// and this machine can be matched up without ever comparing secrets.
APIKeyID string `json:"apikey_id,omitempty"`
}
const (
configVersion = 1
defaultSession = "default"
defaultCacheTTL = "1h"
defaultFormat = "pretty"
defaultConcurrency = 8
defaultRetries = 2
)
// NewConfig is the config a first run gets.
func NewConfig() Config {
return Config{
Version: configVersion,
Sessions: map[string]*Session{},
CacheEnabled: true,
CacheTTL: defaultCacheTTL,
Format: defaultFormat,
Concurrency: defaultConcurrency,
Retries: defaultRetries,
}
}
// ConfigDir is where the config and cache live, created if missing.
//
// 0700 because the config file holds API keys; a 0755 directory would leave
// them listable by every other account on a shared machine.
func ConfigDir() (string, error) {
base, err := os.UserConfigDir()
if err != nil {
return "", err
}
dir := filepath.Join(base, "internetdata")
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err
}
return dir, nil
}
// ConfigPath is the config file.
func ConfigPath() (string, error) {
dir, err := ConfigDir()
if err != nil {
return "", err
}
return filepath.Join(dir, "config.json"), nil
}
// LoadConfig reads the config, creating a default one if there is none.
//
// A file that cannot be parsed is NOT silently replaced: it holds credentials
// the user cannot get back, and overwriting it to recover from a stray edit
// would lose them. The error names the path so it can be fixed by hand.
func LoadConfig() (Config, error) {
path, err := ConfigPath()
if err != nil {
return Config{}, err
}
cfg, err := readConfig(path)
if os.IsNotExist(err) {
cfg = NewConfig()
return cfg, SaveConfig(cfg)
}
return cfg, err
}
// readConfig parses the config file at path.
func readConfig(path string) (Config, error) {
if err := private(path); err != nil {
return Config{}, err
}
data, err := os.ReadFile(path)
if err != nil {
return Config{}, err
}
cfg := NewConfig()
if err := json.Unmarshal(data, &cfg); err != nil {
return Config{}, fmt.Errorf("%s is not valid JSON: %w", path, err)
}
if cfg.Sessions == nil {
cfg.Sessions = map[string]*Session{}
}
return cfg, nil
}
// private refuses a config file other accounts can open, or one in a directory
// they can write, the way ssh refuses a private key: a session's base URL is
// where every key this machine uses is sent, so whoever can edit the file can
// collect them. This CLI writes 0600 inside 0700, so a wider mode was set from
// outside. Windows keeps no such bits.
func private(path string) error {
st, err := os.Stat(path)
if err != nil || runtime.GOOS == "windows" {
return err
}
if perm := st.Mode().Perm(); perm&0o077 != 0 {
return fmt.Errorf("%s is open to other accounts (mode %04o); run `chmod 600 %s`", path, perm, path)
}
dir := filepath.Dir(path)
dst, err := os.Stat(dir)
if err != nil {
return err
}
if perm := dst.Mode().Perm(); perm&0o022 != 0 {
return fmt.Errorf("%s is writable by other accounts (mode %04o); run `chmod 700 %s`", dir, perm, dir)
}
return nil
}
// SaveConfig writes the config back, readable only by its owner.
//
// It never replaces a file LoadConfig could not read: init carries on without
// one, and the next login or setting saved over it would lose every key in it.
func SaveConfig(cfg Config) error {
path, err := ConfigPath()
if err != nil {
return err
}
if _, err := readConfig(path); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("nothing was saved: %w", err)
}
cfg.Version = configVersion
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return err
}
data = append(data, '\n')
// Written to a file of its own and renamed, so an interrupted write cannot
// leave a truncated file - which here means losing every stored key - and
// two processes saving at once cannot interleave into one. CreateTemp makes
// it 0600.
tmp, err := os.CreateTemp(filepath.Dir(path), "config-*.tmp")
if err != nil {
return err
}
_, err = tmp.Write(data)
if closeErr := tmp.Close(); err == nil {
err = closeErr
}
if err == nil {
err = os.Rename(tmp.Name(), path)
}
if err != nil {
_ = os.Remove(tmp.Name())
}
return err
}
// SessionNames are the stored sessions, sorted.
func (c Config) SessionNames() []string {
names := make([]string, 0, len(c.Sessions))
for name := range c.Sessions {
names = append(names, name)
}
sort.Strings(names)
return names
}
// ActiveSession is the session in use, or nil when running unauthenticated.
//
// Precedence is --session, then INTERNETDATA_SESSION, then whatever the config
// says is active. The flag wins so a one-off command can borrow another
// credential without changing anything on disk.
func (c Config) ActiveSession() *Session {
name := c.ActiveSessionName()
if name == "" {
return nil
}
return c.Sessions[name]
}
// ActiveSessionName resolves which session name is in play.
func (c Config) ActiveSessionName() string {
if fSession != "" {
return fSession
}
if env := os.Getenv("INTERNETDATA_SESSION"); env != "" {
return env
}
return c.Active
}
// ResolveKey is the API key to present, and where it came from.
//
// The order is deliberate: an explicit flag beats the environment, which beats
// stored state, and no key at all is a valid answer rather than an error - a
// lookup needs none. A command that genuinely requires one says so itself,
// with a message naming how to get one.
//
// A key given for one run is trimmed, as login trims what it stores: it goes
// out as a header value, and the CR a key file saved on Windows leaves behind
// fails as a network error, retried, rather than as a bad key.
func (c Config) ResolveKey() (key string, source string) {
if key := strings.TrimSpace(fKey); key != "" {
return key, "--key"
}
if key := strings.TrimSpace(os.Getenv("INTERNETDATA_API_KEY")); key != "" {
return key, "INTERNETDATA_API_KEY"
}
if s := c.ActiveSession(); s != nil && s.Key != "" {
return s.Key, "session " + c.ActiveSessionName()
}
return "", "unauthenticated"
}
// ResolveBaseURL is the API to talk to. An empty string means the SDK default.
func (c Config) ResolveBaseURL() string {
if fBaseURL != "" {
return fBaseURL
}
if env := os.Getenv("INTERNETDATA_BASE_URL"); env != "" {
return env
}
if s := c.ActiveSession(); s != nil {
return s.BaseURL
}
return ""
}
// touchSession records that the active session's key is in use, for the LAST
// USED column of `session list`. Best effort and at most once a minute, the
// resolution `since` prints: it must never fail a command, nor rewrite the
// credential file on every lookup of a script. Both are judged by the file as
// it is now rather than by gConfig, so a session another terminal stored since
// this process started survives, and parallel runs stop at the first stamp.
func touchSession(key string) {
if key == "" {
return
}
cfg, err := LoadConfig()
if err != nil {
return
}
s := cfg.Sessions[gConfig.ActiveSessionName()]
if s == nil || s.Key != key || time.Since(s.LastUsed) < time.Minute {
return
}
s.LastUsed = time.Now()
_ = SaveConfig(cfg)
}
// keyFingerprint identifies a key without storing or showing it.
//
// Used to scope the cache and to show which credential is in play. Truncated
// because it is an identifier, not a digest anyone verifies.
func keyFingerprint(key string) string {
if key == "" {
return "none"
}
sum := sha256.Sum256([]byte(key))
return hex.EncodeToString(sum[:])[:12]
}
// maskKey shows enough of a key to recognize it and not enough to use it.
func maskKey(key string) string {
if key == "" {
return ""
}
if len(key) <= 8 {
return strings.Repeat("*", len(key))
}
return key[:4] + strings.Repeat("*", len(key)-8) + key[len(key)-4:]
}
// cacheTTL is the configured TTL, falling back to the default when the stored
// value is unparseable rather than failing every lookup over it.
func (c Config) cacheTTL() time.Duration {
if c.CacheTTL != "" {
if d, err := time.ParseDuration(c.CacheTTL); err == nil && d > 0 {
return d
}
}
d, _ := time.ParseDuration(defaultCacheTTL)
return d
}