Secure Coding & Secrets
Most vulnerabilities are ordinary bugs in ordinary code. Secure coding is less about exotic tricks and more about habits that make whole classes of bugs impossible or harmless. This lesson collects the most important ones, then focuses on a problem every developer faces: secrets.
Principles that prevent bugs
| Principle | In practice |
|---|---|
| Secure defaults | New accounts have no privileges; new buckets are private; debug is off |
| Fail closed | If the permission service is down, deny access rather than allow it |
| Least privilege | Services run as non-root with only the permissions they need |
| Keep it simple | Less code and fewer features means less attack surface |
| Don't roll your own crypto | Use vetted libraries and high-level APIs |
| Validate input, encode output | At every trust boundary, for the specific context |
| Handle errors safely | Log details internally, show users a generic message |
| Dependencies are your code | Pin, scan and update them |
Fail closed
A surprisingly common bug: an exception in a security check accidentally grants access.
def get_permissions(user):
if user == "carol":
raise TimeoutError("permission service unavailable")
return {"alice": ["admin"], "bob": ["read"]}.get(user, [])
def is_admin_fail_open(user):
try:
return "admin" in get_permissions(user)
except Exception:
return True # "don't block people if something breaks" -- WRONG
def is_admin_fail_closed(user):
try:
return "admin" in get_permissions(user)
except Exception:
return False # on any error, deny
for user in ["alice", "bob", "carol"]:
print(f"{user:<6} fail-open={is_admin_fail_open(user)!s:<6} fail-closed={is_admin_fail_closed(user)}")alice fail-open=True fail-closed=True
bob fail-open=False fail-closed=False
carol fail-open=True fail-closed=False
When the permission service times out, the fail-open version makes carol an administrator. The fail-closed version denies her and lets the error be noticed and fixed.
Errors without leaks
Detailed error messages help attackers: stack traces reveal file paths, library versions, SQL queries and sometimes credentials. Show a generic message with a correlation ID, and put the details in the server log:
import hashlib
def handle_request(request_id, action):
try:
action()
return "200 OK"
except Exception as err:
ref = hashlib.sha256(request_id.encode()).hexdigest()[:8]
# internal log: full detail for engineers
print(f"[log] ref={ref} {type(err).__name__}: {err}")
# response to the user: no internals
return f"500 Something went wrong. Reference: {ref}"
def broken_query():
raise RuntimeError("syntax error near 'WHERE' in SELECT * FROM users WHERE pw='...'")
print(handle_request("req-20260101-0042", broken_query))[log] ref=f25b487e RuntimeError: syntax error near 'WHERE' in SELECT * FROM users WHERE pw='...'
500 Something went wrong. Reference: f25b487e
Secrets management
A secret is anything that grants access: passwords, API keys, database URLs with credentials, private keys, signing keys, OAuth client secrets. The rules:
- Never hard-code secrets in source code, and never commit them to version control. Git history is forever, and public repositories are scanned by bots within minutes.
- Inject them at runtime: environment variables, a mounted file, or better, a secrets manager (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, GCP Secret Manager).
- Scope and rotate: one secret per service and environment, with the least privilege; rotate regularly and immediately after a leak.
- Keep them out of logs, URLs and error messages.
- If a secret leaks, revoke it. Deleting the commit is not enough.
# Bad: the key ships with the code and lives in git history forever
API_KEY = "sk_live_51Hx…"
# Better: read it from the environment (set by the deployment platform or a secrets manager)
import os
API_KEY = os.environ["PAYMENT_API_KEY"]Reading configuration safely also means failing loudly when a required secret is missing, instead of silently falling back to an insecure default:
def load_config(env):
required = ["DATABASE_URL", "SESSION_SECRET"]
missing = [name for name in required if not env.get(name)]
if missing:
raise SystemExit(f"refusing to start: missing {', '.join(missing)}")
if len(env["SESSION_SECRET"]) < 32:
raise SystemExit("refusing to start: SESSION_SECRET too short")
return {"db": env["DATABASE_URL"], "debug": env.get("DEBUG") == "1"}
for env in [{"DATABASE_URL": "postgres://app@db/shop", "SESSION_SECRET": "x" * 40},
{"DATABASE_URL": "postgres://app@db/shop"},
{"DATABASE_URL": "postgres://app@db/shop", "SESSION_SECRET": "changeme"}]:
try:
print("started:", load_config(env))
except SystemExit as err:
print(err)started: {'db': 'postgres://app@db/shop', 'debug': False}
refusing to start: missing SESSION_SECRET
refusing to start: SESSION_SECRET too short
Scanning for leaked secrets
Tools such as gitleaks, trufflehog and GitHub secret scanning search code and history for patterns that look like credentials. Many providers use recognisable prefixes precisely so scanners can find leaked keys. Here is a small scanner with a few such patterns; it masks what it finds so the report doesn't leak the secret again. (All keys below are fake.)
import re
PATTERNS = {
"AWS access key id": re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
"GitHub token": re.compile(r"\bghp_[A-Za-z0-9]{36}\b"),
"private key block": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
"password assignment": re.compile(r"(?i)\b(password|passwd|pwd)\s*[=:]\s*['\"]([^'\"\s]{4,})['\"]"),
}
source = '''\
db_host = "db.internal"
aws_key = "AKIAEXAMPLEFAKEKEY12"
password = "Winter2026!"
token = "ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij"
# password = os.environ["DB_PASSWORD"]
-----BEGIN RSA PRIVATE KEY-----
'''
def mask(value):
return value[:4] + "*" * max(0, len(value) - 4)
for lineno, line in enumerate(source.splitlines(), start=1):
for name, pattern in PATTERNS.items():
m = pattern.search(line)
if m:
found = m.group(m.lastindex or 0)
print(f"line {lineno}: {name:<20} {mask(found)}")line 2: AWS access key id AKIA****************
line 3: password assignment Wint*******
line 4: GitHub token ghp_************************************
line 6: private key block ----***************************
Notice that line 5 (reading the password from the environment) is not flagged, because the pattern requires a quoted literal value after password =. Run such scanners in a pre-commit hook and in CI, so secrets are caught before they are pushed.
Go further: Cloud Secret Management and Where Secrets Hide builds a configuration-secret finder, and Leaked Access Keys walks through the response to a leaked key.
Test yourself
The authorization service times out. What should a 'fail closed' system do?
- Allow the request
- Deny the request
- Retry forever
- Grant read-only admin
You notice an API key was committed and pushed an hour ago. What is the essential step?
- Delete the file in a new commit
- Rewrite git history only
- Revoke/rotate the key at the provider
- Make the repository private
What should a production error page show the user?
- The full stack trace
- The failing SQL query
- A generic message and a reference ID
- The server's environment variables