-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcloud-sql-instance.ts
More file actions
590 lines (531 loc) · 17.4 KB
/
cloud-sql-instance.ts
File metadata and controls
590 lines (531 loc) · 17.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
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
// Copyright 2023 Google LLC
//
// 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
//
// https://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.
import t from 'tap';
import {IpAddressTypes} from '../src/ip-addresses';
import {AuthTypes} from '../src/auth-types';
import {CA_CERT, CLIENT_CERT, CLIENT_KEY} from './fixtures/certs';
import {setupCredentials} from './fixtures/setup-credentials';
t.test('CloudSQLInstance', async t => {
setupCredentials(t); // setup google-auth credentials mocks
const fetcher = {
async getInstanceMetadata() {
return {
ipAddresses: {
public: '127.0.0.1',
},
serverCaCert: {
cert: CA_CERT,
expirationTime: '2033-01-06T10:00:00.232Z',
},
};
},
async getEphemeralCertificate() {
return {
cert: CLIENT_CERT,
expirationTime: '2033-01-06T10:00:00.232Z',
};
},
};
// mocks crypto module so that it can return a deterministic result
// and set a standard, fast static value for cert refresh interval
const {CloudSQLInstance} = t.mockRequire('../src/cloud-sql-instance', {
'../src/crypto': {
generateKeys: async () => ({
publicKey: '-----BEGIN PUBLIC KEY-----',
privateKey: CLIENT_KEY,
}),
},
'../src/time': {
getRefreshInterval() {
return 50; // defaults to 50ms in unit tests
},
isExpirationTimeValid() {
return true;
},
},
});
t.test('assert basic instance usage and API', async t => {
const instance = await CloudSQLInstance.getCloudSQLInstance({
ipType: IpAddressTypes.PUBLIC,
authType: AuthTypes.PASSWORD,
instanceConnectionName: 'my-project:us-east1:my-instance',
sqlAdminFetcher: fetcher,
});
t.same(
instance.ephemeralCert.cert,
CLIENT_CERT,
'should have expected privateKey'
);
t.same(
instance.instanceInfo,
{
projectId: 'my-project',
regionId: 'us-east1',
instanceId: 'my-instance',
},
'should have expected connection info'
);
t.same(instance.privateKey, CLIENT_KEY, 'should have expected privateKey');
t.same(instance.host, '127.0.0.1', 'should have expected host');
t.same(instance.port, 3307, 'should have expected port');
t.same(
instance.serverCaCert.cert,
CA_CERT,
'should have expected serverCaCert'
);
instance.cancelRefresh();
});
t.test('initial refresh error should throw errors', async t => {
const failedFetcher = {
...fetcher,
async getInstanceMetadata() {
throw new Error('ERR');
},
};
const instance = new CloudSQLInstance({
ipType: IpAddressTypes.PUBLIC,
authType: AuthTypes.PASSWORD,
instanceConnectionName: 'my-project:us-east1:my-instance',
sqlAdminFetcher: failedFetcher,
limitRateInterval: 50,
});
await t.rejects(
instance.refresh(),
/ERR/,
'should raise the specific error to the end user'
);
});
t.test('refresh', t => {
const start = Date.now();
let refreshCount = 0;
const instance = new CloudSQLInstance({
ipType: IpAddressTypes.PUBLIC,
authType: AuthTypes.PASSWORD,
instanceConnectionName: 'my-project:us-east1:my-instance',
sqlAdminFetcher: fetcher,
limitRateInterval: 50,
});
instance.refresh = () => {
if (refreshCount === 2) {
const end = Date.now();
const duration = end - start;
t.ok(
duration >= 100,
`should respect refresh delay time, ${duration}ms elapsed`
);
instance.cancelRefresh();
return t.end();
}
refreshCount++;
t.ok(refreshCount, `should refresh ${refreshCount} times`);
CloudSQLInstance.prototype.refresh.call(instance);
};
// starts out refresh logic
instance.refresh();
});
t.test(
'refresh error should not throw any errors on established connection',
async t => {
let metadataCount = 0;
const failedFetcher = {
...fetcher,
async getInstanceMetadata() {
if (metadataCount === 1) {
throw new Error('ERR');
}
metadataCount++;
return fetcher.getInstanceMetadata();
},
};
const instance = new CloudSQLInstance({
ipType: IpAddressTypes.PUBLIC,
authType: AuthTypes.PASSWORD,
instanceConnectionName: 'my-project:us-east1:my-instance',
sqlAdminFetcher: failedFetcher,
limitRateInterval: 50,
});
await (() =>
new Promise((res): void => {
let refreshCount = 0;
instance.refresh = function mockRefresh() {
if (refreshCount === 3) {
t.ok('done refreshing 3 times');
instance.cancelRefresh();
return res(null);
}
refreshCount++;
t.ok(refreshCount, `should refresh ${refreshCount} times`);
return CloudSQLInstance.prototype.refresh.call(instance);
};
// starts out refresh logic
instance.refresh();
instance.setEstablishedConnection();
}))();
}
);
t.test(
'refresh error with expired cert should not throw any errors on established connection',
async t => {
const {CloudSQLInstance} = t.mockRequire('../src/cloud-sql-instance', {
'../src/crypto': {
generateKeys: async () => ({
publicKey: '-----BEGIN PUBLIC KEY-----',
privateKey: CLIENT_KEY,
}),
},
'../src/time': {
getRefreshInterval() {
return 0; // an expired cert will want to reload right away
},
},
});
let metadataCount = 0;
const failedFetcher = {
...fetcher,
async getInstanceMetadata() {
if (metadataCount === 1) {
throw new Error('ERR');
}
metadataCount++;
return fetcher.getInstanceMetadata();
},
};
const instance = new CloudSQLInstance({
ipType: IpAddressTypes.PUBLIC,
authType: AuthTypes.PASSWORD,
instanceConnectionName: 'my-project:us-east1:my-instance',
sqlAdminFetcher: failedFetcher,
limitRateInterval: 50,
});
await (() =>
new Promise((res): void => {
let refreshCount = 0;
instance.refresh = function mockRefresh() {
if (refreshCount === 3) {
t.ok('done refreshing 3 times');
instance.cancelRefresh();
return res(null);
}
refreshCount++;
t.ok(refreshCount, `should refresh ${refreshCount} times`);
return CloudSQLInstance.prototype.refresh.call(instance);
};
// starts out refresh logic
instance.refresh();
instance.setEstablishedConnection();
}))();
}
);
t.test('forceRefresh', async t => {
const instance = new CloudSQLInstance({
ipType: IpAddressTypes.PUBLIC,
authType: AuthTypes.PASSWORD,
instanceConnectionName: 'my-project:us-east1:my-instance',
sqlAdminFetcher: fetcher,
limitRateInterval: 50,
});
await instance.refresh();
let cancelRefreshCalled = false;
let refreshCalled = false;
instance.cancelRefresh = () => {
cancelRefreshCalled = true;
CloudSQLInstance.prototype.cancelRefresh.call(instance);
instance.cancelRefresh = CloudSQLInstance.prototype.cancelRefresh;
};
instance.refresh = async () => {
refreshCalled = true;
await CloudSQLInstance.prototype.refresh.call(instance);
instance.refresh = CloudSQLInstance.prototype.refresh;
};
await instance.forceRefresh();
t.ok(
cancelRefreshCalled,
'should cancelRefresh current refresh cycle on force refresh'
);
t.ok(refreshCalled, 'should refresh instance info on force refresh');
instance.cancelRefresh();
});
t.test('forceRefresh ongoing cycle', async t => {
const instance = new CloudSQLInstance({
ipType: IpAddressTypes.PUBLIC,
authType: AuthTypes.PASSWORD,
instanceConnectionName: 'my-project:us-east1:my-instance',
sqlAdminFetcher: fetcher,
limitRateInterval: 50,
});
let cancelRefreshCalled = false;
let refreshCalled = false;
instance.refresh();
instance.cancelRefresh = () => {
cancelRefreshCalled = true;
return CloudSQLInstance.prototype.cancelRefresh.call(instance);
};
instance.refresh = () => {
refreshCalled = true;
return CloudSQLInstance.prototype.refresh.call(instance);
};
await instance.forceRefresh();
t.ok(
!cancelRefreshCalled,
'should not call cancelRefresh if refresh already happening'
);
t.ok(!refreshCalled, 'should not refresh if already happening');
CloudSQLInstance.prototype.cancelRefresh.call(instance);
});
t.test('refresh post-forceRefresh', async t => {
const instance = new CloudSQLInstance({
authType: AuthTypes.PASSWORD,
instanceConnectionName: 'my-project:us-east1:my-instance',
ipType: IpAddressTypes.PUBLIC,
limitRateInterval: 0,
sqlAdminFetcher: fetcher,
});
const start = Date.now();
// starts regular refresh cycle
let refreshCount = 1;
await instance.refresh();
await (() =>
new Promise((res): void => {
instance.refresh = () => {
if (refreshCount === 3) {
const end = Date.now();
const duration = end - start;
t.ok(
duration >= 100,
`should respect refresh delay time, ${duration}ms elapsed`
);
instance.cancelRefresh();
return res(null);
}
refreshCount++;
t.ok(refreshCount, `should refresh ${refreshCount} times`);
CloudSQLInstance.prototype.refresh.call(instance);
};
instance.forceRefresh();
}))();
t.strictSame(refreshCount, 3, 'should have refreshed');
});
t.test('refresh rate limit', async t => {
const instance = new CloudSQLInstance({
ipType: IpAddressTypes.PUBLIC,
authType: AuthTypes.PASSWORD,
instanceConnectionName: 'my-project:us-east1:my-instance',
limitRateInterval: 50,
sqlAdminFetcher: fetcher,
});
const start = Date.now();
// starts out refresh logic
let refreshCount = 1;
await instance.refresh();
await (() =>
new Promise((res): void => {
instance.refresh = () => {
if (refreshCount === 3) {
const end = Date.now();
const duration = end - start;
t.ok(
duration >= 150,
`should respect refresh delay time + rate limit, ${duration}ms elapsed`
);
instance.cancelRefresh();
return res(null);
}
refreshCount++;
t.ok(refreshCount, `should refresh ${refreshCount} times`);
CloudSQLInstance.prototype.refresh.call(instance);
};
}))();
t.strictSame(refreshCount, 3, 'should have refreshed');
});
// The cancelRefresh methods should never hang, given the async and timer
// dependent nature of the refresh cycles, it's possible to get into really
// hard to debug race conditions. The set of cancelRefresh tests below just
// ensure that the tests runs and terminates as expected.
t.test('cancelRefresh first cycle', async t => {
const slowFetcher = {
...fetcher,
async getInstanceMetadata() {
await (() => new Promise(res => setTimeout(res, 50)))();
return fetcher.getInstanceMetadata();
},
};
const instance = new CloudSQLInstance({
ipType: IpAddressTypes.PUBLIC,
authType: AuthTypes.PASSWORD,
instanceConnectionName: 'my-project:us-east1:my-instance',
sqlAdminFetcher: slowFetcher,
limitRateInterval: 50,
});
// starts a new refresh cycle but do not await on it
instance.refresh();
// cancel refresh before the ongoing promise fulfills
instance.cancelRefresh();
t.ok('should not leave hanging setTimeout');
});
t.test('cancelRefresh ongoing cycle', async t => {
const slowFetcher = {
...fetcher,
async getInstanceMetadata() {
await (() => new Promise(res => setTimeout(res, 50)))();
return fetcher.getInstanceMetadata();
},
};
const instance = new CloudSQLInstance({
ipType: IpAddressTypes.PUBLIC,
authType: AuthTypes.PASSWORD,
instanceConnectionName: 'my-project:us-east1:my-instance',
sqlAdminFetcher: slowFetcher,
limitRateInterval: 50,
});
// simulates an ongoing instance, already has data
await instance.refresh();
// starts a new refresh cycle but do not await on it
instance.refresh();
instance.cancelRefresh();
t.ok('should not leave hanging setTimeout');
});
t.test(
'cancelRefresh on established connection and ongoing failed cycle',
async t => {
let metadataCount = 0;
const failAndSlowFetcher = {
...fetcher,
async getInstanceMetadata() {
await (() => new Promise(res => setTimeout(res, 50)))();
if (metadataCount === 1) {
throw new Error('ERR');
}
metadataCount++;
return fetcher.getInstanceMetadata();
},
};
const instance = new CloudSQLInstance({
ipType: IpAddressTypes.PUBLIC,
authType: AuthTypes.PASSWORD,
instanceConnectionName: 'my-project:us-east1:my-instance',
sqlAdminFetcher: failAndSlowFetcher,
limitRateInterval: 50,
});
await instance.refresh();
instance.setEstablishedConnection();
// starts a new refresh cycle but do not await on it
instance.refresh();
instance.cancelRefresh();
t.ok('should not leave hanging setTimeout');
}
);
t.test(
'close on established connection and ongoing failed cycle',
async t => {
let metadataCount = 0;
const failAndSlowFetcher = {
...fetcher,
async getInstanceMetadata() {
await (() => new Promise(res => setTimeout(res, 50)))();
metadataCount++;
return fetcher.getInstanceMetadata();
},
};
const instance = new CloudSQLInstance({
ipType: IpAddressTypes.PUBLIC,
authType: AuthTypes.PASSWORD,
instanceConnectionName: 'my-project:us-east1:my-instance',
sqlAdminFetcher: failAndSlowFetcher,
limitRateInterval: 50,
});
await instance.refresh();
instance.setEstablishedConnection();
// starts a new refresh cycle but do not await on it
instance.close();
await instance.forceRefresh();
t.equal(metadataCount, 1, 'No refresh after close');
await t.rejects(
instance.refresh(),
'closed',
'Refresh after close rejected.'
);
}
);
t.test(
'get invalid certificate data while having a current valid',
async t => {
let checkedExpirationTimeCount = 0;
const {CloudSQLInstance} = t.mockRequire('../src/cloud-sql-instance', {
'../src/crypto': {
generateKeys: async () => ({
publicKey: '-----BEGIN PUBLIC KEY-----',
privateKey: CLIENT_KEY,
}),
},
'../src/time': {
getRefreshInterval() {
return 50;
},
// succeds first time and fails for next calls
isExpirationTimeValid() {
checkedExpirationTimeCount++;
return checkedExpirationTimeCount < 2;
},
},
});
// A fetcher mock that will return a new ip on every refresh
let metadataCount = 0;
const updateFetcher = {
...fetcher,
async getInstanceMetadata() {
const instanceMetadata = await fetcher.getInstanceMetadata();
const ips = ['127.0.0.1', '127.0.0.2'];
const ipAddresses = {
public: ips[metadataCount],
};
metadataCount++;
return {
...instanceMetadata,
ipAddresses,
};
},
};
const instance = new CloudSQLInstance({
ipType: IpAddressTypes.PUBLIC,
authType: AuthTypes.PASSWORD,
instanceConnectionName: 'my-project:us-east1:my-instance',
sqlAdminFetcher: updateFetcher,
limitRateInterval: 0,
});
await (() =>
new Promise((res): void => {
let refreshCount = 0;
instance.refresh = function mockRefresh() {
if (refreshCount === 2) {
t.ok('done refreshing 2 times');
// instance.host value will be 127.0.0.2 if
// isExpirationTimeValid does not work as expected
t.strictSame(
instance.host,
'127.0.0.1',
'should not have updated values'
);
instance.cancelRefresh();
return res(null);
}
refreshCount++;
return CloudSQLInstance.prototype.refresh.call(instance);
};
// starts out refresh logic
instance.refresh();
instance.setEstablishedConnection();
}))();
}
);
});