forked from notaryproject/notary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_test.go
4168 lines (3458 loc) · 156 KB
/
client_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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package client
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"fmt"
"io/ioutil"
"math"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"testing"
"time"
ctxu "github.com/docker/distribution/context"
"github.com/docker/go/canonical/json"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
"github.com/theupdateframework/notary"
"github.com/theupdateframework/notary/client/changelist"
"github.com/theupdateframework/notary/cryptoservice"
"github.com/theupdateframework/notary/passphrase"
"github.com/theupdateframework/notary/server"
"github.com/theupdateframework/notary/server/storage"
store "github.com/theupdateframework/notary/storage"
"github.com/theupdateframework/notary/trustmanager"
"github.com/theupdateframework/notary/trustpinning"
"github.com/theupdateframework/notary/tuf/data"
"github.com/theupdateframework/notary/tuf/signed"
testutils "github.com/theupdateframework/notary/tuf/testutils/keys"
"github.com/theupdateframework/notary/tuf/utils"
"github.com/theupdateframework/notary/tuf/validation"
)
const password = "passphrase"
type passRoleRecorder struct {
rolesCreated []string
rolesAsked []string
}
func newRoleRecorder() *passRoleRecorder {
return &passRoleRecorder{}
}
func (p *passRoleRecorder) clear() {
p.rolesCreated = nil
p.rolesAsked = nil
}
func (p *passRoleRecorder) retriever(_, alias string, createNew bool, _ int) (string, bool, error) {
if createNew {
p.rolesCreated = append(p.rolesCreated, alias)
} else {
p.rolesAsked = append(p.rolesAsked, alias)
}
return password, false, nil
}
func (p *passRoleRecorder) compareRolesRecorded(t *testing.T, expected []string, created bool,
args ...interface{}) {
var actual, useExpected sort.StringSlice
copy(expected, useExpected) // don't sort expected, since we don't want to mutate it
sort.Stable(useExpected)
if created {
copy(p.rolesCreated, actual)
} else {
copy(p.rolesAsked, actual)
}
sort.Stable(actual)
require.Equal(t, useExpected, actual, args...)
}
// requires the following keys be created: order does not matter
func (p *passRoleRecorder) requireCreated(t *testing.T, expected []string, args ...interface{}) {
p.compareRolesRecorded(t, expected, true, args...)
}
// requires that passwords be asked for the following keys: order does not matter
func (p *passRoleRecorder) requireAsked(t *testing.T, expected []string, args ...interface{}) {
p.compareRolesRecorded(t, expected, false, args...)
}
var passphraseRetriever = passphrase.ConstantRetriever(password)
func simpleTestServer(t *testing.T, roles ...string) (
*httptest.Server, *http.ServeMux, map[string]data.PrivateKey) {
if len(roles) == 0 {
roles = []string{data.CanonicalTimestampRole.String(), data.CanonicalSnapshotRole.String()}
}
keys := make(map[string]data.PrivateKey)
mux := http.NewServeMux()
for _, role := range roles {
key, err := utils.GenerateECDSAKey(rand.Reader)
require.NoError(t, err)
keys[role] = key
pubKey := data.PublicKeyFromPrivate(key)
jsonBytes, err := json.MarshalCanonical(&pubKey)
require.NoError(t, err)
keyJSON := string(jsonBytes)
// TUF will request /v2/docker.com/notary/_trust/tuf/<role>.key
mux.HandleFunc(
fmt.Sprintf("/v2/docker.com/notary/_trust/tuf/%s.key", role),
func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, keyJSON)
})
}
ts := httptest.NewServer(mux)
return ts, mux, keys
}
func fullTestServer(t *testing.T) *httptest.Server {
// Set up server
ctx := context.WithValue(
context.Background(), notary.CtxKeyMetaStore, storage.NewMemStorage())
// Do not pass one of the const KeyAlgorithms here as the value! Passing a
// string is in itself good test that we are handling it correctly as we
// will be receiving a string from the configuration.
ctx = context.WithValue(ctx, notary.CtxKeyKeyAlgo, "ecdsa")
// Eat the logs instead of spewing them out
var b bytes.Buffer
l := logrus.New()
l.Out = &b
ctx = ctxu.WithLogger(ctx, logrus.NewEntry(l))
cryptoService := cryptoservice.NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))
return httptest.NewServer(server.RootHandler(ctx, nil, cryptoService, nil, nil, nil))
}
// server that returns some particular error code all the time
func errorTestServer(t *testing.T, errorCode int) *httptest.Server {
handler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(errorCode)
}
server := httptest.NewServer(http.HandlerFunc(handler))
return server
}
// initializes a repository in a temporary directory
func initializeRepo(t *testing.T, rootType, gun, url string,
serverManagesSnapshot bool) (*repository, string) {
// Temporary directory where test files will be created
tempBaseDir, err := ioutil.TempDir("", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory: %s", err)
serverManagedRoles := []data.RoleName{}
if serverManagesSnapshot {
serverManagedRoles = []data.RoleName{data.CanonicalSnapshotRole}
}
repo, rec, rootPubKeyID := createRepoAndKey(t, rootType, tempBaseDir, gun, url)
err = repo.Initialize([]string{rootPubKeyID}, serverManagedRoles...)
if err != nil {
os.RemoveAll(tempBaseDir)
}
require.NoError(t, err, "error creating repository: %s", err)
// generates the target role, maybe the snapshot role
if serverManagesSnapshot {
rec.requireCreated(t, []string{data.CanonicalTargetsRole.String()})
} else {
rec.requireCreated(t, []string{data.CanonicalTargetsRole.String(), data.CanonicalSnapshotRole.String()})
}
// root key is cached by the cryptoservice, so when signing we don't actually ask
// for the passphrase
rec.requireAsked(t, nil)
return repo, rootPubKeyID
}
// Creates a new repository and adds a root key. Returns the repo and key ID.
func createRepoAndKey(t *testing.T, rootType, tempBaseDir, gun, url string) (*repository, *passRoleRecorder, string) {
rec := newRoleRecorder()
r, err := NewFileCachedRepository(
tempBaseDir, data.GUN(gun), url, http.DefaultTransport, rec.retriever, trustpinning.TrustPinConfig{})
require.NoError(t, err, "error creating repo: %s", err)
repo := r.(*repository)
rootPubKey, err := testutils.CreateOrAddKey(repo.GetCryptoService(), data.CanonicalRootRole, repo.gun, rootType)
require.NoError(t, err, "error generating root key: %s", err)
rec.requireCreated(t, []string{data.CanonicalRootRole.String()},
"root passphrase should have been required to generate a root key")
rec.requireAsked(t, nil)
rec.clear()
return repo, rec, rootPubKey.ID()
}
// creates a new notary repository with the same gun and url as the previous
// repo, in order to eliminate caches (for instance, cryptoservice cache)
// if a new directory is to be created, it also eliminates the TUF metadata
// cache
func newRepoToTestRepo(t *testing.T, existingRepo *repository, newDir bool) (
*repository, *passRoleRecorder) {
repoDir := existingRepo.baseDir
if newDir {
tempBaseDir, err := ioutil.TempDir("", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory")
repoDir = tempBaseDir
}
rec := newRoleRecorder()
r, err := NewFileCachedRepository(
repoDir, existingRepo.gun, existingRepo.baseURL,
http.DefaultTransport, rec.retriever, trustpinning.TrustPinConfig{})
require.NoError(t, err, "error creating repository: %s", err)
repo := r.(*repository)
if err != nil && newDir {
defer os.RemoveAll(repoDir)
}
return repo, rec
}
// Initializing a new repo while specifying that the server should manage the root
// role will fail.
func TestInitRepositoryManagedRolesIncludingRoot(t *testing.T) {
// Temporary directory where test files will be created
tempBaseDir, err := ioutil.TempDir("", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory")
defer os.RemoveAll(tempBaseDir)
repo, rec, rootPubKeyID := createRepoAndKey(
t, data.ECDSAKey, tempBaseDir, "docker.com/notary", "http://localhost")
err = repo.Initialize([]string{rootPubKeyID}, data.CanonicalRootRole)
require.Error(t, err)
require.IsType(t, ErrInvalidRemoteRole{}, err)
// Just testing the error message here in this one case
require.Equal(t, err.Error(),
"notary does not permit the server managing the root key")
// no key creation happened
rec.requireCreated(t, nil)
}
// Initializing a new repo while specifying that the server should manage some
// invalid role will fail.
func TestInitRepositoryManagedRolesInvalidRole(t *testing.T) {
// Temporary directory where test files will be created
tempBaseDir, err := ioutil.TempDir("", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory")
defer os.RemoveAll(tempBaseDir)
repo, rec, rootPubKeyID := createRepoAndKey(
t, data.ECDSAKey, tempBaseDir, "docker.com/notary", "http://localhost")
err = repo.Initialize([]string{rootPubKeyID}, "randomrole")
require.Error(t, err)
require.IsType(t, ErrInvalidRemoteRole{}, err)
// no key creation happened
rec.requireCreated(t, nil)
}
// Initializing a new repo while specifying that the server should manage the
// targets role will fail.
func TestInitRepositoryManagedRolesIncludingTargets(t *testing.T) {
// Temporary directory where test files will be created
tempBaseDir, err := ioutil.TempDir("", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory")
defer os.RemoveAll(tempBaseDir)
repo, rec, rootPubKeyID := createRepoAndKey(
t, data.ECDSAKey, tempBaseDir, "docker.com/notary", "http://localhost")
err = repo.Initialize([]string{rootPubKeyID}, data.CanonicalTargetsRole)
require.Error(t, err)
require.IsType(t, ErrInvalidRemoteRole{}, err)
// no key creation happened
rec.requireCreated(t, nil)
}
// Initializing a new repo while specifying that the server should manage the
// timestamp key is fine - that's what it already does, so no error.
func TestInitRepositoryManagedRolesIncludingTimestamp(t *testing.T) {
// Temporary directory where test files will be created
tempBaseDir, err := ioutil.TempDir("", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory")
defer os.RemoveAll(tempBaseDir)
ts, _, _ := simpleTestServer(t)
defer ts.Close()
repo, rec, rootPubKeyID := createRepoAndKey(
t, data.ECDSAKey, tempBaseDir, "docker.com/notary", ts.URL)
err = repo.Initialize([]string{rootPubKeyID}, data.CanonicalTimestampRole)
require.NoError(t, err)
// generates the target role, the snapshot role
rec.requireCreated(t, []string{data.CanonicalTargetsRole.String(), data.CanonicalSnapshotRole.String()})
}
func TestInitRepositoryWithCerts(t *testing.T) {
testCases := []struct {
name string
extraKeys int // the number of extra keys in addition the the first key
numberOfCerts int // initializing with certificates ?
expectedError string // error message
requiredSigningRootKeys int
unmatchedKeyPair bool // true when testing unmatched key pairs
noKeys bool // true when supplying only certificates
}{
{
name: "init with multiple root keys",
extraKeys: 1,
numberOfCerts: 0,
requiredSigningRootKeys: 2,
},
{
name: "1 key and 1 cert",
extraKeys: 0,
numberOfCerts: 1,
requiredSigningRootKeys: 1,
},
{
name: "unmatched key pairs: 1 key and 1 cert",
extraKeys: 1,
numberOfCerts: 2,
expectedError: "should not be able to initialize with non-matching keys",
unmatchedKeyPair: true,
},
{
name: "different number of keys and certs: 2 key, 1 certs",
extraKeys: 1,
numberOfCerts: 1,
expectedError: "should not be able to initialize with different number of keys and certs",
},
{
name: "testing with 1 cert with its private key in cryptoservice",
noKeys: true,
extraKeys: 0,
numberOfCerts: 1,
},
}
gun := "docker.com/notary"
for _, tc := range testCases {
// Temporary directory where test files will be created
tempBaseDir, err := ioutil.TempDir("", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory")
defer os.RemoveAll(tempBaseDir)
ts, _, _ := simpleTestServer(t)
defer ts.Close()
// create repo and first key
repo, rec, kid := createRepoAndKey(t, data.ECDSAKey, tempBaseDir, gun, ts.URL)
pubKeyIDs := []string{kid}
//create extra key pairs if necessary
for i := 0; i < tc.extraKeys; i++ {
key, err := repo.GetCryptoService().Create(data.CanonicalRootRole, repo.gun, data.ECDSAKey)
require.NoError(t, err, "error creating %v-th key: %v", i, err)
pubKeyIDs = append(pubKeyIDs, key.ID())
}
// assign pubKeys if necessary
var pubKeys []data.PublicKey
for i := 0; i < tc.numberOfCerts; i++ {
pubKeys = append(pubKeys, repo.GetCryptoService().GetKey(pubKeyIDs[i]))
}
if !strings.Contains(tc.name, "unmatched key pairs") {
iDs := pubKeyIDs[:1+tc.extraKeys] // use only the correct number of root key ids
if tc.noKeys { // case : 0 keys 1 cert
iDs = []string{}
}
err = repo.initialize(iDs, pubKeys, data.CanonicalTimestampRole)
if len(iDs) == len(pubKeys) || // case: 2 keys 2 certs
(len(iDs) != 0 && len(pubKeys) == 0) || // case: 1 key and 0 cert
(len(iDs) == 0 && len(pubKeys) != 0) { // case: 0 keys and 1 cert
require.NoError(t, err, "initialize returns an error")
rec.requireCreated(t, []string{data.CanonicalTargetsRole.String(), data.CanonicalSnapshotRole.String()})
require.Len(t, repo.tufRepo.Root.Signed.Roles[data.CanonicalRootRole].KeyIDs, tc.requiredSigningRootKeys)
return
}
// implicit else case: 2 keys 1 cert
} else { // unmatched key pairs case
err = repo.initialize(pubKeyIDs[1:], pubKeys[:1])
}
require.Error(t, err, tc.expectedError, tc.name)
require.Nil(t, repo.tufRepo)
}
}
func TestMatchKeyIDsWithPublicKeys(t *testing.T) {
// Temporary directory where test files will be created
tempBaseDir, err := ioutil.TempDir("", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory")
defer os.RemoveAll(tempBaseDir)
ts, _, _ := simpleTestServer(t, data.CanonicalSnapshotRole.String())
defer ts.Close()
// set up repo and keys
repo, _, keyID := createRepoAndKey(t, data.ECDSAKey, tempBaseDir, "docker.com/notary", ts.URL)
publicKey := repo.GetCryptoService().GetKey(keyID)
privateKey, _, err := repo.GetCryptoService().GetPrivateKey(keyID)
require.NoError(t, err, "private key should exist in keystore")
// 1. create a repository and obtain its root key id, use the key id to get the corresponding
// public key. Match this public key with a false key . expect an error.
err = matchKeyIdsWithPubKeys(repo, []string{"fake id"}, []data.PublicKey{publicKey})
require.Error(t, err, "the public key should not be matched with the given id.")
// 2. match a correct public key (non x509) with its corresponding key id
err = matchKeyIdsWithPubKeys(repo, []string{publicKey.ID()}, []data.PublicKey{publicKey})
require.NoError(t, err, "public key should be matched with its corresponding private key ")
// 3. match a correct x509 public key with its corresponding private key id
// create x509 pubkey: create template -> use template to create a cert in PEM form -> convert to Certificate -> convert to pub key
startTime := time.Now()
template, err := utils.NewCertificate(data.CanonicalRootRole.String(), startTime, startTime.AddDate(10, 0, 0))
require.NoError(t, err, "failed to create the certificate template: %v", err)
signer := privateKey.CryptoSigner()
certPEM, err := x509.CreateCertificate(rand.Reader, template, template, signer.Public(), signer)
require.NoError(t, err, "error when generating certificate with public key %v", err)
cert, err := x509.ParseCertificate(certPEM)
require.NoError(t, err, "parsing PEM to certificate but encountered an error: %v", err)
certKey := utils.CertToKey(cert)
err = matchKeyIdsWithPubKeys(repo, []string{publicKey.ID()}, []data.PublicKey{certKey})
require.NoError(t, err, "public key should be matched with its corresponding private key")
// 4. match a non matching key pair, expect error
pub2, err := repo.GetCryptoService().Create(data.CanonicalRootRole, "docker.com/notary", data.ECDSAKey)
require.NoError(t, err, "error generating root key: %s", err)
err = matchKeyIdsWithPubKeys(repo, []string{pub2.ID()}, []data.PublicKey{publicKey})
require.Error(t, err, "validating a non-matching key pair should fail but didn't")
}
// Initializing a new repo fails if unable to get the timestamp key, even if
// the snapshot key is available
func TestInitRepositoryNeedsRemoteTimestampKey(t *testing.T) {
// Temporary directory where test files will be created
tempBaseDir, err := ioutil.TempDir("", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory")
defer os.RemoveAll(tempBaseDir)
ts, _, _ := simpleTestServer(t, data.CanonicalSnapshotRole.String())
defer ts.Close()
repo, rec, rootPubKeyID := createRepoAndKey(
t, data.ECDSAKey, tempBaseDir, "docker.com/notary", ts.URL)
err = repo.Initialize([]string{rootPubKeyID}, data.CanonicalTimestampRole)
require.Error(t, err)
require.IsType(t, store.ErrMetaNotFound{}, err)
// locally managed keys are created first, to avoid unnecssary network calls,
// so they would have been generated
rec.requireCreated(t, []string{data.CanonicalTargetsRole.String(), data.CanonicalSnapshotRole.String()})
}
// Initializing a new repo with remote server signing fails if unable to get
// the snapshot key, even if the timestamp key is available
func TestInitRepositoryNeedsRemoteSnapshotKey(t *testing.T) {
// Temporary directory where test files will be created
tempBaseDir, err := ioutil.TempDir("", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory")
defer os.RemoveAll(tempBaseDir)
ts, _, _ := simpleTestServer(t, data.CanonicalTimestampRole.String())
defer ts.Close()
repo, rec, rootPubKeyID := createRepoAndKey(
t, data.ECDSAKey, tempBaseDir, "docker.com/notary", ts.URL)
err = repo.Initialize([]string{rootPubKeyID}, data.CanonicalSnapshotRole)
require.Error(t, err)
require.IsType(t, store.ErrMetaNotFound{}, err)
// locally managed keys are created first, to avoid unnecssary network calls,
// so they would have been generated
rec.requireCreated(t, []string{data.CanonicalTargetsRole.String()})
}
// passing timestamp + snapshot, or just snapshot, is tested in the next two
// test cases.
// TestInitRepoServerOnlyManagesTimestampKey runs through the process of
// initializing a repository and makes sure the repository looks correct on disk.
// We test this with both an RSA and ECDSA root key.
// This test case covers the default case where the server only manages the
// timestamp key.
func TestInitRepoServerOnlyManagesTimestampKey(t *testing.T) {
testInitRepoMetadata(t, data.ECDSAKey, false)
testInitRepoSigningKeys(t, data.ECDSAKey, false)
if !testing.Short() {
testInitRepoMetadata(t, data.RSAKey, false)
testInitRepoSigningKeys(t, data.RSAKey, false)
}
}
// TestInitRepoServerManagesTimestampAndSnapshotKeys runs through the process of
// initializing a repository and makes sure the repository looks correct on disk.
// We test this with both an RSA and ECDSA root key.
// This test case covers the server managing both the timestamp and snapshot keys.
func TestInitRepoServerManagesTimestampAndSnapshotKeys(t *testing.T) {
testInitRepoMetadata(t, data.ECDSAKey, true)
testInitRepoSigningKeys(t, data.ECDSAKey, true)
if !testing.Short() {
testInitRepoMetadata(t, data.RSAKey, true)
testInitRepoSigningKeys(t, data.RSAKey, false)
}
}
// This creates a new KeyFileStore in the repo's base directory and makes sure
// the repo has the right number of keys
func requireRepoHasExpectedKeys(t *testing.T, repo *repository,
rootKeyID string, expectedSnapshotKey bool) {
// The repo should have a keyFileStore and have created keys using it,
// so create a new KeyFileStore, and check that the keys do exist and are
// valid
ks, err := trustmanager.NewKeyFileStore(repo.baseDir, passphraseRetriever)
require.NoError(t, err)
roles := make(map[string]bool)
for keyID, keyInfo := range ks.ListKeys() {
if keyInfo.Role == data.CanonicalRootRole {
require.Equal(t, rootKeyID, keyID, "Unexpected root key ID")
}
// just to ensure the content of the key files created are valid
_, r, err := ks.GetKey(keyID)
require.NoError(t, err)
require.Equal(t, keyInfo.Role, r)
roles[keyInfo.Role.String()] = true
}
// there is a root key and a targets key
alwaysThere := []string{data.CanonicalRootRole.String(), data.CanonicalTargetsRole.String()}
for _, role := range alwaysThere {
_, ok := roles[role]
require.True(t, ok, "missing %s key", role)
}
// there may be a snapshots key, depending on whether the server is managing
// the snapshots key
_, ok := roles[data.CanonicalSnapshotRole.String()]
if expectedSnapshotKey {
require.True(t, ok, "missing snapshot key")
} else {
require.False(t, ok,
"there should be no snapshot key because the server manages it")
}
// The server manages the timestamp key - there should not be a timestamp
// key
_, ok = roles[data.CanonicalTimestampRole.String()]
require.False(t, ok,
"there should be no timestamp key because the server manages it")
}
// Sanity check the TUF metadata files. Verify that it exists for a particular
// role, the JSON is well-formed, and the signatures exist.
// For the root.json file, also check that the root, snapshot, and
// targets key IDs are present.
func requireRepoHasExpectedMetadata(t *testing.T, repo *repository,
role data.RoleName, expected bool) {
filename := filepath.Join(tufDir, filepath.FromSlash(repo.gun.String()),
"metadata", role.String()+".json")
fullPath := filepath.Join(repo.baseDir, filename)
_, err := os.Stat(fullPath)
if expected {
require.NoError(t, err, "missing TUF metadata file: %s", filename)
} else {
require.Error(t, err,
"%s metadata should not exist, but does: %s", role.String(), filename)
return
}
jsonBytes, err := ioutil.ReadFile(fullPath)
require.NoError(t, err, "error reading TUF metadata file %s: %s", filename, err)
var decoded data.Signed
err = json.Unmarshal(jsonBytes, &decoded)
require.NoError(t, err, "error parsing TUF metadata file %s: %s", filename, err)
require.Len(t, decoded.Signatures, 1,
"incorrect number of signatures in TUF metadata file %s", filename)
require.NotEmpty(t, decoded.Signatures[0].KeyID,
"empty key ID field in TUF metadata file %s", filename)
require.NotEmpty(t, decoded.Signatures[0].Method,
"empty method field in TUF metadata file %s", filename)
require.NotEmpty(t, decoded.Signatures[0].Signature,
"empty signature in TUF metadata file %s", filename)
// Special case for root.json: also check that the signed
// content for keys and roles
if role == data.CanonicalRootRole {
var decodedRoot data.Root
err := json.Unmarshal(*decoded.Signed, &decodedRoot)
require.NoError(t, err, "error parsing root.json signed section: %s", err)
require.Equal(t, "Root", decodedRoot.Type, "_type mismatch in root.json")
// Expect 1 key for each valid role in the Keys map - one for
// each of root, targets, snapshot, timestamp
require.Len(t, decodedRoot.Keys, len(data.BaseRoles),
"wrong number of keys in root.json")
require.True(t, len(decodedRoot.Roles) >= len(data.BaseRoles),
"wrong number of roles in root.json")
for _, role := range data.BaseRoles {
_, ok := decodedRoot.Roles[role]
require.True(t, ok, "Missing role %s in root.json", role)
}
}
}
func testInitRepoMetadata(t *testing.T, rootType string, serverManagesSnapshot bool) {
gun := "docker.com/notary"
ts, _, _ := simpleTestServer(t)
defer ts.Close()
repo, rootKeyID := initializeRepo(t, rootType, gun, ts.URL, serverManagesSnapshot)
defer os.RemoveAll(repo.baseDir)
requireRepoHasExpectedKeys(t, repo, rootKeyID, !serverManagesSnapshot)
requireRepoHasExpectedMetadata(t, repo, data.CanonicalRootRole, true)
requireRepoHasExpectedMetadata(t, repo, data.CanonicalTargetsRole, true)
requireRepoHasExpectedMetadata(t, repo, data.CanonicalSnapshotRole,
!serverManagesSnapshot)
}
func testInitRepoSigningKeys(t *testing.T, rootType string, serverManagesSnapshot bool) {
ts, _, _ := simpleTestServer(t)
defer ts.Close()
// Temporary directory where test files will be created
tempBaseDir, err := ioutil.TempDir("", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory: %s", err)
repo, _, rootPubKeyID := createRepoAndKey(
t, data.ECDSAKey, tempBaseDir, "docker.com/notary", ts.URL)
// create a new repository, so we can wipe out the cryptoservice's cached
// keys, so we can test which keys it asks for passwords for
repo, rec := newRepoToTestRepo(t, repo, false)
if serverManagesSnapshot {
err = repo.Initialize([]string{rootPubKeyID}, data.CanonicalSnapshotRole)
} else {
err = repo.Initialize([]string{rootPubKeyID})
}
require.NoError(t, err, "error initializing repository")
// generates the target role, maybe the snapshot role
if serverManagesSnapshot {
rec.requireCreated(t, []string{data.CanonicalTargetsRole.String()})
} else {
rec.requireCreated(t, []string{data.CanonicalTargetsRole.String(), data.CanonicalSnapshotRole.String()})
}
// root is asked for signing the root role
rec.requireAsked(t, []string{data.CanonicalRootRole.String()})
}
// TestInitRepoAttemptsExceeded tests error handling when passphrase.Retriever
// (or rather the user) insists on an incorrect password.
func TestInitRepoAttemptsExceeded(t *testing.T) {
testInitRepoAttemptsExceeded(t, data.ECDSAKey)
if !testing.Short() {
testInitRepoAttemptsExceeded(t, data.RSAKey)
}
}
func testInitRepoAttemptsExceeded(t *testing.T, rootType string) {
var gun data.GUN = "docker.com/notary"
// Temporary directory where test files will be created
tempBaseDir, err := ioutil.TempDir("", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory: %s", err)
defer os.RemoveAll(tempBaseDir)
ts, _, _ := simpleTestServer(t)
defer ts.Close()
retriever := passphrase.ConstantRetriever("password")
r, err := NewFileCachedRepository(tempBaseDir, gun, ts.URL, http.DefaultTransport, retriever, trustpinning.TrustPinConfig{})
require.NoError(t, err, "error creating repo: %s", err)
repo := r.(*repository)
rootPubKey, err := testutils.CreateOrAddKey(repo.GetCryptoService(), data.CanonicalRootRole, repo.gun, rootType)
require.NoError(t, err, "error generating root key: %s", err)
retriever = passphrase.ConstantRetriever("incorrect password")
// repo.GetCryptoService’s FileKeyStore caches the unlocked private key, so to test
// private key unlocking we need a new repo instance.
r, err = NewFileCachedRepository(tempBaseDir, gun, ts.URL, http.DefaultTransport, retriever, trustpinning.TrustPinConfig{})
require.NoError(t, err, "error creating repo: %s", err)
repo = r.(*repository)
err = repo.Initialize([]string{rootPubKey.ID()})
require.EqualError(t, err, trustmanager.ErrAttemptsExceeded{}.Error())
}
// TestInitRepoPasswordInvalid tests error handling when passphrase.Retriever
// (or rather the user) fails to provide a correct password.
func TestInitRepoPasswordInvalid(t *testing.T) {
testInitRepoPasswordInvalid(t, data.ECDSAKey)
if !testing.Short() {
testInitRepoPasswordInvalid(t, data.RSAKey)
}
}
func giveUpPassphraseRetriever(_, _ string, _ bool, _ int) (string, bool, error) {
return "", true, nil
}
func testInitRepoPasswordInvalid(t *testing.T, rootType string) {
var gun data.GUN = "docker.com/notary"
// Temporary directory where test files will be created
tempBaseDir, err := ioutil.TempDir("", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory: %s", err)
defer os.RemoveAll(tempBaseDir)
ts, _, _ := simpleTestServer(t)
defer ts.Close()
retriever := passphrase.ConstantRetriever("password")
r, err := NewFileCachedRepository(tempBaseDir, gun, ts.URL, http.DefaultTransport, retriever, trustpinning.TrustPinConfig{})
require.NoError(t, err, "error creating repo: %s", err)
repo := r.(*repository)
rootPubKey, err := testutils.CreateOrAddKey(repo.GetCryptoService(), data.CanonicalRootRole, repo.gun, rootType)
require.NoError(t, err, "error generating root key: %s", err)
// repo.GetCryptoService’s FileKeyStore caches the unlocked private key, so to test
// private key unlocking we need a new repo instance.
r, err = NewFileCachedRepository(tempBaseDir, gun, ts.URL, http.DefaultTransport, giveUpPassphraseRetriever, trustpinning.TrustPinConfig{})
require.NoError(t, err, "error creating repo: %s", err)
repo = r.(*repository)
err = repo.Initialize([]string{rootPubKey.ID()})
require.EqualError(t, err, trustmanager.ErrPasswordInvalid{}.Error())
}
func addTarget(t *testing.T, repo *repository, targetName, targetFile string,
roles ...data.RoleName) *Target {
var targetCustom *json.RawMessage
return addTargetWithCustom(t, repo, targetName, targetFile, targetCustom, roles...)
}
func addTargetWithCustom(t *testing.T, repo *repository, targetName,
targetFile string, targetCustom *json.RawMessage, roles ...data.RoleName) *Target {
target, err := NewTarget(targetName, targetFile, targetCustom)
require.NoError(t, err, "error creating target")
err = repo.AddTarget(target, roles...)
require.NoError(t, err, "error adding target")
return target
}
// calls GetChangelist and gets the actual changes out
func getChanges(t *testing.T, repo *repository) []changelist.Change {
changeList, err := repo.GetChangelist()
require.NoError(t, err)
return changeList.List()
}
// TestAddTargetToTargetRoleByDefault adds a target without specifying a role
// to a repo without delegations. Confirms that the changelist is created
// correctly, for the targets scope.
func TestAddTargetToTargetRoleByDefault(t *testing.T) {
testAddTargetToTargetRoleByDefault(t, false)
testAddTargetToTargetRoleByDefault(t, true)
}
func testAddTargetToTargetRoleByDefault(t *testing.T, clearCache bool) {
ts, _, _ := simpleTestServer(t)
defer ts.Close()
repo, _ := initializeRepo(t, data.ECDSAKey, "docker.com/notary", ts.URL, false)
defer os.RemoveAll(repo.baseDir)
var rec *passRoleRecorder
if clearCache {
repo, rec = newRepoToTestRepo(t, repo, false)
}
testAddOrDeleteTarget(t, repo, changelist.ActionCreate, nil,
[]string{data.CanonicalTargetsRole.String()})
if clearCache {
// no key creation or signing happened, because add doesn't ever require signing
rec.requireCreated(t, nil)
rec.requireAsked(t, nil)
}
}
// Tests that adding a target to a repo or deleting a target from a repo,
// with the given roles, makes a change to the expected scopes
func testAddOrDeleteTarget(t *testing.T, repo *repository, action string,
rolesToChange []data.RoleName, expectedScopes []string) {
require.Len(t, getChanges(t, repo), 0, "should start with zero changes")
if action == changelist.ActionCreate {
// Add fixtures/intermediate-ca.crt as a target. There's no particular
// reason for using this file except that it happens to be available as
// a fixture.
addTarget(t, repo, "latest", "../fixtures/intermediate-ca.crt", rolesToChange...)
} else {
err := repo.RemoveTarget("latest", rolesToChange...)
require.NoError(t, err, "error removing target")
}
changes := getChanges(t, repo)
require.Len(t, changes, len(expectedScopes), "wrong number of changes files found")
foundScopes := make(map[string]bool)
for _, c := range changes { // there is only one
require.EqualValues(t, action, c.Action())
foundScopes[c.Scope().String()] = true
require.Equal(t, "target", c.Type())
require.Equal(t, "latest", c.Path())
if action == changelist.ActionCreate {
require.NotEmpty(t, c.Content())
} else {
require.Empty(t, c.Content())
}
}
require.Len(t, foundScopes, len(expectedScopes))
for _, expectedScope := range expectedScopes {
_, ok := foundScopes[expectedScope]
require.True(t, ok, "Target was not added/removed from %s", expectedScope)
}
// add/delete a second time
if action == changelist.ActionCreate {
addTarget(t, repo, "current", "../fixtures/intermediate-ca.crt", rolesToChange...)
} else {
err := repo.RemoveTarget("current", rolesToChange...)
require.NoError(t, err, "error removing target")
}
changes = getChanges(t, repo)
require.Len(t, changes, 2*len(expectedScopes),
"wrong number of changelist files found")
newFileFound := false
foundScopes = make(map[string]bool)
for _, c := range changes {
if c.Path() != "latest" {
require.EqualValues(t, action, c.Action())
foundScopes[c.Scope().String()] = true
require.Equal(t, "target", c.Type())
require.Equal(t, "current", c.Path())
if action == changelist.ActionCreate {
require.NotEmpty(t, c.Content())
} else {
require.Empty(t, c.Content())
}
newFileFound = true
}
}
require.True(t, newFileFound, "second changelist file not found")
require.Len(t, foundScopes, len(expectedScopes))
for _, expectedScope := range expectedScopes {
_, ok := foundScopes[expectedScope]
require.True(t, ok, "Target was not added/removed from %s", expectedScope)
}
}
// TestAddTargetToSpecifiedValidRoles adds a target to the specified roles.
// Confirms that the changelist is created correctly, one for each of the
// the specified roles as scopes.
func TestAddTargetToSpecifiedValidRoles(t *testing.T) {
testAddTargetToSpecifiedValidRoles(t, false)
testAddTargetToSpecifiedValidRoles(t, true)
}
func testAddTargetToSpecifiedValidRoles(t *testing.T, clearCache bool) {
ts, _, _ := simpleTestServer(t)
defer ts.Close()
repo, _ := initializeRepo(t, data.ECDSAKey, "docker.com/notary", ts.URL, false)
defer os.RemoveAll(repo.baseDir)
var rec *passRoleRecorder
if clearCache {
repo, rec = newRepoToTestRepo(t, repo, false)
}
roleName := filepath.Join(data.CanonicalTargetsRole.String(), "a")
testAddOrDeleteTarget(t, repo, changelist.ActionCreate,
[]data.RoleName{
data.CanonicalTargetsRole,
data.RoleName(roleName),
},
[]string{data.CanonicalTargetsRole.String(), roleName})
if clearCache {
// no key creation or signing happened, because add doesn't ever require signing
rec.requireCreated(t, nil)
rec.requireAsked(t, nil)
}
}
// TestAddTargetToSpecifiedInvalidRoles expects errors to be returned if
// adding a target to an invalid role. If any of the roles are invalid,
// no targets are added to any roles.
func TestAddTargetToSpecifiedInvalidRoles(t *testing.T) {
testAddTargetToSpecifiedInvalidRoles(t, false)
testAddTargetToSpecifiedInvalidRoles(t, true)
}
func testAddTargetToSpecifiedInvalidRoles(t *testing.T, clearCache bool) {
ts, _, _ := simpleTestServer(t)
defer ts.Close()
repo, _ := initializeRepo(t, data.ECDSAKey, "docker.com/notary", ts.URL, false)
defer os.RemoveAll(repo.baseDir)
var rec *passRoleRecorder
if clearCache {
repo, rec = newRepoToTestRepo(t, repo, false)
}
invalidRoles := []data.RoleName{
data.CanonicalRootRole,
data.CanonicalSnapshotRole,
data.CanonicalTimestampRole,
"target/otherrole",
"otherrole",
"TARGETS/ALLCAPSROLE",
}
for _, invalidRole := range invalidRoles {
var targetCustom *json.RawMessage
target, err := NewTarget("latest", "../fixtures/intermediate-ca.crt", targetCustom)
require.NoError(t, err, "error creating target")
err = repo.AddTarget(target, data.CanonicalTargetsRole, invalidRole)
require.Error(t, err, "Expected an ErrInvalidRole error")
require.IsType(t, data.ErrInvalidRole{}, err)
changes := getChanges(t, repo)
require.Len(t, changes, 0)
}
if clearCache {
// no key creation or signing happened, because add doesn't ever require signing
rec.requireCreated(t, nil)
rec.requireAsked(t, nil)
}
}
// General way to require that errors writing a changefile are propagated up
func testErrorWritingChangefiles(t *testing.T, writeChangeFile func(*repository) error) {
ts, _, _ := simpleTestServer(t)
defer ts.Close()
gun := "docker.com/notary"
repo, _ := initializeRepo(t, data.ECDSAKey, gun, ts.URL, false)
defer os.RemoveAll(repo.baseDir)
// first, make the actual changefile unwritable by making the changelist
// directory unwritable
changelistPath := filepath.Join(
filepath.Join(repo.baseDir, tufDir, filepath.FromSlash(gun)), "changelist",
)
err := os.MkdirAll(changelistPath, 0744)
require.NoError(t, err, "could not create changelist dir")
err = os.Chmod(changelistPath, 0600)
require.NoError(t, err, "could not change permission of changelist dir")
err = writeChangeFile(repo)
require.Error(t, err, "Expected an error writing the change")
require.IsType(t, &os.PathError{}, err)
// then break prevent the changlist directory from being able to be created
err = os.Chmod(changelistPath, 0744)
require.NoError(t, err, "could not change permission of temp dir")
err = os.RemoveAll(changelistPath)
require.NoError(t, err, "could not remove changelist dir")
// creating a changelist file so the directory can't be created
err = ioutil.WriteFile(changelistPath, []byte("hi"), 0644)
require.NoError(t, err, "could not write temporary file")