-
Notifications
You must be signed in to change notification settings - Fork 458
/
client_fake.go
441 lines (389 loc) · 12.4 KB
/
client_fake.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
package azurekeyvault
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/rand"
"crypto/rsa"
"errors"
"fmt"
"math/big"
"path"
"sync"
"testing"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys"
"github.com/andres-erbsen/clock"
"github.com/spiffe/spire/test/testkey"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type kmsClientFake struct {
t *testing.T
store fakeStore
vaultURI string
trustDomain string
serverID string
mu sync.RWMutex
createKeyErr error
deleteKeyErr error
updateKeyErr error
getKeyErr error
listKeysErr error
getPublicKeyErr error
signErr error
}
type fakeStore struct {
fakeKeys map[string]*fakeKeyEntry
ec256Key crypto.Signer
ec384Key crypto.Signer
rsa2048Key crypto.Signer
rsa4096Key crypto.Signer
mu sync.RWMutex
clk *clock.Mock
}
type fakeKeyEntry struct {
KeyBundle azkeys.KeyBundle
PrivateKey crypto.Signer
}
func newKMSClientFake(t *testing.T, vaultURI, trustDomain, serverID string, c *clock.Mock) *kmsClientFake {
return &kmsClientFake{
t: t,
vaultURI: vaultURI,
trustDomain: trustDomain,
serverID: serverID,
store: newFakeStore(c, t),
}
}
func newFakeStore(c *clock.Mock, t *testing.T) fakeStore {
testKeys := new(testkey.Keys)
return fakeStore{
fakeKeys: make(map[string]*fakeKeyEntry),
clk: c,
ec256Key: testKeys.NewEC256(t),
ec384Key: testKeys.NewEC384(t),
rsa2048Key: testKeys.NewRSA2048(t),
rsa4096Key: testKeys.NewRSA4096(t),
}
}
func (fs *fakeStore) SaveKeyEntry(input *fakeKeyEntry) {
fs.mu.Lock()
defer fs.mu.Unlock()
fs.fakeKeys[input.KeyBundle.Key.KID.Name()] = input
}
func (fs *fakeStore) DeleteKeyEntry(keyName string) {
fs.mu.Lock()
defer fs.mu.Unlock()
delete(fs.fakeKeys, keyName)
}
func (k *kmsClientFake) setEntries(entries []fakeKeyEntry) {
k.mu.Lock()
defer k.mu.Unlock()
if entries == nil {
return
}
for _, e := range entries {
if e.KeyBundle.Key != nil && e.KeyBundle.Key.KID != nil && e.KeyBundle.Key.KID.Name() != "" {
newEntry := e
k.store.SaveKeyEntry(&newEntry)
}
}
}
func (k *kmsClientFake) setCreateKeyErr(fakeError string) {
k.mu.Lock()
defer k.mu.Unlock()
if fakeError != "" {
k.createKeyErr = errors.New(fakeError)
}
}
func (k *kmsClientFake) setGetKeyErr(fakeError string) {
k.mu.Lock()
defer k.mu.Unlock()
if fakeError != "" {
k.getKeyErr = errors.New(fakeError)
}
}
func (k *kmsClientFake) setGetPublicKeyErr(fakeError string) {
k.mu.Lock()
defer k.mu.Unlock()
if fakeError != "" {
k.getPublicKeyErr = errors.New(fakeError)
}
}
func (k *kmsClientFake) setUpdateKeyErr(fakeError string) {
k.mu.Lock()
defer k.mu.Unlock()
if fakeError != "" {
k.updateKeyErr = errors.New(fakeError)
}
}
func (k *kmsClientFake) setDeleteKeyErr(fakeError error) {
k.mu.Lock()
defer k.mu.Unlock()
if fakeError != nil {
k.deleteKeyErr = fakeError
}
}
func (k *kmsClientFake) setSignDataErr(fakeError string) {
k.mu.Lock()
defer k.mu.Unlock()
if fakeError != "" {
k.signErr = errors.New(fakeError)
}
}
func (k *kmsClientFake) setListKeysErr(fakeError string) {
k.mu.Lock()
defer k.mu.Unlock()
if fakeError != "" {
k.listKeysErr = errors.New(fakeError)
}
}
func (k *kmsClientFake) CreateKey(_ context.Context, keyName string, parameters azkeys.CreateKeyParameters, _ *azkeys.CreateKeyOptions) (azkeys.CreateKeyResponse, error) {
k.mu.RLock()
defer k.mu.RUnlock()
if k.createKeyErr != nil {
return azkeys.CreateKeyResponse{}, k.createKeyErr
}
var publicKey *azkeys.JSONWebKey
var privateKey crypto.Signer
keyOperations := getKeyOperations()
kmsKeyID := path.Join(k.vaultURI, keyName)
switch {
case *parameters.Kty == azkeys.JSONWebKeyTypeEC && *parameters.Curve == azkeys.JSONWebKeyCurveNameP256:
privateKey = k.store.ec256Key
publicKey = toECKey(privateKey.Public(), kmsKeyID, *parameters.Curve, keyOperations)
case *parameters.Kty == azkeys.JSONWebKeyTypeEC && *parameters.Curve == azkeys.JSONWebKeyCurveNameP384:
privateKey = k.store.ec384Key
publicKey = toECKey(privateKey.Public(), kmsKeyID, *parameters.Curve, keyOperations)
case *parameters.Kty == azkeys.JSONWebKeyTypeRSA && *parameters.KeySize == 2048:
privateKey = k.store.rsa2048Key
publicKey = toRSAKey(privateKey.Public(), kmsKeyID, keyOperations)
case *parameters.Kty == azkeys.JSONWebKeyTypeRSA && *parameters.KeySize == 4096:
privateKey = k.store.rsa4096Key
publicKey = toRSAKey(privateKey.Public(), kmsKeyID, keyOperations)
default:
return azkeys.CreateKeyResponse{}, fmt.Errorf("unknown key type %q", *parameters.Kty)
}
keyAttr := &azkeys.KeyAttributes{
Enabled: to.Ptr(true),
Created: to.Ptr(time.Now()),
Updated: to.Ptr(time.Now()),
}
tags := make(map[string]*string)
tags[tagNameServerTrustDomain] = to.Ptr(k.trustDomain)
tags[tagNameServerID] = to.Ptr(k.serverID)
keyBundle := &azkeys.KeyBundle{
Attributes: keyAttr,
Key: publicKey,
Tags: tags,
}
keyEntry := &fakeKeyEntry{
KeyBundle: *keyBundle,
PrivateKey: privateKey,
}
k.store.SaveKeyEntry(keyEntry)
return azkeys.CreateKeyResponse{KeyBundle: *keyBundle}, nil
}
func (k *kmsClientFake) DeleteKey(_ context.Context, name string, _ *azkeys.DeleteKeyOptions) (azkeys.DeleteKeyResponse, error) {
k.mu.RLock()
defer k.mu.RUnlock()
if k.deleteKeyErr != nil {
return azkeys.DeleteKeyResponse{}, k.deleteKeyErr
}
keyEntry, err := k.store.fetchKeyEntry(name)
if err != nil {
return azkeys.DeleteKeyResponse{}, err
}
k.store.DeleteKeyEntry(keyEntry.KeyBundle.Key.KID.Name())
deletedKeyBundle := azkeys.DeletedKeyBundle{
Attributes: keyEntry.KeyBundle.Attributes,
Key: keyEntry.KeyBundle.Key,
}
return azkeys.DeleteKeyResponse{DeletedKeyBundle: deletedKeyBundle}, nil
}
func (k *kmsClientFake) UpdateKey(_ context.Context, name, _ string, _ azkeys.UpdateKeyParameters, _ *azkeys.UpdateKeyOptions) (azkeys.UpdateKeyResponse, error) {
k.mu.RLock()
defer k.mu.RUnlock()
if k.updateKeyErr != nil {
return azkeys.UpdateKeyResponse{}, k.updateKeyErr
}
keyEntry, err := k.store.fetchKeyEntry(name)
if err != nil {
return azkeys.UpdateKeyResponse{}, err
}
keyEntry.KeyBundle.Attributes.Updated = to.Ptr(k.store.clk.Now())
k.store.SaveKeyEntry(keyEntry)
keyBundle := &azkeys.KeyBundle{
Attributes: keyEntry.KeyBundle.Attributes,
Key: keyEntry.KeyBundle.Key,
Tags: keyEntry.KeyBundle.Tags,
}
return azkeys.UpdateKeyResponse{KeyBundle: *keyBundle}, nil
}
func (k *kmsClientFake) GetKey(_ context.Context, keyName, _ string, _ *azkeys.GetKeyOptions) (azkeys.GetKeyResponse, error) {
k.mu.RLock()
defer k.mu.RUnlock()
if k.getKeyErr != nil {
return azkeys.GetKeyResponse{}, k.getKeyErr
}
keyEntry, err := k.store.fetchKeyEntry(keyName)
if err != nil {
return azkeys.GetKeyResponse{}, err
}
keyBundle := &azkeys.KeyBundle{
Attributes: keyEntry.KeyBundle.Attributes,
Key: keyEntry.KeyBundle.Key,
Tags: keyEntry.KeyBundle.Tags,
}
return azkeys.GetKeyResponse{KeyBundle: *keyBundle}, err
}
func (k *kmsClientFake) NewListKeysPager(_ *azkeys.ListKeysOptions) *runtime.Pager[azkeys.ListKeysResponse] {
k.mu.RLock()
defer k.mu.RUnlock()
var listResp []*azkeys.KeyItem
for _, keyEntry := range k.store.fetchKeyEntries() {
listResp = append(listResp, &azkeys.KeyItem{
Attributes: keyEntry.KeyBundle.Attributes,
KID: keyEntry.KeyBundle.Key.KID,
Tags: keyEntry.KeyBundle.Tags,
})
}
return runtime.NewPager(runtime.PagingHandler[azkeys.ListKeysResponse]{
More: func(page azkeys.ListKeysResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *azkeys.ListKeysResponse) (azkeys.ListKeysResponse, error) {
if k.listKeysErr != nil {
return azkeys.ListKeysResponse{}, k.listKeysErr
}
return azkeys.ListKeysResponse{
KeyListResult: azkeys.KeyListResult{
NextLink: nil,
Value: listResp,
},
}, nil
},
})
}
func (k *kmsClientFake) Sign(_ context.Context, keyName, _ string, parameters azkeys.SignParameters, _ *azkeys.SignOptions) (azkeys.SignResponse, error) {
k.mu.RLock()
defer k.mu.RUnlock()
if k.signErr != nil {
return azkeys.SignResponse{}, k.signErr
}
entry, err := k.store.FetchKeyEntry(keyName)
if err != nil {
return azkeys.SignResponse{}, err
}
privateKey := entry.PrivateKey
signRSA := func(opts crypto.SignerOpts) ([]byte, error) {
if _, ok := privateKey.(*rsa.PrivateKey); !ok {
return nil, status.Errorf(codes.InvalidArgument, "invalid signing algorithm %q for RSA key", *parameters.Algorithm)
}
return privateKey.(*rsa.PrivateKey).Sign(rand.Reader, parameters.Value, opts)
}
signECDSA := func() ([]byte, error) {
if _, ok := privateKey.(*ecdsa.PrivateKey); !ok {
return nil, status.Errorf(codes.InvalidArgument, "invalid signing algorithm %q for ECDSA key", *parameters.Algorithm)
}
key := privateKey.(*ecdsa.PrivateKey)
// This is to produce an IEEE-P1363 encoded signature since that's how the azure signature is encoded
curveBits := key.Curve.Params().BitSize
keyBytes := curveBits / 8
if curveBits%8 > 0 {
keyBytes++
}
r, s, err := ecdsa.Sign(rand.Reader, key, parameters.Value)
if err != nil {
return nil, fmt.Errorf("failed to sign data using ecdsa: %w", err)
}
rBytes := r.Bytes()
rBytesPadded := make([]byte, keyBytes)
copy(rBytesPadded[keyBytes-len(rBytes):], rBytes)
sBytes := s.Bytes()
sBytesPadded := make([]byte, keyBytes)
copy(sBytesPadded[keyBytes-len(sBytes):], sBytes)
return append(rBytesPadded, sBytesPadded...), nil
}
var signature []byte
switch *parameters.Algorithm {
case azkeys.JSONWebKeySignatureAlgorithmPS256:
signature, err = signRSA(&rsa.PSSOptions{Hash: crypto.SHA256, SaltLength: rsa.PSSSaltLengthEqualsHash})
case azkeys.JSONWebKeySignatureAlgorithmPS384:
signature, err = signRSA(&rsa.PSSOptions{Hash: crypto.SHA384, SaltLength: rsa.PSSSaltLengthEqualsHash})
case azkeys.JSONWebKeySignatureAlgorithmPS512:
signature, err = signRSA(&rsa.PSSOptions{Hash: crypto.SHA512, SaltLength: rsa.PSSSaltLengthEqualsHash})
case azkeys.JSONWebKeySignatureAlgorithmRS256:
signature, err = signRSA(crypto.SHA256)
case azkeys.JSONWebKeySignatureAlgorithmRS384:
signature, err = signRSA(crypto.SHA384)
case azkeys.JSONWebKeySignatureAlgorithmRS512:
signature, err = signRSA(crypto.SHA512)
case azkeys.JSONWebKeySignatureAlgorithmES256:
signature, err = signECDSA()
case azkeys.JSONWebKeySignatureAlgorithmES384:
signature, err = signECDSA()
case azkeys.JSONWebKeySignatureAlgorithmES512:
signature, err = signECDSA()
default:
return azkeys.SignResponse{}, status.Errorf(codes.InvalidArgument, "unsupported signing algorithm: %s", *parameters.Algorithm)
}
if err != nil {
return azkeys.SignResponse{}, status.Errorf(codes.Internal, "unable to sign digest: %v", err)
}
return azkeys.SignResponse{KeyOperationResult: azkeys.KeyOperationResult{
Result: signature,
}}, nil
}
func toRSAKey(publicKey crypto.PublicKey, kmsKeyID string, keyOperations []*string) *azkeys.JSONWebKey {
rsaKey := publicKey.(*rsa.PublicKey)
var s = big.NewInt(int64(rsaKey.E))
var e = s.Bytes()
key := &azkeys.JSONWebKey{
N: rsaKey.N.Bytes(),
E: e,
KID: to.Ptr(azkeys.ID(kmsKeyID)),
KeyOps: keyOperations,
Kty: to.Ptr(azkeys.JSONWebKeyTypeRSA),
}
return key
}
func toECKey(publicKey crypto.PublicKey, keyName string, curveName azkeys.JSONWebKeyCurveName, keyOperations []*string) *azkeys.JSONWebKey {
ecdsaKey := publicKey.(*ecdsa.PublicKey)
key := &azkeys.JSONWebKey{
Crv: to.Ptr(curveName),
//D: ecdsaKey.D.Bytes(),
KID: to.Ptr(azkeys.ID(keyName)),
KeyOps: keyOperations,
Kty: to.Ptr(azkeys.JSONWebKeyTypeEC),
X: ecdsaKey.X.Bytes(),
Y: ecdsaKey.Y.Bytes(),
}
return key
}
func (fs *fakeStore) FetchKeyEntry(keyName string) (*fakeKeyEntry, error) {
fs.mu.RLock()
defer fs.mu.RUnlock()
return fs.fetchKeyEntry(keyName)
}
func (fs *fakeStore) fetchKeyEntry(keyName string) (*fakeKeyEntry, error) {
keyEntry, ok := fs.fakeKeys[keyName]
if ok {
return keyEntry, nil
}
return &fakeKeyEntry{}, fmt.Errorf("no such key %q", keyName)
}
func (fs *fakeStore) fetchKeyEntries() []fakeKeyEntry {
fs.mu.RLock()
defer fs.mu.RUnlock()
var keyEntries []fakeKeyEntry
for _, v := range fs.fakeKeys {
keyEntries = append(keyEntries, *v)
}
return keyEntries
}
func getKeyOperations() []*string {
return []*string{to.Ptr("Sign"), to.Ptr("Verify")}
}