Sources, Sinks, and Data Flow
Trace attacker-controlled values through transformations to database and HTML sinks, and evaluate validation, sanitization, and output encoding.
Source-to-sink analysis follows an actor-controlled value to the place where the application interprets or uses it. The source explains who can choose the data; the sink explains what power that data can gain.
Trace a stored message into a browser, compare SQL and HTML boundaries, and decide which transformations actually enforce the required rule.
What you will learn
- Identify direct, stored, and second-order sources.
- Track a value through transformations and branching uses.
- Choose controls for SQL, HTML, URL, and execution contexts.
- Explain an XSS trace before attempting the independent case.
Sources: where can an actor influence a value?
A source is a value whose content or selection an actor can influence. The obvious sources are HTTP request fields: a query parameter, path segment, form body, JSON property, header, cookie, uploaded filename, or file contents. There are less obvious sources too. A user can create a database record that a different route reads later. An external partner can send a webhook. A repository can ingest package metadata or a feed.
A user can choose an object ID even if the object contents are server-owned. A background job can receive a message created from an earlier request.
The important question is not "Did this value come from the database?" but "Who could choose this value, and under which rules?" A stored comment may have originated from an untrusted form. A support ticket may have been imported from email. A profile name may be displayed on an admin dashboard long after its creator signed out. The storage layer changes when and where the value is read; it does not retrospectively prove the content safe for every future destination.
Conversely, not every dynamic value is attacker-controlled. A sort column selected from a fixed server-owned map has a different risk than raw query text interpolated into SQL. A verified session's internal user ID is different from a userId query parameter, even if both are strings. The reviewer's first task is to label provenance accurately. Variable names such as trustedTitle or safeHtml are claims made by a developer; inspect how the value earned that description.
Direct, stored, and second-order sources
A direct source flows from the current request to the sensitive use. For example, req.query.search travels through a service to a database query in the same request. A stored source was submitted earlier and retrieved now. For example, a user writes a comment today and another user views it tomorrow. A second-order path occurs when input is accepted or stored in one context and becomes dangerous in a later context.
A value may pass a harmless validation at write time and still be unsafe when rendered into HTML, a CSV file, a shell command, or a different SQL query later.
This timing matters. A reviewer who inspects only the display route may see db.comments.findMany() and assume database content is trusted. A reviewer who inspects only the submission route may see a text length check and conclude the comment is safe. The full path connects both routes and the eventual HTML sink. In a real repository, you may need to search for where a field is written as well as where it is read. That is a more reliable way to identify who controls it.
The source can be far from the sink. Inspect each stage, including the later browser use.
Input. The customer chooses the entire message value. Converting it to a string does not remove that control.
const message = String(req.body.message);
Database. A parameterized insert protects the SQL operation. It does not make the stored message safe for every future interpreter.
await db.query("INSERT INTO messages(body) VALUES ($1)", [message]);
JSON API. JSON serialization gives the response a data format. Follow the value into the consuming application before drawing a browser-safety conclusion.
res.json({ body: row.body });
Dashboard. innerHTML asks the browser to parse the value as markup. For a plain-text message, this changes its meaning at the final boundary.
messageElement.innerHTML = response.body;
Review question: Which specific sink determines the output protection the value needs?
Sinks: where does the value gain power?
A sink is an operation where a value can affect a sensitive result. The word does not imply the operation is automatically vulnerable. A database query is a sink, but a fixed prepared statement with bound values can handle untrusted input safely. An HTML renderer is a sink, but rendering ordinary text through a framework's escaping mechanism can be safe in that context. The reviewer asks how the sink interprets the value and which control prevents an unwanted interpretation.
| Sink | What the interpreter may do | Reviewer's question |
|---|---|---|
| SQL execution | Parse a statement and return or modify rows | Is caller data bound as a value or joined into SQL syntax? |
| HTML rendering | Parse markup, attributes, URLs, and scripts | In which browser context is the value inserted, and is it encoded or sanitized for that context? |
| Shell execution | Parse command words and metacharacters | Is input passed as data to a fixed program invocation, or made part of a command string? |
| File access | Resolve a path under the server's filesystem authority | Can a caller choose a path outside the intended directory or name another user's file? |
| Network request | Connect to a destination using server credentials | Can a caller choose the host, protocol, or private network target? |
| Authorization decision | Select an object or action under a principal | Does the check use trusted identity and the exact requested resource? |
The table is a starting map, not a universal mitigation table. Each interpreter has its own rules. An HTML escape function does not make a string safe for SQL. SQL parameter binding does not make returned text safe to insert into innerHTML. A path normalization function may remove .. but still leave authorization failures if the caller can name another person's file. The same value can reach several sinks, each requiring its own review.
Where to mark the trust boundary
When you draw a data flow, mark the point where the value changes meaning. In an SQL example, that point is when application data becomes part of a query string to be parsed as SQL. In an HTML example, it is when text becomes markup interpreted by the browser. In an authorization example, it is when a caller-supplied ID is accepted as a resource the server may read.
A boundary can be crossed in a helper several files away from the source. Locating it makes the finding specific: "this value reaches this operation without this control."
The MITRE CWE-89 entry describes SQL command injection as improper neutralization of special elements in an SQL command. The MITRE CWE-79 entry describes user-controllable input being placed into a web page without proper neutralization. These definitions focus on the interaction between controlled data and an interpreter, which is the reason a source-to-sink trace is useful.
The API used a parameterized INSERT. Is the stored message safe to assign to innerHTML?
Transformations are not automatically defenses
Real data rarely moves unchanged from source to sink. It may be trimmed, converted to a number, validated against a schema, normalized to lowercase, encoded for transport, stored in a database, decoded again, or combined with another value. At each transformation, ask what property it establishes. Do not treat any transformation as a generic "sanitization" step.
Parsing turns a representation into a structured value. Number(req.query.page) may produce a number or NaN; it does not automatically enforce a valid range. JSON parsing proves the body is valid JSON but not that a field is authorized, bounded, or safe for HTML. Parsing is often a prerequisite to effective validation, not a complete defense.
Validation checks whether a value fits a defined input contract. It may enforce type, length, range, format, allowed enum values, or relationships between fields. A fixed integer ID parsed and bounded at the API edge may no longer contain SQL syntax, but the system still needs a query design that maintains value/syntax separation. A valid UUID naming another user's record is still an authorization concern. The OWASP Input Validation Cheat Sheet distinguishes allowlist-style validation from attempts to block a growing list of bad strings.
Normalization changes representation so comparisons are consistent. Trimming whitespace, lowercasing a search term, or normalizing Unicode can be appropriate for product behavior. It does not make data intrinsically trusted. A lowercased HTML tag is still markup if later inserted as HTML; a normalized path can still name an unauthorized object. Some security decisions require normalization before validation to prevent multiple representations of the same value from bypassing a check. The ordering must match the specific interpreter and rule.
Encoding represents data for a destination context. HTML text, HTML attributes, JavaScript string literals, CSS, and URLs have different rules. A string encoded for one context may be unsafe in another. For ordinary text in a web page, use a renderer that treats it as text or applies the correct output encoding. Do not encode early and then decode unexpectedly later. The OWASP XSS Prevention Cheat Sheet explains why context matters.
Sanitization removes or transforms disallowed content when the product intentionally accepts rich content. If users are allowed to write limited HTML, a well-maintained HTML sanitizer with a strict allowed subset may be needed before rendering. Sanitization is much harder than rendering plain text. It should not be used as a blanket excuse to pass arbitrary content to raw HTML APIs. An HTML sanitizer also does not fix SQL injection, object authorization, or a dangerous file path.
Parameter binding keeps SQL values separate from fixed SQL syntax. It is not a string-cleaning operation. The driver sends values as values for placeholders in a prepared or parameterized statement. For dynamic SQL identifiers, map a small allowed input set to fixed server-owned fragments. The OWASP SQL Injection Prevention Cheat Sheet treats prepared statements as a primary defense for value positions.
A transformation table for reviewers
| Code you see | What it establishes | What it does not establish |
|---|---|---|
String(value).trim() | A trimmed string representation | Safe SQL, safe HTML, authorized access |
parseInt(value, 10) | A numeric prefix when parsing succeeds | Valid range, correct object ownership, resistance to unexpected suffixes without further checks |
encodeURIComponent(value) | URL component encoding for transport | Permission to access the named resource |
value.toLowerCase() | A lowercase form for comparison | Trust or safe interpretation at a later sink |
pool.query(sql, [value]) | A value bound separately from SQL text, if the driver honors that API | Authorization for rows returned by the query |
element.textContent = value | Text insertion in that DOM node | Safety if the value is later copied to innerHTML or another interpreter |
This table helps you avoid two opposite errors: assuming a harmless transformation is a security boundary, and overlooking a real defense because it is not named sanitize. Read what the code does at the sink, not what an earlier helper is called.
Worked example: one message, two later destinations
An invented team application lets members save a note and later search and preview it. This design illustrates how a stored value can reach different sinks. Assume members may create notes in their own team, and a viewer may read notes only for teams they belong to. The code below intentionally contains more than one question to review. Start by identifying sources before trying to name a vulnerability.
routes/notes.ts
router.post('/api/teams/:teamId/notes', requireSession, async (req, res) => {
const note = await notes.create({
teamId: req.params.teamId,
authorId: req.session.userId,
title: String(req.body.title ?? ''),
body: String(req.body.body ?? ''),
});
res.status(201).json({ id: note.id });
});
router.get('/api/notes/:noteId/preview', requireSession, async (req, res) => {
const note = await notes.findById(req.params.noteId);
if (!note) return res.sendStatus(404);
res.type('html').send(`<article><h1>${note.title}</h1><p>${note.body}</p></article>`);
});
services/notes.ts
export async function create(input: NewNote) {
const title = input.title.trim().slice(0, 120);
const body = input.body.trim().slice(0, 4000);
return noteRepository.insert({ ...input, title, body });
}
export async function findById(id: string) {
return noteRepository.findById(id);
}
storage/noteRepository.ts
export async function insert(note: StoredNote) {
return db.note.create({ data: note });
}
export async function findById(id: string) {
return db.note.findUnique({ where: { id } });
}
The member controls teamId, title, and body in the create request. authorId comes from a server session if requireSession actually verifies it. The service trims and limits text lengths, but does not alter the meaning of markup inside the values. The repository stores them. Later, a different route reads a note by caller-chosen noteId and builds an HTML string from note.title and note.body. That raw string is sent with an HTML content type.
A browser parsing the response can interpret markup supplied earlier by a member. This is a stored XSS path if an actor can create a note that another user can view under the application's access rules.
The code also raises authorization questions. The create route accepts a teamId but does not show a check that the author is a member of that team. The preview route looks up a note by ID but does not show a check that the viewer may read the note's team. These issues are distinct from the HTML sink. A careful review reports them separately or clearly explains how they combine.
Fixing XSS by treating the note text safely would not repair unauthorized note access; adding a membership check would not make unsafe HTML interpolation safe for authorized viewers.
A safe rendering direction
If the product wants plain-text notes, return structured data and let the frontend render text through a safe text sink:
router.get('/api/notes/:noteId', requireSession, async (req, res) => {
const note = await notes.findReadableByUser(req.params.noteId, req.session.userId);
if (!note) return res.sendStatus(404);
res.json({ title: note.title, body: note.body });
});
function NotePreview({ title, body }: { title: string; body: string }) {
return (
<article>
<h1>{title}</h1>
<p>{body}</p>
</article>
);
}
React's ordinary text interpolation escapes text for this rendering context. If using direct DOM APIs, textContent is a text sink for this purpose:
titleElement.textContent = note.title;
bodyElement.textContent = note.body;
Do not replace textContent with innerHTML when the product needs only text. If rich formatting is a real requirement, design a supported subset and use a maintained sanitizer appropriate to the browser and the content before assigning HTML. The corrected route also uses a resource-aware lookup; the implementation of findReadableByUser must be inspected and tested. Its name alone does not guarantee a membership predicate.
Why JSON alone does not eliminate XSS
Returning JSON moves the HTML decision to the frontend; it does not automatically make later rendering safe. A frontend that receives JSON and writes element.innerHTML = note.body reintroduces the same boundary failure. Similarly, a React component that uses dangerouslySetInnerHTML with untrusted text opts out of normal text escaping. The reviewer must follow the value to the final interpreter, not stop at a response type. A safe data transport and an unsafe rendering sink can coexist in one feature.
SQL sink: data must stay separate from query syntax
The same source-to-sink method applies to SQL, but the correct control differs. Here is a deliberately unsafe search function in an invented inventory service:
export async function searchInventory(req) {
const rawCategory = String(req.query.category ?? '').trim();
const sql = `SELECT sku, name FROM inventory
WHERE category = '${rawCategory}' AND active = true`;
return (await pool.query(sql)).rows;
}
The source is req.query.category. The transformation is string conversion and trimming. The sink is the database call. The dangerous handoff is the interpolation into SQL text before the driver parses it. The apparent category restriction is data-dependent: a value that changes SQL structure can change what the database evaluates. The reviewer should not claim every possible impact from the snippet alone; database permissions and driver behavior matter. The fix for the value position is to keep the query fixed and bind the category:
export async function searchInventory(req) {
const category = String(req.query.category ?? '').trim();
if (category.length > 80) throw new ValidationError('Category is too long');
const sql = `SELECT sku, name FROM inventory
WHERE category = $1 AND active = true`;
return (await pool.query(sql, [category])).rows;
}
The length check is useful for a product contract and resource limits. It is not the control that stops SQL injection. Parameter binding is. These two controls solve different problems. A later UI that renders name from the database must still treat it safely for HTML. The source-to-sink method encourages reviewers to continue tracing beyond the first safe boundary when the value reaches another interpreter.
Dynamic SQL structure needs a different decision
Some products let a user choose a sort order. A SQL placeholder generally represents a value, not a column identifier or a whole ORDER BY clause. Do not interpolate the raw sort choice. Map it to a fixed set of allowed fragments:
const orderBy = req.query.order === 'name' ? 'name ASC' : 'created_at DESC';
const result = await pool.query(
`SELECT sku, name FROM inventory WHERE active = $1 ORDER BY ${orderBy}`,
[true]
);
Here orderBy is chosen from two strings owned by the server, so the caller cannot introduce arbitrary SQL syntax through it. Reviewers should verify that every branch is a fixed constant, not a partial concatenation of caller data. The rule is not "never use string interpolation anywhere near SQL"; it is "do not allow untrusted data to determine SQL syntax outside an intentional, constrained mapping."
Choose the sink that matches the feature
The feature displays plain text. How can the implementation avoid asking the browser to interpret markup at all?
const message = await fetchMessage();
const element = document.querySelector("#message");
element.innerHTML = message.body;
Reveal the safer implementation
const message = await fetchMessage();
const element = document.querySelector("#message");
element.textContent = message.body;
textContent expresses the plain-text contract directly. If the product deliberately supports rich HTML, it needs a maintained HTML sanitizer and a clearly defined policy. Reusing an HTML control in a JavaScript, URL, or CSS context is not an equivalent defense.
HTML sink: the output context determines the control
HTML is not one uniform context. Text between tags, an attribute value, a URL inside an attribute, a JavaScript string inside a script, a CSS value, and raw HTML fragments are interpreted under different rules. Encoding a value for text content does not necessarily make it safe inside href, style, or a script block.
The safest design often avoids a dangerous context entirely: render ordinary user text as text, build URLs from trusted origins and validated components, and use framework APIs instead of assembling markup strings.
Consider this invented client code:
const title = new URLSearchParams(location.search).get('title') ?? '';
document.querySelector('#heading').innerHTML = title;
The URL query parameter is a direct source. innerHTML is an HTML sink. The browser will parse the chosen text as markup, so the code needs a different sink if it is displaying a title:
document.querySelector('#heading').textContent = title;
This change uses the browser's text semantics. It is clearer and less error-prone than writing a custom function to remove a list of tags. If the title is later copied into a URL attribute, another review is needed for that destination. The OWASP XSS Prevention Cheat Sheet documents context-specific output encoding, safe sinks, and the limits of relying on Content Security Policy as the only defense.
Stored data and encoded data can still change context
Suppose a comment is encoded for display as text and then stored with < sequences. Another component might decode it and insert it as raw HTML. Or a stored profile value might be safe in a text node but unsafe when used to build a URL. The lesson is not that encoding is unreliable; it is that encoding must match the final output context and be applied at the right boundary.
Storing a permanently "sanitized" string can be fragile when different consumers need different representations. Prefer storing the intended data and using a safe rendering path for each consumer.
An HTML sanitizer has a narrower legitimate role: the product wants to permit some markup, such as bold text or links, while excluding active content. A reviewer should inspect the sanitizer configuration, allowed tags and attributes, URL scheme handling, update practice, and every place where its output is consumed. Even a well-chosen sanitizer does not grant permission for a user to see another user's note. Keep content safety and authorization separate in the review.
A practical source-to-sink worksheet
Use this worksheet for each suspected flaw. Fill it from code, not memory:
Actor and capability:
Source and who controls it:
Entry point where it first appears:
Transformations in execution order:
Storage or asynchronous handoffs:
Final sink and interpreting component:
Security rule at that sink:
Control that enforces the rule:
Evidence that the path is reachable:
One negative case or safe reproduction:
Unknowns and assumptions:
For a SQL path, the rule may be "the search term remains a bound value and cannot alter the query structure." For an HTML path, the rule may be "the submitted note appears as text, not executable markup, to another viewer." For either path, include the actual file handoffs. If a value is transformed in several places, write them in order. If you cannot prove a transformation's behavior, mark it as unknown and inspect the implementation.
How to avoid stopping too early
The most common premature stops are after a validator, after a database read, and after a JSON response. A validator may only check length. A database read may retrieve stored attacker input. A JSON response may be rendered unsafely by a client. Follow the value until the sensitive interpreter or authority decision. Also avoid stopping at a framework label. React usually escapes ordinary text interpolation, but dangerouslySetInnerHTML explicitly changes that behavior.
An ORM usually binds values in normal query-builder operations, but raw SQL escape hatches can assemble strings. The reviewer must identify which API path the application actually uses.
A value is trimmed, lowercased, and URL-decoded before entering a SQL string. Which observation matters most?
Practice: trace input to a database or HTML renderer
Complete the interactive lecture, Trace untrusted input to a dangerous sink. Follow a value through the compact code explorer, compare HTML and text rendering, inspect SQL binding, and pass its final check. The XSS challenge below is also required.
The exercise below is a new teaching example, not the live challenge. A support portal accepts a ticket subject and shows it in a staff dashboard. Staff can also filter tickets by subject. Read both flows before answering. Assume an external customer can create a ticket and a staff member can view the dashboard.
routes/tickets.ts
router.post('/api/tickets', async (req, res) => {
const subject = String(req.body.subject ?? '').slice(0, 160);
const ticket = await ticketService.create(subject);
res.status(201).json({ id: ticket.id });
});
router.get('/api/tickets', requireStaff, async (req, res) => {
const search = String(req.query.search ?? '').trim();
const tickets = await ticketService.search(search);
res.json({ tickets });
});
services/ticketService.ts
export async function create(subject: string) {
return tickets.insert({ subject });
}
export async function search(search: string) {
return tickets.searchBySubject(`%${search}%`);
}
storage/tickets.ts
export async function insert(ticket: { subject: string }) {
return db.ticket.create({ data: ticket });
}
export async function searchBySubject(pattern: string) {
return db.ticket.findMany({ where: { subject: { contains: pattern } } });
}
web/StaffDashboard.tsx
export function StaffDashboard({ tickets }: { tickets: Ticket[] }) {
return (
<ul>
{tickets.map(ticket => (
<li key={ticket.id} dangerouslySetInnerHTML={{ __html: ticket.subject }} />
))}
</ul>
);
}
On paper, draw two traces: customer subject to the staff HTML renderer, and staff search to the database query. For each trace, record source, transformations, storage if any, sink, and the security control you would expect. Then decide which shown path provides evidence of an unsafe interpretation and which needs more knowledge of the ORM's behavior. Finally, identify a product behavior issue in the search construction even if the ORM binds values safely.
Compare your reasoning
The customer controls subject. The route truncates it to 160 characters, the service passes it through, and the repository stores it. The staff dashboard later reads the stored subject and passes it to dangerouslySetInnerHTML. That is an HTML sink that intentionally treats the string as markup. Length truncation does not prevent browser interpretation; the shown code provides evidence of a stored XSS risk for staff viewers.
The safe direction for a plain-text subject is ordinary React text interpolation, such as <li>{ticket.subject}</li>, with a separate authorization review for who may view the ticket.
The staff member controls search. The route trims it, the service adds wildcard characters, and the repository uses an ORM query builder. The shown code does not assemble raw SQL text, so it does not by itself establish SQL injection. To assess the database operation fully, confirm the ORM API's parameter-handling semantics and any raw-query escape hatches in the real application.
There is also a likely product behavior issue: many ORM contains operators already implement substring matching, so adding % characters may search for literal percent signs or otherwise change matching unexpectedly. Verify the ORM's documented behavior and remove the manual wildcard construction if it is not part of the API contract. Security review should not label a functional mismatch as injection without evidence.
This exercise also shows why sources can be associated with different actors. The external customer supplies stored content. The staff member supplies a search term. The HTML sink affects staff viewers, while the query operates under staff access. Keeping the actors separate prevents you from writing a vague finding such as "untrusted input in tickets" that hides who can exploit which path.
Apply the method to the XSS challenge
Now open the free XSS code review challenge and find the XSS flaw. Do not assume the teaching example uses the same rendering technology or file layout. Trace the chosen value from its earliest controllable source to the browser-facing sink. Write down every transformation you see. State whether the application intends to display plain text or limited rich content, then explain which output context the code actually uses and what control is missing there.
Before selecting a line, ask: could another user encounter this rendered value? Is the value direct from the current request or retrieved from storage? Does a framework's ordinary escaping path apply, or does the code opt into raw HTML? A vulnerability name alone is not evidence; your source-to-sink map is. The lecture does not disclose the challenge's answer, so you can use the live case as an independent review.
Common mistakes in source-to-sink review
Treating a database value as trusted. A database can persist attacker-controlled content. Follow the write path if you need to know who chose it. The ultimate rendering context still matters.
Calling every transformation sanitization. trim(), toLowerCase(), JSON.parse(), and length limits have specific effects. None is a general-purpose guarantee that data cannot become SQL syntax or HTML markup.
Using one defense for every sink. Parameter binding protects SQL value positions, not HTML. HTML text encoding protects a particular output context, not SQL. Authorization determines who may access a resource, not how its text is interpreted.
Stopping at a JSON response. The client may later put returned content into innerHTML, a template, or a URL. Follow to the final consumer when the question is browser execution.
Assuming a framework always protects you. Default APIs may be safe for common cases, but raw HTML, raw SQL, template escape hatches, and custom renderers can change the interpretation. Identify the exact API being used.
Overclaiming exploitability. A suspicious source and sink are not enough if the path cannot be reached by an attacker or a strong control is applied between them. Record reachability, prerequisites, and unknowns. A precise incomplete finding is better than an unsupported dramatic one.
Which source-to-sink note is most useful in a review?
exec() is a sink, but its meaning depends on the language
The next lecture examines dangerous code patterns in detail, including dynamic execution. Before reaching it, practice the source-to-sink method on a function named exec(). The name alone is not enough to know which interpreter receives the value. In Python, the built-in exec() function parses and executes Python code. In Node.js, child_process.exec() launches a shell command. Both can be dangerous when an actor controls the program text, but their syntax, defenses, and impact analysis differ.
A reviewer should identify the language, imported symbol, and exact call before writing "command injection" or "code execution" in a finding.
Consider an invented Python reporting tool that lets a user choose a simple display format. The product intends to support short and full, but a developer builds a Python assignment from the request instead:
def format_report(request, report):
style = request.args.get("style", "short")
scope = {
"report": report,
"result": None,
"render_short": render_short,
"render_full": render_full,
}
exec("result = render_" + style + "(report)", scope)
return scope["result"]
The direct source is the style query parameter. String concatenation is the transformation. The sink is Python's exec(), where the resulting string is parsed as Python statements. The intended output is a formatted report, but the code gives caller-selected text a chance to affect executable syntax. The defect is not repaired by checking that style is a string or by HTML-encoding it. Those controls do not determine what Python code exec() runs.
The simplest safe direction is to avoid dynamic execution and map the allowed style names to functions owned by the application:
FORMATTERS = {
"short": render_short,
"full": render_full,
}
def format_report(request, report):
style = request.args.get("style", "short")
formatter = FORMATTERS.get(style)
if formatter is None:
raise ValueError("Unsupported report style")
return formatter(report)
This design changes the security property. The caller can choose one of two capabilities, but cannot supply Python program text. In a real review, also inspect whether render_short and render_full are safe for the report data they receive and whether the caller is authorized to see the report. Avoid treating the formatter map as proof of every other boundary. The Python documentation explicitly warns about executing untrusted input; it also explains what exec() accepts.
You do not need to memorize a particular payload to recognize the unsafe data-to-code transition.
Now consider Node.js code that constructs a command to generate a thumbnail:
import { exec } from 'node:child_process';
function createThumbnail(filename: string) {
exec(`convert uploads/${filename} thumbnails/${filename}.png`, callback);
}
Here the value becomes part of a shell command string. The shell, not the JavaScript parser, interprets that string. A safe design may avoid an external command by using an image-processing library. If a command-line program is necessary, use a fixed executable with separate argument values, such as execFile or spawn without a shell by default, and validate that the selected file stays inside the intended upload area.
Separate arguments prevent shell metacharacters from becoming shell syntax; they do not automatically prevent an argument from being interpreted as an option by the invoked program or from naming another user's file. The Node.js child process documentation and OWASP OS Command Injection Defense Cheat Sheet explain these distinct layers.
The two examples share a review method: identify who controls the source, trace how the string is assembled, name the interpreter at the sink, and replace the data-to-code transition with a narrow application-owned operation. They do not share an interchangeable escaping function. If you see exec() in an unfamiliar challenge, first resolve its definition or import. In the next lecture, you will use that habit to investigate a remote-code-execution case without assuming every exec() call is equivalent.
A second trace: one field, multiple browser contexts
Even within HTML rendering, a field can have more than one destination. Suppose a profile displayName is shown as heading text, placed in an image alt attribute, added to a downloadable filename, and included in a share link. A safe implementation for the heading does not prove the other uses safe. The profile field may be stored in the database, then copied into several templates. Build a separate source-to-sink trace for each destination.
The common source is useful context, but every sink has its own interpretation and control.
For heading text, use a framework's ordinary text interpolation or a DOM text API. For an attribute, use a framework binding that creates an attribute value rather than hand-assembling markup, and check whether the attribute has special semantics. alt is text; href and src are URLs and need destination rules as well. For a filename, consider path separators, filesystem permissions, and download headers.
For a share link, build the URL from a trusted base and a properly encoded component, then check whether sharing the chosen object is authorized. The security property is specific to the final consumer, not to a one-time label of "safe input."
This is why source-to-sink review often branches like a tree. Start at the write path to establish provenance. At the read path, list every consumer. A value may be harmless in one consumer, unsafe in another, and irrelevant to a third. If a scanner flags the same field in many places, group the paths by interpreter and control rather than filing duplicate generic findings.
If a developer fixes one template by changing innerHTML to textContent, keep tracing the other templates before closing a broader issue. Conversely, do not claim that every use of the field is vulnerable because one raw HTML sink exists.
A review notebook for a branching value
For the note example earlier, make a small table with the columns source, transformation, sink, expected meaning, and actual meaning. The source is the member-controlled note body. Storage is a handoff, not a trust upgrade. The JSON API can carry the body as data; the React text component can display it as text; the raw HTML preview can cause the browser to parse it as markup. Mark the point where meaning changes.
Then add a column for who receives the result. An XSS path viewed only by its author has a different exposure pattern from a stored note opened by another member or an administrator. Both need analysis, but realistic impact depends on the viewer and the privileges available in that browser session.
Use the same table for SQL search. The term begins as a query parameter. Trimming and wildcard wrapping alter the search value. The repository either binds it as a value or concatenates it into SQL text. Only the latter gives the term a path to query grammar. The database returns rows, which may then be rendered.
If a returned title was originally entered by a user, start a second trace from that title to its HTML consumer. One request can contain several independent source-to-sink paths; a complete review names each without merging them into one ambiguous vulnerability claim.
Key terms
- Source: A value an actor can influence, directly or through an earlier write or external input.
- Sink: An operation where that value can affect a sensitive interpreter, resource, output, or decision.
- Data flow: The path and transformations a value takes through code and storage.
- Provenance: The origin of a value and the actor or component that could control it.
- Second-order path: A path where input is stored or transformed first and becomes dangerous in a later operation.
- Validation: Checking whether input fits a defined type, range, format, or business contract.
- Normalization: Converting input to a consistent representation for comparison or processing.
- Output encoding: Representing data so an output interpreter treats it as data in a specific context.
- HTML sanitization: Restricting allowed markup when a product intentionally supports rich HTML content.
- Parameter binding: Passing SQL values separately from fixed query syntax.
- XSS: A failure to keep user-controllable content from being interpreted as active browser content in a context where it should be data.
Frequently asked questions
If I validate input at the API, do I still need output encoding?
Usually yes when that input can reach an HTML output. Validation answers whether a value fits the application's input contract. Output encoding or a safe text renderer answers how the browser interprets that value in a particular context. A valid free-form name can contain punctuation that needs safe rendering. Tight allowlists can reduce risk for some fields, but they do not replace the correct output sink for general text.
Can I sanitize all input once when it is stored?
That is rarely a complete strategy. Different future consumers may need different encodings and policies. A value safe for an HTML text node may not be safe for a URL, SQL construction, or JavaScript string. Store data in the intended form and apply controls at each relevant sink. If the product intentionally accepts rich HTML, review the sanitizer and its policy separately.
Is `dangerouslySetInnerHTML` always a vulnerability?
No. It is a raw HTML sink that requires an appropriate trust and sanitization story. Static server-owned markup may be safe; carefully sanitized limited rich content may be acceptable. Untrusted text passed directly into it is a strong warning. The reviewer needs provenance, reachability, and evidence about the sanitizer or policy before making a final claim.
Does using an ORM mean SQL injection is impossible?
No. Normal query-builder value APIs often bind values, but raw-query methods, dynamic identifiers, and unsafe string construction can reintroduce injection. Inspect the exact API and its documented behavior. Do not report SQL injection solely because input reaches an ORM query; trace whether input can alter query syntax.
Primary references and next lesson
- OWASP Cross Site Scripting Prevention Cheat Sheet explains safe sinks and context-specific output controls.
- OWASP SQL Injection Prevention Cheat Sheet explains prepared statements and fixed query structure.
- OWASP Input Validation Cheat Sheet explains input contracts and allowlist validation.
- MITRE CWE-79 describes improper neutralization in web page generation.
- MITRE CWE-89 describes improper neutralization of special elements in SQL commands.
Continue with Recognizing Dangerous Code Patterns. That lecture expands the sink model to dynamic execution, deserialization, filesystem operations, and other code that grants data new authority.