-
Notifications
You must be signed in to change notification settings - Fork 9
/
connector.ts
343 lines (319 loc) · 10.5 KB
/
connector.ts
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
// 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 {Server, Socket, createServer} from 'node:net';
import tls from 'node:tls';
import {promisify} from 'node:util';
import {AuthClient, GoogleAuth} from 'google-auth-library';
import {CloudSQLInstance} from './cloud-sql-instance';
import {getSocket} from './socket';
import {IpAddressTypes} from './ip-addresses';
import {AuthTypes} from './auth-types';
import {SQLAdminFetcher} from './sqladmin-fetcher';
import {CloudSQLConnectorError} from './errors';
// These Socket types are subsets from nodejs definitely typed repo, ref:
// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/ae0fe42ff0e6e820e8ae324acf4f8e944aa1b2b7/types/node/v18/net.d.ts#L437
export declare interface UnixSocketOptions {
path: string | undefined;
readableAll?: boolean | undefined;
writableAll?: boolean | undefined;
}
// ConnectionOptions are the arguments that the user can provide
// to the Connector.getOptions method when calling it, e.g:
// const connector = new Connector()
// const connectionOptions:ConnectionOptions = {
// ipType: 'PUBLIC',
// instanceConnectionName: 'PROJECT:REGION:INSTANCE',
// };
// await connector.getOptions(connectionOptions);
export declare interface ConnectionOptions {
authType?: AuthTypes;
ipType?: IpAddressTypes;
instanceConnectionName: string;
}
export declare interface SocketConnectionOptions extends ConnectionOptions {
listenOptions: UnixSocketOptions;
}
interface StreamFunction {
(): tls.TLSSocket;
}
interface PromisedStreamFunction {
(): Promise<tls.TLSSocket>;
}
// DriverOptions is the interface describing the object returned by
// the Connector.getOptions method, e.g:
// const connector = new Connector()
// const driverOptions:DriverOptions = await connector.getOptions({
// ipType: 'PUBLIC',
// instanceConnectionName: 'PROJECT:REGION:INSTANCE',
// });
export declare interface DriverOptions {
stream: StreamFunction;
}
export declare interface TediousDriverOptions {
connector: PromisedStreamFunction;
encrypt: boolean;
}
// Internal mapping of the CloudSQLInstances that
// adds extra logic to async initialize items.
class CloudSQLInstanceMap extends Map {
async loadInstance({
ipType,
authType,
instanceConnectionName,
sqlAdminFetcher,
}: {
ipType: IpAddressTypes;
authType: AuthTypes;
instanceConnectionName: string;
sqlAdminFetcher: SQLAdminFetcher;
}): Promise<void> {
// in case an instance to that connection name has already
// been setup there's no need to set it up again
if (this.has(instanceConnectionName)) {
const instance = this.get(instanceConnectionName);
if (instance.authType && instance.authType !== authType) {
throw new CloudSQLConnectorError({
message:
`getOptions called for instance ${instanceConnectionName} with authType ${authType}, ` +
`but was previously called with authType ${instance.authType}. ` +
'If you require both for your use case, please use a new connector object.',
code: 'EMISMATCHAUTHTYPE',
});
}
return;
}
const connectionInstance = await CloudSQLInstance.getCloudSQLInstance({
ipType,
authType,
instanceConnectionName,
sqlAdminFetcher: sqlAdminFetcher,
});
this.set(instanceConnectionName, connectionInstance);
}
getInstance({
instanceConnectionName,
authType,
}: {
instanceConnectionName: string;
authType: AuthTypes;
}): CloudSQLInstance {
const connectionInstance = this.get(instanceConnectionName);
if (!connectionInstance) {
throw new CloudSQLConnectorError({
message: `Cannot find info for instance: ${instanceConnectionName}`,
code: 'ENOINSTANCEINFO',
});
} else if (
connectionInstance.authType &&
connectionInstance.authType !== authType
) {
throw new CloudSQLConnectorError({
message:
`getOptions called for instance ${instanceConnectionName} with authType ${authType}, ` +
`but was previously called with authType ${connectionInstance.authType}. ` +
'If you require both for your use case, please use a new connector object.',
code: 'EMISMATCHAUTHTYPE',
});
}
return connectionInstance;
}
}
interface ConnectorOptions {
auth?: GoogleAuth<AuthClient> | AuthClient;
sqlAdminAPIEndpoint?: string;
/**
* The Trusted Partner Cloud (TPC) Domain DNS of the service used to make requests.
* Defaults to `googleapis.com`.
*/
universeDomain?: string;
}
// The Connector class is the main public API to interact
// with the Cloud SQL Node.js Connector.
export class Connector {
private readonly instances: CloudSQLInstanceMap;
private readonly sqlAdminFetcher: SQLAdminFetcher;
private readonly localProxies: Set<Server>;
private readonly sockets: Set<Socket>;
constructor(opts: ConnectorOptions = {}) {
this.instances = new CloudSQLInstanceMap();
this.sqlAdminFetcher = new SQLAdminFetcher({
loginAuth: opts.auth,
sqlAdminAPIEndpoint: opts.sqlAdminAPIEndpoint,
universeDomain: opts.universeDomain,
});
this.localProxies = new Set();
this.sockets = new Set();
}
// Connector.getOptions is a method that accepts a Cloud SQL instance
// connection name along with the connection type and returns an object
// that can be used to configure a driver to be used with Cloud SQL. e.g:
//
// const connector = new Connector()
// const opts = await connector.getOptions({
// ipType: 'PUBLIC',
// instanceConnectionName: 'PROJECT:REGION:INSTANCE',
// });
// const pool = new Pool(opts)
// const res = await pool.query('SELECT * FROM pg_catalog.pg_tables;')
async getOptions({
authType = AuthTypes.PASSWORD,
ipType = IpAddressTypes.PUBLIC,
instanceConnectionName,
}: ConnectionOptions): Promise<DriverOptions> {
const {instances} = this;
await instances.loadInstance({
ipType,
authType,
instanceConnectionName,
sqlAdminFetcher: this.sqlAdminFetcher,
});
return {
stream() {
const cloudSqlInstance = instances.getInstance({
instanceConnectionName,
authType,
});
const {
instanceInfo,
ephemeralCert,
host,
port,
privateKey,
serverCaCert,
serverCaMode,
dnsName,
} = cloudSqlInstance;
if (
instanceInfo &&
ephemeralCert &&
host &&
port &&
privateKey &&
serverCaCert
) {
const tlsSocket = getSocket({
instanceInfo,
ephemeralCert,
host,
port,
privateKey,
serverCaCert,
serverCaMode,
dnsName,
});
tlsSocket.once('error', async () => {
await cloudSqlInstance.forceRefresh();
});
tlsSocket.once('secureConnect', async () => {
cloudSqlInstance.setEstablishedConnection();
});
return tlsSocket;
}
throw new CloudSQLConnectorError({
message: 'Invalid Cloud SQL Instance info',
code: 'EBADINSTANCEINFO',
});
},
};
}
async getTediousOptions({
authType,
ipType,
instanceConnectionName,
}: ConnectionOptions): Promise<TediousDriverOptions> {
if (authType === AuthTypes.IAM) {
throw new CloudSQLConnectorError({
message: 'Tedious does not support Auto IAM DB Authentication',
code: 'ENOIAM',
});
}
const driverOptions = await this.getOptions({
authType,
ipType,
instanceConnectionName,
});
return {
async connector() {
return driverOptions.stream();
},
// note: the connector handles a secured encrypted connection
// with that in mind, the driver encryption is disabled here
encrypt: false,
};
}
// Connector.startLocalProxy is an alternative to Connector.getOptions that
// creates a local Unix domain socket to listen and proxy data to and from a
// Cloud SQL instance. Can be used alongside a database driver or ORM e.g:
//
// const path = resolve('.s.PGSQL.5432'); // postgres-required socket filename
// const connector = new Connector();
// await connector.startLocalProxy({
// instanceConnectionName,
// ipType: 'PUBLIC',
// listenOptions: {path},
// });
// const datasourceUrl =
// `postgresql://${user}@localhost/${database}?host=${process.cwd()}`;
// const prisma = new PrismaClient({ datasourceUrl });
async startLocalProxy({
authType,
ipType,
instanceConnectionName,
listenOptions,
}: SocketConnectionOptions): Promise<void> {
const {stream} = await this.getOptions({
authType,
ipType,
instanceConnectionName,
});
// Opens a local server that listens
// to the location defined by `listenOptions`
const server = createServer();
this.localProxies.add(server);
/* c8 ignore next 3 */
server.once('error', err => {
console.error(err);
});
// When a connection is established, pipe data from the
// local proxy server to the secure TCP Socket and vice-versa.
server.on('connection', c => {
const s = stream();
this.sockets.add(s);
this.sockets.add(c);
c.pipe(s);
s.pipe(c);
});
const listen = promisify(server.listen) as Function;
await listen.call(server, {
path: listenOptions.path,
readableAll: listenOptions.readableAll,
writableAll: listenOptions.writableAll,
});
}
// Clear up the event loop from the internal cloud sql
// instances timeout callbacks that refreshs instance info.
//
// Also clear up any local proxy servers and socket connections.
close(): void {
for (const instance of this.instances.values()) {
instance.cancelRefresh();
}
for (const server of this.localProxies) {
server.close();
}
for (const socket of this.sockets) {
socket.destroy();
}
}
}