This is an automated email from the ASF dual-hosted git repository.
rombert pushed a commit to branch master
in repository
https://gitbox.apache.org/repos/asf/sling-org-apache-sling-auth-oauth-client.git
The following commit(s) were added to refs/heads/master by this push:
new 46bec3e SLING-12714 - Refactoring Tests - removed custom Mock classes
and junit 4 tests (#20)
46bec3e is described below
commit 46bec3e40f5878bece450b96d7502050247c7bbc
Author: Nicola Scendoni <[email protected]>
AuthorDate: Mon Jun 16 16:54:44 2025 +0200
SLING-12714 - Refactoring Tests - removed custom Mock classes and junit 4
tests (#20)
---
pom.xml | 12 +
.../impl/OidcAuthenticationHandler.java | 14 +-
.../oauth_client/impl/SlingLoginCookieManager.java | 6 +-
.../auth/oauth_client/spi/LoginCookieManager.java | 7 +-
.../sling/auth/oauth_client/spi/package-info.java | 2 +-
.../auth/oauth_client/AuthorizationCodeFlowIT.java | 2 +-
.../impl/CryptoOAuthCookieValueManagerTest.java | 12 -
.../sling/auth/oauth_client/impl/MockRequest.java | 473 ---------------------
.../sling/auth/oauth_client/impl/MockResponse.java | 270 ------------
.../impl/OidcAuthenticationHandlerTest.java | 72 ++--
.../impl/SlingLoginCookieManagerTest.java | 28 +-
.../oauth_client/impl/StubCryptoServiceTest.java | 2 +-
.../auth/oauth_client/impl/TokenStoreTest.java | 43 +-
13 files changed, 91 insertions(+), 852 deletions(-)
diff --git a/pom.xml b/pom.xml
index 0347a29..9acd923 100644
--- a/pom.xml
+++ b/pom.xml
@@ -178,6 +178,18 @@
<version>3.1.2-1.40.0</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.testing.osgi-mock.junit5</artifactId>
+ <version>3.5.2</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.testing.osgi-mock</artifactId>
+ <version>3.5.2</version>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.jcr.jackrabbit.usermanager</artifactId>
diff --git
a/src/main/java/org/apache/sling/auth/oauth_client/impl/OidcAuthenticationHandler.java
b/src/main/java/org/apache/sling/auth/oauth_client/impl/OidcAuthenticationHandler.java
index 8b3026c..86173e6 100644
---
a/src/main/java/org/apache/sling/auth/oauth_client/impl/OidcAuthenticationHandler.java
+++
b/src/main/java/org/apache/sling/auth/oauth_client/impl/OidcAuthenticationHandler.java
@@ -69,14 +69,12 @@ import
org.apache.sling.auth.oauth_client.spi.LoginCookieManager;
import org.apache.sling.auth.oauth_client.spi.OidcAuthCredentials;
import org.apache.sling.auth.oauth_client.spi.UserInfoProcessor;
import org.apache.sling.commons.crypto.CryptoService;
-import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.jcr.resource.api.JcrResourceConstants;
import org.jetbrains.annotations.NotNull;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
-import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.Designate;
@@ -93,10 +91,7 @@ public class OidcAuthenticationHandler extends
DefaultAuthenticationFeedbackHand
private static final Logger logger =
LoggerFactory.getLogger(OidcAuthenticationHandler.class);
private static final String AUTH_TYPE = "oidc";
- private final SlingRepository repository;
-
private final Map<String, ClientConnection> connections;
- private final OAuthStateManager stateManager;
private final String idp;
@@ -147,19 +142,14 @@ public class OidcAuthenticationHandler extends
DefaultAuthenticationFeedbackHand
@Activate
public OidcAuthenticationHandler(
- @Reference(policyOption = ReferencePolicyOption.GREEDY) @NotNull
SlingRepository repository,
@NotNull BundleContext bundleContext,
@Reference List<ClientConnection> connections,
- @Reference OAuthStateManager stateManager,
Config config,
- @Reference(cardinality = ReferenceCardinality.OPTIONAL,
policyOption = ReferencePolicyOption.GREEDY)
- LoginCookieManager loginCookieManager,
+ @Reference(policyOption = ReferencePolicyOption.GREEDY)
LoginCookieManager loginCookieManager,
@Reference(policyOption = ReferencePolicyOption.GREEDY)
UserInfoProcessor userInfoProcessor,
@Reference CryptoService cryptoService) {
- this.repository = repository;
this.connections =
connections.stream().collect(Collectors.toMap(ClientConnection::name,
Function.identity()));
- this.stateManager = stateManager;
this.idp = config.idp();
this.callbackUri = config.callbackUri();
this.loginCookieManager = loginCookieManager;
@@ -548,7 +538,7 @@ public class OidcAuthenticationHandler extends
DefaultAuthenticationFeedbackHand
String token = tokenValueObject.toString();
if (!token.isEmpty()) {
logger.debug("Calling TokenUpdate service to update token
cookie");
- loginCookieManager.setLoginCookie(request, response,
repository, oidcAuthCredentials);
+ loginCookieManager.setLoginCookie(request, response,
oidcAuthCredentials);
}
}
diff --git
a/src/main/java/org/apache/sling/auth/oauth_client/impl/SlingLoginCookieManager.java
b/src/main/java/org/apache/sling/auth/oauth_client/impl/SlingLoginCookieManager.java
index 4b2f800..b3aa3a0 100644
---
a/src/main/java/org/apache/sling/auth/oauth_client/impl/SlingLoginCookieManager.java
+++
b/src/main/java/org/apache/sling/auth/oauth_client/impl/SlingLoginCookieManager.java
@@ -32,7 +32,6 @@ import org.apache.commons.codec.binary.Base64;
import org.apache.sling.auth.core.spi.AuthenticationInfo;
import org.apache.sling.auth.oauth_client.spi.LoginCookieManager;
import org.apache.sling.auth.oauth_client.spi.OidcAuthCredentials;
-import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.jcr.resource.api.JcrResourceConstants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -88,10 +87,7 @@ public class SlingLoginCookieManager implements
LoginCookieManager {
@Override
public void setLoginCookie(
- @NotNull HttpServletRequest request,
- @NotNull HttpServletResponse response,
- @NotNull SlingRepository repository,
- @NotNull Credentials creds) {
+ @NotNull HttpServletRequest request, @NotNull HttpServletResponse
response, @NotNull Credentials creds) {
long expires = System.currentTimeMillis() + this.sessionTimeout;
diff --git
a/src/main/java/org/apache/sling/auth/oauth_client/spi/LoginCookieManager.java
b/src/main/java/org/apache/sling/auth/oauth_client/spi/LoginCookieManager.java
index 4791413..1a802f4 100644
---
a/src/main/java/org/apache/sling/auth/oauth_client/spi/LoginCookieManager.java
+++
b/src/main/java/org/apache/sling/auth/oauth_client/spi/LoginCookieManager.java
@@ -24,7 +24,6 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.sling.auth.core.spi.AuthenticationInfo;
-import org.apache.sling.jcr.api.SlingRepository;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -37,14 +36,10 @@ public interface LoginCookieManager {
* Set the login cookie in the response after a successful authentication.
* @param request
* @param response
- * @param repository
* @param creds
*/
void setLoginCookie(
- @NotNull HttpServletRequest request,
- @NotNull HttpServletResponse response,
- @NotNull SlingRepository repository,
- @NotNull Credentials creds);
+ @NotNull HttpServletRequest request, @NotNull HttpServletResponse
response, @NotNull Credentials creds);
/**
* Verify the login cookie in the request. If the Authentication Handler
do not verify the cookie, return null.
diff --git
a/src/main/java/org/apache/sling/auth/oauth_client/spi/package-info.java
b/src/main/java/org/apache/sling/auth/oauth_client/spi/package-info.java
index bbfbaba..e2c6697 100644
--- a/src/main/java/org/apache/sling/auth/oauth_client/spi/package-info.java
+++ b/src/main/java/org/apache/sling/auth/oauth_client/spi/package-info.java
@@ -16,5 +16,5 @@
* specific language governing permissions and limitations
* under the License.
*/
[email protected]("1.0.0")
[email protected]("2.0.0")
package org.apache.sling.auth.oauth_client.spi;
diff --git
a/src/test/java/org/apache/sling/auth/oauth_client/AuthorizationCodeFlowIT.java
b/src/test/java/org/apache/sling/auth/oauth_client/AuthorizationCodeFlowIT.java
index 3a69665..16e7eea 100644
---
a/src/test/java/org/apache/sling/auth/oauth_client/AuthorizationCodeFlowIT.java
+++
b/src/test/java/org/apache/sling/auth/oauth_client/AuthorizationCodeFlowIT.java
@@ -74,7 +74,7 @@ import org.junit.jupiter.api.io.TempDir;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
class AuthorizationCodeFlowIT {
diff --git
a/src/test/java/org/apache/sling/auth/oauth_client/impl/CryptoOAuthCookieValueManagerTest.java
b/src/test/java/org/apache/sling/auth/oauth_client/impl/CryptoOAuthCookieValueManagerTest.java
index 45601d6..0299f98 100644
---
a/src/test/java/org/apache/sling/auth/oauth_client/impl/CryptoOAuthCookieValueManagerTest.java
+++
b/src/test/java/org/apache/sling/auth/oauth_client/impl/CryptoOAuthCookieValueManagerTest.java
@@ -21,7 +21,6 @@ package org.apache.sling.auth.oauth_client.impl;
import java.util.stream.Stream;
import com.nimbusds.oauth2.sdk.id.State;
-import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
@@ -49,15 +48,4 @@ class CryptoOAuthCookieValueManagerTest {
assertThat(manager.toOAuthState(nimbusState)).as("decoded OAuth
state").contains(state);
}
-
- @Test
- void identicalInputsGenerateDifferentOutputs() {
-
- CryptoOAuthStateManager manager = new CryptoOAuthStateManager(new
StubCryptoService());
-
- State firstState = manager.toNimbusState(states().findFirst().get());
- State secondState = manager.toNimbusState(states().findFirst().get());
-
- assertThat(firstState.getValue()).as("generated states are
different").isNotEqualTo(secondState.getValue());
- }
}
diff --git
a/src/test/java/org/apache/sling/auth/oauth_client/impl/MockRequest.java
b/src/test/java/org/apache/sling/auth/oauth_client/impl/MockRequest.java
deleted file mode 100644
index 1b3b87a..0000000
--- a/src/test/java/org/apache/sling/auth/oauth_client/impl/MockRequest.java
+++ /dev/null
@@ -1,473 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.sling.auth.oauth_client.impl;
-
-import javax.servlet.AsyncContext;
-import javax.servlet.DispatcherType;
-import javax.servlet.RequestDispatcher;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletInputStream;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-import javax.servlet.http.HttpUpgradeHandler;
-import javax.servlet.http.Part;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-
-public class MockRequest implements HttpServletRequest {
-
- ArrayList<Cookie> cookies;
- HashMap<String, Object> attributes = new HashMap<>();
-
- @Override
- public String getAuthType() {
- // TODO
- return null;
- }
-
- @Override
- public Cookie[] getCookies() {
- if (cookies == null) {
- return null;
- }
- return cookies.toArray(new Cookie[cookies.size()]);
- }
-
- public void addCookie(Cookie cookie) {
- if (cookies == null) {
- cookies = new ArrayList<Cookie>();
- }
- cookies.add(cookie);
- }
-
- @Override
- public long getDateHeader(String name) {
- // TODO
- return 0;
- }
-
- @Override
- public String getHeader(String name) {
- // TODO
- return null;
- }
-
- @Override
- public Enumeration<String> getHeaders(String name) {
- // TODO
- return null;
- }
-
- @Override
- public Enumeration<String> getHeaderNames() {
- // TODO
- return null;
- }
-
- @Override
- public int getIntHeader(String name) {
- // TODO
- return 0;
- }
-
- @Override
- public String getMethod() {
- // TODO
- return null;
- }
-
- @Override
- public String getPathInfo() {
- // TODO
- return null;
- }
-
- @Override
- public String getPathTranslated() {
- // TODO
- return null;
- }
-
- @Override
- public String getContextPath() {
- // TODO
- return null;
- }
-
- @Override
- public String getQueryString() {
- // TODO
- return null;
- }
-
- @Override
- public String getRemoteUser() {
- // TODO
- return null;
- }
-
- @Override
- public boolean isUserInRole(String role) {
- // TODO
- return false;
- }
-
- @Override
- public Principal getUserPrincipal() {
- // TODO
- return null;
- }
-
- @Override
- public String getRequestedSessionId() {
- // TODO
- return null;
- }
-
- @Override
- public String getRequestURI() {
- // TODO
- return null;
- }
-
- @Override
- public StringBuffer getRequestURL() {
- // TODO
- return new StringBuffer("/");
- }
-
- @Override
- public String getServletPath() {
- // TODO
- return null;
- }
-
- @Override
- public HttpSession getSession(boolean create) {
- // TODO
- return null;
- }
-
- @Override
- public HttpSession getSession() {
- // TODO
- return null;
- }
-
- @Override
- public String changeSessionId() {
- // TODO
- return null;
- }
-
- @Override
- public boolean isRequestedSessionIdValid() {
- // TODO
- return false;
- }
-
- @Override
- public boolean isRequestedSessionIdFromCookie() {
- // TODO
- return false;
- }
-
- @Override
- public boolean isRequestedSessionIdFromURL() {
- // TODO
- return false;
- }
-
- @Override
- public boolean isRequestedSessionIdFromUrl() {
- // TODO
- return false;
- }
-
- @Override
- public boolean authenticate(HttpServletResponse response) throws
IOException, ServletException {
- // TODO
- return false;
- }
-
- @Override
- public void login(String username, String password) throws
ServletException {
- // TODO
-
- }
-
- @Override
- public void logout() throws ServletException {
- // TODO
-
- }
-
- @Override
- public Collection<Part> getParts() throws IOException, ServletException {
- // TODO
- return null;
- }
-
- @Override
- public Part getPart(String name) throws IOException, ServletException {
- // TODO
- return null;
- }
-
- @Override
- public <T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass)
throws IOException, ServletException {
- // TODO
- return null;
- }
-
- @Override
- public Object getAttribute(String name) {
- return attributes.get(name);
- }
-
- @Override
- public Enumeration<String> getAttributeNames() {
- // TODO
- return null;
- }
-
- @Override
- public String getCharacterEncoding() {
- // TODO
- return null;
- }
-
- @Override
- public void setCharacterEncoding(String env) throws
UnsupportedEncodingException {
- // TODO
-
- }
-
- @Override
- public int getContentLength() {
- // TODO
- return 0;
- }
-
- @Override
- public long getContentLengthLong() {
- // TODO
- return 0;
- }
-
- @Override
- public String getContentType() {
- // TODO
- return null;
- }
-
- @Override
- public ServletInputStream getInputStream() throws IOException {
- // TODO
- return null;
- }
-
- @Override
- public String getParameter(String name) {
- // TODO
- return null;
- }
-
- @Override
- public Enumeration<String> getParameterNames() {
- // TODO
- return null;
- }
-
- @Override
- public String[] getParameterValues(String name) {
- // TODO
- return new String[0];
- }
-
- @Override
- public Map<String, String[]> getParameterMap() {
- // TODO
- return null;
- }
-
- @Override
- public String getProtocol() {
- // TODO
- return null;
- }
-
- @Override
- public String getScheme() {
- // TODO
- return null;
- }
-
- @Override
- public String getServerName() {
- // TODO
- return null;
- }
-
- @Override
- public int getServerPort() {
- // TODO
- return 0;
- }
-
- @Override
- public BufferedReader getReader() throws IOException {
- // TODO
- return null;
- }
-
- @Override
- public String getRemoteAddr() {
- // TODO
- return null;
- }
-
- @Override
- public String getRemoteHost() {
- // TODO
- return null;
- }
-
- @Override
- public void setAttribute(String name, Object o) {
- attributes.put(name, o);
- }
-
- @Override
- public void removeAttribute(String name) {
- // TODO
-
- }
-
- @Override
- public Locale getLocale() {
- // TODO
- return null;
- }
-
- @Override
- public Enumeration<Locale> getLocales() {
- // TODO
- return null;
- }
-
- @Override
- public boolean isSecure() {
- // TODO
- return false;
- }
-
- @Override
- public RequestDispatcher getRequestDispatcher(String path) {
- // TODO
- return null;
- }
-
- @Override
- public String getRealPath(String path) {
- // TODO
- return null;
- }
-
- @Override
- public int getRemotePort() {
- // TODO
- return 0;
- }
-
- @Override
- public String getLocalName() {
- // TODO
- return null;
- }
-
- @Override
- public String getLocalAddr() {
- // TODO
- return null;
- }
-
- @Override
- public int getLocalPort() {
- // TODO
- return 0;
- }
-
- @Override
- public ServletContext getServletContext() {
- // TODO
- return null;
- }
-
- @Override
- public AsyncContext startAsync() throws IllegalStateException {
- // TODO
- return null;
- }
-
- @Override
- public AsyncContext startAsync(ServletRequest servletRequest,
ServletResponse servletResponse)
- throws IllegalStateException {
- // TODO
- return null;
- }
-
- @Override
- public boolean isAsyncStarted() {
- // TODO
- return false;
- }
-
- @Override
- public boolean isAsyncSupported() {
- // TODO
- return false;
- }
-
- @Override
- public AsyncContext getAsyncContext() {
- // TODO
- return null;
- }
-
- @Override
- public DispatcherType getDispatcherType() {
- // TODO
- return null;
- }
-}
diff --git
a/src/test/java/org/apache/sling/auth/oauth_client/impl/MockResponse.java
b/src/test/java/org/apache/sling/auth/oauth_client/impl/MockResponse.java
deleted file mode 100644
index 771d0ec..0000000
--- a/src/test/java/org/apache/sling/auth/oauth_client/impl/MockResponse.java
+++ /dev/null
@@ -1,270 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.sling.auth.oauth_client.impl;
-
-import javax.servlet.ServletOutputStream;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletResponse;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-
-public class MockResponse implements HttpServletResponse {
- ArrayList<Cookie> cookies = new ArrayList();
- HashMap<String, String> headers = new HashMap<>();
- String sendRedirect = null;
- int error = 0;
- String errorMessage = null;
-
- @Override
- public void addCookie(Cookie cookie) {
- cookies.add(cookie);
- }
-
- public List<Cookie> getCookies() {
- return cookies;
- }
-
- @Override
- public boolean containsHeader(String name) {
- // TODO
- return false;
- }
-
- @Override
- public String encodeURL(String url) {
- // TODO
- return null;
- }
-
- @Override
- public String encodeRedirectURL(String url) {
- // TODO
- return null;
- }
-
- @Override
- public String encodeUrl(String url) {
- // TODO
- return null;
- }
-
- @Override
- public String encodeRedirectUrl(String url) {
- // TODO
- return null;
- }
-
- @Override
- public void sendError(int sc, String msg) throws IOException {
- error = sc;
- errorMessage = msg;
- }
-
- public int getErrorCode() {
- return error;
- }
-
- public String getErrorMessage() {
- return errorMessage;
- }
-
- @Override
- public void sendError(int sc) throws IOException {
- // TODO
-
- }
-
- @Override
- public void sendRedirect(String location) throws IOException {
- sendRedirect = location;
- }
-
- public String getSendRedirect() {
- return sendRedirect;
- }
-
- @Override
- public void setDateHeader(String name, long date) {}
-
- @Override
- public void addDateHeader(String name, long date) {
- // TODO
-
- }
-
- @Override
- public void setHeader(String name, String value) {
- headers.put(name, value);
- }
-
- @Override
- public void addHeader(String name, String value) {
- headers.put(name, value);
- }
-
- @Override
- public void setIntHeader(String name, int value) {
- // TODO
-
- }
-
- @Override
- public void addIntHeader(String name, int value) {
- // TODO
-
- }
-
- @Override
- public void setStatus(int sc) {
- // TODO
-
- }
-
- @Override
- public void setStatus(int sc, String sm) {
- // TODO
-
- }
-
- @Override
- public int getStatus() {
- // TODO
- return 0;
- }
-
- @Override
- public String getHeader(String name) {
- // TODO
- return headers.get(name);
- }
-
- @Override
- public Collection<String> getHeaders(String name) {
- // TODO
- return null;
- }
-
- @Override
- public Collection<String> getHeaderNames() {
- // TODO
- return null;
- }
-
- @Override
- public String getCharacterEncoding() {
- // TODO
- return null;
- }
-
- @Override
- public String getContentType() {
- // TODO
- return null;
- }
-
- @Override
- public ServletOutputStream getOutputStream() throws IOException {
- // TODO
- return null;
- }
-
- @Override
- public PrintWriter getWriter() throws IOException {
- // TODO
- return null;
- }
-
- @Override
- public void setCharacterEncoding(String charset) {
- // TODO
-
- }
-
- @Override
- public void setContentLength(int len) {
- // TODO
-
- }
-
- @Override
- public void setContentLengthLong(long len) {
- // TODO
-
- }
-
- @Override
- public void setContentType(String type) {
- // TODO
-
- }
-
- @Override
- public void setBufferSize(int size) {
- // TODO
-
- }
-
- @Override
- public int getBufferSize() {
- // TODO
- return 0;
- }
-
- @Override
- public void flushBuffer() throws IOException {
- // TODO
-
- }
-
- @Override
- public void resetBuffer() {
- // TODO
-
- }
-
- @Override
- public boolean isCommitted() {
- // TODO
- return false;
- }
-
- @Override
- public void reset() {
- // TODO
-
- }
-
- @Override
- public void setLocale(Locale loc) {
- // TODO
-
- }
-
- @Override
- public Locale getLocale() {
- // TODO
- return null;
- }
-}
diff --git
a/src/test/java/org/apache/sling/auth/oauth_client/impl/OidcAuthenticationHandlerTest.java
b/src/test/java/org/apache/sling/auth/oauth_client/impl/OidcAuthenticationHandlerTest.java
index d79e5ba..0d7772a 100644
---
a/src/test/java/org/apache/sling/auth/oauth_client/impl/OidcAuthenticationHandlerTest.java
+++
b/src/test/java/org/apache/sling/auth/oauth_client/impl/OidcAuthenticationHandlerTest.java
@@ -28,6 +28,7 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@@ -54,12 +55,16 @@ import
org.apache.sling.auth.oauth_client.spi.LoginCookieManager;
import org.apache.sling.auth.oauth_client.spi.OidcAuthCredentials;
import org.apache.sling.auth.oauth_client.spi.UserInfoProcessor;
import org.apache.sling.commons.crypto.CryptoService;
-import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.jcr.resource.api.JcrResourceConstants;
+import org.apache.sling.testing.mock.osgi.junit.OsgiContext;
+import org.apache.sling.testing.mock.osgi.junit5.OsgiContextExtension;
+import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest;
+import
org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.osgi.framework.BundleContext;
import static org.junit.jupiter.api.Assertions.*;
@@ -68,14 +73,14 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+@ExtendWith(OsgiContextExtension.class)
class OidcAuthenticationHandlerTest {
private static final String MOCK_OIDC_PARAM = "mock-oidc-param";
private static final String ISSUER = "myIssuer";
- private SlingRepository repository;
+ private OsgiContext osgiContext = new OsgiContext();
private BundleContext bundleContext;
private List<ClientConnection> connections;
- private OAuthStateManager oauthStateManager;
private OidcAuthenticationHandler oidcAuthenticationHandler;
private OidcAuthenticationHandler.Config config;
@@ -92,8 +97,7 @@ class OidcAuthenticationHandlerTest {
tokenEndpointServer = createHttpServer();
idpServer = createHttpServer();
- repository = mock(SlingRepository.class);
- bundleContext = mock(BundleContext.class);
+ bundleContext = osgiContext.bundleContext();
config = mock(OidcAuthenticationHandler.Config.class);
when(config.idp()).thenReturn("myIdP");
when(config.path()).thenReturn(new String[] {"/"});
@@ -109,8 +113,6 @@ class OidcAuthenticationHandlerTest {
connections = new ArrayList<>();
connections.add(MockOidcConnection.DEFAULT_CONNECTION);
- oauthStateManager = new StubOAuthStateManager();
-
request = mock(HttpServletRequest.class);
when(request.getRequestURL()).thenReturn(new
StringBuffer("http://localhost:8080"));
@@ -794,14 +796,7 @@ class OidcAuthenticationHandlerTest {
private void createOidcAuthenticationHandler() {
oidcAuthenticationHandler = new OidcAuthenticationHandler(
- repository,
- bundleContext,
- connections,
- oauthStateManager,
- config,
- loginCookieManager,
- userInfoProcessor,
- cryptoService);
+ bundleContext, connections, config, loginCookieManager,
userInfoProcessor, cryptoService);
}
private HttpServer createHttpServer() throws IOException {
@@ -874,25 +869,26 @@ class OidcAuthenticationHandlerTest {
when(config.pkceEnabled()).thenReturn(false);
when(request.getRequestURI()).thenReturn("http://localhost");
- MockResponse mockResponse = new MockResponse();
+ MockSlingHttpServletResponse mockResponse = new
MockSlingHttpServletResponse();
createOidcAuthenticationHandler();
assertTrue(oidcAuthenticationHandler.requestCredentials(request,
mockResponse));
- assertTrue(mockResponse.getCookies().stream().anyMatch(cookie -> {
+ assertTrue(Arrays.stream(mockResponse.getCookies()).anyMatch(cookie ->
{
if
(OAuthStateManager.COOKIE_NAME_REQUEST_KEY.equals(cookie.getName())) {
OAuthCookieValue oauthCookieValue = new
OAuthCookieValue(cookie.getValue(), cryptoService);
// Verify that state is present in request and in cookie
- assertTrue(mockResponse.getSendRedirect().contains("state=" +
oauthCookieValue.perRequestKey()));
+ assertEquals(302, mockResponse.getStatus());
+
assertTrue(mockResponse.getHeader("location").contains("state=" +
oauthCookieValue.perRequestKey()));
// Verify that nonce is present in request and in cookie
assertTrue(mockResponse
- .getSendRedirect()
+ .getHeader("location")
.contains("nonce=" +
oauthCookieValue.nonce().getValue()));
// Verify that codeVerifier is not present cookie and request
assertNull(oauthCookieValue.codeVerifier());
-
assertFalse(mockResponse.getSendRedirect().contains("code_verifier="));
+
assertFalse(mockResponse.getHeader("location").contains("code_verifier="));
// Verify that the redirect URI in the cookie is correct
assertTrue(oauthCookieValue.redirect().equals("http://localhost"));
@@ -926,7 +922,7 @@ class OidcAuthenticationHandlerTest {
when(config.callbackUri()).thenReturn("http://redirect");
when(config.pkceEnabled()).thenReturn(false);
- MockResponse mockResponse = new MockResponse();
+ MockSlingHttpServletResponse mockResponse = new
MockSlingHttpServletResponse();
when(config.pkceEnabled()).thenReturn(true);
when(config.path()).thenReturn(new String[] {"/"});
@@ -935,17 +931,18 @@ class OidcAuthenticationHandlerTest {
createOidcAuthenticationHandler();
assertTrue(oidcAuthenticationHandler.requestCredentials(request,
mockResponse));
- assertTrue(mockResponse.getCookies().stream().anyMatch(cookie -> {
+ assertTrue(Arrays.stream(mockResponse.getCookies()).anyMatch(cookie ->
{
if
(OAuthStateManager.COOKIE_NAME_REQUEST_KEY.equals(cookie.getName())) {
String cookieValue = cryptoService.decrypt(cookie.getValue());
assertNotNull(cookieValue);
String[] cookieParts = cookieValue.split("\\|");
// Verify code verifier in the cookie match with
code_challenge in the redirect
-
assertTrue(mockResponse.getSendRedirect().contains("code_challenge_method=S256"));
+
assertTrue(mockResponse.getHeader("location").contains("code_challenge_method=S256"));
+ assertEquals(302, mockResponse.getStatus());
CodeVerifier codeVerifier = new
CodeVerifier(cookieParts[OAuthCookieValue.CODE_VERIFIER_INDEX]);
- String codeChallenge = mockResponse.getSendRedirect()
+ String codeChallenge = mockResponse.getHeader("location")
.split("code_challenge=")[1]
.split("&")[0];
CodeChallenge computedCodeChallenge =
CodeChallenge.compute(CodeChallengeMethod.S256, codeVerifier);
@@ -954,12 +951,12 @@ class OidcAuthenticationHandlerTest {
// Verify that steate in the cookie matches with state in the
redirect
assertEquals(
cookieParts[OAuthCookieValue.STATE_INDEX],
-
mockResponse.getSendRedirect().split("state=")[1].split("&")[0]);
+
mockResponse.getHeader("location").split("state=")[1].split("&")[0]);
// Verify that nonce in the cookie matches with nonce in the
redirect
assertEquals(
cookieParts[OAuthCookieValue.NONCE_INDEX],
- URLDecoder.decode(mockResponse.getSendRedirect()
+ URLDecoder.decode(mockResponse.getHeader("location")
.split("nonce=")[1]
.split("&")[0]));
@@ -967,7 +964,7 @@ class OidcAuthenticationHandlerTest {
assertTrue(cookieParts[OAuthCookieValue.REDIRECT_INDEX].equals("http://localhost"));
// Verify that the callbackUri is correct
-
assertTrue(mockResponse.getSendRedirect().contains("redirect_uri=http%3A%2F%2Fredirect"));
+
assertTrue(mockResponse.getHeader("location").contains("redirect_uri=http%3A%2F%2Fredirect"));
return true;
}
return false;
@@ -999,12 +996,12 @@ class OidcAuthenticationHandlerTest {
when(config.callbackUri()).thenReturn("http://redirect");
when(request.getParameter("c")).thenReturn("unknown-connection");
- MockResponse response1 = new MockResponse();
+ MockSlingHttpServletResponse response1 = new
MockSlingHttpServletResponse();
createOidcAuthenticationHandler();
assertFalse(oidcAuthenticationHandler.requestCredentials(request,
response1));
- assertEquals(HttpServletResponse.SC_BAD_REQUEST,
response1.getErrorCode());
- assertEquals("Client requested unknown connection",
response1.getErrorMessage());
+ assertEquals(HttpServletResponse.SC_BAD_REQUEST,
response1.getStatus());
+ assertEquals("Client requested unknown connection",
response1.getStatusMessage());
}
@Test
@@ -1033,7 +1030,7 @@ class OidcAuthenticationHandlerTest {
@Test
void authenticationSucceededLoginManagerWithNoLoginCookie() {
when(loginCookieManager.getLoginCookie(request)).thenReturn(null);
- MockResponse mockResponse = new MockResponse();
+ MockSlingHttpServletResponse mockResponse = new
MockSlingHttpServletResponse();
createOidcAuthenticationHandler();
AuthenticationInfo authInfo = new AuthenticationInfo("oidc",
"testUser");
@@ -1041,16 +1038,17 @@ class OidcAuthenticationHandlerTest {
credentials.setAttribute(".token", "testToken");
authInfo.put(JcrResourceConstants.AUTHENTICATION_INFO_CREDENTIALS,
credentials);
- MockRequest mockRequest = new MockRequest();
+ MockSlingHttpServletRequest mockRequest = new
MockSlingHttpServletRequest(bundleContext);
mockRequest.setAttribute(OidcAuthenticationHandler.REDIRECT_ATTRIBUTE_NAME,
"http://localhost:8080");
when(config.pkceEnabled()).thenReturn(true);
createOidcAuthenticationHandler();
assertTrue(oidcAuthenticationHandler.authenticationSucceeded(mockRequest,
mockResponse, authInfo));
- assertEquals("http://localhost:8080", mockResponse.getSendRedirect());
+ assertEquals("http://localhost:8080",
mockResponse.getHeader("location"));
+ assertEquals(302, mockResponse.getStatus());
- assertTrue(mockResponse.getCookies().stream().anyMatch(cookie -> {
+ assertTrue(Arrays.stream(mockResponse.getCookies()).anyMatch(cookie ->
{
if
(OAuthStateManager.COOKIE_NAME_REQUEST_KEY.equals(cookie.getName())) {
int maxAge = cookie.getMaxAge();
assertEquals(0, maxAge);
@@ -1065,6 +1063,12 @@ class OidcAuthenticationHandlerTest {
OidcConnectionImpl oidcClientConnection =
mock(OidcConnectionImpl.class);
when(oidcClientConnection.scopes()).thenReturn(new String[0]);
when(oidcClientConnection.additionalAuthorizationParameters()).thenReturn(new
String[0]);
+ when(oidcClientConnection.name()).thenReturn("test");
+ when(oidcClientConnection.clientId()).thenReturn("client-id");
+ when(oidcClientConnection.clientSecret()).thenReturn("client-secret");
+
when(oidcClientConnection.authorizationEndpoint()).thenReturn("http://localhost:8080/authorize");
+
when(oidcClientConnection.tokenEndpoint()).thenReturn("http://localhost:8080/token");
+
when(oidcClientConnection.issuer()).thenReturn("http://localhost:8080/issuer");
assertInstanceOf(ResolvedOidcConnection.class,
ResolvedOidcConnection.resolve(oidcClientConnection));
OAuthConnectionImpl oauthClientConnection =
mock(OAuthConnectionImpl.class);
diff --git
a/src/test/java/org/apache/sling/auth/oauth_client/impl/SlingLoginCookieManagerTest.java
b/src/test/java/org/apache/sling/auth/oauth_client/impl/SlingLoginCookieManagerTest.java
index 292b54e..35e7eaa 100644
---
a/src/test/java/org/apache/sling/auth/oauth_client/impl/SlingLoginCookieManagerTest.java
+++
b/src/test/java/org/apache/sling/auth/oauth_client/impl/SlingLoginCookieManagerTest.java
@@ -28,13 +28,15 @@ import java.util.Base64;
import org.apache.sling.auth.core.spi.AuthenticationInfo;
import org.apache.sling.auth.oauth_client.spi.OidcAuthCredentials;
-import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.jcr.resource.api.JcrResourceConstants;
+import org.apache.sling.testing.mock.osgi.junit.OsgiContext;
+import org.apache.sling.testing.mock.osgi.junit5.OsgiContextExtension;
+import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest;
+import
org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.io.TempDir;
-import org.osgi.framework.BundleContext;
+import org.junit.jupiter.api.extension.ExtendWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
@@ -44,32 +46,32 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+@ExtendWith(OsgiContextExtension.class)
class SlingLoginCookieManagerTest {
private static final String COOKIE_NAME = "sling.oidcauth";
- private final MockRequest request = new MockRequest();
- private final MockResponse response = new MockResponse();
- private final SlingRepository repository = mock(SlingRepository.class);
+ private final OsgiContext osgiContext = new OsgiContext();
+ private MockSlingHttpServletRequest request;
+ private final MockSlingHttpServletResponse response = new
MockSlingHttpServletResponse();
private SlingLoginCookieManager slingLoginCookieManager;
- private @TempDir File tempFolder;
@BeforeEach
void setup() throws NoSuchAlgorithmException, InvalidKeyException {
+
+ request = new MockSlingHttpServletRequest(osgiContext.bundleContext());
+
SlingLoginCookieManager.SlingLoginCookieManagerConfig config =
mock(SlingLoginCookieManager.SlingLoginCookieManagerConfig.class);
- File tokenFile = new File(tempFolder, "cookie-tokens.bin");
+ File tokenFile =
osgiContext.bundleContext().getDataFile("cookie-tokens.bin");
when(config.tokenFile()).thenReturn(tokenFile.getAbsolutePath());
when(config.form_token_fastseed()).thenReturn(false);
when(config.sessionTimeout()).thenReturn(8 * 60 * 60 * 1000L);
when(config.cookieName()).thenReturn(COOKIE_NAME);
- BundleContext bundleContext = mock(BundleContext.class);
- when(bundleContext.getDataFile("cookie-tokens")).thenReturn(tokenFile);
-
- slingLoginCookieManager = new SlingLoginCookieManager(config,
bundleContext);
+ slingLoginCookieManager = new SlingLoginCookieManager(config,
osgiContext.bundleContext());
}
@Test
@@ -77,7 +79,7 @@ class SlingLoginCookieManagerTest {
OidcAuthCredentials creds = mock(OidcAuthCredentials.class);
when(creds.getUserId()).thenReturn("testUser");
- slingLoginCookieManager.setLoginCookie(request, response, repository,
creds);
+ slingLoginCookieManager.setLoginCookie(request, response, creds);
Cookie cookie = parseSetCookieHeader(response.getHeader("Set-Cookie"));
assertNotNull(cookie);
diff --git
a/src/test/java/org/apache/sling/auth/oauth_client/impl/StubCryptoServiceTest.java
b/src/test/java/org/apache/sling/auth/oauth_client/impl/StubCryptoServiceTest.java
index ed50791..38237f5 100644
---
a/src/test/java/org/apache/sling/auth/oauth_client/impl/StubCryptoServiceTest.java
+++
b/src/test/java/org/apache/sling/auth/oauth_client/impl/StubCryptoServiceTest.java
@@ -30,7 +30,7 @@ class StubCryptoServiceTest {
assertThat(stubCryptoService.decrypt(stubCryptoService.encrypt("test"))).isEqualTo("test");
}
- @org.junit.Test
+ @Test
void encryptIsNotEqualToInput() {
StubCryptoService stubCryptoService = new StubCryptoService();
assertThat(stubCryptoService.encrypt("test")).isNotEqualTo("test");
diff --git
a/src/test/java/org/apache/sling/auth/oauth_client/impl/TokenStoreTest.java
b/src/test/java/org/apache/sling/auth/oauth_client/impl/TokenStoreTest.java
index a2fdede..13daafd 100644
--- a/src/test/java/org/apache/sling/auth/oauth_client/impl/TokenStoreTest.java
+++ b/src/test/java/org/apache/sling/auth/oauth_client/impl/TokenStoreTest.java
@@ -25,56 +25,51 @@ import java.nio.file.Files;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
-import java.util.Collection;
-import java.util.List;
import java.util.UUID;
+import java.util.stream.Stream;
import org.awaitility.Awaitility;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/* TokenStore tests, taken from org.apache.sling.auth.form */
-@RunWith(Parameterized.class)
public class TokenStoreTest {
private static final long SESSION_TIMEOUT_MSEC = 60 * 1000L;
private static final long DEFAULT_EXPIRATION_TIME_MSEC =
System.currentTimeMillis() + SESSION_TIMEOUT_MSEC / 2;
private static final String USER_ID = "user_" + UUID.randomUUID();
- @Parameterized.Parameters(name = "name={1}")
- public static Collection<Object[]> parameters() {
- return List.of(new Object[] {false, "fastSeed = false"}, new Object[]
{true, "fastSeed = true"});
- }
-
- private final boolean fastSeed;
+ private boolean fastSeed;
private TokenStore store;
private String encodedToken;
private File tokenFile;
private int additionalFileIndex;
- public TokenStoreTest(boolean fastSeed, String name) {
- this.fastSeed = fastSeed;
- }
-
private File additionalTokenFile() {
return new File(tokenFile.getParent(), tokenFile.getName() + "-" +
additionalFileIndex++);
}
- @Before
+ @BeforeEach
public void setup() throws IOException, InvalidKeyException,
NoSuchAlgorithmException, IllegalStateException {
tokenFile = Files.createTempFile(getClass().getName(),
"tokenstore").toFile();
store = new TokenStore(tokenFile, SESSION_TIMEOUT_MSEC, fastSeed);
encodedToken = store.encode(DEFAULT_EXPIRATION_TIME_MSEC, USER_ID);
}
- @Test
- public void validTokenTest() {
+ public static Stream<Object[]> parameters() {
+ return Stream.of(new Object[] {false, "fastSeed = false"}, new
Object[] {true, "fastSeed = true"});
+ }
+
+ @ParameterizedTest(name = "name={1}")
+ @MethodSource("parameters")
+ void validTokenTest(boolean fastSeed, String name) {
+ this.fastSeed = fastSeed;
assertTrue(store.isValid(encodedToken));
}