forked from mongodb/node-mongodb-native
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutf8_validation.test.ts
More file actions
254 lines (214 loc) · 8.4 KB
/
utf8_validation.test.ts
File metadata and controls
254 lines (214 loc) · 8.4 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
import { expect } from 'chai';
import * as net from 'net';
import * as process from 'process';
import * as sinon from 'sinon';
import { type Collection, type MongoClient, MongoServerError } from '../../../../src';
import { BSONError, deserialize } from '../../../../src/bson';
import { OpMsgResponse } from '../../../../src/cmap/commands';
describe('class MongoDBResponse', () => {
let client;
afterEach(async () => {
sinon.restore();
if (client) await client.close();
});
context(
'when the server is given a long multibyte utf sequence and there is a writeError that includes invalid utf8',
() => {
let client: MongoClient;
let error: MongoServerError;
for (const { optionDescription, options } of [
{ optionDescription: 'explicitly enabled', options: { enableUtf8Validation: true } },
{ optionDescription: 'explicitly disabled', options: { enableUtf8Validation: false } },
{ optionDescription: 'omitted', options: {} }
]) {
context('when utf8 validation is ' + optionDescription, function () {
beforeEach(async function () {
client = this.configuration.newClient();
async function generateWriteErrorWithInvalidUtf8() {
// Insert a large string of multibyte UTF-8 characters
const _id = '\u{1F92A}'.repeat(100);
const test = client.db('parsing').collection<{ _id: string }>('parsing');
await test.insertOne({ _id }, options);
const spy = sinon.spy(OpMsgResponse.prototype, 'parse');
error = await test.insertOne({ _id }).catch(error => error);
// Check that the server sent us broken BSON (bad UTF)
expect(() => {
deserialize(spy.returnValues[0], { validation: { utf8: true } });
}).to.throw(BSONError, /Invalid UTF/i, 'did not generate error with invalid utf8');
}
await generateWriteErrorWithInvalidUtf8();
});
afterEach(async function () {
sinon.restore();
await client.db('parsing').dropDatabase();
await client.close();
});
it('does not throw a UTF-8 parsing error', function () {
// Assert the driver squashed it
expect(error).to.be.instanceOf(MongoServerError);
expect(error.message).to.match(/duplicate/i);
expect(error.message).to.not.match(/utf/i);
expect(error.errmsg).to.include('\uFFFD');
});
});
}
}
);
});
describe('parsing of utf8-invalid documents with cursors', function () {
let client: MongoClient;
let collection: Collection;
const compressionPredicate = () =>
process.env.COMPRESSOR ? 'Test requires that compression is disabled' : true;
/**
* Inserts a document with malformed utf8 bytes. This method spies on socket.write, and then waits
* for an OP_MSG payload corresponding to `collection.insertOne({ field: 'é' })`, and then modifies the
* bytes of the character 'é', to produce invalid utf8.
*/
async function insertDocumentWithInvalidUTF8() {
const stub = sinon.stub(net.Socket.prototype, 'write').callsFake(function (...args) {
const providedBuffer = args[0].toString('hex');
const targetBytes = Buffer.from(document.field, 'utf-8').toString('hex');
if (providedBuffer.includes(targetBytes)) {
if (providedBuffer.split(targetBytes).length !== 2) {
sinon.restore();
const message = `too many target bytes sequences: received ${
providedBuffer.split(targetBytes).length
}`;
throw new Error(message);
}
const buffer = Buffer.from(providedBuffer.replace(targetBytes, 'c301'.repeat(8)), 'hex');
const result = stub.wrappedMethod.apply(this, [buffer]);
sinon.restore();
return result;
}
const result = stub.wrappedMethod.apply(this, args);
return result;
});
const document = {
field: 'é'.repeat(8)
};
await collection.insertOne(document);
sinon.restore();
}
beforeEach(async function () {
if (typeof compressionPredicate() === 'string') {
this.currentTest.skipReason = compressionPredicate() as string;
this.skip();
}
client = this.configuration.newClient();
await client.connect();
const db = client.db('test');
collection = db.collection('invalidutf');
await collection.deleteMany({});
await insertDocumentWithInvalidUTF8();
});
afterEach(async function () {
sinon.restore();
await client?.close();
});
context('when utf-8 validation is explicitly disabled', function () {
it('documents can be read using a for-await loop without errors', async function () {
for await (const _doc of collection.find({}, { enableUtf8Validation: false }));
});
it('documents can be read using next() without errors', async function () {
const cursor = collection.find({}, { enableUtf8Validation: false });
while (await cursor.hasNext()) {
await cursor.next();
}
});
it('documents can be read using toArray() without errors', async function () {
const cursor = collection.find({}, { enableUtf8Validation: false });
await cursor.toArray();
});
it('documents can be read using .stream() without errors', async function () {
const cursor = collection.find({}, { enableUtf8Validation: false });
await cursor.stream().toArray();
});
it('documents can be read with tryNext() without error', async function () {
const cursor = collection.find({}, { enableUtf8Validation: false });
while (await cursor.hasNext()) {
await cursor.tryNext();
}
});
});
async function expectReject(fn: () => Promise<void>) {
try {
await fn();
expect.fail('expected the provided callback function to reject, but it did not.');
} catch (error) {
expect(error).to.match(/Invalid UTF-8 string in BSON document/);
expect(error).to.be.instanceOf(BSONError);
}
}
context('when utf-8 validation is explicitly enabled', function () {
it('a for-await loop throws a BSON error', async function () {
await expectReject(async () => {
for await (const _doc of collection.find({}, { enableUtf8Validation: true }));
});
});
it('next() throws a BSON error', async function () {
await expectReject(async () => {
const cursor = collection.find({}, { enableUtf8Validation: true });
while (await cursor.hasNext()) {
await cursor.next();
}
});
});
it('toArray() throws a BSON error', async function () {
await expectReject(async () => {
const cursor = collection.find({}, { enableUtf8Validation: true });
await cursor.toArray();
});
});
it('.stream() throws a BSONError', async function () {
await expectReject(async () => {
const cursor = collection.find({}, { enableUtf8Validation: true });
await cursor.stream().toArray();
});
});
it('tryNext() throws a BSONError', async function () {
await expectReject(async () => {
const cursor = collection.find({}, { enableUtf8Validation: true });
while (await cursor.hasNext()) {
await cursor.tryNext();
}
});
});
});
context('utf-8 validation defaults to enabled', function () {
it('a for-await loop throws a BSON error', async function () {
await expectReject(async () => {
for await (const _doc of collection.find({}));
});
});
it('next() throws a BSON error', async function () {
await expectReject(async () => {
const cursor = collection.find({});
while (await cursor.hasNext()) {
await cursor.next();
}
});
});
it('toArray() throws a BSON error', async function () {
await expectReject(async () => {
const cursor = collection.find({});
await cursor.toArray();
});
});
it('.stream() throws a BSONError', async function () {
await expectReject(async () => {
const cursor = collection.find({});
await cursor.stream().toArray();
});
});
it('tryNext() throws a BSONError', async function () {
await expectReject(async () => {
const cursor = collection.find({}, { enableUtf8Validation: true });
while (await cursor.hasNext()) {
await cursor.tryNext();
}
});
});
});
});