Introduction to Secure Code Review
Learn what secure code review is, how it differs from functional review, how vulnerabilities reach production, and how to document a useful finding.
Secure code review checks whether an actor can make the application violate a security rule. Start with a concrete promise, follow the inputs and authority behind it, and collect enough evidence to explain a failure and verify a fix.
You will use a report-search feature to practise the method, then transfer it to an independent SQL injection case.
What you will learn
- State a testable security rule for a feature.
- Trace caller-controlled input to a sensitive operation.
- Separate a suspicious pattern from a supported finding.
- Explain the root cause, impact, fix, and regression test.
What is secure code review?
A functional review asks whether the code implements the intended feature. Does a report endpoint return the right fields? Are errors handled? Is the change readable, tested, and consistent with the surrounding design? A security review asks an additional set of questions: who can invoke the endpoint, what data can that person influence, which data or capability must remain protected, and what prevents a caller from crossing that boundary?
The same line of code can pass a functional test and still be insecure. A report search that returns the expected rows for an ordinary search term may also allow a crafted term to change the database query itself.
Security review is therefore a form of adversarial reasoning grounded in implementation evidence. "Adversarial" does not mean assuming every developer is careless or that every input is malicious. It means testing a security rule against a caller who is willing to choose unusual values, call a route directly, repeat requests, or act from a different account or tenant.
The reviewer also checks conditions that may arise accidentally: stale sessions, unexpected null values, a trusted helper reused in a new context, or a record written by an external integration. The goal is to uncover conditions under which a promise the product makes to users is false.
Consider a simple product promise: "A signed-in customer can download only their own invoices." The feature can be functionally correct for one customer while violating that promise for another. A test that creates an invoice and downloads it as its owner shows a happy path. The security test creates two customers and asks whether one can name the other's invoice. The distinction is the object of the review: functionality proves that an operation works; security examines where its authority comes from and where it stops.
This distinction does not create two separate codebases or two completely separate review rituals. Both reviews need to understand the feature, its contracts, and its tests. Security review adds explicit actors, assets, boundaries, and denial cases. It is most effective when the reviewer can read enough surrounding code to understand how the feature behaves beyond the changed lines.
A controller may call a helper whose name suggests authorization, but only the helper implementation tells you whether it checks the requested object. A database query may be prepared in a repository file, while a route builds its SQL fragment several calls earlier. A security conclusion based on a single line can therefore be wrong in either direction.
The five pieces of a useful security question
Before examining a vulnerable line, write down five pieces of context. They turn a broad instruction like "look for security bugs" into a question you can answer.
| Piece | Question | Example |
|---|---|---|
| Actor | Who can initiate the action? | An authenticated customer, including one from a different organization. |
| Asset | What should remain protected? | Private invoice data and the ability to export it. |
| Entry point | How can the actor supply or select a value? | The invoice ID in a URL, a search term, or a stored report name. |
| Security rule | What must always be true? | The requested invoice belongs to the caller's authorized organization. |
| Trust boundary | Where is a less trusted value granted authority? | The point where the server uses an ID in a privileged database read or response. |
Write the rule as a statement that can be disproved. "The route is secure" is not a rule. "A customer cannot retrieve an invoice owned by another tenant, even when they know its ID" is. Specific rules point to specific tests. They also help you distinguish one finding from a collection of unrelated concerns.
In the example, validating that the ID is a well-formed string does not establish that the caller is allowed to use it. The missing ownership condition, if present, is a different problem from malformed input.
Select each stage to inspect the evidence. Keep the caller’s control in view as the value changes names.
Request. The instructor chooses title. Login establishes the actor’s identity; it does not make the search term safe.
const title = String(req.query.title ?? '').trim();
Service. Adding wildcard characters changes the search pattern. Neither trim nor interpolation establishes a SQL boundary.
const pattern = `%${title}%`;
return searchReports(instructor.id, pattern);
Repository. Here the value is inserted into SQL text. This is the point to compare the intended security rule with the actual implementation.
const sql = `SELECT * FROM reports
WHERE title ILIKE '${pattern}'`;
Database. The driver executes the assembled statement. Confirm how it receives the query, then describe the impact supported by the code.
return pool.query(sql);
Review question: Which operation must preserve the difference between query structure and caller-controlled data?
How vulnerabilities reach production despite reviews and tests
Most flaws do not require a spectacular mistake. They emerge when a true assumption in one part of a system stops being true in another. A service function written for a trusted internal job may later be exposed to an HTTP route. A UI may hide a button, creating the false impression that the backend action is unavailable to unauthorized users.
A query helper may accept a string because every initial caller supplied a constant; a new caller passes a URL parameter. A framework may escape text in its default rendering path, but a later feature opts into raw HTML. A test suite may assert only the expected success result, never the denied case.
The route from change to incident often contains several opportunities to catch a flaw:
- Requirement and design. The feature description may omit a security rule, such as who may view a report. Engineers cannot implement a rule that was never stated. Reviewers can ask for the rule before discussing code.
- Implementation. The feature may enforce a rule in the browser but not on the server, or may validate a value without constraining the operation it controls.
- Integration. A secure-looking helper may be called with the wrong identity, tenant context, or data type. The security property of a component depends on how it is used.
- Testing. A success test may pass even when a second user can make the same request. Denial and boundary tests expose behavior that happy-path tests do not.
- Deployment and operation. Configuration, credentials, logging, caching, and access to downstream systems can change the effective boundary. A least-privileged database user limits damage but does not repair an injectable query.
These stages explain why neither a static scanner nor a single human review guarantees safety. A scanner can identify a risky call, but it may lack the product context needed to know whether a particular actor can reach it. A human can understand the rule, but may miss a long data path or a rare encoding. Security review is one control in a development process that also needs secure design, testing, remediation, and maintenance.
NIST's Secure Software Development Framework organizes secure development as a set of practices across the software lifecycle; the OWASP Application Security Verification Standard gives teams concrete security requirements to verify. Neither removes the need to examine the actual implementation.
A realistic change-review scenario
Imagine a team adds search to an internal course reporting tool. The feature request says, "Allow instructors to filter student reports by title." A functional reviewer sees a route, a database call, and a test showing that searching for network returns reports whose titles contain that word. The UI presents a text field and the API returns JSON. Nothing in the success test demonstrates what happens when a user supplies database syntax.
The feature may still look complete because an ordinary value exercises the desired behavior.
The security reviewer starts by asking whether the search term can affect query structure or only query data. That is a different question from whether the search works. The reviewer then looks at where the route obtains the term, how the service transforms it, and how the database driver receives the query.
If the application concatenates the term into SQL text, the query parser can interpret parts of the term as SQL rather than as a literal title value. If the application uses a parameterized query, the driver separates the value from the SQL structure. This is the central distinction emphasized by the OWASP SQL Injection Prevention Cheat Sheet and CWE-89.
This lecture will work through a small, invented version of that scenario. Do not assume that the live challenge uses the same files, language, or vulnerable statement. The practice challenge is for transferring the method to unfamiliar code.
The route requires an instructor session. Which security question is still unanswered?
A repeatable review method: scope, trace, verify, report
A reviewer can be thorough without starting every review from a blank page. Use four passes. They are not a rigid checklist that proves a feature safe. They are a way to keep evidence and uncertainty visible.
Scope the feature and its security rule. Read the request, route or job entry point, related tests, and the downstream operation. Name the actor and asset. If the feature has several actors or assets, write more than one rule. For example, a teacher may read class reports but not change student grades; a student may read only their own report. Do not collapse these into "authenticated users can access reports."
Trace attacker-influenced values. Start with request fields, headers, path parameters, uploaded files, session claims, stored records, webhooks, or queue messages. Follow transformations and helper calls until the value reaches a sensitive action. For each step, note whether the code checks shape, identity, authorization, or output context. A value remains attacker-influenced after trimming, parsing, storing, or retrieving it if an attacker could choose its content earlier.
Verify the boundary. Locate the exact code that enforces the security rule. A function name is not enough. A comment is not enough. A frontend restriction is not enough for a server action. For an injection concern, inspect how the parser receives data and syntax. For an authorization concern, inspect whether the policy uses a trusted actor identity and the requested object.
For a suspected leak, inspect what the response or log actually contains and who can receive it. Look for tests or create a bounded, safe reproduction in an authorized environment.
Report the finding in terms of cause and consequence. Include the relevant path through code, the attacker-controlled value, the violated rule, the reachable operation, realistic prerequisites, and a specific fix. Recommend a regression test that would fail before the fix and pass after it. If evidence is incomplete, say so. "Potential injection; need to confirm whether this API uses prepared parameters" is more useful than claiming a confirmed remote compromise without seeing how the driver executes the query.
What to write in a review notebook
Use a short source-to-result worksheet as you read. You can put it in a comment, a private note, or a review tool:
Actor: instructor account with access to the report search route
Asset: student report records in the application database
Entry point: GET /reports?title=...
Controlled value: query parameter `title`
Transformations: trim, then surround with wildcard characters
Sensitive action: database executes a SELECT query
Expected rule: title is only a search value; it cannot change SQL structure
Evidence: route -> service -> query; SQL assembled with string interpolation
Denied case: a crafted title must remain a literal value, not alter the predicate
Fix candidate: parameter binding; allowlist any dynamic identifier separately
Unknowns: database permissions, query limits, and production exposure
The worksheet deliberately separates evidence from unknowns. If you have not confirmed how a helper invokes the database driver, label that gap. If you do not know whether the route is public, avoid claiming anonymous reachability. If the database account has only read permissions, do not claim that an attacker can modify records. A trustworthy finding says what the code supports and what still needs checking.
Keep search values separate from SQL
Before revealing the fix, identify what the database receives in each version: one assembled string, or fixed SQL plus separate values?
const sql = `SELECT id, title FROM reports
WHERE instructor_id = '${instructor.id}'
AND title ILIKE '%${title}%'`;
const result = await pool.query(sql);
Reveal the safer implementation
const result = await pool.query(
`SELECT id, title FROM reports
WHERE instructor_id = $1 AND title ILIKE $2`,
[instructor.id, `%${title}%`]
);
The statement structure is fixed. The instructor identity and title pattern are supplied separately as values. This addresses SQL injection; the instructor predicate must still express the correct ownership policy.
Worked example: review a report search across three files
Read the following example as if you are reviewing a feature. It is intentionally small enough to fit on this page, but its separation across a route, service, and repository mirrors a real application. First, identify the actor, source, and sink without reading the analysis below.
routes/reportSearch.ts
import { Router } from 'express';
import { requireInstructor } from '../auth/requireInstructor';
import { findReports } from '../services/reportSearch';
export const reportsRouter = Router();
reportsRouter.get('/reports', requireInstructor, async (req, res) => {
const title = String(req.query.title ?? '').trim();
const rows = await findReports(req.instructor.id, title);
res.json({ reports: rows });
});
services/reportSearch.ts
import { searchReports } from '../storage/reportRepository';
export async function findReports(instructorId: string, title: string) {
const searchPattern = `%${title}%`;
return searchReports(instructorId, searchPattern);
}
storage/reportRepository.ts
import { pool } from './database';
export async function searchReports(instructorId: string, pattern: string) {
const sql = `SELECT id, title, summary
FROM reports
WHERE instructor_id = '${instructorId}'
AND title ILIKE '${pattern}'
ORDER BY created_at DESC`;
const result = await pool.query(sql);
return result.rows;
}
The route authenticates an instructor. That is useful, but authentication does not make the title value trustworthy. The instructor still chooses the query parameter. String(...) converts a value to text; it does not stop database metacharacters from having meaning later. trim() removes surrounding whitespace; it does not separate data from SQL syntax.
The service adds % wildcards to support substring search; those wildcards change the intended value of the search pattern but do not make it safe to interpolate into SQL. The repository finally assembles a statement by placing both instructorId and pattern inside quote-delimited SQL text.
The title search term is the obvious source. The pool.query(sql) call is the sensitive operation, although the important failure occurs earlier when pattern becomes part of the SQL string. The trust boundary is crossed when application data is treated as query language. The caller can influence a region of SQL text that the database parser will interpret.
The instructor ID is derived from a server-side authentication object and may be harder for the caller to choose, but interpolating it is still an unsafe pattern because the helper can be reused or the identity source can change. A safe implementation binds both values.
What can the reviewer conclude? The code has a SQL injection weakness in the title path because user-controlled text is interpolated into SQL. The exact impact depends on the database dialect, driver behavior, permissions, data, and surrounding controls. It would be careless to assert that this snippet by itself proves the ability to execute multiple statements or modify every table.
The evidence is sufficient to demand a parameterized query and a regression test that treats suspicious input as a literal search term. It is also reasonable to inspect whether any caller can reach searchReports without requireInstructor and whether instructorId is always a trusted value.
The corrected boundary
With the PostgreSQL-style parameter placeholders used by node-postgres, the repository can preserve SQL structure while supplying values separately:
export async function searchReports(instructorId: string, pattern: string) {
const result = await pool.query(
`SELECT id, title, summary
FROM reports
WHERE instructor_id = $1
AND title ILIKE $2
ORDER BY created_at DESC`,
[instructorId, pattern]
);
return result.rows;
}
The SQL parser sees the fixed statement and the driver supplies instructorId and pattern as values. A title containing quote characters or SQL-looking text stays a search value. Parameter binding is the relevant control here; trying to remove a list of suspicious characters is not a dependable substitute. An allowlist can be appropriate when a user selects a SQL identifier such as a permitted sort column, because identifiers often cannot be bound as ordinary values.
In that case, the application should map a small set of accepted choices to fixed SQL fragments rather than copying the caller's text. The two cases have different safe designs: values are bound; structural choices are mapped to known constants.
const sortColumns = {
newest: 'created_at DESC',
oldest: 'created_at ASC',
} as const;
const chosenSort = req.query.sort === 'oldest' ? sortColumns.oldest : sortColumns.newest;
// chosenSort is selected from a fixed server-owned set, not interpolated user text.
const sql = `SELECT id, title FROM reports WHERE instructor_id = $1
ORDER BY ${chosenSort}`;
await pool.query(sql, [req.instructor.id]);
Even a parameterized query is only part of the security story. If instructors should see only their own reports, the server-owned instructorId predicate must reflect the correct principal. If users can select another organization's reports through a separate route, binding values will not repair that authorization failure. Security controls are specific to a boundary. Treating parameterization as a universal "secure query" label can hide other defects.
A regression test worth keeping
The useful test does not merely assert that a query returns rows. It checks that the unsafe input remains data and that the expected scope remains intact:
it('treats a quote-bearing title as a literal search value', async () => {
await seedReport({ instructorId: 'inst-a', title: "Budget's final draft" });
await seedReport({ instructorId: 'inst-b', title: 'Private notes' });
const response = await request(app)
.get('/reports')
.set('Authorization', instructorSession('inst-a'))
.query({ title: "Budget's" });
expect(response.status).toBe(200);
expect(response.body.reports.map((report: { title: string }) => report.title)).toEqual([
"Budget's final draft",
]);
});
This is illustrative test code, not a drop-in test for every framework. Its security value is the assertion about the boundary: the caller's search term retains literal meaning, and another instructor's row does not appear. The test still needs surrounding test helpers and a database fixture. A reviewer should ask whether the application's real test suite has an equivalent denial or literal-value case.
How to decide whether a suspicious pattern is exploitable
Security review begins with suspicion, but findings require a reachable path. A string interpolation in a query helper is strong evidence of a dangerous pattern. A report becomes stronger when the reviewer can show an untrusted source reaches that helper, the query executes under realistic conditions, and no prior control constrains the value to a safe fixed set. Reaching that conclusion may require reading callers, middleware, type conversions, and database adapter behavior.
It may also require an authorized test environment to observe how the driver handles the value. Do not use a production system or another person's account to test a hypothesis without permission.
Several questions help separate a useful finding from an untested hunch:
- Can the actor control the value? Trace back to the route, stored record, webhook, job message, or other source. A constant string chosen by the server is a different risk from a query parameter.
- Can the actor reach the code path? Look at routing, feature flags, authentication, and branch conditions. A private helper may become reachable through an unexpected caller.
- Does a control act before the sensitive use? A parser that converts input to a bounded integer may change the possible values. A browser-only check does not constrain a direct HTTP request.
- What does the receiving interpreter do? SQL drivers, HTML parsers, shells, template engines, and file systems interpret values differently. Identify the actual sink and context.
- What is the smallest believable impact? A wrong row set or unauthorized read may be demonstrable even when a broader compromise is not. Do not overstate the result to make it sound important.
A positive signal on one of these questions does not answer all the others. For example, seeing req.query.title proves caller influence but not that the value reaches a database operation. Seeing pool.query proves a database operation but not that the actor can alter the SQL. The complete trace ties them together. This habit transfers to other vulnerability classes throughout the course.
False positives and false negatives
A false positive is a reported issue that does not violate the proposed rule under the actual conditions. A scanner might flag interpolation in a SQL construction site even when the inserted fragment is chosen solely from a fixed, server-owned map. A reviewer might see an object lookup by ID and miss an authorization predicate applied inside the repository. The correct response is to follow evidence and adjust the claim, not to dismiss all similar findings.
A false negative is a flaw the review fails to identify. It can arise because the reviewer inspects only the route and never reaches a helper, because a stored value was incorrectly treated as trusted, or because the test data contains only one tenant. The countermeasure is not infinite review time. It is a method that deliberately follows sources to sinks, records assumptions, and adds denial cases for important rules.
Chapter 2 will make the multi-file trace more systematic; chapter 3 will deepen the source-to-sink model.
The reviewer's responsibilities and limits
A reviewer is responsible for providing a clear security hypothesis, reading enough code to validate it, recording uncertainty, and helping the team arrive at a safer implementation. That includes checking the proposed fix, not merely naming a weakness. A comment like "SQL injection here" may be directionally correct, but it does not tell a maintainer where the untrusted value enters, what query executes, or which change would preserve the intended search behavior.
A better comment connects the route to the sink and proposes binding the value. A still better review also identifies a test that prevents recurrence.
The reviewer is not responsible for claiming absolute security of an entire product. A review is bounded by scope, access, and time. If you cannot inspect the called service or the deployed database configuration, say which conclusion depends on that missing evidence. If a code sample omits middleware or database details, avoid inventing them.
If you find a vulnerability, report it through the project's normal security process and avoid publishing an exploit before maintainers can respond. The appropriate response to a severe issue may include a private escalation, a temporary mitigation, and a permanent fix. The communication path depends on the organization and the issue.
The reviewer also has a responsibility to keep the review useful to developers. Describe the failing security invariant without attributing motives. Distinguish root cause from symptom: "a user-controlled search term is included in SQL text" is more precise than "the route is bad." Give a fix at the right layer: binding at the query boundary is better than relying on a UI filter that can be bypassed.
Check that the fix preserves the feature's intended behavior and does not introduce a new issue. Use examples with synthetic data when sharing a report, so private customer data does not appear in screenshots or comments.
A finding template you can reuse
Title: User-controlled report title changes the SQL statement
Rule: An instructor's title filter must remain query data, not SQL syntax.
Actor and prerequisite: An instructor who can call GET /reports.
Evidence: routes/reportSearch.ts reads req.query.title; the service adds
wildcards; storage/reportRepository.ts interpolates the resulting pattern
into a SQL string passed to pool.query.
Impact: The query may return unintended data or fail in attacker-chosen ways.
The exact scope depends on database permissions and driver behavior.
Fix: Keep SQL text fixed and bind both instructor ID and search pattern.
Regression test: A quote-bearing title is searched literally and cannot
expand the result set beyond the instructor's authorized reports.
The template starts with the security rule and observable code path. It avoids inventing a payload or making claims about unavailable infrastructure. In a real report, include file and line references, a bounded reproduction where authorized, and the actual response or test result. A maintainer should be able to validate your claim from the evidence rather than trust your confidence.
You found user input interpolated into an executed query. What is the strongest finding you can support without seeing the database permissions?
Practice: conduct a first review before seeing the notes
Read this new example without looking ahead. An internal application lets a signed-in analyst search incident notes by tag. The policy says an analyst may read notes for their own organization. The code below is intentionally incomplete; your job is to state what you can prove and what you need to inspect next.
router.get('/incident-notes', requireSession, async (req, res) => {
const tag = String(req.query.tag ?? '');
const notes = await noteService.findByTag(req.session.orgId, tag);
res.json({ notes });
});
export async function findByTag(orgId: string, tag: string) {
return notesRepository.search({ orgId, tag: tag.toLowerCase() });
}
export async function search(filters: { orgId: string; tag: string }) {
const sql = `SELECT id, title FROM incident_notes
WHERE org_id = $1 AND tag = $2`;
return (await pool.query(sql, [filters.orgId, filters.tag])).rows;
}
Write down the actor, asset, two possible sources, the sensitive operation, and the evidence for or against SQL injection in tag. Then answer these questions:
- Does converting
tagto lowercase make it trustworthy? - Is the repository's query structure influenced by
tag? - Which assumption about
req.session.orgIdshould you verify before claiming that the organization boundary is enforced? - What would a good denial test do with two analyst accounts?
Compare your reasoning
The actor is a signed-in analyst. The asset is the incident-note collection, including notes belonging to another organization. The tag query parameter is caller-controlled. The session's organization ID is a second important input, but whether the caller can alter it depends on how requireSession constructs and validates the session. The repository uses a fixed SQL statement with value placeholders, so this code does not show SQL injection through tag.
Lowercasing is a normalization step, not a security boundary. A denial test would create notes for two organizations, sign in as an analyst from one, and verify that a request cannot return the other's notes. Before claiming the organization rule is enforced, inspect the session middleware and the database query as used in production, including any other callers of the repository.
This exercise illustrates an important reviewer skill: a sound review can conclude that one suspected vulnerability is not present in the shown path while identifying a different assumption to verify. Avoid the pressure to label every example vulnerable. The objective is a defensible explanation.
A deeper review drill: turn a suspicious diff into evidence
Imagine that the report-search change arrives as a pull request with only the route and service files visible in the diff. The repository function already exists. A rushed reviewer could approve because the route requires an instructor session and the service has a descriptive name. A careful reviewer asks what the change makes reachable, then opens the implementation of every called function that participates in the security rule. The diff is the starting point of the investigation, not its boundary.
Work through the following sequence as though you had fifteen minutes to review the change. First, write the behavior promised by the feature: an instructor can find reports by title within the reports they are allowed to see. Then separate that promise into two independent rules. The query-integrity rule says that a title is a search value and must not change SQL grammar. The access rule says that the caller cannot obtain another instructor's report.
A fix for either rule does not prove the other. This separation helps you avoid a single vague finding called "insecure search" that leaves engineers unsure what to change or test.
Next, inventory the points where the caller has influence. The title query parameter is directly chosen by the caller. The session's instructor ID is issued by the server, but the caller can choose which account to sign in with; a compromised or wrongly constructed session could matter to impact. The caller may also choose request timing and repetition. This does not mean every value is equally untrusted.
It means the review needs to state precisely which value can cross which boundary. For SQL injection, the directly chosen title is enough to establish a high-priority trace. For tenant isolation, the account identity and report ownership determine the relevant comparison.
At the route, String(req.query.title ?? '') may look reassuring because it prevents a non-string value from reaching the service. It is an input-shape conversion, not a query-integrity control. At the service, %${title}% changes a value for substring matching. It does not prevent an embedded quote from becoming part of a SQL literal if the repository later constructs SQL text. The reviewer must reach the repository and identify the exact handoff to pool.query.
This is the point where an observation becomes an evidence-backed claim: the query text itself depends on a caller-selected string. A reviewer who stops at the service can only say "check how the repository handles this pattern."
Now assess reachability and limits. requireInstructor shows that the route has an authentication gate, but the code shown does not establish whether all instructors may access it or whether a separate policy limits the route. The repository does not show database grants, statement timeouts, or the driver configuration. Those unknowns matter to the extent of impact; they do not turn unsafe SQL assembly into safe code.
Report what the snippet supports: an authenticated instructor can submit a title that is inserted into SQL text. Avoid claiming that this necessarily permits stacked statements, record modification, or access to every table. Those claims need evidence from the actual environment.
Finally, propose a fix with a testable outcome. Parameter binding makes the title a value. The authorized instructor predicate should remain in the query and use a server-derived identity. A good regression test stores a title with punctuation, sends that title as a query value, and proves that the result is treated literally. A second test signs in as another instructor and checks that cross-owner rows remain absent. These tests target two rules and will tell maintainers exactly which boundary a future edit broke.
What changes when the code looks safer?
Suppose the repository instead calls pool.query('SELECT ... WHERE title ILIKE $1', [pattern]). The original SQL injection claim would no longer be supported for that value position. The reviewer should update the conclusion, not cling to the first hypothesis. The search may still have other risks: a user could request an expensive wildcard search repeatedly, the query might omit an ownership predicate, or the output might expose private fields. Those concerns require their own evidence.
Reviewers are most useful when they can eliminate a suspected finding as confidently as they can confirm one.
Suppose the route uses a helper called sanitizeSearchTerm() before the repository. The name alone changes nothing. Open the helper. If it only removes apostrophes, it may break legitimate report titles and still leave other SQL syntax or encodings to consider. If it returns a tightly validated enum used only to choose a fixed query branch, that could be a meaningful control for that narrow decision.
If it is a library function that binds parameters through the driver, verify how it is invoked. The question is always what property the code establishes at the sink, not whether a security-sounding function appears upstream.
Suppose the same repository method is called by an internal nightly job that supplies a fixed title. That caller alone may not make the function exploitable, but the HTTP route now gives it a new source. Security review of a change should consider the old helper's behavior under the new caller. Conversely, if the route cannot be reached in the deployed product, the immediate exploitability claim changes.
Ask for deployment evidence rather than assuming the development route is public. Keep the code defect and the reachability assessment distinct.
How to make a finding useful to the team
A finding is a compact explanation of a broken rule. It should let an engineer locate the root cause, understand why ordinary tests missed it, implement the right control, and verify the repair. A useful title names the behavior, such as "Report title is interpolated into an SQL query." A title such as "SQLi everywhere" overstates evidence and provides little location information. The body should identify the route, actor, source, transformation, and sink.
It should say what the application is expected to prevent. It should describe a realistic consequence without inventing a maximum-impact exploit.
Separate observed evidence, inference, and open questions. "The route reads req.query.title" and "the repository interpolates pattern into a SQL string" are observations from code. "An instructor can influence the query structure" is an inference supported by those observations and the call path. "The database account can read unrelated tables" is an open question until permissions are checked. This discipline matters during triage: engineers can reproduce the specific issue while security and product owners assess severity using facts about deployment, access, and data sensitivity.
The proposed repair should address the root cause at the boundary. A suggestion to hide the search field or block quote characters in the browser leaves direct API requests and other SQL syntax paths. A suggestion to use parameter binding is concrete for value positions. If the query also needs a user-selectable sort field, give a separate allowlist mapping for that structural choice.
Document any follow-up tests: literal handling of punctuation, denial of cross-owner access, and expected results for an empty or very long search. Functional and security tests can coexist in one suite, but each assertion should have a clear purpose.
Review comments also need proportion. A confirmed injection path deserves a direct blocking comment with the evidence and fix. A possible issue in an uninspected helper should be phrased as a question or investigation item. An unrelated naming preference should not be framed as a vulnerability. The reviewer is responsible for helping the team allocate attention, so accuracy and specificity matter as much as finding volume.
If a design decision is unresolved, state the security rule the team must choose: for example, whether instructors may search only their own reports or all reports in a shared organization. Code cannot be judged against an unstated access policy.
Practice: write the review comment
Without returning to the worked analysis, write a four-sentence review comment for the insecure searchReports function. Sentence one should identify the controllable title and the route that supplies it. Sentence two should point to the SQL assembly and explain why trimming and wildcard wrapping do not preserve query structure. Sentence three should state the supported impact with the authenticated-instructor prerequisite.
Sentence four should request parameter binding and a regression test that treats a quote-bearing title as data. Then write a separate one-sentence question about whether instructors may see each other's reports. Keeping that policy question separate will make the review easier to resolve.
Review notes: A strong answer names the source-to-sink call chain and does not claim database-wide control without evidence. It requests a change at the database boundary and gives a test that would fail under the insecure construction. The ownership question remains open until the product rule and the actual query predicate are checked. If your comment merely says "sanitize input," revise it to identify the exact property needed: the SQL parser must never interpret title characters as query syntax.
A first-review checklist
Use the checklist after you understand the feature, not as a substitute for understanding it. Each item asks for evidence:
- I can name the actor and distinguish the privileges of at least one lower-privileged actor.
- I can name the asset and state the intended security rule in a form a test could falsify.
- I found the server-side entry point, not only the UI that calls it.
- I traced at least one attacker-influenced value through the relevant helpers to a sensitive operation.
- I identified the exact code that enforces or fails to enforce the rule at that operation.
- I separated shape validation, authentication, authorization, and safe output or query construction.
- I checked a negative or denial case, or noted why it has not been tested yet.
- My impact statement follows from the code and does not assume unavailable deployment facts.
- My suggested fix addresses the failing boundary and includes a regression test.
- My report gives the maintainer enough context to reproduce and verify the result.
Which regression test best protects the intended boundary?
Apply the method to a Code Review Lab challenge
Open the free SQL injection code review challenge. Your task is to find the SQL injection. Before selecting a vulnerable line, write a five-line trace in your own words: the actor, the user-controlled source, any transformation, the SQL construction or execution sink, and the exact point where data could gain the power to change query structure. Then identify a fix that preserves the intended feature.
Do not guess from the title or search only for a familiar keyword. Follow the value through the code shown in the challenge.
The lecture does not reveal the challenge's answer. If you need a refresher while working, return to the distinction between a fixed query with bound values and a query assembled from caller-controlled text. Once you have a candidate, test your explanation against the code path: could the actor actually supply that value, and does it reach the database operation in the form you claim? Keep your trace as a model for the distinct code review cases in later topics.
Key terms
- Actor: A person or system that can initiate an operation; a security review usually considers the least-privileged actor who can reach it.
- Asset: Data, capability, or service behavior the application must protect.
- Entry point: The route, message handler, job, file import, or other place where an actor can introduce or select input.
- Security rule or invariant: A statement about what must remain true for all relevant requests, including denied cases.
- Source: A value an actor can influence, directly or indirectly.
- Sink: An operation where a value can affect data, execution, access, output, or another sensitive result.
- Trust boundary: A point where less-trusted information is accepted by a component with more authority or interpreted in a security-sensitive context.
- Parameter binding: Supplying SQL values separately from fixed SQL text so the database treats them as data.
- Finding: A testable statement of the failing rule, reachable code path, impact, and corrective action.
Frequently asked questions
Is secure code review the same as a penetration test?
No. Code review begins with implementation and can trace paths that are difficult to observe from outside. Penetration testing exercises a running system and can reveal behavior that source review misses. Both can provide evidence for a security rule, and neither proves that every possible flaw has been found. A code reviewer may use an authorized running test to confirm a hypothesis, but the starting material and scope differ.
Do I need to know every vulnerability name before reviewing code?
No. Start with actors, assets, trust boundaries, and operations. Vulnerability names help communicate a confirmed pattern, but looking only for a name can miss an unfamiliar route or an unexpected combination of conditions. The source-to-sink trace provides a method that transfers across SQL injection, cross-site scripting, authorization mistakes, file access, and other classes.
Does an authenticated route make its inputs trusted?
No. Authentication establishes an identity according to the session implementation. It does not make the person's query parameters, uploaded files, stored content, or selected object IDs safe to use as authority or syntax. A signed-in user may still choose harmful values or request another person's resource.
If I cannot reproduce an exploit, should I report the code pattern?
Report what you can support. If the code clearly joins user input into a SQL statement, explain that path and the relevant uncertainty. If reachability or driver behavior is unknown, state the unknown and propose a bounded validation step. Do not claim a broader outcome than the evidence supports. A precise hypothesis is useful; an exaggerated conclusion makes remediation harder.
Primary references and next lesson
- OWASP Application Security Verification Standard provides concrete requirements for secure web application design and verification.
- OWASP SQL Injection Prevention Cheat Sheet explains parameterized queries and why input escaping is a weak primary defense.
- MITRE CWE-89 describes improper neutralization of special elements in SQL commands.
- NIST Secure Software Development Framework, SP 800-218 puts secure review within a wider software-development process.
Continue with Understanding Application Architecture to learn how to follow a request across frontend, route, middleware, service, and database code without losing the security rule.