01 //What is a security code review? Start with a clear method
A security code review is a focused reading of code to find where a person or system can cross a security boundary it should not cross. Start with the change, name the asset at risk, trace attacker-controlled data to a sensitive operation, verify the control at that point, and record a testable finding. This method works for a pull request or a small existing feature.
You do not need to memorize every vulnerability class before you begin. You need a repeatable set of questions. In this guide, the running example is an invoice export endpoint; the final exercise is a report search. Use the supplied code or substitute a small change from your own project. Keep your notes as you go.
The review sequence at a glance
| Pass | Question | What to save |
|---|---|---|
| Scope | Who can act, and what asset is at risk? | Actor, asset, and security rule. |
| Trace | Where does untrusted data travel? | Source → decision → sink worksheet. |
| Verify | Which control enforces the rule? | Code evidence and a denied case. |
| Practice | Can the method find a real flaw? | A specific finding and safer fix. |
| Report | Can someone reproduce and resolve it? | Review comment and regression test. |
02 //How to scope a security review
Read the change description, changed files, nearby tests, route or job entry points, and the model or policy that defines access. Look one call upstream and one call downstream of the diff. A new helper may be safe while the caller passes an attacker-controlled ID; an unchanged helper may become dangerous when a new route exposes it.
- Actor: Who can trigger the change: an anonymous visitor, signed-in customer, tenant admin, background worker, or another service?
- Asset: What must remain protected: another customer’s invoice, a credential, an account balance, a private file, or a privileged action?
- Entry point: Where can the actor supply data: URL path, body, header, uploaded file, queue message, webhook, or stored record?
- Security rule: What must always be true? Example: “A customer may export only invoices belonging to their current tenant.”
- Affected component: Which route, service, query, renderer, configuration, and test enforce that rule?
Fast triage when the diff is large
| Look first at changes to… | Why they deserve attention |
|---|---|
| Authentication or access checks | They decide who may act and on which resource. |
| Queries, file paths, templates, and external calls | They are common places where untrusted data gains power. |
| Secrets, logs, errors, and exports | They can disclose data even when the main feature works. |
| Dependencies, permissions, and configuration | A small diff can change the runtime trust boundary. |
Pause and decide: A pull request adds GET /api/invoices/:invoiceId/export. Before reading the handler, what asset, actor, and security rule would you write down?
Reveal review notes
Asset: the invoice PDF and its customer data. Actor: any signed-in user who can call the route, including someone from a different tenant. Rule: the server must allow export only when that specific invoice belongs to the caller’s authorized tenant. Check whether the session’s tenant identity is established by trusted server code.
03 //How to trace untrusted data from source to sink
A source is a value an attacker can influence. A sink is an operation where that value can affect data, execution, access, or output. A trust boundary is the point where less-trusted input is accepted as authority or used by a more-privileged component. Stored values and third-party responses remain untrusted if an attacker could influence them earlier.
1const invoiceId = req.params.invoiceId; // source: caller chooses the ID
2const invoice = await db.invoice.findUnique({ where: { id: invoiceId } });
3if (!invoice) return res.sendStatus(404);
4const pdf = await renderInvoicePdf(invoice); // sensitive transformation
5return res.type('application/pdf').send(pdf); // sink: data leaves the serverDo not stop at the database call. Follow the returned object to the response, log, cache, file, or downstream API. Ask which statement proves the caller may perform this action on this object. In the trace above, the query proves that an invoice exists; it does not prove that the caller may export it.
Copy this source-to-sink worksheet into a review
| Question | Write down |
|---|---|
| What can the actor control? | Parameter, body field, header, stored value, or referenced object ID. |
| Where does it travel? | Parser → helper → query or policy → renderer or side effect. |
| What changes its trust level? | Authentication, field validation, object authorization, or none. |
| What is the sensitive operation? | Read/write, query, file path, HTML output, network request, or log. |
| What assumption could fail? | “Signed in means allowed”, “ID is secret”, “client validation ran”. |
| What test would disprove safety? | A second user, another tenant, malformed input, or a forbidden state. |
Trace exercise: Read the next route without looking for a vulnerability name. On paper, fill in all six rows of the worksheet: actor, controlled values, path through code, decision, sink, and a denial test. Assume requireSession only verifies that a user is signed in.
1router.post('/api/teams/:teamId/invites', requireSession, async (req, res) => {
2 const team = await db.team.findUnique({ where: { id: req.params.teamId } });
3 if (!team) return res.sendStatus(404);
4
5 await mailer.sendInvite({ to: req.body.email, teamName: team.name });
6 return res.sendStatus(204);
7});Pause and decide: Where does caller-controlled data gain authority, and what test would show the missing boundary?
Reveal review notes
The actor is any signed-in user. They control teamId and the invitee email. The route looks up a team by that ID and sends an invitation, but never verifies the caller may invite members to that team. The sensitive action is mailer.sendInvite. Test with a user who belongs to a different team and ensure the route denies the request and sends no email. Also check email validation and invitation abuse limits as separate review questions.
04 //Which security controls should a reviewer verify?
At each trust boundary, find the code that enforces the rule. Read the implementation or a test; a function name such as requireAuth is not evidence that object authorization happens. If a control lives in middleware, verify that this route actually uses it and that it checks the requested action and resource.
High-value questions at the decision point
| Boundary | Ask this | Evidence to look for |
|---|---|---|
| Identity and authorization | Who is the caller, and may they do this to this exact object? | Trusted session identity; server-side policy or tenant/owner predicate; denied cross-user test. |
| Input to query or command | Can input change syntax rather than remain data? | Typed bounds and parameter binding; no concatenation into SQL or shell commands. |
| Data to browser or file | What parser will consume this output? | Context-aware HTML encoding, safe template APIs, and controlled file paths or names. |
| Server to external service | Can input choose the destination or credentials? | Allowed destinations, scoped credentials, timeouts, and response validation. |
| State and abuse limits | Can a caller repeat, reorder, or race this operation? | State transition checks, atomic writes, quotas, and meaningful denial tests. |
Authentication says who the caller is. Authorization says whether that caller may perform this action on this object now. A signed-in user can still request another user’s invoice ID. The server must check the relationship or apply a query scoped to the caller’s authorized tenant. Hiding a button or guessing-resistant IDs cannot enforce that rule.
1// Unsafe: a caller-controlled value changes SQL syntax.
2const sql = "SELECT id FROM invoices WHERE id = '" + invoiceId + "'";
3await db.query(sql);
4
5// Safer: the value stays a bound parameter.
6await db.query('SELECT id FROM invoices WHERE id = $1', [invoiceId]);Parameter binding addresses SQL syntax injection in this example; it still does not authorize access to the invoice. Conversely, a tenant predicate does not make a concatenated query safe. Record each control separately so one green check cannot hide another gap.
Pause and decide: A route has requireSession and validates invoiceId as a UUID. Is that enough to export the invoice?
Reveal review notes
No. The session identifies the caller and UUID validation checks the ID’s shape. Neither proves the invoice belongs to an authorized tenant or that the caller has export permission. Look for the server-side object and action check before the PDF is produced or returned.
Pause and decide: For the invoice export, write three test cases before continuing: one allowed, one unauthenticated, and one authenticated but unauthorized. Which one most directly proves object authorization?
Reveal review notes
Allow Alice to export her tenant’s invoice. Deny a request without a session. Then sign in as Alice and request an existing invoice from Bob’s tenant; deny it and verify that no PDF is returned. The third case proves object authorization. The unauthenticated case proves only that login is required. A real test should create both invoices and tenants so an absent ID cannot accidentally pass.
05 //Worked security code review: an invoice export
Assume requireSession sets req.user from a verified server-side session. The product rule is: a user may export an invoice only from a tenant they belong to. Read the handler once for behavior, then again as a user from a different tenant who knows an invoice ID.
1router.get('/api/invoices/:invoiceId/export', requireSession, async (req, res) => {
2 const invoiceId = req.params.invoiceId;
3 const invoice = await db.invoice.findUnique({ where: { id: invoiceId } });
4 if (!invoice) return res.sendStatus(404);
5
6 logger.info('invoice exported', {
7 invoiceId,
8 userId: req.user.id,
9 customerEmail: invoice.customerEmail,
10 });
11 const pdf = await renderInvoicePdf(invoice);
12 return res.type('application/pdf').send(pdf);
13});Pause and decide: Identify the source, asset, missing decision, sensitive sink, and one additional data-handling concern before opening the notes.
Reveal review notes
- Source: the caller-controlled
invoiceIdpath parameter. - Asset: the invoice and PDF, including customer details.
- Missing decision: whether this user may export this invoice.
- Sink:
res.send(pdf)discloses the PDF. - Additional review question: does this audit event need the customer email, or can it be omitted?
The exploitable path is req.params.invoiceId → findUnique(id) → renderInvoicePdf → response. The failed assumption is “authenticated users may export any invoice they can name.” The fix must bind the requested invoice to a tenant proven to belong to the caller. Check the audit requirements before retaining customer email in the log; if it is not needed, omit it.
1router.get('/api/invoices/:invoiceId/export', requireSession, async (req, res) => {
2 const invoiceId = req.params.invoiceId;
3 // This helper checks membership using req.user.id from the verified session.
4 const tenantId = await getAuthorizedTenantForExport(req.user.id, invoiceId);
5 if (!tenantId) return res.sendStatus(404);
6
7 const invoice = await db.invoice.findFirst({
8 where: { id: invoiceId, tenantId },
9 });
10 if (!invoice) return res.sendStatus(404);
11
12 const pdf = await renderInvoicePdf(invoice);
13 logger.info('invoice exported', { invoiceId, userId: req.user.id });
14 return res.type('application/pdf').send(pdf);
15});Here getAuthorizedTenantForExport is a named policy boundary, not a magic fix: its implementation must verify current membership and export permission for this invoice. A simpler product may derive a trusted tenant ID from the session and scope the query by it. Review the helper and the query together, including what happens when membership changes.
1it('exports only an invoice in an authorized tenant', async () => {
2 const own = await request(app).get('/api/invoices/inv_a/export').set('Cookie', aliceCookie);
3 expect(own.status).toBe(200);
4
5 const other = await request(app).get('/api/invoices/inv_b/export').set('Cookie', aliceCookie);
6 expect(other.status).toBe(404); // inv_b exists, but belongs to another tenant
7});06 //Independent exercise: find two issues in a report search
Before opening the answer, review this route on your own. The product rule is that a signed-in user may search reports only in their current tenant. The route below is new. Name two distinct boundary failures, the evidence for each, and a test that would fail before the fix.
1router.get('/api/reports/search', requireSession, async (req, res) => {
2 const q = String(req.query.q ?? '');
3 if (q.length > 80) return res.sendStatus(400);
4
5 const sql = "SELECT id, title FROM reports WHERE title ILIKE '%" + q + "%'";
6 const reports = await db.query(sql);
7 return res.json(reports.rows);
8});Pause and decide: What two security rules are missing, and what evidence would you put in your review comment?
Reveal review notes
Finding 1 — SQL injection: q enters SQL syntax by string concatenation. A length limit does not keep quote characters or SQL operators out. Bind q as a parameter and test that SQL metacharacters cannot change the query’s structure.
Finding 2 — cross-tenant disclosure: the query has no tenant predicate. A signed-in user can receive report titles from other tenants. Scope the query to a tenant established by the server and test with two tenants, where the other tenant has a matching title.
1const q = String(req.query.q ?? '');
2if (q.length > 80) return res.sendStatus(400);
3
4const reports = await db.query(
5 "SELECT id, title FROM reports " +
6 "WHERE tenant_id = $1 AND title ILIKE '%' || $2 || '%' LIMIT 50",
7 [req.user.tenantId, q]
8);
9return res.json(reports.rows);The parameter keeps input out of SQL syntax, the tenant predicate limits which rows can leave, and the limit caps the response. If users expect % and _ to be literal characters, escape SQL LIKE wildcards as a separate product requirement. The session’s tenant ID must be derived from trusted server state, not an unverified request field.
07 //Security code review checklist and finding template
Turn observations into a review someone can act on. For each checked item, write the file or test that supplies evidence. “No issue found” means you inspected the boundary in scope; it does not certify the whole application.
- ☐ I can name the actor, asset, requested action, and rule that should hold.
- ☐ I found every new entry point and the nearby unchanged code it calls.
- ☐ I traced each attacker-controlled value to a query, file, output, log, or external call.
- ☐ Authentication is enforced by trusted server code where required.
- ☐ Authorization covers the exact action and object, including cross-user and cross-tenant cases.
- ☐ Input is bounded and parsed for its expected type; SQL and commands keep values as data.
- ☐ Browser output uses a safe API or encoding appropriate to its context.
- ☐ Secrets and sensitive personal data do not leak through logs, errors, responses, or caches.
- ☐ External destinations and credentials are constrained to what the feature needs.
- ☐ State changes, quotas, and concurrency cannot bypass the business rule.
- ☐ Dependency, permission, and configuration changes were examined with their lockfiles or manifests.
- ☐ Tests cover both allowed behavior and a realistic denied or adversarial case.
1Finding: [specific boundary failure] in [file/function]
2Evidence: [attacker-controlled source] reaches [sensitive action] without [control]
3Impact: [who can do what to whose data or system]
4Suggested fix: [where to enforce the rule, including the safe API or policy]
5Verification: [allowed case] succeeds; [denied/adversarial case] fails
6Confidence / open question: [what you verified, and what still needs checking]Example: “In the export handler, invoiceId from the URL reaches findUnique(id) and the PDF response without checking tenant membership. A signed-in user who knows another tenant’s invoice ID could download that invoice. Please scope the lookup to a server-verified tenant and add a two-tenant denial test.” That is more useful than “possible IDOR.”
Close the review with a clear decision
| Decision | When it fits |
|---|---|
| Request changes | You have a credible, reproducible boundary failure with a practical fix. |
| Ask a focused question | The policy or upstream control may exist, but you cannot verify it from this change. |
| Approve within scope | The relevant controls and denied cases are evidenced; record the scope you checked. |
| Escalate | Potential exposure is urgent or spans services; follow your team’s incident or security process. |
For deeper practice, continue with object-level access control, SQL injection, and the secure coding checklist. This method follows the OWASP Secure Code Review Cheat Sheet, with supporting guidance from OWASP on threat modeling, authorization, input validation, and logging. For dependency changes, see GitHub’s dependency review guidance.