Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;

import org.keycloak.OAuthErrorException;
import org.keycloak.models.BrowserSecurityHeaders;
import org.keycloak.models.ContentSecurityPolicyBuilder;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.representations.idm.OAuth2ErrorRepresentation;

import org.jboss.logging.Logger;

Expand Down Expand Up @@ -71,7 +73,13 @@ public void addHeaders(ContainerRequestContext requestContext, ContainerResponse
return;
}

MediaType requestType = requestContext.getMediaType();
MediaType requestType;
try {
requestType = requestContext.getMediaType();
} catch (IllegalArgumentException ignored) {
requestType = null;
}

MediaType responseType = responseContext.getMediaType();
MultivaluedMap<String, Object> headers = responseContext.getHeaders();

Expand Down Expand Up @@ -165,6 +173,11 @@ private boolean isEmptyMediaTypeAllowed(ContainerRequestContext requestContext,
}
}

if (responseContext.getStatus() == 400 && responseContext.getEntity() instanceof OAuth2ErrorRepresentation resp
&& OAuthErrorException.INVALID_REQUEST.equals(resp.getError())) {
return true;
}

return false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.protocol.oidc.utils.AuthorizeClientUtil;
import org.keycloak.protocol.oidc.utils.ContentTypeValidationUtil;
import org.keycloak.protocol.oidc.utils.LogoutUtil;
import org.keycloak.protocol.oidc.utils.RedirectUtils;
import org.keycloak.representations.IDToken;
Expand Down Expand Up @@ -311,6 +312,7 @@ private Response displayLogoutConfirmationScreen(LoginFormsProvider loginForm, A
@NoCache
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response logout() {
ContentTypeValidationUtil.requireValidContentType(headers, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
MultivaluedMap<String, String> form = request.getDecodedFormParameters();
if (form.containsKey(OAuth2Constants.REFRESH_TOKEN)) {
return logoutToken();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
import org.keycloak.protocol.oidc.refresh.DefaultRefreshTokenProviderFactory;
import org.keycloak.protocol.oidc.refresh.RefreshTokenProvider;
import org.keycloak.protocol.oidc.utils.AuthorizeClientUtil;
import org.keycloak.protocol.oidc.utils.ContentTypeValidationUtil;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.RefreshToken;
import org.keycloak.services.CorsErrorResponseException;
Expand Down Expand Up @@ -87,6 +88,8 @@ public TokenRevocationEndpoint(KeycloakSession session, EventBuilder event) {
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response revoke() {
ContentTypeValidationUtil.requireValidContentType(request.getHttpHeaders(), MediaType.APPLICATION_FORM_URLENCODED_TYPE);

event.event(EventType.REVOKE_GRANT);

cors = Cors.builder().auth().allowedMethods("POST").auth().exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
import org.keycloak.protocol.oidc.grants.ciba.endpoints.request.BackchannelAuthenticationEndpointRequest;
import org.keycloak.protocol.oidc.grants.ciba.endpoints.request.BackchannelAuthenticationEndpointRequestParserProcessor;
import org.keycloak.protocol.oidc.grants.ciba.resolvers.CIBALoginUserResolver;
import org.keycloak.protocol.oidc.utils.ContentTypeValidationUtil;
import org.keycloak.representations.idm.OAuth2ErrorRepresentation;
import org.keycloak.services.ErrorResponseException;
import org.keycloak.services.clientpolicy.ClientPolicyException;
Expand Down Expand Up @@ -83,6 +84,8 @@ public BackchannelAuthenticationEndpoint(KeycloakSession session, EventBuilder e
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response processGrantRequest() {
ContentTypeValidationUtil.requireValidContentType(session.getContext().getHttpRequest().getHttpHeaders(), MediaType.APPLICATION_FORM_URLENCODED_TYPE);

HttpRequest httpRequest = session.getContext().getHttpRequest();
CIBAAuthenticationRequest request = authorizeClient(httpRequest.getDecodedFormParameters());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@

package org.keycloak.protocol.oidc.grants.device.endpoints;

import java.lang.annotation.Annotation;
import java.util.Map;

import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotSupportedException;
import jakarta.ws.rs.OPTIONS;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
Expand Down Expand Up @@ -57,6 +59,7 @@
import org.keycloak.protocol.oidc.grants.device.clientpolicy.context.DeviceAuthorizationRequestContext;
import org.keycloak.protocol.oidc.utils.AuthorizeClientUtil;
import org.keycloak.representations.OAuth2DeviceAuthorizationResponse;
import org.keycloak.representations.idm.OAuth2ErrorRepresentation;
import org.keycloak.saml.common.util.StringUtil;
import org.keycloak.services.ErrorResponseException;
import org.keycloak.services.ServicesLogger;
Expand All @@ -71,6 +74,8 @@
import org.keycloak.util.TokenUtil;

import org.jboss.logging.Logger;
import org.jboss.resteasy.reactive.server.ServerExceptionMapper;
import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;

import static org.keycloak.protocol.oidc.grants.device.DeviceGrantType.OAUTH2_DEVICE_USER_CODE;

Expand All @@ -92,6 +97,23 @@ public DeviceEndpoint(KeycloakSession session, EventBuilder event) {
this.request = session.getContext().getHttpRequest();
}

@ServerExceptionMapper(NotSupportedException.class)
Response handleNotSupportedException() {
// applied on all endpoints in this resource since it should be fine here,
// but intended for the device authorization request in order to match token endpoint request
// per https://datatracker.ietf.org/doc/html/rfc8628#section-3.2
// if you need to narrow this response to only specific endpoint, extract this mapper with 'handleDeviceRequest'
// into a dedicated resource

// FIXME: drop when https://github.com/quarkusio/quarkus/issues/55818 is fixed
CurrentRequestManager.get().setAllAnnotations(new Annotation[]{});

return Response.status(400)
.entity(new OAuth2ErrorRepresentation(OAuthErrorException.INVALID_REQUEST, "Invalid Content-Type header"))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}

/**
* Handles device authorization requests.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import org.keycloak.protocol.oidc.par.ParResponse;
import org.keycloak.protocol.oidc.par.clientpolicy.context.PushedAuthorizationRequestContext;
import org.keycloak.protocol.oidc.par.endpoints.request.ParEndpointRequestParserProcessor;
import org.keycloak.protocol.oidc.utils.ContentTypeValidationUtil;
import org.keycloak.representations.dpop.DPoP;
import org.keycloak.services.clientpolicy.ClientPolicyException;
import org.keycloak.services.cors.Cors;
Expand Down Expand Up @@ -85,6 +86,7 @@ public ParEndpoint(KeycloakSession session, EventBuilder event) {
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response request() {
ContentTypeValidationUtil.requireValidContentType(httpRequest.getHttpHeaders(), MediaType.APPLICATION_FORM_URLENCODED_TYPE);

ProfileHelper.requireFeature(Profile.Feature.PAR);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package org.keycloak.protocol.oidc.utils;

import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

import org.keycloak.events.Errors;
import org.keycloak.services.ErrorResponseException;

public final class ContentTypeValidationUtil {

// FIXME: remove this validation when we use Quarkus with https://github.com/quarkusio/quarkus/pull/55676
public static void requireValidContentType(HttpHeaders headers, MediaType requiredMediaType) {
String contentType = headers.getHeaderString(HttpHeaders.CONTENT_TYPE);
if (contentType == null) {
return;
}
MediaType requestMediaType;
try {
requestMediaType = MediaType.valueOf(contentType);
} catch (IllegalArgumentException e) {
throw new ErrorResponseException(Errors.INVALID_REQUEST, "The content-type header value did not correspond to a valid media type", Response.Status.BAD_REQUEST);
}
if (!requestMediaType.isCompatible(requiredMediaType)) {
throw new ErrorResponseException(Errors.INVALID_REQUEST, "The content-type header value does not match consumed media type " + requiredMediaType, Response.Status.BAD_REQUEST);
Comment thread
michalvavrik marked this conversation as resolved.
}
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
package org.keycloak.tests.oauth;

import java.util.stream.Stream;

import jakarta.ws.rs.core.MediaType;

import org.keycloak.OAuthErrorException;
import org.keycloak.models.OAuth2DeviceConfig;
import org.keycloak.testframework.annotations.InjectRealm;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.testframework.oauth.OAuthClient;
import org.keycloak.testframework.oauth.annotations.InjectOAuthClient;
import org.keycloak.testframework.realm.ClientBuilder;
import org.keycloak.testframework.realm.ClientConfig;
import org.keycloak.testframework.realm.ManagedRealm;
import org.keycloak.testframework.realm.RealmBuilder;
import org.keycloak.testframework.realm.RealmConfig;
import org.keycloak.testframework.realm.UserBuilder;
import org.keycloak.testsuite.util.oauth.AbstractHttpResponse;
import org.keycloak.testsuite.util.oauth.AccessTokenResponse;
import org.keycloak.testsuite.util.oauth.BackchannelLogoutResponse;
import org.keycloak.testsuite.util.oauth.LogoutResponse;
import org.keycloak.testsuite.util.oauth.ParResponse;
import org.keycloak.testsuite.util.oauth.TokenRevocationResponse;
import org.keycloak.testsuite.util.oauth.ciba.AuthenticationRequestAcknowledgement;
import org.keycloak.testsuite.util.oauth.device.DeviceAuthorizationResponse;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import static org.junit.jupiter.api.Assertions.assertEquals;

@KeycloakIntegrationTest
class MalformedContentTypeTest {

@InjectRealm(config = TestRealm.class)
ManagedRealm realm;

@InjectOAuthClient(config = TestClient.class)
OAuthClient oauth;

static Stream<String> malformedContentTypes() {
return Stream.of(
"invalid/@@##",
"</><script>alert(1)</script>",
"text",
"text/[html]",
""
);
}

@ParameterizedTest
@MethodSource("malformedContentTypes")
void tokenEndpoint(String contentType) {
AccessTokenResponse response = oauth.passwordGrantRequest("test-user@localhost", "password")
.header("Content-Type", contentType)
.send();
assertOAuthInvalidRequest(response);
}

@ParameterizedTest
@MethodSource("malformedContentTypes")
void deviceAuthorizationEndpoint(String contentType) {
DeviceAuthorizationResponse response = oauth.device()
.deviceAuthorizationRequest()
.header("Content-Type", contentType)
.send();
assertOAuthInvalidRequest(response);
}

@ParameterizedTest
@MethodSource("malformedContentTypes")
void logoutEndpoint(String contentType) {
AccessTokenResponse tokenResponse = oauth.doPasswordGrantRequest("test-user@localhost", "password");
LogoutResponse response = oauth.logoutRequest()
.refreshToken(tokenResponse.getRefreshToken())
.header("Content-Type", contentType)
.send();
assertOAuthInvalidRequest(response);
}

@ParameterizedTest
@MethodSource("malformedContentTypes")
void tokenRevocationEndpoint(String contentType) {
AccessTokenResponse tokenResponse = oauth.doPasswordGrantRequest("test-user@localhost", "password");
TokenRevocationResponse response = oauth.tokenRevocationRequest(tokenResponse.getAccessToken())
.header("Content-Type", contentType)
.send();
assertOAuthInvalidRequest(response);
}

@ParameterizedTest
@MethodSource("malformedContentTypes")
void backchannelLogoutEndpoint(String contentType) {
AccessTokenResponse tokenResponse = oauth.doPasswordGrantRequest("test-user@localhost", "password");
BackchannelLogoutResponse response = oauth.backchannelLogoutRequest(tokenResponse.getRefreshToken())
.header("Content-Type", contentType)
.send();
assertOAuthInvalidRequest(response);
}

@ParameterizedTest
@MethodSource("malformedContentTypes")
void parEndpoint(String contentType) {
ParResponse response = oauth.pushedAuthorizationRequest()
.header("Content-Type", contentType)
.send();
assertOAuthInvalidRequest(response);
}

@ParameterizedTest
@MethodSource("malformedContentTypes")
void cibaEndpoint(String contentType) {
AuthenticationRequestAcknowledgement response = oauth.ciba()
.backchannelAuthenticationRequest("test-user@localhost")
.header("Content-Type", contentType)
.send();
assertOAuthInvalidRequest(response);
}

@Test
void deviceAuthorizationEndpointIncompatibleType() {
DeviceAuthorizationResponse response = oauth.device()
.deviceAuthorizationRequest()
.header("Content-Type", MediaType.TEXT_HTML)
.send();
assertOAuthInvalidRequest(response);
}

private static void assertOAuthInvalidRequest(AbstractHttpResponse response) {
assertEquals(400, response.getStatusCode());
assertEquals(OAuthErrorException.INVALID_REQUEST, response.getError());
}

public static class TestRealm implements RealmConfig {
@Override
public RealmBuilder configure(RealmBuilder realm) {
return realm.users(UserBuilder.create("test-user@localhost")
.email("test-user@localhost")
.password("password")
.name("first", "last")
.enabled(true));
}
}

public static class TestClient implements ClientConfig {
@Override
public ClientBuilder configure(ClientBuilder client) {
return client.clientId("test-app")
.secret("test-secret")
.directAccessGrantsEnabled(true)
.attribute(OAuth2DeviceConfig.OAUTH2_DEVICE_AUTHORIZATION_GRANT_ENABLED, "true");
}
}
}
Loading