Search in sources :

Example 61 with ComponentModel

use of org.keycloak.component.ComponentModel in project keycloak by keycloak.

the class GroupStorageTest method testSearchTimeout.

@Test
public void testSearchTimeout() throws Exception {
    runTestWithTimeout(4000, () -> {
        String hardcodedGroup = HardcodedGroupStorageProviderFactory.PROVIDER_ID;
        String delayedSearch = HardcodedGroupStorageProviderFactory.DELAYED_SEARCH;
        String providerId = this.providerId;
        testingClient.server().run(session -> {
            RealmModel realm = session.realms().getRealmByName(AuthRealm.TEST);
            assertThat(session.groupStorageManager().searchForGroupByName(realm, "group", null, null).stream().map(GroupModel::getName).collect(Collectors.toList()), allOf(hasItem(hardcodedGroup), hasItem("sample-realm-group")));
            // update the provider to simulate delay during the search
            ComponentModel memoryProvider = realm.getComponent(providerId);
            memoryProvider.getConfig().putSingle(delayedSearch, Boolean.toString(true));
            realm.updateComponent(memoryProvider);
        });
        testingClient.server().run(session -> {
            RealmModel realm = session.realms().getRealmByName(AuthRealm.TEST);
            // search for groups and check hardcoded-group is not present
            assertThat(session.groupStorageManager().searchForGroupByName(realm, "group", null, null).stream().map(GroupModel::getName).collect(Collectors.toList()), allOf(not(hasItem(hardcodedGroup)), hasItem("sample-realm-group")));
        });
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) ComponentModel(org.keycloak.component.ComponentModel) GroupModel(org.keycloak.models.GroupModel) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 62 with ComponentModel

use of org.keycloak.component.ComponentModel in project keycloak by keycloak.

the class LDAPProvidersIntegrationTest method testHardcodedRoleMapper.

@Test
public void testHardcodedRoleMapper() {
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        RoleModel hardcodedRole = appRealm.addRole("hardcoded-role");
        // assert that user "johnkeycloak" doesn't have hardcoded role
        UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak");
        Assert.assertFalse(john.hasRole(hardcodedRole));
        ComponentModel hardcodedMapperModel = KeycloakModelUtils.createComponentModel("hardcoded role", ctx.getLdapModel().getId(), HardcodedLDAPRoleStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(), HardcodedLDAPRoleStorageMapper.ROLE, "hardcoded-role");
        appRealm.addComponentModel(hardcodedMapperModel);
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        RoleModel hardcodedRole = appRealm.getRole("hardcoded-role");
        // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
        UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak");
        Assert.assertTrue(john.hasRole(hardcodedRole));
        // Can't remove user from hardcoded role
        try {
            john.deleteRoleMapping(hardcodedRole);
            Assert.fail("Didn't expected to remove role mapping");
        } catch (ModelException expected) {
        }
        // Revert mappers
        ComponentModel hardcodedMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "hardcoded role");
        appRealm.removeComponent(hardcodedMapperModel);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserModel(org.keycloak.models.UserModel) LDAPStorageMapper(org.keycloak.storage.ldap.mappers.LDAPStorageMapper) UserAttributeLDAPStorageMapper(org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper) ModelException(org.keycloak.models.ModelException) ComponentModel(org.keycloak.component.ComponentModel) RoleModel(org.keycloak.models.RoleModel) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 63 with ComponentModel

use of org.keycloak.component.ComponentModel in project keycloak by keycloak.

the class LDAPProvidersIntegrationTest method testHardcodedGroupMapper.

@Test
public void testHardcodedGroupMapper() {
    final String uuid = UUID.randomUUID().toString();
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        GroupModel hardcodedGroup = appRealm.createGroup(uuid, "hardcoded-group");
        // assert that user "johnkeycloak" doesn't have hardcoded group
        UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak");
        Assert.assertFalse(john.isMemberOf(hardcodedGroup));
        ComponentModel hardcodedMapperModel = KeycloakModelUtils.createComponentModel("hardcoded group", ctx.getLdapModel().getId(), HardcodedLDAPGroupStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(), HardcodedLDAPGroupStorageMapper.GROUP, "hardcoded-group");
        appRealm.addComponentModel(hardcodedMapperModel);
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        GroupModel hardcodedGroup = appRealm.getGroupById(uuid);
        // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
        UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak");
        Assert.assertTrue(john.isMemberOf(hardcodedGroup));
        // Can't remove user from hardcoded role
        try {
            john.leaveGroup(hardcodedGroup);
            Assert.fail("Didn't expected to leave group");
        } catch (ModelException expected) {
        }
        // Revert mappers
        ComponentModel hardcodedMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "hardcoded group");
        appRealm.removeComponent(hardcodedMapperModel);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserModel(org.keycloak.models.UserModel) LDAPStorageMapper(org.keycloak.storage.ldap.mappers.LDAPStorageMapper) UserAttributeLDAPStorageMapper(org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper) ModelException(org.keycloak.models.ModelException) ComponentModel(org.keycloak.component.ComponentModel) GroupModel(org.keycloak.models.GroupModel) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 64 with ComponentModel

use of org.keycloak.component.ComponentModel in project keycloak by keycloak.

the class LDAPSyncTest method test09MembershipUsingDifferentAttributes.

// KEYCLOAK-14696
@Test
public void test09MembershipUsingDifferentAttributes() throws Exception {
    final Map<String, String> previousConf = testingClient.server().fetch(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        // Remove all users from model
        session.userLocalStorage().getUsersStream(ctx.getRealm(), true).peek(user -> System.out.println("trying to delete user: " + user.getUsername())).collect(Collectors.toList()).forEach(user -> {
            UserCache userCache = session.userCache();
            if (userCache != null) {
                userCache.evict(ctx.getRealm(), user);
            }
            session.userLocalStorage().removeUser(ctx.getRealm(), user);
        });
        Map<String, String> orig = new HashMap<>();
        orig.put(LDAPConstants.RDN_LDAP_ATTRIBUTE, ctx.getLdapModel().getConfig().getFirst(LDAPConstants.RDN_LDAP_ATTRIBUTE));
        orig.put(LDAPConstants.USERS_DN, ctx.getLdapModel().getConfig().getFirst(LDAPConstants.USERS_DN));
        orig.put(LDAPConstants.USERNAME_LDAP_ATTRIBUTE, ctx.getLdapModel().getConfig().getFirst(LDAPConstants.USERNAME_LDAP_ATTRIBUTE));
        // create an OU and this test will work below it, set RDN to CN and username to uid/samaccountname
        LDAPTestUtils.addLdapOU(ctx.getLdapProvider(), "KC14696");
        ctx.getLdapModel().getConfig().putSingle(LDAPConstants.USERS_DN, "ou=KC14696," + orig.get(LDAPConstants.USERS_DN));
        ctx.getLdapModel().getConfig().putSingle(LDAPConstants.RDN_LDAP_ATTRIBUTE, LDAPConstants.CN);
        ctx.getLdapModel().getConfig().putSingle(LDAPConstants.USERNAME_LDAP_ATTRIBUTE, ctx.getLdapProvider().getLdapIdentityStore().getConfig().isActiveDirectory() ? LDAPConstants.SAM_ACCOUNT_NAME : LDAPConstants.UID);
        ctx.getRealm().updateComponent(ctx.getLdapModel());
        ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "username");
        mapperModel.getConfig().putSingle(UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE, ctx.getLdapProvider().getLdapIdentityStore().getConfig().isActiveDirectory() ? LDAPConstants.SAM_ACCOUNT_NAME : LDAPConstants.UID);
        ctx.getRealm().updateComponent(mapperModel);
        LDAPTestUtils.addUserAttributeMapper(appRealm, LDAPTestUtils.getLdapProviderModel(appRealm), "cnMapper", "firstName", LDAPConstants.CN);
        return orig;
    }, Map.class);
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        // create a user8 inside the usersDn
        LDAPObject user8 = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "user8", "User8FN", "User8LN", "user8@email.org", "user8street", "126");
        // create a sample ou inside usersDn
        LDAPTestUtils.addLdapOU(ctx.getLdapProvider(), "sample-org");
        // create a user below the sample org with the same common-name but different username
        String usersDn = ctx.getLdapModel().get(LDAPConstants.USERS_DN);
        ctx.getLdapModel().getConfig().putSingle(LDAPConstants.USERS_DN, "ou=sample-org," + usersDn);
        ctx.getRealm().updateComponent(ctx.getLdapModel());
        LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "user8bis", "User8FN", "User8LN", "user8bis@email.org", "user8street", "126");
        // get back to parent usersDn
        ctx.getLdapModel().getConfig().putSingle(LDAPConstants.USERS_DN, usersDn);
        ctx.getRealm().updateComponent(ctx.getLdapModel());
        // create a group with user8 as a member
        String descriptionAttrName = LDAPTestUtils.getGroupDescriptionLDAPAttrName(ctx.getLdapProvider());
        LDAPObject user8Group = LDAPTestUtils.createLDAPGroup(session, appRealm, ctx.getLdapModel(), "user8group", descriptionAttrName, "user8group - description");
        LDAPUtils.addMember(ctx.getLdapProvider(), MembershipType.DN, LDAPConstants.MEMBER, "not-used", user8Group, user8);
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        SynchronizationResult syncResult = new UserStorageSyncManager().syncAllUsers(sessionFactory, "test", ctx.getLdapModel());
        Assert.assertEquals(2, syncResult.getAdded());
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        GroupModel user8Group = KeycloakModelUtils.findGroupByPath(appRealm, "/user8group");
        Assert.assertNotNull(user8Group);
        UserModel user8 = session.users().getUserByUsername(appRealm, "user8");
        Assert.assertNotNull(user8);
        UserModel user8Bis = session.users().getUserByUsername(appRealm, "user8bis");
        Assert.assertNotNull(user8Bis);
        Assert.assertTrue("User user8 contains the group", user8.getGroupsStream().collect(Collectors.toSet()).contains(user8Group));
        Assert.assertFalse("User user8bis does not contain the group", user8Bis.getGroupsStream().collect(Collectors.toSet()).contains(user8Group));
        List<String> members = session.users().getGroupMembersStream(appRealm, user8Group).map(u -> u.getUsername()).collect(Collectors.toList());
        Assert.assertEquals("Group contains only user8", members, Collections.singletonList("user8"));
    });
    // revert changes
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        session.users().removeImportedUsers(appRealm, ldapModelId);
        LDAPTestUtils.removeLDAPUserByUsername(ctx.getLdapProvider(), appRealm, ctx.getLdapProvider().getLdapIdentityStore().getConfig(), "user8");
        LDAPTestUtils.removeLDAPUserByUsername(ctx.getLdapProvider(), appRealm, ctx.getLdapProvider().getLdapIdentityStore().getConfig(), "user8bis");
        LDAPObject ou = new LDAPObject();
        ou.setDn(LDAPDn.fromString("ou=sample-org,ou=KC14696," + previousConf.get(LDAPConstants.USERS_DN)));
        ctx.getLdapProvider().getLdapIdentityStore().remove(ou);
        ou.setDn(LDAPDn.fromString("ou=KC14696," + previousConf.get(LDAPConstants.USERS_DN)));
        ctx.getLdapProvider().getLdapIdentityStore().remove(ou);
        for (Map.Entry<String, String> e : previousConf.entrySet()) {
            if (e.getValue() == null) {
                ctx.getLdapModel().getConfig().remove(e.getKey());
            } else {
                ctx.getLdapModel().getConfig().putSingle(e.getKey(), e.getValue());
            }
        }
        ctx.getRealm().updateComponent(ctx.getLdapModel());
        ComponentModel cnMapper = LDAPTestUtils.getSubcomponentByName(ctx.getRealm(), ctx.getLdapModel(), "cnMapper");
        ctx.getRealm().removeComponent(cnMapper);
        ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "username");
        mapperModel.getConfig().putSingle(UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE, ctx.getLdapProvider().getLdapIdentityStore().getConfig().getUsernameLdapAttribute());
        ctx.getRealm().updateComponent(mapperModel);
    });
}
Also used : MethodSorters(org.junit.runners.MethodSorters) LDAPStorageProvider(org.keycloak.storage.ldap.LDAPStorageProvider) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) HashMap(java.util.HashMap) SynchronizationResultRepresentation(org.keycloak.representations.idm.SynchronizationResultRepresentation) LDAPConstants(org.keycloak.models.LDAPConstants) ComponentRepresentation(org.keycloak.representations.idm.ComponentRepresentation) UserModel(org.keycloak.models.UserModel) LDAPRule(org.keycloak.testsuite.util.LDAPRule) Map(java.util.Map) ComponentModel(org.keycloak.component.ComponentModel) GroupModel(org.keycloak.models.GroupModel) BadRequestException(javax.ws.rs.BadRequestException) ClassRule(org.junit.ClassRule) LDAPGroupMapperMode(org.keycloak.storage.ldap.mappers.membership.LDAPGroupMapperMode) LDAPDn(org.keycloak.storage.ldap.idm.model.LDAPDn) MembershipType(org.keycloak.storage.ldap.mappers.membership.MembershipType) WaitUtils(org.keycloak.testsuite.util.WaitUtils) RealmModel(org.keycloak.models.RealmModel) LDAPTestUtils(org.keycloak.testsuite.util.LDAPTestUtils) Matchers(org.hamcrest.Matchers) Test(org.junit.Test) LDAPStorageProviderFactory(org.keycloak.storage.ldap.LDAPStorageProviderFactory) GroupLDAPStorageMapperFactory(org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapperFactory) Collectors(java.util.stream.Collectors) GroupLDAPStorageMapper(org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapper) UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) UserProvider(org.keycloak.models.UserProvider) List(java.util.List) UserCache(org.keycloak.models.cache.UserCache) UserAttributeLDAPStorageMapper(org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper) LDAPUtils(org.keycloak.storage.ldap.LDAPUtils) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult) Assert(org.junit.Assert) FixMethodOrder(org.junit.FixMethodOrder) Collections(java.util.Collections) GroupMapperConfig(org.keycloak.storage.ldap.mappers.membership.group.GroupMapperConfig) UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) HashMap(java.util.HashMap) GroupModel(org.keycloak.models.GroupModel) UserCache(org.keycloak.models.cache.UserCache) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ComponentModel(org.keycloak.component.ComponentModel) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 65 with ComponentModel

use of org.keycloak.component.ComponentModel in project keycloak by keycloak.

the class LDAPNoMSADTest method testMultivaluedRDN.

// KEYCLOAK-12842
@Test
public void testMultivaluedRDN() {
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        ComponentModel snMapper = null;
        // Create LDAP user with both "uid" and "sn" attribute in RDN. Something like "uid=johnkeycloak3+sn=Doe3,ou=People,dc=domain,dc=com"
        LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
        LDAPObject john2 = LDAPTestUtils.addLDAPUser(ldapProvider, appRealm, "johnkeycloak3", "John3", "Doe3", "john3@email.org", null, "4321");
        john2.addRdnAttributeName("sn");
        ldapProvider.getLdapIdentityStore().update(john2);
        // Assert DN was changed
        String rdnAttrName = ldapProvider.getLdapIdentityStore().getConfig().getRdnLdapAttribute();
        Assert.assertEquals(rdnAttrName + "=johnkeycloak3+sn=Doe3", john2.getDn().getFirstRdn().toString());
    });
    // Update some user attributes not mapped to DN. DN won't be changed
    String userId = testRealm().users().search("johnkeycloak3").get(0).getId();
    UserResource user = testRealm().users().get(userId);
    UserRepresentation userRep = user.toRepresentation();
    assertFirstRDNEndsWith(userRep, "johnkeycloak3", "Doe3");
    userRep.setEmail("newemail@email.cz");
    user.update(userRep);
    userRep = user.toRepresentation();
    Assert.assertEquals("newemail@email.cz", userRep.getEmail());
    assertFirstRDNEndsWith(userRep, "johnkeycloak3", "Doe3");
    // Update some user attributes mapped to DN. DN will be changed
    userRep.setLastName("Doe3Changed");
    user.update(userRep);
    userRep = user.toRepresentation();
    // ApacheDS bug causes that attribute, which was added to DN, is lowercased. Works for other LDAPs (RHDS, OpenLDAP)
    Assert.assertThat("Doe3Changed", equalToIgnoringCase(userRep.getLastName()));
    assertFirstRDNEndsWith(userRep, "johnkeycloak3", "Doe3Changed");
    // Remove user
    user.remove();
}
Also used : RealmModel(org.keycloak.models.RealmModel) ComponentModel(org.keycloak.component.ComponentModel) UserResource(org.keycloak.admin.client.resource.UserResource) LDAPStorageProvider(org.keycloak.storage.ldap.LDAPStorageProvider) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) Test(org.junit.Test)

Aggregations

ComponentModel (org.keycloak.component.ComponentModel)155 RealmModel (org.keycloak.models.RealmModel)74 Test (org.junit.Test)52 LDAPStorageProvider (org.keycloak.storage.ldap.LDAPStorageProvider)46 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)34 UserModel (org.keycloak.models.UserModel)29 HashMap (java.util.HashMap)22 UserStorageProviderModel (org.keycloak.storage.UserStorageProviderModel)22 GroupModel (org.keycloak.models.GroupModel)21 MultivaluedHashMap (org.keycloak.common.util.MultivaluedHashMap)18 SynchronizationResult (org.keycloak.storage.user.SynchronizationResult)18 ComponentValidationException (org.keycloak.component.ComponentValidationException)16 UserStorageProvider (org.keycloak.storage.UserStorageProvider)16 LDAPStorageMapper (org.keycloak.storage.ldap.mappers.LDAPStorageMapper)15 GroupLDAPStorageMapper (org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapper)15 Path (javax.ws.rs.Path)14 DeclarativeUserProfileProvider (org.keycloak.userprofile.DeclarativeUserProfileProvider)13 ModelException (org.keycloak.models.ModelException)11 UPAttribute (org.keycloak.userprofile.config.UPAttribute)11 UPConfig (org.keycloak.userprofile.config.UPConfig)11