Description
Credentials such as usernames, passwords, and API keys can be exposed with the source code if they are embedded in it.
Potential impact
- Credential exposure: An attacker may use leaked credentials for unauthorized access.
- Privilege abuse: Credentials with administrator privileges can allow an attacker to modify the system.
- Data disclosure: Sensitive information may be exposed.
Remediation
- Manage credentials in an access-controlled store and supply them through the environment at deployment.
- Rotate credentials regularly and retire unused ones. If a credential was exposed, revoke it and issue a replacement.
Examples
For the Flask and FastAPI examples, supply the complete database connection string through DATABASE_URL in the deployment environment.
Django
Before
python
# Hardcoded Django credentials
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydatabase',
'USER': 'myuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '5432',
}
}
After
python
# Django credentials from the environment
import os
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 reads connection settings such as DB_USER and DB_PASSWORD from individual environment variables.
Flask
Before
python
# Hardcoded Flask credentials
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://myuser:mypassword@localhost/mydatabase'
After
python
# Flask credentials from the environment
import os
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
Flask assigns DATABASE_URL to SQLALCHEMY_DATABASE_URI.
FastAPI
Before
python
# Hardcoded FastAPI credentials
DATABASE_URL = "postgresql://myuser:mypassword@localhost/mydatabase"
@app.on_event("startup")
async def startup():
app.state.pool = await asyncpg.create_pool(DATABASE_URL)
After
python
# FastAPI credentials from the environment
import os
DATABASE_URL = os.environ['DATABASE_URL']
@app.on_event("startup")
async def startup():
app.state.pool = await asyncpg.create_pool(DATABASE_URL)
FastAPI uses DATABASE_URL to create the asyncpg connection pool at startup.