Skip to main content

Free 30-min security demo Book Now

Academy Hardcoded Secrets
Beginner · 15 min

Hardcoded Secrets

Discover why embedding credentials in code is catastrophic and how to manage secrets properly.

1 The Danger of Hardcoded Credentials

Hardcoded secrets — API keys, database passwords, JWT signing keys — embedded in source code are one of the most common and impactful security mistakes. Once code is committed to a repository, the secret is compromised — even if it is removed in a later commit, git history preserves it forever.

# CRITICAL — never do this
DB_PASSWORD = "SuperSecret!2024"
API_KEY = "sk-live-abc123xyz789"

def connect():
    return psycopg2.connect(password=DB_PASSWORD)

Public GitHub repositories are continuously scraped by automated tools looking for secrets. Private repositories are also at risk from insider threats, stolen tokens, or accidental exposure.

2 Environment Variables & Secret Managers

The correct approach is to load secrets from the environment or a dedicated secret manager:

import os

# Load from environment
DB_PASSWORD = os.environ['DB_PASSWORD']
API_KEY = os.environ.get('STRIPE_API_KEY')

# Fail fast if required secret is missing
if not API_KEY:
    raise RuntimeError("STRIPE_API_KEY environment variable is required")

Secret managers (AWS Secrets Manager, GCP Secret Manager, HashiCorp Vault, Azure Key Vault) provide audit logs, rotation, and fine-grained access control — much better than env vars for production.

3 Preventing Leaks with Pre-commit Hooks

Use secret scanning tools to catch leaks before they reach the repository:

  • git-secrets — pre-commit hook that scans for patterns
  • truffleHog — scans git history for high-entropy strings
  • GitLeaks — configurable secret scanner for CI/CD
  • GitHub secret scanning — automatic on all public repos

Add a .gitignore entry for .env files and never commit them. Use .env.example with placeholder values to document which variables are needed without revealing their values.

If a secret is ever committed — rotate it immediately. Treat the old credential as fully compromised from the moment of the first commit.

Knowledge Check

0/3 correct
Q1

A developer removes a hardcoded API key from source code and commits the removal. Is the key still compromised?

Q2

What is the recommended way to provide a database password to a production application?

Q3

Which file should NEVER be committed to a git repository?

Code Exercise

Move Credentials to Environment Variables

This code hardcodes a database password and API key directly in the source. Rewrite it to load both values from environment variables using os.environ.

python

Put it into practice

Find Hardcoded Secrets in your own code

Offensive360 SAST traces the tainted data flow behind this class of bug across 60+ languages and ships a secure fix with every finding. Public open-source projects scan free; teams can see it on their own repository in a 30-minute demo.