Skip to content

Latest commit

 

History

History
105 lines (78 loc) · 3.19 KB

File metadata and controls

105 lines (78 loc) · 3.19 KB

SSL

As part of the connection options, you can specify the ssl object to configure the TLS sockets, or set the property to false to not use TLS for the connection.

ssl?:
  | false
  | string
  | SslOptions
  | ((config: ConnectionConfig) => SslOptions | Promise<SslOptions>);

See full list of SslOptions, which are in the same format as tls.createSecureContext.

SSL Options

To enable SSL without manually providing certificates and assuming they are already trusted by the host machine, you can specify an empty object, for example:

const connection = await mysql.createConnection({
  host: 'localhost',
  ssl: {},
});

You can also specify custom certificate(s) as an individual string or array of strings. Please note the arguments expect a string of the certificate, not a file name to the certificate:

import fs from 'node:fs';

const connection = await mysql.createConnection({
  host: 'localhost',
  ssl: {
    ca: fs.readFileSync(__dirname + '/mysql-ca.crt'),
  },
});

When a certificate is read from an environment variable, it's recommended to replace escaped \n characters with proper new line characters, for example:

const connection = await mysql.createConnection({
  host: 'localhost',
  ssl: {
    ca: process.env.DB_SSL_CA?.replace(/\\n/gm, '\n'),
  },
});

SSL Certificate Bundle

Alternatively, you can use a bundle with CA certificates. For example for Amazon RDS you could use:

import awsCaBundle from 'aws-ssl-profiles';

const connection = await mysql.createConnection({
  host: 'db.id.ap-southeast-2.rds.amazonaws.com',
  ssl: awsCaBundle,
});

For detailed instructions, please follow aws-ssl-profiles documentation.

SSL Profile (deprecated)

There is also a deprecated option allowing to specify a string containing name of SSL profile:

const connection = await mysql.createConnection({
  host: 'localhost',
  ssl: 'Amazon RDS',
});

Following profiles are included in the package:

Ignoring Unauthorized SSL Errors

You can also connect to a MySQL server without providing an appropriate CA to trust. This is highly discouraged as being insecure.

const connection = await mysql.createConnection({
  host: 'localhost',
  ssl: {
    // Beware, set `rejectUnauthorized` as `false` is strongly discouraged for security reasons:
    rejectUnauthorized: false,
  },
});

Dynamic SSL Configuration

mysql2 supports providing the SSL configuration dynamically instead of only as a static object. This is particularly useful for environments that use short-lived client certificates, such as systems using SPIFFE, where certificates may need to be fetched or rotated dynamically. If a Promise is returned, the connection waits for it to resolve before upgrading to TLS.

const connection = await mysql.createConnection({
  host: 'localhost',
  ssl: async () => ({
    ca: await fetchCa(),
  }),
});