Your First Complete Security Review
Scope a code review, confirm the root cause and exploitability, communicate impact, propose a fix, and practise on three complete cases.
A complete security code review produces a defensible conclusion, a useful finding when a rule fails, and evidence that the fix restores the rule. It connects scope, architecture, data flow, authorization, testing, and communication.
Review Cedar Desk’s invoice search from the first security question to the retest. Then complete three independent Code Review Lab cases with your own review notes.
Learning objectives and reading plan
- Define the scope and security rules before investigating.
- Trace and confirm the vulnerable behavior with synthetic evidence.
- Write a bounded finding and propose a fix at the root cause.
- Retest the denied and allowed behavior, then complete three cases.
What a complete security review includes
A complete review is complete relative to an agreed scope, not relative to every possible weakness in a product. You may examine one endpoint, one feature, one release diff, or a whole service. Say which. A review of invoice search cannot establish that password recovery is secure. A review of a single controller cannot establish that its repository query is safe. The boundary determines what you must trace and what you may honestly conclude.
The practical sequence is:
| Stage | Question | Useful output |
|---|---|---|
| Scope | Which feature, code revision, deployment assumptions, and attacker roles matter? | A short review charter |
| Map | Where does the request enter, and which files transform or authorize it? | A request path and trust-boundary map |
| Hypothesize | Which attacker-controlled values can reach sensitive operations? | Candidate source-to-sink paths |
| Verify | Can the candidate path be reached under real guards, and does it change behavior? | Reproducible evidence or documented uncertainty |
| Assess | What can the attacker actually read, change, or interrupt? | Bounded impact statement and priority |
| Fix | Which invariant should code enforce, and where? | Suggested change and regression tests |
| Communicate | Can another engineer reproduce and correct the problem? | Finding report and residual questions |
These stages are iterative. A failed test may reveal that middleware blocks the route. A fix proposal may expose another route to the same repository function. The sequence keeps a reviewer from leaping from a suspicious string to a severe claim without checking the path between them.
The reviewer's evidence ladder
Use precise language for the strength of a conclusion:
- Observation: “This repository function concatenates a request-derived value into SQL.”
- Reachability: “An authenticated member can supply that value through this endpoint.”
- Behavior: “In a local fixture, a crafted value changes the result set.”
- Impact: “The changed query returns invoice identifiers and customer email addresses from another workspace in this fixture.”
- Boundary: “I did not test a production database or other endpoints.”
The first observation is useful, but it is not the entire finding. Behavior and impact claims require evidence. If you cannot safely run a test, you can still report a code-based vulnerability with a clearly stated confidence level and a proposed unit test. Do not invent an exploit result.
Select a stage and check its deliverable. Each stage should leave a concrete artifact for the next one.
Scope. Record the actor, entry point, assets, and excluded behavior. Make the rule specific enough that a test could disprove it.
Trace. Follow the controlled search value and the verified tenant identity separately. Record how the route, service, and repository use each one.
Confirm. Use synthetic tenants and records. Demonstrate literal input handling and the foreign-object denial case without collecting real customer data.
Report. Give the root cause, reachable actor, evidence, concrete consequence, uncertainties, and a fix at the failing boundary.
Retest. Review the changed code, rerun the regression and allowed cases, and inspect other callers for the same assumption. A changed line is not itself a demonstrated fix.
Review question: Which artifact is missing from your own review notes right now?
Case study: invoice search in Cedar Desk
Cedar Desk is a fictional multi-workspace application. Members can search invoices for their own workspace. The search endpoint returns invoice number, status, and customer email so a support worker can find an invoice quickly. The team asks you to review a change that adds the search parameter to an existing endpoint.
The security expectation is specific: a member of workspace A may search invoices in A, and the search text must remain data within the database query. A member may not use search text to alter query logic or retrieve invoices from workspace B. Authentication and workspace membership are necessary but do not make a later SQL query safe.
The review is scoped to:
- the new invoice search route and middleware;
- its service and repository calls;
- the returned fields and workspace isolation behavior;
- tests relevant to this endpoint;
- the code revision under review.
It does not include invoice creation, billing calculations, email delivery, production network controls, or a full audit of the database schema. We can note those as outside scope without implying that they are secure.
A short review charter
Before reading the implementation, write a charter. A useful version for this case is:
Review the authenticated invoice search endpoint introduced in this change. Verify workspace membership, trace the customer search parameter to the database, and assess whether a member can cause the query to return invoices outside the selected workspace. Use local seeded test data only. Record exact files and a revision identifier in the finding.
The charter prevents two common mistakes. First, it keeps the reviewer focused on the trust boundary the change crosses. Second, it limits proof-of-concept testing to data the reviewer is authorized to inspect. The developer receiving the report can tell exactly what was and was not reviewed.
Start with the HTTP contract
The product contract says that this request searches by customer email:
GET /api/workspaces/ws_alpha/invoices?customer=alice@example.test
Cookie: session=<valid member session>
The expected response contains only matching invoices belonging to ws_alpha. If the customer parameter is absent, the service shown below converts it to an empty string; that behavior should be documented and tested separately. If the session is missing, the request is rejected. If the session user lacks workspace membership, it is rejected. These conditions are separate; satisfying one does not satisfy the others.
The question for the security review is not merely, “Is the user logged in?” It is: “After the application accepts the request, can any user-controlled string change the database predicate that enforces the workspace boundary?”
Map the request before judging the code
Assume the change touches these files:
src/routes/invoices.ts
src/middleware/session.ts
src/middleware/workspace-membership.ts
src/services/invoice-search.ts
src/repositories/invoices.ts
test/invoice-search.test.ts
Read them in request order. The route defines what the caller can supply. Middleware defines the entry conditions. The service may normalize or transform the value. The repository constructs the sensitive query. Tests reveal intended behavior but do not substitute for code review.
Route and middleware
The route is intentionally small:
router.get(
'/api/workspaces/:workspaceId/invoices',
requireSession,
requireWorkspaceMembership,
async (req, res) => {
const invoices = await searchInvoices({
workspaceId: req.params.workspaceId,
customer: req.query.customer,
});
res.json({ invoices });
}
);
The route supplies two values to the service. workspaceId comes from the URL path. customer comes from the query string. Both are caller-influenced, even though only a logged-in caller reaches the handler. A session narrows the attacker population; it does not turn input into trusted SQL syntax.
The first middleware verifies a session:
async function requireSession(req, res, next) {
const session = await sessions.read(req.cookies.session);
if (!session) return res.sendStatus(401);
req.user = { id: session.userId };
next();
}
The second checks membership in the requested workspace:
async function requireWorkspaceMembership(req, res, next) {
const member = await memberships.findOne({
userId: req.user.id,
workspaceId: req.params.workspaceId,
});
if (!member) return res.sendStatus(403);
next();
}
These checks are valuable. They mean the endpoint is not reachable anonymously and that a caller cannot simply replace ws_alpha with ws_beta to search B. The review must still examine how customer is used once a valid member passes the guards. A security boundary checked at the route can be undermined by a later query if the query's syntax is attacker-controlled.
Service and repository
The service trims the search string and enforces a length bound:
async function searchInvoices(input: { workspaceId: string; customer: unknown }) {
const customer = typeof input.customer === 'string' ? input.customer.trim().slice(0, 120) : '';
return invoiceRepository.search(input.workspaceId, customer);
}
This is a transformation, not a SQL injection defense. Trimming whitespace and limiting length may improve product behavior and avoid oversized requests, but a 120-character string can still contain SQL syntax. The transform preserves the characters that matter to the query. Record it because it affects which values reach the sink, while avoiding a false conclusion that “validated” means “safe in every context.”
The repository constructs the query:
async function search(workspaceId: string, customer: string) {
const sql =
'SELECT id, invoice_number, status, customer_email ' +
'FROM invoices ' +
"WHERE workspace_id = '" +
workspaceId +
"' " +
"AND customer_email = '" +
customer +
"' " +
'ORDER BY created_at DESC LIMIT 50';
return db.query(sql);
}
This is the sink. The code concatenates both the workspace identifier and customer search text into SQL syntax. The middleware has already checked membership in the workspace identifier; the repository still treats it as SQL syntax. The customer text is not constrained to a safe SQL literal. The query is built as one string and sent to the database. A reviewer can now state a precise hypothesis: an authenticated workspace member can supply a customer parameter that changes the query's WHERE expression.
Write the data flow in one line
request query customer
→ route req.query.customer
→ service trim and 120-character slice
→ repository string concatenation
→ db.query(sql)
This line names the source, each relevant transformation, and the database operation. It also shows where to test and where to fix.
Pause and decide: Which part is the root cause? The route's use of a query parameter, the service's length limit, or the repository's construction of SQL? What claim can you make before running a test?
Compare your reasoning
The root cause is the repository treating data values as part of SQL syntax. A query parameter is a normal way to implement search. Trimming and bounding it are reasonable for a user interface, but neither separates data from query instructions. Before testing, you can say the path is reachable to authenticated workspace members and that SQL is assembled unsafely. Describe the cross-workspace effect as a hypothesis until you confirm how the particular database and driver execute the resulting statement.
The query is parameterized, but tenantId comes from req.query. Which question remains open?
Confirm the behavior with controlled evidence
A proof of concept should answer the review question with the least data and disruption necessary. For this tutorial, use a local test database containing only synthetic invoices:
| Invoice | Workspace | Customer |
|---|---|---|
inv_a1 | ws_alpha | alice@example.test |
inv_a2 | ws_alpha | bob@example.test |
inv_b1 | ws_beta | carol@example.test |
Create a session for a user who belongs only to ws_alpha. The baseline request with customer=alice@example.test should return inv_a1. A request with workspaceId=ws_beta should fail at membership middleware. These controls establish that the observed cross-workspace effect is caused by query construction, not by a missing membership check or a misconfigured fixture.
Then send a request whose customer value introduces an additional SQL condition in the local environment. In the repository's string construction, a value shaped like the following can change the WHERE clause:
' OR 1=1 --
When inserted after customer_email = ', the leading quote closes the string, the OR supplies another condition, and the comment marker can hide the trailing quote and ordering text, depending on database syntax. This is an educational local test value, not a claim that it will behave identically under every driver and database. Check the actual rendered query, database dialect, and response. A syntax error alone is evidence of malformed query construction; a changed result set is stronger evidence of exploitability.
In this fixture, suppose the response contains inv_b1, even though the caller belongs only to ws_alpha. Now the report can state that a local test returned a synthetic invoice from another workspace. The impact follows from the returned fields: invoice number, status, and customer email are disclosed through this endpoint. It does not follow that the attacker can edit invoices, dump every table, execute operating system commands, or access production data. Those are different claims requiring different evidence.
Keep the test safe and reproducible
Use a disposable environment with seeded data and a test account. Do not run broad extraction against real customers to prove that a query is injectable. Record enough detail for a maintainer to reproduce the condition: code revision, database type, fixture setup, role, endpoint, baseline request, changed request, and observed response difference. Preserve only the minimum sensitive data needed in a report.
For many findings, a code-level test can be cleaner than an HTTP proof of concept. A repository unit test can inject a fake database client and assert that SQL text remains constant while values are passed separately. An integration test can seed two workspaces and assert that a member of A never receives B's records for special characters in search. The right test depends on the architecture and the claim.
If a proof of concept does not work
A failed probe should change the conclusion, not disappear from the notes. The driver may reject the syntax. An ORM layer may parameterize a different function than the code suggests. The server may return a generic error. A test fixture may be wrong. Trace each possibility. Do not label the issue a false positive just because one value failed. Conversely, do not call it confirmed cross-workspace access merely because SQL looks unsafe.
You can still report a query construction flaw with an explanation of reachability and a clear “behavior not confirmed” note. The developer can then run a targeted regression test. Distinguish what the code proves from what the environment proves.
Assess impact without inflating it
The observed behavior breaks a workspace isolation rule. An authenticated member of one workspace can cause a search response to include invoices from another workspace in the test fixture. That is a confidentiality impact. The intended query projects four columns and returns at most 50 rows, but an injected comment may affect the ORDER BY and LIMIT clauses as well. Do not assume the limit still applies after query text changes; inspect the executed statement.
Do not assume the attacker can read fields absent from the response without testing a different query shape.
Severity depends on context. Consider:
- Attacker prerequisites: Does the attacker need any account, a paid role, or membership in a specific workspace?
- Exposure: Is the endpoint internet-accessible to any member, or restricted by other controls?
- Data sensitivity: Do returned fields contain personal, financial, or operational information?
- Scale: Can an attacker enumerate many workspaces or only affect a narrow result?
- Reliability: Does the technique work consistently in the deployed database and driver?
- Detection and containment: Are there limits or logs that materially restrict repeated access?
The presence of SQL injection is serious, but a severity word is not a substitute for these facts. If your organization uses CVSS, calculate it from the confirmed conditions and state the version and vector. The FIRST CVSS v4.0 specification defines the scoring framework; a score should not be guessed from the vulnerability name alone. A product team also needs business context: cross-workspace invoice disclosure may matter more to them than a generic score communicates.
A useful impact sentence
“An authenticated member of one workspace can manipulate the customer search predicate so the invoice search endpoint returns synthetic invoices from another workspace in the local test database, including invoice number, status, and customer email. We did not test production data or other database operations.”
This identifies actor, route, mechanism, observed effect, fields, and limits. It is more actionable than “SQL injection allows full database compromise,” which would overstate demonstrated impact.
A patch can fix injection and still miss authorization
The query text is fixed in both versions. Which identity should determine the tenant predicate?
const result = await db.query(
"SELECT * FROM invoices WHERE tenant_id = $1 AND title ILIKE $2",
[req.query.tenantId, `%${req.query.title}%`]
);
Reveal the safer implementation
const principal = await requireSession(req);
const result = await db.query(
"SELECT * FROM invoices WHERE tenant_id = $1 AND title ILIKE $2",
[principal.tenantId, `%${String(req.query.title ?? "")}%`]
);
A parameterized query and an authorized tenant are separate requirements. The fixed version obtains the tenant from the verified principal for this tenant-scoped feature. If administrators can choose tenants, that ability needs its own explicit policy and audit context.
Find the root cause and choose the right fix
The underlying invariant is that user-supplied values must remain values, not SQL syntax. The repository should pass them to the database as bound parameters. The membership check remains important and should continue to run for every request. It cannot compensate for a query whose predicate can be rewritten.
A corrected repository function might be:
async function search(workspaceId: string, customer: string) {
const sql = [
'SELECT id, invoice_number, status, customer_email',
'FROM invoices',
'WHERE workspace_id = $1 AND customer_email = $2',
'ORDER BY created_at DESC LIMIT 50',
].join(' ');
return db.query(sql, [workspaceId, customer]);
}
The placeholders shown here follow a PostgreSQL-style client API. Other database clients use different placeholder syntax. The important property is that query structure is fixed and the driver sends values separately. The application should not try to “escape” quotes by hand, strip apostrophes from legitimate email addresses, or build a blacklist of SQL words. Such approaches are hard to make correct and can damage normal input.
The fix should also preserve workspace isolation tests. Even if injection is corrected, a future refactor could accidentally remove requireWorkspaceMembership. The safe query and authorization rule are independent controls. Test both.
Regression tests that prove the invariant
A meaningful integration test should include:
- A normal exact search in workspace A returns A's invoice.
- A search with an apostrophe remains data and does not cause a server error.
- A search value containing SQL punctuation returns only literal matches, not all rows.
- A member of A cannot request B's workspace route.
- A member of A cannot receive B's invoices through A's route.
- No-customer behavior remains bounded and scoped, if that behavior is part of the product contract.
The test should assert returned records and absence of cross-workspace records, not merely a 200 status. A query that returns 200 and leaks data is a failing security test. A query that returns 500 on an apostrophe may still indicate unsafe construction or poor handling even if the original value does not produce leakage.
Check all callers of the repository function
After designing the fix, search for every call to invoiceRepository.search. Another route, background job, or GraphQL resolver may call the same function with different assumptions. If the repository accepts raw strings and concatenates them, the flaw is in a shared boundary. Fixing the function covers all callers; adding a route-only filter covers only one entry path. Also search for similar string construction in adjacent repository functions, but report each additional finding separately if it has a distinct path or effect.
Pause and decide: Would escaping the customer string in the route be an adequate fix? What happens if another caller invokes the repository directly?
Compare your reasoning
Route-level escaping is a fragile workaround. It depends on the right database syntax, character encoding, and every caller remembering to use the same rule. It also leaves workspaceId concatenated into SQL. Bound parameters at the repository boundary establish the property for all callers that use the function. The route can still validate types and lengths for product behavior; the database boundary must keep data separate from SQL structure.
Which finding title best matches demonstrated evidence that one tenant can read another tenant’s invoice totals?
Write a finding that another engineer can use
A security finding is an engineering handoff. The reader should not have to reconstruct your reasoning from a screenshot, guess which endpoint you tested, or infer what “critical” means. Put the consequence near the top, followed by the exact path and evidence. Include a fix direction that addresses the root cause, not just the sample value used in your test.
Here is a model report for the Cedar Desk case. The file names and line references are illustrative; in a real report, use the exact revision and line numbers from the reviewed code.
Title: Invoice search concatenates customer input into SQL, allowing cross-workspace results
Scope and status: Confirmed in a local test database at revision
abc123. Reviewed the invoice search route, session and workspace membership middleware, service, repository, and endpoint test. No production testing performed.Affected entry point:
GET /api/workspaces/:workspaceId/invoices?customer=...for an authenticated member of a workspace.Root cause:
src/repositories/invoices.tsbuilds the SQLWHEREclause by concatenatingworkspaceIdandcustomerinto the query string. The route passesreq.query.customerthrough a trim and length limit; these transformations do not preserve it as data.db.queryreceives the assembled string without bound values.Security expectation: A member may search invoices in their own workspace. Customer search text must not change query structure or the workspace predicate.
Reproduction: Seed one invoice in
ws_alphaand one inws_beta. Authenticate as a user who belongs only tows_alpha. Confirm that an ordinary customer search returns only A's invoice and that a direct request to B is rejected. Then send the crafted customer value shown in the local test record to A's route. In this fixture, the response includes B's invoice.Observed impact: The endpoint returned the other workspace's synthetic invoice number, status, and customer email. The test did not establish write access, access to other fields, or production exposure.
Recommended fix: Use a fixed SQL statement with bound values for both workspaceId and customer. Keep the membership check. Add an integration test with two workspaces and punctuation in the customer parameter, asserting no B records appear in A's response.
Priority note: Triage as a cross-workspace confidentiality issue reachable by authenticated members. Confirm deployment details, data sensitivity, and scale before assigning the organization's final severity.
This report gives a developer enough information to locate, reproduce, and fix the defect. It also gives a reviewer enough information to challenge the conclusion if a hidden guard or test setup changes the result. A good report is falsifiable: another person could repeat the test and see whether the claim holds.
Avoid evidence that obscures the claim
An entire HTTP transcript can be useful as an attachment, but it should not replace the short explanation. A stack trace that shows a SQL syntax error is not proof of cross-workspace data exposure. A screenshot of two result rows without account and fixture context cannot show why either row was unauthorized. Record the baseline and changed response, and identify the rule that the changed response violated.
For sensitive applications, redact session cookies, access tokens, personal data, and unrelated database rows. Preserve a hash or synthetic identifier if that is enough to distinguish the two records. Keep raw evidence in the approved issue system. The report should never become an accidental secondary data leak.
Match the title to the demonstrated outcome
Titles help owners find and prioritize issues. “SQL injection” names a technical class; “invoice search SQL injection can return another workspace's invoices” adds the product consequence. If you have not confirmed the second part, write “invoice search constructs SQL from customer input” and explain the likely risk below. The title should not promise evidence the body does not contain.
Describe a fix, not a payload blacklist
A report that says “block OR 1=1” invites a partial fix. An attacker can vary syntax, and a legitimate customer name may contain unusual characters. The right invariant is stable SQL structure with bound values. Similarly, a missing authorization check should be fixed by enforcing the required policy for the requested object and action, not by hiding an object identifier from the UI. Root-cause language helps the owner choose a durable correction.
Review the proposed patch
A reviewer should not close the issue merely because a developer changed the flagged line. Examine the patch against the invariant. For this case, look for a constant query structure and separately bound values. Confirm both values are bound. Check whether another branch in the repository function still assembles a query with concatenation when the customer parameter is empty. Check whether the route can call a different repository method in that branch.
Suppose a patch changes only the customer clause:
const sql =
'SELECT id, invoice_number, status, customer_email ' +
"FROM invoices WHERE workspace_id = '" +
workspaceId +
"' " +
'AND customer_email = $1';
return db.query(sql, [customer]);
This improves the customer path but leaves workspaceId embedded in SQL text. The membership middleware may accept only identifiers that are members in a database lookup, which can reduce the practical risk. Nevertheless, the repository boundary still fails to treat that value as data. The clean fix binds both values. A security review should record the remaining unsafe construction and decide whether it is reachable, rather than marking the entire class resolved based on one parameter.
Now suppose a different patch uses an ORM query:
return db.invoice.findMany({
where: {
workspaceId,
customerEmail: customer,
},
select: {
id: true,
invoiceNumber: true,
status: true,
customerEmail: true,
},
take: 50,
orderBy: { createdAt: 'desc' },
});
This shape generally expresses values through the ORM's query API. Verify the specific ORM behavior in your project and inspect any raw-query escape hatches. A security review can approve this path when the API actually parameterizes values and the tests preserve workspace isolation. Do not infer safety from the word “ORM” alone; raw SQL APIs and dynamic fragments can reintroduce injection.
Regression review is a separate step
Run the targeted tests and inspect what they assert. A test named “blocks SQL injection” is weak if it only checks that the server returns 200. A strong test seeds data in two workspaces, sends an adversarial search value through the real endpoint, and proves the response remains scoped to the authorized workspace. Also check normal search, empty search, errors, and values with apostrophes. Security fixes should preserve expected product behavior.
Finally, inspect the diff for accidental side effects. Did the new query remove the limit? Did it return more fields? Did it change case sensitivity or exact-match behavior in a way the product did not request? A fix can be secure against the original issue and still introduce a different exposure. A complete review checks the changed behavior, not just the label of the patch.
A repeatable review workflow for a real codebase
The case study was compact. A real feature may include dozens of files. Use a worksheet to prevent losing the path. Fill it in as you read:
| Field | Question to answer |
|---|---|
| Feature and revision | What precise code and behavior are under review? |
| Actor and starting access | Anonymous caller, ordinary member, admin, internal service, or job? |
| Intended rule | Who may perform which action on which object? |
| Entry points | HTTP routes, GraphQL resolvers, jobs, webhooks, imports, or message handlers? |
| Inputs | Which values can the actor control directly or indirectly? |
| Transformations | Parsing, normalization, validation, encoding, lookup, caching? |
| Sinks and decisions | Database query, HTML renderer, command runner, file operation, permission check? |
| Evidence | Code path, local test, failing assertion, or unknown? |
| Impact | Which confidentiality, integrity, or availability property actually changes? |
| Fix and tests | Which invariant is enforced, and how will regressions be caught? |
| Limitations | Which files, roles, environments, and outcomes remain untested? |
For a change review, inspect the diff first to understand what behavior moved, then follow both old and new paths. A changed route may call an old helper that was previously unreachable with user-controlled input. A refactor can remove a middleware guard while leaving the protected service unchanged. The vulnerability may sit outside the diff, but the diff creates the path to it.
Search by data and operation, not only by vulnerability names. In a repository, find the route name, service function, database table, user-controlled parameter, and output field. Keep a map of the actual call chain. If a scanner identifies a sink, work backward to the source and forward to the response or side effect. If a user story defines a permission rule, start at the operation and locate every route that can perform it.
Time-boxing without pretending the review is exhaustive
A useful first pass is to map entry points and intended rules. Then prioritize paths with attacker-controlled data and sensitive effects. If time ends, document what you reached and what remains unexamined. For example: “Reviewed the HTTP route and direct repository call; did not review the background import job that also calls the same function.” That is a valuable handoff. “No issues found” without a scope statement is ambiguous.
When you find one confirmed issue, resist the temptation to stop immediately. Look for the same root cause in neighboring functions and alternate entry points. That does not mean spending unlimited time on speculative variants. It means checking the local pattern: who calls this helper, are values bound in similar queries, and does another route bypass the intended policy? Record the extent of the search so the developer understands whether the finding is isolated or likely systemic.
A stopping rule for an individual finding
You have enough to report when you can identify a reachable entry point, the violated security rule, the responsible code path, evidence appropriate to the claim, the bounded impact, and a plausible fix. Additional payload variations rarely improve the report once the essential behavior is established. Stop extracting data and move to communication and remediation verification. If an uncertainty materially affects severity or the fix, name it and ask the owner to resolve it.
Practice packet: review a different authorization path
Try a second fictional feature without reading the worked answer. Cedar Desk team managers can inspect invitations to their team. An invitation record includes the invitee email and a single-use token used by a separate acceptance flow. The expected rule is that a manager of team A may inspect only invitations belonging to A. The route below requires a session and checks that the caller manages the team in the URL.
router.get(
'/api/teams/:teamId/invitations/:invitationId',
requireSession,
requireTeamManager,
async (req, res) => {
const invitation = await invitations.findById(req.params.invitationId);
if (!invitation) return res.sendStatus(404);
res.json({
email: invitation.email,
token: invitation.token,
});
}
);
The middleware looks up membership using req.user.id and req.params.teamId. The repository's findById fetches solely by invitation ID. Assume invitation IDs are opaque strings that an attacker might learn through logs, shared links, or other product surfaces. Do not assume their opacity is an access-control rule.
Write four short notes before reading on:
- What is the intended authorization decision, and where is it currently made?
- What attack path might exist for a manager of A who knows an invitation ID from B?
- What safe local fixture and request would confirm or refute the path?
- What code change and regression test would enforce the intended rule?
Compare your reasoning
The route checks that the caller manages the team named in the URL. It does not check that the invitation fetched by invitationId belongs to that same team. If a manager of A calls A's route with B's invitation ID, the middleware can pass because the caller manages A. The repository then returns B's record by ID, and the route returns B's email and token. That is a candidate object-level authorization flaw.
To confirm safely, seed two teams and one invitation each in a local test database. Authenticate as a manager of A only. A request for A's invitation should succeed. A request to B's team route should fail. Then request A's route while providing B's invitation ID. If B's email or token appears, the flaw is confirmed in the fixture.
If it returns 404 or 403, inspect whether a hidden repository filter, middleware rule, or data model constraint explains the difference. Do not infer the result from the code fragment alone when real application behavior may differ.
A robust fix fetches the invitation with both its ID and the authorized team ID, or performs an equivalent object-level permission check before returning it. For example:
const invitation = await invitations.findOne({
id: req.params.invitationId,
teamId: req.params.teamId,
});
if (!invitation) return res.sendStatus(404);
The manager check still matters. The query binds the object to the team already authorized by the middleware. The regression test should assert that a manager of A cannot retrieve B's invitation through either A's URL or B's URL. Because the response includes a single-use token, the impact may extend beyond email disclosure if possession of that token permits acceptance or some other action. Investigate the token's role before claiming account takeover or another downstream effect.
This exercise demonstrates why a complete review must combine route-level authorization, object-level lookup, returned fields, and impact. Each part alone is incomplete. The review report should explain the mismatch between teamId used for permission and invitationId used for retrieval, then specify the observed result and test limits.
Which set of checks gives the strongest evidence that the fix preserves the security rule and the feature?
Your first complete security review: three Code Review Lab cases
Complete these challenges as the final practice for Secure Code Review Fundamentals:
For each case, perform a complete review rather than only naming a vulnerability class. Read every file provided in the case. State the intended security rule in your own words. Identify the entry point and attacker-controlled values. Follow the value and authority context through helpers and services to a sensitive operation. Check the guard conditions. Form a hypothesis, test it against the code, and record the exact lines that support or weaken it.
Then write a short finding with root cause, realistic prerequisites, bounded impact, and a fix direction. The challenges themselves assess your answer; this lecture intentionally does not reveal their solutions.
Use this worksheet for each case:
Case URL:
Review scope:
Intended security rule:
Attacker starting access:
Entry point and controlled input:
Files and call path:
Security decision or sensitive sink:
Observed code evidence:
Exploitability hypothesis:
Evidence that confirms or limits the hypothesis:
Root cause:
Realistic impact:
Fix at the right boundary:
Regression test:
Unreviewed paths or open questions:
Spend time on the parts that are easy to skip. A one-sentence vulnerability label does not show whether you can trace the request. A proposed patch that changes only the visible payload does not show whether you understood the root cause. A severity label without actor and returned data does not help the team prioritize. You should be able to explain your conclusion to a developer who has not seen the challenge before.
Self-review rubric
After completing each case, score your write-up against these criteria:
| Criterion | Strong answer |
|---|---|
| Scope | Names what was inspected and any meaningful gaps |
| Security rule | States the intended permission or data-handling property |
| Path | Connects source, transformations, guards, and sink across files |
| Evidence | Cites behavior or code that supports the exact claim |
| Impact | Names attacker prerequisites and affected data or operation |
| Fix | Enforces the invariant at a durable boundary |
| Verification | Includes a regression test that would fail before the fix |
| Honesty | Distinguishes confirmed facts from plausible but untested effects |
If you cannot complete one row, revisit the relevant file. This rubric is a better measure of review quality than the number of suspicious lines you highlight.
Common mistakes in a first complete review
Stopping at the first suspicious line
A string concatenation, dynamic call, or missing check is a lead. Follow the value from an entry point and inspect any guards between source and sink. In the Cedar Desk case, route membership narrowed who could reach the repository but did not prevent an authenticated member from influencing the SQL predicate. Without reading the middleware, the report might have overstated the attacker population.
Without reading the repository, the reviewer might have declared the route safe because membership was checked. Both errors come from stopping too early.
Treating an error as a complete exploit
A query error after entering an apostrophe suggests the input affects SQL parsing, but it does not by itself prove unauthorized data access. A complete finding says what the error demonstrates and what remains to test. The stronger local fixture shows a changed result set and a record from another workspace. Even then, it proves the result for that environment and code revision, not every deployment or every database capability.
Equating “logged in” with “authorized”
Authentication identifies a caller. Authorization decides whether that caller may perform the particular action on the particular object. The invitation exercise shows how a valid team-manager check can still be applied to the wrong team if the fetched invitation is not bound to the authorized team. The OWASP Authorization Cheat Sheet recommends enforcing access rules on each request and denying by default. In code review, locate the precise object and action protected by each check.
Letting the scanner write the conclusion
A scanner may point to a dangerous sink, but it usually does not know every business rule, runtime guard, or data provenance detail. The reviewer must decide whether the path is reachable and the operation is unsafe under the application's actual contract. A scan result can be excellent evidence of where to look. It is not a substitute for the path, proof, and impact sections in a finding.
Writing a fix that covers only the example
Blocking one SQL phrase, one file extension, or one object ID does not establish the security invariant. The fix should be phrased as a property: bound values cannot alter SQL structure; every object read is scoped to the caller's authorized workspace; untrusted text is encoded for the output context. A regression test then probes that property with several representative inputs. When the root cause is in a shared helper, fix the shared helper and inspect its callers.
Forgetting the negative conclusion
Sometimes a suspected issue is blocked by a verified guard. Record why. “The route's fixed badge map selects only literal filenames, and no request value reaches the path argument” is a useful negative conclusion. “No vulnerability” without a source-to-sink explanation is much harder to trust. Also record what was not reviewed. A negative conclusion for one path is not an assurance about the whole application.
Frequently asked questions
How much testing is needed before I report a code-level flaw?
Enough to support the exact claim you make. For a direct unsafe query with an authenticated path, code may establish a strong injection hypothesis. A local integration test that changes the returned data establishes more. If testing is unavailable, report the code path and the limitation. Do not fabricate a successful payload. The receiving team can decide whether to reproduce it before assigning final severity.
Should every review include a CVSS score?
No. Some teams require one, and others prioritize using product-specific impact and exposure. If you provide a CVSS score, use an actual version and vector based on confirmed facts. The FIRST CVSS documentation is the primary reference. A bare number without attacker prerequisites and data impact is less useful than a precise impact statement.
What if I cannot find a vulnerability?
Report the scope, the security rules checked, the paths examined, the tests performed, and any limits. “No confirmed finding in these paths” is a valid result. It is not the same as “the application is secure.” If a high-risk path remains unreviewed, name it so the next reviewer can continue.
How do I handle two related weaknesses in one feature?
Decide whether they share one root cause and one fix. In the Cedar Desk example, unsafe concatenation of both workspaceId and customer into a single SQL statement can be one finding about parameterization at the repository boundary. If a separate route also lacks workspace membership, that is a distinct authorization flaw with different evidence and a different fix. Link related issues, but do not merge unrelated causes merely because they appear in one file.
When is a proof of concept too invasive?
When it accesses real data you do not need, changes state, consumes unusual resources, or goes beyond the review authorization. Prefer a local fixture, synthetic account, and minimal assertion. A good proof answers a specific question with the smallest effect possible. If a live environment is the only option, follow the organization's testing rules and seek an approved test path.
What should I send a developer who has little security background?
Send the intended behavior, the current path, one reproducible observation, and the property the fix must enforce. Avoid a report that relies on jargon alone. A short SQL example showing values bound separately can be more useful than a long list of vulnerability names. Offer a test that will fail before the fix and pass after it.
Key terms
- Review scope: The feature, code revision, roles, environments, and behaviors examined.
- Security invariant: A rule that must remain true for every relevant path, such as “search text cannot change SQL structure.”
- Source: An origin of data that an attacker can control or influence.
- Sink: An operation that interprets data in a security-sensitive context, such as a database query or command execution.
- Reachability: Whether an attacker can get the value to the operation while satisfying or bypassing guards.
- Root cause: The implementation choice that makes the security invariant fail.
- Proof of concept: A minimal demonstration of the claimed behavior under stated conditions.
- Bound parameter: A value passed separately from SQL text so the database treats it as data.
- Regression test: A test that protects the corrected behavior from future changes.
- Residual risk: A relevant path or effect that remains untested or unfixed after the review.
Sources and further reading
- OWASP Code Review Guide for a structured approach to reviewing application code.
- OWASP SQL Injection Prevention Cheat Sheet for parameterized queries and safe query construction.
- OWASP Authorization Cheat Sheet for per-request access decisions and least privilege.
- OWASP Application Security Verification Standard for testable security requirements.
- FIRST CVSS documentation for versioned vulnerability scoring when your organization uses it.