You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by ro...@apache.org on 2024/11/01 16:55:13 UTC
(sling-whiteboard) branch master updated: feat(oidc-rp): switch back some error handling to simple status settting
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-whiteboard.git
The following commit(s) were added to refs/heads/master by this push:
new a5793e56 feat(oidc-rp): switch back some error handling to simple status settting
a5793e56 is described below
commit a5793e56fb5f75f02897643b9e0f0d3403bc2a2a
Author: Robert Munteanu <ro...@apache.org>
AuthorDate: Fri Nov 1 17:54:05 2024 +0100
feat(oidc-rp): switch back some error handling to simple status settting
This prevents log spam from easily-crafted requests.
---
org.apache.sling.servlets.oidc-rp/README.md | 7 +-
.../oauth_client/impl/OAuthCallbackServlet.java | 44 +++++--
.../oauth_client/impl/OAuthEntryPointServlet.java | 22 +++-
.../impl/OAuthCallbackServletTest.java | 136 +++++++++++++++++++++
.../impl/OAuthEntryPointServletTest.java | 39 +++---
.../oauth_client/impl/StubOAuthStateManager.java | 37 ++++++
6 files changed, 249 insertions(+), 36 deletions(-)
diff --git a/org.apache.sling.servlets.oidc-rp/README.md b/org.apache.sling.servlets.oidc-rp/README.md
index 1377f947..004bde61 100644
--- a/org.apache.sling.servlets.oidc-rp/README.md
+++ b/org.apache.sling.servlets.oidc-rp/README.md
@@ -54,8 +54,11 @@ TODO
### Error handling
-The top-level servlets used for the OAuth flow will throw specific subclasses of ServletException.
-These exceptions will return generic messages that can be displayed directly to the user and store
+The top-level servlets used for the OAuth flow will validate parameters that are expected to be
+sent by the client and return a status code of 400 in case the parameters are missing or invalid.
+
+For others problems related to the OAuth flow these servlets throw specific subclasses of ServletException.
+The exceptions will return generic messages that can be displayed directly to the user and store
the actual cause in nested exception so that it is logged.
These exceptions are:
diff --git a/org.apache.sling.servlets.oidc-rp/src/main/java/org/apache/sling/extensions/oauth_client/impl/OAuthCallbackServlet.java b/org.apache.sling.servlets.oidc-rp/src/main/java/org/apache/sling/extensions/oauth_client/impl/OAuthCallbackServlet.java
index 3fd6c3c6..c2504009 100644
--- a/org.apache.sling.servlets.oidc-rp/src/main/java/org/apache/sling/extensions/oauth_client/impl/OAuthCallbackServlet.java
+++ b/org.apache.sling.servlets.oidc-rp/src/main/java/org/apache/sling/extensions/oauth_client/impl/OAuthCallbackServlet.java
@@ -16,11 +16,11 @@
*/
package org.apache.sling.extensions.oauth_client.impl;
-import static java.lang.String.format;
import static org.osgi.service.component.annotations.ReferencePolicyOption.GREEDY;
import java.io.IOException;
import java.net.URI;
+import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
@@ -46,6 +46,8 @@ import org.apache.sling.servlets.annotations.SlingServletPaths;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import com.nimbusds.oauth2.sdk.AuthorizationCode;
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant;
@@ -71,6 +73,8 @@ public class OAuthCallbackServlet extends SlingAllMethodsServlet {
private static final long serialVersionUID = 1L;
+ private final Logger logger = LoggerFactory.getLogger(getClass());
+
private final Map<String, ClientConnection> connections;
private final OAuthTokenStore tokenStore;
private final OAuthStateManager stateManager;
@@ -112,22 +116,38 @@ public class OAuthCallbackServlet extends SlingAllMethodsServlet {
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException {
- try {
- StringBuffer requestURL = request.getRequestURL();
- if ( request.getQueryString() != null )
- requestURL.append('?').append(request.getQueryString());
+ StringBuffer requestURL = request.getRequestURL();
+ if ( request.getQueryString() != null )
+ requestURL.append('?').append(request.getQueryString());
- AuthorizationResponse authResponse = AuthorizationResponse.parse(new URI(requestURL.toString()));
+ AuthorizationResponse authResponse;
+ Optional<OAuthState> clientState;
+ Cookie stateCookie;
+ try {
+ authResponse = AuthorizationResponse.parse(new URI(requestURL.toString()));
- Optional<OAuthState> clientState = stateManager.toOAuthState(authResponse.getState());
- if ( !clientState.isPresent() )
- throw new IllegalStateException("Failed state check: no state found in authorization response");
+ clientState = stateManager.toOAuthState(authResponse.getState());
+ if ( !clientState.isPresent() ) {
+ logger.debug("Failed state check: no state found in authorization response");
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ return;
+ }
- Cookie stateCookie = request.getCookie(OAuthStateManager.COOKIE_NAME_REQUEST_KEY);
- if ( stateCookie == null )
- throw new IllegalStateException(format("Failed state check: No request cookie named '%s' found", OAuthStateManager.COOKIE_NAME_REQUEST_KEY));
+ stateCookie = request.getCookie(OAuthStateManager.COOKIE_NAME_REQUEST_KEY);
+ if ( stateCookie == null ) {
+ logger.debug("Failed state check: No request cookie named '{}' found", OAuthStateManager.COOKIE_NAME_REQUEST_KEY);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ return;
+ }
+
+ } catch (ParseException | URISyntaxException e) {
+ logger.debug("Failed to parse authorization response", e);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ return;
+ }
+ try {
String stateFromAuthServer = clientState.get().perRequestKey();
String stateFromClient = stateCookie.getValue();
if ( ! stateFromAuthServer.equals(stateFromClient) )
diff --git a/org.apache.sling.servlets.oidc-rp/src/main/java/org/apache/sling/extensions/oauth_client/impl/OAuthEntryPointServlet.java b/org.apache.sling.servlets.oidc-rp/src/main/java/org/apache/sling/extensions/oauth_client/impl/OAuthEntryPointServlet.java
index 1295f4c9..b69a87a4 100644
--- a/org.apache.sling.servlets.oidc-rp/src/main/java/org/apache/sling/extensions/oauth_client/impl/OAuthEntryPointServlet.java
+++ b/org.apache.sling.servlets.oidc-rp/src/main/java/org/apache/sling/extensions/oauth_client/impl/OAuthEntryPointServlet.java
@@ -28,6 +28,7 @@ import java.util.stream.Collectors;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletResponse;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
@@ -38,6 +39,8 @@ import org.apache.sling.servlets.annotations.SlingServletPaths;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import com.nimbusds.oauth2.sdk.AuthorizationRequest;
import com.nimbusds.oauth2.sdk.ResponseType;
@@ -60,6 +63,8 @@ public class OAuthEntryPointServlet extends SlingAllMethodsServlet {
private static final int COOKIE_MAX_AGE_SECONDS = 300;
public static final String PATH = "/system/sling/oauth/entry-point"; // NOSONAR
+ private final Logger logger = LoggerFactory.getLogger(getClass());
+
private final Map<String, ClientConnection> connections;
private final OAuthStateManager stateManager;
@@ -77,18 +82,23 @@ public class OAuthEntryPointServlet extends SlingAllMethodsServlet {
try {
String desiredConnectionName = request.getParameter("c");
- if ( desiredConnectionName == null )
- throw new IllegalArgumentException("Missing mandatory request parameter 'c'");
+ if ( desiredConnectionName == null ) {
+ logger.debug("Missing mandatory request parameter 'c'");
+ response.sendError(HttpServletResponse.SC_BAD_REQUEST);
+ return;
+ }
ClientConnection connection = connections.get(desiredConnectionName);
- if ( connection == null )
- throw new IllegalArgumentException(String.format("Client requested unknown connection '%s'; known: '%s'", desiredConnectionName, connections.keySet()));
+ if ( connection == null ) {
+ if ( logger.isDebugEnabled() )
+ logger.debug("Client requested unknown connection '{}'; known: '{}'", desiredConnectionName, connections.keySet());
+ response.sendError(HttpServletResponse.SC_BAD_REQUEST);
+ return;
+ }
var redirect = getAuthenticationRequestUri(connection, request, URI.create(OAuthCallbackServlet.getCallbackUri(request)));
response.addCookie(redirect.cookie());
response.sendRedirect(redirect.uri().toString());
- } catch (IllegalArgumentException e) {
- throw new OAuthEntryPointException("Invalid invocation", e);
} catch (Exception e) {
throw new OAuthEntryPointException("Internal error", e);
}
diff --git a/org.apache.sling.servlets.oidc-rp/src/test/java/org/apache/sling/extensions/oauth_client/impl/OAuthCallbackServletTest.java b/org.apache.sling.servlets.oidc-rp/src/test/java/org/apache/sling/extensions/oauth_client/impl/OAuthCallbackServletTest.java
new file mode 100644
index 00000000..035a0e14
--- /dev/null
+++ b/org.apache.sling.servlets.oidc-rp/src/test/java/org/apache/sling/extensions/oauth_client/impl/OAuthCallbackServletTest.java
@@ -0,0 +1,136 @@
+/*
+ * 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.extensions.oauth_client.impl;
+
+import static java.lang.String.format;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
+
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.sling.extensions.oauth_client.ClientConnection;
+import org.apache.sling.extensions.oauth_client.OAuthTokenStore;
+import org.apache.sling.testing.mock.sling.junit5.SlingContext;
+import org.apache.sling.testing.mock.sling.junit5.SlingContextExtension;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+
+@ExtendWith(SlingContextExtension.class)
+class OAuthCallbackServletTest {
+
+ private static final String MOCK_OIDC_PARAM = "mock-oidc-param";
+
+ private final SlingContext context = new SlingContext();
+
+ private List<ClientConnection> connections;
+
+ @BeforeEach
+ void initConnections() {
+ connections = Arrays.asList(
+ MockOidcConnection.DEFAULT_CONNECTION,
+ new MockOidcConnection(new String[] {"openid"}, MOCK_OIDC_PARAM, "client-id", "client-secret", "http://example.com", new String[] { "access_type=offline" } )
+ );
+ }
+
+ @Test
+ void missingConnectionParameter() throws ServletException, IOException {
+
+ OAuthTokenStore tokenStore = null;
+
+ OAuthCallbackServlet servlet = new OAuthCallbackServlet(connections, tokenStore, new StubOAuthStateManager());
+
+ servlet.service(context.request(), context.response());
+
+ assertThat(context.response().getStatus()).as("response code")
+ .isEqualTo(HttpServletResponse.SC_BAD_REQUEST);
+ }
+
+ @Test
+ void malformedStateParameter() throws ServletException, IOException {
+
+ OAuthTokenStore tokenStore = null;
+
+ OAuthCallbackServlet servlet = new OAuthCallbackServlet(connections, tokenStore, new StubOAuthStateManager());
+
+ context.request().setQueryString("?code=foo&state=bar");
+
+ servlet.service(context.request(), context.response());
+
+ assertThat(context.response().getStatus()).as("response code")
+ .isEqualTo(HttpServletResponse.SC_BAD_REQUEST);
+ }
+
+ @Test
+ void missingStateCookie() throws ServletException, IOException {
+
+ OAuthTokenStore tokenStore = null;
+
+ OAuthCallbackServlet servlet = new OAuthCallbackServlet(connections, tokenStore, new StubOAuthStateManager());
+
+ String state = URLEncoder.encode(format("%s|bar", MockOidcConnection.DEFAULT_CONNECTION.name()), StandardCharsets.UTF_8);
+
+ context.request().setQueryString(format("code=foo&state=%s", state));
+
+ servlet.service(context.request(), context.response());
+
+ assertThat(context.response().getStatus()).as("response code")
+ .isEqualTo(HttpServletResponse.SC_BAD_REQUEST);
+ }
+
+ @Test
+ void invalidStateCookie() {
+ OAuthTokenStore tokenStore = null;
+
+ OAuthCallbackServlet servlet = new OAuthCallbackServlet(connections, tokenStore, new StubOAuthStateManager());
+
+ String state = URLEncoder.encode(format("bar|%s", MockOidcConnection.DEFAULT_CONNECTION.name()), StandardCharsets.UTF_8);
+
+ context.request().setQueryString(format("code=foo&state=%s", state));
+ context.request().addCookie(new Cookie(OAuthStateManager.COOKIE_NAME_REQUEST_KEY, "baz"));
+
+ OAuthCallbackException thrown = assertThrowsExactly(OAuthCallbackException.class, () -> {
+ servlet.service(context.request(), context.response());
+ });
+ assertThat(thrown).hasMessage("State check failed");
+ }
+
+ @Test
+ void errorCode() {
+ OAuthTokenStore tokenStore = null;
+
+ OAuthCallbackServlet servlet = new OAuthCallbackServlet(connections, tokenStore, new StubOAuthStateManager());
+
+ String state = URLEncoder.encode(format("bar|%s", MockOidcConnection.DEFAULT_CONNECTION.name()), StandardCharsets.UTF_8);
+
+ context.request().setQueryString(format("error=access_denied&state=%s", state));
+ context.request().addCookie(new Cookie(OAuthStateManager.COOKIE_NAME_REQUEST_KEY, "bar"));
+
+ OAuthCallbackException thrown = assertThrowsExactly(OAuthCallbackException.class, () -> {
+ servlet.service(context.request(), context.response());
+ });
+ assertThat(thrown).hasMessage("Authentication failed");
+ }
+}
diff --git a/org.apache.sling.servlets.oidc-rp/src/test/java/org/apache/sling/extensions/oauth_client/impl/OAuthEntryPointServletTest.java b/org.apache.sling.servlets.oidc-rp/src/test/java/org/apache/sling/extensions/oauth_client/impl/OAuthEntryPointServletTest.java
index 7c4966f6..9918cda0 100644
--- a/org.apache.sling.servlets.oidc-rp/src/test/java/org/apache/sling/extensions/oauth_client/impl/OAuthEntryPointServletTest.java
+++ b/org.apache.sling.servlets.oidc-rp/src/test/java/org/apache/sling/extensions/oauth_client/impl/OAuthEntryPointServletTest.java
@@ -25,15 +25,12 @@ import java.util.List;
import java.util.Objects;
import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletResponse;
-import org.apache.sling.commons.crypto.CryptoService;
import org.apache.sling.extensions.oauth_client.ClientConnection;
-import org.apache.sling.extensions.oauth_client.impl.CryptoOAuthStateManager;
-import org.apache.sling.extensions.oauth_client.impl.OAuthEntryPointServlet;
import org.apache.sling.testing.mock.sling.junit5.SlingContext;
import org.apache.sling.testing.mock.sling.junit5.SlingContextExtension;
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.extension.ExtendWith;
@@ -53,18 +50,7 @@ class OAuthEntryPointServletTest {
MockOidcConnection.DEFAULT_CONNECTION,
new MockOidcConnection(new String[] {"openid"}, MOCK_OIDC_PARAM, "client-id", "client-secret", "http://example.com", new String[] { "access_type=offline" } )
);
- servlet = new OAuthEntryPointServlet(connections, new CryptoOAuthStateManager(new CryptoService() {
-
- @Override
- public @NotNull String encrypt(@NotNull String message) {
- return message;
- }
-
- @Override
- public @NotNull String decrypt(@NotNull String ciphertext) {
- return ciphertext;
- }
- }));
+ servlet = new OAuthEntryPointServlet(connections, new StubOAuthStateManager());
}
@Test
@@ -101,4 +87,25 @@ class OAuthEntryPointServletTest {
assertThat(location).as("authentication request uri")
.hasParameter("access_type", "offline");
}
+
+ @Test
+ void missingConnectionParameter() throws ServletException, IOException {
+
+ servlet.service(context.request(), context.response());
+
+ assertThat(context.response().getStatus()).as("response code")
+ .isEqualTo(HttpServletResponse.SC_BAD_REQUEST);
+ }
+
+ @Test
+ void invalidConnectionParameter() throws ServletException, IOException {
+
+ context.request().setQueryString("c=invalid");
+
+ MockSlingHttpServletResponse response = context.response();
+ servlet.service(context.request(), response);
+
+ assertThat(context.response().getStatus()).as("response code")
+ .isEqualTo(HttpServletResponse.SC_BAD_REQUEST);
+ }
}
diff --git a/org.apache.sling.servlets.oidc-rp/src/test/java/org/apache/sling/extensions/oauth_client/impl/StubOAuthStateManager.java b/org.apache.sling.servlets.oidc-rp/src/test/java/org/apache/sling/extensions/oauth_client/impl/StubOAuthStateManager.java
new file mode 100644
index 00000000..4f957240
--- /dev/null
+++ b/org.apache.sling.servlets.oidc-rp/src/test/java/org/apache/sling/extensions/oauth_client/impl/StubOAuthStateManager.java
@@ -0,0 +1,37 @@
+/*
+ * 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.extensions.oauth_client.impl;
+
+import org.apache.sling.commons.crypto.CryptoService;
+import org.jetbrains.annotations.NotNull;
+
+class StubOAuthStateManager extends CryptoOAuthStateManager {
+
+ public StubOAuthStateManager() {
+ super(new CryptoService() {
+ @Override
+ public @NotNull String encrypt(@NotNull String message) {
+ return message;
+ }
+
+ @Override
+ public @NotNull String decrypt(@NotNull String ciphertext) {
+ return ciphertext;
+ }
+ });
+ }
+}
\ No newline at end of file