Skip to content

Commit edbc025

Browse files
committed
Fixed connection with ssl modes allow, prefer, require
1 parent 2c74008 commit edbc025

File tree

1 file changed

+36
-5
lines changed

1 file changed

+36
-5
lines changed

reverse_engineering/helpers/connectionHelper.js

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@ const fs = require('fs');
22
const ssh = require('tunnel-ssh');
33
const pg = require('pg');
44

5+
const SSL_NOT_SUPPORTED_MESSAGE = 'The server does not support SSL connections';
6+
const POSTGRES_SSL_REQUIRED_ERROR_CODE = '28000';
7+
58
const getSshConfig = info => {
69
const config = {
710
username: info.ssh_user,
@@ -43,14 +46,16 @@ const connectViaSsh = info =>
4346
});
4447

4548
const getSslOptions = (connectionInfo, logger) => {
46-
const sslType = mapSslType(connectionInfo.sslType);
49+
const sslType = connectionInfo.sslType;
4750

48-
if (!sslType || sslType === 'disable') {
51+
if (!sslType || sslType === 'disable' || sslType === 'allow') {
4952
return false;
5053
}
5154

52-
if (sslType === 'allow') {
53-
return true;
55+
if (['require', 'prefer'].includes(sslType) && !connectionInfo.certAuthority) {
56+
return {
57+
rejectUnauthorized: false,
58+
};
5459
}
5560

5661
let sslOptions = {
@@ -102,6 +107,8 @@ const createClient = async (connectionInfo, logger) => {
102107
connectionInfo = info;
103108
}
104109

110+
connectionInfo = Object.assign({}, connectionInfo, { sslType: mapSslType(connectionInfo.sslType) });
111+
105112
const config = {
106113
host: connectionInfo.host,
107114
user: connectionInfo.userName,
@@ -116,10 +123,34 @@ const createClient = async (connectionInfo, logger) => {
116123
application_name: 'Hackolade',
117124
};
118125

126+
const client = await connectClient(config).catch(retryOnSslError(connectionInfo, config));
127+
128+
return { client, sshTunnel };
129+
};
130+
131+
const retryOnSslError = (connectionInfo, config) => async error => {
132+
if (error.message === SSL_NOT_SUPPORTED_MESSAGE && connectionInfo.sslType === 'prefer') {
133+
return await connectClient({
134+
...config,
135+
ssl: false,
136+
});
137+
}
138+
139+
if (error.code === POSTGRES_SSL_REQUIRED_ERROR_CODE && connectionInfo.sslType === 'allow') {
140+
return await connectClient({
141+
...config,
142+
ssl: { rejectUnauthorized: false },
143+
});
144+
}
145+
146+
throw error;
147+
};
148+
149+
const connectClient = async config => {
119150
const client = new pg.Client(config);
120151
await client.connect();
121152

122-
return { client, sshTunnel };
153+
return client;
123154
};
124155

125156
module.exports = {

0 commit comments

Comments
 (0)