-
Notifications
You must be signed in to change notification settings - Fork 29
/
keys.go
442 lines (360 loc) · 13.3 KB
/
keys.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
// Copyright 2019 IBM Corp.
//
// 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.
package kp
import (
"context"
"encoding/base64"
"fmt"
"log"
"net/url"
"strconv"
"time"
)
const (
ReturnMinimal PreferReturn = 0
ReturnRepresentation PreferReturn = 1
keyType = "application/vnd.ibm.kms.key+json"
)
var (
preferHeaders = []string{"return=minimal", "return=representation"}
)
// PreferReturn designates the value for the "Prefer" header.
type PreferReturn int
// Key represents a key as returned by the KP API.
type Key struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Type string `json:"type,omitempty"`
Tags []string `json:"Tags,omitempty"`
AlgorithmType string `json:"algorithmType,omitempty"`
CreatedBy string `json:"createdBy,omitempty"`
CreationDate *time.Time `json:"creationDate,omitempty"`
LastUpdateDate *time.Time `json:"lastUpdateDate,omitempty"`
LastRotateDate *time.Time `json:"lastRotateDate,omitempty"`
KeyVersion *KeyVersion `json:"keyVersion,omitempty" mapstructure:keyVersion`
Extractable bool `json:"extractable"`
Expiration *time.Time `json:"expirationDate,omitempty"`
Payload string `json:"payload,omitempty"`
State int `json:"state,omitempty"`
EncryptionAlgorithm string `json:"encryptionAlgorithm,omitempty"`
CRN string `json:"crn,omitempty"`
EncryptedNonce string `json:"encryptedNonce,omitempty"`
IV string `json:"iv,omitempty"`
Deleted *bool `json:"deleted,omitempty"`
DeletedBy *string `json:"deletedBy,omitempty"`
DeletionDate *time.Time `json:"deletionDate,omitempty"`
DualAuthDelete *DualAuth `json:"dualAuthDelete,omitempty"`
}
// KeysMetadata represents the metadata of a collection of keys.
type KeysMetadata struct {
CollectionType string `json:"collectionType"`
NumberOfKeys int `json:"collectionTotal"`
}
// Keys represents a collection of Keys.
type Keys struct {
Metadata KeysMetadata `json:"metadata"`
Keys []Key `json:"resources"`
}
// KeysActionRequest represents request parameters for a key action
// API call.
type KeysActionRequest struct {
PlainText string `json:"plaintext,omitempty"`
AAD []string `json:"aad,omitempty"`
CipherText string `json:"ciphertext,omitempty"`
Payload string `json:"payload,omitempty"`
}
type KeyVersion struct {
ID string `json:"id,omitempty"`
CreationDate *time.Time `json:"creationDate,omitempty"`
}
// CreateKey creates a new KP key.
func (c *Client) CreateKey(ctx context.Context, name string, expiration *time.Time, extractable bool) (*Key, error) {
return c.CreateImportedKey(ctx, name, expiration, "", "", "", extractable)
}
// CreateImportedKey creates a new KP key from the given key material.
func (c *Client) CreateImportedKey(ctx context.Context, name string, expiration *time.Time, payload, encryptedNonce, iv string, extractable bool) (*Key, error) {
key := Key{
Name: name,
Type: keyType,
Extractable: extractable,
Payload: payload,
}
if payload != "" && encryptedNonce != "" && iv != "" {
key.EncryptedNonce = encryptedNonce
key.IV = iv
key.EncryptionAlgorithm = importTokenEncAlgo
}
if expiration != nil {
key.Expiration = expiration
}
keysRequest := Keys{
Metadata: KeysMetadata{
CollectionType: keyType,
NumberOfKeys: 1,
},
Keys: []Key{key},
}
req, err := c.newRequest("POST", "keys", &keysRequest)
if err != nil {
return nil, err
}
keysResponse := Keys{}
if _, err := c.do(ctx, req, &keysResponse); err != nil {
return nil, err
}
return &keysResponse.Keys[0], nil
}
// CreateRootKey creates a new, non-extractable key resource without
// key material.
func (c *Client) CreateRootKey(ctx context.Context, name string, expiration *time.Time) (*Key, error) {
return c.CreateKey(ctx, name, expiration, false)
}
// CreateStandardKey creates a new, extractable key resource without
// key material.
func (c *Client) CreateStandardKey(ctx context.Context, name string, expiration *time.Time) (*Key, error) {
return c.CreateKey(ctx, name, expiration, true)
}
// CreateImportedRootKey creates a new, non-extractable key resource
// with the given key material.
func (c *Client) CreateImportedRootKey(ctx context.Context, name string, expiration *time.Time, payload, encryptedNonce, iv string) (*Key, error) {
return c.CreateImportedKey(ctx, name, expiration, payload, encryptedNonce, iv, false)
}
// CreateStandardKey creates a new, extractable key resource with the
// given key material.
func (c *Client) CreateImportedStandardKey(ctx context.Context, name string, expiration *time.Time, payload string) (*Key, error) {
return c.CreateImportedKey(ctx, name, expiration, payload, "", "", true)
}
// GetKeys retrieves a collection of keys that can be paged through.
func (c *Client) GetKeys(ctx context.Context, limit int, offset int) (*Keys, error) {
if limit == 0 {
limit = 2000
}
req, err := c.newRequest("GET", "keys", nil)
if err != nil {
return nil, err
}
v := url.Values{}
v.Set("limit", strconv.Itoa(limit))
v.Set("offset", strconv.Itoa(offset))
req.URL.RawQuery = v.Encode()
keys := Keys{}
_, err = c.do(ctx, req, &keys)
if err != nil {
return nil, err
}
return &keys, nil
}
// GetKey retrieves a key by ID.
func (c *Client) GetKey(ctx context.Context, id string) (*Key, error) {
return c.getKey(ctx, id, "keys/%s")
}
// GetKeyMetadata retrieves the metadata of a Key.
// Note that the "/api/v2/keys/{id}/metadata" API does not return the payload,
// therefore the payload attribute in the Key pointer will always be empty.
// If you need the payload, you need to use the GetKey() function with the
// correct service access role.
// https://cloud.ibm.com/docs/key-protect?topic=key-protect-manage-access#service-access-roles
func (c *Client) GetKeyMetadata(ctx context.Context, id string) (*Key, error) {
return c.getKey(ctx, id, "keys/%s/metadata")
}
func (c *Client) getKey(ctx context.Context, id string, path string) (*Key, error) {
keys := Keys{}
req, err := c.newRequest("GET", fmt.Sprintf(path, id), nil)
if err != nil {
return nil, err
}
_, err = c.do(ctx, req, &keys)
if err != nil {
return nil, err
}
return &keys.Keys[0], nil
}
type CallOpt interface{}
type ForceOpt struct {
Force bool
}
// DeleteKey deletes a key resource by specifying the ID of the key.
func (c *Client) DeleteKey(ctx context.Context, id string, prefer PreferReturn, callOpts ...CallOpt) (*Key, error) {
req, err := c.newRequest("DELETE", fmt.Sprintf("keys/%s", id), nil)
if err != nil {
return nil, err
}
for _, opt := range callOpts {
switch v := opt.(type) {
case ForceOpt:
params := url.Values{}
params.Set("force", strconv.FormatBool(v.Force))
req.URL.RawQuery = params.Encode()
default:
log.Printf("WARNING: Ignoring invalid CallOpt passed to DeleteKey: %v\n", v)
}
}
req.Header.Set("Prefer", preferHeaders[prefer])
keys := Keys{}
_, err = c.do(ctx, req, &keys)
if err != nil {
return nil, err
}
if len(keys.Keys) > 0 {
return &keys.Keys[0], nil
}
return nil, nil
}
// RestoreKey restores a deleted imported root key by specifying the ID of the key
func (c *Client) RestoreKey(ctx context.Context, id, payload, encryptedNonce, iv string) (*Key, error) {
if payload == "" {
return nil, fmt.Errorf("Please provide payload to restore the key")
}
key := Key{
Payload: payload,
IV: iv,
EncryptedNonce: encryptedNonce,
}
if encryptedNonce != "" && iv != "" {
key.EncryptionAlgorithm = importTokenEncAlgo
}
keysRequest := Keys{
Metadata: KeysMetadata{
CollectionType: keyType,
NumberOfKeys: 1,
},
Keys: []Key{key},
}
v := url.Values{}
v.Set("action", "restore")
req, err := c.newRequest("POST", fmt.Sprintf("keys/%s", id), &keysRequest)
if err != nil {
return nil, err
}
req.URL.RawQuery = v.Encode()
keysResponse := Keys{}
if _, err := c.do(ctx, req, &keysResponse); err != nil {
return nil, err
}
return &keysResponse.Keys[0], nil
}
// Wrap calls the wrap action with the given plain text.
func (c *Client) Wrap(ctx context.Context, id string, plainText []byte, additionalAuthData *[]string) ([]byte, error) {
_, ct, err := c.wrap(ctx, id, plainText, additionalAuthData)
return ct, err
}
// WrapCreateDEK calls the wrap action without plain text.
func (c *Client) WrapCreateDEK(ctx context.Context, id string, additionalAuthData *[]string) ([]byte, []byte, error) {
return c.wrap(ctx, id, nil, additionalAuthData)
}
func (c *Client) wrap(ctx context.Context, id string, plainText []byte, additionalAuthData *[]string) ([]byte, []byte, error) {
keysActionReq := &KeysActionRequest{}
if plainText != nil {
_, err := base64.StdEncoding.DecodeString(string(plainText))
if err != nil {
return nil, nil, err
}
keysActionReq.PlainText = string(plainText)
}
if additionalAuthData != nil {
keysActionReq.AAD = *additionalAuthData
}
keysAction, err := c.doKeysAction(ctx, id, "wrap", keysActionReq)
if err != nil {
return nil, nil, err
}
pt := []byte(keysAction.PlainText)
ct := []byte(keysAction.CipherText)
return pt, ct, nil
}
// Unwrap is deprecated since it returns only plaintext and doesn't know how to handle rotation.
func (c *Client) Unwrap(ctx context.Context, id string, cipherText []byte, additionalAuthData *[]string) ([]byte, error) {
plainText, _, err := c.UnwrapV2(ctx, id, cipherText, additionalAuthData)
if err != nil {
return nil, err
}
return plainText, nil
}
// Unwrap with rotation support.
func (c *Client) UnwrapV2(ctx context.Context, id string, cipherText []byte, additionalAuthData *[]string) ([]byte, []byte, error) {
keysAction := &KeysActionRequest{
CipherText: string(cipherText),
}
if additionalAuthData != nil {
keysAction.AAD = *additionalAuthData
}
respAction, err := c.doKeysAction(ctx, id, "unwrap", keysAction)
if err != nil {
return nil, nil, err
}
plainText := []byte(respAction.PlainText)
rewrapped := []byte(respAction.CipherText)
return plainText, rewrapped, nil
}
// Rotate rotates a CRK.
func (c *Client) Rotate(ctx context.Context, id, payload string) error {
actionReq := &KeysActionRequest{
Payload: payload,
}
_, err := c.doKeysAction(ctx, id, "rotate", actionReq)
if err != nil {
return err
}
return nil
}
// Disable a key. The key will not be deleted but it will not be active
// and key operations cannot be performed on a disabled key.
// For more information can refer to the Key Protect docs in the link below:
// https://cloud.ibm.com/docs/key-protect?topic=key-protect-disable-keys
func (c *Client) DisableKey(ctx context.Context, id string) error {
_, err := c.doKeysAction(ctx, id, "disable", nil)
return err
}
// Enable a key. Only disabled keys can be enabled. After enable
// the key becomes active and key operations can be performed on it.
// Note: This does not recover Deleted keys.
// For more information can refer to the Key Protect docs in the link below:
// https://cloud.ibm.com/docs/key-protect?topic=key-protect-disable-keys#enable-api
func (c *Client) EnableKey(ctx context.Context, id string) error {
_, err := c.doKeysAction(ctx, id, "enable", nil)
return err
}
// InitiateDualAuthDelete sets a key for deletion. The key must be configured with a DualAuthDelete policy.
// After the key is set to deletion it can be deleted by another user who has Manager access.
// For more information refer to the Key Protect docs in the link below:
// https://cloud.ibm.com/docs/key-protect?topic=key-protect-delete-dual-auth-keys#set-key-deletion-api
func (c *Client) InitiateDualAuthDelete(ctx context.Context, id string) error {
_, err := c.doKeysAction(ctx, id, "setKeyForDeletion", nil)
return err
}
// CancelDualAuthDelete unsets the key for deletion. If a key is set for deletion, it can
// be prevented from getting deleted by unsetting the key for deletion.
// For more information refer to the Key Protect docs in the link below:
//https://cloud.ibm.com/docs/key-protect?topic=key-protect-delete-dual-auth-keys#unset-key-deletion-api
func (c *Client) CancelDualAuthDelete(ctx context.Context, id string) error {
_, err := c.doKeysAction(ctx, id, "unsetKeyForDeletion", nil)
return err
}
// doKeysAction calls the KP Client to perform an action on a key.
func (c *Client) doKeysAction(ctx context.Context, id string, action string, keysActionReq *KeysActionRequest) (*KeysActionRequest, error) {
keyActionRsp := KeysActionRequest{}
v := url.Values{}
v.Set("action", action)
req, err := c.newRequest("POST", fmt.Sprintf("keys/%s", id), keysActionReq)
if err != nil {
return nil, err
}
req.URL.RawQuery = v.Encode()
_, err = c.do(ctx, req, &keyActionRsp)
if err != nil {
return nil, err
}
return &keyActionRsp, nil
}