-
Notifications
You must be signed in to change notification settings - Fork 903
/
Copy pathclient_side_encryption_examples_test.go
379 lines (344 loc) · 11 KB
/
client_side_encryption_examples_test.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
// Copyright (C) MongoDB, Inc. 2017-present.
//
// 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
package mongo
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"log"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func Example_clientSideEncryption() {
// This would have to be the same master key that was used to create the
// encryption key.
localKey := make([]byte, 96)
if _, err := rand.Read(localKey); err != nil {
log.Panic(err)
}
kmsProviders := map[string]map[string]interface{}{
"local": {
"key": localKey,
},
}
keyVaultNamespace := "encryption.__keyVault"
uri := "mongodb://localhost:27017"
autoEncryptionOpts := options.AutoEncryption().
SetKeyVaultNamespace(keyVaultNamespace).
SetKmsProviders(kmsProviders)
clientOpts := options.Client().
ApplyURI(uri).
SetAutoEncryptionOptions(autoEncryptionOpts)
client, err := Connect(clientOpts)
if err != nil {
log.Panicf("Connect error: %v", err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
log.Panicf("Disconnect error: %v", err)
}
}()
collection := client.Database("test").Collection("coll")
if err := collection.Drop(context.TODO()); err != nil {
log.Panicf("Collection.Drop error: %v", err)
}
_, err = collection.InsertOne(
context.TODO(),
bson.D{{"encryptedField", "123456789"}})
if err != nil {
log.Panicf("InsertOne error: %v", err)
}
res, err := collection.FindOne(context.TODO(), bson.D{}).Raw()
if err != nil {
log.Panicf("FindOne error: %v", err)
}
fmt.Println(res)
}
func Example_clientSideEncryptionCreateKey() {
keyVaultNamespace := "encryption.__keyVault"
uri := "mongodb://localhost:27017"
// kmsProviders would have to be populated with the correct KMS provider
// information before it's used.
var kmsProviders map[string]map[string]interface{}
// Create Client and ClientEncryption
clientEncryptionOpts := options.ClientEncryption().
SetKeyVaultNamespace(keyVaultNamespace).
SetKmsProviders(kmsProviders)
keyVaultClient, err := Connect(options.Client().ApplyURI(uri))
if err != nil {
log.Panicf("Connect error for keyVaultClient: %v", err)
}
clientEnc, err := NewClientEncryption(keyVaultClient, clientEncryptionOpts)
if err != nil {
log.Panicf("NewClientEncryption error: %v", err)
}
defer func() {
// this will disconnect the keyVaultClient as well
if err = clientEnc.Close(context.TODO()); err != nil {
log.Panicf("Close error: %v", err)
}
}()
// Create a new data key and encode it as base64
dataKeyID, err := clientEnc.CreateDataKey(context.TODO(), "local")
if err != nil {
log.Panicf("CreateDataKey error: %v", err)
}
dataKeyBase64 := base64.StdEncoding.EncodeToString(dataKeyID.Data)
// Create a JSON schema using the new data key. This schema could also be
// written in a separate file and read in using I/O functions.
schema := `{
"properties": {
"encryptedField": {
"encrypt": {
"keyId": [{
"$binary": {
"base64": "%s",
"subType": "04"
}
}],
"bsonType": "string",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
}
}
},
"bsonType": "object"
}`
schema = fmt.Sprintf(schema, dataKeyBase64)
var schemaDoc bson.Raw
err = bson.UnmarshalExtJSON([]byte(schema), true, &schemaDoc)
if err != nil {
log.Panicf("UnmarshalExtJSON error: %v", err)
}
// Configure a Client with auto encryption using the new schema
dbName := "test"
collName := "coll"
schemaMap := map[string]interface{}{
dbName + "." + collName: schemaDoc,
}
autoEncryptionOpts := options.AutoEncryption().
SetKmsProviders(kmsProviders).
SetKeyVaultNamespace(keyVaultNamespace).
SetSchemaMap(schemaMap)
clientOptions := options.Client().
ApplyURI(uri).
SetAutoEncryptionOptions(autoEncryptionOpts)
client, err := Connect(clientOptions)
if err != nil {
log.Panicf("Connect error for encrypted client: %v", err)
}
defer func() {
_ = client.Disconnect(context.TODO())
}()
// Use client for operations.
}
func Example_explictEncryption() {
// localMasterKey must be the same master key that was used to create the
// encryption key.
var localMasterKey []byte
kmsProviders := map[string]map[string]interface{}{
"local": {
"key": localMasterKey,
},
}
// The MongoDB namespace (db.collection) used to store the encryption data
// keys.
keyVaultDBName, keyVaultCollName := "encryption", "testKeyVault"
keyVaultNamespace := keyVaultDBName + "." + keyVaultCollName
// The Client used to read/write application data.
opts := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := Connect(opts)
if err != nil {
panic(err)
}
defer func() { _ = client.Disconnect(context.TODO()) }()
// Get a handle to the application collection and clear existing data.
coll := client.Database("test").Collection("coll")
_ = coll.Drop(context.TODO())
// Set up the key vault for this example.
keyVaultColl := client.Database(keyVaultDBName).Collection(keyVaultCollName)
_ = keyVaultColl.Drop(context.TODO())
// Ensure that two data keys cannot share the same keyAltName.
keyVaultIndex := IndexModel{
Keys: bson.D{{"keyAltNames", 1}},
Options: options.Index().
SetUnique(true).
SetPartialFilterExpression(bson.D{
{"keyAltNames", bson.D{
{"$exists", true},
}},
}),
}
_, err = keyVaultColl.Indexes().CreateOne(context.TODO(), keyVaultIndex)
if err != nil {
panic(err)
}
// Create the ClientEncryption object to use for explicit
// encryption/decryption. The Client passed to NewClientEncryption is used
// to read/write to the key vault. This can be the same Client used by the
// main application.
clientEncryptionOpts := options.ClientEncryption().
SetKmsProviders(kmsProviders).
SetKeyVaultNamespace(keyVaultNamespace)
clientEncryption, err := NewClientEncryption(client, clientEncryptionOpts)
if err != nil {
panic(err)
}
defer func() { _ = clientEncryption.Close(context.TODO()) }()
// Create a new data key for the encrypted field.
dataKeyOpts := options.DataKey().
SetKeyAltNames([]string{"go_encryption_example"})
dataKeyID, err := clientEncryption.CreateDataKey(
context.TODO(),
"local",
dataKeyOpts)
if err != nil {
panic(err)
}
// Create a bson.RawValue to encrypt and encrypt it using the key that was
// just created.
rawValueType, rawValueData, err := bson.MarshalValue("123456789")
if err != nil {
panic(err)
}
rawValue := bson.RawValue{Type: rawValueType, Value: rawValueData}
encryptionOpts := options.Encrypt().
SetAlgorithm("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").
SetKeyID(dataKeyID)
encryptedField, err := clientEncryption.Encrypt(
context.TODO(),
rawValue,
encryptionOpts)
if err != nil {
panic(err)
}
// Insert a document with the encrypted field and then find it.
_, err = coll.InsertOne(
context.TODO(),
bson.D{{"encryptedField", encryptedField}})
if err != nil {
panic(err)
}
var foundDoc bson.M
err = coll.FindOne(context.TODO(), bson.D{}).Decode(&foundDoc)
if err != nil {
panic(err)
}
// Decrypt the encrypted field in the found document.
decrypted, err := clientEncryption.Decrypt(
context.TODO(),
foundDoc["encryptedField"].(bson.Binary))
if err != nil {
panic(err)
}
fmt.Printf("Decrypted value: %s\n", decrypted)
}
func Example_explictEncryptionWithAutomaticDecryption() {
// Automatic encryption requires MongoDB 4.2 enterprise, but automatic
// decryption is supported for all users.
// localMasterKey must be the same master key that was used to create the
// encryption key.
var localMasterKey []byte
kmsProviders := map[string]map[string]interface{}{
"local": {
"key": localMasterKey,
},
}
// The MongoDB namespace (db.collection) used to store the encryption data
// keys.
keyVaultDBName, keyVaultCollName := "encryption", "testKeyVault"
keyVaultNamespace := keyVaultDBName + "." + keyVaultCollName
// Create the Client for reading/writing application data. Configure it with
// BypassAutoEncryption=true to disable automatic encryption but keep
// automatic decryption. Setting BypassAutoEncryption will also bypass
// spawning mongocryptd in the driver.
autoEncryptionOpts := options.AutoEncryption().
SetKmsProviders(kmsProviders).
SetKeyVaultNamespace(keyVaultNamespace).
SetBypassAutoEncryption(true)
clientOpts := options.Client().
ApplyURI("mongodb://localhost:27017").
SetAutoEncryptionOptions(autoEncryptionOpts)
client, err := Connect(clientOpts)
if err != nil {
panic(err)
}
defer func() { _ = client.Disconnect(context.TODO()) }()
// Get a handle to the application collection and clear existing data.
coll := client.Database("test").Collection("coll")
_ = coll.Drop(context.TODO())
// Set up the key vault for this example.
keyVaultColl := client.Database(keyVaultDBName).Collection(keyVaultCollName)
_ = keyVaultColl.Drop(context.TODO())
// Ensure that two data keys cannot share the same keyAltName.
keyVaultIndex := IndexModel{
Keys: bson.D{{"keyAltNames", 1}},
Options: options.Index().
SetUnique(true).
SetPartialFilterExpression(bson.D{
{"keyAltNames", bson.D{
{"$exists", true},
}},
}),
}
_, err = keyVaultColl.Indexes().CreateOne(context.TODO(), keyVaultIndex)
if err != nil {
panic(err)
}
// Create the ClientEncryption object to use for explicit
// encryption/decryption. The Client passed to NewClientEncryption is used
// to read/write to the key vault. This can be the same Client used by the
// main application.
clientEncryptionOpts := options.ClientEncryption().
SetKmsProviders(kmsProviders).
SetKeyVaultNamespace(keyVaultNamespace)
clientEncryption, err := NewClientEncryption(client, clientEncryptionOpts)
if err != nil {
panic(err)
}
defer func() { _ = clientEncryption.Close(context.TODO()) }()
// Create a new data key for the encrypted field.
dataKeyOpts := options.DataKey().
SetKeyAltNames([]string{"go_encryption_example"})
dataKeyID, err := clientEncryption.CreateDataKey(
context.TODO(),
"local",
dataKeyOpts)
if err != nil {
panic(err)
}
// Create a bson.RawValue to encrypt and encrypt it using the key that was
// just created.
rawValueType, rawValueData, err := bson.MarshalValue("123456789")
if err != nil {
panic(err)
}
rawValue := bson.RawValue{Type: rawValueType, Value: rawValueData}
encryptionOpts := options.Encrypt().
SetAlgorithm("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").
SetKeyID(dataKeyID)
encryptedField, err := clientEncryption.Encrypt(
context.TODO(),
rawValue,
encryptionOpts)
if err != nil {
panic(err)
}
// Insert a document with the encrypted field and then find it. The FindOne
// call will automatically decrypt the field in the document.
_, err = coll.InsertOne(
context.TODO(),
bson.D{{"encryptedField", encryptedField}})
if err != nil {
panic(err)
}
var foundDoc bson.M
err = coll.FindOne(context.TODO(), bson.D{}).Decode(&foundDoc)
if err != nil {
panic(err)
}
fmt.Printf("Decrypted document: %v\n", foundDoc)
}