-
Notifications
You must be signed in to change notification settings - Fork 1
/
secret.go
368 lines (308 loc) · 12.3 KB
/
secret.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
// Package secret provides a client for REST operations involving secrets.
// This implements calls from this API: https://docs.microsoft.com/en-us/rest/api/keyvault/#secret-operations
package secret
import (
"context"
"fmt"
"net/url"
"strings"
//"strconv"
"github.com/element-of-surprise/keyvault/ops/internal/conn"
"github.com/element-of-surprise/keyvault/ops/values"
)
// DeletionRecoveryLevel indicates what level of recovery is associated with a particular secret.
// Details at: https://docs.microsoft.com/en-us/rest/api/keyvault/getsecretversions/getsecretversions#deletionrecoverylevel
type DeletionRecoveryLevel string
func (d DeletionRecoveryLevel) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%q", d)), nil
}
func (d *DeletionRecoveryLevel) UnmarshalJSON(s []byte) error {
v := DeletionRecoveryLevel(strings.Trim(string(s), `"`))
if !validDeletionRecoveryLevel[v] {
return fmt.Errorf("%q is an unrecognized DeletionRecoveryLevel", v)
}
*d = v
return nil
}
const (
// Purgeable indicates soft-delete is not enabled for this vault. A DELETE operation results in immediate and
// irreversible data loss.
Purgeable DeletionRecoveryLevel = "Purgeable"
// Recoverable indicates soft-delete is enabled for this vault and purge has been disabled. A deleted entity
// will remain in this state until recovered, or the end of the retention interval.
Recoverable DeletionRecoveryLevel = "Recoverable"
// RecoverableProtectedSubscription indicates soft-delete is enabled for this vault, and the subscription is
// protected against immediate deletion.
RecoverableProtectedSubscription DeletionRecoveryLevel = "Recoverable+ProtectedSubscription"
// RecoverablePurgeable indicates soft-delete is enabled for this vault; A privileged user may trigger an
// immediate, irreversible deletion(purge) of a deleted entity.
RecoverablePurgeable DeletionRecoveryLevel = "Recoverable+Purgeable"
)
var validDeletionRecoveryLevel = map[DeletionRecoveryLevel]bool{
Purgeable: true,
Recoverable: true,
RecoverableProtectedSubscription: true,
RecoverablePurgeable: true,
}
// Base contains the base attributes used in multiple return objects.
type Base struct {
// Attributes are attributes tied to a Bundle.
Attributes Attributes
// ContentType is a string that can optionally be set by a user to indicate the content type.
// This is not a definitive content type given by the system.
ContentType string `json:"contentType"`
// ID is the secret"s ID.
ID string `json:"id"`
// Tags are application specific metadata in the form of key-value pairs.
Tags map[string]string `json:"tags"`
}
// Bundle is used to describe a secret.
type Bundle struct {
Base
// KID specifies the corresponding key backing the KV certificate. This is only set if this is a secret backing a KV certificate,
KID string `json:"kid"`
// Managed indicates if a secret"s lifetime is managed by keyvault.
// If this is a secret backing a certificate, this will be true.
Managed bool `json:"managed"`
// Value is the value of the secret.
Value string `json:"value"`
}
// Version describes a secret version.
type Version struct {
Base
// Managed indicates if a secret"s lifetime is managed by keyvault.
// If this is a secret backing a certificate, this will be true.
Managed bool `json:"managed"`
}
// DeletedBundle is returned when we delete a bundle.
type DeletedBundle struct {
Bundle
// DeleteDate is the time when the secret was deleted.
DeleteDate values.Time `json:"deletedDate"`
// RecoveryID is the url of the recovery object, used to identify and recover the deleted secret.
RecoveryID *values.URL `json:"recoveryId"`
// ScheduledPurgeDate is the time when the secret is scheduled to be purged.
ScheduledPurgeDate values.Time `json:"scheduledPurgeDate"`
}
// Deleted is a deleted secret.
type Deleted struct {
Base
// Managed indicates if a secret"s lifetime is managed by keyvault.
// If this is a secret backing a certificate, this will be true.
Managed bool `json:"managed"`
// DeleteDate is the time when the secret was deleted.
DeleteDate values.Time `json:"deletedDate"`
// RecoveryID is the url of the recovery object, used to identify and recover the deleted secret.
RecoveryID *values.URL `json:"recoveryId"`
// ScheduledPurgeDate is the time when the secret is scheduled to be purged.
ScheduledPurgeDate values.Time `json:"scheduledPurgeDate"`
}
// Attributes are attributes associated with this secret.
type Attributes struct {
// RecoveryLevel is the level of recovery for this password when deleted. See the description of
// DeletionRecoveryLevel above.
RecoveryLevel DeletionRecoveryLevel `json:"recoveryLevel,omitempty"`
// RecoverableDays is the soft delete data retention days. Must be >=7 and <=90, otherwise 0.
RecoverableDays int `json:"recoverableDays,omitempty"`
// Enabled indicates if the secret is currently enabled.
Enabled bool `json:"enabled,omitempty"`
// Created indicates the time the secret was created in UTC. If set to the zero value, it indicates
// this was not set.
Created *values.Time `json:"created,omitempty"`
// NotBefore indicate that the key isn"t valid before this time in UTC. If set to the zero value, it indicates
// this was not set.
NotBefore values.Time `json:"nbf,omitempty"`
// Updated indicates the last time the secret was updated in UTC. If set to the zero value, it indicates
// this was not set.
Updated values.Time `json:"updated,omitempty"`
}
// Client is a client for making calls to Secret operations on Keyvault.
type Client struct {
// Conn is the connection to the keyvault service.
Conn *conn.Conn
}
// GetSecret gets a secret with the name "name" from Keyvault. If you wish to get a secret at a certain version,
// pass the Version() option.
func (c *Client) Get(ctx context.Context, name string, version string) (Bundle, error) {
bundle := Bundle{}
path := strings.Builder{}
path.WriteString("/secrets/" + name)
if version != "" {
path.WriteString("/" + version)
}
err := c.Conn.Call(ctx, conn.Get, path.String(), nil, nil, &bundle)
return bundle, err
}
type listResult struct {
NextLink string `json:"nextLink"`
Value []Version `json:"value"`
}
// Versions returns a list of version information for a secret from the service.
func (c *Client) Versions(ctx context.Context, name string, maxResults int32) ([]Version, error) {
if maxResults <= 0 {
maxResults = 25
}
versions := []Version{}
path := strings.Builder{}
path.WriteString("/secrets/" + name + "/versions")
for {
qv := url.Values{}
//qv.Add("maxresults", strconv.Itoa(int(maxResults)))
result := listResult{}
err := c.Conn.Call(ctx, conn.Get, path.String(), qv, nil, &result)
if err != nil {
return nil, fmt.Errorf("issue getting list of secret versions for %q: %w", name, err)
}
versions = append(versions, result.Value...)
if result.NextLink != "" {
path.Reset()
path.WriteString(result.NextLink)
continue
}
break
}
return versions, nil
}
// List returns a list of all secrets in the vault. We use the Version type, which is based on the SecretListResult type
// in the REST API.
func (c *Client) List(ctx context.Context, maxResults int32) ([]Version, error) {
if maxResults <= 0 {
maxResults = 25
}
versions := []Version{}
path := strings.Builder{}
path.WriteString("/secrets")
for {
qv := url.Values{}
//qv.Add("maxresults", strconv.Itoa(int(maxResults)))
result := listResult{}
err := c.Conn.Call(ctx, conn.Get, path.String(), qv, nil, &result)
if err != nil {
return nil, fmt.Errorf("issue getting list of secrets: %w", err)
}
versions = append(versions, result.Value...)
if result.NextLink != "" {
path.Reset()
path.WriteString(result.NextLink)
continue
}
break
}
return versions, nil
}
// UpdateSetRequest is used to set a secret or update its attributes.
type UpdateSetRequest struct {
// Attributes are attributes tied to a Bundle.
Attributes *Attributes `json:",omitempty"`
// ContentType is a string that can optionally be set by a user to indicate the content type.
// This is not a definitive content type given by the system.
ContentType string `json:"contentType,omitempty"`
// Tags are application specific metadata in the form of key-value pairs.
Tags map[string]string `json:"tags,omitempty"`
// Value is the value of the secret. Only valid in a Set.
Value string `json:"value,omitempty"`
// Base64Encode indicates to base64 encode the value.
Base64Encode bool `json:"-"`
}
// Set creates a new secret or adds a new version if the named secret exists.
func (c *Client) Set(ctx context.Context, name string, req UpdateSetRequest) (Bundle, error) {
bundle := Bundle{}
if req.Value == "" {
return bundle, fmt.Errorf("secret.SetRequest() request must provide a value")
}
path := strings.Builder{}
path.WriteString("/secrets/" + name)
err := c.Conn.Call(ctx, conn.Put, path.String(), nil, req, &bundle)
return bundle, err
}
// UpdateAttr updates a secret's attributes.
func (c *Client) UpdateAttr(ctx context.Context, name, version string, req UpdateSetRequest) (Bundle, error) {
bundle := Bundle{}
if version == "" {
return bundle, fmt.Errorf("UpdateAttr requires a version, passed empty string")
}
path := strings.Builder{}
path.WriteString(fmt.Sprintf("/secrets/%s/%s", name, version))
err := c.Conn.Call(ctx, conn.Patch, path.String(), nil, req, &bundle)
return bundle, err
}
// Delete deletes the named secret and returns information the deleted secret.
func (c *Client) Delete(ctx context.Context, name string) (DeletedBundle, error) {
bundle := DeletedBundle{}
path := strings.Builder{}
path.WriteString("/secrets/" + name)
err := c.Conn.Call(ctx, conn.Delete, path.String(), nil, nil, &bundle)
return bundle, err
}
// Deleted returns information on a deleted secret.
func (c *Client) Deleted(ctx context.Context, name string) (DeletedBundle, error) {
bundle := DeletedBundle{}
path := strings.Builder{}
path.WriteString("/deletedsecrets/" + name)
err := c.Conn.Call(ctx, conn.Get, path.String(), nil, nil, &bundle)
return bundle, err
}
type deletedListResult struct {
NextLink string `json:"nextLink"`
Value []Deleted `json:"value"`
}
// ListDeleted returns a list of deleted secrets.
func (c *Client) ListDeleted(ctx context.Context, maxResults int32) ([]Deleted, error) {
if maxResults <= 0 {
maxResults = 25
}
deleted := []Deleted{}
path := strings.Builder{}
path.WriteString("/secrets")
for {
qv := url.Values{}
//qv.Add("maxresults", strconv.Itoa(int(maxResults)))
result := deletedListResult{}
err := c.Conn.Call(ctx, conn.Get, path.String(), qv, nil, &result)
if err != nil {
return nil, fmt.Errorf("issue getting list of deleted secrets: %w", err)
}
deleted = append(deleted, result.Value...)
if result.NextLink != "" {
path.Reset()
path.WriteString(result.NextLink)
continue
}
break
}
return deleted, nil
}
// Backup returns a string representing a blob of all versions of a secret. This is in an undisclosed format.
func (c *Client) Backup(ctx context.Context, name string) (string, error) {
path := strings.Builder{}
path.WriteString(fmt.Sprintf("/secrets/%s/backup", name))
result := struct{ Value string }{}
err := c.Conn.Call(ctx, conn.Post, path.String(), nil, nil, &result)
if err != nil {
return "", err
}
return result.Value, nil
}
// Purge permanently deletes a secret, without the possibility of recovery. Name is the name of a deleted secret.
func (c *Client) Purge(ctx context.Context, name string) error {
path := strings.Builder{}
path.WriteString(fmt.Sprintf("/deletedsecrets/%s", name))
return c.Conn.Call(ctx, conn.Delete, path.String(), nil, nil, nil)
}
// Restore restores a key from the value passed. That value comes from a call to Backup().
func (c *Client) Restore(ctx context.Context, value string) (Bundle, error) {
bundle := Bundle{}
path := strings.Builder{}
path.WriteString("/secrets/restore")
req := struct{ Value string }{Value: value}
err := c.Conn.Call(ctx, conn.Post, path.String(), nil, req, &bundle)
return bundle, err
}
// Recover recovers a deleted secret that has not been purged to the latest version.
func (c *Client) Recover(ctx context.Context, name string) (Bundle, error) {
bundle := Bundle{}
path := strings.Builder{}
path.WriteString(fmt.Sprintf("/deletedsecrets/%s/recover", name))
err := c.Conn.Call(ctx, conn.Post, path.String(), nil, nil, &bundle)
return bundle, err
}