Guidance for AI-assisted work in this repository. This is a security-critical library. When in doubt, do less and ask a maintainer.
OWASP Java HTML Sanitizer (com.googlecode.owasp-java-html-sanitizer:owasp-java-html-sanitizer). Takes attacker-controlled HTML and produces HTML that is safe to embed in a web page. Allowlist policies are built with HtmlPolicyBuilder and compiled into thread-safe PolicyFactory instances.
This is a multi-module Maven build:
owasp-java-html-sanitizer/— the library. Core code:owasp-java-html-sanitizer/src/main/java/org/owasp/html/. Tests:owasp-java-html-sanitizer/src/test/java/org/owasp/html/.src/main/java9/module-info.javais the JPMS module descriptor. A second compiler execution compiles it for Java 9 intoMETA-INF/versions/9/of the multi-release JAR, which is how a Java 8 JAR carries one; it exportsorg.owasp.htmlonly.src/it/jpms-consumer/is a small module that./mvnw verifycompiles and runs against the packaged JAR to check that the descriptor is read and the shim stays encapsulated. Those two are the only Java 9 sources in the library module.src/it/java8-consumer/is a Java 8 program that./mvnw verifyruns against the packaged JAR, and CI on a Java 8 runtime, to check every class's bytecode level and that each runtime picks its shim.java8-shim/,java10-shim/— in-repo shims that let the Java 8 library use newer JDK collection APIs when running on Java 10+. Both are inlined into the library JAR by the shade plugin and do not appear in the published POM.java10-shimis the only module that may use Java 9 and 10 APIs (maven.compiler.release10). Nothing uses anything newer. Every class outsideMETA-INF/versions/of the published JAR must be Java 8 bytecode, because Java 8 consumers reject dependencies with build rules such asenforceBytecodeVersion; newer bytecode goes only underMETA-INF/versions/N/, asjava10-shim's does.empiricism/— in-browser experiments that record how real browsers nest and balance tags. They generateHtmlElementTablesCanned.javain the library's core package. Never hand-edit that file: change the probe orempiricism/canned-data.jsonand runempiricism/rebuild.sh.examples/,docs/— samples and documentation. Not part of the shipped artifact.
Primary threat: XSS, including mutation XSS (mXSS), namespace confusion, and browser parser quirks.
- Build and run all tests:
./mvnw clean verify(ormvn clean verify). This is what CI runs. - Tests only:
./mvnw test - Always build from the repo root across the whole reactor. Building the library module alone (
-pl owasp-java-html-sanitizer) fails to resolve the shim modules unless they were installed first; add-amif you must narrow the build. - Building requires JDK 11 or newer (enforced by the Maven Enforcer plugin); CI runs on JDK 11, 17, 21, and 25. Prefer
./mvnw, which pins a Maven version that satisfies the enforcer. - The library targets Java 8 source and bytecode (
maven.compiler.release8) regardless of the JDK used to build, and test code is compiled at the same level. Do not use newer language features or APIs in either. The module descriptor and the modular consumer check are the exceptions, compiled for Java 9 and nothing newer. - Tests use JUnit 5 (Jupiter). Do not add JUnit 4 style tests.
- Fuzzer tests (
*FuzzerTest.java) and the AntiSamy test suite are part of the normal test run. The fuzzers seed from the clock and report the seed on failure; reproduce with-Djunit.seed=<seed>. A fuzzer failure is a real bug, never something to re-run until it passes. - All tests must pass before proposing any change. No exceptions.
Hard rules. Never violate them, never refactor around them.
- Allowlist only. Everything is denied unless a policy explicitly allows it. Never introduce denylist or strip-known-bad logic.
- Default deny for anything new. New elements, attributes, URL protocols, or CSS properties are unsafe until a policy author explicitly allows them.
- Output must be safe in every HTML parsing context, not just the happy path: foreign content (SVG, MathML), raw-text and RCDATA elements (
script,style,title,textarea,noscript,xmp,iframe,plaintext), comments, CDATA.HtmlTextEscapingModeis the sanitizer's table of these. Browsers treatnoscriptas raw text when scripting is on even though the sanitizer deliberately does not; CVE-2025-66021 exploited that mismatch. - Case sensitivity matters. SVG and MathML element and attribute names are not lower-cased (see the mixed-case foreign name sets in
HtmlLexer); SVGtextAreais distinct from HTMLtextarea. Preserve this. Names with a namespace prefix, such asxlink:href, also keep their case, but browsers lower-case every attribute name, so any check that decides how an attribute is treated (URL guard, style guard) must match the name in any case. - Encoding and rendering are part of the security boundary. Changes to
Encoding,HtmlStreamRenderer,TagBalancingHtmlStreamEventReceiver,HtmlTextEscapingMode, entity handling, or serialization are security changes and require adversarial tests. - The prepackaged policies in
Sanitizersare published safety promises. Never widen what they allow. - Round-trip safety: sanitized output, re-parsed by a browser, must not mutate into a different, unsafe DOM (mXSS).
- Any input terminates, in bounded stack and in time and memory linear in its size.
sanitize()must never throw, and never let aStackOverflowErrorout, for input of any shape. Recursion whose depth follows the input is forbidden: bound it with a small constant and drop what exceeds the bound, asCssGrammar.MAX_FUNCTION_DEPTHdoes, or walk with an explicit stack. Time and memory may grow only linearly with the input, and output only by a constant factor; the tag balancer's quadratic paths, and its formatting reconstruction that turned 70 KB into 17 MB, were both found the hard way. Memory in proportion to the input is unavoidable, so an input too big for the heap can still exhaust it; bounding input size is the caller's job, and that alone is not a bug. A crash, a hang, or a blow-up on hostile input is a denial of service and is handled as a vulnerability.
- Small, single-purpose changes only. No drive-by refactors of parser, policy, or renderer code.
- Normalization after validation, including characters the renderer elides, must not create syntax the policy would reject. Test values supplied by event callers and preprocessors as well as parsed HTML; do not rely on the lexer to make policy inputs safe.
- Any change touching parsing, policy enforcement, rendering, encoding, URL handling, or CSS handling requires new regression tests with hostile payloads, not just benign inputs. Where the code walks the input recursively, keeps state per token, or re-scans what it has already seen, one of those tests runs at hostile size, hundreds of thousands of nested or repeated tokens, and shows no error and linear time. Size it to pass with the test JVM at
-Xmx256m(./mvnw test -DargLine=-Xmx256m): surefire sets no heap, so a test needing a gigabyte passes CI and fails on smaller machines. - Code on the input path must be linear for every
Lista caller can pass, not only theLinkedListthe sanitizer builds: preprocessors and policies can hand on anArrayList. Walk lists with iterators, never by index, and drop items by compacting and truncating once, never by removing each where it stands. A hash index over strings from the input is keyed byStringitself, never by aList, array or other non-Comparablecomposite: an author can choose many strings with one hash code, andHashMapkeeps such a bucket searchable in logarithmic time only when its keys areComparable. - Never weaken, delete, or loosen an existing test to make a change pass. A failing security test means the change is wrong.
- No new dependencies. The published library has zero runtime dependencies. The only compile-time dependency is
spotbugs-annotations(providedscope), which brings in JSR 305 (com.google.code.findbugs:jsr305) for thejavax.annotationnullability and concurrency annotations. Both are annotations only and are not shipped. Test-scope dependencies (JUnit, commons-codec, validator.nu htmlparser) must stay test-scope. Keep it that way. - Follow the Contributing section of
README.md: open an issue first to reach the maintainers, and include both positive and negative tests in any PR that changes behavior or adds functionality. - Preserve public API compatibility. This library is embedded in a very large number of applications.
- Match the surrounding code: 2-space indentation, no tabs, and the same header on every new file, including
SPDX-License-Identifier: Apache-2.0 OR BSD-2-Clause. - Record user-visible changes as a bullet under the
* Next releaseheading at the top ofchange_log.md. The release workflow turns that heading into the release entry; do not add release headings or edit released entries. - Releases are maintainer-driven. Do not modify the project version in any
pom.xml,SECURITY.md,docs/vulnerabilities.md,docs/maven.md,.github/workflows/release.yml, or the JReleaser configuration in the parentpom.xml. - In workflow YAML, quote every version and other value that must stay a string. Unquoted,
20000101.0is a number and reaches the shell as20000101.
- If you find a possible bypass while working, report it privately per
SECURITY.mdso a GitHub security advisory can coordinate the fix. - Regression tests for a vulnerability land publicly only after the advisory and fixed release are out.
Use these as targets when touching parser, policy, or renderer code:
- Policy enforcement gaps on specific elements, e.g.
styleinsideoptionandselect: CVE-2021-42575 (docs/cve202142575.md) - Raw-text and RCDATA content handling (
style,noscript, and friends): CVE-2025-66021 (advisory GHSA-g9gq-3pfx-2gw2) - mXSS via serialize and re-parse differences
- SVG and MathML namespace and case tricks, and names the HTML parser rewrites: outside foreign content an
imagestart tag buildsimg, so the element allowlist must not let one name through as the other - Gaps between the policy's model of the output context and the browser's, which the
imagecheck trusts: names the renderer writes in place of the policy's (xmpaspre), receivers that hide the renderer from the policy,templatecontent (an unknown parent context, or a table part switching its insertion mode), and an element kept inside a same-named one whose content a browser reads as text (title,textarea,noscript,noembed,noframes), whose end tag ends the outer element early javascript:,data:, and scheme-relative URLs in allowed attributes, including namespaced URL attributes such as SVGxlink:hrefin any case (GHSA-643j-x48g-g86p), URL attributes under another name or holding a list of URLs, such asimagesrcsetandping(GHSA-x759-2xw8-gp4m),url(...)in SVG presentation attributes such asfill(GHSA-76cc-622x-jwm4), and SVGsetandanimate, whoseattributeNamemakes them write their values into another attribute (GHSA-ppfr-7xq6-p6c2)- Entity and encoding edge cases: malformed entities, entities without semicolons, null bytes, mixed case, nested and unbalanced tags
- Denial of service: unbounded recursion over nested CSS functions (GHSA-x6fc-6qh4-g3wr), quadratic passes over one tag carrying many attributes, with and without a change listener (GHSA-47x2-9gq9-jg3m), quadratic tag-balancer paths and unbounded formatting reconstruction (release 20260921.1, #490)
- Full history:
docs/vulnerabilities.md
When a bug, a vulnerability, or a review finding shows that a rule was missing here, add the rule, judiciously: one that would have prevented the mistake, stated once, in the section it belongs to, in the voice of its neighbours. Do not log the incident; change_log.md, docs/vulnerabilities.md and the git history hold that. Do not add a rule for a one-off that no rule would have caught, and do not restate a rule that is already here.