Skip to content

Lesson 23 of 28Production ownership

Security Hygiene for Every Engineer

The everyday habits that stop most breaches: secrets out of Git, a locked-down supply chain, least-privilege access, spotting phishing, and reporting fast.

13 min read0/4 questions

It is 5:40 p.m. and you are trying to get a failing integration test green before you leave. You hard-code the payment provider's test key to rule out a config problem, it works, and you push. Ten minutes later you notice and revert the commit. You have not fixed anything: the key is still in the repository's history, in every clone and fork made since, and possibly already in the hands of a bot that scans public pushes for credentials within minutes. Most real breaches start with small, ordinary lapses like this one rather than clever exploits. This lesson is about the habits that prevent them and what to do in the first hour when one slips through.

Where hygiene fits

Security work comes at several levels. Threat Modeling and Security by Design covers how to design a system so whole classes of attack are impossible. Web Security for JavaScript Developers and API Security cover the bugs you can write into code: XSS, CSRF, broken object authorisation, injection. This lesson is the layer underneath all of them: the habits of the person writing the code. A well-designed system still falls over if its deploy token is in a public gist.

It helps to know the shared vocabulary. The OWASP Top 10 is the most cited list of web application risk categories, and the current edition is 2025:

  1. Broken Access Control: users acting outside their permissions. Server-side request forgery (SSRF) now sits in this category.
  2. Security Misconfiguration: default credentials, open storage buckets, verbose errors, unneeded features switched on.
  3. Software Supply Chain Failures (new): compromised or vulnerable dependencies, build tools and pipelines.
  4. Cryptographic Failures: weak or missing encryption, bad key handling.
  5. Injection: untrusted input interpreted as code or queries, including XSS.
  6. Insecure Design: flaws in the design itself, which no amount of careful code fixes.
  7. Authentication Failures: weak login, session and credential handling.
  8. Software or Data Integrity Failures: trusting updates, artefacts or serialised data without verifying them.
  9. Security Logging and Alerting Failures: attacks that nobody sees, or sees too late.
  10. Mishandling of Exceptional Conditions (new): errors that fail open, leak details or leave the system in an unsafe state.

If you learnt the 2021 list, notice that "Vulnerable and Outdated Components" grew into the broader supply chain category, and SSRF is no longer its own entry. Interviewers do ask about the list; knowing why supply chain moved up to third says more than reciting the order. Notice too how many of the categories are about habits rather than clever code: misconfiguration, supply chain, authentication, logging. That is the part every engineer owns.

Secrets: keep them out of Git entirely

A secret is anything that grants access: API keys, database passwords, signing keys, OAuth client secrets, session cookies, private SSH keys, cloud credentials. The rules are short.

  • Never commit a secret, not even to a private repo, not even "temporarily". Private repos get cloned to laptops, mirrored to CI, shared with contractors and occasionally made public.
  • Locally, read secrets from environment variables, usually loaded from a .env file that is in .gitignore. Commit a .env.example with the variable names and fake values so others know what to set.
  • In production and CI, use a secret manager (your cloud's secrets service, Vault, or your CI platform's encrypted secrets) and inject values at run time. Better still, avoid long-lived secrets altogether: workloads that get short-lived credentials from an identity system (cloud roles, OIDC from CI to your cloud) have nothing to leak. IAM shows how that works on AWS.
  • Do not paste secrets into chat, tickets, logs or AI tools. Channels get exported and searched; a key in a Slack message is a leaked key.

Then add automated nets, because the rules will fail on a tired evening. GitHub's secret scanning detects known credential formats in repositories, and push protection blocks a push that contains one before it lands; it is on by default for public repositories, and organisations can enable it more widely (check GitHub's docs for what your plan includes). Tools such as gitleaks and trufflehog run the same kind of check in a pre-commit hook on your machine and again in CI, so a secret is caught before it ever leaves your laptop.

Scanners combine two ideas: known formats (many providers give keys a recognisable prefix) and entropy, a measure of how random a string looks. Here is a small version you can run and change.

Python
import mathimport re # Two of the ideas real scanners such as gitleaks combine:# 1. Known formats: many providers give their keys a recognisable prefix.# 2. Entropy: random-looking strings near words like "secret" or "token".PATTERNS = { "aws_access_key_id": re.compile(r"\bAKIA[0-9A-Z]{16}\b"), "github_token": re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36}\b"), "private_key": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),}ASSIGNMENT = re.compile(r"(?i)(secret|token|password|api_?key)\w*\s*[:=]\s*['\"]?([^'\"\s]+)") def entropy(s): """Shannon entropy in bits per character.""" counts = {c: s.count(c) for c in set(s)} return -sum(n / len(s) * math.log2(n / len(s)) for n in counts.values()) def scan(text): findings = [] for lineno, line in enumerate(text.splitlines(), 1): for name, pattern in PATTERNS.items(): if pattern.search(line): findings.append((lineno, name)) m = ASSIGNMENT.search(line) if m and len(m.group(2)) >= 16 and entropy(m.group(2)) > 3.5: findings.append((lineno, "high_entropy_" + m.group(1).lower())) return findings diff = """DATABASE_URL=postgres://localhost:5432/devSTRIPE_SECRET_KEY=sk_test_51Hx9QeLkT2vR8mWbN4pZ7yJcD3fG6sAAWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLEPASSWORD=changemeAPI_KEY=aaaaaaaaaaaaaaaaaaaaaaaa""" for lineno, rule in scan(diff): print(f"line {lineno}: {rule}")print("entropy of 'changeme':", round(entropy("changeme"), 2))print("entropy of the Stripe value:", round(entropy("sk_test_51Hx9QeLkT2vR8mWbN4pZ7yJcD3fG6sA"), 2))
Output
Press Run (⌘ Enter) to see what happens.

It catches the random-looking Stripe-style key and the AWS key, and it misses PASSWORD=changeme, which is short and low-entropy, yet still a real credential if someone uses it. Every scanner trades false positives against misses. That is why scanning is a net, not a plan: the plan is not putting secrets in code in the first place.

Predict the outputPython

What does this print?

import re
pat = re.compile(r"\bAKIA[0-9A-Z]{16}\b")
lines = [
  "aws_key = AKIAIOSFODNN7EXAMPLE",
  "aws_key = akiaiosfodnn7example",
  "aws_key = AKIAIOSFODNN7EXAMPLE1",
]
print(sum(bool(pat.search(line)) for line in lines))
Need a nudge? Hints walk you through it.

When a secret leaks: rotate before you clean up

When you find a secret in a commit, a log or a screenshot, the order of operations matters. The instinct is to hide the evidence by rewriting history. That is the wrong first move. Once a secret has been pushed, assume it is compromised: you cannot recall copies in clones, forks, CI caches, mirrors or a scraper's database. The only thing that makes it safe is making the secret worthless.

Put it in order6 steps

You notice an API key for a production service in a commit you pushed to a shared repo an hour ago. Order the response.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Do not quietly fix it and hope. Security teams treat a fast, honest report as the best possible outcome, and in a company with a healthy culture, nobody gets in trouble for reporting their own mistake quickly. They do get in trouble for hiding one.

Dependencies and the supply chain

A typical service has hundreds or thousands of transitive dependencies, and each one is code from strangers that runs with your permissions, sometimes at install time. Supply chain attacks went mainstream in 2025. In March, the popular GitHub Action tj-actions/changed-files was compromised: attackers repointed its version tags at a malicious commit that printed CI secrets into workflow logs, so every repo that referenced the action by tag ran the attacker's code. In September, a maintainer of widely used npm packages, including chalk and debug, was phished through a fake npm support email, and malicious versions were published that tried to hijack cryptocurrency transactions in browsers. Within weeks the Shai-Hulud worm went further: it stole npm and cloud tokens from developer machines and CI, then used them to publish infected versions of the victims' own packages, spreading itself. A second wave followed in November.

The habits that limit this kind of damage:

  • Commit your lockfile and install from it. Use npm ci (or pnpm install --frozen-lockfile) in CI, and uv sync --locked for Python. A lockfile pins every transitive version and hash, so a newly published malicious version does not sneak in on a routine build.
  • Treat install scripts as code execution. Lifecycle scripts like postinstall run on your machine when you install. Newer package managers can block them unless you allow a package explicitly (pnpm does this by default since version 10); with npm you can set ignore-scripts. Check the docs for your tool.
  • Do not upgrade the minute a release appears. Dependabot or Renovate opening PRs is good; merging them unread is not. Many teams add a cooldown (a minimum release age) so a new version must survive a few days in the wild before it reaches them; most of the 2025 malicious releases were pulled within hours.
  • Pin third-party GitHub Actions to a full commit SHA, not a tag. Tags can be moved; a SHA cannot. Renovate and Dependabot can keep SHA pins updated.
  • Check what you add. Before npm install some-package, look at who publishes it, how many people use it, and whether the name is exactly right. Typosquatting registers names one keystroke from a popular package. Slopsquatting registers names that AI assistants tend to invent, waiting for someone to install a hallucinated suggestion.
  • Fewer dependencies is a security feature. Twenty lines you write yourself cannot be hijacked by a stranger.
  • For things you publish, use the registry's trusted publishing (CI publishes through short-lived OIDC credentials instead of a stored token) and provenance attestations, so consumers can verify where a package was built. An SBOM (software bill of materials) lists what you ship, which is what lets you answer "are we affected?" in minutes when the next incident hits.
JavaScript
// A tiny version of what dependency firewalls check before an install.const POPULAR = ["react", "lodash", "express", "axios", "chalk", "debug", "requests", "colorama"]; function distance(a, b) { // Levenshtein edit distance: insertions, deletions, substitutions. const dp = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]); for (let j = 1; j <= b.length; j++) dp[0][j] = j; for (let i = 1; i <= a.length; i++) { for (let j = 1; j <= b.length; j++) { const cost = a[i - 1] === b[j - 1] ? 0 : 1; dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost); } } return dp[a.length][b.length];} function check(name) { if (POPULAR.includes(name)) return "ok (exact match)"; const near = POPULAR.filter((p) => distance(name, p) <= 2 && Math.abs(p.length - name.length) <= 2); return near.length ? `SUSPICIOUS: one or two edits from ${near.join(", ")}` : "unknown: check who publishes it";} for (const name of ["axios", "axois", "loadash", "expresss", "colourama", "react-dom-helpers"]) { console.log(name.padEnd(18), check(name));}
Output
Press Run (⌘ Enter) to see what happens.

colourama is a real example: a malicious lookalike of the Python package colorama was published on PyPI years ago. Note the last line, too. A name that is not close to anything popular is not proof of safety; it just means you have to look at the publisher yourself.

Where each habit sits on the path to production
Your laptop: pre-commit scanYour laptoppre-commit scanPackage registry: npm, PyPIPackage registrynpm, PyPIGit repo: push protectionGit repopush protectionCI pipeline: lockfile, pinned actionsCI pipelinelockfile, pinned actionsSecret manager: short-lived credsSecret managershort-lived credsProduction: least privilegeProductionleast privilegeinstallpushbuildinstallOIDCdeployinject

Dependencies enter at install. Check the name and publisher, block install scripts you did not approve, and add new versions after a cooldown.

1/5

Access: least privilege, strong sign-in

Your own accounts are part of the attack surface. An engineer's laptop and logins usually reach source code, CI, cloud consoles and sometimes production data, which is why attackers target engineers specifically.

  • Least privilege. Ask for the access the task needs, for as long as it needs it. Use fine-grained personal access tokens scoped to specific repos with an expiry date, not a classic token with every scope that never expires. Prefer just-in-time elevation for production access over standing admin rights.
  • MFA everywhere, and passkeys where you can. Passkeys and hardware security keys are phishing-resistant: the browser only uses them on the real site's origin, so a lookalike login page gets nothing. One-time codes and push approvals can be phished or relayed.
  • Lock your screen and keep the machine updated. Unattended unlocked laptops and month-old OS patches are still how a lot of incidents start.
  • Clean up. Remove access you no longer need, revoke tokens for finished projects, and tell IT when someone leaves a team so their access is reviewed.

Phishing aimed at engineers

Phishing that targets developers rarely looks like a prize draw. It looks like work.

  • A registry or GitHub "security notice" asking you to re-verify 2FA on a lookalike domain. This is exactly how the npm maintainer in 2025 lost their account.
  • A recruiter with a take-home test: clone this repo, run npm install and the app. The project's dependencies or setup script install malware that steals browser sessions, keys and crypto wallets. Security researchers have tracked campaigns doing this at scale, often called "Contagious Interview". Run unknown code in a throwaway VM or container, never on your work machine.
  • MFA fatigue: a stream of push prompts at midnight, then a message from "IT" asking you to approve one to make them stop. Uber's 2022 breach began roughly this way.
  • OAuth consent phishing: a convincing app asks for access to your GitHub or Google account. Granting it hands over a token without any password being stolen.
  • Help desk impersonation: someone calls your IT support pretending to be you to reset your MFA. You cannot stop that yourself, but you can report odd calls or messages about your account.

The habits: slow down when a message is urgent, go to the site yourself instead of clicking the link, verify unusual requests through a second channel (call the person, ask in the team channel), and report suspicious messages through your company's report button or security channel, even if you did not click. One report lets the security team block the campaign for everyone. If you did click, report that too, immediately. Minutes matter more than embarrassment.

Match the pairs0/5 matched

Match each threat to the habit or control that best defends against it.

Choose an item, then its match on the other side.

Handling data

Treat production data as something you borrow, not something you have.

  • Keep personal data out of logs. Emails, phone numbers, tokens, full card numbers and request bodies end up in log storage that many people can search and that is kept for months. Log ids and redact the rest. This is also a legal matter under privacy laws like GDPR.
  • Do not copy production data to your laptop or into a staging environment without approval. Use anonymised or synthetic data for debugging, and follow your company's process when you truly need real records.
  • Use approved tools only, including AI tools. Pasting customer data or proprietary code into an unapproved chatbot or browser extension is a data leak, even if it feels like asking a colleague. AI Security covers the specific risks of agents, prompt injection and tool access.
  • Fail closed. Mishandling of Exceptional Conditions made the 2025 list for a reason: an exception that skips an authorisation check, or an error page that prints a stack trace with config values, turns a bug into a breach. When you write error handling, ask what the user can do or see after the error.

Reporting and asking for review

Every company has a way to report a security concern internally: a security channel, an email alias, a form or an on-call rotation. Find it in your first week, before you need it. Report anything that looks wrong, including a vulnerability you spot in someone else's code or a suspicious log entry. Give facts: what you saw, where, when, and what you have already done. Do not test an exploit against production to prove it is real; describe it and let the security team decide.

Also learn when to ask for a security review before shipping. Common triggers written into design doc templates: new handling of personal or payment data, a new authentication or authorisation path, a new public endpoint or file upload, new third-party services or SDKs, changes to encryption or key handling, and new infrastructure permissions. Raising these early is cheap; the review is a conversation, not a gate you failed.

Quick check
A teammate leaked a key, force-pushed a rewritten history that removes it, and says the issue is closed. What is missing?
Need a nudge? A hint rules out a wrong answer.
Key terms
OWASP Top 10
OWASP's list of the most important web application risk categories; the current edition is 2025.
secret scanning
Automated detection of credentials in code and history, using known formats and entropy; push protection blocks them before they land.
secret rotation
Replacing a credential with a new one and revoking the old, the only real fix for a leaked secret.
supply chain attack
Compromising software you depend on, such as a package, build tool or CI action, to reach everyone who uses it.
typosquatting
Publishing a malicious package under a name one small typo away from a popular one.
least privilege
Granting only the access a person or service needs, for only as long as it needs it.
phishing-resistant MFA
Sign-in factors such as passkeys and security keys that only work on the genuine site, so lookalike pages cannot capture them.