Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/main/java/com/hubspot/jinjava/lib/filter/XmlAttrFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
Expand Down Expand Up @@ -37,6 +38,11 @@
)
public class XmlAttrFilter implements Filter {

// See https://html.spec.whatwg.org/#attribute-name-state Don't allow characters that would change the attribute name/value state
private static final Pattern ILLEGAL_ATTRIBUTE_KEY_PATTERN = Pattern.compile(
"[\\s/>=]"
);

@Override
public String getName() {
return "xmlattr";
Expand All @@ -53,6 +59,11 @@ public Object filter(Object var, JinjavaInterpreter interpreter, String... args)
List<String> attrs = new ArrayList<>();

for (Map.Entry<String, Object> entry : dict.entrySet()) {
if (ILLEGAL_ATTRIBUTE_KEY_PATTERN.matcher(entry.getKey()).find()) {
throw new IllegalArgumentException(
String.format("Invalid character in attribute name: %s", entry.getKey())
);
}
attrs.add(
new StringBuilder(entry.getKey())
.append("=\"")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

import static org.assertj.core.api.Assertions.assertThat;

import com.google.common.collect.ImmutableList;
import com.hubspot.jinjava.BaseJinjavaTest;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
Expand All @@ -27,4 +30,27 @@ public void testXmlAttr() {
assertThat(dom.select("ul").attr("id")).isEqualTo("list-42");
assertThat(dom.select("ul").attr("missing")).isEmpty();
}

@Test
public void itDoesNotAllowInvalidKeys() {
List<String> invalidStrings = ImmutableList.of("\t", "\n", "\f", " ", "/", ">", "=");
invalidStrings.forEach(invalidString ->
assertThat(
jinjava
.renderForResult(
String.format("{{ {'%s': 'foo'}|xmlattr }}", invalidString),
Collections.emptyMap()
)
.getErrors()
)
.matches(templateErrors ->
templateErrors.size() == 1 &&
templateErrors
.get(0)
.getException()
.getCause()
.getCause() instanceof IllegalArgumentException
)
);
}
}