@Test public void processRequestInContextUnauthorizedGET() { Mockito.when(request.getMethod()).thenReturn("GET"); Mockito.when( apiServer.verifyRequest(Mockito.anyMap(), Mockito.anyLong(), Mockito.anyString())) .thenReturn(false); servlet.processRequestInContext(request, response); Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); Mockito.verify(apiServer, Mockito.never()).handleRequest( Mockito.anyMap(), Mockito.anyString(), Mockito.any(StringBuilder.class)); }
void processRequestInContext(final HttpServletRequest req, final HttpServletResponse resp) { final String remoteAddress = getClientAddress(req); final StringBuilder auditTrailSb = new StringBuilder(128); auditTrailSb.append(" ").append(remoteAddress); auditTrailSb.append(" -- ").append(req.getMethod()).append(' '); String responseType = HttpUtils.RESPONSE_TYPE_XML; final Map<String, Object[]> params = new HashMap<>(); params.putAll(req.getParameterMap()); utf8Fixup(req, params); String reqStr = ""; final String cleanQueryString = StringUtils.cleanString(req.getQueryString()); if (s_logger.isDebugEnabled()) { reqStr = auditTrailSb.toString() + " " + cleanQueryString; s_logger.debug("===START=== " + reqStr); } try { if (HttpUtils.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { resp.setContentType(ApiServer.getJSONContentType()); } else if (HttpUtils.RESPONSE_TYPE_XML.equalsIgnoreCase(responseType)) { resp.setContentType(HttpUtils.XML_CONTENT_TYPE); } HttpSession session = req.getSession(false); final Object[] responseTypeParam = params.get(ApiConstants.RESPONSE); if (responseTypeParam != null) { responseType = (String) responseTypeParam[0]; } final Object[] commandObj = params.get(ApiConstants.COMMAND); if (commandObj != null) { final String command = (String) commandObj[0]; final APIAuthenticator apiAuthenticator = _authManager.getAPIAuthenticator(command); if (apiAuthenticator != null) { auditTrailSb.append("command="); auditTrailSb.append(command); int httpResponseCode = HttpServletResponse.SC_OK; String responseString; if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGIN_API) { if (session != null) { try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } session = req.getSession(true); if (ApiServer.isSecureSessionCookieEnabled()) { resp.setHeader("SET-COOKIE", String.format("JSESSIONID=%s;Secure;HttpOnly;Path=/client", session.getId())); s_logger.debug("Session cookie is marked secure!"); } } try { responseString = apiAuthenticator.authenticate(command, params, session, InetAddress.getByName(remoteAddress), responseType, auditTrailSb, req, resp); if (session != null && session.getAttribute(ApiConstants.SESSIONKEY) != null) { resp.addHeader("SET-COOKIE", String.format("%s=%s;HttpOnly", ApiConstants.SESSIONKEY, session.getAttribute(ApiConstants.SESSIONKEY))); } } catch (final ServerApiException e) { httpResponseCode = e.getErrorCode().getHttpCode(); responseString = e.getMessage(); s_logger.debug("Authentication failure: " + e.getMessage()); } catch (final UnknownHostException e) { httpResponseCode = 400; responseString = e.getMessage(); s_logger.debug("Authentication failure: " + e.getMessage()); } if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGOUT_API) { if (session != null) { final Long userId = (Long) session.getAttribute("userid"); final Account account = (Account) session.getAttribute("accountobj"); Long accountId = null; if (account != null) { accountId = account.getId(); } auditTrailSb.insert(0, "(userId=" + userId + " accountId=" + accountId + " sessionId=" + session.getId() + ")"); if (userId != null) { _apiServer.logoutUser(userId); } try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } final Cookie sessionKeyCookie = new Cookie(ApiConstants.SESSIONKEY, ""); sessionKeyCookie.setMaxAge(0); resp.addCookie(sessionKeyCookie); } HttpUtils.writeHttpResponse(resp, responseString, httpResponseCode, responseType, ApiServer.getJSONContentType()); return; } } auditTrailSb.append(cleanQueryString); final boolean isNew = ((session == null) ? true : session.isNew()); Long userId = null; if (!isNew) { userId = (Long) session.getAttribute("userid"); final String account = (String) session.getAttribute("account"); final Object accountObj = session.getAttribute("accountobj"); if (!HttpUtils.validateSessionKey(session, params, req.getCookies(), ApiConstants.SESSIONKEY)) { denyAuthenticationRequest(resp, auditTrailSb, responseType, params, session); return; } if ((userId != null) && (account != null) && (accountObj != null) && _apiServer.verifyUser(userId)) { final String[] command = (String[]) params.get(ApiConstants.COMMAND); if (command == null) { s_logger.info("missing command, ignoring request..."); auditTrailSb.append(" " + HttpServletResponse.SC_BAD_REQUEST + " " + "no command specified"); final String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "no command specified", params, responseType); HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_BAD_REQUEST, responseType, ApiServer.getJSONContentType()); return; } final User user = _entityMgr.findById(User.class, userId); CallContext.register(user, (Account) accountObj); } else { denyAuthenticationRequest(resp, auditTrailSb, responseType, params, session); } } else { CallContext.register(_accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); } if (_apiServer.verifyRequest(params, userId, remoteAddress)) { auditTrailSb.insert(0, "(userId=" + CallContext.current().getCallingUserId() + " accountId=" + CallContext.current().getCallingAccount().getId() + " sessionId=" + (session != null ? session.getId() : null) + ")"); params.put("httpmethod", new String[]{req.getMethod()}); final String response = _apiServer.handleRequest(params, responseType, auditTrailSb); HttpUtils.writeHttpResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType, ApiServer.getJSONContentType()); } else { if (session != null) { try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } final String errorMessage = "Permission denied due to: Expired session, unavailable API command or non-authorised from ip-address '" + remoteAddress + "'"; auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + errorMessage); final String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, errorMessage, params, responseType); HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType, ApiServer.getJSONContentType()); } } catch (final ServerApiException se) { final String serializedResponseText = _apiServer.getSerializedApiError(se, params, responseType); resp.setHeader("X-Description", se.getDescription()); HttpUtils.writeHttpResponse(resp, serializedResponseText, se.getErrorCode().getHttpCode(), responseType, ApiServer.getJSONContentType()); auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription()); } catch (final CloudRuntimeException e) { s_logger.error("Caught runtime exception while writing api response", e); auditTrailSb.append("Caught runtime exception while writing api response"); } finally { s_logger.info(auditTrailSb.toString()); if (s_logger.isDebugEnabled()) { s_logger.debug("===END=== " + reqStr); } CallContext.unregister(); } }
ApiServlet extends HttpServlet { void processRequestInContext(final HttpServletRequest req, final HttpServletResponse resp) { final String remoteAddress = getClientAddress(req); final StringBuilder auditTrailSb = new StringBuilder(128); auditTrailSb.append(" ").append(remoteAddress); auditTrailSb.append(" -- ").append(req.getMethod()).append(' '); String responseType = HttpUtils.RESPONSE_TYPE_XML; final Map<String, Object[]> params = new HashMap<>(); params.putAll(req.getParameterMap()); utf8Fixup(req, params); String reqStr = ""; final String cleanQueryString = StringUtils.cleanString(req.getQueryString()); if (s_logger.isDebugEnabled()) { reqStr = auditTrailSb.toString() + " " + cleanQueryString; s_logger.debug("===START=== " + reqStr); } try { if (HttpUtils.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { resp.setContentType(ApiServer.getJSONContentType()); } else if (HttpUtils.RESPONSE_TYPE_XML.equalsIgnoreCase(responseType)) { resp.setContentType(HttpUtils.XML_CONTENT_TYPE); } HttpSession session = req.getSession(false); final Object[] responseTypeParam = params.get(ApiConstants.RESPONSE); if (responseTypeParam != null) { responseType = (String) responseTypeParam[0]; } final Object[] commandObj = params.get(ApiConstants.COMMAND); if (commandObj != null) { final String command = (String) commandObj[0]; final APIAuthenticator apiAuthenticator = _authManager.getAPIAuthenticator(command); if (apiAuthenticator != null) { auditTrailSb.append("command="); auditTrailSb.append(command); int httpResponseCode = HttpServletResponse.SC_OK; String responseString; if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGIN_API) { if (session != null) { try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } session = req.getSession(true); if (ApiServer.isSecureSessionCookieEnabled()) { resp.setHeader("SET-COOKIE", String.format("JSESSIONID=%s;Secure;HttpOnly;Path=/client", session.getId())); s_logger.debug("Session cookie is marked secure!"); } } try { responseString = apiAuthenticator.authenticate(command, params, session, InetAddress.getByName(remoteAddress), responseType, auditTrailSb, req, resp); if (session != null && session.getAttribute(ApiConstants.SESSIONKEY) != null) { resp.addHeader("SET-COOKIE", String.format("%s=%s;HttpOnly", ApiConstants.SESSIONKEY, session.getAttribute(ApiConstants.SESSIONKEY))); } } catch (final ServerApiException e) { httpResponseCode = e.getErrorCode().getHttpCode(); responseString = e.getMessage(); s_logger.debug("Authentication failure: " + e.getMessage()); } catch (final UnknownHostException e) { httpResponseCode = 400; responseString = e.getMessage(); s_logger.debug("Authentication failure: " + e.getMessage()); } if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGOUT_API) { if (session != null) { final Long userId = (Long) session.getAttribute("userid"); final Account account = (Account) session.getAttribute("accountobj"); Long accountId = null; if (account != null) { accountId = account.getId(); } auditTrailSb.insert(0, "(userId=" + userId + " accountId=" + accountId + " sessionId=" + session.getId() + ")"); if (userId != null) { _apiServer.logoutUser(userId); } try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } final Cookie sessionKeyCookie = new Cookie(ApiConstants.SESSIONKEY, ""); sessionKeyCookie.setMaxAge(0); resp.addCookie(sessionKeyCookie); } HttpUtils.writeHttpResponse(resp, responseString, httpResponseCode, responseType, ApiServer.getJSONContentType()); return; } } auditTrailSb.append(cleanQueryString); final boolean isNew = ((session == null) ? true : session.isNew()); Long userId = null; if (!isNew) { userId = (Long) session.getAttribute("userid"); final String account = (String) session.getAttribute("account"); final Object accountObj = session.getAttribute("accountobj"); if (!HttpUtils.validateSessionKey(session, params, req.getCookies(), ApiConstants.SESSIONKEY)) { denyAuthenticationRequest(resp, auditTrailSb, responseType, params, session); return; } if ((userId != null) && (account != null) && (accountObj != null) && _apiServer.verifyUser(userId)) { final String[] command = (String[]) params.get(ApiConstants.COMMAND); if (command == null) { s_logger.info("missing command, ignoring request..."); auditTrailSb.append(" " + HttpServletResponse.SC_BAD_REQUEST + " " + "no command specified"); final String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "no command specified", params, responseType); HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_BAD_REQUEST, responseType, ApiServer.getJSONContentType()); return; } final User user = _entityMgr.findById(User.class, userId); CallContext.register(user, (Account) accountObj); } else { denyAuthenticationRequest(resp, auditTrailSb, responseType, params, session); } } else { CallContext.register(_accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); } if (_apiServer.verifyRequest(params, userId, remoteAddress)) { auditTrailSb.insert(0, "(userId=" + CallContext.current().getCallingUserId() + " accountId=" + CallContext.current().getCallingAccount().getId() + " sessionId=" + (session != null ? session.getId() : null) + ")"); params.put("httpmethod", new String[]{req.getMethod()}); final String response = _apiServer.handleRequest(params, responseType, auditTrailSb); HttpUtils.writeHttpResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType, ApiServer.getJSONContentType()); } else { if (session != null) { try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } final String errorMessage = "Permission denied due to: Expired session, unavailable API command or non-authorised from ip-address '" + remoteAddress + "'"; auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + errorMessage); final String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, errorMessage, params, responseType); HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType, ApiServer.getJSONContentType()); } } catch (final ServerApiException se) { final String serializedResponseText = _apiServer.getSerializedApiError(se, params, responseType); resp.setHeader("X-Description", se.getDescription()); HttpUtils.writeHttpResponse(resp, serializedResponseText, se.getErrorCode().getHttpCode(), responseType, ApiServer.getJSONContentType()); auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription()); } catch (final CloudRuntimeException e) { s_logger.error("Caught runtime exception while writing api response", e); auditTrailSb.append("Caught runtime exception while writing api response"); } finally { s_logger.info(auditTrailSb.toString()); if (s_logger.isDebugEnabled()) { s_logger.debug("===END=== " + reqStr); } CallContext.unregister(); } } }
ApiServlet extends HttpServlet { void processRequestInContext(final HttpServletRequest req, final HttpServletResponse resp) { final String remoteAddress = getClientAddress(req); final StringBuilder auditTrailSb = new StringBuilder(128); auditTrailSb.append(" ").append(remoteAddress); auditTrailSb.append(" -- ").append(req.getMethod()).append(' '); String responseType = HttpUtils.RESPONSE_TYPE_XML; final Map<String, Object[]> params = new HashMap<>(); params.putAll(req.getParameterMap()); utf8Fixup(req, params); String reqStr = ""; final String cleanQueryString = StringUtils.cleanString(req.getQueryString()); if (s_logger.isDebugEnabled()) { reqStr = auditTrailSb.toString() + " " + cleanQueryString; s_logger.debug("===START=== " + reqStr); } try { if (HttpUtils.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { resp.setContentType(ApiServer.getJSONContentType()); } else if (HttpUtils.RESPONSE_TYPE_XML.equalsIgnoreCase(responseType)) { resp.setContentType(HttpUtils.XML_CONTENT_TYPE); } HttpSession session = req.getSession(false); final Object[] responseTypeParam = params.get(ApiConstants.RESPONSE); if (responseTypeParam != null) { responseType = (String) responseTypeParam[0]; } final Object[] commandObj = params.get(ApiConstants.COMMAND); if (commandObj != null) { final String command = (String) commandObj[0]; final APIAuthenticator apiAuthenticator = _authManager.getAPIAuthenticator(command); if (apiAuthenticator != null) { auditTrailSb.append("command="); auditTrailSb.append(command); int httpResponseCode = HttpServletResponse.SC_OK; String responseString; if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGIN_API) { if (session != null) { try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } session = req.getSession(true); if (ApiServer.isSecureSessionCookieEnabled()) { resp.setHeader("SET-COOKIE", String.format("JSESSIONID=%s;Secure;HttpOnly;Path=/client", session.getId())); s_logger.debug("Session cookie is marked secure!"); } } try { responseString = apiAuthenticator.authenticate(command, params, session, InetAddress.getByName(remoteAddress), responseType, auditTrailSb, req, resp); if (session != null && session.getAttribute(ApiConstants.SESSIONKEY) != null) { resp.addHeader("SET-COOKIE", String.format("%s=%s;HttpOnly", ApiConstants.SESSIONKEY, session.getAttribute(ApiConstants.SESSIONKEY))); } } catch (final ServerApiException e) { httpResponseCode = e.getErrorCode().getHttpCode(); responseString = e.getMessage(); s_logger.debug("Authentication failure: " + e.getMessage()); } catch (final UnknownHostException e) { httpResponseCode = 400; responseString = e.getMessage(); s_logger.debug("Authentication failure: " + e.getMessage()); } if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGOUT_API) { if (session != null) { final Long userId = (Long) session.getAttribute("userid"); final Account account = (Account) session.getAttribute("accountobj"); Long accountId = null; if (account != null) { accountId = account.getId(); } auditTrailSb.insert(0, "(userId=" + userId + " accountId=" + accountId + " sessionId=" + session.getId() + ")"); if (userId != null) { _apiServer.logoutUser(userId); } try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } final Cookie sessionKeyCookie = new Cookie(ApiConstants.SESSIONKEY, ""); sessionKeyCookie.setMaxAge(0); resp.addCookie(sessionKeyCookie); } HttpUtils.writeHttpResponse(resp, responseString, httpResponseCode, responseType, ApiServer.getJSONContentType()); return; } } auditTrailSb.append(cleanQueryString); final boolean isNew = ((session == null) ? true : session.isNew()); Long userId = null; if (!isNew) { userId = (Long) session.getAttribute("userid"); final String account = (String) session.getAttribute("account"); final Object accountObj = session.getAttribute("accountobj"); if (!HttpUtils.validateSessionKey(session, params, req.getCookies(), ApiConstants.SESSIONKEY)) { denyAuthenticationRequest(resp, auditTrailSb, responseType, params, session); return; } if ((userId != null) && (account != null) && (accountObj != null) && _apiServer.verifyUser(userId)) { final String[] command = (String[]) params.get(ApiConstants.COMMAND); if (command == null) { s_logger.info("missing command, ignoring request..."); auditTrailSb.append(" " + HttpServletResponse.SC_BAD_REQUEST + " " + "no command specified"); final String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "no command specified", params, responseType); HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_BAD_REQUEST, responseType, ApiServer.getJSONContentType()); return; } final User user = _entityMgr.findById(User.class, userId); CallContext.register(user, (Account) accountObj); } else { denyAuthenticationRequest(resp, auditTrailSb, responseType, params, session); } } else { CallContext.register(_accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); } if (_apiServer.verifyRequest(params, userId, remoteAddress)) { auditTrailSb.insert(0, "(userId=" + CallContext.current().getCallingUserId() + " accountId=" + CallContext.current().getCallingAccount().getId() + " sessionId=" + (session != null ? session.getId() : null) + ")"); params.put("httpmethod", new String[]{req.getMethod()}); final String response = _apiServer.handleRequest(params, responseType, auditTrailSb); HttpUtils.writeHttpResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType, ApiServer.getJSONContentType()); } else { if (session != null) { try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } final String errorMessage = "Permission denied due to: Expired session, unavailable API command or non-authorised from ip-address '" + remoteAddress + "'"; auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + errorMessage); final String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, errorMessage, params, responseType); HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType, ApiServer.getJSONContentType()); } } catch (final ServerApiException se) { final String serializedResponseText = _apiServer.getSerializedApiError(se, params, responseType); resp.setHeader("X-Description", se.getDescription()); HttpUtils.writeHttpResponse(resp, serializedResponseText, se.getErrorCode().getHttpCode(), responseType, ApiServer.getJSONContentType()); auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription()); } catch (final CloudRuntimeException e) { s_logger.error("Caught runtime exception while writing api response", e); auditTrailSb.append("Caught runtime exception while writing api response"); } finally { s_logger.info(auditTrailSb.toString()); if (s_logger.isDebugEnabled()) { s_logger.debug("===END=== " + reqStr); } CallContext.unregister(); } } ApiServlet(); }
ApiServlet extends HttpServlet { void processRequestInContext(final HttpServletRequest req, final HttpServletResponse resp) { final String remoteAddress = getClientAddress(req); final StringBuilder auditTrailSb = new StringBuilder(128); auditTrailSb.append(" ").append(remoteAddress); auditTrailSb.append(" -- ").append(req.getMethod()).append(' '); String responseType = HttpUtils.RESPONSE_TYPE_XML; final Map<String, Object[]> params = new HashMap<>(); params.putAll(req.getParameterMap()); utf8Fixup(req, params); String reqStr = ""; final String cleanQueryString = StringUtils.cleanString(req.getQueryString()); if (s_logger.isDebugEnabled()) { reqStr = auditTrailSb.toString() + " " + cleanQueryString; s_logger.debug("===START=== " + reqStr); } try { if (HttpUtils.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { resp.setContentType(ApiServer.getJSONContentType()); } else if (HttpUtils.RESPONSE_TYPE_XML.equalsIgnoreCase(responseType)) { resp.setContentType(HttpUtils.XML_CONTENT_TYPE); } HttpSession session = req.getSession(false); final Object[] responseTypeParam = params.get(ApiConstants.RESPONSE); if (responseTypeParam != null) { responseType = (String) responseTypeParam[0]; } final Object[] commandObj = params.get(ApiConstants.COMMAND); if (commandObj != null) { final String command = (String) commandObj[0]; final APIAuthenticator apiAuthenticator = _authManager.getAPIAuthenticator(command); if (apiAuthenticator != null) { auditTrailSb.append("command="); auditTrailSb.append(command); int httpResponseCode = HttpServletResponse.SC_OK; String responseString; if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGIN_API) { if (session != null) { try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } session = req.getSession(true); if (ApiServer.isSecureSessionCookieEnabled()) { resp.setHeader("SET-COOKIE", String.format("JSESSIONID=%s;Secure;HttpOnly;Path=/client", session.getId())); s_logger.debug("Session cookie is marked secure!"); } } try { responseString = apiAuthenticator.authenticate(command, params, session, InetAddress.getByName(remoteAddress), responseType, auditTrailSb, req, resp); if (session != null && session.getAttribute(ApiConstants.SESSIONKEY) != null) { resp.addHeader("SET-COOKIE", String.format("%s=%s;HttpOnly", ApiConstants.SESSIONKEY, session.getAttribute(ApiConstants.SESSIONKEY))); } } catch (final ServerApiException e) { httpResponseCode = e.getErrorCode().getHttpCode(); responseString = e.getMessage(); s_logger.debug("Authentication failure: " + e.getMessage()); } catch (final UnknownHostException e) { httpResponseCode = 400; responseString = e.getMessage(); s_logger.debug("Authentication failure: " + e.getMessage()); } if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGOUT_API) { if (session != null) { final Long userId = (Long) session.getAttribute("userid"); final Account account = (Account) session.getAttribute("accountobj"); Long accountId = null; if (account != null) { accountId = account.getId(); } auditTrailSb.insert(0, "(userId=" + userId + " accountId=" + accountId + " sessionId=" + session.getId() + ")"); if (userId != null) { _apiServer.logoutUser(userId); } try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } final Cookie sessionKeyCookie = new Cookie(ApiConstants.SESSIONKEY, ""); sessionKeyCookie.setMaxAge(0); resp.addCookie(sessionKeyCookie); } HttpUtils.writeHttpResponse(resp, responseString, httpResponseCode, responseType, ApiServer.getJSONContentType()); return; } } auditTrailSb.append(cleanQueryString); final boolean isNew = ((session == null) ? true : session.isNew()); Long userId = null; if (!isNew) { userId = (Long) session.getAttribute("userid"); final String account = (String) session.getAttribute("account"); final Object accountObj = session.getAttribute("accountobj"); if (!HttpUtils.validateSessionKey(session, params, req.getCookies(), ApiConstants.SESSIONKEY)) { denyAuthenticationRequest(resp, auditTrailSb, responseType, params, session); return; } if ((userId != null) && (account != null) && (accountObj != null) && _apiServer.verifyUser(userId)) { final String[] command = (String[]) params.get(ApiConstants.COMMAND); if (command == null) { s_logger.info("missing command, ignoring request..."); auditTrailSb.append(" " + HttpServletResponse.SC_BAD_REQUEST + " " + "no command specified"); final String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "no command specified", params, responseType); HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_BAD_REQUEST, responseType, ApiServer.getJSONContentType()); return; } final User user = _entityMgr.findById(User.class, userId); CallContext.register(user, (Account) accountObj); } else { denyAuthenticationRequest(resp, auditTrailSb, responseType, params, session); } } else { CallContext.register(_accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); } if (_apiServer.verifyRequest(params, userId, remoteAddress)) { auditTrailSb.insert(0, "(userId=" + CallContext.current().getCallingUserId() + " accountId=" + CallContext.current().getCallingAccount().getId() + " sessionId=" + (session != null ? session.getId() : null) + ")"); params.put("httpmethod", new String[]{req.getMethod()}); final String response = _apiServer.handleRequest(params, responseType, auditTrailSb); HttpUtils.writeHttpResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType, ApiServer.getJSONContentType()); } else { if (session != null) { try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } final String errorMessage = "Permission denied due to: Expired session, unavailable API command or non-authorised from ip-address '" + remoteAddress + "'"; auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + errorMessage); final String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, errorMessage, params, responseType); HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType, ApiServer.getJSONContentType()); } } catch (final ServerApiException se) { final String serializedResponseText = _apiServer.getSerializedApiError(se, params, responseType); resp.setHeader("X-Description", se.getDescription()); HttpUtils.writeHttpResponse(resp, serializedResponseText, se.getErrorCode().getHttpCode(), responseType, ApiServer.getJSONContentType()); auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription()); } catch (final CloudRuntimeException e) { s_logger.error("Caught runtime exception while writing api response", e); auditTrailSb.append("Caught runtime exception while writing api response"); } finally { s_logger.info(auditTrailSb.toString()); if (s_logger.isDebugEnabled()) { s_logger.debug("===END=== " + reqStr); } CallContext.unregister(); } } ApiServlet(); @Override void init(final ServletConfig config); }
ApiServlet extends HttpServlet { void processRequestInContext(final HttpServletRequest req, final HttpServletResponse resp) { final String remoteAddress = getClientAddress(req); final StringBuilder auditTrailSb = new StringBuilder(128); auditTrailSb.append(" ").append(remoteAddress); auditTrailSb.append(" -- ").append(req.getMethod()).append(' '); String responseType = HttpUtils.RESPONSE_TYPE_XML; final Map<String, Object[]> params = new HashMap<>(); params.putAll(req.getParameterMap()); utf8Fixup(req, params); String reqStr = ""; final String cleanQueryString = StringUtils.cleanString(req.getQueryString()); if (s_logger.isDebugEnabled()) { reqStr = auditTrailSb.toString() + " " + cleanQueryString; s_logger.debug("===START=== " + reqStr); } try { if (HttpUtils.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { resp.setContentType(ApiServer.getJSONContentType()); } else if (HttpUtils.RESPONSE_TYPE_XML.equalsIgnoreCase(responseType)) { resp.setContentType(HttpUtils.XML_CONTENT_TYPE); } HttpSession session = req.getSession(false); final Object[] responseTypeParam = params.get(ApiConstants.RESPONSE); if (responseTypeParam != null) { responseType = (String) responseTypeParam[0]; } final Object[] commandObj = params.get(ApiConstants.COMMAND); if (commandObj != null) { final String command = (String) commandObj[0]; final APIAuthenticator apiAuthenticator = _authManager.getAPIAuthenticator(command); if (apiAuthenticator != null) { auditTrailSb.append("command="); auditTrailSb.append(command); int httpResponseCode = HttpServletResponse.SC_OK; String responseString; if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGIN_API) { if (session != null) { try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } session = req.getSession(true); if (ApiServer.isSecureSessionCookieEnabled()) { resp.setHeader("SET-COOKIE", String.format("JSESSIONID=%s;Secure;HttpOnly;Path=/client", session.getId())); s_logger.debug("Session cookie is marked secure!"); } } try { responseString = apiAuthenticator.authenticate(command, params, session, InetAddress.getByName(remoteAddress), responseType, auditTrailSb, req, resp); if (session != null && session.getAttribute(ApiConstants.SESSIONKEY) != null) { resp.addHeader("SET-COOKIE", String.format("%s=%s;HttpOnly", ApiConstants.SESSIONKEY, session.getAttribute(ApiConstants.SESSIONKEY))); } } catch (final ServerApiException e) { httpResponseCode = e.getErrorCode().getHttpCode(); responseString = e.getMessage(); s_logger.debug("Authentication failure: " + e.getMessage()); } catch (final UnknownHostException e) { httpResponseCode = 400; responseString = e.getMessage(); s_logger.debug("Authentication failure: " + e.getMessage()); } if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGOUT_API) { if (session != null) { final Long userId = (Long) session.getAttribute("userid"); final Account account = (Account) session.getAttribute("accountobj"); Long accountId = null; if (account != null) { accountId = account.getId(); } auditTrailSb.insert(0, "(userId=" + userId + " accountId=" + accountId + " sessionId=" + session.getId() + ")"); if (userId != null) { _apiServer.logoutUser(userId); } try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } final Cookie sessionKeyCookie = new Cookie(ApiConstants.SESSIONKEY, ""); sessionKeyCookie.setMaxAge(0); resp.addCookie(sessionKeyCookie); } HttpUtils.writeHttpResponse(resp, responseString, httpResponseCode, responseType, ApiServer.getJSONContentType()); return; } } auditTrailSb.append(cleanQueryString); final boolean isNew = ((session == null) ? true : session.isNew()); Long userId = null; if (!isNew) { userId = (Long) session.getAttribute("userid"); final String account = (String) session.getAttribute("account"); final Object accountObj = session.getAttribute("accountobj"); if (!HttpUtils.validateSessionKey(session, params, req.getCookies(), ApiConstants.SESSIONKEY)) { denyAuthenticationRequest(resp, auditTrailSb, responseType, params, session); return; } if ((userId != null) && (account != null) && (accountObj != null) && _apiServer.verifyUser(userId)) { final String[] command = (String[]) params.get(ApiConstants.COMMAND); if (command == null) { s_logger.info("missing command, ignoring request..."); auditTrailSb.append(" " + HttpServletResponse.SC_BAD_REQUEST + " " + "no command specified"); final String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "no command specified", params, responseType); HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_BAD_REQUEST, responseType, ApiServer.getJSONContentType()); return; } final User user = _entityMgr.findById(User.class, userId); CallContext.register(user, (Account) accountObj); } else { denyAuthenticationRequest(resp, auditTrailSb, responseType, params, session); } } else { CallContext.register(_accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); } if (_apiServer.verifyRequest(params, userId, remoteAddress)) { auditTrailSb.insert(0, "(userId=" + CallContext.current().getCallingUserId() + " accountId=" + CallContext.current().getCallingAccount().getId() + " sessionId=" + (session != null ? session.getId() : null) + ")"); params.put("httpmethod", new String[]{req.getMethod()}); final String response = _apiServer.handleRequest(params, responseType, auditTrailSb); HttpUtils.writeHttpResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType, ApiServer.getJSONContentType()); } else { if (session != null) { try { session.invalidate(); } catch (final IllegalStateException e) { s_logger.warn("Previously ignored exception", e); } } final String errorMessage = "Permission denied due to: Expired session, unavailable API command or non-authorised from ip-address '" + remoteAddress + "'"; auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + errorMessage); final String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, errorMessage, params, responseType); HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType, ApiServer.getJSONContentType()); } } catch (final ServerApiException se) { final String serializedResponseText = _apiServer.getSerializedApiError(se, params, responseType); resp.setHeader("X-Description", se.getDescription()); HttpUtils.writeHttpResponse(resp, serializedResponseText, se.getErrorCode().getHttpCode(), responseType, ApiServer.getJSONContentType()); auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription()); } catch (final CloudRuntimeException e) { s_logger.error("Caught runtime exception while writing api response", e); auditTrailSb.append("Caught runtime exception while writing api response"); } finally { s_logger.info(auditTrailSb.toString()); if (s_logger.isDebugEnabled()) { s_logger.debug("===END=== " + reqStr); } CallContext.unregister(); } } ApiServlet(); @Override void init(final ServletConfig config); static final Logger s_logger; }