Hardcoded secrets

Secrets embedded in application code

Description

Passwords, API keys, and authentication tokens embedded in application code may be exposed with the source.

Potential impact

  • Secret exposure: An attacker may obtain secrets from the source code.
  • Account takeover: Exposed secrets may allow access to accounts.
  • API abuse: An attacker may misuse services with leaked API keys.

Remediation

  • Manage secrets in a tool such as HashiCorp Vault or AWS Secrets Manager and supply them through the environment at deployment. Restrict access to environment variables and keep their values out of logs.
  • Review code regularly for embedded secrets. Revoke and replace any secret that was exposed.

Examples

Django

Before

python
# Hardcoded Django secrets
SECRET_KEY = 'your-hardcoded-secret-key'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

After

python
# Django secrets supplied through the environment
import os

SECRET_KEY = os.getenv('DJANGO_SECRET_KEY')
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.getenv('DB_NAME'),
        'USER': os.getenv('DB_USER'),
        'PASSWORD': os.getenv('DB_PASSWORD'),
        'HOST': os.getenv('DB_HOST'),
        'PORT': os.getenv('DB_PORT'),
    }
}

Django sets SECRET_KEY from DJANGO_SECRET_KEY and reads the database password from DB_PASSWORD.

Flask

Before

python
# Hardcoded Flask secrets
class Config:
    SECRET_KEY = 'your-hardcoded-secret-key'
    SQLALCHEMY_DATABASE_URI = 'postgresql://myuser:mypassword@localhost/mydatabase'

After

python
# Flask secrets supplied through the environment
import os

class Config:
    SECRET_KEY = os.getenv('FLASK_SECRET_KEY')
    SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')

Flask reads the application’s SECRET_KEY from FLASK_SECRET_KEY and the database URI containing credentials from DATABASE_URL.

FastAPI

Before

python
# Hardcoded FastAPI session secret
from fastapi import FastAPI
from starlette.middleware.sessions import SessionMiddleware

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key='your-hardcoded-secret-key', https_only=True)

After

python
# FastAPI session secret supplied through the environment
from fastapi import FastAPI
from starlette.middleware.sessions import SessionMiddleware
import os

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key=os.environ['FASTAPI_SECRET_KEY'], https_only=True)

FastAPI passes FASTAPI_SECRET_KEY to Starlette’s session middleware as secret_key.

References