如何使用 SSL 连接到 Google Cloud SQL?

Ter*_*ney 1 ssl-certificate google-cloud-sql

我有一个 Google Cloud SQL 实例,我希望后端 API 和数据库之间的连接尽可能安全。我已在实例设置中指定“仅允许 SSL 连接”。我正在使用 Google 生成的 SSL 证书,但是我很难弄清楚如何安全连接。

当我使用以下方式连接时:

return mysql.createPool({
  host: db_host,
  port: 3306,
  user: db_user,
  password: db_password,
  ssl: {
    rejectUnauthorized: false,
    key: clientKey,
    cert: clientCert,
    ca: serverCa,
  },
});
Run Code Online (Sandbox Code Playgroud)

它工作正常,但是使用“rejectUnauthorized: false”显然不安全。

如果我删除“rejectUnauthorized: false”,则会收到错误

'Hostname/IP does not match certificate's altnames: IP: ##.##.##.## is not in the cert's list:'
Run Code Online (Sandbox Code Playgroud)

我似乎需要使用主机名进行连接,但是 Cloud SQL 没有提供使用主机名进行连接的选项。

有谁知道如何解决这个问题?

小智 5

您应该考虑使用 Node.js 连接器,因为它将为您处理证书和 mTLS 连接的管理。

以下是如何启动新的mysql2连接池。

import mysql from 'mysql2/promise';
import {Connector} from '@google-cloud/cloud-sql-connector';

const connector = new Connector();
const clientOpts = await connector.getOptions({
  instanceConnectionName: 'my-project:region:my-instance',
  ipType: 'PUBLIC',
});
const pool = await mysql.createPool({
  ...clientOpts,
  user: 'my-user',
  password: 'my-password',
  database: 'db-name',
});
const conn = await pool.getConnection();
const [result] = await conn.query( `SELECT NOW();`);
console.table(result); // prints returned time value from server

await pool.end();
connector.close();
Run Code Online (Sandbox Code Playgroud)

更多信息请访问https://github.com/GoogleCloudPlatform/cloud-sql-nodejs-connector#using-with-mysql