forked from theupdateframework/go-tuf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
repo_test.go
2743 lines (2370 loc) · 84.4 KB
/
repo_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 tuf
import (
"bytes"
"crypto"
"crypto/elliptic"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"path"
"path/filepath"
"reflect"
"sort"
"strings"
"testing"
"time"
"github.com/secure-systems-lab/go-securesystemslib/cjson"
"github.com/theupdateframework/go-tuf/data"
"github.com/theupdateframework/go-tuf/encrypted"
"github.com/theupdateframework/go-tuf/internal/sets"
"github.com/theupdateframework/go-tuf/pkg/keys"
"github.com/theupdateframework/go-tuf/pkg/targets"
"github.com/theupdateframework/go-tuf/util"
"github.com/theupdateframework/go-tuf/verify"
"golang.org/x/crypto/ed25519"
. "gopkg.in/check.v1"
)
// Hook up gocheck into the "go test" runner.
func Test(t *testing.T) { TestingT(t) }
type RepoSuite struct{}
var _ = Suite(&RepoSuite{})
func (RepoSuite) TestNewRepo(c *C) {
testNewRepo(c, NewRepo)
}
func (RepoSuite) TestNewRepoIndent(c *C) {
testNewRepo(c, func(local LocalStore, hashAlgorithms ...string) (*Repo, error) {
return NewRepoIndent(local, "", "\t")
})
}
// UniqueKeys returns the unique keys for each associated role.
// We might have multiple key IDs that correspond to the same key.
func UniqueKeys(r *data.Root) map[string][]*data.PublicKey {
keysByRole := make(map[string][]*data.PublicKey)
for name, role := range r.Roles {
seen := make(map[string]struct{})
roleKeys := []*data.PublicKey{}
for _, id := range role.KeyIDs {
// Double-check that there is actually a key with that ID.
if key, ok := r.Keys[id]; ok {
verifier, err := keys.GetVerifier(key)
if err != nil {
continue
}
val := verifier.Public()
if _, ok := seen[val]; ok {
continue
}
seen[val] = struct{}{}
roleKeys = append(roleKeys, key)
}
}
keysByRole[name] = roleKeys
}
return keysByRole
}
// AssertNumUniqueKeys verifies that the number of unique root keys for a given role is as expected.
func (*RepoSuite) assertNumUniqueKeys(c *C, root *data.Root, role string, num int) {
c.Assert(UniqueKeys(root)[role], HasLen, num)
}
func testNewRepo(c *C, newRepo func(local LocalStore, hashAlgorithms ...string) (*Repo, error)) {
meta := map[string]json.RawMessage{
"root.json": []byte(`{
"signed": {
"_type": "root",
"version": 1,
"expires": "2015-12-26T03:26:55.821520874Z",
"keys": {},
"roles": {}
},
"signatures": []
}`),
"targets.json": []byte(`{
"signed": {
"_type": "targets",
"version": 1,
"expires": "2015-03-26T03:26:55.82155686Z",
"targets": {}
},
"signatures": []
}`),
"snapshot.json": []byte(`{
"signed": {
"_type": "snapshot",
"version": 1,
"expires": "2015-01-02T03:26:55.821585981Z",
"meta": {}
},
"signatures": []
}`),
"timestamp.json": []byte(`{
"signed": {
"_type": "timestamp",
"version": 1,
"expires": "2014-12-27T03:26:55.821599702Z",
"meta": {}
},
"signatures": []
}`),
}
local := MemoryStore(meta, nil)
r, err := newRepo(local)
c.Assert(err, IsNil)
root, err := r.root()
c.Assert(err, IsNil)
c.Assert(root.Type, Equals, "root")
c.Assert(root.Version, Equals, int64(1))
c.Assert(root.Keys, NotNil)
c.Assert(root.Keys, HasLen, 0)
targets, err := r.topLevelTargets()
c.Assert(err, IsNil)
c.Assert(targets.Type, Equals, "targets")
c.Assert(targets.Version, Equals, int64(1))
c.Assert(targets.Targets, NotNil)
c.Assert(targets.Targets, HasLen, 0)
snapshot, err := r.snapshot()
c.Assert(err, IsNil)
c.Assert(snapshot.Type, Equals, "snapshot")
c.Assert(snapshot.Version, Equals, int64(1))
c.Assert(snapshot.Meta, NotNil)
c.Assert(snapshot.Meta, HasLen, 0)
timestamp, err := r.timestamp()
c.Assert(err, IsNil)
c.Assert(timestamp.Type, Equals, "timestamp")
c.Assert(timestamp.Version, Equals, int64(1))
c.Assert(timestamp.Meta, NotNil)
c.Assert(timestamp.Meta, HasLen, 0)
}
func (rs *RepoSuite) TestInit(c *C) {
local := MemoryStore(
make(map[string]json.RawMessage),
map[string][]byte{"foo.txt": []byte("foo")},
)
r, err := NewRepo(local)
c.Assert(err, IsNil)
// Init() sets root.ConsistentSnapshot
for _, v := range []bool{true, false} {
c.Assert(r.Init(v), IsNil)
root, err := r.root()
c.Assert(err, IsNil)
c.Assert(root.ConsistentSnapshot, Equals, v)
}
// Add a target.
generateAndAddPrivateKey(c, r, "targets")
c.Assert(r.AddTarget("foo.txt", nil), IsNil)
// Init() fails if targets have been added
c.Assert(r.Init(true), Equals, ErrInitNotAllowed)
}
func genKey(c *C, r *Repo, role string) []string {
keyids, err := r.GenKey(role)
c.Assert(err, IsNil)
c.Assert(len(keyids) > 0, Equals, true)
return keyids
}
func (rs *RepoSuite) TestGenKey(c *C) {
local := MemoryStore(make(map[string]json.RawMessage), nil)
r, err := NewRepo(local)
c.Assert(err, IsNil)
// generate a key for an unknown role
_, err = r.GenKey("foo")
c.Assert(err, Equals, ErrInvalidRole{"foo", "only support adding keys for top-level roles"})
// generate a root key
ids := genKey(c, r, "root")
// check root metadata is correct
root, err := r.root()
c.Assert(err, IsNil)
c.Assert(root.Roles, NotNil)
c.Assert(root.Roles, HasLen, 1)
rs.assertNumUniqueKeys(c, root, "root", 1)
rootRole, ok := root.Roles["root"]
if !ok {
c.Fatal("missing root role")
}
c.Assert(rootRole.KeyIDs, HasLen, 1)
c.Assert(rootRole.KeyIDs, DeepEquals, ids)
for _, keyID := range ids {
k, ok := root.Keys[keyID]
if !ok {
c.Fatal("missing key")
}
c.Assert(k.IDs(), DeepEquals, ids)
pk, err := keys.GetVerifier(k)
c.Assert(err, IsNil)
c.Assert(pk.Public(), HasLen, ed25519.PublicKeySize)
}
// check root key + role are in db
db, err := r.topLevelKeysDB()
c.Assert(err, IsNil)
for _, keyID := range ids {
rootKey, err := db.GetVerifier(keyID)
c.Assert(err, IsNil)
c.Assert(rootKey.MarshalPublicKey().IDs(), DeepEquals, ids)
role := db.GetRole("root")
c.Assert(role.KeyIDs, DeepEquals, sets.StringSliceToSet(ids))
// check the key was saved correctly
localKeys, err := local.GetSigners("root")
c.Assert(err, IsNil)
c.Assert(localKeys, HasLen, 1)
c.Assert(localKeys[0].PublicData().IDs(), DeepEquals, ids)
// check RootKeys() is correct
rootKeys, err := r.RootKeys()
c.Assert(err, IsNil)
c.Assert(rootKeys, HasLen, 1)
c.Assert(rootKeys[0].IDs(), DeepEquals, rootKey.MarshalPublicKey().IDs())
pk, err := keys.GetVerifier(rootKeys[0])
c.Assert(err, IsNil)
c.Assert(pk.Public(), DeepEquals, rootKey.Public())
}
rootKey, err := db.GetVerifier(ids[0])
c.Assert(err, IsNil)
// generate two targets keys
genKey(c, r, "targets")
genKey(c, r, "targets")
// check root metadata is correct
root, err = r.root()
c.Assert(err, IsNil)
c.Assert(root.Roles, HasLen, 2)
rs.assertNumUniqueKeys(c, root, "root", 1)
rs.assertNumUniqueKeys(c, root, "targets", 2)
targetsRole, ok := root.Roles["targets"]
if !ok {
c.Fatal("missing targets role")
}
c.Assert(targetsRole.KeyIDs, HasLen, 2)
targetKeyIDs := make(map[string]struct{}, 2)
db, err = r.topLevelKeysDB()
c.Assert(err, IsNil)
for _, id := range targetsRole.KeyIDs {
targetKeyIDs[id] = struct{}{}
_, ok = root.Keys[id]
if !ok {
c.Fatal("missing key")
}
verifier, err := db.GetVerifier(id)
c.Assert(err, IsNil)
c.Assert(verifier.MarshalPublicKey().ContainsID(id), Equals, true)
}
role := db.GetRole("targets")
c.Assert(role.KeyIDs, DeepEquals, targetKeyIDs)
// check RootKeys() is unchanged
rootKeys, err := r.RootKeys()
c.Assert(err, IsNil)
c.Assert(rootKeys, HasLen, 1)
c.Assert(rootKeys[0].IDs(), DeepEquals, rootKey.MarshalPublicKey().IDs())
// check the keys were saved correctly
localKeys, err := local.GetSigners("targets")
c.Assert(err, IsNil)
c.Assert(localKeys, HasLen, 2)
for _, key := range localKeys {
found := false
for _, id := range targetsRole.KeyIDs {
if key.PublicData().ContainsID(id) {
found = true
break
}
}
if !found {
c.Fatal("missing key")
}
}
// check root.json got staged
meta, err := local.GetMeta()
c.Assert(err, IsNil)
rootJSON, ok := meta["root.json"]
if !ok {
c.Fatal("missing root metadata")
}
s := &data.Signed{}
c.Assert(json.Unmarshal(rootJSON, s), IsNil)
stagedRoot := &data.Root{}
c.Assert(json.Unmarshal(s.Signed, stagedRoot), IsNil)
c.Assert(stagedRoot.Type, Equals, root.Type)
c.Assert(stagedRoot.Version, Equals, root.Version)
c.Assert(stagedRoot.Expires.UnixNano(), Equals, root.Expires.UnixNano())
// make sure both root and stagedRoot have evaluated IDs(), otherwise
// DeepEquals will fail because those values might not have been
// computed yet.
for _, key := range root.Keys {
key.IDs()
}
for _, key := range stagedRoot.Keys {
key.IDs()
}
c.Assert(stagedRoot.Keys, DeepEquals, root.Keys)
c.Assert(stagedRoot.Roles, DeepEquals, root.Roles)
}
func addPrivateKey(c *C, r *Repo, role string, key keys.Signer) []string {
err := r.AddPrivateKey(role, key)
c.Assert(err, IsNil)
keyids := key.PublicData().IDs()
c.Assert(len(keyids) > 0, Equals, true)
return keyids
}
func generateAndAddPrivateKey(c *C, r *Repo, role string) []string {
signer, err := keys.GenerateEd25519Key()
c.Assert(err, IsNil)
return addPrivateKey(c, r, role, signer)
}
func (rs *RepoSuite) TestAddPrivateKey(c *C) {
local := MemoryStore(make(map[string]json.RawMessage), nil)
r, err := NewRepo(local)
c.Assert(err, IsNil)
// generate a key for an unknown role
signer, err := keys.GenerateEd25519Key()
c.Assert(err, IsNil)
err = r.AddPrivateKey("foo", signer)
c.Assert(err, Equals, ErrInvalidRole{"foo", "only support adding keys for top-level roles"})
// add a root key
ids := addPrivateKey(c, r, "root", signer)
// check root metadata is correct
root, err := r.root()
c.Assert(err, IsNil)
c.Assert(root.Version, Equals, int64(1))
c.Assert(root.Roles, NotNil)
c.Assert(root.Roles, HasLen, 1)
rs.assertNumUniqueKeys(c, root, "root", 1)
rootRole, ok := root.Roles["root"]
if !ok {
c.Fatal("missing root role")
}
c.Assert(rootRole.KeyIDs, HasLen, 1)
c.Assert(rootRole.KeyIDs, DeepEquals, ids)
for _, keyID := range ids {
k, ok := root.Keys[keyID]
if !ok {
c.Fatalf("missing key %s", keyID)
}
c.Assert(k.IDs(), DeepEquals, ids)
pk, err := keys.GetVerifier(k)
c.Assert(err, IsNil)
c.Assert(pk.Public(), HasLen, ed25519.PublicKeySize)
}
// check root key + role are in db
db, err := r.topLevelKeysDB()
c.Assert(err, IsNil)
for _, keyID := range ids {
rootKey, err := db.GetVerifier(keyID)
c.Assert(err, IsNil)
c.Assert(rootKey.MarshalPublicKey().IDs(), DeepEquals, ids)
role := db.GetRole("root")
c.Assert(role.KeyIDs, DeepEquals, sets.StringSliceToSet(ids))
// check the key was saved correctly
localKeys, err := local.GetSigners("root")
c.Assert(err, IsNil)
c.Assert(localKeys, HasLen, 1)
c.Assert(localKeys[0].PublicData().IDs(), DeepEquals, ids)
// check RootKeys() is correct
rootKeys, err := r.RootKeys()
c.Assert(err, IsNil)
c.Assert(rootKeys, HasLen, 1)
c.Assert(rootKeys[0].IDs(), DeepEquals, rootKey.MarshalPublicKey().IDs())
pk, err := keys.GetVerifier(rootKeys[0])
c.Assert(err, IsNil)
c.Assert(pk.Public(), DeepEquals, rootKey.Public())
}
rootKey, err := db.GetVerifier(ids[0])
c.Assert(err, IsNil)
// generate two targets keys
generateAndAddPrivateKey(c, r, "targets")
generateAndAddPrivateKey(c, r, "targets")
// check root metadata is correct
root, err = r.root()
c.Assert(err, IsNil)
c.Assert(root.Roles, HasLen, 2)
rs.assertNumUniqueKeys(c, root, "root", 1)
rs.assertNumUniqueKeys(c, root, "targets", 2)
targetsRole, ok := root.Roles["targets"]
if !ok {
c.Fatal("missing targets role")
}
c.Assert(targetsRole.KeyIDs, HasLen, 2)
targetKeyIDs := make(map[string]struct{}, 2)
db, err = r.topLevelKeysDB()
c.Assert(err, IsNil)
for _, id := range targetsRole.KeyIDs {
targetKeyIDs[id] = struct{}{}
_, ok = root.Keys[id]
if !ok {
c.Fatal("missing key")
}
verifier, err := db.GetVerifier(id)
c.Assert(err, IsNil)
c.Assert(verifier.MarshalPublicKey().ContainsID(id), Equals, true)
}
role := db.GetRole("targets")
c.Assert(role.KeyIDs, DeepEquals, targetKeyIDs)
// check RootKeys() is unchanged
rootKeys, err := r.RootKeys()
c.Assert(err, IsNil)
c.Assert(rootKeys, HasLen, 1)
c.Assert(rootKeys[0].IDs(), DeepEquals, rootKey.MarshalPublicKey().IDs())
// check the keys were saved correctly
localKeys, err := local.GetSigners("targets")
c.Assert(err, IsNil)
c.Assert(localKeys, HasLen, 2)
for _, key := range localKeys {
found := false
for _, id := range targetsRole.KeyIDs {
if key.PublicData().ContainsID(id) {
found = true
break
}
}
if !found {
c.Fatal("missing key")
}
}
// check root.json got staged
meta, err := local.GetMeta()
c.Assert(err, IsNil)
rootJSON, ok := meta["root.json"]
if !ok {
c.Fatal("missing root metadata")
}
s := &data.Signed{}
c.Assert(json.Unmarshal(rootJSON, s), IsNil)
stagedRoot := &data.Root{}
c.Assert(json.Unmarshal(s.Signed, stagedRoot), IsNil)
c.Assert(stagedRoot.Type, Equals, root.Type)
c.Assert(stagedRoot.Version, Equals, root.Version)
c.Assert(stagedRoot.Expires.UnixNano(), Equals, root.Expires.UnixNano())
// make sure both root and stagedRoot have evaluated IDs(), otherwise
// DeepEquals will fail because those values might not have been
// computed yet.
for _, key := range root.Keys {
key.IDs()
}
for _, key := range stagedRoot.Keys {
key.IDs()
}
c.Assert(stagedRoot.Keys, DeepEquals, root.Keys)
c.Assert(stagedRoot.Roles, DeepEquals, root.Roles)
// commit to make sure we don't modify metadata after committing metadata.
generateAndAddPrivateKey(c, r, "snapshot")
generateAndAddPrivateKey(c, r, "timestamp")
c.Assert(r.AddTargets([]string{}, nil), IsNil)
c.Assert(r.Snapshot(), IsNil)
c.Assert(r.Timestamp(), IsNil)
c.Assert(r.Commit(), IsNil)
// add the same root key to make sure the metadata is unmodified.
oldRoot, err := r.root()
c.Assert(err, IsNil)
addPrivateKey(c, r, "root", signer)
newRoot, err := r.root()
c.Assert(err, IsNil)
c.Assert(oldRoot, DeepEquals, newRoot)
if r.local.FileIsStaged("root.json") {
c.Fatal("root should not be marked dirty")
}
}
func (rs *RepoSuite) TestRevokeKey(c *C) {
local := MemoryStore(make(map[string]json.RawMessage), nil)
r, err := NewRepo(local)
c.Assert(err, IsNil)
// revoking a key for an unknown role returns ErrInvalidRole
c.Assert(r.RevokeKey("foo", ""), DeepEquals, ErrInvalidRole{"foo", "only revocations for top-level roles supported"})
// revoking a key which doesn't exist returns ErrKeyNotFound
c.Assert(r.RevokeKey("root", "nonexistent"), DeepEquals, ErrKeyNotFound{"root", "nonexistent"})
// generate keys
genKey(c, r, "root")
target1IDs := genKey(c, r, "targets")
target2IDs := genKey(c, r, "targets")
genKey(c, r, "snapshot")
genKey(c, r, "timestamp")
root, err := r.root()
c.Assert(err, IsNil)
c.Assert(root.Roles, NotNil)
c.Assert(root.Roles, HasLen, 4)
c.Assert(root.Keys, NotNil)
rs.assertNumUniqueKeys(c, root, "root", 1)
rs.assertNumUniqueKeys(c, root, "targets", 2)
rs.assertNumUniqueKeys(c, root, "snapshot", 1)
rs.assertNumUniqueKeys(c, root, "timestamp", 1)
// revoke a key
targetsRole, ok := root.Roles["targets"]
if !ok {
c.Fatal("missing targets role")
}
c.Assert(targetsRole.KeyIDs, HasLen, len(target1IDs)+len(target2IDs))
id := targetsRole.KeyIDs[0]
c.Assert(r.RevokeKey("targets", id), IsNil)
// make sure all the other key ids were also revoked
for _, id := range target1IDs {
c.Assert(r.RevokeKey("targets", id), DeepEquals, ErrKeyNotFound{"targets", id})
}
// check root was updated
root, err = r.root()
c.Assert(err, IsNil)
c.Assert(root.Roles, NotNil)
c.Assert(root.Roles, HasLen, 4)
c.Assert(root.Keys, NotNil)
rs.assertNumUniqueKeys(c, root, "root", 1)
rs.assertNumUniqueKeys(c, root, "targets", 1)
rs.assertNumUniqueKeys(c, root, "snapshot", 1)
rs.assertNumUniqueKeys(c, root, "timestamp", 1)
targetsRole, ok = root.Roles["targets"]
if !ok {
c.Fatal("missing targets role")
}
c.Assert(targetsRole.KeyIDs, HasLen, 1)
c.Assert(targetsRole.KeyIDs, DeepEquals, target2IDs)
}
func (rs *RepoSuite) TestRevokeKeyInMultipleRoles(c *C) {
local := MemoryStore(make(map[string]json.RawMessage), nil)
r, err := NewRepo(local)
c.Assert(err, IsNil)
// generate keys. add a root key that is shared with the targets role
rootSigner, err := keys.GenerateEd25519Key()
c.Assert(err, IsNil)
c.Assert(r.AddVerificationKey("root", rootSigner.PublicData()), IsNil)
sharedSigner, err := keys.GenerateEd25519Key()
c.Assert(err, IsNil)
sharedIDs := sharedSigner.PublicData().IDs()
c.Assert(r.AddVerificationKey("root", sharedSigner.PublicData()), IsNil)
c.Assert(r.AddVerificationKey("targets", sharedSigner.PublicData()), IsNil)
targetIDs := genKey(c, r, "targets")
genKey(c, r, "snapshot")
genKey(c, r, "timestamp")
root, err := r.root()
c.Assert(err, IsNil)
c.Assert(root.Roles, NotNil)
c.Assert(root.Roles, HasLen, 4)
c.Assert(root.Keys, NotNil)
rs.assertNumUniqueKeys(c, root, "root", 2)
rs.assertNumUniqueKeys(c, root, "targets", 2)
rs.assertNumUniqueKeys(c, root, "snapshot", 1)
rs.assertNumUniqueKeys(c, root, "timestamp", 1)
// revoke a key
targetsRole, ok := root.Roles["targets"]
if !ok {
c.Fatal("missing targets role")
}
c.Assert(targetsRole.KeyIDs, HasLen, len(targetIDs)+len(sharedIDs))
id := targetsRole.KeyIDs[0]
c.Assert(r.RevokeKey("targets", id), IsNil)
// make sure all the other key ids were also revoked
for _, id := range sharedIDs {
c.Assert(r.RevokeKey("targets", id), DeepEquals, ErrKeyNotFound{"targets", id})
}
// check root was updated
root, err = r.root()
c.Assert(err, IsNil)
c.Assert(root.Roles, NotNil)
c.Assert(root.Roles, HasLen, 4)
c.Assert(root.Keys, NotNil)
// the shared root/targets signer should still be present in root keys
c.Assert(UniqueKeys(root)["root"], DeepEquals,
[]*data.PublicKey{rootSigner.PublicData(), sharedSigner.PublicData()})
rs.assertNumUniqueKeys(c, root, "root", 2)
rs.assertNumUniqueKeys(c, root, "targets", 1)
rs.assertNumUniqueKeys(c, root, "snapshot", 1)
rs.assertNumUniqueKeys(c, root, "timestamp", 1)
targetsRole, ok = root.Roles["targets"]
if !ok {
c.Fatal("missing targets role")
}
c.Assert(targetsRole.KeyIDs, HasLen, 1)
c.Assert(targetsRole.KeyIDs, DeepEquals, targetIDs)
}
func (rs *RepoSuite) TestSign(c *C) {
meta := map[string]json.RawMessage{"root.json": []byte(`{"signed":{},"signatures":[]}`)}
local := MemoryStore(meta, nil)
r, err := NewRepo(local)
c.Assert(err, IsNil)
c.Assert(r.Sign("foo.json"), Equals, ErrMissingMetadata{"foo.json"})
// signing with no keys returns ErrNoKeys
c.Assert(r.Sign("root.json"), Equals, ErrNoKeys{"root.json"})
checkSigIDs := func(keyIDs ...string) {
meta, err := local.GetMeta()
c.Assert(err, IsNil)
rootJSON, ok := meta["root.json"]
if !ok {
c.Fatal("missing root.json")
}
s := &data.Signed{}
c.Assert(json.Unmarshal(rootJSON, s), IsNil)
c.Assert(s.Signatures, HasLen, len(keyIDs))
// Signatures may be in any order, so must sort key IDs before comparison.
wantKeyIDs := append([]string{}, keyIDs...)
sort.Strings(wantKeyIDs)
gotKeyIDs := []string{}
for _, sig := range s.Signatures {
gotKeyIDs = append(gotKeyIDs, sig.KeyID)
}
sort.Strings(gotKeyIDs)
c.Assert(wantKeyIDs, DeepEquals, gotKeyIDs)
}
// signing with an available key generates a signature
signer, err := keys.GenerateEd25519Key()
c.Assert(err, IsNil)
c.Assert(local.SaveSigner("root", signer), IsNil)
c.Assert(r.Sign("root.json"), IsNil)
checkSigIDs(signer.PublicData().IDs()...)
// signing again does not generate a duplicate signature
c.Assert(r.Sign("root.json"), IsNil)
checkSigIDs(signer.PublicData().IDs()...)
// signing with a new available key generates another signature
newKey, err := keys.GenerateEd25519Key()
c.Assert(err, IsNil)
c.Assert(local.SaveSigner("root", newKey), IsNil)
c.Assert(r.Sign("root.json"), IsNil)
checkSigIDs(append(signer.PublicData().IDs(), newKey.PublicData().IDs()...)...)
// attempt to sign missing metadata
c.Assert(r.Sign("targets.json"), Equals, ErrMissingMetadata{"targets.json"})
}
func (rs *RepoSuite) TestStatus(c *C) {
files := map[string][]byte{"foo.txt": []byte("foo")}
local := MemoryStore(make(map[string]json.RawMessage), files)
r, err := NewRepo(local)
c.Assert(err, IsNil)
genKey(c, r, "root")
genKey(c, r, "targets")
genKey(c, r, "snapshot")
genKey(c, r, "timestamp")
c.Assert(r.AddTarget("foo.txt", nil), IsNil)
c.Assert(r.SnapshotWithExpires(time.Now().Add(24*time.Hour)), IsNil)
c.Assert(r.TimestampWithExpires(time.Now().Add(1*time.Hour)), IsNil)
c.Assert(r.Commit(), IsNil)
expires := time.Now().Add(2 * time.Hour)
c.Assert(r.CheckRoleUnexpired("timestamp", expires), ErrorMatches, "role expired on.*")
c.Assert(r.CheckRoleUnexpired("snapshot", expires), IsNil)
c.Assert(r.CheckRoleUnexpired("targets", expires), IsNil)
c.Assert(r.CheckRoleUnexpired("root", expires), IsNil)
}
func (rs *RepoSuite) TestCommit(c *C) {
files := map[string][]byte{"foo.txt": []byte("foo"), "bar.txt": []byte("bar")}
local := MemoryStore(make(map[string]json.RawMessage), files)
r, err := NewRepo(local)
c.Assert(err, IsNil)
// commit without root.json
c.Assert(r.Commit(), DeepEquals, ErrMissingMetadata{"root.json"})
// Init should create targets.json, but not signed yet
r.Init(false)
c.Assert(r.Commit(), DeepEquals, ErrMissingMetadata{"snapshot.json"})
genKey(c, r, "root")
// commit without snapshot.json
genKey(c, r, "targets")
c.Assert(r.Sign("targets.json"), IsNil)
c.Assert(r.Commit(), DeepEquals, ErrMissingMetadata{"snapshot.json"})
// commit without timestamp.json
genKey(c, r, "snapshot")
c.Assert(r.Snapshot(), IsNil)
c.Assert(r.Commit(), DeepEquals, ErrMissingMetadata{"timestamp.json"})
// commit with timestamp.json but no timestamp key
c.Assert(r.Timestamp(), IsNil)
c.Assert(r.Commit(), DeepEquals, ErrInsufficientSignatures{"timestamp.json", verify.ErrNoSignatures})
// commit success
genKey(c, r, "timestamp")
c.Assert(r.Snapshot(), IsNil)
c.Assert(r.Timestamp(), IsNil)
c.Assert(r.Commit(), IsNil)
// commit with an invalid root hash in snapshot.json due to new key creation
genKey(c, r, "targets")
c.Assert(r.Sign("targets.json"), IsNil)
c.Assert(r.Commit(), DeepEquals, errors.New("tuf: invalid targets.json in snapshot.json: wrong length, expected 338 got 552"))
// commit with an invalid targets hash in snapshot.json
c.Assert(r.Snapshot(), IsNil)
c.Assert(r.AddTarget("bar.txt", nil), IsNil)
c.Assert(r.Commit(), DeepEquals, errors.New("tuf: invalid targets.json in snapshot.json: wrong length, expected 552 got 725"))
// commit with an invalid timestamp
c.Assert(r.Snapshot(), IsNil)
err = r.Commit()
c.Assert(err, NotNil)
c.Assert(err.Error()[0:44], Equals, "tuf: invalid snapshot.json in timestamp.json")
// commit with a role's threshold greater than number of keys
root, err := r.root()
c.Assert(err, IsNil)
role, ok := root.Roles["timestamp"]
if !ok {
c.Fatal("missing timestamp role")
}
c.Assert(role.KeyIDs, HasLen, 1)
c.Assert(role.Threshold, Equals, 1)
c.Assert(r.RevokeKey("timestamp", role.KeyIDs[0]), IsNil)
c.Assert(r.Snapshot(), IsNil)
c.Assert(r.Timestamp(), IsNil)
c.Assert(r.Commit(), DeepEquals, ErrNotEnoughKeys{"timestamp", 0, 1})
}
func (rs *RepoSuite) TestCommitVersions(c *C) {
files := map[string][]byte{"foo.txt": []byte("foo")}
local := MemoryStore(make(map[string]json.RawMessage), files)
r, err := NewRepo(local)
c.Assert(err, IsNil)
genKey(c, r, "root")
genKey(c, r, "targets")
genKey(c, r, "snapshot")
genKey(c, r, "timestamp")
c.Assert(r.AddTarget("foo.txt", nil), IsNil)
c.Assert(r.Snapshot(), IsNil)
c.Assert(r.Timestamp(), IsNil)
c.Assert(r.Commit(), IsNil)
// on initial commit everything should be at version 1.
rootVersion, err := r.RootVersion()
c.Assert(err, IsNil)
c.Assert(rootVersion, Equals, int64(1))
targetsVersion, err := r.TargetsVersion()
c.Assert(err, IsNil)
c.Assert(targetsVersion, Equals, int64(1))
snapshotVersion, err := r.SnapshotVersion()
c.Assert(err, IsNil)
c.Assert(snapshotVersion, Equals, int64(1))
timestampVersion, err := r.SnapshotVersion()
c.Assert(err, IsNil)
c.Assert(timestampVersion, Equals, int64(1))
// taking a snapshot should only increment snapshot and timestamp.
c.Assert(r.Snapshot(), IsNil)
c.Assert(r.Timestamp(), IsNil)
c.Assert(r.Commit(), IsNil)
rootVersion, err = r.RootVersion()
c.Assert(err, IsNil)
c.Assert(rootVersion, Equals, int64(1))
targetsVersion, err = r.TargetsVersion()
c.Assert(err, IsNil)
c.Assert(targetsVersion, Equals, int64(1))
snapshotVersion, err = r.SnapshotVersion()
c.Assert(err, IsNil)
c.Assert(snapshotVersion, Equals, int64(2))
timestampVersion, err = r.SnapshotVersion()
c.Assert(err, IsNil)
c.Assert(timestampVersion, Equals, int64(2))
// rotating multiple keys should increment the root once.
genKey(c, r, "targets")
genKey(c, r, "snapshot")
genKey(c, r, "timestamp")
c.Assert(r.Snapshot(), IsNil)
c.Assert(r.Timestamp(), IsNil)
c.Assert(r.Commit(), IsNil)
rootVersion, err = r.RootVersion()
c.Assert(err, IsNil)
c.Assert(rootVersion, Equals, int64(2))
targetsVersion, err = r.TargetsVersion()
c.Assert(err, IsNil)
c.Assert(targetsVersion, Equals, int64(1))
snapshotVersion, err = r.SnapshotVersion()
c.Assert(err, IsNil)
c.Assert(snapshotVersion, Equals, int64(3))
timestampVersion, err = r.TimestampVersion()
c.Assert(err, IsNil)
c.Assert(timestampVersion, Equals, int64(3))
}
type tmpDir struct {
path string
c *C
}
func newTmpDir(c *C) *tmpDir {
return &tmpDir{path: c.MkDir(), c: c}
}
func (t *tmpDir) assertExists(path string) {
if _, err := os.Stat(filepath.Join(t.path, path)); os.IsNotExist(err) {
t.c.Fatalf("expected path to exist but it doesn't: %s", path)
}
}
func (t *tmpDir) assertNotExist(path string) {
if _, err := os.Stat(filepath.Join(t.path, path)); !os.IsNotExist(err) {
t.c.Fatalf("expected path to not exist but it does: %s", path)
}
}
func (t *tmpDir) assertHashedFilesExist(path string, hashes data.Hashes) {
t.c.Assert(len(hashes) > 0, Equals, true)
for _, path := range util.HashedPaths(path, hashes) {
t.assertExists(path)
}
}
func (t *tmpDir) assertHashedFilesNotExist(path string, hashes data.Hashes) {
for _, path := range util.HashedPaths(path, hashes) {
t.assertNotExist(path)
}
}
func (t *tmpDir) assertVersionedFileExist(path string, version int64) {
t.assertExists(util.VersionedPath(path, version))
}
func (t *tmpDir) assertVersionedFileNotExist(path string, version int64) {
t.assertNotExist(util.VersionedPath(path, version))
}
func (t *tmpDir) assertEmpty(dir string) {
path := filepath.Join(t.path, dir)
f, err := os.Stat(path)
if os.IsNotExist(err) {
t.c.Fatalf("expected dir to exist but it doesn't: %s", dir)
}
t.c.Assert(err, IsNil)
t.c.Assert(f.IsDir(), Equals, true)
entries, err := os.ReadDir(path)
t.c.Assert(err, IsNil)
// check that all (if any) entries are also empty
for _, e := range entries {
t.assertEmpty(filepath.Join(dir, e.Name()))
}
}
func (t *tmpDir) assertFileContent(path, content string) {
actual := t.readFile(path)
t.c.Assert(string(actual), Equals, content)
}
func (t *tmpDir) stagedTargetPath(path string) string {
return filepath.Join(t.path, "staged", "targets", path)
}
func (t *tmpDir) writeStagedTarget(path, data string) {
path = t.stagedTargetPath(path)
t.c.Assert(os.MkdirAll(filepath.Dir(path), 0755), IsNil)
t.c.Assert(os.WriteFile(path, []byte(data), 0644), IsNil)
}
func (t *tmpDir) readFile(path string) []byte {
t.assertExists(path)
data, err := os.ReadFile(filepath.Join(t.path, path))
t.c.Assert(err, IsNil)
return data
}
func (rs *RepoSuite) TestCommitFileSystem(c *C) {
tmp := newTmpDir(c)
local := FileSystemStore(tmp.path, nil)
r, err := NewRepo(local)
c.Assert(err, IsNil)
// don't use consistent snapshots to make the checks simpler
c.Assert(r.Init(false), IsNil)
// cleaning with nothing staged or committed should fail
c.Assert(r.Clean(), Equals, ErrNewRepository)
// generating keys should stage root.json and create repo dirs
genKey(c, r, "root")
genKey(c, r, "targets")
genKey(c, r, "snapshot")
genKey(c, r, "timestamp")
tmp.assertExists("staged/root.json")
tmp.assertEmpty("repository")
tmp.assertEmpty("staged/targets")
// cleaning with nothing committed should fail
c.Assert(r.Clean(), Equals, ErrNewRepository)
// adding a non-existent file fails
c.Assert(r.AddTarget("foo.txt", nil), Equals, ErrFileNotFound{tmp.stagedTargetPath("foo.txt")})
tmp.assertEmpty("repository")
// adding a file stages targets.json
tmp.writeStagedTarget("foo.txt", "foo")
c.Assert(r.AddTarget("foo.txt", nil), IsNil)
tmp.assertExists("staged/targets.json")
tmp.assertEmpty("repository")
t, err := r.topLevelTargets()
c.Assert(err, IsNil)
c.Assert(t.Targets, HasLen, 1)
if _, ok := t.Targets["foo.txt"]; !ok {
c.Fatal("missing target file: foo.txt")
}
// Snapshot() stages snapshot.json
c.Assert(r.Snapshot(), IsNil)
tmp.assertExists("staged/snapshot.json")
tmp.assertEmpty("repository")
// Timestamp() stages timestamp.json
c.Assert(r.Timestamp(), IsNil)
tmp.assertExists("staged/timestamp.json")
tmp.assertEmpty("repository")
// committing moves files from staged -> repository
c.Assert(r.Commit(), IsNil)
tmp.assertExists("repository/root.json")
tmp.assertExists("repository/targets.json")
tmp.assertExists("repository/snapshot.json")
tmp.assertExists("repository/timestamp.json")
tmp.assertFileContent("repository/targets/foo.txt", "foo")
tmp.assertEmpty("staged/targets")
tmp.assertEmpty("staged")