From 89ce1571c4855d196660e784235c87c550ea0e03 Mon Sep 17 00:00:00 2001 From: Ashley Mercer Date: Sat, 8 Jul 2017 20:59:58 +0100 Subject: [PATCH 1/2] Allow java-saml to be used in non-JavaEE containers The default Auth and ServletUtils classes were previously tied to the javax.servlet APIs, so couldn't be used in other frameworks (e.g. Play) Instead, introduce abstract HttpRequest and HttpResponse classes which can be used as wrappers around different request and response objects depending on the framework (plus default javax implementations). --- .../main/java/com/onelogin/saml2/Auth.java | 52 ++- .../com/onelogin/saml2/http/HttpRequest.java | 178 ++------- .../com/onelogin/saml2/http/HttpResponse.java | 21 + .../onelogin/saml2/servlet/ServletUtils.java | 73 ++-- .../com/onelogin/saml2/test/AuthTest.java | 361 ++++++++---------- .../saml2/test/authn/AuthnResponseTest.java | 4 +- .../saml2/test/http/MockHttpRequest.java | 191 +++++++++ .../http/MockHttpRequestTest.java} | 50 +-- .../saml2/test/logout/LogoutRequestTest.java | 9 +- .../saml2/test/logout/LogoutResponseTest.java | 15 +- .../saml2/test/servlet/ServletUtilsTest.java | 83 +--- .../onelogin/saml2/http/JavaxHttpRequest.java | 66 ++++ .../saml2/http/JavaxHttpResponse.java | 27 ++ 13 files changed, 591 insertions(+), 539 deletions(-) rename {toolkit => core}/src/main/java/com/onelogin/saml2/Auth.java (93%) create mode 100644 core/src/main/java/com/onelogin/saml2/http/HttpResponse.java rename {toolkit => core}/src/main/java/com/onelogin/saml2/servlet/ServletUtils.java (62%) rename {toolkit => core}/src/test/java/com/onelogin/saml2/test/AuthTest.java (80%) create mode 100644 core/src/test/java/com/onelogin/saml2/test/http/MockHttpRequest.java rename core/src/test/java/com/onelogin/saml2/{http/HttpRequestTest.java => test/http/MockHttpRequestTest.java} (71%) rename {toolkit => core}/src/test/java/com/onelogin/saml2/test/servlet/ServletUtilsTest.java (68%) create mode 100644 toolkit/src/main/java/com/onelogin/saml2/http/JavaxHttpRequest.java create mode 100644 toolkit/src/main/java/com/onelogin/saml2/http/JavaxHttpResponse.java diff --git a/toolkit/src/main/java/com/onelogin/saml2/Auth.java b/core/src/main/java/com/onelogin/saml2/Auth.java similarity index 93% rename from toolkit/src/main/java/com/onelogin/saml2/Auth.java rename to core/src/main/java/com/onelogin/saml2/Auth.java index db03c967..1bbee0d0 100644 --- a/toolkit/src/main/java/com/onelogin/saml2/Auth.java +++ b/core/src/main/java/com/onelogin/saml2/Auth.java @@ -12,9 +12,6 @@ import java.util.List; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.Instant; @@ -27,6 +24,7 @@ import com.onelogin.saml2.exception.Error; import com.onelogin.saml2.exception.XMLEntityException; import com.onelogin.saml2.http.HttpRequest; +import com.onelogin.saml2.http.HttpResponse; import com.onelogin.saml2.logout.LogoutRequest; import com.onelogin.saml2.logout.LogoutResponse; import com.onelogin.saml2.servlet.ServletUtils; @@ -57,14 +55,14 @@ public class Auth { private Saml2Settings settings; /** - * HttpServletRequest object to be processed (Contains GET and POST parameters, session, ...). + * HttpRequest object to be processed (Contains GET and POST parameters, session, ...). */ - private HttpServletRequest request; + private HttpRequest request; /** - * HttpServletResponse object to be used (For example to execute the redirections). + * HttpResponse object to be used (For example to execute the redirections). */ - private HttpServletResponse response; + private HttpResponse response; /** * NameID. @@ -168,15 +166,15 @@ public Auth(String filename) throws IOException, SettingsException, Error { * Initializes the SP SAML instance. * * @param request - * HttpServletRequest object to be processed + * HttpRequest object to be processed * @param response - * HttpServletResponse object to be used + * HttpResponse object to be used * * @throws IOException * @throws SettingsException * @throws Error */ - public Auth(HttpServletRequest request, HttpServletResponse response) throws IOException, SettingsException, Error { + public Auth(HttpRequest request, HttpResponse response) throws IOException, SettingsException, Error { this(new SettingsBuilder().fromFile("onelogin.saml.properties").build(), request, response); } @@ -186,15 +184,15 @@ public Auth(HttpServletRequest request, HttpServletResponse response) throws IOE * @param filename * String Filename with the settings * @param request - * HttpServletRequest object to be processed + * HttpRequest object to be processed * @param response - * HttpServletResponse object to be used + * HttpResponse object to be used * * @throws SettingsException * @throws IOException * @throws Error */ - public Auth(String filename, HttpServletRequest request, HttpServletResponse response) throws SettingsException, IOException, Error { + public Auth(String filename, HttpRequest request, HttpResponse response) throws SettingsException, IOException, Error { this(new SettingsBuilder().fromFile(filename).build(), request, response); } @@ -204,13 +202,13 @@ public Auth(String filename, HttpServletRequest request, HttpServletResponse res * @param settings * Saml2Settings object. Setting data * @param request - * HttpServletRequest object to be processed + * HttpRequest object to be processed * @param response - * HttpServletResponse object to be used + * HttpResponse object to be used * * @throws SettingsException */ - public Auth(Saml2Settings settings, HttpServletRequest request, HttpServletResponse response) throws SettingsException { + public Auth(Saml2Settings settings, HttpRequest request, HttpResponse response) throws SettingsException { this.settings = settings; this.request = request; this.response = response; @@ -516,11 +514,10 @@ public String getSLOResponseUrl() { */ public void processResponse(String requestId) throws Exception { authenticated = false; - final HttpRequest httpRequest = ServletUtils.makeHttpRequest(this.request); - final String samlResponseParameter = httpRequest.getParameter("SAMLResponse"); + final String samlResponseParameter = request.getParameter("SAMLResponse"); if (samlResponseParameter != null) { - SamlResponse samlResponse = new SamlResponse(settings, httpRequest); + SamlResponse samlResponse = new SamlResponse(settings, request); lastResponse = samlResponse.getSAMLResponseXml(); if (samlResponse.isValid(requestId)) { @@ -568,13 +565,12 @@ public void processResponse() throws Exception { * @throws Exception */ public void processSLO(Boolean keepLocalSession, String requestId) throws Exception { - final HttpRequest httpRequest = ServletUtils.makeHttpRequest(this.request); - final String samlRequestParameter = httpRequest.getParameter("SAMLRequest"); - final String samlResponseParameter = httpRequest.getParameter("SAMLResponse"); + final String samlRequestParameter = request.getParameter("SAMLRequest"); + final String samlResponseParameter = request.getParameter("SAMLResponse"); if (samlResponseParameter != null) { - LogoutResponse logoutResponse = new LogoutResponse(settings, httpRequest); + LogoutResponse logoutResponse = new LogoutResponse(settings, request); lastResponse = logoutResponse.getLogoutResponseXml(); if (!logoutResponse.isValid(requestId)) { errors.add("invalid_logout_response"); @@ -591,12 +587,12 @@ public void processSLO(Boolean keepLocalSession, String requestId) throws Except lastMessageId = logoutResponse.getId(); LOGGER.debug("processSLO success --> " + samlResponseParameter); if (!keepLocalSession) { - request.getSession().invalidate(); + request.invalidateSession(); } } } } else if (samlRequestParameter != null) { - LogoutRequest logoutRequest = new LogoutRequest(settings, httpRequest); + LogoutRequest logoutRequest = new LogoutRequest(settings, request); lastRequest = logoutRequest.getLogoutRequestXml(); if (!logoutRequest.isValid()) { errors.add("invalid_logout_request"); @@ -607,11 +603,11 @@ public void processSLO(Boolean keepLocalSession, String requestId) throws Except lastMessageId = logoutRequest.getId(); LOGGER.debug("processSLO success --> " + samlRequestParameter); if (!keepLocalSession) { - request.getSession().invalidate(); + request.invalidateSession(); } String inResponseTo = logoutRequest.id; - LogoutResponse logoutResponseBuilder = new LogoutResponse(settings, httpRequest); + LogoutResponse logoutResponseBuilder = new LogoutResponse(settings, request); logoutResponseBuilder.build(inResponseTo); lastResponse = logoutResponseBuilder.getLogoutResponseXml(); @@ -819,7 +815,7 @@ public String buildResponseSignature(String samlResponse, String relayState, Str /** * Generates the Signature for a SAML Response * - * @param samlResponse + * @param samlMessage * The SAML Response * @param relayState * The RelayState diff --git a/core/src/main/java/com/onelogin/saml2/http/HttpRequest.java b/core/src/main/java/com/onelogin/saml2/http/HttpRequest.java index 6567bcf5..51274f20 100644 --- a/core/src/main/java/com/onelogin/saml2/http/HttpRequest.java +++ b/core/src/main/java/com/onelogin/saml2/http/HttpRequest.java @@ -1,151 +1,61 @@ package com.onelogin.saml2.http; -import static com.onelogin.saml2.util.Preconditions.checkNotNull; -import static java.util.Collections.unmodifiableList; -import static java.util.Collections.unmodifiableMap; +import com.onelogin.saml2.util.Util; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.commons.lang3.StringUtils; - -import com.onelogin.saml2.util.Util; - /** * Framework-agnostic representation of an HTTP request. * * @since 2.0.0 */ -public final class HttpRequest { - - public static final Map> EMPTY_PARAMETERS = Collections.>emptyMap(); - - private final String requestURL; - private final Map> parameters; - private final String queryString; +public abstract class HttpRequest { /** - * Creates a new HttpRequest. - * - * @param requestURL the request URL (up to but not including query parameters) - * @throws NullPointerException if requestURL is null - * @deprecated Not providing a queryString can cause HTTP Redirect binding to fail. + * @return true if the request is using a secure scheme (HTTPS) */ - @Deprecated - public HttpRequest(String requestURL) { - this(requestURL, EMPTY_PARAMETERS); - } + public abstract boolean isSecure(); /** - * Creates a new HttpRequest. - * - * @param requestURL the request URL (up to but not including query parameters) - * @param queryString string that is contained in the request URL after the path + * @return the name of the request protocol (HTTP / HTTPS) */ - public HttpRequest(String requestURL, String queryString) { - this(requestURL, EMPTY_PARAMETERS, queryString); - } + public abstract String getScheme(); /** - * Creates a new HttpRequest. - * - * @param requestURL the request URL (up to but not including query parameters) - * @param parameters the request query parameters - * @throws NullPointerException if any of the parameters is null - * @deprecated Not providing a queryString can cause HTTP Redirect binding to fail. + * @return the server name in the request e.g. www.example.com */ - @Deprecated - public HttpRequest(String requestURL, Map> parameters) { - this(requestURL, parameters, null); - } + public abstract String getServerName(); /** - * Creates a new HttpRequest. - * - * @param requestURL the request URL (up to but not including query parameters) - * @param parameters the request query parameters - * @param queryString string that is contained in the request URL after the path - * @throws NullPointerException if any of the parameters is null + * @return the port over which the request is made e.g. 80 or 443 */ - public HttpRequest(String requestURL, Map> parameters, String queryString) { - this.requestURL = checkNotNull(requestURL, "requestURL"); - this.parameters = unmodifiableCopyOf(checkNotNull(parameters, "queryParams")); - this.queryString = StringUtils.trimToEmpty(queryString); - } + public abstract int getServerPort(); /** - * @param name the query parameter name - * @param value the query parameter value - * @return a new HttpRequest with the given query parameter added - * @throws NullPointerException if any of the parameters is null + * @return the query string part of the URL */ - public HttpRequest addParameter(String name, String value) { - checkNotNull(name, "name"); - checkNotNull(value, "value"); - - final List oldValues = parameters.containsKey(name) ? parameters.get(name) : new ArrayList(); - final List newValues = new ArrayList<>(oldValues); - newValues.add(value); - final Map> params = new HashMap<>(parameters); - params.put(name, newValues); - - return new HttpRequest(requestURL, params, queryString); - } + public abstract String getQueryString(); /** - * @param name the query parameter name - * @return a new HttpRequest with the given query parameter removed - * @throws NullPointerException if any of the parameters is null + * @return the URI the client used to make the request - only includes + * the server path, but not the query string parameters. */ - public HttpRequest removeParameter(String name) { - checkNotNull(name, "name"); - - final Map> params = new HashMap<>(parameters); - params.remove(name); + public abstract String getRequestURI(); - return new HttpRequest(requestURL, params, queryString); - } - /** * The URL the client used to make the request. Includes a protocol, server name, port number, and server path, but * not the query string parameters. * * @return the request URL */ - public String getRequestURL() { - return requestURL; - } + public abstract String getRequestURL(); /** * @param name the query parameter name * @return the first value for the parameter, or null */ - public String getParameter(String name) { - List values = getParameters(name); - return values.isEmpty() ? null : values.get(0); - } - - /** - * @param name the query parameter name - * @return a List containing all values for the parameter - */ - public List getParameters(String name) { - List values = parameters.get(name); - return values != null ? values : Collections.emptyList(); - } - - /** - * @return a map of all query parameters - */ - public Map> getParameters() { - return parameters; - } + public abstract String getParameter(String name); /** * Return an url encoded get parameter value @@ -155,8 +65,8 @@ public Map> getParameters() { * @param name * @return the first value for the parameter, or null */ - public String getEncodedParameter(String name) { - Matcher matcher = Pattern.compile(Pattern.quote(name) + "=([^&#]+)").matcher(queryString); + public final String getEncodedParameter(String name) { + Matcher matcher = Pattern.compile(Pattern.quote(name) + "=([^&#]+)").matcher(getQueryString()); if (matcher.find()) { return matcher.group(1); } else { @@ -173,49 +83,13 @@ public String getEncodedParameter(String name) { * @param defaultValue * @return the first value for the parameter, or url encoded default value */ - public String getEncodedParameter(String name, String defaultValue) { - String value = getEncodedParameter(name); - return (value != null ? value : Util.urlEncoder(defaultValue)); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - HttpRequest that = (HttpRequest) o; - return Objects.equals(requestURL, that.requestURL) && - Objects.equals(parameters, that.parameters) && - Objects.equals(queryString, that.queryString); + public final String getEncodedParameter(String name, String defaultValue) { + String value = getEncodedParameter(name); + return (value != null ? value : Util.urlEncoder(defaultValue)); } - @Override - public int hashCode() { - return Objects.hash(requestURL, parameters, queryString); - } - - @Override - public String toString() { - return "HttpRequest{" + - "requestURL='" + requestURL + '\'' + - ", parameters=" + parameters + - ", queryString=" + queryString + - '}'; - } - - private static Map> unmodifiableCopyOf(Map> orig) { - Map> copy = new HashMap<>(); - for (Map.Entry> entry : orig.entrySet()) { - copy.put(entry.getKey(), unmodifiableList(new ArrayList<>(entry.getValue()))); - } - - return unmodifiableMap(copy); - } - - + /** + * Invalidate the current session + */ + public abstract void invalidateSession(); } diff --git a/core/src/main/java/com/onelogin/saml2/http/HttpResponse.java b/core/src/main/java/com/onelogin/saml2/http/HttpResponse.java new file mode 100644 index 00000000..dc65487a --- /dev/null +++ b/core/src/main/java/com/onelogin/saml2/http/HttpResponse.java @@ -0,0 +1,21 @@ +package com.onelogin.saml2.http; + +import java.io.IOException; + +/** + * Framework-agnostic representation of an HTTP response. + * + * @since 2.2.0 + */ +public abstract class HttpResponse { + + /** + * Sends an HTTP redirect to the target URL + * + * @param target + * the URL to redirect to + * @throws IOException + * if the redirect could not be sent + */ + public abstract void sendRedirect(String target) throws IOException; +} diff --git a/toolkit/src/main/java/com/onelogin/saml2/servlet/ServletUtils.java b/core/src/main/java/com/onelogin/saml2/servlet/ServletUtils.java similarity index 62% rename from toolkit/src/main/java/com/onelogin/saml2/servlet/ServletUtils.java rename to core/src/main/java/com/onelogin/saml2/servlet/ServletUtils.java index c62bdd71..946849d2 100644 --- a/toolkit/src/main/java/com/onelogin/saml2/servlet/ServletUtils.java +++ b/core/src/main/java/com/onelogin/saml2/servlet/ServletUtils.java @@ -1,58 +1,35 @@ package com.onelogin.saml2.servlet; import java.io.IOException; -import java.util.Arrays; import java.util.HashMap; -import java.util.List; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; - import com.onelogin.saml2.http.HttpRequest; +import com.onelogin.saml2.http.HttpResponse; import com.onelogin.saml2.util.Util; /** * ServletUtils class of OneLogin's Java Toolkit. * - * A class that contains several auxiliary methods related to HttpServletRequest and HttpServletResponse + * A class that contains several auxiliary methods related to HttpRequest and HttpResponse */ public class ServletUtils { private ServletUtils() { //not called } - - /** - * Creates an HttpRequest from an HttpServletRequest. - * - * @param req the incoming HttpServletRequest - * @return a HttpRequest - */ - public static HttpRequest makeHttpRequest(HttpServletRequest req) { - @SuppressWarnings("unchecked") - final Map paramsAsArray = (Map) req.getParameterMap(); - final Map> paramsAsList = new HashMap<>(); - for (Map.Entry param : paramsAsArray.entrySet()) { - paramsAsList.put(param.getKey(), Arrays.asList(param.getValue())); - } - - return new HttpRequest(req.getRequestURL().toString(), paramsAsList, req.getQueryString()); - } /** * Returns the protocol + the current host + the port (if different than * common ports). * * @param request - * HttpServletRequest object to be processed + * HttpRequest object to be processed * * @return the HOST URL */ - public static String getSelfURLhost(HttpServletRequest request) { - String hostUrl = StringUtils.EMPTY; + public static String getSelfURLhost(HttpRequest request) { + final String hostUrl; final int serverPort = request.getServerPort(); if ((serverPort == 80) || (serverPort == 443) || serverPort == 0) { hostUrl = String.format("%s://%s", request.getScheme(), request.getServerName()); @@ -64,11 +41,11 @@ public static String getSelfURLhost(HttpServletRequest request) { /** * @param request - * HttpServletRequest object to be processed + * HttpRequest object to be processed * * @return the server name */ - public static String getSelfHost(HttpServletRequest request) { + public static String getSelfHost(HttpRequest request) { return request.getServerName(); } @@ -76,11 +53,11 @@ public static String getSelfHost(HttpServletRequest request) { * Check if under https or http protocol * * @param request - * HttpServletRequest object to be processed + * HttpRequest object to be processed * * @return false if https is not active */ - public static boolean isHTTPS(HttpServletRequest request) { + public static boolean isHTTPS(HttpRequest request) { return request.isSecure(); } @@ -88,11 +65,11 @@ public static boolean isHTTPS(HttpServletRequest request) { * Returns the URL of the current context + current view + query * * @param request - * HttpServletRequest object to be processed + * HttpRequest object to be processed * * @return current context + current view + query */ - public static String getSelfURL(HttpServletRequest request) { + public static String getSelfURL(HttpRequest request) { String url = getSelfURLhost(request); String requestUri = request.getRequestURI(); @@ -112,23 +89,23 @@ public static String getSelfURL(HttpServletRequest request) { * Returns the URL of the current host + current view. * * @param request - * HttpServletRequest object to be processed + * HttpRequest object to be processed * * @return current host + current view */ - public static String getSelfURLNoQuery(HttpServletRequest request) { - return request.getRequestURL().toString(); + public static String getSelfURLNoQuery(HttpRequest request) { + return request.getRequestURL(); } /** * Returns the routed URL of the current host + current view. * * @param request - * HttpServletRequest object to be processed + * HttpRequest object to be processed * * @return the current routed url */ - public static String getSelfRoutedURLNoQuery(HttpServletRequest request) { + public static String getSelfRoutedURLNoQuery(HttpRequest request) { String url = getSelfURLhost(request); String requestUri = request.getRequestURI(); if (null != requestUri && !requestUri.isEmpty()) { @@ -141,7 +118,7 @@ public static String getSelfRoutedURLNoQuery(HttpServletRequest request) { * Redirect to location url * * @param response - * HttpServletResponse object to be used + * HttpResponse object to be used * @param location * target location url * @param parameters @@ -152,9 +129,9 @@ public static String getSelfRoutedURLNoQuery(HttpServletRequest request) { * @return string the target URL * @throws IOException * - * @see javax.servlet.http.HttpServletResponse#sendRedirect(String) + * @see HttpResponse#sendRedirect(String) */ - public static String sendRedirect(HttpServletResponse response, String location, Map parameters, Boolean stay) throws IOException { + public static String sendRedirect(HttpResponse response, String location, Map parameters, Boolean stay) throws IOException { String target = location; if (!parameters.isEmpty()) { @@ -184,7 +161,7 @@ public static String sendRedirect(HttpServletResponse response, String location, * Redirect to location url * * @param response - * HttpServletResponse object to be used + * HttpResponse object to be used * @param location * target location url * @param parameters @@ -192,9 +169,9 @@ public static String sendRedirect(HttpServletResponse response, String location, * * @throws IOException * - * @see javax.servlet.http.HttpServletResponse#sendRedirect(String) + * @see HttpResponse#sendRedirect(String) */ - public static void sendRedirect(HttpServletResponse response, String location, Map parameters) throws IOException { + public static void sendRedirect(HttpResponse response, String location, Map parameters) throws IOException { sendRedirect(response, location, parameters, false); } @@ -202,15 +179,15 @@ public static void sendRedirect(HttpServletResponse response, String location, M * Redirect to location url * * @param response - * HttpServletResponse object to be used + * HttpResponse object to be used * @param location * target location url * * @throws IOException * - * @see HttpServletResponse#sendRedirect(String) + * @see HttpResponse#sendRedirect(String) */ - public static void sendRedirect(HttpServletResponse response, String location) throws IOException { + public static void sendRedirect(HttpResponse response, String location) throws IOException { Map parameters =new HashMap(); sendRedirect(response, location, parameters); } diff --git a/toolkit/src/test/java/com/onelogin/saml2/test/AuthTest.java b/core/src/test/java/com/onelogin/saml2/test/AuthTest.java similarity index 80% rename from toolkit/src/test/java/com/onelogin/saml2/test/AuthTest.java rename to core/src/test/java/com/onelogin/saml2/test/AuthTest.java index 70ac74c1..fb88292d 100644 --- a/toolkit/src/test/java/com/onelogin/saml2/test/AuthTest.java +++ b/core/src/test/java/com/onelogin/saml2/test/AuthTest.java @@ -1,7 +1,5 @@ package com.onelogin.saml2.test; - -import static java.util.Collections.singletonMap; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; @@ -23,12 +21,9 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import com.onelogin.saml2.http.HttpRequest; +import com.onelogin.saml2.http.HttpResponse; import org.joda.time.Instant; import org.junit.Rule; import org.junit.Test; @@ -104,10 +99,8 @@ public void testConstructorWithFilename() throws IOException, SettingsException, */ @Test public void testConstructorWithReqRes() throws IOException, SettingsException, URISyntaxException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); Auth auth = new Auth(request, response); assertTrue(auth.getSettings() != null); @@ -130,10 +123,8 @@ public void testConstructorWithReqRes() throws IOException, SettingsException, U */ @Test public void testConstructorWithFilenameReqRes() throws IOException, SettingsException, URISyntaxException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); Auth auth = new Auth("config/config.min.properties", request, response); assertTrue(auth.getSettings() != null); @@ -156,10 +147,8 @@ public void testConstructorWithFilenameReqRes() throws IOException, SettingsExce */ @Test public void testConstructorWithSettingsReqRes() throws IOException, SettingsException, URISyntaxException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); Auth auth = new Auth(settings, request, response); @@ -183,13 +172,11 @@ public void testConstructorInvalidSettings() throws IOException, SettingsExcepti expectedEx.expect(SettingsException.class); expectedEx.expectMessage("Invalid settings: sp_entityId_not_found, sp_acs_not_found, sp_cert_not_found_and_required, contact_not_enought_data, organization_not_enought_data, idp_cert_or_fingerprint_not_found_and_required, idp_cert_not_found_and_required"); - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.sperrors.properties").build(); - Auth auth = new Auth(settings, request, response); + new Auth(settings, request, response); } /** @@ -252,10 +239,8 @@ public void testSetStrict() throws IOException, SettingsException, URISyntaxExce */ @Test public void testIsDebugActive() throws IOException, SettingsException, URISyntaxException, Error { - HttpServletResponse response = mock(HttpServletResponse.class); - HttpServletRequest request = mock(HttpServletRequest.class); - String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + HttpResponse response = mock(HttpResponse.class); + HttpRequest request = mock(HttpRequest.class); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); settings.setDebug(false); @@ -280,10 +265,8 @@ public void testIsDebugActive() throws IOException, SettingsException, URISyntax */ @Test public void testGetSSOurl() throws URISyntaxException, IOException, SettingsException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); @@ -303,10 +286,8 @@ public void testGetSSOurl() throws URISyntaxException, IOException, SettingsExce */ @Test public void testGetSLOurl() throws URISyntaxException, IOException, SettingsException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); @@ -327,10 +308,8 @@ public void testGetSLOurl() throws URISyntaxException, IOException, SettingsExce */ @Test public void testGetSLOResponseUrl() throws URISyntaxException, IOException, SettingsException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.all.properties").build(); @@ -350,10 +329,8 @@ public void testGetSLOResponseUrl() throws URISyntaxException, IOException, Sett */ @Test public void testGetSLOResponseUrlNull() throws URISyntaxException, IOException, SettingsException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); @@ -370,9 +347,9 @@ public void testGetSLOResponseUrlNull() throws URISyntaxException, IOException, */ @Test public void testProcessNoResponse() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/java-saml-jspsample/acs.jsp")); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); + when(request.getRequestURL()).thenReturn("http://localhost:8080/java-saml-jspsample/acs.jsp"); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.my.properties").build(); Auth auth = new Auth(settings, request, response); @@ -402,12 +379,12 @@ public void testProcessNoResponse() throws Exception { */ @Test public void testProcessResponse() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/java-saml-jspsample/acs.jsp")); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); + when(request.getRequestURL()).thenReturn("http://localhost:8080/java-saml-jspsample/acs.jsp"); String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.my.properties").build(); Auth auth = new Auth(settings, request, response); @@ -418,7 +395,7 @@ public void testProcessResponse() throws Exception { assertTrue(auth.getAttributes().isEmpty()); samlResponseEncoded = Util.getFileAsString("data/responses/valid_response.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); Auth auth2 = new Auth(settings, request, response); HashMap> expectedAttributes = new HashMap>(); @@ -461,9 +438,9 @@ public void testProcessResponse() throws Exception { */ @Test public void testProcessSLONoMessage() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/java-saml-jspsample/acs.jsp")); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); + when(request.getRequestURL()).thenReturn("http://localhost:8080/java-saml-jspsample/acs.jsp"); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.my.properties").build(); Auth auth = new Auth(settings, request, response); @@ -491,14 +468,12 @@ public void testProcessSLONoMessage() throws Exception { */ @Test public void testProcessSLORequestKeepSession() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - HttpSession session = mock(HttpSession.class); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://stuff.com/endpoints/endpoints/sls.php")); - when(request.getSession()).thenReturn(session); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); + when(request.getRequestURL()).thenReturn("http://stuff.com/endpoints/endpoints/sls.php"); String samlRequestEncoded = Util.getFileAsString("data/logout_requests/logout_request_deflated.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLRequest", new String[]{samlRequestEncoded})); + when(request.getParameter("SAMLRequest")).thenReturn(samlRequestEncoded); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); Auth auth = new Auth(settings, request, response); @@ -506,7 +481,7 @@ public void testProcessSLORequestKeepSession() throws Exception { assertTrue(auth.getErrors().isEmpty()); auth.processSLO(true, null); verify(response).sendRedirect(matches("http:\\/\\/idp.example.com\\/simplesaml\\/saml2\\/idp\\/SingleLogoutService.php\\?SAMLResponse=(.)*")); - verify(session, times(0)).invalidate(); + verify(request, times(0)).invalidateSession(); assertTrue(auth.getErrors().isEmpty()); } @@ -520,21 +495,19 @@ public void testProcessSLORequestKeepSession() throws Exception { */ @Test public void testProcessSLORequestRemoveSession() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - HttpSession session = mock(HttpSession.class); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://stuff.com/endpoints/endpoints/sls.php")); - when(request.getSession()).thenReturn(session); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); + when(request.getRequestURL()).thenReturn("http://stuff.com/endpoints/endpoints/sls.php"); String samlRequestEncoded = Util.getFileAsString("data/logout_requests/logout_request_deflated.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLRequest", new String[]{samlRequestEncoded})); + when(request.getParameter("SAMLRequest")).thenReturn(samlRequestEncoded); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); Auth auth = new Auth(settings, request, response); assertFalse(auth.isAuthenticated()); assertTrue(auth.getErrors().isEmpty()); auth.processSLO(); verify(response).sendRedirect(matches("http:\\/\\/idp.example.com\\/simplesaml\\/saml2\\/idp\\/SingleLogoutService.php\\?SAMLResponse=(.)*")); - verify(session, times(1)).invalidate(); + verify(request, times(1)).invalidateSession(); assertTrue(auth.getErrors().isEmpty()); } @@ -548,20 +521,14 @@ public void testProcessSLORequestRemoveSession() throws Exception { */ @Test public void testProcessSLORequestSignRes() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - HttpSession session = mock(HttpSession.class); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://stuff.com/endpoints/endpoints/sls.php")); - when(request.getSession()).thenReturn(session); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); + when(request.getRequestURL()).thenReturn("http://stuff.com/endpoints/endpoints/sls.php"); String relayState = "http://localhost:8080/expected.jsp"; String samlRequestEncoded = Util.getFileAsString("data/logout_requests/logout_request_deflated.xml.base64"); - Map paramsAsArray = new HashMap<>(); - paramsAsArray.put("SAMLRequest", new String[]{samlRequestEncoded}); - paramsAsArray.put("RelayState", new String[]{relayState}); - when(request.getParameterMap()).thenReturn(paramsAsArray); + when(request.getParameter("SAMLRequest")).thenReturn(samlRequestEncoded); when(request.getParameter("RelayState")).thenReturn(relayState); - Saml2Settings settings = new SettingsBuilder().fromFile("config/config.all.properties").build(); settings.setWantMessagesSigned(false); settings.setLogoutResponseSigned(true); @@ -570,7 +537,7 @@ public void testProcessSLORequestSignRes() throws Exception { assertTrue(auth.getErrors().isEmpty()); auth.processSLO(); verify(response).sendRedirect(matches("http:\\/\\/idp.example.com\\/simplesaml\\/saml2\\/idp\\/SingleLogoutServiceResponse.php\\?SAMLResponse=(.)*&RelayState=http%3A%2F%2Flocalhost%3A8080%2Fexpected.jsp&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha512&Signature=(.)*")); - verify(session, times(1)).invalidate(); + verify(request, times(1)).invalidateSession(); assertTrue(auth.getErrors().isEmpty()); } @@ -584,21 +551,19 @@ public void testProcessSLORequestSignRes() throws Exception { */ @Test public void testProcessSLORequestInvalid() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - HttpSession session = mock(HttpSession.class); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/java-saml-jspsample/sls.jsp")); - when(request.getSession()).thenReturn(session); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); + when(request.getRequestURL()).thenReturn("http://localhost:8080/java-saml-jspsample/sls.jsp"); String samlRequestEncoded = Util.getFileAsString("data/logout_requests/logout_request_deflated.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLRequest", new String[]{samlRequestEncoded})); + when(request.getParameter("SAMLRequest")).thenReturn(samlRequestEncoded); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); settings.setStrict(true); Auth auth = new Auth(settings, request, response); assertFalse(auth.isAuthenticated()); assertTrue(auth.getErrors().isEmpty()); auth.processSLO(); - verify(session, times(0)).invalidate(); + verify(request, times(0)).invalidateSession(); assertFalse(auth.getErrors().isEmpty()); assertTrue(auth.getErrors().contains("invalid_logout_request")); assertThat(auth.getLastErrorReason(), containsString("The LogoutRequest was received at")); @@ -614,20 +579,18 @@ public void testProcessSLORequestInvalid() throws Exception { */ @Test public void testProcessSLOResponseKeepSession() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - HttpSession session = mock(HttpSession.class); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://stuff.com/endpoints/endpoints/sls.php")); - when(request.getSession()).thenReturn(session); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); + when(request.getRequestURL()).thenReturn("http://stuff.com/endpoints/endpoints/sls.php"); String samlResponseEncoded = Util.getFileAsString("data/logout_responses/logout_response_deflated.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); Auth auth = new Auth(settings, request, response); assertFalse(auth.isAuthenticated()); assertTrue(auth.getErrors().isEmpty()); auth.processSLO(true, null); - verify(session, times(0)).invalidate(); + verify(request, times(0)).invalidateSession(); assertTrue(auth.getErrors().isEmpty()); } @@ -641,20 +604,18 @@ public void testProcessSLOResponseKeepSession() throws Exception { */ @Test public void testProcessSLOResponseRemoveSession() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - HttpSession session = mock(HttpSession.class); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://stuff.com/endpoints/endpoints/sls.php")); - when(request.getSession()).thenReturn(session); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); + when(request.getRequestURL()).thenReturn("http://stuff.com/endpoints/endpoints/sls.php"); String samlResponseEncoded = Util.getFileAsString("data/logout_responses/logout_response_deflated.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); Auth auth = new Auth(settings, request, response); assertFalse(auth.isAuthenticated()); assertTrue(auth.getErrors().isEmpty()); auth.processSLO(); - verify(session, times(1)).invalidate(); + verify(request, times(1)).invalidateSession(); assertTrue(auth.getErrors().isEmpty()); } @@ -668,21 +629,19 @@ public void testProcessSLOResponseRemoveSession() throws Exception { */ @Test public void testProcessSLOResponseWrongRequestId() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - HttpSession session = mock(HttpSession.class); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://stuff.com/endpoints/endpoints/sls.php")); - when(request.getSession()).thenReturn(session); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); + when(request.getRequestURL()).thenReturn("http://stuff.com/endpoints/endpoints/sls.php"); String samlResponseEncoded = Util.getFileAsString("data/logout_responses/logout_response_deflated.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); settings.setStrict(true); Auth auth = new Auth(settings, request, response); assertFalse(auth.isAuthenticated()); assertTrue(auth.getErrors().isEmpty()); auth.processSLO(false, "wrong_request_id"); - verify(session, times(0)).invalidate(); + verify(request, times(0)).invalidateSession(); assertTrue(auth.getErrors().contains("invalid_logout_response")); assertEquals("The InResponseTo of the Logout Response: ONELOGIN_21584ccdfaca36a145ae990442dcd96bfe60151e, does not match the ID of the Logout request sent by the SP: wrong_request_id", auth.getLastErrorReason()); } @@ -697,20 +656,18 @@ public void testProcessSLOResponseWrongRequestId() throws Exception { */ @Test public void testProcessSLOResponseStatusResponder() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - HttpSession session = mock(HttpSession.class); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://stuff.com/endpoints/endpoints/sls.php")); - when(request.getSession()).thenReturn(session); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); + when(request.getRequestURL()).thenReturn("http://stuff.com/endpoints/endpoints/sls.php"); String samlResponseEncoded = Util.getFileAsString("data/logout_responses/invalids/status_code_responder.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); Auth auth = new Auth(settings, request, response); assertFalse(auth.isAuthenticated()); assertTrue(auth.getErrors().isEmpty()); auth.processSLO(); - verify(session, times(0)).invalidate(); + verify(request, times(0)).invalidateSession(); assertFalse(auth.getErrors().isEmpty()); assertTrue(auth.getErrors().contains("logout_not_success")); } @@ -726,11 +683,11 @@ public void testProcessSLOResponseStatusResponder() throws Exception { */ @Test public void testIsAuthenticated() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); String samlResponseEncoded = Util.getFileAsString("data/responses/response4.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/java-saml-jspsample/acs.jsp")); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); + when(request.getRequestURL()).thenReturn("http://localhost:8080/java-saml-jspsample/acs.jsp"); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.my.properties").build(); Auth auth = new Auth(settings, request, response); @@ -745,7 +702,7 @@ public void testIsAuthenticated() throws Exception { assertEquals("SAML Response must contain 1 Assertion.", auth.getLastErrorReason()); samlResponseEncoded = Util.getFileAsString("data/responses/valid_encrypted_assertion.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); Auth auth2 = new Auth(settings, request, response); assertFalse(auth2.isAuthenticated()); assertTrue(auth2.getErrors().isEmpty()); @@ -758,7 +715,7 @@ public void testIsAuthenticated() throws Exception { assertThat(auth2.getLastErrorReason(), containsString("Invalid issuer in the Assertion/Response")); samlResponseEncoded = Util.getFileAsString("data/responses/valid_response.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); Auth auth3 = new Auth(settings, request, response); assertFalse(auth3.isAuthenticated()); assertTrue(auth3.getErrors().isEmpty()); @@ -778,11 +735,11 @@ public void testIsAuthenticated() throws Exception { */ @Test public void testGetNameID() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/java-saml-jspsample/acs.jsp")); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); + when(request.getRequestURL()).thenReturn("http://localhost:8080/java-saml-jspsample/acs.jsp"); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.my.properties").build(); Auth auth = new Auth(settings, request, response); @@ -792,7 +749,7 @@ public void testGetNameID() throws Exception { assertNull(auth.getNameId()); samlResponseEncoded = Util.getFileAsString("data/responses/valid_response.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); Auth auth2 = new Auth(settings, request, response); assertNull(auth2.getNameId()); auth2.processResponse(); @@ -800,8 +757,8 @@ public void testGetNameID() throws Exception { assertEquals("492882615acf31c8096b627245d76ae53036c090", auth2.getNameId()); samlResponseEncoded = Util.getFileAsString("data/responses/response_encrypted_nameid.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); - when(request.getRequestURL()).thenReturn(new StringBuffer("https://pitbulk.no-ip.org/newonelogin/demo1/index.php?acs")); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); + when(request.getRequestURL()).thenReturn("https://pitbulk.no-ip.org/newonelogin/demo1/index.php?acs"); settings.setStrict(false); Auth auth3 = new Auth(settings, request, response); assertNull(auth3.getNameId()); @@ -820,11 +777,11 @@ public void testGetNameID() throws Exception { */ @Test public void testGetNameIdFormat() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/java-saml-jspsample/acs.jsp")); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); + when(request.getRequestURL()).thenReturn("http://localhost:8080/java-saml-jspsample/acs.jsp"); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.my.properties").build(); Auth auth = new Auth(settings, request, response); @@ -834,7 +791,7 @@ public void testGetNameIdFormat() throws Exception { assertNull(auth.getNameIdFormat()); samlResponseEncoded = Util.getFileAsString("data/responses/valid_response.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); Auth auth2 = new Auth(settings, request, response); assertNull(auth2.getNameIdFormat()); auth2.processResponse(); @@ -842,8 +799,8 @@ public void testGetNameIdFormat() throws Exception { assertEquals("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", auth2.getNameIdFormat()); samlResponseEncoded = Util.getFileAsString("data/responses/response_encrypted_nameid.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); - when(request.getRequestURL()).thenReturn(new StringBuffer("https://pitbulk.no-ip.org/newonelogin/demo1/index.php?acs")); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); + when(request.getRequestURL()).thenReturn("https://pitbulk.no-ip.org/newonelogin/demo1/index.php?acs"); settings.setStrict(false); Auth auth3 = new Auth(settings, request, response); assertNull(auth3.getNameIdFormat()); @@ -864,12 +821,12 @@ public void testGetNameIDEncWithNoKey() throws Exception { expectedEx.expect(SettingsException.class); expectedEx.expectMessage("Invalid settings: idp_cert_not_found_and_required"); - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.mywithnocert.properties").build(); String samlResponseEncoded = Util.getFileAsString("data/responses/response_encrypted_nameid.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); - when(request.getRequestURL()).thenReturn(new StringBuffer("https://pitbulk.no-ip.org/newonelogin/demo1/index.php?acs")); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); + when(request.getRequestURL()).thenReturn("https://pitbulk.no-ip.org/newonelogin/demo1/index.php?acs"); settings.setStrict(false); Auth auth = new Auth(settings, request, response); assertNull(auth.getNameId()); @@ -890,11 +847,11 @@ public void testOnlyRetrieveAssertionWithIDThatMatchesSignatureReference() throw expectedEx.expect(ValidationError.class); expectedEx.expectMessage("SAML Response could not be processed"); - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); String samlResponseEncoded = Util.getFileAsString("data/responses/invalids/wrapped_response_2.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/java-saml-jspsample/acs.jsp")); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); + when(request.getRequestURL()).thenReturn("http://localhost:8080/java-saml-jspsample/acs.jsp"); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.my.properties").build(); Auth auth = new Auth(settings, request, response); @@ -912,11 +869,11 @@ public void testOnlyRetrieveAssertionWithIDThatMatchesSignatureReference() throw */ @Test public void testGetSessionIndex() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/java-saml-jspsample/acs.jsp")); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); + when(request.getRequestURL()).thenReturn("http://localhost:8080/java-saml-jspsample/acs.jsp"); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.my.properties").build(); Auth auth = new Auth(settings, request, response); @@ -926,7 +883,7 @@ public void testGetSessionIndex() throws Exception { assertNull(auth.getSessionIndex()); samlResponseEncoded = Util.getFileAsString("data/responses/valid_response.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); Auth auth2 = new Auth(settings, request, response); assertNull(auth2.getSessionIndex()); auth2.processResponse(); @@ -936,11 +893,11 @@ public void testGetSessionIndex() throws Exception { @Test public void testGetAssertionDetails() throws Exception { - HttpServletResponse response = mock(HttpServletResponse.class); - HttpServletRequest request = mock(HttpServletRequest.class); + HttpResponse response = mock(HttpResponse.class); + HttpRequest request = mock(HttpRequest.class); String samlResponseEncoded = Util.getFileAsString("data/responses/valid_response.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/java-saml-jspsample/acs.jsp")); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); + when(request.getRequestURL()).thenReturn("http://localhost:8080/java-saml-jspsample/acs.jsp"); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.my.properties").build(); Auth auth = new Auth(settings, request, response); @@ -959,11 +916,11 @@ public void testGetAssertionDetails() throws Exception { */ @Test public void testGetSessionExpiration() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); - when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/java-saml-jspsample/acs.jsp")); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); + when(request.getRequestURL()).thenReturn("http://localhost:8080/java-saml-jspsample/acs.jsp"); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.my.properties").build(); Auth auth = new Auth(settings, request, response); @@ -973,7 +930,7 @@ public void testGetSessionExpiration() throws Exception { assertNull(auth.getSessionExpiration()); samlResponseEncoded = Util.getFileAsString("data/responses/valid_response.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); Auth auth2 = new Auth(settings, request, response); assertNull(auth2.getSessionExpiration()); auth2.processResponse(); @@ -994,8 +951,8 @@ public void testGetSessionExpiration() throws Exception { */ @Test public void testLogin() throws IOException, SettingsException, URISyntaxException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); when(request.getScheme()).thenReturn("http"); when(request.getServerPort()).thenReturn(8080); when(request.getServerName()).thenReturn("localhost"); @@ -1022,8 +979,8 @@ public void testLogin() throws IOException, SettingsException, URISyntaxExceptio */ @Test public void testLoginWithRelayState() throws IOException, SettingsException, URISyntaxException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); when(request.getScheme()).thenReturn("http"); when(request.getServerPort()).thenReturn(8080); when(request.getServerName()).thenReturn("localhost"); @@ -1051,8 +1008,8 @@ public void testLoginWithRelayState() throws IOException, SettingsException, URI */ @Test public void testLoginWithoutRelayState() throws IOException, SettingsException, URISyntaxException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); when(request.getScheme()).thenReturn("http"); when(request.getServerPort()).thenReturn(8080); when(request.getServerName()).thenReturn("localhost"); @@ -1082,8 +1039,8 @@ public void testLoginWithoutRelayState() throws IOException, SettingsException, */ @Test public void testLoginStay() throws IOException, SettingsException, URISyntaxException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); when(request.getScheme()).thenReturn("http"); when(request.getServerPort()).thenReturn(8080); when(request.getServerName()).thenReturn("localhost"); @@ -1119,8 +1076,8 @@ public void testLoginSignedFail() throws IOException, SettingsException, URISynt expectedEx.expect(SettingsException.class); expectedEx.expectMessage("Invalid settings: sp_cert_not_found_and_required"); - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); when(request.getScheme()).thenReturn("http"); when(request.getServerPort()).thenReturn(8080); when(request.getServerName()).thenReturn("localhost"); @@ -1147,8 +1104,8 @@ public void testLoginSignedFail() throws IOException, SettingsException, URISynt */ @Test public void testLoginSigned() throws IOException, SettingsException, URISyntaxException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); when(request.getScheme()).thenReturn("http"); when(request.getServerPort()).thenReturn(8080); when(request.getServerName()).thenReturn("localhost"); @@ -1181,8 +1138,8 @@ public void testLoginSigned() throws IOException, SettingsException, URISyntaxEx */ @Test public void testLogout() throws IOException, SettingsException, XMLEntityException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); when(request.getScheme()).thenReturn("http"); when(request.getServerPort()).thenReturn(8080); when(request.getServerName()).thenReturn("localhost"); @@ -1210,8 +1167,8 @@ public void testLogout() throws IOException, SettingsException, XMLEntityExcepti */ @Test public void testLogoutWithRelayState() throws IOException, SettingsException, XMLEntityException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); when(request.getScheme()).thenReturn("http"); when(request.getServerPort()).thenReturn(8080); when(request.getServerName()).thenReturn("localhost"); @@ -1240,8 +1197,8 @@ public void testLogoutWithRelayState() throws IOException, SettingsException, XM */ @Test public void testLogoutWithoutRelayState() throws IOException, SettingsException, XMLEntityException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); when(request.getScheme()).thenReturn("http"); when(request.getServerPort()).thenReturn(8080); when(request.getServerName()).thenReturn("localhost"); @@ -1272,8 +1229,8 @@ public void testLogoutWithoutRelayState() throws IOException, SettingsException, */ @Test public void testLogoutStay() throws IOException, SettingsException, XMLEntityException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); when(request.getScheme()).thenReturn("http"); when(request.getServerPort()).thenReturn(8080); when(request.getServerName()).thenReturn("localhost"); @@ -1309,8 +1266,8 @@ public void testLogoutSignedFail() throws IOException, SettingsException, XMLEnt expectedEx.expect(SettingsException.class); expectedEx.expectMessage("Invalid settings: sp_cert_not_found_and_required"); - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); when(request.getScheme()).thenReturn("http"); when(request.getServerPort()).thenReturn(8080); when(request.getServerName()).thenReturn("localhost"); @@ -1337,8 +1294,8 @@ public void testLogoutSignedFail() throws IOException, SettingsException, XMLEnt */ @Test public void testLogoutSigned() throws IOException, SettingsException, XMLEntityException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); when(request.getScheme()).thenReturn("http"); when(request.getServerPort()).thenReturn(8080); when(request.getServerName()).thenReturn("localhost"); @@ -1689,8 +1646,8 @@ public void testBuildSignature() throws URISyntaxException, IOException, Setting */ @Test public void testGetLastAuthNRequest() throws IOException, SettingsException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); Auth auth = new Auth(settings, request, response); @@ -1712,8 +1669,8 @@ public void testGetLastAuthNRequest() throws IOException, SettingsException, Err */ @Test public void testGetLastLogoutRequestSent() throws IOException, SettingsException, XMLEntityException, Error { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); Auth auth = new Auth(settings, request, response); @@ -1732,11 +1689,11 @@ public void testGetLastLogoutRequestSent() throws IOException, SettingsException */ @Test public void testGetLastLogoutRequestReceived() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - when(request.getRequestURL()).thenReturn(new StringBuffer("/")); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); + when(request.getRequestURL()).thenReturn("/"); String samlRequestEncoded = Util.getFileAsString("data/logout_requests/logout_request.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLRequest", new String[]{samlRequestEncoded})); + when(request.getParameter("SAMLRequest")).thenReturn(samlRequestEncoded); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.my.properties").build(); Auth auth = new Auth(settings, request, response); @@ -1755,11 +1712,11 @@ public void testGetLastLogoutRequestReceived() throws Exception { */ @Test public void testGetLastSAMLResponse() throws Exception { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - when(request.getRequestURL()).thenReturn(new StringBuffer("/")); + HttpRequest request = mock(HttpRequest.class); + HttpResponse response = mock(HttpResponse.class); + when(request.getRequestURL()).thenReturn("/"); String samlResponseEncoded = Util.getFileAsString("data/responses/response1.xml.base64"); - when(request.getParameterMap()).thenReturn(singletonMap("SAMLResponse", new String[]{samlResponseEncoded})); + when(request.getParameter("SAMLResponse")).thenReturn(samlResponseEncoded); Saml2Settings settings = new SettingsBuilder().fromFile("config/config.my.properties").build(); Auth auth = new Auth(settings, request, response); @@ -1768,7 +1725,7 @@ public void testGetLastSAMLResponse() throws Exception { assertThat(samlResponseXML, containsString("> EMPTY_PARAMETERS = Collections.>emptyMap(); + + private final String requestURL; + private final Map> parameters; + private final String queryString; + + /** + * Creates a new HttpRequest. + * + * @param requestURL the request URL (up to but not including query parameters) + * @throws NullPointerException if requestURL is null + * @deprecated Not providing a queryString can cause HTTP Redirect binding to fail. + */ + @Deprecated + public MockHttpRequest(String requestURL) { + this(requestURL, EMPTY_PARAMETERS); + } + + /** + * Creates a new HttpRequest. + * + * @param requestURL the request URL (up to but not including query parameters) + * @param queryString string that is contained in the request URL after the path + */ + public MockHttpRequest(String requestURL, String queryString) { + this(requestURL, EMPTY_PARAMETERS, queryString); + } + + /** + * Creates a new HttpRequest. + * + * @param requestURL the request URL (up to but not including query parameters) + * @param parameters the request query parameters + * @throws NullPointerException if any of the parameters is null + * @deprecated Not providing a queryString can cause HTTP Redirect binding to fail. + */ + @Deprecated + public MockHttpRequest(String requestURL, Map> parameters) { + this(requestURL, parameters, null); + } + + /** + * Creates a new HttpRequest. + * + * @param requestURL the request URL (up to but not including query parameters) + * @param parameters the request query parameters + * @param queryString string that is contained in the request URL after the path + * @throws NullPointerException if any of the parameters is null + */ + public MockHttpRequest(String requestURL, Map> parameters, String queryString) { + this.requestURL = checkNotNull(requestURL, "requestURL"); + this.parameters = unmodifiableCopyOf(checkNotNull(parameters, "queryParams")); + this.queryString = StringUtils.trimToEmpty(queryString); + } + + @Override + public boolean isSecure() { + return false; + } + + @Override + public String getScheme() { + return "http"; + } + + @Override + public String getServerName() { + return "localhost"; + } + + @Override + public int getServerPort() { + return 80; + } + + @Override + public String getQueryString() { + return queryString; + } + + @Override + public String getRequestURI() { + return requestURL; + } + + /** + * @param name the query parameter name + * @param value the query parameter value + * @return a new HttpRequest with the given query parameter added + * @throws NullPointerException if any of the parameters is null + */ + public MockHttpRequest addParameter(String name, String value) { + checkNotNull(name, "name"); + checkNotNull(value, "value"); + + final List oldValues = parameters.containsKey(name) ? parameters.get(name) : new ArrayList(); + final List newValues = new ArrayList<>(oldValues); + newValues.add(value); + final Map> params = new HashMap<>(parameters); + params.put(name, newValues); + + return new MockHttpRequest(requestURL, params, queryString); + } + + /** + * @param name the query parameter name + * @return a new HttpRequest with the given query parameter removed + * @throws NullPointerException if any of the parameters is null + */ + public MockHttpRequest removeParameter(String name) { + checkNotNull(name, "name"); + + final Map> params = new HashMap<>(parameters); + params.remove(name); + + return new MockHttpRequest(requestURL, params, queryString); + } + + @Override + public String getRequestURL() { + return requestURL; + } + + @Override + public String getParameter(String name) { + final List values = parameters.get(name); + return (values == null || values.isEmpty()) ? null : values.get(0); + } + + @Override + public void invalidateSession() { + // Nothing to do + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + MockHttpRequest that = (MockHttpRequest) o; + return Objects.equals(requestURL, that.requestURL) && + Objects.equals(parameters, that.parameters) && + Objects.equals(queryString, that.queryString); + } + + @Override + public int hashCode() { + return Objects.hash(requestURL, parameters, queryString); + } + + @Override + public String toString() { + return "MockHttpRequest{" + + "requestURL='" + requestURL + '\'' + + ", parameters=" + parameters + + ", queryString=" + queryString + + '}'; + } + + private static Map> unmodifiableCopyOf(Map> orig) { + Map> copy = new HashMap<>(); + for (Map.Entry> entry : orig.entrySet()) { + copy.put(entry.getKey(), unmodifiableList(new ArrayList<>(entry.getValue()))); + } + + return unmodifiableMap(copy); + } +} diff --git a/core/src/test/java/com/onelogin/saml2/http/HttpRequestTest.java b/core/src/test/java/com/onelogin/saml2/test/http/MockHttpRequestTest.java similarity index 71% rename from core/src/test/java/com/onelogin/saml2/http/HttpRequestTest.java rename to core/src/test/java/com/onelogin/saml2/test/http/MockHttpRequestTest.java index a6060352..7c40d55b 100644 --- a/core/src/test/java/com/onelogin/saml2/http/HttpRequestTest.java +++ b/core/src/test/java/com/onelogin/saml2/test/http/MockHttpRequestTest.java @@ -1,4 +1,4 @@ -package com.onelogin.saml2.http; +package com.onelogin.saml2.test.http; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; @@ -6,10 +6,8 @@ import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -19,15 +17,13 @@ import com.onelogin.saml2.test.NaiveUrlEncoder; import com.onelogin.saml2.util.Util; -public class HttpRequestTest { +public class MockHttpRequestTest { @Test public void testConstructorWithNoQueryParams() throws Exception { final String url = "url"; - final HttpRequest request = new HttpRequest(url); + final MockHttpRequest request = new MockHttpRequest(url); assertThat(request.getRequestURL(), equalTo(url)); - assertThat(request.getParameters(), equalTo(Collections.>emptyMap())); - assertThat(request.getParameters("x"), equalTo(Collections.emptyList())); assertThat(request.getParameter("x"), nullValue()); } @@ -41,10 +37,8 @@ public void testConstructorWithQueryParams() throws Exception { final List values = Arrays.asList(value1, value2); final Map> parametersMap = singletonMap(name, values); - final HttpRequest request = new HttpRequest(url, parametersMap); + final MockHttpRequest request = new MockHttpRequest(url, parametersMap); assertThat(request.getRequestURL(), equalTo(url)); - assertThat(request.getParameters(), equalTo(parametersMap)); - assertThat(request.getParameters(name), equalTo(values)); assertThat(request.getParameter(name), equalTo(value1)); } @@ -54,14 +48,9 @@ public void testAddParameter() throws Exception { final String name = "name"; final String value = "value"; - final HttpRequest request = new HttpRequest(url).addParameter(name, value); + final MockHttpRequest request = new MockHttpRequest(url).addParameter(name, value); assertThat(request.getRequestURL(), equalTo(url)); - assertThat(request.getParameters(), equalTo(singletonMap(name, singletonList(value)))); - assertThat(request.getParameters(name), equalTo(singletonList(value))); assertThat(request.getParameter(name), equalTo(value)); - - final HttpRequest request2 = request.addParameter(name, value); - assertThat(request2.getParameters(name), equalTo(Arrays.asList(value, value))); } @Test @@ -70,16 +59,12 @@ public void testRemoveParameter() throws Exception { final String name = "name"; final String value = "value"; - HttpRequest request = new HttpRequest(url).addParameter(name, value); + MockHttpRequest request = new MockHttpRequest(url).addParameter(name, value); assertThat(request.getRequestURL(), equalTo(url)); - assertThat(request.getParameters(), equalTo(singletonMap(name, singletonList(value)))); - assertThat(request.getParameters(name), equalTo(singletonList(value))); assertThat(request.getParameter(name), equalTo(value)); request = request.removeParameter(name); assertThat(request.getRequestURL(), equalTo(url)); - assertTrue(request.getParameters().isEmpty()); - assertTrue(request.getParameters(name).isEmpty()); assertNull(request.getParameter(name)); } @@ -91,10 +76,10 @@ public void testGetEncodedParameter_encodesParametersNotOnQueryString() throws E final String addedName = "added"; final String addedValue = "added#value!"; - final List values = Arrays.asList(value1); + final List values = singletonList(value1); final Map> parametersMap = singletonMap(name, values); - final HttpRequest request = new HttpRequest(url, parametersMap).addParameter(addedName, addedValue); + final MockHttpRequest request = new MockHttpRequest(url, parametersMap).addParameter(addedName, addedValue); assertThat(request.getEncodedParameter(name), equalTo(Util.urlEncoder(value1))); assertThat(request.getEncodedParameter(addedName), equalTo(Util.urlEncoder(addedValue))); @@ -108,10 +93,10 @@ public void testGetEncodedParameter_prefersValueFromQueryString() throws Excepti final String urlValue1 = "onUrl1"; final String queryString = name + "=" + urlValue1; - final List values = Arrays.asList(value1); + final List values = singletonList(value1); final Map> parametersMap = singletonMap(name, values); - final HttpRequest request = new HttpRequest(url, parametersMap, queryString); + final MockHttpRequest request = new MockHttpRequest(url, parametersMap, queryString); assertThat(request.getEncodedParameter(name), equalTo(urlValue1)); assertThat(request.getParameter(name), equalTo(value1)); @@ -124,7 +109,7 @@ public void testGetEncodedParameter_returnsExactAsGivenInQueryString() throws Ex String encodedValue1 = NaiveUrlEncoder.encode("do not alter!"); final String queryString = name + "=" + encodedValue1; - final HttpRequest request = new HttpRequest(url, queryString); + final MockHttpRequest request = new MockHttpRequest(url, queryString); assertThat(request.getEncodedParameter(name), equalTo(encodedValue1)); } @@ -135,7 +120,7 @@ public void testGetEncodedParameter_handlesMultipleValuesOnQueryString() throws final String queryString = "k1=v1&k2=v2&k3=v3"; final Map> parametersMap = new HashMap<>(); - final HttpRequest request = new HttpRequest(url, parametersMap, queryString); + final MockHttpRequest request = new MockHttpRequest(url, parametersMap, queryString); assertThat(request.getEncodedParameter("k1"), equalTo("v1")); assertThat(request.getEncodedParameter("k2"), equalTo("v2")); @@ -147,7 +132,7 @@ public void testGetEncodedParameter_stopsAtUrlFragment() throws Exception { final String url = "url"; final String queryString = "first=&foo=bar#ignore"; - final HttpRequest request = new HttpRequest(url, queryString); + final MockHttpRequest request = new MockHttpRequest(url, queryString); assertThat(request.getEncodedParameter("foo"), equalTo("bar")); } @@ -157,7 +142,7 @@ public void testGetEncodedParameter_withDefault_usesDefaultWhenParameterMissing( final String url = "url"; final String foobar = "foo/bar!"; - final HttpRequest request = new HttpRequest(url); + final MockHttpRequest request = new MockHttpRequest(url); assertThat(request.getEncodedParameter("missing", foobar), equalTo(Util.urlEncoder(foobar))); } @@ -171,7 +156,7 @@ public void testAddParameter_preservesQueryString() throws Exception { final String queryString = name + "=" + encodedValue1; final Map> parametersMap = new HashMap<>(); - final HttpRequest request = new HttpRequest(url, parametersMap, queryString).addParameter(name, value1); + final MockHttpRequest request = new MockHttpRequest(url, parametersMap, queryString).addParameter(name, value1); assertThat(request.getEncodedParameter(name), equalTo(encodedValue1)); } @@ -184,12 +169,11 @@ public void testRemoveParameter_preservesQueryString() throws Exception { String encodedValue1 = NaiveUrlEncoder.encode(value1); final String queryString = name + "=" + encodedValue1; - final List values = Arrays.asList(value1); + final List values = singletonList(value1); final Map> parametersMap = singletonMap(name, values); - final HttpRequest request = new HttpRequest(url, parametersMap, queryString).removeParameter(name); + final MockHttpRequest request = new MockHttpRequest(url, parametersMap, queryString).removeParameter(name); assertThat(request.getEncodedParameter(name), equalTo(encodedValue1)); } - } diff --git a/core/src/test/java/com/onelogin/saml2/test/logout/LogoutRequestTest.java b/core/src/test/java/com/onelogin/saml2/test/logout/LogoutRequestTest.java index d19c2d36..b7f27be4 100644 --- a/core/src/test/java/com/onelogin/saml2/test/logout/LogoutRequestTest.java +++ b/core/src/test/java/com/onelogin/saml2/test/logout/LogoutRequestTest.java @@ -18,6 +18,7 @@ import java.security.PrivateKey; +import com.onelogin.saml2.test.http.MockHttpRequest; import org.w3c.dom.Document; import org.junit.Rule; import org.junit.Test; @@ -646,7 +647,7 @@ public void testIsInValidSign_defaultUrlEncode() throws Exception { //This signature is based on the query string above String signature = "cxDTcLRHhXJKGYcjZE2RRz5p7tVg/irNimq48KkJ0n10wiGwAmuzUByxEm4OHbetDrHGtxI5ygjrR0/HcrD8IkYyI5Ie4r5tJYkfdtpUrvOQ7khbBvP9GzEbZIrz7eH1ALdCDchORaRB/cs6v+OZbBj5uPTrN//wOhZl2k9H2xVW/SYy17jDoIKh/wvqtQ9FF+h2UxdUEhxeB/UUXOC6nVLMo+RGaamSviYkUE1Zu1tmalO+F6FivNQ31T/TkqzWz0KEjmnFs3eKbHakPVuUHpDQm7Gf2gBS1TXwVQsL7e2axtvv4RH5djlq1Z2WH2V+PwGOkIvLxf3igGUSR1A8bw=="; - HttpRequest httpRequest = new HttpRequest(requestURL, queryString) + MockHttpRequest httpRequest = new MockHttpRequest(requestURL, queryString) .addParameter("SAMLRequest", samlRequestEncoded) .addParameter("RelayState", relayState) .addParameter("SigAlg", sigAlg) @@ -674,7 +675,7 @@ public void testIsInValidSign_naiveUrlEncoding() throws Exception { //This signature is based on the query string above String signatureNaiveEncoding = "Gj2mUq6RBPAPXI9VjDDlwAxueSEBlOfgpWKLpsQbqIp+2XPFtC/vPAZpuPjHCDNNnAI3WKZa4l8ijwQBTqQwKz88k9gTx6vcLxPl2L4SrWdLOokiGrIVYJ+0sK2hapHHMa7WzGiTgpeTuejHbD4ptneaRXl4nrJAEo0WJ/rNTSWbJpnb+ENtgBnsfkmj+6z1KFY70ruo7W/vme21Jg+4XNfBSGl6LLSjEnZHJG0ET80HKvJEZayv4BQGZ3MShcSMyab/w+rLfDvDRA5RcRxw+NHOXo/kxZ3qhpa6daOwG69+PiiWmusmB2gaSq6jy2L55zFks9a36Pt5l5fYA2dE4g=="; - HttpRequest httpRequest = new HttpRequest(requestURL, queryString) + MockHttpRequest httpRequest = new MockHttpRequest(requestURL, queryString) .addParameter("SAMLRequest", samlRequestEncoded) .addParameter("RelayState", relayState) .addParameter("SigAlg", sigAlg) @@ -703,7 +704,7 @@ public void testIsInValidSign() throws Exception { String sigAlg = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; String signature = "XCwCyI5cs7WhiJlB5ktSlWxSBxv+6q2xT3c8L7dLV6NQG9LHWhN7gf8qNsahSXfCzA0Ey9dp5BQ0EdRvAk2DIzKmJY6e3hvAIEp1zglHNjzkgcQmZCcrkK9Czi2Y1WkjOwR/WgUTUWsGJAVqVvlRZuS3zk3nxMrLH6f7toyvuJc="; - HttpRequest httpRequest = new HttpRequest(requestURL) + MockHttpRequest httpRequest = new MockHttpRequest(requestURL) .addParameter("SAMLRequest", samlRequestEncoded) .addParameter("RelayState", relayState) .addParameter("SigAlg", sigAlg) @@ -821,6 +822,6 @@ public void testGetError() throws Exception { } private static HttpRequest newHttpRequest(String requestURL, String samlRequestEncoded) { - return new HttpRequest(requestURL).addParameter("SAMLRequest", samlRequestEncoded); + return new MockHttpRequest(requestURL).addParameter("SAMLRequest", samlRequestEncoded); } } diff --git a/core/src/test/java/com/onelogin/saml2/test/logout/LogoutResponseTest.java b/core/src/test/java/com/onelogin/saml2/test/logout/LogoutResponseTest.java index f03560b8..5ca9f45f 100644 --- a/core/src/test/java/com/onelogin/saml2/test/logout/LogoutResponseTest.java +++ b/core/src/test/java/com/onelogin/saml2/test/logout/LogoutResponseTest.java @@ -14,6 +14,7 @@ import javax.xml.xpath.XPathExpressionException; +import com.onelogin.saml2.test.http.MockHttpRequest; import org.junit.Test; import com.onelogin.saml2.exception.Error; @@ -40,7 +41,7 @@ public void testGetEncodedLogoutResponseSimulated() throws Exception { Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); final String logoutResponseString = Util.getFileAsString("data/logout_responses/logout_response.xml"); final String requestURL = "/"; - HttpRequest httpRequest = new HttpRequest(requestURL); + MockHttpRequest httpRequest = new MockHttpRequest(requestURL); LogoutResponse logoutResponseBuilder = new LogoutResponse(settings, httpRequest) { @Override @@ -136,7 +137,7 @@ public void testBuild() throws IOException, XMLEntityException, URISyntaxExcepti Saml2Settings settings = new SettingsBuilder().fromFile("config/config.min.properties").build(); final String requestURL = "/"; - HttpRequest httpRequest = new HttpRequest(requestURL); + MockHttpRequest httpRequest = new MockHttpRequest(requestURL); LogoutResponse logoutResponse = new LogoutResponse(settings, httpRequest); assertFalse(logoutResponse.isValid()); @@ -256,7 +257,7 @@ public void testIsValidNoResponse() throws XMLEntityException, IOException, Erro assertFalse(logoutResponse.isValid()); assertEquals("SAML Logout Response is not loaded", logoutResponse.getError()); - httpRequest = new HttpRequest(requestURL); + httpRequest = new MockHttpRequest(requestURL); logoutResponse = new LogoutResponse(settings, httpRequest); assertFalse(logoutResponse.isValid()); assertEquals("SAML Logout Response is not loaded", logoutResponse.getError()); @@ -439,7 +440,7 @@ public void testIsInValidSign_defaultUrlEncode() throws Exception { //This signature is based on the query string above String signature = "czxEy2WDRZS1U4b2PQFpE4KRhRs8jt5bBKdTFx5oIXpte6qtm0Lk/5lzw/2S6Y1NJpj5DJvSLJvylgNE+RYfJR1GX0zQplm2dZYtlo7CZUyfS3JCLsWviEtPXaon+8Z0lQQkPt4yxCf9v8Qd0pvxHglTUCK/sU0NXnZQdpSxxfsaNCcjQf5gTg/gj8oI7xdrnamBPFtsaH6tAirkjGMoYS4Otju3mcrdcNBIHG40wrffUDnE83Jw4AOFCp8Vsf0zPTQOQsxS4HF4VS78OvGn7jLi2MdabeAQcK5+tP3mUB4vO8AAt8QbkEEiWQbcvA9i1Ezma92CdNYgaf4B3JYpPA=="; - HttpRequest httpRequest = new HttpRequest(requestURL, queryString) + MockHttpRequest httpRequest = new MockHttpRequest(requestURL, queryString) .addParameter("SAMLResponse", samlResponseEncoded) .addParameter("RelayState", relayState) .addParameter("SigAlg", sigAlg) @@ -467,7 +468,7 @@ public void testIsInValidSign_naiveUrlEncoding() throws Exception { //This signature is based on the query string above String signature = "eSoTB+0GA/HfncASEFk7ONHbB3+9YrOBgK9xUyRoCDY97oXw49JYoXOL07kHrVvbngKmKFNx5fnYtDaL8WCe5LfRRgjJz1LLacriHn2ggeMmY/fTaXPoy2zQW0Fv1H362QXicTWQXgWFS5cJAIcBa2I7TLgNwXsMgjdBF2hyacW0IwfkAceGiBwDDTy6XIBAZk2Ff7w5lbZh+fa5JLNKrbvoveJk2NS3KK6INYO7UW5hukWz2cpzbHsx9lfxUJi8/ZCwUtFWZ4rdXVN+Qiw5y8S2eE2BIEfFmz7IfvrMRXa2la/rXFQfmteQo+N1sO3K1YZyoT/aA3k36glXvnj3kw=="; - HttpRequest httpRequest = new HttpRequest(requestURL, queryString) + MockHttpRequest httpRequest = new MockHttpRequest(requestURL, queryString) .addParameter("SAMLResponse", samlResponseEncoded) .addParameter("RelayState", relayState) .addParameter("SigAlg", sigAlg) @@ -499,7 +500,7 @@ public void testIsInValidSign() throws URISyntaxException, IOException, XMLEntit String sigAlg = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; String signature = "vfWbbc47PkP3ejx4bjKsRX7lo9Ml1WRoE5J5owF/0mnyKHfSY6XbhO1wwjBV5vWdrUVX+xp6slHyAf4YoAsXFS0qhan6txDiZY4Oec6yE+l10iZbzvie06I4GPak4QrQ4gAyXOSzwCrRmJu4gnpeUxZ6IqKtdrKfAYRAcVfNKGA="; - HttpRequest httpRequest = new HttpRequest(requestURL) + MockHttpRequest httpRequest = new MockHttpRequest(requestURL) .addParameter("SAMLResponse", samlResponseEncoded) .addParameter("RelayState", relayState) .addParameter("SigAlg", sigAlg) @@ -593,6 +594,6 @@ public void testGetError() throws URISyntaxException, IOException, XMLEntityExce } private static HttpRequest newHttpRequest(String requestURL, String samlResponseEncoded) { - return new HttpRequest(requestURL).addParameter("SAMLResponse", samlResponseEncoded); + return new MockHttpRequest(requestURL).addParameter("SAMLResponse", samlResponseEncoded); } } diff --git a/toolkit/src/test/java/com/onelogin/saml2/test/servlet/ServletUtilsTest.java b/core/src/test/java/com/onelogin/saml2/test/servlet/ServletUtilsTest.java similarity index 68% rename from toolkit/src/test/java/com/onelogin/saml2/test/servlet/ServletUtilsTest.java rename to core/src/test/java/com/onelogin/saml2/test/servlet/ServletUtilsTest.java index 176fe079..96dcd0ae 100644 --- a/toolkit/src/test/java/com/onelogin/saml2/test/servlet/ServletUtilsTest.java +++ b/core/src/test/java/com/onelogin/saml2/test/servlet/ServletUtilsTest.java @@ -1,10 +1,7 @@ package com.onelogin.saml2.test.servlet; -import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; -import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -13,14 +10,11 @@ import java.util.HashMap; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - +import com.onelogin.saml2.http.HttpResponse; import org.junit.Test; import com.onelogin.saml2.http.HttpRequest; import com.onelogin.saml2.servlet.ServletUtils; -import com.onelogin.saml2.test.NaiveUrlEncoder; public class ServletUtilsTest { /** @@ -33,17 +27,13 @@ public class ServletUtilsTest { */ @Test public void testSendRedirectRelative() throws IOException { - HttpServletRequest request_1 = mock(HttpServletRequest.class); - HttpServletResponse response_1 = mock(HttpServletResponse.class); + HttpResponse response_1 = mock(HttpResponse.class); // mock the getRequestURI() response - when(request_1.getRequestURI()).thenReturn("/initial.jsp"); ServletUtils.sendRedirect(response_1, "http://example.com/expectedurl.jsp"); // verify if a sendRedirect() was performed with the expected value verify(response_1).sendRedirect("http://example.com/expectedurl.jsp"); - HttpServletRequest request_2 = mock(HttpServletRequest.class); - HttpServletResponse response_2 = mock(HttpServletResponse.class); - when(request_2.getRequestURI()).thenReturn("/initial.jsp"); + HttpResponse response_2 = mock(HttpResponse.class); ServletUtils.sendRedirect(response_2, "/expectedurl.jsp"); verify(response_2).sendRedirect("/expectedurl.jsp"); } @@ -58,15 +48,11 @@ public void testSendRedirectRelative() throws IOException { */ @Test public void testSendRedirectProtocol() throws IOException { - HttpServletRequest request_1 = mock(HttpServletRequest.class); - HttpServletResponse response_1 = mock(HttpServletResponse.class); - when(request_1.getRequestURI()).thenReturn("/initial.jsp"); + HttpResponse response_1 = mock(HttpResponse.class); ServletUtils.sendRedirect(response_1, "http://example.com/expectedurl.jsp"); verify(response_1).sendRedirect("http://example.com/expectedurl.jsp"); - HttpServletRequest request_2 = mock(HttpServletRequest.class); - HttpServletResponse response_2 = mock(HttpServletResponse.class); - when(request_2.getRequestURI()).thenReturn("/initial.jsp"); + HttpResponse response_2 = mock(HttpResponse.class); ServletUtils.sendRedirect(response_2, "https://example.com/expectedurl.jsp"); verify(response_2).sendRedirect("https://example.com/expectedurl.jsp"); } @@ -82,38 +68,28 @@ public void testSendRedirectProtocol() throws IOException { @Test public void testSendRedirectParams() throws IOException { Map parameters = new HashMap(); - HttpServletRequest request_1 = mock(HttpServletRequest.class); - HttpServletResponse response_1 = mock(HttpServletResponse.class); - when(request_1.getRequestURI()).thenReturn("/initial.jsp"); + HttpResponse response_1 = mock(HttpResponse.class); ServletUtils.sendRedirect(response_1, "http://example.com/expectedurl.jsp", parameters); verify(response_1).sendRedirect("http://example.com/expectedurl.jsp"); parameters.put("test", "true"); - HttpServletRequest request_2 = mock(HttpServletRequest.class); - HttpServletResponse response_2 = mock(HttpServletResponse.class); - when(request_2.getRequestURI()).thenReturn("/initial.jsp"); + HttpResponse response_2 = mock(HttpResponse.class); ServletUtils.sendRedirect(response_2, "http://example.com/expectedurl.jsp", parameters); verify(response_2).sendRedirect("http://example.com/expectedurl.jsp?test=true"); parameters.put("value1", "a"); - HttpServletRequest request_3 = mock(HttpServletRequest.class); - HttpServletResponse response_3 = mock(HttpServletResponse.class); - when(request_3.getRequestURI()).thenReturn("/initial.jsp"); + HttpResponse response_3 = mock(HttpResponse.class); ServletUtils.sendRedirect(response_3, "http://example.com/expectedurl.jsp", parameters); verify(response_3).sendRedirect("http://example.com/expectedurl.jsp?test=true&value1=a"); parameters.put("novalue", ""); - HttpServletRequest request_4 = mock(HttpServletRequest.class); - HttpServletResponse response_4 = mock(HttpServletResponse.class); - when(request_4.getRequestURI()).thenReturn("/initial.jsp"); + HttpResponse response_4 = mock(HttpResponse.class); ServletUtils.sendRedirect(response_4, "http://example.com/expectedurl.jsp", parameters); verify(response_4).sendRedirect("http://example.com/expectedurl.jsp?novalue&test=true&value1=a"); Map parameters_2 = new HashMap(); parameters_2.put("novalue", ""); - HttpServletRequest request_5 = mock(HttpServletRequest.class); - HttpServletResponse response_5 = mock(HttpServletResponse.class); - when(request_5.getRequestURI()).thenReturn("/initial.jsp"); + HttpResponse response_5 = mock(HttpResponse.class); ServletUtils.sendRedirect(response_5, "http://example.com/expectedurl.jsp", parameters_2); verify(response_5).sendRedirect("http://example.com/expectedurl.jsp?novalue"); } @@ -128,7 +104,7 @@ public void testSendRedirectParams() throws IOException { */ @Test public void testSendRedirectStay() throws IOException { - HttpServletResponse response = mock(HttpServletResponse.class); + HttpResponse response = mock(HttpResponse.class); Map parameters = new HashMap(); String url = ServletUtils.sendRedirect(response, "http://example.com/expectedurl.jsp", parameters, true); @@ -145,7 +121,7 @@ public void testSendRedirectStay() throws IOException { */ @Test public void testGetSelfURLhost() { - HttpServletRequest request_1 = mock(HttpServletRequest.class); + HttpRequest request_1 = mock(HttpRequest.class); when(request_1.getScheme()).thenReturn("http"); when(request_1.getServerName()).thenReturn("example.com"); when(request_1.getServerPort()).thenReturn(80); @@ -169,7 +145,7 @@ public void testGetSelfURLhost() { */ @Test public void testGetSelfHost() { - HttpServletRequest request_1 = mock(HttpServletRequest.class); + HttpRequest request_1 = mock(HttpRequest.class); when(request_1.getServerName()).thenReturn("example.com"); assertEquals("example.com", ServletUtils.getSelfHost(request_1)); } @@ -181,7 +157,7 @@ public void testGetSelfHost() { */ @Test public void testIsHTTPS() { - HttpServletRequest request_1 = mock(HttpServletRequest.class); + HttpRequest request_1 = mock(HttpRequest.class); when(request_1.isSecure()).thenReturn(false); assertEquals(false, ServletUtils.isHTTPS(request_1)); @@ -196,7 +172,7 @@ public void testIsHTTPS() { */ @Test public void testGetSelfURL() { - HttpServletRequest request_1 = mock(HttpServletRequest.class); + HttpRequest request_1 = mock(HttpRequest.class); when(request_1.getScheme()).thenReturn("http"); when(request_1.getServerName()).thenReturn("example.com"); when(request_1.getRequestURI()).thenReturn("/test"); @@ -212,7 +188,7 @@ public void testGetSelfURL() { when(request_1.getRequestURI()).thenReturn(null); assertEquals("http://example.com?novalue&test=true&value1=a", ServletUtils.getSelfURL(request_1)); - HttpServletRequest request_2 = mock(HttpServletRequest.class); + HttpRequest request_2 = mock(HttpRequest.class); when(request_2.getScheme()).thenReturn("http"); when(request_2.getServerName()).thenReturn("example.com"); when(request_2.getRequestURI()).thenReturn("/test"); @@ -232,9 +208,8 @@ public void testGetSelfURL() { */ @Test public void testGetSelfURLNoQuery() { - HttpServletRequest request_1 = mock(HttpServletRequest.class); - StringBuffer url = new StringBuffer("http://example.com/test"); - when(request_1.getRequestURL()).thenReturn(url); + HttpRequest request_1 = mock(HttpRequest.class); + when(request_1.getRequestURL()).thenReturn("http://example.com/test"); assertEquals("http://example.com/test", ServletUtils.getSelfURLNoQuery(request_1)); } @@ -245,7 +220,7 @@ public void testGetSelfURLNoQuery() { */ @Test public void testGetSelfRoutedURLNoQuery() { - HttpServletRequest request_1 = mock(HttpServletRequest.class); + HttpRequest request_1 = mock(HttpRequest.class); when(request_1.getScheme()).thenReturn("http"); when(request_1.getServerName()).thenReturn("example.com"); when(request_1.getRequestURI()).thenReturn("/test"); @@ -258,28 +233,10 @@ public void testGetSelfRoutedURLNoQuery() { assertEquals("http://example.com", ServletUtils.getSelfRoutedURLNoQuery(request_1)); } - @Test - public void testMakeHttpRequest() throws Exception { - final String url = "http://localhost:1234/a/b"; - final Map paramAsArray = singletonMap("name", new String[]{"a"}); - - final HttpServletRequest servletRequest = mock(HttpServletRequest.class); - when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(url)); - when(servletRequest.getParameterMap()).thenReturn(paramAsArray); - - final String barNaiveEncoded = NaiveUrlEncoder.encode("bar"); //must differ from normal url encode - when(servletRequest.getQueryString()).thenReturn("foo=" + barNaiveEncoded); - - final HttpRequest httpRequest = ServletUtils.makeHttpRequest(servletRequest); - assertThat(httpRequest.getRequestURL(), equalTo(url)); - assertThat(httpRequest.getParameters(), equalTo(singletonMap("name", singletonList("a")))); - assertThat(httpRequest.getEncodedParameter("foo"), equalTo(barNaiveEncoded)); - } - @Test public void sendRedirectToShouldHandleUrlsWithQueryParams() throws Exception { // having - final HttpServletResponse response = mock(HttpServletResponse.class); + final HttpResponse response = mock(HttpResponse.class); // when ServletUtils.sendRedirect(response, "https://sso.connect.pingidentity.com/sso/idp/SSO.saml2?idpid=ffee-aabbb", singletonMap("SAMLRequest", "data")); diff --git a/toolkit/src/main/java/com/onelogin/saml2/http/JavaxHttpRequest.java b/toolkit/src/main/java/com/onelogin/saml2/http/JavaxHttpRequest.java new file mode 100644 index 00000000..c5a14b47 --- /dev/null +++ b/toolkit/src/main/java/com/onelogin/saml2/http/JavaxHttpRequest.java @@ -0,0 +1,66 @@ +package com.onelogin.saml2.http; + +import javax.servlet.http.HttpServletRequest; + +/** + * {@link HttpRequest} implementation which wraps a standard + * {@link HttpServletRequest} for a JavaEE-style container. + * + * @since 2.2.0 + */ +public class JavaxHttpRequest extends HttpRequest { + + /** + * The underlying request object + */ + private final HttpServletRequest request; + + public JavaxHttpRequest(HttpServletRequest request) { + this.request = request; + } + + @Override + public boolean isSecure() { + return request.isSecure(); + } + + @Override + public String getScheme() { + return request.getScheme(); + } + + @Override + public String getServerName() { + return request.getServerName(); + } + + @Override + public int getServerPort() { + return request.getServerPort(); + } + + @Override + public String getQueryString() { + return request.getQueryString(); + } + + @Override + public String getRequestURI() { + return request.getRequestURI(); + } + + @Override + public String getRequestURL() { + return request.getRequestURL().toString(); + } + + @Override + public String getParameter(String name) { + return request.getParameter(name); + } + + @Override + public void invalidateSession() { + request.getSession().invalidate(); + } +} diff --git a/toolkit/src/main/java/com/onelogin/saml2/http/JavaxHttpResponse.java b/toolkit/src/main/java/com/onelogin/saml2/http/JavaxHttpResponse.java new file mode 100644 index 00000000..929d5f5b --- /dev/null +++ b/toolkit/src/main/java/com/onelogin/saml2/http/JavaxHttpResponse.java @@ -0,0 +1,27 @@ +package com.onelogin.saml2.http; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * {@link HttpResponse} implementation which wraps a standard + * {@link HttpServletResponse} for a JavaEE-style container. + * + * @since 2.2.0 + */ +public class JavaxHttpResponse extends HttpResponse { + + /** + * The underlying response object + */ + private final HttpServletResponse response; + + public JavaxHttpResponse(HttpServletResponse response) { + this.response = response; + } + + @Override + public void sendRedirect(String target) throws IOException { + this.response.sendRedirect(target); + } +} From 779300035044fa89f38c3d4ab255cee1ef5757d0 Mon Sep 17 00:00:00 2001 From: Ashley Mercer Date: Sat, 8 Jul 2017 21:43:09 +0100 Subject: [PATCH 2/2] Provide unit tests for new javax wrappers --- toolkit/pom.xml | 35 ------- .../saml2/test/http/JavaxHttpRequestTest.java | 97 +++++++++++++++++++ .../test/http/JavaxHttpResponseTest.java | 25 +++++ 3 files changed, 122 insertions(+), 35 deletions(-) create mode 100644 toolkit/src/test/java/com/onelogin/saml2/test/http/JavaxHttpRequestTest.java create mode 100644 toolkit/src/test/java/com/onelogin/saml2/test/http/JavaxHttpResponseTest.java diff --git a/toolkit/pom.xml b/toolkit/pom.xml index 8ffeaa2b..a3af3c35 100644 --- a/toolkit/pom.xml +++ b/toolkit/pom.xml @@ -46,17 +46,6 @@ test - - - org.slf4j - slf4j-api - - - ch.qos.logback - logback-classic - test - - javax.servlet @@ -64,30 +53,6 @@ 2.5 provided - - - - joda-time - joda-time - 2.9.4 - - - - - org.apache.commons - commons-lang3 - ${apacheCommonsLangVersion} - - - org.apache.santuario - xmlsec - 2.0.7 - - - commons-codec - commons-codec - 1.10 - diff --git a/toolkit/src/test/java/com/onelogin/saml2/test/http/JavaxHttpRequestTest.java b/toolkit/src/test/java/com/onelogin/saml2/test/http/JavaxHttpRequestTest.java new file mode 100644 index 00000000..010b6d7b --- /dev/null +++ b/toolkit/src/test/java/com/onelogin/saml2/test/http/JavaxHttpRequestTest.java @@ -0,0 +1,97 @@ +package com.onelogin.saml2.test.http; + +import com.onelogin.saml2.http.HttpRequest; +import com.onelogin.saml2.http.JavaxHttpRequest; +import org.junit.Test; + +import javax.servlet.http.HttpServletRequest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * @author ashley.mercer@skylightipv.com + */ +public class JavaxHttpRequestTest { + + @Test + public void testIsSecure() { + final HttpServletRequest javaxRequest = mock(HttpServletRequest.class); + final HttpRequest request = new JavaxHttpRequest(javaxRequest); + + when(javaxRequest.isSecure()).thenReturn(true); + assertTrue(request.isSecure()); + + when(javaxRequest.isSecure()).thenReturn(false); + assertFalse(request.isSecure()); + } + + @Test + public void testGetScheme() { + final HttpServletRequest javaxRequest = mock(HttpServletRequest.class); + final HttpRequest request = new JavaxHttpRequest(javaxRequest); + + when(javaxRequest.getScheme()).thenReturn("http"); + assertEquals(request.getScheme(), "http"); + } + + @Test + public void testGetServerName() { + final HttpServletRequest javaxRequest = mock(HttpServletRequest.class); + final HttpRequest request = new JavaxHttpRequest(javaxRequest); + + when(javaxRequest.getServerName()).thenReturn("www.example.com"); + assertEquals(request.getServerName(), "www.example.com"); + } + + @Test + public void testGetServerPort() { + final HttpServletRequest javaxRequest = mock(HttpServletRequest.class); + final HttpRequest request = new JavaxHttpRequest(javaxRequest); + + when(javaxRequest.getServerPort()).thenReturn(80); + assertEquals(request.getServerPort(), 80); + + when(javaxRequest.getServerPort()).thenReturn(443); + assertEquals(request.getServerPort(), 443); + } + + @Test + public void testGetQueryString() { + final HttpServletRequest javaxRequest = mock(HttpServletRequest.class); + final HttpRequest request = new JavaxHttpRequest(javaxRequest); + + when(javaxRequest.getQueryString()).thenReturn("foo=bar"); + assertEquals(request.getQueryString(), "foo=bar"); + } + + @Test + public void testGetRequestURI() { + final HttpServletRequest javaxRequest = mock(HttpServletRequest.class); + final HttpRequest request = new JavaxHttpRequest(javaxRequest); + + when(javaxRequest.getRequestURI()).thenReturn("/test.html"); + assertEquals(request.getRequestURI(), "/test.html"); + } + + @Test + public void testGetRequestURL() { + final HttpServletRequest javaxRequest = mock(HttpServletRequest.class); + final HttpRequest request = new JavaxHttpRequest(javaxRequest); + + when(javaxRequest.getRequestURL()).thenReturn(new StringBuffer("http://www.example.com/test")); + assertEquals(request.getRequestURL(), "http://www.example.com/test"); + } + + @Test + public void testGetParameter() { + final HttpServletRequest javaxRequest = mock(HttpServletRequest.class); + final HttpRequest request = new JavaxHttpRequest(javaxRequest); + + when(javaxRequest.getParameter("foo")).thenReturn("bar"); + assertEquals(request.getParameter("foo"), "bar"); + } +} diff --git a/toolkit/src/test/java/com/onelogin/saml2/test/http/JavaxHttpResponseTest.java b/toolkit/src/test/java/com/onelogin/saml2/test/http/JavaxHttpResponseTest.java new file mode 100644 index 00000000..e5177491 --- /dev/null +++ b/toolkit/src/test/java/com/onelogin/saml2/test/http/JavaxHttpResponseTest.java @@ -0,0 +1,25 @@ +package com.onelogin.saml2.test.http; + +import com.onelogin.saml2.http.HttpResponse; +import com.onelogin.saml2.http.JavaxHttpResponse; +import org.junit.Test; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +import static org.mockito.Mockito.*; + +/** + * @author ashley.mercer@skylightipv.com + */ +public class JavaxHttpResponseTest { + + @Test + public void testSendRedirect() throws IOException { + final HttpServletResponse javaxResponse = mock(HttpServletResponse.class); + final HttpResponse response = new JavaxHttpResponse(javaxResponse); + + response.sendRedirect("http://www.example.com"); + verify(javaxResponse, times(1)).sendRedirect(matches("http://www\\.example\\.com")); + } +}