Understanding Application Architecture
Follow a request through frontend, API, backend, and database code to identify entry points, identities, and trust boundaries during a security review.
Map an application by following one request and the authority behind it. The browser, middleware, service, repository, and downstream worker each contribute a different part of the security decision.
In this lecture, follow an invoice download from the URL to the stored file. At each handoff, ask where the data came from and who is allowed to use it.
What you will learn
- Identify the entry point and the sensitive result.
- Trace data and verified identity as separate paths.
- Locate ownership and tenant checks across files.
- Follow queued work, caches, and results beyond the HTTP response.
Follow one request through the application
A common review mistake is to open the first file named in a feature description, read a handler, and stop. A handler is often only an orchestrator. It may accept a request, call a service, and serialize the returned object. The security decision may be in middleware, in the service, in a database predicate, or absent entirely. The reviewer must locate the point where the application changes from reading an actor's request to acting with the application's authority.
Consider a customer clicking Download statement. A plausible flow is:
Browser button
-> GET /api/statements/:statementId/download
-> reverse proxy / API gateway
-> session middleware
-> route handler
-> statement service
-> repository query
-> database row
-> PDF renderer
-> HTTP response
-> browser download
Each arrow is a handoff. At the browser-to-server handoff, a user can alter request fields even if the UI does not expose an edit control. At the session handoff, the server decides what identity it accepts. At the route-to-service handoff, an ID from the URL may be passed alongside a trusted user ID. At the repository, a lookup may use both values or only the requested statement ID.
At the response, a private PDF becomes available to the caller. The question "Can this customer download this exact statement?" cannot be answered by looking only at the button or by seeing that the route calls requireSession.
The OWASP Attack Surface Analysis Cheat Sheet recommends mapping entry points and trust boundaries. For code review, that map can be small and local. You do not need an enterprise architecture diagram before inspecting a five-file path. Start with one action and draw the components it actually touches. Add side paths only when they can affect the security rule.
What each layer contributes
The frontend renders controls and sends requests. It can improve usability and avoid accidental invalid input. It cannot be the sole enforcer of a server-side permission because a caller can send an HTTP request without using that frontend. Frontend code is still useful evidence: it shows which parameters the application expects, which endpoint it calls, and whether it renders a returned value as text, HTML, or a download.
The API boundary receives a request from a different trust domain. A route or controller parses path parameters, query parameters, headers, cookies, and bodies. Reverse proxies may normalize paths, set headers, or perform authentication, but the application must understand which assertions are actually guaranteed. An API route should not assume that a client-side form already validated a value.
Middleware can establish cross-cutting facts: a session is valid, a request has a correlation ID, a rate limit is satisfied, or a CSRF rule is enforced. A middleware name is an invitation to inspect its implementation, not proof of what it checks. requireSession might set req.user but know nothing about the statement being downloaded. requireAdmin might check a global role but not tenant scope. Middleware can reject some requests early, while object-level authorization still belongs near the operation that knows the object.
A service layer coordinates product rules. It may check whether a report can be exported, transform input, call several repositories, or send an email. A service can be reused by HTTP routes, scheduled jobs, and administrative tools. That reuse is valuable, but it also means a security assumption made for one caller may not hold for another. Trace every relevant caller when a service's authority depends on who invokes it.
A repository or data access layer constructs database operations. It may apply a tenant predicate, bind parameters, join related tables, or use a privileged connection. A query that returns a row by ID proves the row exists; it does not by itself prove that the caller may see it. Conversely, a repository method that takes both tenantId and id may enforce an important part of the authorization boundary if the tenant ID comes from a trusted session.
The database, cache, object store, or external API carries its own permissions and semantics. A database row might be cached under a key that omits tenant identity. An object store URL might be shared beyond the initial requester. A downstream service might trust a header the caller could influence. Follow the path until you reach the asset and the final output. Stopping at the first database result can miss a disclosure in rendering or logging.
Background workers and queues create additional entry points. A worker may process a message that originated from an HTTP request, an external webhook, or another service. The message can preserve attacker-controlled data even when the immediate job producer is trusted. A queue changes timing and component boundaries; it does not automatically make the message's content safe.
Each handoff carries a value and an assumption. Select a layer to see what you must verify there.
Browser. The client chooses the URL and can modify request fields. A hidden field containing tenantId is still caller-controlled.
GET /invoices/inv-b/download?tenantId=tenant-b
Middleware. Session verification establishes the customer and tenant on the server. Follow this identity object, not a similarly named URL parameter.
const principal = await requireSession(req);
// principal.tenantId comes from verified server identity
Service. The service must preserve the principal when it asks for the invoice. A helper name like loadInvoice does not prove that authorization happens.
return loadInvoiceForTenant(invoiceId, principal.tenantId);
Repository. The lookup links the requested ID to the authorized tenant. An ID-only lookup answers which record exists, not which record this caller may read.
return db.invoice.findFirst({
where: { id: invoiceId, tenantId },
});
Storage. Fetch the file using the storage key of the authorized row. A signed URL or storage key must not substitute for the object-level permission check.
Review question: Does verified authority survive every handoff until the file is returned?
The difference between data flow and authority flow
Two paths run through many features. Data flow describes where a value moves and how it changes. Authority flow describes why the application believes it may act on a particular resource. They often travel together but can diverge. A URL parameter may supply a statement ID while a signed session supplies the customer ID. The security property depends on the server combining those values correctly at the data access or policy decision point.
In a trace, label values by origin rather than by variable name. userId might be a path parameter chosen by a caller, or it might be a verified session claim. The string userId alone says nothing about trust. A service receiving { userId, reportId } cannot know their provenance unless the caller contract and implementation are clear. A defensive design may pass a richer trusted principal object or enforce the check at the repository query.
The reviewer's task is to verify the actual design, not to assume a type name confers authority.
For a statement download, a concise trace may look like this:
| Handoff | Value or authority | Reviewer question |
|---|---|---|
| Browser to route | statementId in URL | Can any signed-in user choose another ID? |
| Session middleware to route | principal.customerId | Is this derived from a verified server session, or from a request header? |
| Route to service | Both values | Does the service preserve the trusted identity or replace it with a caller value? |
| Service to repository | Query arguments | Does the query constrain the selected statement by customer/tenant ownership? |
| Repository to renderer | Statement data | Could a different customer's data reach the PDF? |
| Renderer to response | PDF bytes | Who can receive or reuse the response, URL, or cache entry? |
The table is useful even before you find a flaw. It tells you which files to open and what each file must prove. It also prevents the common mistake of treating every layer as equally important. For the ownership rule, the key question is the resource-specific authorization decision. For SQL injection, the key question might be how a value reaches a query parser.
For cross-site scripting, it might be how a value reaches an HTML renderer. Architecture is a map of where those questions can be answered.
The frontend never displays invoices from other tenants. What should the security engineer inspect next?
Worked example: a multi-file download path
The following invented application serves project documents. A member may download documents belonging to projects they can access. There are five files. Read each file before the analysis and write your own path: where does documentId come from, where is identity established, and what code proves membership in the document's project?
web/DownloadButton.tsx
export function DownloadButton({ documentId }: { documentId: string }) {
return (
<a href={`/api/documents/${encodeURIComponent(documentId)}/download`}>Download document</a>
);
}
server/auth/session.ts
import type { RequestHandler } from 'express';
import { verifySessionCookie } from './cookies';
export const requireSession: RequestHandler = async (req, res, next) => {
const session = await verifySessionCookie(req.cookies.session);
if (!session) return res.sendStatus(401);
req.principal = { userId: session.userId };
next();
};
server/routes/documents.ts
router.get('/api/documents/:documentId/download', requireSession, async (req, res) => {
const bytes = await documents.download(req.params.documentId, req.principal.userId);
if (!bytes) return res.sendStatus(404);
res.type('application/pdf').send(bytes);
});
server/services/documents.ts
export async function download(documentId: string, userId: string) {
const document = await documentRepository.findById(documentId);
if (!document) return null;
return objectStore.read(document.storageKey);
}
server/storage/documentRepository.ts
export async function findById(id: string) {
return db.document.findUnique({ where: { id } });
}
The frontend encodes an ID into a URL. It may receive documentId from a page that already filtered visible documents, but a caller can type a different URL directly. encodeURIComponent helps construct a valid URL; it does not prove ownership. The session middleware verifies a cookie and sets a server-owned userId. The route passes both the caller-chosen document ID and that user ID to the service. This looks promising at a glance.
The service, however, never uses userId. It asks the repository for any document with that ID and reads the corresponding object from storage. The response then sends the bytes to the caller.
The missing rule is not "a user must be signed in"; the middleware establishes that. The missing rule is "the signed-in user may read a document only if they are a member of the document's project." The dangerous authority handoff occurs when a document selected by a caller-controlled ID is treated as eligible for object-store access without a resource-specific check.
The exact file to change depends on the data model, but the decision must use both the trusted principal and the requested document or project. The OWASP Authorization Cheat Sheet emphasizes permission checks on every request and near the appropriate resource boundary.
A safer query and service contract
One possible repair is to constrain the repository lookup by membership, using an identity the server obtained from the verified session. The details of the ORM relation and schema will vary, but the shape of the rule should be explicit:
export async function findReadableByUser(documentId: string, userId: string) {
return db.document.findFirst({
where: {
id: documentId,
project: {
memberships: { some: { userId, status: 'active' } },
},
},
});
}
export async function download(documentId: string, principal: { userId: string }) {
const document = await documentRepository.findReadableByUser(documentId, principal.userId);
if (!document) return null;
return objectStore.read(document.storageKey);
}
This design makes the policy part of the read itself, reducing the chance that the application loads a document and later forgets to check it. It may return the same 404 for missing and unauthorized resources to avoid revealing existence; the exact response policy is a product decision, but the bytes must never be returned without authorization. If a project membership can change while the request runs, a high-stakes operation may need stronger transactional guarantees.
For a simple download, the important first fix is ensuring the object-store read follows an authorized lookup.
The repair also shows why an id format check would be insufficient. The attacker could use a perfectly valid document ID belonging to another project. The issue is not malformed input. It is that the application trusted the caller's choice of object without applying the product's rule. This is often called an insecure direct object reference or broken object-level authorization, but the name is less important than the code path and invariant.
Test the denied case
it('does not return a document from another project', async () => {
const owner = await seedUser();
const outsider = await seedUser();
const project = await seedProject({ members: [owner] });
const document = await seedDocument({ projectId: project.id, body: 'private' });
const response = await request(app)
.get(`/api/documents/${document.id}/download`)
.set('Cookie', sessionCookieFor(outsider));
expect(response.status).toBe(404);
expect(response.text).not.toContain('private');
});
The test uses two actors and the same object, which is more informative than a success test for the owner alone. It should also assert that the object-store read does not occur for a denied request if the application provides a suitable test seam. In a production codebase, tests may use a real test database and a mocked object store or an integration environment. The security property is that a caller cannot obtain bytes for an object they cannot read.
An ID lookup is not an access decision
Both versions find an invoice. Which version also carries the caller’s authority to the database boundary?
const invoice = await db.invoice.findUnique({
where: { id: req.params.id },
});
return storage.read(invoice.storageKey);
Reveal the safer implementation
const invoice = await db.invoice.findFirst({
where: { id: req.params.id, tenantId: principal.tenantId },
});
if (!invoice) throw notFound();
return storage.read(invoice.storageKey);
The protected storage operation follows a tenant-scoped object lookup. The tenant comes from the verified principal. Depending on the product, the policy may also require an owner, role, or project membership check.
How to find the real entry point in an unfamiliar repository
When a task says "review document downloads," begin with the route or action a caller can invoke. Search for the URL, controller action, exported handler, GraphQL resolver, RPC method, or queue consumer. In many repositories, the frontend is easy to find but not the true security entry point. A button may be hidden for some users while the route remains callable. Read the server handler even when the UI is the only file changed.
Then follow calls outward. Open the middleware implementation or the helper it delegates to. Open the service function and every repository or external call that supplies the response. If a method returns a signed URL instead of bytes, follow the URL creation path and its expiration and scope.
If a cache sits in front of the route, check whether the cache key includes any identity or authorization variation needed to prevent a response from one user reaching another. If a background job generates the file, identify the actor that enqueued it and the account whose credentials the worker uses.
You do not need to open every file in the repository. Work backward from the sensitive result and forward from the actor's controlled input until the two traces meet. For a download, the sensitive result is the file or a capability to fetch it. For a write operation, it is the data mutation. For an email, it may be the message recipient and private contents.
For a database search, it is the executed query and returned rows. This bounding method keeps the review focused while still crossing the files that matter.
Useful questions at each handoff
At the browser-to-API boundary, ask what a caller can change. Path parameters, query strings, JSON fields, cookies, headers, and uploaded content can be edited outside the UI. The browser's fetch() function creates requests, but HTTP is not exclusive to browsers; command-line tools and other programs can call the same endpoint. The MDN HTTP overview and Fetch API guide are useful when a request's method, headers, body, or response handling is unfamiliar.
At the middleware-to-route boundary, ask exactly what the middleware guarantees. Does it authenticate a person, select a tenant, validate a CSRF token, or all three? Can a route be reached through another registration path that omits the middleware? If the middleware trusts a forwarded header, which proxy sets it, and can an external caller override it? The fact that middleware ran is evidence only for the checks it actually performs.
At the route-to-service boundary, ask whether the service receives a trusted principal separately from caller-supplied identifiers. If it accepts a raw userId string, inspect all callers. A service invoked by an admin job may legitimately act on a specified user; the same service invoked by a customer route may require the current principal. Shared code can blur this distinction unless the contract makes it explicit.
At the service-to-data boundary, ask whether the query or operation enforces scope. Does a lookup constrain by tenant or ownership? Does a write verify current state and authorized transition? Are database values bound rather than concatenated into interpreter syntax? Is an external URL derived from caller input? Does an object-store key come from an authorized record or directly from the request?
At the data-to-response boundary, ask what leaves the system and who receives it. A service might return a whole object while the route serializes fields the caller should not see. A cache might store a personalized response under a shared key. An error message might disclose record existence or internal details. A safe database query can still lead to unsafe HTML rendering if text is inserted into an execution context later.
Locate trust boundaries by who controls the data
A trust boundary is a point where the system must make a decision about information or authority from a less trusted source. The browser-to-server edge is an obvious boundary, but important boundaries also exist inside a server: between a route and a privileged database connection, between a job message and a worker with broad credentials, between stored user content and an HTML renderer, or between one tenant's data and another tenant's response.
A process boundary or network hop is not automatically a security boundary if both sides have the same authority and verified contract. Conversely, two functions in the same process can cross a meaningful boundary when one treats caller data as authorization or executable syntax.
This is why architecture diagrams should show who controls a value and which component has authority, not only boxes and arrows. For the document example, the client controls documentId; the server controls the session identity; the application has authority to read from the object store. The missing link is a decision that ties the selected document to the authenticated user's project membership. The visual layout of files does not enforce that link. Code does.
Different architectural shapes, same review question
In a monolith, the route, service, and repository may live in one deployment. A caller's request still crosses an authority boundary when the server reads a private record. In a microservice system, an API gateway might authenticate the caller and forward an identity token to a document service. The reviewer must verify what the downstream service trusts and whether authorization is rechecked for the requested document.
In a serverless function, a handler may directly query the database without separate service files; the same actor/asset/rule analysis applies. In a mobile application, the app may make an API call and store a response locally; the backend still must enforce resource access.
An architecture pattern changes where you look, not what you need to prove. Do not infer security from the number of layers. More middleware and services can create more places for a rule to get lost. Fewer layers can make a path easier to read but can also mix parsing, policy, and data access in one function. Trace the actual execution path and assess each relevant boundary.
A controller passes req.query.tenantId to a function named loadInvoiceForTenant. Which assumption needs verification?
Practice: follow a request through a new multi-file application
Complete the interactive request-tracing lecture. It has a file-by-file walkthrough, a request simulator, and a final check that saves this lecture to your path. The example below gives you another trace to practise independently.
This exercise is separate from the worked document example. An organization uses a small application to preview a private export before downloading it. Assume a signed-in member should see only exports belonging to an organization where they have an active membership. Read the files in order, then draw the full request path and identify the earliest point at which the required authorization rule could be enforced. Do not stop at the first file that looks safe.
web/ExportPreview.tsx
export function ExportPreview({ exportId }: { exportId: string }) {
async function openPreview() {
const response = await fetch(`/api/exports/${encodeURIComponent(exportId)}/preview`);
if (!response.ok) throw new Error('Preview unavailable');
const payload = await response.json();
window.open(payload.previewUrl, '_blank', 'noopener');
}
return <button onClick={openPreview}>Preview export</button>;
}
server/auth/requireMember.ts
export async function requireMember(req, res, next) {
const session = await sessions.verify(req.cookies.session);
if (!session) return res.sendStatus(401);
req.principal = { userId: session.userId };
next();
}
server/routes/exports.ts
router.get('/api/exports/:exportId/preview', requireMember, async (req, res) => {
const previewUrl = await exportService.createPreviewUrl({
exportId: req.params.exportId,
principal: req.principal,
});
if (!previewUrl) return res.sendStatus(404);
res.json({ previewUrl });
});
server/services/exportService.ts
export async function createPreviewUrl({ exportId, principal }) {
const exportRecord = await exports.findById(exportId);
if (!exportRecord) return null;
return storage.signReadUrl(exportRecord.previewKey, { expiresInSeconds: 60 });
}
server/storage/exports.ts
export async function findById(id) {
return db.export.findUnique({ where: { id } });
}
Write a table with one row for each file. In each row, record the incoming value, its origin, any check or transformation, and the outgoing value. Then answer:
- Which value can the member choose directly, and which value should be derived from a verified session?
- What does
requireMemberactually establish? Does its name prove organization membership for this export? - Which function creates a capability that could let a caller read private bytes later?
- Does a 60-second expiration repair a missing authorization decision?
- What would a denied-case test assert, including whether the signed URL was created?
Compare your reasoning
The browser receives an exportId and uses it in a URL. A caller can change that ID outside the component. The middleware verifies a session and supplies a userId, but the shown code does not check membership in the export's organization. The route passes both values to createPreviewUrl. The service ignores principal, looks up the export by caller-chosen ID, and asks storage to sign a read URL.
The signed URL is a capability: anyone who obtains it may be able to fetch the preview until it expires, depending on storage configuration. Expiration limits its lifetime but does not establish that the person who requested it was authorized.
The earliest plausible enforcement point is the service before signing the URL, or a repository method that loads only exports readable by the trusted principal. A robust design would combine exportId with an active-membership predicate and return no signed URL for an outsider.
A denied-case test should create two organizations, sign in as a member of one, request the other's export, assert a denied response, and assert that storage.signReadUrl was not called for the inaccessible record. This conclusion follows from the shown path; the code does not reveal whether other guards exist in storage infrastructure, so a real review would inspect that too.
The key lesson is the same as in the worked example, but the sensitive output is different. The first example returned bytes directly. This one returns a URL that can retrieve bytes. A reviewer who stops after seeing res.json({ previewUrl }) might underestimate the impact because the response body is only a short string. The meaning of a value depends on the authority it grants, not on its format or length.
An architecture worksheet for your next review
When you open an unfamiliar feature, fill in this compact map before choosing a vulnerability label:
User action or external event:
Server entry point and HTTP method / message type:
Caller-controlled fields:
Identity established by:
Trusted principal carried as:
Service or policy decision:
Database/cache/object-store/external operation:
Sensitive result and recipient:
Security rule that should hold across the path:
First file that proves or fails that rule:
Unknowns needing inspection:
Then draw arrows between files. Put a mark where a value changes form, such as a URL parameter becoming a database key, a JSON field becoming a file path, a stored note becoming HTML, or a session claim becoming a tenant predicate. Put another mark where a component gains authority, such as access to a database connection, object store, mailer, or cloud API. These marks are the places where a security rule is most likely to be enforced or lost.
Do not turn the worksheet into a ritual that adds work without evidence. For a two-file route, a few lines may suffice. For a feature with a queue, cache, and external API, the map may need a second page. The point is to make your reasoning explicit enough that you can return to it when a new file changes the story.
Common misconceptions
"The frontend only shows documents the user owns." The UI is not an authorization boundary for a server endpoint. An actor can call the API directly with another ID, and cached or stale frontend state may also expose old choices. Review the backend rule for every resource-specific action.
"The route has authentication middleware, so the download is protected." Authentication identifies a caller; the object rule decides whether that caller may read this document. A signed-in outsider is the useful test actor. Read the middleware and the resource lookup.
"The service receives userId, so it must use it." Unused parameters are common and easy to miss. Follow the parameter through the service and repository to see whether it constrains the operation. A method signature is not evidence that a security rule ran.
"The database has row-level security, so the app code does not matter." Row-level security can be a valuable defense, but the reviewer must verify the effective database role and session context for this request. A privileged service account or incorrectly set tenant context may bypass the intended policy. Treat the configured control as evidence only after checking how this path uses it.
"A signed URL expires, so leaking it is harmless." An expiring capability can still be used during its lifetime. The authorization decision should occur before the URL is issued. Expiration reduces exposure if a URL leaks but does not replace the decision to issue it.
"Every hop is a trust boundary." Some hops merely reorganize trusted server code. The important question is what new information or authority crosses at a handoff. Focus on caller influence, privilege changes, interpretation contexts, and asset access.
When the request continues after the response
The simple request lifecycle is browser, route, service, data store, response. Many applications break that shape on purpose. A route may enqueue work and return 202 Accepted; a worker later generates an export. A route may issue a signed URL; a browser fetches the file from storage without another application-server request. A cache may return a response before the route runs.
These designs are useful, but they change where authorization must be checked and where an input can acquire authority. An architecture review must follow the full operation, not just the first HTTP response.
Consider an export request. The caller supplies reportId, the API authenticates the caller, and the route puts { reportId, userId } on a queue. The worker receives that message with a service credential that can read all reports. If the route does not check whether the user may export that report, the worker's broad access can turn a caller-selected ID into a private document.
If the route checks access but the worker later looks up a different report by an unvalidated field, the rule may still fail. If the export is generated hours later, membership could have changed between enqueue and execution. The product needs a deliberate policy: check at request time, at execution time, or both depending on the promised behavior.
A reviewer should write that policy down, inspect the code that implements it, and test a denied case.
The queue message is not automatically trusted just because the queue is internal. A message may be created by multiple producers, retried after code changes, or manually replayed during operations. The worker should validate its schema and use a principal or authorization context whose origin is clear. The worker's access to a broad database or object store is a privilege boundary.
A service account with minimal permissions reduces the damage of a mistake, but it does not prove that the caller was authorized for the requested object. Follow the message from producer to consumer, then to the created artifact and the way the user retrieves it.
Now consider a signed URL. The application server may correctly query a private export record, but the URL itself can act as a bearer capability. Whoever holds it may be able to fetch the bytes until it expires. The review therefore includes the authorization decision before issuing the URL, the scope of the signed key, the expiration policy, and where the URL is exposed.
A URL in a shared log, analytics event, or public response can leak access even if the original issuance was authorized. A short lifetime helps but does not correct issuing a URL to the wrong user. This is why a response containing only a string can be as sensitive as a response containing the file bytes.
Cache boundaries and personalized responses
A cache is another architectural shortcut with a security consequence. Suppose /api/reports/summary returns organization-specific numbers. The route checks the session and queries by organization, but an upstream cache keys only on the URL. The first organization's response could be served to the second before application authorization runs.
To review this path, determine where the cache sits, what requests it stores, how it computes keys, what headers control storage, and whether the response is private or shared by design. Do not assume a framework's cache defaults without inspecting the deployed configuration. A safe route implementation is insufficient if the response path bypasses it on cache hits.
There are also data-layer caches. A service might cache findReport(reportId) by ID and later reuse it for different users. Caching the raw report can be safe if every use rechecks access before returning it; caching an "authorized report" under a key that omits the principal can be unsafe. The review question is what decision the cached value represents.
A cache entry for data and a cache entry for permission have different key requirements and invalidation concerns. An organization membership change may make a previously cached permission false. Trace what is cached, who can retrieve it, and when its authority expires.
A timeline exercise for asynchronous access
Write down three moments for an export feature: request, execution, and download. At request time, the API can identify the caller and reject an export they cannot access. At execution time, the worker can recheck the relationship before reading data, especially if processing is delayed. At download time, a route or signed URL determines who may obtain the finished file. Now ask what happens if membership is revoked between each pair of moments.
The answer is a product-policy choice, but the implementation should match it. A reviewer cannot judge the code solely from a diagram of services; the timing of decisions matters.
The same exercise works for notifications and webhooks. A user may request that a report be emailed to an address. The worker eventually sends it. The reviewer must ask who controls the address, whether the recipient is allowed to receive the data, whether the worker reuses a stale authorization result, and whether retries can send the message again. These questions connect architecture to a concrete security rule. They also show why a queue is a data-flow step rather than a trust reset.
The HTTP handler queues a download job and returns 202. Where does the review continue?
Trace authority and data as two parallel paths
When reviewing a multi-file feature, draw two lines. The data line follows caller-selected values: documentId from a URL, reportId in a message, or a filename in a form. The authority line follows the server's verified identity and permissions: session to principal, principal to active membership, membership to scoped data access. A secure operation requires the lines to meet at the sensitive action.
In the download example, documentId reaches the object-store key, but the first version's authority line ends after session validation. The service never combines the caller's principal with the selected document. That mismatch is more informative than the statement "middleware exists."
For each line, record the origin. A user ID taken from the body is part of the data line even if it is named userId; it is not a trusted principal. A tenant ID from a signed server session may be an authority input, but only if the session was issued and verified correctly and the membership is current enough for the operation.
A tenant ID in an HTTP header may be a useful selector, but its value must be checked against the authenticated principal. Similar names can conceal different trust levels. Write "caller-selected tenant" and "verified tenant membership" in your notes rather than labeling both simply "tenantId."
At a service boundary, inspect whether both lines are passed together. A service signature such as readDocument(documentId) leaves no room for the caller's authority unless it uses a trustworthy context hidden elsewhere. A signature such as readDocument(principal, documentId) makes the intended relationship visible, though you still must inspect the implementation. A repository method such as findReadableDocument(documentId, principal.userId) can combine the two in one scoped query.
A service may instead load the document and check membership before reading storage. Either design can work, but the check must happen before the private result or capability is returned.
If the data line passes through a database row, preserve its provenance. The row may contain a storage key supplied by a previous user, an external importer, or a migration. The current caller may not control the key, but the component that wrote it may have been less trusted.
If the service uses the row's previewKey to ask storage for a signed URL, review both the authorization for the row and the guarantee that the key is within the correct bucket or prefix. A safe lookup by ID is one part of the proof, not the entire proof.
Compare your reasoning
For the preview exercise, one sound design is a service that asks the repository for an export visible to the verified principal, then signs only that record's previewKey. The repository query would join the export to its organization and an active membership belonging to principal.userId, or the service would perform an equivalent explicit policy check. It would return no record for an outsider. The service would not call signReadUrl for that request.
A test should verify both the denied response and the absence of a signed capability. A success test for a member should verify that the signed key belongs to the authorized export, not merely that some URL was returned.
Another sound design may use a separate policy function after loading the export. In that case, the reviewer should inspect the policy's inputs and every call site of the service to ensure the policy cannot be skipped. The difference between these implementations is not a universal security ranking. The important invariant is that a verified principal and a selected object are compared before a privileged read or signed URL creation.
Make that invariant a comment in the test or a named service contract so future changes preserve it.
Key terms
- Frontend: Code that presents an interface and initiates requests from a user's device.
- Backend: Server-side code that processes requests and acts with application credentials.
- API: A defined interface through which clients or services request operations and exchange data.
- Controller or route handler: Code that receives a request and calls the application logic for it.
- Middleware: Code that runs around route handling, often to establish identity or apply a cross-cutting rule.
- Service: Code that coordinates product behavior, policy, and data access.
- Repository: Code that reads or writes a database or other store.
- Principal: The authenticated actor identity and relevant trusted attributes established by the server.
- Capability: A value, such as a signed URL, that grants the holder access to an operation or resource.
- Trust boundary: A point where information from a less trusted actor or component is interpreted or acted upon by one with greater authority.
- Request lifecycle: The sequence from an initiating action through processing, data operations, and the response.
Frequently asked questions
Should a security reviewer always start from the frontend?
No. Start from the entry point that best exposes the security question. A URL or server route is often the fastest starting point for a resource access rule, while a UI component can show what parameters the application expects. For an asynchronous export, the worker or queue consumer may be the important entry point. Follow the path to the sensitive result, then inspect upstream callers as needed.
Is a database query itself an authorization check?
It can enforce part of an authorization rule if its predicate combines the requested object with a trusted actor or tenant context. A query by object ID alone usually establishes existence, not permission. A query using tenantId from an unverified request header also does not establish trustworthy scope. Review both the predicate and the origin of its inputs.
Can the service enforce access instead of the repository?
Yes, if it reliably loads the needed relationship, makes the decision before the sensitive action, and all relevant callers use that service. A scoped repository query can reduce the chance of accidental omission, but neither location is safe by name alone. Verify the actual control and its test coverage.
Do I need to map every microservice to review one feature?
No. Map the components on the path from the actor's input to the asset or side effect. Expand the map when a downstream service, cache, or worker can alter the security property. A bounded trace is more useful than a large diagram that never reaches a decision point.
Primary references and next lesson
- OWASP Attack Surface Analysis Cheat Sheet describes mapping entry points and trust boundaries.
- OWASP Authorization Cheat Sheet covers least privilege, per-request decisions, and denial testing.
- MDN HTTP overview explains request and response structure.
- MDN Using the Fetch API explains how browser code constructs HTTP requests and handles responses.
Continue with Sources, Sinks, and Data Flow. It will make the value trace more precise, especially when a single input travels through several transformations before reaching SQL or an HTML renderer.