Lesson 16 of 18Working like an engineer
Security Habits for Developers
What attackers want from developers, how passwords should be stored, what HTTPS does and does not protect, how to handle secrets, and injection in one example.
A junior developer pushes a side project to a public GitHub repo on a Friday evening. Inside a config file is a cloud access key. By Saturday morning someone has used it to start dozens of servers mining cryptocurrency, and the bill lands on their employer. Nobody targeted that developer personally. Automated scanners watch every public push, and the key was found within minutes. Most security incidents look like this: not a genius hacker, but an ordinary mistake found by an automated tool. This lesson covers the fundamentals every developer needs from week one. The deeper team practices, like the OWASP Top 10, dependency policies and secret scanning in CI, are in "Security Hygiene" in the Engineering at Work course.
What attackers actually want
It helps to think like the other side. Attackers are mostly running a business, and they want things they can use or sell:
- Data. Email addresses, password hashes, payment details, personal records. Sold in bulk, or used for fraud and blackmail.
- Money and compute. Your cloud account can mine cryptocurrency or send spam on your bill. A payment system can be tricked into refunds.
- Access. One account is a stepping stone to the next. A developer's laptop, GitHub account or cloud credentials can reach production systems, other people's code, and the company's customers.
That last point is why developers are a favourite target. You hold keys that ordinary users do not: push access to code that ships to thousands of people, tokens for cloud accounts, database passwords. Most attacks on developers do not break clever cryptography. They take credentials that were left lying around, reused, or handed over to a convincing fake.
So the fundamentals are mostly about not leaving keys lying around:
- Protect your own accounts.
- Store your users' passwords properly.
- Keep data encrypted in transit.
- Keep secrets out of code.
- Never let user input become code.
Protecting your own accounts
Your accounts come first, because a stolen GitHub or email account undoes every other precaution.
- Use a password manager (the one built into your operating system, or a dedicated app). It generates a long random password for every site and remembers them. The point is that every password is unique: when one site is breached, attackers try the leaked email and password on hundreds of other sites. This is called credential stuffing, and it works because people reuse passwords.
- Turn on two-factor authentication (2FA) everywhere that matters: email, GitHub, cloud consoles, the password manager. Prefer an authenticator app or a hardware security key. SMS codes are the weakest form, because attackers can talk a phone company into moving your number to their SIM card.
- Use passkeys where offered. A passkey replaces the password with a key pair stored on your device. GitHub, Google, Apple and Microsoft all support them. They cannot be phished, because your device only uses a passkey on the real site it was created for.
Storing passwords: hashing, salts and slowness
Now the other side: your app has users with passwords. The first rule is that you never store the password itself. If your database leaks, and you should plan as if it will, the attacker should not be able to log in as anyone.
You store a hash instead. A hash function turns any input into a fixed-length fingerprint, and it is one-way: easy to compute from the password, practically impossible to reverse. At login you hash what the user typed and compare it with the stored hash. Note the difference from encryption, which is two-way: anything encrypted can be decrypted by whoever has the key. Passwords should never be decryptable, not even by you.
What does this print?
import hashlib short = hashlib.sha256(b"a").hexdigest() long = hashlib.sha256(b"a much, much longer password").hexdigest() print(len(short), len(long))
But a plain fast hash is still not enough. Run this to see why:
Press Run (⌘ Enter) to see what happens.Two problems show up. Sam and Lee have the same hash, so cracking one cracks both, and the attacker can see who shares a password. And the attacker hashed the common passwords once and cracked everyone with them. Real attackers use lists of billions of leaked passwords, and graphics cards that compute billions of SHA-256 hashes per second.
The fixes:
- A salt: a random value generated for each user and stored next to their hash. The salt is mixed in before hashing, so the same password gives a different hash for every user, and a precomputed list is useless. Salts are not secret. Their job is to be unique.
- A slow hash: an algorithm designed to take real time and memory per guess, such as Argon2id, scrypt or bcrypt. Your login does one hash per attempt and barely notices. An attacker making billions of guesses is slowed down enormously.
This sketch shows both ideas. It uses repeated SHA-256 only to keep the demo in the standard library. Do not copy it into a real app:
Press Run (⌘ Enter) to see what happens.The same password now gives different hashes, and every guess costs milliseconds instead of nanoseconds. secrets is Python's module for security-grade randomness: never use random for salts, tokens or reset codes, because its output can be predicted. hmac.compare_digest compares in constant time, so an attacker cannot learn anything from how long a comparison takes.
In real code, never write any of this yourself. Use your framework's built-in password handling (Django and most auth libraries already do it correctly), or a maintained library such as argon2-cffi or bcrypt in Python and argon2 or bcrypt on npm. Better still, use a proven authentication service so you store no passwords at all. Check the library's docs for current recommended settings.
HTTPS: what it protects and what it does not
In "How the Web Works" you saw that TLS, the S in HTTPS, encrypts traffic and checks the server's certificate. As a developer you need to know exactly what that buys you.
The email and password travel inside TLS. Café Wi-Fi, a home router or an internet provider sees only encrypted bytes and the server's name.
HTTPS gives three guarantees in transit: nobody can read the traffic, nobody can change it unnoticed, and you are talking to the real server named in the address. It does not make the server itself safe. A site with a padlock can still store plain-text passwords, log credit card numbers, or have an injection bug. The padlock means "the pipe is private", not "the destination is trustworthy". Phishing sites have padlocks too.
The practical rules are simple. Use HTTPS for everything, not only login pages, because cookies and tokens travel on every request. Most hosting platforms set up certificates and renew them automatically. Never disable certificate checks in code (such as verify=False in Python's requests or httpx) to make an error go away. That error is usually telling you something real, and switching it off removes the "real server" guarantee.
Secrets do not belong in code
A secret is anything that grants access: API keys, database URLs with passwords in them, tokens, private keys, signing keys. The rule is absolute: secrets never go in your code or your Git history.
In "Setting Up Your Machine" you set up the pattern: a .env file, ignored by Git, holds the real values locally, and a committed .env.example lists the names with fake values. In production the values come from the hosting platform's settings or a secret manager. Your code only ever reads them from the environment.
Tools that scan for leaked secrets work by recognising key shapes. Here is a toy version running over the lines a developer is about to commit:
Press Run (⌘ Enter) to see what happens.(AKIAIOSFODNN7EXAMPLE is the fake key from AWS's own documentation.) GitHub runs a much larger version of this, called secret scanning, and its push protection can block a push that contains a known key format. Leave it on. But scanners only catch formats they know, so they are a safety net, not a plan.
If you do leak a secret, the order matters:
- Revoke or rotate it immediately, in the service that issued it. Assume it has already been copied. Bots scrape public pushes within minutes, and deleting the file does not help, because the key is still in Git history and in every clone and fork.
- Tell someone. At work, your lead or security team. Check the service's logs for use you do not recognise.
- Then clean up the history if needed. A new commit that deletes the file is not enough to remove it from history, and rewriting history is a cleanup step, never the fix.
Two more habits reduce the damage when a secret does leak. Least privilege: create tokens with only the permissions and repositories they need, and with an expiry date. Separate environments: development and production use different credentials, so a leaked dev key cannot touch real customer data.
You just pushed a live API key to a public repo. Put the response in order.
- Tap the steps below in the right order.
Injection in one example
The most important coding rule in security fits in one sentence: never build code out of user input. When text from a user is glued into a SQL query, a shell command or an HTML page, the user can write text that changes what the code means. That is injection.
Here is a user lookup built with an f-string, and the same lookup written properly:
Press Run (⌘ Enter) to see what happens.With a normal email the unsafe version works, which is why this bug survives testing. With the attack string, the quote closes the email early and OR '1'='1' becomes part of the query. That is always true, so the query returns every user, including the admin. In a login form, that can mean logging in without a password. In other queries it can mean reading or deleting whole tables.
The safe version uses a parameterized query: the ? is a placeholder, and the value is sent to the database separately from the SQL. The database never treats it as code, so the attack string is just a strange email that matches nobody. Every database library supports this (? in sqlite3, %s in psycopg, $1 in Postgres drivers for Node), and ORMs do it for you.
The same idea appears everywhere. Gluing user text into HTML lets it run JavaScript in other users' browsers, which is called cross-site scripting (XSS). Templates and frameworks like React escape text by default for exactly this reason. Gluing it into a shell command lets it run other commands. The fix is always to keep data and code separate. "API Security" in the Python Backend course goes further on authentication and the attacks that target APIs.
- hash
- A one-way, fixed-length fingerprint of some data. The same input always gives the same hash, and the hash cannot be turned back into the input.
- salt
- A random value stored with each password hash, so identical passwords get different hashes. Unique, not secret.
- credential stuffing
- Trying email and password pairs leaked from one site on many other sites. Defeated by unique passwords and 2FA.
- passkey
- A phishing-resistant replacement for passwords, using a key pair stored on your device that only works on the real site.
- secret
- Anything that grants access: API keys, tokens, database passwords, private keys. Kept in the environment or a secret manager, never in code.
- least privilege
- Giving each account, token or service only the access it needs, ideally with an expiry date.
- SQL injection
- User input changing the meaning of a SQL query because it was glued into the query text. Prevented with parameterized queries.