forked from notaryproject/notary
/
main_test.go
645 lines (561 loc) · 22.9 KB
/
main_test.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
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
package main
import (
"bytes"
"crypto/tls"
"fmt"
"io/ioutil"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/docker/go-connections/tlsconfig"
"github.com/stretchr/testify/require"
"github.com/theupdateframework/notary"
"github.com/theupdateframework/notary/passphrase"
"github.com/theupdateframework/notary/server/storage"
"github.com/theupdateframework/notary/tuf/data"
)
// the default location for the config file is in ~/.notary/config.json - even if it doesn't exist.
func TestNotaryConfigFileDefault(t *testing.T) {
commander := ¬aryCommander{
getRetriever: func() notary.PassRetriever { return passphrase.ConstantRetriever("pass") },
}
config, err := commander.parseConfig()
require.NoError(t, err)
configFileUsed := config.ConfigFileUsed()
require.True(t, strings.HasSuffix(configFileUsed,
filepath.Join(".notary", "config.json")), "Unknown config file: %s", configFileUsed)
}
// the default server address is notary-server
func TestRemoteServerDefault(t *testing.T) {
tempDir := tempDirWithConfig(t, "{}")
defer os.RemoveAll(tempDir)
configFile := filepath.Join(tempDir, "config.json")
commander := ¬aryCommander{
getRetriever: func() notary.PassRetriever { return passphrase.ConstantRetriever("pass") },
}
// set a blank config file, so it doesn't check ~/.notary/config.json by default
// and execute a random command so that the flags are parsed
cmd := commander.GetCommand()
cmd.SetArgs([]string{"-c", configFile, "list"})
cmd.SetOutput(new(bytes.Buffer)) // eat the output
cmd.Execute()
config, err := commander.parseConfig()
require.NoError(t, err)
require.Equal(t, "https://notary-server:4443", getRemoteTrustServer(config))
}
// providing a config file uses the config file's server url instead
func TestRemoteServerUsesConfigFile(t *testing.T) {
tempDir := tempDirWithConfig(t, `{"remote_server": {"url": "https://myserver"}}`)
defer os.RemoveAll(tempDir)
configFile := filepath.Join(tempDir, "config.json")
commander := ¬aryCommander{
getRetriever: func() notary.PassRetriever { return passphrase.ConstantRetriever("pass") },
}
// set a config file, so it doesn't check ~/.notary/config.json by default,
// and execute a random command so that the flags are parsed
cmd := commander.GetCommand()
cmd.SetArgs([]string{"-c", configFile, "list"})
cmd.SetOutput(new(bytes.Buffer)) // eat the output
cmd.Execute()
config, err := commander.parseConfig()
require.NoError(t, err)
require.Equal(t, "https://myserver", getRemoteTrustServer(config))
}
// a command line flag overrides the config file's server url
func TestRemoteServerCommandLineFlagOverridesConfig(t *testing.T) {
tempDir := tempDirWithConfig(t, `{"remote_server": {"url": "https://myserver"}}`)
defer os.RemoveAll(tempDir)
configFile := filepath.Join(tempDir, "config.json")
commander := ¬aryCommander{
getRetriever: func() notary.PassRetriever { return passphrase.ConstantRetriever("pass") },
}
// set a config file, so it doesn't check ~/.notary/config.json by default,
// and execute a random command so that the flags are parsed
cmd := commander.GetCommand()
cmd.SetArgs([]string{"-c", configFile, "-s", "http://overridden", "list"})
cmd.SetOutput(new(bytes.Buffer)) // eat the output
cmd.Execute()
config, err := commander.parseConfig()
require.NoError(t, err)
require.Equal(t, "http://overridden", getRemoteTrustServer(config))
}
// invalid commands for `notary addhash`
func TestInvalidAddHashCommands(t *testing.T) {
tempDir := tempDirWithConfig(t, `{"remote_server": {"url": "https://myserver"}}`)
defer os.RemoveAll(tempDir)
configFile := filepath.Join(tempDir, "config.json")
b := new(bytes.Buffer)
cmd := NewNotaryCommand()
cmd.SetOutput(b)
// No hashes given
cmd.SetArgs(append([]string{"-c", configFile, "-d", tempDir}, "addhash", "gun", "test", "10"))
err := cmd.Execute()
require.Error(t, err)
require.Contains(t, err.Error(), "Must specify a GUN, target, byte size of target data, and at least one hash")
// Invalid byte size given
cmd = NewNotaryCommand()
cmd.SetArgs(append([]string{"-c", configFile, "-d", tempDir}, "addhash", "gun", "test", "sizeNotAnInt", "--sha256", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"))
err = cmd.Execute()
require.Error(t, err)
// Invalid sha256 size given
cmd = NewNotaryCommand()
cmd.SetArgs(append([]string{"-c", configFile, "-d", tempDir}, "addhash", "gun", "test", "1", "--sha256", "a"))
err = cmd.Execute()
require.Error(t, err)
require.Contains(t, err.Error(), "invalid sha256 hex contents provided")
// Invalid sha256 hex given
cmd = NewNotaryCommand()
cmd.SetArgs(append([]string{"-c", configFile, "-d", tempDir}, "addhash", "gun", "test", "1", "--sha256", "***aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa***"))
err = cmd.Execute()
require.Error(t, err)
// Invalid sha512 size given
cmd = NewNotaryCommand()
cmd.SetArgs(append([]string{"-c", configFile, "-d", tempDir}, "addhash", "gun", "test", "1", "--sha512", "a"))
err = cmd.Execute()
require.Error(t, err)
require.Contains(t, err.Error(), "invalid sha512 hex contents provided")
// Invalid sha512 hex given
cmd = NewNotaryCommand()
cmd.SetArgs(append([]string{"-c", configFile, "-d", tempDir}, "addhash", "gun", "test", "1", "--sha512", "***aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa******aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa***"))
err = cmd.Execute()
require.Error(t, err)
}
var exampleValidCommands = []string{
"init repo",
"list repo",
"status repo",
"reset repo --all",
"publish repo",
"add repo v1 somefile",
"addhash repo targetv1 --sha256 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 10",
"verify repo v1",
"key list",
"key rotate repo snapshot",
"key generate ecdsa",
"key remove e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"key passwd e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"key import backup.pem",
"delegation list repo",
"delegation add repo targets/releases path/to/pem/file.pem",
"delegation remove repo targets/releases",
"witness gun targets/releases",
"delete repo",
}
// config parsing bugs are propagated in all commands
func TestConfigParsingErrorsPropagatedByCommands(t *testing.T) {
tempdir, err := ioutil.TempDir("", "empty-dir")
require.NoError(t, err)
defer os.RemoveAll(tempdir)
for _, args := range exampleValidCommands {
b := new(bytes.Buffer)
cmd := NewNotaryCommand()
cmd.SetOutput(b)
cmd.SetArgs(append(
[]string{"-c", filepath.Join(tempdir, "idonotexist.json"), "-d", tempdir},
strings.Fields(args)...))
err = cmd.Execute()
require.Error(t, err, "expected error when running `notary %s`", args)
require.Contains(t, err.Error(), "error opening config file", "running `notary %s`", args)
require.NotContains(t, b.String(), "Usage:")
}
}
// insufficient arguments produce an error before any parsing of configs happens
func TestInsufficientArgumentsReturnsErrorAndPrintsUsage(t *testing.T) {
tempdir, err := ioutil.TempDir("", "empty-dir")
require.NoError(t, err)
defer os.RemoveAll(tempdir)
for _, args := range exampleValidCommands {
b := new(bytes.Buffer)
cmd := NewNotaryCommand()
cmd.SetOutput(b)
arglist := strings.Fields(args)
if args == "key list" || args == "key generate ecdsa" {
// in these case, "key" or "key generate" are valid commands, so add an arg to them instead
arglist = append(arglist, "extraArg")
} else {
arglist = arglist[:len(arglist)-1]
}
invalid := strings.Join(arglist, " ")
cmd.SetArgs(append(
[]string{"-c", filepath.Join(tempdir, "idonotexist.json"), "-d", tempdir}, arglist...))
err = cmd.Execute()
require.NotContains(t, err.Error(), "error opening config file", "running `notary %s`", invalid)
// it's a usage error, so the usage is printed
require.Contains(t, b.String(), "Usage:", "expected usage when running `notary %s`", invalid)
}
}
// The bare notary command and bare subcommands all print out usage
func TestBareCommandPrintsUsageAndNoError(t *testing.T) {
tempdir, err := ioutil.TempDir("", "empty-dir")
require.NoError(t, err)
defer os.RemoveAll(tempdir)
// just the notary command
b := new(bytes.Buffer)
cmd := NewNotaryCommand()
cmd.SetOutput(b)
cmd.SetArgs([]string{"-c", filepath.Join(tempdir, "idonotexist.json")})
require.NoError(t, cmd.Execute(), "Expected no error from a help request")
// usage is printed
require.Contains(t, b.String(), "Usage:", "expected usage when running `notary`")
// notary key and notary delegation
for _, bareCommand := range []string{"key", "delegation"} {
b := new(bytes.Buffer)
cmd := NewNotaryCommand()
cmd.SetOutput(b)
cmd.SetArgs([]string{"-c", filepath.Join(tempdir, "idonotexist.json"), "-d", tempdir, bareCommand})
require.NoError(t, cmd.Execute(), "Expected no error from a help request")
// usage is printed
require.Contains(t, b.String(), "Usage:", "expected usage when running `notary %s`", bareCommand)
}
}
type recordingMetaStore struct {
gotten []string
storage.MemStorage
}
// GetCurrent gets the metadata from the underlying MetaStore, but also records
// that the metadata was requested
func (r *recordingMetaStore) GetCurrent(gun data.GUN, role data.RoleName) (*time.Time, []byte, error) {
r.gotten = append(r.gotten, fmt.Sprintf("%s.%s", gun.String(), role.String()))
return r.MemStorage.GetCurrent(gun, role)
}
// GetChecksum gets the metadata from the underlying MetaStore, but also records
// that the metadata was requested
func (r *recordingMetaStore) GetChecksum(gun data.GUN, role data.RoleName, checksum string) (*time.Time, []byte, error) {
r.gotten = append(r.gotten, fmt.Sprintf("%s.%s", gun.String(), role.String()))
return r.MemStorage.GetChecksum(gun, role, checksum)
}
// the config can provide all the TLS information necessary - the root ca file,
// the tls client files - they are all relative to the directory of the config
// file, and not the cwd
func TestConfigFileTLSCannotBeRelativeToCWD(t *testing.T) {
// Set up server that with a self signed cert
var err error
// add a handler for getting the root
m := &recordingMetaStore{MemStorage: *storage.NewMemStorage()}
s := httptest.NewUnstartedServer(setupServerHandler(m))
s.TLS, err = tlsconfig.Server(tlsconfig.Options{
CertFile: "../../fixtures/notary-server.crt",
KeyFile: "../../fixtures/notary-server.key",
CAFile: "../../fixtures/root-ca.crt",
ClientAuth: tls.RequireAndVerifyClientCert,
ExclusiveRootPools: true,
})
require.NoError(t, err)
s.StartTLS()
defer s.Close()
// test that a config file with certs that are relative to the cwd fail
tempDir := tempDirWithConfig(t, fmt.Sprintf(`{
"remote_server": {
"url": "%s",
"root_ca": "../../fixtures/root-ca.crt",
"tls_client_cert": "../../fixtures/notary-server.crt",
"tls_client_key": "../../fixtures/notary-server.key"
}
}`, s.URL))
defer os.RemoveAll(tempDir)
configFile := filepath.Join(tempDir, "config.json")
// set a config file, so it doesn't check ~/.notary/config.json by default,
// and execute a random command so that the flags are parsed
cmd := NewNotaryCommand()
cmd.SetArgs([]string{"-c", configFile, "-d", tempDir, "list", "repo"})
cmd.SetOutput(new(bytes.Buffer)) // eat the output
err = cmd.Execute()
require.Error(t, err, "expected a failure due to TLS")
require.Contains(t, err.Error(), "TLS", "should have been a TLS error")
// validate that we failed to connect and attempt any downloads at all
require.Len(t, m.gotten, 0)
}
// the config can provide all the TLS information necessary - the root ca file,
// the tls client files - they are all relative to the directory of the config
// file, and not the cwd, or absolute paths
func TestConfigFileTLSCanBeRelativeToConfigOrAbsolute(t *testing.T) {
// Set up server that with a self signed cert
var err error
// add a handler for getting the root
m := &recordingMetaStore{MemStorage: *storage.NewMemStorage()}
s := httptest.NewUnstartedServer(setupServerHandler(m))
s.TLS, err = tlsconfig.Server(tlsconfig.Options{
CertFile: "../../fixtures/notary-server.crt",
KeyFile: "../../fixtures/notary-server.key",
CAFile: "../../fixtures/root-ca.crt",
ClientAuth: tls.RequireAndVerifyClientCert,
ExclusiveRootPools: true,
})
require.NoError(t, err)
s.StartTLS()
defer s.Close()
tempDir, err := ioutil.TempDir("", "config-test")
require.NoError(t, err)
defer os.RemoveAll(tempDir)
configFile, err := os.Create(filepath.Join(tempDir, "config.json"))
require.NoError(t, err)
fmt.Fprintf(configFile, `{
"remote_server": {
"url": "%s",
"root_ca": "root-ca.crt",
"tls_client_cert": %s,
"tls_client_key": "notary-server.key"
}
}`, s.URL, strconv.Quote(filepath.Join(tempDir, "notary-server.crt")))
configFile.Close()
// copy the certs to be relative to the config directory
for _, fname := range []string{"notary-server.crt", "notary-server.key", "root-ca.crt"} {
content, err := ioutil.ReadFile(filepath.Join("../../fixtures", fname))
require.NoError(t, err)
require.NoError(t, ioutil.WriteFile(filepath.Join(tempDir, fname), content, 0766))
}
// set a config file, so it doesn't check ~/.notary/config.json by default,
// and execute a random command so that the flags are parsed
cmd := NewNotaryCommand()
cmd.SetArgs([]string{"-c", configFile.Name(), "-d", tempDir, "list", "repo"})
cmd.SetOutput(new(bytes.Buffer)) // eat the output
err = cmd.Execute()
require.Error(t, err, "there was no repository, so list should have failed")
require.NotContains(t, err.Error(), "TLS", "there was no TLS error though!")
// validate that we actually managed to connect and attempted to download the root though
require.Len(t, m.gotten, 1)
require.Equal(t, m.gotten[0], "repo.root")
}
// Whatever TLS config is in the config file can be overridden by the command line
// TLS flags, which are relative to the CWD (not the config) or absolute
func TestConfigFileOverridenByCmdLineFlags(t *testing.T) {
// Set up server that with a self signed cert
var err error
// add a handler for getting the root
m := &recordingMetaStore{MemStorage: *storage.NewMemStorage()}
s := httptest.NewUnstartedServer(setupServerHandler(m))
s.TLS, err = tlsconfig.Server(tlsconfig.Options{
CertFile: "../../fixtures/notary-server.crt",
KeyFile: "../../fixtures/notary-server.key",
CAFile: "../../fixtures/root-ca.crt",
ClientAuth: tls.RequireAndVerifyClientCert,
ExclusiveRootPools: true,
})
require.NoError(t, err)
s.StartTLS()
defer s.Close()
tempDir := tempDirWithConfig(t, fmt.Sprintf(`{
"remote_server": {
"url": "%s",
"root_ca": "nope",
"tls_client_cert": "nope",
"tls_client_key": "nope"
}
}`, s.URL))
defer os.RemoveAll(tempDir)
configFile := filepath.Join(tempDir, "config.json")
// set a config file, so it doesn't check ~/.notary/config.json by default,
// and execute a random command so that the flags are parsed
cwd, err := os.Getwd()
require.NoError(t, err)
cmd := NewNotaryCommand()
cmd.SetArgs([]string{
"-c", configFile, "-d", tempDir, "list", "repo",
"--tlscacert", "../../fixtures/root-ca.crt",
"--tlscert", filepath.Clean(filepath.Join(cwd, "../../fixtures/notary-server.crt")),
"--tlskey", "../../fixtures/notary-server.key"})
cmd.SetOutput(new(bytes.Buffer)) // eat the output
err = cmd.Execute()
require.Error(t, err, "there was no repository, so list should have failed")
require.NotContains(t, err.Error(), "TLS", "there was no TLS error though!")
// validate that we actually managed to connect and attempted to download the root though
require.Len(t, m.gotten, 1)
require.Equal(t, m.gotten[0], "repo.root")
}
// the config can specify trust pinning settings for TOFUs, as well as pinned Certs or CA
func TestConfigFileTrustPinning(t *testing.T) {
var err error
tempDir := tempDirWithConfig(t, `{
"trust_pinning": {
"disable_tofu": false
}
}`)
defer os.RemoveAll(tempDir)
commander := ¬aryCommander{
getRetriever: func() notary.PassRetriever { return passphrase.ConstantRetriever("pass") },
configFile: filepath.Join(tempDir, "config.json"),
}
// Check that tofu was set correctly
config, err := commander.parseConfig()
require.NoError(t, err)
require.Equal(t, false, config.GetBool("trust_pinning.disable_tofu"))
trustPin, err := getTrustPinning(config)
require.NoError(t, err)
require.Equal(t, false, trustPin.DisableTOFU)
tempDir = tempDirWithConfig(t, `{
"remote_server": {
"url": "%s"
},
"trust_pinning": {
"disable_tofu": true
}
}`)
defer os.RemoveAll(tempDir)
commander = ¬aryCommander{
getRetriever: func() notary.PassRetriever { return passphrase.ConstantRetriever("pass") },
configFile: filepath.Join(tempDir, "config.json"),
}
// Check that tofu was correctly disabled
config, err = commander.parseConfig()
require.NoError(t, err)
require.Equal(t, true, config.GetBool("trust_pinning.disable_tofu"))
trustPin, err = getTrustPinning(config)
require.NoError(t, err)
require.Equal(t, true, trustPin.DisableTOFU)
tempDir = tempDirWithConfig(t, fmt.Sprintf(`{
"trust_pinning": {
"certs": {
"repo3": ["%s"]
}
}
}`, strings.Repeat("x", notary.SHA256HexSize)))
defer os.RemoveAll(tempDir)
commander = ¬aryCommander{
getRetriever: func() notary.PassRetriever { return passphrase.ConstantRetriever("pass") },
configFile: filepath.Join(tempDir, "config.json"),
}
config, err = commander.parseConfig()
require.NoError(t, err)
require.Equal(t, []interface{}{strings.Repeat("x", notary.SHA256HexSize)}, config.GetStringMap("trust_pinning.certs")["repo3"])
trustPin, err = getTrustPinning(config)
require.NoError(t, err)
require.Equal(t, strings.Repeat("x", notary.SHA256HexSize), trustPin.Certs["repo3"][0])
// Check that an invalid cert ID pinning format fails
tempDir = tempDirWithConfig(t, fmt.Sprintf(`{
"trust_pinning": {
"certs": {
"repo3": "%s"
}
}
}`, strings.Repeat("x", notary.SHA256HexSize)))
defer os.RemoveAll(tempDir)
commander = ¬aryCommander{
getRetriever: func() notary.PassRetriever { return passphrase.ConstantRetriever("pass") },
configFile: filepath.Join(tempDir, "config.json"),
}
config, err = commander.parseConfig()
require.NoError(t, err)
trustPin, err = getTrustPinning(config)
require.Error(t, err)
tempDir = tempDirWithConfig(t, fmt.Sprintf(`{
"trust_pinning": {
"ca": {
"repo4": "%s"
}
}
}`, "root-ca.crt"))
defer os.RemoveAll(tempDir)
commander = ¬aryCommander{
getRetriever: func() notary.PassRetriever { return passphrase.ConstantRetriever("pass") },
configFile: filepath.Join(tempDir, "config.json"),
}
config, err = commander.parseConfig()
require.NoError(t, err)
require.Equal(t, "root-ca.crt", config.GetStringMap("trust_pinning.ca")["repo4"])
trustPin, err = getTrustPinning(config)
require.NoError(t, err)
require.Equal(t, "root-ca.crt", trustPin.CA["repo4"])
}
// sets the env vars to empty, and returns a function to reset them at the end
func cleanupAndSetEnvVars() func() {
orig := map[string]string{
"NOTARY_ROOT_PASSPHRASE": "",
"NOTARY_TARGETS_PASSPHRASE": "",
"NOTARY_SNAPSHOT_PASSPHRASE": "",
"NOTARY_DELEGATION_PASSPHRASE": "",
}
for envVar := range orig {
orig[envVar] = os.Getenv(envVar)
os.Setenv(envVar, "")
}
return func() {
for envVar, value := range orig {
if value == "" {
os.Unsetenv(envVar)
} else {
os.Setenv(envVar, value)
}
}
}
}
func TestPassphraseRetrieverCaching(t *testing.T) {
defer cleanupAndSetEnvVars()()
// Only set up one passphrase environment var first for root
require.NoError(t, os.Setenv("NOTARY_ROOT_PASSPHRASE", "root_passphrase"))
// Check that root is cached
retriever := getPassphraseRetriever()
passphrase, giveup, err := retriever("key", data.CanonicalRootRole.String(), false, 0)
require.NoError(t, err)
require.False(t, giveup)
require.Equal(t, passphrase, "root_passphrase")
_, _, err = retriever("key", "user", false, 0)
require.Error(t, err)
_, _, err = retriever("key", data.CanonicalTargetsRole.String(), false, 0)
require.Error(t, err)
_, _, err = retriever("key", data.CanonicalSnapshotRole.String(), false, 0)
require.Error(t, err)
_, _, err = retriever("key", "targets/delegation", false, 0)
require.Error(t, err)
// Set up the rest of them
require.NoError(t, os.Setenv("NOTARY_TARGETS_PASSPHRASE", "targets_passphrase"))
require.NoError(t, os.Setenv("NOTARY_SNAPSHOT_PASSPHRASE", "snapshot_passphrase"))
require.NoError(t, os.Setenv("NOTARY_DELEGATION_PASSPHRASE", "delegation_passphrase"))
// Get a new retriever and check the caching
retriever = getPassphraseRetriever()
passphrase, giveup, err = retriever("key", data.CanonicalRootRole.String(), false, 0)
require.NoError(t, err)
require.False(t, giveup)
require.Equal(t, passphrase, "root_passphrase")
passphrase, giveup, err = retriever("key", data.CanonicalTargetsRole.String(), false, 0)
require.NoError(t, err)
require.False(t, giveup)
require.Equal(t, passphrase, "targets_passphrase")
passphrase, giveup, err = retriever("key", data.CanonicalSnapshotRole.String(), false, 0)
require.NoError(t, err)
require.False(t, giveup)
require.Equal(t, passphrase, "snapshot_passphrase")
passphrase, giveup, err = retriever("key", "targets/releases", false, 0)
require.NoError(t, err)
require.False(t, giveup)
require.Equal(t, passphrase, "delegation_passphrase")
// We don't require a targets/ prefix in PEM headers for delegation keys
passphrase, giveup, err = retriever("key", "user", false, 0)
require.NoError(t, err)
require.False(t, giveup)
require.Equal(t, passphrase, "delegation_passphrase")
}
func TestPassphraseRetrieverDelegationRoleCaching(t *testing.T) {
defer cleanupAndSetEnvVars()()
// Only set up one passphrase environment var first for delegations
require.NoError(t, os.Setenv("NOTARY_DELEGATION_PASSPHRASE", "delegation_passphrase"))
// Check that any delegation role is cached
retriever := getPassphraseRetriever()
passphrase, giveup, err := retriever("key", "targets/releases", false, 0)
require.NoError(t, err)
require.False(t, giveup)
require.Equal(t, passphrase, "delegation_passphrase")
passphrase, giveup, err = retriever("key", "targets/delegation", false, 0)
require.NoError(t, err)
require.False(t, giveup)
require.Equal(t, passphrase, "delegation_passphrase")
passphrase, giveup, err = retriever("key", "targets/a/b/c/d", false, 0)
require.NoError(t, err)
require.False(t, giveup)
require.Equal(t, passphrase, "delegation_passphrase")
// Also check arbitrary usernames that are non-BaseRoles or imported so that this can be shared across keys
passphrase, giveup, err = retriever("key", "user", false, 0)
require.NoError(t, err)
require.False(t, giveup)
require.Equal(t, passphrase, "delegation_passphrase")
// Make sure base roles fail
_, _, err = retriever("key", data.CanonicalRootRole.String(), false, 0)
require.Error(t, err)
_, _, err = retriever("key", data.CanonicalTargetsRole.String(), false, 0)
require.Error(t, err)
_, _, err = retriever("key", data.CanonicalSnapshotRole.String(), false, 0)
require.Error(t, err)
}