prabhashkr commented on code in PR #21483: URL: https://github.com/apache/kafka/pull/21483#discussion_r2888661556
########## clients/src/test/java/org/apache/kafka/common/security/oauthbearer/internals/secured/assertion/AssertionSupplierFactoryTest.java: ########## @@ -0,0 +1,327 @@ +/* + * 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.kafka.common.security.oauthbearer.internals.secured.assertion; + +import org.apache.kafka.common.security.oauthbearer.JwtRetrieverException; +import org.apache.kafka.common.security.oauthbearer.internals.secured.ConfigurationUtils; +import org.apache.kafka.common.security.oauthbearer.internals.secured.OAuthBearerTest; +import org.apache.kafka.common.utils.MockTime; +import org.apache.kafka.common.utils.Time; + +import org.jose4j.jwt.consumer.JwtConsumer; +import org.jose4j.jwt.consumer.JwtConsumerBuilder; +import org.jose4j.jwt.consumer.JwtContext; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.security.KeyPair; +import java.security.PublicKey; + +import static org.apache.kafka.common.config.SaslConfigs.SASL_OAUTHBEARER_ASSERTION_ALGORITHM; +import static org.apache.kafka.common.config.SaslConfigs.SASL_OAUTHBEARER_ASSERTION_CLAIM_AUD; +import static org.apache.kafka.common.config.SaslConfigs.SASL_OAUTHBEARER_ASSERTION_CLAIM_EXP_SECONDS; +import static org.apache.kafka.common.config.SaslConfigs.SASL_OAUTHBEARER_ASSERTION_CLAIM_ISS; +import static org.apache.kafka.common.config.SaslConfigs.SASL_OAUTHBEARER_ASSERTION_CLAIM_JTI_INCLUDE; +import static org.apache.kafka.common.config.SaslConfigs.SASL_OAUTHBEARER_ASSERTION_CLAIM_NBF_SECONDS; +import static org.apache.kafka.common.config.SaslConfigs.SASL_OAUTHBEARER_ASSERTION_CLAIM_SUB; +import static org.apache.kafka.common.config.SaslConfigs.SASL_OAUTHBEARER_ASSERTION_FILE; +import static org.apache.kafka.common.config.SaslConfigs.SASL_OAUTHBEARER_ASSERTION_PRIVATE_KEY_FILE; +import static org.apache.kafka.common.config.SaslConfigs.SASL_OAUTHBEARER_ASSERTION_PRIVATE_KEY_PASSPHRASE; +import static org.apache.kafka.common.config.SaslConfigs.SASL_OAUTHBEARER_ASSERTION_TEMPLATE_FILE; +import static org.apache.kafka.test.TestUtils.tempFile; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class AssertionSupplierFactoryTest extends OAuthBearerTest { + + /** + * When {@code SASL_OAUTHBEARER_ASSERTION_FILE} is configured, the factory should use file-based + * assertion creation and return the JWT from the file. + */ + @Test + public void testCreateWithAssertionFile() throws Exception { + String expectedJwt = createJwt("test-subject"); + File jwtFile = tempFile(expectedJwt); + + ConfigurationUtils cu = mock(ConfigurationUtils.class); + when(cu.validateString(SASL_OAUTHBEARER_ASSERTION_FILE, false)).thenReturn(jwtFile.getAbsolutePath()); + when(cu.validateFile(SASL_OAUTHBEARER_ASSERTION_FILE)).thenReturn(jwtFile); + + Time time = new MockTime(); + + try (CloseableSupplier<String> supplier = AssertionSupplierFactory.create(cu, time)) { + String assertion = supplier.get(); + assertEquals(expectedJwt, assertion); + } + } + + /** + * When no assertion file is configured, the factory should fall back to locally-generated + * assertions using the private key and signing algorithm. + */ + @Test + public void testCreateWithPrivateKeyFile() throws Exception { + KeyPair keyPair = generateKeyPair(); + File privateKeyFile = generatePrivateKey(keyPair.getPrivate()); + + ConfigurationUtils cu = mockConfigForLocalAssertion(privateKeyFile); + + Time time = new MockTime(); + + try (CloseableSupplier<String> supplier = AssertionSupplierFactory.create(cu, time)) { + String assertion = supplier.get(); + assertNotNull(assertion); + assertValidJwtFormat(assertion); + assertClaims(keyPair.getPublic(), assertion); + } + } + + /** + * When static claims (aud, iss, sub) are configured alongside the private key, + * they should be included in the generated JWT assertion. + */ + @Test + public void testCreateWithPrivateKeyFileAndStaticClaims() throws Exception { + KeyPair keyPair = generateKeyPair(); + File privateKeyFile = generatePrivateKey(keyPair.getPrivate()); + + ConfigurationUtils cu = mockConfigForLocalAssertion(privateKeyFile); + // Override static claims to be present + when(cu.containsKey(SASL_OAUTHBEARER_ASSERTION_CLAIM_AUD)).thenReturn(true); + when(cu.validateString(SASL_OAUTHBEARER_ASSERTION_CLAIM_AUD)).thenReturn("https://auth.example.com"); + when(cu.containsKey(SASL_OAUTHBEARER_ASSERTION_CLAIM_ISS)).thenReturn(true); + when(cu.validateString(SASL_OAUTHBEARER_ASSERTION_CLAIM_ISS)).thenReturn("my-client"); + when(cu.containsKey(SASL_OAUTHBEARER_ASSERTION_CLAIM_SUB)).thenReturn(true); + when(cu.validateString(SASL_OAUTHBEARER_ASSERTION_CLAIM_SUB)).thenReturn("service-account"); + + Time time = new MockTime(); + + try (CloseableSupplier<String> supplier = AssertionSupplierFactory.create(cu, time)) { + String assertion = supplier.get(); + assertNotNull(assertion); + assertValidJwtFormat(assertion); + // Use a consumer that expects the configured audience + assertClaimsWithAudience(keyPair.getPublic(), assertion, "https://auth.example.com"); + } + } + + /** + * When a passphrase is configured, the factory should read it via + * {@code validatePassword} and pass it to the {@code DefaultAssertionCreator}. + * Providing a passphrase for an unencrypted key is an invalid combination and + * should result in a {@code JwtRetrieverException} because the raw key bytes + * cannot be parsed as an {@code EncryptedPrivateKeyInfo} structure. + */ + @Test + public void testCreateWithPassphraseReadsPasswordConfig() throws Exception { + KeyPair keyPair = generateKeyPair(); + File privateKeyFile = generatePrivateKey(keyPair.getPrivate()); + + ConfigurationUtils cu = mockConfigForLocalAssertion(privateKeyFile); + // Enable passphrase config + when(cu.containsKey(SASL_OAUTHBEARER_ASSERTION_PRIVATE_KEY_PASSPHRASE)).thenReturn(true); + when(cu.validatePassword(SASL_OAUTHBEARER_ASSERTION_PRIVATE_KEY_PASSPHRASE)).thenReturn("my-passphrase"); + + Time time = new MockTime(); + + // Providing a passphrase for an unencrypted key triggers an error during key loading + assertThrows(JwtRetrieverException.class, () -> AssertionSupplierFactory.create(cu, time)); + + // Verify that the password config was read from configuration + verify(cu).validatePassword(SASL_OAUTHBEARER_ASSERTION_PRIVATE_KEY_PASSPHRASE); + } + + /** + * When the passphrase config key is absent, the factory should not attempt to read + * a password and should produce a working supplier with the unencrypted private key. + */ + @Test + public void testCreateWithoutPassphraseDoesNotReadPasswordConfig() throws Exception { + KeyPair keyPair = generateKeyPair(); + File privateKeyFile = generatePrivateKey(keyPair.getPrivate()); + + ConfigurationUtils cu = mockConfigForLocalAssertion(privateKeyFile); + // Passphrase not configured (already the default from mockConfigForLocalAssertion) + + Time time = new MockTime(); + + try (CloseableSupplier<String> supplier = AssertionSupplierFactory.create(cu, time)) { + String assertion = supplier.get(); + assertNotNull(assertion); + assertClaims(keyPair.getPublic(), assertion); + } + + // Verify that validatePassword was never called + verify(cu, never()).validatePassword(SASL_OAUTHBEARER_ASSERTION_PRIVATE_KEY_PASSPHRASE); + } + + /** + * The file-based supplier should return the same value on consecutive calls since + * the file contents haven't changed. + */ + @Test + public void testFileBasedSupplierReturnsSameValueOnMultipleCalls() throws Exception { + String expectedJwt = createJwt("repeated-calls"); + File jwtFile = tempFile(expectedJwt); + + ConfigurationUtils cu = mock(ConfigurationUtils.class); + when(cu.validateString(SASL_OAUTHBEARER_ASSERTION_FILE, false)).thenReturn(jwtFile.getAbsolutePath()); + when(cu.validateFile(SASL_OAUTHBEARER_ASSERTION_FILE)).thenReturn(jwtFile); + + Time time = new MockTime(); + + try (CloseableSupplier<String> supplier = AssertionSupplierFactory.create(cu, time)) { + String first = supplier.get(); + String second = supplier.get(); + assertEquals(first, second); + assertEquals(expectedJwt, first); + } + } + + /** + * The locally-generated supplier should produce different assertions on each call + * since timestamps (iat, exp, nbf) are regenerated. + */ + @Test + public void testLocallyGeneratedSupplierProducesConsistentAssertions() throws Exception { + KeyPair keyPair = generateKeyPair(); + File privateKeyFile = generatePrivateKey(keyPair.getPrivate()); + + ConfigurationUtils cu = mockConfigForLocalAssertion(privateKeyFile); + Time time = new MockTime(); + + try (CloseableSupplier<String> supplier = AssertionSupplierFactory.create(cu, time)) { + String first = supplier.get(); + String second = supplier.get(); + assertNotNull(first); + assertNotNull(second); + // Both should be valid JWTs + assertClaims(keyPair.getPublic(), first); + assertClaims(keyPair.getPublic(), second); + } + } + + /** + * When the underlying file is deleted after factory creation, calling get() should + * throw a JwtRetrieverException since the assertion creator cannot read the file. + */ + @Test + public void testSupplierGetWrapsExceptionInJwtRetrieverException() throws Exception { + String jwt = createJwt("will-be-deleted"); + File jwtFile = tempFile(jwt); + + ConfigurationUtils cu = mock(ConfigurationUtils.class); + when(cu.validateString(SASL_OAUTHBEARER_ASSERTION_FILE, false)).thenReturn(jwtFile.getAbsolutePath()); + when(cu.validateFile(SASL_OAUTHBEARER_ASSERTION_FILE)).thenReturn(jwtFile); + + Time time = new MockTime(); + + try (CloseableSupplier<String> supplier = AssertionSupplierFactory.create(cu, time)) { + // Delete the file so the read will fail + assertTrue(jwtFile.delete()); + assertThrows(JwtRetrieverException.class, supplier::get); + } + } + + /** + * Closing the supplier should not throw any exceptions. + */ + @Test + public void testSupplierCloseDoesNotThrow() throws Exception { + String expectedJwt = createJwt("close-test"); + File jwtFile = tempFile(expectedJwt); + + ConfigurationUtils cu = mock(ConfigurationUtils.class); + when(cu.validateString(SASL_OAUTHBEARER_ASSERTION_FILE, false)).thenReturn(jwtFile.getAbsolutePath()); + when(cu.validateFile(SASL_OAUTHBEARER_ASSERTION_FILE)).thenReturn(jwtFile); + + Time time = new MockTime(); + + CloseableSupplier<String> supplier = AssertionSupplierFactory.create(cu, time); + // Verify close does not throw + assertDoesNotThrow(supplier::close); Review Comment: AssertionSupplier.close() delegates to Utils.closeQuietly() for both the creator and template, which swallows any exceptions by design. The test here verifies the public contract, that calling close() on the supplier doesn't propagate exceptions. Creating a custom throwing Closeable would effectively test Utils.closeQuietly() itself. Happy to add it if you feel strongly, though. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
