Skip to content

Commit

Permalink
Add fast path to same origin check
Browse files Browse the repository at this point in the history
  • Loading branch information
stuartwdouglas committed Dec 1, 2022
1 parent 3c18d39 commit 9c5c1f8
Showing 1 changed file with 39 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,23 @@ public void handle(RoutingContext event) {
}
}

private static boolean isSameOrigin(HttpServerRequest request, String origin) {
static boolean isSameOrigin(HttpServerRequest request, String origin) {
//fast path check, when everything is the same
if (origin.startsWith(request.scheme())) {
if (!substringMatch(origin, request.scheme().length(), "://", false)) {
return false;
}
if (substringMatch(origin, request.scheme().length() + 3, request.host(), true)) {
//they are a simple match
return true;
}
return isSameOriginSlowPath(request, origin);
} else {
return false;
}
}

static boolean isSameOriginSlowPath(HttpServerRequest request, String origin) {
String absUriString = request.absoluteURI();
if (absUriString.startsWith(origin)) {
// Make sure that Origin URI contains scheme, host, and port.
Expand All @@ -225,4 +241,26 @@ private static boolean isSameOrigin(HttpServerRequest request, String origin) {
}
return false;
}

static boolean substringMatch(String str, int pos, String substring, boolean requireFull) {
int length = str.length();
int subLength = substring.length();
int strPos = pos;
int subPos = 0;
if (pos + subLength > length) {
//too long, avoid checking in the loop
return false;
}
for (;;) {
if (subPos == subLength) {
//if we are at the end return the correct value, depending on if we are also at the end of the origin
return !requireFull || strPos == length;
}
if (str.charAt(strPos) != substring.charAt(subPos)) {
return false;
}
strPos++;
subPos++;
}
}
}

0 comments on commit 9c5c1f8

Please sign in to comment.