Search code examples
herokuflask-sqlalchemyheroku-postgrespgadmin-4pg-hba.conf

Suddenly, Heroku credentials to a PostgreSQL server gives FATAL password for user error


Without changing anything in my settings, I can't connect to my PostgreSQL database hosted on Heroku. I can't access it in my application, and is given error

OperationalError: (psycopg2.OperationalError) FATAL:  password authentication failed for user "<heroku user>" FATAL:  no pg_hba.conf entry for host "<address>", user "<user>", database "<database>", SSL off

It says SSL off, but this is enabled as I have confirmed in PgAdmin. When attempting to access the database through PgAdmin 4 I get the same problem, saying that there is a fatal password authentication for user '' error.

I have checked the credentials for the database on Heroku, but nothing has changed. Am I doing something wrong? Do I have to change something in pg_hba.conf?

Edit: I can see in the notifications on Heroku that the database was updated right around the time the database stopped working for me. I am not sure if I triggered the update, however.

Here's the notification center:


Solution

  • In general, it isn't a good idea to hard-code credentials when connecting to Heroku Postgres:

    Do not copy and paste database credentials to a separate environment or into your application’s code. The database URL is managed by Heroku and will change under some circumstances such as:

    • User-initiated database credential rotations using heroku pg:credentials:rotate.
    • Catastrophic hardware failures that require Heroku Postgres staff to recover your database on new hardware.
    • Security issues or threats that require Heroku Postgres staff to rotate database credentials.
    • Automated failover events on HA-enabled plans.

    It is best practice to always fetch the database URL config var from the corresponding Heroku app when your application starts. For example, you may follow 12Factor application configuration principles by using the Heroku CLI and invoke your process like so:

    DATABASE_URL=$(heroku config:get DATABASE_URL -a your-app) your_process
    

    This way, you ensure your process or application always has correct database credentials.

    Based on the messages in your screenshot, I suspect you were affected by the second bullet. Whatever the cause, one of those messages explicitly says

    Once it has completed, your database URL will have changed