Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

Your service accepts rich-text HTML from users and shows it to others. How would you sanitise it with jsoup, and what remains risky?

We pass the user's HTML through Jsoup.clean(dirty, safelist), where the safelist names the only tags, attributes and URL protocols allowed, for example a customised Safelist.basic() that allows links with only http, https and mailto. Everything else, including script tags, event handler attributes and javascript: URLs, is removed. What remains risky is using the result in the wrong context, sanitiser bypasses in old library versions, and the absence of a second defence, so we still encode output in templates, add a Content Security Policy and keep jsoup up to date.

Why this question is asked

Comments, product reviews, forum posts and support tickets often allow rich text, which means the server receives HTML written by users and later shows it to other users. If we store and display it as it arrives, any user can run JavaScript in other users' browsers. This is called stored cross-site scripting, or XSS, and it can steal sessions or act on the victim's behalf. Interviewers ask this scenario because the obvious fix, removing script tags, is badly incomplete, and because a good answer knows the limits of sanitising. In this answer, we will recap how HTML carries scripts, see how jsoup's cleaner works, build a safelist for our use, and then go through what is still risky and how we cover it.

1A Quick Recap: How HTML Carries Scripts

Script tags are only the most visible way to run code. A browser will also run JavaScript from event handler attributes such as onerror and onclick, from javascript: URLs in href and src, from some SVG and MathML constructs, and from style tricks in older browsers. Attackers also use malformed markup that parses differently than a naive filter expects.

XML
<script>steal(document.cookie)</script>
<img src="x" onerror="steal(document.cookie)">
<a href="javascript:steal(document.cookie)">click me</a>
<svg><animate onbegin="steal(document.cookie)"/></svg>

So a filter that searches for the word script, or a regular expression that strips tags, will always miss something. The safe approach is the opposite one: parse the HTML properly, then keep only what we explicitly allow and drop everything else. That is called allow-listing, and it is what jsoup's cleaner does.

2How Jsoup.clean() Works

Jsoup.clean() parses the input into a DOM with the same rules a browser uses, then walks the tree and copies only the elements, attributes and protocols that the safelist permits into a new, clean document. Finally it serialises the clean tree back to HTML. Because the output is rebuilt from a parsed tree, broken markup cannot sneak through: whatever comes out is well-formed HTML made only of allowed parts.

Java
String dirty = "<p>Nice post <b>really</b><script>steal()</script>"
+ "<img src=x onerror=steal()>"
+ "<a href=\"javascript:steal()\">x</a>"
+ "<a href=\"https://example.org\" onclick=\"steal()\">site</a></p>";
String clean = Jsoup.clean(dirty, Safelist.basic());
System.out.println(clean);
// <p>Nice post <b>really</b><a rel="nofollow">x</a><a href="https://example.org" rel="nofollow">site</a></p>
// script removed, img removed (not in basic), javascript: href dropped, onclick dropped
Step throughWhat Jsoup.clean() does with user HTML
  1. Parse the input like a browserbroken markup is repaired first
  2. Is the tag in the safelist?
    YesKeep the tagNoDrop it, keep its text if safe
  3. Is the attribute allowed on this tag?
    YesKeep the attributeNoDrop the attribute
  4. Is the URL protocol allowed?
    YesKeep the URLNoDrop the attribute
  5. Serialise the clean treeadd enforced attributes such as rel=nofollow

5 steps in order. Play them, or step through them one at a time.

Anything not explicitly allowed is removed.

Notice that the javascript: link survives as an a tag but loses its href, because javascript is not an allowed protocol. The onclick attribute disappears because no safelist allows event handlers unless we add them. Safelist.basic() also adds rel="nofollow" to links, which tells search engines not to reward links posted by users.

A note on names: older jsoup versions called this class Whitelist. It was renamed to Safelist in jsoup 1.14 and the old name was later removed, so code written against old tutorials may need the rename (check your version). jsoup offers several ready-made safelists, from none() for plain text only, through simpleText() and basic(), to basicWithImages() and relaxed().

3Building a Safelist for Our Rich Text

The ready-made safelists are a starting point. We should allow exactly what our editor produces and no more. If our editor only offers bold, italics, lists, quotes, code and links, the safelist should say so. We also restrict link protocols, because basic() allows ftp too, which we do not need.

Java
Safelist comments = new Safelist()
.addTags("p", "br", "b", "strong", "i", "em", "ul", "ol", "li", "blockquote", "code", "pre", "a")
.addAttributes("a", "href", "title")
.addProtocols("a", "href", "http", "https", "mailto")
.addEnforcedAttribute("a", "rel", "nofollow noopener");
String stored = Jsoup.clean(userInput, comments);
Jsoup.clean("<a href='mailto:me@example.org'>mail</a>", comments);
// <a href="mailto:me@example.org" rel="nofollow noopener">mail</a>
Jsoup.clean("<a href='data:text/html;base64,PHNjcmlwdD4='>x</a>", comments);
// <a rel="nofollow noopener">x</a> data: is not an allowed protocol

The reason we restrict protocols is that an attribute can be allowed while its value is still dangerous. href is a perfectly normal attribute, but href="javascript:..." or a data: URL can run code. With addProtocols, jsoup checks the scheme of every URL in that attribute and drops the attribute when the scheme is not on the list. If we ever allow img, we restrict its src protocols the same way.

Where should we clean: when the HTML arrives, or when we show it? Cleaning on input means the database holds only safe HTML, and every reader of the data benefits. But we should also keep the original if we may need it for audits, and re-clean when the safelist changes, because content stored under an older, looser safelist stays loose.

4What Remains Risky

Sanitising makes the HTML safe to place as HTML inside an element's body, and only there. If someone later puts the same string inside an attribute, inside a script block or inside a URL, the rules are different and the clean HTML can still break out. So the cleaned HTML goes into the body of an element and nowhere else, and all other user data in our templates is still encoded on output. Templating engines such as Thymeleaf encode by default with th:text; using th:utext, which inserts raw HTML, should be reserved for the one field we have sanitised, and every use of it should be reviewed.

XML
<!-- Thymeleaf -->
<div class="comment" th:utext="${comment.safeHtml}"></div> <!-- sanitised HTML, body context only -->
<span th:text="${comment.author}"></span> <!-- everything else: encoded -->
<!-- Never: user data in a script or attribute context -->
<script>var c = '[[${comment.safeHtml}]]';</script>

The second risk is the sanitiser itself. HTML parsing is complicated, and over the years bypasses have been found in many sanitisers, usually through unusual nesting, namespaces such as SVG and MathML, or differences between how the library and a browser parse the same bytes. We reduce that risk by keeping jsoup updated with our dependency scanner, by allowing as few tags as possible, since every extra tag is extra attack surface, and by not allowing svg or math at all.

The third measure is defence in depth: a Content Security Policy, a response header that tells the browser which scripts it may run. A policy such as script-src 'self' with no 'unsafe-inline' means that even if an injected inline script or event handler slipped through, the browser refuses to run it. It does not replace sanitising, but it turns many successful injections into harmless text.

5Follow-up questions

Why not just escape everything and render plain text?

That is the safest option and the right one when rich text is not needed: Safelist.none() or plain encoding with th:text. The question assumes users need formatting. A common middle ground is to accept Markdown, render it to HTML on the server, and then run the rendered HTML through the same jsoup cleaner.

Can I check whether input is already safe without changing it?

Yes, Jsoup.isValid(html, safelist) returns true only if cleaning would not remove anything. It is useful for rejecting a submission with a clear error instead of silently changing what the user wrote, though most products prefer to clean and save.

Does cleaning protect against CSS-based attacks?

Only if we do not allow the style attribute or style tags, and the safelists above do not. Allowing inline styles reopens a hard problem, since CSS can hide content, overlay fake buttons or load URLs, so it is better to offer a few fixed formatting options and map them to classes.

6Conclusion

In this answer, we saw that user HTML can run scripts through tags, event handlers and dangerous URLs, so filtering bad words never works and we must allow-list. Jsoup.clean() parses the input like a browser and rebuilds it from the safelist, and we customise the safelist to our editor's tags with only http, https and mailto links. We also saw what remains risky: placing clean HTML in the wrong context, bypasses in old sanitiser versions, and having only one defence, which we handle with output encoding, a Content Security Policy and regular updates.

What to say in the interviewAbout 80 seconds aloud

Open with

I would sanitise with jsoup's cleaner, using an allow-list rather than trying to remove bad things. Jsoup.clean takes the user's HTML and a Safelist; it parses the input the way a browser would and rebuilds it from only the allowed tags, attributes and URL protocols.

Then, if they want more

I would start from Safelist.basic, which was called Whitelist before jsoup 1.14, and customise it to exactly what our editor produces, for example paragraphs, bold, italics, lists, quotes, code and links, with href limited to http, https and mailto and rel nofollow enforced. That removes script tags, event handlers like onerror, and javascript or data URLs.

I would clean on input so the database holds safe HTML, and re-clean if the safelist changes. What remains risky: the clean HTML is only safe in an element body, so I would never put user content inside attributes or script blocks, and templates still encode everything else, with raw HTML output limited to the sanitised field.

Sanitisers have had bypasses over the years, so I keep jsoup updated and allow no SVG or MathML. And as defence in depth I would add a Content Security Policy without unsafe-inline, so an injection that slips through still cannot run.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your service accepts rich-text HTML from users and shows it to others. How would you...": https://scrivio-interview-library.netlify.app/java/xml-processing/9c59e7d7ca/