Merge pull request #3227 from mhajas/KEYCLOAK-3553

KEYCLOAK-3553 Move all functionality tests to servlets
This commit is contained in:
Stian Thorgersen 2016-09-20 08:51:59 +02:00 committed by GitHub
commit 9d0c9046ad
9 changed files with 466 additions and 4 deletions

View file

@ -0,0 +1,61 @@
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.adapter.page;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.keycloak.testsuite.page.AbstractPageWithInjectedUrl;
import javax.ws.rs.core.UriBuilder;
import java.net.URL;
/**
*
* @author tkyjovsk
*/
public class BasicAuth extends AbstractPageWithInjectedUrl {
public static final String DEPLOYMENT_NAME = "basic-auth";
@ArquillianResource
@OperateOnDeployment(DEPLOYMENT_NAME)
private URL url;
@Override
public URL getInjectedUrl() {
//EAP6 URL fix
URL fixedUrl = createInjectedURL("basic-auth");
return fixedUrl != null ? fixedUrl : url;
}
@Override
public UriBuilder createUriBuilder() {
return super.createUriBuilder()
.userInfo("{user}:{password}")
.path("basic-auth")
.queryParam("value", "{value}");
}
public BasicAuth setTemplateValues(String user, String password, String value) {
setUriParameter("user", user);
setUriParameter("password", password);
setUriParameter("value", value);
return this;
}
}

View file

@ -0,0 +1,27 @@
package org.keycloak.testsuite.adapter.servlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author mhajas
*/
@WebServlet("/basic-auth")
public class BasicAuthServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String value = req.getParameter("value");
System.out.println("In BasicAuthServlet with value: " + value);
resp.setContentType("text/plain");
PrintWriter pw = resp.getWriter();
pw.printf(value);
pw.flush();
}
}

View file

@ -17,6 +17,7 @@
package org.keycloak.testsuite.adapter.servlet;
import org.apache.commons.io.FileUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.shrinkwrap.api.spec.WebArchive;
@ -25,6 +26,7 @@ import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.common.Version;
import org.keycloak.common.util.Time;
import org.keycloak.constants.AdapterConstants;
@ -33,15 +35,22 @@ import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.VersionRepresentation;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.testsuite.adapter.AbstractServletsAdapterTest;
import org.keycloak.testsuite.adapter.filter.AdapterActionsFilter;
import org.keycloak.testsuite.adapter.page.*;
import org.keycloak.testsuite.admin.ApiUtil;
import org.keycloak.testsuite.auth.page.account.Applications;
import org.keycloak.testsuite.auth.page.login.OAuthGrant;
import org.keycloak.testsuite.console.page.events.Config;
import org.keycloak.testsuite.console.page.events.LoginEvents;
import org.keycloak.testsuite.util.URLAssert;
import org.keycloak.testsuite.util.URLUtils;
import org.keycloak.testsuite.util.WaitUtils;
import org.keycloak.util.BasicAuthHelper;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
@ -51,16 +60,22 @@ import javax.ws.rs.core.Form;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.*;
import static org.keycloak.testsuite.auth.page.AuthRealm.DEMO;
import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlEquals;
import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWithLoginUrlOf;
import static org.keycloak.testsuite.util.WaitUtils.pause;
import static org.keycloak.testsuite.util.WaitUtils.waitUntilElement;
/**
*
@ -84,6 +99,16 @@ public abstract class AbstractDemoServletsAdapterTest extends AbstractServletsAd
private InputPortal inputPortal;
@Page
private TokenMinTTLPage tokenMinTTLPage;
@Page
private OAuthGrant oAuthGrantPage;
@Page
private Applications applicationsPage;
@Page
private LoginEvents loginEventsPage;
@Page
private BasicAuth basicAuthPage;
@Page
private Config configPage;
@Deployment(name = CustomerPortal.DEPLOYMENT_NAME)
protected static WebArchive customerPortal() {
@ -125,6 +150,20 @@ public abstract class AbstractDemoServletsAdapterTest extends AbstractServletsAd
return servletDeployment(TokenMinTTLPage.DEPLOYMENT_NAME, AdapterActionsFilter.class, AbstractShowTokensServlet.class, TokenMinTTLServlet.class, ErrorServlet.class);
}
@Deployment(name = BasicAuth.DEPLOYMENT_NAME)
protected static WebArchive basicAuth() {
return servletDeployment(BasicAuth.DEPLOYMENT_NAME, BasicAuthServlet.class);
}
@Override
public void setDefaultPageUriParameters() {
super.setDefaultPageUriParameters();
configPage.setConsoleRealm(DEMO);
loginEventsPage.setConsoleRealm(DEMO);
applicationsPage.setAuthRealm(DEMO);
loginEventsPage.setConsoleRealm(DEMO);
}
@Before
public void beforeDemoServletsAdapterTest() {
// Delete all cookies from token-min-ttl page to be sure we are logged out
@ -220,7 +259,7 @@ public abstract class AbstractDemoServletsAdapterTest extends AbstractServletsAd
.queryParam(AdapterActionsFilter.RESET_PUBLIC_KEY_PARAM, "true")
.build().toString();
driver.navigate().to(timeOffsetUri);
WaitUtils.waitUntilElement(By.tagName("body")).is().visible();
waitUntilElement(By.tagName("body")).is().visible();
setAdapterAndServerTimeOffset(0, adapterActionsUrl);
}
@ -320,7 +359,7 @@ public abstract class AbstractDemoServletsAdapterTest extends AbstractServletsAd
demoRealmRep.setSsoSessionIdleTimeout(1);
testRealmResource().update(demoRealmRep);
pause(2000);
pause(2000);
productPortal.navigateTo();
assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
@ -382,6 +421,10 @@ public abstract class AbstractDemoServletsAdapterTest extends AbstractServletsAd
demoRealmRep.setSsoSessionIdleTimeout(originalIdle);
testRealmResource().update(demoRealmRep);
String logoutUri = OIDCLoginProtocolService.logoutUrl(authServerPage.createUriBuilder())
.queryParam(OAuth2Constants.REDIRECT_URI, securePortal.toString()).build("demo").toString();
driver.navigate().to(logoutUri);
}
@Test
@ -547,5 +590,193 @@ public abstract class AbstractDemoServletsAdapterTest extends AbstractServletsAd
setAdapterAndServerTimeOffset(0, tokenMinTTLPage.toString());
}
@Test
public void testBasicAuth() {
String value = "hello";
Client client = ClientBuilder.newClient();
Response response = client.target(basicAuthPage
.setTemplateValues("mposolda", "password", value).buildUri()).request().get();
assertEquals(200, response.getStatus());
assertEquals(value, response.readEntity(String.class));
response.close();
response = client.target(basicAuthPage
.setTemplateValues("invalid-user", "password", value).buildUri()).request().get();
assertEquals(401, response.getStatus());
String readResponse = response.readEntity(String.class);
assertTrue(readResponse.contains("Unauthorized") || readResponse.contains("Status 401"));
response.close();
response = client.target(basicAuthPage
.setTemplateValues("admin", "invalid-password", value).buildUri()).request().get();
assertEquals(401, response.getStatus());
readResponse = response.readEntity(String.class);
assertTrue(readResponse.contains("Unauthorized") || readResponse.contains("Status 401"));
response.close();
client.close();
}
@Test
public void grantServerBasedApp() {
ClientResource clientResource = ApiUtil.findClientResourceByClientId(testRealmResource(), "customer-portal");
ClientRepresentation client = clientResource.toRepresentation();
client.setConsentRequired(true);
clientResource.update(client);
RealmRepresentation realm = testRealmResource().toRepresentation();
realm.setEventsEnabled(true);
realm.setEnabledEventTypes(Arrays.asList("REVOKE_GRANT", "LOGIN"));
testRealmResource().update(realm);
customerPortal.navigateTo();
loginPage.form().login("bburke@redhat.com", "password");
assertTrue(oAuthGrantPage.isCurrent());
oAuthGrantPage.accept();
waitUntilElement(By.xpath("//body")).text().contains("Bill Burke");
waitUntilElement(By.xpath("//body")).text().contains("Stian Thorgersen");
applicationsPage.navigateTo();
applicationsPage.revokeGrantForApplication("customer-portal");
customerPortal.navigateTo();
assertTrue(oAuthGrantPage.isCurrent());
loginEventsPage.navigateTo();
if (!testContext.isAdminLoggedIn()) {
loginPage.form().login(adminUser);
testContext.setAdminLoggedIn(true);
}
loginEventsPage.table().filter();
loginEventsPage.table().filterForm().addEventType("REVOKE_GRANT");
loginEventsPage.table().update();
List<WebElement> resultList = loginEventsPage.table().rows();
assertEquals(1, resultList.size());
resultList.get(0).findElement(By.xpath(".//td[text()='REVOKE_GRANT']"));
resultList.get(0).findElement(By.xpath(".//td[text()='Client']/../td[text()='account']"));
resultList.get(0).findElement(By.xpath(".//td[text()='IP Address']/../td[text()='127.0.0.1' or text()='0:0:0:0:0:0:0:1']"));
resultList.get(0).findElement(By.xpath(".//td[text()='revoked_client']/../td[text()='customer-portal']"));
loginEventsPage.table().reset();
loginEventsPage.table().filterForm().addEventType("LOGIN");
loginEventsPage.table().update();
resultList = loginEventsPage.table().rows();
assertEquals(1, resultList.size());
resultList.get(0).findElement(By.xpath(".//td[text()='LOGIN']"));
resultList.get(0).findElement(By.xpath(".//td[text()='Client']/../td[text()='customer-portal']"));
resultList.get(0).findElement(By.xpath(".//td[text()='IP Address']/../td[text()='127.0.0.1' or text()='0:0:0:0:0:0:0:1']"));
resultList.get(0).findElement(By.xpath(".//td[text()='username']/../td[text()='bburke@redhat.com']"));
resultList.get(0).findElement(By.xpath(".//td[text()='consent']/../td[text()='consent_granted']"));
configPage.navigateTo();
configPage.form().clearLoginEvents();
driver.findElement(By.xpath("//div[@class='modal-dialog']//button[text()='Delete']")).click();
}
@Test
public void historyOfAccessResourceTest() throws IOException {
RealmRepresentation realm = testRealmResource().toRepresentation();
realm.setEventsEnabled(true);
realm.setEnabledEventTypes(Arrays.asList("LOGIN", "LOGIN_ERROR", "LOGOUT", "CODE_TO_TOKEN"));
testRealmResource().update(realm);
customerPortal.navigateTo();
testRealmLoginPage.form().login("bburke@redhat.com", "password");
waitUntilElement(By.xpath("//body")).text().contains("Bill Burke");
waitUntilElement(By.xpath("//body")).text().contains("Stian Thorgersen");
driver.navigate().to(testRealmPage.getOIDCLogoutUrl() + "?redirect_uri=" + customerPortal);
loginEventsPage.navigateTo();
if (!testContext.isAdminLoggedIn()) {
loginPage.form().login(adminUser);
testContext.setAdminLoggedIn(true);
}
loginEventsPage.table().filter();
loginEventsPage.table().filterForm().addEventType("LOGOUT");
loginEventsPage.table().update();
List<WebElement> resultList = loginEventsPage.table().rows();
assertEquals(1, resultList.size());
resultList.get(0).findElement(By.xpath(".//td[text()='LOGOUT']"));
resultList.get(0).findElement(By.xpath(".//td[text()='Client']/../td[text()='']"));
resultList.get(0).findElement(By.xpath(".//td[text()='IP Address']/../td[text()='127.0.0.1' or text()='0:0:0:0:0:0:0:1']"));
loginEventsPage.table().reset();
loginEventsPage.table().filterForm().addEventType("LOGIN");
loginEventsPage.table().update();
resultList = loginEventsPage.table().rows();
assertEquals(1, resultList.size());
resultList.get(0).findElement(By.xpath(".//td[text()='LOGIN']"));
resultList.get(0).findElement(By.xpath(".//td[text()='Client']/../td[text()='customer-portal']"));
resultList.get(0).findElement(By.xpath(".//td[text()='IP Address']/../td[text()='127.0.0.1' or text()='0:0:0:0:0:0:0:1']"));
resultList.get(0).findElement(By.xpath(".//td[text()='username']/../td[text()='bburke@redhat.com']"));
loginEventsPage.table().reset();
loginEventsPage.table().filterForm().addEventType("CODE_TO_TOKEN");
loginEventsPage.table().update();
resultList = loginEventsPage.table().rows();
assertEquals(1, resultList.size());
resultList.get(0).findElement(By.xpath(".//td[text()='CODE_TO_TOKEN']"));
resultList.get(0).findElement(By.xpath(".//td[text()='Client']/../td[text()='customer-portal']"));
resultList.get(0).findElement(By.xpath(".//td[text()='IP Address']/../td[text()='127.0.0.1' or text()='0:0:0:0:0:0:0:1']"));
resultList.get(0).findElement(By.xpath(".//td[text()='refresh_token_type']/../td[text()='Refresh']"));
configPage.navigateTo();
configPage.form().clearLoginEvents();
driver.findElement(By.xpath("//div[@class='modal-dialog']//button[text()='Delete']")).click();
String serverLogPath = null;
if (System.getProperty("app.server").equals("wildfly") || System.getProperty("app.server").equals("eap6") || System.getProperty("app.server").equals("eap")) {
serverLogPath = System.getProperty("app.server.home") + "/standalone/log/server.log";
}
String appServerUrl;
if (Boolean.parseBoolean(System.getProperty("app.server.ssl.required"))) {
appServerUrl = "https://localhost:" + System.getProperty("app.server.https.port", "8543") + "/";
} else {
appServerUrl = "http://localhost:" + System.getProperty("app.server.http.port", "8280") + "/";
}
if (serverLogPath != null) {
log.info("Checking app server log at: " + serverLogPath);
File serverLog = new File(serverLogPath);
String serverLogContent = FileUtils.readFileToString(serverLog);
UserRepresentation bburke = ApiUtil.findUserByUsername(testRealmResource(), "bburke@redhat.com");
Pattern pattern = Pattern.compile("User '" + bburke.getId() + "' invoking '" + appServerUrl + "customer-portal[^\\s]+' on client 'customer-portal'");
Matcher matcher = pattern.matcher(serverLogContent);
assertTrue(matcher.find());
assertTrue(serverLogContent.contains("User '" + bburke.getId() + "' invoking '" + appServerUrl + "customer-db/' on client 'customer-db'"));
} else {
log.info("Checking app server log on app-server: \"" + System.getProperty("app.server") + "\" is not supported.");
}
}
}

View file

@ -0,0 +1,20 @@
<!--
~ Copyright 2016 Red Hat, Inc. and/or its affiliates
~ and other contributors as indicated by the @author tags.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<Context path="/basic-auth">
<Valve className="org.keycloak.adapters.tomcat.KeycloakAuthenticatorValve"/>
</Context>

View file

@ -0,0 +1,46 @@
<?xml version="1.0"?>
<!--
~ Copyright 2016 Red Hat, Inc. and/or its affiliates
~ and other contributors as indicated by the @author tags.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Get name="securityHandler">
<Set name="authenticator">
<New class="org.keycloak.adapters.jetty.KeycloakJettyAuthenticator">
<!--
<Set name="adapterConfig">
<New class="org.keycloak.representations.adapters.config.AdapterConfig">
<Set name="realm">tomcat</Set>
<Set name="resource">customer-portal</Set>
<Set name="authServerUrl">http://localhost:8180/auth</Set>
<Set name="sslRequired">external</Set>
<Set name="credentials">
<Map>
<Entry>
<Item>secret</Item>
<Item>password</Item>
</Entry>
</Map>
</Set>
<Set name="realmKey">MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB</Set>
</New>
</Set>
-->
</New>
</Set>
</Get>
</Configure>

View file

@ -0,0 +1,11 @@
{
"realm" : "demo",
"resource" : "basic-auth-service",
"realm-public-key" : "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB",
"auth-server-url": "/auth",
"ssl-required" : "external",
"enable-basic-auth" : "true",
"credentials": {
"secret": "password"
}
}

View file

@ -0,0 +1,11 @@
{
"realm" : "demo",
"resource" : "basic-auth-service",
"realm-public-key" : "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB",
"auth-server-url": "/auth",
"ssl-required" : "external",
"enable-basic-auth" : "true",
"credentials": {
"secret": "password"
}
}

View file

@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2016 Red Hat, Inc. and/or its affiliates
~ and other contributors as indicated by the @author tags.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<module-name>basic-auth</module-name>
<security-constraint>
<web-resource-collection>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<!-- <user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint> -->
<auth-constraint>
<role-name>user</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>KEYCLOAK</auth-method>
<realm-name>demo</realm-name>
</login-config>
<security-role>
<role-name>user</role-name>
</security-role>
</web-app>

View file

@ -226,6 +226,15 @@
"/oauth-client-cdi/*"
],
"secret": "password"
},
{
"clientId": "basic-auth-service",
"standardFlowEnabled": false,
"directAccessGrantsEnabled": true,
"enabled": true,
"adminUrl": "/basic-auth",
"baseUrl": "/basic-auth",
"secret": "password"
}
]
}