1

So I deploy my python project using docker and docker-compose and I want to connect mongodb(it is not on the same host) using pymongo and I see some example that include their username/password in the connection string like this.

from pymongo import MongoClient

username = 'pattypatty'
password = 'notrealpwd'
host = 'db.pattypatty.com'
port = '27017'
connection_str = f'mongodb://{username}:{password}@{host}:{port}'
client = MongoClient(connection_str)

I want to try it but, is it safe including your username and password in python code? if not how should I secure my username and password.

Patrick
  • 734
  • 11
  • 26
  • It's safe, even when you `load_env` files, otherwise it would be impossible to connect with external piece of software, like a DBMS. What it's not safe is to log these variables anywhere or, even worse, print them to stdout / stderr. – crissal Jun 11 '21 at 08:55
  • 3
    It's never good idea to store (hard-code) credentials and connection details in the code. For a number of reasons. See https://stackoverflow.com/q/34230673/4046632 or number of other similar questions on SO. – buran Jun 11 '21 at 08:56
  • 2
    EDIT I didn't catch that you hardcoded two variables into the code. No, that's a very bad idea. You should always rely to a configuration file (.cfg, .yaml, .json, .env, whatever you want), place it under a safe location, and then load it from your code. – crissal Jun 11 '21 at 08:57

2 Answers2

3

You should never hard-code sensitive information.

The number one reason for this is that if you put the script into source control (like git), even after you remove it, it will be there for all time in the commit history (unless you specifically rewrite your history).

Configuration files are the next step. It is a good idea to keep these in .gitignore to prevent having the same problem if anyone does something like git add .. But your passwords are still in plain text, so accessible to anyone and anything that has access to the configuration file. In your example this would be stored in any docker images you have lying around, will be passed around between docker services, and may be printed out to standard output somewhere.

But really, you should have some mechanism to store your passwords in an encrypted form.

In the context of Docker, there is a mechanism called docker secrets which will encrypt your sensitive information, mount it in a file in your container (under /etc/secrets), and provide your container with the ability to decrypt it. If it is ever printed to logs, it will automatically come up as "****". You can then read from that file in your python script.

mijiturka
  • 434
  • 6
  • 18
0

I don't have much experience in web, but I guess you should store your config variables in a .env file

You can use this github: https://github.com/henriquebastos/python-decouple

Achille G
  • 748
  • 6
  • 19