Fix bad origin rejections for self-hosted UI

PolyGerrit and GWT UI running from Gerrit itself are running on the
same origin, so they are allowed to read XHR responses even if no CORS
headers are allowed in the response.  Browsers however may still send
Origin header, which likely was not whitelisted by the administrator.

Allow these requests from PolyGerrit and GWT by letting them pass
through into processing.  GET requests will be fulfilled, and the
browser will enforce whether or not the JS can see the XHR reply.
POST/PUT/DELETE requests are still secured by the XSRF token being
required as proof-of-access.  Invalid origins won't have the XSRF
token, and won't be able to present it in the X-Gerrit-Auth header.

Add tests for these conditions to reduce the risk of it being broken
again in the future.

Change-Id: Ia425bd7614a14b011f44910cce49f0f4f9e686a0
This commit is contained in:
Shawn Pearce
2017-06-17 08:54:06 -07:00
parent c6aa1c2774
commit bb47d19f36
2 changed files with 75 additions and 23 deletions

View File

@@ -547,18 +547,21 @@ public class RestApiServlet extends HttpServlet {
private void checkCors(HttpServletRequest req, HttpServletResponse res, boolean isXd)
throws BadRequestException {
String origin = req.getHeader(ORIGIN);
if (!Strings.isNullOrEmpty(origin)) {
res.addHeader(VARY, ORIGIN);
if (!isOriginAllowed(origin)) {
if (isXd) {
// Cross-domain, non-preflighted requests must come from an approved origin.
if (Strings.isNullOrEmpty(origin) || !isOriginAllowed(origin)) {
throw new BadRequestException("origin not allowed");
}
if (isXd) {
res.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
} else {
res.addHeader(VARY, ORIGIN);
res.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
} else if (!Strings.isNullOrEmpty(origin)) {
// All other requests must be processed, but conditionally set CORS headers.
if (globals.allowOrigin != null) {
res.addHeader(VARY, ORIGIN);
}
if (isOriginAllowed(origin)) {
setCorsHeaders(res, origin);
}
} else if (isXd) {
throw new BadRequestException("expected " + ORIGIN);
}
}