PortSwigger teaches you to find these bugs. This chapter is the other half: designing so they can't happen, and catching them in code review. Every section has the same shape: the mistake, how to spot it, the fix.
The OWASP Top 10 is the industry's shared list of the most common web risks. Broken access control has been number one since 2021, so we start there.
1. Broken access control
The mistake. The app checks that you're logged in, but not whether this record is yours or whether your role may do this.
Two flavours:
- Horizontal: a user reads or changes another user's data (often called IDOR, insecure direct object reference).
/api/invoices/1043returns invoice 1043 to anyone signed in. - Vertical: a regular user reaches an admin function.
How to spot it in review.
- Any handler that takes an id from the URL or body and loads a record. Is there a check that ties the record to the caller?
- Role checks that live in the UI only (a hidden button is not a permission).
- Authorization declared in one place but read in another. In NestJS, a guard that reads metadata only from the handler will miss a decorator placed on the class. Pulse had exactly this, and it's fixed:
RolesGuardnow usesgetAllAndOverrideacross handler and class.
The fix.
- Default deny: every route requires an explicit policy.
- Scope queries by the caller, not by trust in the input:
// C#: the caller's id comes from the auth cookie, never from the request
var note = await db.Notes.SingleOrDefaultAsync(n => n.Id == id && n.OwnerId == User.GetUserId());
if (note is null) return NotFound(); // NotFound, not Forbid: don't confirm it exists
// NestJS: scope from req.user, ignore client-supplied tenant fields for non-admins
const partnerId = user.access_level === 'fen_admin' ? query.partner_id : user.partner_id
- Put it in the database too where you can. Maeve's per-user connection scoping (row-level security) means even a buggy handler can't read another family's rows.
- Write a test per role per route. A table-driven test "role X on route Y expects status Z" catches regressions forever.
2. Injection (SQL, command, template)
The mistake. Untrusted text is glued into something that gets interpreted: a SQL query, a shell command, a template.
// Vulnerable: the input becomes part of the SQL grammar
pool.query(`SELECT * FROM users WHERE username = '${username}'`)
How to spot it. Search for string building next to interpreters: template literals or + near query(, exec(, spawn( with shell: true, FromSqlRaw, Process.Start.
grep -rnE "query\(\`[^\`]*\\$\{" src/ # NestJS/pg template literals in queries
grep -rn "FromSqlRaw\|ExecuteSqlRaw" . # EF Core raw SQL
The fix. Parameters, always. The value travels separately from the grammar, so it can never change the query's meaning.
pool.query('SELECT * FROM users WHERE username = $1', [username])
await using var cmd = new NpgsqlCommand("SELECT * FROM users WHERE username = @u", conn);
cmd.Parameters.AddWithValue("u", username);
For things that can't be parameters (a column name to sort by), use an allow-list: map the input to one of a few known values. For shell commands, don't use a shell; pass an argument array, and validate against an allow-list.
3. Cross-site scripting (XSS)
The mistake. User-controlled text is inserted into a page as HTML or script, so it runs in other users' browsers with their session.
How to spot it.
- Razor:
@Html.Raw(...)on anything that isn't fully trusted. Razor encodes@valueautomatically;Html.Rawturns that off. - React:
dangerouslySetInnerHTML, or buildinghrefvalues from user input (ajavascript:URL runs code). - Plain JS:
innerHTML =with data from the server or URL. - Markdown rendering that allows raw HTML.
The fix.
- Let the framework encode. Use
Html.Rawonly on HTML you generated from trusted sources, or that went through a sanitizer. - Render Markdown with raw HTML disabled (Markdig:
.DisableHtml(), which this very guide uses). - Add a Content-Security-Policy header so injected script can't run even if a bug slips through. Start strict:
default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none', then add what you really need. Avoid'unsafe-inline'and'unsafe-eval'where you can. - Session cookies
HttpOnly, so script can't read them.
4. Cross-site request forgery (CSRF)
The mistake. The browser automatically attaches cookies to requests. If your API authenticates with a cookie, a page on another site can make the browser send a request to your API, and the cookie rides along. The attacker can't read the response, but the action still happens.
What makes an app exposed:
- Cookie-based authentication, and
- The cookie is sent cross-site (
SameSite=None, which you need when frontend and API are on different sites), and - State-changing endpoints that accept requests a plain HTML form can send:
POSTwithapplication/x-www-form-urlencoded,multipart/form-dataortext/plainbodies. Express and NestJS parse form bodies by default.
CORS does not stop this. CORS controls whether the other site can read the response; simple form posts don't need permission to be sent.
How to spot it. Check cookie attributes (SameSite), which body parsers are enabled, and whether mutations check anything beyond the cookie.
The fix (pick at least one, ideally two).
- Require JSON on mutations. A cross-site page can only send
application/jsonafter a CORS preflight, which your allow-list refuses. In NestJS, reject other content types on POST/PUT/PATCH/DELETE with a small middleware, or disable the urlencoded parser if nothing uses it. - Check
Origin(fall back toReferer) on state-changing requests against the same allow-list you use for CORS. - Custom header, e.g.
X-Requested-With: pulse, required on mutations. Browsers won't add a custom header cross-site without a preflight. - Anti-forgery tokens. ASP.NET Core Razor Pages does this for you on forms (Maeve's
AntiforgeryFailureFiltershows the failures). - Prefer
SameSite=Laxwhen frontend and API can share a site, e.g.app.example.comandapi.example.comunder one domain.
// NestJS middleware sketch: refuse non-JSON bodies on state-changing requests
app.use((req, res, next) => {
const mutating = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)
const hasBody = Number(req.headers['content-length'] ?? 0) > 0
if (mutating && hasBody && !req.is('application/json')) {
return res.status(415).json({ error: { code: 'UNSUPPORTED_MEDIA_TYPE' } })
}
next()
})
5. Authentication and sessions
Mistakes to look for.
- Rate limits keyed on something the client controls. The classic: reading the client IP from the first
X-Forwarded-Forentry. Anyone can put any value there. Behind a proxy, trust only the entries your own proxies added (count from the right), or use the platform's trusted client-IP feature. - Rate limits only by IP. Add a per-account limit too, so one account can't be attacked from many addresses.
- Tokens that stay valid after logout, password change or role change. (Pulse fixed this with per-request session lookup.)
- JWT secrets with a hardcoded fallback. If configuration is missing, fail to start rather than run with a known secret.
- Password reset links that don't expire, aren't single-use, or reveal whether an email exists.
- Login errors that differ between "no such user" and "wrong password".
The fix. Use the framework's identity system where possible, hash passwords with a slow hash (bcrypt, Argon2, ASP.NET Identity's PBKDF2), short-lived sessions, server-side revocation, MFA for admins, and uniform error messages.
// Fail fast on missing secrets
const secret = config.get<string>('JWT_SECRET')
if (!secret && process.env.NODE_ENV !== 'development') throw new Error('JWT_SECRET is required')
6. Server-side request forgery (SSRF)
The mistake. The server fetches a URL that the user influences. Now the user can make your server reach places they can't: localhost admin ports, internal services, or the cloud metadata address 169.254.169.254, which can hand out credentials.
How to spot it. Any HttpClient, fetch, axios or image/PDF renderer whose URL contains request data.
The fix. Don't let users choose hosts. Build URLs from a fixed base and validated parts, as TomiWebsites' /Portfolio price proxy does: the symbol must match ^[A-Z0-9.\-^=]{1,12}$, is URL-escaped, and is inserted into a fixed Yahoo URL. If you truly need arbitrary URLs, resolve the host, block private and link-local ranges, and disable redirects.
7. Path traversal and file uploads
The mistake. A file name from the request is joined to a directory, and ../ climbs out of it. Or an uploaded file is stored somewhere it can be executed or served as HTML.
The fix. Never use user-supplied names as paths; generate your own (a GUID) and store the original name as data. If you must join paths, canonicalize and confirm the result still starts with the intended directory. Store uploads outside the web root, check the type by content, cap the size, and serve with Content-Disposition: attachment and X-Content-Type-Options: nosniff.
8. Security misconfiguration and information disclosure
- Swagger or API docs exposed in production. Handy for attackers mapping your API. Gate it to development or behind admin auth.
- Detailed error pages or stack traces in production.
- Missing security headers. Check yours with
curl -Ior securityheaders.com. - Default credentials, debug endpoints, verbose server banners.
- Secrets in the repository or in client-side JavaScript. Anything in the browser is public, including passwords for client-side gates.
9. Vulnerable dependencies
Run npm audit (Pulse FE/BE) and dotnet list package --vulnerable (TomiWebsites) regularly, and enable Dependabot or similar on GitHub. Pin versions and read changelogs for security fixes.
The architect's review checklist
Print this and run it on every new feature:
[ ] Every route has an explicit auth + role policy (default deny)
[ ] Every record lookup is scoped to the caller (or proven admin)
[ ] No string-built SQL / shell / templates
[ ] No Html.Raw / dangerouslySetInnerHTML / innerHTML on untrusted data
[ ] Cookie auth + cross-site? โ CSRF defense on every mutation
[ ] Rate limits keyed on trusted values (account + trusted IP)
[ ] Server-side fetches use fixed hosts
[ ] Uploads: generated names, outside web root, type + size checked
[ ] Secrets: none in code, app fails fast when missing
[ ] Errors: generic to users, detailed in logs
[ ] Tests: one per role per sensitive route
The Hacking Lab's Own code tab turns this checklist into missions against your local copies of Pulse, Maeve and TomiWebsites.