Search in sources :

Example 61 with ModelTest

use of org.keycloak.testsuite.arquillian.annotation.ModelTest in project keycloak by keycloak.

the class ClientModelTest method testAddApplicationWithId.

@Test
@ModelTest
public void testAddApplicationWithId(KeycloakSession session) {
    final String id = KeycloakModelUtils.generateId();
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionAppWithId1) -> {
        currentSession = sessionAppWithId1;
        RealmModel realm = currentSession.realms().getRealmByName(realmName);
        client = realm.addClient(id, "application2");
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionAppWithId2) -> {
        currentSession = sessionAppWithId2;
        RealmModel realm = currentSession.realms().getRealmByName(realmName);
        client = currentSession.clients().getClientById(realm, id);
        assertThat("Client 'app-123' is NULL!!", client, notNullValue());
        currentSession.clients().removeClient(realm, client.getId());
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) KeycloakSession(org.keycloak.models.KeycloakSession) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest)

Example 62 with ModelTest

use of org.keycloak.testsuite.arquillian.annotation.ModelTest in project keycloak by keycloak.

the class ClientModelTest method testDefaultDefaultClientScopes.

@Test
@ModelTest
public void testDefaultDefaultClientScopes(KeycloakSession session) {
    AtomicReference<ClientScopeModel> scope1Atomic = new AtomicReference<>();
    AtomicReference<ClientScopeModel> scope2Atomic = new AtomicReference<>();
    AtomicReference<ClientScopeModel> scope3Atomic = new AtomicReference<>();
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionDefaultClientScope1) -> {
        currentSession = sessionDefaultClientScope1;
        RealmModel realm = currentSession.realms().getRealmByName(realmName);
        ClientScopeModel scope1 = realm.addClientScope("scope1");
        scope1.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        scope1Atomic.set(scope1);
        ClientScopeModel scope2 = realm.addClientScope("scope2");
        scope2.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        scope2Atomic.set(scope2);
        ClientScopeModel scope3 = realm.addClientScope("scope3");
        scope3.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        scope3Atomic.set(scope3);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionDefaultClientScope2) -> {
        currentSession = sessionDefaultClientScope2;
        RealmModel realm = currentSession.realms().getRealmByName(realmName);
        ClientScopeModel scope1 = scope1Atomic.get();
        ClientScopeModel scope2 = scope2Atomic.get();
        ClientScopeModel scope3 = scope3Atomic.get();
        scope1 = realm.getClientScopeById(scope1.getId());
        scope2 = realm.getClientScopeById(scope2.getId());
        scope3 = realm.getClientScopeById(scope3.getId());
        realm.addDefaultClientScope(scope1, true);
        realm.addDefaultClientScope(scope2, false);
        realm.addDefaultClientScope(scope3, false);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionDefaultClientScope3) -> {
        currentSession = sessionDefaultClientScope3;
        RealmModel realm = currentSession.realms().getRealmByName(realmName);
        client = realm.addClient("foo");
        client.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionDefaultClientScope4) -> {
        currentSession = sessionDefaultClientScope4;
        RealmModel realm = currentSession.realms().getRealmByName(realmName);
        client = realm.getClientByClientId("foo");
        ClientScopeModel scope1 = scope1Atomic.get();
        ClientScopeModel scope2 = scope2Atomic.get();
        Map<String, ClientScopeModel> clientScopes1 = client.getClientScopes(true);
        assertThat("Client Scope contains 'scope1':", clientScopes1.containsKey("scope1"), is(true));
        assertThat("Client Scope contains 'scope2':", clientScopes1.containsKey("scope2"), is(false));
        assertThat("Client Scope contains 'scope3':", clientScopes1.containsKey("scope3"), is(false));
        Map<String, ClientScopeModel> clientScopes2 = client.getClientScopes(false);
        assertThat("Client Scope contains 'scope1':", clientScopes2.containsKey("scope1"), is(false));
        assertThat("Client Scope contains 'scope2':", clientScopes2.containsKey("scope2"), is(true));
        assertThat("Client Scope contains 'scope3':", clientScopes2.containsKey("scope3"), is(true));
        currentSession.clients().removeClient(realm, client.getId());
        // Remove some realm default client scopes
        realm.removeDefaultClientScope(scope1);
        realm.removeDefaultClientScope(scope2);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionDefaultClientScope5) -> {
        currentSession = sessionDefaultClientScope5;
        RealmModel realm = currentSession.realms().getRealmByName(realmName);
        client = realm.addClient("foo2");
        client.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionDefaultClientScope5) -> {
        currentSession = sessionDefaultClientScope5;
        RealmModel realm = currentSession.realms().getRealmByName(realmName);
        client = realm.getClientByClientId("foo2");
        Map<String, ClientScopeModel> clientScopes1 = client.getClientScopes(true);
        assertThat("Client Scope contains 'scope1':", clientScopes1.containsKey("scope1"), is(false));
        assertThat("Client Scope contains 'scope2':", clientScopes1.containsKey("scope2"), is(false));
        assertThat("Client Scope contains 'scope3':", clientScopes1.containsKey("scope3"), is(false));
        Map<String, ClientScopeModel> clientScopes2 = client.getClientScopes(false);
        assertThat("Client Scope contains 'scope1':", clientScopes2.containsKey("scope1"), is(false));
        assertThat("Client Scope contains 'scope2':", clientScopes2.containsKey("scope2"), is(false));
        assertThat("Client Scope contains 'scope3':", clientScopes2.containsKey("scope3"), is(true));
        currentSession.clients().removeClient(realm, client.getId());
        realm.removeClientScope(scope1Atomic.get().getId());
        realm.removeClientScope(scope2Atomic.get().getId());
        realm.removeDefaultClientScope(scope3Atomic.get());
        realm.removeClientScope(scope3Atomic.get().getId());
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) KeycloakSession(org.keycloak.models.KeycloakSession) ClientScopeModel(org.keycloak.models.ClientScopeModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest)

Example 63 with ModelTest

use of org.keycloak.testsuite.arquillian.annotation.ModelTest in project keycloak by keycloak.

the class ConcurrentTransactionsTest method persistClient.

@Test
@ModelTest
public void persistClient(KeycloakSession session) {
    final ClientModel[] client = { null };
    AtomicReference<String> clientDBIdAtomic = new AtomicReference<>();
    AtomicReference<Exception> exceptionHolder = new AtomicReference<>();
    try {
        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionSetup) -> {
            RealmModel realm = sessionSetup.realms().getRealm("test");
            sessionSetup.users().addUser(realm, "user1").setEmail("user1@localhost");
            sessionSetup.users().addUser(realm, "user2").setEmail("user2@localhost");
            realm = sessionSetup.realms().createRealm("original");
            RoleModel defaultRole = sessionSetup.roles().addRealmRole(realm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realm.getName());
            realm.setDefaultRole(defaultRole);
            client[0] = sessionSetup.clients().addClient(realm, "client");
            client[0].setSecret("old");
        });
        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession session1) -> {
            String clientDBId = client[0].getId();
            clientDBIdAtomic.set(clientDBId);
            final KeycloakSessionFactory sessionFactory = session1.getKeycloakSessionFactory();
            final CountDownLatch transactionsCounter = new CountDownLatch(2);
            final CountDownLatch readLatch = new CountDownLatch(1);
            final CountDownLatch updateLatch = new CountDownLatch(1);
            Thread thread1 = new Thread(() -> {
                KeycloakModelUtils.runJobInTransaction(sessionFactory, session11 -> {
                    try {
                        KeycloakSession currentSession = session11;
                        // Wait until transaction in both threads started
                        transactionsCounter.countDown();
                        logger.info("transaction1 started");
                        if (!transactionsCounter.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
                            throw new IllegalStateException("Timeout when waiting for transactionsCounter latch in thread1");
                        }
                        // Read client
                        RealmModel realm1 = currentSession.realms().getRealmByName("original");
                        ClientModel client1 = currentSession.clients().getClientByClientId(realm1, "client");
                        logger.info("transaction1: Read client finished");
                        readLatch.countDown();
                        // Wait until thread2 updates client and commits
                        if (!updateLatch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
                            throw new IllegalStateException("Timeout when waiting for updateLatch");
                        }
                        logger.info("transaction1: Going to read client again");
                        client1 = currentSession.clients().getClientByClientId(realm1, "client");
                        logger.info("transaction1: secret: " + client1.getSecret());
                    } catch (Exception e) {
                        exceptionHolder.set(e);
                        throw new RuntimeException(e);
                    }
                });
            });
            Thread thread2 = new Thread(() -> {
                KeycloakModelUtils.runJobInTransaction(sessionFactory, session22 -> {
                    try {
                        KeycloakSession currentSession = session22;
                        // Wait until transaction in both threads started
                        transactionsCounter.countDown();
                        logger.info("transaction2 started");
                        if (!transactionsCounter.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
                            throw new IllegalStateException("Timeout when waiting for transactionsCounter latch in thread2");
                        }
                        // Wait until reader thread reads the client
                        if (!readLatch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
                            throw new IllegalStateException("Timeout when waiting for readLatch");
                        }
                        logger.info("transaction2: Going to update client secret");
                        RealmModel realm12 = currentSession.realms().getRealmByName("original");
                        ClientModel client12 = currentSession.clients().getClientByClientId(realm12, "client");
                        client12.setSecret("new");
                    } catch (Exception e) {
                        exceptionHolder.set(e);
                        throw new RuntimeException(e);
                    }
                });
                logger.info("transaction2: commited");
                updateLatch.countDown();
            });
            thread1.start();
            thread2.start();
            try {
                thread1.join();
                thread2.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (exceptionHolder.get() != null) {
                Assert.fail("Some thread thrown an exception. See the log for the details");
            }
            logger.info("after thread join");
        });
        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession session2) -> {
            RealmModel realm = session2.realms().getRealmByName("original");
            String clientDBId = clientDBIdAtomic.get();
            ClientModel clientFromCache = session2.clients().getClientById(realm, clientDBId);
            ClientModel clientFromDB = session2.getProvider(ClientProvider.class).getClientById(realm, clientDBId);
            logger.info("SECRET FROM DB : " + clientFromDB.getSecret());
            logger.info("SECRET FROM CACHE : " + clientFromCache.getSecret());
            Assert.assertEquals("new", clientFromDB.getSecret());
            Assert.assertEquals("new", clientFromCache.getSecret());
            session2.sessions().removeUserSessions(realm);
        });
    } finally {
        tearDownRealm(session, "user1", "user2");
    }
}
Also used : ClientProvider(org.keycloak.models.ClientProvider) AtomicReference(java.util.concurrent.atomic.AtomicReference) RoleModel(org.keycloak.models.RoleModel) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) CountDownLatch(java.util.concurrent.CountDownLatch) RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) KeycloakSession(org.keycloak.models.KeycloakSession) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 64 with ModelTest

use of org.keycloak.testsuite.arquillian.annotation.ModelTest in project keycloak by keycloak.

the class ConcurrentTransactionsTest method removeUserAttribute.

// KEYCLOAK-3296 , KEYCLOAK-3494
@Test
@ModelTest
public void removeUserAttribute(KeycloakSession session) throws Exception {
    try {
        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionSet) -> {
            RealmModel realm = sessionSet.realms().createRealm("original");
            realm.setDefaultRole(sessionSet.roles().addRealmRole(realm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realm.getName()));
            UserModel john = sessionSet.users().addUser(realm, "john");
            john.setSingleAttribute("foo", "val1");
            UserModel john2 = sessionSet.users().addUser(realm, "john2");
            john2.setAttribute("foo", Arrays.asList("val1", "val2"));
        });
        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession session2) -> {
            final KeycloakSessionFactory sessionFactory = session2.getKeycloakSessionFactory();
            AtomicReference<Exception> reference = new AtomicReference<>();
            final CountDownLatch readAttrLatch = new CountDownLatch(2);
            Runnable runnable = () -> {
                try {
                    KeycloakModelUtils.runJobInTransaction(sessionFactory, session1 -> {
                        try {
                            // Read user attribute
                            RealmModel realm = session1.realms().getRealmByName("original");
                            UserModel john = session1.users().getUserByUsername(realm, "john");
                            String attrVal = john.getFirstAttribute("foo");
                            UserModel john2 = session1.users().getUserByUsername(realm, "john2");
                            String attrVal2 = john2.getFirstAttribute("foo");
                            // Wait until it's read in both threads
                            readAttrLatch.countDown();
                            readAttrLatch.await();
                            // KEYCLOAK-3296 : Remove user attribute in both threads
                            john.removeAttribute("foo");
                            // KEYCLOAK-3494 : Set single attribute in both threads
                            john2.setSingleAttribute("foo", "bar");
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    });
                } catch (Exception e) {
                    reference.set(e);
                    throw new RuntimeException(e);
                } finally {
                    readAttrLatch.countDown();
                }
            };
            Thread thread1 = new Thread(runnable);
            Thread thread2 = new Thread(runnable);
            thread1.start();
            thread2.start();
            try {
                thread1.join();
                thread2.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info("removeUserAttribute: after thread join");
            if (reference.get() != null) {
                Assert.fail("Exception happened in some of threads. Details: " + reference.get().getMessage());
            }
        });
    } finally {
        tearDownRealm(session, "john", "john2");
    }
}
Also used : ClientModel(org.keycloak.models.ClientModel) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) UserManager(org.keycloak.models.UserManager) Arrays(java.util.Arrays) RealmModel(org.keycloak.models.RealmModel) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Logger(org.jboss.logging.Logger) ClientProvider(org.keycloak.models.ClientProvider) Constants(org.keycloak.models.Constants) KeycloakSession(org.keycloak.models.KeycloakSession) Test(org.junit.Test) RoleModel(org.keycloak.models.RoleModel) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest) AtomicReference(java.util.concurrent.atomic.AtomicReference) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) UserModel(org.keycloak.models.UserModel) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) Matchers.nullValue(org.hamcrest.Matchers.nullValue) Matchers.is(org.hamcrest.Matchers.is) Assert(org.junit.Assert) AuthServer(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer) AtomicReference(java.util.concurrent.atomic.AtomicReference) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) CountDownLatch(java.util.concurrent.CountDownLatch) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) KeycloakSession(org.keycloak.models.KeycloakSession) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 65 with ModelTest

use of org.keycloak.testsuite.arquillian.annotation.ModelTest in project keycloak by keycloak.

the class UserSessionProviderTest method testUpdateClientSessionInSameTransaction.

@Test
@ModelTest
public void testUpdateClientSessionInSameTransaction(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    UserSessionModel[] sessions = createSessions(session);
    String userSessionId = sessions[0].getId();
    String clientUUID = realm.getClientByClientId("test-app").getId();
    UserSessionModel userSession = session.sessions().getUserSession(realm, userSessionId);
    AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(clientUUID);
    clientSession.setAction(AuthenticatedClientSessionModel.Action.LOGGED_OUT.name());
    clientSession.setNote("foo", "bar");
    AuthenticatedClientSessionModel updated = session.sessions().getUserSession(realm, userSessionId).getAuthenticatedClientSessionByClient(clientUUID);
    assertEquals(AuthenticatedClientSessionModel.Action.LOGGED_OUT.name(), updated.getAction());
    assertEquals("bar", updated.getNote("foo"));
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Aggregations

ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)82 Test (org.junit.Test)81 RealmModel (org.keycloak.models.RealmModel)76 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)66 KeycloakSession (org.keycloak.models.KeycloakSession)60 UserModel (org.keycloak.models.UserModel)37 ClientModel (org.keycloak.models.ClientModel)36 UserSessionModel (org.keycloak.models.UserSessionModel)26 AtomicReference (java.util.concurrent.atomic.AtomicReference)19 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)14 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)12 UserConsentModel (org.keycloak.models.UserConsentModel)10 RealmManager (org.keycloak.services.managers.RealmManager)10 RoleModel (org.keycloak.models.RoleModel)9 ClientScopeModel (org.keycloak.models.ClientScopeModel)6 UserManager (org.keycloak.models.UserManager)6 HashMap (java.util.HashMap)5 HashSet (java.util.HashSet)5 ResetTimeOffsetEvent (org.keycloak.models.utils.ResetTimeOffsetEvent)5 List (java.util.List)4