Reviewing Multi-File Applications
Trace attacker-controlled data and security decisions across controllers, middleware, services, database layers, and shared helpers.
A multi-file review follows both data and authority through every layer relevant to one security rule. The route may establish identity, a service may choose an object, and a worker or repository may perform the sensitive action.
Use the architecture, data-flow, and authorization methods from earlier lessons to connect that path. Then practise on two independent code cases.
What you will be able to do
- Build a call map and a value map for one feature.
- Check the contracts between controllers, services, and repositories.
- Follow queues, stored inputs, and result delivery.
- Write a cross-file finding and an allowed/denied regression pair.
Why a multi-file review changes the question
A security bug is often a relationship between statements. One statement accepts an identifier; another establishes the user; another queries a record; another returns the record. None is necessarily dangerous alone. The security property concerns the relationship: does the record returned by the last statement belong to an object this user may read? If no function in the reachable path proves that property, a valid session can become a route to somebody else's data.
Framework structure hides that relationship in different ways. A controller may declare an authentication middleware but delegate ownership to a service. The service may accept a caller-provided tenant ID and assume the controller validated it. A repository may expose a convenient lookup by primary key that omits the tenant predicate. A response mapper may include fields the controller did not mention. A shared helper may change a path or query after validation.
Generated code, dependency injection, and event handlers add more indirection. The correct unit of review is the reachable behavior, not the file.
This does not mean reading every file in a repository. Begin with a specific request, asset, and rule. Expand outward only as evidence requires. A report-download endpoint might need six small files, its route configuration, and its tests. The entire frontend framework and every database model probably do not matter to the first hypothesis. If a dependency turns out to enforce a security boundary, read that implementation rather than relying on its name.
An effective review has two parallel tracks:
| Track | Question | Typical evidence |
|---|---|---|
| Data | What can the actor choose or influence, and where does that value travel? | Path parameters, parsed body fields, stored values, helper arguments, query predicates, output fields. |
| Authority | On whose authority does each operation run, and where is the permission decision made? | Verified session, tenant context, role or ownership predicate, resource policy, audit record. |
Confusing the tracks creates many false conclusions. An identifier can be well formed yet unauthorized. A session can be valid yet too broad. A repository call can use a safe ORM API yet return the wrong tenant's record. A service can have a correctly named policy function that is not called on this branch.
Establish the security rule before tracing
Before opening the code, write a sentence precise enough to be testable. For the fictional Atlas Reports application, suppose authenticated users may download a report only if it belongs to their current organization and their role permits report reads. An administrator of one organization does not automatically administer another. Archived reports remain readable only if the organization policy explicitly permits them. This is a better review rule than “users should be authorized” because it names actor, object, action, and scope.
You may not know the intended rule immediately. Read product requirements, API documentation, authorization tests, model relations, and neighboring endpoints. Ask the feature owner when a rule is genuinely ambiguous. In your notes, label uncertain policy as an assumption. Do not silently decide that every authenticated user may read every report because the code currently behaves that way.
For each action, write four fields:
- Actor: The principal who can cause it, including a user, service account, scheduled worker, or webhook sender.
- Object: The exact report, invoice, project, message, or file being read or changed.
- Action: Read, export, create, update, delete, approve, or trigger an external side effect.
- Scope: The organization, owner, delegated permission, environment, or time window that limits the action.
“An authenticated user may download only reports in the current organization when the effective role grants report:read” is now a candidate invariant. You can search for code that proves it. You can also construct a denied test: user A in organization A requests a report ID from organization B. A sound implementation denies the request and emits no report bytes, regardless of whether the ID is syntactically valid.
Follow both the call chain and the values. Select each file boundary to see the assumption that travels with it.
Controller. The route obtains a principal. It must establish the caller’s policy for the requested project before scheduling work.
const principal = await requireSession(req);
const projectId = req.params.id;
Queue. A trusted producer records the work and its authorized scope. Queue payloads still need integrity controls; a tenant field copied from the request is not trusted identity.
await queue.add("export", {
projectId, tenantId: principal.tenantId,
requestedBy: principal.userId,
});
Worker. The worker runs with its own credentials. Inspect how it resolves the project and whether the policy requires a fresh permission check after revocation or membership changes.
const project = await loadAuthorizedProject(job);
if (!project) throw new Error("Export denied");
Repository. A tenant-scoped query preserves the tenant boundary only if tenantId is verified. More specific membership or action checks may also be required.
return db.project.findFirst({
where: { id: job.projectId, tenantId: job.tenantId },
});
Output. The archive needs an access policy too. Check storage permissions, ownership of job status endpoints, result links, and how long the output remains accessible.
Review question: At which handoff could a correct assumption become an unchecked string?
Read an original six-file application
The following example uses TypeScript and Express-like syntax. It is intentionally small enough to fit on a page but divided the way a production codebase might be. Treat it as a review, not a puzzle: pause after each file and write what you know and what remains unproven.
File 1: route registration.
// routes/reports.ts
router.get('/api/reports/:reportId/download', requireSession, reportController.download);
The route is externally reachable. A caller controls the path segment reportId. The middleware name suggests an identity check, but the name alone proves nothing about report ownership. The sensitive operation is a download. Before continuing, note whether the same controller can be reached through another route or through internal invocation. A search for download references is a useful next step.
File 2: authentication middleware.
// middleware/requireSession.ts
export async function requireSession(req, res, next) {
const session = await sessionStore.verifyCookie(req.cookies.session);
if (!session) return res.sendStatus(401);
req.auth = {
userId: session.userId,
currentOrgId: session.currentOrgId,
role: session.role,
};
next();
}
The middleware establishes server-verified identity data in req.auth. That is a stronger source for currentOrgId than a request parameter, but the exact trustworthiness still depends on how sessions are issued and updated. This code does not check a specific report. An authenticated user can reach the controller. Record the distinction rather than marking the endpoint “authorized.”
File 3: controller.
// controllers/reportController.ts
export async function download(req, res) {
const reportId = parseReportId(req.params.reportId);
if (!reportId) return res.sendStatus(400);
const report = await reportService.getDownload(reportId);
if (!report) return res.sendStatus(404);
res.type(report.mimeType);
res.setHeader('Content-Disposition', 'attachment');
return res.send(report.bytes);
}
The controller validates the format of reportId. That may prevent malformed identifiers, but it does not establish permission to read the object named by a valid identifier. The controller passes only reportId to the service; no actor, organization, or resource policy context is visible in that call. This is a hypothesis, not yet a complete finding. The service might obtain context through a scoped dependency, or the repository might enforce a database policy. Continue the trace.
File 4: service.
// services/reportService.ts
export async function getDownload(reportId: string) {
const report = await reportRepository.findById(reportId);
if (!report || report.deletedAt) return null;
const bytes = await objectStore.read(report.storageKey);
return {
bytes,
mimeType: report.mimeType,
};
}
The service verifies existence and deletion state. It uses a storage key retrieved from the report record, not a path supplied directly by the caller. That matters for path-traversal analysis. But the visible code still does not check whether this user may read this report. The service sends bytes from the object store toward the response. Read the repository and the object-store helper before closing the trace.
File 5: repository.
// repositories/reportRepository.ts
export async function findById(id: string) {
return db.report.findUnique({
where: { id },
select: {
id: true,
organizationId: true,
deletedAt: true,
storageKey: true,
mimeType: true,
},
});
}
The query selects the report by ID and returns its organizationId, but no tenant predicate restricts the lookup. The shown value is passed through the ORM query API rather than assembled into raw SQL, so this path is about authorization rather than SQL injection. A separate raw-query path would need its own review. The important observation is that a record from any organization can reach the service if its ID is known.
A security reviewer should avoid calling the repository “insecure” in isolation because other callers may enforce policy. The route-to-repository path here is what lacks a decision.
File 6: shared object-store helper.
// infrastructure/objectStore.ts
export async function read(key: string): Promise<Buffer> {
return storageClient.getObject({
bucket: REPORT_BUCKET,
key,
});
}
The helper uses a fixed bucket and a key from the database record. The helper does not decide whether the current actor may read that record. The result flows to res.send. The full chain is now visible: caller-chosen reportId → parsed ID → repository lookup by global ID → object key → object-store read → response. Server-verified userId and currentOrgId exist in req.auth but do not participate in the decision. If no database row-level policy or wrapper intercepts the query, the invariant is unproven.
Write the trace before writing a finding
| Node | Value or authority | What has been established? | What remains unproven? |
|---|---|---|---|
| Route | reportId from URL | Endpoint is reachable after session verification. | Whether actor may download this report. |
| Middleware | userId, currentOrgId, role from session | Caller identity exists on req.auth. | Whether any downstream code uses it. |
| Controller | parsed reportId | Identifier format is accepted. | Ownership and action permission. |
| Service | report and storageKey | Record exists and is not deleted. | Organization relation and role. |
| Repository | lookup by global id | A matching record can be returned. | Tenant restriction. |
| Response | report bytes | Data leaves the server. | Whether this recipient was authorized. |
This table is more valuable than a vague comment on a single line. It identifies the expected control and the missing evidence. It also gives a teammate a reproducible path to verify or disprove the hypothesis. If a database policy automatically filters rows by authenticated tenant, add that evidence; the finding may change or disappear.
Confirm the hypothesis without guessing
Search the entire route registration for wrappers around reportController.download. Read the implementation of reportRepository.findById and any middleware attaching a database transaction context. Inspect database row-level security configuration if the team claims it applies. Determine whether a report ID from another organization is obtainable or guessable. Guessability is not a substitute for authorization: a URL may be exposed in logs, browser history, exports, shared messages, or predictable IDs. Still, realistic attacker prerequisites affect impact and how you explain the finding.
Then create a denied test with two ordinary accounts in separate organizations. Seed one report for organization B. Authenticate as an organization A reader. Request B's report ID. Assert the server denies the request and does not call the object store or return bytes. A passing test for a valid A report is useful too, because a fix that blocks every report does not meet the feature requirement. If you cannot execute the application, state what the code shows and what still needs runtime confirmation.
Avoid proving a vulnerability by printing another user's real data. Use fixtures, a test environment, or approved test accounts. The review goal is to verify the boundary, not to collect sensitive content. A review report should contain enough safe evidence to reproduce the condition without disclosing unnecessary data.
The controller requires login, but the worker looks up projectId without scope. What evidence is still needed?
Repair the security property across the full path
One reasonable repair is to make the service require trusted actor context and select a report within that actor's authorized organization. A policy decision may still be needed for role or report state. The point is to make the security property explicit at a layer that every relevant caller reaches.
// controllers/reportController.ts
export async function download(req, res) {
const reportId = parseReportId(req.params.reportId);
if (!reportId) return res.sendStatus(400);
const report = await reportService.getDownload({
reportId,
actor: req.auth,
});
if (!report) return res.sendStatus(404);
res.type(report.mimeType);
res.setHeader('Content-Disposition', 'attachment');
return res.send(report.bytes);
}
// services/reportService.ts
export async function getDownload(input: {
reportId: string;
actor: { userId: string; currentOrgId: string; role: string };
}) {
if (!canReadReports(input.actor.role)) return null;
const report = await reportRepository.findInOrganization(
input.reportId,
input.actor.currentOrgId
);
if (!report || report.deletedAt) return null;
const bytes = await objectStore.read(report.storageKey);
return { bytes, mimeType: report.mimeType };
}
// repositories/reportRepository.ts
export async function findInOrganization(id: string, organizationId: string) {
return db.report.findFirst({
where: { id, organizationId },
select: {
id: true,
organizationId: true,
deletedAt: true,
storageKey: true,
mimeType: true,
},
});
}
The corrected path passes an actor derived from verified session state, checks the action permission, and selects by both object ID and organization. It still requires review: is currentOrgId truly server controlled? Can a user switch organizations safely? Is canReadReports correct for the action and report state? Is objectStore.read scoped to the expected bucket? Does a cache bypass the service? A patch is not safe merely because it contains an if statement.
Some systems intentionally allow cross-organization sharing. In that case, the rule needs an explicit grant predicate rather than a simple organization match. A service might call a policy function such as mayDownloadReport(actor, report), and tests must cover direct ownership, delegated access, revoked grants, and denial.
A policy check after an unscoped query can be correct if it runs before any data leaves or side effect occurs, but a scoped query narrows accidental exposure and often simplifies reasoning. The choice belongs to the system's policy and data model, not to a universal “always filter by tenant” slogan.
If other entry points call getDownload, the service-layer check protects those callers too. If a background worker legitimately needs broader access, give it an explicit service principal or separate capability rather than silently bypassing the policy. A boolean bypass parameter named skipAuth is difficult to audit and easy to misuse. Make privileged flows visible and test them separately.
Build two maps: calls and data
A call graph says which function invokes which other function. A data-flow graph says which values influence other values. Both are needed. In the report example, a diagram of calls might be route → middleware → controller → service → repository and object store. A data trace follows reportId into the repository query and storageKey from the query into the object store. An authority trace follows req.auth until it stops at the controller.
The gap between the data trace and authority trace is the useful finding.
Do not confuse file names with behavior. A file called auth.ts may only parse a session. A method called getAuthorizedReport may trust a caller-supplied organization ID. A method called sanitizeHtml may remove some tags but not preserve the correct output context. Read implementations and tests at a boundary. When the code invokes a library, read the contract and configuration that matters. For example, an ORM's query binding may prevent query syntax injection, but it does not implement your business authorization policy.
On a large codebase, use targeted searches:
- Find the route or message handler from the externally visible operation.
- Find references to the controller method and service call to expose alternate entry points.
- Search for the entity ID and sensitive object type in the repository and policy layer.
- Search for output operations: res.send, file reads, database writes, queue publishes, or external calls.
- Search for tests that deny cross-user or cross-tenant access.
- Trace any helper that changes the object ID, path, query, or effective identity.
Keep search results as navigation hints. A text search cannot prove runtime reachability by itself. Framework registration, feature flags, queue consumers, runtime routing, and dependency injection determine which code actually executes. When a call is indirect, name the unresolved dispatch edge in your notes and find the binding.
Trace values across controllers and middleware
Controllers frequently mix trusted and untrusted data in a single object. Suppose a route receives req.body.organizationId and also has req.auth.currentOrgId. If a service accepts both without a strong type or clear name, a future caller may pass the body value as the authority. Distinct types such as ActorContext and ReportSearchInput can make misuse less likely, but type names cannot substitute for server-side policy. Review the actual constructor of ActorContext and whether client JSON can populate it.
Parsing is another source of confusion. parseReportId may reject malformed IDs, but a valid ID can name someone else's object. A lookup by id may be safe from SQL injection because the ORM binds values, but unauthorized access is still possible. A controller may return 404 for both absent and forbidden records to reduce information disclosure; that response code does not prove authorization happened. Look for the predicate or policy that produced the decision.
Middleware order matters. If requireSession runs after a route handler, it cannot protect the handler. If a router mounts public and private subrouters under similar prefixes, verify which registration matches first. If the same controller is called by a public health endpoint, an internal job, and an authenticated route, security assumptions may differ per caller. A service that relies on middleware only at one route is fragile unless every entry point is enumerated and controlled.
For authorization, check the intended object and action. A global role named admin might mean “organization admin,” not “platform admin.” A user could have report:read but not report:export. A person might read a report summary but not download its raw attachment. The decision must match the sensitive operation; permission to view a list does not automatically confer permission to fetch every row in that list.
Trace repository and database assumptions
Repositories often expose multiple lookup methods: findById, findByOwner, findInOrganization, findVisibleToActor. The name is a clue, but inspect the where clause and joins. A method may filter organizationId but forget a soft-delete flag. A join may apply the tenant predicate to the parent entity but not to an included child. An aggregate may count all rows even though the list endpoint filters them. A raw SQL helper may concatenate conditions differently than an ORM query.
Database row-level security can be an effective backstop, but it has operational requirements. Which database role executes the query? Does that role bypass policies? How is tenant identity set for a pooled connection? Is the setting cleared between requests? Does a background job use a privileged connection? A reviewer should neither ignore documented row-level security nor assume it covers all queries because a policy file exists. Verify the runtime context and denied tests.
If a repository returns a safe-looking projection, follow every field to the output. A storageKey might be only an internal locator, but a response mapper could accidentally expose it. A nested relation can contain private user data. A cache can store the whole record under a key that lacks organization scope. The SQL result is an intermediate value; the final sink may be an HTTP response, log, analytics event, export file, or email.
Distinguish the value you see from the value the sink uses
A frequent cross-file error is validating one representation and later using another. A controller may validate a normalized filename, then pass the original filename to a storage helper. A service may check an object's public ID and later fetch by a different internal ID. A policy may authorize a parent project while a repository loads a child document whose project relation changed between calls. These are not automatically vulnerabilities, but they are reasons to write down the exact variable and transformation at each edge.
Suppose a controller trims an input before checking an allowlist:
const normalized = req.params.format.trim().toLowerCase();
if (!ALLOWED_FORMATS.has(normalized)) return res.sendStatus(400);
return exportService.create(reportId, req.params.format);
The check applies to normalized. The service receives the original value. If the service uses that value in a file extension, template name, or command argument, the reviewer must follow that actual argument. A repair can pass normalized to the service and keep the service's own accepted-format contract narrow. This example illustrates a general method: when a security check appears, ask whether the checked object is identical to the object used at the sink, or whether a later transformation changes the property that was checked.
The reverse also occurs. A service may normalize a path after a controller checks for traversal. The controller saw an innocent string; decoding or normalization in a helper turns it into a parent directory reference. The code path, not the spelling of a single variable, determines safety. Read the framework's parsing behavior and the helper's transformation order. Do not guess that one decoding step or slash convention applies in every runtime.
Database transactions add another edge. A service can authorize a record, release its transaction, then update a newly loaded record by the same ID. If an attacker or concurrent process can change relevant ownership between those operations, the permission check and effect may apply to different states. Look for transactional boundaries, version predicates, and whether the update repeats the relevant authorization condition. You do not need to label every separate read a race condition; identify the specific invariant and a plausible state change.
Treat stored values as possible sources
The first HTTP request is not the only place an attacker can influence data. A report title may have been set by a lower-privileged editor yesterday and rendered in an administrator's dashboard today. A webhook URL may have been stored through an earlier settings endpoint and used by a privileged worker later. The source is the earlier write path, even when the sink reads from the database. Multi-file review often requires tracing backward from the stored field to all writers.
For a stored field, record who can set it, whether it can be changed after approval, which transformations occur on write, and which output or operation consumes it. A display name safe as text in one view may become unsafe when inserted into raw HTML in another. An object key safe when created by the server may become attacker-influenced if a migration or import endpoint later permits arbitrary values. The database does not cleanse data merely by storing it.
This backward trace can be scoped. Search writes to the exact field and inspect permissions on those writes. Do not assume every user input in the database can reach every sink. If the field is derived from a verified external system and immutable after creation, that fact changes the model. Record the evidence and continue to the actual consumer.
Record what a deny response really proves
A test returning 404 is not always enough. The handler may read or export data before producing the denial. A background job might be queued, an email sent, or a cache populated even though the visible response is an error. Assert the absence of the sensitive side effect where practical.
In the report example, the denied test should verify that no object bytes are returned and the object-store read is not invoked for a forbidden report. If the design intentionally reads a row to evaluate policy, that read alone is not necessarily a user-visible disclosure; the important property is that no unauthorized effect follows.
Tests should also exercise alternate paths. If a file is available through both GET /download and a bulk export endpoint, denial on one route does not prove the other is protected. A policy unit test proves the policy function's logic, while an integration test proves the route actually invokes it with the intended actor and object. Both have value; neither replaces the other.
Do not lose scope when moving code into a worker
Compare the two worker lookups. Which authority must be verified before the added predicate is meaningful?
const project = await db.project.findUnique({
where: { id: job.projectId },
});
return exportProject(project);
Reveal the safer implementation
const project = await db.project.findFirst({
where: { id: job.projectId, tenantId: job.tenantId },
});
if (!project) throw new Error("Export denied");
return exportProject(project);
This preserves the tenant scope supplied by a trusted producer. It is one part of the fix: verify queue integrity, authorize the action for the principal, and decide when revocation must take effect. A caller-controlled tenant field would leave the same trust problem in a different place.
Cross-file paths that leave the request
Not all effects happen before the HTTP response. A controller may enqueue an export job, return 202, and later send an email with a download link. If authorization is checked only in the controller, ask whether the queued payload contains a trusted actor reference or an unchecked object ID. If the worker re-queries a report by ID under a privileged database account, a forged or stale queue message might bypass the original guard.
If the worker receives a signed, scoped capability, verify expiry, issuer, and audience.
Consider a two-stage workflow:
// controller
await queue.publish('report-export', {
reportId: req.params.reportId,
requesterId: req.auth.userId,
});
res.sendStatus(202);
// worker
const report = await reportRepository.findById(job.reportId);
const file = await exportReport(report);
await mailer.send(job.requesterId, file);
The controller has a session, but the worker's read is not visibly scoped to that session's organization or permission. The risk depends on queue trust, job construction, and whether the report remains authorized when the worker runs. A robust design validates a trusted job schema and rechecks the security property at the point of use, especially when permissions can change while a job waits. A check at enqueue time can provide early denial, but it may not be enough for a long-running job.
Webhooks present a related boundary. A webhook body may be signed, yet the fields inside can still refer to an object the sender has no authority to modify. Signature verification establishes sender authenticity, not every business permission. A callback may route through a helper shared with ordinary user requests; trace the effective actor separately for each entry point.
Caches also change the path. A service may check permission on a cache miss but serve a cached report on a hit. Review cache key composition and where the authorization decision occurs. A key of reportId alone may be safe only if cached content is always identical and every caller is authorized before retrieval. For personalized or tenant-scoped output, the key usually needs relevant identity or policy dimensions. “The database query is scoped” is not a defense when the cache bypasses the database.
Review a shared helper without blaming every caller
Shared helpers attract scanner findings because they sit near powerful operations. Suppose a generic file reader accepts an absolute path. That is a dangerous capability, but the review must find a reachable caller who can influence the path. A CLI run by an operator, a test fixture, and a public download route have different threat models. Do not report the helper as remotely exploitable simply because it has a path parameter. Record each caller and its trust source.
At the same time, avoid declaring the helper safe because the first caller is safe. Another caller may pass a filename from an uploaded archive or a webhook. A helper that performs sensitive operations can enforce a narrow invariant itself: for example, accept an opaque storage key rather than an arbitrary filesystem path, and ensure it is resolved within a fixed storage namespace. This can reduce the burden on every caller. Whether enforcement belongs there depends on the helper's purpose and the application's policy.
An important review technique is to look one call upstream and one downstream. Upstream, determine what the argument represents and who can choose it. Downstream, determine how it is interpreted and what asset it affects. If a helper encodes HTML, inspect the context in which its return value is inserted. If it normalizes a path, inspect whether the caller used a different normalization before validating. Security properties often break at the seam between abstractions, not inside a single abstraction.
You found a repository method without a tenant predicate. Is every caller necessarily vulnerable?
Exercise: trace a request through four files
Read the following original example before opening the answer notes. A fictional clinic application lets a signed-in patient download a lab summary. Patients may download only their own summaries. A clinician may download a summary only for a patient assigned to their care. The exercise deliberately omits some implementation details; your task is to state what the shown code proves and what needs confirmation.
// routes/labs.ts
router.get('/api/labs/:summaryId/pdf', requireSession, labController.pdf);
// controllers/labController.ts
export async function pdf(req, res) {
const summaryId = parseUuid(req.params.summaryId);
if (!summaryId) return res.sendStatus(400);
const result = await labService.renderPdf(summaryId, req.auth.userId);
if (!result) return res.sendStatus(404);
return res.type('application/pdf').send(result);
}
// services/labService.ts
export async function renderPdf(summaryId: string, userId: string) {
const summary = await labRepository.get(summaryId);
if (!summary) return null;
const user = await userRepository.get(userId);
if (!user) return null;
return pdfRenderer.render(summary, user.displayName);
}
// repositories/labRepository.ts
export async function get(id: string) {
return db.labSummary.findUnique({
where: { id },
include: { patient: true, results: true },
});
}
Write a five-part answer before reading further:
- What can the caller control, and what identity came from the server?
- Which operation exposes protected data?
- Does the shown code prove the patient or clinician permission rule? Name the exact gap.
- What additional code or configuration could disprove a vulnerability report?
- What denied test and allowed test would you run?
Compare your reasoning
The caller chooses summaryId in the URL; parseUuid restricts format but not ownership. requireSession supplies a user ID, assuming its implementation verifies the session. The service uses that ID to fetch a user display name, yet it never compares the user or clinician assignment with summary.patientId. The repository performs a global lookup, and pdfRenderer receives the full summary and results. The response returns a PDF to the caller. Based only on the shown code, the permission rule is not proved.
A database row-level security policy, a scoped repository wrapper, or a hidden policy in pdfRenderer could change the conclusion. Read the real implementations before reporting certainty. A good denied test authenticates as patient A, requests patient B's summary ID, and asserts no PDF bytes are returned. A clinician test should deny access to an unassigned patient. Allowed tests should confirm A can download A's summary and an assigned clinician can download the appropriate summary.
The fix should check the actor's relationship to the exact summary before rendering, and it should carry the actor's effective role and assignment context from trusted state.
The exercise also reveals an information minimization question: why does pdfRenderer receive the user's display name? Could it include the requester's name on a document belonging to another patient, making the leak less obvious? Reviewers should inspect output mapping as well as access. Do not conflate this with proof that the renderer itself is vulnerable; it is a useful follow-up question.
A practical cross-file review worksheet
Use the worksheet below on unfamiliar code. It gives your notes enough structure to survive a pause and lets another reviewer validate the trace.
| Field | Record this | Example from Atlas Reports |
|---|---|---|
| Entry point | Route, event, job, or CLI command and its caller. | GET report download route; any authenticated user. |
| Security rule | Actor, action, object, and scope in one sentence. | May download only report in current organization with report:read. |
| Untrusted input | Every relevant caller-controlled field and earlier stored influence. | reportId URL segment. |
| Trusted context | How identity and scope are established; implementation checked? | req.auth from verified session; currentOrgId. |
| Call path | Function and file at each boundary; alternate paths. | Router → middleware → controller → service → repository → store. |
| Data path | Value transformations, lookups, and final sink. | reportId → row → storageKey → bytes → response. |
| Decision | Exact statement that enforces the rule, or absence after trace. | No visible organization or role check. |
| Denied case | An adversarial test whose expected result is denial. | User A requests B report; no bytes. |
| Allowed case | Normal behavior that must still work after repair. | A downloads A report. |
| Confidence | Proven from code, inferred, or waiting for runtime evidence. | Depends on database policy verification. |
When you cannot resolve a file edge, write “unknown” rather than inventing behavior. The worksheet is not a scoring rubric; its value is that it makes assumptions visible. A high-confidence report needs a reachable path and an unbroken line of evidence. If an implicit policy or database security layer exists, document it and revise the finding.
A ten-minute working sequence for a large repository
Set a short initial time box to avoid getting lost in framework machinery. In the first two minutes, identify the public action and state the expected rule. In the next three, draw the direct call path until you reach the sensitive read, write, execution, or output. In the next three, trace the attacker-controlled value and actor context across each call.
In the final two, write the first unresolved security decision and the test that would answer it. This is a navigation pass, not a verdict. Expand the time box only around the unresolved edge.
If the route calls an interface with multiple implementations, find the runtime binding. If a service reads a cache before a repository, inspect both branches. If a generated query builder hides the predicate, log or inspect the generated query in a test. If a repository method is only reachable through a scheduled task, revise the actor model from “remote user” to “job producer.” These small corrections prevent a review from accumulating confident but unsupported claims.
Keep a short uncertainty list while working: “Does the session's organization come from a signed server record?”, “Does this database role enforce row-level policy?”, “Can the webhook sender set reportId?”, “Is the cache scoped to organization?” Turn each uncertainty into a code lookup, configuration check, or test. The goal is not to eliminate every unknown in the system, only the ones necessary to judge this action.
For a large review, keep two artifacts: a short human-readable trace and links to exact code locations. The trace is stable conceptually even if line numbers shift. The links help maintainers inspect the actual statements. If the codebase uses generated route registration or build-time dependency injection, include the binding that proves which implementation runs in production.
What a strong multi-file finding sounds like
A weak finding says: “The repository is missing an authorization check.” That may be true, but it gives no reachable actor, sensitive operation, or expected policy. A stronger finding says: “A signed-in user can reach the report download route with an arbitrary reportId. The session middleware supplies currentOrgId, but the controller passes only reportId to getDownload. The service calls findById without a tenant predicate, then returns object-store bytes.
Unless a database policy scopes this query, a report from another organization can be downloaded by its ID. A denied cross-organization test should return no bytes. Pass trusted actor context to the service and enforce report:read and organization scope before the object-store read.”
Notice the qualifications. The statement names code evidence and an unresolved database policy. It does not claim an exploit was reproduced if no test ran. It suggests a fix at the security boundary and a regression test. It says nothing about “critical” severity until impact and prerequisites are assessed. The next lecture on security review tools will use the same evidence discipline for scanner findings.
Common mistakes in multi-file reviews
Stopping at authentication. A route using requireSession establishes identity, not permission for the particular report, patient, or action. Ask where the actor and object meet in a policy decision.
Stopping at input validation. A UUID parser can reject malformed input yet accept another tenant's valid UUID. A schema validator can enforce type and length without enforcing ownership.
Treating the ORM as an authorization system. Parameterized query construction is valuable for injection prevention, but a global lookup can still disclose the wrong row. Read query predicates and policy layers.
Assuming a helper name describes its guarantee. sanitize, authorize, safePath, and getVisible may hide narrower or broader behavior than their names suggest. Read the implementation and tests.
Ignoring alternate entry points. The same service may be used by a worker, webhook, admin endpoint, and public route. A fix in one controller may leave another route exposed.
Calling every shared sink exploitable. A powerful helper is a candidate for review, not automatically a remote vulnerability. Prove which caller can influence its arguments.
Losing the actor during a queue handoff. A worker often has more privilege than a user request. Carry a trusted actor or scoped capability, and revalidate permissions at use time when policy can change.
Overstating evidence. An unscoped query in source code is concerning, but a database policy may constrain it. Conversely, the presence of a policy file does not prove the production connection uses it. Investigate both.
Providing a fix that changes only the symptom. Hiding the download button in the frontend cannot protect a server endpoint. Filtering one list response cannot protect a direct object fetch. Fix the server-side action on every reachable path.
Which artifact best supports a cross-file finding?
Practice: two real Code Review Lab cases
Complete the Pet Caption code review exercise. Trace the request across the files shown by the challenge, record where the attacker-controlled value enters, where it is transformed, which helper or renderer finally interprets it, and where a defensive boundary should operate. Identify the vulnerability and submit your answer through the challenge interface. This is a distinct code review case; solving Course Reports in the introduction does not complete it.
Then review Secure Banking 2FA. Start with the user action and intended security rule. Draw the route, middleware, controller, service, repository, and helper path that actually exists in the case. Mark each trust boundary and permission decision. Identify a vulnerability only after the full reachable path supports it. The lecture deliberately gives no answer about that case.
For each case, keep a short review note with five fields: entry point and actor; controlled value; cross-file path; sensitive operation; and missing or ineffective control. Add a denied test and a repair. Use your trace to justify the vulnerable line you submit through the challenge interface rather than choosing a line by name. Both code review exercises are required for this topic; a correct solve supplies completion evidence for each case.
Key terms
- Call graph: A map of which functions can invoke which others in a particular execution context.
- Data flow: The path by which a value or its derived information travels through transformations and operations.
- Authority flow: The path by which trusted identity, role, scope, or capability reaches a security decision.
- Entry point: A route, event, worker message, CLI command, webhook, or other way an actor can cause code to run.
- Invariant: A property that must hold for every relevant execution, such as “only the owning organization can download this report.”
- Object authorization: A decision about whether an actor may perform a specific action on a specific object.
- Repository: An abstraction that reads or writes persistent data; its name does not imply an authorization guarantee.
- Row-level security: Database policy that can restrict rows visible or writable to a database role and request context.
- Sink: An operation where data affects a sensitive outcome, including responses, writes, execution, file reads, or external calls.
- Trust boundary: A point where data or authority crosses between actors or components with different privileges or guarantees.
Frequently asked questions
How many files should I read for one finding?
Read enough to establish the entry point, attacker control, relevant policy, sensitive operation, and actual reachability. That may be three files or twenty. Stop expanding when the security property is proved or disproved, then inspect alternate callers of any shared function involved in the fix. File count is not a quality metric.
Does a check in middleware always protect downstream code?
Only if the check enforces the correct object and action for this route and the route actually executes that middleware before the sensitive operation. Generic session middleware usually proves identity. It rarely knows which database record a later service will fetch.
Is a repository method that omits a tenant filter always vulnerable?
No. It may be used only by callers that already enforce policy, or database row-level security may constrain it. Still, a global lookup is a place to inspect carefully. Prove a reachable path from an actor to a sensitive effect before reporting exploitation.
Should a background worker trust the controller's earlier authorization?
It depends on the workflow and how long the job can wait. A queued job needs a trusted origin and must avoid accepting forged object IDs. If permissions can change while it waits, recheck the policy at the point of use. Even when an earlier check remains valid, document why the worker's elevated privileges cannot be misused by another producer.
Why write both an allowed and a denied test?
The denied test proves the security boundary. The allowed test proves the repair preserves the legitimate feature. Together they keep a fix from simply returning an error for everyone.
Sources and further reading
- OWASP Code Review Guide for a systematic security review mindset.
- OWASP Authorization Cheat Sheet for server-side access checks, deny-by-default policy, and object-level decisions.
- OWASP ASVS for verifiable application security requirements.
- MITRE CWE-862: Missing Authorization and CWE-639: Authorization Bypass Through User-Controlled Key for precise weakness language.
Continue to Security Review Tools and Techniques when you can explain a complete call, data, and authority path without relying on file names.