[java-oidc-common] 02/03: New to verify the encryption parameters of an incoming encrypted JWT.
Henri Mikkonen
henri.mikkonen at iki.fi
Tue Mar 28 13:37:25 UTC 2023
This is an automated email from the git hooks/post-receive script.
hjmikkon pushed a commit to branch main
in repository java-oidc-common.
View the commit online:
http://git.shibboleth.net/view/?p=java-oidc-common.git;a=commit;h=88707caf2f63c05da8ccb0bc49063a24f16007c7
commit 88707caf2f63c05da8ccb0bc49063a24f16007c7
Author: Henri Mikkonen <henri.mikkonen at iki.fi>
AuthorDate: Tue Mar 28 16:33:39 2023 +0300
New to verify the encryption parameters of an incoming encrypted JWT.
The action is usable at least by OP to verify the incoming request
object encryption setup.
---
.../CheckClientJWTDecryptionConfiguration.java | 239 +++++++++++++++++++++
.../CheckClientJWTDecryptionConfigurationTest.java | 186 ++++++++++++++++
2 files changed, 425 insertions(+)
diff --git a/oidc-common-crypto-impl/src/main/java/net/shibboleth/oidc/security/impl/CheckClientJWTDecryptionConfiguration.java b/oidc-common-crypto-impl/src/main/java/net/shibboleth/oidc/security/impl/CheckClientJWTDecryptionConfiguration.java
new file mode 100644
index 0000000..3f1e0bd
--- /dev/null
+++ b/oidc-common-crypto-impl/src/main/java/net/shibboleth/oidc/security/impl/CheckClientJWTDecryptionConfiguration.java
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the University Corporation for Advanced Internet Development,
+ * Inc. (UCAID) under one or more contributor license agreements. See the
+ * NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The UCAID 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 net.shibboleth.oidc.security.impl;
+
+import java.util.function.Function;
+import java.util.function.Predicate;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.opensaml.profile.action.ActionSupport;
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.nimbusds.jose.JWEHeader;
+import com.nimbusds.jwt.EncryptedJWT;
+import com.nimbusds.jwt.JWT;
+import com.nimbusds.openid.connect.sdk.rp.OIDCClientInformation;
+
+import net.shibboleth.idp.profile.AbstractProfileAction;
+import net.shibboleth.utilities.java.support.annotation.constraint.NonnullAfterInit;
+import net.shibboleth.utilities.java.support.component.ComponentInitializationException;
+import net.shibboleth.utilities.java.support.component.ComponentSupport;
+import net.shibboleth.utilities.java.support.logic.Constraint;
+import net.shibboleth.utilities.java.support.primitive.StringSupport;
+
+/**
+ * An action that uses a {@link OIDCClientInformation} to verify the encryption parameters of an incoming encrypted JWT
+ * are compliant with configuration in the client metadata.
+ */
+public class CheckClientJWTDecryptionConfiguration extends AbstractProfileAction {
+
+ /** Logger. */
+ @Nonnull private final Logger log = LoggerFactory.getLogger(CheckClientJWTDecryptionConfiguration.class);
+
+ /** Function that looks up an encrypted JWT token from the given profile context to validate .*/
+ @NonnullAfterInit private Function<ProfileRequestContext, JWT> jwtTokenLookupStrategy;
+
+ /** Predicate to determine how to proceed if JWT token was not encrypted. */
+ @NonnullAfterInit private Predicate<ProfileRequestContext> encryptionOptionalPredicate;
+
+ /** Function that looks up client information from the given profile context. */
+ @NonnullAfterInit private Function<ProfileRequestContext, OIDCClientInformation> clientInformationLookupStrategy;
+
+ /** A lookup function for the data encryption algorithm in the client metadata. */
+ @NonnullAfterInit private Function<OIDCClientInformation, String> dataEncryptionAlgorithmLookupStrategy;
+
+ /** A lookup function for the key transport algorithm in the client metadata. */
+ @NonnullAfterInit private Function<OIDCClientInformation, String> keyTransportEncryptionAlgorithmLookupStrategy;
+
+ /** Event identifier to publish if token parameters are not compliant with the configuration. */
+ @NonnullAfterInit private String errorEventId;
+
+ /** The extracted encrypted JWT that is to be processed. */
+ @Nullable private EncryptedJWT encryptedJwt;
+
+ /** Whether encryption is optional. */
+ private boolean encryptionOptional;
+
+ /**
+ * Set the strategy used to look up a {@link JWT}.
+ *
+ * @param strategy lookup strategy
+ */
+ public void setJwtTokenLookupStrategy(
+ @Nonnull final Function<ProfileRequestContext, JWT> strategy) {
+ ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this);
+
+ jwtTokenLookupStrategy = Constraint.isNotNull(strategy, "JwtToken lookup strategy cannot be null");
+ }
+
+ /**
+ * Set the lookup strategy to locate the client information.
+ *
+ * @param strategy the strategy.
+ */
+ public void setClientInformationLookupStrategy(
+ @Nonnull final Function<ProfileRequestContext, OIDCClientInformation> strategy) {
+ ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this);
+
+ clientInformationLookupStrategy =
+ Constraint.isNotNull(strategy, "Client information lookup strategy can not be null");
+ }
+
+ /**
+ * Set the strategy used to look up the data encryption algorithm in the client metadata.
+ *
+ * @param strategy lookup strategy
+ */
+ public void setDataEncryptionAlgorithmLookupStrategy(
+ @Nonnull final Function<OIDCClientInformation, String> strategy) {
+ ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this);
+
+ dataEncryptionAlgorithmLookupStrategy = Constraint.isNotNull(strategy,
+ "Data encryption algorithm lookup strategy cannot be null");
+ }
+
+ /**
+ * Set the strategy used to look up the data encryption algorithm in the client metadata.
+ *
+ * @param strategy lookup strategy
+ */
+ public void setKeyTransportEncryptionAlgorithmLookupStrategy(
+ @Nonnull final Function<OIDCClientInformation, String> strategy) {
+ ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this);
+
+ keyTransportEncryptionAlgorithmLookupStrategy = Constraint.isNotNull(strategy,
+ "Key transport encryption algorithm lookup strategy cannot be null");
+ }
+
+ /**
+ * Sets the condition to apply to determine how to proceed if encryption parameter resolution fails.
+ *
+ * @param condition condition to set
+ */
+ public void setEncryptionOptionalPredicate(@Nonnull final Predicate<ProfileRequestContext> condition) {
+ ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this);
+
+ encryptionOptionalPredicate = Constraint.isNotNull(condition, "Condition cannot be null");
+ }
+
+ /**
+ * Sets the event identifier to publish if token parameters are not compliant with the configuration.
+ *
+ * @param id the identifier to set
+ */
+ public void setErrorEventId(@Nonnull final String id) {
+ ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this);
+
+ errorEventId = Constraint.isNotEmpty(id, "Error event identifier cannot be empty");
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected void doInitialize() throws ComponentInitializationException {
+ super.doInitialize();
+
+ if (jwtTokenLookupStrategy == null) {
+ throw new ComponentInitializationException("JwtTokenLookupStrategy cannot be null");
+ }
+ if (dataEncryptionAlgorithmLookupStrategy == null) {
+ throw new ComponentInitializationException("DataEncryptionAlgorithmLookupStrategy cannot be null");
+ }
+ if (keyTransportEncryptionAlgorithmLookupStrategy == null) {
+ throw new ComponentInitializationException("KeyTransportEncryptionAlgorithmLookupStrategy cannot be null");
+ }
+ if (clientInformationLookupStrategy == null) {
+ throw new ComponentInitializationException("ClientInformationLookupStrategy cannot be null");
+ }
+ if (encryptionOptionalPredicate == null) {
+ throw new ComponentInitializationException("EncryptionOptionalPredicate cannot be null");
+ }
+ if (StringSupport.trimOrNull(errorEventId) == null) {
+ throw new ComponentInitializationException("ErrorEventId cannot be empty");
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected boolean doPreExecute(final ProfileRequestContext profileRequestContext) {
+ if (!super.doPreExecute(profileRequestContext)) {
+ return false;
+ }
+
+ encryptionOptional = encryptionOptionalPredicate.test(profileRequestContext);
+
+ final JWT jwt = jwtTokenLookupStrategy.apply(profileRequestContext);
+ if (jwt == null || !(jwt instanceof EncryptedJWT)) {
+ if (encryptionOptional) {
+ log.debug("{} Extracted JWT was not an EncryptedJWT, but encryption is set to optional",
+ getLogPrefix());
+ return false;
+ } else {
+ log.debug("{} Extracted JWT was not an EncryptedJWT and encryption is not optional, cannot proceed",
+ getLogPrefix());
+ ActionSupport.buildEvent(profileRequestContext, errorEventId);
+ return false;
+ }
+ }
+
+ encryptedJwt = (EncryptedJWT) jwt;
+ return true;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected void doExecute(final ProfileRequestContext profileRequestContext) {
+ final JWEHeader jweHeader = encryptedJwt.getHeader();
+ final OIDCClientInformation clientInformation = clientInformationLookupStrategy.apply(profileRequestContext);
+
+ final String tokenJweAlgorithm = jweHeader.getAlgorithm().getName();
+ final String expectedJweAlgorithm = clientInformation == null ?
+ null : dataEncryptionAlgorithmLookupStrategy.apply(clientInformation);
+
+ if (StringSupport.trimOrNull(expectedJweAlgorithm) == null) {
+ log.debug("{} No expected algorithm defined, accepting {} from the token", getLogPrefix(),
+ tokenJweAlgorithm);
+ } else if (tokenJweAlgorithm.equals(expectedJweAlgorithm)) {
+ log.debug("{} The algorithm specified in the token was expected {}", getLogPrefix(), tokenJweAlgorithm);
+ } else {
+ log.warn("{} The algorithnm specified in the token {} was not expected {}", getLogPrefix(),
+ tokenJweAlgorithm, expectedJweAlgorithm);
+ ActionSupport.buildEvent(profileRequestContext, errorEventId);
+ return;
+ }
+
+ final String tokenEncryptionMethod = jweHeader.getEncryptionMethod().getName();
+ final String expectedEncryptionMethod = clientInformation == null ?
+ null : keyTransportEncryptionAlgorithmLookupStrategy.apply(clientInformation);
+
+ if (StringSupport.trimOrNull(expectedEncryptionMethod) == null) {
+ log.debug("{} No expected encryption method defined, accepting {} from the token", getLogPrefix(),
+ tokenEncryptionMethod);
+ } else if (tokenEncryptionMethod.equals(expectedEncryptionMethod)) {
+ log.debug("{} The encryption method specified in the token was expected {}", getLogPrefix(),
+ tokenEncryptionMethod);
+ } else {
+ log.warn("{} The encryption method specified in the token {} was not expected {}", getLogPrefix(),
+ tokenEncryptionMethod, expectedEncryptionMethod);
+ ActionSupport.buildEvent(profileRequestContext, errorEventId);
+ }
+ }
+}
diff --git a/oidc-common-crypto-impl/src/test/java/net/shibboleth/oidc/security/impl/CheckClientJWTDecryptionConfigurationTest.java b/oidc-common-crypto-impl/src/test/java/net/shibboleth/oidc/security/impl/CheckClientJWTDecryptionConfigurationTest.java
new file mode 100644
index 0000000..579a782
--- /dev/null
+++ b/oidc-common-crypto-impl/src/test/java/net/shibboleth/oidc/security/impl/CheckClientJWTDecryptionConfigurationTest.java
@@ -0,0 +1,186 @@
+/*
+ * Licensed to the University Corporation for Advanced Internet Development,
+ * Inc. (UCAID) under one or more contributor license agreements. See the
+ * NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The UCAID 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 net.shibboleth.oidc.security.impl;
+
+import org.mockito.Mockito;
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.springframework.webflow.execution.RequestContext;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import com.nimbusds.jose.EncryptionMethod;
+import com.nimbusds.jose.JWEAlgorithm;
+import com.nimbusds.jose.JWEHeader;
+import com.nimbusds.jwt.EncryptedJWT;
+import com.nimbusds.jwt.JWT;
+import com.nimbusds.oauth2.sdk.id.ClientID;
+import com.nimbusds.openid.connect.sdk.rp.OIDCClientInformation;
+import com.nimbusds.openid.connect.sdk.rp.OIDCClientMetadata;
+
+import net.shibboleth.idp.profile.testing.ActionTestingSupport;
+import net.shibboleth.idp.profile.testing.RequestContextBuilder;
+import net.shibboleth.utilities.java.support.component.ComponentInitializationException;
+
+/**
+ * Unit tests for {@link CheckClientJWTDecryptionConfiguration}.
+ */
+public class CheckClientJWTDecryptionConfigurationTest {
+
+ protected CheckClientJWTDecryptionConfiguration action;
+
+ protected OIDCClientInformation clientInformation = new OIDCClientInformation(new ClientID("mockId"),
+ new OIDCClientMetadata());
+
+ protected String eventId = "mockErrorEventId";
+
+ protected void setup(final JWT jwt, final boolean encryptionOptional, final String dataEncryptionAlg,
+ final String keyTransportEncryptionAlg) {
+ try {
+ action = new CheckClientJWTDecryptionConfiguration();
+ action.setJwtTokenLookupStrategy(prc -> jwt);
+ action.setDataEncryptionAlgorithmLookupStrategy(metadata -> dataEncryptionAlg);
+ action.setKeyTransportEncryptionAlgorithmLookupStrategy(metadata -> keyTransportEncryptionAlg);
+ action.setClientInformationLookupStrategy(prc -> clientInformation);
+ action.setEncryptionOptionalPredicate(prc -> encryptionOptional);
+ action.setErrorEventId(eventId);
+ action.initialize();
+ } catch (final ComponentInitializationException e) {
+ Assert.fail("Object initialization failed", e);
+ }
+ }
+
+ @Test(expectedExceptions = ComponentInitializationException.class)
+ public void init_noJwtTokenLookupStrategy() throws ComponentInitializationException {
+ action = new CheckClientJWTDecryptionConfiguration();
+ action.setDataEncryptionAlgorithmLookupStrategy(metadata -> "dataEncAlgId");
+ action.setKeyTransportEncryptionAlgorithmLookupStrategy(metadata -> "keyEncAlgId");
+ action.setClientInformationLookupStrategy(prc -> clientInformation);
+ action.setEncryptionOptionalPredicate(prc -> true);
+ action.setErrorEventId(eventId);
+ action.initialize();
+ }
+
+ @Test(expectedExceptions = ComponentInitializationException.class)
+ public void init_noDataEncryptionAlgorithmLookupStrategy() throws ComponentInitializationException {
+ action = new CheckClientJWTDecryptionConfiguration();
+ action.setJwtTokenLookupStrategy(prc -> Mockito.mock(JWT.class));
+ action.setKeyTransportEncryptionAlgorithmLookupStrategy(metadata -> "keyEncAlgId");
+ action.setClientInformationLookupStrategy(prc -> clientInformation);
+ action.setEncryptionOptionalPredicate(prc -> true);
+ action.setErrorEventId(eventId);
+ action.initialize();
+ }
+
+ @Test(expectedExceptions = ComponentInitializationException.class)
+ public void init_noKeyTransportEncryptionAlgorithmLookupStrategy() throws ComponentInitializationException {
+ action = new CheckClientJWTDecryptionConfiguration();
+ action.setJwtTokenLookupStrategy(prc -> Mockito.mock(JWT.class));
+ action.setDataEncryptionAlgorithmLookupStrategy(metadata -> "dataEncAlgId");
+ action.setClientInformationLookupStrategy(prc -> clientInformation);
+ action.setEncryptionOptionalPredicate(prc -> true);
+ action.setErrorEventId(eventId);
+ action.initialize();
+ }
+
+ @Test(expectedExceptions = ComponentInitializationException.class)
+ public void init_noClientInformationLookupStrategy() throws ComponentInitializationException {
+ action = new CheckClientJWTDecryptionConfiguration();
+ action.setJwtTokenLookupStrategy(prc -> Mockito.mock(JWT.class));
+ action.setDataEncryptionAlgorithmLookupStrategy(metadata -> "dataEncAlgId");
+ action.setKeyTransportEncryptionAlgorithmLookupStrategy(metadata -> "keyEncAlgId");
+ action.setEncryptionOptionalPredicate(prc -> true);
+ action.setErrorEventId(eventId);
+ action.initialize();
+ }
+
+ @Test(expectedExceptions = ComponentInitializationException.class)
+ public void init_noEncryptionOptionalPredicate() throws ComponentInitializationException {
+ action = new CheckClientJWTDecryptionConfiguration();
+ action.setJwtTokenLookupStrategy(prc -> Mockito.mock(JWT.class));
+ action.setDataEncryptionAlgorithmLookupStrategy(metadata -> "dataEncAlgId");
+ action.setKeyTransportEncryptionAlgorithmLookupStrategy(metadata -> "keyEncAlgId");
+ action.setClientInformationLookupStrategy(prc -> clientInformation);
+ action.setErrorEventId(eventId);
+ action.initialize();
+ }
+
+ @Test(expectedExceptions = ComponentInitializationException.class)
+ public void init_noErrorEventId() throws ComponentInitializationException {
+ action = new CheckClientJWTDecryptionConfiguration();
+ action.setJwtTokenLookupStrategy(prc -> Mockito.mock(JWT.class));
+ action.setDataEncryptionAlgorithmLookupStrategy(metadata -> "dataEncAlgId");
+ action.setKeyTransportEncryptionAlgorithmLookupStrategy(metadata -> "keyEncAlgId");
+ action.setClientInformationLookupStrategy(prc -> clientInformation);
+ action.setEncryptionOptionalPredicate(prc -> true);
+ action.initialize();
+ }
+
+ @Test
+ public void doPreExecute_noEncryptedJwtEncryptionOptional_returnsFalseNoEvent()
+ throws ComponentInitializationException {
+ final RequestContext src = new RequestContextBuilder().buildRequestContext();
+
+ setup(Mockito.mock(JWT.class), true, "dataAlgId", "keyTransportAlgId");
+ Assert.assertFalse(action.doPreExecute(new ProfileRequestContext()));
+ ActionTestingSupport.assertProceedEvent(action.execute(src));
+ }
+
+ @Test
+ public void doPreExecute_noEncryptedJwtEncryptionOptional_returnsFalseWithEvent()
+ throws ComponentInitializationException {
+ final RequestContext src = new RequestContextBuilder().buildRequestContext();
+
+ setup(Mockito.mock(JWT.class), false, "dataAlgId", "keyTransportAlgId");
+ Assert.assertFalse(action.doPreExecute(new ProfileRequestContext()));
+ ActionTestingSupport.assertEvent(action.execute(src), eventId);
+ }
+
+ @Test
+ public void execute_noDataAlgNorKeyTransportAlg_returnsProceed() throws ComponentInitializationException {
+ setup(mockEncryptedJWT(), true, null, null);
+ ActionTestingSupport.assertProceedEvent(action.execute(new RequestContextBuilder().buildRequestContext()));
+ }
+
+ @Test
+ public void execute_noDataAlgMatch_returnsError() throws ComponentInitializationException {
+ setup(mockEncryptedJWT(), true, "mockDataAlgNOT", null);
+ ActionTestingSupport.assertEvent(action.execute(new RequestContextBuilder().buildRequestContext()),
+ eventId);
+ }
+
+ @Test
+ public void execute_noKeyTransportAlgMatch_returnsError() throws ComponentInitializationException {
+ setup(mockEncryptedJWT(), true, null, "mockKeyAlgNOT");
+ ActionTestingSupport.assertEvent(action.execute(new RequestContextBuilder().buildRequestContext()),
+ eventId);
+ }
+
+
+ @Test
+ public void execute_bothDataAlgAndKeyTransportAlgMatch_returnsProceed() throws ComponentInitializationException {
+ setup(mockEncryptedJWT(), true, "mockDataAlgId", "mockKeyAlgId");
+ ActionTestingSupport.assertProceedEvent(action.execute(new RequestContextBuilder().buildRequestContext()));
+ }
+
+ protected EncryptedJWT mockEncryptedJWT() {
+ EncryptedJWT jwt = Mockito.mock(EncryptedJWT.class);
+ Mockito.when(jwt.getHeader()).thenReturn(new JWEHeader(JWEAlgorithm.parse("mockDataAlgId"),
+ EncryptionMethod.parse("mockKeyAlgId")));
+ return jwt;
+ }
+}
--
To stop receiving notification emails like this one, please contact
the administrator of this repository.
More information about the commits
mailing list