Stop exposing sensitive data in your Python code. Keep all settings and credentials private.
Hardcoded variables and global settings in the source files? You can see it quite often. It’s common in the simple small scripts, but you definitely need a more sophisticated and secure way for your applications.
I’m sure that all of you have heard about the secure password managers that keeps your credentials safe. However, it’s not enough to securely store just the passwords. You should not expose any sensitive data like personal info, email addresses, tokens, hosts, API keys or any other credentials in your code. All those information needs to be stored securely. Any malicious user can easily steal it from you if you leave those information in source file. Try to google the following and see what happens:
There are lots of possibilities to search for exposed credentials over the internet. Read this article to find more information if it’s interesting for you.
You already know that it’s not a good idea to publicly expose any sensitive data in your project files. A more secure approach is to store all your sensitive info in environment variables. An easy way of defining environment variables is through a .env file. This type of file uses a bash-like syntax and since it depends on the deployment environment, this file should not be stored in public or private repository. Thus it’s handy to add it to your project’s .gitignore file. Here’s an example of how could .env file looks like:
Okay, now we know how to store our configuration in the .env file. But how to load stored configuration into my application files? Well, there is a python-dotenv module for this purpose.
Python-dotenv reads key and value pairs from a .env file and can set them as environment variables. It helps in the development of applications following the 12-factor principles. You can find a more information here.
Thanks for reading!
Article by Štefan Mastiľák, Anton Hajdu & Dominik Mesaroš