summaryrefslogtreecommitdiff
path: root/jstests/fle2/implicit_schema_validation.js
blob: 81098070d7d8d91631a24305621f1497083e2284 (plain)
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
// Verify implicit schema validation works for encrypted collections

/**
 * @tags: [
 * requires_fcv_60,
 * assumes_unsharded_collection,
 * does_not_support_transactions
 * ]
 */
(function() {
'use strict';
load("jstests/libs/doc_validation_utils.js");  // for assertDocumentValidationFailure

const dbTest = db.getSiblingDB('implicit_schema_validation_db');

const validEncryptedString = HexData(6, "060102030405060708091011121314151602");
const validEncryptedInt = HexData(6, "060102030405060708091011121314151610");
const nonEncryptedBinData = HexData(3, "060102030405060708091011121314151610");
const fle1RandomBinData = HexData(6, "020102030405060708091011121314151602");
const fle2PlaceholderBinData = HexData(6, "030102030405060708091011121314151602");

const typeMatchedArrayError = {
    operator: "type",
    reason: "type did match",
    consideredType: "array"
};
const valueNotEncryptedError = {
    operator: "fle2Encrypt",
    reason: "value was not encrypted"
};
const wrongEncryptedTypeError = {
    operator: "fle2Encrypt",
    reason: "Queryable Encryption encrypted value has wrong type"
};

const userMalformedSchema = {
    $or: [
        {name: {$not: {$foo: true}}},
        {name: {$type: "string"}},
    ]
};

const userQueryOpSchema = {
    $or: [
        {name: {$not: {$exists: true}}},
        {name: {$type: "string"}},
    ]
};

const userJsonSchema = {
    $jsonSchema: {
        bsonType: "object",
        properties: {
            name: {
                bsonType: "string",
            }
        }
    }
};

const userJsonConflictSchema = {
    $jsonSchema: {
        bsonType: "object",
        properties: {
            name: {bsonType: "string"},
            firstName: {bsonType: "string"},
        }
    }
};

const fle1Schema = {
    $jsonSchema: {
        bsonType: "object",
        properties: {
            name: {
                encrypt: {
                    algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Random",
                    keyId: [UUID()],
                    bsonType: "string",
                }
            }
        }
    }
};

const sampleEncryptedFields = {
    fields: [
        {
            path: "firstName",
            keyId: UUID("11d58b8a-0c6c-4d69-a0bd-70c6d9befae9"),
            bsonType: "string",
            queries: {"queryType": "equality"}
        },
        {
            path: "a.b.c",
            keyId: UUID("11d58b8a-0c6c-4d69-a0bd-000000000001"),
            bsonType: "int",
            queries: {"queryType": "equality"}
        },
        {
            path: "a.b.d",
            keyId: UUID("11d58b8a-0c6c-4d69-a0bd-000000000002"),
            bsonType: "int",
            queries: {"queryType": "equality"}
        },
        {
            path: "e.g",
            keyId: UUID("11d58b8a-0c6c-4d69-a0bd-000000000003"),
            bsonType: "string",
            queries: {"queryType": "equality"}
        },
        {
            path: "a.x.y",
            keyId: UUID("11d58b8a-0c6c-4d69-a0bd-000000000004"),
            bsonType: "string",
            queries: {"queryType": "equality"}
        },
    ]
};

/**
 * Finds the sub-object starting at 'obj' that contains the property 'key'
 * and has the string value 'value'
 * @param {object} obj the object to traverse
 * @param {string} key the attribute name to find
 * @param {string} value the attribute value to find
 * @returns the first subobject found that contains the target key-value pair
 */
function findContainingObject(obj, key, value) {
    let queue = [obj];
    while (queue.length > 0) {
        let o = queue.shift();
        if (o.hasOwnProperty(key) && o[key] === value) {
            return o;
        }
        for (let prop in o) {
            if (typeof o[prop] === "object" && o[prop] !== null) {
                queue.push(o[prop]);
            }
        }
    }
    return null;
}

/**
 * Asserts the result of a command is a document validation failure.
 * If 'fleErrors' is defined, then this asserts that the errInfo in the result
 * contains an "implicitFLESchema" annotation, and an annotation for each
 * attribute in 'fleErrors'. Each attribute in 'fleErrors' is a pair where the key
 * is the encrypted field path that is expected to cause an error, and the value is
 * an object containing the expected 'operatorName' and detail fields.
 */
function assertFailedWithAnnotation(result, coll, fleErrors) {
    assertDocumentValidationFailure(result, coll);
    assert(result instanceof WriteResult);
    const errInfo = result.getWriteError().errInfo;
    const schema = findContainingObject(errInfo, "operatorName", "implicitFLESchema");

    if (fleErrors) {
        assert(schema,
               "Result errInfo does not contain an implicitFLESchema error: " + tojson(errInfo));
    } else {
        assert(!schema,
               "Result errInfo contains unexpected implicitFLESchema error: " + tojson(errInfo));
        return;
    }
    assert(schema.hasOwnProperty("schemaRulesNotSatisfied"));

    for (let path in fleErrors) {
        const pathParts = path.split('.');
        let subschema = schema;
        for (let pathIdx in pathParts) {
            subschema = findContainingObject(subschema, "propertyName", pathParts[pathIdx]);
            assert(subschema, "No errors found for property '" + path + "': " + tojson(errInfo));
        }
        assert(subschema.hasOwnProperty("details"),
               "No error details found for property '" + path + "': " + tojson(errInfo));

        const detail =
            findContainingObject(subschema.details, "operatorName", fleErrors[path].operator);
        assert(detail,
               "Error details for property '" + path +
                   "' does not contain the expected operator '" + fleErrors[path].operator +
                   "': " + tojson(errInfo));

        for (let field in fleErrors[path]) {
            if (field === "operator") {
                continue;
            }
            const detailWithField = findContainingObject(detail, field, fleErrors[path][field]);
            assert(detailWithField,
                   "Error details for property '" + path + "' does not contain the expected " +
                       field + " '" + fleErrors[path][field] + "': " + tojson(errInfo));
        }
    }
}

// Tests invalid inserts on encrypted collection 'coll'.
// This assumes 'coll' was created encrypted fields specified in 'sampleEncryptedFields'.
// If 'hasUserValidator' is true, this assumes it validates the optional field 'name' is a string.
function negativeTests(coll, hasUserValidator, invert = false) {
    function assertExpectedResult(result, fleErrors) {
        if (invert) {
            assert.commandWorked(result);
        } else {
            assertFailedWithAnnotation(result, coll, fleErrors);
        }
        return result;
    }

    jsTestLog("test inserting non-bindata value for encrypted field");
    assertExpectedResult(coll.insert({firstName: "foo"}), {firstName: valueNotEncryptedError});
    assertExpectedResult(coll.insert({
        firstName: validEncryptedString,
        a: {
            b: {
                c: "bar",
                d: "foo",
            },
        }
    }),
                         {"a.b.c": valueNotEncryptedError, "a.b.d": valueNotEncryptedError});

    jsTestLog("test path to encrypted field has arrays");
    assertExpectedResult(coll.insert({a: [{b: {c: validEncryptedInt}}]}),
                         {"a": typeMatchedArrayError});
    assertExpectedResult(coll.insert({a: {b: [{c: validEncryptedInt}]}}),
                         {"a.b": typeMatchedArrayError});
    assertExpectedResult(coll.insert({a: {b: {c: []}}}), {"a.b.c": valueNotEncryptedError});

    jsTestLog("test inserting encrypted field with BinData of incorrect subtype");
    assertExpectedResult(coll.insert({firstName: nonEncryptedBinData}),
                         {firstName: valueNotEncryptedError});
    assertExpectedResult(coll.insert({
        firstName: validEncryptedString,
        a: {
            b: {
                c: nonEncryptedBinData,
                d: validEncryptedInt,
            },
        }
    }),
                         {"a.b.c": valueNotEncryptedError});

    jsTestLog("test inserting encrypted field with incorrect Queryable Encryption subtype");
    assertExpectedResult(coll.insert({firstName: fle1RandomBinData}),
                         {firstName: wrongEncryptedTypeError});
    assertExpectedResult(coll.insert({
        firstName: validEncryptedString,
        a: {
            b: {
                c: fle2PlaceholderBinData,
                d: validEncryptedInt,
            },
        }
    }),
                         {"a.b.c": wrongEncryptedTypeError});

    jsTestLog(
        "test inserting encrypted field with incorrect BSONType specifier for the unencrypted value");
    assertExpectedResult(coll.insert({firstName: validEncryptedInt}),
                         {firstName: wrongEncryptedTypeError});
    assertExpectedResult(coll.insert({
        firstName: validEncryptedString,
        a: {
            b: {
                c: validEncryptedString,
                d: validEncryptedInt,
            },
        }
    }),
                         {"a.b.c": wrongEncryptedTypeError});

    if (!hasUserValidator) {
        return;
    }

    jsTestLog("test insert violating user-provided validator");
    assertExpectedResult(coll.insert({firstName: validEncryptedString, name: 234}));
    assertExpectedResult(coll.insert({firstName: nonEncryptedBinData, name: 234}),
                         {firstName: valueNotEncryptedError});
}

// Tests invalid updates on encrypted collection 'coll'
// This assumes 'coll' was created encrypted fields specified in 'sampleEncryptedFields'.
function negativeUpdateTests(coll, invert = false) {
    function assertExpectedResult(result, fleErrors) {
        if (invert) {
            assert.commandWorked(result);
        } else {
            assertFailedWithAnnotation(result, coll, fleErrors);
        }
    }

    // first, insert a valid document to update
    assert.commandWorked(coll.insert({
        test_id: 0,
        firstName: validEncryptedString,
        a: {
            b: {
                c: validEncryptedInt,
                d: validEncryptedInt,
            },
            x: {
                y: validEncryptedString,
            }
        }
    }));

    jsTestLog("test updating encrypted field with invalid value");
    assertExpectedResult(coll.update({"test_id": 0}, {$set: {"firstName": "roger"}}),
                         {firstName: valueNotEncryptedError});
    assertExpectedResult(coll.update({"test_id": 0}, {$set: {"firstName": nonEncryptedBinData}}),
                         {firstName: valueNotEncryptedError});
    assertExpectedResult(coll.update({"test_id": 0}, {$set: {"firstName": fle1RandomBinData}}),
                         {firstName: wrongEncryptedTypeError});
    assertExpectedResult(coll.update({"test_id": 0}, {$set: {"firstName": validEncryptedInt}}),
                         {firstName: wrongEncryptedTypeError});
    assertExpectedResult(coll.update({"test_id": 0}, {$set: {"a.x.y": [1, 2, 3]}}),
                         {"a.x.y": valueNotEncryptedError});
    assertExpectedResult(coll.update({"test_id": 0}, {$set: {"a.x": {"y": 42}}}),
                         {"a.x": valueNotEncryptedError});

    jsTestLog("test updating prefix of encrypted field with array value");
    assertExpectedResult(coll.update({"test_id": 0}, {$set: {"a.b": [1, 2, 3]}}),
                         {"a.b": typeMatchedArrayError});
}

// Tests valid inserts on encrypted collection 'coll'.
// This assumes 'coll' was created encrypted fields specified in 'sampleEncryptedFields'.
// If 'hasUserValidator' is true, this assumes it validates the optional field 'name' is a string.
function positiveTests(coll, hasUserValidator, invert = false) {
    function assertExpectedResult(result) {
        if (invert) {
            assert.commandFailedWithCode(result, ErrorCodes.DocumentValidationFailure);
        } else {
            assert.commandWorked(result);
        }
    }

    jsTestLog("test inserting document without any encrypted fields");
    assert.commandWorked(coll.insert({}));
    assert.commandWorked(coll.insert({foo: 1}));
    assert.commandWorked(coll.insert({a: {foo: 1}}));
    assert.commandWorked(coll.insert({a: {b: {foo: 1}, x: {foo: 1}}}));

    jsTestLog("test inserting single encrypted field with valid type");
    assertExpectedResult(coll.insert({firstName: validEncryptedString}));

    jsTestLog("test inserting multiple encrypted fields with valid type");
    assertExpectedResult(coll.insert({
        firstName: validEncryptedString,
        a: {
            b: {
                c: validEncryptedInt,
                d: validEncryptedInt,
            },
            x: {
                y: validEncryptedString,
            }
        }
    }));

    jsTestLog("test inserting non-object along encrypted path");
    assertExpectedResult(coll.insert({
        firstName: validEncryptedString,
        a: "foo",
    }));
    assertExpectedResult(coll.insert({
        firstName: validEncryptedString,
        a: {
            b: {
                c: validEncryptedInt,
                d: validEncryptedInt,
            },
            x: "foo",
        }
    }));

    jsTestLog("test insert satisfies user-provided validator");
    assertExpectedResult(coll.insert({name: "joe", firstName: validEncryptedString}));
}

// Tests valid updates on encrypted collection 'coll'
// This assumes 'coll' was created encrypted fields specified in 'sampleEncryptedFields'.
function positiveUpdateTests(coll, invert = false) {
    function assertExpectedResult(result) {
        if (invert) {
            assert.commandFailedWithCode(result, ErrorCodes.DocumentValidationFailure);
        } else {
            assert.commandWorked(result);
        }
    }

    // first, insert a valid document to update
    assert.commandWorked(coll.insert({
        test_id: 0,
        firstName: validEncryptedString,
        a: {
            b: {
                c: validEncryptedInt,
                d: validEncryptedInt,
            },
            x: {
                y: validEncryptedString,
            }
        }
    }));

    jsTestLog("test unset & set of encrypted field");
    assertExpectedResult(coll.update({"test_id": 0}, {$unset: {"firstName": ""}}));
    assertExpectedResult(coll.update({"test_id": 0}, {$set: {"firstName": validEncryptedString}}));
    assertExpectedResult(
        coll.update({"test_id": 0}, {$set: {"a": {"x": {"y": validEncryptedString}}}}));
    assertExpectedResult(coll.update({"test_id": 0}, {$set: {"a.x": {"y": validEncryptedString}}}));

    jsTestLog("test updating prefix of encrypted field with non-array value");
    assertExpectedResult(coll.update({"test_id": 0}, {$set: {"a.b": 1}}));
    assertExpectedResult(coll.update({"test_id": 0}, {$set: {"a.x": {"z": 42}}}));
}

jsTestLog("test implicit validator only");
dbTest.test.drop();
assert.commandWorked(dbTest.createCollection("test", {encryptedFields: sampleEncryptedFields}));
negativeTests(dbTest.test, false);
positiveTests(dbTest.test, false);

jsTestLog("test implicit validator with user validator containing query ops");
dbTest.test.drop();
assert.commandWorked(dbTest.createCollection(
    "test", {encryptedFields: sampleEncryptedFields, validator: userQueryOpSchema}));
negativeTests(dbTest.test, true);
positiveTests(dbTest.test, true);

jsTestLog("test implicit validator with user validator containing json schema");
dbTest.test.drop();
assert.commandWorked(dbTest.createCollection(
    "test", {encryptedFields: sampleEncryptedFields, validator: userJsonSchema}));
negativeTests(dbTest.test, true);
positiveTests(dbTest.test, true);

jsTestLog("test user validator rules conflicting with implicit rules");
dbTest.test.drop();
assert.commandWorked(dbTest.createCollection(
    "test", {encryptedFields: sampleEncryptedFields, validator: userJsonConflictSchema}));
negativeTests(dbTest.test, true);
positiveTests(dbTest.test, true, true);

jsTestLog("test malformed user validator on encrypted collection");
dbTest.test.drop();
assert.commandFailed(dbTest.createCollection(
    "test", {encryptedFields: sampleEncryptedFields, validator: userMalformedSchema}));

jsTestLog("test FLE1 schema validator on Queryable Encryption collection");
dbTest.test.drop();
assert.commandFailedWithCode(
    dbTest.createCollection("test",
                            {encryptedFields: sampleEncryptedFields, validator: fle1Schema}),
    ErrorCodes.QueryFeatureNotAllowed);

jsTestLog("test collMod adding user validator on encrypted collection");
dbTest.test.drop();
assert.commandWorked(dbTest.createCollection("test", {encryptedFields: sampleEncryptedFields}));
assert.commandWorked(dbTest.runCommand({collMod: "test", validator: userQueryOpSchema}));
negativeTests(dbTest.test, true);
positiveTests(dbTest.test, true);

jsTestLog("test collMod adding FLE1 user validator on encrypted collection");
dbTest.test.drop();
assert.commandWorked(dbTest.createCollection("test", {encryptedFields: sampleEncryptedFields}));
assert.commandFailedWithCode(dbTest.runCommand({collMod: "test", validator: fle1Schema}),
                             ErrorCodes.QueryFeatureNotAllowed);

jsTestLog("test implicit validation works on updates");
dbTest.test.drop();
assert.commandWorked(dbTest.createCollection("test", {encryptedFields: sampleEncryptedFields}));
negativeUpdateTests(dbTest.test);
positiveUpdateTests(dbTest.test);
}());