-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
109 lines (98 loc) · 2.48 KB
/
utils.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
package utils
import (
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"fmt"
"io"
"github.com/docker/notary/tuf/data"
)
// StrSliceContains checks if the given string appears in the slice
func StrSliceContains(ss []string, s string) bool {
for _, v := range ss {
if v == s {
return true
}
}
return false
}
// StrSliceRemove removes the the given string from the slice, returning a new slice
func StrSliceRemove(ss []string, s string) []string {
res := []string{}
for _, v := range ss {
if v != s {
res = append(res, v)
}
}
return res
}
// NoopCloser is a simple Reader wrapper that does nothing when Close is
// called
type NoopCloser struct {
io.Reader
}
// Close does nothing for a NoopCloser
func (nc *NoopCloser) Close() error {
return nil
}
// DoHash returns the digest of d using the hashing algorithm named
// in alg
func DoHash(alg string, d []byte) []byte {
switch alg {
case "sha256":
digest := sha256.Sum256(d)
return digest[:]
case "sha512":
digest := sha512.Sum512(d)
return digest[:]
}
return nil
}
// UnusedDelegationKeys prunes a list of keys, returning those that are no
// longer in use for a given targets file
func UnusedDelegationKeys(t data.SignedTargets) []string {
// compare ids to all still active key ids in all active roles
// with the targets file
found := make(map[string]bool)
for _, r := range t.Signed.Delegations.Roles {
for _, id := range r.KeyIDs {
found[id] = true
}
}
var discard []string
for id := range t.Signed.Delegations.Keys {
if !found[id] {
discard = append(discard, id)
}
}
return discard
}
// RemoveUnusedKeys determines which keys in the slice of IDs are no longer
// used in the given targets file and removes them from the delegated keys
// map
func RemoveUnusedKeys(t *data.SignedTargets) {
unusedIDs := UnusedDelegationKeys(*t)
for _, id := range unusedIDs {
delete(t.Signed.Delegations.Keys, id)
}
}
// FindRoleIndex returns the index of the role named <name> or -1 if no
// matching role is found.
func FindRoleIndex(rs []*data.Role, name string) int {
for i, r := range rs {
if r.Name == name {
return i
}
}
return -1
}
// ConsistentName generates the appropriate HTTP URL path for the role,
// based on whether the repo is marked as consistent. The RemoteStore
// is responsible for adding file extensions.
func ConsistentName(role string, hashSha256 []byte) string {
if len(hashSha256) > 0 {
hash := hex.EncodeToString(hashSha256)
return fmt.Sprintf("%s.%s", role, hash)
}
return role
}