forked from Vodafone/vault-plugin-aead
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath_bqsync.go
More file actions
296 lines (262 loc) · 10.2 KB
/
path_bqsync.go
File metadata and controls
296 lines (262 loc) · 10.2 KB
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
package aeadplugin
import (
"bytes"
"context"
"fmt"
"strings"
"cloud.google.com/go/bigquery"
kms "cloud.google.com/go/kms/apiv1"
"github.com/google/tink/go/insecurecleartextkeyset"
"github.com/google/tink/go/keyset"
hclog "github.com/hashicorp/go-hclog"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)
func (b *backend) pathBQKeySync(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
// retrive the config from storage
err := b.getAeadConfig(ctx, req)
if err != nil {
return nil, err
}
for keyField, encryptionKey := range AEAD_CONFIG.Items() {
fieldName := fmt.Sprintf("%v", keyField)
keyStr := fmt.Sprintf("%v", encryptionKey)
if !strings.Contains(keyStr, "primaryKeyId") {
continue
} else {
encryptionKeyStr, deterministic := isKeyJsonDeterministic(encryptionKey)
if deterministic {
kh, _, err := CreateInsecureHandleAndDeterministicAead(encryptionKeyStr)
if err != nil {
hclog.L().Error("failed to create deterministic key handle")
return &logical.Response{
Data: make(map[string]interface{}),
}, err
}
doBQSync(kh, fieldName, true)
// do deterministic sync
} else {
kh, _, err := CreateInsecureHandleAndAead(encryptionKeyStr)
if err != nil {
hclog.L().Error("failed to create non deterministic key handle")
return &logical.Response{
Data: make(map[string]interface{}),
}, err
}
// do non- deterministic sync
doBQSync(kh, fieldName, false)
}
}
}
return nil, nil
}
type Options struct {
projectId string
encryptDatasetId string
decryptDatasetId string
encryptRoutineId string
decryptRoutineId string
detRoutinePrefix string
nondetRoutinePrefix string
kmsKeyName string
fieldName string
}
func doBQSync(kh *keyset.Handle, fieldName string, deterministic bool) {
var options Options
resolveOptions(&options, fieldName, deterministic)
// 0. Initate clients
ctx := context.Background()
kmsClient, err := kms.NewKeyManagementClient(ctx)
if err != nil {
hclog.L().Error("failed to setup client: %v", err)
}
defer kmsClient.Close()
binaryKeyset := new(bytes.Buffer)
insecurecleartextkeyset.Write(kh, keyset.NewBinaryWriter(binaryKeyset))
// 2. Wrap the binary keyset with KMS.
encryptReq := &kmspb.EncryptRequest{
Name: options.kmsKeyName,
Plaintext: binaryKeyset.Bytes(),
}
encryptResp, err := kmsClient.Encrypt(ctx, encryptReq)
if err != nil {
hclog.L().Error("Failed to encrypt keyset: %v", err)
}
// 3. Format the wrapped keyset as an escaped bytestring (like '\x00\x01\xAD') so BQ can accept it.
escapedWrappedKeyset := ""
for _, cbyte := range encryptResp.Ciphertext {
escapedWrappedKeyset += fmt.Sprintf("\\x%02x", cbyte)
}
doBQRoutineCreateOrUpdate(ctx, options, escapedWrappedKeyset, deterministic)
}
func doBQRoutineCreateOrUpdate(ctx context.Context, options Options, escapedWrappedKeyset string, deterministic bool) {
bigqueryClient, err := bigquery.NewClient(ctx, options.projectId)
if err != nil {
hclog.L().Error("Failed to create a bigquery client: %v", err)
}
defer bigqueryClient.Close()
// 4. Create a BigQuery Routine. You'll likely want to create one Routine each for encryption/decryption.
routineEncryptBody := fmt.Sprintf("AEAD.ENCRYPT(KEYS.KEYSET_CHAIN(\"gcp-kms://%s\", b\"%s\"), plaintext, aad)", options.kmsKeyName, escapedWrappedKeyset)
if deterministic {
routineEncryptBody = fmt.Sprintf("DETERMINISTIC_ENCRYPT(KEYS.KEYSET_CHAIN(\"gcp-kms://%s\", b\"%s\"), plaintext, aad)", options.kmsKeyName, escapedWrappedKeyset)
}
routineEncryptRef := bigqueryClient.Dataset(options.encryptDatasetId).Routine(options.encryptRoutineId)
routineExists := true
rm, err := routineEncryptRef.Metadata(ctx)
if err != nil {
routineExists = false
}
if !routineExists {
metadataEncrypt := &bigquery.RoutineMetadata{
Type: "SCALAR_FUNCTION",
Language: "SQL",
Body: routineEncryptBody,
Arguments: []*bigquery.RoutineArgument{
{Name: "plaintext", DataType: &bigquery.StandardSQLDataType{TypeKind: "STRING"}},
{Name: "aad", DataType: &bigquery.StandardSQLDataType{TypeKind: "STRING"}},
},
}
err := routineEncryptRef.Create(ctx, metadataEncrypt)
if err != nil {
hclog.L().Error("Failed to create encrypt routine: %v errmessge=%s", err, err.Error())
}
hclog.L().Info("Encrypt Routine successfully created!", "info", nil)
} else {
metadataUpdatetoUpdate := &bigquery.RoutineMetadataToUpdate{
Type: "SCALAR_FUNCTION",
Language: "SQL",
Body: routineEncryptBody,
Arguments: []*bigquery.RoutineArgument{
{Name: "plaintext", DataType: &bigquery.StandardSQLDataType{TypeKind: "STRING"}},
{Name: "aad", DataType: &bigquery.StandardSQLDataType{TypeKind: "STRING"}},
},
}
_, err = routineEncryptRef.Update(ctx, metadataUpdatetoUpdate, rm.ETag)
if err != nil {
hclog.L().Error("Failed to update encrypt routine: %v errmessge=%s", err, err.Error())
}
hclog.L().Info("Encrypt Routine successfully updated!", "info", nil)
}
routineDecryptBody := fmt.Sprintf("AEAD.DECRYPT_STRING(KEYS.KEYSET_CHAIN(\"gcp-kms://%s\", b\"%s\"), ciphertext, aad)", options.kmsKeyName, escapedWrappedKeyset)
if deterministic {
routineDecryptBody = fmt.Sprintf("DETERMINISTIC_DECRYPT_BYTES(KEYS.KEYSET_CHAIN(\"gcp-kms://%s\", b\"%s\"), ciphertext, aad)", options.kmsKeyName, escapedWrappedKeyset)
}
routineDecryptRef := bigqueryClient.Dataset(options.decryptDatasetId).Routine(options.decryptRoutineId)
routineExists = true
rm, err = routineDecryptRef.Metadata(ctx)
if err != nil {
routineExists = false
}
// fmt.Printf("routineExists=%v", routineExists)
if !routineExists {
var metadataDecrypt *bigquery.RoutineMetadata
if deterministic {
metadataDecrypt = &bigquery.RoutineMetadata{
Type: "SCALAR_FUNCTION",
Language: "SQL",
Body: routineDecryptBody,
Arguments: []*bigquery.RoutineArgument{
{Name: "ciphertext", DataType: &bigquery.StandardSQLDataType{TypeKind: "BYTES"}},
{Name: "aad", DataType: &bigquery.StandardSQLDataType{TypeKind: "BYTES"}},
},
}
} else {
// non deterministic
metadataDecrypt = &bigquery.RoutineMetadata{
Type: "SCALAR_FUNCTION",
Language: "SQL",
Body: routineDecryptBody,
Arguments: []*bigquery.RoutineArgument{
{Name: "ciphertext", DataType: &bigquery.StandardSQLDataType{TypeKind: "BYTES"}},
{Name: "aad", DataType: &bigquery.StandardSQLDataType{TypeKind: "STRING"}},
},
}
}
err = routineDecryptRef.Create(ctx, metadataDecrypt)
if err != nil {
hclog.L().Error("Failed to create decrypt routine: %v", err)
}
hclog.L().Info("Decrypt Routine successfully created!", "info", nil)
} else {
var metadataUpdatetoUpdate *bigquery.RoutineMetadataToUpdate
if deterministic {
metadataUpdatetoUpdate = &bigquery.RoutineMetadataToUpdate{
Type: "SCALAR_FUNCTION",
Language: "SQL",
Body: routineDecryptBody,
Arguments: []*bigquery.RoutineArgument{
{Name: "ciphertext", DataType: &bigquery.StandardSQLDataType{TypeKind: "BYTES"}},
{Name: "aad", DataType: &bigquery.StandardSQLDataType{TypeKind: "BYTES"}},
},
}
} else {
metadataUpdatetoUpdate = &bigquery.RoutineMetadataToUpdate{
Type: "SCALAR_FUNCTION",
Language: "SQL",
Body: routineDecryptBody,
Arguments: []*bigquery.RoutineArgument{
{Name: "ciphertext", DataType: &bigquery.StandardSQLDataType{TypeKind: "BYTES"}},
{Name: "aad", DataType: &bigquery.StandardSQLDataType{TypeKind: "STRING"}},
},
}
}
_, err = routineDecryptRef.Update(ctx, metadataUpdatetoUpdate, rm.ETag)
if err != nil {
hclog.L().Error("Failed to update decrypt routine: %v errmessge=%s", err, err.Error())
}
hclog.L().Info("Decrypt Routine successfully updated!", "info", nil)
}
}
func resolveOptions(options *Options, fieldName string, deterministic bool) {
// set the defaults
options.kmsKeyName = "projects/your-kms-project/locations/europe/keyRings/tink-keyring/cryptoKeys/key1" // Format: 'projects/.../locations/.../keyRings/.../cryptoKeys/...'
options.projectId = "your-bq-project"
options.encryptDatasetId = "pii_dataset_eu"
options.decryptDatasetId = "pii_dataset_eu"
options.detRoutinePrefix = "pii_daead_"
options.nondetRoutinePrefix = "pii_aead_"
// set any overrides
kmsKeyInterface, ok := AEAD_CONFIG.Get("BQ_KMSKEY")
if ok {
options.kmsKeyName = fmt.Sprintf("%s", kmsKeyInterface)
}
projectIdInterface, ok := AEAD_CONFIG.Get("BQ_PROJECT")
if ok {
options.projectId = fmt.Sprintf("%s", projectIdInterface)
}
encryptDatasetIdInterface, ok := AEAD_CONFIG.Get("BQ_DEFAULT_ENCRYPT_DATASET")
if ok {
options.encryptDatasetId = fmt.Sprintf("%s", encryptDatasetIdInterface)
}
decryptDatasetIdInterface, ok := AEAD_CONFIG.Get("BQ_DEFAULT_DECRYPT_DATASET")
if ok {
options.decryptDatasetId = fmt.Sprintf("%s", decryptDatasetIdInterface)
}
detRoutinePrefixInterface, ok := AEAD_CONFIG.Get("BQ_ROUTINE_DET_PREFIX")
if ok {
options.detRoutinePrefix = fmt.Sprintf("%s", detRoutinePrefixInterface)
}
nondetRoutinePrefixInterface, ok := AEAD_CONFIG.Get("BQ_ROUTINE_NONDET_PREFIX")
if ok {
options.nondetRoutinePrefix = fmt.Sprintf("%s", nondetRoutinePrefixInterface)
}
// fieldName might have a "-" in it, but "-" are not allowed in BQ, so translate them to "_"
options.fieldName = strings.Replace(fieldName, "-", "_", -1)
if deterministic {
options.encryptRoutineId = options.detRoutinePrefix + options.fieldName + "_encrypt"
options.decryptRoutineId = options.detRoutinePrefix + options.fieldName + "_decrypt"
} else {
options.encryptRoutineId = options.nondetRoutinePrefix + options.fieldName + "_encrypt"
options.decryptRoutineId = options.nondetRoutinePrefix + options.fieldName + "_decrypt"
}
// if we have a config entry for the encrypt or decrypt routine then use that as the dataset
overrideBQDatasetInterface, ok := AEAD_CONFIG.Get(options.encryptRoutineId)
if ok {
options.encryptDatasetId = fmt.Sprintf("%s", overrideBQDatasetInterface)
}
overrideBQDatasetInterface, ok = AEAD_CONFIG.Get(options.decryptRoutineId)
if ok {
options.decryptDatasetId = fmt.Sprintf("%s", overrideBQDatasetInterface)
}
}