在 Golang 应用程序中,SASL 身份验证在将变量传递给进程时会成功,但在使用导出的变量时会失败。为什么?

发布于 2025-01-15 03:54:09 字数 1101 浏览 1 评论 0原文

我们有一个使用 Gorm 构建的 Golang 应用程序,它通过 verify-full 的 SSL 模式与 PostgreSQL 14(托管在同一台机器上)连接。证书由 ZeroSSL 颁发,并在 Acme.sh 的帮助下生成。在 PostgreSQL 配置中,我们设置了以下与证书相关的变量:

ssl = on
ssl_cert_file = '/etc/ssl/certs/our-certificate.pem'
ssl_key_file = '/etc/ssl/private/our-certificate.key'

Golang 应用程序和 PostgreSQL 服务器托管在 Ubuntu 20.04 计算机中。

我们的 Golang 应用程序依赖于一系列环境变量,其中包括数据库密码和用户名。当我们直接将这些变量传递给我们的应用程序时,即:

DB_HOST=dbhost DB_NAME=dbname DB_USERNAME=username DB_PASSWORD=123456789 [...] ./go-app

一切正常。

另一方面,我们也尝试先导出这些变量。导出变量的方法是首先将变量放入 env 文件中,然后执行以下操作:

set -a
source env-file.env
set +a

此时环境变量已导出,我们可以从终端回显变量。

不幸的是,当我们的 Golang 应用程序尝试连接 PostgreSQL 服务器时,我们会收到以下错误消息:

error="failed to connect to `host=dbhost user=username database=dbname`: failed SASL auth (FATAL: password authentication failed for user \"username\" (SQLSTATE 28P01))"

我已经将导出的数据库相关环境变量的内容记录到控制台,并且它们是与直接传递给进程的变量的值相同。

为什么会出现这种情况?这对我来说是一种奇怪的行为,但我相信我只是缺乏一些必要的信息。

We have a Golang app built with Gorm that connects with PostgreSQL 14 (hosted in the same machine) with an SSL mode of verify-full. The certificates were issued by ZeroSSL, and generated with the help of Acme.sh. In the PostgreSQL configuration, we have set the following certificate-related variables:

ssl = on
ssl_cert_file = '/etc/ssl/certs/our-certificate.pem'
ssl_key_file = '/etc/ssl/private/our-certificate.key'

The Golang app and the PostgreSQL server are hosted in an Ubuntu 20.04 machine.

Our Golang app depends on a bunch of environment variables for, among others, database passwords and usernames. When we pass those variables to our app directly, i.e.:

DB_HOST=dbhost DB_NAME=dbname DB_USERNAME=username DB_PASSWORD=123456789 [...] ./go-app

Everything works well.

On the other hand, we also tried exporting those variables first. Exporting the variables is done by putting the variables inside an env file first, then doing the following:

set -a
source env-file.env
set +a

The environment variables are exported now at this point, and we can echo the variables from the terminal.

Unfortunately, when our Golang app reaches the point where it would attempt to connect with the PostgreSQL server, we would get the following error message:

error="failed to connect to `host=dbhost user=username database=dbname`: failed SASL auth (FATAL: password authentication failed for user \"username\" (SQLSTATE 28P01))"

I have already logged the contents of the exported database-related environment variables to the console, and they were of the same values as the variables directly passed to the process.

Why does this happen? It's a weird behaviour for me, but I believe I am simply lacking some necessary information.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文