Search in sources :

Example 1 with TempFileResource

use of org.keycloak.testsuite.util.TempFileResource in project keycloak by keycloak.

the class KcAdmSessionTest method test.

@Test
public void test() throws IOException {
    FileConfigHandler handler = initCustomConfigFile();
    try (TempFileResource configFile = new TempFileResource(handler.getConfigFile())) {
        // login as admin
        loginAsUser(configFile.getFile(), serverUrl, "master", "admin", "admin");
        // create realm
        KcAdmExec exe = execute("create realms --config '" + configFile.getName() + "' -s realm=demorealm -s enabled=true");
        assertExitCodeAndStreamSizes(exe, 0, 0, 1);
        Assert.assertTrue(exe.stderrLines().get(0).startsWith("Created "));
        // create user
        exe = execute("create users --config '" + configFile.getName() + "' -r demorealm -s username=testuser -s enabled=true -i");
        assertExitCodeAndStreamSizes(exe, 0, 1, 0);
        String userId = exe.stdoutLines().get(0);
        // add realm admin capabilities to user
        exe = execute("add-roles --config '" + configFile.getName() + "' -r demorealm --uusername testuser --cclientid realm-management --rolename realm-admin");
        assertExitCodeAndStreamSizes(exe, 0, 0, 0);
        // set password for the user
        exe = execute("set-password --config '" + configFile.getName() + "' -r demorealm --username testuser -p password");
        assertExitCodeAndStdErrSize(exe, 0, 0);
        // login as testuser
        loginAsUser(configFile.getFile(), serverUrl, "demorealm", "testuser", "password");
        // get realm roles
        exe = execute("get-roles --config '" + configFile.getName() + "'");
        assertExitCodeAndStdErrSize(exe, 0, 0);
        List<ObjectNode> roles = loadJson(exe.stdout(), LIST_OF_JSON);
        Assert.assertThat("expected three realm roles available", roles.size(), equalTo(3));
        // create realm role
        exe = execute("create roles --config '" + configFile.getName() + "' -s name=testrole -s 'description=Test role' -o");
        assertExitCodeAndStdErrSize(exe, 0, 0);
        ObjectNode role = loadJson(exe.stdout(), ObjectNode.class);
        Assert.assertEquals("testrole", role.get("name").asText());
        String roleId = role.get("id").asText();
        // get realm roles again
        exe = execute("get-roles --config '" + configFile.getName() + "'");
        assertExitCodeAndStdErrSize(exe, 0, 0);
        roles = loadJson(exe.stdout(), LIST_OF_JSON);
        Assert.assertThat("expected four realm roles available", roles.size(), equalTo(4));
        // create client
        exe = execute("create clients --config '" + configFile.getName() + "' -s clientId=testclient -i");
        assertExitCodeAndStreamSizes(exe, 0, 1, 0);
        String idOfClient = exe.stdoutLines().get(0);
        // create client role
        exe = execute("create clients/" + idOfClient + "/roles --config '" + configFile.getName() + "' -s name=clientrole  -s 'description=Test client role'");
        assertExitCodeAndStreamSizes(exe, 0, 0, 1);
        Assert.assertTrue(exe.stderrLines().get(0).startsWith("Created "));
        // make sure client role has been created
        exe = execute("get-roles --config '" + configFile.getName() + "' --cclientid testclient");
        assertExitCodeAndStdErrSize(exe, 0, 0);
        roles = loadJson(exe.stdout(), LIST_OF_JSON);
        Assert.assertThat("expected one role", roles.size(), equalTo(1));
        Assert.assertEquals("clientrole", roles.get(0).get("name").asText());
        // add created role to user - we are realm admin so we can add role to ourself
        exe = execute("add-roles --config '" + configFile.getName() + "' --uusername testuser --cclientid testclient --rolename clientrole");
        assertExitCodeAndStreamSizes(exe, 0, 0, 0);
        // make sure the roles have been added
        exe = execute("get-roles --config '" + configFile.getName() + "' --uusername testuser --all");
        assertExitCodeAndStdErrSize(exe, 0, 0);
        ObjectNode node = loadJson(exe.stdout(), ObjectNode.class);
        Assert.assertNotNull(node.get("realmMappings"));
        List<String> realmMappings = StreamSupport.stream(node.get("realmMappings").spliterator(), false).map(o -> o.get("name").asText()).sorted().collect(Collectors.toList());
        Assert.assertEquals(Arrays.asList("default-roles-demorealm"), realmMappings);
        ObjectNode clientRoles = (ObjectNode) node.get("clientMappings");
        // List<String> fields = asSortedList(clientRoles.fieldNames());
        List<String> fields = StreamSupport.stream(clientRoles.spliterator(), false).map(o -> o.get("client").asText()).sorted().collect(Collectors.toList());
        Assert.assertEquals(Arrays.asList("realm-management", "testclient"), fields);
        realmMappings = StreamSupport.stream(clientRoles.get("realm-management").get("mappings").spliterator(), false).map(o -> o.get("name").asText()).sorted().collect(Collectors.toList());
        Assert.assertEquals(Arrays.asList("realm-admin"), realmMappings);
        realmMappings = StreamSupport.stream(clientRoles.get("testclient").get("mappings").spliterator(), false).map(o -> o.get("name").asText()).sorted().collect(Collectors.toList());
        Assert.assertEquals(Arrays.asList("clientrole"), realmMappings);
        // add a realm role to the user
        exe = execute("add-roles --config '" + configFile.getName() + "' --uusername testuser --rolename testrole");
        assertExitCodeAndStreamSizes(exe, 0, 0, 0);
        // get all roles for the user again
        exe = execute("get-roles --config '" + configFile.getName() + "' --uusername testuser --all");
        assertExitCodeAndStdErrSize(exe, 0, 0);
        node = loadJson(exe.stdout(), ObjectNode.class);
        Assert.assertNotNull(node.get("realmMappings"));
        realmMappings = StreamSupport.stream(node.get("realmMappings").spliterator(), false).map(o -> o.get("name").asText()).sorted().collect(Collectors.toList());
        Assert.assertEquals(Arrays.asList("default-roles-demorealm", "testrole"), realmMappings);
        // create a group
        exe = execute("create groups --config '" + configFile.getName() + "' -s name=TestUsers -i");
        assertExitCodeAndStdErrSize(exe, 0, 0);
        String groupId = exe.stdoutLines().get(0);
        // create a sub-group
        exe = execute("create groups/" + groupId + "/children --config '" + configFile.getName() + "' -s name=TestPowerUsers -i");
        assertExitCodeAndStdErrSize(exe, 0, 0);
        String subGroupId = exe.stdoutLines().get(0);
        // add testuser to TestPowerUsers
        exe = execute("update users/" + userId + "/groups/" + subGroupId + " --config '" + configFile.getName() + "' -s realm=demorealm -s userId=" + userId + " -s groupId=" + subGroupId + " -n");
        assertExitCodeAndStreamSizes(exe, 0, 0, 0);
        // delete everything
        exe = execute("delete groups/" + subGroupId + " --config '" + configFile.getName() + "'");
        assertExitCodeAndStreamSizes(exe, 0, 0, 0);
        exe = execute("delete groups/" + groupId + " --config '" + configFile.getName() + "'");
        assertExitCodeAndStreamSizes(exe, 0, 0, 0);
        exe = execute("delete clients/" + idOfClient + " --config '" + configFile.getName() + "'");
        assertExitCodeAndStreamSizes(exe, 0, 0, 0);
        exe = execute("delete roles/testrole --config '" + configFile.getName() + "'");
        assertExitCodeAndStreamSizes(exe, 0, 0, 0);
        exe = execute("delete users/" + userId + " --config '" + configFile.getName() + "'");
        assertExitCodeAndStreamSizes(exe, 0, 0, 0);
        // delete realm as well - using initial master realm session still saved in config file
        exe = execute("delete realms/demorealm --config '" + configFile.getName() + "' --realm master");
        assertExitCodeAndStreamSizes(exe, 0, 0, 0);
    }
}
Also used : Arrays(java.util.Arrays) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) AbstractAdminTest.loadJson(org.keycloak.testsuite.admin.AbstractAdminTest.loadJson) Test(org.junit.Test) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) FileConfigHandler(org.keycloak.client.admin.cli.config.FileConfigHandler) KcAdmExec(org.keycloak.testsuite.cli.KcAdmExec) List(java.util.List) Matchers.equalTo(org.hamcrest.Matchers.equalTo) TempFileResource(org.keycloak.testsuite.util.TempFileResource) StreamSupport(java.util.stream.StreamSupport) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Assert(org.junit.Assert) AuthServer(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer) KcAdmExec.execute(org.keycloak.testsuite.cli.KcAdmExec.execute) FileConfigHandler(org.keycloak.client.admin.cli.config.FileConfigHandler) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) KcAdmExec(org.keycloak.testsuite.cli.KcAdmExec) TempFileResource(org.keycloak.testsuite.util.TempFileResource) Test(org.junit.Test)

Example 2 with TempFileResource

use of org.keycloak.testsuite.util.TempFileResource in project keycloak by keycloak.

the class KcRegCreateTest method testCreateWithRealmOverride.

@Test
public void testCreateWithRealmOverride() throws IOException {
    FileConfigHandler handler = initCustomConfigFile();
    try (TempFileResource configFile = new TempFileResource(handler.getConfigFile())) {
        // authenticate as a regular user against one realm
        KcRegExec exe = execute("config credentials -x --config '" + configFile.getName() + "' --insecure --server " + oauth.AUTH_SERVER_ROOT + " --realm master --user admin --password admin");
        assertExitCodeAndStreamSizes(exe, 0, 0, 3);
        // use initial token of another realm with server, and realm override
        String token = issueInitialAccessToken("test");
        exe = execute("create --config '" + configFile.getName() + "' --insecure --server " + oauth.AUTH_SERVER_ROOT + " --realm test -s clientId=my_first_client -t " + token);
        assertExitCodeAndStreamSizes(exe, 0, 0, 3);
    }
}
Also used : FileConfigHandler(org.keycloak.client.registration.cli.config.FileConfigHandler) KcRegExec(org.keycloak.testsuite.cli.KcRegExec) TempFileResource(org.keycloak.testsuite.util.TempFileResource) Test(org.junit.Test)

Example 3 with TempFileResource

use of org.keycloak.testsuite.util.TempFileResource in project keycloak by keycloak.

the class KcRegCreateTest method testCreateWithAuthorizationServices.

@Test
public void testCreateWithAuthorizationServices() throws IOException {
    ProfileAssume.assumeFeatureEnabled(Profile.Feature.AUTHORIZATION);
    FileConfigHandler handler = initCustomConfigFile();
    try (TempFileResource configFile = new TempFileResource(handler.getConfigFile())) {
        KcRegExec exe = execute("config credentials -x --config '" + configFile.getName() + "' --insecure --server " + oauth.AUTH_SERVER_ROOT + " --realm master --user admin --password admin");
        assertExitCodeAndStreamSizes(exe, 0, 0, 3);
        String token = issueInitialAccessToken("test");
        exe = execute("create --config '" + configFile.getName() + "' --insecure --server " + oauth.AUTH_SERVER_ROOT + " --realm test -s clientId=authz-client -s authorizationServicesEnabled=true -t " + token);
        assertExitCodeAndStreamSizes(exe, 0, 0, 3);
        RealmResource realm = adminClient.realm("test");
        ClientsResource clients = realm.clients();
        ClientRepresentation clientRep = clients.findByClientId("authz-client").get(0);
        ClientResource client = clients.get(clientRep.getId());
        clientRep = client.toRepresentation();
        Assert.assertTrue(clientRep.getAuthorizationServicesEnabled());
        ResourceServerRepresentation settings = client.authorization().getSettings();
        Assert.assertEquals(PolicyEnforcementMode.ENFORCING, settings.getPolicyEnforcementMode());
        Assert.assertTrue(settings.isAllowRemoteResourceManagement());
        List<RoleRepresentation> roles = client.roles().list();
        Assert.assertEquals(1, roles.size());
        Assert.assertEquals("uma_protection", roles.get(0).getName());
        // create using oidc endpoint - autodetect format
        String content = "        {\n" + "            \"redirect_uris\" : [ \"http://localhost:8980/myapp/*\" ],\n" + "            \"grant_types\" : [ \"authorization_code\", \"client_credentials\", \"refresh_token\", \"" + OAuth2Constants.UMA_GRANT_TYPE + "\" ],\n" + "            \"response_types\" : [ \"code\", \"none\" ],\n" + "            \"client_name\" : \"My Reg Authz\",\n" + "            \"client_uri\" : \"http://localhost:8980/myapp\"\n" + "        }";
        try (TempFileResource tmpFile = new TempFileResource(initTempFile(".json", content))) {
            exe = execute("create --insecure --config '" + configFile.getName() + "' -s 'client_name=My Reg Authz' --realm test -t " + token + " -s 'redirect_uris=[\"http://localhost:8980/myapp5/*\"]' -s client_uri=http://localhost:8980/myapp5" + " -o -f - < '" + tmpFile.getName() + "'");
            assertExitCodeAndStdErrSize(exe, 0, 2);
            OIDCClientRepresentation oidcClient = JsonSerialization.readValue(exe.stdout(), OIDCClientRepresentation.class);
            Assert.assertNotNull("clientId", oidcClient.getClientId());
            Assert.assertEquals("redirect_uris", Arrays.asList("http://localhost:8980/myapp5/*"), oidcClient.getRedirectUris());
            Assert.assertThat("grant_types", oidcClient.getGrantTypes(), Matchers.containsInAnyOrder("authorization_code", "client_credentials", "refresh_token", OAuth2Constants.UMA_GRANT_TYPE));
            Assert.assertEquals("response_types", Arrays.asList("code", "none"), oidcClient.getResponseTypes());
            Assert.assertEquals("client_name", "My Reg Authz", oidcClient.getClientName());
            Assert.assertEquals("client_uri", "http://localhost:8980/myapp5", oidcClient.getClientUri());
            client = clients.get(oidcClient.getClientId());
            clientRep = client.toRepresentation();
            Assert.assertTrue(clientRep.getAuthorizationServicesEnabled());
            settings = client.authorization().getSettings();
            Assert.assertEquals(PolicyEnforcementMode.ENFORCING, settings.getPolicyEnforcementMode());
            Assert.assertTrue(settings.isAllowRemoteResourceManagement());
            roles = client.roles().list();
            Assert.assertEquals(1, roles.size());
            Assert.assertEquals("uma_protection", roles.get(0).getName());
            UserRepresentation serviceAccount = realm.users().search(ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + clientRep.getClientId()).get(0);
            Assert.assertNotNull(serviceAccount);
            List<RoleRepresentation> serviceAccountRoles = realm.users().get(serviceAccount.getId()).roles().clientLevel(clientRep.getId()).listAll();
            Assert.assertTrue(serviceAccountRoles.stream().anyMatch(roleRepresentation -> "uma_protection".equals(roleRepresentation.getName())));
        }
    }
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) FileConfigHandler(org.keycloak.client.registration.cli.config.FileConfigHandler) Arrays(java.util.Arrays) Profile(org.keycloak.common.Profile) AUTH_SERVER_SSL_REQUIRED(org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_SSL_REQUIRED) ClientsResource(org.keycloak.admin.client.resource.ClientsResource) KcRegExec.execute(org.keycloak.testsuite.cli.KcRegExec.execute) TempFileResource(org.keycloak.testsuite.util.TempFileResource) Assume(org.junit.Assume) PolicyEnforcementMode(org.keycloak.representations.idm.authorization.PolicyEnforcementMode) ClientResource(org.keycloak.admin.client.resource.ClientResource) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ProfileAssume(org.keycloak.testsuite.ProfileAssume) Before(org.junit.Before) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) Matchers(org.hamcrest.Matchers) Test(org.junit.Test) IOException(java.io.IOException) File(java.io.File) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) KcRegExec(org.keycloak.testsuite.cli.KcRegExec) JsonSerialization(org.keycloak.util.JsonSerialization) ServiceAccountConstants(org.keycloak.common.constants.ServiceAccountConstants) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) List(java.util.List) Assert(org.junit.Assert) OAuth2Constants(org.keycloak.OAuth2Constants) ConfigData(org.keycloak.client.registration.cli.config.ConfigData) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) KcRegExec(org.keycloak.testsuite.cli.KcRegExec) TempFileResource(org.keycloak.testsuite.util.TempFileResource) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) FileConfigHandler(org.keycloak.client.registration.cli.config.FileConfigHandler) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientsResource(org.keycloak.admin.client.resource.ClientsResource) ClientResource(org.keycloak.admin.client.resource.ClientResource) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) Test(org.junit.Test)

Example 4 with TempFileResource

use of org.keycloak.testsuite.util.TempFileResource in project keycloak by keycloak.

the class KcRegCreateTest method testCreateThoroughly.

@Test
public void testCreateThoroughly() throws IOException {
    FileConfigHandler handler = initCustomConfigFile();
    try (TempFileResource configFile = new TempFileResource(handler.getConfigFile())) {
        // set initial access token in config
        String token = issueInitialAccessToken("test");
        final String realm = "test";
        KcRegExec exe = execute("config initial-token -x --config '" + configFile.getName() + "' --insecure --server " + oauth.AUTH_SERVER_ROOT + " --realm " + realm + " " + token);
        assertExitCodeAndStreamSizes(exe, 0, 0, 0);
        // check that current server, realm, and initial token are saved in the file
        ConfigData config = handler.loadConfig();
        Assert.assertEquals("Config serverUrl", oauth.AUTH_SERVER_ROOT, config.getServerUrl());
        Assert.assertEquals("Config realm", realm, config.getRealm());
        Assert.assertEquals("Config initial access token", token, config.ensureRealmConfigData(oauth.AUTH_SERVER_ROOT, realm).getInitialToken());
        // create configuration from file using stdin redirect ... output an object
        String content = "{\n" + "        \"clientId\": \"my_client\",\n" + "        \"enabled\": true,\n" + "        \"redirectUris\": [\"http://localhost:8980/myapp/*\"],\n" + "        \"serviceAccountsEnabled\": true,\n" + "        \"name\": \"My Client App\",\n" + "        \"implicitFlowEnabled\": false,\n" + "        \"publicClient\": true,\n" + "        \"protocol\": \"openid-connect\",\n" + "        \"webOrigins\": [\"http://localhost:8980/myapp\"],\n" + "        \"consentRequired\": false,\n" + "        \"baseUrl\": \"http://localhost:8980/myapp\",\n" + "        \"rootUrl\": \"http://localhost:8980/myapp\",\n" + "        \"bearerOnly\": true,\n" + "        \"standardFlowEnabled\": true\n" + "}";
        try (TempFileResource tmpFile = new TempFileResource(initTempFile(".json", content))) {
            exe = execute("create --insecure --config '" + configFile.getName() + "' -o -f - < '" + tmpFile.getName() + "'");
            assertExitCodeAndStdErrSize(exe, 0, 2);
            ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
            Assert.assertNotNull("id", client.getId());
            Assert.assertEquals("clientId", "my_client", client.getClientId());
            Assert.assertEquals("enabled", true, client.isEnabled());
            Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris());
            Assert.assertEquals("serviceAccountsEnabled", true, client.isServiceAccountsEnabled());
            Assert.assertEquals("name", "My Client App", client.getName());
            Assert.assertEquals("implicitFlowEnabled", false, client.isImplicitFlowEnabled());
            Assert.assertEquals("publicClient", true, client.isPublicClient());
            // note there is no server-side check if protocol is supported
            Assert.assertEquals("protocol", "openid-connect", client.getProtocol());
            Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8980/myapp"), client.getWebOrigins());
            Assert.assertEquals("consentRequired", false, client.isConsentRequired());
            Assert.assertEquals("baseUrl", "http://localhost:8980/myapp", client.getBaseUrl());
            Assert.assertEquals("rootUrl", "http://localhost:8980/myapp", client.getRootUrl());
            Assert.assertEquals("bearerOnly", true, client.isStandardFlowEnabled());
            Assert.assertNull("mappers are null", client.getProtocolMappers());
            // create configuration from file as a template and override clientId and other attributes ... output an object
            exe = execute("create --insecure --config '" + configFile.getName() + "' -o -f '" + tmpFile.getName() + "' -s clientId=my_client2 -s enabled=false -s 'redirectUris=[\"http://localhost:8980/myapp2/*\"]'" + " -s 'name=My Client App II' -s protocol=openid-connect -s 'webOrigins=[\"http://localhost:8980/myapp2\"]'" + " -s baseUrl=http://localhost:8980/myapp2 -s rootUrl=http://localhost:8980/myapp2");
            assertExitCodeAndStdErrSize(exe, 0, 2);
            ClientRepresentation client2 = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
            Assert.assertNotNull("id", client2.getId());
            Assert.assertEquals("clientId", "my_client2", client2.getClientId());
            Assert.assertEquals("enabled", false, client2.isEnabled());
            Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp2/*"), client2.getRedirectUris());
            Assert.assertEquals("serviceAccountsEnabled", true, client2.isServiceAccountsEnabled());
            Assert.assertEquals("name", "My Client App II", client2.getName());
            Assert.assertEquals("implicitFlowEnabled", false, client2.isImplicitFlowEnabled());
            Assert.assertEquals("publicClient", true, client2.isPublicClient());
            Assert.assertEquals("protocol", "openid-connect", client2.getProtocol());
            Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8980/myapp2"), client2.getWebOrigins());
            Assert.assertEquals("consentRequired", false, client2.isConsentRequired());
            Assert.assertEquals("baseUrl", "http://localhost:8980/myapp2", client2.getBaseUrl());
            Assert.assertEquals("rootUrl", "http://localhost:8980/myapp2", client2.getRootUrl());
            Assert.assertEquals("bearerOnly", true, client2.isStandardFlowEnabled());
            Assert.assertNull("mappers are null", client2.getProtocolMappers());
            // check that using an invalid attribute key is not ignored
            exe = execute("create --config '" + configFile.getName() + "' -o -f '" + tmpFile.getName() + "' -s client_id=my_client3");
            assertExitCodeAndStreamSizes(exe, 1, 0, 1);
            Assert.assertEquals("Failed to set attribute 'client_id' on document type 'default'", exe.stderrLines().get(0));
        }
        // simple create, output an id
        exe = execute("create --insecure --config '" + configFile.getName() + "' -i -s clientId=my_client3");
        assertExitCodeAndStreamSizes(exe, 0, 1, 2);
        Assert.assertEquals("only clientId returned", "my_client3", exe.stdoutLines().get(0));
        // simple create, default output
        exe = execute("create --insecure --config '" + configFile.getName() + "' -s clientId=my_client4");
        assertExitCodeAndStreamSizes(exe, 0, 0, 3);
        Assert.assertEquals("only clientId returned", "Registered new client with client_id 'my_client4'", exe.stderrLines().get(2));
        // create using oidc endpoint - autodetect format
        content = "        {\n" + "            \"redirect_uris\" : [ \"http://localhost:8980/myapp/*\" ],\n" + "            \"grant_types\" : [ \"authorization_code\", \"client_credentials\", \"refresh_token\" ],\n" + "            \"response_types\" : [ \"code\", \"none\" ],\n" + "            \"client_name\" : \"My Client App\",\n" + "            \"client_uri\" : \"http://localhost:8980/myapp\"\n" + "        }";
        try (TempFileResource tmpFile = new TempFileResource(initTempFile(".json", content))) {
            exe = execute("create --insecure --config '" + configFile.getName() + "' -s 'client_name=My Client App V' " + " -s 'redirect_uris=[\"http://localhost:8980/myapp5/*\"]' -s client_uri=http://localhost:8980/myapp5" + " -o -f - < '" + tmpFile.getName() + "'");
            assertExitCodeAndStdErrSize(exe, 0, 2);
            OIDCClientRepresentation client = JsonSerialization.readValue(exe.stdout(), OIDCClientRepresentation.class);
            Assert.assertNotNull("clientId", client.getClientId());
            Assert.assertEquals("redirect_uris", Arrays.asList("http://localhost:8980/myapp5/*"), client.getRedirectUris());
            Assert.assertEquals("grant_types", Arrays.asList("authorization_code", "client_credentials", "refresh_token"), client.getGrantTypes());
            Assert.assertEquals("response_types", Arrays.asList("code", "none"), client.getResponseTypes());
            Assert.assertEquals("client_name", "My Client App V", client.getClientName());
            Assert.assertEquals("client_uri", "http://localhost:8980/myapp5", client.getClientUri());
            // try use incompatible endpoint override
            exe = execute("create --config '" + configFile.getName() + "' -e default -f '" + tmpFile.getName() + "'");
            assertExitCodeAndStreamSizes(exe, 1, 0, 1);
            Assert.assertEquals("Error message", "Attribute 'redirect_uris' not supported on document type 'default'", exe.stderrLines().get(0));
        }
        // test create saml formated xml - format autodetection
        File samlSpMetaFile = new File(System.getProperty("user.dir") + "/src/test/resources/cli/kcreg/saml-sp-metadata.xml");
        Assert.assertTrue("saml-sp-metadata.xml exists", samlSpMetaFile.isFile());
        exe = execute("create --insecure --config '" + configFile.getName() + "' -o -f - < '" + samlSpMetaFile.getAbsolutePath() + "'");
        assertExitCodeAndStdErrSize(exe, 0, 2);
        ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        Assert.assertNotNull("id", client.getId());
        Assert.assertEquals("clientId", "http://localhost:8080/sales-post-enc/", client.getClientId());
        Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8081/sales-post-enc/saml"), client.getRedirectUris());
        Assert.assertEquals("attributes.saml_name_id_format", "username", client.getAttributes().get("saml_name_id_format"));
        Assert.assertEquals("attributes.saml_assertion_consumer_url_post", "http://localhost:8081/sales-post-enc/saml", client.getAttributes().get("saml_assertion_consumer_url_post"));
        Assert.assertEquals("attributes.saml.signature.algorithm", "RSA_SHA256", client.getAttributes().get("saml.signature.algorithm"));
        // delete initial token
        exe = execute("config initial-token --config '" + configFile.getName() + "' --insecure --server " + serverUrl + " --realm " + realm + " --delete");
        assertExitCodeAndStreamSizes(exe, 0, 0, 0);
        config = handler.loadConfig();
        Assert.assertNull("initial token == null", config.ensureRealmConfigData(serverUrl, realm).getInitialToken());
    }
}
Also used : FileConfigHandler(org.keycloak.client.registration.cli.config.FileConfigHandler) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ConfigData(org.keycloak.client.registration.cli.config.ConfigData) KcRegExec(org.keycloak.testsuite.cli.KcRegExec) File(java.io.File) TempFileResource(org.keycloak.testsuite.util.TempFileResource) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Test(org.junit.Test)

Example 5 with TempFileResource

use of org.keycloak.testsuite.util.TempFileResource in project keycloak by keycloak.

the class KcRegTruststoreTest method testTruststore.

@Test
public void testTruststore() throws IOException {
    File truststore = new File("src/test/resources/keystore/keycloak.truststore");
    KcRegExec exe = execute("config truststore --no-config '" + truststore.getAbsolutePath() + "'");
    assertExitCodeAndStreamSizes(exe, 1, 0, 2);
    Assert.assertEquals("stderr first line", "Unsupported option: --no-config", exe.stderrLines().get(0));
    Assert.assertEquals("try help", "Try '" + OsUtil.CMD + " help config truststore' for more information", exe.stderrLines().get(1));
    // only run the rest of this test if ssl protected keycloak server is available
    if (!AUTH_SERVER_SSL_REQUIRED) {
        System.out.println("TEST SKIPPED - This test requires HTTPS. Run with '-Pauth-server-wildfly -Dauth.server.ssl.required=true'");
        return;
    }
    FileConfigHandler handler = initCustomConfigFile();
    try (TempFileResource configFile = new TempFileResource(handler.getConfigFile())) {
        if (runIntermittentlyFailingTests()) {
            // configure truststore
            exe = execute("config truststore --config '" + configFile.getName() + "' '" + truststore.getAbsolutePath() + "'");
            assertExitCodeAndStreamSizes(exe, 0, 0, 0);
            // perform authentication against server - asks for password, then for truststore password
            exe = KcRegExec.newBuilder().argsLine("config credentials --server " + oauth.AUTH_SERVER_ROOT + " --realm test --user user1" + " --config '" + configFile.getName() + "'").executeAsync();
            exe.waitForStdout("Enter password: ");
            exe.sendToStdin("userpass" + EOL);
            exe.waitForStdout("Enter truststore password: ");
            exe.sendToStdin("secret" + EOL);
            exe.waitCompletion();
            assertExitCodeAndStreamSizes(exe, 0, 2, 1);
            // configure truststore with password
            exe = execute("config truststore --config '" + configFile.getName() + "' --trustpass secret '" + truststore.getAbsolutePath() + "'");
            assertExitCodeAndStreamSizes(exe, 0, 0, 0);
            // perform authentication against server - asks for password, then for truststore password
            exe = KcRegExec.newBuilder().argsLine("config credentials --server " + oauth.AUTH_SERVER_ROOT + " --realm test --user user1" + " --config '" + configFile.getName() + "'").executeAsync();
            exe.waitForStdout("Enter password: ");
            exe.sendToStdin("userpass" + EOL);
            exe.waitCompletion();
            assertExitCodeAndStreamSizes(exe, 0, 1, 1);
        } else {
            System.out.println("TEST SKIPPED PARTIALLY - This test currently suffers from intermittent failures. Use -Dtest.intermittent=true to run it in full.");
        }
    }
    // configure truststore with password
    exe = execute("config truststore --trustpass secret '" + truststore.getAbsolutePath() + "'");
    assertExitCodeAndStreamSizes(exe, 0, 0, 0);
    // perform authentication against server - asks for password, then for truststore password
    exe = execute("config credentials --server " + serverUrl + " --realm test --user user1 --password userpass");
    assertExitCodeAndStreamSizes(exe, 0, 0, 1);
    exe = execute("config truststore --delete");
    assertExitCodeAndStreamSizes(exe, 0, 0, 0);
    exe = execute("config truststore --delete '" + truststore.getAbsolutePath() + "'");
    assertExitCodeAndStreamSizes(exe, 1, 0, 2);
    Assert.assertEquals("incompatible", "Option --delete is mutually exclusive with specifying a TRUSTSTORE", exe.stderrLines().get(0));
    Assert.assertEquals("try help", "Try '" + CMD + " help config truststore' for more information", exe.stderrLines().get(1));
    exe = execute("config truststore --delete --trustpass secret");
    assertExitCodeAndStreamSizes(exe, 1, 0, 2);
    Assert.assertEquals("no truststore error", "Options --trustpass and --delete are mutually exclusive", exe.stderrLines().get(0));
    Assert.assertEquals("try help", "Try '" + CMD + " help config truststore' for more information", exe.stderrLines().get(1));
    FileConfigHandler cfghandler = new FileConfigHandler();
    cfghandler.setConfigFile(DEFAULT_CONFIG_FILE_PATH);
    ConfigData config = cfghandler.loadConfig();
    Assert.assertNull("truststore null", config.getTruststore());
    Assert.assertNull("trustpass null", config.getTrustpass());
    // perform no-config CRUD test against ssl protected endpoint
    testCRUDWithOnTheFlyAuth(serverUrl, "--user user1 --password userpass", " --truststore '" + truststore.getAbsolutePath() + "' --trustpass secret", "Logging into " + serverUrl + " as user user1 of realm test");
}
Also used : FileConfigHandler(org.keycloak.client.registration.cli.config.FileConfigHandler) ConfigData(org.keycloak.client.registration.cli.config.ConfigData) KcRegExec(org.keycloak.testsuite.cli.KcRegExec) File(java.io.File) TempFileResource(org.keycloak.testsuite.util.TempFileResource) Test(org.junit.Test)

Aggregations

TempFileResource (org.keycloak.testsuite.util.TempFileResource)19 Test (org.junit.Test)17 FileConfigHandler (org.keycloak.client.registration.cli.config.FileConfigHandler)10 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)10 KcRegExec (org.keycloak.testsuite.cli.KcRegExec)10 FileConfigHandler (org.keycloak.client.admin.cli.config.FileConfigHandler)9 KcAdmExec (org.keycloak.testsuite.cli.KcAdmExec)9 File (java.io.File)6 ConfigData (org.keycloak.client.registration.cli.config.ConfigData)6 RealmResource (org.keycloak.admin.client.resource.RealmResource)3 RealmConfigData (org.keycloak.client.registration.cli.config.RealmConfigData)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 Arrays (java.util.Arrays)2 List (java.util.List)2 Assert (org.junit.Assert)2 ConfigData (org.keycloak.client.admin.cli.config.ConfigData)2 OIDCClientRepresentation (org.keycloak.representations.oidc.OIDCClientRepresentation)2 AuthServerContainerExclude (org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude)2 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1