forked from mongodb/mongo-csharp-driver
/
ClientEncryption.cs
346 lines (312 loc) · 19 KB
/
ClientEncryption.cs
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
/* Copyright 2019-present MongoDB Inc.
*
* 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.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver.Core.Clusters;
using MongoDB.Driver.Core.Configuration;
using MongoDB.Driver.Core.Misc;
using MongoDB.Libmongocrypt;
namespace MongoDB.Driver.Encryption
{
/// <summary>
/// Explicit client encryption.
/// </summary>
public sealed class ClientEncryption : IDisposable
{
// private fields
private readonly CryptClient _cryptClient;
private bool _disposed;
private readonly ExplicitEncryptionLibMongoCryptController _libMongoCryptController;
// constructors
/// <summary>
/// Initializes a new instance of the <see cref="ClientEncryption"/> class.
/// </summary>
/// <param name="clientEncryptionOptions">The client encryption options.</param>
public ClientEncryption(ClientEncryptionOptions clientEncryptionOptions)
{
var cryptClientSettings = new CryptClientSettings(
bypassQueryAnalysis: null,
cryptSharedLibPath: null,
cryptSharedLibSearchPath: null,
encryptedFieldsMap: null,
isCryptSharedLibRequired: null,
kmsProviders: clientEncryptionOptions.KmsProviders,
schemaMap: null);
_cryptClient = CryptClientCreator.CreateCryptClient(cryptClientSettings);
_libMongoCryptController = new ExplicitEncryptionLibMongoCryptController(
_cryptClient,
clientEncryptionOptions);
}
// public methods
/// <summary>
/// Adds an alternate key name to the keyAltNames array of the key document in the key vault collection with the given UUID (BSON binary subtype 0x04).
/// </summary>
/// <param name="id">The id.</param>
/// <param name="alternateKeyName">The alternate key name.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Returns the previous version of the key document.</returns>
public BsonDocument AddAlternateKeyName(Guid id, string alternateKeyName, CancellationToken cancellationToken = default) =>
_libMongoCryptController.AddAlternateKeyName(id, alternateKeyName, cancellationToken);
/// <summary>
/// Adds an alternate key name to the keyAltNames array of the key document in the key vault collection with the given UUID (BSON binary subtype 0x04).
/// </summary>
/// <param name="id">The id.</param>
/// <param name="alternateKeyName">The key alter name.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Returns the previous version of the key document.</returns>
public Task<BsonDocument> AddAlternateKeyNameAsync(Guid id, string alternateKeyName, CancellationToken cancellationToken = default) =>
_libMongoCryptController.AddAlternateKeyNameAsync(id, alternateKeyName, cancellationToken);
/// <summary>
/// Create encrypted collection.
/// </summary>
/// <param name="database">The database.</param>
/// <param name="collectionName">The collection name.</param>
/// <param name="createCollectionOptions">The create collection options.</param>
/// <param name="kmsProvider">The kms provider.</param>
/// <param name="dataKeyOptions">The datakey options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The operation result.</returns>
/// <remarks>
/// if EncryptionFields contains a keyId with a null value, a data key will be automatically generated and assigned to keyId value.
/// </remarks>
public CreateEncryptedCollectionResult CreateEncryptedCollection(IMongoDatabase database, string collectionName, CreateCollectionOptions createCollectionOptions, string kmsProvider, DataKeyOptions dataKeyOptions, CancellationToken cancellationToken = default)
{
Ensure.IsNotNull(database, nameof(database));
Ensure.IsNotNull(collectionName, nameof(collectionName));
Ensure.IsNotNull(createCollectionOptions, nameof(createCollectionOptions));
Ensure.IsNotNull(dataKeyOptions, nameof(dataKeyOptions));
Ensure.IsNotNull(kmsProvider, nameof(kmsProvider));
var encryptedFields = createCollectionOptions.EncryptedFields?.DeepClone()?.AsBsonDocument;
try
{
foreach (var fieldDocument in EncryptedCollectionHelper.IterateEmptyKeyIds(new CollectionNamespace(database.DatabaseNamespace.DatabaseName, collectionName), encryptedFields))
{
var dataKey = CreateDataKey(kmsProvider, dataKeyOptions, cancellationToken);
EncryptedCollectionHelper.ModifyEncryptedFields(fieldDocument, dataKey);
}
var effectiveCreateEncryptionOptions = createCollectionOptions.Clone();
effectiveCreateEncryptionOptions.EncryptedFields = encryptedFields;
database.CreateCollection(collectionName, effectiveCreateEncryptionOptions, cancellationToken);
}
catch (Exception ex)
{
throw new MongoEncryptionCreateCollectionException(ex, encryptedFields);
}
return new CreateEncryptedCollectionResult(encryptedFields);
}
/// <summary>
/// Create encrypted collection.
/// </summary>
/// <param name="database">The database.</param>
/// <param name="collectionName">The collection name.</param>
/// <param name="createCollectionOptions">The create collection options.</param>
/// <param name="kmsProvider">The kms provider.</param>
/// <param name="dataKeyOptions">The datakey options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The operation result.</returns>
/// <remarks>
/// if EncryptionFields contains a keyId with a null value, a data key will be automatically generated and assigned to keyId value.
/// </remarks>
public async Task<CreateEncryptedCollectionResult> CreateEncryptedCollectionAsync(IMongoDatabase database, string collectionName, CreateCollectionOptions createCollectionOptions, string kmsProvider, DataKeyOptions dataKeyOptions, CancellationToken cancellationToken = default)
{
Ensure.IsNotNull(database, nameof(database));
Ensure.IsNotNull(collectionName, nameof(collectionName));
Ensure.IsNotNull(createCollectionOptions, nameof(createCollectionOptions));
Ensure.IsNotNull(dataKeyOptions, nameof(dataKeyOptions));
Ensure.IsNotNull(kmsProvider, nameof(kmsProvider));
var encryptedFields = createCollectionOptions.EncryptedFields?.DeepClone()?.AsBsonDocument;
try
{
foreach (var fieldDocument in EncryptedCollectionHelper.IterateEmptyKeyIds(new CollectionNamespace(database.DatabaseNamespace.DatabaseName, collectionName), encryptedFields))
{
var dataKey = await CreateDataKeyAsync(kmsProvider, dataKeyOptions, cancellationToken).ConfigureAwait(false);
EncryptedCollectionHelper.ModifyEncryptedFields(fieldDocument, dataKey);
}
var effectiveCreateEncryptionOptions = createCollectionOptions.Clone();
effectiveCreateEncryptionOptions.EncryptedFields = encryptedFields;
await database.CreateCollectionAsync(collectionName, effectiveCreateEncryptionOptions, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
throw new MongoEncryptionCreateCollectionException(ex, encryptedFields);
}
return new CreateEncryptedCollectionResult(encryptedFields);
}
/// <summary>
/// An alias function equivalent to createKey.
/// </summary>
/// <param name="kmsProvider">The kms provider.</param>
/// <param name="dataKeyOptions">The data key options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A data key.</returns>
public Guid CreateDataKey(string kmsProvider, DataKeyOptions dataKeyOptions, CancellationToken cancellationToken = default) =>
_libMongoCryptController.CreateDataKey(
kmsProvider,
dataKeyOptions,
cancellationToken);
/// <summary>
/// An alias function equivalent to createKey.
/// </summary>
/// <param name="kmsProvider">The kms provider.</param>
/// <param name="dataKeyOptions">The data key options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A data key.</returns>
public Task<Guid> CreateDataKeyAsync(string kmsProvider, DataKeyOptions dataKeyOptions, CancellationToken cancellationToken = default) =>
_libMongoCryptController.CreateDataKeyAsync(
kmsProvider,
dataKeyOptions,
cancellationToken);
/// <summary>
/// Decrypts the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The decrypted value.</returns>
public BsonValue Decrypt(BsonBinaryData value, CancellationToken cancellationToken = default) => _libMongoCryptController.DecryptField(value, cancellationToken);
/// <summary>
/// Decrypts the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The decrypted value.</returns>
public Task<BsonValue> DecryptAsync(BsonBinaryData value, CancellationToken cancellationToken = default) => _libMongoCryptController.DecryptFieldAsync(value, cancellationToken);
/// <summary>
/// Removes the key document with the given UUID (BSON binary subtype 0x04) from the key vault collection.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Returns the result of the internal deleteOne() operation on the key vault collection.</returns>
public DeleteResult DeleteKey(Guid id, CancellationToken cancellationToken = default) =>
_libMongoCryptController.DeleteKey(id, cancellationToken);
/// <summary>
/// Removes the key document with the given UUID (BSON binary subtype 0x04) from the key vault collection.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Returns the result of the internal deleteOne() operation on the key vault collection.</returns>
public Task<DeleteResult> DeleteKeyAsync(Guid id, CancellationToken cancellationToken = default) =>
_libMongoCryptController.DeleteKeyAsync(id, cancellationToken);
/// <inheritdoc />
public void Dispose()
{
if (!_disposed)
{
_cryptClient.Dispose();
_disposed = true;
}
}
/// <summary>
/// Encrypts the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="encryptOptions">The encrypt options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The encrypted value.</returns>
public BsonBinaryData Encrypt(BsonValue value, EncryptOptions encryptOptions, CancellationToken cancellationToken = default) => _libMongoCryptController.EncryptField(value, encryptOptions, cancellationToken);
/// <summary>
/// Encrypts the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="encryptOptions">The encrypt options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The encrypted value.</returns>
public Task<BsonBinaryData> EncryptAsync(BsonValue value, EncryptOptions encryptOptions, CancellationToken cancellationToken = default) => _libMongoCryptController.EncryptFieldAsync(value, encryptOptions, cancellationToken);
/// <summary>
/// Finds a single key document with the given UUID (BSON binary subtype 0x04).
/// </summary>
/// <param name="id">The id.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Returns the result of the internal find() operation on the key vault collection.</returns>
public BsonDocument GetKey(Guid id, CancellationToken cancellationToken = default) =>
_libMongoCryptController.GetKey(id, cancellationToken);
/// <summary>
/// Finds a single key document with the given UUID (BSON binary subtype 0x04).
/// </summary>
/// <param name="id">The id.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Returns the result of the internal find() operation on the key vault collection.</returns>
public Task<BsonDocument> GetKeyAsync(Guid id, CancellationToken cancellationToken = default) =>
_libMongoCryptController.GetKeyAsync(id, cancellationToken);
/// <summary>
/// Finds a single key document with the given alter name.
/// </summary>
/// <param name="alternateKeyName">The alternate key name.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Returns a key document in the key vault collection with the given alternateKeyName.</returns>
public BsonDocument GetKeyByAlternateKeyName(string alternateKeyName, CancellationToken cancellationToken = default) =>
_libMongoCryptController.GetKeyByAlternateKeyName(alternateKeyName, cancellationToken);
/// <summary>
/// Finds a single key document with the given UUID (BSON binary subtype 0x04).
/// </summary>
/// <param name="alternateKeyName">The alternate key name.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Returns a key document in the key vault collection with the given alternateKeyName.</returns>
public Task<BsonDocument> GetKeyByAlternateKeyNameAsync(string alternateKeyName, CancellationToken cancellationToken = default) =>
_libMongoCryptController.GetKeyByAlternateKeyNameAsync(alternateKeyName, cancellationToken);
/// <summary>
/// Finds all documents in the key vault collection.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Returns the result of the internal find() operation on the key vault collection.</returns>
public IReadOnlyList<BsonDocument> GetKeys(CancellationToken cancellationToken = default) =>
_libMongoCryptController.GetKeys(cancellationToken);
/// <summary>
/// Finds all documents in the key vault collection.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Returns the result of the internal find() operation on the key vault collection.</returns>
public Task<IReadOnlyList<BsonDocument>> GetKeysAsync(CancellationToken cancellationToken = default) =>
_libMongoCryptController.GetKeysAsync(cancellationToken);
/// <summary>
/// Removes an alternateKeyName from the keyAltNames array of the key document in the key vault collection with the given UUID (BSON binary subtype 0x04).
/// </summary>
/// <param name="id">The id.</param>
/// <param name="alternateKeyName">The alternate key name.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Returns the previous version of the key document.</returns>
public BsonDocument RemoveAlternateKeyName(Guid id, string alternateKeyName, CancellationToken cancellationToken = default) =>
_libMongoCryptController.RemoveAlternateKeyName(id, alternateKeyName, cancellationToken);
/// <summary>
/// Removes an alternateKeyName from the keyAltNames array of the key document in the key vault collection with the given UUID (BSON binary subtype 0x04).
/// </summary>
/// <param name="id">The id.</param>
/// <param name="alternateKeyName">The alternate key name.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Returns the previous version of the key document.</returns>
public Task<BsonDocument> RemoveAlternateKeyNameAsync(Guid id, string alternateKeyName, CancellationToken cancellationToken = default) =>
_libMongoCryptController.RemoveAlternateKeyNameAsync(id, alternateKeyName, cancellationToken);
/// <summary>
/// Decrypts multiple data keys and (re-)encrypts them with a new masterKey, or with their current masterKey if a new one is not given.
/// </summary>
/// <param name="filter">The filter.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result.</returns>
public RewrapManyDataKeyResult RewrapManyDataKey(FilterDefinition<BsonDocument> filter, RewrapManyDataKeyOptions options, CancellationToken cancellationToken = default) =>
_libMongoCryptController.RewrapManyDataKey(filter, options, cancellationToken);
/// <summary>
/// Decrypts multiple data keys and (re-)encrypts them with a new masterKey, or with their current masterKey if a new one is not given.
/// </summary>
/// <param name="filter">The filter.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result.</returns>
public Task<RewrapManyDataKeyResult> RewrapManyDataKeyAsync(FilterDefinition<BsonDocument> filter, RewrapManyDataKeyOptions options, CancellationToken cancellationToken = default) =>
_libMongoCryptController.RewrapManyDataKeyAsync(filter, options, cancellationToken);
}
}