/
read.go
281 lines (233 loc) · 7.62 KB
/
read.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
// Copyright 2019 The Berglas 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.
package berglas
import (
"context"
"encoding/base64"
"fmt"
"io"
"path"
"sort"
"strings"
"cloud.google.com/go/kms/apiv1/kmspb"
secretspb "cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
"cloud.google.com/go/storage"
"github.com/GoogleCloudPlatform/berglas/v2/pkg/berglas/logging"
grpccodes "google.golang.org/grpc/codes"
grpcstatus "google.golang.org/grpc/status"
)
type readRequest interface {
isReadRequest()
}
// StorageReadRequest is used as input to read a secret from Cloud Storage
// encrypted with Cloud KMS.
type StorageReadRequest struct {
// Bucket is the name of the bucket where the secret lives.
Bucket string
// Object is the name of the object in Cloud Storage.
Object string
// Generation of the object to fetch.
Generation int64
}
func (r *StorageReadRequest) isReadRequest() {}
// ReadRequest is an alias for StorageReadRequest for backwards-compatibility.
// New clients should use StorageReadRequest.
type ReadRequest = StorageReadRequest
// SecretManagerReadRequest is used as input to read a secret from Secret
// Manager.
type SecretManagerReadRequest struct {
// Project is the ID or number of the project from which to read secrets.
Project string
// Name is the name of the secret to read.
Name string
// Version is the version of the secret to read.
Version string
}
func (r *SecretManagerReadRequest) isReadRequest() {}
// Read is a top-level package function for reading an entire secret object. It
// returns attributes about the secret object, including the plaintext.
func Read(ctx context.Context, i readRequest) (*Secret, error) {
client, err := New(ctx)
if err != nil {
return nil, err
}
return client.Read(ctx, i)
}
// Read read a secret. When given a SecretManagerReadRequest, this reads a
// secret from Secret Manager. When given a StorageReadRequest, this reads a
// secret stored in Cloud Storage.
func (c *Client) Read(ctx context.Context, i readRequest) (*Secret, error) {
if i == nil {
return nil, fmt.Errorf("missing request")
}
switch t := i.(type) {
case *SecretManagerReadRequest:
return c.secretManagerRead(ctx, t)
case *StorageReadRequest:
return c.storageRead(ctx, t)
default:
return nil, fmt.Errorf("unknown read type %T", t)
}
}
func (c *Client) secretManagerRead(ctx context.Context, i *SecretManagerReadRequest) (*Secret, error) {
project := i.Project
if project == "" {
return nil, fmt.Errorf("missing project")
}
name := i.Name
if name == "" {
return nil, fmt.Errorf("missing secret name")
}
version := i.Version
if version == "" {
version = "latest"
}
logger := logging.FromContext(ctx).With(
"project", project,
"name", name,
"version", version,
)
logger.DebugContext(ctx, "read.start")
defer logger.DebugContext(ctx, "read.finish")
logger.DebugContext(ctx, "reading secret version")
versionResp, err := c.secretManagerClient.GetSecretVersion(ctx, &secretspb.GetSecretVersionRequest{
Name: fmt.Sprintf("projects/%s/secrets/%s/versions/%s", project, name, version),
})
if err != nil {
terr, ok := grpcstatus.FromError(err)
if ok && terr.Code() == grpccodes.NotFound {
return nil, errSecretDoesNotExist
}
return nil, fmt.Errorf("failed to read secret: %w", err)
}
logger.DebugContext(ctx, "accessing secret data")
accessResp, err := c.secretManagerClient.AccessSecretVersion(ctx, &secretspb.AccessSecretVersionRequest{
Name: fmt.Sprintf("projects/%s/secrets/%s/versions/%s", project, name, version),
})
if err != nil {
return nil, fmt.Errorf("failed to access secret: %w", err)
}
logger.DebugContext(ctx, "parsing location")
var locations []string
replication := versionResp.ReplicationStatus.GetUserManaged()
if replication != nil {
locations = make([]string, len(replication.Replicas))
for i, r := range replication.Replicas {
locations[i] = r.Location
}
}
sort.Strings(locations)
return &Secret{
Parent: project,
Name: name,
Version: path.Base(versionResp.Name),
Plaintext: accessResp.Payload.Data,
UpdatedAt: timestampToTime(versionResp.CreateTime),
Locations: locations,
}, nil
}
func (c *Client) storageRead(ctx context.Context, i *StorageReadRequest) (*Secret, error) {
bucket := i.Bucket
if bucket == "" {
return nil, fmt.Errorf("missing bucket name")
}
object := i.Object
if object == "" {
return nil, fmt.Errorf("missing object name")
}
generation := i.Generation
if generation == 0 {
generation = -1
}
logger := logging.FromContext(ctx).With(
"bucket", bucket,
"object", object,
"generation", generation,
)
logger.DebugContext(ctx, "read.start")
defer logger.DebugContext(ctx, "read.finish")
// Get attributes to find the KMS key
logger.DebugContext(ctx, "reading attributes from storage")
attrs, err := c.storageClient.
Bucket(bucket).
Object(object).
Generation(generation).
Attrs(ctx)
if err == storage.ErrObjectNotExist {
return nil, errSecretDoesNotExist
}
if err != nil {
return nil, fmt.Errorf("failed to read secret metadata: %w", err)
}
if attrs.Metadata == nil || attrs.Metadata[MetadataKMSKey] == "" {
return nil, fmt.Errorf("missing kms key in secret metadata")
}
key := attrs.Metadata[MetadataKMSKey]
logger = logger.With("key", key)
logger.DebugContext(ctx, "found kms key")
// Download the file from GCS
logger.DebugContext(ctx, "downloading file from storage")
ior, err := c.storageClient.
Bucket(bucket).
Object(object).
Generation(generation).
NewReader(ctx)
if err == storage.ErrObjectNotExist {
return nil, fmt.Errorf("secret object not found")
}
if err != nil {
return nil, fmt.Errorf("failed to read secret: %w", err)
}
// Read the entire response into memory
logger.DebugContext(ctx, "reading object into memory")
data, err := io.ReadAll(ior)
if err != nil {
return nil, fmt.Errorf("failed to read secret into string: %w", err)
}
if err := ior.Close(); err != nil {
return nil, fmt.Errorf("failed to close reader: %w", err)
}
// Split into parts
logger.DebugContext(ctx, "deconstructing and decoding ciphertext into parts")
parts := strings.SplitN(string(data), ":", 2)
if len(parts) < 2 {
return nil, fmt.Errorf("invalid ciphertext: not enough parts")
}
encDEK, err := base64.StdEncoding.DecodeString(parts[0])
if err != nil {
return nil, fmt.Errorf("invalid ciphertext: failed to parse dek")
}
ciphertext, err := base64.StdEncoding.DecodeString(parts[1])
if err != nil {
return nil, fmt.Errorf("invalid ciphertext: failed to parse ciphertext")
}
// Decrypt the DEK using a KMS key
logger.DebugContext(ctx, "decrypting dek using kms")
kmsResp, err := c.kmsClient.Decrypt(ctx, &kmspb.DecryptRequest{
Name: key,
Ciphertext: encDEK,
AdditionalAuthenticatedData: []byte(object),
})
if err != nil {
return nil, fmt.Errorf("failed to decrypt dek: %w", err)
}
dek := kmsResp.Plaintext
// Decrypt with the local key
logger.DebugContext(ctx, "decrypting data with deck locally")
plaintext, err := envelopeDecrypt(dek, ciphertext)
if err != nil {
return nil, fmt.Errorf("failed to decrypt envelope: %w", err)
}
return secretFromAttrs(bucket, attrs, plaintext), nil
}