Search in sources :

Example 16 with RealmAttributeUpdater

use of org.keycloak.testsuite.updaters.RealmAttributeUpdater in project keycloak by keycloak.

the class WebAuthnPolicySettingsTest method policySettingsWithExternalProperties.

@Test
public void policySettingsWithExternalProperties() throws IOException {
    try (RealmAttributeUpdater rau = updateWebAuthnPolicy("rpName", Collections.singletonList("ES256"), INDIRECT.getValue(), CROSS_PLATFORM.getValue(), "No", null, PREFERRED.getValue(), Collections.singletonList(ALL_ZERO_AAGUID))) {
        WebAuthnRealmData realm = new WebAuthnRealmData(testRealmResource().toRepresentation(), isPasswordless());
        assertThat(realm, notNullValue());
        assertThat(realm.getSignatureAlgorithms(), hasItems("ES256"));
        assertThat(realm.getAttestationConveyancePreference(), is(INDIRECT.getValue()));
        assertThat(realm.getAuthenticatorAttachment(), is(CROSS_PLATFORM.getValue()));
        assertThat(realm.getRequireResidentKey(), is("No"));
        assertThat(realm.getRpId(), is(""));
        assertThat(realm.getUserVerificationRequirement(), is(PREFERRED.getValue()));
        assertThat(realm.getAcceptableAaguids(), hasItems(ALL_ZERO_AAGUID));
    }
}
Also used : WebAuthnRealmAttributeUpdater(org.keycloak.testsuite.webauthn.updaters.WebAuthnRealmAttributeUpdater) RealmAttributeUpdater(org.keycloak.testsuite.updaters.RealmAttributeUpdater) PasswordLessRealmAttributeUpdater(org.keycloak.testsuite.webauthn.updaters.PasswordLessRealmAttributeUpdater) WebAuthnRealmData(org.keycloak.testsuite.webauthn.utils.WebAuthnRealmData) AbstractConsoleTest(org.keycloak.testsuite.console.AbstractConsoleTest) Test(org.junit.Test)

Example 17 with RealmAttributeUpdater

use of org.keycloak.testsuite.updaters.RealmAttributeUpdater in project keycloak by keycloak.

the class RefreshTokenTest method testRefreshTokenWhenClientSessionTimeoutPassedButRealmDidNot.

// KEYCLOAK-17323
@Test
public void testRefreshTokenWhenClientSessionTimeoutPassedButRealmDidNot() {
    getCleanup().addCleanup(new RealmAttributeUpdater(adminClient.realm("test")).setSsoSessionIdleTimeout(// 30 Days
    2592000).setSsoSessionMaxLifespan(// 999 Days
    86313600).update()).addCleanup(ClientAttributeUpdater.forClient(adminClient, "test", "test-app").setAttribute(CLIENT_SESSION_IDLE_TIMEOUT, // 1 minute
    "60").setAttribute(CLIENT_SESSION_MAX_LIFESPAN, // 1 minute 5 seconds
    "65").update());
    oauth.doLogin("test-user@localhost", "password");
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    assertEquals(200, response.getStatusCode());
    assertExpiration(response.getExpiresIn(), 65);
    setTimeOffset(70);
    oauth.openLoginForm();
    code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response2 = oauth.doAccessTokenRequest(code, "password");
    assertExpiration(response2.getExpiresIn(), 65);
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) RealmAttributeUpdater(org.keycloak.testsuite.updaters.RealmAttributeUpdater) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 18 with RealmAttributeUpdater

use of org.keycloak.testsuite.updaters.RealmAttributeUpdater in project keycloak by keycloak.

the class SessionsPreloadCrossDCTest method loginFailuresPreloadTest.

@Test
public void loginFailuresPreloadTest() throws Exception {
    // Enable brute force protector
    try (RealmAttributeUpdater rau = new RealmAttributeUpdater(getAdminClientForStartedNodeInDc(0).realms().realm("test")).updateWith(r -> r.setBruteForceProtected(true)).updateWith(// This is necessary so user is not locked out for too fast consecutive login attempts; when user is locked out failure count stops increasing
    r -> r.setQuickLoginCheckMilliSeconds(20L)).update()) {
        String userId = ApiUtil.findUserByUsername(getAdminClientForStartedNodeInDc(0).realms().realm("test"), "test-user@localhost").getId();
        int loginFailuresBefore = (Integer) getAdminClientForStartedNodeInDc(0).realm("test").attackDetection().bruteForceUserStatus(userId).get("numFailures");
        log.infof("loginFailuresBefore: %d", loginFailuresBefore);
        // Create initial brute force records
        for (int i = 0; i < SESSIONS_COUNT; i++) {
            OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "bad-password");
            Assert.assertNull(response.getAccessToken());
            Assert.assertNotNull(response.getError());
        }
        // Start 2nd DC.
        CrossDCTestEnricher.startAuthServerBackendNode(DC.SECOND, 0);
        enableLoadBalancerNode(DC.SECOND, 0);
        Retry.execute(() -> {
            // Ensure loginFailures are loaded in both 1st DC and 2nd DC
            Set<String> keys1 = getTestingClientForStartedNodeInDc(0).testing().cache(InfinispanConnectionProvider.LOGIN_FAILURE_CACHE_NAME).enumerateKeys();
            Set<String> keys2 = getTestingClientForStartedNodeInDc(1).testing().cache(InfinispanConnectionProvider.LOGIN_FAILURE_CACHE_NAME).enumerateKeys();
            int loginFailures1 = (Integer) getAdminClientForStartedNodeInDc(0).realm("test").attackDetection().bruteForceUserStatus(userId).get("numFailures");
            int loginFailures2 = (Integer) getAdminClientForStartedNodeInDc(1).realm("test").attackDetection().bruteForceUserStatus(userId).get("numFailures");
            log.infof("keys1: %d, keys2: %d, loginFailures1: %d, loginFailures2: %d", keys1, keys2, loginFailures1, loginFailures2);
            Assert.assertThat(keys1, Matchers.equalTo(keys2));
            Assert.assertEquals(loginFailuresBefore + SESSIONS_COUNT, loginFailures1);
            Assert.assertEquals(loginFailuresBefore + SESSIONS_COUNT, loginFailures2);
        }, 3, 400);
        // On DC2 sessions were preloaded from remoteCache
        Assert.assertTrue(getTestingClientForStartedNodeInDc(1).testing().cache(InfinispanConnectionProvider.WORK_CACHE_NAME).contains("distributed::remoteCacheLoad::loginFailures"));
    }
}
Also used : InfinispanConnectionProvider(org.keycloak.connections.infinispan.InfinispanConnectionProvider) Assert(org.keycloak.testsuite.Assert) Set(java.util.Set) Matchers(org.hamcrest.Matchers) Test(org.junit.Test) RealmAttributeUpdater(org.keycloak.testsuite.updaters.RealmAttributeUpdater) OAuthClient(org.keycloak.testsuite.util.OAuthClient) List(java.util.List) CrossDCTestEnricher(org.keycloak.testsuite.arquillian.CrossDCTestEnricher) LinkedList(java.util.LinkedList) InitialDcState(org.keycloak.testsuite.arquillian.annotation.InitialDcState) OAuth2Constants(org.keycloak.OAuth2Constants) Retry(org.keycloak.common.util.Retry) Before(org.junit.Before) ApiUtil(org.keycloak.testsuite.admin.ApiUtil) OAuthClient(org.keycloak.testsuite.util.OAuthClient) RealmAttributeUpdater(org.keycloak.testsuite.updaters.RealmAttributeUpdater) Test(org.junit.Test)

Example 19 with RealmAttributeUpdater

use of org.keycloak.testsuite.updaters.RealmAttributeUpdater in project keycloak by keycloak.

the class IdentityProviderTest method failCreateInvalidUrl.

@Test
@AuthServerContainerExclude(REMOTE)
public void failCreateInvalidUrl() throws Exception {
    try (AutoCloseable c = new RealmAttributeUpdater(realmsResouce().realm("test")).updateWith(r -> r.setSslRequired(SslRequired.ALL.name())).update()) {
        IdentityProviderRepresentation newIdentityProvider = createRep("new-identity-provider", "oidc");
        newIdentityProvider.getConfig().put("clientId", "clientId");
        newIdentityProvider.getConfig().put("clientSecret", "some secret value");
        OIDCIdentityProviderConfigRep oidcConfig = new OIDCIdentityProviderConfigRep(newIdentityProvider);
        oidcConfig.setAuthorizationUrl("invalid://test");
        try (Response response = this.realm.identityProviders().create(newIdentityProvider)) {
            assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
            ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);
            assertEquals("The url [authorization_url] is malformed", error.getErrorMessage());
        }
        oidcConfig.setAuthorizationUrl(null);
        oidcConfig.setTokenUrl("http://test");
        try (Response response = this.realm.identityProviders().create(newIdentityProvider)) {
            assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
            ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);
            assertEquals("The url [token_url] requires secure connections", error.getErrorMessage());
        }
        oidcConfig.setAuthorizationUrl(null);
        oidcConfig.setTokenUrl(null);
        oidcConfig.setJwksUrl("http://test");
        try (Response response = this.realm.identityProviders().create(newIdentityProvider)) {
            assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
            ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);
            assertEquals("The url [jwks_url] requires secure connections", error.getErrorMessage());
        }
        oidcConfig.setAuthorizationUrl(null);
        oidcConfig.setTokenUrl(null);
        oidcConfig.setJwksUrl(null);
        oidcConfig.setLogoutUrl("http://test");
        try (Response response = this.realm.identityProviders().create(newIdentityProvider)) {
            assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
            ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);
            assertEquals("The url [logout_url] requires secure connections", error.getErrorMessage());
        }
        oidcConfig.setAuthorizationUrl(null);
        oidcConfig.setTokenUrl(null);
        oidcConfig.setJwksUrl(null);
        oidcConfig.setLogoutUrl(null);
        oidcConfig.setUserInfoUrl("http://test");
        try (Response response = this.realm.identityProviders().create(newIdentityProvider)) {
            assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
            ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);
            assertEquals("The url [userinfo_url] requires secure connections", error.getErrorMessage());
        }
    }
}
Also used : EndpointType(org.keycloak.dom.saml.v2.metadata.EndpointType) Arrays(java.util.Arrays) ResourceType(org.keycloak.events.admin.ResourceType) OIDCIdentityProviderConfigRep(org.keycloak.testsuite.broker.OIDCIdentityProviderConfigRep) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) Matchers.not(org.hamcrest.Matchers.not) ClientErrorException(javax.ws.rs.ClientErrorException) Assert.assertThat(org.junit.Assert.assertThat) SAMLIdentityProviderConfig(org.keycloak.broker.saml.SAMLIdentityProviderConfig) MediaType(javax.ws.rs.core.MediaType) MultipartFormDataOutput(org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput) ByteArrayInputStream(java.io.ByteArrayInputStream) REMOTE(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer.REMOTE) Document(org.w3c.dom.Document) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) URI(java.net.URI) AdminEventPaths(org.keycloak.testsuite.util.AdminEventPaths) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Set(java.util.Set) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) UUID(java.util.UUID) RealmAttributeUpdater(org.keycloak.testsuite.updaters.RealmAttributeUpdater) NotFoundException(javax.ws.rs.NotFoundException) DocumentUtil(org.keycloak.saml.common.util.DocumentUtil) IdentityProviderResource(org.keycloak.admin.client.resource.IdentityProviderResource) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) List(java.util.List) SslRequired(org.keycloak.common.enums.SslRequired) Response(javax.ws.rs.core.Response) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) Assert.assertFalse(org.junit.Assert.assertFalse) Matchers.equalTo(org.hamcrest.Matchers.equalTo) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) Matchers.is(org.hamcrest.Matchers.is) Matchers.containsString(org.hamcrest.Matchers.containsString) XMLSignature(javax.xml.crypto.dsig.XMLSignature) SAMLParser(org.keycloak.saml.processing.core.parsers.saml.SAMLParser) OperationType(org.keycloak.events.admin.OperationType) IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) Assert(org.keycloak.testsuite.Assert) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) IdentityProviderMapperModel(org.keycloak.models.IdentityProviderMapperModel) HashMap(java.util.HashMap) IdentityProviderMapperTypeRepresentation(org.keycloak.representations.idm.IdentityProviderMapperTypeRepresentation) ErrorRepresentation(org.keycloak.representations.idm.ErrorRepresentation) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) HashSet(java.util.HashSet) ComponentRepresentation(org.keycloak.representations.idm.ComponentRepresentation) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException) Charset(java.nio.charset.Charset) AUTH_SERVER_SSL_REQUIRED(org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_SSL_REQUIRED) IndexedEndpointType(org.keycloak.dom.saml.v2.metadata.IndexedEndpointType) AdminEventRepresentation(org.keycloak.representations.idm.AdminEventRepresentation) IdentityProviderMapperRepresentation(org.keycloak.representations.idm.IdentityProviderMapperRepresentation) StripSecretsUtils(org.keycloak.models.utils.StripSecretsUtils) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) Matchers.hasEntry(org.hamcrest.Matchers.hasEntry) SPSSODescriptorType(org.keycloak.dom.saml.v2.metadata.SPSSODescriptorType) Matchers.empty(org.hamcrest.Matchers.empty) NodeList(org.w3c.dom.NodeList) EntityDescriptorType(org.keycloak.dom.saml.v2.metadata.EntityDescriptorType) Files(java.nio.file.Files) Assert.assertNotNull(org.junit.Assert.assertNotNull) KeyTypes(org.keycloak.dom.saml.v2.metadata.KeyTypes) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) XMLDSIG_NSURI(org.keycloak.saml.common.constants.JBossSAMLURIConstants.XMLDSIG_NSURI) Element(org.w3c.dom.Element) Assert.assertNull(org.junit.Assert.assertNull) Paths(java.nio.file.Paths) KeyDescriptorType(org.keycloak.dom.saml.v2.metadata.KeyDescriptorType) IdentityProviderMapperSyncMode(org.keycloak.models.IdentityProviderMapperSyncMode) Assert.assertEquals(org.junit.Assert.assertEquals) Response(javax.ws.rs.core.Response) OIDCIdentityProviderConfigRep(org.keycloak.testsuite.broker.OIDCIdentityProviderConfigRep) ErrorRepresentation(org.keycloak.representations.idm.ErrorRepresentation) IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) RealmAttributeUpdater(org.keycloak.testsuite.updaters.RealmAttributeUpdater) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) Test(org.junit.Test)

Example 20 with RealmAttributeUpdater

use of org.keycloak.testsuite.updaters.RealmAttributeUpdater in project keycloak by keycloak.

the class LoginTest method loginRememberMeExpiredMaxLifespan.

@Test
// TODO remove this (KEYCLOAK-16228)
@DisableFeature(value = Profile.Feature.ACCOUNT2, skipRestart = true)
public void loginRememberMeExpiredMaxLifespan() throws Exception {
    try (Closeable c = new RealmAttributeUpdater(adminClient.realm("test")).setSsoSessionMaxLifespanRememberMe(1).setRememberMe(true).update()) {
        // login form shown after redirect from app
        oauth.clientId("test-app");
        oauth.redirectUri(OAuthClient.APP_ROOT + "/auth");
        oauth.openLoginForm();
        assertTrue(loginPage.isCurrent());
        loginPage.setRememberMe(true);
        loginPage.login("test-user@localhost", "password");
        // sucessful login - app page should be on display.
        events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent();
        appPage.assertCurrent();
        // expire the max lifespan.
        setTimeOffset(2);
        // trying to open the account page with an expired lifespan should redirect back to the login page.
        appPage.openAccount();
        loginPage.assertCurrent();
    }
}
Also used : Closeable(java.io.Closeable) RealmAttributeUpdater(org.keycloak.testsuite.updaters.RealmAttributeUpdater) DisableFeature(org.keycloak.testsuite.arquillian.annotation.DisableFeature) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Aggregations

Test (org.junit.Test)27 RealmAttributeUpdater (org.keycloak.testsuite.updaters.RealmAttributeUpdater)27 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)15 Matchers.containsString (org.hamcrest.Matchers.containsString)10 List (java.util.List)5 AuthServerContainerExclude (org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude)5 WebAuthnRealmAttributeUpdater (org.keycloak.testsuite.webauthn.updaters.WebAuthnRealmAttributeUpdater)5 Closeable (java.io.Closeable)4 Arrays (java.util.Arrays)4 HashMap (java.util.HashMap)4 Set (java.util.Set)4 Response (javax.ws.rs.core.Response)4 Matchers.equalTo (org.hamcrest.Matchers.equalTo)4 Assert.assertFalse (org.junit.Assert.assertFalse)4 IOException (java.io.IOException)3 URISyntaxException (java.net.URISyntaxException)3 HashSet (java.util.HashSet)3 Map (java.util.Map)3 UUID (java.util.UUID)3 MimeMessage (javax.mail.internet.MimeMessage)3