Skip to main content

Are your Secrets Safe In Python?

Storing your secrets as Python file, here is what you need to be aware of

On scrolling through Hackernews, I stumbled upon this article where Jesse points out how you or your organization can have secrets hidden in the form of pyc files.

While Jesse’s code has scrolled through Github repos and intimated the code owners, there is a good chance that our private repo could have some hanging around.

I modified the code to scroll through Saama’s private repositories. Gladly I didn’t find any pyc files checked in.

You can use the same code to scroll through your private repositories.

Where should secrets live, then?

Before the scanning code, the bigger question: where should a Python app keep its secrets in the first place? There is no single answer. Here are the options, roughly in order of how much machinery they need.

Option 1: A Python (or config) file in the repo

This is what the post started with: a config.py or secrets.py holding API_KEY = "...".

# config.py
DB_PASSWORD = "hunter2"

It is the easiest thing to write, and it has the worst trade-offs:

  • It lives next to your code, so a git add . is all it takes to commit it.
  • Python caches imported modules as .pyc files. Even if you delete the source, a committed __pycache__ can still hold the values, which is exactly what Jesse Li found in public repositories and what the scanner below looks for.
  • Rotating a secret means a code change and a deploy.

If you do use a file, keep it out of version control (.gitignore both the file and __pycache__/) and treat it as a stopgap for local development. The twelve-factor app guide makes the same point: config files kept out of revision control are a big improvement over constants in code, but they can still be committed by mistake and tend to get scattered across places and formats.

Option 2: OS environment variables

Let the environment hand the secret to your process. Nothing secret sits in the repo.

# macOS / Linux (current shell and its child processes)
export DB_PASSWORD="hunter2"
:: Windows: persists for future terminals, NOT the current one
setx DB_PASSWORD "hunter2"

setx writes the variable for future command windows only, so open a new terminal before testing it (Microsoft docs).

import os

db_password = os.environ["DB_PASSWORD"]          # raises KeyError if missing: good, fail loudly
region = os.environ.get("APP_REGION", "us-east-1")  # fine for non-secret defaults

I prefer os.environ[...] over .get() for secrets, because a missing secret should stop the app at startup rather than surface as a None three calls later.

For local development, python-dotenv loads a .env file into os.environ (add .env to .gitignore):

from dotenv import load_dotenv

load_dotenv()  # does not override variables already set in the environment

The twelve-factor guide recommends storing config in environment variables, and it is the lowest-effort step up from a secrets file. The trade-off: the OWASP Secrets Management Cheat Sheet points out that environment variables are generally accessible to all processes and may end up in logs or system dumps, and recommends them only when the other methods are not possible. There is also no audit trail, no per-secret access control, and no rotation: you update every machine yourself.

Option 3: A cloud secret manager

If you already run on a cloud, use its managed store. Secrets are encrypted at rest, access is controlled by IAM, reads can be audited, and rotation does not need a redeploy. Your app authenticates with its cloud identity (an IAM role, service account or managed identity), so there is no long-lived password to hide in the first place.

AWS Secrets Manager with boto3:

import json
import boto3

def get_secret(name: str, region: str = "us-east-1") -> dict:
    client = boto3.session.Session().client("secretsmanager", region_name=region)
    response = client.get_secret_value(SecretId=name)
    return json.loads(response["SecretString"])

creds = get_secret("prod/myapp/db")

AWS has a guide for retrieving secrets in Python that also recommends client-side caching, which cuts both latency and the number of billed API calls.

Google Cloud Secret Manager:

from google.cloud import secretmanager

client = secretmanager.SecretManagerServiceClient()
name = "projects/my-project/secrets/db-password/versions/latest"
response = client.access_secret_version(request={"name": name})
db_password = response.payload.data.decode("UTF-8")

The Google docs show the same call, plus a CRC32C checksum check on the payload.

Azure Key Vault:

from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient

client = SecretClient(
    vault_url="https://my-key-vault.vault.azure.net/",
    credential=DefaultAzureCredential(),
)
db_password = client.get_secret("db-password").value

See the Key Vault secrets client library for details.

Trade-offs: it costs money, adds a network call at startup (cache it), ties you to one provider, and you still need a way to authenticate locally. The usual pattern is to keep the secret manager’s location (a name or URL) in an environment variable and let the cloud identity do the rest.

Option 4: A self-hosted vault, or encrypted files in the repo

If you are multi-cloud, on-prem, or want dynamic, short-lived credentials, a dedicated tool fits better.

HashiCorp Vault with hvac:

import hvac

client = hvac.Client()  # reads VAULT_ADDR and VAULT_TOKEN from the environment
response = client.secrets.kv.v2.read_secret_version(path="myapp/db")
creds = response["data"]["data"]  # {"user": "...", "password": "..."}

Vault checks every request against access policies, logs activity for auditing, and can generate dynamic credentials. The price is operating it: unsealing, high availability, upgrades and policies are now your job (or you pay for the hosted version).

SOPS is the lighter option when you want secrets in the repo, but encrypted. SOPS encrypts the values in YAML, JSON, ENV, INI or binary files and supports AWS KMS, GCP KMS, Azure Key Vault, age and PGP as key backends. With age:

age-keygen -o key.txt                      # prints: Public key: age1...
sops encrypt --age <your-age-public-key> secrets.yaml > secrets.enc.yaml
export SOPS_AGE_KEY_FILE=key.txt           # where SOPS finds the private key
sops decrypt secrets.enc.yaml              # plaintext to stdout
import subprocess
import yaml  # pip install pyyaml

secrets = yaml.safe_load(
    subprocess.run(["sops", "decrypt", "secrets.enc.yaml"],
                   check=True, capture_output=True, text=True).stdout
)

You get versioned, reviewable secrets and a clean git history, but the key is now the thing to protect, and it needs its own safe home (a KMS key is better than a file on a laptop).

Which one should you pick?

OptionSetup effortRotation / auditGood forWatch out for
Python/config fileNoneNoneThrowaway local scriptsCommitted by accident, .pyc leaks
Environment variablesLowManual, no auditLocal dev, small apps, containersVisible to every process, can leak into logs
Cloud secret managerMediumBuilt inApps already on one cloudProvider lock-in, per-call cost
Vault / SOPSMedium to highStrong (Vault) / via git (SOPS)Multi-cloud, on-prem, GitOpsYou operate it; protect the master key

My default: environment variables plus .env locally, and a cloud secret manager in production. Whichever you choose, assume a secret will leak someday. Rotate it, and turn on GitHub secret scanning so you hear about it from a bot first.

Checking your own repos for leaked .pyc files

Back to where this post began. If you (or your team) ever used Option 1, this is how to find out whether it bit you.

Dependencies

pip install PyGithub
pip install uncompyle6

Code

If you want to jump ahead to the whole code checkout the Github repo

  1. Import necessary packages
import base64
import io
import os
import tempfile
import uncompyle6
from github import Github
  1. Authenticate with Github

Create a private access token and use it to authenticate yourself

GITHUB_KEY = <GITHUB_ACCESS_TOKEN>
g = Github(GITHUB_KEY)
  1. Get all repos given an organization
repos  = g.get_organization(<ORGANIZATION>).get_repos(type="private")
  1. Find files with *.pyc extension
for repo in repos:
    print (repo)
    try:
        contents = repo.get_contents("")
    except:
        continue
    for file_ in contents:
        try:
            extension = file_.name.split(".")[1]
        except IndexError:
            extension = None
        if file_.name in secrets or ( extension and extension  == "pyc"):
            items.append(file_)
  1. If there are no pyc files, you are good to go
if not items:
    print ("No files found, you are good!")
  1. If any pyc files might contain secrets decompile and print them out
for item in items:
    print(f"DECOMPILING REPO https://github.com/{item.repository.full_name}")
    print(f"OWNER TYPE: {item.repository.owner.type}")
    try:
        contents = base64.b64decode(item.content)
        with tempfile.NamedTemporaryFile(suffix=".pyc") as f:
            f.write(contents)
            f.seek(0)

            out = io.StringIO()
            uncompyle6.decompile_file(f.name, out)
            out.seek(0)
            print(out.read())
    except Exception as e:
        print(e)
        print(f"COULD NOT DECOMPILE REPO https://github.com/{item.repository.full_name}")
        continue
    print("\n\n\n")