diff --git a/components/security-mgt/org.wso2.carbon.security.mgt/src/main/java/org/wso2/carbon/security/keystore/KeyStoreAdmin.java b/components/security-mgt/org.wso2.carbon.security.mgt/src/main/java/org/wso2/carbon/security/keystore/KeyStoreAdmin.java index 6efdc8309e04..95d5a53e6bc5 100644 --- a/components/security-mgt/org.wso2.carbon.security.mgt/src/main/java/org/wso2/carbon/security/keystore/KeyStoreAdmin.java +++ b/components/security-mgt/org.wso2.carbon.security.mgt/src/main/java/org/wso2/carbon/security/keystore/KeyStoreAdmin.java @@ -26,15 +26,11 @@ import org.wso2.carbon.CarbonException; import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.core.RegistryResources; -import org.wso2.carbon.core.util.CryptoUtil; +import org.wso2.carbon.core.security.KeyStoreMetadata; import org.wso2.carbon.core.util.KeyStoreManager; import org.wso2.carbon.core.util.KeyStoreUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.registry.core.Association; -import org.wso2.carbon.registry.core.Collection; import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.Resource; -import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.security.SecurityConfigException; import org.wso2.carbon.security.SecurityConstants; import org.wso2.carbon.security.keystore.service.CertData; @@ -63,20 +59,16 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Enumeration; -import java.util.Iterator; import java.util.List; public class KeyStoreAdmin { private static final Log log = LogFactory.getLog(KeyStoreAdmin.class); - private Registry registry = null; private final KeyStoreManager keyStoreManager; private boolean includeCert = false; - public KeyStoreAdmin(int tenantId, Registry registry) { - this.registry = registry; keyStoreManager = KeyStoreManager.getInstance(tenantId); } @@ -89,93 +81,41 @@ public void setIncludeCert(boolean includeCert) { } /** - * Method to retrive keystore data. + * Method to retrieve keystore data. * - * @param isSuperTenant - Indication whether the querying super tennat data - * @return - * @throws SecurityConfigException + * @param isSuperTenant - Indication whether the querying super tenant data. + * @return Array of KeyStoreData objects. + * @throws SecurityConfigException If an error occurs while retrieving keystore data. */ public KeyStoreData[] getKeyStores(boolean isSuperTenant) throws SecurityConfigException { + CarbonUtils.checkSecurity(); - KeyStoreData[] names = new KeyStoreData[0]; + List keyStoreDataList = new ArrayList<>(); try { - if (registry.resourceExists(SecurityConstants.KEY_STORES)) { - Collection collection = (Collection) registry.get(SecurityConstants.KEY_STORES); - String[] ks = collection.getChildren(); - List lst = new ArrayList<>(); - for (int i = 0; i < ks.length; i++) { - String fullname = ks[i]; - - if (RegistryResources.SecurityManagement.PRIMARY_KEYSTORE_PHANTOM_RESOURCE - .equals(fullname)) { - continue; - } - - Resource store = registry.get(ks[i]); - int lastIndex = fullname.lastIndexOf("/"); - String name = fullname.substring(lastIndex + 1); - String type = store.getProperty(SecurityConstants.PROP_TYPE); - String provider = store.getProperty(SecurityConstants.PROP_PROVIDER); - - KeyStoreData data = new KeyStoreData(); - data.setKeyStoreName(name); - data.setKeyStoreType(type); - data.setProvider(provider); - - String alias = store.getProperty(SecurityConstants.PROP_PRIVATE_KEY_ALIAS); - if (alias != null) { - data.setPrivateStore(true); - } else { - data.setPrivateStore(false); - } - - // Dump the generated public key to the file system for sub tenants - if (!isSuperTenant) { - Association[] associations = registry.getAssociations( - ks[i], SecurityConstants.ASSOCIATION_TENANT_KS_PUB_KEY); - if (associations != null && associations.length > 0) { - Resource pubKeyResource = registry.get(associations[0].getDestinationPath()); - String fileName = generatePubCertFileName(ks[i], - pubKeyResource.getProperty( - SecurityConstants.PROP_TENANT_PUB_KEY_FILE_NAME_APPENDER)); - if (MessageContext.getCurrentMessageContext() != null) { - String pubKeyFilePath = KeyStoreMgtUtil.dumpCert( - MessageContext.getCurrentMessageContext().getConfigurationContext(), - (byte[]) pubKeyResource.getContent(), fileName); - data.setPubKeyFilePath(pubKeyFilePath); - } - } - } - lst.add(data); - - } - names = new KeyStoreData[lst.size() + 1]; - Iterator ite = lst.iterator(); - int count = 0; - while (ite.hasNext()) { - names[count] = ite.next(); - count++; - } - - if (isSuperTenant) { - KeyStoreData data = new KeyStoreData(); - ServerConfiguration config = ServerConfiguration.getInstance(); - String fileName = config - .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_FILE); - String type = config - .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE); - String name = KeyStoreUtil.getKeyStoreFileName(fileName); - data.setKeyStoreName(name); - data.setKeyStoreType(type); - data.setProvider(" "); - data.setPrivateStore(true); - - names[count] = data; + KeyStoreMetadata[] keyStoreMetadataArray = keyStoreManager.getKeyStoresMetadata(isSuperTenant); + for (KeyStoreMetadata keyStoreMetadata : keyStoreMetadataArray) { + KeyStoreData keyStoreData = new KeyStoreData(); + keyStoreData.setKeyStoreName(keyStoreMetadata.getKeyStoreName()); + keyStoreData.setKeyStoreType(keyStoreMetadata.getKeyStoreType()); + keyStoreData.setProvider(keyStoreMetadata.getProvider()); + keyStoreData.setPrivateStore(keyStoreMetadata.isPrivateStore()); + + // Dump the generated public key to the file system for sub tenants. + if (!isSuperTenant && keyStoreMetadata.getPublicCert() != null + && StringUtils.isNotBlank(keyStoreMetadata.getPublicCertId()) + && MessageContext.getCurrentMessageContext() != null) { + + String fileName = generatePubCertFileName(keyStoreMetadata.getKeyStoreName(), + keyStoreMetadata.getPublicCertId()); + String pubKeyFilePath = KeyStoreMgtUtil.dumpCert( + MessageContext.getCurrentMessageContext().getConfigurationContext(), + keyStoreMetadata.getPublicCert(), fileName); + keyStoreData.setPubKeyFilePath(pubKeyFilePath); } - + keyStoreDataList.add(keyStoreData); } - return names; - } catch (RegistryException e) { + return keyStoreDataList.toArray(new KeyStoreData[0]); + } catch (SecurityException e) { String msg = "Error when getting keyStore data"; log.error(msg, e); throw new SecurityConfigException(msg, e); @@ -383,34 +323,18 @@ public KeyStoreData getKeystoreInfo(String keyStoreName) throws SecurityConfigEx KeyStore keyStore; String keyStoreType; - String privateKeyPassword = null; ServerConfiguration serverConfig = ServerConfiguration.getInstance(); if (KeyStoreUtil.isPrimaryStore(keyStoreName)) { keyStore = this.keyStoreManager.getPrimaryKeyStore(); keyStoreType = serverConfig.getFirstProperty( RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE); - privateKeyPassword = serverConfig.getFirstProperty( - RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD); } else if (KeyStoreUtil.isTrustStore(keyStoreName)) { keyStore = this.keyStoreManager.getTrustStore(); keyStoreType = serverConfig.getFirstProperty( RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_TYPE); - privateKeyPassword = serverConfig.getFirstProperty( - RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_PASSWORD); } else { - String path = SecurityConstants.KEY_STORES + "/" + keyStoreName; - if (!registry.resourceExists(path)) { - throw new SecurityConfigException("Key Store not found"); - } - Resource resource = registry.get(path); keyStore = this.keyStoreManager.getKeyStore(keyStoreName); - keyStoreType = resource.getProperty(SecurityConstants.PROP_TYPE); - - String encpass = resource.getProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS); - if (encpass != null) { - CryptoUtil util = CryptoUtil.getDefaultCryptoUtil(); - privateKeyPassword = new String(util.base64DecodeAndDecrypt(encpass)); - } + keyStoreType = keyStore.getType(); } // Fill the information about the certificates Enumeration aliases = keyStore.aliases(); @@ -441,8 +365,7 @@ public KeyStoreData getKeystoreInfo(String keyStoreName) throws SecurityConfigEx if (keyStore.isKeyEntry(alias)) { X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); keyStoreData.setKey(fillCertData(cert, alias, formatter)); - PrivateKey key = (PrivateKey) keyStore.getKey(alias, privateKeyPassword - .toCharArray()); + PrivateKey key = (PrivateKey) this.keyStoreManager.getPrivateKey(keyStoreName, alias); String pemKey; pemKey = "-----BEGIN PRIVATE KEY-----\n"; pemKey += Base64.encode(key.getEncoded()); @@ -459,7 +382,6 @@ public KeyStoreData getKeystoreInfo(String keyStoreName) throws SecurityConfigEx log.error(msg, e); throw new SecurityConfigException(msg); } - } public Key getPrivateKey(String alias, boolean isSuperTenant) throws SecurityConfigException { @@ -538,21 +460,21 @@ private byte[] readBytesFromFile(String filePath) throws IOException { } /** - * This method is used to generate the file name of the pub. cert of a tenant + * This method is used to generate the file name of the public cert of a tenant. * - * @param ksLocation keystore location in the registry - * @param uuid UUID appender - * @return file name of the pub. cert + * @param keyStoreName Keystore Name. + * @param uuid UUID appender. + * @return file name of the public cert. */ - private String generatePubCertFileName(String ksLocation, String uuid) { - String tenantName = ksLocation.substring(ksLocation.lastIndexOf("/")); + private String generatePubCertFileName(String keyStoreName, String uuid) { + for (KeystoreUtils.StoreFileType fileType: KeystoreUtils.StoreFileType.values()) { String fileExtension = KeystoreUtils.StoreFileType.getExtension(fileType); - if (tenantName.endsWith(fileExtension)) { - tenantName = tenantName.replace(fileExtension, ""); + if (keyStoreName.endsWith(fileExtension)) { + keyStoreName = keyStoreName.replace(fileExtension, ""); } } - return tenantName + "-" + uuid + ".cert"; + return keyStoreName + "-" + uuid + ".cert"; } /** @@ -636,7 +558,7 @@ public PaginatedKeyStoreData getPaginatedKeystoreInfo(String keyStoreName, int p // Get keystore. KeyStore keyStore = this.keyStoreManager.getKeyStore(keyStoreName); // Get keystore type. - String keyStoreType = getKeyStoreType(keyStoreName); + String keyStoreType = keyStore.getType(); // Extract certificates from aliases as list. List certDataList = getCertificates(keyStore); @@ -684,7 +606,7 @@ public PaginatedKeyStoreData getFilteredPaginatedKeyStoreInfo(String keyStoreNam // Get keystore. KeyStore keyStore = this.keyStoreManager.getKeyStore(keyStoreName); // Get keystore type. - String keyStoreType = getKeyStoreType(keyStoreName); + String keyStoreType = keyStore.getType(); // Extract certificates from aliases as list. List certDataList = getCertificates(keyStore); @@ -702,34 +624,6 @@ public PaginatedKeyStoreData getFilteredPaginatedKeyStoreInfo(String keyStoreNam } } - /** - * Get keystore type. - * - * @param keyStoreName Keystore name. - * @return - * @throws SecurityConfigException - * @throws RegistryException - */ - private String getKeyStoreType(String keyStoreName) throws SecurityConfigException, RegistryException { - - String keyStoreType; - ServerConfiguration serverConfig = ServerConfiguration.getInstance(); - if (KeyStoreUtil.isPrimaryStore(keyStoreName)) { - keyStoreType = serverConfig - .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE); - } else if (KeyStoreUtil.isTrustStore(keyStoreName)) { - keyStoreType = serverConfig.getFirstProperty(RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_TYPE); - } else { - String path = SecurityConstants.KEY_STORES + "/" + keyStoreName; - if (!registry.resourceExists(path)) { - throw new SecurityConfigException("Keystore " + keyStoreName + " not found at " + path); - } - Resource resource = registry.get(path); - keyStoreType = resource.getProperty(SecurityConstants.PROP_TYPE); - } - return keyStoreType; - } - /** * Fill PaginatedKeyStoreData with keystore details. * diff --git a/components/security-mgt/org.wso2.carbon.security.mgt/src/test/java/org/wso2/carbon/security/keystore/KeyStoreAdminTest.java b/components/security-mgt/org.wso2.carbon.security.mgt/src/test/java/org/wso2/carbon/security/keystore/KeyStoreAdminTest.java index 7b81cb1ec9a2..ee0594949502 100644 --- a/components/security-mgt/org.wso2.carbon.security.mgt/src/test/java/org/wso2/carbon/security/keystore/KeyStoreAdminTest.java +++ b/components/security-mgt/org.wso2.carbon.security.mgt/src/test/java/org/wso2/carbon/security/keystore/KeyStoreAdminTest.java @@ -18,36 +18,43 @@ package org.wso2.carbon.security.keystore; +import org.apache.geronimo.mail.util.Base64; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.testng.MockitoTestNGListener; import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import org.wso2.carbon.CarbonException; import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.base.ServerConfiguration; -import org.wso2.carbon.core.RegistryResources; +import org.wso2.carbon.core.security.KeyStoreMetadata; import org.wso2.carbon.core.util.CryptoUtil; import org.wso2.carbon.core.util.KeyStoreManager; import org.wso2.carbon.core.util.KeyStoreUtil; import org.wso2.carbon.identity.testutil.IdentityBaseTest; -import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.security.SecurityConfigException; import org.wso2.carbon.security.keystore.service.CertData; +import org.wso2.carbon.security.keystore.service.KeyStoreData; import org.wso2.carbon.security.keystore.service.PaginatedKeyStoreData; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; +import java.security.Key; import java.security.KeyStore; +import java.util.ArrayList; +import java.util.List; import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mockStatic; @@ -62,13 +69,12 @@ public class KeyStoreAdminTest extends IdentityBaseTest { private static final String KEYSTORE_NAME = "wso2carbon.jks"; private static final String KEYSTORE_TYPE = "JKS"; private static final String KEYSTORE_PASSWORD = "wso2carbon"; + private static final String KEYSTORE_ALIAS = "wso2carbon"; @Mock private ServerConfiguration serverConfiguration; @Mock private KeyStoreManager keyStoreManager; @Mock - private Registry registry; - @Mock private CryptoUtil cryptoUtil; @Mock private Resource resource; @@ -81,7 +87,7 @@ public void setup() throws Exception { System.setProperty( CarbonBaseConstants.CARBON_HOME, Paths.get(System.getProperty("user.dir"), "src", "test", "resources").toString() - ); + ); } @Test(description = "Add KeyStore test") @@ -97,8 +103,9 @@ public void testAddKeyStore() throws Exception { keyStoreUtil.when(() -> KeyStoreUtil.isPrimaryStore(any())).thenReturn(false); keyStoreUtil.when(() -> KeyStoreUtil.isTrustStore(any())).thenReturn(false); - keyStoreAdmin = new KeyStoreAdmin(tenantID, registry); - keyStoreAdmin.addKeyStore(keyStoreContent, "new_keystore.jks", KEYSTORE_PASSWORD, " ", "JKS", KEYSTORE_PASSWORD); + keyStoreAdmin = new KeyStoreAdmin(tenantID, null); + keyStoreAdmin.addKeyStore(keyStoreContent, "new_keystore.jks", KEYSTORE_PASSWORD, " ", "JKS", + KEYSTORE_PASSWORD); } } @@ -115,8 +122,9 @@ public void testAddTrustStore() throws Exception { keyStoreUtil.when(() -> KeyStoreUtil.isPrimaryStore(any())).thenReturn(false); keyStoreUtil.when(() -> KeyStoreUtil.isTrustStore(any())).thenReturn(true); - keyStoreAdmin = new KeyStoreAdmin(tenantID, registry); - keyStoreAdmin.addTrustStore(keyStoreContent, "new_truststore.jks", KEYSTORE_PASSWORD, " ", "JKS"); + keyStoreAdmin = new KeyStoreAdmin(tenantID, null); + keyStoreAdmin.addTrustStore(Base64.encode(keyStoreContent), "new_truststore.jks", KEYSTORE_PASSWORD, " ", + "JKS"); } } @@ -129,7 +137,7 @@ public void testGetTrustStoreSuccess() throws Exception { when(this.keyStoreManager.getTrustStore()) .thenReturn(getKeyStoreFromFile(KEYSTORE_NAME, KEYSTORE_PASSWORD)); - keyStoreAdmin = new KeyStoreAdmin(tenantID, registry); + keyStoreAdmin = new KeyStoreAdmin(tenantID, null); KeyStore result = keyStoreAdmin.getTrustStore(); assertNotNull(result); @@ -146,7 +154,7 @@ public void testGetTrustStoreException() throws Exception { when(this.keyStoreManager.getTrustStore()) .thenThrow(new CarbonException("Error occurred while retrieving TrustStore")); - keyStoreAdmin = new KeyStoreAdmin(tenantID, registry); + keyStoreAdmin = new KeyStoreAdmin(tenantID, null); // Execute method under test assertThrows(SecurityConfigException.class, () -> { keyStoreAdmin.getTrustStore(); @@ -165,7 +173,7 @@ public void testDeleteKeyStore() throws Exception { keyStoreUtil.when(() -> KeyStoreUtil.isPrimaryStore(anyString())).thenReturn(false); keyStoreUtil.when(() -> KeyStoreUtil.isTrustStore(anyString())).thenReturn(false); - keyStoreAdmin = new KeyStoreAdmin(tenantID, registry); + keyStoreAdmin = new KeyStoreAdmin(tenantID, null); keyStoreAdmin.deleteStore("new_keystore.jks"); verify(this.keyStoreManager).deleteStore("new_keystore.jks"); } @@ -182,14 +190,12 @@ public void testDeleteTrustStore() throws Exception { keyStoreUtil.when(() -> KeyStoreUtil.isPrimaryStore(anyString())).thenReturn(false); keyStoreUtil.when(() -> KeyStoreUtil.isTrustStore(anyString())).thenReturn(false); - keyStoreAdmin = new KeyStoreAdmin(tenantID, registry); + keyStoreAdmin = new KeyStoreAdmin(tenantID, null); keyStoreAdmin.deleteStore("new_truststore.jks"); verify(this.keyStoreManager).deleteStore("new_truststore.jks"); } } - - @Test public void testGetPaginatedKeystoreInfo() throws Exception { @@ -198,8 +204,6 @@ public void testGetPaginatedKeystoreInfo() throws Exception { MockedStatic keyStoreUtil = mockStatic(KeyStoreUtil.class)) { serverConfiguration.when(ServerConfiguration::getInstance).thenReturn(this.serverConfiguration); - when(this.serverConfiguration.getFirstProperty( - RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE)).thenReturn(KEYSTORE_TYPE); keyStoreUtil.when(() -> KeyStoreUtil.isPrimaryStore(any())).thenReturn(true); @@ -207,13 +211,128 @@ public void testGetPaginatedKeystoreInfo() throws Exception { when(this.keyStoreManager.getKeyStore(anyString())) .thenReturn(getKeyStoreFromFile(KEYSTORE_NAME, KEYSTORE_PASSWORD)); - keyStoreAdmin = new KeyStoreAdmin(tenantID, registry); + keyStoreAdmin = new KeyStoreAdmin(tenantID, null); PaginatedKeyStoreData result = keyStoreAdmin.getPaginatedKeystoreInfo(KEYSTORE_NAME, 10); int actualKeysNo = findCertDataSetSize(result.getPaginatedKeyData().getCertDataSet()); assertEquals(actualKeysNo, 3, "Incorrect key numbers"); } + } + + @Test + public void testGetFilteredPaginatedKeystoreInfo() throws Exception { + + try (MockedStatic serverConfigurationMockedStatic = mockStatic(ServerConfiguration.class); + MockedStatic keyStoreManagerMockedStatic = mockStatic(KeyStoreManager.class); + MockedStatic keyStoreUtil = mockStatic(KeyStoreUtil.class)) { + + serverConfigurationMockedStatic.when(ServerConfiguration::getInstance).thenReturn(serverConfiguration); + keyStoreUtil.when(() -> KeyStoreUtil.isPrimaryStore(any())).thenReturn(true); + + keyStoreManagerMockedStatic.when(() -> KeyStoreManager.getInstance(tenantID)).thenReturn(keyStoreManager); + when(keyStoreManager.getKeyStore(anyString())) + .thenReturn(getKeyStoreFromFile(KEYSTORE_NAME, KEYSTORE_PASSWORD)); + + keyStoreAdmin = new KeyStoreAdmin(tenantID, null); + PaginatedKeyStoreData result = + keyStoreAdmin.getFilteredPaginatedKeyStoreInfo(KEYSTORE_NAME, 10, KEYSTORE_ALIAS); + int actualKeysNo = findCertDataSetSize(result.getPaginatedKeyData().getCertDataSet()); + assertEquals(actualKeysNo, 1, "Incorrect key numbers"); + } + } + + @Test + public void testGetKeystoresInfo() throws Exception { + + try (MockedStatic serverConfiguration = mockStatic(ServerConfiguration.class); + MockedStatic keyStoreManager = mockStatic(KeyStoreManager.class); + MockedStatic keyStoreUtil = mockStatic(KeyStoreUtil.class)) { + + serverConfiguration.when(ServerConfiguration::getInstance).thenReturn(this.serverConfiguration); + keyStoreUtil.when(() -> KeyStoreUtil.isPrimaryStore(any())).thenReturn(false); + keyStoreUtil.when(() -> KeyStoreUtil.isTrustStore(any())).thenReturn(false); + + keyStoreManager.when(() -> KeyStoreManager.getInstance(tenantID)).thenReturn(this.keyStoreManager); + when(this.keyStoreManager.getKeyStore(anyString())) + .thenReturn(getKeyStoreFromFile(KEYSTORE_NAME, KEYSTORE_PASSWORD)); + when(this.keyStoreManager.getPrivateKey(anyString(), anyString())) + .thenReturn(getPrivateKeyFromKeyStore(KEYSTORE_NAME, KEYSTORE_ALIAS, KEYSTORE_PASSWORD)); + + keyStoreAdmin = new KeyStoreAdmin(tenantID, null); + KeyStoreData keystoreInfo = keyStoreAdmin.getKeystoreInfo(KEYSTORE_NAME); + assertEquals(keystoreInfo.getKeyStoreName(), KEYSTORE_NAME, "Incorrect keystore name"); + assertEquals(keystoreInfo.getKeyStoreType(), KEYSTORE_TYPE, "Incorrect keystore type"); + assertNotNull(keystoreInfo.getKeyValue()); + } + } + @DataProvider(name = "testGetKeyStoreMetadataDataProvider") + public Object[][] testGetKeyStoreMetadataDataProvider() { + return new Object[][]{ + {true, getPrimaryKeyStoreMetadata()}, + {false, getTenantKeyStoreMetadata()} + }; + } + + @Test(dataProvider = "testGetKeyStoreMetadataDataProvider", + description = "Test case to verify successful retrieval keystore metadata") + public void testGetKeyStoreMetadata(boolean isSuperTenant, KeyStoreMetadata keyStoreMetadata) + throws SecurityConfigException { + + List metadataList = new ArrayList<>(); + metadataList.add(keyStoreMetadata); + try (MockedStatic keyStoreManagerMockedStatic = mockStatic(KeyStoreManager.class)) { + + keyStoreManagerMockedStatic.when(() -> KeyStoreManager.getInstance(anyInt())).thenReturn(keyStoreManager); + when(keyStoreManager.getKeyStoresMetadata(anyBoolean())).thenReturn( + metadataList.toArray(new KeyStoreMetadata[0])); + + keyStoreAdmin = new KeyStoreAdmin(tenantID, null); + KeyStoreData[] keyStores = keyStoreAdmin.getKeyStores(isSuperTenant); + + assertEquals(keyStores.length, 1, "Incorrect number of keystores"); + assertEquals(keyStores[0].getKeyStoreName(), keyStoreMetadata.getKeyStoreName()); + assertEquals(keyStores[0].getKeyStoreType(), keyStoreMetadata.getKeyStoreType()); + assertEquals(keyStores[0].getProvider(), keyStoreMetadata.getProvider()); + assertEquals(keyStores[0].getPrivateStore(), keyStoreMetadata.isPrivateStore()); + } + } + + @Test + public void testGetKeystoreEntries() throws Exception { + + try (MockedStatic keyStoreManager = mockStatic(KeyStoreManager.class)) { + + keyStoreManager.when(() -> KeyStoreManager.getInstance(anyInt())).thenReturn(this.keyStoreManager); + when(this.keyStoreManager.getKeyStore(KEYSTORE_NAME)) + .thenReturn(getKeyStoreFromFile(KEYSTORE_NAME, KEYSTORE_PASSWORD)); + keyStoreAdmin = new KeyStoreAdmin(tenantID, null); + String[] names = keyStoreAdmin.getStoreEntries(KEYSTORE_NAME); + assertEquals(names.length, 38, "Incorrect key numbers"); + } + } + + private KeyStoreMetadata getPrimaryKeyStoreMetadata() { + + String name = createPath(KEYSTORE_NAME).toString(); + KeyStoreMetadata primaryKeyStoreMetadata = new KeyStoreMetadata(); + primaryKeyStoreMetadata.setKeyStoreName(name); + primaryKeyStoreMetadata.setKeyStoreType(KEYSTORE_TYPE); + primaryKeyStoreMetadata.setProvider(" "); + primaryKeyStoreMetadata.setPrivateStore(true); + return primaryKeyStoreMetadata; + } + + private KeyStoreMetadata getTenantKeyStoreMetadata() { + + KeyStoreMetadata TenantKeyStoreMetadata = new KeyStoreMetadata(); + TenantKeyStoreMetadata.setKeyStoreName(KEYSTORE_NAME); + TenantKeyStoreMetadata.setKeyStoreType(KEYSTORE_TYPE); + TenantKeyStoreMetadata.setProvider(" "); + TenantKeyStoreMetadata.setPrivateStore(true); + TenantKeyStoreMetadata.setPublicCertId("12345"); + TenantKeyStoreMetadata.setPublicCert("publicCert".getBytes(StandardCharsets.UTF_8)); + return TenantKeyStoreMetadata; } private KeyStore getKeyStoreFromFile(String keystoreName, String password) throws Exception { @@ -225,6 +344,15 @@ private KeyStore getKeyStoreFromFile(String keystoreName, String password) throw return keystore; } + private Key getPrivateKeyFromKeyStore(String keystoreName, String alias, String password) throws Exception { + + Path tenantKeystorePath = createPath(keystoreName); + FileInputStream file = new FileInputStream(tenantKeystorePath.toString()); + KeyStore keystore = KeyStore.getInstance("JKS"); + keystore.load(file, password.toCharArray()); + return keystore.getKey(alias, password.toCharArray()); + } + private Path createPath(String keystoreName) { Path keystorePath = Paths.get(System.getProperty(CarbonBaseConstants.CARBON_HOME), "repository", @@ -258,6 +386,4 @@ private byte[] readBytesFromFile(String filePath) throws IOException { } return bytes; } - - }