Adam Jacobs
Adam Jacobs

Reputation: 423

"Correct" way to store postgres password in python website

I'm writing a web application in Python (on Apache server on a Linux system) that needs to connect to a Postgres database. It therefore needs a valid password for the database server. It seems rather unsatisfactory to hard code the password in my Python files.

I did wonder about using a .pgpass file, but it would need to belong to the www-data user, right? By default, there is no /home/www-data directory, which is where I would have expected to store the .pgpass file. Can I just create such a directory and store the .pgpass file there? And if not, then what is the "correct" way to enable my Python scripts to connect to the database?

Upvotes: 4

Views: 1482

Answers (2)

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125404

Install the application and its config files in its own directory different from the static files directory and only readable by the application user.

Set another user to run the application and use the WSGIDaemonProcess directive.

All of that and much more is clearly described in the mod_wsgi site, in the Quick Configuration Guide, Configuration Guidelines and Configuration Directives

Upvotes: 1

Craig Ringer
Craig Ringer

Reputation: 324691

No matter what approach you use, other apps running as www-data will be able to read your password and log in as you to the database. Using peer auth won't help you out, it'll still trust all apps running under www-data.

If you want your application to be able to isolate its data from other databases you'll need to run it as a separate user ID. The main approaches with this are:

  • Use the apache suexec module to run scripts as a separate user;
  • Use fast-cgi (fcgi) or scgi to run the cgi as a different user; or
  • Have the app run its own minimal HTTP server and have Apache reverse proxy for it

Of these, by far the best option is usually to use scgi/fcgi. It lets you easily run your app as a different unix user but avoids the complexity and overhead of reverse proxying.

Upvotes: 1

Related Questions