diff --git a/internal-api/src/main/java/datadog/trace/api/appsec/route/JaxRsRequestMatch.java b/internal-api/src/main/java/datadog/trace/api/appsec/route/JaxRsRequestMatch.java new file mode 100644 index 00000000000..ff6bb49f713 --- /dev/null +++ b/internal-api/src/main/java/datadog/trace/api/appsec/route/JaxRsRequestMatch.java @@ -0,0 +1,85 @@ +package datadog.trace.api.appsec.route; + +import static java.util.Collections.singletonMap; +import static java.util.Collections.unmodifiableMap; + +import datadog.trace.api.internal.VisibleForTesting; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * What a JAX-RS framework matched for the current request, captured by its routing advice (Jersey + * {@code UriRoutingContext}, RESTEasy {@code ResteasyUriInfo}) and read by the JAX-RS decorators to + * render {@code _dd.appsec.normalized_route}: the decoded mount prefix served before the route and + * the path parameters bound from the URL. Immutable: it only holds copies, never framework objects. + */ +public final class JaxRsRequestMatch { + + /** + * Stored instead of a match once a sub-resource locator handled the request: its route is + * truncated, so the decorators set no normalized route and the capture advices keep this entry. + */ + public static final JaxRsRequestMatch SUBRESOURCE = new JaxRsRequestMatch(null, null); + + private final String prefix; + private final Map boundValues; + + private JaxRsRequestMatch(String prefix, Map boundValues) { + this.prefix = prefix; + this.boundValues = boundValues; + } + + /** + * @param rawBasePath raw (encoded) path of the framework's base URI, e.g. {@code /ctx/api/}, or + * null when there is none + * @param boundValues path parameters bound by the framework, by name; a {@link List} value (e.g. + * a {@code MultivaluedMap} entry) keeps its first element. Null or empty for none. + */ + public static JaxRsRequestMatch of(String rawBasePath, Map boundValues) { + return new JaxRsRequestMatch(RouteEncoding.decodePath(rawBasePath), copyOf(boundValues)); + } + + /** Decoded mount prefix (context path, servlet mount, application path), or null for none. */ + public String prefix() { + return prefix; + } + + /** Bound path parameters (first value per name), or null when none were bound. */ + @VisibleForTesting + Map boundValues() { + return boundValues; + } + + /** + * Presence of the optional parts of {@code template} from the bound values; {@link + * PresenceResolver#UNKNOWN} when the template has none (no allocation then). + */ + public PresenceResolver presenceFor(RouteTemplate template) { + return BoundValuesPresenceResolver.of(template, boundValues, null); + } + + private static Map copyOf(Map values) { + if (values == null || values.isEmpty()) { + return null; + } + if (values.size() == 1) { + Map.Entry entry = values.entrySet().iterator().next(); + return singletonMap(entry.getKey(), valueOf(entry.getValue())); + } + // initial capacity that holds every entry under the default 0.75 load factor, without a resize + Map copy = new HashMap<>(values.size() * 4 / 3 + 1); + for (Map.Entry entry : values.entrySet()) { + copy.put(entry.getKey(), valueOf(entry.getValue())); + } + return unmodifiableMap(copy); + } + + private static String valueOf(Object value) { + if (value instanceof List) { + List list = (List) value; + value = list.isEmpty() ? null : list.get(0); + } + return value == null ? null : String.valueOf(value); + } +} diff --git a/internal-api/src/main/java/datadog/trace/api/appsec/route/JaxRsRouteParser.java b/internal-api/src/main/java/datadog/trace/api/appsec/route/JaxRsRouteParser.java new file mode 100644 index 00000000000..709bfa4aeff --- /dev/null +++ b/internal-api/src/main/java/datadog/trace/api/appsec/route/JaxRsRouteParser.java @@ -0,0 +1,673 @@ +package datadog.trace.api.appsec.route; + +import static datadog.trace.api.appsec.route.RoutePart.catchAll; +import static datadog.trace.api.appsec.route.RoutePart.constrainedParam; +import static datadog.trace.api.appsec.route.RoutePart.literal; +import static datadog.trace.api.appsec.route.RoutePart.param; + +import datadog.trace.api.cache.DDCache; +import datadog.trace.api.cache.DDCaches; +import datadog.trace.api.internal.VisibleForTesting; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Function; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Turns a JAX-RS route (the class and method {@code @Path} values joined, as the JAX-RS decorators + * pass it to {@code withRoute}) into a {@link RouteTemplate}: + * + *
    + *
  • {@code {name}} and {@code {name: regex}}, with optional whitespace around the name, the + * colon and the regex: parameter {@code name}. The regex is skipped by counting braces and + * backslash escapes, never compiled, and may contain {@code /}; segments are only split on a + * {@code /} outside braces; + *
  • a regex that can match {@code /} (see {@link #acceptsSlash(String)}) makes the parameter a + * catch-all, e.g. {@code {path: .*}}; + *
  • everything else: static text. JAX-RS treats {@code %XX} in {@code @Path} as an escape, so a + * valid escape is decoded (as UTF-8) before the literal is encoded: {@code %c3%a9} and {@code + * é} both give {@code %C3%A9}, {@code %20} stays {@code %20}. The core always re-encodes + * literal text, so an escape of an unreserved character comes out decoded ({@code %7E} gives + * {@code ~}) and invalid UTF-8 gives U+FFFD. A {@code %} that does not start an escape is + * literal text ({@code %25}). + *
+ * + * Unbalanced braces, a closing brace outside a parameter, or an empty or invalid name give {@link + * RouteTemplate#NOT_EXPRESSIBLE}. Empty segments are ignored; a trailing {@code /} is kept. + */ +public final class JaxRsRouteParser { + + private static final Logger log = LoggerFactory.getLogger(JaxRsRouteParser.class); + + /** Routes are declared in code, so their cardinality is low; 256 bounds odd apps. */ + private static final int CACHE_CAPACITY = 256; + + private static final DDCache CACHE = + DDCaches.newFixedSizeCache(CACHE_CAPACITY); + + /** {@code literalStart} when no static text is pending. */ + private static final int NO_LITERAL = -1; + + private static final Function SAFE_PARSE = safely(JaxRsRouteParser::parse); + + private JaxRsRouteParser() {} + + /** + * Same as {@link #parse(String)} but backed by a bounded cache keyed by the route, for the + * request hot path. Never returns null or throws. + */ + public static RouteTemplate cached(String route) { + return cached(CACHE, route, SAFE_PARSE); + } + + @VisibleForTesting + static RouteTemplate cached(DDCache cache, String route) { + return cached(cache, route, SAFE_PARSE); + } + + @VisibleForTesting + static RouteTemplate cached( + DDCache cache, + String route, + Function producer) { + // null cannot be a cache key, and empty is not worth an entry + if (route == null || route.isEmpty()) { + return RouteTemplate.NOT_EXPRESSIBLE; + } + try { + return cache.computeIfAbsent(route, producer); + } catch (Throwable t) { + // an Error may be transient (e.g. OutOfMemoryError): the cache stores nothing when the + // producer throws, so the next request retries + log.debug("Failed to parse JAX-RS route {}", route, t); + return RouteTemplate.NOT_EXPRESSIBLE; + } + } + + /** + * Wraps {@code parser} so that a {@link RuntimeException} becomes a cached {@link + * RouteTemplate#NOT_EXPRESSIBLE}: parsing is deterministic, so it would fail again for the same + * route. Errors propagate so that {@link #cached} does not cache them. + */ + @VisibleForTesting + static Function safely(final Function parser) { + return route -> { + try { + return parser.apply(route); + } catch (RuntimeException e) { + log.debug("Failed to parse JAX-RS route {}", route, e); + return RouteTemplate.NOT_EXPRESSIBLE; + } + }; + } + + /** + * Parses a JAX-RS route in a single pass. Malformed input is not an error: it gives {@link + * RouteTemplate#NOT_EXPRESSIBLE}. + * + * @return the template, or {@link RouteTemplate#NOT_EXPRESSIBLE} for null, empty or malformed + * routes + */ + public static RouteTemplate parse(String route) { + if (route == null || route.isEmpty()) { + return RouteTemplate.NOT_EXPRESSIBLE; + } + RouteTemplate.Builder builder = RouteTemplate.builder(); + List parts = new ArrayList<>(); + int len = route.length(); + int literalStart = NO_LITERAL; + int i = 0; + while (i < len) { + char c = route.charAt(i); + if (c == '/') { + flushLiteral(route, literalStart, i, parts); + literalStart = NO_LITERAL; + endSegment(builder, parts); + i++; + } else if (c == '{') { + flushLiteral(route, literalStart, i, parts); + literalStart = NO_LITERAL; + i = parseParam(route, i, parts); + if (i < 0) { + return RouteTemplate.NOT_EXPRESSIBLE; + } + } else if (c == '}') { + return RouteTemplate.NOT_EXPRESSIBLE; + } else { + if (literalStart == NO_LITERAL) { + literalStart = i; + } + i++; + } + } + flushLiteral(route, literalStart, len, parts); + endSegment(builder, parts); + return builder.trailingSlash(len > 1 && route.charAt(len - 1) == '/').build(); + } + + /** + * Adds the parameter opened at {@code open}: {@code name} or {@code name: regex}, with optional + * whitespace. Returns the index after its closing brace, or -1 when it cannot be expressed. + */ + private static int parseParam(String route, int open, List parts) { + int close = closingBrace(route, open); + if (close < 0) { + return -1; + } + int colon = route.indexOf(':', open + 1); + int nameEnd = colon < 0 || colon > close ? close : colon; + String name = route.substring(open + 1, nameEnd).trim(); + if (!isValidName(name)) { + return -1; + } + String regex = nameEnd < close ? route.substring(nameEnd + 1, close).trim() : ""; + if (regex.isEmpty()) { + parts.add(param(name)); + } else if (acceptsSlash(regex)) { + parts.add(catchAll(name)); + } else { + parts.add(constrainedParam(name)); + } + return close + 1; + } + + /** JAX-RS names are letters, digits, {@code _}, {@code -} and {@code .}; never empty. */ + private static boolean isValidName(String name) { + if (name.isEmpty()) { + return false; + } + for (int i = 0; i < name.length(); i++) { + char c = name.charAt(i); + if (!Character.isLetterOrDigit(c) && c != '_' && c != '-' && c != '.') { + return false; + } + } + return true; + } + + /** + * Index of the closing brace of the parameter opened at {@code open}, tracking nested braces and + * backslash escapes of the regex; -1 when unbalanced. + */ + private static int closingBrace(String route, int open) { + int depth = 0; + for (int i = open; i < route.length(); i++) { + char c = route.charAt(i); + if (c == '\\') { + i++; + } else if (c == '{') { + depth++; + } else if (c == '}' && --depth == 0) { + return i; + } + } + return -1; + } + + /** + * True when {@code regex} may match a {@code /}, found by a static scan (the regex is never + * compiled). Each element is classified as {@link Slash#YES}, {@link Slash#NO} or {@link + * Slash#UNKNOWN}, and anything but NO counts as accepting {@code /}: a wrong yes only keeps the + * catch-all, a wrong no would make the parameter mandatory. Outside a character class: an + * unescaped {@code .} or {@code /}, or an escape that may match {@code /} (see {@link #escape}). + * Inside a class: a member or a range that holds {@code /} (e.g. {@code !-~}), or a negated class + * without it (negation swaps YES and NO but keeps UNKNOWN). A class with a nested class or an + * intersection, a class starting with {@code ]}, an unterminated class, invalid escapes and the + * comments flag {@code (?x)} are UNKNOWN. + */ + @VisibleForTesting + static boolean acceptsSlash(String regex) { + int len = regex.length(); + int i = 0; + while (i < len) { + char c = regex.charAt(i); + if (c == '\\') { + Atom escape = escape(regex, i, false); + if (escape.slash != Slash.NO) { + return true; + } + i = escape.end; + } else if (c == '[') { + int end = classEnd(regex, i); + if (end < 0 || classSlash(regex, i, end) != Slash.NO) { + return true; + } + i = end + 1; + } else if (c == '.' || c == '/' || (c == '(' && setsCommentsFlag(regex, i))) { + return true; + } else { + i++; + } + } + return false; + } + + /** + * Whether the group opened at {@code open} sets inline flags with {@code x}: comments mode + * ignores whitespace inside classes too ({@code [! - ~]} is the range {@code !-~}), which the + * scan does not model. + */ + private static boolean setsCommentsFlag(String regex, int open) { + int i = open + 1; + if (i >= regex.length() || regex.charAt(i) != '?') { + return false; + } + for (i++; i < regex.length(); i++) { + char c = regex.charAt(i); + if (c == 'x') { + return true; + } + if (!Character.isLetter(c) && c != '-') { + return false; + } + } + return false; + } + + /** + * Index of the {@code ]} closing the class opened at {@code open}, or -1 when unterminated or + * when the class starts with {@code ]} (Java takes it as a member, so the end is not known). + */ + private static int classEnd(String regex, int open) { + int len = regex.length(); + int first = open + 1 < len && regex.charAt(open + 1) == '^' ? open + 2 : open + 1; + if (first < len && regex.charAt(first) == ']') { + return -1; + } + int depth = 0; + for (int i = open; i < len; i++) { + char c = regex.charAt(i); + if (c == '\\') { + i++; + } else if (c == '[') { + depth++; + } else if (c == ']' && --depth == 0) { + return i; + } + } + return -1; + } + + /** + * True when the class between {@code open} and {@code end} holds an unescaped nested class + * ({@code [}) or an intersection ({@code &&}). A lone {@code &} is a plain member. + */ + private static boolean hasNestedClassOrIntersection(String regex, int open, int end) { + for (int i = open + 1; i < end; i++) { + char c = regex.charAt(i); + if (c == '\\') { + i++; + } else if (c == '[' || (c == '&' && i + 1 < end && regex.charAt(i + 1) == '&')) { + return true; + } + } + return false; + } + + /** Whether the class between {@code open} ({@code [}) and {@code end} ({@code ]}) admits '/'. */ + private static Slash classSlash(String regex, int open, int end) { + if (hasNestedClassOrIntersection(regex, open, end)) { + // a nested class or an intersection can negate or narrow its members + return Slash.UNKNOWN; + } + int i = open + 1; + boolean negated = i < end && regex.charAt(i) == '^'; + if (negated) { + i++; + } + Slash members = Slash.NO; + Atom previous = null; // the last member, the possible start of a range + while (i < end && members != Slash.YES) { + Atom member; + if (isRangeDash(regex, i, end, previous)) { + member = classMember(regex, i + 1); + members = members.or(rangeSlash(previous, member)); + previous = null; + } else { + member = classMember(regex, i); + members = members.or(member.slash); + previous = member; + } + i = member.end; + } + return negated ? members.negate() : members; + } + + /** Whether the {@code -} at {@code i} joins {@code previous} and the next member into a range. */ + private static boolean isRangeDash(String regex, int i, int end, Atom previous) { + return regex.charAt(i) == '-' && previous != null && previous.mayBoundRange() && i + 1 < end; + } + + /** A range admits '/' when it spans it; UNKNOWN when a bound is not a known character. */ + private static Slash rangeSlash(Atom from, Atom to) { + if (from.code < 0 || to.code < 0) { + return Slash.UNKNOWN; + } + return from.code <= '/' && '/' <= to.code ? Slash.YES : Slash.NO; + } + + /** + * The class member at {@code at}: an escape or a plain character ({@code &} and {@code ^} too). + */ + private static Atom classMember(String regex, int at) { + char c = regex.charAt(at); + return c == '\\' ? escape(regex, at, true) : Atom.character(at + 1, c); + } + + /** + * The escape starting with the backslash at {@code at}, shared by the scans inside ({@code + * inClass}) and outside classes. The character escapes {@code \/}, {@code \x2F}, {@code \x{2F}}, + * \u002F, octal {@code \057} / {@code \0057}, {@code \co} and {@code + * \N{SOLIDUS}} are a {@code /}; {@code \S}, {@code \W}, {@code \D}, {@code \H}, {@code \V} and + * {@code \X} accept it; {@code \p{..}} and {@code \P{..}} follow {@link #propertySlash}. A {@code + * \Q..\E} quote accepts it when the quoted text holds it. Inside a class, a quote and a named + * character other than {@code SOLIDUS} are UNKNOWN, since they may bound a range. + */ + private static Atom escape(String regex, int at, boolean inClass) { + int len = regex.length(); + if (at + 1 >= len) { + return Atom.of(len, Slash.NO); // trailing backslash + } + char e = regex.charAt(at + 1); + int from = at + 2; + switch (e) { + case 'Q': + return quote(regex, from, inClass); + case 'p': + case 'P': + return property(regex, from, e == 'P'); + case 'x': + return from < len && regex.charAt(from) == '{' + ? bracedHex(regex, from) + : hex(regex, from, from + 2); + case 'u': + return hex(regex, from, from + 4); + case '0': + return octal(regex, from); + case 'c': + return from < len ? Atom.character(from + 1, regex.charAt(from) ^ 0x40) : Atom.invalid(len); + case 'N': + return named(regex, from, inClass); + case 'k': + int close = regex.indexOf('>', from); + return Atom.of(close < 0 ? len : close + 1, Slash.NO); // back reference + default: + return simpleEscape(e, from); + } + } + + /** Escapes of a class that may match '/'. */ + private static final String SLASH_CLASS_ESCAPES = "SWDHVX"; + + /** Escapes of a class without '/', zero-width assertions and the quote end. */ + private static final String SLASH_FREE_ESCAPES = "swdhvRbBAzZGE"; + + /** Control character escapes and, at the same index, their characters. */ + private static final String CONTROL_ESCAPES = "tnrfae"; + + private static final String CONTROL_CHARACTERS = "\t\n\r\f\u0007\u001B"; + + /** The one-character escape {@code \e}, ending at {@code end}. */ + private static Atom simpleEscape(char e, int end) { + if (SLASH_CLASS_ESCAPES.indexOf(e) >= 0) { + return Atom.of(end, Slash.YES); + } + if (SLASH_FREE_ESCAPES.indexOf(e) >= 0 || (e >= '1' && e <= '9')) { + // a back reference's group is scanned where it is declared + return Atom.of(end, Slash.NO); + } + int control = CONTROL_ESCAPES.indexOf(e); + if (control >= 0) { + return Atom.character(end, CONTROL_CHARACTERS.charAt(control)); + } + // an unknown letter escape is invalid in Java; any other escaped character is itself + boolean letter = (e >= 'a' && e <= 'z') || (e >= 'A' && e <= 'Z'); + return letter ? Atom.invalid(end) : Atom.character(end, e); + } + + /** + * {@code \Q..\E} quote whose text starts at {@code from}; unterminated runs to the end. Inside a + * class it is UNKNOWN, since its last character may start a range. + */ + private static Atom quote(String regex, int from, boolean inClass) { + int close = regex.indexOf("\\E", from); + int stop = close < 0 ? regex.length() : close; + int end = close < 0 ? stop : close + 2; + if (inClass) { + return Atom.of(end, Slash.UNKNOWN); + } + int slash = regex.indexOf('/', from); + return Atom.of(end, slash >= 0 && slash < stop ? Slash.YES : Slash.NO); + } + + /** {@code \x{h..h}} with its brace at {@code open}. */ + private static Atom bracedHex(String regex, int open) { + int close = regex.indexOf('}', open); + if (close < 0 || close == open + 1 || close - open > 7) { + return Atom.invalid(close < 0 ? regex.length() : close + 1); + } + Atom atom = hex(regex, open + 1, close); + return atom.code < 0 ? Atom.invalid(close + 1) : Atom.character(close + 1, atom.code); + } + + /** + * The character whose hex digits are {@code [from, to)} ({@code \xhh}, \uhhhh). + */ + private static Atom hex(String regex, int from, int to) { + if (to > regex.length()) { + return Atom.invalid(regex.length()); + } + int code = 0; + for (int i = from; i < to; i++) { + int digit = Character.digit(regex.charAt(i), 16); + if (digit < 0) { + return Atom.invalid(to); + } + code = code * 16 + digit; + } + return code > Character.MAX_CODE_POINT ? Atom.invalid(to) : Atom.character(to, code); + } + + /** + * Octal escape {@code \0n}, {@code \0nn} or {@code \0mnn} (m at most 3), digits at {@code from}. + */ + private static Atom octal(String regex, int from) { + int len = regex.length(); + int max = from < len && regex.charAt(from) <= '3' ? 3 : 2; + int code = 0; + int i = from; + while (i < len && i - from < max && regex.charAt(i) >= '0' && regex.charAt(i) <= '7') { + code = code * 8 + regex.charAt(i) - '0'; + i++; + } + return i == from ? Atom.invalid(i) : Atom.character(i, code); + } + + /** + * {@code \N{name}}: only {@code SOLIDUS} (the one name Java resolves to '/') is resolved. Any + * other name is a character other than '/', UNKNOWN inside a class where it may bound a range. + */ + private static Atom named(String regex, int from, boolean inClass) { + int close = from < regex.length() && regex.charAt(from) == '{' ? regex.indexOf('}', from) : -1; + if (close < 0) { + return Atom.invalid(regex.length()); + } + String name = regex.substring(from + 1, close).trim(); + if ("SOLIDUS".equalsIgnoreCase(name)) { + return Atom.character(close + 1, '/'); + } + return Atom.of(close + 1, inClass ? Slash.UNKNOWN : Slash.NO); + } + + /** {@code \p{..}} or, when {@code negated}, {@code \P{..}}, with the name at {@code from}. */ + private static Atom property(String regex, int from, boolean negated) { + int end = propertyEnd(regex, from); + Slash slash = propertySlash(regex, from, end); + return Atom.of(end, negated ? slash.negate() : slash); + } + + /** + * Index after the {@code \p} property name starting at {@code from} ({@code X} or {@code {..}}). + */ + private static int propertyEnd(String regex, int from) { + if (from < regex.length() && regex.charAt(from) == '{') { + int close = regex.indexOf('}', from); + return close < 0 ? regex.length() : close + 1; + } + return Math.min(from + 1, regex.length()); + } + + /** Properties known to exclude '/' (letters, digits, marks, whitespace). */ + private static final Set SLASH_FREE_PROPERTIES = + new HashSet<>( + Arrays.asList( + "L", + "Lu", + "Ll", + "Lt", + "Lm", + "Lo", + "N", + "Nd", + "Nl", + "No", + "M", + "Alpha", + "Digit", + "Alnum", + "Upper", + "Lower", + "IsAlphabetic", + "IsLetter", + "IsDigit", + "IsUppercase", + "IsLowercase", + "javaLetter", + "javaDigit", + "javaLetterOrDigit", + "javaUpperCase", + "javaLowerCase", + "XDigit", + "Space", + "IsWhite_Space")); + + /** Properties known to include '/' (punctuation Po, script Common, block Basic Latin). */ + private static final Set SLASH_PROPERTIES = + new HashSet<>( + Arrays.asList( + "P", + "Po", + "IsP", + "IsPo", + "gc=P", + "gc=Po", + "general_category=P", + "general_category=Po", + "Punct", + "IsPunctuation", + "Graph", + "Print", + "ASCII", + "InBasicLatin", + "InBasic_Latin", + "IsCommon", + "sc=Common", + "script=Common", + "IsAssigned", + "javaDefined", + "all")); + + /** + * Whether the {@code \p} property in {@code [from, end)} includes '/': YES or NO for the names in + * {@link #SLASH_PROPERTIES} and {@link #SLASH_FREE_PROPERTIES}, UNKNOWN for any other name or + * alias. + */ + private static Slash propertySlash(String regex, int from, int end) { + String name = regex.substring(from, end); + if (name.startsWith("{")) { + name = name.substring(1, name.length() - (name.endsWith("}") ? 1 : 0)); + } + if (SLASH_PROPERTIES.contains(name)) { + return Slash.YES; + } + return SLASH_FREE_PROPERTIES.contains(name) ? Slash.NO : Slash.UNKNOWN; + } + + /** Whether a regex element may match '/'; UNKNOWN when the scan cannot tell. */ + private enum Slash { + YES, + NO, + UNKNOWN; + + /** The answer for the complement: YES and NO swap, UNKNOWN stays UNKNOWN. */ + Slash negate() { + if (this == UNKNOWN) { + return UNKNOWN; + } + return this == YES ? NO : YES; + } + + /** The answer for the union with {@code other}: YES if either is YES, then UNKNOWN, then NO. */ + Slash or(Slash other) { + if (this == YES || other == YES) { + return YES; + } + return this == UNKNOWN || other == UNKNOWN ? UNKNOWN : NO; + } + } + + /** + * One element of a regex: where it ends, its character code when it is a single known character + * ({@link #NO_CODE} otherwise) and whether it may match '/'. + */ + private static final class Atom { + /** Not a single known character. */ + static final int NO_CODE = -1; + + final int end; + final int code; + final Slash slash; + + private Atom(int end, int code, Slash slash) { + this.end = end; + this.code = code; + this.slash = slash; + } + + static Atom character(int end, int code) { + return new Atom(end, code, code == '/' ? Slash.YES : Slash.NO); + } + + static Atom of(int end, Slash slash) { + return new Atom(end, NO_CODE, slash); + } + + /** An invalid construct: UNKNOWN, so that a negated class does not flip it. */ + static Atom invalid(int end) { + return of(end, Slash.UNKNOWN); + } + + /** A single character, known or UNKNOWN, may start a range; a class escape may not. */ + boolean mayBoundRange() { + return code >= 0 || slash == Slash.UNKNOWN; + } + } + + /** Adds the literal in {@code [start, end)} with its {@code %XX} escapes decoded. */ + private static void flushLiteral(String route, int start, int end, List parts) { + if (start != NO_LITERAL && end > start) { + parts.add(literal(RouteEncoding.decodePath(route.substring(start, end)))); + } + } + + private static void endSegment(RouteTemplate.Builder builder, List parts) { + if (!parts.isEmpty()) { + builder.segment(parts.toArray(new RoutePart[0])); + parts.clear(); + } + } +} diff --git a/internal-api/src/test/java/datadog/trace/api/appsec/route/JaxRsRequestMatchTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/JaxRsRequestMatchTest.java new file mode 100644 index 00000000000..6ce7470de90 --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/JaxRsRequestMatchTest.java @@ -0,0 +1,99 @@ +package datadog.trace.api.appsec.route; + +import static java.util.Arrays.asList; +import static java.util.Collections.emptyList; +import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonList; +import static java.util.Collections.singletonMap; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.tabletest.junit.TableTest; + +class JaxRsRequestMatchTest { + + @TableTest({ + "Scenario | Raw base path | Prefix ", + "null | | ", + "empty | '' | '' ", + "plain | '/ctx/api/' | '/ctx/api/' ", + "escapes decoded | '/my%20ctx/caf%C3%A9' | '/my ctx/café'" + }) + void decodesTheBasePath(String rawBasePath, String prefix) { + assertEquals(prefix, JaxRsRequestMatch.of(rawBasePath, null).prefix()); + } + + @Test + void noBoundValuesIsNull() { + assertNull(JaxRsRequestMatch.of("/", null).boundValues()); + assertNull(JaxRsRequestMatch.of("/", emptyMap()).boundValues()); + } + + @Test + void listValuesKeepTheFirstElement() { + Map raw = new HashMap<>(); + raw.put("path", asList("a/b", "c")); + raw.put("empty", emptyList()); + raw.put("id", 7); + raw.put("none", null); + + Map bound = JaxRsRequestMatch.of("/", raw).boundValues(); + + assertEquals("a/b", bound.get("path")); + assertNull(bound.get("empty")); + assertEquals("7", bound.get("id")); + assertNull(bound.get("none")); + assertEquals(4, bound.size()); + } + + @Test + void boundValuesAreACopy() { + List values = new ArrayList<>(asList("x")); + Map raw = new HashMap<>(); + raw.put("path", values); + raw.put("id", "1"); + JaxRsRequestMatch match = JaxRsRequestMatch.of("/", raw); + JaxRsRequestMatch single = JaxRsRequestMatch.of("/", singletonMap("path", values)); + + values.set(0, ""); + raw.clear(); + + assertEquals("x", match.boundValues().get("path")); + assertEquals("1", match.boundValues().get("id")); + assertEquals("x", single.boundValues().get("path")); + assertThrows(UnsupportedOperationException.class, () -> match.boundValues().put("a", "b")); + assertThrows(UnsupportedOperationException.class, () -> single.boundValues().put("a", "b")); + } + + @TableTest({ + "Scenario | Value | Expected ", + "catch-all with value | 'a/b' | '/ctx/files/{path}'", + "catch-all only slash | '/' | '/ctx/files/' ", + "catch-all empty | '' | '/ctx/files' " + }) + void presenceComesFromTheBoundValues(String value, String expected) { + RouteTemplate template = JaxRsRouteParser.parse("/files/{path: .*}"); + JaxRsRequestMatch match = + JaxRsRequestMatch.of("/ctx/", singletonMap("path", singletonList(value))); + + assertEquals(expected, template.render(match.prefix(), match.presenceFor(template))); + } + + @Test + void presenceIsUnknownWithoutBoundValuesOrOptionalParts() { + RouteTemplate catchAll = JaxRsRouteParser.parse("/files/{path: .*}"); + RouteTemplate plain = JaxRsRouteParser.parse("/users/{id}"); + JaxRsRequestMatch match = JaxRsRequestMatch.of("/", singletonMap("id", "1")); + + assertSame(PresenceResolver.UNKNOWN, JaxRsRequestMatch.of("/", null).presenceFor(catchAll)); + assertSame(PresenceResolver.UNKNOWN, match.presenceFor(plain)); + assertSame(PresenceResolver.UNKNOWN, match.presenceFor(null)); + } +} diff --git a/internal-api/src/test/java/datadog/trace/api/appsec/route/JaxRsRouteParserCacheTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/JaxRsRouteParserCacheTest.java new file mode 100644 index 00000000000..eb6b0d66304 --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/JaxRsRouteParserCacheTest.java @@ -0,0 +1,105 @@ +package datadog.trace.api.appsec.route; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import datadog.trace.api.cache.DDCache; +import datadog.trace.api.cache.DDCaches; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import org.junit.jupiter.api.Test; + +class JaxRsRouteParserCacheTest { + + @Test + void sameRouteReturnsCachedInstance() { + RouteTemplate first = JaxRsRouteParser.cached("/users/{id: \\d+}"); + assertSame(first, JaxRsRouteParser.cached(new String("/users/{id: \\d+}"))); + assertEquals("/users/{id}", first.staticRoute()); + } + + @Test + void differentRoutesGiveDifferentTemplates() { + RouteTemplate users = JaxRsRouteParser.cached("/users/{id}"); + RouteTemplate orders = JaxRsRouteParser.cached("/orders/{id}"); + assertNotSame(users, orders); + assertEquals("/orders/{id}", orders.staticRoute()); + } + + @Test + void nullOrEmptyIsNotExpressible() { + assertSame(RouteTemplate.NOT_EXPRESSIBLE, JaxRsRouteParser.cached(null)); + assertSame(RouteTemplate.NOT_EXPRESSIBLE, JaxRsRouteParser.cached("")); + } + + @Test + void nullOrEmptyNeverReachesTheCache() { + DDCache cache = DDCaches.newFixedSizeCache(4); + JaxRsRouteParser.cached(cache, null); + JaxRsRouteParser.cached(cache, ""); + assertEquals(0, size(cache)); + } + + @Test + void unparseableRouteIsCachedAsNotExpressible() { + DDCache cache = DDCaches.newFixedSizeCache(4); + assertSame(RouteTemplate.NOT_EXPRESSIBLE, JaxRsRouteParser.cached(cache, "/a/{id")); + assertEquals(1, size(cache)); + assertSame(RouteTemplate.NOT_EXPRESSIBLE, JaxRsRouteParser.cached(cache, "/a/{id")); + assertEquals(1, size(cache)); + } + + @Test + void parserRuntimeExceptionIsCachedAsNotExpressible() { + DDCache cache = DDCaches.newFixedSizeCache(4); + AtomicInteger calls = new AtomicInteger(); + Function producer = + JaxRsRouteParser.safely(route -> { + calls.incrementAndGet(); + throw new IllegalStateException("parser bug"); + }); + + assertSame(RouteTemplate.NOT_EXPRESSIBLE, JaxRsRouteParser.cached(cache, "/a", producer)); + assertSame(RouteTemplate.NOT_EXPRESSIBLE, JaxRsRouteParser.cached(cache, "/a", producer)); + assertEquals(1, calls.get()); + assertEquals(1, size(cache)); + } + + @Test + void parserErrorIsNotCached() { + DDCache cache = DDCaches.newFixedSizeCache(4); + Function failing = + JaxRsRouteParser.safely(route -> { + throw new StackOverflowError("transient"); + }); + + assertSame(RouteTemplate.NOT_EXPRESSIBLE, JaxRsRouteParser.cached(cache, "/a/{id}", failing)); + assertEquals(0, size(cache)); + + RouteTemplate retried = JaxRsRouteParser.cached(cache, "/a/{id}"); + assertEquals("/a/{id}", retried.staticRoute()); + assertEquals(1, size(cache)); + } + + @Test + void cacheStaysBounded() { + int capacity = 8; + DDCache cache = DDCaches.newFixedSizeCache(capacity); + for (int i = 0; i < 1000; i++) { + String route = "/p" + i + "/{id}"; + RouteTemplate template = JaxRsRouteParser.cached(cache, route); + assertEquals(route, template.staticRoute()); + assertTrue(size(cache) <= capacity); + } + RouteTemplate last = JaxRsRouteParser.cached(cache, "/p999/{id}"); + assertSame(last, JaxRsRouteParser.cached(cache, "/p999/{id}")); + } + + private static int size(DDCache cache) { + AtomicInteger count = new AtomicInteger(); + cache.visit((k, v) -> count.incrementAndGet()); + return count.get(); + } +} diff --git a/internal-api/src/test/java/datadog/trace/api/appsec/route/JaxRsRouteParserRfcVectorsTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/JaxRsRouteParserRfcVectorsTest.java new file mode 100644 index 00000000000..0b122752c43 --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/JaxRsRouteParserRfcVectorsTest.java @@ -0,0 +1,56 @@ +package datadog.trace.api.appsec.route; + +import static java.util.Collections.singletonMap; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Map; +import org.tabletest.junit.TableTest; + +/** + * The RFC-1125 "Test cases" rows (see {@link NormalizedRouteRfcVectorsTest}) that JAX-RS + * {@code @Path} can express, written in JAX-RS syntax and run through {@link JaxRsRouteParser}. + * Presence comes from the value the framework binds ({@code Name} / {@code Value}; a blank name + * means nothing bound), through {@link BoundValuesPresenceResolver}, as the JAX-RS decorators do. + * + *

Not applicable: 15-29 and 39-45 (optional parameters, optional static text and optional groups + * do not exist in {@code @Path}), 36-38 and 50 (unnamed wildcards: every JAX-RS parameter has a + * name), 46-48 (Go only). + * + *

Row 49: for {@code /files/{path: .*}} Jersey binds {@code ""} on {@code /files/} (the regex + * runs after {@code /files/}), which the core treats as absent ({@code /files}); it binds {@code /} + * on {@code /files//}, which gives the RFC tag {@code /files/}. Both bindings are listed. + */ +class JaxRsRouteParserRfcVectorsTest { + + @TableTest({ + "Scenario | Route | Hit URL | Name | Value | Tag ", + "#1 Basics | '/users' | '/users' | | | '/users' ", + "#2 Basics | '/' | '/' | | | '/' ", + "#3 Basics | '/users/{id}' | '/users/42' | id | '42' | '/users/{id}' ", + "#4 Basics | '/users/{id}/posts/{post_id}' | '/users/1/posts/5' | id | '1' | '/users/{id}/posts/{post_id}'", + "#5 Basics | '/users/{id}/' | '/users/1/' | id | '1' | '/users/{id}/' ", + "#6 Static text in a segment | '/users/user-{id}' | '/users/user-42' | id | '42' | '/users/user-{id}' ", + "#7 Static text in a segment | '/v{version}/items' | '/v2/items' | | | '/v{version}/items' ", + "#8 Static text in a segment | '/files/{name}.json' | '/files/report.json' | | | '/files/{name}.json' ", + "#9 Static text in a segment | '/café' | '/caf%C3%A9' | | | '/caf%C3%A9' ", + "#10 Static text in a segment | '/user:me' | '/user:me' | | | '/user%3Ame' ", + "#11 Static text in a segment | '/a+b/{id}' | '/a+b/1' | | | '/a%2Bb/{id}' ", + "#12 Several parameters in one segment | '/photos/{id}.{format}' | '/photos/1.jpg' | | | '/photos/{id}.{format}' ", + "#13 Several parameters in one segment | '/d/{a}-{b}-{c}' | '/d/1-2-3' | | | '/d/{a}-{b}-{c}' ", + "#14 Several parameters in one segment | '/v/{major}{minor}' | '/v/12' | | | '/v/{major}{minor}' ", + "#30 Parameter names | '/users/{user-id}' | '/users/1' | | | '/users/{user_id}' ", + "#31 Parameter names | '/items/{item.id}' | '/items/1' | | | '/items/{item_id}' ", + "#32 Parameter names, collision | '/a/{user-id}/{user_id}' | '/a/1/2' | | | '/a/{user_id_2}/{user_id}' ", + "#33 Parameter names, collision (suffix _2 already used) | '/a/{x-y}/{x_y}/{x_y_2}' | '/a/1/2/3' | | | '/a/{x_y_3}/{x_y}/{x_y_2}' ", + "#34 Parameter names, non-ASCII | '/u/{föo}' | '/u/1' | | | '/u/{f_o}' ", + "#35 Catch-all, named | '/files/{path: .*}' | '/files/a/b/c.txt' | path | 'a/b/c.txt' | '/files/{path}' ", + "#49 Catch-all, empty value (Jersey binds slash) | '/files/{path: .*}' | '/files//' | path | '/' | '/files/' ", + "#49 Catch-all, empty value (Jersey binds empty) | '/files/{path: .*}' | '/files/' | path | '' | '/files' " + }) + void rendersRfcRows(String route, String hitUrl, String name, String value, String tag) { + RouteTemplate template = JaxRsRouteParser.parse(route); + Map bound = name == null ? null : singletonMap(name, value); + assertEquals( + tag, template.render(null, BoundValuesPresenceResolver.of(template, bound, null)), hitUrl); + } +} diff --git a/internal-api/src/test/java/datadog/trace/api/appsec/route/JaxRsRouteParserTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/JaxRsRouteParserTest.java new file mode 100644 index 00000000000..5f62404a89b --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/JaxRsRouteParserTest.java @@ -0,0 +1,221 @@ +package datadog.trace.api.appsec.route; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Set; +import org.junit.jupiter.api.Test; +import org.tabletest.junit.TableTest; + +class JaxRsRouteParserTest { + + @TableTest({ + "Scenario | Route | Present | Expected ", + "QA static text after param | '/api_security/files/{name}.json' | {} | '/api_security/files/{name}.json'", + "QA regex with nested braces | '/u/{id: [0-9]{3}}' | {} | '/u/{id}' ", + "nested braces mid route | '/a/{id: [0-9]{3}}/b' | {} | '/a/{id}/b' ", + "whitespace around name and regex | '/a/{ id : \\d+ }' | {} | '/a/{id}' ", + "whitespace without regex | '/a/{ id }' | {} | '/a/{id}' ", + "empty regex | '/a/{id:}' | {} | '/a/{id}' ", + "escaped brace in regex | '/a/{v: \\{}' | {} | '/a/{v}' ", + "slash inside regex, present | '/a/{p: [a-z/]+}/b' | {p} | '/a/{p}/b' ", + "slash inside regex, absent | '/a/{p: [a-z/]+}/b' | {} | '/a/b' ", + "several params in one segment | '/d/{a}-{b}-{c}' | {} | '/d/{a}-{b}-{c}' ", + "static text before param | '/users/user-{id}' | {} | '/users/user-{id}' ", + "version prefix | '/v{version}/items' | {} | '/v{version}/items' ", + "name sanitized | '/users/{user-id}' | {} | '/users/{user_id}' ", + "lowercase escape uppercased | '/caf%c3%a9' | {} | '/caf%C3%A9' ", + "space escapes kept | '/encoded%20path%20query' | {} | '/encoded%20path%20query' ", + "non-ASCII literal | '/café' | {} | '/caf%C3%A9' ", + "percent without escape | '/100%' | {} | '/100%25' ", + "percent with one hex digit | '/a%2' | {} | '/a%252' ", + "percent with non-hex digits | '/a%zz' | {} | '/a%25zz' ", + "escaped slash stays in segment | '/a%2Fb' | {} | '/a%2Fb' ", + "unreserved escape decoded | '/a%7Eb' | {} | '/a~b' ", + "catch-all mid segment, present | '/files/{path: .*}.json' | {path} | '/files/{path}.json' ", + "catch-all mid segment, absent | '/files/{path: .*}.json' | {} | '/files/.json' ", + "catch-all only slash | '/catch-all/{path: .*}' | {'path=/'} | '/catch-all/' ", + "catch-all unknown | '/catch-all/{path: .*}' | | '/catch-all' ", + "nested negation, empty value | '/files/{path: [^[^/]]*}' | {} | '/files' ", + "nested negation, only slash | '/files/{path: [^[^/]]*}' | {'path=/'} | '/files/' ", + "unlisted property, empty value | '/files/{path: \\p{blk=Basic_Latin}*}' | {} | '/files' ", + "unlisted property, only slash | '/files/{path: \\p{blk=Basic_Latin}*}' | {'path=/'} | '/files/' ", + "root | '/' | {} | '/' ", + "empty segments ignored | '//a//b' | {} | '/a/b' ", + "trailing slash kept | '/a/{id}/' | {} | '/a/{id}/' ", + "no leading slash | 'users/{id}' | {} | '/users/{id}' ", + "colon in literal | '/user:me' | {} | '/user%3Ame' " + }) + void parsesJaxRsRoutes(String route, Set present, String expected) { + RouteTemplate template = JaxRsRouteParser.parse(route); + assertEquals(expected, template.render(null, RfcRouteNotation.presence(present))); + } + + @TableTest({ + "Scenario | Route ", + "null | ", + "empty | '' ", + "unclosed brace | '/a/{id' ", + "unopened brace | '/a/id}' ", + "unclosed nested regex | '/a/{id: [0-9]{3}'", + "escaped closing brace | '/a/{id: \\}' ", + "empty name | '/a/{}' ", + "blank name | '/a/{ }' ", + "regex without name | '/a/{: \\d+}' ", + "invalid name character | '/a/{*path}' ", + "whitespace inside name | '/a/{a b}' " + }) + void rejectsRoutesThatCannotBeExpressed(String route) { + assertSame(RouteTemplate.NOT_EXPRESSIBLE, JaxRsRouteParser.parse(route)); + } + + /** + * Braces are balanced without regard to regex character classes, so a {@code }} inside one closes + * the parameter early: the route fails closed (no tag) rather than being misparsed. + */ + @Test + void closingBraceInsideARegexClassIsNotExpressible() { + assertSame(RouteTemplate.NOT_EXPRESSIBLE, JaxRsRouteParser.parse("/a/{id: [}a]+}")); + } + + @TableTest({ + "Scenario | Regex | Accepts slash", + "dot star | '.*' | true ", + "dot plus | '.+' | true ", + "negated class without slash | '[^/]+' | false ", + "negated class with escaped slash | '[^\\/]+' | false ", + "class with slash | '[a-z/]+' | true ", + "class with escaped slash | '[a-z\\/]+' | true ", + "digits | '\\d+' | false ", + "non-whitespace | '\\S+' | true ", + "non-word | '\\W+' | true ", + "non-digit | '\\D+' | true ", + "non-whitespace inside class | '[\\S]+' | true ", + "non-word inside class | '[a\\W]+' | true ", + "non-digit inside class | '[\\D]+' | true ", + "negated non-whitespace class | '[^\\S]+' | false ", + "range over slash | '[!-~]+' | true ", + "range below slash | '[!-.]+' | false ", + "range above slash | '[0-9]+' | false ", + "range with escaped end | '[!-\\~]+' | true ", + "escaped dot in optional group | '(?:\\.json)?' | false ", + "quantifier braces | '[0-9]{3}' | false ", + "negated class without slash char | '[^a]+' | true ", + "word chars | '\\w+' | false ", + "word chars inside class | '[\\w\\s\\d-]+' | false ", + "literal slash | 'a/b' | true ", + "escaped literal slash | 'a\\/b' | true ", + "escaped backslash | '\\\\' | false ", + "trailing backslash | 'a\\' | false ", + "dash at class start | '[-a]+' | false ", + "dash at class end | '[a-]+' | false ", + "escaped char in class | '[\\-\\]]+' | false ", + "unterminated class | '[a-z' | true ", + "nested class with slash | '[a[/]]' | true ", + "negated nested negation | '[^[^/]]*' | true ", + "nested class without slash | '[a[b]]+' | true ", + "intersection | '[a-z&&[^b]]+' | true ", + "quote with slash | '\\Qa/b\\E' | true ", + "quote without slash | '\\Qa.b\\E' | false ", + "unterminated quote | '\\Qa.b' | false ", + "punctuation property | '\\p{Punct}+' | true ", + "alpha property | '\\p{Alpha}+' | false ", + "one-letter property | '\\pL+' | false ", + "unterminated property | '\\p{Alpha' | false ", + "negated property | '\\P{Alpha}+' | true ", + "property inside class | '[\\p{ASCII}]' | true ", + "alpha property inside class | '[\\p{L}]' | false ", + "negated property inside class | '[\\PL]' | true ", + "hex escape of slash | '\\x2F+' | true ", + "lowercase hex escape of slash | '\\x2f+' | true ", + "hex escape of a letter | '\\x41+' | false ", + "braced hex escape of slash | '\\x{2F}+' | true ", + "braced hex escape of a letter | '\\x{41}+' | false ", + "empty braced hex escape | '\\x{}' | true ", + "malformed hex escape | '\\xZZ' | true ", + "unicode escape of slash | '\\u002F+' | true ", + "unicode escape of a letter | '\\u0041+' | false ", + "octal escape of slash | '\\057+' | true ", + "three-digit octal escape of slash | '\\0057+' | true ", + "octal escape of a letter | '\\0101+' | false ", + "control escape of slash | '\\co' | true ", + "named slash | '\\N{SOLIDUS}+' | true ", + "named letter | '\\N{LATIN SMALL LETTER A}+' | false ", + "hex escape of slash in class | '[\\x2F]+' | true ", + "braced hex escape in class | '[\\x{2F}]+' | true ", + "unicode escape of slash in class | '[\\u002F]+' | true ", + "octal escape of slash in class | '[\\057]+' | true ", + "named slash in class | '[\\N{SOLIDUS}]+' | true ", + "negated class without hex slash | '[^\\x2F]+' | false ", + "range with hex end | '[!-\\x7E]+' | true ", + "range with unicode end | '[!-\\u007E]+' | true ", + "range with octal end | '[!-\\0176]+' | true ", + "range with tab start | '[\\t-~]+' | true ", + "hex range above slash | '[\\x30-\\x39]+' | false ", + "range with named end | '[!-\\N{TILDE}]+' | true ", + "non-horizontal-whitespace | '\\H+' | true ", + "non-vertical-whitespace | '\\V+' | true ", + "grapheme cluster | '\\X+' | true ", + "non-horizontal-whitespace in class | '[\\H]+' | true ", + "horizontal whitespace | '\\h+' | false ", + "vertical whitespace | '\\v+' | false ", + "linebreak | '\\R' | false ", + "unknown letter escape | '\\y' | true ", + "back reference | '(a)\\1' | false ", + "named back reference | '(?a)\\k' | false ", + "negated punctuation property | '\\P{Punct}+' | false ", + "negated ASCII property in class | '[\\P{ASCII}]+' | false ", + "common script property | '\\p{IsCommon}+' | true ", + "other punctuation category | '\\p{gc=Po}+' | true ", + "negated class, unknown range bound | '[^\\N{LATIN CAPITAL LETTER A}-Z]*' | true ", + "block alias property | '\\p{blk=Basic_Latin}*' | true ", + "uppercase block property | '\\p{InBASIC_LATIN}' | true ", + "script code property | '\\p{sc=Zyyy}' | true ", + "block keyword property | '\\p{block=Basic_Latin}' | true ", + "negated unlisted property | '\\P{blk=Basic_Latin}' | true ", + "quoted range start in class | '[\\Q!\\E-~]*' | true ", + "negated quote in class | '[^\\Q!\\E]*' | true ", + "quote and slash in negated class | '[^\\Q!\\E/]*' | false ", + "lone ampersand range start | '[&-0]*' | true ", + "lone ampersand member | '[&a]+' | false ", + "letter property | '\\p{L}' | false ", + "negated letter property class | '[^\\p{L}]' | true ", + "negated invalid escape in class | '[^\\y]' | true ", + "leading bracket member | '[]!-~]+' | true ", + "negated leading bracket member | '[^]a]+' | true ", + "comments flag | '(?x)[! - ~]+' | true ", + "comments flag group | '(?ix:[! - ~])' | true ", + "case-insensitive flag | '(?i)[a-z]+' | false ", + "alternation of literals | 'json|xml' | false " + }) + void detectsRegexesThatAcceptSlash(String regex, boolean acceptsSlash) { + assertEquals(acceptsSlash, JaxRsRouteParser.acceptsSlash(regex)); + } + + @Test + void regexParamKindsAreRecorded() { + RouteTemplate template = JaxRsRouteParser.parse("/a/{id: \\d+}/{name}/{rest: .*}"); + RoutePart.Param id = template.params().get(0); + RoutePart.Param name = template.params().get(1); + RoutePart.Param rest = template.params().get(2); + assertTrue(id.hasRegexConstraint()); + assertFalse(id.isOptional()); + assertFalse(name.hasRegexConstraint()); + assertTrue(rest.isCatchAll()); + } + + @Test + void routeWithoutCatchAllIsPreRendered() { + assertEquals("/a/{id}/b", JaxRsRouteParser.parse("/a/{id: [0-9]{3}}/b").staticRoute()); + assertNull(JaxRsRouteParser.parse("/files/{path: .*}").staticRoute()); + } + + @Test + void rendersWithMountPrefix() { + assertEquals("/ctx/users/{id}", JaxRsRouteParser.parse("/users/{id}").render("/ctx", null)); + assertEquals("/ctx/", JaxRsRouteParser.parse("/").render("/ctx", null)); + } +}