Repository navigation
Expand file tree
/
Copy pathconfig_test.go
More file actions
370 lines (337 loc) · 10.9 KB
/
Copy pathconfig_test.go
File metadata and controls
370 lines (337 loc) · 10.9 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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package main
import (
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"time"
)
// The order is --key, then the environment, then the active session, then
// nothing - and "nothing" is a working state rather than an error, because a
// lookup needs no key.
func TestResolveKeyPrecedence(t *testing.T) {
cfg := NewConfig()
cfg.Sessions["work"] = &Session{Key: "from-session"}
cfg.Active = "work"
reset := func() {
fKey, fSession = "", ""
os.Unsetenv("INTERNETDATA_API_KEY")
os.Unsetenv("INTERNETDATA_SESSION")
}
t.Cleanup(reset)
reset()
if key, src := cfg.ResolveKey(); key != "from-session" || src != "session work" {
t.Errorf("stored session: got %q from %q", key, src)
}
reset()
t.Setenv("INTERNETDATA_API_KEY", "from-env")
if key, src := cfg.ResolveKey(); key != "from-env" || src != "INTERNETDATA_API_KEY" {
t.Errorf("env beats session: got %q from %q", key, src)
}
fKey = "from-flag"
if key, src := cfg.ResolveKey(); key != "from-flag" || src != "--key" {
t.Errorf("flag beats env: got %q from %q", key, src)
}
reset()
empty := NewConfig()
if key, src := empty.ResolveKey(); key != "" || src != "unauthenticated" {
t.Errorf("no credential: got %q from %q", key, src)
}
}
// A key given for one run arrives the way a shell hands it over, and the CR a
// key file saved on Windows leaves on the end must not reach the header.
func TestResolveKeyTrimsWhatARunIsGiven(t *testing.T) {
t.Cleanup(func() { fKey = "" })
cfg := NewConfig()
fKey = ""
t.Setenv("INTERNETDATA_API_KEY", "k_from_env\r\n")
if key, _ := cfg.ResolveKey(); key != "k_from_env" {
t.Errorf("from the environment: got %q", key)
}
fKey = " k_from_flag\r"
if key, _ := cfg.ResolveKey(); key != "k_from_flag" {
t.Errorf("from --key: got %q", key)
}
// Whitespace alone is no key, so the next source answers.
fKey = " "
if key, src := cfg.ResolveKey(); key != "k_from_env" || src != "INTERNETDATA_API_KEY" {
t.Errorf("a blank --key: got %q from %q", key, src)
}
}
func TestResolveSessionPrecedence(t *testing.T) {
cfg := NewConfig()
cfg.Sessions["a"] = &Session{Key: "ka"}
cfg.Sessions["b"] = &Session{Key: "kb"}
cfg.Active = "a"
t.Cleanup(func() { fSession = "" })
fSession = ""
if got := cfg.ActiveSessionName(); got != "a" {
t.Errorf("config: got %q", got)
}
t.Setenv("INTERNETDATA_SESSION", "b")
if got := cfg.ActiveSessionName(); got != "b" {
t.Errorf("env beats config: got %q", got)
}
fSession = "a"
if got := cfg.ActiveSessionName(); got != "a" {
t.Errorf("flag beats env: got %q", got)
}
}
// The base URL comes from the SESSION, which is what lets a credential for
// another deployment sit beside a production one without a flag on every
// command.
func TestResolveBaseURL(t *testing.T) {
cfg := NewConfig()
cfg.Sessions["alt"] = &Session{Key: "k", BaseURL: "https://api.example.com"}
cfg.Active = "alt"
t.Cleanup(func() { fBaseURL = "" })
if got := cfg.ResolveBaseURL(); got != "https://api.example.com" {
t.Errorf("got %q", got)
}
fBaseURL = "https://elsewhere.example"
if got := cfg.ResolveBaseURL(); got != "https://elsewhere.example" {
t.Errorf("flag should win: got %q", got)
}
}
// A config file is written 0600 and its directory 0700, because it holds API
// keys in plain text.
func TestConfigFilePermissions(t *testing.T) {
dir := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", dir)
cfg := NewConfig()
cfg.Sessions["a"] = &Session{Key: "secret", Created: time.Now()}
if err := SaveConfig(cfg); err != nil {
t.Fatal(err)
}
path, err := ConfigPath()
if err != nil {
t.Fatal(err)
}
st, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if perm := st.Mode().Perm(); perm != 0o600 {
t.Errorf("config file is %o, want 600", perm)
}
confDir, _ := ConfigDir()
dst, err := os.Stat(confDir)
if err != nil {
t.Fatal(err)
}
if perm := dst.Mode().Perm(); perm != 0o700 {
t.Errorf("config dir is %o, want 700", perm)
}
}
// A config file that cannot be parsed must NOT be replaced with a default one:
// it holds credentials that cannot be recovered from anywhere else.
func TestLoadConfigRefusesToClobberGarbage(t *testing.T) {
dir := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", dir)
path, err := ConfigPath()
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte("{not json"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := LoadConfig(); err == nil {
t.Fatal("expected an error rather than a silent overwrite")
}
body, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if string(body) != "{not json" {
t.Errorf("the file was rewritten: %q", body)
}
}
// A save after a load that failed must not write over the file the load could
// not read: init carries on with an empty config, and the first login or
// setting saved from it would otherwise replace every stored key with its own.
func TestSaveConfigKeepsAFileItCannotRead(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
path, err := ConfigPath()
if err != nil {
t.Fatal(err)
}
const stored = `{"sessions": {"work": {"key": "k_work"},}}`
if err := os.WriteFile(path, []byte(stored), 0o600); err != nil {
t.Fatal(err)
}
cfg := NewConfig()
cfg.Sessions["other"] = &Session{Key: "k_other"}
if err := SaveConfig(cfg); err == nil {
t.Fatal("saved over a config that does not parse")
}
if body, _ := os.ReadFile(path); string(body) != stored {
t.Errorf("the file was rewritten: %q", body)
}
}
// A config another account can open is refused, as ssh refuses a private key:
// a session's base URL is where every key on this machine is sent, so whoever
// can edit the file can collect them, and whoever can write its directory can
// replace it.
func TestLoadConfigRefusesWhatOthersCanOpen(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Windows keeps no permission bits to read")
}
for _, tt := range []struct {
name string
file, dir os.FileMode
wantRefusedOn string
}{
{"a file others can read", 0o644, 0o700, "chmod 600"},
{"a file others can write", 0o622, 0o700, "chmod 600"},
{"a directory others can write", 0o600, 0o777, "chmod 700"},
{"a directory its group can write", 0o600, 0o770, "chmod 700"},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := SaveConfig(NewConfig()); err != nil {
t.Fatal(err)
}
path, _ := ConfigPath()
if err := os.Chmod(path, tt.file); err != nil {
t.Fatal(err)
}
if err := os.Chmod(filepath.Dir(path), tt.dir); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chmod(filepath.Dir(path), 0o700) })
if _, err := LoadConfig(); err == nil || !strings.Contains(err.Error(), tt.wantRefusedOn) {
t.Errorf("LoadConfig() = %v, want a refusal naming %q", err, tt.wantRefusedOn)
}
if err := SaveConfig(NewConfig()); err == nil {
t.Error("SaveConfig wrote into a config it refuses to read")
}
})
}
}
// The fingerprint is what partitions the cache, so its width is load-bearing:
// two keys whose fingerprints collide share a bucket, and one is then served
// the other's answer under a plan that need not carry the same fields.
// cache_test.go pins only that two sampled keys differ, which a narrower
// truncation would still satisfy.
func TestKeyFingerprint(t *testing.T) {
const width = 12
const key = "mk_1234567890abcd"
if got := keyFingerprint(""); got != "none" {
t.Errorf("keyFingerprint(%q) = %q, want %q", "", got, "none")
}
fp := keyFingerprint(key)
if len(fp) != width {
t.Errorf("fingerprint %q is %d chars, want %d: narrower collides sooner", fp, len(fp), width)
}
if strings.Trim(fp, "0123456789abcdef") != "" {
t.Errorf("fingerprint %q is not lowercase hex", fp)
}
if keyFingerprint(key) != fp {
t.Error("the fingerprint is not stable for one key, so the cache never hits")
}
if strings.Contains(fp, key) {
t.Errorf("the fingerprint leaks the key: %q", fp)
}
}
func TestMaskKey(t *testing.T) {
cases := map[string]string{
"": "",
"abc": "***",
"abcdefgh": "********",
"mk_1234567890abcd": "mk_1*********abcd",
}
for in, want := range cases {
if got := maskKey(in); got != want {
t.Errorf("maskKey(%q) = %q, want %q", in, got, want)
}
}
// Whatever it shows, it must never be the key itself.
if maskKey("mk_1234567890abcd") == "mk_1234567890abcd" {
t.Error("the key leaked through the mask")
}
}
// LAST USED in `session list` is only as good as the stamp NewClient leaves: a
// key given for one run is not the session's use, the stamp goes into the file
// as it is now rather than over whatever another terminal saved since this
// process read it, and it is written at most once a minute.
func TestNewClientStampsTheSessionItUses(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("INTERNETDATA_API_KEY", "")
t.Setenv("INTERNETDATA_SESSION", "")
savedConfig, savedKey, savedSession := gConfig, fKey, fSession
t.Cleanup(func() { gConfig, fKey, fSession = savedConfig, savedKey, savedSession })
fSession = ""
gConfig = NewConfig()
gConfig.CacheEnabled = false
gConfig.Sessions["work"] = &Session{Key: "key-work", Created: time.Now()}
gConfig.Active = "work"
if err := SaveConfig(gConfig); err != nil {
t.Fatal(err)
}
use := func(key string) {
t.Helper()
fKey = key
client, err := NewClient()
if err != nil {
t.Fatal(err)
}
client.Close()
}
load := func() Config {
t.Helper()
cfg, err := LoadConfig()
if err != nil {
t.Fatal(err)
}
return cfg
}
use("key-other")
if got := load().Sessions["work"].LastUsed; !got.IsZero() {
t.Errorf("a key given for one run was recorded as the session's use: %v", got)
}
// Another terminal stores a session after this process read the file.
onDisk := load()
onDisk.Sessions["acme"] = &Session{Key: "key-acme", Created: time.Now()}
if err := SaveConfig(onDisk); err != nil {
t.Fatal(err)
}
use("")
after := load()
if got := after.Sessions["work"].LastUsed; time.Since(got) > time.Minute {
t.Errorf("using the session's own key did not stamp it: %v", got)
}
if after.Sessions["acme"] == nil {
t.Error("the stamp wrote this process's stale copy over a session stored since")
}
// A second use inside the minute leaves the file alone.
use("")
if got := load().Sessions["work"].LastUsed; !got.Equal(after.Sessions["work"].LastUsed) {
t.Errorf("a second use inside the minute rewrote the stamp: %v, then %v",
after.Sessions["work"].LastUsed, got)
}
}
// Two saves at once must leave one of them, never a mix: with a single shared
// temp file, one save renames the other's half-written copy into place, or
// finds it already gone.
func TestSaveConfigConcurrently(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := NewConfig()
cfg.Sessions["work"] = &Session{Key: "key-work"}
var wg sync.WaitGroup
errs := make(chan error, 16)
for range 16 {
wg.Go(func() { errs <- SaveConfig(cfg) })
}
wg.Wait()
close(errs)
for err := range errs {
if err != nil {
t.Fatal(err)
}
}
if got, err := LoadConfig(); err != nil || got.Sessions["work"] == nil {
t.Fatalf("after concurrent saves: sessions %v, err %v", got.Sessions, err)
}
}