Skip to main content
Secrets Hygiene, Env Vars & Safe Dependencies
Lesson 10 of 10

Secrets Hygiene, Env Vars & Safe Dependencies

Learn how to keep API keys and passwords out of Git history using environment variables and git-secrets, and how to pin and audit third-party Python dependencies with pip-audit.

Intermediate 20 min Programming

Learning objectives

  • Explain why deleting a committed secret in a later commit does not remove exposure from Git history
  • Configure Python applications to load credentials from environment variables and ignored local files
  • Prevent and detect hardcoded secrets in repositories using git-secrets
  • Pin Python dependencies and scan for known vulnerabilities using pip-audit

Recommended first: Git & GitHub Essentials for Security EngineersInput Validation, Command Safety & Error Handling

#Why this matters

Even input-validated code breaks down if a developer commits an API token to Git or ships an outdated library with a remote code execution flaw. Automated bots watch public repositories and container registries continuously, harvesting exposed credentials within seconds of a push. At the same time, modern Python projects rely on dozens of third-party packages, meaning a vulnerability in one indirect dependency becomes a weakness in your application.

Good secrets hygiene and dependency management keep credentials separate from code and keep external libraries visible and patchable.

#Why hardcoded secrets persist in Git

Writing API_TOKEN = "example-lab-token-1234" directly inside config.py creates secret sprawl. Even if you spot the mistake five minutes later and delete the line in a second commit, Git preserves every previous snapshot. Anyone who clones the repository or runs git log -p can still read the secret from the earlier commit.

Why deleting a secret in a follow-up commit is not enoughWhy deleting a secret in a follow-up commit is not enoughDeveloperGitAttackerCommit 1 adds API_TOKEN in config.py and pushesClones repo or fetches commit 1 objectCommit 2 removes API_TOKEN from config.pyCommit 1 still contains the secret; rotation is mandatory

Tools like git-secrets block accidental commits locally and scan existing history before a push:

Setting up git-secrets and scanning repository history
$ git secrets --install
$ git secrets --register-aws
$ git secrets --add 'LAB_TOKEN_[A-Z0-9]{12}'
$ git secrets --scan-history
src/client.py:4:LAB_TOKEN_9F8E7D6C5B4A
[ERROR] Matched one or more prohibited patterns

Installing the hook into .git/hooks/ checks staged changes at commit time, while --scan-history inspects older commits that a normal file search misses.

#Managing configuration with environment variables

Code belongs in Git; configuration and secrets belong in the runtime environment. In Python, read required secrets from os.environ so the program fails closed at startup if a variable is missing, rather than falling back to an insecure default.

python
import os

API_TOKEN = os.environ["LAB_API_TOKEN"]
API_BASE_URL = os.environ.get("LAB_API_URL", "https://api.example.test")

For local lab work, store values in an untracked .env file and commit only a .env.example template with empty placeholders. Always add .env to .gitignore before your first commit.

Storage method Suitable for Key risk if misused
Hardcoded string in .py Never Exposed to anyone with repo or image access
Local .env listed in .gitignore Local development only Accidentally committed if .gitignore is missing
OS / container env vars or secret manager Staging and production Leaked if /proc or debug endpoints dump os.environ

Never print os.environ in error handlers, startup banners, or diagnostic endpoints, because all injected tokens live in that dictionary.

#Auditing and pinning third-party dependencies

When you install one package such as requests, pip also installs transitive dependencies (urllib3, certifi, charset-normalizer, idna). Unpinned lines in requirements.txt (such as requests or requests>=2.28) pull newer releases unpredictably across builds, making security testing unreliable.

Pin exact versions in requirements.txt (for example requests==2.32.3), generate lockfiles from a clean virtual environment, and audit them regularly with pip-audit. pip-audit checks installed packages or requirements files against the Python Packaging Advisory Database (PyPI / OSV):

Auditing a requirements file with pip-audit
$ pip-audit -r requirements.txt
Found 2 known vulnerabilities in 1 package
Name     Version ID                  Fix Versions
-------- ------- ------------------- ------------
examplepkg 1.2.0 PYSEC-2024-0000     1.2.4

Review the Fix Versions column, update the pinned version in requirements.txt, run your test suite, and re-run pip-audit until it reports No known vulnerabilities found. Also verify package names carefully before installing to avoid typosquatting (malicious packages named similarly to popular libraries, such as reqeusts).

#Common mistakes

  • Committing .env first and adding .gitignore later: Git continues tracking already-committed files even after they appear in .gitignore; you must run git rm --cached .env, commit, and rotate the exposed values.
  • Providing hardcoded fallback secrets: Writing os.getenv("SECRET_KEY", "dev-only-key") means a missing environment variable silently runs production with a guessable key.
  • Assuming git commit --amend or a new commit fixes a pushed leak: Once pushed, others may have fetched the old commit object, so secret rotation is always required.
  • Auditing only direct imports: Skipping pip-audit on transitive dependencies leaves hidden vulnerabilities in libraries pulled underneath your main packages.

#Summary

  • Never store passwords or API tokens in source files; keep them in runtime environment variables or a secret manager, and fail closed when required variables are missing.
  • Deleting a secret in a newer commit leaves it readable in Git history; use git-secrets to prevent commits and rotate any exposed credential immediately.
  • Pin exact package versions in requirements.txt, watch for typosquatted package names, and run pip-audit regularly to catch vulnerable direct and transitive dependencies.

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge