Search in sources :

Example 1 with KcRegExec

use of org.keycloak.testsuite.cli.KcRegExec 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 2 with KcRegExec

use of org.keycloak.testsuite.cli.KcRegExec 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 3 with KcRegExec

use of org.keycloak.testsuite.cli.KcRegExec 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 4 with KcRegExec

use of org.keycloak.testsuite.cli.KcRegExec 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)

Example 5 with KcRegExec

use of org.keycloak.testsuite.cli.KcRegExec in project keycloak by keycloak.

the class KcRegUpdateTest method testUpdateThoroughly.

@Test
public void testUpdateThoroughly() throws IOException {
    FileConfigHandler handler = initCustomConfigFile();
    try (TempFileResource configFile = new TempFileResource(handler.getConfigFile())) {
        final String realm = "test";
        loginAsUser(configFile.getFile(), serverUrl, realm, "user1", "userpass");
        // create an object so we can update it
        KcRegExec exe = execute("create --config '" + configFile.getName() + "' -o -s clientId=my_client");
        assertExitCodeAndStdErrSize(exe, 0, 0);
        ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        Assert.assertEquals("enabled", true, client.isEnabled());
        Assert.assertEquals("publicClient", false, client.isPublicClient());
        Assert.assertEquals("bearerOnly", false, client.isBearerOnly());
        Assert.assertTrue("redirectUris is empty", client.getRedirectUris().isEmpty());
        // Merge update
        exe = execute("update my_client --config '" + configFile.getName() + "' -o " + " -s enabled=false -s 'redirectUris=[\"http://localhost:8980/myapp/*\"]'");
        assertExitCodeAndStdErrSize(exe, 0, 0);
        client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        Assert.assertEquals("enabled", false, client.isEnabled());
        Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris());
        // Another merge update - test deleting an attribute, deleting a list item and adding a list item
        exe = execute("update my_client --config '" + configFile.getName() + "' -o -d redirectUris -s webOrigins+=http://localhost:8980/myapp -s webOrigins+=http://localhost:8981/myapp -d webOrigins[0]");
        assertExitCodeAndStdErrSize(exe, 0, 0);
        client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        Assert.assertTrue("redirectUris is empty", client.getRedirectUris().isEmpty());
        Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8981/myapp"), client.getWebOrigins());
        // Another merge update - test nested attributes and setting an attribute using json format
        // TODO KEYCLOAK-3705 Updating protocolMapper config via client registration endpoint has no effect
        /*
            exe = execute("update my_client --config '" + configFile.getName() + "' -o -s 'protocolMappers[0].config.\"id.token.claim\"=false' " +
                    "-s 'protocolMappers[4].config={\"single\": \"true\", \"attribute.nameformat\": \"Basic\", \"attribute.name\": \"Role\"}'");

            assertExitCodeAndStdErrSize(exe, 0, 0);

            client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
            Assert.assertEquals("protocolMapper[0].config.\"id.token.claim\"", "false", client.getProtocolMappers().get(0).getConfig().get("id.token.claim"));
            Assert.assertEquals("protocolMappers[4].config.single", "true", client.getProtocolMappers().get(4).getConfig().get("single"));
            Assert.assertEquals("protocolMappers[4].config.\"attribute.nameformat\"", "Basic", client.getProtocolMappers().get(4).getConfig().get("attribute.nameformat"));
            Assert.assertEquals("protocolMappers[4].config.\"attribute.name\"", "Role", client.getProtocolMappers().get(4).getConfig().get("attribute.name"));
            */
        // update using oidc format
        // check that using an invalid attribute key is not ignored
        exe = execute("update my_client --nonexisting --config '" + configFile.getName() + "'");
        assertExitCodeAndStreamSizes(exe, 1, 0, 2);
        Assert.assertEquals("error message", "Unsupported option: --nonexisting", exe.stderrLines().get(0));
        Assert.assertEquals("try help", "Try '" + CMD + " help update' for more information", exe.stderrLines().get(1));
        // try use incompatible endpoint
        exe = execute("update my_client --config '" + configFile.getName() + "' -o -s enabled=true -e oidc");
        assertExitCodeAndStreamSizes(exe, 1, 0, 1);
        Assert.assertEquals("error message", "Failed to set attribute 'enabled' on document type 'oidc'", exe.stderrLines().get(0));
        // test overwrite from file
        exe = KcRegExec.newBuilder().argsLine("update my_client --config '" + configFile.getName() + "' -o  -s clientId=my_client -s 'redirectUris=[\"http://localhost:8980/myapp/*\"]' -f -").stdin(new ByteArrayInputStream("{ \"enabled\": false }".getBytes())).execute();
        assertExitCodeAndStdErrSize(exe, 0, 0);
        client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        // web origin is not sent to the server, thus it retains the current value
        Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8981/myapp"), client.getWebOrigins());
        Assert.assertFalse("enabled is false", client.isEnabled());
        Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris());
        // test using merge with file
        exe = KcRegExec.newBuilder().argsLine("update my_client --config '" + configFile.getName() + "' -o -s enabled=true -m -f -").stdin(new ByteArrayInputStream("{ \"webOrigins\": [\"http://localhost:8980/myapp\"] }".getBytes())).execute();
        assertExitCodeAndStdErrSize(exe, 0, 0);
        client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8980/myapp"), client.getWebOrigins());
        Assert.assertTrue("enabled is true", client.isEnabled());
        Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris());
        // remove registration access token
        exe = execute("config registration-token --config '" + configFile.getName() + "' --server " + serverUrl + " --realm " + realm + " --client my_client -d");
        assertExitCodeAndStdErrSize(exe, 0, 0);
        Assert.assertNull("my_client registration token", handler.loadConfig().ensureRealmConfigData(serverUrl, realm).getClients().get("my_client"));
    }
}
Also used : FileConfigHandler(org.keycloak.client.registration.cli.config.FileConfigHandler) ByteArrayInputStream(java.io.ByteArrayInputStream) KcRegExec(org.keycloak.testsuite.cli.KcRegExec) TempFileResource(org.keycloak.testsuite.util.TempFileResource) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Test(org.junit.Test)

Aggregations

KcRegExec (org.keycloak.testsuite.cli.KcRegExec)28 Test (org.junit.Test)24 FileConfigHandler (org.keycloak.client.registration.cli.config.FileConfigHandler)11 TempFileResource (org.keycloak.testsuite.util.TempFileResource)10 File (java.io.File)8 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)8 ConfigData (org.keycloak.client.registration.cli.config.ConfigData)7 AuthServerContainerExclude (org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude)5 RealmConfigData (org.keycloak.client.registration.cli.config.RealmConfigData)4 FileOutputStream (java.io.FileOutputStream)2 OIDCClientRepresentation (org.keycloak.representations.oidc.OIDCClientRepresentation)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 IOException (java.io.IOException)1 Arrays (java.util.Arrays)1 List (java.util.List)1 Matchers (org.hamcrest.Matchers)1 Assert (org.junit.Assert)1 Assume (org.junit.Assume)1 Before (org.junit.Before)1 OAuth2Constants (org.keycloak.OAuth2Constants)1