Skip to content

Commit

Permalink
♻️ Use Pattern.quote() for regex escaping in MongoRequest
Browse files Browse the repository at this point in the history
  • Loading branch information
ujibang committed Feb 24, 2025
1 parent 7fa4940 commit e70b6c4
Showing 1 changed file with 6 additions and 12 deletions.
18 changes: 6 additions & 12 deletions commons/src/main/java/org/restheart/exchange/MongoRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -492,21 +492,15 @@ private String unmapUri(String mappedUri) {
}
}

Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");

String escapeSpecialRegexChars(String str) {
return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
}

private String unmapPathUri(String mappedUri) {
var ret = URLUtils.removeTrailingSlashes(mappedUri);

if (whatUri.equals("*")) {
if (!this.whereUri.equals(SLASH)) {
ret = ret.replaceFirst("^" + escapeSpecialRegexChars(this.whereUri), "");
ret = ret.replaceFirst("^" + Pattern.quote(this.whereUri), "");
}
} else if (!this.whereUri.equals(SLASH)) {
ret = URLUtils.removeTrailingSlashes(ret.replaceFirst("^" + escapeSpecialRegexChars(this.whereUri), this.whatUri));
ret = URLUtils.removeTrailingSlashes(ret.replaceFirst("^" + Pattern.quote(this.whereUri), this.whatUri));
} else {
ret = URLUtils.removeTrailingSlashes(URLUtils.removeTrailingSlashes(this.whatUri) + ret);
}
Expand All @@ -525,11 +519,11 @@ private String unmapPathTemplateUri(String mappedUri) {
// now replace mappedUri with resolved path template
if (replacedWhatUri.equals("*")) {
if (!this.whereUri.equals(SLASH)) {
ret = ret.replaceFirst("^" + escapeSpecialRegexChars(rewriteUri), "");
ret = ret.replaceFirst("^" + Pattern.quote(rewriteUri), "");
}
} else if (!this.whereUri.equals(SLASH)) {
var x = rewriteUri;
ret = URLUtils.removeTrailingSlashes(ret.replaceFirst("^" + escapeSpecialRegexChars(rewriteUri), replacedWhatUri));
ret = URLUtils.removeTrailingSlashes(ret.replaceFirst("^" + Pattern.quote(rewriteUri), replacedWhatUri));
} else {
ret = URLUtils.removeTrailingSlashes(URLUtils.removeTrailingSlashes(replacedWhatUri) + ret);
}
Expand Down Expand Up @@ -561,7 +555,7 @@ private String mapPathUri(String unmappedUri) {
return this.whereUri + unmappedUri;
}
} else {
ret = URLUtils.removeTrailingSlashes(ret.replaceFirst("^" + escapeSpecialRegexChars(this.whatUri), this.whereUri));
ret = URLUtils.removeTrailingSlashes(ret.replaceFirst("^" + Pattern.quote(this.whatUri), this.whereUri));
}

if (ret.isEmpty()) {
Expand All @@ -584,7 +578,7 @@ private String mapPathTemplateUri(String unmappedUri) {
return rewriteUri + unmappedUri;
}
} else {
ret = URLUtils.removeTrailingSlashes(ret.replaceFirst("^" + escapeSpecialRegexChars(replacedWhatUri), rewriteUri));
ret = URLUtils.removeTrailingSlashes(ret.replaceFirst("^" + Pattern.quote(replacedWhatUri), rewriteUri));
}

return ret.isEmpty() ? SLASH : ret;
Expand Down

0 comments on commit e70b6c4

Please sign in to comment.