Connection String Security
Protecting database connection strings containing credentials from exposure in code, logs, and configuration files.
Description
A database connection string typically contains the hostname, port, database name, username, and password -- everything an attacker needs to access your data. Hardcoding connection strings in source code is one of the most common and dangerous security mistakes. Connection strings committed to version control can be harvested from git history even after deletion, and they frequently appear in CI/CD logs, error messages, and crash reports.
The gold standard for managing database credentials is a secrets manager (AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager, Azure Key Vault). The application retrieves the connection string at startup from the secrets manager, and credentials can be rotated without redeploying the application. For simpler setups, use environment variables loaded from a .env file that is excluded from version control via .gitignore. Never pass connection strings as command-line arguments (they appear in process listings via ps aux).
Additional hardening measures include: enabling TLS/SSL for all database connections (sslmode=verify-full in PostgreSQL), using short-lived credentials rotated automatically, restricting database user permissions to the minimum required (principle of least privilege), and configuring network-level access controls (VPC security groups, pg_hba.conf rules) so the database is not accessible from the public internet. Log sanitization middleware should redact connection strings and passwords from application logs.
Prompt Snippet
Store database credentials in AWS Secrets Manager or HashiCorp Vault with automatic rotation every 90 days. Retrieve the connection string at application startup and cache it in memory -- never write it to disk or environment variable files in production. Enforce sslmode=verify-full in PostgreSQL connection strings with a pinned CA certificate. Configure pg_hba.conf to allow connections only from application subnet CIDRs using scram-sha-256 authentication. Add a pre-commit hook (git-secrets or trufflehog) to prevent accidental credential commits.
Tags
Related Terms
Database Connection Pooling
Maintaining a reusable pool of database connections to avoid the overhead of establishing new connections for every query.
Database Connection Timeouts
Configuring time limits for establishing database connections and executing queries to prevent resource exhaustion from hanging operations.
Database Backup Strategies
Systematic approaches to creating, storing, and verifying database backups to protect against data loss from hardware failure, human error, or security incidents.