Security vulnerabilities in application code are rarely exotic. They come from a small set of decisions made early: accepting data because it looks harmless, concatenating strings into queries, rendering text into a browser without deciding its context, and committing a credential because the environment variable was not wired up yet. Each of those choices is individually reasonable at 6 p.m. on a deadline, which is exactly why secure coding is less about clever techniques and more about making the safe path the path of least resistance â through framework defaults, review checklists, and tests that fail loudly when a guardrail is missing.
The principle: treat every input as hostile, every output as untrusted context
Every request boundary is a place where data changes trust level. Anything arriving from a client, a queue, a third-party webhook, or even a file your own system wrote last week should be re-validated before it drives logic. The mirror image holds on the way out: data that was safe in a database becomes dangerous the moment it lands in an HTML page, a shell command, a SQL statement, or a log viewer. The techniques that follow are all specific instances of those two sentences.
Validate input with an allowlist, not a blocklist
Blocklists fail because attackers use encodings, case variations, and characters you did not think of. Allowlists describe exactly what the field is supposed to contain, so anything unexpected fails closed. Validation also belongs next to the point of use: a validator that runs in one controller but not in the batch job that calls the same function protects only half the surface.
import re
from datetime import datetime
USERNAME = re.compile(r"^[a-z0-9_]{3,32}$")
SLUG = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
ALLOWED_MIME = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}
def validate_username(raw: str) -> str:
if not isinstance(raw, str) or not USERNAME.fullmatch(raw):
raise ValueError("username must be 3-32 chars: a-z, 0-9, underscore")
return raw.lower()
def validate_age(raw) -> int:
if isinstance(raw, bool) or not isinstance(raw, int):
raise ValueError("age must be an integer")
if not 0 <= raw <= 130:
raise ValueError("age out of range")
return raw
def validate_upload(filename: str, mime: str, header: bytes) -> str:
if mime not in ALLOWED_MIME:
raise ValueError("unsupported content type")
# Magic-number check: the declared MIME type is a client-side claim
signatures = {".png": b"\x89PNG", ".jpg": b"\xff\xd8\xff", ".webp": b"RIFF"}
ext = ALLOWED_MIME[mime]
if not header.startswith(signatures[ext]):
raise ValueError("file content does not match declared type")
if len(filename) > 128 or "/" in filename or "\\" in filename:
raise ValueError("unsafe filename")
return ext
def parse_date(raw: str) -> datetime:
try:
return datetime.strptime(raw, "%Y-%m-%d")
except (TypeError, ValueError) as exc:
raise ValueError("date must be ISO 8601: YYYY-MM-DD") from exc
Note the two details that blocklist approaches would miss: rejecting booleans when an integer is expected (in Python, True is an instance of int), and checking the file's magic bytes rather than trusting the client-declared content type. Return errors that describe the rule without echoing the rejected input back into a response or log entry.
Encode output for the context it will be rendered in
Output encoding is not one operation. HTML-escaping text that will be placed inside a script block, or HTML-escaping a value destined for a URL parameter, protects the wrong boundary. Match the encoder to the destination, and prefer framework mechanisms that do it automatically over hand-rolled replacements.
import html
import json
import urllib.parse
def encode_for_html(text: str) -> str:
"""Text nodes and attribute values in an HTML document."""
return html.escape(text, quote=True)
def encode_for_url_param(value: str) -> str:
"""A single query-string component."""
return urllib.parse.quote(value, safe="")
def encode_for_json_script_tag(payload: dict) -> str:
"""Data serialized into a script block; escapes the closing tag too."""
blob = json.dumps(payload, ensure_ascii=False)
return blob.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
def build_safe_link(base: str, params: dict) -> str:
query = urllib.parse.urlencode(params, doseq=True)
return f"{base}?{query}"
# Rendered through an auto-escaping template engine, this is safe by default:
# template: <p>{{ user.display_name }}</p>
# Set | safe only for content you sanitized yourself, never merely trusted.
Pair encoding with a Content Security Policy so that a missed encoding still cannot execute inline script. A policy of default-src 'self' with no unsafe-inline turns a surviving markup injection into a harmless broken page rather than a session theft, which is why defense in depth is not optional here.
Parameterized queries: the fix that removes the whole class
SQL injection survives because query structure and data are combined into one string. Prepared statements separate them permanently: the query plan is fixed first, and the data is bound afterwards in a way that can never alter structure. The same applies to any interpreter you face â shells, LDAP filters, template engines, NoSQL query builders.
import sqlite3
def get_orders_vulnerable(db, customer_id): # never write it this way
cur = db.execute(f"SELECT id, total FROM orders WHERE customer_id = {customer_id}")
return cur.fetchall()
def get_orders_safe(db, customer_id, status="paid"):
# Structure is fixed; values are bound
cur = db.execute(
"SELECT id, total, created_at FROM orders "
"WHERE customer_id = ? AND status = ? ORDER BY created_at DESC",
(customer_id, status),
)
return cur.fetchall()
def search_users_safe(db, term: str, limit: int = 50):
# LIKE wildcard injection is a separate issue: escape the pattern
escaped = term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
cur = db.execute(
"SELECT id, email FROM users WHERE email LIKE ? ESCAPE '\\' "
"ORDER BY id LIMIT ?",
(f"%{escaped}%", min(limit, 100)),
)
return cur.fetchall()
Two quieter variants deserve attention. Wildcard injection â where a user supplies percent signs to make a LIKE match everything â is not injection in the classic sense but still defeats expectations, so escape the pattern. And dynamic table or column names cannot be parameterized at all; if a user choice must influence a sort column, map it through a dictionary of allowed identifiers instead of interpolating it.
Keep secrets out of the repository, permanently
A credential committed to version control is compromised even if you delete it in the next commit â the history retains it, forks retain it, and caches retain it. The discipline is simple to state: configuration comes from the environment or a secret manager at runtime, the repository contains only a sample file, and a pre-commit hook plus a scanner stops the mistake before it lands.
# .env.example is committed; .env never is
cat .env.example
PAYMENTS_API_KEY=
DATABASE_URL=
SESSION_SECRET=
# Rotate anything that has ever been committed, then purge history
git filter-repo --invert-paths --path secrets/local.env
git reflog expire --expire=now --all && git gc --prune=now --aggressive
# Fail the build if a credential appears in the tree or in history
gitleaks detect --source . --verbose
trufflehog git file://. --only-verified
# Load configuration at runtime, not build time
export DATABASE_URL="$(vault kv get -field=url secret/prod/payments)"
Rotation is the part teams skip. Write the incident-style runbook for a leaked key before you need it: revoke first, investigate second, because the key is already in someone else's hands. Dependency vulnerabilities follow the same logic â pin versions, update continuously, and let the scanner fail builds on known-exploitable advisories rather than reviewing a monthly report.
Errors and logs that tell an attacker nothing useful
Error handling decides whether an ordinary bug becomes an information leak. Exception messages routinely contain connection strings, fragmentary query text, internal file paths, and the names of services that were never meant to be public, and returning them to the client hands an attacker a map of your internals for free. The safe pattern is a two-part response: a stable, generic error code for the caller, plus a correlation identifier that lets your own support team find the detailed trace in the logging system. Details belong in the log, keyed to that identifier, where only people with access can read them â never in the HTTP body, never in a client-side console, and never in a message the user is expected to forward.
Logs deserve the same discipline because they are read by attackers who have already obtained some level of access. Writing raw user input straight into a log line allows newlines and control characters to forge entries, which is how an intruder makes one failed login look like a dozen separate events. Treat every field as data, strip line breaks before writing, and keep a strict separation between operational logs and audit logs: the audit trail records who did what to which object, survives longer, and must never contain tokens, session identifiers, or personal data beyond the identifiers needed for accountability.
import logging
import re
logger = logging.getLogger("payments")
SAFE_ERROR = {
"ValueError": "invalid_request",
"PermissionError": "forbidden",
}
def handle(exc, request_id):
# Generic code for the client; full detail stays in the log
public = SAFE_ERROR.get(type(exc).__name__, "internal_error")
logger.warning("request_failed id=%s type=%s", request_id, type(exc).__name__)
return {"error": public, "request_id": request_id}
LOG_STRIP = re.compile(r"[\r\n\t]+")
def audit(actor, action, target):
# One event per line: user input can never forge an extra entry
clean = lambda v: LOG_STRIP.sub(" ", str(v))
logger.info("audit actor=%s action=%s target=%s",
clean(actor), clean(action), clean(target))
The review checklist that catches most issues before tooling does
Static analyzers find patterns; reviewers find design problems. The checklist below is ordered by how often each item catches a real defect, and each row maps to an automated check you can add later so the same finding is never raised twice by a human.
| Check | What to look for | Automate with |
|---|---|---|
| Injection | Strings built into queries, shells, or LDAP filters | SAST rules, lint rules banning string SQL |
| Authorization | New endpoints without an ownership check | Route inventory diff in pull request review |
| Encoding | Rendering unescaped values, use of a raw/safe flag | CSP reporting plus template linting |
| Secrets | Hard-coded credentials, keys in config files | Pre-commit secret scanning |
| Error handling | Stack traces, SQL, or paths returned to clients | Integration tests asserting response shape |
| Dependencies | Newly added packages without a version pin | Lockfile checks, advisory scanning |
| Concurrency | Shared mutable state across requests | Targeted unit tests under load |
Add a row every time a defect escapes review; a checklist that never changes has stopped reflecting your codebase. The goal is not exhaustive coverage on day one, it is that the next author faces fewer decisions than the last one did.
â¨Make the secure path the default
Common Mistakes
Validating with a blocklist of forbidden characters
Fix: Describe the field with an allowlist pattern and reject anything that does not match exactly.
Applying one generic HTML escape everywhere, including inside script blocks or URLs
Fix: Choose the encoder for the destination context and let the template engine handle HTML by default.
Interpolating identifiers such as sort columns into parameterized queries
Fix: Map user choices through a dictionary of allowed identifiers; only values can be bound, never structure.
Deleting a leaked credential from the working tree and considering it resolved
Fix: Rotate the credential first, purge history second, and treat the old value as permanently compromised.
Relying on scanners to find missing authorization checks
Fix: Review new endpoints for ownership enforcement; scanners cannot infer your intended access model.
Best Practices
- Validate at every trust boundary and re-validate inside shared functions that multiple callers reach.
- Keep secrets in a manager or environment variable, commit only a sample file, and scan history on every push.
- Prefer framework auto-escaping and parameterized queries over custom replacements.
- Set a strict Content Security Policy so a missed encoding still cannot execute script.
- Extend the review checklist whenever a defect escapes, and automate each new row within the same sprint.
Key Takeaways
- Allowlist validation fails closed; blocklists fail on the first variation nobody anticipated.
- Output encoding is context-specific â HTML, URL, JSON, and shell each need their own treatment.
- Prepared statements eliminate SQL injection by fixing query structure before data is ever bound.
- Committed secrets must be rotated, not merely removed, because history and forks remember them.
- Scanners find patterns while reviewers find design flaws; authorization needs a human check on every new endpoint.