Add a JSON response instead of default error page

Use custom error handler instead of default that leaks server info.

- Use in API context
- Use in default/web context
- Add tests
This commit is contained in:
hugh-obrien 2017-07-14 17:46:54 +01:00 committed by Michael Mazour
parent 0d2a33be14
commit d9e368ac35
3 changed files with 60 additions and 0 deletions

View file

@ -123,6 +123,9 @@ public class GitBridgeServer {
handlers.addHandler(new DefaultHandler());
api.setHandler(handlers);
ProductionErrorHandler errorHandler = new ProductionErrorHandler();
api.setErrorHandler(errorHandler);
return api;
}
@ -149,6 +152,8 @@ public class GitBridgeServer {
),
"/*"
);
ProductionErrorHandler errorHandler = new ProductionErrorHandler();
servletContextHandler.setErrorHandler(errorHandler);
return servletContextHandler;
}

View file

@ -0,0 +1,21 @@
package uk.ac.ic.wlgitbridge.server;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.handler.ErrorHandler;
import java.io.IOException;
public class ProductionErrorHandler extends ErrorHandler {
@Override
public void handle(
String target,
org.eclipse.jetty.server.Request baseRequest,
HttpServletRequest request,
HttpServletResponse response
) throws IOException {
response.getWriter()
.append("{\"message\":\"HTTP error ")
.append(String.valueOf(response.getStatus()))
.append("\"}");
}
}

View file

@ -693,6 +693,40 @@ public class WLGitBridgeIntegrationTest {
wlgb.stop();
}
@Test
public void usesCustomErrorHandler(
) throws IOException, ExecutionException, InterruptedException {
int gitBridgePort = 33873;
int mockServerPort = 3873;
MockSnapshotServer server = new MockSnapshotServer(
mockServerPort, getResource("/canServePushedFiles").toFile());
server.start();
server.setState(states.get("canServePushedFiles").get("state"));
GitBridgeApp wlgb = new GitBridgeApp(new String[] {
makeConfigFile(gitBridgePort, mockServerPort)
});
wlgb.run();
// With an invalid project and no key, we should get a 404,
// which is rendered by our custom error handler.
String url = "http://127.0.0.1:" + gitBridgePort + "/api/notavalidproject/main.tex";
Response response = new AsyncHttpClient().prepareGet(url).execute().get();
assertEquals(404, response.getStatusCode());
assertEquals("{\"message\":\"HTTP error 404\"}", response.getResponseBody());
// With an unsupported URL outside the api, we should get a 500,
// which is rendered by our custom error handler.
url = "http://127.0.0.1:" + gitBridgePort + "/foo";
response = new AsyncHttpClient().prepareGet(url).execute().get();
assertEquals(500, response.getStatusCode());
assertEquals("{\"message\":\"HTTP error 500\"}", response.getResponseBody());
wlgb.stop();
}
private String makeConfigFile(
int port,
int apiPort