Engineering

Security from day one: small habits so you don't get hacked

Leaked keys, open ports, old libraries, no backups: the boring mistakes. Fixing them early is nearly free. Fixing them later costs a lot.

Translated from the Vietnamese original.

Share
Feedback

Quick recap

  • Most breaches come from mundane mistakes like leaked keys, open ports and stale libraries; fixing them from day one costs almost nothing.
  • Secrets never go in git: add .env to .gitignore from the first commit, scan for secrets in CI, and if a key leaks, revoke it and issue a new one.
  • Apply least privilege everywhere; expose only ports 80 and 443, never make the database or Redis public, and watch out for Docker opening ports even when ufw blocks them.
  • Commit lockfiles, enable automatic dependency updates, hash passwords with Argon2id, always use parameterized queries and filter by tenant.
  • Keep backups offline or immutable, actually test a restore, and go through the checklist at the end before going live.

▶ Listen to this post

A multi-layered white brick wall with a blue lock block in the middle, illustrating defense in depth
Contents
  1. Why this is the builder’s job
  2. A 30-minute threat model
  3. Secrets: never in git
  4. Least privilege, everywhere
  5. Network: open as few ports as possible
  6. Dependencies and the supply chain
  7. Login: the basics people still get wrong
  8. Input: don’t trust anything from outside
  9. HTTP headers and TLS
  10. Containers: don’t run as root
  11. Logs and monitoring: you can’t fix what you can’t see
  12. Backups: your last lifeline
  13. What if it happens anyway
  14. Go-live checklist
  15. Final words
  16. Nguồn tham khảo

If you build systems, you’ve probably had that 2 a.m. thought: did a key leak? Is someone poking at my database? That fear is real. But most hacks don’t come from a movie-style genius hacker. They come from boring mistakes: a .env file committed by accident, a database port open to the internet, an old library you’ll patch “next week” and then forget.

The good news: small habits block most of that, and they cost almost nothing if you start early. By the end of this post you’ll have a concrete list of things to do, plus a checklist to run before go-live.

Quick disclaimer before someone points it out: I’m not a security expert, and I don’t do pentesting (paying people to attack your system to find holes). This is what I’ve learned building and running systems with my team for small and medium-sized businesses. Your situation may be different, so skip what doesn’t fit.

Why this is the builder’s job

Two numbers made me reshuffle my priorities.

Verizon’s 2026 DBIR says almost a third (31%) of data breaches started with vulnerability exploitation. It’s the first time in the report’s 19 years that this path has beaten the use of stolen credentials. The same report found that breaches involving a third party made up 48%.1 In short: attackers don’t need to steal your keys anymore, because there’s an unpatched hole sitting right there. And almost half of breaches involve something you depend on.

The OWASP Top 10 for 2025 (a ranking of the 10 most common web security problems) says the same thing. The top three are Broken Access Control (bad permission checks), Security Misconfiguration (bad settings) and Software Supply Chain Failures (problems coming from outside libraries and tools).2 All three are in the hands of the people writing code and setting up infrastructure. And small teams usually don’t have a dedicated security team.

So nobody is going to do this for you.

A 30-minute threat model

A threat model just means sitting down and thinking about where your system could be attacked. The name sounds like committee meetings and thick documents. For small projects, my team usually needs 30 minutes at a whiteboard and four questions:

  1. What are we building? Draw boxes and arrows: users, frontend, API, database, queues, external services. Ugly is fine.
  2. What can go wrong? For each arrow, ask: who sends data here, can it be faked, can it be read by someone else?
  3. What are we going to do about it? Pick a few concrete things. You don’t need to fix everything.
  4. Did we do enough? Book a review in a month or two. Put it on the calendar, don’t just say “when we have time”.

The most useful question: “If one of our keys leaked today, what could the person holding it do?” The answer shows you right away where permissions are too wide.

Secrets: never in git

Secrets are things like database passwords, API keys and tokens. If they leak, someone else gets into your system. This is the mistake I see most, and the easiest to prevent.

GitGuardian’s 2026 report counted 28.65 million new hardcoded secrets (written straight into code) in public GitHub commits in 2025, up 34% from the year before. When they rechecked in January 2026, more than 64% of the secrets confirmed valid back in 2022 still worked.3 So keys leak, and years later nobody has changed them. If you’re thinking “it’s a private repo, I’m fine”: the same report says internal repos are about 6 times more likely to contain hardcoded secrets than public ones.3

What to do:

  • Put .env in .gitignore from the very first commit. The repo only holds a .env.example with fake values.
  • Run a secret scanner like gitleaks in both pre-commit and CI. People in a hurry find ways around pre-commit. CI doesn’t negotiate.
  • One set of keys per environment. If a staging key can open production, that’s a back door, not staging.
  • Production reads secrets from your cloud provider’s secret manager, or at least from a file on the server with 600 permissions. Not baked into the Docker image.
  • If a secret leaks, revoke it and create a new one. Deleting the commit isn’t enough. It’s like unsending a message after it’s been read: git history, forks and CI caches can still have it.
.env
.env.*
!.env.example

Least privilege, everywhere

Least privilege means giving each thing exactly the access it needs, nothing more. Everyone knows the rule, and everyone skips it “to save time”. The day something breaks, you pay for that time. Concretely:

  • Database: one user per service, with rights only on the schema it needs. A reporting service that only reads gets read-only access. Don’t run your app as postgres or root.
  • Cloud IAM (the part of the cloud that controls who can do what): one role per workload, no shared “admin” access key for everything. The CI key can deploy, but it can’t delete the backup bucket.
  • People: admin accounts separate from everyday accounts, with MFA (an extra login step like an OTP code or security key). When someone leaves, review the account list. Don’t let an ex-colleague’s account outlive their contract.
  • Application: every data query filters by owner or tenant (the customer or organization that owns the data). Broken Access Control is #1 on the OWASP Top 10 for a reason: bugs like “change the id in the URL and see someone else’s order” happen all the time when you only check are they logged in and forget do they have access to this record.2 A movie ticket doesn’t mean you can sit in any seat.

Network: open as few ports as possible

For a web server, my team aims for this: from the internet, you only see ports 80 and 443. Any other port needs a reason, and “easier debugging” doesn’t count.

  • Database and Redis are never exposed to the internet. They only listen on the internal network or 127.0.0.1.
  • Admin pages and monitoring dashboards sit behind a VPN or an IP allowlist (only certain IPs can get in). Don’t rely on just a password.
  • SSH with keys only, root login and password login turned off. Add fail2ban or restrict source IPs if you can.
# /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no

Here’s a Docker trap I’m guessing a lot of you have hit: when you write ports: "5432:5432" in docker-compose, Docker adds its own iptables rules, and that port can be open to the outside even if ufw is blocking it.4 You think the firewall has you covered. It doesn’t. If you really need access from the host, bind to localhost:

services:
  db:
    image: postgres:17
    ports:
      - "127.0.0.1:5432:5432"   # not "5432:5432"

Better still, don’t publish the database port to the host at all. Let services talk over Docker’s internal network.

Dependencies and the supply chain

A normal Node.js project pulls in hundreds of packages. Each one is code from people you’ve never met, running right on your server. Software Supply Chain Failures is #3 on the OWASP Top 10:2025,2 and that 48% of breaches involving a third party is the same story.1

Cheap things that work:

  • Commit the lockfile and use npm ci (or the equivalent) in CI, so what builds today builds the same tomorrow.
  • Turn on Dependabot or Renovate to get regular update PRs. Small updates every week are easy. Letting them pile up and jumping three major versions at once is painful.
  • Scan for vulnerabilities in CI with npm audit, osv-scanner or similar. To start, just fail the build on high-severity issues.
  • Watch out for typosquatting (fake packages with names close to real ones): one typo and you’ve installed a knockoff. Check the maintainer and download count before adding a new dependency.
  • Pin versions of Docker images and GitHub Actions. Don’t use latest. latest means “whatever”, and servers shouldn’t live like that. For Actions, pinning to a commit SHA is safer than pinning to a tag.
  • Generate an SBOM (a list of every library your system uses), so when a big vulnerability drops, “do we use this library?” takes seconds to answer instead of the whole team grepping until midnight.

Login: the basics people still get wrong

Storing passwords. Don’t roll your own, and don’t use plain MD5/SHA-256. OWASP recommends Argon2id with a minimum of 19 MiB of memory, 2 iterations and a parallelism of 1; if Argon2id isn’t available, use scrypt; bcrypt is only for legacy systems, with a work factor of 10 or more, and keep its 72-byte input limit in mind.5

Password rules. Good news if you’ve ever been forced to change your password on a schedule and just added 1, 2, 3 at the end: the new NIST SP 800-63B requires passwords used as the only factor to be at least 15 characters, doesn’t allow rules like “must have uppercase and special characters”, doesn’t allow forced periodic changes, but does require checking against lists of common or leaked passwords.6

Limit login attempts by both account and IP. Limit only by IP, and attackers just switch IPs. Limit only by account, and people can lock other users out on purpose. Keep the counters in Redis so they work correctly across multiple instances.

MFA is required for admin accounts, even if regular users don’t have it yet. Admin accounts have the highest privileges, so a leaked admin password exposes the whole system.

Sessions and JWT (a token holding login info, signed by the server and kept by the client). Traps I see often:

  • A JWT can’t be revoked, so if it leaks it stays valid until it expires. If you use JWT, keep access tokens short-lived and pair them with refresh tokens you can revoke on the server.
  • Not fixing the algorithm when verifying, which opens the door to alg-swap attacks.
  • Storing tokens in localStorage, where one XSS hole (someone injecting a script into your page) is enough to steal them. HttpOnly; Secure; SameSite=Lax cookies are usually safer for web apps.

Input: don’t trust anything from outside

Simple rule: treat anything users send you as possibly malicious, and check it all.

Always use parameterized queries, never string concatenation. Here’s an example with node-postgres, filtering by tenant too:

// Wrong: string concatenation, and forgot to check permissions
await db.query(`SELECT * FROM orders WHERE id = '${req.params.id}'`);

// Right: parameterized, and filtered by the logged-in user's tenant
await db.query(
  'SELECT * FROM orders WHERE id = $1 AND tenant_id = $2',
  [req.params.id, req.user.tenantId]
);

Escape output for its context. Most modern frontend frameworks escape by default. The holes usually show up exactly where you turn that off (dangerouslySetInnerHTML, v-html, {@html}). The first one literally says “dangerously”, so review those spots carefully.

SSRF in “enter a URL” features. SSRF is when outsiders get your server to call any address they want, including internal ones. It shows up in link previews, importing images from a URL, and webhooks. OWASP recommends an allowlist when possible; if you have to use a blocklist, block localhost, private IP ranges and link-local, check the IP after DNS resolution, turn off automatic redirect following, and especially block the cloud metadata address 169.254.169.254.7

File uploads. Check size and file type by content, not by extension (anyone can name a file .jpg), rename files when saving, and store them outside the web root or in object storage.

HTTP headers and TLS

Turn on HTTPS everywhere, redirect HTTP to HTTPS, then add a few basic security headers. A starter nginx config, based on OWASP’s recommendations:8

add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'" always;

A few notes:

  • HSTS (tells browsers to only use HTTPS for your site) is very hard to undo once browsers remember it. Start with a small max-age, make sure every subdomain runs HTTPS, then raise it. OWASP also warns that a bad config can lock real users out.8
  • X-XSS-Protection is outdated; OWASP says don’t turn it on, use CSP instead.8
  • In nginx, by default, if a location block has its own add_header, headers set at the server level are not inherited there.9 That’s why some pages have the headers and others don’t, and someone spends an afternoon scratching their head.
  • CSP (rules for where a page can load scripts and styles from) should start in Content-Security-Policy-Report-Only mode. See what gets blocked, then turn it on for real.
  • For APIs that use cookies, check the Origin header on requests that change data, or use a CSRF token. SameSite helps a lot, but I don’t treat it as the only layer.

Containers: don’t run as root

OWASP’s Docker cheat sheet has a few rules I think are worth memorizing.4

Don’t run as root. A simple Node.js Dockerfile:

FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
# Code is owned by root; the process runs as a user that can't modify it
USER node
CMD ["node", "server.js"]

Cut down permissions at runtime:

services:
  api:
    read_only: true
    tmpfs:
      - /tmp
    cap_drop:
      - ALL
    security_opt:
      - no-new-privileges:true

Don’t mount /var/run/docker.sock into a container, not even read-only. OWASP is clear that giving someone access to this socket is the same as giving them root on the host, and mounting it read-only doesn’t make the Docker API read-only.4 The “read-only” there is just for your peace of mind.

Also: use small base images, use multi-stage builds so the final image doesn’t carry build tools, and scan images in CI.

Logs and monitoring: you can’t fix what you can’t see

  • Structured logs (JSON) with a trace id (an ID that follows one request across services), so you can trace what happened.
  • Never log secrets, tokens, passwords or sensitive personal data. Filter sensitive fields in the logger itself. Don’t rely on everyone remembering.
  • Alert on weird login activity: a spike in failed logins, an admin login from an unusual country, a new API key being created, a user’s permissions changing.
  • Ship logs off the app server, because whoever breaks into the server usually deletes the logs there first.

Backups: your last lifeline

The old 3-2-1 rule still holds: three copies, on two types of storage, one somewhere else. Against ransomware (malware that encrypts your data and demands payment), what matters is having a copy that’s offline or can’t be overwritten. CISA says plainly that many ransomware strains look for and delete or encrypt reachable backups, so it recommends keeping backups offline and encrypted, and regularly testing that you can restore.10

Two questions I keep asking myself:

  • When did our team last test a restore? A backup you’ve never restored might not actually work.
  • Can the credentials that write backups also delete them? If yes, whoever takes over the server can delete them too. Use a bucket with object lock (blocks deletes and changes for a set time) or separate accounts.

What if it happens anyway

Nobody wants to think about it, but preparing a few things means less panic when it happens:

  • A key rotation runbook (step-by-step doc for changing keys): list every important secret, where it’s used, and how to replace it without taking the system down. Practice it at least once.
  • Who to call: who can shut the system down, who contacts the cloud provider, who talks to customers.
  • Keep evidence before cleaning up: take disk snapshots and save logs before wiping and rebuilding a machine. Don’t helpfully erase the attacker’s tracks for them.
  • Write it up afterward, no blame: why it wasn’t stopped, and what to fix so it doesn’t happen again. The goal is to fix the system, not to find someone to punish.

Go-live checklist

This is the list my team runs through before putting a system into production. It’s not everything, but it’s the minimum. Missing a row means you’re not going live, you’re just gambling:

Area What to check
Secrets No secrets in the repo or images; secret scanning in CI; separate keys per environment
Permissions One DB user per service; separate IAM roles; MFA for admins; every query filtered by owner/tenant
Network Only 80/443 visible from the internet; DB/Redis not public; SSH keys only; admin pages behind VPN/allowlist
Dependencies Lockfile committed; Dependabot/Renovate on; vulnerability scans fail the build on high severity
Authentication Passwords hashed with Argon2id/scrypt; rate limits by account + IP; sessions/tokens can be revoked
Input Parameterized queries; SSRF protection on URL-fetching features; uploads checked for content and size
HTTP HTTPS everywhere; HSTS, CSP, nosniff, Referrer-Policy; Origin/CSRF checks on data-changing requests
Containers Not running as root; cap_drop: ALL; no docker.sock mount; pinned image versions
Monitoring JSON logs with trace id; no secrets/PII in logs; alerts for unusual logins; logs stored off the server
Backups Offline/undeletable copy; real restore tested; separate backup credentials
Incidents Key rotation runbook; contact list; know how to preserve evidence

Final words

Security for builders isn’t about knowing every attack. It’s about making the safe way the default way: a project template with the right .gitignore, a sample Dockerfile that already has USER, a sample compose file that doesn’t publish the DB port, a sample CI with the scan step built in. When the right way is also the easiest way, the whole team does it without being reminded. Everyone is in a hurry sometimes. Designing things so the hurried way is still safe is the actual job.

This is what my team and I actually do and run today. If you have better habits or see it differently, message me, and when you’re free let’s grab a coffee and keep talking. Your secrets stay with you.

Nguồn tham khảo

  1. Verizon (05/2026). Vulnerability exploitation top breach entry point, 2026 industry-wide DBIR finds. ↩ ↩2

  2. OWASP (2025). OWASP Top 10:2025. ↩ ↩2 ↩3

  3. GitGuardian (03/2026). The State of Secrets Sprawl 2026. ↩ ↩2

  4. OWASP Cheat Sheet Series. Docker Security Cheat Sheet. ↩ ↩2 ↩3

  5. OWASP Cheat Sheet Series. Password Storage Cheat Sheet. ↩

  6. NIST (2025). SP 800-63B-4: Digital Identity Guidelines — Authentication and Authenticator Management, section 3.1.1. ↩

  7. OWASP Cheat Sheet Series. Server-Side Request Forgery Prevention Cheat Sheet. ↩

  8. OWASP Cheat Sheet Series. HTTP Security Response Headers Cheat Sheet. ↩ ↩2 ↩3

  9. nginx. Module ngx_http_headers_module, add_header section. ↩

  10. CISA & MS-ISAC (09/2023). #StopRansomware Guide. ↩