-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathmongodb-handshake.prose.test.ts
More file actions
355 lines (318 loc) · 12.8 KB
/
mongodb-handshake.prose.test.ts
File metadata and controls
355 lines (318 loc) · 12.8 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
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
import { expect } from 'chai';
import * as sinon from 'sinon';
import {
Connection,
getFAASEnv,
Int32,
LEGACY_HELLO_COMMAND,
type MongoClient
} from '../../mongodb';
import { sleep } from '../../tools/utils';
type EnvironmentVariables = Array<[string, string]>;
function stubEnv(env: EnvironmentVariables) {
let cachedEnv: NodeJS.ProcessEnv;
before(function () {
cachedEnv = process.env;
process.env = {
...process.env,
...Object.fromEntries(env)
};
});
after(function () {
process.env = cachedEnv;
});
}
describe('Handshake Prose Tests', function () {
let client: MongoClient;
afterEach(async function () {
await client?.close();
});
const tests: Array<{
context: string;
expectedProvider: string | undefined;
env: EnvironmentVariables;
}> = [
{
context: '1. Valid AWS',
expectedProvider: 'aws.lambda',
env: [
['AWS_EXECUTION_ENV', 'AWS_Lambda_java8'],
['AWS_REGION', 'us-east-2'],
['AWS_LAMBDA_FUNCTION_MEMORY_SIZE', '1024']
]
},
{
context: '2. Valid Azure',
expectedProvider: 'azure.func',
env: [['FUNCTIONS_WORKER_RUNTIME', 'node']]
},
{
context: '3. Valid GCP',
expectedProvider: 'gcp.func',
env: [
['K_SERVICE', 'servicename'],
['FUNCTION_MEMORY_MB', '1024'],
['FUNCTION_TIMEOUT_SEC', '60'],
['FUNCTION_REGION', 'us-central1']
]
},
{
context: '4. Valid Vercel',
expectedProvider: 'vercel',
env: [
['VERCEL', '1'],
['VERCEL_REGION', 'cdg1']
]
},
{
expectedProvider: undefined,
context: '5. Invalid - multiple providers',
env: [
['AWS_EXECUTION_ENV', 'AWS_Lambda_java8'],
['FUNCTIONS_WORKER_RUNTIME', 'node']
]
},
{
expectedProvider: 'aws.lambda',
context: '6. Invalid - long string',
env: [
['AWS_EXECUTION_ENV', 'AWS_Lambda_java8'],
['AWS_REGION', 'a'.repeat(1024)]
]
},
{
expectedProvider: 'aws.lambda',
context: '7. Invalid - wrong types',
env: [
['AWS_EXECUTION_ENV', 'AWS_Lambda_java8'],
['AWS_LAMBDA_FUNCTION_MEMORY_SIZE', 'big']
]
},
{
expectedProvider: undefined,
context: '8. Invalid - AWS_EXECUTION_ENV does not start with "AWS_Lambda_"',
env: [['AWS_EXECUTION_ENV', 'EC2']]
}
];
for (const { context: name, env, expectedProvider } of tests) {
context(name, function () {
stubEnv(env);
it(`metadata confirmation test for ${name}`, function () {
expect(getFAASEnv()?.get('name')).to.equal(
expectedProvider,
'determined the wrong cloud provider'
);
});
it('runs a hello successfully', async function () {
client = this.configuration.newClient({
// if the handshake is not truncated, the `hello`s fail and the client does
// not connect. Lowering the server selection timeout causes the tests
// to fail more quickly in that scenario.
serverSelectionTimeoutMS: 3000
});
await client.connect();
});
});
}
context('Test 9: Valid container and FaaS provider', function () {
stubEnv([
['AWS_EXECUTION_ENV', 'AWS_Lambda_java8'],
['AWS_REGION', 'us-east-2'],
['AWS_LAMBDA_FUNCTION_MEMORY_SIZE', '1024'],
['KUBERNETES_SERVICE_HOST', '1']
]);
it('runs a hello successfully', async function () {
client = this.configuration.newClient({
// if the handshake is not truncated, the `hello`s fail and the client does
// not connect. Lowering the server selection timeout causes the tests
// to fail more quickly in that scenario.
serverSelectionTimeoutMS: 3000
});
await client.connect();
});
it('includes both container and FAAS provider information in the client metadata', async function () {
client = this.configuration.newClient();
await client.connect();
expect(client.topology?.s.options.extendedMetadata).to.exist;
const { env } = await client.topology.s.options.extendedMetadata;
expect(env).to.deep.equal({
region: 'us-east-2',
name: 'aws.lambda',
memory_mb: new Int32(1024),
container: { orchestrator: 'kubernetes' }
});
});
});
context(`Test 2: Test that the driver accepts an arbitrary auth mechanism`, function () {
let stubCalled = false;
beforeEach(() => {
// Mock the server response in a way that saslSupportedMechs array in the hello command response contains an arbitrary string.
sinon.stub(Connection.prototype, 'command').callsFake(async function (ns, cmd, options) {
// @ts-expect-error: sinon will place wrappedMethod there
const command = Connection.prototype.command.wrappedMethod.bind(this);
if (cmd.hello || cmd[LEGACY_HELLO_COMMAND]) {
return stub();
}
return command(ns, cmd, options);
async function stub() {
stubCalled = true;
const response = await command(ns, cmd, options);
return {
...response,
saslSupportedMechs: [...(response.saslSupportedMechs ?? []), 'random string']
};
}
});
});
afterEach(() => sinon.restore());
it('no error is thrown', { requires: { auth: 'enabled' } }, async function () {
// Create and connect a Connection object that connects to the server that returns the mocked response.
// Assert that no error is raised.
client = this.configuration.newClient();
await client.connect();
await client.db('foo').collection('bar').insertOne({ name: 'john doe' });
expect(stubCalled).to.be.true;
await client.close();
});
});
});
describe('Client Metadata Update Prose Tests', function () {
let client: MongoClient;
afterEach(async function () {
await client?.close();
sinon.restore();
});
describe('Test 1: Test that the driver updates metadata', function () {
let initialClientMetadata;
let updatedClientMetadata;
const tests = [
{ testCase: 1, name: 'framework', version: '2.0', platform: 'Framework Platform' },
{ testCase: 2, name: 'framework', version: '2.0' },
{ testCase: 3, name: 'framework', platform: 'Framework Platform' },
{ testCase: 4, name: 'framework' }
];
for (const { testCase, name, version, platform } of tests) {
context(`Case: ${testCase}`, function () {
// 1. Create a `MongoClient` instance with the following:
// - `maxIdleTimeMS` set to `1ms`
// - Wrapping library metadata:
// | Field | Value |
// | -------- | ---------------- |
// | name | library |
// | version | 1.2 |
// | platform | Library Platform |
// 2. Send a `ping` command to the server and verify that the command succeeds.
// 3. Save intercepted `client` document as `initialClientMetadata`.
// 4. Wait 5ms for the connection to become idle.
beforeEach(async function () {
client = this.configuration.newClient(
{},
{
maxIdleTimeMS: 1,
driverInfo: { name: 'library', version: '1.2', platform: 'Library Platform' }
}
);
sinon.stub(Connection.prototype, 'command').callsFake(async function (ns, cmd, options) {
// @ts-expect-error: sinon will place wrappedMethod on the command method.
const command = Connection.prototype.command.wrappedMethod.bind(this);
if (cmd.hello || cmd[LEGACY_HELLO_COMMAND]) {
if (!initialClientMetadata) {
initialClientMetadata = cmd.client;
} else {
updatedClientMetadata = cmd.client;
}
}
return command(ns, cmd, options);
});
await client.db('test').command({ ping: 1 });
await sleep(5);
});
it('appends the metadata', async function () {
// 1. Append the `DriverInfoOptions` from the selected test case to the `MongoClient` metadata.
// 2. Send a `ping` command to the server and verify:
// - The command succeeds.
// - The framework metadata is appended to the existing `DriverInfoOptions` in the `client.driver` fields of the `hello`
// command, with values separated by a pipe `|`.
client.appendMetadata({ name, version, platform });
await client.db('test').command({ ping: 1 });
// Since we have our own driver metadata getting added, we really want to just
// assert that the last driver info values are appended at the end.
expect(updatedClientMetadata.driver.name).to.match(/^.*\|framework$/);
expect(updatedClientMetadata.driver.version).to.match(
new RegExp(`^.*\\|${version ? version : '1.2'}$`)
);
expect(updatedClientMetadata.platform).to.match(
new RegExp(`^.*\\|${platform ? platform : 'Library Platform'}$`)
);
// - All other subfields in the client document remain unchanged from initialClientMetadata.
// (Note os is the only one getting set in these tests)
expect(updatedClientMetadata.os).to.deep.equal(initialClientMetadata.os);
});
});
}
});
describe('Test 2: Multiple Successive Metadata Updates', function () {
let initialClientMetadata;
let updatedClientMetadata;
const tests = [
{ testCase: 1, name: 'framework', version: '2.0', platform: 'Framework Platform' },
{ testCase: 2, name: 'framework', version: '2.0' },
{ testCase: 3, name: 'framework', platform: 'Framework Platform' },
{ testCase: 4, name: 'framework' }
];
for (const { testCase, name, version, platform } of tests) {
context(`Case: ${testCase}`, function () {
// 1. Create a `MongoClient` instance with the following:
// - `maxIdleTimeMS` set to `1ms`
// 2. Append the following `DriverInfoOptions` to the `MongoClient` metadata:
// | Field | Value |
// | -------- | ---------------- |
// | name | library |
// | version | 1.2 |
// | platform | Library Platform |
// 3. Send a `ping` command to the server and verify that the command succeeds.
// 4. Save intercepted `client` document as `updatedClientMetadata`.
// 5. Wait 5ms for the connection to become idle.
beforeEach(async function () {
client = this.configuration.newClient({}, { maxIdleTimeMS: 1 });
client.appendMetadata({ name: 'library', version: '1.2', platform: 'Library Platform' });
sinon.stub(Connection.prototype, 'command').callsFake(async function (ns, cmd, options) {
// @ts-expect-error: sinon will place wrappedMethod on the command method.
const command = Connection.prototype.command.wrappedMethod.bind(this);
if (cmd.hello || cmd[LEGACY_HELLO_COMMAND]) {
if (!initialClientMetadata) {
initialClientMetadata = cmd.client;
} else {
updatedClientMetadata = cmd.client;
}
}
return command(ns, cmd, options);
});
await client.db('test').command({ ping: 1 });
await sleep(5);
});
it('appends the metadata', async function () {
// 1. Append the `DriverInfoOptions` from the selected test case to the `MongoClient` metadata.
// 2. Send a `ping` command to the server and verify:
// - The command succeeds.
// - The framework metadata is appended to the existing `DriverInfoOptions` in the `client.driver` fields of the `hello`
// command, with values separated by a pipe `|`.
client.appendMetadata({ name, version, platform });
await client.db('test').command({ ping: 1 });
// Since we have our own driver metadata getting added, we really want to just
// assert that the last driver info values are appended at the end.
expect(updatedClientMetadata.driver.name).to.match(/^.*\|framework$/);
expect(updatedClientMetadata.driver.version).to.match(
new RegExp(`^.*\\|${version ? version : '1.2'}$`)
);
expect(updatedClientMetadata.platform).to.match(
new RegExp(`^.*\\|${platform ? platform : 'Library Platform'}$`)
);
// - All other subfields in the client document remain unchanged from initialClientMetadata.
// (Note os is the only one getting set in these tests)
expect(updatedClientMetadata.os).to.deep.equal(initialClientMetadata.os);
});
});
}
});
});