forked from sigstore/cosign
/
tuf_policy.go
232 lines (202 loc) · 5.67 KB
/
tuf_policy.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
//
// Copyright 2024 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// For backwards compatibility
// Verbatim copy of https://github.com/sigstore/sigstore/blob/v1.4.5/pkg/tuf/policy.go
package cli
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"sync"
"time"
cjson "github.com/secure-systems-lab/go-securesystemslib/cjson"
)
type Signed struct {
Signed json.RawMessage `json:"signed"`
Signatures []Signature `json:"signatures"`
}
type Signature struct {
KeyID string `json:"keyid"`
Signature string `json:"sig"`
Cert string `json:"cert,omitempty"`
}
type Key struct {
Type string `json:"keytype"`
Scheme string `json:"scheme"`
Algorithms []string `json:"keyid_hash_algorithms,omitempty"`
Value json.RawMessage `json:"keyval"`
id string
idOnce sync.Once
}
func (k *Key) ID() string {
k.idOnce.Do(func() {
data, _ := cjson.EncodeCanonical(k)
digest := sha256.Sum256(data)
k.id = hex.EncodeToString(digest[:])
})
return k.id
}
func (k *Key) ContainsID(id string) bool {
return id == k.ID()
}
type Root struct {
Type string `json:"_type"`
SpecVersion string `json:"spec_version"`
Version int `json:"version"`
Expires time.Time `json:"expires"`
Keys map[string]*Key `json:"keys"`
Roles map[string]*Role `json:"roles"`
Namespace string `json:"namespace"`
ConsistentSnapshot bool `json:"consistent_snapshot"`
}
func NewRoot() *Root {
return &Root{
Type: "root",
SpecVersion: "1.0",
Version: 1,
// Default expires in 3 months
Expires: time.Now().AddDate(0, 3, 0).UTC().Round(time.Second),
Keys: make(map[string]*Key),
Roles: make(map[string]*Role),
ConsistentSnapshot: true,
}
}
func (r *Root) AddKey(key *Key) bool {
changed := false
if _, ok := r.Keys[key.ID()]; !ok {
changed = true
r.Keys[key.ID()] = key
}
return changed
}
type Role struct {
KeyIDs []string `json:"keyids"`
Threshold int `json:"threshold"`
}
func (r *Role) AddKeysWithThreshold(keys []*Key, threshold int) bool {
roleIDs := make(map[string]struct{})
for _, id := range r.KeyIDs {
roleIDs[id] = struct{}{}
}
changed := false
for _, key := range keys {
if _, ok := roleIDs[key.ID()]; !ok {
changed = true
r.KeyIDs = append(r.KeyIDs, key.ID())
}
}
r.Threshold = threshold
return changed
}
func (r *Root) Marshal() (*Signed, error) {
// Marshals the Root into a Signed type
b, err := cjson.EncodeCanonical(r)
if err != nil {
return nil, err
}
return &Signed{Signed: b}, nil
}
func (r *Root) ValidKey(key *Key, role string) (string, error) {
// Checks if id is a valid key for role by matching the identity and issuer if specified.
// Returns the key ID or an error if invalid key.
fulcioKeyVal, err := GetFulcioKeyVal(key)
if err != nil {
return "", fmt.Errorf("error parsing signer key: %w", err)
}
result := ""
for keyid, rootKey := range r.Keys {
fulcioRootKeyVal, err := GetFulcioKeyVal(rootKey)
if err != nil {
return "", fmt.Errorf("error parsing root key: %w", err)
}
if fulcioKeyVal.Identity == fulcioRootKeyVal.Identity {
if fulcioRootKeyVal.Issuer == "" || fulcioRootKeyVal.Issuer == fulcioKeyVal.Issuer {
result = keyid
break
}
}
}
if result == "" {
return "", errors.New("key not found in root keys")
}
rootRole, ok := r.Roles[role]
if !ok {
return "", errors.New("invalid role")
}
for _, id := range rootRole.KeyIDs {
if id == result {
return result, nil
}
}
return "", errors.New("key not found in role")
}
func (s *Signed) JSONMarshal(prefix, indent string) ([]byte, error) {
// Marshals Signed with prefix and indent.
b, err := cjson.EncodeCanonical(s)
if err != nil {
return []byte{}, err
}
var out bytes.Buffer
if err := json.Indent(&out, b, prefix, indent); err != nil {
return []byte{}, err
}
return out.Bytes(), nil
}
func (s *Signed) AddOrUpdateSignature(key *Key, signature Signature) error {
root := &Root{}
if err := json.Unmarshal(s.Signed, root); err != nil {
return fmt.Errorf("unmarshalling root policy: %w", err)
}
var err error
signature.KeyID, err = root.ValidKey(key, "root")
if err != nil {
return errors.New("invalid root key")
}
signatures := []Signature{}
for _, sig := range s.Signatures {
if sig.KeyID != signature.KeyID {
signatures = append(signatures, sig)
}
}
signatures = append(signatures, signature)
s.Signatures = signatures
return nil
}
const (
KeyTypeFulcio = "sigstore-oidc"
KeySchemeFulcio = "https://fulcio.sigstore.dev"
)
var KeyAlgorithms = []string{"sha256", "sha512"}
type FulcioKeyVal struct {
Identity string `json:"identity"`
Issuer string `json:"issuer,omitempty"`
}
func FulcioVerificationKey(email, issuer string) *Key {
keyValBytes, _ := json.Marshal(FulcioKeyVal{Identity: email, Issuer: issuer})
return &Key{
Type: KeyTypeFulcio,
Scheme: KeySchemeFulcio,
Algorithms: KeyAlgorithms,
Value: keyValBytes,
}
}
func GetFulcioKeyVal(key *Key) (*FulcioKeyVal, error) {
fulcioKeyVal := &FulcioKeyVal{}
err := json.Unmarshal(key.Value, fulcioKeyVal)
return fulcioKeyVal, err
}