Search in sources :

Example 1 with ExportImportManager

use of org.keycloak.exportimport.ExportImportManager in project keycloak by keycloak.

the class KeycloakApplication method bootstrap.

// Bootstrap master realm, import realms and create admin user.
protected ExportImportManager bootstrap() {
    ExportImportManager[] exportImportManager = new ExportImportManager[1];
    logger.debug("bootstrap");
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            // TODO what is the purpose of following piece of code? Leaving it as is for now.
            JtaTransactionManagerLookup lookup = (JtaTransactionManagerLookup) sessionFactory.getProviderFactory(JtaTransactionManagerLookup.class);
            if (lookup != null) {
                if (lookup.getTransactionManager() != null) {
                    try {
                        Transaction transaction = lookup.getTransactionManager().getTransaction();
                        logger.debugv("bootstrap current transaction? {0}", transaction != null);
                        if (transaction != null) {
                            logger.debugv("bootstrap current transaction status? {0}", transaction.getStatus());
                        }
                    } catch (SystemException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            // TODO up here ^^
            ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);
            exportImportManager[0] = new ExportImportManager(session);
            boolean createMasterRealm = applianceBootstrap.isNewInstall();
            if (exportImportManager[0].isRunImport() && exportImportManager[0].isImportMasterIncluded()) {
                createMasterRealm = false;
            }
            if (createMasterRealm) {
                applianceBootstrap.createMasterRealm();
            }
        }
    });
    if (exportImportManager[0].isRunImport()) {
        exportImportManager[0].runImport();
    } else {
        importRealms();
    }
    importAddUser();
    return exportImportManager[0];
}
Also used : ApplianceBootstrap(org.keycloak.services.managers.ApplianceBootstrap) JtaTransactionManagerLookup(org.keycloak.transaction.JtaTransactionManagerLookup) Transaction(javax.transaction.Transaction) SystemException(javax.transaction.SystemException) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession) ExportImportManager(org.keycloak.exportimport.ExportImportManager)

Example 2 with ExportImportManager

use of org.keycloak.exportimport.ExportImportManager in project keycloak by keycloak.

the class ComponentExportImportTest method testSingleFile.

@Test
public void testSingleFile() {
    clearExportImportProperties(testingClient);
    RealmRepresentation realmRep = RealmBuilder.create().name(REALM_NAME).build();
    adminClient.realms().create(realmRep);
    String realmId = testRealmResource().toRepresentation().getId();
    ComponentRepresentation parentComponent = new ComponentRepresentation();
    parentComponent.setParentId(realmId);
    parentComponent.setName("parent");
    parentComponent.setSubType("subtype");
    parentComponent.setProviderId(UserMapStorageFactory.PROVIDER_ID);
    parentComponent.setProviderType(UserStorageProvider.class.getName());
    parentComponent.setConfig(new MultivaluedHashMap<>());
    parentComponent.getConfig().putSingle("priority", Integer.toString(0));
    parentComponent.getConfig().putSingle("attr", "value");
    parentComponent.getConfig().putSingle(IMPORT_ENABLED, Boolean.toString(false));
    String parentComponentId = addComponent(parentComponent);
    ComponentRepresentation subcomponent = new ComponentRepresentation();
    subcomponent.setParentId(parentComponentId);
    subcomponent.setName("child");
    subcomponent.setSubType("subtype2");
    subcomponent.setProviderId(UserMapStorageFactory.PROVIDER_ID);
    subcomponent.setProviderType(UserStorageProvider.class.getName());
    subcomponent.setConfig(new MultivaluedHashMap<>());
    subcomponent.getConfig().putSingle("priority", Integer.toString(0));
    subcomponent.getConfig().putSingle("attr", "value2");
    subcomponent.getConfig().putSingle(IMPORT_ENABLED, Boolean.toString(false));
    String subcomponentId = addComponent(subcomponent);
    final String exportFilePath = exportFile.getAbsolutePath();
    // export
    testingClient.server().run(session -> {
        ExportImportConfig.setProvider(SingleFileExportProviderFactory.PROVIDER_ID);
        ExportImportConfig.setFile(exportFilePath);
        ExportImportConfig.setRealmName(REALM_NAME);
        ExportImportConfig.setAction(ExportImportConfig.ACTION_EXPORT);
        new ExportImportManager(session).runExport();
    });
    testRealmResource().remove();
    try {
        testRealmResource().toRepresentation();
        Assert.fail("Realm wasn't expected to be found");
    } catch (NotFoundException nfe) {
    // Expected
    }
    // import
    testingClient.server().run(session -> {
        Assert.assertNull(session.realms().getRealmByName(REALM_NAME));
        ExportImportConfig.setAction(ExportImportConfig.ACTION_IMPORT);
        new ExportImportManager(session).runImport();
    });
    // Assert realm was imported
    Assert.assertNotNull(testRealmResource().toRepresentation());
    try {
        parentComponent = testRealmResource().components().component(parentComponentId).toRepresentation();
        subcomponent = testRealmResource().components().component(subcomponentId).toRepresentation();
    } catch (NotFoundException nfe) {
        fail("Components not found after import.");
    }
    Assert.assertEquals(parentComponent.getParentId(), realmId);
    Assert.assertEquals(parentComponent.getName(), "parent");
    Assert.assertEquals(parentComponent.getSubType(), "subtype");
    Assert.assertEquals(parentComponent.getProviderId(), UserMapStorageFactory.PROVIDER_ID);
    Assert.assertEquals(parentComponent.getProviderType(), UserStorageProvider.class.getName());
    Assert.assertEquals(parentComponent.getConfig().getFirst("attr"), "value");
    Assert.assertEquals(subcomponent.getParentId(), parentComponent.getId());
    Assert.assertEquals(subcomponent.getName(), "child");
    Assert.assertEquals(subcomponent.getSubType(), "subtype2");
    Assert.assertEquals(subcomponent.getProviderId(), UserMapStorageFactory.PROVIDER_ID);
    Assert.assertEquals(subcomponent.getProviderType(), UserStorageProvider.class.getName());
    Assert.assertEquals(subcomponent.getConfig().getFirst("attr"), "value2");
}
Also used : ComponentRepresentation(org.keycloak.representations.idm.ComponentRepresentation) UserStorageProvider(org.keycloak.storage.UserStorageProvider) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) ExportImportManager(org.keycloak.exportimport.ExportImportManager) NotFoundException(javax.ws.rs.NotFoundException) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 3 with ExportImportManager

use of org.keycloak.exportimport.ExportImportManager in project keycloak by keycloak.

the class FederatedStorageExportImportTest method testSingleFile.

@Test
public void testSingleFile() {
    ComponentExportImportTest.clearExportImportProperties(testingClient);
    final String userId = "f:1:path";
    testingClient.server().run(session -> {
        RealmModel realm = new RealmManager(session).createRealm(REALM_NAME);
        RoleModel role = realm.addRole("test-role");
        GroupModel group = realm.createGroup("test-group");
        List<String> attrValues = new LinkedList<>();
        attrValues.add("1");
        attrValues.add("2");
        session.userFederatedStorage().setSingleAttribute(realm, userId, "single1", "value1");
        session.userFederatedStorage().setAttribute(realm, userId, "list1", attrValues);
        session.userFederatedStorage().addRequiredAction(realm, userId, "UPDATE_PASSWORD");
        PasswordCredentialModel credential = FederatedStorageExportImportTest.getHashProvider(session, realm.getPasswordPolicy()).encodedCredential("password", realm.getPasswordPolicy().getHashIterations());
        session.userFederatedStorage().createCredential(realm, userId, credential);
        session.userFederatedStorage().grantRole(realm, userId, role);
        session.userFederatedStorage().joinGroup(realm, userId, group);
    });
    final String realmId = testRealmResource().toRepresentation().getId();
    final String groupId = testRealmResource().getGroupByPath("/test-group").getId();
    final String exportFileAbsolutePath = this.exportFileAbsolutePath;
    testingClient.server().run(session -> {
        ExportImportConfig.setProvider(SingleFileExportProviderFactory.PROVIDER_ID);
        ExportImportConfig.setFile(exportFileAbsolutePath);
        ExportImportConfig.setRealmName(REALM_NAME);
        ExportImportConfig.setAction(ExportImportConfig.ACTION_EXPORT);
        new ExportImportManager(session).runExport();
        session.realms().removeRealm(realmId);
    });
    testingClient.server().run(session -> {
        Assert.assertNull(session.realms().getRealmByName(REALM_NAME));
        ExportImportConfig.setAction(ExportImportConfig.ACTION_IMPORT);
        new ExportImportManager(session).runImport();
    });
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName(REALM_NAME);
        Assert.assertNotNull(realm);
        RoleModel role = realm.getRole("test-role");
        GroupModel group = realm.getGroupById(groupId);
        Assert.assertEquals(1, session.userFederatedStorage().getStoredUsersCount(realm));
        MultivaluedHashMap<String, String> attributes = session.userFederatedStorage().getAttributes(realm, userId);
        Assert.assertEquals(3, attributes.size());
        Assert.assertEquals("value1", attributes.getFirst("single1"));
        Assert.assertTrue(attributes.getList("list1").contains("1"));
        Assert.assertTrue(attributes.getList("list1").contains("2"));
        Assert.assertTrue(session.userFederatedStorage().getRequiredActionsStream(realm, userId).collect(Collectors.toSet()).contains("UPDATE_PASSWORD"));
        Assert.assertTrue(session.userFederatedStorage().getRoleMappingsStream(realm, userId).collect(Collectors.toSet()).contains(role));
        Assert.assertTrue(session.userFederatedStorage().getGroupsStream(realm, userId).collect(Collectors.toSet()).contains(group));
        List<CredentialModel> creds = session.userFederatedStorage().getStoredCredentialsStream(realm, userId).collect(Collectors.toList());
        Assert.assertEquals(1, creds.size());
        Assert.assertTrue(FederatedStorageExportImportTest.getHashProvider(session, realm.getPasswordPolicy()).verify("password", PasswordCredentialModel.createFromCredentialModel(creds.get(0))));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) CredentialModel(org.keycloak.credential.CredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) GroupModel(org.keycloak.models.GroupModel) ExportImportManager(org.keycloak.exportimport.ExportImportManager) RoleModel(org.keycloak.models.RoleModel) RealmManager(org.keycloak.services.managers.RealmManager) LinkedList(java.util.LinkedList) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 4 with ExportImportManager

use of org.keycloak.exportimport.ExportImportManager in project keycloak by keycloak.

the class FederatedStorageExportImportTest method testDir.

@Test
public void testDir() {
    ComponentExportImportTest.clearExportImportProperties(testingClient);
    final String userId = "f:1:path";
    testingClient.server().run(session -> {
        RealmModel realm = new RealmManager(session).createRealm(REALM_NAME);
        RoleModel role = realm.addRole("test-role");
        GroupModel group = realm.createGroup("test-group");
        List<String> attrValues = new LinkedList<>();
        attrValues.add("1");
        attrValues.add("2");
        session.userFederatedStorage().setSingleAttribute(realm, userId, "single1", "value1");
        session.userFederatedStorage().setAttribute(realm, userId, "list1", attrValues);
        session.userFederatedStorage().addRequiredAction(realm, userId, "UPDATE_PASSWORD");
        PasswordCredentialModel credential = FederatedStorageExportImportTest.getHashProvider(session, realm.getPasswordPolicy()).encodedCredential("password", realm.getPasswordPolicy().getHashIterations());
        session.userFederatedStorage().createCredential(realm, userId, credential);
        session.userFederatedStorage().grantRole(realm, userId, role);
        session.userFederatedStorage().joinGroup(realm, userId, group);
        session.userFederatedStorage().setNotBeforeForUser(realm, userId, 50);
    });
    final String realmId = testRealmResource().toRepresentation().getId();
    final String groupId = testRealmResource().getGroupByPath("/test-group").getId();
    final String exportDirAbsolutePath = this.exportDirAbsolutePath;
    testingClient.server().run(session -> {
        ExportImportConfig.setProvider(DirExportProviderFactory.PROVIDER_ID);
        ExportImportConfig.setDir(exportDirAbsolutePath);
        ExportImportConfig.setRealmName(REALM_NAME);
        ExportImportConfig.setAction(ExportImportConfig.ACTION_EXPORT);
        new ExportImportManager(session).runExport();
        session.realms().removeRealm(realmId);
    });
    testingClient.server().run(session -> {
        Assert.assertNull(session.realms().getRealmByName(REALM_NAME));
        ExportImportConfig.setAction(ExportImportConfig.ACTION_IMPORT);
        new ExportImportManager(session).runImport();
    });
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName(REALM_NAME);
        Assert.assertNotNull(realm);
        RoleModel role = realm.getRole("test-role");
        GroupModel group = realm.getGroupById(groupId);
        Assert.assertEquals(1, session.userFederatedStorage().getStoredUsersCount(realm));
        MultivaluedHashMap<String, String> attributes = session.userFederatedStorage().getAttributes(realm, userId);
        Assert.assertEquals(3, attributes.size());
        Assert.assertEquals("value1", attributes.getFirst("single1"));
        Assert.assertTrue(attributes.getList("list1").contains("1"));
        Assert.assertTrue(attributes.getList("list1").contains("2"));
        Assert.assertTrue(session.userFederatedStorage().getRequiredActionsStream(realm, userId).collect(Collectors.toSet()).contains("UPDATE_PASSWORD"));
        Assert.assertTrue(session.userFederatedStorage().getRoleMappingsStream(realm, userId).collect(Collectors.toSet()).contains(role));
        Assert.assertTrue(session.userFederatedStorage().getGroupsStream(realm, userId).collect(Collectors.toSet()).contains(group));
        Assert.assertEquals(50, session.userFederatedStorage().getNotBeforeOfUser(realm, userId));
        List<CredentialModel> creds = session.userFederatedStorage().getStoredCredentialsStream(realm, userId).collect(Collectors.toList());
        Assert.assertEquals(1, creds.size());
        Assert.assertTrue(FederatedStorageExportImportTest.getHashProvider(session, realm.getPasswordPolicy()).verify("password", PasswordCredentialModel.createFromCredentialModel(creds.get(0))));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) CredentialModel(org.keycloak.credential.CredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) GroupModel(org.keycloak.models.GroupModel) ExportImportManager(org.keycloak.exportimport.ExportImportManager) RoleModel(org.keycloak.models.RoleModel) RealmManager(org.keycloak.services.managers.RealmManager) LinkedList(java.util.LinkedList) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 5 with ExportImportManager

use of org.keycloak.exportimport.ExportImportManager in project keycloak by keycloak.

the class KeycloakApplication method startup.

protected void startup() {
    KeycloakApplication.sessionFactory = createSessionFactory();
    ExportImportManager[] exportImportManager = new ExportImportManager[1];
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            DBLockManager dbLockManager = new DBLockManager(session);
            dbLockManager.checkForcedUnlock();
            DBLockProvider dbLock = dbLockManager.getDBLock();
            dbLock.waitForLock(DBLockProvider.Namespace.KEYCLOAK_BOOT);
            try {
                exportImportManager[0] = bootstrap();
            } finally {
                dbLock.releaseLock();
            }
        }
    });
    if (exportImportManager[0].isRunExport()) {
        exportImportManager[0].runExport();
    }
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            boolean shouldBootstrapAdmin = new ApplianceBootstrap(session).isNoMasterUser();
            BOOTSTRAP_ADMIN_USER.set(shouldBootstrapAdmin);
        }
    });
    sessionFactory.publish(new PostMigrationEvent());
    setupScheduledTasks(sessionFactory);
}
Also used : ApplianceBootstrap(org.keycloak.services.managers.ApplianceBootstrap) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession) ExportImportManager(org.keycloak.exportimport.ExportImportManager) DBLockManager(org.keycloak.models.dblock.DBLockManager) DBLockProvider(org.keycloak.models.dblock.DBLockProvider) PostMigrationEvent(org.keycloak.models.utils.PostMigrationEvent)

Aggregations

ExportImportManager (org.keycloak.exportimport.ExportImportManager)6 Test (org.junit.Test)3 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)3 LinkedList (java.util.LinkedList)2 CredentialModel (org.keycloak.credential.CredentialModel)2 GroupModel (org.keycloak.models.GroupModel)2 KeycloakSession (org.keycloak.models.KeycloakSession)2 KeycloakSessionTask (org.keycloak.models.KeycloakSessionTask)2 RealmModel (org.keycloak.models.RealmModel)2 RoleModel (org.keycloak.models.RoleModel)2 PasswordCredentialModel (org.keycloak.models.credential.PasswordCredentialModel)2 DBLockManager (org.keycloak.models.dblock.DBLockManager)2 DBLockProvider (org.keycloak.models.dblock.DBLockProvider)2 ApplianceBootstrap (org.keycloak.services.managers.ApplianceBootstrap)2 RealmManager (org.keycloak.services.managers.RealmManager)2 SystemException (javax.transaction.SystemException)1 Transaction (javax.transaction.Transaction)1 NotFoundException (javax.ws.rs.NotFoundException)1 PostMigrationEvent (org.keycloak.models.utils.PostMigrationEvent)1 ComponentRepresentation (org.keycloak.representations.idm.ComponentRepresentation)1