

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Injection
incomplete
2: Fixing SQL Injection
incomplete
3: Injection Beyond SQL
incomplete
4: Safe Validation and Sanitization
incomplete
5: When to Sanitize
incomplete
6: Unsafe Archive Extraction
incomplete
7: Safe Archive Extraction
incomplete
8: LLM Prompt Injection
incomplete
9: Limiting Tool Calls
incomplete
10: Narrow Tool Interfaces
incomplete
11: File Upload Security
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Of course, there are times when sanitization makes sense. For example, you might want to remove trailing and leading whitespace from the username input silently, as most users expect that behavior. But you still should have a validation step that rejects invalid ones.
For example, you might use it when:
\n with <br> in HTML)Here's a "create comment" endpoint that validates input, sanitizes it to a small allowlist of HTML tags, and saves it:
app.post("/comments", (req: Request, res: Response) => {
const { content } = req.body;
// validate: string, not too long
if (typeof content !== "string" || content.length > 280) {
return res.status(400).json({ error: "Invalid content" });
}
// sanitize: strip all tags except for bold and italics
const sanitizedContent = sanitizeHtml(content, {
allowedTags: ["b", "i", "em", "strong"],
allowedAttributes: {},
});
// re-validate: not empty after sanitization
if (sanitizedContent.trim().length === 0) {
return res.status(400).json({ error: "Empty content" });
}
saveComment(sanitizedContent); // Error handling omitted for brevity
res.status(201).json({ message: "Comment saved" });
});
Notice that validation happens first, and sanitization is tightly scoped.
Bearly Secure validates review bodies, but preserves leading and trailing whitespace. Sanitize review text by trimming only its outer whitespace.
With Bearly Secure still running, run and submit the CLI tests from the project root.