forked from theupdateframework/go-tuf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
local_store.go
527 lines (479 loc) · 12.7 KB
/
local_store.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
package tuf
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/theupdateframework/go-tuf/data"
"github.com/theupdateframework/go-tuf/encrypted"
"github.com/theupdateframework/go-tuf/pkg/keys"
"github.com/theupdateframework/go-tuf/util"
)
func signers(privateKeys []*data.PrivateKey) []keys.Signer {
res := make([]keys.Signer, 0, len(privateKeys))
for _, k := range privateKeys {
signer, err := keys.GetSigner(k)
if err != nil {
continue
}
res = append(res, signer)
}
return res
}
func MemoryStore(meta map[string]json.RawMessage, files map[string][]byte) LocalStore {
if meta == nil {
meta = make(map[string]json.RawMessage)
}
return &memoryStore{
meta: meta,
stagedMeta: make(map[string]json.RawMessage),
files: files,
signers: make(map[string][]keys.Signer),
}
}
type memoryStore struct {
meta map[string]json.RawMessage
stagedMeta map[string]json.RawMessage
files map[string][]byte
signers map[string][]keys.Signer
}
func (m *memoryStore) GetMeta() (map[string]json.RawMessage, error) {
meta := make(map[string]json.RawMessage, len(m.meta)+len(m.stagedMeta))
for key, value := range m.meta {
meta[key] = value
}
for key, value := range m.stagedMeta {
meta[key] = value
}
return meta, nil
}
func (m *memoryStore) SetMeta(name string, meta json.RawMessage) error {
m.stagedMeta[name] = meta
return nil
}
func (m *memoryStore) FileIsStaged(name string) bool {
_, ok := m.stagedMeta[name]
return ok
}
func (m *memoryStore) WalkStagedTargets(paths []string, targetsFn TargetsWalkFunc) error {
if len(paths) == 0 {
for path, data := range m.files {
if err := targetsFn(path, bytes.NewReader(data)); err != nil {
return err
}
}
return nil
}
for _, path := range paths {
data, ok := m.files[path]
if !ok {
return ErrFileNotFound{path}
}
if err := targetsFn(path, bytes.NewReader(data)); err != nil {
return err
}
}
return nil
}
func (m *memoryStore) Commit(consistentSnapshot bool, versions map[string]int, hashes map[string]data.Hashes) error {
for name, meta := range m.stagedMeta {
paths := computeMetadataPaths(consistentSnapshot, name, versions)
for _, path := range paths {
m.meta[path] = meta
}
// Remove from staged metadata.
// This will prompt incrementing version numbers again now that we've
// successfully committed the metadata to the local store.
delete(m.stagedMeta, name)
}
return nil
}
func (m *memoryStore) GetSigners(role string) ([]keys.Signer, error) {
return m.signers[role], nil
}
func (m *memoryStore) SaveSigner(role string, signer keys.Signer) error {
m.signers[role] = append(m.signers[role], signer)
return nil
}
func (m *memoryStore) Clean() error {
return nil
}
type persistedKeys struct {
Encrypted bool `json:"encrypted"`
Data json.RawMessage `json:"data"`
}
func FileSystemStore(dir string, p util.PassphraseFunc) LocalStore {
return &fileSystemStore{
dir: dir,
passphraseFunc: p,
signers: make(map[string][]keys.Signer),
}
}
type fileSystemStore struct {
dir string
passphraseFunc util.PassphraseFunc
// signers is a cache of persisted keys to avoid decrypting multiple times
signers map[string][]keys.Signer
}
func (f *fileSystemStore) repoDir() string {
return filepath.Join(f.dir, "repository")
}
func (f *fileSystemStore) stagedDir() string {
return filepath.Join(f.dir, "staged")
}
func (f *fileSystemStore) GetMeta() (map[string]json.RawMessage, error) {
meta := make(map[string]json.RawMessage)
var err error
notExists := func(path string) bool {
_, err := os.Stat(path)
return os.IsNotExist(err)
}
for _, name := range topLevelMetadata {
path := filepath.Join(f.stagedDir(), name)
if notExists(path) {
path = filepath.Join(f.repoDir(), name)
if notExists(path) {
continue
}
}
meta[name], err = ioutil.ReadFile(path)
if err != nil {
return nil, err
}
}
return meta, nil
}
func (f *fileSystemStore) SetMeta(name string, meta json.RawMessage) error {
if err := f.createDirs(); err != nil {
return err
}
if err := util.AtomicallyWriteFile(filepath.Join(f.stagedDir(), name), meta, 0644); err != nil {
return err
}
return nil
}
func (f *fileSystemStore) FileIsStaged(name string) bool {
_, err := os.Stat(filepath.Join(f.stagedDir(), name))
return err == nil
}
func (f *fileSystemStore) createDirs() error {
for _, dir := range []string{"keys", "repository", "staged/targets"} {
if err := os.MkdirAll(filepath.Join(f.dir, dir), 0755); err != nil {
return err
}
}
return nil
}
func (f *fileSystemStore) WalkStagedTargets(paths []string, targetsFn TargetsWalkFunc) error {
if len(paths) == 0 {
walkFunc := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() || !info.Mode().IsRegular() {
return nil
}
rel, err := filepath.Rel(filepath.Join(f.stagedDir(), "targets"), path)
if err != nil {
return err
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
return targetsFn(rel, file)
}
return filepath.Walk(filepath.Join(f.stagedDir(), "targets"), walkFunc)
}
// check all the files exist before processing any files
for _, path := range paths {
realPath := filepath.Join(f.stagedDir(), "targets", path)
if _, err := os.Stat(realPath); err != nil {
if os.IsNotExist(err) {
return ErrFileNotFound{realPath}
}
return err
}
}
for _, path := range paths {
realPath := filepath.Join(f.stagedDir(), "targets", path)
file, err := os.Open(realPath)
if err != nil {
if os.IsNotExist(err) {
return ErrFileNotFound{realPath}
}
return err
}
err = targetsFn(path, file)
file.Close()
if err != nil {
return err
}
}
return nil
}
func (f *fileSystemStore) createRepoFile(path string) (*os.File, error) {
dst := filepath.Join(f.repoDir(), path)
if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
return nil, err
}
return os.Create(dst)
}
func (f *fileSystemStore) Commit(consistentSnapshot bool, versions map[string]int, hashes map[string]data.Hashes) error {
isTarget := func(path string) bool {
return strings.HasPrefix(path, "targets/")
}
copyToRepo := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() || !info.Mode().IsRegular() {
return nil
}
rel, err := filepath.Rel(f.stagedDir(), path)
if err != nil {
return err
}
var paths []string
if isTarget(rel) {
paths = computeTargetPaths(consistentSnapshot, rel, hashes)
} else {
paths = computeMetadataPaths(consistentSnapshot, rel, versions)
}
var files []io.Writer
for _, path := range paths {
file, err := f.createRepoFile(path)
if err != nil {
return err
}
defer file.Close()
files = append(files, file)
}
staged, err := os.Open(path)
if err != nil {
return err
}
defer staged.Close()
if _, err = io.Copy(io.MultiWriter(files...), staged); err != nil {
return err
}
return nil
}
needsRemoval := func(path string) bool {
if consistentSnapshot {
// strip out the hash
name := strings.SplitN(filepath.Base(path), ".", 2)
if len(name) != 2 || name[1] == "" {
return false
}
path = filepath.Join(filepath.Dir(path), name[1])
}
_, ok := hashes[path]
return !ok
}
removeFile := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
rel, err := filepath.Rel(f.repoDir(), path)
if err != nil {
return err
}
if !info.IsDir() && isTarget(rel) && needsRemoval(rel) {
//lint:ignore SA9003 empty branch
if err := os.Remove(path); err != nil {
// TODO: log / handle error
}
// TODO: remove empty directory
}
return nil
}
if err := filepath.Walk(f.stagedDir(), copyToRepo); err != nil {
return err
}
if err := filepath.Walk(f.repoDir(), removeFile); err != nil {
return err
}
return f.Clean()
}
func (f *fileSystemStore) GetSigners(role string) ([]keys.Signer, error) {
if keys, ok := f.signers[role]; ok {
return keys, nil
}
keys, _, err := f.loadPrivateKeys(role)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
f.signers[role] = signers(keys)
return f.signers[role], nil
}
// ChangePassphrase changes the passphrase for a role keys file. Implements
// PassphraseChanger interface.
func (f *fileSystemStore) ChangePassphrase(role string) error {
// No need to proceed if passphrase func is not set
if f.passphraseFunc == nil {
return ErrPassphraseRequired{role}
}
// Read the existing keys (if any)
// If encrypted, will prompt for existing passphrase
keys, _, err := f.loadPrivateKeys(role)
if err != nil {
if os.IsNotExist(err) {
fmt.Printf("Failed to change passphrase. Missing keys file for %s role. \n", role)
}
return err
}
// Prompt for new passphrase
pass, err := f.passphraseFunc(role, true, true)
if err != nil {
return err
}
// Proceed saving the keys
pk := &persistedKeys{Encrypted: true}
pk.Data, err = encrypted.Marshal(keys, pass)
if err != nil {
return err
}
data, err := json.MarshalIndent(pk, "", "\t")
if err != nil {
return err
}
if err := util.AtomicallyWriteFile(f.keysPath(role), append(data, '\n'), 0600); err != nil {
return err
}
fmt.Printf("Successfully changed passphrase for %s keys file\n", role)
return nil
}
func (f *fileSystemStore) SaveSigner(role string, signer keys.Signer) error {
if err := f.createDirs(); err != nil {
return err
}
// add the key to the existing keys (if any)
keys, pass, err := f.loadPrivateKeys(role)
if err != nil && !os.IsNotExist(err) {
return err
}
key, err := signer.MarshalPrivateKey()
if err != nil {
return err
}
keys = append(keys, key)
// if loadPrivateKeys didn't return a passphrase (because no keys yet exist)
// and passphraseFunc is set, get the passphrase so the keys file can
// be encrypted later (passphraseFunc being nil indicates the keys file
// should not be encrypted)
if pass == nil && f.passphraseFunc != nil {
pass, err = f.passphraseFunc(role, true, false)
if err != nil {
return err
}
}
pk := &persistedKeys{}
if pass != nil {
pk.Data, err = encrypted.Marshal(keys, pass)
if err != nil {
return err
}
pk.Encrypted = true
} else {
pk.Data, err = json.MarshalIndent(keys, "", "\t")
if err != nil {
return err
}
}
data, err := json.MarshalIndent(pk, "", "\t")
if err != nil {
return err
}
if err := util.AtomicallyWriteFile(f.keysPath(role), append(data, '\n'), 0600); err != nil {
return err
}
f.signers[role] = append(f.signers[role], signer)
return nil
}
// loadPrivateKeys loads keys for the given role and returns them along with the
// passphrase (if read) so that callers don't need to re-read it.
func (f *fileSystemStore) loadPrivateKeys(role string) ([]*data.PrivateKey, []byte, error) {
file, err := os.Open(f.keysPath(role))
if err != nil {
return nil, nil, err
}
defer file.Close()
pk := &persistedKeys{}
if err := json.NewDecoder(file).Decode(pk); err != nil {
return nil, nil, err
}
var keys []*data.PrivateKey
if !pk.Encrypted {
if err := json.Unmarshal(pk.Data, &keys); err != nil {
return nil, nil, err
}
return keys, nil, nil
}
// the keys are encrypted so cannot be loaded if passphraseFunc is not set
if f.passphraseFunc == nil {
return nil, nil, ErrPassphraseRequired{role}
}
// try the empty string as the password first
pass := []byte("")
if err := encrypted.Unmarshal(pk.Data, &keys, pass); err != nil {
pass, err = f.passphraseFunc(role, false, false)
if err != nil {
return nil, nil, err
}
if err = encrypted.Unmarshal(pk.Data, &keys, pass); err != nil {
return nil, nil, err
}
}
return keys, pass, nil
}
func (f *fileSystemStore) keysPath(role string) string {
return filepath.Join(f.dir, "keys", role+".json")
}
func (f *fileSystemStore) Clean() error {
_, err := os.Stat(filepath.Join(f.repoDir(), "root.json"))
if os.IsNotExist(err) {
return ErrNewRepository
} else if err != nil {
return err
}
if err := os.RemoveAll(f.stagedDir()); err != nil {
return err
}
return os.MkdirAll(filepath.Join(f.stagedDir(), "targets"), 0755)
}
func computeTargetPaths(consistentSnapshot bool, name string, hashes map[string]data.Hashes) []string {
if consistentSnapshot {
return util.HashedPaths(name, hashes[name])
} else {
return []string{name}
}
}
func computeMetadataPaths(consistentSnapshot bool, name string, versions map[string]int) []string {
copyVersion := false
switch name {
case "root.json":
copyVersion = true
case "timestamp.json":
copyVersion = false
default:
if consistentSnapshot {
copyVersion = true
} else {
copyVersion = false
}
}
paths := []string{name}
if copyVersion {
paths = append(paths, util.VersionedPath(name, versions[name]))
}
return paths
}